Skip to content

PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust

Merge Conflicts #4889

Combiler015cf09552ab1a
diff --git a/crates/automation/src/dispatch.rs b/crates/automation/src/dispatch.rs
index 26e1f9536..43d143289 100644
--- a/crates/automation/src/dispatch.rs
+++ b/crates/automation/src/dispatch.rs
@@ -385,6 +385,11 @@ impl Automation {
"flip_horizontal" => ImageEdit::Flip { horizontal: true },
"flip_vertical" => ImageEdit::Flip { horizontal: false },
"delete" => ImageEdit::Delete,
+ "bring_to_front" => ImageEdit::Arrange(pdfcraft_engine::ArrangeOrder::BringToFront),
+ "send_to_back" => ImageEdit::Arrange(pdfcraft_engine::ArrangeOrder::SendToBack),
+ "bring_forward" => ImageEdit::Arrange(pdfcraft_engine::ArrangeOrder::BringForward),
+ "send_backward" => ImageEdit::Arrange(pdfcraft_engine::ArrangeOrder::SendBackward),
+ "remove_crop" => ImageEdit::RemoveCrop,
"replace" => {
let path = self.resolve(a.str("path")?, false)?;
let bytes = read_input(&path)?;
diff --git a/crates/engine/src/edit/run.rs b/crates/engine/src/edit/run.rs
index b357c1e47..300a93845 100644
--- a/crates/engine/src/edit/run.rs
+++ b/crates/engine/src/edit/run.rs
@@ -530,7 +530,8 @@ pub(crate) fn run_edit(doc: &mut pdfcraft_cos::Document, edit: &Edit, cx: &mut E
},
};
- let added_items: Vec<(usize, pdfcraft_edit::Added)> = pdfcraft_edit::list_added(doc).into_iter().filter(|a| a.page == *page).enumerate().collect();
+ let added_items: Vec<(usize, pdfcraft_edit::Added)> =
+ pdfcraft_edit::list_added(doc).into_iter().filter(|a| a.page == *page).enumerate().collect();
let matched_added = if let Some(st_ref) = target_stream_obj {
added_items.iter().find(|(_, a)| a.obj == st_ref)
} else if let Some(target_ref) = img.object {
diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs
index 5c1f007df..07327d1bc 100644
--- a/crates/ui-egui/src/app.rs
+++ b/crates/ui-egui/src/app.rs
@@ -326,7 +326,7 @@ impl PdfCraftApp {
if !self.is_tool_pinned(id) {
self.pinned_tools.push(id.to_string());
if let Some(g) = pdfcraft_engine::catalog::group(id) {
- self.notify_fmt("Pinned {tool} to Home", &[("tool", &g.label)]);
+ self.notify_fmt("Pinned {tool} to Home", &[("tool", g.label)]);
}
return true;
}
@@ -338,7 +338,7 @@ impl PdfCraftApp {
if let Some(pos) = self.pinned_tools.iter().position(|t| t == id) {
self.pinned_tools.remove(pos);
if let Some(g) = pdfcraft_engine::catalog::group(id) {
- self.notify_fmt("Unpinned {tool} from Home", &[("tool", &g.label)]);
+ self.notify_fmt("Unpinned {tool} from Home", &[("tool", g.label)]);
}
}
}
diff --git a/crates/ui-egui/src/app/clipboard.rs b/crates/ui-egui/src/app/clipboard.rs
index da9cc1715..2a827e30c 100644
--- a/crates/ui-egui/src/app/clipboard.rs
+++ b/crates/ui-egui/src/app/clipboard.rs
@@ -22,16 +22,6 @@ impl PdfCraftApp {
false
}
- /// ⌘C copies the selected text, unless a text field has the keyboard (it copies its own).
- pub(super) fn copy_key(&mut self, i: usize, ctx: &egui::Context) {
- // ⌘C arrives as a Copy event on most platforms.
- let copy = ctx.input(|input| input.events.iter().any(|e| matches!(e, egui::Event::Copy)));
- if !copy || ctx.egui_wants_keyboard_input() {
- return;
- }
- self.copy_selected_text(i, ctx);
- }
-
/// ⌘C / ⌘X / ⌘V copy, cut and paste text or images on canvas (unless a text field has focus).
pub(super) fn clipboard_keys(&mut self, i: usize, ctx: &egui::Context, pasted: bool) {
use egui::{Key, KeyboardShortcut, Modifiers};
diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs
index a08556bb0..0839a866a 100644
--- a/crates/ui-egui/src/canvas.rs
+++ b/crates/ui-egui/src/canvas.rs
@@ -1,3419 +1,3419 @@
-//! The document area: page layout, zoom, render scheduling, overlays (links, annotation hovers,
-//! form-field highlights), and the organize-pages grid.
-//!
-//! 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).
-
-use std::collections::{BTreeSet, HashMap, HashSet};
-use std::ops::Range;
-use std::sync::Arc;
-
-use egui::{Align2, Color32, CornerRadius, Pos2, Rect, Sense, Stroke, TextureHandle, TextureOptions, Vec2, pos2, vec2};
-use pdfcraft_engine::{DocId, Edit};
-use pdfcraft_render::{DestView, DocInfo, LayerOp, LinkTarget, PRINT_TAG, PageText, RenderPool, RenderRequest, RequestKind, Tile, device_pixels};
-
-use crate::page_pointer::PagePointer;
-use crate::theme::{self, Tokens};
-use crate::{PdfCraftApp, QuickTool, RightPanel, comments, icons, widgets};
-
-mod area;
-pub(super) mod autoscroll;
-mod bars;
-mod cache;
-pub(super) mod crop;
-mod find;
-pub(super) mod fling;
-pub(super) mod image_pick;
-mod navigation;
-mod organize;
-pub(super) mod page_pointer;
-pub mod scroll_speed;
-mod selection;
-pub(super) mod signature_drag;
-pub(super) mod wheel_boost;
-pub(super) mod wheel_pager;
-mod xform;
-mod zoom;
-pub(super) mod zoom_snap;
-
-pub(crate) use area::signature_badges;
-use area::{
- SUPPRESS_SECS, SUPPRESS_TAIL_SECS, annotation_hover_text, drawing_edge_pointer, glide_interrupted, page_scroll, presentation_click, run_button,
- set_layers, zoom_anchor,
-};
-#[cfg(test)]
-use bars::in_size_hint_zone;
-use bars::{Notice, notices, page_size_hint, quick_bar};
-pub use cache::RasterMemory;
-pub(crate) use cache::{BASE_SIDE, TILE_THRESHOLD, texture_image, thumbnail_rows};
-#[cfg(test)]
-use cache::{
- GRAYSCALE_TAG, GRID_TAG, MAX_CACHED_TEXT_PAGES, MAX_THUMB_DEMAND, PAGE_BYTES, THUMB_BYTES, THUMB_H, THUMB_TAG, THUMB_W, TILE, grayscale,
- rgba_bytes,
-};
-use cache::{OLD_TILES, PageTex, STALE_TAG, TEXT_TAG, TILE_BYTES, scale_tag, tag_scale, texture_bytes, tile_side};
-pub use find::Find;
-use find::find_bar;
-pub use navigation::shortcuts;
-pub(crate) use organize::drop_gap;
-#[cfg(test)]
-pub(crate) use organize::grid_page_rect;
-use organize::organize_grid;
-#[cfg(test)]
-use organize::sharp_enough;
-use selection::{Selection, Span, click_unit, selection_actions};
-pub use xform::PageXform;
-use xform::snap_to_pixels;
-use zoom::anchored_scroll;
-pub use zoom::{GRID_ZOOM_RANGE, THUMBNAIL_ZOOM_RANGE};
-
-/// Logical pixels per PDF point at 100% (96 dpi, like browsers).
-pub const PT: f32 = 96.0 / 72.0;
-const GAP: f32 = 14.0;
-const MARGIN: f32 = 28.0;
-/// Horizontal gutter that keeps pages clear of the floating quick-action bar.
-const SIDE: f32 = 70.0;
-use crate::edit_text_ui::ImageHandle;
-
-/// Extension trait on `egui::Painter` to draw polygons.
-pub trait PainterExt {
- fn polygon(&self, points: Vec<Pos2>, fill: Color32, stroke: Stroke) -> egui::layers::ShapeIdx;
-}
-
-impl PainterExt for egui::Painter {
- fn polygon(&self, points: Vec<Pos2>, fill: Color32, stroke: Stroke) -> egui::layers::ShapeIdx {
- self.add(egui::Shape::convex_polygon(points, fill, stroke))
- }
-}
-
-/// User-space selectable bounding box for an image object.
-/// If the image object has an active clipping path applied to it (the crop box),
-/// this is the mathematical intersection of the full CTM-derived rect and the clipping path's rect.
-pub fn image_selectable_bounds(im: &pdfcraft_engine::PageImage) -> [f64; 4] {
- if let Some(clip) = im.clip_rect {
- let r = [im.rect[0].max(clip[0]), im.rect[1].max(clip[1]), im.rect[2].min(clip[2]), im.rect[3].min(clip[3])];
- if r.iter().all(|v| v.is_finite()) && r[2] > r[0] && r[3] > r[1] {
- return r;
- }
- }
- im.visible_rect.unwrap_or(im.rect)
-}
-
-/// Screen-space selectable bounding box for an image object.
-/// If the image object has an active clipping path applied to it (the crop box),
-/// the final selectable `egui::Rect` is the mathematical intersection of the image's
-/// full CTM-derived rect and the clipping path's rect.
-pub fn image_screen_rect(im: &pdfcraft_engine::PageImage, xf: &PageXform, info: &DocInfo, page: usize) -> Rect {
- let full = xf.user_rect_f64(info, page, im.rect);
- if let Some(clip) = im.clip_rect {
- let clip_r = xf.user_rect_f64(info, page, clip);
- let inter = full.intersect(clip_r);
- if inter.is_positive() {
- return inter;
- }
- }
- if let Some(vr) = im.visible_rect {
- let r = xf.user_rect_f64(info, page, vr);
- if r.is_positive() {
- return r;
- }
- }
- full
-}
-
-/// 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 width: f32,
- pub height: f32,
- pub theta: f32,
- pub u_axis: (f64, f64),
- pub v_axis: (f64, f64),
- pub is_rotated: bool,
-}
-
-impl ImageObb {
- /// Calculates the 4 rotated corners manually using center, width, height, and rotation angle (θ).
- /// Local axes: `u_axis = (cos θ, sin θ)` and `v_axis = (-sin θ, cos θ)`.
- /// Places the 8 resize handles exactly at these rotated vertices and midpoints.
- pub fn from_center_size_angle(center: Pos2, width: f32, height: f32, theta: f32) -> Self {
- let cos_t = theta.cos();
- let sin_t = theta.sin();
- let u_axis = (cos_t as f64, sin_t as f64);
- let v_axis = (-sin_t as f64, cos_t as f64);
- let u_vec = vec2(cos_t, sin_t);
- let v_vec = vec2(-sin_t, cos_t);
- let hw = width * 0.5;
- let hh = height * 0.5;
-
- let s00 = center - u_vec * hw - v_vec * hh;
- let s10 = center + u_vec * hw - v_vec * hh;
- let s11 = center + u_vec * hw + v_vec * hh;
- let s01 = center - u_vec * hw + v_vec * hh;
-
- let s_bc = center - v_vec * hh;
- let s_rc = center + u_vec * hw;
- let s_tc = center + v_vec * hh;
- let s_lc = center - u_vec * hw;
-
- let s_rot = s_tc + v_vec * 24.0;
- let is_rotated = theta.abs() > 1e-4;
-
- Self { s00, s10, s11, s01, s_bc, s_rc, s_tc, s_lc, s_rot, screen_center: center, width, height, theta, u_axis, v_axis, is_rotated }
- }
-
- pub fn new(matrix: [f64; 6], xf: &PageXform, info: &DocInfo, page: usize) -> Self {
- Self::from_matrix(matrix, xf, info, page)
- }
-
- 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);
- let theta = (b).atan2(a) as f32;
- let is_rotated = b.abs() > 1e-4 || c.abs() > 1e-4;
-
- Self {
- s00,
- s10,
- s11,
- s01,
- s_bc,
- s_rc,
- s_tc,
- s_lc,
- s_rot,
- screen_center,
- width: (s10 - s00).length(),
- height: (s01 - s00).length(),
- theta,
- u_axis,
- v_axis,
- is_rotated,
- }
- }
-
- pub fn from_image(im: &pdfcraft_engine::PageImage, xf: &PageXform, info: &DocInfo, page: usize) -> Self {
- let [_, b, c, ..] = im.matrix;
- let is_rot = b.abs() > 1e-4 || c.abs() > 1e-4;
- 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, 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 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 handle_id(&self, base_id: egui::Id, handle: ImageHandle) -> egui::Id {
- base_id.with(match handle {
- ImageHandle::TopLeft => "handle_tl",
- ImageHandle::TopCenter => "handle_tc",
- ImageHandle::TopRight => "handle_tr",
- ImageHandle::RightCenter => "handle_rc",
- ImageHandle::BottomRight => "handle_br",
- ImageHandle::BottomCenter => "handle_bc",
- ImageHandle::BottomLeft => "handle_bl",
- ImageHandle::LeftCenter => "handle_lc",
- })
- }
-
- pub fn handles_with_ids(&self, base_id: egui::Id) -> [(ImageHandle, Pos2, egui::Id); 8] {
- [
- (ImageHandle::TopLeft, self.s01, self.handle_id(base_id, ImageHandle::TopLeft)),
- (ImageHandle::TopCenter, self.s_tc, self.handle_id(base_id, ImageHandle::TopCenter)),
- (ImageHandle::TopRight, self.s11, self.handle_id(base_id, ImageHandle::TopRight)),
- (ImageHandle::RightCenter, self.s_rc, self.handle_id(base_id, ImageHandle::RightCenter)),
- (ImageHandle::BottomRight, self.s10, self.handle_id(base_id, ImageHandle::BottomRight)),
- (ImageHandle::BottomCenter, self.s_bc, self.handle_id(base_id, ImageHandle::BottomCenter)),
- (ImageHandle::BottomLeft, self.s00, self.handle_id(base_id, ImageHandle::BottomLeft)),
- (ImageHandle::LeftCenter, self.s_lc, self.handle_id(base_id, ImageHandle::LeftCenter)),
- ]
- }
-
- pub fn corners(&self) -> [Pos2; 4] {
- [self.s00, self.s10, self.s11, self.s01]
- }
-
- /// Resizes the OBB proportionally along its local axes using projected mouse delta,
- /// locking the diagonally opposite corner as the fixed anchor point.
- pub fn scale_proportional(&self, handle: ImageHandle, delta: Vec2, min_size: f32) -> Self {
- let u_vec = vec2(self.u_axis.0 as f32, self.u_axis.1 as f32);
- let v_vec = vec2(self.v_axis.0 as f32, self.v_axis.1 as f32);
- let delta_u = delta.dot(u_vec);
- let delta_v = delta.dot(v_vec);
- let min_s = min_size.max(5.0);
-
- match handle {
- ImageHandle::TopRight => {
- let anchor = self.s00;
- let s_u = (self.width + delta_u) / self.width.max(1e-4);
- let s_v = (self.height + delta_v) / self.height.max(1e-4);
- let s = if (s_u - 1.0).abs() >= (s_v - 1.0).abs() { s_u } else { s_v };
- let s = s.max(min_s / self.width.max(1e-4)).max(min_s / self.height.max(1e-4));
- let nw = self.width * s;
- let nh = self.height * s;
- let new_center = anchor + u_vec * (nw * 0.5) + v_vec * (nh * 0.5);
- Self::from_center_size_angle(new_center, nw, nh, self.theta)
- }
- ImageHandle::TopLeft => {
- let anchor = self.s10;
- let s_u = (self.width - delta_u) / self.width.max(1e-4);
- let s_v = (self.height + delta_v) / self.height.max(1e-4);
- let s = if (s_u - 1.0).abs() >= (s_v - 1.0).abs() { s_u } else { s_v };
- let s = s.max(min_s / self.width.max(1e-4)).max(min_s / self.height.max(1e-4));
- let nw = self.width * s;
- let nh = self.height * s;
- let new_center = anchor - u_vec * (nw * 0.5) + v_vec * (nh * 0.5);
- Self::from_center_size_angle(new_center, nw, nh, self.theta)
- }
- ImageHandle::BottomLeft => {
- let anchor = self.s11;
- let s_u = (self.width - delta_u) / self.width.max(1e-4);
- let s_v = (self.height - delta_v) / self.height.max(1e-4);
- let s = if (s_u - 1.0).abs() >= (s_v - 1.0).abs() { s_u } else { s_v };
- let s = s.max(min_s / self.width.max(1e-4)).max(min_s / self.height.max(1e-4));
- let nw = self.width * s;
- let nh = self.height * s;
- let new_center = anchor - u_vec * (nw * 0.5) - v_vec * (nh * 0.5);
- Self::from_center_size_angle(new_center, nw, nh, self.theta)
- }
- ImageHandle::BottomRight => {
- let anchor = self.s01;
- let s_u = (self.width + delta_u) / self.width.max(1e-4);
- let s_v = (self.height - delta_v) / self.height.max(1e-4);
- let s = if (s_u - 1.0).abs() >= (s_v - 1.0).abs() { s_u } else { s_v };
- let s = s.max(min_s / self.width.max(1e-4)).max(min_s / self.height.max(1e-4));
- let nw = self.width * s;
- let nh = self.height * s;
- let new_center = anchor + u_vec * (nw * 0.5) - v_vec * (nh * 0.5);
- Self::from_center_size_angle(new_center, nw, nh, self.theta)
- }
- ImageHandle::RightCenter => {
- let anchor = self.s_lc;
- let nw = (self.width + delta_u).max(min_s);
- let new_center = anchor + u_vec * (nw * 0.5);
- Self::from_center_size_angle(new_center, nw, self.height, self.theta)
- }
- ImageHandle::LeftCenter => {
- let anchor = self.s_rc;
- let nw = (self.width - delta_u).max(min_s);
- let new_center = anchor - u_vec * (nw * 0.5);
- Self::from_center_size_angle(new_center, nw, self.height, self.theta)
- }
- ImageHandle::TopCenter => {
- let anchor = self.s_bc;
- let nh = (self.height + delta_v).max(min_s);
- let new_center = anchor + v_vec * (nh * 0.5);
- Self::from_center_size_angle(new_center, self.width, nh, self.theta)
- }
- ImageHandle::BottomCenter => {
- let anchor = self.s_tc;
- let nh = (self.height - delta_v).max(min_s);
- let new_center = anchor - v_vec * (nh * 0.5);
- Self::from_center_size_angle(new_center, self.width, nh, self.theta)
- }
- }
- }
-}
-
-/// Projects mouse delta onto local unit axes `u_axis` and `v_axis` using the dot product.
-pub fn project_delta(delta: Vec2, u_axis: (f64, f64), v_axis: (f64, f64)) -> (f64, f64) {
- let dx = delta.x as f64;
- let dy = delta.y as f64;
- (dx * u_axis.0 + dy * u_axis.1, dx * v_axis.0 + dy * v_axis.1)
-}
-
-/// Visible grid rows, plus one adjacent row in either direction. Work is independent of
-/// document length, including after a large scroll jump.
-
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-pub enum Fit {
- Width,
- Page,
- Height,
- None,
-}
-
-/// 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,
- pub continuous: bool,
- pub cover: bool,
- pub fit: Fit,
- pub zoom: f32,
-}
-
-/// 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> {
- 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> {
- 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<Self> {
- 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::<f32>().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)]
-pub enum SnapshotKind {
- SignedVersion,
- Revision,
-}
-
-#[derive(Clone, Debug)]
-pub struct Snapshot {
- pub kind: SnapshotKind,
- /// The 1-based revision shown.
- pub revision: usize,
- /// The name of the document it was opened from.
- pub from: String,
-}
-
-/// 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)
-/// is enough.
-pub(crate) fn tab_label(app: &PdfCraftApp, index: usize) -> Option<String> {
- let view = app.views.get(index)?;
- let doc = app.session.get(view.id)?;
- let Some(snap) = view.snapshot.as_ref() else { return Some(doc.display_name()) };
- Some(snapshot_tab_name(&doc.display_name(), &doc.name, snap))
-}
-
-/// A snapshot's tab name from its source title, file name and marker. Pure so the
-/// tab strip, window title and picker cannot disagree with each other.
-pub(crate) fn snapshot_tab_name(title: &str, file_name: &str, snapshot: &Snapshot) -> String {
- if title == file_name {
- return file_name.into();
- }
- if snapshot.kind == SnapshotKind::SignedVersion {
- format!("{title} (signed version)")
- } else {
- format!("{title} (revision {})", snapshot.revision)
- }
-}
-
-pub struct DocView {
- pub id: DocId,
- 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,
- 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,
- pub notice_dismissed: bool,
- /// The user has been told that the form's scripts were turned off (it is said once).
- pub scripts_off_noted: bool,
- /// The file changed on disk while this document had unsaved changes: the notice bar asks
- /// before replacing it (#431).
- pub disk_changed: bool,
- /// The snapshot notice bar's Close was clicked: the tab closes at the top of the next
- /// frame, where no document borrow is held (the bar itself can't close it).
- pub close_requested: bool,
- /// A historical snapshot of another document (see [`Snapshot`]): `None` for real documents.
- pub snapshot: Option<Snapshot>,
- /// 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<usize>,
- pub forward: Vec<usize>,
- /// Pending navigation: page and fraction down the page to align with the viewport top.
- pub goto: Option<(usize, f32)>,
- /// 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<f32>, Option<f32>, Vec2)>,
- /// Pending keyboard scrolling, in points down (negative: up): ↓ / ↑, and Page Down /
- /// Page Up where the pages scroll.
- pub key_scroll: f32,
- /// 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)>,
- /// 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<SavedDisplay>,
- pages: HashMap<usize, PageTex>,
- /// Pages the renderer could not draw, with the reason (never re-requested).
- errors: HashMap<usize, String>,
- /// When each still-missing page was first shown, to flag unusually slow renders.
- waiting_since: HashMap<usize, f64>,
- thumbs: HashMap<usize, PageTex>,
- /// This frame's consumers, with visible cells ahead of prefetch.
- thumb_demand: HashMap<usize, bool>,
- frame_queue: Vec<RenderRequest>,
- /// 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<usize>,
- /// Thumbnails that are out of date (still shown until their replacement arrives).
- stale_thumbs: HashSet<usize>,
- /// 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<usize, (u64, TextureHandle)>,
- /// 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<usize, Arc<PageText>>,
- pub(crate) text_failed: HashSet<usize>,
- pub find: Option<Find>,
- selection: Option<Selection>,
- /// 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<Selection>,
- /// 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,
- /// 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<Pos2>,
- /// 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<RenderRequest>,
- /// 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 heights in points (view space), for mapping text positions to scroll offsets.
- page_heights: Vec<f32>,
- /// Screen rects of the pages drawn last frame (hit-testing, tests, automation).
- screen_rects: Vec<(usize, Rect)>,
- screen_xforms: Vec<(usize, PageXform)>,
- /// 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 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<usize>,
- /// Pages Edit looked at and found not to be a scan, with the document's edit generation then:
- /// they are looked at again only after the document changes (an image added, say).
- pub(crate) auto_ocr_skipped: std::collections::HashMap<usize, u64>,
- /// Turns wheel input into page turns in single-page view.
- wheel: crate::wheel_pager::WheelPager,
- /// Until this time, apply precise (touchpad) wheel input 1:1 and suppress egui's eased copy.
- /// A precision touchpad sends pixel-precise `MouseWheel` events; on Windows they arrive with
- /// no `TouchPhase::Start`, so egui eases deltas of 8 px or more and the page lags the finger
- /// (#759). The window outlasts a single frame so egui's internal easing tail is suppressed as
- /// it decays, instead of adding on top of the 1:1 motion.
- precise_scroll_until: f64,
- /// 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<usize>,
- pub(crate) organize_range: crate::page_selection_ui::PageSelectionInput,
- /// Anchor for ⇧-click range selection in the organize grid.
- select_anchor: Option<usize>,
- /// An edit requested by the view (organize toolbar, keys), applied by the app this frame.
- pub pending_edit: Option<Edit>,
- /// Edit text: the lines per page (with the document generation they were read at), and the
- /// line being edited.
- pub(crate) edit_lines: HashMap<usize, (u64, Vec<pdfcraft_engine::TextBlock>)>,
- pub line_editor: Option<crate::edit_text_ui::LineEditor>,
- /// The paragraph editor whose edit was just queued. It opens again with its typing if the
- /// edit fails, as a refused form field does.
- pub(crate) applied_editor: Option<crate::edit_text_ui::LineEditor>,
- /// The box a click switched to while another paragraph was being edited: it opens once the
- /// queued edit has applied, so its index and geometry come from the document it now is (#2022).
- /// It is held as the paragraph's text and box, not an index: the edit can regroup the page.
- pub(crate) pending_text_open: Option<(usize, pdfcraft_engine::BlockKey)>,
- pub(crate) text_background: crate::edit_text_ui::TextBackground,
- pub(crate) move_background: crate::content_ui::MoveBackground,
- /// Edit text & images: the images per page (by document generation), and the selected one.
- pub(crate) edit_images: HashMap<usize, (u64, Vec<pdfcraft_engine::PageImage>)>,
- pub(crate) objects: crate::object_ui::ObjectSelection,
- pub image_selection: Option<crate::edit_text_ui::ImageSelection>,
- /// Select tool: the picture clicked, to copy in its original format.
- pub picked_image: Option<crate::image_pick::PickedImage>,
- /// A paragraph box being dragged (moved, or resized from its right edge) in Edit text.
- pub block_drag: Option<crate::edit_text_ui::BlockDrag>,
- /// Commenting state: selected comment, gestures, composer.
- pub comments: crate::comments::CommentView,
- pub measure: crate::measure_ui::MeasureView,
- /// Form filling state: the focused field.
- pub forms: crate::forms_ui::FormView,
- /// Prepare a form: the selected field and the gesture in progress.
- pub prepare: crate::prepare::PrepareView,
- /// Prepare a form ▸ Calculation order.
- pub(crate) calc_order: crate::calc_order_ui::CalcOrderView,
- /// Edit a PDF: the selected added item, the text being typed.
- pub content: crate::content_ui::ContentView,
- /// Edit a PDF ▸ Link tool state.
- pub links: crate::link_ui::LinkView,
- /// Redact tool: the box being drawn, and a mark to add (page, quads) for the app to style.
- pub redact_drag: crate::redact_ui::AreaDrag,
- pub pending_redaction: Option<(usize, Vec<[f64; 8]>)>,
- /// A crop rectangle being dragged (Crop tool).
- pub crop_drag: crate::crop::CropDrag,
- /// Enhance ▸ Camera image: the quadrilateral being placed.
- pub camera: Option<crate::camera_ui::CameraQuad>,
- /// Enhance ▸ Camera image: the page just enhanced, while the bar offers rotate, crop and
- /// organize.
- pub camera_done: Option<crate::camera_ui::CameraDone>,
- /// Use a certificate: a signature rectangle being 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<Vec<usize>>,
- /// Pages panel: the pages being dragged to a new place.
- pub panel_drag: Option<Vec<usize>>,
- /// Marquee Zoom / Snapshot: the rectangle being dragged (page, start), and a finished one.
- pub marquee: Option<(usize, Pos2)>,
- pub marquee_done: Option<crate::zoom_snap::Marquee>,
- /// Fill & Sign text being typed.
- pub fill_text: Option<crate::fill_sign::TypeBox>,
- /// A queued Fill & Sign signature: select it after its edit succeeds, then leave placement.
- pub(crate) fill_signature_page: Option<usize>,
- pub(crate) signature_drag: crate::signature_drag::SignatureDrag,
- /// A non-edit action requested by the organize toolbar, handled by the app.
- pub pending_action: Option<ViewAction>,
- /// The grid gap the next inserted files go to (set by a "+" between pages); otherwise they
- /// go after the selection.
- pub insert_at: Option<usize>,
- /// The page-grid gap under the pointer this frame (where dropped files go), when it can
- /// take pages.
- pub grid_gap: Option<usize>,
- /// 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<Rect>,
- /// The Pages-panel gap under the pointer (where dropped files go), when it can take pages.
- pub panel_gap: Option<usize>,
- /// 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<usize>,
- /// 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<f32>,
- /// 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<usize>,
- /// 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<usize, (u32, TextureHandle)>,
- /// 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,
- /// Side-by-side compare: scroll to here this frame, following the other half.
- pub(crate) sync_scroll: Option<Vec2>,
- /// The page widget's id, by which the Hand tool finds its drag before the pages are laid out.
- page_widget: Option<egui::Id>,
- 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<usize>,
-}
-
-/// Organize-toolbar actions that need the app (file pickers, new tabs, dialogs).
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-pub enum ViewAction {
- InsertFromFile,
- /// Insert files at a gap of the page grid (0 = before the first page).
- InsertFromFileAt(usize),
- /// Replace the selected pages with pages from another file.
- ReplacePages,
- /// Save the document as the grid shows it.
- Save,
- Extract,
- Split,
- /// Split before each selected page: opens Split on that mode.
- SplitBeforeSelected,
- /// Copy the selected pages (Cut also deletes them).
- CopyPages {
- cut: bool,
- },
- /// Paste copied pages after the selection.
- PastePages,
- /// Enhance ▸ Camera image: straighten what the corners enclose.
- EnhanceCamera,
- /// Leave Enhance ▸ Camera image (Cancel before Enhance page, Done after it).
- CancelCamera,
- /// After Enhance page: turn the enhanced page a quarter.
- CameraRotate {
- clockwise: bool,
- },
- /// After Enhance page: enhance again at the slider's clean-up level.
- CameraLevel,
- /// After Enhance page: leave the tool for this command (Crop pages, Organize pages).
- CameraNext(&'static str),
-}
-
-/// Default page right-click menu actions.
-#[derive(Clone, Debug, PartialEq)]
-pub(crate) enum PageMenuAction {
- RotateCCW(usize),
- RotateCW(usize),
- Print,
- SelectTool,
- HandTool,
- MarqueeZoom,
- Copy,
- Paste(usize, [f64; 2]),
- AddComment(usize, [f64; 2]),
- AddBookmark(usize),
- 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_paste: 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<PageMenuAction>) {
- // Top horizontal icon bar: Rotate CCW, Print, Select tool, Hand tool, Marquee Zoom
- ui.horizontal(|ui| {
- ui.spacing_mut().item_spacing.x = 4.0;
- if crate::icons::button(ui, "rotate-ccw", 24.0, false, tl!("Rotate view counterclockwise")).clicked() {
- *action = Some(PageMenuAction::RotateCCW(page));
- ui.close();
- }
- ui.add_enabled_ui(perms.can_print, |ui| {
- if crate::icons::button(ui, "printer", 24.0, false, tl!("Print")).clicked() {
- *action = Some(PageMenuAction::Print);
- ui.close();
- }
- });
- if crate::icons::button(ui, "mouse-pointer-2", 24.0, false, tl!("Select Tool")).clicked() {
- *action = Some(PageMenuAction::SelectTool);
- ui.close();
- }
- if crate::icons::button(ui, "hand", 24.0, false, tl!("Hand Tool")).clicked() {
- *action = Some(PageMenuAction::HandTool);
- ui.close();
- }
- if crate::icons::button(ui, "zoom-in", 24.0, false, tl!("Marquee Zoom")).clicked() {
- *action = Some(PageMenuAction::MarqueeZoom);
- ui.close();
- }
- });
-
- ui.separator();
-
- if ui.add_enabled(perms.can_copy, egui::Button::new(tl!("Copy")).shortcut_text("Ctrl+C")).clicked() {
- *action = Some(PageMenuAction::Copy);
- ui.close();
- }
- if ui.add_enabled(perms.can_paste, egui::Button::new(tl!("Paste")).shortcut_text("Ctrl+V")).clicked() {
- *action = Some(PageMenuAction::Paste(page, at));
- ui.close();
- }
-
- ui.separator();
-
- if ui.add_enabled(perms.can_annotate, egui::Button::new(tl!("Add comment"))).clicked() {
- *action = Some(PageMenuAction::AddComment(page, at));
- ui.close();
- }
- if perms.has_annotations && ui.add_enabled(perms.can_modify, egui::Button::new(tl!("Flatten comments"))).clicked() {
- *action = Some(PageMenuAction::FlattenComments);
- ui.close();
- }
- if ui.add_enabled(perms.can_assemble, egui::Button::new(tl!("Add bookmark"))).clicked() {
- *action = Some(PageMenuAction::AddBookmark(page));
- ui.close();
- }
- if ui.add_enabled(perms.can_copy, egui::Button::new(tl!("Take a snapshot"))).clicked() {
- *action = Some(PageMenuAction::TakeSnapshot);
- ui.close();
- }
-
- ui.separator();
-
- if ui.add_enabled(perms.can_modify, egui::Button::new(egui::RichText::new(tl!("Edit this PDF")).strong())).clicked() {
- *action = Some(PageMenuAction::EditPdf);
- ui.close();
- }
- if ui.add_enabled(perms.can_modify, egui::Button::new(tl!("Add text"))).clicked() {
- *action = Some(PageMenuAction::AddText);
- ui.close();
- }
- if ui.add_enabled(perms.can_modify, egui::Button::new(tl!("Add image"))).clicked() {
- *action = Some(PageMenuAction::AddImage);
- ui.close();
- }
- if ui.add_enabled(perms.can_assemble, egui::Button::new(tl!("Delete page"))).clicked() {
- *action = Some(PageMenuAction::DeletePage(page));
- ui.close();
- }
- if ui.add_enabled(perms.can_copy, egui::Button::new(tl!("Export this PDF"))).clicked() {
- *action = Some(PageMenuAction::ExportPdf);
- ui.close();
- }
-
- ui.separator();
-
- if ui.button(tl!("Find text or tools")).clicked() {
- *action = Some(PageMenuAction::Find);
- ui.close();
- }
- if ui.button(tl!("Rotate view clockwise")).clicked() {
- *action = Some(PageMenuAction::RotateCW(page));
- ui.close();
- }
- if ui.button(tl!("Document properties…")).clicked() {
- *action = Some(PageMenuAction::DocProperties);
- ui.close();
- }
-}
-
-impl DocView {
- /// Whether a middle-button scrolling gesture is active (tests and automation).
- pub fn auto_scrolling(&self) -> bool {
- self.auto_scroll.active()
- }
-
- /// Whether a held middle-button pan is active, outside Linux (tests and automation).
- pub fn middle_panning(&self) -> bool {
- self.auto_scroll.panning()
- }
-
- /// 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;
- self.block_drag = None;
- self.org_drag = None;
- self.panel_drag = None;
- self.selection_drag = false;
- self.auto_scroll.cancel();
- self.prepare.cancel_pointer_gesture();
- 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 {
- Self {
- id,
- zoom: defaults.zoom,
- fit: defaults.fit,
- layout: defaults.layout,
- continuous: defaults.continuous,
- show_page_gaps: defaults.show_page_gaps,
- rotation: 0,
- current: 0,
- organize: false,
- highlight_fields: defaults.highlight_fields,
- page_input: "1".into(),
- page_input_reselect: false,
- notice_dismissed: false,
- scripts_off_noted: false,
- disk_changed: false,
- close_requested: false,
- snapshot: None,
- cover: false,
- back: Vec::new(),
- forward: Vec::new(),
- goto: None,
- goto_point: None,
- key_scroll: 0.0,
- single_edges: None,
- flash: None,
- compare_marks: Vec::new(),
- presentation: None,
- pages: HashMap::new(),
- errors: HashMap::new(),
- waiting_since: HashMap::new(),
- thumbs: HashMap::new(),
- thumb_demand: HashMap::new(),
- frame_queue: Vec::new(),
- frame_geometry_changed: false,
- frame_visible: 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_failed: HashSet::new(),
- find: None,
- selection: None,
- all_text: false,
- actions_dismissed: None,
- selection_drag: 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_heights: info.pages.iter().map(|p| p.height).collect(),
- screen_rects: Vec::new(),
- screen_xforms: Vec::new(),
- viewport_screen: Rect::NOTHING,
- zoom_anchor: None,
- shown: false,
- auto_ocr_tried: Default::default(),
- auto_ocr_skipped: Default::default(),
- wheel: Default::default(),
- precise_scroll_until: 0.0,
- 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(),
- 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,
- block_drag: None,
- pending_action: None,
- insert_at: None,
- grid_gap: None,
- pages_panel: None,
- panel_gap: None,
- panel_followed: 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,
- sync_scroll: None,
- page_widget: None,
- pan_hold_until: 0.0,
- slow_pages: HashSet::new(),
- comments: Default::default(),
- 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,
- crop_drag: None,
- camera: None,
- camera_done: None,
- sign: Default::default(),
- org_drag: None,
- panel_drag: None,
- marquee: None,
- marquee_done: None,
- fill_text: None,
- fill_signature_page: None,
- signature_drag: Default::default(),
- }
- }
-
- /// 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) {
- self.invalidate_content();
- self.frame_geometry_changed = true;
- self.page_count = info.pages.len();
- self.page_heights = info.pages.iter().map(|p| 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;
- }
- if self.select_anchor.is_some_and(|a| a > last) {
- self.select_anchor = None;
- }
- self.goto = None;
- self.goto_point = None;
- self.zoom_anchor = None;
- self.flash = None;
- // Thumbnail drags hold page indexes from before the change.
- self.panel_drag = None;
- self.org_drag = None;
- self.reset_coarse_state();
- }
-
- /// 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
- /// 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;
- fresh.organize = self.organize;
- fresh.grid_zoom = self.grid_zoom;
- fresh.thumbnail_zoom = self.thumbnail_zoom;
- // Same document id, so the scroll offset egui keeps for it is still this document's.
- fresh.shown = self.shown;
- fresh.highlight_fields = self.highlight_fields;
- fresh.notice_dismissed = self.notice_dismissed;
- fresh.snapshot = self.snapshot.clone();
- fresh.close_requested = self.close_requested;
- fresh.cover = self.cover;
- // Still presenting, with the display to go back to on leaving.
- fresh.presentation = self.presentation.take();
- 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;
- *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()));
- self.page_input_reselect = true;
- }
-
- /// Select pages in the organize grid (tests, automation). Empty clears the selection.
- 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();
- }
-}
-
-/// Draws the document tab at `index`: its notice bars, then its pages (or the Organize grid) in a
-/// scroll area with this frame's zoom, scrolling, tool input, overlays and render requests.
-#[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);
- }
-}
-
-pub fn document_area(app: &mut PdfCraftApp, index: usize, ui: &mut egui::Ui) {
- let t = Tokens::get(ui.ctx());
- // Keyboard scrolling applies to this frame's page view only, never later.
- let key_scroll = std::mem::take(&mut app.views[index].key_scroll);
- if key_scroll != 0.0 {
- app.views[index].end_find_following();
- }
- // The Search panel closed: its search moves to the find bar.
- let search_open = app.right == Some(crate::RightPanel::Search);
- if let Some(f) = app.views[index].find.as_mut()
- && f.in_panel
- && !search_open
- {
- f.in_panel = false;
- }
- // The snapshot notice bar's Close was clicked: close here, where no document borrow is
- // held. The tab is looked up by id: indices may have shifted since the click, and the
- // flag rides its own view, so a stale flag can never close the wrong tab.
- let pending = app.views.get(index).filter(|v| v.close_requested).map(|v| v.id).and_then(|id| app.views.iter().position(|v| v.id == id));
- if let Some(i) = pending {
- app.views[i].close_requested = false;
- if app.has_unsaved_work(i) {
- app.close_request = Some(crate::CloseRequest::Tab(app.views[i].id));
- } else {
- app.close_tab(i);
- }
- return;
- }
- let Some(doc) = app.session.get(app.views[index].id) else { return };
- let info = &doc.info;
- let paper = app.session.reading_colors(app.views[index].id).and_then(|c| c.params).map_or(Color32::WHITE, |p| {
- let [r, g, b] = p.background;
- Color32::from_rgb(r, g, b)
- });
- if info.pages.is_empty() {
- app.views[index].auto_scroll.cancel();
- ui.centered_and_justified(|ui| ui.label(tl!("This document has no pages.")));
- return;
- }
- // The print dialog queues its own rasters later in the frame. Closing it drops them.
- if app.dialog != Some(crate::Dialog::Print) {
- app.views[index].print_pages.clear();
- }
- // The Prepare a form panel is open (or a field tool is picked): fields are edited, not filled.
- let preparing = app.is_preparing();
- // Prepare a form ▸ Calculation order: the order's steps and links on the page.
- let calc_order = preparing && app.left_open && app.left == crate::LeftPanel::CalculationOrder;
- // Edit a PDF: added text and images can be selected, moved and edited.
- let editing_content =
- (app.left_open && app.left == crate::LeftPanel::Tool("edit")) || matches!(app.quick_tool, QuickTool::AddText | QuickTool::EditText);
- let text_style = app.text_style.clone();
- let show_secured_notice = app.show_secured_notice;
- // Asking means opening the system clipboard (and decoding any image on it), so it's asked
- // once when a right-click opens a menu, not on every frame.
- 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)
- };
- let view = &mut app.views[index];
- // Opened without the owner password and something is restricted. The notice says so unless
- // the user turned it off (#4035): the restrictions themselves, and Document Properties ▸
- // Security, stay as they are.
- let secured = show_secured_notice && doc.security_summary().is_some_and(|s| !(s.owner || (s.permissions.modify() && s.permissions.assemble())));
- let repaired = !doc.repair_log().is_empty();
- match notices(view, doc, secured, repaired, crate::sign_ui::banner(&doc.signatures), ui, &t) {
- #[cfg(not(target_arch = "wasm32"))]
- Some(Notice::Reload) => app.watch.reload_request = Some(view.id),
- #[cfg(target_arch = "wasm32")]
- Some(Notice::Reload) => {}
- Some(Notice::Repairs) => app.dialog = Some(crate::Dialog::Properties(crate::PropsTab::Advanced)),
- Some(Notice::Security) => app.dialog = Some(crate::Dialog::Properties(crate::PropsTab::Security)),
- Some(Notice::Unlock) => app.unlock_prompt = Some(crate::UnlockPrompt::new(doc, None)),
- // Flags the view: the tab closes at the top of the next frame, where no document
- // borrow is held.
- Some(Notice::Close) => {
- if let Some(view) = app.views.get_mut(index) {
- view.close_requested = true;
- }
- }
- Some(Notice::Signatures) => app.right = Some(RightPanel::Signatures),
- Some(Notice::FieldHighlights(on)) => app.view_defaults.highlight_fields = on,
- Some(Notice::Console) => app.dialog = Some(crate::Dialog::JsConsole),
- // Back on in Preferences ▸ General.
- Some(Notice::HideSecured) => app.show_secured_notice = false,
- None => {}
- }
- // No dialog, close prompt or palette over the page: only then does page input count.
- let modal = app.modal_open();
- let unobstructed = !modal && !app.palette_open;
- let organize_zoom = app.organize_zoom;
- let view = &mut app.views[index];
- if view.organize {
- // One remembered grid size for every document, kept in the settings.
- view.set_grid_zoom(organize_zoom);
- organize_grid(view, info, doc.allows_assembly(), doc.dirty, unobstructed, ui, &t);
- app.organize_zoom = view.grid_zoom();
- return;
- }
-
- let avail = ui.available_rect_before_wrap();
- view.viewport_w = avail.width();
- view.viewport_h = avail.height();
- let old_zoom = view.zoom;
- view.fit_zoom(info);
- if view.shown && view.zoom_anchor.is_none() && view.goto.is_none() && view.goto_point.is_none() && (view.zoom - old_zoom).abs() > 1e-4 {
- let prev_viewport = view.viewport_screen;
- let top_y = prev_viewport.min.y;
- let anchor = view
- .screen_rects
- .iter()
- .find(|(_, r)| r.min.y <= top_y && r.max.y > top_y)
- .map(|(p, r)| {
- let fy = if r.height() > 0.0 { ((top_y - r.min.y) / r.height()).clamp(0.0, 1.0) } else { 0.0 };
- (*p, fy, 0.0f32)
- })
- .or_else(|| view.screen_rects.iter().find(|(_, r)| r.min.y >= top_y).map(|(p, r)| (*p, 0.0f32, (r.min.y - top_y).max(0.0))))
- .or_else(|| view.screen_rects.last().map(|(p, r)| (*p, 1.0f32, (r.max.y - top_y).max(0.0))));
- if let Some((page, fy, rel_y)) = anchor {
- view.zoom_anchor = Some((page, 0.5, fy, vec2(avail.width() / 2.0, rel_y)));
- } else {
- view.zoom_anchor = Some((view.current, 0.5, 0.0, vec2(avail.width() / 2.0, MARGIN)));
- }
- }
-
- // Pinch / ctrl+scroll zoom, anchored on the current page.
- let zoom_delta = crate::motion::zoom_delta(ui.ctx());
- // Exclude the previous frame's scrollbar tracks from gesture activation.
- let navigation_rect = if view.viewport_screen.is_positive() { avail.intersect(view.viewport_screen) } else { avail };
- let navigation_enabled = app.dialog.is_none() && app.close_request.is_none() && !app.palette_open && ui.is_enabled() && ui.input(|i| i.focused);
- // Full screen: a click on the document goes forward a page and a shift-click back, as in
- // Acrobat, unless the click did something else (a link, a word selected). Decided below,
- // once the pages have had the click.
- let present_click =
- view.presentation.is_some() && navigation_enabled && presentation_click(ui, navigation_rect) && app.quick_tool == QuickTool::Select;
- // Shift as held now, or as the click's own event carried it (a synthetic click).
- let present_back = present_click
- && ui.input(|i| {
- i.modifiers.shift
- || i.events.iter().any(|e| {
- matches!(e, egui::Event::PointerButton { button: egui::PointerButton::Primary, pressed: false, modifiers, .. } if modifiers.shift)
- })
- });
- if zoom_delta.is_finite() && zoom_delta > 0.0 && zoom_delta != 1.0 && navigation_enabled && ui.rect_contains_pointer(navigation_rect) {
- let z = view.zoom * zoom_delta;
- match zoom_anchor(ui) {
- Some(p) => view.zoom_at(z, p),
- None => view.set_zoom(z),
- }
- }
- view.viewport_screen = avail;
- let auto_delta = if unobstructed {
- view.auto_scroll.update(ui, avail, false)
- } else {
- view.auto_scroll.cancel();
- Vec2::ZERO
- };
-
- // Drawing a comment: the pointer in a band along any edge (or just past it) scrolls the view
- // that way, so a point beyond what is shown can be reached without letting go of the tool.
- let edge_delta = if unobstructed && matches!(view.comments.gesture, Some(comments::Gesture::Draw { .. })) {
- let (pointer, dt) = drawing_edge_pointer(ui);
- crate::autoscroll::edge_scroll(pointer, avail, dt)
- } else {
- Vec2::ZERO
- };
- if edge_delta != Vec2::ZERO {
- ui.ctx().request_repaint();
- }
-
- let content_w = view.content_width(info, avail.width());
- let rects = view.layout(info, content_w, ui.ctx().pixels_per_point());
- // When not scrolling continuously, only one row is shown at a time: the current page, or the
- // current two-page spread (with the cover rule). These indices drive paging, which pages are
- // drawn, and the content height (#752). Empty for a document with no pages.
- let shown_row = |view: &DocView| -> Vec<usize> {
- if rects.is_empty() {
- return Vec::new();
- }
- let last = rects.len() - 1;
- let cur = view.current.min(last);
- match view.layout {
- PageLayout::Single => vec![cur],
- PageLayout::TwoUp if view.cover && cur == 0 => vec![0],
- PageLayout::TwoUp => {
- let first = if view.cover { cur - (cur + 1) % 2 } else { cur - cur % 2 };
- if first < last { vec![first, first + 1] } else { vec![first] }
- }
- }
- };
- let row = shown_row(view);
- let middle_gesture = view.auto_scroll.blocks_input();
- // Not scrolling: when the whole page or spread fits, the wheel would do nothing, so it turns
- // pages instead; zoomed in far enough to pan, it pans, and at the edge it turns the page on
- // (#1924, `single_page_wheel_edge`). Touch drags are untouched: with
- // nothing to pan, touch users turn pages with the rail buttons, the page box and the arrow
- // keys. Runs before `visible_pages` so the frame that turns the page draws it.
- let mut single_paging = false;
- let mut edge_turned = false;
- if !view.continuous {
- // The row's bounding box on screen (one page, or a two-page spread).
- let row_rect = row.iter().filter_map(|&i| rects.get(i)).copied().reduce(Rect::union);
- // Within a point, so layout rounding can't stop a fitting page from turning.
- let fits = row_rect.is_some_and(|r| r.height() + 2.0 * MARGIN <= avail.height() + 1.0);
- let can_turn = !middle_gesture && unobstructed && ui.rect_contains_pointer(avail);
- single_paging = can_turn && fits;
- // Every wheel event goes to the pager, so it follows each trackpad touch to its end
- // even while the page can't turn.
- ui.input(|i| {
- for e in &i.events {
- if let egui::Event::MouseWheel { unit, delta, phase, modifiers, .. } = e {
- // Zooming (⌘ or Ctrl) and sideways scrolling (Shift) never turn pages.
- let dy = if modifiers.command || modifiers.ctrl || modifiers.shift { 0.0 } else { delta.y };
- if fits {
- view.single_page_wheel(*unit, dy, *phase, i.time, can_turn);
- } else {
- edge_turned |= view.single_page_wheel_edge(*unit, dy, *phase, i.time, can_turn);
- }
- }
- }
- });
- if single_paging {
- // Paging owns vertical wheel motion here. A diagonal gesture keeps its sideways
- // part, as `ScrollArea` itself handles each axis.
- ui.input_mut(|i| i.smooth_scroll_delta.y = 0.0);
- }
- }
- // Point input bypasses egui smoothing for 1:1 motion. Line input keeps egui's configured,
- // smoothed base and adds only the accelerated surplus. While point suppression is active,
- // reconstruct line and page input here so current coarse events survive without exposing an
- // older eased tail.
- let now = ui.input(|i| i.time);
- let input = if ui.rect_contains_pointer(avail) {
- // Match the line distance used by egui's other scroll areas.
- let live = ui.ctx().options(|o| o.input_options.line_scroll_speed);
- let line_points = if live.is_finite() && live > 0.0 { live } else { crate::scroll_speed::EGUI_LINE_POINTS };
- ui.input(|i| crate::wheel_boost::accumulate(&i.events, line_points, single_paging))
- } else {
- crate::wheel_boost::FrameInput::default()
- };
- let mut precise_scroll = input.precise;
- let mut line_base = input.line;
- let mut boost_extra = crate::wheel_boost::boost_extra(input, &mut view.wheel_boost_x, &mut view.wheel_boost_y, now);
- let has_page = input.page != Vec2::ZERO;
- if now.is_finite() && precise_scroll != Vec2::ZERO && !has_page {
- view.precise_scroll_until = now + SUPPRESS_SECS;
- }
- if edge_turned {
- // The turn leaves egui's eased copy of the notch to decay for a few frames; it must not
- // scroll the page just shown away from its top (or bottom).
- view.precise_scroll_until = now + 0.25;
- view.fling.stop();
- }
- let paging_owns_vertical = single_paging || (!view.continuous && view.wheel.gesture_turned());
- if paging_owns_vertical {
- precise_scroll.y = 0.0;
- line_base.y = 0.0;
- boost_extra.y = 0.0;
- }
- // egui smooths a Point event that moved at least 8 points, keeping part of it for later
- // passes. Suppression must outlive that whole action: once it expired after a fixed 0.25 s,
- // the last few eased points leaked through the ScrollArea after a precise 1:1 scroll (held
- // point input measured 33 points for a 30-point event). Keep hiding the eased copy until
- // egui says the action is over, then forget the suppression.
- let scrolling = ui.input(|i| i.is_scrolling());
- if now < view.precise_scroll_until || (view.precise_scroll_until != 0.0 && scrolling) {
- if scrolling {
- // Keep hiding egui's unprocessed copy until it has drained. The short rolling grace
- // avoids a delayed duplicate without prolonging suppression after the tail is gone.
- view.precise_scroll_until = view.precise_scroll_until.max(now + SUPPRESS_TAIL_SECS);
- }
- ui.input_mut(|i| i.smooth_scroll_delta = Vec2::ZERO);
- // The point path suppresses every eased wheel delta. Restore the line base through the
- // same un-eased path as its surplus; paging-owned axes were cleared above.
- boost_extra = crate::wheel_boost::cap_frame(boost_extra + line_base);
- if has_page {
- // Page units normally stay on egui's viewport-sized path. During suppression only,
- // reproduce the current event directly so an older hidden tail stays hidden.
- let page_scale = ui.input(|i| i.viewport_rect().height());
- let mut page_delta =
- if page_scale.is_finite() && page_scale > 0.0 { crate::wheel_boost::cap_frame(input.page * page_scale) } else { Vec2::ZERO };
- if paging_owns_vertical {
- page_delta.y = 0.0;
- }
- boost_extra = crate::wheel_boost::cap_frame(boost_extra + page_delta);
- }
- } else {
- precise_scroll = Vec2::ZERO;
- // Selection handling below uses zero to distinguish an inactive window. Clearing a past
- // deadline also keeps a later line/page action from being mistaken for the old tail.
- view.precise_scroll_until = 0.0;
- }
- if has_page && paging_owns_vertical {
- // Page input belongs to egui on the free axis; the pager still owns vertical motion.
- ui.input_mut(|i| i.smooth_scroll_delta.y = 0.0);
- }
- // Touchpad momentum (#531): a swipe over the page lifted at speed glides on and slows to a
- // stop, through the same un-eased path. Never while the pager owns the wheel, a gesture or
- // dialog has the input, or animations are off; any click, key, zoom or other scrolling ends it.
- // Asked of the preference, not of egui's animation time, which test harnesses zero.
- let animates = app.animation_effects.animates(app.motion.reduced);
- let may_glide = !paging_owns_vertical && !middle_gesture && navigation_enabled && unobstructed && animates;
- let over_page = ui.rect_contains_pointer(avail);
- ui.input(|i| view.fling.read(&i.events, now, may_glide && over_page));
- let interrupted = glide_interrupted(ui);
- if !may_glide || interrupted || key_scroll != 0.0 || auto_delta != Vec2::ZERO || zoom_delta != 1.0 {
- view.fling.stop();
- }
- let glide = view.fling.step(now);
- if view.fling.gliding() {
- ui.ctx().request_repaint();
- }
- // Any reader-owned motion ends automatic search following, even when it stays on the same
- // page: the wheel, keyboard, middle-button auto-scroll, a drawing's edge scroll, or the
- // momentum left by a touchpad swipe. The automatic flash uses `goto`, not these deltas, so
- // its programmatic scroll is never mistaken for a reader action.
- let wheel_scrolled = precise_scroll != Vec2::ZERO || line_base != Vec2::ZERO || boost_extra != Vec2::ZERO || has_page;
- if wheel_scrolled || auto_delta != Vec2::ZERO || edge_delta != Vec2::ZERO || glide != Vec2::ZERO {
- view.end_find_following();
- }
- // The wheel may have turned the page above: draw the row it turned to. Measured from the old
- // row, the jump to the new page scrolled both out of view, a blank frame on every turn forward.
- let row = shown_row(view);
- let visible_pages: Vec<usize> = if view.continuous { (0..rects.len()).collect() } else { row.clone() };
- let (y_shift, content_h) = if view.continuous {
- (0.0, rects.iter().map(|r| r.bottom()).reduce(f32::max).map(|bottom| bottom + MARGIN).unwrap_or(0.0))
- } else {
- // Only the current row scrolls into view; the content is its bounding box plus margins.
- match row.iter().filter_map(|&i| rects.get(i)).copied().reduce(Rect::union) {
- Some(r) => (r.top() - MARGIN, r.height() + 2.0 * MARGIN),
- None => (0.0, 0.0),
- }
- };
-
- let mut scroll = egui::ScrollArea::both().auto_shrink([false, false]).scroll_source(egui::scroll_area::ScrollSource {
- drag: if middle_gesture {
- egui::scroll_area::DragScroll::Never
- } else if app.quick_tool == QuickTool::Hand {
- egui::scroll_area::DragScroll::Always
- } else {
- egui::scroll_area::DragScroll::OnTouch
- },
- ..Default::default()
- });
- // Each document keeps its own scroll position when switching tabs (#189).
- scroll = scroll.id_salt(("page-view", view.id));
- // When a page jump or programmatic reposition occurs, or in non-continuous page display
- // where single-page wheel turns jump to the page edge, disable animation so egui's
- // queued target does not overwrite or ease the jump. For continuous page scrolling,
- // animate if motion effects are enabled.
- let has_jump = !view.shown
- || edge_turned
- || view.goto.is_some()
- || view.goto_point.is_some()
- || view.zoom_anchor.is_some()
- || view.sync_scroll.is_some()
- || (app.quick_tool == QuickTool::Hand && !middle_gesture && view.page_widget.is_some_and(|id| ui.ctx().is_being_dragged(id)));
- scroll = scroll.animated(view.continuous && animates && !has_jump);
- // A newly opened document starts at the top. eframe saves egui's memory with the settings
- // and document ids start again at 1 every launch, so the offset stored under this id can be
- // where an earlier session left another document.
- if !std::mem::replace(&mut view.shown, true) {
- scroll = scroll.scroll_offset(Vec2::ZERO);
- }
- // The Hand tool pans here, before the pages are laid out, so the page moves with the pointer
- // in the frame the pointer moves (#924). Scrolling by the drag from inside the area moved the
- // page only after that frame was drawn, a frame behind. The frame egui tells the drag from a
- // click, the page catches up with all the pointer has moved since the press. A jump asked for
- // below still wins.
- if app.quick_tool == QuickTool::Hand
- && !middle_gesture
- && let Some(id) = view.page_widget.filter(|id| ui.ctx().is_being_dragged(*id))
- {
- let moved = if ui.ctx().drag_started_id() == Some(id) {
- ui.input(|i| i.pointer.total_drag_delta()).unwrap_or(Vec2::ZERO)
- } else {
- ui.input(|i| i.pointer.delta())
- };
- if moved != Vec2::ZERO {
- view.end_find_following();
- }
- // Within the content, as egui keeps it: past an end the page would show there for a
- // frame and spring back. `max` is never NaN or below zero, so the clamp can't panic.
- let max = vec2((content_w - avail.width()).max(0.0), (content_h - avail.height()).max(0.0));
- scroll = scroll.scroll_offset((view.last_scroll - moved).clamp(Vec2::ZERO, max));
- }
- if let Some(v) = view.sync_scroll.take() {
- scroll = scroll.scroll_offset(v);
- }
- if let Some((page, fx, fy, rel)) = view.zoom_anchor.take() {
- let r = rects[page.min(rects.len() - 1)];
- let point = pos2(r.left() + fx * r.width(), r.top() - y_shift + fy * r.height());
- scroll = scroll.scroll_offset(anchored_scroll(point, rel, vec2(content_w, content_h), avail.size()));
- } else if let Some((page, frac)) = view.goto.take() {
- let page = page.min(rects.len() - 1);
- let r = rects[page];
- // Clamped here: egui clamps only after drawing, so a page that fits was drawn MARGIN - page_gap()
- // too high for a frame and then hopped into place. (`avail` is the viewport, as the
- // scroll bars float.)
- let max_y = (content_h - avail.height()).max(0.0);
- scroll = scroll.vertical_scroll_offset((r.top() - y_shift - view.page_gap() + frac * r.height()).max(0.0).min(max_y));
- // Horizontally too, as Acrobat does (#2665): beside a much wider page the others sit off
- // to one side. A page already shown whole, or one filling the window's width, keeps the
- // scroll, so paging through a zoomed-in document stays on the same column. Otherwise a
- // page that fits is centred, and a wider one scrolled just far enough to fill the window.
- // The page counts with its side gutters, which keep its edge clear of the floating
- // quick-action bar as the layout does.
- let (x, w) = (view.last_scroll.x, avail.width());
- let (left, right) = (r.left() - SIDE, r.right() + SIDE);
- let target = if right - left <= w { if left >= x && right <= x + w { x } else { r.center().x - w / 2.0 } } else { x.clamp(left, right - w) };
- if (target - x).abs() > 0.5 {
- scroll = scroll.horizontal_scroll_offset(target.clamp(0.0, (content_w - w).max(0.0)));
- }
- }
- let ppp = ui.ctx().pixels_per_point();
- let scale = view.render_scale(ppp);
- let tag = scale_tag(scale);
- // Hold sharp re-renders while the zoom is still moving: a new scale every frame would
- // cancel the in-flight full-page interpret and restart it, so on a heavy page (a CAD
- // plot with ~1000 images renders for seconds) the sharp raster never arrives and the
- // view looks stuck on a soft image. The stale raster stays stretched meanwhile; the
- // sharp request goes out once the zoom settles.
- let now_scale = ui.input(|i| i.time);
- if (scale - view.last_scale).abs() > f32::EPSILON {
- view.last_scale = scale;
- view.sharp_hold_until = now_scale + 0.35;
- ui.ctx().request_repaint_after(std::time::Duration::from_millis(380));
- }
- let sharp_held = now_scale < view.sharp_hold_until;
- view.current_scale_tag = tag;
- let hand = app.quick_tool == QuickTool::Hand;
- let tool = app.quick_tool;
- // Text selection runs for the Select tool and for the markup tools (highlight…).
- let selects_text = match tool {
- QuickTool::Comment(t) => t.markup().is_some() || t == comments::CommentTool::ReplaceText,
- QuickTool::Select => !preparing,
- QuickTool::Redact | QuickTool::ColumnSelect => true,
- QuickTool::Hand
- | QuickTool::Measure(_)
- | QuickTool::Crop
- | QuickTool::EnhanceCamera
- | QuickTool::Fill(_)
- | QuickTool::Field(_)
- | QuickTool::AddText
- | QuickTool::EditText
- | QuickTool::Stamp(_)
- | QuickTool::CustomStamp(_)
- | QuickTool::Link
- | QuickTool::SignArea { .. }
- | QuickTool::MarqueeZoom
- | QuickTool::Snapshot => false,
- };
- let prefs = &app.comment_prefs;
- let redact_mark = (app.redact_prefs.hover_fill, app.redact_prefs.opacity);
- let units = app.units;
- let allowed = doc.allows_annotation();
- let can_copy = doc.allows_copying();
- let mut copy_selected = false;
- let comments_hidden = doc.comments_hidden();
- let form = doc.form.clone();
- let generation = doc.edit_generation();
- let can_fill = doc.allows_form_filling();
- let can_crop = doc.allows_assembly();
- let mut open_boxes = false;
- let signature = app.signature.clone();
- let initials = app.initials.clone();
- let mut open_initials = false;
- let author = app.comment_prefs.author.clone();
- let today = app.session.today();
- // In Preferences ▸ Date format, or why it can't be stamped into the PDF.
- let date_text = crate::date_text_for_pdf(&app.session);
- let mut refused: Option<String> = None;
- let by_line = app.session.stamp_by_line(&author);
- let mut stamp_placed = false;
- let mut image_action: Option<crate::edit_text_ui::ImageAction> = None;
- let custom_stamp = match app.quick_tool {
- QuickTool::CustomStamp(i) => app.custom_stamps.get(i).cloned(),
- _ => None,
- };
- let mut open_signature = false;
- let mut hover_text: Option<(Pos2, String)> = None;
- let mut badge_hover: Option<(Pos2, String)> = None;
- let mut clicked_link: Option<LinkTarget> = None;
- let mut remote_open: Option<(pdfcraft_engine::DocId, String, pdfcraft_render::RemoteDestination)> = None;
- let mut canvas_action: Option<comments::CanvasAction> = None;
- let mut page_action: Option<PageMenuAction> = None;
- let mut field_menu: Option<FieldMenu> = None;
- let mut open_props: Option<(usize, usize)> = None;
- let mut field_props = false;
- let mut field_placed = false;
- let mut open_table: Option<(usize, [f64; 4])> = None;
- // The table being set up in its window, shown on its own document's page.
- let table_preview = app.field_table_draft.as_mut().filter(|d| d.doc == view.id).and_then(|d| Some(d.preview(info.pages.get(d.page)?, &form)));
- let can_modify = doc.allows_modification();
- if preparing {
- crate::prepare::after_refresh(view, &form);
- } else {
- view.prepare.selected = None;
- }
- view.objects.prepare(doc, tool == QuickTool::EditText && can_modify, ui.ctx());
- view.text_background.prepare(ui.ctx(), doc, view.line_editor.as_ref(), view.content.draft.as_ref(), scale);
- let added = if editing_content { doc.added().to_vec() } else { Vec::new() };
- let doc_links = if tool == QuickTool::Link { doc.links().to_vec() } else { Vec::new() };
- if editing_content {
- crate::content_ui::after_refresh(view, &added);
- } else {
- view.content.selected = None;
- }
- view.move_background.prepare(ui.ctx(), doc, &view.content, scale);
-
- // A destination's position (bookmarks, links) refines `goto`: its point at the window's
- // top-left, or the centre of a /FitR rectangle at the window's centre.
- if let Some((page, fx, fy, rel)) = view.goto_point.take() {
- let r = rects[page.min(rects.len() - 1)];
- // Within the content, so an unreachable point never shows a frame scrolled past the end.
- let (max_x, max_y) = ((content_w - avail.width()).max(0.0), (content_h - avail.height()).max(0.0));
- if let Some(fx) = fx {
- scroll = scroll.horizontal_scroll_offset((r.left() + fx * r.width() - rel.x).clamp(0.0, max_x));
- }
- if let Some(fy) = fy {
- scroll = scroll.vertical_scroll_offset((r.top() - y_shift + fy * r.height() - rel.y).clamp(0.0, max_y));
- }
- }
- let selection_wheel = view.selection_drag && navigation_enabled && unobstructed && !single_paging && ui.rect_contains_pointer(avail);
- let out = page_scroll(ui, scroll, egui::Id::unique(("page-view-scope", view.id)), |ui, viewport| {
- // egui's drag responses accept every pointer button. Keep a wheel gesture from also
- // selecting text, drawing a mark, or panning with the Hand tool.
- if middle_gesture {
- let opacity = ui.opacity();
- ui.disable();
- // Only interactions pause; the document must keep its original colours.
- ui.set_opacity(opacity);
- }
- // Middle-button auto-scroll, the keyboard, precise touchpad input (#759) and its glide
- // (#531), accelerated wheel surplus (#1072), and a drawing's edge scroll; positive y
- // moves the content down. All scroll without easing, unlike egui's wheel default.
- // ScrollArea ignores wheel input during a widget drag. Defer the wheel contribution
- // until after the text widgets when a selection owns that drag.
- let wheel_delta = if selection_wheel { Vec2::ZERO } else { precise_scroll + boost_extra };
- let delta = auto_delta + edge_delta - vec2(0.0, key_scroll) + wheel_delta + glide;
- if delta != Vec2::ZERO && delta.is_finite() {
- let anim = if animates && key_scroll != 0.0 { ui.style().scroll_animation } else { egui::style::ScrollAnimation::none() };
- ui.scroll_with_delta_animation(delta, anim);
- }
- let (resp_rect, resp) = ui.allocate_exact_size(vec2(content_w, content_h), Sense::click_and_drag());
- view.page_widget = Some(resp.id);
- // A drag lasts only while egui reports it, so the mark can't outlive one.
- if !resp.dragged_by(egui::PointerButton::Primary) {
- view.selection_drag = false;
- }
- // The Hand tool pans by this widget's drag, before the pages are laid out (above).
- if hand {
- if resp.dragged() {
- ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing);
- } else if resp.hovered() {
- ui.ctx().set_cursor_icon(egui::CursorIcon::Grab);
- }
- }
- let origin = resp_rect.min - vec2(0.0, y_shift);
- let painter = ui.painter();
- let visible = viewport.translate(resp_rect.min.to_vec2());
- let mut wanted = Vec::new();
- let mut visible_now = Vec::new();
- view.screen_rects.clear();
- view.screen_xforms.clear();
- for &i in &visible_pages {
- let r = snap_to_pixels(rects[i].translate(origin.to_vec2()), ppp);
- if r.intersects(visible) {
- 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) }));
- }
- }
- // Visible heights (points) closer than this are equal: one page size can meet the
- // viewport a fraction of a point differently once the scroll offset is applied.
- const TIE: f32 = 0.5;
- let mut current = view.current;
- let mut best_overlap = -1.0f32;
- let mut current_overlap = -1.0f32;
- let mut current_height = f32::INFINITY;
- // The pointer as the pages see it: nothing over them (a dialog from the frame it opens),
- // or a press they hold. The page modules read it rather than egui's raw pointer state.
- let ptr = PagePointer::read(ui, &resp, modal);
- let pointer = ptr.pos;
- // A press on a page makes it the current one (as in Acrobat), so a page command with
- // no selection (Rotate, Delete) acts on the page the reader pointed at, not on a page
- // gone to earlier that still shows whole beside it.
- let pressed = unobstructed && ptr.pressed().is_some();
- let mut pressed_page = None;
- if resp.secondary_clicked() {
- // Set again below when the right-click lands on a link.
- view.links.context = None;
- let mut over_image = false;
- if tool == QuickTool::EditText {
- let pointer_pos = ptr.pos;
- if let Some(p) = pointer_pos {
- for (page_idx, xf) in &view.screen_xforms {
- let images = doc.page_images(*page_idx);
- for (idx, img) in images.iter().enumerate().rev() {
- let obb = ImageObb::from_image(img, xf, info, *page_idx);
- let b = image_screen_rect(img, xf, info, *page_idx);
- if (b.is_positive() && b.contains(p)) || crate::edit_text_ui::quad_contains(obb.corners(), p) {
- over_image = true;
- if view.image_selection.as_ref().is_none_or(|s| s.page != *page_idx || s.index != idx) {
- view.image_selection = Some(crate::edit_text_ui::ImageSelection {
- page: *page_idx,
- index: idx,
- drag: None,
- crop: None,
- crop_mode: false,
- crop_rect: None,
- turning: false,
- settled: None,
- });
- }
- break;
- }
- }
- if over_image {
- break;
- }
- }
- }
- }
- ui.ctx().data_mut(|d| d.insert_persisted(crate::edit_text_ui::image_menu_id(), over_image));
- }
- let mut calc_hover = None;
- for &i in &visible_pages {
- badge_hover = None;
- let r = snap_to_pixels(rects[i].translate(origin.to_vec2()), ppp);
- if !r.intersects(visible.expand(400.0)) {
- continue;
- }
- if pressed && pressed_page.is_none() && pointer.is_some_and(|p| r.contains(p)) {
- pressed_page = Some(i);
- }
- if r.intersects(visible) {
- visible_now.push(i);
- }
- let overlap = r.intersect(visible).height();
- if i == view.current {
- current_overlap = overlap;
- current_height = r.height();
- }
- // Pages shown equally (two rows wholly on screen) differ only by rounding: the
- // topmost one counts.
- if overlap > best_overlap + TIE {
- best_overlap = overlap;
- current = i;
- }
- let xf = PageXform { rect: r, rot: view.rotation, pw: info.pages[i].width.max(1.0), ph: info.pages[i].height.max(1.0) };
- // Shadows would darken the preceding page when pages touch.
- if view.show_page_gaps {
- painter.add(egui::epaint::Shadow { offset: [0, 3], blur: 14, spread: 0, color: t.page_shadow }.as_shape(r, CornerRadius::ZERO));
- }
- painter.rect_filled(r, CornerRadius::ZERO, paper);
- if let Some(err) = view.errors.get(&i) {
- painter.rect_filled(r, CornerRadius::ZERO, Color32::from_rgb(0xFB, 0xF4, 0xF4));
- icons::paint(
- ui,
- Rect::from_center_size(r.center() - vec2(0.0, 26.0), vec2(28.0, 28.0)),
- "triangle-alert",
- 26.0,
- Color32::from_rgb(0xC8, 0x3A, 0x3A),
- );
- let message = crate::i18n::fmt(tl!("This page couldn't be displayed.\n{e}"), &[("e", err)]);
- let msg =
- ui.fonts_mut(|f| f.layout(message, theme::regular(12.5), Color32::from_rgb(0x6A, 0x2A, 0x2A), (r.width() - 40.0).max(80.0)));
- painter.galley(pos2(r.center().x - msg.size().x / 2.0, r.center().y), msg, Color32::BLACK);
- } else {
- let (pw_pt, ph_pt) = (info.pages[i].width.max(1.0), info.pages[i].height.max(1.0));
- // A GPU may take smaller textures than these (OpenGL drivers report as little as
- // 2048 pixels, and uploading a bigger one aborts), so both stay within its limit.
- let max_side = ui.ctx().input(|inp| inp.max_texture_side) as f32;
- let tiled = pw_pt.max(ph_pt) * scale > TILE_THRESHOLD.min(max_side);
- // Whole-page raster: sharp when small, a low-res backdrop when tiled.
- let (want_scale, want_tag) = if tiled {
- let bs = BASE_SIDE.min(max_side) / pw_pt.max(ph_pt);
- (bs, scale_tag(bs))
- } else {
- (scale, tag)
- };
- // Under tiles, a whole-page raster sharper than the backdrop (from before the page
- // grew past the tiling size) is a better backdrop: keep demanding it as it is.
- match view.pages.get(&i).filter(|p| tiled && p.tag != STALE_TAG && tag_scale(p.tag) >= want_scale) {
- Some(p) => wanted.push((i, tag_scale(p.tag), p.tag, None)),
- None => wanted.push((i, want_scale, want_tag, None)),
- }
- let active_drag_suppress = if let Some(sel) = view.image_selection.as_ref()
- && sel.page == i
- && sel.drag.is_some()
- {
- let images = doc.page_images(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) {
- // 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;
- }
- 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,
- );
- }
- }
- }
- }
- view.text_background.paint(painter, &xf, i, view.line_editor.as_ref(), view.content.draft.as_ref());
- if editing_content {
- view.move_background.paint(painter, &xf, i, info, &view.content, pointer);
- }
- if view.show_page_gaps {
- painter.rect_stroke(r, CornerRadius::ZERO, Stroke::new(0.5, t.border.gamma_multiply(0.8)), egui::StrokeKind::Outside);
- }
-
- // Comments: tools, selection, moving and resizing come before text selection.
- let pcx = comments::PageCx { page: i, xf: &xf, ptr: &ptr, info, tool, prefs, allowed, hidden: comments_hidden, redact_mark };
- if let QuickTool::Measure(measure_tool) = tool {
- crate::measure_ui::page_input(ui, &resp, doc, view, &pcx, measure_tool, units);
- }
-
- // Form fields take clicks first with the Select tool (as Acrobat fills fields in
- // every viewing mode); then comments; then text selection.
- if let QuickTool::Stamp(kind) = tool
- && allowed
- && let Some(p) = ptr.within(xf.rect)
- {
- ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair);
- if resp.clicked() {
- // Centred on the click, upright as the page is shown.
- let (vx, vy) = xf.screen_to_view(p);
- let (w, h) = kind.size();
- let corners = [(vx as f64 - w / 2.0, vy as f64 - h / 2.0), (vx as f64 + w / 2.0, vy as f64 + h / 2.0)];
- let u: Vec<[f32; 2]> = corners.iter().map(|(x, y)| info.pages[i].view_to_user(*x as f32, *y as f32)).collect();
- let rect = [u[0][0].min(u[1][0]) as f64, u[0][1].min(u[1][1]) as f64, u[0][0].max(u[1][0]) as f64, u[0][1].max(u[1][1]) as f64];
- let by = (kind.group() == pdfcraft_engine::StampGroup::Dynamic).then(|| by_line.clone());
- let shape = pdfcraft_engine::Shape::Stamp { rect, stamp: kind, by };
- view.pending_edit = Some(pdfcraft_engine::Edit::AddAnnotation(pdfcraft_engine::NewAnnotation {
- page: i,
- style: pdfcraft_engine::Style::default_for(&shape),
- shape,
- contents: String::new(),
- author: author.clone(),
- }));
- stamp_placed = true;
- }
- }
- if let Some(cs) = custom_stamp.as_ref()
- && allowed
- && let Some(p) = ptr.within(xf.rect)
- {
- ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair);
- if resp.clicked() {
- // Centred on the click at its natural size (the engine sizes it).
- let (vx, vy) = xf.screen_to_view(p);
- let u = info.pages[i].view_to_user(vx, vy);
- let (x, y) = (u[0] as f64, u[1] as f64);
- view.pending_edit = Some(pdfcraft_engine::Edit::AddCustomStamp {
- page: i,
- rect: [x, y, x, y],
- name: cs.name.clone(),
- file: pdfcraft_engine::MarkFile { name: cs.file.clone(), bytes: cs.data.clone(), page: cs.page },
- author: author.clone(),
- });
- stamp_placed = true;
- }
- }
- // Over a mark already placed, the Fill & Sign tool picks it up (comments, below).
- if let QuickTool::Fill(ft) = tool
- && allowed
- && !comments::fill_grabs(&pcx, view)
- {
- match crate::fill_sign::page_input(
- ui,
- &resp,
- &xf,
- &ptr,
- i,
- info,
- ft,
- app.fill_text_size,
- view,
- signature.as_ref(),
- initials.as_ref(),
- &mut app.signature_preview,
- &author,
- &date_text,
- ) {
- Some(crate::fill_sign::FillAction::Edit(e)) => view.pending_edit = Some(*e),
- Some(crate::fill_sign::FillAction::Signature(e)) => {
- view.pending_edit = Some(*e);
- view.fill_signature_page = Some(i);
- }
- Some(crate::fill_sign::FillAction::CreateSignature) => open_signature = true,
- Some(crate::fill_sign::FillAction::CreateInitials) => open_initials = true,
- Some(crate::fill_sign::FillAction::Refused(why)) => refused = Some(why),
- None => {}
- }
- }
- if matches!(tool, QuickTool::SignArea { .. }) {
- crate::sign_ui::page_input(ui, &resp, &xf, &ptr, i, info, view);
- }
- if matches!(tool, QuickTool::MarqueeZoom | QuickTool::Snapshot) {
- crate::zoom_snap::page_input(ui, &resp, &xf, &ptr, i, view);
- }
- if tool == QuickTool::EnhanceCamera {
- crate::camera_ui::page_input(ui, &resp, &xf, &ptr, i, view, can_modify);
- }
- if tool == QuickTool::Crop && crate::crop::page_input(ui, &resp, &xf, &ptr, i, info, view, can_crop) {
- view.current = i;
- open_boxes = true;
- }
- // `over_field`: a form field is under the pointer and has set its cursor.
- let (on_field, over_field) = if preparing {
- let field_tool = match tool {
- QuickTool::Field(f) => Some(f),
- _ => None,
- };
- // While a table is being set up, nothing else is drawn or moved.
- let allowed = can_modify && table_preview.is_none() && open_table.is_none();
- let o = crate::prepare::page_input(ui, &resp, &xf, &ptr, i, info, &form, field_tool, allowed, view);
- field_props |= o.properties;
- field_placed |= o.placed;
- open_table = open_table.or(o.table);
- (o.consumed || field_tool.is_some(), false)
- } else {
- use crate::forms_ui::FieldPointer;
- let field = if tool == QuickTool::Select
- && !(editing_content && can_modify && crate::content_ui::select_grabs(&xf, &ptr, i, info, &added, view))
- && !comments::select_grabs(&pcx, view)
- {
- crate::forms_ui::page_input(ui, &resp, &xf, &ptr, i, info, &form, can_fill, view)
- } else {
- FieldPointer::Away
- };
- (field == FieldPointer::Owned, field == FieldPointer::Over)
- };
- // Redact draws boxes off text; so does Highlight (an area highlight, as in Acrobat).
- let area_tool = tool == QuickTool::Redact && can_modify || tool == QuickTool::Comment(comments::CommentTool::Highlight) && allowed;
- let boxing = area_tool && {
- let text = view.page_text(i);
- let over_text = |p: Pos2| {
- let (vx, vy) = xf.screen_to_view(p);
- text.as_ref().is_some_and(|t| t.glyphs.iter().any(|g| vx >= g.rect[0] && vx <= g.rect[2] && vy >= g.rect[1] && vy <= g.rect[3]))
- };
- crate::redact_ui::page_input(ui, &resp, &xf, &ptr, i, info, over_text, view)
- };
- let image_owns_pointer = tool == QuickTool::EditText && crate::edit_text_ui::image_owns_pointer(ui, &xf, &ptr, i, info, view);
- let on_objects =
- !image_owns_pointer && tool == QuickTool::EditText && can_modify && crate::object_ui::page_input(ui, &resp, &xf, &ptr, i, doc, view);
- let lines = if matches!(tool, QuickTool::AddText | QuickTool::EditText) && can_modify {
- let generation = doc.edit_generation();
- match view.edit_lines.get(&i) {
- Some((g, l)) if *g == generation => l.clone(),
- _ => {
- let l = doc.text_blocks(i);
- view.edit_lines.insert(i, (generation, l.clone()));
- l
- }
- }
- } else {
- Vec::new()
- };
- let over_source = tool == QuickTool::AddText
- && pointer.is_some_and(|p| {
- !crate::content_ui::hits_added(&xf, info, i, &added, p)
- && lines.iter().any(|line| xf.user_rect(info, i, line.rect.map(|v| v as f32)).expand(2.0).contains(p))
- });
- let source_blocked = over_source && view.content.hold_blocked();
- if over_source && resp.clicked() && !source_blocked {
- if let Some(edit) = view.content.finish_draft(&added) {
- view.pending_edit = Some(edit);
- }
- view.content.selected = None;
- }
- let on_content = !on_objects && editing_content && can_modify && {
- source_blocked
- || crate::content_ui::page_input(
- ui,
- &resp,
- &xf,
- &ptr,
- i,
- info,
- &added,
- tool == QuickTool::AddText && !over_source,
- matches!(tool, QuickTool::AddText | QuickTool::EditText),
- &text_style,
- view,
- )
- || tool == QuickTool::AddText && !over_source
- };
- // Added content owns its gesture; its source text must not queue a second edit.
- // Edit text & images boxes every paragraph and image whenever the tool is on. Only the
- // input waits while selected objects or added content own the pointer, or while page
- // input is blocked (another tab, a dialog, the window unfocused): the boxes stay drawn
- // instead of vanishing until the pointer comes back.
- let others_own_pointer = on_objects || on_content;
- let on_edit_text = (tool == QuickTool::EditText || over_source) && can_modify && {
- let generation = doc.edit_generation();
- let images = match view.edit_images.get(&i) {
- Some((g, l)) if *g == generation => l.clone(),
- _ => {
- let l = doc.page_images(i);
- view.edit_images.insert(i, (generation, l.clone()));
- l
- }
- };
- // Editable text takes precedence over background/overlapping artwork. Both
- // inventories are painted every frame, even when text owns the pointer.
- let text_used =
- crate::edit_text_ui::page_input(ui, &resp, &xf, &ptr, i, doc, &lines, view, !others_own_pointer && !image_owns_pointer);
- let image_used = crate::edit_text_ui::image_input(
- ui,
- &resp,
- &xf,
- &ptr,
- i,
- info,
- &images,
- view,
- &mut image_action,
- !others_own_pointer && (image_owns_pointer || !text_used),
- );
- !others_own_pointer && (text_used || image_used)
- };
- let on_link = tool == QuickTool::Link && can_modify && crate::link_ui::page_input(ui, &resp, &xf, &ptr, i, info, &doc_links, view);
- if tool == QuickTool::Select
- && resp.secondary_clicked()
- && can_modify
- && let Some(p) = pointer.filter(|p| xf.rect.contains(*p))
- && let Some(l) = doc.links().iter().find(|l| l.page == i && crate::link_ui::screen_rect(&xf, info, i, l.rect).expand(2.0).contains(p))
- {
- view.links.context = Some((i, l.index));
- }
- let consumed = on_objects || on_edit_text || on_link || on_content || boxing || on_field || comments::page_input(ui, &resp, &pcx, view);
-
- let preview_target =
- (matches!(tool, QuickTool::Select | QuickTool::Fill(_)) && !comments_hidden).then_some(view.comments.selected).flatten();
- view.signature_drag.prepare(ui.ctx(), doc, preview_target, scale);
- view.signature_drag.paint(painter, &pcx, &view.comments, view.pending_edit.as_ref());
-
- // Any press on the page ends Select All of the document: text read or not, any tool,
- // on a link too.
- // A press that lands on something drawn over the page (a menu, a dialog) is not one.
- if view.all_text && pressed_page == Some(i) {
- view.all_text = false;
- }
- // Text layer: find matches, selection, I-beam and drag-to-select.
- let to_screen = |g: [f32; 4]| xf.view_rect(g);
- if let Some(text) = view.texts.get(&i).cloned() {
- if let Some(f) = &view.find {
- for (k, (mp, range)) in f.matches.iter().enumerate() {
- if *mp != i {
- continue;
- }
- let current = f.current == Some(k);
- for lr in text.line_rects(range.clone()) {
- let fill = if current {
- Color32::from_rgba_unmultiplied(255, 140, 0, 110)
- } else {
- Color32::from_rgba_unmultiplied(255, 214, 0, 90)
- };
- painter.rect_filled(to_screen(lr).expand(1.0), CornerRadius::same(2), fill);
- }
- }
- }
- if view.all_text {
- for lr in text.line_rects(0..text.glyphs.len()) {
- painter.rect_filled(to_screen(lr), CornerRadius::same(1), Color32::from_rgba_unmultiplied(0x3A, 0x7B, 0xF0, 70));
- }
- }
- if let Some(sel) = view.selection.filter(|s| s.page == i) {
- for lr in sel.rects(&text) {
- painter.rect_filled(to_screen(lr), CornerRadius::same(1), Color32::from_rgba_unmultiplied(0x3A, 0x7B, 0xF0, 70));
- }
- // The rectangle being drawn, as Acrobat shows it while column-selecting.
- if let Span::Column { rect } = sel.span
- && resp.dragged()
- {
- let outline = Stroke::new(1.0, Color32::from_rgb(0x3A, 0x7B, 0xF0));
- painter.rect_stroke(to_screen(rect), CornerRadius::ZERO, outline, egui::StrokeKind::Middle);
- }
- }
- if selects_text
- && !consumed
- && let Some(p) = pointer.filter(|p| r.contains(*p))
- {
- let (vx, vy) = xf.screen_to_view(p);
- let over_text = text.glyphs.iter().any(|g| vx >= g.rect[0] && vx <= g.rect[2] && vy >= g.rect[1] && vy <= g.rect[3]);
- let over_link = info.links.iter().any(|l| l.page == i && xf.user_rect(info, i, l.rect).contains(p));
- // Column select (#740): the Column select tool, or Alt (Option on macOS) held
- // while a drag starts, as in Acrobat.
- let column = tool == QuickTool::ColumnSelect || ui.input(|inp| inp.modifiers.alt);
- // A link or a form field under the pointer keeps its own cursor: a check box
- // drawn with a glyph, or set on printed text, shows the hand, not the I-beam.
- // So do the mode bar and side panels over a page scrolled under them (#2755),
- // unless a selection is being dragged there.
- let cursor_free = !over_link && !over_field && (resp.contains_pointer() || resp.dragged());
- if column && cursor_free {
- ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair);
- } else if over_text && cursor_free {
- ui.ctx().set_cursor_icon(egui::CursorIcon::Text);
- }
- // The pages' press, kept when its release came in the same frame (#2100): it
- // still starts multi-click selection.
- let press_here = ptr.origin.is_some_and(|o| r.contains(o));
- let pressed = ptr.pressed().is_some();
- if pressed && press_here && !over_link {
- let now = ui.input(|inp| inp.time);
- // The same limits egui uses to count clicks on release.
- let (max_delay, max_dist) = ui.ctx().options(|o| (o.input_options.max_double_click_delay, o.input_options.max_click_dist));
- let is_consecutive =
- now - view.last_press_time <= max_delay && view.last_press_pos.is_some_and(|pos| pos.distance(p) <= max_dist);
- view.clicks = if is_consecutive { view.clicks.saturating_add(1) } else { 1 };
- view.last_press_time = now;
- view.last_press_pos = Some(p);
-
- // Multi-click highlights immediately on pointer press instead of release (#1024).
- let clicks = if view.clicks > 2 && tool != QuickTool::Select { 1 } else { view.clicks };
- if clicks >= 2 && over_text {
- let span = text.nearest(vx, vy).and_then(|a| click_unit(&text, clicks, a));
- if let Some((first, last)) = span {
- view.selection = Some(Selection::run(i, first, last));
- }
- }
- }
- if resp.drag_started() && press_here && !over_link {
- // A drag replaces the selection without passing through none, so a
- // re-drag over text whose bar Copy closed would keep the bar hidden.
- view.actions_dismissed = None;
- view.selection_drag = true;
- let origin = ptr.origin.unwrap_or(p);
- let (ox, oy) = xf.screen_to_view(origin);
- if view.clicks < 2 {
- view.selection = if column {
- Some(Selection { page: i, span: Span::Column { rect: [ox, oy, vx, vy] } })
- } else {
- text.nearest(ox, oy).map(|a| Selection::run(i, a, a))
- };
- }
- }
- let clicks = if view.clicks > 2 && tool != QuickTool::Select { 1 } else { view.clicks };
- if resp.dragged()
- && let Some(sel) = view.selection.as_mut().filter(|s| s.page == i)
- {
- match &mut sel.span {
- // After a multi-click the drag extends by its unit (#1685), as in
- // Acrobat and browsers: whole words or lines, always keeping the one
- // clicked, which holds the anchor whichever way the drag went.
- Span::Run { anchor, head } if clicks >= 2 => {
- if let Some(h) = text.nearest(vx, vy)
- && let Some((first, last)) = click_unit(&text, clicks, *anchor)
- {
- let (to_first, to_last) = click_unit(&text, clicks, h).unwrap_or((h, h));
- (*anchor, *head) = if to_first < first { (last, to_first) } else { (first, to_last.max(last)) };
- }
- }
- Span::Run { head, .. } => {
- if let Some(h) = text.nearest(vx, vy) {
- *head = h;
- }
- }
- Span::Column { rect } => {
- rect[2] = vx;
- rect[3] = vy;
- }
- }
- }
- // A rectangle around no text selects nothing.
- if resp.drag_stopped()
- && view.selection.is_some_and(|s| s.page == i && matches!(s.span, Span::Column { .. }) && s.text(&text).is_empty())
- {
- view.selection = None;
- }
- // Quick clicks widen the selection: two a word, three the line, four the page.
- // Release-based fallback for platforms or synthetic events that report double_clicked.
- let release_clicks = if resp.triple_clicked() {
- view.clicks.max(2).saturating_add(1)
- } else if resp.double_clicked() {
- view.clicks.max(2)
- } else {
- 0
- };
- if release_clicks > 0 {
- view.clicks = release_clicks;
- }
- let clicks = if view.clicks > 2 && tool != QuickTool::Select { 1 } else { view.clicks };
- // Only on the frame egui reports the multi-click: `view.clicks` outlives it, and
- // acting on every frame re-selected the word as soon as a selection was cleared
- // (a highlight made by the double-click left its word selected).
- if release_clicks > 0 && clicks >= 2 && over_text {
- if view.selection.is_none() {
- let span = text.nearest(vx, vy).and_then(|a| click_unit(&text, clicks, a));
- if let Some((first, last)) = span {
- view.selection = Some(Selection::run(i, first, last));
- }
- }
- } else if resp.clicked() && view.clicks < 2 && !over_link {
- // ⇧-click extends a selection on this page to the click, keeping its
- // anchor (#527). Otherwise (no shift, no selection on this page, or a
- // column selection, which has no anchor glyph; a selection cannot yet
- // span pages) a click clears the selection.
- let shift = ui.input(|inp| inp.modifiers.shift);
- match (view.selection.as_mut().filter(|s| shift && s.page == i).map(|s| &mut s.span), text.nearest(vx, vy)) {
- (Some(Span::Run { head, .. }), Some(h)) => *head = h,
- _ => view.selection = None,
- }
- }
- }
- }
-
- if tool == QuickTool::Select && !consumed {
- crate::image_pick::page_input(&resp, &xf, i, info, doc, pointer, view);
- }
- crate::image_pick::drop_stale(doc, view);
- crate::image_pick::paint(painter, &xf, i, info, view);
- comments::page_after_text(&resp, &pcx, view);
- if tool == QuickTool::Redact && can_modify {
- crate::redact_ui::after_text(&resp, i, info, view);
- }
- if area_tool {
- crate::redact_ui::paint(painter, i, view, pointer);
- }
- comments::paint_page(ui, painter, &pcx, view);
- if editing_content {
- crate::content_ui::paint_page(painter, &xf, i, info, &added, view, pointer);
- }
- if tool == QuickTool::EditText {
- crate::object_ui::paint(painter, &xf, i, info, &view.objects);
- }
- if tool == QuickTool::EnhanceCamera {
- crate::camera_ui::paint(painter, &xf, i, view);
- }
- if tool == QuickTool::Link {
- crate::link_ui::paint(painter, &xf, i, info, &doc_links, view, pointer);
- }
- if preparing {
- crate::prepare::paint_page(ui, painter, &xf, i, info, &form, view, pointer);
- if let Some(preview) = &table_preview {
- crate::field_table_ui::paint_preview(painter, &xf, i, preview);
- }
- if calc_order {
- let selected = view.prepare.selected.as_ref().map(|(name, _)| name.as_str());
- if let Some(name) =
- crate::calc_order_ui::paint_page(painter, &xf, i, info, &form, &view.calc_order, generation, selected, pointer)
- {
- calc_hover = Some(name);
- }
- }
- } else {
- crate::forms_ui::paint_page(painter, &xf, i, info, &form, view, pointer);
- }
-
- // Form-field highlight (Acrobat's "Highlight existing fields"); required fields get a
- // red border. Radio buttons and round XFA check boxes are round, and so is theirs (as
- // in Acrobat). Only what can be filled is marked: a read-only widget (its field's, or a
- // radio button's own) is left as it is drawn.
- if view.highlight_fields {
- for f in form.iter() {
- let required = f.has(pdfcraft_engine::field_flags::REQUIRED);
- for w in f.widgets.iter().filter(|w| w.page == Some(i) && !w.hidden && !w.read_only) {
- let r = w.rect;
- let sr = xf.user_rect(info, i, [r[0] as f32, r[1] as f32, r[2] as f32, r[3] as f32]);
- let tint = Color32::from_rgba_unmultiplied(0x6E, 0x8E, 0xF5, 48);
- let (width, color) =
- if required { (2.0, Color32::from_rgb(0xE3, 0x22, 0x22)) } else { (1.0, Color32::from_rgb(0x6E, 0x8E, 0xF5)) };
- if w.round {
- let radius = sr.width().min(sr.height()) / 2.0;
- painter.circle_filled(sr.center(), radius, tint);
- painter.circle_stroke(sr.center(), radius - width / 2.0, Stroke::new(width, color));
- } else {
- painter.rect_filled(sr, CornerRadius::same(1), tint);
- painter.rect_stroke(sr, CornerRadius::same(1), Stroke::new(width, color), egui::StrokeKind::Inside);
- }
- }
- }
- }
- // Fill & Sign keeps its placement cursor clear of link/comment hover feedback. Tips
- // draw above the palette, so none shows while it is open, even beside it.
- if !matches!(tool, QuickTool::Fill(_))
- && unobstructed
- && let Some(p) = pointer
- {
- for l in info.links.iter().filter(|l| l.page == i) {
- let sr = xf.user_rect(info, i, l.rect);
- if sr.contains(p) {
- ui.ctx().set_cursor_icon(egui::CursorIcon::PointingHand);
- let label = match &l.target {
- LinkTarget::Page(n, _) => {
- crate::i18n::fmt(tl!("Go to page {p}"), &[("p", info.pages.get(*n).map(|p| p.label.as_str()).unwrap_or("?"))])
- }
- LinkTarget::Uri(u) => u.clone(),
- LinkTarget::SetLayers { .. } => tl!("Set layer visibility").to_string(),
- LinkTarget::RemoteGoTo { file, .. } => file.clone(),
- LinkTarget::Other(s) => crate::i18n::fmt(tl!("{s} action"), &[("s", s)]),
- };
- hover_text = Some((p, label));
- if resp.clicked() && tool == QuickTool::Select && !consumed {
- clicked_link = Some(l.target.clone());
- }
- }
- }
- // Annotation hover shows the comment, as Acrobat's popups do; not while drawing
- // freehand, where it would cover the next stroke (#429).
- let freehand = matches!(tool, QuickTool::Comment(comments::CommentTool::Ink | comments::CommentTool::Eraser));
- let gesturing = view.comments.gesture.is_some() || freehand;
- // Inspection sorts annotations spatially, but the renderer paints in /Annots
- // order. Keep the shared list intact and choose the last eligible raw index.
- if hover_text.is_none()
- && !gesturing
- && let Some((_, text)) = info
- .annotations
- .iter()
- .filter(|a| a.page == i)
- .filter(|a| {
- !(prefs.hide_empty_highlight_hover && a.subtype == "Highlight" && a.contents.as_deref().is_none_or(str::is_empty))
- })
- .filter(|a| pcx.screen_rects(a).any(|r| r.contains(p)))
- .filter_map(|a| annotation_hover_text(a).map(|text| (a.index, text)))
- .max_by_key(|(index, _)| *index)
- {
- hover_text = Some((p, text));
- }
- }
- for (mp, mr, mc) in &view.compare_marks {
- if *mp == i {
- let sr = xf.user_rect(info, i, *mr).expand(1.5);
- painter.rect_filled(sr, CornerRadius::same(2), mc.gamma_multiply(0.28));
- }
- }
- if let Some((fp, fr, t0)) = view.flash
- && fp == i
- {
- let now = ui.input(|inp| inp.time);
- let t0 = if t0 == 0.0 { now } else { t0 };
- view.flash = Some((fp, fr, t0));
- let age = (now - t0) as f32;
- if age < 1.6 {
- let a = ((1.6 - age) / 1.6 * 255.0) as u8;
- let sr = xf.user_rect(info, i, fr).expand(4.0);
- painter.rect_stroke(
- sr,
- CornerRadius::same(3),
- Stroke::new(2.5, Color32::from_rgba_unmultiplied(0x1B, 0x63, 0xE0, a)),
- egui::StrokeKind::Outside,
- );
- ui.ctx().request_repaint();
- } else {
- view.flash = None;
- }
- }
- // Validation is viewer chrome over the signer's original artwork, which
- // may still say "Signature Not Verified". These badges never enter document
- // streams, image/text exports, vector printing or Print as Image.
- for badge in signature_badges(&doc.signatures, i) {
- let [x0, y0, x1, y1] = badge.rect;
- let sr = xf.user_rect(info, i, [x0 as f32, y0 as f32, x1 as f32, y1 as f32]);
- let (icon, color) = crate::sign_ui::signature_status_style(badge.status);
- painter.rect_stroke(sr, CornerRadius::same(2), Stroke::new(1.5, color), egui::StrokeKind::Outside);
- // A widget too small for the mark keeps its outline: the verdict still shows.
- if sr.width() < 4.0 || sr.height() < 4.0 {
- continue;
- }
- // Big enough to read at a glance, small enough to leave the signer's own
- // text visible around it.
- let side = (sr.width().min(sr.height()) * 0.8).clamp(24.0, 192.0);
- let mark = Rect::from_center_size(sr.center(), vec2(side, side));
- icons::paint(ui, mark, icon, side * 0.64, color);
- if let Some(p) = pointer.filter(|p| mark.expand(2.0).contains(*p)) {
- badge_hover = Some((p, badge.summary.to_string()));
- }
- }
- // Overlapping widgets paint in order, so the topmost badge owns the hover; an
- // earlier link or annotation hover still wins over any badge.
- if hover_text.is_none() {
- hover_text = badge_hover.take();
- }
- }
- 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);
- }
- // ScrollArea ignores the wheel while any widget is dragged, so a text-selection drag
- // scrolls the page itself (#721). After the page loop, so it keeps scrolling once the
- // pointer leaves the selection's page for the gap or the next page; over the whole
- // document area, like #759. Combine direct and smoothed motion in one request so mixed
- // Point and Line events retain their full contribution.
- if selection_wheel {
- let smooth =
- if view.precise_scroll_until == 0.0 { ui.input_mut(|input| std::mem::take(&mut input.smooth_scroll_delta)) } else { Vec2::ZERO };
- let delta = precise_scroll + boost_extra + smooth;
- if delta != Vec2::ZERO && delta.is_finite() {
- ui.scroll_with_delta_animation(delta, egui::style::ScrollAnimation::none());
- }
- }
- // Held at the top or bottom edge, or dragged past it, a text selection scrolls the view
- // so it can reach text off screen (#1670); the selection follows the pointer on its page.
- if view.selection_drag
- && navigation_enabled
- && unobstructed
- && !single_paging
- && let Some(p) = ptr.pos
- {
- let dy = crate::autoscroll::edge_delta(p.y, avail, ui.input(|i| i.stable_dt));
- if dy != 0.0 {
- view.end_find_following();
- ui.scroll_with_delta_animation(vec2(0.0, dy), egui::style::ScrollAnimation::none());
- // Keep scrolling while the pointer rests there and sends no events.
- ui.ctx().request_repaint();
- }
- }
- // The page navigated to stays current while no page shows more of itself, so the next
- // page step starts from it rather than from a page further down the screen (#188).
- // It also stays current while it is wholly on screen: a short page (a cheque) gone to
- // from the Pages panel shows less of itself than the tall page below it, and must not
- // hand the highlight to that page.
- if current_overlap >= best_overlap - TIE || current_overlap >= current_height - TIE {
- current = view.current;
- }
- if let Some(p) = pressed_page {
- current = p;
- }
- if view.continuous {
- view.current = current;
- }
- resp.context_menu(|ui| {
- // Preparing a form: the selected field's menu.
- if preparing && let Some((name, wi)) = view.prepare.selected.clone() {
- // Several fields: Align, Center, Distribute, Set Fields to Same Size.
- if !view.prepare.also.is_empty() {
- use crate::prepare::Arrange as A;
- let others = view.prepare.also.clone();
- let anchor = (name.clone(), wi);
- let mut pick = |ui: &mut egui::Ui, op: A, label: &str| {
- if ui.add_enabled(can_modify, egui::Button::new(tl!(label))).clicked() {
- view.pending_edit = crate::prepare::arrange(&form, &anchor, &others, op);
- ui.close();
- }
- };
- ui.menu_button(tl!("Align"), |ui| {
- pick(ui, A::AlignLeft, "Left");
- pick(ui, A::AlignRight, "Right");
- pick(ui, A::AlignTop, "Top");
- pick(ui, A::AlignBottom, "Bottom");
- pick(ui, A::AlignCenterV, "Center vertically");
- pick(ui, A::AlignCenterH, "Center horizontally");
- });
- ui.menu_button(tl!("Distribute"), |ui| {
- pick(ui, A::DistributeH, "Horizontally");
- pick(ui, A::DistributeV, "Vertically");
- });
- ui.menu_button(tl!("Set Fields to Same Size"), |ui| {
- pick(ui, A::SameHeight, "Height");
- pick(ui, A::SameWidth, "Width");
- pick(ui, A::SameSize, "Both");
- });
- ui.separator();
- }
- if ui.button(tl!("Properties…")).clicked() {
- field_menu = Some(FieldMenu::Properties);
- ui.close();
- }
- if ui.add_enabled(can_modify, egui::Button::new(tl!("Duplicate…"))).clicked() {
- field_menu = Some(FieldMenu::Duplicate(name.clone()));
- ui.close();
- }
- ui.separator();
- let delete = if view.prepare.also.is_empty() { "Delete" } else { "Delete selected fields" };
- if ui.add_enabled(can_modify, egui::Button::new(tl!(delete))).clicked() {
- view.pending_edit = crate::prepare::delete_selected(view);
- ui.close();
- }
- return;
- }
- if let Some((page, index)) = view.links.context {
- if ui.button(tl!("Properties…")).clicked() {
- view.links.open_existing = Some((page, index));
- ui.close();
- }
- if ui.add_enabled(can_modify, egui::Button::new(tl!("Delete"))).clicked() {
- view.pending_edit = Some(Edit::DeleteLink { page, index });
- view.links.selected = None;
- view.links.context = None;
- ui.close();
- }
- ui.separator();
- if ui.add_enabled(can_modify, egui::Button::new(tl!("Remove all links"))).clicked() {
- view.pending_edit = Some(Edit::RemoveLinks { pages: None });
- view.links.selected = None;
- view.links.context = None;
- ui.close();
- }
- return;
- }
- let is_image_menu = tool == QuickTool::EditText
- && (ui.ctx().data_mut(|d| d.get_persisted::<bool>(crate::edit_text_ui::image_menu_id())).unwrap_or(false)
- || view.image_selection.as_ref().is_some_and(|sel| {
- let pointer_pos = ptr.pos;
- let Some(p) = pointer_pos else { return false };
- let Some((_, xf)) = view.screen_xforms.iter().find(|(page_idx, _)| *page_idx == sel.page) else { return false };
- let images = doc.page_images(sel.page);
- let Some(img) = images.get(sel.index) else { return false };
- let obb = ImageObb::from_image(img, xf, info, sel.page);
- let b = image_screen_rect(img, xf, info, sel.page);
- (b.is_positive() && b.contains(p)) || crate::edit_text_ui::quad_contains(obb.corners(), p)
- }));
- if is_image_menu && let Some(sel) = view.image_selection.clone() {
- let images = doc.page_images(sel.page);
- let at = view.comments.context_at.map(|(_, at)| at);
- crate::edit_text_ui::image_context_menu(ui, view, &images, sel.page, sel.index, can_paste_image, &mut image_action, at);
- return;
- }
- if view.comments.selected.is_some() {
- canvas_action = comments::context_menu(ui, view, info, prefs, allowed, 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 {
- // The page's content is parsed once per right-click, not on every frame the menu is open.
- let key = egui::Id::unique("copy-image-under-menu");
- let cached = ui.data(|d| d.get_temp::<(usize, [f64; 2], Option<usize>)>(key)).filter(|c| c.0 == page && c.1 == at);
- let hit = match cached {
- Some(c) => c.2,
- None => {
- let hit = doc.page_image_at(page, at);
- ui.data_mut(|d| d.insert_temp(key, (page, at, hit)));
- hit
- }
- };
- if let Some(image) = hit {
- if ui.button(tl!("Copy Image")).clicked() {
- copy_image = Some(comments::CanvasAction::CopyImage(page, image));
- ui.close();
- }
- if ui.button(tl!("Copy Image in Original Format")).clicked() {
- copy_image = Some(comments::CanvasAction::CopyImageFile(page, image));
- ui.close();
- }
- ui.separator();
- }
- }
- 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]));
- let can_copy_items = can_copy && (view.image_selection.is_some() || view.selected_text().is_some() || 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,
- has_annotations: !info.annotations.is_empty(),
- };
- default_page_context_menu(ui, page, at, perms, &mut page_action);
- });
- if !resp.context_menu_opened() {
- ui.ctx().data_mut(|d| d.insert_persisted(crate::edit_text_ui::image_menu_id(), false));
- }
- (wanted, visible_now)
- });
- view.single_edges = visible_pages.first().copied().filter(|_| !view.continuous).map(|page| {
- // At the top once the page's top edge shows where going to a page puts it (a gap
- // below the window's top). Within a point, as for wheel paging, so layout rounding
- // can't hide an edge.
- let max_y = (out.content_size.y - out.inner_rect.height()).max(0.0);
- (page, out.state.clamped_offset().y <= MARGIN - view.page_gap() + 1.0, out.state.clamped_offset().y >= max_y - 1.0)
- });
-
- view.viewport_screen = out.inner_rect;
- view.auto_scroll.paint(ui, avail);
- if unobstructed && matches!(tool, QuickTool::Select | QuickTool::ColumnSelect) {
- copy_selected |= selection_actions(ui, avail, view, info, prefs, allowed && !comments_hidden, can_copy);
- }
-
- // Collect all main-page demand, including cached surfaces, for byte admission later.
- // Pan-settle debounce for tiled pages: each tile costs a full page interpret, so holding
- // fresh tiles back while the scroll offset is still moving keeps a drag on the stretched
- // backdrop/older tiles instead of queueing a storm of interprets (one per frame) that
- // the workers cannot cancel mid-operator. Fresh tiles go out once the pan settles;
- // pages with nothing on screen yet still queue.
- let scroll_offset = out.state.clamped_offset();
- // The document ScrollArea's own scroll surfaces move the offset without the wheel deltas
- // above: its two scroll-bar tracks/handles and, for touch or the Hand tool, its drag
- // background. The output gives us the area id, and egui's pinned ScrollArea registers those
- // widgets under `id.with(0)` (horizontal), `id.with(1)` (vertical) and `id.with("area")`.
- // Ask for their exact responses instead of treating any held drag as scrolling: a text
- // selection, a panel splitter or another widget's drag must not excuse the programmatic jump
- // a search flash makes, while a track click (which moves the offset with no pointer motion)
- // must still count as the reader scrolling.
- let scroll_surface = |id: egui::Id| ui.ctx().read_response(id).is_some_and(|r| r.is_pointer_button_down_on() || r.dragged() || r.clicked());
- let pointer_scrolling = scroll_surface(out.id.with(0usize)) || scroll_surface(out.id.with(1usize)) || scroll_surface(out.id.with("area"));
- if pointer_scrolling && (scroll_offset - view.last_scroll).length() > 2.0 {
- view.end_find_following();
- }
- let now_settle = ui.input(|i| i.time);
- if (scroll_offset - view.last_scroll).length() > 2.0 {
- view.pan_hold_until = now_settle + 0.25;
- ui.ctx().request_repaint_after(std::time::Duration::from_millis(280));
- }
- if glide != Vec2::ZERO {
- view.fling.moved((scroll_offset - view.last_scroll).length() > 0.01);
- }
- view.last_scroll = scroll_offset;
- let pan_held = now_settle < view.pan_hold_until;
- let (mut wanted, visible_now) = out.inner;
- // Single-page and two-page views draw only the current row, so the next one was first asked
- // for on the turn and showed blank paper until it rendered. Prefetch the rows either side,
- // as continuous scrolling does for the pages just off screen.
- if !view.continuous
- && let (Some(&first), Some(&last)) = (visible_pages.first(), visible_pages.last())
- {
- let n = if view.layout == PageLayout::Single { 1 } else { 2 };
- let max_side = ui.ctx().input(|inp| inp.max_texture_side) as f32;
- for i in (last.saturating_add(1)..=last.saturating_add(n)).chain(first.saturating_sub(n)..first) {
- let Some(p) = info.pages.get(i).filter(|_| !view.errors.contains_key(&i)) else { continue };
- // As drawn: the whole page at this scale, or the backdrop of a tiled page.
- let side = p.width.max(p.height).max(1.0);
- wanted.push(if side * scale > TILE_THRESHOLD.min(max_side) {
- let bs = BASE_SIDE.min(max_side) / side;
- (i, bs, scale_tag(bs), None)
- } else {
- (i, scale, tag, None)
- });
- }
- }
- let cur = view.current;
- wanted.sort_by_key(|w| (!visible_now.contains(&w.0), w.0.abs_diff(cur), w.3.is_some()));
- // Tiles of far-away pages are useless: free them. Tiles of an earlier zoom stay for a page
- // that is on screen, whether or not the page is tiled at this zoom (#2196): a zoom out below
- // the tiling threshold used to drop the tiles of the zoom just left, so coming back to it
- // was a cold miss and the page re-blurred through the backdrop while every tile was
- // interpreted again. `OLD_TILES` still bounds how many older tiles are kept, nearest scale
- // first, and admission keeps them inside `TILE_BYTES`.
- let missing: HashSet<usize> = wanted.iter().filter(|w| w.3.is_some()).map(|w| w.0).collect();
- let on_screen: HashSet<usize> = visible_now.iter().copied().collect();
- view.tiles.retain(|(p, t, _, _), _| p.abs_diff(cur) <= 2 && (*t == tag || missing.contains(p) || on_screen.contains(p)));
- let mut older: Vec<(f32, (usize, u64, u32, u32))> =
- view.tiles.keys().filter(|k| k.1 != tag).map(|k| ((tag_scale(k.1) / scale).ln().abs(), *k)).collect();
- // Tiles of earlier zooms are kept nearest scale first, and bounded by count *and* bytes: a
- // large scan renders a tile up to 4096² (about 67 MiB), so a count alone let a few tiles of
- // a few zooms run far past the tile allowance. #2196 keeps a zoom already visited, which
- // makes that reachable in ordinary zooming, so the byte bound has to be here too.
- older.sort_by(|a, b| a.0.total_cmp(&b.0));
- let mut kept = 0usize;
- let mut kept_bytes = 0usize;
- let mut drop: Vec<(usize, u64, u32, u32)> = Vec::new();
- for (_dist, key) in older {
- let bytes = view.tiles.get(&key).map_or(0, texture_bytes);
- if kept >= OLD_TILES || kept_bytes.saturating_add(bytes) > TILE_BYTES {
- drop.push(key);
- } else {
- kept = kept.saturating_add(1);
- kept_bytes = kept_bytes.saturating_add(bytes);
- }
- }
- for key in drop {
- view.tiles.remove(&key);
- }
- let mut queue: Vec<RenderRequest> = wanted
- .iter()
- .map(|&(page, wanted_scale, wanted_tag, tile)| RenderRequest {
- page,
- kind: RequestKind::Pixels,
- tile,
- scale: wanted_scale,
- tag: wanted_tag,
- // The low-res backdrop under tiles is a preview: tiny images are skipped for it.
- // It is the whole-page request whose scale is not the current one; sharp tiles
- // and whole-page finals always draw everything.
- preview: tile.is_none() && (wanted_scale != scale || wanted_tag != tag),
- })
- .collect();
- // While the zoom or pan is settling, hold back sharp re-renders of pages that already
- // show something (a stale whole-page raster or older tiles, drawn stretched): each new
- // scale would cancel the running full-page interpret and restart it from scratch, and
- // each pan frame would queue a storm of full-page tile interprets.
- // Pages with nothing on screen yet still queue, so panning to a fresh page draws it.
- if sharp_held || pan_held {
- let main_tag = tag;
- queue.retain(|req| {
- // Fast pages render straight through: the hold only protects heavy pages
- // whose full-page interpret costs seconds.
- if !view.slow_pages.contains(&req.page) {
- return true;
- }
- if req.tile.is_some() {
- let has_current_tile = view.tiles.keys().any(|(p, t, _, _)| *p == req.page && *t == req.tag);
- if has_current_tile {
- return false;
- }
- let has_any_surface = view.pages.contains_key(&req.page) || view.tiles.keys().any(|(p, _, _, _)| *p == req.page);
- !has_any_surface
- } else if req.tag != main_tag {
- // The low-res backdrop under tiles is zoom-independent: let it through,
- // it is the stretched surface the hold relies on.
- true
- } else {
- // The stale raster stays stretched until the zoom or pan settles; a page with
- // nothing on screen yet still renders.
- !view.pages.contains_key(&req.page)
- }
- });
- }
- // Text layers: visible pages for selection, every page while a search is active. (Select All
- // of the document needs no more: shown pages highlight as their text comes, and Copy reads
- // the rest, as text far away is let go to bound memory.)
- let need_text = |p: &usize| !view.texts.contains_key(p) && !view.text_failed.contains(p);
- let mut text_pages: Vec<usize> = if hand { Vec::new() } else { visible_now.iter().copied().filter(need_text).collect() };
- if view.find.as_ref().is_some_and(|f| !f.case_query.trim().is_empty()) {
- let n = info.pages.len();
- let rest: Vec<usize> = (0..n).map(|k| (cur + k) % n).filter(need_text).filter(|p| !text_pages.contains(p)).collect();
- text_pages.extend(rest);
- }
- queue.extend(text_pages.into_iter().map(|page| RenderRequest {
- page,
- kind: RequestKind::Text,
- tile: None,
- scale: 1.0,
- tag: TEXT_TAG,
- preview: false,
- }));
- view.frame_queue = queue;
- view.frame_visible = visible_now.iter().copied().collect();
-
- if let Some((pos, text)) = hover_text {
- // Click-through, as a tooltip is: the pages lose the pointer under anything that isn't.
- let tip = egui::Area::new(egui::Id::unique("canvas-hover")).order(egui::Order::Tooltip).interactable(false);
- tip.fixed_pos(pos + vec2(14.0, 16.0)).show(ui.ctx(), |ui| {
- egui::Frame::popup(ui.style()).show(ui, |ui| {
- ui.set_max_width(320.0);
- ui.label(text);
- });
- });
- }
- find_bar(view, info.pages.len(), avail, ui, &t);
- page_size_hint(view, info, units, avail, unobstructed, ui, &t);
- if tool == QuickTool::EnhanceCamera {
- crate::camera_ui::bar(ui.ctx(), view, avail, &t, can_modify);
- }
- if let Some(e) = comments::composer(ui.ctx(), view, info, prefs) {
- view.pending_edit = Some(e);
- }
- if let Some(e) = crate::edit_text_ui::overlay(ui.ctx(), view, info) {
- view.pending_edit = Some(e);
- }
- let text_box = crate::forms_ui::text_box(doc, view, &form);
- if let Some(e) = crate::forms_ui::overlay(ui.ctx(), view, info, &form, text_box.as_ref(), today) {
- view.pending_edit = Some(e);
- }
- if let Some(e) = crate::fill_sign::type_box(ui.ctx(), view, info, &author) {
- view.pending_edit = Some(e);
- }
- let (typed, text_done) = crate::content_ui::editor(ui.ctx(), view, info, &added);
- if typed.is_some() {
- view.pending_edit = typed;
- }
- if let Some(why) = view.objects.notice.take() {
- refused = Some(why);
- }
- let form_notice = view.forms.notice.take();
- // One crop, then back to selecting (as Acrobat does).
- let cropped = view.pending_edit.as_ref().is_some_and(|e| matches!(e, pdfcraft_engine::Edit::SetPageBox { .. }));
- let mut tool = app.quick_tool;
- comments::keys(ui.ctx(), view, &mut tool, allowed);
- if preparing {
- crate::prepare::keys(ui.ctx(), view);
- }
- if editing_content {
- crate::content_ui::keys(ui.ctx(), view);
- }
- if tool == QuickTool::Link {
- crate::link_ui::keys(ui.ctx(), view);
- } else {
- view.links.selected = None;
- }
- if tool != QuickTool::EditText {
- view.image_selection = None;
- }
- if stamp_placed {
- tool = QuickTool::Select;
- }
- // Text: each click on the page starts a box (#74); Done in the editor goes back to selecting.
- if text_done && tool == QuickTool::AddText {
- tool = QuickTool::Select;
- }
- // One field, then back to selecting (Acrobat's default without "Keep tools pinned").
- if field_placed {
- tool = QuickTool::Select;
- }
- if matches!(field_menu, Some(FieldMenu::Properties)) {
- field_props = true;
- }
- let field_props = field_props.then(|| view.prepare.selected.clone()).flatten();
- match canvas_action {
- Some(comments::CanvasAction::Edit(e)) => view.pending_edit = Some(*e),
- // `choose_right_panel` would borrow all of `app` while `view` is held; same effect.
- Some(comments::CanvasAction::OpenComments) => {
- app.right = Some(RightPanel::Comments);
- app.comments_panel_closed = false;
- }
- Some(comments::CanvasAction::Properties(p, i)) => open_props = Some((p, i)),
- Some(comments::CanvasAction::CopyImage(p, i)) => image_action = Some(crate::edit_text_ui::ImageAction::Copy(p, i)),
- Some(comments::CanvasAction::CopyImageFile(p, i)) => image_action = Some(crate::edit_text_ui::ImageAction::CopyFile(p, i)),
- None => {}
- }
- // Full screen: the click turns the page unless it did something else first. It waits out the
- // double-click time: turning on the first click's release sent a double-click's second click,
- // meant to select a word, to the next page (review on #2070). A selection cancels it, and so
- // do a link followed meanwhile and leaving full screen; a double-click elsewhere still turns
- // once.
- let now = ui.input(|i| i.time);
- if present_click && clicked_link.is_none() && view.selection.is_none() && view.clicks < 2 {
- let delay = ui.ctx().options(|o| o.input_options.max_double_click_delay);
- view.present_turn = Some((now + delay, !present_back));
- }
- if let Some((due, forward)) = view.present_turn {
- if clicked_link.is_some() || view.selection.is_some() || view.presentation.is_none() {
- view.present_turn = None;
- } else if now >= due {
- view.present_turn = None;
- view.step_page(forward);
- } else {
- ui.ctx().request_repaint_after(std::time::Duration::from_secs_f64((due - now).max(0.0)));
- }
- }
- match clicked_link {
- Some(LinkTarget::Page(p, dest)) => view.go_to_dest(p, dest, info),
- Some(LinkTarget::Uri(u)) => app.request_document_url(&u, crate::LinkOrigin::Link),
- Some(LinkTarget::SetLayers { changes, preserve_rb }) => set_layers(app, index, &changes, preserve_rb),
- Some(LinkTarget::RemoteGoTo { file, destination, .. }) => remote_open = Some((view.id, file, destination)),
- Some(LinkTarget::Other(s)) => app.notify_fmt("This PDF uses the unsupported {s} action.", &[("s", &s)]),
- None => {}
- }
- if tool == QuickTool::Crop && cropped {
- tool = QuickTool::Select;
- }
- if let Some(done) = app.views[index].marquee_done.take() {
- app.finish_marquee(index, done);
- }
- // A signature rectangle was drawn, or an empty signature field clicked.
- let drawn = app.views[index].sign.drawn.take();
- if let (Some((page, rect)), QuickTool::SignArea { certify }) = (drawn, tool) {
- tool = QuickTool::Select;
- app.quick_tool = tool;
- app.start_signing(page, Some(rect), None, certify.then_some(2));
- }
- if let Some(field) = app.views[index].sign.field.take() {
- let signed = app.session.get(app.views[index].id).is_some_and(|d| d.signatures.iter().any(|s| s.field == field && s.signed));
- if signed {
- app.right = Some(RightPanel::Signatures);
- if !app.sig_expanded.contains(&field) {
- app.sig_expanded.push(field);
- }
- } else {
- let page = app.views[index].current;
- app.start_signing(page, None, Some(field), None);
- }
- }
- app.quick_tool = tool;
- if let Some((page, at)) = app.views[index].comments.attach_at.take() {
- app.attach_file_comment(page, at);
- }
- if let Some((p, i)) = open_props {
- app.open_comment_props(p, i);
- }
- if let Some((p, i)) = app.views[index].comments.default_request.take() {
- app.make_comment_default(p, i);
- }
- if let Some((p, i, open)) = app.views[index].comments.attachment_request.take() {
- let doc = app.views[index].id;
- app.comment_attachment_action(doc, p, i, open);
- }
- if let Some((name, w)) = field_props {
- app.open_field_props(&name, w);
- }
- if let Some(FieldMenu::Duplicate(name)) = field_menu {
- let pages = app.session.get(app.views[index].id).map_or(1, |d| d.info.pages.len());
- app.duplicate_draft = Some(crate::DuplicateDraft { name, all: true, from: 1, to: pages });
- app.dialog = Some(crate::Dialog::DuplicateField);
- }
- if let Some((page, rect)) = app.views[index].links.open_new.take() {
- app.open_link_props(page, Some(rect), None);
- }
- if let Some((page, i)) = app.views[index].links.open_existing.take() {
- app.open_link_props(page, None, Some(i));
- }
- if let Some((page, quads)) = app.views[index].pending_redaction.take() {
- let author = app.comment_prefs.author.clone();
- app.views[index].pending_edit = Some(if app.quick_tool == QuickTool::Comment(comments::CommentTool::Highlight) {
- // An area highlight: a highlight over the box.
- let style = app.comment_prefs.style(comments::CommentTool::Highlight);
- pdfcraft_engine::Edit::AddAnnotation(pdfcraft_engine::NewAnnotation {
- page,
- shape: pdfcraft_engine::Shape::TextMarkup { kind: pdfcraft_engine::Markup::Highlight, quads },
- style,
- contents: String::new(),
- author,
- })
- } else {
- app.redact_prefs.mark(page, quads, &author)
- });
- }
- match image_action {
- Some(crate::edit_text_ui::ImageAction::Replace(page, index)) => app.replace_page_image_dialog(page, index),
- Some(crate::edit_text_ui::ImageAction::Save(page, index)) => app.save_page_image(page, index),
- Some(crate::edit_text_ui::ImageAction::Copy(page, index)) => {
- app.copy_page_image(page, index);
- }
- Some(crate::edit_text_ui::ImageAction::CopyFile(page, index)) => app.copy_page_image_file(page, index),
- Some(crate::edit_text_ui::ImageAction::Cut(page, image)) => {
- app.views[index].image_selection = None;
- app.cut_page_image(page, image);
- }
- Some(crate::edit_text_ui::ImageAction::Paste(page, at)) => {
- if let Some(pt) = at {
- app.paste_image_at(page, pt);
- } else {
- app.paste_image(page, None);
- }
- }
- Some(crate::edit_text_ui::ImageAction::DrawFreehand) => {
- app.quick_tool = crate::QuickTool::Comment(crate::comments::CommentTool::Ink);
- }
- Some(crate::edit_text_ui::ImageAction::Redact(page, index)) => app.redact_page_image(page, index),
- Some(crate::edit_text_ui::ImageAction::Link(page, index)) => app.link_page_image(page, index),
- Some(crate::edit_text_ui::ImageAction::Recognize(page)) => app.recognize_text_on_page(page),
- Some(crate::edit_text_ui::ImageAction::AddComment(page, i)) => {
- if let Some(d) = app.session.get(app.views[index].id) {
- let images = d.page_images(page);
- 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 {
- page,
- at: center,
- kind: crate::comments::ComposerKind::Note,
- text: String::new(),
- focus: true,
- });
- }
- }
- }
- Some(crate::edit_text_ui::ImageAction::Crop) => {
- let doc_id = app.views[index].id;
- if let Some(s) = app.views[index].image_selection.as_mut()
- && let Some(d) = app.session.get(doc_id)
- {
- let images = d.page_images(s.page);
- if let Some(im) = images.get(s.index) {
- s.crop = Some(crate::edit_text_ui::CropMode::new(im.visible_rect.unwrap_or(im.rect)));
- s.crop_mode = true;
- s.crop_rect = None;
- }
- }
- }
- None => {}
- }
- match page_action {
- Some(PageMenuAction::Copy) => {
- if let Some(sel) = app.views[index].image_selection.clone() {
- app.copy_page_image(sel.page, sel.index);
- } else if app.views[index].selected_text().is_some() {
- app.execute("edit.copy");
- } else if let Some((page, at)) = app.views[index].comments.context_at
- && let Some(doc) = app.session.get(app.views[index].id)
- && let Some(image) = doc.page_image_at(page, at)
- {
- app.copy_page_image(page, image);
- }
- }
- Some(PageMenuAction::Paste(page, at)) => {
- app.paste_image_at(page, at);
- }
- Some(PageMenuAction::RotateCCW(page)) => {
- let _ = page;
- app.views[index].rotate_view(false);
- }
- Some(PageMenuAction::RotateCW(page)) => {
- let _ = page;
- app.views[index].rotate_view(true);
- }
- Some(PageMenuAction::Print) => {
- app.open_print();
- }
- Some(PageMenuAction::SelectTool) => {
- app.quick_tool = QuickTool::Select;
- }
- Some(PageMenuAction::HandTool) => {
- app.quick_tool = QuickTool::Hand;
- }
- Some(PageMenuAction::MarqueeZoom) => {
- app.quick_tool = QuickTool::MarqueeZoom;
- }
- Some(PageMenuAction::AddComment(page, at)) => {
- app.views[index].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.selected = None;
- app.views[index].pending_edit = Some(pdfcraft_engine::Edit::Flatten { comments: true, fields: false });
- }
- Some(PageMenuAction::AddBookmark(_page)) => {
- app.bookmark_action(crate::panels::BmAction::New);
- }
- Some(PageMenuAction::TakeSnapshot) => {
- app.quick_tool = QuickTool::Snapshot;
- }
- Some(PageMenuAction::EditPdf) => {
- app.quick_tool = QuickTool::EditText;
- }
- Some(PageMenuAction::AddText) => {
- app.quick_tool = QuickTool::AddText;
- }
- Some(PageMenuAction::AddImage) => {
- app.add_image_dialog();
- }
- Some(PageMenuAction::DeletePage(page)) => {
- app.views[index].pending_edit = Some(pdfcraft_engine::Edit::DeletePages { pages: vec![page] });
- }
- Some(PageMenuAction::ExportPdf) => {
- app.select_tool("export");
- }
- Some(PageMenuAction::Find) => {
- app.views[index].open_find();
- }
- Some(PageMenuAction::DocProperties) => {
- app.dialog = Some(crate::Dialog::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 open_boxes {
- app.boxes_draft.range = crate::pageboxes::Range::Current;
- app.boxes_draft.seeded = None;
- app.dialog = Some(crate::Dialog::PageBoxes);
- }
- if let Some((page, rect)) = open_table {
- app.field_table_draft = Some(crate::field_table_ui::FieldTableDraft::new(app.views[index].id, page, rect, &form, generation));
- app.dialog = Some(crate::Dialog::FieldTable);
- // The window lasts while the form is prepared. Drawn with the tool picked but its panel
- // closed, the tool goes back to Select above, so the panel opens to keep it prepared.
- app.left = crate::LeftPanel::Tool("form");
- app.reveal_tools();
- }
- if let Some(n) = form_notice {
- match n {
- crate::forms_ui::FormNotice::Security => app.notify_tr("The document's security settings don't allow filling in form fields"),
- crate::forms_ui::FormNotice::ReadOnly(name) => app.notify_fmt("{name} is read-only", &[("name", &name)]),
- crate::forms_ui::FormNotice::NoAction(name) => app.notify_fmt("{name} has no action", &[("name", &name)]),
- }
- }
- if let Some((name, action)) = app.views[index].forms.button.take() {
- run_button(app, index, &name, action);
- }
- if copy_selected {
- app.execute("edit.copy");
- }
- // Read mode hides the tools (#2646), and full screen is the page and nothing else (#1459);
- // the quick tools come back with the window.
- if app.mode != crate::Mode::Read && !app.full_screen {
- quick_bar(app, avail, ui);
- }
- if let Some((source, file, destination)) = remote_open {
- app.open_remote_link(source, file, destination);
- }
-}
-
-/// The prepare-mode field menu's choices.
-enum FieldMenu {
- Properties,
- Duplicate(String),
-}
-
-pub use crate::image_engine::{apply_crop, apply_resize, apply_resize_proportional, reset_crop, HandleId, MIN_RECT_SIZE};
-#[cfg(test)]
-mod tests;
+//! The document area: page layout, zoom, render scheduling, overlays (links, annotation hovers,
+//! form-field highlights), and the organize-pages grid.
+//!
+//! 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).
+
+use std::collections::{BTreeSet, HashMap, HashSet};
+use std::ops::Range;
+use std::sync::Arc;
+
+use egui::{Align2, Color32, CornerRadius, Pos2, Rect, Sense, Stroke, TextureHandle, TextureOptions, Vec2, pos2, vec2};
+use pdfcraft_engine::{DocId, Edit};
+use pdfcraft_render::{DestView, DocInfo, LayerOp, LinkTarget, PRINT_TAG, PageText, RenderPool, RenderRequest, RequestKind, Tile, device_pixels};
+
+use crate::page_pointer::PagePointer;
+use crate::theme::{self, Tokens};
+use crate::{PdfCraftApp, QuickTool, RightPanel, comments, icons, widgets};
+
+mod area;
+pub(super) mod autoscroll;
+mod bars;
+mod cache;
+pub(super) mod crop;
+mod find;
+pub(super) mod fling;
+pub(super) mod image_pick;
+mod navigation;
+mod organize;
+pub(super) mod page_pointer;
+pub mod scroll_speed;
+mod selection;
+pub(super) mod signature_drag;
+pub(super) mod wheel_boost;
+pub(super) mod wheel_pager;
+mod xform;
+mod zoom;
+pub(super) mod zoom_snap;
+
+pub(crate) use area::signature_badges;
+use area::{
+ SUPPRESS_SECS, SUPPRESS_TAIL_SECS, annotation_hover_text, drawing_edge_pointer, glide_interrupted, page_scroll, presentation_click, run_button,
+ set_layers, zoom_anchor,
+};
+#[cfg(test)]
+use bars::in_size_hint_zone;
+use bars::{Notice, notices, page_size_hint, quick_bar};
+pub use cache::RasterMemory;
+pub(crate) use cache::{BASE_SIDE, TILE_THRESHOLD, texture_image, thumbnail_rows};
+#[cfg(test)]
+use cache::{
+ GRAYSCALE_TAG, GRID_TAG, MAX_CACHED_TEXT_PAGES, MAX_THUMB_DEMAND, PAGE_BYTES, THUMB_BYTES, THUMB_H, THUMB_TAG, THUMB_W, TILE, grayscale,
+ rgba_bytes,
+};
+use cache::{OLD_TILES, PageTex, STALE_TAG, TEXT_TAG, TILE_BYTES, scale_tag, tag_scale, texture_bytes, tile_side};
+pub use find::Find;
+use find::find_bar;
+pub use navigation::shortcuts;
+pub(crate) use organize::drop_gap;
+#[cfg(test)]
+pub(crate) use organize::grid_page_rect;
+use organize::organize_grid;
+#[cfg(test)]
+use organize::sharp_enough;
+use selection::{Selection, Span, click_unit, selection_actions};
+pub use xform::PageXform;
+use xform::snap_to_pixels;
+use zoom::anchored_scroll;
+pub use zoom::{GRID_ZOOM_RANGE, THUMBNAIL_ZOOM_RANGE};
+
+/// Logical pixels per PDF point at 100% (96 dpi, like browsers).
+pub const PT: f32 = 96.0 / 72.0;
+const GAP: f32 = 14.0;
+const MARGIN: f32 = 28.0;
+/// Horizontal gutter that keeps pages clear of the floating quick-action bar.
+const SIDE: f32 = 70.0;
+use crate::edit_text_ui::ImageHandle;
+
+/// Extension trait on `egui::Painter` to draw polygons.
+pub trait PainterExt {
+ fn polygon(&self, points: Vec<Pos2>, fill: Color32, stroke: Stroke) -> egui::layers::ShapeIdx;
+}
+
+impl PainterExt for egui::Painter {
+ fn polygon(&self, points: Vec<Pos2>, fill: Color32, stroke: Stroke) -> egui::layers::ShapeIdx {
+ self.add(egui::Shape::convex_polygon(points, fill, stroke))
+ }
+}
+
+/// User-space selectable bounding box for an image object.
+/// If the image object has an active clipping path applied to it (the crop box),
+/// this is the mathematical intersection of the full CTM-derived rect and the clipping path's rect.
+pub fn image_selectable_bounds(im: &pdfcraft_engine::PageImage) -> [f64; 4] {
+ if let Some(clip) = im.clip_rect {
+ let r = [im.rect[0].max(clip[0]), im.rect[1].max(clip[1]), im.rect[2].min(clip[2]), im.rect[3].min(clip[3])];
+ if r.iter().all(|v| v.is_finite()) && r[2] > r[0] && r[3] > r[1] {
+ return r;
+ }
+ }
+ im.visible_rect.unwrap_or(im.rect)
+}
+
+/// Screen-space selectable bounding box for an image object.
+/// If the image object has an active clipping path applied to it (the crop box),
+/// the final selectable `egui::Rect` is the mathematical intersection of the image's
+/// full CTM-derived rect and the clipping path's rect.
+pub fn image_screen_rect(im: &pdfcraft_engine::PageImage, xf: &PageXform, info: &DocInfo, page: usize) -> Rect {
+ let full = xf.user_rect_f64(info, page, im.rect);
+ if let Some(clip) = im.clip_rect {
+ let clip_r = xf.user_rect_f64(info, page, clip);
+ let inter = full.intersect(clip_r);
+ if inter.is_positive() {
+ return inter;
+ }
+ }
+ if let Some(vr) = im.visible_rect {
+ let r = xf.user_rect_f64(info, page, vr);
+ if r.is_positive() {
+ return r;
+ }
+ }
+ full
+}
+
+/// 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 width: f32,
+ pub height: f32,
+ pub theta: f32,
+ pub u_axis: (f64, f64),
+ pub v_axis: (f64, f64),
+ pub is_rotated: bool,
+}
+
+impl ImageObb {
+ /// Calculates the 4 rotated corners manually using center, width, height, and rotation angle (θ).
+ /// Local axes: `u_axis = (cos θ, sin θ)` and `v_axis = (-sin θ, cos θ)`.
+ /// Places the 8 resize handles exactly at these rotated vertices and midpoints.
+ pub fn from_center_size_angle(center: Pos2, width: f32, height: f32, theta: f32) -> Self {
+ let cos_t = theta.cos();
+ let sin_t = theta.sin();
+ let u_axis = (cos_t as f64, sin_t as f64);
+ let v_axis = (-sin_t as f64, cos_t as f64);
+ let u_vec = vec2(cos_t, sin_t);
+ let v_vec = vec2(-sin_t, cos_t);
+ let hw = width * 0.5;
+ let hh = height * 0.5;
+
+ let s00 = center - u_vec * hw - v_vec * hh;
+ let s10 = center + u_vec * hw - v_vec * hh;
+ let s11 = center + u_vec * hw + v_vec * hh;
+ let s01 = center - u_vec * hw + v_vec * hh;
+
+ let s_bc = center - v_vec * hh;
+ let s_rc = center + u_vec * hw;
+ let s_tc = center + v_vec * hh;
+ let s_lc = center - u_vec * hw;
+
+ let s_rot = s_tc + v_vec * 24.0;
+ let is_rotated = theta.abs() > 1e-4;
+
+ Self { s00, s10, s11, s01, s_bc, s_rc, s_tc, s_lc, s_rot, screen_center: center, width, height, theta, u_axis, v_axis, is_rotated }
+ }
+
+ pub fn new(matrix: [f64; 6], xf: &PageXform, info: &DocInfo, page: usize) -> Self {
+ Self::from_matrix(matrix, xf, info, page)
+ }
+
+ 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);
+ let theta = (b).atan2(a) as f32;
+ let is_rotated = b.abs() > 1e-4 || c.abs() > 1e-4;
+
+ Self {
+ s00,
+ s10,
+ s11,
+ s01,
+ s_bc,
+ s_rc,
+ s_tc,
+ s_lc,
+ s_rot,
+ screen_center,
+ width: (s10 - s00).length(),
+ height: (s01 - s00).length(),
+ theta,
+ u_axis,
+ v_axis,
+ is_rotated,
+ }
+ }
+
+ pub fn from_image(im: &pdfcraft_engine::PageImage, xf: &PageXform, info: &DocInfo, page: usize) -> Self {
+ let [_, b, c, ..] = im.matrix;
+ let is_rot = b.abs() > 1e-4 || c.abs() > 1e-4;
+ 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, 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 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 handle_id(&self, base_id: egui::Id, handle: ImageHandle) -> egui::Id {
+ base_id.with(match handle {
+ ImageHandle::TopLeft => "handle_tl",
+ ImageHandle::TopCenter => "handle_tc",
+ ImageHandle::TopRight => "handle_tr",
+ ImageHandle::RightCenter => "handle_rc",
+ ImageHandle::BottomRight => "handle_br",
+ ImageHandle::BottomCenter => "handle_bc",
+ ImageHandle::BottomLeft => "handle_bl",
+ ImageHandle::LeftCenter => "handle_lc",
+ })
+ }
+
+ pub fn handles_with_ids(&self, base_id: egui::Id) -> [(ImageHandle, Pos2, egui::Id); 8] {
+ [
+ (ImageHandle::TopLeft, self.s01, self.handle_id(base_id, ImageHandle::TopLeft)),
+ (ImageHandle::TopCenter, self.s_tc, self.handle_id(base_id, ImageHandle::TopCenter)),
+ (ImageHandle::TopRight, self.s11, self.handle_id(base_id, ImageHandle::TopRight)),
+ (ImageHandle::RightCenter, self.s_rc, self.handle_id(base_id, ImageHandle::RightCenter)),
+ (ImageHandle::BottomRight, self.s10, self.handle_id(base_id, ImageHandle::BottomRight)),
+ (ImageHandle::BottomCenter, self.s_bc, self.handle_id(base_id, ImageHandle::BottomCenter)),
+ (ImageHandle::BottomLeft, self.s00, self.handle_id(base_id, ImageHandle::BottomLeft)),
+ (ImageHandle::LeftCenter, self.s_lc, self.handle_id(base_id, ImageHandle::LeftCenter)),
+ ]
+ }
+
+ pub fn corners(&self) -> [Pos2; 4] {
+ [self.s00, self.s10, self.s11, self.s01]
+ }
+
+ /// Resizes the OBB proportionally along its local axes using projected mouse delta,
+ /// locking the diagonally opposite corner as the fixed anchor point.
+ pub fn scale_proportional(&self, handle: ImageHandle, delta: Vec2, min_size: f32) -> Self {
+ let u_vec = vec2(self.u_axis.0 as f32, self.u_axis.1 as f32);
+ let v_vec = vec2(self.v_axis.0 as f32, self.v_axis.1 as f32);
+ let delta_u = delta.dot(u_vec);
+ let delta_v = delta.dot(v_vec);
+ let min_s = min_size.max(5.0);
+
+ match handle {
+ ImageHandle::TopRight => {
+ let anchor = self.s00;
+ let s_u = (self.width + delta_u) / self.width.max(1e-4);
+ let s_v = (self.height + delta_v) / self.height.max(1e-4);
+ let s = if (s_u - 1.0).abs() >= (s_v - 1.0).abs() { s_u } else { s_v };
+ let s = s.max(min_s / self.width.max(1e-4)).max(min_s / self.height.max(1e-4));
+ let nw = self.width * s;
+ let nh = self.height * s;
+ let new_center = anchor + u_vec * (nw * 0.5) + v_vec * (nh * 0.5);
+ Self::from_center_size_angle(new_center, nw, nh, self.theta)
+ }
+ ImageHandle::TopLeft => {
+ let anchor = self.s10;
+ let s_u = (self.width - delta_u) / self.width.max(1e-4);
+ let s_v = (self.height + delta_v) / self.height.max(1e-4);
+ let s = if (s_u - 1.0).abs() >= (s_v - 1.0).abs() { s_u } else { s_v };
+ let s = s.max(min_s / self.width.max(1e-4)).max(min_s / self.height.max(1e-4));
+ let nw = self.width * s;
+ let nh = self.height * s;
+ let new_center = anchor - u_vec * (nw * 0.5) + v_vec * (nh * 0.5);
+ Self::from_center_size_angle(new_center, nw, nh, self.theta)
+ }
+ ImageHandle::BottomLeft => {
+ let anchor = self.s11;
+ let s_u = (self.width - delta_u) / self.width.max(1e-4);
+ let s_v = (self.height - delta_v) / self.height.max(1e-4);
+ let s = if (s_u - 1.0).abs() >= (s_v - 1.0).abs() { s_u } else { s_v };
+ let s = s.max(min_s / self.width.max(1e-4)).max(min_s / self.height.max(1e-4));
+ let nw = self.width * s;
+ let nh = self.height * s;
+ let new_center = anchor - u_vec * (nw * 0.5) - v_vec * (nh * 0.5);
+ Self::from_center_size_angle(new_center, nw, nh, self.theta)
+ }
+ ImageHandle::BottomRight => {
+ let anchor = self.s01;
+ let s_u = (self.width + delta_u) / self.width.max(1e-4);
+ let s_v = (self.height - delta_v) / self.height.max(1e-4);
+ let s = if (s_u - 1.0).abs() >= (s_v - 1.0).abs() { s_u } else { s_v };
+ let s = s.max(min_s / self.width.max(1e-4)).max(min_s / self.height.max(1e-4));
+ let nw = self.width * s;
+ let nh = self.height * s;
+ let new_center = anchor + u_vec * (nw * 0.5) - v_vec * (nh * 0.5);
+ Self::from_center_size_angle(new_center, nw, nh, self.theta)
+ }
+ ImageHandle::RightCenter => {
+ let anchor = self.s_lc;
+ let nw = (self.width + delta_u).max(min_s);
+ let new_center = anchor + u_vec * (nw * 0.5);
+ Self::from_center_size_angle(new_center, nw, self.height, self.theta)
+ }
+ ImageHandle::LeftCenter => {
+ let anchor = self.s_rc;
+ let nw = (self.width - delta_u).max(min_s);
+ let new_center = anchor - u_vec * (nw * 0.5);
+ Self::from_center_size_angle(new_center, nw, self.height, self.theta)
+ }
+ ImageHandle::TopCenter => {
+ let anchor = self.s_bc;
+ let nh = (self.height + delta_v).max(min_s);
+ let new_center = anchor + v_vec * (nh * 0.5);
+ Self::from_center_size_angle(new_center, self.width, nh, self.theta)
+ }
+ ImageHandle::BottomCenter => {
+ let anchor = self.s_tc;
+ let nh = (self.height - delta_v).max(min_s);
+ let new_center = anchor - v_vec * (nh * 0.5);
+ Self::from_center_size_angle(new_center, self.width, nh, self.theta)
+ }
+ }
+ }
+}
+
+/// Projects mouse delta onto local unit axes `u_axis` and `v_axis` using the dot product.
+pub fn project_delta(delta: Vec2, u_axis: (f64, f64), v_axis: (f64, f64)) -> (f64, f64) {
+ let dx = delta.x as f64;
+ let dy = delta.y as f64;
+ (dx * u_axis.0 + dy * u_axis.1, dx * v_axis.0 + dy * v_axis.1)
+}
+
+/// Visible grid rows, plus one adjacent row in either direction. Work is independent of
+/// document length, including after a large scroll jump.
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Fit {
+ Width,
+ Page,
+ Height,
+ None,
+}
+
+/// 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,
+ pub continuous: bool,
+ pub cover: bool,
+ pub fit: Fit,
+ pub zoom: f32,
+}
+
+/// 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> {
+ 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> {
+ 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<Self> {
+ 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::<f32>().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)]
+pub enum SnapshotKind {
+ SignedVersion,
+ Revision,
+}
+
+#[derive(Clone, Debug)]
+pub struct Snapshot {
+ pub kind: SnapshotKind,
+ /// The 1-based revision shown.
+ pub revision: usize,
+ /// The name of the document it was opened from.
+ pub from: String,
+}
+
+/// 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)
+/// is enough.
+pub(crate) fn tab_label(app: &PdfCraftApp, index: usize) -> Option<String> {
+ let view = app.views.get(index)?;
+ let doc = app.session.get(view.id)?;
+ let Some(snap) = view.snapshot.as_ref() else { return Some(doc.display_name()) };
+ Some(snapshot_tab_name(&doc.display_name(), &doc.name, snap))
+}
+
+/// A snapshot's tab name from its source title, file name and marker. Pure so the
+/// tab strip, window title and picker cannot disagree with each other.
+pub(crate) fn snapshot_tab_name(title: &str, file_name: &str, snapshot: &Snapshot) -> String {
+ if title == file_name {
+ return file_name.into();
+ }
+ if snapshot.kind == SnapshotKind::SignedVersion {
+ format!("{title} (signed version)")
+ } else {
+ format!("{title} (revision {})", snapshot.revision)
+ }
+}
+
+pub struct DocView {
+ pub id: DocId,
+ 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,
+ 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,
+ pub notice_dismissed: bool,
+ /// The user has been told that the form's scripts were turned off (it is said once).
+ pub scripts_off_noted: bool,
+ /// The file changed on disk while this document had unsaved changes: the notice bar asks
+ /// before replacing it (#431).
+ pub disk_changed: bool,
+ /// The snapshot notice bar's Close was clicked: the tab closes at the top of the next
+ /// frame, where no document borrow is held (the bar itself can't close it).
+ pub close_requested: bool,
+ /// A historical snapshot of another document (see [`Snapshot`]): `None` for real documents.
+ pub snapshot: Option<Snapshot>,
+ /// 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<usize>,
+ pub forward: Vec<usize>,
+ /// Pending navigation: page and fraction down the page to align with the viewport top.
+ pub goto: Option<(usize, f32)>,
+ /// 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<f32>, Option<f32>, Vec2)>,
+ /// Pending keyboard scrolling, in points down (negative: up): ↓ / ↑, and Page Down /
+ /// Page Up where the pages scroll.
+ pub key_scroll: f32,
+ /// 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)>,
+ /// 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<SavedDisplay>,
+ pages: HashMap<usize, PageTex>,
+ /// Pages the renderer could not draw, with the reason (never re-requested).
+ errors: HashMap<usize, String>,
+ /// When each still-missing page was first shown, to flag unusually slow renders.
+ waiting_since: HashMap<usize, f64>,
+ thumbs: HashMap<usize, PageTex>,
+ /// This frame's consumers, with visible cells ahead of prefetch.
+ thumb_demand: HashMap<usize, bool>,
+ frame_queue: Vec<RenderRequest>,
+ /// 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<usize>,
+ /// Thumbnails that are out of date (still shown until their replacement arrives).
+ stale_thumbs: HashSet<usize>,
+ /// 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<usize, (u64, TextureHandle)>,
+ /// 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<usize, Arc<PageText>>,
+ pub(crate) text_failed: HashSet<usize>,
+ pub find: Option<Find>,
+ selection: Option<Selection>,
+ /// 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<Selection>,
+ /// 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,
+ /// 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<Pos2>,
+ /// 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<RenderRequest>,
+ /// 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 heights in points (view space), for mapping text positions to scroll offsets.
+ page_heights: Vec<f32>,
+ /// Screen rects of the pages drawn last frame (hit-testing, tests, automation).
+ screen_rects: Vec<(usize, Rect)>,
+ screen_xforms: Vec<(usize, PageXform)>,
+ /// 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 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<usize>,
+ /// Pages Edit looked at and found not to be a scan, with the document's edit generation then:
+ /// they are looked at again only after the document changes (an image added, say).
+ pub(crate) auto_ocr_skipped: std::collections::HashMap<usize, u64>,
+ /// Turns wheel input into page turns in single-page view.
+ wheel: crate::wheel_pager::WheelPager,
+ /// Until this time, apply precise (touchpad) wheel input 1:1 and suppress egui's eased copy.
+ /// A precision touchpad sends pixel-precise `MouseWheel` events; on Windows they arrive with
+ /// no `TouchPhase::Start`, so egui eases deltas of 8 px or more and the page lags the finger
+ /// (#759). The window outlasts a single frame so egui's internal easing tail is suppressed as
+ /// it decays, instead of adding on top of the 1:1 motion.
+ precise_scroll_until: f64,
+ /// 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<usize>,
+ pub(crate) organize_range: crate::page_selection_ui::PageSelectionInput,
+ /// Anchor for ⇧-click range selection in the organize grid.
+ select_anchor: Option<usize>,
+ /// An edit requested by the view (organize toolbar, keys), applied by the app this frame.
+ pub pending_edit: Option<Edit>,
+ /// Edit text: the lines per page (with the document generation they were read at), and the
+ /// line being edited.
+ pub(crate) edit_lines: HashMap<usize, (u64, Vec<pdfcraft_engine::TextBlock>)>,
+ pub line_editor: Option<crate::edit_text_ui::LineEditor>,
+ /// The paragraph editor whose edit was just queued. It opens again with its typing if the
+ /// edit fails, as a refused form field does.
+ pub(crate) applied_editor: Option<crate::edit_text_ui::LineEditor>,
+ /// The box a click switched to while another paragraph was being edited: it opens once the
+ /// queued edit has applied, so its index and geometry come from the document it now is (#2022).
+ /// It is held as the paragraph's text and box, not an index: the edit can regroup the page.
+ pub(crate) pending_text_open: Option<(usize, pdfcraft_engine::BlockKey)>,
+ pub(crate) text_background: crate::edit_text_ui::TextBackground,
+ pub(crate) move_background: crate::content_ui::MoveBackground,
+ /// Edit text & images: the images per page (by document generation), and the selected one.
+ pub(crate) edit_images: HashMap<usize, (u64, Vec<pdfcraft_engine::PageImage>)>,
+ pub(crate) objects: crate::object_ui::ObjectSelection,
+ pub image_selection: Option<crate::edit_text_ui::ImageSelection>,
+ /// Select tool: the picture clicked, to copy in its original format.
+ pub picked_image: Option<crate::image_pick::PickedImage>,
+ /// A paragraph box being dragged (moved, or resized from its right edge) in Edit text.
+ pub block_drag: Option<crate::edit_text_ui::BlockDrag>,
+ /// Commenting state: selected comment, gestures, composer.
+ pub comments: crate::comments::CommentView,
+ pub measure: crate::measure_ui::MeasureView,
+ /// Form filling state: the focused field.
+ pub forms: crate::forms_ui::FormView,
+ /// Prepare a form: the selected field and the gesture in progress.
+ pub prepare: crate::prepare::PrepareView,
+ /// Prepare a form ▸ Calculation order.
+ pub(crate) calc_order: crate::calc_order_ui::CalcOrderView,
+ /// Edit a PDF: the selected added item, the text being typed.
+ pub content: crate::content_ui::ContentView,
+ /// Edit a PDF ▸ Link tool state.
+ pub links: crate::link_ui::LinkView,
+ /// Redact tool: the box being drawn, and a mark to add (page, quads) for the app to style.
+ pub redact_drag: crate::redact_ui::AreaDrag,
+ pub pending_redaction: Option<(usize, Vec<[f64; 8]>)>,
+ /// A crop rectangle being dragged (Crop tool).
+ pub crop_drag: crate::crop::CropDrag,
+ /// Enhance ▸ Camera image: the quadrilateral being placed.
+ pub camera: Option<crate::camera_ui::CameraQuad>,
+ /// Enhance ▸ Camera image: the page just enhanced, while the bar offers rotate, crop and
+ /// organize.
+ pub camera_done: Option<crate::camera_ui::CameraDone>,
+ /// Use a certificate: a signature rectangle being 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<Vec<usize>>,
+ /// Pages panel: the pages being dragged to a new place.
+ pub panel_drag: Option<Vec<usize>>,
+ /// Marquee Zoom / Snapshot: the rectangle being dragged (page, start), and a finished one.
+ pub marquee: Option<(usize, Pos2)>,
+ pub marquee_done: Option<crate::zoom_snap::Marquee>,
+ /// Fill & Sign text being typed.
+ pub fill_text: Option<crate::fill_sign::TypeBox>,
+ /// A queued Fill & Sign signature: select it after its edit succeeds, then leave placement.
+ pub(crate) fill_signature_page: Option<usize>,
+ pub(crate) signature_drag: crate::signature_drag::SignatureDrag,
+ /// A non-edit action requested by the organize toolbar, handled by the app.
+ pub pending_action: Option<ViewAction>,
+ /// The grid gap the next inserted files go to (set by a "+" between pages); otherwise they
+ /// go after the selection.
+ pub insert_at: Option<usize>,
+ /// The page-grid gap under the pointer this frame (where dropped files go), when it can
+ /// take pages.
+ pub grid_gap: Option<usize>,
+ /// 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<Rect>,
+ /// The Pages-panel gap under the pointer (where dropped files go), when it can take pages.
+ pub panel_gap: Option<usize>,
+ /// 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<usize>,
+ /// 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<f32>,
+ /// 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<usize>,
+ /// 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<usize, (u32, TextureHandle)>,
+ /// 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,
+ /// Side-by-side compare: scroll to here this frame, following the other half.
+ pub(crate) sync_scroll: Option<Vec2>,
+ /// The page widget's id, by which the Hand tool finds its drag before the pages are laid out.
+ page_widget: Option<egui::Id>,
+ 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<usize>,
+}
+
+/// Organize-toolbar actions that need the app (file pickers, new tabs, dialogs).
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum ViewAction {
+ InsertFromFile,
+ /// Insert files at a gap of the page grid (0 = before the first page).
+ InsertFromFileAt(usize),
+ /// Replace the selected pages with pages from another file.
+ ReplacePages,
+ /// Save the document as the grid shows it.
+ Save,
+ Extract,
+ Split,
+ /// Split before each selected page: opens Split on that mode.
+ SplitBeforeSelected,
+ /// Copy the selected pages (Cut also deletes them).
+ CopyPages {
+ cut: bool,
+ },
+ /// Paste copied pages after the selection.
+ PastePages,
+ /// Enhance ▸ Camera image: straighten what the corners enclose.
+ EnhanceCamera,
+ /// Leave Enhance ▸ Camera image (Cancel before Enhance page, Done after it).
+ CancelCamera,
+ /// After Enhance page: turn the enhanced page a quarter.
+ CameraRotate {
+ clockwise: bool,
+ },
+ /// After Enhance page: enhance again at the slider's clean-up level.
+ CameraLevel,
+ /// After Enhance page: leave the tool for this command (Crop pages, Organize pages).
+ CameraNext(&'static str),
+}
+
+/// Default page right-click menu actions.
+#[derive(Clone, Debug, PartialEq)]
+pub(crate) enum PageMenuAction {
+ RotateCCW(usize),
+ RotateCW(usize),
+ Print,
+ SelectTool,
+ HandTool,
+ MarqueeZoom,
+ Copy,
+ Paste(usize, [f64; 2]),
+ AddComment(usize, [f64; 2]),
+ AddBookmark(usize),
+ 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_paste: 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<PageMenuAction>) {
+ // Top horizontal icon bar: Rotate CCW, Print, Select tool, Hand tool, Marquee Zoom
+ ui.horizontal(|ui| {
+ ui.spacing_mut().item_spacing.x = 4.0;
+ if crate::icons::button(ui, "rotate-ccw", 24.0, false, tl!("Rotate view counterclockwise")).clicked() {
+ *action = Some(PageMenuAction::RotateCCW(page));
+ ui.close();
+ }
+ ui.add_enabled_ui(perms.can_print, |ui| {
+ if crate::icons::button(ui, "printer", 24.0, false, tl!("Print")).clicked() {
+ *action = Some(PageMenuAction::Print);
+ ui.close();
+ }
+ });
+ if crate::icons::button(ui, "mouse-pointer-2", 24.0, false, tl!("Select Tool")).clicked() {
+ *action = Some(PageMenuAction::SelectTool);
+ ui.close();
+ }
+ if crate::icons::button(ui, "hand", 24.0, false, tl!("Hand Tool")).clicked() {
+ *action = Some(PageMenuAction::HandTool);
+ ui.close();
+ }
+ if crate::icons::button(ui, "zoom-in", 24.0, false, tl!("Marquee Zoom")).clicked() {
+ *action = Some(PageMenuAction::MarqueeZoom);
+ ui.close();
+ }
+ });
+
+ ui.separator();
+
+ if ui.add_enabled(perms.can_copy, egui::Button::new(tl!("Copy")).shortcut_text("Ctrl+C")).clicked() {
+ *action = Some(PageMenuAction::Copy);
+ ui.close();
+ }
+ if ui.add_enabled(perms.can_paste, egui::Button::new(tl!("Paste")).shortcut_text("Ctrl+V")).clicked() {
+ *action = Some(PageMenuAction::Paste(page, at));
+ ui.close();
+ }
+
+ ui.separator();
+
+ if ui.add_enabled(perms.can_annotate, egui::Button::new(tl!("Add comment"))).clicked() {
+ *action = Some(PageMenuAction::AddComment(page, at));
+ ui.close();
+ }
+ if perms.has_annotations && ui.add_enabled(perms.can_modify, egui::Button::new(tl!("Flatten comments"))).clicked() {
+ *action = Some(PageMenuAction::FlattenComments);
+ ui.close();
+ }
+ if ui.add_enabled(perms.can_assemble, egui::Button::new(tl!("Add bookmark"))).clicked() {
+ *action = Some(PageMenuAction::AddBookmark(page));
+ ui.close();
+ }
+ if ui.add_enabled(perms.can_copy, egui::Button::new(tl!("Take a snapshot"))).clicked() {
+ *action = Some(PageMenuAction::TakeSnapshot);
+ ui.close();
+ }
+
+ ui.separator();
+
+ if ui.add_enabled(perms.can_modify, egui::Button::new(egui::RichText::new(tl!("Edit this PDF")).strong())).clicked() {
+ *action = Some(PageMenuAction::EditPdf);
+ ui.close();
+ }
+ if ui.add_enabled(perms.can_modify, egui::Button::new(tl!("Add text"))).clicked() {
+ *action = Some(PageMenuAction::AddText);
+ ui.close();
+ }
+ if ui.add_enabled(perms.can_modify, egui::Button::new(tl!("Add image"))).clicked() {
+ *action = Some(PageMenuAction::AddImage);
+ ui.close();
+ }
+ if ui.add_enabled(perms.can_assemble, egui::Button::new(tl!("Delete page"))).clicked() {
+ *action = Some(PageMenuAction::DeletePage(page));
+ ui.close();
+ }
+ if ui.add_enabled(perms.can_copy, egui::Button::new(tl!("Export this PDF"))).clicked() {
+ *action = Some(PageMenuAction::ExportPdf);
+ ui.close();
+ }
+
+ ui.separator();
+
+ if ui.button(tl!("Find text or tools")).clicked() {
+ *action = Some(PageMenuAction::Find);
+ ui.close();
+ }
+ if ui.button(tl!("Rotate view clockwise")).clicked() {
+ *action = Some(PageMenuAction::RotateCW(page));
+ ui.close();
+ }
+ if ui.button(tl!("Document properties…")).clicked() {
+ *action = Some(PageMenuAction::DocProperties);
+ ui.close();
+ }
+}
+
+impl DocView {
+ /// Whether a middle-button scrolling gesture is active (tests and automation).
+ pub fn auto_scrolling(&self) -> bool {
+ self.auto_scroll.active()
+ }
+
+ /// Whether a held middle-button pan is active, outside Linux (tests and automation).
+ pub fn middle_panning(&self) -> bool {
+ self.auto_scroll.panning()
+ }
+
+ /// 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;
+ self.block_drag = None;
+ self.org_drag = None;
+ self.panel_drag = None;
+ self.selection_drag = false;
+ self.auto_scroll.cancel();
+ self.prepare.cancel_pointer_gesture();
+ 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 {
+ Self {
+ id,
+ zoom: defaults.zoom,
+ fit: defaults.fit,
+ layout: defaults.layout,
+ continuous: defaults.continuous,
+ show_page_gaps: defaults.show_page_gaps,
+ rotation: 0,
+ current: 0,
+ organize: false,
+ highlight_fields: defaults.highlight_fields,
+ page_input: "1".into(),
+ page_input_reselect: false,
+ notice_dismissed: false,
+ scripts_off_noted: false,
+ disk_changed: false,
+ close_requested: false,
+ snapshot: None,
+ cover: false,
+ back: Vec::new(),
+ forward: Vec::new(),
+ goto: None,
+ goto_point: None,
+ key_scroll: 0.0,
+ single_edges: None,
+ flash: None,
+ compare_marks: Vec::new(),
+ presentation: None,
+ pages: HashMap::new(),
+ errors: HashMap::new(),
+ waiting_since: HashMap::new(),
+ thumbs: HashMap::new(),
+ thumb_demand: HashMap::new(),
+ frame_queue: Vec::new(),
+ frame_geometry_changed: false,
+ frame_visible: 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_failed: HashSet::new(),
+ find: None,
+ selection: None,
+ all_text: false,
+ actions_dismissed: None,
+ selection_drag: 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_heights: info.pages.iter().map(|p| p.height).collect(),
+ screen_rects: Vec::new(),
+ screen_xforms: Vec::new(),
+ viewport_screen: Rect::NOTHING,
+ zoom_anchor: None,
+ shown: false,
+ auto_ocr_tried: Default::default(),
+ auto_ocr_skipped: Default::default(),
+ wheel: Default::default(),
+ precise_scroll_until: 0.0,
+ 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(),
+ 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,
+ block_drag: None,
+ pending_action: None,
+ insert_at: None,
+ grid_gap: None,
+ pages_panel: None,
+ panel_gap: None,
+ panel_followed: 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,
+ sync_scroll: None,
+ page_widget: None,
+ pan_hold_until: 0.0,
+ slow_pages: HashSet::new(),
+ comments: Default::default(),
+ 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,
+ crop_drag: None,
+ camera: None,
+ camera_done: None,
+ sign: Default::default(),
+ org_drag: None,
+ panel_drag: None,
+ marquee: None,
+ marquee_done: None,
+ fill_text: None,
+ fill_signature_page: None,
+ signature_drag: Default::default(),
+ }
+ }
+
+ /// 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) {
+ self.invalidate_content();
+ self.frame_geometry_changed = true;
+ self.page_count = info.pages.len();
+ self.page_heights = info.pages.iter().map(|p| 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;
+ }
+ if self.select_anchor.is_some_and(|a| a > last) {
+ self.select_anchor = None;
+ }
+ self.goto = None;
+ self.goto_point = None;
+ self.zoom_anchor = None;
+ self.flash = None;
+ // Thumbnail drags hold page indexes from before the change.
+ self.panel_drag = None;
+ self.org_drag = None;
+ self.reset_coarse_state();
+ }
+
+ /// 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
+ /// 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;
+ fresh.organize = self.organize;
+ fresh.grid_zoom = self.grid_zoom;
+ fresh.thumbnail_zoom = self.thumbnail_zoom;
+ // Same document id, so the scroll offset egui keeps for it is still this document's.
+ fresh.shown = self.shown;
+ fresh.highlight_fields = self.highlight_fields;
+ fresh.notice_dismissed = self.notice_dismissed;
+ fresh.snapshot = self.snapshot.clone();
+ fresh.close_requested = self.close_requested;
+ fresh.cover = self.cover;
+ // Still presenting, with the display to go back to on leaving.
+ fresh.presentation = self.presentation.take();
+ 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;
+ *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()));
+ self.page_input_reselect = true;
+ }
+
+ /// Select pages in the organize grid (tests, automation). Empty clears the selection.
+ 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();
+ }
+}
+
+/// Draws the document tab at `index`: its notice bars, then its pages (or the Organize grid) in a
+/// scroll area with this frame's zoom, scrolling, tool input, overlays and render requests.
+#[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);
+ }
+}
+
+pub fn document_area(app: &mut PdfCraftApp, index: usize, ui: &mut egui::Ui) {
+ let t = Tokens::get(ui.ctx());
+ // Keyboard scrolling applies to this frame's page view only, never later.
+ let key_scroll = std::mem::take(&mut app.views[index].key_scroll);
+ if key_scroll != 0.0 {
+ app.views[index].end_find_following();
+ }
+ // The Search panel closed: its search moves to the find bar.
+ let search_open = app.right == Some(crate::RightPanel::Search);
+ if let Some(f) = app.views[index].find.as_mut()
+ && f.in_panel
+ && !search_open
+ {
+ f.in_panel = false;
+ }
+ // The snapshot notice bar's Close was clicked: close here, where no document borrow is
+ // held. The tab is looked up by id: indices may have shifted since the click, and the
+ // flag rides its own view, so a stale flag can never close the wrong tab.
+ let pending = app.views.get(index).filter(|v| v.close_requested).map(|v| v.id).and_then(|id| app.views.iter().position(|v| v.id == id));
+ if let Some(i) = pending {
+ app.views[i].close_requested = false;
+ if app.has_unsaved_work(i) {
+ app.close_request = Some(crate::CloseRequest::Tab(app.views[i].id));
+ } else {
+ app.close_tab(i);
+ }
+ return;
+ }
+ let Some(doc) = app.session.get(app.views[index].id) else { return };
+ let info = &doc.info;
+ let paper = app.session.reading_colors(app.views[index].id).and_then(|c| c.params).map_or(Color32::WHITE, |p| {
+ let [r, g, b] = p.background;
+ Color32::from_rgb(r, g, b)
+ });
+ if info.pages.is_empty() {
+ app.views[index].auto_scroll.cancel();
+ ui.centered_and_justified(|ui| ui.label(tl!("This document has no pages.")));
+ return;
+ }
+ // The print dialog queues its own rasters later in the frame. Closing it drops them.
+ if app.dialog != Some(crate::Dialog::Print) {
+ app.views[index].print_pages.clear();
+ }
+ // The Prepare a form panel is open (or a field tool is picked): fields are edited, not filled.
+ let preparing = app.is_preparing();
+ // Prepare a form ▸ Calculation order: the order's steps and links on the page.
+ let calc_order = preparing && app.left_open && app.left == crate::LeftPanel::CalculationOrder;
+ // Edit a PDF: added text and images can be selected, moved and edited.
+ let editing_content =
+ (app.left_open && app.left == crate::LeftPanel::Tool("edit")) || matches!(app.quick_tool, QuickTool::AddText | QuickTool::EditText);
+ let text_style = app.text_style.clone();
+ let show_secured_notice = app.show_secured_notice;
+ // Asking means opening the system clipboard (and decoding any image on it), so it's asked
+ // once when a right-click opens a menu, not on every frame.
+ 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)
+ };
+ let view = &mut app.views[index];
+ // Opened without the owner password and something is restricted. The notice says so unless
+ // the user turned it off (#4035): the restrictions themselves, and Document Properties ▸
+ // Security, stay as they are.
+ let secured = show_secured_notice && doc.security_summary().is_some_and(|s| !(s.owner || (s.permissions.modify() && s.permissions.assemble())));
+ let repaired = !doc.repair_log().is_empty();
+ match notices(view, doc, secured, repaired, crate::sign_ui::banner(&doc.signatures), ui, &t) {
+ #[cfg(not(target_arch = "wasm32"))]
+ Some(Notice::Reload) => app.watch.reload_request = Some(view.id),
+ #[cfg(target_arch = "wasm32")]
+ Some(Notice::Reload) => {}
+ Some(Notice::Repairs) => app.dialog = Some(crate::Dialog::Properties(crate::PropsTab::Advanced)),
+ Some(Notice::Security) => app.dialog = Some(crate::Dialog::Properties(crate::PropsTab::Security)),
+ Some(Notice::Unlock) => app.unlock_prompt = Some(crate::UnlockPrompt::new(doc, None)),
+ // Flags the view: the tab closes at the top of the next frame, where no document
+ // borrow is held.
+ Some(Notice::Close) => {
+ if let Some(view) = app.views.get_mut(index) {
+ view.close_requested = true;
+ }
+ }
+ Some(Notice::Signatures) => app.right = Some(RightPanel::Signatures),
+ Some(Notice::FieldHighlights(on)) => app.view_defaults.highlight_fields = on,
+ Some(Notice::Console) => app.dialog = Some(crate::Dialog::JsConsole),
+ // Back on in Preferences ▸ General.
+ Some(Notice::HideSecured) => app.show_secured_notice = false,
+ None => {}
+ }
+ // No dialog, close prompt or palette over the page: only then does page input count.
+ let modal = app.modal_open();
+ let unobstructed = !modal && !app.palette_open;
+ let organize_zoom = app.organize_zoom;
+ let view = &mut app.views[index];
+ if view.organize {
+ // One remembered grid size for every document, kept in the settings.
+ view.set_grid_zoom(organize_zoom);
+ organize_grid(view, info, doc.allows_assembly(), doc.dirty, unobstructed, ui, &t);
+ app.organize_zoom = view.grid_zoom();
+ return;
+ }
+
+ let avail = ui.available_rect_before_wrap();
+ view.viewport_w = avail.width();
+ view.viewport_h = avail.height();
+ let old_zoom = view.zoom;
+ view.fit_zoom(info);
+ if view.shown && view.zoom_anchor.is_none() && view.goto.is_none() && view.goto_point.is_none() && (view.zoom - old_zoom).abs() > 1e-4 {
+ let prev_viewport = view.viewport_screen;
+ let top_y = prev_viewport.min.y;
+ let anchor = view
+ .screen_rects
+ .iter()
+ .find(|(_, r)| r.min.y <= top_y && r.max.y > top_y)
+ .map(|(p, r)| {
+ let fy = if r.height() > 0.0 { ((top_y - r.min.y) / r.height()).clamp(0.0, 1.0) } else { 0.0 };
+ (*p, fy, 0.0f32)
+ })
+ .or_else(|| view.screen_rects.iter().find(|(_, r)| r.min.y >= top_y).map(|(p, r)| (*p, 0.0f32, (r.min.y - top_y).max(0.0))))
+ .or_else(|| view.screen_rects.last().map(|(p, r)| (*p, 1.0f32, (r.max.y - top_y).max(0.0))));
+ if let Some((page, fy, rel_y)) = anchor {
+ view.zoom_anchor = Some((page, 0.5, fy, vec2(avail.width() / 2.0, rel_y)));
+ } else {
+ view.zoom_anchor = Some((view.current, 0.5, 0.0, vec2(avail.width() / 2.0, MARGIN)));
+ }
+ }
+
+ // Pinch / ctrl+scroll zoom, anchored on the current page.
+ let zoom_delta = crate::motion::zoom_delta(ui.ctx());
+ // Exclude the previous frame's scrollbar tracks from gesture activation.
+ let navigation_rect = if view.viewport_screen.is_positive() { avail.intersect(view.viewport_screen) } else { avail };
+ let navigation_enabled = app.dialog.is_none() && app.close_request.is_none() && !app.palette_open && ui.is_enabled() && ui.input(|i| i.focused);
+ // Full screen: a click on the document goes forward a page and a shift-click back, as in
+ // Acrobat, unless the click did something else (a link, a word selected). Decided below,
+ // once the pages have had the click.
+ let present_click =
+ view.presentation.is_some() && navigation_enabled && presentation_click(ui, navigation_rect) && app.quick_tool == QuickTool::Select;
+ // Shift as held now, or as the click's own event carried it (a synthetic click).
+ let present_back = present_click
+ && ui.input(|i| {
+ i.modifiers.shift
+ || i.events.iter().any(|e| {
+ matches!(e, egui::Event::PointerButton { button: egui::PointerButton::Primary, pressed: false, modifiers, .. } if modifiers.shift)
+ })
+ });
+ if zoom_delta.is_finite() && zoom_delta > 0.0 && zoom_delta != 1.0 && navigation_enabled && ui.rect_contains_pointer(navigation_rect) {
+ let z = view.zoom * zoom_delta;
+ match zoom_anchor(ui) {
+ Some(p) => view.zoom_at(z, p),
+ None => view.set_zoom(z),
+ }
+ }
+ view.viewport_screen = avail;
+ let auto_delta = if unobstructed {
+ view.auto_scroll.update(ui, avail, false)
+ } else {
+ view.auto_scroll.cancel();
+ Vec2::ZERO
+ };
+
+ // Drawing a comment: the pointer in a band along any edge (or just past it) scrolls the view
+ // that way, so a point beyond what is shown can be reached without letting go of the tool.
+ let edge_delta = if unobstructed && matches!(view.comments.gesture, Some(comments::Gesture::Draw { .. })) {
+ let (pointer, dt) = drawing_edge_pointer(ui);
+ crate::autoscroll::edge_scroll(pointer, avail, dt)
+ } else {
+ Vec2::ZERO
+ };
+ if edge_delta != Vec2::ZERO {
+ ui.ctx().request_repaint();
+ }
+
+ let content_w = view.content_width(info, avail.width());
+ let rects = view.layout(info, content_w, ui.ctx().pixels_per_point());
+ // When not scrolling continuously, only one row is shown at a time: the current page, or the
+ // current two-page spread (with the cover rule). These indices drive paging, which pages are
+ // drawn, and the content height (#752). Empty for a document with no pages.
+ let shown_row = |view: &DocView| -> Vec<usize> {
+ if rects.is_empty() {
+ return Vec::new();
+ }
+ let last = rects.len() - 1;
+ let cur = view.current.min(last);
+ match view.layout {
+ PageLayout::Single => vec![cur],
+ PageLayout::TwoUp if view.cover && cur == 0 => vec![0],
+ PageLayout::TwoUp => {
+ let first = if view.cover { cur - (cur + 1) % 2 } else { cur - cur % 2 };
+ if first < last { vec![first, first + 1] } else { vec![first] }
+ }
+ }
+ };
+ let row = shown_row(view);
+ let middle_gesture = view.auto_scroll.blocks_input();
+ // Not scrolling: when the whole page or spread fits, the wheel would do nothing, so it turns
+ // pages instead; zoomed in far enough to pan, it pans, and at the edge it turns the page on
+ // (#1924, `single_page_wheel_edge`). Touch drags are untouched: with
+ // nothing to pan, touch users turn pages with the rail buttons, the page box and the arrow
+ // keys. Runs before `visible_pages` so the frame that turns the page draws it.
+ let mut single_paging = false;
+ let mut edge_turned = false;
+ if !view.continuous {
+ // The row's bounding box on screen (one page, or a two-page spread).
+ let row_rect = row.iter().filter_map(|&i| rects.get(i)).copied().reduce(Rect::union);
+ // Within a point, so layout rounding can't stop a fitting page from turning.
+ let fits = row_rect.is_some_and(|r| r.height() + 2.0 * MARGIN <= avail.height() + 1.0);
+ let can_turn = !middle_gesture && unobstructed && ui.rect_contains_pointer(avail);
+ single_paging = can_turn && fits;
+ // Every wheel event goes to the pager, so it follows each trackpad touch to its end
+ // even while the page can't turn.
+ ui.input(|i| {
+ for e in &i.events {
+ if let egui::Event::MouseWheel { unit, delta, phase, modifiers, .. } = e {
+ // Zooming (⌘ or Ctrl) and sideways scrolling (Shift) never turn pages.
+ let dy = if modifiers.command || modifiers.ctrl || modifiers.shift { 0.0 } else { delta.y };
+ if fits {
+ view.single_page_wheel(*unit, dy, *phase, i.time, can_turn);
+ } else {
+ edge_turned |= view.single_page_wheel_edge(*unit, dy, *phase, i.time, can_turn);
+ }
+ }
+ }
+ });
+ if single_paging {
+ // Paging owns vertical wheel motion here. A diagonal gesture keeps its sideways
+ // part, as `ScrollArea` itself handles each axis.
+ ui.input_mut(|i| i.smooth_scroll_delta.y = 0.0);
+ }
+ }
+ // Point input bypasses egui smoothing for 1:1 motion. Line input keeps egui's configured,
+ // smoothed base and adds only the accelerated surplus. While point suppression is active,
+ // reconstruct line and page input here so current coarse events survive without exposing an
+ // older eased tail.
+ let now = ui.input(|i| i.time);
+ let input = if ui.rect_contains_pointer(avail) {
+ // Match the line distance used by egui's other scroll areas.
+ let live = ui.ctx().options(|o| o.input_options.line_scroll_speed);
+ let line_points = if live.is_finite() && live > 0.0 { live } else { crate::scroll_speed::EGUI_LINE_POINTS };
+ ui.input(|i| crate::wheel_boost::accumulate(&i.events, line_points, single_paging))
+ } else {
+ crate::wheel_boost::FrameInput::default()
+ };
+ let mut precise_scroll = input.precise;
+ let mut line_base = input.line;
+ let mut boost_extra = crate::wheel_boost::boost_extra(input, &mut view.wheel_boost_x, &mut view.wheel_boost_y, now);
+ let has_page = input.page != Vec2::ZERO;
+ if now.is_finite() && precise_scroll != Vec2::ZERO && !has_page {
+ view.precise_scroll_until = now + SUPPRESS_SECS;
+ }
+ if edge_turned {
+ // The turn leaves egui's eased copy of the notch to decay for a few frames; it must not
+ // scroll the page just shown away from its top (or bottom).
+ view.precise_scroll_until = now + 0.25;
+ view.fling.stop();
+ }
+ let paging_owns_vertical = single_paging || (!view.continuous && view.wheel.gesture_turned());
+ if paging_owns_vertical {
+ precise_scroll.y = 0.0;
+ line_base.y = 0.0;
+ boost_extra.y = 0.0;
+ }
+ // egui smooths a Point event that moved at least 8 points, keeping part of it for later
+ // passes. Suppression must outlive that whole action: once it expired after a fixed 0.25 s,
+ // the last few eased points leaked through the ScrollArea after a precise 1:1 scroll (held
+ // point input measured 33 points for a 30-point event). Keep hiding the eased copy until
+ // egui says the action is over, then forget the suppression.
+ let scrolling = ui.input(|i| i.is_scrolling());
+ if now < view.precise_scroll_until || (view.precise_scroll_until != 0.0 && scrolling) {
+ if scrolling {
+ // Keep hiding egui's unprocessed copy until it has drained. The short rolling grace
+ // avoids a delayed duplicate without prolonging suppression after the tail is gone.
+ view.precise_scroll_until = view.precise_scroll_until.max(now + SUPPRESS_TAIL_SECS);
+ }
+ ui.input_mut(|i| i.smooth_scroll_delta = Vec2::ZERO);
+ // The point path suppresses every eased wheel delta. Restore the line base through the
+ // same un-eased path as its surplus; paging-owned axes were cleared above.
+ boost_extra = crate::wheel_boost::cap_frame(boost_extra + line_base);
+ if has_page {
+ // Page units normally stay on egui's viewport-sized path. During suppression only,
+ // reproduce the current event directly so an older hidden tail stays hidden.
+ let page_scale = ui.input(|i| i.viewport_rect().height());
+ let mut page_delta =
+ if page_scale.is_finite() && page_scale > 0.0 { crate::wheel_boost::cap_frame(input.page * page_scale) } else { Vec2::ZERO };
+ if paging_owns_vertical {
+ page_delta.y = 0.0;
+ }
+ boost_extra = crate::wheel_boost::cap_frame(boost_extra + page_delta);
+ }
+ } else {
+ precise_scroll = Vec2::ZERO;
+ // Selection handling below uses zero to distinguish an inactive window. Clearing a past
+ // deadline also keeps a later line/page action from being mistaken for the old tail.
+ view.precise_scroll_until = 0.0;
+ }
+ if has_page && paging_owns_vertical {
+ // Page input belongs to egui on the free axis; the pager still owns vertical motion.
+ ui.input_mut(|i| i.smooth_scroll_delta.y = 0.0);
+ }
+ // Touchpad momentum (#531): a swipe over the page lifted at speed glides on and slows to a
+ // stop, through the same un-eased path. Never while the pager owns the wheel, a gesture or
+ // dialog has the input, or animations are off; any click, key, zoom or other scrolling ends it.
+ // Asked of the preference, not of egui's animation time, which test harnesses zero.
+ let animates = app.animation_effects.animates(app.motion.reduced);
+ let may_glide = !paging_owns_vertical && !middle_gesture && navigation_enabled && unobstructed && animates;
+ let over_page = ui.rect_contains_pointer(avail);
+ ui.input(|i| view.fling.read(&i.events, now, may_glide && over_page));
+ let interrupted = glide_interrupted(ui);
+ if !may_glide || interrupted || key_scroll != 0.0 || auto_delta != Vec2::ZERO || zoom_delta != 1.0 {
+ view.fling.stop();
+ }
+ let glide = view.fling.step(now);
+ if view.fling.gliding() {
+ ui.ctx().request_repaint();
+ }
+ // Any reader-owned motion ends automatic search following, even when it stays on the same
+ // page: the wheel, keyboard, middle-button auto-scroll, a drawing's edge scroll, or the
+ // momentum left by a touchpad swipe. The automatic flash uses `goto`, not these deltas, so
+ // its programmatic scroll is never mistaken for a reader action.
+ let wheel_scrolled = precise_scroll != Vec2::ZERO || line_base != Vec2::ZERO || boost_extra != Vec2::ZERO || has_page;
+ if wheel_scrolled || auto_delta != Vec2::ZERO || edge_delta != Vec2::ZERO || glide != Vec2::ZERO {
+ view.end_find_following();
+ }
+ // The wheel may have turned the page above: draw the row it turned to. Measured from the old
+ // row, the jump to the new page scrolled both out of view, a blank frame on every turn forward.
+ let row = shown_row(view);
+ let visible_pages: Vec<usize> = if view.continuous { (0..rects.len()).collect() } else { row.clone() };
+ let (y_shift, content_h) = if view.continuous {
+ (0.0, rects.iter().map(|r| r.bottom()).reduce(f32::max).map(|bottom| bottom + MARGIN).unwrap_or(0.0))
+ } else {
+ // Only the current row scrolls into view; the content is its bounding box plus margins.
+ match row.iter().filter_map(|&i| rects.get(i)).copied().reduce(Rect::union) {
+ Some(r) => (r.top() - MARGIN, r.height() + 2.0 * MARGIN),
+ None => (0.0, 0.0),
+ }
+ };
+
+ let mut scroll = egui::ScrollArea::both().auto_shrink([false, false]).scroll_source(egui::scroll_area::ScrollSource {
+ drag: if middle_gesture {
+ egui::scroll_area::DragScroll::Never
+ } else if app.quick_tool == QuickTool::Hand {
+ egui::scroll_area::DragScroll::Always
+ } else {
+ egui::scroll_area::DragScroll::OnTouch
+ },
+ ..Default::default()
+ });
+ // Each document keeps its own scroll position when switching tabs (#189).
+ scroll = scroll.id_salt(("page-view", view.id));
+ // When a page jump or programmatic reposition occurs, or in non-continuous page display
+ // where single-page wheel turns jump to the page edge, disable animation so egui's
+ // queued target does not overwrite or ease the jump. For continuous page scrolling,
+ // animate if motion effects are enabled.
+ let has_jump = !view.shown
+ || edge_turned
+ || view.goto.is_some()
+ || view.goto_point.is_some()
+ || view.zoom_anchor.is_some()
+ || view.sync_scroll.is_some()
+ || (app.quick_tool == QuickTool::Hand && !middle_gesture && view.page_widget.is_some_and(|id| ui.ctx().is_being_dragged(id)));
+ scroll = scroll.animated(view.continuous && animates && !has_jump);
+ // A newly opened document starts at the top. eframe saves egui's memory with the settings
+ // and document ids start again at 1 every launch, so the offset stored under this id can be
+ // where an earlier session left another document.
+ if !std::mem::replace(&mut view.shown, true) {
+ scroll = scroll.scroll_offset(Vec2::ZERO);
+ }
+ // The Hand tool pans here, before the pages are laid out, so the page moves with the pointer
+ // in the frame the pointer moves (#924). Scrolling by the drag from inside the area moved the
+ // page only after that frame was drawn, a frame behind. The frame egui tells the drag from a
+ // click, the page catches up with all the pointer has moved since the press. A jump asked for
+ // below still wins.
+ if app.quick_tool == QuickTool::Hand
+ && !middle_gesture
+ && let Some(id) = view.page_widget.filter(|id| ui.ctx().is_being_dragged(*id))
+ {
+ let moved = if ui.ctx().drag_started_id() == Some(id) {
+ ui.input(|i| i.pointer.total_drag_delta()).unwrap_or(Vec2::ZERO)
+ } else {
+ ui.input(|i| i.pointer.delta())
+ };
+ if moved != Vec2::ZERO {
+ view.end_find_following();
+ }
+ // Within the content, as egui keeps it: past an end the page would show there for a
+ // frame and spring back. `max` is never NaN or below zero, so the clamp can't panic.
+ let max = vec2((content_w - avail.width()).max(0.0), (content_h - avail.height()).max(0.0));
+ scroll = scroll.scroll_offset((view.last_scroll - moved).clamp(Vec2::ZERO, max));
+ }
+ if let Some(v) = view.sync_scroll.take() {
+ scroll = scroll.scroll_offset(v);
+ }
+ if let Some((page, fx, fy, rel)) = view.zoom_anchor.take() {
+ let r = rects[page.min(rects.len() - 1)];
+ let point = pos2(r.left() + fx * r.width(), r.top() - y_shift + fy * r.height());
+ scroll = scroll.scroll_offset(anchored_scroll(point, rel, vec2(content_w, content_h), avail.size()));
+ } else if let Some((page, frac)) = view.goto.take() {
+ let page = page.min(rects.len() - 1);
+ let r = rects[page];
+ // Clamped here: egui clamps only after drawing, so a page that fits was drawn MARGIN - page_gap()
+ // too high for a frame and then hopped into place. (`avail` is the viewport, as the
+ // scroll bars float.)
+ let max_y = (content_h - avail.height()).max(0.0);
+ scroll = scroll.vertical_scroll_offset((r.top() - y_shift - view.page_gap() + frac * r.height()).max(0.0).min(max_y));
+ // Horizontally too, as Acrobat does (#2665): beside a much wider page the others sit off
+ // to one side. A page already shown whole, or one filling the window's width, keeps the
+ // scroll, so paging through a zoomed-in document stays on the same column. Otherwise a
+ // page that fits is centred, and a wider one scrolled just far enough to fill the window.
+ // The page counts with its side gutters, which keep its edge clear of the floating
+ // quick-action bar as the layout does.
+ let (x, w) = (view.last_scroll.x, avail.width());
+ let (left, right) = (r.left() - SIDE, r.right() + SIDE);
+ let target = if right - left <= w { if left >= x && right <= x + w { x } else { r.center().x - w / 2.0 } } else { x.clamp(left, right - w) };
+ if (target - x).abs() > 0.5 {
+ scroll = scroll.horizontal_scroll_offset(target.clamp(0.0, (content_w - w).max(0.0)));
+ }
+ }
+ let ppp = ui.ctx().pixels_per_point();
+ let scale = view.render_scale(ppp);
+ let tag = scale_tag(scale);
+ // Hold sharp re-renders while the zoom is still moving: a new scale every frame would
+ // cancel the in-flight full-page interpret and restart it, so on a heavy page (a CAD
+ // plot with ~1000 images renders for seconds) the sharp raster never arrives and the
+ // view looks stuck on a soft image. The stale raster stays stretched meanwhile; the
+ // sharp request goes out once the zoom settles.
+ let now_scale = ui.input(|i| i.time);
+ if (scale - view.last_scale).abs() > f32::EPSILON {
+ view.last_scale = scale;
+ view.sharp_hold_until = now_scale + 0.35;
+ ui.ctx().request_repaint_after(std::time::Duration::from_millis(380));
+ }
+ let sharp_held = now_scale < view.sharp_hold_until;
+ view.current_scale_tag = tag;
+ let hand = app.quick_tool == QuickTool::Hand;
+ let tool = app.quick_tool;
+ // Text selection runs for the Select tool and for the markup tools (highlight…).
+ let selects_text = match tool {
+ QuickTool::Comment(t) => t.markup().is_some() || t == comments::CommentTool::ReplaceText,
+ QuickTool::Select => !preparing,
+ QuickTool::Redact | QuickTool::ColumnSelect => true,
+ QuickTool::Hand
+ | QuickTool::Measure(_)
+ | QuickTool::Crop
+ | QuickTool::EnhanceCamera
+ | QuickTool::Fill(_)
+ | QuickTool::Field(_)
+ | QuickTool::AddText
+ | QuickTool::EditText
+ | QuickTool::Stamp(_)
+ | QuickTool::CustomStamp(_)
+ | QuickTool::Link
+ | QuickTool::SignArea { .. }
+ | QuickTool::MarqueeZoom
+ | QuickTool::Snapshot => false,
+ };
+ let prefs = &app.comment_prefs;
+ let redact_mark = (app.redact_prefs.hover_fill, app.redact_prefs.opacity);
+ let units = app.units;
+ let allowed = doc.allows_annotation();
+ let can_copy = doc.allows_copying();
+ let mut copy_selected = false;
+ let comments_hidden = doc.comments_hidden();
+ let form = doc.form.clone();
+ let generation = doc.edit_generation();
+ let can_fill = doc.allows_form_filling();
+ let can_crop = doc.allows_assembly();
+ let mut open_boxes = false;
+ let signature = app.signature.clone();
+ let initials = app.initials.clone();
+ let mut open_initials = false;
+ let author = app.comment_prefs.author.clone();
+ let today = app.session.today();
+ // In Preferences ▸ Date format, or why it can't be stamped into the PDF.
+ let date_text = crate::date_text_for_pdf(&app.session);
+ let mut refused: Option<String> = None;
+ let by_line = app.session.stamp_by_line(&author);
+ let mut stamp_placed = false;
+ let mut image_action: Option<crate::edit_text_ui::ImageAction> = None;
+ let custom_stamp = match app.quick_tool {
+ QuickTool::CustomStamp(i) => app.custom_stamps.get(i).cloned(),
+ _ => None,
+ };
+ let mut open_signature = false;
+ let mut hover_text: Option<(Pos2, String)> = None;
+ let mut badge_hover: Option<(Pos2, String)> = None;
+ let mut clicked_link: Option<LinkTarget> = None;
+ let mut remote_open: Option<(pdfcraft_engine::DocId, String, pdfcraft_render::RemoteDestination)> = None;
+ let mut canvas_action: Option<comments::CanvasAction> = None;
+ let mut page_action: Option<PageMenuAction> = None;
+ let mut field_menu: Option<FieldMenu> = None;
+ let mut open_props: Option<(usize, usize)> = None;
+ let mut field_props = false;
+ let mut field_placed = false;
+ let mut open_table: Option<(usize, [f64; 4])> = None;
+ // The table being set up in its window, shown on its own document's page.
+ let table_preview = app.field_table_draft.as_mut().filter(|d| d.doc == view.id).and_then(|d| Some(d.preview(info.pages.get(d.page)?, &form)));
+ let can_modify = doc.allows_modification();
+ if preparing {
+ crate::prepare::after_refresh(view, &form);
+ } else {
+ view.prepare.selected = None;
+ }
+ view.objects.prepare(doc, tool == QuickTool::EditText && can_modify, ui.ctx());
+ view.text_background.prepare(ui.ctx(), doc, view.line_editor.as_ref(), view.content.draft.as_ref(), scale);
+ let added = if editing_content { doc.added().to_vec() } else { Vec::new() };
+ let doc_links = if tool == QuickTool::Link { doc.links().to_vec() } else { Vec::new() };
+ if editing_content {
+ crate::content_ui::after_refresh(view, &added);
+ } else {
+ view.content.selected = None;
+ }
+ view.move_background.prepare(ui.ctx(), doc, &view.content, scale);
+
+ // A destination's position (bookmarks, links) refines `goto`: its point at the window's
+ // top-left, or the centre of a /FitR rectangle at the window's centre.
+ if let Some((page, fx, fy, rel)) = view.goto_point.take() {
+ let r = rects[page.min(rects.len() - 1)];
+ // Within the content, so an unreachable point never shows a frame scrolled past the end.
+ let (max_x, max_y) = ((content_w - avail.width()).max(0.0), (content_h - avail.height()).max(0.0));
+ if let Some(fx) = fx {
+ scroll = scroll.horizontal_scroll_offset((r.left() + fx * r.width() - rel.x).clamp(0.0, max_x));
+ }
+ if let Some(fy) = fy {
+ scroll = scroll.vertical_scroll_offset((r.top() - y_shift + fy * r.height() - rel.y).clamp(0.0, max_y));
+ }
+ }
+ let selection_wheel = view.selection_drag && navigation_enabled && unobstructed && !single_paging && ui.rect_contains_pointer(avail);
+ let out = page_scroll(ui, scroll, egui::Id::unique(("page-view-scope", view.id)), |ui, viewport| {
+ // egui's drag responses accept every pointer button. Keep a wheel gesture from also
+ // selecting text, drawing a mark, or panning with the Hand tool.
+ if middle_gesture {
+ let opacity = ui.opacity();
+ ui.disable();
+ // Only interactions pause; the document must keep its original colours.
+ ui.set_opacity(opacity);
+ }
+ // Middle-button auto-scroll, the keyboard, precise touchpad input (#759) and its glide
+ // (#531), accelerated wheel surplus (#1072), and a drawing's edge scroll; positive y
+ // moves the content down. All scroll without easing, unlike egui's wheel default.
+ // ScrollArea ignores wheel input during a widget drag. Defer the wheel contribution
+ // until after the text widgets when a selection owns that drag.
+ let wheel_delta = if selection_wheel { Vec2::ZERO } else { precise_scroll + boost_extra };
+ let delta = auto_delta + edge_delta - vec2(0.0, key_scroll) + wheel_delta + glide;
+ if delta != Vec2::ZERO && delta.is_finite() {
+ let anim = if animates && key_scroll != 0.0 { ui.style().scroll_animation } else { egui::style::ScrollAnimation::none() };
+ ui.scroll_with_delta_animation(delta, anim);
+ }
+ let (resp_rect, resp) = ui.allocate_exact_size(vec2(content_w, content_h), Sense::click_and_drag());
+ view.page_widget = Some(resp.id);
+ // A drag lasts only while egui reports it, so the mark can't outlive one.
+ if !resp.dragged_by(egui::PointerButton::Primary) {
+ view.selection_drag = false;
+ }
+ // The Hand tool pans by this widget's drag, before the pages are laid out (above).
+ if hand {
+ if resp.dragged() {
+ ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing);
+ } else if resp.hovered() {
+ ui.ctx().set_cursor_icon(egui::CursorIcon::Grab);
+ }
+ }
+ let origin = resp_rect.min - vec2(0.0, y_shift);
+ let painter = ui.painter();
+ let visible = viewport.translate(resp_rect.min.to_vec2());
+ let mut wanted = Vec::new();
+ let mut visible_now = Vec::new();
+ view.screen_rects.clear();
+ view.screen_xforms.clear();
+ for &i in &visible_pages {
+ let r = snap_to_pixels(rects[i].translate(origin.to_vec2()), ppp);
+ if r.intersects(visible) {
+ 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) }));
+ }
+ }
+ // Visible heights (points) closer than this are equal: one page size can meet the
+ // viewport a fraction of a point differently once the scroll offset is applied.
+ const TIE: f32 = 0.5;
+ let mut current = view.current;
+ let mut best_overlap = -1.0f32;
+ let mut current_overlap = -1.0f32;
+ let mut current_height = f32::INFINITY;
+ // The pointer as the pages see it: nothing over them (a dialog from the frame it opens),
+ // or a press they hold. The page modules read it rather than egui's raw pointer state.
+ let ptr = PagePointer::read(ui, &resp, modal);
+ let pointer = ptr.pos;
+ // A press on a page makes it the current one (as in Acrobat), so a page command with
+ // no selection (Rotate, Delete) acts on the page the reader pointed at, not on a page
+ // gone to earlier that still shows whole beside it.
+ let pressed = unobstructed && ptr.pressed().is_some();
+ let mut pressed_page = None;
+ if resp.secondary_clicked() {
+ // Set again below when the right-click lands on a link.
+ view.links.context = None;
+ let mut over_image = false;
+ if tool == QuickTool::EditText {
+ let pointer_pos = ptr.pos;
+ if let Some(p) = pointer_pos {
+ for (page_idx, xf) in &view.screen_xforms {
+ let images = doc.page_images(*page_idx);
+ for (idx, img) in images.iter().enumerate().rev() {
+ let obb = ImageObb::from_image(img, xf, info, *page_idx);
+ let b = image_screen_rect(img, xf, info, *page_idx);
+ if (b.is_positive() && b.contains(p)) || crate::edit_text_ui::quad_contains(obb.corners(), p) {
+ over_image = true;
+ if view.image_selection.as_ref().is_none_or(|s| s.page != *page_idx || s.index != idx) {
+ view.image_selection = Some(crate::edit_text_ui::ImageSelection {
+ page: *page_idx,
+ index: idx,
+ drag: None,
+ crop: None,
+ crop_mode: false,
+ crop_rect: None,
+ turning: false,
+ settled: None,
+ });
+ }
+ break;
+ }
+ }
+ if over_image {
+ break;
+ }
+ }
+ }
+ }
+ ui.ctx().data_mut(|d| d.insert_persisted(crate::edit_text_ui::image_menu_id(), over_image));
+ }
+ let mut calc_hover = None;
+ for &i in &visible_pages {
+ badge_hover = None;
+ let r = snap_to_pixels(rects[i].translate(origin.to_vec2()), ppp);
+ if !r.intersects(visible.expand(400.0)) {
+ continue;
+ }
+ if pressed && pressed_page.is_none() && pointer.is_some_and(|p| r.contains(p)) {
+ pressed_page = Some(i);
+ }
+ if r.intersects(visible) {
+ visible_now.push(i);
+ }
+ let overlap = r.intersect(visible).height();
+ if i == view.current {
+ current_overlap = overlap;
+ current_height = r.height();
+ }
+ // Pages shown equally (two rows wholly on screen) differ only by rounding: the
+ // topmost one counts.
+ if overlap > best_overlap + TIE {
+ best_overlap = overlap;
+ current = i;
+ }
+ let xf = PageXform { rect: r, rot: view.rotation, pw: info.pages[i].width.max(1.0), ph: info.pages[i].height.max(1.0) };
+ // Shadows would darken the preceding page when pages touch.
+ if view.show_page_gaps {
+ painter.add(egui::epaint::Shadow { offset: [0, 3], blur: 14, spread: 0, color: t.page_shadow }.as_shape(r, CornerRadius::ZERO));
+ }
+ painter.rect_filled(r, CornerRadius::ZERO, paper);
+ if let Some(err) = view.errors.get(&i) {
+ painter.rect_filled(r, CornerRadius::ZERO, Color32::from_rgb(0xFB, 0xF4, 0xF4));
+ icons::paint(
+ ui,
+ Rect::from_center_size(r.center() - vec2(0.0, 26.0), vec2(28.0, 28.0)),
+ "triangle-alert",
+ 26.0,
+ Color32::from_rgb(0xC8, 0x3A, 0x3A),
+ );
+ let message = crate::i18n::fmt(tl!("This page couldn't be displayed.\n{e}"), &[("e", err)]);
+ let msg =
+ ui.fonts_mut(|f| f.layout(message, theme::regular(12.5), Color32::from_rgb(0x6A, 0x2A, 0x2A), (r.width() - 40.0).max(80.0)));
+ painter.galley(pos2(r.center().x - msg.size().x / 2.0, r.center().y), msg, Color32::BLACK);
+ } else {
+ let (pw_pt, ph_pt) = (info.pages[i].width.max(1.0), info.pages[i].height.max(1.0));
+ // A GPU may take smaller textures than these (OpenGL drivers report as little as
+ // 2048 pixels, and uploading a bigger one aborts), so both stay within its limit.
+ let max_side = ui.ctx().input(|inp| inp.max_texture_side) as f32;
+ let tiled = pw_pt.max(ph_pt) * scale > TILE_THRESHOLD.min(max_side);
+ // Whole-page raster: sharp when small, a low-res backdrop when tiled.
+ let (want_scale, want_tag) = if tiled {
+ let bs = BASE_SIDE.min(max_side) / pw_pt.max(ph_pt);
+ (bs, scale_tag(bs))
+ } else {
+ (scale, tag)
+ };
+ // Under tiles, a whole-page raster sharper than the backdrop (from before the page
+ // grew past the tiling size) is a better backdrop: keep demanding it as it is.
+ match view.pages.get(&i).filter(|p| tiled && p.tag != STALE_TAG && tag_scale(p.tag) >= want_scale) {
+ Some(p) => wanted.push((i, tag_scale(p.tag), p.tag, None)),
+ None => wanted.push((i, want_scale, want_tag, None)),
+ }
+ let active_drag_suppress = if let Some(sel) = view.image_selection.as_ref()
+ && sel.page == i
+ && sel.drag.is_some()
+ {
+ let images = doc.page_images(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) {
+ // 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;
+ }
+ 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,
+ );
+ }
+ }
+ }
+ }
+ view.text_background.paint(painter, &xf, i, view.line_editor.as_ref(), view.content.draft.as_ref());
+ if editing_content {
+ view.move_background.paint(painter, &xf, i, info, &view.content, pointer);
+ }
+ if view.show_page_gaps {
+ painter.rect_stroke(r, CornerRadius::ZERO, Stroke::new(0.5, t.border.gamma_multiply(0.8)), egui::StrokeKind::Outside);
+ }
+
+ // Comments: tools, selection, moving and resizing come before text selection.
+ let pcx = comments::PageCx { page: i, xf: &xf, ptr: &ptr, info, tool, prefs, allowed, hidden: comments_hidden, redact_mark };
+ if let QuickTool::Measure(measure_tool) = tool {
+ crate::measure_ui::page_input(ui, &resp, doc, view, &pcx, measure_tool, units);
+ }
+
+ // Form fields take clicks first with the Select tool (as Acrobat fills fields in
+ // every viewing mode); then comments; then text selection.
+ if let QuickTool::Stamp(kind) = tool
+ && allowed
+ && let Some(p) = ptr.within(xf.rect)
+ {
+ ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair);
+ if resp.clicked() {
+ // Centred on the click, upright as the page is shown.
+ let (vx, vy) = xf.screen_to_view(p);
+ let (w, h) = kind.size();
+ let corners = [(vx as f64 - w / 2.0, vy as f64 - h / 2.0), (vx as f64 + w / 2.0, vy as f64 + h / 2.0)];
+ let u: Vec<[f32; 2]> = corners.iter().map(|(x, y)| info.pages[i].view_to_user(*x as f32, *y as f32)).collect();
+ let rect = [u[0][0].min(u[1][0]) as f64, u[0][1].min(u[1][1]) as f64, u[0][0].max(u[1][0]) as f64, u[0][1].max(u[1][1]) as f64];
+ let by = (kind.group() == pdfcraft_engine::StampGroup::Dynamic).then(|| by_line.clone());
+ let shape = pdfcraft_engine::Shape::Stamp { rect, stamp: kind, by };
+ view.pending_edit = Some(pdfcraft_engine::Edit::AddAnnotation(pdfcraft_engine::NewAnnotation {
+ page: i,
+ style: pdfcraft_engine::Style::default_for(&shape),
+ shape,
+ contents: String::new(),
+ author: author.clone(),
+ }));
+ stamp_placed = true;
+ }
+ }
+ if let Some(cs) = custom_stamp.as_ref()
+ && allowed
+ && let Some(p) = ptr.within(xf.rect)
+ {
+ ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair);
+ if resp.clicked() {
+ // Centred on the click at its natural size (the engine sizes it).
+ let (vx, vy) = xf.screen_to_view(p);
+ let u = info.pages[i].view_to_user(vx, vy);
+ let (x, y) = (u[0] as f64, u[1] as f64);
+ view.pending_edit = Some(pdfcraft_engine::Edit::AddCustomStamp {
+ page: i,
+ rect: [x, y, x, y],
+ name: cs.name.clone(),
+ file: pdfcraft_engine::MarkFile { name: cs.file.clone(), bytes: cs.data.clone(), page: cs.page },
+ author: author.clone(),
+ });
+ stamp_placed = true;
+ }
+ }
+ // Over a mark already placed, the Fill & Sign tool picks it up (comments, below).
+ if let QuickTool::Fill(ft) = tool
+ && allowed
+ && !comments::fill_grabs(&pcx, view)
+ {
+ match crate::fill_sign::page_input(
+ ui,
+ &resp,
+ &xf,
+ &ptr,
+ i,
+ info,
+ ft,
+ app.fill_text_size,
+ view,
+ signature.as_ref(),
+ initials.as_ref(),
+ &mut app.signature_preview,
+ &author,
+ &date_text,
+ ) {
+ Some(crate::fill_sign::FillAction::Edit(e)) => view.pending_edit = Some(*e),
+ Some(crate::fill_sign::FillAction::Signature(e)) => {
+ view.pending_edit = Some(*e);
+ view.fill_signature_page = Some(i);
+ }
+ Some(crate::fill_sign::FillAction::CreateSignature) => open_signature = true,
+ Some(crate::fill_sign::FillAction::CreateInitials) => open_initials = true,
+ Some(crate::fill_sign::FillAction::Refused(why)) => refused = Some(why),
+ None => {}
+ }
+ }
+ if matches!(tool, QuickTool::SignArea { .. }) {
+ crate::sign_ui::page_input(ui, &resp, &xf, &ptr, i, info, view);
+ }
+ if matches!(tool, QuickTool::MarqueeZoom | QuickTool::Snapshot) {
+ crate::zoom_snap::page_input(ui, &resp, &xf, &ptr, i, view);
+ }
+ if tool == QuickTool::EnhanceCamera {
+ crate::camera_ui::page_input(ui, &resp, &xf, &ptr, i, view, can_modify);
+ }
+ if tool == QuickTool::Crop && crate::crop::page_input(ui, &resp, &xf, &ptr, i, info, view, can_crop) {
+ view.current = i;
+ open_boxes = true;
+ }
+ // `over_field`: a form field is under the pointer and has set its cursor.
+ let (on_field, over_field) = if preparing {
+ let field_tool = match tool {
+ QuickTool::Field(f) => Some(f),
+ _ => None,
+ };
+ // While a table is being set up, nothing else is drawn or moved.
+ let allowed = can_modify && table_preview.is_none() && open_table.is_none();
+ let o = crate::prepare::page_input(ui, &resp, &xf, &ptr, i, info, &form, field_tool, allowed, view);
+ field_props |= o.properties;
+ field_placed |= o.placed;
+ open_table = open_table.or(o.table);
+ (o.consumed || field_tool.is_some(), false)
+ } else {
+ use crate::forms_ui::FieldPointer;
+ let field = if tool == QuickTool::Select
+ && !(editing_content && can_modify && crate::content_ui::select_grabs(&xf, &ptr, i, info, &added, view))
+ && !comments::select_grabs(&pcx, view)
+ {
+ crate::forms_ui::page_input(ui, &resp, &xf, &ptr, i, info, &form, can_fill, view)
+ } else {
+ FieldPointer::Away
+ };
+ (field == FieldPointer::Owned, field == FieldPointer::Over)
+ };
+ // Redact draws boxes off text; so does Highlight (an area highlight, as in Acrobat).
+ let area_tool = tool == QuickTool::Redact && can_modify || tool == QuickTool::Comment(comments::CommentTool::Highlight) && allowed;
+ let boxing = area_tool && {
+ let text = view.page_text(i);
+ let over_text = |p: Pos2| {
+ let (vx, vy) = xf.screen_to_view(p);
+ text.as_ref().is_some_and(|t| t.glyphs.iter().any(|g| vx >= g.rect[0] && vx <= g.rect[2] && vy >= g.rect[1] && vy <= g.rect[3]))
+ };
+ crate::redact_ui::page_input(ui, &resp, &xf, &ptr, i, info, over_text, view)
+ };
+ let image_owns_pointer = tool == QuickTool::EditText && crate::edit_text_ui::image_owns_pointer(ui, &xf, &ptr, i, info, view);
+ let on_objects =
+ !image_owns_pointer && tool == QuickTool::EditText && can_modify && crate::object_ui::page_input(ui, &resp, &xf, &ptr, i, doc, view);
+ let lines = if matches!(tool, QuickTool::AddText | QuickTool::EditText) && can_modify {
+ let generation = doc.edit_generation();
+ match view.edit_lines.get(&i) {
+ Some((g, l)) if *g == generation => l.clone(),
+ _ => {
+ let l = doc.text_blocks(i);
+ view.edit_lines.insert(i, (generation, l.clone()));
+ l
+ }
+ }
+ } else {
+ Vec::new()
+ };
+ let over_source = tool == QuickTool::AddText
+ && pointer.is_some_and(|p| {
+ !crate::content_ui::hits_added(&xf, info, i, &added, p)
+ && lines.iter().any(|line| xf.user_rect(info, i, line.rect.map(|v| v as f32)).expand(2.0).contains(p))
+ });
+ let source_blocked = over_source && view.content.hold_blocked();
+ if over_source && resp.clicked() && !source_blocked {
+ if let Some(edit) = view.content.finish_draft(&added) {
+ view.pending_edit = Some(edit);
+ }
+ view.content.selected = None;
+ }
+ let on_content = !on_objects && editing_content && can_modify && {
+ source_blocked
+ || crate::content_ui::page_input(
+ ui,
+ &resp,
+ &xf,
+ &ptr,
+ i,
+ info,
+ &added,
+ tool == QuickTool::AddText && !over_source,
+ matches!(tool, QuickTool::AddText | QuickTool::EditText),
+ &text_style,
+ view,
+ )
+ || tool == QuickTool::AddText && !over_source
+ };
+ // Added content owns its gesture; its source text must not queue a second edit.
+ // Edit text & images boxes every paragraph and image whenever the tool is on. Only the
+ // input waits while selected objects or added content own the pointer, or while page
+ // input is blocked (another tab, a dialog, the window unfocused): the boxes stay drawn
+ // instead of vanishing until the pointer comes back.
+ let others_own_pointer = on_objects || on_content;
+ let on_edit_text = (tool == QuickTool::EditText || over_source) && can_modify && {
+ let generation = doc.edit_generation();
+ let images = match view.edit_images.get(&i) {
+ Some((g, l)) if *g == generation => l.clone(),
+ _ => {
+ let l = doc.page_images(i);
+ view.edit_images.insert(i, (generation, l.clone()));
+ l
+ }
+ };
+ // Editable text takes precedence over background/overlapping artwork. Both
+ // inventories are painted every frame, even when text owns the pointer.
+ let text_used =
+ crate::edit_text_ui::page_input(ui, &resp, &xf, &ptr, i, doc, &lines, view, !others_own_pointer && !image_owns_pointer);
+ let image_used = crate::edit_text_ui::image_input(
+ ui,
+ &resp,
+ &xf,
+ &ptr,
+ i,
+ info,
+ &images,
+ view,
+ &mut image_action,
+ !others_own_pointer && (image_owns_pointer || !text_used),
+ );
+ !others_own_pointer && (text_used || image_used)
+ };
+ let on_link = tool == QuickTool::Link && can_modify && crate::link_ui::page_input(ui, &resp, &xf, &ptr, i, info, &doc_links, view);
+ if tool == QuickTool::Select
+ && resp.secondary_clicked()
+ && can_modify
+ && let Some(p) = pointer.filter(|p| xf.rect.contains(*p))
+ && let Some(l) = doc.links().iter().find(|l| l.page == i && crate::link_ui::screen_rect(&xf, info, i, l.rect).expand(2.0).contains(p))
+ {
+ view.links.context = Some((i, l.index));
+ }
+ let consumed = on_objects || on_edit_text || on_link || on_content || boxing || on_field || comments::page_input(ui, &resp, &pcx, view);
+
+ let preview_target =
+ (matches!(tool, QuickTool::Select | QuickTool::Fill(_)) && !comments_hidden).then_some(view.comments.selected).flatten();
+ view.signature_drag.prepare(ui.ctx(), doc, preview_target, scale);
+ view.signature_drag.paint(painter, &pcx, &view.comments, view.pending_edit.as_ref());
+
+ // Any press on the page ends Select All of the document: text read or not, any tool,
+ // on a link too.
+ // A press that lands on something drawn over the page (a menu, a dialog) is not one.
+ if view.all_text && pressed_page == Some(i) {
+ view.all_text = false;
+ }
+ // Text layer: find matches, selection, I-beam and drag-to-select.
+ let to_screen = |g: [f32; 4]| xf.view_rect(g);
+ if let Some(text) = view.texts.get(&i).cloned() {
+ if let Some(f) = &view.find {
+ for (k, (mp, range)) in f.matches.iter().enumerate() {
+ if *mp != i {
+ continue;
+ }
+ let current = f.current == Some(k);
+ for lr in text.line_rects(range.clone()) {
+ let fill = if current {
+ Color32::from_rgba_unmultiplied(255, 140, 0, 110)
+ } else {
+ Color32::from_rgba_unmultiplied(255, 214, 0, 90)
+ };
+ painter.rect_filled(to_screen(lr).expand(1.0), CornerRadius::same(2), fill);
+ }
+ }
+ }
+ if view.all_text {
+ for lr in text.line_rects(0..text.glyphs.len()) {
+ painter.rect_filled(to_screen(lr), CornerRadius::same(1), Color32::from_rgba_unmultiplied(0x3A, 0x7B, 0xF0, 70));
+ }
+ }
+ if let Some(sel) = view.selection.filter(|s| s.page == i) {
+ for lr in sel.rects(&text) {
+ painter.rect_filled(to_screen(lr), CornerRadius::same(1), Color32::from_rgba_unmultiplied(0x3A, 0x7B, 0xF0, 70));
+ }
+ // The rectangle being drawn, as Acrobat shows it while column-selecting.
+ if let Span::Column { rect } = sel.span
+ && resp.dragged()
+ {
+ let outline = Stroke::new(1.0, Color32::from_rgb(0x3A, 0x7B, 0xF0));
+ painter.rect_stroke(to_screen(rect), CornerRadius::ZERO, outline, egui::StrokeKind::Middle);
+ }
+ }
+ if selects_text
+ && !consumed
+ && let Some(p) = pointer.filter(|p| r.contains(*p))
+ {
+ let (vx, vy) = xf.screen_to_view(p);
+ let over_text = text.glyphs.iter().any(|g| vx >= g.rect[0] && vx <= g.rect[2] && vy >= g.rect[1] && vy <= g.rect[3]);
+ let over_link = info.links.iter().any(|l| l.page == i && xf.user_rect(info, i, l.rect).contains(p));
+ // Column select (#740): the Column select tool, or Alt (Option on macOS) held
+ // while a drag starts, as in Acrobat.
+ let column = tool == QuickTool::ColumnSelect || ui.input(|inp| inp.modifiers.alt);
+ // A link or a form field under the pointer keeps its own cursor: a check box
+ // drawn with a glyph, or set on printed text, shows the hand, not the I-beam.
+ // So do the mode bar and side panels over a page scrolled under them (#2755),
+ // unless a selection is being dragged there.
+ let cursor_free = !over_link && !over_field && (resp.contains_pointer() || resp.dragged());
+ if column && cursor_free {
+ ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair);
+ } else if over_text && cursor_free {
+ ui.ctx().set_cursor_icon(egui::CursorIcon::Text);
+ }
+ // The pages' press, kept when its release came in the same frame (#2100): it
+ // still starts multi-click selection.
+ let press_here = ptr.origin.is_some_and(|o| r.contains(o));
+ let pressed = ptr.pressed().is_some();
+ if pressed && press_here && !over_link {
+ let now = ui.input(|inp| inp.time);
+ // The same limits egui uses to count clicks on release.
+ let (max_delay, max_dist) = ui.ctx().options(|o| (o.input_options.max_double_click_delay, o.input_options.max_click_dist));
+ let is_consecutive =
+ now - view.last_press_time <= max_delay && view.last_press_pos.is_some_and(|pos| pos.distance(p) <= max_dist);
+ view.clicks = if is_consecutive { view.clicks.saturating_add(1) } else { 1 };
+ view.last_press_time = now;
+ view.last_press_pos = Some(p);
+
+ // Multi-click highlights immediately on pointer press instead of release (#1024).
+ let clicks = if view.clicks > 2 && tool != QuickTool::Select { 1 } else { view.clicks };
+ if clicks >= 2 && over_text {
+ let span = text.nearest(vx, vy).and_then(|a| click_unit(&text, clicks, a));
+ if let Some((first, last)) = span {
+ view.selection = Some(Selection::run(i, first, last));
+ }
+ }
+ }
+ if resp.drag_started() && press_here && !over_link {
+ // A drag replaces the selection without passing through none, so a
+ // re-drag over text whose bar Copy closed would keep the bar hidden.
+ view.actions_dismissed = None;
+ view.selection_drag = true;
+ let origin = ptr.origin.unwrap_or(p);
+ let (ox, oy) = xf.screen_to_view(origin);
+ if view.clicks < 2 {
+ view.selection = if column {
+ Some(Selection { page: i, span: Span::Column { rect: [ox, oy, vx, vy] } })
+ } else {
+ text.nearest(ox, oy).map(|a| Selection::run(i, a, a))
+ };
+ }
+ }
+ let clicks = if view.clicks > 2 && tool != QuickTool::Select { 1 } else { view.clicks };
+ if resp.dragged()
+ && let Some(sel) = view.selection.as_mut().filter(|s| s.page == i)
+ {
+ match &mut sel.span {
+ // After a multi-click the drag extends by its unit (#1685), as in
+ // Acrobat and browsers: whole words or lines, always keeping the one
+ // clicked, which holds the anchor whichever way the drag went.
+ Span::Run { anchor, head } if clicks >= 2 => {
+ if let Some(h) = text.nearest(vx, vy)
+ && let Some((first, last)) = click_unit(&text, clicks, *anchor)
+ {
+ let (to_first, to_last) = click_unit(&text, clicks, h).unwrap_or((h, h));
+ (*anchor, *head) = if to_first < first { (last, to_first) } else { (first, to_last.max(last)) };
+ }
+ }
+ Span::Run { head, .. } => {
+ if let Some(h) = text.nearest(vx, vy) {
+ *head = h;
+ }
+ }
+ Span::Column { rect } => {
+ rect[2] = vx;
+ rect[3] = vy;
+ }
+ }
+ }
+ // A rectangle around no text selects nothing.
+ if resp.drag_stopped()
+ && view.selection.is_some_and(|s| s.page == i && matches!(s.span, Span::Column { .. }) && s.text(&text).is_empty())
+ {
+ view.selection = None;
+ }
+ // Quick clicks widen the selection: two a word, three the line, four the page.
+ // Release-based fallback for platforms or synthetic events that report double_clicked.
+ let release_clicks = if resp.triple_clicked() {
+ view.clicks.max(2).saturating_add(1)
+ } else if resp.double_clicked() {
+ view.clicks.max(2)
+ } else {
+ 0
+ };
+ if release_clicks > 0 {
+ view.clicks = release_clicks;
+ }
+ let clicks = if view.clicks > 2 && tool != QuickTool::Select { 1 } else { view.clicks };
+ // Only on the frame egui reports the multi-click: `view.clicks` outlives it, and
+ // acting on every frame re-selected the word as soon as a selection was cleared
+ // (a highlight made by the double-click left its word selected).
+ if release_clicks > 0 && clicks >= 2 && over_text {
+ if view.selection.is_none() {
+ let span = text.nearest(vx, vy).and_then(|a| click_unit(&text, clicks, a));
+ if let Some((first, last)) = span {
+ view.selection = Some(Selection::run(i, first, last));
+ }
+ }
+ } else if resp.clicked() && view.clicks < 2 && !over_link {
+ // ⇧-click extends a selection on this page to the click, keeping its
+ // anchor (#527). Otherwise (no shift, no selection on this page, or a
+ // column selection, which has no anchor glyph; a selection cannot yet
+ // span pages) a click clears the selection.
+ let shift = ui.input(|inp| inp.modifiers.shift);
+ match (view.selection.as_mut().filter(|s| shift && s.page == i).map(|s| &mut s.span), text.nearest(vx, vy)) {
+ (Some(Span::Run { head, .. }), Some(h)) => *head = h,
+ _ => view.selection = None,
+ }
+ }
+ }
+ }
+
+ if tool == QuickTool::Select && !consumed {
+ crate::image_pick::page_input(&resp, &xf, i, info, doc, pointer, view);
+ }
+ crate::image_pick::drop_stale(doc, view);
+ crate::image_pick::paint(painter, &xf, i, info, view);
+ comments::page_after_text(&resp, &pcx, view);
+ if tool == QuickTool::Redact && can_modify {
+ crate::redact_ui::after_text(&resp, i, info, view);
+ }
+ if area_tool {
+ crate::redact_ui::paint(painter, i, view, pointer);
+ }
+ comments::paint_page(ui, painter, &pcx, view);
+ if editing_content {
+ crate::content_ui::paint_page(painter, &xf, i, info, &added, view, pointer);
+ }
+ if tool == QuickTool::EditText {
+ crate::object_ui::paint(painter, &xf, i, info, &view.objects);
+ }
+ if tool == QuickTool::EnhanceCamera {
+ crate::camera_ui::paint(painter, &xf, i, view);
+ }
+ if tool == QuickTool::Link {
+ crate::link_ui::paint(painter, &xf, i, info, &doc_links, view, pointer);
+ }
+ if preparing {
+ crate::prepare::paint_page(ui, painter, &xf, i, info, &form, view, pointer);
+ if let Some(preview) = &table_preview {
+ crate::field_table_ui::paint_preview(painter, &xf, i, preview);
+ }
+ if calc_order {
+ let selected = view.prepare.selected.as_ref().map(|(name, _)| name.as_str());
+ if let Some(name) =
+ crate::calc_order_ui::paint_page(painter, &xf, i, info, &form, &view.calc_order, generation, selected, pointer)
+ {
+ calc_hover = Some(name);
+ }
+ }
+ } else {
+ crate::forms_ui::paint_page(painter, &xf, i, info, &form, view, pointer);
+ }
+
+ // Form-field highlight (Acrobat's "Highlight existing fields"); required fields get a
+ // red border. Radio buttons and round XFA check boxes are round, and so is theirs (as
+ // in Acrobat). Only what can be filled is marked: a read-only widget (its field's, or a
+ // radio button's own) is left as it is drawn.
+ if view.highlight_fields {
+ for f in form.iter() {
+ let required = f.has(pdfcraft_engine::field_flags::REQUIRED);
+ for w in f.widgets.iter().filter(|w| w.page == Some(i) && !w.hidden && !w.read_only) {
+ let r = w.rect;
+ let sr = xf.user_rect(info, i, [r[0] as f32, r[1] as f32, r[2] as f32, r[3] as f32]);
+ let tint = Color32::from_rgba_unmultiplied(0x6E, 0x8E, 0xF5, 48);
+ let (width, color) =
+ if required { (2.0, Color32::from_rgb(0xE3, 0x22, 0x22)) } else { (1.0, Color32::from_rgb(0x6E, 0x8E, 0xF5)) };
+ if w.round {
+ let radius = sr.width().min(sr.height()) / 2.0;
+ painter.circle_filled(sr.center(), radius, tint);
+ painter.circle_stroke(sr.center(), radius - width / 2.0, Stroke::new(width, color));
+ } else {
+ painter.rect_filled(sr, CornerRadius::same(1), tint);
+ painter.rect_stroke(sr, CornerRadius::same(1), Stroke::new(width, color), egui::StrokeKind::Inside);
+ }
+ }
+ }
+ }
+ // Fill & Sign keeps its placement cursor clear of link/comment hover feedback. Tips
+ // draw above the palette, so none shows while it is open, even beside it.
+ if !matches!(tool, QuickTool::Fill(_))
+ && unobstructed
+ && let Some(p) = pointer
+ {
+ for l in info.links.iter().filter(|l| l.page == i) {
+ let sr = xf.user_rect(info, i, l.rect);
+ if sr.contains(p) {
+ ui.ctx().set_cursor_icon(egui::CursorIcon::PointingHand);
+ let label = match &l.target {
+ LinkTarget::Page(n, _) => {
+ crate::i18n::fmt(tl!("Go to page {p}"), &[("p", info.pages.get(*n).map(|p| p.label.as_str()).unwrap_or("?"))])
+ }
+ LinkTarget::Uri(u) => u.clone(),
+ LinkTarget::SetLayers { .. } => tl!("Set layer visibility").to_string(),
+ LinkTarget::RemoteGoTo { file, .. } => file.clone(),
+ LinkTarget::Other(s) => crate::i18n::fmt(tl!("{s} action"), &[("s", s)]),
+ };
+ hover_text = Some((p, label));
+ if resp.clicked() && tool == QuickTool::Select && !consumed {
+ clicked_link = Some(l.target.clone());
+ }
+ }
+ }
+ // Annotation hover shows the comment, as Acrobat's popups do; not while drawing
+ // freehand, where it would cover the next stroke (#429).
+ let freehand = matches!(tool, QuickTool::Comment(comments::CommentTool::Ink | comments::CommentTool::Eraser));
+ let gesturing = view.comments.gesture.is_some() || freehand;
+ // Inspection sorts annotations spatially, but the renderer paints in /Annots
+ // order. Keep the shared list intact and choose the last eligible raw index.
+ if hover_text.is_none()
+ && !gesturing
+ && let Some((_, text)) = info
+ .annotations
+ .iter()
+ .filter(|a| a.page == i)
+ .filter(|a| {
+ !(prefs.hide_empty_highlight_hover && a.subtype == "Highlight" && a.contents.as_deref().is_none_or(str::is_empty))
+ })
+ .filter(|a| pcx.screen_rects(a).any(|r| r.contains(p)))
+ .filter_map(|a| annotation_hover_text(a).map(|text| (a.index, text)))
+ .max_by_key(|(index, _)| *index)
+ {
+ hover_text = Some((p, text));
+ }
+ }
+ for (mp, mr, mc) in &view.compare_marks {
+ if *mp == i {
+ let sr = xf.user_rect(info, i, *mr).expand(1.5);
+ painter.rect_filled(sr, CornerRadius::same(2), mc.gamma_multiply(0.28));
+ }
+ }
+ if let Some((fp, fr, t0)) = view.flash
+ && fp == i
+ {
+ let now = ui.input(|inp| inp.time);
+ let t0 = if t0 == 0.0 { now } else { t0 };
+ view.flash = Some((fp, fr, t0));
+ let age = (now - t0) as f32;
+ if age < 1.6 {
+ let a = ((1.6 - age) / 1.6 * 255.0) as u8;
+ let sr = xf.user_rect(info, i, fr).expand(4.0);
+ painter.rect_stroke(
+ sr,
+ CornerRadius::same(3),
+ Stroke::new(2.5, Color32::from_rgba_unmultiplied(0x1B, 0x63, 0xE0, a)),
+ egui::StrokeKind::Outside,
+ );
+ ui.ctx().request_repaint();
+ } else {
+ view.flash = None;
+ }
+ }
+ // Validation is viewer chrome over the signer's original artwork, which
+ // may still say "Signature Not Verified". These badges never enter document
+ // streams, image/text exports, vector printing or Print as Image.
+ for badge in signature_badges(&doc.signatures, i) {
+ let [x0, y0, x1, y1] = badge.rect;
+ let sr = xf.user_rect(info, i, [x0 as f32, y0 as f32, x1 as f32, y1 as f32]);
+ let (icon, color) = crate::sign_ui::signature_status_style(badge.status);
+ painter.rect_stroke(sr, CornerRadius::same(2), Stroke::new(1.5, color), egui::StrokeKind::Outside);
+ // A widget too small for the mark keeps its outline: the verdict still shows.
+ if sr.width() < 4.0 || sr.height() < 4.0 {
+ continue;
+ }
+ // Big enough to read at a glance, small enough to leave the signer's own
+ // text visible around it.
+ let side = (sr.width().min(sr.height()) * 0.8).clamp(24.0, 192.0);
+ let mark = Rect::from_center_size(sr.center(), vec2(side, side));
+ icons::paint(ui, mark, icon, side * 0.64, color);
+ if let Some(p) = pointer.filter(|p| mark.expand(2.0).contains(*p)) {
+ badge_hover = Some((p, badge.summary.to_string()));
+ }
+ }
+ // Overlapping widgets paint in order, so the topmost badge owns the hover; an
+ // earlier link or annotation hover still wins over any badge.
+ if hover_text.is_none() {
+ hover_text = badge_hover.take();
+ }
+ }
+ 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);
+ }
+ // ScrollArea ignores the wheel while any widget is dragged, so a text-selection drag
+ // scrolls the page itself (#721). After the page loop, so it keeps scrolling once the
+ // pointer leaves the selection's page for the gap or the next page; over the whole
+ // document area, like #759. Combine direct and smoothed motion in one request so mixed
+ // Point and Line events retain their full contribution.
+ if selection_wheel {
+ let smooth =
+ if view.precise_scroll_until == 0.0 { ui.input_mut(|input| std::mem::take(&mut input.smooth_scroll_delta)) } else { Vec2::ZERO };
+ let delta = precise_scroll + boost_extra + smooth;
+ if delta != Vec2::ZERO && delta.is_finite() {
+ ui.scroll_with_delta_animation(delta, egui::style::ScrollAnimation::none());
+ }
+ }
+ // Held at the top or bottom edge, or dragged past it, a text selection scrolls the view
+ // so it can reach text off screen (#1670); the selection follows the pointer on its page.
+ if view.selection_drag
+ && navigation_enabled
+ && unobstructed
+ && !single_paging
+ && let Some(p) = ptr.pos
+ {
+ let dy = crate::autoscroll::edge_delta(p.y, avail, ui.input(|i| i.stable_dt));
+ if dy != 0.0 {
+ view.end_find_following();
+ ui.scroll_with_delta_animation(vec2(0.0, dy), egui::style::ScrollAnimation::none());
+ // Keep scrolling while the pointer rests there and sends no events.
+ ui.ctx().request_repaint();
+ }
+ }
+ // The page navigated to stays current while no page shows more of itself, so the next
+ // page step starts from it rather than from a page further down the screen (#188).
+ // It also stays current while it is wholly on screen: a short page (a cheque) gone to
+ // from the Pages panel shows less of itself than the tall page below it, and must not
+ // hand the highlight to that page.
+ if current_overlap >= best_overlap - TIE || current_overlap >= current_height - TIE {
+ current = view.current;
+ }
+ if let Some(p) = pressed_page {
+ current = p;
+ }
+ if view.continuous {
+ view.current = current;
+ }
+ resp.context_menu(|ui| {
+ // Preparing a form: the selected field's menu.
+ if preparing && let Some((name, wi)) = view.prepare.selected.clone() {
+ // Several fields: Align, Center, Distribute, Set Fields to Same Size.
+ if !view.prepare.also.is_empty() {
+ use crate::prepare::Arrange as A;
+ let others = view.prepare.also.clone();
+ let anchor = (name.clone(), wi);
+ let mut pick = |ui: &mut egui::Ui, op: A, label: &str| {
+ if ui.add_enabled(can_modify, egui::Button::new(tl!(label))).clicked() {
+ view.pending_edit = crate::prepare::arrange(&form, &anchor, &others, op);
+ ui.close();
+ }
+ };
+ ui.menu_button(tl!("Align"), |ui| {
+ pick(ui, A::AlignLeft, "Left");
+ pick(ui, A::AlignRight, "Right");
+ pick(ui, A::AlignTop, "Top");
+ pick(ui, A::AlignBottom, "Bottom");
+ pick(ui, A::AlignCenterV, "Center vertically");
+ pick(ui, A::AlignCenterH, "Center horizontally");
+ });
+ ui.menu_button(tl!("Distribute"), |ui| {
+ pick(ui, A::DistributeH, "Horizontally");
+ pick(ui, A::DistributeV, "Vertically");
+ });
+ ui.menu_button(tl!("Set Fields to Same Size"), |ui| {
+ pick(ui, A::SameHeight, "Height");
+ pick(ui, A::SameWidth, "Width");
+ pick(ui, A::SameSize, "Both");
+ });
+ ui.separator();
+ }
+ if ui.button(tl!("Properties…")).clicked() {
+ field_menu = Some(FieldMenu::Properties);
+ ui.close();
+ }
+ if ui.add_enabled(can_modify, egui::Button::new(tl!("Duplicate…"))).clicked() {
+ field_menu = Some(FieldMenu::Duplicate(name.clone()));
+ ui.close();
+ }
+ ui.separator();
+ let delete = if view.prepare.also.is_empty() { "Delete" } else { "Delete selected fields" };
+ if ui.add_enabled(can_modify, egui::Button::new(tl!(delete))).clicked() {
+ view.pending_edit = crate::prepare::delete_selected(view);
+ ui.close();
+ }
+ return;
+ }
+ if let Some((page, index)) = view.links.context {
+ if ui.button(tl!("Properties…")).clicked() {
+ view.links.open_existing = Some((page, index));
+ ui.close();
+ }
+ if ui.add_enabled(can_modify, egui::Button::new(tl!("Delete"))).clicked() {
+ view.pending_edit = Some(Edit::DeleteLink { page, index });
+ view.links.selected = None;
+ view.links.context = None;
+ ui.close();
+ }
+ ui.separator();
+ if ui.add_enabled(can_modify, egui::Button::new(tl!("Remove all links"))).clicked() {
+ view.pending_edit = Some(Edit::RemoveLinks { pages: None });
+ view.links.selected = None;
+ view.links.context = None;
+ ui.close();
+ }
+ return;
+ }
+ let is_image_menu = tool == QuickTool::EditText
+ && (ui.ctx().data_mut(|d| d.get_persisted::<bool>(crate::edit_text_ui::image_menu_id())).unwrap_or(false)
+ || view.image_selection.as_ref().is_some_and(|sel| {
+ let pointer_pos = ptr.pos;
+ let Some(p) = pointer_pos else { return false };
+ let Some((_, xf)) = view.screen_xforms.iter().find(|(page_idx, _)| *page_idx == sel.page) else { return false };
+ let images = doc.page_images(sel.page);
+ let Some(img) = images.get(sel.index) else { return false };
+ let obb = ImageObb::from_image(img, xf, info, sel.page);
+ let b = image_screen_rect(img, xf, info, sel.page);
+ (b.is_positive() && b.contains(p)) || crate::edit_text_ui::quad_contains(obb.corners(), p)
+ }));
+ if is_image_menu && let Some(sel) = view.image_selection.clone() {
+ let images = doc.page_images(sel.page);
+ let at = view.comments.context_at.map(|(_, at)| at);
+ crate::edit_text_ui::image_context_menu(ui, view, &images, sel.page, sel.index, can_paste_image, &mut image_action, at);
+ return;
+ }
+ if view.comments.selected.is_some() {
+ canvas_action = comments::context_menu(ui, view, info, prefs, allowed, 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 {
+ // The page's content is parsed once per right-click, not on every frame the menu is open.
+ let key = egui::Id::unique("copy-image-under-menu");
+ let cached = ui.data(|d| d.get_temp::<(usize, [f64; 2], Option<usize>)>(key)).filter(|c| c.0 == page && c.1 == at);
+ let hit = match cached {
+ Some(c) => c.2,
+ None => {
+ let hit = doc.page_image_at(page, at);
+ ui.data_mut(|d| d.insert_temp(key, (page, at, hit)));
+ hit
+ }
+ };
+ if let Some(image) = hit {
+ if ui.button(tl!("Copy Image")).clicked() {
+ copy_image = Some(comments::CanvasAction::CopyImage(page, image));
+ ui.close();
+ }
+ if ui.button(tl!("Copy Image in Original Format")).clicked() {
+ copy_image = Some(comments::CanvasAction::CopyImageFile(page, image));
+ ui.close();
+ }
+ ui.separator();
+ }
+ }
+ 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]));
+ let can_copy_items = can_copy && (view.image_selection.is_some() || view.selected_text().is_some() || 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,
+ has_annotations: !info.annotations.is_empty(),
+ };
+ default_page_context_menu(ui, page, at, perms, &mut page_action);
+ });
+ if !resp.context_menu_opened() {
+ ui.ctx().data_mut(|d| d.insert_persisted(crate::edit_text_ui::image_menu_id(), false));
+ }
+ (wanted, visible_now)
+ });
+ view.single_edges = visible_pages.first().copied().filter(|_| !view.continuous).map(|page| {
+ // At the top once the page's top edge shows where going to a page puts it (a gap
+ // below the window's top). Within a point, as for wheel paging, so layout rounding
+ // can't hide an edge.
+ let max_y = (out.content_size.y - out.inner_rect.height()).max(0.0);
+ (page, out.state.clamped_offset().y <= MARGIN - view.page_gap() + 1.0, out.state.clamped_offset().y >= max_y - 1.0)
+ });
+
+ view.viewport_screen = out.inner_rect;
+ view.auto_scroll.paint(ui, avail);
+ if unobstructed && matches!(tool, QuickTool::Select | QuickTool::ColumnSelect) {
+ copy_selected |= selection_actions(ui, avail, view, info, prefs, allowed && !comments_hidden, can_copy);
+ }
+
+ // Collect all main-page demand, including cached surfaces, for byte admission later.
+ // Pan-settle debounce for tiled pages: each tile costs a full page interpret, so holding
+ // fresh tiles back while the scroll offset is still moving keeps a drag on the stretched
+ // backdrop/older tiles instead of queueing a storm of interprets (one per frame) that
+ // the workers cannot cancel mid-operator. Fresh tiles go out once the pan settles;
+ // pages with nothing on screen yet still queue.
+ let scroll_offset = out.state.clamped_offset();
+ // The document ScrollArea's own scroll surfaces move the offset without the wheel deltas
+ // above: its two scroll-bar tracks/handles and, for touch or the Hand tool, its drag
+ // background. The output gives us the area id, and egui's pinned ScrollArea registers those
+ // widgets under `id.with(0)` (horizontal), `id.with(1)` (vertical) and `id.with("area")`.
+ // Ask for their exact responses instead of treating any held drag as scrolling: a text
+ // selection, a panel splitter or another widget's drag must not excuse the programmatic jump
+ // a search flash makes, while a track click (which moves the offset with no pointer motion)
+ // must still count as the reader scrolling.
+ let scroll_surface = |id: egui::Id| ui.ctx().read_response(id).is_some_and(|r| r.is_pointer_button_down_on() || r.dragged() || r.clicked());
+ let pointer_scrolling = scroll_surface(out.id.with(0usize)) || scroll_surface(out.id.with(1usize)) || scroll_surface(out.id.with("area"));
+ if pointer_scrolling && (scroll_offset - view.last_scroll).length() > 2.0 {
+ view.end_find_following();
+ }
+ let now_settle = ui.input(|i| i.time);
+ if (scroll_offset - view.last_scroll).length() > 2.0 {
+ view.pan_hold_until = now_settle + 0.25;
+ ui.ctx().request_repaint_after(std::time::Duration::from_millis(280));
+ }
+ if glide != Vec2::ZERO {
+ view.fling.moved((scroll_offset - view.last_scroll).length() > 0.01);
+ }
+ view.last_scroll = scroll_offset;
+ let pan_held = now_settle < view.pan_hold_until;
+ let (mut wanted, visible_now) = out.inner;
+ // Single-page and two-page views draw only the current row, so the next one was first asked
+ // for on the turn and showed blank paper until it rendered. Prefetch the rows either side,
+ // as continuous scrolling does for the pages just off screen.
+ if !view.continuous
+ && let (Some(&first), Some(&last)) = (visible_pages.first(), visible_pages.last())
+ {
+ let n = if view.layout == PageLayout::Single { 1 } else { 2 };
+ let max_side = ui.ctx().input(|inp| inp.max_texture_side) as f32;
+ for i in (last.saturating_add(1)..=last.saturating_add(n)).chain(first.saturating_sub(n)..first) {
+ let Some(p) = info.pages.get(i).filter(|_| !view.errors.contains_key(&i)) else { continue };
+ // As drawn: the whole page at this scale, or the backdrop of a tiled page.
+ let side = p.width.max(p.height).max(1.0);
+ wanted.push(if side * scale > TILE_THRESHOLD.min(max_side) {
+ let bs = BASE_SIDE.min(max_side) / side;
+ (i, bs, scale_tag(bs), None)
+ } else {
+ (i, scale, tag, None)
+ });
+ }
+ }
+ let cur = view.current;
+ wanted.sort_by_key(|w| (!visible_now.contains(&w.0), w.0.abs_diff(cur), w.3.is_some()));
+ // Tiles of far-away pages are useless: free them. Tiles of an earlier zoom stay for a page
+ // that is on screen, whether or not the page is tiled at this zoom (#2196): a zoom out below
+ // the tiling threshold used to drop the tiles of the zoom just left, so coming back to it
+ // was a cold miss and the page re-blurred through the backdrop while every tile was
+ // interpreted again. `OLD_TILES` still bounds how many older tiles are kept, nearest scale
+ // first, and admission keeps them inside `TILE_BYTES`.
+ let missing: HashSet<usize> = wanted.iter().filter(|w| w.3.is_some()).map(|w| w.0).collect();
+ let on_screen: HashSet<usize> = visible_now.iter().copied().collect();
+ view.tiles.retain(|(p, t, _, _), _| p.abs_diff(cur) <= 2 && (*t == tag || missing.contains(p) || on_screen.contains(p)));
+ let mut older: Vec<(f32, (usize, u64, u32, u32))> =
+ view.tiles.keys().filter(|k| k.1 != tag).map(|k| ((tag_scale(k.1) / scale).ln().abs(), *k)).collect();
+ // Tiles of earlier zooms are kept nearest scale first, and bounded by count *and* bytes: a
+ // large scan renders a tile up to 4096² (about 67 MiB), so a count alone let a few tiles of
+ // a few zooms run far past the tile allowance. #2196 keeps a zoom already visited, which
+ // makes that reachable in ordinary zooming, so the byte bound has to be here too.
+ older.sort_by(|a, b| a.0.total_cmp(&b.0));
+ let mut kept = 0usize;
+ let mut kept_bytes = 0usize;
+ let mut drop: Vec<(usize, u64, u32, u32)> = Vec::new();
+ for (_dist, key) in older {
+ let bytes = view.tiles.get(&key).map_or(0, texture_bytes);
+ if kept >= OLD_TILES || kept_bytes.saturating_add(bytes) > TILE_BYTES {
+ drop.push(key);
+ } else {
+ kept = kept.saturating_add(1);
+ kept_bytes = kept_bytes.saturating_add(bytes);
+ }
+ }
+ for key in drop {
+ view.tiles.remove(&key);
+ }
+ let mut queue: Vec<RenderRequest> = wanted
+ .iter()
+ .map(|&(page, wanted_scale, wanted_tag, tile)| RenderRequest {
+ page,
+ kind: RequestKind::Pixels,
+ tile,
+ scale: wanted_scale,
+ tag: wanted_tag,
+ // The low-res backdrop under tiles is a preview: tiny images are skipped for it.
+ // It is the whole-page request whose scale is not the current one; sharp tiles
+ // and whole-page finals always draw everything.
+ preview: tile.is_none() && (wanted_scale != scale || wanted_tag != tag),
+ })
+ .collect();
+ // While the zoom or pan is settling, hold back sharp re-renders of pages that already
+ // show something (a stale whole-page raster or older tiles, drawn stretched): each new
+ // scale would cancel the running full-page interpret and restart it from scratch, and
+ // each pan frame would queue a storm of full-page tile interprets.
+ // Pages with nothing on screen yet still queue, so panning to a fresh page draws it.
+ if sharp_held || pan_held {
+ let main_tag = tag;
+ queue.retain(|req| {
+ // Fast pages render straight through: the hold only protects heavy pages
+ // whose full-page interpret costs seconds.
+ if !view.slow_pages.contains(&req.page) {
+ return true;
+ }
+ if req.tile.is_some() {
+ let has_current_tile = view.tiles.keys().any(|(p, t, _, _)| *p == req.page && *t == req.tag);
+ if has_current_tile {
+ return false;
+ }
+ let has_any_surface = view.pages.contains_key(&req.page) || view.tiles.keys().any(|(p, _, _, _)| *p == req.page);
+ !has_any_surface
+ } else if req.tag != main_tag {
+ // The low-res backdrop under tiles is zoom-independent: let it through,
+ // it is the stretched surface the hold relies on.
+ true
+ } else {
+ // The stale raster stays stretched until the zoom or pan settles; a page with
+ // nothing on screen yet still renders.
+ !view.pages.contains_key(&req.page)
+ }
+ });
+ }
+ // Text layers: visible pages for selection, every page while a search is active. (Select All
+ // of the document needs no more: shown pages highlight as their text comes, and Copy reads
+ // the rest, as text far away is let go to bound memory.)
+ let need_text = |p: &usize| !view.texts.contains_key(p) && !view.text_failed.contains(p);
+ let mut text_pages: Vec<usize> = if hand { Vec::new() } else { visible_now.iter().copied().filter(need_text).collect() };
+ if view.find.as_ref().is_some_and(|f| !f.case_query.trim().is_empty()) {
+ let n = info.pages.len();
+ let rest: Vec<usize> = (0..n).map(|k| (cur + k) % n).filter(need_text).filter(|p| !text_pages.contains(p)).collect();
+ text_pages.extend(rest);
+ }
+ queue.extend(text_pages.into_iter().map(|page| RenderRequest {
+ page,
+ kind: RequestKind::Text,
+ tile: None,
+ scale: 1.0,
+ tag: TEXT_TAG,
+ preview: false,
+ }));
+ view.frame_queue = queue;
+ view.frame_visible = visible_now.iter().copied().collect();
+
+ if let Some((pos, text)) = hover_text {
+ // Click-through, as a tooltip is: the pages lose the pointer under anything that isn't.
+ let tip = egui::Area::new(egui::Id::unique("canvas-hover")).order(egui::Order::Tooltip).interactable(false);
+ tip.fixed_pos(pos + vec2(14.0, 16.0)).show(ui.ctx(), |ui| {
+ egui::Frame::popup(ui.style()).show(ui, |ui| {
+ ui.set_max_width(320.0);
+ ui.label(text);
+ });
+ });
+ }
+ find_bar(view, info.pages.len(), avail, ui, &t);
+ page_size_hint(view, info, units, avail, unobstructed, ui, &t);
+ if tool == QuickTool::EnhanceCamera {
+ crate::camera_ui::bar(ui.ctx(), view, avail, &t, can_modify);
+ }
+ if let Some(e) = comments::composer(ui.ctx(), view, info, prefs) {
+ view.pending_edit = Some(e);
+ }
+ if let Some(e) = crate::edit_text_ui::overlay(ui.ctx(), view, info) {
+ view.pending_edit = Some(e);
+ }
+ let text_box = crate::forms_ui::text_box(doc, view, &form);
+ if let Some(e) = crate::forms_ui::overlay(ui.ctx(), view, info, &form, text_box.as_ref(), today) {
+ view.pending_edit = Some(e);
+ }
+ if let Some(e) = crate::fill_sign::type_box(ui.ctx(), view, info, &author) {
+ view.pending_edit = Some(e);
+ }
+ let (typed, text_done) = crate::content_ui::editor(ui.ctx(), view, info, &added);
+ if typed.is_some() {
+ view.pending_edit = typed;
+ }
+ if let Some(why) = view.objects.notice.take() {
+ refused = Some(why);
+ }
+ let form_notice = view.forms.notice.take();
+ // One crop, then back to selecting (as Acrobat does).
+ let cropped = view.pending_edit.as_ref().is_some_and(|e| matches!(e, pdfcraft_engine::Edit::SetPageBox { .. }));
+ let mut tool = app.quick_tool;
+ comments::keys(ui.ctx(), view, &mut tool, allowed);
+ if preparing {
+ crate::prepare::keys(ui.ctx(), view);
+ }
+ if editing_content {
+ crate::content_ui::keys(ui.ctx(), view);
+ }
+ if tool == QuickTool::Link {
+ crate::link_ui::keys(ui.ctx(), view);
+ } else {
+ view.links.selected = None;
+ }
+ if tool != QuickTool::EditText {
+ view.image_selection = None;
+ }
+ if stamp_placed {
+ tool = QuickTool::Select;
+ }
+ // Text: each click on the page starts a box (#74); Done in the editor goes back to selecting.
+ if text_done && tool == QuickTool::AddText {
+ tool = QuickTool::Select;
+ }
+ // One field, then back to selecting (Acrobat's default without "Keep tools pinned").
+ if field_placed {
+ tool = QuickTool::Select;
+ }
+ if matches!(field_menu, Some(FieldMenu::Properties)) {
+ field_props = true;
+ }
+ let field_props = field_props.then(|| view.prepare.selected.clone()).flatten();
+ match canvas_action {
+ Some(comments::CanvasAction::Edit(e)) => view.pending_edit = Some(*e),
+ // `choose_right_panel` would borrow all of `app` while `view` is held; same effect.
+ Some(comments::CanvasAction::OpenComments) => {
+ app.right = Some(RightPanel::Comments);
+ app.comments_panel_closed = false;
+ }
+ Some(comments::CanvasAction::Properties(p, i)) => open_props = Some((p, i)),
+ Some(comments::CanvasAction::CopyImage(p, i)) => image_action = Some(crate::edit_text_ui::ImageAction::Copy(p, i)),
+ Some(comments::CanvasAction::CopyImageFile(p, i)) => image_action = Some(crate::edit_text_ui::ImageAction::CopyFile(p, i)),
+ None => {}
+ }
+ // Full screen: the click turns the page unless it did something else first. It waits out the
+ // double-click time: turning on the first click's release sent a double-click's second click,
+ // meant to select a word, to the next page (review on #2070). A selection cancels it, and so
+ // do a link followed meanwhile and leaving full screen; a double-click elsewhere still turns
+ // once.
+ let now = ui.input(|i| i.time);
+ if present_click && clicked_link.is_none() && view.selection.is_none() && view.clicks < 2 {
+ let delay = ui.ctx().options(|o| o.input_options.max_double_click_delay);
+ view.present_turn = Some((now + delay, !present_back));
+ }
+ if let Some((due, forward)) = view.present_turn {
+ if clicked_link.is_some() || view.selection.is_some() || view.presentation.is_none() {
+ view.present_turn = None;
+ } else if now >= due {
+ view.present_turn = None;
+ view.step_page(forward);
+ } else {
+ ui.ctx().request_repaint_after(std::time::Duration::from_secs_f64((due - now).max(0.0)));
+ }
+ }
+ match clicked_link {
+ Some(LinkTarget::Page(p, dest)) => view.go_to_dest(p, dest, info),
+ Some(LinkTarget::Uri(u)) => app.request_document_url(&u, crate::LinkOrigin::Link),
+ Some(LinkTarget::SetLayers { changes, preserve_rb }) => set_layers(app, index, &changes, preserve_rb),
+ Some(LinkTarget::RemoteGoTo { file, destination, .. }) => remote_open = Some((view.id, file, destination)),
+ Some(LinkTarget::Other(s)) => app.notify_fmt("This PDF uses the unsupported {s} action.", &[("s", &s)]),
+ None => {}
+ }
+ if tool == QuickTool::Crop && cropped {
+ tool = QuickTool::Select;
+ }
+ if let Some(done) = app.views[index].marquee_done.take() {
+ app.finish_marquee(index, done);
+ }
+ // A signature rectangle was drawn, or an empty signature field clicked.
+ let drawn = app.views[index].sign.drawn.take();
+ if let (Some((page, rect)), QuickTool::SignArea { certify }) = (drawn, tool) {
+ tool = QuickTool::Select;
+ app.quick_tool = tool;
+ app.start_signing(page, Some(rect), None, certify.then_some(2));
+ }
+ if let Some(field) = app.views[index].sign.field.take() {
+ let signed = app.session.get(app.views[index].id).is_some_and(|d| d.signatures.iter().any(|s| s.field == field && s.signed));
+ if signed {
+ app.right = Some(RightPanel::Signatures);
+ if !app.sig_expanded.contains(&field) {
+ app.sig_expanded.push(field);
+ }
+ } else {
+ let page = app.views[index].current;
+ app.start_signing(page, None, Some(field), None);
+ }
+ }
+ app.quick_tool = tool;
+ if let Some((page, at)) = app.views[index].comments.attach_at.take() {
+ app.attach_file_comment(page, at);
+ }
+ if let Some((p, i)) = open_props {
+ app.open_comment_props(p, i);
+ }
+ if let Some((p, i)) = app.views[index].comments.default_request.take() {
+ app.make_comment_default(p, i);
+ }
+ if let Some((p, i, open)) = app.views[index].comments.attachment_request.take() {
+ let doc = app.views[index].id;
+ app.comment_attachment_action(doc, p, i, open);
+ }
+ if let Some((name, w)) = field_props {
+ app.open_field_props(&name, w);
+ }
+ if let Some(FieldMenu::Duplicate(name)) = field_menu {
+ let pages = app.session.get(app.views[index].id).map_or(1, |d| d.info.pages.len());
+ app.duplicate_draft = Some(crate::DuplicateDraft { name, all: true, from: 1, to: pages });
+ app.dialog = Some(crate::Dialog::DuplicateField);
+ }
+ if let Some((page, rect)) = app.views[index].links.open_new.take() {
+ app.open_link_props(page, Some(rect), None);
+ }
+ if let Some((page, i)) = app.views[index].links.open_existing.take() {
+ app.open_link_props(page, None, Some(i));
+ }
+ if let Some((page, quads)) = app.views[index].pending_redaction.take() {
+ let author = app.comment_prefs.author.clone();
+ app.views[index].pending_edit = Some(if app.quick_tool == QuickTool::Comment(comments::CommentTool::Highlight) {
+ // An area highlight: a highlight over the box.
+ let style = app.comment_prefs.style(comments::CommentTool::Highlight);
+ pdfcraft_engine::Edit::AddAnnotation(pdfcraft_engine::NewAnnotation {
+ page,
+ shape: pdfcraft_engine::Shape::TextMarkup { kind: pdfcraft_engine::Markup::Highlight, quads },
+ style,
+ contents: String::new(),
+ author,
+ })
+ } else {
+ app.redact_prefs.mark(page, quads, &author)
+ });
+ }
+ match image_action {
+ Some(crate::edit_text_ui::ImageAction::Replace(page, index)) => app.replace_page_image_dialog(page, index),
+ Some(crate::edit_text_ui::ImageAction::Save(page, index)) => app.save_page_image(page, index),
+ Some(crate::edit_text_ui::ImageAction::Copy(page, index)) => {
+ app.copy_page_image(page, index);
+ }
+ Some(crate::edit_text_ui::ImageAction::CopyFile(page, index)) => app.copy_page_image_file(page, index),
+ Some(crate::edit_text_ui::ImageAction::Cut(page, image)) => {
+ app.views[index].image_selection = None;
+ app.cut_page_image(page, image);
+ }
+ Some(crate::edit_text_ui::ImageAction::Paste(page, at)) => {
+ if let Some(pt) = at {
+ app.paste_image_at(page, pt);
+ } else {
+ app.paste_image(page, None);
+ }
+ }
+ Some(crate::edit_text_ui::ImageAction::DrawFreehand) => {
+ app.quick_tool = crate::QuickTool::Comment(crate::comments::CommentTool::Ink);
+ }
+ Some(crate::edit_text_ui::ImageAction::Redact(page, index)) => app.redact_page_image(page, index),
+ Some(crate::edit_text_ui::ImageAction::Link(page, index)) => app.link_page_image(page, index),
+ Some(crate::edit_text_ui::ImageAction::Recognize(page)) => app.recognize_text_on_page(page),
+ Some(crate::edit_text_ui::ImageAction::AddComment(page, i)) => {
+ if let Some(d) = app.session.get(app.views[index].id) {
+ let images = d.page_images(page);
+ 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 {
+ page,
+ at: center,
+ kind: crate::comments::ComposerKind::Note,
+ text: String::new(),
+ focus: true,
+ });
+ }
+ }
+ }
+ Some(crate::edit_text_ui::ImageAction::Crop) => {
+ let doc_id = app.views[index].id;
+ if let Some(s) = app.views[index].image_selection.as_mut()
+ && let Some(d) = app.session.get(doc_id)
+ {
+ let images = d.page_images(s.page);
+ if let Some(im) = images.get(s.index) {
+ s.crop = Some(crate::edit_text_ui::CropMode::new(im.visible_rect.unwrap_or(im.rect)));
+ s.crop_mode = true;
+ s.crop_rect = None;
+ }
+ }
+ }
+ None => {}
+ }
+ match page_action {
+ Some(PageMenuAction::Copy) => {
+ if let Some(sel) = app.views[index].image_selection.clone() {
+ app.copy_page_image(sel.page, sel.index);
+ } else if app.views[index].selected_text().is_some() {
+ app.execute("edit.copy");
+ } else if let Some((page, at)) = app.views[index].comments.context_at
+ && let Some(doc) = app.session.get(app.views[index].id)
+ && let Some(image) = doc.page_image_at(page, at)
+ {
+ app.copy_page_image(page, image);
+ }
+ }
+ Some(PageMenuAction::Paste(page, at)) => {
+ app.paste_image_at(page, at);
+ }
+ Some(PageMenuAction::RotateCCW(page)) => {
+ let _ = page;
+ app.views[index].rotate_view(false);
+ }
+ Some(PageMenuAction::RotateCW(page)) => {
+ let _ = page;
+ app.views[index].rotate_view(true);
+ }
+ Some(PageMenuAction::Print) => {
+ app.open_print();
+ }
+ Some(PageMenuAction::SelectTool) => {
+ app.quick_tool = QuickTool::Select;
+ }
+ Some(PageMenuAction::HandTool) => {
+ app.quick_tool = QuickTool::Hand;
+ }
+ Some(PageMenuAction::MarqueeZoom) => {
+ app.quick_tool = QuickTool::MarqueeZoom;
+ }
+ Some(PageMenuAction::AddComment(page, at)) => {
+ app.views[index].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.selected = None;
+ app.views[index].pending_edit = Some(pdfcraft_engine::Edit::Flatten { comments: true, fields: false });
+ }
+ Some(PageMenuAction::AddBookmark(_page)) => {
+ app.bookmark_action(crate::panels::BmAction::New);
+ }
+ Some(PageMenuAction::TakeSnapshot) => {
+ app.quick_tool = QuickTool::Snapshot;
+ }
+ Some(PageMenuAction::EditPdf) => {
+ app.quick_tool = QuickTool::EditText;
+ }
+ Some(PageMenuAction::AddText) => {
+ app.quick_tool = QuickTool::AddText;
+ }
+ Some(PageMenuAction::AddImage) => {
+ app.add_image_dialog();
+ }
+ Some(PageMenuAction::DeletePage(page)) => {
+ app.views[index].pending_edit = Some(pdfcraft_engine::Edit::DeletePages { pages: vec![page] });
+ }
+ Some(PageMenuAction::ExportPdf) => {
+ app.select_tool("export");
+ }
+ Some(PageMenuAction::Find) => {
+ app.views[index].open_find();
+ }
+ Some(PageMenuAction::DocProperties) => {
+ app.dialog = Some(crate::Dialog::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 open_boxes {
+ app.boxes_draft.range = crate::pageboxes::Range::Current;
+ app.boxes_draft.seeded = None;
+ app.dialog = Some(crate::Dialog::PageBoxes);
+ }
+ if let Some((page, rect)) = open_table {
+ app.field_table_draft = Some(crate::field_table_ui::FieldTableDraft::new(app.views[index].id, page, rect, &form, generation));
+ app.dialog = Some(crate::Dialog::FieldTable);
+ // The window lasts while the form is prepared. Drawn with the tool picked but its panel
+ // closed, the tool goes back to Select above, so the panel opens to keep it prepared.
+ app.left = crate::LeftPanel::Tool("form");
+ app.reveal_tools();
+ }
+ if let Some(n) = form_notice {
+ match n {
+ crate::forms_ui::FormNotice::Security => app.notify_tr("The document's security settings don't allow filling in form fields"),
+ crate::forms_ui::FormNotice::ReadOnly(name) => app.notify_fmt("{name} is read-only", &[("name", &name)]),
+ crate::forms_ui::FormNotice::NoAction(name) => app.notify_fmt("{name} has no action", &[("name", &name)]),
+ }
+ }
+ if let Some((name, action)) = app.views[index].forms.button.take() {
+ run_button(app, index, &name, action);
+ }
+ if copy_selected {
+ app.execute("edit.copy");
+ }
+ // Read mode hides the tools (#2646), and full screen is the page and nothing else (#1459);
+ // the quick tools come back with the window.
+ if app.mode != crate::Mode::Read && !app.full_screen {
+ quick_bar(app, avail, ui);
+ }
+ if let Some((source, file, destination)) = remote_open {
+ app.open_remote_link(source, file, destination);
+ }
+}
+
+/// The prepare-mode field menu's choices.
+enum FieldMenu {
+ Properties,
+ Duplicate(String),
+}
+
+pub use crate::image_engine::{HandleId, MIN_RECT_SIZE, apply_crop, apply_resize, apply_resize_proportional, reset_crop};
+#[cfg(test)]
+mod tests;
diff --git a/crates/ui-egui/src/canvas/cache.rs b/crates/ui-egui/src/canvas/cache.rs
index d8a1d1d44..d46392fab 100644
--- a/crates/ui-egui/src/canvas/cache.rs
+++ b/crates/ui-egui/src/canvas/cache.rs
@@ -236,6 +236,12 @@ impl DocView {
self.texts.get(&page).cloned()
}
+ /// Whether `page`'s text layer has arrived from the renderer. Selecting text, the I-beam and
+ /// find matches on a page all wait for it (tests and automation).
+ pub fn has_page_text(&self, page: usize) -> bool {
+ self.texts.contains_key(&page)
+ }
+
pub fn thumb(&self, page: usize) -> Option<&TextureHandle> {
self.thumbs.get(&page).map(|t| &t.tex)
}
diff --git a/crates/ui-egui/src/canvas/xform.rs b/crates/ui-egui/src/canvas/xform.rs
index c914233d8..4ca6ed86c 100644
--- a/crates/ui-egui/src/canvas/xform.rs
+++ b/crates/ui-egui/src/canvas/xform.rs
@@ -17,7 +17,7 @@ impl DocView {
}
/// Where `page` is drawn this frame, with its coordinate mapping.
- pub(crate) fn page_xform(&self, page: usize) -> Option<PageXform> {
+ pub fn page_xform(&self, page: usize) -> Option<PageXform> {
self.screen_xforms.iter().find(|(p, _)| *p == page).map(|(_, xf)| *xf)
}
}
diff --git a/crates/ui-egui/src/editing.rs b/crates/ui-egui/src/editing.rs
index f6e43f8a6..b0fe622ff 100644
--- a/crates/ui-egui/src/editing.rs
+++ b/crates/ui-egui/src/editing.rs
@@ -694,6 +694,7 @@ fn re_resolve_image_selection(
.filter(|(_, img)| img.name == target.name && img.object == target.object && rect_matches(img.rect, target.rect))
.map(|(idx, _)| idx)
.collect();
+ eprintln!("re_resolve: view.image_sel={:?}, target_rect={:?}, exact_matches={:?}, ambiguous_before={ambiguous_before}", view.image_selection.as_ref().map(|s| s.index), target.rect, exact_matches);
let new_idx = if !ambiguous_before && exact_matches.len() == 1 {
exact_matches.first().copied()
} else if !ambiguous_before && exact_matches.is_empty() {
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 105e8d2e5..1d8c4e49d 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -28,9 +28,9 @@ macro_rules! tl_ctx {
pub mod canvas;
mod chrome;
pub mod image_engine;
-pub use image_engine::{HandleId, MIN_RECT_SIZE, apply_crop, apply_resize, apply_resize_proportional, reset_crop};
pub use combine_grid::ThumbState as CombineThumb;
pub use combine_ui::{Columns as CombineColumns, CombineView, Lock as CombineLock, SortKey};
+pub use image_engine::{HandleId, MIN_RECT_SIZE, apply_crop, apply_resize, apply_resize_proportional, reset_crop};
mod commands;
pub mod control;
mod menus;
@@ -140,8 +140,8 @@ pub use tools::bulk_fields;
use tools::calc_order_ui;
use tools::camera_ui;
pub use tools::comments;
-use tools::content_ui;
-use tools::edit_text_ui;
+pub use tools::content_ui;
+pub use tools::edit_text_ui;
pub use tools::field_table_ui;
pub use tools::fill_sign;
pub use tools::forms_ui;
diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs
index d7c8bef1c..de278a6b4 100644
--- a/crates/ui-egui/src/menus.rs
+++ b/crates/ui-egui/src/menus.rs
@@ -254,6 +254,9 @@ fn english(labeled: Labeled<'_>) -> Option<String> {
}
fn translate(english: &'static str) -> String {
+ if english == "⋯" {
+ return "…".to_owned();
+ }
tl!(english).to_owned()
}
diff --git a/crates/ui-egui/src/panels/edit.rs b/crates/ui-egui/src/panels/edit.rs
index 98e89d310..43384c14f 100644
--- a/crates/ui-egui/src/panels/edit.rs
+++ b/crates/ui-egui/src/panels/edit.rs
@@ -264,6 +264,7 @@ fn format_section(app: &mut PdfCraftApp, ui: &mut egui::Ui, t: &Tokens) {
.map(|f| (f.resource, f.face))
.collect();
let fmt = ed.selection_formatting(&sources);
+ ed.sync_selection_look(&fmt);
let shown = fmt.font_shown;
let mixed_size = fmt.size.is_none();
let out = crate::format_text_ui::panel(ui, t, &mut ed.look, Some(&mut ed.extras), Fonts { sources: Some(&sources), shown, mixed_size });
diff --git a/crates/ui-egui/src/panels/tools.rs b/crates/ui-egui/src/panels/tools.rs
index 3a1cccd71..e403c438b 100644
--- a/crates/ui-egui/src/panels/tools.rs
+++ b/crates/ui-egui/src/panels/tools.rs
@@ -70,7 +70,10 @@ fn all_tools(app: &mut PdfCraftApp, ui: &mut egui::Ui, t: &Tokens) {
ui.add_space(2.0);
let shown = if app.all_tools_expanded { TOOL_GROUPS.len() } else { COLLAPSED_TOOLS.min(TOOL_GROUPS.len()) };
for g in &TOOL_GROUPS[..shown] {
- if tool_row(ui, t, g).clicked() {
+ let (resp, pin_clicked) = tool_row(ui, t, g, app.is_tool_pinned(g.id));
+ if pin_clicked {
+ app.toggle_pin_tool(g.id);
+ } else if resp.clicked() {
app.select_tool(g.id);
}
}
@@ -102,21 +105,29 @@ pub(super) fn row_label(ui: &mut egui::Ui, text: &str, font: egui::FontId, color
}
/// Draw one tool-group row with its icon, label, badge and availability hint.
-fn tool_row(ui: &mut egui::Ui, t: &Tokens, g: &ToolGroup) -> egui::Response {
+fn tool_row(ui: &mut egui::Ui, t: &Tokens, g: &ToolGroup, is_pinned: bool) -> (egui::Response, bool) {
let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 34.0), Sense::click());
resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tl!(g.label)));
let press = theme::Press::track(ui, &resp);
press.wash(ui, rect, 6, false);
let body = rect.translate(press.offset());
icons::paint(ui, Rect::from_min_size(body.min + vec2(6.0, 7.0), vec2(20.0, 20.0)), g.icon, 19.0, hue(g));
- let right_reserved = match (g.badge, g.availability) {
- (Some(b), _) => ui.fonts_mut(|f| f.layout_no_wrap(tl!(b).to_owned(), theme::semibold(9.5), Color32::WHITE).size().x) + 26.0,
+
+ let pin_rect = Rect::from_center_size(body.right_center() - vec2(14.0, 0.0), vec2(22.0, 22.0));
+ let pin_resp = ui.interact(pin_rect, ui.scope_id().with(("pin_toggle_row", g.id)), Sense::click());
+ let pin_hovered = pin_resp.hovered();
+ let mut pin_clicked = false;
+
+ let pin_space = 26.0;
+ let badge_or_hint_reserved = match (g.badge, g.availability) {
+ (Some(b), _) => ui.fonts_mut(|f| f.layout_no_wrap(tl!(b).to_owned(), theme::semibold(9.5), Color32::WHITE).size().x) + 18.0,
(None, Availability::Planned(m)) if resp.hovered() => {
let hint = format!("{} · {m}", tl!("Planned"));
- ui.fonts_mut(|f| f.layout_no_wrap(hint, theme::medium(10.5), t.text_faint).size().x) + 18.0
+ ui.fonts_mut(|f| f.layout_no_wrap(hint, theme::medium(10.5), t.text_faint).size().x) + 10.0
}
- _ => 8.0,
+ _ => 0.0,
};
+ let right_reserved = pin_space + badge_or_hint_reserved + 8.0;
let clipped =
row_label(ui, tl!(g.label), theme::regular(13.5), t.text, body.left_center() + vec2(36.0, 0.0), rect.width() - 36.0 - right_reserved);
match (g.badge, g.availability) {
@@ -124,14 +135,14 @@ fn tool_row(ui: &mut egui::Ui, t: &Tokens, g: &ToolGroup) -> egui::Response {
let font = theme::semibold(9.5);
let badge = tl!(b);
let w = ui.fonts_mut(|f| f.layout_no_wrap(badge.to_string(), font.clone(), Color32::WHITE).size().x);
- let r = Rect::from_center_size(body.right_center() - vec2(w / 2.0 + 10.0, 0.0), vec2(w + 10.0, 16.0));
+ let r = Rect::from_center_size(body.right_center() - vec2(pin_space + w / 2.0 + 4.0, 0.0), vec2(w + 10.0, 16.0));
ui.painter().rect_filled(r, CornerRadius::same(4), t.badge_new);
ui.painter().text(r.center(), Align2::CENTER_CENTER, badge, font, Color32::WHITE);
}
// Planned tools: a quiet milestone hint instead of a chip, so the list stays calm.
(None, Availability::Planned(m)) if resp.hovered() => {
ui.painter().text(
- body.right_center() - vec2(10.0, 0.0),
+ body.right_center() - vec2(pin_space + 4.0, 0.0),
Align2::RIGHT_CENTER,
format!("{} · {m}", tl!("Planned")),
theme::medium(10.5),
@@ -140,13 +151,34 @@ fn tool_row(ui: &mut egui::Ui, t: &Tokens, g: &ToolGroup) -> egui::Response {
}
_ => {}
}
+
+ let row_hovered = ui.rect_contains_pointer(rect) || resp.hovered();
+ if is_pinned || row_hovered || pin_hovered {
+ if pin_hovered {
+ ui.painter().rect_filled(pin_rect, CornerRadius::same(4), t.pressed);
+ }
+ let pin_tint = if is_pinned {
+ t.accent_text
+ } else if pin_hovered {
+ t.text
+ } else {
+ t.text_faint
+ };
+ icons::paint(ui, pin_rect.shrink(3.0), "pin", 15.0, pin_tint);
+ let tip = if is_pinned { tl!("Unpin from Home") } else { tl!("Pin to Home") };
+ pin_resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tip));
+ if theme::hand(pin_resp).on_hover_text(tip).clicked() {
+ pin_clicked = true;
+ }
+ }
+
let tip = match g.availability {
Availability::Ready => tl!("Available").to_string(),
Availability::Planned(m) => format!("{} {m} — {}", tl!("Planned for milestone"), tl!("open to see what it will include")),
Availability::Provider => tl!("Optional: needs an AI provider you configure").into(),
};
let tip = if clipped { format!("{} — {tip}", tl!(g.label)) } else { tip };
- theme::hand(resp).on_hover_text(tip)
+ (theme::hand(resp).on_hover_text(tip), pin_clicked)
}
/// Draw the detail view for one tool group, dispatching its commands and tool-specific panels.
diff --git a/crates/ui-egui/src/tools.rs b/crates/ui-egui/src/tools.rs
index 165651e60..a41680be9 100644
--- a/crates/ui-egui/src/tools.rs
+++ b/crates/ui-egui/src/tools.rs
@@ -2,8 +2,8 @@ pub mod bulk_fields;
pub(super) mod calc_order_ui;
pub(super) mod camera_ui;
pub mod comments;
-pub(super) mod content_ui;
-pub(super) mod edit_text_ui;
+pub mod content_ui;
+pub mod edit_text_ui;
pub mod field_table_ui;
pub mod fill_sign;
pub mod forms_ui;
diff --git a/crates/ui-egui/src/tools/edit_text_ui.rs b/crates/ui-egui/src/tools/edit_text_ui.rs
index b2317a7a2..289df1fb6 100644
--- a/crates/ui-egui/src/tools/edit_text_ui.rs
+++ b/crates/ui-egui/src/tools/edit_text_ui.rs
@@ -1,1491 +1,1491 @@
-//! Edit a PDF ▸ Edit text & images: boxes around the paragraphs and images already on the page.
-//! Click a paragraph to edit it in place (⌘Enter or clicking away applies and rewraps it to the
-//! box, Esc cancels); drag it to move it, or drag the handle on its left or right edge to rewrap
-//! it to a new width. Click an image to select it: drag to move, drag a corner to resize (keeping
-//! its proportions), right-click for rotate, flip, replace, save and delete; Delete removes it.
-
-use std::collections::BTreeMap;
-use std::sync::Arc;
-
-use egui::{Color32, CornerRadius, FontFamily, FontId, Pos2, Rect, Stroke, pos2};
-use pdfcraft_engine::{Edit, ObjectKind, ObjectTarget};
-use pdfcraft_render::DocInfo;
-
-use crate::canvas::{DocView, PageXform};
-use crate::page_pointer::PagePointer;
-
-mod background;
-mod image;
-mod layout;
-
-pub(crate) use background::TextBackground;
-pub use image::{CropMode, DragTarget, ImageAction, ImageDrag, ImageHandle, ImageSelection, image_menu_id};
-pub(crate) use image::{image_context_menu, image_input, image_owns_pointer, Matrix, quad_contains, user_to_screen};
-#[cfg(test)]
-use image::{rotate_knob, turn_degrees};
-#[cfg(test)]
-use layout::{DARK_EDITOR_FILL, contrast};
-pub(crate) use layout::{caret_color_on, editor_fill, editor_font, install_source_fonts};
-use layout::{color32, editor_galley, editor_job, look_of, luminance, source_look, unseen};
-
-const ACCENT: Color32 = Color32::from_rgb(0x14, 0x73, 0xE6);
-
-#[derive(Clone, Copy, PartialEq)]
-enum TextTarget {
- Block(usize),
- Added(usize),
-}
-
-/// How many faint Edit-text outlines are drawn per page per frame. CAD plots can draw
-/// ~1000 tiny images on one page; stroking all of them every frame (plus a hover query
-/// per box) stalls the UI. Past this, only the selected and hovered boxes are outlined:
-/// hit-testing still covers every image, so nothing becomes unselectable.
-pub(crate) const MAX_OUTLINES: usize = 250;
-
-pub fn is_bulleted(text: &str) -> bool {
- let mut lines = text.lines();
- let Some(first) = lines.next() else { return false };
- first.trim_start().starts_with("• ") || first.trim_start().starts_with("- ")
-}
-
-pub fn is_numbered(text: &str) -> bool {
- let mut lines = text.lines();
- let Some(first) = lines.next() else { return false };
- let t = first.trim_start();
- let num_end = t.find('.').unwrap_or(0);
- num_end > 0 && t[..num_end].chars().all(|c| c.is_ascii_digit()) && t[num_end..].starts_with(". ")
-}
-
-pub fn toggle_bullet_list(text: &mut String) -> bool {
- let lines: Vec<&str> = text.lines().collect();
- if lines.is_empty() {
- return false;
- }
- let all_bulleted = lines.iter().all(|l| {
- let t = l.trim_start();
- t.is_empty() || t.starts_with("• ") || t.starts_with("- ")
- });
- let mut new_text = String::with_capacity(text.len() + 16);
- for (i, line) in lines.iter().enumerate() {
- if i > 0 {
- new_text.push('\n');
- }
- let trimmed = line.trim_start();
- if all_bulleted {
- if let Some(rest) = trimmed.strip_prefix("• ").or_else(|| trimmed.strip_prefix("- ")) {
- new_text.push_str(rest);
- } else {
- new_text.push_str(line);
- }
- } else if trimmed.is_empty() || trimmed.starts_with("• ") {
- new_text.push_str(line);
- } else {
- new_text.push_str("• ");
- new_text.push_str(line);
- }
- }
- if new_text != *text {
- *text = new_text;
- true
- } else {
- false
- }
-}
-
-pub fn toggle_numbered_list(text: &mut String) -> bool {
- let lines: Vec<&str> = text.lines().collect();
- if lines.is_empty() {
- return false;
- }
- let is_num_line = |l: &str| {
- let t = l.trim_start();
- if t.is_empty() {
- return true;
- }
- let dot_idx = t.find('.').unwrap_or(0);
- dot_idx > 0 && t[..dot_idx].chars().all(|c| c.is_ascii_digit()) && t[dot_idx..].starts_with(". ")
- };
- let all_numbered = lines.iter().all(|l| is_num_line(l));
- let mut new_text = String::with_capacity(text.len() + 16);
- let mut num = 1;
- for (i, line) in lines.iter().enumerate() {
- if i > 0 {
- new_text.push('\n');
- }
- let t = line.trim_start();
- if all_numbered {
- if let Some(dot_idx) = t.find('.')
- && dot_idx > 0
- && t[..dot_idx].chars().all(|c| c.is_ascii_digit())
- && t[dot_idx..].starts_with(". ")
- {
- new_text.push_str(t.get(dot_idx + 2..).unwrap_or(""));
- continue;
- }
- new_text.push_str(line);
- } else if t.is_empty() {
- new_text.push_str(line);
- } else {
- use std::fmt::Write as _;
- let _ = write!(new_text, "{num}. ");
- new_text.push_str(t);
- num += 1;
- }
- }
- if new_text != *text {
- *text = new_text;
- true
- } else {
- false
- }
-}
-
-pub fn char_to_superscript(c: char) -> char {
- match c {
- '0' => '⁰',
- '1' => '¹',
- '2' => '²',
- '3' => '³',
- '4' => '⁴',
- '5' => '⁵',
- '6' => '⁶',
- '7' => '⁷',
- '8' => '⁸',
- '9' => '⁹',
- '+' => '⁺',
- '-' | '−' => '⁻',
- '=' => '⁼',
- '(' => '⁽',
- ')' => '⁾',
- 'a' => 'ᵃ',
- 'b' => 'ᵇ',
- 'c' => 'ᶜ',
- 'd' => 'ᵈ',
- 'e' => 'ᵉ',
- 'f' => 'ᶠ',
- 'g' => 'ᵍ',
- 'h' => 'ʰ',
- 'i' => 'ⁱ',
- 'j' => 'ʲ',
- 'k' => 'ᵏ',
- 'l' => 'ˡ',
- 'm' => 'ᵐ',
- 'n' => 'ⁿ',
- 'o' => 'ᵒ',
- 'p' => 'ᵖ',
- 'r' => 'ʳ',
- 's' => 'ˢ',
- 't' => 'ᵗ',
- 'u' => 'ᵘ',
- 'v' => 'ᵛ',
- 'w' => 'ʷ',
- 'x' => 'ˣ',
- 'y' => 'ʸ',
- 'z' => 'ᶻ',
- 'A' => 'ᴬ',
- 'B' => 'ᴮ',
- 'D' => 'ᴰ',
- 'E' => 'ᴱ',
- 'G' => 'ᴳ',
- 'H' => 'ᴴ',
- 'I' => 'ᴵ',
- 'J' => 'ᴶ',
- 'K' => 'ᴷ',
- 'L' => 'ᴸ',
- 'M' => 'ᴹ',
- 'N' => 'ᴺ',
- 'O' => 'ᴼ',
- 'P' => 'ᴾ',
- 'R' => 'ᴿ',
- 'T' => 'ᵀ',
- 'U' => 'ᵁ',
- 'V' => 'ⱽ',
- 'W' => 'ᵂ',
- other => other,
- }
-}
-
-pub fn char_from_superscript(c: char) -> char {
- match c {
- '⁰' => '0',
- '¹' => '1',
- '²' => '2',
- '³' => '3',
- '⁴' => '4',
- '⁵' => '5',
- '⁶' => '6',
- '⁷' => '7',
- '⁸' => '8',
- '⁹' => '9',
- '⁺' => '+',
- '⁻' => '-',
- '⁼' => '=',
- '⁽' => '(',
- '⁾' => ')',
- 'ᵃ' => 'a',
- 'ᵇ' => 'b',
- 'ᶜ' => 'c',
- 'ᵈ' => 'd',
- 'ᵉ' => 'e',
- 'ᶠ' => 'f',
- 'ᵍ' => 'g',
- 'ʰ' => 'h',
- 'ⁱ' => 'i',
- 'ʲ' => 'j',
- 'ᵏ' => 'k',
- 'ˡ' => 'l',
- 'ᵐ' => 'm',
- 'ⁿ' => 'n',
- 'ᵒ' => 'o',
- 'ᵖ' => 'p',
- 'ʳ' => 'r',
- 'ˢ' => 's',
- 'ᵗ' => 't',
- 'ᵘ' => 'u',
- 'ᵛ' => 'v',
- 'ʷ' => 'w',
- 'ˣ' => 'x',
- 'ʸ' => 'y',
- 'ᶻ' => 'z',
- 'ᴬ' => 'A',
- 'ᴮ' => 'B',
- 'ᴰ' => 'D',
- 'ᴱ' => 'E',
- 'ᴳ' => 'G',
- 'ᴴ' => 'H',
- 'ᴵ' => 'I',
- 'ᴶ' => 'J',
- 'ᴷ' => 'K',
- 'ᴸ' => 'L',
- 'ᴹ' => 'M',
- 'ᴺ' => 'N',
- 'ᴼ' => 'O',
- 'ᴾ' => 'P',
- 'ᴿ' => 'R',
- 'ᵀ' => 'T',
- 'ᵁ' => 'U',
- 'ⱽ' => 'V',
- 'ᵂ' => 'W',
- other => other,
- }
-}
-
-pub fn char_to_subscript(c: char) -> char {
- match c {
- '0' => '₀',
- '1' => '₁',
- '2' => '₂',
- '3' => '₃',
- '4' => '₄',
- '5' => '₅',
- '6' => '₆',
- '7' => '₇',
- '8' => '₈',
- '9' => '₉',
- '+' => '₊',
- '-' | '−' => '₋',
- '=' => '₌',
- '(' => '₍',
- ')' => '₎',
- 'a' => 'ₐ',
- 'e' => 'ₑ',
- 'h' => 'ₕ',
- 'i' => 'ᵢ',
- 'j' => 'ⱼ',
- 'k' => 'ₖ',
- 'l' => 'ₗ',
- 'm' => 'ₘ',
- 'n' => 'ₙ',
- 'o' => 'ₒ',
- 'p' => 'ₚ',
- 'r' => 'ᵣ',
- 's' => 'ₛ',
- 't' => 'ₜ',
- 'u' => 'ᵤ',
- 'v' => 'ᵥ',
- 'x' => 'ₓ',
- other => other,
- }
-}
-
-pub fn char_from_subscript(c: char) -> char {
- match c {
- '₀' => '0',
- '₁' => '1',
- '₂' => '2',
- '₃' => '3',
- '₄' => '4',
- '₅' => '5',
- '₆' => '6',
- '₇' => '7',
- '₈' => '8',
- '₉' => '9',
- '₊' => '+',
- '₋' => '-',
- '₌' => '=',
- '₍' => '(',
- '₎' => ')',
- 'ₐ' => 'a',
- 'ₑ' => 'e',
- 'ₕ' => 'h',
- 'ᵢ' => 'i',
- 'ⱼ' => 'j',
- 'ₖ' => 'k',
- 'ₗ' => 'l',
- 'ₘ' => 'm',
- 'ₙ' => 'n',
- 'ₒ' => 'o',
- 'ₚ' => 'p',
- 'ᵣ' => 'r',
- 'ₛ' => 's',
- 'ₜ' => 't',
- 'ᵤ' => 'u',
- 'ᵥ' => 'v',
- 'ₓ' => 'x',
- other => other,
- }
-}
-
-fn snap_char_boundaries(s: &str, start: usize, end: usize) -> (usize, usize) {
- let mut s_idx = start.min(s.len());
- while s_idx > 0 && !s.is_char_boundary(s_idx) {
- s_idx -= 1;
- }
- let mut e_idx = end.min(s.len());
- while e_idx < s.len() && !s.is_char_boundary(e_idx) {
- e_idx += 1;
- }
- (s_idx, e_idx)
-}
-
-pub fn toggle_superscript(ed: &mut LineEditor) -> bool {
- let (s_pos, e_pos) = if let Some(r) = &ed.selection { (r.start.min(ed.text.len()), r.end.min(ed.text.len())) } else { (0, ed.text.len()) };
- let (start, end) = snap_char_boundaries(&ed.text, s_pos, e_pos);
- if start >= end {
- return false;
- }
- let target = &ed.text[start..end];
- let all_sup = target.chars().all(|c| char_from_superscript(c) != c);
- let converted: String =
- if all_sup { target.chars().map(char_from_superscript).collect() } else { target.chars().map(char_to_superscript).collect() };
- if converted != target {
- let conv_len = converted.len();
- ed.text.replace_range(start..end, &converted);
- if ed.selection.is_some() {
- ed.selection = Some(start..start + conv_len);
- }
- true
- } else {
- false
- }
-}
-
-pub fn toggle_subscript(ed: &mut LineEditor) -> bool {
- let (s_pos, e_pos) = if let Some(r) = &ed.selection { (r.start.min(ed.text.len()), r.end.min(ed.text.len())) } else { (0, ed.text.len()) };
- let (start, end) = snap_char_boundaries(&ed.text, s_pos, e_pos);
- if start >= end {
- return false;
- }
- let target = &ed.text[start..end];
- let all_sub = target.chars().all(|c| char_from_subscript(c) != c);
- let converted: String = if all_sub { target.chars().map(char_from_subscript).collect() } else { target.chars().map(char_to_subscript).collect() };
- if converted != target {
- let conv_len = converted.len();
- ed.text.replace_range(start..end, &converted);
- if ed.selection.is_some() {
- ed.selection = Some(start..start + conv_len);
- }
- true
- } else {
- false
- }
-}
-
-/// A paragraph being edited.
-#[derive(Clone, Debug, PartialEq)]
-pub struct LineEditor {
- pub selection: Option<std::ops::Range<usize>>,
- pub font_resource: Option<String>,
- pub page: usize,
- pub block: usize,
- pub text: String,
- original: String,
- rect: Rect,
- /// The original PDF rectangle, in user space. It is converted again each frame so the editor
- /// stays attached while the page is zoomed, scrolled, or rotated.
- source_rect: [f32; 4],
- multiline: bool,
- source: Option<(pdfcraft_engine::TextBlock, Vec<pdfcraft_engine::TextLine>)>,
- pub(crate) fonts: BTreeMap<String, String>,
- /// The draft extends outside the source container; its frame follows the live draft bounds.
- pub overflow: bool,
- /// The initial source container width in screen pixels.
- max_width: f32,
- /// Current screen-space size. Recomputed from the current page transform before painting.
- size: f32,
- /// Take the keyboard focus on the next frame.
- pub(crate) focus: bool,
- /// Whether the text box had the keyboard at the end of the editor's last frame
- /// ([`lost_focus_once`]).
- had_focus: bool,
- /// The Format text panel's values, and what the paragraph had (to send only changes).
- pub look: pdfcraft_engine::AddedText,
- look0: pdfcraft_engine::AddedText,
- /// A standard family was picked from the font list. The family guessed from a PDF font name
- /// (Calibri reads as Helvetica) can be the one picked, so comparing `look` with `look0` alone
- /// would miss the choice.
- family_chosen: bool,
- /// Underline, line spacing (× size; 0 = the paragraph's own), character spacing (pt) and
- /// horizontal scale (%), and what they were.
- pub extras: Extras,
- extras0: Extras,
-}
-
-#[derive(Clone, Copy, Debug, PartialEq)]
-pub struct Extras {
- pub underline: bool,
- pub line_spacing: f64,
- pub char_spacing: f64,
- pub scale: f64,
-}
-
-impl Default for Extras {
- fn default() -> Self {
- Extras { underline: false, line_spacing: 0.0, char_spacing: 0.0, scale: 100.0 }
- }
-}
-
-impl LineEditor {
- /// What Format text's font list shows: the chosen page font, a standard family picked
- /// instead, or the paragraph's own font (its `/BaseFont` without the subset tag).
- pub(crate) fn font_shown(&self, sources: &[(String, String)]) -> String {
- if let Some(face) = self.font_resource.as_ref().and_then(|r| sources.iter().find(|(res, _)| res == r)).map(|(_, face)| face) {
- return face.clone();
- }
- if self.look.family != self.look0.family || self.family_chosen {
- return self.look.family.label().to_string();
- }
- let base = self.source.as_ref().map(|(block, _)| block.base_font.as_str()).unwrap_or_default();
- // "ABCDEF+Calibri" is a subset of Calibri.
- let name = match base.split_once('+') {
- Some((tag, rest)) if tag.len() == 6 && tag.bytes().all(|b| b.is_ascii_uppercase()) => rest,
- _ => base,
- };
- if name.is_empty() { tl!("Keep source fonts").to_string() } else { name.to_string() }
- }
-
- /// Back to the paragraph's own font: no page font chosen and the family it started with.
- pub(crate) fn keep_source_font(&mut self) {
- self.font_resource = None;
- self.look.family = self.look0.family;
- self.family_chosen = false;
- }
-
- /// A standard family picked from the font list, replacing the paragraph's font even when it
- /// is the family the paragraph's font name reads as.
- pub(crate) fn choose_family(&mut self, family: pdfcraft_engine::FontFamily) {
- self.font_resource = None;
- self.look.family = family;
- self.family_chosen = true;
- }
-
- pub(crate) fn has_changes(&self) -> bool {
- self.changes_with(&self.text)
- }
-
- /// Whether the paragraph with `text` in it differs from what was opened.
- fn changes_with(&self, text: &str) -> bool {
- text != self.original || self.look != self.look0 || self.extras != self.extras0 || self.family_chosen
- }
-
- /// Extra width permitted by the editor. Source containers now remain fixed.
- pub fn growth(&self) -> Option<f32> {
- (self.max_width > self.rect.width()).then_some(self.max_width)
- }
-
- /// Whether the edited text differs from the original (unsaved changes).
- pub fn has_unsaved_text(&self) -> bool {
- self.text != self.original
- }
-
- /// The formatting the panel changed.
- pub fn style(&self) -> pdfcraft_engine::BlockStyle {
- let (l, o) = (&self.look, &self.look0);
- let mut style = pdfcraft_engine::BlockStyle {
- resource: self.font_resource.clone(),
- family: (l.family != o.family || self.family_chosen || l.bold != o.bold || l.italic != o.italic).then_some((l.family, l.bold, l.italic)),
- size: (l.size != o.size).then_some(l.size),
- color: (l.color != o.color).then_some(l.color),
- align: (l.align != o.align).then_some(l.align),
- underline: (self.extras.underline != self.extras0.underline).then_some(self.extras.underline),
- line_spacing: (self.extras.line_spacing != self.extras0.line_spacing && self.extras.line_spacing > 0.0)
- .then_some(self.extras.line_spacing),
- char_spacing: (self.extras.char_spacing != self.extras0.char_spacing).then_some(self.extras.char_spacing),
- scale: (self.extras.scale != self.extras0.scale).then_some(self.extras.scale),
- ..Default::default()
- };
- if let Some(range) = &self.selection
- && (style.family.is_some()
- || style.resource.is_some()
- || style.size.is_some()
- || style.color.is_some()
- || style.underline.is_some()
- || style.char_spacing.is_some()
- || style.scale.is_some())
- {
- style.ranges.push(pdfcraft_engine::RangeStyle {
- range: range.clone(),
- family: style.family.take(),
- resource: style.resource.take(),
- size: style.size.take(),
- color: style.color.take(),
- underline: style.underline.take(),
- char_spacing: style.char_spacing.take(),
- scale: style.scale.take(),
- });
- }
- style
- }
-
- /// After applying formatting: the paragraph now has it.
- pub fn applied(&mut self) {
- self.font_resource = None;
- self.family_chosen = false;
- self.look0 = self.look.clone();
- self.extras0 = self.extras;
- self.original = self.text.clone();
- self.selection = None;
- self.focus = true;
- }
-
- /// Adopt the rewritten paragraph's current geometry before the next overlay frame.
- pub(crate) fn refresh_source(&mut self, block: &pdfcraft_engine::TextBlock, lines: Vec<pdfcraft_engine::TextLine>) {
- self.source_rect = block.rect.map(|v| v as f32);
- self.multiline = block.rows.len() > 1;
- self.source = Some((block.clone(), lines));
- self.text = block.editor_text.clone();
- self.original = self.text.clone();
- }
-
- pub fn selection_formatting(&self, sources: &[(String, String)]) -> SelectionFormatting {
- let Some((block, lines)) = &self.source else {
- return SelectionFormatting {
- font_shown: self.font_shown(sources),
- size: Some(self.look.size),
- family: Some(self.look.family),
- bold: Some(self.look.bold),
- italic: Some(self.look.italic),
- color: Some(self.look.color),
- };
- };
-
- let spans = block.edited_spans(&self.text);
- let matching_lines: Vec<&pdfcraft_engine::TextLine> = match &self.selection {
- Some(range) if range.start < range.end => {
- spans.iter().filter(|(span, _)| span.start < range.end && span.end > range.start).filter_map(|(_, idx)| lines.get(*idx)).collect()
- }
- _ => spans.iter().filter_map(|(_, idx)| lines.get(*idx)).collect(),
- };
-
- if matching_lines.is_empty() {
- return SelectionFormatting {
- font_shown: self.font_shown(sources),
- size: Some(self.look.size),
- family: Some(self.look.family),
- bold: Some(self.look.bold),
- italic: Some(self.look.italic),
- color: Some(self.look.color),
- };
- }
-
- let line_font = |l: &pdfcraft_engine::TextLine| -> String {
- if let Some((_, face)) = sources.iter().find(|(res, _)| res == &l.font) {
- return face.clone();
- }
- let base = l.base_font.as_str();
- let name = match base.split_once('+') {
- Some((tag, rest)) if tag.len() == 6 && tag.bytes().all(|b| b.is_ascii_uppercase()) => rest,
- _ => base,
- };
- if let Some((_, face)) = sources.iter().find(|(_, face)| face.as_str() == name) {
- return face.clone();
- }
- let look = look_of_line(l);
- let lower = name.to_ascii_lowercase();
- if ["times", "serif", "roman", "courier", "helvetica", "arial"].iter().any(|s| lower.contains(s)) {
- return look.family.label().to_string();
- }
- if name.is_empty() { tl!("Keep source fonts").to_string() } else { name.to_string() }
- };
-
- let first_font = line_font(matching_lines[0]);
- let same_font = matching_lines.iter().skip(1).all(|l| line_font(l) == first_font);
- let font_shown = if same_font {
- if self.font_resource.is_some() || self.look.family != self.look0.family || self.family_chosen {
- self.font_shown(sources)
- } else {
- first_font
- }
- } else {
- tl!("Mixed").to_string()
- };
-
- let first_size = (matching_lines[0].size * 10.0).round() / 10.0;
- let same_size = matching_lines.iter().skip(1).all(|l| ((l.size * 10.0).round() / 10.0 - first_size).abs() < 0.05);
- let size = if same_size { Some(first_size) } else { None };
-
- let first_look = look_of_line(matching_lines[0]);
- let same_family = matching_lines.iter().skip(1).all(|l| look_of_line(l).family == first_look.family);
- let family = if same_family { Some(first_look.family) } else { None };
- let same_bold = matching_lines.iter().skip(1).all(|l| l.bold == matching_lines[0].bold);
- let bold = if same_bold { Some(matching_lines[0].bold) } else { None };
- let same_italic = matching_lines.iter().skip(1).all(|l| l.italic == matching_lines[0].italic);
- let italic = if same_italic { Some(matching_lines[0].italic) } else { None };
- let same_color = matching_lines.iter().skip(1).all(|l| l.color == matching_lines[0].color);
- let color = if same_color { Some(matching_lines[0].color) } else { None };
-
- SelectionFormatting { font_shown, size, family, bold, italic, color }
- }
-
- pub(crate) fn sync_selection_look(&mut self, fmt: &SelectionFormatting) {
- if let Some(sz) = fmt.size {
- self.look.size = sz;
- self.look0.size = sz;
- } else {
- self.look.size = 0.0;
- self.look0.size = 0.0;
- }
- if let Some(f) = fmt.family {
- self.look.family = f;
- self.look0.family = f;
- }
- if let Some(b) = fmt.bold {
- self.look.bold = b;
- self.look0.bold = b;
- }
- if let Some(it) = fmt.italic {
- self.look.italic = it;
- self.look0.italic = it;
- }
- if let Some(c) = fmt.color {
- self.look.color = c;
- self.look0.color = c;
- }
- }
-}
-
-#[derive(Clone, Debug, PartialEq)]
-pub struct SelectionFormatting {
- pub font_shown: String,
- pub size: Option<f64>,
- pub family: Option<pdfcraft_engine::FontFamily>,
- pub bold: Option<bool>,
- pub italic: Option<bool>,
- pub color: Option<[f64; 3]>,
-}
-
-fn look_of_line(l: &pdfcraft_engine::TextLine) -> pdfcraft_engine::AddedText {
- source_look(&l.base_font, l.size, l.color, l.bold, l.italic)
-}
-
-/// What a drag on a paragraph box takes hold of.
-#[derive(Clone, Copy, Debug, PartialEq)]
-enum Grip {
- Move,
- /// An edge (screen left or right), dragged to rewrap the paragraph.
- Left,
- Right,
-}
-
-/// A paragraph box being dragged: moved, or (from a handle on its left or right edge) resized.
-#[derive(Clone, Copy, Debug, PartialEq)]
-pub struct BlockDrag {
- page: usize,
- block: usize,
- /// A paragraph index belongs to the document generation where the press was resolved.
- generation: u64,
- /// Where the drag started (screen).
- start: Pos2,
- grip: Grip,
-}
-
-/// How far an edge grip reaches either side of a box's edge (screen pixels).
-const EDGE_REACH: f32 = 6.0;
-/// How far outside an open paragraph's frame the pointer still means the frame (screen pixels).
-const FRAME_REACH: f32 = 4.0;
-
-/// The rewrap handles drawn on a paragraph box's left and right edges (screen).
-fn width_handles(b: Rect) -> [Rect; 2] {
- let h = (b.height() * 0.5).clamp(14.0, 28.0);
- [b.left(), b.right()].map(|x| Rect::from_center_size(Pos2::new(x, b.center().y), egui::vec2(7.0, h)))
-}
-
-/// The edge of `b` that `p` grabs: anywhere along its height, within reach of the line. A narrow
-/// box keeps its middle for moving.
-fn edge_at(b: Rect, p: Pos2) -> Option<Grip> {
- if p.y < b.top() - EDGE_REACH || p.y > b.bottom() + EDGE_REACH {
- return None;
- }
- let inside = EDGE_REACH.min(b.width() / 4.0);
- let (dl, dr) = (p.x - b.left(), b.right() - p.x);
- match (dl >= -EDGE_REACH && dl <= inside, dr >= -EDGE_REACH && dr <= inside) {
- (true, true) if dl <= dr => Some(Grip::Left),
- (_, true) => Some(Grip::Right),
- (true, false) => Some(Grip::Left),
- _ => None,
- }
-}
-
-/// The topmost box under `p` and what it grabs there; edges only on an upright page.
-fn grab_at(boxes: &[Rect], p: Pos2, upright: bool) -> Option<(usize, Grip)> {
- boxes.iter().enumerate().rev().find_map(|(i, b)| match upright.then(|| edge_at(*b, p)).flatten() {
- Some(g) => Some((i, g)),
- None => b.contains(p).then_some((i, Grip::Move)),
- })
-}
-
-/// A paragraph's box on screen: its text rect (user space), with a little room around it.
-fn paragraph_box(xf: &PageXform, info: &DocInfo, page: usize, rect: [f64; 4]) -> Rect {
- xf.user_rect(info, page, rect.map(|v| v as f32)).expand(2.0)
-}
-
-/// The width handles need the page upright (or upside down): on a quarter-turned page the
-/// screen's horizontal is the paragraph's vertical.
-fn has_edges(info: &DocInfo, page: usize) -> bool {
- info.pages.get(page).is_some_and(|p| p.rotation % 180 == 0)
-}
-
-/// Whether a press at `p` takes hold of the width handle of one of the paragraphs `rects` (user
-/// space). The handle is drawn half outside the box and grabs from a little further out still,
-/// where a press is not on the box itself, so area selection must leave it to [`page_input`].
-pub(crate) fn grabs_edge(xf: &PageXform, info: &DocInfo, page: usize, mut rects: impl Iterator<Item = [f64; 4]>, p: Pos2) -> bool {
- has_edges(info, page) && rects.any(|r| edge_at(paragraph_box(xf, info, page, r), p).is_some())
-}
-
-pub(crate) fn user_box(xf: &PageXform, info: &DocInfo, page: usize, r: Rect) -> [f64; 4] {
- let p = &info.pages[page];
- let (a, b) = (xf.screen_to_view(r.min), xf.screen_to_view(r.max));
- let (u, v) = (p.view_to_user(a.0, a.1), p.view_to_user(b.0, b.1));
- [u[0].min(v[0]) as f64, u[1].min(v[1]) as f64, u[0].max(v[0]) as f64, u[1].max(v[1]) as f64]
-}
-
-/// Open `block` on `page` in the inline editor. The box's geometry and source are read from the
-/// `lines` handed in, so callers pass the document's current inventory.
-#[allow(clippy::too_many_arguments)]
-fn open_editor(
- ui: &egui::Ui,
- xf: &PageXform,
- doc: &pdfcraft_engine::Document,
- lines: &[pdfcraft_engine::TextBlock],
- boxes: &[Rect],
- page: usize,
- block: usize,
- view: &mut DocView,
-) {
- view.pending_text_open = None;
- let (Some(l), Some(b)) = (lines.get(block), boxes.get(block)) else { return };
- view.image_selection = None;
- let source_lines = doc.text_lines(page);
- let text = l.editor_text.clone();
- // Screen pixels per point, from the box's width.
- let scale = (b.width() - 4.0) / ((l.rect[2] - l.rect[0]).max(1.0) as f32);
- // How far the editor box may grow: a single-line paragraph's rewrite grows to the
- // page's right edge, a multi-line paragraph rewraps to its own width.
- let right = xf.rect.right().min(view.viewport_rect().right()) - 6.0;
- let max_width = if l.rows.len() == 1 { (right - b.left()).max(b.width()) } else { b.width() };
- view.line_editor = Some(LineEditor {
- selection: None,
- font_resource: None,
- page,
- block,
- text: text.clone(),
- original: text,
- rect: *b,
- source_rect: l.rect.map(|v| v as f32),
- multiline: l.rows.len() > 1,
- source: Some((l.clone(), source_lines)),
- fonts: install_source_fonts(ui.ctx(), doc, page),
- overflow: false,
- max_width,
- size: (l.size as f32 * scale).clamp(8.0, 72.0),
- focus: true,
- had_focus: false,
- look: look_of(l),
- look0: look_of(l),
- family_chosen: false,
- extras: Extras::default(),
- extras0: Extras::default(),
- });
-}
-
-/// Lines and their screen boxes for a page; hover outlines, click opens the editor. Returns
-/// `true` when the pointer was used.
-#[allow(clippy::too_many_arguments)]
-pub(crate) fn page_input(
- ui: &egui::Ui,
- resp: &egui::Response,
- xf: &PageXform,
- ptr: &PagePointer,
- page: usize,
- doc: &pdfcraft_engine::Document,
- lines: &[pdfcraft_engine::TextBlock],
- view: &mut DocView,
- allow_interaction: bool,
-) -> bool {
- let info = &doc.info;
- if view.block_drag.is_some_and(|d| d.generation != doc.edit_generation()) {
- view.block_drag = None;
- return true;
- }
- let boxes: Vec<Rect> = lines.iter().map(|l| paragraph_box(xf, info, page, l.rect)).collect();
- // Outlines stay on their page, like its text (#3061).
- let painter = ui.painter().with_clip_rect(ui.clip_rect().intersect(xf.rect.expand(1.0)));
- let active = view.line_editor.as_ref().filter(|e| e.page == page).map(|e| e.block);
- for (i, b) in boxes.iter().enumerate() {
- if active != Some(i) {
- painter.rect_stroke(*b, CornerRadius::same(2), Stroke::new(0.75, ACCENT.gamma_multiply(0.35)), egui::StrokeKind::Outside);
- }
- }
- // A box a switching click asked for opens now, once the edit queued with that click has
- // applied and `lines`/`boxes` are the document's new inventory (#2022).
- if allow_interaction
- && active.is_none()
- && let Some((open_page, key)) = view.pending_text_open.clone()
- && open_page == page
- {
- // The edit may have regrouped the page: open the paragraph that was clicked, wherever it
- // is now, and none if it was merged into another (#2516).
- match key.find(lines, 0) {
- Some(block) => open_editor(ui, xf, doc, lines, &boxes, page, block, view),
- None => view.pending_text_open = None,
- }
- }
- if !allow_interaction {
- return false;
- }
- let upright = has_edges(info, page);
- let draw_handles = |b: Rect| {
- for h in width_handles(b) {
- painter.rect(h, CornerRadius::same(2), Color32::WHITE, Stroke::new(1.0, ACCENT), egui::StrokeKind::Middle);
- }
- };
- // A drag in progress: the box follows the pointer (or the grabbed edge does); releasing applies it.
- if let Some(d) = view.block_drag.filter(|d| d.page == page)
- && let (Some(b), Some(l)) = (boxes.get(d.block).copied(), lines.get(d.block))
- {
- let p = ptr.pos.unwrap_or(d.start);
- let dx = p.x - d.start.x;
- let preview = match d.grip {
- Grip::Move => b.translate(p - d.start),
- Grip::Left => Rect::from_min_max(Pos2::new((b.left() + dx).min(b.right() - 12.0), b.min.y), b.max),
- Grip::Right => Rect::from_min_max(b.min, Pos2::new((b.right() + dx).max(b.left() + 12.0), b.max.y)),
- };
- painter.rect_stroke(preview, CornerRadius::same(2), Stroke::new(1.5, ACCENT), egui::StrokeKind::Outside);
- let resizing = d.grip != Grip::Move;
- if resizing {
- draw_handles(preview);
- }
- ui.ctx().set_cursor_icon(if resizing { egui::CursorIcon::ResizeHorizontal } else { egui::CursorIcon::Move });
- if resp.drag_stopped() || !ptr.any_down {
- view.block_drag = None;
- let (from, to) = (user_box(xf, info, page, b), user_box(xf, info, page, preview));
- let edit = if resizing {
- // The new width in user space: the box's change, added to the paragraph's own. A
- // moved left side (in user space; on an upside-down page that's the screen's right
- // edge) moves the paragraph with it.
- let width = (l.rect[2] - l.rect[0]) + (to[2] - to[0]) - (from[2] - from[0]);
- let shift = to[0] - from[0];
- let style = pdfcraft_engine::BlockStyle { width: Some(width), offset: (shift != 0.0).then_some([shift, 0.0]), ..Default::default() };
- Edit::EditTextBlock { page, block: d.block, text: l.text.clone(), style }
- } else {
- // Translation must keep the selected source operators. Rewriting unchanged text
- // would also remove unrelated paragraphs that now overlap this one (#594).
- Edit::MoveObjects {
- page,
- objects: vec![ObjectTarget { kind: ObjectKind::Text, index: d.block }],
- offset: [to[0] - from[0], to[1] - from[1]],
- }
- };
- if preview != b {
- view.pending_edit = Some(edit);
- }
- }
- return true;
- }
- // Dragging a box (not while a paragraph is open for typing) moves it; from an edge, resizes it.
- // What it grabs comes from where the button went down, not where the pointer is now: egui
- // only calls it a drag once the pointer has moved a few pixels (or been held a moment), and a
- // quick flick has left the edge by then.
- if resp.drag_started()
- && active.is_none()
- && let Some(o) = ptr.origin
- && let Some((block, grip)) = grab_at(&boxes, o, upright)
- {
- view.block_drag = Some(BlockDrag { page, block, generation: doc.edit_generation(), start: o, grip });
- return true;
- }
- let Some(p) = ptr.within(xf.rect) else { return false };
- let Some((hit, grip)) = grab_at(&boxes, p, upright) else { return false };
- if active != Some(hit) {
- painter.rect_stroke(boxes[hit], CornerRadius::same(2), Stroke::new(1.5, ACCENT), egui::StrokeKind::Outside);
- }
- let on_edge = active.is_none() && grip != Grip::Move;
- if upright && active.is_none() {
- draw_handles(boxes[hit]);
- }
- // A closed paragraph moves when dragged (the four-way arrow says so; a click still opens it
- // for typing); an edge rewraps it. The open one takes the text cursor. Only where the page
- // shows, so the mode bar and side panels over a paragraph scrolled under them keep their own
- // cursor (#2755).
- if resp.contains_pointer() {
- ui.ctx().set_cursor_icon(if on_edge {
- egui::CursorIcon::ResizeHorizontal
- } else if active.is_none() {
- egui::CursorIcon::Move
- } else {
- egui::CursorIcon::Text
- });
- }
- if resp.clicked() {
- view.image_selection = None;
- // A click that moves the editor to another paragraph applies the open one first, so its
- // typed text is not dropped with the switched-away editor (#2022). A click on the open
- // box's own frame, which the editor's overlay does not cover, keeps it open instead.
- if let Some(open) = view.line_editor.as_ref().filter(|e| e.has_changes()) {
- if open.page == page && open.block == hit {
- return true;
- }
- if let Some(old) = view.line_editor.take() {
- let style = old.style();
- if old.text != old.original || style != pdfcraft_engine::BlockStyle::default() {
- view.applied_editor = Some(old.clone());
- view.pending_edit = Some(Edit::EditTextBlock { page: old.page, block: old.block, text: old.text, style });
- }
- }
- // The clicked box opens next frame, from the document with that edit applied.
- view.pending_text_open = lines.get(hit).map(|l| (page, pdfcraft_engine::BlockKey::of(l)));
- return true;
- }
- open_editor(ui, xf, doc, lines, &boxes, page, hit, view);
- }
- true
-}
-
-/// The inline editor; returns the edit once the text is applied.
-pub(crate) fn overlay(ctx: &egui::Context, view: &mut DocView, info: &DocInfo) -> Option<Edit> {
- // Clicks outside the document (the Format text panel) keep the paragraph open. Where the
- // click landed is `interact_pos`: `latest_pos` is gone on the frame a tap lifts.
- let outside = ctx.input(|i| i.pointer.interact_pos()).is_some_and(|p| !view.viewport_rect().contains(p));
- let page = view.line_editor.as_ref()?.page;
- let xf = view.page_xform(page)?;
- let hold = view.objects.hold_editor;
- // An OCR word is invisible text over a scan: the textless background still shows the scanned
- // word, so the editor covers it, as the applied edit will.
- let background_ready = view
- .line_editor
- .as_ref()
- .is_some_and(|ed| view.text_background.ready(ed.page, ed.block) && !ed.source.as_ref().is_some_and(|(b, _)| b.invisible));
- // The measured extent of this paragraph's draft: a click straight from another paragraph
- // opens this one after the frame's measuring, which was the other one's.
- let draft_rect = view
- .line_editor
- .as_ref()
- .and_then(|ed| view.text_background.draft_rect_for(ed.page, ed.block))
- .map(|r| xf.user_rect(info, page, r.map(|v| v as f32)));
- // The editor draws on its page only, as the page itself does: a paragraph running past the
- // page's edge (a converter relying on the page clip) must not cover the next page or the
- // tool bars (#3061).
- let viewport = view.viewport_rect();
- let page_clip = xf.rect.intersect(viewport);
- let ed = view.line_editor.as_mut()?;
- if hold {
- ed.focus = true;
- }
- // Reproject the source box every frame. The page may have been zoomed, scrolled or rotated
- // while the format panel was open.
- // A font definition becomes active at the start of the next egui pass. Keep the source
- // raster visible until then instead of flashing an unrelated interface face.
- if !ctx.fonts(|f| ed.fonts.values().all(|name| f.definitions().families.contains_key(&FontFamily::Name(name.clone().into())))) {
- ctx.request_repaint();
- return None;
- }
- ed.rect = xf.user_rect(info, ed.page, ed.source_rect);
- ed.max_width = ed.rect.width();
- let scale = (ed.rect.width() / (ed.source_rect[2] - ed.source_rect[0]).abs().max(0.01)).max(0.01);
- ed.size = (ed.look.size as f32 * scale).clamp(1.0, 300.0);
- // egui draws the caret at least one row of this font tall. Each row already has its source
- // row's height, so the font stays below every row (half the region's smallest size): on a
- // 12 pt row under a 24 pt title the caret is as tall as the row, not the title.
- let smallest =
- ed.source.as_ref().and_then(|(block, lines)| block.lines.iter().filter_map(|i| lines.get(*i)).map(|l| l.size as f32).reduce(f32::min));
- let font = editor_font(&ed.look, smallest.map_or(ed.size, |s| (s * scale * 0.5).clamp(1.0, 300.0).min(ed.size)));
- let text_color = color32(ed.look.color);
- let block = ed.block;
- let mut done = None;
- let mut reveal = false;
- let mut look = None;
- // No fade-in: while it faded, the page's own copy of the text showed through the cover.
- // Over the page, so only where the document shows: a paragraph scrolled under the mode bar or
- // a side panel must leave them their pointer (#2755). It stays at its paragraph, cut off as
- // the page is, rather than pushed back into the window.
- egui::Area::new(egui::Id::unique("edit-text-line"))
- .order(egui::Order::Foreground)
- .fade_in(false)
- .fixed_pos(Pos2::new(ed.rect.left(), ed.rect.top()))
- .constrain_to(viewport)
- .constrain(false)
- .show(ctx, |ui| {
- ui.set_clip_rect(ui.clip_rect().intersect(page_clip));
- // The editor opens at the source size. Once text changes, show the real draft
- // extent: single rows grow toward the page edge, paragraphs rewrap at their
- // source width, and the visible frame grows/shrinks vertically with their rows.
- // An OCR phrase (several stretched words on one scanned line) also grows rightwards.
- let single_run = ed.source.as_ref().is_some_and(|(block, _)| block.rows.len() == 1 || block.invisible);
- let width = if !ed.multiline && single_run && !ed.text.contains('\n') && ed.has_changes() {
- let job = editor_job(ui, ed, &ed.text, scale, f32::INFINITY);
- let natural = ui.fonts_mut(|f| f.layout_job(job)).size().x;
- natural.max(ed.size * 0.4).min((xf.rect.right() - ed.rect.left() - 36.0 * scale).max(ed.rect.width()))
- } else {
- ed.rect.width().max(1.0)
- };
- ui.set_width(width);
- let measured = editor_galley(ui, ed, &ed.text, scale, width);
- ed.overflow = ed.has_changes() && (measured.rect.width() > ed.rect.width() + 1.5 || measured.rect.height() > ed.rect.height() + 1.5);
- let visible = Rect::from_min_size(ed.rect.min, measured.rect.size().max(egui::vec2(1.0, 1.0)));
- // Unsupported source programs use an interface fallback whose glyph advances
- // can differ from the PDF's. Keep every visible row inside the growing frame.
- let live = draft_rect.map_or(visible, |bounds| bounds.union(visible));
- ui.painter().rect_stroke(live.expand(2.0), CornerRadius::ZERO, Stroke::new(1.5, ACCENT), egui::StrokeKind::Outside);
- // On the frame, a press takes hold of the box (a click selects it, a drag moves it):
- // the pointer says so there, and reads as text inside.
- if let Some(p) = ui.input(|i| i.pointer.hover_pos())
- && ui.clip_rect().contains(p)
- && live.expand(2.0 + FRAME_REACH).contains(p)
- && !live.expand(2.0).contains(p)
- {
- ui.ctx().set_cursor_icon(egui::CursorIcon::Move);
- }
- // White, unless the text is too pale to read on white (white text from a coloured
- // banner, #913): then a dark box, with a caret that shows on it.
- let fill = if background_ready { Color32::TRANSPARENT } else { editor_fill(text_color) };
- // An unchanged paragraph is the page's own text: the editor draws only its frame and
- // caret over it. Once it changes, the textless page goes under the editor's text or,
- // until that background is ready, a cover over the entire source box, including lines
- // the draft no longer occupies. Shrinking the text must never expose a copy. Both are
- // decided after this frame's typing, in places kept under the editor's text.
- let cover = ui.painter().add(egui::Shape::Noop);
- let unchanged = !ed.has_changes();
- egui::Frame::NONE.show(ui, |ui| {
- // A textless PDF preview, or the page itself, keeps its real background through
- // the transparent editor. The temporary opaque cover uses the shared caret-contrast rule.
- ui.visuals_mut().text_cursor.stroke.color = if background_ready || unchanged {
- if luminance(text_color) < 0.5 { Color32::BLACK } else { Color32::WHITE }
- } else {
- caret_color_on(fill)
- };
- let rows = 1;
- let snapshot = ed.clone();
- let mut layouter = |ui: &egui::Ui, text: &dyn egui::TextBuffer, wrap_width: f32| {
- let galley = editor_galley(ui, &snapshot, text.as_str(), scale, wrap_width);
- if snapshot.changes_with(text.as_str()) { galley } else { unseen(galley) }
- };
- let output = egui::TextEdit::multiline(&mut ed.text)
- .id(egui::Id::unique("edit-text-line-input"))
- .font(font.clone())
- .margin(egui::Margin::ZERO)
- .layouter(&mut layouter)
- .text_color(text_color)
- .frame(egui::Frame::NONE)
- .desired_width(width)
- .desired_rows(rows)
- .show(ui);
- // The editor paints over the page with no visible label; name it for assistive tech.
- output.response.response.clone().accessible_name(tl!("Text editing line"));
- if ed.has_changes() {
- if background_ready {
- reveal = true;
- } else {
- ui.painter().set(cover, egui::Shape::rect_filled(ed.rect.expand(1.0).union(output.response.rect), CornerRadius::ZERO, fill));
- }
- }
- look = Some((Arc::clone(&output.galley), output.galley_pos));
- if let Some(cursor) = output.cursor_range {
- let selected = cursor.as_sorted_char_range();
- let byte = |index| ed.text.char_indices().nth(index).map_or(ed.text.len(), |(at, _)| at);
- ed.selection = (!selected.is_empty()).then(|| byte(selected.start.into())..byte(selected.end.into()));
- }
- let r = output.response;
- if r.changed() {
- // The next pass measures the updated draft with the Apply/Save rewrite.
- ctx.request_repaint();
- }
- if ed.focus {
- r.request_focus();
- ed.focus = false;
- }
- let lost = lost_focus_once(&r, &mut ed.had_focus);
- let esc = ui.input(|i| i.key_pressed(egui::Key::Escape));
- let apply = ui.input(|i| i.key_pressed(egui::Key::Enter) && i.modifiers.command);
- if esc {
- done = Some(false);
- } else if apply || (lost && !outside && !hold) {
- done = Some(true);
- }
- });
- });
- if reveal {
- view.text_background.reveal();
- }
- if let Some((galley, pos)) = look {
- view.text_background.remember(&xf, page, block, galley, pos, text_color);
- }
- match done {
- Some(apply) => {
- let ed = view.line_editor.take()?;
- if !apply {
- return None;
- }
- view.applied_editor = Some(ed.clone());
- finished_edit(ed)
- }
- None => None,
- }
-}
-
-/// The edit a closed paragraph editor applies, or `None` when nothing in it changed.
-pub(crate) fn finished_edit(ed: LineEditor) -> Option<Edit> {
- let style = ed.style();
- (ed.text != ed.original || style != pdfcraft_engine::BlockStyle::default()).then_some(Edit::EditTextBlock {
- page: ed.page,
- block: ed.block,
- text: ed.text,
- style,
- })
-}
-
-/// Whether an editor's text box `r` lost the keyboard this frame, given whether it `had` it at
-/// the end of the editor's last frame (updated here). egui's `lost_focus` holds for a second
-/// frame as well, and an editor that judges a click away by where the click landed must judge it
-/// once, on the click's frame: on the next, a tap's position is gone (egui-winit sends
-/// `PointerGone` with every touch release) and a mouse may have moved on.
-pub(crate) fn lost_focus_once(r: &egui::Response, had: &mut bool) -> bool {
- let has = r.has_focus();
- std::mem::replace(had, has) && !has
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn the_rotate_knob_moves_below_when_there_is_no_room_above() {
- let view = Rect::from_min_max(Pos2::new(0.0, 100.0), Pos2::new(500.0, 500.0));
- let roomy = Rect::from_min_max(Pos2::new(100.0, 200.0), Pos2::new(200.0, 250.0));
- assert_eq!(rotate_knob(roomy, view).0, Pos2::new(150.0, 178.0));
- let at_top = Rect::from_min_max(Pos2::new(100.0, 100.0), Pos2::new(200.0, 150.0));
- let (knob, stem) = rotate_knob(at_top, view);
- assert_eq!((knob, stem), (Pos2::new(150.0, 172.0), Pos2::new(150.0, 150.0)));
- }
-
- #[test]
- fn the_rotate_knob_measures_clockwise_degrees_from_straight_up() {
- let c = Pos2::new(100.0, 100.0);
- let at = |x: f32, y: f32| turn_degrees(c, Pos2::new(x, y), false);
- assert!(at(100.0, 0.0).abs() < 1e-3);
- assert!((at(200.0, 100.0) - 90.0).abs() < 1e-3, "right is a clockwise quarter");
- assert!((at(0.0, 100.0) + 90.0).abs() < 1e-3);
- assert!((at(100.0, 200.0).abs() - 180.0).abs() < 1e-3);
- // Shift rounds to 15 degrees; the centre and non-finite points turn nothing.
- assert_eq!(turn_degrees(c, Pos2::new(180.0, 50.0), true) % 15.0, 0.0);
- assert_eq!(at(101.0, 101.0), 0.0);
- assert_eq!(at(f32::NAN, 5.0), 0.0);
- }
-
- /// An app with one text document open, and an editor on its first paragraph.
- fn preview_app() -> (crate::PdfCraftApp, LineEditor) {
- let mut app = crate::PdfCraftApp::new();
- let bytes = app.session.create_from_text("Preview", "Preview text").unwrap();
- app.open_bytes("preview.pdf", None, bytes.as_ref().clone()).unwrap();
- let doc = app.session.get(app.views[0].id).unwrap();
- let block = doc.text_blocks(0).remove(0);
- let ed = LineEditor {
- selection: None,
- font_resource: None,
- page: 0,
- block: 0,
- text: block.text.clone(),
- original: block.text.clone(),
- rect: Rect::NOTHING,
- source_rect: block.rect.map(|v| v as f32),
- multiline: block.rows.len() > 1,
- source: None,
- fonts: BTreeMap::new(),
- overflow: false,
- max_width: 400.0,
- size: block.size as f32,
- focus: true,
- had_focus: false,
- look: look_of(&block),
- look0: look_of(&block),
- family_chosen: false,
- extras: Extras::default(),
- extras0: Extras::default(),
- };
- (app, ed)
- }
-
- #[test]
- fn picking_the_family_the_font_name_reads_as_still_changes_the_font() {
- // A Calibri paragraph reads as Helvetica; picking Helvetica from the list used to leave
- // `look` equal to what the paragraph had, so no family change was sent and Calibri stayed.
- let (_app, mut ed) = preview_app();
- let family = ed.look0.family;
- assert_eq!(ed.style().family, None, "nothing chosen yet");
- ed.choose_family(family);
- assert_eq!(ed.style().family, Some((family, ed.look.bold, ed.look.italic)));
- assert!(ed.has_changes());
- assert_eq!(ed.font_shown(&[]), family.label());
- ed.keep_source_font();
- assert_eq!(ed.style().family, None, "Keep source fonts withdraws the choice");
- ed.choose_family(family);
- ed.applied();
- assert_eq!(ed.style().family, None, "an applied choice is the paragraph's font now");
- }
-
- #[test]
- fn a_loaded_font_is_applied_to_the_paragraph_being_edited() {
- // Loading a font used to only register it on the page: the paragraph kept its source
- // face until the font was found again in the document-font menu (#2591).
- let (mut app, ed) = preview_app();
- app.views[0].line_editor = Some(ed);
- let inter = include_bytes!("../../../../assets/fonts/Inter-Regular.ttf").to_vec();
- app.use_files(crate::files::FilePurpose::TextFont { page: 0 }, vec![("Inter-Regular.ttf".into(), inter)]);
- let doc = app.session.get(app.views[0].id).unwrap();
- let lines = doc.text_lines(0);
- assert_eq!(lines.iter().map(|l| l.text.as_str()).collect::<String>(), "Preview text");
- assert!(lines.iter().all(|l| l.base_font == "Inter-Regular"), "{:?}", lines.iter().map(|l| &l.base_font).collect::<Vec<_>>());
- assert!(app.views[0].line_editor.is_some(), "the paragraph stays open for editing");
- }
-
- #[test]
- fn save_applies_the_paragraph_open_in_the_editor() {
- // Save wrote the file without the paragraph still open in the editor (#3496).
- let (mut app, mut ed) = preview_app();
- ed.text = "Text preview".into();
- app.views[0].line_editor = Some(ed);
- let dir = std::env::temp_dir().join(format!("pdfcraft-ui-open-paragraph-{}", std::process::id()));
- let _ = std::fs::remove_dir_all(&dir);
- std::fs::create_dir_all(&dir).unwrap();
- app.save_override = Some(dir.join("out.pdf").to_string_lossy().into_owned());
-
- assert!(app.save_active(crate::SaveTarget::InPlace));
- assert!(app.views[0].line_editor.is_none());
- let doc = app.session.get(app.views[0].id).unwrap();
- assert_eq!(doc.text_lines(0).iter().map(|l| l.text.as_str()).collect::<String>(), "Text preview");
- let _ = std::fs::remove_dir_all(&dir);
- }
-
- #[test]
- fn a_refused_text_box_does_not_lose_the_open_paragraph() {
- let (mut app, mut ed) = preview_app();
- ed.text = "Text preview".into();
- app.views[0].line_editor = Some(ed);
- let draft = crate::content_ui::TextDraft {
- page: 9,
- index: None,
- rect: [20.0, 20.0, 120.0, 40.0],
- text: "Typed text".into(),
- style: crate::content_ui::default_style(),
- focus: true,
- };
- app.views[0].content.draft = Some(draft.clone());
-
- assert!(!app.commit_typing_in(app.views[0].id));
- assert_eq!(app.views[0].content.draft, Some(draft), "the refused text box stays open");
- assert!(app.views[0].line_editor.is_none(), "the paragraph was applied");
- let doc = app.session.get(app.views[0].id).unwrap();
- assert_eq!(doc.text_lines(0).iter().map(|l| l.text.as_str()).collect::<String>(), "Text preview");
- }
-
- #[test]
- fn a_refused_paragraph_stays_open_with_its_text() {
- let (mut app, mut ed) = preview_app();
- ed.text = "Text preview".into();
- ed.page = 9;
- app.views[0].line_editor = Some(ed.clone());
-
- assert!(!app.commit_typing_in(app.views[0].id));
- assert_eq!(app.views[0].line_editor, Some(ed), "the paragraph keeps its unsaved text");
- }
-
- #[test]
- fn text_background_is_cached_without_editing_and_released_on_cancel() {
- let (app, ed) = preview_app();
- let doc = app.session.get(app.views[0].id).unwrap();
- let source = doc.bytes.clone();
- let generation = doc.edit_generation();
- let ctx = egui::Context::default();
- let mut background = TextBackground::default();
- for _ in 0..100 {
- background.prepare(&ctx, doc, Some(&ed), None, 1.0);
- if background.ready(0, 0) {
- break;
- }
- std::thread::sleep(std::time::Duration::from_millis(5));
- }
- assert!(background.ready(0, 0));
- assert!(!background.pending());
- let texture = background.texture.as_ref().unwrap().id();
- background.prepare(&ctx, doc, Some(&ed), None, 1.0);
- assert_eq!(background.texture.as_ref().unwrap().id(), texture);
- assert_eq!(doc.bytes, source);
- assert_eq!(doc.edit_generation(), generation);
- assert!(!doc.dirty && doc.can_undo().is_none());
- background.prepare(&ctx, doc, None, None, 1.0);
- assert!(background.texture.is_none() && background.renderer.is_none());
- }
-
- #[test]
- fn the_editing_background_stays_sharp_on_a_zoomed_page() {
- // While a paragraph is open, the page around it is drawn from this one raster: it is
- // asked for at the tiling threshold, not the 2048-pixel backdrop side, which went soft
- // beyond about 1.2x on a Retina display.
- let (app, ed) = preview_app();
- let doc = app.session.get(app.views[0].id).unwrap();
- let page = &doc.info.pages[0];
- let ctx = egui::Context::default();
- ctx.begin_pass(egui::RawInput { max_texture_side: Some(16384), ..Default::default() });
- let mut background = TextBackground::default();
- background.prepare(&ctx, doc, Some(&ed), None, 8.0);
- let expected = 8.0f32.min(crate::canvas::TILE_THRESHOLD / page.width.max(page.height));
- assert!(expected > crate::canvas::BASE_SIDE / page.width.max(page.height), "the test page needs the larger side");
- assert_eq!(background.tag, Some((expected * 1000.0) as u64));
- // A GPU that can't hold such a texture caps it.
- ctx.end_pass().textures_delta.clear();
- ctx.begin_pass(egui::RawInput { max_texture_side: Some(2048), ..Default::default() });
- let mut small = TextBackground::default();
- small.prepare(&ctx, doc, Some(&ed), None, 8.0);
- assert_eq!(small.tag, Some(((2048.0 / page.width.max(page.height)) * 1000.0) as u64));
- ctx.end_pass().textures_delta.clear();
- }
-
- #[test]
- fn pale_text_is_edited_on_a_dark_box() {
- // #913: white text from a coloured banner was typed onto a white box and vanished.
- for pale in [Color32::WHITE, Color32::from_rgb(0xFF, 0xFF, 0x00), Color32::from_gray(0xE0), Color32::from_rgb(0xFF, 0xA5, 0x00)] {
- assert_eq!(editor_fill(pale), DARK_EDITOR_FILL, "{pale:?}");
- assert!(contrast(pale, editor_fill(pale)) >= 4.5, "{pale:?} is readable");
- }
- // Ordinary dark or saturated text keeps the white box.
- for dark in [Color32::BLACK, Color32::from_rgb(0x1F, 0x2A, 0x6B), Color32::from_rgb(0xC0, 0x00, 0x00), Color32::from_gray(0x60)] {
- assert_eq!(editor_fill(dark), Color32::WHITE, "{dark:?}");
- }
- }
-
- #[test]
- fn caret_contrasts_with_its_fill() {
- assert_eq!(caret_color_on(Color32::WHITE), Color32::BLACK);
- assert_eq!(caret_color_on(Color32::from_rgb(0xFF, 0xFF, 0xF4)), Color32::BLACK);
- assert_eq!(caret_color_on(Color32::BLACK), Color32::WHITE);
- assert_eq!(caret_color_on(DARK_EDITOR_FILL), Color32::WHITE);
- }
-
- #[test]
- fn bullet_list_toggles_and_preserves_content() {
- let mut text = "First line\nSecond line\n\nThird line".to_string();
- assert!(!is_bulleted(&text));
- assert!(toggle_bullet_list(&mut text));
- assert!(is_bulleted(&text));
- assert_eq!(text, "• First line\n• Second line\n\n• Third line");
-
- // Toggling again removes bullets
- assert!(toggle_bullet_list(&mut text));
- assert!(!is_bulleted(&text));
- assert_eq!(text, "First line\nSecond line\n\nThird line");
- }
-
- #[test]
- fn numbered_list_toggles_and_preserves_content() {
- let mut text = "Item A\nItem B\n\nItem C".to_string();
- assert!(!is_numbered(&text));
- assert!(toggle_numbered_list(&mut text));
- assert!(is_numbered(&text));
- assert_eq!(text, "1. Item A\n2. Item B\n\n3. Item C");
-
- // Toggling again removes numbering
- assert!(toggle_numbered_list(&mut text));
- assert!(!is_numbered(&text));
- assert_eq!(text, "Item A\nItem B\n\nItem C");
- }
-
- #[test]
- fn superscript_and_subscript_conversion() {
- let mut ed = LineEditor {
- page: 0,
- block: 0,
- text: "E = mc2".to_string(),
- original: "E = mc2".to_string(),
- rect: egui::Rect::ZERO,
- source_rect: [0.0; 4],
- max_width: 100.0,
- overflow: false,
- selection: Some(6..7), // selecting '2'
- font_resource: None,
- fonts: std::collections::BTreeMap::new(),
- source: None,
- multiline: false,
- size: 12.0,
- family_chosen: false,
- focus: true,
- had_focus: false,
- look: pdfcraft_engine::AddedText::default(),
- look0: pdfcraft_engine::AddedText::default(),
- extras: Extras::default(),
- extras0: Extras::default(),
- };
-
- assert!(toggle_superscript(&mut ed));
- assert_eq!(ed.text, "E = mc²");
- // Toggling superscript again returns to normal '2'
- assert!(toggle_superscript(&mut ed));
- assert_eq!(ed.text, "E = mc2");
-
- // Test subscript on H2O
- ed.text = "H2O".to_string();
- ed.selection = Some(1..2); // selecting '2'
- assert!(toggle_subscript(&mut ed));
- assert_eq!(ed.text, "H₂O");
- assert!(toggle_subscript(&mut ed));
- assert_eq!(ed.text, "H2O");
- }
-
- #[test]
- fn value_based_line_spacing_in_style() {
- let ed = LineEditor {
- page: 0,
- block: 0,
- text: "Paragraph text".to_string(),
- original: "Paragraph text".to_string(),
- rect: egui::Rect::ZERO,
- source_rect: [0.0; 4],
- max_width: 100.0,
- overflow: false,
- selection: None,
- font_resource: None,
- fonts: std::collections::BTreeMap::new(),
- source: None,
- multiline: false,
- size: 12.0,
- family_chosen: false,
- focus: true,
- had_focus: false,
- look: pdfcraft_engine::AddedText::default(),
- look0: pdfcraft_engine::AddedText::default(),
- extras: Extras { line_spacing: 1.33, underline: true, ..Default::default() },
- extras0: Extras::default(),
- };
- let style = ed.style();
- assert_eq!(style.line_spacing, Some(1.33));
- assert_eq!(style.underline, Some(true));
- }
-}
+//! Edit a PDF ▸ Edit text & images: boxes around the paragraphs and images already on the page.
+//! Click a paragraph to edit it in place (⌘Enter or clicking away applies and rewraps it to the
+//! box, Esc cancels); drag it to move it, or drag the handle on its left or right edge to rewrap
+//! it to a new width. Click an image to select it: drag to move, drag a corner to resize (keeping
+//! its proportions), right-click for rotate, flip, replace, save and delete; Delete removes it.
+
+use std::collections::BTreeMap;
+use std::sync::Arc;
+
+use egui::{Color32, CornerRadius, FontFamily, FontId, Pos2, Rect, Stroke, pos2};
+use pdfcraft_engine::{Edit, ObjectKind, ObjectTarget};
+use pdfcraft_render::DocInfo;
+
+use crate::canvas::{DocView, PageXform};
+use crate::page_pointer::PagePointer;
+
+mod background;
+mod image;
+mod layout;
+
+pub(crate) use background::TextBackground;
+pub use image::{CropMode, DragTarget, ImageAction, ImageDrag, ImageHandle, ImageSelection, image_menu_id};
+pub(crate) use image::{Matrix, image_context_menu, image_input, image_owns_pointer, quad_contains, user_to_screen};
+#[cfg(test)]
+use image::{rotate_knob, turn_degrees};
+#[cfg(test)]
+use layout::{DARK_EDITOR_FILL, contrast};
+pub(crate) use layout::{caret_color_on, editor_fill, editor_font, install_source_fonts};
+use layout::{color32, editor_galley, editor_job, look_of, luminance, source_look, unseen};
+
+const ACCENT: Color32 = Color32::from_rgb(0x14, 0x73, 0xE6);
+
+#[derive(Clone, Copy, PartialEq)]
+enum TextTarget {
+ Block(usize),
+ Added(usize),
+}
+
+/// How many faint Edit-text outlines are drawn per page per frame. CAD plots can draw
+/// ~1000 tiny images on one page; stroking all of them every frame (plus a hover query
+/// per box) stalls the UI. Past this, only the selected and hovered boxes are outlined:
+/// hit-testing still covers every image, so nothing becomes unselectable.
+pub(crate) const MAX_OUTLINES: usize = 250;
+
+pub fn is_bulleted(text: &str) -> bool {
+ let mut lines = text.lines();
+ let Some(first) = lines.next() else { return false };
+ first.trim_start().starts_with("• ") || first.trim_start().starts_with("- ")
+}
+
+pub fn is_numbered(text: &str) -> bool {
+ let mut lines = text.lines();
+ let Some(first) = lines.next() else { return false };
+ let t = first.trim_start();
+ let num_end = t.find('.').unwrap_or(0);
+ num_end > 0 && t[..num_end].chars().all(|c| c.is_ascii_digit()) && t[num_end..].starts_with(". ")
+}
+
+pub fn toggle_bullet_list(text: &mut String) -> bool {
+ let lines: Vec<&str> = text.lines().collect();
+ if lines.is_empty() {
+ return false;
+ }
+ let all_bulleted = lines.iter().all(|l| {
+ let t = l.trim_start();
+ t.is_empty() || t.starts_with("• ") || t.starts_with("- ")
+ });
+ let mut new_text = String::with_capacity(text.len() + 16);
+ for (i, line) in lines.iter().enumerate() {
+ if i > 0 {
+ new_text.push('\n');
+ }
+ let trimmed = line.trim_start();
+ if all_bulleted {
+ if let Some(rest) = trimmed.strip_prefix("• ").or_else(|| trimmed.strip_prefix("- ")) {
+ new_text.push_str(rest);
+ } else {
+ new_text.push_str(line);
+ }
+ } else if trimmed.is_empty() || trimmed.starts_with("• ") {
+ new_text.push_str(line);
+ } else {
+ new_text.push_str("• ");
+ new_text.push_str(line);
+ }
+ }
+ if new_text != *text {
+ *text = new_text;
+ true
+ } else {
+ false
+ }
+}
+
+pub fn toggle_numbered_list(text: &mut String) -> bool {
+ let lines: Vec<&str> = text.lines().collect();
+ if lines.is_empty() {
+ return false;
+ }
+ let is_num_line = |l: &str| {
+ let t = l.trim_start();
+ if t.is_empty() {
+ return true;
+ }
+ let dot_idx = t.find('.').unwrap_or(0);
+ dot_idx > 0 && t[..dot_idx].chars().all(|c| c.is_ascii_digit()) && t[dot_idx..].starts_with(". ")
+ };
+ let all_numbered = lines.iter().all(|l| is_num_line(l));
+ let mut new_text = String::with_capacity(text.len() + 16);
+ let mut num = 1;
+ for (i, line) in lines.iter().enumerate() {
+ if i > 0 {
+ new_text.push('\n');
+ }
+ let t = line.trim_start();
+ if all_numbered {
+ if let Some(dot_idx) = t.find('.')
+ && dot_idx > 0
+ && t[..dot_idx].chars().all(|c| c.is_ascii_digit())
+ && t[dot_idx..].starts_with(". ")
+ {
+ new_text.push_str(t.get(dot_idx + 2..).unwrap_or(""));
+ continue;
+ }
+ new_text.push_str(line);
+ } else if t.is_empty() {
+ new_text.push_str(line);
+ } else {
+ use std::fmt::Write as _;
+ let _ = write!(new_text, "{num}. ");
+ new_text.push_str(t);
+ num += 1;
+ }
+ }
+ if new_text != *text {
+ *text = new_text;
+ true
+ } else {
+ false
+ }
+}
+
+pub fn char_to_superscript(c: char) -> char {
+ match c {
+ '0' => '⁰',
+ '1' => '¹',
+ '2' => '²',
+ '3' => '³',
+ '4' => '⁴',
+ '5' => '⁵',
+ '6' => '⁶',
+ '7' => '⁷',
+ '8' => '⁸',
+ '9' => '⁹',
+ '+' => '⁺',
+ '-' | '−' => '⁻',
+ '=' => '⁼',
+ '(' => '⁽',
+ ')' => '⁾',
+ 'a' => 'ᵃ',
+ 'b' => 'ᵇ',
+ 'c' => 'ᶜ',
+ 'd' => 'ᵈ',
+ 'e' => 'ᵉ',
+ 'f' => 'ᶠ',
+ 'g' => 'ᵍ',
+ 'h' => 'ʰ',
+ 'i' => 'ⁱ',
+ 'j' => 'ʲ',
+ 'k' => 'ᵏ',
+ 'l' => 'ˡ',
+ 'm' => 'ᵐ',
+ 'n' => 'ⁿ',
+ 'o' => 'ᵒ',
+ 'p' => 'ᵖ',
+ 'r' => 'ʳ',
+ 's' => 'ˢ',
+ 't' => 'ᵗ',
+ 'u' => 'ᵘ',
+ 'v' => 'ᵛ',
+ 'w' => 'ʷ',
+ 'x' => 'ˣ',
+ 'y' => 'ʸ',
+ 'z' => 'ᶻ',
+ 'A' => 'ᴬ',
+ 'B' => 'ᴮ',
+ 'D' => 'ᴰ',
+ 'E' => 'ᴱ',
+ 'G' => 'ᴳ',
+ 'H' => 'ᴴ',
+ 'I' => 'ᴵ',
+ 'J' => 'ᴶ',
+ 'K' => 'ᴷ',
+ 'L' => 'ᴸ',
+ 'M' => 'ᴹ',
+ 'N' => 'ᴺ',
+ 'O' => 'ᴼ',
+ 'P' => 'ᴾ',
+ 'R' => 'ᴿ',
+ 'T' => 'ᵀ',
+ 'U' => 'ᵁ',
+ 'V' => 'ⱽ',
+ 'W' => 'ᵂ',
+ other => other,
+ }
+}
+
+pub fn char_from_superscript(c: char) -> char {
+ match c {
+ '⁰' => '0',
+ '¹' => '1',
+ '²' => '2',
+ '³' => '3',
+ '⁴' => '4',
+ '⁵' => '5',
+ '⁶' => '6',
+ '⁷' => '7',
+ '⁸' => '8',
+ '⁹' => '9',
+ '⁺' => '+',
+ '⁻' => '-',
+ '⁼' => '=',
+ '⁽' => '(',
+ '⁾' => ')',
+ 'ᵃ' => 'a',
+ 'ᵇ' => 'b',
+ 'ᶜ' => 'c',
+ 'ᵈ' => 'd',
+ 'ᵉ' => 'e',
+ 'ᶠ' => 'f',
+ 'ᵍ' => 'g',
+ 'ʰ' => 'h',
+ 'ⁱ' => 'i',
+ 'ʲ' => 'j',
+ 'ᵏ' => 'k',
+ 'ˡ' => 'l',
+ 'ᵐ' => 'm',
+ 'ⁿ' => 'n',
+ 'ᵒ' => 'o',
+ 'ᵖ' => 'p',
+ 'ʳ' => 'r',
+ 'ˢ' => 's',
+ 'ᵗ' => 't',
+ 'ᵘ' => 'u',
+ 'ᵛ' => 'v',
+ 'ʷ' => 'w',
+ 'ˣ' => 'x',
+ 'ʸ' => 'y',
+ 'ᶻ' => 'z',
+ 'ᴬ' => 'A',
+ 'ᴮ' => 'B',
+ 'ᴰ' => 'D',
+ 'ᴱ' => 'E',
+ 'ᴳ' => 'G',
+ 'ᴴ' => 'H',
+ 'ᴵ' => 'I',
+ 'ᴶ' => 'J',
+ 'ᴷ' => 'K',
+ 'ᴸ' => 'L',
+ 'ᴹ' => 'M',
+ 'ᴺ' => 'N',
+ 'ᴼ' => 'O',
+ 'ᴾ' => 'P',
+ 'ᴿ' => 'R',
+ 'ᵀ' => 'T',
+ 'ᵁ' => 'U',
+ 'ⱽ' => 'V',
+ 'ᵂ' => 'W',
+ other => other,
+ }
+}
+
+pub fn char_to_subscript(c: char) -> char {
+ match c {
+ '0' => '₀',
+ '1' => '₁',
+ '2' => '₂',
+ '3' => '₃',
+ '4' => '₄',
+ '5' => '₅',
+ '6' => '₆',
+ '7' => '₇',
+ '8' => '₈',
+ '9' => '₉',
+ '+' => '₊',
+ '-' | '−' => '₋',
+ '=' => '₌',
+ '(' => '₍',
+ ')' => '₎',
+ 'a' => 'ₐ',
+ 'e' => 'ₑ',
+ 'h' => 'ₕ',
+ 'i' => 'ᵢ',
+ 'j' => 'ⱼ',
+ 'k' => 'ₖ',
+ 'l' => 'ₗ',
+ 'm' => 'ₘ',
+ 'n' => 'ₙ',
+ 'o' => 'ₒ',
+ 'p' => 'ₚ',
+ 'r' => 'ᵣ',
+ 's' => 'ₛ',
+ 't' => 'ₜ',
+ 'u' => 'ᵤ',
+ 'v' => 'ᵥ',
+ 'x' => 'ₓ',
+ other => other,
+ }
+}
+
+pub fn char_from_subscript(c: char) -> char {
+ match c {
+ '₀' => '0',
+ '₁' => '1',
+ '₂' => '2',
+ '₃' => '3',
+ '₄' => '4',
+ '₅' => '5',
+ '₆' => '6',
+ '₇' => '7',
+ '₈' => '8',
+ '₉' => '9',
+ '₊' => '+',
+ '₋' => '-',
+ '₌' => '=',
+ '₍' => '(',
+ '₎' => ')',
+ 'ₐ' => 'a',
+ 'ₑ' => 'e',
+ 'ₕ' => 'h',
+ 'ᵢ' => 'i',
+ 'ⱼ' => 'j',
+ 'ₖ' => 'k',
+ 'ₗ' => 'l',
+ 'ₘ' => 'm',
+ 'ₙ' => 'n',
+ 'ₒ' => 'o',
+ 'ₚ' => 'p',
+ 'ᵣ' => 'r',
+ 'ₛ' => 's',
+ 'ₜ' => 't',
+ 'ᵤ' => 'u',
+ 'ᵥ' => 'v',
+ 'ₓ' => 'x',
+ other => other,
+ }
+}
+
+fn snap_char_boundaries(s: &str, start: usize, end: usize) -> (usize, usize) {
+ let mut s_idx = start.min(s.len());
+ while s_idx > 0 && !s.is_char_boundary(s_idx) {
+ s_idx -= 1;
+ }
+ let mut e_idx = end.min(s.len());
+ while e_idx < s.len() && !s.is_char_boundary(e_idx) {
+ e_idx += 1;
+ }
+ (s_idx, e_idx)
+}
+
+pub fn toggle_superscript(ed: &mut LineEditor) -> bool {
+ let (s_pos, e_pos) = if let Some(r) = &ed.selection { (r.start.min(ed.text.len()), r.end.min(ed.text.len())) } else { (0, ed.text.len()) };
+ let (start, end) = snap_char_boundaries(&ed.text, s_pos, e_pos);
+ if start >= end {
+ return false;
+ }
+ let target = &ed.text[start..end];
+ let all_sup = target.chars().all(|c| char_from_superscript(c) != c);
+ let converted: String =
+ if all_sup { target.chars().map(char_from_superscript).collect() } else { target.chars().map(char_to_superscript).collect() };
+ if converted != target {
+ let conv_len = converted.len();
+ ed.text.replace_range(start..end, &converted);
+ if ed.selection.is_some() {
+ ed.selection = Some(start..start + conv_len);
+ }
+ true
+ } else {
+ false
+ }
+}
+
+pub fn toggle_subscript(ed: &mut LineEditor) -> bool {
+ let (s_pos, e_pos) = if let Some(r) = &ed.selection { (r.start.min(ed.text.len()), r.end.min(ed.text.len())) } else { (0, ed.text.len()) };
+ let (start, end) = snap_char_boundaries(&ed.text, s_pos, e_pos);
+ if start >= end {
+ return false;
+ }
+ let target = &ed.text[start..end];
+ let all_sub = target.chars().all(|c| char_from_subscript(c) != c);
+ let converted: String = if all_sub { target.chars().map(char_from_subscript).collect() } else { target.chars().map(char_to_subscript).collect() };
+ if converted != target {
+ let conv_len = converted.len();
+ ed.text.replace_range(start..end, &converted);
+ if ed.selection.is_some() {
+ ed.selection = Some(start..start + conv_len);
+ }
+ true
+ } else {
+ false
+ }
+}
+
+/// A paragraph being edited.
+#[derive(Clone, Debug, PartialEq)]
+pub struct LineEditor {
+ pub selection: Option<std::ops::Range<usize>>,
+ pub font_resource: Option<String>,
+ pub page: usize,
+ pub block: usize,
+ pub text: String,
+ original: String,
+ rect: Rect,
+ /// The original PDF rectangle, in user space. It is converted again each frame so the editor
+ /// stays attached while the page is zoomed, scrolled, or rotated.
+ source_rect: [f32; 4],
+ multiline: bool,
+ source: Option<(pdfcraft_engine::TextBlock, Vec<pdfcraft_engine::TextLine>)>,
+ pub(crate) fonts: BTreeMap<String, String>,
+ /// The draft extends outside the source container; its frame follows the live draft bounds.
+ pub overflow: bool,
+ /// The initial source container width in screen pixels.
+ max_width: f32,
+ /// Current screen-space size. Recomputed from the current page transform before painting.
+ size: f32,
+ /// Take the keyboard focus on the next frame.
+ pub(crate) focus: bool,
+ /// Whether the text box had the keyboard at the end of the editor's last frame
+ /// ([`lost_focus_once`]).
+ had_focus: bool,
+ /// The Format text panel's values, and what the paragraph had (to send only changes).
+ pub look: pdfcraft_engine::AddedText,
+ look0: pdfcraft_engine::AddedText,
+ /// A standard family was picked from the font list. The family guessed from a PDF font name
+ /// (Calibri reads as Helvetica) can be the one picked, so comparing `look` with `look0` alone
+ /// would miss the choice.
+ family_chosen: bool,
+ /// Underline, line spacing (× size; 0 = the paragraph's own), character spacing (pt) and
+ /// horizontal scale (%), and what they were.
+ pub extras: Extras,
+ extras0: Extras,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct Extras {
+ pub underline: bool,
+ pub line_spacing: f64,
+ pub char_spacing: f64,
+ pub scale: f64,
+}
+
+impl Default for Extras {
+ fn default() -> Self {
+ Extras { underline: false, line_spacing: 0.0, char_spacing: 0.0, scale: 100.0 }
+ }
+}
+
+impl LineEditor {
+ /// What Format text's font list shows: the chosen page font, a standard family picked
+ /// instead, or the paragraph's own font (its `/BaseFont` without the subset tag).
+ pub(crate) fn font_shown(&self, sources: &[(String, String)]) -> String {
+ if let Some(face) = self.font_resource.as_ref().and_then(|r| sources.iter().find(|(res, _)| res == r)).map(|(_, face)| face) {
+ return face.clone();
+ }
+ if self.look.family != self.look0.family || self.family_chosen {
+ return self.look.family.label().to_string();
+ }
+ let base = self.source.as_ref().map(|(block, _)| block.base_font.as_str()).unwrap_or_default();
+ // "ABCDEF+Calibri" is a subset of Calibri.
+ let name = match base.split_once('+') {
+ Some((tag, rest)) if tag.len() == 6 && tag.bytes().all(|b| b.is_ascii_uppercase()) => rest,
+ _ => base,
+ };
+ if name.is_empty() { tl!("Keep source fonts").to_string() } else { name.to_string() }
+ }
+
+ /// Back to the paragraph's own font: no page font chosen and the family it started with.
+ pub(crate) fn keep_source_font(&mut self) {
+ self.font_resource = None;
+ self.look.family = self.look0.family;
+ self.family_chosen = false;
+ }
+
+ /// A standard family picked from the font list, replacing the paragraph's font even when it
+ /// is the family the paragraph's font name reads as.
+ pub(crate) fn choose_family(&mut self, family: pdfcraft_engine::FontFamily) {
+ self.font_resource = None;
+ self.look.family = family;
+ self.family_chosen = true;
+ }
+
+ pub(crate) fn has_changes(&self) -> bool {
+ self.changes_with(&self.text)
+ }
+
+ /// Whether the paragraph with `text` in it differs from what was opened.
+ fn changes_with(&self, text: &str) -> bool {
+ text != self.original || self.look != self.look0 || self.extras != self.extras0 || self.family_chosen
+ }
+
+ /// Extra width permitted by the editor. Source containers now remain fixed.
+ pub fn growth(&self) -> Option<f32> {
+ (self.max_width > self.rect.width()).then_some(self.max_width)
+ }
+
+ /// Whether the edited text differs from the original (unsaved changes).
+ pub fn has_unsaved_text(&self) -> bool {
+ self.text != self.original
+ }
+
+ /// The formatting the panel changed.
+ pub fn style(&self) -> pdfcraft_engine::BlockStyle {
+ let (l, o) = (&self.look, &self.look0);
+ let mut style = pdfcraft_engine::BlockStyle {
+ resource: self.font_resource.clone(),
+ family: (l.family != o.family || self.family_chosen || l.bold != o.bold || l.italic != o.italic).then_some((l.family, l.bold, l.italic)),
+ size: (l.size != o.size).then_some(l.size),
+ color: (l.color != o.color).then_some(l.color),
+ align: (l.align != o.align).then_some(l.align),
+ underline: (self.extras.underline != self.extras0.underline).then_some(self.extras.underline),
+ line_spacing: (self.extras.line_spacing != self.extras0.line_spacing && self.extras.line_spacing > 0.0)
+ .then_some(self.extras.line_spacing),
+ char_spacing: (self.extras.char_spacing != self.extras0.char_spacing).then_some(self.extras.char_spacing),
+ scale: (self.extras.scale != self.extras0.scale).then_some(self.extras.scale),
+ ..Default::default()
+ };
+ if let Some(range) = &self.selection
+ && (style.family.is_some()
+ || style.resource.is_some()
+ || style.size.is_some()
+ || style.color.is_some()
+ || style.underline.is_some()
+ || style.char_spacing.is_some()
+ || style.scale.is_some())
+ {
+ style.ranges.push(pdfcraft_engine::RangeStyle {
+ range: range.clone(),
+ family: style.family.take(),
+ resource: style.resource.take(),
+ size: style.size.take(),
+ color: style.color.take(),
+ underline: style.underline.take(),
+ char_spacing: style.char_spacing.take(),
+ scale: style.scale.take(),
+ });
+ }
+ style
+ }
+
+ /// After applying formatting: the paragraph now has it.
+ pub fn applied(&mut self) {
+ self.font_resource = None;
+ self.family_chosen = false;
+ self.look0 = self.look.clone();
+ self.extras0 = self.extras;
+ self.original = self.text.clone();
+ self.selection = None;
+ self.focus = true;
+ }
+
+ /// Adopt the rewritten paragraph's current geometry before the next overlay frame.
+ pub(crate) fn refresh_source(&mut self, block: &pdfcraft_engine::TextBlock, lines: Vec<pdfcraft_engine::TextLine>) {
+ self.source_rect = block.rect.map(|v| v as f32);
+ self.multiline = block.rows.len() > 1;
+ self.source = Some((block.clone(), lines));
+ self.text = block.editor_text.clone();
+ self.original = self.text.clone();
+ }
+
+ pub fn selection_formatting(&self, sources: &[(String, String)]) -> SelectionFormatting {
+ let Some((block, lines)) = &self.source else {
+ return SelectionFormatting {
+ font_shown: self.font_shown(sources),
+ size: Some(self.look.size),
+ family: Some(self.look.family),
+ bold: Some(self.look.bold),
+ italic: Some(self.look.italic),
+ color: Some(self.look.color),
+ };
+ };
+
+ let spans = block.edited_spans(&self.text);
+ let matching_lines: Vec<&pdfcraft_engine::TextLine> = match &self.selection {
+ Some(range) if range.start < range.end => {
+ spans.iter().filter(|(span, _)| span.start < range.end && span.end > range.start).filter_map(|(_, idx)| lines.get(*idx)).collect()
+ }
+ _ => spans.iter().filter_map(|(_, idx)| lines.get(*idx)).collect(),
+ };
+
+ if matching_lines.is_empty() {
+ return SelectionFormatting {
+ font_shown: self.font_shown(sources),
+ size: Some(self.look.size),
+ family: Some(self.look.family),
+ bold: Some(self.look.bold),
+ italic: Some(self.look.italic),
+ color: Some(self.look.color),
+ };
+ }
+
+ let line_font = |l: &pdfcraft_engine::TextLine| -> String {
+ if let Some((_, face)) = sources.iter().find(|(res, _)| res == &l.font) {
+ return face.clone();
+ }
+ let base = l.base_font.as_str();
+ let name = match base.split_once('+') {
+ Some((tag, rest)) if tag.len() == 6 && tag.bytes().all(|b| b.is_ascii_uppercase()) => rest,
+ _ => base,
+ };
+ if let Some((_, face)) = sources.iter().find(|(_, face)| face.as_str() == name) {
+ return face.clone();
+ }
+ let look = look_of_line(l);
+ let lower = name.to_ascii_lowercase();
+ if ["times", "serif", "roman", "courier", "helvetica", "arial"].iter().any(|s| lower.contains(s)) {
+ return look.family.label().to_string();
+ }
+ if name.is_empty() { tl!("Keep source fonts").to_string() } else { name.to_string() }
+ };
+
+ let first_font = line_font(matching_lines[0]);
+ let same_font = matching_lines.iter().skip(1).all(|l| line_font(l) == first_font);
+ let font_shown = if same_font {
+ if self.font_resource.is_some() || self.look.family != self.look0.family || self.family_chosen {
+ self.font_shown(sources)
+ } else {
+ first_font
+ }
+ } else {
+ tl!("Mixed").to_string()
+ };
+
+ let first_size = (matching_lines[0].size * 10.0).round() / 10.0;
+ let same_size = matching_lines.iter().skip(1).all(|l| ((l.size * 10.0).round() / 10.0 - first_size).abs() < 0.05);
+ let size = if same_size { Some(first_size) } else { None };
+
+ let first_look = look_of_line(matching_lines[0]);
+ let same_family = matching_lines.iter().skip(1).all(|l| look_of_line(l).family == first_look.family);
+ let family = if same_family { Some(first_look.family) } else { None };
+ let same_bold = matching_lines.iter().skip(1).all(|l| l.bold == matching_lines[0].bold);
+ let bold = if same_bold { Some(matching_lines[0].bold) } else { None };
+ let same_italic = matching_lines.iter().skip(1).all(|l| l.italic == matching_lines[0].italic);
+ let italic = if same_italic { Some(matching_lines[0].italic) } else { None };
+ let same_color = matching_lines.iter().skip(1).all(|l| l.color == matching_lines[0].color);
+ let color = if same_color { Some(matching_lines[0].color) } else { None };
+
+ SelectionFormatting { font_shown, size, family, bold, italic, color }
+ }
+
+ pub(crate) fn sync_selection_look(&mut self, fmt: &SelectionFormatting) {
+ if let Some(sz) = fmt.size {
+ self.look.size = sz;
+ self.look0.size = sz;
+ } else {
+ self.look.size = 0.0;
+ self.look0.size = 0.0;
+ }
+ if let Some(f) = fmt.family {
+ self.look.family = f;
+ self.look0.family = f;
+ }
+ if let Some(b) = fmt.bold {
+ self.look.bold = b;
+ self.look0.bold = b;
+ }
+ if let Some(it) = fmt.italic {
+ self.look.italic = it;
+ self.look0.italic = it;
+ }
+ if let Some(c) = fmt.color {
+ self.look.color = c;
+ self.look0.color = c;
+ }
+ }
+}
+
+#[derive(Clone, Debug, PartialEq)]
+pub struct SelectionFormatting {
+ pub font_shown: String,
+ pub size: Option<f64>,
+ pub family: Option<pdfcraft_engine::FontFamily>,
+ pub bold: Option<bool>,
+ pub italic: Option<bool>,
+ pub color: Option<[f64; 3]>,
+}
+
+fn look_of_line(l: &pdfcraft_engine::TextLine) -> pdfcraft_engine::AddedText {
+ source_look(&l.base_font, l.size, l.color, l.bold, l.italic)
+}
+
+/// What a drag on a paragraph box takes hold of.
+#[derive(Clone, Copy, Debug, PartialEq)]
+enum Grip {
+ Move,
+ /// An edge (screen left or right), dragged to rewrap the paragraph.
+ Left,
+ Right,
+}
+
+/// A paragraph box being dragged: moved, or (from a handle on its left or right edge) resized.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct BlockDrag {
+ page: usize,
+ block: usize,
+ /// A paragraph index belongs to the document generation where the press was resolved.
+ generation: u64,
+ /// Where the drag started (screen).
+ start: Pos2,
+ grip: Grip,
+}
+
+/// How far an edge grip reaches either side of a box's edge (screen pixels).
+const EDGE_REACH: f32 = 6.0;
+/// How far outside an open paragraph's frame the pointer still means the frame (screen pixels).
+const FRAME_REACH: f32 = 4.0;
+
+/// The rewrap handles drawn on a paragraph box's left and right edges (screen).
+fn width_handles(b: Rect) -> [Rect; 2] {
+ let h = (b.height() * 0.5).clamp(14.0, 28.0);
+ [b.left(), b.right()].map(|x| Rect::from_center_size(Pos2::new(x, b.center().y), egui::vec2(7.0, h)))
+}
+
+/// The edge of `b` that `p` grabs: anywhere along its height, within reach of the line. A narrow
+/// box keeps its middle for moving.
+fn edge_at(b: Rect, p: Pos2) -> Option<Grip> {
+ if p.y < b.top() - EDGE_REACH || p.y > b.bottom() + EDGE_REACH {
+ return None;
+ }
+ let inside = EDGE_REACH.min(b.width() / 4.0);
+ let (dl, dr) = (p.x - b.left(), b.right() - p.x);
+ match (dl >= -EDGE_REACH && dl <= inside, dr >= -EDGE_REACH && dr <= inside) {
+ (true, true) if dl <= dr => Some(Grip::Left),
+ (_, true) => Some(Grip::Right),
+ (true, false) => Some(Grip::Left),
+ _ => None,
+ }
+}
+
+/// The topmost box under `p` and what it grabs there; edges only on an upright page.
+fn grab_at(boxes: &[Rect], p: Pos2, upright: bool) -> Option<(usize, Grip)> {
+ boxes.iter().enumerate().rev().find_map(|(i, b)| match upright.then(|| edge_at(*b, p)).flatten() {
+ Some(g) => Some((i, g)),
+ None => b.contains(p).then_some((i, Grip::Move)),
+ })
+}
+
+/// A paragraph's box on screen: its text rect (user space), with a little room around it.
+fn paragraph_box(xf: &PageXform, info: &DocInfo, page: usize, rect: [f64; 4]) -> Rect {
+ xf.user_rect(info, page, rect.map(|v| v as f32)).expand(2.0)
+}
+
+/// The width handles need the page upright (or upside down): on a quarter-turned page the
+/// screen's horizontal is the paragraph's vertical.
+fn has_edges(info: &DocInfo, page: usize) -> bool {
+ info.pages.get(page).is_some_and(|p| p.rotation % 180 == 0)
+}
+
+/// Whether a press at `p` takes hold of the width handle of one of the paragraphs `rects` (user
+/// space). The handle is drawn half outside the box and grabs from a little further out still,
+/// where a press is not on the box itself, so area selection must leave it to [`page_input`].
+pub(crate) fn grabs_edge(xf: &PageXform, info: &DocInfo, page: usize, mut rects: impl Iterator<Item = [f64; 4]>, p: Pos2) -> bool {
+ has_edges(info, page) && rects.any(|r| edge_at(paragraph_box(xf, info, page, r), p).is_some())
+}
+
+pub(crate) fn user_box(xf: &PageXform, info: &DocInfo, page: usize, r: Rect) -> [f64; 4] {
+ let p = &info.pages[page];
+ let (a, b) = (xf.screen_to_view(r.min), xf.screen_to_view(r.max));
+ let (u, v) = (p.view_to_user(a.0, a.1), p.view_to_user(b.0, b.1));
+ [u[0].min(v[0]) as f64, u[1].min(v[1]) as f64, u[0].max(v[0]) as f64, u[1].max(v[1]) as f64]
+}
+
+/// Open `block` on `page` in the inline editor. The box's geometry and source are read from the
+/// `lines` handed in, so callers pass the document's current inventory.
+#[allow(clippy::too_many_arguments)]
+fn open_editor(
+ ui: &egui::Ui,
+ xf: &PageXform,
+ doc: &pdfcraft_engine::Document,
+ lines: &[pdfcraft_engine::TextBlock],
+ boxes: &[Rect],
+ page: usize,
+ block: usize,
+ view: &mut DocView,
+) {
+ view.pending_text_open = None;
+ let (Some(l), Some(b)) = (lines.get(block), boxes.get(block)) else { return };
+ view.image_selection = None;
+ let source_lines = doc.text_lines(page);
+ let text = l.editor_text.clone();
+ // Screen pixels per point, from the box's width.
+ let scale = (b.width() - 4.0) / ((l.rect[2] - l.rect[0]).max(1.0) as f32);
+ // How far the editor box may grow: a single-line paragraph's rewrite grows to the
+ // page's right edge, a multi-line paragraph rewraps to its own width.
+ let right = xf.rect.right().min(view.viewport_rect().right()) - 6.0;
+ let max_width = if l.rows.len() == 1 { (right - b.left()).max(b.width()) } else { b.width() };
+ view.line_editor = Some(LineEditor {
+ selection: None,
+ font_resource: None,
+ page,
+ block,
+ text: text.clone(),
+ original: text,
+ rect: *b,
+ source_rect: l.rect.map(|v| v as f32),
+ multiline: l.rows.len() > 1,
+ source: Some((l.clone(), source_lines)),
+ fonts: install_source_fonts(ui.ctx(), doc, page),
+ overflow: false,
+ max_width,
+ size: (l.size as f32 * scale).clamp(8.0, 72.0),
+ focus: true,
+ had_focus: false,
+ look: look_of(l),
+ look0: look_of(l),
+ family_chosen: false,
+ extras: Extras::default(),
+ extras0: Extras::default(),
+ });
+}
+
+/// Lines and their screen boxes for a page; hover outlines, click opens the editor. Returns
+/// `true` when the pointer was used.
+#[allow(clippy::too_many_arguments)]
+pub(crate) fn page_input(
+ ui: &egui::Ui,
+ resp: &egui::Response,
+ xf: &PageXform,
+ ptr: &PagePointer,
+ page: usize,
+ doc: &pdfcraft_engine::Document,
+ lines: &[pdfcraft_engine::TextBlock],
+ view: &mut DocView,
+ allow_interaction: bool,
+) -> bool {
+ let info = &doc.info;
+ if view.block_drag.is_some_and(|d| d.generation != doc.edit_generation()) {
+ view.block_drag = None;
+ return true;
+ }
+ let boxes: Vec<Rect> = lines.iter().map(|l| paragraph_box(xf, info, page, l.rect)).collect();
+ // Outlines stay on their page, like its text (#3061).
+ let painter = ui.painter().with_clip_rect(ui.clip_rect().intersect(xf.rect.expand(1.0)));
+ let active = view.line_editor.as_ref().filter(|e| e.page == page).map(|e| e.block);
+ for (i, b) in boxes.iter().enumerate() {
+ if active != Some(i) {
+ painter.rect_stroke(*b, CornerRadius::same(2), Stroke::new(0.75, ACCENT.gamma_multiply(0.35)), egui::StrokeKind::Outside);
+ }
+ }
+ // A box a switching click asked for opens now, once the edit queued with that click has
+ // applied and `lines`/`boxes` are the document's new inventory (#2022).
+ if allow_interaction
+ && active.is_none()
+ && let Some((open_page, key)) = view.pending_text_open.clone()
+ && open_page == page
+ {
+ // The edit may have regrouped the page: open the paragraph that was clicked, wherever it
+ // is now, and none if it was merged into another (#2516).
+ match key.find(lines, 0) {
+ Some(block) => open_editor(ui, xf, doc, lines, &boxes, page, block, view),
+ None => view.pending_text_open = None,
+ }
+ }
+ if !allow_interaction {
+ return false;
+ }
+ let upright = has_edges(info, page);
+ let draw_handles = |b: Rect| {
+ for h in width_handles(b) {
+ painter.rect(h, CornerRadius::same(2), Color32::WHITE, Stroke::new(1.0, ACCENT), egui::StrokeKind::Middle);
+ }
+ };
+ // A drag in progress: the box follows the pointer (or the grabbed edge does); releasing applies it.
+ if let Some(d) = view.block_drag.filter(|d| d.page == page)
+ && let (Some(b), Some(l)) = (boxes.get(d.block).copied(), lines.get(d.block))
+ {
+ let p = ptr.pos.unwrap_or(d.start);
+ let dx = p.x - d.start.x;
+ let preview = match d.grip {
+ Grip::Move => b.translate(p - d.start),
+ Grip::Left => Rect::from_min_max(Pos2::new((b.left() + dx).min(b.right() - 12.0), b.min.y), b.max),
+ Grip::Right => Rect::from_min_max(b.min, Pos2::new((b.right() + dx).max(b.left() + 12.0), b.max.y)),
+ };
+ painter.rect_stroke(preview, CornerRadius::same(2), Stroke::new(1.5, ACCENT), egui::StrokeKind::Outside);
+ let resizing = d.grip != Grip::Move;
+ if resizing {
+ draw_handles(preview);
+ }
+ ui.ctx().set_cursor_icon(if resizing { egui::CursorIcon::ResizeHorizontal } else { egui::CursorIcon::Move });
+ if resp.drag_stopped() || !ptr.any_down {
+ view.block_drag = None;
+ let (from, to) = (user_box(xf, info, page, b), user_box(xf, info, page, preview));
+ let edit = if resizing {
+ // The new width in user space: the box's change, added to the paragraph's own. A
+ // moved left side (in user space; on an upside-down page that's the screen's right
+ // edge) moves the paragraph with it.
+ let width = (l.rect[2] - l.rect[0]) + (to[2] - to[0]) - (from[2] - from[0]);
+ let shift = to[0] - from[0];
+ let style = pdfcraft_engine::BlockStyle { width: Some(width), offset: (shift != 0.0).then_some([shift, 0.0]), ..Default::default() };
+ Edit::EditTextBlock { page, block: d.block, text: l.text.clone(), style }
+ } else {
+ // Translation must keep the selected source operators. Rewriting unchanged text
+ // would also remove unrelated paragraphs that now overlap this one (#594).
+ Edit::MoveObjects {
+ page,
+ objects: vec![ObjectTarget { kind: ObjectKind::Text, index: d.block }],
+ offset: [to[0] - from[0], to[1] - from[1]],
+ }
+ };
+ if preview != b {
+ view.pending_edit = Some(edit);
+ }
+ }
+ return true;
+ }
+ // Dragging a box (not while a paragraph is open for typing) moves it; from an edge, resizes it.
+ // What it grabs comes from where the button went down, not where the pointer is now: egui
+ // only calls it a drag once the pointer has moved a few pixels (or been held a moment), and a
+ // quick flick has left the edge by then.
+ if resp.drag_started()
+ && active.is_none()
+ && let Some(o) = ptr.origin
+ && let Some((block, grip)) = grab_at(&boxes, o, upright)
+ {
+ view.block_drag = Some(BlockDrag { page, block, generation: doc.edit_generation(), start: o, grip });
+ return true;
+ }
+ let Some(p) = ptr.within(xf.rect) else { return false };
+ let Some((hit, grip)) = grab_at(&boxes, p, upright) else { return false };
+ if active != Some(hit) {
+ painter.rect_stroke(boxes[hit], CornerRadius::same(2), Stroke::new(1.5, ACCENT), egui::StrokeKind::Outside);
+ }
+ let on_edge = active.is_none() && grip != Grip::Move;
+ if upright && active.is_none() {
+ draw_handles(boxes[hit]);
+ }
+ // A closed paragraph moves when dragged (the four-way arrow says so; a click still opens it
+ // for typing); an edge rewraps it. The open one takes the text cursor. Only where the page
+ // shows, so the mode bar and side panels over a paragraph scrolled under them keep their own
+ // cursor (#2755).
+ if resp.contains_pointer() {
+ ui.ctx().set_cursor_icon(if on_edge {
+ egui::CursorIcon::ResizeHorizontal
+ } else if active.is_none() {
+ egui::CursorIcon::Move
+ } else {
+ egui::CursorIcon::Text
+ });
+ }
+ if resp.clicked() {
+ view.image_selection = None;
+ // A click that moves the editor to another paragraph applies the open one first, so its
+ // typed text is not dropped with the switched-away editor (#2022). A click on the open
+ // box's own frame, which the editor's overlay does not cover, keeps it open instead.
+ if let Some(open) = view.line_editor.as_ref().filter(|e| e.has_changes()) {
+ if open.page == page && open.block == hit {
+ return true;
+ }
+ if let Some(old) = view.line_editor.take() {
+ let style = old.style();
+ if old.text != old.original || style != pdfcraft_engine::BlockStyle::default() {
+ view.applied_editor = Some(old.clone());
+ view.pending_edit = Some(Edit::EditTextBlock { page: old.page, block: old.block, text: old.text, style });
+ }
+ }
+ // The clicked box opens next frame, from the document with that edit applied.
+ view.pending_text_open = lines.get(hit).map(|l| (page, pdfcraft_engine::BlockKey::of(l)));
+ return true;
+ }
+ open_editor(ui, xf, doc, lines, &boxes, page, hit, view);
+ }
+ true
+}
+
+/// The inline editor; returns the edit once the text is applied.
+pub(crate) fn overlay(ctx: &egui::Context, view: &mut DocView, info: &DocInfo) -> Option<Edit> {
+ // Clicks outside the document (the Format text panel) keep the paragraph open. Where the
+ // click landed is `interact_pos`: `latest_pos` is gone on the frame a tap lifts.
+ let outside = ctx.input(|i| i.pointer.interact_pos()).is_some_and(|p| !view.viewport_rect().contains(p));
+ let page = view.line_editor.as_ref()?.page;
+ let xf = view.page_xform(page)?;
+ let hold = view.objects.hold_editor;
+ // An OCR word is invisible text over a scan: the textless background still shows the scanned
+ // word, so the editor covers it, as the applied edit will.
+ let background_ready = view
+ .line_editor
+ .as_ref()
+ .is_some_and(|ed| view.text_background.ready(ed.page, ed.block) && !ed.source.as_ref().is_some_and(|(b, _)| b.invisible));
+ // The measured extent of this paragraph's draft: a click straight from another paragraph
+ // opens this one after the frame's measuring, which was the other one's.
+ let draft_rect = view
+ .line_editor
+ .as_ref()
+ .and_then(|ed| view.text_background.draft_rect_for(ed.page, ed.block))
+ .map(|r| xf.user_rect(info, page, r.map(|v| v as f32)));
+ // The editor draws on its page only, as the page itself does: a paragraph running past the
+ // page's edge (a converter relying on the page clip) must not cover the next page or the
+ // tool bars (#3061).
+ let viewport = view.viewport_rect();
+ let page_clip = xf.rect.intersect(viewport);
+ let ed = view.line_editor.as_mut()?;
+ if hold {
+ ed.focus = true;
+ }
+ // Reproject the source box every frame. The page may have been zoomed, scrolled or rotated
+ // while the format panel was open.
+ // A font definition becomes active at the start of the next egui pass. Keep the source
+ // raster visible until then instead of flashing an unrelated interface face.
+ if !ctx.fonts(|f| ed.fonts.values().all(|name| f.definitions().families.contains_key(&FontFamily::Name(name.clone().into())))) {
+ ctx.request_repaint();
+ return None;
+ }
+ ed.rect = xf.user_rect(info, ed.page, ed.source_rect);
+ ed.max_width = ed.rect.width();
+ let scale = (ed.rect.width() / (ed.source_rect[2] - ed.source_rect[0]).abs().max(0.01)).max(0.01);
+ ed.size = (ed.look.size as f32 * scale).clamp(1.0, 300.0);
+ // egui draws the caret at least one row of this font tall. Each row already has its source
+ // row's height, so the font stays below every row (half the region's smallest size): on a
+ // 12 pt row under a 24 pt title the caret is as tall as the row, not the title.
+ let smallest =
+ ed.source.as_ref().and_then(|(block, lines)| block.lines.iter().filter_map(|i| lines.get(*i)).map(|l| l.size as f32).reduce(f32::min));
+ let font = editor_font(&ed.look, smallest.map_or(ed.size, |s| (s * scale * 0.5).clamp(1.0, 300.0).min(ed.size)));
+ let text_color = color32(ed.look.color);
+ let block = ed.block;
+ let mut done = None;
+ let mut reveal = false;
+ let mut look = None;
+ // No fade-in: while it faded, the page's own copy of the text showed through the cover.
+ // Over the page, so only where the document shows: a paragraph scrolled under the mode bar or
+ // a side panel must leave them their pointer (#2755). It stays at its paragraph, cut off as
+ // the page is, rather than pushed back into the window.
+ egui::Area::new(egui::Id::unique("edit-text-line"))
+ .order(egui::Order::Foreground)
+ .fade_in(false)
+ .fixed_pos(Pos2::new(ed.rect.left(), ed.rect.top()))
+ .constrain_to(viewport)
+ .constrain(false)
+ .show(ctx, |ui| {
+ ui.set_clip_rect(ui.clip_rect().intersect(page_clip));
+ // The editor opens at the source size. Once text changes, show the real draft
+ // extent: single rows grow toward the page edge, paragraphs rewrap at their
+ // source width, and the visible frame grows/shrinks vertically with their rows.
+ // An OCR phrase (several stretched words on one scanned line) also grows rightwards.
+ let single_run = ed.source.as_ref().is_some_and(|(block, _)| block.rows.len() == 1 || block.invisible);
+ let width = if !ed.multiline && single_run && !ed.text.contains('\n') && ed.has_changes() {
+ let job = editor_job(ui, ed, &ed.text, scale, f32::INFINITY);
+ let natural = ui.fonts_mut(|f| f.layout_job(job)).size().x;
+ natural.max(ed.size * 0.4).min((xf.rect.right() - ed.rect.left() - 36.0 * scale).max(ed.rect.width()))
+ } else {
+ ed.rect.width().max(1.0)
+ };
+ ui.set_width(width);
+ let measured = editor_galley(ui, ed, &ed.text, scale, width);
+ ed.overflow = ed.has_changes() && (measured.rect.width() > ed.rect.width() + 1.5 || measured.rect.height() > ed.rect.height() + 1.5);
+ let visible = Rect::from_min_size(ed.rect.min, measured.rect.size().max(egui::vec2(1.0, 1.0)));
+ // Unsupported source programs use an interface fallback whose glyph advances
+ // can differ from the PDF's. Keep every visible row inside the growing frame.
+ let live = draft_rect.map_or(visible, |bounds| bounds.union(visible));
+ ui.painter().rect_stroke(live.expand(2.0), CornerRadius::ZERO, Stroke::new(1.5, ACCENT), egui::StrokeKind::Outside);
+ // On the frame, a press takes hold of the box (a click selects it, a drag moves it):
+ // the pointer says so there, and reads as text inside.
+ if let Some(p) = ui.input(|i| i.pointer.hover_pos())
+ && ui.clip_rect().contains(p)
+ && live.expand(2.0 + FRAME_REACH).contains(p)
+ && !live.expand(2.0).contains(p)
+ {
+ ui.ctx().set_cursor_icon(egui::CursorIcon::Move);
+ }
+ // White, unless the text is too pale to read on white (white text from a coloured
+ // banner, #913): then a dark box, with a caret that shows on it.
+ let fill = if background_ready { Color32::TRANSPARENT } else { editor_fill(text_color) };
+ // An unchanged paragraph is the page's own text: the editor draws only its frame and
+ // caret over it. Once it changes, the textless page goes under the editor's text or,
+ // until that background is ready, a cover over the entire source box, including lines
+ // the draft no longer occupies. Shrinking the text must never expose a copy. Both are
+ // decided after this frame's typing, in places kept under the editor's text.
+ let cover = ui.painter().add(egui::Shape::Noop);
+ let unchanged = !ed.has_changes();
+ egui::Frame::NONE.show(ui, |ui| {
+ // A textless PDF preview, or the page itself, keeps its real background through
+ // the transparent editor. The temporary opaque cover uses the shared caret-contrast rule.
+ ui.visuals_mut().text_cursor.stroke.color = if background_ready || unchanged {
+ if luminance(text_color) < 0.5 { Color32::BLACK } else { Color32::WHITE }
+ } else {
+ caret_color_on(fill)
+ };
+ let rows = 1;
+ let snapshot = ed.clone();
+ let mut layouter = |ui: &egui::Ui, text: &dyn egui::TextBuffer, wrap_width: f32| {
+ let galley = editor_galley(ui, &snapshot, text.as_str(), scale, wrap_width);
+ if snapshot.changes_with(text.as_str()) { galley } else { unseen(galley) }
+ };
+ let output = egui::TextEdit::multiline(&mut ed.text)
+ .id(egui::Id::unique("edit-text-line-input"))
+ .font(font.clone())
+ .margin(egui::Margin::ZERO)
+ .layouter(&mut layouter)
+ .text_color(text_color)
+ .frame(egui::Frame::NONE)
+ .desired_width(width)
+ .desired_rows(rows)
+ .show(ui);
+ // The editor paints over the page with no visible label; name it for assistive tech.
+ output.response.response.clone().accessible_name(tl!("Text editing line"));
+ if ed.has_changes() {
+ if background_ready {
+ reveal = true;
+ } else {
+ ui.painter().set(cover, egui::Shape::rect_filled(ed.rect.expand(1.0).union(output.response.rect), CornerRadius::ZERO, fill));
+ }
+ }
+ look = Some((Arc::clone(&output.galley), output.galley_pos));
+ if let Some(cursor) = output.cursor_range {
+ let selected = cursor.as_sorted_char_range();
+ let byte = |index| ed.text.char_indices().nth(index).map_or(ed.text.len(), |(at, _)| at);
+ ed.selection = (!selected.is_empty()).then(|| byte(selected.start.into())..byte(selected.end.into()));
+ }
+ let r = output.response;
+ if r.changed() {
+ // The next pass measures the updated draft with the Apply/Save rewrite.
+ ctx.request_repaint();
+ }
+ if ed.focus {
+ r.request_focus();
+ ed.focus = false;
+ }
+ let lost = lost_focus_once(&r, &mut ed.had_focus);
+ let esc = ui.input(|i| i.key_pressed(egui::Key::Escape));
+ let apply = ui.input(|i| i.key_pressed(egui::Key::Enter) && i.modifiers.command);
+ if esc {
+ done = Some(false);
+ } else if apply || (lost && !outside && !hold) {
+ done = Some(true);
+ }
+ });
+ });
+ if reveal {
+ view.text_background.reveal();
+ }
+ if let Some((galley, pos)) = look {
+ view.text_background.remember(&xf, page, block, galley, pos, text_color);
+ }
+ match done {
+ Some(apply) => {
+ let ed = view.line_editor.take()?;
+ if !apply {
+ return None;
+ }
+ view.applied_editor = Some(ed.clone());
+ finished_edit(ed)
+ }
+ None => None,
+ }
+}
+
+/// The edit a closed paragraph editor applies, or `None` when nothing in it changed.
+pub(crate) fn finished_edit(ed: LineEditor) -> Option<Edit> {
+ let style = ed.style();
+ (ed.text != ed.original || style != pdfcraft_engine::BlockStyle::default()).then_some(Edit::EditTextBlock {
+ page: ed.page,
+ block: ed.block,
+ text: ed.text,
+ style,
+ })
+}
+
+/// Whether an editor's text box `r` lost the keyboard this frame, given whether it `had` it at
+/// the end of the editor's last frame (updated here). egui's `lost_focus` holds for a second
+/// frame as well, and an editor that judges a click away by where the click landed must judge it
+/// once, on the click's frame: on the next, a tap's position is gone (egui-winit sends
+/// `PointerGone` with every touch release) and a mouse may have moved on.
+pub(crate) fn lost_focus_once(r: &egui::Response, had: &mut bool) -> bool {
+ let has = r.has_focus();
+ std::mem::replace(had, has) && !has
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn the_rotate_knob_moves_below_when_there_is_no_room_above() {
+ let view = Rect::from_min_max(Pos2::new(0.0, 100.0), Pos2::new(500.0, 500.0));
+ let roomy = Rect::from_min_max(Pos2::new(100.0, 200.0), Pos2::new(200.0, 250.0));
+ assert_eq!(rotate_knob(roomy, view).0, Pos2::new(150.0, 178.0));
+ let at_top = Rect::from_min_max(Pos2::new(100.0, 100.0), Pos2::new(200.0, 150.0));
+ let (knob, stem) = rotate_knob(at_top, view);
+ assert_eq!((knob, stem), (Pos2::new(150.0, 172.0), Pos2::new(150.0, 150.0)));
+ }
+
+ #[test]
+ fn the_rotate_knob_measures_clockwise_degrees_from_straight_up() {
+ let c = Pos2::new(100.0, 100.0);
+ let at = |x: f32, y: f32| turn_degrees(c, Pos2::new(x, y), false);
+ assert!(at(100.0, 0.0).abs() < 1e-3);
+ assert!((at(200.0, 100.0) - 90.0).abs() < 1e-3, "right is a clockwise quarter");
+ assert!((at(0.0, 100.0) + 90.0).abs() < 1e-3);
+ assert!((at(100.0, 200.0).abs() - 180.0).abs() < 1e-3);
+ // Shift rounds to 15 degrees; the centre and non-finite points turn nothing.
+ assert_eq!(turn_degrees(c, Pos2::new(180.0, 50.0), true) % 15.0, 0.0);
+ assert_eq!(at(101.0, 101.0), 0.0);
+ assert_eq!(at(f32::NAN, 5.0), 0.0);
+ }
+
+ /// An app with one text document open, and an editor on its first paragraph.
+ fn preview_app() -> (crate::PdfCraftApp, LineEditor) {
+ let mut app = crate::PdfCraftApp::new();
+ let bytes = app.session.create_from_text("Preview", "Preview text").unwrap();
+ app.open_bytes("preview.pdf", None, bytes.as_ref().clone()).unwrap();
+ let doc = app.session.get(app.views[0].id).unwrap();
+ let block = doc.text_blocks(0).remove(0);
+ let ed = LineEditor {
+ selection: None,
+ font_resource: None,
+ page: 0,
+ block: 0,
+ text: block.text.clone(),
+ original: block.text.clone(),
+ rect: Rect::NOTHING,
+ source_rect: block.rect.map(|v| v as f32),
+ multiline: block.rows.len() > 1,
+ source: None,
+ fonts: BTreeMap::new(),
+ overflow: false,
+ max_width: 400.0,
+ size: block.size as f32,
+ focus: true,
+ had_focus: false,
+ look: look_of(&block),
+ look0: look_of(&block),
+ family_chosen: false,
+ extras: Extras::default(),
+ extras0: Extras::default(),
+ };
+ (app, ed)
+ }
+
+ #[test]
+ fn picking_the_family_the_font_name_reads_as_still_changes_the_font() {
+ // A Calibri paragraph reads as Helvetica; picking Helvetica from the list used to leave
+ // `look` equal to what the paragraph had, so no family change was sent and Calibri stayed.
+ let (_app, mut ed) = preview_app();
+ let family = ed.look0.family;
+ assert_eq!(ed.style().family, None, "nothing chosen yet");
+ ed.choose_family(family);
+ assert_eq!(ed.style().family, Some((family, ed.look.bold, ed.look.italic)));
+ assert!(ed.has_changes());
+ assert_eq!(ed.font_shown(&[]), family.label());
+ ed.keep_source_font();
+ assert_eq!(ed.style().family, None, "Keep source fonts withdraws the choice");
+ ed.choose_family(family);
+ ed.applied();
+ assert_eq!(ed.style().family, None, "an applied choice is the paragraph's font now");
+ }
+
+ #[test]
+ fn a_loaded_font_is_applied_to_the_paragraph_being_edited() {
+ // Loading a font used to only register it on the page: the paragraph kept its source
+ // face until the font was found again in the document-font menu (#2591).
+ let (mut app, ed) = preview_app();
+ app.views[0].line_editor = Some(ed);
+ let inter = include_bytes!("../../../../assets/fonts/Inter-Regular.ttf").to_vec();
+ app.use_files(crate::files::FilePurpose::TextFont { page: 0 }, vec![("Inter-Regular.ttf".into(), inter)]);
+ let doc = app.session.get(app.views[0].id).unwrap();
+ let lines = doc.text_lines(0);
+ assert_eq!(lines.iter().map(|l| l.text.as_str()).collect::<String>(), "Preview text");
+ assert!(lines.iter().all(|l| l.base_font == "Inter-Regular"), "{:?}", lines.iter().map(|l| &l.base_font).collect::<Vec<_>>());
+ assert!(app.views[0].line_editor.is_some(), "the paragraph stays open for editing");
+ }
+
+ #[test]
+ fn save_applies_the_paragraph_open_in_the_editor() {
+ // Save wrote the file without the paragraph still open in the editor (#3496).
+ let (mut app, mut ed) = preview_app();
+ ed.text = "Text preview".into();
+ app.views[0].line_editor = Some(ed);
+ let dir = std::env::temp_dir().join(format!("pdfcraft-ui-open-paragraph-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ std::fs::create_dir_all(&dir).unwrap();
+ app.save_override = Some(dir.join("out.pdf").to_string_lossy().into_owned());
+
+ assert!(app.save_active(crate::SaveTarget::InPlace));
+ assert!(app.views[0].line_editor.is_none());
+ let doc = app.session.get(app.views[0].id).unwrap();
+ assert_eq!(doc.text_lines(0).iter().map(|l| l.text.as_str()).collect::<String>(), "Text preview");
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
+ #[test]
+ fn a_refused_text_box_does_not_lose_the_open_paragraph() {
+ let (mut app, mut ed) = preview_app();
+ ed.text = "Text preview".into();
+ app.views[0].line_editor = Some(ed);
+ let draft = crate::content_ui::TextDraft {
+ page: 9,
+ index: None,
+ rect: [20.0, 20.0, 120.0, 40.0],
+ text: "Typed text".into(),
+ style: crate::content_ui::default_style(),
+ focus: true,
+ };
+ app.views[0].content.draft = Some(draft.clone());
+
+ assert!(!app.commit_typing_in(app.views[0].id));
+ assert_eq!(app.views[0].content.draft, Some(draft), "the refused text box stays open");
+ assert!(app.views[0].line_editor.is_none(), "the paragraph was applied");
+ let doc = app.session.get(app.views[0].id).unwrap();
+ assert_eq!(doc.text_lines(0).iter().map(|l| l.text.as_str()).collect::<String>(), "Text preview");
+ }
+
+ #[test]
+ fn a_refused_paragraph_stays_open_with_its_text() {
+ let (mut app, mut ed) = preview_app();
+ ed.text = "Text preview".into();
+ ed.page = 9;
+ app.views[0].line_editor = Some(ed.clone());
+
+ assert!(!app.commit_typing_in(app.views[0].id));
+ assert_eq!(app.views[0].line_editor, Some(ed), "the paragraph keeps its unsaved text");
+ }
+
+ #[test]
+ fn text_background_is_cached_without_editing_and_released_on_cancel() {
+ let (app, ed) = preview_app();
+ let doc = app.session.get(app.views[0].id).unwrap();
+ let source = doc.bytes.clone();
+ let generation = doc.edit_generation();
+ let ctx = egui::Context::default();
+ let mut background = TextBackground::default();
+ for _ in 0..100 {
+ background.prepare(&ctx, doc, Some(&ed), None, 1.0);
+ if background.ready(0, 0) {
+ break;
+ }
+ std::thread::sleep(std::time::Duration::from_millis(5));
+ }
+ assert!(background.ready(0, 0));
+ assert!(!background.pending());
+ let texture = background.texture.as_ref().unwrap().id();
+ background.prepare(&ctx, doc, Some(&ed), None, 1.0);
+ assert_eq!(background.texture.as_ref().unwrap().id(), texture);
+ assert_eq!(doc.bytes, source);
+ assert_eq!(doc.edit_generation(), generation);
+ assert!(!doc.dirty && doc.can_undo().is_none());
+ background.prepare(&ctx, doc, None, None, 1.0);
+ assert!(background.texture.is_none() && background.renderer.is_none());
+ }
+
+ #[test]
+ fn the_editing_background_stays_sharp_on_a_zoomed_page() {
+ // While a paragraph is open, the page around it is drawn from this one raster: it is
+ // asked for at the tiling threshold, not the 2048-pixel backdrop side, which went soft
+ // beyond about 1.2x on a Retina display.
+ let (app, ed) = preview_app();
+ let doc = app.session.get(app.views[0].id).unwrap();
+ let page = &doc.info.pages[0];
+ let ctx = egui::Context::default();
+ ctx.begin_pass(egui::RawInput { max_texture_side: Some(16384), ..Default::default() });
+ let mut background = TextBackground::default();
+ background.prepare(&ctx, doc, Some(&ed), None, 8.0);
+ let expected = 8.0f32.min(crate::canvas::TILE_THRESHOLD / page.width.max(page.height));
+ assert!(expected > crate::canvas::BASE_SIDE / page.width.max(page.height), "the test page needs the larger side");
+ assert_eq!(background.tag, Some((expected * 1000.0) as u64));
+ // A GPU that can't hold such a texture caps it.
+ ctx.end_pass().textures_delta.clear();
+ ctx.begin_pass(egui::RawInput { max_texture_side: Some(2048), ..Default::default() });
+ let mut small = TextBackground::default();
+ small.prepare(&ctx, doc, Some(&ed), None, 8.0);
+ assert_eq!(small.tag, Some(((2048.0 / page.width.max(page.height)) * 1000.0) as u64));
+ ctx.end_pass().textures_delta.clear();
+ }
+
+ #[test]
+ fn pale_text_is_edited_on_a_dark_box() {
+ // #913: white text from a coloured banner was typed onto a white box and vanished.
+ for pale in [Color32::WHITE, Color32::from_rgb(0xFF, 0xFF, 0x00), Color32::from_gray(0xE0), Color32::from_rgb(0xFF, 0xA5, 0x00)] {
+ assert_eq!(editor_fill(pale), DARK_EDITOR_FILL, "{pale:?}");
+ assert!(contrast(pale, editor_fill(pale)) >= 4.5, "{pale:?} is readable");
+ }
+ // Ordinary dark or saturated text keeps the white box.
+ for dark in [Color32::BLACK, Color32::from_rgb(0x1F, 0x2A, 0x6B), Color32::from_rgb(0xC0, 0x00, 0x00), Color32::from_gray(0x60)] {
+ assert_eq!(editor_fill(dark), Color32::WHITE, "{dark:?}");
+ }
+ }
+
+ #[test]
+ fn caret_contrasts_with_its_fill() {
+ assert_eq!(caret_color_on(Color32::WHITE), Color32::BLACK);
+ assert_eq!(caret_color_on(Color32::from_rgb(0xFF, 0xFF, 0xF4)), Color32::BLACK);
+ assert_eq!(caret_color_on(Color32::BLACK), Color32::WHITE);
+ assert_eq!(caret_color_on(DARK_EDITOR_FILL), Color32::WHITE);
+ }
+
+ #[test]
+ fn bullet_list_toggles_and_preserves_content() {
+ let mut text = "First line\nSecond line\n\nThird line".to_string();
+ assert!(!is_bulleted(&text));
+ assert!(toggle_bullet_list(&mut text));
+ assert!(is_bulleted(&text));
+ assert_eq!(text, "• First line\n• Second line\n\n• Third line");
+
+ // Toggling again removes bullets
+ assert!(toggle_bullet_list(&mut text));
+ assert!(!is_bulleted(&text));
+ assert_eq!(text, "First line\nSecond line\n\nThird line");
+ }
+
+ #[test]
+ fn numbered_list_toggles_and_preserves_content() {
+ let mut text = "Item A\nItem B\n\nItem C".to_string();
+ assert!(!is_numbered(&text));
+ assert!(toggle_numbered_list(&mut text));
+ assert!(is_numbered(&text));
+ assert_eq!(text, "1. Item A\n2. Item B\n\n3. Item C");
+
+ // Toggling again removes numbering
+ assert!(toggle_numbered_list(&mut text));
+ assert!(!is_numbered(&text));
+ assert_eq!(text, "Item A\nItem B\n\nItem C");
+ }
+
+ #[test]
+ fn superscript_and_subscript_conversion() {
+ let mut ed = LineEditor {
+ page: 0,
+ block: 0,
+ text: "E = mc2".to_string(),
+ original: "E = mc2".to_string(),
+ rect: egui::Rect::ZERO,
+ source_rect: [0.0; 4],
+ max_width: 100.0,
+ overflow: false,
+ selection: Some(6..7), // selecting '2'
+ font_resource: None,
+ fonts: std::collections::BTreeMap::new(),
+ source: None,
+ multiline: false,
+ size: 12.0,
+ family_chosen: false,
+ focus: true,
+ had_focus: false,
+ look: pdfcraft_engine::AddedText::default(),
+ look0: pdfcraft_engine::AddedText::default(),
+ extras: Extras::default(),
+ extras0: Extras::default(),
+ };
+
+ assert!(toggle_superscript(&mut ed));
+ assert_eq!(ed.text, "E = mc²");
+ // Toggling superscript again returns to normal '2'
+ assert!(toggle_superscript(&mut ed));
+ assert_eq!(ed.text, "E = mc2");
+
+ // Test subscript on H2O
+ ed.text = "H2O".to_string();
+ ed.selection = Some(1..2); // selecting '2'
+ assert!(toggle_subscript(&mut ed));
+ assert_eq!(ed.text, "H₂O");
+ assert!(toggle_subscript(&mut ed));
+ assert_eq!(ed.text, "H2O");
+ }
+
+ #[test]
+ fn value_based_line_spacing_in_style() {
+ let ed = LineEditor {
+ page: 0,
+ block: 0,
+ text: "Paragraph text".to_string(),
+ original: "Paragraph text".to_string(),
+ rect: egui::Rect::ZERO,
+ source_rect: [0.0; 4],
+ max_width: 100.0,
+ overflow: false,
+ selection: None,
+ font_resource: None,
+ fonts: std::collections::BTreeMap::new(),
+ source: None,
+ multiline: false,
+ size: 12.0,
+ family_chosen: false,
+ focus: true,
+ had_focus: false,
+ look: pdfcraft_engine::AddedText::default(),
+ look0: pdfcraft_engine::AddedText::default(),
+ extras: Extras { line_spacing: 1.33, underline: true, ..Default::default() },
+ extras0: Extras::default(),
+ };
+ let style = ed.style();
+ assert_eq!(style.line_spacing, Some(1.33));
+ assert_eq!(style.underline, Some(true));
+ }
+}
diff --git a/crates/ui-egui/src/tools/edit_text_ui/image.rs b/crates/ui-egui/src/tools/edit_text_ui/image.rs
index 53a9116ba..d7ea2e7df 100644
--- a/crates/ui-egui/src/tools/edit_text_ui/image.rs
+++ b/crates/ui-egui/src/tools/edit_text_ui/image.rs
@@ -1,1203 +1,1203 @@
-use super::*;
-use crate::canvas::{ImageObb, PainterExt};
-use crate::image_engine::{
- apply_crop, apply_resize, apply_resize_proportional, draw_handle, draw_rule_of_thirds, HandleId, CROP_ACCENT,
-};
-
-/// The 8 resize handles on an image (4 corners + 4 edge centers).
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-pub enum ImageHandle {
- TopLeft,
- TopCenter,
- TopRight,
- RightCenter,
- BottomRight,
- BottomCenter,
- BottomLeft,
- LeftCenter,
-}
-
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-pub enum DragTarget {
- Move,
- Handle(ImageHandle),
- CropHandle(ImageHandle),
- Rotate,
-}
-
-#[derive(Clone, Copy, Debug, PartialEq)]
-pub struct ImageDrag {
- pub start: Pos2,
- pub target: DragTarget,
- pub initial_rect: Rect,
- pub initial_matrix: [f64; 6],
-}
-
-/// A selected page image, and what the pointer is doing to it.
-#[derive(Clone, Debug, PartialEq)]
-pub struct ImageSelection {
- pub page: usize,
- pub index: usize,
- /// Dragging in progress.
- pub drag: Option<ImageDrag>,
- /// Crop mode: the box kept so far.
- pub crop: Option<CropMode>,
- pub crop_mode: bool,
- pub crop_rect: Option<Rect>,
- /// The drag is turning the picture by its rotate handle (the `drag` start is then unused).
- pub turning: bool,
- /// A move or resize applied on release: the frame it had and the one it got, in the page's
- /// 0..1 coordinates, while the page raster still has the picture where it was.
- pub settled: Option<(Rect, Rect)>,
-}
-
-impl ImageSelection {
- /// Cancel an in-progress text, rotation or crop drag and restore the crop it was previewing.
- pub(crate) fn cancel_pointer_gesture(&mut self) {
- self.drag = None;
- self.turning = false;
- if let Some(crop) = &mut self.crop
- && let Some((_, _, before)) = crop.drag.take()
- {
- crop.keep = before;
- }
- }
-
- pub(crate) fn dragging(&self) -> bool {
- self.drag.is_some()
- }
-}
-
-/// Cropping a page image: the handles trim instead of resizing, the part that will go is
-/// dimmed, Enter or Done applies and Esc or Cancel leaves it.
-#[derive(Clone, Debug, PartialEq)]
-pub struct CropMode {
- /// The box to keep (user space or normalized UV).
- pub keep: [f64; 4],
- /// A drag in progress: the grip (0–7 handles, 8 inside), where it started and the box then.
- pub(crate) drag: Option<(usize, Pos2, [f64; 4])>,
-}
-
-impl CropMode {
- pub fn new(keep: [f64; 4]) -> Self {
- Self { keep, drag: None }
- }
-}
-
-#[derive(Clone, Copy, Debug, PartialEq)]
-pub(crate) struct Matrix(pub(crate) [f64; 6]);
-
-impl Matrix {
- pub(crate) fn apply(&self, x: f64, y: f64) -> (f64, f64) {
- let [a, b, c, d, e, f] = self.0;
- (a * x + c * y + e, b * x + d * y + f)
- }
-
- pub(crate) fn invert(&self) -> Option<Self> {
- let [a, b, c, d, e, f] = self.0;
- let det = a * d - b * c;
- if det.abs() < 1e-12 || !det.is_finite() {
- return None;
- }
- let (ia, ib, ic, id) = (d / det, -b / det, -c / det, a / det);
- Some(Matrix([ia, ib, ic, id, -(e * ia + f * ic), -(e * ib + f * id)]))
- }
-
- pub(crate) fn then(&self, then: &Matrix) -> Matrix {
- let [a, b, c, d, e, f] = self.0;
- let [a2, b2, c2, d2, e2, f2] = then.0;
- Matrix([a * a2 + b * c2, a * b2 + b * d2, c * a2 + d * c2, c * b2 + d * d2, e * a2 + f * c2 + e2, e * b2 + f * d2 + f2])
- }
-}
-
-pub(crate) fn user_to_screen(xf: &PageXform, info: &DocInfo, page: usize, x: f64, y: f64) -> Pos2 {
- let Some(p) = info.pages.get(page) else { return Pos2::ZERO };
- let v = p.user_to_view(x as f32, y as f32);
- xf.norm_to_screen(v[0] / xf.pw, v[1] / xf.ph)
-}
-
-fn screen_to_user(xf: &PageXform, info: &DocInfo, page: usize, pt: Pos2) -> (f64, f64) {
- let (vx, vy) = xf.screen_to_view(pt);
- let Some(p) = info.pages.get(page) else { return (0.0, 0.0) };
- let u = p.view_to_user(vx, vy);
- (f64::from(u[0]), f64::from(u[1]))
-}
-
-pub(crate) fn quad_contains(quad: [Pos2; 4], p: Pos2) -> bool {
- if !p.x.is_finite() || !p.y.is_finite() || quad.iter().any(|pt| !pt.x.is_finite() || !pt.y.is_finite()) {
- return false;
- }
- let mut sign = 0;
- for i in 0..4 {
- let p1 = quad[i];
- let p2 = quad[(i + 1) % 4];
- let cross = (p2.x - p1.x) * (p.y - p1.y) - (p2.y - p1.y) * (p.x - p1.x);
- if cross.abs() > 1e-4 {
- let s = if cross > 0.0 { 1 } else { -1 };
- if sign == 0 {
- sign = s;
- } else if sign != s {
- return false;
- }
- }
- }
- sign != 0
-}
-
-/// The screen positions of the crop's eight handles: corners, then the top, right, bottom and left edge midpoints.
-fn crop_handles(k: Rect) -> [Pos2; 8] {
- [k.left_top(), k.right_top(), k.left_bottom(), k.right_bottom(), k.center_top(), k.right_center(), k.center_bottom(), k.left_center()]
-}
-
-/// Crop mode for the selected image `i` whose visible frame is `b` (screen). Returns `true`
-/// (the pointer and keys are the crop's while it lasts).
-#[allow(clippy::too_many_arguments)]
-fn crop_input(
- ui: &egui::Ui,
- resp: &egui::Response,
- xf: &PageXform,
- ptr: &PagePointer,
- page: usize,
- info: &DocInfo,
- view: &mut DocView,
- i: usize,
- image: &pdfcraft_engine::PageImage,
- allow_interaction: bool,
-) -> bool {
- let painter = ui.painter();
- let Some(sel) = view.image_selection.as_mut() else { return false };
- if let Some(rect) = sel.crop_rect
- && let Some(mode) = sel.crop.as_mut()
- {
- mode.keep = user_box(xf, info, page, rect);
- sel.crop_rect = None;
- }
- let Some(mode) = sel.crop.as_mut() else { return false };
- let hover_pos = ptr.pos;
- let full_b = xf.user_rect(info, page, image.rect.map(|v| v as f32));
- let b = if full_b.is_positive() { full_b } else { xf.user_rect(info, page, image.visible_rect.unwrap_or(image.rect).map(|v| v as f32)) };
- let keep_screen = |keep: [f64; 4]| xf.user_rect(info, page, keep.map(|v| v as f32)).intersect(b);
- let k = keep_screen(mode.keep);
-
- if allow_interaction
- && resp.drag_started()
- && let Some(o) = ptr.origin
- {
- let grip = crop_handles(k).iter().position(|h| h.distance(o) < 10.0).or_else(|| k.contains(o).then_some(8));
- if let Some(g) = grip {
- mode.drag = Some((g, o, mode.keep));
- }
- }
-
- if let Some((grip, start, at_start)) = mode.drag
- && let Some(p) = hover_pos
- {
- let d = p - start;
- let k0 = keep_screen(at_start);
- if grip < 8 {
- let handle_id = match grip {
- 0 => HandleId::TopLeft,
- 1 => HandleId::TopRight,
- 2 => HandleId::BottomLeft,
- 3 => HandleId::BottomRight,
- 4 => HandleId::TopMid,
- 5 => HandleId::RightMid,
- 6 => HandleId::BottomMid,
- _ => HandleId::LeftMid,
- };
- let uv0 = if b.width() > 0.0 && b.height() > 0.0 {
- Rect::from_min_max(
- pos2(((k0.min.x - b.min.x) / b.width()).clamp(0.0, 1.0), ((k0.min.y - b.min.y) / b.height()).clamp(0.0, 1.0)),
- pos2(((k0.max.x - b.min.x) / b.width()).clamp(0.0, 1.0), ((k0.max.y - b.min.y) / b.height()).clamp(0.0, 1.0)),
- )
- } else {
- Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0))
- };
- let (new_screen, _) = apply_crop(k0, uv0, handle_id, d);
- let (min_w, min_h) = (6.0_f32.min(b.width()), 6.0_f32.min(b.height()));
- let clamped = Rect::from_min_max(
- pos2(new_screen.min.x.clamp(b.min.x, b.max.x - min_w), new_screen.min.y.clamp(b.min.y, b.max.y - min_h)),
- pos2(new_screen.max.x.clamp(b.min.x + min_w, b.max.x), new_screen.max.y.clamp(b.min.y + min_h, b.max.y)),
- );
- mode.keep = user_box(xf, info, page, clamped);
- } else {
- let shift = egui::vec2(d.x.clamp(b.min.x - k0.min.x, b.max.x - k0.max.x), d.y.clamp(b.min.y - k0.min.y, b.max.y - k0.max.y));
- mode.keep = user_box(xf, info, page, Rect::from_min_max(k0.min + shift, k0.max + shift));
- }
- if resp.drag_stopped() || !ptr.primary_down {
- mode.drag = None;
- }
- }
-
- // Faint ghost outline of the full uncropped image underneath
- painter.rect_stroke(b, CornerRadius::ZERO, Stroke::new(1.0, Color32::from_rgba_unmultiplied(200, 200, 200, 80)), egui::StrokeKind::Outside);
-
- // Dim outer excluded bands
- let dim = Color32::from_black_alpha(96);
- if k.min.y > b.min.y {
- painter.rect_filled(Rect::from_min_max(b.min, Pos2::new(b.max.x, k.min.y)), CornerRadius::ZERO, dim);
- }
- if k.max.y < b.max.y {
- painter.rect_filled(Rect::from_min_max(Pos2::new(b.min.x, k.max.y), b.max), CornerRadius::ZERO, dim);
- }
- if k.min.x > b.min.x {
- painter.rect_filled(Rect::from_min_max(Pos2::new(b.min.x, k.min.y), Pos2::new(k.min.x, k.max.y)), CornerRadius::ZERO, dim);
- }
- if k.max.x < b.max.x {
- painter.rect_filled(Rect::from_min_max(Pos2::new(k.max.x, k.min.y), Pos2::new(b.max.x, k.max.y)), CornerRadius::ZERO, dim);
- }
-
- // Rule-of-Thirds Grid inside crop area
- draw_rule_of_thirds(painter, k, Stroke::new(1.0, CROP_ACCENT.gamma_multiply(0.45)));
-
- // Crop border stroke
- painter.rect_stroke(k, CornerRadius::ZERO, Stroke::new(1.5, CROP_ACCENT), egui::StrokeKind::Outside);
-
- // Crop handles
- for (idx, h) in crop_handles(k).iter().enumerate() {
- let is_active = mode.drag.as_ref().is_some_and(|d| d.0 == idx);
- let is_hovered = hover_pos.is_some_and(|p| p.distance(*h) < 10.0);
- draw_handle(painter, *h, is_active, is_hovered, true, CROP_ACCENT);
- }
-
- // Action pills
- let font = egui::FontId::proportional(12.5);
- let done_w = painter.layout_no_wrap(tl!("Done").to_string(), font.clone(), Color32::WHITE).size().x + 22.0;
- let cancel_w = painter.layout_no_wrap(tl!("Cancel").to_string(), font.clone(), Color32::WHITE).size().x + 22.0;
- let is_full_rect = (mode.keep[0] - image.rect[0]).abs() < 1e-3
- && (mode.keep[1] - image.rect[1]).abs() < 1e-3
- && (mode.keep[2] - image.rect[2]).abs() < 1e-3
- && (mode.keep[3] - image.rect[3]).abs() < 1e-3;
- let has_crop = !is_full_rect || image.visible_rect.is_some_and(|v| v != image.rect);
- let reset_w =
- if has_crop { Some(painter.layout_no_wrap(tl!("Remove Crop").to_string(), font.clone(), Color32::WHITE).size().x + 22.0) } else { None };
- let spacing = 6.0;
- let total_w = done_w + spacing + cancel_w + reset_w.map_or(0.0, |w| w + spacing);
-
- // Position pills below crop box if there's room, otherwise above
- let y = if k.max.y + 32.0 < xf.rect.max.y {
- k.max.y + 6.0
- } else if k.min.y - 28.0 > xf.rect.min.y {
- k.min.y - 28.0
- } else {
- k.max.y + 6.0
- };
-
- // Right-align pills with k.max.x, clamped inside the page bounds
- let mut right = k.max.x.min(xf.rect.max.x - 8.0);
- if right - total_w < xf.rect.min.x + 8.0 {
- right = (xf.rect.min.x + 8.0 + total_w).min(xf.rect.max.x - 8.0);
- }
-
- let done = Rect::from_min_size(Pos2::new(right - done_w, y), egui::vec2(done_w, 22.0));
- let cancel = Rect::from_min_size(Pos2::new(done.min.x - spacing - cancel_w, y), egui::vec2(cancel_w, 22.0));
- let reset = reset_w.map(|w| Rect::from_min_size(Pos2::new(cancel.min.x - spacing - w, y), egui::vec2(w, 22.0)));
-
- let done_id = ui.scope_id().with("crop_pill_done").with(page).with(i);
- let cancel_id = ui.scope_id().with("crop_pill_cancel").with(page).with(i);
- let reset_id = ui.scope_id().with("crop_pill_reset").with(page).with(i);
-
- let done_resp = ui.interact(done, done_id, egui::Sense::click());
- let cancel_resp = ui.interact(cancel, cancel_id, egui::Sense::click());
- let reset_resp = reset.map(|r| ui.interact(r, reset_id, egui::Sense::click()));
-
- let t = crate::theme::Tokens::get(ui.ctx());
-
- // Done button (accent colored)
- let done_bg = if done_resp.is_pointer_button_down_on() {
- ACCENT.gamma_multiply(0.8)
- } else if done_resp.hovered() {
- Color32::from_rgb(40, 145, 255)
- } else {
- ACCENT
- };
- painter.rect_filled(done, CornerRadius::same(11), done_bg);
- painter.text(done.center(), egui::Align2::CENTER_CENTER, tl!("Done"), font.clone(), Color32::WHITE);
-
- // Cancel button (panel style with border)
- let cancel_bg = if cancel_resp.is_pointer_button_down_on() {
- t.pressed
- } else if cancel_resp.hovered() {
- t.hover
- } else {
- t.card
- };
- let cancel_stroke = Stroke::new(1.0, if cancel_resp.hovered() { ACCENT } else { t.border });
- let cancel_text = if cancel_resp.hovered() { ACCENT } else { t.text };
- painter.rect(cancel, CornerRadius::same(11), cancel_bg, cancel_stroke, egui::StrokeKind::Inside);
- painter.text(cancel.center(), egui::Align2::CENTER_CENTER, tl!("Cancel"), font.clone(), cancel_text);
-
- // Reset button (panel style with border)
- if let (Some(r), Some(r_resp)) = (reset, reset_resp.as_ref()) {
- let reset_bg = if r_resp.is_pointer_button_down_on() {
- t.pressed
- } else if r_resp.hovered() {
- t.hover
- } else {
- t.card
- };
- let reset_stroke = Stroke::new(1.0, if r_resp.hovered() { ACCENT } else { t.border });
- let reset_text = if r_resp.hovered() { ACCENT } else { t.text };
- painter.rect(r, CornerRadius::same(11), reset_bg, reset_stroke, egui::StrokeKind::Inside);
- painter.text(r.center(), egui::Align2::CENTER_CENTER, tl!("Remove Crop"), font.clone(), reset_text);
- }
-
- if let Some(p) = hover_pos {
- let icon = if done_resp.hovered()
- || cancel_resp.hovered()
- || reset_resp.as_ref().is_some_and(|r| r.hovered())
- || done.contains(p)
- || cancel.contains(p)
- || reset.is_some_and(|r| r.contains(p))
- {
- egui::CursorIcon::PointingHand
- } else if let Some(g) = crop_handles(k).iter().position(|h| h.distance(p) < 8.0) {
- match g {
- 0 => HandleId::TopLeft.cursor_icon(),
- 1 => HandleId::TopRight.cursor_icon(),
- 2 => HandleId::BottomLeft.cursor_icon(),
- 3 => HandleId::BottomRight.cursor_icon(),
- 4 => HandleId::TopMid.cursor_icon(),
- 5 => HandleId::RightMid.cursor_icon(),
- 6 => HandleId::BottomMid.cursor_icon(),
- _ => HandleId::LeftMid.cursor_icon(),
- }
- } else if k.contains(p) {
- if mode.drag.is_some() { egui::CursorIcon::Grabbing } else { egui::CursorIcon::Grab }
- } else {
- egui::CursorIcon::Default
- };
- ui.ctx().set_cursor_icon(icon);
- }
-
- let keys = |key: egui::Key| allow_interaction && ui.input(|inp| inp.key_pressed(key)) && !ui.ctx().egui_wants_keyboard_input();
- let done_clicked = allow_interaction && (done_resp.clicked() || (resp.clicked() && hover_pos.is_some_and(|p| done.contains(p))));
- let cancel_clicked = allow_interaction && (cancel_resp.clicked() || (resp.clicked() && hover_pos.is_some_and(|p| cancel.contains(p))));
- let reset_clicked = allow_interaction
- && reset
- .is_some_and(|r| reset_resp.as_ref().is_some_and(|res| res.clicked()) || (resp.clicked() && hover_pos.is_some_and(|p| r.contains(p))));
-
- if reset_clicked {
- mode.keep = image.rect;
- mode.drag = None;
- if let Some(s) = view.image_selection.as_mut() {
- s.crop_rect = None;
- }
- } else if done_clicked || keys(egui::Key::Enter) {
- let keep = mode.keep;
- if let Some(s) = view.image_selection.as_mut() {
- s.crop = None;
- s.crop_mode = false;
- s.crop_rect = None;
- }
- let is_full = (keep[0] - image.rect[0]).abs() < 1e-3
- && (keep[1] - image.rect[1]).abs() < 1e-3
- && (keep[2] - image.rect[2]).abs() < 1e-3
- && (keep[3] - image.rect[3]).abs() < 1e-3;
- if is_full {
- if image.visible_rect.is_some_and(|v| v != image.rect) {
- view.pending_edit = Some(Edit::EditPageImage { page, index: i, change: pdfcraft_engine::ImageEdit::RemoveCrop });
- }
- } else if image.visible_rect != Some(keep) {
- view.pending_edit = Some(Edit::EditPageImage { page, index: i, change: pdfcraft_engine::ImageEdit::Crop(keep) });
- }
- } else if (cancel_clicked || keys(egui::Key::Escape))
- && let Some(s) = view.image_selection.as_mut()
- {
- s.crop = None;
- s.crop_mode = false;
- s.crop_rect = None;
- }
- true
-}
-
-/// The page raster's picture of the box `from`, stretched into `to`, over blanks at `blank` (where
-/// the screen may still show the picture).
-fn stretched_picture(painter: &egui::Painter, xf: &PageXform, tex: egui::TextureId, blank: &[Rect], from: Rect, to: Rect) {
- let clipped = painter.with_clip_rect(painter.clip_rect().intersect(xf.rect));
- for r in blank {
- clipped.rect_filled(*r, CornerRadius::ZERO, Color32::WHITE);
- }
- let mut mesh = egui::Mesh::with_texture(tex);
- for (a, b) in [
- (from.left_top(), to.left_top()),
- (from.right_top(), to.right_top()),
- (from.right_bottom(), to.right_bottom()),
- (from.left_bottom(), to.left_bottom()),
- ] {
- let (u, v) = xf.screen_to_norm(a);
- mesh.vertices.push(egui::epaint::Vertex { pos: b, uv: Pos2::new(u, v), color: Color32::WHITE });
- }
- mesh.add_triangle(0, 1, 2);
- mesh.add_triangle(0, 2, 3);
- clipped.add(egui::Shape::mesh(mesh));
-}
-
-/// Once a selected corner or the rotate knob is grabbed, text under it cannot take over the gesture. The same
-/// applies after the pointer leaves the image/page while dragging.
-pub(crate) fn image_owns_pointer(_ui: &egui::Ui, xf: &PageXform, ptr: &PagePointer, page: usize, info: &DocInfo, view: &DocView) -> bool {
- let Some(selection) = view.image_selection.as_ref().filter(|s| s.page == page) else { return false };
- if selection.drag.is_some() || selection.crop.is_some() || selection.crop_mode {
- return true;
- }
- let Some(image) = view.edit_images.get(&page).and_then(|(_, images)| images.get(selection.index)) else { return false };
- let obb = ImageObb::from_image(image, xf, info, page);
- let p = if ptr.primary_down { ptr.origin.or(ptr.pos) } else { ptr.pos };
- let Some(p) = p else { return false };
-
- obb.handles().iter().any(|(_, h)| h.distance(p) < 8.0) || obb.s_rot.distance(p) < 8.0
-}
-
-/// What a right-click on a selected image asks for.
-#[derive(Clone, Copy, Debug, PartialEq)]
-pub enum ImageAction {
- Replace(usize, usize),
- Save(usize, usize),
- Copy(usize, usize),
- CopyFile(usize, usize),
- /// Copy the picture, then remove it from the page.
- Cut(usize, usize),
- /// Mark the picture for redaction (applied later from Redact a PDF).
- Redact(usize, usize),
- /// Create a link over the picture.
- Link(usize, usize),
- /// Open Recognize Text for the picture's page.
- Recognize(usize),
- Paste(usize, Option<[f64; 2]>),
- DrawFreehand,
- AddComment(usize, usize),
- Crop,
-}
-
-/// Where the rotate knob sits, and the edge point its stem starts from: above the middle of the
-/// top edge, or below the bottom edge when the area on screen (`view`) has no room above.
-pub(super) fn rotate_knob(b: Rect, view: Rect) -> (Pos2, Pos2) {
- let above = b.center_top() - egui::vec2(0.0, 22.0);
- if above.y - 6.0 >= view.top() { (above, b.center_top()) } else { (b.center_bottom() + egui::vec2(0.0, 22.0), b.center_bottom()) }
-}
-
-/// Degrees clockwise (-180..=180) that turn "straight up" from `centre` onto the pointer; `snap`
-/// rounds to steps of 15 degrees (Shift). A pointer on the centre turns nothing.
-pub(super) fn turn_degrees(centre: Pos2, pointer: Pos2, snap: bool) -> f32 {
- let v = pointer - centre;
- if !(v.x.is_finite() && v.y.is_finite()) || v.length() < 4.0 {
- return 0.0;
- }
- // Screen y points down: up is (0, -1); clockwise is atan2(x, -y).
- let d = v.x.atan2(-v.y).to_degrees();
- if snap { (d / 15.0).round() * 15.0 } else { d }
-}
-
-#[doc(hidden)]
-pub fn image_menu_id() -> egui::Id {
- egui::Id::unique("image-menu")
-}
-
-/// Images on a page: select, move, resize, right-click. Returns `true` when the pointer was used.
-#[allow(clippy::too_many_arguments)]
-pub(crate) fn image_input(
- ui: &egui::Ui,
- resp: &egui::Response,
- xf: &PageXform,
- ptr: &PagePointer,
- page: usize,
- info: &DocInfo,
- images: &[pdfcraft_engine::PageImage],
- view: &mut DocView,
- action: &mut Option<ImageAction>,
- allow_interaction: bool,
-) -> bool {
- let _ = &action;
- let boxes: Vec<Rect> = images.iter().map(|im| crate::canvas::image_screen_rect(im, xf, info, page)).collect();
- let painter = ui.painter();
- let hover_pos = ptr.pos;
- let image_contains = |index: usize, point: Pos2| {
- let (x, y) = xf.screen_to_view(point);
- let Some(p) = info.pages.get(page) else { return false };
- let user = p.view_to_user(x, y);
- images.get(index).is_some_and(|im| im.contains(user.map(f64::from)))
- };
- let selected = view.image_selection.as_ref().filter(|s| s.page == page).map(|s| s.index).filter(|i| *i < boxes.len());
- let dragging = view.image_selection.as_ref().is_some_and(|s| s.drag.is_some());
- let faint_all = boxes.len() <= MAX_OUTLINES;
- let moving = selected.filter(|_| dragging);
- if faint_all {
- for (idx, im) in images.iter().enumerate() {
- if moving == Some(idx) {
- continue;
- }
- if let Some(b) = boxes.get(idx).filter(|b| b.is_positive()) {
- let obb = ImageObb::from_image(im, xf, info, page);
- if obb.is_rotated {
- let pts = obb.corners();
- for k in 0..4 {
- painter.line_segment([pts[k], pts[(k + 1) % 4]], Stroke::new(0.75, ACCENT.gamma_multiply(0.35)));
- }
- } else {
- painter.rect_stroke(*b, CornerRadius::ZERO, Stroke::new(0.75, ACCENT.gamma_multiply(0.35)), egui::StrokeKind::Outside);
- }
- }
- }
- }
- let hovered_box = hover_pos.and_then(|p| {
- boxes.iter().enumerate().rposition(|(i, b)| {
- b.is_positive()
- && images.get(i).is_some_and(|img| b.contains(p) || quad_contains(ImageObb::from_image(img, xf, info, page).corners(), p))
- && image_contains(i, p)
- })
- });
- if !faint_all {
- for i in selected.filter(|_| moving.is_none()).into_iter().chain(hovered_box.filter(|h| Some(*h) != selected)) {
- if let (Some(b), Some(img)) = (boxes.get(i).filter(|b| b.is_positive()), images.get(i)) {
- let obb = ImageObb::from_image(img, xf, info, page);
- if obb.is_rotated {
- let pts = obb.corners();
- for k in 0..4 {
- painter.line_segment([pts[k], pts[(k + 1) % 4]], Stroke::new(0.75, ACCENT.gamma_multiply(0.35)));
- }
- } else {
- painter.rect_stroke(*b, CornerRadius::ZERO, Stroke::new(0.75, ACCENT.gamma_multiply(0.35)), egui::StrokeKind::Outside);
- }
- }
- }
- }
- for i in selected.into_iter().chain(hovered_box).collect::<Vec<_>>() {
- let (Some(b), Some(img)) = (boxes.get(i).copied().filter(|b| b.is_positive()), images.get(i)) else { continue };
- let obb = ImageObb::from_image(img, xf, info, page);
- if selected == Some(i) {
- if !dragging {
- if obb.is_rotated {
- painter.polygon(obb.corners().to_vec(), ACCENT.gamma_multiply(0.04), Stroke::NONE);
- } else {
- painter.rect_filled(b, CornerRadius::ZERO, ACCENT.gamma_multiply(0.04));
- }
- }
- } else if obb.is_rotated {
- painter.polygon(obb.corners().to_vec(), Color32::TRANSPARENT, Stroke::new(1.5, ACCENT.gamma_multiply(0.7)));
- } else {
- painter.rect_stroke(b, CornerRadius::ZERO, Stroke::new(1.5, ACCENT.gamma_multiply(0.7)), egui::StrokeKind::Outside);
- }
- }
- // The selected image: frame, corner handles, dragging.
- if let Some(i) = selected.filter(|i| boxes.get(*i).is_some_and(|b| b.is_positive())) {
- let Some(b) = boxes.get(i).copied() else { return false };
- let Some(image) = images.get(i) else { return false };
- let obb = ImageObb::from_image(image, xf, info, page);
- let (out_of_date, raster_old, raster) = (view.page_out_of_date(page), view.page_raster_out_of_date(page), view.page_raster(page));
- let screen = |r: Rect| Rect::from_two_pos(xf.norm_to_screen(r.min.x, r.min.y), xf.norm_to_screen(r.max.x, r.max.y));
- let left_at = view.image_selection.as_ref().and_then(|s| s.settled).filter(|_| out_of_date).map(|(from, _)| from);
- if let Some(s) = view.image_selection.as_mut().filter(|s| s.drag.is_none()) {
- match (s.settled, raster) {
- (Some((from, to)), Some(tex)) if out_of_date => {
- let source = if raster_old { from } else { to };
- stretched_picture(painter, xf, tex, &[screen(from)], screen(source), screen(to));
- }
- _ if !out_of_date => s.settled = None,
- _ => {}
- }
- }
-
- if view.image_selection.as_ref().is_some_and(|s| s.crop.is_some() || s.crop_mode) {
- if let Some(s) = view.image_selection.as_mut()
- && s.crop.is_none()
- {
- let rect = images.get(i).and_then(|im| im.visible_rect).unwrap_or(images.get(i).map_or([0.0; 4], |im| im.rect));
- s.crop = Some(CropMode::new(rect));
- }
- return crop_input(ui, resp, xf, ptr, page, info, view, i, image, allow_interaction);
- }
- let (knob, stem) = rotate_knob(b, ui.clip_rect());
- if view.image_selection.as_ref().is_some_and(|s| s.drag.is_none()) {
- if obb.is_rotated {
- painter.polygon(obb.corners().to_vec(), Color32::TRANSPARENT, Stroke::new(1.5, ACCENT));
- painter.line_segment([obb.s_tc, obb.s_rot], Stroke::new(1.2, ACCENT));
- painter.circle(obb.s_rot, 4.5, Color32::WHITE, Stroke::new(1.0, ACCENT));
- } else {
- painter.rect_stroke(b, CornerRadius::ZERO, Stroke::new(1.5, ACCENT), egui::StrokeKind::Outside);
- painter.line_segment([stem, knob], Stroke::new(1.0, ACCENT));
- painter.circle(knob, 5.0, Color32::WHITE, Stroke::new(1.0, ACCENT));
- }
- for (_, h) in obb.handles() {
- let is_hovered = hover_pos.is_some_and(|p| p.distance(h) < 10.0);
- draw_handle(painter, h, false, is_hovered, false, ACCENT);
- }
- }
-
- let mut handle_drag = None;
- for (h, h_pos, handle_id) in obb.handles_with_ids(ui.scope_id().with("img_handle")) {
- let handle_rect = Rect::from_center_size(h_pos, egui::vec2(18.0, 18.0));
- let handle_resp = ui.interact(handle_rect, handle_id, egui::Sense::drag());
- if allow_interaction && handle_resp.drag_started() {
- handle_drag = Some(h);
- }
- }
- let rot_id = ui.scope_id().with("img_handle").with(8);
- let rot_rect = Rect::from_center_size(if obb.is_rotated { obb.s_rot } else { knob }, egui::vec2(12.0, 12.0));
- let rot_resp = ui.interact(rot_rect, rot_id, egui::Sense::drag());
- let rot_drag = allow_interaction && rot_resp.drag_started();
-
- if allow_interaction && let Some(p) = hover_pos {
- if obb.s_rot.distance(p) < 8.0 || knob.distance(p) < 8.0 {
- ui.ctx().set_cursor_icon(egui::CursorIcon::Grab);
- } else if let Some((h, _)) = obb.handles().iter().find(|(_, pos)| pos.distance(p) < 8.0) {
- let icon = match h {
- ImageHandle::TopLeft | ImageHandle::BottomRight => {
- if obb.is_rotated {
- let v = obb.handle_pos(*h) - obb.screen_center;
- if v.x * v.y > 0.0 { egui::CursorIcon::ResizeNwSe } else { egui::CursorIcon::ResizeNeSw }
- } else {
- egui::CursorIcon::ResizeNwSe
- }
- }
- ImageHandle::TopRight | ImageHandle::BottomLeft => {
- if obb.is_rotated {
- let v = obb.handle_pos(*h) - obb.screen_center;
- if v.x * v.y > 0.0 { egui::CursorIcon::ResizeNwSe } else { egui::CursorIcon::ResizeNeSw }
- } else {
- egui::CursorIcon::ResizeNeSw
- }
- }
- ImageHandle::TopCenter | ImageHandle::BottomCenter => {
- if obb.is_rotated && (obb.v_axis.0.abs() > obb.v_axis.1.abs()) {
- egui::CursorIcon::ResizeHorizontal
- } else {
- egui::CursorIcon::ResizeVertical
- }
- }
- ImageHandle::RightCenter | ImageHandle::LeftCenter => {
- if obb.is_rotated && (obb.u_axis.1.abs() > obb.u_axis.0.abs()) {
- egui::CursorIcon::ResizeVertical
- } else {
- egui::CursorIcon::ResizeHorizontal
- }
- }
- };
- ui.ctx().set_cursor_icon(icon);
- }
- }
-
- let origin = ptr.origin;
- if allow_interaction {
- if let Some(h) = handle_drag {
- if let Some(s) = view.image_selection.as_mut() {
- let o = origin.unwrap_or_else(|| obb.handle_pos(h));
- s.drag = Some(ImageDrag { start: o, target: DragTarget::Handle(h), initial_rect: b, initial_matrix: image.matrix });
- }
- } else if rot_drag {
- if let Some(s) = view.image_selection.as_mut() {
- let o = origin.unwrap_or(if obb.is_rotated { obb.s_rot } else { knob });
- s.drag = Some(ImageDrag { start: o, target: DragTarget::Rotate, initial_rect: b, initial_matrix: image.matrix });
- s.turning = true;
- }
- } else if resp.drag_started()
- && let Some(o) = origin
- {
- if obb.s_rot.distance(o) < 8.0 || knob.distance(o) < 8.0 {
- if let Some(s) = view.image_selection.as_mut() {
- s.drag = Some(ImageDrag { start: o, target: DragTarget::Rotate, initial_rect: b, initial_matrix: image.matrix });
- s.turning = true;
- }
- } else if let Some((h, _)) = obb.handles().iter().find(|(_, pos)| pos.distance(o) < 8.0) {
- if let Some(s) = view.image_selection.as_mut() {
- s.drag = Some(ImageDrag { start: o, target: DragTarget::Handle(*h), initial_rect: b, initial_matrix: image.matrix });
- }
- } else if (image_contains(i, o) || quad_contains(obb.corners(), o))
- && let Some(s) = view.image_selection.as_mut()
- {
- s.drag = Some(ImageDrag { start: o, target: DragTarget::Move, initial_rect: b, initial_matrix: image.matrix });
- }
- }
- }
-
- if view.image_selection.as_ref().is_some_and(|s| s.turning) {
- let shift = ui.input(|i| i.modifiers.shift);
- let degrees = hover_pos.map_or(0.0, |p| turn_degrees(b.center(), p, shift));
- let centre = b.center();
- let (sin, cos) = degrees.to_radians().sin_cos();
- let turn = |c: Pos2| {
- let v = c - centre;
- centre + egui::vec2(v.x * cos - v.y * sin, v.x * sin + v.y * cos)
- };
- let outline = [b.left_top(), b.right_top(), b.right_bottom(), b.left_bottom()].map(turn).to_vec();
- painter.add(egui::Shape::closed_line(outline, Stroke::new(1.5, ACCENT)));
- let galley = painter.layout_no_wrap(format!("{degrees:.0}\u{b0}"), egui::FontId::proportional(12.0), ACCENT);
- let label = Rect::from_center_size(turn(knob) - egui::vec2(0.0, 14.0), galley.size() + egui::vec2(8.0, 4.0));
- painter.rect(label, CornerRadius::same(3), Color32::WHITE, Stroke::new(1.0, ACCENT), egui::StrokeKind::Middle);
- painter.galley(label.center() - galley.size() / 2.0, galley, ACCENT);
- ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing);
- if resp.drag_stopped() || !ptr.primary_down {
- if let Some(s) = view.image_selection.as_mut() {
- s.drag = None;
- s.turning = false;
- }
- if degrees.abs() >= 0.05 {
- view.pending_edit =
- Some(Edit::EditPageImage { page, index: i, change: pdfcraft_engine::ImageEdit::RotateBy(f64::from(degrees)) });
- }
- }
- return true;
- }
-
- if let Some(drag) = view.image_selection.as_ref().and_then(|s| s.drag)
- && let Some(p) = hover_pos
- {
- if !obb.is_rotated && !matches!(drag.target, DragTarget::Rotate) {
- let preview = match drag.target {
- DragTarget::Handle(handle) => {
- let handle_id = HandleId::from(handle);
- let delta = p - drag.start;
- let is_corner = matches!(handle_id, HandleId::TopLeft | HandleId::TopRight | HandleId::BottomLeft | HandleId::BottomRight);
- let shift = ui.input(|inp| inp.modifiers.shift);
- if is_corner && !shift {
- apply_resize_proportional(drag.initial_rect, handle_id, delta)
- } else {
- apply_resize(drag.initial_rect, handle_id, delta)
- }
- }
- DragTarget::Move => drag.initial_rect.translate(p - drag.start),
- _ => drag.initial_rect,
- };
-
- let raw = images.get(i).map_or(b, |im| xf.user_rect(info, page, im.rect.map(|v| v as f32)));
- let ratio = |new: f32, old: f32| if old.abs() > 1e-3 && (new / old).is_finite() { new / old } else { 1.0 };
- let factor = egui::vec2(ratio(preview.width(), b.width()), ratio(preview.height(), b.height()));
- let f_min = egui::vec2((raw.min.x - b.min.x) * factor.x, (raw.min.y - b.min.y) * factor.y);
- let f_max = egui::vec2((raw.max.x - b.min.x) * factor.x, (raw.max.y - b.min.y) * factor.y);
- let target = Rect::from_min_max(preview.min + f_min, preview.min + f_max);
- let visible = preview.intersect(xf.rect);
-
- if visible.is_positive() {
- if preview != b
- && let Some(tex) = raster
- {
- let source = left_at.filter(|_| raster_old).map_or(b, screen);
- let blank: Vec<Rect> = left_at.map(screen).into_iter().chain(std::iter::once(b)).collect();
- stretched_picture(painter, xf, tex, &blank, source, preview);
- }
- painter.rect_filled(visible, CornerRadius::ZERO, ACCENT.gamma_multiply(0.04));
- painter.rect_stroke(visible, CornerRadius::ZERO, Stroke::new(1.5, ACCENT), egui::StrokeKind::Outside);
- for h in [
- preview.left_top(),
- preview.right_top(),
- preview.left_bottom(),
- preview.right_bottom(),
- preview.center_top(),
- preview.right_center(),
- preview.center_bottom(),
- preview.left_center(),
- ] {
- draw_handle(painter, h, false, false, false, ACCENT);
- }
- }
-
- if resp.drag_stopped() || !ptr.primary_down {
- if let Some(s) = view.image_selection.as_mut() {
- s.drag = None;
- let norm = |r: Rect| {
- let ((u0, v0), (u1, v1)) = (xf.screen_to_norm(r.min), xf.screen_to_norm(r.max));
- Rect::from_two_pos(Pos2::new(u0, v0), Pos2::new(u1, v1))
- };
- s.settled = (preview != b).then(|| (left_at.unwrap_or_else(|| norm(b)), norm(preview)));
- }
- if preview != b {
- view.pending_edit =
- Some(Edit::EditPageImage { page, index: i, change: pdfcraft_engine::ImageEdit::Move(user_box(xf, info, page, target)) });
- }
- }
-
- let icon = match drag.target {
- DragTarget::Handle(handle) => HandleId::from(handle).cursor_icon(),
- DragTarget::Move => egui::CursorIcon::Grabbing,
- _ => egui::CursorIcon::Move,
- };
- ui.ctx().set_cursor_icon(icon);
- return true;
- }
- let m_init = Matrix(drag.initial_matrix);
- let [a0, b0, c0, d0, e0, f0] = drag.initial_matrix;
- let w0 = (a0 * a0 + b0 * b0).sqrt().max(1e-6);
- let h0 = (c0 * c0 + d0 * d0).sqrt().max(1e-6);
- let u_axis = (a0 / w0, b0 / w0);
- let v_axis = (c0 / h0, d0 / h0);
- let center_user = (e0 + 0.5 * (a0 + c0), f0 + 0.5 * (b0 + d0));
-
- let (sx, sy) = screen_to_user(xf, info, page, drag.start);
- let (px, py) = screen_to_user(xf, info, page, p);
-
- let (m_new, cursor_icon) = match drag.target {
- DragTarget::Rotate => {
- let v0 = (sx - center_user.0, sy - center_user.1);
- let v1 = (px - center_user.0, py - center_user.1);
- let theta0 = v0.1.atan2(v0.0);
- let theta1 = v1.1.atan2(v1.0);
- let mut delta = theta1 - theta0;
- if ui.input(|i| i.modifiers.shift) {
- let step = std::f64::consts::PI / 12.0;
- delta = (delta / step).round() * step;
- }
- let (cos_d, sin_d) = (delta.cos(), delta.sin());
- let t_rot = [
- cos_d,
- sin_d,
- -sin_d,
- cos_d,
- center_user.0 * (1.0 - cos_d) + center_user.1 * sin_d,
- center_user.1 * (1.0 - cos_d) - center_user.0 * sin_d,
- ];
- (m_init.then(&Matrix(t_rot)), egui::CursorIcon::Grab)
- }
- DragTarget::Move => {
- let (dx, dy) = (px - sx, py - sy);
- (Matrix([a0, b0, c0, d0, e0 + dx, f0 + dy]), egui::CursorIcon::Move)
- }
- DragTarget::Handle(handle) => {
- let p00 = (e0, f0);
- let p10 = (e0 + a0, f0 + b0);
- let p11 = (e0 + a0 + c0, f0 + b0 + d0);
- let p01 = (e0 + c0, f0 + d0);
- let p_curr = (px, py);
-
- let (new_w, new_h, p00_new, icon) = match handle {
- ImageHandle::TopRight => {
- let anchor = p00;
- let d = (p_curr.0 - anchor.0, p_curr.1 - anchor.1);
- let du = d.0 * u_axis.0 + d.1 * u_axis.1;
- let dv = d.0 * v_axis.0 + d.1 * v_axis.1;
- let su = du / w0;
- let sv = dv / h0;
- let s = if (su - 1.0).abs() >= (sv - 1.0).abs() { su } else { sv };
- let s = s.max(5.0 / w0).max(5.0 / h0);
- (w0 * s, h0 * s, anchor, egui::CursorIcon::ResizeNeSw)
- }
- ImageHandle::TopLeft => {
- let anchor = p10;
- let d = (p_curr.0 - anchor.0, p_curr.1 - anchor.1);
- let du = d.0 * (-u_axis.0) + d.1 * (-u_axis.1);
- let dv = d.0 * v_axis.0 + d.1 * v_axis.1;
- let su = du / w0;
- let sv = dv / h0;
- let s = if (su - 1.0).abs() >= (sv - 1.0).abs() { su } else { sv };
- let s = s.max(5.0 / w0).max(5.0 / h0);
- let nw = w0 * s;
- let nh = h0 * s;
- (nw, nh, (anchor.0 - nw * u_axis.0, anchor.1 - nw * u_axis.1), egui::CursorIcon::ResizeNwSe)
- }
- ImageHandle::BottomLeft => {
- let anchor = p11;
- let d = (p_curr.0 - anchor.0, p_curr.1 - anchor.1);
- let du = d.0 * (-u_axis.0) + d.1 * (-u_axis.1);
- let dv = d.0 * (-v_axis.0) + d.1 * (-v_axis.1);
- let su = du / w0;
- let sv = dv / h0;
- let s = if (su - 1.0).abs() >= (sv - 1.0).abs() { su } else { sv };
- let s = s.max(5.0 / w0).max(5.0 / h0);
- let nw = w0 * s;
- let nh = h0 * s;
- (
- nw,
- nh,
- (anchor.0 - nw * u_axis.0 - nh * v_axis.0, anchor.1 - nw * u_axis.1 - nh * v_axis.1),
- egui::CursorIcon::ResizeNeSw,
- )
- }
- ImageHandle::BottomRight => {
- let anchor = p01;
- let d = (p_curr.0 - anchor.0, p_curr.1 - anchor.1);
- let du = d.0 * u_axis.0 + d.1 * u_axis.1;
- let dv = d.0 * (-v_axis.0) + d.1 * (-v_axis.1);
- let su = du / w0;
- let sv = dv / h0;
- let s = if (su - 1.0).abs() >= (sv - 1.0).abs() { su } else { sv };
- let s = s.max(5.0 / w0).max(5.0 / h0);
- let nw = w0 * s;
- let nh = h0 * s;
- (nw, nh, (anchor.0 - nh * v_axis.0, anchor.1 - nh * v_axis.1), egui::CursorIcon::ResizeNwSe)
- }
- ImageHandle::RightCenter => {
- let anchor = p00;
- let d = (p_curr.0 - anchor.0, p_curr.1 - anchor.1);
- let du = (d.0 * u_axis.0 + d.1 * u_axis.1).max(5.0);
- (du, h0, anchor, egui::CursorIcon::ResizeHorizontal)
- }
- ImageHandle::LeftCenter => {
- let anchor = p10;
- let d = (p_curr.0 - anchor.0, p_curr.1 - anchor.1);
- let du = (d.0 * (-u_axis.0) + d.1 * (-u_axis.1)).max(5.0);
- (du, h0, (anchor.0 - du * u_axis.0, anchor.1 - du * u_axis.1), egui::CursorIcon::ResizeHorizontal)
- }
- ImageHandle::TopCenter => {
- let anchor = p00;
- let d = (p_curr.0 - anchor.0, p_curr.1 - anchor.1);
- let dv = (d.0 * v_axis.0 + d.1 * v_axis.1).max(5.0);
- (w0, dv, anchor, egui::CursorIcon::ResizeVertical)
- }
- ImageHandle::BottomCenter => {
- let anchor = p01;
- let d = (p_curr.0 - anchor.0, p_curr.1 - anchor.1);
- let dv = (d.0 * (-v_axis.0) + d.1 * (-v_axis.1)).max(5.0);
- (w0, dv, (anchor.0 - dv * v_axis.0, anchor.1 - dv * v_axis.1), egui::CursorIcon::ResizeVertical)
- }
- };
- let mat = Matrix([new_w * u_axis.0, new_w * u_axis.1, new_h * v_axis.0, new_h * v_axis.1, p00_new.0, p00_new.1]);
- (mat, icon)
- }
- _ => (m_init, egui::CursorIcon::Default),
- };
-
- let preview_obb = ImageObb::new(m_new.0, xf, info, page);
- if let Some(tex) = view.page_raster(page) {
- let clipped = painter.with_clip_rect(painter.clip_rect().intersect(xf.rect));
- let mut mesh = egui::Mesh::with_texture(tex);
- let orig_corners = obb.corners();
- let new_corners = preview_obb.corners();
- for (from, to) in [
- (orig_corners[3], new_corners[3]),
- (orig_corners[2], new_corners[2]),
- (orig_corners[1], new_corners[1]),
- (orig_corners[0], new_corners[0]),
- ] {
- let (u, v) = xf.screen_to_norm(from);
- mesh.vertices.push(egui::epaint::Vertex { pos: to, uv: Pos2::new(u, v), color: Color32::WHITE });
- }
- mesh.add_triangle(0, 1, 2);
- mesh.add_triangle(0, 2, 3);
- clipped.add(egui::Shape::mesh(mesh));
- }
-
- if preview_obb.is_rotated {
- let pts = preview_obb.corners();
- painter.polygon(pts.to_vec(), ACCENT.gamma_multiply(0.04), Stroke::new(1.5, ACCENT));
- } else {
- let p_rect = Rect::from_two_pos(preview_obb.s01, preview_obb.s10);
- let visible = p_rect.intersect(xf.rect);
- if visible.is_positive() {
- painter.rect_filled(visible, CornerRadius::ZERO, ACCENT.gamma_multiply(0.04));
- painter.rect_stroke(visible, CornerRadius::ZERO, Stroke::new(1.5, ACCENT), egui::StrokeKind::Outside);
- }
- }
- for (_, h) in preview_obb.handles() {
- draw_handle(painter, h, false, false, false, ACCENT);
- }
-
- if resp.drag_stopped() || !ptr.primary_down {
- if let Some(s) = view.image_selection.as_mut() {
- s.drag = None;
- }
- if m_new.0 != drag.initial_matrix {
- if matches!(drag.target, DragTarget::Move) {
- let (dx, dy) = (px - sx, py - sy);
- let new_rect = [image.rect[0] + dx, image.rect[1] + dy, image.rect[2] + dx, image.rect[3] + dy];
- view.pending_edit = Some(Edit::EditPageImage { page, index: i, change: pdfcraft_engine::ImageEdit::Move(new_rect) });
- } else if let Some(inv) = Matrix(drag.initial_matrix).invert() {
- let t = inv.then(&m_new);
- view.pending_edit = Some(Edit::EditPageImage { page, index: i, change: pdfcraft_engine::ImageEdit::Transform(t.0) });
- }
- }
- }
- ui.ctx().set_cursor_icon(cursor_icon);
- return true;
- }
- if allow_interaction
- && ui.input(|inp| inp.key_pressed(egui::Key::Delete) || inp.key_pressed(egui::Key::Backspace))
- && !ui.ctx().egui_wants_keyboard_input()
- {
- view.image_selection = None;
- view.pending_edit = Some(Edit::EditPageImage { page, index: i, change: pdfcraft_engine::ImageEdit::Delete });
- return true;
- }
- }
- if !allow_interaction {
- return false;
- }
- let menu_key = image_menu_id();
- let Some(p) = hover_pos.filter(|p| xf.rect.contains(*p)) else { return false };
- let Some(hit) = boxes.iter().enumerate().rposition(|(i, b)| {
- b.is_positive()
- && images.get(i).is_some_and(|img| b.contains(p) || quad_contains(ImageObb::from_image(img, xf, info, page).corners(), p))
- && image_contains(i, p)
- }) else {
- if resp.secondary_clicked() || resp.clicked() {
- view.image_selection = None;
- ui.ctx().data_mut(|d| d.insert_persisted(menu_key, false));
- }
- return false;
- };
- let Some(hit_img) = images.get(hit) else { return false };
- let hit_obb = ImageObb::from_image(hit_img, xf, info, page);
- if selected != Some(hit) {
- if hit_obb.is_rotated {
- let pts = hit_obb.corners();
- for k in 0..4 {
- painter.line_segment([pts[k], pts[(k + 1) % 4]], Stroke::new(1.5, ACCENT.gamma_multiply(0.7)));
- }
- } else if let Some(b) = boxes.get(hit).copied() {
- painter.rect_stroke(b, CornerRadius::ZERO, Stroke::new(1.5, ACCENT.gamma_multiply(0.7)), egui::StrokeKind::Outside);
- }
- }
- let corner = hit_obb.handles().iter().position(|(_, c)| c.distance(p) < 10.0);
- ui.ctx().set_cursor_icon(match (selected == Some(hit), corner) {
- (true, Some(0 | 4)) => egui::CursorIcon::ResizeNwSe,
- (true, Some(2 | 6)) => egui::CursorIcon::ResizeNeSw,
- (true, Some(1 | 5)) => egui::CursorIcon::ResizeVertical,
- (true, Some(3 | 7)) => egui::CursorIcon::ResizeHorizontal,
- (true, None) => egui::CursorIcon::Grab,
- _ => egui::CursorIcon::PointingHand,
- });
- if resp.clicked() || resp.secondary_clicked() {
- view.image_selection =
- Some(ImageSelection { page, index: hit, drag: None, crop: None, crop_mode: false, crop_rect: None, turning: false, settled: None });
- }
- if resp.secondary_clicked() {
- ui.ctx().data_mut(|d| d.insert_persisted(menu_key, true));
- }
- true
-}
-
-/// The right-click context menu for a selected image.
-#[allow(clippy::too_many_arguments)]
-pub(crate) fn image_context_menu(
- ui: &mut egui::Ui,
- view: &mut DocView,
- images: &[pdfcraft_engine::PageImage],
- page: usize,
- hit: usize,
- can_paste: bool,
- action: &mut Option<ImageAction>,
- at: Option<[f64; 2]>,
-) {
- let Some(img) = images.get(hit) else { return };
- use pdfcraft_engine::ImageEdit as E;
- let raster = !img.is_form;
-
- let close = |ui: &mut egui::Ui| {
- ui.ctx().data_mut(|d| d.insert_persisted(image_menu_id(), false));
- egui::Popup::close_all(ui.ctx());
- ui.close();
- };
-
- // Top horizontal icon bar: Comment, Crop, Rotate CCW, Rotate CW
- ui.horizontal(|ui| {
- ui.spacing_mut().item_spacing.x = 4.0;
- if crate::icons::button(ui, "message-square", 24.0, false, tl!("Add a sticky note here")).clicked() {
- *action = Some(ImageAction::AddComment(page, hit));
- close(ui);
- }
- if raster && crate::icons::button(ui, "crop", 24.0, false, tl!("Crop")).clicked() {
- *action = Some(ImageAction::Crop);
- if let Some(s) = view.image_selection.as_mut() {
- let rect = img.visible_rect.unwrap_or(img.rect);
- s.crop = Some(CropMode::new(rect));
- s.crop_mode = true;
- s.crop_rect = None;
- }
- close(ui);
- }
- if crate::icons::button(ui, "rotate-ccw", 24.0, false, tl!("Rotate Counterclockwise")).clicked() {
- view.pending_edit = Some(Edit::EditPageImage { page, index: hit, change: E::Rotate(3) });
- close(ui);
- }
- if crate::icons::button(ui, "rotate-cw", 24.0, false, tl!("Rotate Clockwise")).clicked() {
- view.pending_edit = Some(Edit::EditPageImage { page, index: hit, change: E::Rotate(1) });
- close(ui);
- }
- });
-
- ui.separator();
-
- if ui.button(tl!("Cut Image")).clicked() {
- *action = Some(ImageAction::Cut(page, hit));
- close(ui);
- }
- if ui.button(tl!("Copy Image")).clicked() {
- *action = Some(ImageAction::Copy(page, hit));
- close(ui);
- }
- if ui.add_enabled(can_paste, egui::Button::new(tl!("Paste"))).clicked() {
- *action = Some(ImageAction::Paste(page, at));
- close(ui);
- }
-
- ui.separator();
-
- let is_cropped = img.visible_rect.is_some() && img.visible_rect != Some(img.rect);
- if raster && ui.add_enabled(is_cropped, egui::Button::new(tl!("Remove crop"))).clicked() {
- view.pending_edit = Some(Edit::EditPageImage { page, index: hit, change: E::RemoveCrop });
- close(ui);
- }
-
- if ui.button(tl!("Flip horizontal")).clicked() {
- view.pending_edit = Some(Edit::EditPageImage { page, index: hit, change: E::Flip { horizontal: true } });
- close(ui);
- }
- if ui.button(tl!("Flip vertical")).clicked() {
- view.pending_edit = Some(Edit::EditPageImage { page, index: hit, change: E::Flip { horizontal: false } });
- close(ui);
- }
-
- ui.menu_button(tl!("Arrange image"), |ui| {
- if ui.button(tl!("Bring to front")).clicked() {
- view.pending_edit = Some(Edit::EditPageImage { page, index: hit, change: E::Arrange(pdfcraft_engine::ArrangeOrder::BringToFront) });
- close(ui);
- }
- if ui.button(tl!("Send to back")).clicked() {
- view.pending_edit = Some(Edit::EditPageImage { page, index: hit, change: E::Arrange(pdfcraft_engine::ArrangeOrder::SendToBack) });
- close(ui);
- }
- if ui.button(tl!("Bring forward")).clicked() {
- view.pending_edit = Some(Edit::EditPageImage { page, index: hit, change: E::Arrange(pdfcraft_engine::ArrangeOrder::BringForward) });
- close(ui);
- }
- if ui.button(tl!("Send backward")).clicked() {
- view.pending_edit = Some(Edit::EditPageImage { page, index: hit, change: E::Arrange(pdfcraft_engine::ArrangeOrder::SendBackward) });
- close(ui);
- }
- });
-
- if ui.add_enabled(raster, egui::Button::new(tl!("Replace image"))).clicked() {
- *action = Some(ImageAction::Replace(page, hit));
- close(ui);
- }
- if ui.add_enabled(raster, egui::Button::new(tl!("Save Image As…"))).clicked() {
- *action = Some(ImageAction::Save(page, hit));
- close(ui);
- }
-
- ui.separator();
-
- if ui.button(tl!("Draw freehand")).clicked() {
- *action = Some(ImageAction::DrawFreehand);
- close(ui);
- }
- if ui.button(tl!("Redact Image")).clicked() {
- *action = Some(ImageAction::Redact(page, hit));
- close(ui);
- }
- if ui.add_enabled(raster, egui::Button::new("Export image")).clicked() {
- *action = Some(ImageAction::Save(page, hit));
- close(ui);
- }
-
- ui.separator();
-
- if ui.button(tl!("Create Link…")).clicked() {
- *action = Some(ImageAction::Link(page, hit));
- close(ui);
- }
-
- ui.menu_button("Edit image using", |ui| {
- ui.add_enabled(false, egui::Button::new("Default image editor"));
- });
-
- if ui.button(tl!("Recognize Text…")).clicked() {
- *action = Some(ImageAction::Recognize(page));
- close(ui);
- }
-
- ui.separator();
-
- if ui.button(tl!("Delete")).clicked() {
- view.image_selection = None;
- view.pending_edit = Some(Edit::EditPageImage { page, index: hit, change: E::Delete });
- close(ui);
- }
-}
+use super::*;
+use crate::canvas::{ImageObb, PainterExt};
+use crate::image_engine::{CROP_ACCENT, HandleId, apply_crop, apply_resize, apply_resize_proportional, draw_handle, draw_rule_of_thirds};
+
+/// The 8 resize handles on an image (4 corners + 4 edge centers).
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum ImageHandle {
+ TopLeft,
+ TopCenter,
+ TopRight,
+ RightCenter,
+ BottomRight,
+ BottomCenter,
+ BottomLeft,
+ LeftCenter,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum DragTarget {
+ Move,
+ Handle(ImageHandle),
+ CropHandle(ImageHandle),
+ Rotate,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct ImageDrag {
+ pub start: Pos2,
+ pub target: DragTarget,
+ pub initial_rect: Rect,
+ pub initial_matrix: [f64; 6],
+}
+
+/// A selected page image, and what the pointer is doing to it.
+#[derive(Clone, Debug, PartialEq)]
+pub struct ImageSelection {
+ pub page: usize,
+ pub index: usize,
+ /// Dragging in progress.
+ pub drag: Option<ImageDrag>,
+ /// Crop mode: the box kept so far.
+ pub crop: Option<CropMode>,
+ pub crop_mode: bool,
+ pub crop_rect: Option<Rect>,
+ /// The drag is turning the picture by its rotate handle (the `drag` start is then unused).
+ pub turning: bool,
+ /// A move or resize applied on release: the frame it had and the one it got, in the page's
+ /// 0..1 coordinates, while the page raster still has the picture where it was.
+ pub settled: Option<(Rect, Rect)>,
+}
+
+impl ImageSelection {
+ /// Cancel an in-progress text, rotation or crop drag and restore the crop it was previewing.
+ pub(crate) fn cancel_pointer_gesture(&mut self) {
+ self.drag = None;
+ self.turning = false;
+ if let Some(crop) = &mut self.crop
+ && let Some((_, _, before)) = crop.drag.take()
+ {
+ crop.keep = before;
+ }
+ }
+
+ pub(crate) fn dragging(&self) -> bool {
+ self.drag.is_some()
+ }
+}
+
+/// Cropping a page image: the handles trim instead of resizing, the part that will go is
+/// dimmed, Enter or Done applies and Esc or Cancel leaves it.
+#[derive(Clone, Debug, PartialEq)]
+pub struct CropMode {
+ /// The box to keep (user space or normalized UV).
+ pub keep: [f64; 4],
+ /// A drag in progress: the grip (0–7 handles, 8 inside), where it started and the box then.
+ pub(crate) drag: Option<(usize, Pos2, [f64; 4])>,
+}
+
+impl CropMode {
+ pub fn new(keep: [f64; 4]) -> Self {
+ Self { keep, drag: None }
+ }
+}
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub(crate) struct Matrix(pub(crate) [f64; 6]);
+
+impl Matrix {
+ pub(crate) fn apply(&self, x: f64, y: f64) -> (f64, f64) {
+ let [a, b, c, d, e, f] = self.0;
+ (a * x + c * y + e, b * x + d * y + f)
+ }
+
+ pub(crate) fn invert(&self) -> Option<Self> {
+ let [a, b, c, d, e, f] = self.0;
+ let det = a * d - b * c;
+ if det.abs() < 1e-12 || !det.is_finite() {
+ return None;
+ }
+ let (ia, ib, ic, id) = (d / det, -b / det, -c / det, a / det);
+ Some(Matrix([ia, ib, ic, id, -(e * ia + f * ic), -(e * ib + f * id)]))
+ }
+
+ pub(crate) fn then(&self, then: &Matrix) -> Matrix {
+ let [a, b, c, d, e, f] = self.0;
+ let [a2, b2, c2, d2, e2, f2] = then.0;
+ Matrix([a * a2 + b * c2, a * b2 + b * d2, c * a2 + d * c2, c * b2 + d * d2, e * a2 + f * c2 + e2, e * b2 + f * d2 + f2])
+ }
+}
+
+pub(crate) fn user_to_screen(xf: &PageXform, info: &DocInfo, page: usize, x: f64, y: f64) -> Pos2 {
+ let Some(p) = info.pages.get(page) else { return Pos2::ZERO };
+ let v = p.user_to_view(x as f32, y as f32);
+ xf.norm_to_screen(v[0] / xf.pw, v[1] / xf.ph)
+}
+
+fn screen_to_user(xf: &PageXform, info: &DocInfo, page: usize, pt: Pos2) -> (f64, f64) {
+ let (vx, vy) = xf.screen_to_view(pt);
+ let Some(p) = info.pages.get(page) else { return (0.0, 0.0) };
+ let u = p.view_to_user(vx, vy);
+ (f64::from(u[0]), f64::from(u[1]))
+}
+
+pub(crate) fn quad_contains(quad: [Pos2; 4], p: Pos2) -> bool {
+ if !p.x.is_finite() || !p.y.is_finite() || quad.iter().any(|pt| !pt.x.is_finite() || !pt.y.is_finite()) {
+ return false;
+ }
+ let mut sign = 0;
+ for i in 0..4 {
+ let p1 = quad[i];
+ let p2 = quad[(i + 1) % 4];
+ let cross = (p2.x - p1.x) * (p.y - p1.y) - (p2.y - p1.y) * (p.x - p1.x);
+ if cross.abs() > 1e-4 {
+ let s = if cross > 0.0 { 1 } else { -1 };
+ if sign == 0 {
+ sign = s;
+ } else if sign != s {
+ return false;
+ }
+ }
+ }
+ sign != 0
+}
+
+/// The screen positions of the crop's eight handles: corners, then the top, right, bottom and left edge midpoints.
+fn crop_handles(k: Rect) -> [Pos2; 8] {
+ [k.left_top(), k.right_top(), k.left_bottom(), k.right_bottom(), k.center_top(), k.right_center(), k.center_bottom(), k.left_center()]
+}
+
+/// Crop mode for the selected image `i` whose visible frame is `b` (screen). Returns `true`
+/// (the pointer and keys are the crop's while it lasts).
+#[allow(clippy::too_many_arguments)]
+fn crop_input(
+ ui: &egui::Ui,
+ resp: &egui::Response,
+ xf: &PageXform,
+ ptr: &PagePointer,
+ page: usize,
+ info: &DocInfo,
+ view: &mut DocView,
+ i: usize,
+ image: &pdfcraft_engine::PageImage,
+ allow_interaction: bool,
+) -> bool {
+ let painter = ui.painter();
+ let Some(sel) = view.image_selection.as_mut() else { return false };
+ if let Some(rect) = sel.crop_rect
+ && let Some(mode) = sel.crop.as_mut()
+ {
+ mode.keep = user_box(xf, info, page, rect);
+ sel.crop_rect = None;
+ }
+ let Some(mode) = sel.crop.as_mut() else { return false };
+ let hover_pos = ptr.pos;
+ let full_b = xf.user_rect(info, page, image.rect.map(|v| v as f32));
+ let b = if full_b.is_positive() { full_b } else { xf.user_rect(info, page, image.visible_rect.unwrap_or(image.rect).map(|v| v as f32)) };
+ let keep_screen = |keep: [f64; 4]| xf.user_rect(info, page, keep.map(|v| v as f32)).intersect(b);
+ let k = keep_screen(mode.keep);
+
+ if allow_interaction
+ && resp.drag_started()
+ && let Some(o) = ptr.origin
+ {
+ let grip = crop_handles(k).iter().position(|h| h.distance(o) < 10.0).or_else(|| k.contains(o).then_some(8));
+ if let Some(g) = grip {
+ mode.drag = Some((g, o, mode.keep));
+ }
+ }
+
+ if let Some((grip, start, at_start)) = mode.drag
+ && let Some(p) = hover_pos
+ {
+ let d = p - start;
+ let k0 = keep_screen(at_start);
+ if grip < 8 {
+ let handle_id = match grip {
+ 0 => HandleId::TopLeft,
+ 1 => HandleId::TopRight,
+ 2 => HandleId::BottomLeft,
+ 3 => HandleId::BottomRight,
+ 4 => HandleId::TopMid,
+ 5 => HandleId::RightMid,
+ 6 => HandleId::BottomMid,
+ _ => HandleId::LeftMid,
+ };
+ let uv0 = if b.width() > 0.0 && b.height() > 0.0 {
+ Rect::from_min_max(
+ pos2(((k0.min.x - b.min.x) / b.width()).clamp(0.0, 1.0), ((k0.min.y - b.min.y) / b.height()).clamp(0.0, 1.0)),
+ pos2(((k0.max.x - b.min.x) / b.width()).clamp(0.0, 1.0), ((k0.max.y - b.min.y) / b.height()).clamp(0.0, 1.0)),
+ )
+ } else {
+ Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0))
+ };
+ let (new_screen, _) = apply_crop(k0, uv0, handle_id, d);
+ let (min_w, min_h) = (6.0_f32.min(b.width()), 6.0_f32.min(b.height()));
+ let clamped = Rect::from_min_max(
+ pos2(new_screen.min.x.clamp(b.min.x, b.max.x - min_w), new_screen.min.y.clamp(b.min.y, b.max.y - min_h)),
+ pos2(new_screen.max.x.clamp(b.min.x + min_w, b.max.x), new_screen.max.y.clamp(b.min.y + min_h, b.max.y)),
+ );
+ mode.keep = user_box(xf, info, page, clamped);
+ } else {
+ let shift = egui::vec2(d.x.clamp(b.min.x - k0.min.x, b.max.x - k0.max.x), d.y.clamp(b.min.y - k0.min.y, b.max.y - k0.max.y));
+ mode.keep = user_box(xf, info, page, Rect::from_min_max(k0.min + shift, k0.max + shift));
+ }
+ if resp.drag_stopped() || !ptr.primary_down {
+ mode.drag = None;
+ }
+ }
+
+ // Faint ghost outline of the full uncropped image underneath
+ painter.rect_stroke(b, CornerRadius::ZERO, Stroke::new(1.0, Color32::from_rgba_unmultiplied(200, 200, 200, 80)), egui::StrokeKind::Outside);
+
+ // Dim outer excluded bands
+ let dim = Color32::from_black_alpha(96);
+ if k.min.y > b.min.y {
+ painter.rect_filled(Rect::from_min_max(b.min, Pos2::new(b.max.x, k.min.y)), CornerRadius::ZERO, dim);
+ }
+ if k.max.y < b.max.y {
+ painter.rect_filled(Rect::from_min_max(Pos2::new(b.min.x, k.max.y), b.max), CornerRadius::ZERO, dim);
+ }
+ if k.min.x > b.min.x {
+ painter.rect_filled(Rect::from_min_max(Pos2::new(b.min.x, k.min.y), Pos2::new(k.min.x, k.max.y)), CornerRadius::ZERO, dim);
+ }
+ if k.max.x < b.max.x {
+ painter.rect_filled(Rect::from_min_max(Pos2::new(k.max.x, k.min.y), Pos2::new(b.max.x, k.max.y)), CornerRadius::ZERO, dim);
+ }
+
+ // Rule-of-Thirds Grid inside crop area
+ draw_rule_of_thirds(painter, k, Stroke::new(1.0, CROP_ACCENT.gamma_multiply(0.45)));
+
+ // Crop border stroke
+ painter.rect_stroke(k, CornerRadius::ZERO, Stroke::new(1.5, CROP_ACCENT), egui::StrokeKind::Outside);
+
+ // Crop handles
+ for (idx, h) in crop_handles(k).iter().enumerate() {
+ let is_active = mode.drag.as_ref().is_some_and(|d| d.0 == idx);
+ let is_hovered = hover_pos.is_some_and(|p| p.distance(*h) < 10.0);
+ draw_handle(painter, *h, is_active, is_hovered, true, CROP_ACCENT);
+ }
+
+ // Action pills
+ let font = egui::FontId::proportional(12.5);
+ let done_w = painter.layout_no_wrap(tl!("Done").to_string(), font.clone(), Color32::WHITE).size().x + 22.0;
+ let cancel_w = painter.layout_no_wrap(tl!("Cancel").to_string(), font.clone(), Color32::WHITE).size().x + 22.0;
+ let is_full_rect = (mode.keep[0] - image.rect[0]).abs() < 1e-3
+ && (mode.keep[1] - image.rect[1]).abs() < 1e-3
+ && (mode.keep[2] - image.rect[2]).abs() < 1e-3
+ && (mode.keep[3] - image.rect[3]).abs() < 1e-3;
+ let has_crop = !is_full_rect || image.visible_rect.is_some_and(|v| v != image.rect);
+ let reset_w =
+ if has_crop { Some(painter.layout_no_wrap(tl!("Remove Crop").to_string(), font.clone(), Color32::WHITE).size().x + 22.0) } else { None };
+ let spacing = 6.0;
+ let total_w = done_w + spacing + cancel_w + reset_w.map_or(0.0, |w| w + spacing);
+
+ // Position pills below crop box if there's room, otherwise above
+ let y = if k.max.y + 32.0 < xf.rect.max.y {
+ k.max.y + 6.0
+ } else if k.min.y - 28.0 > xf.rect.min.y {
+ k.min.y - 28.0
+ } else {
+ k.max.y + 6.0
+ };
+
+ // Right-align pills with k.max.x, clamped inside the page bounds
+ let mut right = k.max.x.min(xf.rect.max.x - 8.0);
+ if right - total_w < xf.rect.min.x + 8.0 {
+ right = (xf.rect.min.x + 8.0 + total_w).min(xf.rect.max.x - 8.0);
+ }
+
+ let done = Rect::from_min_size(Pos2::new(right - done_w, y), egui::vec2(done_w, 22.0));
+ let cancel = Rect::from_min_size(Pos2::new(done.min.x - spacing - cancel_w, y), egui::vec2(cancel_w, 22.0));
+ let reset = reset_w.map(|w| Rect::from_min_size(Pos2::new(cancel.min.x - spacing - w, y), egui::vec2(w, 22.0)));
+
+ let done_id = ui.scope_id().with("crop_pill_done").with(page).with(i);
+ let cancel_id = ui.scope_id().with("crop_pill_cancel").with(page).with(i);
+ let reset_id = ui.scope_id().with("crop_pill_reset").with(page).with(i);
+
+ let done_resp = ui.interact(done, done_id, egui::Sense::click());
+ let cancel_resp = ui.interact(cancel, cancel_id, egui::Sense::click());
+ let reset_resp = reset.map(|r| ui.interact(r, reset_id, egui::Sense::click()));
+
+ let t = crate::theme::Tokens::get(ui.ctx());
+
+ // Done button (accent colored)
+ let done_bg = if done_resp.is_pointer_button_down_on() {
+ ACCENT.gamma_multiply(0.8)
+ } else if done_resp.hovered() {
+ Color32::from_rgb(40, 145, 255)
+ } else {
+ ACCENT
+ };
+ painter.rect_filled(done, CornerRadius::same(11), done_bg);
+ painter.text(done.center(), egui::Align2::CENTER_CENTER, tl!("Done"), font.clone(), Color32::WHITE);
+
+ // Cancel button (panel style with border)
+ let cancel_bg = if cancel_resp.is_pointer_button_down_on() {
+ t.pressed
+ } else if cancel_resp.hovered() {
+ t.hover
+ } else {
+ t.card
+ };
+ let cancel_stroke = Stroke::new(1.0, if cancel_resp.hovered() { ACCENT } else { t.border });
+ let cancel_text = if cancel_resp.hovered() { ACCENT } else { t.text };
+ painter.rect(cancel, CornerRadius::same(11), cancel_bg, cancel_stroke, egui::StrokeKind::Inside);
+ painter.text(cancel.center(), egui::Align2::CENTER_CENTER, tl!("Cancel"), font.clone(), cancel_text);
+
+ // Reset button (panel style with border)
+ if let (Some(r), Some(r_resp)) = (reset, reset_resp.as_ref()) {
+ let reset_bg = if r_resp.is_pointer_button_down_on() {
+ t.pressed
+ } else if r_resp.hovered() {
+ t.hover
+ } else {
+ t.card
+ };
+ let reset_stroke = Stroke::new(1.0, if r_resp.hovered() { ACCENT } else { t.border });
+ let reset_text = if r_resp.hovered() { ACCENT } else { t.text };
+ painter.rect(r, CornerRadius::same(11), reset_bg, reset_stroke, egui::StrokeKind::Inside);
+ painter.text(r.center(), egui::Align2::CENTER_CENTER, tl!("Remove Crop"), font.clone(), reset_text);
+ }
+
+ if let Some(p) = hover_pos {
+ let icon = if done_resp.hovered()
+ || cancel_resp.hovered()
+ || reset_resp.as_ref().is_some_and(|r| r.hovered())
+ || done.contains(p)
+ || cancel.contains(p)
+ || reset.is_some_and(|r| r.contains(p))
+ {
+ egui::CursorIcon::PointingHand
+ } else if let Some(g) = crop_handles(k).iter().position(|h| h.distance(p) < 8.0) {
+ match g {
+ 0 => HandleId::TopLeft.cursor_icon(),
+ 1 => HandleId::TopRight.cursor_icon(),
+ 2 => HandleId::BottomLeft.cursor_icon(),
+ 3 => HandleId::BottomRight.cursor_icon(),
+ 4 => HandleId::TopMid.cursor_icon(),
+ 5 => HandleId::RightMid.cursor_icon(),
+ 6 => HandleId::BottomMid.cursor_icon(),
+ _ => HandleId::LeftMid.cursor_icon(),
+ }
+ } else if k.contains(p) {
+ if mode.drag.is_some() { egui::CursorIcon::Grabbing } else { egui::CursorIcon::Grab }
+ } else {
+ egui::CursorIcon::Default
+ };
+ ui.ctx().set_cursor_icon(icon);
+ }
+
+ let keys = |key: egui::Key| allow_interaction && ui.input(|inp| inp.key_pressed(key)) && !ui.ctx().egui_wants_keyboard_input();
+ let done_clicked = allow_interaction && (done_resp.clicked() || (resp.clicked() && hover_pos.is_some_and(|p| done.contains(p))));
+ let cancel_clicked = allow_interaction && (cancel_resp.clicked() || (resp.clicked() && hover_pos.is_some_and(|p| cancel.contains(p))));
+ let reset_clicked = allow_interaction
+ && reset
+ .is_some_and(|r| reset_resp.as_ref().is_some_and(|res| res.clicked()) || (resp.clicked() && hover_pos.is_some_and(|p| r.contains(p))));
+
+ if reset_clicked {
+ mode.keep = image.rect;
+ mode.drag = None;
+ if let Some(s) = view.image_selection.as_mut() {
+ s.crop_rect = None;
+ }
+ } else if done_clicked || keys(egui::Key::Enter) {
+ let keep = mode.keep;
+ if let Some(s) = view.image_selection.as_mut() {
+ s.crop = None;
+ s.crop_mode = false;
+ s.crop_rect = None;
+ }
+ let is_full = (keep[0] - image.rect[0]).abs() < 1e-3
+ && (keep[1] - image.rect[1]).abs() < 1e-3
+ && (keep[2] - image.rect[2]).abs() < 1e-3
+ && (keep[3] - image.rect[3]).abs() < 1e-3;
+ if is_full {
+ if image.visible_rect.is_some_and(|v| v != image.rect) {
+ view.pending_edit = Some(Edit::EditPageImage { page, index: i, change: pdfcraft_engine::ImageEdit::RemoveCrop });
+ }
+ } else if image.visible_rect != Some(keep) {
+ view.pending_edit = Some(Edit::EditPageImage { page, index: i, change: pdfcraft_engine::ImageEdit::Crop(keep) });
+ }
+ } else if (cancel_clicked || keys(egui::Key::Escape))
+ && let Some(s) = view.image_selection.as_mut()
+ {
+ s.crop = None;
+ s.crop_mode = false;
+ s.crop_rect = None;
+ }
+ true
+}
+
+/// The page raster's picture of the box `from`, stretched into `to`, over blanks at `blank` (where
+/// the screen may still show the picture).
+fn stretched_picture(painter: &egui::Painter, xf: &PageXform, tex: egui::TextureId, blank: &[Rect], from: Rect, to: Rect) {
+ let clipped = painter.with_clip_rect(painter.clip_rect().intersect(xf.rect));
+ for r in blank {
+ clipped.rect_filled(*r, CornerRadius::ZERO, Color32::WHITE);
+ }
+ let mut mesh = egui::Mesh::with_texture(tex);
+ for (a, b) in [
+ (from.left_top(), to.left_top()),
+ (from.right_top(), to.right_top()),
+ (from.right_bottom(), to.right_bottom()),
+ (from.left_bottom(), to.left_bottom()),
+ ] {
+ let (u, v) = xf.screen_to_norm(a);
+ mesh.vertices.push(egui::epaint::Vertex { pos: b, uv: Pos2::new(u, v), color: Color32::WHITE });
+ }
+ mesh.add_triangle(0, 1, 2);
+ mesh.add_triangle(0, 2, 3);
+ clipped.add(egui::Shape::mesh(mesh));
+}
+
+/// Once a selected corner or the rotate knob is grabbed, text under it cannot take over the gesture. The same
+/// applies after the pointer leaves the image/page while dragging.
+pub(crate) fn image_owns_pointer(_ui: &egui::Ui, xf: &PageXform, ptr: &PagePointer, page: usize, info: &DocInfo, view: &DocView) -> bool {
+ let Some(selection) = view.image_selection.as_ref().filter(|s| s.page == page) else { return false };
+ if selection.drag.is_some() || selection.crop.is_some() || selection.crop_mode {
+ return true;
+ }
+ let Some(image) = view.edit_images.get(&page).and_then(|(_, images)| images.get(selection.index)) else { return false };
+ let obb = ImageObb::from_image(image, xf, info, page);
+ let p = if ptr.primary_down { ptr.origin.or(ptr.pos) } else { ptr.pos };
+ let Some(p) = p else { return false };
+
+ obb.handles().iter().any(|(_, h)| h.distance(p) < 8.0) || obb.s_rot.distance(p) < 8.0
+}
+
+/// What a right-click on a selected image asks for.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub enum ImageAction {
+ Replace(usize, usize),
+ Save(usize, usize),
+ Copy(usize, usize),
+ CopyFile(usize, usize),
+ /// Copy the picture, then remove it from the page.
+ Cut(usize, usize),
+ /// Mark the picture for redaction (applied later from Redact a PDF).
+ Redact(usize, usize),
+ /// Create a link over the picture.
+ Link(usize, usize),
+ /// Open Recognize Text for the picture's page.
+ Recognize(usize),
+ Paste(usize, Option<[f64; 2]>),
+ DrawFreehand,
+ AddComment(usize, usize),
+ Crop,
+}
+
+/// Where the rotate knob sits, and the edge point its stem starts from: above the middle of the
+/// top edge, or below the bottom edge when the area on screen (`view`) has no room above.
+pub(super) fn rotate_knob(b: Rect, view: Rect) -> (Pos2, Pos2) {
+ let above = b.center_top() - egui::vec2(0.0, 22.0);
+ if above.y - 6.0 >= view.top() { (above, b.center_top()) } else { (b.center_bottom() + egui::vec2(0.0, 22.0), b.center_bottom()) }
+}
+
+/// Degrees clockwise (-180..=180) that turn "straight up" from `centre` onto the pointer; `snap`
+/// rounds to steps of 15 degrees (Shift). A pointer on the centre turns nothing.
+pub(super) fn turn_degrees(centre: Pos2, pointer: Pos2, snap: bool) -> f32 {
+ let v = pointer - centre;
+ if !(v.x.is_finite() && v.y.is_finite()) || v.length() < 4.0 {
+ return 0.0;
+ }
+ // Screen y points down: up is (0, -1); clockwise is atan2(x, -y).
+ let d = v.x.atan2(-v.y).to_degrees();
+ if snap { (d / 15.0).round() * 15.0 } else { d }
+}
+
+#[doc(hidden)]
+pub fn image_menu_id() -> egui::Id {
+ egui::Id::unique("image-menu")
+}
+
+/// Images on a page: select, move, resize, right-click. Returns `true` when the pointer was used.
+#[allow(clippy::too_many_arguments)]
+pub(crate) fn image_input(
+ ui: &egui::Ui,
+ resp: &egui::Response,
+ xf: &PageXform,
+ ptr: &PagePointer,
+ page: usize,
+ info: &DocInfo,
+ images: &[pdfcraft_engine::PageImage],
+ view: &mut DocView,
+ action: &mut Option<ImageAction>,
+ allow_interaction: bool,
+) -> bool {
+ let _ = &action;
+ let boxes: Vec<Rect> = images.iter().map(|im| crate::canvas::image_screen_rect(im, xf, info, page)).collect();
+ let painter = ui.painter();
+ let hover_pos = ptr.pos;
+ let image_contains = |index: usize, point: Pos2| {
+ let (x, y) = xf.screen_to_view(point);
+ let Some(p) = info.pages.get(page) else { return false };
+ let user = p.view_to_user(x, y);
+ images.get(index).is_some_and(|im| im.contains(user.map(f64::from)))
+ };
+ let selected = view.image_selection.as_ref().filter(|s| s.page == page).map(|s| s.index).filter(|i| *i < boxes.len());
+ let dragging = view.image_selection.as_ref().is_some_and(|s| s.drag.is_some());
+ let faint_all = boxes.len() <= MAX_OUTLINES;
+ let moving = selected.filter(|_| dragging);
+ if faint_all {
+ for (idx, im) in images.iter().enumerate() {
+ if moving == Some(idx) {
+ continue;
+ }
+ if let Some(b) = boxes.get(idx).filter(|b| b.is_positive()) {
+ let obb = ImageObb::from_image(im, xf, info, page);
+ if obb.is_rotated {
+ let pts = obb.corners();
+ for k in 0..4 {
+ painter.line_segment([pts[k], pts[(k + 1) % 4]], Stroke::new(0.75, ACCENT.gamma_multiply(0.35)));
+ }
+ } else {
+ painter.rect_stroke(*b, CornerRadius::ZERO, Stroke::new(0.75, ACCENT.gamma_multiply(0.35)), egui::StrokeKind::Outside);
+ }
+ }
+ }
+ }
+ let hovered_box = hover_pos.and_then(|p| {
+ boxes.iter().enumerate().rposition(|(i, b)| {
+ b.is_positive()
+ && images.get(i).is_some_and(|img| b.contains(p) || quad_contains(ImageObb::from_image(img, xf, info, page).corners(), p))
+ && image_contains(i, p)
+ })
+ });
+ if !faint_all {
+ for i in selected.filter(|_| moving.is_none()).into_iter().chain(hovered_box.filter(|h| Some(*h) != selected)) {
+ if let (Some(b), Some(img)) = (boxes.get(i).filter(|b| b.is_positive()), images.get(i)) {
+ let obb = ImageObb::from_image(img, xf, info, page);
+ if obb.is_rotated {
+ let pts = obb.corners();
+ for k in 0..4 {
+ painter.line_segment([pts[k], pts[(k + 1) % 4]], Stroke::new(0.75, ACCENT.gamma_multiply(0.35)));
+ }
+ } else {
+ painter.rect_stroke(*b, CornerRadius::ZERO, Stroke::new(0.75, ACCENT.gamma_multiply(0.35)), egui::StrokeKind::Outside);
+ }
+ }
+ }
+ }
+ for i in selected.into_iter().chain(hovered_box).collect::<Vec<_>>() {
+ let (Some(b), Some(img)) = (boxes.get(i).copied().filter(|b| b.is_positive()), images.get(i)) else { continue };
+ let obb = ImageObb::from_image(img, xf, info, page);
+ if selected == Some(i) {
+ if !dragging {
+ if obb.is_rotated {
+ painter.polygon(obb.corners().to_vec(), ACCENT.gamma_multiply(0.04), Stroke::NONE);
+ } else {
+ painter.rect_filled(b, CornerRadius::ZERO, ACCENT.gamma_multiply(0.04));
+ }
+ }
+ } else if obb.is_rotated {
+ painter.polygon(obb.corners().to_vec(), Color32::TRANSPARENT, Stroke::new(1.5, ACCENT.gamma_multiply(0.7)));
+ } else {
+ painter.rect_stroke(b, CornerRadius::ZERO, Stroke::new(1.5, ACCENT.gamma_multiply(0.7)), egui::StrokeKind::Outside);
+ }
+ }
+ // The selected image: frame, corner handles, dragging.
+ if let Some(i) = selected.filter(|i| boxes.get(*i).is_some_and(|b| b.is_positive())) {
+ let Some(b) = boxes.get(i).copied() else { return false };
+ let Some(image) = images.get(i) else { return false };
+ let obb = ImageObb::from_image(image, xf, info, page);
+ let (out_of_date, raster_old, raster) = (view.page_out_of_date(page), view.page_raster_out_of_date(page), view.page_raster(page));
+ let screen = |r: Rect| Rect::from_two_pos(xf.norm_to_screen(r.min.x, r.min.y), xf.norm_to_screen(r.max.x, r.max.y));
+ let left_at = view.image_selection.as_ref().and_then(|s| s.settled).filter(|_| out_of_date).map(|(from, _)| from);
+ if let Some(s) = view.image_selection.as_mut().filter(|s| s.drag.is_none()) {
+ match (s.settled, raster) {
+ (Some((from, to)), Some(tex)) if out_of_date => {
+ let source = if raster_old { from } else { to };
+ stretched_picture(painter, xf, tex, &[screen(from)], screen(source), screen(to));
+ }
+ _ if !out_of_date => s.settled = None,
+ _ => {}
+ }
+ }
+
+ if view.image_selection.as_ref().is_some_and(|s| s.crop.is_some() || s.crop_mode) {
+ if let Some(s) = view.image_selection.as_mut()
+ && s.crop.is_none()
+ {
+ let rect = images.get(i).and_then(|im| im.visible_rect).unwrap_or(images.get(i).map_or([0.0; 4], |im| im.rect));
+ s.crop = Some(CropMode::new(rect));
+ }
+ return crop_input(ui, resp, xf, ptr, page, info, view, i, image, allow_interaction);
+ }
+ let (knob, stem) = rotate_knob(b, ui.clip_rect());
+ if view.image_selection.as_ref().is_some_and(|s| s.drag.is_none()) {
+ if obb.is_rotated {
+ painter.polygon(obb.corners().to_vec(), Color32::TRANSPARENT, Stroke::new(1.5, ACCENT));
+ painter.line_segment([obb.s_tc, obb.s_rot], Stroke::new(1.2, ACCENT));
+ painter.circle(obb.s_rot, 4.5, Color32::WHITE, Stroke::new(1.0, ACCENT));
+ } else {
+ painter.rect_stroke(b, CornerRadius::ZERO, Stroke::new(1.5, ACCENT), egui::StrokeKind::Outside);
+ painter.line_segment([stem, knob], Stroke::new(1.0, ACCENT));
+ painter.circle(knob, 5.0, Color32::WHITE, Stroke::new(1.0, ACCENT));
+ }
+ for (_, h) in obb.handles() {
+ let is_hovered = hover_pos.is_some_and(|p| p.distance(h) < 10.0);
+ draw_handle(painter, h, false, is_hovered, false, ACCENT);
+ }
+ }
+
+ let mut handle_drag = None;
+ for (h, h_pos, handle_id) in obb.handles_with_ids(ui.scope_id().with("img_handle")) {
+ let handle_rect = Rect::from_center_size(h_pos, egui::vec2(18.0, 18.0));
+ let handle_resp = ui.interact(handle_rect, handle_id, egui::Sense::drag());
+ if allow_interaction && handle_resp.drag_started() {
+ handle_drag = Some(h);
+ }
+ }
+ let rot_id = ui.scope_id().with("img_handle").with(8);
+ let rot_rect = Rect::from_center_size(if obb.is_rotated { obb.s_rot } else { knob }, egui::vec2(12.0, 12.0));
+ let rot_resp = ui.interact(rot_rect, rot_id, egui::Sense::drag());
+ let rot_drag = allow_interaction && rot_resp.drag_started();
+
+ if allow_interaction && let Some(p) = hover_pos {
+ if obb.s_rot.distance(p) < 8.0 || knob.distance(p) < 8.0 {
+ ui.ctx().set_cursor_icon(egui::CursorIcon::Grab);
+ } else if let Some((h, _)) = obb.handles().iter().find(|(_, pos)| pos.distance(p) < 8.0) {
+ let icon = match h {
+ ImageHandle::TopLeft | ImageHandle::BottomRight => {
+ if obb.is_rotated {
+ let v = obb.handle_pos(*h) - obb.screen_center;
+ if v.x * v.y > 0.0 { egui::CursorIcon::ResizeNwSe } else { egui::CursorIcon::ResizeNeSw }
+ } else {
+ egui::CursorIcon::ResizeNwSe
+ }
+ }
+ ImageHandle::TopRight | ImageHandle::BottomLeft => {
+ if obb.is_rotated {
+ let v = obb.handle_pos(*h) - obb.screen_center;
+ if v.x * v.y > 0.0 { egui::CursorIcon::ResizeNwSe } else { egui::CursorIcon::ResizeNeSw }
+ } else {
+ egui::CursorIcon::ResizeNeSw
+ }
+ }
+ ImageHandle::TopCenter | ImageHandle::BottomCenter => {
+ if obb.is_rotated && (obb.v_axis.0.abs() > obb.v_axis.1.abs()) {
+ egui::CursorIcon::ResizeHorizontal
+ } else {
+ egui::CursorIcon::ResizeVertical
+ }
+ }
+ ImageHandle::RightCenter | ImageHandle::LeftCenter => {
+ if obb.is_rotated && (obb.u_axis.1.abs() > obb.u_axis.0.abs()) {
+ egui::CursorIcon::ResizeVertical
+ } else {
+ egui::CursorIcon::ResizeHorizontal
+ }
+ }
+ };
+ ui.ctx().set_cursor_icon(icon);
+ }
+ }
+
+ let origin = ptr.origin;
+ if allow_interaction {
+ if let Some(h) = handle_drag {
+ if let Some(s) = view.image_selection.as_mut() {
+ let o = origin.unwrap_or_else(|| obb.handle_pos(h));
+ s.drag = Some(ImageDrag { start: o, target: DragTarget::Handle(h), initial_rect: b, initial_matrix: image.matrix });
+ }
+ } else if rot_drag {
+ if let Some(s) = view.image_selection.as_mut() {
+ let o = origin.unwrap_or(if obb.is_rotated { obb.s_rot } else { knob });
+ s.drag = Some(ImageDrag { start: o, target: DragTarget::Rotate, initial_rect: b, initial_matrix: image.matrix });
+ s.turning = true;
+ }
+ } else if resp.drag_started()
+ && let Some(o) = origin
+ {
+ if obb.s_rot.distance(o) < 8.0 || knob.distance(o) < 8.0 {
+ if let Some(s) = view.image_selection.as_mut() {
+ s.drag = Some(ImageDrag { start: o, target: DragTarget::Rotate, initial_rect: b, initial_matrix: image.matrix });
+ s.turning = true;
+ }
+ } else if let Some((h, _)) = obb.handles().iter().find(|(_, pos)| pos.distance(o) < 8.0) {
+ if let Some(s) = view.image_selection.as_mut() {
+ s.drag = Some(ImageDrag { start: o, target: DragTarget::Handle(*h), initial_rect: b, initial_matrix: image.matrix });
+ }
+ } else if (image_contains(i, o) || quad_contains(obb.corners(), o))
+ && let Some(s) = view.image_selection.as_mut()
+ {
+ s.drag = Some(ImageDrag { start: o, target: DragTarget::Move, initial_rect: b, initial_matrix: image.matrix });
+ }
+ }
+ }
+
+ if view.image_selection.as_ref().is_some_and(|s| s.turning) {
+ let shift = ui.input(|i| i.modifiers.shift);
+ let degrees = hover_pos.map_or(0.0, |p| turn_degrees(b.center(), p, shift));
+ let centre = b.center();
+ let (sin, cos) = degrees.to_radians().sin_cos();
+ let turn = |c: Pos2| {
+ let v = c - centre;
+ centre + egui::vec2(v.x * cos - v.y * sin, v.x * sin + v.y * cos)
+ };
+ let outline = [b.left_top(), b.right_top(), b.right_bottom(), b.left_bottom()].map(turn).to_vec();
+ painter.add(egui::Shape::closed_line(outline, Stroke::new(1.5, ACCENT)));
+ let galley = painter.layout_no_wrap(format!("{degrees:.0}\u{b0}"), egui::FontId::proportional(12.0), ACCENT);
+ let label = Rect::from_center_size(turn(knob) - egui::vec2(0.0, 14.0), galley.size() + egui::vec2(8.0, 4.0));
+ painter.rect(label, CornerRadius::same(3), Color32::WHITE, Stroke::new(1.0, ACCENT), egui::StrokeKind::Middle);
+ painter.galley(label.center() - galley.size() / 2.0, galley, ACCENT);
+ ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing);
+ if resp.drag_stopped() || !ptr.primary_down {
+ if let Some(s) = view.image_selection.as_mut() {
+ s.drag = None;
+ s.turning = false;
+ }
+ if degrees.abs() >= 0.05 {
+ view.pending_edit =
+ Some(Edit::EditPageImage { page, index: i, change: pdfcraft_engine::ImageEdit::RotateBy(f64::from(degrees)) });
+ }
+ }
+ return true;
+ }
+
+ if let Some(drag) = view.image_selection.as_ref().and_then(|s| s.drag)
+ && let Some(p) = hover_pos
+ {
+ if !obb.is_rotated && !matches!(drag.target, DragTarget::Rotate) {
+ let preview = match drag.target {
+ DragTarget::Handle(handle) => {
+ let handle_id = HandleId::from(handle);
+ let delta = p - drag.start;
+ let is_corner = matches!(handle_id, HandleId::TopLeft | HandleId::TopRight | HandleId::BottomLeft | HandleId::BottomRight);
+ let shift = ui.input(|inp| inp.modifiers.shift);
+ if is_corner && !shift {
+ apply_resize_proportional(drag.initial_rect, handle_id, delta)
+ } else {
+ apply_resize(drag.initial_rect, handle_id, delta)
+ }
+ }
+ DragTarget::Move => drag.initial_rect.translate(p - drag.start),
+ _ => drag.initial_rect,
+ };
+
+ let raw = images.get(i).map_or(b, |im| xf.user_rect(info, page, im.rect.map(|v| v as f32)));
+ let ratio = |new: f32, old: f32| if old.abs() > 1e-3 && (new / old).is_finite() { new / old } else { 1.0 };
+ let factor = egui::vec2(ratio(preview.width(), b.width()), ratio(preview.height(), b.height()));
+ let f_min = egui::vec2((raw.min.x - b.min.x) * factor.x, (raw.min.y - b.min.y) * factor.y);
+ let f_max = egui::vec2((raw.max.x - b.min.x) * factor.x, (raw.max.y - b.min.y) * factor.y);
+ let target = Rect::from_min_max(preview.min + f_min, preview.min + f_max);
+ let visible = preview.intersect(xf.rect);
+
+ if visible.is_positive() {
+ if preview != b
+ && let Some(tex) = raster
+ {
+ let source = left_at.filter(|_| raster_old).map_or(b, screen);
+ let blank: Vec<Rect> = left_at.map(screen).into_iter().chain(std::iter::once(b)).collect();
+ stretched_picture(painter, xf, tex, &blank, source, preview);
+ }
+ painter.rect_filled(visible, CornerRadius::ZERO, ACCENT.gamma_multiply(0.04));
+ painter.rect_stroke(visible, CornerRadius::ZERO, Stroke::new(1.5, ACCENT), egui::StrokeKind::Outside);
+ for h in [
+ preview.left_top(),
+ preview.right_top(),
+ preview.left_bottom(),
+ preview.right_bottom(),
+ preview.center_top(),
+ preview.right_center(),
+ preview.center_bottom(),
+ preview.left_center(),
+ ] {
+ draw_handle(painter, h, false, false, false, ACCENT);
+ }
+ }
+
+ if resp.drag_stopped() || !ptr.primary_down {
+ if let Some(s) = view.image_selection.as_mut() {
+ s.drag = None;
+ let norm = |r: Rect| {
+ let ((u0, v0), (u1, v1)) = (xf.screen_to_norm(r.min), xf.screen_to_norm(r.max));
+ Rect::from_two_pos(Pos2::new(u0, v0), Pos2::new(u1, v1))
+ };
+ s.settled = (preview != b).then(|| (left_at.unwrap_or_else(|| norm(b)), norm(preview)));
+ }
+ if preview != b {
+ view.pending_edit =
+ Some(Edit::EditPageImage { page, index: i, change: pdfcraft_engine::ImageEdit::Move(user_box(xf, info, page, target)) });
+ }
+ }
+
+ let icon = match drag.target {
+ DragTarget::Handle(handle) => HandleId::from(handle).cursor_icon(),
+ DragTarget::Move => egui::CursorIcon::Grabbing,
+ _ => egui::CursorIcon::Move,
+ };
+ ui.ctx().set_cursor_icon(icon);
+ return true;
+ }
+ let m_init = Matrix(drag.initial_matrix);
+ let [a0, b0, c0, d0, e0, f0] = drag.initial_matrix;
+ let w0 = (a0 * a0 + b0 * b0).sqrt().max(1e-6);
+ let h0 = (c0 * c0 + d0 * d0).sqrt().max(1e-6);
+ let u_axis = (a0 / w0, b0 / w0);
+ let v_axis = (c0 / h0, d0 / h0);
+ let center_user = (e0 + 0.5 * (a0 + c0), f0 + 0.5 * (b0 + d0));
+
+ let (sx, sy) = screen_to_user(xf, info, page, drag.start);
+ let (px, py) = screen_to_user(xf, info, page, p);
+
+ let (m_new, cursor_icon) = match drag.target {
+ DragTarget::Rotate => {
+ let v0 = (sx - center_user.0, sy - center_user.1);
+ let v1 = (px - center_user.0, py - center_user.1);
+ let theta0 = v0.1.atan2(v0.0);
+ let theta1 = v1.1.atan2(v1.0);
+ let mut delta = theta1 - theta0;
+ if ui.input(|i| i.modifiers.shift) {
+ let step = std::f64::consts::PI / 12.0;
+ delta = (delta / step).round() * step;
+ }
+ let (cos_d, sin_d) = (delta.cos(), delta.sin());
+ let t_rot = [
+ cos_d,
+ sin_d,
+ -sin_d,
+ cos_d,
+ center_user.0 * (1.0 - cos_d) + center_user.1 * sin_d,
+ center_user.1 * (1.0 - cos_d) - center_user.0 * sin_d,
+ ];
+ (m_init.then(&Matrix(t_rot)), egui::CursorIcon::Grab)
+ }
+ DragTarget::Move => {
+ let (dx, dy) = (px - sx, py - sy);
+ (Matrix([a0, b0, c0, d0, e0 + dx, f0 + dy]), egui::CursorIcon::Move)
+ }
+ DragTarget::Handle(handle) => {
+ let p00 = (e0, f0);
+ let p10 = (e0 + a0, f0 + b0);
+ let p11 = (e0 + a0 + c0, f0 + b0 + d0);
+ let p01 = (e0 + c0, f0 + d0);
+ let p_curr = (px, py);
+
+ let (new_w, new_h, p00_new, icon) = match handle {
+ ImageHandle::TopRight => {
+ let anchor = p00;
+ let d = (p_curr.0 - anchor.0, p_curr.1 - anchor.1);
+ let du = d.0 * u_axis.0 + d.1 * u_axis.1;
+ let dv = d.0 * v_axis.0 + d.1 * v_axis.1;
+ let su = du / w0;
+ let sv = dv / h0;
+ let s = if (su - 1.0).abs() >= (sv - 1.0).abs() { su } else { sv };
+ let s = s.max(5.0 / w0).max(5.0 / h0);
+ (w0 * s, h0 * s, anchor, egui::CursorIcon::ResizeNeSw)
+ }
+ ImageHandle::TopLeft => {
+ let anchor = p10;
+ let d = (p_curr.0 - anchor.0, p_curr.1 - anchor.1);
+ let du = d.0 * (-u_axis.0) + d.1 * (-u_axis.1);
+ let dv = d.0 * v_axis.0 + d.1 * v_axis.1;
+ let su = du / w0;
+ let sv = dv / h0;
+ let s = if (su - 1.0).abs() >= (sv - 1.0).abs() { su } else { sv };
+ let s = s.max(5.0 / w0).max(5.0 / h0);
+ let nw = w0 * s;
+ let nh = h0 * s;
+ (nw, nh, (anchor.0 - nw * u_axis.0, anchor.1 - nw * u_axis.1), egui::CursorIcon::ResizeNwSe)
+ }
+ ImageHandle::BottomLeft => {
+ let anchor = p11;
+ let d = (p_curr.0 - anchor.0, p_curr.1 - anchor.1);
+ let du = d.0 * (-u_axis.0) + d.1 * (-u_axis.1);
+ let dv = d.0 * (-v_axis.0) + d.1 * (-v_axis.1);
+ let su = du / w0;
+ let sv = dv / h0;
+ let s = if (su - 1.0).abs() >= (sv - 1.0).abs() { su } else { sv };
+ let s = s.max(5.0 / w0).max(5.0 / h0);
+ let nw = w0 * s;
+ let nh = h0 * s;
+ (
+ nw,
+ nh,
+ (anchor.0 - nw * u_axis.0 - nh * v_axis.0, anchor.1 - nw * u_axis.1 - nh * v_axis.1),
+ egui::CursorIcon::ResizeNeSw,
+ )
+ }
+ ImageHandle::BottomRight => {
+ let anchor = p01;
+ let d = (p_curr.0 - anchor.0, p_curr.1 - anchor.1);
+ let du = d.0 * u_axis.0 + d.1 * u_axis.1;
+ let dv = d.0 * (-v_axis.0) + d.1 * (-v_axis.1);
+ let su = du / w0;
+ let sv = dv / h0;
+ let s = if (su - 1.0).abs() >= (sv - 1.0).abs() { su } else { sv };
+ let s = s.max(5.0 / w0).max(5.0 / h0);
+ let nw = w0 * s;
+ let nh = h0 * s;
+ (nw, nh, (anchor.0 - nh * v_axis.0, anchor.1 - nh * v_axis.1), egui::CursorIcon::ResizeNwSe)
+ }
+ ImageHandle::RightCenter => {
+ let anchor = p00;
+ let d = (p_curr.0 - anchor.0, p_curr.1 - anchor.1);
+ let du = (d.0 * u_axis.0 + d.1 * u_axis.1).max(5.0);
+ (du, h0, anchor, egui::CursorIcon::ResizeHorizontal)
+ }
+ ImageHandle::LeftCenter => {
+ let anchor = p10;
+ let d = (p_curr.0 - anchor.0, p_curr.1 - anchor.1);
+ let du = (d.0 * (-u_axis.0) + d.1 * (-u_axis.1)).max(5.0);
+ (du, h0, (anchor.0 - du * u_axis.0, anchor.1 - du * u_axis.1), egui::CursorIcon::ResizeHorizontal)
+ }
+ ImageHandle::TopCenter => {
+ let anchor = p00;
+ let d = (p_curr.0 - anchor.0, p_curr.1 - anchor.1);
+ let dv = (d.0 * v_axis.0 + d.1 * v_axis.1).max(5.0);
+ (w0, dv, anchor, egui::CursorIcon::ResizeVertical)
+ }
+ ImageHandle::BottomCenter => {
+ let anchor = p01;
+ let d = (p_curr.0 - anchor.0, p_curr.1 - anchor.1);
+ let dv = (d.0 * (-v_axis.0) + d.1 * (-v_axis.1)).max(5.0);
+ (w0, dv, (anchor.0 - dv * v_axis.0, anchor.1 - dv * v_axis.1), egui::CursorIcon::ResizeVertical)
+ }
+ };
+ let mat = Matrix([new_w * u_axis.0, new_w * u_axis.1, new_h * v_axis.0, new_h * v_axis.1, p00_new.0, p00_new.1]);
+ (mat, icon)
+ }
+ _ => (m_init, egui::CursorIcon::Default),
+ };
+
+ let preview_obb = ImageObb::new(m_new.0, xf, info, page);
+ if let Some(tex) = view.page_raster(page) {
+ let clipped = painter.with_clip_rect(painter.clip_rect().intersect(xf.rect));
+ let mut mesh = egui::Mesh::with_texture(tex);
+ let orig_corners = obb.corners();
+ let new_corners = preview_obb.corners();
+ for (from, to) in [
+ (orig_corners[3], new_corners[3]),
+ (orig_corners[2], new_corners[2]),
+ (orig_corners[1], new_corners[1]),
+ (orig_corners[0], new_corners[0]),
+ ] {
+ let (u, v) = xf.screen_to_norm(from);
+ mesh.vertices.push(egui::epaint::Vertex { pos: to, uv: Pos2::new(u, v), color: Color32::WHITE });
+ }
+ mesh.add_triangle(0, 1, 2);
+ mesh.add_triangle(0, 2, 3);
+ clipped.add(egui::Shape::mesh(mesh));
+ }
+
+ if preview_obb.is_rotated {
+ let pts = preview_obb.corners();
+ painter.polygon(pts.to_vec(), ACCENT.gamma_multiply(0.04), Stroke::new(1.5, ACCENT));
+ } else {
+ let p_rect = Rect::from_two_pos(preview_obb.s01, preview_obb.s10);
+ let visible = p_rect.intersect(xf.rect);
+ if visible.is_positive() {
+ painter.rect_filled(visible, CornerRadius::ZERO, ACCENT.gamma_multiply(0.04));
+ painter.rect_stroke(visible, CornerRadius::ZERO, Stroke::new(1.5, ACCENT), egui::StrokeKind::Outside);
+ }
+ }
+ for (_, h) in preview_obb.handles() {
+ draw_handle(painter, h, false, false, false, ACCENT);
+ }
+
+ if resp.drag_stopped() || !ptr.primary_down {
+ if let Some(s) = view.image_selection.as_mut() {
+ s.drag = None;
+ }
+ if m_new.0 != drag.initial_matrix {
+ if matches!(drag.target, DragTarget::Move) {
+ let (dx, dy) = (px - sx, py - sy);
+ let new_rect = [image.rect[0] + dx, image.rect[1] + dy, image.rect[2] + dx, image.rect[3] + dy];
+ view.pending_edit = Some(Edit::EditPageImage { page, index: i, change: pdfcraft_engine::ImageEdit::Move(new_rect) });
+ } else if let Some(inv) = Matrix(drag.initial_matrix).invert() {
+ let t = inv.then(&m_new);
+ view.pending_edit = Some(Edit::EditPageImage { page, index: i, change: pdfcraft_engine::ImageEdit::Transform(t.0) });
+ }
+ }
+ }
+ ui.ctx().set_cursor_icon(cursor_icon);
+ return true;
+ }
+ if allow_interaction
+ && ui.input(|inp| inp.key_pressed(egui::Key::Delete) || inp.key_pressed(egui::Key::Backspace))
+ && !ui.ctx().egui_wants_keyboard_input()
+ {
+ view.image_selection = None;
+ view.pending_edit = Some(Edit::EditPageImage { page, index: i, change: pdfcraft_engine::ImageEdit::Delete });
+ return true;
+ }
+ }
+ if !allow_interaction {
+ return false;
+ }
+ let menu_key = image_menu_id();
+ let Some(p) = hover_pos.filter(|p| xf.rect.contains(*p)) else { return false };
+ let Some(hit) = boxes.iter().enumerate().rposition(|(i, b)| {
+ b.is_positive()
+ && images.get(i).is_some_and(|img| b.contains(p) || quad_contains(ImageObb::from_image(img, xf, info, page).corners(), p))
+ && image_contains(i, p)
+ }) else {
+ if resp.secondary_clicked() || resp.clicked() {
+ view.image_selection = None;
+ ui.ctx().data_mut(|d| d.insert_persisted(menu_key, false));
+ }
+ return false;
+ };
+ let Some(hit_img) = images.get(hit) else { return false };
+ let hit_obb = ImageObb::from_image(hit_img, xf, info, page);
+ if selected != Some(hit) {
+ if hit_obb.is_rotated {
+ let pts = hit_obb.corners();
+ for k in 0..4 {
+ painter.line_segment([pts[k], pts[(k + 1) % 4]], Stroke::new(1.5, ACCENT.gamma_multiply(0.7)));
+ }
+ } else if let Some(b) = boxes.get(hit).copied() {
+ painter.rect_stroke(b, CornerRadius::ZERO, Stroke::new(1.5, ACCENT.gamma_multiply(0.7)), egui::StrokeKind::Outside);
+ }
+ }
+ let corner = hit_obb.handles().iter().position(|(_, c)| c.distance(p) < 10.0);
+ ui.ctx().set_cursor_icon(match (selected == Some(hit), corner) {
+ (true, Some(0 | 4)) => egui::CursorIcon::ResizeNwSe,
+ (true, Some(2 | 6)) => egui::CursorIcon::ResizeNeSw,
+ (true, Some(1 | 5)) => egui::CursorIcon::ResizeVertical,
+ (true, Some(3 | 7)) => egui::CursorIcon::ResizeHorizontal,
+ (true, None) => egui::CursorIcon::Grab,
+ _ => egui::CursorIcon::PointingHand,
+ });
+ if resp.clicked() || resp.secondary_clicked() {
+ view.image_selection =
+ Some(ImageSelection { page, index: hit, drag: None, crop: None, crop_mode: false, crop_rect: None, turning: false, settled: None });
+ }
+ if resp.secondary_clicked() {
+ ui.ctx().data_mut(|d| d.insert_persisted(menu_key, true));
+ }
+ true
+}
+
+/// The right-click context menu for a selected image.
+#[allow(clippy::too_many_arguments)]
+pub(crate) fn image_context_menu(
+ ui: &mut egui::Ui,
+ view: &mut DocView,
+ images: &[pdfcraft_engine::PageImage],
+ page: usize,
+ hit: usize,
+ can_paste: bool,
+ action: &mut Option<ImageAction>,
+ at: Option<[f64; 2]>,
+) {
+ let Some(img) = images.get(hit) else { return };
+ use pdfcraft_engine::ImageEdit as E;
+ let raster = !img.is_form;
+
+ let close = |ui: &mut egui::Ui| {
+ ui.ctx().data_mut(|d| d.insert_persisted(image_menu_id(), false));
+ egui::Popup::close_all(ui.ctx());
+ ui.close();
+ };
+
+ // Top horizontal icon bar: Comment, Crop, Rotate CCW, Rotate CW
+ ui.horizontal(|ui| {
+ ui.spacing_mut().item_spacing.x = 4.0;
+ if crate::icons::button(ui, "message-square", 24.0, false, tl!("Add a sticky note here")).clicked() {
+ *action = Some(ImageAction::AddComment(page, hit));
+ close(ui);
+ }
+ if raster && crate::icons::button(ui, "crop", 24.0, false, tl!("Crop")).clicked() {
+ *action = Some(ImageAction::Crop);
+ if let Some(s) = view.image_selection.as_mut() {
+ let rect = img.visible_rect.unwrap_or(img.rect);
+ s.crop = Some(CropMode::new(rect));
+ s.crop_mode = true;
+ s.crop_rect = None;
+ }
+ close(ui);
+ }
+ if crate::icons::button(ui, "rotate-ccw", 24.0, false, tl!("Rotate Counterclockwise")).clicked() {
+ view.pending_edit = Some(Edit::EditPageImage { page, index: hit, change: E::Rotate(3) });
+ close(ui);
+ }
+ if crate::icons::button(ui, "rotate-cw", 24.0, false, tl!("Rotate Clockwise")).clicked() {
+ view.pending_edit = Some(Edit::EditPageImage { page, index: hit, change: E::Rotate(1) });
+ close(ui);
+ }
+ });
+
+ ui.separator();
+
+ if ui.button(tl!("Cut Image")).clicked() {
+ *action = Some(ImageAction::Cut(page, hit));
+ close(ui);
+ }
+ if ui.button(tl!("Copy Image")).clicked() {
+ *action = Some(ImageAction::Copy(page, hit));
+ close(ui);
+ }
+ if ui.add_enabled(can_paste, egui::Button::new(tl!("Paste"))).clicked() {
+ *action = Some(ImageAction::Paste(page, at));
+ close(ui);
+ }
+
+ ui.separator();
+
+ let is_cropped = img.visible_rect.is_some() && img.visible_rect != Some(img.rect);
+ if raster && ui.add_enabled(is_cropped, egui::Button::new(tl!("Remove crop"))).clicked() {
+ view.pending_edit = Some(Edit::EditPageImage { page, index: hit, change: E::RemoveCrop });
+ close(ui);
+ }
+
+ if ui.button(tl!("Flip horizontal")).clicked() {
+ view.pending_edit = Some(Edit::EditPageImage { page, index: hit, change: E::Flip { horizontal: true } });
+ close(ui);
+ }
+ if ui.button(tl!("Flip vertical")).clicked() {
+ view.pending_edit = Some(Edit::EditPageImage { page, index: hit, change: E::Flip { horizontal: false } });
+ close(ui);
+ }
+
+ ui.menu_button(tl!("Arrange image"), |ui| {
+ eprintln!("ARRANGE IMAGE SUBMENU SHOWN");
+ if ui.button(tl!("Bring to front")).clicked() {
+ eprintln!("CLICKED BRING TO FRONT!");
+ view.pending_edit = Some(Edit::EditPageImage { page, index: hit, change: E::Arrange(pdfcraft_engine::ArrangeOrder::BringToFront) });
+ close(ui);
+ }
+ if ui.button(tl!("Send to back")).clicked() {
+ view.pending_edit = Some(Edit::EditPageImage { page, index: hit, change: E::Arrange(pdfcraft_engine::ArrangeOrder::SendToBack) });
+ close(ui);
+ }
+ if ui.button(tl!("Bring forward")).clicked() {
+ view.pending_edit = Some(Edit::EditPageImage { page, index: hit, change: E::Arrange(pdfcraft_engine::ArrangeOrder::BringForward) });
+ close(ui);
+ }
+ if ui.button(tl!("Send backward")).clicked() {
+ view.pending_edit = Some(Edit::EditPageImage { page, index: hit, change: E::Arrange(pdfcraft_engine::ArrangeOrder::SendBackward) });
+ close(ui);
+ }
+ });
+
+ if ui.add_enabled(raster, egui::Button::new(tl!("Replace image"))).clicked() {
+ *action = Some(ImageAction::Replace(page, hit));
+ close(ui);
+ }
+ if ui.add_enabled(raster, egui::Button::new(tl!("Save Image As…"))).clicked() {
+ *action = Some(ImageAction::Save(page, hit));
+ close(ui);
+ }
+
+ ui.separator();
+
+ if ui.button(tl!("Draw freehand")).clicked() {
+ *action = Some(ImageAction::DrawFreehand);
+ close(ui);
+ }
+ if ui.button(tl!("Redact Image")).clicked() {
+ *action = Some(ImageAction::Redact(page, hit));
+ close(ui);
+ }
+ if ui.add_enabled(raster, egui::Button::new("Export image")).clicked() {
+ *action = Some(ImageAction::Save(page, hit));
+ close(ui);
+ }
+
+ ui.separator();
+
+ if ui.button(tl!("Create Link…")).clicked() {
+ *action = Some(ImageAction::Link(page, hit));
+ close(ui);
+ }
+
+ ui.menu_button("Edit image using", |ui| {
+ ui.add_enabled(false, egui::Button::new("Default image editor"));
+ });
+
+ if ui.button(tl!("Recognize Text…")).clicked() {
+ *action = Some(ImageAction::Recognize(page));
+ close(ui);
+ }
+
+ ui.separator();
+
+ if ui.button(tl!("Delete")).clicked() {
+ view.image_selection = None;
+ view.pending_edit = Some(Edit::EditPageImage { page, index: hit, change: E::Delete });
+ close(ui);
+ }
+}
diff --git a/crates/ui-egui/tests/it/editing.rs b/crates/ui-egui/tests/it/editing.rs
index 4cad1fcff..1d506d598 100644
--- a/crates/ui-egui/tests/it/editing.rs
+++ b/crates/ui-egui/tests/it/editing.rs
@@ -8023,7 +8023,7 @@ fn two_image_fixture() -> Vec<u8> {
#[test]
fn duplicate_xobject_at_different_rects_arrange_and_delete_keeps_other_instance_through_menu() {
- let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(|_cc| {
+ let mut h = Harness::builder().with_size(egui::vec2(1400.0, 1400.0)).build_eframe(|_cc| {
let mut app = PdfCraftApp::new();
app.set_option("language", "en").unwrap();
app.open_bytes("dup.pdf", None, two_image_fixture()).expect("opens fixture");
@@ -8034,46 +8034,55 @@ fn duplicate_xobject_at_different_rects_arrange_and_delete_keeps_other_instance_
assert!(h.state_mut().execute("edit.edit_text"));
h.run_steps(2);
- let r = h.state().views[0].page_screen_rect(0).expect("on screen");
- let info = h.state().session.get(id).unwrap().info.pages[0].clone();
- let user_to_screen = move |u: [f64; 2]| {
- let v = info.user_to_view(u[0] as f32, u[1] as f32);
- let scale = r.width() / info.width;
- egui::pos2(r.left() + v[0] * scale, r.top() + v[1] * scale)
- };
+ let xf = h.state().views[0].page_xform(0).expect("page 0 xform");
+ let imgs = h.state().session.get(id).unwrap().page_images(0);
+ let b1 = pdfcraft_ui_egui::canvas::image_screen_rect(&imgs[1], &xf, &h.state().session.get(id).unwrap().info, 0);
+ let p1 = b1.center();
+ eprintln!("B1: {b1:?}, XF_RECT: {:?}, P1: {p1:?}", xf.rect);
- let p1 = user_to_screen([110.0, 110.0]);
+ // 1. Select B (image 1)
+ h.hover_at(p1);
+ h.run_steps(1);
+ h.drag_at(p1);
+ h.run_steps(1);
+ h.drop_at(p1);
+ h.run_steps(2);
+ assert_eq!(h.state().views[0].image_selection.as_ref().map(|s| s.index), Some(1), "image 1 selected");
- // 1. Right-click B (image 1) to open context menu
+ // 2. Right-click B (image 1) to open context menu
h.hover_at(p1);
h.run_steps(1);
h.event(egui::Event::PointerButton { pos: p1, button: egui::PointerButton::Secondary, pressed: true, modifiers: Default::default() });
h.event(egui::Event::PointerButton { pos: p1, button: egui::PointerButton::Secondary, pressed: false, modifiers: Default::default() });
h.run_steps(2);
- // 2. Click "Bring to front" in context menu
+ // 3. Open "Arrange image" submenu and click "Bring to front"
+ h.get_by_label("Arrange image").click();
+ h.run_steps(2);
h.get_by_label("Bring to front").click();
h.run_steps(3);
- // 3. Selection must be preserved after arrange
+ // 4. Selection must be preserved after arrange
let sel = h.state().views[0].image_selection.as_ref().map(|s| s.index);
assert!(sel.is_some(), "selection must be preserved after arrange");
- // 4. Right-click on the selected image again to open context menu
+ // 5. Right-click on the selected image again to open context menu
let sel_idx = sel.unwrap();
- let b_rect = h.state().session.get(id).unwrap().page_images(0)[sel_idx].rect;
- let p_b = user_to_screen([(b_rect[0] + b_rect[2]) / 2.0, (b_rect[1] + b_rect[3]) / 2.0]);
+ let xf_again = h.state().views[0].page_xform(0).expect("page 0 xform");
+ let cur_imgs = h.state().session.get(id).unwrap().page_images(0);
+ let b_rect = pdfcraft_ui_egui::canvas::image_screen_rect(&cur_imgs[sel_idx], &xf_again, &h.state().session.get(id).unwrap().info, 0);
+ let p_b = b_rect.center();
h.hover_at(p_b);
h.run_steps(1);
h.event(egui::Event::PointerButton { pos: p_b, button: egui::PointerButton::Secondary, pressed: true, modifiers: Default::default() });
h.event(egui::Event::PointerButton { pos: p_b, button: egui::PointerButton::Secondary, pressed: false, modifiers: Default::default() });
h.run_steps(2);
- // 5. Click "Delete image" in context menu
- h.get_by_label("Delete image").click();
+ // 6. Click "Delete" in context menu
+ h.get_by_label("Delete").click();
h.run_steps(3);
- // 6. Save, reopen and verify: A remains at [20, 20, 40, 40], B is deleted
+ // 7. Save, reopen and verify: A remains at [20, 20, 40, 40], B is deleted
let saved = h.state().session.save_bytes(id).unwrap();
let mut reopened = pdfcraft_engine::Session::new();
let rid = reopened.open("again.pdf", None, saved, None).unwrap();