PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust
Merge origin/main into fix/page-cursor-writer
alehel871a3e1e96fc
diff --cc CLAUDE.mdindex 944479805,a37cec4ca..cd1b5b284--- a/CLAUDE.md+++ b/CLAUDE.md@@@ -22,7 -22,6 +22,7 @@@ PdfCraft is a clean-room, open-source,- **Privacy.** When observing Acrobat, use synthetic fixtures only. Never capture the Home view, recent files or account info. Capture by window id (`plan/acrobat/tools/`). Never commit Acrobat outputs, corpus files or personal data.- **Layering.** Nothing below L7 depends on egui/winit/eframe/rfd (`plan/architecture.md` §3). `cos`/`filters`/`crypt`/`arlington` stay standalone.- **Page input.** Page modules read `PagePointer` (`crates/ui-egui/src/page_pointer.rs`), never egui's raw pointer state (`hover_pos`, `interact_pos`, `latest_pos`, `press_origin`, button reads); `page_pointer::tests::page_modules_read_the_pointer_only_through_page_pointer` enforces it.- - **Page cursor.** Page modules claim the cursor for what is under the pointer (`view.cursor.claim(Layer::…, icon)`, `crates/ui-egui/src/page_cursor.rs`), never set it (`set_cursor_icon`, `cursor_icon =`, `on_hover_cursor`); `document_area` sets it once, from the claim on the highest layer the active tool reaches. `page_pointer::tests::page_modules_claim_the_cursor_and_never_set_it` enforces it.++- **Page cursor.** Page modules claim the cursor for what is under the pointer (`view.cursor.claim(Layer::…, icon)`, `crates/ui-egui/src/canvas/page_cursor.rs`), never set it (`set_cursor_icon`, `cursor_icon =`, `on_hover_cursor`); `document_area` sets it once, from the claim on the highest layer the active tool reaches. `page_pointer::tests::page_modules_claim_the_cursor_and_never_set_it` enforces it.- **Fidelity.** The PDF object graph is the model. Preserve unknown data. Saves are incremental unless a full rewrite is required. Never silently drop or repair data without recording it.- **Never panic.** Every PDF, script, MCP call, settings file and keystroke is untrusted input, and none of it may crash the app or lose the user's work. This outranks feature work. Return `Result` (the crate's error enum) and propagate with `?`, or fall back leniently and record it. In non-test code:- No `unwrap`/`expect`/`panic!`/`unreachable!`/`todo!` unless it is provably infallible, with a comment saying why.diff --cc crates/ui-egui/src/canvas.rsindex 1b9dce828,ea37eb0df..91d2c4136--- a/crates/ui-egui/src/canvas.rs+++ b/crates/ui-egui/src/canvas.rs@@@ -17,6 -16,57 +17,57 @@@ use crate::page_pointer::PagePointeruse crate::theme::{self, Tokens};use crate::{PdfCraftApp, QuickTool, RightPanel, comments, icons, widgets};+ mod area;+ pub(super) mod autoscroll;+ mod bars;+ mod cache;+ pub(super) mod crop;+ mod find;+ pub(super) mod fling;+ pub(super) mod image_pick;+ mod navigation;+ mod organize;++pub(super) mod page_cursor;+ pub(super) mod page_pointer;+ pub mod scroll_speed;+ mod selection;+ pub(super) mod signature_drag;+ pub(super) mod wheel_boost;+ pub(super) mod wheel_pager;+ mod xform;+ mod zoom;+ pub(super) mod zoom_snap;++ pub(crate) use area::signature_badges;+ use area::{- SUPPRESS_SECS, SUPPRESS_TAIL_SECS, annotation_hover_text, drawing_edge_pointer, glide_interrupted, page_scroll, presentation_click, run_button,- set_layers, zoom_anchor,++ SUPPRESS_SECS, SUPPRESS_TAIL_SECS, drawing_edge_pointer, glide_interrupted, page_scroll, presentation_click, run_button, set_layers, zoom_anchor,+ };+ #[cfg(test)]+ use bars::in_size_hint_zone;+ use bars::{Notice, notices, page_size_hint, quick_bar};+ pub use cache::RasterMemory;+ pub(crate) use cache::{BASE_SIDE, TILE_THRESHOLD, texture_image, thumbnail_rows};+ #[cfg(test)]+ use cache::{+ GRAYSCALE_TAG, GRID_TAG, MAX_CACHED_TEXT_PAGES, MAX_THUMB_DEMAND, PAGE_BYTES, THUMB_BYTES, THUMB_H, THUMB_TAG, THUMB_W, TILE, grayscale,+ rgba_bytes,+ };+ use cache::{OLD_TILES, PageTex, STALE_TAG, TEXT_TAG, TILE_BYTES, scale_tag, tag_scale, texture_bytes, tile_side};+ pub use find::Find;+ use find::find_bar;+ pub use navigation::shortcuts;+ pub(crate) use organize::drop_gap;+ #[cfg(test)]+ pub(crate) use organize::grid_page_rect;+ use organize::organize_grid;+ #[cfg(test)]+ use organize::sharp_enough;+ use selection::{Selection, Span, click_unit, selection_actions};+ pub use xform::PageXform;+ use xform::snap_to_pixels;+ use zoom::anchored_scroll;+ pub use zoom::{GRID_ZOOM_RANGE, THUMBNAIL_ZOOM_RANGE};+/// Logical pixels per PDF point at 100% (96 dpi, like browsers).pub const PT: f32 = 96.0 / 72.0;const GAP: f32 = 14.0;@@@ -1045,6919 -799,2540 +803,2500 @@@ impl DocViewself.page_count}- pub fn select_pages(&mut self, pages: &[usize]) {- self.selected = pages.iter().copied().filter(|p| *p < self.page_count).collect();- if let Some(first) = self.selected.first() {- self.current = *first;- }+ /// Drops wheel state after a discontinuous jump so the destination cannot+ /// inherit momentum from the previous viewport.+ fn reset_coarse_state(&mut self) {+ self.wheel.clear_motion();+ self.wheel_boost_x.reset();+ self.wheel_boost_y.reset();}+ }- /// A click on page `i`'s thumbnail, in the organize grid or the Pages panel. ⇧ selects the- /// range from the anchor (or the current page); ⌘/Ctrl toggles the page; a plain click- /// selects only it. `seed_current` is for the Pages panel, where an empty selection means- /// the current page: the first ⌘-click on another page keeps the current one selected too.- pub fn click_page(&mut self, i: usize, modifiers: egui::Modifiers, seed_current: bool) {- if i >= self.page_count {- return;- }- if modifiers.shift {- let a = self.select_anchor.unwrap_or(self.current);- self.selected = (a.min(i)..=a.max(i)).collect();- } else if modifiers.command {- if seed_current && self.selected.is_empty() && i != self.current {- self.selected.insert(self.current);- }- if !self.selected.remove(&i) {- self.selected.insert(i);- }- self.select_anchor = Some(i);- } else {- self.selected = [i].into();- self.select_anchor = Some(i);- }- }+ /// The renders a frame wants (page, scale, tag, tile), and the pages visible.+ type PageRenders = (Vec<(usize, f32, u64, Option<Tile>)>, Vec<usize>);- /// Drop the page selection; a later ⇧-click ranges from `anchor`.- pub fn clear_page_selection(&mut self, anchor: Option<usize>) {- self.selected.clear();- self.select_anchor = anchor.filter(|a| *a < self.page_count);- }+ /// What the page-scroll closure reads: this frame's zoom, scrolling, tool and document state.+ #[derive(Clone, Copy)]+ struct PageEnv<'a> {+ added: &'a Vec<pdfcraft_engine::Added>,+ allowed: bool,+ author: &'a String,+ auto_delta: Vec2,+ avail: Rect,+ boost_extra: Vec2,+ by_line: &'a String,+ calc_order: bool,+ can_copy: bool,+ can_crop: bool,+ can_fill: bool,+ can_modify: bool,+ comments_hidden: bool,+ content_h: f32,+ content_w: f32,+ custom_stamp: &'a Option<crate::stamps_ui::CustomStamp>,+ date_text: &'a Result<String, String>,+ doc: &'a pdfcraft_engine::Document,+ doc_links: &'a Vec<pdfcraft_engine::LinkItem>,+ edge_delta: Vec2,+ editing_content: bool,+ form: &'a Arc<Vec<pdfcraft_engine::FormField>>,+ generation: u64,+ glide: Vec2,+ hand: bool,+ info: &'a DocInfo,+ initials: &'a Option<crate::fill_sign::SavedSig>,+ key_scroll: f32,+ middle_gesture: bool,+ modal: bool,+ navigation_enabled: bool,+ paper: Color32,+ ppp: f32,+ precise_scroll: Vec2,+ prefs: &'a comments::CommentPrefs,+ preparing: bool,+ rects: &'a Vec<Rect>,+ redact_mark: ([f64; 3], f64),+ scale: f32,+ selection_wheel: bool,+ selects_text: bool,+ signature: &'a Option<crate::fill_sign::SavedSig>,+ single_paging: bool,+ t: &'a Tokens,+ table_preview: &'a Option<crate::field_table_ui::Preview>,+ tag: u64,+ text_style: &'a pdfcraft_engine::AddedText,+ tool: QuickTool,+ units: crate::units::Unit,+ unobstructed: bool,+ visible_pages: &'a Vec<usize>,+ y_shift: f32,+ fill_text_size: f64,+ today: (i64, u32, u32),+ }- pub fn render_pending(&self) -> bool {- !self.last_queue.is_empty() || self.text_background.pending() || self.move_background.pending()+ /// What the page-scroll closure produces for the rest of the frame.+ #[derive(Default)]+ struct PageOut {- badge_hover: Option<(Pos2, String)>,+ canvas_action: Option<comments::CanvasAction>,+ clicked_link: Option<LinkTarget>,+ copy_selected: bool,+ field_menu: Option<FieldMenu>,+ field_placed: bool,+ field_props: bool,+ hover_text: Option<(Pos2, String)>,+ image_action: Option<crate::edit_text_ui::ImageAction>,+ open_boxes: bool,+ open_initials: bool,+ open_signature: bool,+ open_table: Option<(usize, [f64; 4])>,+ primary_down: bool,+ refused: Option<String>,+ stamp_placed: bool,+ }++ /// The page-scroll closure's body: lays out and draws the visible pages, their tools and overlays, and+ /// returns the renders wanted and the pages visible.+ /// The state of one pass over the visible pages: what is read, and what the pages add up to.+ struct PageFrame<'a> {+ env: PageEnv<'a>,+ resp: &'a egui::Response,+ ptr: &'a PagePointer,+ origin: Pos2,+ visible: Rect,+ pressed: bool,+ pointer: Option<Pos2>,+ signature_preview: &'a mut Option<(crate::fill_sign::SavedSig, egui::TextureHandle)>,+ out: PageOut,+ wanted: Vec<(usize, f32, u64, Option<Tile>)>,+ visible_now: Vec<usize>,+ current: usize,+ best_overlap: f32,+ current_overlap: f32,+ current_height: f32,+ pressed_page: Option<usize>,+ calc_hover: Option<String>,+ }++ /// Visible heights (points) closer than this are equal: one page size can meet the viewport a+ /// fraction of a point differently once the scroll offset is applied.+ const PAGE_TIE: f32 = 0.5;++ /// Draws page `i` of the visible pages: its raster, the tools' input and overlays.+ /// One visible page: its index, its rectangle on screen and the transform to and from the page.+ #[derive(Clone, Copy)]+ struct PageSlot {+ i: usize,+ r: Rect,+ xf: PageXform,+ }++ /// Paints the page's paper, shadow and raster (or why it can't be shown), and asks for the renders+ /// it wants.+ fn paint_page_surface(ui: &mut egui::Ui, view: &mut DocView, frame: &mut PageFrame<'_>, slot: &PageSlot) {+ let PageEnv { paper, ppp, scale, t, tag, .. } = frame.env;+ let PageSlot { i, r, xf } = *slot;+ let visible = frame.visible;+ let info = frame.env.info;+ let painter = ui.painter();+ // Shadows would darken the preceding page when pages touch.+ if view.show_page_gaps {+ painter.add(egui::epaint::Shadow { offset: [0, 3], blur: 14, spread: 0, color: t.page_shadow }.as_shape(r, CornerRadius::ZERO));+ }+ painter.rect_filled(r, CornerRadius::ZERO, paper);+ if let Some(err) = view.errors.get(&i) {+ painter.rect_filled(r, CornerRadius::ZERO, Color32::from_rgb(0xFB, 0xF4, 0xF4));+ icons::paint(+ ui,+ Rect::from_center_size(r.center() - vec2(0.0, 26.0), vec2(28.0, 28.0)),+ "triangle-alert",+ 26.0,+ Color32::from_rgb(0xC8, 0x3A, 0x3A),+ );+ let message = crate::i18n::fmt(tl!("This page couldn't be displayed.\n{e}"), &[("e", err)]);+ let msg = ui.fonts_mut(|f| f.layout(message, theme::regular(12.5), Color32::from_rgb(0x6A, 0x2A, 0x2A), (r.width() - 40.0).max(80.0)));+ painter.galley(pos2(r.center().x - msg.size().x / 2.0, r.center().y), msg, Color32::BLACK);+ } else {+ let (pw_pt, ph_pt) = (info.pages[i].width.max(1.0), info.pages[i].height.max(1.0));+ // A GPU may take smaller textures than these (OpenGL drivers report as little as+ // 2048 pixels, and uploading a bigger one aborts), so both stay within its limit.+ let max_side = ui.ctx().input(|inp| inp.max_texture_side) as f32;+ let tiled = pw_pt.max(ph_pt) * scale > TILE_THRESHOLD.min(max_side);+ // Whole-page raster: sharp when small, a low-res backdrop when tiled.+ let (want_scale, want_tag) = if tiled {+ let bs = BASE_SIDE.min(max_side) / pw_pt.max(ph_pt);+ (bs, scale_tag(bs))+ } else {+ (scale, tag)+ };+ // Under tiles, a whole-page raster sharper than the backdrop (from before the page+ // grew past the tiling size) is a better backdrop: keep demanding it as it is.+ match view.pages.get(&i).filter(|p| tiled && p.tag != STALE_TAG && tag_scale(p.tag) >= want_scale) {+ Some(p) => frame.wanted.push((i, tag_scale(p.tag), p.tag, None)),+ None => frame.wanted.push((i, want_scale, want_tag, None)),+ }+ match view.pages.get(&i) {+ Some(p) => {+ if !tiled && p.tag == want_tag {+ xf.texel_aligned(p.tex.size(), ppp).paint_image(painter, p.tex.id(), 0.0, 0.0, 1.0, 1.0);+ } else {+ // A backdrop, or a raster at an older scale until the new one arrives.+ xf.paint_image(painter, p.tex.id(), 0.0, 0.0, 1.0, 1.0);+ }+ }+ None => {+ let now = ui.input(|inp| inp.time);+ let since = *view.waiting_since.entry(i).or_insert(now);+ let msg = if now - since > 6.0 { "Still rendering — this page is unusually complex…" } else { "Rendering…" };+ painter.text(r.center(), Align2::CENTER_CENTER, tl!(msg), theme::regular(12.0), t.text_faint);+ }+ }+ if tiled && r.intersects(visible) {+ paint_page_tiles(ui, view, frame, slot, (pw_pt, ph_pt, max_side));+ }+ }+ }++ /// Paints the tiles of a page too big to draw whole: the tiles of earlier zooms first, stretched,+ /// then the visible tiles of this one, nearest the viewport centre first, asking for those missing.+ fn paint_page_tiles(ui: &egui::Ui, view: &mut DocView, frame: &mut PageFrame<'_>, slot: &PageSlot, (pw_pt, ph_pt, max_side): (f32, f32, f32)) {+ let PageEnv { ppp, scale, tag, .. } = frame.env;+ let PageSlot { i, r, xf } = *slot;+ let visible = frame.visible;+ let painter = ui.painter();+ // Device-pixel geometry of the scaled page, and the visible part of it+ // (found by mapping the visible screen corners back into the page). Sides round+ // up as whole-page rasters do, so the last partial row and column get tiles.+ let (dw, dh) = (device_pixels(pw_pt, scale), device_pixels(ph_pt, scale));+ // Adaptive tile side for this zoom and page, within the GPU texture limit:+ // a zoomed viewport or a giant sheet is covered by a few large tiles+ // instead of many small ones, and each tile costs one full page interpret.+ // Never zero (u32 division below).+ let ts = tile_side(scale, dw.max(dh)).min(max_side as u32).max(64);+ let vis = r.intersect(visible);+ let corners = [vis.left_top(), vis.right_top(), vis.right_bottom(), vis.left_bottom()].map(|c| xf.screen_to_norm(c));+ let (u0, u1) = corners.iter().fold((1.0f32, 0.0f32), |(a, b), c| (a.min(c.0), b.max(c.0)));+ let (v0, v1) = corners.iter().fold((1.0f32, 0.0f32), |(a, b), c| (a.min(c.1), b.max(c.1)));+ let (vx0, vy0) = ((u0.max(0.0) * dw as f32) as u32, (v0.max(0.0) * dh as f32) as u32);+ let (vx1, vy1) = (((u1.min(1.0) * dw as f32).ceil() as u32).min(dw), ((v1.min(1.0) * dh as f32).ceil() as u32).min(dh));+ // Tiles of earlier zooms first, stretched, the nearest scale last (on top):+ // until the current tiles arrive, a zoom shows them rather than the backdrop.+ let mut older: Vec<(f32, u32, u32, &TextureHandle)> =+ view.tiles.iter().filter(|((p, t, _, _), _)| *p == i && *t != tag).map(|((_, t, ox, oy), tex)| (tag_scale(*t), *ox, *oy, tex)).collect();+ older.sort_by(|a, b| (b.0 / scale).ln().abs().total_cmp(&(a.0 / scale).ln().abs()));+ for (s, ox, oy, tex) in older {+ let (ow, oh) = (device_pixels(pw_pt, s) as f32, device_pixels(ph_pt, s) as f32);+ let [w, h] = tex.size();+ let (x, y) = (ox as f32, oy as f32);+ xf.paint_image(painter, tex.id(), x / ow, y / oh, (x + w as f32) / ow, (y + h as f32) / oh);+ }+ // Visible tiles, nearest the viewport centre first: each tile costs a full+ // page interpret, so the workers sharpen what is looked at before the edges.+ let (vcx, vcy) = ((vx0 + vx1) as f32 / 2.0, (vy0 + vy1) as f32 / 2.0);+ let mut coords: Vec<(u32, u32)> = Vec::new();+ for ty in vy0 / ts..=(vy1.saturating_sub(1)) / ts {+ for tx in vx0 / ts..=(vx1.saturating_sub(1)) / ts {+ coords.push((tx, ty));+ }+ }+ coords.sort_by(|a, b| {+ let da = ((a.0 * ts + ts / 2) as f32 - vcx).abs() + ((a.1 * ts + ts / 2) as f32 - vcy).abs();+ let db = ((b.0 * ts + ts / 2) as f32 - vcx).abs() + ((b.1 * ts + ts / 2) as f32 - vcy).abs();+ da.total_cmp(&db)+ });+ for (tx, ty) in coords {+ let (x, y) = (tx * ts, ty * ts);+ let (w, h) = (ts.min(dw.saturating_sub(x)), ts.min(dh.saturating_sub(y)));+ if w == 0 || h == 0 {+ continue;+ }+ frame.wanted.push((i, scale, tag, Some(Tile { x, y, w, h })));+ if let Some(tex) = view.tiles.get(&(i, tag, x, y)) {+ let (fw, fh) = (dw as f32, dh as f32);+ xf.texel_aligned([dw as usize, dh as usize], ppp).paint_image(+ painter,+ tex.id(),+ x as f32 / fw,+ y as f32 / fh,+ (x + w) as f32 / fw,+ (y + h) as f32 / fh,+ );+ }}+ }- /// The cached tile keys of a page, as (scale tag, tile x, tile y) (diagnostics and tests).- pub fn tiles_debug(&self, page: usize) -> Vec<(u64, u32, u32)> {- let mut k: Vec<(u64, u32, u32)> = self.tiles.keys().filter(|key| key.0 == page).map(|key| (key.1, key.2, key.3)).collect();- k.sort_unstable();- k- }+ /// What the page's tools did with the pointer this frame.+ struct PageInput {+ /// A tool, a field or a comment took the pointer: text selection must leave it alone.+ consumed: bool,- /// A form field is under the pointer and has set its cursor.- over_field: bool,+ /// Redact or Highlight draws boxes off text.+ area_tool: bool,+ }- /// Re-render every page and text layer (the document's appearance changed, e.g. a layer- /// was toggled). Out-of-date rasters stay on screen until their replacements arrive, so the- /// view never flashes blank.- pub fn invalidate_content(&mut self) {- // Undo, redo and other document-wide changes: a released drawing's preview would be a ghost.- self.comments.settling.clear();- for p in self.pages.values_mut() {- p.tag = STALE_TAG;- }- self.stale_thumbs.extend(self.thumbs.keys().copied());- for slot in self.print_pages.values_mut() {- slot.0 = STALE_TAG;- }- // Pages may have moved: a sharp render of another page would be worse than a soft one.- self.grid_pages.clear();- self.tiles.clear();- self.stale_tiles.clear();- self.forms.unbaked.clear();- self.texts.clear();- self.text_failed.clear();- self.errors.clear();- self.slow_pages.clear();- self.waiting_since.clear();- self.last_queue.clear();- self.selection = 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- // took over stays in control. `document_changed` clamps `current`; if the view no longer- // sits where the automatic choice left it, `follow_page` ends it.- if let Some(f) = self.find.as_mut() {- f.matches.clear();- f.current = None;+ /// Common geometry and pointer state for a tool acting on one page.+ #[derive(Clone, Copy)]+ pub(crate) struct PageToolContext<'a> {+ pub ui: &'a egui::Ui,+ pub resp: &'a egui::Response,+ pub xf: &'a PageXform,+ pub ptr: &'a PagePointer,+ pub page: usize,+ pub doc: &'a pdfcraft_engine::Document,+ pub info: &'a DocInfo,+ }++ /// Comments: tools, selection, moving and resizing come before text selection. Form fields take+ /// clicks first with the Select tool (as Acrobat fills fields in every viewing mode); then+ /// comments; then text selection.+ fn page_tool_input(ui: &mut egui::Ui, view: &mut DocView, frame: &mut PageFrame<'_>, slot: &PageSlot) -> PageInput {+ let PageEnv {+ added,+ allowed,+ author,+ by_line,+ can_crop,+ can_fill,+ can_modify,+ comments_hidden,+ custom_stamp,+ date_text,+ doc,+ doc_links,+ editing_content,+ form,+ info,+ initials,+ prefs,+ preparing,+ redact_mark,+ signature,+ table_preview,+ text_style,+ tool,+ units,+ fill_text_size,+ ..+ } = frame.env;+ let PageSlot { i, xf, .. } = *slot;+ let PageFrame { resp, ptr, pointer, .. } = *frame;+ let cx = PageToolContext { ui, resp, xf: &xf, ptr, page: i, doc, info };+ let pcx = comments::PageCx { page: i, xf: &xf, ptr, info, tool, prefs, allowed, hidden: comments_hidden, redact_mark };+ if let QuickTool::Measure(measure_tool) = tool {+ crate::measure_ui::page_input(ui, resp, doc, view, &pcx, measure_tool, units);+ }++ // Form fields take clicks first with the Select tool (as Acrobat fills fields in+ // every viewing mode); then comments; then text selection.+ if let QuickTool::Stamp(kind) = tool+ && allowed+ && let Some(p) = ptr.within(xf.rect)+ {- ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair);++ view.cursor.claim(Layer::ToolArea, egui::CursorIcon::Crosshair);+ if resp.clicked() {+ // Centred on the click, upright as the page is shown.+ let (vx, vy) = xf.screen_to_view(p);+ let (w, h) = kind.size();+ let corners = [(vx as f64 - w / 2.0, vy as f64 - h / 2.0), (vx as f64 + w / 2.0, vy as f64 + h / 2.0)];+ let u: Vec<[f32; 2]> = corners.iter().map(|(x, y)| info.pages[i].view_to_user(*x as f32, *y as f32)).collect();+ let rect = [u[0][0].min(u[1][0]) as f64, u[0][1].min(u[1][1]) as f64, u[0][0].max(u[1][0]) as f64, u[0][1].max(u[1][1]) as f64];+ let by = (kind.group() == pdfcraft_engine::StampGroup::Dynamic).then(|| by_line.clone());+ let shape = pdfcraft_engine::Shape::Stamp { rect, stamp: kind, by };+ view.pending_edit = Some(pdfcraft_engine::Edit::AddAnnotation(pdfcraft_engine::NewAnnotation {+ page: i,+ style: pdfcraft_engine::Style::default_for(&shape),+ shape,+ contents: String::new(),+ author: author.clone(),+ }));+ frame.out.stamp_placed = true;}}-- /// Only `page` changed (a comment was added, edited or removed): re-render that page and- /// re-read its text, keep everything else. Out-of-date tiles stay on screen until replacements arrive.- pub fn page_changed(&mut self, page: usize) {- if let Some(p) = self.pages.get_mut(&page) {- p.tag = STALE_TAG;- }- if self.thumbs.contains_key(&page) {- self.stale_thumbs.insert(page);+ if let Some(cs) = custom_stamp.as_ref()+ && allowed+ && let Some(p) = ptr.within(xf.rect)+ {- ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair);++ view.cursor.claim(Layer::ToolArea, egui::CursorIcon::Crosshair);+ if resp.clicked() {+ // Centred on the click at its natural size (the engine sizes it).+ let (vx, vy) = xf.screen_to_view(p);+ let u = info.pages[i].view_to_user(vx, vy);+ let (x, y) = (u[0] as f64, u[1] as f64);+ view.pending_edit = Some(pdfcraft_engine::Edit::AddCustomStamp {+ page: i,+ rect: [x, y, x, y],+ name: cs.name.clone(),+ file: pdfcraft_engine::MarkFile { name: cs.file.clone(), bytes: cs.data.clone(), page: cs.page },+ author: author.clone(),+ });+ frame.out.stamp_placed = true;}- if let Some(slot) = self.print_pages.get_mut(&page) {- slot.0 = STALE_TAG;+ }+ // Over a mark already placed, the Fill & Sign tool picks it up (comments, below).+ if let QuickTool::Fill(ft) = tool+ && allowed+ && !comments::fill_grabs(&pcx, view)+ {+ match crate::fill_sign::page_input(+ cx,+ crate::fill_sign::PageInput {+ tool: ft,+ text_size: fill_text_size,+ signature: signature.as_ref(),+ initials: initials.as_ref(),+ preview: frame.signature_preview,+ author,+ date_text,+ },+ view,+ ) {+ Some(crate::fill_sign::FillAction::Edit(e)) => view.pending_edit = Some(*e),+ Some(crate::fill_sign::FillAction::Signature(e)) => {+ view.pending_edit = Some(*e);+ view.fill_signature_page = Some(i);+ }+ Some(crate::fill_sign::FillAction::CreateSignature) => frame.out.open_signature = true,+ Some(crate::fill_sign::FillAction::CreateInitials) => frame.out.open_initials = true,+ Some(crate::fill_sign::FillAction::Refused(why)) => frame.out.refused = Some(why),+ None => {}}- let current_tag = if self.current_scale_tag != 0 {- self.current_scale_tag- } else {- self.tiles.keys().filter(|k| k.0 == page).map(|k| k.1).max().unwrap_or(0)+ }+ if matches!(tool, QuickTool::SignArea { .. }) {+ crate::sign_ui::page_input(ui, resp, &xf, ptr, i, info, view);+ }+ if matches!(tool, QuickTool::MarqueeZoom | QuickTool::Snapshot) {+ crate::zoom_snap::page_input(ui, resp, &xf, ptr, i, view);+ }+ if tool == QuickTool::EnhanceCamera {- crate::camera_ui::page_input(ui, resp, &xf, ptr, i, view, can_modify);++ crate::camera_ui::page_input(resp, &xf, ptr, i, view, can_modify);+ }+ if tool == QuickTool::Crop+ && crate::crop::page_input(ui, crate::crop::CropPageInput { resp, xf: &xf, ptr, page: i, info, view, allowed: can_crop })+ {+ view.current = i;+ frame.out.open_boxes = true;+ }- // `over_field`: a form field is under the pointer and has set its cursor.- let (on_field, over_field) = if preparing {++ let on_field = if preparing {+ let field_tool = match tool {+ QuickTool::Field(f) => Some(f),+ _ => None,+ };+ // While a table is being set up, nothing else is drawn or moved.+ let allowed = can_modify && table_preview.is_none() && frame.out.open_table.is_none();+ let o = crate::prepare::page_input(cx, form, field_tool, allowed, view);+ frame.out.field_props |= o.properties;+ frame.out.field_placed |= o.placed;+ frame.out.open_table = frame.out.open_table.or(o.table);- (o.consumed || field_tool.is_some(), false)++ o.consumed || field_tool.is_some()+ } else {- use crate::forms_ui::FieldPointer;- let field = if tool == QuickTool::Select++ tool == QuickTool::Select+ && !(editing_content && can_modify && crate::content_ui::select_grabs(&xf, ptr, i, info, added, view))+ && !comments::select_grabs(&pcx, view)- {- crate::forms_ui::page_input(cx, form, can_fill, view)- } else {- FieldPointer::Away- };- (field == FieldPointer::Owned, field == FieldPointer::Over)++ && crate::forms_ui::page_input(cx, form, can_fill, view)+ };+ // Redact draws boxes off text; so does Highlight (an area highlight, as in Acrobat).+ let area_tool = tool == QuickTool::Redact && can_modify || tool == QuickTool::Comment(comments::CommentTool::Highlight) && allowed;+ let boxing = area_tool && {+ let text = view.page_text(i);+ let over_text = |p: Pos2| {+ let (vx, vy) = xf.screen_to_view(p);+ text.as_ref().is_some_and(|t| t.glyphs.iter().any(|g| vx >= g.rect[0] && vx <= g.rect[2] && vy >= g.rect[1] && vy <= g.rect[3]))};- self.tiles.retain(|key, _| key.0 != page || key.1 == current_tag);- self.stale_tiles.retain(|key| key.0 != page || key.1 == current_tag);- for &key in self.tiles.keys() {- if key.0 == page && key.1 == current_tag {- self.stale_tiles.insert(key);+ crate::redact_ui::page_input(cx, over_text, view)+ };+ let image_owns_pointer = tool == QuickTool::EditText && crate::edit_text_ui::image_owns_pointer(ui, &xf, ptr, i, info, view);+ let on_objects = !image_owns_pointer && tool == QuickTool::EditText && can_modify && crate::object_ui::page_input(cx, view);+ let lines = if matches!(tool, QuickTool::AddText | QuickTool::EditText) && can_modify {+ let generation = doc.edit_generation();+ match view.edit_lines.get(&i) {+ Some((g, l)) if *g == generation => l.clone(),+ _ => {+ let l = doc.text_blocks(i);+ view.edit_lines.insert(i, (generation, l.clone()));+ l}}- self.slow_pages.remove(&page);- self.texts.remove(&page);- self.text_failed.remove(&page);- self.errors.remove(&page);- self.last_queue.clear();- if self.selection.is_some_and(|s| s.page == page) {- self.selection = None;+ } else {+ Vec::new()+ };+ let over_source = tool == QuickTool::AddText+ && pointer.is_some_and(|p| {+ !crate::content_ui::hits_added(&xf, info, i, added, p)+ && lines.iter().any(|line| xf.user_rect(info, i, line.rect.map(|v| v as f32)).expand(2.0).contains(p))+ });+ let source_blocked = over_source && view.content.hold_blocked();+ if over_source && resp.clicked() && !source_blocked {+ if let Some(edit) = view.content.finish_draft(added) {+ view.pending_edit = Some(edit);}+ view.content.selected = None;}-- /// Pages drawn last frame and their screen rectangles.- pub fn visible_page_rects(&self) -> Vec<(usize, Rect)> {- self.screen_xforms.iter().map(|(p, xf)| (*p, xf.rect)).collect()- }-- /// Where `page` is drawn this frame, with its coordinate mapping.- pub(crate) fn page_xform(&self, page: usize) -> Option<PageXform> {- self.screen_xforms.iter().find(|(p, _)| *p == page).map(|(_, xf)| *xf)- }-- /// 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))+ let on_content = !on_objects && editing_content && can_modify && {+ source_blocked+ || crate::content_ui::page_input(+ cx,+ added,+ tool == QuickTool::AddText && !over_source,+ matches!(tool, QuickTool::AddText | QuickTool::EditText),+ text_style,+ view,+ )+ || tool == QuickTool::AddText && !over_source+ };+ // Added content owns its gesture; its source text must not queue a second edit.+ // Edit text & images boxes every paragraph and image whenever the tool is on. Only the+ // input waits while selected objects or added content own the pointer, or while page+ // input is blocked (another tab, a dialog, the window unfocused): the boxes stay drawn+ // instead of vanishing until the pointer comes back.+ let others_own_pointer = on_objects || on_content;+ let on_edit_text = (tool == QuickTool::EditText || over_source) && can_modify && {+ let generation = doc.edit_generation();+ let images = match view.edit_images.get(&i) {+ Some((g, l)) if *g == generation => l.clone(),+ _ => {+ let l = doc.page_images(i);+ view.edit_images.insert(i, (generation, l.clone()));+ l+ }+ };+ // Editable text takes precedence over background/overlapping artwork. Both+ // inventories are painted every frame, even when text owns the pointer.+ let text_used = crate::edit_text_ui::page_input(cx, &lines, view, !others_own_pointer && !image_owns_pointer);+ let image_cx = crate::edit_text_ui::ImageCx {+ ui,+ resp,+ xf: &xf,+ ptr,+ page: i,+ info,+ allow_interaction: !others_own_pointer && (image_owns_pointer || !text_used),+ };+ let image_used = crate::edit_text_ui::image_input(&image_cx, &images, view, &mut frame.out.image_action);+ !others_own_pointer && (text_used || image_used)+ };+ let on_link = tool == QuickTool::Link && can_modify && crate::link_ui::page_input(cx, doc_links, view);+ if tool == QuickTool::Select+ && resp.secondary_clicked()+ && can_modify+ && let Some(p) = pointer.filter(|p| xf.rect.contains(*p))+ && let Some(l) = doc.links().iter().find(|l| l.page == i && crate::link_ui::screen_rect(&xf, info, i, l.rect).expand(2.0).contains(p))+ {+ view.links.context = Some((i, l.index));+ }+ let consumed = on_objects || on_edit_text || on_link || on_content || boxing || on_field || comments::page_input(ui, resp, &pcx, view);- PageInput { consumed, over_field, area_tool }++ PageInput { consumed, area_tool }+ }++ /// Text layer: find matches, selection, I-beam and drag-to-select.+ fn text_layer(ui: &mut egui::Ui, view: &mut DocView, frame: &mut PageFrame<'_>, slot: &PageSlot, input: &PageInput) {+ let PageEnv { info, selects_text, tool, .. } = frame.env;+ let PageSlot { i, r, xf } = *slot;+ let PageFrame { resp, ptr, pointer, .. } = *frame;+ if let Some(text) = view.texts.get(&i).cloned() {+ paint_text_marks(ui, view, &text, i, xf, resp.dragged());+ if selects_text+ && !input.consumed+ && let Some(p) = pointer.filter(|p| r.contains(*p))+ {- text_pointer_input(- ui,- view,- &text,- TextPointer { page: i, xf, rect: r, info, tool, resp, ptr: ptr.clone(), pointer: p, over_field: input.over_field },- );++ text_pointer_input(ui, view, &text, TextPointer { page: i, xf, rect: r, info, tool, resp, ptr: ptr.clone(), pointer: p });+ }}+ }- /// Where a bookmark made now should go: the page and the `/XYZ` position `[left, top]` in user- /// space. With text selected it is the corner of the selection that shows at its top-left- /// (its page, both coordinates); otherwise the top of the window (the page showing there, and- /// only the position along the window's vertical, so the reader's other scroll position and- /// zoom are kept). `None` before the first frame has laid pages out, when the bookmark just- /// goes to the current page.- pub(crate) fn bookmark_position(&self, info: &DocInfo) -> Option<(usize, [Option<f32>; 2])> {- if let Some(sel) = self.selection- && let Some(text) = self.texts.get(&sel.page)- && let Some(p) = info.pages.get(sel.page)- {- // 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 (x, y) = match self.rotation {- 90 => (x0, y1),- 180 => (x1, y1),- 270 => (x1, y0),- _ => (x0, y0),+ fn paint_text_marks(ui: &egui::Ui, view: &DocView, text: &PageText, page: usize, xf: PageXform, dragging: bool) {+ let painter = ui.painter();+ let to_screen = |g: [f32; 4]| xf.view_rect(g);+ if let Some(find) = &view.find {+ for (index, (match_page, range)) in find.matches.iter().enumerate() {+ if *match_page != page {+ continue;+ }+ let fill = if find.current == Some(index) {+ Color32::from_rgba_unmultiplied(255, 140, 0, 110)+ } else {+ Color32::from_rgba_unmultiplied(255, 214, 0, 90)};- if x.is_finite() && y.is_finite() {- return Some((sel.page, p.xyz_for_view(Some(x), Some(y))));+ for line_rect in text.line_rects(range.clone()) {+ painter.rect_filled(to_screen(line_rect).expand(1.0), CornerRadius::same(2), fill);}}- // The page showing at the window's top edge: one that crosses it (the first, in a spread- // of pages of different heights, whose shorter page can start below it), else the- // nearest one below.- let top = self.viewport_screen.top();- let showing = || self.screen_xforms.iter().filter(|(_, xf)| xf.rect.bottom() > top);- let (page, xf) = showing()- .filter(|(_, xf)| xf.rect.top() <= top)- .min_by_key(|(p, _)| *p)- .or_else(|| showing().min_by(|a, b| a.1.rect.top().total_cmp(&b.1.rect.top()).then(a.0.cmp(&b.0))))?;- let p = info.pages.get(*page)?;- // Above the page (in the gap before it) is the page's own top. The window's vertical is- // the view's y, or its x when the view is turned a quarter.- let (x, y) = xf.screen_to_view(pos2(xf.rect.center().x, top.max(xf.rect.top())));- let at = if xf.rot.is_multiple_of(180) {- p.xyz_for_view(None, Some(y.clamp(0.0, p.height)))- } else {- p.xyz_for_view(Some(x.clamp(0.0, p.width)), None)- };- Some((*page, at))}-- /// The user-space `[left, top]` at the window's top-left (where `/XYZ` puts its point), on the- /// page showing there: what a destination's null coordinate keeps (ISO 32000-2 §12.3.2.2).- /// Acrobat keeps the place this way across pages, so a CAD sheet's cross-reference opens the- /// next sheet where the reader was looking. A coordinate is `None` along a screen axis the- /// page fits, which keeps the layout's own placement (centred, or the page's top); the whole- /// place is `None` before the first frame has laid pages out.- fn place_at_corner(&self, info: &DocInfo) -> Option<[Option<f32>; 2]> {- let area = self.viewport_screen;- if !area.is_positive() {- return None;+ if view.all_text {+ for line_rect in text.line_rects(0..text.glyphs.len()) {+ painter.rect_filled(to_screen(line_rect), CornerRadius::same(1), Color32::from_rgba_unmultiplied(0x3A, 0x7B, 0xF0, 70));}- let corner = area.min + vec2(SIDE, 0.0);- let (page, xf) = self- .screen_xforms- .iter()- .filter(|(_, xf)| xf.rect.is_positive())- .min_by(|a, b| a.1.rect.distance_sq_to_pos(corner).total_cmp(&b.1.rect.distance_sq_to_pos(corner)).then(a.0.cmp(&b.0)))?;- let p = info.pages.get(*page)?;- let (x, y) = xf.screen_to_view(corner.clamp(xf.rect.min, xf.rect.max));- // `max` drops a NaN size, so the bounds stay ordered and `clamp` can't panic.- let (x, y) = (x.clamp(0.0, p.width.max(0.0)), y.clamp(0.0, p.height.max(0.0)));- // The page counts with its side gutters, as the layout places it.- let wide = xf.rect.width() + 2.0 * SIDE > area.width();- let tall = xf.rect.height() > area.height();- // The view's x runs across the screen unless the view is turned a quarter.- let (keep_x, keep_y) = if xf.rot.is_multiple_of(180) { (wide, tall) } else { (tall, wide) };- Some(p.xyz_for_view(keep_x.then_some(x), keep_y.then_some(y)))}-- /// A page's thumbnail texture, when rendered.- pub(crate) fn thumb_id(&self, page: usize) -> Option<egui::TextureId> {- self.thumbs.get(&page).map(|t| t.tex.id())+ if let Some(selection) = view.selection.filter(|selection| selection.page == page) {+ for line_rect in selection.rects(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+ && dragging+ {+ let outline = Stroke::new(1.0, Color32::from_rgb(0x3A, 0x7B, 0xF0));+ painter.rect_stroke(to_screen(rect), CornerRadius::ZERO, outline, egui::StrokeKind::Middle);+ }}+ }- /// The whole-page raster on screen for `page` (the low-res backdrop of a tiled page), if any.- pub(crate) fn page_raster(&self, page: usize) -> Option<egui::TextureId> {- self.pages.get(&page).map(|p| p.tex.id())- }+ struct TextPointer<'a> {+ page: usize,+ xf: PageXform,+ rect: Rect,+ info: &'a DocInfo,+ tool: QuickTool,+ resp: &'a egui::Response,+ ptr: PagePointer,+ pointer: Pos2,- over_field: bool,+ }- /// Whether `page`'s whole-page raster (a tiled page's backdrop too) is still the one from- /// before its last change, whatever its tiles are.- pub(crate) fn page_raster_out_of_date(&self, page: usize) -> bool {- self.pages.get(&page).is_some_and(|p| p.tag == STALE_TAG)+ struct TextGesture<'a> {+ page: usize,+ xf: PageXform,+ rect: Rect,+ tool: QuickTool,+ ptr: PagePointer,+ resp: &'a egui::Response,+ pointer: Pos2,+ vx: f32,+ vy: f32,+ over_text: bool,+ over_link: bool,+ column: bool,+ }++ fn text_pointer_input(ui: &mut egui::Ui, view: &mut DocView, text: &PageText, pointer: TextPointer<'_>) {- let TextPointer { page, xf, rect, info, tool, resp, ptr, pointer: screen_pointer, over_field } = pointer;++ let TextPointer { page, xf, rect, info, tool, resp, ptr, pointer: screen_pointer } = pointer;+ let (vx, vy) = xf.screen_to_view(screen_pointer);+ let over_text = text.glyphs.iter().any(|glyph| vx >= glyph.rect[0] && vx <= glyph.rect[2] && vy >= glyph.rect[1] && vy <= glyph.rect[3]);+ let over_link = info.links.iter().any(|link| link.page == page && xf.user_rect(info, page, link.rect).contains(screen_pointer));+ let column = tool == QuickTool::ColumnSelect || ui.input(|input| input.modifiers.alt);+ let gesture = TextGesture { page, xf, rect, tool, ptr, resp, pointer: screen_pointer, vx, vy, over_text, over_link, column };- update_text_cursor(ui, resp, over_field, &gesture);++ update_text_cursor(view, &gesture);+ update_selection_on_press(ui, view, text, &gesture);+ update_dragged_selection(view, text, &gesture);+ finish_text_pointer_gesture(ui, view, text, &gesture);+ }+-fn update_text_cursor(ui: &egui::Ui, resp: &egui::Response, over_field: bool, gesture: &TextGesture<'_>) {- let cursor_free = !gesture.over_link && !over_field && (resp.contains_pointer() || resp.dragged());- if gesture.column && cursor_free {- ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair);- } else if gesture.over_text && cursor_free {- ui.ctx().set_cursor_icon(egui::CursorIcon::Text);++fn update_text_cursor(view: &mut DocView, gesture: &TextGesture<'_>) {++ // A press on a link selects nothing (it is the link's), so no cursor here says it would.++ if gesture.column && !gesture.over_link {++ view.cursor.claim(Layer::Text, egui::CursorIcon::Crosshair);++ } else if gesture.over_text && !gesture.over_link {++ view.cursor.claim(Layer::Text, egui::CursorIcon::Text);+ }+ }++ fn update_selection_on_press(ui: &egui::Ui, view: &mut DocView, text: &PageText, gesture: &TextGesture<'_>) {+ let press_here = gesture.ptr.origin.is_some_and(|origin| gesture.rect.contains(origin));+ if gesture.ptr.pressed().is_some() && press_here && !gesture.over_link {+ let now = ui.input(|input| input.time);+ let (max_delay, max_dist) = ui.ctx().options(|options| (options.input_options.max_double_click_delay, options.input_options.max_click_dist));+ let consecutive = now - view.last_press_time <= max_delay && view.last_press_pos.is_some_and(|pos| pos.distance(gesture.pointer) <= max_dist);+ view.clicks = if consecutive { view.clicks.saturating_add(1) } else { 1 };+ view.last_press_time = now;+ view.last_press_pos = Some(gesture.pointer);+ let clicks = selection_click_count(view.clicks, gesture.tool);+ if clicks >= 2+ && gesture.over_text+ && let Some((first, last)) = text.nearest(gesture.vx, gesture.vy).and_then(|anchor| click_unit(text, clicks, anchor))+ {+ view.selection = Some(Selection::run(gesture.page, first, last));+ }}-- /// Whether `page` is still drawn, somewhere, as it was before its last change: its whole-page- /// raster (a tiled page's backdrop too) or any of its tiles waits for a replacement.- pub(crate) fn page_out_of_date(&self, page: usize) -> bool {- self.pages.get(&page).is_some_and(|p| p.tag == STALE_TAG) || self.stale_tiles.iter().any(|k| k.0 == page)+ if gesture.resp.drag_started() && press_here && !gesture.over_link {+ 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))+ };+ }}+ }- /// The print preview's picture of `page`: the sheet raster when it has arrived, otherwise the- /// thumbnail.- pub(crate) fn page_preview(&self, page: usize) -> Option<egui::TextureId> {- self.print_pages.get(&page).map(|(_, tex)| tex.id()).or_else(|| self.thumb_id(page))- }+ fn selection_click_count(clicks: u32, tool: QuickTool) -> u32 {+ if clicks > 2 && tool != QuickTool::Select { 1 } else { clicks }+ }- pub(crate) fn page_text(&self, page: usize) -> Option<Arc<PageText>> {- self.texts.get(&page).cloned()+ fn update_dragged_selection(view: &mut DocView, text: &PageText, gesture: &TextGesture<'_>) {+ let clicks = selection_click_count(view.clicks, gesture.tool);+ if gesture.resp.dragged()+ && let Some(selection) = view.selection.as_mut().filter(|selection| selection.page == gesture.page)+ {+ match &mut selection.span {+ Span::Run { anchor, head } 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));+ (*anchor, *head) = if to_first < first { (last, to_first) } else { (first, to_last.max(last)) };+ }+ }+ Span::Run { head, .. } => {+ if let Some(hit) = text.nearest(gesture.vx, gesture.vy) {+ *head = hit;+ }+ }+ Span::Column { rect } => {+ rect[2] = gesture.vx;+ rect[3] = gesture.vy;+ }+ }}-- pub(crate) fn clear_selection(&mut self) {- self.selection = None;- self.actions_dismissed = None;+ 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()+ })+ {+ view.selection = None;}+ }- /// 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));+ 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)+ } else if gesture.resp.double_clicked() {+ view.clicks.max(2)+ } else {+ 0+ };+ if release_clicks > 0 {+ view.clicks = release_clicks;+ }+ let clicks = selection_click_count(view.clicks, gesture.tool);+ if release_clicks > 0+ && clicks >= 2+ && gesture.over_text+ && view.selection.is_none()+ && let Some((first, last)) = text.nearest(gesture.vx, gesture.vy).and_then(|anchor| click_unit(text, clicks, anchor))+ {+ view.selection = Some(Selection::run(gesture.page, first, last));+ } else if gesture.resp.clicked() && view.clicks < 2 && !gesture.over_link {+ 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, .. }), Some(hit)) => *head = hit,+ _ => view.selection = None,+ }+ }+ }++ /// Everything drawn over the page after its text: pictures, comments, content, links, fields, marks+ /// and badges.+ fn page_overlays(ui: &mut egui::Ui, view: &mut DocView, frame: &mut PageFrame<'_>, slot: &PageSlot, input: &PageInput) {+ let PageEnv {+ added,+ allowed,+ calc_order,+ can_modify,+ comments_hidden,+ doc,+ doc_links,+ editing_content,+ form,+ generation,+ info,+ prefs,+ preparing,+ redact_mark,+ table_preview,+ tool,+ unobstructed,+ ..+ } = frame.env;+ let PageSlot { i, xf, .. } = *slot;+ let PageFrame { resp, ptr, pointer, .. } = *frame;+ let painter = ui.painter();+ let tool_cx = PageToolContext { ui, resp, xf: &xf, ptr, page: i, doc, info };+ let pcx = comments::PageCx { page: i, xf: &xf, ptr, info, tool, prefs, allowed, hidden: comments_hidden, redact_mark };+ if tool == QuickTool::Select && !input.consumed {+ crate::image_pick::page_input(resp, &xf, i, info, doc, pointer, view);+ }+ crate::image_pick::drop_stale(doc, view);+ crate::image_pick::paint(painter, &xf, i, info, view);+ comments::page_after_text(resp, &pcx, view);+ if tool == QuickTool::Redact && can_modify {+ crate::redact_ui::after_text(resp, i, info, view);+ }+ if input.area_tool {+ crate::redact_ui::paint(painter, i, view, pointer);+ }+ comments::paint_page(ui, painter, &pcx, view);+ if editing_content {+ crate::content_ui::paint_page(painter, &xf, i, info, added, view, pointer);}-- /// Open the find bar (or focus it if already open).- pub fn open_find(&mut self) {- let f = self.find.get_or_insert_with(Find::default);- f.focus = true;+ if tool == QuickTool::EditText {+ crate::object_ui::paint(painter, &xf, i, info, &view.objects);}-- /// Re-run the search on all pages whose text is known (after the query changed).- pub fn rerun_find(&mut self) {- let Some(f) = self.find.as_mut() else { return };- f.case_query = f.query.clone();- f.matches.clear();- f.current = None;- // Refining the query keeps the page the reader started searching from, even when an- // automatic choice has already scrolled them to a match. Only a view the reader moved- // themselves re-anchors the search on the page now shown.- let from = match (f.auto_from, f.auto_page) {- (Some(from), Some(page)) if !f.follow_ended && page == self.current => from,- _ => self.current,- };- f.auto_from = Some(from);- f.auto_page = Some(self.current);- f.follow_ended = false;- if f.case_query.trim().is_empty() {- return;+ if tool == QuickTool::EnhanceCamera {+ crate::camera_ui::paint(painter, &xf, i, view);+ }+ if tool == QuickTool::Link {+ crate::link_ui::paint(painter, &xf, i, info, doc_links, view, pointer);+ }+ if preparing {+ crate::prepare::paint_page(tool_cx, form, view);+ if let Some(preview) = &table_preview {+ crate::field_table_ui::paint_preview(painter, &xf, i, preview);}- let mut pages: Vec<usize> = self.texts.keys().copied().collect();- pages.sort();- for &p in &pages {- if let Some(text) = self.texts.get(&p) {- f.matches.extend(text.find_opts(&f.case_query, f.case_sensitive, f.whole_words).into_iter().map(|r| (p, r)));+ if calc_order {+ let selected = view.prepare.selected.as_ref().map(|(name, _)| name.as_str());+ if let Some(name) = crate::calc_order_ui::paint_page(tool_cx, form, &view.calc_order, generation, selected) {+ frame.calc_hover = Some(name);}}- f.matches.sort_by_key(|(p, r)| (*p, r.start));- // First match at or after the page the search started from.- if let Some(i) = f.first_at_or_after(from)- && let Some(&(p, _)) = f.matches.get(i)- {- f.current = Some(i);- f.auto_page = Some(p);- self.flash_match(p);+ } else {+ crate::forms_ui::paint_page(painter, &xf, i, info, form, view, pointer);+ }++ // Form-field highlight (Acrobat's "Highlight existing fields"); required fields get a+ // red border. Radio buttons and round XFA check boxes are round, and so is theirs (as+ // in Acrobat). Only what can be filled is marked: a read-only widget (its field's, or a+ // radio button's own) is left as it is drawn.+ paint_field_highlights(painter, &xf, info, form.as_slice(), i, view.highlight_fields);- // Fill & Sign keeps its placement cursor clear of link/comment hover feedback. Tips- // draw above the palette, so none shows while it is open, even beside it.- if !matches!(tool, QuickTool::Fill(_))- && unobstructed- && let Some(p) = pointer- {++ // Links: the hand and the link's target, which count only for the tools that follow or++ // edit links (`Layer::reached_by`). Tips draw above the palette, so none shows while it is++ // open, even beside it.++ if unobstructed && let Some(p) = pointer {+ for l in info.links.iter().filter(|l| l.page == i) {+ let sr = xf.user_rect(info, i, l.rect);+ if sr.contains(p) {- ui.ctx().set_cursor_icon(egui::CursorIcon::PointingHand);+ let label = match &l.target {+ LinkTarget::Page(n, _) => {+ crate::i18n::fmt(tl!("Go to page {p}"), &[("p", info.pages.get(*n).map(|p| p.label.as_str()).unwrap_or("?"))])+ }+ LinkTarget::Uri(u) => u.clone(),+ LinkTarget::SetLayers { .. } => tl!("Set layer visibility").to_string(),+ LinkTarget::RemoteGoTo { file, .. } => file.clone(),+ LinkTarget::Other(s) => crate::i18n::fmt(tl!("{s} action"), &[("s", s)]),+ };- frame.out.hover_text = Some((p, label));++ view.cursor.claim_with_tip(Layer::Link, egui::CursorIcon::PointingHand, Some(label));+ if resp.clicked() && tool == QuickTool::Select && !input.consumed {+ frame.out.clicked_link = Some(l.target.clone());+ }+ }}- // Annotation hover shows the comment, as Acrobat's popups do; not while drawing- // freehand, where it would cover the next stroke (#429).- let freehand = matches!(tool, QuickTool::Comment(comments::CommentTool::Ink | comments::CommentTool::Eraser));- let gesturing = view.comments.gesture.is_some() || freehand;- // Inspection sorts annotations spatially, but the renderer paints in /Annots- // order. Keep the shared list intact and choose the last eligible raw index.- if frame.out.hover_text.is_none()- && !gesturing- && let Some((_, text)) = info- .annotations- .iter()- .filter(|a| a.page == i)- .filter(|a| !(prefs.hide_empty_highlight_hover && a.subtype == "Highlight" && a.contents.as_deref().is_none_or(str::is_empty)))- .filter(|a| pcx.screen_rects(a).any(|r| r.contains(p)))- .filter_map(|a| annotation_hover_text(a).map(|text| (a.index, text)))- .max_by_key(|(index, _)| *index)- {- frame.out.hover_text = Some((p, text));- }}-- fn refresh_find_page(&mut self, page: usize) {- let (Some(f), Some(text)) = (self.find.as_mut(), self.texts.get(&page)) else { return };- if f.case_query.trim().is_empty() {- return;++ // Comments say what they are with any tool, beside its cursor, as Acrobat's do.++ comments::describe(&pcx, view);+ for (mp, mr, mc) in &view.compare_marks {+ if *mp == i {+ let sr = xf.user_rect(info, i, *mr).expand(1.5);+ painter.rect_filled(sr, CornerRadius::same(2), mc.gamma_multiply(0.28));}- let previous = f.current.and_then(|c| f.matches.get(c).cloned());- // An automatic choice follows the page it was anchored on, so a page whose text- // arrives late can still supply an earlier match. Once the reader has moved the view,- // this arrival must not pull them back; the choice then becomes theirs to keep.- let follow = f.follow_page(self.current);- f.matches.retain(|(p, _)| *p != page);- f.matches.extend(text.find_opts(&f.case_query, f.case_sensitive, f.whole_words).into_iter().map(|r| (page, r)));- f.matches.sort_by_key(|(p, r)| (*p, r.start));- if let Follow::Active(from) = follow {- f.current = f.first_at_or_after(from);- let selected = f.current.and_then(|i| f.matches.get(i).cloned());- // Follow a changed automatic choice; the view is still where the last one left it.- if selected != previous- && let Some((p, _)) = selected- {- f.auto_page = Some(p);- self.flash_match(p);- }- return;+ }+ if let Some((fp, fr, t0)) = view.flash+ && fp == i+ {+ let now = ui.input(|inp| inp.time);+ let t0 = if t0 == 0.0 { now } else { t0 };+ view.flash = Some((fp, fr, t0));+ let age = (now - t0) as f32;+ if age < 1.6 {+ let a = ((1.6 - age) / 1.6 * 255.0) as u8;+ let sr = xf.user_rect(info, i, fr).expand(4.0);+ painter.rect_stroke(+ sr,+ CornerRadius::same(3),+ Stroke::new(2.5, Color32::from_rgba_unmultiplied(0x1B, 0x63, 0xE0, a)),+ egui::StrokeKind::Outside,+ );+ ui.ctx().request_repaint();+ } else {+ view.flash = None;}- // A match the user picked keeps its identity, exactly as before automatic following.- // When it is gone (or none was picked), the first match at or after the viewed page is- // selected for the panel, but the view stays put: `Ended` and `Never` have no automatic- // choice to reveal, and a reader who moved before the first layer arrived must not be- // pulled back by that late match.- let preserved = previous.as_ref().and_then(|k| f.matches.iter().position(|m| m == k));- f.current = preserved.or_else(|| f.first_at_or_after(self.current));}-- /// Go to match `i` (the Search panel's results).- pub fn go_to_match(&mut self, i: usize) {- let Some(f) = self.find.as_mut() else { return };- let Some(&(p, _)) = f.matches.get(i) else { return };- f.current = Some(i);- f.stop_following();- self.go_to_page(p);- self.goto_point = None;- self.flash_match(p);+ // Validation is viewer chrome over the signer's original artwork, which+ // may still say "Signature Not Verified". These badges never enter document+ // streams, image/text exports, vector printing or Print as Image.+ for badge in signature_badges(&doc.signatures, i) {+ let [x0, y0, x1, y1] = badge.rect;+ let sr = xf.user_rect(info, i, [x0 as f32, y0 as f32, x1 as f32, y1 as f32]);+ let (icon, color) = crate::sign_ui::signature_status_style(badge.status);+ painter.rect_stroke(sr, CornerRadius::same(2), Stroke::new(1.5, color), egui::StrokeKind::Outside);+ // A widget too small for the mark keeps its outline: the verdict still shows.+ if sr.width() < 4.0 || sr.height() < 4.0 {+ continue;+ }+ // Big enough to read at a glance, small enough to leave the signer's own+ // text visible around it.+ let side = (sr.width().min(sr.height()) * 0.8).clamp(24.0, 192.0);+ let mark = Rect::from_center_size(sr.center(), vec2(side, side));+ icons::paint(ui, mark, icon, side * 0.64, color);- if let Some(p) = pointer.filter(|p| mark.expand(2.0).contains(*p)) {- frame.out.badge_hover = Some((p, badge.summary.to_string()));++ // Overlapping widgets paint in order, so the topmost badge's verdict is the tip, with++ // any tool; a link's or a comment's tip wins over any badge.++ if pointer.is_some_and(|p| mark.expand(2.0).contains(p)) {++ view.cursor.describe(Subject::SignatureBadge, badge.summary.to_string());+ }}- // Overlapping widgets paint in order, so the topmost badge owns the hover; an- // earlier link or annotation hover still wins over any badge.- if frame.out.hover_text.is_none() {- frame.out.hover_text = frame.out.badge_hover.take();- }+ }- /// Move to the next/previous match.- pub fn find_step(&mut self, forward: bool) {- let Some(f) = self.find.as_mut() else { return };- if f.matches.is_empty() {- return;+ fn paint_field_highlights(painter: &egui::Painter, xf: &PageXform, info: &DocInfo, form: &[pdfcraft_engine::FormField], page: usize, enabled: bool) {+ if !enabled {+ return;+ }+ for field in form.iter() {+ let required = field.has(pdfcraft_engine::field_flags::REQUIRED);+ for widget in field.widgets.iter().filter(|widget| widget.page == Some(page) && !widget.hidden && !widget.read_only) {+ let rect = widget.rect;+ let screen_rect = xf.user_rect(info, page, [rect[0] as f32, rect[1] as f32, rect[2] as f32, rect[3] as f32]);+ let tint = Color32::from_rgba_unmultiplied(0x6E, 0x8E, 0xF5, 48);+ let (width, color) = if required { (2.0, Color32::from_rgb(0xE3, 0x22, 0x22)) } else { (1.0, Color32::from_rgb(0x6E, 0x8E, 0xF5)) };+ if widget.round {+ let radius = screen_rect.width().min(screen_rect.height()) / 2.0;+ painter.circle_filled(screen_rect.center(), radius, tint);+ painter.circle_stroke(screen_rect.center(), radius - width / 2.0, Stroke::new(width, color));+ } else {+ painter.rect_filled(screen_rect, CornerRadius::same(1), tint);+ painter.rect_stroke(screen_rect, CornerRadius::same(1), Stroke::new(width, color), egui::StrokeKind::Inside);+ }}- let n = f.matches.len();- let c = f.current.unwrap_or(0);- let next = if forward { (c + 1) % n } else { (c + n - 1) % n };- f.current = Some(next);- f.stop_following();- let p = f.matches[next].0;- // Only explicit search navigation joins history; background refresh uses flash_match alone.- self.go_to_page(p);- self.goto_point = None;- self.flash_match(p);}+ }- fn flash_match(&mut self, page: usize) {- let frac = self- .find- .as_ref()- .and_then(|f| f.current.and_then(|c| f.matches.get(c)))- .and_then(|(p, r)| self.texts.get(p).and_then(|t| t.glyphs.get(r.start)).map(|g| g.rect[1]))- .zip(self.page_heights.get(page).copied())- .map(|(y, h)| ((y - 60.0) / h).clamp(0.0, 1.0))- .unwrap_or(0.0);- self.goto = Some((page, frac));- self.current = page;- self.reset_coarse_state();+ fn draw_page(ui: &mut egui::Ui, view: &mut DocView, frame: &mut PageFrame<'_>, i: usize) {+ let PageEnv { allowed, comments_hidden, doc, editing_content, info, ppp, prefs, rects, redact_mark, scale, t, tool, .. } = frame.env;+ let PageFrame { ptr, origin, visible, pressed, pointer, .. } = *frame;- frame.out.badge_hover = None;+ let r = snap_to_pixels(rects[i].translate(origin.to_vec2()), ppp);+ if !r.intersects(visible.expand(400.0)) {+ return;}-- /// Screen position of the centre of glyph `glyph` on `page`, if that page is on screen and its- /// text layer is loaded (used by UI tests and automation to aim pointer input).- pub fn glyph_screen_pos(&self, page: usize, glyph: usize) -> Option<Pos2> {- let (_, xf) = self.screen_xforms.iter().find(|(p, _)| *p == page)?;- let g = self.texts.get(&page)?.glyphs.get(glyph)?;- Some(xf.view_rect(g.rect).center())+ if pressed && frame.pressed_page.is_none() && pointer.is_some_and(|p| r.contains(p)) {+ frame.pressed_page = Some(i);+ }+ if r.intersects(visible) {+ frame.visible_now.push(i);+ view.screen_rects.push((i, r));+ view.screen_xforms.push((i, PageXform { rect: r, rot: view.rotation, pw: info.pages[i].width.max(1.0), ph: info.pages[i].height.max(1.0) }));+ }+ let overlap = r.intersect(visible).height();+ if i == view.current {+ frame.current_overlap = overlap;+ frame.current_height = r.height();+ }+ // Pages shown equally (two rows wholly on screen) differ only by rounding: the+ // topmost one counts.+ if overlap > frame.best_overlap + PAGE_TIE {+ frame.best_overlap = overlap;+ frame.current = i;+ }+ let xf = PageXform { rect: r, rot: view.rotation, pw: info.pages[i].width.max(1.0), ph: info.pages[i].height.max(1.0) };+ paint_page_surface(ui, view, frame, &PageSlot { i, r, xf });+ let painter = ui.painter();+ view.text_background.paint(painter, &xf, i, view.line_editor.as_ref(), view.content.draft.as_ref());+ if editing_content {+ view.move_background.paint(painter, &xf, i, info, &view.content, pointer);}-- /// 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`]).- pub fn selected_text(&self) -> Option<String> {- 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())+ if view.show_page_gaps {+ painter.rect_stroke(r, CornerRadius::ZERO, Stroke::new(0.5, t.border.gamma_multiply(0.8)), egui::StrokeKind::Outside);}- pub fn thumb(&self, page: usize) -> Option<&TextureHandle> {- self.thumbs.get(&page).map(|t| &t.tex)- }-- /// Drops wheel state after a discontinuous jump so the destination cannot- /// inherit momentum from the previous viewport.- fn reset_coarse_state(&mut self) {- self.wheel.clear_motion();- self.wheel_boost_x.reset();- self.wheel_boost_y.reset();- }+ let slot = PageSlot { i, r, xf };+ let input = page_tool_input(ui, view, frame, &slot);+ let painter = ui.painter();+ let pcx = comments::PageCx { page: i, xf: &xf, ptr, info, tool, prefs, allowed, hidden: comments_hidden, redact_mark };+ let preview_target = (matches!(tool, QuickTool::Select | QuickTool::Fill(_)) && !comments_hidden).then_some(view.comments.selected).flatten();+ view.signature_drag.prepare(ui.ctx(), doc, preview_target, scale);+ view.signature_drag.paint(painter, &pcx, &view.comments, view.pending_edit.as_ref());- /// Ends automatic search following after the reader navigated or scrolled the view. A- /// programmatic search flash never comes through here; it sets `goto` and `current` directly- /// so that its own scroll cannot be mistaken for the reader's.- fn end_find_following(&mut self) {- if let Some(f) = self.find.as_mut() {- f.stop_following();- }+ // Any press on the page ends Select All of the document: text read or not, any tool,+ // on a link too.+ // A press that lands on something drawn over the page (a menu, a dialog) is not one.+ if view.all_text && frame.pressed_page == Some(i) {+ view.all_text = false;}+ text_layer(ui, view, frame, &slot, &input);+ page_overlays(ui, view, frame, &slot, &input);+ }- pub fn go_to_page(&mut self, page: usize) {- let page = page.min(self.page_count.saturating_sub(1));- self.end_find_following();- if page != self.current {- // The view history (Previous view / Next view).- if self.back.last() != Some(&self.current) {- self.back.push(self.current);- if self.back.len() > 200 {- self.back.remove(0);- }- }- self.forward.clear();+ fn draw_pages(+ ui: &mut egui::Ui,+ viewport: Rect,+ view: &mut DocView,+ env: &PageEnv<'_>,+ out: &mut PageOut,+ signature_preview: &mut Option<(crate::fill_sign::SavedSig, egui::TextureHandle)>,+ ) -> PageRenders {+ let PageEnv {+ allowed,+ auto_delta,+ avail,+ boost_extra,+ calc_order,+ can_copy,+ can_modify,+ content_h,+ content_w,+ doc,+ edge_delta,+ form,+ generation,+ glide,+ hand,+ info,+ key_scroll,+ middle_gesture,+ modal,+ navigation_enabled,+ precise_scroll,+ prefs,+ preparing,+ selection_wheel,+ single_paging,++ tool,+ unobstructed,+ visible_pages,+ y_shift,+ ..+ } = *env;+ // egui's drag responses accept every pointer button. Keep a wheel gesture from also+ // selecting text, drawing a mark, or panning with the Hand tool.+ if middle_gesture {+ let opacity = ui.opacity();+ ui.disable();+ // Only interactions pause; the document must keep its original colours.+ ui.set_opacity(opacity);+ }+ // Middle-button auto-scroll, the keyboard, precise touchpad input (#759) and its glide+ // (#531), accelerated wheel surplus (#1072), and a drawing's edge scroll; positive y+ // moves the content down. All scroll without easing, unlike egui's wheel default.+ // ScrollArea ignores wheel input during a widget drag. Defer the wheel contribution+ // until after the text widgets when a selection owns that drag.+ let wheel_delta = if selection_wheel { Vec2::ZERO } else { precise_scroll + boost_extra };+ let delta = auto_delta + edge_delta - vec2(0.0, key_scroll) + wheel_delta + glide;+ if delta != Vec2::ZERO && delta.is_finite() {+ ui.scroll_with_delta_animation(delta, egui::style::ScrollAnimation::none());+ }+ let (resp_rect, resp) = ui.allocate_exact_size(vec2(content_w, content_h), 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.+ if !resp.dragged_by(egui::PointerButton::Primary) {+ view.selection_drag = false;+ }+ // The Hand tool pans by this widget's drag, before the pages are laid out (above).+ if hand {+ if resp.dragged() {- ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing);++ view.cursor.claim(Layer::Drag, egui::CursorIcon::Grabbing);+ } else if resp.hovered() {- ui.ctx().set_cursor_icon(egui::CursorIcon::Grab);++ view.cursor.claim(Layer::ToolArea, egui::CursorIcon::Grab);+ }+ }+ let origin = resp_rect.min - vec2(0.0, y_shift);+ let visible = viewport.translate(resp_rect.min.to_vec2());+ view.screen_rects.clear();+ view.screen_xforms.clear();+ // The pointer as the pages see it: nothing over them (a dialog from the frame it opens),+ // or a press they hold. The page modules read it rather than egui's raw pointer state.+ let ptr = PagePointer::read(ui, &resp, modal);+ let pointer = ptr.pos;+ // A press on a page makes it the current one (as in Acrobat), so a page command with+ // no selection (Rotate, Delete) acts on the page the reader pointed at, not on a page+ // gone to earlier that still shows whole beside it.+ let pressed = unobstructed && ptr.pressed().is_some();+ if resp.secondary_clicked() {+ // Set again below when the right-click lands on a link.+ view.links.context = None;+ }+ let mut frame = PageFrame {+ env: *env,+ resp: &resp,+ ptr: &ptr,+ origin,+ visible,+ pressed,+ pointer,+ signature_preview,+ out: std::mem::take(out),+ wanted: Vec::new(),+ visible_now: Vec::new(),+ current: view.current,+ best_overlap: -1.0,+ current_overlap: -1.0,+ current_height: f32::INFINITY,+ pressed_page: None,+ calc_hover: None,+ };+ for &i in visible_pages {+ draw_page(ui, view, &mut frame, i);+ }+ let PageFrame {+ wanted, visible_now, mut current, best_overlap, current_overlap, current_height, pressed_page, calc_hover, out: page_out, ..+ } = frame;+ let PageOut {- badge_hover,+ mut canvas_action,+ clicked_link,+ mut copy_selected,+ mut field_menu,+ field_placed,+ field_props,- hover_text,++ hover_text: _,+ image_action,+ open_boxes,+ open_initials,+ open_signature,+ open_table,+ primary_down: _,+ refused,+ stamp_placed,+ } = page_out;+ let painter = ui.painter();+ if calc_order {+ view.calc_order.set_hover_page(calc_hover);+ let selected = view.prepare.selected.as_ref().map(|(name, _)| name.as_str());+ crate::calc_order_ui::paint_trace(ui, painter, visible, &view.calc_order, generation, selected);+ }++ // The pages' one cursor, from the claim on the highest layer the tool reaches, and the tip.++ let hover_text = pointer.filter(|_| unobstructed).zip(view.cursor.resolve(ui.ctx(), tool));+ // ScrollArea ignores the wheel while any widget is dragged, so a text-selection drag+ // scrolls the page itself (#721). After the page loop, so it keeps scrolling once the+ // pointer leaves the selection's page for the gap or the next page; over the whole+ // document area, like #759. Combine direct and smoothed motion in one request so mixed+ // Point and Line events retain their full contribution.+ if selection_wheel {+ let smooth = if view.precise_scroll_until == 0.0 { ui.input_mut(|input| std::mem::take(&mut input.smooth_scroll_delta)) } else { Vec2::ZERO };+ let delta = precise_scroll + boost_extra + smooth;+ if delta != Vec2::ZERO && delta.is_finite() {+ ui.scroll_with_delta_animation(delta, egui::style::ScrollAnimation::none());}- // Partial wheel motion belongs to the old place.- self.reset_coarse_state();- self.goto = Some((page, 0.0));- self.current = page;}-- /// Reveal a user-space rectangle without changing zoom, centred where the scroll bounds allow.- pub(crate) fn reveal_rect(&mut self, page: usize, rect: [f32; 4], info: &DocInfo) {- self.go_to_page(page);- self.goto_point = None;- let Some(p) = info.pages.get(self.current) else { return };- if !rect.iter().all(|v| v.is_finite()) {- return;+ // 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.+ if view.selection_drag+ && navigation_enabled+ && unobstructed+ && !single_paging+ && let Some(p) = ptr.pos+ {+ let dy = crate::autoscroll::edge_delta(p.y, avail, ui.input(|i| i.stable_dt));+ if dy != 0.0 {+ view.end_find_following();+ ui.scroll_with_delta_animation(vec2(0.0, dy), egui::style::ScrollAnimation::none());+ // Keep scrolling while the pointer rests there and sends no events.+ ui.ctx().request_repaint();}- // Halve before adding so even large finite coordinates cannot overflow the midpoint.- let x = rect[0] * 0.5 + rect[2] * 0.5;- let y = rect[1] * 0.5 + rect[3] * 0.5;- let [fx, fy] = p.dest_fraction(Some(x), Some(y), self.rotation);- self.goto_point = Some((self.current, fx, fy, vec2(self.viewport_w, self.viewport_h) / 2.0));}-- /// Go to a destination, a bookmark's or a link's (ISO 32000-2 §12.3.2.2): its page, scrolled- /// and zoomed as `dest` asks, as Acrobat does. `/XYZ` puts (left, top) at the window's- /// top-left at its zoom (null or 0 keeps the zoom); `/Fit`, `/FitH` and `/FitV` switch to fit- /// page, width and height with `top` or `left` at the window's edge; `/FitR` zooms so the- /// rectangle fits, centred. The `B` (content box) forms are read as the page. A null `/XYZ`- /// coordinate keeps the reader's place: the same user-space point stays at the window's- /// top-left on the new page, as Acrobat does. A point past the end of the document scrolls- /// as far as it can.- pub fn go_to_dest(&mut self, page: usize, dest: DestView, info: &DocInfo) {- // Read before the jump: it is where the reader is now.- let kept = match dest {- DestView::Xyz { left, top, .. } if left.is_none() || top.is_none() => self.place_at_corner(info),- _ => None,- };- self.go_to_page(page);- let page = self.current;- self.goto_point = None;- let Some(p) = info.pages.get(page) else { return };- let point = |x: Option<f32>, y: Option<f32>| p.dest_fraction(x, y, self.rotation);- // The window's top-left as far as pages go: its left edge is the gutter that keeps them- // clear of the floating quick-action bar, so `left` 0 shows the page's edge beside it.- let corner = vec2(SIDE, 0.0);- let (fx, fy, rel) = match dest {- DestView::Top => return,- DestView::Xyz { left, top, zoom } => {- if let Some(z) = zoom {- self.zoom = z.clamp(0.08, 64.0);- self.fit = Fit::None;- self.zoom_anchor = None;- }- let [kept_left, kept_top] = kept.unwrap_or([None, None]);- let [fx, fy] = point(left.or(kept_left), top.or(kept_top));- (fx, fy, corner)- }- DestView::Fit => {- self.fit = Fit::Page;- return;+ // The page navigated to stays current while no page shows more of itself, so the next+ // page step starts from it rather than from a page further down the screen (#188).+ // It also stays current while it is wholly on screen: a short page (a cheque) gone to+ // from the Pages panel shows less of itself than the tall page below it, and must not+ // hand the highlight to that page.+ if current_overlap >= best_overlap - PAGE_TIE || current_overlap >= current_height - PAGE_TIE {+ current = view.current;+ }+ if let Some(p) = pressed_page {+ current = p;+ }+ if view.continuous {+ view.current = current;+ }+ resp.context_menu(|ui| {+ // Preparing a form: the selected field's menu.+ if preparing && let Some((name, wi)) = view.prepare.selected.clone() {+ // Several fields: Align, Center, Distribute, Set Fields to Same Size.+ if !view.prepare.also.is_empty() {+ use crate::prepare::Arrange as A;+ let others = view.prepare.also.clone();+ let anchor = (name.clone(), wi);+ let mut pick = |ui: &mut egui::Ui, op: A, label: &str| {+ if ui.add_enabled(can_modify, egui::Button::new(tl!(label))).clicked() {+ view.pending_edit = crate::prepare::arrange(form, &anchor, &others, op);+ ui.close();+ }+ };+ ui.menu_button(tl!("Align"), |ui| {+ pick(ui, A::AlignLeft, "Left");+ pick(ui, A::AlignRight, "Right");+ pick(ui, A::AlignTop, "Top");+ pick(ui, A::AlignBottom, "Bottom");+ pick(ui, A::AlignCenterV, "Center vertically");+ pick(ui, A::AlignCenterH, "Center horizontally");+ });+ ui.menu_button(tl!("Distribute"), |ui| {+ pick(ui, A::DistributeH, "Horizontally");+ pick(ui, A::DistributeV, "Vertically");+ });+ ui.menu_button(tl!("Set Fields to Same Size"), |ui| {+ pick(ui, A::SameHeight, "Height");+ pick(ui, A::SameWidth, "Width");+ pick(ui, A::SameSize, "Both");+ });+ ui.separator();}- DestView::FitH { top } => {- self.fit = Fit::Width;- let [fx, fy] = point(None, top);- (fx, fy, corner)+ if ui.button(tl!("Properties…")).clicked() {+ field_menu = Some(FieldMenu::Properties);+ ui.close();}- DestView::FitV { left } => {- self.fit = Fit::Height;- let [fx, fy] = point(left, None);- (fx, fy, corner)+ if ui.add_enabled(can_modify, egui::Button::new(tl!("Duplicate…"))).clicked() {+ field_menu = Some(FieldMenu::Duplicate(name.clone()));+ ui.close();}- DestView::FitR { rect } => {- let ([Some(ax), Some(ay)], [Some(bx), Some(by)]) = (point(Some(rect[0]), Some(rect[3])), point(Some(rect[2]), Some(rect[1]))) else {- return;- };- // The rectangle as displayed, in points (it can be turned a quarter).- let (dw, dh) = self.display_size(p);- let (w, h) = ((ax - bx).abs() * dw, (ay - by).abs() * dh);- if w >= 1.0 && h >= 1.0 && self.viewport_w >= 1.0 && self.viewport_h >= 1.0 {- self.zoom = (self.viewport_w / (w * PT)).min(self.viewport_h / (h * PT)).clamp(0.08, 64.0);- self.fit = Fit::None;- self.zoom_anchor = None;- }- (Some((ax + bx) / 2.0), Some((ay + by) / 2.0), vec2(self.viewport_w, self.viewport_h) / 2.0)+ ui.separator();+ let delete = if view.prepare.also.is_empty() { "Delete" } else { "Delete selected fields" };+ if ui.add_enabled(can_modify, egui::Button::new(tl!(delete))).clicked() {+ view.pending_edit = crate::prepare::delete_selected(view);+ ui.close();}- };- if fx.is_some() || fy.is_some() {- self.goto_point = Some((page, fx, fy, rel));+ return;}- }-- /// Next page (`true`) or previous page. In two-page view this moves a whole spread: the other- /// page of the spread is already on screen, so stepping to it wouldn't move the view (#70).- pub fn step_page(&mut self, forward: bool) {- let c = self.current;- let last = self.page_count.saturating_sub(1);- let (target, first) = match self.layout {- PageLayout::TwoUp => {- let first = self.spread_first(c);- let target = match (forward, self.cover && c == 0) {- (true, true) => 1,- (true, false) => first.saturating_add(2),- (false, _) if self.cover && first <= 1 => 0,- (false, _) => first.saturating_sub(2),- };- (target, first)+ if let Some((page, index)) = view.links.context {+ if ui.button(tl!("Properties…")).clicked() {+ view.links.open_existing = Some((page, index));+ ui.close();+ }+ if ui.add_enabled(can_modify, egui::Button::new(tl!("Delete"))).clicked() {+ view.pending_edit = Some(Edit::DeleteLink { page, index });+ view.links.selected = None;+ view.links.context = None;+ ui.close();+ }+ ui.separator();+ if ui.add_enabled(can_modify, egui::Button::new(tl!("Remove all links"))).clicked() {+ view.pending_edit = Some(Edit::RemoveLinks { pages: None });+ view.links.selected = None;+ view.links.context = None;+ ui.close();}- PageLayout::Single if forward => (c + 1, c),- PageLayout::Single => (c.saturating_sub(1), c),- };- // Past either end there is nowhere to go: stay put rather than re-align the view, which- // would scroll the page back to its top.- if if forward { target > last } else { first == 0 } {return;}- self.go_to_page(target);- }-- /// Page-editor focus and drafts belong to a document, even while another tab is active.- pub(crate) fn page_input_id(&self) -> egui::Id {- egui::Id::unique(("page-input", self.id.0))- }-- /// The idle page box and unchanged-input lookup share the same label fallback.- pub(crate) fn current_page_label(&self, label: Option<&str>) -> String {- label.filter(|l| !l.is_empty()).map(str::to_owned).unwrap_or_else(|| (self.current + 1).to_string())- }-- /// Retain the current page when `typed` exactly matches its displayed label, even if- /// another page has that label. Otherwise resolve a trimmed label (case-insensitive),- /// then a physical page number. `false` when it names no page.- pub fn go_to_typed(&mut self, typed: &str, labels: &[String]) -> bool {- // Compare the displayed value before trimming: a label may itself contain spaces.- // Repeated labels occur in restarted sections and prefix-only ranges.- if self.current < self.page_count && self.current_page_label(labels.get(self.current).map(String::as_str)) == typed {- return true;- }- let t = typed.trim();- let page = labels- .iter()- .position(|l| !l.is_empty() && l.eq_ignore_ascii_case(t))- .or_else(|| t.parse::<usize>().ok().filter(|n| *n >= 1).map(|n| n - 1));- match page {- Some(p) if p < self.page_count => {- self.go_to_page(p);- true+ if view.comments.selected.is_none() {+ let selected = view.selected_text().is_some_and(|t| !t.is_empty());+ let key = crate::commands::shortcut_label(ui.ctx(), crate::commands::COPY);+ if ui.add_enabled(can_copy && selected, egui::Button::new(tl!("Copy")).shortcut_text(key)).clicked() {+ copy_selected = true;+ ui.close();}- _ => false,+ ui.separator();}- }-- /// View ▸ Page navigation ▸ Previous view (`false`) / Next view (`true`).- pub fn view_history(&mut self, forward: bool) -> bool {- let has_target = if forward { !self.forward.is_empty() } else { !self.back.is_empty() };- if !has_target {- return false;+ // Over a picture (and no comment): Copy Image, as in Acrobat's page menu.+ let mut copy_image = None;+ if view.comments.selected.is_none()+ && let Some((page, at)) = view.comments.context_at+ {+ // The page's content is parsed once per right-click, not on every frame the menu is open.+ let key = egui::Id::unique("copy-image-under-menu");+ let cached = ui.data(|d| d.get_temp::<(usize, [f64; 2], Option<usize>)>(key)).filter(|c| c.0 == page && c.1 == at);+ let hit = match cached {+ Some(c) => c.2,+ None => {+ let hit = doc.page_image_at(page, at);+ ui.data_mut(|d| d.insert_temp(key, (page, at, hit)));+ hit+ }+ };+ if let Some(image) = hit {+ if ui.button(tl!("Copy Image")).clicked() {+ copy_image = Some(comments::CanvasAction::CopyImage(page, image));+ ui.close();+ }+ if ui.button(tl!("Copy Image in Original Format")).clicked() {+ copy_image = Some(comments::CanvasAction::CopyImageFile(page, image));+ ui.close();+ }+ ui.separator();+ }}- self.end_find_following();- let (from, to) = if forward { (&mut self.forward, &mut self.back) } else { (&mut self.back, &mut self.forward) };- let Some(page) = from.pop() else { return false };- to.push(self.current);- let page = page.min(self.page_count.saturating_sub(1));- self.goto = Some((page, 0.0));- self.current = page;- self.reset_coarse_state();- true- }+ canvas_action = comments::context_menu(ui, view, info, prefs, allowed, can_modify).or(copy_image);+ });+ *out = PageOut {- badge_hover,+ canvas_action,+ clicked_link,+ copy_selected,+ field_menu,+ field_placed,+ field_props,+ hover_text,+ image_action,+ open_boxes,+ open_initials,+ open_signature,+ open_table,+ primary_down: ptr.primary_down,+ refused,+ stamp_placed,+ };+ (wanted, visible_now)+ }- /// Select all: every page in Organize, or every word on the current page.- pub fn select_all(&mut self) -> bool {- if self.organize {- self.selected = (0..self.page_count).collect();- // Keep the current page as the anchor for the next Shift-click.- self.select_anchor = (self.page_count > 0).then_some(self.current);- return !self.selected.is_empty();- }- // Scrolling continuously, Select All takes the whole document's text (#2639); one page at- // a time, the page shown.- // 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.all_text = true;- return self.selected_text().is_some();- }- self.all_text = false;- let page = self.current;- let Some(t) = self.texts.get(&page) else { return false };- if t.glyphs.is_empty() {- return false;+ /// A zoom the fit mode changed keeps the page at the top of the view in place.+ fn anchor_zoom_change(view: &mut DocView, avail_width: f32, old_zoom: f32) {+ if view.shown && view.zoom_anchor.is_none() && view.goto.is_none() && view.goto_point.is_none() && (view.zoom - old_zoom).abs() > 1e-4 {+ let prev_viewport = view.viewport_screen;+ let top_y = prev_viewport.min.y;+ let anchor = view+ .screen_rects+ .iter()+ .find(|(_, r)| r.min.y <= top_y && r.max.y > top_y)+ .map(|(p, r)| {+ let fy = if r.height() > 0.0 { ((top_y - r.min.y) / r.height()).clamp(0.0, 1.0) } else { 0.0 };+ (*p, fy, 0.0f32)+ })+ .or_else(|| view.screen_rects.iter().find(|(_, r)| r.min.y >= top_y).map(|(p, r)| (*p, 0.0f32, (r.min.y - top_y).max(0.0))))+ .or_else(|| view.screen_rects.last().map(|(p, r)| (*p, 1.0f32, (r.max.y - top_y).max(0.0))));+ if let Some((page, fy, rel_y)) = anchor {+ view.zoom_anchor = Some((page, 0.5, fy, vec2(avail_width / 2.0, rel_y)));+ } else {+ view.zoom_anchor = Some((view.current, 0.5, 0.0, vec2(avail_width / 2.0, MARGIN)));}- self.selection = Some(Selection::run(page, 0, t.glyphs.len() - 1));- true- }-- /// Pages whose text [`DocView::whole_text`] still needs: not read yet, nor failed.- pub(crate) fn pages_without_text(&self) -> Vec<usize> {- (0..self.page_count).filter(|p| !self.texts.contains_key(p) && !self.text_failed.contains(p)).collect()}+ }- /// The whole document's text in page order, one page after another on new lines, from the- /// pages' text read so far and `more` (pages read for this, keyed by page).- pub(crate) fn whole_text(&self, more: &HashMap<usize, Arc<PageText>>) -> String {- let mut out = String::new();- for p in 0..self.page_count {- let Some(t) = self.texts.get(&p).or_else(|| more.get(&p)) else { continue };- let text = t.text_of(0..t.glyphs.len());- if text.is_empty() {- continue;- }- if !out.is_empty() {- out.push('\n');+ /// What the pager needs to know about the page row on screen.+ #[derive(Clone, Copy)]+ struct PagingCx<'a> {+ row: &'a [usize],+ rects: &'a [Rect],+ avail: Rect,+ middle_gesture: bool,+ unobstructed: bool,+ }++ /// Not scrolling: when the whole page or spread fits, the wheel turns pages instead. Returns whether+ /// paging owns the wheel, and whether it turned the page at an edge.+ fn single_page_paging(ui: &egui::Ui, view: &mut DocView, cx: &PagingCx<'_>) -> (bool, bool) {+ let (mut single_paging, mut edge_turned) = (false, false);+ let PagingCx { row, rects, avail, middle_gesture, unobstructed } = *cx;+ if !view.continuous {+ // The row's bounding box on screen (one page, or a two-page spread).+ let row_rect = row.iter().filter_map(|&i| rects.get(i)).copied().reduce(Rect::union);+ // Within a point, so layout rounding can't stop a fitting page from turning.+ let fits = row_rect.is_some_and(|r| r.height() + 2.0 * MARGIN <= avail.height() + 1.0);+ let can_turn = !middle_gesture && unobstructed && ui.rect_contains_pointer(avail);+ single_paging = can_turn && fits;+ // Every wheel event goes to the pager, so it follows each trackpad touch to its end+ // even while the page can't turn.+ ui.input(|i| {+ for e in &i.events {+ if let egui::Event::MouseWheel { unit, delta, phase, modifiers, .. } = e {+ // Zooming (⌘ or Ctrl) and sideways scrolling (Shift) never turn pages.+ let dy = if modifiers.command || modifiers.ctrl || modifiers.shift { 0.0 } else { delta.y };+ if fits {+ view.single_page_wheel(*unit, dy, *phase, i.time, can_turn);+ } else {+ edge_turned |= view.single_page_wheel_edge(*unit, dy, *phase, i.time, can_turn);+ }+ }}- out.push_str(&text);- }- out- }-- /// Rotate the view 90° clockwise or counter-clockwise (View ▸ Rotate View, ⇧⌘+ / ⇧⌘−).- pub fn rotate_view(&mut self, clockwise: bool) {- self.rotation = (self.rotation + if clockwise { 90 } else { 270 }) % 360;- self.goto = Some((self.current, 0.0));- self.reset_coarse_state();- }-- /// Switch the zoom mode, keeping the current page in view.- pub fn set_fit(&mut self, fit: Fit) {- self.fit = fit;- self.goto = Some((self.current, 0.0));- self.reset_coarse_state();- }-- /// Full screen, as Acrobat's Full Screen Mode (#379, #1459): one page at a time (or one- /// spread, when two-page view was on: #1353), fitted to the screen, from the current page.- /// The display it replaces is kept for [`Self::leave_presentation`]. A no-op while presenting.- pub fn enter_presentation(&mut self) {- if self.presentation.is_some() {- return;+ });+ if single_paging {+ // Paging owns vertical wheel motion here. A diagonal gesture keeps its sideways+ // part, as `ScrollArea` itself handles each axis.+ ui.input_mut(|i| i.smooth_scroll_delta.y = 0.0);}- self.presentation =- Some(SavedDisplay { layout: self.layout, continuous: self.continuous, cover: self.cover, fit: self.fit, zoom: self.zoom });- self.continuous = false;- self.fit = Fit::Page;- self.selection = None;- self.goto = Some((self.current, 0.0));- }-- /// Leave full screen: the display from before it comes back, at the page reached meanwhile.- pub fn leave_presentation(&mut self) {- let Some(saved) = self.presentation.take() else { return };- self.layout = saved.layout;- self.continuous = saved.continuous;- self.cover = saved.cover;- self.fit = saved.fit;- self.zoom = saved.zoom;- self.goto = Some((self.current, 0.0));}+ (single_paging, edge_turned)+ }- /// The display shown outside full screen: the one presenting replaced, or the current one.- pub fn normal_display(&self) -> SavedDisplay {- self.presentation.unwrap_or(SavedDisplay {- layout: self.layout,- continuous: self.continuous,- cover: self.cover,- fit: self.fit,- zoom: self.zoom,- })- }+ /// This frame's wheel motion over the page view, after paging and point/line suppression.+ struct Wheel {+ precise_scroll: Vec2,+ line_base: Vec2,+ boost_extra: Vec2,+ has_page: bool,+ /// The pager owns the vertical axis (single-page view, or the rest of a gesture that turned the page).+ paging_owns_vertical: bool,+ }- /// Whether the view is in full screen's one-page-at-a-time display.- pub fn presenting(&self) -> bool {- self.presentation.is_some()+ /// Point input bypasses egui smoothing for 1:1 motion. Line input keeps egui's configured, smoothed+ /// base and adds only the accelerated surplus. While point suppression is active, line and page+ /// input are reconstructed so current coarse events survive without exposing an older eased tail.+ fn read_wheel(ui: &mut egui::Ui, view: &mut DocView, avail: Rect, single_paging: bool, edge_turned: bool) -> Wheel {+ let now = ui.input(|i| i.time);+ let input = if ui.rect_contains_pointer(avail) {+ // Match the line distance used by egui's other scroll areas.+ let live = ui.ctx().options(|o| o.input_options.line_scroll_speed);+ let line_points = if live.is_finite() && live > 0.0 { live } else { crate::scroll_speed::EGUI_LINE_POINTS };+ ui.input(|i| crate::wheel_boost::accumulate(&i.events, line_points, single_paging))+ } else {+ crate::wheel_boost::FrameInput::default()+ };+ let mut precise_scroll = input.precise;+ let mut line_base = input.line;+ let mut boost_extra = crate::wheel_boost::boost_extra(input, &mut view.wheel_boost_x, &mut view.wheel_boost_y, now);+ let has_page = input.page != Vec2::ZERO;+ if now.is_finite() && precise_scroll != Vec2::ZERO && !has_page {+ view.precise_scroll_until = now + SUPPRESS_SECS;}-- /// Switch the base page display (Single or Two-page), leaving continuous scrolling as it is.- /// A no-op when the layout is already current, so re-selecting it never yanks a scrolled view- /// back to the top.- pub fn set_layout(&mut self, layout: PageLayout) {- if self.layout == layout {- return;- }- self.layout = layout;- self.goto = Some((self.current, 0.0));- self.reset_coarse_state();+ if edge_turned {+ // The turn leaves egui's eased copy of the notch to decay for a few frames; it must not+ // scroll the page just shown away from its top (or bottom).+ view.precise_scroll_until = now + 0.25;}-- /// Whether the view scrolls continuously (as opposed to one page or spread at a time).- pub fn continuous(&self) -> bool {- self.continuous+ // Paging owns the vertical axis in single-page view; leave it to the pager.+ // The rest of a gesture that turned the page is swallowed too, or it would pan the new page+ // away from the edge it was shown at.+ let paging_owns_vertical = single_paging || (!view.continuous && view.wheel.gesture_turned());+ if paging_owns_vertical {+ precise_scroll.y = 0.0;+ line_base.y = 0.0;+ boost_extra.y = 0.0;}-- /// Change page separation without editing the PDF or losing the reader's place.- pub fn set_page_gaps(&mut self, show: bool) {- if self.show_page_gaps == show {- return;+ // egui smooths a Point event that moved at least 8 points, keeping part of it for later+ // passes. Suppression must outlive that whole action: once it expired after a fixed 0.25 s,+ // the last few eased points leaked through the ScrollArea after a precise 1:1 scroll (held+ // point input measured 33 points for a 30-point event). Keep hiding the eased copy until+ // egui says the action is over, then forget the suppression.+ let scrolling = ui.input(|i| i.is_scrolling());+ if now < view.precise_scroll_until || (view.precise_scroll_until != 0.0 && scrolling) {+ if scrolling {+ // Keep hiding egui's unprocessed copy until it has drained. The short rolling grace+ // avoids a delayed duplicate without prolonging suppression after the tail is gone.+ view.precise_scroll_until = view.precise_scroll_until.max(now + SUPPRESS_TAIL_SECS);}- if !self.organize && self.viewport_screen.is_positive() {- let at = self.viewport_screen.center();- if let Some((page, r)) = self- .screen_rects- .iter()- .filter(|(_, r)| r.is_positive())- .min_by(|(_, a), (_, b)| a.distance_sq_to_pos(at).total_cmp(&b.distance_sq_to_pos(at)))- {- let fraction = (at - r.min) / r.size();- self.zoom_anchor = Some((*page, fraction.x, fraction.y, at - self.viewport_screen.min));+ ui.input_mut(|i| i.smooth_scroll_delta = Vec2::ZERO);+ // The point path suppresses every eased wheel delta. Restore the line base through the+ // same un-eased path as its surplus; paging-owned axes were cleared above.+ boost_extra = crate::wheel_boost::cap_frame(boost_extra + line_base);+ if has_page {+ // Page units normally stay on egui's viewport-sized path. During suppression only,+ // reproduce the current event directly so an older hidden tail stays hidden.+ let page_scale = ui.input(|i| i.viewport_rect().height());+ let mut page_delta =+ if page_scale.is_finite() && page_scale > 0.0 { crate::wheel_boost::cap_frame(input.page * page_scale) } else { Vec2::ZERO };+ if paging_owns_vertical {+ page_delta.y = 0.0;}+ boost_extra = crate::wheel_boost::cap_frame(boost_extra + page_delta);}- self.show_page_gaps = show;- }-- /// Separation between adjacent page rectangles, in logical screen points.- fn page_gap(&self) -> f32 {- if self.show_page_gaps { GAP } else { 0.0 }- }-- /// Turn continuous scrolling on or off, keeping the current page in view. A no-op when it is- /// already in that state.- pub fn set_continuous(&mut self, continuous: bool) {- if self.continuous != continuous {- self.continuous = continuous;- // Select All of the document belongs to continuous scrolling.- self.all_text = false;- self.goto = Some((self.current, 0.0));- self.reset_coarse_state();- }- }-- /// Set the whole page display at once (the base layout and continuous scrolling together),- /// as the control channel and settings do through a single [`display_token`].- pub fn set_display(&mut self, layout: PageLayout, continuous: bool) {- self.set_layout(layout);- self.set_continuous(continuous);- }-- /// Set the cover page in two-page view. A no-op unless something changed.- pub fn set_cover(&mut self, cover: bool) {- if self.cover != cover {- self.cover = cover;- self.goto = Some((self.current, 0.0));- self.reset_coarse_state();- }+ } else {+ precise_scroll = Vec2::ZERO;+ // Selection handling below uses zero to distinguish an inactive window. Clearing a past+ // deadline also keeps a later line/page action from being mistaken for the old tail.+ view.precise_scroll_until = 0.0;}-- /// Whether the cover page setting applies: only two-page view has a cover page.- pub fn cover_applies(&self) -> bool {- self.layout == PageLayout::TwoUp+ if has_page && paging_owns_vertical {+ // Page input belongs to egui on the free axis; the pager still owns vertical motion.+ ui.input_mut(|i| i.smooth_scroll_delta.y = 0.0);}+ Wheel { precise_scroll, line_base, boost_extra, has_page, paging_owns_vertical }+ }- /// One wheel event in a non-continuous view, where the wheel turns pages or spreads (the- /// rules are in `wheel_pager`): `dy` is its vertical delta (negative scrolls down) and `now`- /// is egui time. With `can_turn` false the gesture is followed but the page stays. Returns- /// whether the page turned.- pub fn single_page_wheel(&mut self, unit: egui::MouseWheelUnit, dy: f32, phase: egui::TouchPhase, now: f64, can_turn: bool) -> bool {- if self.continuous {- return false;- }- let Some(forward) = self.wheel.feed(unit, dy, phase, now, can_turn) else { return false };- let before = self.current;- self.step_page(forward);- self.current != before- }+ /// What decides which renders a frame asks for.+ #[derive(Clone, Copy)]+ struct RenderPlan<'a> {+ visible_pages: &'a [usize],+ tag: u64,+ scale: f32,+ sharp_held: bool,+ pan_held: bool,+ hand: bool,+ }- /// One wheel event in a non-continuous view whose page is taller than the window, where the- /// wheel pans (#1924). Once the view is at the bottom (top) edge, scrolling on turns to the- /// next (previous) page, which shows its top (bottom). A smooth gesture that panned the page- /// has to end first (see `WheelPager::feed_edge`). `can_turn` is false when something else- /// owns the wheel. Returns whether the page turned.- pub fn single_page_wheel_edge(&mut self, unit: egui::MouseWheelUnit, dy: f32, phase: egui::TouchPhase, now: f64, can_turn: bool) -> bool {- if self.continuous {- return false;- }- // Only an up-to-date view counts: the page drawn is the shown one, with no jump pending.- let edge = self.goto.is_none()- && self.goto_point.is_none()- && self.single_edges.is_some_and(|(page, top, bottom)| page == self.current && if dy < 0.0 { bottom } else { top });- let Some(forward) = self.wheel.feed_edge(unit, dy, phase, now, can_turn && edge) else { return false };- let before = self.current;- self.step_page(forward);- if self.current == before {- return false;- }- if !forward {- // Going back lands on the bottom of the previous page.- self.goto = Some((self.current, 1.0));+ /// Queues the renders for the pages and tiles `renders` wants (nearest the view first), prefetches the+ /// rows either side, frees tiles of far pages and old zooms, and asks for the text layers.+ fn plan_renders(ui: &egui::Ui, view: &mut DocView, info: &DocInfo, renders: PageRenders, plan: &RenderPlan<'_>) {+ let (mut wanted, visible_now) = renders;+ let RenderPlan { visible_pages, tag, scale, sharp_held, pan_held, hand } = *plan;+ // Single-page and two-page views draw only the current row, so the next one was first asked+ // for on the turn and showed blank paper until it rendered. Prefetch the rows either side,+ // as continuous scrolling does for the pages just off screen.+ if !view.continuous+ && let (Some(&first), Some(&last)) = (visible_pages.first(), visible_pages.last())+ {+ let n = if view.layout == PageLayout::Single { 1 } else { 2 };+ let max_side = ui.ctx().input(|inp| inp.max_texture_side) as f32;+ for i in (last.saturating_add(1)..=last.saturating_add(n)).chain(first.saturating_sub(n)..first) {+ let Some(p) = info.pages.get(i).filter(|_| !view.errors.contains_key(&i)) else { continue };+ // As drawn: the whole page at this scale, or the backdrop of a tiled page.+ let side = p.width.max(p.height).max(1.0);+ wanted.push(if side * scale > TILE_THRESHOLD.min(max_side) {+ let bs = BASE_SIDE.min(max_side) / side;+ (i, bs, scale_tag(bs), None)+ } else {+ (i, scale, tag, None)+ });}- self.single_edges = None;- true- }-- /// Displayed page size in points for this view rotation.- fn display_size(&self, p: &pdfcraft_render::PageInfo) -> (f32, f32) {- if self.rotation % 180 == 90 { (p.height, p.width) } else { (p.width, p.height) }- }-- /// Marquee Zoom: zoom so `r` (on screen) fills the window, centred.- pub fn zoom_to_rect(&mut self, r: Rect) {- let Some((page, pr)) = self.screen_rects.iter().find(|(_, pr)| pr.contains(r.center())).copied() else { return };- let k = (self.viewport_screen.width() / r.width().max(1.0)).min(self.viewport_screen.height() / r.height().max(1.0));- let f = (r.center() - pr.min) / pr.size();- self.zoom = (self.zoom * k).clamp(0.08, 64.0);- self.fit = Fit::None;- self.zoom_anchor = Some((page, f.x.clamp(0.0, 1.0), f.y.clamp(0.0, 1.0), self.viewport_screen.center() - self.viewport_screen.min));- }-- /// View ▸ Zoom ▸ Fit Visible: zoom so the visible content of `page` (display-normalised- /// [x0, y0, x1, y1], i.e. after view rotation) spans the window's width, its left edge at- /// the window's left and its top at the top.- pub fn fit_content(&mut self, page: usize, content: [f32; 4]) -> bool {- const PAD: f32 = 16.0;- let Some((_, pr)) = self.screen_rects.iter().find(|(p, _)| *p == page).copied() else { return false };- let w = (content[2] - content[0]).max(0.01) * pr.width();- let k = (self.viewport_screen.width() - 2.0 * PAD).max(50.0) / w.max(1.0);- self.zoom = (self.zoom * k).clamp(0.08, 64.0);- self.fit = Fit::None;- self.zoom_anchor = Some((page, content[0].clamp(0.0, 1.0), content[1].clamp(0.0, 1.0), vec2(PAD, MARGIN)));- true- }-- /// How large the page grid draws its pages (1.0 = the usual thumbnails).- pub fn grid_zoom(&self) -> f32 {- self.grid_zoom}-- /// Scale of the thumbnails in the Pages inspector (1.0 is the usual size).- pub fn thumbnail_zoom(&self) -> f32 {- self.thumbnail_zoom- }-- /// Resize the inspector thumbnails, keeping the current page in view after layout.- /// Out-of-range values are clamped; non-finite values are ignored.- pub fn set_thumbnail_zoom(&mut self, zoom: f32) {- if zoom.is_finite() {- let zoom = zoom.clamp(*THUMBNAIL_ZOOM_RANGE.start(), *THUMBNAIL_ZOOM_RANGE.end());- if zoom != self.thumbnail_zoom {- self.thumbnail_zoom = zoom;- self.panel_followed = None;- }- }- }-- /// Zoom the page grid; out-of-range values are clamped and nonsense is ignored.- pub fn set_grid_zoom(&mut self, zoom: f32) {- if zoom.is_finite() {- self.grid_zoom = zoom.clamp(*GRID_ZOOM_RANGE.start(), *GRID_ZOOM_RANGE.end());- }- }-- /// How many device pixels wide the grid's sharp render of `page` is, if it has one.- pub fn grid_page_pixels(&self, page: usize) -> Option<u32> {- self.grid_pages.get(&page).map(|(w, _)| *w)- }-- /// Zoom keeping the centre of the view still.- pub fn set_zoom(&mut self, zoom: f32) {- // CLI/view options can set zoom before the first layout. Rect::NOTHING has no- // finite centre yet, but an initial zoom still needs to leave the default fit mode.- let centre = if self.viewport_screen.is_positive() { self.viewport_screen.center() } else { Pos2::ZERO };- self.zoom_at(zoom, centre);- }-- /// Zoom keeping the document point under `screen_pos` still (pinch, ⌘-scroll).- pub fn zoom_at(&mut self, zoom: f32, screen_pos: Pos2) {- if !zoom.is_finite() || !screen_pos.is_finite() {- return;- }- let zoom = zoom.clamp(0.08, 64.0);- if zoom == self.zoom && self.fit == Fit::None {- return;- }- // In gutters/gaps, anchor relative to the nearest page rather than jumping to its top.- // Fractions outside 0..1 preserve the pointer's position outside the page as well.- let anchor =- self.screen_rects.iter().min_by(|(_, a), (_, b)| a.distance_sq_to_pos(screen_pos).total_cmp(&b.distance_sq_to_pos(screen_pos))).map(- |(p, r)| {- let f = (screen_pos - r.min) / r.size();- (*p, f.x, f.y, screen_pos - self.viewport_screen.min)- },- );- self.zoom = zoom;- self.fit = Fit::None;- match anchor {- Some(a) => self.zoom_anchor = Some(a),- // Nothing on screen yet (e.g. a launch option): align the current page instead.- None => self.goto = Some((self.current, 0.0)),- }- }-- /// A zoom typed as a percentage ("150", "150%", " 62.5 % ") as a zoom factor; `None` unless it is a- /// finite, positive number. `set_zoom` clamps it to the supported range.- pub fn parse_zoom_percent(typed: &str) -> Option<f32> {- let percent = typed.trim().trim_end_matches('%').trim_end().parse::<f32>().ok()?;- (percent.is_finite() && percent > 0.0).then_some(percent / 100.0)- }-- /// Standard zoom steps (as in Acrobat's zoom menu).- pub fn zoom_step(&mut self, up: bool) {- const STEPS: [f32; 17] = [0.1, 0.25, 0.33, 0.5, 0.66, 0.75, 1.0, 1.25, 1.5, 2.0, 3.0, 4.0, 6.0, 8.0, 12.0, 16.0, 32.0];- let z = self.zoom;- let next = if up { STEPS.iter().copied().find(|s| *s > z * 1.01) } else { STEPS.iter().rev().copied().find(|s| *s < z * 0.99) };- if let Some(n) = next {- self.set_zoom(n);- }- }-- /// Start collecting demand from every consumer before scheduling or uploading results.- pub(crate) fn begin_render_frame(&mut self) {- self.frame_geometry_changed = false;- self.pages_panel = None;- self.panel_gap = None;- self.thumb_demand.clear();- self.frame_queue.clear();- self.frame_visible.clear();- }-- pub(crate) fn need_thumbnail(&mut self, page: usize, visible: bool) {- if page >= self.page_count {- return;- }- if let Some(priority) = self.thumb_demand.get_mut(&page) {- *priority |= visible;- } else if self.thumb_demand.len() < MAX_THUMB_DEMAND {- self.thumb_demand.insert(page, visible);- } else if visible && let Some(prefetch) = self.thumb_demand.iter().find_map(|(&p, &v)| (!v).then_some(p)) {- self.thumb_demand.remove(&prefetch);- self.thumb_demand.insert(page, true);- }- }-- /// Only the displayed document owns raster textures. Tabs keep their document and view- /// state, but do not each retain a separate full application texture allowance.- pub(crate) fn suspend_rendering(&mut self, pool: &RenderPool) {- self.begin_render_frame();- self.pages.clear();- self.tiles.clear();- self.thumbs.clear();- self.grid_pages.clear();- self.print_pages.clear();- self.stale_thumbs.clear();- self.stale_tiles.clear();- self.waiting_since.clear();- // Signature previews own a separate renderer and image/background textures.- self.signature_drag = Default::default();- self.text_background = Default::default();- self.move_background = Default::default();- if !self.last_queue.is_empty() {- pool.set_queue(Vec::new());- self.last_queue.clear();- }- // Results already finished for this tab would otherwise sit in its pool, rasters and- // all, until the tab is shown again. (An inline pool renders inside try_recv: skip it.)- if !pool.is_inline() {- while pool.try_recv().is_some() {}- }- }-- fn thumbnail_requests(&self, info: &DocInfo, ppp: f32) -> Vec<RenderRequest> {- let mut pages: Vec<_> = self.thumb_demand.iter().map(|(&p, &visible)| (p, visible)).collect();- pages.sort_unstable_by_key(|&(p, visible)| (!visible, p));- // At high DPI or in a very large viewport every demanded cell still fits the same- // byte allowance. Both dimensions are capped, including tall/wide page boxes.- // The count is rounded up to a power of two: the scale is part of each request's tag,- // so a density that followed every row scrolling in or out would re-render them all.- let density = thumbnail_density(pages.len(), ppp);- pages- .into_iter()- .filter_map(|(page, _)| {- let p = info.pages.get(page)?;- let scale = thumbnail_scale(p.width, p.height, density);- Some(RenderRequest {- page,- kind: RequestKind::Pixels,- tile: None,- scale,- tag: THUMB_TAG | u64::from(scale.to_bits()),- // Thumbnails are previews: tiny images are skipped for them.- preview: true,- })- })- .collect()- }-- /// Admit current demand within explicit byte limits. Cached and pending surfaces share- /// the allowance, so an evicted page can be requested again without a permanent done set.- fn prepare_render_queue(&mut self, info: &DocInfo, ppp: f32) -> Vec<RenderRequest> {- let requests = std::mem::take(&mut self.frame_queue);- let mut queue = Vec::new();- let mut pages = HashSet::new();- let mut tiles = HashSet::new();- let mut tile_tags = HashSet::new();- let mut grid = Vec::new();- let (mut page_bytes, mut tile_bytes) = (0usize, 0usize);- for req in requests.iter().filter(|r| r.kind == RequestKind::Pixels) {- let Some(p) = info.pages.get(req.page) else { continue };- // Organize-grid renders: only the cells in view that need one (organize_grid).- if req.tag & GRID_TAG != 0 {- grid.push(*req);- continue;- }- // Print-preview rasters: a few sheets at the pane's size (the dialog bounds them).- if req.tag & PRINT_TAG != 0 {- if !self.errors.contains_key(&req.page) {- queue.push(*req);- }- continue;- }- // On-screen work is always admitted (the viewport bounds it); the limits only- // decide how much prefetch fits beside it.- let visible = self.frame_visible.contains(&req.page);- if let Some(tile) = req.tile {- // Keyed by exact device-pixel origin: the tile side varies with the zoom- // (`tile_side`), so grid indices would need the scale to decode.- let key = (req.page, req.tag, tile.x, tile.y);- let bytes = rgba_bytes(tile.w as usize, tile.h as usize);- if (!visible && tile_bytes.saturating_add(bytes) > TILE_BYTES) || !tiles.insert(key) {- continue;- }- tile_bytes = tile_bytes.saturating_add(bytes);- tile_tags.insert(req.tag);- if !self.tiles.contains_key(&key) || self.stale_tiles.contains(&key) {- queue.push(*req);- }- } else {- let bytes = rgba_bytes(device_pixels(p.width, req.scale) as usize, device_pixels(p.height, req.scale) as usize);- if (!visible && (page_bytes.saturating_add(bytes) > PAGE_BYTES || pages.len() >= MAX_CACHED_PAGES)) || !pages.insert(req.page) {- continue;- }- page_bytes = page_bytes.saturating_add(bytes);- if self.pages.get(&req.page).is_none_or(|p| p.tag != req.tag) {- queue.push(*req);- }- }- }- // Pages no longer demanded stay cached while the allowance has room, nearest to the- // current page first, so turning back a page shows it at once instead of rendering.- let mut undemanded: Vec<usize> = self.pages.keys().copied().filter(|p| !pages.contains(p)).collect();- undemanded.sort_by_key(|p| p.abs_diff(self.current));- let mut kept = pages.len();- for page in undemanded {- let bytes = self.pages.get(&page).map_or(0, |p| texture_bytes(&p.tex));- if kept < MAX_CACHED_PAGES && page_bytes.saturating_add(bytes) <= PAGE_BYTES {- page_bytes = page_bytes.saturating_add(bytes);- kept += 1;- pages.insert(page);- }- }- self.pages.retain(|p, _| pages.contains(p));- // Tiles of an earlier zoom (not a demanded scale) stay while the canvas keeps them, a- // bounded few under a page whose current tiles are still missing (OLD_TILES). Tiles of a- // page on screen stay too even when this frame does not demand them (#2196): the viewport- // moves while zooming, so a tile that was sharp a moment ago falls outside the demanded- // rectangle, and dropping it made every pan or zoom back a cold miss that re-blurred the- // page and re-interpreted it once per tile. The per-frame cap below (OLD_TILES,- // nearest scale first) is what bounds how much of that stays.- self.tiles.retain(|key, _| tiles.contains(key) || !tile_tags.contains(&key.1) || self.frame_visible.contains(&key.0));- self.stale_tiles.retain(|key| self.tiles.contains_key(key));- queue.extend(grid);- // Opening (or turning to) a page queues its pixels alongside thumbnails and- // text extraction. The workers would otherwise spend the first seconds on- // thumbnails and search text while the visible page stays blank: hold those- // until no visible main-page raster is still missing. Errored pages never- // block: they are never re-requested.- let visible_mains_pending = queue.iter().any(|r| {- r.kind == RequestKind::Pixels- && r.tag & (GRID_TAG | PRINT_TAG | THUMB_TAG | TEXT_TAG) == 0- && self.frame_visible.contains(&r.page)- && !self.errors.contains_key(&r.page)- });- if visible_mains_pending {- // Caches are kept; demand is re-evaluated next frame once pixels arrive.- return queue;- }- let thumbs = self.thumbnail_requests(info, ppp);- let mut thumb_bytes = 0usize;- let mut admitted = HashSet::new();- for req in thumbs {- let Some(p) = info.pages.get(req.page) else { continue };- let bytes = rgba_bytes(device_pixels(p.width, req.scale) as usize, device_pixels(p.height, req.scale) as usize);- if thumb_bytes.saturating_add(bytes) > THUMB_BYTES || self.errors.contains_key(&req.page) {- continue;- }- thumb_bytes += bytes;- admitted.insert(req.page);- if self.thumbs.get(&req.page).is_none_or(|t| t.tag != req.tag) || self.stale_thumbs.contains(&req.page) {- queue.push(req);- }- }- self.thumbs.retain(|p, _| admitted.contains(p));- self.stale_thumbs.retain(|p| admitted.contains(p));- self.retain_text_layers();- // Visible main pages and thumbnails take precedence over background search work.- queue.extend(requests.into_iter().filter(|r| r.kind == RequestKind::Text));- queue- }-- /// Drop text layers nothing can still need. Every visited page's text used to stay- /// cached for the session. Keep visible, selected and matched pages plus the nearest- /// prefetch window; evicted pages re-extract on revisit. (Count window only: unlike- /// rasters there is no byte budget here.) While a search is active keep everything:- /// demand still wants every page, so evicting would re-request evicted pages each- /// frame and churn the workers. Failures are never evicted either: they cost nothing- /// to remember, and evicting one would re-request and re-fail it every frame.- fn retain_text_layers(&mut self) {- if self.texts.len() <= MAX_CACHED_TEXT_PAGES {- return;- }- if self.find.as_ref().is_some_and(|f| !f.case_query.trim().is_empty()) {- return;- }- let mut keep: HashSet<usize> = self.frame_visible.clone();- if let Some(s) = self.selection {- keep.insert(s.page);- }- if let Some(f) = self.find.as_ref() {- keep.extend(f.matches.iter().map(|(p, _)| *p));- }- let mut rest: Vec<usize> = self.texts.keys().filter(|p| !keep.contains(*p)).copied().collect();- rest.sort_by_key(|p| p.abs_diff(self.current));- keep.extend(rest.into_iter().take(MAX_CACHED_TEXT_PAGES));- self.texts.retain(|p, _| keep.contains(p));- }-- pub(crate) fn finish_render_frame(&mut self, ctx: &egui::Context, info: &DocInfo, pool: &RenderPool) {- if self.frame_geometry_changed {- // Dialogs and edits can replace pages after the canvas collected demand. Its- // scales and indexes belong to the old pages, not to the new renderer (#3149).- self.begin_render_frame();- self.last_queue.clear();- pool.set_queue(Vec::new());- ctx.request_repaint();- return;- }- let queue = self.prepare_render_queue(info, ctx.pixels_per_point());- if queue != self.last_queue {- pool.set_queue(queue.clone());- self.last_queue = queue;- }- if !self.hold_rasters {- self.receive(ctx, pool);- }- if !self.last_queue.is_empty() {- ctx.request_repaint_after(std::time::Duration::from_millis(30));- }- }-- /// Pull a bounded batch of current results into textures. Demand is committed first, so- /// offscreen results and obsolete scale/configuration tags never allocate a ColorImage.- pub fn receive(&mut self, ctx: &egui::Context, pool: &RenderPool) {- let budget = if pool.is_inline() { 1 } else { RESULTS_PER_FRAME };- let mut uploaded = 0usize;- #[cfg(not(target_arch = "wasm32"))]- let started = std::time::Instant::now();- for _ in 0..budget {- let Some(r) = pool.try_recv() else { break };- uploaded = uploaded.saturating_add(self.receive_result(ctx, r));- // One whole-page upload may exceed the frame allowance; it must still progress.- if uploaded >= UPLOAD_BYTES_PER_FRAME {- break;- }- #[cfg(not(target_arch = "wasm32"))]- if started.elapsed() >= std::time::Duration::from_millis(4) {- break;- }- }- }-- fn receive_result(&mut self, ctx: &egui::Context, r: pdfcraft_render::RenderedPage) -> usize {- if !self.last_queue.contains(&r.request) {- return 0;- }- ctx.request_repaint();- if r.request.kind == RequestKind::Text {- match r.text {- Some(t) => {- self.texts.insert(r.request.page, t);- self.refresh_find_page(r.request.page);- }- None => {- log::warn!("page {} text: {}", r.request.page + 1, r.error.unwrap_or_default());- self.text_failed.insert(r.request.page);- if let Some(f) = self.find.as_mut() {- let previous = f.current.and_then(|c| f.matches.get(c).cloned());- let follow = f.follow_page(self.current);- f.matches.retain(|(p, _)| *p != r.request.page);- match follow {- // An automatic choice keeps following its anchor; a failure never- // flashes, so the view stays exactly where it was.- Follow::Active(from) => f.current = f.first_at_or_after(from),- Follow::Ended | Follow::Never => {- let preserved = previous.as_ref().and_then(|k| f.matches.iter().position(|m| m == k));- f.current = preserved.or_else(|| f.first_at_or_after(self.current));- }- }- }- }- }- return 0;- }- if let Some(e) = r.error {- log::warn!("page {}: {e}", r.request.page + 1);- self.errors.insert(r.request.page, e);- return 0;- }- // Even current demand may have been sized with obsolete geometry or a different- // device limit. Check before cache eviction, conversion and every upload path.- let max_side = ctx.input(|i| i.max_texture_side);- if r.width == 0 || r.height == 0 || r.width as usize > max_side || r.height as usize > max_side {- return 0;- }- // Remember heavy pages: only these get the zoom/pan settle holds, so fast pages- // never pay added latency. Stale entries die with the tiles on edits.- if r.millis >= SLOW_MILLIS {- self.slow_pages.insert(r.request.page);- }- let page = r.request.page;- let bytes = rgba_bytes(r.width as usize, r.height as usize);- if bytes != r.rgba.len() || !self.admit_texture(r.request, bytes) {- return 0;- }- // The length was checked above, so the renderer's buffer becomes the texture data as is.- let img = texture_image([r.width as usize, r.height as usize], r.rgba);- if let Some(t) = r.request.tile {- let key = (page, r.request.tag, t.x, t.y);- let tex = ctx.load_texture(format!("tile-{:?}-{page}-{}-{}", self.id, t.x, t.y), img, TextureOptions::LINEAR);- self.tiles.insert(key, tex);- self.stale_tiles.remove(&key);- if !self.stale_tiles.iter().any(|k| k.0 == page) {- self.forms.unbaked.retain(|(_, p)| *p != page);- self.comments.page_rendered(page);- }- if !self.page_out_of_date(page) {- self.text_background.page_received(page);- }- } else if r.request.tag & PRINT_TAG != 0 {- let tex = ctx.load_texture(- format!("print-{:?}-{page}", self.id),- if r.request.tag & GRAYSCALE_TAG != 0 { grayscale(img) } else { img },- TextureOptions::LINEAR,- );- self.print_pages.insert(page, (r.request.tag, tex));- } else if r.request.tag & GRID_TAG != 0 {- let tex = ctx.load_texture(format!("grid-{:?}-{page}", self.id), img, TextureOptions::LINEAR);- self.grid_pages.insert(page, (r.width, tex));- } else if r.request.tag & THUMB_TAG != 0 {- let tex = ctx.load_texture(format!("thumb-{:?}-{page}", self.id), img, TextureOptions::LINEAR);- self.thumbs.insert(page, PageTex { tag: r.request.tag, tex });- self.stale_thumbs.remove(&page);- } else {- let tex = ctx.load_texture(format!("page-{:?}-{page}", self.id), img, TextureOptions::LINEAR);- self.pages.insert(page, PageTex { tag: r.request.tag, tex });- self.signature_drag.page_received(page);- self.move_background.page_received(page);- if !self.page_out_of_date(page) {- self.text_background.page_received(page);- }- self.comments.page_rendered(page);- self.waiting_since.remove(&page);- if !self.stale_tiles.iter().any(|k| k.0 == page) {- self.forms.unbaked.retain(|(_, p)| *p != page);- }- }- bytes- }-- /// Check real dimensions before conversion, including stale textures kept during edits.- /// Dropping an old handle releases its backend allocation after the current frame.- fn admit_texture(&mut self, req: RenderRequest, bytes: usize) -> bool {- // An on-screen page or tile is always taken (the viewport bounds it): it may evict- // off-screen rasters but never another on-screen one, and is never refused.- let visible = req.tag & THUMB_TAG == 0 && self.frame_visible.contains(&req.page);- // Organize-grid renders are bounded by the cells in view (organize_grid). Print- // previews are the sheets around the one on screen.- if req.tag & (GRID_TAG | PRINT_TAG) != 0 {- return true;- }- if let Some(t) = req.tile {- let key = (req.page, req.tag, t.x, t.y);- self.tiles.remove(&key);- let retained = self.tiles.values().fold(0usize, |n, tex| n.saturating_add(texture_bytes(tex)));- visible || bytes <= TILE_BYTES.saturating_sub(retained)- } else {- let thumb = req.tag & THUMB_TAG != 0;- let (cache, limit) = if thumb { (&mut self.thumbs, THUMB_BYTES) } else { (&mut self.pages, PAGE_BYTES) };- cache.remove(&req.page);- let mut retained = cache.values().fold(0usize, |n, p| n.saturating_add(texture_bytes(&p.tex)));- // A zoom/DPI change can temporarily retain larger stale images than the new- // demand estimates. Evict those first, then let the current demand refill them.- let on_screen = |p: &usize| !thumb && self.frame_visible.contains(p);- while retained.saturating_add(bytes) > limit {- let Some(page) = cache.keys().copied().filter(|p| !on_screen(p)).max_by_key(|p| p.abs_diff(self.current)) else { break };- if let Some(old) = cache.remove(&page) {- retained = retained.saturating_sub(texture_bytes(&old.tex));- }- }- visible || bytes <= limit.saturating_sub(retained)- }- }-- /// The first page of the two-page spread page `c` is in: spreads are [0, 1], [2, 3], … or,- /// with a cover page, [0], [1, 2], [3, 4], ….- fn spread_first(&self, c: usize) -> usize {- if self.cover { c.saturating_sub((c + 1) % 2) } else { c - c % 2 }- }-- fn fit_zoom(&mut self, info: &DocInfo) {- let largest = |side: fn((f32, f32)) -> f32| info.pages.iter().map(|p| side(self.display_size(p))).fold(1.0, f32::max);- let max_w = largest(|s| s.0);- // A single page shown on its own fits that page, and full screen in two-page view fits- // the spread it shows (review on #2070). Every other display (scrolling, or two-page- // view in the window) fits its largest page, so the zoom holds still while pages of- // other sizes scroll or page past.- let (w, h) = if self.layout == PageLayout::Single && !self.continuous {- info.pages.get(self.current).map_or_else(|| (max_w, largest(|s| s.1)), |p| self.display_size(p))- } else if self.presentation.is_some() && self.layout == PageLayout::TwoUp && !self.continuous {- let first = self.spread_first(self.current);- let last = if self.cover && first == 0 { 0 } else { first.saturating_add(1) };- let spread: Vec<(f32, f32)> = info.pages.iter().skip(first).take(last - first + 1).map(|p| self.display_size(p)).collect();- if spread.is_empty() {- (max_w, largest(|s| s.1))- } else {- (spread.iter().map(|s| s.0).fold(1.0, f32::max), spread.iter().map(|s| s.1).fold(1.0, f32::max))- }- } else {- (max_w, largest(|s| s.1))- };- let avail_w = (self.viewport_w - 2.0 * SIDE).max(100.0);- let per_row = if self.layout == PageLayout::TwoUp { 2.0 } else { 1.0 };- match self.fit {- Fit::Width => self.zoom = (avail_w - self.page_gap() * (per_row - 1.0)) / (w * PT * per_row),- Fit::Page => {- let zw = (avail_w - self.page_gap() * (per_row - 1.0)) / (w * PT * per_row);- let zh = (self.viewport_h - 2.0 * MARGIN) / (h * PT);- self.zoom = zw.min(zh);- }- Fit::Height => self.zoom = (self.viewport_h - 2.0 * MARGIN) / (h * PT),- Fit::None => {}- }- self.zoom = self.zoom.clamp(0.08, 64.0);- }-- /// Width of the scroll content. Single-page view sizes it to the page it shows, so a- /// wider page elsewhere in the document can't push the shown one off-centre.- fn content_width(&self, info: &DocInfo, avail_w: f32) -> f32 {- let single = (self.layout == PageLayout::Single && !self.continuous).then(|| self.current.min(info.pages.len().saturating_sub(1)));- let shown = info.pages.iter().enumerate().filter(|&(i, _)| single.is_none_or(|c| c == i));- let max_w = shown.map(|(_, p)| self.display_size(p).0).fold(0.0, f32::max);- let per_row = if self.layout == PageLayout::TwoUp { 2.0 } else { 1.0 };- (max_w * self.zoom * PT * per_row + 2.0 * SIDE).max(avail_w)- }-- /// Page rects in content coordinates (origin at the scroll content's top-left).- fn layout(&self, info: &DocInfo, content_w: f32, ppp: f32) -> Vec<Rect> {- let s = self.zoom * PT;- let gap = self.page_gap();- let page_size = |p: &pdfcraft_render::PageInfo| {- let (w, h) = self.display_size(p);- if self.show_page_gaps {- vec2(w * s, h * s)- } else {- // Match the raster's whole physical pixels. Snapping each page's origin- // independently with fractional sizes would leave hairline seams.- vec2(device_pixels(w, s * ppp) as f32 / ppp, device_pixels(h, s * ppp) as f32 / ppp)- }- };- let mut rects = Vec::with_capacity(info.pages.len());- let mut y = MARGIN;- match self.layout {- PageLayout::Single => {- for p in &info.pages {- let size = page_size(p);- rects.push(Rect::from_min_size(pos2(((content_w - size.x) / 2.0).max(SIDE), y), size));- y += size.y + gap;- }- }- PageLayout::TwoUp => {- // With a cover page, the first page sits alone on the right.- let rows: Vec<&[pdfcraft_render::PageInfo]> = if self.cover && !info.pages.is_empty() {- std::iter::once(&info.pages[..1]).chain(info.pages[1..].chunks(2)).collect()- } else {- info.pages.chunks(2).collect()- };- for (ri, pair) in rows.into_iter().enumerate() {- let sizes: Vec<Vec2> = pair.iter().map(page_size).collect();- let row_w: f32 = sizes.iter().map(|v| v.x).sum::<f32>() + gap * (sizes.len() as f32 - 1.0);- let row_h = sizes.iter().map(|v| v.y).fold(0.0, f32::max);- let mut x = if self.cover && ri == 0 { (content_w / 2.0 + gap / 2.0).max(SIDE) } else { ((content_w - row_w) / 2.0).max(SIDE) };- for size in sizes {- rects.push(Rect::from_min_size(pos2(x, y + (row_h - size.y) / 2.0), size));- x += size.x + gap;- }- y += row_h + gap;- }- }- }- rects- }-- fn render_scale(&self, ppp: f32) -> f32 {- // Exactly the device scale: a raster at any other scale is resampled on screen, which- // blurs every line and glyph (#260).- self.zoom * PT * ppp- }-- /// Set whether the print preview rasters become luminance before upload. Toggling it drops- /// the colour previews: new requests carry the grayscale tag, so stale ones are replaced.- pub(crate) fn set_print_grayscale(&mut self, grayscale: bool) {- if self.grayscale != grayscale {- self.grayscale = grayscale;- self.print_pages.clear();- }- }-- /// Queue sharp rasters for the print preview. Pages that leave the nearby sheets are dropped.- /// Previews render with reading colours off (the request's tag tells the renderer): they must- /// match the printout, which is imposed from the uncoloured document.- pub(crate) fn queue_print_previews(&mut self, pages: &[(usize, f32)]) {- self.print_pages.retain(|page, _| pages.iter().any(|(p, _)| p == page));- for &(page, scale) in pages {- if self.errors.contains_key(&page) || !scale.is_finite() || scale <= 0.0 {- continue;- }- let tag = scale_tag(scale) | PRINT_TAG | if self.grayscale { GRAYSCALE_TAG } else { 0 };- let fresh = self.print_pages.get(&page).is_some_and(|(have, _)| *have == tag);- if !fresh {- self.frame_queue.push(RenderRequest { page, kind: RequestKind::Pixels, tile: None, scale, tag, preview: false });- }- }- }- }-- /// The scroll offset that puts `point` (content coordinates) at `rel` in the viewport, kept within- /// the content as egui keeps it. egui clamps only after drawing, so an offset past the end showed- /// the page misplaced for a frame and then jumped (zooming out beside a page that fits).- fn anchored_scroll(point: Pos2, rel: Vec2, content: Vec2, viewport: Vec2) -> Vec2 {- let max = vec2((content.x - viewport.x).max(0.0), (content.y - viewport.y).max(0.0));- vec2((point.x - rel.x).clamp(0.0, max.x), (point.y - rel.y).clamp(0.0, max.y))- }-- /// The request tag for a raster at `scale`: equal tags mean the same scale (to 1/65536).- fn scale_tag(scale: f32) -> u64 {- (f64::from(scale) * 65536.0).round() as u64- }-- /// The scale of a raster tagged by [`scale_tag`].- fn tag_scale(tag: u64) -> f32 {- (tag as f64 / 65536.0) as f32- }-- /// Device-pixel side of a page tile at `scale` for a page `page_max_px` device pixels on- /// its long side. Each tile costs a full page interpret, so tiles grow with the zoom and- /// with the page: a zoomed viewport, or a giant sheet shown whole, is covered by a few- /// large tiles instead of dozens of small ones. Bounded by the render backend (tile sides- /// above 4096 are clamped there) and kept granular at ordinary zooms.- fn tile_side(scale: f32, page_max_px: u32) -> u32 {- if !scale.is_finite() || scale <= 0.0 {- return TILE;- }- let by_zoom = (TILE as f32 * (scale / 6.0)).clamp(TILE as f32, 4096.0) as u32;- // At most four tiles along the long side, so a giant sheet needs a handful of- // interprets instead of dozens.- by_zoom.max(page_max_px.div_ceil(4).min(4096))- }-- /// Tiles of earlier zooms kept for a page while its current tiles are rendered.- const OLD_TILES: usize = 64;-- /// A page whose raster took at least this long is heavy: zoom/pan holds apply to it,- /// so gestures stay on stretched surfaces instead of queueing full-page interprets.- const SLOW_MILLIS: u32 = 500;-- /// `r` moved so its corner lies on a whole physical pixel, so that a raster drawn from there- /// maps texel for texel onto the screen.- fn snap_to_pixels(r: Rect, ppp: f32) -> Rect {- let snap = |v: f32| (v * ppp).round() / ppp;- Rect::from_min_size(pos2(snap(r.min.x), snap(r.min.y)), r.size())- }-- /// Maps between a page's coordinate spaces and the screen, including view rotation.- ///- /// *View space* is the page as rendered (points, y down, the document's own `/Rotate` applied);- /// normalised page coordinates `(u, v)` are view space divided by the page size. The view- /// rotation (View ▸ Rotate View) turns the page clockwise on screen by `rot` degrees.- #[derive(Clone, Copy)]- pub struct PageXform {- /// The page's rectangle on screen (already rotated, so width/height may be swapped).- pub rect: Rect,- pub rot: u16,- /// Page size in view space (unrotated by the view).- pub pw: f32,- pub ph: f32,- }-- impl PageXform {- /// Screen pixels per page point. The view's rotation swaps the rectangle's sides, so a page- /// turned a quarter shows its width down the screen.- pub(crate) fn zoom(&self) -> f32 {- let across = if self.rot % 180 == 90 { self.rect.height() } else { self.rect.width() };- across / self.pw.max(1.0)- }-- /// Draw an image in the PDF user-space `rect` as a custom stamp's appearance draws it: turned- /// back by `turn` (the page /Rotate it was placed for), so with the page's own rotation it- /// reads upright as displayed.- pub(crate) fn paint_user_image(- &self,- painter: &egui::Painter,- tex: egui::TextureId,- p: &pdfcraft_render::PageInfo,- rect: [f64; 4],- turn: i64,- color: Color32,- ) {- let mut mesh = egui::Mesh::with_texture(tex);- let (w, h) = (rect[2] - rect[0], rect[3] - rect[1]);- let (shown_w, shown_h) = if turn % 180 == 0 { (w, h) } else { (h, w) };- let [a, b, c, d, e, f] = pdfcraft_model::view_matrix_for(turn, rect);- for (u, v) in [(0.0_f32, 0.0_f32), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)] {- // The texture's (u, v), from its top-left, in the picture's upright frame, then in user space.- let (dx, dy) = (f64::from(u) * shown_w, f64::from(1.0 - v) * shown_h);- let (x, y) = (a * dx + c * dy + e, b * dx + d * dy + f);- let q = p.user_to_view(x as f32, y as f32);- mesh.vertices.push(egui::epaint::Vertex { pos: self.norm_to_screen(q[0] / self.pw, q[1] / self.ph), uv: pos2(u, v), color });- }- mesh.add_triangle(0, 1, 2);- mesh.add_triangle(0, 2, 3);- painter.add(egui::Shape::mesh(mesh));- }- pub fn norm_to_screen(&self, u: f32, v: f32) -> Pos2 {- let (a, b) = match self.rot {- 90 => (1.0 - v, u),- 180 => (1.0 - u, 1.0 - v),- 270 => (v, 1.0 - u),- _ => (u, v),- };- pos2(self.rect.left() + a * self.rect.width(), self.rect.top() + b * self.rect.height())- }-- pub fn screen_to_norm(&self, p: Pos2) -> (f32, f32) {- let (a, b) = ((p.x - self.rect.left()) / self.rect.width().max(1e-3), (p.y - self.rect.top()) / self.rect.height().max(1e-3));- match self.rot {- 90 => (b, 1.0 - a),- 180 => (1.0 - a, 1.0 - b),- 270 => (1.0 - b, a),- _ => (a, b),- }- }-- /// Screen point → view space (points).- pub fn screen_to_view(&self, p: Pos2) -> (f32, f32) {- let (u, v) = self.screen_to_norm(p);- (u * self.pw, v * self.ph)- }-- /// A view-space rect [x0, y0, x1, y1] → screen rect.- pub fn view_rect(&self, g: [f32; 4]) -> Rect {- Rect::from_two_pos(self.norm_to_screen(g[0] / self.pw, g[1] / self.ph), self.norm_to_screen(g[2] / self.pw, g[3] / self.ph))- }-- /// A PDF user-space rect (crop box, document `/Rotate`) → screen rect.- pub fn user_rect(&self, info: &DocInfo, page: usize, r: [f32; 4]) -> Rect {- let p = &info.pages[page];- let [cx0, cy0, cx1, cy1] = p.crop;- let (cw, ch) = ((cx1 - cx0).max(1.0), (cy1 - cy0).max(1.0));- let norm = |x: f32, y: f32| -> (f32, f32) {- let (u, v) = ((x - cx0) / cw, (cy1 - y) / ch);- match p.rotation {- 90 => (1.0 - v, u),- 180 => (1.0 - u, 1.0 - v),- 270 => (v, 1.0 - u),- _ => (u, v),- }- };- let (a, b) = (norm(r[0], r[1]), norm(r[2], r[3]));- Rect::from_two_pos(self.norm_to_screen(a.0, a.1), self.norm_to_screen(b.0, b.1))- }-- /// This transform resized to a raster of `px` device pixels (width, height before the view- /// rotation), so each of its texels covers one screen pixel. The rectangle's corner must- /// already be on a whole pixel ([`snap_to_pixels`]).- fn texel_aligned(&self, px: [usize; 2], ppp: f32) -> PageXform {- let (w, h) = (px[0] as f32 / ppp, px[1] as f32 / ppp);- let size = if self.rot % 180 == 90 { vec2(h, w) } else { vec2(w, h) };- PageXform { rect: Rect::from_min_size(self.rect.min, size), ..*self }- }-- /// Draw a texture covering the normalised page region, rotated with the view.- pub fn paint_image(&self, painter: &egui::Painter, tex: egui::TextureId, u0: f32, v0: f32, u1: f32, v1: f32) {- let mut mesh = egui::Mesh::with_texture(tex);- let corners = [(u0, v0, 0.0, 0.0), (u1, v0, 1.0, 0.0), (u1, v1, 1.0, 1.0), (u0, v1, 0.0, 1.0)];- for (u, v, tu, tv) in corners {- mesh.vertices.push(egui::epaint::Vertex { pos: self.norm_to_screen(u, v), uv: pos2(tu, tv), color: Color32::WHITE });- }- mesh.add_triangle(0, 1, 2);- mesh.add_triangle(0, 2, 3);- painter.add(egui::Shape::mesh(mesh));- }- }-- pub fn shortcuts(view: &mut DocView, ctx: &egui::Context, speed: crate::scroll_speed::ScrollSpeed) {- use egui::{Key, KeyboardShortcut, Modifiers};- if ctx.input_mut(|i| i.consume_shortcut(&KeyboardShortcut::new(Modifiers::COMMAND, Key::F))) {- view.open_find();- }- let cmd = |k| KeyboardShortcut::new(Modifiers::COMMAND, k);- let pressed = |s: KeyboardShortcut| ctx.input_mut(|i| i.consume_shortcut(&s));- // ⌘G / ⇧⌘G step through the matches from the find field too, as in Acrobat and Preview- // (#2669): ahead of the text-input check, but only while there is a search to step.- if view.find.is_some() {- if pressed(KeyboardShortcut::new(Modifiers::COMMAND | Modifiers::SHIFT, Key::G)) {- view.find_step(false);- } else if pressed(cmd(Key::G)) {- view.find_step(true);- }- }- // A focused check box or radio button holds egui's keyboard focus only for Space, and a- // radio button for the arrows that move within its group: the other page keys still work.- let form_box = view.forms.keys.filter(|(id, _)| ctx.memory(|m| m.focused()) == Some(*id));- if ctx.egui_wants_keyboard_input() && form_box.is_none() {- return;- }- let arrows = !form_box.is_some_and(|(_, radio)| radio);- // Rotation first: egui matches ⌘+ loosely with respect to Shift.- if pressed(KeyboardShortcut::new(Modifiers::COMMAND | Modifiers::SHIFT, Key::Plus))- || pressed(KeyboardShortcut::new(Modifiers::COMMAND | Modifiers::SHIFT, Key::Equals))- {- view.rotate_view(true);- }- if pressed(KeyboardShortcut::new(Modifiers::COMMAND | Modifiers::SHIFT, Key::Minus)) {- view.rotate_view(false);- }- // In the page grid ⌘+ / ⌘− / ⌘0 size its pages instead (looking is always allowed).- let (zoom_in, zoom_out, zoom_reset) = (pressed(cmd(Key::Plus)) || pressed(cmd(Key::Equals)), pressed(cmd(Key::Minus)), pressed(cmd(Key::Num0)));- if view.organize {- if zoom_in {- view.grid_zoom_request = Some(view.grid_zoom * GRID_ZOOM_STEP);- }- if zoom_out {- view.grid_zoom_request = Some(view.grid_zoom / GRID_ZOOM_STEP);- }- if zoom_reset {- view.grid_zoom_request = Some(1.0);- }- } else {- if zoom_in {- view.zoom_step(true);- }- if zoom_out {- view.zoom_step(false);- }- if zoom_reset {- view.fit = Fit::Page;- view.goto = Some((view.current, 0.0));- }- }- if pressed(cmd(Key::Num1)) {- view.set_zoom(1.0);- }- if pressed(cmd(Key::Num2)) {- view.fit = Fit::Width;- view.goto = Some((view.current, 0.0));- }- if pressed(cmd(Key::OpenBracket)) {- view.view_history(false);- }- if pressed(cmd(Key::CloseBracket)) {- view.view_history(true);- }- let key = |k| (arrows || !matches!(k, Key::ArrowLeft | Key::ArrowRight | Key::ArrowUp | Key::ArrowDown)) && ctx.input(|i| i.key_pressed(k));- // An open menu takes Escape first and closes; the selection stays for the next one (#3535).- if key(Key::Escape) && !egui::Popup::is_any_open(ctx) {- if view.camera.is_some() || view.camera_done.is_some() {- view.pending_action = Some(ViewAction::CancelCamera);- } else if view.selection.is_some() || view.all_text {- view.selection = None;- view.all_text = false;- } else {- view.find = None;- }- }- if key(Key::Home) {- view.go_to_page(0);- }- if key(Key::End) {- view.go_to_page(usize::MAX);- }- // Full screen: Space and Enter go forward a page and Backspace back, as in Acrobat (the- // arrows and Page Up / Page Down already turn pages where nothing scrolls, below).- if view.presentation.is_some() {- if key(Key::Space) || key(Key::Enter) {- view.step_page(true);- }- if key(Key::Backspace) {- view.step_page(false);- }- }- // As in Acrobat: → / ← go to the next / previous page in every layout (#185), and so do- // ⌘Page Down / ⌘Page Up, or plain Page Down / Page Up in single-page view.- let command = ctx.input(|i| i.modifiers.command);- let scrolls = view.continuous;- if key(Key::ArrowRight) || (key(Key::PageDown) && (command || !scrolls)) {- view.step_page(true);- }- if key(Key::ArrowLeft) || (key(Key::PageUp) && (command || !scrolls)) {- view.step_page(false);- }- // ↓ / ↑ scroll a line, and Page Down / Page Up a screen where the pages scroll. In- // single-page view, ↓ / ↑ turn the page once there is nothing left to scroll that way, as- // the wheel does (#273): always on a page that fits.- // The Scroll speed preference sets how far ↓ / ↑ go as well as the wheel (#985); Page Down /- // Page Up keep a screen.- if !command {- let line = KEY_SCROLL_LINE * speed.factor();- let screen = (view.viewport_h - KEY_SCROLL_LINE).max(KEY_SCROLL_LINE);- let steps = [(Key::ArrowDown, line), (Key::ArrowUp, -line), (Key::PageDown, screen), (Key::PageUp, -screen)];- for (k, by) in steps {- let arrow = matches!(k, Key::ArrowDown | Key::ArrowUp);- if !key(k) || !(scrolls || arrow) {- continue;- }- let forward = k == Key::ArrowDown;- // Only an up-to-date view counts: the page drawn is the current one, with no jump pending.- let at_end = !scrolls- && view.goto.is_none()- && view.single_edges.is_some_and(|(page, top, bottom)| page == view.current && if forward { bottom } else { top });- if at_end {- let before = view.current;- view.step_page(forward);- if !forward && view.current != before {- // Going back up lands on the bottom of the previous page.- view.goto = Some((view.current, 1.0));- }- view.single_edges = None;- } else {- view.key_scroll += by;- }- }- }- }-- /// How far ↓ / ↑ scroll at Normal speed (Scroll speed halves or doubles it). Page Down / Page Up- /// keep this much of the previous screen in view.- const KEY_SCROLL_LINE: f32 = 40.0;- /// Suppression window for egui's eased copy of point input.- ///- /// egui 0.36.2 drains `WheelState::after_events` tail deltas by 90% per 0.1 s.- const SUPPRESS_SECS: f64 = 0.25;- /// Short rolling extension while egui still has an unprocessed wheel tail.- const SUPPRESS_TAIL_SECS: f64 = 0.05;-- // Keep the viewer's scroll identity tied to the document instead of its parent UI.- fn page_scroll<R>(- ui: &mut egui::Ui,- scroll: egui::ScrollArea,- id: egui::Id,- draw: impl FnOnce(&mut egui::Ui, egui::Rect) -> R,- ) -> egui::scroll_area::ScrollAreaOutput<R> {- ui.scope_builder(egui::UiBuilder::new().scope_id(id), |ui| scroll.show_viewport(ui, draw)).inner- }-- /// Draws the document tab at `index`: its notice bars, then its pages (or the Organize grid) in a- /// scroll area with this frame's zoom, scrolling, tool input, overlays and render requests.- pub fn document_area(app: &mut PdfCraftApp, index: usize, ui: &mut egui::Ui) {- let t = Tokens::get(ui.ctx());- // Keyboard scrolling applies to this frame's page view only, never later.- let key_scroll = std::mem::take(&mut app.views[index].key_scroll);- if key_scroll != 0.0 {- app.views[index].end_find_following();- }- // The Search panel closed: its search moves to the find bar.- let search_open = app.right == Some(crate::RightPanel::Search);- if let Some(f) = app.views[index].find.as_mut()- && f.in_panel- && !search_open- {- f.in_panel = false;- }- // The snapshot notice bar's Close was clicked: close here, where no document borrow is- // held. The tab is looked up by id: indices may have shifted since the click, and the- // flag rides its own view, so a stale flag can never close the wrong tab.- let pending = app.views.get(index).filter(|v| v.close_requested).map(|v| v.id).and_then(|id| app.views.iter().position(|v| v.id == id));- if let Some(i) = pending {- app.views[i].close_requested = false;- if app.has_unsaved_work(i) {- app.close_request = Some(crate::CloseRequest::Tab(app.views[i].id));- } else {- app.close_tab(i);- }- return;- }- let Some(doc) = app.session.get(app.views[index].id) else { return };- let info = &doc.info;- let paper = app.session.reading_colors(app.views[index].id).and_then(|c| c.params).map_or(Color32::WHITE, |p| {- let [r, g, b] = p.background;- Color32::from_rgb(r, g, b)- });- if info.pages.is_empty() {- app.views[index].auto_scroll.cancel();- ui.centered_and_justified(|ui| ui.label(tl!("This document has no pages.")));- return;- }- // The print dialog queues its own rasters later in the frame. Closing it drops them.- if app.dialog != Some(crate::Dialog::Print) {- app.views[index].print_pages.clear();- }- // The Prepare a form panel is open (or a field tool is picked): fields are edited, not filled.- let preparing = app.is_preparing();- // Prepare a form ▸ Calculation order: the order's steps and links on the page.- let calc_order = preparing && app.left_open && app.left == crate::LeftPanel::CalculationOrder;- // Edit a PDF: added text and images can be selected, moved and edited.- let editing_content =- (app.left_open && app.left == crate::LeftPanel::Tool("edit")) || matches!(app.quick_tool, QuickTool::AddText | QuickTool::EditText);- let text_style = app.text_style.clone();- let show_secured_notice = app.show_secured_notice;- let view = &mut app.views[index];- // Opened without the owner password and something is restricted. The notice says so unless- // the user turned it off (#4035): the restrictions themselves, and Document Properties ▸- // Security, stay as they are.- let secured = show_secured_notice && doc.security_summary().is_some_and(|s| !(s.owner || (s.permissions.modify() && s.permissions.assemble())));- let repaired = !doc.repair_log().is_empty();- match notices(view, doc, secured, repaired, crate::sign_ui::banner(&doc.signatures), ui, &t) {- #[cfg(not(target_arch = "wasm32"))]- Some(Notice::Reload) => app.watch.reload_request = Some(view.id),- #[cfg(target_arch = "wasm32")]- Some(Notice::Reload) => {}- Some(Notice::Repairs) => app.dialog = Some(crate::Dialog::Properties(crate::PropsTab::Advanced)),- Some(Notice::Security) => app.dialog = Some(crate::Dialog::Properties(crate::PropsTab::Security)),- Some(Notice::Unlock) => app.unlock_prompt = Some(crate::UnlockPrompt::new(doc, None)),- // Flags the view: the tab closes at the top of the next frame, where no document- // borrow is held.- Some(Notice::Close) => {- if let Some(view) = app.views.get_mut(index) {- view.close_requested = true;- }- }- Some(Notice::Signatures) => app.right = Some(RightPanel::Signatures),- Some(Notice::FieldHighlights(on)) => app.view_defaults.highlight_fields = on,- Some(Notice::Console) => app.dialog = Some(crate::Dialog::JsConsole),- // Back on in Preferences ▸ General.- Some(Notice::HideSecured) => app.show_secured_notice = false,- None => {}- }- // No dialog, close prompt or palette over the page: only then does page input count.- let modal = app.modal_open();- let unobstructed = !modal && !app.palette_open;- let organize_zoom = app.organize_zoom;- let view = &mut app.views[index];- if view.organize {- // One remembered grid size for every document, kept in the settings.- view.set_grid_zoom(organize_zoom);- organize_grid(view, info, doc.allows_assembly(), doc.dirty, unobstructed, ui, &t);- app.organize_zoom = view.grid_zoom();- return;- }-- let avail = ui.available_rect_before_wrap();- view.viewport_w = avail.width();- view.viewport_h = avail.height();- let old_zoom = view.zoom;- view.fit_zoom(info);- if view.shown && view.zoom_anchor.is_none() && view.goto.is_none() && view.goto_point.is_none() && (view.zoom - old_zoom).abs() > 1e-4 {- let prev_viewport = view.viewport_screen;- let top_y = prev_viewport.min.y;- let anchor = view- .screen_rects- .iter()- .find(|(_, r)| r.min.y <= top_y && r.max.y > top_y)- .map(|(p, r)| {- let fy = if r.height() > 0.0 { ((top_y - r.min.y) / r.height()).clamp(0.0, 1.0) } else { 0.0 };- (*p, fy, 0.0f32)- })- .or_else(|| view.screen_rects.iter().find(|(_, r)| r.min.y >= top_y).map(|(p, r)| (*p, 0.0f32, (r.min.y - top_y).max(0.0))))- .or_else(|| view.screen_rects.last().map(|(p, r)| (*p, 1.0f32, (r.max.y - top_y).max(0.0))));- if let Some((page, fy, rel_y)) = anchor {- view.zoom_anchor = Some((page, 0.5, fy, vec2(avail.width() / 2.0, rel_y)));- } else {- view.zoom_anchor = Some((view.current, 0.5, 0.0, vec2(avail.width() / 2.0, MARGIN)));- }- }-- // Pinch / ctrl+scroll zoom, anchored on the current page.- let zoom_delta = crate::motion::zoom_delta(ui.ctx());- // Exclude the previous frame's scrollbar tracks from gesture activation.- let navigation_rect = if view.viewport_screen.is_positive() { avail.intersect(view.viewport_screen) } else { avail };- let navigation_enabled = app.dialog.is_none() && app.close_request.is_none() && !app.palette_open && ui.is_enabled() && ui.input(|i| i.focused);- // Full screen: a click on the document goes forward a page and a shift-click back, as in- // Acrobat, unless the click did something else (a link, a word selected). Decided below,- // once the pages have had the click.- let present_click =- view.presentation.is_some() && navigation_enabled && presentation_click(ui, navigation_rect) && app.quick_tool == QuickTool::Select;- // Shift as held now, or as the click's own event carried it (a synthetic click).- let present_back = present_click- && ui.input(|i| {- i.modifiers.shift- || i.events.iter().any(|e| {- matches!(e, egui::Event::PointerButton { button: egui::PointerButton::Primary, pressed: false, modifiers, .. } if modifiers.shift)- })- });- if zoom_delta.is_finite() && zoom_delta > 0.0 && zoom_delta != 1.0 && navigation_enabled && ui.rect_contains_pointer(navigation_rect) {- let z = view.zoom * zoom_delta;- match zoom_anchor(ui) {- Some(p) => view.zoom_at(z, p),- None => view.set_zoom(z),- }- }- view.viewport_screen = avail;- let auto_delta = if unobstructed {- view.auto_scroll.update(ui, avail, false)- } else {- view.auto_scroll.cancel();- Vec2::ZERO- };-- // Drawing a comment: the pointer in a band along any edge (or just past it) scrolls the view- // that way, so a point beyond what is shown can be reached without letting go of the tool.- let edge_delta = if unobstructed && matches!(view.comments.gesture, Some(comments::Gesture::Draw { .. })) {- let (pointer, dt) = drawing_edge_pointer(ui);- crate::autoscroll::edge_scroll(pointer, avail, dt)- } else {- Vec2::ZERO- };- if edge_delta != Vec2::ZERO {- ui.ctx().request_repaint();- }-- let content_w = view.content_width(info, avail.width());- let rects = view.layout(info, content_w, ui.ctx().pixels_per_point());- // When not scrolling continuously, only one row is shown at a time: the current page, or the- // current two-page spread (with the cover rule). These indices drive paging, which pages are- // drawn, and the content height (#752). Empty for a document with no pages.- let shown_row = |view: &DocView| -> Vec<usize> {- if rects.is_empty() {- return Vec::new();- }- let last = rects.len() - 1;- let cur = view.current.min(last);- match view.layout {- PageLayout::Single => vec![cur],- PageLayout::TwoUp if view.cover && cur == 0 => vec![0],- PageLayout::TwoUp => {- let first = if view.cover { cur - (cur + 1) % 2 } else { cur - cur % 2 };- if first < last { vec![first, first + 1] } else { vec![first] }- }- }- };- let row = shown_row(view);- let middle_gesture = view.auto_scroll.blocks_input();- // Not scrolling: when the whole page or spread fits, the wheel would do nothing, so it turns- // pages instead; zoomed in far enough to pan, it pans, and at the edge it turns the page on- // (#1924, `single_page_wheel_edge`). Touch drags are untouched: with- // nothing to pan, touch users turn pages with the rail buttons, the page box and the arrow- // keys. Runs before `visible_pages` so the frame that turns the page draws it.- let mut single_paging = false;- let mut edge_turned = false;- if !view.continuous {- // The row's bounding box on screen (one page, or a two-page spread).- let row_rect = row.iter().filter_map(|&i| rects.get(i)).copied().reduce(Rect::union);- // Within a point, so layout rounding can't stop a fitting page from turning.- let fits = row_rect.is_some_and(|r| r.height() + 2.0 * MARGIN <= avail.height() + 1.0);- let can_turn = !middle_gesture && unobstructed && ui.rect_contains_pointer(avail);- single_paging = can_turn && fits;- // Every wheel event goes to the pager, so it follows each trackpad touch to its end- // even while the page can't turn.- ui.input(|i| {- for e in &i.events {- if let egui::Event::MouseWheel { unit, delta, phase, modifiers, .. } = e {- // Zooming (⌘ or Ctrl) and sideways scrolling (Shift) never turn pages.- let dy = if modifiers.command || modifiers.ctrl || modifiers.shift { 0.0 } else { delta.y };- if fits {- view.single_page_wheel(*unit, dy, *phase, i.time, can_turn);- } else {- edge_turned |= view.single_page_wheel_edge(*unit, dy, *phase, i.time, can_turn);- }- }- }- });- if single_paging {- // Paging owns vertical wheel motion here. A diagonal gesture keeps its sideways- // part, as `ScrollArea` itself handles each axis.- ui.input_mut(|i| i.smooth_scroll_delta.y = 0.0);- }- }- // Point input bypasses egui smoothing for 1:1 motion. Line input keeps egui's configured,- // smoothed base and adds only the accelerated surplus. While point suppression is active,- // reconstruct line and page input here so current coarse events survive without exposing an- // older eased tail.- let now = ui.input(|i| i.time);- let input = if ui.rect_contains_pointer(avail) {- // Match the line distance used by egui's other scroll areas.- let live = ui.ctx().options(|o| o.input_options.line_scroll_speed);- let line_points = if live.is_finite() && live > 0.0 { live } else { crate::scroll_speed::EGUI_LINE_POINTS };- ui.input(|i| crate::wheel_boost::accumulate(&i.events, line_points, single_paging))- } else {- crate::wheel_boost::FrameInput::default()- };- let mut precise_scroll = input.precise;- let mut line_base = input.line;- let mut boost_extra = crate::wheel_boost::boost_extra(input, &mut view.wheel_boost_x, &mut view.wheel_boost_y, now);- let has_page = input.page != Vec2::ZERO;- if now.is_finite() && precise_scroll != Vec2::ZERO && !has_page {- view.precise_scroll_until = now + SUPPRESS_SECS;- }- if edge_turned {- // The turn leaves egui's eased copy of the notch to decay for a few frames; it must not- // scroll the page just shown away from its top (or bottom).- view.precise_scroll_until = now + 0.25;- }- // Paging owns the vertical axis in single-page view; leave it to the pager.- // The rest of a gesture that turned the page is swallowed too, or it would pan the new page- // away from the edge it was shown at.- let paging_owns_vertical = single_paging || (!view.continuous && view.wheel.gesture_turned());- if paging_owns_vertical {- precise_scroll.y = 0.0;- line_base.y = 0.0;- boost_extra.y = 0.0;- }- // egui smooths a Point event that moved at least 8 points, keeping part of it for later- // passes. Suppression must outlive that whole action: once it expired after a fixed 0.25 s,- // the last few eased points leaked through the ScrollArea after a precise 1:1 scroll (held- // point input measured 33 points for a 30-point event). Keep hiding the eased copy until- // egui says the action is over, then forget the suppression.- let scrolling = ui.input(|i| i.is_scrolling());- if now < view.precise_scroll_until || (view.precise_scroll_until != 0.0 && scrolling) {- if scrolling {- // Keep hiding egui's unprocessed copy until it has drained. The short rolling grace- // avoids a delayed duplicate without prolonging suppression after the tail is gone.- view.precise_scroll_until = view.precise_scroll_until.max(now + SUPPRESS_TAIL_SECS);- }- ui.input_mut(|i| i.smooth_scroll_delta = Vec2::ZERO);- // The point path suppresses every eased wheel delta. Restore the line base through the- // same un-eased path as its surplus; paging-owned axes were cleared above.- boost_extra = crate::wheel_boost::cap_frame(boost_extra + line_base);- if has_page {- // Page units normally stay on egui's viewport-sized path. During suppression only,- // reproduce the current event directly so an older hidden tail stays hidden.- let page_scale = ui.input(|i| i.viewport_rect().height());- let mut page_delta =- if page_scale.is_finite() && page_scale > 0.0 { crate::wheel_boost::cap_frame(input.page * page_scale) } else { Vec2::ZERO };- if paging_owns_vertical {- page_delta.y = 0.0;- }- boost_extra = crate::wheel_boost::cap_frame(boost_extra + page_delta);- }- } else {- precise_scroll = Vec2::ZERO;- // Selection handling below uses zero to distinguish an inactive window. Clearing a past- // deadline also keeps a later line/page action from being mistaken for the old tail.- view.precise_scroll_until = 0.0;- }- if has_page && paging_owns_vertical {- // Page input belongs to egui on the free axis; the pager still owns vertical motion.- ui.input_mut(|i| i.smooth_scroll_delta.y = 0.0);- }- // Touchpad momentum (#531): a swipe over the page lifted at speed glides on and slows to a- // stop, through the same un-eased path. Never while the pager owns the wheel, a gesture or- // dialog has the input, or animations are off; any click, key, zoom or other scrolling ends it.- // Asked of the preference, not of egui's animation time, which test harnesses zero.- let animates = app.animation_effects.animates(app.motion.reduced);- let may_glide = !paging_owns_vertical && !middle_gesture && navigation_enabled && unobstructed && animates;- let over_page = ui.rect_contains_pointer(avail);- ui.input(|i| view.fling.read(&i.events, now, may_glide && over_page));- let interrupted = glide_interrupted(ui);- if !may_glide || interrupted || key_scroll != 0.0 || auto_delta != Vec2::ZERO || zoom_delta != 1.0 {- view.fling.stop();- }- let glide = view.fling.step(now);- if view.fling.gliding() {- ui.ctx().request_repaint();- }- // Any reader-owned motion ends automatic search following, even when it stays on the same- // page: the wheel, keyboard, middle-button auto-scroll, a drawing's edge scroll, or the- // momentum left by a touchpad swipe. The automatic flash uses `goto`, not these deltas, so- // its programmatic scroll is never mistaken for a reader action.- let wheel_scrolled = precise_scroll != Vec2::ZERO || line_base != Vec2::ZERO || boost_extra != Vec2::ZERO || has_page;- if wheel_scrolled || auto_delta != Vec2::ZERO || edge_delta != Vec2::ZERO || glide != Vec2::ZERO {- view.end_find_following();- }- // The wheel may have turned the page above: draw the row it turned to. Measured from the old- // row, the jump to the new page scrolled both out of view, a blank frame on every turn forward.- let row = shown_row(view);- let visible_pages: Vec<usize> = if view.continuous { (0..rects.len()).collect() } else { row.clone() };- let (y_shift, content_h) = if view.continuous {- (0.0, rects.iter().map(|r| r.bottom()).reduce(f32::max).map(|bottom| bottom + MARGIN).unwrap_or(0.0))- } else {- // Only the current row scrolls into view; the content is its bounding box plus margins.- match row.iter().filter_map(|&i| rects.get(i)).copied().reduce(Rect::union) {- Some(r) => (r.top() - MARGIN, r.height() + 2.0 * MARGIN),- None => (0.0, 0.0),- }- };-- let mut scroll = egui::ScrollArea::both().auto_shrink([false, false]).scroll_source(egui::scroll_area::ScrollSource {- drag: if middle_gesture {- egui::scroll_area::DragScroll::Never- } else if app.quick_tool == QuickTool::Hand {- egui::scroll_area::DragScroll::Always- } else {- egui::scroll_area::DragScroll::OnTouch- },- ..Default::default()- });- // Each document keeps its own scroll position when switching tabs (#189).- scroll = scroll.id_salt(("page-view", view.id));- // Every scroll here asks for no animation. An animated area would still queue a zero-length- // offset target for the next frame, which overwrites the jump a page turn just set.- scroll = scroll.animated(false);- // A newly opened document starts at the top. eframe saves egui's memory with the settings- // and document ids start again at 1 every launch, so the offset stored under this id can be- // where an earlier session left another document.- if !std::mem::replace(&mut view.shown, true) {- scroll = scroll.scroll_offset(Vec2::ZERO);- }- // The Hand tool pans here, before the pages are laid out, so the page moves with the pointer- // in the frame the pointer moves (#924). Scrolling by the drag from inside the area moved the- // page only after that frame was drawn, a frame behind. The frame egui tells the drag from a- // click, the page catches up with all the pointer has moved since the press. A jump asked for- // below still wins.- if app.quick_tool == QuickTool::Hand- && !middle_gesture- && let Some(id) = view.page_widget.filter(|id| ui.ctx().is_being_dragged(*id))- {- let moved = if ui.ctx().drag_started_id() == Some(id) {- ui.input(|i| i.pointer.total_drag_delta()).unwrap_or(Vec2::ZERO)- } else {- ui.input(|i| i.pointer.delta())- };- if moved != Vec2::ZERO {- view.end_find_following();- }- // Within the content, as egui keeps it: past an end the page would show there for a- // frame and spring back. `max` is never NaN or below zero, so the clamp can't panic.- let max = vec2((content_w - avail.width()).max(0.0), (content_h - avail.height()).max(0.0));- scroll = scroll.scroll_offset((view.last_scroll - moved).clamp(Vec2::ZERO, max));- }- if let Some(v) = view.sync_scroll.take() {- scroll = scroll.scroll_offset(v);- }- if let Some((page, fx, fy, rel)) = view.zoom_anchor.take() {- let r = rects[page.min(rects.len() - 1)];- let point = pos2(r.left() + fx * r.width(), r.top() - y_shift + fy * r.height());- scroll = scroll.scroll_offset(anchored_scroll(point, rel, vec2(content_w, content_h), avail.size()));- } else if let Some((page, frac)) = view.goto.take() {- let page = page.min(rects.len() - 1);- let r = rects[page];- // Clamped here: egui clamps only after drawing, so a page that fits was drawn MARGIN - page_gap()- // too high for a frame and then hopped into place. (`avail` is the viewport, as the- // scroll bars float.)- let max_y = (content_h - avail.height()).max(0.0);- scroll = scroll.vertical_scroll_offset((r.top() - y_shift - view.page_gap() + frac * r.height()).max(0.0).min(max_y));- // Horizontally too, as Acrobat does (#2665): beside a much wider page the others sit off- // to one side. A page already shown whole, or one filling the window's width, keeps the- // scroll, so paging through a zoomed-in document stays on the same column. Otherwise a- // page that fits is centred, and a wider one scrolled just far enough to fill the window.- // The page counts with its side gutters, which keep its edge clear of the floating- // quick-action bar as the layout does.- let (x, w) = (view.last_scroll.x, avail.width());- let (left, right) = (r.left() - SIDE, r.right() + SIDE);- let target = if right - left <= w { if left >= x && right <= x + w { x } else { r.center().x - w / 2.0 } } else { x.clamp(left, right - w) };- if (target - x).abs() > 0.5 {- scroll = scroll.horizontal_scroll_offset(target.clamp(0.0, (content_w - w).max(0.0)));- }- }- let ppp = ui.ctx().pixels_per_point();- let scale = view.render_scale(ppp);- let tag = scale_tag(scale);- // Hold sharp re-renders while the zoom is still moving: a new scale every frame would- // cancel the in-flight full-page interpret and restart it, so on a heavy page (a CAD- // plot with ~1000 images renders for seconds) the sharp raster never arrives and the- // view looks stuck on a soft image. The stale raster stays stretched meanwhile; the- // sharp request goes out once the zoom settles.- let now_scale = ui.input(|i| i.time);- if (scale - view.last_scale).abs() > f32::EPSILON {- view.last_scale = scale;- view.sharp_hold_until = now_scale + 0.35;- ui.ctx().request_repaint_after(std::time::Duration::from_millis(380));- }- let sharp_held = now_scale < view.sharp_hold_until;- view.current_scale_tag = tag;- let hand = app.quick_tool == QuickTool::Hand;- let tool = app.quick_tool;- // Text selection runs for the Select tool and for the markup tools (highlight…).- let selects_text = match tool {- QuickTool::Comment(t) => t.markup().is_some() || t == comments::CommentTool::ReplaceText,- QuickTool::Select => !preparing,- QuickTool::Redact | QuickTool::ColumnSelect => true,- QuickTool::Hand- | QuickTool::Measure(_)- | QuickTool::Crop- | QuickTool::EnhanceCamera- | QuickTool::Fill(_)- | QuickTool::Field(_)- | QuickTool::AddText- | QuickTool::EditText- | QuickTool::Stamp(_)- | QuickTool::CustomStamp(_)- | QuickTool::Link- | QuickTool::SignArea { .. }- | QuickTool::MarqueeZoom- | QuickTool::Snapshot => false,- };- let prefs = &app.comment_prefs;- let redact_mark = (app.redact_prefs.hover_fill, app.redact_prefs.opacity);- let units = app.units;- let allowed = doc.allows_annotation();- let can_copy = doc.allows_copying();- let mut copy_selected = false;- let comments_hidden = doc.comments_hidden();- let form = doc.form.clone();- let generation = doc.edit_generation();- let can_fill = doc.allows_form_filling();- let can_crop = doc.allows_assembly();- let mut open_boxes = false;- let signature = app.signature.clone();- let initials = app.initials.clone();- let mut open_initials = false;- let author = app.comment_prefs.author.clone();- let today = app.session.today();- // In Preferences ▸ Date format, or why it can't be stamped into the PDF.- let date_text = crate::date_text_for_pdf(&app.session);- let mut refused: Option<String> = None;- let by_line = app.session.stamp_by_line(&author);- let mut stamp_placed = false;- let mut image_action: Option<crate::edit_text_ui::ImageAction> = None;- let custom_stamp = match app.quick_tool {- QuickTool::CustomStamp(i) => app.custom_stamps.get(i).cloned(),- _ => None,- };- let mut open_signature = false;- let mut hover_text: Option<(Pos2, String)> = None;- let mut clicked_link: Option<LinkTarget> = None;- let mut remote_open: Option<(pdfcraft_engine::DocId, String, pdfcraft_render::RemoteDestination)> = None;- let mut canvas_action: Option<comments::CanvasAction> = None;- let mut field_menu: Option<FieldMenu> = None;- let mut open_props: Option<(usize, usize)> = None;- let mut field_props = false;- let mut field_placed = false;- let mut open_table: Option<(usize, [f64; 4])> = None;- // The table being set up in its window, shown on its own document's page.- let table_preview = app.field_table_draft.as_mut().filter(|d| d.doc == view.id).and_then(|d| Some(d.preview(info.pages.get(d.page)?, &form)));- let can_modify = doc.allows_modification();- if preparing {- crate::prepare::after_refresh(view, &form);- } else {- view.prepare.selected = None;- }- view.objects.prepare(doc, tool == QuickTool::EditText && can_modify, ui.ctx());- view.text_background.prepare(ui.ctx(), doc, view.line_editor.as_ref(), view.content.draft.as_ref(), scale);- let added = if editing_content { doc.added().to_vec() } else { Vec::new() };- let doc_links = if tool == QuickTool::Link { doc.links().to_vec() } else { Vec::new() };- if editing_content {- crate::content_ui::after_refresh(view, &added);- } else {- view.content.selected = None;- }- view.move_background.prepare(ui.ctx(), doc, &view.content, scale);-- // A destination's position (bookmarks, links) refines `goto`: its point at the window's- // top-left, or the centre of a /FitR rectangle at the window's centre.- if let Some((page, fx, fy, rel)) = view.goto_point.take() {- let r = rects[page.min(rects.len() - 1)];- // Within the content, so an unreachable point never shows a frame scrolled past the end.- let (max_x, max_y) = ((content_w - avail.width()).max(0.0), (content_h - avail.height()).max(0.0));- if let Some(fx) = fx {- scroll = scroll.horizontal_scroll_offset((r.left() + fx * r.width() - rel.x).clamp(0.0, max_x));- }- if let Some(fy) = fy {- scroll = scroll.vertical_scroll_offset((r.top() - y_shift + fy * r.height() - rel.y).clamp(0.0, max_y));- }- }- let selection_wheel = view.selection_drag && navigation_enabled && unobstructed && !single_paging && ui.rect_contains_pointer(avail);- let out = page_scroll(ui, scroll, egui::Id::unique(("page-view-scope", view.id)), |ui, viewport| {- // egui's drag responses accept every pointer button. Keep a wheel gesture from also- // selecting text, drawing a mark, or panning with the Hand tool.- if middle_gesture {- let opacity = ui.opacity();- ui.disable();- // Only interactions pause; the document must keep its original colours.- ui.set_opacity(opacity);- }- // Middle-button auto-scroll, the keyboard, precise touchpad input (#759) and its glide- // (#531), accelerated wheel surplus (#1072), and a drawing's edge scroll; positive y- // moves the content down. All scroll without easing, unlike egui's wheel default.- // ScrollArea ignores wheel input during a widget drag. Defer the wheel contribution- // until after the text widgets when a selection owns that drag.- let wheel_delta = if selection_wheel { Vec2::ZERO } else { precise_scroll + boost_extra };- let delta = auto_delta + edge_delta - vec2(0.0, key_scroll) + wheel_delta + glide;- if delta != Vec2::ZERO && delta.is_finite() {- ui.scroll_with_delta_animation(delta, egui::style::ScrollAnimation::none());- }- let (resp_rect, resp) = ui.allocate_exact_size(vec2(content_w, content_h), 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.- if !resp.dragged_by(egui::PointerButton::Primary) {- view.selection_drag = false;- }- // The Hand tool pans by this widget's drag, before the pages are laid out (above).- if hand {- if resp.dragged() {- view.cursor.claim(Layer::Drag, egui::CursorIcon::Grabbing);- } else if resp.hovered() {- view.cursor.claim(Layer::ToolArea, egui::CursorIcon::Grab);- }- }- let origin = resp_rect.min - vec2(0.0, y_shift);- let painter = ui.painter();- let visible = viewport.translate(resp_rect.min.to_vec2());- let mut wanted = Vec::new();- let mut visible_now = Vec::new();- view.screen_rects.clear();- view.screen_xforms.clear();- // Visible heights (points) closer than this are equal: one page size can meet the- // viewport a fraction of a point differently once the scroll offset is applied.- const TIE: f32 = 0.5;- let mut current = view.current;- let mut best_overlap = -1.0f32;- let mut current_overlap = -1.0f32;- let mut current_height = f32::INFINITY;- // The pointer as the pages see it: nothing over them (a dialog from the frame it opens),- // or a press they hold. The page modules read it rather than egui's raw pointer state.- let ptr = PagePointer::read(ui, &resp, modal);- let pointer = ptr.pos;- // A press on a page makes it the current one (as in Acrobat), so a page command with- // no selection (Rotate, Delete) acts on the page the reader pointed at, not on a page- // gone to earlier that still shows whole beside it.- let pressed = unobstructed && ptr.pressed().is_some();- let mut pressed_page = None;- if resp.secondary_clicked() {- // Set again below when the right-click lands on a link.- view.links.context = None;- }- let mut calc_hover = None;- for &i in &visible_pages {- let r = snap_to_pixels(rects[i].translate(origin.to_vec2()), ppp);- if !r.intersects(visible.expand(400.0)) {- continue;- }- if pressed && pressed_page.is_none() && pointer.is_some_and(|p| r.contains(p)) {- pressed_page = Some(i);- }- if r.intersects(visible) {- visible_now.push(i);- view.screen_rects.push((i, r));- view.screen_xforms- .push((i, PageXform { rect: r, rot: view.rotation, pw: info.pages[i].width.max(1.0), ph: info.pages[i].height.max(1.0) }));- }- let overlap = r.intersect(visible).height();- if i == view.current {- current_overlap = overlap;- current_height = r.height();- }- // Pages shown equally (two rows wholly on screen) differ only by rounding: the- // topmost one counts.- if overlap > best_overlap + TIE {- best_overlap = overlap;- current = i;- }- let xf = PageXform { rect: r, rot: view.rotation, pw: info.pages[i].width.max(1.0), ph: info.pages[i].height.max(1.0) };- // Shadows would darken the preceding page when pages touch.- if view.show_page_gaps {- painter.add(egui::epaint::Shadow { offset: [0, 3], blur: 14, spread: 0, color: t.page_shadow }.as_shape(r, CornerRadius::ZERO));- }- painter.rect_filled(r, CornerRadius::ZERO, paper);- if let Some(err) = view.errors.get(&i) {- painter.rect_filled(r, CornerRadius::ZERO, Color32::from_rgb(0xFB, 0xF4, 0xF4));- icons::paint(- ui,- Rect::from_center_size(r.center() - vec2(0.0, 26.0), vec2(28.0, 28.0)),- "triangle-alert",- 26.0,- Color32::from_rgb(0xC8, 0x3A, 0x3A),- );- let message = crate::i18n::fmt(tl!("This page couldn't be displayed.\n{e}"), &[("e", err)]);- let msg =- ui.fonts_mut(|f| f.layout(message, theme::regular(12.5), Color32::from_rgb(0x6A, 0x2A, 0x2A), (r.width() - 40.0).max(80.0)));- painter.galley(pos2(r.center().x - msg.size().x / 2.0, r.center().y), msg, Color32::BLACK);- } else {- let (pw_pt, ph_pt) = (info.pages[i].width.max(1.0), info.pages[i].height.max(1.0));- // A GPU may take smaller textures than these (OpenGL drivers report as little as- // 2048 pixels, and uploading a bigger one aborts), so both stay within its limit.- let max_side = ui.ctx().input(|inp| inp.max_texture_side) as f32;- let tiled = pw_pt.max(ph_pt) * scale > TILE_THRESHOLD.min(max_side);- // Whole-page raster: sharp when small, a low-res backdrop when tiled.- let (want_scale, want_tag) = if tiled {- let bs = BASE_SIDE.min(max_side) / pw_pt.max(ph_pt);- (bs, scale_tag(bs))- } else {- (scale, tag)- };- // Under tiles, a whole-page raster sharper than the backdrop (from before the page- // grew past the tiling size) is a better backdrop: keep demanding it as it is.- match view.pages.get(&i).filter(|p| tiled && p.tag != STALE_TAG && tag_scale(p.tag) >= want_scale) {- Some(p) => wanted.push((i, tag_scale(p.tag), p.tag, None)),- None => wanted.push((i, want_scale, want_tag, None)),- }- match view.pages.get(&i) {- Some(p) => {- if !tiled && p.tag == want_tag {- xf.texel_aligned(p.tex.size(), ppp).paint_image(painter, p.tex.id(), 0.0, 0.0, 1.0, 1.0);- } else {- // A backdrop, or a raster at an older scale until the new one arrives.- xf.paint_image(painter, p.tex.id(), 0.0, 0.0, 1.0, 1.0);- }- }- None => {- let now = ui.input(|inp| inp.time);- let since = *view.waiting_since.entry(i).or_insert(now);- let msg = if now - since > 6.0 { "Still rendering — this page is unusually complex…" } else { "Rendering…" };- painter.text(r.center(), Align2::CENTER_CENTER, tl!(msg), theme::regular(12.0), t.text_faint);- }- }- if tiled && r.intersects(visible) {- // Device-pixel geometry of the scaled page, and the visible part of it- // (found by mapping the visible screen corners back into the page). Sides round- // up as whole-page rasters do, so the last partial row and column get tiles.- let (dw, dh) = (device_pixels(pw_pt, scale), device_pixels(ph_pt, scale));- // Adaptive tile side for this zoom and page, within the GPU texture limit:- // a zoomed viewport or a giant sheet is covered by a few large tiles- // instead of many small ones, and each tile costs one full page interpret.- // Never zero (u32 division below).- let ts = tile_side(scale, dw.max(dh)).min(max_side as u32).max(64);- let vis = r.intersect(visible);- let corners = [vis.left_top(), vis.right_top(), vis.right_bottom(), vis.left_bottom()].map(|c| xf.screen_to_norm(c));- let (u0, u1) = corners.iter().fold((1.0f32, 0.0f32), |(a, b), c| (a.min(c.0), b.max(c.0)));- let (v0, v1) = corners.iter().fold((1.0f32, 0.0f32), |(a, b), c| (a.min(c.1), b.max(c.1)));- let (vx0, vy0) = ((u0.max(0.0) * dw as f32) as u32, (v0.max(0.0) * dh as f32) as u32);- let (vx1, vy1) = (((u1.min(1.0) * dw as f32).ceil() as u32).min(dw), ((v1.min(1.0) * dh as f32).ceil() as u32).min(dh));- // Tiles of earlier zooms first, stretched, the nearest scale last (on top):- // until the current tiles arrive, a zoom shows them rather than the backdrop.- let mut older: Vec<(f32, u32, u32, &TextureHandle)> = view- .tiles- .iter()- .filter(|((p, t, _, _), _)| *p == i && *t != tag)- .map(|((_, t, ox, oy), tex)| (tag_scale(*t), *ox, *oy, tex))- .collect();- older.sort_by(|a, b| (b.0 / scale).ln().abs().total_cmp(&(a.0 / scale).ln().abs()));- for (s, ox, oy, tex) in older {- let (ow, oh) = (device_pixels(pw_pt, s) as f32, device_pixels(ph_pt, s) as f32);- let [w, h] = tex.size();- let (x, y) = (ox as f32, oy as f32);- xf.paint_image(painter, tex.id(), x / ow, y / oh, (x + w as f32) / ow, (y + h as f32) / oh);- }- // Visible tiles, nearest the viewport centre first: each tile costs a full- // page interpret, so the workers sharpen what is looked at before the edges.- let (vcx, vcy) = ((vx0 + vx1) as f32 / 2.0, (vy0 + vy1) as f32 / 2.0);- let mut coords: Vec<(u32, u32)> = Vec::new();- for ty in vy0 / ts..=(vy1.saturating_sub(1)) / ts {- for tx in vx0 / ts..=(vx1.saturating_sub(1)) / ts {- coords.push((tx, ty));- }- }- coords.sort_by(|a, b| {- let da = ((a.0 * ts + ts / 2) as f32 - vcx).abs() + ((a.1 * ts + ts / 2) as f32 - vcy).abs();- let db = ((b.0 * ts + ts / 2) as f32 - vcx).abs() + ((b.1 * ts + ts / 2) as f32 - vcy).abs();- da.total_cmp(&db)- });- for (tx, ty) in coords {- let (x, y) = (tx * ts, ty * ts);- let (w, h) = (ts.min(dw.saturating_sub(x)), ts.min(dh.saturating_sub(y)));- if w == 0 || h == 0 {- continue;- }- wanted.push((i, scale, tag, Some(Tile { x, y, w, h })));- if let Some(tex) = view.tiles.get(&(i, tag, x, y)) {- let (fw, fh) = (dw as f32, dh as f32);- xf.texel_aligned([dw as usize, dh as usize], ppp).paint_image(- painter,- tex.id(),- x as f32 / fw,- y as f32 / fh,- (x + w) as f32 / fw,- (y + h) as f32 / fh,- );- }- }- }- }- view.text_background.paint(painter, &xf, i, view.line_editor.as_ref(), view.content.draft.as_ref());- if editing_content {- view.move_background.paint(painter, &xf, i, info, &view.content, pointer);- }- if view.show_page_gaps {- painter.rect_stroke(r, CornerRadius::ZERO, Stroke::new(0.5, t.border.gamma_multiply(0.8)), egui::StrokeKind::Outside);- }-- // Comments: tools, selection, moving and resizing come before text selection.- let pcx = comments::PageCx { page: i, xf: &xf, ptr: &ptr, info, tool, prefs, allowed, hidden: comments_hidden, redact_mark };- if let QuickTool::Measure(measure_tool) = tool {- crate::measure_ui::page_input(ui, &resp, doc, view, &pcx, measure_tool, units);- }-- // Form fields take clicks first with the Select tool (as Acrobat fills fields in- // every viewing mode); then comments; then text selection.- if let QuickTool::Stamp(kind) = tool- && allowed- && let Some(p) = ptr.within(xf.rect)- {- view.cursor.claim(Layer::ToolArea, egui::CursorIcon::Crosshair);- if resp.clicked() {- // Centred on the click, upright as the page is shown.- let (vx, vy) = xf.screen_to_view(p);- let (w, h) = kind.size();- let corners = [(vx as f64 - w / 2.0, vy as f64 - h / 2.0), (vx as f64 + w / 2.0, vy as f64 + h / 2.0)];- let u: Vec<[f32; 2]> = corners.iter().map(|(x, y)| info.pages[i].view_to_user(*x as f32, *y as f32)).collect();- let rect = [u[0][0].min(u[1][0]) as f64, u[0][1].min(u[1][1]) as f64, u[0][0].max(u[1][0]) as f64, u[0][1].max(u[1][1]) as f64];- let by = (kind.group() == pdfcraft_engine::StampGroup::Dynamic).then(|| by_line.clone());- let shape = pdfcraft_engine::Shape::Stamp { rect, stamp: kind, by };- view.pending_edit = Some(pdfcraft_engine::Edit::AddAnnotation(pdfcraft_engine::NewAnnotation {- page: i,- style: pdfcraft_engine::Style::default_for(&shape),- shape,- contents: String::new(),- author: author.clone(),- }));- stamp_placed = true;- }- }- if let Some(cs) = custom_stamp.as_ref()- && allowed- && let Some(p) = ptr.within(xf.rect)- {- view.cursor.claim(Layer::ToolArea, egui::CursorIcon::Crosshair);- if resp.clicked() {- // Centred on the click at its natural size (the engine sizes it).- let (vx, vy) = xf.screen_to_view(p);- let u = info.pages[i].view_to_user(vx, vy);- let (x, y) = (u[0] as f64, u[1] as f64);- view.pending_edit = Some(pdfcraft_engine::Edit::AddCustomStamp {- page: i,- rect: [x, y, x, y],- name: cs.name.clone(),- file: pdfcraft_engine::MarkFile { name: cs.file.clone(), bytes: cs.data.clone(), page: cs.page },- author: author.clone(),- });- stamp_placed = true;- }- }- // Over a mark already placed, the Fill & Sign tool picks it up (comments, below).- if let QuickTool::Fill(ft) = tool- && allowed- && !comments::fill_grabs(&pcx, view)- {- match crate::fill_sign::page_input(- ui,- &resp,- &xf,- &ptr,- i,- info,- ft,- app.fill_text_size,- view,- signature.as_ref(),- initials.as_ref(),- &mut app.signature_preview,- &author,- &date_text,- ) {- Some(crate::fill_sign::FillAction::Edit(e)) => view.pending_edit = Some(*e),- Some(crate::fill_sign::FillAction::Signature(e)) => {- view.pending_edit = Some(*e);- view.fill_signature_page = Some(i);- }- Some(crate::fill_sign::FillAction::CreateSignature) => open_signature = true,- Some(crate::fill_sign::FillAction::CreateInitials) => open_initials = true,- Some(crate::fill_sign::FillAction::Refused(why)) => refused = Some(why),- None => {}- }- }- if matches!(tool, QuickTool::SignArea { .. }) {- crate::sign_ui::page_input(ui, &resp, &xf, &ptr, i, info, view);- }- if matches!(tool, QuickTool::MarqueeZoom | QuickTool::Snapshot) {- crate::zoom_snap::page_input(ui, &resp, &xf, &ptr, i, view);- }- if tool == QuickTool::EnhanceCamera {- crate::camera_ui::page_input(&resp, &xf, &ptr, i, view, can_modify);- }- if tool == QuickTool::Crop && crate::crop::page_input(ui, &resp, &xf, &ptr, i, info, view, can_crop) {- view.current = i;- open_boxes = true;- }- let on_field = if preparing {- let field_tool = match tool {- QuickTool::Field(f) => Some(f),- _ => None,- };- // While a table is being set up, nothing else is drawn or moved.- let allowed = can_modify && table_preview.is_none() && open_table.is_none();- let o = crate::prepare::page_input(ui, &resp, &xf, &ptr, i, info, &form, field_tool, allowed, view);- field_props |= o.properties;- field_placed |= o.placed;- open_table = open_table.or(o.table);- o.consumed || field_tool.is_some()- } else {- tool == QuickTool::Select- && !(editing_content && can_modify && crate::content_ui::select_grabs(&xf, &ptr, i, info, &added, view))- && !comments::select_grabs(&pcx, view)- && crate::forms_ui::page_input(ui, &resp, &xf, &ptr, i, info, &form, can_fill, view)- };- // Redact draws boxes off text; so does Highlight (an area highlight, as in Acrobat).- let area_tool = tool == QuickTool::Redact && can_modify || tool == QuickTool::Comment(comments::CommentTool::Highlight) && allowed;- let boxing = area_tool && {- let text = view.page_text(i);- let over_text = |p: Pos2| {- let (vx, vy) = xf.screen_to_view(p);- text.as_ref().is_some_and(|t| t.glyphs.iter().any(|g| vx >= g.rect[0] && vx <= g.rect[2] && vy >= g.rect[1] && vy <= g.rect[3]))- };- crate::redact_ui::page_input(&resp, &xf, &ptr, i, info, over_text, view)- };- let image_owns_pointer = tool == QuickTool::EditText && crate::edit_text_ui::image_owns_pointer(ui, &xf, &ptr, i, info, view);- let on_objects =- !image_owns_pointer && tool == QuickTool::EditText && can_modify && crate::object_ui::page_input(ui, &resp, &xf, &ptr, i, doc, view);- let lines = if matches!(tool, QuickTool::AddText | QuickTool::EditText) && can_modify {- let generation = doc.edit_generation();- match view.edit_lines.get(&i) {- Some((g, l)) if *g == generation => l.clone(),- _ => {- let l = doc.text_blocks(i);- view.edit_lines.insert(i, (generation, l.clone()));- l- }- }- } else {- Vec::new()- };- let over_source = tool == QuickTool::AddText- && pointer.is_some_and(|p| {- !crate::content_ui::hits_added(&xf, info, i, &added, p)- && lines.iter().any(|line| xf.user_rect(info, i, line.rect.map(|v| v as f32)).expand(2.0).contains(p))- });- let source_blocked = over_source && view.content.hold_blocked();- if over_source && resp.clicked() && !source_blocked {- if let Some(edit) = view.content.finish_draft(&added) {- view.pending_edit = Some(edit);- }- view.content.selected = None;- }- let on_content = !on_objects && editing_content && can_modify && {- source_blocked- || crate::content_ui::page_input(- &resp,- &xf,- &ptr,- i,- info,- &added,- tool == QuickTool::AddText && !over_source,- matches!(tool, QuickTool::AddText | QuickTool::EditText),- &text_style,- view,- )- || tool == QuickTool::AddText && !over_source- };- // Added content owns its gesture; its source text must not queue a second edit.- // Edit text & images boxes every paragraph and image whenever the tool is on. Only the- // input waits while selected objects or added content own the pointer, or while page- // input is blocked (another tab, a dialog, the window unfocused): the boxes stay drawn- // instead of vanishing until the pointer comes back.- let others_own_pointer = on_objects || on_content;- let on_edit_text = (tool == QuickTool::EditText || over_source) && can_modify && {- let generation = doc.edit_generation();- let images = match view.edit_images.get(&i) {- Some((g, l)) if *g == generation => l.clone(),- _ => {- let l = doc.page_images(i);- view.edit_images.insert(i, (generation, l.clone()));- l- }- };- // Editable text takes precedence over background/overlapping artwork. Both- // inventories are painted every frame, even when text owns the pointer.- let text_used =- crate::edit_text_ui::page_input(ui, &resp, &xf, &ptr, i, doc, &lines, view, !others_own_pointer && !image_owns_pointer);- let image_used = crate::edit_text_ui::image_input(- ui,- &resp,- &xf,- &ptr,- i,- info,- &images,- view,- &mut image_action,- !others_own_pointer && (image_owns_pointer || !text_used),- );- !others_own_pointer && (text_used || image_used)- };- let on_link = tool == QuickTool::Link && can_modify && crate::link_ui::page_input(ui, &resp, &xf, &ptr, i, info, &doc_links, view);- if tool == QuickTool::Select- && resp.secondary_clicked()- && can_modify- && let Some(p) = pointer.filter(|p| xf.rect.contains(*p))- && let Some(l) = doc.links().iter().find(|l| l.page == i && crate::link_ui::screen_rect(&xf, info, i, l.rect).expand(2.0).contains(p))- {- view.links.context = Some((i, l.index));- }- let consumed = on_objects || on_edit_text || on_link || on_content || boxing || on_field || comments::page_input(ui, &resp, &pcx, view);-- let preview_target =- (matches!(tool, QuickTool::Select | QuickTool::Fill(_)) && !comments_hidden).then_some(view.comments.selected).flatten();- view.signature_drag.prepare(ui.ctx(), doc, preview_target, scale);- view.signature_drag.paint(painter, &pcx, &view.comments, view.pending_edit.as_ref());-- // Any press on the page ends Select All of the document: text read or not, any tool,- // on a link too.- // A press that lands on something drawn over the page (a menu, a dialog) is not one.- if view.all_text && pressed_page == Some(i) {- view.all_text = false;- }- // Text layer: find matches, selection, I-beam and drag-to-select.- let to_screen = |g: [f32; 4]| xf.view_rect(g);- if let Some(text) = view.texts.get(&i).cloned() {- if let Some(f) = &view.find {- for (k, (mp, range)) in f.matches.iter().enumerate() {- if *mp != i {- continue;- }- let current = f.current == Some(k);- for lr in text.line_rects(range.clone()) {- let fill = if current {- Color32::from_rgba_unmultiplied(255, 140, 0, 110)- } else {- Color32::from_rgba_unmultiplied(255, 214, 0, 90)- };- painter.rect_filled(to_screen(lr).expand(1.0), CornerRadius::same(2), fill);- }- }- }- if view.all_text {- for lr in text.line_rects(0..text.glyphs.len()) {- painter.rect_filled(to_screen(lr), CornerRadius::same(1), Color32::from_rgba_unmultiplied(0x3A, 0x7B, 0xF0, 70));- }- }- if let Some(sel) = view.selection.filter(|s| s.page == i) {- for lr in sel.rects(&text) {- painter.rect_filled(to_screen(lr), CornerRadius::same(1), Color32::from_rgba_unmultiplied(0x3A, 0x7B, 0xF0, 70));- }- // The rectangle being drawn, as Acrobat shows it while column-selecting.- if let Span::Column { rect } = sel.span- && resp.dragged()- {- let outline = Stroke::new(1.0, Color32::from_rgb(0x3A, 0x7B, 0xF0));- painter.rect_stroke(to_screen(rect), CornerRadius::ZERO, outline, egui::StrokeKind::Middle);- }- }- if selects_text- && !consumed- && let Some(p) = pointer.filter(|p| r.contains(*p))- {- let (vx, vy) = xf.screen_to_view(p);- let over_text = text.glyphs.iter().any(|g| vx >= g.rect[0] && vx <= g.rect[2] && vy >= g.rect[1] && vy <= g.rect[3]);- let over_link = info.links.iter().any(|l| l.page == i && xf.user_rect(info, i, l.rect).contains(p));- // Column select (#740): the Column select tool, or Alt (Option on macOS) held- // while a drag starts, as in Acrobat.- let column = tool == QuickTool::ColumnSelect || ui.input(|inp| inp.modifiers.alt);- // A press on a link selects nothing (it is the link's), so no cursor here says- // it would.- if column && !over_link {- view.cursor.claim(Layer::Text, egui::CursorIcon::Crosshair);- } else if over_text && !over_link {- view.cursor.claim(Layer::Text, egui::CursorIcon::Text);- }- // The pages' press, kept when its release came in the same frame (#2100): it- // still starts multi-click selection.- let press_here = ptr.origin.is_some_and(|o| r.contains(o));- let pressed = ptr.pressed().is_some();- if pressed && press_here && !over_link {- let now = ui.input(|inp| inp.time);- // The same limits egui uses to count clicks on release.- let (max_delay, max_dist) = ui.ctx().options(|o| (o.input_options.max_double_click_delay, o.input_options.max_click_dist));- let is_consecutive =- now - view.last_press_time <= max_delay && view.last_press_pos.is_some_and(|pos| pos.distance(p) <= max_dist);- view.clicks = if is_consecutive { view.clicks.saturating_add(1) } else { 1 };- view.last_press_time = now;- view.last_press_pos = Some(p);-- // Multi-click highlights immediately on pointer press instead of release (#1024).- let clicks = if view.clicks > 2 && tool != QuickTool::Select { 1 } else { view.clicks };- if clicks >= 2 && over_text {- let span = text.nearest(vx, vy).and_then(|a| click_unit(&text, clicks, a));- if let Some((first, last)) = span {- view.selection = Some(Selection::run(i, first, last));- }- }- }- if resp.drag_started() && press_here && !over_link {- // 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;- let origin = ptr.origin.unwrap_or(p);- let (ox, oy) = xf.screen_to_view(origin);- if view.clicks < 2 {- view.selection = if column {- Some(Selection { page: i, span: Span::Column { rect: [ox, oy, vx, vy] } })- } else {- text.nearest(ox, oy).map(|a| Selection::run(i, a, a))- };- }- }- let clicks = if view.clicks > 2 && tool != QuickTool::Select { 1 } else { view.clicks };- if resp.dragged()- && let Some(sel) = view.selection.as_mut().filter(|s| s.page == i)- {- match &mut sel.span {- // 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.- Span::Run { anchor, head } if clicks >= 2 => {- if let Some(h) = text.nearest(vx, vy)- && let Some((first, last)) = click_unit(&text, clicks, *anchor)- {- let (to_first, to_last) = click_unit(&text, clicks, h).unwrap_or((h, h));- (*anchor, *head) = if to_first < first { (last, to_first) } else { (first, to_last.max(last)) };- }- }- Span::Run { head, .. } => {- if let Some(h) = text.nearest(vx, vy) {- *head = h;- }- }- Span::Column { rect } => {- rect[2] = vx;- rect[3] = vy;- }- }- }- // A rectangle around no text selects nothing.- if resp.drag_stopped()- && view.selection.is_some_and(|s| s.page == i && matches!(s.span, Span::Column { .. }) && s.text(&text).is_empty())- {- view.selection = None;- }- // Quick clicks widen the selection: two a word, three the line, four the page.- // Release-based fallback for platforms or synthetic events that report double_clicked.- let release_clicks = if resp.triple_clicked() {- view.clicks.max(2).saturating_add(1)- } else if resp.double_clicked() {- view.clicks.max(2)- } else {- 0- };- if release_clicks > 0 {- view.clicks = release_clicks;- }- let clicks = if view.clicks > 2 && tool != QuickTool::Select { 1 } else { view.clicks };- // Only on the frame egui reports the multi-click: `view.clicks` outlives it, and- // acting on every frame re-selected the word as soon as a selection was cleared- // (a highlight made by the double-click left its word selected).- if release_clicks > 0 && clicks >= 2 && over_text {- if view.selection.is_none() {- let span = text.nearest(vx, vy).and_then(|a| click_unit(&text, clicks, a));- if let Some((first, last)) = span {- view.selection = Some(Selection::run(i, first, last));- }- }- } else if resp.clicked() && view.clicks < 2 && !over_link {- // ⇧-click extends a selection on this page to the click, keeping its- // anchor (#527). Otherwise (no shift, no selection on this page, or a- // column selection, which has no anchor glyph; a selection cannot yet- // span pages) a click clears the selection.- let shift = ui.input(|inp| inp.modifiers.shift);- match (view.selection.as_mut().filter(|s| shift && s.page == i).map(|s| &mut s.span), text.nearest(vx, vy)) {- (Some(Span::Run { head, .. }), Some(h)) => *head = h,- _ => view.selection = None,- }- }- }- }-- if tool == QuickTool::Select && !consumed {- crate::image_pick::page_input(&resp, &xf, i, info, doc, pointer, view);- }- crate::image_pick::drop_stale(doc, view);- crate::image_pick::paint(painter, &xf, i, info, view);- comments::page_after_text(&resp, &pcx, view);- if tool == QuickTool::Redact && can_modify {- crate::redact_ui::after_text(&resp, i, info, view);- }- if area_tool {- crate::redact_ui::paint(painter, i, view, pointer);- }- comments::paint_page(ui, painter, &pcx, view);- if editing_content {- crate::content_ui::paint_page(painter, &xf, i, info, &added, view, pointer);- }- if tool == QuickTool::EditText {- crate::object_ui::paint(painter, &xf, i, info, &view.objects);- }- if tool == QuickTool::EnhanceCamera {- crate::camera_ui::paint(painter, &xf, i, view);- }- if tool == QuickTool::Link {- crate::link_ui::paint(painter, &xf, i, info, &doc_links, view, pointer);- }- if preparing {- crate::prepare::paint_page(ui, painter, &xf, i, info, &form, view, pointer);- if let Some(preview) = &table_preview {- crate::field_table_ui::paint_preview(painter, &xf, i, preview);- }- if calc_order {- let selected = view.prepare.selected.as_ref().map(|(name, _)| name.as_str());- if let Some(name) =- crate::calc_order_ui::paint_page(painter, &xf, i, info, &form, &view.calc_order, generation, selected, pointer)- {- calc_hover = Some(name);- }- }- } else {- crate::forms_ui::paint_page(painter, &xf, i, info, &form, view, pointer);- }-- // Form-field highlight (Acrobat's "Highlight existing fields"); required fields get a- // red border. Radio buttons and round XFA check boxes are round, and so is theirs (as- // in Acrobat). Only what can be filled is marked: a read-only widget (its field's, or a- // radio button's own) is left as it is drawn.- if view.highlight_fields {- for f in form.iter() {- let required = f.has(pdfcraft_engine::field_flags::REQUIRED);- for w in f.widgets.iter().filter(|w| w.page == Some(i) && !w.hidden && !w.read_only) {- let r = w.rect;- let sr = xf.user_rect(info, i, [r[0] as f32, r[1] as f32, r[2] as f32, r[3] as f32]);- let tint = Color32::from_rgba_unmultiplied(0x6E, 0x8E, 0xF5, 48);- let (width, color) =- if required { (2.0, Color32::from_rgb(0xE3, 0x22, 0x22)) } else { (1.0, Color32::from_rgb(0x6E, 0x8E, 0xF5)) };- if w.round {- let radius = sr.width().min(sr.height()) / 2.0;- painter.circle_filled(sr.center(), radius, tint);- painter.circle_stroke(sr.center(), radius - width / 2.0, Stroke::new(width, color));- } else {- painter.rect_filled(sr, CornerRadius::same(1), tint);- painter.rect_stroke(sr, CornerRadius::same(1), Stroke::new(width, color), egui::StrokeKind::Inside);- }- }- }- }- // Links: the hand and the link's target, which count only for the tools that follow- // or edit links (`Layer::reached_by`). Tips draw above the palette, so none shows- // while it is open, even beside it.- if unobstructed && let Some(p) = pointer {- for l in info.links.iter().filter(|l| l.page == i) {- let sr = xf.user_rect(info, i, l.rect);- if sr.contains(p) {- let label = match &l.target {- LinkTarget::Page(n, _) => {- crate::i18n::fmt(tl!("Go to page {p}"), &[("p", info.pages.get(*n).map(|p| p.label.as_str()).unwrap_or("?"))])- }- LinkTarget::Uri(u) => u.clone(),- LinkTarget::SetLayers { .. } => tl!("Set layer visibility").to_string(),- LinkTarget::RemoteGoTo { file, .. } => file.clone(),- LinkTarget::Other(s) => crate::i18n::fmt(tl!("{s} action"), &[("s", s)]),- };- view.cursor.claim_with_tip(Layer::Link, egui::CursorIcon::PointingHand, Some(label));- if resp.clicked() && tool == QuickTool::Select && !consumed {- clicked_link = Some(l.target.clone());- }- }- }- }- // Comments say what they are with any tool, beside its cursor, as Acrobat's do.- comments::describe(&pcx, view);- for (mp, mr, mc) in &view.compare_marks {- if *mp == i {- let sr = xf.user_rect(info, i, *mr).expand(1.5);- painter.rect_filled(sr, CornerRadius::same(2), mc.gamma_multiply(0.28));- }- }- if let Some((fp, fr, t0)) = view.flash- && fp == i- {- let now = ui.input(|inp| inp.time);- let t0 = if t0 == 0.0 { now } else { t0 };- view.flash = Some((fp, fr, t0));- let age = (now - t0) as f32;- if age < 1.6 {- let a = ((1.6 - age) / 1.6 * 255.0) as u8;- let sr = xf.user_rect(info, i, fr).expand(4.0);- painter.rect_stroke(- sr,- CornerRadius::same(3),- Stroke::new(2.5, Color32::from_rgba_unmultiplied(0x1B, 0x63, 0xE0, a)),- egui::StrokeKind::Outside,- );- ui.ctx().request_repaint();- } else {- view.flash = None;- }- }- // Validation is viewer chrome over the signer's original artwork, which- // may still say "Signature Not Verified". These badges never enter document- // streams, image/text exports, vector printing or Print as Image.- for badge in signature_badges(&doc.signatures, i) {- let [x0, y0, x1, y1] = badge.rect;- let sr = xf.user_rect(info, i, [x0 as f32, y0 as f32, x1 as f32, y1 as f32]);- let (icon, color) = crate::sign_ui::signature_status_style(badge.status);- painter.rect_stroke(sr, CornerRadius::same(2), Stroke::new(1.5, color), egui::StrokeKind::Outside);- // A widget too small for the mark keeps its outline: the verdict still shows.- if sr.width() < 4.0 || sr.height() < 4.0 {- continue;- }- // Big enough to read at a glance, small enough to leave the signer's own- // text visible around it.- let side = (sr.width().min(sr.height()) * 0.8).clamp(24.0, 192.0);- let mark = Rect::from_center_size(sr.center(), vec2(side, side));- icons::paint(ui, mark, icon, side * 0.64, color);- // Overlapping widgets paint in order, so the topmost badge's verdict is the tip,- // with any tool; a link's or a comment's tip wins over any badge.- if pointer.is_some_and(|p| mark.expand(2.0).contains(p)) {- view.cursor.describe(Subject::SignatureBadge, badge.summary.to_string());- }- }- }- if calc_order {- view.calc_order.set_hover_page(calc_hover);- let selected = view.prepare.selected.as_ref().map(|(name, _)| name.as_str());- crate::calc_order_ui::paint_trace(ui, painter, visible, &view.calc_order, generation, selected);- }- // The pages' one cursor, from the claim on the highest layer the tool reaches, and the tip.- hover_text = pointer.filter(|_| unobstructed).zip(view.cursor.resolve(ui.ctx(), tool));- // ScrollArea ignores the wheel while any widget is dragged, so a text-selection drag- // scrolls the page itself (#721). After the page loop, so it keeps scrolling once the- // pointer leaves the selection's page for the gap or the next page; over the whole- // document area, like #759. Combine direct and smoothed motion in one request so mixed- // Point and Line events retain their full contribution.- if selection_wheel {- let smooth =- if view.precise_scroll_until == 0.0 { ui.input_mut(|input| std::mem::take(&mut input.smooth_scroll_delta)) } else { Vec2::ZERO };- let delta = precise_scroll + boost_extra + smooth;- if delta != Vec2::ZERO && delta.is_finite() {- ui.scroll_with_delta_animation(delta, egui::style::ScrollAnimation::none());- }- }- // 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.- if view.selection_drag- && navigation_enabled- && unobstructed- && !single_paging- && let Some(p) = ptr.pos- {- let dy = crate::autoscroll::edge_delta(p.y, avail, ui.input(|i| i.stable_dt));- if dy != 0.0 {- view.end_find_following();- ui.scroll_with_delta_animation(vec2(0.0, dy), egui::style::ScrollAnimation::none());- // Keep scrolling while the pointer rests there and sends no events.- ui.ctx().request_repaint();- }- }- // The page navigated to stays current while no page shows more of itself, so the next- // page step starts from it rather than from a page further down the screen (#188).- // It also stays current while it is wholly on screen: a short page (a cheque) gone to- // from the Pages panel shows less of itself than the tall page below it, and must not- // hand the highlight to that page.- if current_overlap >= best_overlap - TIE || current_overlap >= current_height - TIE {- current = view.current;- }- if let Some(p) = pressed_page {- current = p;- }- if view.continuous {- view.current = current;- }- resp.context_menu(|ui| {- // Preparing a form: the selected field's menu.- if preparing && let Some((name, wi)) = view.prepare.selected.clone() {- // Several fields: Align, Center, Distribute, Set Fields to Same Size.- if !view.prepare.also.is_empty() {- use crate::prepare::Arrange as A;- let others = view.prepare.also.clone();- let anchor = (name.clone(), wi);- let mut pick = |ui: &mut egui::Ui, op: A, label: &str| {- if ui.add_enabled(can_modify, egui::Button::new(tl!(label))).clicked() {- view.pending_edit = crate::prepare::arrange(&form, &anchor, &others, op);- ui.close();- }- };- ui.menu_button(tl!("Align"), |ui| {- pick(ui, A::AlignLeft, "Left");- pick(ui, A::AlignRight, "Right");- pick(ui, A::AlignTop, "Top");- pick(ui, A::AlignBottom, "Bottom");- pick(ui, A::AlignCenterV, "Center vertically");- pick(ui, A::AlignCenterH, "Center horizontally");- });- ui.menu_button(tl!("Distribute"), |ui| {- pick(ui, A::DistributeH, "Horizontally");- pick(ui, A::DistributeV, "Vertically");- });- ui.menu_button(tl!("Set Fields to Same Size"), |ui| {- pick(ui, A::SameHeight, "Height");- pick(ui, A::SameWidth, "Width");- pick(ui, A::SameSize, "Both");- });- ui.separator();- }- if ui.button(tl!("Properties…")).clicked() {- field_menu = Some(FieldMenu::Properties);- ui.close();- }- if ui.add_enabled(can_modify, egui::Button::new(tl!("Duplicate…"))).clicked() {- field_menu = Some(FieldMenu::Duplicate(name.clone()));- ui.close();- }- ui.separator();- let delete = if view.prepare.also.is_empty() { "Delete" } else { "Delete selected fields" };- if ui.add_enabled(can_modify, egui::Button::new(tl!(delete))).clicked() {- view.pending_edit = crate::prepare::delete_selected(view);- ui.close();- }- return;- }- if let Some((page, index)) = view.links.context {- if ui.button(tl!("Properties…")).clicked() {- view.links.open_existing = Some((page, index));- ui.close();- }- if ui.add_enabled(can_modify, egui::Button::new(tl!("Delete"))).clicked() {- view.pending_edit = Some(Edit::DeleteLink { page, index });- view.links.selected = None;- view.links.context = None;- ui.close();- }- ui.separator();- if ui.add_enabled(can_modify, egui::Button::new(tl!("Remove all links"))).clicked() {- view.pending_edit = Some(Edit::RemoveLinks { pages: None });- view.links.selected = None;- view.links.context = None;- ui.close();- }- return;- }- if view.comments.selected.is_none() {- let selected = view.selected_text().is_some_and(|t| !t.is_empty());- let key = crate::commands::shortcut_label(ui.ctx(), crate::commands::COPY);- if ui.add_enabled(can_copy && selected, egui::Button::new(tl!("Copy")).shortcut_text(key)).clicked() {- copy_selected = true;- ui.close();- }- ui.separator();- }- // Over a picture (and no comment): Copy Image, as in Acrobat's page menu.- let mut copy_image = None;- if view.comments.selected.is_none()- && let Some((page, at)) = view.comments.context_at- {- // The page's content is parsed once per right-click, not on every frame the menu is open.- let key = egui::Id::unique("copy-image-under-menu");- let cached = ui.data(|d| d.get_temp::<(usize, [f64; 2], Option<usize>)>(key)).filter(|c| c.0 == page && c.1 == at);- let hit = match cached {- Some(c) => c.2,- None => {- let hit = doc.page_image_at(page, at);- ui.data_mut(|d| d.insert_temp(key, (page, at, hit)));- hit- }- };- if let Some(image) = hit {- if ui.button(tl!("Copy Image")).clicked() {- copy_image = Some(comments::CanvasAction::CopyImage(page, image));- ui.close();- }- if ui.button(tl!("Copy Image in Original Format")).clicked() {- copy_image = Some(comments::CanvasAction::CopyImageFile(page, image));- ui.close();- }- ui.separator();- }- }- canvas_action = comments::context_menu(ui, view, info, prefs, allowed, can_modify).or(copy_image);- });- (wanted, visible_now)- });- view.single_edges = visible_pages.first().copied().filter(|_| !view.continuous).map(|page| {- // At the top once the page's top edge shows where going to a page puts it (a gap- // below the window's top). Within a point, as for wheel paging, so layout rounding- // can't hide an edge.- let max_y = (out.content_size.y - out.inner_rect.height()).max(0.0);- (page, out.state.clamped_offset().y <= MARGIN - view.page_gap() + 1.0, out.state.clamped_offset().y >= max_y - 1.0)- });-- view.viewport_screen = out.inner_rect;- view.auto_scroll.paint(ui, avail);- if unobstructed && matches!(tool, QuickTool::Select | QuickTool::ColumnSelect) {- copy_selected |= selection_actions(ui, avail, view, info, prefs, allowed && !comments_hidden, can_copy);- }-- // Collect all main-page demand, including cached surfaces, for byte admission later.- // Pan-settle debounce for tiled pages: each tile costs a full page interpret, so holding- // fresh tiles back while the scroll offset is still moving keeps a drag on the stretched- // backdrop/older tiles instead of queueing a storm of interprets (one per frame) that- // the workers cannot cancel mid-operator. Fresh tiles go out once the pan settles;- // pages with nothing on screen yet still queue.- let scroll_offset = out.state.clamped_offset();- // The document ScrollArea's own scroll surfaces move the offset without the wheel deltas- // above: its two scroll-bar tracks/handles and, for touch or the Hand tool, its drag- // background. The output gives us the area id, and egui's pinned ScrollArea registers those- // widgets under `id.with(0)` (horizontal), `id.with(1)` (vertical) and `id.with("area")`.- // Ask for their exact responses instead of treating any held drag as scrolling: a text- // selection, a panel splitter or another widget's drag must not excuse the programmatic jump- // a search flash makes, while a track click (which moves the offset with no pointer motion)- // must still count as the reader scrolling.- let scroll_surface = |id: egui::Id| ui.ctx().read_response(id).is_some_and(|r| r.is_pointer_button_down_on() || r.dragged() || r.clicked());- let pointer_scrolling = scroll_surface(out.id.with(0usize)) || scroll_surface(out.id.with(1usize)) || scroll_surface(out.id.with("area"));- if pointer_scrolling && (scroll_offset - view.last_scroll).length() > 2.0 {- view.end_find_following();- }- let now_settle = ui.input(|i| i.time);- if (scroll_offset - view.last_scroll).length() > 2.0 {- view.pan_hold_until = now_settle + 0.25;- ui.ctx().request_repaint_after(std::time::Duration::from_millis(280));- }- if glide != Vec2::ZERO {- view.fling.moved((scroll_offset - view.last_scroll).length() > 0.01);- }- view.last_scroll = scroll_offset;- let pan_held = now_settle < view.pan_hold_until;- let (mut wanted, visible_now) = out.inner;- // Single-page and two-page views draw only the current row, so the next one was first asked- // for on the turn and showed blank paper until it rendered. Prefetch the rows either side,- // as continuous scrolling does for the pages just off screen.- if !view.continuous- && let (Some(&first), Some(&last)) = (visible_pages.first(), visible_pages.last())- {- let n = if view.layout == PageLayout::Single { 1 } else { 2 };- let max_side = ui.ctx().input(|inp| inp.max_texture_side) as f32;- for i in (last.saturating_add(1)..=last.saturating_add(n)).chain(first.saturating_sub(n)..first) {- let Some(p) = info.pages.get(i).filter(|_| !view.errors.contains_key(&i)) else { continue };- // As drawn: the whole page at this scale, or the backdrop of a tiled page.- let side = p.width.max(p.height).max(1.0);- wanted.push(if side * scale > TILE_THRESHOLD.min(max_side) {- let bs = BASE_SIDE.min(max_side) / side;- (i, bs, scale_tag(bs), None)- } else {- (i, scale, tag, None)- });- }- }- let cur = view.current;- wanted.sort_by_key(|w| (!visible_now.contains(&w.0), w.0.abs_diff(cur), w.3.is_some()));- // Tiles of far-away pages are useless: free them. Tiles of an earlier zoom stay for a page- // that is on screen, whether or not the page is tiled at this zoom (#2196): a zoom out below- // the tiling threshold used to drop the tiles of the zoom just left, so coming back to it- // was a cold miss and the page re-blurred through the backdrop while every tile was- // interpreted again. `OLD_TILES` still bounds how many older tiles are kept, nearest scale- // first, and admission keeps them inside `TILE_BYTES`.- let missing: HashSet<usize> = wanted.iter().filter(|w| w.3.is_some()).map(|w| w.0).collect();- let on_screen: HashSet<usize> = visible_now.iter().copied().collect();- view.tiles.retain(|(p, t, _, _), _| p.abs_diff(cur) <= 2 && (*t == tag || missing.contains(p) || on_screen.contains(p)));- let mut older: Vec<(f32, (usize, u64, u32, u32))> =- view.tiles.keys().filter(|k| k.1 != tag).map(|k| ((tag_scale(k.1) / scale).ln().abs(), *k)).collect();- // Tiles of earlier zooms are kept nearest scale first, and bounded by count *and* bytes: a- // large scan renders a tile up to 4096² (about 67 MiB), so a count alone let a few tiles of- // a few zooms run far past the tile allowance. #2196 keeps a zoom already visited, which- // makes that reachable in ordinary zooming, so the byte bound has to be here too.- older.sort_by(|a, b| a.0.total_cmp(&b.0));- let mut kept = 0usize;- let mut kept_bytes = 0usize;- let mut drop: Vec<(usize, u64, u32, u32)> = Vec::new();- for (_dist, key) in older {- let bytes = view.tiles.get(&key).map_or(0, texture_bytes);- if kept >= OLD_TILES || kept_bytes.saturating_add(bytes) > TILE_BYTES {- drop.push(key);- } else {- kept = kept.saturating_add(1);- kept_bytes = kept_bytes.saturating_add(bytes);- }- }- for key in drop {- view.tiles.remove(&key);- }- let mut queue: Vec<RenderRequest> = wanted- .iter()- .map(|&(page, wanted_scale, wanted_tag, tile)| RenderRequest {- page,- kind: RequestKind::Pixels,- tile,- scale: wanted_scale,- tag: wanted_tag,- // The low-res backdrop under tiles is a preview: tiny images are skipped for it.- // It is the whole-page request whose scale is not the current one; sharp tiles- // and whole-page finals always draw everything.- preview: tile.is_none() && (wanted_scale != scale || wanted_tag != tag),- })- .collect();- // While the zoom or pan is settling, hold back sharp re-renders of pages that already- // show something (a stale whole-page raster or older tiles, drawn stretched): each new- // scale would cancel the running full-page interpret and restart it from scratch, and- // each pan frame would queue a storm of full-page tile interprets.- // Pages with nothing on screen yet still queue, so panning to a fresh page draws it.- if sharp_held || pan_held {- let main_tag = tag;- queue.retain(|req| {- // Fast pages render straight through: the hold only protects heavy pages- // whose full-page interpret costs seconds.- if !view.slow_pages.contains(&req.page) {- return true;- }- if req.tile.is_some() {- let has_current_tile = view.tiles.keys().any(|(p, t, _, _)| *p == req.page && *t == req.tag);- if has_current_tile {- return false;- }- let has_any_surface = view.pages.contains_key(&req.page) || view.tiles.keys().any(|(p, _, _, _)| *p == req.page);- !has_any_surface- } else if req.tag != main_tag {- // The low-res backdrop under tiles is zoom-independent: let it through,- // it is the stretched surface the hold relies on.- true- } else {- // The stale raster stays stretched until the zoom or pan settles; a page with- // nothing on screen yet still renders.- !view.pages.contains_key(&req.page)- }- });- }- // Text layers: visible pages for selection, every page while a search is active. (Select All- // of the document needs no more: shown pages highlight as their text comes, and Copy reads- // 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<usize> = if hand { Vec::new() } else { visible_now.iter().copied().filter(need_text).collect() };- if view.find.as_ref().is_some_and(|f| !f.case_query.trim().is_empty()) {- let n = info.pages.len();- let rest: Vec<usize> = (0..n).map(|k| (cur + k) % n).filter(need_text).filter(|p| !text_pages.contains(p)).collect();- text_pages.extend(rest);- }- queue.extend(text_pages.into_iter().map(|page| RenderRequest {- page,- kind: RequestKind::Text,- tile: None,- scale: 1.0,- tag: TEXT_TAG,- preview: false,- }));- view.frame_queue = queue;- view.frame_visible = visible_now.iter().copied().collect();-- if let Some((pos, text)) = hover_text {- // Click-through, as a tooltip is: the pages lose the pointer under anything that isn't.- let tip = egui::Area::new(egui::Id::unique("canvas-hover")).order(egui::Order::Tooltip).interactable(false);- tip.fixed_pos(pos + vec2(14.0, 16.0)).show(ui.ctx(), |ui| {- egui::Frame::popup(ui.style()).show(ui, |ui| {- ui.set_max_width(320.0);- ui.label(text);- });- });- }- find_bar(view, info.pages.len(), avail, ui, &t);- page_size_hint(view, info, units, avail, unobstructed, ui, &t);- if tool == QuickTool::EnhanceCamera {- crate::camera_ui::bar(ui.ctx(), view, avail, &t, can_modify);- }- if let Some(e) = comments::composer(ui.ctx(), view, info, prefs) {- view.pending_edit = Some(e);- }- if let Some(e) = crate::edit_text_ui::overlay(ui.ctx(), view, info) {- view.pending_edit = Some(e);- }- let text_box = crate::forms_ui::text_box(doc, view, &form);- if let Some(e) = crate::forms_ui::overlay(ui.ctx(), view, info, &form, text_box.as_ref(), today) {- view.pending_edit = Some(e);- }- if let Some(e) = crate::fill_sign::type_box(ui.ctx(), view, info, &author) {- view.pending_edit = Some(e);- }- let (typed, text_done) = crate::content_ui::editor(ui.ctx(), view, info, &added);- if typed.is_some() {- view.pending_edit = typed;- }- if let Some(why) = view.objects.notice.take() {- refused = Some(why);- }- let form_notice = view.forms.notice.take();- // One crop, then back to selecting (as Acrobat does).- let cropped = view.pending_edit.as_ref().is_some_and(|e| matches!(e, pdfcraft_engine::Edit::SetPageBox { .. }));- let mut tool = app.quick_tool;- comments::keys(ui.ctx(), view, &mut tool, allowed);- if preparing {- crate::prepare::keys(ui.ctx(), view);- }- if editing_content {- crate::content_ui::keys(ui.ctx(), view);- }- if tool == QuickTool::Link {- crate::link_ui::keys(ui.ctx(), view);- } else {- view.links.selected = None;- }- if stamp_placed {- tool = QuickTool::Select;- }- // Text: each click on the page starts a box (#74); Done in the editor goes back to selecting.- if text_done && tool == QuickTool::AddText {- tool = QuickTool::Select;- }- // One field, then back to selecting (Acrobat's default without "Keep tools pinned").- if field_placed {- tool = QuickTool::Select;- }- if matches!(field_menu, Some(FieldMenu::Properties)) {- field_props = true;- }- let field_props = field_props.then(|| view.prepare.selected.clone()).flatten();- match canvas_action {- Some(comments::CanvasAction::Edit(e)) => view.pending_edit = Some(*e),- // `choose_right_panel` would borrow all of `app` while `view` is held; same effect.- Some(comments::CanvasAction::OpenComments) => {- app.right = Some(RightPanel::Comments);- app.comments_panel_closed = false;- }- Some(comments::CanvasAction::Properties(p, i)) => open_props = Some((p, i)),- Some(comments::CanvasAction::CopyImage(p, i)) => image_action = Some(crate::edit_text_ui::ImageAction::Copy(p, i)),- Some(comments::CanvasAction::CopyImageFile(p, i)) => image_action = Some(crate::edit_text_ui::ImageAction::CopyFile(p, i)),- None => {}- }- // Full screen: the click turns the page unless it did something else first. It waits out the- // double-click time: turning on the first click's release sent a double-click's second click,- // meant to select a word, to the next page (review on #2070). A selection cancels it, and so- // do a link followed meanwhile and leaving full screen; a double-click elsewhere still turns- // once.- let now = ui.input(|i| i.time);- if present_click && clicked_link.is_none() && view.selection.is_none() && view.clicks < 2 {- let delay = ui.ctx().options(|o| o.input_options.max_double_click_delay);- view.present_turn = Some((now + delay, !present_back));- }- if let Some((due, forward)) = view.present_turn {- if clicked_link.is_some() || view.selection.is_some() || view.presentation.is_none() {- view.present_turn = None;- } else if now >= due {- view.present_turn = None;- view.step_page(forward);- } else {- ui.ctx().request_repaint_after(std::time::Duration::from_secs_f64((due - now).max(0.0)));- }- }- match clicked_link {- Some(LinkTarget::Page(p, dest)) => view.go_to_dest(p, dest, info),- Some(LinkTarget::Uri(u)) => app.request_document_url(&u, crate::LinkOrigin::Link),- Some(LinkTarget::SetLayers { changes, preserve_rb }) => set_layers(app, index, &changes, preserve_rb),- Some(LinkTarget::RemoteGoTo { file, destination, .. }) => remote_open = Some((view.id, file, destination)),- Some(LinkTarget::Other(s)) => app.notify_fmt("This PDF uses the unsupported {s} action.", &[("s", &s)]),- None => {}- }- if tool == QuickTool::Crop && cropped {- tool = QuickTool::Select;- }- if let Some(done) = app.views[index].marquee_done.take() {- app.finish_marquee(index, done);- }- // A signature rectangle was drawn, or an empty signature field clicked.- let drawn = app.views[index].sign.drawn.take();- if let (Some((page, rect)), QuickTool::SignArea { certify }) = (drawn, tool) {- tool = QuickTool::Select;- app.quick_tool = tool;- app.start_signing(page, Some(rect), None, certify.then_some(2));- }- if let Some(field) = app.views[index].sign.field.take() {- let signed = app.session.get(app.views[index].id).is_some_and(|d| d.signatures.iter().any(|s| s.field == field && s.signed));- if signed {- app.right = Some(RightPanel::Signatures);- if !app.sig_expanded.contains(&field) {- app.sig_expanded.push(field);- }- } else {- let page = app.views[index].current;- app.start_signing(page, None, Some(field), None);- }- }- app.quick_tool = tool;- if let Some((page, at)) = app.views[index].comments.attach_at.take() {- app.attach_file_comment(page, at);- }- if let Some((p, i)) = open_props {- app.open_comment_props(p, i);- }- if let Some((p, i)) = app.views[index].comments.default_request.take() {- app.make_comment_default(p, i);- }- if let Some((p, i, open)) = app.views[index].comments.attachment_request.take() {- let doc = app.views[index].id;- app.comment_attachment_action(doc, p, i, open);- }- if let Some((name, w)) = field_props {- app.open_field_props(&name, w);- }- if let Some(FieldMenu::Duplicate(name)) = field_menu {- let pages = app.session.get(app.views[index].id).map_or(1, |d| d.info.pages.len());- app.duplicate_draft = Some(crate::DuplicateDraft { name, all: true, from: 1, to: pages });- app.dialog = Some(crate::Dialog::DuplicateField);- }- if let Some((page, rect)) = app.views[index].links.open_new.take() {- app.open_link_props(page, Some(rect), None);- }- 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() {- 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,- })- } else {- app.redact_prefs.mark(page, quads, &author)- });- }- match image_action {- Some(crate::edit_text_ui::ImageAction::Replace(page, index)) => app.replace_page_image_dialog(page, index),- Some(crate::edit_text_ui::ImageAction::Save(page, index)) => app.save_page_image(page, index),- Some(crate::edit_text_ui::ImageAction::Copy(page, index)) => {- app.copy_page_image(page, index);- }- Some(crate::edit_text_ui::ImageAction::CopyFile(page, index)) => app.copy_page_image_file(page, index),- Some(crate::edit_text_ui::ImageAction::Cut(page, image)) => {- app.views[index].image_selection = None;- app.cut_page_image(page, image);- }- Some(crate::edit_text_ui::ImageAction::Redact(page, index)) => app.redact_page_image(page, index),- Some(crate::edit_text_ui::ImageAction::Link(page, index)) => app.link_page_image(page, index),- Some(crate::edit_text_ui::ImageAction::Recognize(page)) => app.recognize_text_on_page(page),- None => {}- }- if let Some(why) = refused {- app.notify_error(why);- }- if open_signature || open_initials {- app.signature_draft = crate::fill_sign::SigDraft::new(open_initials, &app.comment_prefs.author);- app.dialog = Some(crate::Dialog::Signature);- }- if open_boxes {- app.boxes_draft.range = crate::pageboxes::Range::Current;- app.boxes_draft.seeded = None;- app.dialog = Some(crate::Dialog::PageBoxes);- }- if let Some((page, rect)) = open_table {- app.field_table_draft = Some(crate::field_table_ui::FieldTableDraft::new(app.views[index].id, page, rect, &form, generation));- app.dialog = Some(crate::Dialog::FieldTable);- // The window lasts while the form is prepared. Drawn with the tool picked but its panel- // closed, the tool goes back to Select above, so the panel opens to keep it prepared.- app.left = crate::LeftPanel::Tool("form");- app.reveal_tools();- }- if let Some(n) = form_notice {- match n {- crate::forms_ui::FormNotice::Security => app.notify_tr("The document's security settings don't allow filling in form fields"),- crate::forms_ui::FormNotice::ReadOnly(name) => app.notify_fmt("{name} is read-only", &[("name", &name)]),- crate::forms_ui::FormNotice::NoAction(name) => app.notify_fmt("{name} has no action", &[("name", &name)]),- }- }- if let Some((name, action)) = app.views[index].forms.button.take() {- run_button(app, index, &name, action);- }- if copy_selected {- app.execute("edit.copy");- }- // Read mode hides the tools (#2646), and full screen is the page and nothing else (#1459);- // the quick tools come back with the window.- if app.mode != crate::Mode::Read && !app.full_screen {- quick_bar(app, avail, ui);- }- if let Some((source, file, destination)) = remote_open {- app.open_remote_link(source, file, destination);- }- }-- #[derive(Clone, Copy)]- enum SelectionAction {- Note,- Markup(comments::CommentTool),- Replace,- Copy,- }-- /// Actions on an existing text selection, next to the selected words.- fn selection_actions(- ui: &mut egui::Ui,- viewport: Rect,- view: &mut DocView,- info: &DocInfo,- prefs: &comments::CommentPrefs,- can_comment: bool,- can_copy: bool,- ) -> bool {- if ui.input(|input| input.pointer.is_decidedly_dragging()) {- return false;- }- let Some(selection) = view.selection else {- view.actions_dismissed = None;- return false;- };- 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() {- return false;- }- let rect = xf.view_rect(last);- if !viewport.intersects(rect) {- return false;- }- let x = rect.left().clamp(viewport.left() + 8.0, (viewport.right() - 520.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 mut chosen = None;- egui::Area::new(egui::Id::unique(("text-selection-actions", view.id.0))).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),- ] {- if ui.add_enabled(can_comment, egui::Button::new(label)).clicked() {- chosen = Some(action);- }- }- if ui.add_enabled(can_copy, egui::Button::new(tl!("Copy"))).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);- 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();- match action {- SelectionAction::Note | SelectionAction::Replace => {- if matches!(action, SelectionAction::Replace) {- view.comments.replace = Some(quads);- }- view.comments.composer = Some(comments::Composer {- page,- at,- kind: if matches!(action, SelectionAction::Replace) { comments::ComposerKind::Replace } else { comments::ComposerKind::Note },- 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.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(),- }));- }- // Copy is dispatched through the app after the view borrow ends.- SelectionAction::Copy => {}- }- false- }-- /// Run a push button's action (the ones that need no JavaScript engine).- fn run_button(app: &mut PdfCraftApp, index: usize, name: &str, action: pdfcraft_engine::form_scripts::ButtonAction) {- use pdfcraft_engine::form_scripts::ButtonAction as B;- let pages = app.session.get(app.views[index].id).map_or(0, |d| d.info.pages.len());- match action {- B::Reset { fields, exclude } => {- let all: Vec<String> = app.session.get(app.views[index].id).map(|d| d.form.iter().map(|f| f.name.clone()).collect()).unwrap_or_default();- let listed = |n: &String| fields.iter().any(|f| n == f || n.starts_with(&format!("{f}.")));- let names = match (fields.is_empty(), exclude) {- (true, _) => None,- (false, false) => Some(all.iter().filter(|n| listed(n)).cloned().collect()),- (false, true) => Some(all.iter().filter(|n| !listed(n)).cloned().collect()),- };- app.views[index].forms.focus = None;- app.views[index].pending_edit = Some(pdfcraft_engine::Edit::ResetForm { names });- }- B::Named(n) => match n.as_str() {- "Print" => app.open_print(),- // What PdfCraft's XFA buttons use, and what a script's `execMenuItem("Save")`- // does too: the Save As dialog, so a click never overwrites the file unasked.- "SaveAs" => app.run_command("file.save_as"),- "NextPage" => app.views[index].step_page(true),- "PrevPage" => app.views[index].step_page(false),- "FirstPage" => app.views[index].go_to_page(0),- "LastPage" => app.views[index].go_to_page(pages.saturating_sub(1)),- other => app.notify_fmt("{name}: the {other} action isn't supported yet", &[("name", name), ("other", other)]),- },- B::Uri(u) => app.request_document_url(&u, crate::LinkOrigin::Button),- B::GoTo(p) => app.views[index].go_to_page(p.min(pages.saturating_sub(1))),- B::ShowHide { fields, hide } => {- let listed = |n: &String| fields.iter().any(|f| n == f || n.starts_with(&format!("{f}.")));- // `display.hidden` 1, `display.visible` 0, as a script setting `field.display` would.- let changes: Vec<pdfcraft_engine::FieldChange> = app- .session- .get(app.views[index].id)- .map(|d| d.form.iter().filter(|f| listed(&f.name)).map(|f| f.name.clone()).collect::<Vec<_>>())- .unwrap_or_default()- .into_iter()- .map(|name| pdfcraft_engine::FieldChange {- name,- value: None,- read_only: None,- required: None,- display: Some(if hide { 1 } else { 0 }),- })- .collect();- if !changes.is_empty() {- let label = if hide { "Hide a field" } else { "Show a field" };- app.views[index].pending_edit =- Some(pdfcraft_engine::Edit::Batch { label: label.into(), edits: vec![pdfcraft_engine::Edit::ApplyScriptChanges { changes }] });- }- }- B::SetLayers { changes, preserve_rb } => {- use pdfcraft_engine::form_scripts::LayerOp as Op;- let changes: Vec<(LayerOp, (u32, u16))> = changes- .into_iter()- .map(|(op, ocg)| {- let op = match op {- Op::On => LayerOp::On,- Op::Off => LayerOp::Off,- Op::Toggle => LayerOp::Toggle,- };- (op, ocg)- })- .collect();- set_layers(app, index, &changes, preserve_rb);- }- B::Alert(m) => app.notify(m),- B::Submit(url) => app.notify_fmt(- "{name} submits the form to {url}; PdfCraft doesn't send form data. Save the document to keep your entries.",- &[("name", name), ("url", &url)],- ),- B::ImportIcon => app.choose_field_image(name),- B::Script(js) => {- let id = app.views[index].id;- app.run_button_script(id, name, &js);- }- }- }-- /// Run a set-layer-visibility action from a button or link. It changes what is shown, as the- /// Layers panel does (which follows), not the document.- fn set_layers(app: &mut PdfCraftApp, index: usize, changes: &[(LayerOp, (u32, u16))], preserve_rb: bool) {- let id = app.views[index].id;- if app.session.set_layer_state(id, changes, preserve_rb) {- app.views[index].invalidate_content();- }- }-- /// Where a pinch or ⌘-scroll zooms the view about: the pointer, wherever it is over the view. Not- /// page input: it is read before the pages' widget exists, once `rect_contains_pointer` has found- /// the view under the pointer.- fn zoom_anchor(ui: &egui::Ui) -> Option<Pos2> {- ui.input(|i| i.pointer.hover_pos())- }-- /// The pointer and frame time that scroll the view while a comment is drawn. Not page input: it is- /// read before the pages' widget exists, and the pointer may be past the view's edge.- fn drawing_edge_pointer(ui: &egui::Ui) -> (Option<Pos2>, f32) {- ui.input(|i| (i.pointer.latest_pos(), i.stable_dt))- }-- /// A press anywhere, or a key, stops the touchpad's glide (#531).- fn glide_interrupted(ui: &egui::Ui) -> bool {- ui.input(|i| i.pointer.any_pressed() || i.events.iter().any(|e| matches!(e, egui::Event::Key { pressed: true, .. })))- }-- /// Full screen's click on the document, which turns the page: a primary click this frame with the- /// view on top under it in `area`. Not page input: it is read before the pages' widget exists, and- /// the turn waits until the pages have had the click.- fn presentation_click(ui: &egui::Ui, area: Rect) -> bool {- ui.rect_contains_pointer(area) && ui.input(|i| i.pointer.primary_clicked())- }-- /// Whether `p` lies in the bottom-left quadrant of `area`, where the page size shows (#1855).- fn in_size_hint_zone(area: Rect, p: Pos2) -> bool {- p.x >= area.min.x && p.x < area.center().x && p.y > area.center().y && p.y <= area.max.y- }-- /// The current page's size, floating at the bottom-left of the document area while the pointer is- /// in that quadrant, as Acrobat does. Same formatter and unit as Document Properties.- fn page_size_hint(view: &DocView, info: &DocInfo, units: crate::units::Unit, area: Rect, unobstructed: bool, ui: &mut egui::Ui, t: &Tokens) {- let Some(page) = info.pages.get(view.current) else { return };- let inside = unobstructed && ui.input(|i| i.pointer.hover_pos()).is_some_and(|p| in_size_hint_zone(area, p));- if !inside {- return;- }- let text = units.size(f64::from(page.width), f64::from(page.height));- egui::Area::new(egui::Id::unique("page-size-hint"))- .order(egui::Order::Foreground)- .interactable(false)- .pivot(egui::Align2::LEFT_BOTTOM)- .fixed_pos(area.left_bottom() + vec2(14.0, -14.0))- .show(ui.ctx(), |ui| {- egui::Frame::NONE- .fill(t.card)- .stroke(Stroke::new(1.0, t.border))- .corner_radius(CornerRadius::same(6))- .inner_margin(egui::Margin::symmetric(8, 4))- .show(ui, |ui| {- ui.add(egui::Label::new(egui::RichText::new(text).color(t.text)).selectable(false));- });- });- }-- /// Acrobat-style floating find bar at the top-right of the document area.- fn find_bar(view: &mut DocView, pages: usize, area: Rect, ui: &mut egui::Ui, t: &Tokens) {- let Some(find) = view.find.as_mut() else { return };- // The Search panel shows this search.- if find.in_panel {- return;- }- let mut close = false;- let mut step: Option<bool> = None;- let searched = view.texts.len() + view.text_failed.len();- egui::Area::new(egui::Id::unique("find-bar"))- .order(egui::Order::Middle)- .pivot(Align2::RIGHT_TOP)- .fixed_pos(area.right_top() + vec2(-18.0, 12.0))- .show(ui.ctx(), |ui| {- egui::Frame::NONE- .fill(t.card)- .stroke(Stroke::new(1.0, t.border))- .corner_radius(CornerRadius::same(10))- .shadow(egui::Shadow { offset: [0, 4], blur: 16, spread: 0, color: Color32::from_black_alpha(if t.dark() { 90 } else { 30 }) })- .inner_margin(egui::Margin::symmetric(10, 6))- .show(ui, |ui| {- ui.horizontal(|ui| {- ui.add(icons::image("search", 16.0, t.text_muted));- let edit = egui::TextEdit::singleline(&mut find.query)- .id(egui::Id::unique("find-input"))- .hint_text(tl!("Find text"))- .desired_width(220.0)- .frame(egui::Frame::NONE);- let r = ui.add(edit).accessible_name(tl!("Find text"));- if find.focus {- r.request_focus();- find.focus = false;- }- if r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)) {- step = Some(!ui.input(|i| i.modifiers.shift));- r.request_focus();- }- if r.has_focus() && ui.input(|i| i.key_pressed(egui::Key::Escape)) {- close = true;- }- let status = if find.query.trim().is_empty() {- String::new()- } else if find.matches.is_empty() {- if searched < pages {- crate::i18n::fmt(tl!("Searching… {s}/{p}"), &[("s", &searched.to_string()), ("p", &pages.to_string())])- } else {- tl!("No matches").to_string()- }- } else {- let more = if searched < pages { "+" } else { "" };- crate::i18n::fmt(- tl!("{c} of {n}{more}"),- &[- ("c", &find.current.map(|c| c + 1).unwrap_or(0).to_string()),- ("n", &find.matches.len().to_string()),- ("more", more),- ],- )- };- ui.label(egui::RichText::new(status).font(theme::regular(12.0)).color(t.text_muted));- let tip = crate::commands::key_tip(ui.ctx(), tl!("Previous ({key})"), crate::commands::FIND_PREV);- if icons::button(ui, "chevron-up", 26.0, false, &tip).clicked() {- step = Some(false);- }- let tip = crate::commands::key_tip(ui.ctx(), tl!("Next ({key})"), crate::commands::FIND_NEXT);- if icons::button(ui, "chevron-down", 26.0, false, &tip).clicked() {- step = Some(true);- }- let opts = icons::button(ui, "settings-2", 26.0, find.case_sensitive || find.whole_words, tl!("Find options"));- egui::Popup::menu(&opts).show(|ui| {- let a = ui.add(widgets::checkbox(&mut find.whole_words, tl!("Whole words only"))).changed();- let b = ui.add(widgets::checkbox(&mut find.case_sensitive, tl!("Case-sensitive"))).changed();- if a || b {- // Search again with the new options.- find.case_query.clear();- }- });- if icons::button(ui, "x", 26.0, false, tl!("Close (Esc)")).clicked() {- close = true;- }- });- });- });- if close {- view.find = None;- return;- }- if find.query != find.case_query {- view.rerun_find();- }- if let Some(forward) = step {- view.find_step(forward);- }- }-- /// The prepare-mode field menu's choices.- enum FieldMenu {- Properties,- Duplicate(String),- }-- /// What the notice bar's buttons ask for.- enum Notice {- /// Reload the file that changed on disk, dropping unsaved changes.- Reload,- Security,- Signatures,- Repairs,- /// Highlight fields was turned on or off.- FieldHighlights(bool),- /// Open the JavaScript console (the form's scripts were turned off; the error is there).- Console,- /// Unlock… (enter the permissions password).- Unlock,- /// Close this historical snapshot tab (View signed version / View revision).- Close,- /// Stop showing the secured-document notice, in every document (#4035).- HideSecured,- }-- /// The notice bar above the pages: a file changed on disk first, then what a historical- /// snapshot is, then the signature status bar, a form's scripts having been turned- /// off, security, forms and warnings.- fn notices(- view: &mut DocView,- doc: &pdfcraft_engine::Document,- secured: bool,- repaired: bool,- signed: Option<(&str, Color32, &str, String)>,- ui: &mut egui::Ui,- t: &Tokens,- ) -> Option<Notice> {- let info = &doc.info;- let xfa = doc.xfa.as_ref();- // The file changed on disk while this document has unsaved changes (#431): ask before- // replacing it, ahead of every other notice.- if view.disk_changed {- let mut reload = false;- egui::Frame::NONE.fill(t.accent_soft).inner_margin(egui::Margin::symmetric(14, 7)).show(ui, |ui| {- ui.horizontal(|ui| {- ui.add(icons::image("rotate-cw", 16.0, t.accent_text));- ui.label(- egui::RichText::new(tl!(- "This file changed on disk. Reload shows the new version and drops your unsaved changes; Save replaces it with this version."- ))- .color(t.text),- );- ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {- if icons::button(ui, "x", 22.0, false, tl!("Dismiss")).clicked() {- view.disk_changed = false;- }- reload = crate::widgets::pill_button(ui, tl!("Reload"), false).clicked();- });- });- });- return reload.then_some(Notice::Reload);- }- // A historical snapshot (View signed version / View revision): what it is, above the- // signature and security bars, so the tab is never mistaken for the live document.- if let Some(snap) = view.snapshot.as_ref() {- let mut close = false;- let text = if snap.kind == SnapshotKind::SignedVersion {- crate::i18n::fmt(- tl!("You are viewing the signed version of “{from}” (revision {rev}). It is a snapshot: changes here won't affect the original."),- &[("from", &snap.from), ("rev", &snap.revision.to_string())],- )+ let cur = view.current;+ wanted.sort_by_key(|w| (!visible_now.contains(&w.0), w.0.abs_diff(cur), w.3.is_some()));+ // Tiles of far-away pages are useless: free them. Tiles of an earlier zoom stay for a page+ // that is on screen, whether or not the page is tiled at this zoom (#2196): a zoom out below+ // the tiling threshold used to drop the tiles of the zoom just left, so coming back to it+ // was a cold miss and the page re-blurred through the backdrop while every tile was+ // interpreted again. `OLD_TILES` still bounds how many older tiles are kept, nearest scale+ // first, and admission keeps them inside `TILE_BYTES`.+ let missing: HashSet<usize> = wanted.iter().filter(|w| w.3.is_some()).map(|w| w.0).collect();+ let on_screen: HashSet<usize> = visible_now.iter().copied().collect();+ view.tiles.retain(|(p, t, _, _), _| p.abs_diff(cur) <= 2 && (*t == tag || missing.contains(p) || on_screen.contains(p)));+ let mut older: Vec<(f32, (usize, u64, u32, u32))> =+ view.tiles.keys().filter(|k| k.1 != tag).map(|k| ((tag_scale(k.1) / scale).ln().abs(), *k)).collect();+ // Tiles of earlier zooms are kept nearest scale first, and bounded by count *and* bytes: a+ // large scan renders a tile up to 4096² (about 67 MiB), so a count alone let a few tiles of+ // a few zooms run far past the tile allowance. #2196 keeps a zoom already visited, which+ // makes that reachable in ordinary zooming, so the byte bound has to be here too.+ older.sort_by(|a, b| a.0.total_cmp(&b.0));+ let mut kept = 0usize;+ let mut kept_bytes = 0usize;+ let mut drop: Vec<(usize, u64, u32, u32)> = Vec::new();+ for (_dist, key) in older {+ let bytes = view.tiles.get(&key).map_or(0, texture_bytes);+ if kept >= OLD_TILES || kept_bytes.saturating_add(bytes) > TILE_BYTES {+ drop.push(key);} else {- crate::i18n::fmt(- tl!("You are viewing revision {rev} of “{from}”. It is a snapshot: changes here won't affect the original."),- &[("rev", &snap.revision.to_string()), ("from", &snap.from)],- )- };- notice_bar(ui, t, "clock", t.accent_text, text, |ui| {- if crate::widgets::pill_button(ui, tl!("Close"), true).clicked() {- close = true;- }- });- if close {- return Some(Notice::Close);- }- }- if let Some((icon, color, template, arg)) = signed {- let mut open = false;- notice_bar(ui, t, icon, color, crate::i18n::fmt(tl!(template), &[("by", &arg)]), |ui| {- if crate::widgets::pill_button(ui, tl!("Signature panel"), false).clicked() {- open = true;- }- });- return open.then_some(Notice::Signatures);- }- if view.notice_dismissed {- return None;- }- let mut open_security = false;- let mut unlock = false;- let mut hide_secured = false;- let mut open_repairs = false;- let mut open_console = false;- let mut toggled = None;- // A form whose scripts were turned off no longer calculates or answers its buttons: that- // comes before what else there is to say about the document.- let scripts_off = doc.xfa_scripts_off();- // What the document is as a form, if it is one: what the bar says first, secured or not.- let form = if let Some(x) = xfa {- let lang = crate::i18n::current();- let pages = crate::i18n::trn(lang, x.pages as u64, "{n} page", "{n} pages");- let fields = crate::i18n::trn(lang, x.fields as u64, "{n} field", "{n} fields");- let mut text =- crate::i18n::fmt(tl!("Dynamic XFA form laid out from its template: {pages}, {fields}."), &[("pages", &pages), ("fields", &fields)]);- if !x.warnings.is_empty() {- // The notes are clauses ("a picture is left out"); the first starts a sentence here.- let notes = x.warnings.join("; ");- let mut chars = notes.chars();- text.push(' ');- text.extend(chars.next().into_iter().flat_map(char::to_uppercase));- text.push_str(chars.as_str());- text.push('.');- }- Some(("text-cursor-input", text, true))- } else if info.xfa == Some(pdfcraft_render::Xfa::Dynamic) {- Some((- "triangle-alert",- tl!("This is a dynamic XFA form, which PdfCraft can't display yet. What you see is the file's placeholder page.").to_string(),- false,- ))- } else if info.xfa == Some(pdfcraft_render::Xfa::Static) {- Some((- "text-cursor-input",- tl!("XFA form: its fields and its XFA data are kept in step, so other viewers show what you fill in.").to_string(),- true,- ))- } else if info.fields.iter().any(|f| f.kind != pdfcraft_render::FieldKind::PushButton) {- // Push buttons alone (LaTeX `animate` frames, navigation buttons) leave nothing to fill in.- Some((- "text-cursor-input",- crate::i18n::fmt(tl!("This document contains {n} interactive form fields."), &[("n", &info.fields.len().to_string())]),- true,- ))- } else {- None- };- let msg = if scripts_off {- Some(("triangle-alert", crate::js_ui::scripts_off_notice(), true))- } else if secured {- // A secured form still says what it is, and keeps Highlight fields: the security- // sentence follows the form's.- let security = tl!("This document is secured. Some changes are restricted by its security settings.");- Some(match form {- Some((icon, text, fields)) => (icon, format!("{text} {security}"), fields),- None => ("lock", security.to_string(), false),- })- } else if form.is_some() {- form- } else if repaired {- Some(("bandage", tl!("This file was damaged and has been repaired. Saving keeps the repaired version.").to_string(), false))- } else if !info.warnings.is_empty() {- Some(("triangle-alert", info.warnings[0].clone(), false))- } else {- None- };- let (icon, text, fields) = msg?;- notice_bar(ui, t, icon, t.accent_text, text, |ui| {- if icons::button(ui, "x", 22.0, false, tl!("Dismiss")).clicked() {- view.notice_dismissed = true;- }- if fields {- let label = if view.highlight_fields { tl!("Hide field highlights") } else { tl!("Highlight fields") };- if crate::widgets::pill_button(ui, label, view.highlight_fields).clicked() {- view.highlight_fields = !view.highlight_fields;- toggled = Some(Notice::FieldHighlights(view.highlight_fields));- }- }- if scripts_off && crate::widgets::pill_button(ui, tl!("JavaScript Console"), false).clicked() {- open_console = true;- }- if secured && crate::widgets::pill_button(ui, tl!("Security settings"), false).clicked() {- open_security = true;- }- if secured && doc.can_unlock() && crate::widgets::pill_button(ui, tl!("Unlock…"), true).clicked() {- unlock = true;- }- // Only when the bar shows the security message: a form's stopped scripts come first.- if secured && !scripts_off && crate::widgets::pill_button(ui, tl!("Don't show again"), false).clicked() {- hide_secured = true;- }- if repaired && !secured && info.fields.is_empty() && crate::widgets::pill_button(ui, tl!("Details"), false).clicked() {- open_repairs = true;+ kept = kept.saturating_add(1);+ kept_bytes = kept_bytes.saturating_add(bytes);}- });- if open_repairs {- return Some(Notice::Repairs);- }- if open_console {- return Some(Notice::Console);- }- if unlock {- return Some(Notice::Unlock);- }- if hide_secured {- return Some(Notice::HideSecured);}- open_security.then_some(Notice::Security).or(toggled)- }-- /// One notice bar: an icon and a message on the left, `buttons` (added right to left) on the- /// right. The buttons are laid out first, so the message only gets the width they leave: it- /// wraps there (or, when very little is left, is cut short with the full text on hover) instead- /// of running under the buttons and past the document area into the side panel (#785). The- /// buttons are centred on a row of button height, and the message's first line is centred on- /// the same row; a wrapped message grows the bar downwards.- fn notice_bar(ui: &mut egui::Ui, t: &Tokens, icon: &str, icon_color: Color32, text: String, buttons: impl FnOnce(&mut egui::Ui)) {- const ROW: f32 = 28.0;- const ICON: f32 = 16.0;- egui::Frame::NONE.fill(t.accent_soft).inner_margin(egui::Margin::symmetric(14, 7)).show(ui, |ui| {- let width = ui.available_width();- ui.allocate_ui_with_layout(vec2(width, ROW), egui::Layout::right_to_left(egui::Align::Center), |ui| {- ui.set_min_height(ROW);- buttons(ui);- let rest = ui.available_width().max(0.0);- ui.allocate_ui_with_layout(vec2(rest, ROW), egui::Layout::top_down(egui::Align::Min), |ui| {- let font = egui::TextStyle::Body.resolve(ui.style());- let line = ui.fonts_mut(|f| f.row_height(&font)).max(ICON);- ui.add_space(((ROW - line) / 2.0).max(0.0));- ui.with_layout(egui::Layout::left_to_right(egui::Align::Min), |ui| {- let (slot, _) = ui.allocate_exact_size(vec2(ICON, line), Sense::hover());- icons::paint(ui, Rect::from_center_size(slot.center(), vec2(ICON, ICON)), icon, ICON, icon_color);- let label = egui::Label::new(egui::RichText::new(text).color(t.text));- // Wrapping into a sliver would stack the message a few letters per line.- ui.add(if ui.available_width() >= 120.0 { label.wrap() } else { label.truncate() });- });- });- });- });- }-- /// The floating quick-action bar at the left edge of the document area.- fn quick_bar(app: &mut PdfCraftApp, area: Rect, ui: &mut egui::Ui) {- let t = Tokens::get(ui.ctx());- let pos = area.left_top() + vec2(14.0, 14.0);- egui::Area::new(egui::Id::unique("quick-bar")).order(egui::Order::Middle).fixed_pos(pos).show(ui.ctx(), |ui| {- egui::Frame::NONE- .fill(t.card)- .stroke(Stroke::new(1.0, t.border))- .corner_radius(CornerRadius::same(12))- .shadow(egui::Shadow { offset: [0, 4], blur: 16, spread: 0, color: Color32::from_black_alpha(if t.dark() { 100 } else { 28 }) })- .inner_margin(egui::Margin::same(6))- .show(ui, |ui| {- ui.spacing_mut().item_spacing.y = 2.0;- ui.vertical(|ui| {- if icons::button(ui, "mouse-pointer-2", 32.0, app.quick_tool == QuickTool::Select, tl!("Select (V)")).clicked() {- app.quick_tool = QuickTool::Select;- }- if icons::button(ui, "hand", 32.0, app.quick_tool == QuickTool::Hand, tl!("Hand (H)")).clicked() {- app.quick_tool = QuickTool::Hand;- }- // Comment ▸, Highlight ▸, Draw ▸ (Acrobat's comment toolbar groups). Clicking a- // group selects its last-used tool; clicking it again opens the flyout.- for g in 0..comments::GROUPS.len() {- let current = app.comment_prefs.group_tool[g];- let active = matches!(app.quick_tool, QuickTool::Comment(t) if t.group() == g);- let resp = icons::button(ui, current.icon(), 32.0, active, tl!(current.label()));- // A small corner triangle marks the flyout.- let r = resp.rect;- let tri = [r.right_bottom() + vec2(-4.0, -4.0), r.right_bottom() + vec2(-9.0, -4.0), r.right_bottom() + vec2(-4.0, -9.0)];- ui.painter().add(egui::Shape::convex_polygon(tri.to_vec(), if active { t.accent } else { t.text_faint }, Stroke::NONE));- let open = (resp.clicked() && active) || resp.secondary_clicked();- if resp.clicked() && !active {- app.execute(current.command());- }- egui::Popup::menu(&resp)- .open_memory(open.then_some(egui::SetOpenCommand::Toggle))- .align(egui::RectAlign::RIGHT_START)- .gap(6.0)- .show(|ui| {- for tool in comments::GROUPS[g] {- let on = app.quick_tool == QuickTool::Comment(*tool);- let (row, click) = ui.allocate_exact_size(vec2(180.0, 28.0), Sense::click());- let press = theme::Press::track(ui, &click);- press.wash(ui, row, 4, on);- let body = row.translate(press.offset());- icons::paint(ui, Rect::from_min_size(body.min + vec2(8.0, 6.0), vec2(16.0, 16.0)), tool.icon(), 16.0, t.text);- let reserve = if on { 28.0 } else { 8.0 };- crate::widgets::paint_left(- ui,- body.left_center() + vec2(34.0, 0.0),- tl!(tool.label()),- theme::regular(13.0),- t.text,- (row.width() - 34.0 - reserve).max(0.0),- );- if on {- icons::paint(- ui,- Rect::from_min_size(body.right_top() + vec2(-24.0, 7.0), vec2(14.0, 14.0)),- "check",- 14.0,- t.accent,- );- }- let click = theme::hand(click);- let info = tl!(tool.label()).to_string();- click.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, on, info.clone()));- if click.clicked() {- app.execute(tool.command());- ui.close();- }- }- });- }- // Edit text & images, while the Edit workspace is open (Acrobat's Edit toolbar)- // or the tool is in use.- if app.mode == crate::Mode::Edit || app.quick_tool == QuickTool::EditText {- let on = app.quick_tool == QuickTool::EditText;- if icons::button(ui, "text-cursor-input", 32.0, on, tl!("Edit text & images")).clicked() {- if on {- app.put_down_edit_text();- } else {- app.quick_tool = QuickTool::EditText;- }- }- }- // Fill & Sign ▸ (text, marks, date, signature).- let current_fill = match app.quick_tool {- QuickTool::Fill(f) => Some(f),- _ => None,- };- let shown = current_fill.unwrap_or(crate::fill_sign::FillTool::Text);- let resp = icons::button(- ui,- if current_fill.is_some() { shown.icon() } else { "pen-line" },- 32.0,- current_fill.is_some(),- tl!("Fill & Sign"),- );- let r = resp.rect;- let tri = [r.right_bottom() + vec2(-4.0, -4.0), r.right_bottom() + vec2(-9.0, -4.0), r.right_bottom() + vec2(-4.0, -9.0)];- ui.painter().add(egui::Shape::convex_polygon(- tri.to_vec(),- if current_fill.is_some() { t.accent } else { t.text_faint },- Stroke::NONE,- ));- if resp.clicked() && current_fill.is_none() {- app.execute(shown.command());- }- let open = (resp.clicked() && current_fill.is_some()) || resp.secondary_clicked();- egui::Popup::menu(&resp)- .open_memory(open.then_some(egui::SetOpenCommand::Toggle))- .align(egui::RectAlign::RIGHT_START)- .gap(6.0)- .show(|ui| {- for tool in crate::fill_sign::FILL_TOOLS {- if matches!(tool, crate::fill_sign::FillTool::Signature | crate::fill_sign::FillTool::Initials) {- continue;- }- let on = current_fill == Some(tool);- let (row, click) = ui.allocate_exact_size(vec2(180.0, 28.0), Sense::click());- let press = theme::Press::track(ui, &click);- press.wash(ui, row, 4, on);- let body = row.translate(press.offset());- icons::paint(ui, Rect::from_min_size(body.min + vec2(8.0, 6.0), vec2(16.0, 16.0)), tool.icon(), 16.0, t.text);- let reserve = if on { 28.0 } else { 8.0 };- crate::widgets::paint_left(- ui,- body.left_center() + vec2(34.0, 0.0),- tl!(tool.label()),- theme::regular(13.0),- t.text,- (row.width() - 34.0 - reserve).max(0.0),- );- if on {- icons::paint(- ui,- Rect::from_min_size(body.right_top() + vec2(-24.0, 7.0), vec2(14.0, 14.0)),- "check",- 14.0,- t.accent,- );- }- let click = theme::hand(click);- let info = tl!(tool.label()).to_string();- click.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, on, info.clone()));- if click.clicked() {- app.execute(tool.command());- ui.close();- }- }- ui.separator();- if let Some(command) = crate::fill_sign::signature_entries(ui, app, &t) {- app.execute(command);- ui.close();- }- });- if matches!(current_fill, Some(crate::fill_sign::FillTool::Text | crate::fill_sign::FillTool::Date)) {- ui.label(tl!("Font size:"));- let size = ui.add(- egui::DragValue::new(&mut app.fill_text_size)- .range(crate::fill_sign::MIN_TEXT_SIZE..=crate::fill_sign::MAX_TEXT_SIZE)- .speed(0.25)- .suffix(" pt"),- );- // #1274: the size also applies to the Fill & Sign text that is selected,- // once per change (a typed value, or the end of a drag), so a drag adds- // one undo step and not one per frame.- if ((size.changed() && !size.dragged()) || size.drag_stopped())- && let Some((index, id)) = app.active_ids()- && let Some((page, annotation)) = app.views.get(index).and_then(|view| view.comments.selected)- && app.session.get(id).is_some_and(|doc| {- doc.allows_annotation()- && doc- .info- .annotations- .iter()- .any(|a| a.page == page && a.index == annotation && a.fill_sign && a.subtype == "FreeText" && !a.locked)- })- {- app.apply_edit(Edit::FontSizeAnnotation { page, index: annotation, size: app.fill_text_size });- }- }- if let QuickTool::Comment(tool) = app.quick_tool {- let (r, _) = ui.allocate_exact_size(vec2(32.0, 9.0), Sense::hover());- ui.painter().hline(r.x_range().shrink(6.0), r.center().y, Stroke::new(1.0, t.divider));- if let Some(color) = comments::quick_bar_controls(ui, tool, &mut app.comment_prefs)- && let Some((index, id)) = app.active_ids()- && let Some((page, annotation)) = app.views.get(index).and_then(|view| view.comments.selected)- && app.session.get(id).is_some_and(|doc| {- doc.allows_annotation()- && doc- .info- .annotations- .iter()- .any(|a| a.page == page && a.index == annotation && !a.is_reply() && comments::made_by(a, tool))- })- {- app.apply_edit(Edit::StyleAnnotation {- page,- index: annotation,- color: Some(color),- opacity: None,- width: None,- endings: None,- });- }- }- });- });- });- }-- /// Where a page of `page` size (points, as shown: after its rotation) is drawn in the grid cell- /// `cell`: as large as the picture area allows and centred in it, so a landscape or rotated page- /// fills the cell's width in its middle, as Acrobat draws it, instead of a small strip at the top.- /// The picture area leaves room for the page number and actions below. Its sides narrow only when- /// a picture that wide would reach the selection checkbox in the cell's corner.- pub(crate) fn grid_page_rect(cell: Rect, page: Vec2) -> Rect {- let area = Rect::from_min_max(pos2(cell.left(), cell.top() + 16.0), pos2(cell.right(), cell.bottom() - 72.0));- // A page size from a damaged file can be zero, NaN or infinite; draw such a page square.- let side = |v: f32| if v.is_finite() { v.max(1.0) } else { 1.0 };- let (w, h) = (side(page.x), side(page.y));- let fit = |margin: f32| {- let s = ((area.width() - 2.0 * margin).max(1.0) / w).min(area.height().max(1.0) / h);- Rect::from_center_size(area.center(), vec2(w * s, h * s))- };- let wide = fit(16.0);- // The checkbox sits at (8, 8)-(28, 28) from the cell's corner; keep 4 px clear of it.- let checkbox = Rect::from_min_size(cell.min + vec2(8.0, 8.0), Vec2::splat(20.0)).expand(4.0);- if wide.intersects(checkbox) { fit(30.0) } else { wide }- }-- /// The organize toolbar: page operations on the selection (Acrobat's Organize Pages bar).- fn organize_toolbar(view: &mut DocView, info: &DocInfo, editable: bool, dirty: bool, unobstructed: bool, ui: &mut egui::Ui, t: &Tokens) {- let targets = view.target_pages();- let n = info.pages.len();- let (first, last) = (targets.first().copied().unwrap_or(0), targets.last().copied().unwrap_or(0));- egui::Frame::NONE.fill(t.chrome).inner_margin(egui::Margin::symmetric(16, 8)).show(ui, |ui| {- ui.horizontal(|ui| {- ui.spacing_mut().item_spacing.x = 4.0;- let label = match view.selected.len() {- 0 => crate::i18n::fmt(tl!("Page {p} of {n}"), &[("p", &(view.current + 1).to_string()), ("n", &n.to_string())]),- 1 => tl!("1 page selected").to_string(),- k => crate::i18n::fmt(tl!("{n} pages selected"), &[("n", &k.to_string())]),- };- // Fixed width so the buttons never shift as the selection text changes.- ui.add_sized([150.0, 30.0], egui::Label::new(egui::RichText::new(label).font(theme::medium(13.0)).color(t.text_muted)).truncate());- ui.add_enabled_ui(editable, |ui| {- ui.add_space(8.0);- if ui.add_enabled_ui(first > 0, |ui| icons::button(ui, "chevron-left", 30.0, false, tl!("Move earlier"))).inner.clicked() {- view.pending_edit = Some(Edit::MovePages { pages: targets.clone(), to: first - 1 });- }- if ui.add_enabled_ui(last + 1 < n, |ui| icons::button(ui, "chevron-right", 30.0, false, tl!("Move later"))).inner.clicked() {- view.pending_edit = Some(Edit::MovePages { pages: targets.clone(), to: first + 1 });- }- });- ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {- if widgets::ghost_button(ui, "x", tl!("Close")).on_hover_text(tl!("Back to the document")).clicked() {- view.organize = false;- }- // What the grid shows is what is saved.- let save = ui.add_enabled_ui(dirty, |ui| widgets::pill_button(ui, tl!("Save pages"), true)).inner;- if save.on_hover_text(tl!("Save these pages as one PDF")).on_disabled_hover_text(tl!("No changes to save")).clicked() {- view.pending_action = Some(ViewAction::Save);- }- ui.add_space(8.0);- // Page size in the grid (right to left: in, the percentage, out).- let zoom = view.grid_zoom;- if ui- .add_enabled_ui(zoom < *GRID_ZOOM_RANGE.end(), |ui| icons::button(ui, "zoom-in", 30.0, false, tl!("Larger pages")))- .inner- .clicked()- {- view.grid_zoom_request = Some(zoom * GRID_ZOOM_STEP);- }- let percent = egui::Button::new(egui::RichText::new(format!("{:.0}%", zoom * 100.0)).font(theme::medium(12.0)).color(t.text_muted))- .frame(false);- let percent = ui.add_sized([44.0, 30.0], percent);- percent.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tl!("Reset page size")));- if percent.on_hover_text(tl!("Reset page size")).clicked() {- view.grid_zoom_request = Some(1.0);- }- if ui- .add_enabled_ui(zoom > *GRID_ZOOM_RANGE.start(), |ui| icons::button(ui, "zoom-out", 30.0, false, tl!("Smaller pages")))- .inner- .clicked()- {- view.grid_zoom_request = Some(zoom / GRID_ZOOM_STEP);- }- });- });- });- // Keys act on the selection unless a text field or a dialog has them (Delete under- // Preferences deleted the selected pages).- if editable && unobstructed && !ui.ctx().egui_wants_keyboard_input() {- use egui::{Key, Modifiers};- let (del, esc) = ui.input_mut(|i| {- (- i.consume_key(Modifiers::NONE, Key::Delete) || i.consume_key(Modifiers::NONE, Key::Backspace),- i.consume_key(Modifiers::NONE, Key::Escape),- )- });- // ⌘C / ⌘X / ⌘V copy, cut and paste pages (egui delivers them as clipboard events).- let (copy, cut, paste) = ui.input(|i| {- let any = |f: &dyn Fn(&egui::Event) -> bool| i.events.iter().any(f);- (any(&|e| matches!(e, egui::Event::Copy)), any(&|e| matches!(e, egui::Event::Cut)), any(&|e| matches!(e, egui::Event::Paste(_))))- });- if copy || cut {- view.pending_action = Some(ViewAction::CopyPages { cut });- }- if paste {- view.pending_action = Some(ViewAction::PastePages);- }- if del && targets.len() < n {- view.pending_edit = Some(Edit::DeletePages { pages: targets });- }- if esc {- view.selected.clear();- }+ for key in drop {+ view.tiles.remove(&key);}- }-- /// Organize pages: a thumbnail grid (Acrobat's Organize Pages view). Click selects, ⌘-click- /// toggles, ⇧-click extends; double-click opens the page.- /// The gap (0 = before the first page, n = after the last) the pointer points at in the grid.- pub(crate) fn drop_gap(cells: &[(usize, Rect)], p: Pos2) -> Option<usize> {- let (i, r) = cells.iter().min_by(|(_, a), (_, b)| a.distance_sq_to_pos(p).total_cmp(&b.distance_sq_to_pos(p)))?;- Some(if p.x < r.center().x { *i } else { i + 1 })- }-- /// Ctrl (Option on macOS) held when a page drag drops copies the dragged pages into the gap- /// instead of moving them, as Acrobat's Organize Pages does.- ///- /// The OS comes from the context, not `cfg!`: the wasm build runs on macOS too, where- /// `cfg!(target_os = "macos")` is false, so Option has to copy there as well (#3092 review).- fn copy_modifier(ctx: &egui::Context, m: &egui::Modifiers) -> bool {- if crate::commands::mac_shortcuts(ctx) { m.alt } else { m.ctrl }- }-- /// A "+" on a gap of the page grid: insert files there. Returns whether it was clicked.- fn gap_button(ui: &mut egui::Ui, gap: usize, at: Pos2, height: f32, label: String, t: &Tokens) -> bool {- let resp = ui.interact(Rect::from_center_size(at, Vec2::splat(22.0)), ui.scope_id().with(("org-gap", gap)), Sense::click());- resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, label.clone()));- let hot = resp.hovered();- if hot {- ui.painter().line_segment([pos2(at.x, at.y - height / 2.0), pos2(at.x, at.y + height / 2.0)], Stroke::new(3.0, t.accent));- }- ui.painter().circle(at, 9.0, if hot { t.accent } else { t.chrome }, Stroke::new(1.0, if hot { t.accent } else { t.border }));- let ink = Stroke::new(1.5, if hot { Color32::WHITE } else { t.text_muted });- ui.painter().line_segment([at - vec2(4.0, 0.0), at + vec2(4.0, 0.0)], ink);- ui.painter().line_segment([at - vec2(0.0, 4.0), at + vec2(0.0, 4.0)], ink);- resp.on_hover_text(label).clicked()- }-- fn organize_grid(view: &mut DocView, info: &DocInfo, editable: bool, dirty: bool, unobstructed: bool, ui: &mut egui::Ui, t: &Tokens) {- let ppp = ui.ctx().pixels_per_point();- // The page image scales with the zoom; the padding and the page number don't.- let cell = vec2(146.0 * view.grid_zoom + 44.0, 194.0 * view.grid_zoom + 88.0);- let anchor = view.grid_anchor.take();- let reveal = view.grid_reveal.take();- let mut open_page = None;- organize_toolbar(view, info, editable, dirty, unobstructed, ui, t);- let viewport = ui.available_rect_before_wrap();- view.viewport_screen = viewport;- let auto_delta = if unobstructed {- view.auto_scroll.update(ui, viewport, true)- } else {- view.auto_scroll.cancel();- Vec2::ZERO- };- let middle_gesture = view.auto_scroll.blocks_input();- let mut cells: Vec<(usize, Rect)> = Vec::new();- // The pages in view that are drawn larger than their thumbnails, and those of them that- // need a sharper render than they have. The width is the size drawn, in device pixels.- let (mut in_view, mut sharper): (Vec<(usize, f32)>, Vec<RenderRequest>) = (Vec::new(), Vec::new());- // The source cell can scroll out of the virtualized rows during a drag.- let mut drop = view.org_drag.is_some() && ui.input(|i| i.pointer.primary_released());- egui::ScrollArea::vertical().auto_shrink([false, false]).show_viewport(ui, |ui, clip| {- if middle_gesture {- let opacity = ui.opacity();- ui.disable();- ui.set_opacity(opacity);- }- if auto_delta != Vec2::ZERO {- ui.scroll_with_delta_animation(auto_delta, egui::style::ScrollAnimation::none());- }- ui.add_space(20.0);- let cols = ((ui.available_width() - 40.0) / cell.x).floor().max(1.0) as usize;- let rows = info.pages.len().div_ceil(cols);- let left = (ui.available_width() - cols as f32 * cell.x) / 2.0;- let (grid, _) = ui.allocate_exact_size(vec2(ui.available_width(), rows as f32 * cell.y), Sense::hover());- // The page Organize opened on may lie in a row the virtualized grid has not laid out,- // so its cell is computed rather than found.- if let Some(page) = reveal.filter(|p| *p < info.pages.len()) {- let row = page / cols;- let col = page % cols;- let c = Rect::from_min_size(pos2(grid.left() + left + col as f32 * cell.x, grid.top() + row as f32 * cell.y), cell);- ui.scroll_to_rect_animation(c, Some(egui::Align::Center), egui::style::ScrollAnimation::none());- }- for row in thumbnail_rows(clip.top() - 20.0, clip.bottom() - 20.0, cell.y, rows) {- let row_rect = Rect::from_min_size(grid.min + vec2(0.0, row as f32 * cell.y), vec2(grid.width(), cell.y));- for col in 0..cols {- let i = row * cols + col;- let Some(p) = info.pages.get(i) else { break };- let c = Rect::from_min_size(pos2(row_rect.left() + left + col as f32 * cell.x, row_rect.top()), cell);- view.need_thumbnail(i, c.intersects(ui.clip_rect()));- let resp = ui.interact(c, ui.scope_id().with(("org", i)), if editable { Sense::click_and_drag() } else { Sense::click() });- cells.push((i, c));- if let Some((_, above)) = anchor.filter(|(page, _)| *page == i) {- ui.scroll_to_rect_animation(c.translate(vec2(0.0, -above)), Some(egui::Align::Min), egui::style::ScrollAnimation::none());- }- // Drag pages to move them (the selection, or the page grabbed).- if resp.drag_started() {- if !view.selected.contains(&i) {- view.selected = [i].into();- view.select_anchor = Some(i);- }- let mut pages: Vec<usize> = view.selected.iter().copied().collect();- pages.sort_unstable();- view.org_drag = Some(pages);- }- if resp.drag_stopped() {- drop = true;- }- let page_label = crate::i18n::fmt(tl!("Page {label}"), &[("label", &p.label)]);- resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::CheckBox, true, view.selected.contains(&i), page_label.clone()));- let pr = grid_page_rect(c, vec2(p.width, p.height));- let size = pr.size();- let selected = view.selected.contains(&i) || (view.selected.is_empty() && i == view.current);- if selected || resp.hovered() {- ui.painter().rect_filled(c.shrink(6.0), CornerRadius::same(8), if selected { t.accent_soft } else { t.hover });- }- if view.selected.contains(&i) {- ui.painter().rect_stroke(c.shrink(6.0), CornerRadius::same(8), Stroke::new(1.5, t.accent), egui::StrokeKind::Inside);- }- ui.painter().rect_filled(pr.translate(vec2(0.0, 1.5)), CornerRadius::same(1), t.page_shadow);- ui.painter().rect_filled(pr, CornerRadius::ZERO, Color32::WHITE);- // A page drawn larger than its thumbnail gets a render at the size drawn, while- // it is in view; until that arrives the thumbnail stands in.- let want = size.x * ppp;- let thumb = view.thumbs.get(&i).map(|t| &t.tex);- let thumb_ok = thumb.is_some_and(|t| t.size()[0] as f32 >= want * GRID_SHARP.start());- let sharp = view.grid_pages.get(&i).filter(|_| !thumb_ok);- if !thumb_ok && ui.is_rect_visible(c) {- in_view.push((i, want));- if !sharp.is_some_and(|(w, _)| sharp_enough(*w, want)) && !view.errors.contains_key(&i) {- sharper.push(RenderRequest {- page: i,- kind: RequestKind::Pixels,- tile: None,- scale: want / p.width.max(1.0),- tag: GRID_TAG,- // Grid cells are previews: tiny images are skipped for them.- preview: true,- });- }- }- if let Some(tex) = sharp.map(|(_, t)| t).or(thumb) {- ui.painter().image(tex.id(), pr, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE);- }- ui.painter().rect_stroke(pr, CornerRadius::ZERO, Stroke::new(1.0, t.border), egui::StrokeKind::Outside);- let label_font = theme::medium(12.0);- let label_w = (c.width() - 12.0).max(0.0);- let page_label = crate::widgets::fit_line(&p.label, label_w, |s| crate::widgets::text_width(ui, s, &label_font));- let label_pos = pos2(c.center().x, c.bottom() - 48.0);- ui.painter().with_clip_rect(Rect::from_center_size(label_pos, vec2(label_w, 18.0))).text(- label_pos,- Align2::CENTER_CENTER,- page_label,- label_font,- t.text_muted,- );- // The checkbox toggles just this page without requiring a modifier. Keep it- // outside the page image, including on very tall or wide pages.- let mut checked = view.selected.contains(&i);- let check_rect = Rect::from_min_size(c.min + vec2(8.0, 8.0), Vec2::splat(20.0));- let check = ui.push_id(("org-check", i), |ui| ui.put(check_rect, widgets::checkbox_without_text(&mut checked))).inner;- let label = crate::i18n::fmt(tl!("Select page {label}"), &[("label", &p.label)]);- check.widget_info(|| egui::WidgetInfo::selected(egui::Role::CheckBox, true, checked, label.clone()));- if check.on_hover_text(label).changed() {- view.click_page(i, egui::Modifiers::COMMAND, false);- // The document shows the page picked here when the grid closes, as after a- // Pages-panel click, so reopening the grid keeps the pick (issue #1910).- view.go_to_page(i);- }- // Local actions always target the labelled page. The toolbar above the grid- // remains the place for actions on the whole selection.- if selected || resp.contains_pointer() || resp.has_focus() {- let actions = Rect::from_center_size(pos2(c.center().x, c.bottom() - 24.0), vec2(84.0, 26.0));- ui.scope_builder(- egui::UiBuilder::new().id_salt(("org-actions", i)).max_rect(actions).layout(egui::Layout::left_to_right(egui::Align::Center)),- |ui| {- ui.spacing_mut().item_spacing.x = 3.0;- ui.add_enabled_ui(editable, |ui| {- for (icon, degrees, key) in- [("rotate-ccw", -90, "Rotate page {label} counterclockwise"), ("rotate-cw", 90, "Rotate page {label} clockwise")]- {- let label = crate::i18n::fmt(tl!(key), &[("label", &p.label)]);- if icons::button(ui, icon, 26.0, false, &label).clicked() {- view.pending_edit = Some(Edit::RotatePages { pages: vec![i], degrees });- }- }- let label = crate::i18n::fmt(tl!("Delete page {label}"), &[("label", &p.label)]);- if ui.add_enabled_ui(info.pages.len() > 1, |ui| icons::button(ui, "trash-2", 26.0, false, &label)).inner.clicked() {- view.pending_edit = Some(Edit::DeletePages { pages: vec![i] });- }- });- },- );- }- if resp.clicked() {- let m = ui.input(|i| i.modifiers);- view.click_page(i, m, false);- view.go_to_page(i);- }- if resp.double_clicked() {- open_page = Some(i);- }- // Right-click: Extract, Replace, Cut, Copy, Paste (on the selection, or this page).- resp.context_menu(|ui| {- if !view.selected.contains(&i) {- view.selected = [i].into();- view.go_to_page(i);- }- if ui.button(tl!("Extract pages")).clicked() {- view.pending_action = Some(ViewAction::Extract);- ui.close();- }- if ui.button(tl!("Split document…")).clicked() {- view.pending_action = Some(ViewAction::SplitBeforeSelected);- ui.close();- }- if ui.add_enabled(editable, egui::Button::new(tl!("Replace pages…"))).clicked() {- view.pending_action = Some(ViewAction::ReplacePages);- ui.close();- }- ui.separator();- if ui.add_enabled(editable, egui::Button::new(tl!("Cut"))).clicked() {- view.pending_action = Some(ViewAction::CopyPages { cut: true });- ui.close();- }- if ui.button(tl!("Copy")).clicked() {- view.pending_action = Some(ViewAction::CopyPages { cut: false });- ui.close();- }- if ui.add_enabled(editable, egui::Button::new(tl!("Paste after"))).clicked() {- view.pending_action = Some(ViewAction::PastePages);- ui.close();- }- });- }- }- // Between pages (and at both ends): insert files right there.- if editable && !middle_gesture && view.org_drag.is_none() {- let mid = |r: &Rect| r.top() + 16.0 + (cell.y - 88.0) / 2.0;- for (i, c) in &cells {- let label = info- .pages- .get(*i)- .map(|p| crate::i18n::fmt(tl!("Insert a file before page {label}"), &[("label", &p.label)]))- .unwrap_or_default();- if gap_button(ui, *i, pos2(c.left(), mid(c)), cell.y - 88.0, label, t) {- view.pending_action = Some(ViewAction::InsertFromFileAt(*i));- }- }- if let Some((i, c)) = cells.last()- && i + 1 == info.pages.len()- && gap_button(ui, i + 1, pos2(c.right(), mid(c)), cell.y - 88.0, tl!("Insert a file at the end").to_string(), t)- {- view.pending_action = Some(ViewAction::InsertFromFileAt(i + 1));- }- }- // While dragging: the gap the pages would go to, drawn as a bar.- if let (Some(pages), Some(p)) = (view.org_drag.clone(), ui.input(|i| i.pointer.hover_pos())) {- // Ctrl (Option on macOS) held over the drop copies the pages; see #2997.- let copying = copy_modifier(ui.ctx(), &ui.input(|i| i.modifiers));- if let Some(gap) = drop_gap(&cells, p) {- let x = match cells.iter().find(|(i, _)| *i == gap) {- Some((_, r)) => r.left() + 3.0,- None => cells.last().map_or(0.0, |(_, r)| r.right() - 3.0),- };- let row = cells.iter().find(|(i, _)| *i == gap).or(cells.last()).map(|(_, r)| r.y_range()).unwrap_or(egui::Rangef::new(0.0, 0.0));- ui.painter().line_segment([pos2(x, row.min + 10.0), pos2(x, row.max - 10.0)], Stroke::new(3.0, t.accent));- let mut text_at = p + vec2(14.0, 14.0);- if copying {- // A "+" by the pointer: this drop copies the pages, it doesn't move them.- let badge = p + vec2(12.0, 12.0);- ui.painter().circle(badge, 9.0, t.accent, Stroke::new(1.0, t.accent));- let ink = Stroke::new(1.5, Color32::WHITE);- ui.painter().line_segment([badge - vec2(4.0, 0.0), badge + vec2(4.0, 0.0)], ink);- ui.painter().line_segment([badge - vec2(0.0, 4.0), badge + vec2(0.0, 4.0)], ink);- text_at.x += 18.0;- }- ui.painter().text(- text_at,- Align2::LEFT_TOP,- if pages.len() == 1 { tl!("1 page").to_string() } else { crate::i18n::fmt(tl!("{n} pages"), &[("n", &pages.len().to_string())]) },- theme::medium(12.0),- t.accent_text,- );+ let mut queue: Vec<RenderRequest> = wanted+ .iter()+ .map(|&(page, wanted_scale, wanted_tag, tile)| RenderRequest {+ page,+ kind: RequestKind::Pixels,+ tile,+ scale: wanted_scale,+ tag: wanted_tag,+ // The low-res backdrop under tiles is a preview: tiny images are skipped for it.+ // It is the whole-page request whose scale is not the current one; sharp tiles+ // and whole-page finals always draw everything.+ preview: tile.is_none() && (wanted_scale != scale || wanted_tag != tag),+ })+ .collect();+ // While the zoom or pan is settling, hold back sharp re-renders of pages that already+ // show something (a stale whole-page raster or older tiles, drawn stretched): each new+ // scale would cancel the running full-page interpret and restart it from scratch, and+ // each pan frame would queue a storm of full-page tile interprets.+ // Pages with nothing on screen yet still queue, so panning to a fresh page draws it.+ if sharp_held || pan_held {+ let main_tag = tag;+ queue.retain(|req| {+ // Fast pages render straight through: the hold only protects heavy pages+ // whose full-page interpret costs seconds.+ if !view.slow_pages.contains(&req.page) {+ return true;}- if drop {- view.org_drag = None;- if let Some(gap) = drop_gap(&cells, p) {- if copying {- // The copies land at the gap as it is: nothing leaves its place.- view.pending_edit = Some(Edit::DuplicatePages { pages: pages.clone(), at: Some(gap) });- view.selected = (gap..gap + pages.len()).collect();- } else {- // `to` counts positions without the moving pages.- let to = gap - pages.iter().filter(|x| **x < gap).count();- let first = pages[0];- let contiguous = pages.windows(2).all(|w| w[1] == w[0] + 1);- if !(contiguous && to == first) {- view.pending_edit = Some(Edit::MovePages { pages: pages.clone(), to });- view.selected = (to..to + pages.len()).collect();- }- }+ if req.tile.is_some() {+ let has_current_tile = view.tiles.keys().any(|(p, t, _, _)| *p == req.page && *t == req.tag);+ if has_current_tile {+ return false;}+ let has_any_surface = view.pages.contains_key(&req.page) || view.tiles.keys().any(|(p, _, _, _)| *p == req.page);+ !has_any_surface+ } else if req.tag != main_tag {+ // The low-res backdrop under tiles is zoom-independent: let it through,+ // it is the stretched surface the hold relies on.+ true+ } else {+ // The stale raster stays stretched until the zoom or pan settles; a page with+ // nothing on screen yet still renders.+ !view.pages.contains_key(&req.page)}- } else if drop {- view.org_drag = None;- }- });- // Files dragged in from outside go to the gap under the pointer. Some platforms don't say- // where the pointer is until the files are dropped; then the whole grid is the target.- let pointer = ui.input(|i| i.pointer.hover_pos()).filter(|p| viewport.contains(*p));- view.grid_gap = pointer.filter(|_| editable && view.org_drag.is_none()).and_then(|p| drop_gap(&cells, p));- if editable && ui.input(|i| !i.raw.hovered_files.is_empty()) {- let painter = ui.painter().with_clip_rect(viewport);- painter.rect_stroke(viewport.shrink(2.0), CornerRadius::same(6), Stroke::new(2.0, t.accent), egui::StrokeKind::Inside);- if let Some(gap) = view.grid_gap {- let at = cells.iter().find(|(i, _)| *i == gap).map(|(_, r)| (r.left() + 3.0, r.y_range()));- if let Some((x, row)) = at.or(cells.last().map(|(_, r)| (r.right() - 3.0, r.y_range()))) {- painter.line_segment([pos2(x, row.min + 10.0), pos2(x, row.max - 10.0)], Stroke::new(3.0, t.accent));- }- }- // A "+" that follows the pointer.- if let Some(p) = pointer {- let at = p + vec2(16.0, 16.0);- painter.circle_filled(at, 9.0, t.accent);- painter.line_segment([at - vec2(4.0, 0.0), at + vec2(4.0, 0.0)], Stroke::new(1.5, Color32::WHITE));- painter.line_segment([at - vec2(0.0, 4.0), at + vec2(0.0, 4.0)], Stroke::new(1.5, Color32::WHITE));- }- }- view.auto_scroll.paint(ui, viewport);- // Pinch, or Ctrl/⌘ with the wheel, zooms the grid about the page under the pointer.- let pinch = crate::motion::zoom_delta(ui.ctx());- if (pinch - 1.0).abs() > 0.001 && pointer.is_some() && !middle_gesture {- view.grid_zoom_request = Some(view.grid_zoom * pinch);- }- if let Some(zoom) = view.grid_zoom_request.take() {- let before = view.grid_zoom;- view.set_grid_zoom(zoom);- if view.grid_zoom != before {- // Keep the page under the pointer (or else the first one in view) where it is.- let under = pointer.and_then(|p| cells.iter().find(|(_, r)| r.contains(p)));- let anchor = under.or_else(|| cells.iter().find(|(_, r)| r.bottom() > viewport.top()));- view.grid_anchor = anchor.map(|(i, r)| (*i, r.top() - viewport.top()));- ui.ctx().request_repaint();- }+ });}- // When this frame's thumbnail will cover the cell, drop the sharp render without waiting- // for that texture to arrive.- let density = thumbnail_density(view.thumb_demand.len(), ppp);- in_view.retain(|&(page, want)| {- info.pages.get(page).is_none_or(|p| (device_pixels(p.width, thumbnail_scale(p.width, p.height, density)) as f32) < want * GRID_SHARP.start())- });- sharper.retain(|req| in_view.iter().any(|(page, _)| *page == req.page));- view.grid_pages.retain(|page, _| in_view.iter().any(|(kept, _)| kept == page));- // Sharp renders of the pages in view join this frame's demand ahead of the thumbnails.- view.frame_queue.extend(sharper);- if let Some(p) = open_page {- view.organize = false;- view.go_to_page(p);+ // Text layers: visible pages for selection, every page while a search is active. (Select All+ // of the document needs no more: shown pages highlight as their text comes, and Copy reads+ // 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<usize> = if hand { Vec::new() } else { visible_now.iter().copied().filter(need_text).collect() };+ if view.find.as_ref().is_some_and(|f| !f.case_query.trim().is_empty()) {+ let n = info.pages.len();+ let rest: Vec<usize> = (0..n).map(|k| (cur + k) % n).filter(need_text).filter(|p| !text_pages.contains(p)).collect();+ text_pages.extend(rest);}+ queue.extend(text_pages.into_iter().map(|page| RenderRequest {+ page,+ kind: RequestKind::Text,+ tile: None,+ scale: 1.0,+ tag: TEXT_TAG,+ preview: false,+ }));+ view.frame_queue = queue;+ view.frame_visible = visible_now.iter().copied().collect();}- /// A rendered raster as texture data. Its words are premultiplied RGBA bytes, exactly- /// `Color32`s, so the renderer's buffer becomes the image without a copy on the UI thread.- pub(crate) fn texture_image(size: [usize; 2], pixels: pdfcraft_render::Pixels) -> egui::ColorImage {- match bytemuck::allocation::try_cast_vec::<u32, Color32>(pixels.into_words()) {- Ok(px) if px.len() == size[0].saturating_mul(size[1]) => egui::ColorImage::new(size, px),- Ok(px) => egui::ColorImage::from_rgba_premultiplied(size, bytemuck::cast_slice(&px)),- Err((_, words)) => egui::ColorImage::from_rgba_premultiplied(size, bytemuck::cast_slice(&words)),+ /// Acts on the notice bar button that was clicked.+ fn apply_notice(app: &mut PdfCraftApp, index: usize, notice: Option<Notice>) {+ match notice {+ #[cfg(not(target_arch = "wasm32"))]+ Some(Notice::Reload) => app.watch.reload_request = app.views.get(index).map(|view| view.id),+ #[cfg(target_arch = "wasm32")]+ Some(Notice::Reload) => {}+ Some(Notice::Repairs) => app.dialog = Some(crate::Dialog::Properties(crate::PropsTab::Advanced)),+ Some(Notice::Security) => app.dialog = Some(crate::Dialog::Properties(crate::PropsTab::Security)),+ Some(Notice::Unlock) => {+ if let Some(doc) = app.views.get(index).and_then(|view| app.session.get(view.id)) {+ app.unlock_prompt = Some(crate::UnlockPrompt::new(doc, None));+ }+ }+ // Flags the view: the tab closes at the top of the next frame, where no document+ // borrow is held.+ Some(Notice::Close) => {+ if let Some(view) = app.views.get_mut(index) {+ view.close_requested = true;+ }+ }+ Some(Notice::Signatures) => app.right = Some(RightPanel::Signatures),+ Some(Notice::FieldHighlights(on)) => app.view_defaults.highlight_fields = on,+ Some(Notice::Console) => app.dialog = Some(crate::Dialog::JsConsole),+ // Back on in Preferences ▸ General.+ Some(Notice::HideSecured) => app.show_secured_notice = false,+ None => {}}}- /// A luminance preview for a monochrome print. `Color32` stores premultiplied pixels, so a- /// non-opaque colour's alpha is restored after multiplying the unmultiplied RGB by its- /// luminance. This uses the display gamma-space weights users expect in editors/print dialogs,- /// not the linear-light coefficients of a colour-managed render.- fn grayscale(mut img: egui::ColorImage) -> egui::ColorImage {- for c in img.pixels.iter_mut() {- let a = c.a();- let luminance = f32::from(c.r()) * 0.299_f32 + f32::from(c.g()) * 0.587_f32 + f32::from(c.b()) * 0.114_f32;- let gray = if a == 0 || a == 255 {- luminance.round() as u8- } else {- // Unmultiply first, so translucent content keeps its paper-relative luminance.- let f = f32::from(a) / 255.0;- let un = [f32::from(c.r()) / f, f32::from(c.g()) / f, f32::from(c.b()) / f];- let l = un[0] * 0.299_f32 + un[1] * 0.587_f32 + un[2] * 0.114_f32;- (f * l).round() as u8- };- *c = Color32::from_rgba_premultiplied(gray, gray, gray, a);+ /// The snapshot notice bar's Close was clicked: close here, where no document borrow is held. The+ /// tab is looked up by id: indices may have shifted since the click, and the flag rides its own+ /// view, so a stale flag can never close the wrong tab. Whether a tab was closed (or asked about).+ fn close_requested_tab(app: &mut PdfCraftApp, index: usize) -> bool {+ let pending = app.views.get(index).filter(|v| v.close_requested).map(|v| v.id).and_then(|id| app.views.iter().position(|v| v.id == id));+ let Some(i) = pending else { return false };+ app.views[i].close_requested = false;+ if app.has_unsaved_work(i) {+ app.close_request = Some(crate::CloseRequest::Tab(app.views[i].id));+ } else {+ app.close_tab(i);}- img+ true}- #[cfg(test)]- mod tests {- #[test]- fn zoom_anchor_scroll_stays_within_the_content() {- let (content, viewport) = (vec2(1000.0, 2000.0), vec2(800.0, 600.0));- // Past the end: clamped to the maximum (200, 1400), not left for egui to snap back.- assert_eq!(anchored_scroll(pos2(900.0, 1900.0), vec2(0.0, 0.0), content, viewport), vec2(200.0, 1400.0));- // Before the start.- assert_eq!(anchored_scroll(pos2(10.0, 10.0), vec2(300.0, 300.0), content, viewport), Vec2::ZERO);- // Inside: unchanged.- assert_eq!(anchored_scroll(pos2(150.0, 800.0), vec2(100.0, 100.0), content, viewport), vec2(50.0, 700.0));- // Content smaller than the viewport: no scrolling.- assert_eq!(anchored_scroll(pos2(400.0, 400.0), Vec2::ZERO, vec2(500.0, 500.0), viewport), vec2(0.0, 0.0));- }-- #[test]- fn page_size_hint_zone_is_the_bottom_left_quadrant() {- let area = Rect::from_min_max(pos2(100.0, 50.0), pos2(500.0, 450.0));- assert!(in_size_hint_zone(area, pos2(110.0, 440.0)));- assert!(!in_size_hint_zone(area, pos2(110.0, 100.0)), "top-left");- assert!(!in_size_hint_zone(area, pos2(400.0, 440.0)), "bottom-right");- assert!(!in_size_hint_zone(area, pos2(50.0, 440.0)), "outside");- assert!(!in_size_hint_zone(area, pos2(f32::NAN, 440.0)));- }-- use super::*;-- #[test]- fn typed_zoom_percentages_parse() {- for (typed, zoom) in [("150", 1.5), ("150%", 1.5), (" 62.5 % ", 0.625), ("6400%", 64.0)] {- assert_eq!(DocView::parse_zoom_percent(typed), Some(zoom), "{typed}");- }- for typed in ["", "%", "abc", "0", "-50", "NaN", "inf", "1e40", "150%%x", "%150"] {- assert_eq!(DocView::parse_zoom_percent(typed), None, "{typed}");- }- }-- /// A rotated (landscape) page is drawn as wide as the cell allows and centred in the picture- /// area, as Acrobat draws it, not as a small strip pinned to the top; a portrait page still- /// fills the area's height; neither covers the checkbox corner or the label below.- #[test]- fn grid_pages_are_centred_and_as_large_as_the_cell_allows() {- let cell = Rect::from_min_size(pos2(100.0, 50.0), vec2(190.0, 282.0));- let area = Rect::from_min_max(pos2(cell.left(), cell.top() + 16.0), pos2(cell.right(), cell.bottom() - 72.0));- let checkbox = Rect::from_min_size(cell.min + vec2(8.0, 8.0), Vec2::splat(20.0));- let landscape = grid_page_rect(cell, vec2(842.0, 595.0));- assert!((landscape.center().y - area.center().y).abs() < 0.01, "centred vertically: {landscape:?}");- assert!((landscape.center().x - cell.center().x).abs() < 0.01);- assert!((landscape.width() - (cell.width() - 32.0)).abs() < 0.01, "as wide as the cell allows: {landscape:?}");- assert!(!landscape.intersects(checkbox));- let portrait = grid_page_rect(cell, vec2(595.0, 842.0));- assert!(area.contains_rect(portrait), "inside the picture area: {portrait:?}");- assert!((portrait.center().y - area.center().y).abs() < 0.01);- assert!(portrait.left() >= checkbox.right(), "clear of the checkbox: {portrait:?}");- // Degenerate sizes still give a finite rectangle inside the cell.- for page in [vec2(0.0, 0.0), vec2(1e9, 1.0), vec2(1.0, 1e9), vec2(f32::NAN, 10.0), vec2(f32::INFINITY, 10.0)] {- let r = grid_page_rect(cell, page);- assert!(r.is_finite() && cell.contains_rect(r), "{page:?} -> {r:?}");- }+ /// Where the pages are laid out, for placing the scroll area.+ #[derive(Clone, Copy)]+ struct ScrollGeometry<'a> {+ rects: &'a [Rect],+ y_shift: f32,+ content_w: f32,+ content_h: f32,+ avail: Rect,+ middle_gesture: bool,+ hand: bool,+ }++ /// The page view's scroll area, with the offset this frame's jumps, drags and zoom anchor ask for.+ fn page_scroll_area(ui: &egui::Ui, view: &mut DocView, geometry: &ScrollGeometry<'_>) -> egui::ScrollArea {+ let ScrollGeometry { rects, y_shift, content_w, content_h, avail, middle_gesture, hand } = *geometry;+ let mut scroll = egui::ScrollArea::both().auto_shrink([false, false]).scroll_source(egui::scroll_area::ScrollSource {+ drag: if middle_gesture {+ egui::scroll_area::DragScroll::Never+ } else if hand {+ egui::scroll_area::DragScroll::Always+ } else {+ egui::scroll_area::DragScroll::OnTouch+ },+ ..Default::default()+ });+ // Each document keeps its own scroll position when switching tabs (#189).+ scroll = scroll.id_salt(("page-view", view.id));+ // Every scroll here asks for no animation. An animated area would still queue a zero-length+ // offset target for the next frame, which overwrites the jump a page turn just set.+ scroll = scroll.animated(false);+ // A newly opened document starts at the top. eframe saves egui's memory with the settings+ // and document ids start again at 1 every launch, so the offset stored under this id can be+ // where an earlier session left another document.+ if !std::mem::replace(&mut view.shown, true) {+ scroll = scroll.scroll_offset(Vec2::ZERO);}-- fn signature(signed: bool, visible: bool, page: Option<usize>, rect: Option<[f64; 4]>) -> pdfcraft_engine::SignatureInfo {- pdfcraft_engine::SignatureInfo {- field: "Signature1".into(),- signed,- page,- rect,- visible,- signer: None,- certificate: None,- chain: Vec::new(),- date: None,- signing_time: None,- reason: None,- location: None,- contact: None,- sub_filter: None,- doc_timestamp: false,- certify: None,- revision: 1,- signed_len: 0,- digest: None,- algorithm: None,- timestamp: false,- timestamp_time: None,- status: pdfcraft_engine::SignatureStatus::Valid,- modification: pdfcraft_engine::sign::Modification::None,- details: Vec::new(),+ // The Hand tool pans here, before the pages are laid out, so the page moves with the pointer+ // in the frame the pointer moves (#924). Scrolling by the drag from inside the area moved the+ // page only after that frame was drawn, a frame behind. The frame egui tells the drag from a+ // click, the page catches up with all the pointer has moved since the press. A jump asked for+ // below still wins.+ if hand+ && !middle_gesture+ && let Some(id) = view.page_widget.filter(|id| ui.ctx().is_being_dragged(*id))+ {+ let moved = if ui.ctx().drag_started_id() == Some(id) {+ ui.input(|i| i.pointer.total_drag_delta()).unwrap_or(Vec2::ZERO)+ } else {+ ui.input(|i| i.pointer.delta())+ };+ if moved != Vec2::ZERO {+ view.end_find_following();}+ // Within the content, as egui keeps it: past an end the page would show there for a+ // frame and spring back. `max` is never NaN or below zero, so the clamp can't panic.+ let max = vec2((content_w - avail.width()).max(0.0), (content_h - avail.height()).max(0.0));+ scroll = scroll.scroll_offset((view.last_scroll - moved).clamp(Vec2::ZERO, max));}-- #[test]- fn signature_badges_keep_signed_visible_widgets_on_the_page() {- let rect = [10.0, 10.0, 100.0, 50.0];- let signatures =- vec![signature(true, true, Some(0), Some(rect)), signature(true, true, Some(1), Some(rect)), signature(true, true, Some(0), Some(rect))];- let badges = signature_badges(&signatures, 0);- assert_eq!(badges.len(), 2);- assert_eq!(badges[0].rect, rect);- }-- #[test]- fn signature_badges_skip_unsigned_invisible_and_unplaced_fields() {- let rect = [10.0, 10.0, 100.0, 50.0];- let signatures = vec![- signature(false, true, Some(0), Some(rect)),- signature(true, false, Some(0), Some(rect)),- signature(true, true, Some(0), None),- signature(true, true, Some(0), Some(rect)),- ];- let badges = signature_badges(&signatures, 0);- assert_eq!(badges.len(), 1);- assert_eq!(badges[0].rect, rect);- }-- #[test]- fn signature_badges_skip_rectangles_that_cannot_reach_the_screen() {- let hostile = vec![- [f64::NAN, 10.0, 100.0, 50.0],- [10.0, f64::INFINITY, 100.0, 50.0],- [10.0, 10.0, f64::NEG_INFINITY, 50.0],- [10.0, 10.0, 1e300, 50.0],- [10.0, 10.0, 100.0, 50.0],- ];- let signatures: Vec<_> = hostile.into_iter().map(|rect| signature(true, true, Some(0), Some(rect))).collect();- let badges = signature_badges(&signatures, 0);- assert_eq!(badges.len(), 1);+ if let Some(v) = view.sync_scroll.take() {+ scroll = scroll.scroll_offset(v);}-- #[test]- fn page_zoom_reads_the_side_the_page_width_is_on() {- // A 200 x 100 pt page at 2 pixels per point: 400 x 200 on screen, or 200 x 400 turned.- let xf = |rot: u16, size: Vec2| PageXform { rect: Rect::from_min_size(Pos2::ZERO, size), rot, pw: 200.0, ph: 100.0 };- for rot in [0, 180] {- assert_eq!(xf(rot, vec2(400.0, 200.0)).zoom(), 2.0, "{rot}");- }- for rot in [90, 270] {- assert_eq!(xf(rot, vec2(200.0, 400.0)).zoom(), 2.0, "{rot}: the width runs down the screen");+ if let Some((page, fx, fy, rel)) = view.zoom_anchor.take() {+ let r = rects[page.min(rects.len() - 1)];+ let point = pos2(r.left() + fx * r.width(), r.top() - y_shift + fy * r.height());+ scroll = scroll.scroll_offset(anchored_scroll(point, rel, vec2(content_w, content_h), avail.size()));+ } else if let Some((page, frac)) = view.goto.take() {+ let page = page.min(rects.len() - 1);+ let r = rects[page];+ // Clamped here: egui clamps only after drawing, so a page that fits was drawn MARGIN - page_gap()+ // too high for a frame and then hopped into place. (`avail` is the viewport, as the+ // scroll bars float.)+ let max_y = (content_h - avail.height()).max(0.0);+ scroll = scroll.vertical_scroll_offset((r.top() - y_shift - view.page_gap() + frac * r.height()).max(0.0).min(max_y));+ // Horizontally too, as Acrobat does (#2665): beside a much wider page the others sit off+ // to one side. A page already shown whole, or one filling the window's width, keeps the+ // scroll, so paging through a zoomed-in document stays on the same column. Otherwise a+ // page that fits is centred, and a wider one scrolled just far enough to fill the window.+ // The page counts with its side gutters, which keep its edge clear of the floating+ // quick-action bar as the layout does.+ let (x, w) = (view.last_scroll.x, avail.width());+ let (left, right) = (r.left() - SIDE, r.right() + SIDE);+ let target = if right - left <= w { if left >= x && right <= x + w { x } else { r.center().x - w / 2.0 } } else { x.clamp(left, right - w) };+ if (target - x).abs() > 0.5 {+ scroll = scroll.horizontal_scroll_offset(target.clamp(0.0, (content_w - w).max(0.0)));}}+ scroll+ }- #[test]- fn snapshot_tabs_read_like_their_source_plus_the_suffix() {- let snap = Snapshot { kind: SnapshotKind::SignedVersion, revision: 1, from: "report.pdf".into() };- assert_eq!(snapshot_tab_name("Report", "report.pdf", &snap), "Report (signed version)");- let rev = Snapshot { kind: SnapshotKind::Revision, revision: 2, from: "report.pdf".into() };- assert_eq!(snapshot_tab_name("Report", "report.pdf", &rev), "Report (revision 2)");- assert_eq!(snapshot_tab_name("report.pdf", "report.pdf", &snap), "report.pdf");- assert_eq!(snapshot_tab_name("report (revision 2).pdf", "report (revision 2).pdf", &rev), "report (revision 2).pdf");+ /// Notes how far the page view scrolled this frame: reader-owned scrolling ends search following,+ /// a pan holds back fresh tile renders until it settles, and a glide keeps going or stops. Whether+ /// a pan is still settling.+ fn track_scroll<T>(ui: &egui::Ui, view: &mut DocView, out: &egui::containers::scroll_area::ScrollAreaOutput<T>, glide: Vec2) -> bool {+ let scroll_offset = out.state.clamped_offset();+ // The document ScrollArea's own scroll surfaces move the offset without the wheel deltas+ // above: its two scroll-bar tracks/handles and, for touch or the Hand tool, its drag+ // background. The output gives us the area id, and egui's pinned ScrollArea registers those+ // widgets under `id.with(0)` (horizontal), `id.with(1)` (vertical) and `id.with("area")`.+ // Ask for their exact responses instead of treating any held drag as scrolling: a text+ // selection, a panel splitter or another widget's drag must not excuse the programmatic jump+ // a search flash makes, while a track click (which moves the offset with no pointer motion)+ // must still count as the reader scrolling.+ let scroll_surface = |id: egui::Id| ui.ctx().read_response(id).is_some_and(|r| r.is_pointer_button_down_on() || r.dragged() || r.clicked());+ let pointer_scrolling = scroll_surface(out.id.with(0usize)) || scroll_surface(out.id.with(1usize)) || scroll_surface(out.id.with("area"));+ if pointer_scrolling && (scroll_offset - view.last_scroll).length() > 2.0 {+ view.end_find_following();}-- #[test]- fn grayscale_converts_colours_to_their_luminance() {- let img = egui::ColorImage::new([2, 1], vec![Color32::from_rgb(255, 0, 0), Color32::from_rgba_premultiplied(0, 51, 102, 128)]);- let gray = grayscale(img);- let opaque = gray.pixels[0];- assert_eq!(opaque.to_array(), [76, 76, 76, 255]);- // Unmultiply RGB first, so a translucent colour keeps its paper-relative luminance.- let translucent = gray.pixels[1];- assert_eq!(translucent.to_array(), [42, 42, 42, 128]);+ let now_settle = ui.input(|i| i.time);+ if (scroll_offset - view.last_scroll).length() > 2.0 {+ view.pan_hold_until = now_settle + 0.25;+ ui.ctx().request_repaint_after(std::time::Duration::from_millis(280));}-- #[test]- fn black_white_and_transparents_are_preserved_by_grayscale() {- let img = egui::ColorImage::new([3, 1], vec![Color32::BLACK, Color32::WHITE, Color32::TRANSPARENT]);- let gray = grayscale(img);- assert_eq!(gray.pixels[0].to_array(), [0, 0, 0, 255]);- assert_eq!(gray.pixels[1].to_array(), [255, 255, 255, 255]);- assert_eq!(gray.pixels[2].to_array(), [0, 0, 0, 0]);+ if glide != Vec2::ZERO {+ view.fling.moved((scroll_offset - view.last_scroll).length() > 0.01);}+ view.last_scroll = scroll_offset;+ now_settle < view.pan_hold_until+ }- #[test]- fn rendered_rasters_become_texture_images_without_a_copy() {- let pdf = b"%PDF-1.4- 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 100 50] /Contents 4 0 R >> endobj- 4 0 obj << /Length 35 >> stream- 0 0 1 rg 10 10 30 20 re f- endstream endobj- trailer << /Root 1 0 R >>- %%EOF";- let mut r = pdfcraft_render::PageRenderer::new(Arc::new(pdf.to_vec()), Default::default());- let out = r.render(RenderRequest { page: 0, kind: RequestKind::Pixels, tile: None, scale: 1.5, tag: 0, preview: false });- assert!(out.error.is_none(), "{:?}", out.error);- let size = [out.width as usize, out.height as usize];- let copied = egui::ColorImage::from_rgba_premultiplied(size, &out.rgba);- let at = out.rgba.as_ptr();- let img = texture_image(size, out.rgba);- assert_eq!(img, copied);- assert_eq!(img.pixels.as_ptr().cast::<u8>(), at, "the renderer's own buffer");+ /// The hover tip, find bar, size hint and the in-place editors drawn over the pages. Whether the+ /// text editor was finished.+ fn frame_overlays(ui: &mut egui::Ui, view: &mut DocView, env: &PageEnv<'_>, primary_down: bool, hover_text: Option<(Pos2, String)>) -> bool {+ let PageEnv { added, author, avail, can_modify, doc, form, info, prefs, t, today, tool, units, unobstructed, .. } = *env;+ if let Some((pos, text)) = hover_text {+ // Click-through, as a tooltip is: the pages lose the pointer under anything that isn't.+ let tip = egui::Area::new(egui::Id::unique("canvas-hover")).order(egui::Order::Tooltip).interactable(false);+ tip.fixed_pos(pos + vec2(14.0, 16.0)).show(ui.ctx(), |ui| {+ egui::Frame::popup(ui.style()).show(ui, |ui| {+ ui.set_max_width(320.0);+ ui.label(text);+ });+ });}-- #[test]- fn tiles_stay_granular_up_close_and_cover_giant_sheets_in_a_handful() {- // Ordinary zooms keep 1024 px tiles; degenerate scales fall back to it, never zero.- assert_eq!(tile_side(1.0, 2000), TILE);- assert_eq!(tile_side(4.0, 2000), TILE);- assert_eq!(tile_side(f32::NAN, 2000), TILE);- assert_eq!(tile_side(f32::INFINITY, 2000), TILE);- assert_eq!(tile_side(0.0, 2000), TILE);- // Zoomed viewports need a few large tiles instead of many small ones.- assert_eq!(tile_side(12.0, 2000), 2048);- assert_eq!(tile_side(20.0, 2000), 3413);- assert_eq!(tile_side(100.0, 2000), 4096);- // A giant sheet at fit width (6740 px long side) is covered four tiles a side.- assert_eq!(tile_side(96.0 / 72.0, 6740), 1685);- // The backend clamps tile sides at 4096.- assert_eq!(tile_side(20.0, 100_000), 4096);+ find_bar(view, info.pages.len(), avail, ui, t);+ page_size_hint(view, info, units, avail, unobstructed, ui, t);+ if tool == QuickTool::EnhanceCamera {+ crate::camera_ui::bar(ui.ctx(), view, avail, t, can_modify);}-- #[test]- fn grid_zoom_is_clamped_and_sharp_renders_tolerate_a_pinch() {- assert!(sharp_enough(900, 876.0) && sharp_enough(800, 876.0) && sharp_enough(1300, 876.0));- assert!(!sharp_enough(264, 876.0), "a thumbnail stretched over a zoomed page");- assert!(!sharp_enough(876, 200.0), "far larger than drawn: wasteful");- assert!(!sharp_enough(100, 0.0) && !sharp_enough(100, f32::NAN));- let mut v = view(3, PageLayout::Single, true);- for odd in [f32::NAN, f32::INFINITY] {- v.set_grid_zoom(odd);- assert_eq!(v.grid_zoom(), 1.0);- }- v.set_grid_zoom(99.0);- assert_eq!(v.grid_zoom(), 3.0);- v.set_grid_zoom(-4.0);- assert_eq!(v.grid_zoom(), 0.5);+ if let Some(e) = comments::composer(ui.ctx(), view, info, prefs) {+ view.pending_edit = Some(e);}-- fn view(pages: usize, layout: PageLayout, continuous: bool) -> DocView {- let info = pdfcraft_render::DocInfo {- pages: (0..pages)- .map(|_| pdfcraft_render::PageInfo { width: 300.0, height: 400.0, label: String::new(), crop: [0.0, 0.0, 300.0, 400.0], rotation: 0 })- .collect(),- ..Default::default()- };- DocView::new(DocId(1), &info, ViewDefaults { layout, continuous, ..Default::default() })+ if let Some(e) = crate::edit_text_ui::overlay(ui.ctx(), view, info) {+ view.pending_edit = Some(e);}-- fn history_search_view() -> DocView {- let mut v = view(5, PageLayout::Single, true);- v.texts.insert(- 3,- pdfcraft_render::PageText {- glyphs: vec![pdfcraft_render::TextGlyph {- text: "match".into(),- rect: [20.0, 260.0, 60.0, 280.0],- quad: [[20.0, 260.0], [60.0, 260.0], [60.0, 280.0], [20.0, 280.0]],- direction: [1.0, 0.0],- }],- line_of: vec![0],- space_before: vec![false],- }- .into(),- );- v.find = Some(Find { matches: vec![(3, 0..1), (3, 0..1), (1, 0..1)], current: Some(2), ..Default::default() });- v+ let text_box = crate::forms_ui::text_box(doc, view, form);+ if let Some(e) = crate::forms_ui::overlay(ui.ctx(), view, info, form, primary_down, text_box.as_ref(), today) {+ view.pending_edit = Some(e);}-- #[test]- fn explicit_search_jumps_record_history_and_keep_match_destination() {- for step in [None, Some(true), Some(false)] {- let mut v = history_search_view();- v.page_input = "draft in progress".into();- v.goto_point = Some((3, Some(0.8), Some(0.9), Vec2::ZERO));- if let Some(forward) = step {- v.find_step(forward);- } else {- v.go_to_match(0);- }- assert_eq!(v.back, vec![0], "explicit search jump must remember its origin");- assert_eq!(v.goto, Some((3, 0.5)), "keep the match offset instead of the page top");- assert_eq!(v.current, 3);- assert_eq!(v.current_page_label(None), "4");- // Chrome refreshes the idle page box; navigation must not overwrite a draft- // that may still be focused. DocView does not own the editor's focus state.- assert_eq!(v.page_input, "draft in progress");- assert!(v.goto_point.is_none(), "an earlier link destination cannot override the search offset");- v.go_to_match(1);- assert_eq!(v.back, vec![0], "same-page matches do not duplicate history");- assert!(v.view_history(false));- assert_eq!(v.current, 0);- assert!(v.view_history(true));- assert_eq!(v.current, 3);- assert!(v.view_history(false));- v.go_to_match(2);- assert!(v.forward.is_empty(), "a new explicit jump discards Forward");- assert_eq!(v.back, vec![0]);- }+ if let Some(e) = crate::fill_sign::type_box(ui.ctx(), view, info, author) {+ view.pending_edit = Some(e);}-- #[test]- fn automatic_search_updates_do_not_record_history_or_discard_forward() {- let mut v = history_search_view();- v.forward = vec![4];- v.find = Some(Find { query: "match".into(), ..Default::default() });- v.rerun_find();- assert_eq!(v.current, 3);- assert_eq!(v.goto, Some((3, 0.5)));- assert!(v.back.is_empty());- assert_eq!(v.forward, vec![4]);- v.find.as_mut().unwrap().current = None;- v.texts.insert(1, Arc::new(find_test_text("match")));- v.refresh_find_page(1);- assert_eq!(v.current, 1, "an automatic late match still follows its anchor");- assert!(v.back.is_empty(), "automatic search updates do not record history");- assert_eq!(v.forward, vec![4]);+ let (typed, text_done) = crate::content_ui::editor(ui.ctx(), view, info, added);+ if typed.is_some() {+ view.pending_edit = typed;}+ text_done+ }- /// One glyph per character on one line, for the search-order tests below.- fn find_test_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(),- }+ /// Full screen: the click turns the page unless it did something else first. It waits out the+ /// double-click time: turning on the first click's release sent a double-click's second click,+ /// meant to select a word, to the next page (review on #2070). A selection cancels it, and so do a+ /// link followed meanwhile and leaving full screen; a double-click elsewhere still turns once.+ /// `click` is `Some(back)` on the frame of a click, `back` when it was a shift-click.+ fn schedule_presentation_turn(ui: &egui::Ui, view: &mut DocView, click: Option<bool>, link_followed: bool) {+ let now = ui.input(|i| i.time);+ if let Some(back) = click+ && !link_followed+ && view.selection.is_none()+ && view.clicks < 2+ {+ let delay = ui.ctx().options(|o| o.input_options.max_double_click_delay);+ view.present_turn = Some((now + delay, !back));}-- /// A text-layer result for `page`, for the search tests below.- fn find_text_result(page: usize, text: &str) -> pdfcraft_render::RenderedPage {- pdfcraft_render::RenderedPage {- request: RenderRequest { page, kind: RequestKind::Text, tag: TEXT_TAG, ..Default::default() },- width: 0,- height: 0,- rgba: Default::default(),- error: None,- text: Some(Arc::new(find_test_text(text))),- warnings: Vec::new(),- millis: 0,+ if let Some((due, forward)) = view.present_turn {+ if link_followed || view.selection.is_some() || view.presentation.is_none() {+ view.present_turn = None;+ } else if now >= due {+ view.present_turn = None;+ view.step_page(forward);+ } else {+ ui.ctx().request_repaint_after(std::time::Duration::from_secs_f64((due - now).max(0.0)));}}+ }- /// Text layers arrive in whatever order the workers finish, not in page order. A search- /// started on page 1 must settle on page 1's match even when page 2's text arrives first,- /// instead of keeping the later match picked only because page 1 had not been read yet.- #[test]- fn automatic_search_match_follows_the_viewed_page_when_text_arrives_out_of_order() {- let mut v = view(2, PageLayout::Single, true);- v.current = 0;- v.find = Some(Find { query: "sample".into(), ..Default::default() });- v.rerun_find();- assert_eq!(v.find.as_ref().unwrap().current, None, "no text yet, so no match");-- let ctx = egui::Context::default();- let request = |page| RenderRequest { page, kind: RequestKind::Text, tag: TEXT_TAG, ..Default::default() };- let result = |page, text: &str| pdfcraft_render::RenderedPage {- request: request(page),- width: 0,- height: 0,- rgba: Default::default(),- error: None,- text: Some(Arc::new(find_test_text(text))),- warnings: Vec::new(),- millis: 0,- };- v.last_queue = vec![request(1), request(0)];- // Page 2's text finishes first, as it can when the workers race.- v.receive_result(&ctx, result(1, "Second page sample text"));- assert_eq!(v.find.as_ref().unwrap().current, Some(0), "the only known match is picked while page 1 is pending");-- v.receive_result(&ctx, result(0, "Panel sample draft notes"));- let f = v.find.as_ref().unwrap();- assert_eq!(f.matches.iter().map(|(p, _)| *p).collect::<Vec<_>>(), vec![0, 1]);- assert_eq!(f.current, Some(0), "page 1's match takes over once its text arrives");- assert_eq!(v.current, 0, "the view follows the first match at or after the page being viewed");- }-- /// A match the user picked (a click in the Search panel, or ⌘G) is not moved by a text- /// layer that arrives later: only automatic choices follow the viewed page.- #[test]- fn a_user_picked_search_match_stays_put_when_earlier_text_arrives() {- let mut v = view(2, PageLayout::Single, true);- v.current = 0;- v.find = Some(Find { query: "sample".into(), ..Default::default() });- v.rerun_find();- v.texts.insert(1, Arc::new(find_test_text("Second page sample text")));- v.refresh_find_page(1);- v.go_to_match(0);- assert_eq!(v.find.as_ref().unwrap().auto_from, None, "an explicit choice is not automatic");-- v.texts.insert(0, Arc::new(find_test_text("Panel sample draft notes")));- v.refresh_find_page(0);- let f = v.find.as_ref().unwrap();- assert_eq!(f.matches.iter().map(|(p, _)| *p).collect::<Vec<_>>(), vec![0, 1]);- assert_eq!(f.current, Some(1), "the picked match keeps its identity after page 1 is inserted");- assert_eq!(v.current, 1, "the user's page does not change under them");- }-- /// The automatic choice may move the view only while the reader has left it where that- /// choice put it. Navigating by the page box/Pages panel/outline or by view history is the- /// reader's decision: a text layer arriving afterwards must not pull them back to an- /// anchor-derived match. (The harness covers same-page wheel and pointer scrolling.)- #[test]- fn a_late_automatic_match_does_not_override_the_readers_navigation() {- enum Nav {- Page,- History,- }- for nav in [Nav::Page, Nav::History] {- let mut v = view(3, PageLayout::Single, true);- v.current = 0;- v.texts.insert(2, Arc::new(find_test_text("Second page sample")));- v.find = Some(Find { query: "sample".into(), ..Default::default() });- v.rerun_find();- assert_eq!((v.current, v.find.as_ref().unwrap().auto_page), (2, Some(2)), "the automatic match was shown");- match nav {- // The page box, the Pages panel and outline destinations all end here.- Nav::Page => v.go_to_page(1),- // View ▸ Page navigation ▸ Previous view writes `current` directly.- Nav::History => {- v.back = vec![1];- assert!(v.view_history(false));- }+ /// Follows the link that was clicked. A link to another file comes back, to be opened once the+ /// document is no longer borrowed.+ fn follow_link(+ app: &mut PdfCraftApp,+ index: usize,+ target: Option<LinkTarget>,+ ) -> Option<(pdfcraft_engine::DocId, String, pdfcraft_render::RemoteDestination)> {+ let view_id = app.views[index].id;+ match target? {+ LinkTarget::Page(p, dest) => {+ let view = &mut app.views[index];+ if let Some(doc) = app.session.get(view.id) {+ view.go_to_dest(p, dest, &doc.info);}- assert_eq!(v.current, 1);- v.texts.insert(0, Arc::new(find_test_text("First page sample")));- v.refresh_find_page(0);- let f = v.find.as_ref().unwrap();- assert_eq!(f.auto_from, None, "the reader's navigation ends automatic following");- assert_eq!(f.auto_page, None);- assert_eq!(v.current, 1, "a late match cannot pull the reader back");}+ LinkTarget::Uri(u) => app.request_document_url(&u, crate::LinkOrigin::Link),+ LinkTarget::SetLayers { changes, preserve_rb } => set_layers(app, index, &changes, preserve_rb),+ LinkTarget::RemoteGoTo { file, destination, .. } => return Some((view_id, file, destination)),+ LinkTarget::Other(s) => app.notify_fmt("This PDF uses the unsupported {s} action.", &[("s", &s)]),}+ None+ }- /// Typing on while the results arrive must not re-anchor the search on a page the automatic- /// flash picked. The anchor stays the page the reader was on when they started searching.- #[test]- fn refining_the_query_keeps_the_page_the_search_started_from() {- let mut v = view(3, PageLayout::Single, true);- v.current = 0;- v.texts.insert(2, Arc::new(find_test_text("Second page sample text")));- v.find = Some(Find { query: "sample".into(), ..Default::default() });- v.rerun_find();- assert_eq!((v.current, v.find.as_ref().unwrap().auto_from), (2, Some(0)), "the first query's match scrolled the view");-- // Page 1 has a match for the refined query, and so has page 3. Anchored on the page the- // automatic flash reached, the search would pick page 3; the starting page picks page 1.- v.texts.insert(0, Arc::new(find_test_text("Panel draft text")));- v.find.as_mut().unwrap().query = "text".into();- v.rerun_find();- let f = v.find.as_ref().unwrap();- assert_eq!(f.auto_from, Some(0), "refinement keeps the page the reader searched from");- assert_eq!(f.matches.first().map(|(p, _)| *p), Some(0));- assert_eq!(f.current, Some(0));- assert_eq!(v.current, 0);+ /// A finished marquee zoom, a signature rectangle drawn, or an empty signature field clicked.+ /// Returns the tool to go on with.+ fn finish_sign_requests(app: &mut PdfCraftApp, index: usize, mut tool: QuickTool) -> QuickTool {+ if let Some(done) = app.views[index].marquee_done.take() {+ app.finish_marquee(index, done);}-- /// ⌘G / Ctrl+G goes through `find_step`, an explicit choice like a Search-panel click: a- /// text layer arriving later must not undo it.- #[test]- fn keyboard_find_step_is_explicit_and_a_late_text_layer_cannot_undo_it() {- let mut v = view(3, PageLayout::Single, true);- v.current = 0;- v.texts.insert(1, Arc::new(find_test_text("first sample")));- v.texts.insert(2, Arc::new(find_test_text("second sample")));- v.find = Some(Find { query: "sample".into(), ..Default::default() });- v.rerun_find();- assert_eq!((v.current, v.find.as_ref().unwrap().auto_from), (1, Some(0)));-- let ctx = egui::Context::default();- ctx.input_mut(|i| {- i.events.push(egui::Event::Key {- key: egui::Key::G,- physical_key: None,- pressed: true,- repeat: false,- modifiers: egui::Modifiers::COMMAND,- });- });- shortcuts(&mut v, &ctx, Default::default());-- assert_eq!(v.current, 2, "the keyboard step chose the next match");- assert_eq!(v.find.as_ref().unwrap().auto_from, None, "the keyboard step is the user's choice");- assert_eq!(v.back, vec![1], "an explicit search jump records its origin");-- v.texts.insert(0, Arc::new(find_test_text("intro sample")));- v.refresh_find_page(0);- let f = v.find.as_ref().unwrap();- assert_eq!(v.current, 2, "the chosen match keeps the view");- assert_eq!(f.current.and_then(|i| f.matches.get(i)).map(|(p, _)| *p), Some(2));+ // A signature rectangle was drawn, or an empty signature field clicked.+ let drawn = app.views[index].sign.drawn.take();+ if let (Some((page, rect)), QuickTool::SignArea { certify }) = (drawn, tool) {+ tool = QuickTool::Select;+ app.quick_tool = tool;+ app.start_signing(page, Some(rect), None, certify.then_some(2));}-- /// A page whose text extraction failed keeps the automatic anchor: the failure selects the- /// next match without moving the view, and a later text layer can still follow the anchor.- #[test]- fn a_failed_text_layer_keeps_the_automatic_anchor_without_jitter() {- let mut v = view(3, PageLayout::Single, true);- v.current = 0;- v.texts.insert(1, Arc::new(find_test_text("first sample")));- v.texts.insert(2, Arc::new(find_test_text("second sample")));- v.find = Some(Find { query: "sample".into(), ..Default::default() });- v.rerun_find();- assert_eq!((v.current, v.find.as_ref().unwrap().auto_page), (1, Some(1)));-- let goto = v.goto;- let ctx = egui::Context::default();- let request = RenderRequest { page: 1, kind: RequestKind::Text, ..Default::default() };- v.last_queue = vec![request];- v.receive_result(- &ctx,- pdfcraft_render::RenderedPage {- request,- width: 0,- height: 0,- rgba: Default::default(),- error: Some("extraction failed".into()),- text: None,- warnings: Vec::new(),- millis: 0,- },- );- let f = v.find.as_ref().unwrap();- assert_eq!(f.matches.iter().map(|(p, _)| *p).collect::<Vec<_>>(), vec![2]);- assert_eq!(f.current, Some(0), "the remaining match is selected");- assert_eq!((f.auto_from, f.auto_page), (Some(0), Some(1)), "a failure does not end automatic following");- assert_eq!(v.current, 1, "a failure never moves the view");- assert_eq!(v.goto, goto, "a failure never flashes the match");-- // The search still follows its original page when that page's text arrives.- v.last_queue = vec![RenderRequest { page: 0, kind: RequestKind::Text, tag: TEXT_TAG, ..Default::default() }];- v.receive_result(&ctx, find_text_result(0, "intro sample"));- assert_eq!(v.current, 0, "the anchor's earlier match takes over");- let f = v.find.as_ref().unwrap();- assert_eq!(f.current.and_then(|i| f.matches.get(i)).map(|(p, _)| *p), Some(0));+ if let Some(field) = app.views[index].sign.field.take() {+ let signed = app.session.get(app.views[index].id).is_some_and(|d| d.signatures.iter().any(|s| s.field == field && s.signed));+ if signed {+ app.right = Some(RightPanel::Signatures);+ if !app.sig_expanded.contains(&field) {+ app.sig_expanded.push(field);+ }+ } else {+ let page = app.views[index].current;+ app.start_signing(page, None, Some(field), None);+ }}+ tool+ }- /// A reader who navigated before a page's text failed is not pulled back by a later- /// matching layer: the failure path must preserve the same `Ended` state as a successful- /// one, and the result list may select the late match without revealing it.- #[test]- fn a_failed_text_layer_after_navigation_does_not_reveal_a_late_match() {- let mut v = view(3, PageLayout::Single, true);- v.current = 0;- v.find = Some(Find { query: "sample".into(), ..Default::default() });- v.rerun_find();- v.go_to_page(2);- let moved = v.goto;- assert!(v.find.as_ref().unwrap().follow_ended, "the reader navigated before any match arrived");-- let ctx = egui::Context::default();- let failed = RenderRequest { page: 1, kind: RequestKind::Text, tag: TEXT_TAG, ..Default::default() };- v.last_queue = vec![failed];- v.receive_result(- &ctx,- pdfcraft_render::RenderedPage {- request: failed,- width: 0,- height: 0,- rgba: Default::default(),- error: Some("extraction failed".into()),- text: None,- warnings: Vec::new(),- millis: 0,- },- );- let f = v.find.as_ref().unwrap();- assert!(f.follow_ended, "a failure after navigation does not restart following");- assert_eq!((f.auto_from, f.auto_page), (None, None));- assert_eq!(v.current, 2, "a failure never moves the view");- assert_eq!(v.goto, moved);-- let arrived = RenderRequest { page: 0, kind: RequestKind::Text, tag: TEXT_TAG, ..Default::default() };- v.last_queue = vec![arrived];- v.receive_result(&ctx, find_text_result(0, "intro sample"));- let f = v.find.as_ref().unwrap();- assert!(f.follow_ended);- assert_eq!((f.auto_from, f.auto_page), (None, None));- assert_eq!(v.current, 2, "the late matching layer does not pull the reader back");- assert_eq!(v.goto, moved, "no flash was issued");- assert_eq!(f.current.and_then(|i| f.matches.get(i)).map(|(p, _)| *p), Some(0), "the result list still selects the late match");+ /// When not scrolling continuously, only one row is shown at a time: the current page, or the+ /// current two-page spread (with the cover rule). These indices drive paging, which pages are+ /// drawn, and the content height (#752). Empty for a document with no pages.+ fn shown_row(view: &DocView, rects: &[Rect]) -> Vec<usize> {+ if rects.is_empty() {+ return Vec::new();}-- /// The reader can navigate before any text layer has supplied a match. That navigation- /// still ends automatic following, so the first late match is listed but not revealed by- /// a flash that would pull the reader back.- #[test]- fn navigation_before_the_first_match_is_not_overridden_by_a_late_text_layer() {- let mut v = view(3, PageLayout::Single, true);- v.current = 0;- v.find = Some(Find { query: "sample".into(), ..Default::default() });- v.rerun_find();- let f = v.find.as_ref().unwrap();- assert_eq!(f.current, None, "no text layer has arrived yet");- assert_eq!((f.auto_from, f.auto_page), (Some(0), Some(0)));-- v.go_to_page(2);- assert_eq!(v.goto, Some((2, 0.0)), "the reader moved to page 3");- assert!(v.find.as_ref().unwrap().follow_ended, "moving the view ends automatic following");-- let ctx = egui::Context::default();- let request = RenderRequest { page: 1, kind: RequestKind::Text, tag: TEXT_TAG, ..Default::default() };- v.last_queue = vec![request];- v.receive_result(&ctx, find_text_result(1, "late sample"));- let f = v.find.as_ref().unwrap();- assert_eq!(v.current, 2, "the late first match does not pull the reader back");- assert_eq!(v.goto, Some((2, 0.0)), "no flash was issued");- assert_eq!((f.auto_from, f.auto_page), (None, None));- assert_eq!(f.current.and_then(|i| f.matches.get(i)).map(|(p, _)| *p), Some(1), "the result list still selects the match");+ let last = rects.len() - 1;+ let cur = view.current.min(last);+ match view.layout {+ PageLayout::Single => vec![cur],+ PageLayout::TwoUp if view.cover && cur == 0 => vec![0],+ PageLayout::TwoUp => {+ let first = if view.cover { cur - (cur + 1) % 2 } else { cur - cur % 2 };+ if first < last { vec![first, first + 1] } else { vec![first] }+ }}+ }- /// A page-box jump to the page already shown is still the reader's navigation: automatic- /// following must end, so a late earlier match is listed without moving the view. (The- /// harness covers wheel, scrollbar and pointer scrolling through the production paint path.)- #[test]- fn a_same_page_page_box_jump_ends_automatic_following() {- let mut v = view(3, PageLayout::Single, true);- v.current = 0;- v.texts.insert(1, Arc::new(find_test_text("first sample")));- v.find = Some(Find { query: "sample".into(), ..Default::default() });- v.rerun_find();- assert_eq!((v.current, v.find.as_ref().unwrap().auto_page), (1, Some(1)), "the automatic choice is on page 2");-- // Choosing the page already shown still ends following; it stays on page 2 at its top.- v.go_to_page(1);- let shown = v.goto;- assert_eq!(shown, Some((1, 0.0)));+ /// Full screen: a click on the document goes forward a page and a shift-click back, as in+ /// Acrobat, unless the click did something else (a link, a word selected). Decided once the pages+ /// have had the click. `Some(back)` on the frame of a click, `back` when it was a shift-click.+ fn presentation_click_state(ui: &egui::Ui, view: &DocView, navigation_rect: Rect, enabled: bool) -> Option<bool> {+ let clicked = view.presentation.is_some() && enabled && presentation_click(ui, navigation_rect);+ // Shift as held now, or as the click's own event carried it (a synthetic click).+ clicked.then(|| {+ ui.input(|i| {+ i.modifiers.shift+ || i.events.iter().any(|e| {+ matches!(e, egui::Event::PointerButton { button: egui::PointerButton::Primary, pressed: false, modifiers, .. } if modifiers.shift)+ })+ })+ })+ }- v.texts.insert(0, Arc::new(find_test_text("intro sample")));- v.refresh_find_page(0);- let f = v.find.as_ref().unwrap();- assert!(f.follow_ended);- assert_eq!((f.auto_from, f.auto_page), (None, None));- assert_eq!(v.current, 1, "the late earlier match does not move the reader within the page");- assert_eq!(v.goto, shown, "no flash was issued");- assert_eq!(f.current.and_then(|i| f.matches.get(i)).map(|(p, _)| *p), Some(1), "the page-2 match stays selected");+ /// Pinch / ctrl+scroll zoom, anchored on the pointer or the current page.+ fn pinch_zoom(ui: &egui::Ui, view: &mut DocView, zoom_delta: f32, navigation_rect: Rect, enabled: bool) {+ if zoom_delta.is_finite() && zoom_delta > 0.0 && zoom_delta != 1.0 && enabled && ui.rect_contains_pointer(navigation_rect) {+ let z = view.zoom * zoom_delta;+ match zoom_anchor(ui) {+ Some(p) => view.zoom_at(z, p),+ None => view.set_zoom(z),+ }}+ }- /// A document-wide invalidation (a layer toggle, an edit, undo/redo) clears results for- /// re-extraction but is not the reader navigating. Automatic following keeps its anchor so- /// the re-extracted layers still reveal the automatic choice; a reader who already took- /// over stays in control. If `document_changed` clamps the view away from that anchor, the- /// next layer ends following instead of revealing a match from the stale page.- #[test]- fn content_invalidation_keeps_the_following_state() {- let mut v = view(3, PageLayout::Single, true);- v.current = 0;- v.texts.insert(1, Arc::new(find_test_text("first sample")));- v.find = Some(Find { query: "sample".into(), ..Default::default() });- v.rerun_find();- assert_eq!((v.current, v.find.as_ref().unwrap().auto_page), (1, Some(1)), "the automatic choice is on page 2");-- v.invalidate_content();- let f = v.find.as_ref().unwrap();- assert!(f.matches.is_empty() && f.current.is_none(), "results wait for the re-extracted text");- assert!(!f.follow_ended, "a content change is not reader navigation");- assert_eq!((f.auto_from, f.auto_page), (Some(0), Some(1)));-- // Re-extracted text still follows the page the search started from.- let ctx = egui::Context::default();- let request = RenderRequest { page: 0, kind: RequestKind::Text, tag: TEXT_TAG, ..Default::default() };- v.last_queue = vec![request];- v.receive_result(&ctx, find_text_result(0, "intro sample"));- assert_eq!(v.current, 0, "the re-extracted match is revealed by the still-active search");- let f = v.find.as_ref().unwrap();- assert!(!f.follow_ended);- assert_eq!((f.auto_from, f.auto_page), (Some(0), Some(0)));+ /// The middle-button auto-scroll's delta, and the edge scroll a drawing in progress asks for: the+ /// pointer in a band along any edge (or just past it) scrolls the view that way, so a point+ /// beyond what is shown can be reached without letting go of the tool.+ fn auto_scroll_deltas(ui: &egui::Ui, view: &mut DocView, avail: Rect, unobstructed: bool) -> (Vec2, Vec2) {+ let auto_delta = if unobstructed {+ view.auto_scroll.update(ui, avail, false)+ } else {+ view.auto_scroll.cancel();+ Vec2::ZERO+ };- // A reader who navigated first keeps the view they chose across the invalidation.- v.go_to_page(2);- let moved = v.goto;- assert!(v.find.as_ref().unwrap().follow_ended);- v.invalidate_content();- let f = v.find.as_ref().unwrap();- assert!(f.follow_ended);- assert_eq!((f.auto_from, f.auto_page), (None, None));- v.last_queue = vec![request];- v.receive_result(&ctx, find_text_result(0, "late sample"));- assert_eq!(v.current, 2, "no delayed reveal after the reader navigated");- assert_eq!(v.goto, moved, "no flash was issued");- let f = v.find.as_ref().unwrap();- assert_eq!(f.current.and_then(|i| f.matches.get(i)).map(|(p, _)| *p), Some(0), "the result list still selects the late match");+ // Drawing a comment: the pointer in a band along any edge (or just past it) scrolls the view+ // that way, so a point beyond what is shown can be reached without letting go of the tool.+ let edge_delta = if unobstructed && matches!(view.comments.gesture, Some(comments::Gesture::Draw { .. })) {+ let (pointer, dt) = drawing_edge_pointer(ui);+ crate::autoscroll::edge_scroll(pointer, avail, dt)+ } else {+ Vec2::ZERO+ };+ if edge_delta != Vec2::ZERO {+ ui.ctx().request_repaint();}+ (auto_delta, edge_delta)+ }- /// A document edit can shrink the page count. `document_changed` clamps `current` but leaves- /// the automatic anchor's page index alone; a re-extracted layer must then end following- /// rather than reveal a match by scrolling from a page that no longer exists.- #[test]- fn a_page_count_shrink_ends_following_before_a_late_reveal() {- let mut v = view(5, PageLayout::Single, true);- v.current = 0;- v.texts.insert(4, Arc::new(find_test_text("last sample")));- v.find = Some(Find { query: "sample".into(), ..Default::default() });- v.rerun_find();- assert_eq!((v.current, v.find.as_ref().unwrap().auto_page), (4, Some(4)), "the automatic choice is on the last page");-- let info = pdfcraft_render::DocInfo {- pages: (0..2)- .map(|_| pdfcraft_render::PageInfo { width: 300.0, height: 400.0, label: String::new(), crop: [0.0, 0.0, 300.0, 400.0], rotation: 0 })- .collect(),- ..Default::default()- };- v.document_changed(&info);- assert_eq!(v.current, 1, "the view clamps to the last remaining page");- let f = v.find.as_ref().unwrap();- assert!(!f.follow_ended, "the content change itself keeps the automatic state");- assert_eq!((f.auto_from, f.auto_page), (Some(0), Some(4)), "the anchor still names the removed page");- let goto = v.goto;-- let ctx = egui::Context::default();- let request = RenderRequest { page: 0, kind: RequestKind::Text, tag: TEXT_TAG, ..Default::default() };- v.last_queue = vec![request];- v.receive_result(&ctx, find_text_result(0, "intro sample"));- let f = v.find.as_ref().unwrap();- assert!(f.follow_ended, "a layer for the remaining pages ends the stale follow");- assert_eq!((f.auto_from, f.auto_page), (None, None));- assert_eq!(v.current, 1, "the late layer cannot pull the view back");- assert_eq!(v.goto, goto, "no flash was issued");- assert_eq!(f.current.and_then(|i| f.matches.get(i)).map(|(p, _)| *p), Some(0), "the result list still selects the match");+ /// What decides whether touchpad momentum goes on.+ #[derive(Clone, Copy)]+ struct GlideCx {+ now: f64,+ may_glide: bool,+ key_scroll: f32,+ auto_delta: Vec2,+ zoom_delta: f32,+ edge_delta: Vec2,+ wheel_scrolled: bool,+ }++ /// Touchpad momentum (#531): a swipe over the page lifted at speed glides on and slows to a stop,+ /// through the same un-eased path. Never while the pager owns the wheel, a gesture or dialog has+ /// the input, or animations are off; any click, key, zoom or other scrolling ends it. Any+ /// reader-owned motion ends automatic search following, even when it stays on the same page; the+ /// automatic flash uses `goto`, not these deltas, so its programmatic scroll is never mistaken for+ /// a reader action. Returns this frame's glide.+ fn step_glide(ui: &egui::Ui, view: &mut DocView, avail: Rect, cx: &GlideCx) -> Vec2 {+ let GlideCx { now, may_glide, key_scroll, auto_delta, zoom_delta, edge_delta, wheel_scrolled } = *cx;+ let over_page = ui.rect_contains_pointer(avail);+ ui.input(|i| view.fling.read(&i.events, now, may_glide && over_page));+ let interrupted = glide_interrupted(ui);+ if !may_glide || interrupted || key_scroll != 0.0 || auto_delta != Vec2::ZERO || zoom_delta != 1.0 {+ view.fling.stop();}+ let glide = view.fling.step(now);+ if view.fling.gliding() {+ ui.ctx().request_repaint();+ }+ if wheel_scrolled || auto_delta != Vec2::ZERO || edge_delta != Vec2::ZERO || glide != Vec2::ZERO {+ view.end_find_following();+ }+ glide+ }- /// Typing refinements while text layers keep arriving must keep the page the search began- /// on, not re-anchor on whichever page an earlier automatic flash happened to show.- #[test]- fn rapid_query_edits_interleaved_with_text_results_keep_the_start_anchor() {- let mut v = view(3, PageLayout::Single, true);- v.current = 0;- v.find = Some(Find { query: "sam".into(), ..Default::default() });- v.rerun_find();- assert!(v.find.as_ref().unwrap().current.is_none());-- let edits = [("samp", 2, "Page three sample", 2), ("sampl", 1, "Page two sample", 1), ("sample", 0, "Page one sample", 0)];- for (query, page, text, shown) in edits {- v.find.as_mut().unwrap().query = query.into();- v.rerun_find();- let f = v.find.as_ref().unwrap();- assert_eq!(f.auto_from, Some(0), "refinement keeps the page the reader started from");- assert!(!f.follow_ended);- v.texts.insert(page, Arc::new(find_test_text(text)));- v.refresh_find_page(page);- let f = v.find.as_ref().unwrap();- assert_eq!(v.current, shown, "the late page follows the automatic anchor {shown}");- assert_eq!((f.auto_from, f.auto_page), (Some(0), Some(shown)));- assert!(!f.follow_ended, "the automatic flash itself does not end following");- }- assert!(v.back.is_empty(), "automatic search updates do not record history");+ /// Text selection runs for the Select tool and for the markup tools (highlight…).+ fn tool_selects_text(tool: QuickTool, preparing: bool) -> bool {+ match tool {+ QuickTool::Comment(t) => t.markup().is_some() || t == comments::CommentTool::ReplaceText,+ QuickTool::Select => !preparing,+ QuickTool::Redact | QuickTool::ColumnSelect => true,+ QuickTool::Hand+ | QuickTool::Measure(_)+ | QuickTool::Crop+ | QuickTool::EnhanceCamera+ | QuickTool::Fill(_)+ | QuickTool::Field(_)+ | QuickTool::AddText+ | QuickTool::EditText+ | QuickTool::Stamp(_)+ | QuickTool::CustomStamp(_)+ | QuickTool::Link+ | QuickTool::SignArea { .. }+ | QuickTool::MarqueeZoom+ | QuickTool::Snapshot => false,}+ }- #[test]- fn text_layers_evict_far_pages_but_keep_visible_and_matches() {- let info = thumbnail_info(100);- let mut v = DocView::new(DocId(1), &info, ViewDefaults::default());- v.current = 50;- v.frame_visible = HashSet::from([50, 51]);- for p in 0..100 {- v.texts.insert(p, Arc::new(PageText::default()));- }- v.text_failed.insert(0);- v.text_failed.insert(99);- v.find = Some(Find { matches: vec![(0, 0..1)], ..Default::default() });- let _ = v.prepare_render_queue(&info, 1.0);- assert!(v.texts.contains_key(&50) && v.texts.contains_key(&51), "visible pages stay");- assert!(v.texts.contains_key(&0), "matched pages stay");- assert!(v.texts.contains_key(&49), "nearest prefetch window stays");- assert!(!v.texts.contains_key(&99), "far pages go");- assert_eq!(v.texts.len(), 2 + 1 + MAX_CACHED_TEXT_PAGES, "visible + matched + prefetch window");- assert!(v.text_failed.contains(&0) && v.text_failed.contains(&99), "failures are bytes-free: never evict");+ /// Holds sharp re-renders while the zoom is still moving: a new scale every frame would cancel the+ /// in-flight full-page interpret and restart it, so on a heavy page (a CAD plot with ~1000 images+ /// renders for seconds) the sharp raster never arrives and the view looks stuck on a soft image.+ /// The stale raster stays stretched meanwhile; the sharp request goes out once the zoom settles.+ fn hold_sharp_renders(ui: &egui::Ui, view: &mut DocView, scale: f32) -> bool {+ let now_scale = ui.input(|i| i.time);+ if (scale - view.last_scale).abs() > f32::EPSILON {+ view.last_scale = scale;+ view.sharp_hold_until = now_scale + 0.35;+ ui.ctx().request_repaint_after(std::time::Duration::from_millis(380));}+ now_scale < view.sharp_hold_until+ }- /// A PDF of one line of text on each page, `lines[i]` on page `i`.- fn text_pages_pdf(lines: &[&str]) -> Vec<u8> {- let n = lines.len();- // 1 catalog, 2 pages, 3 font, then a page and its content stream for each line.- let mut objects = vec![- "<< /Type /Catalog /Pages 2 0 R >>".to_string(),- format!("<< /Type /Pages /Count {n} /Kids [{}] >>", (0..n).map(|i| format!("{} 0 R", 4 + 2 * i)).collect::<Vec<_>>().join(" ")),- "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>".to_string(),- ];- for (i, line) in lines.iter().enumerate() {- let content = format!("BT /F1 18 Tf 72 700 Td ({line}) Tj ET");- objects.push(format!(- "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << /Font << /F1 3 0 R >> >> /Contents {} 0 R >>",- 5 + 2 * i- ));- objects.push(format!("<< /Length {} >>\nstream\n{content}\nendstream", content.len()));- }- let mut out = b"%PDF-1.7\n".to_vec();- let mut offsets = Vec::new();- for (i, o) in objects.iter().enumerate() {- offsets.push(out.len());- out.extend(format!("{} 0 obj\n{o}\nendobj\n", i + 1).bytes());+ /// A destination's position (bookmarks, links) refines `goto`: its point at the window's top-left,+ /// or the centre of a /FitR rectangle at the window's centre.+ fn refine_goto_point(mut scroll: egui::ScrollArea, view: &mut DocView, geometry: &ScrollGeometry<'_>) -> egui::ScrollArea {+ let ScrollGeometry { rects, y_shift, content_w, content_h, avail, .. } = *geometry;+ if let Some((page, fx, fy, rel)) = view.goto_point.take() {+ let r = rects[page.min(rects.len() - 1)];+ // Within the content, so an unreachable point never shows a frame scrolled past the end.+ let (max_x, max_y) = ((content_w - avail.width()).max(0.0), (content_h - avail.height()).max(0.0));+ if let Some(fx) = fx {+ scroll = scroll.horizontal_scroll_offset((r.left() + fx * r.width() - rel.x).clamp(0.0, max_x));}- let xref = out.len();- out.extend(format!("xref\n0 {}\n0000000000 65535 f \n", objects.len() + 1).bytes());- for o in offsets {- out.extend(format!("{o:010} 00000 n \n").bytes());+ if let Some(fy) = fy {+ scroll = scroll.vertical_scroll_offset((r.top() - y_shift + fy * r.height() - rel.y).clamp(0.0, max_y));}- out.extend(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objects.len() + 1).bytes());- out}+ scroll+ }- /// #2639: scrolling continuously, Select All takes every page's text, and Copy gets all of it- /// in page order, reading the pages whose text wasn't read for display.- #[test]- fn select_all_copies_the_whole_document_while_scrolling_continuously() {- let mut app = PdfCraftApp::new();- app.open_bytes("three.pdf", None, text_pages_pdf(&["Alpha one", "Bravo two", "Charlie three"])).unwrap();- let v = &mut app.views[0];- assert!(v.continuous, "continuous scrolling is the default");- assert!(v.texts.is_empty(), "no page's text read yet");- // Nothing shown is selected yet (false, as for a page whose text isn't read), but the whole- // document is: Copy reads every page.- assert!(!v.select_all());- assert!(v.all_text && v.selection.is_none());- assert_eq!(v.pages_without_text(), vec![0, 1, 2]);- // Copy reads the pages off the UI thread; the clipboard gets the text once they're read.- let ctx = egui::Context::default();- assert!(app.copy_selected_text(0, &ctx), "the copy starts");- assert!(app.document_copy.is_some(), "reading the pages, not on this thread");- let mut text = 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();- text = out.platform_output.commands.iter().find_map(|c| match c {- egui::OutputCommand::CopyText(t) => Some(t.clone()),- _ => None,- });- if text.is_some() {- break;- }- std::thread::sleep(std::time::Duration::from_millis(10));- }- let text = text.expect("the copied text arrives");- assert!(app.document_copy.is_none(), "done");- let at = |w: &str| text.find(w).unwrap_or_else(|| panic!("{w:?} missing from {text:?}"));- assert!(at("Alpha") < at("Bravo") && at("Bravo") < at("Charlie"), "page order: {text:?}");- assert_eq!(text.lines().count(), 3, "a line per page: {text:?}");- // A new scope ends it: one page at a time, Select All is the page's again.- app.views[0].set_continuous(false);- assert!(!app.views[0].all_text, "not after switching to one page at a time");- // So do a page selection and a change of the document's content (an edit, undo).- app.views[0].set_continuous(true);- app.views[0].select_all();- app.views[0].select_text(0, 0, 0);- assert!(!app.views[0].all_text, "a page selection replaces it");- app.views[0].select_all();- app.views[0].invalidate_content();- assert!(!app.views[0].all_text, "not past an edit of the document");+ /// Draws the document tab at `index`: its notice bars, then its pages (or the Organize grid) in a+ /// scroll area with this frame's zoom, scrolling, tool input, overlays and render requests.+ pub fn document_area(app: &mut PdfCraftApp, index: usize, ui: &mut egui::Ui) {+ let t = Tokens::get(ui.ctx());+ // Keyboard scrolling applies to this frame's page view only, never later.+ let key_scroll = std::mem::take(&mut app.views[index].key_scroll);+ if key_scroll != 0.0 {+ app.views[index].end_find_following();}-- /// A whole-document copy reads the pages without text, keeps those already read and skips- /// those that failed before.- #[test]- fn a_document_copy_reads_only_the_pages_it_needs() {- let mut app = PdfCraftApp::new();- app.open_bytes("three.pdf", None, text_pages_pdf(&["Alpha one", "Bravo two", "Charlie three"])).unwrap();- app.views[0].text_failed.insert(2);- let job = crate::DocumentCopyJob::of(&app.views[0], app.session.get(app.views[0].id).unwrap());- let kinds: Vec<_> = job.pages.iter().map(|p| matches!(p, crate::CopyPage::ToRead)).collect();- assert_eq!(kinds, vec![true, true, false], "pages 1 and 2 to read, page 3 failed before");- assert!(matches!(job.pages[2], crate::CopyPage::Skip));+ // The Search panel closed: its search moves to the find bar.+ let search_open = app.right == Some(crate::RightPanel::Search);+ if let Some(f) = app.views[index].find.as_mut()+ && f.in_panel+ && !search_open+ {+ f.in_panel = false;}-- /// A later copy wins: a whole-document copy still reading its pages never replaces what was- /// copied after it started, from the page or anywhere else (a text field, a comment).- #[test]- fn a_later_copy_cancels_a_document_copy_still_reading() {- let mut app = PdfCraftApp::new();- app.open_bytes("three.pdf", None, text_pages_pdf(&["Alpha one", "Bravo two", "Charlie three"])).unwrap();- let ctx = egui::Context::default();- // Another copy in the same frame (here a text field's) drops it.- app.views[0].select_all();- assert!(app.copy_selected_text(0, &ctx) && app.document_copy.is_some());- let mut out = ctx.run_ui(egui::RawInput::default(), |ui| {- ui.ctx().copy_text("a word".to_owned());- app.finish_document_copy(ui.ctx());- });- out.textures_delta.clear();- 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.- 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.copy_selected_text(0, &ctx);- assert!(app.document_copy.is_none(), "a page selection's copy cancels it");+ if close_requested_tab(app, index) {+ return;}-- /// A press anywhere on a page ends Select All of the document, whatever the tool (here the- /// Hand, which selects no text) and whether the page's text is read yet.- #[test]- fn a_press_on_a_page_ends_select_all_of_the_document() {- 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("three.pdf", None, text_pages_pdf(&["Alpha one", "Bravo two", "Charlie three"])).unwrap();- app- });- let mut on_screen = None;- for _ in 0..600 {- 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 first page is on screen");- h.state_mut().quick_tool = crate::QuickTool::Hand;- h.state_mut().views[0].select_all();- assert!(h.state().views[0].all_text);- let at = r.center();- h.event(egui::Event::PointerMoved(at));- h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE });- h.run_steps(1);- h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE });- h.run_steps(2);- assert!(!h.state().views[0].all_text, "a press on the page ends it");-- // A press while a dialog is up lands on the dialog, not the page: the selection stays.- h.state_mut().views[0].select_all();- h.state_mut().dialog = Some(crate::Dialog::JsConsole);- h.run_steps(2);- h.event(egui::Event::PointerMoved(at));- h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE });- h.run_steps(1);- h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE });- h.run_steps(2);- assert!(h.state().views[0].all_text, "a press beneath a dialog doesn't end it");+ let Some(doc) = app.session.get(app.views[index].id) else { return };+ let info = &doc.info;+ let paper = app.session.reading_colors(app.views[index].id).and_then(|c| c.params).map_or(Color32::WHITE, |p| {+ let [r, g, b] = p.background;+ Color32::from_rgb(r, g, b)+ });+ if info.pages.is_empty() {+ app.views[index].auto_scroll.cancel();+ ui.centered_and_justified(|ui| ui.label(tl!("This document has no pages.")));+ return;}-- /// The pages of a whole-document copy come out in order whatever was read before, and a- /// cancelled copy gives nothing (a new copy or a closed document cancels the old one).- #[test]- fn a_document_copy_reads_in_page_order_and_stops_when_cancelled() {- let mut app = PdfCraftApp::new();- app.open_bytes("three.pdf", None, text_pages_pdf(&["Alpha one", "Bravo two", "Charlie three"])).unwrap();- // The middle page's text read for display already; the others read by the copy.- let doc = app.session.get(app.views[0].id).unwrap();- let mut r = pdfcraft_render::PageRenderer::new(doc.bytes.clone(), Default::default());- let middle = r.render(RenderRequest { page: 1, kind: RequestKind::Text, ..Default::default() }).text.unwrap();- app.views[0].texts.insert(1, middle);- let job = || crate::DocumentCopyJob::of(&app.views[0], app.session.get(app.views[0].id).unwrap());- let text = job().text(&std::sync::atomic::AtomicBool::new(false)).unwrap();- assert!(text.find("Alpha").unwrap() < text.find("Bravo").unwrap() && text.find("Bravo").unwrap() < text.find("Charlie").unwrap(), "{text:?}");- assert_eq!(job().text(&std::sync::atomic::AtomicBool::new(true)), None, "cancelled");+ // The print dialog queues its own rasters later in the frame. Closing it drops them.+ if app.dialog != Some(crate::Dialog::Print) {+ app.views[index].print_pages.clear();}-- /// Select All keeps to the page shown one page at a time, and in a document of one page; of- /// the document, it reads the text already read and doesn't ask again for failed pages.- #[test]- fn select_all_of_the_document_only_while_scrolling_through_several_pages() {- let info = thumbnail_info(3);- let one_line = |s: &str| 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(),- };- let mut v = DocView::new(DocId(1), &info, ViewDefaults::default());- for p in 0..3 {- v.texts.insert(p, Arc::new(one_line("abc")));- }- v.continuous = false;- v.current = 1;- assert!(v.select_all());- assert!(!v.all_text && v.selection.is_some_and(|s| s.page == 1), "one page at a time: the page shown");- let single = thumbnail_info(1);- let mut w = DocView::new(DocId(2), &single, ViewDefaults::default());- w.texts.insert(0, Arc::new(one_line("abc")));- assert!(w.select_all());- assert!(!w.all_text && w.selection.is_some(), "a one-page document: that page");- // Text read for display is used; pages that failed aren't asked for again.- let mut d = DocView::new(DocId(3), &info, ViewDefaults::default());- d.texts.insert(1, Arc::new(one_line("abc")));- d.text_failed.insert(2);- assert!(d.select_all() && d.all_text);- assert_eq!(d.pages_without_text(), vec![0]);+ // The Prepare a form panel is open (or a field tool is picked): fields are edited, not filled.+ let preparing = app.is_preparing();+ // Prepare a form ▸ Calculation order: the order's steps and links on the page.+ let calc_order = preparing && app.left_open && app.left == crate::LeftPanel::CalculationOrder;+ // Edit a PDF: added text and images can be selected, moved and edited.+ let editing_content =+ (app.left_open && app.left == crate::LeftPanel::Tool("edit")) || matches!(app.quick_tool, QuickTool::AddText | QuickTool::EditText);+ let text_style = app.text_style.clone();+ let show_secured_notice = app.show_secured_notice;+ let view = &mut app.views[index];+ // Opened without the owner password and something is restricted. The notice says so unless+ // the user turned it off (#4035): the restrictions themselves, and Document Properties ▸+ // Security, stay as they are.+ let secured = show_secured_notice && doc.security_summary().is_some_and(|s| !(s.owner || (s.permissions.modify() && s.permissions.assemble())));+ let repaired = !doc.repair_log().is_empty();+ let notice = notices(view, doc, secured, repaired, crate::sign_ui::banner(&doc.signatures), ui, &t);+ apply_notice(app, index, notice);+ let Some(doc) = app.session.get(app.views[index].id) else { return };+ let info = &doc.info;+ // No dialog, close prompt or palette over the page: only then does page input count.+ let modal = app.modal_open();+ let unobstructed = !modal && !app.palette_open;+ let organize_zoom = app.organize_zoom;+ let view = &mut app.views[index];+ if view.organize {+ // One remembered grid size for every document, kept in the settings.+ view.set_grid_zoom(organize_zoom);+ organize_grid(view, info, doc.allows_assembly(), doc.dirty, unobstructed, ui, &t);+ app.organize_zoom = view.grid_zoom();+ return;}- #[test]- fn text_layers_keep_the_selection_page() {- let info = thumbnail_info(100);- let mut v = DocView::new(DocId(1), &info, ViewDefaults::default());- let text = PageText {- glyphs: vec![pdfcraft_render::TextGlyph { text: "x".into(), rect: [0.0, 0.0, 10.0, 10.0], quad: [[0.0, 0.0]; 4], direction: [1.0, 0.0] }],- line_of: vec![0],- space_before: vec![false],- };- for p in 0..100 {- v.texts.insert(p, Arc::new(text.clone()));+ let avail = ui.available_rect_before_wrap();+ view.viewport_w = avail.width();+ view.viewport_h = avail.height();+ let old_zoom = view.zoom;+ view.fit_zoom(info);+ anchor_zoom_change(view, avail.width(), old_zoom);++ // Pinch / ctrl+scroll zoom, anchored on the current page.+ let zoom_delta = crate::motion::zoom_delta(ui.ctx());+ // Exclude the previous frame's scrollbar tracks from gesture activation.+ let navigation_rect = if view.viewport_screen.is_positive() { avail.intersect(view.viewport_screen) } else { avail };+ let navigation_enabled = app.dialog.is_none() && app.close_request.is_none() && !app.palette_open && ui.is_enabled() && ui.input(|i| i.focused);+ let present = presentation_click_state(ui, view, navigation_rect, navigation_enabled && app.quick_tool == QuickTool::Select);+ pinch_zoom(ui, view, zoom_delta, navigation_rect, navigation_enabled);+ view.viewport_screen = avail;+ let (auto_delta, edge_delta) = auto_scroll_deltas(ui, view, avail, unobstructed);++ let content_w = view.content_width(info, avail.width());+ let rects = view.layout(info, content_w, ui.ctx().pixels_per_point());+ // When not scrolling continuously, only one row is shown at a time: the current page, or the+ // current two-page spread (with the cover rule). These indices drive paging, which pages are+ // drawn, and the content height (#752). Empty for a document with no pages.+ let row = shown_row(view, &rects);+ let middle_gesture = view.auto_scroll.blocks_input();+ // Not scrolling: when the whole page or spread fits, the wheel would do nothing, so it turns+ // pages instead; zoomed in far enough to pan, it pans, and at the edge it turns the page on+ // (#1924, `single_page_wheel_edge`). Touch drags are untouched: with+ // nothing to pan, touch users turn pages with the rail buttons, the page box and the arrow+ // keys. Runs before `visible_pages` so the frame that turns the page draws it.+ let (single_paging, edge_turned) = single_page_paging(ui, view, &PagingCx { row: &row, rects: &rects, avail, middle_gesture, unobstructed });+ // Point input bypasses egui smoothing for 1:1 motion. Line input keeps egui's configured,+ // smoothed base and adds only the accelerated surplus. While point suppression is active,+ // reconstruct line and page input here so current coarse events survive without exposing an+ // older eased tail.+ let now = ui.input(|i| i.time);+ let Wheel { precise_scroll, line_base, boost_extra, has_page, paging_owns_vertical } = read_wheel(ui, view, avail, single_paging, edge_turned);+ let animates = app.animation_effects.animates(app.motion.reduced);+ let may_glide = !paging_owns_vertical && !middle_gesture && navigation_enabled && unobstructed && animates;+ let wheel_scrolled = precise_scroll != Vec2::ZERO || line_base != Vec2::ZERO || boost_extra != Vec2::ZERO || has_page;+ let motion = GlideCx { now, may_glide, key_scroll, auto_delta, zoom_delta, edge_delta, wheel_scrolled };+ let glide = step_glide(ui, view, avail, &motion);+ // The wheel may have turned the page above: draw the row it turned to. Measured from the old+ // row, the jump to the new page scrolled both out of view, a blank frame on every turn forward.+ let row = shown_row(view, &rects);+ let visible_pages: Vec<usize> = if view.continuous { (0..rects.len()).collect() } else { row.clone() };+ let (y_shift, content_h) = if view.continuous {+ (0.0, rects.iter().map(|r| r.bottom()).reduce(f32::max).map(|bottom| bottom + MARGIN).unwrap_or(0.0))+ } else {+ // Only the current row scrolls into view; the content is its bounding box plus margins.+ match row.iter().filter_map(|&i| rects.get(i)).copied().reduce(Rect::union) {+ Some(r) => (r.top() - MARGIN, r.height() + 2.0 * MARGIN),+ None => (0.0, 0.0),}- v.select_text(0, 0, 0);- v.current = 90;- 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");+ };++ let mut scroll = page_scroll_area(+ ui,+ view,+ &ScrollGeometry { rects: &rects, y_shift, content_w, content_h, avail, middle_gesture, hand: app.quick_tool == QuickTool::Hand },+ );+ let ppp = ui.ctx().pixels_per_point();+ let scale = view.render_scale(ppp);+ let tag = scale_tag(scale);+ // Hold sharp re-renders while the zoom is still moving: a new scale every frame would+ // cancel the in-flight full-page interpret and restart it, so on a heavy page (a CAD+ // plot with ~1000 images renders for seconds) the sharp raster never arrives and the+ // view looks stuck on a soft image. The stale raster stays stretched meanwhile; the+ // sharp request goes out once the zoom settles.+ let sharp_held = hold_sharp_renders(ui, view, scale);+ view.current_scale_tag = tag;+ let hand = app.quick_tool == QuickTool::Hand;+ let tool = app.quick_tool;+ // Text selection runs for the Select tool and for the markup tools (highlight…).+ let selects_text = tool_selects_text(tool, preparing);+ let prefs = &app.comment_prefs;+ let redact_mark = (app.redact_prefs.hover_fill, app.redact_prefs.opacity);+ let units = app.units;+ let allowed = doc.allows_annotation();+ let can_copy = doc.allows_copying();+ let comments_hidden = doc.comments_hidden();+ let form = doc.form.clone();+ let generation = doc.edit_generation();+ let can_fill = doc.allows_form_filling();+ let can_crop = doc.allows_assembly();+ let signature = app.signature.clone();+ let initials = app.initials.clone();+ let author = app.comment_prefs.author.clone();+ let today = app.session.today();+ // In Preferences ▸ Date format, or why it can't be stamped into the PDF.+ let date_text = crate::date_text_for_pdf(&app.session);+ let by_line = app.session.stamp_by_line(&author);+ let custom_stamp = match app.quick_tool {+ QuickTool::CustomStamp(i) => app.custom_stamps.get(i).cloned(),+ _ => None,+ };+ let mut open_props: Option<(usize, usize)> = None;+ // The table being set up in its window, shown on its own document's page.+ let table_preview = app.field_table_draft.as_mut().filter(|d| d.doc == view.id).and_then(|d| Some(d.preview(info.pages.get(d.page)?, &form)));+ let can_modify = doc.allows_modification();+ if preparing {+ crate::prepare::after_refresh(view, &form);+ } else {+ view.prepare.selected = None;}-- #[test]- fn text_layers_stay_while_a_search_is_active() {- let info = thumbnail_info(100);- let mut v = DocView::new(DocId(1), &info, ViewDefaults::default());- v.current = 50;- v.frame_visible = HashSet::from([50]);- for p in 0..100 {- v.texts.insert(p, Arc::new(PageText::default()));- }- v.find = Some(Find { query: "dup".into(), case_query: "dup".into(), matches: vec![(0, 0..1)], ..Default::default() });- let _ = v.prepare_render_queue(&info, 1.0);- assert_eq!(v.texts.len(), 100, "evicting mid-search would churn the workers");+ view.objects.prepare(doc, tool == QuickTool::EditText && can_modify, ui.ctx());+ view.text_background.prepare(ui.ctx(), doc, view.line_editor.as_ref(), view.content.draft.as_ref(), scale);+ let added = if editing_content { doc.added().to_vec() } else { Vec::new() };+ let doc_links = if tool == QuickTool::Link { doc.links().to_vec() } else { Vec::new() };+ if editing_content {+ crate::content_ui::after_refresh(view, &added);+ } else {+ view.content.selected = None;}+ view.move_background.prepare(ui.ctx(), doc, &view.content, scale);- fn thumbnail_info(count: usize) -> DocInfo {- DocInfo {- pages: (0..count)- .map(|i| {- let (width, height) = match i % 3 {- 0 => (612.0, 792.0),- 1 => (200.0, 4000.0),- _ => (4000.0, 200.0),- };- pdfcraft_render::PageInfo { width, height, label: (i + 1).to_string(), crop: [0.0, 0.0, width, height], rotation: 0 }- })- .collect(),- ..Default::default()- }- }+ scroll = refine_goto_point(scroll, view, &ScrollGeometry { rects: &rects, y_shift, content_w, content_h, avail, middle_gesture, hand });+ let selection_wheel = view.selection_drag && navigation_enabled && unobstructed && !single_paging && ui.rect_contains_pointer(avail);+ let env = PageEnv {+ added: &added,+ allowed,+ author: &author,+ auto_delta,+ avail,+ boost_extra,+ by_line: &by_line,+ calc_order,+ can_copy,+ can_crop,+ can_fill,+ can_modify,+ comments_hidden,+ content_h,+ content_w,+ custom_stamp: &custom_stamp,+ date_text: &date_text,+ doc,+ doc_links: &doc_links,+ edge_delta,+ editing_content,+ form: &form,+ generation,+ glide,+ hand,+ info,+ initials: &initials,+ key_scroll,+ middle_gesture,+ modal,+ navigation_enabled,+ paper,+ ppp,+ precise_scroll,+ prefs,+ preparing,+ rects: &rects,+ redact_mark,+ scale,+ selection_wheel,+ selects_text,+ signature: &signature,+ single_paging,+ t: &t,+ table_preview: &table_preview,+ tag,+ text_style: &text_style,+ tool,+ units,+ unobstructed,+ visible_pages: &visible_pages,+ y_shift,+ fill_text_size: app.fill_text_size,+ today,+ };+ let mut page_out = PageOut::default();+ let out = page_scroll(ui, scroll, egui::Id::unique(("page-view-scope", view.id)), |ui, viewport| {+ draw_pages(ui, viewport, view, &env, &mut page_out, &mut app.signature_preview)+ });+ let PageOut {- badge_hover: _,+ canvas_action,+ clicked_link,+ mut copy_selected,+ field_menu,+ field_placed,+ mut field_props,+ hover_text,+ mut image_action,+ open_boxes,+ open_initials,+ open_signature,+ open_table,+ primary_down,+ mut refused,+ stamp_placed,+ } = page_out;+ view.single_edges = visible_pages.first().copied().filter(|_| !view.continuous).map(|page| {+ // At the top once the page's top edge shows where going to a page puts it (a gap+ // below the window's top). Within a point, as for wheel paging, so layout rounding+ // can't hide an edge.+ let max_y = (out.content_size.y - out.inner_rect.height()).max(0.0);+ (page, out.state.clamped_offset().y <= MARGIN - view.page_gap() + 1.0, out.state.clamped_offset().y >= max_y - 1.0)+ });- #[test]- fn ten_thousand_pages_only_demand_viewport_and_prefetch_at_both_densities() {- let info = thumbnail_info(10_000);- let mut v = DocView::new(DocId(1), &info, ViewDefaults::default());- let cols = 4;- let rows = info.pages.len().div_ceil(cols);- for ppp in [1.0, 2.0] {- for row in [0, 1234, rows - 1] {- v.begin_render_frame();- let range = thumbnail_rows(row as f32 * 250.0, row as f32 * 250.0 + 750.0, 250.0, rows);- for p in range.start * cols..(range.end * cols).min(info.pages.len()) {- v.need_thumbnail(p, p / cols == row);- }- let queue = v.prepare_render_queue(&info, ppp);- assert!(queue.len() <= 5 * cols, "only three visible rows and two prefetch rows");- assert_eq!(queue.first().unwrap().page / cols, row, "visible cells precede prefetch");- let bytes: usize = queue- .iter()- .map(|r| {- let p = &info.pages[r.page];- let (w, h) = (device_pixels(p.width, r.scale), device_pixels(p.height, r.scale));- assert!(w <= (THUMB_W * ppp).ceil() as u32);- assert!(h <= (THUMB_H * ppp).ceil() as u32);- rgba_bytes(w as usize, h as usize)- })- .sum();- assert!(bytes <= THUMB_BYTES);- assert_eq!(queue, v.prepare_render_queue(&info, ppp), "unchanged demand reconstructs the same work");- }- }+ view.viewport_screen = out.inner_rect;+ view.auto_scroll.paint(ui, avail);+ if unobstructed && matches!(tool, QuickTool::Select | QuickTool::ColumnSelect) {+ copy_selected |= selection_actions(ui, avail, view, info, prefs, allowed && !comments_hidden, can_copy);}- #[test]- fn oversized_thumbnail_viewport_scales_all_admitted_cells_to_one_budget() {- let info = thumbnail_info(10_000);- let mut v = DocView::new(DocId(1), &info, ViewDefaults::default());- for page in 0..MAX_THUMB_DEMAND {- v.need_thumbnail(page, true);- }- let queue = v.prepare_render_queue(&info, 2.0);- assert_eq!(queue.len(), MAX_THUMB_DEMAND);- let bytes: usize = queue- .iter()- .map(|r| {- let p = &info.pages[r.page];- rgba_bytes(device_pixels(p.width, r.scale) as usize, device_pixels(p.height, r.scale) as usize)- })- .sum();- assert!(bytes <= THUMB_BYTES);- }+ // Collect all main-page demand, including cached surfaces, for byte admission later.+ // Pan-settle debounce for tiled pages: each tile costs a full page interpret, so holding+ // fresh tiles back while the scroll offset is still moving keeps a drag on the stretched+ // backdrop/older tiles instead of queueing a storm of interprets (one per frame) that+ // the workers cannot cancel mid-operator. Fresh tiles go out once the pan settles;+ // pages with nothing on screen yet still queue.+ let pan_held = track_scroll(ui, view, &out, glide);+ plan_renders(ui, view, info, out.inner, &RenderPlan { visible_pages: &visible_pages, tag, scale, sharp_held, pan_held, hand });- fn solid_result(request: RenderRequest, w: u32, h: u32) -> pdfcraft_render::RenderedPage {- pdfcraft_render::RenderedPage {- request,- width: w,- height: h,- rgba: pdfcraft_render::Pixels::from(vec![u32::MAX; rgba_bytes(w as usize, h as usize) / 4]),- text: None,- error: None,- warnings: Vec::new(),- millis: 0,- }+ let text_done = frame_overlays(ui, view, &env, primary_down, hover_text);+ if let Some(why) = view.objects.notice.take() {+ refused = Some(why);}-- /// #3149: the replacement dialog commits after the canvas collected this frame's demand.- #[test]- fn replacing_a_page_after_layout_never_uploads_an_oversized_texture() {- let ctx = egui::Context::default();- ctx.input_mut(|i| i.max_texture_side = 2048);- let mut app = PdfCraftApp::new();- let original = app.session.create_blank(200.0, 300.0, 1).unwrap();- let replacement = app.session.create_blank(400.0, 500.0, 1).unwrap();- app.open_bytes("original.pdf", None, original.as_ref().clone()).unwrap();- let request = RenderRequest { scale: 4.7, tag: scale_tag(4.7), ..Default::default() };- app.views[0].frame_queue = vec![request];- app.views[0].frame_visible.insert(0);- assert!(app.apply_edit(Edit::ReplacePages { pages: vec![0], name: "replacement.pdf".into(), bytes: replacement, src_pages: vec![0] }));- let doc = app.session.get(app.views[0].id).unwrap();- assert_eq!((doc.info.pages[0].width, doc.info.pages[0].height), (400.0, 500.0));- let edited_bytes = doc.bytes.clone();- let pool = RenderPool::new_inline(doc.display.clone(), Default::default());- app.views[0].finish_render_frame(&ctx, &doc.info, &pool);- assert!(app.views[0].last_queue.is_empty(), "old geometry must not reach the replacement renderer");-- // The next layout can render a bounded backdrop and sharp tiles at the same zoom.- let backdrop = RenderRequest { scale: 2048.0 / 500.0, tag: scale_tag(2048.0 / 500.0), ..request };- let tile = RenderRequest { tile: Some(Tile { x: 0, y: 0, w: 1024, h: 1024 }), ..request };- for _ in 0..2 {- let view = &mut app.views[0];- view.begin_render_frame();- view.frame_visible.insert(0);- view.frame_queue = vec![backdrop, tile];- view.finish_render_frame(&ctx, &doc.info, &pool);- }- let view = &app.views[0];- assert_eq!(view.pages.get(&0).unwrap().tex.size(), [1639, 2048]);- assert_eq!(view.tiles.get(&(0, tile.tag, 0, 0)).unwrap().size(), [1024, 1024]);- assert!(view.errors.is_empty());- assert_eq!(doc.bytes, edited_bytes, "rendering preserves the unsaved edit");- assert!(doc.dirty);- assert_eq!(doc.can_undo(), Some("Replace page"));+ let form_notice = view.forms.notice.take();+ // One crop, then back to selecting (as Acrobat does).+ let cropped = view.pending_edit.as_ref().is_some_and(|e| matches!(e, pdfcraft_engine::Edit::SetPageBox { .. }));+ let mut tool = app.quick_tool;+ comments::keys(ui.ctx(), view, &mut tool, allowed);+ if preparing {+ crate::prepare::keys(ui.ctx(), view);}-- #[test]- fn oversized_raster_results_do_not_replace_cached_textures() {- let ctx = egui::Context::default();- ctx.input_mut(|i| i.max_texture_side = 64);- for request in [- RenderRequest::default(),- RenderRequest { tag: THUMB_TAG, ..Default::default() },- RenderRequest { tag: GRID_TAG, ..Default::default() },- RenderRequest { tag: PRINT_TAG, ..Default::default() },- RenderRequest { tile: Some(Tile { x: 0, y: 0, w: 64, h: 32 }), ..Default::default() },- ] {- let mut view = DocView::new(DocId(1), &thumbnail_info(1), ViewDefaults::default());- view.last_queue = vec![request];- let texture = |v: &DocView| {- v.pages- .values()- .map(|p| &p.tex)- .chain(v.thumbs.values().map(|p| &p.tex))- .chain(v.grid_pages.values().map(|(_, t)| t))- .chain(v.print_pages.values().map(|(_, t)| t))- .chain(v.tiles.values())- .map(|t| (t.id(), t.size()))- .collect::<Vec<_>>()- };- assert_eq!(view.receive_result(&ctx, solid_result(request, 64, 32)), 64 * 32 * 4);- let cached = texture(&view);- assert_eq!(cached.len(), 1);- for (w, h) in [(65, 32), (32, 65), (65, 65), (0, 32), (32, 0)] {- assert_eq!(view.receive_result(&ctx, solid_result(request, w, h)), 0, "{request:?}: {w}x{h}");- assert_eq!(texture(&view), cached, "an invalid result must keep the previous raster");- }- assert_eq!(view.receive_result(&ctx, solid_result(request, 32, 64)), 32 * 64 * 4);- assert_eq!(texture(&view)[0].1, [32, 64], "valid results still make progress");- }+ if editing_content {+ crate::content_ui::keys(ui.ctx(), view);}-- /// A print preview carries the renderer's print bit; the bit that asks for luminance is- /// its own, so a colour preview is not converted to monochrome and the two modes are told- /// apart by their tags.- #[test]- fn print_preview_tag_distinguishes_grayscale_from_colour() {- let mut v = view(1, PageLayout::Single, true);- v.set_print_grayscale(false);- v.queue_print_previews(&[(0, 1.0)]);- let colour = v.frame_queue.last().expect("a print preview was queued").tag;- assert_ne!(colour & PRINT_TAG, 0, "a print preview carries the renderer's print bit");- assert_eq!(colour & GRAYSCALE_TAG, 0, "a colour print preview must not ask for luminance");-- v.set_print_grayscale(true);- v.queue_print_previews(&[(0, 1.0)]);- let gray = v.frame_queue.last().expect("a grayscale print preview was queued").tag;- assert_ne!(gray & GRAYSCALE_TAG, 0, "a grayscale print preview asks for luminance");- assert_ne!(gray, colour, "the two print preview modes must not share a tag");+ if tool == QuickTool::Link {+ crate::link_ui::keys(ui.ctx(), view);+ } else {+ view.links.selected = None;}-- #[test]- fn thumbnails_release_on_scroll_panel_close_and_request_again_after_eviction() {- let ctx = egui::Context::default();- let info = thumbnail_info(10_000);- let mut v = DocView::new(DocId(1), &info, ViewDefaults::default());- v.need_thumbnail(0, true);- let first = v.prepare_render_queue(&info, 1.0);- v.last_queue = first.clone();- assert_eq!(v.receive_result(&ctx, solid_result(first[0], 132, 171)), 132 * 171 * 4);- assert!(v.prepare_render_queue(&info, 1.0).is_empty());- v.begin_render_frame();- v.need_thumbnail(9999, true);- v.prepare_render_queue(&info, 1.0);- assert!(v.thumbs.is_empty(), "jump releases old handles");- v.begin_render_frame();- v.need_thumbnail(0, true);- assert_eq!(v.prepare_render_queue(&info, 1.0), first, "an evicted result must be requested again");- v.begin_render_frame();- assert!(v.prepare_render_queue(&info, 1.0).is_empty(), "closing consumers cancels thumbnail work");+ if stamp_placed {+ tool = QuickTool::Select;}-- #[test]- fn stale_results_are_rejected_before_conversion_after_dpi_invalidation_and_suspend() {- let ctx = egui::Context::default();- let info = thumbnail_info(1);- let mut v = DocView::new(DocId(1), &info, ViewDefaults::default());- v.need_thumbnail(0, true);- let first = v.prepare_render_queue(&info, 1.0)[0];- v.last_queue = v.prepare_render_queue(&info, 2.0);- // Valid pixels: only the request gate can keep these out (a size check can't).- let obsolete = || solid_result(first, 132, 171);- assert_eq!(v.receive_result(&ctx, obsolete()), 0);- assert!(v.thumbs.is_empty(), "a result for the old DPI is not uploaded");- // The same result is uploaded while its request is current.- v.last_queue = vec![first];- assert_eq!(v.receive_result(&ctx, obsolete()), 132 * 171 * 4);- v.thumbs.clear();- v.invalidate_content();- assert_eq!(v.receive_result(&ctx, obsolete()), 0);- assert!(v.thumbs.is_empty(), "nor after the content changed");- let pool = RenderPool::new_inline(Arc::new(Vec::new()), Default::default());- v.last_queue = vec![first];- v.suspend_rendering(&pool);- assert_eq!(v.receive_result(&ctx, obsolete()), 0);- assert!(v.thumbs.is_empty(), "nor after the tab was suspended");+ // Text: each click on the page starts a box (#74); Done in the editor goes back to selecting.+ if text_done && tool == QuickTool::AddText {+ tool = QuickTool::Select;}-- #[test]- fn editing_after_layout_preserves_stale_page_until_replacement() {- let ctx = egui::Context::default();- let info = thumbnail_info(1);- let mut v = DocView::new(DocId(1), &info, ViewDefaults::default());- let req = RenderRequest { scale: 1.0, tag: 1000, ..Default::default() };- v.last_queue = vec![req];- v.receive_result(&ctx, solid_result(req, 10, 10));- v.frame_queue = vec![req];- v.page_changed(0);- assert_eq!(v.prepare_render_queue(&info, 1.0), vec![req]);- assert_eq!(v.pages.get(&0).unwrap().tag, STALE_TAG);+ // One field, then back to selecting (Acrobat's default without "Keep tools pinned").+ if field_placed {+ tool = QuickTool::Select;}-- /// #1858: a released drawing stays painted from its points until a raster that has it- /// arrives. A page raster that lands before the drawing's edit is applied (in full screen the- /// edit waits for the next frame, and a render already under way can finish first) is of the- /// document without it, and must not end the preview.- #[test]- fn a_raster_from_before_a_drawing_is_committed_keeps_it_drawn() {- let ctx = egui::Context::default();- let info = thumbnail_info(1);- let mut v = DocView::new(DocId(1), &info, ViewDefaults::default());- let req = RenderRequest { scale: 1.0, tag: 1000, ..Default::default() };- v.comments.settle(0.0, 0, crate::comments::CommentTool::Ink, &[[10.0, 10.0], [40.0, 30.0]]);- v.last_queue = vec![req];- assert!(v.receive_result(&ctx, solid_result(req, 10, 10)) > 0, "the raster is taken");- assert_eq!(v.comments.settling_len(), 1, "a raster from before the commit doesn't have the stroke");- v.comments.drawings_committed();- v.last_queue = vec![req];- assert!(v.receive_result(&ctx, solid_result(req, 10, 10)) > 0);- assert_eq!(v.comments.settling_len(), 0, "a raster after the commit draws it");- // An edit that fails leaves nothing to wait for.- v.comments.settle(0.0, 0, crate::comments::CommentTool::Ink, &[[10.0, 10.0], [40.0, 30.0]]);- v.comments.drawings_refused();- assert_eq!(v.comments.settling_len(), 0, "a refused drawing isn't left painted");+ if matches!(field_menu, Some(FieldMenu::Properties)) {+ field_props = true;}-- #[test]- fn page_and_tile_admission_accounts_for_bytes_before_count_limits() {- let mut info = thumbnail_info(40);- for p in &mut info.pages {- p.width = 4000.0;- p.height = 4000.0;+ let field_props = field_props.then(|| view.prepare.selected.clone()).flatten();+ match canvas_action {+ Some(comments::CanvasAction::Edit(e)) => view.pending_edit = Some(*e),+ // `choose_right_panel` would borrow all of `app` while `view` is held; same effect.+ Some(comments::CanvasAction::OpenComments) => {+ app.right = Some(RightPanel::Comments);+ app.comments_panel_closed = false;}- let mut v = DocView::new(DocId(1), &info, ViewDefaults::default());- v.frame_queue = (0..40).map(|page| RenderRequest { page, scale: 1.0, tag: 1000, ..Default::default() }).collect();- let queue = v.prepare_render_queue(&info, 1.0);- assert_eq!(queue.len(), 2, "128 MiB admits two 4000-square pages, not 24");- v.frame_queue = (0..40)- .map(|page| RenderRequest { page, scale: 1.0, tag: 1000, tile: Some(Tile { x: 0, y: 0, w: 1024, h: 1024 }), ..Default::default() })- .collect();- assert_eq!(v.prepare_render_queue(&info, 1.0).len(), 32);- assert!(!v.admit_texture(RenderRequest::default(), PAGE_BYTES + 1));+ Some(comments::CanvasAction::Properties(p, i)) => open_props = Some((p, i)),+ Some(comments::CanvasAction::CopyImage(p, i)) => image_action = Some(crate::edit_text_ui::ImageAction::Copy(p, i)),+ Some(comments::CanvasAction::CopyImageFile(p, i)) => image_action = Some(crate::edit_text_ui::ImageAction::CopyFile(p, i)),+ None => {}}-- #[test]- fn on_screen_pages_and_tiles_are_admitted_beyond_the_prefetch_allowance() {- let ctx = egui::Context::default();- let mut info = thumbnail_info(40);- for p in &mut info.pages {- p.width = 2000.0;- p.height = 2000.0;- }- let mut v = DocView::new(DocId(1), &info, ViewDefaults::default());- // Ten 16 MB pages on screen (a zoomed-out HiDPI view) exceed the 128 MiB allowance.- v.frame_visible = (0..10).collect();- v.frame_queue = (0..40).map(|page| RenderRequest { page, scale: 1.0, tag: 1000, ..Default::default() }).collect();- let queue = v.prepare_render_queue(&info, 1.0);- let pages: Vec<usize> = queue.iter().map(|r| r.page).collect();- assert_eq!(pages, (0..10).collect::<Vec<_>>(), "every on-screen page, and no prefetch past the allowance");- v.last_queue = queue.clone();- for req in &queue {- assert!(v.receive_result(&ctx, solid_result(*req, 2000, 2000)) > 0, "on-screen page {} uploaded", req.page);- }- assert_eq!(v.pages.len(), 10, "none evicted another on-screen page");- // A 5K viewport needs more 1024-pixel tiles than the tile allowance holds.- v.frame_queue = (0..40)- .map(|x| RenderRequest { page: 0, scale: 1.0, tag: 1000, tile: Some(Tile { x: x * TILE, y: 0, w: 1024, h: 1024 }), ..Default::default() })- .collect();- assert_eq!(v.prepare_render_queue(&info, 1.0).len(), 40);+ schedule_presentation_turn(ui, view, present, clicked_link.is_some());+ let remote_open = follow_link(app, index, clicked_link);+ if tool == QuickTool::Crop && cropped {+ tool = QuickTool::Select;}-- #[test]- fn a_page_turned_back_to_is_still_cached() {- let ctx = egui::Context::default();- let info = thumbnail_info(10);- let mut v = DocView::new(DocId(1), &info, ViewDefaults::default());- let req = |page| RenderRequest { page, scale: 1.0, tag: 1000, ..Default::default() };- v.frame_visible = [0].into();- v.frame_queue = vec![req(0)];- v.last_queue = v.prepare_render_queue(&info, 1.0);- v.receive_result(&ctx, solid_result(req(0), 100, 130));- // Single-page view moves on to page 1: page 0 is no longer demanded.- v.begin_render_frame();- v.current = 1;- v.frame_visible = [1].into();- v.frame_queue = vec![req(1)];- assert_eq!(v.prepare_render_queue(&info, 1.0), vec![req(1)]);- assert!(v.pages.contains_key(&0), "kept while the allowance has room");- // And back: nothing to render.- v.begin_render_frame();- v.current = 0;- v.frame_visible = [0].into();- v.frame_queue = vec![req(0)];- assert!(v.prepare_render_queue(&info, 1.0).is_empty());+ let tool = finish_sign_requests(app, index, tool);+ app.quick_tool = tool;+ let requests = FrameRequests {+ open_props,+ field_props,+ field_menu,+ image_action,+ refused,+ open_signature,+ open_initials,+ open_boxes,+ open_table,+ form_notice,+ copy_selected,+ remote_open,+ form,+ generation,+ avail,+ };+ apply_frame_requests(app, index, ui, requests);+ }++ /// What the frame's input asked the app to do, once the document is no longer borrowed.+ struct FrameRequests {+ open_props: Option<(usize, usize)>,+ field_props: Option<(String, usize)>,+ field_menu: Option<FieldMenu>,+ image_action: Option<crate::edit_text_ui::ImageAction>,+ refused: Option<String>,+ open_signature: bool,+ open_initials: bool,+ open_boxes: bool,+ open_table: Option<(usize, [f64; 4])>,+ form_notice: Option<crate::forms_ui::FormNotice>,+ copy_selected: bool,+ remote_open: Option<(pdfcraft_engine::DocId, String, pdfcraft_render::RemoteDestination)>,+ form: Arc<Vec<pdfcraft_engine::FormField>>,+ generation: u64,+ avail: Rect,+ }++ /// Opens the dialogs and runs the app commands the frame asked for.+ fn apply_frame_requests(app: &mut PdfCraftApp, index: usize, ui: &mut egui::Ui, requests: FrameRequests) {+ let FrameRequests {+ open_props,+ field_props,+ field_menu,+ image_action,+ refused,+ open_signature,+ open_initials,+ open_boxes,+ open_table,+ form_notice,+ copy_selected,+ remote_open,+ form,+ generation,+ avail,+ } = requests;+ if let Some((page, at)) = app.views[index].comments.attach_at.take() {+ app.attach_file_comment(page, at);}-- #[test]- fn visible_pages_render_before_thumbnails_and_text() {- let ctx = egui::Context::default();- let info = thumbnail_info(4);- let mut v = DocView::new(DocId(1), &info, ViewDefaults::default());- let main = RenderRequest { page: 0, scale: 1.0, tag: 1000, ..Default::default() };- let text = RenderRequest { page: 0, kind: RequestKind::Text, scale: 1.0, tag: TEXT_TAG, ..Default::default() };- // Opening page 0 queues its pixels and text alongside Pages-panel thumbnails.- v.begin_render_frame();- v.frame_visible = [0].into();- v.frame_queue = vec![main, text];- for p in 1..4 {- v.need_thumbnail(p, true);- }- let queue = v.prepare_render_queue(&info, 1.0);- assert_eq!(queue, vec![main], "visible pixels first: no thumbnails or text yet");- // Once the visible raster arrives, background work is admitted.- v.last_queue = queue;- assert!(v.receive_result(&ctx, solid_result(main, 100, 130)) > 0);- v.begin_render_frame();- v.frame_visible = [0].into();- v.frame_queue = vec![text];- for p in 1..4 {- v.need_thumbnail(p, true);- }- let queue = v.prepare_render_queue(&info, 1.0);- assert!(queue.iter().any(|r| r.kind == RequestKind::Text), "text admitted after pixels");- assert!(queue.iter().any(|r| r.tag & THUMB_TAG != 0), "thumbnails admitted after pixels");- assert!(!queue.iter().any(|r| r.kind == RequestKind::Pixels && r.tag & THUMB_TAG == 0), "no main pixels re-requested");- // An errored visible page never holds background work back.- v.errors.insert(0, "gone".to_string());- v.begin_render_frame();- v.frame_visible = [0].into();- v.frame_queue = vec![main, text];- for p in 1..4 {- v.need_thumbnail(p, true);- }- let queue = v.prepare_render_queue(&info, 1.0);- assert!(queue.iter().any(|r| r.kind == RequestKind::Text), "text admitted despite the error");- assert!(queue.iter().any(|r| r.tag & THUMB_TAG != 0), "thumbnails still admitted");+ if let Some((p, i)) = open_props {+ app.open_comment_props(p, i);}-- #[test]- fn thumbnail_tags_do_not_change_as_a_row_scrolls_in_or_out() {- let info = thumbnail_info(10_000);- let mut v = DocView::new(DocId(1), &info, ViewDefaults::default());- let tags = |v: &mut DocView, cells: usize| {- v.begin_render_frame();- for page in 0..cells {- v.need_thumbnail(page, true);- }- v.thumbnail_requests(&info, 2.0).into_iter().map(|r| (r.page, r.tag)).collect::<HashMap<_, _>>()- };- // 2x on a large screen: about 70 cells, give or take a row of six.- let (a, b) = (tags(&mut v, 70), tags(&mut v, 76));- assert!((0..70).all(|p| a[&p] == b[&p]), "a row more or less re-renders nothing");+ if let Some((p, i)) = app.views[index].comments.default_request.take() {+ app.make_comment_default(p, i);}-- #[test]- fn many_open_documents_share_one_raster_allowance_and_close_releases_handles() {- let ctx = egui::Context::default();- let mut app = PdfCraftApp::new();- let bytes = app.session.create_blank(612.0, 792.0, 1).unwrap();- let mut expected = Vec::new();- for index in 0..6 {- app.open_bytes(&format!("synthetic-{index}.pdf"), None, bytes.as_ref().clone()).unwrap();- let info = app.session.get(app.views.last().unwrap().id).unwrap().info.clone();- let view = app.views.last_mut().unwrap();- view.begin_render_frame();- view.need_thumbnail(0, true);- let request = view.thumbnail_requests(&info, ctx.pixels_per_point()).into_iter().next().unwrap();- let page = info.pages.get(request.page).unwrap();- let dimensions = (device_pixels(page.width, request.scale), device_pixels(page.height, request.scale));- view.last_queue = vec![request];- assert_eq!(- view.receive_result(&ctx, solid_result(request, dimensions.0, dimensions.1)),- rgba_bytes(dimensions.0 as usize, dimensions.1 as usize)- );- assert_eq!(view.thumbs.get(&0).unwrap().tag, request.tag);- assert_eq!(view.thumbs.get(&0).unwrap().tex.size(), [dimensions.0 as usize, dimensions.1 as usize]);-- view.begin_render_frame();- view.need_thumbnail(0, true);- let queue = view.prepare_render_queue(&info, ctx.pixels_per_point());- assert!(queue.is_empty(), "the synthetic thumbnail satisfies current demand");- view.last_queue = queue;- expected.push((request, dimensions));- }- assert_eq!(app.views.len(), 6, "all six documents were opened");- assert_eq!(app.active_ids().map(|(index, _)| index), Some(5));- assert!(app.views.iter().zip(&expected).all(|(view, (request, dimensions))| {- view.thumbs.len() == 1- && view- .thumbs- .get(&0)- .is_some_and(|thumb| thumb.tag == request.tag && thumb.tex.size() == [dimensions.0 as usize, dimensions.1 as usize])- }));-- app.finish_render_frame(&ctx);- let total: usize = app.views.iter().map(|v| v.thumbs.values().map(|p| texture_bytes(&p.tex)).sum::<usize>()).sum();- let (active_request, active_dimensions) = expected.last().unwrap();- let active_bytes = rgba_bytes(active_dimensions.0 as usize, active_dimensions.1 as usize);- assert_eq!(total, active_bytes, "only the active view retains a thumbnail");- assert!(total <= THUMB_BYTES, "retained thumbnails stay within the existing allowance");- assert!(app.views.iter().take(5).all(|v| v.thumbs.is_empty() && v.last_queue.is_empty()));- let active = app.views.last().unwrap();- assert_eq!(active.thumbs.len(), 1);- assert_eq!(active.thumbs.get(&0).unwrap().tag, active_request.tag);- assert!(active.last_queue.is_empty(), "the current thumbnail is already cached");- for view in &app.views {- let doc = app.session.get(view.id).unwrap();- assert_eq!(doc.renderer.stats().render_requests, 0, "the fixture must not launch a native render");- }-- app.close_tab(5);- assert_eq!(app.views.len(), 5, "closing the active tab drops its owning view");- assert!(app.views.iter().all(|v| v.thumbs.is_empty()));+ if let Some((p, i, open)) = app.views[index].comments.attachment_request.take() {+ let doc = app.views[index].id;+ app.comment_attachment_action(doc, p, i, open);}-- #[test]- fn suspended_signature_preview_releases_layers_and_rebuilds_without_editing() {- let ctx = egui::Context::default();- let mut png = std::io::Cursor::new(Vec::new());- image::RgbaImage::from_pixel(12, 4, image::Rgba([20, 30, 40, 255])).write_to(&mut png, image::ImageFormat::Png).unwrap();- let image = pdfcraft_engine::SignatureImage::from_bytes(png.get_ref()).unwrap();- let mut session = pdfcraft_engine::Session::new();- let blank = session.create_blank(300.0, 400.0, 1).unwrap();- let id = session.open_new("signature-preview.pdf", blank).unwrap();- let info = session.get(id).unwrap().info.pages[0].clone();- session.apply(id, image.edit(0, &info, [20.0, 100.0], false, "Test").unwrap()).unwrap();- let doc = session.get(id).unwrap();- let bytes = doc.bytes.clone();- let generation = doc.edit_generation();- let mut v = DocView::new(id, &doc.info, ViewDefaults::default());- v.comments.selected = Some((0, 0));- v.signature_drag.prepare(&ctx, doc, v.comments.selected, 1.0);- assert!(v.signature_drag.contains(0, 0));-- v.suspend_rendering(&doc.renderer);- assert!(!v.signature_drag.contains(0, 0), "inactive tabs release the preview pool and textures");- assert_eq!(v.comments.selected, Some((0, 0)), "the user's selection survives suspension");- v.signature_drag.prepare(&ctx, doc, v.comments.selected, 1.0);- assert!(v.signature_drag.contains(0, 0), "reactivating the view rebuilds the selected image's preview");- assert!(Arc::ptr_eq(&bytes, &doc.bytes));- assert_eq!(doc.edit_generation(), generation);- assert_eq!(doc.can_undo(), Some("Add signature"));- assert!(doc.dirty);+ if let Some((name, w)) = field_props {+ app.open_field_props(&name, w);}-- #[test]- fn suspending_a_view_releases_owned_raster_textures_and_queue_state() {- let ctx = egui::Context::default();- let mut view = view(2, PageLayout::Single, true);- let texture = |name| ctx.load_texture(name, egui::ColorImage::filled([1, 1], Color32::WHITE), TextureOptions::LINEAR);- let request = RenderRequest { page: 0, scale: 1.0, tag: 1, ..Default::default() };- view.pages.insert(0, PageTex { tag: request.tag, tex: texture("suspended-page") });- view.thumbs.insert(1, PageTex { tag: THUMB_TAG, tex: texture("suspended-thumbnail") });- view.tiles.insert((0, request.tag, 0, 0), texture("suspended-tile"));- view.grid_pages.insert(1, (1, texture("suspended-grid-page")));- view.print_pages.insert(1, (PRINT_TAG, texture("suspended-print-page")));- view.stale_thumbs.insert(1);- view.waiting_since.insert(0, 1.0);- view.last_queue = vec![request];- view.frame_queue = vec![request];- view.frame_visible.insert(0);- view.need_thumbnail(1, true);-- let pool = RenderPool::new_inline(Arc::new(Vec::new()), Default::default());- view.suspend_rendering(&pool);-- assert!(view.pages.is_empty(), "page handles are released");- assert!(view.thumbs.is_empty(), "thumbnail handles are released");- assert!(view.tiles.is_empty(), "tile handles are released");- assert!(view.grid_pages.is_empty(), "organize-grid handles are released");- assert!(view.print_pages.is_empty(), "print-preview handles are released");- assert!(view.stale_thumbs.is_empty(), "stale thumbnail bookkeeping is cleared");- assert!(view.waiting_since.is_empty(), "waiting bookkeeping is cleared");- assert!(view.last_queue.is_empty() && !view.render_pending(), "queued demand is retired");- assert!(view.frame_queue.is_empty() && view.frame_visible.is_empty() && view.thumb_demand.is_empty());+ if let Some(FieldMenu::Duplicate(name)) = field_menu {+ let pages = app.session.get(app.views[index].id).map_or(1, |d| d.info.pages.len());+ app.duplicate_draft = Some(crate::DuplicateDraft { name, all: true, from: 1, to: pages });+ app.dialog = Some(crate::Dialog::DuplicateField);}-- /// Edit text & images keeps its boxes while page input is blocked (the window unfocused, a- /// dialog or the palette open): the page's paragraphs are still measured for the latest edit- /// and drawn, instead of vanishing until the pointer comes back.- #[test]- fn edit_text_boxes_stay_drawn_while_page_input_is_blocked() {- let mut h = egui_kittest::Harness::builder().with_size(vec2(1400.0, 900.0)).build_eframe(|_cc| {- let mut app = PdfCraftApp::new();- let bytes = app.session.create_blank(300.0, 400.0, 1).unwrap();- app.open_bytes("blank.pdf", None, bytes.as_ref().clone()).unwrap();- app.quick_tool = QuickTool::EditText;- app- });- h.run_steps(3);- // Block page input the way the window losing focus does.- h.state_mut().palette_open = true;- h.run_steps(2);- assert!(h.state_mut().apply_edit(Edit::RotatePages { pages: vec![0], degrees: 90 }));- h.run_steps(3);- let app = h.state();- let generation = app.session.get(app.views[0].id).unwrap().edit_generation();- assert_eq!(app.views[0].edit_lines.get(&0).map(|(g, _)| *g), Some(generation), "the boxes follow the edit while input is blocked");+ if let Some((page, rect)) = app.views[index].links.open_new.take() {+ app.open_link_props(page, Some(rect), None);}-- #[test]- fn virtualized_organizer_keeps_insert_gaps_at_document_positions() {- use egui_kittest::kittest::Queryable;-- let mut h = egui_kittest::Harness::builder().with_size(vec2(1400.0, 900.0)).build_eframe(|_cc| {- let mut app = PdfCraftApp::new();- let bytes = app.session.create_blank(300.0, 400.0, 100).unwrap();- app.open_bytes("organize-gaps.pdf", None, bytes.as_ref().clone()).unwrap();- app.views[0].organize = true;- app- });- h.run_steps(4);- assert!(h.state().views[0].thumb_demand.len() < 50);- assert_eq!(h.query_all_by_label("Insert a file at the end").count(), 0, "the last virtualized cell is not the final page");- let center = h.state().views[0].viewport_rect().center();- h.hover_at(center);- h.event(egui::Event::MouseWheel {- unit: egui::MouseWheelUnit::Point,- delta: vec2(0.0, -100_000.0),- phase: egui::TouchPhase::Move,- modifiers: egui::Modifiers::NONE,- source: egui::MouseWheelSource::Unknown,- });- // Well past egui's longest scroll animation (about 0.3 s).- h.run_steps(40);- h.get_by_label("Insert a file at the end");- let before_last = h.get_by_label("Insert a file before page 100").rect().center();- h.hover_at(before_last);- h.run_steps(2);- assert_eq!(h.state().views[0].grid_gap, Some(99), "external drops use the document index after virtualized scrolling");- assert!(h.state().views[0].thumb_demand.len() < 50);+ if let Some((page, i)) = app.views[index].links.open_existing.take() {+ app.open_link_props(page, None, Some(i));}-- #[test]- fn real_shell_pages_organizer_and_print_only_collect_current_thumbnail_consumers() {- let mut h = egui_kittest::Harness::builder().with_size(vec2(1400.0, 900.0)).build_eframe(|_cc| {- let mut app = PdfCraftApp::new();- let bytes = app.session.create_blank(612.0, 792.0, 10_000).unwrap();- app.open_bytes("synthetic-ten-thousand.pdf", None, bytes.as_ref().clone()).unwrap();- app.right = Some(RightPanel::Pages);- app+ if let Some((page, quads)) = 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,+ })+ } else {+ app.redact_prefs.mark(page, quads, &author)});- h.run_steps(4);- assert!((1..20).contains(&h.state().views[0].thumb_demand.len()));- h.state_mut().right = None;- h.state_mut().views[0].organize = true;- h.run_steps(2);- assert!((1..50).contains(&h.state().views[0].thumb_demand.len()));- h.state_mut().views[0].organize = false;- h.state_mut().dialog = Some(crate::Dialog::Print);- h.state_mut().print_draft.sheet = 9999;- h.run_steps(2);- assert_eq!(h.state().views[0].thumb_demand.keys().copied().collect::<Vec<_>>(), vec![9999]);- h.state_mut().print_draft.handling = crate::PrintHandling::Booklet;- h.state_mut().print_draft.sheet = 0;- h.run_steps(2);- assert_eq!(h.state().views[0].thumb_demand.len(), 2, "booklet only needs its two placed pages");- h.state_mut().dialog = None;- h.run_steps(2);- assert!(h.state().views[0].thumb_demand.is_empty());- assert!(h.state().views[0].thumbs.is_empty());- }-- /// One mouse-wheel notch (a line) at `at` seconds.- fn notch(v: &mut DocView, dy: f32, at: f64) -> bool {- v.single_page_wheel(egui::MouseWheelUnit::Line, dy, egui::TouchPhase::Move, at, true)- }-- #[test]- fn thumbnails_cover_the_panel_on_a_high_dpi_screen() {- // Pages panel slot is at most 150 logical points. At 2 px/pt a letter page's thumbnail- // must be at least that wide, so the panel samples it down instead of stretching it.- let info = thumbnail_info(1);- let mut v = DocView::new(DocId(1), &info, ViewDefaults::default());- v.need_thumbnail(0, true);- let queue = v.prepare_render_queue(&info, 2.0);- let scale = queue.first().expect("one thumbnail").scale;- assert!(612.0 * scale >= 150.0 * 2.0, "{scale}");}-- #[test]- fn notches_turn_pages_and_stop_at_the_ends() {- let mut v = view(3, PageLayout::Single, false);- assert!(notch(&mut v, -1.0, 1.0) && notch(&mut v, -1.0, 1.05));- assert_eq!(v.current, 2);- assert!(!notch(&mut v, -1.0, 1.1), "nothing turns past the last page");- assert!(notch(&mut v, 1.0, 1.2));- assert_eq!(v.current, 1);- }-- #[test]- fn notches_turn_two_page_spreads() {- // Two-page view, shown one spread at a time (not continuous): a notch turns a whole- // spread at once, not a single page (#752).- let mut v = view(4, PageLayout::TwoUp, false);- assert!(notch(&mut v, -1.0, 1.0));- assert_eq!(v.current, 2, "a notch turns from the first spread to the second");- assert!(notch(&mut v, 1.0, 1.1));- assert_eq!(v.current, 0, "a notch back turns to the previous spread");- }-- #[test]- fn continuous_views_ignore_the_wheel_for_paging() {- // Scrolling views let the ScrollArea handle the wheel; it never turns pages.- for layout in [PageLayout::Single, PageLayout::TwoUp] {- let mut v = view(3, layout, true);- assert!(!notch(&mut v, -1.0, 1.0), "{layout:?} continuous ignores the wheel");- assert_eq!(v.current, 0);+ match image_action {+ Some(crate::edit_text_ui::ImageAction::Replace(page, index)) => app.replace_page_image_dialog(page, index),+ Some(crate::edit_text_ui::ImageAction::Save(page, index)) => app.save_page_image(page, index),+ Some(crate::edit_text_ui::ImageAction::Copy(page, index)) => {+ app.copy_page_image(page, index);}+ Some(crate::edit_text_ui::ImageAction::CopyFile(page, index)) => app.copy_page_image_file(page, index),+ Some(crate::edit_text_ui::ImageAction::Cut(page, image)) => {+ app.views[index].image_selection = None;+ app.cut_page_image(page, image);+ }+ Some(crate::edit_text_ui::ImageAction::Redact(page, index)) => app.redact_page_image(page, index),+ Some(crate::edit_text_ui::ImageAction::Link(page, index)) => app.link_page_image(page, index),+ Some(crate::edit_text_ui::ImageAction::Recognize(page)) => app.recognize_text_on_page(page),+ None => {}}-- #[test]- fn navigation_drops_partial_wheel_motion() {- use egui::{MouseWheelUnit::Point, TouchPhase::Move, TouchPhase::Start};- let mut v = view(3, PageLayout::Single, false);- assert!(!v.single_page_wheel(Point, 0.0, Start, 1.0, true));- assert!(!v.single_page_wheel(Point, -30.0, Move, 1.02, true));- v.go_to_page(1);- // The same touch has to move a full notch's worth again before it turns.- assert!(!v.single_page_wheel(Point, -30.0, Move, 1.04, true));- assert!(v.single_page_wheel(Point, -30.0, Move, 1.06, true));- assert_eq!(v.current, 2);- }-- #[test]- fn reselecting_the_layout_does_not_scroll_to_top() {- let mut v = view(3, PageLayout::Single, true);- v.goto = None;- v.set_layout(PageLayout::Single);- assert!(v.goto.is_none(), "re-selecting the current layout is a no-op");- v.set_continuous(true);- assert!(v.goto.is_none(), "re-selecting the current continuity is a no-op");- v.set_layout(PageLayout::TwoUp);- assert_eq!(v.goto, Some((0, 0.0)), "switching the base layout aligns the current page");- v.goto = None;- v.set_continuous(false);- assert_eq!(v.goto, Some((0, 0.0)), "toggling continuous scrolling aligns the current page");+ if let Some(why) = refused {+ app.notify_error(why);}-- #[test]- fn fit_page_and_height_hold_still_while_mixed_page_sizes_scroll_past() {- let page =- |width: f32, height: f32| pdfcraft_render::PageInfo { width, height, label: String::new(), crop: [0.0, 0.0, width, height], rotation: 0 };- let info = DocInfo { pages: vec![page(300.0, 400.0), page(600.0, 800.0)], ..Default::default() };- for fit in [Fit::Page, Fit::Height] {- let mut v = DocView::new(DocId(1), &info, ViewDefaults::default());- (v.fit, v.viewport_w, v.viewport_h) = (fit, 1000.0, 800.0);- v.fit_zoom(&info);- let zoom = v.zoom;- v.current = 1;- v.fit_zoom(&info);- assert_eq!(v.zoom, zoom, "{fit:?}: scrolling onto a bigger page keeps the zoom");- // A single page shown on its own (not scrolling) fits each one.- (v.layout, v.continuous) = (PageLayout::Single, false);- v.fit_zoom(&info);- let big = v.zoom;- v.current = 0;- v.fit_zoom(&info);- assert!(v.zoom > big, "{fit:?}: single-page view fits the page it shows");- }+ if open_signature || open_initials {+ app.signature_draft = crate::fill_sign::SigDraft::new(open_initials, &app.comment_prefs.author);+ app.dialog = Some(crate::Dialog::Signature);}-- /// Review on #2070: full screen in two-page view fits the spread it shows, the cover page- /// on its own included; two-page view in the window keeps one zoom for the document.- #[test]- fn full_screen_two_page_view_fits_the_spread_it_shows() {- let page =- |width: f32, height: f32| pdfcraft_render::PageInfo { width, height, label: String::new(), crop: [0.0, 0.0, width, height], rotation: 0 };- // Spreads [0, 1] small, [2, 3] large; with a cover page [0], [1, 2] mixed, [3].- let info = DocInfo { pages: vec![page(300.0, 400.0), page(300.0, 400.0), page(600.0, 800.0), page(600.0, 800.0)], ..Default::default() };- let mut v = DocView::new(DocId(1), &info, ViewDefaults::default());- (v.layout, v.continuous, v.viewport_w, v.viewport_h) = (PageLayout::TwoUp, false, 1000.0, 800.0);- v.fit = Fit::Page;- v.fit_zoom(&info);- let windowed = v.zoom;- v.enter_presentation();- v.fit_zoom(&info);- let small = v.zoom;- assert!(small > windowed * 1.9, "the small spread fills the screen: {small} vs {windowed}");- v.current = 3;- v.fit_zoom(&info);- assert!((v.zoom - windowed).abs() < 1e-4, "the large spread fits as before");- v.current = 1;- v.fit_zoom(&info);- assert_eq!(v.zoom, small, "page 2 is in the first spread");- // With a cover page: [0] alone, then [1, 2] (the large page decides), then [3].- v.cover = true;- v.current = 0;- v.fit_zoom(&info);- assert_eq!(v.zoom, small, "the cover page alone");- v.current = 1;- v.fit_zoom(&info);- assert!((v.zoom - windowed).abs() < 1e-4, "page 2 shares a spread with the large page 3");- // Scrolling while in full screen fits the document, as scrolling does in the window.- (v.continuous, v.current) = (true, 0);- v.fit_zoom(&info);- assert!((v.zoom - windowed).abs() < 1e-4, "continuous full screen keeps one zoom");- v.continuous = false;- // The cover page is a spread of its own even when the next page is larger.- let mixed = DocInfo { pages: vec![page(300.0, 400.0), page(600.0, 800.0), page(600.0, 800.0)], ..Default::default() };- v.current = 0;- v.fit_zoom(&mixed);- assert_eq!(v.zoom, small, "the small cover alone, not with page 2");- // Leaving full screen brings the document-wide fit back.- v.leave_presentation();- (v.fit, v.current) = (Fit::Page, 0);- (v.layout, v.continuous) = (PageLayout::TwoUp, false);- v.fit_zoom(&info);- assert!((v.zoom - windowed).abs() < 1e-4, "in the window, one zoom for the document");+ if open_boxes {+ app.boxes_draft.range = crate::pageboxes::Range::Current;+ app.boxes_draft.seeded = None;+ app.dialog = Some(crate::Dialog::PageBoxes);}-- #[test]- fn fit_width_fits_the_shown_page_in_single_page_view_only() {- let page =- |width: f32, height: f32| pdfcraft_render::PageInfo { width, height, label: String::new(), crop: [0.0, 0.0, width, height], rotation: 0 };- let info = DocInfo { pages: vec![page(300.0, 400.0), page(600.0, 400.0)], ..Default::default() };- let mut v = DocView::new(DocId(1), &info, ViewDefaults::default());- (v.fit, v.viewport_w, v.viewport_h) = (Fit::Width, 1000.0, 800.0);- v.layout = PageLayout::Single;- v.continuous = false;- v.fit_zoom(&info);- let narrow = v.zoom;- // The shown page fills the width between the side gutters, not centred for the wide page.- let shown = v.layout(&info, v.content_width(&info, 1000.0), 1.0)[0];- assert!((shown.left() - SIDE).abs() < 1e-2 && (shown.width() - 860.0).abs() < 1e-2, "{shown:?}");- v.current = 1;- v.fit_zoom(&info);- assert!((narrow / v.zoom - 2.0).abs() < 1e-3, "the narrow page gets twice the zoom of the wide one");- // Scrolling views keep one zoom for the whole document.- v.continuous = true;- v.fit_zoom(&info);- let wide = v.zoom;- v.current = 0;- v.fit_zoom(&info);- assert_eq!(v.zoom, wide, "continuous fit width holds still across page sizes");+ if let Some((page, rect)) = open_table {+ app.field_table_draft = Some(crate::field_table_ui::FieldTableDraft::new(app.views[index].id, page, rect, &form, generation));+ app.dialog = Some(crate::Dialog::FieldTable);+ // The window lasts while the form is prepared. Drawn with the tool picked but its panel+ // closed, the tool goes back to Select above, so the panel opens to keep it prepared.+ app.left = crate::LeftPanel::Tool("form");+ app.reveal_tools();}-- #[test]- fn layouts_match_their_commands_and_names() {- for l in PageLayout::ORDER {- let spec = pdfcraft_engine::commands::command(l.command()).expect("registered");- assert_eq!((l.label(), l.icon()), (spec.label, spec.icon), "{l:?}");- assert_eq!(PageLayout::from_command(l.command()), Some(l));- assert_eq!(PageLayout::try_parse(l.as_str()), Some(l));+ if let Some(n) = form_notice {+ match n {+ crate::forms_ui::FormNotice::Security => app.notify_tr("The document's security settings don't allow filling in form fields"),+ crate::forms_ui::FormNotice::ReadOnly(name) => app.notify_fmt("{name} is read-only", &[("name", &name)]),+ crate::forms_ui::FormNotice::NoAction(name) => app.notify_fmt("{name} has no action", &[("name", &name)]),}- assert_eq!(PageLayout::try_parse(" Two-Up "), Some(PageLayout::TwoUp));- assert_eq!(PageLayout::try_parse("facing"), None);}-- #[test]- fn a_null_xyz_coordinate_keeps_the_readers_place_on_the_new_page() {- // CAD exports link each cross-reference as `/XYZ null null 0`. Acrobat keeps the- // point at the window's top-left (and the zoom) when following one to another sheet.- let info = pdfcraft_render::DocInfo {- pages: (0..3)- .map(|_| pdfcraft_render::PageInfo { width: 842.0, height: 595.0, label: String::new(), crop: [0.0, 0.0, 842.0, 595.0], rotation: 0 })- .collect(),- ..Default::default()- };- // Page 1 at 400 %, scrolled so its point 200 pt across and 125 pt down is at the corner- // where /XYZ puts its point.- let zoomed = |rot: u16, size: Vec2| {- let mut v = view(3, PageLayout::Single, true);- v.rotation = rot;- v.viewport_screen = Rect::from_min_size(Pos2::ZERO, vec2(1000.0, 600.0));- v.screen_xforms = vec![(0, PageXform { rect: Rect::from_min_size(pos2(SIDE - 800.0, -500.0), size), rot, pw: 842.0, ph: 595.0 })];- v- };- let near = |a: Option<f32>, b: f32| a.is_some_and(|a| (a - b).abs() < 1e-4);- let mut v = zoomed(0, vec2(4.0 * 842.0, 4.0 * 595.0));- v.go_to_dest(1, DestView::Xyz { left: None, top: None, zoom: None }, &info);- let (page, fx, fy, rel) = v.goto_point.expect("the place is kept");- assert_eq!((v.current, page, rel), (1, 1, vec2(SIDE, 0.0)));- assert!(near(fx, 200.0 / 842.0) && near(fy, 125.0 / 595.0), "{fx:?} {fy:?}");- // A coordinate the destination gives wins; only the null one is kept.- let mut v = zoomed(0, vec2(4.0 * 842.0, 4.0 * 595.0));- v.go_to_dest(2, DestView::Xyz { left: Some(421.0), top: None, zoom: Some(4.0) }, &info);- let (_, fx, fy, _) = v.goto_point.expect("the place is kept");- assert!(near(fx, 0.5) && near(fy, 125.0 / 595.0), "{fx:?} {fy:?}");- // With the view turned a quarter, the point under the corner is still the one kept.- let mut v = zoomed(90, vec2(4.0 * 595.0, 4.0 * 842.0));- v.go_to_dest(1, DestView::Xyz { left: None, top: None, zoom: None }, &info);- let (_, fx, fy, _) = v.goto_point.expect("the place is kept");- assert!(near(fx, 800.0 / (4.0 * 595.0)) && near(fy, 500.0 / (4.0 * 842.0)), "{fx:?} {fy:?}");- // A page that fits the window keeps the layout's placement: no point, as before.- let mut v = zoomed(0, vec2(800.0, 565.0));- v.go_to_dest(1, DestView::Xyz { left: None, top: None, zoom: None }, &info);- assert_eq!((v.current, v.goto, v.goto_point), (1, Some((1, 0.0)), None));+ if let Some((name, action)) = app.views[index].forms.button.take() {+ run_button(app, index, &name, action);}-- #[test]- fn destinations_set_the_zoom_mode_and_the_point_to_show() {- let info = pdfcraft_render::DocInfo {- pages: (0..3)- .map(|_| pdfcraft_render::PageInfo { width: 300.0, height: 400.0, label: String::new(), crop: [0.0, 0.0, 300.0, 400.0], rotation: 0 })- .collect(),- ..Default::default()- };- let mut v = view(3, PageLayout::Single, true);- v.fit = Fit::Width;- // No position (or a malformed one): the top of the page, zoom as it was.- v.go_to_dest(1, DestView::Top, &info);- assert_eq!((v.current, v.goto, v.goto_point, v.fit), (1, Some((1, 0.0)), None, Fit::Width));- // /XYZ with a null zoom keeps the zoom mode; its point is a quarter down page 3.- v.go_to_dest(2, DestView::Xyz { left: None, top: Some(300.0), zoom: None }, &info);- assert_eq!((v.current, v.fit, v.goto_point), (2, Fit::Width, Some((2, None, Some(0.25), vec2(SIDE, 0.0)))));- v.go_to_dest(0, DestView::Xyz { left: Some(150.0), top: None, zoom: Some(2.5) }, &info);- assert_eq!((v.fit, v.zoom, v.goto_point), (Fit::None, 2.5, Some((0, Some(0.5), None, vec2(SIDE, 0.0)))));- // A zoom beyond the view's range is clamped to it.- v.go_to_dest(0, DestView::Xyz { left: None, top: None, zoom: Some(1e30) }, &info);- assert_eq!((v.zoom, v.goto_point), (64.0, None));- v.go_to_dest(0, DestView::Fit, &info);- assert_eq!((v.fit, v.goto_point), (Fit::Page, None));- v.go_to_dest(0, DestView::FitH { top: Some(100.0) }, &info);- assert_eq!((v.fit, v.goto_point), (Fit::Width, Some((0, None, Some(0.75), vec2(SIDE, 0.0)))));- v.go_to_dest(0, DestView::FitV { left: Some(75.0) }, &info);- assert_eq!((v.fit, v.goto_point), (Fit::Height, Some((0, Some(0.25), None, vec2(SIDE, 0.0)))));- // /FitR: the zoom that fits a 100×50 pt rectangle in an 800×600 window, centred.- (v.viewport_w, v.viewport_h) = (800.0, 600.0);- v.go_to_dest(0, DestView::FitR { rect: [0.0, 300.0, 100.0, 350.0] }, &info);- assert_eq!(v.fit, Fit::None);- assert!((v.zoom - 8.0 / PT).abs() < 1e-4, "{}", v.zoom);- let (page, fx, fy, rel) = v.goto_point.expect("a point to show");- assert_eq!((page, rel), (0, vec2(400.0, 300.0)));- assert!((fx.unwrap_or(-1.0) - 50.0 / 300.0).abs() < 1e-4 && (fy.unwrap_or(-1.0) - 75.0 / 400.0).abs() < 1e-4, "{fx:?} {fy:?}");- // A page past the end goes to the last page; a page the document info lacks, to its top.- v.go_to_dest(usize::MAX, DestView::FitH { top: Some(100.0) }, &info);- assert_eq!((v.current, v.goto_point.map(|g| g.0)), (2, Some(2)));- let empty = pdfcraft_render::DocInfo::default();- v.go_to_dest(1, DestView::FitH { top: Some(100.0) }, &empty);- assert_eq!((v.current, v.goto_point), (1, None));+ if copy_selected {+ app.execute("edit.copy");}-- #[test]- fn page_text_failure_preserves_valid_search_match_without_jitter() {- let mut v = view(3, PageLayout::Single, true);- v.current = 1;- v.find = Some(Find {- query: "test".into(),- case_query: "test".into(),- matches: vec![(0, 0..4), (1, 5..9)],- current: Some(0),- ..Default::default()- });- let req = RenderRequest { page: 0, kind: RequestKind::Text, ..Default::default() };- v.last_queue = vec![req];- let ctx = egui::Context::default();- v.receive_result(- &ctx,- pdfcraft_render::RenderedPage {- request: req,- width: 0,- height: 0,- rgba: Default::default(),- error: Some("extraction failed".into()),- text: None,- warnings: Vec::new(),- millis: 0,- },- );- // Active match was on page 0 which failed: current should fall back to match on page 1 without jitter- assert_eq!(v.find.as_ref().unwrap().current, Some(0));- assert_eq!(v.find.as_ref().unwrap().matches, vec![(1, 5..9)]);- assert!(v.goto.is_none());+ // Read mode hides the tools (#2646), and full screen is the page and nothing else (#1459);+ // the quick tools come back with the window.+ if app.mode != crate::Mode::Read && !app.full_screen {+ quick_bar(app, avail, ui);}-- /// A page whose picture moved can get its whole-page raster back before its last stale tile.- /// From then on the raster has the picture where it went: it is drawn from there, not from- /// where it was (which the raster now shows empty), and another drag starts from there too.- #[test]- fn a_moved_picture_is_drawn_from_the_fresh_raster_while_a_tile_is_still_stale() {- let content = b"q 60 0 0 60 40 260 cm /Im0 Do Q";- let objs: Vec<Vec<u8>> = vec![- b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(),- b"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 300 400] >>".to_vec(),- b"<< /Type /Page /Parent 2 0 R /Contents 4 0 R /Resources << /XObject << /Im0 5 0 R >> >> >>".to_vec(),- [format!("<< /Length {} >>\nstream\n", content.len()).as_bytes(), content.as_slice(), b"\nendstream"].concat(),- [- b"<< /Type /XObject /Subtype /Image /Width 1 /Height 1 /BitsPerComponent 8 /ColorSpace /DeviceRGB /Length 3 >>\nstream\n".as_slice(),- &[200, 30, 30],- b"\nendstream",- ]- .concat(),- ];- let mut bytes = b"%PDF-1.7\n".to_vec();- let mut offsets = Vec::new();- for (i, o) in objs.iter().enumerate() {- offsets.push(bytes.len());- bytes.extend_from_slice(format!("{} 0 obj\n", i + 1).as_bytes());- bytes.extend_from_slice(o);- bytes.extend_from_slice(b"\nendobj\n");- }- let xref = bytes.len();- bytes.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes());- for o in offsets {- bytes.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());- }- bytes.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes());- let mut h = egui_kittest::Harness::builder().with_size(vec2(1400.0, 1100.0)).build_eframe(move |_cc| {- let mut app = PdfCraftApp::new();- app.set_option("language", "en").unwrap();- app.open_bytes("picture.pdf", None, bytes.clone()).unwrap();- app.set_option("zoom", "100").unwrap();- app.quick_tool = QuickTool::EditText;- app- });- let settle = |h: &mut egui_kittest::Harness<'static, PdfCraftApp>| {- for _ in 0..400 {- h.step();- if !h.state().render_pending() {- return;- }- std::thread::sleep(std::time::Duration::from_millis(5));- }- };- h.run_steps(4);- settle(&mut h);- let page = h.state().views[0].page_screen_rect(0).unwrap();- let at = |x: f32, y: f32| egui::pos2(page.left() + x / 300.0 * page.width(), page.top() + (400.0 - y) / 400.0 * page.height());- let red = |pixels: &image::RgbaImage, r: Rect| {- let (w, hh) = (pixels.width(), pixels.height());- (r.top().max(0.0) as u32..(r.bottom() as u32).min(hh))- .flat_map(|y| (r.left().max(0.0) as u32..(r.right() as u32).min(w)).map(move |x| (x, y)))- .filter(|(x, y)| matches!(pixels.get_pixel(*x, *y).0, [r, g, b, _] if r > 150 && g < 90 && b < 90))- .count()- };- let (old, new) = (Rect::from_two_pos(at(42.0, 262.0), at(98.0, 318.0)), Rect::from_two_pos(at(182.0, 82.0), at(238.0, 138.0)));- // Select the picture and drag it, without overlap, from (40, 260) to (180, 80).- let drag = |h: &mut egui_kittest::Harness<'static, PdfCraftApp>, from: Pos2, to: Pos2, release: bool| {- h.hover_at(from);- h.run_steps(1);- h.drag_at(from);- h.run_steps(1);- for k in 1..=4 {- h.hover_at(from + (to - from) * (k as f32 / 4.0));- h.run_steps(1);- }- if release {- h.drop_at(to);- h.step();- }- };- let (grab, put) = (at(70.0, 290.0), at(210.0, 110.0));- h.hover_at(grab);- h.run_steps(1);- h.drag_at(grab);- h.run_steps(1);- h.drop_at(grab);- h.run_steps(3);- assert!(h.state().views[0].image_selection.is_some(), "the picture is selected");- h.state_mut().views[0].hold_rasters = true;- drag(&mut h, grab, put, true);- // One tile stays stale, as a tile result arriving after the whole-page raster would; then- // the whole-page raster is let through.- let tile = h.ctx.load_texture("stale-tile", egui::ColorImage::new([1, 1], vec![Color32::TRANSPARENT]), TextureOptions::LINEAR);- h.state_mut().views[0].tiles.insert((0, 1, 0, 0), tile);- h.state_mut().views[0].stale_tiles.insert((0, 1, 0, 0));- h.state_mut().views[0].hold_rasters = false;- for _ in 0..400 {- h.step();- if !h.state().views[0].page_raster_out_of_date(0) {- break;- }- std::thread::sleep(std::time::Duration::from_millis(5));- }- assert!(!h.state().views[0].page_raster_out_of_date(0), "the whole-page raster is fresh");- assert!(h.state().views[0].page_out_of_date(0), "a tile is still stale");- h.run_steps(2);- let pixels = h.render().unwrap();- assert!(red(&pixels, new) > 100, "the picture shows where it went");- assert_eq!(red(&pixels, old), 0, "and not where it was");- // Another drag in that interval takes its pixels from where the raster has them.- let further = at(210.0, 200.0);- drag(&mut h, put, further, false);- let pixels = h.render().unwrap();- let moving = Rect::from_two_pos(at(182.0, 172.0), at(238.0, 228.0));- assert!(red(&pixels, moving) > 100, "the dragged picture is drawn from the fresh raster");- assert_eq!(red(&pixels, old), 0, "nothing shows where it first was");- h.state_mut().views[0].stale_tiles.clear();- h.state_mut().views[0].tiles.clear();+ if let Some((source, file, destination)) = remote_open {+ app.open_remote_link(source, file, destination);}}++ /// The prepare-mode field menu's choices.+ enum FieldMenu {+ Properties,+ Duplicate(String),+ }++ #[cfg(test)]+ mod tests;diff --cc crates/ui-egui/src/canvas/area.rsindex 000000000,ea3b74170..068661ea5mode 000000,100644..100644--- a/crates/ui-egui/src/canvas/area.rs+++ b/crates/ui-egui/src/canvas/area.rs@@@ -1,0 -1,168 +1,157 @@@+ use super::{LayerOp, PdfCraftApp, Pos2, Rect};++ /// A validation badge drawn over a signature widget: the widget rectangle (user space), the verdict it shows, and its hover text.+ pub(crate) struct SignatureBadge {+ pub rect: [f64; 4],+ pub status: pdfcraft_engine::SignatureStatus,+ pub summary: &'static str,+ }++ /// The validation badges drawn over one page's signature widgets: signed, visible widgets+ /// on this page with coordinates that survive the cast to screen space. Hostile files can+ /// carry NaN, infinite or gigantic rectangles, which must never reach the painter.+ pub(crate) fn signature_badges(signatures: &[pdfcraft_engine::SignatureInfo], page: usize) -> Vec<SignatureBadge> {+ signatures+ .iter()+ .filter(|s| s.signed && s.visible && s.page == Some(page))+ .filter_map(|s| {+ s.rect.filter(|r| r.iter().all(|v| v.is_finite() && v.abs() < f32::MAX as f64)).map(|rect| SignatureBadge {+ rect,+ status: s.status,+ summary: s.summary(),+ })+ })+ .collect()+ }+-/// The hover popup for an annotation. Replies and Fill & Sign marks (typed text, checks, signatures)-/// show none: they are page content being edited, not comments.-pub(super) fn annotation_hover_text(a: &pdfcraft_render::Annotation) -> Option<String> {- if a.is_reply() || a.fill_sign {- return None;- }- let who = a.author.clone().unwrap_or_else(|| a.subtype.clone());- let body = a.contents.clone().unwrap_or_default();- Some(if body.is_empty() { who } else { format!("{who}\n{body}") })-}-+ /// Suppression window for egui's eased copy of point input.+ ///+ /// egui 0.36.2 drains `WheelState::after_events` tail deltas by 90% per 0.1 s.+ pub(super) const SUPPRESS_SECS: f64 = 0.25;++ /// Short rolling extension while egui still has an unprocessed wheel tail.+ pub(super) const SUPPRESS_TAIL_SECS: f64 = 0.05;++ // Keep the viewer's scroll identity tied to the document instead of its parent UI.+ pub(super) fn page_scroll<R>(+ ui: &mut egui::Ui,+ scroll: egui::ScrollArea,+ id: egui::Id,+ draw: impl FnOnce(&mut egui::Ui, egui::Rect) -> R,+ ) -> egui::scroll_area::ScrollAreaOutput<R> {+ ui.scope_builder(egui::UiBuilder::new().scope_id(id), |ui| scroll.show_viewport(ui, draw)).inner+ }++ /// Run a push button's action (the ones that need no JavaScript engine).+ pub(super) fn run_button(app: &mut PdfCraftApp, index: usize, name: &str, action: pdfcraft_engine::form_scripts::ButtonAction) {+ use pdfcraft_engine::form_scripts::ButtonAction as B;+ let pages = app.session.get(app.views[index].id).map_or(0, |d| d.info.pages.len());+ match action {+ B::Reset { fields, exclude } => {+ let all: Vec<String> = app.session.get(app.views[index].id).map(|d| d.form.iter().map(|f| f.name.clone()).collect()).unwrap_or_default();+ let listed = |n: &String| fields.iter().any(|f| n == f || n.starts_with(&format!("{f}.")));+ let names = match (fields.is_empty(), exclude) {+ (true, _) => None,+ (false, false) => Some(all.iter().filter(|n| listed(n)).cloned().collect()),+ (false, true) => Some(all.iter().filter(|n| !listed(n)).cloned().collect()),+ };+ app.views[index].forms.focus = None;+ app.views[index].pending_edit = Some(pdfcraft_engine::Edit::ResetForm { names });+ }+ B::Named(n) => match n.as_str() {+ "Print" => app.open_print(),+ // What PdfCraft's XFA buttons use, and what a script's `execMenuItem("Save")`+ // does too: the Save As dialog, so a click never overwrites the file unasked.+ "SaveAs" => app.run_command("file.save_as"),+ "NextPage" => app.views[index].step_page(true),+ "PrevPage" => app.views[index].step_page(false),+ "FirstPage" => app.views[index].go_to_page(0),+ "LastPage" => app.views[index].go_to_page(pages.saturating_sub(1)),+ other => app.notify_fmt("{name}: the {other} action isn't supported yet", &[("name", name), ("other", other)]),+ },+ B::Uri(u) => app.request_document_url(&u, crate::LinkOrigin::Button),+ B::GoTo(p) => app.views[index].go_to_page(p.min(pages.saturating_sub(1))),+ B::ShowHide { fields, hide } => {+ let listed = |n: &String| fields.iter().any(|f| n == f || n.starts_with(&format!("{f}.")));+ // `display.hidden` 1, `display.visible` 0, as a script setting `field.display` would.+ let changes: Vec<pdfcraft_engine::FieldChange> = app+ .session+ .get(app.views[index].id)+ .map(|d| d.form.iter().filter(|f| listed(&f.name)).map(|f| f.name.clone()).collect::<Vec<_>>())+ .unwrap_or_default()+ .into_iter()+ .map(|name| pdfcraft_engine::FieldChange {+ name,+ value: None,+ read_only: None,+ required: None,+ display: Some(if hide { 1 } else { 0 }),+ })+ .collect();+ if !changes.is_empty() {+ let label = if hide { "Hide a field" } else { "Show a field" };+ app.views[index].pending_edit =+ Some(pdfcraft_engine::Edit::Batch { label: label.into(), edits: vec![pdfcraft_engine::Edit::ApplyScriptChanges { changes }] });+ }+ }+ B::SetLayers { changes, preserve_rb } => {+ use pdfcraft_engine::form_scripts::LayerOp as Op;+ let changes: Vec<(LayerOp, (u32, u16))> = changes+ .into_iter()+ .map(|(op, ocg)| {+ let op = match op {+ Op::On => LayerOp::On,+ Op::Off => LayerOp::Off,+ Op::Toggle => LayerOp::Toggle,+ };+ (op, ocg)+ })+ .collect();+ set_layers(app, index, &changes, preserve_rb);+ }+ B::Alert(m) => app.notify(m),+ B::Submit(url) => app.notify_fmt(+ "{name} submits the form to {url}; PdfCraft doesn't send form data. Save the document to keep your entries.",+ &[("name", name), ("url", &url)],+ ),+ B::ImportIcon => app.choose_field_image(name),+ B::Script(js) => {+ let id = app.views[index].id;+ app.run_button_script(id, name, &js);+ }+ }+ }++ /// Run a set-layer-visibility action from a button or link. It changes what is shown, as the+ /// Layers panel does (which follows), not the document.+ pub(super) fn set_layers(app: &mut PdfCraftApp, index: usize, changes: &[(LayerOp, (u32, u16))], preserve_rb: bool) {+ let id = app.views[index].id;+ if app.session.set_layer_state(id, changes, preserve_rb) {+ app.views[index].invalidate_content();+ }+ }++ /// Where a pinch or ⌘-scroll zooms the view about: the pointer, wherever it is over the view. Not+ /// page input: it is read before the pages' widget exists, once `rect_contains_pointer` has found+ /// the view under the pointer.+ pub(super) fn zoom_anchor(ui: &egui::Ui) -> Option<Pos2> {+ ui.input(|i| i.pointer.hover_pos())+ }++ /// The pointer and frame time that scroll the view while a comment is drawn. Not page input: it is+ /// read before the pages' widget exists, and the pointer may be past the view's edge.+ pub(super) fn drawing_edge_pointer(ui: &egui::Ui) -> (Option<Pos2>, f32) {+ ui.input(|i| (i.pointer.latest_pos(), i.stable_dt))+ }++ /// A press anywhere, or a key, stops the touchpad's glide (#531).+ pub(super) fn glide_interrupted(ui: &egui::Ui) -> bool {+ ui.input(|i| i.pointer.any_pressed() || i.events.iter().any(|e| matches!(e, egui::Event::Key { pressed: true, .. })))+ }++ /// Full screen's click on the document, which turns the page: a primary click this frame with the+ /// view on top under it in `area`. Not page input: it is read before the pages' widget exists, and+ /// the turn waits until the pages have had the click.+ pub(super) fn presentation_click(ui: &egui::Ui, area: Rect) -> bool {+ ui.rect_contains_pointer(area) && ui.input(|i| i.pointer.primary_clicked())+ }diff --cc crates/ui-egui/src/canvas/crop.rsindex 9e0d69b26,403209291..dd88db1a1--- a/crates/ui-egui/src/canvas/crop.rs+++ b/crates/ui-egui/src/canvas/crop.rs@@@ -19,20 -18,21 +19,21 @@@ fn to_user(xf: &PageXform, info: &DocIn}/// Crop gestures on one page. Returns `Some(true)` to open Set Page Boxes for this page.- #[allow(clippy::too_many_arguments)]- pub(crate) fn page_input(- ui: &egui::Ui,- resp: &egui::Response,- xf: &PageXform,- ptr: &PagePointer,- page: usize,- info: &DocInfo,- view: &mut DocView,- allowed: bool,- ) -> bool {+ pub(crate) struct CropPageInput<'a> {+ pub(crate) resp: &'a egui::Response,+ pub(crate) xf: &'a PageXform,+ pub(crate) ptr: &'a PagePointer,+ pub(crate) page: usize,+ pub(crate) info: &'a DocInfo,+ pub(crate) view: &'a mut DocView,+ pub(crate) allowed: bool,+ }++ pub(crate) fn page_input(ui: &egui::Ui, input: CropPageInput<'_>) -> bool {+ let CropPageInput { resp, xf, ptr, page, info, view, allowed } = input;let (pointer, origin) = (ptr.pos, ptr.origin);if pointer.is_some_and(|p| xf.rect.contains(p)) {- ui.ctx().set_cursor_icon(if allowed { egui::CursorIcon::Crosshair } else { egui::CursorIcon::NotAllowed });+ view.cursor.claim(Layer::ToolArea, if allowed { egui::CursorIcon::Crosshair } else { egui::CursorIcon::NotAllowed });}if !allowed {return false;diff --cc crates/ui-egui/src/canvas/page_cursor.rsindex 9abfb7e99,000000000..d8ae61bc3mode 100644,000000..100644--- a/crates/ui-egui/src/canvas/page_cursor.rs+++ b/crates/ui-egui/src/canvas/page_cursor.rs@@@ -1,332 -1,0 +1,332 @@@+//! The cursor the pages show, and the tip beside it, set once a frame.+//!+//! A page module claims the cursor for what it has under the pointer, on a [`Layer`], and never+//! sets egui's cursor itself: where each module set it, the last write of a frame won, so the+//! order of the per-page chain decided the cursor and not what a press there does. A link's hand+//! showed over every tool though only the Select tool follows links, and the I-beam of the text+//! under a comment hid that a drag there moves the comment. `canvas::document_area` sets the+//! cursor once, from the claim on the highest layer the active tool reaches. The tip beside it is+//! that claim's own (a link's target, so only where a press follows the link), or else what lies+//! under the pointer says (a comment, or a signature's validation badge), with any tool, as- //! Acrobat shows a comment's tooltip. A test in `page_pointer.rs` keeps page modules from setting- //! the cursor.++//! Acrobat shows a comment's tooltip. A test in `page_pointer/tests.rs` keeps page modules from++//! setting the cursor.++use egui::CursorIcon;++use crate::QuickTool;++/// What a claim is for, from the bottom up: a claim on a higher layer wins.+#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]+pub(crate) enum Layer {+ /// The page under the active tool: the crosshair it places or draws with, its I-beam or hand.+ ToolArea,+ /// The page's text, to select, and Edit text's paragraphs.+ Text,+ /// Links.+ Link,+ /// Comments: notes, shapes and markup.+ Comment,+ /// Form fields.+ Field,+ /// What a drag moves whole: signatures and Fill & Sign's marks, added text and images,+ /// selected objects, pictures in Edit text.+ Placed,+ /// The grips of the selected item: resize, rewrap and crop handles, paragraph edges.+ Handle,+ /// An open editor: a paragraph being typed in, a picture being cropped.+ Editor,+ /// A drag in progress: what is dragged keeps its cursor until the release.+ Drag,+}++/// Every layer, bottom first.+const LAYERS: [Layer; 9] =+ [Layer::ToolArea, Layer::Text, Layer::Link, Layer::Comment, Layer::Field, Layer::Placed, Layer::Handle, Layer::Editor, Layer::Drag];++impl Layer {+ /// Whether a press with `tool` acts on what lies on this layer, so that the layer's claims+ /// count. Only the Select tool follows links (the Link tool edits them) and picks up+ /// comments: every other tool draws, places or selects text over them. The other layers are+ /// claimed only by the modules of the tools that act on them, so they count for every tool.+ pub(crate) fn reached_by(self, tool: QuickTool) -> bool {+ match self {+ Layer::Link => matches!(tool, QuickTool::Select | QuickTool::Link),+ Layer::Comment => tool == QuickTool::Select,+ Layer::ToolArea | Layer::Text | Layer::Field | Layer::Placed | Layer::Handle | Layer::Editor | Layer::Drag => true,+ }+ }+}++/// A claim on the cursor: the icon, and the tip that goes with it (a link's target).+#[derive(Clone, Debug, PartialEq)]+struct Claim {+ icon: CursorIcon,+ tip: Option<String>,+}++/// What a description tells about, from the least up: a higher one shows over a lower one.+#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]+pub(crate) enum Subject {+ /// A signature's validation badge: viewer chrome over the signer's own artwork.+ SignatureBadge,+ /// A comment: who wrote it, and what it says.+ Comment,+}++/// What the page modules claim for the cursor this frame. `canvas::document_area` sets the+/// cursor from it once, after the pages ([`PageCursor::resolve`]).+#[derive(Debug, Default)]+pub(crate) struct PageCursor {+ /// The last claim on each layer, bottom layer first.+ claims: [Option<Claim>; LAYERS.len()],+ /// What lies under the pointer says ([`PageCursor::describe`]).+ description: Option<(Subject, String)>,+}++impl PageCursor {+ /// Shows `icon` while the pointer is over what lies on `layer`, unless the active tool+ /// reaches a higher layer that is claimed too.+ pub(crate) fn claim(&mut self, layer: Layer, icon: CursorIcon) {+ self.claim_with_tip(layer, icon, None);+ }++ /// As [`Self::claim`], with `tip` beside the pointer where the claim wins.+ pub(crate) fn claim_with_tip(&mut self, layer: Layer, icon: CursorIcon, tip: Option<String>) {+ if let Some(slot) = self.claims.get_mut(layer as usize) {+ *slot = Some(Claim { icon, tip });+ }+ }++ /// Says what lies under the pointer without claiming the cursor: the tip shows with any tool,+ /// beside that tool's cursor, as Acrobat shows a comment's tooltip, unless the winning claim+ /// has a tip of its own. The description of the highest subject stands, and the last of+ /// equals (the topmost of overlapping badges).+ pub(crate) fn describe(&mut self, subject: Subject, text: String) {+ if self.description.as_ref().is_none_or(|(held, _)| *held <= subject) {+ self.description = Some((subject, text));+ }+ }++ /// The claim on the highest layer `tool` reaches.+ fn winner(claims: [Option<Claim>; LAYERS.len()], tool: QuickTool) -> Option<Claim> {+ LAYERS.into_iter().zip(claims).rev().find_map(|(layer, claim)| claim.filter(|_| layer.reached_by(tool)))+ }++ /// Sets the cursor, once, to the icon of the claim on the highest layer `tool` reaches, and+ /// returns the tip: that claim's own, or else the description. With no such claim the cursor+ /// is left as it is. The claims are spent: the next frame starts with none.+ pub(crate) fn resolve(&mut self, ctx: &egui::Context, tool: QuickTool) -> Option<String> {+ let PageCursor { claims, description } = std::mem::take(self);+ let winner = Self::winner(claims, tool);+ if let Some(w) = &winner {+ ctx.set_cursor_icon(w.icon);+ }+ winner.and_then(|w| w.tip).or(description.map(|(_, text)| text))+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::comments::CommentTool;+ use crate::fill_sign::FillTool;+ use crate::prepare::FieldTool;++ /// One of each tool. The match stops compiling when a tool is added, so that it gets a row+ /// in [`Layer::reached_by`]'s tests.+ fn tools() -> Vec<QuickTool> {+ let tools = vec![+ QuickTool::Select,+ QuickTool::Hand,+ QuickTool::Comment(CommentTool::Rectangle),+ QuickTool::Comment(CommentTool::Highlight),+ QuickTool::Measure(crate::measure_ui::Tool::Distance),+ QuickTool::Crop,+ QuickTool::EnhanceCamera,+ QuickTool::Fill(FillTool::Signature),+ QuickTool::Field(FieldTool::Text),+ QuickTool::Redact,+ QuickTool::AddText,+ QuickTool::EditText,+ QuickTool::Stamp(pdfcraft_engine::StampKind::DynApproved),+ QuickTool::CustomStamp(0),+ QuickTool::Link,+ QuickTool::SignArea { certify: false },+ QuickTool::MarqueeZoom,+ QuickTool::Snapshot,+ QuickTool::ColumnSelect,+ ];+ for tool in &tools {+ match tool {+ QuickTool::Select+ | QuickTool::Hand+ | QuickTool::Comment(_)+ | QuickTool::Measure(_)+ | QuickTool::Crop+ | QuickTool::EnhanceCamera+ | QuickTool::Fill(_)+ | QuickTool::Field(_)+ | QuickTool::Redact+ | QuickTool::AddText+ | QuickTool::EditText+ | QuickTool::Stamp(_)+ | QuickTool::CustomStamp(_)+ | QuickTool::Link+ | QuickTool::SignArea { .. }+ | QuickTool::MarqueeZoom+ | QuickTool::Snapshot+ | QuickTool::ColumnSelect => {}+ }+ }+ tools+ }++ #[test]+ fn layers_are_listed_bottom_first_in_their_order() {+ for (i, layer) in LAYERS.into_iter().enumerate() {+ assert_eq!(layer as usize, i, "{layer:?}");+ }+ assert!(LAYERS.windows(2).all(|w| w[0] < w[1]));+ }++ #[test]+ fn links_count_for_the_select_and_link_tools_only() {+ for tool in tools() {+ assert_eq!(Layer::Link.reached_by(tool), matches!(tool, QuickTool::Select | QuickTool::Link), "{tool:?}");+ }+ }++ #[test]+ fn comments_count_for_the_select_tool_only() {+ for tool in tools() {+ assert_eq!(Layer::Comment.reached_by(tool), tool == QuickTool::Select, "{tool:?}");+ }+ }++ #[test]+ fn the_other_layers_count_for_every_tool() {+ for tool in tools() {+ for layer in [Layer::ToolArea, Layer::Text, Layer::Field, Layer::Placed, Layer::Handle, Layer::Editor, Layer::Drag] {+ assert!(layer.reached_by(tool), "{layer:?} for {tool:?}");+ }+ }+ }++ fn claims(claims: &[(Layer, CursorIcon, Option<&str>)]) -> PageCursor {+ let mut cursor = PageCursor::default();+ for (layer, icon, tip) in claims {+ cursor.claim_with_tip(*layer, *icon, tip.map(str::to_string));+ }+ cursor+ }++ fn winner(cursor: PageCursor, tool: QuickTool) -> Option<Claim> {+ PageCursor::winner(cursor.claims, tool)+ }++ #[test]+ fn the_highest_layer_the_tool_reaches_wins_with_its_tip() {+ let on_text_under_a_link = [(Layer::Text, CursorIcon::Text, None), (Layer::Link, CursorIcon::PointingHand, Some("https://example.org/"))];+ let select = winner(claims(&on_text_under_a_link), QuickTool::Select);+ assert_eq!(select, Some(Claim { icon: CursorIcon::PointingHand, tip: Some("https://example.org/".into()) }));+ // A markup tool selects the text there, and the link's tip goes with its hand.+ let highlight = winner(claims(&on_text_under_a_link), QuickTool::Comment(CommentTool::Highlight));+ assert_eq!(highlight, Some(Claim { icon: CursorIcon::Text, tip: None }));+ // A tool reaching nothing claimed leaves the cursor alone.+ assert_eq!(winner(claims(&[(Layer::Link, CursorIcon::PointingHand, None)]), QuickTool::Hand), None);+ }++ #[test]+ fn a_higher_claim_without_a_tip_hides_a_lower_ones_tip() {+ let field_over_a_link = [(Layer::Link, CursorIcon::PointingHand, Some("Go to page 2")), (Layer::Field, CursorIcon::Text, None)];+ assert_eq!(winner(claims(&field_over_a_link), QuickTool::Select), Some(Claim { icon: CursorIcon::Text, tip: None }));+ }++ #[test]+ fn the_last_claim_on_a_layer_wins() {+ let two_links = [(Layer::Link, CursorIcon::PointingHand, Some("first")), (Layer::Link, CursorIcon::PointingHand, Some("second"))];+ assert_eq!(winner(claims(&two_links), QuickTool::Select).and_then(|c| c.tip).as_deref(), Some("second"));+ }++ /// Runs one frame that sets the cursor to `before`, if any, then resolves `claims` for+ /// `tool`. Returns the frame's cursor and the tip.+ fn frame(ctx: &egui::Context, before: Option<CursorIcon>, claims: &mut PageCursor, tool: QuickTool) -> (CursorIcon, Option<String>) {+ let mut tip = None;+ let mut output = ctx.run_ui(egui::RawInput::default(), |ui| {+ if let Some(icon) = before {+ ui.ctx().set_cursor_icon(icon);+ }+ tip = claims.resolve(ui.ctx(), tool);+ });+ // An input-only test has no renderer to take the font texture.+ output.textures_delta.clear();+ (output.platform_output.cursor_icon, tip)+ }++ #[test]+ fn resolve_sets_the_winners_cursor_and_spends_the_claims() {+ let ctx = egui::Context::default();+ let on_a_link = || claims(&[(Layer::ToolArea, CursorIcon::Crosshair, None), (Layer::Link, CursorIcon::PointingHand, Some("tip"))]);+ assert_eq!(frame(&ctx, None, &mut on_a_link(), QuickTool::Select), (CursorIcon::PointingHand, Some("tip".into())));+ let stamp = QuickTool::Stamp(pdfcraft_engine::StampKind::DynApproved);+ assert_eq!(frame(&ctx, None, &mut on_a_link(), stamp), (CursorIcon::Crosshair, None), "the stamp's crosshair, and no link tip");+ // Nothing the tool reaches: the cursor stays as the frame set it.+ let mut only_a_link = claims(&[(Layer::Link, CursorIcon::PointingHand, Some("tip"))]);+ only_a_link.describe(Subject::Comment, "Ana".into());+ assert_eq!(frame(&ctx, Some(CursorIcon::Help), &mut only_a_link, QuickTool::Hand), (CursorIcon::Help, Some("Ana".into())));+ // Resolving spends the claims, reached or not, and the description.+ assert_eq!(only_a_link.description, None);+ assert_eq!(winner(only_a_link, QuickTool::Select), None);+ }++ #[test]+ fn a_description_shows_with_any_tool_unless_the_winner_has_a_tip_of_its_own() {+ let ctx = egui::Context::default();+ let stamp = QuickTool::Stamp(pdfcraft_engine::StampKind::DynApproved);+ let link = (Layer::Link, CursorIcon::PointingHand, Some("https://example.org/"));+ let described = |claimed: &[(Layer, CursorIcon, Option<&str>)]| {+ let mut cursor = claims(claimed);+ cursor.describe(Subject::Comment, "Ana\nCheck this".into());+ cursor+ };+ let comment = Some("Ana\nCheck this".to_string());+ // A comment under the stamp's crosshair: the tool's cursor, and what the comment says.+ let crosshair = (Layer::ToolArea, CursorIcon::Crosshair, None);+ assert_eq!(frame(&ctx, None, &mut described(&[crosshair]), stamp), (CursorIcon::Crosshair, comment.clone()));+ // A link the tool follows speaks for itself; one it doesn't keeps its tip to itself.+ assert_eq!(+ frame(&ctx, None, &mut described(&[crosshair, link]), QuickTool::Select),+ (CursorIcon::PointingHand, Some("https://example.org/".into()))+ );+ assert_eq!(frame(&ctx, None, &mut described(&[crosshair, link]), stamp), (CursorIcon::Crosshair, comment.clone()));+ // A winner without a tip of its own, such as the Select tool's comment claim.+ let picked_up = (Layer::Comment, CursorIcon::Move, None);+ assert_eq!(frame(&ctx, None, &mut described(&[link, picked_up]), QuickTool::Select), (CursorIcon::Move, comment));+ }++ #[test]+ fn a_comment_says_more_than_a_signature_badge_and_the_last_badge_stands() {+ let badge_then_comment = {+ let mut cursor = PageCursor::default();+ cursor.describe(Subject::SignatureBadge, "Signature is valid".into());+ cursor.describe(Subject::Comment, "Ana".into());+ cursor+ };+ let comment_then_badges = {+ let mut cursor = PageCursor::default();+ cursor.describe(Subject::Comment, "Ana".into());+ cursor.describe(Subject::SignatureBadge, "Signature is valid".into());+ cursor+ };+ let two_badges = {+ let mut cursor = PageCursor::default();+ cursor.describe(Subject::SignatureBadge, "Signature is valid".into());+ cursor.describe(Subject::SignatureBadge, "Signature is invalid".into());+ cursor+ };+ let said = |cursor: PageCursor| cursor.description.map(|(_, text)| text);+ assert_eq!(said(badge_then_comment).as_deref(), Some("Ana"));+ assert_eq!(said(comment_then_badges).as_deref(), Some("Ana"), "whichever came first");+ assert_eq!(said(two_badges).as_deref(), Some("Signature is invalid"), "the badge painted last is on top");+ }+}diff --cc crates/ui-egui/src/canvas/page_pointer/tests.rsindex 000000000,29630b715..b405832abmode 000000,100644..100644--- a/crates/ui-egui/src/canvas/page_pointer/tests.rs+++ b/crates/ui-egui/src/canvas/page_pointer/tests.rs@@@ -1,0 -1,324 +1,363 @@@+ use super::*;+ use egui::{Context, Modifiers, Sense, TouchDeviceId, TouchId, TouchPhase, pos2, vec2};++ /// The pages' widget: x 0..200, y 0..200 of a 400×400 screen.+ const PAGES: Rect = Rect { min: Pos2::ZERO, max: Pos2 { x: 200.0, y: 200.0 } };+ /// An Area drawn over the pages' lower right corner.+ const OVER: Rect = Rect { min: Pos2 { x: 120.0, y: 120.0 }, max: Pos2 { x: 260.0, y: 260.0 } };++ fn button(pos: Pos2, button: PointerButton, pressed: bool) -> Event {+ Event::PointerButton { pos, button, pressed, modifiers: Modifiers::NONE }+ }++ fn touch(phase: TouchPhase, pos: Pos2) -> Event {+ Event::Touch { device_id: TouchDeviceId(1), id: TouchId(1), phase, pos, force: None }+ }++ /// Runs one frame of the pages' widget (and the Area over it, with `area`) and returns what+ /// the pages see.+ fn frame(ctx: &Context, events: Vec<Event>, area: bool) -> PagePointer {+ frame_with(ctx, events, area, false)+ }++ /// [`frame`], with a dialog open (`modal`) whose layer egui has not met.+ fn frame_with(ctx: &Context, events: Vec<Event>, area: bool, modal: bool) -> PagePointer {+ let mut seen = PagePointer::default();+ let input = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(400.0, 400.0))), events, ..Default::default() };+ let mut output = ctx.run_ui(input, |ui| {+ let (_, resp) = ui.allocate_exact_size(PAGES.size(), Sense::click_and_drag());+ seen = PagePointer::read(ui, &resp, modal);+ if area {+ egui::Area::new(egui::Id::unique("over")).fixed_pos(OVER.min).show(ui.ctx(), |ui| {+ ui.allocate_exact_size(OVER.size(), Sense::hover());+ });+ }+ });+ // An input-only test has no renderer to take the font texture.+ output.textures_delta.clear();+ seen+ }++ #[test]+ fn a_touch_tap_keeps_its_position_on_the_frame_it_lifts() {+ let ctx = Context::default();+ let p = pos2(50.0, 60.0);+ frame(&ctx, vec![], false);+ let down = frame(&ctx, vec![touch(TouchPhase::Start, p), Event::PointerMoved(p), button(p, PointerButton::Primary, true)], false);+ assert_eq!((down.pos, down.origin, down.pressed()), (Some(p), Some(p), Some(p)));+ // egui-winit ends a touch with the release and `PointerGone` in one frame.+ let up = frame(&ctx, vec![touch(TouchPhase::End, p), button(p, PointerButton::Primary, false), Event::PointerGone], false);+ assert_eq!(ctx.input(|i| i.pointer.hover_pos()), None, "egui's hover position is gone");+ assert_eq!(up.pos, Some(p), "the pages still know where the finger lifted");+ assert_eq!(up.edges, [Edge::Release(p)]);+ assert_eq!(frame(&ctx, vec![], false), PagePointer::default(), "and forget it the frame after");+ }++ #[test]+ fn a_press_and_release_in_one_frame_keep_the_press() {+ let ctx = Context::default();+ let p = pos2(50.0, 60.0);+ frame(&ctx, vec![Event::PointerMoved(p)], false);+ let click = frame(&ctx, vec![button(p, PointerButton::Primary, true), button(p, PointerButton::Primary, false)], false);+ assert_eq!(ctx.input(|i| i.pointer.press_origin()), None, "egui has forgotten the press");+ assert_eq!(click.origin, Some(p));+ assert_eq!(click.edges, [Edge::Press(p), Edge::Release(p)]);+ }++ #[test]+ fn something_drawn_over_the_pages_hides_the_pointer() {+ let ctx = Context::default();+ // The Area and the widget rects egui hit-tests against come from the frame before.+ frame(&ctx, vec![], true);+ frame(&ctx, vec![], true);+ let beside = pos2(100.0, 100.0);+ assert_eq!(frame(&ctx, vec![Event::PointerMoved(beside)], true).pos, Some(beside));+ // Inside the Area, and just inside its edge where egui's interact radius still finds the+ // pages' widget.+ for p in [pos2(160.0, 160.0), pos2(122.0, 150.0)] {+ assert_eq!(frame(&ctx, vec![Event::PointerMoved(p)], true).pos, None, "{p:?}");+ }+ // Off the pages altogether.+ assert_eq!(frame(&ctx, vec![Event::PointerMoved(pos2(300.0, 50.0))], true).pos, None);+ // A press on the Area is not the pages' press, though the button is down all the same.+ let p = pos2(160.0, 160.0);+ let press = frame(&ctx, vec![button(p, PointerButton::Primary, true)], true);+ assert_eq!(press, PagePointer { primary_down: true, any_down: true, ..PagePointer::default() });+ }++ #[test]+ fn a_press_on_the_pages_keeps_the_pointer_until_its_release() {+ let ctx = Context::default();+ frame(&ctx, vec![], true);+ frame(&ctx, vec![], true);+ let start = pos2(40.0, 40.0);+ frame(&ctx, vec![Event::PointerMoved(start), button(start, PointerButton::Primary, true)], true);+ // Dragged over the Area and off the pages: still theirs.+ for p in [pos2(160.0, 160.0), pos2(300.0, 50.0)] {+ let held = frame(&ctx, vec![Event::PointerMoved(p)], true);+ assert_eq!((held.pos, held.origin, held.primary_down), (Some(p), Some(start), true), "{p:?}");+ }+ let end = pos2(300.0, 60.0);+ let up = frame(&ctx, vec![Event::PointerMoved(end), button(end, PointerButton::Primary, false)], true);+ assert_eq!((up.pos, up.edges.as_slice()), (Some(end), [Edge::Release(end)].as_slice()), "the release is the pages' too");+ assert!(!up.primary_down && !up.any_down, "and the button is up");+ assert_eq!(frame(&ctx, vec![], true).pos, None, "then off the pages, the pointer is not theirs");+ }++ #[test]+ fn a_dialog_hides_the_pointer_and_its_clicks_but_not_a_drag_the_pages_have() {+ let ctx = Context::default();+ let p = pos2(50.0, 50.0);+ frame(&ctx, vec![Event::PointerMoved(p)], false);+ assert_eq!(frame(&ctx, vec![], false).pos, Some(p));+ assert_eq!(frame_with(&ctx, vec![], false, true).pos, None, "no pointer under a dialog, before egui knows its layer too");+ let click = frame_with(&ctx, vec![button(p, PointerButton::Primary, true), button(p, PointerButton::Primary, false)], false, true);+ assert_eq!((click.pos, click.origin, click.edges.as_slice()), (None, None, [].as_slice()), "nor a click egui gives the pages then");+ // A drag the pages already have when a dialog opens goes on until its release.+ frame(&ctx, vec![button(p, PointerButton::Primary, true)], false);+ frame(&ctx, vec![Event::PointerMoved(pos2(80.0, 50.0))], false);+ let q = pos2(110.0, 50.0);+ let dragging = frame_with(&ctx, vec![Event::PointerMoved(q)], false, true);+ assert_eq!((dragging.pos, dragging.origin), (Some(q), Some(p)), "a drag the pages have keeps its pointer under a dialog");+ let up = frame_with(&ctx, vec![button(q, PointerButton::Primary, false)], false, true);+ assert_eq!(up.edges.as_slice(), [Edge::Release(q)].as_slice(), "and its release");+ }++ #[test]+ fn a_secondary_press_is_some_button_down_but_no_primary_edge() {+ let ctx = Context::default();+ let p = pos2(50.0, 60.0);+ frame(&ctx, vec![Event::PointerMoved(p)], false);+ let right = frame(&ctx, vec![button(p, PointerButton::Secondary, true)], false);+ assert_eq!((right.pos, right.any_down, right.primary_down, right.edges.len()), (Some(p), true, false, 0));+ }++ #[test]+ fn edges_are_primary_finite_in_order_and_capped() {+ let p = pos2(1.0, 2.0);+ let q = pos2(3.0, 4.0);+ let events = vec![+ button(p, PointerButton::Secondary, true),+ button(p, PointerButton::Primary, true),+ Event::PointerMoved(q),+ button(pos2(f32::NAN, 0.0), PointerButton::Primary, false),+ button(q, PointerButton::Primary, false),+ ];+ assert_eq!(edges(&events), [Edge::Press(p), Edge::Release(q)]);+ let many: Vec<Event> = (0..100).map(|i| button(p, PointerButton::Primary, i % 2 == 0)).collect();+ assert_eq!(edges(&many).len(), MAX_EDGES);+ assert_eq!(first_press(&[Edge::Release(q), Edge::Press(p), Edge::Press(q)]), Some(p));+ }++ /// The page modules: the per-page chain in `canvas::document_area` and what it calls.+ const PAGE_MODULES: [&str; 35] = [+ "canvas.rs",+ "canvas/area.rs",+ "canvas/bars.rs",+ "canvas/cache.rs",+ "canvas/find.rs",+ "canvas/navigation.rs",+ "canvas/organize.rs",+ "canvas/selection.rs",+ "canvas/xform.rs",+ "canvas/zoom.rs",+ "tools/comments.rs",+ "tools/comments/composer.rs",+ "tools/comments/geometry.rs",+ "tools/comments/input.rs",+ "tools/comments/menu.rs",+ "tools/comments/paint.rs",+ "tools/comments/state.rs",+ "tools/forms_ui.rs",+ "tools/prepare.rs",+ "tools/fill_sign.rs",+ "tools/fill_sign/scan.rs",+ "tools/sign_ui.rs",+ "canvas/crop.rs",+ "canvas/zoom_snap.rs",+ "tools/camera_ui.rs",+ "tools/measure_ui.rs",+ "tools/redact_ui.rs",+ "tools/link_ui.rs",+ "tools/content_ui.rs",+ "tools/edit_text_ui.rs",+ "tools/edit_text_ui/image.rs",+ "tools/object_ui.rs",+ "canvas/image_pick.rs",+ "canvas/signature_drag.rs",+ "tools/calc_order_ui.rs",+ ];++ /// egui's raw pointer state: where the pointer is, and which buttons are down or went down.+ const RAW_READS: [&str; 21] = [+ "hover_pos()",+ "interact_pos()",+ "latest_pos()",+ "press_origin()",+ "pointer_hover_pos()",+ "pointer_interact_pos()",+ "pointer_latest_pos()",+ "primary_down()",+ "primary_pressed()",+ "primary_released()",+ "primary_clicked()",+ "any_down()",+ "any_pressed()",+ "any_released()",+ "any_click()",+ // These take the button, so they match up to the parenthesis.+ "button_down(",+ "button_pressed(",+ "button_released(",+ "button_clicked(",+ "button_double_clicked(",+ "button_triple_clicked(",+ ];++ /// Functions in the page modules that are not page input and read egui's pointer state+ /// themselves: (file, function, why).+ const NOT_PAGE_INPUT: [(&str, &str, &str); 11] = [+ ("canvas/area.rs", "zoom_anchor", "a pinch zooms the whole view, and is read before the pages' widget exists"),+ ("canvas/area.rs", "drawing_edge_pointer", "scrolls the view at its edges, read before the pages' widget exists"),+ ("canvas/area.rs", "glide_interrupted", "a press anywhere stops the touchpad's glide"),+ ("canvas/area.rs", "presentation_click", "full screen's click to turn the page, read before the pages' widget exists"),+ ("canvas/bars.rs", "page_size_hint", "the page size hint sits in the view's corner, not on a page"),+ ("canvas/organize.rs", "organize_grid", "Organize Pages shows thumbnails, not pages"),+ ("tools/comments/input.rs", "keys", "keyboard handling after the pages: a drag cancelled with Escape ends once no button is down"),+ ("tools/forms_ui.rs", "overlay", "the field editor is an Area of its own over the page"),+ ("tools/content_ui.rs", "editor", "the added-text editor is an Area of its own over the page"),+ ("tools/edit_text_ui.rs", "overlay", "the paragraph editor is an Area of its own over the page"),+ ("tools/fill_sign/scan.rs", "scan_tab", "the signature dialog's Scan tab"),+ ];++ /// The function a `fn` line declares, laid out as rustfmt does (`pub`, `const` and the like+ /// before `fn`).+ fn declares(line: &str) -> Option<&str> {+ let mut rest = line;+ loop {+ let before = rest;+ for prefix in ["pub(crate) ", "pub(super) ", "pub ", "const ", "async ", "unsafe "] {+ rest = rest.strip_prefix(prefix).unwrap_or(rest);+ }+ if rest == before {+ break;+ }+ }+ let rest = rest.strip_prefix("fn ")?;+ rest.find(|c: char| !(c.is_alphanumeric() || c == '_')).map(|end| &rest[..end])+ }+-/// Whether `line` calls `read`, and not a longer name that ends in it.-fn reads(line: &str, read: &str) -> bool {- line.match_indices(read).any(|(at, _)| !line[..at].ends_with(|c: char| c.is_alphanumeric() || c == '_'))++/// Ways to set egui's cursor.++const CURSOR_WRITES: [&str; 4] = ["set_cursor_icon(", ".cursor_icon = ", "on_hover_cursor(", "on_hover_and_drag_cursor("];++++/// Functions in the page modules that set a cursor other than the pages': (file, function, why).++const NOT_PAGE_CURSOR: [(&str, &str, &str); 3] = [++ ("tools/fill_sign/scan.rs", "scan_tab", "the signature dialog's Scan tab"),++ ("tools/edit_text_ui.rs", "overlay", "the paragraph editor is an Area of its own over the page, drawn after the pages' cursor is set"),++ ("tools/calc_order_ui.rs", "panel", "the Calculation order panel, whose rows are dragged to reorder them"),++];++++/// Whether `line` uses `name`, and not a longer name that ends in it (a field, after its `.`, is++/// never part of a longer name).++fn uses(line: &str, name: &str) -> bool {++ line.match_indices(name).any(|(at, _)| name.starts_with('.') || !line[..at].ends_with(|c: char| c.is_alphanumeric() || c == '_'))+ }+-/// Page modules read the pointer only through `PagePointer`. egui's raw state misses what is-/// drawn over the pages and where a touch lifted, so a raw read in a page module brings back-/// the bugs `PagePointer` fixed: a cursor or a press through a dialog, a tap that does nothing.-#[test]-fn page_modules_read_the_pointer_only_through_page_pointer() {++/// Each use of one of `names` in the page modules' code (their tests left out) outside the++/// functions `allowed` to, as "src/file:line: `name` why"; then each allowed function that uses++/// none of them any more, as "src/file: fn function unused".++fn misuses(names: &[&str], allowed: &[(&str, &str, &str)], why: &str, unused: &str) -> Vec<String> {+ let src = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src");+ let mut problems = Vec::new();- let mut needed = vec![false; NOT_PAGE_INPUT.len()];++ let mut needed = vec![false; allowed.len()];+ for file in PAGE_MODULES {+ let source = std::fs::read_to_string(src.join(file)).expect("page module").replace("\r\n", "\n");- // Tests drive egui's input themselves.++ // Tests drive egui's input and read its output themselves.+ let code = source.split("#[cfg(test)]\nmod ").next().unwrap_or_default();+ // The top-level function, or method of an `impl`, that each line is in.+ let (mut function, mut in_impl) = (None, false);+ for (n, line) in code.lines().enumerate() {+ if line.starts_with("impl") {+ (function, in_impl) = (None, true);+ } else if line == "}" {+ (function, in_impl) = (None, false);+ } else if let Some(name) = declares(line).or_else(|| line.strip_prefix(" ").filter(|_| in_impl).and_then(declares)) {+ function = Some(name);+ }+ if line.trim_start().starts_with("//") {+ continue;+ }- for read in RAW_READS.into_iter().filter(|read| reads(line, read)) {- match NOT_PAGE_INPUT.iter().position(|(f, name, _)| *f == file && function == Some(*name)) {++ for name in names.iter().filter(|name| uses(line, name)) {++ match allowed.iter().position(|(f, function_name, _)| *f == file && function == Some(*function_name)) {+ Some(k) => needed[k] = true,- None => problems.push(format!(- "src/{file}:{}: `{read}` reads egui's pointer state in a page module. Read `PagePointer` \- (src/page_pointer.rs) instead: it knows what is drawn over the pages and where a touch \- lifted. Not page input? Add the function to NOT_PAGE_INPUT there, with why.",- n + 1- )),++ None => problems.push(format!("src/{file}:{}: `{name}` {why}", n + 1)),+ }+ }+ }+ }- for ((file, name, _), needed) in NOT_PAGE_INPUT.iter().zip(needed) {++ for ((file, name, _), needed) in allowed.iter().zip(needed) {+ if !needed {- problems.push(format!("src/{file}: fn {name} reads no pointer state any more: remove it from NOT_PAGE_INPUT."));++ problems.push(format!("src/{file}: fn {name} {unused}"));+ }+ }++ problems++}++++/// Page modules read the pointer only through `PagePointer`. egui's raw state misses what is++/// drawn over the pages and where a touch lifted, so a raw read in a page module brings back++/// the bugs `PagePointer` fixed: a cursor or a press through a dialog, a tap that does nothing.++#[test]++fn page_modules_read_the_pointer_only_through_page_pointer() {++ let src = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src");++ let mut problems = misuses(++ &RAW_READS,++ &NOT_PAGE_INPUT,++ "reads egui's pointer state in a page module. Read `PagePointer` (src/canvas/page_pointer.rs) instead: it \++ knows what is drawn over the pages and where a touch lifted. Not page input? Add the function to \++ NOT_PAGE_INPUT there, with why.",++ "reads no pointer state any more: remove it from NOT_PAGE_INPUT.",++ );+ // A module that takes the page pointer is a page module, so it is checked too.+ let mut dirs = vec![src.clone()];+ while let Some(dir) = dirs.pop() {+ for entry in std::fs::read_dir(dir).expect("source directory") {+ let path = entry.expect("source entry").path();+ // Tests drive egui's input themselves, in test modules and in test files.+ let stem = path.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default();+ if stem == "tests" || stem.ends_with("_tests") {+ continue;+ }+ if path.is_dir() {+ dirs.push(path);+ continue;+ }+ if path.extension().is_none_or(|ext| ext != "rs") {+ continue;+ }+ let file =+ path.strip_prefix(&src).expect("under src").components().map(|c| c.as_os_str().to_string_lossy()).collect::<Vec<_>>().join("/");+ let source = std::fs::read_to_string(&path).expect("source file");+ if file != "canvas/page_pointer.rs" && source.contains("PagePointer") && !PAGE_MODULES.contains(&file.as_str()) {+ problems.push(format!("src/{file} takes the page pointer: add it to PAGE_MODULES."));+ }+ }+ }+ assert!(problems.is_empty(), "{}", problems.join("\n"));+ }++++/// Page modules claim the cursor and never set it. Where each set it, the last write of a frame++/// won, so the order of the per-page chain decided the cursor and not what a press does: a++/// link's hand over every tool, the I-beam over a comment that a drag moves.++#[test]++fn page_modules_claim_the_cursor_and_never_set_it() {++ let problems = misuses(++ &CURSOR_WRITES,++ &NOT_PAGE_CURSOR,++ "sets the cursor in a page module, where the last write of a frame would win. Claim it instead, on the layer \++ of what is under the pointer (`view.cursor.claim`, src/canvas/page_cursor.rs): `document_area` sets it once, \++ from the claim on the highest layer the active tool reaches. Not the pages' cursor? Add the function to \++ NOT_PAGE_CURSOR in src/canvas/page_pointer/tests.rs, with why.",++ "sets no cursor any more: remove it from NOT_PAGE_CURSOR.",++ );++ assert!(problems.is_empty(), "{}", problems.join("\n"));++}diff --cc crates/ui-egui/src/canvas/tests.rsindex 000000000,01eba9b0b..634a88511mode 000000,100644..100644--- a/crates/ui-egui/src/canvas/tests.rs+++ b/crates/ui-egui/src/canvas/tests.rs@@@ -1,0 -1,2034 +1,2004 @@@+ #[test]+ fn zoom_anchor_scroll_stays_within_the_content() {+ let (content, viewport) = (vec2(1000.0, 2000.0), vec2(800.0, 600.0));+ // Past the end: clamped to the maximum (200, 1400), not left for egui to snap back.+ assert_eq!(anchored_scroll(pos2(900.0, 1900.0), vec2(0.0, 0.0), content, viewport), vec2(200.0, 1400.0));+ // Before the start.+ assert_eq!(anchored_scroll(pos2(10.0, 10.0), vec2(300.0, 300.0), content, viewport), Vec2::ZERO);+ // Inside: unchanged.+ assert_eq!(anchored_scroll(pos2(150.0, 800.0), vec2(100.0, 100.0), content, viewport), vec2(50.0, 700.0));+ // Content smaller than the viewport: no scrolling.+ assert_eq!(anchored_scroll(pos2(400.0, 400.0), Vec2::ZERO, vec2(500.0, 500.0), viewport), vec2(0.0, 0.0));+ }++ #[test]+ fn page_size_hint_zone_is_the_bottom_left_quadrant() {+ let area = Rect::from_min_max(pos2(100.0, 50.0), pos2(500.0, 450.0));+ assert!(in_size_hint_zone(area, pos2(110.0, 440.0)));+ assert!(!in_size_hint_zone(area, pos2(110.0, 100.0)), "top-left");+ assert!(!in_size_hint_zone(area, pos2(400.0, 440.0)), "bottom-right");+ assert!(!in_size_hint_zone(area, pos2(50.0, 440.0)), "outside");+ assert!(!in_size_hint_zone(area, pos2(f32::NAN, 440.0)));+ }++ use super::*;++ #[test]+ fn typed_zoom_percentages_parse() {+ for (typed, zoom) in [("150", 1.5), ("150%", 1.5), (" 62.5 % ", 0.625), ("6400%", 64.0)] {+ assert_eq!(DocView::parse_zoom_percent(typed), Some(zoom), "{typed}");+ }+ for typed in ["", "%", "abc", "0", "-50", "NaN", "inf", "1e40", "150%%x", "%150"] {+ assert_eq!(DocView::parse_zoom_percent(typed), None, "{typed}");+ }+ }++ /// A rotated (landscape) page is drawn as wide as the cell allows and centred in the picture+ /// area, as Acrobat draws it, not as a small strip pinned to the top; a portrait page still+ /// fills the area's height; neither covers the checkbox corner or the label below.+ #[test]+ fn grid_pages_are_centred_and_as_large_as_the_cell_allows() {+ let cell = Rect::from_min_size(pos2(100.0, 50.0), vec2(190.0, 282.0));+ let area = Rect::from_min_max(pos2(cell.left(), cell.top() + 16.0), pos2(cell.right(), cell.bottom() - 72.0));+ let checkbox = Rect::from_min_size(cell.min + vec2(8.0, 8.0), Vec2::splat(20.0));+ let landscape = grid_page_rect(cell, vec2(842.0, 595.0));+ assert!((landscape.center().y - area.center().y).abs() < 0.01, "centred vertically: {landscape:?}");+ assert!((landscape.center().x - cell.center().x).abs() < 0.01);+ assert!((landscape.width() - (cell.width() - 32.0)).abs() < 0.01, "as wide as the cell allows: {landscape:?}");+ assert!(!landscape.intersects(checkbox));+ let portrait = grid_page_rect(cell, vec2(595.0, 842.0));+ assert!(area.contains_rect(portrait), "inside the picture area: {portrait:?}");+ assert!((portrait.center().y - area.center().y).abs() < 0.01);+ assert!(portrait.left() >= checkbox.right(), "clear of the checkbox: {portrait:?}");+ // Degenerate sizes still give a finite rectangle inside the cell.+ for page in [vec2(0.0, 0.0), vec2(1e9, 1.0), vec2(1.0, 1e9), vec2(f32::NAN, 10.0), vec2(f32::INFINITY, 10.0)] {+ let r = grid_page_rect(cell, page);+ assert!(r.is_finite() && cell.contains_rect(r), "{page:?} -> {r:?}");+ }+ }+-fn annotation(fill_sign: bool) -> pdfcraft_render::Annotation {- pdfcraft_render::Annotation {- page: 0,- subtype: "FreeText".into(),- author: None,- contents: Some("Hello".into()),- modified: None,- name: None,- in_reply_to: None,- parent: None,- grouped: false,- rect: [0.0; 4],- color: None,- index: 0,- state: None,- quads: Vec::new(),- locked: false,- intent: None,- fill_sign,- no_rotate: false,- points: Vec::new(),- }-}--#[test]-fn hover_popup_skips_fill_and_sign_marks() {- assert_eq!(annotation_hover_text(&annotation(false)).as_deref(), Some("FreeText\nHello"));- assert_eq!(annotation_hover_text(&annotation(true)), None);-}-+ fn signature(signed: bool, visible: bool, page: Option<usize>, rect: Option<[f64; 4]>) -> pdfcraft_engine::SignatureInfo {+ pdfcraft_engine::SignatureInfo {+ field: "Signature1".into(),+ signed,+ page,+ rect,+ visible,+ signer: None,+ certificate: None,+ chain: Vec::new(),+ date: None,+ signing_time: None,+ reason: None,+ location: None,+ contact: None,+ sub_filter: None,+ doc_timestamp: false,+ certify: None,+ revision: 1,+ signed_len: 0,+ digest: None,+ algorithm: None,+ timestamp: false,+ timestamp_time: None,+ status: pdfcraft_engine::SignatureStatus::Valid,+ modification: pdfcraft_engine::sign::Modification::None,+ details: Vec::new(),+ }+ }++ #[test]+ fn signature_badges_keep_signed_visible_widgets_on_the_page() {+ let rect = [10.0, 10.0, 100.0, 50.0];+ let signatures =+ vec![signature(true, true, Some(0), Some(rect)), signature(true, true, Some(1), Some(rect)), signature(true, true, Some(0), Some(rect))];+ let badges = signature_badges(&signatures, 0);+ assert_eq!(badges.len(), 2);+ assert_eq!(badges[0].rect, rect);+ }++ #[test]+ fn signature_badges_skip_unsigned_invisible_and_unplaced_fields() {+ let rect = [10.0, 10.0, 100.0, 50.0];+ let signatures = vec![+ signature(false, true, Some(0), Some(rect)),+ signature(true, false, Some(0), Some(rect)),+ signature(true, true, Some(0), None),+ signature(true, true, Some(0), Some(rect)),+ ];+ let badges = signature_badges(&signatures, 0);+ assert_eq!(badges.len(), 1);+ assert_eq!(badges[0].rect, rect);+ }++ #[test]+ fn signature_badges_skip_rectangles_that_cannot_reach_the_screen() {+ let hostile = vec![+ [f64::NAN, 10.0, 100.0, 50.0],+ [10.0, f64::INFINITY, 100.0, 50.0],+ [10.0, 10.0, f64::NEG_INFINITY, 50.0],+ [10.0, 10.0, 1e300, 50.0],+ [10.0, 10.0, 100.0, 50.0],+ ];+ let signatures: Vec<_> = hostile.into_iter().map(|rect| signature(true, true, Some(0), Some(rect))).collect();+ let badges = signature_badges(&signatures, 0);+ assert_eq!(badges.len(), 1);+ }++ #[test]+ fn page_zoom_reads_the_side_the_page_width_is_on() {+ // A 200 x 100 pt page at 2 pixels per point: 400 x 200 on screen, or 200 x 400 turned.+ let xf = |rot: u16, size: Vec2| PageXform { rect: Rect::from_min_size(Pos2::ZERO, size), rot, pw: 200.0, ph: 100.0 };+ for rot in [0, 180] {+ assert_eq!(xf(rot, vec2(400.0, 200.0)).zoom(), 2.0, "{rot}");+ }+ for rot in [90, 270] {+ assert_eq!(xf(rot, vec2(200.0, 400.0)).zoom(), 2.0, "{rot}: the width runs down the screen");+ }+ }++ #[test]+ fn snapshot_tabs_read_like_their_source_plus_the_suffix() {+ let snap = Snapshot { kind: SnapshotKind::SignedVersion, revision: 1, from: "report.pdf".into() };+ assert_eq!(snapshot_tab_name("Report", "report.pdf", &snap), "Report (signed version)");+ let rev = Snapshot { kind: SnapshotKind::Revision, revision: 2, from: "report.pdf".into() };+ assert_eq!(snapshot_tab_name("Report", "report.pdf", &rev), "Report (revision 2)");+ assert_eq!(snapshot_tab_name("report.pdf", "report.pdf", &snap), "report.pdf");+ assert_eq!(snapshot_tab_name("report (revision 2).pdf", "report (revision 2).pdf", &rev), "report (revision 2).pdf");+ }++ #[test]+ fn grayscale_converts_colours_to_their_luminance() {+ let img = egui::ColorImage::new([2, 1], vec![Color32::from_rgb(255, 0, 0), Color32::from_rgba_premultiplied(0, 51, 102, 128)]);+ let gray = grayscale(img);+ let opaque = gray.pixels[0];+ assert_eq!(opaque.to_array(), [76, 76, 76, 255]);+ // Unmultiply RGB first, so a translucent colour keeps its paper-relative luminance.+ let translucent = gray.pixels[1];+ assert_eq!(translucent.to_array(), [42, 42, 42, 128]);+ }++ #[test]+ fn black_white_and_transparents_are_preserved_by_grayscale() {+ let img = egui::ColorImage::new([3, 1], vec![Color32::BLACK, Color32::WHITE, Color32::TRANSPARENT]);+ let gray = grayscale(img);+ assert_eq!(gray.pixels[0].to_array(), [0, 0, 0, 255]);+ assert_eq!(gray.pixels[1].to_array(), [255, 255, 255, 255]);+ assert_eq!(gray.pixels[2].to_array(), [0, 0, 0, 0]);+ }++ #[test]+ fn rendered_rasters_become_texture_images_without_a_copy() {+ let pdf = b"%PDF-1.4+ 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 100 50] /Contents 4 0 R >> endobj+ 4 0 obj << /Length 35 >> stream+ 0 0 1 rg 10 10 30 20 re f+ endstream endobj+ trailer << /Root 1 0 R >>+ %%EOF";+ let mut r = pdfcraft_render::PageRenderer::new(Arc::new(pdf.to_vec()), Default::default());+ let out = r.render(RenderRequest { page: 0, kind: RequestKind::Pixels, tile: None, scale: 1.5, tag: 0, preview: false });+ assert!(out.error.is_none(), "{:?}", out.error);+ let size = [out.width as usize, out.height as usize];+ let copied = egui::ColorImage::from_rgba_premultiplied(size, &out.rgba);+ let at = out.rgba.as_ptr();+ let img = texture_image(size, out.rgba);+ assert_eq!(img, copied);+ assert_eq!(img.pixels.as_ptr().cast::<u8>(), at, "the renderer's own buffer");+ }++ #[test]+ fn tiles_stay_granular_up_close_and_cover_giant_sheets_in_a_handful() {+ // Ordinary zooms keep 1024 px tiles; degenerate scales fall back to it, never zero.+ assert_eq!(tile_side(1.0, 2000), TILE);+ assert_eq!(tile_side(4.0, 2000), TILE);+ assert_eq!(tile_side(f32::NAN, 2000), TILE);+ assert_eq!(tile_side(f32::INFINITY, 2000), TILE);+ assert_eq!(tile_side(0.0, 2000), TILE);+ // Zoomed viewports need a few large tiles instead of many small ones.+ assert_eq!(tile_side(12.0, 2000), 2048);+ assert_eq!(tile_side(20.0, 2000), 3413);+ assert_eq!(tile_side(100.0, 2000), 4096);+ // A giant sheet at fit width (6740 px long side) is covered four tiles a side.+ assert_eq!(tile_side(96.0 / 72.0, 6740), 1685);+ // The backend clamps tile sides at 4096.+ assert_eq!(tile_side(20.0, 100_000), 4096);+ }++ #[test]+ fn grid_zoom_is_clamped_and_sharp_renders_tolerate_a_pinch() {+ assert!(sharp_enough(900, 876.0) && sharp_enough(800, 876.0) && sharp_enough(1300, 876.0));+ assert!(!sharp_enough(264, 876.0), "a thumbnail stretched over a zoomed page");+ assert!(!sharp_enough(876, 200.0), "far larger than drawn: wasteful");+ assert!(!sharp_enough(100, 0.0) && !sharp_enough(100, f32::NAN));+ let mut v = view(3, PageLayout::Single, true);+ for odd in [f32::NAN, f32::INFINITY] {+ v.set_grid_zoom(odd);+ assert_eq!(v.grid_zoom(), 1.0);+ }+ v.set_grid_zoom(99.0);+ assert_eq!(v.grid_zoom(), 3.0);+ v.set_grid_zoom(-4.0);+ assert_eq!(v.grid_zoom(), 0.5);+ }++ fn view(pages: usize, layout: PageLayout, continuous: bool) -> DocView {+ let info = pdfcraft_render::DocInfo {+ pages: (0..pages)+ .map(|_| pdfcraft_render::PageInfo { width: 300.0, height: 400.0, label: String::new(), crop: [0.0, 0.0, 300.0, 400.0], rotation: 0 })+ .collect(),+ ..Default::default()+ };+ DocView::new(DocId(1), &info, ViewDefaults { layout, continuous, ..Default::default() })+ }++ fn history_search_view() -> DocView {+ let mut v = view(5, PageLayout::Single, true);+ v.texts.insert(+ 3,+ pdfcraft_render::PageText {+ glyphs: vec![pdfcraft_render::TextGlyph {+ text: "match".into(),+ rect: [20.0, 260.0, 60.0, 280.0],+ quad: [[20.0, 260.0], [60.0, 260.0], [60.0, 280.0], [20.0, 280.0]],+ direction: [1.0, 0.0],+ }],+ line_of: vec![0],+ space_before: vec![false],+ }+ .into(),+ );+ v.find = Some(Find { matches: vec![(3, 0..1), (3, 0..1), (1, 0..1)], current: Some(2), ..Default::default() });+ v+ }++ #[test]+ fn explicit_search_jumps_record_history_and_keep_match_destination() {+ for step in [None, Some(true), Some(false)] {+ let mut v = history_search_view();+ v.page_input = "draft in progress".into();+ v.goto_point = Some((3, Some(0.8), Some(0.9), Vec2::ZERO));+ if let Some(forward) = step {+ v.find_step(forward);+ } else {+ v.go_to_match(0);+ }+ assert_eq!(v.back, vec![0], "explicit search jump must remember its origin");+ assert_eq!(v.goto, Some((3, 0.5)), "keep the match offset instead of the page top");+ assert_eq!(v.current, 3);+ assert_eq!(v.current_page_label(None), "4");+ // Chrome refreshes the idle page box; navigation must not overwrite a draft+ // that may still be focused. DocView does not own the editor's focus state.+ assert_eq!(v.page_input, "draft in progress");+ assert!(v.goto_point.is_none(), "an earlier link destination cannot override the search offset");+ v.go_to_match(1);+ assert_eq!(v.back, vec![0], "same-page matches do not duplicate history");+ assert!(v.view_history(false));+ assert_eq!(v.current, 0);+ assert!(v.view_history(true));+ assert_eq!(v.current, 3);+ assert!(v.view_history(false));+ v.go_to_match(2);+ assert!(v.forward.is_empty(), "a new explicit jump discards Forward");+ assert_eq!(v.back, vec![0]);+ }+ }++ #[test]+ fn automatic_search_updates_do_not_record_history_or_discard_forward() {+ let mut v = history_search_view();+ v.forward = vec![4];+ v.find = Some(Find { query: "match".into(), ..Default::default() });+ v.rerun_find();+ assert_eq!(v.current, 3);+ assert_eq!(v.goto, Some((3, 0.5)));+ assert!(v.back.is_empty());+ assert_eq!(v.forward, vec![4]);+ v.find.as_mut().unwrap().current = None;+ v.texts.insert(1, Arc::new(find_test_text("match")));+ v.refresh_find_page(1);+ assert_eq!(v.current, 1, "an automatic late match still follows its anchor");+ assert!(v.back.is_empty(), "automatic search updates do not record history");+ assert_eq!(v.forward, vec![4]);+ }++ /// One glyph per character on one line, for the search-order tests below.+ fn find_test_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(),+ }+ }++ /// A text-layer result for `page`, for the search tests below.+ fn find_text_result(page: usize, text: &str) -> pdfcraft_render::RenderedPage {+ pdfcraft_render::RenderedPage {+ request: RenderRequest { page, kind: RequestKind::Text, tag: TEXT_TAG, ..Default::default() },+ width: 0,+ height: 0,+ rgba: Default::default(),+ error: None,+ text: Some(Arc::new(find_test_text(text))),+ warnings: Vec::new(),+ millis: 0,+ }+ }++ /// Text layers arrive in whatever order the workers finish, not in page order. A search+ /// started on page 1 must settle on page 1's match even when page 2's text arrives first,+ /// instead of keeping the later match picked only because page 1 had not been read yet.+ #[test]+ fn automatic_search_match_follows_the_viewed_page_when_text_arrives_out_of_order() {+ let mut v = view(2, PageLayout::Single, true);+ v.current = 0;+ v.find = Some(Find { query: "sample".into(), ..Default::default() });+ v.rerun_find();+ assert_eq!(v.find.as_ref().unwrap().current, None, "no text yet, so no match");++ let ctx = egui::Context::default();+ let request = |page| RenderRequest { page, kind: RequestKind::Text, tag: TEXT_TAG, ..Default::default() };+ let result = |page, text: &str| pdfcraft_render::RenderedPage {+ request: request(page),+ width: 0,+ height: 0,+ rgba: Default::default(),+ error: None,+ text: Some(Arc::new(find_test_text(text))),+ warnings: Vec::new(),+ millis: 0,+ };+ v.last_queue = vec![request(1), request(0)];+ // Page 2's text finishes first, as it can when the workers race.+ v.receive_result(&ctx, result(1, "Second page sample text"));+ assert_eq!(v.find.as_ref().unwrap().current, Some(0), "the only known match is picked while page 1 is pending");++ v.receive_result(&ctx, result(0, "Panel sample draft notes"));+ let f = v.find.as_ref().unwrap();+ assert_eq!(f.matches.iter().map(|(p, _)| *p).collect::<Vec<_>>(), vec![0, 1]);+ assert_eq!(f.current, Some(0), "page 1's match takes over once its text arrives");+ assert_eq!(v.current, 0, "the view follows the first match at or after the page being viewed");+ }++ /// A match the user picked (a click in the Search panel, or ⌘G) is not moved by a text+ /// layer that arrives later: only automatic choices follow the viewed page.+ #[test]+ fn a_user_picked_search_match_stays_put_when_earlier_text_arrives() {+ let mut v = view(2, PageLayout::Single, true);+ v.current = 0;+ v.find = Some(Find { query: "sample".into(), ..Default::default() });+ v.rerun_find();+ v.texts.insert(1, Arc::new(find_test_text("Second page sample text")));+ v.refresh_find_page(1);+ v.go_to_match(0);+ assert_eq!(v.find.as_ref().unwrap().auto_from, None, "an explicit choice is not automatic");++ v.texts.insert(0, Arc::new(find_test_text("Panel sample draft notes")));+ v.refresh_find_page(0);+ let f = v.find.as_ref().unwrap();+ assert_eq!(f.matches.iter().map(|(p, _)| *p).collect::<Vec<_>>(), vec![0, 1]);+ assert_eq!(f.current, Some(1), "the picked match keeps its identity after page 1 is inserted");+ assert_eq!(v.current, 1, "the user's page does not change under them");+ }++ /// The automatic choice may move the view only while the reader has left it where that+ /// choice put it. Navigating by the page box/Pages panel/outline or by view history is the+ /// reader's decision: a text layer arriving afterwards must not pull them back to an+ /// anchor-derived match. (The harness covers same-page wheel and pointer scrolling.)+ #[test]+ fn a_late_automatic_match_does_not_override_the_readers_navigation() {+ enum Nav {+ Page,+ History,+ }+ for nav in [Nav::Page, Nav::History] {+ let mut v = view(3, PageLayout::Single, true);+ v.current = 0;+ v.texts.insert(2, Arc::new(find_test_text("Second page sample")));+ v.find = Some(Find { query: "sample".into(), ..Default::default() });+ v.rerun_find();+ assert_eq!((v.current, v.find.as_ref().unwrap().auto_page), (2, Some(2)), "the automatic match was shown");+ match nav {+ // The page box, the Pages panel and outline destinations all end here.+ Nav::Page => v.go_to_page(1),+ // View ▸ Page navigation ▸ Previous view writes `current` directly.+ Nav::History => {+ v.back = vec![1];+ assert!(v.view_history(false));+ }+ }+ assert_eq!(v.current, 1);+ v.texts.insert(0, Arc::new(find_test_text("First page sample")));+ v.refresh_find_page(0);+ let f = v.find.as_ref().unwrap();+ assert_eq!(f.auto_from, None, "the reader's navigation ends automatic following");+ assert_eq!(f.auto_page, None);+ assert_eq!(v.current, 1, "a late match cannot pull the reader back");+ }+ }++ /// Typing on while the results arrive must not re-anchor the search on a page the automatic+ /// flash picked. The anchor stays the page the reader was on when they started searching.+ #[test]+ fn refining_the_query_keeps_the_page_the_search_started_from() {+ let mut v = view(3, PageLayout::Single, true);+ v.current = 0;+ v.texts.insert(2, Arc::new(find_test_text("Second page sample text")));+ v.find = Some(Find { query: "sample".into(), ..Default::default() });+ v.rerun_find();+ assert_eq!((v.current, v.find.as_ref().unwrap().auto_from), (2, Some(0)), "the first query's match scrolled the view");++ // Page 1 has a match for the refined query, and so has page 3. Anchored on the page the+ // automatic flash reached, the search would pick page 3; the starting page picks page 1.+ v.texts.insert(0, Arc::new(find_test_text("Panel draft text")));+ v.find.as_mut().unwrap().query = "text".into();+ v.rerun_find();+ let f = v.find.as_ref().unwrap();+ assert_eq!(f.auto_from, Some(0), "refinement keeps the page the reader searched from");+ assert_eq!(f.matches.first().map(|(p, _)| *p), Some(0));+ assert_eq!(f.current, Some(0));+ assert_eq!(v.current, 0);+ }++ /// ⌘G / Ctrl+G goes through `find_step`, an explicit choice like a Search-panel click: a+ /// text layer arriving later must not undo it.+ #[test]+ fn keyboard_find_step_is_explicit_and_a_late_text_layer_cannot_undo_it() {+ let mut v = view(3, PageLayout::Single, true);+ v.current = 0;+ v.texts.insert(1, Arc::new(find_test_text("first sample")));+ v.texts.insert(2, Arc::new(find_test_text("second sample")));+ v.find = Some(Find { query: "sample".into(), ..Default::default() });+ v.rerun_find();+ assert_eq!((v.current, v.find.as_ref().unwrap().auto_from), (1, Some(0)));++ let ctx = egui::Context::default();+ ctx.input_mut(|i| {+ i.events.push(egui::Event::Key { key: egui::Key::G, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::COMMAND });+ });+ shortcuts(&mut v, &ctx, Default::default());++ assert_eq!(v.current, 2, "the keyboard step chose the next match");+ assert_eq!(v.find.as_ref().unwrap().auto_from, None, "the keyboard step is the user's choice");+ assert_eq!(v.back, vec![1], "an explicit search jump records its origin");++ v.texts.insert(0, Arc::new(find_test_text("intro sample")));+ v.refresh_find_page(0);+ let f = v.find.as_ref().unwrap();+ assert_eq!(v.current, 2, "the chosen match keeps the view");+ assert_eq!(f.current.and_then(|i| f.matches.get(i)).map(|(p, _)| *p), Some(2));+ }++ /// A page whose text extraction failed keeps the automatic anchor: the failure selects the+ /// next match without moving the view, and a later text layer can still follow the anchor.+ #[test]+ fn a_failed_text_layer_keeps_the_automatic_anchor_without_jitter() {+ let mut v = view(3, PageLayout::Single, true);+ v.current = 0;+ v.texts.insert(1, Arc::new(find_test_text("first sample")));+ v.texts.insert(2, Arc::new(find_test_text("second sample")));+ v.find = Some(Find { query: "sample".into(), ..Default::default() });+ v.rerun_find();+ assert_eq!((v.current, v.find.as_ref().unwrap().auto_page), (1, Some(1)));++ let goto = v.goto;+ let ctx = egui::Context::default();+ let request = RenderRequest { page: 1, kind: RequestKind::Text, ..Default::default() };+ v.last_queue = vec![request];+ v.receive_result(+ &ctx,+ pdfcraft_render::RenderedPage {+ request,+ width: 0,+ height: 0,+ rgba: Default::default(),+ error: Some("extraction failed".into()),+ text: None,+ warnings: Vec::new(),+ millis: 0,+ },+ );+ let f = v.find.as_ref().unwrap();+ assert_eq!(f.matches.iter().map(|(p, _)| *p).collect::<Vec<_>>(), vec![2]);+ assert_eq!(f.current, Some(0), "the remaining match is selected");+ assert_eq!((f.auto_from, f.auto_page), (Some(0), Some(1)), "a failure does not end automatic following");+ assert_eq!(v.current, 1, "a failure never moves the view");+ assert_eq!(v.goto, goto, "a failure never flashes the match");++ // The search still follows its original page when that page's text arrives.+ v.last_queue = vec![RenderRequest { page: 0, kind: RequestKind::Text, tag: TEXT_TAG, ..Default::default() }];+ v.receive_result(&ctx, find_text_result(0, "intro sample"));+ assert_eq!(v.current, 0, "the anchor's earlier match takes over");+ let f = v.find.as_ref().unwrap();+ assert_eq!(f.current.and_then(|i| f.matches.get(i)).map(|(p, _)| *p), Some(0));+ }++ /// A reader who navigated before a page's text failed is not pulled back by a later+ /// matching layer: the failure path must preserve the same `Ended` state as a successful+ /// one, and the result list may select the late match without revealing it.+ #[test]+ fn a_failed_text_layer_after_navigation_does_not_reveal_a_late_match() {+ let mut v = view(3, PageLayout::Single, true);+ v.current = 0;+ v.find = Some(Find { query: "sample".into(), ..Default::default() });+ v.rerun_find();+ v.go_to_page(2);+ let moved = v.goto;+ assert!(v.find.as_ref().unwrap().follow_ended, "the reader navigated before any match arrived");++ let ctx = egui::Context::default();+ let failed = RenderRequest { page: 1, kind: RequestKind::Text, tag: TEXT_TAG, ..Default::default() };+ v.last_queue = vec![failed];+ v.receive_result(+ &ctx,+ pdfcraft_render::RenderedPage {+ request: failed,+ width: 0,+ height: 0,+ rgba: Default::default(),+ error: Some("extraction failed".into()),+ text: None,+ warnings: Vec::new(),+ millis: 0,+ },+ );+ let f = v.find.as_ref().unwrap();+ assert!(f.follow_ended, "a failure after navigation does not restart following");+ assert_eq!((f.auto_from, f.auto_page), (None, None));+ assert_eq!(v.current, 2, "a failure never moves the view");+ assert_eq!(v.goto, moved);++ let arrived = RenderRequest { page: 0, kind: RequestKind::Text, tag: TEXT_TAG, ..Default::default() };+ v.last_queue = vec![arrived];+ v.receive_result(&ctx, find_text_result(0, "intro sample"));+ let f = v.find.as_ref().unwrap();+ assert!(f.follow_ended);+ assert_eq!((f.auto_from, f.auto_page), (None, None));+ assert_eq!(v.current, 2, "the late matching layer does not pull the reader back");+ assert_eq!(v.goto, moved, "no flash was issued");+ assert_eq!(f.current.and_then(|i| f.matches.get(i)).map(|(p, _)| *p), Some(0), "the result list still selects the late match");+ }++ /// The reader can navigate before any text layer has supplied a match. That navigation+ /// still ends automatic following, so the first late match is listed but not revealed by+ /// a flash that would pull the reader back.+ #[test]+ fn navigation_before_the_first_match_is_not_overridden_by_a_late_text_layer() {+ let mut v = view(3, PageLayout::Single, true);+ v.current = 0;+ v.find = Some(Find { query: "sample".into(), ..Default::default() });+ v.rerun_find();+ let f = v.find.as_ref().unwrap();+ assert_eq!(f.current, None, "no text layer has arrived yet");+ assert_eq!((f.auto_from, f.auto_page), (Some(0), Some(0)));++ v.go_to_page(2);+ assert_eq!(v.goto, Some((2, 0.0)), "the reader moved to page 3");+ assert!(v.find.as_ref().unwrap().follow_ended, "moving the view ends automatic following");++ let ctx = egui::Context::default();+ let request = RenderRequest { page: 1, kind: RequestKind::Text, tag: TEXT_TAG, ..Default::default() };+ v.last_queue = vec![request];+ v.receive_result(&ctx, find_text_result(1, "late sample"));+ let f = v.find.as_ref().unwrap();+ assert_eq!(v.current, 2, "the late first match does not pull the reader back");+ assert_eq!(v.goto, Some((2, 0.0)), "no flash was issued");+ assert_eq!((f.auto_from, f.auto_page), (None, None));+ assert_eq!(f.current.and_then(|i| f.matches.get(i)).map(|(p, _)| *p), Some(1), "the result list still selects the match");+ }++ /// A page-box jump to the page already shown is still the reader's navigation: automatic+ /// following must end, so a late earlier match is listed without moving the view. (The+ /// harness covers wheel, scrollbar and pointer scrolling through the production paint path.)+ #[test]+ fn a_same_page_page_box_jump_ends_automatic_following() {+ let mut v = view(3, PageLayout::Single, true);+ v.current = 0;+ v.texts.insert(1, Arc::new(find_test_text("first sample")));+ v.find = Some(Find { query: "sample".into(), ..Default::default() });+ v.rerun_find();+ assert_eq!((v.current, v.find.as_ref().unwrap().auto_page), (1, Some(1)), "the automatic choice is on page 2");++ // Choosing the page already shown still ends following; it stays on page 2 at its top.+ v.go_to_page(1);+ let shown = v.goto;+ assert_eq!(shown, Some((1, 0.0)));++ v.texts.insert(0, Arc::new(find_test_text("intro sample")));+ v.refresh_find_page(0);+ let f = v.find.as_ref().unwrap();+ assert!(f.follow_ended);+ assert_eq!((f.auto_from, f.auto_page), (None, None));+ assert_eq!(v.current, 1, "the late earlier match does not move the reader within the page");+ assert_eq!(v.goto, shown, "no flash was issued");+ assert_eq!(f.current.and_then(|i| f.matches.get(i)).map(|(p, _)| *p), Some(1), "the page-2 match stays selected");+ }++ /// A document-wide invalidation (a layer toggle, an edit, undo/redo) clears results for+ /// re-extraction but is not the reader navigating. Automatic following keeps its anchor so+ /// the re-extracted layers still reveal the automatic choice; a reader who already took+ /// over stays in control. If `document_changed` clamps the view away from that anchor, the+ /// next layer ends following instead of revealing a match from the stale page.+ #[test]+ fn content_invalidation_keeps_the_following_state() {+ let mut v = view(3, PageLayout::Single, true);+ v.current = 0;+ v.texts.insert(1, Arc::new(find_test_text("first sample")));+ v.find = Some(Find { query: "sample".into(), ..Default::default() });+ v.rerun_find();+ assert_eq!((v.current, v.find.as_ref().unwrap().auto_page), (1, Some(1)), "the automatic choice is on page 2");++ v.invalidate_content();+ let f = v.find.as_ref().unwrap();+ assert!(f.matches.is_empty() && f.current.is_none(), "results wait for the re-extracted text");+ assert!(!f.follow_ended, "a content change is not reader navigation");+ assert_eq!((f.auto_from, f.auto_page), (Some(0), Some(1)));++ // Re-extracted text still follows the page the search started from.+ let ctx = egui::Context::default();+ let request = RenderRequest { page: 0, kind: RequestKind::Text, tag: TEXT_TAG, ..Default::default() };+ v.last_queue = vec![request];+ v.receive_result(&ctx, find_text_result(0, "intro sample"));+ assert_eq!(v.current, 0, "the re-extracted match is revealed by the still-active search");+ let f = v.find.as_ref().unwrap();+ assert!(!f.follow_ended);+ assert_eq!((f.auto_from, f.auto_page), (Some(0), Some(0)));++ // A reader who navigated first keeps the view they chose across the invalidation.+ v.go_to_page(2);+ let moved = v.goto;+ assert!(v.find.as_ref().unwrap().follow_ended);+ v.invalidate_content();+ let f = v.find.as_ref().unwrap();+ assert!(f.follow_ended);+ assert_eq!((f.auto_from, f.auto_page), (None, None));+ v.last_queue = vec![request];+ v.receive_result(&ctx, find_text_result(0, "late sample"));+ assert_eq!(v.current, 2, "no delayed reveal after the reader navigated");+ assert_eq!(v.goto, moved, "no flash was issued");+ let f = v.find.as_ref().unwrap();+ assert_eq!(f.current.and_then(|i| f.matches.get(i)).map(|(p, _)| *p), Some(0), "the result list still selects the late match");+ }++ /// A document edit can shrink the page count. `document_changed` clamps `current` but leaves+ /// the automatic anchor's page index alone; a re-extracted layer must then end following+ /// rather than reveal a match by scrolling from a page that no longer exists.+ #[test]+ fn a_page_count_shrink_ends_following_before_a_late_reveal() {+ let mut v = view(5, PageLayout::Single, true);+ v.current = 0;+ v.texts.insert(4, Arc::new(find_test_text("last sample")));+ v.find = Some(Find { query: "sample".into(), ..Default::default() });+ v.rerun_find();+ assert_eq!((v.current, v.find.as_ref().unwrap().auto_page), (4, Some(4)), "the automatic choice is on the last page");++ let info = pdfcraft_render::DocInfo {+ pages: (0..2)+ .map(|_| pdfcraft_render::PageInfo { width: 300.0, height: 400.0, label: String::new(), crop: [0.0, 0.0, 300.0, 400.0], rotation: 0 })+ .collect(),+ ..Default::default()+ };+ v.document_changed(&info);+ assert_eq!(v.current, 1, "the view clamps to the last remaining page");+ let f = v.find.as_ref().unwrap();+ assert!(!f.follow_ended, "the content change itself keeps the automatic state");+ assert_eq!((f.auto_from, f.auto_page), (Some(0), Some(4)), "the anchor still names the removed page");+ let goto = v.goto;++ let ctx = egui::Context::default();+ let request = RenderRequest { page: 0, kind: RequestKind::Text, tag: TEXT_TAG, ..Default::default() };+ v.last_queue = vec![request];+ v.receive_result(&ctx, find_text_result(0, "intro sample"));+ let f = v.find.as_ref().unwrap();+ assert!(f.follow_ended, "a layer for the remaining pages ends the stale follow");+ assert_eq!((f.auto_from, f.auto_page), (None, None));+ assert_eq!(v.current, 1, "the late layer cannot pull the view back");+ assert_eq!(v.goto, goto, "no flash was issued");+ assert_eq!(f.current.and_then(|i| f.matches.get(i)).map(|(p, _)| *p), Some(0), "the result list still selects the match");+ }++ /// Typing refinements while text layers keep arriving must keep the page the search began+ /// on, not re-anchor on whichever page an earlier automatic flash happened to show.+ #[test]+ fn rapid_query_edits_interleaved_with_text_results_keep_the_start_anchor() {+ let mut v = view(3, PageLayout::Single, true);+ v.current = 0;+ v.find = Some(Find { query: "sam".into(), ..Default::default() });+ v.rerun_find();+ assert!(v.find.as_ref().unwrap().current.is_none());++ let edits = [("samp", 2, "Page three sample", 2), ("sampl", 1, "Page two sample", 1), ("sample", 0, "Page one sample", 0)];+ for (query, page, text, shown) in edits {+ v.find.as_mut().unwrap().query = query.into();+ v.rerun_find();+ let f = v.find.as_ref().unwrap();+ assert_eq!(f.auto_from, Some(0), "refinement keeps the page the reader started from");+ assert!(!f.follow_ended);+ v.texts.insert(page, Arc::new(find_test_text(text)));+ v.refresh_find_page(page);+ let f = v.find.as_ref().unwrap();+ assert_eq!(v.current, shown, "the late page follows the automatic anchor {shown}");+ assert_eq!((f.auto_from, f.auto_page), (Some(0), Some(shown)));+ assert!(!f.follow_ended, "the automatic flash itself does not end following");+ }+ assert!(v.back.is_empty(), "automatic search updates do not record history");+ }++ #[test]+ fn text_layers_evict_far_pages_but_keep_visible_and_matches() {+ let info = thumbnail_info(100);+ let mut v = DocView::new(DocId(1), &info, ViewDefaults::default());+ v.current = 50;+ v.frame_visible = HashSet::from([50, 51]);+ for p in 0..100 {+ v.texts.insert(p, Arc::new(PageText::default()));+ }+ v.text_failed.insert(0);+ v.text_failed.insert(99);+ v.find = Some(Find { matches: vec![(0, 0..1)], ..Default::default() });+ let _ = v.prepare_render_queue(&info, 1.0);+ assert!(v.texts.contains_key(&50) && v.texts.contains_key(&51), "visible pages stay");+ assert!(v.texts.contains_key(&0), "matched pages stay");+ assert!(v.texts.contains_key(&49), "nearest prefetch window stays");+ assert!(!v.texts.contains_key(&99), "far pages go");+ assert_eq!(v.texts.len(), 2 + 1 + MAX_CACHED_TEXT_PAGES, "visible + matched + prefetch window");+ assert!(v.text_failed.contains(&0) && v.text_failed.contains(&99), "failures are bytes-free: never evict");+ }++ /// A PDF of one line of text on each page, `lines[i]` on page `i`.+ fn text_pages_pdf(lines: &[&str]) -> Vec<u8> {+ let n = lines.len();+ // 1 catalog, 2 pages, 3 font, then a page and its content stream for each line.+ let mut objects = vec![+ "<< /Type /Catalog /Pages 2 0 R >>".to_string(),+ format!("<< /Type /Pages /Count {n} /Kids [{}] >>", (0..n).map(|i| format!("{} 0 R", 4 + 2 * i)).collect::<Vec<_>>().join(" ")),+ "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>".to_string(),+ ];+ for (i, line) in lines.iter().enumerate() {+ let content = format!("BT /F1 18 Tf 72 700 Td ({line}) Tj ET");+ objects.push(format!(+ "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << /Font << /F1 3 0 R >> >> /Contents {} 0 R >>",+ 5 + 2 * i+ ));+ objects.push(format!("<< /Length {} >>\nstream\n{content}\nendstream", content.len()));+ }+ let mut out = b"%PDF-1.7\n".to_vec();+ let mut offsets = Vec::new();+ for (i, o) in objects.iter().enumerate() {+ offsets.push(out.len());+ out.extend(format!("{} 0 obj\n{o}\nendobj\n", i + 1).bytes());+ }+ let xref = out.len();+ out.extend(format!("xref\n0 {}\n0000000000 65535 f \n", objects.len() + 1).bytes());+ for o in offsets {+ out.extend(format!("{o:010} 00000 n \n").bytes());+ }+ out.extend(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objects.len() + 1).bytes());+ out+ }++ /// #2639: scrolling continuously, Select All takes every page's text, and Copy gets all of it+ /// in page order, reading the pages whose text wasn't read for display.+ #[test]+ fn select_all_copies_the_whole_document_while_scrolling_continuously() {+ let mut app = PdfCraftApp::new();+ app.open_bytes("three.pdf", None, text_pages_pdf(&["Alpha one", "Bravo two", "Charlie three"])).unwrap();+ let v = &mut app.views[0];+ assert!(v.continuous, "continuous scrolling is the default");+ assert!(v.texts.is_empty(), "no page's text read yet");+ // Nothing shown is selected yet (false, as for a page whose text isn't read), but the whole+ // document is: Copy reads every page.+ assert!(!v.select_all());+ assert!(v.all_text && v.selection.is_none());+ assert_eq!(v.pages_without_text(), vec![0, 1, 2]);+ // Copy reads the pages off the UI thread; the clipboard gets the text once they're read.+ let ctx = egui::Context::default();+ assert!(app.copy_selected_text(0, &ctx), "the copy starts");+ assert!(app.document_copy.is_some(), "reading the pages, not on this thread");+ let mut text = 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();+ text = out.platform_output.commands.iter().find_map(|c| match c {+ egui::OutputCommand::CopyText(t) => Some(t.clone()),+ _ => None,+ });+ if text.is_some() {+ break;+ }+ std::thread::sleep(std::time::Duration::from_millis(10));+ }+ let text = text.expect("the copied text arrives");+ assert!(app.document_copy.is_none(), "done");+ let at = |w: &str| text.find(w).unwrap_or_else(|| panic!("{w:?} missing from {text:?}"));+ assert!(at("Alpha") < at("Bravo") && at("Bravo") < at("Charlie"), "page order: {text:?}");+ assert_eq!(text.lines().count(), 3, "a line per page: {text:?}");+ // A new scope ends it: one page at a time, Select All is the page's again.+ app.views[0].set_continuous(false);+ assert!(!app.views[0].all_text, "not after switching to one page at a time");+ // So do a page selection and a change of the document's content (an edit, undo).+ app.views[0].set_continuous(true);+ app.views[0].select_all();+ app.views[0].select_text(0, 0, 0);+ assert!(!app.views[0].all_text, "a page selection replaces it");+ app.views[0].select_all();+ app.views[0].invalidate_content();+ assert!(!app.views[0].all_text, "not past an edit of the document");+ }++ /// A whole-document copy reads the pages without text, keeps those already read and skips+ /// those that failed before.+ #[test]+ fn a_document_copy_reads_only_the_pages_it_needs() {+ let mut app = PdfCraftApp::new();+ app.open_bytes("three.pdf", None, text_pages_pdf(&["Alpha one", "Bravo two", "Charlie three"])).unwrap();+ app.views[0].text_failed.insert(2);+ let job = crate::DocumentCopyJob::of(&app.views[0], app.session.get(app.views[0].id).unwrap());+ let kinds: Vec<_> = job.pages.iter().map(|p| matches!(p, crate::CopyPage::ToRead)).collect();+ assert_eq!(kinds, vec![true, true, false], "pages 1 and 2 to read, page 3 failed before");+ assert!(matches!(job.pages[2], crate::CopyPage::Skip));+ }++ /// A later copy wins: a whole-document copy still reading its pages never replaces what was+ /// copied after it started, from the page or anywhere else (a text field, a comment).+ #[test]+ fn a_later_copy_cancels_a_document_copy_still_reading() {+ let mut app = PdfCraftApp::new();+ app.open_bytes("three.pdf", None, text_pages_pdf(&["Alpha one", "Bravo two", "Charlie three"])).unwrap();+ let ctx = egui::Context::default();+ // Another copy in the same frame (here a text field's) drops it.+ app.views[0].select_all();+ assert!(app.copy_selected_text(0, &ctx) && app.document_copy.is_some());+ let mut out = ctx.run_ui(egui::RawInput::default(), |ui| {+ ui.ctx().copy_text("a word".to_owned());+ app.finish_document_copy(ui.ctx());+ });+ out.textures_delta.clear();+ 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.+ 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.copy_selected_text(0, &ctx);+ assert!(app.document_copy.is_none(), "a page selection's copy cancels it");+ }++ /// A press anywhere on a page ends Select All of the document, whatever the tool (here the+ /// Hand, which selects no text) and whether the page's text is read yet.+ #[test]+ fn a_press_on_a_page_ends_select_all_of_the_document() {+ 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("three.pdf", None, text_pages_pdf(&["Alpha one", "Bravo two", "Charlie three"])).unwrap();+ app+ });+ let mut on_screen = None;+ for _ in 0..600 {+ 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 first page is on screen");+ h.state_mut().quick_tool = crate::QuickTool::Hand;+ h.state_mut().views[0].select_all();+ assert!(h.state().views[0].all_text);+ let at = r.center();+ h.event(egui::Event::PointerMoved(at));+ h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE });+ h.run_steps(1);+ h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE });+ h.run_steps(2);+ assert!(!h.state().views[0].all_text, "a press on the page ends it");++ // A press while a dialog is up lands on the dialog, not the page: the selection stays.+ h.state_mut().views[0].select_all();+ h.state_mut().dialog = Some(crate::Dialog::JsConsole);+ h.run_steps(2);+ h.event(egui::Event::PointerMoved(at));+ h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE });+ h.run_steps(1);+ h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE });+ h.run_steps(2);+ assert!(h.state().views[0].all_text, "a press beneath a dialog doesn't end it");+ }++ /// The pages of a whole-document copy come out in order whatever was read before, and a+ /// cancelled copy gives nothing (a new copy or a closed document cancels the old one).+ #[test]+ fn a_document_copy_reads_in_page_order_and_stops_when_cancelled() {+ let mut app = PdfCraftApp::new();+ app.open_bytes("three.pdf", None, text_pages_pdf(&["Alpha one", "Bravo two", "Charlie three"])).unwrap();+ // The middle page's text read for display already; the others read by the copy.+ let doc = app.session.get(app.views[0].id).unwrap();+ let mut r = pdfcraft_render::PageRenderer::new(doc.bytes.clone(), Default::default());+ let middle = r.render(RenderRequest { page: 1, kind: RequestKind::Text, ..Default::default() }).text.unwrap();+ app.views[0].texts.insert(1, middle);+ let job = || crate::DocumentCopyJob::of(&app.views[0], app.session.get(app.views[0].id).unwrap());+ let text = job().text(&std::sync::atomic::AtomicBool::new(false)).unwrap();+ assert!(text.find("Alpha").unwrap() < text.find("Bravo").unwrap() && text.find("Bravo").unwrap() < text.find("Charlie").unwrap(), "{text:?}");+ assert_eq!(job().text(&std::sync::atomic::AtomicBool::new(true)), None, "cancelled");+ }++ /// Select All keeps to the page shown one page at a time, and in a document of one page; of+ /// the document, it reads the text already read and doesn't ask again for failed pages.+ #[test]+ fn select_all_of_the_document_only_while_scrolling_through_several_pages() {+ let info = thumbnail_info(3);+ let one_line = |s: &str| 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(),+ };+ let mut v = DocView::new(DocId(1), &info, ViewDefaults::default());+ for p in 0..3 {+ v.texts.insert(p, Arc::new(one_line("abc")));+ }+ v.continuous = false;+ v.current = 1;+ assert!(v.select_all());+ assert!(!v.all_text && v.selection.is_some_and(|s| s.page == 1), "one page at a time: the page shown");+ let single = thumbnail_info(1);+ let mut w = DocView::new(DocId(2), &single, ViewDefaults::default());+ w.texts.insert(0, Arc::new(one_line("abc")));+ assert!(w.select_all());+ assert!(!w.all_text && w.selection.is_some(), "a one-page document: that page");+ // Text read for display is used; pages that failed aren't asked for again.+ let mut d = DocView::new(DocId(3), &info, ViewDefaults::default());+ d.texts.insert(1, Arc::new(one_line("abc")));+ d.text_failed.insert(2);+ assert!(d.select_all() && d.all_text);+ assert_eq!(d.pages_without_text(), vec![0]);+ }++ #[test]+ fn text_layers_keep_the_selection_page() {+ let info = thumbnail_info(100);+ let mut v = DocView::new(DocId(1), &info, ViewDefaults::default());+ let text = PageText {+ glyphs: vec![pdfcraft_render::TextGlyph { text: "x".into(), rect: [0.0, 0.0, 10.0, 10.0], quad: [[0.0, 0.0]; 4], direction: [1.0, 0.0] }],+ line_of: vec![0],+ space_before: vec![false],+ };+ for p in 0..100 {+ v.texts.insert(p, Arc::new(text.clone()));+ }+ v.select_text(0, 0, 0);+ v.current = 90;+ 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");+ }++ #[test]+ fn text_layers_stay_while_a_search_is_active() {+ let info = thumbnail_info(100);+ let mut v = DocView::new(DocId(1), &info, ViewDefaults::default());+ v.current = 50;+ v.frame_visible = HashSet::from([50]);+ for p in 0..100 {+ v.texts.insert(p, Arc::new(PageText::default()));+ }+ v.find = Some(Find { query: "dup".into(), case_query: "dup".into(), matches: vec![(0, 0..1)], ..Default::default() });+ let _ = v.prepare_render_queue(&info, 1.0);+ assert_eq!(v.texts.len(), 100, "evicting mid-search would churn the workers");+ }++ fn thumbnail_info(count: usize) -> DocInfo {+ DocInfo {+ pages: (0..count)+ .map(|i| {+ let (width, height) = match i % 3 {+ 0 => (612.0, 792.0),+ 1 => (200.0, 4000.0),+ _ => (4000.0, 200.0),+ };+ pdfcraft_render::PageInfo { width, height, label: (i + 1).to_string(), crop: [0.0, 0.0, width, height], rotation: 0 }+ })+ .collect(),+ ..Default::default()+ }+ }++ #[test]+ fn ten_thousand_pages_only_demand_viewport_and_prefetch_at_both_densities() {+ let info = thumbnail_info(10_000);+ let mut v = DocView::new(DocId(1), &info, ViewDefaults::default());+ let cols = 4;+ let rows = info.pages.len().div_ceil(cols);+ for ppp in [1.0, 2.0] {+ for row in [0, 1234, rows - 1] {+ v.begin_render_frame();+ let range = thumbnail_rows(row as f32 * 250.0, row as f32 * 250.0 + 750.0, 250.0, rows);+ for p in range.start * cols..(range.end * cols).min(info.pages.len()) {+ v.need_thumbnail(p, p / cols == row);+ }+ let queue = v.prepare_render_queue(&info, ppp);+ assert!(queue.len() <= 5 * cols, "only three visible rows and two prefetch rows");+ assert_eq!(queue.first().unwrap().page / cols, row, "visible cells precede prefetch");+ let bytes: usize = queue+ .iter()+ .map(|r| {+ let p = &info.pages[r.page];+ let (w, h) = (device_pixels(p.width, r.scale), device_pixels(p.height, r.scale));+ assert!(w <= (THUMB_W * ppp).ceil() as u32);+ assert!(h <= (THUMB_H * ppp).ceil() as u32);+ rgba_bytes(w as usize, h as usize)+ })+ .sum();+ assert!(bytes <= THUMB_BYTES);+ assert_eq!(queue, v.prepare_render_queue(&info, ppp), "unchanged demand reconstructs the same work");+ }+ }+ }++ #[test]+ fn oversized_thumbnail_viewport_scales_all_admitted_cells_to_one_budget() {+ let info = thumbnail_info(10_000);+ let mut v = DocView::new(DocId(1), &info, ViewDefaults::default());+ for page in 0..MAX_THUMB_DEMAND {+ v.need_thumbnail(page, true);+ }+ let queue = v.prepare_render_queue(&info, 2.0);+ assert_eq!(queue.len(), MAX_THUMB_DEMAND);+ let bytes: usize = queue+ .iter()+ .map(|r| {+ let p = &info.pages[r.page];+ rgba_bytes(device_pixels(p.width, r.scale) as usize, device_pixels(p.height, r.scale) as usize)+ })+ .sum();+ assert!(bytes <= THUMB_BYTES);+ }++ fn solid_result(request: RenderRequest, w: u32, h: u32) -> pdfcraft_render::RenderedPage {+ pdfcraft_render::RenderedPage {+ request,+ width: w,+ height: h,+ rgba: pdfcraft_render::Pixels::from(vec![u32::MAX; rgba_bytes(w as usize, h as usize) / 4]),+ text: None,+ error: None,+ warnings: Vec::new(),+ millis: 0,+ }+ }++ /// #3149: the replacement dialog commits after the canvas collected this frame's demand.+ #[test]+ fn replacing_a_page_after_layout_never_uploads_an_oversized_texture() {+ let ctx = egui::Context::default();+ ctx.input_mut(|i| i.max_texture_side = 2048);+ let mut app = PdfCraftApp::new();+ let original = app.session.create_blank(200.0, 300.0, 1).unwrap();+ let replacement = app.session.create_blank(400.0, 500.0, 1).unwrap();+ app.open_bytes("original.pdf", None, original.as_ref().clone()).unwrap();+ let request = RenderRequest { scale: 4.7, tag: scale_tag(4.7), ..Default::default() };+ app.views[0].frame_queue = vec![request];+ app.views[0].frame_visible.insert(0);+ assert!(app.apply_edit(Edit::ReplacePages { pages: vec![0], name: "replacement.pdf".into(), bytes: replacement, src_pages: vec![0] }));+ let doc = app.session.get(app.views[0].id).unwrap();+ assert_eq!((doc.info.pages[0].width, doc.info.pages[0].height), (400.0, 500.0));+ let edited_bytes = doc.bytes.clone();+ let pool = RenderPool::new_inline(doc.display.clone(), Default::default());+ app.views[0].finish_render_frame(&ctx, &doc.info, &pool);+ assert!(app.views[0].last_queue.is_empty(), "old geometry must not reach the replacement renderer");++ // The next layout can render a bounded backdrop and sharp tiles at the same zoom.+ let backdrop = RenderRequest { scale: 2048.0 / 500.0, tag: scale_tag(2048.0 / 500.0), ..request };+ let tile = RenderRequest { tile: Some(Tile { x: 0, y: 0, w: 1024, h: 1024 }), ..request };+ for _ in 0..2 {+ let view = &mut app.views[0];+ view.begin_render_frame();+ view.frame_visible.insert(0);+ view.frame_queue = vec![backdrop, tile];+ view.finish_render_frame(&ctx, &doc.info, &pool);+ }+ let view = &app.views[0];+ assert_eq!(view.pages.get(&0).unwrap().tex.size(), [1639, 2048]);+ assert_eq!(view.tiles.get(&(0, tile.tag, 0, 0)).unwrap().size(), [1024, 1024]);+ assert!(view.errors.is_empty());+ assert_eq!(doc.bytes, edited_bytes, "rendering preserves the unsaved edit");+ assert!(doc.dirty);+ assert_eq!(doc.can_undo(), Some("Replace page"));+ }++ #[test]+ fn oversized_raster_results_do_not_replace_cached_textures() {+ let ctx = egui::Context::default();+ ctx.input_mut(|i| i.max_texture_side = 64);+ for request in [+ RenderRequest::default(),+ RenderRequest { tag: THUMB_TAG, ..Default::default() },+ RenderRequest { tag: GRID_TAG, ..Default::default() },+ RenderRequest { tag: PRINT_TAG, ..Default::default() },+ RenderRequest { tile: Some(Tile { x: 0, y: 0, w: 64, h: 32 }), ..Default::default() },+ ] {+ let mut view = DocView::new(DocId(1), &thumbnail_info(1), ViewDefaults::default());+ view.last_queue = vec![request];+ let texture = |v: &DocView| {+ v.pages+ .values()+ .map(|p| &p.tex)+ .chain(v.thumbs.values().map(|p| &p.tex))+ .chain(v.grid_pages.values().map(|(_, t)| t))+ .chain(v.print_pages.values().map(|(_, t)| t))+ .chain(v.tiles.values())+ .map(|t| (t.id(), t.size()))+ .collect::<Vec<_>>()+ };+ assert_eq!(view.receive_result(&ctx, solid_result(request, 64, 32)), 64 * 32 * 4);+ let cached = texture(&view);+ assert_eq!(cached.len(), 1);+ for (w, h) in [(65, 32), (32, 65), (65, 65), (0, 32), (32, 0)] {+ assert_eq!(view.receive_result(&ctx, solid_result(request, w, h)), 0, "{request:?}: {w}x{h}");+ assert_eq!(texture(&view), cached, "an invalid result must keep the previous raster");+ }+ assert_eq!(view.receive_result(&ctx, solid_result(request, 32, 64)), 32 * 64 * 4);+ assert_eq!(texture(&view)[0].1, [32, 64], "valid results still make progress");+ }+ }++ /// A print preview carries the renderer's print bit; the bit that asks for luminance is+ /// its own, so a colour preview is not converted to monochrome and the two modes are told+ /// apart by their tags.+ #[test]+ fn print_preview_tag_distinguishes_grayscale_from_colour() {+ let mut v = view(1, PageLayout::Single, true);+ v.set_print_grayscale(false);+ v.queue_print_previews(&[(0, 1.0)]);+ let colour = v.frame_queue.last().expect("a print preview was queued").tag;+ assert_ne!(colour & PRINT_TAG, 0, "a print preview carries the renderer's print bit");+ assert_eq!(colour & GRAYSCALE_TAG, 0, "a colour print preview must not ask for luminance");++ v.set_print_grayscale(true);+ v.queue_print_previews(&[(0, 1.0)]);+ let gray = v.frame_queue.last().expect("a grayscale print preview was queued").tag;+ assert_ne!(gray & GRAYSCALE_TAG, 0, "a grayscale print preview asks for luminance");+ assert_ne!(gray, colour, "the two print preview modes must not share a tag");+ }++ #[test]+ fn thumbnails_release_on_scroll_panel_close_and_request_again_after_eviction() {+ let ctx = egui::Context::default();+ let info = thumbnail_info(10_000);+ let mut v = DocView::new(DocId(1), &info, ViewDefaults::default());+ v.need_thumbnail(0, true);+ let first = v.prepare_render_queue(&info, 1.0);+ v.last_queue = first.clone();+ assert_eq!(v.receive_result(&ctx, solid_result(first[0], 132, 171)), 132 * 171 * 4);+ assert!(v.prepare_render_queue(&info, 1.0).is_empty());+ v.begin_render_frame();+ v.need_thumbnail(9999, true);+ v.prepare_render_queue(&info, 1.0);+ assert!(v.thumbs.is_empty(), "jump releases old handles");+ v.begin_render_frame();+ v.need_thumbnail(0, true);+ assert_eq!(v.prepare_render_queue(&info, 1.0), first, "an evicted result must be requested again");+ v.begin_render_frame();+ assert!(v.prepare_render_queue(&info, 1.0).is_empty(), "closing consumers cancels thumbnail work");+ }++ #[test]+ fn stale_results_are_rejected_before_conversion_after_dpi_invalidation_and_suspend() {+ let ctx = egui::Context::default();+ let info = thumbnail_info(1);+ let mut v = DocView::new(DocId(1), &info, ViewDefaults::default());+ v.need_thumbnail(0, true);+ let first = v.prepare_render_queue(&info, 1.0)[0];+ v.last_queue = v.prepare_render_queue(&info, 2.0);+ // Valid pixels: only the request gate can keep these out (a size check can't).+ let obsolete = || solid_result(first, 132, 171);+ assert_eq!(v.receive_result(&ctx, obsolete()), 0);+ assert!(v.thumbs.is_empty(), "a result for the old DPI is not uploaded");+ // The same result is uploaded while its request is current.+ v.last_queue = vec![first];+ assert_eq!(v.receive_result(&ctx, obsolete()), 132 * 171 * 4);+ v.thumbs.clear();+ v.invalidate_content();+ assert_eq!(v.receive_result(&ctx, obsolete()), 0);+ assert!(v.thumbs.is_empty(), "nor after the content changed");+ let pool = RenderPool::new_inline(Arc::new(Vec::new()), Default::default());+ v.last_queue = vec![first];+ v.suspend_rendering(&pool);+ assert_eq!(v.receive_result(&ctx, obsolete()), 0);+ assert!(v.thumbs.is_empty(), "nor after the tab was suspended");+ }++ #[test]+ fn editing_after_layout_preserves_stale_page_until_replacement() {+ let ctx = egui::Context::default();+ let info = thumbnail_info(1);+ let mut v = DocView::new(DocId(1), &info, ViewDefaults::default());+ let req = RenderRequest { scale: 1.0, tag: 1000, ..Default::default() };+ v.last_queue = vec![req];+ v.receive_result(&ctx, solid_result(req, 10, 10));+ v.frame_queue = vec![req];+ v.page_changed(0);+ assert_eq!(v.prepare_render_queue(&info, 1.0), vec![req]);+ assert_eq!(v.pages.get(&0).unwrap().tag, STALE_TAG);+ }++ /// #1858: a released drawing stays painted from its points until a raster that has it+ /// arrives. A page raster that lands before the drawing's edit is applied (in full screen the+ /// edit waits for the next frame, and a render already under way can finish first) is of the+ /// document without it, and must not end the preview.+ #[test]+ fn a_raster_from_before_a_drawing_is_committed_keeps_it_drawn() {+ let ctx = egui::Context::default();+ let info = thumbnail_info(1);+ let mut v = DocView::new(DocId(1), &info, ViewDefaults::default());+ let req = RenderRequest { scale: 1.0, tag: 1000, ..Default::default() };+ v.comments.settle(0.0, 0, crate::comments::CommentTool::Ink, &[[10.0, 10.0], [40.0, 30.0]]);+ v.last_queue = vec![req];+ assert!(v.receive_result(&ctx, solid_result(req, 10, 10)) > 0, "the raster is taken");+ assert_eq!(v.comments.settling_len(), 1, "a raster from before the commit doesn't have the stroke");+ v.comments.drawings_committed();+ v.last_queue = vec![req];+ assert!(v.receive_result(&ctx, solid_result(req, 10, 10)) > 0);+ assert_eq!(v.comments.settling_len(), 0, "a raster after the commit draws it");+ // An edit that fails leaves nothing to wait for.+ v.comments.settle(0.0, 0, crate::comments::CommentTool::Ink, &[[10.0, 10.0], [40.0, 30.0]]);+ v.comments.drawings_refused();+ assert_eq!(v.comments.settling_len(), 0, "a refused drawing isn't left painted");+ }++ #[test]+ fn page_and_tile_admission_accounts_for_bytes_before_count_limits() {+ let mut info = thumbnail_info(40);+ for p in &mut info.pages {+ p.width = 4000.0;+ p.height = 4000.0;+ }+ let mut v = DocView::new(DocId(1), &info, ViewDefaults::default());+ v.frame_queue = (0..40).map(|page| RenderRequest { page, scale: 1.0, tag: 1000, ..Default::default() }).collect();+ let queue = v.prepare_render_queue(&info, 1.0);+ assert_eq!(queue.len(), 2, "128 MiB admits two 4000-square pages, not 24");+ v.frame_queue = (0..40)+ .map(|page| RenderRequest { page, scale: 1.0, tag: 1000, tile: Some(Tile { x: 0, y: 0, w: 1024, h: 1024 }), ..Default::default() })+ .collect();+ assert_eq!(v.prepare_render_queue(&info, 1.0).len(), 32);+ assert!(!v.admit_texture(RenderRequest::default(), PAGE_BYTES + 1));+ }++ #[test]+ fn on_screen_pages_and_tiles_are_admitted_beyond_the_prefetch_allowance() {+ let ctx = egui::Context::default();+ let mut info = thumbnail_info(40);+ for p in &mut info.pages {+ p.width = 2000.0;+ p.height = 2000.0;+ }+ let mut v = DocView::new(DocId(1), &info, ViewDefaults::default());+ // Ten 16 MB pages on screen (a zoomed-out HiDPI view) exceed the 128 MiB allowance.+ v.frame_visible = (0..10).collect();+ v.frame_queue = (0..40).map(|page| RenderRequest { page, scale: 1.0, tag: 1000, ..Default::default() }).collect();+ let queue = v.prepare_render_queue(&info, 1.0);+ let pages: Vec<usize> = queue.iter().map(|r| r.page).collect();+ assert_eq!(pages, (0..10).collect::<Vec<_>>(), "every on-screen page, and no prefetch past the allowance");+ v.last_queue = queue.clone();+ for req in &queue {+ assert!(v.receive_result(&ctx, solid_result(*req, 2000, 2000)) > 0, "on-screen page {} uploaded", req.page);+ }+ assert_eq!(v.pages.len(), 10, "none evicted another on-screen page");+ // A 5K viewport needs more 1024-pixel tiles than the tile allowance holds.+ v.frame_queue = (0..40)+ .map(|x| RenderRequest { page: 0, scale: 1.0, tag: 1000, tile: Some(Tile { x: x * TILE, y: 0, w: 1024, h: 1024 }), ..Default::default() })+ .collect();+ assert_eq!(v.prepare_render_queue(&info, 1.0).len(), 40);+ }++ #[test]+ fn a_page_turned_back_to_is_still_cached() {+ let ctx = egui::Context::default();+ let info = thumbnail_info(10);+ let mut v = DocView::new(DocId(1), &info, ViewDefaults::default());+ let req = |page| RenderRequest { page, scale: 1.0, tag: 1000, ..Default::default() };+ v.frame_visible = [0].into();+ v.frame_queue = vec![req(0)];+ v.last_queue = v.prepare_render_queue(&info, 1.0);+ v.receive_result(&ctx, solid_result(req(0), 100, 130));+ // Single-page view moves on to page 1: page 0 is no longer demanded.+ v.begin_render_frame();+ v.current = 1;+ v.frame_visible = [1].into();+ v.frame_queue = vec![req(1)];+ assert_eq!(v.prepare_render_queue(&info, 1.0), vec![req(1)]);+ assert!(v.pages.contains_key(&0), "kept while the allowance has room");+ // And back: nothing to render.+ v.begin_render_frame();+ v.current = 0;+ v.frame_visible = [0].into();+ v.frame_queue = vec![req(0)];+ assert!(v.prepare_render_queue(&info, 1.0).is_empty());+ }++ #[test]+ fn visible_pages_render_before_thumbnails_and_text() {+ let ctx = egui::Context::default();+ let info = thumbnail_info(4);+ let mut v = DocView::new(DocId(1), &info, ViewDefaults::default());+ let main = RenderRequest { page: 0, scale: 1.0, tag: 1000, ..Default::default() };+ let text = RenderRequest { page: 0, kind: RequestKind::Text, scale: 1.0, tag: TEXT_TAG, ..Default::default() };+ // Opening page 0 queues its pixels and text alongside Pages-panel thumbnails.+ v.begin_render_frame();+ v.frame_visible = [0].into();+ v.frame_queue = vec![main, text];+ for p in 1..4 {+ v.need_thumbnail(p, true);+ }+ let queue = v.prepare_render_queue(&info, 1.0);+ assert_eq!(queue, vec![main], "visible pixels first: no thumbnails or text yet");+ // Once the visible raster arrives, background work is admitted.+ v.last_queue = queue;+ assert!(v.receive_result(&ctx, solid_result(main, 100, 130)) > 0);+ v.begin_render_frame();+ v.frame_visible = [0].into();+ v.frame_queue = vec![text];+ for p in 1..4 {+ v.need_thumbnail(p, true);+ }+ let queue = v.prepare_render_queue(&info, 1.0);+ assert!(queue.iter().any(|r| r.kind == RequestKind::Text), "text admitted after pixels");+ assert!(queue.iter().any(|r| r.tag & THUMB_TAG != 0), "thumbnails admitted after pixels");+ assert!(!queue.iter().any(|r| r.kind == RequestKind::Pixels && r.tag & THUMB_TAG == 0), "no main pixels re-requested");+ // An errored visible page never holds background work back.+ v.errors.insert(0, "gone".to_string());+ v.begin_render_frame();+ v.frame_visible = [0].into();+ v.frame_queue = vec![main, text];+ for p in 1..4 {+ v.need_thumbnail(p, true);+ }+ let queue = v.prepare_render_queue(&info, 1.0);+ assert!(queue.iter().any(|r| r.kind == RequestKind::Text), "text admitted despite the error");+ assert!(queue.iter().any(|r| r.tag & THUMB_TAG != 0), "thumbnails still admitted");+ }++ #[test]+ fn thumbnail_tags_do_not_change_as_a_row_scrolls_in_or_out() {+ let info = thumbnail_info(10_000);+ let mut v = DocView::new(DocId(1), &info, ViewDefaults::default());+ let tags = |v: &mut DocView, cells: usize| {+ v.begin_render_frame();+ for page in 0..cells {+ v.need_thumbnail(page, true);+ }+ v.thumbnail_requests(&info, 2.0).into_iter().map(|r| (r.page, r.tag)).collect::<HashMap<_, _>>()+ };+ // 2x on a large screen: about 70 cells, give or take a row of six.+ let (a, b) = (tags(&mut v, 70), tags(&mut v, 76));+ assert!((0..70).all(|p| a[&p] == b[&p]), "a row more or less re-renders nothing");+ }++ #[test]+ fn many_open_documents_share_one_raster_allowance_and_close_releases_handles() {+ let ctx = egui::Context::default();+ let mut app = PdfCraftApp::new();+ let bytes = app.session.create_blank(612.0, 792.0, 1).unwrap();+ let mut expected = Vec::new();+ for index in 0..6 {+ app.open_bytes(&format!("synthetic-{index}.pdf"), None, bytes.as_ref().clone()).unwrap();+ let info = app.session.get(app.views.last().unwrap().id).unwrap().info.clone();+ let view = app.views.last_mut().unwrap();+ view.begin_render_frame();+ view.need_thumbnail(0, true);+ let request = view.thumbnail_requests(&info, ctx.pixels_per_point()).into_iter().next().unwrap();+ let page = info.pages.get(request.page).unwrap();+ let dimensions = (device_pixels(page.width, request.scale), device_pixels(page.height, request.scale));+ view.last_queue = vec![request];+ assert_eq!(+ view.receive_result(&ctx, solid_result(request, dimensions.0, dimensions.1)),+ rgba_bytes(dimensions.0 as usize, dimensions.1 as usize)+ );+ assert_eq!(view.thumbs.get(&0).unwrap().tag, request.tag);+ assert_eq!(view.thumbs.get(&0).unwrap().tex.size(), [dimensions.0 as usize, dimensions.1 as usize]);++ view.begin_render_frame();+ view.need_thumbnail(0, true);+ let queue = view.prepare_render_queue(&info, ctx.pixels_per_point());+ assert!(queue.is_empty(), "the synthetic thumbnail satisfies current demand");+ view.last_queue = queue;+ expected.push((request, dimensions));+ }+ assert_eq!(app.views.len(), 6, "all six documents were opened");+ assert_eq!(app.active_ids().map(|(index, _)| index), Some(5));+ assert!(app.views.iter().zip(&expected).all(|(view, (request, dimensions))| {+ view.thumbs.len() == 1+ && view.thumbs.get(&0).is_some_and(|thumb| thumb.tag == request.tag && thumb.tex.size() == [dimensions.0 as usize, dimensions.1 as usize])+ }));++ app.finish_render_frame(&ctx);+ let total: usize = app.views.iter().map(|v| v.thumbs.values().map(|p| texture_bytes(&p.tex)).sum::<usize>()).sum();+ let (active_request, active_dimensions) = expected.last().unwrap();+ let active_bytes = rgba_bytes(active_dimensions.0 as usize, active_dimensions.1 as usize);+ assert_eq!(total, active_bytes, "only the active view retains a thumbnail");+ assert!(total <= THUMB_BYTES, "retained thumbnails stay within the existing allowance");+ assert!(app.views.iter().take(5).all(|v| v.thumbs.is_empty() && v.last_queue.is_empty()));+ let active = app.views.last().unwrap();+ assert_eq!(active.thumbs.len(), 1);+ assert_eq!(active.thumbs.get(&0).unwrap().tag, active_request.tag);+ assert!(active.last_queue.is_empty(), "the current thumbnail is already cached");+ for view in &app.views {+ let doc = app.session.get(view.id).unwrap();+ assert_eq!(doc.renderer.stats().render_requests, 0, "the fixture must not launch a native render");+ }++ app.close_tab(5);+ assert_eq!(app.views.len(), 5, "closing the active tab drops its owning view");+ assert!(app.views.iter().all(|v| v.thumbs.is_empty()));+ }++ #[test]+ fn suspended_signature_preview_releases_layers_and_rebuilds_without_editing() {+ let ctx = egui::Context::default();+ let mut png = std::io::Cursor::new(Vec::new());+ image::RgbaImage::from_pixel(12, 4, image::Rgba([20, 30, 40, 255])).write_to(&mut png, image::ImageFormat::Png).unwrap();+ let image = pdfcraft_engine::SignatureImage::from_bytes(png.get_ref()).unwrap();+ let mut session = pdfcraft_engine::Session::new();+ let blank = session.create_blank(300.0, 400.0, 1).unwrap();+ let id = session.open_new("signature-preview.pdf", blank).unwrap();+ let info = session.get(id).unwrap().info.pages[0].clone();+ session.apply(id, image.edit(0, &info, [20.0, 100.0], false, "Test").unwrap()).unwrap();+ let doc = session.get(id).unwrap();+ let bytes = doc.bytes.clone();+ let generation = doc.edit_generation();+ let mut v = DocView::new(id, &doc.info, ViewDefaults::default());+ v.comments.selected = Some((0, 0));+ v.signature_drag.prepare(&ctx, doc, v.comments.selected, 1.0);+ assert!(v.signature_drag.contains(0, 0));++ v.suspend_rendering(&doc.renderer);+ assert!(!v.signature_drag.contains(0, 0), "inactive tabs release the preview pool and textures");+ assert_eq!(v.comments.selected, Some((0, 0)), "the user's selection survives suspension");+ v.signature_drag.prepare(&ctx, doc, v.comments.selected, 1.0);+ assert!(v.signature_drag.contains(0, 0), "reactivating the view rebuilds the selected image's preview");+ assert!(Arc::ptr_eq(&bytes, &doc.bytes));+ assert_eq!(doc.edit_generation(), generation);+ assert_eq!(doc.can_undo(), Some("Add signature"));+ assert!(doc.dirty);+ }++ #[test]+ fn suspending_a_view_releases_owned_raster_textures_and_queue_state() {+ let ctx = egui::Context::default();+ let mut view = view(2, PageLayout::Single, true);+ let texture = |name| ctx.load_texture(name, egui::ColorImage::filled([1, 1], Color32::WHITE), TextureOptions::LINEAR);+ let request = RenderRequest { page: 0, scale: 1.0, tag: 1, ..Default::default() };+ view.pages.insert(0, PageTex { tag: request.tag, tex: texture("suspended-page") });+ view.thumbs.insert(1, PageTex { tag: THUMB_TAG, tex: texture("suspended-thumbnail") });+ view.tiles.insert((0, request.tag, 0, 0), texture("suspended-tile"));+ view.grid_pages.insert(1, (1, texture("suspended-grid-page")));+ view.print_pages.insert(1, (PRINT_TAG, texture("suspended-print-page")));+ view.stale_thumbs.insert(1);+ view.waiting_since.insert(0, 1.0);+ view.last_queue = vec![request];+ view.frame_queue = vec![request];+ view.frame_visible.insert(0);+ view.need_thumbnail(1, true);++ let pool = RenderPool::new_inline(Arc::new(Vec::new()), Default::default());+ view.suspend_rendering(&pool);++ assert!(view.pages.is_empty(), "page handles are released");+ assert!(view.thumbs.is_empty(), "thumbnail handles are released");+ assert!(view.tiles.is_empty(), "tile handles are released");+ assert!(view.grid_pages.is_empty(), "organize-grid handles are released");+ assert!(view.print_pages.is_empty(), "print-preview handles are released");+ assert!(view.stale_thumbs.is_empty(), "stale thumbnail bookkeeping is cleared");+ assert!(view.waiting_since.is_empty(), "waiting bookkeeping is cleared");+ assert!(view.last_queue.is_empty() && !view.render_pending(), "queued demand is retired");+ assert!(view.frame_queue.is_empty() && view.frame_visible.is_empty() && view.thumb_demand.is_empty());+ }++ /// Edit text & images keeps its boxes while page input is blocked (the window unfocused, a+ /// dialog or the palette open): the page's paragraphs are still measured for the latest edit+ /// and drawn, instead of vanishing until the pointer comes back.+ #[test]+ fn edit_text_boxes_stay_drawn_while_page_input_is_blocked() {+ let mut h = egui_kittest::Harness::builder().with_size(vec2(1400.0, 900.0)).build_eframe(|_cc| {+ let mut app = PdfCraftApp::new();+ let bytes = app.session.create_blank(300.0, 400.0, 1).unwrap();+ app.open_bytes("blank.pdf", None, bytes.as_ref().clone()).unwrap();+ app.quick_tool = QuickTool::EditText;+ app+ });+ h.run_steps(3);+ // Block page input the way the window losing focus does.+ h.state_mut().palette_open = true;+ h.run_steps(2);+ assert!(h.state_mut().apply_edit(Edit::RotatePages { pages: vec![0], degrees: 90 }));+ h.run_steps(3);+ let app = h.state();+ let generation = app.session.get(app.views[0].id).unwrap().edit_generation();+ assert_eq!(app.views[0].edit_lines.get(&0).map(|(g, _)| *g), Some(generation), "the boxes follow the edit while input is blocked");+ }++ #[test]+ fn virtualized_organizer_keeps_insert_gaps_at_document_positions() {+ use egui_kittest::kittest::Queryable;++ let mut h = egui_kittest::Harness::builder().with_size(vec2(1400.0, 900.0)).build_eframe(|_cc| {+ let mut app = PdfCraftApp::new();+ let bytes = app.session.create_blank(300.0, 400.0, 100).unwrap();+ app.open_bytes("organize-gaps.pdf", None, bytes.as_ref().clone()).unwrap();+ app.views[0].organize = true;+ app+ });+ h.run_steps(4);+ assert!(h.state().views[0].thumb_demand.len() < 50);+ assert_eq!(h.query_all_by_label("Insert a file at the end").count(), 0, "the last virtualized cell is not the final page");+ let center = h.state().views[0].viewport_rect().center();+ h.hover_at(center);+ h.event(egui::Event::MouseWheel {+ unit: egui::MouseWheelUnit::Point,+ delta: vec2(0.0, -100_000.0),+ phase: egui::TouchPhase::Move,+ modifiers: egui::Modifiers::NONE,+ source: egui::MouseWheelSource::Unknown,+ });+ // Well past egui's longest scroll animation (about 0.3 s).+ h.run_steps(40);+ h.get_by_label("Insert a file at the end");+ let before_last = h.get_by_label("Insert a file before page 100").rect().center();+ h.hover_at(before_last);+ h.run_steps(2);+ assert_eq!(h.state().views[0].grid_gap, Some(99), "external drops use the document index after virtualized scrolling");+ assert!(h.state().views[0].thumb_demand.len() < 50);+ }++ #[test]+ fn real_shell_pages_organizer_and_print_only_collect_current_thumbnail_consumers() {+ let mut h = egui_kittest::Harness::builder().with_size(vec2(1400.0, 900.0)).build_eframe(|_cc| {+ let mut app = PdfCraftApp::new();+ let bytes = app.session.create_blank(612.0, 792.0, 10_000).unwrap();+ app.open_bytes("synthetic-ten-thousand.pdf", None, bytes.as_ref().clone()).unwrap();+ app.right = Some(RightPanel::Pages);+ app+ });+ h.run_steps(4);+ assert!((1..20).contains(&h.state().views[0].thumb_demand.len()));+ h.state_mut().right = None;+ h.state_mut().views[0].organize = true;+ h.run_steps(2);+ assert!((1..50).contains(&h.state().views[0].thumb_demand.len()));+ h.state_mut().views[0].organize = false;+ h.state_mut().dialog = Some(crate::Dialog::Print);+ h.state_mut().print_draft.sheet = 9999;+ h.run_steps(2);+ assert_eq!(h.state().views[0].thumb_demand.keys().copied().collect::<Vec<_>>(), vec![9999]);+ h.state_mut().print_draft.handling = crate::PrintHandling::Booklet;+ h.state_mut().print_draft.sheet = 0;+ h.run_steps(2);+ assert_eq!(h.state().views[0].thumb_demand.len(), 2, "booklet only needs its two placed pages");+ h.state_mut().dialog = None;+ h.run_steps(2);+ assert!(h.state().views[0].thumb_demand.is_empty());+ assert!(h.state().views[0].thumbs.is_empty());+ }++ /// One mouse-wheel notch (a line) at `at` seconds.+ fn notch(v: &mut DocView, dy: f32, at: f64) -> bool {+ v.single_page_wheel(egui::MouseWheelUnit::Line, dy, egui::TouchPhase::Move, at, true)+ }++ #[test]+ fn thumbnails_cover_the_panel_on_a_high_dpi_screen() {+ // Pages panel slot is at most 150 logical points. At 2 px/pt a letter page's thumbnail+ // must be at least that wide, so the panel samples it down instead of stretching it.+ let info = thumbnail_info(1);+ let mut v = DocView::new(DocId(1), &info, ViewDefaults::default());+ v.need_thumbnail(0, true);+ let queue = v.prepare_render_queue(&info, 2.0);+ let scale = queue.first().expect("one thumbnail").scale;+ assert!(612.0 * scale >= 150.0 * 2.0, "{scale}");+ }++ #[test]+ fn notches_turn_pages_and_stop_at_the_ends() {+ let mut v = view(3, PageLayout::Single, false);+ assert!(notch(&mut v, -1.0, 1.0) && notch(&mut v, -1.0, 1.05));+ assert_eq!(v.current, 2);+ assert!(!notch(&mut v, -1.0, 1.1), "nothing turns past the last page");+ assert!(notch(&mut v, 1.0, 1.2));+ assert_eq!(v.current, 1);+ }++ #[test]+ fn notches_turn_two_page_spreads() {+ // Two-page view, shown one spread at a time (not continuous): a notch turns a whole+ // spread at once, not a single page (#752).+ let mut v = view(4, PageLayout::TwoUp, false);+ assert!(notch(&mut v, -1.0, 1.0));+ assert_eq!(v.current, 2, "a notch turns from the first spread to the second");+ assert!(notch(&mut v, 1.0, 1.1));+ assert_eq!(v.current, 0, "a notch back turns to the previous spread");+ }++ #[test]+ fn continuous_views_ignore_the_wheel_for_paging() {+ // Scrolling views let the ScrollArea handle the wheel; it never turns pages.+ for layout in [PageLayout::Single, PageLayout::TwoUp] {+ let mut v = view(3, layout, true);+ assert!(!notch(&mut v, -1.0, 1.0), "{layout:?} continuous ignores the wheel");+ assert_eq!(v.current, 0);+ }+ }++ #[test]+ fn navigation_drops_partial_wheel_motion() {+ use egui::{MouseWheelUnit::Point, TouchPhase::Move, TouchPhase::Start};+ let mut v = view(3, PageLayout::Single, false);+ assert!(!v.single_page_wheel(Point, 0.0, Start, 1.0, true));+ assert!(!v.single_page_wheel(Point, -30.0, Move, 1.02, true));+ v.go_to_page(1);+ // The same touch has to move a full notch's worth again before it turns.+ assert!(!v.single_page_wheel(Point, -30.0, Move, 1.04, true));+ assert!(v.single_page_wheel(Point, -30.0, Move, 1.06, true));+ assert_eq!(v.current, 2);+ }++ #[test]+ fn reselecting_the_layout_does_not_scroll_to_top() {+ let mut v = view(3, PageLayout::Single, true);+ v.goto = None;+ v.set_layout(PageLayout::Single);+ assert!(v.goto.is_none(), "re-selecting the current layout is a no-op");+ v.set_continuous(true);+ assert!(v.goto.is_none(), "re-selecting the current continuity is a no-op");+ v.set_layout(PageLayout::TwoUp);+ assert_eq!(v.goto, Some((0, 0.0)), "switching the base layout aligns the current page");+ v.goto = None;+ v.set_continuous(false);+ assert_eq!(v.goto, Some((0, 0.0)), "toggling continuous scrolling aligns the current page");+ }++ #[test]+ fn fit_page_and_height_hold_still_while_mixed_page_sizes_scroll_past() {+ let page =+ |width: f32, height: f32| pdfcraft_render::PageInfo { width, height, label: String::new(), crop: [0.0, 0.0, width, height], rotation: 0 };+ let info = DocInfo { pages: vec![page(300.0, 400.0), page(600.0, 800.0)], ..Default::default() };+ for fit in [Fit::Page, Fit::Height] {+ let mut v = DocView::new(DocId(1), &info, ViewDefaults::default());+ (v.fit, v.viewport_w, v.viewport_h) = (fit, 1000.0, 800.0);+ v.fit_zoom(&info);+ let zoom = v.zoom;+ v.current = 1;+ v.fit_zoom(&info);+ assert_eq!(v.zoom, zoom, "{fit:?}: scrolling onto a bigger page keeps the zoom");+ // A single page shown on its own (not scrolling) fits each one.+ (v.layout, v.continuous) = (PageLayout::Single, false);+ v.fit_zoom(&info);+ let big = v.zoom;+ v.current = 0;+ v.fit_zoom(&info);+ assert!(v.zoom > big, "{fit:?}: single-page view fits the page it shows");+ }+ }++ /// Review on #2070: full screen in two-page view fits the spread it shows, the cover page+ /// on its own included; two-page view in the window keeps one zoom for the document.+ #[test]+ fn full_screen_two_page_view_fits_the_spread_it_shows() {+ let page =+ |width: f32, height: f32| pdfcraft_render::PageInfo { width, height, label: String::new(), crop: [0.0, 0.0, width, height], rotation: 0 };+ // Spreads [0, 1] small, [2, 3] large; with a cover page [0], [1, 2] mixed, [3].+ let info = DocInfo { pages: vec![page(300.0, 400.0), page(300.0, 400.0), page(600.0, 800.0), page(600.0, 800.0)], ..Default::default() };+ let mut v = DocView::new(DocId(1), &info, ViewDefaults::default());+ (v.layout, v.continuous, v.viewport_w, v.viewport_h) = (PageLayout::TwoUp, false, 1000.0, 800.0);+ v.fit = Fit::Page;+ v.fit_zoom(&info);+ let windowed = v.zoom;+ v.enter_presentation();+ v.fit_zoom(&info);+ let small = v.zoom;+ assert!(small > windowed * 1.9, "the small spread fills the screen: {small} vs {windowed}");+ v.current = 3;+ v.fit_zoom(&info);+ assert!((v.zoom - windowed).abs() < 1e-4, "the large spread fits as before");+ v.current = 1;+ v.fit_zoom(&info);+ assert_eq!(v.zoom, small, "page 2 is in the first spread");+ // With a cover page: [0] alone, then [1, 2] (the large page decides), then [3].+ v.cover = true;+ v.current = 0;+ v.fit_zoom(&info);+ assert_eq!(v.zoom, small, "the cover page alone");+ v.current = 1;+ v.fit_zoom(&info);+ assert!((v.zoom - windowed).abs() < 1e-4, "page 2 shares a spread with the large page 3");+ // Scrolling while in full screen fits the document, as scrolling does in the window.+ (v.continuous, v.current) = (true, 0);+ v.fit_zoom(&info);+ assert!((v.zoom - windowed).abs() < 1e-4, "continuous full screen keeps one zoom");+ v.continuous = false;+ // The cover page is a spread of its own even when the next page is larger.+ let mixed = DocInfo { pages: vec![page(300.0, 400.0), page(600.0, 800.0), page(600.0, 800.0)], ..Default::default() };+ v.current = 0;+ v.fit_zoom(&mixed);+ assert_eq!(v.zoom, small, "the small cover alone, not with page 2");+ // Leaving full screen brings the document-wide fit back.+ v.leave_presentation();+ (v.fit, v.current) = (Fit::Page, 0);+ (v.layout, v.continuous) = (PageLayout::TwoUp, false);+ v.fit_zoom(&info);+ assert!((v.zoom - windowed).abs() < 1e-4, "in the window, one zoom for the document");+ }++ #[test]+ fn fit_width_fits_the_shown_page_in_single_page_view_only() {+ let page =+ |width: f32, height: f32| pdfcraft_render::PageInfo { width, height, label: String::new(), crop: [0.0, 0.0, width, height], rotation: 0 };+ let info = DocInfo { pages: vec![page(300.0, 400.0), page(600.0, 400.0)], ..Default::default() };+ let mut v = DocView::new(DocId(1), &info, ViewDefaults::default());+ (v.fit, v.viewport_w, v.viewport_h) = (Fit::Width, 1000.0, 800.0);+ v.layout = PageLayout::Single;+ v.continuous = false;+ v.fit_zoom(&info);+ let narrow = v.zoom;+ // The shown page fills the width between the side gutters, not centred for the wide page.+ let shown = v.layout(&info, v.content_width(&info, 1000.0), 1.0)[0];+ assert!((shown.left() - SIDE).abs() < 1e-2 && (shown.width() - 860.0).abs() < 1e-2, "{shown:?}");+ v.current = 1;+ v.fit_zoom(&info);+ assert!((narrow / v.zoom - 2.0).abs() < 1e-3, "the narrow page gets twice the zoom of the wide one");+ // Scrolling views keep one zoom for the whole document.+ v.continuous = true;+ v.fit_zoom(&info);+ let wide = v.zoom;+ v.current = 0;+ v.fit_zoom(&info);+ assert_eq!(v.zoom, wide, "continuous fit width holds still across page sizes");+ }++ #[test]+ fn layouts_match_their_commands_and_names() {+ for l in PageLayout::ORDER {+ let spec = pdfcraft_engine::commands::command(l.command()).expect("registered");+ assert_eq!((l.label(), l.icon()), (spec.label, spec.icon), "{l:?}");+ assert_eq!(PageLayout::from_command(l.command()), Some(l));+ assert_eq!(PageLayout::try_parse(l.as_str()), Some(l));+ }+ assert_eq!(PageLayout::try_parse(" Two-Up "), Some(PageLayout::TwoUp));+ assert_eq!(PageLayout::try_parse("facing"), None);+ }++ #[test]+ fn a_null_xyz_coordinate_keeps_the_readers_place_on_the_new_page() {+ // CAD exports link each cross-reference as `/XYZ null null 0`. Acrobat keeps the+ // point at the window's top-left (and the zoom) when following one to another sheet.+ let info = pdfcraft_render::DocInfo {+ pages: (0..3)+ .map(|_| pdfcraft_render::PageInfo { width: 842.0, height: 595.0, label: String::new(), crop: [0.0, 0.0, 842.0, 595.0], rotation: 0 })+ .collect(),+ ..Default::default()+ };+ // Page 1 at 400 %, scrolled so its point 200 pt across and 125 pt down is at the corner+ // where /XYZ puts its point.+ let zoomed = |rot: u16, size: Vec2| {+ let mut v = view(3, PageLayout::Single, true);+ v.rotation = rot;+ v.viewport_screen = Rect::from_min_size(Pos2::ZERO, vec2(1000.0, 600.0));+ v.screen_xforms = vec![(0, PageXform { rect: Rect::from_min_size(pos2(SIDE - 800.0, -500.0), size), rot, pw: 842.0, ph: 595.0 })];+ v+ };+ let near = |a: Option<f32>, b: f32| a.is_some_and(|a| (a - b).abs() < 1e-4);+ let mut v = zoomed(0, vec2(4.0 * 842.0, 4.0 * 595.0));+ v.go_to_dest(1, DestView::Xyz { left: None, top: None, zoom: None }, &info);+ let (page, fx, fy, rel) = v.goto_point.expect("the place is kept");+ assert_eq!((v.current, page, rel), (1, 1, vec2(SIDE, 0.0)));+ assert!(near(fx, 200.0 / 842.0) && near(fy, 125.0 / 595.0), "{fx:?} {fy:?}");+ // A coordinate the destination gives wins; only the null one is kept.+ let mut v = zoomed(0, vec2(4.0 * 842.0, 4.0 * 595.0));+ v.go_to_dest(2, DestView::Xyz { left: Some(421.0), top: None, zoom: Some(4.0) }, &info);+ let (_, fx, fy, _) = v.goto_point.expect("the place is kept");+ assert!(near(fx, 0.5) && near(fy, 125.0 / 595.0), "{fx:?} {fy:?}");+ // With the view turned a quarter, the point under the corner is still the one kept.+ let mut v = zoomed(90, vec2(4.0 * 595.0, 4.0 * 842.0));+ v.go_to_dest(1, DestView::Xyz { left: None, top: None, zoom: None }, &info);+ let (_, fx, fy, _) = v.goto_point.expect("the place is kept");+ assert!(near(fx, 800.0 / (4.0 * 595.0)) && near(fy, 500.0 / (4.0 * 842.0)), "{fx:?} {fy:?}");+ // A page that fits the window keeps the layout's placement: no point, as before.+ let mut v = zoomed(0, vec2(800.0, 565.0));+ v.go_to_dest(1, DestView::Xyz { left: None, top: None, zoom: None }, &info);+ assert_eq!((v.current, v.goto, v.goto_point), (1, Some((1, 0.0)), None));+ }++ #[test]+ fn destinations_set_the_zoom_mode_and_the_point_to_show() {+ let info = pdfcraft_render::DocInfo {+ pages: (0..3)+ .map(|_| pdfcraft_render::PageInfo { width: 300.0, height: 400.0, label: String::new(), crop: [0.0, 0.0, 300.0, 400.0], rotation: 0 })+ .collect(),+ ..Default::default()+ };+ let mut v = view(3, PageLayout::Single, true);+ v.fit = Fit::Width;+ // No position (or a malformed one): the top of the page, zoom as it was.+ v.go_to_dest(1, DestView::Top, &info);+ assert_eq!((v.current, v.goto, v.goto_point, v.fit), (1, Some((1, 0.0)), None, Fit::Width));+ // /XYZ with a null zoom keeps the zoom mode; its point is a quarter down page 3.+ v.go_to_dest(2, DestView::Xyz { left: None, top: Some(300.0), zoom: None }, &info);+ assert_eq!((v.current, v.fit, v.goto_point), (2, Fit::Width, Some((2, None, Some(0.25), vec2(SIDE, 0.0)))));+ v.go_to_dest(0, DestView::Xyz { left: Some(150.0), top: None, zoom: Some(2.5) }, &info);+ assert_eq!((v.fit, v.zoom, v.goto_point), (Fit::None, 2.5, Some((0, Some(0.5), None, vec2(SIDE, 0.0)))));+ // A zoom beyond the view's range is clamped to it.+ v.go_to_dest(0, DestView::Xyz { left: None, top: None, zoom: Some(1e30) }, &info);+ assert_eq!((v.zoom, v.goto_point), (64.0, None));+ v.go_to_dest(0, DestView::Fit, &info);+ assert_eq!((v.fit, v.goto_point), (Fit::Page, None));+ v.go_to_dest(0, DestView::FitH { top: Some(100.0) }, &info);+ assert_eq!((v.fit, v.goto_point), (Fit::Width, Some((0, None, Some(0.75), vec2(SIDE, 0.0)))));+ v.go_to_dest(0, DestView::FitV { left: Some(75.0) }, &info);+ assert_eq!((v.fit, v.goto_point), (Fit::Height, Some((0, Some(0.25), None, vec2(SIDE, 0.0)))));+ // /FitR: the zoom that fits a 100×50 pt rectangle in an 800×600 window, centred.+ (v.viewport_w, v.viewport_h) = (800.0, 600.0);+ v.go_to_dest(0, DestView::FitR { rect: [0.0, 300.0, 100.0, 350.0] }, &info);+ assert_eq!(v.fit, Fit::None);+ assert!((v.zoom - 8.0 / PT).abs() < 1e-4, "{}", v.zoom);+ let (page, fx, fy, rel) = v.goto_point.expect("a point to show");+ assert_eq!((page, rel), (0, vec2(400.0, 300.0)));+ assert!((fx.unwrap_or(-1.0) - 50.0 / 300.0).abs() < 1e-4 && (fy.unwrap_or(-1.0) - 75.0 / 400.0).abs() < 1e-4, "{fx:?} {fy:?}");+ // A page past the end goes to the last page; a page the document info lacks, to its top.+ v.go_to_dest(usize::MAX, DestView::FitH { top: Some(100.0) }, &info);+ assert_eq!((v.current, v.goto_point.map(|g| g.0)), (2, Some(2)));+ let empty = pdfcraft_render::DocInfo::default();+ v.go_to_dest(1, DestView::FitH { top: Some(100.0) }, &empty);+ assert_eq!((v.current, v.goto_point), (1, None));+ }++ #[test]+ fn page_text_failure_preserves_valid_search_match_without_jitter() {+ let mut v = view(3, PageLayout::Single, true);+ v.current = 1;+ v.find =+ Some(Find { query: "test".into(), case_query: "test".into(), matches: vec![(0, 0..4), (1, 5..9)], current: Some(0), ..Default::default() });+ let req = RenderRequest { page: 0, kind: RequestKind::Text, ..Default::default() };+ v.last_queue = vec![req];+ let ctx = egui::Context::default();+ v.receive_result(+ &ctx,+ pdfcraft_render::RenderedPage {+ request: req,+ width: 0,+ height: 0,+ rgba: Default::default(),+ error: Some("extraction failed".into()),+ text: None,+ warnings: Vec::new(),+ millis: 0,+ },+ );+ // Active match was on page 0 which failed: current should fall back to match on page 1 without jitter+ assert_eq!(v.find.as_ref().unwrap().current, Some(0));+ assert_eq!(v.find.as_ref().unwrap().matches, vec![(1, 5..9)]);+ assert!(v.goto.is_none());+ }++ /// A page whose picture moved can get its whole-page raster back before its last stale tile.+ /// From then on the raster has the picture where it went: it is drawn from there, not from+ /// where it was (which the raster now shows empty), and another drag starts from there too.+ #[test]+ fn a_moved_picture_is_drawn_from_the_fresh_raster_while_a_tile_is_still_stale() {+ let content = b"q 60 0 0 60 40 260 cm /Im0 Do Q";+ let objs: Vec<Vec<u8>> = vec![+ b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(),+ b"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 300 400] >>".to_vec(),+ b"<< /Type /Page /Parent 2 0 R /Contents 4 0 R /Resources << /XObject << /Im0 5 0 R >> >> >>".to_vec(),+ [format!("<< /Length {} >>\nstream\n", content.len()).as_bytes(), content.as_slice(), b"\nendstream"].concat(),+ [+ b"<< /Type /XObject /Subtype /Image /Width 1 /Height 1 /BitsPerComponent 8 /ColorSpace /DeviceRGB /Length 3 >>\nstream\n".as_slice(),+ &[200, 30, 30],+ b"\nendstream",+ ]+ .concat(),+ ];+ let mut bytes = b"%PDF-1.7\n".to_vec();+ let mut offsets = Vec::new();+ for (i, o) in objs.iter().enumerate() {+ offsets.push(bytes.len());+ bytes.extend_from_slice(format!("{} 0 obj\n", i + 1).as_bytes());+ bytes.extend_from_slice(o);+ bytes.extend_from_slice(b"\nendobj\n");+ }+ let xref = bytes.len();+ bytes.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes());+ for o in offsets {+ bytes.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());+ }+ bytes.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes());+ let mut h = egui_kittest::Harness::builder().with_size(vec2(1400.0, 1100.0)).build_eframe(move |_cc| {+ let mut app = PdfCraftApp::new();+ app.set_option("language", "en").unwrap();+ app.open_bytes("picture.pdf", None, bytes.clone()).unwrap();+ app.set_option("zoom", "100").unwrap();+ app.quick_tool = QuickTool::EditText;+ app+ });+ let settle = |h: &mut egui_kittest::Harness<'static, PdfCraftApp>| {+ for _ in 0..400 {+ h.step();+ if !h.state().render_pending() {+ return;+ }+ std::thread::sleep(std::time::Duration::from_millis(5));+ }+ };+ h.run_steps(4);+ settle(&mut h);+ let page = h.state().views[0].page_screen_rect(0).unwrap();+ let at = |x: f32, y: f32| egui::pos2(page.left() + x / 300.0 * page.width(), page.top() + (400.0 - y) / 400.0 * page.height());+ let red = |pixels: &image::RgbaImage, r: Rect| {+ let (w, hh) = (pixels.width(), pixels.height());+ (r.top().max(0.0) as u32..(r.bottom() as u32).min(hh))+ .flat_map(|y| (r.left().max(0.0) as u32..(r.right() as u32).min(w)).map(move |x| (x, y)))+ .filter(|(x, y)| matches!(pixels.get_pixel(*x, *y).0, [r, g, b, _] if r > 150 && g < 90 && b < 90))+ .count()+ };+ let (old, new) = (Rect::from_two_pos(at(42.0, 262.0), at(98.0, 318.0)), Rect::from_two_pos(at(182.0, 82.0), at(238.0, 138.0)));+ // Select the picture and drag it, without overlap, from (40, 260) to (180, 80).+ let drag = |h: &mut egui_kittest::Harness<'static, PdfCraftApp>, from: Pos2, to: Pos2, release: bool| {+ h.hover_at(from);+ h.run_steps(1);+ h.drag_at(from);+ h.run_steps(1);+ for k in 1..=4 {+ h.hover_at(from + (to - from) * (k as f32 / 4.0));+ h.run_steps(1);+ }+ if release {+ h.drop_at(to);+ h.step();+ }+ };+ let (grab, put) = (at(70.0, 290.0), at(210.0, 110.0));+ h.hover_at(grab);+ h.run_steps(1);+ h.drag_at(grab);+ h.run_steps(1);+ h.drop_at(grab);+ h.run_steps(3);+ assert!(h.state().views[0].image_selection.is_some(), "the picture is selected");+ h.state_mut().views[0].hold_rasters = true;+ drag(&mut h, grab, put, true);+ // One tile stays stale, as a tile result arriving after the whole-page raster would; then+ // the whole-page raster is let through.+ let tile = h.ctx.load_texture("stale-tile", egui::ColorImage::new([1, 1], vec![Color32::TRANSPARENT]), TextureOptions::LINEAR);+ h.state_mut().views[0].tiles.insert((0, 1, 0, 0), tile);+ h.state_mut().views[0].stale_tiles.insert((0, 1, 0, 0));+ h.state_mut().views[0].hold_rasters = false;+ for _ in 0..400 {+ h.step();+ if !h.state().views[0].page_raster_out_of_date(0) {+ break;+ }+ std::thread::sleep(std::time::Duration::from_millis(5));+ }+ assert!(!h.state().views[0].page_raster_out_of_date(0), "the whole-page raster is fresh");+ assert!(h.state().views[0].page_out_of_date(0), "a tile is still stale");+ h.run_steps(2);+ let pixels = h.render().unwrap();+ assert!(red(&pixels, new) > 100, "the picture shows where it went");+ assert_eq!(red(&pixels, old), 0, "and not where it was");+ // Another drag in that interval takes its pixels from where the raster has them.+ let further = at(210.0, 200.0);+ drag(&mut h, put, further, false);+ let pixels = h.render().unwrap();+ let moving = Rect::from_two_pos(at(182.0, 172.0), at(238.0, 228.0));+ assert!(red(&pixels, moving) > 100, "the dragged picture is drawn from the fresh raster");+ assert_eq!(red(&pixels, old), 0, "nothing shows where it first was");+ h.state_mut().views[0].stale_tiles.clear();+ h.state_mut().views[0].tiles.clear();+ }diff --cc crates/ui-egui/src/lib.rsindex f90969823,65bc7e4b1..e1a1f5dd3--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@@ -170,113 -60,109 +60,110 @@@ pub use files::{ExtractDraft, FilePurpopub use recovery::{AUTOSAVE_SECS, RecoveryMeta, RecoveryStore};use theme::{ThemeKind, ThemePreference};- /// Top-level workspace modes (Acrobat's mode bar).- #[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]- #[serde(rename_all = "lowercase")]- pub enum Mode {- #[serde(rename = "all")]- AllTools,- Read,- Edit,- Convert,- Sign,- }-- impl Mode {- fn parse(value: &str) -> Option<Self> {- match value {- "all" => Some(Self::AllTools),- "read" => Some(Self::Read),- "edit" => Some(Self::Edit),- "convert" => Some(Self::Convert),- "sign" => Some(Self::Sign),- _ => None,- }- }- }-- /// What the left panel shows.- #[derive(Clone, Copy, Debug, PartialEq, Eq)]- pub enum LeftPanel {- AllTools,- Tool(&'static str),- /// Prepare a form ▸ Calculation order, a page of its own; Back returns to Prepare a form.- CalculationOrder,- }-- /// Right-hand panels, opened from the rail.- #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]- pub enum RightPanel {- Comments,- Bookmarks,- Pages,- Fields,- Layers,- Attachments,- Signatures,- /// Accessibility Checker results.- Accessibility,- /// Reachable PDF structure tags and their properties.- Tags,- /// Advanced Search results.- Search,- /// Compare files: the differences.- Compare,- }-- /// Quick-action bar tools (the vertical floating strip).- #[derive(Clone, Copy, Debug, PartialEq, Eq)]- pub enum QuickTool {- Select,- Hand,- /// A commenting tool (Add comments).- Comment(comments::CommentTool),- Measure(measure_ui::Tool),- /// Crop pages by dragging a rectangle.- Crop,- /// Scan & OCR ▸ Enhance ▸ Camera image: drag four corners, then Enhance page.- EnhanceCamera,- /// A Fill & Sign tool.- Fill(fill_sign::FillTool),- /// A Prepare a form field tool.- Field(prepare::FieldTool),- /// Redact text and images (drag across text or draw a box).- Redact,- /// Edit a PDF ▸ Add content ▸ Text.- AddText,- /// Edit a PDF ▸ Edit text: click a line of existing text to edit it.- EditText,- /// Add a stamp: click to place this stamp.- Stamp(pdfcraft_engine::StampKind),- /// A custom stamp from the library (its index).- CustomStamp(usize),- /// Edit a PDF ▸ Link: draw link areas, select and edit links.- Link,- /// Use a certificate ▸ Digitally sign / Certify (visible): drag the signature's rectangle.- SignArea {- certify: bool,- },- /// View ▸ Zoom ▸ Marquee Zoom.- MarqueeZoom,- /// Edit ▸ Take a Snapshot.- Snapshot,- /// Edit ▸ Column Select: drag a rectangle to select only the text inside it (#740). The- /// Select tool does the same while Alt/Option is held at the start of a drag.- ColumnSelect,- }-- /// A file dropped on a page grid: its name, and its bytes or, for a file on disk, the path they are- /// read from when the file's turn to be inserted comes (so a long drop holds one file at a time).- type GridFile = (String, Result<Vec<u8>, std::path::PathBuf>);+ mod app;+ mod hooks;+ mod persist;+ mod platform;+ mod state;+ mod tools;+ mod workflows;- /// Read a file dropped on a page grid (see [`GridFile`]).- fn read_grid_file((name, source): GridFile) -> Result<(String, Vec<u8>), (String, String)> {- let bytes = match source {- Ok(bytes) => bytes,- Err(path) => std::fs::read(&path).map_err(|e| (name.clone(), e.to_string()))?,- };- Ok((name, bytes))- }+ #[cfg(not(target_arch = "wasm32"))]+ pub(crate) use app::same_file;+ pub(crate) use app::{MAX_AUTHOR_CHARS, copy_refused, date_text_for_pdf, print_refused};+ use canvas::autoscroll;+ use canvas::crop;+ use canvas::fling;+ use canvas::image_pick;++use canvas::page_cursor;+ use canvas::page_pointer;+ pub use canvas::scroll_speed;+ use canvas::signature_drag;+ use canvas::wheel_boost;+ use canvas::wheel_pager;+ use canvas::zoom_snap;+ use dialogs::appearance;+ use dialogs::comment_props;+ use dialogs::credits;+ use dialogs::marks_ui;+ use dialogs::pageboxes;+ use dialogs::palette;+ use dialogs::protect;+ use dialogs::standards_ui;+ use dialogs::word_count_ui;+ pub use home::folders_ui;+ pub use hooks::{FailedInbox, HostDirtyFn, HostSaveFn, Inbox, OsEvent, OsEventsFn};+ use menus::tab_context;+ use panels::all_tools_ui;+ use panels::comments_panel;+ use panels::format_text_ui;+ use panels::organize_panel;+ use panels::page_selection_ui;+ use panels::search_ui;+ pub use panels::side_panels;+ pub use persist::last_session;+ pub use persist::last_view;+ use persist::recovery;+ pub use persist::units;+ #[cfg(not(target_arch = "wasm32"))]+ pub use persist::window_state;+ use platform::drag_pointer;+ #[cfg(not(target_arch = "wasm32"))]+ pub use platform::file_watch;+ #[cfg(target_os = "macos")]+ use platform::macos_association;+ pub use platform::motion;+ #[cfg(not(target_arch = "wasm32"))]+ use platform::open_worker;+ #[cfg(not(target_arch = "wasm32"))]+ use platform::pickers;+ pub use platform::portable;+ #[cfg(not(target_arch = "wasm32"))]+ use platform::system_fonts;+ pub use platform::ui_scale;+ pub use platform::updates;+ pub use platform::window_controls;+ #[cfg(test)]+ use state::CopyPage;+ #[cfg(not(target_arch = "wasm32"))]+ use state::OpenRequest;+ pub use state::{+ CustomDraft, Dialog, DuplicateDraft, LeftPanel, LinkOrigin, Mode, NumberDraft, OpenOutcome, PageClip, PasswordPrompt, PendingLink,+ PendingRemoteLink, PropsTab, QuickTool, RecentFile, RightPanel, UnlockPrompt,+ };+ use state::{DocumentCopyJob, GridFile};+ pub use tools::bulk_fields;+ use tools::calc_order_ui;+ use tools::camera_ui;+ pub use tools::comments;+ use tools::content_ui;+ use tools::edit_text_ui;+ pub use tools::field_table_ui;+ pub use tools::fill_sign;+ pub use tools::forms_ui;+ use tools::link_ui;+ use tools::measure_ui;+ use tools::object_ui;+ pub use tools::prepare;+ use tools::redact_ui;+ use tools::sign_ui;+ use tools::stamps_ui;+ use tools::tags_ui;+ use widgets::icon_data;+ pub use widgets::icons;+ use workflows::a11y_ui;+ use workflows::actions_ui;+ use workflows::combine_grid;+ use workflows::combine_ui;+ use workflows::compare_ui;+ use workflows::create_ui;+ use workflows::export_ui;+ use workflows::files;+ use workflows::js_ui;+ use workflows::ocr_ui;+ use workflows::optimize_ui;+ use workflows::print_ui;+ use workflows::web_print;/// Files dropped on a document's page grid or its Pages panel.struct GridDrop {diff --cc crates/ui-egui/src/tools/comments.rsindex 000000000,674a3b4ea..5909fdd42mode 000000,100644..100644--- a/crates/ui-egui/src/tools/comments.rs+++ b/crates/ui-egui/src/tools/comments.rs@@@ -1,0 -1,394 +1,396 @@@+ //! Commenting in the document view (execution plan M5.3–M5.4; Acrobat's "Add comments").+ //!+ //! - **Tools** ([`CommentTool`]): sticky note, text box, highlight / underline / strikethrough+ //! (driven by text selection), freehand, line, arrow, rectangle, oval. They live in the quick+ //! bar in three flyout groups, as in Acrobat's comment toolbar (audit `a14-*`).+ //! - **On the page:** drawing gestures with live previews; with the Select tool, comments can be+ //! hovered, selected (blue frame with 8 round handles), moved, resized (rectangles, ovals and+ //! text boxes), edited (double-click) and deleted (⌫ / Delete); a context menu offers Edit,+ //! Reply, Set status, Colour and Delete.+ //! - **Composer:** the floating "Add a comment" card used for new notes, text boxes and edits.+ //!+ //! Everything is turned into `pdfcraft_engine::Edit`s, queued on the view as `pending_edit` and+ //! applied by the app, so each change is one undo step.++ use egui::{Color32, CornerRadius, Pos2, Rect, Sense, Stroke, pos2, vec2};+ use pdfcraft_engine::{Edit, LineEnding, Markup, NewAnnotation, NoteIcon, ReviewState, Rgb, Shape, Style};+ use pdfcraft_render::{Annotation, DocInfo, PageInfo, PageText};++ use crate::canvas::{DocView, PageXform};+ use crate::page_pointer::PagePointer;+ use crate::theme::{self, Tokens};+ use crate::{QuickTool, icons};++ mod composer;+ mod geometry;+ mod input;+ mod menu;+ mod paint;+ mod state;++ pub(crate) use composer::{composer, submit_key};+ #[cfg(test)]+ use geometry::handle_pos;+ #[cfg(test)]+ pub(crate) use geometry::{caret_snap, snapped_caret};+ pub(crate) use geometry::{corner_ratio, page_rotation, resized};+ pub use geometry::{drawn_text_box_rect, text_box_rect};-pub(crate) use input::{fill_grabs, keys, nudge_keys, page_after_text, page_input, select_grabs};++#[cfg(test)]++use input::hover_tip;++pub(crate) use input::{describe, fill_grabs, keys, nudge_keys, page_after_text, page_input, select_grabs};+ pub use menu::{CanvasAction, fill_picker, recent_custom_colours, remember_custom_colour, status_badge, swatch_grid};+ #[cfg(test)]+ use menu::{RECENT_CUSTOM, same_colour};+ pub(crate) use menu::{attachment_items, context_menu, quick_bar_controls};+ pub(crate) use paint::paint_page;+ #[cfg(test)]+ use paint::{changing_points, drawn_shape, edited_in_view};+ use state::login_name;+ pub use state::{CommentView, Composer, ComposerKind, Gesture, SortBy};+ pub(crate) use state::{EditorFocus, PageCx};++ /// Acrobat's selection blue for annotation frames and handles (11-visual-spec §5).+ const SELECT_BLUE: Color32 = Color32::from_rgb(0x14, 0x73, 0xE6);++ #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+ pub enum CommentTool {+ Note,+ TextBox,+ Highlight,+ Underline,+ StrikeOut,+ Squiggly,+ Ink,+ Line,+ Arrow,+ Rectangle,+ Oval,+ Polygon,+ PolyLine,+ Cloud,+ Callout,+ Caret,+ ReplaceText,+ Attach,+ Eraser,+ }++ /// The quick-bar flyout groups, in Acrobat's order: Comment ▸, Highlight ▸, Draw ▸.+ pub const GROUPS: [&[CommentTool]; 3] = [+ &[CommentTool::Note, CommentTool::TextBox, CommentTool::Callout, CommentTool::Attach],+ &[CommentTool::Highlight, CommentTool::Underline, CommentTool::StrikeOut, CommentTool::Squiggly, CommentTool::Caret, CommentTool::ReplaceText],+ &[+ CommentTool::Ink,+ CommentTool::Line,+ CommentTool::Arrow,+ CommentTool::Rectangle,+ CommentTool::Oval,+ CommentTool::PolyLine,+ CommentTool::Polygon,+ CommentTool::Cloud,+ CommentTool::Eraser,+ ],+ ];++ pub const ALL: [CommentTool; 19] = [+ CommentTool::Eraser,+ CommentTool::ReplaceText,+ CommentTool::Attach,+ CommentTool::Polygon,+ CommentTool::PolyLine,+ CommentTool::Cloud,+ CommentTool::Callout,+ CommentTool::Caret,+ CommentTool::Note,+ CommentTool::TextBox,+ CommentTool::Highlight,+ CommentTool::Underline,+ CommentTool::StrikeOut,+ CommentTool::Squiggly,+ CommentTool::Ink,+ CommentTool::Line,+ CommentTool::Arrow,+ CommentTool::Rectangle,+ CommentTool::Oval,+ ];++ impl CommentTool {+ pub fn command(self) -> &'static str {+ match self {+ Self::Note => "comment.note",+ Self::TextBox => "comment.freetext",+ Self::Highlight => "comment.highlight",+ Self::Underline => "comment.underline",+ Self::StrikeOut => "comment.strikeout",+ Self::Squiggly => "comment.squiggly",+ Self::Ink => "comment.ink",+ Self::Line => "comment.line",+ Self::Arrow => "comment.arrow",+ Self::Rectangle => "comment.square",+ Self::Oval => "comment.circle",+ Self::Polygon => "comment.polygon",+ Self::PolyLine => "comment.polyline",+ Self::Cloud => "comment.cloud",+ Self::Callout => "comment.callout",+ Self::Caret => "comment.caret",+ Self::ReplaceText => "comment.replace",+ Self::Attach => "comment.attach",+ Self::Eraser => "comment.eraser",+ }+ }++ pub fn from_command(id: &str) -> Option<Self> {+ ALL.into_iter().find(|t| t.command() == id)+ }++ pub fn label(self) -> &'static str {+ match self {+ Self::Note => "Add a sticky note",+ Self::TextBox => "Add a text box",+ Self::Highlight => "Highlight",+ Self::Underline => "Underline",+ Self::StrikeOut => "Strikethrough",+ Self::Squiggly => "Squiggly underline",+ Self::Ink => "Draw",+ Self::Line => "Line",+ Self::Arrow => "Arrow",+ Self::Rectangle => "Rectangle",+ Self::Oval => "Oval",+ Self::Polygon => "Polygon",+ Self::PolyLine => "Connected lines",+ Self::Cloud => "Cloud",+ Self::Callout => "Add a callout",+ Self::Caret => "Insert text",+ Self::ReplaceText => "Replace text",+ Self::Attach => "Attach file",+ Self::Eraser => "Eraser",+ }+ }++ pub fn icon(self) -> &'static str {+ match self {+ Self::Note => "message-square-plus",+ Self::TextBox => "type",+ Self::Highlight => "highlighter",+ Self::Underline => "underline",+ Self::StrikeOut => "strikethrough",+ Self::Squiggly => "spline",+ Self::Ink => "pencil",+ Self::Line => "minus",+ Self::Arrow => "move-right",+ Self::Rectangle => "square",+ Self::Oval => "circle",+ Self::Polygon => "pentagon",+ Self::PolyLine => "spline",+ Self::Cloud => "cloud",+ Self::Callout => "message-square-quote",+ Self::Caret => "text-cursor-input",+ Self::ReplaceText => "replace",+ Self::Attach => "paperclip",+ Self::Eraser => "eraser",+ }+ }++ pub fn group(self) -> usize {+ GROUPS.iter().position(|g| g.contains(&self)).unwrap_or(0)+ }++ pub fn markup(self) -> Option<Markup> {+ match self {+ Self::Highlight => Some(Markup::Highlight),+ Self::Underline => Some(Markup::Underline),+ Self::StrikeOut => Some(Markup::StrikeOut),+ Self::Squiggly => Some(Markup::Squiggly),+ _ => None,+ }+ }++ /// Tools that draw with a drag gesture.+ pub fn draws(self) -> bool {+ matches!(self, Self::Ink | Self::Line | Self::Arrow | Self::Rectangle | Self::Oval | Self::Eraser)+ }++ /// Tools that place points one click at a time (double-click or Enter finishes).+ pub fn clicks_points(self) -> bool {+ matches!(self, Self::Polygon | Self::PolyLine | Self::Cloud)+ }++ /// Whether the line-thickness control applies.+ pub fn has_width(self) -> bool {+ self.draws() || self.clicks_points() || matches!(self, Self::TextBox | Self::Callout)+ }++ /// Text comments may have no border while retaining visible text or fill.+ fn min_width(self) -> f64 {+ if matches!(self, Self::TextBox | Self::Callout) { 0.0 } else { 0.5 }+ }++ /// Whether the fill-colour control applies to this tool.+ pub fn has_fill(self) -> bool {+ matches!(self, Self::Rectangle | Self::Oval | Self::Polygon | Self::Cloud | Self::TextBox | Self::Callout)+ }++ /// A placeholder shape of this kind (for per-tool default styles).+ fn sample(self) -> Shape {+ match self {+ Self::Note => Shape::Note { at: [0.0; 2], icon: NoteIcon::Comment },+ Self::TextBox => Shape::TextBox { rect: [0.0; 4], font_size: 12.0 },+ Self::Highlight | Self::Underline | Self::StrikeOut | Self::Squiggly => {+ Shape::TextMarkup { kind: self.markup().unwrap_or(Markup::Highlight), quads: Vec::new() }+ }+ Self::Ink => Shape::Ink { strokes: Vec::new() },+ Self::Line => Shape::Line { from: [0.0; 2], to: [0.0; 2], start: LineEnding::None, end: LineEnding::None },+ Self::Arrow => Shape::Line { from: [0.0; 2], to: [0.0; 2], start: LineEnding::None, end: LineEnding::OpenArrow },+ Self::Rectangle => Shape::Rectangle { rect: [0.0; 4] },+ Self::Oval => Shape::Oval { rect: [0.0; 4] },+ Self::Polygon => Shape::Polygon { vertices: Vec::new(), cloud: false },+ Self::Cloud => Shape::Polygon { vertices: Vec::new(), cloud: true },+ Self::PolyLine => Shape::PolyLine { vertices: Vec::new(), start: LineEnding::None, end: LineEnding::None },+ Self::Callout => Shape::Callout { rect: [0.0; 4], knee: [0.0; 2], point: [0.0; 2], font_size: 10.0, ending: LineEnding::OpenArrow },+ Self::Caret => Shape::Caret { rect: [0.0; 4] },+ Self::ReplaceText => Shape::TextMarkup { kind: Markup::StrikeOut, quads: Vec::new() },+ Self::Eraser => Shape::Ink { strokes: Vec::new() },+ Self::Attach => Shape::Attachment { at: [0.0; 2], icon: pdfcraft_engine::AttachIcon::PushPin, file: String::new(), data: Vec::new() },+ }+ }+ }++ /// The comment swatches (our palette, close to Acrobat's quick colours).+ pub const SWATCHES: [(&str, Rgb); 10] = [+ ("Yellow", [1.0, 0.94, 0.0]),+ ("Orange", [1.0, 0.54, 0.0]),+ ("Red", [0.89, 0.13, 0.13]),+ ("Pink", [1.0, 0.37, 0.64]),+ ("Purple", [0.54, 0.25, 0.82]),+ ("Blue", [0.0, 0.47, 0.84]),+ ("Light blue", [0.36, 0.75, 0.98]),+ ("Green", [0.18, 0.62, 0.36]),+ ("Gray", [0.5, 0.5, 0.5]),+ ("Black", [0.0, 0.0, 0.0]),+ ];++ pub fn color32(c: Rgb) -> Color32 {+ let b = |v: f64| (v.clamp(0.0, 1.0) * 255.0).round() as u8;+ Color32::from_rgb(b(c[0]), b(c[1]), b(c[2]))+ }++ /// Commenting preferences shared by every document (author, per-tool styles, pin).+ #[derive(Clone, Debug)]+ pub struct CommentPrefs {+ /// `/T` of new comments (Acrobat: Preferences ▸ Identity, default the login name).+ pub author: String,+ styles: Vec<(CommentTool, Style)>,+ /// Keep the tool selected after use (the pin).+ pub pinned: bool,+ /// The tool each flyout group shows (the last one used).+ pub group_tool: [CommentTool; 3],+ /// Hide hover previews on highlight annotations when they contain no comment text beyond the author.+ pub hide_empty_highlight_hover: bool,+ }++ impl Default for CommentPrefs {+ fn default() -> Self {+ Self {+ author: login_name(),+ styles: ALL.iter().map(|t| (*t, Style::default_for(&t.sample()))).collect(),+ pinned: false,+ group_tool: [CommentTool::Note, CommentTool::Highlight, CommentTool::Ink],+ hide_empty_highlight_hover: false,+ }+ }+ }++ impl CommentPrefs {+ pub fn style(&self, tool: CommentTool) -> Style {+ self.styles.iter().find(|(t, _)| *t == tool).map(|(_, s)| s.clone()).unwrap_or_default()+ }++ /// Every tool with its current default style (the persisted settings read this).+ pub fn styles(&self) -> impl Iterator<Item = (CommentTool, &Style)> {+ self.styles.iter().map(|(t, s)| (*t, s))+ }++ pub fn set_color(&mut self, tool: CommentTool, c: Rgb) {+ if let Some((_, s)) = self.styles.iter_mut().find(|(t, _)| *t == tool) {+ s.color = c;+ }+ }++ pub fn set_width(&mut self, tool: CommentTool, w: f64) {+ if let Some((_, s)) = self.styles.iter_mut().find(|(t, _)| *t == tool) {+ s.width = w.clamp(tool.min_width(), 12.0);+ }+ }++ /// The tool's opacity, 10–100 % (an invisible comment can't be found again).+ pub fn set_opacity(&mut self, tool: CommentTool, o: f64) {+ if let Some((_, s)) = self.styles.iter_mut().find(|(t, _)| *t == tool) {+ s.opacity = if o.is_finite() { o.clamp(0.1, 1.0) } else { 1.0 };+ }+ }++ /// The tool's fill (`None`: no fill).+ pub fn set_fill(&mut self, tool: CommentTool, fill: Option<Rgb>) {+ if let Some((_, s)) = self.styles.iter_mut().find(|(t, _)| *t == tool) {+ s.fill = if tool.has_fill() { fill.filter(|c| c.iter().all(|x| x.is_finite())).map(|c| c.map(|x| x.clamp(0.0, 1.0))) } else { None };+ }+ }++ pub fn set_style(&mut self, tool: CommentTool, style: Style) {+ if let Some((_, s)) = self.styles.iter_mut().find(|(t, _)| *t == tool) {+ *s = style;+ }+ }+ }++ /// Whether `tool` makes comments like `a`. Arrows are saved as plain Line annotations with an+ /// ending, so the Line and Arrow tools both match a line.+ pub(crate) fn made_by(a: &Annotation, tool: CommentTool) -> bool {+ match tool_for(a) {+ Some(CommentTool::Line) => matches!(tool, CommentTool::Line | CommentTool::Arrow),+ made => made == Some(tool),+ }+ }++ /// The tool whose defaults "Make Current Properties Default" should update.+ ///+ /// Arrows are stored as Line annotations. An arrow ending belongs to the Arrow tool, so its+ /// defaults stay separate from a plain line.+ pub(crate) fn tool_for_default(a: &Annotation, endings: Option<&[LineEnding]>) -> Option<CommentTool> {+ match tool_for(a) {+ Some(CommentTool::Line) if endings.is_some_and(|ends| ends.iter().copied().any(arrow_ending)) => Some(CommentTool::Arrow),+ other => other,+ }+ }++ fn arrow_ending(ending: LineEnding) -> bool {+ matches!(ending, LineEnding::OpenArrow | LineEnding::ClosedArrow | LineEnding::ROpenArrow | LineEnding::RClosedArrow)+ }++ /// The tool that makes comments like `a` (for Make Current Properties Default).+ pub fn tool_for(a: &Annotation) -> Option<CommentTool> {+ Some(match (a.subtype.as_str(), a.intent.as_deref()) {+ ("Text", _) => CommentTool::Note,+ ("FreeText", Some("FreeTextCallout")) => CommentTool::Callout,+ ("FreeText", Some("FreeTextTypeWriter")) => return None,+ ("FreeText", _) => CommentTool::TextBox,+ ("Highlight", _) => CommentTool::Highlight,+ ("Underline", _) => CommentTool::Underline,+ ("StrikeOut", Some("StrikeOutTextEdit")) => CommentTool::ReplaceText,+ ("StrikeOut", _) => CommentTool::StrikeOut,+ ("Squiggly", _) => CommentTool::Squiggly,+ ("Ink", _) => CommentTool::Ink,+ ("Line", _) => CommentTool::Line,+ ("Square", _) => CommentTool::Rectangle,+ ("Circle", _) => CommentTool::Oval,+ ("Polygon", Some("PolygonCloud")) => CommentTool::Cloud,+ ("Polygon", _) => CommentTool::Polygon,+ ("PolyLine", _) => CommentTool::PolyLine,+ ("Caret", _) => CommentTool::Caret,+ ("FileAttachment", _) => CommentTool::Attach,+ _ => return None,+ })+ }++ #[cfg(test)]+ mod tests;diff --cc crates/ui-egui/src/tools/comments/input.rsindex 000000000,ef0341b71..af78a1e46mode 000000,100644..100644--- a/crates/ui-egui/src/tools/comments/input.rs+++ b/crates/ui-egui/src/tools/comments/input.rs@@@ -1,0 -1,622 +1,668 @@@+ use super::geometry::{+ CARET_SIZE, HANDLES, clamp_to, corner_ratio, drawn_box, grabs_points, handle_pos, is_markup, point_handle, reshapable, reshaped, resizable,+ resized, snapped_caret,+ };+ use super::paint::{drawn_shape, edit_anchor, erase, new_comment};+ use super::state::{Composer, ComposerKind, Gesture, PageCx};-use super::{Annotation, CommentTool, DocInfo, DocView, Edit, Pos2, QuickTool, Rect, Shape, vec2};++use super::{Annotation, CommentPrefs, CommentTool, DocInfo, DocView, Edit, Pos2, QuickTool, Rect, Shape, vec2};++use crate::page_cursor::{Layer, Subject};++ /// Comment input on one page, before text selection runs. Returns `true` when the pointer+ /// gesture belongs to commenting (text selection must ignore it).+ pub(crate) fn page_input(ui: &egui::Ui, resp: &egui::Response, cx: &PageCx<'_>, view: &mut DocView) -> bool {+ let (pointer, origin) = (cx.ptr.pos, cx.ptr.origin);+ let page_rect = cx.xf.rect;+ let pressed_here = origin.is_some_and(|o| page_rect.contains(o));+ let over_page = pointer.is_some_and(|p| page_rect.contains(p));+ let fill_grab = fill_grabs(cx, view);+ let draw_grab = draw_grabs(cx, view);+ let caret_text = if cx.tool == QuickTool::Comment(CommentTool::Caret) { view.page_text(cx.page) } else { None };+ let cv = &mut view.comments;+ if cv.gesture.is_some() && ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape)) {+ cv.gesture = None;+ cv.cancelled_drag = true;+ return true;+ }+ if cv.cancelled_drag {+ return true;+ }+ if resp.secondary_clicked()+ && let Some(p) = pointer.filter(|p| page_rect.contains(*p))+ {+ cv.context_at = Some((cx.page, cx.to_user(p)));+ cv.selected = cx.hit(p).map(|a| (cx.page, a.index));+ }+ let gestures = Gestures { ui, resp, cx, pointer, origin, page_rect, pressed_here, over_page };+ match cx.tool {+ QuickTool::Comment(_) if draw_grab => select_input(ui, resp, cx, view, pointer, origin, pressed_here),+ QuickTool::Comment(tool) if tool.draws() => gestures.draw_shape(view, tool),+ QuickTool::Comment(tool) if tool.clicks_points() => gestures.click_points(view, tool),+ QuickTool::Comment(CommentTool::Callout) => gestures.callout(view),+ QuickTool::Comment(CommentTool::Attach) => gestures.attach(view),+ QuickTool::Comment(CommentTool::Caret) => gestures.caret(view, caret_text.as_deref()),+ QuickTool::Comment(tool @ (CommentTool::Note | CommentTool::TextBox)) => gestures.note_or_box(view, tool),+ QuickTool::Select => select_input(ui, resp, cx, view, pointer, origin, pressed_here),+ QuickTool::Fill(_) if fill_grab => select_input(ui, resp, cx, view, pointer, origin, pressed_here),+ _ => false,+ }+ }++ /// With a Fill & Sign tool, the Fill & Sign marks already on the page are picked up as with the+ /// Select tool, as in Acrobat: hovering one shows the move cursor, a click selects it, a drag+ /// moves it and the selected one's handles resize it. Elsewhere the tool places its mark. While+ /// the button is down the press decides; otherwise the pointer (egui clears the press origin on+ /// release, so a click is located by the pointer).+ pub(crate) fn fill_grabs(cx: &PageCx<'_>, view: &DocView) -> bool {+ matches!(cx.tool, QuickTool::Fill(_)) && grabs(cx, view, |a| a.fill_sign)+ }++ /// With the Select tool, a comment that would move (not text markup) is picked up before a form+ /// field under it, so a signature placed over a field can still be dragged off it.+ pub(crate) fn select_grabs(cx: &PageCx<'_>, view: &DocView) -> bool {+ cx.tool == QuickTool::Select && grabs(cx, view, |a| !is_markup(&a.subtype))+ }++ /// With a shape tool (rectangle, oval, line, polygon…), the selected comment's resize handles+ /// are picked up as with the Select tool, so the shape just drawn can be resized straight away+ /// (#2338). Only the handles: a press anywhere else, the shape itself included, still draws.+ pub(crate) fn draw_grabs(cx: &PageCx<'_>, view: &DocView) -> bool {+ let QuickTool::Comment(tool) = cx.tool else { return false };+ if !(tool.draws() || tool.clicks_points()) || tool == CommentTool::Eraser || cx.hidden {+ return false;+ }+ let cv = &view.comments;+ if matches!(cv.gesture, Some(Gesture::Resize { page, .. } | Gesture::Reshape { page, .. }) if page == cx.page) {+ return true;+ }+ // A polygon being clicked out keeps its clicks, even near an old shape's handle.+ if cv.gesture.is_some() {+ return false;+ }+ press_point(cx).is_some_and(|p| on_handle(cx, view, p, |_| true))+ }++ /// Whether the press (or, with no button down, the pointer) is on a `pick` comment or on the+ /// selected one's resize handles.+ fn grabs(cx: &PageCx<'_>, view: &DocView, pick: impl Fn(&Annotation) -> bool) -> bool {+ if cx.hidden {+ return false;+ }+ if matches!(view.comments.gesture, Some(Gesture::Move { page, .. } | Gesture::Resize { page, .. } | Gesture::Reshape { page, .. }) if page == cx.page)+ {+ return true;+ }+ let Some(p) = press_point(cx) else { return false };+ on_handle(cx, view, p, &pick) || cx.hit(p).is_some_and(pick)+ }++ /// Where a gesture on this page is decided: the press while the button is down, otherwise the+ /// pointer (egui clears the press origin on release). `None` off the page.+ fn press_point(cx: &PageCx<'_>) -> Option<Pos2> {+ (if cx.ptr.any_down { cx.ptr.origin } else { cx.ptr.pos }).filter(|p| cx.xf.rect.contains(*p))+ }++ /// Whether `p` is on a resize handle of the selected comment, when it is a resizable `pick`.+ fn on_handle(cx: &PageCx<'_>, view: &DocView, p: Pos2, pick: impl Fn(&Annotation) -> bool) -> bool {+ view.comments.selected.filter(|(page, _)| *page == cx.page).and_then(|(_, i)| cx.get(i)).filter(|a| pick(a) && cx.allowed).is_some_and(|a| {+ (resizable(a) && HANDLES.into_iter().any(|h| handle_pos(cx.screen_rect(a), h).distance(p) <= 7.0))+ || (grabs_points(cx.tool) && reshapable(a) && point_handle(cx, a, p).is_some())+ })+ }+++/// Whether `p` is on one of this page's links.++fn on_link(cx: &PageCx<'_>, p: Pos2) -> bool {++ cx.info.links.iter().any(|link| link.page == cx.page && cx.xf.user_rect(cx.info, cx.page, link.rect).contains(p))++}++++/// The tip for the comment under the pointer, with any tool, beside that tool's own cursor: Acrobat++/// shows a comment's tooltip whatever tool is active. Not with Fill & Sign, whose placement stays++/// clear; not while drawing freehand, where it would cover the next stroke (#429); and not while a++/// comment is moved, resized or drawn.++pub(crate) fn describe(cx: &PageCx<'_>, view: &mut DocView) {++ let freehand = matches!(cx.tool, QuickTool::Comment(CommentTool::Ink | CommentTool::Eraser));++ if matches!(cx.tool, QuickTool::Fill(_)) || freehand || view.comments.gesture.is_some() {++ return;++ }++ let Some(p) = cx.ptr.pos else { return };++ // Inspection sorts comments by position, but the renderer paints them in `/Annots` order: the++ // tip is that of the one drawn on top, among those with something to say (#3620).++ let top = cx++ .comments()++ .filter(|a| cx.screen_rects(a).any(|r| r.contains(p)))++ .filter_map(|a| hover_tip(a, cx.prefs).map(|text| (a.index, text)))++ .max_by_key(|(index, _)| *index);++ if let Some((_, text)) = top {++ view.cursor.describe(Subject::Comment, text);++ }++}++++/// What hovering `a` says, as Acrobat's popups do. Replies and Fill & Sign's marks (typed text,++/// checks, signatures) say nothing: they are page content being edited, not comments. Neither++/// does a highlight with no text of its own, when the preferences say so.++pub(super) fn hover_tip(a: &Annotation, prefs: &CommentPrefs) -> Option<String> {++ let empty_highlight = a.subtype == "Highlight" && a.contents.as_deref().is_none_or(str::is_empty);++ if a.is_reply() || a.fill_sign || prefs.hide_empty_highlight_hover && empty_highlight {++ return None;++ }++ let who = a.author.clone().unwrap_or_else(|| a.subtype.clone());++ let body = a.contents.clone().unwrap_or_default();++ Some(if body.is_empty() { who } else { format!("{who}\n{body}") })++}+++ /// The Select tool: hover, select, move, resize, edit, delete.+ fn select_input(+ ui: &egui::Ui,+ resp: &egui::Response,+ cx: &PageCx<'_>,+ view: &mut DocView,+ pointer: Option<Pos2>,+ origin: Option<Pos2>,+ pressed_here: bool,+ ) -> bool {+ let cv = &mut view.comments;+ let selected = cv.selected.filter(|(p, _)| *p == cx.page).and_then(|(_, i)| cx.get(i));+ // Handles of a selected, resizable comment.+ let handle_at = |p: Pos2| -> Option<(i8, i8)> {+ let a = selected.filter(|a| cx.allowed && resizable(a))?;+ let r = cx.screen_rect(a);+ HANDLES.into_iter().find(|h| handle_pos(r, *h).distance(p) <= 7.0)+ };+ // Ends and corners of a selected line, connected lines, polygon or cloud.+ let point_at =+ |p: Pos2| -> Option<usize> { selected.filter(|a| cx.allowed && grabs_points(cx.tool) && reshapable(a)).and_then(|a| point_handle(cx, a, p)) };+ let mut consumed = false;+ if let Some(p) = pointer {+ if point_at(p).is_some() {- ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair);++ view.cursor.claim(Layer::Handle, egui::CursorIcon::Crosshair);+ } else if let Some(h) = handle_at(p) {- ui.ctx().set_cursor_icon(match h {- (0, _) => egui::CursorIcon::ResizeVertical,- (_, 0) => egui::CursorIcon::ResizeHorizontal,- (-1, -1) | (1, 1) => egui::CursorIcon::ResizeNwSe,- _ => egui::CursorIcon::ResizeNeSw,- });- } else if let Some(a) = cx.hit(p) {++ view.cursor.claim(++ Layer::Handle,++ match h {++ (0, _) => egui::CursorIcon::ResizeVertical,++ (_, 0) => egui::CursorIcon::ResizeHorizontal,++ (-1, -1) | (1, 1) => egui::CursorIcon::ResizeNwSe,++ _ => egui::CursorIcon::ResizeNeSw,++ },++ );++ } else if let Some(a) = cx.hit(p)++ // A click on a highlight over a link follows the link, so the link's hand and tip++ // show there.++ && !(a.subtype == "Highlight" && on_link(cx, p))++ {+ let movable = cx.allowed && !is_markup(&a.subtype);- ui.ctx().set_cursor_icon(if movable { egui::CursorIcon::Move } else { egui::CursorIcon::PointingHand });++ let icon = if movable { egui::CursorIcon::Move } else { egui::CursorIcon::PointingHand };++ // Signatures and Fill & Sign's marks are placed on the page rather than comments on it.++ view.cursor.claim(if a.fill_sign { Layer::Placed } else { Layer::Comment }, icon);+ }+ }+ if resp.drag_started()+ && pressed_here+ && let Some(o) = origin+ {+ if let (Some(point), Some(a)) = (point_at(o), selected) {+ let points = a.points.iter().map(|q| [f64::from(q[0]), f64::from(q[1])]).collect();+ cv.gesture = Some(Gesture::Reshape { page: cx.page, index: a.index, point, points });+ consumed = true;+ } else if let (Some(h), Some(a)) = (handle_at(o), selected) {+ // On screen, the image is also turned by the view's rotation.+ let turned = !cx.xf.rot.is_multiple_of(180);+ let aspect_ratio = view.signature_drag.aspect_ratio(cx.page, a.index).map(|ratio| if turned { ratio.recip() } else { ratio });+ // A drawn signature keeps its shape from the corners, as image signatures do.+ let aspect_ratio = aspect_ratio.or_else(|| {+ let r = cx.screen_rect(a);+ (a.fill_sign && a.subtype == "Ink" && r.height() > 0.0).then(|| r.width() / r.height())+ });+ cv.gesture = Some(Gesture::Resize { page: cx.page, index: a.index, handle: h, from: o, aspect_ratio });+ consumed = true;+ } else if let Some(a) = cx.hit(o)+ && !is_markup(&a.subtype)+ {+ cv.selected = Some((cx.page, a.index));+ cv.reveal = true;+ if cx.allowed {+ cv.gesture = Some(Gesture::Move { page: cx.page, index: a.index, from: o });+ }+ consumed = true;+ }+ }+ if matches!(cv.gesture, Some(Gesture::Move { page, .. } | Gesture::Resize { page, .. } | Gesture::Reshape { page, .. }) if page == cx.page) {+ consumed = true;+ }+ if resp.drag_stopped()+ && let Some(p) = pointer+ {+ match cv.gesture.clone() {+ Some(Gesture::Move { page, index, from }) if page == cx.page => {+ cv.gesture = None;+ let (a, b) = (cx.to_user(from), cx.to_user(p));+ let (dx, dy) = (b[0] - a[0], b[1] - a[1]);+ if from.distance(p) >= 2.0 {+ view.pending_edit = Some(Edit::MoveAnnotation { page, index, dx, dy });+ }+ }+ Some(Gesture::Resize { page, index, handle, from, aspect_ratio }) if page == cx.page => {+ cv.gesture = None;+ if let Some(a) = cx.get(index) {+ let from_rect = cx.screen_rect(a);+ let shift = ui.input(|i| i.modifiers.shift);+ let r = resized(from_rect, handle, p - from, corner_ratio(from_rect, aspect_ratio, shift));+ let rect = a.rect_for_shown(cx.rect_to_user(r), cx.rotation());+ if r.width() >= 4.0 && r.height() >= 4.0 {+ view.pending_edit = Some(Edit::ResizeAnnotation { page, index, rect });+ }+ }+ }+ Some(Gesture::Reshape { page, index, point, points }) if page == cx.page => {+ cv.gesture = None;+ let shift = ui.input(|i| i.modifiers.shift);+ let moved = points.get(point).is_some_and(|q| cx.to_screen(*q).distance(p) >= 2.0);+ if moved {+ view.pending_edit = Some(Edit::ReshapeAnnotation { page, index, points: reshaped(&points, point, cx.to_user(p), shift) });+ }+ }+ _ => {}+ }+ }+ // (egui clears the press origin on release, so clicks are located by the pointer.)+ let on_page = pointer.is_some_and(|p| cx.xf.rect.contains(p));+ if resp.clicked() && on_page {- let follow_link = cx.tool == QuickTool::Select- && !consumed- && cv.gesture.is_none()- && !resp.double_clicked()- && pointer- .is_some_and(|p| cx.info.links.iter().any(|link| link.page == cx.page && cx.xf.user_rect(cx.info, cx.page, link.rect).contains(p)));++ let follow_link =++ cx.tool == QuickTool::Select && !consumed && cv.gesture.is_none() && !resp.double_clicked() && pointer.is_some_and(|p| on_link(cx, p));+ match pointer.and_then(|p| cx.hit(p)) {+ Some(a) if a.subtype == "Highlight" && follow_link => {+ // A plain click follows the link beneath text highlighting. Keep other+ // annotations and active gestures in control of their own input.+ cv.selected = None;+ }+ Some(a) => {+ cv.selected = Some((cx.page, a.index));+ cv.reveal = true;+ consumed = true;+ }+ None => cv.selected = None,+ }+ }+ if resp.double_clicked()+ && on_page+ && cx.allowed+ && let Some(a) = pointer.and_then(|p| cx.hit(p))+ {+ cv.selected = Some((cx.page, a.index));+ cv.composer = Some(Composer {+ page: cx.page,+ at: edit_anchor(cx.info, a),+ kind: ComposerKind::Edit(a.index),+ text: a.contents.clone().unwrap_or_default(),+ focus: true,+ });+ consumed = true;+ }+ consumed+ }++ /// After text selection ran: a markup tool turns a finished selection into a comment; Replace+ /// Text asks for the replacement.+ pub(crate) fn page_after_text(resp: &egui::Response, cx: &PageCx<'_>, view: &mut DocView) {+ let QuickTool::Comment(tool) = cx.tool else { return };+ if tool == CommentTool::ReplaceText && cx.allowed && (resp.drag_stopped() || resp.double_clicked()) {+ if let Some((page, quads)) = view.selection_quads(cx.info).filter(|(p, _)| *p == 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])];+ view.comments.replace = Some(quads);+ view.comments.composer = Some(Composer { page, at, kind: ComposerKind::Replace, text: String::new(), focus: true });+ }+ return;+ }+ if tool.markup().is_none() || !cx.allowed || !(resp.drag_stopped() || resp.double_clicked()) {+ return;+ }+ if let Some(kind) = tool.markup()+ && let Some((page, quads)) = view.selection_quads(cx.info).filter(|(p, _)| *p == cx.page)+ {+ view.clear_selection();+ view.pending_edit = Some(new_comment(cx, tool, Shape::TextMarkup { kind, quads }, String::new()));+ let _ = page;+ }+ }++ /// What the pointer is doing on one page, for the comment tools that draw or place things.+ #[derive(Clone, Copy)]+ struct Gestures<'a> {+ ui: &'a egui::Ui,+ resp: &'a egui::Response,+ cx: &'a PageCx<'a>,+ pointer: Option<Pos2>,+ origin: Option<Pos2>,+ page_rect: Rect,+ pressed_here: bool,+ over_page: bool,+ }++ impl Gestures<'_> {+ fn draw_shape(&self, view: &mut DocView, tool: CommentTool) -> bool {+ let Self { ui, resp, cx, pointer, origin, page_rect, pressed_here, over_page } = *self;+ let cv = &mut view.comments;+ if !cx.allowed {+ return false;+ }+ if over_page {- ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair);++ view.cursor.claim(Layer::ToolArea, egui::CursorIcon::Crosshair);+ }+ if resp.drag_started()+ && pressed_here+ && let Some(o) = origin+ {+ cv.gesture = Some(Gesture::Draw { page: cx.page, tool, points: vec![cx.to_user(o)] });+ cv.selected = None;+ }+ if let Some(Gesture::Draw { page, tool, points }) = cv.gesture.as_mut()+ && *page == cx.page+ && let Some(p) = pointer+ {+ let p = clamp_to(page_rect, p);+ let u = cx.to_user(p);+ if matches!(*tool, CommentTool::Ink | CommentTool::Eraser) {+ let last = points.last().map(|l| cx.to_screen(*l)).unwrap_or(p);+ if last.distance(p) >= 1.5 {+ points.push(u);+ }+ } else {+ points.truncate(1);+ points.push(u);+ }+ }+ if resp.drag_stopped()+ && let Some(Gesture::Draw { page, tool, points }) = cv.gesture.clone()+ && page == cx.page+ {+ cv.gesture = None;+ if tool == CommentTool::Eraser {+ view.pending_edit = erase(cx, &points);+ } else if let Some(shape) = drawn_shape(tool, &points) {+ let now = ui.input(|i| i.time);+ cv.settle(now, page, tool, &points);+ view.pending_edit = Some(new_comment(cx, tool, shape, String::new()));+ }+ }+ // A quick press/release does not start an egui drag, but Acrobat's Draw tool treats+ // it as a one-point ink stroke (a dot). The appearance uses round line caps, so a+ // single PDF point is visible and remains editable like any other drawing.+ if tool == CommentTool::Ink+ && resp.clicked()+ && over_page+ && let Some(p) = pointer+ && let Some(shape) = drawn_shape(tool, &[cx.to_user(p)])+ {+ cv.selected = None;+ let now = ui.input(|i| i.time);+ cv.settle(now, cx.page, tool, &[cx.to_user(p)]);+ view.pending_edit = Some(new_comment(cx, tool, shape, String::new()));+ }+ true+ }++ fn click_points(&self, view: &mut DocView, tool: CommentTool) -> bool {+ let Self { ui, resp, cx, pointer, over_page, .. } = *self;+ let cv = &mut view.comments;+ if !cx.allowed {+ return false;+ }+ if over_page {- ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair);++ view.cursor.claim(Layer::ToolArea, egui::CursorIcon::Crosshair);+ }+ let finish = resp.double_clicked() || ui.input(|i| i.key_pressed(egui::Key::Enter));+ // Backspace (or Delete) takes back the last point, e.g. after a wrong click; Undo does too.+ // Only while a drawing is in progress: otherwise Delete belongs to the selected comment.+ if matches!(cv.gesture, Some(Gesture::Draw { page, .. }) if page == cx.page)+ && !ui.ctx().egui_wants_keyboard_input()+ && ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Backspace) || i.consume_key(egui::Modifiers::NONE, egui::Key::Delete))+ {+ cv.undo_point();+ return true;+ }+ if resp.clicked()+ && over_page+ && let Some(p) = pointer+ {+ let u = cx.to_user(p);+ match cv.gesture.as_mut() {+ Some(Gesture::Draw { page, tool: t, points }) if *page == cx.page && *t == tool => {+ // Clicking the first point again closes a polygon.+ let closes = points.len() >= 3 && tool != CommentTool::PolyLine && cx.to_screen(points[0]).distance(p) <= 6.0;+ let repeat = points.last().is_some_and(|l| cx.to_screen(*l).distance(p) < 2.0);+ if closes {+ let pts = std::mem::take(points);+ cv.gesture = None;+ if let Some(shape) = drawn_shape(tool, &pts) {+ view.pending_edit = Some(new_comment(cx, tool, shape, String::new()));+ }+ return true;+ }+ if !repeat {+ points.push(u);+ }+ }+ _ => {+ cv.gesture = Some(Gesture::Draw { page: cx.page, tool, points: vec![u] });+ cv.selected = None;+ }+ }+ }+ if finish+ && let Some(Gesture::Draw { page, tool: t, points }) = cv.gesture.clone()+ && page == cx.page+ && t == tool+ {+ cv.gesture = None;+ if let Some(shape) = drawn_shape(tool, &points) {+ view.pending_edit = Some(new_comment(cx, tool, shape, String::new()));+ }+ }+ true+ }++ fn callout(&self, view: &mut DocView) -> bool {- let Self { ui, resp, cx, pointer, origin, page_rect, pressed_here, over_page } = *self;++ let Self { resp, cx, pointer, origin, page_rect, pressed_here, over_page, .. } = *self;+ let cv = &mut view.comments;+ // Drag from what the callout points at to where its text box goes.+ if !cx.allowed {+ return false;+ }+ if over_page {- ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair);++ view.cursor.claim(Layer::ToolArea, egui::CursorIcon::Crosshair);+ }+ if resp.drag_started()+ && pressed_here+ && let Some(o) = origin+ {+ cv.gesture = Some(Gesture::Draw { page: cx.page, tool: CommentTool::Callout, points: vec![cx.to_user(o)] });+ cv.selected = None;+ }+ if let Some(Gesture::Draw { page, points, .. }) = cv.gesture.as_mut()+ && *page == cx.page+ && let Some(p) = pointer+ {+ points.truncate(1);+ points.push(cx.to_user(clamp_to(page_rect, p)));+ }+ if resp.drag_stopped()+ && let Some(Gesture::Draw { page, points, .. }) = cv.gesture.clone()+ && page == cx.page+ {+ cv.gesture = None;+ if let [point, at] = points[..]+ && (point[0] - at[0]).hypot(point[1] - at[1]) >= 8.0+ {+ cv.composer = Some(Composer { page, at, kind: ComposerKind::Callout { point }, text: String::new(), focus: true });+ }+ }+ true+ }++ fn attach(&self, view: &mut DocView) -> bool {- let Self { ui, resp, cx, pointer, over_page, .. } = *self;++ let Self { resp, cx, pointer, over_page, .. } = *self;+ let cv = &mut view.comments;+ if !cx.allowed {+ return false;+ }+ if over_page {- ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair);++ view.cursor.claim(Layer::ToolArea, egui::CursorIcon::Crosshair);+ }+ if resp.clicked()+ && over_page+ && let Some(p) = pointer+ {+ cv.attach_at = Some((cx.page, cx.to_user(p)));+ cv.selected = None;+ }+ true+ }++ fn caret(&self, view: &mut DocView, caret_text: Option<&pdfcraft_render::PageText>) -> bool {- let Self { ui, resp, cx, pointer, over_page, .. } = *self;++ let Self { resp, cx, pointer, over_page, .. } = *self;+ let cv = &mut view.comments;+ if !cx.allowed {+ return false;+ }+ if over_page {- ui.ctx().set_cursor_icon(egui::CursorIcon::Text);++ view.cursor.claim(Layer::ToolArea, egui::CursorIcon::Text);+ }+ if resp.clicked()+ && over_page+ && let Some(p) = pointer+ {+ let (vx, vy) = cx.xf.screen_to_view(p);+ let snapped = cx.info.pages.get(cx.page).zip(caret_text).and_then(|(page, t)| snapped_caret(page, t, vx, vy));+ let (at, size) = snapped.unwrap_or_else(|| (cx.to_user(p), CARET_SIZE));+ cv.composer = Some(Composer { page: cx.page, at, kind: ComposerKind::Caret { size }, text: String::new(), focus: true });+ cv.selected = None;+ }+ true+ }++ fn note_or_box(&self, view: &mut DocView, tool: CommentTool) -> bool {- let Self { ui, resp, cx, pointer, origin, page_rect, pressed_here, over_page } = *self;++ let Self { resp, cx, pointer, origin, page_rect, pressed_here, over_page, .. } = *self;+ let cv = &mut view.comments;+ if !cx.allowed {+ return false;+ }+ if over_page {- ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair);++ view.cursor.claim(Layer::ToolArea, egui::CursorIcon::Crosshair);+ }+ // A text box also takes a drag, as in Acrobat: the box is drawn at that size and its+ // text wraps inside it (#2669).+ if tool == CommentTool::TextBox {+ if resp.drag_started()+ && pressed_here+ && let Some(o) = origin+ {+ cv.gesture = Some(Gesture::Draw { page: cx.page, tool, points: vec![cx.to_user(o)] });+ cv.selected = None;+ }+ if let Some(Gesture::Draw { page, points, .. }) = cv.gesture.as_mut()+ && *page == cx.page+ && let Some(p) = pointer+ {+ points.truncate(1);+ points.push(cx.to_user(clamp_to(page_rect, p)));+ }+ if resp.drag_stopped()+ && let Some(Gesture::Draw { page, points, .. }) = cv.gesture.clone()+ && page == cx.page+ {+ cv.gesture = None;+ if let (Some(first), Some(last)) = (points.first(), points.last()) {+ let r = Rect::from_two_pos(cx.to_screen(*first), cx.to_screen(*last));+ // A drag of a few pixels is a click: the box fits its text.+ let drawn =+ (r.width() >= 6.0 && r.height() >= 6.0).then(|| cx.info.pages.get(page)).flatten().map(|p| drawn_box(p, *first, *last));+ let (at, size) = drawn.map_or((*first, None), |(at, size)| (at, Some(size)));+ cv.composer = Some(Composer { page, at, kind: ComposerKind::TextBox { size }, text: String::new(), focus: true });+ }+ }+ }+ if resp.clicked()+ && over_page+ && let Some(p) = pointer+ {+ let kind = if tool == CommentTool::Note { ComposerKind::Note } else { ComposerKind::TextBox { size: None } };+ cv.composer = Some(Composer { page: cx.page, at: cx.to_user(p), kind, text: String::new(), focus: true });+ cv.selected = None;+ }+ true+ }+ }++ /// Delete / Escape handling for comments (only while no text field has focus).+ pub(crate) fn keys(ctx: &egui::Context, view: &mut DocView, tool: &mut QuickTool, allowed: bool) {+ if !ctx.input(|i| i.pointer.any_down()) {+ view.comments.cancelled_drag = false;+ }+ if ctx.egui_wants_keyboard_input() {+ return;+ }+ let cv = &mut view.comments;+ if ctx.input(|i| i.key_pressed(egui::Key::Escape)) {+ // One step back per press: cancel the gesture, then deselect, then drop the tool.+ let cancelled = cv.gesture.take().is_some() || cv.selected.take().is_some();+ if !cancelled && matches!(tool, QuickTool::Comment(_)) {+ *tool = QuickTool::Select;+ }+ }+ if allowed+ && let Some((page, index)) = cv.selected+ && ctx.input(|i| i.key_pressed(egui::Key::Delete) || i.key_pressed(egui::Key::Backspace))+ {+ cv.selected = None;+ view.pending_edit = Some(Edit::DeleteAnnotation { page, index });+ }+ }++ /// The arrow keys move the selected comment a screen pixel; with ⌘/Ctrl or Shift, ten. Up is up+ /// on screen whatever the zoom, the page's rotation and the view's; the keys are taken before+ /// the view scrolls or turns the page with them. Each press is one undo step. Text markup stays+ /// with its text, and a locked comment where it is.+ pub(crate) fn nudge_keys(ctx: &egui::Context, view: &mut DocView, info: &DocInfo) {+ if ctx.egui_wants_keyboard_input() || view.pending_edit.is_some() {+ return;+ }+ let cv = &view.comments;+ if cv.gesture.is_some() || cv.composer.is_some() {+ return;+ }+ let Some((page, index)) = cv.selected else { return };+ let movable = info.annotations.iter().any(|a| a.page == page && a.index == index && !a.is_reply() && !is_markup(&a.subtype) && !a.locked);+ let (Some(xf), Some(p)) = (view.page_xform(page), info.pages.get(page)) else { return };+ if !movable {+ return;+ }+ use egui::{Key, Modifiers};+ let mut step = egui::Vec2::ZERO;+ ctx.input_mut(|i| {+ for (key, direction) in+ [(Key::ArrowLeft, vec2(-1.0, 0.0)), (Key::ArrowRight, vec2(1.0, 0.0)), (Key::ArrowUp, vec2(0.0, -1.0)), (Key::ArrowDown, vec2(0.0, 1.0))]+ {+ // The modified patterns first: a plain one also matches a Shift press.+ if i.consume_key(Modifiers::COMMAND, key) || i.consume_key(Modifiers::SHIFT, key) {+ step += direction * 10.0;+ } else if i.consume_key(Modifiers::NONE, key) {+ step += direction;+ }+ }+ });+ if step == egui::Vec2::ZERO {+ return;+ }+ // The step on screen, in user space: from the page's centre to `step` pixels away.+ let user = |s: Pos2| {+ let (vx, vy) = xf.screen_to_view(s);+ let u = p.view_to_user(vx, vy);+ [f64::from(u[0]), f64::from(u[1])]+ };+ let (a, b) = (user(xf.rect.center()), user(xf.rect.center() + step));+ let (dx, dy) = (b[0] - a[0], b[1] - a[1]);+ if dx.is_finite() && dy.is_finite() && (dx != 0.0 || dy != 0.0) {+ view.pending_edit = Some(Edit::MoveAnnotation { page, index, dx, dy });+ }+ }diff --cc crates/ui-egui/src/tools/comments/tests.rsindex 000000000,fff7f0136..286c5265dmode 000000,100644..100644--- a/crates/ui-egui/src/tools/comments/tests.rs+++ b/crates/ui-egui/src/tools/comments/tests.rs@@@ -1,0 -1,386 +1,424 @@@+ use super::*;++ /// A selected line is drawn where it is going: moved by its body (both ends follow the+ /// pointer), with an end dragged (that end alone), and as released until the page is drawn.+ #[test]+ fn a_moved_or_reshaped_line_is_drawn_at_its_new_points() {+ let line = [[10.0, 10.0], [50.0, 10.0]];+ let to_user = |p: Pos2| [f64::from(p.x), f64::from(p.y)];+ let moving = Gesture::Move { page: 0, index: 3, from: pos2(20.0, 10.0) };+ let at = Some(pos2(25.0, 30.0));+ assert_eq!(changing_points(Some(&moving), None, (0, 3), &line, to_user, at, false), Some(vec![[15.0, 30.0], [55.0, 30.0]]));+ assert_eq!(changing_points(Some(&moving), None, (0, 4), &line, to_user, at, false), None, "another comment's move");+ let released = Edit::MoveAnnotation { page: 0, index: 3, dx: 5.0, dy: 20.0 };+ assert_eq!(changing_points(None, Some(&released), (0, 3), &line, to_user, None, false), Some(vec![[15.0, 30.0], [55.0, 30.0]]));+ let dragging = Gesture::Reshape { page: 0, index: 3, point: 1, points: line.to_vec() };+ let to = Some(pos2(60.0, 10.0));+ assert_eq!(changing_points(Some(&dragging), None, (0, 3), &line, to_user, to, false), Some(vec![[10.0, 10.0], [60.0, 10.0]]));+ assert_eq!(changing_points(None, None, (0, 3), &line, to_user, to, false), None, "not changing");+ }++ /// A sticky note on a page turned a quarter is drawn upright beside its `/Rect`: an edit+ /// composer stays open while the drawn note is partly in view, even with `/Rect` out of it.+ #[test]+ fn an_upright_note_on_a_turned_page_is_in_view_where_it_is_drawn() {+ let note = |no_rotate| Annotation {+ page: 0,+ subtype: "Text".into(),+ author: None,+ contents: None,+ modified: None,+ name: None,+ in_reply_to: None,+ parent: None,+ grouped: false,+ rect: [40.0, 20.0, 70.0, 40.0],+ color: None,+ index: 0,+ state: None,+ quads: Vec::new(),+ locked: false,+ intent: None,+ fill_sign: false,+ no_rotate,+ points: Vec::new(),+ };+ let page = PageInfo { width: 140.0, height: 200.0, label: String::new(), crop: [0.0, 0.0, 200.0, 140.0], rotation: 90 };+ let xf = PageXform { rect: Rect::from_min_size(Pos2::ZERO, vec2(140.0, 200.0)), rot: 0, pw: 140.0, ph: 200.0 };+ let prefs = CommentPrefs::default();+ // Screen x is user y here: `/Rect` spans x 20..40, the upright note x 40..70.+ let viewport = Rect::from_min_max(pos2(50.0, 0.0), pos2(140.0, 200.0));+ for (no_rotate, in_view) in [(true, true), (false, false)] {+ let info = DocInfo { pages: vec![page.clone()], annotations: vec![note(no_rotate)], ..Default::default() };+ let cx = PageCx {+ page: 0,+ xf: &xf,+ ptr: &PagePointer::default(),+ info: &info,+ tool: QuickTool::Select,+ prefs: &prefs,+ allowed: true,+ hidden: false,+ redact_mark: ([0.0; 3], 1.0),+ };+ assert_eq!(edited_in_view(&cx, 0, viewport), in_view, "no_rotate: {no_rotate}");+ }+ }++ use pdfcraft_render::TextGlyph;++ /// One glyph per character, `w` points wide, on a line of `em`-point text whose baseline is at `y`, drawn+ /// along `direction` (a unit vector in view space, y down).+ fn line(chars: &str, x: f32, y: f32, w: f32, em: f32, direction: [f32; 2]) -> PageText {+ let [dx, dy] = direction;+ // "Up" for the glyph: its writing direction turned a quarter counterclockwise (y down).+ let [ux, uy] = [dy, -dx];+ let glyphs = chars+ .chars()+ .enumerate()+ .map(|(i, c)| {+ let start = [x + dx * w * i as f32, y + dy * w * i as f32];+ let at = |along: f32, up: f32| [start[0] + dx * along + ux * up, start[1] + dy * along + uy * up];+ let quad = [at(0.0, -0.2 * em), at(w, -0.2 * em), at(w, 0.8 * em), at(0.0, 0.8 * em)];+ let xs = quad.map(|p| p[0]);+ let ys = quad.map(|p| p[1]);+ let rect = [+ xs.into_iter().fold(f32::INFINITY, f32::min),+ ys.into_iter().fold(f32::INFINITY, f32::min),+ xs.into_iter().fold(f32::NEG_INFINITY, f32::max),+ ys.into_iter().fold(f32::NEG_INFINITY, f32::max),+ ];+ TextGlyph { text: c.to_string(), rect, quad, direction }+ })+ .collect::<Vec<_>>();+ let n = glyphs.len();+ PageText { glyphs, line_of: vec![0; n], space_before: vec![false; n] }+ }+++fn annotation(subtype: &str, contents: Option<&str>, fill_sign: bool) -> Annotation {++ Annotation {++ page: 0,++ subtype: subtype.into(),++ author: None,++ contents: contents.map(str::to_string),++ modified: None,++ name: None,++ in_reply_to: None,++ parent: None,++ grouped: false,++ rect: [0.0; 4],++ color: None,++ index: 0,++ state: None,++ quads: Vec::new(),++ locked: false,++ intent: None,++ fill_sign,++ no_rotate: false,++ points: Vec::new(),++ }++}++++#[test]++fn the_hover_tip_skips_fill_and_sign_marks_replies_and_bare_highlights_when_asked() {++ let prefs = CommentPrefs::default();++ assert_eq!(hover_tip(&annotation("FreeText", Some("Hello"), false), &prefs).as_deref(), Some("FreeText\nHello"));++ assert_eq!(hover_tip(&annotation("FreeText", Some("Hello"), true), &prefs), None);++ let reply = Annotation { in_reply_to: Some("1 0 R".into()), parent: Some((0, 1)), ..annotation("Text", Some("Agreed"), false) };++ assert_eq!(hover_tip(&reply, &prefs), None);++ let bare = Annotation { author: Some("Ana".into()), ..annotation("Highlight", None, false) };++ assert_eq!(hover_tip(&bare, &prefs).as_deref(), Some("Ana"));++ let hide = CommentPrefs { hide_empty_highlight_hover: true, ..CommentPrefs::default() };++ assert_eq!(hover_tip(&bare, &hide), None);++ assert_eq!(hover_tip(&annotation("Highlight", Some("Check this"), false), &hide).as_deref(), Some("Highlight\nCheck this"));++}+++ fn near(a: Option<([f32; 2], f32)>, b: ([f32; 2], f32)) -> bool {+ a.is_some_and(|([x, y], s)| (x - b.0[0]).abs() < 1e-3 && (y - b.0[1]).abs() < 1e-3 && (s - b.1).abs() < 1e-3)+ }++ #[test]+ fn the_caret_snaps_to_the_nearer_edge_on_the_baseline() {+ let text = line("abcd", 20.0, 100.0, 10.0, 14.0, [1.0, 0.0]);+ // "c" spans 40..50: its left half snaps before it, its right half after it.+ assert!(near(caret_snap(&text, 43.0, 95.0), ([40.0, 100.0], 7.0)));+ assert!(near(caret_snap(&text, 47.0, 92.0), ([50.0, 100.0], 7.0)));+ // Just past the last character, on the line: after it.+ assert!(near(caret_snap(&text, 63.0, 99.0), ([60.0, 100.0], 7.0)));+ }++ #[test]+ fn the_snapped_caret_follows_the_page_into_user_space() {+ let text = line("abcd", 20.0, 100.0, 10.0, 14.0, [1.0, 0.0]);+ let page = |rotation, user_unit: f32| PageInfo {+ width: 300.0 * user_unit,+ height: 200.0 * user_unit,+ label: "1".into(),+ crop: [0.0, 0.0, 300.0, 200.0],+ rotation,+ };+ // An unrotated page: view y = 100 is user y = 100 (y up from the bottom of a 200 pt page).+ let (tip, side) = snapped_caret(&page(0, 1.0), &text, 43.0, 95.0).expect("snaps");+ assert!((tip[0] - 40.0).abs() < 1e-3 && (tip[1] - 100.0).abs() < 1e-3 && (side - 7.0).abs() < 1e-3);+ // /UserUnit 2: the view is twice as large, so the same text is half as many user units.+ let doubled = line("abcd", 40.0, 200.0, 20.0, 28.0, [1.0, 0.0]);+ let (tip, side) = snapped_caret(&page(0, 2.0), &doubled, 86.0, 190.0).expect("snaps");+ assert!((tip[0] - 40.0).abs() < 1e-3 && (tip[1] - 100.0).abs() < 1e-3 && (side - 7.0).abs() < 1e-3, "{tip:?} {side}");+ // A rotated page: the caret would lie on its side, so it stays at the click.+ for rotation in [90, 180, 270] {+ assert_eq!(snapped_caret(&page(rotation, 1.0), &text, 43.0, 95.0), None, "/Rotate {rotation}");+ }+ }++ #[test]+ fn away_from_upright_horizontal_text_the_caret_stays_at_the_click() {+ let text = line("abcd", 20.0, 100.0, 10.0, 14.0, [1.0, 0.0]);+ assert_eq!(caret_snap(&text, 200.0, 100.0), None, "far to the right");+ assert_eq!(caret_snap(&text, 40.0, 40.0), None, "far above the line");+ assert_eq!(caret_snap(&PageText::default(), 40.0, 100.0), None, "no text");+ for (direction, what) in [([0.0, 1.0], "vertical"), ([-1.0, 0.0], "upside down"), ([0.995, 0.0998], "sloped")] {+ let turned = line("abcd", 20.0, 100.0, 10.0, 14.0, direction);+ let [x0, y0, x1, y1] = turned.glyphs[2].rect;+ assert_eq!(caret_snap(&turned, (x0 + x1) / 2.0, (y0 + y1) / 2.0), None, "{what}");+ }+ }++ #[test]+ fn recent_custom_colours_dedupe_cap_and_skip_swatches() {+ // #1193: "Other colour…" remembers what it applied, newest first.+ let ctx = egui::Context::default();+ assert!(recent_custom_colours(&ctx).is_empty());+ for i in 0..7 {+ remember_custom_colour(&ctx, [0.1 * f64::from(i), 0.3, 0.7]);+ }+ let recent = recent_custom_colours(&ctx);+ assert_eq!(recent.len(), RECENT_CUSTOM, "capped");+ assert!(same_colour(&recent[0], &[0.6, 0.3, 0.7]), "newest first: {recent:?}");+ remember_custom_colour(&ctx, [0.2, 0.3, 0.7]);+ let again = recent_custom_colours(&ctx);+ assert_eq!(again.len(), RECENT_CUSTOM);+ assert!(+ same_colour(&again[0], &[0.2, 0.3, 0.7]) && again.iter().filter(|c| same_colour(c, &[0.2, 0.3, 0.7])).count() == 1,+ "moved, not repeated"+ );+ // Swatches and unusable values are not remembered; out-of-range ones are clamped.+ remember_custom_colour(&ctx, SWATCHES[0].1);+ remember_custom_colour(&ctx, [f64::NAN, 0.0, 0.0]);+ assert!(same_colour(&recent_custom_colours(&ctx)[0], &[0.2, 0.3, 0.7]));+ remember_custom_colour(&ctx, [1.7, -0.5, 0.25]);+ assert!(same_colour(&recent_custom_colours(&ctx)[0], &[1.0, 0.0, 0.25]));+ }++ #[test]+ fn other_colour_applies_the_picked_colour_once() {+ // #1193: the swatch grid has a full picker; Apply returns its colour and remembers it.+ use egui_kittest::kittest::Queryable;+ let current = [0.2, 0.4, 0.6];+ let mut h = egui_kittest::Harness::new_ui_state(+ |ui, picked: &mut Vec<Rgb>| {+ if let Some(c) = swatch_grid(ui, Some(current)) {+ picked.push(c);+ }+ },+ Vec::new(),+ );+ h.run();+ assert!(h.query_by_label("Apply").is_none(), "the picker starts closed");+ assert!(h.query_by_label("Recent colours").is_none());+ h.get_by_label("Other colour…").click();+ h.run();+ h.get_by_label("Apply").click();+ h.run();+ let picked = h.state().clone();+ assert_eq!(picked.len(), 1, "one choice: {picked:?}");+ assert!(same_colour(&picked[0], ¤t), "the picker opens on the current colour: {picked:?}");+ assert!(h.query_by_label("Apply").is_none(), "applying closes the picker");+ assert!(h.query_by_label("Recent colours").is_some(), "the colour is offered again");+ }++ #[test]+ fn two_grids_in_one_parent_open_their_pickers_separately() {+ // Redaction properties and Prepare a form draw two grids in one parent ui.+ use egui_kittest::kittest::Queryable;+ let mut h = egui_kittest::Harness::new_ui(|ui| {+ let _ = swatch_grid(ui, Some([0.2, 0.4, 0.6]));+ let _ = swatch_grid(ui, Some([0.6, 0.4, 0.2]));+ });+ h.run();+ let plus = h.query_all_by_label("Other colour…").collect::<Vec<_>>();+ assert_eq!(plus.len(), 2);+ plus[0].click();+ h.run();+ assert_eq!(h.query_all_by_label("Apply").count(), 1, "only the first grid's picker opens");+ }++ #[test]+ fn other_colour_opens_the_picker_inside_the_quick_bar_popup() {+ use egui_kittest::kittest::Queryable;+ let mut h = egui_kittest::Harness::new_ui_state(+ |ui, prefs: &mut CommentPrefs| {+ let _ = quick_bar_controls(ui, CommentTool::Highlight, prefs);+ },+ CommentPrefs::default(),+ );+ h.run();+ h.get_by_label("Colour").click();+ h.run();+ h.get_by_label("Other colour…").click();+ h.run();+ assert!(h.query_by_label("Apply").is_some(), "the popup stays open with the picker showing");+ h.get_by_label("Apply").click();+ h.run();+ assert!(h.query_by_label("Other colour…").is_none(), "applying a colour closes the popup");+ }++ #[test]+ fn other_colour_opens_the_picker_inside_the_quick_bar_fill_popup() {+ use egui_kittest::kittest::Queryable;+ let prefs = CommentPrefs::default();+ let fill_label = if prefs.style(CommentTool::Rectangle).fill.is_some() { "Fill colour" } else { "Fill colour: none" };+ let mut h = egui_kittest::Harness::new_ui_state(+ |ui, prefs: &mut CommentPrefs| {+ let _ = quick_bar_controls(ui, CommentTool::Rectangle, prefs);+ },+ prefs,+ );+ h.ctx.set_fonts(theme::font_definitions());+ h.run();+ h.get_by_label(fill_label).click();+ h.run();+ h.get_by_label("Other colour…").click();+ h.run();+ assert!(h.query_by_label("Apply").is_some(), "the popup stays open with the picker showing");+ h.get_by_label("Apply").click();+ h.run();+ assert!(h.query_by_label("No fill").is_none(), "applying a colour closes the popup");+ assert!(h.state().style(CommentTool::Rectangle).fill.is_some());+ }++ #[test]+ fn context_menu_colour_submenu_keeps_its_picker_open_and_a_swatch_closes_the_menu() {+ use egui_kittest::kittest::Queryable;+ let info = DocInfo {+ pages: vec![PageInfo { width: 300.0, height: 400.0, label: String::new(), crop: [0.0, 0.0, 300.0, 400.0], rotation: 0 }],+ annotations: vec![Annotation {+ page: 0,+ subtype: "Square".into(),+ author: None,+ contents: None,+ modified: None,+ name: None,+ in_reply_to: None,+ parent: None,+ grouped: false,+ rect: [10.0, 10.0, 50.0, 50.0],+ color: None,+ index: 0,+ state: None,+ quads: Vec::new(),+ locked: false,+ intent: None,+ fill_sign: false,+ points: Vec::new(),+ no_rotate: false,+ }],+ ..Default::default()+ };+ let mut view = DocView::new(pdfcraft_engine::DocId(1), &info, crate::canvas::ViewDefaults::default());+ view.comments.selected = Some((0, 0));+ let prefs = CommentPrefs::default();+ let mut h = egui_kittest::Harness::new_ui_state(+ |ui, (view, actions): &mut (DocView, Vec<CanvasAction>)| {+ ui.button("Page").context_menu(|ui| {+ if let Some(a) = context_menu(ui, view, &info, &prefs, true, true) {+ actions.push(a);+ }+ });+ },+ (view, Vec::new()),+ );+ h.run();+ h.get_by_label("Page").click_secondary();+ h.run();+ h.get_by_label("Colour").click();+ h.run();+ h.get_by_label("Other colour…").click();+ h.run();+ assert!(h.query_by_label("Apply").is_some(), "the submenu stays open with the picker showing");+ h.get_by_label("Red").click();+ h.run();+ assert!(h.query_by_label("Edit text…").is_none(), "picking a swatch closes the whole menu");+ let actions = &h.state().1;+ assert!(+ matches!(actions.as_slice(), [CanvasAction::Edit(e)] if matches!(**e, Edit::StyleAnnotation { page: 0, index: 0, color: Some(_), .. })),+ "{actions:?}"+ );+ }++ #[test]+ fn shift_keeps_the_current_proportions_unless_the_box_has_its_own() {+ let r = Rect::from_min_max(pos2(100.0, 100.0), pos2(196.0, 132.0));+ assert_eq!(corner_ratio(r, None, false), None);+ assert_eq!(corner_ratio(r, None, true), Some(3.0));+ assert_eq!(corner_ratio(r, Some(2.0), false), Some(2.0));+ assert_eq!(corner_ratio(r, Some(2.0), true), Some(2.0));+ // A degenerate box has no proportions to keep (no division by zero).+ let flat = Rect::from_min_max(pos2(100.0, 100.0), pos2(196.0, 100.0));+ assert_eq!(corner_ratio(flat, None, true), None);+ // Dragging a corner with Shift held scales the box instead of stretching it.+ let out = resized(r, (1, 1), vec2(48.0, 0.0), corner_ratio(r, None, true));+ assert_eq!(out.min, r.min);+ assert!((out.width() / out.height() - 3.0).abs() < 0.001);+ }++ #[test]+ fn proportional_corners_keep_the_opposite_anchor_and_edges_stretch_one_axis() {+ let r = Rect::from_min_max(pos2(100.0, 100.0), pos2(196.0, 132.0));+ for (hx, hy) in [(-1, -1), (1, -1), (-1, 1), (1, 1)] {+ for (dx, dy) in [(24.0, 0.0), (0.0, 16.0), (-48.0, -20.0), (-200.0, -200.0)] {+ let out = resized(r, (hx, hy), vec2(f32::from(hx) * dx, f32::from(hy) * dy), Some(3.0));+ assert_eq!(handle_pos(out, (-hx, -hy)), handle_pos(r, (-hx, -hy)));+ assert!((out.width() / out.height() - 3.0).abs() < 0.001);+ assert!(out.width() >= 4.0 && out.height() >= 4.0);+ }+ }+ for handle in [(0, -1), (1, 0), (0, 1), (-1, 0)] {+ let out = resized(r, handle, vec2(24.0, 16.0), Some(3.0));+ assert_eq!(out, resized(r, handle, vec2(24.0, 16.0), None));+ assert_eq!(if handle.0 == 0 { out.width() } else { out.height() }, if handle.0 == 0 { r.width() } else { r.height() });+ }+ // Ordinary comment corners keep their existing independent width/height behavior.+ let free = resized(r, (1, 1), vec2(24.0, 0.0), None);+ assert_eq!(free.size(), vec2(120.0, 32.0));+ }++ #[test]+ fn tools_round_trip_through_their_commands() {+ for t in ALL {+ assert_eq!(CommentTool::from_command(t.command()), Some(t));+ assert!(pdfcraft_engine::commands::command(t.command()).is_some(), "{} is registered", t.command());+ assert!(icons::exists(t.icon()), "icon {}", t.icon());+ assert!(GROUPS[t.group()].contains(&t));+ }+ }++ #[test]+ fn drawn_shapes_ignore_slips() {+ assert_eq!(drawn_shape(CommentTool::Rectangle, &[[0.0, 0.0], [1.0, 1.0]]), None);+ assert_eq!(drawn_shape(CommentTool::Rectangle, &[[10.0, 0.0], [0.0, 10.0]]), Some(Shape::Rectangle { rect: [0.0, 0.0, 10.0, 10.0] }));+ assert_eq!(drawn_shape(CommentTool::Ink, &[[0.0, 0.0]]), Some(Shape::Ink { strokes: vec![vec![[0.0, 0.0]]] }));+ assert!(matches!(+ drawn_shape(CommentTool::Arrow, &[[0.0, 0.0], [5.0, 0.0]]),+ Some(Shape::Line { start: LineEnding::None, end: LineEnding::OpenArrow, .. })+ ));+ }++ #[test]+ fn text_boxes_fit_their_text() {+ let r = text_box_rect([100.0, 500.0], "Hi", 12.0, 0);+ assert_eq!((r[0], r[3]), (100.0, 500.0));+ assert!(r[2] - r[0] < 60.0);+ let long = text_box_rect([0.0, 500.0], &"word ".repeat(80), 12.0, 0);+ assert_eq!(long[2], 300.0);+ assert!(long[3] - long[1] > 50.0);+ }diff --cc crates/ui-egui/src/tools/content_ui.rsindex 56f5ac272,ee99ee0a2..a0d9cefa1--- a/crates/ui-egui/src/tools/content_ui.rs+++ b/crates/ui-egui/src/tools/content_ui.rs@@@ -7,8 -7,7 +7,8 @@@ use egui::{Color32, CornerRadius, Pos2use pdfcraft_engine::{Added, AddedContent, AddedText, Edit};use pdfcraft_render::DocInfo;- use crate::canvas::{DocView, PageXform};+ use crate::canvas::{DocView, PageToolContext, PageXform};+use crate::page_cursor::Layer;use crate::page_pointer::PagePointer;use crate::theme::Tokens;use crate::widgets;@@@ -359,6 -353,7 +354,7 @@@ pub(crate) fn page_inputstyle: &AddedText,view: &mut DocView,) -> bool {- let PageToolContext { ui, resp, xf, ptr, page, info, .. } = cx;++ let PageToolContext { resp, xf, ptr, page, info, .. } = cx;let mut consumed = false;let pointer = ptr.pos;let cv = &mut view.content;diff --cc crates/ui-egui/src/tools/edit_text_ui.rsindex 000000000,a14e4e661..224bc3f54mode 000000,100644..100644--- a/crates/ui-egui/src/tools/edit_text_ui.rs+++ b/crates/ui-egui/src/tools/edit_text_ui.rs@@@ -1,0 -1,894 +1,891 @@@+ //! Edit a PDF ▸ Edit text & images: boxes around the paragraphs and images already on the page.+ //! Click a paragraph to edit it in place (⌘Enter or clicking away applies and rewraps it to the+ //! box, Esc cancels); drag it to move it, or drag the handle on its left or right edge to rewrap+ //! it to a new width. Click an image to select it: drag to move, drag a corner to resize (keeping+ //! its proportions), right-click for rotate, flip, replace, save and delete; Delete removes it.++ use std::collections::BTreeMap;+ use std::sync::Arc;++ use egui::{Color32, CornerRadius, FontFamily, FontId, Pos2, Rect, Stroke};+ use pdfcraft_engine::{Edit, ObjectKind, ObjectTarget};+ use pdfcraft_render::DocInfo;++ use crate::canvas::{DocView, PageToolContext, PageXform};++use crate::page_cursor::Layer;+ use crate::page_pointer::PagePointer;++ mod background;+ mod image;+ mod layout;++ pub(crate) use background::TextBackground;+ pub use image::{CropMode, ImageSelection};+ pub(crate) use image::{ImageAction, ImageCx, image_input, image_owns_pointer};+ #[cfg(test)]+ use image::{rotate_knob, turn_degrees};+ #[cfg(test)]+ use layout::{DARK_EDITOR_FILL, contrast};+ pub(crate) use layout::{caret_color_on, editor_fill, editor_font, install_source_fonts};+ use layout::{color32, editor_galley, editor_job, look_of, luminance, unseen};++ const ACCENT: Color32 = Color32::from_rgb(0x14, 0x73, 0xE6);++ #[derive(Clone, Copy, PartialEq)]+ enum TextTarget {+ Block(usize),+ Added(usize),+ }++ /// How many faint Edit-text outlines are drawn per page per frame. CAD plots can draw+ /// ~1000 tiny images on one page; stroking all of them every frame (plus a hover query+ /// per box) stalls the UI. Past this, only the selected and hovered boxes are outlined:+ /// hit-testing still covers every image, so nothing becomes unselectable.+ const MAX_OUTLINES: usize = 250;++ /// A paragraph being edited.+ #[derive(Clone, Debug, PartialEq)]+ pub struct LineEditor {+ pub selection: Option<std::ops::Range<usize>>,+ pub font_resource: Option<String>,+ pub page: usize,+ pub block: usize,+ pub text: String,+ original: String,+ rect: Rect,+ /// The original PDF rectangle, in user space. It is converted again each frame so the editor+ /// stays attached while the page is zoomed, scrolled, or rotated.+ source_rect: [f32; 4],+ multiline: bool,+ source: Option<(pdfcraft_engine::TextBlock, Vec<pdfcraft_engine::TextLine>)>,+ pub(crate) fonts: BTreeMap<String, String>,+ /// The draft extends outside the source container; its frame follows the live draft bounds.+ pub overflow: bool,+ /// The initial source container width in screen pixels.+ max_width: f32,+ /// Current screen-space size. Recomputed from the current page transform before painting.+ size: f32,+ /// Take the keyboard focus on the next frame.+ pub(crate) focus: bool,+ /// Whether the text box had the keyboard at the end of the editor's last frame+ /// ([`lost_focus_once`]).+ had_focus: bool,+ /// The Format text panel's values, and what the paragraph had (to send only changes).+ pub look: pdfcraft_engine::AddedText,+ look0: pdfcraft_engine::AddedText,+ /// A standard family was picked from the font list. The family guessed from a PDF font name+ /// (Calibri reads as Helvetica) can be the one picked, so comparing `look` with `look0` alone+ /// would miss the choice.+ family_chosen: bool,+ /// Underline, line spacing (× size; 0 = the paragraph's own), character spacing (pt) and+ /// horizontal scale (%), and what they were.+ pub extras: Extras,+ extras0: Extras,+ }++ #[derive(Clone, Copy, Debug, PartialEq)]+ pub struct Extras {+ pub underline: bool,+ pub line_spacing: f64,+ pub char_spacing: f64,+ pub scale: f64,+ }++ impl Default for Extras {+ fn default() -> Self {+ Extras { underline: false, line_spacing: 0.0, char_spacing: 0.0, scale: 100.0 }+ }+ }++ impl LineEditor {+ /// What Format text's font list shows: the chosen page font, a standard family picked+ /// instead, or the paragraph's own font (its `/BaseFont` without the subset tag).+ pub(crate) fn font_shown(&self, sources: &[(String, String)]) -> String {+ if let Some(face) = self.font_resource.as_ref().and_then(|r| sources.iter().find(|(res, _)| res == r)).map(|(_, face)| face) {+ return face.clone();+ }+ if self.look.family != self.look0.family || self.family_chosen {+ return self.look.family.label().to_string();+ }+ let base = self.source.as_ref().map(|(block, _)| block.base_font.as_str()).unwrap_or_default();+ // "ABCDEF+Calibri" is a subset of Calibri.+ let name = match base.split_once('+') {+ Some((tag, rest)) if tag.len() == 6 && tag.bytes().all(|b| b.is_ascii_uppercase()) => rest,+ _ => base,+ };+ if name.is_empty() { tl!("Keep source fonts").to_string() } else { name.to_string() }+ }++ /// Back to the paragraph's own font: no page font chosen and the family it started with.+ pub(crate) fn keep_source_font(&mut self) {+ self.font_resource = None;+ self.look.family = self.look0.family;+ self.family_chosen = false;+ }++ /// A standard family picked from the font list, replacing the paragraph's font even when it+ /// is the family the paragraph's font name reads as.+ pub(crate) fn choose_family(&mut self, family: pdfcraft_engine::FontFamily) {+ self.font_resource = None;+ self.look.family = family;+ self.family_chosen = true;+ }++ pub(crate) fn has_changes(&self) -> bool {+ self.changes_with(&self.text)+ }++ /// Whether the paragraph with `text` in it differs from what was opened.+ fn changes_with(&self, text: &str) -> bool {+ text != self.original || self.look != self.look0 || self.extras != self.extras0 || self.family_chosen+ }++ /// Extra width permitted by the editor. Source containers now remain fixed.+ pub fn growth(&self) -> Option<f32> {+ (self.max_width > self.rect.width()).then_some(self.max_width)+ }++ /// Whether the edited text differs from the original (unsaved changes).+ pub fn has_unsaved_text(&self) -> bool {+ self.text != self.original+ }++ /// The formatting the panel changed.+ pub fn style(&self) -> pdfcraft_engine::BlockStyle {+ let (l, o) = (&self.look, &self.look0);+ let mut style = pdfcraft_engine::BlockStyle {+ resource: self.font_resource.clone(),+ family: (l.family != o.family || self.family_chosen || l.bold != o.bold || l.italic != o.italic).then_some((l.family, l.bold, l.italic)),+ size: (l.size != o.size).then_some(l.size),+ color: (l.color != o.color).then_some(l.color),+ align: (l.align != o.align).then_some(l.align),+ underline: (self.extras.underline != self.extras0.underline).then_some(self.extras.underline),+ line_spacing: (self.extras.line_spacing != self.extras0.line_spacing && self.extras.line_spacing > 0.0)+ .then_some(self.extras.line_spacing),+ char_spacing: (self.extras.char_spacing != self.extras0.char_spacing).then_some(self.extras.char_spacing),+ scale: (self.extras.scale != self.extras0.scale).then_some(self.extras.scale),+ ..Default::default()+ };+ if let Some(range) = &self.selection+ && (style.family.is_some()+ || style.resource.is_some()+ || style.size.is_some()+ || style.color.is_some()+ || style.underline.is_some()+ || style.char_spacing.is_some()+ || style.scale.is_some())+ {+ style.ranges.push(pdfcraft_engine::RangeStyle {+ range: range.clone(),+ family: style.family.take(),+ resource: style.resource.take(),+ size: style.size.take(),+ color: style.color.take(),+ underline: style.underline.take(),+ char_spacing: style.char_spacing.take(),+ scale: style.scale.take(),+ });+ }+ style+ }++ /// After applying formatting: the paragraph now has it.+ pub fn applied(&mut self) {+ self.selection = None;+ self.font_resource = None;+ self.family_chosen = false;+ self.look0 = self.look.clone();+ self.extras0 = self.extras;+ self.original = self.text.clone();+ self.focus = true;+ }++ /// Adopt the rewritten paragraph's current geometry before the next overlay frame.+ pub(crate) fn refresh_source(&mut self, block: &pdfcraft_engine::TextBlock, lines: Vec<pdfcraft_engine::TextLine>) {+ self.source_rect = block.rect.map(|v| v as f32);+ self.multiline = block.rows.len() > 1;+ self.source = Some((block.clone(), lines));+ self.text = block.editor_text.clone();+ self.original = self.text.clone();+ }+ }++ /// What a drag on a paragraph box takes hold of.+ #[derive(Clone, Copy, Debug, PartialEq)]+ enum Grip {+ Move,+ /// An edge (screen left or right), dragged to rewrap the paragraph.+ Left,+ Right,+ }++ /// A paragraph box being dragged: moved, or (from a handle on its left or right edge) resized.+ #[derive(Clone, Copy, Debug, PartialEq)]+ pub struct BlockDrag {+ page: usize,+ block: usize,+ /// A paragraph index belongs to the document generation where the press was resolved.+ generation: u64,+ /// Where the drag started (screen).+ start: Pos2,+ grip: Grip,+ }++ /// How far an edge grip reaches either side of a box's edge (screen pixels).+ const EDGE_REACH: f32 = 6.0;+ /// How far outside an open paragraph's frame the pointer still means the frame (screen pixels).+ const FRAME_REACH: f32 = 4.0;++ /// The rewrap handles drawn on a paragraph box's left and right edges (screen).+ fn width_handles(b: Rect) -> [Rect; 2] {+ let h = (b.height() * 0.5).clamp(14.0, 28.0);+ [b.left(), b.right()].map(|x| Rect::from_center_size(Pos2::new(x, b.center().y), egui::vec2(7.0, h)))+ }++ /// The edge of `b` that `p` grabs: anywhere along its height, within reach of the line. A narrow+ /// box keeps its middle for moving.+ fn edge_at(b: Rect, p: Pos2) -> Option<Grip> {+ if p.y < b.top() - EDGE_REACH || p.y > b.bottom() + EDGE_REACH {+ return None;+ }+ let inside = EDGE_REACH.min(b.width() / 4.0);+ let (dl, dr) = (p.x - b.left(), b.right() - p.x);+ match (dl >= -EDGE_REACH && dl <= inside, dr >= -EDGE_REACH && dr <= inside) {+ (true, true) if dl <= dr => Some(Grip::Left),+ (_, true) => Some(Grip::Right),+ (true, false) => Some(Grip::Left),+ _ => None,+ }+ }++ /// The topmost box under `p` and what it grabs there; edges only on an upright page.+ fn grab_at(boxes: &[Rect], p: Pos2, upright: bool) -> Option<(usize, Grip)> {+ boxes.iter().enumerate().rev().find_map(|(i, b)| match upright.then(|| edge_at(*b, p)).flatten() {+ Some(g) => Some((i, g)),+ None => b.contains(p).then_some((i, Grip::Move)),+ })+ }++ /// A paragraph's box on screen: its text rect (user space), with a little room around it.+ fn paragraph_box(xf: &PageXform, info: &DocInfo, page: usize, rect: [f64; 4]) -> Rect {+ xf.user_rect(info, page, rect.map(|v| v as f32)).expand(2.0)+ }++ /// The width handles need the page upright (or upside down): on a quarter-turned page the+ /// screen's horizontal is the paragraph's vertical.+ fn has_edges(info: &DocInfo, page: usize) -> bool {+ info.pages.get(page).is_some_and(|p| p.rotation % 180 == 0)+ }++ /// Whether a press at `p` takes hold of the width handle of one of the paragraphs `rects` (user+ /// space). The handle is drawn half outside the box and grabs from a little further out still,+ /// where a press is not on the box itself, so area selection must leave it to [`page_input`].+ pub(crate) fn grabs_edge(xf: &PageXform, info: &DocInfo, page: usize, mut rects: impl Iterator<Item = [f64; 4]>, p: Pos2) -> bool {+ has_edges(info, page) && rects.any(|r| edge_at(paragraph_box(xf, info, page, r), p).is_some())+ }++ fn user_box(xf: &PageXform, info: &DocInfo, page: usize, r: Rect) -> [f64; 4] {+ let p = &info.pages[page];+ let (a, b) = (xf.screen_to_view(r.min), xf.screen_to_view(r.max));+ let (u, v) = (p.view_to_user(a.0, a.1), p.view_to_user(b.0, b.1));+ [u[0].min(v[0]) as f64, u[1].min(v[1]) as f64, u[0].max(v[0]) as f64, u[1].max(v[1]) as f64]+ }++ /// Open `block` on `page` in the inline editor. The box's geometry and source are read from the+ /// `lines` handed in, so callers pass the document's current inventory.+ fn open_editor(cx: PageToolContext<'_>, lines: &[pdfcraft_engine::TextBlock], boxes: &[Rect], block: usize, view: &mut DocView) {+ let PageToolContext { ui, xf, doc, page, .. } = cx;+ view.pending_text_open = None;+ let (Some(l), Some(b)) = (lines.get(block), boxes.get(block)) else { return };+ view.image_selection = None;+ let source_lines = doc.text_lines(page);+ let text = l.editor_text.clone();+ // Screen pixels per point, from the box's width.+ let scale = (b.width() - 4.0) / ((l.rect[2] - l.rect[0]).max(1.0) as f32);+ // How far the editor box may grow: a single-line paragraph's rewrite grows to the+ // page's right edge, a multi-line paragraph rewraps to its own width.+ let right = xf.rect.right().min(view.viewport_rect().right()) - 6.0;+ let max_width = if l.rows.len() == 1 { (right - b.left()).max(b.width()) } else { b.width() };+ view.line_editor = Some(LineEditor {+ selection: None,+ font_resource: None,+ page,+ block,+ text: text.clone(),+ original: text,+ rect: *b,+ source_rect: l.rect.map(|v| v as f32),+ multiline: l.rows.len() > 1,+ source: Some((l.clone(), source_lines)),+ fonts: install_source_fonts(ui.ctx(), doc, page),+ overflow: false,+ max_width,+ size: (l.size as f32 * scale).clamp(8.0, 72.0),+ focus: true,+ had_focus: false,+ look: look_of(l),+ look0: look_of(l),+ family_chosen: false,+ extras: Extras::default(),+ extras0: Extras::default(),+ });+ }++ /// Lines and their screen boxes for a page; hover outlines, click opens the editor. Returns+ /// `true` when the pointer was used.+ pub(crate) fn page_input(cx: PageToolContext<'_>, lines: &[pdfcraft_engine::TextBlock], view: &mut DocView, allow_interaction: bool) -> bool {+ let PageToolContext { ui, resp, xf, ptr, page, doc, .. } = cx;+ let info = &doc.info;+ if view.block_drag.is_some_and(|d| d.generation != doc.edit_generation()) {+ view.block_drag = None;+ return true;+ }+ let boxes: Vec<Rect> = lines.iter().map(|l| paragraph_box(xf, info, page, l.rect)).collect();+ // Outlines stay on their page, like its text (#3061).+ let painter = ui.painter().with_clip_rect(ui.clip_rect().intersect(xf.rect.expand(1.0)));+ let active = view.line_editor.as_ref().filter(|e| e.page == page).map(|e| e.block);+ for (i, b) in boxes.iter().enumerate() {+ if active != Some(i) {+ painter.rect_stroke(*b, CornerRadius::same(2), Stroke::new(0.75, ACCENT.gamma_multiply(0.35)), egui::StrokeKind::Outside);+ }+ }+ // A box a switching click asked for opens now, once the edit queued with that click has+ // applied and `lines`/`boxes` are the document's new inventory (#2022).+ if allow_interaction+ && active.is_none()+ && let Some((open_page, key)) = view.pending_text_open.clone()+ && open_page == page+ {+ // The edit may have regrouped the page: open the paragraph that was clicked, wherever it+ // is now, and none if it was merged into another (#2516).+ match key.find(lines, 0) {+ Some(block) => open_editor(cx, lines, &boxes, block, view),+ None => view.pending_text_open = None,+ }+ }+ if !allow_interaction {+ return false;+ }+ let upright = has_edges(info, page);+ let draw_handles = |b: Rect| {+ for h in width_handles(b) {+ painter.rect(h, CornerRadius::same(2), Color32::WHITE, Stroke::new(1.0, ACCENT), egui::StrokeKind::Middle);+ }+ };+ // A drag in progress: the box follows the pointer (or the grabbed edge does); releasing applies it.+ if let Some(d) = view.block_drag.filter(|d| d.page == page)+ && let (Some(b), Some(l)) = (boxes.get(d.block).copied(), lines.get(d.block))+ {+ let p = ptr.pos.unwrap_or(d.start);+ let dx = p.x - d.start.x;+ let preview = match d.grip {+ Grip::Move => b.translate(p - d.start),+ Grip::Left => Rect::from_min_max(Pos2::new((b.left() + dx).min(b.right() - 12.0), b.min.y), b.max),+ Grip::Right => Rect::from_min_max(b.min, Pos2::new((b.right() + dx).max(b.left() + 12.0), b.max.y)),+ };+ painter.rect_stroke(preview, CornerRadius::same(2), Stroke::new(1.5, ACCENT), egui::StrokeKind::Outside);+ let resizing = d.grip != Grip::Move;+ if resizing {+ draw_handles(preview);+ }- ui.ctx().set_cursor_icon(if resizing { egui::CursorIcon::ResizeHorizontal } else { egui::CursorIcon::Move });++ view.cursor.claim(Layer::Drag, if resizing { egui::CursorIcon::ResizeHorizontal } else { egui::CursorIcon::Move });+ if resp.drag_stopped() || !ptr.any_down {+ view.block_drag = None;+ let (from, to) = (user_box(xf, info, page, b), user_box(xf, info, page, preview));+ let edit = if resizing {+ // The new width in user space: the box's change, added to the paragraph's own. A+ // moved left side (in user space; on an upside-down page that's the screen's right+ // edge) moves the paragraph with it.+ let width = (l.rect[2] - l.rect[0]) + (to[2] - to[0]) - (from[2] - from[0]);+ let shift = to[0] - from[0];+ let style = pdfcraft_engine::BlockStyle { width: Some(width), offset: (shift != 0.0).then_some([shift, 0.0]), ..Default::default() };+ Edit::EditTextBlock { page, block: d.block, text: l.text.clone(), style }+ } else {+ // Translation must keep the selected source operators. Rewriting unchanged text+ // would also remove unrelated paragraphs that now overlap this one (#594).+ Edit::MoveObjects {+ page,+ objects: vec![ObjectTarget { kind: ObjectKind::Text, index: d.block }],+ offset: [to[0] - from[0], to[1] - from[1]],+ }+ };+ if preview != b {+ view.pending_edit = Some(edit);+ }+ }+ return true;+ }+ // Dragging a box (not while a paragraph is open for typing) moves it; from an edge, resizes it.+ // What it grabs comes from where the button went down, not where the pointer is now: egui+ // only calls it a drag once the pointer has moved a few pixels (or been held a moment), and a+ // quick flick has left the edge by then.+ if resp.drag_started()+ && active.is_none()+ && let Some(o) = ptr.origin+ && let Some((block, grip)) = grab_at(&boxes, o, upright)+ {+ view.block_drag = Some(BlockDrag { page, block, generation: doc.edit_generation(), start: o, grip });+ return true;+ }+ let Some(p) = ptr.within(xf.rect) else { return false };+ let Some((hit, grip)) = grab_at(&boxes, p, upright) else { return false };+ if active != Some(hit) {+ painter.rect_stroke(boxes[hit], CornerRadius::same(2), Stroke::new(1.5, ACCENT), egui::StrokeKind::Outside);+ }+ let on_edge = active.is_none() && grip != Grip::Move;+ if upright && active.is_none() {+ draw_handles(boxes[hit]);+ }+ // A closed paragraph moves when dragged (the four-way arrow says so; a click still opens it- // for typing); an edge rewraps it. The open one takes the text cursor. Only where the page- // shows, so the mode bar and side panels over a paragraph scrolled under them keep their own- // cursor (#2755).- if resp.contains_pointer() {- ui.ctx().set_cursor_icon(if on_edge {- egui::CursorIcon::ResizeHorizontal- } else if active.is_none() {- egui::CursorIcon::Move- } else {- egui::CursorIcon::Text- });++ // for typing); an edge rewraps it. The open one takes the text cursor.++ if on_edge {++ view.cursor.claim(Layer::Handle, egui::CursorIcon::ResizeHorizontal);++ } else if active.is_none() {++ view.cursor.claim(Layer::Text, egui::CursorIcon::Move);++ } else {++ view.cursor.claim(if active == Some(hit) { Layer::Editor } else { Layer::Text }, egui::CursorIcon::Text);+ }+ if resp.clicked() {+ view.image_selection = None;+ // A click that moves the editor to another paragraph applies the open one first, so its+ // typed text is not dropped with the switched-away editor (#2022). A click on the open+ // box's own frame, which the editor's overlay does not cover, keeps it open instead.+ if let Some(open) = view.line_editor.as_ref().filter(|e| e.has_changes()) {+ if open.page == page && open.block == hit {+ return true;+ }+ if let Some(old) = view.line_editor.take() {+ let style = old.style();+ if old.text != old.original || style != pdfcraft_engine::BlockStyle::default() {+ view.applied_editor = Some(old.clone());+ view.pending_edit = Some(Edit::EditTextBlock { page: old.page, block: old.block, text: old.text, style });+ }+ }+ // The clicked box opens next frame, from the document with that edit applied.+ view.pending_text_open = lines.get(hit).map(|l| (page, pdfcraft_engine::BlockKey::of(l)));+ return true;+ }+ open_editor(cx, lines, &boxes, hit, view);+ }+ true+ }++ /// The inline editor; returns the edit once the text is applied.+ pub(crate) fn overlay(ctx: &egui::Context, view: &mut DocView, info: &DocInfo) -> Option<Edit> {+ // Clicks outside the document (the Format text panel) keep the paragraph open. Where the+ // click landed is `interact_pos`: `latest_pos` is gone on the frame a tap lifts.+ let outside = ctx.input(|i| i.pointer.interact_pos()).is_some_and(|p| !view.viewport_rect().contains(p));+ let page = view.line_editor.as_ref()?.page;+ let xf = view.page_xform(page)?;+ let hold = view.objects.hold_editor;+ // An OCR word is invisible text over a scan: the textless background still shows the scanned+ // word, so the editor covers it, as the applied edit will.+ let background_ready = view+ .line_editor+ .as_ref()+ .is_some_and(|ed| view.text_background.ready(ed.page, ed.block) && !ed.source.as_ref().is_some_and(|(b, _)| b.invisible));+ // The measured extent of this paragraph's draft: a click straight from another paragraph+ // opens this one after the frame's measuring, which was the other one's.+ let draft_rect = view+ .line_editor+ .as_ref()+ .and_then(|ed| view.text_background.draft_rect_for(ed.page, ed.block))+ .map(|r| xf.user_rect(info, page, r.map(|v| v as f32)));+ // The editor draws on its page only, as the page itself does: a paragraph running past the+ // page's edge (a converter relying on the page clip) must not cover the next page or the+ // tool bars (#3061).+ let viewport = view.viewport_rect();+ let page_clip = xf.rect.intersect(viewport);+ let ed = view.line_editor.as_mut()?;+ if hold {+ ed.focus = true;+ }+ // Reproject the source box every frame. The page may have been zoomed, scrolled or rotated+ // while the format panel was open.+ // A font definition becomes active at the start of the next egui pass. Keep the source+ // raster visible until then instead of flashing an unrelated interface face.+ if !ctx.fonts(|f| ed.fonts.values().all(|name| f.definitions().families.contains_key(&FontFamily::Name(name.clone().into())))) {+ ctx.request_repaint();+ return None;+ }+ ed.rect = xf.user_rect(info, ed.page, ed.source_rect);+ ed.max_width = ed.rect.width();+ let scale = (ed.rect.width() / (ed.source_rect[2] - ed.source_rect[0]).abs().max(0.01)).max(0.01);+ ed.size = (ed.look.size as f32 * scale).clamp(1.0, 300.0);+ // egui draws the caret at least one row of this font tall. Each row already has its source+ // row's height, so the font stays below every row (half the region's smallest size): on a+ // 12 pt row under a 24 pt title the caret is as tall as the row, not the title.+ let smallest =+ ed.source.as_ref().and_then(|(block, lines)| block.lines.iter().filter_map(|i| lines.get(*i)).map(|l| l.size as f32).reduce(f32::min));+ let font = editor_font(&ed.look, smallest.map_or(ed.size, |s| (s * scale * 0.5).clamp(1.0, 300.0).min(ed.size)));+ let text_color = color32(ed.look.color);+ let block = ed.block;+ let mut done = None;+ let mut reveal = false;+ let mut look = None;+ // No fade-in: while it faded, the page's own copy of the text showed through the cover.+ // Over the page, so only where the document shows: a paragraph scrolled under the mode bar or+ // a side panel must leave them their pointer (#2755). It stays at its paragraph, cut off as+ // the page is, rather than pushed back into the window.+ egui::Area::new(egui::Id::unique("edit-text-line"))+ .order(egui::Order::Foreground)+ .fade_in(false)+ .fixed_pos(Pos2::new(ed.rect.left(), ed.rect.top()))+ .constrain_to(viewport)+ .constrain(false)+ .show(ctx, |ui| {+ ui.set_clip_rect(ui.clip_rect().intersect(page_clip));+ // The editor opens at the source size. Once text changes, show the real draft+ // extent: single rows grow toward the page edge, paragraphs rewrap at their+ // source width, and the visible frame grows/shrinks vertically with their rows.+ // An OCR phrase (several stretched words on one scanned line) also grows rightwards.+ let single_run = ed.source.as_ref().is_some_and(|(block, _)| block.rows.len() == 1 || block.invisible);+ let width = if !ed.multiline && single_run && !ed.text.contains('\n') && ed.has_changes() {+ let job = editor_job(ui, ed, &ed.text, scale, f32::INFINITY);+ let natural = ui.fonts_mut(|f| f.layout_job(job)).size().x;+ natural.max(ed.size * 0.4).min((xf.rect.right() - ed.rect.left() - 36.0 * scale).max(ed.rect.width()))+ } else {+ ed.rect.width().max(1.0)+ };+ ui.set_width(width);+ let measured = editor_galley(ui, ed, &ed.text, scale, width);+ ed.overflow = ed.has_changes() && (measured.rect.width() > ed.rect.width() + 1.5 || measured.rect.height() > ed.rect.height() + 1.5);+ let visible = Rect::from_min_size(ed.rect.min, measured.rect.size().max(egui::vec2(1.0, 1.0)));+ // Unsupported source programs use an interface fallback whose glyph advances+ // can differ from the PDF's. Keep every visible row inside the growing frame.+ let live = draft_rect.map_or(visible, |bounds| bounds.union(visible));+ ui.painter().rect_stroke(live.expand(2.0), CornerRadius::ZERO, Stroke::new(1.5, ACCENT), egui::StrokeKind::Outside);+ // On the frame, a press takes hold of the box (a click selects it, a drag moves it):+ // the pointer says so there, and reads as text inside.+ if let Some(p) = ui.input(|i| i.pointer.hover_pos())+ && ui.clip_rect().contains(p)+ && live.expand(2.0 + FRAME_REACH).contains(p)+ && !live.expand(2.0).contains(p)+ {+ ui.ctx().set_cursor_icon(egui::CursorIcon::Move);+ }+ // White, unless the text is too pale to read on white (white text from a coloured+ // banner, #913): then a dark box, with a caret that shows on it.+ let fill = if background_ready { Color32::TRANSPARENT } else { editor_fill(text_color) };+ // An unchanged paragraph is the page's own text: the editor draws only its frame and+ // caret over it. Once it changes, the textless page goes under the editor's text or,+ // until that background is ready, a cover over the entire source box, including lines+ // the draft no longer occupies. Shrinking the text must never expose a copy. Both are+ // decided after this frame's typing, in places kept under the editor's text.+ let cover = ui.painter().add(egui::Shape::Noop);+ let unchanged = !ed.has_changes();+ egui::Frame::NONE.show(ui, |ui| {+ // A textless PDF preview, or the page itself, keeps its real background through+ // the transparent editor. The temporary opaque cover uses the shared caret-contrast rule.+ ui.visuals_mut().text_cursor.stroke.color = if background_ready || unchanged {+ if luminance(text_color) < 0.5 { Color32::BLACK } else { Color32::WHITE }+ } else {+ caret_color_on(fill)+ };+ let rows = 1;+ let snapshot = ed.clone();+ let mut layouter = |ui: &egui::Ui, text: &dyn egui::TextBuffer, wrap_width: f32| {+ let galley = editor_galley(ui, &snapshot, text.as_str(), scale, wrap_width);+ if snapshot.changes_with(text.as_str()) { galley } else { unseen(galley) }+ };+ let output = egui::TextEdit::multiline(&mut ed.text)+ .id(egui::Id::unique("edit-text-line-input"))+ .font(font.clone())+ .margin(egui::Margin::ZERO)+ .layouter(&mut layouter)+ .text_color(text_color)+ .frame(egui::Frame::NONE)+ .desired_width(width)+ .desired_rows(rows)+ .show(ui);+ // The editor paints over the page with no visible label; name it for assistive tech.+ output.response.response.clone().accessible_name(tl!("Text editing line"));+ if ed.has_changes() {+ if background_ready {+ reveal = true;+ } else {+ ui.painter().set(cover, egui::Shape::rect_filled(ed.rect.expand(1.0).union(output.response.rect), CornerRadius::ZERO, fill));+ }+ }+ look = Some((Arc::clone(&output.galley), output.galley_pos));+ if let Some(cursor) = output.cursor_range {+ let selected = cursor.as_sorted_char_range();+ let byte = |index| ed.text.char_indices().nth(index).map_or(ed.text.len(), |(at, _)| at);+ ed.selection = (!selected.is_empty()).then(|| byte(selected.start.into())..byte(selected.end.into()));+ }+ let r = output.response;+ if r.changed() {+ // The next pass measures the updated draft with the Apply/Save rewrite.+ ctx.request_repaint();+ }+ if ed.focus {+ r.request_focus();+ ed.focus = false;+ }+ let lost = lost_focus_once(&r, &mut ed.had_focus);+ let esc = ui.input(|i| i.key_pressed(egui::Key::Escape));+ let apply = ui.input(|i| i.key_pressed(egui::Key::Enter) && i.modifiers.command);+ if esc {+ done = Some(false);+ } else if apply || (lost && !outside && !hold) {+ done = Some(true);+ }+ });+ });+ if reveal {+ view.text_background.reveal();+ }+ if let Some((galley, pos)) = look {+ view.text_background.remember(&xf, page, block, galley, pos, text_color);+ }+ match done {+ Some(apply) => {+ let ed = view.line_editor.take()?;+ if !apply {+ return None;+ }+ view.applied_editor = Some(ed.clone());+ finished_edit(ed)+ }+ None => None,+ }+ }++ /// The edit a closed paragraph editor applies, or `None` when nothing in it changed.+ pub(crate) fn finished_edit(ed: LineEditor) -> Option<Edit> {+ let style = ed.style();+ (ed.text != ed.original || style != pdfcraft_engine::BlockStyle::default()).then_some(Edit::EditTextBlock {+ page: ed.page,+ block: ed.block,+ text: ed.text,+ style,+ })+ }++ /// Whether an editor's text box `r` lost the keyboard this frame, given whether it `had` it at+ /// the end of the editor's last frame (updated here). egui's `lost_focus` holds for a second+ /// frame as well, and an editor that judges a click away by where the click landed must judge it+ /// once, on the click's frame: on the next, a tap's position is gone (egui-winit sends+ /// `PointerGone` with every touch release) and a mouse may have moved on.+ pub(crate) fn lost_focus_once(r: &egui::Response, had: &mut bool) -> bool {+ let has = r.has_focus();+ std::mem::replace(had, has) && !has+ }++ #[cfg(test)]+ mod tests {+ use super::*;++ #[test]+ fn the_rotate_knob_moves_below_when_there_is_no_room_above() {+ let view = Rect::from_min_max(Pos2::new(0.0, 100.0), Pos2::new(500.0, 500.0));+ let roomy = Rect::from_min_max(Pos2::new(100.0, 200.0), Pos2::new(200.0, 250.0));+ assert_eq!(rotate_knob(roomy, view).0, Pos2::new(150.0, 178.0));+ let at_top = Rect::from_min_max(Pos2::new(100.0, 100.0), Pos2::new(200.0, 150.0));+ let (knob, stem) = rotate_knob(at_top, view);+ assert_eq!((knob, stem), (Pos2::new(150.0, 172.0), Pos2::new(150.0, 150.0)));+ }++ #[test]+ fn the_rotate_knob_measures_clockwise_degrees_from_straight_up() {+ let c = Pos2::new(100.0, 100.0);+ let at = |x: f32, y: f32| turn_degrees(c, Pos2::new(x, y), false);+ assert!(at(100.0, 0.0).abs() < 1e-3);+ assert!((at(200.0, 100.0) - 90.0).abs() < 1e-3, "right is a clockwise quarter");+ assert!((at(0.0, 100.0) + 90.0).abs() < 1e-3);+ assert!((at(100.0, 200.0).abs() - 180.0).abs() < 1e-3);+ // Shift rounds to 15 degrees; the centre and non-finite points turn nothing.+ assert_eq!(turn_degrees(c, Pos2::new(180.0, 50.0), true) % 15.0, 0.0);+ assert_eq!(at(101.0, 101.0), 0.0);+ assert_eq!(at(f32::NAN, 5.0), 0.0);+ }++ /// An app with one text document open, and an editor on its first paragraph.+ fn preview_app() -> (crate::PdfCraftApp, LineEditor) {+ let mut app = crate::PdfCraftApp::new();+ let bytes = app.session.create_from_text("Preview", "Preview text").unwrap();+ app.open_bytes("preview.pdf", None, bytes.as_ref().clone()).unwrap();+ let doc = app.session.get(app.views[0].id).unwrap();+ let block = doc.text_blocks(0).remove(0);+ let ed = LineEditor {+ selection: None,+ font_resource: None,+ page: 0,+ block: 0,+ text: block.text.clone(),+ original: block.text.clone(),+ rect: Rect::NOTHING,+ source_rect: block.rect.map(|v| v as f32),+ multiline: block.rows.len() > 1,+ source: None,+ fonts: BTreeMap::new(),+ overflow: false,+ max_width: 400.0,+ size: block.size as f32,+ focus: true,+ had_focus: false,+ look: look_of(&block),+ look0: look_of(&block),+ family_chosen: false,+ extras: Extras::default(),+ extras0: Extras::default(),+ };+ (app, ed)+ }++ #[test]+ fn picking_the_family_the_font_name_reads_as_still_changes_the_font() {+ // A Calibri paragraph reads as Helvetica; picking Helvetica from the list used to leave+ // `look` equal to what the paragraph had, so no family change was sent and Calibri stayed.+ let (_app, mut ed) = preview_app();+ let family = ed.look0.family;+ assert_eq!(ed.style().family, None, "nothing chosen yet");+ ed.choose_family(family);+ assert_eq!(ed.style().family, Some((family, ed.look.bold, ed.look.italic)));+ assert!(ed.has_changes());+ assert_eq!(ed.font_shown(&[]), family.label());+ ed.keep_source_font();+ assert_eq!(ed.style().family, None, "Keep source fonts withdraws the choice");+ ed.choose_family(family);+ ed.applied();+ assert_eq!(ed.style().family, None, "an applied choice is the paragraph's font now");+ }++ #[test]+ fn a_loaded_font_is_applied_to_the_paragraph_being_edited() {+ // Loading a font used to only register it on the page: the paragraph kept its source+ // face until the font was found again in the document-font menu (#2591).+ let (mut app, ed) = preview_app();+ app.views[0].line_editor = Some(ed);+ let inter = include_bytes!("../../../../assets/fonts/Inter-Regular.ttf").to_vec();+ app.use_files(crate::files::FilePurpose::TextFont { page: 0 }, vec![("Inter-Regular.ttf".into(), inter)]);+ let doc = app.session.get(app.views[0].id).unwrap();+ let lines = doc.text_lines(0);+ assert_eq!(lines.iter().map(|l| l.text.as_str()).collect::<String>(), "Preview text");+ assert!(lines.iter().all(|l| l.base_font == "Inter-Regular"), "{:?}", lines.iter().map(|l| &l.base_font).collect::<Vec<_>>());+ assert!(app.views[0].line_editor.is_some(), "the paragraph stays open for editing");+ }++ #[test]+ fn save_applies_the_paragraph_open_in_the_editor() {+ // Save wrote the file without the paragraph still open in the editor (#3496).+ let (mut app, mut ed) = preview_app();+ ed.text = "Text preview".into();+ app.views[0].line_editor = Some(ed);+ let dir = std::env::temp_dir().join(format!("pdfcraft-ui-open-paragraph-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(&dir).unwrap();+ app.save_override = Some(dir.join("out.pdf").to_string_lossy().into_owned());++ assert!(app.save_active(crate::SaveTarget::InPlace));+ assert!(app.views[0].line_editor.is_none());+ let doc = app.session.get(app.views[0].id).unwrap();+ assert_eq!(doc.text_lines(0).iter().map(|l| l.text.as_str()).collect::<String>(), "Text preview");+ let _ = std::fs::remove_dir_all(&dir);+ }++ #[test]+ fn a_refused_text_box_does_not_lose_the_open_paragraph() {+ let (mut app, mut ed) = preview_app();+ ed.text = "Text preview".into();+ app.views[0].line_editor = Some(ed);+ let draft = crate::content_ui::TextDraft {+ page: 9,+ index: None,+ rect: [20.0, 20.0, 120.0, 40.0],+ text: "Typed text".into(),+ style: crate::content_ui::default_style(),+ focus: true,+ };+ app.views[0].content.draft = Some(draft.clone());++ assert!(!app.commit_typing_in(app.views[0].id));+ assert_eq!(app.views[0].content.draft, Some(draft), "the refused text box stays open");+ assert!(app.views[0].line_editor.is_none(), "the paragraph was applied");+ let doc = app.session.get(app.views[0].id).unwrap();+ assert_eq!(doc.text_lines(0).iter().map(|l| l.text.as_str()).collect::<String>(), "Text preview");+ }++ #[test]+ fn a_refused_paragraph_stays_open_with_its_text() {+ let (mut app, mut ed) = preview_app();+ ed.text = "Text preview".into();+ ed.page = 9;+ app.views[0].line_editor = Some(ed.clone());++ assert!(!app.commit_typing_in(app.views[0].id));+ assert_eq!(app.views[0].line_editor, Some(ed), "the paragraph keeps its unsaved text");+ }++ #[test]+ fn text_background_is_cached_without_editing_and_released_on_cancel() {+ let (app, ed) = preview_app();+ let doc = app.session.get(app.views[0].id).unwrap();+ let source = doc.bytes.clone();+ let generation = doc.edit_generation();+ let ctx = egui::Context::default();+ let mut background = TextBackground::default();+ for _ in 0..100 {+ background.prepare(&ctx, doc, Some(&ed), None, 1.0);+ if background.ready(0, 0) {+ break;+ }+ std::thread::sleep(std::time::Duration::from_millis(5));+ }+ assert!(background.ready(0, 0));+ assert!(!background.pending());+ let texture = background.texture.as_ref().unwrap().id();+ background.prepare(&ctx, doc, Some(&ed), None, 1.0);+ assert_eq!(background.texture.as_ref().unwrap().id(), texture);+ assert_eq!(doc.bytes, source);+ assert_eq!(doc.edit_generation(), generation);+ assert!(!doc.dirty && doc.can_undo().is_none());+ background.prepare(&ctx, doc, None, None, 1.0);+ assert!(background.texture.is_none() && background.renderer.is_none());+ }++ #[test]+ fn the_editing_background_stays_sharp_on_a_zoomed_page() {+ // While a paragraph is open, the page around it is drawn from this one raster: it is+ // asked for at the tiling threshold, not the 2048-pixel backdrop side, which went soft+ // beyond about 1.2x on a Retina display.+ let (app, ed) = preview_app();+ let doc = app.session.get(app.views[0].id).unwrap();+ let page = &doc.info.pages[0];+ let ctx = egui::Context::default();+ ctx.begin_pass(egui::RawInput { max_texture_side: Some(16384), ..Default::default() });+ let mut background = TextBackground::default();+ background.prepare(&ctx, doc, Some(&ed), None, 8.0);+ let expected = 8.0f32.min(crate::canvas::TILE_THRESHOLD / page.width.max(page.height));+ assert!(expected > crate::canvas::BASE_SIDE / page.width.max(page.height), "the test page needs the larger side");+ assert_eq!(background.tag, Some((expected * 1000.0) as u64));+ // A GPU that can't hold such a texture caps it.+ ctx.end_pass().textures_delta.clear();+ ctx.begin_pass(egui::RawInput { max_texture_side: Some(2048), ..Default::default() });+ let mut small = TextBackground::default();+ small.prepare(&ctx, doc, Some(&ed), None, 8.0);+ assert_eq!(small.tag, Some(((2048.0 / page.width.max(page.height)) * 1000.0) as u64));+ ctx.end_pass().textures_delta.clear();+ }++ #[test]+ fn pale_text_is_edited_on_a_dark_box() {+ // #913: white text from a coloured banner was typed onto a white box and vanished.+ for pale in [Color32::WHITE, Color32::from_rgb(0xFF, 0xFF, 0x00), Color32::from_gray(0xE0), Color32::from_rgb(0xFF, 0xA5, 0x00)] {+ assert_eq!(editor_fill(pale), DARK_EDITOR_FILL, "{pale:?}");+ assert!(contrast(pale, editor_fill(pale)) >= 4.5, "{pale:?} is readable");+ }+ // Ordinary dark or saturated text keeps the white box.+ for dark in [Color32::BLACK, Color32::from_rgb(0x1F, 0x2A, 0x6B), Color32::from_rgb(0xC0, 0x00, 0x00), Color32::from_gray(0x60)] {+ assert_eq!(editor_fill(dark), Color32::WHITE, "{dark:?}");+ }+ }++ #[test]+ fn caret_contrasts_with_its_fill() {+ assert_eq!(caret_color_on(Color32::WHITE), Color32::BLACK);+ assert_eq!(caret_color_on(Color32::from_rgb(0xFF, 0xFF, 0xF4)), Color32::BLACK);+ assert_eq!(caret_color_on(Color32::BLACK), Color32::WHITE);+ assert_eq!(caret_color_on(DARK_EDITOR_FILL), Color32::WHITE);+ }+ }diff --cc crates/ui-egui/src/tools/edit_text_ui/image.rsindex 000000000,2c231c19d..d9dbb59famode 000000,100644..100644--- a/crates/ui-egui/src/tools/edit_text_ui/image.rs+++ b/crates/ui-egui/src/tools/edit_text_ui/image.rs@@@ -1,0 -1,679 +1,686 @@@+ use super::{ACCENT, Color32, CornerRadius, DocInfo, DocView, Edit, MAX_OUTLINES, PagePointer, PageXform, Pos2, Rect, Stroke, user_box};++use crate::page_cursor::Layer;++ /// A selected page image, and what the pointer is doing to it.+ #[derive(Clone, Debug, PartialEq)]+ pub struct ImageSelection {+ pub page: usize,+ pub index: usize,+ /// Dragging: the start point and, for a corner, the opposite corner (screen).+ drag: Option<(Pos2, Option<Pos2>)>,+ /// Crop mode (Acrobat's crop handles): the box kept so far.+ pub crop: Option<CropMode>,+ /// The drag is turning the picture by its rotate handle (the `drag` start is then unused).+ turning: bool,+ /// A move or resize applied on release: the frame it had and the one it got, in the page's+ /// 0..1 coordinates, while the page raster still has the picture where it was.+ settled: Option<(Rect, Rect)>,+ }++ impl ImageSelection {+ /// Cancel an in-progress text, rotation or crop drag and restore the crop it was previewing.+ pub(crate) fn cancel_pointer_gesture(&mut self) {+ self.drag = None;+ self.turning = false;+ if let Some(crop) = &mut self.crop+ && let Some((_, _, before)) = crop.drag.take()+ {+ crop.keep = before;+ }+ }+ }++ /// Cropping a page image: the handles trim instead of resizing, the part that will go is+ /// dimmed, Enter or Done applies and Esc or Cancel leaves it.+ #[derive(Clone, Debug, PartialEq)]+ pub struct CropMode {+ /// The box to keep (user space).+ pub keep: [f64; 4],+ /// A drag in progress: the grip (0–3 corners, 4–7 edges, 8 the inside), where it started+ /// and the box then.+ drag: Option<(usize, Pos2, [f64; 4])>,+ }++ impl CropMode {+ pub fn new(keep: [f64; 4]) -> Self {+ Self { keep, drag: None }+ }+ }++ /// What the pointer and the page are, for the image tools on one page.+ #[derive(Clone, Copy)]+ pub(crate) struct ImageCx<'a> {+ pub ui: &'a egui::Ui,+ pub resp: &'a egui::Response,+ pub xf: &'a PageXform,+ pub ptr: &'a PagePointer,+ pub page: usize,+ pub info: &'a DocInfo,+ pub allow_interaction: bool,+ }++ /// The screen boxes of the crop's eight handles: corners, then the top, right, bottom and left+ /// edge midpoints.+ fn crop_handles(k: Rect) -> [Pos2; 8] {+ [k.left_top(), k.right_top(), k.left_bottom(), k.right_bottom(), k.center_top(), k.right_center(), k.center_bottom(), k.left_center()]+ }++ /// Crop mode for the selected image `i` whose visible frame is `b` (screen). Returns `true`+ /// (the pointer and keys are the crop's while it lasts).+ fn crop_input(cx: &ImageCx<'_>, view: &mut DocView, i: usize, b: Rect) -> bool {+ let ImageCx { ui, resp, xf, ptr, page, info, allow_interaction } = *cx;+ let painter = ui.painter();+ let Some(mode) = view.image_selection.as_mut().and_then(|s| s.crop.as_mut()) else { return false };+ let hover_pos = ptr.pos;+ let keep_screen = |keep: [f64; 4]| xf.user_rect(info, page, keep.map(|v| v as f32)).intersect(b);+ // A drag in progress moves a grip; the box stays inside the picture and at least 6 px.+ if allow_interaction+ && resp.drag_started()+ && let Some(o) = ptr.origin+ {+ let k = keep_screen(mode.keep);+ let grip = crop_handles(k).iter().position(|h| h.distance(o) < 8.0).or_else(|| k.contains(o).then_some(8));+ if let Some(g) = grip {+ mode.drag = Some((g, o, mode.keep));+ }+ }+ if let Some((grip, start, at_start)) = mode.drag+ && let Some(p) = hover_pos+ {+ let d = p - start;+ let k0 = keep_screen(at_start);+ let (mut min, mut max) = (k0.min, k0.max);+ match grip {+ 0 => {+ min.x += d.x;+ min.y += d.y;+ }+ 1 => {+ max.x += d.x;+ min.y += d.y;+ }+ 2 => {+ min.x += d.x;+ max.y += d.y;+ }+ 3 => {+ max.x += d.x;+ max.y += d.y;+ }+ 4 => min.y += d.y,+ 5 => max.x += d.x,+ 6 => max.y += d.y,+ 7 => min.x += d.x,+ _ => {+ let shift = egui::vec2(d.x.clamp(b.min.x - k0.min.x, b.max.x - k0.max.x), d.y.clamp(b.min.y - k0.min.y, b.max.y - k0.max.y));+ min += shift;+ max += shift;+ }+ }+ let (min_w, min_h) = (6.0_f32.min(b.width()), 6.0_f32.min(b.height()));+ min.x = min.x.clamp(b.min.x, b.max.x - min_w);+ min.y = min.y.clamp(b.min.y, b.max.y - min_h);+ max.x = max.x.clamp(min.x + min_w, b.max.x);+ max.y = max.y.clamp(min.y + min_h, b.max.y);+ mode.keep = user_box(xf, info, page, Rect::from_min_max(min, max));+ if resp.drag_stopped() || !ptr.primary_down {+ mode.drag = None;+ }+ }+ let k = keep_screen(mode.keep);+ // What goes is dimmed; what stays keeps its frame and handles.+ let dim = Color32::from_black_alpha(96);+ for r in [+ Rect::from_min_max(b.min, Pos2::new(b.max.x, k.min.y)),+ Rect::from_min_max(Pos2::new(b.min.x, k.max.y), b.max),+ Rect::from_min_max(Pos2::new(b.min.x, k.min.y), Pos2::new(k.min.x, k.max.y)),+ Rect::from_min_max(Pos2::new(k.max.x, k.min.y), Pos2::new(b.max.x, k.max.y)),+ ] {+ if r.is_positive() {+ painter.rect_filled(r.intersect(xf.rect), CornerRadius::ZERO, dim);+ }+ }+ painter.rect_stroke(k, CornerRadius::ZERO, Stroke::new(1.5, ACCENT), egui::StrokeKind::Outside);+ for h in crop_handles(k) {+ painter.rect(+ Rect::from_center_size(h, egui::vec2(8.0, 8.0)),+ CornerRadius::ZERO,+ Color32::WHITE,+ Stroke::new(1.0, ACCENT),+ egui::StrokeKind::Middle,+ );+ }+ // Done and Cancel, painted under the box (above it near the bottom of the view).+ let font = egui::FontId::proportional(12.5);+ let pill = |label: &str, right: f32, y: f32| -> Rect {+ let w = painter.layout_no_wrap(label.to_string(), font.clone(), Color32::WHITE).size().x + 20.0;+ Rect::from_min_size(Pos2::new(right - w, y), egui::vec2(w, 22.0))+ };+ let y = if k.max.y + 30.0 < xf.rect.max.y { k.max.y + 6.0 } else { k.min.y - 28.0 };+ let done = pill(tl!("Done"), k.max.x, y);+ let cancel = pill(tl!("Cancel"), done.min.x - 6.0, y);+ let t = crate::theme::Tokens::get(ui.ctx());+ painter.rect_filled(done, CornerRadius::same(11), ACCENT);+ painter.text(done.center(), egui::Align2::CENTER_CENTER, tl!("Done"), font.clone(), Color32::WHITE);+ painter.rect(cancel, CornerRadius::same(11), t.panel, Stroke::new(1.0, t.border), egui::StrokeKind::Inside);+ painter.text(cancel.center(), egui::Align2::CENTER_CENTER, tl!("Cancel"), font, t.text);- if let Some(p) = hover_pos {++ // Cropping takes over its page's cursor, and the buttons' wherever they are; other pages++ // keep theirs.++ if let Some(p) = hover_pos.filter(|p| xf.rect.contains(*p) || done.contains(*p) || cancel.contains(*p)) {+ let icon = if let Some(g) = crop_handles(k).iter().position(|h| h.distance(p) < 8.0) {+ match g {+ 0 | 3 => egui::CursorIcon::ResizeNwSe,+ 1 | 2 => egui::CursorIcon::ResizeNeSw,+ 4 | 6 => egui::CursorIcon::ResizeVertical,+ _ => egui::CursorIcon::ResizeHorizontal,+ }+ } else if done.contains(p) || cancel.contains(p) {+ egui::CursorIcon::PointingHand+ } else if k.contains(p) {+ egui::CursorIcon::Move+ } else {+ egui::CursorIcon::Default+ };- ui.ctx().set_cursor_icon(icon);++ view.cursor.claim(Layer::Editor, icon);+ }+ let clicked = |r: Rect| allow_interaction && resp.clicked() && hover_pos.is_some_and(|p| r.contains(p));+ let keys = |key: egui::Key| allow_interaction && ui.input(|inp| inp.key_pressed(key)) && !ui.ctx().egui_wants_keyboard_input();+ if clicked(done) || keys(egui::Key::Enter) {+ let keep = mode.keep;+ if let Some(s) = view.image_selection.as_mut() {+ s.crop = None;+ }+ if keep_screen(keep) != b {+ view.pending_edit = Some(Edit::EditPageImage { page, index: i, change: pdfcraft_engine::ImageEdit::Crop(keep) });+ }+ } else if (clicked(cancel) || keys(egui::Key::Escape))+ && let Some(s) = view.image_selection.as_mut()+ {+ s.crop = None;+ }+ true+ }++ impl ImageSelection {+ pub(crate) fn dragging(&self) -> bool {+ self.drag.is_some()+ }+ }++ /// The page raster's picture of the box `from`, stretched into `to`, over blanks at `blank` (where+ /// the screen may still show the picture).+ fn stretched_picture(painter: &egui::Painter, xf: &PageXform, tex: egui::TextureId, blank: &[Rect], from: Rect, to: Rect) {+ let clipped = painter.with_clip_rect(painter.clip_rect().intersect(xf.rect));+ for r in blank {+ clipped.rect_filled(*r, CornerRadius::ZERO, Color32::WHITE);+ }+ let mut mesh = egui::Mesh::with_texture(tex);+ for (a, b) in [+ (from.left_top(), to.left_top()),+ (from.right_top(), to.right_top()),+ (from.right_bottom(), to.right_bottom()),+ (from.left_bottom(), to.left_bottom()),+ ] {+ let (u, v) = xf.screen_to_norm(a);+ mesh.vertices.push(egui::epaint::Vertex { pos: b, uv: Pos2::new(u, v), color: Color32::WHITE });+ }+ mesh.add_triangle(0, 1, 2);+ mesh.add_triangle(0, 2, 3);+ clipped.add(egui::Shape::mesh(mesh));+ }++ /// Once a selected corner or the rotate knob is grabbed, text under it cannot take over the gesture. The same+ /// applies after the pointer leaves the image/page while dragging.+ pub(crate) fn image_owns_pointer(ui: &egui::Ui, xf: &PageXform, ptr: &PagePointer, page: usize, info: &DocInfo, view: &DocView) -> bool {+ let Some(selection) = view.image_selection.as_ref().filter(|s| s.page == page) else { return false };+ if selection.drag.is_some() {+ return true;+ }+ let Some(image) = view.edit_images.get(&page).and_then(|(_, images)| images.get(selection.index)) else { return false };+ let Some(rect) = image.visible_rect else { return false };+ let b = xf.user_rect(info, page, rect.map(|v| v as f32));+ let p = if ptr.primary_down { ptr.origin } else { ptr.pos };+ let knob = rotate_knob(b, ui.clip_rect()).0;+ p.is_some_and(|p| [b.left_top(), b.right_top(), b.left_bottom(), b.right_bottom(), knob].iter().any(|c| c.distance(p) < 8.0))+ }++ /// What a right-click on a selected image asks for.+ #[derive(Clone, Copy, Debug, PartialEq)]+ pub(crate) enum ImageAction {+ Replace(usize, usize),+ Save(usize, usize),+ Copy(usize, usize),+ CopyFile(usize, usize),+ /// Copy the picture, then remove it from the page.+ Cut(usize, usize),+ /// Mark the picture for redaction (applied later from Redact a PDF).+ Redact(usize, usize),+ /// Create a link over the picture.+ Link(usize, usize),+ /// Open Recognize Text for the picture's page.+ Recognize(usize),+ }++ /// Where the rotate knob sits, and the edge point its stem starts from: above the middle of the+ /// top edge, or below the bottom edge when the area on screen (`view`) has no room above.+ pub(super) fn rotate_knob(b: Rect, view: Rect) -> (Pos2, Pos2) {+ let above = b.center_top() - egui::vec2(0.0, 22.0);+ if above.y - 6.0 >= view.top() { (above, b.center_top()) } else { (b.center_bottom() + egui::vec2(0.0, 22.0), b.center_bottom()) }+ }++ /// Degrees clockwise (-180..=180) that turn "straight up" from `centre` onto the pointer; `snap`+ /// rounds to steps of 15 degrees (Shift). A pointer on the centre turns nothing.+ pub(super) fn turn_degrees(centre: Pos2, pointer: Pos2, snap: bool) -> f32 {+ let v = pointer - centre;+ if !(v.x.is_finite() && v.y.is_finite()) || v.length() < 4.0 {+ return 0.0;+ }+ // Screen y points down: up is (0, -1); clockwise is atan2(x, -y).+ let d = v.x.atan2(-v.y).to_degrees();+ if snap { (d / 15.0).round() * 15.0 } else { d }+ }++ /// Which boxes are outlined on the page, and why.+ struct OutlineState {+ selected: Option<usize>,+ hovered_box: Option<usize>,+ /// The picture being dragged, whose outline would trail behind until the release.+ moving: Option<usize>,+ dragging: bool,+ /// Few images: faint outlines for all of them.+ faint_all: bool,+ }++ /// Outlines the images: all of them faintly when there are few, else the selected and hovered+ /// ones; the hovered or selected one is emphasised.+ fn draw_outlines(painter: &egui::Painter, boxes: &[Rect], state: OutlineState) {+ let OutlineState { selected, hovered_box, moving, dragging, faint_all } = state;+ if faint_all {+ for (_, b) in boxes.iter().enumerate().filter(|(i, b)| b.is_positive() && moving != Some(*i)) {+ painter.rect_stroke(*b, CornerRadius::ZERO, Stroke::new(0.75, ACCENT.gamma_multiply(0.35)), egui::StrokeKind::Outside);+ }+ }+ if !faint_all {+ for i in selected.filter(|_| moving.is_none()).into_iter().chain(hovered_box.filter(|h| Some(*h) != selected)) {+ if let Some(b) = boxes.get(i).filter(|b| b.is_positive()) {+ painter.rect_stroke(*b, CornerRadius::ZERO, Stroke::new(0.75, ACCENT.gamma_multiply(0.35)), egui::StrokeKind::Outside);+ }+ }+ }+ for i in selected.into_iter().chain(hovered_box).collect::<Vec<_>>() {+ let Some(b) = boxes.get(i).copied().filter(|b| b.is_positive()) else { continue };+ if selected == Some(i) {+ // The selected frame and handles are drawn below (or the drag preview instead).+ if !dragging {+ painter.rect_filled(b, CornerRadius::ZERO, ACCENT.gamma_multiply(0.04));+ }+ } else {+ painter.rect_stroke(b, CornerRadius::ZERO, Stroke::new(1.5, ACCENT.gamma_multiply(0.7)), egui::StrokeKind::Outside);+ }+ }+ }++ fn draw_handles(painter: &egui::Painter, rect: Rect) {+ for c in [rect.left_top(), rect.right_top(), rect.left_bottom(), rect.right_bottom()] {+ painter.rect(+ Rect::from_center_size(c, egui::vec2(8.0, 8.0)),+ CornerRadius::ZERO,+ Color32::WHITE,+ Stroke::new(1.0, ACCENT),+ egui::StrokeKind::Middle,+ );+ }+ }++ /// Turning the picture by its rotate handle: the turned outline as a preview (the engine redraws+ /// the pixels on release).+ fn turn_preview(cx: &ImageCx<'_>, view: &mut DocView, i: usize, b: Rect, knob: Pos2) {+ let ImageCx { ui, resp, ptr, page, .. } = *cx;+ let painter = ui.painter();+ let hover_pos = ptr.pos;+ let shift = ui.input(|i| i.modifiers.shift);+ let degrees = hover_pos.map_or(0.0, |p| turn_degrees(b.center(), p, shift));+ // The turned outline as a preview; the engine redraws the pixels on release.+ let centre = b.center();+ let (sin, cos) = degrees.to_radians().sin_cos();+ let turn = |c: Pos2| {+ let v = c - centre;+ centre + egui::vec2(v.x * cos - v.y * sin, v.x * sin + v.y * cos)+ };+ let outline = [b.left_top(), b.right_top(), b.right_bottom(), b.left_bottom()].map(turn).to_vec();+ painter.add(egui::Shape::closed_line(outline, Stroke::new(1.5, ACCENT)));+ let galley = painter.layout_no_wrap(format!("{degrees:.0}\u{b0}"), egui::FontId::proportional(12.0), ACCENT);+ let label = Rect::from_center_size(turn(knob) - egui::vec2(0.0, 14.0), galley.size() + egui::vec2(8.0, 4.0));+ painter.rect(label, CornerRadius::same(3), Color32::WHITE, Stroke::new(1.0, ACCENT), egui::StrokeKind::Middle);+ painter.galley(label.center() - galley.size() / 2.0, galley, ACCENT);- ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing);++ view.cursor.claim(Layer::Drag, egui::CursorIcon::Grabbing);+ if resp.drag_stopped() || !ptr.primary_down {+ if let Some(s) = view.image_selection.as_mut() {+ s.drag = None;+ s.turning = false;+ }+ if degrees.abs() >= 0.05 {+ view.pending_edit = Some(Edit::EditPageImage { page, index: i, change: pdfcraft_engine::ImageEdit::RotateBy(f64::from(degrees)) });+ }+ }+ }++ /// Where the screen may still show the picture from before an applied move, and whether the+ /// page's whole raster is the old one.+ #[derive(Clone, Copy)]+ struct Blanked {+ left_at: Option<Rect>,+ raster_old: bool,+ }++ /// A frame of the picture being moved or resized: the stretched picture, its frame and handles,+ /// and on release the edit.+ fn drag_preview(+ cx: &ImageCx<'_>,+ images: &[pdfcraft_engine::PageImage],+ view: &mut DocView,+ (i, b): (usize, Rect),+ (start, opposite, p): (Pos2, Option<Pos2>, Pos2),+ blanked: Blanked,+ ) {+ let ImageCx { ui, resp, xf, ptr, page, info, .. } = *cx;+ let painter = ui.painter();+ let Blanked { left_at, raster_old } = blanked;+ let screen = |r: Rect| Rect::from_two_pos(xf.norm_to_screen(r.min.x, r.min.y), xf.norm_to_screen(r.max.x, r.max.y));+ let preview = match opposite {+ // Resize from the opposite corner, keeping the aspect ratio.+ Some(fixed) => {+ let (w0, h0) = (b.width().max(1.0), b.height().max(1.0));+ // Use the axis with the larger relative pointer change. Taking the maximum+ // absolute size freezes shrinking when the other axis hasn't moved. Measure+ // from the press point so grabbing a handle off-centre cannot cause a jump.+ let horizontal = (p.x - start.x) * (start.x - fixed.x).signum() / w0;+ let vertical = (p.y - start.y) * (start.y - fixed.y).signum() / h0;+ let delta = if horizontal.abs() > vertical.abs() { horizontal } else { vertical };+ let k = (1.0 + delta).max(0.05);+ let (w, h) = (w0 * k, h0 * k);+ let x = if start.x < fixed.x { fixed.x - w } else { fixed.x };+ let y = if start.y < fixed.y { fixed.y - h } else { fixed.y };+ Rect::from_min_size(Pos2::new(x, y), egui::vec2(w, h))+ }+ None => b.translate(p - start),+ };+ // Move/resize the full placement by the visible frame's change. The engine+ // transforms an isolated crop together with its image, preserving its contents.+ let raw = images.get(i).map_or(b, |im| xf.user_rect(info, page, im.rect.map(|v| v as f32)));+ // A zero-width or zero-height visible frame (or a degenerate ratio) keeps the+ // placement's scale instead of producing inf/NaN.+ let ratio = |new: f32, old: f32| if old.abs() > 1e-3 && (new / old).is_finite() { new / old } else { 1.0 };+ let factor = egui::vec2(ratio(preview.width(), b.width()), ratio(preview.height(), b.height()));+ let target = Rect::from_min_max(preview.min + (raw.min - b.min) * factor, preview.min + (raw.max - b.min) * factor);+ let visible = preview.intersect(xf.rect);+ if visible.is_positive() {+ // The pixels follow the frame: the page raster's picture of the image, stretched+ // into the preview over a blank where it was. Re-rendering every frame of a drag+ // would lag; the edit renders it properly on release.+ if preview != b+ && let Some(tex) = view.page_raster(page)+ {+ // Its pixels: where the whole-page raster has it.+ let source = left_at.filter(|_| raster_old).map_or(b, screen);+ let blank: Vec<Rect> = left_at.map(screen).into_iter().chain(std::iter::once(b)).collect();+ stretched_picture(painter, xf, tex, &blank, source, preview);+ }+ painter.rect_filled(visible, CornerRadius::ZERO, ACCENT.gamma_multiply(0.04));+ painter.rect_stroke(visible, CornerRadius::ZERO, Stroke::new(1.5, ACCENT), egui::StrokeKind::Outside);+ draw_handles(painter, preview);+ }+ if resp.drag_stopped() || !ptr.primary_down {+ if let Some(s) = view.image_selection.as_mut() {+ s.drag = None;+ let norm = |r: Rect| {+ let ((u0, v0), (u1, v1)) = (xf.screen_to_norm(r.min), xf.screen_to_norm(r.max));+ Rect::from_two_pos(Pos2::new(u0, v0), Pos2::new(u1, v1))+ };+ s.settled = (preview != b).then(|| (left_at.unwrap_or_else(|| norm(b)), norm(preview)));+ }+ if preview != b {+ view.pending_edit =+ Some(Edit::EditPageImage { page, index: i, change: pdfcraft_engine::ImageEdit::Move(user_box(xf, info, page, target)) });+ }+ }- ui.ctx().set_cursor_icon(match opposite {- Some(fixed) if (start.x - fixed.x) * (start.y - fixed.y) < 0.0 => egui::CursorIcon::ResizeNeSw,- Some(_) => egui::CursorIcon::ResizeNwSe,- None => egui::CursorIcon::Move,- });++ view.cursor.claim(++ Layer::Drag,++ match opposite {++ Some(fixed) if (start.x - fixed.x) * (start.y - fixed.y) < 0.0 => egui::CursorIcon::ResizeNeSw,++ Some(_) => egui::CursorIcon::ResizeNwSe,++ None => egui::CursorIcon::Move,++ },++ );+ }++ /// Images on a page: select, move, resize, right-click. Returns `true` when the pointer was used.+ pub(crate) fn image_input(cx: &ImageCx<'_>, images: &[pdfcraft_engine::PageImage], view: &mut DocView, action: &mut Option<ImageAction>) -> bool {+ let ImageCx { ui, resp, xf, ptr, page, info, allow_interaction } = *cx;+ let boxes: Vec<Rect> = images.iter().map(|im| im.visible_rect.map_or(Rect::NOTHING, |r| xf.user_rect(info, page, r.map(|v| v as f32)))).collect();+ let painter = ui.painter();+ let hover_pos = ptr.pos;+ let image_contains = |index: usize, point: Pos2| {+ let (x, y) = xf.screen_to_view(point);+ let Some(p) = info.pages.get(page) else { return false };+ let user = p.view_to_user(x, y);+ images.get(index).is_some_and(|im| im.contains(user.map(f64::from)))+ };+ let selected = view.image_selection.as_ref().filter(|s| s.page == page).map(|s| s.index).filter(|i| *i < boxes.len());+ let dragging = view.image_selection.as_ref().is_some_and(|s| s.drag.is_some());+ // Few images: faint outlines for all of them, as before. Many: only the selected and+ // hovered boxes, so a ~1000-image CAD page stays interactive in Edit text & images.+ // Fully clipped placements (empty visible frames) get no outline.+ let faint_all = boxes.len() <= MAX_OUTLINES;+ // The picture being dragged has its frame at the pointer; its outline where it was would+ // trail behind until the release.+ let moving = selected.filter(|_| dragging);+ let hovered_box = hover_pos.and_then(|p| boxes.iter().enumerate().rposition(|(i, b)| b.is_positive() && b.contains(p) && image_contains(i, p)));+ draw_outlines(painter, &boxes, OutlineState { selected, hovered_box, moving, dragging, faint_all });+ // The selected image: frame, corner handles, dragging.+ if let Some(i) = selected.filter(|i| boxes.get(*i).is_some_and(|b| b.is_positive())) {+ let b = boxes[i];+ if view.image_selection.as_ref().is_some_and(|s| s.crop.is_some()) {+ return crop_input(cx, view, i, b);+ }+ let corners = [b.left_top(), b.right_top(), b.left_bottom(), b.right_bottom()];+ // Until the page is rendered again its raster has an applied move or resize's picture+ // where it was: it stays blanked there and drawn where it went.+ // The whole-page raster and its tiles are replaced separately: the old frame stays blanked+ // while anything still shows the picture there, but its pixels come from the old frame+ // only while the whole-page raster itself is the old one. Once that is fresh it has the+ // picture where it went, and that is where they come from.+ let (out_of_date, raster_old, raster) = (view.page_out_of_date(page), view.page_raster_out_of_date(page), view.page_raster(page));+ let screen = |r: Rect| Rect::from_two_pos(xf.norm_to_screen(r.min.x, r.min.y), xf.norm_to_screen(r.max.x, r.max.y));+ // Where the screen may still show the picture from before an applied move, while the page+ // isn't drawn again yet. Another drag keeps it blanked too.+ let left_at = view.image_selection.as_ref().and_then(|s| s.settled).filter(|_| out_of_date).map(|(from, _)| from);+ if let Some(s) = view.image_selection.as_mut().filter(|s| s.drag.is_none()) {+ match (s.settled, raster) {+ (Some((from, to)), Some(tex)) if out_of_date => {+ let source = if raster_old { from } else { to };+ stretched_picture(painter, xf, tex, &[screen(from)], screen(source), screen(to));+ }+ _ => s.settled = None,+ }+ }+ if view.image_selection.as_ref().is_some_and(|s| s.drag.is_none()) {+ painter.rect_stroke(b, CornerRadius::ZERO, Stroke::new(1.5, ACCENT), egui::StrokeKind::Outside);+ draw_handles(painter, b);+ }+ if allow_interaction && let Some(corner) = hover_pos.and_then(|p| corners.iter().position(|c| c.distance(p) < 8.0)) {- ui.ctx().set_cursor_icon(if matches!(corner, 0 | 3) { egui::CursorIcon::ResizeNwSe } else { egui::CursorIcon::ResizeNeSw });++ view.cursor.claim(Layer::Handle, if matches!(corner, 0 | 3) { egui::CursorIcon::ResizeNwSe } else { egui::CursorIcon::ResizeNeSw });+ }+ // The rotate handle: a knob above the top edge, joined to it by a short stem.+ let (knob, stem) = rotate_knob(b, ui.clip_rect());+ if view.image_selection.as_ref().is_some_and(|s| s.drag.is_none()) {+ painter.line_segment([stem, knob], Stroke::new(1.0, ACCENT));+ painter.circle(knob, 5.0, Color32::WHITE, Stroke::new(1.0, ACCENT));+ if allow_interaction && hover_pos.is_some_and(|p| p.distance(knob) < 8.0) {- ui.ctx().set_cursor_icon(egui::CursorIcon::Grab);++ view.cursor.claim(Layer::Handle, egui::CursorIcon::Grab);+ }+ }+ if allow_interaction+ && resp.drag_started()+ && let Some(o) = ptr.origin+ && o.distance(knob) < 8.0+ {+ if let Some(s) = view.image_selection.as_mut() {+ s.drag = Some((o, None));+ s.turning = true;+ }+ } else if allow_interaction+ && resp.drag_started()+ && let Some(o) = ptr.origin+ {+ let corner = corners.iter().position(|c| c.distance(o) < 8.0);+ if corner.is_some() || image_contains(i, o) {+ let opposite = corner.map(|k| corners[3 - k]);+ if let Some(s) = view.image_selection.as_mut() {+ s.drag = Some((o, opposite));+ }+ }+ }+ if view.image_selection.as_ref().is_some_and(|s| s.turning) {+ turn_preview(cx, view, i, b, knob);+ return true;+ }+ if let Some((start, opposite)) = view.image_selection.as_ref().and_then(|s| s.drag)+ && let Some(p) = hover_pos+ {+ drag_preview(cx, images, view, (i, b), (start, opposite, p), Blanked { left_at, raster_old });+ return true;+ }+ if allow_interaction+ && ui.input(|inp| inp.key_pressed(egui::Key::Delete) || inp.key_pressed(egui::Key::Backspace))+ && !ui.ctx().egui_wants_keyboard_input()+ {+ view.image_selection = None;+ view.pending_edit = Some(Edit::EditPageImage { page, index: i, change: pdfcraft_engine::ImageEdit::Delete });+ return true;+ }+ }+ if !allow_interaction {+ return false;+ }+ // An open menu stays drawn wherever the pointer is: most of its items lie outside the picture+ // (a logo is smaller than its menu), and a menu that is not drawn for a frame cannot be clicked.+ // Only a menu opened by a right-click on the picture: one opened over text or empty page while+ // a picture stays selected is the page's own menu.+ let menu_key = resp.id.with("image-menu");+ if resp.secondary_clicked() {+ ui.ctx().data_mut(|d| d.insert_temp(menu_key, false));+ }+ let mut menu_drawn = false;+ if let Some(sel) = selected+ && resp.context_menu_opened()+ && ui.ctx().data(|d| d.get_temp::<bool>(menu_key)).unwrap_or(false)+ {+ resp.context_menu(|ui| image_menu(ui, page, sel, images, view, action));+ menu_drawn = true;+ }+ let Some(p) = hover_pos.filter(|p| xf.rect.contains(*p)) else { return false };+ let Some(hit) = boxes.iter().enumerate().rposition(|(i, b)| b.contains(p) && image_contains(i, p)) else { return false };+ if selected != Some(hit) {+ painter.rect_stroke(boxes[hit], CornerRadius::ZERO, Stroke::new(1.5, ACCENT.gamma_multiply(0.7)), egui::StrokeKind::Outside);+ }+ let Some(b) = boxes.get(hit).copied() else { return false };+ let corner = [b.left_top(), b.right_top(), b.left_bottom(), b.right_bottom()].iter().position(|c| c.distance(p) < 8.0);- ui.ctx().set_cursor_icon(match (selected == Some(hit), corner) {- (true, Some(0 | 3)) => egui::CursorIcon::ResizeNwSe,- (true, Some(_)) => egui::CursorIcon::ResizeNeSw,- (true, None) => egui::CursorIcon::Move,- _ => egui::CursorIcon::PointingHand,- });++ match (selected == Some(hit), corner) {++ (true, Some(0 | 3)) => view.cursor.claim(Layer::Handle, egui::CursorIcon::ResizeNwSe),++ (true, Some(_)) => view.cursor.claim(Layer::Handle, egui::CursorIcon::ResizeNeSw),++ (true, None) => view.cursor.claim(Layer::Placed, egui::CursorIcon::Move),++ // A click selects it.++ _ => view.cursor.claim(Layer::Placed, egui::CursorIcon::PointingHand),++ }+ if resp.clicked() || resp.secondary_clicked() {+ view.image_selection = Some(ImageSelection { page, index: hit, drag: None, crop: None, turning: false, settled: None });+ }+ if resp.secondary_clicked() {+ ui.ctx().data_mut(|d| d.insert_temp(menu_key, true));+ }+ if selected == Some(hit) && !menu_drawn {+ resp.context_menu(|ui| image_menu(ui, page, hit, images, view, action));+ }+ true+ }++ /// The right-click menu of the picture `hit` (its rotate, flip, replace, copy, cut, redact, link,+ /// recognize and delete items).+ fn image_menu(+ ui: &mut egui::Ui,+ page: usize,+ hit: usize,+ images: &[pdfcraft_engine::PageImage],+ view: &mut DocView,+ action: &mut Option<ImageAction>,+ ) {+ use pdfcraft_engine::ImageEdit as E;+ let items: [(&str, Option<E>); 4] = [+ (tl!("Rotate Clockwise"), Some(E::Rotate(1))),+ (tl!("Rotate Counterclockwise"), Some(E::Rotate(3))),+ (tl!("Flip Horizontal"), Some(E::Flip { horizontal: true })),+ (tl!("Flip Vertical"), Some(E::Flip { horizontal: false })),+ ];+ for (label, change) in items {+ if ui.button(label).clicked() {+ view.pending_edit = change.map(|c| Edit::EditPageImage { page, index: hit, change: c });+ ui.close();+ }+ }+ // Crop: the handles trim instead of resizing until Done.+ if ui.button(tl!("Crop Image")).clicked() {+ if let (Some(s), Some(im)) = (view.image_selection.as_mut(), images.get(hit)) {+ s.crop = Some(CropMode::new(im.visible_rect.unwrap_or(im.rect)));+ }+ ui.close();+ }+ let cropped = images.get(hit).is_some_and(|im| im.visible_rect.is_some_and(|v| v.iter().zip(im.rect.iter()).any(|(a, b)| (a - b).abs() > 0.01)));+ if ui.add_enabled(cropped, egui::Button::new(tl!("Remove Crop"))).clicked() {+ if let Some(im) = images.get(hit) {+ view.pending_edit = Some(Edit::EditPageImage { page, index: hit, change: E::Crop(im.rect) });+ }+ ui.close();+ }+ let raster = images.get(hit).is_some_and(|image| !image.is_form);+ if ui.add_enabled(raster, egui::Button::new(tl!("Replace Image…"))).clicked() {+ *action = Some(ImageAction::Replace(page, hit));+ ui.close();+ }+ if ui.add_enabled(raster, egui::Button::new(tl!("Save Image As…"))).clicked() {+ *action = Some(ImageAction::Save(page, hit));+ ui.close();+ }+ // Cutting and copying also find the picture inside grouped Form artwork.+ if ui.button(tl!("Cut Image")).clicked() {+ *action = Some(ImageAction::Cut(page, hit));+ ui.close();+ }+ if ui.button(tl!("Copy Image")).clicked() {+ *action = Some(ImageAction::Copy(page, hit));+ ui.close();+ }+ if ui.button(tl!("Copy Image in Original Format")).clicked() {+ *action = Some(ImageAction::CopyFile(page, hit));+ ui.close();+ }+ ui.separator();+ if ui.button(tl!("Redact Image")).clicked() {+ *action = Some(ImageAction::Redact(page, hit));+ ui.close();+ }+ if ui.button(tl!("Create Link…")).clicked() {+ *action = Some(ImageAction::Link(page, hit));+ ui.close();+ }+ if ui.button(tl!("Recognize Text…")).clicked() {+ *action = Some(ImageAction::Recognize(page));+ ui.close();+ }+ ui.separator();+ if ui.button(tl!("Delete")).clicked() {+ view.image_selection = None;+ view.pending_edit = Some(Edit::EditPageImage { page, index: hit, change: E::Delete });+ ui.close();+ }+ }diff --cc crates/ui-egui/src/tools/fill_sign.rsindex 0861cd3cd,995b60fc4..486194482--- a/crates/ui-egui/src/tools/fill_sign.rs+++ b/crates/ui-egui/src/tools/fill_sign.rs@@@ -8,11 -8,14 +8,15 @@@ use pdfcraft_engine::signature_scan::{Duse pdfcraft_engine::{Edit, FillMark, NewAnnotation, PhotoRect, Shape, SignatureImage, SignaturePhoto, Style, Turn};use pdfcraft_render::{DocInfo, PageInfo};- use crate::canvas::{DocView, PageXform};+ use crate::canvas::{DocView, PageToolContext, PageXform};+use crate::page_cursor::Layer;- use crate::page_pointer::PagePointer;use crate::theme::Tokens;+ mod scan;++ pub use scan::ScanDraft;+ use scan::scan_tab;+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]pub enum FillTool {Text,diff --cc crates/ui-egui/src/tools/forms_ui.rsindex e0d51a3da,705ecf45b..ea593006e--- a/crates/ui-egui/src/tools/forms_ui.rs+++ b/crates/ui-egui/src/tools/forms_ui.rs@@@ -13,9 -13,7 +13,8 @@@ use egui::{Color32, CornerRadius, Pos2use pdfcraft_engine::{Edit, FieldValue, FormField, FormFieldKind, FormWidget, field_flags, form_appearance};use pdfcraft_render::DocInfo;- use crate::canvas::{DocView, PageXform};+ use crate::canvas::{DocView, PageToolContext, PageXform};+use crate::page_cursor::Layer;- use crate::page_pointer::PagePointer;use crate::theme::Tokens;const FOCUS_BLUE: Color32 = Color32::from_rgb(0x14, 0x73, 0xE6);@@@ -152,20 -150,23 +151,10 @@@ fn toggle_edit(f: &FormField, w: &FormWSome(Edit::SetFieldValue { name: f.name.clone(), value })}-/// Where the pointer is relative to one page's form widgets.-#[derive(Clone, Copy, Debug, PartialEq, Eq)]-pub(crate) enum FieldPointer {- /// Not over a field.- Away,- /// Over a field, which has set the cursor. Nothing is pressed, so the layers below still see- /// the hover, but they must not replace the cursor: a check box drawn with a glyph, or set- /// on printed text, is a button, not text to select.- Over,- /// The field owns the press or click.- Owned,-}--/// Clicks on form widgets of one page.-pub(crate) fn page_input(cx: PageToolContext<'_>, form: &[FormField], allowed: bool, view: &mut DocView) -> FieldPointer {+/// Clicks on form widgets of one page. `true` when a field owns the press or click.- #[allow(clippy::too_many_arguments)]- pub(crate) fn page_input(- ui: &egui::Ui,- resp: &egui::Response,- xf: &PageXform,- ptr: &PagePointer,- page: usize,- info: &DocInfo,- form: &[FormField],- allowed: bool,- view: &mut DocView,- ) -> bool {++pub(crate) fn page_input(cx: PageToolContext<'_>, form: &[FormField], allowed: bool, view: &mut DocView) -> bool {+ let PageToolContext { ui, resp, xf, ptr, page, info, .. } = cx;- let Some(p) = ptr.within(xf.rect) else { return FieldPointer::Away };+ let Some(p) = ptr.within(xf.rect) else { return false };let hit = form.iter().find_map(|f| {f.widgets.iter()diff --cc crates/ui-egui/src/tools/link_ui.rsindex 012a95f95,c68ccca81..a0840e1b8--- a/crates/ui-egui/src/tools/link_ui.rs+++ b/crates/ui-egui/src/tools/link_ui.rs@@@ -6,9 -6,7 +6,8 @@@ use egui::{Color32, CornerRadius, Pos2use pdfcraft_engine::{Edit, LinkAction, LinkHighlight, LinkItem, LinkStyle};use pdfcraft_render::DocInfo;- use crate::canvas::{DocView, PageXform};+ use crate::canvas::{DocView, PageToolContext, PageXform};+use crate::page_cursor::Layer;- use crate::page_pointer::PagePointer;use crate::theme::{self, Tokens};use crate::{PdfCraftApp, widgets};diff --cc crates/ui-egui/src/tools/object_ui.rsindex 8d4a1137e,be23b86d4..96cc0adf2--- a/crates/ui-egui/src/tools/object_ui.rs+++ b/crates/ui-egui/src/tools/object_ui.rs@@@ -7,9 -7,7 +7,8 @@@ use egui::{Color32, Pos2, Rect, Stroke}use pdfcraft_engine::{Document, Edit, EditableObject, MAX_MOVE_OBJECTS, ObjectKind, ObjectTarget};use pdfcraft_render::DocInfo;- use crate::canvas::{DocView, PageXform};+ use crate::canvas::{DocView, PageToolContext, PageXform};+use crate::page_cursor::Layer;- use crate::page_pointer::PagePointer;const BLUE: Color32 = Color32::from_rgb(0x14, 0x73, 0xE6);diff --cc crates/ui-egui/src/tools/prepare.rsindex 000000000,88f0b1d2b..2c3dc5556mode 000000,100644..100644--- a/crates/ui-egui/src/tools/prepare.rs+++ b/crates/ui-egui/src/tools/prepare.rs@@@ -1,0 -1,740 +1,741 @@@+ //! Prepare a form (Acrobat's Prepare Form, execution plan M6.6): add fields with the field+ //! tools (click for the default size, or drag a rectangle), select, move and resize them, see+ //! their name tags, delete them, and edit them in Field Properties.+ //!+ //! While the Prepare a form panel is open the page shows every field with a light-blue fill and+ //! its name; clicks select fields instead of filling them in, as in Acrobat.++ use egui::{Color32, CornerRadius, Pos2, Rect, Stroke, vec2};+ use pdfcraft_engine::form_scripts::{CalcOp, Calculate, DATE_PRESETS, Format, TIME_PRESETS, Validate, format_value};+ use pdfcraft_engine::{BorderStyle, Document, Edit, FieldFont, FieldLook, FieldProps, FormField, FormFieldKind, NewField};+ use pdfcraft_render::DocInfo;++ use crate::canvas::{DocView, PageToolContext, PageXform};+ use crate::comments;++use crate::page_cursor::Layer;+ use crate::theme;+ use crate::widgets;++ mod draft;+ mod properties;+ mod tabs;++ pub use draft::{ACTION_KINDS, ActionDraft, FieldDraft, FieldTab};+ pub(crate) use draft::{da_font, da_size};+ pub(crate) use properties::body;++ const SELECT_BLUE: Color32 = Color32::from_rgb(0x14, 0x73, 0xE6);+ /// Acrobat's field fill in Prepare Form (light blue).+ pub(crate) const FIELD_FILL: Color32 = Color32::from_rgba_premultiplied(0x1B, 0x34, 0x54, 0x59);++ /// The Add form components tools.+ #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+ pub enum FieldTool {+ Text,+ /// Rows and columns of text fields in the area drawn, set up in a window first.+ TextTable,+ CheckBox,+ Radio,+ Combo,+ List,+ Button,+ Image,+ Date,+ Signature,+ }++ pub const FIELD_TOOLS: [FieldTool; 10] = [+ FieldTool::Text,+ FieldTool::TextTable,+ FieldTool::CheckBox,+ FieldTool::Radio,+ FieldTool::Combo,+ FieldTool::List,+ FieldTool::Button,+ FieldTool::Image,+ FieldTool::Date,+ FieldTool::Signature,+ ];++ impl FieldTool {+ pub fn command(self) -> &'static str {+ match self {+ FieldTool::Text => "form.add.text",+ FieldTool::TextTable => "form.add.text_table",+ FieldTool::CheckBox => "form.add.checkbox",+ FieldTool::Radio => "form.add.radio",+ FieldTool::Combo => "form.add.combo",+ FieldTool::List => "form.add.list",+ FieldTool::Button => "form.add.button",+ FieldTool::Image => "form.add.image",+ FieldTool::Date => "form.add.date",+ FieldTool::Signature => "form.add.signature",+ }+ }++ pub fn from_command(id: &str) -> Option<Self> {+ FIELD_TOOLS.into_iter().find(|t| t.command() == id)+ }++ pub fn label(self) -> &'static str {+ match self {+ FieldTool::Text => "Text field",+ FieldTool::TextTable => "Text field table",+ FieldTool::CheckBox => "Checkbox",+ FieldTool::Radio => "Radio button",+ FieldTool::Combo => "Drop-down list",+ FieldTool::List => "List box",+ FieldTool::Button => "Button",+ FieldTool::Image => "Image field",+ FieldTool::Date => "Date field",+ FieldTool::Signature => "Digital signature",+ }+ }++ /// The field a click or drag creates. Radio buttons dropped next to a selected radio group+ /// join it with the next free choice.+ pub fn new_field(self, join: Option<&FormField>) -> NewField {+ match self {+ // A table's cells are text fields.+ FieldTool::Text | FieldTool::TextTable => NewField::Text { multiline: false },+ FieldTool::CheckBox => NewField::CheckBox,+ FieldTool::Radio => match join.filter(|f| f.kind == FormFieldKind::Radio) {+ Some(g) => {+ let taken: Vec<&str> = g.widgets.iter().filter_map(|w| w.on_state.as_deref()).collect();+ let export =+ (1..=u64::MAX).map(|i| format!("Choice{i}")).find(|c| !taken.contains(&c.as_str())).unwrap_or_else(|| "Choice".into());+ NewField::Radio { group: Some(g.name.clone()), export }+ }+ None => NewField::Radio { group: None, export: "Choice1".into() },+ },+ FieldTool::Combo => NewField::Combo { options: Vec::new(), editable: false },+ FieldTool::List => NewField::List { options: Vec::new(), multi: false },+ FieldTool::Button => NewField::Button { caption: String::new() },+ FieldTool::Image => NewField::Image,+ FieldTool::Date => NewField::Date,+ FieldTool::Signature => NewField::Signature,+ }+ }++ /// Width and height in points of a field placed with a single click.+ pub fn default_size(self) -> (f64, f64) {+ match self {+ FieldTool::TextTable => (180.0, 110.0),+ FieldTool::CheckBox | FieldTool::Radio => (14.0, 14.0),+ FieldTool::List => (144.0, 54.0),+ FieldTool::Button => (72.0, 22.0),+ FieldTool::Image => (144.0, 108.0),+ FieldTool::Signature => (180.0, 36.0),+ FieldTool::Date => (108.0, 22.0),+ FieldTool::Text | FieldTool::Combo => (144.0, 22.0),+ }+ }+ }++ /// What the pointer is doing to a field.+ #[derive(Clone, Copy, Debug, PartialEq)]+ enum Grab {+ /// Drawing a new field from this screen point.+ Draw(Pos2),+ /// Selecting fields inside a dragged rectangle.+ Select(Pos2),+ Move,+ /// Resizing by a corner: (moves left edge, moves top edge) in screen terms.+ Corner(bool, bool),+ }++ #[derive(Clone, Debug, Default, PartialEq)]+ pub struct PrepareView {+ /// The selected field and which of its widgets (the anchor of Align and Match Size).+ pub selected: Option<(String, usize)>,+ /// More fields selected with Shift- or ⌘-click.+ pub also: Vec<(String, usize)>,+ /// Select the field an Add field edit creates (the form's length before it).+ pub select_added: Option<usize>,+ grab: Option<(usize, Grab, Pos2)>,+ marquee_before: Option<Vec<(String, usize)>>,+ /// Escape ends egui's drag too; ignore its release until the mouse is up.+ ignore_release: bool,+ }++ impl PrepareView {+ /// Cancel a preparation marquee without injecting the terminal pointer release that Escape does.+ pub(crate) fn cancel_pointer_gesture(&mut self) {+ cancel_marquee(self);+ // Unlike Escape, control cancellation never injects a terminal pointer release.+ self.ignore_release = false;+ }++ /// Unique field names: selecting several widgets of one radio group still edits one field.+ pub fn names(&self) -> Vec<String> {+ let mut names = Vec::new();+ for (name, _) in self.selected.iter().chain(self.also.iter()) {+ if !names.contains(name) {+ names.push(name.clone());+ }+ }+ names+ }++ pub(crate) fn select(&mut self, key: (String, usize), extend: bool) {+ if !extend || self.selected.is_none() {+ self.selected = Some(key);+ self.also.clear();+ } else if self.selected.as_ref() == Some(&key) {+ self.selected = if self.also.is_empty() { None } else { Some(self.also.remove(0)) };+ } else if let Some(index) = self.also.iter().position(|k| *k == key) {+ self.also.remove(index);+ } else {+ self.also.push(key);+ }+ }+ }++ fn screen_rect(xf: &PageXform, info: &DocInfo, page: usize, r: [f64; 4]) -> Rect {+ xf.user_rect(info, page, [r[0] as f32, r[1] as f32, r[2] as f32, r[3] as f32])+ }++ fn to_user(xf: &PageXform, info: &DocInfo, page: usize, p: Pos2) -> [f64; 2] {+ let (vx, vy) = xf.screen_to_view(p);+ let u = info.pages[page].view_to_user(vx, vy);+ [u[0] as f64, u[1] as f64]+ }++ /// Where a table goes, in view space, for a screen rect drawn with the table tool: a click (a rect+ /// under 4 pixels either way) puts the default size's top-left corner at the pointer, moved in from+ /// the page's edges as far as it takes to stay on the page.+ fn table_rect(xf: &PageXform, r: Rect) -> [f64; 4] {+ let (x0, y0) = xf.screen_to_view(r.min);+ if r.width() < 4.0 || r.height() < 4.0 {+ let (pw, ph) = (f64::from(xf.pw), f64::from(xf.ph));+ let (dw, dh) = FieldTool::TextTable.default_size();+ // Smaller than the default only on a page smaller than it.+ let (w, h) = (dw.min(pw), dh.min(ph));+ let (x, y) = (f64::from(x0).min(pw - w).max(0.0), f64::from(y0).min(ph - h).max(0.0));+ return [x, y, x + w, y + h];+ }+ let (x1, y1) = xf.screen_to_view(r.max);+ [x0, y0, x1, y1].map(f64::from)+ }++ /// A screen rect → a normalised user-space rect.+ fn user_rect(xf: &PageXform, info: &DocInfo, page: usize, r: Rect) -> [f64; 4] {+ let (a, b) = (to_user(xf, info, page, r.min), to_user(xf, info, page, r.max));+ [a[0].min(b[0]), a[1].min(b[1]), a[0].max(b[0]), a[1].max(b[1])]+ }++ fn handles(r: Rect) -> [(Pos2, bool, bool); 4] {+ [(r.left_top(), true, true), (r.right_top(), false, true), (r.left_bottom(), true, false), (r.right_bottom(), false, false)]+ }++ /// The rect while a move or resize is in progress. With `shift` held a corner keeps the field's+ /// proportions, as it does for comments and stamps.+ fn dragged(r: Rect, grab: Grab, delta: egui::Vec2, shift: bool) -> Rect {+ match grab {+ Grab::Move => r.translate(delta),+ Grab::Corner(left, top) => {+ let handle = (if left { -1 } else { 1 }, if top { -1 } else { 1 });+ comments::resized(r, handle, delta, comments::corner_ratio(r, None, shift))+ }+ Grab::Draw(_) | Grab::Select(_) => r,+ }+ }++ pub(crate) struct Outcome {+ /// The click or drag belonged to Prepare a form.+ pub consumed: bool,+ /// Open Field Properties for the selected field.+ pub properties: bool,+ /// A field was placed: go back to the Select tool.+ pub placed: bool,+ /// A table of text fields was drawn: open its window for this page and area (view space).+ pub table: Option<(usize, [f64; 4])>,+ }++ /// Pointer input on one page while preparing a form.+ pub(crate) fn page_input(cx: PageToolContext<'_>, form: &[FormField], tool: Option<FieldTool>, allowed: bool, view: &mut DocView) -> Outcome {+ let PageToolContext { ui, resp, xf, ptr, page, info, .. } = cx;+ let mut out = Outcome { consumed: false, properties: false, placed: false, table: None };+ let pointer = ptr.pos;+ let prep = &mut view.prepare;++ if prep.marquee_before.is_some() && ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape)) {+ cancel_marquee(prep);+ out.consumed = true;+ return out;+ }+ if prep.ignore_release {+ if !ptr.primary_down {+ prep.ignore_release = false;+ }+ out.consumed = true;+ return out;+ }++ // A grab in progress on this page.+ if let Some((gp, grab, start)) = prep.grab+ && gp == page+ {+ out.consumed = true;+ if resp.drag_stopped() || !ptr.primary_down {+ prep.grab = None;+ let end = pointer.unwrap_or(start);+ match grab {+ Grab::Select(from) => {+ prep.marquee_before = None;+ let rect = Rect::from_two_pos(from, end).intersect(xf.rect);+ for f in form {+ for (wi, w) in f.widgets.iter().enumerate().filter(|(_, w)| w.page == Some(page)) {+ if screen_rect(xf, info, page, w.rect).intersects(rect) {+ let key = (f.name.clone(), wi);+ if prep.selected.is_none() {+ prep.selected = Some(key);+ } else if prep.selected.as_ref() != Some(&key) && !prep.also.contains(&key) {+ prep.also.push(key);+ }+ }+ }+ }+ }+ Grab::Draw(from) => {+ let Some(tool) = tool else { return out };+ if tool == FieldTool::TextTable {+ out.table = Some((page, table_rect(xf, Rect::from_two_pos(from, end).intersect(xf.rect))));+ out.placed = true;+ return out;+ }+ let r = Rect::from_two_pos(from, end).intersect(xf.rect);+ let rect = user_rect(xf, info, page, r);+ let rect = if r.width() < 4.0 || r.height() < 4.0 {+ // A click: the default size, top-left at the pointer.+ let at = to_user(xf, info, page, from);+ let (w, h) = tool.default_size();+ [at[0], at[1] - h, at[0] + w, at[1]]+ } else {+ rect+ };+ let join = prep.selected.as_ref().and_then(|(n, _)| form.iter().find(|f| &f.name == n));+ prep.select_added = Some(form.len());+ view.pending_edit = Some(Edit::AddField { page, rect, kind: tool.new_field(join), name: None });+ out.placed = true;+ }+ Grab::Move | Grab::Corner(..) => {+ let Some((name, wi)) = prep.selected.clone() else { return out };+ let Some(w) = form.iter().find(|f| f.name == name).and_then(|f| f.widgets.get(wi)) else { return out };+ let delta = end - start;+ if delta.length() >= 1.0 {+ let shift = ui.input(|i| i.modifiers.shift);+ let r = dragged(screen_rect(xf, info, page, w.rect), grab, delta, shift);+ let rect = user_rect(xf, info, page, r);+ view.pending_edit =+ Some(Edit::SetFieldProps { name, props: Box::new(FieldProps { rect: Some((wi, rect)), ..Default::default() }) });+ }+ }+ }+ }+ return out;+ }++ let Some(p) = pointer.filter(|p| xf.rect.contains(*p)) else { return out };+ if !allowed {+ return out;+ }+ if let Some(tool) = tool {- ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair);++ view.cursor.claim(Layer::ToolArea, egui::CursorIcon::Crosshair);+ if resp.drag_started() || resp.clicked() {+ let origin = ptr.origin.filter(|o| xf.rect.contains(*o)).unwrap_or(p);+ prep.grab = Some((page, Grab::Draw(origin), origin));+ out.consumed = true;+ if resp.clicked() {+ // A click without a drag: finish at once.+ prep.grab = None;+ if tool == FieldTool::TextTable {+ out.table = Some((page, table_rect(xf, Rect::from_min_size(p, egui::Vec2::ZERO))));+ out.placed = true;+ return out;+ }+ let at = to_user(xf, info, page, p);+ let (w, h) = tool.default_size();+ let join = prep.selected.as_ref().and_then(|(n, _)| form.iter().find(|f| &f.name == n));+ prep.select_added = Some(form.len());+ view.pending_edit = Some(Edit::AddField { page, rect: [at[0], at[1] - h, at[0] + w, at[1]], kind: tool.new_field(join), name: None });+ out.placed = true;+ }+ }+ return out;+ }++ // Right-click a field: select it (the context menu acts on it).+ if resp.secondary_clicked()+ && let Some((f, wi)) = form.iter().find_map(|f| {+ f.widgets.iter().enumerate().find(|(_, w)| w.page == Some(page) && screen_rect(xf, info, page, w.rect).contains(p)).map(|(i, _)| (f, i))+ })+ {+ let key = (f.name.clone(), wi);+ if let Some(i) = prep.also.iter().position(|k| *k == key) {+ // Part of the selection: it becomes the anchor the others line up with.+ prep.also.remove(i);+ if let Some(old) = prep.selected.replace(key) {+ prep.also.push(old);+ }+ } else if prep.selected.as_ref() != Some(&key) {+ prep.selected = Some(key);+ prep.also.clear();+ }+ }+ // The Select tool: corner handles of the selection, then fields.+ let selected_rect = prep+ .selected+ .as_ref()+ .and_then(|(n, wi)| form.iter().find(|f| &f.name == n)?.widgets.get(*wi).filter(|w| w.page == Some(page)))+ .map(|w| screen_rect(xf, info, page, w.rect));+ let corner = selected_rect.and_then(|r| handles(r).into_iter().find(|(c, ..)| c.distance(p) <= 6.0));+ let hit = form.iter().find_map(|f| {+ f.widgets.iter().enumerate().find(|(_, w)| w.page == Some(page) && screen_rect(xf, info, page, w.rect).contains(p)).map(|(i, _)| (f, i))+ });+ if let Some((_, left, top)) = corner {- ui.ctx().set_cursor_icon(if left == top { egui::CursorIcon::ResizeNwSe } else { egui::CursorIcon::ResizeNeSw });++ view.cursor.claim(Layer::Handle, if left == top { egui::CursorIcon::ResizeNwSe } else { egui::CursorIcon::ResizeNeSw });+ } else if hit.is_some() {- ui.ctx().set_cursor_icon(egui::CursorIcon::Move);++ view.cursor.claim(Layer::Field, egui::CursorIcon::Move);+ }+ if resp.drag_started() {+ let origin = ptr.origin.unwrap_or(p);+ if let Some((_, left, top)) = selected_rect.and_then(|r| handles(r).into_iter().find(|(c, ..)| c.distance(origin) <= 6.0)) {+ prep.grab = Some((page, Grab::Corner(left, top), origin));+ out.consumed = true;+ } else if let Some((f, wi)) = form.iter().find_map(|f| {+ f.widgets+ .iter()+ .enumerate()+ .find(|(_, w)| w.page == Some(page) && screen_rect(xf, info, page, w.rect).contains(origin))+ .map(|(i, _)| (f, i))+ }) {+ prep.selected = Some((f.name.clone(), wi));+ prep.grab = Some((page, Grab::Move, origin));+ out.consumed = true;+ } else {+ prep.marquee_before = Some(prep.selected.iter().chain(prep.also.iter()).cloned().collect());+ if !ui.input(|i| i.modifiers.shift || i.modifiers.command) {+ prep.selected = None;+ prep.also.clear();+ }+ prep.grab = Some((page, Grab::Select(origin), origin));+ out.consumed = true;+ }+ return out;+ }+ if resp.double_clicked() && hit.is_some() && !ui.input(|i| i.modifiers.shift || i.modifiers.command) {+ out.consumed = true;+ out.properties = true;+ return out;+ }+ if resp.clicked() {+ let extend = ui.input(|i| i.modifiers.shift || i.modifiers.command);+ match hit {+ // Shift/⌘-click adds or removes a field from the selection.+ Some((f, wi)) => {+ prep.select((f.name.clone(), wi), extend);+ out.consumed = true;+ }+ None if corner.is_none() => {+ prep.selected = None;+ prep.also.clear();+ }+ None => out.consumed = true,+ }+ }+ out.consumed |= hit.is_some() && resp.is_pointer_button_down_on();+ out+ }++ /// Align, Center, Distribute and Set Fields to Same Size (Prepare a form, several fields+ /// selected).+ #[derive(Clone, Copy, Debug, PartialEq, Eq)]+ pub enum Arrange {+ AlignLeft,+ AlignRight,+ AlignTop,+ AlignBottom,+ /// Centres on one vertical line (the anchor's).+ AlignCenterH,+ /// Centres on one horizontal line.+ AlignCenterV,+ DistributeH,+ DistributeV,+ SameWidth,+ SameHeight,+ SameSize,+ }++ impl Arrange {+ pub fn label(self) -> &'static str {+ match self {+ Arrange::AlignLeft | Arrange::AlignRight | Arrange::AlignTop | Arrange::AlignBottom | Arrange::AlignCenterH | Arrange::AlignCenterV => {+ "Align fields"+ }+ Arrange::DistributeH | Arrange::DistributeV => "Distribute fields",+ Arrange::SameWidth | Arrange::SameHeight | Arrange::SameSize => "Match field sizes",+ }+ }+ }++ /// The edits that arrange the selected widgets (user space; the anchor stays put).+ pub fn arrange(form: &[FormField], anchor: &(String, usize), others: &[(String, usize)], op: Arrange) -> Option<Edit> {+ let rect_of = |k: &(String, usize)| form.iter().find(|f| f.name == k.0).and_then(|f| f.widgets.get(k.1)).map(|w| w.rect);+ let a = rect_of(anchor)?;+ let mut items: Vec<((String, usize), [f64; 4])> = others.iter().filter_map(|k| rect_of(k).map(|r| (k.clone(), r))).collect();+ if items.is_empty() {+ return None;+ }+ let (aw, ah) = (a[2] - a[0], a[3] - a[1]);+ let mut moved: Vec<((String, usize), [f64; 4])> = Vec::new();+ match op {+ Arrange::DistributeH | Arrange::DistributeV => {+ // Even gaps between all selected fields (the outermost stay).+ items.push((anchor.clone(), a));+ if items.len() < 3 {+ return None;+ }+ let horiz = op == Arrange::DistributeH;+ items.sort_by(|x, y| if horiz { x.1[0].total_cmp(&y.1[0]) } else { y.1[3].total_cmp(&x.1[3]) });+ let size = |r: &[f64; 4]| if horiz { r[2] - r[0] } else { r[3] - r[1] };+ let (first, last) = (items[0].1, items[items.len() - 1].1);+ let span = if horiz { last[2] - first[0] } else { first[3] - last[1] };+ let total: f64 = items.iter().map(|(_, r)| size(r)).sum();+ let gap = (span - total) / (items.len() - 1) as f64;+ let mut at = if horiz { first[0] } else { first[3] };+ for (k, r) in &items {+ let s = size(r);+ let nr = if horiz { [at, r[1], at + s, r[3]] } else { [r[0], at - s, r[2], at] };+ at = if horiz { at + s + gap } else { at - s - gap };+ moved.push((k.clone(), nr));+ }+ }+ _ => {+ for (k, r) in items {+ let (w, h) = (r[2] - r[0], r[3] - r[1]);+ let nr = match op {+ Arrange::AlignLeft => [a[0], r[1], a[0] + w, r[3]],+ Arrange::AlignRight => [a[2] - w, r[1], a[2], r[3]],+ Arrange::AlignTop => [r[0], a[3] - h, r[2], a[3]],+ Arrange::AlignBottom => [r[0], a[1], r[2], a[1] + h],+ Arrange::AlignCenterH => {+ let cx = (a[0] + a[2]) / 2.0;+ [cx - w / 2.0, r[1], cx + w / 2.0, r[3]]+ }+ Arrange::AlignCenterV => {+ let cy = (a[1] + a[3]) / 2.0;+ [r[0], cy - h / 2.0, r[2], cy + h / 2.0]+ }+ Arrange::SameWidth => [r[0], r[1], r[0] + aw, r[3]],+ Arrange::SameHeight => [r[0], r[3] - ah, r[2], r[3]],+ _ => [r[0], r[3] - ah, r[0] + aw, r[3]],+ };+ moved.push((k, nr));+ }+ }+ }+ let edits: Vec<Edit> = moved+ .into_iter()+ .filter(|(k, nr)| rect_of(k).is_some_and(|r| r.iter().zip(nr).any(|(x, y)| (x - y).abs() > 1e-6)))+ .map(|((name, wi), rect)| Edit::SetFieldProps { name, props: Box::new(FieldProps { rect: Some((wi, rect)), ..Default::default() }) })+ .collect();+ (!edits.is_empty()).then(|| Edit::Batch { label: op.label().into(), edits })+ }++ /// Fields with their light-blue fill and name tags, the selection with its handles, and the+ /// rectangle being drawn or dragged to the pages' `pointer`.+ pub(crate) fn paint_page(cx: PageToolContext<'_>, form: &[FormField], view: &DocView) {+ let PageToolContext { ui, xf, page, info, ptr, .. } = cx;+ let painter = ui.painter();+ let pointer = ptr.pos;+ let prep = &view.prepare;+ let grab = prep.grab.filter(|(gp, ..)| *gp == page);+ let zoom = xf.zoom().clamp(0.5, 3.0);+ for f in form {+ for (wi, w) in f.widgets.iter().enumerate().filter(|(_, w)| w.page == Some(page)) {+ let mut r = screen_rect(xf, info, page, w.rect);+ let selected = prep.selected.as_ref().is_some_and(|(n, i)| n == &f.name && *i == wi);+ let also = prep.also.iter().any(|(n, i)| n == &f.name && *i == wi);+ if selected && let (Some((_, g, start)), Some(p)) = (grab, pointer) {+ r = dragged(r, g, p - start, ui.input(|i| i.modifiers.shift));+ }+ painter.rect_filled(r, CornerRadius::ZERO, FIELD_FILL);+ painter.rect_stroke(+ r,+ CornerRadius::ZERO,+ Stroke::new(if also { 2.0 } else { 1.0 }, if selected || also { SELECT_BLUE } else { Color32::from_gray(90) }),+ egui::StrokeKind::Inside,+ );+ // The name tag: white text on black, clipped to the field.+ // The full name, as Acrobat shows it: MASTER.first, not first (#2696).+ let label = f.name.as_str();+ let font = theme::regular((9.0 * zoom).clamp(7.0, 13.0));+ let galley = painter.layout_no_wrap(label.to_string(), font, Color32::WHITE);+ let size = galley.size() + vec2(6.0, 2.0);+ let tag = Rect::from_center_size(r.center(), size);+ let clip = painter.clip_rect().intersect(r);+ let p2 = painter.with_clip_rect(clip);+ p2.rect_filled(tag, CornerRadius::same(1), if selected { SELECT_BLUE } else { Color32::BLACK });+ p2.galley(tag.min + vec2(3.0, 1.0), galley, Color32::WHITE);+ if selected {+ painter.rect_stroke(r.expand(1.0), CornerRadius::ZERO, Stroke::new(2.0, SELECT_BLUE), egui::StrokeKind::Outside);+ for (c, ..) in handles(r) {+ painter.circle(c, 3.5, Color32::WHITE, Stroke::new(1.5, SELECT_BLUE));+ }+ }+ }+ }+ if let (Some((_, Grab::Draw(from) | Grab::Select(from), _)), Some(p)) = (grab, pointer) {+ let r = Rect::from_two_pos(from, p).intersect(xf.rect);+ painter.rect_filled(r, CornerRadius::ZERO, FIELD_FILL);+ painter.rect_stroke(r, CornerRadius::ZERO, Stroke::new(1.0, SELECT_BLUE), egui::StrokeKind::Inside);+ }+ }++ /// Delete the selected field and every field selected with it (#95), as one undoable step, and+ /// clear the selection.+ pub(crate) fn delete_selected(view: &mut DocView) -> Option<Edit> {+ let (first, _) = view.prepare.selected.take()?;+ let mut names = vec![first];+ for (name, _) in std::mem::take(&mut view.prepare.also) {+ if !names.contains(&name) {+ names.push(name);+ }+ }+ if names.len() == 1 {+ return names.pop().map(|name| Edit::DeleteField { name });+ }+ let label = format!("Delete {} fields", names.len());+ Some(Edit::Batch { label, edits: names.into_iter().map(|name| Edit::DeleteField { name }).collect() })+ }++ /// The arrow keys move the selected field a point, Shift and an arrow ten points, as in Acrobat,+ /// as the object nudge does (`object_ui::nudge_keys`) and as dragging it does (#2608). The keys+ /// are consumed before the view turns the page with them; one press is one undo step.+ pub(crate) fn nudge_keys(ctx: &egui::Context, view: &mut DocView, doc: &Document) {+ // `consume_key` lets an extra Alt through, and Alt+↑/↓ belongs to Calculation order's move.+ if ctx.egui_wants_keyboard_input() || view.prepare.grab.is_some() || ctx.input(|i| i.modifiers.alt) {+ return;+ }+ let Some((name, wi)) = view.prepare.selected.clone() else { return };+ let Some(w) = doc.form.iter().find(|f| f.name == name).and_then(|f| f.widgets.get(wi)) else { return };+ let Some(page) = w.page else { return };+ let Some(xf) = view.page_xform(page) else { return };+ use egui::{Key, Modifiers};+ let mut step = egui::Vec2::ZERO;+ ctx.input_mut(|i| {+ for (key, direction) in [+ (Key::ArrowLeft, egui::vec2(-1.0, 0.0)),+ (Key::ArrowRight, egui::vec2(1.0, 0.0)),+ (Key::ArrowUp, egui::vec2(0.0, -1.0)),+ (Key::ArrowDown, egui::vec2(0.0, 1.0)),+ ] {+ // Shift first: a plain key pattern also matches a Shift press.+ if i.consume_key(Modifiers::SHIFT, key) {+ step += direction * 10.0;+ } else if i.consume_key(Modifiers::NONE, key) {+ step += direction;+ }+ }+ });+ if step == egui::Vec2::ZERO {+ return;+ }+ // A point in view space whatever the zoom and whatever way the view is turned; the page's own+ // rotation turns it into the user-space move the widget's rect is stored in.+ let c = xf.rect.center();+ let unit = |d: egui::Vec2| {+ let (a, b) = (xf.screen_to_view(c), xf.screen_to_view(c + d));+ let v = egui::vec2(b.0 - a.0, b.1 - a.1);+ if v.length() > 0.0 { v / v.length() } else { egui::Vec2::ZERO }+ };+ let delta = unit(egui::vec2(1.0, 0.0)) * step.x + unit(egui::vec2(0.0, 1.0)) * step.y;+ let Ok(offset) = doc.object_move_offset(page, [f64::from(delta.x), f64::from(delta.y)]) else { return };+ let r = w.rect;+ let rect = [r[0] + offset[0], r[1] + offset[1], r[2] + offset[0], r[3] + offset[1]];+ view.pending_edit = Some(Edit::SetFieldProps { name, props: Box::new(FieldProps { rect: Some((wi, rect)), ..Default::default() }) });+ }++ /// Delete removes the selected fields; Escape clears the selection.+ pub(crate) fn select_all(view: &mut DocView, form: &[FormField]) {+ let mut selected =+ form.iter().flat_map(|f| f.widgets.iter().enumerate().filter(|(_, w)| w.page == Some(view.current)).map(|(wi, _)| (f.name.clone(), wi)));+ view.prepare.selected = selected.next();+ view.prepare.also = selected.collect();+ }++ fn cancel_marquee(prep: &mut PrepareView) {+ prep.grab = None;+ prep.ignore_release = true;+ if let Some(before) = prep.marquee_before.take() {+ let mut before = before.into_iter();+ prep.selected = before.next();+ prep.also = before.collect();+ }+ }++ pub(crate) fn keys(ctx: &egui::Context, view: &mut DocView) {+ if ctx.egui_wants_keyboard_input() {+ return;+ }+ if view.prepare.marquee_before.is_some() && ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape)) {+ cancel_marquee(&mut view.prepare);+ return;+ }+ if view.prepare.selected.is_none() {+ return;+ }+ let (del, esc) = ctx.input(|i| (i.key_pressed(egui::Key::Delete) || i.key_pressed(egui::Key::Backspace), i.key_pressed(egui::Key::Escape)));+ if del {+ view.pending_edit = delete_selected(view);+ } else if esc {+ view.prepare.selected = None;+ view.prepare.also.clear();+ }+ }++ /// After an Add field edit: select the new field (the form's last).+ pub(crate) fn after_refresh(view: &mut DocView, form: &[FormField]) {+ view.prepare.also.retain(|(name, wi)| form.iter().any(|f| &f.name == name && *wi < f.widgets.len()));+ if let Some(n) = view.prepare.select_added.take() {+ if form.len() > n+ && let Some(f) = form.last()+ {+ view.prepare.selected = Some((f.name.clone(), 0));+ } else if let Some((name, _)) = &view.prepare.selected+ && let Some(f) = form.iter().find(|f| &f.name == name)+ {+ // A radio button joined the selected group: select the new button.+ view.prepare.selected = Some((f.name.clone(), f.widgets.len().saturating_sub(1)));+ }+ }+ if let Some((name, wi)) = &view.prepare.selected+ && !form.iter().any(|f| &f.name == name && *wi < f.widgets.len())+ {+ view.prepare.selected = None;+ }+ }++ #[cfg(test)]+ mod tests {+ use egui::pos2;++ use super::*;++ #[test]+ fn corner_drags_stretch_freely_and_keep_proportions_with_shift() {+ let r = Rect::from_min_max(pos2(100.0, 100.0), pos2(196.0, 132.0));+ let free = dragged(r, Grab::Corner(false, false), vec2(24.0, 0.0), false);+ assert_eq!(free, Rect::from_min_max(pos2(100.0, 100.0), pos2(220.0, 132.0)));+ for (left, top) in [(true, true), (false, true), (true, false), (false, false)] {+ let d = vec2(if left { -48.0 } else { 48.0 }, 0.0);+ let out = dragged(r, Grab::Corner(left, top), d, true);+ assert!((out.width() / out.height() - 3.0).abs() < 0.001, "{left} {top}: {out:?}");+ // The opposite corner stays put.+ assert_eq!(if left { out.max.x } else { out.min.x }, if left { r.max.x } else { r.min.x });+ assert_eq!(if top { out.max.y } else { out.min.y }, if top { r.max.y } else { r.min.y });+ }+ assert_eq!(dragged(r, Grab::Move, vec2(5.0, 6.0), true), r.translate(vec2(5.0, 6.0)));+ }+ }diff --cc crates/ui-egui/src/tools/redact_ui.rsindex 52cadc2aa,99974787f..e5c2ac06e--- a/crates/ui-egui/src/tools/redact_ui.rs+++ b/crates/ui-egui/src/tools/redact_ui.rs@@@ -7,9 -7,7 +7,8 @@@ use egui::{Color32, CornerRadius, Pos2use pdfcraft_engine::{Edit, NewAnnotation, REDACT_PATTERNS, REDACTION_CODE_SETS, RedactPattern, RedactionCodeSet, Rgb, Shape, Style, rect_quad};use pdfcraft_render::DocInfo;- use crate::canvas::{DocView, PageXform};+ use crate::canvas::{DocView, PageToolContext, PageXform};+use crate::page_cursor::Layer;- use crate::page_pointer::PagePointer;use crate::theme::Tokens;use crate::{PdfCraftApp, widgets};@@@ -236,16 -234,8 +235,8 @@@ fn to_user(xf: &PageXform, info: &DocIn/// 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 elsewhere draw a box. Returns `true` when/// the gesture is a box.- #[allow(clippy::too_many_arguments)]- pub(crate) fn page_input(- resp: &egui::Response,- xf: &PageXform,- ptr: &PagePointer,- page: usize,- info: &DocInfo,- over_text: impl Fn(Pos2) -> bool,- view: &mut DocView,- ) -> bool {+ pub(crate) fn page_input(cx: PageToolContext<'_>, over_text: impl Fn(Pos2) -> bool, view: &mut DocView) -> bool {- let PageToolContext { ui, resp, xf, ptr, page, info, .. } = cx;++ let PageToolContext { resp, xf, ptr, page, info, .. } = cx;let pointer = ptr.pos;if let Some((dp, start)) = view.redact_drag&& dp == pagediff --cc crates/ui-egui/tests/it/signing.rsindex b37f134a1,0d8bc72de..4f7ec44bc--- a/crates/ui-egui/tests/it/signing.rs+++ b/crates/ui-egui/tests/it/signing.rs@@@ -373,41 -399,11 +411,41 @@@ fn sign_the_empty_field(h: &mut Harnessd.password = "test".into();}h.run_steps(2);- h.get_by_label("Sign").click();- support::outside_menus(&h, "Sign").click();++ support::outside_menus(h, "Sign").click();h.run_steps(6);- let s = h.state();- let sig = s.session.get(s.views[1].id).unwrap().signatures.iter().find(|x| x.field == "Approver").cloned().unwrap();- assert!(sig.signed && sig.visible);+}++/// Whether the page's hover tip shows and says `text`.+fn tip_says(h: &Harness<'static, PdfCraftApp>, text: &str) -> bool {+ let layer = egui::LayerId::new(egui::Order::Tooltip, egui::Id::unique("canvas-hover"));+ let Some(tip) = h.ctx.memory(|m| m.area_rect(egui::Id::unique("canvas-hover")).filter(|_| m.areas().is_visible(&layer))) else { return false };+ h.query_all_by_label_contains(text).any(|n| tip.contains(n.rect().center()))+}++/// A signed field's validation badge is the viewer's own mark, not part of the page: its verdict+/// is the tip with any tool, beside that tool's cursor.+#[test]+fn a_signature_badge_says_its_verdict_with_any_tool() {+ let dir = dir().join("badge");+ std::fs::create_dir_all(&dir).unwrap();+ let mut h = harness(dir.clone());+ sign_the_empty_field(&mut h);+ let verdict = {+ let s = h.state();+ let sig = s.session.get(s.views[1].id).unwrap().signatures.iter().find(|x| x.field == "Approver").cloned().unwrap();+ sig.summary()+ };+ let p = field_centre(&h);+ let hover = |h: &mut Harness<'static, PdfCraftApp>, tool: QuickTool, at: Pos2| {+ h.state_mut().quick_tool = tool;+ h.run_steps(4);+ h.hover_at(at);+ h.run_steps(4);+ (h.output().platform_output.cursor_icon, tip_says(h, verdict))+ };+ assert!(hover(&mut h, QuickTool::Select, p).1, "the Select tool shows the verdict");+ let stamp = QuickTool::Stamp(pdfcraft_engine::StampKind::DynApproved);+ assert_eq!(hover(&mut h, stamp, p + egui::vec2(1.0, 0.0)), (egui::CursorIcon::Crosshair, true), "so does a stamp, beside its crosshair");}#[test]