diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 5ef59e76aa..207859a350 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -1,108 +1,70 @@ -//! The document area: page layout, zoom, render scheduling, overlays (links, annotation hovers, -//! form-field highlights), and the organize-pages grid. +//! The document area: a document tab's notice bars, then its pages in the framework's page view (or the Organize +//! grid), with the page body that registers what is on the pages, runs the page tools and paints the overlays, and +//! what the pass asked the app to do. //! -//! Page images come from the engine's render pool as whole-page rasters at the current zoom; -//! stale rasters are shown stretched until the sharp one arrives (tiling comes in M3.3). +//! Page pictures come from the page view's texture stores over [`pictures::DocPages`]; the app holds no raster. -use std::collections::{BTreeSet, HashMap, HashSet}; -use std::ops::Range; +use std::collections::{HashMap, HashSet}; use std::sync::Arc; -use egui::{Align2, Color32, CornerRadius, Pos2, Rect, Sense, Stroke, TextureHandle, TextureOptions, Vec2, pos2, vec2}; +use craft::behavior::{CanvasView, PointerButton, PressPhase, Selection}; +use craft::pages::ui::{PageBody, PageView, PageViewOutput, PageViewState, PlacedPage, TextMark, TextMarks, TextSelectState, TextSelection}; +use craft::host::queue::{JobQueue, QueueOptions}; +use craft::ui::canvas::{ContextRequest, Momentary, NavigationOptions, PageBorder, ToolHost}; +use craft::ui::contract::Show as _; +use craft::ui::display::Text; +use craft::ui::list::OpenSet; +use craft::ui::primitives::TextureStatistics; +use craft::ui::style::DataColor; +use egui::{Color32, Rect}; use pdfcraft_engine::text_links::TextLink; use pdfcraft_engine::{DocId, Edit}; -use pdfcraft_render::{DestView, DocInfo, LayerOp, LinkTarget, PRINT_TAG, PageText, RenderPool, RenderRequest, RequestKind, Tile, device_pixels}; +use pdfcraft_render::{DocInfo, LinkTarget, PageText}; -use crate::page_cursor::Layer; -use crate::page_pointer::PagePointer; -use crate::theme::{self, Tokens}; -use crate::{PdfCraftApp, QuickTool, RightPanel, comments, icons, widgets}; +use crate::{PdfCraftApp, QuickTool, RightPanel, comments}; mod area; -pub(crate) mod autoscroll; pub(crate) 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; -mod page_input; -pub(super) mod page_keys; -pub(super) mod page_pointer; -pub(super) mod page_router; +// PLAN: no sheet assigns the `mod` lines of the four new page-body files (pdf-canvas-w9 `page_parts.rs`, +// `page_tools.rs`; pdf-canvas-w10 `pictures.rs`; pdf-canvas-w15 `page_overlays.rs`); the host writes them here. +pub(crate) mod page_overlays; +pub(crate) mod page_parts; +pub(crate) mod page_tools; +pub(crate) mod pictures; mod presenter; pub mod scroll_speed; mod selection; pub(super) mod signature_drag; -pub(super) mod wheel_boost; -pub(super) mod wheel_pager; -pub(super) mod wheel_reset; mod xform; mod zoom; pub(super) mod zoom_snap; pub(crate) use area::SignTab; pub(crate) use area::signature_badges; -use area::{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 area::signature_states_changed; +use area::{run_button, set_layers}; +use bars::{Notice, notices, page_size_hint}; 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 craft::pages::{Fit, PageDisplay, PageSpacing, ViewDefaults, display_token, parse_display_token}; pub use find::Find; use find::find_bar; -pub(crate) 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; -pub(crate) use page_input::PageToolContext; -use page_input::{PageInput, cancel_on_escape, page_overlays, page_tool_input, text_layer}; -use selection::{Selection, Span, click_unit, selection_actions, start_selection_drag}; -pub(crate) use selection::{TextSpan, ToolMarks}; +use page_menu::{FieldMenu, PageMenuAction}; +use page_overlays::{LinkEvent, LinkMode, PageLinks, PageOverlays, overlay_parts}; +use page_parts::{Owner, PagePart, PageParts, PagePress}; +use page_tools::{PageToolCx, page_tool}; +use pictures::{DocPages, PageRevisions, RenderReports}; +pub(crate) use selection::ToolMarks; 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; -const MARGIN: f32 = 28.0; -/// Horizontal gutter that keeps pages clear of the floating quick-action bar. -const SIDE: f32 = 70.0; - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum Fit { - Width, - Page, - Height, - None, -} - -use crate::edit_text_ui::ImageHandle; - -/// Extension trait on `egui::Painter` to draw polygons. -pub trait PainterExt { - fn polygon(&self, points: Vec, fill: Color32, stroke: Stroke) -> egui::layers::ShapeIdx; -} - -impl PainterExt for egui::Painter { - fn polygon(&self, points: Vec, fill: Color32, stroke: Stroke) -> egui::layers::ShapeIdx { - self.add(egui::Shape::convex_polygon(points, fill, stroke)) - } -} /// User-space editing frame: explicit PDF/editor crops apply, but the page edge does not /// truncate a selected image's handles. Body hit testing still respects page visibility. @@ -115,273 +77,22 @@ pub fn image_screen_rect(im: &pdfcraft_engine::PageImage, xf: &PageXform, info: xf.user_rect_f64(info, page, image_selectable_bounds(im)) } -/// An Oriented Bounding Box (OBB) representing a rotated rectangle in screen space, -/// with 8 resize handles and rotated local axes. -#[derive(Clone, Copy, Debug, PartialEq)] -pub struct ImageObb { - pub s00: Pos2, - pub s10: Pos2, - pub s11: Pos2, - pub s01: Pos2, - pub s_bc: Pos2, - pub s_rc: Pos2, - pub s_tc: Pos2, - pub s_lc: Pos2, - pub s_rot: Pos2, - pub screen_center: Pos2, - pub u_axis: (f64, f64), - pub v_axis: (f64, f64), - pub is_rotated: bool, -} - -impl ImageObb { - pub(crate) fn handle_cursor(&self, handle: ImageHandle) -> egui::CursorIcon { - let direction = self.handle_pos(handle) - self.screen_center; - match handle { - ImageHandle::TopLeft | ImageHandle::TopRight | ImageHandle::BottomLeft | ImageHandle::BottomRight => { - if direction.x * direction.y > 0.0 { - egui::CursorIcon::ResizeNwSe - } else { - egui::CursorIcon::ResizeNeSw - } - } - _ if direction.x.abs() > direction.y.abs() => egui::CursorIcon::ResizeHorizontal, - _ => egui::CursorIcon::ResizeVertical, - } - } - - pub(crate) fn contains(&self, visible: Rect, p: Pos2) -> bool { - (visible.is_positive() && visible.contains(p)) || crate::edit_text_ui::quad_contains(self.corners(), p) - } - - pub fn from_matrix(matrix: [f64; 6], xf: &PageXform, info: &DocInfo, page: usize) -> Self { - let m = crate::edit_text_ui::Matrix(matrix); - let p00 = m.apply(0.0, 0.0); - let p10 = m.apply(1.0, 0.0); - let p11 = m.apply(1.0, 1.0); - let p01 = m.apply(0.0, 1.0); - - let s00 = crate::edit_text_ui::user_to_screen(xf, info, page, p00.0, p00.1); - let s10 = crate::edit_text_ui::user_to_screen(xf, info, page, p10.0, p10.1); - let s11 = crate::edit_text_ui::user_to_screen(xf, info, page, p11.0, p11.1); - let s01 = crate::edit_text_ui::user_to_screen(xf, info, page, p01.0, p01.1); - - let s_bc = Pos2::new((s00.x + s10.x) * 0.5, (s00.y + s10.y) * 0.5); - let s_rc = Pos2::new((s10.x + s11.x) * 0.5, (s10.y + s11.y) * 0.5); - let s_tc = Pos2::new((s01.x + s11.x) * 0.5, (s01.y + s11.y) * 0.5); - let s_lc = Pos2::new((s00.x + s01.x) * 0.5, (s00.y + s01.y) * 0.5); - - let screen_center = Pos2::new((s00.x + s10.x + s11.x + s01.x) * 0.25, (s00.y + s10.y + s11.y + s01.y) * 0.25); - let out_dir = s_tc - screen_center; - let out_len = out_dir.length().max(1e-4); - let out_norm = out_dir / out_len; - let s_rot = s_tc + out_norm * 24.0; - - let [a, b, c, d, ..] = matrix; - let w_u = (a * a + b * b).sqrt().max(1e-6); - let h_v = (c * c + d * d).sqrt().max(1e-6); - let u_axis = (a / w_u, b / w_u); - let v_axis = (c / h_v, d / h_v); - // The fast rectangle path interprets labels in screen space. Use matrix - // resizing whenever the image's user-space axes are turned or reflected - // on screen, including page /Rotate and View > Rotate View. - let u = s10 - s00; - let v = s01 - s00; - let is_rotated = u.y.abs() > 1e-4 || v.x.abs() > 1e-4 || u.x < 0.0 || v.y > 0.0; - - Self { s00, s10, s11, s01, s_bc, s_rc, s_tc, s_lc, s_rot, screen_center, u_axis, v_axis, is_rotated } - } - - pub fn from_image(im: &pdfcraft_engine::PageImage, xf: &PageXform, info: &DocInfo, page: usize) -> Self { - let [a, b, c, d, ..] = im.matrix; - let is_rot = b.abs() > 1e-4 || c.abs() > 1e-4 || a < 0.0 || d < 0.0; - let bounds = image_selectable_bounds(im); - let matrix = if !is_rot && bounds[2] > bounds[0] && bounds[3] > bounds[1] { - [bounds[2] - bounds[0], 0.0, 0.0, bounds[3] - bounds[1], bounds[0], bounds[1]] - } else { - im.matrix - }; - Self::from_matrix(matrix, xf, info, page) - } - - pub fn handles(&self) -> [(ImageHandle, Pos2); 8] { - [ - ImageHandle::TopLeft, - ImageHandle::TopCenter, - ImageHandle::TopRight, - ImageHandle::RightCenter, - ImageHandle::BottomRight, - ImageHandle::BottomCenter, - ImageHandle::BottomLeft, - ImageHandle::LeftCenter, - ] - .map(|h| (h, self.handle_pos(h))) - } - - pub fn handle_pos(&self, handle: ImageHandle) -> Pos2 { - match handle { - ImageHandle::TopLeft => self.s01, - ImageHandle::TopCenter => self.s_tc, - ImageHandle::TopRight => self.s11, - ImageHandle::RightCenter => self.s_rc, - ImageHandle::BottomRight => self.s10, - ImageHandle::BottomCenter => self.s_bc, - ImageHandle::BottomLeft => self.s00, - ImageHandle::LeftCenter => self.s_lc, - } - } - - pub fn corners(&self) -> [Pos2; 4] { - [self.s00, self.s10, self.s11, self.s01] - } -} - /// The page display as it was before full screen, put back on leaving it /// ([`DocView::enter_presentation`]). #[derive(Clone, Copy, Debug, PartialEq)] pub struct SavedDisplay { - pub layout: PageLayout, + /// Single pages, two-up spreads or columns. + pub display: PageDisplay, + /// Whether the pages scrolled continuously. pub continuous: bool, + /// Whether two-page spreads started with the first page alone. pub cover: bool, + /// The fit the view had. pub fit: Fit, - pub zoom: f32, + /// The zoom the view had (1.0 = 100%). + pub zoom: f64, } -/// The base page display: one page across, or a two-page spread. Whether it scrolls continuously -/// is a separate flag (`continuous`), as in Acrobat, so every combination is reachable (#752). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum PageLayout { - Single, - TwoUp, -} - -impl PageLayout { - /// The base page displays, in the order the View menu, the rail's Page display button and - /// Preferences list them. - pub const ORDER: [Self; 2] = [Self::Single, Self::TwoUp]; - - /// The name settings and view options use for the base layout: `single` or `two-up`. - pub fn as_str(self) -> &'static str { - match self { - Self::Single => "single", - Self::TwoUp => "two-up", - } - } - - /// The base layout an [`as_str`](Self::as_str) name stands for, in any case. `None` for - /// anything else, so callers can reject a typo rather than switch layouts silently. - pub fn try_parse(value: &str) -> Option { - Self::ORDER.into_iter().find(|l| l.as_str().eq_ignore_ascii_case(value.trim())) - } - - /// Rail icon for this layout. - pub fn icon(self) -> &'static str { - match self { - Self::Single => "file-text", - Self::TwoUp => "columns-2", - } - } - - /// Registry command that switches to this base layout (`PdfCraftApp::execute`). - pub fn command(self) -> &'static str { - match self { - Self::Single => "view.layout.single", - Self::TwoUp => "view.layout.two_up", - } - } - - /// The base layout a [`command`](Self::command) id switches to. - pub fn from_command(id: &str) -> Option { - Self::ORDER.into_iter().find(|l| l.command() == id) - } - - /// Menu label: the label of [`command`](Self::command), which the catalogs translate. - pub fn label(self) -> &'static str { - match self { - Self::Single => "Single page", - Self::TwoUp => "Two-page view", - } - } -} - -/// The single page-display token settings and the control channel use, combining the base layout -/// with continuous scrolling. `single` and `two-page` show one page or one spread at a time; -/// `continuous` (Single, scrolling) and `two-up` (Two-page, scrolling) keep their earlier names -/// for back-compat. -pub fn display_token(layout: PageLayout, continuous: bool) -> &'static str { - match (layout, continuous) { - (PageLayout::Single, false) => "single", - (PageLayout::Single, true) => "continuous", - (PageLayout::TwoUp, true) => "two-up", - (PageLayout::TwoUp, false) => "two-page", - } -} - -/// The base layout and continuous flag a [`display_token`] names, in any case. `None` for a typo. -pub fn parse_display_token(value: &str) -> Option<(PageLayout, bool)> { - match value.trim().to_ascii_lowercase().as_str() { - "single" => Some((PageLayout::Single, false)), - "continuous" => Some((PageLayout::Single, true)), - "two-up" => Some((PageLayout::TwoUp, true)), - "two-page" | "two-up-single" => Some((PageLayout::TwoUp, false)), - _ => None, - } -} - -/// How a newly opened document is shown (Preferences ▸ Documents and view). A PDF that asks -/// for its own layout or zoom gets that instead. -#[derive(Clone, Copy, Debug, PartialEq)] -pub struct ViewDefaults { - pub layout: PageLayout, - /// Whether the base layout scrolls continuously. - pub continuous: bool, - /// Separate pages with a gutter and shadow; off joins adjacent page edges. - pub show_page_gaps: bool, - /// [`Fit::Width`] or [`Fit::Page`], or [`Fit::None`] for a fixed `zoom`. - pub fit: Fit, - /// The zoom with [`Fit::None`] (1.0 = 100%). - pub zoom: f32, - /// Highlight existing fields: a preference in Acrobat, so it carries over to the next - /// document and the next session. On for new settings; a stored choice wins. - pub highlight_fields: bool, -} - -impl Default for ViewDefaults { - fn default() -> Self { - // Single page, scrolling continuously at fit width: the earlier "continuous" default. - Self { layout: PageLayout::Single, continuous: true, show_page_gaps: true, fit: Fit::Width, zoom: 1.0, highlight_fields: true } - } -} - -impl ViewDefaults { - /// The zoom as settings and view options name it: `fit-width`, `fit-page` or a percentage. - pub fn zoom_name(&self) -> String { - match self.fit { - Fit::Page => "fit-page".into(), - Fit::None => format!("{}%", (self.zoom * 100.0).round()), - Fit::Width | Fit::Height => "fit-width".into(), - } - } - - /// These defaults with the zoom a [`zoom_name`](Self::zoom_name) names, in any case. `None` - /// for anything else, including a percentage outside the 8–6400% the view can show. - pub fn with_zoom(self, name: &str) -> Option { - let name = name.trim(); - let (fit, zoom) = if name.eq_ignore_ascii_case("fit-width") { - (Fit::Width, self.zoom) - } else if name.eq_ignore_ascii_case("fit-page") { - (Fit::Page, self.zoom) - } else { - let percent = name.strip_suffix('%').unwrap_or(name).trim().parse::().ok().filter(|p| (8.0..=6400.0).contains(p))?; - (Fit::None, percent / 100.0) - }; - Some(Self { fit, zoom, ..self }) - } -} - -/// A historical snapshot opened from another document: View signed version opens the bytes -/// a signature covers, View revision an earlier incremental revision. Repeats reuse the tab, -/// and the tab and notice bar name what it is, instead of piling up identical tabs. /// What a historical snapshot shows: the bytes a signature covers, or an earlier /// incremental revision. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -390,6 +101,9 @@ pub enum SnapshotKind { Revision, } +/// A historical snapshot opened from another document: View signed version opens the bytes +/// a signature covers, View revision an earlier incremental revision. Repeats reuse the tab, +/// and the tab and notice bar name what it is, instead of piling up identical tabs. #[derive(Clone, Debug)] pub struct Snapshot { pub kind: SnapshotKind, @@ -399,63 +113,6 @@ pub struct Snapshot { pub from: String, } -/// Whether what the pages show of the signatures differs between `before` and `after`: a verdict, -/// or whether a signature's appearance draws it. -pub(crate) fn signature_states_changed(before: &[pdfcraft_engine::SignatureInfo], after: &[pdfcraft_engine::SignatureInfo]) -> bool { - before.len() != after.len() - || before.iter().zip(after).any(|(b, a)| b.field != a.field || b.status != a.status || b.verdict_shown != a.verdict_shown) -} - -/// The mark's side as a share of the widget's shorter side. -const MARK_SIDE_SHARE: f32 = 0.25; - -/// The largest side of the mark, in screen points, so zooming in stops enlarging it. -const MARK_SIDE_MAX: f32 = 48.0; - -/// The smallest legible side of the mark, in screen points: a widget whose shorter side is under -/// `MARK_SIDE_MIN / MARK_SIDE_SHARE` (32 points) keeps only its outline. A field over that at 100% -/// can fall under it when the page is zoomed out to fit. -const MARK_SIDE_MIN: f32 = 8.0; - -/// The gap between the mark and the widget's edges, as a share of the mark's side. -const MARK_INSET_SHARE: f32 = 0.2; - -/// The icon's size as a share of the mark's side; the icon is centred in it. -const MARK_ICON_SHARE: f32 = 0.64; - -/// The screen position of a widget's bottom-right corner on the page (`rect`, user space): where -/// its validation mark goes, wherever the page's /Rotate and the view turn it. -fn mark_anchor(xf: &PageXform, info: &DocInfo, page: usize, rect: [f64; 4]) -> Pos2 { - let [_, bottom, right, _] = rect.map(|v| v as f32); - xf.user_rect(info, page, [right, bottom, right, bottom]).min -} - -/// Where the validation mark sits in the part of a signature widget's screen rectangle that is on -/// the page (`page`, on screen too), or `None` when that part is too small for a legible one. It -/// goes in the corner nearest `anchor`, the screen position of the widget's bottom-right corner on -/// the page, so it turns with the page and the view: off the middle, where a signer's artwork -/// usually is, and clear of the state a named-layer appearance captions across its top. -fn verdict_mark_rect(widget: Rect, page: Rect, anchor: Pos2) -> Option { - // A NaN or infinite corner has no place on screen. - if !widget.is_finite() { - return None; - } - // A widget past the crop box's edge shows its mark on the page, not beside it. - let widget = widget.intersect(page); - let side = (widget.width().min(widget.height()) * MARK_SIDE_SHARE).min(MARK_SIDE_MAX); - // Also refuses the negative side of an inverted rectangle. - if !(MARK_SIDE_MIN..).contains(&side) { - return None; - } - let inset = side * MARK_INSET_SHARE; - // A NaN anchor compares false either way and takes the bottom-right corner. - let left = anchor.x - widget.min.x < widget.max.x - anchor.x; - let top = anchor.y - widget.min.y < widget.max.y - anchor.y; - let x = if left { widget.min.x + inset } else { widget.max.x - inset - side }; - let y = if top { widget.min.y + inset } else { widget.max.y - inset - side }; - Some(Rect::from_min_size(pos2(x, y), vec2(side, side))) -} - /// The name shown for a document tab, the window title and the Combine picker. /// A snapshot reads like its source document, plus the snapshot suffix that tells /// the tabs apart. Without a title the file name (which already carries the suffix) @@ -483,6 +140,10 @@ pub(crate) fn snapshot_tab_name(title: &str, file_name: &str, snapshot: &Snapsho /// Markup quadrilaterals in user space, one entry per page: (page, quads). pub type PageMarks = Vec<(usize, Vec<[f64; 8]>)>; +/// One document tab: what the page view shows ([`PageViewState`]), the data its page source reads, the records the +/// last pass left for readers between frames, and the [`PageSession`] the page body works on. +/// +/// The three are separate fields so the page view can hold `&mut view` while the page body holds `&mut session`. pub struct DocView { /// Where the tab shows (split view's panes) and the key that tells two /// views of one document apart (`crate::panes`). @@ -491,17 +152,32 @@ pub struct DocView { /// The document and attached file this tab was opened from, when a form or the Attachments /// panel opened it: asking for that attachment again comes back to this tab. pub from_attachment: Option<(DocId, String)>, - pub zoom: f32, - pub fit: Fit, - pub layout: PageLayout, - /// Whether the base layout scrolls continuously (independent of `layout`, as in Acrobat). - pub continuous: bool, - pub show_page_gaps: bool, - /// View rotation in degrees clockwise (0, 90, 180, 270); display only, never saved. - pub rotation: u16, - pub current: usize, + /// What the page view shows: the page, display, zoom, fit, rotation and scroll offset. + pub view: PageViewState, + /// Everything the page body touches: the tools' and editors' state, the text selection, the pages placed. + pub session: PageSession, + /// The momentary tools (Space for the Hand, with Cmd or Alt the Zoom), held across passes by the tool host. + pub(crate) momentary: Momentary, + /// The navigation options `momentary` was made with: its Hand and Zoom tools keep them, so a change of the user's + /// options makes it again. + momentary_options: NavigationOptions, + /// Each page's picture revision, which the page source stamps its renders with. + pub(crate) revisions: PageRevisions, + /// Pages the renderer could not draw or cut at its limits, written by the render jobs. + pub(crate) reports: RenderReports, + /// What the page view's picture stores held and did in the last pass (written by [`document_area_at`]), for + /// automation between frames. No pass reads it to compute its result. + pub textures: TextureStatistics, + /// The spacing the last pass laid the pages out with (written by [`document_area_at`]); `None` before the first. + // PLAN: `PageSpacing` has no default (it comes from the page view's tokens), so the record is an `Option`. + pub spacing: Option, + /// The document area on screen in the last pass (written by [`document_area_at`]). + viewport: Rect, + /// The canvas view of the last pass (written by [`document_area_at`]), for the zoom field between frames. + canvas: Option, + /// A latched or held middle-button scroll ran in the last pass (written by [`document_area_at`]). + middle_scrolling: bool, pub organize: bool, - pub highlight_fields: bool, pub page_input: String, /// Select the replacement page label once if its editor remains focused. pub(crate) page_input_reselect: bool, @@ -516,130 +192,21 @@ pub struct DocView { pub close_requested: bool, /// A historical snapshot of another document (see [`Snapshot`]): `None` for real documents. pub snapshot: Option, - /// Two-page view: show the first page alone, as a cover (View ▸ Page display). - pub cover: bool, /// Previous view / Next view: pages visited before (and after, once going back). pub back: Vec, pub forward: Vec, - /// Pending navigation: page and fraction down the page to align with the viewport top. - pub goto: Option<(usize, f32)>, - /// With `goto`: → / ← turned the page at an edge, so a page or spread wider than the window - /// starts at the edge the reader comes from (`false`: its left, after →; `true`: its right, - /// after ←) instead of keeping the column. - pub(crate) goto_side: Option, - /// Pending position within that page from a destination ([`Self::go_to_dest`]): the point - /// (fractions of the displayed page; `None` leaves that axis to `goto`) to put `rel` points - /// from the viewport's top-left corner. - goto_point: Option<(usize, Option, Option, Vec2)>, - /// Pending keyboard scrolling, in points down (negative: up): ↓ / ↑, and Page Down / - /// Page Up where the pages scroll. - pub key_scroll: f32, - /// Pending keyboard scrolling sideways, in points right (negative: left): → / ← on a page - /// wider than the window. - pub key_side: f32, - /// As last drawn: whether the view was at its left and at its right edge (both when the - /// pages fit across), so → / ← turn the page there and scroll sideways elsewhere. - side_edges: Option<(bool, bool)>, - /// Single-page view, as last drawn: the page shown and whether the view was at its top and - /// at its bottom, so ↑ / ↓ turn the page there instead of doing nothing (#273). - single_edges: Option<(usize, bool, bool)>, - /// Briefly outline an annotation after navigating to it from a panel. - pub flash: Option<(usize, [f32; 4], f64)>, - /// Compare files: differences shaded on this document's pages (page, user-space box, colour). - pub compare_marks: Vec<(usize, [f32; 4], Color32)>, /// The interface the document hid in this tab, and what is hidden now (ISO 32000-2 Table 147 /// `HideToolbar`, `HideMenubar`, `HideWindowUI`). Never saved. pub interface: crate::viewer_prefs::TabInterface, /// Full screen (Acrobat's Full Screen Mode): the display saved on entering it, while the view /// shows one page or spread at a time, fitted to the screen. `None` outside full screen. presentation: Option, - /// Full screen's transitions, display times and pointer (see [`presenter`]). - pub(crate) presenter: presenter::Presenter, - pages: HashMap, - /// Pages the renderer could not draw, with the reason (never re-requested). - errors: HashMap, - /// Pages whose content was cut at the renderer's limits (#623): drawn and searched in part. - cut_pages: std::collections::BTreeSet, /// Cut pages whose notice the reader dismissed: a page cut later shows it again. cut_notice_dismissed: std::collections::BTreeSet, - /// When each still-missing page was first shown, to flag unusually slow renders. - waiting_since: HashMap, - thumbs: HashMap, - /// This frame's consumers, with visible cells ahead of prefetch. - thumb_demand: HashMap, - frame_queue: Vec, - /// A page-list edit after layout invalidates this frame's scales and page indexes. - frame_geometry_changed: bool, - /// Pages on screen this frame. Their rasters and tiles are always admitted: the viewport - /// bounds them, and the byte and count limits apply to prefetch only. - frame_visible: HashSet, - /// Pages whose whole-page raster this frame asks for, on screen or prefetched. An arriving - /// raster over the allowance evicts the other cached pages first. - frame_demanded: HashSet, - /// Thumbnails that are out of date (still shown until their replacement arrives). - stale_thumbs: HashSet, - /// Tiles that are out of date (still shown until their replacement arrives). - stale_tiles: HashSet<(usize, u64, u32, u32)>, - /// Scale tag of the current zoom level, as last drawn. - current_scale_tag: u64, - /// Print dialog: the current sheet's pages at the preview pane's device resolution. - print_pages: HashMap, - /// Print dialog: preview rasters become luminance when Print ▸ Print in grayscale is on. - grayscale: bool, - /// Sharp tiles of large pages: (page, scale tag, tile x, tile y) → texture. Tiles of an - /// earlier zoom stay, drawn stretched, until those of the current one cover the page. - tiles: HashMap<(usize, u64, u32, u32), TextureHandle>, - /// Text layers, extracted in the background on demand (selection, find, copy). - pub(crate) texts: HashMap>, - /// Addresses written as plain text on a page (#4207), with the text layer they were found in. - text_links: HashMap, Arc<[TextLink]>)>, - pub(crate) text_failed: HashSet, pub find: Option, - selection: Option, - /// Select All while scrolling continuously (#2639): the text of every page of the document, - /// highlighted on each page as its text arrives and copied whole ([`DocView::whole_text`]). - pub(crate) all_text: bool, - /// The selection whose action bar was closed by its Copy button: the bar stays hidden - /// until the selection changes, as it does once a markup button consumes the selection. - actions_dismissed: Option, - /// The drag in progress started a text selection: the wheel scrolls the page during it - /// (#721), which egui's scroll area refuses while anything is dragged. - selection_drag: bool, - /// The frame a text-selection drag is released: `selection_drag` is already off, but the - /// pages still extend the selection to where it was let go. - selection_drag_ended: bool, - /// Clicks in the current run on the text layer: two select a word, three the line, four the page. - clicks: u32, - last_press_time: f64, - last_press_pos: Option, - /// Full screen: a click's page turn, when it falls due (input time) and which way. It waits - /// out the double-click time, as the click may be the first of a double-click selecting a word. - present_turn: Option<(f64, bool)>, - last_queue: Vec, - /// Finished renders wait in the pool instead of reaching the view (tests): what the view - /// shows before a raster arrives can be looked at however fast the renderer is. - pub hold_rasters: bool, - viewport_w: f32, - viewport_h: f32, page_count: usize, - /// Page sizes (width, height) in points (view space), for mapping text positions to scroll offsets. + /// Page sizes (width, height) in points (view space, unrotated by the view), for the page transforms. page_sizes: Vec<(f32, f32)>, - /// Screen rects of the pages drawn last frame (hit-testing, tests, automation). - screen_rects: Vec<(usize, Rect)>, - screen_xforms: Vec<(usize, PageXform)>, - /// Pixels per point last frame, for telling a rounding sliver of a page from a visible one. - screen_ppp: f32, - /// The scroll viewport on screen last frame. - viewport_screen: Rect, - /// Pending zoom anchor: page, fractional position (also in gutters), and viewport offset. - zoom_anchor: Option<(usize, f32, f32, Vec2)>, - /// The match a find step just went to: its page and its centre as fractions of the displayed - /// page. A zoom before the step has been laid out, or the rest of an eased ⌘-wheel zoom - /// still arriving, keeps it at the window's centre instead of the point under the pointer - /// (#3530). Let go in the first frame without a zoom gesture once the step is laid out. - find_hold: Option<(usize, f32, f32)>, - /// The page view has been shown, so its scroll offset in egui's memory is this document's. - shown: bool, /// Pages that Edit already tried to turn into editable text (once each, so Undo sticks). pub(crate) auto_ocr_tried: std::collections::HashSet, /// Pages Edit looked at and found not to be a scan, with the document's edit generation then: @@ -649,25 +216,104 @@ pub struct DocView { /// then: they wait for one (the web build downloads the models when first needed), and are /// read once the models are in (see `PdfCraftApp::ocr_models_loaded`) or the document changes. pub(crate) auto_ocr_awaiting_models: std::collections::HashMap, - /// Turns wheel input into page turns in single-page view. - wheel: crate::wheel_pager::WheelPager, - /// The document owns the full coarse-wheel distance, including its acceleration. - wheel_motion: crate::wheel_boost::Motion, - /// Raw input and retained motion advance once per frame, including discarded UI passes. - wheel_frame: Option, - /// Per-axis line-wheel state; horizontal input cannot extend a vertical burst. - wheel_boost_x: crate::wheel_boost::WheelBoost, - wheel_boost_y: crate::wheel_boost::WheelBoost, - /// Touchpad momentum after the fingers lift (#531). - fling: crate::fling::Fling, - pub(crate) auto_scroll: crate::autoscroll::AutoScroll, /// Pages selected in the organize grid or the Pages panel (0-based). Empty means "the current page". - pub selected: BTreeSet, - pub(crate) organize_range: crate::page_selection_ui::PageSelectionInput, - /// Anchor for ⇧-click range selection in the organize grid. - select_anchor: Option, + pub selected: Selection, + /// A non-edit action requested by the organize toolbar, handled by the app. + pub pending_action: Option, + /// The grid gap the next inserted files go to (set by a "+" between pages); otherwise they + /// go after the selection. + pub insert_at: Option, + /// The page-grid gap under the pointer this frame (where dropped files go), when it can + /// take pages. + pub grid_gap: Option, + /// The visible part of the Pages panel as last drawn, when it can take dropped files + /// (cleared each frame before the panels draw). + pub pages_panel: Option, + /// The Pages-panel gap under the pointer (where dropped files go), when it can take pages. + pub panel_gap: Option, + /// Transient keyboard owner for this document's Pages sidebar. + pub(crate) pages_focus_id: Option, + /// Scale of the thumbnails in the Pages inspector, independent of document and grid zoom. + thumbnail_zoom: f32, + /// The page the grid scrolls into view on its next pass (Organize just opened on it). + grid_reveal: Option, + /// The bookmarks open in the Bookmarks panel, by their path in the outline. + pub(crate) bookmarks_open: OpenSet>, + /// How many Apply redactions steps are in effect in this view. While it is above 0, Save + /// proposes the name with `_Redacted` ([`pdfcraft_engine::redacted_file_name`]), and while it is + /// above `redactions_downloaded`, Save asks where. + /// Undo of an Apply redactions step takes one off and Redo adds it back. Reload and a desktop + /// save set it to 0, and Revert sets it to `redactions_downloaded`; after a desktop save the document has the name it was saved + /// under. A web download keeps it, so later downloads carry the `_Redacted` name. + pub redactions_applied: usize, + /// How many Apply redactions steps saved into the document's file are undone in this view. + /// While it is above 0, Save asks where, so the restored content is not written over the + /// redacted file. Redo takes one off. Revert, Reload and a desktop save set it to 0. + pub redactions_undone_after_save: usize, + /// Set when Apply redactions runs while saved Apply redactions steps are undone: Redo can no + /// longer bring those steps back, so Save asks where until a desktop save or Revert clears it. + pub saved_redactions_cut_off: bool, + /// `redactions_applied` at the last web download, which Revert restores. While + /// `redactions_applied` is below it, a delivered step is undone and Save asks where. A desktop + /// save leaves it at 0. + pub redactions_downloaded: usize, + /// A queued Fill & Sign signature: select it after its edit succeeds, then leave placement. + pub(crate) fill_signature_page: Option, + /// The "Signature added … Lock now" notice was dismissed; placing another signature shows it + /// again (#2149). + pub(crate) lock_offer_dismissed: bool, +} + +/// What the page body works on: the pages placed this pass, the text selection, and the state of every tool, +/// editor and overlay drawn over the pages. The page body's functions take `&mut PageSession`, never the whole +/// [`DocView`], so the page view can hold the view state while they run. +pub struct PageSession { + /// The pages placed in the last run of the page body (this pass's while the body runs), with their pictures. + pub placed: Vec, + /// The text selection, and the selection gesture in progress. + pub text: TextSelectState, + /// Select All while scrolling continuously (#2639): the text of every page of the document, + /// highlighted on each page as its text arrives and copied whole ([`DocView::whole_text`]). + pub(crate) all_text: bool, + /// The selection whose action bar was closed by its Copy button: the bar stays hidden + /// until the selection changes, as it does once a markup button consumes the selection. + pub(crate) actions_dismissed: Option, + /// A marking tool finished this text selection while a page it covers was still to be read + /// (or none was drawn): it is marked once they are ([`DocView::tool_marks`]). + pub(crate) marks_waiting: Option<(QuickTool, TextSelection)>, + /// Text layers, extracted in the background on demand (selection, find, copy). + pub(crate) texts: HashMap>, + /// Addresses written as plain text on a page (#4207), with the text layer they were found in. + pub(crate) text_links: HashMap, Arc<[TextLink]>)>, + pub(crate) text_failed: HashSet, + /// The background jobs that extract text layers, made on the first pass that has the app's job host. + // PLAN: pdf-canvas-w10's `want_text` and `cache.rs` read `text_queue` as a `JobQueue`; they take this `Option` + // (`as_mut()`), since a `JobQueue` needs the host's jobs and `DocView::new` has none. + pub(crate) text_queue: Option>, + /// Highlight existing fields: the app's preference when the view was opened. + pub highlight_fields: bool, + /// Briefly outline an annotation after navigating to it from a panel. + pub flash: Option<(usize, [f32; 4], f64)>, + /// Compare files: differences shaded on this document's pages (page, user-space box, colour). + pub compare_marks: Vec<(usize, [f32; 4], Color32)>, + /// Full screen's transitions, display times, pointer and click turns (see [`presenter`]). + pub(crate) presenter: presenter::Presenter, /// An edit requested by the view (organize toolbar, keys), applied by the app this frame. pub pending_edit: Option, + /// Redact tool: the marks to add (page, quads) for the app to style, one per page (a text + /// selection can cover several), added in one undo step. + /// With the tool that made them, read when they are styled: a key handled later in the same + /// frame (Escape back to Select) must not turn an area highlight into a redaction. + /// The last field is the page the marks are followed up on (where a selection ended). + pub pending_redaction: Option<(QuickTool, PageMarks, usize)>, + /// A text selection Redact did not mark: it covers a page whose text could not be read + /// ([`ToolMarks::Unreadable`]). The app says so. + pub(crate) redaction_refused: bool, + /// The next edit applied is markup on a text selection across pages, one comment per page in + /// one batch ([`DocView::selection_marks_edit`]): `apply_edit` follows it up as one markup and + /// takes this back, whatever becomes of the edit. It holds the page the selection ends on, + /// whose markup is followed up. + pub(crate) marks_across_pages: Option, /// Edit text: the lines per page (with the document generation they were read at), and the /// line being edited. pub(crate) edit_lines: HashMap)>, @@ -695,9 +341,7 @@ pub struct DocView { pub(crate) pending_pick: Option<(usize, [f64; 2], u64)>, /// The pictures of the page last asked about. pub(crate) pictures: crate::image_pick::PagePictures, - /// A paragraph box being dragged (moved, or resized from its right edge) in Edit text. - pub block_drag: Option, - /// Commenting state: selected comment, gestures, composer. + /// Commenting state: selected comment, the comments tool, composer. pub comments: crate::comments::CommentView, pub measure: crate::measure_ui::MeasureView, /// Form filling state: the focused field. @@ -710,143 +354,77 @@ pub struct DocView { pub content: crate::content_ui::ContentView, /// Edit a PDF ▸ Link tool state. pub links: crate::link_ui::LinkView, - /// Redact tool: the box being drawn, and the marks to add (page, quads) for the app to style, - /// one per page (a text selection can cover several), added in one undo step. - pub redact_drag: crate::redact_ui::AreaDrag, - /// With the tool that made them, read when they are styled: a key handled later in the same - /// frame (Escape back to Select) must not turn an area highlight into a redaction. - /// The last field is the page the marks are followed up on (where a selection ended). - pub pending_redaction: Option<(QuickTool, PageMarks, usize)>, - /// How many Apply redactions steps are in effect in this view. While it is above 0, Save - /// proposes the name with `_Redacted` ([`pdfcraft_engine::redacted_file_name`]), and while it is - /// above `redactions_downloaded`, Save asks where. - /// Undo of an Apply redactions step takes one off and Redo adds it back. Reload and a desktop - /// save set it to 0, and Revert sets it to `redactions_downloaded`; after a desktop save the document has the name it was saved - /// under. A web download keeps it, so later downloads carry the `_Redacted` name. - pub redactions_applied: usize, - /// How many Apply redactions steps saved into the document's file are undone in this view. - /// While it is above 0, Save asks where, so the restored content is not written over the - /// redacted file. Redo takes one off. Revert, Reload and a desktop save set it to 0. - pub redactions_undone_after_save: usize, - /// Set when Apply redactions runs while saved Apply redactions steps are undone: Redo can no - /// longer bring those steps back, so Save asks where until a desktop save or Revert clears it. - pub saved_redactions_cut_off: bool, - /// `redactions_applied` at the last web download, which Revert restores. While - /// `redactions_applied` is below it, a delivered step is undone and Save asks where. A desktop - /// save leaves it at 0. - pub redactions_downloaded: usize, - /// A text selection Redact did not mark: it covers a page whose text could not be read - /// ([`ToolMarks::Unreadable`]). The app says so. - pub(crate) redaction_refused: bool, - /// The next edit applied is markup on a text selection across pages, one comment per page in - /// one batch ([`DocView::selection_marks_edit`]): `apply_edit` follows it up as one markup and - /// takes this back, whatever becomes of the edit. It holds the page the selection ends on, - /// whose markup is followed up. - pub(crate) marks_across_pages: Option, - /// A marking tool finished this text selection while a page it covers was still to be read - /// (or none was drawn): it is marked once they are ([`DocView::tool_marks`]). - marks_waiting: Option<(QuickTool, Selection)>, - /// A crop rectangle being dragged (Crop tool). - pub crop_drag: crate::crop::CropDrag, /// Enhance ▸ Camera image: the quadrilateral being placed. pub camera: Option, /// Enhance ▸ Camera image: the page just enhanced, while the bar offers rotate, crop and /// organize. pub camera_done: Option, - /// Use a certificate: a signature rectangle being drawn, or an empty signature field clicked. + /// Use a certificate: a signature rectangle drawn, or an empty signature field clicked. pub sign: crate::sign_ui::SignView, - /// Organize: the pages being dragged to a new place. - pub org_drag: Option>, - /// Pages panel: the pages being dragged to a new place. - pub panel_drag: Option>, - /// Transient keyboard owner for this document's Pages sidebar. - pub(crate) pages_focus_id: Option, - /// Marquee Zoom / Snapshot: the rectangle being dragged (page, start), and a finished one. - pub marquee: Option<(usize, Pos2)>, - pub marquee_done: Option, - /// Snapshot: the area just copied (page, view-space rect), kept with a small menu under it - /// (Print area…, Save as image…), and what was chosen there. + /// Snapshot: the area just copied (page, view-space rect), kept with a small bar under it + /// (Print area…, Save as image…). pub area_pick: Option<(usize, [f32; 4])>, - pub area_choice: Option, /// Fill & Sign text being typed. pub fill_text: Option, - /// A queued Fill & Sign signature: select it after its edit succeeds, then leave placement. - pub(crate) fill_signature_page: Option, - /// The "Signature added … Lock now" notice was dismissed; placing another signature shows it - /// again (#2149). - pub(crate) lock_offer_dismissed: bool, + /// The caret and selection in the Fill & Sign text being typed. + pub fill_selection: craft::text::ui::editor::TextSelection, pub(crate) signature_drag: crate::signature_drag::SignatureDrag, - /// What the page modules claim for the cursor this frame; `document_area` sets it once. - pub(crate) cursor: crate::page_cursor::PageCursor, - /// Who the press the pages hold belongs to. Only the page view reads it: it tells each page - /// module what the press is to its page (`PagePress`). - pub(in crate::canvas) router: crate::page_router::PageRouter, - /// What the last right-click on a page went to, and on which page (`None` off the pages, and for - /// Add text, which takes every right-click): the page's menu shows its entries when it has a menu - /// and is the one selected, or else the page's own. - pub(in crate::canvas) menu_for: Option<(usize, crate::page_router::Owner)>, - /// Escape cancelled the press the pages hold: the page ignores it until the button is up, so - /// its release neither clicks nor ends a drag. - pub(crate) press_cancelled: bool, - /// A non-edit action requested by the organize toolbar, handled by the app. - pub pending_action: Option, - /// The grid gap the next inserted files go to (set by a "+" between pages); otherwise they - /// go after the selection. - pub insert_at: Option, - /// The page-grid gap under the pointer this frame (where dropped files go), when it can - /// take pages. - pub grid_gap: Option, - /// The visible part of the Pages panel as last drawn, when it can take dropped files - /// (cleared each frame before the panels draw). - pub pages_panel: Option, - /// The Pages-panel gap under the pointer (where dropped files go), when it can take pages. - pub panel_gap: Option, - /// The current page the Pages panel last followed: it scrolls to the current page's - /// thumbnail only when the page changes. - pub(crate) panel_followed: Option, - /// Scale of the thumbnails in the Pages inspector, independent of document and grid zoom. - thumbnail_zoom: f32, - /// How large the page grid draws its pages (1.0 = the usual thumbnails). - grid_zoom: f32, - /// A zoom asked for this frame (toolbar, pinch, keys); the grid applies it once it has laid - /// out, so it can keep the same pages in view. - grid_zoom_request: Option, - /// The page to keep in place after a grid zoom, and how far below the top of the grid its - /// cell was. - grid_anchor: Option<(usize, f32)>, - /// The page the grid scrolls into view on its next frame (Organize just opened on it). - grid_reveal: Option, - /// Sharp renders of the pages the grid shows larger than a thumbnail: only those in view, - /// at the size drawn (device pixels wide). - grid_pages: HashMap, - /// Zoom-settle debounce for heavy pages: the last requested device scale, and the egui - /// time until which sharp whole-page/tile re-renders are held back. While the zoom is - /// still moving, every frame would otherwise cancel the in-flight full-page interpret - /// (seconds on image-heavy CAD plots) and start it over, so a sharp raster never - /// arrives. The stale raster stays on screen stretched meanwhile. - last_scale: f32, - sharp_hold_until: f64, - /// Pan-settle debounce for tiled pages: the scroll offset last frame, and the egui time - /// until which sharp tile re-renders are held back. Each tile costs a full page - /// interpret, so a drag would otherwise queue a storm of them (one per frame) while the - /// in-flight ones cannot be cancelled mid-operator. Older tiles and the backdrop stay - /// stretched meanwhile; fresh tiles go out once the pan settles. - pub(crate) last_scroll: Vec2, - /// The way the view last moved vertically: 1 down, -1 up, 0 before any move and after the - /// content's size changes (a zoom or a layout change). A jump to a page or a search result - /// counts as a move. It stays set while the view is still, so the pages prefetched ahead stay - /// in the render queue until they arrive. - scroll_dir: i8, - /// The content's size when `scroll_dir` was last updated. - scroll_content: Vec2, - /// Side-by-side compare: scroll to here this frame, following the other half. - pub(crate) sync_scroll: Option, - /// The page widget's id, by which the Hand tool finds its drag before the pages are laid out. - page_widget: Option, - pan_hold_until: f64, - /// Pages whose raster proved slow (see `SLOW_MILLIS`): only these get the zoom/pan - /// settle holds. Fast pages render straight through, with no added latency. - slow_pages: HashSet, + /// What the last secondary press on a page went to, and on which page (`None` off the pages): the page's menu + /// shows its entries when it has a menu and is the one selected, or else the page's own. + pub(crate) menu_for: Option<(usize, Owner)>, +} + +impl PageSession { + /// The session of a newly opened document. + fn new(info: &DocInfo, highlight_fields: bool) -> Self { + Self { + placed: Vec::new(), + text: TextSelectState::default(), + all_text: false, + actions_dismissed: None, + marks_waiting: None, + texts: HashMap::new(), + text_links: HashMap::new(), + text_failed: HashSet::new(), + text_queue: None, + highlight_fields, + flash: None, + compare_marks: Vec::new(), + presenter: Default::default(), + pending_edit: None, + pending_redaction: None, + redaction_refused: false, + marks_across_pages: None, + edit_lines: HashMap::new(), + grouped_text_click: None, + line_editor: None, + applied_editor: None, + pending_text_open: None, + text_background: Default::default(), + move_background: Default::default(), + edit_images: HashMap::new(), + objects: Default::default(), + image_selection: None, + picked_image: None, + pending_pick: None, + pictures: Default::default(), + comments: crate::comments::CommentView::from_info(info), + measure: Default::default(), + forms: Default::default(), + prepare: Default::default(), + calc_order: Default::default(), + content: Default::default(), + links: Default::default(), + camera: None, + camera_done: None, + sign: Default::default(), + area_pick: None, + fill_text: None, + fill_selection: Default::default(), + signature_drag: Default::default(), + menu_for: None, + } + } } /// Organize-toolbar actions that need the app (file pickers, new tabs, dialogs). @@ -889,174 +467,77 @@ pub enum ViewAction { LockSignatures, } -/// Default page right-click menu actions. -#[derive(Clone, Debug, PartialEq)] -pub(crate) enum PageMenuAction { - RotateCCW, - RotateCW, - Print, - SelectTool, - HandTool, - MarqueeZoom, - Copy, - Paste(usize, [f64; 2]), - /// Paste the copied comments, centred at this point of the page. - PasteComments(usize, [f64; 2]), - AddComment(usize, [f64; 2]), - AddBookmark, - TakeSnapshot, - EditPdf, - AddText, - AddImage, - DeletePage(usize), - ExportPdf, - Find, - DocProperties, - FlattenComments, -} - -pub(crate) struct PageMenuPerms { - pub can_modify: bool, - pub can_assemble: bool, - pub can_annotate: bool, - pub can_print: bool, - pub can_copy: bool, - pub can_copy_items: bool, - pub can_paste: bool, - /// Copied comments wait to be pasted, and comments may be added. - pub can_paste_comments: bool, - pub has_annotations: bool, -} - -pub(crate) fn default_page_context_menu(ui: &mut egui::Ui, page: usize, at: [f64; 2], perms: PageMenuPerms, action: &mut Option) { - use PageMenuAction as A; - // Takes `choice` when `entry` was clicked, and closes the menu. - let mut pick = |entry: egui::Response, ui: &mut egui::Ui, choice: PageMenuAction| { - if entry.clicked() { - *action = Some(choice); - ui.close(); - } - }; - let icon = |ui: &mut egui::Ui, name: &str, tip: &str| crate::icons::button(ui, name, 24.0, false, tip); - // Top horizontal icon bar: Rotate CCW, Print, Select tool, Hand tool, Marquee Zoom - ui.horizontal(|ui| { - ui.spacing_mut().item_spacing.x = 4.0; - pick(icon(ui, "rotate-ccw", tl!("Rotate view counterclockwise")), ui, A::RotateCCW); - ui.add_enabled_ui(perms.can_print, |ui| pick(icon(ui, "printer", tl!("Print")), ui, A::Print)); - pick(icon(ui, "mouse-pointer-2", tl!("Select Tool")), ui, A::SelectTool); - pick(icon(ui, "hand", tl!("Hand Tool")), ui, A::HandTool); - pick(icon(ui, "zoom-in", tl!("Marquee Zoom")), ui, A::MarqueeZoom); - }); - - ui.separator(); - - pick( - ui.add_enabled( - perms.can_copy_items, - egui::Button::new(tl!("Copy")).shortcut_text(crate::commands::shortcut_label(ui.ctx(), crate::commands::COPY)), - ), - ui, - A::Copy, - ); - pick( - ui.add_enabled( - perms.can_paste, - egui::Button::new(tl!("Paste")).shortcut_text(crate::commands::shortcut_label(ui.ctx(), pdfcraft_engine::commands::Shortcut::cmd("V"))), - ), - ui, - A::Paste(page, at), - ); - if perms.can_paste_comments { - pick(ui.button(tl!("Paste comments")), ui, A::PasteComments(page, at)); - } - - ui.separator(); - - pick(ui.add_enabled(perms.can_annotate, egui::Button::new(tl!("Add comment"))), ui, A::AddComment(page, at)); - if perms.has_annotations { - pick(ui.add_enabled(perms.can_modify, egui::Button::new(tl!("Flatten comments"))), ui, A::FlattenComments); - } - pick(ui.add_enabled(perms.can_assemble, egui::Button::new(tl!("Add bookmark"))), ui, A::AddBookmark); - pick(ui.add_enabled(perms.can_copy, egui::Button::new(tl!("Take a snapshot"))), ui, A::TakeSnapshot); - - ui.separator(); - - pick(ui.add_enabled(perms.can_modify, egui::Button::new(egui::RichText::new(tl!("Edit this PDF")).strong())), ui, A::EditPdf); - pick(ui.add_enabled(perms.can_modify, egui::Button::new(tl!("Add text"))), ui, A::AddText); - pick(ui.add_enabled(perms.can_modify, egui::Button::new(tl!("Add image"))), ui, A::AddImage); - pick(ui.add_enabled(perms.can_assemble, egui::Button::new(tl!("Delete page"))), ui, A::DeletePage(page)); - pick(ui.add_enabled(perms.can_copy, egui::Button::new(tl!("Export this PDF"))), ui, A::ExportPdf); - - ui.separator(); - - pick(ui.button(tl!("Find text or tools")), ui, A::Find); - pick(ui.button(tl!("Rotate view clockwise")), ui, A::RotateCW); - pick(ui.button(tl!("Document properties…")), ui, A::DocProperties); -} - impl DocView { /// Whether a middle-button scrolling gesture is active (tests and automation). pub fn auto_scrolling(&self) -> bool { - self.auto_scroll.active() + self.middle_scrolling } /// Whether a held middle-button pan is active, outside Linux (tests and automation). pub fn middle_panning(&self) -> bool { - self.auto_scroll.panning() + // PLAN: `CanvasOutput` reports one `auto_scrolling` for a latched and a held middle scroll (CV-C6) and no + // separate held-pan fact, so both readers read that record. + self.middle_scrolling + } + + /// The current page: the one the page box shows and paging moves from. + pub fn current(&self) -> usize { + self.view.current + } + + /// The fit the view keeps as it resizes. + pub fn fit(&self) -> Fit { + self.view.fit + } + + /// The zoom (1.0 = 100%), equal to what a fit shows. + pub fn zoom(&self) -> f64 { + self.view.zoom + } + + /// The canvas view of the last pass, as the framework's zoom field reads it: its zoom is the view's own zoom, so + /// the field's points scale shows it as the percentage the view shows. `None` before the view was first shown. + pub fn canvas_view(&self) -> Option { + self.canvas + } + + /// Takes the zoom of a view the zoom field committed an edit of (from [`canvas_view`](Self::canvas_view)) into the + /// view: a typed or stepped zoom ends the fit; the next pass clamps it to the zoom range and keeps the view centre. + /// The caller calls it only for the field's committed edit. + pub fn apply_canvas_view(&mut self, edited: &CanvasView) { + if edited.zoom.is_finite() { + self.view.fit = Fit::None; + self.view.zoom = edited.zoom; + } } /// Abandon only pointer previews: clearing egui's held button must not commit an app-owned /// grab through a tool's `!primary_down` fallback. Keep selections, text drafts and edits /// that were already completed before cancellation. - pub(crate) fn cancel_pointer_gestures(&mut self) { - self.marquee = None; - self.marquee_done = None; - self.comments.gesture = None; - self.links.drag = None; - self.sign.drag = None; - self.redact_drag = None; - self.crop_drag = None; - if let Some(q) = &mut self.camera { - q.grab = None; - } - self.org_drag = None; - self.panel_drag = None; - self.selection_drag = false; - self.selection_drag_ended = false; - self.router.cancel(); - self.auto_scroll.cancel(); - self.prepare.cancel_pointer_gesture(); - self.cancel_edit_text_gestures(); + pub(crate) fn cancel_pointer_gestures(&mut self, ctx: &egui::Context) { + self.session.comments.tool.cancel_drawing(); + self.cancel_organize_press(ctx); } - /// Abandon Edit text's pointer gestures (a paragraph moved or rewrapped, a picture moved, - /// resized, turned or cropped, added content moved, the objects' area selection or move), as - /// [`Self::cancel_pointer_gestures`] does: what they were previewing is not applied. - pub(crate) fn cancel_edit_text_gestures(&mut self) { - self.block_drag = None; - self.content.cancel_pointer_gesture(); - self.objects.cancel_pointer_gesture(); - if let Some(image) = &mut self.image_selection { - image.cancel_pointer_gesture(); - } - } - - /// A view of a newly opened document, shown as `defaults` say. Opening a file then applies - /// any layout or zoom the PDF itself asks for. - pub fn new(id: DocId, info: &DocInfo, defaults: ViewDefaults) -> Self { + /// A view of a newly opened document, shown as `defaults` say, with fields highlighted when `highlight_fields` + /// (the app's preference). Opening a file then applies any layout or zoom the PDF itself asks for. + pub fn new(id: DocId, info: &DocInfo, defaults: ViewDefaults, highlight_fields: bool) -> Self { Self { pane: Default::default(), id, from_attachment: None, - zoom: defaults.zoom, - fit: defaults.fit, - layout: defaults.layout, - continuous: defaults.continuous, - show_page_gaps: defaults.show_page_gaps, - rotation: 0, - current: 0, + view: PageViewState::from_defaults(&defaults), + session: PageSession::new(info, highlight_fields), + momentary: Momentary::new(NavigationOptions::default()), + momentary_options: NavigationOptions::default(), + revisions: PageRevisions::default(), + reports: RenderReports::default(), + textures: TextureStatistics::default(), + spacing: None, + viewport: Rect::NOTHING, + canvas: None, + middle_scrolling: false, organize: false, - highlight_fields: defaults.highlight_fields, page_input: "1".into(), page_input_reselect: false, notice_dismissed: false, @@ -1064,257 +545,118 @@ impl DocView { disk_changed: false, close_requested: false, snapshot: None, - cover: false, back: Vec::new(), forward: Vec::new(), - goto: None, - goto_side: None, - goto_point: None, - key_scroll: 0.0, - key_side: 0.0, - side_edges: None, - single_edges: None, - flash: None, - compare_marks: Vec::new(), interface: Default::default(), presentation: None, - presenter: Default::default(), - pages: HashMap::new(), - errors: HashMap::new(), - cut_pages: Default::default(), cut_notice_dismissed: Default::default(), - waiting_since: HashMap::new(), - thumbs: HashMap::new(), - thumb_demand: HashMap::new(), - frame_queue: Vec::new(), - frame_geometry_changed: false, - frame_visible: HashSet::new(), - frame_demanded: HashSet::new(), - stale_thumbs: HashSet::new(), - stale_tiles: HashSet::new(), - current_scale_tag: 0, - print_pages: HashMap::new(), - grayscale: false, - tiles: HashMap::new(), - texts: HashMap::new(), - text_links: HashMap::new(), - text_failed: HashSet::new(), find: None, - selection: None, - all_text: false, - actions_dismissed: None, - selection_drag: false, - selection_drag_ended: false, - clicks: 0, - last_press_time: 0.0, - last_press_pos: None, - present_turn: None, - last_queue: Vec::new(), - hold_rasters: false, - viewport_w: 800.0, - viewport_h: 600.0, page_count: info.pages.len(), page_sizes: info.pages.iter().map(|p| (p.width, p.height)).collect(), - screen_rects: Vec::new(), - screen_xforms: Vec::new(), - screen_ppp: 1.0, - viewport_screen: Rect::NOTHING, - zoom_anchor: None, - find_hold: None, - shown: false, auto_ocr_tried: Default::default(), auto_ocr_skipped: Default::default(), auto_ocr_awaiting_models: Default::default(), - wheel: Default::default(), - wheel_motion: Default::default(), - wheel_frame: None, - wheel_boost_x: Default::default(), - wheel_boost_y: Default::default(), - fling: Default::default(), - auto_scroll: Default::default(), - selected: BTreeSet::new(), - select_anchor: None, - organize_range: Default::default(), - pending_edit: None, - edit_lines: HashMap::new(), - grouped_text_click: None, - line_editor: None, - applied_editor: None, - pending_text_open: None, - text_background: Default::default(), - move_background: Default::default(), - edit_images: HashMap::new(), - objects: Default::default(), - image_selection: None, - picked_image: None, - pending_pick: None, - pictures: Default::default(), - block_drag: None, + selected: Selection::new(Vec::new(), None, None), pending_action: None, insert_at: None, grid_gap: None, pages_panel: None, panel_gap: None, - panel_followed: None, + pages_focus_id: None, thumbnail_zoom: 1.0, - grid_zoom: 1.0, - grid_zoom_request: None, - grid_anchor: None, grid_reveal: None, - grid_pages: HashMap::new(), - last_scale: 0.0, - sharp_hold_until: 0.0, - last_scroll: Vec2::ZERO, - scroll_dir: 0, - scroll_content: Vec2::ZERO, - sync_scroll: None, - page_widget: None, - pan_hold_until: 0.0, - slow_pages: HashSet::new(), - comments: crate::comments::CommentView::from_info(info), - measure: Default::default(), - forms: Default::default(), - prepare: Default::default(), - calc_order: Default::default(), - content: Default::default(), - links: Default::default(), - redact_drag: None, - pending_redaction: None, + bookmarks_open: OpenSet::default(), redactions_applied: 0, redactions_undone_after_save: 0, saved_redactions_cut_off: false, redactions_downloaded: 0, - redaction_refused: false, - marks_across_pages: None, - marks_waiting: None, - crop_drag: None, - camera: None, - camera_done: None, - sign: Default::default(), - org_drag: None, - panel_drag: None, - pages_focus_id: None, - marquee: None, - marquee_done: None, - area_pick: None, - area_choice: None, - fill_text: None, fill_signature_page: None, lock_offer_dismissed: false, - signature_drag: Default::default(), - cursor: Default::default(), - router: Default::default(), - menu_for: None, - press_cancelled: false, } } /// The document's content or page list changed (an edit, undo or redo): drop caches and - /// adopt the new page geometry, keeping the reader's place where possible. - pub fn document_changed(&mut self, info: &DocInfo) { + /// adopt the new page geometry, keeping the reader's place where possible. The Organize grid's open press ends: + /// it holds page indexes from before the change. + pub fn document_changed(&mut self, ctx: &egui::Context, info: &DocInfo) { self.invalidate_content(); - self.frame_geometry_changed = true; self.page_count = info.pages.len(); self.page_sizes = info.pages.iter().map(|p| (p.width, p.height)).collect(); let last = self.page_count.saturating_sub(1); - self.current = self.current.min(last); - self.selected.retain(|p| *p <= last); - // Text being typed on a page that no longer exists goes with the page. - if self.content.draft.as_ref().is_some_and(|d| d.page > last || self.page_count == 0) { - self.content.draft = None; + self.view.current = self.view.current.min(last); + let gone = |p: &usize| *p > last; + self.selected.items.retain(|p| !gone(p)); + if self.selected.lead.as_ref().is_some_and(gone) { + self.selected.lead = None; } - if self.select_anchor.is_some_and(|a| a > last) { - self.select_anchor = None; + if self.selected.anchor.as_ref().is_some_and(gone) { + self.selected.anchor = None; + } + // Text being typed on a page that no longer exists goes with the page. + if self.session.content.draft.as_ref().is_some_and(|d| d.page > last || self.page_count == 0) { + self.session.content.draft = None; } // A Snapshot area names a page by its index and a rectangle on it: after pages were // deleted or moved it would outline, print and save a different page. - self.area_pick = None; - self.area_choice = None; - self.goto = None; - self.goto_point = None; - self.zoom_anchor = None; - self.find_hold = None; - self.flash = None; + self.session.area_pick = None; + self.view.go_to = None; + self.session.flash = None; // Thumbnail drags hold page indexes from before the change. - self.panel_drag = None; - self.org_drag = None; - self.comments.document_changed(info); - self.reset_coarse_state(); + self.cancel_organize_press(ctx); + self.session.comments.document_changed(info); } /// The document was replaced by a newer version of its file (#431). The reader's place /// stays: zoom, layout, rotation, page, scroll, full screen, view history and the find bar, - /// the snapshot marker and its pending close, and the page images on screen until their - /// replacements are drawn, so nothing flashes. Everything that pointed into the old version (a selected + /// the snapshot marker and its pending close. Everything that pointed into the old version (a selected /// comment, a field being typed in, text being edited, a drag, page selection) starts /// afresh, so no stale index reaches the new one. - pub fn document_replaced(&mut self, info: &DocInfo) { - let mut fresh = Self::new(self.id, info, ViewDefaults::default()); - fresh.zoom = self.zoom; - fresh.fit = self.fit; - fresh.layout = self.layout; - fresh.continuous = self.continuous; - fresh.show_page_gaps = self.show_page_gaps; - fresh.rotation = self.rotation; - fresh.current = self.current; + pub fn document_replaced(&mut self, ctx: &egui::Context, info: &DocInfo) { + let mut fresh = Self::new(self.id, info, ViewDefaults::default(), self.session.highlight_fields); + // Display, page and scroll offset: the reader's place. + fresh.view = self.view.clone(); fresh.organize = self.organize; - fresh.grid_zoom = self.grid_zoom; fresh.thumbnail_zoom = self.thumbnail_zoom; - // Same view key (`pane`), so the scroll offset egui keeps for it is still this view's. - fresh.shown = self.shown; - fresh.highlight_fields = self.highlight_fields; fresh.notice_dismissed = self.notice_dismissed; fresh.cut_notice_dismissed = std::mem::take(&mut self.cut_notice_dismissed); fresh.snapshot = self.snapshot.clone(); fresh.close_requested = self.close_requested; - fresh.cover = self.cover; // What the document asked to hide, and what is hidden now (F8), belong to the tab. fresh.interface = self.interface; // Still presenting, with the display to go back to on leaving. fresh.presentation = self.presentation.take(); - // A new document: none of the old one's transition, page or timer carries over. - fresh.presenter = Default::default(); fresh.back = std::mem::take(&mut self.back); fresh.forward = std::mem::take(&mut self.forward); fresh.find = self.find.take(); - fresh.pages = std::mem::take(&mut self.pages); - fresh.thumbs = std::mem::take(&mut self.thumbs); - fresh.viewport_w = self.viewport_w; - fresh.viewport_h = self.viewport_h; - fresh.viewport_screen = self.viewport_screen; + // The revision stamps carry on, so the pictures on screen stay until their replacements land. + fresh.revisions = std::mem::take(&mut self.revisions); + fresh.viewport = self.viewport; + // Same view key (`pane`): the page view's remembered state and the grid's press id are still this view's. fresh.pane = self.pane.clone(); *self = fresh; - // Marks the kept images out of date and clamps the page to the new page count. - self.document_changed(info); - self.page_input = self.current_page_label(info.pages.get(self.current).map(|page| page.label.as_str())); + // Marks the kept pictures out of date and clamps the page to the new page count. + self.document_changed(ctx, info); + self.page_input = self.current_page_label(info.pages.get(self.view.current).map(|page| page.label.as_str())); self.page_input_reselect = true; } /// Another view of this document changed it (split view: an edit, Undo, /// a reload): start afresh as a reload does, keeping the reader's place, so nothing here /// points into the old version. - pub(crate) fn follow_document(&mut self, info: &DocInfo) { - let continuous = self.continuous; - self.document_replaced(info); - self.continuous = continuous; + pub(crate) fn follow_document(&mut self, ctx: &egui::Context, info: &DocInfo) { + let continuous = self.view.continuous; + self.document_replaced(ctx, info); + self.view.continuous = continuous; } /// A second view of this document (split view), showing what this one shows. pub(crate) fn twin(&self, info: &DocInfo) -> Self { - let mut v = Self::new(self.id, info, ViewDefaults::default()); - v.zoom = self.zoom; - v.fit = self.fit; - v.layout = self.layout; - v.continuous = self.continuous; - v.show_page_gaps = self.show_page_gaps; - v.rotation = self.rotation; - v.cover = self.cover; - v.current = self.current; + let mut v = Self::new(self.id, info, ViewDefaults::default(), self.session.highlight_fields); + v.view = self.view.clone(); + v.view.go_to(self.view.current); v.page_input = self.page_input.clone(); - v.highlight_fields = self.highlight_fields; v.notice_dismissed = self.notice_dismissed; v.scripts_off_noted = self.scripts_off_noted; - v.goto = Some((self.current, 0.0)); v } @@ -1329,1326 +671,21 @@ impl DocView { self.pane.place } - /// Select pages in the organize grid (tests, automation). Empty clears the selection. + /// The number of pages the view was last given. pub(crate) fn page_count(&self) -> usize { self.page_count } - - /// 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(); - self.wheel_motion.reset(); - } -} - -/// The renders a frame wants (page, scale, tag, tile), and the pages visible. -type PageRenders = (Vec<(usize, f32, u64, Option)>, Vec); - -/// What the page-scroll closure reads: this frame's zoom, scrolling, tool and document state. -#[derive(Clone, Copy)] -struct PageEnv<'a> { - added: &'a Vec, - allowed: bool, - author: &'a String, - auto_delta: Vec2, - avail: Rect, - coarse_scroll: Vec2, - by_line: &'a String, - calc_order: bool, - can_copy: bool, - /// Copied comments wait to be pasted. - can_paste_comments: bool, - /// Copied comments hang on the pointer (`Gesture::Place`): the click is theirs. - placing: bool, - can_crop: bool, - can_fill: bool, - can_modify: bool, - comments_hidden: bool, - content_h: f32, - content_w: f32, - /// The custom stamp's line, filled in now (#1741). - custom_line: &'a Option, - custom_stamp: &'a Option, - date_text: &'a Result, - doc: &'a pdfcraft_engine::Document, - doc_links: &'a Vec, - edge_delta: Vec2, - editing_content: bool, - form: &'a Arc>, - generation: u64, - glide: Vec2, - hand: bool, - info: &'a DocInfo, - /// The Animation effects preference as it applies now (full screen's transitions follow it). - animates: bool, - initials: &'a Option, - key_scroll: f32, - key_side: f32, - /// This frame's keys as the pages see them. - keys: crate::page_keys::PageKeys, - middle_gesture: bool, - modal: bool, - navigation_enabled: bool, - paper: Color32, - show_page_edge_shadows: bool, - ppp: f32, - precise_scroll: Vec2, - prefs: &'a comments::CommentPrefs, - preparing: bool, - prepare_tab_order: Option<&'a [(usize, usize)]>, - rects: &'a Vec, - redact_mark: ([f64; 3], f64), - scale: f32, - selection_wheel: bool, - selects_text: bool, - signature: &'a Option, - single_paging: bool, - t: &'a Tokens, - table_preview: &'a Option, - tag: u64, - text_style: &'a pdfcraft_engine::AddedText, - /// Preferences: addresses written as plain page text open like links (#4207). - text_links: bool, - tool: QuickTool, - units: crate::units::Unit, - unobstructed: bool, - visible_pages: &'a Vec, - y_shift: f32, - fill_text_size: f64, - fill_text_color: [f64; 3], - fill_text_border: crate::fill_sign::TextBorder, - today: (i64, u32, u32), - can_paste_image: bool, -} - -/// What the page-scroll closure produces for the rest of the frame. -#[derive(Default)] -struct PageOut { - canvas_action: Option, - clicked_link: Option, - /// The JavaScript link clicked, by page and annotation index (0-based), to run its action. - javascript_link: Option<(usize, usize)>, - comment_notice: Option<&'static str>, - copy_comments: bool, - copy_selected: bool, - field_menu: Option, - field_placed: bool, - field_props: bool, - hover_text: Option<(Pos2, String)>, - image_action: Option, - open_boxes: bool, - open_initials: bool, - open_signature: bool, - open_table: Option<(usize, [f64; 4])>, - page_action: Option, - paste_comments_at: Option<(usize, [f64; 2])>, - primary_down: bool, - /// The pointer is over a link, comment, field or what is placed on the page: a click there is - /// for it, and turns no page in full screen. - on_object: bool, - refused: Option, - /// The current page or spread where it is drawn, every page of it: one off screen (the second - /// page of a zoomed spread) has no screen transform, but still decides where the row ends. - row_on_screen: Option, - 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, - signature_preview: &'a mut Option<(crate::fill_sign::SavedSig, egui::TextureHandle)>, - out: PageOut, - wanted: Vec<(usize, f32, u64, Option)>, - visible_now: Vec, - current: usize, - best_overlap: f32, - current_overlap: f32, - current_height: f32, - pressed_page: Option, - calc_hover: Option, - /// The form field widget under the pointer on any page, for its Mouse Enter and Exit scripts. - field_hover: Option, - /// A page took this frame's right-click. - right_clicked: bool, -} - -impl PageFrame<'_> { - /// Where this frame's right-click is, for the first page it is `on`: pages that touch (the gaps - /// hidden) can share a row of pixels, and a right-click there is one page's, as a press is. - fn right_click_on(&mut self, on: impl FnOnce(Pos2) -> bool) -> Option { - let p = self.pointer.filter(|p| !self.right_clicked && self.resp.secondary_clicked() && on(*p))?; - self.right_clicked = true; - Some(p) - } -} - -/// 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. -#[allow(clippy::too_many_arguments)] -fn paint_image_suppressed( - xf: &PageXform, - painter: &egui::Painter, - tex: egui::TextureId, - u0: f32, - v0: f32, - u1: f32, - v1: f32, - suppress: Option<[f32; 4]>, - is_full_page_tex: bool, -) { - let Some([su0, sv0, su1, sv1]) = suppress else { - if is_full_page_tex { - xf.paint_page_texture_rect(painter, tex, u0, v0, u1, v1); - } else { - xf.paint_image(painter, tex, u0, v0, u1, v1); - } - return; - }; - let iu0 = u0.max(su0); - let iu1 = u1.min(su1); - let iv0 = v0.max(sv0); - let iv1 = v1.min(sv1); - if iu0 >= iu1 || iv0 >= iv1 { - if is_full_page_tex { - xf.paint_page_texture_rect(painter, tex, u0, v0, u1, v1); - } else { - xf.paint_image(painter, tex, u0, v0, u1, v1); - } - return; - } - let map_uv = |pu: f32, pv: f32| -> (f32, f32) { - if is_full_page_tex { - (pu, pv) - } else { - let du = (u1 - u0).max(1e-6); - let dv = (v1 - v0).max(1e-6); - ((pu - u0) / du, (pv - v0) / dv) - } - }; - let draw_strip = |pu0: f32, pv0: f32, pu1: f32, pv1: f32| { - if pu1 <= pu0 || pv1 <= pv0 { - return; - } - let (tu0, tv0) = map_uv(pu0, pv0); - let (tu1, tv1) = map_uv(pu1, pv1); - xf.paint_image_region(painter, tex, pu0, pv0, pu1, pv1, tu0, tv0, tu1, tv1); - }; - - if iv0 > v0 { - draw_strip(u0, v0, u1, iv0); - } - if v1 > iv1 { - draw_strip(u0, iv1, u1, v1); - } - if iu0 > u0 { - draw_strip(u0, iv0, iu0, iv1); - } - if u1 > iu1 { - draw_strip(iu1, iv0, u1, iv1); - } -} - -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 && frame.env.show_page_edge_shadows { - 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)), - } - let doc = frame.env.doc; - let active_drag_suppress = if let Some(sel) = view.image_selection.clone() - && sel.page == i - && sel.drag.is_some() - { - let images = cached_edit_images(view, doc, i); - if let Some(img) = images.get(sel.index) { - let obb = ImageObb::from_image(img, &xf, info, i); - let uvs = obb.corners().map(|c| xf.screen_to_norm(c)); - let u0 = uvs.iter().map(|(u, _)| *u).fold(1.0f32, f32::min).clamp(0.0, 1.0); - let u1 = uvs.iter().map(|(u, _)| *u).fold(0.0f32, f32::max).clamp(0.0, 1.0); - let v0 = uvs.iter().map(|(_, v)| *v).fold(1.0f32, f32::min).clamp(0.0, 1.0); - let v1 = uvs.iter().map(|(_, v)| *v).fold(0.0f32, f32::max).clamp(0.0, 1.0); - if u1 > u0 && v1 > v0 { Some([u0, v0, u1, v1]) } else { None } - } else { - None - } - } else { - None - }; - match view.pages.get(&i) { - Some(p) => { - if !tiled && p.tag == want_tag { - paint_image_suppressed(&xf.texel_aligned(p.tex.size(), ppp), painter, p.tex.id(), 0.0, 0.0, 1.0, 1.0, active_drag_suppress, true); - } else { - // A backdrop, or a raster at an older scale until the new one arrives. - paint_image_suppressed(&xf, painter, p.tex.id(), 0.0, 0.0, 1.0, 1.0, active_drag_suppress, true); - } - } - 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), active_drag_suppress); - } - } -} - -/// 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), - active_drag_suppress: Option<[f32; 4]>, -) { - 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); - paint_image_suppressed(&xf, painter, tex.id(), x / ow, y / oh, (x + w as f32) / ow, (y + h as f32) / oh, active_drag_suppress, false); - } - // 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); - paint_image_suppressed( - &xf.texel_aligned([dw as usize, dh as usize], ppp), - painter, - tex.id(), - x as f32 / fw, - y as f32 / fh, - (x + w) as f32 / fw, - (y + h) as f32 / fh, - active_drag_suppress, - false, - ); - } - } -} - -/// Images parsed once per page and document edit generation, shared by painting and menus. -fn cached_edit_images<'a>(view: &'a mut DocView, doc: &pdfcraft_engine::Document, page: usize) -> &'a [pdfcraft_engine::PageImage] { - let generation = doc.edit_generation(); - let entry = view.edit_images.entry(page).or_insert_with(|| (generation, doc.page_images(page))); - if entry.0 != generation { - *entry = (generation, doc.page_images(page)); - } - &entry.1 -} - -fn draw_page(ui: &mut egui::Ui, view: &mut DocView, frame: &mut PageFrame<'_>, i: usize) { - let PageEnv { allowed, comments_hidden, doc, editing_content, info, keys, ppp, prefs, rects, redact_mark, scale, t, tool, .. } = frame.env; - let PageFrame { ptr, origin, visible, pressed, pointer, .. } = *frame; - let r = snap_to_pixels(rects[i].translate(origin.to_vec2()), ppp); - if !r.intersects(visible.expand(400.0)) { - return; - } - 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); - } - if view.show_page_gaps { - painter.rect_stroke(r, CornerRadius::ZERO, Stroke::new(0.5, t.border.gamma_multiply(0.8)), egui::StrokeKind::Outside); - } - - let slot = PageSlot { i, r, xf }; - // Addresses written as plain text are found once per text layer, before the tools hit-test them. - if frame.env.text_links { - view.refresh_text_links(i); - } - let pcx = comments::PageCx { page: i, xf: &xf, ptr, info, tool, prefs, allowed, hidden: comments_hidden, redact_mark, keys }; - // A cancelled press takes nothing until the button is up, though the page's menu still opens - // where a right-click is. A page full screen doesn't show yet takes nothing at all. (A press - // there gives nothing on the page an owner, so its release, once the page is in, takes nothing - // either.) - let veiled = page_input::veiled(view); - let input = if view.press_cancelled || veiled { - if !veiled && let Some(p) = frame.right_click_on(|p| xf.rect.contains(p)) { - comments::anchor(&pcx, p, view); - } - PageInput { - press: crate::page_router::PagePress::Elsewhere, - text_drag: false, - consumed: true, - area_tool: false, - hover: None, - released_over: false, - sign_tabs: Vec::new(), - } - } else { - page_tool_input(ui, view, frame, &slot) - }; - let painter = ui.painter(); - 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 other comment being moved: drawn where it goes, over the page that still shows it - // where it was. - let stale = view.signature_drag.moving_page().is_some_and(|p| view.page_out_of_date(p)); - view.signature_drag.prepare_move(ui.ctx(), doc, &view.comments, view.pending_edit.as_ref(), stale, scale); - view.signature_drag.paint_move(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 && frame.pressed_page == Some(i) { - view.all_text = false; - } - text_layer(ui, view, frame, &slot, &input); - page_overlays(ui, view, frame, &slot, &input); -} - -#[allow(clippy::cognitive_complexity)] -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, - coarse_scroll, - calc_order, - can_copy, - can_paste_comments, - can_modify, - content_h, - content_w, - doc, - edge_delta, - form, - generation, - glide, - hand, - info, - key_scroll, - key_side, - middle_gesture, - modal, - navigation_enabled, - precise_scroll, - prefs, - preparing, - selection_wheel, - single_paging, - tool, - unobstructed, - visible_pages, - y_shift, - .. - } = *env; - let animates = env.animates; - // 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); - } - // These deltas already contain their motion policy. Positive y moves the content down; - // applying another ScrollArea animation would ease the wheel twice. - // 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 + coarse_scroll }; - let delta = auto_delta + edge_delta - vec2(key_side, key_scroll) + wheel_delta + glide; - if delta != Vec2::ZERO && delta.is_finite() { - ui.scroll_with_delta_animation(delta, egui::style::ScrollAnimation::none()); - } - // A resized handle can sit in the window beside a page that does not fill it. The - // response has to cover that visible area or the next press never starts: the pointer - // is reported only inside this rectangle once the previous drag has been released. - // Page positions stay on `content_w`/`content_h`; the extra area is not a new page. - let response_size = vec2(content_w.max(viewport.width()), content_h.max(viewport.height())); - let (resp_rect, resp) = ui.allocate_exact_size(response_size, Sense::click_and_drag()); - view.page_widget = Some(resp.id); - // A drag lasts only while egui reports it, so the mark can't outlive one. - view.selection_drag_ended = view.selection_drag && resp.drag_stopped_by(egui::PointerButton::Primary); - if !resp.dragged_by(egui::PointerButton::Primary) { - view.selection_drag = false; - } - // 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 visible = viewport.translate(resp_rect.min.to_vec2()); - view.screen_rects.clear(); - view.screen_ppp = ui.ctx().pixels_per_point(); - 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); - cancel_on_escape(ui.ctx(), view, &ptr); - view.router.settle(ptr.any_down, !ptr.edges.is_empty()); - // A new press is no longer the last one's, wherever it lands (the page it is on gives it - // its owner; in the gap between pages it is no page's). - if ptr.pressed().is_some() { - view.router.begin(); - // The page widget is not focusable. Explicitly return keyboard ownership from Pages - // when the user presses the document, without stealing focus through a modal. - if let Some(id) = view.pages_focus_id { - ui.memory_mut(|m| m.surrender_focus(id)); - } - } - 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; - // Set again below by the page right-clicked: a right-click off the pages (between them, - // beside one) anchors no page's menu, which then acts on the current page. It deselects the - // comment, and Edit text's picture, too (below), as one on a page's empty part does. A - // selected Prepare field stays selected, and the menu is the page's there too. - view.comments.context_at = None; - view.menu_for = 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, - field_hover: None, - right_clicked: false, - }; - 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, - field_hover, - out: page_out, - right_clicked, - .. - } = frame; - crate::forms_ui::hover_moved(view, field_hover); - // A right-click no page took deselects the comment, so the page's menu opens, not the comment's, - // and with Edit text the picture (one on a page went to that page, `page_input`). - if resp.secondary_clicked() && !right_clicked { - view.comments.selected = None; - if tool == QuickTool::EditText { - view.image_selection = None; - } - } - let PageOut { - mut canvas_action, - clicked_link, - javascript_link, - copy_selected, - mut field_menu, - field_placed, - field_props, - hover_text: _, - mut image_action, - open_boxes, - open_initials, - open_signature, - open_table, - page_action: _, - primary_down: _, - on_object: _, - refused, - row_on_screen: _, - stamp_placed, - .. - } = page_out; - let mut page_action: Option = None; - 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); - } - // Full screen plays transitions over the page just drawn, and keeps time (#379). - let mut hide_pointer = false; - if view.presentation.is_some() { - let now = ui.input(|i| i.time); - hide_pointer = presenter::frame(view, info, painter, ui.ctx(), now, animates, pointer); - } - // Read before the claims are spent below, and before the pointer hides, which claims the top layer. - let on_object = view.cursor.over_object(tool); - // A still pointer hides over a link too, and its tip with it: the top layer, which every tool reaches. - if hide_pointer { - view.cursor.claim(Layer::Drag, egui::CursorIcon::None); - } - // The pages' one cursor, from the claim on the highest layer the tool reaches, and the tip. - let hover_text = pointer.filter(|_| unobstructed && !hide_pointer).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. The viewer owns both precise and coarse wheel motion, so selection uses - // the same distance as ordinary document scrolling. - if selection_wheel { - let delta = precise_scroll + coarse_scroll; - 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, onto the - // pages it scrolls to. - 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 - 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; - } - // The menu of what the right-click went to (`menu_for`), or else the page's. - use crate::page_router::{Owner, PicturePart}; - let menu_for = view.menu_for.map(|(_, owner)| owner); - // A right-click while a press is held leaves the selections alone, so the menu is its owner's only - // when that owner is the one selected. - let on_selected_field = match menu_for { - Some(Owner::PrepareField { field, widget }) => { - form.get(field).is_some_and(|f| view.prepare.selected.as_ref().is_some_and(|(name, w)| *name == f.name && *w == widget)) - } - Some(Owner::PrepareCorner { .. }) => true, - _ => false, - }; - // The row as it is now: in continuous view the current page may have changed above. - let row_on_screen = - shown_row(view, env.rects).iter().filter_map(|&i| env.rects.get(i)).map(|r| r.translate(origin.to_vec2())).reduce(Rect::union); - let presenting = view.presentation.is_some(); - page_context_menu(&resp, presenting, |ui| { - // Crop mode has no menu: a right-click on the picture being cropped, its box or its grips is - // the crop's (#5835). - if matches!(menu_for, Some(Owner::Picture { part: PicturePart::Crop(_), .. })) { - egui::Popup::close_all(ui.ctx()); - ui.close(); - return; - } - // Preparing a form: the selected field's menu, on a field. - if preparing - && on_selected_field - && 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 matches!(menu_for, Some(Owner::Link { .. })) - && 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; - } - let can_paste_image = env.can_paste_image; - if tool == QuickTool::EditText - && let Some((page, Owner::Picture { index, .. })) = view.menu_for - && let Some(sel) = view.image_selection.clone().filter(|s| (s.page, s.index) == (page, index)) - { - let images = cached_edit_images(view, doc, sel.page).to_vec(); - // Paste lands where the menu opened, on the picture's page: the right-click that opened - // it went to that page (`page_input`), and another page's point means nothing there. - let at = view.comments.context_at.filter(|(page, _)| *page == sel.page).map(|(_, at)| at); - let rotation = (view.rotation % 360 + info.pages.get(sel.page).map_or(0, |p| p.rotation % 360)) % 360; - crate::edit_text_ui::image_context_menu(ui, view, &images, sel.page, sel.index, can_paste_image, &mut image_action, at, rotation); - return; - } - // The comment the right-click went to, when it is the one selected, or connected lines being - // drawn (Complete, Undo last point): the comment menu. - let on_selected_comment = - matches!(view.menu_for, Some((page, Owner::Comment { index, .. })) if view.comments.selected == Some((page, index))); - let drawing_points = matches!(&view.comments.gesture, Some(comments::Gesture::Draw { tool, .. }) if tool.clicks_points()); - if on_selected_comment || drawing_points { - canvas_action = comments::context_menu( - ui, - view, - info, - &|page, index| doc.annotation_deletable(page, index), - prefs, - comments::MenuRights { allowed, can_paste: can_paste_comments, can_modify }, - ); - return; - } - // Over a picture (and no comment): Copy Image, as in Acrobat's page menu. - let mut copy_image = None; - if let Some((page, at)) = view.comments.context_at { - // On a page still being read, these items appear when the answer comes. - let hit = view.pictures.get(ui.ctx(), doc, page).and_then(|pictures| pdfcraft_engine::picture_at(pictures, at)).map(|(index, _)| *index); - 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(); - } - } - let has_copy_image = copy_image.is_some(); - if copy_image.is_some() { - canvas_action = copy_image; - } - let (page, at) = view.comments.context_at.unwrap_or((view.current, [0.0, 0.0])); - // A text selection whose pages are still being read copies once they are. - let has_text = view.selected_text().is_some() || view.selection_waits_for_text().is_some(); - let can_copy_items = can_copy && (view.image_selection.is_some() || has_text || has_copy_image); - let can_paste = can_paste_image && can_modify; - let perms = PageMenuPerms { - can_modify, - can_assemble: doc.allows_assembly(), - can_annotate: allowed, - can_print: doc.allows_printing(), - can_copy, - can_copy_items, - can_paste, - can_paste_comments: allowed && can_paste_comments, - has_annotations: !info.annotations.is_empty(), - }; - default_page_context_menu(ui, page, at, perms, &mut page_action); - }); - // Copy comments / Paste comments from the page's menu or a Comments panel card. - let copy_comments = std::mem::take(&mut view.comments.copy_request); - let paste_comments_at = view.comments.paste_request.take(); - let comment_notice = view.comments.notice.take(); - *out = PageOut { - canvas_action, - clicked_link, - javascript_link, - comment_notice, - copy_comments, - copy_selected, - field_menu, - field_placed, - field_props, - hover_text, - image_action, - open_boxes, - open_initials, - open_signature, - open_table, - page_action, - paste_comments_at, - primary_down: ptr.primary_down, - on_object, - refused, - row_on_screen, - stamp_placed, - }; - (wanted, visible_now) -} - -/// A zoom the fit mode changed keeps the page at the top of the view in place, or, just after a -/// find step, the match in the middle of the view (`avail` is the view's size). -fn anchor_zoom_change(view: &mut DocView, avail: Vec2, old_zoom: f32) { - let avail_width = avail.x; - 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, fx, fy)) = view.find_hold { - // A fit zoom that changes just after a find step keeps the match in the middle too. - view.zoom_anchor = Some((page, fx, fy, avail / 2.0)); - } else 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))); - } - } -} - -/// 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); - let fits = row_rect.is_some_and(|r| fits_height(r, avail.height(), ui.ctx().pixels_per_point())); - 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. - let now = ui.input(|i| i.time); - for e in &crate::motion::gesture_wheel_events(ui.ctx()) { - 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, now, can_turn); - } else { - edge_turned |= view.single_page_wheel_edge(*unit, dy, *phase, now, 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); - } - } - (single_paging, edge_turned) -} - -/// This frame's wheel motion over the page view, after paging and motion integration. -struct Wheel { - precise_scroll: Vec2, - line_base: Vec2, - coarse_scroll: 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, -} - -/// Cancels older motion before the pager reads new input, without discarding that input. -fn reset_interrupted_wheel(ui: &egui::Ui, view: &mut DocView, other_motion: bool) { - let frame = ui.ctx().cumulative_frame_nr(); - let resumed = view.wheel_frame.is_some_and(|last| last != frame && last.checked_add(1) != Some(frame)); - if resumed || glide_interrupted(ui) || other_motion { - view.reset_coarse_state(); - } -} - -/// Integrates the whole coarse-wheel distance once, independently of egui's wheel easing. -/// Precise input remains direct, and interrupts clear retained motion before accepting new input. -fn read_wheel(ui: &mut egui::Ui, view: &mut DocView, avail: Rect, single_paging: bool, edge_turned: bool, enabled: bool, animate: bool) -> Wheel { - let now = ui.input(|i| i.time); - let hovered = ui.rect_contains_pointer(avail); - let frame = ui.ctx().cumulative_frame_nr(); - let repeated = view.wheel_frame == Some(frame); - view.wheel_frame = Some(frame); - // ScrollArea must not add egui's independently eased copy to the viewer's own motion. - // Keep draining that copy on later frames and discarded passes too. - if hovered { - ui.input_mut(|i| i.smooth_scroll_delta = Vec2::ZERO); - } - let paging_owns_vertical = single_paging || (!view.continuous && view.wheel.gesture_turned()); - if repeated || !hovered || !enabled { - if !hovered || !enabled { - view.reset_coarse_state(); - } - return Wheel { precise_scroll: Vec2::ZERO, line_base: Vec2::ZERO, coarse_scroll: Vec2::ZERO, has_page: false, paging_owns_vertical }; - } - // A touch gesture zooms to its end once it began with ⌘ or Ctrl, the keys let go or not. - let events = crate::motion::gesture_wheel_events(ui.ctx()); - let consumed = events.iter().any(|event| { - matches!(event, egui::Event::MouseWheel { delta, modifiers, .. } if *delta != Vec2::ZERO && delta.is_finite() && !modifiers.command && !modifiers.ctrl) - }); - if consumed { - wheel_reset::consumed(ui.ctx()); - } - let input = { - // 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 }; - crate::wheel_boost::accumulate(&events, line_points, single_paging) - }; - let mut precise_scroll = input.precise; - let mut line_base = input.line; - if precise_scroll.x != 0.0 { - view.wheel_boost_x.reset(); - } - if precise_scroll.y != 0.0 { - view.wheel_boost_y.reset(); - } - let mut coarse_input = line_base + 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 edge_turned { - view.fling.stop(); - } - let page_scale = ui.input(|i| i.viewport_rect().height()); - if page_scale.is_finite() && page_scale > 0.0 { - coarse_input += input.page * page_scale; - } - // 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. - if paging_owns_vertical { - precise_scroll.y = 0.0; - line_base.y = 0.0; - coarse_input.y = 0.0; - view.wheel_motion.cancel_axes(vec2(0.0, 1.0)); - } - view.wheel_motion.cancel_axes(precise_scroll); - let coarse_scroll = view.wheel_motion.step(coarse_input, now, ui.input(|i| i.stable_dt), animate); - if view.wheel_motion.has_pending() { - ui.ctx().request_repaint(); - } - Wheel { precise_scroll, line_base, coarse_scroll, has_page, paging_owns_vertical } -} - -/// Rows of pages that continuous view prefetches past the window in the direction it last -/// moved. -const PREFETCH_ROWS: usize = 2; - -/// The pages continuous view prefetches past the window: the next [`PREFETCH_ROWS`] rows the way -/// it last moved, nearest first, and none before it moves. The web build renders on the UI -/// thread, so it prefetches none. -fn scroll_prefetch(view: &DocView, visible_now: &[usize]) -> Vec { - if !view.continuous || cfg!(target_arch = "wasm32") { - return Vec::new(); - } - let n = PREFETCH_ROWS * if view.layout == PageLayout::Single { 1 } else { 2 }; - // At high zoom the other page of a two-page row can be off to the side and not on screen, so - // the rows are counted from the edges of the rows shown, and that page is prefetched too. - match (view.scroll_dir, visible_now.iter().min(), visible_now.iter().max()) { - (1, _, Some(&last)) => (last.saturating_add(1)..=row_bounds(view, last).1.saturating_add(n)).collect(), - (-1, Some(&first), _) => (row_bounds(view, first).0.saturating_sub(n)..first).rev().collect(), - _ => Vec::new(), - } -} - -/// The first and last page of the row that page `i` is in, paired as [`shown_row`] pairs them. -fn row_bounds(view: &DocView, i: usize) -> (usize, usize) { - match view.layout { - PageLayout::Single => (i, i), - PageLayout::TwoUp if view.cover && i == 0 => (0, 0), - PageLayout::TwoUp => { - let first = view.spread_first(i); - (first, first.saturating_add(1)) - } - } -} - -/// The whole-page raster a prefetch asks for: the page at this scale, or the backdrop of a page -/// that is tiled at this scale. A cached raster sharper than the backdrop stays demanded as it -/// is, as `paint_page_surface` demands it under tiles. -fn prefetch_demand(view: &DocView, p: &pdfcraft_render::PageInfo, i: usize, scale: f32, tag: u64, max_side: f32) -> (usize, f32, u64, Option) { - let side = p.width.max(p.height).max(1.0); - if side * scale <= TILE_THRESHOLD.min(max_side) { - return (i, scale, tag, None); - } - let bs = BASE_SIDE.min(max_side) / side; - match view.pages.get(&i).filter(|c| c.tag != STALE_TAG && tag_scale(c.tag) >= bs) { - Some(c) => (i, tag_scale(c.tag), c.tag, None), - None => (i, bs, scale_tag(bs), None), - } -} - -/// Whether `page` lies behind the way continuous view last moved: above the current page while -/// scrolling down, below it while scrolling up. `false` outside continuous view. -fn behind_scroll(continuous: bool, scroll_dir: i8, current: usize, page: usize) -> bool { - continuous && ((scroll_dir > 0 && page < current) || (scroll_dir < 0 && page > current)) -} - -/// Orders a frame's demand: pages on screen first, then off-screen pages ahead of the way the -/// view last moved, then those behind it, each nearest the current page first. -fn order_demand(view: &DocView, wanted: &mut [(usize, f32, u64, Option)], visible_now: &[usize]) { - let cur = view.current; - wanted.sort_by_key(|w| { - let shown = visible_now.contains(&w.0); - (!shown, !shown && behind_scroll(view.continuous, view.scroll_dir, cur, w.0), w.0.abs_diff(cur), w.3.is_some()) - }); -} - -/// 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, -} - -/// Queues the renders for the pages and tiles `renders` wants (nearest the view first), prefetches the -/// rows either side (in continuous view, the rows ahead in the scroll direction), 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. - wanted.push(prefetch_demand(view, p, i, scale, tag, max_side)); - } - } - // Continuous view also asks for the rows ahead of the way it last moved. - let max_side = ui.ctx().input(|inp| inp.max_texture_side) as f32; - for i in scroll_prefetch(view, &visible_now) { - if view.errors.contains_key(&i) || wanted.iter().any(|w| w.0 == i) { - continue; - } - let Some(p) = info.pages.get(i) else { continue }; - wanted.push(prefetch_demand(view, p, i, scale, tag, max_side)); - } - let cur = view.current; - order_demand(view, &mut wanted, &visible_now); - // 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 = wanted.iter().filter(|w| w.3.is_some()).map(|w| w.0).collect(); - let on_screen: HashSet = 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 = 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 = if hand { Vec::new() } else { visible_now.iter().copied().filter(need_text).collect() }; - // A selection across pages copies and marks every page it covers, scrolled past or not. - if let Some(s) = view.selection { - let rest: Vec = s.pages().filter(|p| *p < info.pages.len()).filter(need_text).filter(|p| !text_pages.contains(p)).collect(); - text_pages.extend(rest); - } - if view.find.as_ref().is_some_and(|f| !f.case_query.trim().is_empty()) { - let n = info.pages.len(); - let rest: Vec = (0..n).map(|k| (cur + k) % n).filter(need_text).filter(|p| !text_pages.contains(p)).collect(); - 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(); } /// Acts on the notice bar button that was clicked. fn apply_notice(app: &mut PdfCraftApp, index: usize, notice: Option) { match notice { #[cfg(not(target_arch = "wasm32"))] - Some(Notice::Reload) => app.watch.reload_request = app.views.get(index).map(|view| view.id), + Some(Notice::Reload) => app.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::Repairs) => app.open_properties(crate::PropsTab::Advanced), + Some(Notice::Security) => app.open_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)); @@ -2661,9 +698,11 @@ fn apply_notice(app: &mut PdfCraftApp, index: usize, notice: Option) { 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), + // PLAN: assumed `side_panels::set_panel_visible(app, panel: RightPanel, visible: bool)` (pdf-shell-w13, + // pdf-chrome-w13 name no panel type). + Some(Notice::Signatures) => crate::side_panels::set_panel_visible(app, RightPanel::Signatures, true), + Some(Notice::FieldHighlights(on)) => app.highlight_fields = on, + Some(Notice::Console) => crate::js_dialogs::open_console(app), // Back on in Preferences ▸ General. Some(Notice::HideSecured) => app.show_secured_notice = false, // Handled by the app with the other view actions (`ViewAction`). @@ -2688,248 +727,6 @@ fn close_requested_tab(app: &mut PdfCraftApp, index: usize) -> bool { true } -/// 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 tab keeps its own scroll position when switching tabs (#189), and so does each view of - // one document in split view. - scroll = scroll.id_salt(("page-view", view.view_key())); - // 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 document that hides the window's interface (`HideWindowUI`) hides the scroll bars too; - // the wheel, keys and Hand tool still scroll. - if view.interface.hidden.window_ui { - scroll = scroll.scroll_bar_visibility(egui::scroll_area::ScrollBarVisibility::AlwaysHidden); - } - // 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 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 side = view.goto_side.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); - // Turned by → / ← at an edge (`goto_side`): a page or spread wider than the window starts at - // the edge the reader comes from. - let row = shown_row(view, rects).iter().filter_map(|&i| rects.get(i)).copied().reduce(Rect::union).unwrap_or(r); - let (row_left, row_right) = (row.left() - SIDE, row.right() + SIDE); - let target = match side { - Some(from_right) if row_right - row_left > w => { - if from_right { - row_right - w - } else { - row_left - } - } - _ if right - left <= w => { - if left >= x && right <= x + w { - x - } else { - r.center().x - w / 2.0 - } - } - _ => 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 -} - -/// Notes how far and which way the page view scrolled this frame: reader-owned scrolling ends -/// search following, a pan holds back fresh tile renders until it settles, a glide keeps going or -/// stops, and the vertical direction is kept for continuous view's prefetch. Whether a pan is -/// still settling. -fn track_scroll(ui: &egui::Ui, view: &mut DocView, out: &egui::containers::scroll_area::ScrollAreaOutput, 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(); - } - 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.scroll_dir = scroll_direction(view.scroll_dir, scroll_offset.y - view.last_scroll.y, out.content_size != view.scroll_content); - view.scroll_content = out.content_size; - view.last_scroll = scroll_offset; - now_settle < view.pan_hold_until -} - -/// The way the view moves after a frame whose offset changed by `dy` points: down (1) or up (-1) -/// for a move of more than half a point, `dir` otherwise, and 0 when the content's size changed -/// (a zoom or a layout change). -fn scroll_direction(dir: i8, dy: f32, resized: bool) -> i8 { - if resized { - 0 - } else if dy > 0.5 { - 1 - } else if dy < -0.5 { - -1 - } else { - dir - } -} - -/// 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, allowed, author, avail, can_modify, comments_hidden, doc, form, info, keys, 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); - }); - }); - } - find_bar(view, info.pages.len(), avail, tool == QuickTool::EditText && can_modify, 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(), keys, view, info, prefs) { - view.pending_edit = Some(e); - } - if let Some(e) = comments::popups(ui.ctx(), view, info, prefs, comments_hidden, allowed) { - // A click on the composer's Post also takes the focus from a pop-up's box, saving what - // was typed there: both edits land in this frame, so both are kept, in one batch. - view.pending_edit = Some(match view.pending_edit.take() { - Some(first) => Edit::Batch { label: "Edit comment".into(), edits: vec![first, e] }, - None => e, - }); - } - if let Some(e) = crate::edit_text_ui::overlay(ui.ctx(), keys, 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(), keys, view, info, form, primary_down, text_box.as_ref(), today) { - view.pending_edit = Some(e); - } - if let Some(e) = crate::fill_sign::type_box(ui.ctx(), keys, view, info, author) { - view.pending_edit = Some(e); - } - let (typed, text_done) = crate::content_ui::editor(ui.ctx(), keys, view, info, added); - if typed.is_some() { - view.pending_edit = typed; - } - text_done -} - -/// 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 -/// click on a link, field or comment (`clicked_object`) and leaving full screen: the pointer stays -/// active "so that you can click links and open notes" (*Adobe Acrobat Help*, 2019, p. 65), and -/// fields to fill. 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, clicked_object: bool) { - let now = ui.input(|i| i.time); - if let Some(back) = click - && !clicked_object - && 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)); - } - if let Some((due, forward)) = view.present_turn { - if clicked_object || 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))); - } - } -} - /// Follows the link, or the bookmark's action, that was clicked. A link to another file comes /// back, to be opened once the document is no longer borrowed. pub(crate) fn follow_link( @@ -2955,21 +752,18 @@ pub(crate) fn follow_link( None } -/// A finished marquee zoom, a signature rectangle drawn, or an empty signature field clicked. +/// A Snapshot area's bar choice, 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); - } - // The copied area and its menu belong to Snapshot: another tool puts them away. The tool is +fn finish_sign_requests(app: &mut PdfCraftApp, index: usize, mut tool: QuickTool, area_choice: Option) -> QuickTool { + // The copied area and its bar belong to Snapshot: another tool puts them away. The tool is // the app's, not the tab's, so every tab's area goes, not only the one on screen. if tool != QuickTool::Snapshot { for v in &mut app.views { - v.area_pick = None; + v.session.area_pick = None; } } - if let Some(choice) = app.views[index].area_choice.take() - && let Some((page, area)) = app.views[index].area_pick + if let Some(choice) = area_choice + && let Some((page, area)) = app.views[index].session.area_pick { match choice { crate::zoom_snap::AreaChoice::Print => app.open_print_area(page, area), @@ -2977,621 +771,646 @@ fn finish_sign_requests(app: &mut PdfCraftApp, index: usize, mut tool: QuickTool } } // A signature rectangle was drawn, or an empty signature field clicked. - let drawn = app.views[index].sign.drawn.take(); + let drawn = app.views[index].session.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() { + if let Some(field) = app.views[index].session.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); - } + app.sig_open = Some(field); + crate::side_panels::set_panel_visible(app, RightPanel::Signatures, true); } else { - let page = app.views[index].current; + let page = app.views[index].view.current; app.start_signing(page, None, Some(field), None); } } tool } -/// 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 { - if rects.is_empty() { - return Vec::new(); +/// What the page body reads besides the session, settled before the page view is shown: the document, the tool and +/// the frame's facts. One per pass; the body never changes it. +struct PageBodyCx<'a> { + doc: &'a pdfcraft_engine::Document, + info: &'a DocInfo, + /// The tool the page sees ([`page_tool`] keeps the rule that copied comments on the pointer make it Select). + tool: QuickTool, + /// The tool the user picked, before that rule. + chosen: QuickTool, + /// The view's rotation this pass: the page view holds the view state while the body runs. + rotation: u16, + /// The view's current page this pass. + current: usize, + /// Full screen: the page, display and rotation it shows, captured before the page view holds the view state; + /// `None` outside full screen. + present_at: Option, + preparing: bool, + calc_order: bool, + editing_content: bool, + allowed: bool, + can_modify: bool, + can_copy: bool, + comments_hidden: bool, + text_links: bool, + /// No dialog, close prompt or palette over the pages. + unobstructed: bool, + /// Every page's size in view space, unturned by the view (`DocView::page_sizes`). + sizes: &'a [(f32, f32)], + /// What the page tool reads besides the session; its `pages` is filled from the body each run. + tools: page_tools::PageToolCx<'a>, + /// Animation effects apply (the preference after Reduce Motion), for full screen's transitions. + animates: bool, + prefs: &'a comments::CommentPrefs, + /// The user's Redaction Tool Properties hover colour and opacity, a data colour, not a theme role (L-90). + redact_hover: ([f64; 3], f64), + form: &'a Arc>, + units: crate::units::Unit, + find_marks: &'a [TextMark], + table_preview: Option<&'a crate::field_table_ui::Preview>, +} + +/// What a run of the page body reports for the rest of the pass. The body runs twice in a pass (a measuring run with +/// no tool pass, then the real one): each run starts from the default, so the real run's report is the one read. +#[derive(Default)] +struct BodyOut { + /// The canvas view the page view showed this pass. + shown: Option, + /// The view a tool or the canvas set this pass, for [`PageViewOutput::adopt`]. + view: Option, + /// The Crop tool's double-click: open Set Page Boxes on that page. + open_boxes: bool, + /// Fill & Sign asked for a signature (`false`) or initials (`true`) before it can place one. + open_signature: Option, + /// Where the canvas menu opens: a secondary press the tool did not take, or the Menu key. + context: Option, + /// The link clicked, and the JavaScript link by page and annotation index (0-based). + link: Option<(LinkTarget, Option<(usize, usize)>)>, + /// The running tool finished and the app goes back to the Select tool (a stamp placed, a crop committed, Add + /// text done, a field placed). + back_to_select: bool, + /// A Snapshot area drawn: (page, view-space rect). + snapshot: Option<(usize, [f32; 4])>, + /// What the prepare tool asked for this pass. + prepare: Option, + /// Full screen: the page or spread to turn to, forward when `true`. + turn: Option, + /// The Snapshot bar's choice. + area_choice: Option, + /// The selection bar's Copy. + copy_selected: bool, +} + +/// The part list of a pass, in paint order: pictures, paragraphs and added items, links and text links (only under +/// Select and Link), comments (only under Select), fields, sign tabs (painted over their fields), then prepare fields, +/// selected objects and the frame band. A later part outranks an earlier one of the same layer, so this order is the +/// stacking order hit testing ranks on. +fn page_parts_of(ui: &mut egui::Ui, body: &PageBody<'_>, session: &PageSession, cx: &PageBodyCx<'_>) -> (Vec, Vec<(usize, PageXform, Vec)>) { + let mut parts = Vec::new(); + // PLAN: assumed `edit_text_ui::picture_parts(out, session, doc, pages, rotation)`, `edit_text_ui::page_parts` and + // `content_ui::page_parts` with the same shape (pdf-edit-w7, w8, w9 give no argument list). + if cx.editing_content { + crate::edit_text_ui::picture_parts(&mut parts, session, cx.doc, body.pages, cx.rotation); + crate::edit_text_ui::page_parts(&mut parts, session, cx.doc, body.pages, cx.rotation); + crate::content_ui::page_parts(&mut parts, session, cx.doc, body.pages, cx.rotation); } - 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] } + if matches!(cx.tool, QuickTool::Select | QuickTool::Link) { + links_of(session, cx, body).parts(&mut parts); + } + if cx.tool == QuickTool::Select && !cx.comments_hidden { + // PLAN: assumed `comments::bridge::parts(out, session, info, pages, rotation, unobstructed)` (pdf-comments-w8). + crate::comments::bridge::parts(&mut parts, session, cx.info, body.pages, cx.rotation, cx.unobstructed); + } + if !cx.preparing { + // PLAN: assumed `forms_ui::field_parts(out, session, doc, form, pages, rotation, tool)` (pdf-forms-w7 AP-5). + crate::forms_ui::field_parts(&mut parts, session, cx.doc, cx.form, body.pages, cx.rotation, cx.tool); + } + // The sign tabs of each page, after the fields: a tab is painted over its field. + // PLAN: `can_fill` is `can_modify` (pdf-canvas-w15 does not say which right a click that signs needs). + let shown = cx.tool == QuickTool::Select && !cx.preparing; + let mut tabs = Vec::new(); + for placed in body.pages { + let size = cx.sizes.get(placed.page).copied().unwrap_or_default(); + let xf = PageXform::of(placed, cx.rotation, size); + let overlay = overlay_parts(ui, &xf, cx.doc, placed.page, cx.can_modify, shown); + parts.extend(overlay.parts); + tabs.push((placed.page, xf, overlay.tabs)); + } + if cx.preparing { + // PLAN: assumed `prepare::tool::page_parts(out, session, form, info, pages, rotation)` (pdf-forms-w9). + crate::prepare::tool::page_parts(&mut parts, session, cx.form, cx.info, body.pages, cx.rotation); + } + if cx.tool == QuickTool::EditText && cx.can_modify { + // PLAN: assumed `object_ui::page_parts(out, session, pages, rotation)` for the selected objects and the + // frame band (pdf-edit-w10). + crate::object_ui::page_parts(&mut parts, session, body.pages, cx.rotation); + } + (parts, tabs) +} + +/// The links of the pages: followed under Select, edited under the Link tool. +fn links_of<'a>(session: &'a PageSession, cx: &'a PageBodyCx<'_>, body: &'a PageBody<'_>) -> PageLinks<'a> { + let mode = if cx.tool == QuickTool::Link { LinkMode::Edit } else { LinkMode::Follow }; + // PLAN: assumed `PageLinks::new(mode, session, info, doc.links(), pages, rotation).text_links(on).tips(on)` + // (pdf-canvas-w15 names `parts` and `read` only). + PageLinks::new(mode, session, cx.info, cx.doc.links(), body.pages, cx.rotation).text_links(cx.text_links).tips(cx.unobstructed) +} + +/// Whether `phase` is the first pass of a press of `button`. +fn pressed_by(phase: &PressPhase, button: PointerButton) -> bool { + matches!(phase, PressPhase::Down { start, .. } if start.button == button) +} + +/// What a press on a part does, routed by its owner. +fn route_press(session: &mut PageSession, press: &PagePress, cx: &PageBodyCx<'_>, body: &PageBody<'_>, out: &mut BodyOut) { + if pressed_by(&press.phase, PointerButton::Secondary) { + // The page's menu reads what the secondary press went to. + session.menu_for = Some((press.page, press.owner.clone())); + return; + } + let clicked = matches!(press.phase, PressPhase::Release { click: true, .. }); + match &press.owner { + Owner::Link { .. } | Owner::TextLink { .. } => { + // Read before acting: the links borrow the session. + let event = links_of(session, cx, body).read(press); + if let Some(event) = event { + // A click on a link is not a picture pick (pdf-canvas-w12 note 5). + session.pending_pick = None; + match event { + LinkEvent::Follow { target, javascript } => out.link = Some((target, javascript)), + LinkEvent::Select { page, index, clicks } => crate::link_ui::select(session, page, index, clicks), + LinkEvent::Context { page, index } => session.links.context = Some((page, index)), + } + } } - } -} - -/// The pages' context menu, except in full screen, where a right-click turns back a page instead -/// ([`presentation_click_state`]). -fn page_context_menu(resp: &egui::Response, presenting: bool, add: impl FnOnce(&mut egui::Ui)) { - if !presenting { - resp.context_menu(add); - } -} - -/// 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 { - let presenting = view.presentation.is_some() && enabled; - // A right-click goes back a page, as a left click goes forward (*Adobe Acrobat Help*, 2019, - // "Full Screen preferences", p. 69). - if presenting && ui.rect_contains_pointer(navigation_rect) && ui.input(|i| i.pointer.secondary_clicked()) { - return Some(true); - } - let clicked = presenting && 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) - }) - }) - }) -} - -/// 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), + // PLAN: assumed `comments::tool::part_pressed(session, info, press)` (pdf-comments-w8). + Owner::Comment { .. } => crate::comments::tool::part_pressed(session, cx.info, press), + // PLAN: assumed `forms_ui::field_press(session, doc, form, press)` (pdf-forms-w5). + Owner::Field { .. } => crate::forms_ui::field_press(session, cx.doc, cx.form, press), + Owner::SignTab { field } => { + if clicked && let Some(field) = cx.form.get(*field) { + session.sign.field = Some(field.name.clone()); + } } - } else if view.goto_point.is_none() && zoom_delta == 1.0 { - // The find step has been laid out and no zoom is easing on: zoom at the pointer again. - // egui spreads a ⌘/Ctrl-wheel notch over about a quarter of a second; while the pointer - // is off the page view that zoom waits, and the hold must outlast it, or the rest of it - // anchors on the pointer once it is back and the match drifts off the middle. - view.find_hold = None; + // PLAN: assumed `prepare::tool::field_press(session, form, press)` (pdf-forms-w9). + Owner::PrepareField { .. } => crate::prepare::tool::field_press(session, cx.form, press), + // PLAN: assumed `edit_text_ui::paragraph_press(session, doc, press)` and `content_ui::added_press(session, + // doc, press)` (pdf-edit-w7, w8). + Owner::Paragraph { .. } => crate::edit_text_ui::paragraph_press(session, cx.doc, press), + Owner::Added { .. } => crate::content_ui::added_press(session, cx.doc, press), + // PLAN: assumed `edit_text_ui::picture_press(session, doc, press)` and `object_ui::objects_press(session, + // press)` (pdf-edit-w9, w10). + Owner::Picture { .. } => crate::edit_text_ui::picture_press(session, cx.doc, press), + Owner::Objects => crate::object_ui::objects_press(session, press), } } -/// 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, invert: bool) -> (Vec2, Vec2) { - let auto_delta = if unobstructed { - view.auto_scroll.update(ui, avail, false, invert) - } else { - view.auto_scroll.cancel(); - Vec2::ZERO +/// The page body, run by the page view on every run of its canvas body. Its order is the paint order, and with it +/// the stacking order hit testing ranks on: the placed pages recorded, the parts registered, the tool host, then the +/// overlays. +fn page_body(ui: &mut egui::Ui, body: &PageBody<'_>, session: &mut PageSession, momentary: &mut Momentary, cx: &PageBodyCx<'_>, out: &mut BodyOut) { + *out = BodyOut { shown: Some(body.view), ..BodyOut::default() }; + // 1. This pass's placement, before anything that maps through it. + session.placed.clear(); + session.placed.extend_from_slice(body.pages); + + // 2-3. Every part on the pages, in one control: hit priority ranks parts inside one control only. + let (parts, tabs) = page_parts_of(ui, body, session, cx); + // PLAN: assumed `forms_ui::focus_owner(&FormView) -> Option` for the focused field (pdf-forms-w7 AP-6). + let focus = crate::forms_ui::focus_owner(&session.forms); + let parts_out = PageParts::new(&parts).focus(focus).show_at(ui, body.rect); + if let Some(press) = &parts_out.press { + // Any press on a page ends Select All of the document, on a link too. + if matches!(press.phase, PressPhase::Down { .. }) { + session.all_text = false; + } + route_press(session, press, cx, body, out); + } + if let Some((owner, page)) = &parts_out.focused { + // Focus arrived on a field (Tab, a request or a click): the field opens, a text field with its text selected. + // PLAN: assumed `forms_ui::field_focused(session, doc, form, owner, page)` (pdf-forms-w5 AP-6). + crate::forms_ui::field_focused(session, cx.doc, cx.form, owner, *page); + } + if let Some((owner, key)) = &parts_out.key { + // PLAN: assumed `forms_ui::field_key(session, doc, form, owner, key)` (pdf-forms-w5). + crate::forms_ui::field_key(session, cx.doc, cx.form, owner, key); + } + + // 4. The tool host, in the real run only: a measuring run has no tool pass. + if let Some(pass) = body.pass { + if matches!(pass.press.phase, PressPhase::Down { .. }) { + // A press nobody's part took, on the page or the gap between pages, ends Select All of the document. + session.all_text = false; + } + let tool_cx = PageToolCx { pages: body.pages, ..cx.tools }; + let mut bench = page_tools::ToolBench::default(); + let mut fill = None; + let mut tool = page_tool(cx.chosen, tool_cx, &mut *session, &mut bench, &mut fill); + let reply = ToolHost::new().momentary(momentary).run(ui, pass, &mut tool); + let mut finish = tool.finish(); + finish.apply(fill, session, &tool_cx); + if let Some(why) = finish.refused.take() { + session.objects.notice = Some(why.into()); + } + out.view = reply.view; + out.context = reply.context; + out.back_to_select = finish.back_to_select; + out.snapshot = finish.snapshot; + out.open_boxes = finish.open_boxes; + out.open_signature = finish.open_signature; + let outcome = session.prepare.take_outcome(); + out.back_to_select |= outcome.placed; + out.prepare = Some(outcome); + } + + // 5. The overlays. + for (page, xf, page_tabs) in &tabs { + PageOverlays::new(*page, *xf, cx.doc, page_tabs, &session.compare_marks, &mut session.flash) + .highlight_fields(session.highlight_fields) + .show_at(ui, body.rect); + } + if cx.editing_content { + // PLAN: assumed `(ui, body, session, doc, rotation)` for the edit controls (pdf-edit-w7..w11). + crate::edit_text_ui::picture_controls(ui, body, session, cx.doc, cx.rotation); + crate::object_ui::object_controls(ui, body, session, cx.doc, cx.rotation); + crate::content_ui::content_controls(ui, body, session, cx.doc, cx.rotation); + crate::edit_text_ui::paragraph_controls(ui, body, session, cx.doc, cx.rotation); + } + if cx.tool == QuickTool::Link { + crate::link_ui::link_outlines(ui, body, session, cx.doc, cx.rotation); + } + if !cx.comments_hidden { + // PLAN: assumed `comments::overlay::show(ui, body, session, info, prefs, tool, redact_hover)` (pdf-comments-w7, + // L-90: the redaction hover is the user's setting, passed as a data colour). + crate::comments::overlay::show(ui, body, session, cx.info, cx.prefs, cx.tool, cx.redact_hover); + } + if cx.calc_order { + let hovered = match &parts_out.hovered { + Some(Owner::Field { field, .. } | Owner::PrepareField { field, .. }) => cx.form.get(*field).map(crate::calc_order_ui::Focus::of_field), + _ => None, + }; + let selected = session.prepare.selected.as_ref().map(|(name, _)| name.as_str()); + // PLAN: assumed `CalcOrderOverlay::new(&CalcOrderView, pages, rotation, generation, selected, hovered, + // viewport)` (pdf-forms-w12 gives `new(.., viewport: body.rect)`). + crate::calc_order_ui::CalcOrderOverlay::new(&session.calc_order, body.pages, cx.rotation, cx.doc.edit_generation(), selected, hovered, body.rect) + .show_at(ui, body.rect); + } + if let Some(preview) = cx.table_preview { + // PLAN: assumed `field_table_ui::TablePreview::new(&Preview, pages, rotation)` (pdf-forms-w11). + crate::field_table_ui::TablePreview::new(preview, body.pages, cx.rotation).show_at(ui, body.rect); + } + // The find marks under any tool, and the text selection where the Select tool is not the one painting it. + let texts = selection::DocTexts::new(&session.texts, &session.text_failed, cx.rotation, cx.sizes); + let paints_selection = !page_tools::tool_selects_text(cx.tool, cx.preparing); + let marks = TextMarks::new(body.pages, &texts, cx.find_marks); + let marks = match session.text.selection.filter(|_| paints_selection) { + Some(selection) => marks.selection(selection), + None => marks, }; - - // 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(); + marks.show_at(ui, body.rect); + // PLAN: assumed `selection::show_picked(ui, body, session, info)` (pdf-canvas-w12). + selection::show_picked(ui, body, session, cx.info); + if let Some(at) = cx.present_at { + // PLAN: `PresentFrame::hide_pointer` asks for `CursorPriority::Hidden`; the page body has no `BodyCx` to claim + // it through, so the pointer is not hidden yet (pdf-canvas-w18). + let (now, pointer) = ui.input(|i| (i.time, i.pointer.hover_pos())); + let frame = presenter::frame(&mut session.presenter, body, at, cx.info, ui.painter(), now, cx.animates, pointer); + out.turn = frame.step; } - (auto_delta, edge_delta) -} - -/// What decides whether touchpad momentum goes on. -#[derive(Clone, Copy)] -struct GlideCx { - now: f64, - may_glide: bool, - key_scroll: f32, - key_side: 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, key_side, auto_delta, zoom_delta, edge_delta, wheel_scrolled } = *cx; - let over_page = ui.rect_contains_pointer(avail); - view.fling.read(&crate::motion::gesture_wheel_events(ui.ctx()), now, may_glide && over_page); - let interrupted = glide_interrupted(ui); - if !may_glide || interrupted || key_scroll != 0.0 || key_side != 0.0 || auto_delta != Vec2::ZERO || zoom_delta != 1.0 { - view.fling.stop(); + if cx.tool == QuickTool::EnhanceCamera { + crate::camera_ui::show_quad(ui, body, session, cx.can_modify); + crate::camera_ui::bar(ui, body, session, cx.can_modify); } - let glide = view.fling.step(now); - if view.fling.gliding() { - ui.ctx().request_repaint(); + if cx.chosen == QuickTool::Snapshot { + let sizes = cx.sizes; + out.area_choice = crate::zoom_snap::area_bar(ui, body.rect, body.pages, session.area_pick, cx.rotation, |page| { + sizes.get(page).copied().unwrap_or_default() + }); } - if wheel_scrolled || auto_delta != Vec2::ZERO || edge_delta != Vec2::ZERO || glide != Vec2::ZERO { - view.end_find_following(); + if cx.unobstructed && matches!(cx.tool, QuickTool::Select | QuickTool::ColumnSelect) { + // PLAN: assumed `selection_bar(ui, body, session, info, prefs, may_mark, can_copy)`, the old + // `selection_actions` arguments after `body` (pdf-canvas-w12 note 4 gives `(ui, body, view, ..)`). + out.copy_selected = selection::selection_bar(ui, body, session, cx.info, cx.prefs, cx.allowed && !cx.comments_hidden, cx.can_copy); } - glide -} - -/// The tool the page sees this frame, and whether copied comments hang on the pointer. Those -/// take the next click whatever tool is on: the page sees the Select tool until the bundle is -/// placed or let go, and no form field, added content or field being prepared takes the click -/// either. -fn page_tool(view: &DocView, chosen: QuickTool) -> (QuickTool, bool) { - let placing = matches!(view.comments.gesture, Some(comments::Gesture::Place { .. })); - (if placing { QuickTool::Select } else { chosen }, placing) -} - -/// 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, + if cx.unobstructed + && let Some(page) = cx.info.pages.get(cx.current) + { + page_size_hint(ui, body, page, cx.units); } } -/// 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)); +/// The text layers the pass asks for, as `(visible, rest)` for [`DocView::want_text`], which skips pages whose layer is +/// held, failed or on its way: the pages in view (none under the Hand tool, which selects nothing), then every page a +/// selection covers, and while a search runs every page from the current one on, so a match far off is found. +fn text_demand(view: &DocView, visible: std::ops::Range, hand: bool) -> (Vec, Vec) { + let count = view.page_count; + let visible: Vec = if hand { Vec::new() } else { visible.collect() }; + let mut rest: Vec = view.session.text.selection.iter().flat_map(|s| s.pages()).collect(); + if count > 0 && view.find.as_ref().is_some_and(|f| !f.case_query.trim().is_empty()) { + let current = view.view.current; + rest.extend((0..count).map(|k| (current + k) % count)); } - now_scale < view.sharp_hold_until + (visible, rest) } -/// 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)); - } - if let Some(fy) = fy { - scroll = scroll.vertical_scroll_offset((r.top() - y_shift + fy * r.height() - rel.y).clamp(0.0, max_y)); - } - } - scroll -} - -/// Where the `shown` pages sit in the scroll content, as how far the content starts into the -/// layout and how tall it is. Scrolling continuously every page scrolls; otherwise only the -/// current row does, the content being its bounding box plus margins. Pages that fit a view -/// `view_height` tall sit in its middle, the spare height shared above and below (#5708): the -/// content fills the view, so there is nothing to scroll, and starts on a whole physical pixel -/// as the layout's pages do, or their edges would blur and the seams between them open. -fn vertical_placement(continuous: bool, rects: &[Rect], shown: &[usize], view_height: f32, pixels_per_point: f32) -> (f32, f32) { - let Some(r) = shown.iter().filter_map(|&i| rects.get(i)).copied().reduce(Rect::union) else { return (0.0, 0.0) }; - if fits_height(r, view_height, pixels_per_point) { - return (((r.center().y - view_height / 2.0) * pixels_per_point).round() / pixels_per_point, view_height); - } - if continuous { (0.0, r.bottom() + MARGIN) } else { (r.top() - MARGIN, r.height() + 2.0 * MARGIN) } -} - -/// Whether the pages in `r` show whole in a view `view_height` tall, without their margins. -/// Within half a physical pixel, which is all that snapping the pages to pixels can add: a -/// fitting page is centred and has nothing to scroll, so any more would be cut off unseen. -fn fits_height(r: Rect, view_height: f32, pixels_per_point: f32) -> bool { - let slack = if pixels_per_point.is_finite() && pixels_per_point > 0.0 { 0.5 / pixels_per_point } else { 0.0 }; - r.height() <= view_height + slack -} - -/// 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 (form fields, comments, -/// signature badges and sign tabs) and render requests. +/// Draws the document tab at `index` in the room left in `ui`: [`document_area_at`] with the available rect. pub fn document_area(app: &mut PdfCraftApp, index: usize, ui: &mut egui::Ui) { - let t = Tokens::get(ui.ctx()); - let can_paste_key = egui::Id::unique("can-paste-image"); - let can_paste_image = if ui.input(|i| i.pointer.secondary_pressed()) { - let can = app.can_paste_image(); - ui.data_mut(|d| d.insert_temp(can_paste_key, can)); - can - } else { - ui.data(|d| d.get_temp(can_paste_key)).unwrap_or(false) - }; - // Keyboard scrolling applies to this frame's page view only, never later. - let key_scroll = std::mem::take(&mut app.views[index].key_scroll); - let key_side = std::mem::take(&mut app.views[index].key_side); - if key_scroll != 0.0 || key_side != 0.0 { - app.views[index].end_find_following(); - } + let rect = ui.available_rect_before_wrap(); + // The output is for callers that place two views (Compare); a whole tab has nothing to sync. + let _ = document_area_at(app, index, rect, ui); +} + +/// Draws the document tab at `index` in `rect`: its notice bars, then its pages in the page view (or the Organize +/// grid), with the page body's parts, tools and overlays, and acts on what the pass asked for. Returns the page view's +/// output, for callers that place several views (Compare). +/// +/// It records the pass's facts on the view for readers between frames (`textures`, `spacing`, the viewport, the +/// canvas view, the middle-button scroll); nothing in the next pass reads them to compute its result. +pub fn document_area_at(app: &mut PdfCraftApp, index: usize, rect: Rect, ui: &mut egui::Ui) -> Option { + // The seam returns `None` for a tab that closes, has no pages or shows the Organize grid: no page view runs there, + // and `PageViewOutput` cannot be built outside its crate. // 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() + if let Some(f) = app.views.get_mut(index).and_then(|v| v.find.as_mut()) && f.in_panel && !search_open { f.in_panel = false; } if close_requested_tab(app, index) { - return; + return None; } - 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 doc_id = app.views.get(index)?.id; + let doc = app.session.get(doc_id)?; + // PLAN: the print preview is the dialog's own `Thumbnails` store (pdf-canvas-w10 note 2); no view keeps + // print rasters to drop while `HostedPrint` is closed, so the old `Dialog::Print` check has nothing left to guard. let show_secured_notice = app.show_secured_notice; // Offer to lock a just-placed signature (#2149) on the same terms the save-time question // asks: one is still there, saving doesn't lock it anyway, and the document isn't signed. - let lock_offer = !app.flatten_fill_sign_on_save - && app.placed_signatures.contains(&app.views[index].id) - && doc.info.annotations.iter().any(|a| a.fill_sign) - && !doc.is_signed(); + let lock_offer = + !app.flatten_fill_sign_on_save && app.placed_signatures.contains(&doc_id) && doc.info.annotations.iter().any(|a| a.fill_sign) && !doc.is_signed(); 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, lock_offer, crate::sign_ui::banner(&doc.signatures), ui, &t); + // PLAN: assumed `notices(view, doc, secured, repaired, lock_offer, banner, ui)`: pdf-canvas-w16 drops the tokens + // argument and gives no other change. + let notice = notices(view, doc, secured, repaired, lock_offer, crate::sign_ui::banner(&doc.signatures), ui); apply_notice(app, index, notice); - let Some(doc) = app.session.get(app.views[index].id) else { return }; + let doc = app.session.get(doc_id)?; let info = &doc.info; + if info.pages.is_empty() { + let _ = Text::new(tl!("This document has no pages.")).show(ui); + return 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; - // A menu click can open a dialog after the frame's first look. - app.page_keys = app.page_keys.also(app.covers_pages()); - let keys = app.page_keys; - let organize_zoom = app.organize_zoom; - let invert_middle = app.invert_middle_drag; + let unobstructed = !app.modal_open() && !app.palette_open; + if app.views[index].organize { + let invert_middle = app.navigation_options().invert_middle; + organize_grid(&mut app.views[index], doc, &mut organize::GridCx { ui, zoom: &mut app.organize_zoom, invert_middle }); + return None; + } + // The room under the notice bars, inside the rect the caller gave. + let rect = rect.intersect(ui.available_rect_before_wrap()); + + let preparing = app.is_preparing(); + // PLAN: assumed `side_panels::panel_visible(app, panel) -> bool` for the left panel's visibility (`left_open` is + // not a field after L-136; pdf-shell-w13 names only the setter). + // Prepare a form ▸ Calculation order: the order's steps and links on the page. + let calc_order = preparing && crate::side_panels::panel_visible(app, crate::LeftPanel::CalculationOrder); + // Edit a PDF: added text and images can be selected, moved and edited. + let editing_content = crate::side_panels::panel_visible(app, crate::LeftPanel::Tool("edit")) + || matches!(app.quick_tool, QuickTool::AddText | QuickTool::EditText); + let chosen = app.quick_tool; + let navigation = app.navigation_options(); + let presenting = app.views[index].presenting(); + let allowed = doc.allows_annotation(); + let can_modify = doc.allows_modification(); + let form = doc.form.clone(); + let paper = app.session.reading_colors(doc_id).and_then(|c| c.params).map_or(Color32::WHITE, |p| { + let [r, g, b] = p.background; + Color32::from_rgb(r, g, b) + }); + let table_preview = crate::field_table_ui::preview(&mut app.dialogs, doc_id); 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, doc, unobstructed, keys, app.show_page_edge_shadows, invert_middle, ui, &t); - app.organize_zoom = view.grid_zoom(); - return; + // PLAN: assumed `page_tools::seen_tool(&PageSession, QuickTool) -> QuickTool`, the placing rule `page_tool` + // applies (copied comments on the pointer make the page see Select), so the parts gate on the same tool. + let tool = page_tools::seen_tool(&view.session, chosen); + if preparing { + crate::prepare::after_refresh(&mut view.session, &form); + } else { + view.session.prepare.selected = None; + } + view.session.objects.prepare(doc, tool == QuickTool::EditText && can_modify); + let scale = view.render_scale(ui.ctx().pixels_per_point()); + let session = &mut view.session; + session.text_background.prepare(ui.ctx(), doc, session.line_editor.as_ref(), session.content.draft.as_ref(), scale); + let added = if editing_content { doc.added().to_vec() } else { Vec::new() }; + if editing_content { + crate::content_ui::after_refresh(&mut view.session, &added); + } else { + view.session.content.selected = None; + } + view.session.move_background.prepare(ui.ctx(), doc, &view.session.content, scale); + + let find_marks: Vec = view.find.as_ref().map(Find::marks).unwrap_or_default(); + let present_at = presenting.then_some(presenter::PresentAt { current: view.view.current, display: view.view.display, rotation: view.view.rotation }); + let border = if view.view.page_gaps { PageBorder::DropShadow } else { PageBorder::None }; + let keep = view.session.presenter.keep_pages(); + if view.momentary_options != navigation { + view.momentary = Momentary::new(navigation); + view.momentary_options = navigation; + } + let mut body_out = BodyOut::default(); + let DocView { view: state, session, momentary, revisions, reports, page_sizes, .. } = &mut *view; + // PLAN: assumed app fields (pdf-hub-w1, pdf-forms-w5): `host_scope: HostScope`, `wake: Wake`, `fill_text_size`, + // `fill_text_color`, `fill_text_border`, `fill_signature`, `fill_initials`, `fill_date_text`, `stamp_by_line`, + // `custom_stamp_choice: Option<(CustomStamp, Option)>`, `animation_effects` and `motion`. + let tools = page_tools::PageToolCx { + doc, + info, + form: form.as_slice(), + pages: &[], + sizes: &page_sizes[..], + rotation: state.rotation, + allowed, + can_modify, + can_crop: can_modify, + preparing, + presenting, + units: app.units, + navigation, + host: &app.host_scope, + wake: &app.wake, + author: &app.comment_prefs.author, + date_text: &app.fill_date_text, + fill: page_tools::FillPrefs { + text_size: app.fill_text_size, + text_color: app.fill_text_color, + text_border: app.fill_text_border, + signature: app.fill_signature.as_ref(), + initials: app.fill_initials.as_ref(), + }, + by_line: &app.stamp_by_line, + custom_stamp: app.custom_stamp_choice.as_ref().map(|(stamp, line)| (stamp, line.as_deref())), + }; + let cx = PageBodyCx { + doc, + info, + tool, + chosen, + rotation: state.rotation, + current: state.current, + sizes: &page_sizes[..], + tools, + animates: app.animation_effects.animates(app.motion.reduced), + present_at, + preparing, + calc_order, + editing_content, + allowed, + can_modify, + can_copy: doc.allows_copying(), + comments_hidden: doc.comments_hidden(), + text_links: app.text_links, + unobstructed, + prefs: &app.comment_prefs, + redact_hover: (app.redact_prefs.hover_fill, app.redact_prefs.opacity), + form: &form, + units: app.units, + find_marks: &find_marks, + table_preview: table_preview.as_ref(), + }; + let source = DocPages::new(&app.session, doc_id).rotated(state.rotation).revisions(revisions).reports(reports); + // A modal over the pages blocks the canvas's keys and presses in the framework, so the view needs no gate here. + let out = PageView::new(tl!("Pages"), &source, state, DataColor::new(paper)) + .navigation(navigation) + .border(border) + .keep(&keep) + .show_at(ui, rect, |ui, body| page_body(ui, body, session, momentary, &cx, &mut body_out)); + if let Some(canvas) = &body_out.view { + out.adopt(&mut view.view, canvas); + } + if out.toggle_white_space { + view.view.hide_white_space = !view.view.hide_white_space; + } + // A turn the presenter's display time or a full-screen key asked for, then a click's turn once the + // double-click time has passed with no object clicked and no selection made (#2070). + let now = ui.input(|i| i.time); + let has_selection = view.session.text.selection.is_some(); + let click = (presenting && matches!(out.canvas.press.phase, PressPhase::Release { click: true, .. })).then(|| presenter::PresentClick { + forward: !out.canvas.press.mods.shift, + clicks: if out.canvas.press.double_pressed() { 2 } else { 1 }, + }); + let delay = ui.ctx().options(|o| o.input_options.max_double_click_delay); + let cancels = body_out.link.is_some() || has_selection; + let click_turn = if presenting { view.session.presenter.click_turn(ui.ctx(), click, cancels, now, delay) } else { None }; + if let Some(forward) = body_out.turn.or(click_turn) { + view.view.step(forward); + } + // The records readers between frames take; no pass reads them back. + view.textures = out.textures; + view.spacing = Some(out.spacing); + view.viewport = rect; + view.canvas = body_out.view.or(body_out.shown); + view.middle_scrolling = out.canvas.auto_scrolling; + // Addresses written as plain text are found once per text layer that has arrived; the link parts read them. + if app.text_links { + for page in out.visible.clone() { + view.refresh_text_links(page); + } + } + // Text layers: the queue is made once, from the app's job host; each pass takes what has arrived and asks for what + // it needs. + if view.session.text_queue.is_none() { + let ctx = ui.ctx().clone(); + let wake = craft::host::Wake::new(move || ctx.request_repaint()); + view.session.text_queue = Some(JobQueue::new(app.host.jobs_shared().clone(), wake, QueueOptions { name: "text-layers", ..QueueOptions::default() })); + } + let (visible_pages, rest_pages) = text_demand(view, out.visible.clone(), chosen == QuickTool::Hand); + view.want_text(&app.session, &visible_pages, &rest_pages); + + find_bar(view, info.pages.len(), rect, tool == QuickTool::EditText && can_modify, ui); + // Whether the clipboard holds a picture, read only when this pass opens the page menu (a clipboard read is slow). + // PLAN: a menu left open from an earlier pass keeps its row only if `page_menu` reads the clipboard itself. + let can_paste_image = body_out.context.is_some() && app.can_paste_image(); + let view = &mut app.views[index]; + // The in-place editors and comment windows over the pages, in their old order, mapped through this pass's + // placement. + let session = &mut view.session; + // PLAN: assumed the comments A-4 shapes `composer(ui, session, info, prefs)` and `note_popups(ui, session, info, + // prefs, hidden, allowed)` (note 18 names `composer(ui, view, info, prefs)` and `note_popups(ui, ..)`). + if let Some(e) = crate::comments::composer(ui, session, info, &app.comment_prefs) { + session.pending_edit = Some(e); + } + if let Some(e) = crate::comments::note_popups(ui, session, info, &app.comment_prefs, doc.comments_hidden(), allowed) { + // A click on the composer's Post also takes the focus from a pop-up's box, saving what + // was typed there: both edits land in this pass, so both are kept, in one batch. + session.pending_edit = Some(match session.pending_edit.take() { + Some(first) => Edit::Batch { label: "Edit comment".into(), edits: vec![first, e] }, + None => e, + }); + } + let text_box = crate::forms_ui::text_box(doc, session, &form); + // PLAN: assumed `forms_ui::editor::show(ui, session, info, form, text_box, today)` and + // `fill_sign::type_box::show(ui, session, info, author)` (pdf-forms-w5, w9). + if let Some(e) = crate::forms_ui::editor::show(ui, session, info, &form, text_box.as_ref(), app.session.today()) { + session.pending_edit = Some(e); + } + if let Some(e) = crate::fill_sign::type_box::show(ui, session, info, &app.comment_prefs.author) { + session.pending_edit = Some(e); } - 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.size(), 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 }; - // Wheel zoom works in a visible window without focus, as wheel scrolling does; the other gestures need focus. - let zoom_enabled = unobstructed && ui.is_enabled(); - let navigation_enabled = zoom_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, zoom_enabled); - view.viewport_screen = avail; - let (auto_delta, edge_delta) = auto_scroll_deltas(ui, view, avail, unobstructed, invert_middle); - - 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(); - reset_interrupted_wheel(ui, view, zoom_delta != 1.0 || key_scroll != 0.0 || auto_delta != Vec2::ZERO || edge_delta != Vec2::ZERO); - // 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 }); - let now = ui.input(|i| i.time); - let animates = app.animation_effects.animates(app.motion.reduced); - let wheel_enabled = navigation_enabled && unobstructed && !middle_gesture; - let Wheel { precise_scroll, line_base, coarse_scroll, has_page, paging_owns_vertical } = - read_wheel(ui, view, avail, single_paging, edge_turned, wheel_enabled, animates); - let may_glide = !paging_owns_vertical && !middle_gesture && navigation_enabled && unobstructed && animates; - let wheel_scrolled = precise_scroll != Vec2::ZERO || line_base != Vec2::ZERO || coarse_scroll != Vec2::ZERO || has_page; - let motion = GlideCx { now, may_glide, key_scroll, key_side, 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 = if view.continuous { (0..rects.len()).collect() } else { row.clone() }; - let (y_shift, content_h) = vertical_placement(view.continuous, &rects, &visible_pages, avail.height(), ui.ctx().pixels_per_point()); - - let mut scroll = page_scroll_area( + let refused = view.session.objects.notice.take(); + let form_notice = view.session.forms.notice.take(); + let mut tool = app.quick_tool; + if tool != QuickTool::EditText { + view.session.image_selection = None; + crate::content_ui::release_image_selection(&mut view.session, &added); + } + if tool != QuickTool::Link { + view.session.links.selected = None; + } + // A stamp placed, a crop committed, Add text done or a field placed: one, then back to selecting (Acrobat's + // default without "Keep tools pinned"). + if body_out.back_to_select { + tool = QuickTool::Select; + } + let prepare = body_out.prepare.take().unwrap_or_default(); + let field_props = prepare.properties.then(|| view.session.prepare.selected.clone()).flatten(); + let (clicked_link, javascript_link) = body_out.link.take().map_or((None, None), |(target, js)| (Some(target), js)); + // The page's menu, opened by the context request of this pass or still open from an earlier one. + let menu_for = view.session.menu_for.as_ref().map(|(_, owner)| owner.clone()); + let pick = page_menu::show( ui, - view, - &ScrollGeometry { rects: &rects, y_shift, content_w, content_h, avail, middle_gesture, hand: app.quick_tool == QuickTool::Hand }, + body_out.context.as_ref(), + &out.canvas.response, + menu_for, + &mut app.views[index], + &page_menu::PageMenuCx { + doc, + info, + prefs: &app.comment_prefs, + rights: comments::MenuRights { allowed, can_paste: app.comment_clipboard.is_some(), can_modify }, + recent: &app.recent_colours, + tool, + preparing, + form: &form, + can_copy: doc.allows_copying(), + can_paste_image, + }, ); - 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, placing) = page_tool(view, 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 can_paste_comments = app.comment_clipboard.is_some(); - 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 tool { - QuickTool::CustomStamp(i) => app.custom_stamps.get(i).cloned(), - _ => None, - }; - let custom_line = custom_stamp.as_ref().and_then(|cs| cs.line.as_deref()).map(|t| app.session.stamp_line(t, &author)); let mut open_props: Option<(usize, usize)> = None; let mut recolour: Option = 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(), keys); - 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); - - 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 prepare_tab_order = (preparing && view.prepare.show_tab_numbers).then(|| crate::forms_ui::tab_order(&form, info)); - let env = PageEnv { - added: &added, - allowed, - animates, - author: &author, - auto_delta, - avail, - coarse_scroll, - by_line: &by_line, - calc_order, - can_copy, - can_paste_comments, - placing, - can_crop, - can_fill, - can_modify, - comments_hidden, - content_h, - content_w, - custom_line: &custom_line, - 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, - key_side, - keys, - middle_gesture, - modal, - navigation_enabled, - paper, - show_page_edge_shadows: app.show_page_edge_shadows, - ppp, - precise_scroll, - prefs, - preparing, - prepare_tab_order: prepare_tab_order.as_deref(), - rects: &rects, - redact_mark, - scale, - selection_wheel, - selects_text, - signature: &signature, - single_paging, - t: &t, - table_preview: &table_preview, - tag, - text_style: &text_style, - text_links: app.text_links, - tool, - units, - unobstructed, - visible_pages: &visible_pages, - y_shift, - fill_text_size: app.fill_text_size, - fill_text_color: app.fill_text_color, - fill_text_border: crate::fill_sign::TextBorder { - width: app.fill_text_border, - color: app.fill_text_border_color, - shape: app.fill_text_border_shape, - }, - today, - can_paste_image, - }; - let mut page_out = PageOut::default(); - // Keyed by the view, not the document: with one document in both panes of split view, shared - // ids gave the main pane's clicks on the page to the second pane's widgets. - let out = page_scroll(ui, scroll, egui::Id::unique(("page-view-scope", view.view_key())), app.show_page_edge_shadows, |ui, viewport| { - draw_pages(ui, viewport, view, &env, &mut page_out, &mut app.signature_preview) - }); - let PageOut { - canvas_action, - clicked_link, - javascript_link, - comment_notice, - copy_comments, - mut copy_selected, - field_menu, - field_placed, - mut field_props, - hover_text, - mut image_action, - open_boxes, - open_initials, - open_signature, - open_table, - page_action, - paste_comments_at, - primary_down, - on_object, - mut refused, - row_on_screen, - 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) - }); - // Within a point, as above: at an edge of the scrolled content, or of the current page or - // spread shown whole that way (in continuous view the content is as wide as the widest page, - // and a narrower current page shows whole inside it). - let max_x = (out.content_size.x - out.inner_rect.width()).max(0.0); - let inner = out.inner_rect; - view.side_edges = Some(( - out.state.clamped_offset().x <= 1.0 || row_on_screen.is_some_and(|r| r.left() >= inner.left() - 1.0), - out.state.clamped_offset().x >= max_x - 1.0 || row_on_screen.is_some_and(|r| r.right() <= inner.right() + 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 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 }); - - let text_done = frame_overlays(ui, view, &env, primary_down, hover_text); - 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(), keys, view, info, &mut tool, allowed); - if preparing { - crate::prepare::keys(ui.ctx(), keys, view); - } - if tool != QuickTool::EditText { - view.image_selection = None; - crate::content_ui::release_image_selection(view, &added); - } - if editing_content { - crate::content_ui::keys(ui.ctx(), keys, view, tool == QuickTool::EditText); - } - if tool == QuickTool::Link { - crate::link_ui::keys(ui.ctx(), keys, 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. + let mut image_action = pick.image; + match pick.canvas { + Some(comments::CanvasAction::Edit(e)) => app.views[index].session.pending_edit = Some(*e), Some(comments::CanvasAction::OpenComments) => { - app.right = Some(RightPanel::Comments); app.comments_panel_closed = false; + crate::side_panels::set_panel_visible(app, RightPanel::Comments, true); } Some(comments::CanvasAction::Properties(p, i)) => open_props = Some((p, i)), Some(comments::CanvasAction::Colour(c)) => recolour = Some(c), @@ -3599,40 +1418,36 @@ pub fn document_area(app: &mut PdfCraftApp, index: usize, ui: &mut egui::Ui) { Some(comments::CanvasAction::CopyImageFile(p, i)) => image_action = Some(crate::edit_text_ui::ImageAction::CopyFile(p, i)), None => {} } - schedule_presentation_turn(ui, view, present, clicked_link.is_some() || on_object && present.is_some()); + if let Some(why) = refused { + app.notify_error(why); + } + if let Some((page, area)) = body_out.snapshot { + app.finish_marquee(index, (page, area)); + } let remote_open = follow_link(app, index, clicked_link); if let Some((page, link)) = javascript_link { - let id = app.views[index].id; - app.run_link_script(id, page, link); + app.run_link_script(doc_id, page, link); } - if tool == QuickTool::Crop && cropped { - tool = QuickTool::Select; - } - let tool = finish_sign_requests(app, index, tool); + let tool = finish_sign_requests(app, index, tool, body_out.area_choice); app.quick_tool = tool; let requests = FrameRequests { open_props, field_props, - field_menu, + field_menu: pick.field, image_action, - page_action, - refused, - open_signature, - open_initials, - open_boxes, - open_table, + page_action: pick.page, form_notice, - copy_selected, - copy_comments, - paste_comments_at, - comment_notice, + copy_selected: body_out.copy_selected, recolour, remote_open, + open_table: prepare.table, + open_boxes: body_out.open_boxes, + open_signature: body_out.open_signature, form, - generation, - avail, + generation: app.session.get(doc_id).map_or(0, |d| d.edit_generation()), }; - apply_frame_requests(app, index, ui, requests); + apply_frame_requests(app, index, requests); + Some(out) } /// What the frame's input asked the app to do, once the document is no longer borrowed. @@ -3642,52 +1457,41 @@ struct FrameRequests { field_menu: Option, image_action: Option, page_action: Option, - refused: Option, - open_signature: bool, - open_initials: bool, - open_boxes: bool, - open_table: Option<(usize, [f64; 4])>, form_notice: Option, copy_selected: bool, - /// Copy comments / Paste comments from the page's menu or a Comments panel card, and what - /// the comment tools have to say. - copy_comments: bool, - paste_comments_at: Option<(usize, [f64; 2])>, - comment_notice: Option<&'static str>, /// A colour picked for every selected comment (Colour in the page's menu). recolour: Option, remote_open: Option<(pdfcraft_engine::DocId, String, pdfcraft_render::RemoteDestination)>, + /// A table drawn with the prepare tool: its page and user-space rectangle. + open_table: Option<(usize, [f64; 4])>, + /// The Crop tool's double-click: open Set Page Boxes on the current page. + open_boxes: bool, + /// Fill & Sign needs a signature (`false`) or initials (`true`) first. + open_signature: Option, form: Arc>, generation: u64, - avail: Rect, } /// Opens the dialogs and runs the app commands the frame asked for. #[allow(clippy::cognitive_complexity)] -fn apply_frame_requests(app: &mut PdfCraftApp, index: usize, ui: &mut egui::Ui, requests: FrameRequests) { +fn apply_frame_requests(app: &mut PdfCraftApp, index: usize, requests: FrameRequests) { let FrameRequests { open_props, field_props, field_menu, image_action, page_action, - refused, - open_signature, - open_initials, - open_boxes, - open_table, form_notice, copy_selected, - copy_comments, - paste_comments_at, - comment_notice, recolour, remote_open, + open_table, + open_boxes, + open_signature, form, generation, - avail, } = requests; - if let Some((page, at)) = app.views[index].comments.attach_at.take() { + if let Some((page, at)) = app.views[index].session.comments.attach_at.take() { app.attach_file_comment(page, at); } if let Some((p, i)) = open_props { @@ -3696,31 +1500,29 @@ fn apply_frame_requests(app: &mut PdfCraftApp, index: usize, ui: &mut egui::Ui, if let Some(c) = recolour { app.colour_selected_comments(c); } - if let Some((p, i)) = app.views[index].comments.default_request.take() { + if let Some((p, i)) = app.views[index].session.comments.default_request.take() { app.make_comment_default(p, i); } - if let Some((p, i, open)) = app.views[index].comments.attachment_request.take() { + if let Some((p, i, open)) = app.views[index].session.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); + crate::prepare::dialog::open(app, &name, w, crate::prepare::dialog::FieldTab::General); } 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); + crate::duplicate_field::open(app, name); } - if let Some((page, rect)) = app.views[index].links.open_new.take() { + if let Some((page, rect)) = app.views[index].session.links.open_new.take() { app.open_link_props(page, Some(rect), None); } - if let Some((page, i)) = app.views[index].links.open_existing.take() { + if let Some((page, i)) = app.views[index].session.links.open_existing.take() { app.open_link_props(page, None, Some(i)); } - if std::mem::take(&mut app.views[index].redaction_refused) { + if std::mem::take(&mut app.views[index].session.redaction_refused) { app.notify_tr("Part of the selected text is on a page whose text could not be read, so nothing was marked for redaction. Mark that page with a box instead."); } - if let Some((made_by, marks, head)) = app.views[index].pending_redaction.take() { + if let Some((made_by, marks, head)) = app.views[index].session.pending_redaction.take() { let author = app.comment_prefs.author.clone(); let edits: Vec = marks .into_iter() @@ -3741,7 +1543,7 @@ fn apply_frame_requests(app: &mut PdfCraftApp, index: usize, ui: &mut egui::Ui, }) .collect(); let edit = app.views[index].selection_marks_edit(edits, head); - app.views[index].pending_edit = edit; + app.views[index].session.pending_edit = edit; } match image_action { Some(crate::edit_text_ui::ImageAction::Replace(page, index)) => app.replace_page_image_dialog(page, index), @@ -3772,8 +1574,8 @@ fn apply_frame_requests(app: &mut PdfCraftApp, index: usize, ui: &mut egui::Ui, if let Some(img) = images.get(i) { let r = img.visible_rect.unwrap_or(img.rect); let center = [(r[0] + r[2]) / 2.0, (r[1] + r[3]) / 2.0]; - app.views[index].comments.context_at = Some((page, center)); - app.views[index].comments.composer = Some(crate::comments::Composer { + app.views[index].session.comments.context_at = Some((page, center)); + app.views[index].session.comments.composer = Some(crate::comments::Composer { page, at: center, kind: crate::comments::ComposerKind::Note, @@ -3787,11 +1589,11 @@ fn apply_frame_requests(app: &mut PdfCraftApp, index: usize, ui: &mut egui::Ui, } match page_action { Some(PageMenuAction::Copy) => { - if let Some(sel) = app.views[index].image_selection.clone() { + if let Some(sel) = app.views[index].session.image_selection.clone() { app.copy_page_image(sel.page, sel.index); } else if app.views[index].selected_text().is_some() || app.views[index].selection_waits_for_text().is_some() { app.execute("edit.copy"); - } else if let Some((page, at)) = app.views[index].comments.context_at + } else if let Some((page, at)) = app.views[index].session.comments.context_at && let Some(doc) = app.session.get(app.views[index].id) && let Some(image) = doc.page_image_at(page, at) { @@ -3804,11 +1606,15 @@ fn apply_frame_requests(app: &mut PdfCraftApp, index: usize, ui: &mut egui::Ui, Some(PageMenuAction::PasteComments(page, at)) => { app.paste_comments(index, None, Some((page, at))); } + // A quarter turn either way; the next pass makes the rotation one of the four and keeps the current page in + // view. Some(PageMenuAction::RotateCCW) => { - app.views[index].rotate_view(false); + let view = &mut app.views[index].view; + view.rotation = (view.rotation % 360 + 270) % 360; } Some(PageMenuAction::RotateCW) => { - app.views[index].rotate_view(true); + let view = &mut app.views[index].view; + view.rotation = (view.rotation % 360 + 90) % 360; } Some(PageMenuAction::Print) => { app.open_print(); @@ -3823,12 +1629,12 @@ fn apply_frame_requests(app: &mut PdfCraftApp, index: usize, ui: &mut egui::Ui, app.quick_tool = QuickTool::MarqueeZoom; } Some(PageMenuAction::AddComment(page, at)) => { - app.views[index].comments.composer = + app.views[index].session.comments.composer = Some(crate::comments::Composer { page, at, kind: crate::comments::ComposerKind::Note, text: String::new(), focus: true }); } Some(PageMenuAction::FlattenComments) => { - app.views[index].comments.select(None); - app.views[index].pending_edit = Some(pdfcraft_engine::Edit::Flatten { comments: true, fields: false }); + app.views[index].session.comments.select(None); + app.views[index].session.pending_edit = Some(pdfcraft_engine::Edit::Flatten { comments: true, fields: false }); } Some(PageMenuAction::AddBookmark) => { app.bookmark_action(crate::panels::BmAction::New); @@ -3846,7 +1652,7 @@ fn apply_frame_requests(app: &mut PdfCraftApp, index: usize, ui: &mut egui::Ui, app.add_image_dialog(); } Some(PageMenuAction::DeletePage(page)) => { - app.views[index].pending_edit = Some(pdfcraft_engine::Edit::DeletePages { pages: vec![page] }); + app.views[index].session.pending_edit = Some(pdfcraft_engine::Edit::DeletePages { pages: vec![page] }); } Some(PageMenuAction::ExportPdf) => { app.select_tool("export"); @@ -3855,25 +1661,22 @@ fn apply_frame_requests(app: &mut PdfCraftApp, index: usize, ui: &mut egui::Ui, app.views[index].open_find(); } Some(PageMenuAction::DocProperties) => { - app.dialog = Some(crate::Dialog::Properties(crate::PropsTab::Description)); + app.open_properties(crate::PropsTab::Description); } 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 let Some(initials) = open_signature { + // PLAN: assumed `dialogs::signature::open(app, initials, editing: bool)` (pdf-hub-w3 gives + // `signature::open(self, initials, editing)`, forms AP-4). + crate::dialogs::signature::open(app, initials, false); } if open_boxes { - app.boxes_draft.range = crate::pageboxes::Range::Current; - app.boxes_draft.seeded = None; - app.dialog = Some(crate::Dialog::PageBoxes); + // Set Page Boxes on the current page, with no draft written here. + app.open_page_boxes(true); } 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); + let doc = app.views[index].id; + crate::field_table_ui::open(app, doc, page, rect, &form, generation); // 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"); @@ -3886,40 +1689,27 @@ fn apply_frame_requests(app: &mut PdfCraftApp, index: usize, ui: &mut egui::Ui, crate::forms_ui::FormNotice::NoAction(name) => app.notify_fmt("{name} has no action", &[("name", &name)]), } } - if let Some((name, identity, action)) = app.views[index].forms.button.take() { + if let Some((name, identity, action)) = app.views[index].session.forms.button.take() { run_button(app, index, &name, identity, action); } if copy_selected { app.execute("edit.copy"); } + let copy_comments = std::mem::take(&mut app.views[index].session.comments.copy_request); if copy_comments { app.execute("comment.copy"); } - if let Some(at) = paste_comments_at { + if let Some(at) = app.views[index].session.comments.paste_request.take() { app.paste_comments(index, None, Some(at)); } - if let Some(notice) = comment_notice { + if let Some(notice) = app.views[index].session.comments.notice.take() { app.notify_tr(notice); } - // Read mode hides the tools (#2646), and full screen is the page and nothing else (#1459); - // the quick tools come back with the window. - // A document that hides the toolbars (`HideToolbar`) hides this one too. - if !app.hotbar_hidden() && !app.views.get(index).is_some_and(|v| v.interface.hidden.toolbar) { - // The page nearest the left edge, whose margin the bar sits in. - let page_left = app.views[index].screen_rects.iter().map(|(_, r)| r.left()).reduce(f32::min); - quick_bar(app, avail, page_left, ui); - } 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 sign_tab_tests; #[cfg(test)] diff --git a/crates/ui-egui/src/canvas/xform.rs b/crates/ui-egui/src/canvas/xform.rs index c3ffcfb6ee..e64144f3b8 100644 --- a/crates/ui-egui/src/canvas/xform.rs +++ b/crates/ui-egui/src/canvas/xform.rs @@ -1,43 +1,47 @@ -use super::{Color32, DocInfo, DocView, Pos2, Rect, pos2, vec2}; +use craft::pages::ui::PlacedPage; +use egui::{Color32, Pos2, Rect, pos2}; +use pdfcraft_render::DocInfo; + +use super::DocView; impl DocView { - /// Where `page` is drawn on screen this frame (`None` when it is not on screen). + /// Where `page` is drawn on screen in the last pass (`None` when it was not on screen). pub fn page_screen_rect(&self, page: usize) -> Option { - self.screen_xforms.iter().find(|(p, _)| *p == page).map(|(_, xf)| xf.rect) + self.session.placed.iter().find(|p| p.page == page).map(|p| p.rect) } /// Whether the page full screen shows is wholly in view: no transition playing or waiting for /// its raster, so a click on it reaches what is on it. Always true outside full screen. pub fn presentation_settled(&self) -> bool { - self.presentation.is_none() || self.presenter.settled_on(self.current) + self.presentation.is_none() || self.session.presenter.settled_on(self.view.current) } - /// The document area on screen. + /// The document area on screen in the last pass. pub fn viewport_rect(&self) -> Rect { - self.viewport_screen + self.viewport } - /// Pages drawn last frame and their screen rectangles. + /// Pages drawn in the last pass and their screen rectangles. pub fn visible_page_rects(&self) -> Vec<(usize, Rect)> { - self.screen_xforms.iter().map(|(p, xf)| (*p, xf.rect)).collect() + self.session.placed.iter().map(|p| (p.page, p.rect)).collect() } - /// Where `page` is drawn this frame, with its coordinate mapping. + /// Where `page` is drawn in the last pass (this pass's while the page body runs), with its coordinate mapping. pub fn page_xform(&self, page: usize) -> Option { - self.screen_xforms.iter().find(|(p, _)| *p == page).map(|(_, xf)| *xf) + self.session.placed.iter().find(|p| p.page == page).map(|p| self.xform_of(p)) } - /// Where the pages are on screen this frame, with their transforms. + /// Where the pages are on screen in the last pass, with their transforms. pub(crate) fn page_xforms(&self) -> Vec<(usize, PageXform)> { - self.screen_xforms.iter().map(|(p, xf)| (*p, *xf)).collect() + self.session.placed.iter().map(|p| (p.page, self.xform_of(p))).collect() } -} -/// `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. -pub(super) 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()) + /// The transform of a placed page, with the view's rotation and the page's size as the view reads it. + fn xform_of(&self, placed: &PlacedPage) -> PageXform { + // A page the list no longer has (an edit since the pass) maps as a unit page; `of` keeps the size positive. + let size = self.page_sizes.get(placed.page).copied().unwrap_or((1.0, 1.0)); + PageXform::of(placed, self.view.rotation, size) + } } /// Maps between a page's coordinate spaces and the screen, including view rotation. @@ -56,6 +60,14 @@ pub struct PageXform { } impl PageXform { + /// The transform of `placed`, a page the page view placed: its screen rectangle, the view's `rotation` (degrees + /// clockwise) and the page's view-space `size` (width, height in points, before the view's rotation). The page + /// view places the page already turned, so a 600 × 800 page turned 90° has a rectangle 800 wide and 600 high, + /// and [`zoom`](Self::zoom) reads its height over 600. + pub fn of(placed: &PlacedPage, rotation: u16, size: (f32, f32)) -> PageXform { + PageXform { rect: placed.rect, rot: rotation, pw: size.0.max(1.0), ph: size.1.max(1.0) } + } + /// 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 { @@ -156,15 +168,6 @@ impl PageXform { self.user_rect(info, page, r.map(|v| v as f32)) } - /// 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`]). - pub(super) 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); @@ -176,34 +179,4 @@ impl PageXform { mesh.add_triangle(0, 2, 3); painter.add(egui::Shape::mesh(mesh)); } - - /// Draw a sub-rectangle of a whole-page raster texture with specific texture UVs covering the normalised page region. - #[allow(clippy::too_many_arguments)] - pub fn paint_image_region( - &self, - painter: &egui::Painter, - tex: egui::TextureId, - pu0: f32, - pv0: f32, - pu1: f32, - pv1: f32, - tu0: f32, - tv0: f32, - tu1: f32, - tv1: f32, - ) { - let mut mesh = egui::Mesh::with_texture(tex); - let corners = [(pu0, pv0, tu0, tv0), (pu1, pv0, tu1, tv0), (pu1, pv1, tu1, tv1), (pu0, pv1, tu0, tv1)]; - 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)); - } - - /// Draw a sub-rectangle of a whole-page raster texture, where UV space matches page normalized space. - pub fn paint_page_texture_rect(&self, painter: &egui::Painter, tex: egui::TextureId, u0: f32, v0: f32, u1: f32, v1: f32) { - self.paint_image_region(painter, tex, u0, v0, u1, v1, u0, v0, u1, v1); - } }