PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust
refactor(ui-egui): split canvas.rs into canvas/
aiongg41a525eee36a
diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rsindex 51b2c06db..3aa9fde4f 100644--- a/crates/ui-egui/src/canvas.rs+++ b/crates/ui-egui/src/canvas.rs@@ -16,65 +16,53 @@ use crate::page_pointer::PagePointer;use crate::theme::{self, Tokens};use crate::{PdfCraftApp, QuickTool, RightPanel, comments, icons, widgets};+mod area;+mod bars;+mod cache;+mod find;+mod navigation;+mod organize;+mod selection;+mod xform;+mod zoom;++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;-const THUMB_TAG: u64 = 1 << 63;-const TEXT_TAG: u64 = 1 << 62;-/// A page rendered for the organize grid at the size it is drawn there.-const GRID_TAG: u64 = 1 << 61;-/// Preview rasters tagged with this bit are converted to luminance on receipt, matching the-/// monochrome print requested by Print ▸ Print in grayscale. It is a bit of its own: the-/// renderer's print bit ([`PRINT_TAG`]) is carried by every print preview, so sharing it would-/// turn colour previews into monochrome ones too.-const GRAYSCALE_TAG: u64 = 1 << 59;-/// The tag of a raster that is out of date (shown until its replacement arrives).-const STALE_TAG: u64 = u64::MAX;-/// Pages whose raster would exceed this many device pixels on a side are drawn in tiles.-pub(crate) const TILE_THRESHOLD: f32 = 4096.0;-/// Base device-pixel side of a page tile. The actual side grows with the zoom-/// ([`tile_side`]), so a zoomed viewport is covered by a few tiles instead of many.-const TILE: u32 = 1024;-/// Longest side of the backdrop drawn under tiles, and of a live page preview (signature drag).-pub(crate) const BASE_SIDE: f32 = 2048.0;-/// Thumbnail slot before density scaling. The pages panel draws at most 150 logical points and-/// the organize grid about 146; when the byte budget allows, density reaches the screen so those-/// images are sampled down instead of stretched.-const THUMB_W: f32 = 240.0;-const THUMB_H: f32 = 320.0;-const THUMB_BYTES: usize = 24 * 1024 * 1024;-const PAGE_BYTES: usize = 128 * 1024 * 1024;-const TILE_BYTES: usize = 128 * 1024 * 1024;-const UPLOAD_BYTES_PER_FRAME: usize = 16 * 1024 * 1024;-const RESULTS_PER_FRAME: usize = 8;-/// A defensive ceiling for unusually large viewports / n-up previews.-const MAX_THUMB_DEMAND: usize = 256;-/// At most this many whole-page rasters are cached beyond the ones on screen.-const MAX_CACHED_PAGES: usize = 24;-/// At most this many text layers are cached beyond visible, selected and matched pages.-/// Text layers are glyph structs, far smaller than rasters; deliberately independent of-/// `MAX_CACHED_PAGES` so raster tuning never silently retunes text memory.-const MAX_CACHED_TEXT_PAGES: usize = 24;--fn rgba_bytes(width: usize, height: usize) -> usize {- width.saturating_mul(height).saturating_mul(4)-}--fn texture_bytes(tex: &TextureHandle) -> usize {- let [w, h] = tex.size();- rgba_bytes(w, h)-}--/// Visible grid rows, plus one adjacent row in either direction. Work is independent of-/// document length, including after a large scroll jump.-pub(crate) fn thumbnail_rows(top: f32, bottom: f32, row_height: f32, rows: usize) -> Range<usize> {- let first = (top.max(0.0) / row_height).floor() as usize;- let end = (bottom.max(0.0) / row_height).ceil() as usize;- first.saturating_sub(1).min(rows)..end.saturating_add(1).min(rows)-}#[derive(Clone, Copy, Debug, PartialEq, Eq)]pub enum Fit {@@ -227,151 +215,6 @@ impl ViewDefaults {}}-/// The find bar (⌘F): query, matches across the document, current match.-#[derive(Default)]-pub struct Find {- pub query: String,- /// (page, glyph range) in document order.- pub matches: Vec<(usize, Range<usize>)>,- pub current: Option<usize>,- /// The page a search started from while its match is picked automatically: a text layer- /// that arrives out of order can still supply an earlier match, and the automatic choice- /// follows this page. Cleared when the user picks a match or moves the view themselves.- pub auto_from: Option<usize>,- /// The page the automatic choice last put the view on (the search's starting page until it- /// chose anything). Compared with the viewed page, it tells an automatic scroll from one- /// the reader made themselves; `None` with `auto_from` once the choice is the user's.- pub auto_page: Option<usize>,- /// The reader ended automatic following (by navigating, scrolling, or picking a match).- /// This is distinct from a search that never followed: a late match must be listed without- /// being revealed by scrolling, even when the reader moved before the first match arrived.- pub follow_ended: bool,- pub focus: bool,- pub case_query: String,- /// Find options (Acrobat's: case-sensitive, whole words only).- pub case_sensitive: bool,- pub whole_words: bool,- /// Shown in the Search panel (Advanced Search) instead of the find bar.- pub in_panel: bool,-}--/// What a text layer arriving after a search began may do with the automatic choice.-#[derive(Clone, Copy, Debug, PartialEq, Eq)]-enum Follow {- /// The reader has not moved the view since the automatic choice: it may follow `from`.- Active(usize),- /// The reader navigated, scrolled or picked a match, so no automatic choice may reveal.- Ended,- /// No automatic choice is being followed (the search has not started, or the reader chose).- Never,-}--impl Find {- /// The first match at or after `page`, or the first match when none follows (the search- /// wraps round the document).- fn first_at_or_after(&self, page: usize) -> Option<usize> {- self.matches.iter().position(|(p, _)| *p >= page).or_else(|| (!self.matches.is_empty()).then_some(0))- }-- /// How a text layer arriving now relates to the automatic choice. Once the reader has moved- /// the view (page box, Pages panel, outline, view history or any scrolling), automatic- /// following ends: a later layer must not pull them back to an anchor-derived match.- /// `Ended` is deliberately distinct from `Never`, so a first match arriving after that move- /// is not revealed by a flash meant only for a search that is still following.- fn follow_page(&mut self, viewed: usize) -> Follow {- if self.follow_ended {- return Follow::Ended;- }- match (self.auto_from, self.auto_page) {- (Some(from), Some(page)) if page == viewed => Follow::Active(from),- (Some(_), _) | (_, Some(_)) => {- self.stop_following();- Follow::Ended- }- (None, None) => Follow::Never,- }- }-- /// Ends automatic following: the selected match is now the user's choice to keep.- fn stop_following(&mut self) {- self.auto_from = None;- self.auto_page = None;- self.follow_ended = true;- }-}--/// A text selection on one page.-#[derive(Clone, Copy, Debug, PartialEq)]-struct Selection {- page: usize,- span: Span,-}--#[derive(Clone, Copy, Debug, PartialEq)]-enum Span {- /// Reading order, between two glyph indices.- Run { anchor: usize, head: usize },- /// Column select (#740): the glyphs inside a rectangle in page view space, drawn from the- /// corner the drag started at (`rect[0..2]`) to the pointer (`rect[2..4]`).- Column { rect: [f32; 4] },-}--impl Selection {- fn run(page: usize, anchor: usize, head: usize) -> Self {- Self { page, span: Span::Run { anchor, head } }- }-- fn range(anchor: usize, head: usize) -> Range<usize> {- anchor.min(head)..anchor.max(head).saturating_add(1)- }-- /// One rectangle per selected piece of a line, in view space (highlighting, markup quads).- fn rects(&self, text: &PageText) -> Vec<[f32; 4]> {- match self.span {- Span::Run { anchor, head } => text.line_rects(Self::range(anchor, head)),- Span::Column { rect } => text.glyph_rects(&text.glyphs_in(rect)),- }- }-- /// The selected text, as Copy puts it on the clipboard.- fn text(&self, text: &PageText) -> String {- match self.span {- Span::Run { anchor, head } => text.text_of(Self::range(anchor, head)),- Span::Column { rect } => text.column_text(&text.glyphs_in(rect)),- }- }-}--/// The glyphs `clicks` quick clicks select around glyph `a`: two the word, three the line, more-/// the page.-fn click_unit(text: &PageText, clicks: u32, a: usize) -> Option<(usize, usize)> {- match clicks {- 2 => text.word_at(a),- 3 => text.line_at(a),- _ => text.glyphs.len().checked_sub(1).map(|last| (0, last)),- }-}--struct PageTex {- tag: u64,- tex: TextureHandle,-}--/// Retained RGBA texture accounting for automation and performance regressions. These-/// surface bytes exclude driver overhead and temporary upload buffers; they are not RSS.-#[derive(Clone, Copy, Debug, Default, serde::Serialize)]-pub struct RasterMemory {- pub thumbnail_count: usize,- pub thumbnail_bytes: usize,- pub page_count: usize,- pub page_bytes: usize,- pub tile_count: usize,- pub tile_bytes: usize,- pub thumbnail_demand: usize,- /// Last submitted missing results; workers may have completed some since submission.- pub pending_requests: usize,-}-/// 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.@@ -392,30 +235,6 @@ pub struct Snapshot {pub from: String,}-/// A validation badge drawn over a signature widget: the widget rectangle (user space), the verdict it shows, and its hover text.-pub(crate) struct SignatureBadge {- pub rect: [f64; 4],- pub status: pdfcraft_engine::SignatureStatus,- pub summary: &'static str,-}--/// The validation badges drawn over one page's signature widgets: signed, visible widgets-/// on this page with coordinates that survive the cast to screen space. Hostile files can-/// carry NaN, infinite or gigantic rectangles, which must never reach the painter.-pub(crate) fn signature_badges(signatures: &[pdfcraft_engine::SignatureInfo], page: usize) -> Vec<SignatureBadge> {- signatures- .iter()- .filter(|s| s.signed && s.visible && s.page == Some(page))- .filter_map(|s| {- s.rect.filter(|r| r.iter().all(|v| v.is_finite() && v.abs() < f32::MAX as f64)).map(|rect| SignatureBadge {- rect,- status: s.status,- summary: s.summary(),- })- })- .collect()-}-/// The 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)@@ -695,30 +514,6 @@ pub struct DocView {slow_pages: HashSet<usize>,}-/// The page grid's zoom range and the step of its buttons and keys.-pub const GRID_ZOOM_RANGE: std::ops::RangeInclusive<f32> = 0.5..=3.0;-/// Thumbnail size in the Pages inspector, relative to its usual size.-pub const THUMBNAIL_ZOOM_RANGE: std::ops::RangeInclusive<f32> = 0.5..=1.5;-const GRID_ZOOM_STEP: f32 = 1.25;-/// How far a sharp grid render may be from the size drawn before it is redone: a pinch changes-/// the size on every frame, and a slightly soft or slightly large image is fine meanwhile.-const GRID_SHARP: std::ops::RangeInclusive<f32> = 0.9..=1.6;--/// Whether an image `have` device pixels wide is good enough to draw `want` pixels wide.-fn sharp_enough(have: u32, want: f32) -> bool {- want > 0.0 && GRID_SHARP.contains(&(have as f32 / want))-}--/// Thumbnail device-pixel density when `demand` pages share the thumbnail allowance.-fn thumbnail_density(demand: usize, ppp: f32) -> f32 {- let per_thumb = THUMB_BYTES / demand.max(1).next_power_of_two();- ppp.clamp(0.25, 4.0).min((per_thumb as f32 / (4.0 * THUMB_W * THUMB_H)).sqrt() * 0.98)-}--fn thumbnail_scale(width: f32, height: f32, density: f32) -> f32 {- (THUMB_W / width.max(1.0)).min(THUMB_H / height.max(1.0)) * density-}-/// Organize-toolbar actions that need the app (file pickers, new tabs, dialogs).#[derive(Clone, Copy, Debug, PartialEq, Eq)]pub enum ViewAction {@@ -754,29 +549,6 @@ pub enum ViewAction {}impl DocView {- pub fn raster_memory(&self) -> RasterMemory {- RasterMemory {- thumbnail_count: self.thumbs.len(),- thumbnail_bytes: self.thumbs.values().fold(0usize, |n, p| n.saturating_add(texture_bytes(&p.tex))),- page_count: self.pages.len(),- page_bytes: self.pages.values().fold(0usize, |n, p| n.saturating_add(texture_bytes(&p.tex))),- tile_count: self.tiles.len(),- tile_bytes: self.tiles.values().fold(0usize, |n, tex| n.saturating_add(texture_bytes(tex))),- thumbnail_demand: self.thumb_demand.len(),- pending_requests: self.last_queue.len(),- }- }-- /// Where `page` is drawn on screen this frame (`None` when it is not on screen).- pub fn page_screen_rect(&self, page: usize) -> Option<Rect> {- self.screen_xforms.iter().find(|(p, _)| *p == page).map(|(_, xf)| xf.rect)- }-- /// The document area on screen.- pub fn viewport_rect(&self) -> Rect {- self.viewport_screen- }-/// Whether a middle-button scrolling gesture is active (tests and automation).pub fn auto_scrolling(&self) -> bool {self.auto_scroll.active()@@ -811,13 +583,6 @@ impl DocView {}}- /// Pages that could not be rendered, with the reason (for automation; 0-based pages).- pub fn page_errors(&self) -> Vec<(usize, &str)> {- let mut v: Vec<(usize, &str)> = self.errors.iter().map(|(p, e)| (*p, e.as_str())).collect();- v.sort_unstable_by_key(|(p, _)| *p);- v- }-/// 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 {@@ -1019,1979 +784,172 @@ impl DocView {self.page_input_reselect = true;}- /// Open Organize Pages on the page being read (issue #1910). An empty selection means the- /// current page, so a selection left from earlier that does not include it is dropped, and- /// the grid scrolls its cell into view. Every way into the grid goes through here; closing- /// it is a plain `organize = false`.- pub fn open_organize(&mut self) {- self.organize = true;- if !self.selected.is_empty() && !self.selected.contains(&self.current) {- self.clear_page_selection(Some(self.current));- }- self.grid_reveal = Some(self.current);- }-- /// Pages an organize command acts on: the selection, or the current page.- pub fn target_pages(&self) -> Vec<usize> {- if self.selected.is_empty() { vec![self.current] } else { self.selected.iter().copied().collect() }- }-/// Select pages in the organize grid (tests, automation). Empty clears the selection.pub(crate) fn page_count(&self) -> usize {self.page_count}- pub fn select_pages(&mut self, pages: &[usize]) {- self.selected = pages.iter().copied().filter(|p| *p < self.page_count).collect();- if let Some(first) = self.selected.first() {- self.current = *first;- }- }-- /// A click on page `i`'s thumbnail, in the organize grid or the Pages panel. ⇧ selects the- /// range from the anchor (or the current page); ⌘/Ctrl toggles the page; a plain click- /// selects only it. `seed_current` is for the Pages panel, where an empty selection means- /// the current page: the first ⌘-click on another page keeps the current one selected too.- pub fn click_page(&mut self, i: usize, modifiers: egui::Modifiers, seed_current: bool) {- if i >= self.page_count {- return;- }- if modifiers.shift {- let a = self.select_anchor.unwrap_or(self.current);- self.selected = (a.min(i)..=a.max(i)).collect();- } else if modifiers.command {- if seed_current && self.selected.is_empty() && i != self.current {- self.selected.insert(self.current);- }- if !self.selected.remove(&i) {- self.selected.insert(i);- }- self.select_anchor = Some(i);- } else {- self.selected = [i].into();- self.select_anchor = Some(i);- }- }-- /// Drop the page selection; a later ⇧-click ranges from `anchor`.- pub fn clear_page_selection(&mut self, anchor: Option<usize>) {- self.selected.clear();- self.select_anchor = anchor.filter(|a| *a < self.page_count);- }-- pub fn render_pending(&self) -> bool {- !self.last_queue.is_empty() || self.text_background.pending() || self.move_background.pending()+ /// 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();}+}- /// The cached tile keys of a page, as (scale tag, tile x, tile y) (diagnostics and tests).- pub fn tiles_debug(&self, page: usize) -> Vec<(u64, u32, u32)> {- let mut k: Vec<(u64, u32, u32)> = self.tiles.keys().filter(|key| key.0 == page).map(|key| (key.1, key.2, key.3)).collect();- k.sort_unstable();- k+/// Draws the document tab at `index`: its notice bars, then its pages (or the Organize grid) in a+/// scroll area with this frame's zoom, scrolling, tool input, overlays and render requests.+pub fn document_area(app: &mut PdfCraftApp, index: usize, ui: &mut egui::Ui) {+ let t = Tokens::get(ui.ctx());+ // Keyboard scrolling applies to this frame's page view only, never later.+ let key_scroll = std::mem::take(&mut app.views[index].key_scroll);+ if key_scroll != 0.0 {+ app.views[index].end_find_following();}-- /// Re-render every page and text layer (the document's appearance changed, e.g. a layer- /// was toggled). Out-of-date rasters stay on screen until their replacements arrive, so the- /// view never flashes blank.- pub fn invalidate_content(&mut self) {- // Undo, redo and other document-wide changes: a released drawing's preview would be a ghost.- self.comments.settling.clear();- for p in self.pages.values_mut() {- p.tag = STALE_TAG;- }- self.stale_thumbs.extend(self.thumbs.keys().copied());- for slot in self.print_pages.values_mut() {- slot.0 = STALE_TAG;- }- // Pages may have moved: a sharp render of another page would be worse than a soft one.- self.grid_pages.clear();- self.tiles.clear();- self.stale_tiles.clear();- self.forms.unbaked.clear();- self.texts.clear();- self.text_failed.clear();- self.errors.clear();- self.slow_pages.clear();- self.waiting_since.clear();- self.last_queue.clear();- self.selection = None;- self.all_text = false;- // A content change is not reader navigation: keep the automatic anchor so the- // re-extracted layers still follow it, and keep `follow_ended` so a reader who already- // took over stays in control. `document_changed` clamps `current`; if the view no longer- // sits where the automatic choice left it, `follow_page` ends it.- if let Some(f) = self.find.as_mut() {- f.matches.clear();- f.current = None;- }+ // 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;}-- /// Only `page` changed (a comment was added, edited or removed): re-render that page and- /// re-read its text, keep everything else. Out-of-date tiles stay on screen until replacements arrive.- pub fn page_changed(&mut self, page: usize) {- if let Some(p) = self.pages.get_mut(&page) {- p.tag = STALE_TAG;- }- if self.thumbs.contains_key(&page) {- self.stale_thumbs.insert(page);- }- if let Some(slot) = self.print_pages.get_mut(&page) {- slot.0 = STALE_TAG;- }- let current_tag = if self.current_scale_tag != 0 {- self.current_scale_tag+ // 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 {- self.tiles.keys().filter(|k| k.0 == page).map(|k| k.1).max().unwrap_or(0)- };- self.tiles.retain(|key, _| key.0 != page || key.1 == current_tag);- self.stale_tiles.retain(|key| key.0 != page || key.1 == current_tag);- for &key in self.tiles.keys() {- if key.0 == page && key.1 == current_tag {- self.stale_tiles.insert(key);- }- }- self.slow_pages.remove(&page);- self.texts.remove(&page);- self.text_failed.remove(&page);- self.errors.remove(&page);- self.last_queue.clear();- if self.selection.is_some_and(|s| s.page == page) {- self.selection = None;+ app.close_tab(i);}+ return;}-- /// Pages drawn last frame and their screen rectangles.- pub fn visible_page_rects(&self) -> Vec<(usize, Rect)> {- self.screen_xforms.iter().map(|(p, xf)| (*p, xf.rect)).collect()- }-- /// Where `page` is drawn this frame, with its coordinate mapping.- pub(crate) fn page_xform(&self, page: usize) -> Option<PageXform> {- self.screen_xforms.iter().find(|(p, _)| *p == page).map(|(_, xf)| *xf)+ 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 text selection as markup quadrilaterals in user space: (page, quads).- pub(crate) fn selection_quads(&self, info: &DocInfo) -> Option<(usize, Vec<[f64; 8]>)> {- let s = self.selection?;- let text = self.texts.get(&s.page)?;- let page = info.pages.get(s.page)?;- let quads: Vec<[f64; 8]> = s.rects(text).into_iter().map(|r| page.view_rect_to_quad(r)).collect();- (!quads.is_empty()).then_some((s.page, quads))+ // The 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();}-- /// Where a bookmark made now should go: the page and the `/XYZ` position `[left, top]` in user- /// space. With text selected it is the corner of the selection that shows at its top-left- /// (its page, both coordinates); otherwise the top of the window (the page showing there, and- /// only the position along the window's vertical, so the reader's other scroll position and- /// zoom are kept). `None` before the first frame has laid pages out, when the bookmark just- /// goes to the current page.- pub(crate) fn bookmark_position(&self, info: &DocInfo) -> Option<(usize, [Option<f32>; 2])> {- if let Some(sel) = self.selection- && let Some(text) = self.texts.get(&sel.page)- && let Some(p) = info.pages.get(sel.page)- {- // The selection's bounds in view space, which View ▸ Rotate View leaves unturned: the- // corner at the screen's top-left is a different one for each quarter turn.- let [x0, y0, x1, y1] = sel.rects(text).iter().fold([f32::INFINITY, f32::INFINITY, f32::NEG_INFINITY, f32::NEG_INFINITY], |b, r| {- [b[0].min(r[0]), b[1].min(r[1]), b[2].max(r[2]), b[3].max(r[3])]- });- let (x, y) = match self.rotation {- 90 => (x0, y1),- 180 => (x1, y1),- 270 => (x1, y0),- _ => (x0, y0),- };- if x.is_finite() && y.is_finite() {- return Some((sel.page, p.xyz_for_view(Some(x), Some(y))));+ // The Prepare a form panel is open (or a field tool is picked): fields are edited, not filled.+ let preparing = app.is_preparing();+ // Prepare a form ▸ Calculation order: the order's steps and links on the page.+ let calc_order = preparing && app.left_open && app.left == crate::LeftPanel::CalculationOrder;+ // Edit a PDF: added text and images can be selected, moved and edited.+ let editing_content =+ (app.left_open && app.left == crate::LeftPanel::Tool("edit")) || matches!(app.quick_tool, QuickTool::AddText | QuickTool::EditText);+ let text_style = app.text_style.clone();+ let show_secured_notice = app.show_secured_notice;+ let view = &mut app.views[index];+ // Opened without the owner password and something is restricted. The notice says so unless+ // the user turned it off (#4035): the restrictions themselves, and Document Properties ▸+ // Security, stay as they are.+ let secured = show_secured_notice && doc.security_summary().is_some_and(|s| !(s.owner || (s.permissions.modify() && s.permissions.assemble())));+ let repaired = !doc.repair_log().is_empty();+ match notices(view, doc, secured, repaired, crate::sign_ui::banner(&doc.signatures), ui, &t) {+ #[cfg(not(target_arch = "wasm32"))]+ Some(Notice::Reload) => app.watch.reload_request = Some(view.id),+ #[cfg(target_arch = "wasm32")]+ Some(Notice::Reload) => {}+ Some(Notice::Repairs) => app.dialog = Some(crate::Dialog::Properties(crate::PropsTab::Advanced)),+ Some(Notice::Security) => app.dialog = Some(crate::Dialog::Properties(crate::PropsTab::Security)),+ Some(Notice::Unlock) => app.unlock_prompt = Some(crate::UnlockPrompt::new(doc, None)),+ // Flags the view: the tab closes at the top of the next frame, where no document+ // borrow is held.+ Some(Notice::Close) => {+ if let Some(view) = app.views.get_mut(index) {+ view.close_requested = true;}}- // The page showing at the window's top edge: one that crosses it (the first, in a spread- // of pages of different heights, whose shorter page can start below it), else the- // nearest one below.- let top = self.viewport_screen.top();- let showing = || self.screen_xforms.iter().filter(|(_, xf)| xf.rect.bottom() > top);- let (page, xf) = showing()- .filter(|(_, xf)| xf.rect.top() <= top)- .min_by_key(|(p, _)| *p)- .or_else(|| showing().min_by(|a, b| a.1.rect.top().total_cmp(&b.1.rect.top()).then(a.0.cmp(&b.0))))?;- let p = info.pages.get(*page)?;- // Above the page (in the gap before it) is the page's own top. The window's vertical is- // the view's y, or its x when the view is turned a quarter.- let (x, y) = xf.screen_to_view(pos2(xf.rect.center().x, top.max(xf.rect.top())));- let at = if xf.rot.is_multiple_of(180) {- p.xyz_for_view(None, Some(y.clamp(0.0, p.height)))- } else {- p.xyz_for_view(Some(x.clamp(0.0, p.width)), None)- };- Some((*page, at))+ 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;}- /// The user-space `[left, top]` at the window's top-left (where `/XYZ` puts its point), on the- /// page showing there: what a destination's null coordinate keeps (ISO 32000-2 §12.3.2.2).- /// Acrobat keeps the place this way across pages, so a CAD sheet's cross-reference opens the- /// next sheet where the reader was looking. A coordinate is `None` along a screen axis the- /// page fits, which keeps the layout's own placement (centred, or the page's top); the whole- /// place is `None` before the first frame has laid pages out.- fn place_at_corner(&self, info: &DocInfo) -> Option<[Option<f32>; 2]> {- let area = self.viewport_screen;- if !area.is_positive() {- return None;- }- let corner = area.min + vec2(SIDE, 0.0);- let (page, xf) = self- .screen_xforms+ 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()- .filter(|(_, xf)| xf.rect.is_positive())- .min_by(|a, b| a.1.rect.distance_sq_to_pos(corner).total_cmp(&b.1.rect.distance_sq_to_pos(corner)).then(a.0.cmp(&b.0)))?;- let p = info.pages.get(*page)?;- let (x, y) = xf.screen_to_view(corner.clamp(xf.rect.min, xf.rect.max));- // `max` drops a NaN size, so the bounds stay ordered and `clamp` can't panic.- let (x, y) = (x.clamp(0.0, p.width.max(0.0)), y.clamp(0.0, p.height.max(0.0)));- // The page counts with its side gutters, as the layout places it.- let wide = xf.rect.width() + 2.0 * SIDE > area.width();- let tall = xf.rect.height() > area.height();- // The view's x runs across the screen unless the view is turned a quarter.- let (keep_x, keep_y) = if xf.rot.is_multiple_of(180) { (wide, tall) } else { (tall, wide) };- Some(p.xyz_for_view(keep_x.then_some(x), keep_y.then_some(y)))+ .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)));+ }}- /// A page's thumbnail texture, when rendered.- pub(crate) fn thumb_id(&self, page: usize) -> Option<egui::TextureId> {- self.thumbs.get(&page).map(|t| t.tex.id())+ // 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),+ }}-- /// The whole-page raster on screen for `page` (the low-res backdrop of a tiled page), if any.- pub(crate) fn page_raster(&self, page: usize) -> Option<egui::TextureId> {- self.pages.get(&page).map(|p| p.tex.id())- }-- /// Whether `page`'s whole-page raster (a tiled page's backdrop too) is still the one from- /// before its last change, whatever its tiles are.- pub(crate) fn page_raster_out_of_date(&self, page: usize) -> bool {- self.pages.get(&page).is_some_and(|p| p.tag == STALE_TAG)- }-- /// Whether `page` is still drawn, somewhere, as it was before its last change: its whole-page- /// raster (a tiled page's backdrop too) or any of its tiles waits for a replacement.- pub(crate) fn page_out_of_date(&self, page: usize) -> bool {- self.pages.get(&page).is_some_and(|p| p.tag == STALE_TAG) || self.stale_tiles.iter().any(|k| k.0 == page)- }-- /// The print preview's picture of `page`: the sheet raster when it has arrived, otherwise the- /// thumbnail.- pub(crate) fn page_preview(&self, page: usize) -> Option<egui::TextureId> {- self.print_pages.get(&page).map(|(_, tex)| tex.id()).or_else(|| self.thumb_id(page))- }-- pub(crate) fn page_text(&self, page: usize) -> Option<Arc<PageText>> {- self.texts.get(&page).cloned()- }-- pub(crate) fn clear_selection(&mut self) {- self.selection = None;- self.actions_dismissed = None;- }-- /// Select text on `page` from glyph `from` to glyph `to` (tests and automation).- pub fn select_text(&mut self, page: usize, from: usize, to: usize) {- self.all_text = false;- self.selection = Some(Selection::run(page, from, to));- }-- /// Open the find bar (or focus it if already open).- pub fn open_find(&mut self) {- let f = self.find.get_or_insert_with(Find::default);- f.focus = true;- }-- /// Re-run the search on all pages whose text is known (after the query changed).- pub fn rerun_find(&mut self) {- let Some(f) = self.find.as_mut() else { return };- f.case_query = f.query.clone();- f.matches.clear();- f.current = None;- // Refining the query keeps the page the reader started searching from, even when an- // automatic choice has already scrolled them to a match. Only a view the reader moved- // themselves re-anchors the search on the page now shown.- let from = match (f.auto_from, f.auto_page) {- (Some(from), Some(page)) if !f.follow_ended && page == self.current => from,- _ => self.current,- };- f.auto_from = Some(from);- f.auto_page = Some(self.current);- f.follow_ended = false;- if f.case_query.trim().is_empty() {- return;- }- let mut pages: Vec<usize> = self.texts.keys().copied().collect();- pages.sort();- for &p in &pages {- if let Some(text) = self.texts.get(&p) {- f.matches.extend(text.find_opts(&f.case_query, f.case_sensitive, f.whole_words).into_iter().map(|r| (p, r)));- }- }- f.matches.sort_by_key(|(p, r)| (*p, r.start));- // First match at or after the page the search started from.- if let Some(i) = f.first_at_or_after(from)- && let Some(&(p, _)) = f.matches.get(i)- {- f.current = Some(i);- f.auto_page = Some(p);- self.flash_match(p);- }- }-- fn refresh_find_page(&mut self, page: usize) {- let (Some(f), Some(text)) = (self.find.as_mut(), self.texts.get(&page)) else { return };- if f.case_query.trim().is_empty() {- return;- }- let previous = f.current.and_then(|c| f.matches.get(c).cloned());- // An automatic choice follows the page it was anchored on, so a page whose text- // arrives late can still supply an earlier match. Once the reader has moved the view,- // this arrival must not pull them back; the choice then becomes theirs to keep.- let follow = f.follow_page(self.current);- f.matches.retain(|(p, _)| *p != page);- f.matches.extend(text.find_opts(&f.case_query, f.case_sensitive, f.whole_words).into_iter().map(|r| (page, r)));- f.matches.sort_by_key(|(p, r)| (*p, r.start));- if let Follow::Active(from) = follow {- f.current = f.first_at_or_after(from);- let selected = f.current.and_then(|i| f.matches.get(i).cloned());- // Follow a changed automatic choice; the view is still where the last one left it.- if selected != previous- && let Some((p, _)) = selected- {- f.auto_page = Some(p);- self.flash_match(p);- }- return;- }- // A match the user picked keeps its identity, exactly as before automatic following.- // When it is gone (or none was picked), the first match at or after the viewed page is- // selected for the panel, but the view stays put: `Ended` and `Never` have no automatic- // choice to reveal, and a reader who moved before the first layer arrived must not be- // pulled back by that late match.- let preserved = previous.as_ref().and_then(|k| f.matches.iter().position(|m| m == k));- f.current = preserved.or_else(|| f.first_at_or_after(self.current));- }-- /// Go to match `i` (the Search panel's results).- pub fn go_to_match(&mut self, i: usize) {- let Some(f) = self.find.as_mut() else { return };- let Some(&(p, _)) = f.matches.get(i) else { return };- f.current = Some(i);- f.stop_following();- self.go_to_page(p);- self.goto_point = None;- self.flash_match(p);- }-- /// Move to the next/previous match.- pub fn find_step(&mut self, forward: bool) {- let Some(f) = self.find.as_mut() else { return };- if f.matches.is_empty() {- return;- }- let n = f.matches.len();- let c = f.current.unwrap_or(0);- let next = if forward { (c + 1) % n } else { (c + n - 1) % n };- f.current = Some(next);- f.stop_following();- let p = f.matches[next].0;- // Only explicit search navigation joins history; background refresh uses flash_match alone.- self.go_to_page(p);- self.goto_point = None;- self.flash_match(p);- }-- fn flash_match(&mut self, page: usize) {- let frac = self- .find- .as_ref()- .and_then(|f| f.current.and_then(|c| f.matches.get(c)))- .and_then(|(p, r)| self.texts.get(p).and_then(|t| t.glyphs.get(r.start)).map(|g| g.rect[1]))- .zip(self.page_heights.get(page).copied())- .map(|(y, h)| ((y - 60.0) / h).clamp(0.0, 1.0))- .unwrap_or(0.0);- self.goto = Some((page, frac));- self.current = page;- self.reset_coarse_state();- }-- /// Screen position of the centre of glyph `glyph` on `page`, if that page is on screen and its- /// text layer is loaded (used by UI tests and automation to aim pointer input).- pub fn glyph_screen_pos(&self, page: usize, glyph: usize) -> Option<Pos2> {- let (_, xf) = self.screen_xforms.iter().find(|(p, _)| *p == page)?;- let g = self.texts.get(&page)?.glyphs.get(glyph)?;- Some(xf.view_rect(g.rect).center())- }-- /// Selected text, if any (⌘C).- /// The selected text: of the pages read so far, after Select All of the document (Copy reads- /// the others, [`DocView::pages_without_text`]).- pub fn selected_text(&self) -> Option<String> {- if self.all_text {- return Some(self.whole_text(&HashMap::new())).filter(|x| !x.is_empty());- }- let s = self.selection?;- let t = self.texts.get(&s.page)?;- Some(s.text(t)).filter(|x| !x.is_empty())- }-- pub fn thumb(&self, page: usize) -> Option<&TextureHandle> {- self.thumbs.get(&page).map(|t| &t.tex)- }-- /// Drops wheel state after a discontinuous jump so the destination cannot- /// inherit momentum from the previous viewport.- fn reset_coarse_state(&mut self) {- self.wheel.clear_motion();- self.wheel_boost_x.reset();- self.wheel_boost_y.reset();- }-- /// Ends automatic search following after the reader navigated or scrolled the view. A- /// programmatic search flash never comes through here; it sets `goto` and `current` directly- /// so that its own scroll cannot be mistaken for the reader's.- fn end_find_following(&mut self) {- if let Some(f) = self.find.as_mut() {- f.stop_following();- }- }-- pub fn go_to_page(&mut self, page: usize) {- let page = page.min(self.page_count.saturating_sub(1));- self.end_find_following();- if page != self.current {- // The view history (Previous view / Next view).- if self.back.last() != Some(&self.current) {- self.back.push(self.current);- if self.back.len() > 200 {- self.back.remove(0);- }- }- self.forward.clear();- }- // Partial wheel motion belongs to the old place.- self.reset_coarse_state();- self.goto = Some((page, 0.0));- self.current = page;- }-- /// Reveal a user-space rectangle without changing zoom, centred where the scroll bounds allow.- pub(crate) fn reveal_rect(&mut self, page: usize, rect: [f32; 4], info: &DocInfo) {- self.go_to_page(page);- self.goto_point = None;- let Some(p) = info.pages.get(self.current) else { return };- if !rect.iter().all(|v| v.is_finite()) {- return;- }- // Halve before adding so even large finite coordinates cannot overflow the midpoint.- let x = rect[0] * 0.5 + rect[2] * 0.5;- let y = rect[1] * 0.5 + rect[3] * 0.5;- let [fx, fy] = p.dest_fraction(Some(x), Some(y), self.rotation);- self.goto_point = Some((self.current, fx, fy, vec2(self.viewport_w, self.viewport_h) / 2.0));- }-- /// Go to a destination, a bookmark's or a link's (ISO 32000-2 §12.3.2.2): its page, scrolled- /// and zoomed as `dest` asks, as Acrobat does. `/XYZ` puts (left, top) at the window's- /// top-left at its zoom (null or 0 keeps the zoom); `/Fit`, `/FitH` and `/FitV` switch to fit- /// page, width and height with `top` or `left` at the window's edge; `/FitR` zooms so the- /// rectangle fits, centred. The `B` (content box) forms are read as the page. A null `/XYZ`- /// coordinate keeps the reader's place: the same user-space point stays at the window's- /// top-left on the new page, as Acrobat does. A point past the end of the document scrolls- /// as far as it can.- pub fn go_to_dest(&mut self, page: usize, dest: DestView, info: &DocInfo) {- // Read before the jump: it is where the reader is now.- let kept = match dest {- DestView::Xyz { left, top, .. } if left.is_none() || top.is_none() => self.place_at_corner(info),- _ => None,- };- self.go_to_page(page);- let page = self.current;- self.goto_point = None;- let Some(p) = info.pages.get(page) else { return };- let point = |x: Option<f32>, y: Option<f32>| p.dest_fraction(x, y, self.rotation);- // The window's top-left as far as pages go: its left edge is the gutter that keeps them- // clear of the floating quick-action bar, so `left` 0 shows the page's edge beside it.- let corner = vec2(SIDE, 0.0);- let (fx, fy, rel) = match dest {- DestView::Top => return,- DestView::Xyz { left, top, zoom } => {- if let Some(z) = zoom {- self.zoom = z.clamp(0.08, 64.0);- self.fit = Fit::None;- self.zoom_anchor = None;- }- let [kept_left, kept_top] = kept.unwrap_or([None, None]);- let [fx, fy] = point(left.or(kept_left), top.or(kept_top));- (fx, fy, corner)- }- DestView::Fit => {- self.fit = Fit::Page;- return;- }- DestView::FitH { top } => {- self.fit = Fit::Width;- let [fx, fy] = point(None, top);- (fx, fy, corner)- }- DestView::FitV { left } => {- self.fit = Fit::Height;- let [fx, fy] = point(left, None);- (fx, fy, corner)- }- DestView::FitR { rect } => {- let ([Some(ax), Some(ay)], [Some(bx), Some(by)]) = (point(Some(rect[0]), Some(rect[3])), point(Some(rect[2]), Some(rect[1]))) else {- return;- };- // The rectangle as displayed, in points (it can be turned a quarter).- let (dw, dh) = self.display_size(p);- let (w, h) = ((ax - bx).abs() * dw, (ay - by).abs() * dh);- if w >= 1.0 && h >= 1.0 && self.viewport_w >= 1.0 && self.viewport_h >= 1.0 {- self.zoom = (self.viewport_w / (w * PT)).min(self.viewport_h / (h * PT)).clamp(0.08, 64.0);- self.fit = Fit::None;- self.zoom_anchor = None;- }- (Some((ax + bx) / 2.0), Some((ay + by) / 2.0), vec2(self.viewport_w, self.viewport_h) / 2.0)- }- };- if fx.is_some() || fy.is_some() {- self.goto_point = Some((page, fx, fy, rel));- }- }-- /// Next page (`true`) or previous page. In two-page view this moves a whole spread: the other- /// page of the spread is already on screen, so stepping to it wouldn't move the view (#70).- pub fn step_page(&mut self, forward: bool) {- let c = self.current;- let last = self.page_count.saturating_sub(1);- let (target, first) = match self.layout {- PageLayout::TwoUp => {- let first = self.spread_first(c);- let target = match (forward, self.cover && c == 0) {- (true, true) => 1,- (true, false) => first.saturating_add(2),- (false, _) if self.cover && first <= 1 => 0,- (false, _) => first.saturating_sub(2),- };- (target, first)- }- PageLayout::Single if forward => (c + 1, c),- PageLayout::Single => (c.saturating_sub(1), c),- };- // Past either end there is nowhere to go: stay put rather than re-align the view, which- // would scroll the page back to its top.- if if forward { target > last } else { first == 0 } {- return;- }- self.go_to_page(target);- }-- /// Page-editor focus and drafts belong to a document, even while another tab is active.- pub(crate) fn page_input_id(&self) -> egui::Id {- egui::Id::unique(("page-input", self.id.0))- }-- /// The idle page box and unchanged-input lookup share the same label fallback.- pub(crate) fn current_page_label(&self, label: Option<&str>) -> String {- label.filter(|l| !l.is_empty()).map(str::to_owned).unwrap_or_else(|| (self.current + 1).to_string())- }-- /// Retain the current page when `typed` exactly matches its displayed label, even if- /// another page has that label. Otherwise resolve a trimmed label (case-insensitive),- /// then a physical page number. `false` when it names no page.- pub fn go_to_typed(&mut self, typed: &str, labels: &[String]) -> bool {- // Compare the displayed value before trimming: a label may itself contain spaces.- // Repeated labels occur in restarted sections and prefix-only ranges.- if self.current < self.page_count && self.current_page_label(labels.get(self.current).map(String::as_str)) == typed {- return true;- }- let t = typed.trim();- let page = labels- .iter()- .position(|l| !l.is_empty() && l.eq_ignore_ascii_case(t))- .or_else(|| t.parse::<usize>().ok().filter(|n| *n >= 1).map(|n| n - 1));- match page {- Some(p) if p < self.page_count => {- self.go_to_page(p);- true- }- _ => false,- }- }-- /// View ▸ Page navigation ▸ Previous view (`false`) / Next view (`true`).- pub fn view_history(&mut self, forward: bool) -> bool {- let has_target = if forward { !self.forward.is_empty() } else { !self.back.is_empty() };- if !has_target {- return false;- }- self.end_find_following();- let (from, to) = if forward { (&mut self.forward, &mut self.back) } else { (&mut self.back, &mut self.forward) };- let Some(page) = from.pop() else { return false };- to.push(self.current);- let page = page.min(self.page_count.saturating_sub(1));- self.goto = Some((page, 0.0));- self.current = page;- self.reset_coarse_state();- true- }-- /// Select all: every page in Organize, or every word on the current page.- pub fn select_all(&mut self) -> bool {- if self.organize {- self.selected = (0..self.page_count).collect();- // Keep the current page as the anchor for the next Shift-click.- self.select_anchor = (self.page_count > 0).then_some(self.current);- return !self.selected.is_empty();- }- // Scrolling continuously, Select All takes the whole document's text (#2639); one page at- // a time, the page shown.- // Like the page's, true once some text is selected: the pages whose text isn't read yet are- // read when the selection is copied.- if self.continuous && self.page_count > 1 {- self.selection = None;- self.all_text = true;- return self.selected_text().is_some();- }- self.all_text = false;- let page = self.current;- let Some(t) = self.texts.get(&page) else { return false };- if t.glyphs.is_empty() {- return false;- }- self.selection = Some(Selection::run(page, 0, t.glyphs.len() - 1));- true- }-- /// Pages whose text [`DocView::whole_text`] still needs: not read yet, nor failed.- pub(crate) fn pages_without_text(&self) -> Vec<usize> {- (0..self.page_count).filter(|p| !self.texts.contains_key(p) && !self.text_failed.contains(p)).collect()- }-- /// The whole document's text in page order, one page after another on new lines, from the- /// pages' text read so far and `more` (pages read for this, keyed by page).- pub(crate) fn whole_text(&self, more: &HashMap<usize, Arc<PageText>>) -> String {- let mut out = String::new();- for p in 0..self.page_count {- let Some(t) = self.texts.get(&p).or_else(|| more.get(&p)) else { continue };- let text = t.text_of(0..t.glyphs.len());- if text.is_empty() {- continue;- }- if !out.is_empty() {- out.push('\n');- }- out.push_str(&text);- }- out- }-- /// Rotate the view 90° clockwise or counter-clockwise (View ▸ Rotate View, ⇧⌘+ / ⇧⌘−).- pub fn rotate_view(&mut self, clockwise: bool) {- self.rotation = (self.rotation + if clockwise { 90 } else { 270 }) % 360;- self.goto = Some((self.current, 0.0));- self.reset_coarse_state();- }-- /// Switch the zoom mode, keeping the current page in view.- pub fn set_fit(&mut self, fit: Fit) {- self.fit = fit;- self.goto = Some((self.current, 0.0));- self.reset_coarse_state();- }-- /// Full screen, as Acrobat's Full Screen Mode (#379, #1459): one page at a time (or one- /// spread, when two-page view was on: #1353), fitted to the screen, from the current page.- /// The display it replaces is kept for [`Self::leave_presentation`]. A no-op while presenting.- pub fn enter_presentation(&mut self) {- if self.presentation.is_some() {- return;- }- self.presentation =- Some(SavedDisplay { layout: self.layout, continuous: self.continuous, cover: self.cover, fit: self.fit, zoom: self.zoom });- self.continuous = false;- self.fit = Fit::Page;- self.selection = None;- self.goto = Some((self.current, 0.0));- }-- /// Leave full screen: the display from before it comes back, at the page reached meanwhile.- pub fn leave_presentation(&mut self) {- let Some(saved) = self.presentation.take() else { return };- self.layout = saved.layout;- self.continuous = saved.continuous;- self.cover = saved.cover;- self.fit = saved.fit;- self.zoom = saved.zoom;- self.goto = Some((self.current, 0.0));- }-- /// The display shown outside full screen: the one presenting replaced, or the current one.- pub fn normal_display(&self) -> SavedDisplay {- self.presentation.unwrap_or(SavedDisplay {- layout: self.layout,- continuous: self.continuous,- cover: self.cover,- fit: self.fit,- zoom: self.zoom,- })- }-- /// Whether the view is in full screen's one-page-at-a-time display.- pub fn presenting(&self) -> bool {- self.presentation.is_some()- }-- /// Switch the base page display (Single or Two-page), leaving continuous scrolling as it is.- /// A no-op when the layout is already current, so re-selecting it never yanks a scrolled view- /// back to the top.- pub fn set_layout(&mut self, layout: PageLayout) {- if self.layout == layout {- return;- }- self.layout = layout;- self.goto = Some((self.current, 0.0));- self.reset_coarse_state();- }-- /// Whether the view scrolls continuously (as opposed to one page or spread at a time).- pub fn continuous(&self) -> bool {- self.continuous- }-- /// Change page separation without editing the PDF or losing the reader's place.- pub fn set_page_gaps(&mut self, show: bool) {- if self.show_page_gaps == show {- return;- }- if !self.organize && self.viewport_screen.is_positive() {- let at = self.viewport_screen.center();- if let Some((page, r)) = self- .screen_rects- .iter()- .filter(|(_, r)| r.is_positive())- .min_by(|(_, a), (_, b)| a.distance_sq_to_pos(at).total_cmp(&b.distance_sq_to_pos(at)))- {- let fraction = (at - r.min) / r.size();- self.zoom_anchor = Some((*page, fraction.x, fraction.y, at - self.viewport_screen.min));- }- }- self.show_page_gaps = show;- }-- /// Separation between adjacent page rectangles, in logical screen points.- fn page_gap(&self) -> f32 {- if self.show_page_gaps { GAP } else { 0.0 }- }-- /// Turn continuous scrolling on or off, keeping the current page in view. A no-op when it is- /// already in that state.- pub fn set_continuous(&mut self, continuous: bool) {- if self.continuous != continuous {- self.continuous = continuous;- // Select All of the document belongs to continuous scrolling.- self.all_text = false;- self.goto = Some((self.current, 0.0));- self.reset_coarse_state();- }- }-- /// Set the whole page display at once (the base layout and continuous scrolling together),- /// as the control channel and settings do through a single [`display_token`].- pub fn set_display(&mut self, layout: PageLayout, continuous: bool) {- self.set_layout(layout);- self.set_continuous(continuous);- }-- /// Set the cover page in two-page view. A no-op unless something changed.- pub fn set_cover(&mut self, cover: bool) {- if self.cover != cover {- self.cover = cover;- self.goto = Some((self.current, 0.0));- self.reset_coarse_state();- }- }-- /// Whether the cover page setting applies: only two-page view has a cover page.- pub fn cover_applies(&self) -> bool {- self.layout == PageLayout::TwoUp- }-- /// One wheel event in a non-continuous view, where the wheel turns pages or spreads (the- /// rules are in `wheel_pager`): `dy` is its vertical delta (negative scrolls down) and `now`- /// is egui time. With `can_turn` false the gesture is followed but the page stays. Returns- /// whether the page turned.- pub fn single_page_wheel(&mut self, unit: egui::MouseWheelUnit, dy: f32, phase: egui::TouchPhase, now: f64, can_turn: bool) -> bool {- if self.continuous {- return false;- }- let Some(forward) = self.wheel.feed(unit, dy, phase, now, can_turn) else { return false };- let before = self.current;- self.step_page(forward);- self.current != before- }-- /// One wheel event in a non-continuous view whose page is taller than the window, where the- /// wheel pans (#1924). Once the view is at the bottom (top) edge, scrolling on turns to the- /// next (previous) page, which shows its top (bottom). A smooth gesture that panned the page- /// has to end first (see `WheelPager::feed_edge`). `can_turn` is false when something else- /// owns the wheel. Returns whether the page turned.- pub fn single_page_wheel_edge(&mut self, unit: egui::MouseWheelUnit, dy: f32, phase: egui::TouchPhase, now: f64, can_turn: bool) -> bool {- if self.continuous {- return false;- }- // Only an up-to-date view counts: the page drawn is the shown one, with no jump pending.- let edge = self.goto.is_none()- && self.goto_point.is_none()- && self.single_edges.is_some_and(|(page, top, bottom)| page == self.current && if dy < 0.0 { bottom } else { top });- let Some(forward) = self.wheel.feed_edge(unit, dy, phase, now, can_turn && edge) else { return false };- let before = self.current;- self.step_page(forward);- if self.current == before {- return false;- }- if !forward {- // Going back lands on the bottom of the previous page.- self.goto = Some((self.current, 1.0));- }- self.single_edges = None;- true- }-- /// Displayed page size in points for this view rotation.- fn display_size(&self, p: &pdfcraft_render::PageInfo) -> (f32, f32) {- if self.rotation % 180 == 90 { (p.height, p.width) } else { (p.width, p.height) }- }-- /// Marquee Zoom: zoom so `r` (on screen) fills the window, centred.- pub fn zoom_to_rect(&mut self, r: Rect) {- let Some((page, pr)) = self.screen_rects.iter().find(|(_, pr)| pr.contains(r.center())).copied() else { return };- let k = (self.viewport_screen.width() / r.width().max(1.0)).min(self.viewport_screen.height() / r.height().max(1.0));- let f = (r.center() - pr.min) / pr.size();- self.zoom = (self.zoom * k).clamp(0.08, 64.0);- self.fit = Fit::None;- self.zoom_anchor = Some((page, f.x.clamp(0.0, 1.0), f.y.clamp(0.0, 1.0), self.viewport_screen.center() - self.viewport_screen.min));- }-- /// View ▸ Zoom ▸ Fit Visible: zoom so the visible content of `page` (display-normalised- /// [x0, y0, x1, y1], i.e. after view rotation) spans the window's width, its left edge at- /// the window's left and its top at the top.- pub fn fit_content(&mut self, page: usize, content: [f32; 4]) -> bool {- const PAD: f32 = 16.0;- let Some((_, pr)) = self.screen_rects.iter().find(|(p, _)| *p == page).copied() else { return false };- let w = (content[2] - content[0]).max(0.01) * pr.width();- let k = (self.viewport_screen.width() - 2.0 * PAD).max(50.0) / w.max(1.0);- self.zoom = (self.zoom * k).clamp(0.08, 64.0);- self.fit = Fit::None;- self.zoom_anchor = Some((page, content[0].clamp(0.0, 1.0), content[1].clamp(0.0, 1.0), vec2(PAD, MARGIN)));- true- }-- /// How large the page grid draws its pages (1.0 = the usual thumbnails).- pub fn grid_zoom(&self) -> f32 {- self.grid_zoom- }-- /// Scale of the thumbnails in the Pages inspector (1.0 is the usual size).- pub fn thumbnail_zoom(&self) -> f32 {- self.thumbnail_zoom- }-- /// Resize the inspector thumbnails, keeping the current page in view after layout.- /// Out-of-range values are clamped; non-finite values are ignored.- pub fn set_thumbnail_zoom(&mut self, zoom: f32) {- if zoom.is_finite() {- let zoom = zoom.clamp(*THUMBNAIL_ZOOM_RANGE.start(), *THUMBNAIL_ZOOM_RANGE.end());- if zoom != self.thumbnail_zoom {- self.thumbnail_zoom = zoom;- self.panel_followed = None;- }- }- }-- /// Zoom the page grid; out-of-range values are clamped and nonsense is ignored.- pub fn set_grid_zoom(&mut self, zoom: f32) {- if zoom.is_finite() {- self.grid_zoom = zoom.clamp(*GRID_ZOOM_RANGE.start(), *GRID_ZOOM_RANGE.end());- }- }-- /// How many device pixels wide the grid's sharp render of `page` is, if it has one.- pub fn grid_page_pixels(&self, page: usize) -> Option<u32> {- self.grid_pages.get(&page).map(|(w, _)| *w)- }-- /// Zoom keeping the centre of the view still.- pub fn set_zoom(&mut self, zoom: f32) {- // CLI/view options can set zoom before the first layout. Rect::NOTHING has no- // finite centre yet, but an initial zoom still needs to leave the default fit mode.- let centre = if self.viewport_screen.is_positive() { self.viewport_screen.center() } else { Pos2::ZERO };- self.zoom_at(zoom, centre);- }-- /// Zoom keeping the document point under `screen_pos` still (pinch, ⌘-scroll).- pub fn zoom_at(&mut self, zoom: f32, screen_pos: Pos2) {- if !zoom.is_finite() || !screen_pos.is_finite() {- return;- }- let zoom = zoom.clamp(0.08, 64.0);- if zoom == self.zoom && self.fit == Fit::None {- return;- }- // In gutters/gaps, anchor relative to the nearest page rather than jumping to its top.- // Fractions outside 0..1 preserve the pointer's position outside the page as well.- let anchor =- self.screen_rects.iter().min_by(|(_, a), (_, b)| a.distance_sq_to_pos(screen_pos).total_cmp(&b.distance_sq_to_pos(screen_pos))).map(- |(p, r)| {- let f = (screen_pos - r.min) / r.size();- (*p, f.x, f.y, screen_pos - self.viewport_screen.min)- },- );- self.zoom = zoom;- self.fit = Fit::None;- match anchor {- Some(a) => self.zoom_anchor = Some(a),- // Nothing on screen yet (e.g. a launch option): align the current page instead.- None => self.goto = Some((self.current, 0.0)),- }- }-- /// A zoom typed as a percentage ("150", "150%", " 62.5 % ") as a zoom factor; `None` unless it is a- /// finite, positive number. `set_zoom` clamps it to the supported range.- pub fn parse_zoom_percent(typed: &str) -> Option<f32> {- let percent = typed.trim().trim_end_matches('%').trim_end().parse::<f32>().ok()?;- (percent.is_finite() && percent > 0.0).then_some(percent / 100.0)- }-- /// Standard zoom steps (as in Acrobat's zoom menu).- pub fn zoom_step(&mut self, up: bool) {- const STEPS: [f32; 17] = [0.1, 0.25, 0.33, 0.5, 0.66, 0.75, 1.0, 1.25, 1.5, 2.0, 3.0, 4.0, 6.0, 8.0, 12.0, 16.0, 32.0];- let z = self.zoom;- let next = if up { STEPS.iter().copied().find(|s| *s > z * 1.01) } else { STEPS.iter().rev().copied().find(|s| *s < z * 0.99) };- if let Some(n) = next {- self.set_zoom(n);- }- }-- /// Start collecting demand from every consumer before scheduling or uploading results.- pub(crate) fn begin_render_frame(&mut self) {- self.frame_geometry_changed = false;- self.pages_panel = None;- self.panel_gap = None;- self.thumb_demand.clear();- self.frame_queue.clear();- self.frame_visible.clear();- }-- pub(crate) fn need_thumbnail(&mut self, page: usize, visible: bool) {- if page >= self.page_count {- return;- }- if let Some(priority) = self.thumb_demand.get_mut(&page) {- *priority |= visible;- } else if self.thumb_demand.len() < MAX_THUMB_DEMAND {- self.thumb_demand.insert(page, visible);- } else if visible && let Some(prefetch) = self.thumb_demand.iter().find_map(|(&p, &v)| (!v).then_some(p)) {- self.thumb_demand.remove(&prefetch);- self.thumb_demand.insert(page, true);- }- }-- /// Only the displayed document owns raster textures. Tabs keep their document and view- /// state, but do not each retain a separate full application texture allowance.- pub(crate) fn suspend_rendering(&mut self, pool: &RenderPool) {- self.begin_render_frame();- self.pages.clear();- self.tiles.clear();- self.thumbs.clear();- self.grid_pages.clear();- self.print_pages.clear();- self.stale_thumbs.clear();- self.stale_tiles.clear();- self.waiting_since.clear();- // Signature previews own a separate renderer and image/background textures.- self.signature_drag = Default::default();- self.text_background = Default::default();- self.move_background = Default::default();- if !self.last_queue.is_empty() {- pool.set_queue(Vec::new());- self.last_queue.clear();- }- // Results already finished for this tab would otherwise sit in its pool, rasters and- // all, until the tab is shown again. (An inline pool renders inside try_recv: skip it.)- if !pool.is_inline() {- while pool.try_recv().is_some() {}- }- }-- fn thumbnail_requests(&self, info: &DocInfo, ppp: f32) -> Vec<RenderRequest> {- let mut pages: Vec<_> = self.thumb_demand.iter().map(|(&p, &visible)| (p, visible)).collect();- pages.sort_unstable_by_key(|&(p, visible)| (!visible, p));- // At high DPI or in a very large viewport every demanded cell still fits the same- // byte allowance. Both dimensions are capped, including tall/wide page boxes.- // The count is rounded up to a power of two: the scale is part of each request's tag,- // so a density that followed every row scrolling in or out would re-render them all.- let density = thumbnail_density(pages.len(), ppp);- pages- .into_iter()- .filter_map(|(page, _)| {- let p = info.pages.get(page)?;- let scale = thumbnail_scale(p.width, p.height, density);- Some(RenderRequest {- page,- kind: RequestKind::Pixels,- tile: None,- scale,- tag: THUMB_TAG | u64::from(scale.to_bits()),- // Thumbnails are previews: tiny images are skipped for them.- preview: true,- })- })- .collect()- }-- /// Admit current demand within explicit byte limits. Cached and pending surfaces share- /// the allowance, so an evicted page can be requested again without a permanent done set.- fn prepare_render_queue(&mut self, info: &DocInfo, ppp: f32) -> Vec<RenderRequest> {- let requests = std::mem::take(&mut self.frame_queue);- let mut queue = Vec::new();- let mut pages = HashSet::new();- let mut tiles = HashSet::new();- let mut tile_tags = HashSet::new();- let mut grid = Vec::new();- let (mut page_bytes, mut tile_bytes) = (0usize, 0usize);- for req in requests.iter().filter(|r| r.kind == RequestKind::Pixels) {- let Some(p) = info.pages.get(req.page) else { continue };- // Organize-grid renders: only the cells in view that need one (organize_grid).- if req.tag & GRID_TAG != 0 {- grid.push(*req);- continue;- }- // Print-preview rasters: a few sheets at the pane's size (the dialog bounds them).- if req.tag & PRINT_TAG != 0 {- if !self.errors.contains_key(&req.page) {- queue.push(*req);- }- continue;- }- // On-screen work is always admitted (the viewport bounds it); the limits only- // decide how much prefetch fits beside it.- let visible = self.frame_visible.contains(&req.page);- if let Some(tile) = req.tile {- // Keyed by exact device-pixel origin: the tile side varies with the zoom- // (`tile_side`), so grid indices would need the scale to decode.- let key = (req.page, req.tag, tile.x, tile.y);- let bytes = rgba_bytes(tile.w as usize, tile.h as usize);- if (!visible && tile_bytes.saturating_add(bytes) > TILE_BYTES) || !tiles.insert(key) {- continue;- }- tile_bytes = tile_bytes.saturating_add(bytes);- tile_tags.insert(req.tag);- if !self.tiles.contains_key(&key) || self.stale_tiles.contains(&key) {- queue.push(*req);- }- } else {- let bytes = rgba_bytes(device_pixels(p.width, req.scale) as usize, device_pixels(p.height, req.scale) as usize);- if (!visible && (page_bytes.saturating_add(bytes) > PAGE_BYTES || pages.len() >= MAX_CACHED_PAGES)) || !pages.insert(req.page) {- continue;- }- page_bytes = page_bytes.saturating_add(bytes);- if self.pages.get(&req.page).is_none_or(|p| p.tag != req.tag) {- queue.push(*req);- }- }- }- // Pages no longer demanded stay cached while the allowance has room, nearest to the- // current page first, so turning back a page shows it at once instead of rendering.- let mut undemanded: Vec<usize> = self.pages.keys().copied().filter(|p| !pages.contains(p)).collect();- undemanded.sort_by_key(|p| p.abs_diff(self.current));- let mut kept = pages.len();- for page in undemanded {- let bytes = self.pages.get(&page).map_or(0, |p| texture_bytes(&p.tex));- if kept < MAX_CACHED_PAGES && page_bytes.saturating_add(bytes) <= PAGE_BYTES {- page_bytes = page_bytes.saturating_add(bytes);- kept += 1;- pages.insert(page);- }- }- self.pages.retain(|p, _| pages.contains(p));- // Tiles of an earlier zoom (not a demanded scale) stay while the canvas keeps them, a- // bounded few under a page whose current tiles are still missing (OLD_TILES). Tiles of a- // page on screen stay too even when this frame does not demand them (#2196): the viewport- // moves while zooming, so a tile that was sharp a moment ago falls outside the demanded- // rectangle, and dropping it made every pan or zoom back a cold miss that re-blurred the- // page and re-interpreted it once per tile. The per-frame cap below (OLD_TILES,- // nearest scale first) is what bounds how much of that stays.- self.tiles.retain(|key, _| tiles.contains(key) || !tile_tags.contains(&key.1) || self.frame_visible.contains(&key.0));- self.stale_tiles.retain(|key| self.tiles.contains_key(key));- queue.extend(grid);- // Opening (or turning to) a page queues its pixels alongside thumbnails and- // text extraction. The workers would otherwise spend the first seconds on- // thumbnails and search text while the visible page stays blank: hold those- // until no visible main-page raster is still missing. Errored pages never- // block: they are never re-requested.- let visible_mains_pending = queue.iter().any(|r| {- r.kind == RequestKind::Pixels- && r.tag & (GRID_TAG | PRINT_TAG | THUMB_TAG | TEXT_TAG) == 0- && self.frame_visible.contains(&r.page)- && !self.errors.contains_key(&r.page)- });- if visible_mains_pending {- // Caches are kept; demand is re-evaluated next frame once pixels arrive.- return queue;- }- let thumbs = self.thumbnail_requests(info, ppp);- let mut thumb_bytes = 0usize;- let mut admitted = HashSet::new();- for req in thumbs {- let Some(p) = info.pages.get(req.page) else { continue };- let bytes = rgba_bytes(device_pixels(p.width, req.scale) as usize, device_pixels(p.height, req.scale) as usize);- if thumb_bytes.saturating_add(bytes) > THUMB_BYTES || self.errors.contains_key(&req.page) {- continue;- }- thumb_bytes += bytes;- admitted.insert(req.page);- if self.thumbs.get(&req.page).is_none_or(|t| t.tag != req.tag) || self.stale_thumbs.contains(&req.page) {- queue.push(req);- }- }- self.thumbs.retain(|p, _| admitted.contains(p));- self.stale_thumbs.retain(|p| admitted.contains(p));- self.retain_text_layers();- // Visible main pages and thumbnails take precedence over background search work.- queue.extend(requests.into_iter().filter(|r| r.kind == RequestKind::Text));- queue- }-- /// Drop text layers nothing can still need. Every visited page's text used to stay- /// cached for the session. Keep visible, selected and matched pages plus the nearest- /// prefetch window; evicted pages re-extract on revisit. (Count window only: unlike- /// rasters there is no byte budget here.) While a search is active keep everything:- /// demand still wants every page, so evicting would re-request evicted pages each- /// frame and churn the workers. Failures are never evicted either: they cost nothing- /// to remember, and evicting one would re-request and re-fail it every frame.- fn retain_text_layers(&mut self) {- if self.texts.len() <= MAX_CACHED_TEXT_PAGES {- return;- }- if self.find.as_ref().is_some_and(|f| !f.case_query.trim().is_empty()) {- return;- }- let mut keep: HashSet<usize> = self.frame_visible.clone();- if let Some(s) = self.selection {- keep.insert(s.page);- }- if let Some(f) = self.find.as_ref() {- keep.extend(f.matches.iter().map(|(p, _)| *p));- }- let mut rest: Vec<usize> = self.texts.keys().filter(|p| !keep.contains(*p)).copied().collect();- rest.sort_by_key(|p| p.abs_diff(self.current));- keep.extend(rest.into_iter().take(MAX_CACHED_TEXT_PAGES));- self.texts.retain(|p, _| keep.contains(p));- }-- pub(crate) fn finish_render_frame(&mut self, ctx: &egui::Context, info: &DocInfo, pool: &RenderPool) {- if self.frame_geometry_changed {- // Dialogs and edits can replace pages after the canvas collected demand. Its- // scales and indexes belong to the old pages, not to the new renderer (#3149).- self.begin_render_frame();- self.last_queue.clear();- pool.set_queue(Vec::new());- ctx.request_repaint();- return;- }- let queue = self.prepare_render_queue(info, ctx.pixels_per_point());- if queue != self.last_queue {- pool.set_queue(queue.clone());- self.last_queue = queue;- }- if !self.hold_rasters {- self.receive(ctx, pool);- }- if !self.last_queue.is_empty() {- ctx.request_repaint_after(std::time::Duration::from_millis(30));- }- }-- /// Pull a bounded batch of current results into textures. Demand is committed first, so- /// offscreen results and obsolete scale/configuration tags never allocate a ColorImage.- pub fn receive(&mut self, ctx: &egui::Context, pool: &RenderPool) {- let budget = if pool.is_inline() { 1 } else { RESULTS_PER_FRAME };- let mut uploaded = 0usize;- #[cfg(not(target_arch = "wasm32"))]- let started = std::time::Instant::now();- for _ in 0..budget {- let Some(r) = pool.try_recv() else { break };- uploaded = uploaded.saturating_add(self.receive_result(ctx, r));- // One whole-page upload may exceed the frame allowance; it must still progress.- if uploaded >= UPLOAD_BYTES_PER_FRAME {- break;- }- #[cfg(not(target_arch = "wasm32"))]- if started.elapsed() >= std::time::Duration::from_millis(4) {- break;- }- }- }-- fn receive_result(&mut self, ctx: &egui::Context, r: pdfcraft_render::RenderedPage) -> usize {- if !self.last_queue.contains(&r.request) {- return 0;- }- ctx.request_repaint();- if r.request.kind == RequestKind::Text {- match r.text {- Some(t) => {- self.texts.insert(r.request.page, t);- self.refresh_find_page(r.request.page);- }- None => {- log::warn!("page {} text: {}", r.request.page + 1, r.error.unwrap_or_default());- self.text_failed.insert(r.request.page);- if let Some(f) = self.find.as_mut() {- let previous = f.current.and_then(|c| f.matches.get(c).cloned());- let follow = f.follow_page(self.current);- f.matches.retain(|(p, _)| *p != r.request.page);- match follow {- // An automatic choice keeps following its anchor; a failure never- // flashes, so the view stays exactly where it was.- Follow::Active(from) => f.current = f.first_at_or_after(from),- Follow::Ended | Follow::Never => {- let preserved = previous.as_ref().and_then(|k| f.matches.iter().position(|m| m == k));- f.current = preserved.or_else(|| f.first_at_or_after(self.current));- }- }- }- }- }- return 0;- }- if let Some(e) = r.error {- log::warn!("page {}: {e}", r.request.page + 1);- self.errors.insert(r.request.page, e);- return 0;- }- // Even current demand may have been sized with obsolete geometry or a different- // device limit. Check before cache eviction, conversion and every upload path.- let max_side = ctx.input(|i| i.max_texture_side);- if r.width == 0 || r.height == 0 || r.width as usize > max_side || r.height as usize > max_side {- return 0;- }- // Remember heavy pages: only these get the zoom/pan settle holds, so fast pages- // never pay added latency. Stale entries die with the tiles on edits.- if r.millis >= SLOW_MILLIS {- self.slow_pages.insert(r.request.page);- }- let page = r.request.page;- let bytes = rgba_bytes(r.width as usize, r.height as usize);- if bytes != r.rgba.len() || !self.admit_texture(r.request, bytes) {- return 0;- }- // The length was checked above, so the renderer's buffer becomes the texture data as is.- let img = texture_image([r.width as usize, r.height as usize], r.rgba);- if let Some(t) = r.request.tile {- let key = (page, r.request.tag, t.x, t.y);- let tex = ctx.load_texture(format!("tile-{:?}-{page}-{}-{}", self.id, t.x, t.y), img, TextureOptions::LINEAR);- self.tiles.insert(key, tex);- self.stale_tiles.remove(&key);- if !self.stale_tiles.iter().any(|k| k.0 == page) {- self.forms.unbaked.retain(|(_, p)| *p != page);- self.comments.page_rendered(page);- }- if !self.page_out_of_date(page) {- self.text_background.page_received(page);- }- } else if r.request.tag & PRINT_TAG != 0 {- let tex = ctx.load_texture(- format!("print-{:?}-{page}", self.id),- if r.request.tag & GRAYSCALE_TAG != 0 { grayscale(img) } else { img },- TextureOptions::LINEAR,- );- self.print_pages.insert(page, (r.request.tag, tex));- } else if r.request.tag & GRID_TAG != 0 {- let tex = ctx.load_texture(format!("grid-{:?}-{page}", self.id), img, TextureOptions::LINEAR);- self.grid_pages.insert(page, (r.width, tex));- } else if r.request.tag & THUMB_TAG != 0 {- let tex = ctx.load_texture(format!("thumb-{:?}-{page}", self.id), img, TextureOptions::LINEAR);- self.thumbs.insert(page, PageTex { tag: r.request.tag, tex });- self.stale_thumbs.remove(&page);- } else {- let tex = ctx.load_texture(format!("page-{:?}-{page}", self.id), img, TextureOptions::LINEAR);- self.pages.insert(page, PageTex { tag: r.request.tag, tex });- self.signature_drag.page_received(page);- self.move_background.page_received(page);- if !self.page_out_of_date(page) {- self.text_background.page_received(page);- }- self.comments.page_rendered(page);- self.waiting_since.remove(&page);- if !self.stale_tiles.iter().any(|k| k.0 == page) {- self.forms.unbaked.retain(|(_, p)| *p != page);- }- }- bytes- }-- /// Check real dimensions before conversion, including stale textures kept during edits.- /// Dropping an old handle releases its backend allocation after the current frame.- fn admit_texture(&mut self, req: RenderRequest, bytes: usize) -> bool {- // An on-screen page or tile is always taken (the viewport bounds it): it may evict- // off-screen rasters but never another on-screen one, and is never refused.- let visible = req.tag & THUMB_TAG == 0 && self.frame_visible.contains(&req.page);- // Organize-grid renders are bounded by the cells in view (organize_grid). Print- // previews are the sheets around the one on screen.- if req.tag & (GRID_TAG | PRINT_TAG) != 0 {- return true;- }- if let Some(t) = req.tile {- let key = (req.page, req.tag, t.x, t.y);- self.tiles.remove(&key);- let retained = self.tiles.values().fold(0usize, |n, tex| n.saturating_add(texture_bytes(tex)));- visible || bytes <= TILE_BYTES.saturating_sub(retained)- } else {- let thumb = req.tag & THUMB_TAG != 0;- let (cache, limit) = if thumb { (&mut self.thumbs, THUMB_BYTES) } else { (&mut self.pages, PAGE_BYTES) };- cache.remove(&req.page);- let mut retained = cache.values().fold(0usize, |n, p| n.saturating_add(texture_bytes(&p.tex)));- // A zoom/DPI change can temporarily retain larger stale images than the new- // demand estimates. Evict those first, then let the current demand refill them.- let on_screen = |p: &usize| !thumb && self.frame_visible.contains(p);- while retained.saturating_add(bytes) > limit {- let Some(page) = cache.keys().copied().filter(|p| !on_screen(p)).max_by_key(|p| p.abs_diff(self.current)) else { break };- if let Some(old) = cache.remove(&page) {- retained = retained.saturating_sub(texture_bytes(&old.tex));- }- }- visible || bytes <= limit.saturating_sub(retained)- }- }-- /// The first page of the two-page spread page `c` is in: spreads are [0, 1], [2, 3], … or,- /// with a cover page, [0], [1, 2], [3, 4], ….- fn spread_first(&self, c: usize) -> usize {- if self.cover { c.saturating_sub((c + 1) % 2) } else { c - c % 2 }- }-- fn fit_zoom(&mut self, info: &DocInfo) {- let largest = |side: fn((f32, f32)) -> f32| info.pages.iter().map(|p| side(self.display_size(p))).fold(1.0, f32::max);- let max_w = largest(|s| s.0);- // A single page shown on its own fits that page, and full screen in two-page view fits- // the spread it shows (review on #2070). Every other display (scrolling, or two-page- // view in the window) fits its largest page, so the zoom holds still while pages of- // other sizes scroll or page past.- let (w, h) = if self.layout == PageLayout::Single && !self.continuous {- info.pages.get(self.current).map_or_else(|| (max_w, largest(|s| s.1)), |p| self.display_size(p))- } else if self.presentation.is_some() && self.layout == PageLayout::TwoUp && !self.continuous {- let first = self.spread_first(self.current);- let last = if self.cover && first == 0 { 0 } else { first.saturating_add(1) };- let spread: Vec<(f32, f32)> = info.pages.iter().skip(first).take(last - first + 1).map(|p| self.display_size(p)).collect();- if spread.is_empty() {- (max_w, largest(|s| s.1))- } else {- (spread.iter().map(|s| s.0).fold(1.0, f32::max), spread.iter().map(|s| s.1).fold(1.0, f32::max))- }- } else {- (max_w, largest(|s| s.1))- };- let avail_w = (self.viewport_w - 2.0 * SIDE).max(100.0);- let per_row = if self.layout == PageLayout::TwoUp { 2.0 } else { 1.0 };- match self.fit {- Fit::Width => self.zoom = (avail_w - self.page_gap() * (per_row - 1.0)) / (w * PT * per_row),- Fit::Page => {- let zw = (avail_w - self.page_gap() * (per_row - 1.0)) / (w * PT * per_row);- let zh = (self.viewport_h - 2.0 * MARGIN) / (h * PT);- self.zoom = zw.min(zh);- }- Fit::Height => self.zoom = (self.viewport_h - 2.0 * MARGIN) / (h * PT),- Fit::None => {}- }- self.zoom = self.zoom.clamp(0.08, 64.0);- }-- /// Width of the scroll content. Single-page view sizes it to the page it shows, so a- /// wider page elsewhere in the document can't push the shown one off-centre.- fn content_width(&self, info: &DocInfo, avail_w: f32) -> f32 {- let single = (self.layout == PageLayout::Single && !self.continuous).then(|| self.current.min(info.pages.len().saturating_sub(1)));- let shown = info.pages.iter().enumerate().filter(|&(i, _)| single.is_none_or(|c| c == i));- let max_w = shown.map(|(_, p)| self.display_size(p).0).fold(0.0, f32::max);- let per_row = if self.layout == PageLayout::TwoUp { 2.0 } else { 1.0 };- (max_w * self.zoom * PT * per_row + 2.0 * SIDE).max(avail_w)- }-- /// Page rects in content coordinates (origin at the scroll content's top-left).- fn layout(&self, info: &DocInfo, content_w: f32, ppp: f32) -> Vec<Rect> {- let s = self.zoom * PT;- let gap = self.page_gap();- let page_size = |p: &pdfcraft_render::PageInfo| {- let (w, h) = self.display_size(p);- if self.show_page_gaps {- vec2(w * s, h * s)- } else {- // Match the raster's whole physical pixels. Snapping each page's origin- // independently with fractional sizes would leave hairline seams.- vec2(device_pixels(w, s * ppp) as f32 / ppp, device_pixels(h, s * ppp) as f32 / ppp)- }- };- let mut rects = Vec::with_capacity(info.pages.len());- let mut y = MARGIN;- match self.layout {- PageLayout::Single => {- for p in &info.pages {- let size = page_size(p);- rects.push(Rect::from_min_size(pos2(((content_w - size.x) / 2.0).max(SIDE), y), size));- y += size.y + gap;- }- }- PageLayout::TwoUp => {- // With a cover page, the first page sits alone on the right.- let rows: Vec<&[pdfcraft_render::PageInfo]> = if self.cover && !info.pages.is_empty() {- std::iter::once(&info.pages[..1]).chain(info.pages[1..].chunks(2)).collect()- } else {- info.pages.chunks(2).collect()- };- for (ri, pair) in rows.into_iter().enumerate() {- let sizes: Vec<Vec2> = pair.iter().map(page_size).collect();- let row_w: f32 = sizes.iter().map(|v| v.x).sum::<f32>() + gap * (sizes.len() as f32 - 1.0);- let row_h = sizes.iter().map(|v| v.y).fold(0.0, f32::max);- let mut x = if self.cover && ri == 0 { (content_w / 2.0 + gap / 2.0).max(SIDE) } else { ((content_w - row_w) / 2.0).max(SIDE) };- for size in sizes {- rects.push(Rect::from_min_size(pos2(x, y + (row_h - size.y) / 2.0), size));- x += size.x + gap;- }- y += row_h + gap;- }- }- }- rects- }-- fn render_scale(&self, ppp: f32) -> f32 {- // Exactly the device scale: a raster at any other scale is resampled on screen, which- // blurs every line and glyph (#260).- self.zoom * PT * ppp- }-- /// Set whether the print preview rasters become luminance before upload. Toggling it drops- /// the colour previews: new requests carry the grayscale tag, so stale ones are replaced.- pub(crate) fn set_print_grayscale(&mut self, grayscale: bool) {- if self.grayscale != grayscale {- self.grayscale = grayscale;- self.print_pages.clear();- }- }-- /// Queue sharp rasters for the print preview. Pages that leave the nearby sheets are dropped.- /// Previews render with reading colours off (the request's tag tells the renderer): they must- /// match the printout, which is imposed from the uncoloured document.- pub(crate) fn queue_print_previews(&mut self, pages: &[(usize, f32)]) {- self.print_pages.retain(|page, _| pages.iter().any(|(p, _)| p == page));- for &(page, scale) in pages {- if self.errors.contains_key(&page) || !scale.is_finite() || scale <= 0.0 {- continue;- }- let tag = scale_tag(scale) | PRINT_TAG | if self.grayscale { GRAYSCALE_TAG } else { 0 };- let fresh = self.print_pages.get(&page).is_some_and(|(have, _)| *have == tag);- if !fresh {- self.frame_queue.push(RenderRequest { page, kind: RequestKind::Pixels, tile: None, scale, tag, preview: false });- }- }- }-}--/// The hover popup for an annotation. Replies and Fill & Sign marks (typed text, checks, signatures)-/// show none: they are page content being edited, not comments.-fn annotation_hover_text(a: &pdfcraft_render::Annotation) -> Option<String> {- if a.is_reply() || a.fill_sign {- return None;- }- let who = a.author.clone().unwrap_or_else(|| a.subtype.clone());- let body = a.contents.clone().unwrap_or_default();- Some(if body.is_empty() { who } else { format!("{who}\n{body}") })-}--/// The scroll offset that puts `point` (content coordinates) at `rel` in the viewport, kept within-/// the content as egui keeps it. egui clamps only after drawing, so an offset past the end showed-/// the page misplaced for a frame and then jumped (zooming out beside a page that fits).-fn anchored_scroll(point: Pos2, rel: Vec2, content: Vec2, viewport: Vec2) -> Vec2 {- let max = vec2((content.x - viewport.x).max(0.0), (content.y - viewport.y).max(0.0));- vec2((point.x - rel.x).clamp(0.0, max.x), (point.y - rel.y).clamp(0.0, max.y))-}--/// The request tag for a raster at `scale`: equal tags mean the same scale (to 1/65536).-fn scale_tag(scale: f32) -> u64 {- (f64::from(scale) * 65536.0).round() as u64-}--/// The scale of a raster tagged by [`scale_tag`].-fn tag_scale(tag: u64) -> f32 {- (tag as f64 / 65536.0) as f32-}--/// Device-pixel side of a page tile at `scale` for a page `page_max_px` device pixels on-/// its long side. Each tile costs a full page interpret, so tiles grow with the zoom and-/// with the page: a zoomed viewport, or a giant sheet shown whole, is covered by a few-/// large tiles instead of dozens of small ones. Bounded by the render backend (tile sides-/// above 4096 are clamped there) and kept granular at ordinary zooms.-fn tile_side(scale: f32, page_max_px: u32) -> u32 {- if !scale.is_finite() || scale <= 0.0 {- return TILE;- }- let by_zoom = (TILE as f32 * (scale / 6.0)).clamp(TILE as f32, 4096.0) as u32;- // At most four tiles along the long side, so a giant sheet needs a handful of- // interprets instead of dozens.- by_zoom.max(page_max_px.div_ceil(4).min(4096))-}--/// Tiles of earlier zooms kept for a page while its current tiles are rendered.-const OLD_TILES: usize = 64;--/// A page whose raster took at least this long is heavy: zoom/pan holds apply to it,-/// so gestures stay on stretched surfaces instead of queueing full-page interprets.-const SLOW_MILLIS: u32 = 500;--/// `r` moved so its corner lies on a whole physical pixel, so that a raster drawn from there-/// maps texel for texel onto the screen.-fn snap_to_pixels(r: Rect, ppp: f32) -> Rect {- let snap = |v: f32| (v * ppp).round() / ppp;- Rect::from_min_size(pos2(snap(r.min.x), snap(r.min.y)), r.size())-}--/// Maps between a page's coordinate spaces and the screen, including view rotation.-///-/// *View space* is the page as rendered (points, y down, the document's own `/Rotate` applied);-/// normalised page coordinates `(u, v)` are view space divided by the page size. The view-/// rotation (View ▸ Rotate View) turns the page clockwise on screen by `rot` degrees.-#[derive(Clone, Copy)]-pub struct PageXform {- /// The page's rectangle on screen (already rotated, so width/height may be swapped).- pub rect: Rect,- pub rot: u16,- /// Page size in view space (unrotated by the view).- pub pw: f32,- pub ph: f32,-}--impl PageXform {- /// Screen pixels per page point. The view's rotation swaps the rectangle's sides, so a page- /// turned a quarter shows its width down the screen.- pub(crate) fn zoom(&self) -> f32 {- let across = if self.rot % 180 == 90 { self.rect.height() } else { self.rect.width() };- across / self.pw.max(1.0)- }-- /// Draw an image in the PDF user-space `rect` as a custom stamp's appearance draws it: turned- /// back by `turn` (the page /Rotate it was placed for), so with the page's own rotation it- /// reads upright as displayed.- pub(crate) fn paint_user_image(- &self,- painter: &egui::Painter,- tex: egui::TextureId,- p: &pdfcraft_render::PageInfo,- rect: [f64; 4],- turn: i64,- color: Color32,- ) {- let mut mesh = egui::Mesh::with_texture(tex);- let (w, h) = (rect[2] - rect[0], rect[3] - rect[1]);- let (shown_w, shown_h) = if turn % 180 == 0 { (w, h) } else { (h, w) };- let [a, b, c, d, e, f] = pdfcraft_model::view_matrix_for(turn, rect);- for (u, v) in [(0.0_f32, 0.0_f32), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)] {- // The texture's (u, v), from its top-left, in the picture's upright frame, then in user space.- let (dx, dy) = (f64::from(u) * shown_w, f64::from(1.0 - v) * shown_h);- let (x, y) = (a * dx + c * dy + e, b * dx + d * dy + f);- let q = p.user_to_view(x as f32, y as f32);- mesh.vertices.push(egui::epaint::Vertex { pos: self.norm_to_screen(q[0] / self.pw, q[1] / self.ph), uv: pos2(u, v), color });- }- mesh.add_triangle(0, 1, 2);- mesh.add_triangle(0, 2, 3);- painter.add(egui::Shape::mesh(mesh));- }- pub fn norm_to_screen(&self, u: f32, v: f32) -> Pos2 {- let (a, b) = match self.rot {- 90 => (1.0 - v, u),- 180 => (1.0 - u, 1.0 - v),- 270 => (v, 1.0 - u),- _ => (u, v),- };- pos2(self.rect.left() + a * self.rect.width(), self.rect.top() + b * self.rect.height())- }-- pub fn screen_to_norm(&self, p: Pos2) -> (f32, f32) {- let (a, b) = ((p.x - self.rect.left()) / self.rect.width().max(1e-3), (p.y - self.rect.top()) / self.rect.height().max(1e-3));- match self.rot {- 90 => (b, 1.0 - a),- 180 => (1.0 - a, 1.0 - b),- 270 => (1.0 - b, a),- _ => (a, b),- }- }-- /// Screen point → view space (points).- pub fn screen_to_view(&self, p: Pos2) -> (f32, f32) {- let (u, v) = self.screen_to_norm(p);- (u * self.pw, v * self.ph)- }-- /// A view-space rect [x0, y0, x1, y1] → screen rect.- pub fn view_rect(&self, g: [f32; 4]) -> Rect {- Rect::from_two_pos(self.norm_to_screen(g[0] / self.pw, g[1] / self.ph), self.norm_to_screen(g[2] / self.pw, g[3] / self.ph))- }-- /// A PDF user-space rect (crop box, document `/Rotate`) → screen rect.- pub fn user_rect(&self, info: &DocInfo, page: usize, r: [f32; 4]) -> Rect {- let p = &info.pages[page];- let [cx0, cy0, cx1, cy1] = p.crop;- let (cw, ch) = ((cx1 - cx0).max(1.0), (cy1 - cy0).max(1.0));- let norm = |x: f32, y: f32| -> (f32, f32) {- let (u, v) = ((x - cx0) / cw, (cy1 - y) / ch);- match p.rotation {- 90 => (1.0 - v, u),- 180 => (1.0 - u, 1.0 - v),- 270 => (v, 1.0 - u),- _ => (u, v),- }- };- let (a, b) = (norm(r[0], r[1]), norm(r[2], r[3]));- Rect::from_two_pos(self.norm_to_screen(a.0, a.1), self.norm_to_screen(b.0, b.1))- }-- /// This transform resized to a raster of `px` device pixels (width, height before the view- /// rotation), so each of its texels covers one screen pixel. The rectangle's corner must- /// already be on a whole pixel ([`snap_to_pixels`]).- fn texel_aligned(&self, px: [usize; 2], ppp: f32) -> PageXform {- let (w, h) = (px[0] as f32 / ppp, px[1] as f32 / ppp);- let size = if self.rot % 180 == 90 { vec2(h, w) } else { vec2(w, h) };- PageXform { rect: Rect::from_min_size(self.rect.min, size), ..*self }- }-- /// Draw a texture covering the normalised page region, rotated with the view.- pub fn paint_image(&self, painter: &egui::Painter, tex: egui::TextureId, u0: f32, v0: f32, u1: f32, v1: f32) {- let mut mesh = egui::Mesh::with_texture(tex);- let corners = [(u0, v0, 0.0, 0.0), (u1, v0, 1.0, 0.0), (u1, v1, 1.0, 1.0), (u0, v1, 0.0, 1.0)];- for (u, v, tu, tv) in corners {- mesh.vertices.push(egui::epaint::Vertex { pos: self.norm_to_screen(u, v), uv: pos2(tu, tv), color: Color32::WHITE });- }- mesh.add_triangle(0, 1, 2);- mesh.add_triangle(0, 2, 3);- painter.add(egui::Shape::mesh(mesh));- }-}--pub fn shortcuts(view: &mut DocView, ctx: &egui::Context, speed: crate::scroll_speed::ScrollSpeed) {- use egui::{Key, KeyboardShortcut, Modifiers};- if ctx.input_mut(|i| i.consume_shortcut(&KeyboardShortcut::new(Modifiers::COMMAND, Key::F))) {- view.open_find();- }- let cmd = |k| KeyboardShortcut::new(Modifiers::COMMAND, k);- let pressed = |s: KeyboardShortcut| ctx.input_mut(|i| i.consume_shortcut(&s));- // ⌘G / ⇧⌘G step through the matches from the find field too, as in Acrobat and Preview- // (#2669): ahead of the text-input check, but only while there is a search to step.- if view.find.is_some() {- if pressed(KeyboardShortcut::new(Modifiers::COMMAND | Modifiers::SHIFT, Key::G)) {- view.find_step(false);- } else if pressed(cmd(Key::G)) {- view.find_step(true);- }- }- // A focused check box or radio button holds egui's keyboard focus only for Space, and a- // radio button for the arrows that move within its group: the other page keys still work.- let form_box = view.forms.keys.filter(|(id, _)| ctx.memory(|m| m.focused()) == Some(*id));- if ctx.egui_wants_keyboard_input() && form_box.is_none() {- return;- }- let arrows = !form_box.is_some_and(|(_, radio)| radio);- // Rotation first: egui matches ⌘+ loosely with respect to Shift.- if pressed(KeyboardShortcut::new(Modifiers::COMMAND | Modifiers::SHIFT, Key::Plus))- || pressed(KeyboardShortcut::new(Modifiers::COMMAND | Modifiers::SHIFT, Key::Equals))- {- view.rotate_view(true);- }- if pressed(KeyboardShortcut::new(Modifiers::COMMAND | Modifiers::SHIFT, Key::Minus)) {- view.rotate_view(false);- }- // In the page grid ⌘+ / ⌘− / ⌘0 size its pages instead (looking is always allowed).- let (zoom_in, zoom_out, zoom_reset) = (pressed(cmd(Key::Plus)) || pressed(cmd(Key::Equals)), pressed(cmd(Key::Minus)), pressed(cmd(Key::Num0)));- if view.organize {- if zoom_in {- view.grid_zoom_request = Some(view.grid_zoom * GRID_ZOOM_STEP);- }- if zoom_out {- view.grid_zoom_request = Some(view.grid_zoom / GRID_ZOOM_STEP);- }- if zoom_reset {- view.grid_zoom_request = Some(1.0);- }- } else {- if zoom_in {- view.zoom_step(true);- }- if zoom_out {- view.zoom_step(false);- }- if zoom_reset {- view.fit = Fit::Page;- view.goto = Some((view.current, 0.0));- }- }- if pressed(cmd(Key::Num1)) {- view.set_zoom(1.0);- }- if pressed(cmd(Key::Num2)) {- view.fit = Fit::Width;- view.goto = Some((view.current, 0.0));- }- if pressed(cmd(Key::OpenBracket)) {- view.view_history(false);- }- if pressed(cmd(Key::CloseBracket)) {- view.view_history(true);- }- let key = |k| (arrows || !matches!(k, Key::ArrowLeft | Key::ArrowRight | Key::ArrowUp | Key::ArrowDown)) && ctx.input(|i| i.key_pressed(k));- // An open menu takes Escape first and closes; the selection stays for the next one (#3535).- if key(Key::Escape) && !egui::Popup::is_any_open(ctx) {- if view.camera.is_some() || view.camera_done.is_some() {- view.pending_action = Some(ViewAction::CancelCamera);- } else if view.selection.is_some() || view.all_text {- view.selection = None;- view.all_text = false;- } else {- view.find = None;- }- }- if key(Key::Home) {- view.go_to_page(0);- }- if key(Key::End) {- view.go_to_page(usize::MAX);- }- // Full screen: Space and Enter go forward a page and Backspace back, as in Acrobat (the- // arrows and Page Up / Page Down already turn pages where nothing scrolls, below).- if view.presentation.is_some() {- if key(Key::Space) || key(Key::Enter) {- view.step_page(true);- }- if key(Key::Backspace) {- view.step_page(false);- }- }- // As in Acrobat: → / ← go to the next / previous page in every layout (#185), and so do- // ⌘Page Down / ⌘Page Up, or plain Page Down / Page Up in single-page view.- let command = ctx.input(|i| i.modifiers.command);- let scrolls = view.continuous;- if key(Key::ArrowRight) || (key(Key::PageDown) && (command || !scrolls)) {- view.step_page(true);- }- if key(Key::ArrowLeft) || (key(Key::PageUp) && (command || !scrolls)) {- view.step_page(false);- }- // ↓ / ↑ scroll a line, and Page Down / Page Up a screen where the pages scroll. In- // single-page view, ↓ / ↑ turn the page once there is nothing left to scroll that way, as- // the wheel does (#273): always on a page that fits.- // The Scroll speed preference sets how far ↓ / ↑ go as well as the wheel (#985); Page Down /- // Page Up keep a screen.- if !command {- let line = KEY_SCROLL_LINE * speed.factor();- let screen = (view.viewport_h - KEY_SCROLL_LINE).max(KEY_SCROLL_LINE);- let steps = [(Key::ArrowDown, line), (Key::ArrowUp, -line), (Key::PageDown, screen), (Key::PageUp, -screen)];- for (k, by) in steps {- let arrow = matches!(k, Key::ArrowDown | Key::ArrowUp);- if !key(k) || !(scrolls || arrow) {- continue;- }- let forward = k == Key::ArrowDown;- // Only an up-to-date view counts: the page drawn is the current one, with no jump pending.- let at_end = !scrolls- && view.goto.is_none()- && view.single_edges.is_some_and(|(page, top, bottom)| page == view.current && if forward { bottom } else { top });- if at_end {- let before = view.current;- view.step_page(forward);- if !forward && view.current != before {- // Going back up lands on the bottom of the previous page.- view.goto = Some((view.current, 1.0));- }- view.single_edges = None;- } else {- view.key_scroll += by;- }- }- }-}--/// How far ↓ / ↑ scroll at Normal speed (Scroll speed halves or doubles it). Page Down / Page Up-/// keep this much of the previous screen in view.-const KEY_SCROLL_LINE: f32 = 40.0;-/// Suppression window for egui's eased copy of point input.-///-/// egui 0.36.2 drains `WheelState::after_events` tail deltas by 90% per 0.1 s.-const SUPPRESS_SECS: f64 = 0.25;-/// Short rolling extension while egui still has an unprocessed wheel tail.-const SUPPRESS_TAIL_SECS: f64 = 0.05;--// Keep the viewer's scroll identity tied to the document instead of its parent UI.-fn page_scroll<R>(- ui: &mut egui::Ui,- scroll: egui::ScrollArea,- id: egui::Id,- draw: impl FnOnce(&mut egui::Ui, egui::Rect) -> R,-) -> egui::scroll_area::ScrollAreaOutput<R> {- ui.scope_builder(egui::UiBuilder::new().scope_id(id), |ui| scroll.show_viewport(ui, draw)).inner-}--/// Draws the document tab at `index`: its notice bars, then its pages (or the Organize grid) in a-/// scroll area with this frame's zoom, scrolling, tool input, overlays and render requests.-pub fn document_area(app: &mut PdfCraftApp, index: usize, ui: &mut egui::Ui) {- let t = Tokens::get(ui.ctx());- // Keyboard scrolling applies to this frame's page view only, never later.- let key_scroll = std::mem::take(&mut app.views[index].key_scroll);- if key_scroll != 0.0 {- app.views[index].end_find_following();- }- // The Search panel closed: its search moves to the find bar.- let search_open = app.right == Some(crate::RightPanel::Search);- if let Some(f) = app.views[index].find.as_mut()- && f.in_panel- && !search_open- {- f.in_panel = false;- }- // The snapshot notice bar's Close was clicked: close here, where no document borrow is- // held. The tab is looked up by id: indices may have shifted since the click, and the- // flag rides its own view, so a stale flag can never close the wrong tab.- let pending = app.views.get(index).filter(|v| v.close_requested).map(|v| v.id).and_then(|id| app.views.iter().position(|v| v.id == id));- if let Some(i) = pending {- app.views[i].close_requested = false;- if app.has_unsaved_work(i) {- app.close_request = Some(crate::CloseRequest::Tab(app.views[i].id));- } else {- app.close_tab(i);- }- return;- }- let Some(doc) = app.session.get(app.views[index].id) else { return };- let info = &doc.info;- let paper = app.session.reading_colors(app.views[index].id).and_then(|c| c.params).map_or(Color32::WHITE, |p| {- let [r, g, b] = p.background;- Color32::from_rgb(r, g, b)- });- if info.pages.is_empty() {- app.views[index].auto_scroll.cancel();- ui.centered_and_justified(|ui| ui.label(tl!("This document has no pages.")));- return;- }- // The print dialog queues its own rasters later in the frame. Closing it drops them.- if app.dialog != Some(crate::Dialog::Print) {- app.views[index].print_pages.clear();- }- // The Prepare a form panel is open (or a field tool is picked): fields are edited, not filled.- let preparing = app.is_preparing();- // Prepare a form ▸ Calculation order: the order's steps and links on the page.- let calc_order = preparing && app.left_open && app.left == crate::LeftPanel::CalculationOrder;- // Edit a PDF: added text and images can be selected, moved and edited.- let editing_content =- (app.left_open && app.left == crate::LeftPanel::Tool("edit")) || matches!(app.quick_tool, QuickTool::AddText | QuickTool::EditText);- let text_style = app.text_style.clone();- let show_secured_notice = app.show_secured_notice;- let view = &mut app.views[index];- // Opened without the owner password and something is restricted. The notice says so unless- // the user turned it off (#4035): the restrictions themselves, and Document Properties ▸- // Security, stay as they are.- let secured = show_secured_notice && doc.security_summary().is_some_and(|s| !(s.owner || (s.permissions.modify() && s.permissions.assemble())));- let repaired = !doc.repair_log().is_empty();- match notices(view, doc, secured, repaired, crate::sign_ui::banner(&doc.signatures), ui, &t) {- #[cfg(not(target_arch = "wasm32"))]- Some(Notice::Reload) => app.watch.reload_request = Some(view.id),- #[cfg(target_arch = "wasm32")]- Some(Notice::Reload) => {}- Some(Notice::Repairs) => app.dialog = Some(crate::Dialog::Properties(crate::PropsTab::Advanced)),- Some(Notice::Security) => app.dialog = Some(crate::Dialog::Properties(crate::PropsTab::Security)),- Some(Notice::Unlock) => app.unlock_prompt = Some(crate::UnlockPrompt::new(doc, None)),- // Flags the view: the tab closes at the top of the next frame, where no document- // borrow is held.- Some(Notice::Close) => {- if let Some(view) = app.views.get_mut(index) {- view.close_requested = true;- }- }- Some(Notice::Signatures) => app.right = Some(RightPanel::Signatures),- Some(Notice::FieldHighlights(on)) => app.view_defaults.highlight_fields = on,- Some(Notice::Console) => app.dialog = Some(crate::Dialog::JsConsole),- // Back on in Preferences ▸ General.- Some(Notice::HideSecured) => app.show_secured_notice = false,- None => {}- }- // No dialog, close prompt or palette over the page: only then does page input count.- let modal = app.modal_open();- let unobstructed = !modal && !app.palette_open;- let organize_zoom = app.organize_zoom;- let view = &mut app.views[index];- if view.organize {- // One remembered grid size for every document, kept in the settings.- view.set_grid_zoom(organize_zoom);- organize_grid(view, info, doc.allows_assembly(), doc.dirty, unobstructed, ui, &t);- app.organize_zoom = view.grid_zoom();- return;- }-- let avail = ui.available_rect_before_wrap();- view.viewport_w = avail.width();- view.viewport_h = avail.height();- let old_zoom = view.zoom;- view.fit_zoom(info);- if view.shown && view.zoom_anchor.is_none() && view.goto.is_none() && view.goto_point.is_none() && (view.zoom - old_zoom).abs() > 1e-4 {- let prev_viewport = view.viewport_screen;- let top_y = prev_viewport.min.y;- let anchor = view- .screen_rects- .iter()- .find(|(_, r)| r.min.y <= top_y && r.max.y > top_y)- .map(|(p, r)| {- let fy = if r.height() > 0.0 { ((top_y - r.min.y) / r.height()).clamp(0.0, 1.0) } else { 0.0 };- (*p, fy, 0.0f32)- })- .or_else(|| view.screen_rects.iter().find(|(_, r)| r.min.y >= top_y).map(|(p, r)| (*p, 0.0f32, (r.min.y - top_y).max(0.0))))- .or_else(|| view.screen_rects.last().map(|(p, r)| (*p, 1.0f32, (r.max.y - top_y).max(0.0))));- if let Some((page, fy, rel_y)) = anchor {- view.zoom_anchor = Some((page, 0.5, fy, vec2(avail.width() / 2.0, rel_y)));- } else {- view.zoom_anchor = Some((view.current, 0.5, 0.0, vec2(avail.width() / 2.0, MARGIN)));- }- }-- // Pinch / ctrl+scroll zoom, anchored on the current page.- let zoom_delta = crate::motion::zoom_delta(ui.ctx());- // Exclude the previous frame's scrollbar tracks from gesture activation.- let navigation_rect = if view.viewport_screen.is_positive() { avail.intersect(view.viewport_screen) } else { avail };- let navigation_enabled = app.dialog.is_none() && app.close_request.is_none() && !app.palette_open && ui.is_enabled() && ui.input(|i| i.focused);- // Full screen: a click on the document goes forward a page and a shift-click back, as in- // Acrobat, unless the click did something else (a link, a word selected). Decided below,- // once the pages have had the click.- let present_click =- view.presentation.is_some() && navigation_enabled && presentation_click(ui, navigation_rect) && app.quick_tool == QuickTool::Select;- // Shift as held now, or as the click's own event carried it (a synthetic click).- let present_back = present_click- && ui.input(|i| {- i.modifiers.shift- || i.events.iter().any(|e| {- matches!(e, egui::Event::PointerButton { button: egui::PointerButton::Primary, pressed: false, modifiers, .. } if modifiers.shift)- })- });- if zoom_delta.is_finite() && zoom_delta > 0.0 && zoom_delta != 1.0 && navigation_enabled && ui.rect_contains_pointer(navigation_rect) {- let z = view.zoom * zoom_delta;- match zoom_anchor(ui) {- Some(p) => view.zoom_at(z, p),- None => view.set_zoom(z),- }- }- view.viewport_screen = avail;- let auto_delta = if unobstructed {- view.auto_scroll.update(ui, avail, false)- } else {- view.auto_scroll.cancel();- Vec2::ZERO- };+ 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.@@ -4571,1416 +2529,125 @@ pub fn document_area(app: &mut PdfCraftApp, index: usize, ui: &mut egui::Ui) {app.quick_tool = tool;app.start_signing(page, Some(rect), None, certify.then_some(2));}- if let Some(field) = app.views[index].sign.field.take() {- let signed = app.session.get(app.views[index].id).is_some_and(|d| d.signatures.iter().any(|s| s.field == field && s.signed));- if signed {- app.right = Some(RightPanel::Signatures);- if !app.sig_expanded.contains(&field) {- app.sig_expanded.push(field);- }- } else {- let page = app.views[index].current;- app.start_signing(page, None, Some(field), None);- }- }- app.quick_tool = tool;- if let Some((page, at)) = app.views[index].comments.attach_at.take() {- app.attach_file_comment(page, at);- }- if let Some((p, i)) = open_props {- app.open_comment_props(p, i);- }- if let Some((p, i)) = app.views[index].comments.default_request.take() {- app.make_comment_default(p, i);- }- if let Some((p, i, open)) = app.views[index].comments.attachment_request.take() {- let doc = app.views[index].id;- app.comment_attachment_action(doc, p, i, open);- }- if let Some((name, w)) = field_props {- app.open_field_props(&name, w);- }- if let Some(FieldMenu::Duplicate(name)) = field_menu {- let pages = app.session.get(app.views[index].id).map_or(1, |d| d.info.pages.len());- app.duplicate_draft = Some(crate::DuplicateDraft { name, all: true, from: 1, to: pages });- app.dialog = Some(crate::Dialog::DuplicateField);- }- if let Some((page, rect)) = app.views[index].links.open_new.take() {- app.open_link_props(page, Some(rect), None);- }- if let Some((page, i)) = app.views[index].links.open_existing.take() {- app.open_link_props(page, None, Some(i));- }- if let Some((page, quads)) = app.views[index].pending_redaction.take() {- let author = app.comment_prefs.author.clone();- app.views[index].pending_edit = Some(if app.quick_tool == QuickTool::Comment(comments::CommentTool::Highlight) {- // An area highlight: a highlight over the box.- let style = app.comment_prefs.style(comments::CommentTool::Highlight);- pdfcraft_engine::Edit::AddAnnotation(pdfcraft_engine::NewAnnotation {- page,- shape: pdfcraft_engine::Shape::TextMarkup { kind: pdfcraft_engine::Markup::Highlight, quads },- style,- contents: String::new(),- author,- })- } else {- app.redact_prefs.mark(page, quads, &author)- });- }- match image_action {- Some(crate::edit_text_ui::ImageAction::Replace(page, index)) => app.replace_page_image_dialog(page, index),- Some(crate::edit_text_ui::ImageAction::Save(page, index)) => app.save_page_image(page, index),- Some(crate::edit_text_ui::ImageAction::Copy(page, index)) => {- app.copy_page_image(page, index);- }- Some(crate::edit_text_ui::ImageAction::CopyFile(page, index)) => app.copy_page_image_file(page, index),- Some(crate::edit_text_ui::ImageAction::Cut(page, image)) => {- app.views[index].image_selection = None;- app.cut_page_image(page, image);- }- Some(crate::edit_text_ui::ImageAction::Redact(page, index)) => app.redact_page_image(page, index),- Some(crate::edit_text_ui::ImageAction::Link(page, index)) => app.link_page_image(page, index),- Some(crate::edit_text_ui::ImageAction::Recognize(page)) => app.recognize_text_on_page(page),- None => {}- }- if let Some(why) = refused {- app.notify_error(why);- }- if open_signature || open_initials {- app.signature_draft = crate::fill_sign::SigDraft::new(open_initials, &app.comment_prefs.author);- app.dialog = Some(crate::Dialog::Signature);- }- if open_boxes {- app.boxes_draft.range = crate::pageboxes::Range::Current;- app.boxes_draft.seeded = None;- app.dialog = Some(crate::Dialog::PageBoxes);- }- if let Some((page, rect)) = open_table {- app.field_table_draft = Some(crate::field_table_ui::FieldTableDraft::new(app.views[index].id, page, rect, &form, generation));- app.dialog = Some(crate::Dialog::FieldTable);- // The window lasts while the form is prepared. Drawn with the tool picked but its panel- // closed, the tool goes back to Select above, so the panel opens to keep it prepared.- app.left = crate::LeftPanel::Tool("form");- app.reveal_tools();- }- if let Some(n) = form_notice {- match n {- crate::forms_ui::FormNotice::Security => app.notify_tr("The document's security settings don't allow filling in form fields"),- crate::forms_ui::FormNotice::ReadOnly(name) => app.notify_fmt("{name} is read-only", &[("name", &name)]),- crate::forms_ui::FormNotice::NoAction(name) => app.notify_fmt("{name} has no action", &[("name", &name)]),- }- }- if let Some((name, action)) = app.views[index].forms.button.take() {- run_button(app, index, &name, action);- }- if copy_selected {- app.execute("edit.copy");- }- // Read mode hides the tools (#2646), and full screen is the page and nothing else (#1459);- // the quick tools come back with the window.- if app.mode != crate::Mode::Read && !app.full_screen {- quick_bar(app, avail, ui);- }- if let Some((source, file, destination)) = remote_open {- app.open_remote_link(source, file, destination);- }-}--#[derive(Clone, Copy)]-enum SelectionAction {- Note,- Markup(comments::CommentTool),- Replace,- Copy,-}--/// Actions on an existing text selection, next to the selected words.-fn selection_actions(- ui: &mut egui::Ui,- viewport: Rect,- view: &mut DocView,- info: &DocInfo,- prefs: &comments::CommentPrefs,- can_comment: bool,- can_copy: bool,-) -> bool {- if ui.input(|input| input.pointer.is_decidedly_dragging()) {- return false;- }- let Some(selection) = view.selection else {- view.actions_dismissed = None;- return false;- };- if view.actions_dismissed == Some(selection) {- return false;- }- let Some(text) = view.texts.get(&selection.page) else { return false };- let Some(xf) = view.page_xform(selection.page) else { return false };- let Some(last) = selection.rects(text).last().copied() else { return false };- let selected = selection.text(text);- if selected.is_empty() {- return false;- }- let rect = xf.view_rect(last);- if !viewport.intersects(rect) {- return false;- }- let x = rect.left().clamp(viewport.left() + 8.0, (viewport.right() - 520.0).max(viewport.left() + 8.0));- let y = if rect.bottom() + 48.0 < viewport.bottom() { rect.bottom() + 6.0 } else { (rect.top() - 44.0).max(viewport.top() + 6.0) };- let mut chosen = None;- egui::Area::new(egui::Id::unique(("text-selection-actions", view.id.0))).order(egui::Order::Foreground).fixed_pos(pos2(x, y)).show(- ui.ctx(),- |ui| {- egui::Frame::popup(ui.style()).show(ui, |ui| {- ui.horizontal(|ui| {- for (label, action) in [- (tl!("Add comment"), SelectionAction::Note),- (tl!("Highlight"), SelectionAction::Markup(comments::CommentTool::Highlight)),- (tl!("Underline"), SelectionAction::Markup(comments::CommentTool::Underline)),- (tl!("Strikethrough"), SelectionAction::Markup(comments::CommentTool::StrikeOut)),- (tl!("Replace text"), SelectionAction::Replace),- ] {- if ui.add_enabled(can_comment, egui::Button::new(label)).clicked() {- chosen = Some(action);- }- }- if ui.add_enabled(can_copy, egui::Button::new(tl!("Copy"))).clicked() {- chosen = Some(SelectionAction::Copy);- }- });- });- },- );- let Some(action) = chosen else { return false };- if let SelectionAction::Copy = action {- // Copying closes the bar but keeps the words selected, for ⌘C or a second action.- view.actions_dismissed = Some(selection);- return true;- }- let Some((page, quads)) = view.selection_quads(info) else { return false };- let last = quads.last().copied().unwrap_or_default();- let at = [last[2].max(last[6]), last[1].max(last[3])];- view.clear_selection();- match action {- SelectionAction::Note | SelectionAction::Replace => {- if matches!(action, SelectionAction::Replace) {- view.comments.replace = Some(quads);- }- view.comments.composer = Some(comments::Composer {- page,- at,- kind: if matches!(action, SelectionAction::Replace) { comments::ComposerKind::Replace } else { comments::ComposerKind::Note },- text: String::new(),- focus: true,- });- }- SelectionAction::Markup(tool) => {- // Every markup button carries a markup tool; anything else adds nothing.- let Some(kind) = tool.markup() else { return false };- view.pending_edit = Some(Edit::AddAnnotation(pdfcraft_engine::NewAnnotation {- page,- shape: pdfcraft_engine::Shape::TextMarkup { kind, quads },- style: prefs.style(tool),- contents: String::new(),- author: prefs.author.clone(),- }));- }- // Copy is dispatched through the app after the view borrow ends.- SelectionAction::Copy => {}- }- false-}--/// Run a push button's action (the ones that need no JavaScript engine).-fn run_button(app: &mut PdfCraftApp, index: usize, name: &str, action: pdfcraft_engine::form_scripts::ButtonAction) {- use pdfcraft_engine::form_scripts::ButtonAction as B;- let pages = app.session.get(app.views[index].id).map_or(0, |d| d.info.pages.len());- match action {- B::Reset { fields, exclude } => {- let all: Vec<String> = app.session.get(app.views[index].id).map(|d| d.form.iter().map(|f| f.name.clone()).collect()).unwrap_or_default();- let listed = |n: &String| fields.iter().any(|f| n == f || n.starts_with(&format!("{f}.")));- let names = match (fields.is_empty(), exclude) {- (true, _) => None,- (false, false) => Some(all.iter().filter(|n| listed(n)).cloned().collect()),- (false, true) => Some(all.iter().filter(|n| !listed(n)).cloned().collect()),- };- app.views[index].forms.focus = None;- app.views[index].pending_edit = Some(pdfcraft_engine::Edit::ResetForm { names });- }- B::Named(n) => match n.as_str() {- "Print" => app.open_print(),- // What PdfCraft's XFA buttons use, and what a script's `execMenuItem("Save")`- // does too: the Save As dialog, so a click never overwrites the file unasked.- "SaveAs" => app.run_command("file.save_as"),- "NextPage" => app.views[index].step_page(true),- "PrevPage" => app.views[index].step_page(false),- "FirstPage" => app.views[index].go_to_page(0),- "LastPage" => app.views[index].go_to_page(pages.saturating_sub(1)),- other => app.notify_fmt("{name}: the {other} action isn't supported yet", &[("name", name), ("other", other)]),- },- B::Uri(u) => app.request_document_url(&u, crate::LinkOrigin::Button),- B::GoTo(p) => app.views[index].go_to_page(p.min(pages.saturating_sub(1))),- B::ShowHide { fields, hide } => {- let listed = |n: &String| fields.iter().any(|f| n == f || n.starts_with(&format!("{f}.")));- // `display.hidden` 1, `display.visible` 0, as a script setting `field.display` would.- let changes: Vec<pdfcraft_engine::FieldChange> = app- .session- .get(app.views[index].id)- .map(|d| d.form.iter().filter(|f| listed(&f.name)).map(|f| f.name.clone()).collect::<Vec<_>>())- .unwrap_or_default()- .into_iter()- .map(|name| pdfcraft_engine::FieldChange {- name,- value: None,- read_only: None,- required: None,- display: Some(if hide { 1 } else { 0 }),- })- .collect();- if !changes.is_empty() {- let label = if hide { "Hide a field" } else { "Show a field" };- app.views[index].pending_edit =- Some(pdfcraft_engine::Edit::Batch { label: label.into(), edits: vec![pdfcraft_engine::Edit::ApplyScriptChanges { changes }] });- }- }- B::SetLayers { changes, preserve_rb } => {- use pdfcraft_engine::form_scripts::LayerOp as Op;- let changes: Vec<(LayerOp, (u32, u16))> = changes- .into_iter()- .map(|(op, ocg)| {- let op = match op {- Op::On => LayerOp::On,- Op::Off => LayerOp::Off,- Op::Toggle => LayerOp::Toggle,- };- (op, ocg)- })- .collect();- set_layers(app, index, &changes, preserve_rb);- }- B::Alert(m) => app.notify(m),- B::Submit(url) => app.notify_fmt(- "{name} submits the form to {url}; PdfCraft doesn't send form data. Save the document to keep your entries.",- &[("name", name), ("url", &url)],- ),- B::ImportIcon => app.choose_field_image(name),- B::Script(js) => {- let id = app.views[index].id;- app.run_button_script(id, name, &js);- }- }-}--/// Run a set-layer-visibility action from a button or link. It changes what is shown, as the-/// Layers panel does (which follows), not the document.-fn set_layers(app: &mut PdfCraftApp, index: usize, changes: &[(LayerOp, (u32, u16))], preserve_rb: bool) {- let id = app.views[index].id;- if app.session.set_layer_state(id, changes, preserve_rb) {- app.views[index].invalidate_content();- }-}--/// Where a pinch or ⌘-scroll zooms the view about: the pointer, wherever it is over the view. Not-/// page input: it is read before the pages' widget exists, once `rect_contains_pointer` has found-/// the view under the pointer.-fn zoom_anchor(ui: &egui::Ui) -> Option<Pos2> {- ui.input(|i| i.pointer.hover_pos())-}--/// The pointer and frame time that scroll the view while a comment is drawn. Not page input: it is-/// read before the pages' widget exists, and the pointer may be past the view's edge.-fn drawing_edge_pointer(ui: &egui::Ui) -> (Option<Pos2>, f32) {- ui.input(|i| (i.pointer.latest_pos(), i.stable_dt))-}--/// A press anywhere, or a key, stops the touchpad's glide (#531).-fn glide_interrupted(ui: &egui::Ui) -> bool {- ui.input(|i| i.pointer.any_pressed() || i.events.iter().any(|e| matches!(e, egui::Event::Key { pressed: true, .. })))-}--/// Full screen's click on the document, which turns the page: a primary click this frame with the-/// view on top under it in `area`. Not page input: it is read before the pages' widget exists, and-/// the turn waits until the pages have had the click.-fn presentation_click(ui: &egui::Ui, area: Rect) -> bool {- ui.rect_contains_pointer(area) && ui.input(|i| i.pointer.primary_clicked())-}--/// Whether `p` lies in the bottom-left quadrant of `area`, where the page size shows (#1855).-fn in_size_hint_zone(area: Rect, p: Pos2) -> bool {- p.x >= area.min.x && p.x < area.center().x && p.y > area.center().y && p.y <= area.max.y-}--/// The current page's size, floating at the bottom-left of the document area while the pointer is-/// in that quadrant, as Acrobat does. Same formatter and unit as Document Properties.-fn page_size_hint(view: &DocView, info: &DocInfo, units: crate::units::Unit, area: Rect, unobstructed: bool, ui: &mut egui::Ui, t: &Tokens) {- let Some(page) = info.pages.get(view.current) else { return };- let inside = unobstructed && ui.input(|i| i.pointer.hover_pos()).is_some_and(|p| in_size_hint_zone(area, p));- if !inside {- return;- }- let text = units.size(f64::from(page.width), f64::from(page.height));- egui::Area::new(egui::Id::unique("page-size-hint"))- .order(egui::Order::Foreground)- .interactable(false)- .pivot(egui::Align2::LEFT_BOTTOM)- .fixed_pos(area.left_bottom() + vec2(14.0, -14.0))- .show(ui.ctx(), |ui| {- egui::Frame::NONE- .fill(t.card)- .stroke(Stroke::new(1.0, t.border))- .corner_radius(CornerRadius::same(6))- .inner_margin(egui::Margin::symmetric(8, 4))- .show(ui, |ui| {- ui.add(egui::Label::new(egui::RichText::new(text).color(t.text)).selectable(false));- });- });-}--/// Acrobat-style floating find bar at the top-right of the document area.-fn find_bar(view: &mut DocView, pages: usize, area: Rect, ui: &mut egui::Ui, t: &Tokens) {- let Some(find) = view.find.as_mut() else { return };- // The Search panel shows this search.- if find.in_panel {- return;- }- let mut close = false;- let mut step: Option<bool> = None;- let searched = view.texts.len() + view.text_failed.len();- egui::Area::new(egui::Id::unique("find-bar"))- .order(egui::Order::Middle)- .pivot(Align2::RIGHT_TOP)- .fixed_pos(area.right_top() + vec2(-18.0, 12.0))- .show(ui.ctx(), |ui| {- egui::Frame::NONE- .fill(t.card)- .stroke(Stroke::new(1.0, t.border))- .corner_radius(CornerRadius::same(10))- .shadow(egui::Shadow { offset: [0, 4], blur: 16, spread: 0, color: Color32::from_black_alpha(if t.dark() { 90 } else { 30 }) })- .inner_margin(egui::Margin::symmetric(10, 6))- .show(ui, |ui| {- ui.horizontal(|ui| {- ui.add(icons::image("search", 16.0, t.text_muted));- let edit = egui::TextEdit::singleline(&mut find.query)- .id(egui::Id::unique("find-input"))- .hint_text(tl!("Find text"))- .desired_width(220.0)- .frame(egui::Frame::NONE);- let r = ui.add(edit).accessible_name(tl!("Find text"));- if find.focus {- r.request_focus();- find.focus = false;- }- if r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)) {- step = Some(!ui.input(|i| i.modifiers.shift));- r.request_focus();- }- if r.has_focus() && ui.input(|i| i.key_pressed(egui::Key::Escape)) {- close = true;- }- let status = if find.query.trim().is_empty() {- String::new()- } else if find.matches.is_empty() {- if searched < pages {- crate::i18n::fmt(tl!("Searching… {s}/{p}"), &[("s", &searched.to_string()), ("p", &pages.to_string())])- } else {- tl!("No matches").to_string()- }- } else {- let more = if searched < pages { "+" } else { "" };- crate::i18n::fmt(- tl!("{c} of {n}{more}"),- &[- ("c", &find.current.map(|c| c + 1).unwrap_or(0).to_string()),- ("n", &find.matches.len().to_string()),- ("more", more),- ],- )- };- ui.label(egui::RichText::new(status).font(theme::regular(12.0)).color(t.text_muted));- let tip = crate::commands::key_tip(ui.ctx(), tl!("Previous ({key})"), crate::commands::FIND_PREV);- if icons::button(ui, "chevron-up", 26.0, false, &tip).clicked() {- step = Some(false);- }- let tip = crate::commands::key_tip(ui.ctx(), tl!("Next ({key})"), crate::commands::FIND_NEXT);- if icons::button(ui, "chevron-down", 26.0, false, &tip).clicked() {- step = Some(true);- }- let opts = icons::button(ui, "settings-2", 26.0, find.case_sensitive || find.whole_words, tl!("Find options"));- egui::Popup::menu(&opts).show(|ui| {- let a = ui.add(widgets::checkbox(&mut find.whole_words, tl!("Whole words only"))).changed();- let b = ui.add(widgets::checkbox(&mut find.case_sensitive, tl!("Case-sensitive"))).changed();- if a || b {- // Search again with the new options.- find.case_query.clear();- }- });- if icons::button(ui, "x", 26.0, false, tl!("Close (Esc)")).clicked() {- close = true;- }- });- });- });- if close {- view.find = None;- return;- }- if find.query != find.case_query {- view.rerun_find();- }- if let Some(forward) = step {- view.find_step(forward);- }-}--/// The prepare-mode field menu's choices.-enum FieldMenu {- Properties,- Duplicate(String),-}--/// What the notice bar's buttons ask for.-enum Notice {- /// Reload the file that changed on disk, dropping unsaved changes.- Reload,- Security,- Signatures,- Repairs,- /// Highlight fields was turned on or off.- FieldHighlights(bool),- /// Open the JavaScript console (the form's scripts were turned off; the error is there).- Console,- /// Unlock… (enter the permissions password).- Unlock,- /// Close this historical snapshot tab (View signed version / View revision).- Close,- /// Stop showing the secured-document notice, in every document (#4035).- HideSecured,-}--/// The notice bar above the pages: a file changed on disk first, then what a historical-/// snapshot is, then the signature status bar, a form's scripts having been turned-/// off, security, forms and warnings.-fn notices(- view: &mut DocView,- doc: &pdfcraft_engine::Document,- secured: bool,- repaired: bool,- signed: Option<(&str, Color32, &str, String)>,- ui: &mut egui::Ui,- t: &Tokens,-) -> Option<Notice> {- let info = &doc.info;- let xfa = doc.xfa.as_ref();- // The file changed on disk while this document has unsaved changes (#431): ask before- // replacing it, ahead of every other notice.- if view.disk_changed {- let mut reload = false;- egui::Frame::NONE.fill(t.accent_soft).inner_margin(egui::Margin::symmetric(14, 7)).show(ui, |ui| {- ui.horizontal(|ui| {- ui.add(icons::image("rotate-cw", 16.0, t.accent_text));- ui.label(- egui::RichText::new(tl!(- "This file changed on disk. Reload shows the new version and drops your unsaved changes; Save replaces it with this version."- ))- .color(t.text),- );- ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {- if icons::button(ui, "x", 22.0, false, tl!("Dismiss")).clicked() {- view.disk_changed = false;- }- reload = crate::widgets::pill_button(ui, tl!("Reload"), false).clicked();- });- });- });- return reload.then_some(Notice::Reload);- }- // A historical snapshot (View signed version / View revision): what it is, above the- // signature and security bars, so the tab is never mistaken for the live document.- if let Some(snap) = view.snapshot.as_ref() {- let mut close = false;- let text = if snap.kind == SnapshotKind::SignedVersion {- crate::i18n::fmt(- tl!("You are viewing the signed version of “{from}” (revision {rev}). It is a snapshot: changes here won't affect the original."),- &[("from", &snap.from), ("rev", &snap.revision.to_string())],- )- } else {- crate::i18n::fmt(- tl!("You are viewing revision {rev} of “{from}”. It is a snapshot: changes here won't affect the original."),- &[("rev", &snap.revision.to_string()), ("from", &snap.from)],- )- };- notice_bar(ui, t, "clock", t.accent_text, text, |ui| {- if crate::widgets::pill_button(ui, tl!("Close"), true).clicked() {- close = true;+ if 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);}- });- if close {- return Some(Notice::Close);+ } else {+ let page = app.views[index].current;+ app.start_signing(page, None, Some(field), None);}}- if let Some((icon, color, template, arg)) = signed {- let mut open = false;- notice_bar(ui, t, icon, color, crate::i18n::fmt(tl!(template), &[("by", &arg)]), |ui| {- if crate::widgets::pill_button(ui, tl!("Signature panel"), false).clicked() {- open = true;- }- });- return open.then_some(Notice::Signatures);+ app.quick_tool = tool;+ if let Some((page, at)) = app.views[index].comments.attach_at.take() {+ app.attach_file_comment(page, at);}- if view.notice_dismissed {- return None;+ if let Some((p, i)) = open_props {+ app.open_comment_props(p, i);}- let mut open_security = false;- let mut unlock = false;- let mut hide_secured = false;- let mut open_repairs = false;- let mut open_console = false;- let mut toggled = None;- // A form whose scripts were turned off no longer calculates or answers its buttons: that- // comes before what else there is to say about the document.- let scripts_off = doc.xfa_scripts_off();- // What the document is as a form, if it is one: what the bar says first, secured or not.- let form = if let Some(x) = xfa {- let lang = crate::i18n::current();- let pages = crate::i18n::trn(lang, x.pages as u64, "{n} page", "{n} pages");- let fields = crate::i18n::trn(lang, x.fields as u64, "{n} field", "{n} fields");- let mut text =- crate::i18n::fmt(tl!("Dynamic XFA form laid out from its template: {pages}, {fields}."), &[("pages", &pages), ("fields", &fields)]);- if !x.warnings.is_empty() {- // The notes are clauses ("a picture is left out"); the first starts a sentence here.- let notes = x.warnings.join("; ");- let mut chars = notes.chars();- text.push(' ');- text.extend(chars.next().into_iter().flat_map(char::to_uppercase));- text.push_str(chars.as_str());- text.push('.');- }- Some(("text-cursor-input", text, true))- } else if info.xfa == Some(pdfcraft_render::Xfa::Dynamic) {- Some((- "triangle-alert",- tl!("This is a dynamic XFA form, which PdfCraft can't display yet. What you see is the file's placeholder page.").to_string(),- false,- ))- } else if info.xfa == Some(pdfcraft_render::Xfa::Static) {- Some((- "text-cursor-input",- tl!("XFA form: its fields and its XFA data are kept in step, so other viewers show what you fill in.").to_string(),- true,- ))- } else if info.fields.iter().any(|f| f.kind != pdfcraft_render::FieldKind::PushButton) {- // Push buttons alone (LaTeX `animate` frames, navigation buttons) leave nothing to fill in.- Some((- "text-cursor-input",- crate::i18n::fmt(tl!("This document contains {n} interactive form fields."), &[("n", &info.fields.len().to_string())]),- true,- ))- } else {- None- };- let msg = if scripts_off {- Some(("triangle-alert", crate::js_ui::scripts_off_notice(), true))- } else if secured {- // A secured form still says what it is, and keeps Highlight fields: the security- // sentence follows the form's.- let security = tl!("This document is secured. Some changes are restricted by its security settings.");- Some(match form {- Some((icon, text, fields)) => (icon, format!("{text} {security}"), fields),- None => ("lock", security.to_string(), false),- })- } else if form.is_some() {- form- } else if repaired {- Some(("bandage", tl!("This file was damaged and has been repaired. Saving keeps the repaired version.").to_string(), false))- } else if !info.warnings.is_empty() {- Some(("triangle-alert", info.warnings[0].clone(), false))- } else {- None- };- let (icon, text, fields) = msg?;- notice_bar(ui, t, icon, t.accent_text, text, |ui| {- if icons::button(ui, "x", 22.0, false, tl!("Dismiss")).clicked() {- view.notice_dismissed = true;- }- if fields {- let label = if view.highlight_fields { tl!("Hide field highlights") } else { tl!("Highlight fields") };- if crate::widgets::pill_button(ui, label, view.highlight_fields).clicked() {- view.highlight_fields = !view.highlight_fields;- toggled = Some(Notice::FieldHighlights(view.highlight_fields));- }- }- if scripts_off && crate::widgets::pill_button(ui, tl!("JavaScript Console"), false).clicked() {- open_console = true;- }- if secured && crate::widgets::pill_button(ui, tl!("Security settings"), false).clicked() {- open_security = true;- }- if secured && doc.can_unlock() && crate::widgets::pill_button(ui, tl!("Unlock…"), true).clicked() {- unlock = true;- }- // Only when the bar shows the security message: a form's stopped scripts come first.- if secured && !scripts_off && crate::widgets::pill_button(ui, tl!("Don't show again"), false).clicked() {- hide_secured = true;- }- if repaired && !secured && info.fields.is_empty() && crate::widgets::pill_button(ui, tl!("Details"), false).clicked() {- open_repairs = true;- }- });- if open_repairs {- return Some(Notice::Repairs);+ if let Some((p, i)) = app.views[index].comments.default_request.take() {+ app.make_comment_default(p, i);}- if open_console {- return Some(Notice::Console);+ 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 unlock {- return Some(Notice::Unlock);+ if let Some((name, w)) = field_props {+ app.open_field_props(&name, w);}- if hide_secured {- return Some(Notice::HideSecured);+ 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);}- open_security.then_some(Notice::Security).or(toggled)-}--/// One notice bar: an icon and a message on the left, `buttons` (added right to left) on the-/// right. The buttons are laid out first, so the message only gets the width they leave: it-/// wraps there (or, when very little is left, is cut short with the full text on hover) instead-/// of running under the buttons and past the document area into the side panel (#785). The-/// buttons are centred on a row of button height, and the message's first line is centred on-/// the same row; a wrapped message grows the bar downwards.-fn notice_bar(ui: &mut egui::Ui, t: &Tokens, icon: &str, icon_color: Color32, text: String, buttons: impl FnOnce(&mut egui::Ui)) {- const ROW: f32 = 28.0;- const ICON: f32 = 16.0;- egui::Frame::NONE.fill(t.accent_soft).inner_margin(egui::Margin::symmetric(14, 7)).show(ui, |ui| {- let width = ui.available_width();- ui.allocate_ui_with_layout(vec2(width, ROW), egui::Layout::right_to_left(egui::Align::Center), |ui| {- ui.set_min_height(ROW);- buttons(ui);- let rest = ui.available_width().max(0.0);- ui.allocate_ui_with_layout(vec2(rest, ROW), egui::Layout::top_down(egui::Align::Min), |ui| {- let font = egui::TextStyle::Body.resolve(ui.style());- let line = ui.fonts_mut(|f| f.row_height(&font)).max(ICON);- ui.add_space(((ROW - line) / 2.0).max(0.0));- ui.with_layout(egui::Layout::left_to_right(egui::Align::Min), |ui| {- let (slot, _) = ui.allocate_exact_size(vec2(ICON, line), Sense::hover());- icons::paint(ui, Rect::from_center_size(slot.center(), vec2(ICON, ICON)), icon, ICON, icon_color);- let label = egui::Label::new(egui::RichText::new(text).color(t.text));- // Wrapping into a sliver would stack the message a few letters per line.- ui.add(if ui.available_width() >= 120.0 { label.wrap() } else { label.truncate() });- });- });- });- });-}--/// The floating quick-action bar at the left edge of the document area.-fn quick_bar(app: &mut PdfCraftApp, area: Rect, ui: &mut egui::Ui) {- let t = Tokens::get(ui.ctx());- let pos = area.left_top() + vec2(14.0, 14.0);- egui::Area::new(egui::Id::unique("quick-bar")).order(egui::Order::Middle).fixed_pos(pos).show(ui.ctx(), |ui| {- egui::Frame::NONE- .fill(t.card)- .stroke(Stroke::new(1.0, t.border))- .corner_radius(CornerRadius::same(12))- .shadow(egui::Shadow { offset: [0, 4], blur: 16, spread: 0, color: Color32::from_black_alpha(if t.dark() { 100 } else { 28 }) })- .inner_margin(egui::Margin::same(6))- .show(ui, |ui| {- ui.spacing_mut().item_spacing.y = 2.0;- ui.vertical(|ui| {- if icons::button(ui, "mouse-pointer-2", 32.0, app.quick_tool == QuickTool::Select, tl!("Select (V)")).clicked() {- app.quick_tool = QuickTool::Select;- }- if icons::button(ui, "hand", 32.0, app.quick_tool == QuickTool::Hand, tl!("Hand (H)")).clicked() {- app.quick_tool = QuickTool::Hand;- }- // Comment ▸, Highlight ▸, Draw ▸ (Acrobat's comment toolbar groups). Clicking a- // group selects its last-used tool; clicking it again opens the flyout.- for g in 0..comments::GROUPS.len() {- let current = app.comment_prefs.group_tool[g];- let active = matches!(app.quick_tool, QuickTool::Comment(t) if t.group() == g);- let resp = icons::button(ui, current.icon(), 32.0, active, tl!(current.label()));- // A small corner triangle marks the flyout.- let r = resp.rect;- let tri = [r.right_bottom() + vec2(-4.0, -4.0), r.right_bottom() + vec2(-9.0, -4.0), r.right_bottom() + vec2(-4.0, -9.0)];- ui.painter().add(egui::Shape::convex_polygon(tri.to_vec(), if active { t.accent } else { t.text_faint }, Stroke::NONE));- let open = (resp.clicked() && active) || resp.secondary_clicked();- if resp.clicked() && !active {- app.execute(current.command());- }- egui::Popup::menu(&resp)- .open_memory(open.then_some(egui::SetOpenCommand::Toggle))- .align(egui::RectAlign::RIGHT_START)- .gap(6.0)- .show(|ui| {- for tool in comments::GROUPS[g] {- let on = app.quick_tool == QuickTool::Comment(*tool);- let (row, click) = ui.allocate_exact_size(vec2(180.0, 28.0), Sense::click());- let press = theme::Press::track(ui, &click);- press.wash(ui, row, 4, on);- let body = row.translate(press.offset());- icons::paint(ui, Rect::from_min_size(body.min + vec2(8.0, 6.0), vec2(16.0, 16.0)), tool.icon(), 16.0, t.text);- let reserve = if on { 28.0 } else { 8.0 };- crate::widgets::paint_left(- ui,- body.left_center() + vec2(34.0, 0.0),- tl!(tool.label()),- theme::regular(13.0),- t.text,- (row.width() - 34.0 - reserve).max(0.0),- );- if on {- icons::paint(- ui,- Rect::from_min_size(body.right_top() + vec2(-24.0, 7.0), vec2(14.0, 14.0)),- "check",- 14.0,- t.accent,- );- }- let click = theme::hand(click);- let info = tl!(tool.label()).to_string();- click.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, on, info.clone()));- if click.clicked() {- app.execute(tool.command());- ui.close();- }- }- });- }- // Edit text & images, while the Edit workspace is open (Acrobat's Edit toolbar)- // or the tool is in use.- if app.mode == crate::Mode::Edit || app.quick_tool == QuickTool::EditText {- let on = app.quick_tool == QuickTool::EditText;- if icons::button(ui, "text-cursor-input", 32.0, on, tl!("Edit text & images")).clicked() {- if on {- app.put_down_edit_text();- } else {- app.quick_tool = QuickTool::EditText;- }- }- }- // Fill & Sign ▸ (text, marks, date, signature).- let current_fill = match app.quick_tool {- QuickTool::Fill(f) => Some(f),- _ => None,- };- let shown = current_fill.unwrap_or(crate::fill_sign::FillTool::Text);- let resp = icons::button(- ui,- if current_fill.is_some() { shown.icon() } else { "pen-line" },- 32.0,- current_fill.is_some(),- tl!("Fill & Sign"),- );- let r = resp.rect;- let tri = [r.right_bottom() + vec2(-4.0, -4.0), r.right_bottom() + vec2(-9.0, -4.0), r.right_bottom() + vec2(-4.0, -9.0)];- ui.painter().add(egui::Shape::convex_polygon(- tri.to_vec(),- if current_fill.is_some() { t.accent } else { t.text_faint },- Stroke::NONE,- ));- if resp.clicked() && current_fill.is_none() {- app.execute(shown.command());- }- let open = (resp.clicked() && current_fill.is_some()) || resp.secondary_clicked();- egui::Popup::menu(&resp)- .open_memory(open.then_some(egui::SetOpenCommand::Toggle))- .align(egui::RectAlign::RIGHT_START)- .gap(6.0)- .show(|ui| {- for tool in crate::fill_sign::FILL_TOOLS {- if matches!(tool, crate::fill_sign::FillTool::Signature | crate::fill_sign::FillTool::Initials) {- continue;- }- let on = current_fill == Some(tool);- let (row, click) = ui.allocate_exact_size(vec2(180.0, 28.0), Sense::click());- let press = theme::Press::track(ui, &click);- press.wash(ui, row, 4, on);- let body = row.translate(press.offset());- icons::paint(ui, Rect::from_min_size(body.min + vec2(8.0, 6.0), vec2(16.0, 16.0)), tool.icon(), 16.0, t.text);- let reserve = if on { 28.0 } else { 8.0 };- crate::widgets::paint_left(- ui,- body.left_center() + vec2(34.0, 0.0),- tl!(tool.label()),- theme::regular(13.0),- t.text,- (row.width() - 34.0 - reserve).max(0.0),- );- if on {- icons::paint(- ui,- Rect::from_min_size(body.right_top() + vec2(-24.0, 7.0), vec2(14.0, 14.0)),- "check",- 14.0,- t.accent,- );- }- let click = theme::hand(click);- let info = tl!(tool.label()).to_string();- click.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, on, info.clone()));- if click.clicked() {- app.execute(tool.command());- ui.close();- }- }- ui.separator();- if let Some(command) = crate::fill_sign::signature_entries(ui, app, &t) {- app.execute(command);- ui.close();- }- });- if matches!(current_fill, Some(crate::fill_sign::FillTool::Text | crate::fill_sign::FillTool::Date)) {- ui.label(tl!("Font size:"));- let size = ui.add(- egui::DragValue::new(&mut app.fill_text_size)- .range(crate::fill_sign::MIN_TEXT_SIZE..=crate::fill_sign::MAX_TEXT_SIZE)- .speed(0.25)- .suffix(" pt"),- );- // #1274: the size also applies to the Fill & Sign text that is selected,- // once per change (a typed value, or the end of a drag), so a drag adds- // one undo step and not one per frame.- if ((size.changed() && !size.dragged()) || size.drag_stopped())- && let Some((index, id)) = app.active_ids()- && let Some((page, annotation)) = app.views.get(index).and_then(|view| view.comments.selected)- && app.session.get(id).is_some_and(|doc| {- doc.allows_annotation()- && doc- .info- .annotations- .iter()- .any(|a| a.page == page && a.index == annotation && a.fill_sign && a.subtype == "FreeText" && !a.locked)- })- {- app.apply_edit(Edit::FontSizeAnnotation { page, index: annotation, size: app.fill_text_size });- }- }- if let QuickTool::Comment(tool) = app.quick_tool {- let (r, _) = ui.allocate_exact_size(vec2(32.0, 9.0), Sense::hover());- ui.painter().hline(r.x_range().shrink(6.0), r.center().y, Stroke::new(1.0, t.divider));- if let Some(color) = comments::quick_bar_controls(ui, tool, &mut app.comment_prefs)- && let Some((index, id)) = app.active_ids()- && let Some((page, annotation)) = app.views.get(index).and_then(|view| view.comments.selected)- && app.session.get(id).is_some_and(|doc| {- doc.allows_annotation()- && doc- .info- .annotations- .iter()- .any(|a| a.page == page && a.index == annotation && !a.is_reply() && comments::made_by(a, tool))- })- {- app.apply_edit(Edit::StyleAnnotation {- page,- index: annotation,- color: Some(color),- opacity: None,- width: None,- endings: None,- });- }- }- });- });- });-}--/// Where a page of `page` size (points, as shown: after its rotation) is drawn in the grid cell-/// `cell`: as large as the picture area allows and centred in it, so a landscape or rotated page-/// fills the cell's width in its middle, as Acrobat draws it, instead of a small strip at the top.-/// The picture area leaves room for the page number and actions below. Its sides narrow only when-/// a picture that wide would reach the selection checkbox in the cell's corner.-pub(crate) fn grid_page_rect(cell: Rect, page: Vec2) -> Rect {- let area = Rect::from_min_max(pos2(cell.left(), cell.top() + 16.0), pos2(cell.right(), cell.bottom() - 72.0));- // A page size from a damaged file can be zero, NaN or infinite; draw such a page square.- let side = |v: f32| if v.is_finite() { v.max(1.0) } else { 1.0 };- let (w, h) = (side(page.x), side(page.y));- let fit = |margin: f32| {- let s = ((area.width() - 2.0 * margin).max(1.0) / w).min(area.height().max(1.0) / h);- Rect::from_center_size(area.center(), vec2(w * s, h * s))- };- let wide = fit(16.0);- // The checkbox sits at (8, 8)-(28, 28) from the cell's corner; keep 4 px clear of it.- let checkbox = Rect::from_min_size(cell.min + vec2(8.0, 8.0), Vec2::splat(20.0)).expand(4.0);- if wide.intersects(checkbox) { fit(30.0) } else { wide }-}--/// The organize toolbar: page operations on the selection (Acrobat's Organize Pages bar).-fn organize_toolbar(view: &mut DocView, info: &DocInfo, editable: bool, dirty: bool, unobstructed: bool, ui: &mut egui::Ui, t: &Tokens) {- let targets = view.target_pages();- let n = info.pages.len();- let (first, last) = (targets.first().copied().unwrap_or(0), targets.last().copied().unwrap_or(0));- egui::Frame::NONE.fill(t.chrome).inner_margin(egui::Margin::symmetric(16, 8)).show(ui, |ui| {- ui.horizontal(|ui| {- ui.spacing_mut().item_spacing.x = 4.0;- let label = match view.selected.len() {- 0 => crate::i18n::fmt(tl!("Page {p} of {n}"), &[("p", &(view.current + 1).to_string()), ("n", &n.to_string())]),- 1 => tl!("1 page selected").to_string(),- k => crate::i18n::fmt(tl!("{n} pages selected"), &[("n", &k.to_string())]),- };- // Fixed width so the buttons never shift as the selection text changes.- ui.add_sized([150.0, 30.0], egui::Label::new(egui::RichText::new(label).font(theme::medium(13.0)).color(t.text_muted)).truncate());- ui.add_enabled_ui(editable, |ui| {- ui.add_space(8.0);- if ui.add_enabled_ui(first > 0, |ui| icons::button(ui, "chevron-left", 30.0, false, tl!("Move earlier"))).inner.clicked() {- view.pending_edit = Some(Edit::MovePages { pages: targets.clone(), to: first - 1 });- }- if ui.add_enabled_ui(last + 1 < n, |ui| icons::button(ui, "chevron-right", 30.0, false, tl!("Move later"))).inner.clicked() {- view.pending_edit = Some(Edit::MovePages { pages: targets.clone(), to: first + 1 });- }- });- ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {- if widgets::ghost_button(ui, "x", tl!("Close")).on_hover_text(tl!("Back to the document")).clicked() {- view.organize = false;- }- // What the grid shows is what is saved.- let save = ui.add_enabled_ui(dirty, |ui| widgets::pill_button(ui, tl!("Save pages"), true)).inner;- if save.on_hover_text(tl!("Save these pages as one PDF")).on_disabled_hover_text(tl!("No changes to save")).clicked() {- view.pending_action = Some(ViewAction::Save);- }- ui.add_space(8.0);- // Page size in the grid (right to left: in, the percentage, out).- let zoom = view.grid_zoom;- if ui- .add_enabled_ui(zoom < *GRID_ZOOM_RANGE.end(), |ui| icons::button(ui, "zoom-in", 30.0, false, tl!("Larger pages")))- .inner- .clicked()- {- view.grid_zoom_request = Some(zoom * GRID_ZOOM_STEP);- }- let percent = egui::Button::new(egui::RichText::new(format!("{:.0}%", zoom * 100.0)).font(theme::medium(12.0)).color(t.text_muted))- .frame(false);- let percent = ui.add_sized([44.0, 30.0], percent);- percent.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tl!("Reset page size")));- if percent.on_hover_text(tl!("Reset page size")).clicked() {- view.grid_zoom_request = Some(1.0);- }- if ui- .add_enabled_ui(zoom > *GRID_ZOOM_RANGE.start(), |ui| icons::button(ui, "zoom-out", 30.0, false, tl!("Smaller pages")))- .inner- .clicked()- {- view.grid_zoom_request = Some(zoom / GRID_ZOOM_STEP);- }- });- });- });- // Keys act on the selection unless a text field or a dialog has them (Delete under- // Preferences deleted the selected pages).- if editable && unobstructed && !ui.ctx().egui_wants_keyboard_input() {- use egui::{Key, Modifiers};- let (del, esc) = ui.input_mut(|i| {- (- i.consume_key(Modifiers::NONE, Key::Delete) || i.consume_key(Modifiers::NONE, Key::Backspace),- i.consume_key(Modifiers::NONE, Key::Escape),- )- });- // ⌘C / ⌘X / ⌘V copy, cut and paste pages (egui delivers them as clipboard events).- let (copy, cut, paste) = ui.input(|i| {- let any = |f: &dyn Fn(&egui::Event) -> bool| i.events.iter().any(f);- (any(&|e| matches!(e, egui::Event::Copy)), any(&|e| matches!(e, egui::Event::Cut)), any(&|e| matches!(e, egui::Event::Paste(_))))+ if 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)});- if copy || cut {- view.pending_action = Some(ViewAction::CopyPages { cut });- }- if paste {- view.pending_action = Some(ViewAction::PastePages);- }- if del && targets.len() < n {- view.pending_edit = Some(Edit::DeletePages { pages: targets });+ }+ 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);}- if esc {- view.selected.clear();+ Some(crate::edit_text_ui::ImageAction::CopyFile(page, index)) => app.copy_page_image_file(page, index),+ Some(crate::edit_text_ui::ImageAction::Cut(page, image)) => {+ app.views[index].image_selection = None;+ app.cut_page_image(page, image);}+ Some(crate::edit_text_ui::ImageAction::Redact(page, index)) => app.redact_page_image(page, index),+ Some(crate::edit_text_ui::ImageAction::Link(page, index)) => app.link_page_image(page, index),+ Some(crate::edit_text_ui::ImageAction::Recognize(page)) => app.recognize_text_on_page(page),+ None => {}}-}--/// Organize pages: a thumbnail grid (Acrobat's Organize Pages view). Click selects, ⌘-click-/// toggles, ⇧-click extends; double-click opens the page.-/// The gap (0 = before the first page, n = after the last) the pointer points at in the grid.-pub(crate) fn drop_gap(cells: &[(usize, Rect)], p: Pos2) -> Option<usize> {- let (i, r) = cells.iter().min_by(|(_, a), (_, b)| a.distance_sq_to_pos(p).total_cmp(&b.distance_sq_to_pos(p)))?;- Some(if p.x < r.center().x { *i } else { i + 1 })-}--/// Ctrl (Option on macOS) held when a page drag drops copies the dragged pages into the gap-/// instead of moving them, as Acrobat's Organize Pages does.-///-/// The OS comes from the context, not `cfg!`: the wasm build runs on macOS too, where-/// `cfg!(target_os = "macos")` is false, so Option has to copy there as well (#3092 review).-fn copy_modifier(ctx: &egui::Context, m: &egui::Modifiers) -> bool {- if crate::commands::mac_shortcuts(ctx) { m.alt } else { m.ctrl }-}--/// A "+" on a gap of the page grid: insert files there. Returns whether it was clicked.-fn gap_button(ui: &mut egui::Ui, gap: usize, at: Pos2, height: f32, label: String, t: &Tokens) -> bool {- let resp = ui.interact(Rect::from_center_size(at, Vec2::splat(22.0)), ui.scope_id().with(("org-gap", gap)), Sense::click());- resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, label.clone()));- let hot = resp.hovered();- if hot {- ui.painter().line_segment([pos2(at.x, at.y - height / 2.0), pos2(at.x, at.y + height / 2.0)], Stroke::new(3.0, t.accent));+ if let Some(why) = refused {+ app.notify_error(why);}- ui.painter().circle(at, 9.0, if hot { t.accent } else { t.chrome }, Stroke::new(1.0, if hot { t.accent } else { t.border }));- let ink = Stroke::new(1.5, if hot { Color32::WHITE } else { t.text_muted });- ui.painter().line_segment([at - vec2(4.0, 0.0), at + vec2(4.0, 0.0)], ink);- ui.painter().line_segment([at - vec2(0.0, 4.0), at + vec2(0.0, 4.0)], ink);- resp.on_hover_text(label).clicked()-}--fn organize_grid(view: &mut DocView, info: &DocInfo, editable: bool, dirty: bool, unobstructed: bool, ui: &mut egui::Ui, t: &Tokens) {- let ppp = ui.ctx().pixels_per_point();- // The page image scales with the zoom; the padding and the page number don't.- let cell = vec2(146.0 * view.grid_zoom + 44.0, 194.0 * view.grid_zoom + 88.0);- let anchor = view.grid_anchor.take();- let reveal = view.grid_reveal.take();- let mut open_page = None;- organize_toolbar(view, info, editable, dirty, unobstructed, ui, t);- let viewport = ui.available_rect_before_wrap();- view.viewport_screen = viewport;- let auto_delta = if unobstructed {- view.auto_scroll.update(ui, viewport, true)- } else {- view.auto_scroll.cancel();- Vec2::ZERO- };- let middle_gesture = view.auto_scroll.blocks_input();- let mut cells: Vec<(usize, Rect)> = Vec::new();- // The pages in view that are drawn larger than their thumbnails, and those of them that- // need a sharper render than they have. The width is the size drawn, in device pixels.- let (mut in_view, mut sharper): (Vec<(usize, f32)>, Vec<RenderRequest>) = (Vec::new(), Vec::new());- // The source cell can scroll out of the virtualized rows during a drag.- let mut drop = view.org_drag.is_some() && ui.input(|i| i.pointer.primary_released());- egui::ScrollArea::vertical().auto_shrink([false, false]).show_viewport(ui, |ui, clip| {- if middle_gesture {- let opacity = ui.opacity();- ui.disable();- ui.set_opacity(opacity);- }- if auto_delta != Vec2::ZERO {- ui.scroll_with_delta_animation(auto_delta, egui::style::ScrollAnimation::none());- }- ui.add_space(20.0);- let cols = ((ui.available_width() - 40.0) / cell.x).floor().max(1.0) as usize;- let rows = info.pages.len().div_ceil(cols);- let left = (ui.available_width() - cols as f32 * cell.x) / 2.0;- let (grid, _) = ui.allocate_exact_size(vec2(ui.available_width(), rows as f32 * cell.y), Sense::hover());- // The page Organize opened on may lie in a row the virtualized grid has not laid out,- // so its cell is computed rather than found.- if let Some(page) = reveal.filter(|p| *p < info.pages.len()) {- let row = page / cols;- let col = page % cols;- let c = Rect::from_min_size(pos2(grid.left() + left + col as f32 * cell.x, grid.top() + row as f32 * cell.y), cell);- ui.scroll_to_rect_animation(c, Some(egui::Align::Center), egui::style::ScrollAnimation::none());- }- for row in thumbnail_rows(clip.top() - 20.0, clip.bottom() - 20.0, cell.y, rows) {- let row_rect = Rect::from_min_size(grid.min + vec2(0.0, row as f32 * cell.y), vec2(grid.width(), cell.y));- for col in 0..cols {- let i = row * cols + col;- let Some(p) = info.pages.get(i) else { break };- let c = Rect::from_min_size(pos2(row_rect.left() + left + col as f32 * cell.x, row_rect.top()), cell);- view.need_thumbnail(i, c.intersects(ui.clip_rect()));- let resp = ui.interact(c, ui.scope_id().with(("org", i)), if editable { Sense::click_and_drag() } else { Sense::click() });- cells.push((i, c));- if let Some((_, above)) = anchor.filter(|(page, _)| *page == i) {- ui.scroll_to_rect_animation(c.translate(vec2(0.0, -above)), Some(egui::Align::Min), egui::style::ScrollAnimation::none());- }- // Drag pages to move them (the selection, or the page grabbed).- if resp.drag_started() {- if !view.selected.contains(&i) {- view.selected = [i].into();- view.select_anchor = Some(i);- }- let mut pages: Vec<usize> = view.selected.iter().copied().collect();- pages.sort_unstable();- view.org_drag = Some(pages);- }- if resp.drag_stopped() {- drop = true;- }- let page_label = crate::i18n::fmt(tl!("Page {label}"), &[("label", &p.label)]);- resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::CheckBox, true, view.selected.contains(&i), page_label.clone()));- let pr = grid_page_rect(c, vec2(p.width, p.height));- let size = pr.size();- let selected = view.selected.contains(&i) || (view.selected.is_empty() && i == view.current);- if selected || resp.hovered() {- ui.painter().rect_filled(c.shrink(6.0), CornerRadius::same(8), if selected { t.accent_soft } else { t.hover });- }- if view.selected.contains(&i) {- ui.painter().rect_stroke(c.shrink(6.0), CornerRadius::same(8), Stroke::new(1.5, t.accent), egui::StrokeKind::Inside);- }- ui.painter().rect_filled(pr.translate(vec2(0.0, 1.5)), CornerRadius::same(1), t.page_shadow);- ui.painter().rect_filled(pr, CornerRadius::ZERO, Color32::WHITE);- // A page drawn larger than its thumbnail gets a render at the size drawn, while- // it is in view; until that arrives the thumbnail stands in.- let want = size.x * ppp;- let thumb = view.thumbs.get(&i).map(|t| &t.tex);- let thumb_ok = thumb.is_some_and(|t| t.size()[0] as f32 >= want * GRID_SHARP.start());- let sharp = view.grid_pages.get(&i).filter(|_| !thumb_ok);- if !thumb_ok && ui.is_rect_visible(c) {- in_view.push((i, want));- if !sharp.is_some_and(|(w, _)| sharp_enough(*w, want)) && !view.errors.contains_key(&i) {- sharper.push(RenderRequest {- page: i,- kind: RequestKind::Pixels,- tile: None,- scale: want / p.width.max(1.0),- tag: GRID_TAG,- // Grid cells are previews: tiny images are skipped for them.- preview: true,- });- }- }- if let Some(tex) = sharp.map(|(_, t)| t).or(thumb) {- ui.painter().image(tex.id(), pr, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE);- }- ui.painter().rect_stroke(pr, CornerRadius::ZERO, Stroke::new(1.0, t.border), egui::StrokeKind::Outside);- let label_font = theme::medium(12.0);- let label_w = (c.width() - 12.0).max(0.0);- let page_label = crate::widgets::fit_line(&p.label, label_w, |s| crate::widgets::text_width(ui, s, &label_font));- let label_pos = pos2(c.center().x, c.bottom() - 48.0);- ui.painter().with_clip_rect(Rect::from_center_size(label_pos, vec2(label_w, 18.0))).text(- label_pos,- Align2::CENTER_CENTER,- page_label,- label_font,- t.text_muted,- );- // The checkbox toggles just this page without requiring a modifier. Keep it- // outside the page image, including on very tall or wide pages.- let mut checked = view.selected.contains(&i);- let check_rect = Rect::from_min_size(c.min + vec2(8.0, 8.0), Vec2::splat(20.0));- let check = ui.push_id(("org-check", i), |ui| ui.put(check_rect, widgets::checkbox_without_text(&mut checked))).inner;- let label = crate::i18n::fmt(tl!("Select page {label}"), &[("label", &p.label)]);- check.widget_info(|| egui::WidgetInfo::selected(egui::Role::CheckBox, true, checked, label.clone()));- if check.on_hover_text(label).changed() {- view.click_page(i, egui::Modifiers::COMMAND, false);- // The document shows the page picked here when the grid closes, as after a- // Pages-panel click, so reopening the grid keeps the pick (issue #1910).- view.go_to_page(i);- }- // Local actions always target the labelled page. The toolbar above the grid- // remains the place for actions on the whole selection.- if selected || resp.contains_pointer() || resp.has_focus() {- let actions = Rect::from_center_size(pos2(c.center().x, c.bottom() - 24.0), vec2(84.0, 26.0));- ui.scope_builder(- egui::UiBuilder::new().id_salt(("org-actions", i)).max_rect(actions).layout(egui::Layout::left_to_right(egui::Align::Center)),- |ui| {- ui.spacing_mut().item_spacing.x = 3.0;- ui.add_enabled_ui(editable, |ui| {- for (icon, degrees, key) in- [("rotate-ccw", -90, "Rotate page {label} counterclockwise"), ("rotate-cw", 90, "Rotate page {label} clockwise")]- {- let label = crate::i18n::fmt(tl!(key), &[("label", &p.label)]);- if icons::button(ui, icon, 26.0, false, &label).clicked() {- view.pending_edit = Some(Edit::RotatePages { pages: vec![i], degrees });- }- }- let label = crate::i18n::fmt(tl!("Delete page {label}"), &[("label", &p.label)]);- if ui.add_enabled_ui(info.pages.len() > 1, |ui| icons::button(ui, "trash-2", 26.0, false, &label)).inner.clicked() {- view.pending_edit = Some(Edit::DeletePages { pages: vec![i] });- }- });- },- );- }- if resp.clicked() {- let m = ui.input(|i| i.modifiers);- view.click_page(i, m, false);- view.go_to_page(i);- }- if resp.double_clicked() {- open_page = Some(i);- }- // Right-click: Extract, Replace, Cut, Copy, Paste (on the selection, or this page).- resp.context_menu(|ui| {- if !view.selected.contains(&i) {- view.selected = [i].into();- view.go_to_page(i);- }- if ui.button(tl!("Extract pages")).clicked() {- view.pending_action = Some(ViewAction::Extract);- ui.close();- }- if ui.button(tl!("Split document…")).clicked() {- view.pending_action = Some(ViewAction::SplitBeforeSelected);- ui.close();- }- if ui.add_enabled(editable, egui::Button::new(tl!("Replace pages…"))).clicked() {- view.pending_action = Some(ViewAction::ReplacePages);- ui.close();- }- ui.separator();- if ui.add_enabled(editable, egui::Button::new(tl!("Cut"))).clicked() {- view.pending_action = Some(ViewAction::CopyPages { cut: true });- ui.close();- }- if ui.button(tl!("Copy")).clicked() {- view.pending_action = Some(ViewAction::CopyPages { cut: false });- ui.close();- }- if ui.add_enabled(editable, egui::Button::new(tl!("Paste after"))).clicked() {- view.pending_action = Some(ViewAction::PastePages);- ui.close();- }- });- }- }- // Between pages (and at both ends): insert files right there.- if editable && !middle_gesture && view.org_drag.is_none() {- let mid = |r: &Rect| r.top() + 16.0 + (cell.y - 88.0) / 2.0;- for (i, c) in &cells {- let label = info- .pages- .get(*i)- .map(|p| crate::i18n::fmt(tl!("Insert a file before page {label}"), &[("label", &p.label)]))- .unwrap_or_default();- if gap_button(ui, *i, pos2(c.left(), mid(c)), cell.y - 88.0, label, t) {- view.pending_action = Some(ViewAction::InsertFromFileAt(*i));- }- }- if let Some((i, c)) = cells.last()- && i + 1 == info.pages.len()- && gap_button(ui, i + 1, pos2(c.right(), mid(c)), cell.y - 88.0, tl!("Insert a file at the end").to_string(), t)- {- view.pending_action = Some(ViewAction::InsertFromFileAt(i + 1));- }- }- // While dragging: the gap the pages would go to, drawn as a bar.- if let (Some(pages), Some(p)) = (view.org_drag.clone(), ui.input(|i| i.pointer.hover_pos())) {- // Ctrl (Option on macOS) held over the drop copies the pages; see #2997.- let copying = copy_modifier(ui.ctx(), &ui.input(|i| i.modifiers));- if let Some(gap) = drop_gap(&cells, p) {- let x = match cells.iter().find(|(i, _)| *i == gap) {- Some((_, r)) => r.left() + 3.0,- None => cells.last().map_or(0.0, |(_, r)| r.right() - 3.0),- };- let row = cells.iter().find(|(i, _)| *i == gap).or(cells.last()).map(|(_, r)| r.y_range()).unwrap_or(egui::Rangef::new(0.0, 0.0));- ui.painter().line_segment([pos2(x, row.min + 10.0), pos2(x, row.max - 10.0)], Stroke::new(3.0, t.accent));- let mut text_at = p + vec2(14.0, 14.0);- if copying {- // A "+" by the pointer: this drop copies the pages, it doesn't move them.- let badge = p + vec2(12.0, 12.0);- ui.painter().circle(badge, 9.0, t.accent, Stroke::new(1.0, t.accent));- let ink = Stroke::new(1.5, Color32::WHITE);- ui.painter().line_segment([badge - vec2(4.0, 0.0), badge + vec2(4.0, 0.0)], ink);- ui.painter().line_segment([badge - vec2(0.0, 4.0), badge + vec2(0.0, 4.0)], ink);- text_at.x += 18.0;- }- ui.painter().text(- text_at,- Align2::LEFT_TOP,- if pages.len() == 1 { tl!("1 page").to_string() } else { crate::i18n::fmt(tl!("{n} pages"), &[("n", &pages.len().to_string())]) },- theme::medium(12.0),- t.accent_text,- );- }- if drop {- view.org_drag = None;- if let Some(gap) = drop_gap(&cells, p) {- if copying {- // The copies land at the gap as it is: nothing leaves its place.- view.pending_edit = Some(Edit::DuplicatePages { pages: pages.clone(), at: Some(gap) });- view.selected = (gap..gap + pages.len()).collect();- } else {- // `to` counts positions without the moving pages.- let to = gap - pages.iter().filter(|x| **x < gap).count();- let first = pages[0];- let contiguous = pages.windows(2).all(|w| w[1] == w[0] + 1);- if !(contiguous && to == first) {- view.pending_edit = Some(Edit::MovePages { pages: pages.clone(), to });- view.selected = (to..to + pages.len()).collect();- }- }- }- }- } else if drop {- view.org_drag = None;- }- });- // Files dragged in from outside go to the gap under the pointer. Some platforms don't say- // where the pointer is until the files are dropped; then the whole grid is the target.- let pointer = ui.input(|i| i.pointer.hover_pos()).filter(|p| viewport.contains(*p));- view.grid_gap = pointer.filter(|_| editable && view.org_drag.is_none()).and_then(|p| drop_gap(&cells, p));- if editable && ui.input(|i| !i.raw.hovered_files.is_empty()) {- let painter = ui.painter().with_clip_rect(viewport);- painter.rect_stroke(viewport.shrink(2.0), CornerRadius::same(6), Stroke::new(2.0, t.accent), egui::StrokeKind::Inside);- if let Some(gap) = view.grid_gap {- let at = cells.iter().find(|(i, _)| *i == gap).map(|(_, r)| (r.left() + 3.0, r.y_range()));- if let Some((x, row)) = at.or(cells.last().map(|(_, r)| (r.right() - 3.0, r.y_range()))) {- painter.line_segment([pos2(x, row.min + 10.0), pos2(x, row.max - 10.0)], Stroke::new(3.0, t.accent));- }- }- // A "+" that follows the pointer.- if let Some(p) = pointer {- let at = p + vec2(16.0, 16.0);- painter.circle_filled(at, 9.0, t.accent);- painter.line_segment([at - vec2(4.0, 0.0), at + vec2(4.0, 0.0)], Stroke::new(1.5, Color32::WHITE));- painter.line_segment([at - vec2(0.0, 4.0), at + vec2(0.0, 4.0)], Stroke::new(1.5, Color32::WHITE));- }+ 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);}- view.auto_scroll.paint(ui, viewport);- // Pinch, or Ctrl/⌘ with the wheel, zooms the grid about the page under the pointer.- let pinch = crate::motion::zoom_delta(ui.ctx());- if (pinch - 1.0).abs() > 0.001 && pointer.is_some() && !middle_gesture {- view.grid_zoom_request = Some(view.grid_zoom * pinch);+ if let Some((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(zoom) = view.grid_zoom_request.take() {- let before = view.grid_zoom;- view.set_grid_zoom(zoom);- if view.grid_zoom != before {- // Keep the page under the pointer (or else the first one in view) where it is.- let under = pointer.and_then(|p| cells.iter().find(|(_, r)| r.contains(p)));- let anchor = under.or_else(|| cells.iter().find(|(_, r)| r.bottom() > viewport.top()));- view.grid_anchor = anchor.map(|(i, r)| (*i, r.top() - viewport.top()));- ui.ctx().request_repaint();+ 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)]),}}- // When this frame's thumbnail will cover the cell, drop the sharp render without waiting- // for that texture to arrive.- let density = thumbnail_density(view.thumb_demand.len(), ppp);- in_view.retain(|&(page, want)| {- info.pages.get(page).is_none_or(|p| (device_pixels(p.width, thumbnail_scale(p.width, p.height, density)) as f32) < want * GRID_SHARP.start())- });- sharper.retain(|req| in_view.iter().any(|(page, _)| *page == req.page));- view.grid_pages.retain(|page, _| in_view.iter().any(|(kept, _)| kept == page));- // Sharp renders of the pages in view join this frame's demand ahead of the thumbnails.- view.frame_queue.extend(sharper);- if let Some(p) = open_page {- view.organize = false;- view.go_to_page(p);+ if let Some((name, action)) = app.views[index].forms.button.take() {+ run_button(app, index, &name, action);}-}--/// A rendered raster as texture data. Its words are premultiplied RGBA bytes, exactly-/// `Color32`s, so the renderer's buffer becomes the image without a copy on the UI thread.-pub(crate) fn texture_image(size: [usize; 2], pixels: pdfcraft_render::Pixels) -> egui::ColorImage {- match bytemuck::allocation::try_cast_vec::<u32, Color32>(pixels.into_words()) {- Ok(px) if px.len() == size[0].saturating_mul(size[1]) => egui::ColorImage::new(size, px),- Ok(px) => egui::ColorImage::from_rgba_premultiplied(size, bytemuck::cast_slice(&px)),- Err((_, words)) => egui::ColorImage::from_rgba_premultiplied(size, bytemuck::cast_slice(&words)),+ 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);}}-/// A luminance preview for a monochrome print. `Color32` stores premultiplied pixels, so a-/// non-opaque colour's alpha is restored after multiplying the unmultiplied RGB by its-/// luminance. This uses the display gamma-space weights users expect in editors/print dialogs,-/// not the linear-light coefficients of a colour-managed render.-fn grayscale(mut img: egui::ColorImage) -> egui::ColorImage {- for c in img.pixels.iter_mut() {- let a = c.a();- let luminance = f32::from(c.r()) * 0.299_f32 + f32::from(c.g()) * 0.587_f32 + f32::from(c.b()) * 0.114_f32;- let gray = if a == 0 || a == 255 {- luminance.round() as u8- } else {- // Unmultiply first, so translucent content keeps its paper-relative luminance.- let f = f32::from(a) / 255.0;- let un = [f32::from(c.r()) / f, f32::from(c.g()) / f, f32::from(c.b()) / f];- let l = un[0] * 0.299_f32 + un[1] * 0.587_f32 + un[2] * 0.114_f32;- (f * l).round() as u8- };- *c = Color32::from_rgba_premultiplied(gray, gray, gray, a);- }- img+/// The prepare-mode field menu's choices.+enum FieldMenu {+ Properties,+ Duplicate(String),}#[cfg(test)]diff --git a/crates/ui-egui/src/canvas/area.rs b/crates/ui-egui/src/canvas/area.rsnew file mode 100644index 000000000..d7997a79a--- /dev/null+++ b/crates/ui-egui/src/canvas/area.rs@@ -0,0 +1,168 @@+use super::*;++/// A validation badge drawn over a signature widget: the widget rectangle (user space), the verdict it shows, and its hover text.+pub(crate) struct SignatureBadge {+ pub rect: [f64; 4],+ pub status: pdfcraft_engine::SignatureStatus,+ pub summary: &'static str,+}++/// The validation badges drawn over one page's signature widgets: signed, visible widgets+/// on this page with coordinates that survive the cast to screen space. Hostile files can+/// carry NaN, infinite or gigantic rectangles, which must never reach the painter.+pub(crate) fn signature_badges(signatures: &[pdfcraft_engine::SignatureInfo], page: usize) -> Vec<SignatureBadge> {+ signatures+ .iter()+ .filter(|s| s.signed && s.visible && s.page == Some(page))+ .filter_map(|s| {+ s.rect.filter(|r| r.iter().all(|v| v.is_finite() && v.abs() < f32::MAX as f64)).map(|rect| SignatureBadge {+ rect,+ status: s.status,+ summary: s.summary(),+ })+ })+ .collect()+}++/// The hover popup for an annotation. Replies and Fill & Sign marks (typed text, checks, signatures)+/// show none: they are page content being edited, not comments.+pub(super) fn annotation_hover_text(a: &pdfcraft_render::Annotation) -> Option<String> {+ if a.is_reply() || a.fill_sign {+ return None;+ }+ let who = a.author.clone().unwrap_or_else(|| a.subtype.clone());+ let body = a.contents.clone().unwrap_or_default();+ Some(if body.is_empty() { who } else { format!("{who}\n{body}") })+}++/// Suppression window for egui's eased copy of point input.+///+/// egui 0.36.2 drains `WheelState::after_events` tail deltas by 90% per 0.1 s.+pub(super) const SUPPRESS_SECS: f64 = 0.25;++/// Short rolling extension while egui still has an unprocessed wheel tail.+pub(super) const SUPPRESS_TAIL_SECS: f64 = 0.05;++// Keep the viewer's scroll identity tied to the document instead of its parent UI.+pub(super) fn page_scroll<R>(+ ui: &mut egui::Ui,+ scroll: egui::ScrollArea,+ id: egui::Id,+ draw: impl FnOnce(&mut egui::Ui, egui::Rect) -> R,+) -> egui::scroll_area::ScrollAreaOutput<R> {+ ui.scope_builder(egui::UiBuilder::new().scope_id(id), |ui| scroll.show_viewport(ui, draw)).inner+}++/// Run a push button's action (the ones that need no JavaScript engine).+pub(super) fn run_button(app: &mut PdfCraftApp, index: usize, name: &str, action: pdfcraft_engine::form_scripts::ButtonAction) {+ use pdfcraft_engine::form_scripts::ButtonAction as B;+ let pages = app.session.get(app.views[index].id).map_or(0, |d| d.info.pages.len());+ match action {+ B::Reset { fields, exclude } => {+ let all: Vec<String> = app.session.get(app.views[index].id).map(|d| d.form.iter().map(|f| f.name.clone()).collect()).unwrap_or_default();+ let listed = |n: &String| fields.iter().any(|f| n == f || n.starts_with(&format!("{f}.")));+ let names = match (fields.is_empty(), exclude) {+ (true, _) => None,+ (false, false) => Some(all.iter().filter(|n| listed(n)).cloned().collect()),+ (false, true) => Some(all.iter().filter(|n| !listed(n)).cloned().collect()),+ };+ app.views[index].forms.focus = None;+ app.views[index].pending_edit = Some(pdfcraft_engine::Edit::ResetForm { names });+ }+ B::Named(n) => match n.as_str() {+ "Print" => app.open_print(),+ // What PdfCraft's XFA buttons use, and what a script's `execMenuItem("Save")`+ // does too: the Save As dialog, so a click never overwrites the file unasked.+ "SaveAs" => app.run_command("file.save_as"),+ "NextPage" => app.views[index].step_page(true),+ "PrevPage" => app.views[index].step_page(false),+ "FirstPage" => app.views[index].go_to_page(0),+ "LastPage" => app.views[index].go_to_page(pages.saturating_sub(1)),+ other => app.notify_fmt("{name}: the {other} action isn't supported yet", &[("name", name), ("other", other)]),+ },+ B::Uri(u) => app.request_document_url(&u, crate::LinkOrigin::Button),+ B::GoTo(p) => app.views[index].go_to_page(p.min(pages.saturating_sub(1))),+ B::ShowHide { fields, hide } => {+ let listed = |n: &String| fields.iter().any(|f| n == f || n.starts_with(&format!("{f}.")));+ // `display.hidden` 1, `display.visible` 0, as a script setting `field.display` would.+ let changes: Vec<pdfcraft_engine::FieldChange> = app+ .session+ .get(app.views[index].id)+ .map(|d| d.form.iter().filter(|f| listed(&f.name)).map(|f| f.name.clone()).collect::<Vec<_>>())+ .unwrap_or_default()+ .into_iter()+ .map(|name| pdfcraft_engine::FieldChange {+ name,+ value: None,+ read_only: None,+ required: None,+ display: Some(if hide { 1 } else { 0 }),+ })+ .collect();+ if !changes.is_empty() {+ let label = if hide { "Hide a field" } else { "Show a field" };+ app.views[index].pending_edit =+ Some(pdfcraft_engine::Edit::Batch { label: label.into(), edits: vec![pdfcraft_engine::Edit::ApplyScriptChanges { changes }] });+ }+ }+ B::SetLayers { changes, preserve_rb } => {+ use pdfcraft_engine::form_scripts::LayerOp as Op;+ let changes: Vec<(LayerOp, (u32, u16))> = changes+ .into_iter()+ .map(|(op, ocg)| {+ let op = match op {+ Op::On => LayerOp::On,+ Op::Off => LayerOp::Off,+ Op::Toggle => LayerOp::Toggle,+ };+ (op, ocg)+ })+ .collect();+ set_layers(app, index, &changes, preserve_rb);+ }+ B::Alert(m) => app.notify(m),+ B::Submit(url) => app.notify_fmt(+ "{name} submits the form to {url}; PdfCraft doesn't send form data. Save the document to keep your entries.",+ &[("name", name), ("url", &url)],+ ),+ B::ImportIcon => app.choose_field_image(name),+ B::Script(js) => {+ let id = app.views[index].id;+ app.run_button_script(id, name, &js);+ }+ }+}++/// Run a set-layer-visibility action from a button or link. It changes what is shown, as the+/// Layers panel does (which follows), not the document.+pub(super) fn set_layers(app: &mut PdfCraftApp, index: usize, changes: &[(LayerOp, (u32, u16))], preserve_rb: bool) {+ let id = app.views[index].id;+ if app.session.set_layer_state(id, changes, preserve_rb) {+ app.views[index].invalidate_content();+ }+}++/// Where a pinch or ⌘-scroll zooms the view about: the pointer, wherever it is over the view. Not+/// page input: it is read before the pages' widget exists, once `rect_contains_pointer` has found+/// the view under the pointer.+pub(super) fn zoom_anchor(ui: &egui::Ui) -> Option<Pos2> {+ ui.input(|i| i.pointer.hover_pos())+}++/// The pointer and frame time that scroll the view while a comment is drawn. Not page input: it is+/// read before the pages' widget exists, and the pointer may be past the view's edge.+pub(super) fn drawing_edge_pointer(ui: &egui::Ui) -> (Option<Pos2>, f32) {+ ui.input(|i| (i.pointer.latest_pos(), i.stable_dt))+}++/// A press anywhere, or a key, stops the touchpad's glide (#531).+pub(super) fn glide_interrupted(ui: &egui::Ui) -> bool {+ ui.input(|i| i.pointer.any_pressed() || i.events.iter().any(|e| matches!(e, egui::Event::Key { pressed: true, .. })))+}++/// Full screen's click on the document, which turns the page: a primary click this frame with the+/// view on top under it in `area`. Not page input: it is read before the pages' widget exists, and+/// the turn waits until the pages have had the click.+pub(super) fn presentation_click(ui: &egui::Ui, area: Rect) -> bool {+ ui.rect_contains_pointer(area) && ui.input(|i| i.pointer.primary_clicked())+}diff --git a/crates/ui-egui/src/canvas/bars.rs b/crates/ui-egui/src/canvas/bars.rsnew file mode 100644index 000000000..4d916a1b8--- /dev/null+++ b/crates/ui-egui/src/canvas/bars.rs@@ -0,0 +1,487 @@+use super::*;++/// Whether `p` lies in the bottom-left quadrant of `area`, where the page size shows (#1855).+pub(super) fn in_size_hint_zone(area: Rect, p: Pos2) -> bool {+ p.x >= area.min.x && p.x < area.center().x && p.y > area.center().y && p.y <= area.max.y+}++/// The current page's size, floating at the bottom-left of the document area while the pointer is+/// in that quadrant, as Acrobat does. Same formatter and unit as Document Properties.+pub(super) fn page_size_hint(+ view: &DocView,+ info: &DocInfo,+ units: crate::units::Unit,+ area: Rect,+ unobstructed: bool,+ ui: &mut egui::Ui,+ t: &Tokens,+) {+ let Some(page) = info.pages.get(view.current) else { return };+ let inside = unobstructed && ui.input(|i| i.pointer.hover_pos()).is_some_and(|p| in_size_hint_zone(area, p));+ if !inside {+ return;+ }+ let text = units.size(f64::from(page.width), f64::from(page.height));+ egui::Area::new(egui::Id::unique("page-size-hint"))+ .order(egui::Order::Foreground)+ .interactable(false)+ .pivot(egui::Align2::LEFT_BOTTOM)+ .fixed_pos(area.left_bottom() + vec2(14.0, -14.0))+ .show(ui.ctx(), |ui| {+ egui::Frame::NONE+ .fill(t.card)+ .stroke(Stroke::new(1.0, t.border))+ .corner_radius(CornerRadius::same(6))+ .inner_margin(egui::Margin::symmetric(8, 4))+ .show(ui, |ui| {+ ui.add(egui::Label::new(egui::RichText::new(text).color(t.text)).selectable(false));+ });+ });+}++/// What the notice bar's buttons ask for.+pub(super) enum Notice {+ /// Reload the file that changed on disk, dropping unsaved changes.+ Reload,+ Security,+ Signatures,+ Repairs,+ /// Highlight fields was turned on or off.+ FieldHighlights(bool),+ /// Open the JavaScript console (the form's scripts were turned off; the error is there).+ Console,+ /// Unlock… (enter the permissions password).+ Unlock,+ /// Close this historical snapshot tab (View signed version / View revision).+ Close,+ /// Stop showing the secured-document notice, in every document (#4035).+ HideSecured,+}++/// The notice bar above the pages: a file changed on disk first, then what a historical+/// snapshot is, then the signature status bar, a form's scripts having been turned+/// off, security, forms and warnings.+pub(super) fn notices(+ view: &mut DocView,+ doc: &pdfcraft_engine::Document,+ secured: bool,+ repaired: bool,+ signed: Option<(&str, Color32, &str, String)>,+ ui: &mut egui::Ui,+ t: &Tokens,+) -> Option<Notice> {+ let info = &doc.info;+ let xfa = doc.xfa.as_ref();+ // The file changed on disk while this document has unsaved changes (#431): ask before+ // replacing it, ahead of every other notice.+ if view.disk_changed {+ let mut reload = false;+ egui::Frame::NONE.fill(t.accent_soft).inner_margin(egui::Margin::symmetric(14, 7)).show(ui, |ui| {+ ui.horizontal(|ui| {+ ui.add(icons::image("rotate-cw", 16.0, t.accent_text));+ ui.label(+ egui::RichText::new(tl!(+ "This file changed on disk. Reload shows the new version and drops your unsaved changes; Save replaces it with this version."+ ))+ .color(t.text),+ );+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {+ if icons::button(ui, "x", 22.0, false, tl!("Dismiss")).clicked() {+ view.disk_changed = false;+ }+ reload = crate::widgets::pill_button(ui, tl!("Reload"), false).clicked();+ });+ });+ });+ return reload.then_some(Notice::Reload);+ }+ // A historical snapshot (View signed version / View revision): what it is, above the+ // signature and security bars, so the tab is never mistaken for the live document.+ if let Some(snap) = view.snapshot.as_ref() {+ let mut close = false;+ let text = if snap.kind == SnapshotKind::SignedVersion {+ crate::i18n::fmt(+ tl!("You are viewing the signed version of “{from}” (revision {rev}). It is a snapshot: changes here won't affect the original."),+ &[("from", &snap.from), ("rev", &snap.revision.to_string())],+ )+ } else {+ crate::i18n::fmt(+ tl!("You are viewing revision {rev} of “{from}”. It is a snapshot: changes here won't affect the original."),+ &[("rev", &snap.revision.to_string()), ("from", &snap.from)],+ )+ };+ notice_bar(ui, t, "clock", t.accent_text, text, |ui| {+ if crate::widgets::pill_button(ui, tl!("Close"), true).clicked() {+ close = true;+ }+ });+ if close {+ return Some(Notice::Close);+ }+ }+ if let Some((icon, color, template, arg)) = signed {+ let mut open = false;+ notice_bar(ui, t, icon, color, crate::i18n::fmt(tl!(template), &[("by", &arg)]), |ui| {+ if crate::widgets::pill_button(ui, tl!("Signature panel"), false).clicked() {+ open = true;+ }+ });+ return open.then_some(Notice::Signatures);+ }+ if view.notice_dismissed {+ return None;+ }+ let mut open_security = false;+ let mut unlock = false;+ let mut hide_secured = false;+ let mut open_repairs = false;+ let mut open_console = false;+ let mut toggled = None;+ // A form whose scripts were turned off no longer calculates or answers its buttons: that+ // comes before what else there is to say about the document.+ let scripts_off = doc.xfa_scripts_off();+ // What the document is as a form, if it is one: what the bar says first, secured or not.+ let form = if let Some(x) = xfa {+ let lang = crate::i18n::current();+ let pages = crate::i18n::trn(lang, x.pages as u64, "{n} page", "{n} pages");+ let fields = crate::i18n::trn(lang, x.fields as u64, "{n} field", "{n} fields");+ let mut text =+ crate::i18n::fmt(tl!("Dynamic XFA form laid out from its template: {pages}, {fields}."), &[("pages", &pages), ("fields", &fields)]);+ if !x.warnings.is_empty() {+ // The notes are clauses ("a picture is left out"); the first starts a sentence here.+ let notes = x.warnings.join("; ");+ let mut chars = notes.chars();+ text.push(' ');+ text.extend(chars.next().into_iter().flat_map(char::to_uppercase));+ text.push_str(chars.as_str());+ text.push('.');+ }+ Some(("text-cursor-input", text, true))+ } else if info.xfa == Some(pdfcraft_render::Xfa::Dynamic) {+ Some((+ "triangle-alert",+ tl!("This is a dynamic XFA form, which PdfCraft can't display yet. What you see is the file's placeholder page.").to_string(),+ false,+ ))+ } else if info.xfa == Some(pdfcraft_render::Xfa::Static) {+ Some((+ "text-cursor-input",+ tl!("XFA form: its fields and its XFA data are kept in step, so other viewers show what you fill in.").to_string(),+ true,+ ))+ } else if info.fields.iter().any(|f| f.kind != pdfcraft_render::FieldKind::PushButton) {+ // Push buttons alone (LaTeX `animate` frames, navigation buttons) leave nothing to fill in.+ Some((+ "text-cursor-input",+ crate::i18n::fmt(tl!("This document contains {n} interactive form fields."), &[("n", &info.fields.len().to_string())]),+ true,+ ))+ } else {+ None+ };+ let msg = if scripts_off {+ Some(("triangle-alert", crate::js_ui::scripts_off_notice(), true))+ } else if secured {+ // A secured form still says what it is, and keeps Highlight fields: the security+ // sentence follows the form's.+ let security = tl!("This document is secured. Some changes are restricted by its security settings.");+ Some(match form {+ Some((icon, text, fields)) => (icon, format!("{text} {security}"), fields),+ None => ("lock", security.to_string(), false),+ })+ } else if form.is_some() {+ form+ } else if repaired {+ Some(("bandage", tl!("This file was damaged and has been repaired. Saving keeps the repaired version.").to_string(), false))+ } else if !info.warnings.is_empty() {+ Some(("triangle-alert", info.warnings[0].clone(), false))+ } else {+ None+ };+ let (icon, text, fields) = msg?;+ notice_bar(ui, t, icon, t.accent_text, text, |ui| {+ if icons::button(ui, "x", 22.0, false, tl!("Dismiss")).clicked() {+ view.notice_dismissed = true;+ }+ if fields {+ let label = if view.highlight_fields { tl!("Hide field highlights") } else { tl!("Highlight fields") };+ if crate::widgets::pill_button(ui, label, view.highlight_fields).clicked() {+ view.highlight_fields = !view.highlight_fields;+ toggled = Some(Notice::FieldHighlights(view.highlight_fields));+ }+ }+ if scripts_off && crate::widgets::pill_button(ui, tl!("JavaScript Console"), false).clicked() {+ open_console = true;+ }+ if secured && crate::widgets::pill_button(ui, tl!("Security settings"), false).clicked() {+ open_security = true;+ }+ if secured && doc.can_unlock() && crate::widgets::pill_button(ui, tl!("Unlock…"), true).clicked() {+ unlock = true;+ }+ // Only when the bar shows the security message: a form's stopped scripts come first.+ if secured && !scripts_off && crate::widgets::pill_button(ui, tl!("Don't show again"), false).clicked() {+ hide_secured = true;+ }+ if repaired && !secured && info.fields.is_empty() && crate::widgets::pill_button(ui, tl!("Details"), false).clicked() {+ open_repairs = true;+ }+ });+ if open_repairs {+ return Some(Notice::Repairs);+ }+ if open_console {+ return Some(Notice::Console);+ }+ if unlock {+ return Some(Notice::Unlock);+ }+ if hide_secured {+ return Some(Notice::HideSecured);+ }+ open_security.then_some(Notice::Security).or(toggled)+}++/// One notice bar: an icon and a message on the left, `buttons` (added right to left) on the+/// right. The buttons are laid out first, so the message only gets the width they leave: it+/// wraps there (or, when very little is left, is cut short with the full text on hover) instead+/// of running under the buttons and past the document area into the side panel (#785). The+/// buttons are centred on a row of button height, and the message's first line is centred on+/// the same row; a wrapped message grows the bar downwards.+fn notice_bar(ui: &mut egui::Ui, t: &Tokens, icon: &str, icon_color: Color32, text: String, buttons: impl FnOnce(&mut egui::Ui)) {+ const ROW: f32 = 28.0;+ const ICON: f32 = 16.0;+ egui::Frame::NONE.fill(t.accent_soft).inner_margin(egui::Margin::symmetric(14, 7)).show(ui, |ui| {+ let width = ui.available_width();+ ui.allocate_ui_with_layout(vec2(width, ROW), egui::Layout::right_to_left(egui::Align::Center), |ui| {+ ui.set_min_height(ROW);+ buttons(ui);+ let rest = ui.available_width().max(0.0);+ ui.allocate_ui_with_layout(vec2(rest, ROW), egui::Layout::top_down(egui::Align::Min), |ui| {+ let font = egui::TextStyle::Body.resolve(ui.style());+ let line = ui.fonts_mut(|f| f.row_height(&font)).max(ICON);+ ui.add_space(((ROW - line) / 2.0).max(0.0));+ ui.with_layout(egui::Layout::left_to_right(egui::Align::Min), |ui| {+ let (slot, _) = ui.allocate_exact_size(vec2(ICON, line), Sense::hover());+ icons::paint(ui, Rect::from_center_size(slot.center(), vec2(ICON, ICON)), icon, ICON, icon_color);+ let label = egui::Label::new(egui::RichText::new(text).color(t.text));+ // Wrapping into a sliver would stack the message a few letters per line.+ ui.add(if ui.available_width() >= 120.0 { label.wrap() } else { label.truncate() });+ });+ });+ });+ });+}++/// The floating quick-action bar at the left edge of the document area.+pub(super) fn quick_bar(app: &mut PdfCraftApp, area: Rect, ui: &mut egui::Ui) {+ let t = Tokens::get(ui.ctx());+ let pos = area.left_top() + vec2(14.0, 14.0);+ egui::Area::new(egui::Id::unique("quick-bar")).order(egui::Order::Middle).fixed_pos(pos).show(ui.ctx(), |ui| {+ egui::Frame::NONE+ .fill(t.card)+ .stroke(Stroke::new(1.0, t.border))+ .corner_radius(CornerRadius::same(12))+ .shadow(egui::Shadow { offset: [0, 4], blur: 16, spread: 0, color: Color32::from_black_alpha(if t.dark() { 100 } else { 28 }) })+ .inner_margin(egui::Margin::same(6))+ .show(ui, |ui| {+ ui.spacing_mut().item_spacing.y = 2.0;+ ui.vertical(|ui| {+ if icons::button(ui, "mouse-pointer-2", 32.0, app.quick_tool == QuickTool::Select, tl!("Select (V)")).clicked() {+ app.quick_tool = QuickTool::Select;+ }+ if icons::button(ui, "hand", 32.0, app.quick_tool == QuickTool::Hand, tl!("Hand (H)")).clicked() {+ app.quick_tool = QuickTool::Hand;+ }+ // Comment ▸, Highlight ▸, Draw ▸ (Acrobat's comment toolbar groups). Clicking a+ // group selects its last-used tool; clicking it again opens the flyout.+ for g in 0..comments::GROUPS.len() {+ let current = app.comment_prefs.group_tool[g];+ let active = matches!(app.quick_tool, QuickTool::Comment(t) if t.group() == g);+ let resp = icons::button(ui, current.icon(), 32.0, active, tl!(current.label()));+ // A small corner triangle marks the flyout.+ let r = resp.rect;+ let tri = [r.right_bottom() + vec2(-4.0, -4.0), r.right_bottom() + vec2(-9.0, -4.0), r.right_bottom() + vec2(-4.0, -9.0)];+ ui.painter().add(egui::Shape::convex_polygon(tri.to_vec(), if active { t.accent } else { t.text_faint }, Stroke::NONE));+ let open = (resp.clicked() && active) || resp.secondary_clicked();+ if resp.clicked() && !active {+ app.execute(current.command());+ }+ egui::Popup::menu(&resp)+ .open_memory(open.then_some(egui::SetOpenCommand::Toggle))+ .align(egui::RectAlign::RIGHT_START)+ .gap(6.0)+ .show(|ui| {+ for tool in comments::GROUPS[g] {+ let on = app.quick_tool == QuickTool::Comment(*tool);+ let (row, click) = ui.allocate_exact_size(vec2(180.0, 28.0), Sense::click());+ let press = theme::Press::track(ui, &click);+ press.wash(ui, row, 4, on);+ let body = row.translate(press.offset());+ icons::paint(ui, Rect::from_min_size(body.min + vec2(8.0, 6.0), vec2(16.0, 16.0)), tool.icon(), 16.0, t.text);+ let reserve = if on { 28.0 } else { 8.0 };+ crate::widgets::paint_left(+ ui,+ body.left_center() + vec2(34.0, 0.0),+ tl!(tool.label()),+ theme::regular(13.0),+ t.text,+ (row.width() - 34.0 - reserve).max(0.0),+ );+ if on {+ icons::paint(+ ui,+ Rect::from_min_size(body.right_top() + vec2(-24.0, 7.0), vec2(14.0, 14.0)),+ "check",+ 14.0,+ t.accent,+ );+ }+ let click = theme::hand(click);+ let info = tl!(tool.label()).to_string();+ click.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, on, info.clone()));+ if click.clicked() {+ app.execute(tool.command());+ ui.close();+ }+ }+ });+ }+ // Edit text & images, while the Edit workspace is open (Acrobat's Edit toolbar)+ // or the tool is in use.+ if app.mode == crate::Mode::Edit || app.quick_tool == QuickTool::EditText {+ let on = app.quick_tool == QuickTool::EditText;+ if icons::button(ui, "text-cursor-input", 32.0, on, tl!("Edit text & images")).clicked() {+ if on {+ app.put_down_edit_text();+ } else {+ app.quick_tool = QuickTool::EditText;+ }+ }+ }+ // Fill & Sign ▸ (text, marks, date, signature).+ let current_fill = match app.quick_tool {+ QuickTool::Fill(f) => Some(f),+ _ => None,+ };+ let shown = current_fill.unwrap_or(crate::fill_sign::FillTool::Text);+ let resp = icons::button(+ ui,+ if current_fill.is_some() { shown.icon() } else { "pen-line" },+ 32.0,+ current_fill.is_some(),+ tl!("Fill & Sign"),+ );+ let r = resp.rect;+ let tri = [r.right_bottom() + vec2(-4.0, -4.0), r.right_bottom() + vec2(-9.0, -4.0), r.right_bottom() + vec2(-4.0, -9.0)];+ ui.painter().add(egui::Shape::convex_polygon(+ tri.to_vec(),+ if current_fill.is_some() { t.accent } else { t.text_faint },+ Stroke::NONE,+ ));+ if resp.clicked() && current_fill.is_none() {+ app.execute(shown.command());+ }+ let open = (resp.clicked() && current_fill.is_some()) || resp.secondary_clicked();+ egui::Popup::menu(&resp)+ .open_memory(open.then_some(egui::SetOpenCommand::Toggle))+ .align(egui::RectAlign::RIGHT_START)+ .gap(6.0)+ .show(|ui| {+ for tool in crate::fill_sign::FILL_TOOLS {+ if matches!(tool, crate::fill_sign::FillTool::Signature | crate::fill_sign::FillTool::Initials) {+ continue;+ }+ let on = current_fill == Some(tool);+ let (row, click) = ui.allocate_exact_size(vec2(180.0, 28.0), Sense::click());+ let press = theme::Press::track(ui, &click);+ press.wash(ui, row, 4, on);+ let body = row.translate(press.offset());+ icons::paint(ui, Rect::from_min_size(body.min + vec2(8.0, 6.0), vec2(16.0, 16.0)), tool.icon(), 16.0, t.text);+ let reserve = if on { 28.0 } else { 8.0 };+ crate::widgets::paint_left(+ ui,+ body.left_center() + vec2(34.0, 0.0),+ tl!(tool.label()),+ theme::regular(13.0),+ t.text,+ (row.width() - 34.0 - reserve).max(0.0),+ );+ if on {+ icons::paint(+ ui,+ Rect::from_min_size(body.right_top() + vec2(-24.0, 7.0), vec2(14.0, 14.0)),+ "check",+ 14.0,+ t.accent,+ );+ }+ let click = theme::hand(click);+ let info = tl!(tool.label()).to_string();+ click.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, on, info.clone()));+ if click.clicked() {+ app.execute(tool.command());+ ui.close();+ }+ }+ ui.separator();+ if let Some(command) = crate::fill_sign::signature_entries(ui, app, &t) {+ app.execute(command);+ ui.close();+ }+ });+ if matches!(current_fill, Some(crate::fill_sign::FillTool::Text | crate::fill_sign::FillTool::Date)) {+ ui.label(tl!("Font size:"));+ let size = ui.add(+ egui::DragValue::new(&mut app.fill_text_size)+ .range(crate::fill_sign::MIN_TEXT_SIZE..=crate::fill_sign::MAX_TEXT_SIZE)+ .speed(0.25)+ .suffix(" pt"),+ );+ // #1274: the size also applies to the Fill & Sign text that is selected,+ // once per change (a typed value, or the end of a drag), so a drag adds+ // one undo step and not one per frame.+ if ((size.changed() && !size.dragged()) || size.drag_stopped())+ && let Some((index, id)) = app.active_ids()+ && let Some((page, annotation)) = app.views.get(index).and_then(|view| view.comments.selected)+ && app.session.get(id).is_some_and(|doc| {+ doc.allows_annotation()+ && doc+ .info+ .annotations+ .iter()+ .any(|a| a.page == page && a.index == annotation && a.fill_sign && a.subtype == "FreeText" && !a.locked)+ })+ {+ app.apply_edit(Edit::FontSizeAnnotation { page, index: annotation, size: app.fill_text_size });+ }+ }+ if let QuickTool::Comment(tool) = app.quick_tool {+ let (r, _) = ui.allocate_exact_size(vec2(32.0, 9.0), Sense::hover());+ ui.painter().hline(r.x_range().shrink(6.0), r.center().y, Stroke::new(1.0, t.divider));+ if let Some(color) = comments::quick_bar_controls(ui, tool, &mut app.comment_prefs)+ && let Some((index, id)) = app.active_ids()+ && let Some((page, annotation)) = app.views.get(index).and_then(|view| view.comments.selected)+ && app.session.get(id).is_some_and(|doc| {+ doc.allows_annotation()+ && doc+ .info+ .annotations+ .iter()+ .any(|a| a.page == page && a.index == annotation && !a.is_reply() && comments::made_by(a, tool))+ })+ {+ app.apply_edit(Edit::StyleAnnotation {+ page,+ index: annotation,+ color: Some(color),+ opacity: None,+ width: None,+ endings: None,+ });+ }+ }+ });+ });+ });+}diff --git a/crates/ui-egui/src/canvas/cache.rs b/crates/ui-egui/src/canvas/cache.rsnew file mode 100644index 000000000..d8a1d1d44--- /dev/null+++ b/crates/ui-egui/src/canvas/cache.rs@@ -0,0 +1,736 @@+use super::find::Follow;+use super::*;++pub(super) const THUMB_TAG: u64 = 1 << 63;++pub(super) const TEXT_TAG: u64 = 1 << 62;++/// A page rendered for the organize grid at the size it is drawn there.+pub(super) const GRID_TAG: u64 = 1 << 61;++/// Preview rasters tagged with this bit are converted to luminance on receipt, matching the+/// monochrome print requested by Print ▸ Print in grayscale. It is a bit of its own: the+/// renderer's print bit ([`PRINT_TAG`]) is carried by every print preview, so sharing it would+/// turn colour previews into monochrome ones too.+pub(super) const GRAYSCALE_TAG: u64 = 1 << 59;++/// The tag of a raster that is out of date (shown until its replacement arrives).+pub(super) const STALE_TAG: u64 = u64::MAX;++/// Pages whose raster would exceed this many device pixels on a side are drawn in tiles.+pub(crate) const TILE_THRESHOLD: f32 = 4096.0;++/// Base device-pixel side of a page tile. The actual side grows with the zoom+/// ([`tile_side`]), so a zoomed viewport is covered by a few tiles instead of many.+pub(super) const TILE: u32 = 1024;++/// Longest side of the backdrop drawn under tiles, and of a live page preview (signature drag).+pub(crate) const BASE_SIDE: f32 = 2048.0;++/// Thumbnail slot before density scaling. The pages panel draws at most 150 logical points and+/// the organize grid about 146; when the byte budget allows, density reaches the screen so those+/// images are sampled down instead of stretched.+pub(super) const THUMB_W: f32 = 240.0;++pub(super) const THUMB_H: f32 = 320.0;++pub(super) const THUMB_BYTES: usize = 24 * 1024 * 1024;++pub(super) const PAGE_BYTES: usize = 128 * 1024 * 1024;++pub(super) const TILE_BYTES: usize = 128 * 1024 * 1024;++const UPLOAD_BYTES_PER_FRAME: usize = 16 * 1024 * 1024;++const RESULTS_PER_FRAME: usize = 8;++/// A defensive ceiling for unusually large viewports / n-up previews.+pub(super) const MAX_THUMB_DEMAND: usize = 256;++/// At most this many whole-page rasters are cached beyond the ones on screen.+const MAX_CACHED_PAGES: usize = 24;++/// At most this many text layers are cached beyond visible, selected and matched pages.+/// Text layers are glyph structs, far smaller than rasters; deliberately independent of+/// `MAX_CACHED_PAGES` so raster tuning never silently retunes text memory.+pub(super) const MAX_CACHED_TEXT_PAGES: usize = 24;++pub(super) fn rgba_bytes(width: usize, height: usize) -> usize {+ width.saturating_mul(height).saturating_mul(4)+}++pub(super) fn texture_bytes(tex: &TextureHandle) -> usize {+ let [w, h] = tex.size();+ rgba_bytes(w, h)+}++/// Visible grid rows, plus one adjacent row in either direction. Work is independent of+/// document length, including after a large scroll jump.+pub(crate) fn thumbnail_rows(top: f32, bottom: f32, row_height: f32, rows: usize) -> Range<usize> {+ let first = (top.max(0.0) / row_height).floor() as usize;+ let end = (bottom.max(0.0) / row_height).ceil() as usize;+ first.saturating_sub(1).min(rows)..end.saturating_add(1).min(rows)+}++pub(super) struct PageTex {+ pub(super) tag: u64,+ pub(super) tex: TextureHandle,+}++/// Retained RGBA texture accounting for automation and performance regressions. These+/// surface bytes exclude driver overhead and temporary upload buffers; they are not RSS.+#[derive(Clone, Copy, Debug, Default, serde::Serialize)]+pub struct RasterMemory {+ pub thumbnail_count: usize,+ pub thumbnail_bytes: usize,+ pub page_count: usize,+ pub page_bytes: usize,+ pub tile_count: usize,+ pub tile_bytes: usize,+ pub thumbnail_demand: usize,+ /// Last submitted missing results; workers may have completed some since submission.+ pub pending_requests: usize,+}++/// Thumbnail device-pixel density when `demand` pages share the thumbnail allowance.+pub(super) fn thumbnail_density(demand: usize, ppp: f32) -> f32 {+ let per_thumb = THUMB_BYTES / demand.max(1).next_power_of_two();+ ppp.clamp(0.25, 4.0).min((per_thumb as f32 / (4.0 * THUMB_W * THUMB_H)).sqrt() * 0.98)+}++pub(super) fn thumbnail_scale(width: f32, height: f32, density: f32) -> f32 {+ (THUMB_W / width.max(1.0)).min(THUMB_H / height.max(1.0)) * density+}++impl DocView {+ pub fn raster_memory(&self) -> RasterMemory {+ RasterMemory {+ thumbnail_count: self.thumbs.len(),+ thumbnail_bytes: self.thumbs.values().fold(0usize, |n, p| n.saturating_add(texture_bytes(&p.tex))),+ page_count: self.pages.len(),+ page_bytes: self.pages.values().fold(0usize, |n, p| n.saturating_add(texture_bytes(&p.tex))),+ tile_count: self.tiles.len(),+ tile_bytes: self.tiles.values().fold(0usize, |n, tex| n.saturating_add(texture_bytes(tex))),+ thumbnail_demand: self.thumb_demand.len(),+ pending_requests: self.last_queue.len(),+ }+ }++ /// Pages that could not be rendered, with the reason (for automation; 0-based pages).+ pub fn page_errors(&self) -> Vec<(usize, &str)> {+ let mut v: Vec<(usize, &str)> = self.errors.iter().map(|(p, e)| (*p, e.as_str())).collect();+ v.sort_unstable_by_key(|(p, _)| *p);+ v+ }++ pub fn render_pending(&self) -> bool {+ !self.last_queue.is_empty() || self.text_background.pending() || self.move_background.pending()+ }++ /// The cached tile keys of a page, as (scale tag, tile x, tile y) (diagnostics and tests).+ pub fn tiles_debug(&self, page: usize) -> Vec<(u64, u32, u32)> {+ let mut k: Vec<(u64, u32, u32)> = self.tiles.keys().filter(|key| key.0 == page).map(|key| (key.1, key.2, key.3)).collect();+ k.sort_unstable();+ k+ }++ /// Re-render every page and text layer (the document's appearance changed, e.g. a layer+ /// was toggled). Out-of-date rasters stay on screen until their replacements arrive, so the+ /// view never flashes blank.+ pub fn invalidate_content(&mut self) {+ // Undo, redo and other document-wide changes: a released drawing's preview would be a ghost.+ self.comments.settling.clear();+ for p in self.pages.values_mut() {+ p.tag = STALE_TAG;+ }+ self.stale_thumbs.extend(self.thumbs.keys().copied());+ for slot in self.print_pages.values_mut() {+ slot.0 = STALE_TAG;+ }+ // Pages may have moved: a sharp render of another page would be worse than a soft one.+ self.grid_pages.clear();+ self.tiles.clear();+ self.stale_tiles.clear();+ self.forms.unbaked.clear();+ self.texts.clear();+ self.text_failed.clear();+ self.errors.clear();+ self.slow_pages.clear();+ self.waiting_since.clear();+ self.last_queue.clear();+ self.selection = None;+ self.all_text = false;+ // A content change is not reader navigation: keep the automatic anchor so the+ // re-extracted layers still follow it, and keep `follow_ended` so a reader who already+ // took over stays in control. `document_changed` clamps `current`; if the view no longer+ // sits where the automatic choice left it, `follow_page` ends it.+ if let Some(f) = self.find.as_mut() {+ f.matches.clear();+ f.current = None;+ }+ }++ /// Only `page` changed (a comment was added, edited or removed): re-render that page and+ /// re-read its text, keep everything else. Out-of-date tiles stay on screen until replacements arrive.+ pub fn page_changed(&mut self, page: usize) {+ if let Some(p) = self.pages.get_mut(&page) {+ p.tag = STALE_TAG;+ }+ if self.thumbs.contains_key(&page) {+ self.stale_thumbs.insert(page);+ }+ if let Some(slot) = self.print_pages.get_mut(&page) {+ slot.0 = STALE_TAG;+ }+ let current_tag = if self.current_scale_tag != 0 {+ self.current_scale_tag+ } else {+ self.tiles.keys().filter(|k| k.0 == page).map(|k| k.1).max().unwrap_or(0)+ };+ self.tiles.retain(|key, _| key.0 != page || key.1 == current_tag);+ self.stale_tiles.retain(|key| key.0 != page || key.1 == current_tag);+ for &key in self.tiles.keys() {+ if key.0 == page && key.1 == current_tag {+ self.stale_tiles.insert(key);+ }+ }+ self.slow_pages.remove(&page);+ self.texts.remove(&page);+ self.text_failed.remove(&page);+ self.errors.remove(&page);+ self.last_queue.clear();+ if self.selection.is_some_and(|s| s.page == page) {+ self.selection = None;+ }+ }++ /// A page's thumbnail texture, when rendered.+ pub(crate) fn thumb_id(&self, page: usize) -> Option<egui::TextureId> {+ self.thumbs.get(&page).map(|t| t.tex.id())+ }++ /// The whole-page raster on screen for `page` (the low-res backdrop of a tiled page), if any.+ pub(crate) fn page_raster(&self, page: usize) -> Option<egui::TextureId> {+ self.pages.get(&page).map(|p| p.tex.id())+ }++ /// Whether `page`'s whole-page raster (a tiled page's backdrop too) is still the one from+ /// before its last change, whatever its tiles are.+ pub(crate) fn page_raster_out_of_date(&self, page: usize) -> bool {+ self.pages.get(&page).is_some_and(|p| p.tag == STALE_TAG)+ }++ /// Whether `page` is still drawn, somewhere, as it was before its last change: its whole-page+ /// raster (a tiled page's backdrop too) or any of its tiles waits for a replacement.+ pub(crate) fn page_out_of_date(&self, page: usize) -> bool {+ self.pages.get(&page).is_some_and(|p| p.tag == STALE_TAG) || self.stale_tiles.iter().any(|k| k.0 == page)+ }++ /// The print preview's picture of `page`: the sheet raster when it has arrived, otherwise the+ /// thumbnail.+ pub(crate) fn page_preview(&self, page: usize) -> Option<egui::TextureId> {+ self.print_pages.get(&page).map(|(_, tex)| tex.id()).or_else(|| self.thumb_id(page))+ }++ pub(crate) fn page_text(&self, page: usize) -> Option<Arc<PageText>> {+ self.texts.get(&page).cloned()+ }++ pub fn thumb(&self, page: usize) -> Option<&TextureHandle> {+ self.thumbs.get(&page).map(|t| &t.tex)+ }++ /// How many device pixels wide the grid's sharp render of `page` is, if it has one.+ pub fn grid_page_pixels(&self, page: usize) -> Option<u32> {+ self.grid_pages.get(&page).map(|(w, _)| *w)+ }++ /// Start collecting demand from every consumer before scheduling or uploading results.+ pub(crate) fn begin_render_frame(&mut self) {+ self.frame_geometry_changed = false;+ self.pages_panel = None;+ self.panel_gap = None;+ self.thumb_demand.clear();+ self.frame_queue.clear();+ self.frame_visible.clear();+ }++ pub(crate) fn need_thumbnail(&mut self, page: usize, visible: bool) {+ if page >= self.page_count {+ return;+ }+ if let Some(priority) = self.thumb_demand.get_mut(&page) {+ *priority |= visible;+ } else if self.thumb_demand.len() < MAX_THUMB_DEMAND {+ self.thumb_demand.insert(page, visible);+ } else if visible && let Some(prefetch) = self.thumb_demand.iter().find_map(|(&p, &v)| (!v).then_some(p)) {+ self.thumb_demand.remove(&prefetch);+ self.thumb_demand.insert(page, true);+ }+ }++ /// Only the displayed document owns raster textures. Tabs keep their document and view+ /// state, but do not each retain a separate full application texture allowance.+ pub(crate) fn suspend_rendering(&mut self, pool: &RenderPool) {+ self.begin_render_frame();+ self.pages.clear();+ self.tiles.clear();+ self.thumbs.clear();+ self.grid_pages.clear();+ self.print_pages.clear();+ self.stale_thumbs.clear();+ self.stale_tiles.clear();+ self.waiting_since.clear();+ // Signature previews own a separate renderer and image/background textures.+ self.signature_drag = Default::default();+ self.text_background = Default::default();+ self.move_background = Default::default();+ if !self.last_queue.is_empty() {+ pool.set_queue(Vec::new());+ self.last_queue.clear();+ }+ // Results already finished for this tab would otherwise sit in its pool, rasters and+ // all, until the tab is shown again. (An inline pool renders inside try_recv: skip it.)+ if !pool.is_inline() {+ while pool.try_recv().is_some() {}+ }+ }++ pub(super) fn thumbnail_requests(&self, info: &DocInfo, ppp: f32) -> Vec<RenderRequest> {+ let mut pages: Vec<_> = self.thumb_demand.iter().map(|(&p, &visible)| (p, visible)).collect();+ pages.sort_unstable_by_key(|&(p, visible)| (!visible, p));+ // At high DPI or in a very large viewport every demanded cell still fits the same+ // byte allowance. Both dimensions are capped, including tall/wide page boxes.+ // The count is rounded up to a power of two: the scale is part of each request's tag,+ // so a density that followed every row scrolling in or out would re-render them all.+ let density = thumbnail_density(pages.len(), ppp);+ pages+ .into_iter()+ .filter_map(|(page, _)| {+ let p = info.pages.get(page)?;+ let scale = thumbnail_scale(p.width, p.height, density);+ Some(RenderRequest {+ page,+ kind: RequestKind::Pixels,+ tile: None,+ scale,+ tag: THUMB_TAG | u64::from(scale.to_bits()),+ // Thumbnails are previews: tiny images are skipped for them.+ preview: true,+ })+ })+ .collect()+ }++ /// Admit current demand within explicit byte limits. Cached and pending surfaces share+ /// the allowance, so an evicted page can be requested again without a permanent done set.+ pub(super) fn prepare_render_queue(&mut self, info: &DocInfo, ppp: f32) -> Vec<RenderRequest> {+ let requests = std::mem::take(&mut self.frame_queue);+ let mut queue = Vec::new();+ let mut pages = HashSet::new();+ let mut tiles = HashSet::new();+ let mut tile_tags = HashSet::new();+ let mut grid = Vec::new();+ let (mut page_bytes, mut tile_bytes) = (0usize, 0usize);+ for req in requests.iter().filter(|r| r.kind == RequestKind::Pixels) {+ let Some(p) = info.pages.get(req.page) else { continue };+ // Organize-grid renders: only the cells in view that need one (organize_grid).+ if req.tag & GRID_TAG != 0 {+ grid.push(*req);+ continue;+ }+ // Print-preview rasters: a few sheets at the pane's size (the dialog bounds them).+ if req.tag & PRINT_TAG != 0 {+ if !self.errors.contains_key(&req.page) {+ queue.push(*req);+ }+ continue;+ }+ // On-screen work is always admitted (the viewport bounds it); the limits only+ // decide how much prefetch fits beside it.+ let visible = self.frame_visible.contains(&req.page);+ if let Some(tile) = req.tile {+ // Keyed by exact device-pixel origin: the tile side varies with the zoom+ // (`tile_side`), so grid indices would need the scale to decode.+ let key = (req.page, req.tag, tile.x, tile.y);+ let bytes = rgba_bytes(tile.w as usize, tile.h as usize);+ if (!visible && tile_bytes.saturating_add(bytes) > TILE_BYTES) || !tiles.insert(key) {+ continue;+ }+ tile_bytes = tile_bytes.saturating_add(bytes);+ tile_tags.insert(req.tag);+ if !self.tiles.contains_key(&key) || self.stale_tiles.contains(&key) {+ queue.push(*req);+ }+ } else {+ let bytes = rgba_bytes(device_pixels(p.width, req.scale) as usize, device_pixels(p.height, req.scale) as usize);+ if (!visible && (page_bytes.saturating_add(bytes) > PAGE_BYTES || pages.len() >= MAX_CACHED_PAGES)) || !pages.insert(req.page) {+ continue;+ }+ page_bytes = page_bytes.saturating_add(bytes);+ if self.pages.get(&req.page).is_none_or(|p| p.tag != req.tag) {+ queue.push(*req);+ }+ }+ }+ // Pages no longer demanded stay cached while the allowance has room, nearest to the+ // current page first, so turning back a page shows it at once instead of rendering.+ let mut undemanded: Vec<usize> = self.pages.keys().copied().filter(|p| !pages.contains(p)).collect();+ undemanded.sort_by_key(|p| p.abs_diff(self.current));+ let mut kept = pages.len();+ for page in undemanded {+ let bytes = self.pages.get(&page).map_or(0, |p| texture_bytes(&p.tex));+ if kept < MAX_CACHED_PAGES && page_bytes.saturating_add(bytes) <= PAGE_BYTES {+ page_bytes = page_bytes.saturating_add(bytes);+ kept += 1;+ pages.insert(page);+ }+ }+ self.pages.retain(|p, _| pages.contains(p));+ // Tiles of an earlier zoom (not a demanded scale) stay while the canvas keeps them, a+ // bounded few under a page whose current tiles are still missing (OLD_TILES). Tiles of a+ // page on screen stay too even when this frame does not demand them (#2196): the viewport+ // moves while zooming, so a tile that was sharp a moment ago falls outside the demanded+ // rectangle, and dropping it made every pan or zoom back a cold miss that re-blurred the+ // page and re-interpreted it once per tile. The per-frame cap below (OLD_TILES,+ // nearest scale first) is what bounds how much of that stays.+ self.tiles.retain(|key, _| tiles.contains(key) || !tile_tags.contains(&key.1) || self.frame_visible.contains(&key.0));+ self.stale_tiles.retain(|key| self.tiles.contains_key(key));+ queue.extend(grid);+ // Opening (or turning to) a page queues its pixels alongside thumbnails and+ // text extraction. The workers would otherwise spend the first seconds on+ // thumbnails and search text while the visible page stays blank: hold those+ // until no visible main-page raster is still missing. Errored pages never+ // block: they are never re-requested.+ let visible_mains_pending = queue.iter().any(|r| {+ r.kind == RequestKind::Pixels+ && r.tag & (GRID_TAG | PRINT_TAG | THUMB_TAG | TEXT_TAG) == 0+ && self.frame_visible.contains(&r.page)+ && !self.errors.contains_key(&r.page)+ });+ if visible_mains_pending {+ // Caches are kept; demand is re-evaluated next frame once pixels arrive.+ return queue;+ }+ let thumbs = self.thumbnail_requests(info, ppp);+ let mut thumb_bytes = 0usize;+ let mut admitted = HashSet::new();+ for req in thumbs {+ let Some(p) = info.pages.get(req.page) else { continue };+ let bytes = rgba_bytes(device_pixels(p.width, req.scale) as usize, device_pixels(p.height, req.scale) as usize);+ if thumb_bytes.saturating_add(bytes) > THUMB_BYTES || self.errors.contains_key(&req.page) {+ continue;+ }+ thumb_bytes += bytes;+ admitted.insert(req.page);+ if self.thumbs.get(&req.page).is_none_or(|t| t.tag != req.tag) || self.stale_thumbs.contains(&req.page) {+ queue.push(req);+ }+ }+ self.thumbs.retain(|p, _| admitted.contains(p));+ self.stale_thumbs.retain(|p| admitted.contains(p));+ self.retain_text_layers();+ // Visible main pages and thumbnails take precedence over background search work.+ queue.extend(requests.into_iter().filter(|r| r.kind == RequestKind::Text));+ queue+ }++ /// Drop text layers nothing can still need. Every visited page's text used to stay+ /// cached for the session. Keep visible, selected and matched pages plus the nearest+ /// prefetch window; evicted pages re-extract on revisit. (Count window only: unlike+ /// rasters there is no byte budget here.) While a search is active keep everything:+ /// demand still wants every page, so evicting would re-request evicted pages each+ /// frame and churn the workers. Failures are never evicted either: they cost nothing+ /// to remember, and evicting one would re-request and re-fail it every frame.+ fn retain_text_layers(&mut self) {+ if self.texts.len() <= MAX_CACHED_TEXT_PAGES {+ return;+ }+ if self.find.as_ref().is_some_and(|f| !f.case_query.trim().is_empty()) {+ return;+ }+ let mut keep: HashSet<usize> = self.frame_visible.clone();+ if let Some(s) = self.selection {+ keep.insert(s.page);+ }+ if let Some(f) = self.find.as_ref() {+ keep.extend(f.matches.iter().map(|(p, _)| *p));+ }+ let mut rest: Vec<usize> = self.texts.keys().filter(|p| !keep.contains(*p)).copied().collect();+ rest.sort_by_key(|p| p.abs_diff(self.current));+ keep.extend(rest.into_iter().take(MAX_CACHED_TEXT_PAGES));+ self.texts.retain(|p, _| keep.contains(p));+ }++ pub(crate) fn finish_render_frame(&mut self, ctx: &egui::Context, info: &DocInfo, pool: &RenderPool) {+ if self.frame_geometry_changed {+ // Dialogs and edits can replace pages after the canvas collected demand. Its+ // scales and indexes belong to the old pages, not to the new renderer (#3149).+ self.begin_render_frame();+ self.last_queue.clear();+ pool.set_queue(Vec::new());+ ctx.request_repaint();+ return;+ }+ let queue = self.prepare_render_queue(info, ctx.pixels_per_point());+ if queue != self.last_queue {+ pool.set_queue(queue.clone());+ self.last_queue = queue;+ }+ if !self.hold_rasters {+ self.receive(ctx, pool);+ }+ if !self.last_queue.is_empty() {+ ctx.request_repaint_after(std::time::Duration::from_millis(30));+ }+ }++ /// Pull a bounded batch of current results into textures. Demand is committed first, so+ /// offscreen results and obsolete scale/configuration tags never allocate a ColorImage.+ pub fn receive(&mut self, ctx: &egui::Context, pool: &RenderPool) {+ let budget = if pool.is_inline() { 1 } else { RESULTS_PER_FRAME };+ let mut uploaded = 0usize;+ #[cfg(not(target_arch = "wasm32"))]+ let started = std::time::Instant::now();+ for _ in 0..budget {+ let Some(r) = pool.try_recv() else { break };+ uploaded = uploaded.saturating_add(self.receive_result(ctx, r));+ // One whole-page upload may exceed the frame allowance; it must still progress.+ if uploaded >= UPLOAD_BYTES_PER_FRAME {+ break;+ }+ #[cfg(not(target_arch = "wasm32"))]+ if started.elapsed() >= std::time::Duration::from_millis(4) {+ break;+ }+ }+ }++ pub(super) fn receive_result(&mut self, ctx: &egui::Context, r: pdfcraft_render::RenderedPage) -> usize {+ if !self.last_queue.contains(&r.request) {+ return 0;+ }+ ctx.request_repaint();+ if r.request.kind == RequestKind::Text {+ match r.text {+ Some(t) => {+ self.texts.insert(r.request.page, t);+ self.refresh_find_page(r.request.page);+ }+ None => {+ log::warn!("page {} text: {}", r.request.page + 1, r.error.unwrap_or_default());+ self.text_failed.insert(r.request.page);+ if let Some(f) = self.find.as_mut() {+ let previous = f.current.and_then(|c| f.matches.get(c).cloned());+ let follow = f.follow_page(self.current);+ f.matches.retain(|(p, _)| *p != r.request.page);+ match follow {+ // An automatic choice keeps following its anchor; a failure never+ // flashes, so the view stays exactly where it was.+ Follow::Active(from) => f.current = f.first_at_or_after(from),+ Follow::Ended | Follow::Never => {+ let preserved = previous.as_ref().and_then(|k| f.matches.iter().position(|m| m == k));+ f.current = preserved.or_else(|| f.first_at_or_after(self.current));+ }+ }+ }+ }+ }+ return 0;+ }+ if let Some(e) = r.error {+ log::warn!("page {}: {e}", r.request.page + 1);+ self.errors.insert(r.request.page, e);+ return 0;+ }+ // Even current demand may have been sized with obsolete geometry or a different+ // device limit. Check before cache eviction, conversion and every upload path.+ let max_side = ctx.input(|i| i.max_texture_side);+ if r.width == 0 || r.height == 0 || r.width as usize > max_side || r.height as usize > max_side {+ return 0;+ }+ // Remember heavy pages: only these get the zoom/pan settle holds, so fast pages+ // never pay added latency. Stale entries die with the tiles on edits.+ if r.millis >= SLOW_MILLIS {+ self.slow_pages.insert(r.request.page);+ }+ let page = r.request.page;+ let bytes = rgba_bytes(r.width as usize, r.height as usize);+ if bytes != r.rgba.len() || !self.admit_texture(r.request, bytes) {+ return 0;+ }+ // The length was checked above, so the renderer's buffer becomes the texture data as is.+ let img = texture_image([r.width as usize, r.height as usize], r.rgba);+ if let Some(t) = r.request.tile {+ let key = (page, r.request.tag, t.x, t.y);+ let tex = ctx.load_texture(format!("tile-{:?}-{page}-{}-{}", self.id, t.x, t.y), img, TextureOptions::LINEAR);+ self.tiles.insert(key, tex);+ self.stale_tiles.remove(&key);+ if !self.stale_tiles.iter().any(|k| k.0 == page) {+ self.forms.unbaked.retain(|(_, p)| *p != page);+ self.comments.page_rendered(page);+ }+ if !self.page_out_of_date(page) {+ self.text_background.page_received(page);+ }+ } else if r.request.tag & PRINT_TAG != 0 {+ let tex = ctx.load_texture(+ format!("print-{:?}-{page}", self.id),+ if r.request.tag & GRAYSCALE_TAG != 0 { grayscale(img) } else { img },+ TextureOptions::LINEAR,+ );+ self.print_pages.insert(page, (r.request.tag, tex));+ } else if r.request.tag & GRID_TAG != 0 {+ let tex = ctx.load_texture(format!("grid-{:?}-{page}", self.id), img, TextureOptions::LINEAR);+ self.grid_pages.insert(page, (r.width, tex));+ } else if r.request.tag & THUMB_TAG != 0 {+ let tex = ctx.load_texture(format!("thumb-{:?}-{page}", self.id), img, TextureOptions::LINEAR);+ self.thumbs.insert(page, PageTex { tag: r.request.tag, tex });+ self.stale_thumbs.remove(&page);+ } else {+ let tex = ctx.load_texture(format!("page-{:?}-{page}", self.id), img, TextureOptions::LINEAR);+ self.pages.insert(page, PageTex { tag: r.request.tag, tex });+ self.signature_drag.page_received(page);+ self.move_background.page_received(page);+ if !self.page_out_of_date(page) {+ self.text_background.page_received(page);+ }+ self.comments.page_rendered(page);+ self.waiting_since.remove(&page);+ if !self.stale_tiles.iter().any(|k| k.0 == page) {+ self.forms.unbaked.retain(|(_, p)| *p != page);+ }+ }+ bytes+ }++ /// Check real dimensions before conversion, including stale textures kept during edits.+ /// Dropping an old handle releases its backend allocation after the current frame.+ pub(super) fn admit_texture(&mut self, req: RenderRequest, bytes: usize) -> bool {+ // An on-screen page or tile is always taken (the viewport bounds it): it may evict+ // off-screen rasters but never another on-screen one, and is never refused.+ let visible = req.tag & THUMB_TAG == 0 && self.frame_visible.contains(&req.page);+ // Organize-grid renders are bounded by the cells in view (organize_grid). Print+ // previews are the sheets around the one on screen.+ if req.tag & (GRID_TAG | PRINT_TAG) != 0 {+ return true;+ }+ if let Some(t) = req.tile {+ let key = (req.page, req.tag, t.x, t.y);+ self.tiles.remove(&key);+ let retained = self.tiles.values().fold(0usize, |n, tex| n.saturating_add(texture_bytes(tex)));+ visible || bytes <= TILE_BYTES.saturating_sub(retained)+ } else {+ let thumb = req.tag & THUMB_TAG != 0;+ let (cache, limit) = if thumb { (&mut self.thumbs, THUMB_BYTES) } else { (&mut self.pages, PAGE_BYTES) };+ cache.remove(&req.page);+ let mut retained = cache.values().fold(0usize, |n, p| n.saturating_add(texture_bytes(&p.tex)));+ // A zoom/DPI change can temporarily retain larger stale images than the new+ // demand estimates. Evict those first, then let the current demand refill them.+ let on_screen = |p: &usize| !thumb && self.frame_visible.contains(p);+ while retained.saturating_add(bytes) > limit {+ let Some(page) = cache.keys().copied().filter(|p| !on_screen(p)).max_by_key(|p| p.abs_diff(self.current)) else { break };+ if let Some(old) = cache.remove(&page) {+ retained = retained.saturating_sub(texture_bytes(&old.tex));+ }+ }+ visible || bytes <= limit.saturating_sub(retained)+ }+ }++ pub(super) fn render_scale(&self, ppp: f32) -> f32 {+ // Exactly the device scale: a raster at any other scale is resampled on screen, which+ // blurs every line and glyph (#260).+ self.zoom * PT * ppp+ }++ /// Set whether the print preview rasters become luminance before upload. Toggling it drops+ /// the colour previews: new requests carry the grayscale tag, so stale ones are replaced.+ pub(crate) fn set_print_grayscale(&mut self, grayscale: bool) {+ if self.grayscale != grayscale {+ self.grayscale = grayscale;+ self.print_pages.clear();+ }+ }++ /// Queue sharp rasters for the print preview. Pages that leave the nearby sheets are dropped.+ /// Previews render with reading colours off (the request's tag tells the renderer): they must+ /// match the printout, which is imposed from the uncoloured document.+ pub(crate) fn queue_print_previews(&mut self, pages: &[(usize, f32)]) {+ self.print_pages.retain(|page, _| pages.iter().any(|(p, _)| p == page));+ for &(page, scale) in pages {+ if self.errors.contains_key(&page) || !scale.is_finite() || scale <= 0.0 {+ continue;+ }+ let tag = scale_tag(scale) | PRINT_TAG | if self.grayscale { GRAYSCALE_TAG } else { 0 };+ let fresh = self.print_pages.get(&page).is_some_and(|(have, _)| *have == tag);+ if !fresh {+ self.frame_queue.push(RenderRequest { page, kind: RequestKind::Pixels, tile: None, scale, tag, preview: false });+ }+ }+ }+}++/// The request tag for a raster at `scale`: equal tags mean the same scale (to 1/65536).+pub(super) fn scale_tag(scale: f32) -> u64 {+ (f64::from(scale) * 65536.0).round() as u64+}++/// The scale of a raster tagged by [`scale_tag`].+pub(super) fn tag_scale(tag: u64) -> f32 {+ (tag as f64 / 65536.0) as f32+}++/// Device-pixel side of a page tile at `scale` for a page `page_max_px` device pixels on+/// its long side. Each tile costs a full page interpret, so tiles grow with the zoom and+/// with the page: a zoomed viewport, or a giant sheet shown whole, is covered by a few+/// large tiles instead of dozens of small ones. Bounded by the render backend (tile sides+/// above 4096 are clamped there) and kept granular at ordinary zooms.+pub(super) fn tile_side(scale: f32, page_max_px: u32) -> u32 {+ if !scale.is_finite() || scale <= 0.0 {+ return TILE;+ }+ let by_zoom = (TILE as f32 * (scale / 6.0)).clamp(TILE as f32, 4096.0) as u32;+ // At most four tiles along the long side, so a giant sheet needs a handful of+ // interprets instead of dozens.+ by_zoom.max(page_max_px.div_ceil(4).min(4096))+}++/// Tiles of earlier zooms kept for a page while its current tiles are rendered.+pub(super) const OLD_TILES: usize = 64;++/// A page whose raster took at least this long is heavy: zoom/pan holds apply to it,+/// so gestures stay on stretched surfaces instead of queueing full-page interprets.+const SLOW_MILLIS: u32 = 500;++/// A rendered raster as texture data. Its words are premultiplied RGBA bytes, exactly+/// `Color32`s, so the renderer's buffer becomes the image without a copy on the UI thread.+pub(crate) fn texture_image(size: [usize; 2], pixels: pdfcraft_render::Pixels) -> egui::ColorImage {+ match bytemuck::allocation::try_cast_vec::<u32, Color32>(pixels.into_words()) {+ Ok(px) if px.len() == size[0].saturating_mul(size[1]) => egui::ColorImage::new(size, px),+ Ok(px) => egui::ColorImage::from_rgba_premultiplied(size, bytemuck::cast_slice(&px)),+ Err((_, words)) => egui::ColorImage::from_rgba_premultiplied(size, bytemuck::cast_slice(&words)),+ }+}++/// A luminance preview for a monochrome print. `Color32` stores premultiplied pixels, so a+/// non-opaque colour's alpha is restored after multiplying the unmultiplied RGB by its+/// luminance. This uses the display gamma-space weights users expect in editors/print dialogs,+/// not the linear-light coefficients of a colour-managed render.+pub(super) fn grayscale(mut img: egui::ColorImage) -> egui::ColorImage {+ for c in img.pixels.iter_mut() {+ let a = c.a();+ let luminance = f32::from(c.r()) * 0.299_f32 + f32::from(c.g()) * 0.587_f32 + f32::from(c.b()) * 0.114_f32;+ let gray = if a == 0 || a == 255 {+ luminance.round() as u8+ } else {+ // Unmultiply first, so translucent content keeps its paper-relative luminance.+ let f = f32::from(a) / 255.0;+ let un = [f32::from(c.r()) / f, f32::from(c.g()) / f, f32::from(c.b()) / f];+ let l = un[0] * 0.299_f32 + un[1] * 0.587_f32 + un[2] * 0.114_f32;+ (f * l).round() as u8+ };+ *c = Color32::from_rgba_premultiplied(gray, gray, gray, a);+ }+ img+}diff --git a/crates/ui-egui/src/canvas/find.rs b/crates/ui-egui/src/canvas/find.rsnew file mode 100644index 000000000..d44ad9d5e--- /dev/null+++ b/crates/ui-egui/src/canvas/find.rs@@ -0,0 +1,301 @@+use super::*;++/// The find bar (⌘F): query, matches across the document, current match.+#[derive(Default)]+pub struct Find {+ pub query: String,+ /// (page, glyph range) in document order.+ pub matches: Vec<(usize, Range<usize>)>,+ pub current: Option<usize>,+ /// The page a search started from while its match is picked automatically: a text layer+ /// that arrives out of order can still supply an earlier match, and the automatic choice+ /// follows this page. Cleared when the user picks a match or moves the view themselves.+ pub auto_from: Option<usize>,+ /// The page the automatic choice last put the view on (the search's starting page until it+ /// chose anything). Compared with the viewed page, it tells an automatic scroll from one+ /// the reader made themselves; `None` with `auto_from` once the choice is the user's.+ pub auto_page: Option<usize>,+ /// The reader ended automatic following (by navigating, scrolling, or picking a match).+ /// This is distinct from a search that never followed: a late match must be listed without+ /// being revealed by scrolling, even when the reader moved before the first match arrived.+ pub follow_ended: bool,+ pub focus: bool,+ pub case_query: String,+ /// Find options (Acrobat's: case-sensitive, whole words only).+ pub case_sensitive: bool,+ pub whole_words: bool,+ /// Shown in the Search panel (Advanced Search) instead of the find bar.+ pub in_panel: bool,+}++/// What a text layer arriving after a search began may do with the automatic choice.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub(super) enum Follow {+ /// The reader has not moved the view since the automatic choice: it may follow `from`.+ Active(usize),+ /// The reader navigated, scrolled or picked a match, so no automatic choice may reveal.+ Ended,+ /// No automatic choice is being followed (the search has not started, or the reader chose).+ Never,+}++impl Find {+ /// The first match at or after `page`, or the first match when none follows (the search+ /// wraps round the document).+ pub(super) fn first_at_or_after(&self, page: usize) -> Option<usize> {+ self.matches.iter().position(|(p, _)| *p >= page).or_else(|| (!self.matches.is_empty()).then_some(0))+ }++ /// How a text layer arriving now relates to the automatic choice. Once the reader has moved+ /// the view (page box, Pages panel, outline, view history or any scrolling), automatic+ /// following ends: a later layer must not pull them back to an anchor-derived match.+ /// `Ended` is deliberately distinct from `Never`, so a first match arriving after that move+ /// is not revealed by a flash meant only for a search that is still following.+ pub(super) fn follow_page(&mut self, viewed: usize) -> Follow {+ if self.follow_ended {+ return Follow::Ended;+ }+ match (self.auto_from, self.auto_page) {+ (Some(from), Some(page)) if page == viewed => Follow::Active(from),+ (Some(_), _) | (_, Some(_)) => {+ self.stop_following();+ Follow::Ended+ }+ (None, None) => Follow::Never,+ }+ }++ /// Ends automatic following: the selected match is now the user's choice to keep.+ fn stop_following(&mut self) {+ self.auto_from = None;+ self.auto_page = None;+ self.follow_ended = true;+ }+}++impl DocView {+ /// Open the find bar (or focus it if already open).+ pub fn open_find(&mut self) {+ let f = self.find.get_or_insert_with(Find::default);+ f.focus = true;+ }++ /// Re-run the search on all pages whose text is known (after the query changed).+ pub fn rerun_find(&mut self) {+ let Some(f) = self.find.as_mut() else { return };+ f.case_query = f.query.clone();+ f.matches.clear();+ f.current = None;+ // Refining the query keeps the page the reader started searching from, even when an+ // automatic choice has already scrolled them to a match. Only a view the reader moved+ // themselves re-anchors the search on the page now shown.+ let from = match (f.auto_from, f.auto_page) {+ (Some(from), Some(page)) if !f.follow_ended && page == self.current => from,+ _ => self.current,+ };+ f.auto_from = Some(from);+ f.auto_page = Some(self.current);+ f.follow_ended = false;+ if f.case_query.trim().is_empty() {+ return;+ }+ let mut pages: Vec<usize> = self.texts.keys().copied().collect();+ pages.sort();+ for &p in &pages {+ if let Some(text) = self.texts.get(&p) {+ f.matches.extend(text.find_opts(&f.case_query, f.case_sensitive, f.whole_words).into_iter().map(|r| (p, r)));+ }+ }+ f.matches.sort_by_key(|(p, r)| (*p, r.start));+ // First match at or after the page the search started from.+ if let Some(i) = f.first_at_or_after(from)+ && let Some(&(p, _)) = f.matches.get(i)+ {+ f.current = Some(i);+ f.auto_page = Some(p);+ self.flash_match(p);+ }+ }++ pub(super) fn refresh_find_page(&mut self, page: usize) {+ let (Some(f), Some(text)) = (self.find.as_mut(), self.texts.get(&page)) else { return };+ if f.case_query.trim().is_empty() {+ return;+ }+ let previous = f.current.and_then(|c| f.matches.get(c).cloned());+ // An automatic choice follows the page it was anchored on, so a page whose text+ // arrives late can still supply an earlier match. Once the reader has moved the view,+ // this arrival must not pull them back; the choice then becomes theirs to keep.+ let follow = f.follow_page(self.current);+ f.matches.retain(|(p, _)| *p != page);+ f.matches.extend(text.find_opts(&f.case_query, f.case_sensitive, f.whole_words).into_iter().map(|r| (page, r)));+ f.matches.sort_by_key(|(p, r)| (*p, r.start));+ if let Follow::Active(from) = follow {+ f.current = f.first_at_or_after(from);+ let selected = f.current.and_then(|i| f.matches.get(i).cloned());+ // Follow a changed automatic choice; the view is still where the last one left it.+ if selected != previous+ && let Some((p, _)) = selected+ {+ f.auto_page = Some(p);+ self.flash_match(p);+ }+ return;+ }+ // A match the user picked keeps its identity, exactly as before automatic following.+ // When it is gone (or none was picked), the first match at or after the viewed page is+ // selected for the panel, but the view stays put: `Ended` and `Never` have no automatic+ // choice to reveal, and a reader who moved before the first layer arrived must not be+ // pulled back by that late match.+ let preserved = previous.as_ref().and_then(|k| f.matches.iter().position(|m| m == k));+ f.current = preserved.or_else(|| f.first_at_or_after(self.current));+ }++ /// Go to match `i` (the Search panel's results).+ pub fn go_to_match(&mut self, i: usize) {+ let Some(f) = self.find.as_mut() else { return };+ let Some(&(p, _)) = f.matches.get(i) else { return };+ f.current = Some(i);+ f.stop_following();+ self.go_to_page(p);+ self.goto_point = None;+ self.flash_match(p);+ }++ /// Move to the next/previous match.+ pub fn find_step(&mut self, forward: bool) {+ let Some(f) = self.find.as_mut() else { return };+ if f.matches.is_empty() {+ return;+ }+ let n = f.matches.len();+ let c = f.current.unwrap_or(0);+ let next = if forward { (c + 1) % n } else { (c + n - 1) % n };+ f.current = Some(next);+ f.stop_following();+ let p = f.matches[next].0;+ // Only explicit search navigation joins history; background refresh uses flash_match alone.+ self.go_to_page(p);+ self.goto_point = None;+ self.flash_match(p);+ }++ fn flash_match(&mut self, page: usize) {+ let frac = self+ .find+ .as_ref()+ .and_then(|f| f.current.and_then(|c| f.matches.get(c)))+ .and_then(|(p, r)| self.texts.get(p).and_then(|t| t.glyphs.get(r.start)).map(|g| g.rect[1]))+ .zip(self.page_heights.get(page).copied())+ .map(|(y, h)| ((y - 60.0) / h).clamp(0.0, 1.0))+ .unwrap_or(0.0);+ self.goto = Some((page, frac));+ self.current = page;+ self.reset_coarse_state();+ }++ /// Ends automatic search following after the reader navigated or scrolled the view. A+ /// programmatic search flash never comes through here; it sets `goto` and `current` directly+ /// so that its own scroll cannot be mistaken for the reader's.+ pub(super) fn end_find_following(&mut self) {+ if let Some(f) = self.find.as_mut() {+ f.stop_following();+ }+ }+}++/// Acrobat-style floating find bar at the top-right of the document area.+pub(super) fn find_bar(view: &mut DocView, pages: usize, area: Rect, ui: &mut egui::Ui, t: &Tokens) {+ let Some(find) = view.find.as_mut() else { return };+ // The Search panel shows this search.+ if find.in_panel {+ return;+ }+ let mut close = false;+ let mut step: Option<bool> = None;+ let searched = view.texts.len() + view.text_failed.len();+ egui::Area::new(egui::Id::unique("find-bar"))+ .order(egui::Order::Middle)+ .pivot(Align2::RIGHT_TOP)+ .fixed_pos(area.right_top() + vec2(-18.0, 12.0))+ .show(ui.ctx(), |ui| {+ egui::Frame::NONE+ .fill(t.card)+ .stroke(Stroke::new(1.0, t.border))+ .corner_radius(CornerRadius::same(10))+ .shadow(egui::Shadow { offset: [0, 4], blur: 16, spread: 0, color: Color32::from_black_alpha(if t.dark() { 90 } else { 30 }) })+ .inner_margin(egui::Margin::symmetric(10, 6))+ .show(ui, |ui| {+ ui.horizontal(|ui| {+ ui.add(icons::image("search", 16.0, t.text_muted));+ let edit = egui::TextEdit::singleline(&mut find.query)+ .id(egui::Id::unique("find-input"))+ .hint_text(tl!("Find text"))+ .desired_width(220.0)+ .frame(egui::Frame::NONE);+ let r = ui.add(edit).accessible_name(tl!("Find text"));+ if find.focus {+ r.request_focus();+ find.focus = false;+ }+ if r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)) {+ step = Some(!ui.input(|i| i.modifiers.shift));+ r.request_focus();+ }+ if r.has_focus() && ui.input(|i| i.key_pressed(egui::Key::Escape)) {+ close = true;+ }+ let status = if find.query.trim().is_empty() {+ String::new()+ } else if find.matches.is_empty() {+ if searched < pages {+ crate::i18n::fmt(tl!("Searching… {s}/{p}"), &[("s", &searched.to_string()), ("p", &pages.to_string())])+ } else {+ tl!("No matches").to_string()+ }+ } else {+ let more = if searched < pages { "+" } else { "" };+ crate::i18n::fmt(+ tl!("{c} of {n}{more}"),+ &[+ ("c", &find.current.map(|c| c + 1).unwrap_or(0).to_string()),+ ("n", &find.matches.len().to_string()),+ ("more", more),+ ],+ )+ };+ ui.label(egui::RichText::new(status).font(theme::regular(12.0)).color(t.text_muted));+ let tip = crate::commands::key_tip(ui.ctx(), tl!("Previous ({key})"), crate::commands::FIND_PREV);+ if icons::button(ui, "chevron-up", 26.0, false, &tip).clicked() {+ step = Some(false);+ }+ let tip = crate::commands::key_tip(ui.ctx(), tl!("Next ({key})"), crate::commands::FIND_NEXT);+ if icons::button(ui, "chevron-down", 26.0, false, &tip).clicked() {+ step = Some(true);+ }+ let opts = icons::button(ui, "settings-2", 26.0, find.case_sensitive || find.whole_words, tl!("Find options"));+ egui::Popup::menu(&opts).show(|ui| {+ let a = ui.add(widgets::checkbox(&mut find.whole_words, tl!("Whole words only"))).changed();+ let b = ui.add(widgets::checkbox(&mut find.case_sensitive, tl!("Case-sensitive"))).changed();+ if a || b {+ // Search again with the new options.+ find.case_query.clear();+ }+ });+ if icons::button(ui, "x", 26.0, false, tl!("Close (Esc)")).clicked() {+ close = true;+ }+ });+ });+ });+ if close {+ view.find = None;+ return;+ }+ if find.query != find.case_query {+ view.rerun_find();+ }+ if let Some(forward) = step {+ view.find_step(forward);+ }+}diff --git a/crates/ui-egui/src/canvas/navigation.rs b/crates/ui-egui/src/canvas/navigation.rsnew file mode 100644index 000000000..1cf3be91e--- /dev/null+++ b/crates/ui-egui/src/canvas/navigation.rs@@ -0,0 +1,445 @@+use super::zoom::GRID_ZOOM_STEP;+use super::*;++impl DocView {+ /// Where a bookmark made now should go: the page and the `/XYZ` position `[left, top]` in user+ /// space. With text selected it is the corner of the selection that shows at its top-left+ /// (its page, both coordinates); otherwise the top of the window (the page showing there, and+ /// only the position along the window's vertical, so the reader's other scroll position and+ /// zoom are kept). `None` before the first frame has laid pages out, when the bookmark just+ /// goes to the current page.+ pub(crate) fn bookmark_position(&self, info: &DocInfo) -> Option<(usize, [Option<f32>; 2])> {+ if let Some(sel) = self.selection+ && let Some(text) = self.texts.get(&sel.page)+ && let Some(p) = info.pages.get(sel.page)+ {+ // The selection's bounds in view space, which View ▸ Rotate View leaves unturned: the+ // corner at the screen's top-left is a different one for each quarter turn.+ let [x0, y0, x1, y1] = sel.rects(text).iter().fold([f32::INFINITY, f32::INFINITY, f32::NEG_INFINITY, f32::NEG_INFINITY], |b, r| {+ [b[0].min(r[0]), b[1].min(r[1]), b[2].max(r[2]), b[3].max(r[3])]+ });+ let (x, y) = match self.rotation {+ 90 => (x0, y1),+ 180 => (x1, y1),+ 270 => (x1, y0),+ _ => (x0, y0),+ };+ if x.is_finite() && y.is_finite() {+ return Some((sel.page, p.xyz_for_view(Some(x), Some(y))));+ }+ }+ // The page showing at the window's top edge: one that crosses it (the first, in a spread+ // of pages of different heights, whose shorter page can start below it), else the+ // nearest one below.+ let top = self.viewport_screen.top();+ let showing = || self.screen_xforms.iter().filter(|(_, xf)| xf.rect.bottom() > top);+ let (page, xf) = showing()+ .filter(|(_, xf)| xf.rect.top() <= top)+ .min_by_key(|(p, _)| *p)+ .or_else(|| showing().min_by(|a, b| a.1.rect.top().total_cmp(&b.1.rect.top()).then(a.0.cmp(&b.0))))?;+ let p = info.pages.get(*page)?;+ // Above the page (in the gap before it) is the page's own top. The window's vertical is+ // the view's y, or its x when the view is turned a quarter.+ let (x, y) = xf.screen_to_view(pos2(xf.rect.center().x, top.max(xf.rect.top())));+ let at = if xf.rot.is_multiple_of(180) {+ p.xyz_for_view(None, Some(y.clamp(0.0, p.height)))+ } else {+ p.xyz_for_view(Some(x.clamp(0.0, p.width)), None)+ };+ Some((*page, at))+ }++ /// The user-space `[left, top]` at the window's top-left (where `/XYZ` puts its point), on the+ /// page showing there: what a destination's null coordinate keeps (ISO 32000-2 §12.3.2.2).+ /// Acrobat keeps the place this way across pages, so a CAD sheet's cross-reference opens the+ /// next sheet where the reader was looking. A coordinate is `None` along a screen axis the+ /// page fits, which keeps the layout's own placement (centred, or the page's top); the whole+ /// place is `None` before the first frame has laid pages out.+ fn place_at_corner(&self, info: &DocInfo) -> Option<[Option<f32>; 2]> {+ let area = self.viewport_screen;+ if !area.is_positive() {+ return None;+ }+ let corner = area.min + vec2(SIDE, 0.0);+ let (page, xf) = self+ .screen_xforms+ .iter()+ .filter(|(_, xf)| xf.rect.is_positive())+ .min_by(|a, b| a.1.rect.distance_sq_to_pos(corner).total_cmp(&b.1.rect.distance_sq_to_pos(corner)).then(a.0.cmp(&b.0)))?;+ let p = info.pages.get(*page)?;+ let (x, y) = xf.screen_to_view(corner.clamp(xf.rect.min, xf.rect.max));+ // `max` drops a NaN size, so the bounds stay ordered and `clamp` can't panic.+ let (x, y) = (x.clamp(0.0, p.width.max(0.0)), y.clamp(0.0, p.height.max(0.0)));+ // The page counts with its side gutters, as the layout places it.+ let wide = xf.rect.width() + 2.0 * SIDE > area.width();+ let tall = xf.rect.height() > area.height();+ // The view's x runs across the screen unless the view is turned a quarter.+ let (keep_x, keep_y) = if xf.rot.is_multiple_of(180) { (wide, tall) } else { (tall, wide) };+ Some(p.xyz_for_view(keep_x.then_some(x), keep_y.then_some(y)))+ }++ pub fn go_to_page(&mut self, page: usize) {+ let page = page.min(self.page_count.saturating_sub(1));+ self.end_find_following();+ if page != self.current {+ // The view history (Previous view / Next view).+ if self.back.last() != Some(&self.current) {+ self.back.push(self.current);+ if self.back.len() > 200 {+ self.back.remove(0);+ }+ }+ self.forward.clear();+ }+ // Partial wheel motion belongs to the old place.+ self.reset_coarse_state();+ self.goto = Some((page, 0.0));+ self.current = page;+ }++ /// Reveal a user-space rectangle without changing zoom, centred where the scroll bounds allow.+ pub(crate) fn reveal_rect(&mut self, page: usize, rect: [f32; 4], info: &DocInfo) {+ self.go_to_page(page);+ self.goto_point = None;+ let Some(p) = info.pages.get(self.current) else { return };+ if !rect.iter().all(|v| v.is_finite()) {+ return;+ }+ // Halve before adding so even large finite coordinates cannot overflow the midpoint.+ let x = rect[0] * 0.5 + rect[2] * 0.5;+ let y = rect[1] * 0.5 + rect[3] * 0.5;+ let [fx, fy] = p.dest_fraction(Some(x), Some(y), self.rotation);+ self.goto_point = Some((self.current, fx, fy, vec2(self.viewport_w, self.viewport_h) / 2.0));+ }++ /// Go to a destination, a bookmark's or a link's (ISO 32000-2 §12.3.2.2): its page, scrolled+ /// and zoomed as `dest` asks, as Acrobat does. `/XYZ` puts (left, top) at the window's+ /// top-left at its zoom (null or 0 keeps the zoom); `/Fit`, `/FitH` and `/FitV` switch to fit+ /// page, width and height with `top` or `left` at the window's edge; `/FitR` zooms so the+ /// rectangle fits, centred. The `B` (content box) forms are read as the page. A null `/XYZ`+ /// coordinate keeps the reader's place: the same user-space point stays at the window's+ /// top-left on the new page, as Acrobat does. A point past the end of the document scrolls+ /// as far as it can.+ pub fn go_to_dest(&mut self, page: usize, dest: DestView, info: &DocInfo) {+ // Read before the jump: it is where the reader is now.+ let kept = match dest {+ DestView::Xyz { left, top, .. } if left.is_none() || top.is_none() => self.place_at_corner(info),+ _ => None,+ };+ self.go_to_page(page);+ let page = self.current;+ self.goto_point = None;+ let Some(p) = info.pages.get(page) else { return };+ let point = |x: Option<f32>, y: Option<f32>| p.dest_fraction(x, y, self.rotation);+ // The window's top-left as far as pages go: its left edge is the gutter that keeps them+ // clear of the floating quick-action bar, so `left` 0 shows the page's edge beside it.+ let corner = vec2(SIDE, 0.0);+ let (fx, fy, rel) = match dest {+ DestView::Top => return,+ DestView::Xyz { left, top, zoom } => {+ if let Some(z) = zoom {+ self.zoom = z.clamp(0.08, 64.0);+ self.fit = Fit::None;+ self.zoom_anchor = None;+ }+ let [kept_left, kept_top] = kept.unwrap_or([None, None]);+ let [fx, fy] = point(left.or(kept_left), top.or(kept_top));+ (fx, fy, corner)+ }+ DestView::Fit => {+ self.fit = Fit::Page;+ return;+ }+ DestView::FitH { top } => {+ self.fit = Fit::Width;+ let [fx, fy] = point(None, top);+ (fx, fy, corner)+ }+ DestView::FitV { left } => {+ self.fit = Fit::Height;+ let [fx, fy] = point(left, None);+ (fx, fy, corner)+ }+ DestView::FitR { rect } => {+ let ([Some(ax), Some(ay)], [Some(bx), Some(by)]) = (point(Some(rect[0]), Some(rect[3])), point(Some(rect[2]), Some(rect[1]))) else {+ return;+ };+ // The rectangle as displayed, in points (it can be turned a quarter).+ let (dw, dh) = self.display_size(p);+ let (w, h) = ((ax - bx).abs() * dw, (ay - by).abs() * dh);+ if w >= 1.0 && h >= 1.0 && self.viewport_w >= 1.0 && self.viewport_h >= 1.0 {+ self.zoom = (self.viewport_w / (w * PT)).min(self.viewport_h / (h * PT)).clamp(0.08, 64.0);+ self.fit = Fit::None;+ self.zoom_anchor = None;+ }+ (Some((ax + bx) / 2.0), Some((ay + by) / 2.0), vec2(self.viewport_w, self.viewport_h) / 2.0)+ }+ };+ if fx.is_some() || fy.is_some() {+ self.goto_point = Some((page, fx, fy, rel));+ }+ }++ /// Next page (`true`) or previous page. In two-page view this moves a whole spread: the other+ /// page of the spread is already on screen, so stepping to it wouldn't move the view (#70).+ pub fn step_page(&mut self, forward: bool) {+ let c = self.current;+ let last = self.page_count.saturating_sub(1);+ let (target, first) = match self.layout {+ PageLayout::TwoUp => {+ let first = self.spread_first(c);+ let target = match (forward, self.cover && c == 0) {+ (true, true) => 1,+ (true, false) => first.saturating_add(2),+ (false, _) if self.cover && first <= 1 => 0,+ (false, _) => first.saturating_sub(2),+ };+ (target, first)+ }+ PageLayout::Single if forward => (c + 1, c),+ PageLayout::Single => (c.saturating_sub(1), c),+ };+ // Past either end there is nowhere to go: stay put rather than re-align the view, which+ // would scroll the page back to its top.+ if if forward { target > last } else { first == 0 } {+ return;+ }+ self.go_to_page(target);+ }++ /// Page-editor focus and drafts belong to a document, even while another tab is active.+ pub(crate) fn page_input_id(&self) -> egui::Id {+ egui::Id::unique(("page-input", self.id.0))+ }++ /// The idle page box and unchanged-input lookup share the same label fallback.+ pub(crate) fn current_page_label(&self, label: Option<&str>) -> String {+ label.filter(|l| !l.is_empty()).map(str::to_owned).unwrap_or_else(|| (self.current + 1).to_string())+ }++ /// Retain the current page when `typed` exactly matches its displayed label, even if+ /// another page has that label. Otherwise resolve a trimmed label (case-insensitive),+ /// then a physical page number. `false` when it names no page.+ pub fn go_to_typed(&mut self, typed: &str, labels: &[String]) -> bool {+ // Compare the displayed value before trimming: a label may itself contain spaces.+ // Repeated labels occur in restarted sections and prefix-only ranges.+ if self.current < self.page_count && self.current_page_label(labels.get(self.current).map(String::as_str)) == typed {+ return true;+ }+ let t = typed.trim();+ let page = labels+ .iter()+ .position(|l| !l.is_empty() && l.eq_ignore_ascii_case(t))+ .or_else(|| t.parse::<usize>().ok().filter(|n| *n >= 1).map(|n| n - 1));+ match page {+ Some(p) if p < self.page_count => {+ self.go_to_page(p);+ true+ }+ _ => false,+ }+ }++ /// View ▸ Page navigation ▸ Previous view (`false`) / Next view (`true`).+ pub fn view_history(&mut self, forward: bool) -> bool {+ let has_target = if forward { !self.forward.is_empty() } else { !self.back.is_empty() };+ if !has_target {+ return false;+ }+ self.end_find_following();+ let (from, to) = if forward { (&mut self.forward, &mut self.back) } else { (&mut self.back, &mut self.forward) };+ let Some(page) = from.pop() else { return false };+ to.push(self.current);+ let page = page.min(self.page_count.saturating_sub(1));+ self.goto = Some((page, 0.0));+ self.current = page;+ self.reset_coarse_state();+ true+ }++ /// One wheel event in a non-continuous view, where the wheel turns pages or spreads (the+ /// rules are in `wheel_pager`): `dy` is its vertical delta (negative scrolls down) and `now`+ /// is egui time. With `can_turn` false the gesture is followed but the page stays. Returns+ /// whether the page turned.+ pub fn single_page_wheel(&mut self, unit: egui::MouseWheelUnit, dy: f32, phase: egui::TouchPhase, now: f64, can_turn: bool) -> bool {+ if self.continuous {+ return false;+ }+ let Some(forward) = self.wheel.feed(unit, dy, phase, now, can_turn) else { return false };+ let before = self.current;+ self.step_page(forward);+ self.current != before+ }++ /// One wheel event in a non-continuous view whose page is taller than the window, where the+ /// wheel pans (#1924). Once the view is at the bottom (top) edge, scrolling on turns to the+ /// next (previous) page, which shows its top (bottom). A smooth gesture that panned the page+ /// has to end first (see `WheelPager::feed_edge`). `can_turn` is false when something else+ /// owns the wheel. Returns whether the page turned.+ pub fn single_page_wheel_edge(&mut self, unit: egui::MouseWheelUnit, dy: f32, phase: egui::TouchPhase, now: f64, can_turn: bool) -> bool {+ if self.continuous {+ return false;+ }+ // Only an up-to-date view counts: the page drawn is the shown one, with no jump pending.+ let edge = self.goto.is_none()+ && self.goto_point.is_none()+ && self.single_edges.is_some_and(|(page, top, bottom)| page == self.current && if dy < 0.0 { bottom } else { top });+ let Some(forward) = self.wheel.feed_edge(unit, dy, phase, now, can_turn && edge) else { return false };+ let before = self.current;+ self.step_page(forward);+ if self.current == before {+ return false;+ }+ if !forward {+ // Going back lands on the bottom of the previous page.+ self.goto = Some((self.current, 1.0));+ }+ self.single_edges = None;+ true+ }+}++pub fn shortcuts(view: &mut DocView, ctx: &egui::Context, speed: crate::scroll_speed::ScrollSpeed) {+ use egui::{Key, KeyboardShortcut, Modifiers};+ if ctx.input_mut(|i| i.consume_shortcut(&KeyboardShortcut::new(Modifiers::COMMAND, Key::F))) {+ view.open_find();+ }+ let cmd = |k| KeyboardShortcut::new(Modifiers::COMMAND, k);+ let pressed = |s: KeyboardShortcut| ctx.input_mut(|i| i.consume_shortcut(&s));+ // ⌘G / ⇧⌘G step through the matches from the find field too, as in Acrobat and Preview+ // (#2669): ahead of the text-input check, but only while there is a search to step.+ if view.find.is_some() {+ if pressed(KeyboardShortcut::new(Modifiers::COMMAND | Modifiers::SHIFT, Key::G)) {+ view.find_step(false);+ } else if pressed(cmd(Key::G)) {+ view.find_step(true);+ }+ }+ // A focused check box or radio button holds egui's keyboard focus only for Space, and a+ // radio button for the arrows that move within its group: the other page keys still work.+ let form_box = view.forms.keys.filter(|(id, _)| ctx.memory(|m| m.focused()) == Some(*id));+ if ctx.egui_wants_keyboard_input() && form_box.is_none() {+ return;+ }+ let arrows = !form_box.is_some_and(|(_, radio)| radio);+ // Rotation first: egui matches ⌘+ loosely with respect to Shift.+ if pressed(KeyboardShortcut::new(Modifiers::COMMAND | Modifiers::SHIFT, Key::Plus))+ || pressed(KeyboardShortcut::new(Modifiers::COMMAND | Modifiers::SHIFT, Key::Equals))+ {+ view.rotate_view(true);+ }+ if pressed(KeyboardShortcut::new(Modifiers::COMMAND | Modifiers::SHIFT, Key::Minus)) {+ view.rotate_view(false);+ }+ // In the page grid ⌘+ / ⌘− / ⌘0 size its pages instead (looking is always allowed).+ let (zoom_in, zoom_out, zoom_reset) = (pressed(cmd(Key::Plus)) || pressed(cmd(Key::Equals)), pressed(cmd(Key::Minus)), pressed(cmd(Key::Num0)));+ if view.organize {+ if zoom_in {+ view.grid_zoom_request = Some(view.grid_zoom * GRID_ZOOM_STEP);+ }+ if zoom_out {+ view.grid_zoom_request = Some(view.grid_zoom / GRID_ZOOM_STEP);+ }+ if zoom_reset {+ view.grid_zoom_request = Some(1.0);+ }+ } else {+ if zoom_in {+ view.zoom_step(true);+ }+ if zoom_out {+ view.zoom_step(false);+ }+ if zoom_reset {+ view.fit = Fit::Page;+ view.goto = Some((view.current, 0.0));+ }+ }+ if pressed(cmd(Key::Num1)) {+ view.set_zoom(1.0);+ }+ if pressed(cmd(Key::Num2)) {+ view.fit = Fit::Width;+ view.goto = Some((view.current, 0.0));+ }+ if pressed(cmd(Key::OpenBracket)) {+ view.view_history(false);+ }+ if pressed(cmd(Key::CloseBracket)) {+ view.view_history(true);+ }+ let key = |k| (arrows || !matches!(k, Key::ArrowLeft | Key::ArrowRight | Key::ArrowUp | Key::ArrowDown)) && ctx.input(|i| i.key_pressed(k));+ // An open menu takes Escape first and closes; the selection stays for the next one (#3535).+ if key(Key::Escape) && !egui::Popup::is_any_open(ctx) {+ if view.camera.is_some() || view.camera_done.is_some() {+ view.pending_action = Some(ViewAction::CancelCamera);+ } else if view.selection.is_some() || view.all_text {+ view.selection = None;+ view.all_text = false;+ } else {+ view.find = None;+ }+ }+ if key(Key::Home) {+ view.go_to_page(0);+ }+ if key(Key::End) {+ view.go_to_page(usize::MAX);+ }+ // Full screen: Space and Enter go forward a page and Backspace back, as in Acrobat (the+ // arrows and Page Up / Page Down already turn pages where nothing scrolls, below).+ if view.presentation.is_some() {+ if key(Key::Space) || key(Key::Enter) {+ view.step_page(true);+ }+ if key(Key::Backspace) {+ view.step_page(false);+ }+ }+ // As in Acrobat: → / ← go to the next / previous page in every layout (#185), and so do+ // ⌘Page Down / ⌘Page Up, or plain Page Down / Page Up in single-page view.+ let command = ctx.input(|i| i.modifiers.command);+ let scrolls = view.continuous;+ if key(Key::ArrowRight) || (key(Key::PageDown) && (command || !scrolls)) {+ view.step_page(true);+ }+ if key(Key::ArrowLeft) || (key(Key::PageUp) && (command || !scrolls)) {+ view.step_page(false);+ }+ // ↓ / ↑ scroll a line, and Page Down / Page Up a screen where the pages scroll. In+ // single-page view, ↓ / ↑ turn the page once there is nothing left to scroll that way, as+ // the wheel does (#273): always on a page that fits.+ // The Scroll speed preference sets how far ↓ / ↑ go as well as the wheel (#985); Page Down /+ // Page Up keep a screen.+ if !command {+ let line = KEY_SCROLL_LINE * speed.factor();+ let screen = (view.viewport_h - KEY_SCROLL_LINE).max(KEY_SCROLL_LINE);+ let steps = [(Key::ArrowDown, line), (Key::ArrowUp, -line), (Key::PageDown, screen), (Key::PageUp, -screen)];+ for (k, by) in steps {+ let arrow = matches!(k, Key::ArrowDown | Key::ArrowUp);+ if !key(k) || !(scrolls || arrow) {+ continue;+ }+ let forward = k == Key::ArrowDown;+ // Only an up-to-date view counts: the page drawn is the current one, with no jump pending.+ let at_end = !scrolls+ && view.goto.is_none()+ && view.single_edges.is_some_and(|(page, top, bottom)| page == view.current && if forward { bottom } else { top });+ if at_end {+ let before = view.current;+ view.step_page(forward);+ if !forward && view.current != before {+ // Going back up lands on the bottom of the previous page.+ view.goto = Some((view.current, 1.0));+ }+ view.single_edges = None;+ } else {+ view.key_scroll += by;+ }+ }+ }+}++/// How far ↓ / ↑ scroll at Normal speed (Scroll speed halves or doubles it). Page Down / Page Up+/// keep this much of the previous screen in view.+const KEY_SCROLL_LINE: f32 = 40.0;diff --git a/crates/ui-egui/src/canvas/organize.rs b/crates/ui-egui/src/canvas/organize.rsnew file mode 100644index 000000000..3eae2cc37--- /dev/null+++ b/crates/ui-egui/src/canvas/organize.rs@@ -0,0 +1,535 @@+use super::cache::{GRID_TAG, thumbnail_density, thumbnail_rows, thumbnail_scale};+use super::zoom::{GRID_ZOOM_RANGE, GRID_ZOOM_STEP};+use super::*;++/// How far a sharp grid render may be from the size drawn before it is redone: a pinch changes+/// the size on every frame, and a slightly soft or slightly large image is fine meanwhile.+const GRID_SHARP: std::ops::RangeInclusive<f32> = 0.9..=1.6;++/// Whether an image `have` device pixels wide is good enough to draw `want` pixels wide.+pub(super) fn sharp_enough(have: u32, want: f32) -> bool {+ want > 0.0 && GRID_SHARP.contains(&(have as f32 / want))+}++impl DocView {+ /// Open Organize Pages on the page being read (issue #1910). An empty selection means the+ /// current page, so a selection left from earlier that does not include it is dropped, and+ /// the grid scrolls its cell into view. Every way into the grid goes through here; closing+ /// it is a plain `organize = false`.+ pub fn open_organize(&mut self) {+ self.organize = true;+ if !self.selected.is_empty() && !self.selected.contains(&self.current) {+ self.clear_page_selection(Some(self.current));+ }+ self.grid_reveal = Some(self.current);+ }++ /// Pages an organize command acts on: the selection, or the current page.+ pub fn target_pages(&self) -> Vec<usize> {+ if self.selected.is_empty() { vec![self.current] } else { self.selected.iter().copied().collect() }+ }++ pub fn select_pages(&mut self, pages: &[usize]) {+ self.selected = pages.iter().copied().filter(|p| *p < self.page_count).collect();+ if let Some(first) = self.selected.first() {+ self.current = *first;+ }+ }++ /// A click on page `i`'s thumbnail, in the organize grid or the Pages panel. ⇧ selects the+ /// range from the anchor (or the current page); ⌘/Ctrl toggles the page; a plain click+ /// selects only it. `seed_current` is for the Pages panel, where an empty selection means+ /// the current page: the first ⌘-click on another page keeps the current one selected too.+ pub fn click_page(&mut self, i: usize, modifiers: egui::Modifiers, seed_current: bool) {+ if i >= self.page_count {+ return;+ }+ if modifiers.shift {+ let a = self.select_anchor.unwrap_or(self.current);+ self.selected = (a.min(i)..=a.max(i)).collect();+ } else if modifiers.command {+ if seed_current && self.selected.is_empty() && i != self.current {+ self.selected.insert(self.current);+ }+ if !self.selected.remove(&i) {+ self.selected.insert(i);+ }+ self.select_anchor = Some(i);+ } else {+ self.selected = [i].into();+ self.select_anchor = Some(i);+ }+ }++ /// Drop the page selection; a later ⇧-click ranges from `anchor`.+ pub fn clear_page_selection(&mut self, anchor: Option<usize>) {+ self.selected.clear();+ self.select_anchor = anchor.filter(|a| *a < self.page_count);+ }+}++/// Where a page of `page` size (points, as shown: after its rotation) is drawn in the grid cell+/// `cell`: as large as the picture area allows and centred in it, so a landscape or rotated page+/// fills the cell's width in its middle, as Acrobat draws it, instead of a small strip at the top.+/// The picture area leaves room for the page number and actions below. Its sides narrow only when+/// a picture that wide would reach the selection checkbox in the cell's corner.+pub(crate) fn grid_page_rect(cell: Rect, page: Vec2) -> Rect {+ let area = Rect::from_min_max(pos2(cell.left(), cell.top() + 16.0), pos2(cell.right(), cell.bottom() - 72.0));+ // A page size from a damaged file can be zero, NaN or infinite; draw such a page square.+ let side = |v: f32| if v.is_finite() { v.max(1.0) } else { 1.0 };+ let (w, h) = (side(page.x), side(page.y));+ let fit = |margin: f32| {+ let s = ((area.width() - 2.0 * margin).max(1.0) / w).min(area.height().max(1.0) / h);+ Rect::from_center_size(area.center(), vec2(w * s, h * s))+ };+ let wide = fit(16.0);+ // The checkbox sits at (8, 8)-(28, 28) from the cell's corner; keep 4 px clear of it.+ let checkbox = Rect::from_min_size(cell.min + vec2(8.0, 8.0), Vec2::splat(20.0)).expand(4.0);+ if wide.intersects(checkbox) { fit(30.0) } else { wide }+}++/// The organize toolbar: page operations on the selection (Acrobat's Organize Pages bar).+fn organize_toolbar(view: &mut DocView, info: &DocInfo, editable: bool, dirty: bool, unobstructed: bool, ui: &mut egui::Ui, t: &Tokens) {+ let targets = view.target_pages();+ let n = info.pages.len();+ let (first, last) = (targets.first().copied().unwrap_or(0), targets.last().copied().unwrap_or(0));+ egui::Frame::NONE.fill(t.chrome).inner_margin(egui::Margin::symmetric(16, 8)).show(ui, |ui| {+ ui.horizontal(|ui| {+ ui.spacing_mut().item_spacing.x = 4.0;+ let label = match view.selected.len() {+ 0 => crate::i18n::fmt(tl!("Page {p} of {n}"), &[("p", &(view.current + 1).to_string()), ("n", &n.to_string())]),+ 1 => tl!("1 page selected").to_string(),+ k => crate::i18n::fmt(tl!("{n} pages selected"), &[("n", &k.to_string())]),+ };+ // Fixed width so the buttons never shift as the selection text changes.+ ui.add_sized([150.0, 30.0], egui::Label::new(egui::RichText::new(label).font(theme::medium(13.0)).color(t.text_muted)).truncate());+ ui.add_enabled_ui(editable, |ui| {+ ui.add_space(8.0);+ if ui.add_enabled_ui(first > 0, |ui| icons::button(ui, "chevron-left", 30.0, false, tl!("Move earlier"))).inner.clicked() {+ view.pending_edit = Some(Edit::MovePages { pages: targets.clone(), to: first - 1 });+ }+ if ui.add_enabled_ui(last + 1 < n, |ui| icons::button(ui, "chevron-right", 30.0, false, tl!("Move later"))).inner.clicked() {+ view.pending_edit = Some(Edit::MovePages { pages: targets.clone(), to: first + 1 });+ }+ });+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {+ if widgets::ghost_button(ui, "x", tl!("Close")).on_hover_text(tl!("Back to the document")).clicked() {+ view.organize = false;+ }+ // What the grid shows is what is saved.+ let save = ui.add_enabled_ui(dirty, |ui| widgets::pill_button(ui, tl!("Save pages"), true)).inner;+ if save.on_hover_text(tl!("Save these pages as one PDF")).on_disabled_hover_text(tl!("No changes to save")).clicked() {+ view.pending_action = Some(ViewAction::Save);+ }+ ui.add_space(8.0);+ // Page size in the grid (right to left: in, the percentage, out).+ let zoom = view.grid_zoom;+ if ui+ .add_enabled_ui(zoom < *GRID_ZOOM_RANGE.end(), |ui| icons::button(ui, "zoom-in", 30.0, false, tl!("Larger pages")))+ .inner+ .clicked()+ {+ view.grid_zoom_request = Some(zoom * GRID_ZOOM_STEP);+ }+ let percent = egui::Button::new(egui::RichText::new(format!("{:.0}%", zoom * 100.0)).font(theme::medium(12.0)).color(t.text_muted))+ .frame(false);+ let percent = ui.add_sized([44.0, 30.0], percent);+ percent.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tl!("Reset page size")));+ if percent.on_hover_text(tl!("Reset page size")).clicked() {+ view.grid_zoom_request = Some(1.0);+ }+ if ui+ .add_enabled_ui(zoom > *GRID_ZOOM_RANGE.start(), |ui| icons::button(ui, "zoom-out", 30.0, false, tl!("Smaller pages")))+ .inner+ .clicked()+ {+ view.grid_zoom_request = Some(zoom / GRID_ZOOM_STEP);+ }+ });+ });+ });+ // Keys act on the selection unless a text field or a dialog has them (Delete under+ // Preferences deleted the selected pages).+ if editable && unobstructed && !ui.ctx().egui_wants_keyboard_input() {+ use egui::{Key, Modifiers};+ let (del, esc) = ui.input_mut(|i| {+ (+ i.consume_key(Modifiers::NONE, Key::Delete) || i.consume_key(Modifiers::NONE, Key::Backspace),+ i.consume_key(Modifiers::NONE, Key::Escape),+ )+ });+ // ⌘C / ⌘X / ⌘V copy, cut and paste pages (egui delivers them as clipboard events).+ let (copy, cut, paste) = ui.input(|i| {+ let any = |f: &dyn Fn(&egui::Event) -> bool| i.events.iter().any(f);+ (any(&|e| matches!(e, egui::Event::Copy)), any(&|e| matches!(e, egui::Event::Cut)), any(&|e| matches!(e, egui::Event::Paste(_))))+ });+ if copy || cut {+ view.pending_action = Some(ViewAction::CopyPages { cut });+ }+ if paste {+ view.pending_action = Some(ViewAction::PastePages);+ }+ if del && targets.len() < n {+ view.pending_edit = Some(Edit::DeletePages { pages: targets });+ }+ if esc {+ view.selected.clear();+ }+ }+}++/// Organize pages: a thumbnail grid (Acrobat's Organize Pages view). Click selects, ⌘-click+/// toggles, ⇧-click extends; double-click opens the page.+/// The gap (0 = before the first page, n = after the last) the pointer points at in the grid.+pub(crate) fn drop_gap(cells: &[(usize, Rect)], p: Pos2) -> Option<usize> {+ let (i, r) = cells.iter().min_by(|(_, a), (_, b)| a.distance_sq_to_pos(p).total_cmp(&b.distance_sq_to_pos(p)))?;+ Some(if p.x < r.center().x { *i } else { i + 1 })+}++/// Ctrl (Option on macOS) held when a page drag drops copies the dragged pages into the gap+/// instead of moving them, as Acrobat's Organize Pages does.+///+/// The OS comes from the context, not `cfg!`: the wasm build runs on macOS too, where+/// `cfg!(target_os = "macos")` is false, so Option has to copy there as well (#3092 review).+fn copy_modifier(ctx: &egui::Context, m: &egui::Modifiers) -> bool {+ if crate::commands::mac_shortcuts(ctx) { m.alt } else { m.ctrl }+}++/// A "+" on a gap of the page grid: insert files there. Returns whether it was clicked.+fn gap_button(ui: &mut egui::Ui, gap: usize, at: Pos2, height: f32, label: String, t: &Tokens) -> bool {+ let resp = ui.interact(Rect::from_center_size(at, Vec2::splat(22.0)), ui.scope_id().with(("org-gap", gap)), Sense::click());+ resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, label.clone()));+ let hot = resp.hovered();+ if hot {+ ui.painter().line_segment([pos2(at.x, at.y - height / 2.0), pos2(at.x, at.y + height / 2.0)], Stroke::new(3.0, t.accent));+ }+ ui.painter().circle(at, 9.0, if hot { t.accent } else { t.chrome }, Stroke::new(1.0, if hot { t.accent } else { t.border }));+ let ink = Stroke::new(1.5, if hot { Color32::WHITE } else { t.text_muted });+ ui.painter().line_segment([at - vec2(4.0, 0.0), at + vec2(4.0, 0.0)], ink);+ ui.painter().line_segment([at - vec2(0.0, 4.0), at + vec2(0.0, 4.0)], ink);+ resp.on_hover_text(label).clicked()+}++pub(super) fn organize_grid(view: &mut DocView, info: &DocInfo, editable: bool, dirty: bool, unobstructed: bool, ui: &mut egui::Ui, t: &Tokens) {+ let ppp = ui.ctx().pixels_per_point();+ // The page image scales with the zoom; the padding and the page number don't.+ let cell = vec2(146.0 * view.grid_zoom + 44.0, 194.0 * view.grid_zoom + 88.0);+ let anchor = view.grid_anchor.take();+ let reveal = view.grid_reveal.take();+ let mut open_page = None;+ organize_toolbar(view, info, editable, dirty, unobstructed, ui, t);+ let viewport = ui.available_rect_before_wrap();+ view.viewport_screen = viewport;+ let auto_delta = if unobstructed {+ view.auto_scroll.update(ui, viewport, true)+ } else {+ view.auto_scroll.cancel();+ Vec2::ZERO+ };+ let middle_gesture = view.auto_scroll.blocks_input();+ let mut cells: Vec<(usize, Rect)> = Vec::new();+ // The pages in view that are drawn larger than their thumbnails, and those of them that+ // need a sharper render than they have. The width is the size drawn, in device pixels.+ let (mut in_view, mut sharper): (Vec<(usize, f32)>, Vec<RenderRequest>) = (Vec::new(), Vec::new());+ // The source cell can scroll out of the virtualized rows during a drag.+ let mut drop = view.org_drag.is_some() && ui.input(|i| i.pointer.primary_released());+ egui::ScrollArea::vertical().auto_shrink([false, false]).show_viewport(ui, |ui, clip| {+ if middle_gesture {+ let opacity = ui.opacity();+ ui.disable();+ ui.set_opacity(opacity);+ }+ if auto_delta != Vec2::ZERO {+ ui.scroll_with_delta_animation(auto_delta, egui::style::ScrollAnimation::none());+ }+ ui.add_space(20.0);+ let cols = ((ui.available_width() - 40.0) / cell.x).floor().max(1.0) as usize;+ let rows = info.pages.len().div_ceil(cols);+ let left = (ui.available_width() - cols as f32 * cell.x) / 2.0;+ let (grid, _) = ui.allocate_exact_size(vec2(ui.available_width(), rows as f32 * cell.y), Sense::hover());+ // The page Organize opened on may lie in a row the virtualized grid has not laid out,+ // so its cell is computed rather than found.+ if let Some(page) = reveal.filter(|p| *p < info.pages.len()) {+ let row = page / cols;+ let col = page % cols;+ let c = Rect::from_min_size(pos2(grid.left() + left + col as f32 * cell.x, grid.top() + row as f32 * cell.y), cell);+ ui.scroll_to_rect_animation(c, Some(egui::Align::Center), egui::style::ScrollAnimation::none());+ }+ for row in thumbnail_rows(clip.top() - 20.0, clip.bottom() - 20.0, cell.y, rows) {+ let row_rect = Rect::from_min_size(grid.min + vec2(0.0, row as f32 * cell.y), vec2(grid.width(), cell.y));+ for col in 0..cols {+ let i = row * cols + col;+ let Some(p) = info.pages.get(i) else { break };+ let c = Rect::from_min_size(pos2(row_rect.left() + left + col as f32 * cell.x, row_rect.top()), cell);+ view.need_thumbnail(i, c.intersects(ui.clip_rect()));+ let resp = ui.interact(c, ui.scope_id().with(("org", i)), if editable { Sense::click_and_drag() } else { Sense::click() });+ cells.push((i, c));+ if let Some((_, above)) = anchor.filter(|(page, _)| *page == i) {+ ui.scroll_to_rect_animation(c.translate(vec2(0.0, -above)), Some(egui::Align::Min), egui::style::ScrollAnimation::none());+ }+ // Drag pages to move them (the selection, or the page grabbed).+ if resp.drag_started() {+ if !view.selected.contains(&i) {+ view.selected = [i].into();+ view.select_anchor = Some(i);+ }+ let mut pages: Vec<usize> = view.selected.iter().copied().collect();+ pages.sort_unstable();+ view.org_drag = Some(pages);+ }+ if resp.drag_stopped() {+ drop = true;+ }+ let page_label = crate::i18n::fmt(tl!("Page {label}"), &[("label", &p.label)]);+ resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::CheckBox, true, view.selected.contains(&i), page_label.clone()));+ let pr = grid_page_rect(c, vec2(p.width, p.height));+ let size = pr.size();+ let selected = view.selected.contains(&i) || (view.selected.is_empty() && i == view.current);+ if selected || resp.hovered() {+ ui.painter().rect_filled(c.shrink(6.0), CornerRadius::same(8), if selected { t.accent_soft } else { t.hover });+ }+ if view.selected.contains(&i) {+ ui.painter().rect_stroke(c.shrink(6.0), CornerRadius::same(8), Stroke::new(1.5, t.accent), egui::StrokeKind::Inside);+ }+ ui.painter().rect_filled(pr.translate(vec2(0.0, 1.5)), CornerRadius::same(1), t.page_shadow);+ ui.painter().rect_filled(pr, CornerRadius::ZERO, Color32::WHITE);+ // A page drawn larger than its thumbnail gets a render at the size drawn, while+ // it is in view; until that arrives the thumbnail stands in.+ let want = size.x * ppp;+ let thumb = view.thumbs.get(&i).map(|t| &t.tex);+ let thumb_ok = thumb.is_some_and(|t| t.size()[0] as f32 >= want * GRID_SHARP.start());+ let sharp = view.grid_pages.get(&i).filter(|_| !thumb_ok);+ if !thumb_ok && ui.is_rect_visible(c) {+ in_view.push((i, want));+ if !sharp.is_some_and(|(w, _)| sharp_enough(*w, want)) && !view.errors.contains_key(&i) {+ sharper.push(RenderRequest {+ page: i,+ kind: RequestKind::Pixels,+ tile: None,+ scale: want / p.width.max(1.0),+ tag: GRID_TAG,+ // Grid cells are previews: tiny images are skipped for them.+ preview: true,+ });+ }+ }+ if let Some(tex) = sharp.map(|(_, t)| t).or(thumb) {+ ui.painter().image(tex.id(), pr, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE);+ }+ ui.painter().rect_stroke(pr, CornerRadius::ZERO, Stroke::new(1.0, t.border), egui::StrokeKind::Outside);+ let label_font = theme::medium(12.0);+ let label_w = (c.width() - 12.0).max(0.0);+ let page_label = crate::widgets::fit_line(&p.label, label_w, |s| crate::widgets::text_width(ui, s, &label_font));+ let label_pos = pos2(c.center().x, c.bottom() - 48.0);+ ui.painter().with_clip_rect(Rect::from_center_size(label_pos, vec2(label_w, 18.0))).text(+ label_pos,+ Align2::CENTER_CENTER,+ page_label,+ label_font,+ t.text_muted,+ );+ // The checkbox toggles just this page without requiring a modifier. Keep it+ // outside the page image, including on very tall or wide pages.+ let mut checked = view.selected.contains(&i);+ let check_rect = Rect::from_min_size(c.min + vec2(8.0, 8.0), Vec2::splat(20.0));+ let check = ui.push_id(("org-check", i), |ui| ui.put(check_rect, widgets::checkbox_without_text(&mut checked))).inner;+ let label = crate::i18n::fmt(tl!("Select page {label}"), &[("label", &p.label)]);+ check.widget_info(|| egui::WidgetInfo::selected(egui::Role::CheckBox, true, checked, label.clone()));+ if check.on_hover_text(label).changed() {+ view.click_page(i, egui::Modifiers::COMMAND, false);+ // The document shows the page picked here when the grid closes, as after a+ // Pages-panel click, so reopening the grid keeps the pick (issue #1910).+ view.go_to_page(i);+ }+ // Local actions always target the labelled page. The toolbar above the grid+ // remains the place for actions on the whole selection.+ if selected || resp.contains_pointer() || resp.has_focus() {+ let actions = Rect::from_center_size(pos2(c.center().x, c.bottom() - 24.0), vec2(84.0, 26.0));+ ui.scope_builder(+ egui::UiBuilder::new().id_salt(("org-actions", i)).max_rect(actions).layout(egui::Layout::left_to_right(egui::Align::Center)),+ |ui| {+ ui.spacing_mut().item_spacing.x = 3.0;+ ui.add_enabled_ui(editable, |ui| {+ for (icon, degrees, key) in+ [("rotate-ccw", -90, "Rotate page {label} counterclockwise"), ("rotate-cw", 90, "Rotate page {label} clockwise")]+ {+ let label = crate::i18n::fmt(tl!(key), &[("label", &p.label)]);+ if icons::button(ui, icon, 26.0, false, &label).clicked() {+ view.pending_edit = Some(Edit::RotatePages { pages: vec![i], degrees });+ }+ }+ let label = crate::i18n::fmt(tl!("Delete page {label}"), &[("label", &p.label)]);+ if ui.add_enabled_ui(info.pages.len() > 1, |ui| icons::button(ui, "trash-2", 26.0, false, &label)).inner.clicked() {+ view.pending_edit = Some(Edit::DeletePages { pages: vec![i] });+ }+ });+ },+ );+ }+ if resp.clicked() {+ let m = ui.input(|i| i.modifiers);+ view.click_page(i, m, false);+ view.go_to_page(i);+ }+ if resp.double_clicked() {+ open_page = Some(i);+ }+ // Right-click: Extract, Replace, Cut, Copy, Paste (on the selection, or this page).+ resp.context_menu(|ui| {+ if !view.selected.contains(&i) {+ view.selected = [i].into();+ view.go_to_page(i);+ }+ if ui.button(tl!("Extract pages")).clicked() {+ view.pending_action = Some(ViewAction::Extract);+ ui.close();+ }+ if ui.button(tl!("Split document…")).clicked() {+ view.pending_action = Some(ViewAction::SplitBeforeSelected);+ ui.close();+ }+ if ui.add_enabled(editable, egui::Button::new(tl!("Replace pages…"))).clicked() {+ view.pending_action = Some(ViewAction::ReplacePages);+ ui.close();+ }+ ui.separator();+ if ui.add_enabled(editable, egui::Button::new(tl!("Cut"))).clicked() {+ view.pending_action = Some(ViewAction::CopyPages { cut: true });+ ui.close();+ }+ if ui.button(tl!("Copy")).clicked() {+ view.pending_action = Some(ViewAction::CopyPages { cut: false });+ ui.close();+ }+ if ui.add_enabled(editable, egui::Button::new(tl!("Paste after"))).clicked() {+ view.pending_action = Some(ViewAction::PastePages);+ ui.close();+ }+ });+ }+ }+ // Between pages (and at both ends): insert files right there.+ if editable && !middle_gesture && view.org_drag.is_none() {+ let mid = |r: &Rect| r.top() + 16.0 + (cell.y - 88.0) / 2.0;+ for (i, c) in &cells {+ let label = info+ .pages+ .get(*i)+ .map(|p| crate::i18n::fmt(tl!("Insert a file before page {label}"), &[("label", &p.label)]))+ .unwrap_or_default();+ if gap_button(ui, *i, pos2(c.left(), mid(c)), cell.y - 88.0, label, t) {+ view.pending_action = Some(ViewAction::InsertFromFileAt(*i));+ }+ }+ if let Some((i, c)) = cells.last()+ && i + 1 == info.pages.len()+ && gap_button(ui, i + 1, pos2(c.right(), mid(c)), cell.y - 88.0, tl!("Insert a file at the end").to_string(), t)+ {+ view.pending_action = Some(ViewAction::InsertFromFileAt(i + 1));+ }+ }+ // While dragging: the gap the pages would go to, drawn as a bar.+ if let (Some(pages), Some(p)) = (view.org_drag.clone(), ui.input(|i| i.pointer.hover_pos())) {+ // Ctrl (Option on macOS) held over the drop copies the pages; see #2997.+ let copying = copy_modifier(ui.ctx(), &ui.input(|i| i.modifiers));+ if let Some(gap) = drop_gap(&cells, p) {+ let x = match cells.iter().find(|(i, _)| *i == gap) {+ Some((_, r)) => r.left() + 3.0,+ None => cells.last().map_or(0.0, |(_, r)| r.right() - 3.0),+ };+ let row = cells.iter().find(|(i, _)| *i == gap).or(cells.last()).map(|(_, r)| r.y_range()).unwrap_or(egui::Rangef::new(0.0, 0.0));+ ui.painter().line_segment([pos2(x, row.min + 10.0), pos2(x, row.max - 10.0)], Stroke::new(3.0, t.accent));+ let mut text_at = p + vec2(14.0, 14.0);+ if copying {+ // A "+" by the pointer: this drop copies the pages, it doesn't move them.+ let badge = p + vec2(12.0, 12.0);+ ui.painter().circle(badge, 9.0, t.accent, Stroke::new(1.0, t.accent));+ let ink = Stroke::new(1.5, Color32::WHITE);+ ui.painter().line_segment([badge - vec2(4.0, 0.0), badge + vec2(4.0, 0.0)], ink);+ ui.painter().line_segment([badge - vec2(0.0, 4.0), badge + vec2(0.0, 4.0)], ink);+ text_at.x += 18.0;+ }+ ui.painter().text(+ text_at,+ Align2::LEFT_TOP,+ if pages.len() == 1 { tl!("1 page").to_string() } else { crate::i18n::fmt(tl!("{n} pages"), &[("n", &pages.len().to_string())]) },+ theme::medium(12.0),+ t.accent_text,+ );+ }+ if drop {+ view.org_drag = None;+ if let Some(gap) = drop_gap(&cells, p) {+ if copying {+ // The copies land at the gap as it is: nothing leaves its place.+ view.pending_edit = Some(Edit::DuplicatePages { pages: pages.clone(), at: Some(gap) });+ view.selected = (gap..gap + pages.len()).collect();+ } else {+ // `to` counts positions without the moving pages.+ let to = gap - pages.iter().filter(|x| **x < gap).count();+ let first = pages[0];+ let contiguous = pages.windows(2).all(|w| w[1] == w[0] + 1);+ if !(contiguous && to == first) {+ view.pending_edit = Some(Edit::MovePages { pages: pages.clone(), to });+ view.selected = (to..to + pages.len()).collect();+ }+ }+ }+ }+ } else if drop {+ view.org_drag = None;+ }+ });+ // Files dragged in from outside go to the gap under the pointer. Some platforms don't say+ // where the pointer is until the files are dropped; then the whole grid is the target.+ let pointer = ui.input(|i| i.pointer.hover_pos()).filter(|p| viewport.contains(*p));+ view.grid_gap = pointer.filter(|_| editable && view.org_drag.is_none()).and_then(|p| drop_gap(&cells, p));+ if editable && ui.input(|i| !i.raw.hovered_files.is_empty()) {+ let painter = ui.painter().with_clip_rect(viewport);+ painter.rect_stroke(viewport.shrink(2.0), CornerRadius::same(6), Stroke::new(2.0, t.accent), egui::StrokeKind::Inside);+ if let Some(gap) = view.grid_gap {+ let at = cells.iter().find(|(i, _)| *i == gap).map(|(_, r)| (r.left() + 3.0, r.y_range()));+ if let Some((x, row)) = at.or(cells.last().map(|(_, r)| (r.right() - 3.0, r.y_range()))) {+ painter.line_segment([pos2(x, row.min + 10.0), pos2(x, row.max - 10.0)], Stroke::new(3.0, t.accent));+ }+ }+ // A "+" that follows the pointer.+ if let Some(p) = pointer {+ let at = p + vec2(16.0, 16.0);+ painter.circle_filled(at, 9.0, t.accent);+ painter.line_segment([at - vec2(4.0, 0.0), at + vec2(4.0, 0.0)], Stroke::new(1.5, Color32::WHITE));+ painter.line_segment([at - vec2(0.0, 4.0), at + vec2(0.0, 4.0)], Stroke::new(1.5, Color32::WHITE));+ }+ }+ view.auto_scroll.paint(ui, viewport);+ // Pinch, or Ctrl/⌘ with the wheel, zooms the grid about the page under the pointer.+ let pinch = crate::motion::zoom_delta(ui.ctx());+ if (pinch - 1.0).abs() > 0.001 && pointer.is_some() && !middle_gesture {+ view.grid_zoom_request = Some(view.grid_zoom * pinch);+ }+ if let Some(zoom) = view.grid_zoom_request.take() {+ let before = view.grid_zoom;+ view.set_grid_zoom(zoom);+ if view.grid_zoom != before {+ // Keep the page under the pointer (or else the first one in view) where it is.+ let under = pointer.and_then(|p| cells.iter().find(|(_, r)| r.contains(p)));+ let anchor = under.or_else(|| cells.iter().find(|(_, r)| r.bottom() > viewport.top()));+ view.grid_anchor = anchor.map(|(i, r)| (*i, r.top() - viewport.top()));+ ui.ctx().request_repaint();+ }+ }+ // When this frame's thumbnail will cover the cell, drop the sharp render without waiting+ // for that texture to arrive.+ let density = thumbnail_density(view.thumb_demand.len(), ppp);+ in_view.retain(|&(page, want)| {+ info.pages.get(page).is_none_or(|p| (device_pixels(p.width, thumbnail_scale(p.width, p.height, density)) as f32) < want * GRID_SHARP.start())+ });+ sharper.retain(|req| in_view.iter().any(|(page, _)| *page == req.page));+ view.grid_pages.retain(|page, _| in_view.iter().any(|(kept, _)| kept == page));+ // Sharp renders of the pages in view join this frame's demand ahead of the thumbnails.+ view.frame_queue.extend(sharper);+ if let Some(p) = open_page {+ view.organize = false;+ view.go_to_page(p);+ }+}diff --git a/crates/ui-egui/src/canvas/selection.rs b/crates/ui-egui/src/canvas/selection.rsnew file mode 100644index 000000000..43d5990c5--- /dev/null+++ b/crates/ui-egui/src/canvas/selection.rs@@ -0,0 +1,250 @@+use super::*;++/// A text selection on one page.+#[derive(Clone, Copy, Debug, PartialEq)]+pub(super) struct Selection {+ pub(super) page: usize,+ pub(super) span: Span,+}++#[derive(Clone, Copy, Debug, PartialEq)]+pub(super) enum Span {+ /// Reading order, between two glyph indices.+ Run { anchor: usize, head: usize },+ /// Column select (#740): the glyphs inside a rectangle in page view space, drawn from the+ /// corner the drag started at (`rect[0..2]`) to the pointer (`rect[2..4]`).+ Column { rect: [f32; 4] },+}++impl Selection {+ pub(super) fn run(page: usize, anchor: usize, head: usize) -> Self {+ Self { page, span: Span::Run { anchor, head } }+ }++ fn range(anchor: usize, head: usize) -> Range<usize> {+ anchor.min(head)..anchor.max(head).saturating_add(1)+ }++ /// One rectangle per selected piece of a line, in view space (highlighting, markup quads).+ pub(super) fn rects(&self, text: &PageText) -> Vec<[f32; 4]> {+ match self.span {+ Span::Run { anchor, head } => text.line_rects(Self::range(anchor, head)),+ Span::Column { rect } => text.glyph_rects(&text.glyphs_in(rect)),+ }+ }++ /// The selected text, as Copy puts it on the clipboard.+ pub(super) fn text(&self, text: &PageText) -> String {+ match self.span {+ Span::Run { anchor, head } => text.text_of(Self::range(anchor, head)),+ Span::Column { rect } => text.column_text(&text.glyphs_in(rect)),+ }+ }+}++/// The glyphs `clicks` quick clicks select around glyph `a`: two the word, three the line, more+/// the page.+pub(super) fn click_unit(text: &PageText, clicks: u32, a: usize) -> Option<(usize, usize)> {+ match clicks {+ 2 => text.word_at(a),+ 3 => text.line_at(a),+ _ => text.glyphs.len().checked_sub(1).map(|last| (0, last)),+ }+}++impl DocView {+ /// The text selection as markup quadrilaterals in user space: (page, quads).+ pub(crate) fn selection_quads(&self, info: &DocInfo) -> Option<(usize, Vec<[f64; 8]>)> {+ let s = self.selection?;+ let text = self.texts.get(&s.page)?;+ let page = info.pages.get(s.page)?;+ let quads: Vec<[f64; 8]> = s.rects(text).into_iter().map(|r| page.view_rect_to_quad(r)).collect();+ (!quads.is_empty()).then_some((s.page, quads))+ }++ pub(crate) fn clear_selection(&mut self) {+ self.selection = None;+ self.actions_dismissed = None;+ }++ /// Select text on `page` from glyph `from` to glyph `to` (tests and automation).+ pub fn select_text(&mut self, page: usize, from: usize, to: usize) {+ self.all_text = false;+ self.selection = Some(Selection::run(page, from, to));+ }++ /// Screen position of the centre of glyph `glyph` on `page`, if that page is on screen and its+ /// text layer is loaded (used by UI tests and automation to aim pointer input).+ pub fn glyph_screen_pos(&self, page: usize, glyph: usize) -> Option<Pos2> {+ let (_, xf) = self.screen_xforms.iter().find(|(p, _)| *p == page)?;+ let g = self.texts.get(&page)?.glyphs.get(glyph)?;+ Some(xf.view_rect(g.rect).center())+ }++ /// Selected text, if any (⌘C).+ /// The selected text: of the pages read so far, after Select All of the document (Copy reads+ /// the others, [`DocView::pages_without_text`]).+ pub fn selected_text(&self) -> Option<String> {+ if self.all_text {+ return Some(self.whole_text(&HashMap::new())).filter(|x| !x.is_empty());+ }+ let s = self.selection?;+ let t = self.texts.get(&s.page)?;+ Some(s.text(t)).filter(|x| !x.is_empty())+ }++ /// Select all: every page in Organize, or every word on the current page.+ pub fn select_all(&mut self) -> bool {+ if self.organize {+ self.selected = (0..self.page_count).collect();+ // Keep the current page as the anchor for the next Shift-click.+ self.select_anchor = (self.page_count > 0).then_some(self.current);+ return !self.selected.is_empty();+ }+ // Scrolling continuously, Select All takes the whole document's text (#2639); one page at+ // a time, the page shown.+ // Like the page's, true once some text is selected: the pages whose text isn't read yet are+ // read when the selection is copied.+ if self.continuous && self.page_count > 1 {+ self.selection = None;+ self.all_text = true;+ return self.selected_text().is_some();+ }+ self.all_text = false;+ let page = self.current;+ let Some(t) = self.texts.get(&page) else { return false };+ if t.glyphs.is_empty() {+ return false;+ }+ self.selection = Some(Selection::run(page, 0, t.glyphs.len() - 1));+ true+ }++ /// Pages whose text [`DocView::whole_text`] still needs: not read yet, nor failed.+ pub(crate) fn pages_without_text(&self) -> Vec<usize> {+ (0..self.page_count).filter(|p| !self.texts.contains_key(p) && !self.text_failed.contains(p)).collect()+ }++ /// The whole document's text in page order, one page after another on new lines, from the+ /// pages' text read so far and `more` (pages read for this, keyed by page).+ pub(crate) fn whole_text(&self, more: &HashMap<usize, Arc<PageText>>) -> String {+ let mut out = String::new();+ for p in 0..self.page_count {+ let Some(t) = self.texts.get(&p).or_else(|| more.get(&p)) else { continue };+ let text = t.text_of(0..t.glyphs.len());+ if text.is_empty() {+ continue;+ }+ if !out.is_empty() {+ out.push('\n');+ }+ out.push_str(&text);+ }+ out+ }+}++#[derive(Clone, Copy)]+enum SelectionAction {+ Note,+ Markup(comments::CommentTool),+ Replace,+ Copy,+}++/// Actions on an existing text selection, next to the selected words.+pub(super) fn selection_actions(+ ui: &mut egui::Ui,+ viewport: Rect,+ view: &mut DocView,+ info: &DocInfo,+ prefs: &comments::CommentPrefs,+ can_comment: bool,+ can_copy: bool,+) -> bool {+ if ui.input(|input| input.pointer.is_decidedly_dragging()) {+ return false;+ }+ let Some(selection) = view.selection else {+ view.actions_dismissed = None;+ return false;+ };+ if view.actions_dismissed == Some(selection) {+ return false;+ }+ let Some(text) = view.texts.get(&selection.page) else { return false };+ let Some(xf) = view.page_xform(selection.page) else { return false };+ let Some(last) = selection.rects(text).last().copied() else { return false };+ let selected = selection.text(text);+ if selected.is_empty() {+ return false;+ }+ let rect = xf.view_rect(last);+ if !viewport.intersects(rect) {+ return false;+ }+ let x = rect.left().clamp(viewport.left() + 8.0, (viewport.right() - 520.0).max(viewport.left() + 8.0));+ let y = if rect.bottom() + 48.0 < viewport.bottom() { rect.bottom() + 6.0 } else { (rect.top() - 44.0).max(viewport.top() + 6.0) };+ let mut chosen = None;+ egui::Area::new(egui::Id::unique(("text-selection-actions", view.id.0))).order(egui::Order::Foreground).fixed_pos(pos2(x, y)).show(+ ui.ctx(),+ |ui| {+ egui::Frame::popup(ui.style()).show(ui, |ui| {+ ui.horizontal(|ui| {+ for (label, action) in [+ (tl!("Add comment"), SelectionAction::Note),+ (tl!("Highlight"), SelectionAction::Markup(comments::CommentTool::Highlight)),+ (tl!("Underline"), SelectionAction::Markup(comments::CommentTool::Underline)),+ (tl!("Strikethrough"), SelectionAction::Markup(comments::CommentTool::StrikeOut)),+ (tl!("Replace text"), SelectionAction::Replace),+ ] {+ if ui.add_enabled(can_comment, egui::Button::new(label)).clicked() {+ chosen = Some(action);+ }+ }+ if ui.add_enabled(can_copy, egui::Button::new(tl!("Copy"))).clicked() {+ chosen = Some(SelectionAction::Copy);+ }+ });+ });+ },+ );+ let Some(action) = chosen else { return false };+ if let SelectionAction::Copy = action {+ // Copying closes the bar but keeps the words selected, for ⌘C or a second action.+ view.actions_dismissed = Some(selection);+ return true;+ }+ let Some((page, quads)) = view.selection_quads(info) else { return false };+ let last = quads.last().copied().unwrap_or_default();+ let at = [last[2].max(last[6]), last[1].max(last[3])];+ view.clear_selection();+ match action {+ SelectionAction::Note | SelectionAction::Replace => {+ if matches!(action, SelectionAction::Replace) {+ view.comments.replace = Some(quads);+ }+ view.comments.composer = Some(comments::Composer {+ page,+ at,+ kind: if matches!(action, SelectionAction::Replace) { comments::ComposerKind::Replace } else { comments::ComposerKind::Note },+ text: String::new(),+ focus: true,+ });+ }+ SelectionAction::Markup(tool) => {+ // Every markup button carries a markup tool; anything else adds nothing.+ let Some(kind) = tool.markup() else { return false };+ view.pending_edit = Some(Edit::AddAnnotation(pdfcraft_engine::NewAnnotation {+ page,+ shape: pdfcraft_engine::Shape::TextMarkup { kind, quads },+ style: prefs.style(tool),+ contents: String::new(),+ author: prefs.author.clone(),+ }));+ }+ // Copy is dispatched through the app after the view borrow ends.+ SelectionAction::Copy => {}+ }+ false+}diff --git a/crates/ui-egui/src/canvas/xform.rs b/crates/ui-egui/src/canvas/xform.rsnew file mode 100644index 000000000..24ff25f7d--- /dev/null+++ b/crates/ui-egui/src/canvas/xform.rs@@ -0,0 +1,151 @@+use super::*;++impl DocView {+ /// Where `page` is drawn on screen this frame (`None` when it is not on screen).+ pub fn page_screen_rect(&self, page: usize) -> Option<Rect> {+ self.screen_xforms.iter().find(|(p, _)| *p == page).map(|(_, xf)| xf.rect)+ }++ /// The document area on screen.+ pub fn viewport_rect(&self) -> Rect {+ self.viewport_screen+ }++ /// Pages drawn last frame and their screen rectangles.+ pub fn visible_page_rects(&self) -> Vec<(usize, Rect)> {+ self.screen_xforms.iter().map(|(p, xf)| (*p, xf.rect)).collect()+ }++ /// Where `page` is drawn this frame, with its coordinate mapping.+ pub(crate) fn page_xform(&self, page: usize) -> Option<PageXform> {+ self.screen_xforms.iter().find(|(p, _)| *p == page).map(|(_, xf)| *xf)+ }+}++/// `r` moved so its corner lies on a whole physical pixel, so that a raster drawn from there+/// maps texel for texel onto the screen.+pub(super) fn snap_to_pixels(r: Rect, ppp: f32) -> Rect {+ let snap = |v: f32| (v * ppp).round() / ppp;+ Rect::from_min_size(pos2(snap(r.min.x), snap(r.min.y)), r.size())+}++/// Maps between a page's coordinate spaces and the screen, including view rotation.+///+/// *View space* is the page as rendered (points, y down, the document's own `/Rotate` applied);+/// normalised page coordinates `(u, v)` are view space divided by the page size. The view+/// rotation (View ▸ Rotate View) turns the page clockwise on screen by `rot` degrees.+#[derive(Clone, Copy)]+pub struct PageXform {+ /// The page's rectangle on screen (already rotated, so width/height may be swapped).+ pub rect: Rect,+ pub rot: u16,+ /// Page size in view space (unrotated by the view).+ pub pw: f32,+ pub ph: f32,+}++impl PageXform {+ /// Screen pixels per page point. The view's rotation swaps the rectangle's sides, so a page+ /// turned a quarter shows its width down the screen.+ pub(crate) fn zoom(&self) -> f32 {+ let across = if self.rot % 180 == 90 { self.rect.height() } else { self.rect.width() };+ across / self.pw.max(1.0)+ }++ /// Draw an image in the PDF user-space `rect` as a custom stamp's appearance draws it: turned+ /// back by `turn` (the page /Rotate it was placed for), so with the page's own rotation it+ /// reads upright as displayed.+ pub(crate) fn paint_user_image(+ &self,+ painter: &egui::Painter,+ tex: egui::TextureId,+ p: &pdfcraft_render::PageInfo,+ rect: [f64; 4],+ turn: i64,+ color: Color32,+ ) {+ let mut mesh = egui::Mesh::with_texture(tex);+ let (w, h) = (rect[2] - rect[0], rect[3] - rect[1]);+ let (shown_w, shown_h) = if turn % 180 == 0 { (w, h) } else { (h, w) };+ let [a, b, c, d, e, f] = pdfcraft_model::view_matrix_for(turn, rect);+ for (u, v) in [(0.0_f32, 0.0_f32), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)] {+ // The texture's (u, v), from its top-left, in the picture's upright frame, then in user space.+ let (dx, dy) = (f64::from(u) * shown_w, f64::from(1.0 - v) * shown_h);+ let (x, y) = (a * dx + c * dy + e, b * dx + d * dy + f);+ let q = p.user_to_view(x as f32, y as f32);+ mesh.vertices.push(egui::epaint::Vertex { pos: self.norm_to_screen(q[0] / self.pw, q[1] / self.ph), uv: pos2(u, v), color });+ }+ mesh.add_triangle(0, 1, 2);+ mesh.add_triangle(0, 2, 3);+ painter.add(egui::Shape::mesh(mesh));+ }+ pub fn norm_to_screen(&self, u: f32, v: f32) -> Pos2 {+ let (a, b) = match self.rot {+ 90 => (1.0 - v, u),+ 180 => (1.0 - u, 1.0 - v),+ 270 => (v, 1.0 - u),+ _ => (u, v),+ };+ pos2(self.rect.left() + a * self.rect.width(), self.rect.top() + b * self.rect.height())+ }++ pub fn screen_to_norm(&self, p: Pos2) -> (f32, f32) {+ let (a, b) = ((p.x - self.rect.left()) / self.rect.width().max(1e-3), (p.y - self.rect.top()) / self.rect.height().max(1e-3));+ match self.rot {+ 90 => (b, 1.0 - a),+ 180 => (1.0 - a, 1.0 - b),+ 270 => (1.0 - b, a),+ _ => (a, b),+ }+ }++ /// Screen point → view space (points).+ pub fn screen_to_view(&self, p: Pos2) -> (f32, f32) {+ let (u, v) = self.screen_to_norm(p);+ (u * self.pw, v * self.ph)+ }++ /// A view-space rect [x0, y0, x1, y1] → screen rect.+ pub fn view_rect(&self, g: [f32; 4]) -> Rect {+ Rect::from_two_pos(self.norm_to_screen(g[0] / self.pw, g[1] / self.ph), self.norm_to_screen(g[2] / self.pw, g[3] / self.ph))+ }++ /// A PDF user-space rect (crop box, document `/Rotate`) → screen rect.+ pub fn user_rect(&self, info: &DocInfo, page: usize, r: [f32; 4]) -> Rect {+ let p = &info.pages[page];+ let [cx0, cy0, cx1, cy1] = p.crop;+ let (cw, ch) = ((cx1 - cx0).max(1.0), (cy1 - cy0).max(1.0));+ let norm = |x: f32, y: f32| -> (f32, f32) {+ let (u, v) = ((x - cx0) / cw, (cy1 - y) / ch);+ match p.rotation {+ 90 => (1.0 - v, u),+ 180 => (1.0 - u, 1.0 - v),+ 270 => (v, 1.0 - u),+ _ => (u, v),+ }+ };+ let (a, b) = (norm(r[0], r[1]), norm(r[2], r[3]));+ Rect::from_two_pos(self.norm_to_screen(a.0, a.1), self.norm_to_screen(b.0, b.1))+ }++ /// This transform resized to a raster of `px` device pixels (width, height before the view+ /// rotation), so each of its texels covers one screen pixel. The rectangle's corner must+ /// already be on a whole pixel ([`snap_to_pixels`]).+ pub(super) fn texel_aligned(&self, px: [usize; 2], ppp: f32) -> PageXform {+ let (w, h) = (px[0] as f32 / ppp, px[1] as f32 / ppp);+ let size = if self.rot % 180 == 90 { vec2(h, w) } else { vec2(w, h) };+ PageXform { rect: Rect::from_min_size(self.rect.min, size), ..*self }+ }++ /// Draw a texture covering the normalised page region, rotated with the view.+ pub fn paint_image(&self, painter: &egui::Painter, tex: egui::TextureId, u0: f32, v0: f32, u1: f32, v1: f32) {+ let mut mesh = egui::Mesh::with_texture(tex);+ let corners = [(u0, v0, 0.0, 0.0), (u1, v0, 1.0, 0.0), (u1, v1, 1.0, 1.0), (u0, v1, 0.0, 1.0)];+ for (u, v, tu, tv) in corners {+ mesh.vertices.push(egui::epaint::Vertex { pos: self.norm_to_screen(u, v), uv: pos2(tu, tv), color: Color32::WHITE });+ }+ mesh.add_triangle(0, 1, 2);+ mesh.add_triangle(0, 2, 3);+ painter.add(egui::Shape::mesh(mesh));+ }+}diff --git a/crates/ui-egui/src/canvas/zoom.rs b/crates/ui-egui/src/canvas/zoom.rsnew file mode 100644index 000000000..b6a9669fd--- /dev/null+++ b/crates/ui-egui/src/canvas/zoom.rs@@ -0,0 +1,359 @@+use super::*;++/// The page grid's zoom range and the step of its buttons and keys.+pub const GRID_ZOOM_RANGE: std::ops::RangeInclusive<f32> = 0.5..=3.0;++/// Thumbnail size in the Pages inspector, relative to its usual size.+pub const THUMBNAIL_ZOOM_RANGE: std::ops::RangeInclusive<f32> = 0.5..=1.5;++pub(super) const GRID_ZOOM_STEP: f32 = 1.25;++impl DocView {+ /// Rotate the view 90° clockwise or counter-clockwise (View ▸ Rotate View, ⇧⌘+ / ⇧⌘−).+ pub fn rotate_view(&mut self, clockwise: bool) {+ self.rotation = (self.rotation + if clockwise { 90 } else { 270 }) % 360;+ self.goto = Some((self.current, 0.0));+ self.reset_coarse_state();+ }++ /// Switch the zoom mode, keeping the current page in view.+ pub fn set_fit(&mut self, fit: Fit) {+ self.fit = fit;+ self.goto = Some((self.current, 0.0));+ self.reset_coarse_state();+ }++ /// Full screen, as Acrobat's Full Screen Mode (#379, #1459): one page at a time (or one+ /// spread, when two-page view was on: #1353), fitted to the screen, from the current page.+ /// The display it replaces is kept for [`Self::leave_presentation`]. A no-op while presenting.+ pub fn enter_presentation(&mut self) {+ if self.presentation.is_some() {+ return;+ }+ self.presentation =+ Some(SavedDisplay { layout: self.layout, continuous: self.continuous, cover: self.cover, fit: self.fit, zoom: self.zoom });+ self.continuous = false;+ self.fit = Fit::Page;+ self.selection = None;+ self.goto = Some((self.current, 0.0));+ }++ /// Leave full screen: the display from before it comes back, at the page reached meanwhile.+ pub fn leave_presentation(&mut self) {+ let Some(saved) = self.presentation.take() else { return };+ self.layout = saved.layout;+ self.continuous = saved.continuous;+ self.cover = saved.cover;+ self.fit = saved.fit;+ self.zoom = saved.zoom;+ self.goto = Some((self.current, 0.0));+ }++ /// The display shown outside full screen: the one presenting replaced, or the current one.+ pub fn normal_display(&self) -> SavedDisplay {+ self.presentation.unwrap_or(SavedDisplay {+ layout: self.layout,+ continuous: self.continuous,+ cover: self.cover,+ fit: self.fit,+ zoom: self.zoom,+ })+ }++ /// Whether the view is in full screen's one-page-at-a-time display.+ pub fn presenting(&self) -> bool {+ self.presentation.is_some()+ }++ /// Switch the base page display (Single or Two-page), leaving continuous scrolling as it is.+ /// A no-op when the layout is already current, so re-selecting it never yanks a scrolled view+ /// back to the top.+ pub fn set_layout(&mut self, layout: PageLayout) {+ if self.layout == layout {+ return;+ }+ self.layout = layout;+ self.goto = Some((self.current, 0.0));+ self.reset_coarse_state();+ }++ /// Whether the view scrolls continuously (as opposed to one page or spread at a time).+ pub fn continuous(&self) -> bool {+ self.continuous+ }++ /// Change page separation without editing the PDF or losing the reader's place.+ pub fn set_page_gaps(&mut self, show: bool) {+ if self.show_page_gaps == show {+ return;+ }+ if !self.organize && self.viewport_screen.is_positive() {+ let at = self.viewport_screen.center();+ if let Some((page, r)) = self+ .screen_rects+ .iter()+ .filter(|(_, r)| r.is_positive())+ .min_by(|(_, a), (_, b)| a.distance_sq_to_pos(at).total_cmp(&b.distance_sq_to_pos(at)))+ {+ let fraction = (at - r.min) / r.size();+ self.zoom_anchor = Some((*page, fraction.x, fraction.y, at - self.viewport_screen.min));+ }+ }+ self.show_page_gaps = show;+ }++ /// Separation between adjacent page rectangles, in logical screen points.+ pub(super) fn page_gap(&self) -> f32 {+ if self.show_page_gaps { GAP } else { 0.0 }+ }++ /// Turn continuous scrolling on or off, keeping the current page in view. A no-op when it is+ /// already in that state.+ pub fn set_continuous(&mut self, continuous: bool) {+ if self.continuous != continuous {+ self.continuous = continuous;+ // Select All of the document belongs to continuous scrolling.+ self.all_text = false;+ self.goto = Some((self.current, 0.0));+ self.reset_coarse_state();+ }+ }++ /// Set the whole page display at once (the base layout and continuous scrolling together),+ /// as the control channel and settings do through a single [`display_token`].+ pub fn set_display(&mut self, layout: PageLayout, continuous: bool) {+ self.set_layout(layout);+ self.set_continuous(continuous);+ }++ /// Set the cover page in two-page view. A no-op unless something changed.+ pub fn set_cover(&mut self, cover: bool) {+ if self.cover != cover {+ self.cover = cover;+ self.goto = Some((self.current, 0.0));+ self.reset_coarse_state();+ }+ }++ /// Whether the cover page setting applies: only two-page view has a cover page.+ pub fn cover_applies(&self) -> bool {+ self.layout == PageLayout::TwoUp+ }++ /// Displayed page size in points for this view rotation.+ pub(super) fn display_size(&self, p: &pdfcraft_render::PageInfo) -> (f32, f32) {+ if self.rotation % 180 == 90 { (p.height, p.width) } else { (p.width, p.height) }+ }++ /// Marquee Zoom: zoom so `r` (on screen) fills the window, centred.+ pub fn zoom_to_rect(&mut self, r: Rect) {+ let Some((page, pr)) = self.screen_rects.iter().find(|(_, pr)| pr.contains(r.center())).copied() else { return };+ let k = (self.viewport_screen.width() / r.width().max(1.0)).min(self.viewport_screen.height() / r.height().max(1.0));+ let f = (r.center() - pr.min) / pr.size();+ self.zoom = (self.zoom * k).clamp(0.08, 64.0);+ self.fit = Fit::None;+ self.zoom_anchor = Some((page, f.x.clamp(0.0, 1.0), f.y.clamp(0.0, 1.0), self.viewport_screen.center() - self.viewport_screen.min));+ }++ /// View ▸ Zoom ▸ Fit Visible: zoom so the visible content of `page` (display-normalised+ /// [x0, y0, x1, y1], i.e. after view rotation) spans the window's width, its left edge at+ /// the window's left and its top at the top.+ pub fn fit_content(&mut self, page: usize, content: [f32; 4]) -> bool {+ const PAD: f32 = 16.0;+ let Some((_, pr)) = self.screen_rects.iter().find(|(p, _)| *p == page).copied() else { return false };+ let w = (content[2] - content[0]).max(0.01) * pr.width();+ let k = (self.viewport_screen.width() - 2.0 * PAD).max(50.0) / w.max(1.0);+ self.zoom = (self.zoom * k).clamp(0.08, 64.0);+ self.fit = Fit::None;+ self.zoom_anchor = Some((page, content[0].clamp(0.0, 1.0), content[1].clamp(0.0, 1.0), vec2(PAD, MARGIN)));+ true+ }++ /// How large the page grid draws its pages (1.0 = the usual thumbnails).+ pub fn grid_zoom(&self) -> f32 {+ self.grid_zoom+ }++ /// Scale of the thumbnails in the Pages inspector (1.0 is the usual size).+ pub fn thumbnail_zoom(&self) -> f32 {+ self.thumbnail_zoom+ }++ /// Resize the inspector thumbnails, keeping the current page in view after layout.+ /// Out-of-range values are clamped; non-finite values are ignored.+ pub fn set_thumbnail_zoom(&mut self, zoom: f32) {+ if zoom.is_finite() {+ let zoom = zoom.clamp(*THUMBNAIL_ZOOM_RANGE.start(), *THUMBNAIL_ZOOM_RANGE.end());+ if zoom != self.thumbnail_zoom {+ self.thumbnail_zoom = zoom;+ self.panel_followed = None;+ }+ }+ }++ /// Zoom the page grid; out-of-range values are clamped and nonsense is ignored.+ pub fn set_grid_zoom(&mut self, zoom: f32) {+ if zoom.is_finite() {+ self.grid_zoom = zoom.clamp(*GRID_ZOOM_RANGE.start(), *GRID_ZOOM_RANGE.end());+ }+ }++ /// Zoom keeping the centre of the view still.+ pub fn set_zoom(&mut self, zoom: f32) {+ // CLI/view options can set zoom before the first layout. Rect::NOTHING has no+ // finite centre yet, but an initial zoom still needs to leave the default fit mode.+ let centre = if self.viewport_screen.is_positive() { self.viewport_screen.center() } else { Pos2::ZERO };+ self.zoom_at(zoom, centre);+ }++ /// Zoom keeping the document point under `screen_pos` still (pinch, ⌘-scroll).+ pub fn zoom_at(&mut self, zoom: f32, screen_pos: Pos2) {+ if !zoom.is_finite() || !screen_pos.is_finite() {+ return;+ }+ let zoom = zoom.clamp(0.08, 64.0);+ if zoom == self.zoom && self.fit == Fit::None {+ return;+ }+ // In gutters/gaps, anchor relative to the nearest page rather than jumping to its top.+ // Fractions outside 0..1 preserve the pointer's position outside the page as well.+ let anchor =+ self.screen_rects.iter().min_by(|(_, a), (_, b)| a.distance_sq_to_pos(screen_pos).total_cmp(&b.distance_sq_to_pos(screen_pos))).map(+ |(p, r)| {+ let f = (screen_pos - r.min) / r.size();+ (*p, f.x, f.y, screen_pos - self.viewport_screen.min)+ },+ );+ self.zoom = zoom;+ self.fit = Fit::None;+ match anchor {+ Some(a) => self.zoom_anchor = Some(a),+ // Nothing on screen yet (e.g. a launch option): align the current page instead.+ None => self.goto = Some((self.current, 0.0)),+ }+ }++ /// A zoom typed as a percentage ("150", "150%", " 62.5 % ") as a zoom factor; `None` unless it is a+ /// finite, positive number. `set_zoom` clamps it to the supported range.+ pub fn parse_zoom_percent(typed: &str) -> Option<f32> {+ let percent = typed.trim().trim_end_matches('%').trim_end().parse::<f32>().ok()?;+ (percent.is_finite() && percent > 0.0).then_some(percent / 100.0)+ }++ /// Standard zoom steps (as in Acrobat's zoom menu).+ pub fn zoom_step(&mut self, up: bool) {+ const STEPS: [f32; 17] = [0.1, 0.25, 0.33, 0.5, 0.66, 0.75, 1.0, 1.25, 1.5, 2.0, 3.0, 4.0, 6.0, 8.0, 12.0, 16.0, 32.0];+ let z = self.zoom;+ let next = if up { STEPS.iter().copied().find(|s| *s > z * 1.01) } else { STEPS.iter().rev().copied().find(|s| *s < z * 0.99) };+ if let Some(n) = next {+ self.set_zoom(n);+ }+ }++ /// The first page of the two-page spread page `c` is in: spreads are [0, 1], [2, 3], … or,+ /// with a cover page, [0], [1, 2], [3, 4], ….+ pub(super) fn spread_first(&self, c: usize) -> usize {+ if self.cover { c.saturating_sub((c + 1) % 2) } else { c - c % 2 }+ }++ pub(super) fn fit_zoom(&mut self, info: &DocInfo) {+ let largest = |side: fn((f32, f32)) -> f32| info.pages.iter().map(|p| side(self.display_size(p))).fold(1.0, f32::max);+ let max_w = largest(|s| s.0);+ // A single page shown on its own fits that page, and full screen in two-page view fits+ // the spread it shows (review on #2070). Every other display (scrolling, or two-page+ // view in the window) fits its largest page, so the zoom holds still while pages of+ // other sizes scroll or page past.+ let (w, h) = if self.layout == PageLayout::Single && !self.continuous {+ info.pages.get(self.current).map_or_else(|| (max_w, largest(|s| s.1)), |p| self.display_size(p))+ } else if self.presentation.is_some() && self.layout == PageLayout::TwoUp && !self.continuous {+ let first = self.spread_first(self.current);+ let last = if self.cover && first == 0 { 0 } else { first.saturating_add(1) };+ let spread: Vec<(f32, f32)> = info.pages.iter().skip(first).take(last - first + 1).map(|p| self.display_size(p)).collect();+ if spread.is_empty() {+ (max_w, largest(|s| s.1))+ } else {+ (spread.iter().map(|s| s.0).fold(1.0, f32::max), spread.iter().map(|s| s.1).fold(1.0, f32::max))+ }+ } else {+ (max_w, largest(|s| s.1))+ };+ let avail_w = (self.viewport_w - 2.0 * SIDE).max(100.0);+ let per_row = if self.layout == PageLayout::TwoUp { 2.0 } else { 1.0 };+ match self.fit {+ Fit::Width => self.zoom = (avail_w - self.page_gap() * (per_row - 1.0)) / (w * PT * per_row),+ Fit::Page => {+ let zw = (avail_w - self.page_gap() * (per_row - 1.0)) / (w * PT * per_row);+ let zh = (self.viewport_h - 2.0 * MARGIN) / (h * PT);+ self.zoom = zw.min(zh);+ }+ Fit::Height => self.zoom = (self.viewport_h - 2.0 * MARGIN) / (h * PT),+ Fit::None => {}+ }+ self.zoom = self.zoom.clamp(0.08, 64.0);+ }++ /// Width of the scroll content. Single-page view sizes it to the page it shows, so a+ /// wider page elsewhere in the document can't push the shown one off-centre.+ pub(super) fn content_width(&self, info: &DocInfo, avail_w: f32) -> f32 {+ let single = (self.layout == PageLayout::Single && !self.continuous).then(|| self.current.min(info.pages.len().saturating_sub(1)));+ let shown = info.pages.iter().enumerate().filter(|&(i, _)| single.is_none_or(|c| c == i));+ let max_w = shown.map(|(_, p)| self.display_size(p).0).fold(0.0, f32::max);+ let per_row = if self.layout == PageLayout::TwoUp { 2.0 } else { 1.0 };+ (max_w * self.zoom * PT * per_row + 2.0 * SIDE).max(avail_w)+ }++ /// Page rects in content coordinates (origin at the scroll content's top-left).+ pub(super) fn layout(&self, info: &DocInfo, content_w: f32, ppp: f32) -> Vec<Rect> {+ let s = self.zoom * PT;+ let gap = self.page_gap();+ let page_size = |p: &pdfcraft_render::PageInfo| {+ let (w, h) = self.display_size(p);+ if self.show_page_gaps {+ vec2(w * s, h * s)+ } else {+ // Match the raster's whole physical pixels. Snapping each page's origin+ // independently with fractional sizes would leave hairline seams.+ vec2(device_pixels(w, s * ppp) as f32 / ppp, device_pixels(h, s * ppp) as f32 / ppp)+ }+ };+ let mut rects = Vec::with_capacity(info.pages.len());+ let mut y = MARGIN;+ match self.layout {+ PageLayout::Single => {+ for p in &info.pages {+ let size = page_size(p);+ rects.push(Rect::from_min_size(pos2(((content_w - size.x) / 2.0).max(SIDE), y), size));+ y += size.y + gap;+ }+ }+ PageLayout::TwoUp => {+ // With a cover page, the first page sits alone on the right.+ let rows: Vec<&[pdfcraft_render::PageInfo]> = if self.cover && !info.pages.is_empty() {+ std::iter::once(&info.pages[..1]).chain(info.pages[1..].chunks(2)).collect()+ } else {+ info.pages.chunks(2).collect()+ };+ for (ri, pair) in rows.into_iter().enumerate() {+ let sizes: Vec<Vec2> = pair.iter().map(page_size).collect();+ let row_w: f32 = sizes.iter().map(|v| v.x).sum::<f32>() + gap * (sizes.len() as f32 - 1.0);+ let row_h = sizes.iter().map(|v| v.y).fold(0.0, f32::max);+ let mut x = if self.cover && ri == 0 { (content_w / 2.0 + gap / 2.0).max(SIDE) } else { ((content_w - row_w) / 2.0).max(SIDE) };+ for size in sizes {+ rects.push(Rect::from_min_size(pos2(x, y + (row_h - size.y) / 2.0), size));+ x += size.x + gap;+ }+ y += row_h + gap;+ }+ }+ }+ rects+ }+}++/// The scroll offset that puts `point` (content coordinates) at `rel` in the viewport, kept within+/// the content as egui keeps it. egui clamps only after drawing, so an offset past the end showed+/// the page misplaced for a frame and then jumped (zooming out beside a page that fits).+pub(super) fn anchored_scroll(point: Pos2, rel: Vec2, content: Vec2, viewport: Vec2) -> Vec2 {+ let max = vec2((content.x - viewport.x).max(0.0), (content.y - viewport.y).max(0.0));+ vec2((point.x - rel.x).clamp(0.0, max.x), (point.y - rel.y).clamp(0.0, max.y))+}