PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust
Integrate 21 clean-merging PdfCraft parity PRs
FredAppsb21af3b96999
diff --cc CLAUDE.mdindex ef8a730ed,cd1b5b284,cd1b5b284,cd1b5b284,cd1b5b284,f51a96d56,c47674135,cd1b5b284,cd1b5b284,cd1b5b284,f51a96d56,cd1b5b284,cd1b5b284,cd1b5b284,a37cec4ca,cd1b5b284,a37cec4ca,cd1b5b284,f51a96d56,a37cec4ca,ef8a730ed,ef8a730ed..5bf9403c9--- a/CLAUDE.md+++ b/CLAUDE.md@@@@@@@@@@@@@@@@@@@@@@@ -22,7 -22,7 -22,7 -22,7 -22,7 -22,6 -22,8 -22,7 -22,7 -22,7 -22,6 -22,7 -22,7 -22,7 -22,6 -22,7 -22,6 -22,7 -22,6 -22,6 -22,7 -22,7 +22,8 @@@@@@@@@@@@@@@@@@@@@@@ PdfCraft is a clean-room, open-source,- **Privacy.** When observing Acrobat, use synthetic fixtures only. Never capture the Home view, recent files or account info. Capture by window id (`plan/acrobat/tools/`). Never commit Acrobat outputs, corpus files or personal data.- **Layering.** Nothing below L7 depends on egui/winit/eframe/rfd (`plan/architecture.md` §3). `cos`/`filters`/`crypt`/`arlington` stay standalone.- **Page input.** Page modules read `PagePointer` (`crates/ui-egui/src/page_pointer.rs`), never egui's raw pointer state (`hover_pos`, `interact_pos`, `latest_pos`, `press_origin`, button reads); `page_pointer::tests::page_modules_read_the_pointer_only_through_page_pointer` enforces it.+ + + + ++ - **Page cursor.** Page modules claim the cursor for what is under the pointer (`view.cursor.claim(Layer::…, icon)`, `crates/ui-egui/src/canvas/page_cursor.rs`), never set it (`set_cursor_icon`, `cursor_icon =`, `on_hover_cursor`); `document_area` sets it once, from the claim on the highest layer the active tool reaches. `page_pointer::tests::page_modules_claim_the_cursor_and_never_set_it` enforces it.++++++ +++++++++++++++- **Page presses.** A page module decides what of its own is under a point in one hit test, which returns a `Hit` (owner, layer, cursor, tip; `crates/ui-egui/src/canvas/page_router.rs`) and gives its cursor, its tip and its press. It acts on a press only when the router says the press is its own (`view.router.owner(page)`), never by testing the press point again or by asking another module whether it wants it. Escape cancels any press the pages hold (`cancel_on_escape`), and that press is ignored until the button is up.- **Fidelity.** The PDF object graph is the model. Preserve unknown data. Saves are incremental unless a full rewrite is required. Never silently drop or repair data without recording it.- **Never panic.** Every PDF, script, MCP call, settings file and keystroke is untrusted input, and none of it may crash the app or lose the user's work. This outranks feature work. Return `Result` (the crate's error enum) and propagate with `?`, or fall back leniently and record it. In non-test code:- No `unwrap`/`expect`/`panic!`/`unreachable!`/`todo!` unless it is provably infallible, with a comment saying why.diff --cc Cargo.lockindex c4f57c026,42426bc68,e2427a1b0,c6ee963a3,c6ee963a3,3c713ba5c,8fd7c9133,8fd7c9133,8fd7c9133,56274f385,3c713ba5c,8df9cf623,8df9cf623,8fd7c9133,8df9cf623,8fd7c9133,4f8e8ac8c,8fd7c9133,845a94c0d,4f8e8ac8c,c4f57c026,c4f57c026..62a997067--- a/Cargo.lock+++ b/Cargo.lock@@@@@@@@@@@@@@@@@@@@@@@ -1279,7 -1279,7 -1279,7 -1279,7 -1279,7 -1234,7 -1279,7 -1279,7 -1279,7 -1279,7 -1234,7 -1279,7 -1279,7 -1279,7 -1279,7 -1279,7 -1279,7 -1279,7 -1234,7 -1279,7 -1279,7 -1279,7 +1279,7 @@@@@@@@@@@@@@@@@@@@@@@ dependencies =[[package]]name = "craft-update"version = "0.1.0"---- ---- ------- - source = "git+https://github.com/storytold/craft-libs?rev=e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545#e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545"- - - source = "git+https://github.com/storytold/craft-libs?rev=495e5971bc024aa96e6ed318cb6e7cd3a0103184#495e5971bc024aa96e6ed318cb6e7cd3a0103184"+++++++++++++++++++ source = "git+https://github.com/storytold/craft-libs?rev=04aa1703b32d299e54f78fcde4182f2b393a9116#04aa1703b32d299e54f78fcde4182f2b393a9116"dependencies = ["chrono","dunce",@@@@@@@@@@@@@@@@@@@@@@@ -4331,15 -4330,15 -4330,17 -4330,17 -4330,17 -4179,14 -4330,15 -4330,15 -4330,15 -4330,14 -4179,14 -4330,14 -4330,14 -4330,15 -4330,14 -4330,15 -4330,14 -4330,15 -4179,14 -4330,14 -4331,15 -4331,15 +4331,17 @@@@@@@@@@@@@@@@@@@@@@@ dependencies =[[package]]name = "pdfcraft-create"- - - -- version = "0.14.0"+ + + ++ version = "0.15.0"dependencies = ["encoding_rs",++ +++++++++++++++++ "hayro-ccitt","hayro-syntax","image","pdfcraft-cos",++ +++++++++++++++++ "pdfcraft-filters","pdfcraft-fonts","pdfcraft-model",+ ++++ + + ++ "pdfcraft-xfa","png 0.18.1","thiserror 2.0.21","tiff",@@@@@@@@@@@@@@@@@@@@@@@ -4423,9 -4422,11 -4424,11 -4424,11 -4424,11 -4270,9 -4422,9 -4422,9 -4422,9 -4422,9 -4270,9 -4421,9 -4421,9 -4422,9 -4421,9 -4422,9 -4421,9 -4422,9 -4271,9 -4421,9 -4423,9 -4423,9 +4427,11 @@@@@@@@@@@@@@@@@@@@@@@ dependencies =[[package]]name = "pdfcraft-filters"- - - -- version = "0.14.0"+ + + ++ version = "0.15.0"dependencies = [+ +++++++++++++++++ "fax","flate2",+ +++++++++++++++++ "hayro-ccitt","proptest","thiserror 2.0.21","weezl 0.2.1",@@@@@@@@@@@@@@@@@@@@@@@ -4545,7 -4546,7 -4548,7 -4549,7 -4549,7 -4391,7 -4544,7 -4544,7 -4544,7 -4544,7 -4391,7 -4543,7 -4543,7 -4544,7 -4543,7 -4544,7 -4543,7 -4544,7 -4392,7 -4543,7 -4545,7 -4545,7 +4552,7 @@@@@@@@@@@@@@@@@@@@@@@ dependencies ="pdfcraft-content","pdfcraft-cos","pdfcraft-model",---- ---- ------- - "roxmltree 0.20.0",- - - "roxmltree",+++++++++++++++++++ "roxmltree 0.21.2",][[package]]@@@@@@@@@@@@@@@@@@@@@@@ -4708,7 -4709,7 -4711,7 -4713,7 -4713,7 -4554,7 -4707,7 -4707,7 -4707,7 -4707,7 -4554,7 -4706,7 -4706,7 -4707,7 -4706,7 -4707,7 -4706,7 -4707,7 -4555,7 -4706,7 -4708,7 -4708,7 +4716,7 @@@@@@@@@@@@@@@@@@@@@@@ dependencies ="pdfcraft-cos","pdfcraft-fonts","png 0.18.1",---- ---- ------- - "roxmltree 0.20.0",- - - "roxmltree",+++++++++++++++++++ "roxmltree 0.21.2","sha2 0.11.1","thiserror 2.0.21",]@@@@@@@@@@@@@@@@@@@@@@@ -4721,7 -4722,7 -4724,7 -4726,7 -4726,7 -4567,7 -4720,7 -4720,7 -4720,7 -4720,7 -4567,7 -4719,7 -4719,7 -4720,7 -4719,7 -4720,7 -4719,7 -4720,7 -4568,7 -4719,7 -4721,7 -4721,7 +4729,7 @@@@@@@@@@@@@@@@@@@@@@@ dependencies ="pdfcraft-cos","pdfcraft-forms","pdfcraft-model",---- ---- ------- - "roxmltree 0.20.0",- - - "roxmltree",+++++++++++++++++++ "roxmltree 0.21.2","thiserror 2.0.21",]diff --cc Cargo.tomlindex 493896336,5a92b6747,b2380a749,f0995622b,f0995622b,8eb38b29a,64a3cf5b6,64a3cf5b6,64a3cf5b6,436731c13,8eb38b29a,436731c13,436731c13,64a3cf5b6,436731c13,64a3cf5b6,f86ebaa15,64a3cf5b6,8eb38b29a,f86ebaa15,493896336,493896336..d374218fd--- a/Cargo.toml+++ b/Cargo.toml@@@@@@@@@@@@@@@@@@@@@@@ -13,52 -13,51 -13,51 -13,51 -13,51 -13,51 -13,51 -13,51 -13,51 -13,51 -13,51 -13,51 -13,51 -13,51 -13,51 -13,51 -13,51 -13,51 -13,51 -13,51 -13,52 -13,52 +13,52 @@@@@@@@@@@@@@@@@@@@@@@ repository = "https://github.com/storyt[workspace.dependencies]# Shared frontend components; engines remain independent of egui.- - - craft-ui = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "edc41f68fa24c46651c3b5117d10f0ead75ec9cb", features = ["serde"] }+ + + craft-ui = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545", features = ["serde"] }# Quit the macOS way (#1136): ⌘Q asks about unsaved changes, and closing quits through `terminate:`.- - - craft-quit = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "edc41f68fa24c46651c3b5117d10f0ead75ec9cb" }+ + + craft-quit = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545" }# One menu definition for the native macOS menu bar and the in-window bar elsewhere.- - - craft-menu = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "edc41f68fa24c46651c3b5117d10f0ead75ec9cb" }- - - craft-keymap = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "edc41f68fa24c46651c3b5117d10f0ead75ec9cb", default-features = false }+ + + craft-menu = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545" }+ + + craft-keymap = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545", default-features = false }# Shared system spooler; document composition remains in pdfcraft-print.- - - craft-print = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "42e30cd5b3f4b114270dd053fccbc33bedc47f68" }+ + + craft-print = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545" }# Whether a path stored in a document may be opened (GoToR link targets).- - - craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "82a24b006eefa036b43c09a67fb9a3fbd17ffe63" }- - - craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "495e5971bc024aa96e6ed318cb6e7cd3a0103184", features = ["egui"] }+ + + craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545" }---- ---- ------- - craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545", features = ["egui"] }+++++++++++++++++++ # craft-update: app-specific pretend versions apply to startup and manual checks.+++++++++++++++++++ craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "04aa1703b32d299e54f78fcde4182f2b393a9116", features = ["egui"] }# internal- - - -- pdfcraft-geom = { path = "crates/geom", version = "0.14.0" }- - - -- pdfcraft-filters = { path = "crates/filters", version = "0.14.0" }- - - -- pdfcraft-cos = { path = "crates/cos", version = "0.14.0" }- - - -- pdfcraft-crypt = { path = "crates/crypt", version = "0.14.0" }- - - -- pdfcraft-organize = { path = "crates/organize", version = "0.14.0" }- - - -- pdfcraft-measure = { path = "crates/measure", version = "0.14.0" }- - - -- pdfcraft-annot = { path = "crates/annot", version = "0.14.0" }- - - -- pdfcraft-audit = { path = "crates/audit", version = "0.14.0" }- - - -- pdfcraft-fonts = { path = "crates/fonts", version = "0.14.0" }- - - -- pdfcraft-model = { path = "crates/model", version = "0.14.0" }- - - -- pdfcraft-content = { path = "crates/content", version = "0.14.0" }- - - -- pdfcraft-redact = { path = "crates/redact", version = "0.14.0" }- - - -- pdfcraft-print = { path = "crates/print", version = "0.14.0" }- - - -- pdfcraft-xfdf = { path = "crates/xfdf", version = "0.14.0" }- - - -- pdfcraft-sign = { path = "crates/sign", version = "0.14.0" }- - - -- pdfcraft-optimize = { path = "crates/optimize", version = "0.14.0" }- - - -- pdfcraft-a11y = { path = "crates/a11y", version = "0.14.0" }- - - -- pdfcraft-oracle = { path = "crates/oracle", version = "0.14.0" }- - - -- pdfcraft-testkit = { path = "crates/testkit", version = "0.14.0" }- - - -- pdfcraft-ocr = { path = "crates/ocr", version = "0.14.0" }- - - -- pdfcraft-js = { path = "crates/js", version = "0.14.0" }- - - -- pdfcraft-compare = { path = "crates/compare", version = "0.14.0" }- - - -- pdfcraft-preflight = { path = "crates/preflight", version = "0.14.0" }- - - -- pdfcraft-export = { path = "crates/export", version = "0.14.0" }- - - -- pdfcraft-edit = { path = "crates/edit", version = "0.14.0" }- - - -- pdfcraft-create = { path = "crates/create", version = "0.14.0" }- - - -- pdfcraft-forms = { path = "crates/forms", version = "0.14.0" }- - - -- pdfcraft-xfa = { path = "crates/xfa", version = "0.14.0" }- - - -- pdfcraft-render = { path = "crates/render", version = "0.14.0" }- - - -- pdfcraft-engine = { path = "crates/engine", version = "0.14.0" }- - - -- pdfcraft-platform = { path = "crates/platform", version = "0.14.0" }- - - -- pdfcraft-ui-egui = { path = "crates/ui-egui", version = "0.14.0" }- - - -- pdfcraft-automation = { path = "crates/automation", version = "0.14.0", default-features = false }+ + + ++ pdfcraft-geom = { path = "crates/geom", version = "0.15.0" }+ + + ++ pdfcraft-filters = { path = "crates/filters", version = "0.15.0" }+ + + ++ pdfcraft-cos = { path = "crates/cos", version = "0.15.0" }+ + + ++ pdfcraft-crypt = { path = "crates/crypt", version = "0.15.0" }+ + + ++ pdfcraft-organize = { path = "crates/organize", version = "0.15.0" }+ + + ++ pdfcraft-measure = { path = "crates/measure", version = "0.15.0" }+ + + ++ pdfcraft-annot = { path = "crates/annot", version = "0.15.0" }+ + + ++ pdfcraft-audit = { path = "crates/audit", version = "0.15.0" }+ + + ++ pdfcraft-fonts = { path = "crates/fonts", version = "0.15.0" }+ + + ++ pdfcraft-model = { path = "crates/model", version = "0.15.0" }+ + + ++ pdfcraft-content = { path = "crates/content", version = "0.15.0" }+ + + ++ pdfcraft-redact = { path = "crates/redact", version = "0.15.0" }+ + + ++ pdfcraft-print = { path = "crates/print", version = "0.15.0" }+ + + ++ pdfcraft-xfdf = { path = "crates/xfdf", version = "0.15.0" }+ + + ++ pdfcraft-sign = { path = "crates/sign", version = "0.15.0" }+ + + ++ pdfcraft-optimize = { path = "crates/optimize", version = "0.15.0" }+ + + ++ pdfcraft-a11y = { path = "crates/a11y", version = "0.15.0" }+ + + ++ pdfcraft-oracle = { path = "crates/oracle", version = "0.15.0" }+ + + ++ pdfcraft-testkit = { path = "crates/testkit", version = "0.15.0" }+ + + ++ pdfcraft-ocr = { path = "crates/ocr", version = "0.15.0" }+ + + ++ pdfcraft-js = { path = "crates/js", version = "0.15.0" }+ + + ++ pdfcraft-compare = { path = "crates/compare", version = "0.15.0" }+ + + ++ pdfcraft-preflight = { path = "crates/preflight", version = "0.15.0" }+ + + ++ pdfcraft-export = { path = "crates/export", version = "0.15.0" }+ + + ++ pdfcraft-edit = { path = "crates/edit", version = "0.15.0" }+ + + ++ pdfcraft-create = { path = "crates/create", version = "0.15.0" }+ + + ++ pdfcraft-forms = { path = "crates/forms", version = "0.15.0" }+ + + ++ pdfcraft-xfa = { path = "crates/xfa", version = "0.15.0" }+ + + ++ pdfcraft-render = { path = "crates/render", version = "0.15.0" }+ + + ++ pdfcraft-engine = { path = "crates/engine", version = "0.15.0" }+ + + ++ pdfcraft-platform = { path = "crates/platform", version = "0.15.0" }+ + + ++ pdfcraft-ui-egui = { path = "crates/ui-egui", version = "0.15.0" }+ + + ++ pdfcraft-automation = { path = "crates/automation", version = "0.15.0", default-features = false }hayro = "0.7.1"@@@@@@@@@@@@@@@@@@@@@@@ -66,6 -65,10 -65,11 -65,11 -65,11 -65,6 -65,6 -65,6 -65,6 -65,6 -65,6 -65,6 -65,6 -65,6 -65,6 -65,6 -65,6 -65,6 -65,6 -65,6 -66,6 -66,6 +66,11 @@@@@@@@@@@@@@@@@@@@@@@ hayro-syntax = "0.7.2lopdf = "0.45"flate2 = { version = "1.1", default-features = false, features = ["rust_backend"] }weezl = "0.2"+ +++++++++++++++++# CCITT Group 4 encoding (pdfcraft-filters); already in the tree through tiff.+ +++++++++++++++++fax = "0.2.7"- # An independent CCITT decoder, for round-trip tests; already in the tree through hayro.- # A CCITT decoder: Export ▸ Images decodes fax images with it, and the encoder's round-trip tests- # check against it; already in the tree through hayro.+++ +++++++++++++++++# CCITT fax decoding (pdfcraft-filters' decode_ccitt), also the independent decoder in its+++ +++++++++++++++++# encoder's round-trip tests; already in the tree through hayro.+ +++++++++++++++++hayro-ccitt = "0.3"# foundationthiserror = "2"diff --cc ROADMAP.mdindex f5de8044e,87f5b6705,2b2f78516,baae83997,5a441aa55,165fccc5e,f5de8044e,6f580f609,1793d3929,9c7773b33,165fccc5e,f5de8044e,f5de8044e,f5de8044e,e230d6e57,f5de8044e,f5de8044e,f5de8044e,165fccc5e,f5de8044e,7b371cf1b,be3171bb9..6d261cc1f--- a/ROADMAP.md+++ b/ROADMAP.md@@@@@@@@@@@@@@@@@@@@@@@ -1,8 -1,8 -1,8 -1,8 -1,8 -1,7 -1,8 -1,8 -1,8 -1,8 -1,7 -1,8 -1,8 -1,8 -1,8 -1,8 -1,8 -1,8 -1,7 -1,8 -1,8 -1,10 +1,10 @@@@@@@@@@@@@@@@@@@@@@@# PdfCraft roadmap+++++++++++++++++++++ > **Last reviewed:** 2026-10-15 · **Last updated:** 2026-10-15 · **Change:** minor (typed small Edit font sizes and Fill & Sign text/date colour, #2444/#2496; estimates unchanged)+++++++++++++++++++++**Stage: alpha** · next: beta, ~25% (ready for real work 50% → 75%) and ~400–700 h away+ + + > **Last reviewed:** 2026-10-27 | **Last updated:** 2026-10-27 | **Change:** minor (M10: OCR model downloads use verified ONNX pairs with legacy discovery fallback; estimates unchanged)> **Last reviewed:** 2026-10-25 | **Last updated:** 2026-10-25 | **Change:** minor (M14 localization current state: Arabic logical catalog, explicit RTL label direction and mirrored stock chrome; native/browser RTL workflows unqualified. Native release Hans face via LXGW WenKai Lite; estimates unchanged)> **Last reviewed:** 2026-10-23 · **Last updated:** 2026-10-23 · **Change:** minor (M7, #2636 partial: pasting added text boxes and images in the engine and through `content_copy`; estimates unchanged)> **Last reviewed:** 2026-10-23 · **Last updated:** 2026-10-23 · **Change:** minor (M11: image optimization accounts for page-local UserUnit; estimates unchanged)@@@@@@@@@@@@@@@@@@@@@@@ -200,11 -200,12 -200,13 -200,14 -200,15 -199,10 -200,11 -200,12 -200,11 -200,11 -199,10 -200,11 -200,11 -200,11 -200,11 -200,11 -200,11 -200,11 -199,10 -200,11 -200,11 -202,11 +202,16 @@@@@@@@@@@@@@@@@@@@@@@ Ranked; detail and the full milestone t## Progress log+ + + - **2026-10-27 (M10, OCR models):** Model staging downloads and verifies the ONNX pair after the upstream RTEN URL brownout; runtime discovery prefers complete ONNX pairs per directory, retains complete RTEN fallback and preserves directory precedence.+++++++ ++++++++++++++- **2026-10-25 (M5, comment replies):** One reply can be deleted from the Comments panel without its thread. On the selected card each reply has its own "…" menu (Edit, Copy text, Delete); Delete takes that reply with its pop-up and the replies to it, as `comment_delete` already did headlessly, and the comment and its other replies stay. The card stays selected, and the panel's editor stays open, on what they were on though the delete moved it in `/Annots`. Undo and Redo close the editor, since either can move what it was open on. A locked reply can't be deleted. Estimates unchanged.- **2026-10-24 (M10, #4158 partial):** Word, HTML, RTF and PowerPoint export keep a block that continues another on its line (an italic case name, a link, a superscript) as a run in its own style inside that paragraph, with the source's word space, instead of a paragraph of its own. Style changes that wrap onto the next line still split paragraphs (the reading blocks keep style boundaries). Estimates unchanged.- **2026-10-24 (M3, window move on Wayland, #3970 follow-up):** After a move or resize by PdfCraft's own title bar or edges, the button release given back to egui goes before the pointer leaving the window, so hover no longer sticks at the old place until the pointer moves. Found by CodeRabbit in review of #3970; a unit test covers it. Estimates unchanged.- **2026-10-24 (M14, #4253):** The annotation quick bar remembers Keep tool selected across restarts, including unpinning. Old and malformed settings keep safe defaults; the opt-in UI control channel reads and changes the same preference. Estimates unchanged.++++ +++++++++++++++++- **2026-10-24 (M11, more black-and-white images):** The optimizer re-stores Group 3 fax images as Group 4 when that is smaller, instead of leaving any CCITT image it doesn't resample as it is. Black-and-white images stored as eight-bit RGB (as some phone and scanner apps write them) become one-bit grey, and indexed images that use only their first two palette entries become one bit with their palette, so Monochrome Images compresses and downsamples them too.+++ +++++++++++++++++- **2026-10-24 (M11, monochrome downsampling):** The PDF Optimizer and Reduce File Size average black-and-white images above 450 ppi down to 300 ppi (Monochrome Images ▸ Downsample to), Group 4 scans included, so a 600 ppi text page goes from 79 KB to 40 KB. CCITT decoding moved into `pdfcraft-filters` (`decode_ccitt`), shared by Export ▸ Images and the optimizer through `Document::decoded_image`.++ +++++++++++++++++- **2026-10-24 (M11, black-and-white pictures):** A scan saved as a 1-bit PNG became an eight-bit grey image when made into a PDF, larger than the PNG; Create PDF now stores pictures of only black and white at one bit (Group 4 when smaller), the optimizer packs eight-bit black-and-white grey images to one bit unless the grey settings make them smaller, as they can a dithered scan, soft mask counted, and Export ▸ Images reads CCITT fax images.+ +++++++++++++++++- **2026-10-23 (M11, monochrome compression):** The PDF Optimizer and Reduce File Size store black-and-white images (scans, image masks) losslessly as CCITT Group 4 when that is smaller, with a Monochrome Images setting in the Optimizer and `doc_optimize` `mono`. JBIG2 and monochrome downsampling are next.- **2026-10-23 (M7, #4280):** Edit text names each standard stand-in font after its face (`PCEdTimesBold`, ...) instead of one shared `PCEdHelv`. Rewriting a bold paragraph whose subset lacks an accent no longer repoints the paragraphs set earlier in a regular stand-in at Times-Bold, and the editor's frame stays on the paragraph being edited. Pages saved by older builds keep their shared name and are not repaired. Estimates unchanged.- **2026-10-23 (M8, #3205 follow-up):** Phone-pattern redaction matches complete labelled Italian geographic numbers such as `Tel. +39 0426/123456`, with synthetic matcher and mark/apply/save/reopen coverage; unlabelled international slash numbers remain unsupported.- **2026-10-23 (M7, #2636 partial):** A new `PasteContent` edit pastes an added text box or image copied in the same document or another, keeping its style, picture, turns, flips and crop, as one undo step; `content_copy` drives it headlessly. A paste lands beside earlier copies (18 pt steps) and stays on the page. A pasted image reuses its picture object in its own document and after the first paste into another; there a colour profile is dropped and CMYK colours stored losslessly are turned to RGB. The desktop keys and menus follow in separate PRs. Estimates unchanged.diff --cc crates/annot/src/lib.rsindex e9e0359ce,e9e0359ce,e9e0359ce,e9e0359ce,e9e0359ce,1d85d0bd6,e9e0359ce,f51c64514,e43fb8029,e9e0359ce,1d85d0bd6,e9e0359ce,e9e0359ce,e9e0359ce,e9e0359ce,e9e0359ce,e9e0359ce,e9e0359ce,1d85d0bd6,e9e0359ce,e9e0359ce,e9e0359ce..7bd0894c6--- a/crates/annot/src/lib.rs+++ b/crates/annot/src/lib.rs@@@@@@@@@@@@@@@@@@@@@@@ -33,11 -33,11 -33,11 -33,11 -33,11 -33,11 -33,11 -33,11 -33,13 -33,11 -33,11 -33,11 -33,11 -33,11 -33,11 -33,11 -33,11 -33,11 -33,11 -33,11 -33,11 -33,11 +33,13 @@@@@@@@@@@@@@@@@@@@@@@ pub use info::{Props, Summary, is_comme#[cfg(test)]use lookup::{ANNOTS_ENTRIES_COPIED, PageWalk, annot_dict, annot_ref};use lookup::{annots, page_ref};-------- -------------pub use lookup::{has_visible_fill_sign, is_fill_sign, isolate_annotation, page_refs, picture_rotation, set_annots, signature_image};++++++++ +++++++++++++pub use lookup::{++++++++ +++++++++++++ has_visible_fill_sign, is_fill_sign, isolate_annotation, isolate_annotations, page_refs, picture_rotation, set_annots, signature_image,++++++++ +++++++++++++};pub(crate) use modify::n;pub use modify::{------- -------------- add_reply, add_text_replacement, delete_annotation, erase_ink, fillable, goes_with, move_annotation, set_contents, set_fill, set_font_size,------- -------------- set_locked, set_marked, set_points, set_rect, set_review_state, set_style, with_replies_and_popups,+++++++ ++++++++++++++ add_reply, add_text_replacement, deletable, delete_annotation, erase_ink, fillable, goes_with, lift_annotation, move_annotation, set_contents,+++++++ ++++++++++++++ set_fill, set_font_size, set_locked, set_marked, set_points, set_rect, set_review_state, set_style, with_replies_and_popups,};pub use types::{AttachIcon, FillMark, LineEnding, Markup, Meta, NOTE_SIZE, NewAnnotation, NoteIcon, OverlayFont, OverlayLook, ReviewState, Rgb, Shape,diff --cc crates/automation/src/dispatch.rsindex b136076bc,b136076bc,b136076bc,b136076bc,b136076bc,26e1f9536,b136076bc,b136076bc,b136076bc,5c56b6f58,26e1f9536,b136076bc,b136076bc,b136076bc,87f47e8eb,b136076bc,87f47e8eb,cbb143fc2,26e1f9536,87f47e8eb,b136076bc,b136076bc..63602e52d--- a/crates/automation/src/dispatch.rs+++ b/crates/automation/src/dispatch.rs@@@@@@@@@@@@@@@@@@@@@@@ -1,7 -1,7 -1,7 -1,7 -1,7 -1,7 -1,7 -1,7 -1,7 -1,7 -1,7 -1,7 -1,7 -1,7 -1,7 -1,7 -1,7 -1,7 -1,7 -1,7 -1,7 -1,7 +1,7 @@@@@@@@@@@@@@@@@@@@@@@use super::error::{Result, ToolError, failed};- - - - -- use super::json::{Args, document_attachment_keys, info, one_based, parse_style_ranges, security, summary};+ + + + ++ use super::json::{Args, document_attachment_keys, info, one_based, parse_style_ranges, security, summary, text_style_levels};use super::paths::{read_input, write_atomic};- - - use super::*;+ + + use super::{Arc, Automation, Edit, Value, block_overlapping, comments, json, tools};/// One piece of a tool's result.#[derive(Clone, Debug, PartialEq)]diff --cc crates/automation/src/documents.rsindex 476c45102,40aa4ac52,40aa4ac52,5d2c416ee,5d2c416ee,26addfd80,476c45102,476c45102,476c45102,2e6b763b5,26addfd80,476c45102,476c45102,476c45102,476c45102,476c45102,476c45102,476c45102,26addfd80,476c45102,476c45102,476c45102..835547968--- a/crates/automation/src/documents.rs+++ b/crates/automation/src/documents.rs@@@@@@@@@@@@@@@@@@@@@@@ -279,7 -279,7 -279,7 -279,8 -279,8 -279,7 -279,7 -279,7 -279,7 -279,7 -279,7 -279,7 -279,7 -279,7 -279,7 -279,7 -279,7 -279,7 -279,7 -279,7 -279,7 -279,7 +279,8 @@@@@@@@@@@@@@@@@@@@@@@ impl Automation}pub(crate) fn doc_optimize(&mut self, a: &Args) -> Result<Value> {- ----------------- use pdfcraft_engine::optimize::{Compatibility, Compression, ImageSettings, Preset};+ +++++++++++++++++ use pdfcraft_engine::optimize::{Compatibility, Compression, ImageSettings, MonoCompression, Preset};+++ +++++++++++++++++ const MONO_KEYS: [&str; 4] = ["downsample", "ppi", "above_ppi", "compression"];let id = self.doc(a)?.id;let before = self.doc(a)?.bytes.len();let path = self.resolve(a.str("path")?, true)?;@@@@@@@@@@@@@@@@@@@@@@@ -317,6 -317,21 -317,21 -318,37 -318,37 -317,6 -317,6 -317,6 -317,6 -317,6 -317,6 -317,6 -317,6 -317,6 -317,6 -317,6 -317,6 -317,6 -317,6 -317,6 -317,6 -317,6 +318,37 @@@@@@@@@@@@@@@@@@@@@@@};settings.color = images("color", settings.color)?;settings.gray = images("gray", settings.gray)?;+ +++++++++++++++++ if let Some(mono) = a.get("mono") {+ +++++++++++++++++ let unknown = |c: &Value| ToolError::InvalidArgs(format!("unknown mono compression {c} (ccitt_g4, retain)"));-- let mono = mono.as_object().ok_or_else(|| ToolError::InvalidArgs("mono must be an object: { compression: ccitt_g4|retain }".into()))?;+++ +++++++++++++++++ let mono = mono.as_object().ok_or_else(|| {+++ +++++++++++++++++ ToolError::InvalidArgs("mono must be an object: { downsample, ppi, above_ppi, compression: ccitt_g4|retain }".into())+++ +++++++++++++++++ })?;+ +++++++++++++++++ // A misspelled key would otherwise leave the preset's setting in place unnoticed.-- if let Some(key) = mono.keys().find(|k| *k != "compression") {-- return Err(ToolError::InvalidArgs(format!("unknown mono key {key:?} (compression)")));+++ +++++++++++++++++ if let Some(key) = mono.keys().find(|k| !MONO_KEYS.contains(&k.as_str())) {+++ +++++++++++++++++ return Err(ToolError::InvalidArgs(format!("unknown mono key {key:?} ({})", MONO_KEYS.join(", "))));+ +++++++++++++++++ }+++ +++++++++++++++++ let m = &mut settings.mono;+++ +++++++++++++++++ if let Some(d) = mono.get("downsample") {+++ +++++++++++++++++ m.downsample = d.as_bool().ok_or_else(|| ToolError::InvalidArgs(format!("mono downsample must be true or false, not {d}")))?;+++ +++++++++++++++++ }+++ +++++++++++++++++ for (key, ppi) in [("ppi", &mut m.target_ppi), ("above_ppi", &mut m.above_ppi)] {+++ +++++++++++++++++ if let Some(p) = mono.get(key) {+++ +++++++++++++++++ *ppi = p+++ +++++++++++++++++ .as_f64()+++ +++++++++++++++++ .filter(|p| p.is_finite())+++ +++++++++++++++++ .ok_or_else(|| ToolError::InvalidArgs(format!("mono {key} must be a number, not {p}")))?+++ +++++++++++++++++ .clamp(9.0, 2400.0);+++ +++++++++++++++++ }+++ +++++++++++++++++ }+++ +++++++++++++++++ m.above_ppi = m.above_ppi.max(m.target_ppi);+ +++++++++++++++++ if let Some(c) = mono.get("compression") {-- settings.mono = match c.as_str() {+++ +++++++++++++++++ m.compression = match c.as_str() {+ +++++++++++++++++ Some("ccitt_g4" | "ccitt" | "g4") => MonoCompression::CcittG4,+ +++++++++++++++++ Some("retain") => MonoCompression::Retain,+ +++++++++++++++++ _ => return Err(unknown(c)),+ +++++++++++++++++ };+ +++++++++++++++++ }+ +++++++++++++++++ }for (key, flag) in [("merge_fragments", &mut settings.merge_fragments),("discard_thumbnails", &mut settings.discard_thumbnails),diff --cc crates/automation/src/tools.rsindex 53c4582af,2760be929,15530229f,3f53a07ff,45471f47d,4b4ac8873,53c4582af,dfd859797,53c4582af,e55bd7110,4b4ac8873,53c4582af,53c4582af,53c4582af,38ed3306f,53c4582af,4b4ac8873,5882d3a3b,4b4ac8873,4b4ac8873,53c4582af,589e40fd9..554496b4b--- a/crates/automation/src/tools.rs+++ b/crates/automation/src/tools.rs@@@@@@@@@@@@@@@@@@@@@@@ -1332,7 -1332,7 -1332,7 -1332,7 -1332,7 -1299,7 -1332,7 -1332,7 -1332,7 -1336,7 -1299,7 -1332,7 -1332,7 -1332,7 -1299,7 -1332,7 -1299,7 -1332,7 -1299,7 -1299,7 -1332,7 -1333,7 +1337,7 @@@@@@@@@@@@@@@@@@@@@@@ pub fn tools() -> Vec<ToolDef>}),&["from"],)),- ----------------- t("doc_reduce", "Reduce file size", "Write a smaller copy of the document to `path` with Acrobat's Reduce File Size choices: images above 225 ppi downsampled to 150 ppi and JPEG-compressed (medium quality), thumbnails dropped, identical fonts and images merged, unused objects dropped, compressed object streams. If the copy wouldn't be smaller, nothing is written and `written` is false. The open document is unchanged.")-- t("doc_reduce", "Reduce file size", "Write a smaller copy of the document to `path` with Acrobat's Reduce File Size choices: colour and grey images above 225 ppi downsampled to 150 ppi and JPEG-compressed (medium quality), black-and-white images stored as CCITT Group 4 whenever that is smaller, thumbnails dropped, identical fonts and images merged, unused objects dropped, compressed object streams. If the copy wouldn't be smaller, nothing is written and `written` is false. The open document is unchanged.")- t("doc_reduce", "Reduce file size", "Write a smaller copy of the document to `path` with Acrobat's Reduce File Size choices: colour and grey images above 225 ppi downsampled to 150 ppi and JPEG-compressed (medium quality), black-and-white images averaged down to 300 ppi above 450 ppi and each stored as CCITT Group 4 (or 1-bit Flate, once resampled) whenever that is smaller, thumbnails dropped, identical fonts and images merged, unused objects dropped, compressed object streams. If the copy wouldn't be smaller, nothing is written and `written` is false. The open document is unchanged.")++++ +++++++++++++++++ t("doc_reduce", "Reduce file size", "Write a smaller copy of the document to `path` with Acrobat's Reduce File Size choices: colour and grey images above 225 ppi downsampled to 150 ppi and JPEG-compressed (medium quality), black-and-white images averaged down to 300 ppi above 450 ppi and each stored as CCITT Group 4 (or 1-bit Flate, once resampled or packed from more bits) whenever that is smaller, thumbnails dropped, identical fonts and images merged, unused objects dropped, compressed object streams. If the copy wouldn't be smaller, nothing is written and `written` is false. The open document is unchanged.").cmd("optimize.reduce").with(schema(json!({ "doc": doc(), "path": { "type": "string" } }), &["doc", "path"])),t("doc_initial_view", "Initial view", "Read or change how the document opens (Document Properties ▸ Initial View) and its reading options: navigation (page, bookmarks, pages, attachments, layers), layout (default, single, continuous, two_up, two_up_continuous, two_up_cover, two_up_continuous_cover), magnification (default, actual, fit_page, fit_width, fit_height, fit_visible, or a percentage), page, window options (fit_window, center_window, full_screen, display_title), interface options (hide_menubar, hide_toolbar, hide_window_ui), language and binding (left, right). Only the given ones change; returns the result. Undoable.").with(schema(@@@@@@@@@@@@@@@@@@@@@@@ -1433,7 -1433,7 -1433,7 -1433,7 -1433,7 -1400,7 -1433,7 -1433,7 -1433,7 -1437,7 -1400,7 -1433,7 -1433,7 -1433,7 -1400,7 -1433,7 -1400,7 -1433,7 -1400,7 -1400,7 -1433,7 -1434,7 +1438,7 @@@@@@@@@@@@@@@@@@@@@@@.with(schema(json!({ "doc": doc() }), &["doc"])),t("doc_open_revision", "Open a revision", "Open saved revision `revision` (1 = the oldest) of a document as a new, unsaved document, to see the file as it was then.").with(schema(json!({ "doc": doc(), "revision": { "type": "integer", "minimum": 1 } }), &["doc", "revision"])),- ----------------- t("doc_optimize", "Optimize PDF", "Write an optimized copy to `path` (Acrobat's PDF Optimizer). preset: standard (default; Reduce File Size's choices) or mobile (images to 96 ppi above 144, JPEG high quality); the options below change it. compatibility: retain (default; keeps the document's version, or 1.5 when object streams are written), 1.4, 1.5, 1.6, 1.7 or 2.0. merge_fragments (default true) first puts a page picture drawn as many stacked image strips (as some PDF printers write it) back together into one image, so it can be resampled (merged_images, fragments_merged). color / gray: { downsample, ppi, above_ppi, compression: jpeg|zip|retain, quality 1–100 } (defaults: downsample to 150 ppi above 225, JPEG 60). Images are measured where pages draw them and replaced only when smaller. discard_*: thumbnails (default true), alternate_images (true), tags, print_settings; flate_unencoded (true); object_streams (default true; always off for 1.4); lzw_to_flate (true) decodes LZW streams and stores them with Flate instead, leaving any it cannot decode unchanged (lzw_streams counts the streams converted); remove_invalid_links and remove_unreferenced_dests (true); images and forms the pages list but never draw are always dropped (unused_xobjects). discard: Remove Hidden Information categories (metadata, attachments, comments, form-fields, hidden-text, hidden-layers, bookmarks, links-actions-scripts, private-data). Signed documents are refused. The open document is unchanged.")-- t("doc_optimize", "Optimize PDF", "Write an optimized copy to `path` (Acrobat's PDF Optimizer). preset: standard (default; Reduce File Size's choices) or mobile (images to 96 ppi above 144, JPEG high quality); the options below change it. compatibility: retain (default; keeps the document's version, or 1.5 when object streams are written), 1.4, 1.5, 1.6, 1.7 or 2.0. merge_fragments (default true) first puts a page picture drawn as many stacked image strips (as some PDF printers write it) back together into one image, so it can be resampled (merged_images, fragments_merged). color / gray: { downsample, ppi, above_ppi, compression: jpeg|zip|retain, quality 1–100 } (defaults: downsample to 150 ppi above 225, JPEG 60). mono: { compression: ccitt_g4|retain } (default ccitt_g4: black-and-white images and image masks are stored losslessly as CCITT Group 4 when that is smaller; counted in images_recompressed). Images are measured where pages draw them and replaced only when smaller. discard_*: thumbnails (default true), alternate_images (true), tags, print_settings; flate_unencoded (true); object_streams (default true; always off for 1.4); lzw_to_flate (true) decodes LZW streams and stores them with Flate instead, leaving any it cannot decode unchanged (lzw_streams counts the streams converted); remove_invalid_links and remove_unreferenced_dests (true); images and forms the pages list but never draw are always dropped (unused_xobjects). discard: Remove Hidden Information categories (metadata, attachments, comments, form-fields, hidden-text, hidden-layers, bookmarks, links-actions-scripts, private-data). Signed documents are refused. The open document is unchanged.")- t("doc_optimize", "Optimize PDF", "Write an optimized copy to `path` (Acrobat's PDF Optimizer). preset: standard (default; Reduce File Size's choices) or mobile (images to 96 ppi above 144, JPEG high quality); the options below change it. compatibility: retain (default; keeps the document's version, or 1.5 when object streams are written), 1.4, 1.5, 1.6, 1.7 or 2.0. merge_fragments (default true) first puts a page picture drawn as many stacked image strips (as some PDF printers write it) back together into one image, so it can be resampled (merged_images, fragments_merged). color / gray: { downsample, ppi, above_ppi, compression: jpeg|zip|retain, quality 1–100 } (defaults: downsample to 150 ppi above 225, JPEG 60). mono: { downsample, ppi, above_ppi, compression: ccitt_g4|retain } for black-and-white images and image masks (default: averaged down to 300 ppi above 450 ppi, counted in images_resampled; stored losslessly as CCITT Group 4 when that is smaller, counted in images_recompressed; retain resamples only, a CCITT image staying CCITT and any other becoming Flate). Images are measured where pages draw them and replaced only when smaller. discard_*: thumbnails (default true), alternate_images (true), tags, print_settings; flate_unencoded (true); object_streams (default true; always off for 1.4); lzw_to_flate (true) decodes LZW streams and stores them with Flate instead, leaving any it cannot decode unchanged (lzw_streams counts the streams converted); remove_invalid_links and remove_unreferenced_dests (true); images and forms the pages list but never draw are always dropped (unused_xobjects). discard: Remove Hidden Information categories (metadata, attachments, comments, form-fields, hidden-text, hidden-layers, bookmarks, links-actions-scripts, private-data). Signed documents are refused. The open document is unchanged.")++++ +++++++++++++++++ t("doc_optimize", "Optimize PDF", "Write an optimized copy to `path` (Acrobat's PDF Optimizer). preset: standard (default; Reduce File Size's choices) or mobile (images to 96 ppi above 144, JPEG high quality); the options below change it. compatibility: retain (default; keeps the document's version, or 1.5 when object streams are written), 1.4, 1.5, 1.6, 1.7 or 2.0. merge_fragments (default true) first puts a page picture drawn as many stacked image strips (as some PDF printers write it) back together into one image, so it can be resampled (merged_images, fragments_merged). color / gray: { downsample, ppi, above_ppi, compression: jpeg|zip|retain, quality 1–100 } (defaults: downsample to 150 ppi above 225, JPEG 60). mono: { downsample, ppi, above_ppi, compression: ccitt_g4|retain } for black-and-white images and image masks (default: averaged down to 300 ppi above 450 ppi, counted in images_resampled; stored losslessly as CCITT Group 4 (or 1-bit Flate, once resampled or packed from more bits) when that is smaller, Group 3 fax images, black-and-white RGB and indexed images using only palette entries 0 and 1 among them, counted in images_recompressed; retain resamples only, a CCITT image staying CCITT and any other becoming Flate). Images are measured where pages draw them and replaced only when smaller. discard_*: thumbnails (default true), alternate_images (true), tags, print_settings; flate_unencoded (true); object_streams (default true; always off for 1.4); lzw_to_flate (true) decodes LZW streams and stores them with Flate instead, leaving any it cannot decode unchanged (lzw_streams counts the streams converted); remove_invalid_links and remove_unreferenced_dests (true); images and forms the pages list but never draw are always dropped (unused_xobjects). discard: Remove Hidden Information categories (metadata, attachments, comments, form-fields, hidden-text, hidden-layers, bookmarks, links-actions-scripts, private-data). Signed documents are refused. The open document is unchanged.").cmd("optimize.advanced").with(schema(json!({diff --cc crates/automation/tests/it/automation.rsindex 01d0d1eb2,dcd321edd,ea943eff7,d17627a95,d17627a95,23351db9a,01d0d1eb2,f8012669e,01d0d1eb2,9a27d9eef,23351db9a,9a27d9eef,9a27d9eef,01d0d1eb2,4cdf0c8a0,01d0d1eb2,78038d8eb,01d0d1eb2,23351db9a,78038d8eb,01d0d1eb2,547add173..a3cd8dcd3--- a/crates/automation/tests/it/automation.rs+++ b/crates/automation/tests/it/automation.rs@@@@@@@@@@@@@@@@@@@@@@@ -6372,6 -6372,96 -6372,145 -6372,207 -6372,207 -6173,6 -6372,6 -6401,6 -6372,6 -6326,6 -6173,6 -6326,6 -6326,6 -6372,6 -6237,6 -6372,6 -6237,6 -6372,6 -6173,6 -6237,6 -6372,6 -6404,6 +6433,207 @@@@@@@@@@@@@@@@@@@@@@@ fn lzw_streams_are_stored_with_flate_thassert_eq!(filters("kept.pdf"), (Some(Object::name("LZWDecode")), ops));}+ +++++++++++++++++/// A one-page PDF drawing a 1-bit scan of text (glyph strokes with ragged edges, as a scanner+ +++++++++++++++++/// leaves them) of 1000 × 400 samples, stored with Flate.+ +++++++++++++++++fn scanned_page() -> Vec<u8> {+++ +++++++++++++++++ scan_drawn(b"q 500 0 0 200 50 500 cm /Scan Do Q")+++ +++++++++++++++++}+++ ++++++++++++++++++++ +++++++++++++++++/// [`scanned_page`]'s scan, drawn by `content` (which names it `/Scan`).+++ +++++++++++++++++fn scan_drawn(content: &[u8]) -> Vec<u8> {+ +++++++++++++++++ use pdfcraft_cos::{Dict, Document, Object, SaveOptions, Stream, write_full};+ +++++++++++++++++ let (w, h) = (1000usize, 400usize);+ +++++++++++++++++ let stride = w.div_ceil(8);+ +++++++++++++++++ let mut data = vec![0xFFu8; stride * h];+ +++++++++++++++++ let mut seed = 0x2545_F491_4F6C_DD1Du64;+ +++++++++++++++++ let mut next = move || {+ +++++++++++++++++ seed ^= seed << 13;+ +++++++++++++++++ seed ^= seed >> 7;+ +++++++++++++++++ seed ^= seed << 17;+ +++++++++++++++++ seed+ +++++++++++++++++ };+ +++++++++++++++++ for line in (4..h - 20).step_by(24) {+ +++++++++++++++++ let mut x = 8;+ +++++++++++++++++ while x + 12 < w {+ +++++++++++++++++ let wide = 3 + (next() % 5) as usize;+ +++++++++++++++++ let (top, bottom) = (line + (next() % 4) as usize, line + 14);+ +++++++++++++++++ for y in top..bottom {+ +++++++++++++++++ let left = x + usize::from(next() % 8 == 0);+ +++++++++++++++++ let right = x + wide - usize::from(next() % 8 == 0);+ +++++++++++++++++ for xx in left..right {+ +++++++++++++++++ data[y * stride + xx / 8] &= !(0x80 >> (xx % 8));+ +++++++++++++++++ }+ +++++++++++++++++ }+ +++++++++++++++++ x += wide + 2 + (next() % 4) as usize;+ +++++++++++++++++ }+ +++++++++++++++++ }+ +++++++++++++++++ let mut doc = Document::new_empty();+ +++++++++++++++++ let mut d = Dict::new();+ +++++++++++++++++ d.set(b"Type".to_vec(), Object::name("XObject"));+ +++++++++++++++++ d.set(b"Subtype".to_vec(), Object::name("Image"));+ +++++++++++++++++ d.set(b"Width".to_vec(), Object::Int(w as i64));+ +++++++++++++++++ d.set(b"Height".to_vec(), Object::Int(h as i64));+ +++++++++++++++++ d.set(b"BitsPerComponent".to_vec(), Object::Int(1));+ +++++++++++++++++ d.set(b"ColorSpace".to_vec(), Object::name("DeviceGray"));+ +++++++++++++++++ let image = doc.add(Object::Stream(Stream::flate(d, &data)));+ +++++++++++++++++ let pages = doc.root().and_then(|r| doc.get(r).as_dict().and_then(|d| d.reference(b"Pages"))).unwrap();+ +++++++++++++++++ let mut x = Dict::new();+ +++++++++++++++++ x.set(b"Scan".to_vec(), Object::Ref(image));+ +++++++++++++++++ let mut res = Dict::new();+ +++++++++++++++++ res.set(b"XObject".to_vec(), Object::Dict(x));-- let content = doc.add(Object::Stream(Stream::from_raw(Dict::new(), b"q 500 0 0 200 50 500 cm /Scan Do Q".to_vec())));+++ +++++++++++++++++ let content = doc.add(Object::Stream(Stream::from_raw(Dict::new(), content.to_vec())));+ +++++++++++++++++ let mut p = Dict::new();+ +++++++++++++++++ p.set(b"Type".to_vec(), Object::name("Page"));+ +++++++++++++++++ p.set(b"Parent".to_vec(), Object::Ref(pages));+ +++++++++++++++++ p.set(b"MediaBox".to_vec(), Object::Array(vec![0.into(), 0.into(), 612.into(), 792.into()]));+ +++++++++++++++++ p.set(b"Resources".to_vec(), Object::Dict(res));+ +++++++++++++++++ p.set(b"Contents".to_vec(), Object::Ref(content));+ +++++++++++++++++ let page = doc.add(Object::Dict(p));+ +++++++++++++++++ doc.update_dict(pages, |d| {+ +++++++++++++++++ d.set(b"Kids".to_vec(), Object::Array(vec![Object::Ref(page)]));+ +++++++++++++++++ d.set(b"Count".to_vec(), Object::Int(1));+ +++++++++++++++++ })+ +++++++++++++++++ .unwrap();+ +++++++++++++++++ write_full(&doc, &SaveOptions::default()).unwrap()+ +++++++++++++++++}+ +++++++++++++++++++ +++++++++++++++++/// A scan saved as a 1-bit PNG becomes a page whose picture stays one bit per pixel (not the eight++ +++++++++++++++++/// bits the PNG decodes to), and Export all images gives the picture back.++ +++++++++++++++++#[test]++ +++++++++++++++++fn a_one_bit_scan_stays_one_bit_and_exports() {++ +++++++++++++++++ let dir = workdir("bilevel");++ +++++++++++++++++ let (w, h) = (800u32, 200u32);++ +++++++++++++++++ let stride = (w as usize).div_ceil(8);++ +++++++++++++++++ let mut bits = vec![0xFFu8; stride * h as usize];++ +++++++++++++++++ for y in 0..h as usize {++ +++++++++++++++++ for x in 0..w as usize {++ +++++++++++++++++ if y % 25 >= 6 && y % 25 < 18 && (x * 7 + y / 25 * 13) % 11 < 4 {++ +++++++++++++++++ bits[y * stride + x / 8] &= !(0x80 >> (x % 8));++ +++++++++++++++++ }++ +++++++++++++++++ }++ +++++++++++++++++ }++ +++++++++++++++++ let mut png_bytes = Vec::new();++ +++++++++++++++++ {++ +++++++++++++++++ let mut enc = png::Encoder::new(&mut png_bytes, w, h);++ +++++++++++++++++ enc.set_color(png::ColorType::Grayscale);++ +++++++++++++++++ enc.set_depth(png::BitDepth::One);++ +++++++++++++++++ enc.write_header().unwrap().write_image_data(&bits).unwrap();++ +++++++++++++++++ }++ +++++++++++++++++ std::fs::write(dir.join("scan.png"), &png_bytes).unwrap();++ +++++++++++++++++ let mut a = auto(&dir);++ +++++++++++++++++ let doc = ok(&mut a, "doc_create", json!({ "from": "images", "paths": ["scan.png"] }))["doc"].as_u64().unwrap();++ +++++++++++++++++ ok(&mut a, "doc_save", json!({ "doc": doc, "path": "scan.pdf" }));++ +++++++++++++++++ let saved = pdfcraft_cos::Document::open(std::sync::Arc::new(std::fs::read(dir.join("scan.pdf")).unwrap())).unwrap();++ +++++++++++++++++ let images: Vec<Option<i64>> = saved++ +++++++++++++++++ .object_numbers()++ +++++++++++++++++ .into_iter()++ +++++++++++++++++ .filter_map(|num| match &*saved.get(pdfcraft_cos::ObjRef { num, generation: saved.generation(num) }) {++ +++++++++++++++++ pdfcraft_cos::Object::Stream(s) if s.dict.name(b"Subtype") == Some(b"Image") => Some(s.dict.int(b"BitsPerComponent")),++ +++++++++++++++++ _ => None,++ +++++++++++++++++ })++ +++++++++++++++++ .collect();++ +++++++++++++++++ assert_eq!(images, [Some(1)]);++ +++++++++++++++++ let r = ok(&mut a, "doc_export_all_images", json!({ "doc": doc, "folder": "out" }));++ +++++++++++++++++ let files = r["files"].as_array().unwrap();++ +++++++++++++++++ assert_eq!(files.len(), 1, "{r}");++ +++++++++++++++++ let exported = std::fs::read(files[0]["path"].as_str().unwrap()).unwrap();++ +++++++++++++++++ let mut reader = png::Decoder::new(std::io::Cursor::new(exported)).read_info().unwrap();++ +++++++++++++++++ let mut buf = vec![0; reader.output_buffer_size().unwrap()];++ +++++++++++++++++ let frame = reader.next_frame(&mut buf).unwrap();++ +++++++++++++++++ let white: Vec<bool> = buf[..frame.buffer_size()].as_chunks::<3>().0.iter().map(|p| *p == [255, 255, 255]).collect();++ +++++++++++++++++ let expected: Vec<bool> =++ +++++++++++++++++ (0..h as usize).flat_map(|y| (0..w as usize).map(move |x| (y, x))).map(|(y, x)| bits[y * stride + x / 8] & (0x80 >> (x % 8)) != 0).collect();++ +++++++++++++++++ assert_eq!(white, expected);++ +++++++++++++++++}++ ++++++++++++++++++ +++++++++++++++++/// A scan's black-and-white image is stored as CCITT Group 4 by default, and kept as it is with+ +++++++++++++++++/// `mono: { compression: retain }`.+ +++++++++++++++++#[test]+ +++++++++++++++++fn doc_optimize_stores_black_and_white_images_as_ccitt_group_4() {+ +++++++++++++++++ let dir = workdir("optimize-mono");+ +++++++++++++++++ std::fs::write(dir.join("scan.pdf"), scanned_page()).unwrap();+ +++++++++++++++++ let mut a = auto(&dir);+ +++++++++++++++++ let doc = ok(&mut a, "doc_open", json!({ "path": "scan.pdf" }))["doc"].as_u64().unwrap();+ +++++++++++++++++ let kept = ok(&mut a, "doc_optimize", json!({ "doc": doc, "path": "kept.pdf", "mono": { "compression": "retain" } }));+ +++++++++++++++++ assert_eq!((kept["images"].as_u64(), kept["images_recompressed"].as_u64()), (Some(1), Some(0)), "{kept}");+ +++++++++++++++++ let r = ok(&mut a, "doc_optimize", json!({ "doc": doc, "path": "small.pdf" }));+ +++++++++++++++++ assert_eq!((r["images"].as_u64(), r["images_recompressed"].as_u64()), (Some(1), Some(1)), "{r}");+ +++++++++++++++++ assert!(r["image_bytes_after"].as_u64() < r["image_bytes_before"].as_u64(), "{r}");+ +++++++++++++++++ // The copy written stores the image as Group 4.+ +++++++++++++++++ let small = pdfcraft_cos::Document::open(std::sync::Arc::new(std::fs::read(dir.join("small.pdf")).unwrap())).unwrap();+ +++++++++++++++++ let filters: Vec<Vec<u8>> = small+ +++++++++++++++++ .object_numbers()+ +++++++++++++++++ .into_iter()+ +++++++++++++++++ .filter_map(|num| match &*small.get(pdfcraft_cos::ObjRef { num, generation: small.generation(num) }) {+ +++++++++++++++++ pdfcraft_cos::Object::Stream(s) if s.dict.name(b"Subtype") == Some(b"Image") => s.dict.name(b"Filter").map(<[u8]>::to_vec),+ +++++++++++++++++ _ => None,+ +++++++++++++++++ })+ +++++++++++++++++ .collect();+ +++++++++++++++++ assert_eq!(filters, [b"CCITTFaxDecode".to_vec()]);+ +++++++++++++++++ // An unknown compression, one that isn't a name, a misspelled key, or a mono that isn't an+ +++++++++++++++++ // object is refused, not read as the default.+ +++++++++++++++++ for mono in [json!({ "compression": "jbig2" }), json!({ "compression": false }), json!({ "compresson": "retain" }), json!("retain")] {+ +++++++++++++++++ assert!(matches!(a.call("doc_optimize", &json!({ "doc": doc, "path": "x.pdf", "mono": mono })), Err(ToolError::InvalidArgs(_))), "{mono}");+ +++++++++++++++++ }+ +++++++++++++++++}+ ++++++++++++++++++++ +++++++++++++++++/// A scan drawn at 600 ppi is averaged down to 300 ppi by default. `mono: { downsample: false }`+++ +++++++++++++++++/// keeps its size, `ppi` and `above_ppi` choose others, and values of the wrong type are refused.+++ +++++++++++++++++#[test]+++ +++++++++++++++++fn doc_optimize_averages_black_and_white_scans_down() {+++ +++++++++++++++++ let dir = workdir("optimize-mono-downsample");+++ +++++++++++++++++ // 1000 × 400 samples on 120 × 48 pt: 600 ppi.+++ +++++++++++++++++ std::fs::write(dir.join("scan.pdf"), scan_drawn(b"q 120 0 0 48 50 500 cm /Scan Do Q")).unwrap();+++ +++++++++++++++++ let mut a = auto(&dir);+++ +++++++++++++++++ let doc = ok(&mut a, "doc_open", json!({ "path": "scan.pdf" }))["doc"].as_u64().unwrap();+++ +++++++++++++++++ let sizes = |name: &str| image_sizes(&dir.join(name));+++ +++++++++++++++++ let r = ok(&mut a, "doc_optimize", json!({ "doc": doc, "path": "small.pdf" }));+++ +++++++++++++++++ assert_eq!(r["images_resampled"].as_u64(), Some(1), "{r}");+++ +++++++++++++++++ assert_eq!(sizes("small.pdf"), [(Some(500), Some(200))]);+++ +++++++++++++++++ let r = ok(&mut a, "doc_optimize", json!({ "doc": doc, "path": "kept.pdf", "mono": { "downsample": false } }));+++ +++++++++++++++++ assert_eq!(r["images_resampled"].as_u64(), Some(0), "{r}");+++ +++++++++++++++++ assert_eq!(sizes("kept.pdf"), [(Some(1000), Some(400))]);+++ +++++++++++++++++ ok(&mut a, "doc_optimize", json!({ "doc": doc, "path": "200.pdf", "mono": { "ppi": 200, "above_ppi": 250 } }));+++ +++++++++++++++++ assert_eq!(sizes("200.pdf"), [(Some(333), Some(133))]);+++ +++++++++++++++++ for mono in [json!({ "downsample": "yes" }), json!({ "ppi": "300" }), json!({ "above": 450 })] {+++ +++++++++++++++++ assert!(matches!(a.call("doc_optimize", &json!({ "doc": doc, "path": "x.pdf", "mono": mono })), Err(ToolError::InvalidArgs(_))), "{mono}");+++ +++++++++++++++++ }+++ +++++++++++++++++}+++ ++++++++++++++++++++ +++++++++++++++++/// The width and height of every image in the PDF at `path`.+++ +++++++++++++++++fn image_sizes(path: &std::path::Path) -> Vec<(Option<i64>, Option<i64>)> {+++ +++++++++++++++++ let written = pdfcraft_cos::Document::open(std::sync::Arc::new(std::fs::read(path).unwrap())).unwrap();+++ +++++++++++++++++ written+++ +++++++++++++++++ .object_numbers()+++ +++++++++++++++++ .into_iter()+++ +++++++++++++++++ .filter_map(|num| match &*written.get(pdfcraft_cos::ObjRef { num, generation: written.generation(num) }) {+++ +++++++++++++++++ pdfcraft_cos::Object::Stream(s) if s.dict.name(b"Subtype") == Some(b"Image") => Some((s.dict.int(b"Width"), s.dict.int(b"Height"))),+++ +++++++++++++++++ _ => None,+++ +++++++++++++++++ })+++ +++++++++++++++++ .collect()+++ +++++++++++++++++}+++ ++++++++++++++++++++ +++++++++++++++++/// The batch optimize step's `ppi` reaches black-and-white images too: they go to the larger of+++ +++++++++++++++++/// it and Reduce File Size's 300 ppi. Before, a batch run took every scan to 300 ppi whatever+++ +++++++++++++++++/// `ppi` said, so `ppi: 600` halved 600 ppi scans.+++ +++++++++++++++++#[test]+++ +++++++++++++++++fn batch_ppi_bounds_how_far_black_and_white_scans_are_resampled() {+++ +++++++++++++++++ let dir = workdir("batch-mono-ppi");+++ +++++++++++++++++ // 1000 × 400 samples on 120 × 48 pt: 600 ppi.+++ +++++++++++++++++ std::fs::write(dir.join("scan.pdf"), scan_drawn(b"q 120 0 0 48 50 500 cm /Scan Do Q")).unwrap();+++ +++++++++++++++++ let mut a = auto(&dir);+++ +++++++++++++++++ for (ppi, size) in [(None, (500, 200)), (Some(600), (1000, 400)), (Some(96), (500, 200))] {+++ +++++++++++++++++ let out = format!("out-{ppi:?}");+++ +++++++++++++++++ let mut args = json!({ "paths": ["scan.pdf"], "steps": ["optimize"], "out_dir": out });+++ +++++++++++++++++ if let Some(ppi) = ppi {+++ +++++++++++++++++ args["ppi"] = json!(ppi);+++ +++++++++++++++++ }+++ +++++++++++++++++ let report = ok(&mut a, "doc_batch", args);+++ +++++++++++++++++ assert_eq!(report["completed"], 1, "{report}");+++ +++++++++++++++++ assert_eq!(image_sizes(&dir.join(&out).join("scan.pdf")), [(Some(size.0), Some(size.1))], "ppi {ppi:?}");+++ +++++++++++++++++ }+++ +++++++++++++++++}+++ +++++++++++++++++/// A one-page PDF whose page picture is drawn as `rows` grey images one pixel row high, 600 px/// wide on a 72 pt square (600 ppi), as some PDF printers write it.fn printed_in_strips(rows: usize) -> Vec<u8> {@@@@@@@@@@@@@@@@@@@@@@@ -9385,75 -9475,75 -9524,75 -9586,75 -9586,75 -9175,3 -9385,75 -9414,75 -9385,75 -9339,24 -9175,3 -9339,24 -9339,24 -9385,75 -9243,3 -9385,75 -9239,3 -9385,75 -9175,3 -9239,3 -9385,75 -9417,75 +9651,75 @@@@@@@@@@@@@@@@@@@@@@@ fn page_render_draws_stamps_without_an_let grey = custom.iter().filter(|p| p[0].abs_diff(p[1]) < 24 && p[1].abs_diff(p[2]) < 24).count();assert!(grey > 100 && grey == custom.len(), "an unknown name is a grey placeholder: {grey} of {}", custom.len());}+ + + + +++ + + + ++ #[test]+ + + + ++ fn deleting_one_radio_button_through_tools_keeps_the_group() {+ + + + ++ let dir = workdir("delete-radio");+ + + + ++ let mut a = auto(&dir);+ + + + ++ let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap();+ + + + ++ for (x, export) in [(20, "S"), (40, "M"), (60, "L")] {+ + + + ++ let args = json!({ "doc": doc, "page": 1, "type": "radio", "rect": [x, 100, x + 14, 114], "group": "size", "export": export });+ + + + ++ ok(&mut a, "form_add_field", args);+ + + + ++ }+ + + + ++ ok(&mut a, "form_fill", json!({ "doc": doc, "values": { "size": "L" } }));+ + + + ++ ok(&mut a, "form_delete_field", json!({ "doc": doc, "field": "size", "widget": 2 }));+ + + + ++ let size = |a: &mut Automation| ok(a, "form_fields", json!({ "doc": doc }))["fields"][0].clone();+ + + + ++ assert_eq!((size(&mut a)["options"].clone(), size(&mut a)["value"].clone()), (json!(["S", "L"]), json!("L")), "only M is gone");+ + + + ++ for widget in [0, 3, -1] {+ + + + ++ let r = a.call("form_delete_field", &json!({ "doc": doc, "field": "size", "widget": widget }));+ + + + ++ assert!(matches!(r, Err(ToolError::InvalidArgs(_))), "widget {widget}: {r:?}");+ + + + ++ }+ + + + ++ ok(&mut a, "edit_undo", json!({ "doc": doc }));+ + + + ++ assert_eq!(size(&mut a)["options"], json!(["S", "M", "L"]), "one undo step brings it back");+ + + + ++ }+ ++++ + + ++ /// `/I` of the top-level field `name` in the saved file `path`.+ ++++ + + ++ fn saved_selection_indices(path: &Path, name: &str) -> Option<Vec<i64>> {+ ++++ + + ++ let d = pdfcraft_cos::Document::open(std::sync::Arc::new(std::fs::read(path).unwrap())).unwrap();+ ++++ + + ++ let root = d.get(d.root().unwrap()).as_dict().cloned().unwrap();+ ++++ + + ++ let form = d.resolve(root.get(b"AcroForm").unwrap()).as_dict().cloned().unwrap();+ ++++ + + ++ let all = d.resolve(form.get(b"Fields").unwrap()).as_array().cloned().unwrap();+ ++++ + + ++ let f = all+ ++++ + + ++ .iter()+ ++++ + + ++ .filter_map(|o| d.resolve(o).as_dict().cloned())+ ++++ + + ++ .find(|f| f.get(b"T").and_then(|t| d.resolve(t).as_string().map(|s| s.to_text())).as_deref() == Some(name))+ ++++ + + ++ .unwrap();+ ++++ + + ++ f.get(b"I").map(|i| d.resolve(i).as_array().unwrap().iter().map(|o| o.as_int().unwrap()).collect())+ ++++ + + ++ }+ ++++ + + +++ ++++ + + ++ #[test]+ ++++ + + ++ fn changing_a_lists_options_through_tools_keeps_its_saved_selection_on_the_same_items() {+ ++++ + + ++ let dir = workdir("choice-index");+ ++++ + + ++ let mut a = auto(&dir);+ ++++ + + ++ let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap();+ ++++ + + ++ let args = json!({ "doc": doc, "page": 1, "type": "list", "rect": [20, 60, 180, 140], "options": ["A", "B", "C"], "multi_select": true, "name": "letters" });+ ++++ + + ++ ok(&mut a, "form_add_field", args);+ ++++ + + ++ ok(&mut a, "form_fill", json!({ "doc": doc, "values": { "letters": ["B", "C"] } }));+ ++++ + + ++ ok(&mut a, "form_set_props", json!({ "doc": doc, "field": "letters", "options": ["B", "C", "D"] }));+ ++++ + + ++ ok(&mut a, "doc_save", json!({ "doc": doc, "path": "letters.pdf" }));+ ++++ + + ++ assert_eq!(saved_selection_indices(&dir.join("letters.pdf"), "letters"), Some(vec![0, 1]), "B and C are now items 0 and 1");+ ++++ + + ++ }+ ++++ + + +++ ++++ + + ++ /// Clearing a field's default through `form_set_props` (`"default": ""`) leaves it with none,+ ++++ + + ++ /// even when its parent field has one it would otherwise inherit.+ ++++ + + ++ #[test]+ ++++ + + ++ fn clearing_a_kids_default_through_tools_does_not_bring_back_its_parents() {+ ++++ + + ++ let objs = [+ ++++ + + ++ "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>",+ ++++ + + ++ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 400 300] >>",+ ++++ + + ++ "<< /Type /Page /Parent 2 0 R /Annots [6 0 R] >>",+ ++++ + + ++ "<< /Fields [5 0 R] /DA (/Helv 12 Tf 0 g) /DR << /Font << /Helv 7 0 R >> >> >>",+ ++++ + + ++ "<< /T (address) /FT /Tx /DV (Main St) /Kids [6 0 R] >>",+ ++++ + + ++ "<< /Type /Annot /Subtype /Widget /T (city) /Parent 5 0 R /DV (Elm) /V (Elm) /Rect [10 250 150 268] /P 3 0 R >>",+ ++++ + + ++ "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>",+ ++++ + + ++ ];+ ++++ + + ++ let dir = workdir("kid-default");+ ++++ + + ++ std::fs::write(dir.join("form.pdf"), pdf_of(&objs)).unwrap();+ ++++ + + ++ let mut a = auto(&dir);+ ++++ + + ++ let doc = ok(&mut a, "doc_open", json!({ "path": "form.pdf" }))["doc"].as_u64().unwrap();+ ++++ + + ++ ok(&mut a, "form_set_props", json!({ "doc": doc, "field": "address.city", "default": "" }));+ ++++ + + ++ ok(&mut a, "form_fill", json!({ "doc": doc, "values": { "address.city": "Oak" } }));+ ++++ + + ++ ok(&mut a, "form_reset", json!({ "doc": doc }));+ ++++ + + ++ let fields = ok(&mut a, "form_fields", json!({ "doc": doc }));+ ++++ + + ++ let city = fields["fields"].as_array().unwrap().iter().find(|f| f["name"] == "address.city").unwrap().clone();+ ++++ + + ++ assert!(city["value"].is_null() || city["value"] == "", "reset clears it rather than restoring the parent's Main St: {}", city["value"]);+ ++++ + + ++ }diff --cc crates/automation/tests/it/main.rsindex b48b23bf0,b48b23bf0,b48b23bf0,b48b23bf0,b48b23bf0,d94aa9f7c,b48b23bf0,b48b23bf0,b48b23bf0,ee74968a9,d94aa9f7c,d94aa9f7c,d94aa9f7c,b48b23bf0,d94aa9f7c,b48b23bf0,d94aa9f7c,73725be64,d94aa9f7c,d94aa9f7c,b48b23bf0,b48b23bf0..d36dbe93a--- a/crates/automation/tests/it/main.rs+++ b/crates/automation/tests/it/main.rs@@@@@@@@@@@@@@@@@@@@@@@ -8,5 -8,5 -8,5 -8,5 -8,5 -8,3 -8,5 -8,5 -8,5 -9,3 -8,3 -8,3 -8,3 -8,5 -8,3 -8,5 -8,3 -8,6 -8,3 -8,3 -8,5 -8,5 +9,6 @@@@@@@@@@@@@@@@@@@@@@@ mod button_captionmod form_bulk;mod hostile_args;mod optimize_content_boundaries;+ ++++ + + ++ mod redact_after_stray_q_form;+ ++++ + + ++ mod redact_text_after_q;+++++++++++++++++ ++++mod render_warnings;diff --cc crates/cos/src/document/open.rsindex d41d564e3,d41d564e3,d41d564e3,d41d564e3,d41d564e3,c90d5c090,d41d564e3,d41d564e3,d41d564e3,d41d564e3,c90d5c090,d41d564e3,d41d564e3,d41d564e3,d41d564e3,d41d564e3,d41d564e3,d41d564e3,8b9b914ce,d41d564e3,d41d564e3,d41d564e3..57d697ed6--- a/crates/cos/src/document/open.rs+++ b/crates/cos/src/document/open.rs@@@@@@@@@@@@@@@@@@@@@@@ -1,7 -1,7 -1,7 -1,7 -1,7 -1,7 -1,7 -1,7 -1,7 -1,7 -1,7 -1,7 -1,7 -1,7 -1,7 -1,7 -1,7 -1,7 -1,7 -1,7 -1,7 -1,7 +1,7 @@@@@@@@@@@@@@@@@@@@@@@------------------ ---use super::reader::{find, generated_id};++++++++++++++++++ +++use super::reader::find;use super::state::Credentials;use super::xref::XrefIndex;- - - use super::*;+ + + use super::{Arc, BTreeMap, CosError, Dict, Document, ObjRef, Object};impl Document {/// A new document with an empty page tree (for split / extract / combine). It has nodiff --cc crates/cos/src/document/tests.rsindex bf22f23d7,d8d75c4af,d8d75c4af,96b407834,96b407834,bf22f23d7,bf22f23d7,bf22f23d7,bf22f23d7,bf22f23d7,bf22f23d7,bf22f23d7,bf22f23d7,bf22f23d7,bf22f23d7,bf22f23d7,bf22f23d7,bf22f23d7,0ec2cc3a8,bf22f23d7,bf22f23d7,bf22f23d7..f5e36f9c8--- a/crates/cos/src/document/tests.rs+++ b/crates/cos/src/document/tests.rs@@@@@@@@@@@@@@@@@@@@@@@ -1,5 -1,84 -1,84 -1,178 -1,178 -1,5 -1,5 -1,5 -1,5 -1,5 -1,5 -1,5 -1,5 -1,5 -1,5 -1,5 -1,5 -1,5 -1,37 -1,5 -1,5 -1,5 +1,210 @@@@@@@@@@@@@@@@@@@@@@@use super::*;+ +++++++++++++++++/// /DecodeParms given by reference, whole, as array entries or as the numbers inside, are read+ +++++++++++++++++/// once made direct: here a Flate predictor, which the stream alone doesn't see. Only the entries the filters use are+ +++++++++++++++++/// resolved, and nothing is for a chain longer than a decoder takes.+ +++++++++++++++++#[test]+ +++++++++++++++++fn decode_parms_given_by_reference_are_read_once_direct() {+ +++++++++++++++++ let rows = [1u8, 2, 3, 4, 5, 6, 7, 8];+ +++++++++++++++++ let params = pdfcraft_filters::Params { predictor: 12, colors: 1, bits_per_component: 8, columns: 4, early_change: 1 };+ +++++++++++++++++ let coded = pdfcraft_filters::encode(&pdfcraft_filters::Filter::Flate, ¶ms, &rows).unwrap();+ +++++++++++++++++ let mut parms = Dict::new();+ +++++++++++++++++ parms.set(b"Predictor".to_vec(), Object::Int(12));+ +++++++++++++++++ parms.set(b"Columns".to_vec(), Object::Int(4));+ +++++++++++++++++ let mut doc = Document::new_empty();+ +++++++++++++++++ let r = doc.add(Object::Dict(parms.clone()));+ +++++++++++++++++ let array = doc.add(Object::Array(vec![Object::Ref(r)]));+ +++++++++++++++++ let stream = |filters: usize, p: Object| {+ +++++++++++++++++ let mut d = Dict::new();+ +++++++++++++++++ d.set(b"Filter".to_vec(), Object::Array(vec![Object::name("FlateDecode"); filters]));+ +++++++++++++++++ d.set(b"DecodeParms".to_vec(), p);+ +++++++++++++++++ Stream::from_raw(d, coded.clone())+ +++++++++++++++++ };+ +++++++++++++++++ for p in [Object::Ref(r), Object::Array(vec![Object::Ref(r)]), Object::Ref(array)] {+ +++++++++++++++++ let s = stream(1, p.clone());+ +++++++++++++++++ assert_ne!(s.decoded().unwrap(), rows, "{p:?} read as it is");+ +++++++++++++++++ assert_eq!(doc.with_direct_parms(&s).decoded().unwrap(), rows, "{p:?}");+ +++++++++++++++++ }+ +++++++++++++++++ // A number inside given by reference, which `Dict::int` doesn't follow: in the dictionary+ +++++++++++++++++ // itself, and in an array's entry.+ +++++++++++++++++ let twelve = doc.add(Object::Int(12));+ +++++++++++++++++ let mut inner = parms.clone();+ +++++++++++++++++ inner.set(b"Predictor".to_vec(), Object::Ref(twelve));+ +++++++++++++++++ for p in [Object::Dict(inner.clone()), Object::Array(vec![Object::Dict(inner)])] {+ +++++++++++++++++ let s = stream(1, p.clone());+ +++++++++++++++++ assert_ne!(s.decoded().unwrap(), rows, "{p:?} read as it is");+ +++++++++++++++++ assert_eq!(doc.with_direct_parms(&s).decoded().unwrap(), rows, "{p:?}");+ +++++++++++++++++ }+ +++++++++++++++++ // Only numbers and flags are copied: a key naming a big array, or an entry that is no+ +++++++++++++++++ // dictionary, is left out (a file could name one big object from every key and filter).+ +++++++++++++++++ let big = doc.add(Object::Array(vec![Object::Int(1); 100_000]));+ +++++++++++++++++ let mut hostile = Dict::new();+ +++++++++++++++++ hostile.set(b"Predictor".to_vec(), Object::Ref(big));+ +++++++++++++++++ hostile.set(b"Columns".to_vec(), Object::Ref(big));+ +++++++++++++++++ hostile.set(b"Colors".to_vec(), Object::Ref(twelve));+ +++++++++++++++++ let entry = doc.add(Object::Dict(hostile));+ +++++++++++++++++ let two = stream(2, Object::Array(vec![Object::Ref(entry), Object::Ref(big)]));+ +++++++++++++++++ let made = doc.with_direct_parms(&two);+ +++++++++++++++++ let made = made.dict.get(b"DecodeParms").and_then(Object::as_array).unwrap();+ +++++++++++++++++ let first = made[0].as_dict().unwrap();+ +++++++++++++++++ assert_eq!((first.contains(b"Predictor"), first.contains(b"Columns"), first.int(b"Colors")), (false, false, Some(12)));+ +++++++++++++++++ assert!(matches!(made[1], Object::Null), "{:?}", made[1]);+ +++++++++++++++++ let direct = stream(1, Object::Dict(parms));+ +++++++++++++++++ assert!(matches!(doc.with_direct_parms(&direct), Cow::Borrowed(_)), "nothing to resolve");+ +++++++++++++++++ assert_eq!(direct.decoded().unwrap(), rows);+ +++++++++++++++++ // Entries past the filters' are left out, unresolved; so is everything past the chain limit.+ +++++++++++++++++ let many = stream(1, Object::Array(vec![Object::Ref(r); 1000]));+ +++++++++++++++++ let made = doc.with_direct_parms(&many);+ +++++++++++++++++ assert_eq!(made.dict.get(b"DecodeParms").and_then(Object::as_array).map(Vec::len), Some(1));+ +++++++++++++++++ let long = stream(pdfcraft_filters::MAX_CHAIN + 1, Object::Array(vec![Object::Ref(r); 9]));+ +++++++++++++++++ assert!(matches!(doc.with_direct_parms(&long), Cow::Borrowed(_)));+ +++++++++++++++++ // A chain as long as a decoder takes is resolved, and a `/Crypt` in it doesn't count, as+ +++++++++++++++++ // the decoders leave it out: ASCIIHex as often as the limit allows, then the predictor's+ +++++++++++++++++ // Flate, its parameters by reference.+ +++++++++++++++++ let hex = |b: &[u8]| b.iter().flat_map(|x| format!("{x:02X}").into_bytes()).chain(*b">").collect::<Vec<u8>>();+ +++++++++++++++++ let wrapped = (1..pdfcraft_filters::MAX_CHAIN).fold(coded.clone(), |data, _| hex(&data));+ +++++++++++++++++ for crypt in [false, true] {+ +++++++++++++++++ let mut names = vec![Object::name("ASCIIHexDecode"); pdfcraft_filters::MAX_CHAIN - 1];+ +++++++++++++++++ names.push(Object::name("FlateDecode"));+ +++++++++++++++++ if crypt {+ +++++++++++++++++ names.insert(0, Object::name("Crypt"));+ +++++++++++++++++ }+ +++++++++++++++++ let mut entries = vec![Object::Null; names.len() - 1];+ +++++++++++++++++ entries.push(Object::Ref(r));+ +++++++++++++++++ let mut d = Dict::new();+ +++++++++++++++++ d.set(b"Filter".to_vec(), Object::Array(names));+ +++++++++++++++++ d.set(b"DecodeParms".to_vec(), Object::Array(entries));+ +++++++++++++++++ let s = Stream::from_raw(d, wrapped.clone());+ +++++++++++++++++ assert_eq!(doc.with_direct_parms(&s).decoded().unwrap(), rows, "with /Crypt: {crypt}");+ +++++++++++++++++ }+ +++++++++++++++++}+ ++++++++++++++++++++ +++++++++++++++++/// A CCITT fax image reads through its /DecodeParms, given directly, in an array or by+++ +++++++++++++++++/// reference (its numbers too), with /BlackIs1, and behind other filters; one whose /Columns+++ +++++++++++++++++/// aren't its /Width is refused, /Height rows are decoded whatever /Rows says, and other images+++ +++++++++++++++++/// decode through their filters.+++ +++++++++++++++++#[test]+++ +++++++++++++++++fn fax_images_decode_with_their_parameters() {+++ +++++++++++++++++ // 10 × 3: the first five samples of each row white, the rest black.+++ +++++++++++++++++ let bits = [0b1111_1000, 0, 0b1111_1000, 0, 0b1111_1000, 0];+++ +++++++++++++++++ let coded = pdfcraft_filters::encode_g4(&bits, 10, 3).unwrap();+++ +++++++++++++++++ let mut doc = Document::new_empty();+++ +++++++++++++++++ let mut parms = Dict::new();+++ +++++++++++++++++ parms.set(b"K".to_vec(), Object::Int(-1));+++ +++++++++++++++++ parms.set(b"Columns".to_vec(), Object::Int(10));+++ +++++++++++++++++ let indirect = doc.add(Object::Dict(parms.clone()));+++ +++++++++++++++++ let image = |doc: &Document, parms: Option<Object>, width: i64, height: i64| {+++ +++++++++++++++++ let mut d = Dict::new();+++ +++++++++++++++++ d.set(b"Width".to_vec(), Object::Int(width));+++ +++++++++++++++++ d.set(b"Height".to_vec(), Object::Int(height));+++ +++++++++++++++++ d.set(b"Filter".to_vec(), Object::name("CCITTFaxDecode"));+++ +++++++++++++++++ if let Some(p) = parms {+++ +++++++++++++++++ d.set(b"DecodeParms".to_vec(), p);+++ +++++++++++++++++ }+++ +++++++++++++++++ doc.decoded_image(&Stream::from_raw(d, coded.clone()))+++ +++++++++++++++++ };+++ +++++++++++++++++ for p in [+++ +++++++++++++++++ Object::Dict(parms.clone()),+++ +++++++++++++++++ Object::Array(vec![Object::Dict(parms.clone())]),+++ +++++++++++++++++ Object::Ref(indirect),+++ +++++++++++++++++ Object::Array(vec![Object::Ref(indirect)]),+++ +++++++++++++++++ ] {+++ +++++++++++++++++ assert_eq!(image(&doc, Some(p.clone()), 10, 3).unwrap(), bits, "{p:?}");+++ +++++++++++++++++ }+++ +++++++++++++++++ let mut inverted = parms.clone();+++ +++++++++++++++++ inverted.set(b"BlackIs1".to_vec(), Object::Bool(true));+++ +++++++++++++++++ assert_eq!(+++ +++++++++++++++++ image(&doc, Some(Object::Dict(inverted)), 10, 3).unwrap(),+++ +++++++++++++++++ [0b0000_0111, 0b1100_0000, 0b0000_0111, 0b1100_0000, 0b0000_0111, 0b1100_0000]+++ +++++++++++++++++ );+++ +++++++++++++++++ assert_eq!(image(&doc, Some(Object::Dict(parms.clone())), 10, 2).unwrap(), bits[..4], "at most /Height rows");+++ +++++++++++++++++ // Within a bound: no more rows than it holds.+++ +++++++++++++++++ let mut bounded = Dict::new();+++ +++++++++++++++++ bounded.set(b"Width".to_vec(), Object::Int(10));+++ +++++++++++++++++ bounded.set(b"Height".to_vec(), Object::Int(3));+++ +++++++++++++++++ bounded.set(b"Filter".to_vec(), Object::name("CCITTFaxDecode"));+++ +++++++++++++++++ bounded.set(b"DecodeParms".to_vec(), Object::Dict(parms.clone()));+++ +++++++++++++++++ assert_eq!(doc.decoded_image_within(&Stream::from_raw(bounded, coded.clone()), 5).unwrap(), bits[..4], "two rows of two bytes in five");+++ +++++++++++++++++ let mut by_reference = Dict::new();+++ +++++++++++++++++ by_reference.set(b"K".to_vec(), Object::Ref(doc.add(Object::Int(-1))));+++ +++++++++++++++++ by_reference.set(b"Columns".to_vec(), Object::Ref(doc.add(Object::Int(10))));+++ +++++++++++++++++ assert_eq!(image(&doc, Some(Object::Dict(by_reference)), 10, 3).unwrap(), bits, "/K and /Columns by reference");+++ +++++++++++++++++ let mut understated = parms.clone();+++ +++++++++++++++++ understated.set(b"Rows".to_vec(), Object::Int(1));+++ +++++++++++++++++ assert_eq!(image(&doc, Some(Object::Dict(understated.clone())), 10, 3).unwrap(), bits, "/Height rows, whatever /Rows says");+++ +++++++++++++++++ // The parameters as the file gives them, /Rows included, and Table 11's defaults.+++ +++++++++++++++++ let mut d = Dict::new();+++ +++++++++++++++++ d.set(b"Filter".to_vec(), Object::name("CCITTFaxDecode"));+++ +++++++++++++++++ d.set(b"DecodeParms".to_vec(), Object::Dict(understated));+++ +++++++++++++++++ let p = doc.fax_params(&Stream::from_raw(d.clone(), Vec::new())).unwrap();+++ +++++++++++++++++ assert_eq!((p.k, p.columns, p.rows, p.end_of_block, p.black_is_1), (-1, 10, 1, true, false));+++ +++++++++++++++++ d.set(b"Filter".to_vec(), Object::name("FlateDecode"));+++ +++++++++++++++++ assert!(doc.fax_params(&Stream::from_raw(d, Vec::new())).is_none(), "not a fax image");+++ +++++++++++++++++ assert!(matches!(image(&doc, Some(Object::Dict(parms.clone())), 12, 3), Err(CosError::Filter(_))), "/Columns other than /Width");+++ +++++++++++++++++ assert!(matches!(image(&doc, None, 10, 3), Err(CosError::Filter(_))), "the default 1728 /Columns");+++ +++++++++++++++++ let mut plain = Dict::new();+++ +++++++++++++++++ plain.set(b"Filter".to_vec(), Object::name("FlateDecode"));+++ +++++++++++++++++ assert_eq!(doc.decoded_image(&Stream::from_raw(plain, pdfcraft_filters::encode_flate(&bits))).unwrap(), bits);+++ ++++++++++++++++++++ +++++++++++++++++ // Behind other filters, its parameters at its own place in the array (/Crypt counts).+++ +++++++++++++++++ let behind = |filters: &[Object], parms: &[Object], data: Vec<u8>| {+++ +++++++++++++++++ let mut d = Dict::new();+++ +++++++++++++++++ d.set(b"Width".to_vec(), Object::Int(10));+++ +++++++++++++++++ d.set(b"Height".to_vec(), Object::Int(3));+++ +++++++++++++++++ d.set(b"Filter".to_vec(), Object::Array(filters.to_vec()));+++ +++++++++++++++++ d.set(b"DecodeParms".to_vec(), Object::Array(parms.to_vec()));+++ +++++++++++++++++ doc.decoded_image(&Stream::from_raw(d, data))+++ +++++++++++++++++ };+++ +++++++++++++++++ let (fax, null, own) = (Object::name("CCITTFaxDecode"), Object::Null, Object::Dict(parms.clone()));+++ +++++++++++++++++ let hex = coded.iter().map(|b| format!("{b:02x}")).chain([">".to_string()]).collect::<String>().into_bytes();+++ +++++++++++++++++ let flated = pdfcraft_filters::encode_flate(&coded);+++ +++++++++++++++++ let ahx = [Object::name("AHx"), fax.clone()];+++ +++++++++++++++++ assert_eq!(behind(&ahx, &[null.clone(), Object::Ref(indirect)], hex.clone()).unwrap(), bits, "behind ASCIIHexDecode");+++ +++++++++++++++++ assert_eq!(+++ +++++++++++++++++ behind(&[Object::name("FlateDecode"), Object::name("CCF")], &[null.clone(), own.clone()], flated.clone()).unwrap(),+++ +++++++++++++++++ bits,+++ +++++++++++++++++ "behind Flate"+++ +++++++++++++++++ );+++ +++++++++++++++++ assert_eq!(behind(&[Object::name("Crypt"), fax.clone()], &[null.clone(), own.clone()], coded.clone()).unwrap(), bits, "after /Crypt");+++ +++++++++++++++++ // A /Crypt belongs first (§7.4.10); one after the fax filter leaves it its own entry.+++ +++++++++++++++++ assert_eq!(behind(&[fax.clone(), Object::name("Crypt")], &[own.clone(), null.clone()], coded.clone()).unwrap(), bits, "before /Crypt");+++ +++++++++++++++++ assert!(behind(&ahx, &[own.clone(), null.clone()], hex).is_err(), "the first entry is the other filter's");+++ +++++++++++++++++ assert!(behind(&[fax.clone(), Object::name("FlateDecode")], &[own.clone(), null.clone()], flated).is_err(), "CCITT, then Flate");+++ +++++++++++++++++ assert!(behind(&[Object::Int(5), fax], &[null, own], coded.clone()).is_err(), "a /Filter entry that isn't a name");+++ +++++++++++++++++}+++ +++++++++++++++++++++++++++++++++++ +++#[test]++++++++++++++++++ +++fn a_missing_file_id_is_derived_from_the_encryption_seed() {++++++++++++++++++ +++ let mut doc = Document::new_empty();++++++++++++++++++ +++ let seed = [9u8; 32];++++++++++++++++++ +++ doc.set_encryption(&pdfcraft_crypt::NewEncryption {++++++++++++++++++ +++ algorithm: pdfcraft_crypt::Algorithm::Aes256,++++++++++++++++++ +++ user_password: "user",++++++++++++++++++ +++ owner_password: "owner",++++++++++++++++++ +++ permissions: -4,++++++++++++++++++ +++ encrypt_metadata: true,++++++++++++++++++ +++ seed,++++++++++++++++++ +++ })++++++++++++++++++ +++ .unwrap();++++++++++++++++++ +++ let id = doc.trailer().get(b"ID").and_then(|o| o.as_array()).and_then(|a| a.first()).and_then(|o| o.as_string()).map(|s| s.bytes.clone());++++++++++++++++++ +++ assert_eq!(id.as_deref(), Some(pdfcraft_crypt::file_id(&seed).as_slice()));++++++++++++++++++ +++++++++++++++++++++ +++ let mut kept = Document::new_empty();++++++++++++++++++ +++ let fixed = Object::String(crate::PdfString { bytes: b"0123456789abcdef".to_vec(), hex: true });++++++++++++++++++ +++ kept.trailer_mut().set(b"ID".to_vec(), Object::Array(vec![fixed.clone(), fixed]));++++++++++++++++++ +++ kept.set_encryption(&pdfcraft_crypt::NewEncryption {++++++++++++++++++ +++ algorithm: pdfcraft_crypt::Algorithm::Aes256,++++++++++++++++++ +++ user_password: "user",++++++++++++++++++ +++ owner_password: "owner",++++++++++++++++++ +++ permissions: -4,++++++++++++++++++ +++ encrypt_metadata: true,++++++++++++++++++ +++ seed,++++++++++++++++++ +++ })++++++++++++++++++ +++ .unwrap();++++++++++++++++++ +++ let still = kept.trailer().get(b"ID").and_then(|o| o.as_array()).and_then(|a| a.first()).and_then(|o| o.as_string()).map(|s| s.bytes.clone());++++++++++++++++++ +++ assert_eq!(still.as_deref(), Some(b"0123456789abcdef".as_slice()));++++++++++++++++++ +++}++++++++++++++++++ +++#[test]fn a_read_state_matches_a_clone_and_no_changed_document() {let mut doc = Document::new_empty();diff --cc crates/engine/src/edit/run.rsindex 32dc7942a,32dc7942a,32dc7942a,32dc7942a,32dc7942a,7901a3b7d,32dc7942a,32dc7942a,32dc7942a,32dc7942a,7901a3b7d,32dc7942a,32dc7942a,32dc7942a,49f19fa63,32dc7942a,49f19fa63,32dc7942a,2c64fbb75,49f19fa63,32dc7942a,32dc7942a..c6b1a7438--- a/crates/engine/src/edit/run.rs+++ b/crates/engine/src/edit/run.rs@@@@@@@@@@@@@@@@@@@@@@@ -1,9 -1,9 -1,9 -1,9 -1,9 -1,4 -1,9 -1,9 -1,9 -1,9 -1,4 -1,9 -1,9 -1,9 -1,7 -1,9 -1,7 -1,9 -1,4 -1,7 -1,9 -1,9 +1,9 @@@@@@@@@@@@@@@@@@@@@@@- - - use super::*;+ + + use super::{+ + + AddedContent, Arc, Edit, EditError, FieldValue, ImageEdit, NewAnnotation, Shape, a11y, copy_image, decode_data_file, embed_image, fit_picture,+ + + image_content_type, is_xfa_data_file, js, mark_source, measure, open_source, strip_xfa, unrestricted, xfa, xfa_after_data_change,+ + + };+ + + + ++ use crate::SourceProblem;+ + + + ++ use crate::sources::{comment_source, import_pdf_comments};/// Whether the opening password allows an edit (§7.6.4.2, Table 22).pub(crate) fn check_permission(edit: &Edit, p: &pdfcraft_cos::Permissions) -> Result<(), EditError> {diff --cc crates/engine/src/lib.rsindex c41c0466c,c41c0466c,c41c0466c,c41c0466c,c41c0466c,889b83936,c41c0466c,c41c0466c,cb3297b9d,9f3927fc9,889b83936,2d4c2bb15,2d4c2bb15,c41c0466c,889b83936,c41c0466c,889b83936,c41c0466c,889b83936,889b83936,c41c0466c,c41c0466c..c8744c4a0--- a/crates/engine/src/lib.rs+++ b/crates/engine/src/lib.rs@@@@@@@@@@@@@@@@@@@@@@@ -66,8 -66,8 -66,8 -66,8 -66,8 -65,8 -66,8 -66,8 -66,8 -66,8 -65,8 -66,8 -66,8 -66,8 -65,8 -66,8 -65,8 -66,8 -65,8 -65,8 -66,8 -66,8 +66,8 @@@@@@@@@@@@@@@@@@@@@@@ pub use links::};pub use signature_image::{ImageSignaturePreview, SignatureImage};pub use signature_scan::{PhotoRect, ScanError, SignaturePhoto, Turn};-------- -------------pub use stamp_preview::StampPreview;- - - - -- pub use text_preview::TextEditPreview;++++++++ +++++++++++++pub use stamp_preview::{CommentLayer, StampPreview};+ + + + ++ pub use text_preview::{TextEditPreview, UnmarkedPages};pub use pdfcraft_organize::{BoxSpec, FieldConflicts, PageBox, SplitBy, Transition, TransitionSpec, mime_for_name, split_ranges};diff --cc crates/engine/src/tests.rsindex 6a68916df,6a68916df,6a68916df,6a68916df,6a68916df,c622af21b,6a68916df,23e8a0a74,f59f8af15,898023bd4,c622af21b,6a68916df,6a68916df,6a68916df,14a61b263,6a68916df,14a61b263,6a68916df,441e103ee,14a61b263,6a68916df,6a68916df..174433236--- a/crates/engine/src/tests.rs+++ b/crates/engine/src/tests.rs@@@@@@@@@@@@@@@@@@@@@@@ -3149,45 -3149,45 -3149,45 -3149,45 -3149,45 -3002,6 -3149,45 -3149,45 -3149,45 -3149,98 -3002,6 -3149,45 -3149,45 -3149,45 -3002,6 -3149,45 -3002,6 -3149,45 -3080,6 -3002,6 -3149,45 -3149,45 +3227,98 @@@@@@@@@@@@@@@@@@@@@@@ fn headers_footers_watermarks_and_backgassert_eq!(s.get(id).unwrap().can_undo(), Some("Remove background"));}+++++++++ ++++++++++++/// One 100 × 100 page under a background (`/PCMark /Background`), its own content painting a+++++++++ ++++++++++++/// white backdrop first. With `copy`, that content is a backdrop copy whose tag is `copy`.+++++++++ ++++++++++++fn backdrop_pdf(copy: Option<&str>) -> Vec<u8> {+++++++++ ++++++++++++ let bg = "q 1 0 0 rg 0 0 100 100 re f Q";+++++++++ ++++++++++++ let (tag, fill) = match copy {+++++++++ ++++++++++++ Some(tag) => (format!("/PCBackdrop {tag} "), "n"),+++++++++ ++++++++++++ None => (String::new(), "f"),+++++++++ ++++++++++++ };+++++++++ ++++++++++++ let content = format!("1 g 0 0 100 100 re {fill} 0 g BT /F1 12 Tf 10 50 Td (Hi) Tj ET");+++++++++ ++++++++++++ format!(+++++++++ ++++++++++++ "%PDF-1.7\n\+++++++++ ++++++++++++ 1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n\+++++++++ ++++++++++++ 2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj\n\+++++++++ ++++++++++++ 3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] /Contents [4 0 R 5 0 R] /Resources << /Font << /F1 << /Type /Font /Subtype /Type1 /BaseFont /Helvetica >> >> >> >> endobj\n\+++++++++ ++++++++++++ 4 0 obj << /PCMark /Background /Length {} >> stream\n{bg}\nendstream endobj\n\+++++++++ ++++++++++++ 5 0 obj << {tag}/Length {} >> stream\n{content}\nendstream endobj\n\+++++++++ ++++++++++++ trailer << /Root 1 0 R >>\n%%EOF",+++++++++ ++++++++++++ bg.len(),+++++++++ ++++++++++++ content.len()+++++++++ ++++++++++++ )+++++++++ ++++++++++++ .into_bytes()+++++++++ ++++++++++++}+++++++++ +++++++++++++++++++++ ++++++++++++/// Remove background says which pages keep their own white backdrop off (it couldn't be turned+++++++++ ++++++++++++/// back on safely), and says nothing when every backdrop comes back.+++++++++ ++++++++++++#[test]+++++++++ ++++++++++++fn remove_background_names_the_pages_whose_own_backdrop_stays_off() {+++++++++ ++++++++++++ let mut s = Session::new();+++++++++ ++++++++++++ // A tag whose hash doesn't match the bytes before the fill: something changed them since.+++++++++ ++++++++++++ let tag = format!("<< /Index 2 /Op (f) /Before <{}> >>", "00".repeat(32));+++++++++ ++++++++++++ let id = s.open("a.pdf", None, Arc::new(backdrop_pdf(Some(&tag))), None).unwrap();+++++++++ ++++++++++++ s.apply(id, Edit::RemoveMarks { kind: MarkKind::Background }).unwrap();+++++++++ ++++++++++++ let d = s.get(id).unwrap();+++++++++ ++++++++++++ assert_eq!(d.edit_notices, [EditNotice::BackdropsLeftOff { pages: vec![0] }]);+++++++++ ++++++++++++ let said = d.edit_notices[0].to_string();+++++++++ ++++++++++++ assert!(said.starts_with("page 1 changed after the background was added"), "{said}");+++++++++ ++++++++++++ // An unrelated edit after it says nothing.+++++++++ ++++++++++++ s.apply(id, Edit::RotatePages { pages: vec![0], degrees: 90 }).unwrap();+++++++++ ++++++++++++ assert!(s.get(id).unwrap().edit_notices.is_empty());+++++++++ +++++++++++++++++++++ ++++++++++++ // Added and removed here: the backdrop comes back, and nothing is said.+++++++++ ++++++++++++ let id = s.open("b.pdf", None, Arc::new(backdrop_pdf(None)), None).unwrap();+++++++++ ++++++++++++ s.apply(id, Edit::RemoveMarks { kind: MarkKind::Background }).unwrap();+++++++++ ++++++++++++ let background = Background { color: [1.0, 0.0, 0.0], ..Background::default() };+++++++++ ++++++++++++ s.apply(id, Edit::AddBackground { pages: vec![0], settings: background, replace: false, file: None }).unwrap();+++++++++ ++++++++++++ assert_eq!(s.get(id).unwrap().page_backdrops(&[0]), [None], "replaced");+++++++++ ++++++++++++ s.apply(id, Edit::RemoveMarks { kind: MarkKind::Background }).unwrap();+++++++++ ++++++++++++ assert!(s.get(id).unwrap().edit_notices.is_empty());+++++++++ ++++++++++++ assert_eq!(s.get(id).unwrap().page_backdrops(&[0]), [Some(Backdrop::Fill)], "turned back on");+++++++++ ++++++++++++ assert_eq!(page_runs(&[0, 1, 2, 5, 7, 8]), "1-3, 6, 8-9");+++++++++ ++++++++++++ assert_eq!(page_runs(&[]), "");+++++++++ ++++++++++++}+++++++++ +++++++++++++ + + + ++ /// Update previews its marks on the page without the ones it replaces: a yellow background+ + + + ++ /// updated to blue isn't previewed as blue over yellow, nor a new watermark over the old one.+ + + + ++ /// The other kinds of mark and the page's own content stay, every page is prepared at once (the+ + + + ++ /// dialog steps through them), a document without that kind has nothing to prepare, and+ + + + ++ /// preparing changes nothing in the document.+ + + + ++ #[test]+ + + + ++ fn update_previews_on_the_page_without_the_marks_it_replaces() {+ + + + ++ let (mut s, id) = session_with(2);+ + + + ++ let yellow = Background { color: [1.0, 1.0, 0.0], ..Background::default() };+ + + + ++ s.apply(id, Edit::AddBackground { pages: vec![0, 1], settings: yellow, replace: false, file: None }).unwrap();+ + + + ++ let red = Watermark { text: "SECRET".into(), color: [1.0, 0.0, 0.0], opacity: 1.0, ..Watermark::default() };+ + + + ++ s.apply(id, Edit::AddWatermark { pages: vec![0], settings: red, replace: false, file: None }).unwrap();+ + + + ++ let doc = s.get(id).unwrap();+ + + + ++ let (generation, dirty) = (doc.edit_generation(), doc.dirty);+ + + + ++ let px = |p: &pdfcraft_render::RenderedPage, x: u32, y: u32| -> [u8; 3] {+ + + + ++ p.rgba[(((300 - y) * p.width + x) * 4) as usize..][..3].try_into().unwrap()+ + + + ++ };+ + + + ++ let reds = |p: &pdfcraft_render::RenderedPage| p.rgba.as_chunks::<4>().0.iter().filter(|[r, g, b, _]| *r > 200 && *g < 80 && *b < 80).count();+ + + + ++ let dark = |p: &pdfcraft_render::RenderedPage| p.rgba.as_chunks::<4>().0.iter().filter(|[r, g, b, _]| *r < 100 && *g < 100 && *b < 100).count();+ + + + ++ assert_eq!(pixel(&s, id, 0, 5, 5)[..3], [255, 255, 0], "the page has the yellow background");+ + + + +++ + + + ++ let mut unmarked = doc.without_marks(MarkKind::Background).unwrap().expect("the pages have a background");+ + + + ++ let page = unmarked.render_page(0, 1.0).unwrap();+ + + + ++ assert_eq!(px(&page, 5, 5), [255, 255, 255], "without the background the page is white");+ + + + ++ assert!(reds(&page) > 50, "the watermark stays");+ + + + ++ assert!(dark(&page) > 10, "the page text stays");+ + + + +++ + + + ++ let page = doc.without_marks(MarkKind::Watermark).unwrap().expect("page 1 has a watermark").render_page(0, 1.0).unwrap();+ + + + ++ assert_eq!(reds(&page), 0, "without the watermark");+ + + + ++ assert_eq!(px(&page, 5, 5), [255, 255, 0], "the background stays");+ + + + +++ + + + ++ assert_eq!(px(&unmarked.render_page(1, 1.0).unwrap(), 5, 5), [255, 255, 255], "made once, for every page: page 2 is white too");+ + + + ++ assert_eq!(unmarked.parser_builds(), 1, "parsed once for both pages");+ + + + ++ assert!(doc.without_marks(MarkKind::HeaderFooter).unwrap().is_none(), "the document has no header");+ + + + ++ assert!(unmarked.render_page(9, 1.0).is_err(), "no page 10");+ + + + ++ let doc = s.get(id).unwrap();+ + + + ++ assert_eq!((doc.edit_generation(), doc.dirty, doc.can_undo()), (generation, dirty, Some("Add watermark")), "the document is unchanged");+ + + + ++ }+ + + + ++#[test]fn marker_indexes_match_after_open_and_save_when_requested() {let (mut source, source_id) = session_with(1);diff --cc crates/ui-egui/src/canvas.rsindex 91d2c4136,91d2c4136,91d2c4136,91d2c4136,91d2c4136,edcd64569,c39fdedef,b0fad267b,35069064d,91d2c4136,edcd64569,91d2c4136,91d2c4136,91d2c4136,ea37eb0df,91d2c4136,ea37eb0df,91d2c4136,edcd64569,ea37eb0df,a5c5f7e70,ba7d150f4..5269383b5--- a/crates/ui-egui/src/canvas.rs+++ b/crates/ui-egui/src/canvas.rs@@@@@@@@@@@@@@@@@@@@@@@ -27,8 -27,8 -27,8 -27,8 -27,8 -26,7 -27,9 -27,8 -27,8 -27,8 -26,7 -27,8 -27,8 -27,8 -26,7 -27,8 -26,7 -27,8 -26,7 -26,7 -27,8 -27,8 +27,9 @@@@@@@@@@@@@@@@@@@@@@@ pub(super) mod flingpub(super) mod image_pick;mod navigation;mod organize;+ + + + ++ pub(super) mod page_cursor;pub(super) mod page_pointer;++++++ +++++++++++++++pub(super) mod page_router;pub mod scroll_speed;mod selection;pub(super) mod signature_drag;@@@@@@@@@@@@@@@@@@@@@@@ -471,8 -471,8 -471,8 -471,8 -471,8 -470,6 -472,13 -471,8 -471,8 -471,8 -470,6 -471,8 -471,8 -471,8 -470,6 -471,8 -470,6 -471,8 -470,6 -470,6 -473,8 -471,8 +474,13 @@@@@@@@@@@@@@@@@@@@@@@ pub struct DocView/// A queued Fill & Sign signature: select it after its edit succeeds, then leave placement.pub(crate) fill_signature_page: Option<usize>,pub(crate) signature_drag: crate::signature_drag::SignatureDrag,+ + + + ++ /// What the page modules claim for the cursor this frame; `document_area` sets it once.+ + + + ++ pub(crate) cursor: crate::page_cursor::PageCursor,++++++ +++++++++++++++ /// Who the press the pages hold belongs to.++++++ +++++++++++++++ pub(crate) router: crate::page_router::PageRouter,++++++ +++++++++++++++ /// Escape cancelled the press the pages hold: the page ignores it until the button is up, so++++++ +++++++++++++++ /// its release neither clicks nor ends a drag.++++++ +++++++++++++++ pub(crate) press_cancelled: bool,/// A non-edit action requested by the organize toolbar, handled by the app.pub pending_action: Option<ViewAction>,/// The grid gap the next inserted files go to (set by a "+" between pages); otherwise they@@@@@@@@@@@@@@@@@@@@@@@ -725,7 -725,7 -725,7 -725,7 -725,7 -722,6 -732,9 -725,7 -725,7 -725,7 -722,6 -725,7 -725,7 -725,7 -722,6 -725,7 -722,6 -725,7 -722,6 -722,6 -728,7 -725,7 +735,9 @@@@@@@@@@@@@@@@@@@@@@@ impl DocViewfill_text: None,fill_signature_page: None,signature_drag: Default::default(),+ + + + ++ cursor: Default::default(),++++++ +++++++++++++++ router: Default::default(),++++++ +++++++++++++++ press_cancelled: false,}}@@@@@@@@@@@@@@@@@@@@@@@ -812,2249 -812,2249 -812,2249 -812,2249 -812,2249 -808,1454 -821,2416 -812,2250 -812,2254 -812,2249 -808,1454 -812,2249 -812,2249 -812,2249 -808,2289 -812,2249 -808,2289 -812,2249 -808,1454 -808,2289 -815,2249 -812,2253 +824,2426 @@@@@@@@@@@@@@@@@@@@@@@}}- - - /// 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));+ + + /// The renders a frame wants (page, scale, tag, tile), and the pages visible.+ + + type PageRenders = (Vec<(usize, f32, u64, Option<Tile>)>, Vec<usize>);+ + ++ + + /// What the page-scroll closure reads: this frame's zoom, scrolling, tool and document state.+ + + #[derive(Clone, Copy)]+ + + struct PageEnv<'a> {+ + + added: &'a Vec<pdfcraft_engine::Added>,+ + + allowed: bool,+ + + author: &'a String,+ + + auto_delta: Vec2,+ + + avail: Rect,+ + + boost_extra: Vec2,+ + + by_line: &'a String,+ + + calc_order: bool,+ + + can_copy: bool,+ + + can_crop: bool,+ + + can_fill: bool,+ + + can_modify: bool,+ + + comments_hidden: bool,+ + + content_h: f32,+ + + content_w: f32,+ + + custom_stamp: &'a Option<crate::stamps_ui::CustomStamp>,+ + + date_text: &'a Result<String, String>,+ + + doc: &'a pdfcraft_engine::Document,+ + + doc_links: &'a Vec<pdfcraft_engine::LinkItem>,+ + + edge_delta: Vec2,+ + + editing_content: bool,+ + + form: &'a Arc<Vec<pdfcraft_engine::FormField>>,+ + + generation: u64,+ + + glide: Vec2,+ + + hand: bool,+ + + info: &'a DocInfo,+ + + initials: &'a Option<crate::fill_sign::SavedSig>,+ + + key_scroll: f32,+ + + middle_gesture: bool,+ + + modal: bool,+ + + navigation_enabled: bool,+ + + paper: Color32,+ + + ppp: f32,+ + + precise_scroll: Vec2,+ + + prefs: &'a comments::CommentPrefs,+ + + preparing: bool,+ + + rects: &'a Vec<Rect>,+ + + redact_mark: ([f64; 3], f64),+ + + scale: f32,+ + + selection_wheel: bool,+ + + selects_text: bool,+ + + signature: &'a Option<crate::fill_sign::SavedSig>,+ + + single_paging: bool,+ + + t: &'a Tokens,+ + + table_preview: &'a Option<crate::field_table_ui::Preview>,+ + + tag: u64,+ + + text_style: &'a pdfcraft_engine::AddedText,+ + + tool: QuickTool,+ + + units: crate::units::Unit,+ + + unobstructed: bool,+ + + visible_pages: &'a Vec<usize>,+ + + y_shift: f32,+ + + fill_text_size: f64,+++++++++++++++++++++ fill_text_color: [f64; 3],+ + + today: (i64, u32, u32),+ + + }+ + ++ + + /// What the page-scroll closure produces for the rest of the frame.+ + + #[derive(Default)]+ + + struct PageOut {- - - badge_hover: Option<(Pos2, String)>,+ + + canvas_action: Option<comments::CanvasAction>,+ + + clicked_link: Option<LinkTarget>,+ + + copy_selected: bool,+ + + field_menu: Option<FieldMenu>,+ + + field_placed: bool,+ + + field_props: bool,+ + + hover_text: Option<(Pos2, String)>,+ + + image_action: Option<crate::edit_text_ui::ImageAction>,+ + + open_boxes: bool,+ + + open_initials: bool,+ + + open_signature: bool,+ + + open_table: Option<(usize, [f64; 4])>,+ + + primary_down: bool,+ + + refused: Option<String>,+ + + stamp_placed: bool,+ + + }+ + ++ + + /// The page-scroll closure's body: lays out and draws the visible pages, their tools and overlays, and+ + + /// returns the renders wanted and the pages visible.+ + + /// The state of one pass over the visible pages: what is read, and what the pages add up to.+ + + struct PageFrame<'a> {+ + + env: PageEnv<'a>,+ + + resp: &'a egui::Response,+ + + ptr: &'a PagePointer,+ + + origin: Pos2,+ + + visible: Rect,+ + + pressed: bool,+ + + pointer: Option<Pos2>,+ + + signature_preview: &'a mut Option<(crate::fill_sign::SavedSig, egui::TextureHandle)>,+ + + out: PageOut,+ + + wanted: Vec<(usize, f32, u64, Option<Tile>)>,+ + + visible_now: Vec<usize>,+ + + current: usize,+ + + best_overlap: f32,+ + + current_overlap: f32,+ + + current_height: f32,+ + + pressed_page: Option<usize>,+ + + calc_hover: Option<String>,+ + + }+ + ++ + + /// Visible heights (points) closer than this are equal: one page size can meet the viewport a+ + + /// fraction of a point differently once the scroll offset is applied.+ + + const PAGE_TIE: f32 = 0.5;+ + ++ + + /// Draws page `i` of the visible pages: its raster, the tools' input and overlays.+ + + /// One visible page: its index, its rectangle on screen and the transform to and from the page.+ + + #[derive(Clone, Copy)]+ + + struct PageSlot {+ + + i: usize,+ + + r: Rect,+ + + xf: PageXform,+ + + }+ + ++ + + /// Paints the page's paper, shadow and raster (or why it can't be shown), and asks for the renders+ + + /// it wants.+ + + fn paint_page_surface(ui: &mut egui::Ui, view: &mut DocView, frame: &mut PageFrame<'_>, slot: &PageSlot) {+ + + let PageEnv { paper, ppp, scale, t, tag, .. } = frame.env;+ + + let PageSlot { i, r, xf } = *slot;+ + + let visible = frame.visible;+ + + let info = frame.env.info;+ + + let painter = ui.painter();+ + + // Shadows would darken the preceding page when pages touch.+ + + if view.show_page_gaps {+ + + painter.add(egui::epaint::Shadow { offset: [0, 3], blur: 14, spread: 0, color: t.page_shadow }.as_shape(r, CornerRadius::ZERO));+ + + }+ + + painter.rect_filled(r, CornerRadius::ZERO, paper);+ + + if let Some(err) = view.errors.get(&i) {+ + + painter.rect_filled(r, CornerRadius::ZERO, Color32::from_rgb(0xFB, 0xF4, 0xF4));+ + + icons::paint(+ + + ui,+ + + Rect::from_center_size(r.center() - vec2(0.0, 26.0), vec2(28.0, 28.0)),+ + + "triangle-alert",+ + + 26.0,+ + + Color32::from_rgb(0xC8, 0x3A, 0x3A),+ + + );+ + + let message = crate::i18n::fmt(tl!("This page couldn't be displayed.\n{e}"), &[("e", err)]);+ + + let msg = ui.fonts_mut(|f| f.layout(message, theme::regular(12.5), Color32::from_rgb(0x6A, 0x2A, 0x2A), (r.width() - 40.0).max(80.0)));+ + + painter.galley(pos2(r.center().x - msg.size().x / 2.0, r.center().y), msg, Color32::BLACK);+ + + } else {+ + + let (pw_pt, ph_pt) = (info.pages[i].width.max(1.0), info.pages[i].height.max(1.0));+ + + // A GPU may take smaller textures than these (OpenGL drivers report as little as+ + + // 2048 pixels, and uploading a bigger one aborts), so both stay within its limit.+ + + let max_side = ui.ctx().input(|inp| inp.max_texture_side) as f32;+ + + let tiled = pw_pt.max(ph_pt) * scale > TILE_THRESHOLD.min(max_side);+ + + // Whole-page raster: sharp when small, a low-res backdrop when tiled.+ + + let (want_scale, want_tag) = if tiled {+ + + let bs = BASE_SIDE.min(max_side) / pw_pt.max(ph_pt);+ + + (bs, scale_tag(bs))} else {- - - app.close_tab(i);+ + + (scale, tag)+ + + };+ + + // Under tiles, a whole-page raster sharper than the backdrop (from before the page+ + + // grew past the tiling size) is a better backdrop: keep demanding it as it is.+ + + match view.pages.get(&i).filter(|p| tiled && p.tag != STALE_TAG && tag_scale(p.tag) >= want_scale) {+ + + Some(p) => frame.wanted.push((i, tag_scale(p.tag), p.tag, None)),+ + + None => frame.wanted.push((i, want_scale, want_tag, None)),}- - - 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;+ + + match view.pages.get(&i) {+ + + Some(p) => {+ + + if !tiled && p.tag == want_tag {+ + + xf.texel_aligned(p.tex.size(), ppp).paint_image(painter, p.tex.id(), 0.0, 0.0, 1.0, 1.0);+ + + } else {+ + + // A backdrop, or a raster at an older scale until the new one arrives.+ + + xf.paint_image(painter, p.tex.id(), 0.0, 0.0, 1.0, 1.0);+ + + }+ + + }+ + + None => {+ + + let now = ui.input(|inp| inp.time);+ + + let since = *view.waiting_since.entry(i).or_insert(now);+ + + let msg = if now - since > 6.0 { "Still rendering — this page is unusually complex…" } else { "Rendering…" };+ + + painter.text(r.center(), Align2::CENTER_CENTER, tl!(msg), theme::regular(12.0), t.text_faint);}}- - - 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;+ + + if tiled && r.intersects(visible) {+ + + paint_page_tiles(ui, view, frame, slot, (pw_pt, ph_pt, max_side));+ + + }}+ + + }- - - 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)));+ + + /// Paints the tiles of a page too big to draw whole: the tiles of earlier zooms first, stretched,+ + + /// then the visible tiles of this one, nearest the viewport centre first, asking for those missing.+ + + fn paint_page_tiles(ui: &egui::Ui, view: &mut DocView, frame: &mut PageFrame<'_>, slot: &PageSlot, (pw_pt, ph_pt, max_side): (f32, f32, f32)) {+ + + let PageEnv { ppp, scale, tag, .. } = frame.env;+ + + let PageSlot { i, r, xf } = *slot;+ + + let visible = frame.visible;+ + + let painter = ui.painter();+ + + // Device-pixel geometry of the scaled page, and the visible part of it+ + + // (found by mapping the visible screen corners back into the page). Sides round+ + + // up as whole-page rasters do, so the last partial row and column get tiles.+ + + let (dw, dh) = (device_pixels(pw_pt, scale), device_pixels(ph_pt, scale));+ + + // Adaptive tile side for this zoom and page, within the GPU texture limit:+ + + // a zoomed viewport or a giant sheet is covered by a few large tiles+ + + // instead of many small ones, and each tile costs one full page interpret.+ + + // Never zero (u32 division below).+ + + let ts = tile_side(scale, dw.max(dh)).min(max_side as u32).max(64);+ + + let vis = r.intersect(visible);+ + + let corners = [vis.left_top(), vis.right_top(), vis.right_bottom(), vis.left_bottom()].map(|c| xf.screen_to_norm(c));+ + + let (u0, u1) = corners.iter().fold((1.0f32, 0.0f32), |(a, b), c| (a.min(c.0), b.max(c.0)));+ + + let (v0, v1) = corners.iter().fold((1.0f32, 0.0f32), |(a, b), c| (a.min(c.1), b.max(c.1)));+ + + let (vx0, vy0) = ((u0.max(0.0) * dw as f32) as u32, (v0.max(0.0) * dh as f32) as u32);+ + + let (vx1, vy1) = (((u1.min(1.0) * dw as f32).ceil() as u32).min(dw), ((v1.min(1.0) * dh as f32).ceil() as u32).min(dh));+ + + // Tiles of earlier zooms first, stretched, the nearest scale last (on top):+ + + // until the current tiles arrive, a zoom shows them rather than the backdrop.+ + + let mut older: Vec<(f32, u32, u32, &TextureHandle)> =+ + + view.tiles.iter().filter(|((p, t, _, _), _)| *p == i && *t != tag).map(|((_, t, ox, oy), tex)| (tag_scale(*t), *ox, *oy, tex)).collect();+ + + older.sort_by(|a, b| (b.0 / scale).ln().abs().total_cmp(&(a.0 / scale).ln().abs()));+ + + for (s, ox, oy, tex) in older {+ + + let (ow, oh) = (device_pixels(pw_pt, s) as f32, device_pixels(ph_pt, s) as f32);+ + + let [w, h] = tex.size();+ + + let (x, y) = (ox as f32, oy as f32);+ + + xf.paint_image(painter, tex.id(), x / ow, y / oh, (x + w as f32) / ow, (y + h as f32) / oh);+ + + }+ + + // Visible tiles, nearest the viewport centre first: each tile costs a full+ + + // page interpret, so the workers sharpen what is looked at before the edges.+ + + let (vcx, vcy) = ((vx0 + vx1) as f32 / 2.0, (vy0 + vy1) as f32 / 2.0);+ + + let mut coords: Vec<(u32, u32)> = Vec::new();+ + + for ty in vy0 / ts..=(vy1.saturating_sub(1)) / ts {+ + + for tx in vx0 / ts..=(vx1.saturating_sub(1)) / ts {+ + + coords.push((tx, ty));}}- - -- - - // 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),+ + + coords.sort_by(|a, b| {+ + + let da = ((a.0 * ts + ts / 2) as f32 - vcx).abs() + ((a.1 * ts + ts / 2) as f32 - vcy).abs();+ + + let db = ((b.0 * ts + ts / 2) as f32 - vcx).abs() + ((b.1 * ts + ts / 2) as f32 - vcy).abs();+ + + da.total_cmp(&db)+ + + });+ + + for (tx, ty) in coords {+ + + let (x, y) = (tx * ts, ty * ts);+ + + let (w, h) = (ts.min(dw.saturating_sub(x)), ts.min(dh.saturating_sub(y)));+ + + if w == 0 || h == 0 {+ + + continue;+ + + }+ + + frame.wanted.push((i, scale, tag, Some(Tile { x, y, w, h })));+ + + if let Some(tex) = view.tiles.get(&(i, tag, x, y)) {+ + + let (fw, fh) = (dw as f32, dh as f32);+ + + xf.texel_aligned([dw as usize, dh as usize], ppp).paint_image(+ + + painter,+ + + tex.id(),+ + + x as f32 / fw,+ + + y as f32 / fh,+ + + (x + w) as f32 / fw,+ + + (y + h) as f32 / fh,+ + + );}}- - - view.viewport_screen = avail;- - - let auto_delta = if unobstructed {- - - view.auto_scroll.update(ui, avail, false)- - - } else {- - - view.auto_scroll.cancel();- - - Vec2::ZERO- - - };+ + + }- - - // Drawing a comment: the pointer in a band along any edge (or just past it) scrolls the view- - - // that way, so a point beyond what is shown can be reached without letting go of the tool.- - - let edge_delta = if unobstructed && matches!(view.comments.gesture, Some(comments::Gesture::Draw { .. })) {- - - let (pointer, dt) = drawing_edge_pointer(ui);- - - crate::autoscroll::edge_scroll(pointer, avail, dt)- - - } else {- - - Vec2::ZERO+ + + /// What the page's tools did with the pointer this frame.+ + + struct PageInput {+ + + /// A tool, a field or a comment took the pointer: text selection must leave it alone.+ + + consumed: bool,- - - /// A form field is under the pointer and has set its cursor.- - - over_field: bool,+ + + /// Redact or Highlight draws boxes off text.+ + + area_tool: bool,+ + + }+ + ++ + + /// Common geometry and pointer state for a tool acting on one page.+ + + #[derive(Clone, Copy)]+ + + pub(crate) struct PageToolContext<'a> {+ + + pub ui: &'a egui::Ui,+ + + pub resp: &'a egui::Response,+ + + pub xf: &'a PageXform,+ + + pub ptr: &'a PagePointer,+ + + pub page: usize,+ + + pub doc: &'a pdfcraft_engine::Document,+ + + pub info: &'a DocInfo,+ + + }+ + ++ + + /// Comments: tools, selection, moving and resizing come before text selection. Form fields take+ + + /// clicks first with the Select tool (as Acrobat fills fields in every viewing mode); then+ + + /// comments; then text selection.+ + + fn page_tool_input(ui: &mut egui::Ui, view: &mut DocView, frame: &mut PageFrame<'_>, slot: &PageSlot) -> PageInput {+ + + let PageEnv {+ + + added,+ + + allowed,+ + + author,+ + + by_line,+ + + can_crop,+ + + can_fill,+ + + can_modify,+ + + comments_hidden,+ + + custom_stamp,+ + + date_text,+ + + doc,+ + + doc_links,+ + + editing_content,+ + + form,+ + + info,+ + + initials,+ + + prefs,+ + + preparing,+ + + redact_mark,+ + + signature,+ + + table_preview,+ + + text_style,+ + + tool,+ + + units,+ + + fill_text_size,+++++++++++++++++++++ fill_text_color,+ + + ..+ + + } = frame.env;+ + + let PageSlot { i, xf, .. } = *slot;+ + + let PageFrame { resp, ptr, pointer, .. } = *frame;+ + + let cx = PageToolContext { ui, resp, xf: &xf, ptr, page: i, doc, info };+ + + let pcx = comments::PageCx { page: i, xf: &xf, ptr, info, tool, prefs, allowed, hidden: comments_hidden, redact_mark };++++++ +++++++++++++++ let (lines, images) =++++++ +++++++++++++++ if matches!(tool, QuickTool::AddText | QuickTool::EditText) && can_modify { edit_inventory(view, doc, i) } else { Default::default() };++++++ +++++++++++++++ let field_tool = match tool {++++++ +++++++++++++++ QuickTool::Field(f) => Some(f),++++++ +++++++++++++++ _ => None,+++++ +++ +++++++ +++ };- - - if edge_delta != Vec2::ZERO {- - - ui.ctx().request_repaint();++++++ +++++++++++++++ // While a table is being set up, nothing else is drawn or moved.++++++ +++++++++++++++ let prepare_allowed = can_modify && table_preview.is_none() && frame.out.open_table.is_none();++++++ +++++++++++++++ let hits = PageHits {++++++ +++++++++++++++ page: i,++++++ +++++++++++++++ xf: &xf,++++++ +++++++++++++++ info,++++++ +++++++++++++++ tool,++++++ +++++++++++++++ pcx: &pcx,++++++ +++++++++++++++ form,++++++ +++++++++++++++ can_fill,++++++ +++++++++++++++ can_modify,++++++ +++++++++++++++ editing_content,++++++ +++++++++++++++ preparing,++++++ +++++++++++++++ field_tool,++++++ +++++++++++++++ prepare_allowed,++++++ +++++++++++++++ added,++++++ +++++++++++++++ lines: &lines,++++++ +++++++++++++++ images: &images,++++++ +++++++++++++++ clip: ui.clip_rect(),++++++ +++++++++++++++ };++++++ +++++++++++++++ if let Some(o) = ptr.pressed().filter(|o| xf.rect.contains(*o)) {++++++ +++++++++++++++ let at = hits.at(view, o);++++++ +++++++++++++++ view.router.press(i, at, tool);++++++ +++++++++++++++ }+ + + if let QuickTool::Measure(measure_tool) = tool {+ + + crate::measure_ui::page_input(ui, resp, doc, view, &pcx, measure_tool, units);}- - - let content_w = view.content_width(info, avail.width());- - - let rects = view.layout(info, content_w, ui.ctx().pixels_per_point());- - - // When not scrolling continuously, only one row is shown at a time: the current page, or the- - - // current two-page spread (with the cover rule). These indices drive paging, which pages are- - - // drawn, and the content height (#752). Empty for a document with no pages.- - - let shown_row = |view: &DocView| -> Vec<usize> {- - - if rects.is_empty() {- - - return Vec::new();- - - }- - - let last = rects.len() - 1;- - - let cur = view.current.min(last);- - - match view.layout {- - - PageLayout::Single => vec![cur],- - - PageLayout::TwoUp if view.cover && cur == 0 => vec![0],- - - PageLayout::TwoUp => {- - - let first = if view.cover { cur - (cur + 1) % 2 } else { cur - cur % 2 };- - - if first < last { vec![first, first + 1] } else { vec![first] }- - - }+ + + // Form fields take clicks first with the Select tool (as Acrobat fills fields in+ + + // every viewing mode); then comments; then text selection.+ + + if let QuickTool::Stamp(kind) = tool+ + + && allowed+ + + && let Some(p) = ptr.within(xf.rect)+ + + {- - - ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair);- - - if resp.clicked() {+ + + + ++ view.cursor.claim(Layer::ToolArea, egui::CursorIcon::Crosshair);----- --- --- - - -- if resp.clicked() {++++++ +++++++++++++++ // The tool's own click: nothing drawn over the page here holds the press.++++++ +++++++++++++++ if resp.clicked() && view.router.owner(i).is_none() {+ + + // Centred on the click, upright as the page is shown.+ + + let (vx, vy) = xf.screen_to_view(p);+ + + let (w, h) = kind.size();+ + + let corners = [(vx as f64 - w / 2.0, vy as f64 - h / 2.0), (vx as f64 + w / 2.0, vy as f64 + h / 2.0)];+ + + let u: Vec<[f32; 2]> = corners.iter().map(|(x, y)| info.pages[i].view_to_user(*x as f32, *y as f32)).collect();+ + + let rect = [u[0][0].min(u[1][0]) as f64, u[0][1].min(u[1][1]) as f64, u[0][0].max(u[1][0]) as f64, u[0][1].max(u[1][1]) as f64];+ + + let by = (kind.group() == pdfcraft_engine::StampGroup::Dynamic).then(|| by_line.clone());+ + + let shape = pdfcraft_engine::Shape::Stamp { rect, stamp: kind, by };+ + + view.pending_edit = Some(pdfcraft_engine::Edit::AddAnnotation(pdfcraft_engine::NewAnnotation {+ + + page: i,+ + + style: pdfcraft_engine::Style::default_for(&shape),+ + + shape,+ + + contents: String::new(),+ + + author: author.clone(),+ + + }));+ + + frame.out.stamp_placed = true;}- - - };- - - let row = shown_row(view);- - - let middle_gesture = view.auto_scroll.blocks_input();- - - // Not scrolling: when the whole page or spread fits, the wheel would do nothing, so it turns- - - // pages instead; zoomed in far enough to pan, it pans, and at the edge it turns the page on- - - // (#1924, `single_page_wheel_edge`). Touch drags are untouched: with- - - // nothing to pan, touch users turn pages with the rail buttons, the page box and the arrow- - - // keys. Runs before `visible_pages` so the frame that turns the page draws it.- - - let mut single_paging = false;- - - let mut edge_turned = false;- - - if !view.continuous {- - - // The row's bounding box on screen (one page, or a two-page spread).- - - let row_rect = row.iter().filter_map(|&i| rects.get(i)).copied().reduce(Rect::union);- - - // Within a point, so layout rounding can't stop a fitting page from turning.- - - let fits = row_rect.is_some_and(|r| r.height() + 2.0 * MARGIN <= avail.height() + 1.0);- - - let can_turn = !middle_gesture && unobstructed && ui.rect_contains_pointer(avail);- - - single_paging = can_turn && fits;- - - // Every wheel event goes to the pager, so it follows each trackpad touch to its end- - - // even while the page can't turn.- - - ui.input(|i| {- - - for e in &i.events {- - - if let egui::Event::MouseWheel { unit, delta, phase, modifiers, .. } = e {- - - // Zooming (⌘ or Ctrl) and sideways scrolling (Shift) never turn pages.- - - let dy = if modifiers.command || modifiers.ctrl || modifiers.shift { 0.0 } else { delta.y };- - - if fits {- - - view.single_page_wheel(*unit, dy, *phase, i.time, can_turn);- - - } else {- - - edge_turned |= view.single_page_wheel_edge(*unit, dy, *phase, i.time, can_turn);- - - }- - - }+ + + }+ + + if let Some(cs) = custom_stamp.as_ref()+ + + && allowed+ + + && let Some(p) = ptr.within(xf.rect)+ + + {- - - ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair);- - - if resp.clicked() {+ + + + ++ view.cursor.claim(Layer::ToolArea, egui::CursorIcon::Crosshair);----- --- --- - - -- if resp.clicked() {++++++ +++++++++++++++ // The tool's own click: nothing drawn over the page here holds the press.++++++ +++++++++++++++ if resp.clicked() && view.router.owner(i).is_none() {+ + + // Centred on the click at its natural size (the engine sizes it).+ + + let (vx, vy) = xf.screen_to_view(p);+ + + let u = info.pages[i].view_to_user(vx, vy);+ + + let (x, y) = (u[0] as f64, u[1] as f64);+ + + view.pending_edit = Some(pdfcraft_engine::Edit::AddCustomStamp {+ + + page: i,+ + + rect: [x, y, x, y],+ + + name: cs.name.clone(),+ + + file: pdfcraft_engine::MarkFile { name: cs.file.clone(), bytes: cs.data.clone(), page: cs.page },+ + + author: author.clone(),+ + + });+ + + frame.out.stamp_placed = true;+ + + }+ + + }+ + + // Over a mark already placed, the Fill & Sign tool picks it up (comments, below).+ + + if let QuickTool::Fill(ft) = tool+ + + && allowed+ + + && !comments::fill_grabs(&pcx, view)+ + + {+ + + match crate::fill_sign::page_input(+ + + cx,+ + + crate::fill_sign::PageInput {+ + + tool: ft,+ + + text_size: fill_text_size,+++++++++++++++++++++ text_color: fill_text_color,+ + + signature: signature.as_ref(),+ + + initials: initials.as_ref(),+ + + preview: frame.signature_preview,+ + + author,+ + + date_text,+ + + },+ + + view,+ + + ) {+ + + Some(crate::fill_sign::FillAction::Edit(e)) => view.pending_edit = Some(*e),+ + + Some(crate::fill_sign::FillAction::Signature(e)) => {+ + + view.pending_edit = Some(*e);+ + + view.fill_signature_page = Some(i);}- - - });- - - if single_paging {- - - // Paging owns vertical wheel motion here. A diagonal gesture keeps its sideways- - - // part, as `ScrollArea` itself handles each axis.- - - ui.input_mut(|i| i.smooth_scroll_delta.y = 0.0);+ + + Some(crate::fill_sign::FillAction::CreateSignature) => frame.out.open_signature = true,+ + + Some(crate::fill_sign::FillAction::CreateInitials) => frame.out.open_initials = true,+ + + Some(crate::fill_sign::FillAction::Refused(why)) => frame.out.refused = Some(why),+ + + None => {}}}- - - // Point input bypasses egui smoothing for 1:1 motion. Line input keeps egui's configured,- - - // smoothed base and adds only the accelerated surplus. While point suppression is active,- - - // reconstruct line and page input here so current coarse events survive without exposing an- - - // older eased tail.- - - let now = ui.input(|i| i.time);- - - let input = if ui.rect_contains_pointer(avail) {- - - // Match the line distance used by egui's other scroll areas.- - - let live = ui.ctx().options(|o| o.input_options.line_scroll_speed);- - - let line_points = if live.is_finite() && live > 0.0 { live } else { crate::scroll_speed::EGUI_LINE_POINTS };- - - ui.input(|i| crate::wheel_boost::accumulate(&i.events, line_points, single_paging))+ + + if matches!(tool, QuickTool::SignArea { .. }) {+ + + crate::sign_ui::page_input(ui, resp, &xf, ptr, i, info, view);+ + + }+ + + if matches!(tool, QuickTool::MarqueeZoom | QuickTool::Snapshot) {+ + + crate::zoom_snap::page_input(ui, resp, &xf, ptr, i, view);+ + + }+ + + if tool == QuickTool::EnhanceCamera {- - - crate::camera_ui::page_input(ui, resp, &xf, ptr, i, view, can_modify);+ + + + ++ crate::camera_ui::page_input(resp, &xf, ptr, i, view, can_modify);+ + + }+ + + if tool == QuickTool::Crop+ + + && crate::crop::page_input(ui, crate::crop::CropPageInput { resp, xf: &xf, ptr, page: i, info, view, allowed: can_crop })+ + + {+ + + view.current = i;+ + + frame.out.open_boxes = true;+ + + }- - - // `over_field`: a form field is under the pointer and has set its cursor.- - - let (on_field, over_field) = if preparing {- - - let field_tool = match tool {- - - QuickTool::Field(f) => Some(f),- - - _ => None,- - - };- - - // While a table is being set up, nothing else is drawn or moved.- - - let allowed = can_modify && table_preview.is_none() && frame.out.open_table.is_none();- - - let o = crate::prepare::page_input(cx, form, field_tool, allowed, view);+ + + + ++ let on_field = if preparing {----- --- --- - - -- let field_tool = match tool {----- --- --- - - -- QuickTool::Field(f) => Some(f),----- --- --- - - -- _ => None,----- --- --- - - -- };----- --- --- - - -- // While a table is being set up, nothing else is drawn or moved.----- --- --- - - -- let allowed = can_modify && table_preview.is_none() && frame.out.open_table.is_none();----- --- --- - - -- let o = crate::prepare::page_input(cx, form, field_tool, allowed, view);++++++ +++++++++++++++ let o = crate::prepare::page_input(cx, form, field_tool, prepare_allowed, view);+ + + frame.out.field_props |= o.properties;+ + + frame.out.field_placed |= o.placed;+ + + frame.out.open_table = frame.out.open_table.or(o.table);- - - (o.consumed || field_tool.is_some(), false)+ + + + ++ o.consumed || field_tool.is_some()} else {----- --- --- - - -- tool == QuickTool::Select- - - use crate::forms_ui::FieldPointer;- - - let field = if tool == QuickTool::Select----- --- ------- --- && !(editing_content && can_modify && crate::content_ui::select_grabs(&xf, ptr, i, info, added, view))----- --- ------- --- && !comments::select_grabs(&pcx, view)----- --- --- - - -- && crate::forms_ui::page_input(cx, form, can_fill, view)- - - crate::wheel_boost::FrameInput::default()- - - {- - - crate::forms_ui::page_input(cx, form, can_fill, view)- - - } else {- - - FieldPointer::Away- - - };- - - (field == FieldPointer::Owned, field == FieldPointer::Over)++++++ +++++++++++++++ tool == QuickTool::Select && crate::forms_ui::page_input(cx, form, can_fill, view)};- - - let mut precise_scroll = input.precise;- - - let mut line_base = input.line;- - - let mut boost_extra = crate::wheel_boost::boost_extra(input, &mut view.wheel_boost_x, &mut view.wheel_boost_y, now);- - - let has_page = input.page != Vec2::ZERO;- - - if now.is_finite() && precise_scroll != Vec2::ZERO && !has_page {- - - view.precise_scroll_until = now + SUPPRESS_SECS;+ + + // Redact draws boxes off text; so does Highlight (an area highlight, as in Acrobat).+ + + let area_tool = tool == QuickTool::Redact && can_modify || tool == QuickTool::Comment(comments::CommentTool::Highlight) && allowed;+ + + let boxing = area_tool && {+ + + let text = view.page_text(i);+ + + let over_text = |p: Pos2| {+ + + let (vx, vy) = xf.screen_to_view(p);+ + + text.as_ref().is_some_and(|t| t.glyphs.iter().any(|g| vx >= g.rect[0] && vx <= g.rect[2] && vy >= g.rect[1] && vy <= g.rect[3]))+ + + };+ + + crate::redact_ui::page_input(cx, over_text, view)+ + + };----- --- ------- --- let image_owns_pointer = tool == QuickTool::EditText && crate::edit_text_ui::image_owns_pointer(ui, &xf, ptr, i, info, view);----- --- ------- --- let on_objects = !image_owns_pointer && tool == QuickTool::EditText && can_modify && crate::object_ui::page_input(cx, view);----- --- ------- --- let lines = if matches!(tool, QuickTool::AddText | QuickTool::EditText) && can_modify {----- --- ------- --- let generation = doc.edit_generation();----- --- ------- --- match view.edit_lines.get(&i) {----- --- ------- --- Some((g, l)) if *g == generation => l.clone(),----- --- ------- --- _ => {----- --- ------- --- let l = doc.text_blocks(i);----- --- ------- --- view.edit_lines.insert(i, (generation, l.clone()));----- --- ------- --- l----- --- ------- --- }----- --- ------- --- }----- --- ------- --- } else {----- --- ------- --- Vec::new()----- --- ------- --- };++++++ +++++++++++++++ let on_objects = tool == QuickTool::EditText && can_modify && crate::object_ui::page_input(cx, view);++++++ +++++++++++++++ // Add text acts on the page's own paragraphs over them, and on the one its press was on until++++++ +++++++++++++++ // the button is up: a drag that leaves the box still ends, and no new box takes it over.+ + + let over_source = tool == QuickTool::AddText----- --- ------- --- && pointer.is_some_and(|p| {----- --- ------- --- !crate::content_ui::hits_added(&xf, info, i, added, p)----- --- ------- --- && lines.iter().any(|line| xf.user_rect(info, i, line.rect.map(|v| v as f32)).expand(2.0).contains(p))----- --- ------- --- });++++++ +++++++++++++++ && (matches!(view.router.owner(i), Some(crate::page_router::Owner::Paragraph { .. }))++++++ +++++++++++++++ || pointer.is_some_and(|p| {++++++ +++++++++++++++ !crate::content_ui::hits_added(&xf, info, i, added, p) && crate::edit_text_ui::over_paragraph(&xf, info, i, &lines, p)++++++ +++++++++++++++ }));+ + + let source_blocked = over_source && view.content.hold_blocked();+ + + if over_source && resp.clicked() && !source_blocked {+ + + if let Some(edit) = view.content.finish_draft(added) {+ + + view.pending_edit = Some(edit);+ + + }+ + + view.content.selected = None;}- - - if edge_turned {- - - // The turn leaves egui's eased copy of the notch to decay for a few frames; it must not- - - // scroll the page just shown away from its top (or bottom).- - - view.precise_scroll_until = now + 0.25;+ + + let on_content = !on_objects && editing_content && can_modify && {+ + + source_blocked+ + + || crate::content_ui::page_input(+ + + cx,+ + + added,+ + + tool == QuickTool::AddText && !over_source,+ + + matches!(tool, QuickTool::AddText | QuickTool::EditText),+ + + text_style,+ + + view,+ + + )+ + + || tool == QuickTool::AddText && !over_source+ + + };+ + + // Added content owns its gesture; its source text must not queue a second edit.+ + + // Edit text & images boxes every paragraph and image whenever the tool is on. Only the+ + + // input waits while selected objects or added content own the pointer, or while page+ + + // input is blocked (another tab, a dialog, the window unfocused): the boxes stay drawn+ + + // instead of vanishing until the pointer comes back.+ + + let others_own_pointer = on_objects || on_content;+ + + let on_edit_text = (tool == QuickTool::EditText || over_source) && can_modify && {----- --- ------- --- let generation = doc.edit_generation();----- --- ------- --- let images = match view.edit_images.get(&i) {----- --- ------- --- Some((g, l)) if *g == generation => l.clone(),----- --- ------- --- _ => {----- --- ------- --- let l = doc.page_images(i);----- --- ------- --- view.edit_images.insert(i, (generation, l.clone()));----- --- ------- --- l----- --- ------- --- }----- --- ------- --- };+ + + // Editable text takes precedence over background/overlapping artwork. Both+ + + // inventories are painted every frame, even when text owns the pointer.----- --- ------- --- let text_used = crate::edit_text_ui::page_input(cx, &lines, view, !others_own_pointer && !image_owns_pointer);++++++ +++++++++++++++ let text_used = crate::edit_text_ui::page_input(cx, &lines, view, !others_own_pointer);+ + + let image_cx = crate::edit_text_ui::ImageCx {+ + + ui,+ + + resp,+ + + xf: &xf,+ + + ptr,+ + + page: i,+ + + info,----- --- ------- --- allow_interaction: !others_own_pointer && (image_owns_pointer || !text_used),++++++ +++++++++++++++ allow_interaction: !others_own_pointer && (matches!(view.router.owner(i), Some(crate::page_router::Owner::Picture { .. })) || !text_used),+ + + };+ + + let image_used = crate::edit_text_ui::image_input(&image_cx, &images, view, &mut frame.out.image_action);+ + + !others_own_pointer && (text_used || image_used)+ + + };+ + + let on_link = tool == QuickTool::Link && can_modify && crate::link_ui::page_input(cx, doc_links, view);+ + + if tool == QuickTool::Select+ + + && resp.secondary_clicked()+ + + && can_modify+ + + && let Some(p) = pointer.filter(|p| xf.rect.contains(*p))+ + + && let Some(l) = doc.links().iter().find(|l| l.page == i && crate::link_ui::screen_rect(&xf, info, i, l.rect).expand(2.0).contains(p))+ + + {+ + + view.links.context = Some((i, l.index));}- - - // Paging owns the vertical axis in single-page view; leave it to the pager.- - - // The rest of a gesture that turned the page is swallowed too, or it would pan the new page- - - // away from the edge it was shown at.- - - let paging_owns_vertical = single_paging || (!view.continuous && view.wheel.gesture_turned());- - - if paging_owns_vertical {- - - precise_scroll.y = 0.0;- - - line_base.y = 0.0;- - - boost_extra.y = 0.0;+ + + let consumed = on_objects || on_edit_text || on_link || on_content || boxing || on_field || comments::page_input(ui, resp, &pcx, view);- - - PageInput { consumed, over_field, area_tool }++++++ +++++++++++++++ // The cursor and the tip from what lies under the pointer, after the tools claimed theirs (the++++++ +++++++++++++++ // last claim on a layer stands).++++++ +++++++++++++++ if frame.env.unobstructed++++++ +++++++++++++++ && let Some(p) = pointer++++++ +++++++++++++++ {++++++ +++++++++++++++ for h in hits.at(view, p) {++++++ +++++++++++++++ view.cursor.claim_with_tip(h.layer, h.icon, h.tip);++++++ +++++++++++++++ }+++++ +++ +++++++ +++ }- - - // egui smooths a Point event that moved at least 8 points, keeping part of it for later- - - // passes. Suppression must outlive that whole action: once it expired after a fixed 0.25 s,- - - // the last few eased points leaked through the ScrollArea after a precise 1:1 scroll (held- - - // point input measured 33 points for a 30-point event). Keep hiding the eased copy until- - - // egui says the action is over, then forget the suppression.- - - let scrolling = ui.input(|i| i.is_scrolling());- - - if now < view.precise_scroll_until || (view.precise_scroll_until != 0.0 && scrolling) {- - - if scrolling {- - - // Keep hiding egui's unprocessed copy until it has drained. The short rolling grace- - - // avoids a delayed duplicate without prolonging suppression after the tail is gone.- - - view.precise_scroll_until = view.precise_scroll_until.max(now + SUPPRESS_TAIL_SECS);- - - }- - - ui.input_mut(|i| i.smooth_scroll_delta = Vec2::ZERO);- - - // The point path suppresses every eased wheel delta. Restore the line base through the- - - // same un-eased path as its surplus; paging-owned axes were cleared above.- - - boost_extra = crate::wheel_boost::cap_frame(boost_extra + line_base);- - - if has_page {- - - // Page units normally stay on egui's viewport-sized path. During suppression only,- - - // reproduce the current event directly so an older hidden tail stays hidden.- - - let page_scale = ui.input(|i| i.viewport_rect().height());- - - let mut page_delta =- - - if page_scale.is_finite() && page_scale > 0.0 { crate::wheel_boost::cap_frame(input.page * page_scale) } else { Vec2::ZERO };- - - if paging_owns_vertical {- - - page_delta.y = 0.0;- - - }- - - boost_extra = crate::wheel_boost::cap_frame(boost_extra + page_delta);+ + + + ++ PageInput { consumed, area_tool }+ + + + ++ }+ + + + ++++++++ +++++++++++++++/// Edit text's paragraphs and pictures on page `i`, kept while the document is unchanged.++++++ +++++++++++++++fn edit_inventory(++++++ +++++++++++++++ view: &mut DocView,++++++ +++++++++++++++ doc: &pdfcraft_engine::Document,++++++ +++++++++++++++ i: usize,++++++ +++++++++++++++) -> (Vec<pdfcraft_engine::TextBlock>, Vec<pdfcraft_engine::PageImage>) {++++++ +++++++++++++++ let generation = doc.edit_generation();++++++ +++++++++++++++ let lines = match view.edit_lines.get(&i) {++++++ +++++++++++++++ Some((g, l)) if *g == generation => l.clone(),++++++ +++++++++++++++ _ => {++++++ +++++++++++++++ let l = doc.text_blocks(i);++++++ +++++++++++++++ view.edit_lines.insert(i, (generation, l.clone()));++++++ +++++++++++++++ l+++++ +++ +++++++ +++ }- - - } else {- - - precise_scroll = Vec2::ZERO;- - - // Selection handling below uses zero to distinguish an inactive window. Clearing a past- - - // deadline also keeps a later line/page action from being mistaken for the old tail.- - - view.precise_scroll_until = 0.0;- - - }- - - if has_page && paging_owns_vertical {- - - // Page input belongs to egui on the free axis; the pager still owns vertical motion.- - - ui.input_mut(|i| i.smooth_scroll_delta.y = 0.0);- - - }- - - // Touchpad momentum (#531): a swipe over the page lifted at speed glides on and slows to a- - - // stop, through the same un-eased path. Never while the pager owns the wheel, a gesture or- - - // dialog has the input, or animations are off; any click, key, zoom or other scrolling ends it.- - - // Asked of the preference, not of egui's animation time, which test harnesses zero.- - - let animates = app.animation_effects.animates(app.motion.reduced);- - - let may_glide = !paging_owns_vertical && !middle_gesture && navigation_enabled && unobstructed && animates;- - - let over_page = ui.rect_contains_pointer(avail);- - - ui.input(|i| view.fling.read(&i.events, now, may_glide && over_page));- - - let interrupted = glide_interrupted(ui);- - - if !may_glide || interrupted || key_scroll != 0.0 || auto_delta != Vec2::ZERO || zoom_delta != 1.0 {- - - view.fling.stop();- - - }- - - let glide = view.fling.step(now);- - - if view.fling.gliding() {- - - ui.ctx().request_repaint();- - - }- - - // Any reader-owned motion ends automatic search following, even when it stays on the same- - - // page: the wheel, keyboard, middle-button auto-scroll, a drawing's edge scroll, or the- - - // momentum left by a touchpad swipe. The automatic flash uses `goto`, not these deltas, so- - - // its programmatic scroll is never mistaken for a reader action.- - - let wheel_scrolled = precise_scroll != Vec2::ZERO || line_base != Vec2::ZERO || boost_extra != Vec2::ZERO || has_page;- - - if wheel_scrolled || auto_delta != Vec2::ZERO || edge_delta != Vec2::ZERO || glide != Vec2::ZERO {- - - view.end_find_following();- - - }- - - // The wheel may have turned the page above: draw the row it turned to. Measured from the old- - - // row, the jump to the new page scrolled both out of view, a blank frame on every turn forward.- - - let row = shown_row(view);- - - let visible_pages: Vec<usize> = if view.continuous { (0..rects.len()).collect() } else { row.clone() };- - - let (y_shift, content_h) = if view.continuous {- - - (0.0, rects.iter().map(|r| r.bottom()).reduce(f32::max).map(|bottom| bottom + MARGIN).unwrap_or(0.0))- - - } else {- - - // Only the current row scrolls into view; the content is its bounding box plus margins.- - - match row.iter().filter_map(|&i| rects.get(i)).copied().reduce(Rect::union) {- - - Some(r) => (r.top() - MARGIN, r.height() + 2.0 * MARGIN),- - - None => (0.0, 0.0),++++++ +++++++++++++++ };++++++ +++++++++++++++ let images = match view.edit_images.get(&i) {++++++ +++++++++++++++ Some((g, l)) if *g == generation => l.clone(),++++++ +++++++++++++++ _ => {++++++ +++++++++++++++ let l = doc.page_images(i);++++++ +++++++++++++++ view.edit_images.insert(i, (generation, l.clone()));++++++ +++++++++++++++ l+++++ +++ +++++++ +++ }+++++ +++ +++++++ +++ };++++++ +++++++++++++++ (lines, images)++++++ +++++++++++++++}+++++ +++ +++++++ +++- - - let mut scroll = egui::ScrollArea::both().auto_shrink([false, false]).scroll_source(egui::scroll_area::ScrollSource {- - - drag: if middle_gesture {- - - egui::scroll_area::DragScroll::Never- - - } else if app.quick_tool == QuickTool::Hand {- - - egui::scroll_area::DragScroll::Always++++++ +++++++++++++++/// What the page modules have under a point on one page, for the page router.++++++ +++++++++++++++struct PageHits<'a> {++++++ +++++++++++++++ page: usize,++++++ +++++++++++++++ xf: &'a PageXform,++++++ +++++++++++++++ info: &'a DocInfo,++++++ +++++++++++++++ tool: QuickTool,++++++ +++++++++++++++ pcx: &'a comments::PageCx<'a>,++++++ +++++++++++++++ form: &'a [pdfcraft_engine::FormField],++++++ +++++++++++++++ can_fill: bool,++++++ +++++++++++++++ can_modify: bool,++++++ +++++++++++++++ /// Edit a PDF is open: added text and pictures can be picked up.++++++ +++++++++++++++ editing_content: bool,++++++ +++++++++++++++ preparing: bool,++++++ +++++++++++++++ field_tool: Option<crate::prepare::FieldTool>,++++++ +++++++++++++++ /// Prepare may draw and move fields (not while a table is being set up).++++++ +++++++++++++++ prepare_allowed: bool,++++++ +++++++++++++++ added: &'a [pdfcraft_engine::Added],++++++ +++++++++++++++ lines: &'a [pdfcraft_engine::TextBlock],++++++ +++++++++++++++ images: &'a [pdfcraft_engine::PageImage],++++++ +++++++++++++++ /// The pages' visible area (the picture's rotate knob stays inside it).++++++ +++++++++++++++ clip: Rect,++++++ +++++++++++++++}++++++ +++++++++++++++++++++ +++++++++++++++impl PageHits<'_> {++++++ +++++++++++++++ /// The hits at `p`, bottom up: links, comments; Edit text's pictures under its paragraphs (text++++++ +++++++++++++++ /// on top of artwork takes the press), added content, the objects selected together and the++++++ +++++++++++++++ /// open paragraph's frame, the selected picture's grips over them all; then form fields++++++ +++++++++++++++ /// (Prepare's, being moved, over the comments; filled ones under added content and the++++++ +++++++++++++++ /// comments that move).++++++ +++++++++++++++ fn at(&self, view: &DocView, p: Pos2) -> Vec<crate::page_router::Hit> {++++++ +++++++++++++++ let PageHits {++++++ +++++++++++++++ page,++++++ +++++++++++++++ xf,++++++ +++++++++++++++ info,++++++ +++++++++++++++ tool,++++++ +++++++++++++++ pcx,++++++ +++++++++++++++ form,++++++ +++++++++++++++ can_fill,++++++ +++++++++++++++ can_modify,++++++ +++++++++++++++ editing_content,++++++ +++++++++++++++ preparing,++++++ +++++++++++++++ field_tool,++++++ +++++++++++++++ prepare_allowed,++++++ +++++++++++++++ added,++++++ +++++++++++++++ lines,++++++ +++++++++++++++ images,++++++ +++++++++++++++ clip,++++++ +++++++++++++++ } = *self;++++++ +++++++++++++++ let fields = if preparing {++++++ +++++++++++++++ crate::prepare::hit(xf, info, page, form, field_tool, prepare_allowed, &view.prepare, p)++++++ +++++++++++++++ } else if tool == QuickTool::Select {++++++ +++++++++++++++ crate::forms_ui::hit(xf, info, page, form, can_fill, p)+++++ +++ +++++++ +++ } else {- - - egui::scroll_area::DragScroll::OnTouch- - - },- - - ..Default::default()- - - });- - - // Each document keeps its own scroll position when switching tabs (#189).- - - scroll = scroll.id_salt(("page-view", view.id));- - - // Every scroll here asks for no animation. An animated area would still queue a zero-length- - - // offset target for the next frame, which overwrites the jump a page turn just set.- - - scroll = scroll.animated(false);- - - // A newly opened document starts at the top. eframe saves egui's memory with the settings- - - // and document ids start again at 1 every launch, so the offset stored under this id can be- - - // where an earlier session left another document.- - - if !std::mem::replace(&mut view.shown, true) {- - - scroll = scroll.scroll_offset(Vec2::ZERO);- - - }- - - // The Hand tool pans here, before the pages are laid out, so the page moves with the pointer- - - // in the frame the pointer moves (#924). Scrolling by the drag from inside the area moved the- - - // page only after that frame was drawn, a frame behind. The frame egui tells the drag from a- - - // click, the page catches up with all the pointer has moved since the press. A jump asked for- - - // below still wins.- - - if app.quick_tool == QuickTool::Hand- - - && !middle_gesture- - - && let Some(id) = view.page_widget.filter(|id| ui.ctx().is_being_dragged(*id))- - - {- - - let moved = if ui.ctx().drag_started_id() == Some(id) {- - - ui.input(|i| i.pointer.total_drag_delta()).unwrap_or(Vec2::ZERO)++++++ +++++++++++++++ None++++++ +++++++++++++++ };++++++ +++++++++++++++ // With Add text, only the paragraphs and pictures not under added content.++++++ +++++++++++++++ let editing =++++++ +++++++++++++++ can_modify && (tool == QuickTool::EditText || tool == QuickTool::AddText && !crate::content_ui::hits_added(xf, info, page, added, p));++++++ +++++++++++++++ let (pictures, paragraphs, objects, grips) = if editing {++++++ +++++++++++++++ let open = view.line_editor.as_ref().filter(|e| e.page == page);++++++ +++++++++++++++ let frame = open++++++ +++++++++++++++ .filter(|e| !e.has_changes())++++++ +++++++++++++++ .and_then(|e| lines.get(e.block))++++++ +++++++++++++++ .map(|l| xf.user_rect(info, page, l.rect.map(|v| v as f32)).expand(2.0));++++++ +++++++++++++++ // Add text acts on the page's paragraphs only in their boxes, edges included (it++++++ +++++++++++++++ // finishes the box being typed there, `over_source`): not on pictures, nor beside a++++++ +++++++++++++++ // paragraph, where a click starts a new box.++++++ +++++++++++++++ let edit_text = tool == QuickTool::EditText;++++++ +++++++++++++++ let on_paragraphs = edit_text || crate::edit_text_ui::over_paragraph(xf, info, page, lines, p);++++++ +++++++++++++++ (++++++ +++++++++++++++ edit_text.then(|| crate::edit_text_ui::picture_hit(xf, page, info, images, view, p)).flatten(),++++++ +++++++++++++++ on_paragraphs.then(|| crate::edit_text_ui::hit(xf, info, page, lines, open.map(|e| e.block), p)).flatten(),++++++ +++++++++++++++ edit_text.then(|| crate::object_ui::hit(view, xf, info, page, frame, p)).flatten(),++++++ +++++++++++++++ edit_text.then(|| crate::edit_text_ui::picture_handle_hit(clip, xf, page, info, images, view, p)).flatten(),++++++ +++++++++++++++ )+++++ +++ +++++++ +++ } else {- - - ui.input(|i| i.pointer.delta())++++++ +++++++++++++++ (None, None, None, None)+++++ +++ +++++++ +++ };- - - if moved != Vec2::ZERO {- - - view.end_find_following();- - - }- - - // Within the content, as egui keeps it: past an end the page would show there for a- - - // frame and spring back. `max` is never NaN or below zero, so the clamp can't panic.- - - let max = vec2((content_w - avail.width()).max(0.0), (content_h - avail.height()).max(0.0));- - - scroll = scroll.scroll_offset((view.last_scroll - moved).clamp(Vec2::ZERO, max));++++++ +++++++++++++++ // Added text and pictures, over the page's own paragraphs and under the objects selected++++++ +++++++++++++++ // together.++++++ +++++++++++++++ let picks_up = matches!(tool, QuickTool::Select | QuickTool::AddText | QuickTool::EditText);++++++ +++++++++++++++ let added = (editing_content && can_modify && picks_up).then(|| crate::content_ui::hit(xf, info, page, added, view, p)).flatten();++++++ +++++++++++++++ [link_hit(info, xf, page, p), comments::hit(pcx, view, p), pictures, paragraphs, added, objects, grips, fields]++++++ +++++++++++++++ .into_iter()++++++ +++++++++++++++ .flatten()++++++ +++++++++++++++ .collect()+++++ +++ +++++++ +++ }- - - if let Some(v) = view.sync_scroll.take() {- - - scroll = scroll.scroll_offset(v);++++++ +++++++ + ++ ++}++++++ +++++++ + ++ +++ + + /// Text layer: find matches, selection, I-beam and drag-to-select.+ + + fn text_layer(ui: &mut egui::Ui, view: &mut DocView, frame: &mut PageFrame<'_>, slot: &PageSlot, input: &PageInput) {+ + + let PageEnv { info, selects_text, tool, .. } = frame.env;+ + + let PageSlot { i, r, xf } = *slot;+ + + let PageFrame { resp, ptr, pointer, .. } = *frame;+ + + if let Some(text) = view.texts.get(&i).cloned() {+ + + paint_text_marks(ui, view, &text, i, xf, resp.dragged());+ + + if selects_text+ + + && !input.consumed+ + + && let Some(p) = pointer.filter(|p| r.contains(*p))+ + + {- - - text_pointer_input(- - - ui,- - - view,- - - &text,- - - TextPointer { page: i, xf, rect: r, info, tool, resp, ptr: ptr.clone(), pointer: p, over_field: input.over_field },- - - );+ + + + ++ text_pointer_input(ui, view, &text, TextPointer { page: i, xf, rect: r, info, tool, resp, ptr: ptr.clone(), pointer: p });+ + + }}- - - if let Some((page, fx, fy, rel)) = view.zoom_anchor.take() {- - - let r = rects[page.min(rects.len() - 1)];- - - let point = pos2(r.left() + fx * r.width(), r.top() - y_shift + fy * r.height());- - - scroll = scroll.scroll_offset(anchored_scroll(point, rel, vec2(content_w, content_h), avail.size()));- - - } else if let Some((page, frac)) = view.goto.take() {- - - let page = page.min(rects.len() - 1);- - - let r = rects[page];- - - // Clamped here: egui clamps only after drawing, so a page that fits was drawn MARGIN - page_gap()- - - // too high for a frame and then hopped into place. (`avail` is the viewport, as the- - - // scroll bars float.)- - - let max_y = (content_h - avail.height()).max(0.0);- - - scroll = scroll.vertical_scroll_offset((r.top() - y_shift - view.page_gap() + frac * r.height()).max(0.0).min(max_y));- - - // Horizontally too, as Acrobat does (#2665): beside a much wider page the others sit off- - - // to one side. A page already shown whole, or one filling the window's width, keeps the- - - // scroll, so paging through a zoomed-in document stays on the same column. Otherwise a- - - // page that fits is centred, and a wider one scrolled just far enough to fill the window.- - - // The page counts with its side gutters, which keep its edge clear of the floating- - - // quick-action bar as the layout does.- - - let (x, w) = (view.last_scroll.x, avail.width());- - - let (left, right) = (r.left() - SIDE, r.right() + SIDE);- - - let target = if right - left <= w { if left >= x && right <= x + w { x } else { r.center().x - w / 2.0 } } else { x.clamp(left, right - w) };- - - if (target - x).abs() > 0.5 {- - - scroll = scroll.horizontal_scroll_offset(target.clamp(0.0, (content_w - w).max(0.0)));+ + + }+ + ++ + + fn paint_text_marks(ui: &egui::Ui, view: &DocView, text: &PageText, page: usize, xf: PageXform, dragging: bool) {+ + + let painter = ui.painter();+ + + let to_screen = |g: [f32; 4]| xf.view_rect(g);+ + + if let Some(find) = &view.find {+ + + for (index, (match_page, range)) in find.matches.iter().enumerate() {+ + + if *match_page != page {+ + + continue;+ + + }+ + + let fill = if find.current == Some(index) {+ + + Color32::from_rgba_unmultiplied(255, 140, 0, 110)+ + + } else {+ + + Color32::from_rgba_unmultiplied(255, 214, 0, 90)+ + + };+ + + for line_rect in text.line_rects(range.clone()) {+ + + painter.rect_filled(to_screen(line_rect).expand(1.0), CornerRadius::same(2), fill);+ + + }}}- - - let ppp = ui.ctx().pixels_per_point();- - - let scale = view.render_scale(ppp);- - - let tag = scale_tag(scale);- - - // Hold sharp re-renders while the zoom is still moving: a new scale every frame would- - - // cancel the in-flight full-page interpret and restart it, so on a heavy page (a CAD- - - // plot with ~1000 images renders for seconds) the sharp raster never arrives and the- - - // view looks stuck on a soft image. The stale raster stays stretched meanwhile; the- - - // sharp request goes out once the zoom settles.- - - let now_scale = ui.input(|i| i.time);- - - if (scale - view.last_scale).abs() > f32::EPSILON {- - - view.last_scale = scale;- - - view.sharp_hold_until = now_scale + 0.35;- - - ui.ctx().request_repaint_after(std::time::Duration::from_millis(380));+ + + if view.all_text {+ + + for line_rect in text.line_rects(0..text.glyphs.len()) {+ + + painter.rect_filled(to_screen(line_rect), CornerRadius::same(1), Color32::from_rgba_unmultiplied(0x3A, 0x7B, 0xF0, 70));+ + + }}- - - let sharp_held = now_scale < view.sharp_hold_until;- - - view.current_scale_tag = tag;- - - let hand = app.quick_tool == QuickTool::Hand;- - - let tool = app.quick_tool;- - - // Text selection runs for the Select tool and for the markup tools (highlight…).- - - let selects_text = match tool {- - - QuickTool::Comment(t) => t.markup().is_some() || t == comments::CommentTool::ReplaceText,- - - QuickTool::Select => !preparing,- - - QuickTool::Redact | QuickTool::ColumnSelect => true,- - - QuickTool::Hand- - - | QuickTool::Measure(_)- - - | QuickTool::Crop- - - | QuickTool::EnhanceCamera- - - | QuickTool::Fill(_)- - - | QuickTool::Field(_)- - - | QuickTool::AddText- - - | QuickTool::EditText- - - | QuickTool::Stamp(_)- - - | QuickTool::CustomStamp(_)- - - | QuickTool::Link- - - | QuickTool::SignArea { .. }- - - | QuickTool::MarqueeZoom- - - | QuickTool::Snapshot => false,- - - };- - - let prefs = &app.comment_prefs;- - - let redact_mark = (app.redact_prefs.hover_fill, app.redact_prefs.opacity);- - - let units = app.units;- - - let allowed = doc.allows_annotation();- - - let can_copy = doc.allows_copying();- - - let mut copy_selected = false;- - - let comments_hidden = doc.comments_hidden();- - - let form = doc.form.clone();- - - let generation = doc.edit_generation();- - - let can_fill = doc.allows_form_filling();- - - let can_crop = doc.allows_assembly();- - - let mut open_boxes = false;- - - let signature = app.signature.clone();- - - let initials = app.initials.clone();- - - let mut open_initials = false;- - - let author = app.comment_prefs.author.clone();- - - let today = app.session.today();- - - // In Preferences ▸ Date format, or why it can't be stamped into the PDF.- - - let date_text = crate::date_text_for_pdf(&app.session);- - - let mut refused: Option<String> = None;- - - let by_line = app.session.stamp_by_line(&author);- - - let mut stamp_placed = false;- - - let mut image_action: Option<crate::edit_text_ui::ImageAction> = None;- - - let custom_stamp = match app.quick_tool {- - - QuickTool::CustomStamp(i) => app.custom_stamps.get(i).cloned(),- - - _ => None,- - - };- - - let mut open_signature = false;- - - let mut hover_text: Option<(Pos2, String)> = None;- - - let mut badge_hover: Option<(Pos2, String)> = None;- - - let mut clicked_link: Option<LinkTarget> = None;- - - let mut remote_open: Option<(pdfcraft_engine::DocId, String, pdfcraft_render::RemoteDestination)> = None;- - - let mut canvas_action: Option<comments::CanvasAction> = None;- - - let mut field_menu: Option<FieldMenu> = None;- - - let mut open_props: Option<(usize, usize)> = None;- - - let mut field_props = false;- - - let mut field_placed = false;- - - let mut open_table: Option<(usize, [f64; 4])> = None;- - - // The table being set up in its window, shown on its own document's page.- - - let table_preview = app.field_table_draft.as_mut().filter(|d| d.doc == view.id).and_then(|d| Some(d.preview(info.pages.get(d.page)?, &form)));- - - let can_modify = doc.allows_modification();- - - if preparing {- - - crate::prepare::after_refresh(view, &form);- - - } else {- - - view.prepare.selected = None;+ + + if let Some(selection) = view.selection.filter(|selection| selection.page == page) {+ + + for line_rect in selection.rects(text) {+ + + painter.rect_filled(to_screen(line_rect), CornerRadius::same(1), Color32::from_rgba_unmultiplied(0x3A, 0x7B, 0xF0, 70));+ + + }+ + + if let Span::Column { rect } = selection.span+ + + && dragging+ + + {+ + + let outline = Stroke::new(1.0, Color32::from_rgb(0x3A, 0x7B, 0xF0));+ + + painter.rect_stroke(to_screen(rect), CornerRadius::ZERO, outline, egui::StrokeKind::Middle);+ + + }}- - - view.objects.prepare(doc, tool == QuickTool::EditText && can_modify, ui.ctx());- - - view.text_background.prepare(ui.ctx(), doc, view.line_editor.as_ref(), view.content.draft.as_ref(), scale);- - - let added = if editing_content { doc.added().to_vec() } else { Vec::new() };- - - let doc_links = if tool == QuickTool::Link { doc.links().to_vec() } else { Vec::new() };- - - if editing_content {- - - crate::content_ui::after_refresh(view, &added);- - - } else {- - - view.content.selected = None;+ + + }+ + ++ + + struct TextPointer<'a> {+ + + page: usize,+ + + xf: PageXform,+ + + rect: Rect,+ + + info: &'a DocInfo,+ + + tool: QuickTool,+ + + resp: &'a egui::Response,+ + + ptr: PagePointer,+ + + pointer: Pos2,- - - over_field: bool,+ + + }+ + ++ + + struct TextGesture<'a> {+ + + page: usize,+ + + xf: PageXform,+ + + rect: Rect,+ + + tool: QuickTool,+ + + ptr: PagePointer,+ + + resp: &'a egui::Response,+ + + pointer: Pos2,+ + + vx: f32,+ + + vy: f32,+ + + over_text: bool,+ + + over_link: bool,+ + + column: bool,+ + + }+ + ++ + + fn text_pointer_input(ui: &mut egui::Ui, view: &mut DocView, text: &PageText, pointer: TextPointer<'_>) {- - - let TextPointer { page, xf, rect, info, tool, resp, ptr, pointer: screen_pointer, over_field } = pointer;+ + + + ++ let TextPointer { page, xf, rect, info, tool, resp, ptr, pointer: screen_pointer } = pointer;+ + + let (vx, vy) = xf.screen_to_view(screen_pointer);+ + + let over_text = text.glyphs.iter().any(|glyph| vx >= glyph.rect[0] && vx <= glyph.rect[2] && vy >= glyph.rect[1] && vy <= glyph.rect[3]);+ + + let over_link = info.links.iter().any(|link| link.page == page && xf.user_rect(info, page, link.rect).contains(screen_pointer));+ + + let column = tool == QuickTool::ColumnSelect || ui.input(|input| input.modifiers.alt);+ + + let gesture = TextGesture { page, xf, rect, tool, ptr, resp, pointer: screen_pointer, vx, vy, over_text, over_link, column };- - - update_text_cursor(ui, resp, over_field, &gesture);+ + + + ++ update_text_cursor(view, &gesture);+ + + update_selection_on_press(ui, view, text, &gesture);+ + + update_dragged_selection(view, text, &gesture);+ + + finish_text_pointer_gesture(ui, view, text, &gesture);+ + + }+ + +- - - fn update_text_cursor(ui: &egui::Ui, resp: &egui::Response, over_field: bool, gesture: &TextGesture<'_>) {- - - let cursor_free = !gesture.over_link && !over_field && (resp.contains_pointer() || resp.dragged());- - - if gesture.column && cursor_free {- - - ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair);- - - } else if gesture.over_text && cursor_free {- - - ui.ctx().set_cursor_icon(egui::CursorIcon::Text);+ + + + ++ fn update_text_cursor(view: &mut DocView, gesture: &TextGesture<'_>) {+ + + + ++ // A press on a link selects nothing (it is the link's), so no cursor here says it would.+ + + + ++ if gesture.column && !gesture.over_link {+ + + + ++ view.cursor.claim(Layer::Text, egui::CursorIcon::Crosshair);+ + + + ++ } else if gesture.over_text && !gesture.over_link {+ + + + ++ view.cursor.claim(Layer::Text, egui::CursorIcon::Text);}- - - view.move_background.prepare(ui.ctx(), doc, &view.content, scale);+ + + }- - - // A destination's position (bookmarks, links) refines `goto`: its point at the window's- - - // top-left, or the centre of a /FitR rectangle at the window's centre.- - - if let Some((page, fx, fy, rel)) = view.goto_point.take() {- - - let r = rects[page.min(rects.len() - 1)];- - - // Within the content, so an unreachable point never shows a frame scrolled past the end.- - - let (max_x, max_y) = ((content_w - avail.width()).max(0.0), (content_h - avail.height()).max(0.0));- - - if let Some(fx) = fx {- - - scroll = scroll.horizontal_scroll_offset((r.left() + fx * r.width() - rel.x).clamp(0.0, max_x));- - - }- - - if let Some(fy) = fy {- - - scroll = scroll.vertical_scroll_offset((r.top() - y_shift + fy * r.height() - rel.y).clamp(0.0, max_y));+ + + fn update_selection_on_press(ui: &egui::Ui, view: &mut DocView, text: &PageText, gesture: &TextGesture<'_>) {++++++ +++++++++++++++ // A press held by what keeps its drag (a link, a comment that moves) selects no text; one on++++++ +++++++++++++++ // text markup lets its drag select the text underneath.+ + + let press_here = gesture.ptr.origin.is_some_and(|origin| gesture.rect.contains(origin));----- --- ------- --- if gesture.ptr.pressed().is_some() && press_here && !gesture.over_link {++++++ +++++++++++++++ if gesture.ptr.pressed().is_some() && press_here && !view.router.keeps_drag() {+ + + let now = ui.input(|input| input.time);+ + + let (max_delay, max_dist) = ui.ctx().options(|options| (options.input_options.max_double_click_delay, options.input_options.max_click_dist));+ + + let consecutive = now - view.last_press_time <= max_delay && view.last_press_pos.is_some_and(|pos| pos.distance(gesture.pointer) <= max_dist);+ + + view.clicks = if consecutive { view.clicks.saturating_add(1) } else { 1 };+ + + view.last_press_time = now;+ + + view.last_press_pos = Some(gesture.pointer);+ + + let clicks = selection_click_count(view.clicks, gesture.tool);+ + + if clicks >= 2+ + + && gesture.over_text+ + + && let Some((first, last)) = text.nearest(gesture.vx, gesture.vy).and_then(|anchor| click_unit(text, clicks, anchor))+ + + {+ + + view.selection = Some(Selection::run(gesture.page, first, last));}}----- --- ------- --- if gesture.resp.drag_started() && press_here && !gesture.over_link {- - - let selection_wheel = view.selection_drag && navigation_enabled && unobstructed && !single_paging && ui.rect_contains_pointer(avail);- - - let out = page_scroll(ui, scroll, egui::Id::unique(("page-view-scope", view.id)), |ui, viewport| {- - - // egui's drag responses accept every pointer button. Keep a wheel gesture from also- - - // selecting text, drawing a mark, or panning with the Hand tool.- - - if middle_gesture {- - - let opacity = ui.opacity();- - - ui.disable();- - - // Only interactions pause; the document must keep its original colours.- - - ui.set_opacity(opacity);- - - }- - - // Middle-button auto-scroll, the keyboard, precise touchpad input (#759) and its glide- - - // (#531), accelerated wheel surplus (#1072), and a drawing's edge scroll; positive y- - - // moves the content down. All scroll without easing, unlike egui's wheel default.- - - // ScrollArea ignores wheel input during a widget drag. Defer the wheel contribution- - - // until after the text widgets when a selection owns that drag.- - - let wheel_delta = if selection_wheel { Vec2::ZERO } else { precise_scroll + boost_extra };- - - let delta = auto_delta + edge_delta - vec2(0.0, key_scroll) + wheel_delta + glide;- - - if delta != Vec2::ZERO && delta.is_finite() {- - - ui.scroll_with_delta_animation(delta, egui::style::ScrollAnimation::none());- - - }- - - let (resp_rect, resp) = ui.allocate_exact_size(vec2(content_w, content_h), Sense::click_and_drag());- - - view.page_widget = Some(resp.id);- - - // A drag lasts only while egui reports it, so the mark can't outlive one.- - - if !resp.dragged_by(egui::PointerButton::Primary) {- - - view.selection_drag = false;- - - }- - - // The Hand tool pans by this widget's drag, before the pages are laid out (above).- - - if hand {- - - if resp.dragged() {- - - ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing);- - - } else if resp.hovered() {- - - ui.ctx().set_cursor_icon(egui::CursorIcon::Grab);- - - }++++++ +++++++++++++++ if gesture.resp.drag_started() && press_here && !view.router.keeps_drag() {+ + + view.actions_dismissed = None;+ + + view.selection_drag = true;+ + + let origin = gesture.ptr.origin.unwrap_or(gesture.pointer);+ + + let (ox, oy) = gesture.xf.screen_to_view(origin);+ + + if view.clicks < 2 {+ + + view.selection = if gesture.column {+ + + Some(Selection { page: gesture.page, span: Span::Column { rect: [ox, oy, gesture.vx, gesture.vy] } })+ + + } else {+ + + text.nearest(ox, oy).map(|anchor| Selection::run(gesture.page, anchor, anchor))+ + + };}- - - let origin = resp_rect.min - vec2(0.0, y_shift);- - - let painter = ui.painter();- - - let visible = viewport.translate(resp_rect.min.to_vec2());- - - let mut wanted = Vec::new();- - - let mut visible_now = Vec::new();- - - view.screen_rects.clear();- - - view.screen_xforms.clear();- - - // Visible heights (points) closer than this are equal: one page size can meet the- - - // viewport a fraction of a point differently once the scroll offset is applied.- - - const TIE: f32 = 0.5;- - - let mut current = view.current;- - - let mut best_overlap = -1.0f32;- - - let mut current_overlap = -1.0f32;- - - let mut current_height = f32::INFINITY;- - - // The pointer as the pages see it: nothing over them (a dialog from the frame it opens),- - - // or a press they hold. The page modules read it rather than egui's raw pointer state.- - - let ptr = PagePointer::read(ui, &resp, modal);- - - let pointer = ptr.pos;- - - // A press on a page makes it the current one (as in Acrobat), so a page command with- - - // no selection (Rotate, Delete) acts on the page the reader pointed at, not on a page- - - // gone to earlier that still shows whole beside it.- - - let pressed = unobstructed && ptr.pressed().is_some();- - - let mut pressed_page = None;- - - if resp.secondary_clicked() {- - - // Set again below when the right-click lands on a link.- - - view.links.context = None;- - - }- - - let mut calc_hover = None;- - - for &i in &visible_pages {- - - badge_hover = None;- - - let r = snap_to_pixels(rects[i].translate(origin.to_vec2()), ppp);- - - if !r.intersects(visible.expand(400.0)) {- - - continue;- - - }- - - if pressed && pressed_page.is_none() && pointer.is_some_and(|p| r.contains(p)) {- - - pressed_page = Some(i);- - - }- - - if r.intersects(visible) {- - - visible_now.push(i);- - - view.screen_rects.push((i, r));- - - view.screen_xforms- - - .push((i, PageXform { rect: r, rot: view.rotation, pw: info.pages[i].width.max(1.0), ph: info.pages[i].height.max(1.0) }));- - - }- - - let overlap = r.intersect(visible).height();- - - if i == view.current {- - - current_overlap = overlap;- - - current_height = r.height();+ + + }+ + + }+ + ++ + + fn selection_click_count(clicks: u32, tool: QuickTool) -> u32 {+ + + if clicks > 2 && tool != QuickTool::Select { 1 } else { clicks }+ + + }+ + ++ + + fn update_dragged_selection(view: &mut DocView, text: &PageText, gesture: &TextGesture<'_>) {+ + + let clicks = selection_click_count(view.clicks, gesture.tool);+ + + if gesture.resp.dragged()+ + + && let Some(selection) = view.selection.as_mut().filter(|selection| selection.page == gesture.page)+ + + {+ + + match &mut selection.span {+ + + Span::Run { anchor, head } if clicks >= 2 => {+ + + if let Some(hit) = text.nearest(gesture.vx, gesture.vy)+ + + && let Some((first, last)) = click_unit(text, clicks, *anchor)+ + + {+ + + let (to_first, to_last) = click_unit(text, clicks, hit).unwrap_or((hit, hit));+ + + (*anchor, *head) = if to_first < first { (last, to_first) } else { (first, to_last.max(last)) };+ + + }}- - - // Pages shown equally (two rows wholly on screen) differ only by rounding: the- - - // topmost one counts.- - - if overlap > best_overlap + TIE {- - - best_overlap = overlap;- - - current = i;+ + + Span::Run { head, .. } => {+ + + if let Some(hit) = text.nearest(gesture.vx, gesture.vy) {+ + + *head = hit;+ + + }}- - - let xf = PageXform { rect: r, rot: view.rotation, pw: info.pages[i].width.max(1.0), ph: info.pages[i].height.max(1.0) };- - - // Shadows would darken the preceding page when pages touch.- - - if view.show_page_gaps {- - - painter.add(egui::epaint::Shadow { offset: [0, 3], blur: 14, spread: 0, color: t.page_shadow }.as_shape(r, CornerRadius::ZERO));- - - }- - - painter.rect_filled(r, CornerRadius::ZERO, paper);- - - if let Some(err) = view.errors.get(&i) {- - - painter.rect_filled(r, CornerRadius::ZERO, Color32::from_rgb(0xFB, 0xF4, 0xF4));- - - icons::paint(- - - ui,- - - Rect::from_center_size(r.center() - vec2(0.0, 26.0), vec2(28.0, 28.0)),- - - "triangle-alert",- - - 26.0,- - - Color32::from_rgb(0xC8, 0x3A, 0x3A),- - - );- - - let message = crate::i18n::fmt(tl!("This page couldn't be displayed.\n{e}"), &[("e", err)]);- - - let msg =- - - ui.fonts_mut(|f| f.layout(message, theme::regular(12.5), Color32::from_rgb(0x6A, 0x2A, 0x2A), (r.width() - 40.0).max(80.0)));- - - painter.galley(pos2(r.center().x - msg.size().x / 2.0, r.center().y), msg, Color32::BLACK);- - - } else {- - - let (pw_pt, ph_pt) = (info.pages[i].width.max(1.0), info.pages[i].height.max(1.0));- - - // A GPU may take smaller textures than these (OpenGL drivers report as little as- - - // 2048 pixels, and uploading a bigger one aborts), so both stay within its limit.- - - let max_side = ui.ctx().input(|inp| inp.max_texture_side) as f32;- - - let tiled = pw_pt.max(ph_pt) * scale > TILE_THRESHOLD.min(max_side);- - - // Whole-page raster: sharp when small, a low-res backdrop when tiled.- - - let (want_scale, want_tag) = if tiled {- - - let bs = BASE_SIDE.min(max_side) / pw_pt.max(ph_pt);- - - (bs, scale_tag(bs))- - - } else {- - - (scale, tag)- - - };- - - // Under tiles, a whole-page raster sharper than the backdrop (from before the page- - - // grew past the tiling size) is a better backdrop: keep demanding it as it is.- - - match view.pages.get(&i).filter(|p| tiled && p.tag != STALE_TAG && tag_scale(p.tag) >= want_scale) {- - - Some(p) => wanted.push((i, tag_scale(p.tag), p.tag, None)),- - - None => wanted.push((i, want_scale, want_tag, None)),- - - }- - - match view.pages.get(&i) {- - - Some(p) => {- - - if !tiled && p.tag == want_tag {- - - xf.texel_aligned(p.tex.size(), ppp).paint_image(painter, p.tex.id(), 0.0, 0.0, 1.0, 1.0);- - - } else {- - - // A backdrop, or a raster at an older scale until the new one arrives.- - - xf.paint_image(painter, p.tex.id(), 0.0, 0.0, 1.0, 1.0);- - - }- - - }- - - None => {- - - let now = ui.input(|inp| inp.time);- - - let since = *view.waiting_since.entry(i).or_insert(now);- - - let msg = if now - since > 6.0 { "Still rendering — this page is unusually complex…" } else { "Rendering…" };- - - painter.text(r.center(), Align2::CENTER_CENTER, tl!(msg), theme::regular(12.0), t.text_faint);- - - }- - - }- - - if tiled && r.intersects(visible) {- - - // Device-pixel geometry of the scaled page, and the visible part of it- - - // (found by mapping the visible screen corners back into the page). Sides round- - - // up as whole-page rasters do, so the last partial row and column get tiles.- - - let (dw, dh) = (device_pixels(pw_pt, scale), device_pixels(ph_pt, scale));- - - // Adaptive tile side for this zoom and page, within the GPU texture limit:- - - // a zoomed viewport or a giant sheet is covered by a few large tiles- - - // instead of many small ones, and each tile costs one full page interpret.- - - // Never zero (u32 division below).- - - let ts = tile_side(scale, dw.max(dh)).min(max_side as u32).max(64);- - - let vis = r.intersect(visible);- - - let corners = [vis.left_top(), vis.right_top(), vis.right_bottom(), vis.left_bottom()].map(|c| xf.screen_to_norm(c));- - - let (u0, u1) = corners.iter().fold((1.0f32, 0.0f32), |(a, b), c| (a.min(c.0), b.max(c.0)));- - - let (v0, v1) = corners.iter().fold((1.0f32, 0.0f32), |(a, b), c| (a.min(c.1), b.max(c.1)));- - - let (vx0, vy0) = ((u0.max(0.0) * dw as f32) as u32, (v0.max(0.0) * dh as f32) as u32);- - - let (vx1, vy1) = (((u1.min(1.0) * dw as f32).ceil() as u32).min(dw), ((v1.min(1.0) * dh as f32).ceil() as u32).min(dh));- - - // Tiles of earlier zooms first, stretched, the nearest scale last (on top):- - - // until the current tiles arrive, a zoom shows them rather than the backdrop.- - - let mut older: Vec<(f32, u32, u32, &TextureHandle)> = view- - - .tiles- - - .iter()- - - .filter(|((p, t, _, _), _)| *p == i && *t != tag)- - - .map(|((_, t, ox, oy), tex)| (tag_scale(*t), *ox, *oy, tex))- - - .collect();- - - older.sort_by(|a, b| (b.0 / scale).ln().abs().total_cmp(&(a.0 / scale).ln().abs()));- - - for (s, ox, oy, tex) in older {- - - let (ow, oh) = (device_pixels(pw_pt, s) as f32, device_pixels(ph_pt, s) as f32);- - - let [w, h] = tex.size();- - - let (x, y) = (ox as f32, oy as f32);- - - xf.paint_image(painter, tex.id(), x / ow, y / oh, (x + w as f32) / ow, (y + h as f32) / oh);- - - }- - - // Visible tiles, nearest the viewport centre first: each tile costs a full- - - // page interpret, so the workers sharpen what is looked at before the edges.- - - let (vcx, vcy) = ((vx0 + vx1) as f32 / 2.0, (vy0 + vy1) as f32 / 2.0);- - - let mut coords: Vec<(u32, u32)> = Vec::new();- - - for ty in vy0 / ts..=(vy1.saturating_sub(1)) / ts {- - - for tx in vx0 / ts..=(vx1.saturating_sub(1)) / ts {- - - coords.push((tx, ty));- - - }- - - }- - - coords.sort_by(|a, b| {- - - let da = ((a.0 * ts + ts / 2) as f32 - vcx).abs() + ((a.1 * ts + ts / 2) as f32 - vcy).abs();- - - let db = ((b.0 * ts + ts / 2) as f32 - vcx).abs() + ((b.1 * ts + ts / 2) as f32 - vcy).abs();- - - da.total_cmp(&db)- - - });- - - for (tx, ty) in coords {- - - let (x, y) = (tx * ts, ty * ts);- - - let (w, h) = (ts.min(dw.saturating_sub(x)), ts.min(dh.saturating_sub(y)));- - - if w == 0 || h == 0 {- - - continue;- - - }- - - wanted.push((i, scale, tag, Some(Tile { x, y, w, h })));- - - if let Some(tex) = view.tiles.get(&(i, tag, x, y)) {- - - let (fw, fh) = (dw as f32, dh as f32);- - - xf.texel_aligned([dw as usize, dh as usize], ppp).paint_image(- - - painter,- - - tex.id(),- - - x as f32 / fw,- - - y as f32 / fh,- - - (x + w) as f32 / fw,- - - (y + h) as f32 / fh,- - - );- - - }- - - }- - - }- - - }- - - view.text_background.paint(painter, &xf, i, view.line_editor.as_ref(), view.content.draft.as_ref());- - - if editing_content {- - - view.move_background.paint(painter, &xf, i, info, &view.content, pointer);- - - }- - - if view.show_page_gaps {- - - painter.rect_stroke(r, CornerRadius::ZERO, Stroke::new(0.5, t.border.gamma_multiply(0.8)), egui::StrokeKind::Outside);+ + + Span::Column { rect } => {+ + + rect[2] = gesture.vx;+ + + rect[3] = gesture.vy;}+ + + }+ + + }+ + + if gesture.resp.drag_stopped()+ + + && view.selection.is_some_and(|selection| {+ + + selection.page == gesture.page && matches!(selection.span, Span::Column { .. }) && selection.text(text).is_empty()+ + + })+ + + {+ + + view.selection = None;+ + + }+ + + }- - - // Comments: tools, selection, moving and resizing come before text selection.- - - let pcx = comments::PageCx { page: i, xf: &xf, ptr: &ptr, info, tool, prefs, allowed, hidden: comments_hidden, redact_mark };- - - if let QuickTool::Measure(measure_tool) = tool {- - - crate::measure_ui::page_input(ui, &resp, doc, view, &pcx, measure_tool, units);- - - }+ + + fn finish_text_pointer_gesture(ui: &egui::Ui, view: &mut DocView, text: &PageText, gesture: &TextGesture<'_>) {+ + + let release_clicks = if gesture.resp.triple_clicked() {+ + + view.clicks.max(2).saturating_add(1)+ + + } else if gesture.resp.double_clicked() {+ + + view.clicks.max(2)+ + + } else {+ + + 0+ + + };+ + + if release_clicks > 0 {+ + + view.clicks = release_clicks;+ + + }+ + + let clicks = selection_click_count(view.clicks, gesture.tool);+ + + if release_clicks > 0+ + + && clicks >= 2+ + + && gesture.over_text+ + + && view.selection.is_none()+ + + && let Some((first, last)) = text.nearest(gesture.vx, gesture.vy).and_then(|anchor| click_unit(text, clicks, anchor))+ + + {+ + + view.selection = Some(Selection::run(gesture.page, first, last));----- --- ------- --- } else if gesture.resp.clicked() && view.clicks < 2 && !gesture.over_link {++++++ +++++++++++++++ } else if gesture.resp.clicked() && view.clicks < 2 && !view.router.keeps_drag() {+ + + let shift = ui.input(|input| input.modifiers.shift);+ + + match (+ + + view.selection.as_mut().filter(|selection| shift && selection.page == gesture.page).map(|selection| &mut selection.span),+ + + text.nearest(gesture.vx, gesture.vy),+ + + ) {+ + + (Some(Span::Run { head, .. }), Some(hit)) => *head = hit,+ + + _ => view.selection = None,+ + + }+ + + }+ + + }- - - // Form fields take clicks first with the Select tool (as Acrobat fills fields in- - - // every viewing mode); then comments; then text selection.- - - if let QuickTool::Stamp(kind) = tool- - - && allowed- - - && let Some(p) = ptr.within(xf.rect)- - - {- - - ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair);- - - if resp.clicked() {- - - // Centred on the click, upright as the page is shown.- - - let (vx, vy) = xf.screen_to_view(p);- - - let (w, h) = kind.size();- - - let corners = [(vx as f64 - w / 2.0, vy as f64 - h / 2.0), (vx as f64 + w / 2.0, vy as f64 + h / 2.0)];- - - let u: Vec<[f32; 2]> = corners.iter().map(|(x, y)| info.pages[i].view_to_user(*x as f32, *y as f32)).collect();- - - let rect = [u[0][0].min(u[1][0]) as f64, u[0][1].min(u[1][1]) as f64, u[0][0].max(u[1][0]) as f64, u[0][1].max(u[1][1]) as f64];- - - let by = (kind.group() == pdfcraft_engine::StampGroup::Dynamic).then(|| by_line.clone());- - - let shape = pdfcraft_engine::Shape::Stamp { rect, stamp: kind, by };- - - view.pending_edit = Some(pdfcraft_engine::Edit::AddAnnotation(pdfcraft_engine::NewAnnotation {- - - page: i,- - - style: pdfcraft_engine::Style::default_for(&shape),- - - shape,- - - contents: String::new(),- - - author: author.clone(),- - - }));- - - stamp_placed = true;- - - }- - - }- - - if let Some(cs) = custom_stamp.as_ref()- - - && allowed- - - && let Some(p) = ptr.within(xf.rect)- - - {- - - ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair);- - - if resp.clicked() {- - - // Centred on the click at its natural size (the engine sizes it).- - - let (vx, vy) = xf.screen_to_view(p);- - - let u = info.pages[i].view_to_user(vx, vy);- - - let (x, y) = (u[0] as f64, u[1] as f64);- - - view.pending_edit = Some(pdfcraft_engine::Edit::AddCustomStamp {- - - page: i,- - - rect: [x, y, x, y],- - - name: cs.name.clone(),- - - file: pdfcraft_engine::MarkFile { name: cs.file.clone(), bytes: cs.data.clone(), page: cs.page },- - - author: author.clone(),- - - });- - - stamp_placed = true;- - - }- - - }- - - // Over a mark already placed, the Fill & Sign tool picks it up (comments, below).- - - if let QuickTool::Fill(ft) = tool- - - && allowed- - - && !comments::fill_grabs(&pcx, view)- - - {- - - match crate::fill_sign::page_input(- - - ui,- - - &resp,- - - &xf,- - - &ptr,- - - i,- - - info,- - - ft,- - - app.fill_text_size,- - - view,- - - signature.as_ref(),- - - initials.as_ref(),- - - &mut app.signature_preview,- - - &author,- - - &date_text,- - - ) {- - - Some(crate::fill_sign::FillAction::Edit(e)) => view.pending_edit = Some(*e),- - - Some(crate::fill_sign::FillAction::Signature(e)) => {- - - view.pending_edit = Some(*e);- - - view.fill_signature_page = Some(i);- - - }- - - Some(crate::fill_sign::FillAction::CreateSignature) => open_signature = true,- - - Some(crate::fill_sign::FillAction::CreateInitials) => open_initials = true,- - - Some(crate::fill_sign::FillAction::Refused(why)) => refused = Some(why),- - - None => {}- - - }- - - }- - - if matches!(tool, QuickTool::SignArea { .. }) {- - - crate::sign_ui::page_input(ui, &resp, &xf, &ptr, i, info, view);- - - }- - - if matches!(tool, QuickTool::MarqueeZoom | QuickTool::Snapshot) {- - - crate::zoom_snap::page_input(ui, &resp, &xf, &ptr, i, view);- - - }- - - if tool == QuickTool::EnhanceCamera {- - - crate::camera_ui::page_input(ui, &resp, &xf, &ptr, i, view, can_modify);- - - }- - - if tool == QuickTool::Crop && crate::crop::page_input(ui, &resp, &xf, &ptr, i, info, view, can_crop) {- - - view.current = i;- - - open_boxes = true;- - - }- - - // `over_field`: a form field is under the pointer and has set its cursor.- - - let (on_field, over_field) = if preparing {- - - let field_tool = match tool {- - - QuickTool::Field(f) => Some(f),- - - _ => None,- - - };- - - // While a table is being set up, nothing else is drawn or moved.- - - let allowed = can_modify && table_preview.is_none() && open_table.is_none();- - - let o = crate::prepare::page_input(ui, &resp, &xf, &ptr, i, info, &form, field_tool, allowed, view);- - - field_props |= o.properties;- - - field_placed |= o.placed;- - - open_table = open_table.or(o.table);- - - (o.consumed || field_tool.is_some(), false)- - - } else {- - - use crate::forms_ui::FieldPointer;- - - let field = if tool == QuickTool::Select- - - && !(editing_content && can_modify && crate::content_ui::select_grabs(&xf, &ptr, i, info, &added, view))- - - && !comments::select_grabs(&pcx, view)- - - {- - - crate::forms_ui::page_input(ui, &resp, &xf, &ptr, i, info, &form, can_fill, view)- - - } else {- - - FieldPointer::Away- - - };- - - (field == FieldPointer::Owned, field == FieldPointer::Over)- - - };- - - // Redact draws boxes off text; so does Highlight (an area highlight, as in Acrobat).- - - let area_tool = tool == QuickTool::Redact && can_modify || tool == QuickTool::Comment(comments::CommentTool::Highlight) && allowed;- - - let boxing = area_tool && {- - - let text = view.page_text(i);- - - let over_text = |p: Pos2| {- - - let (vx, vy) = xf.screen_to_view(p);- - - text.as_ref().is_some_and(|t| t.glyphs.iter().any(|g| vx >= g.rect[0] && vx <= g.rect[2] && vy >= g.rect[1] && vy <= g.rect[3]))- - - };- - - crate::redact_ui::page_input(ui, &resp, &xf, &ptr, i, info, over_text, view)- - - };- - - let image_owns_pointer = tool == QuickTool::EditText && crate::edit_text_ui::image_owns_pointer(ui, &xf, &ptr, i, info, view);- - - let on_objects =- - - !image_owns_pointer && tool == QuickTool::EditText && can_modify && crate::object_ui::page_input(ui, &resp, &xf, &ptr, i, doc, view);- - - let lines = if matches!(tool, QuickTool::AddText | QuickTool::EditText) && can_modify {- - - let generation = doc.edit_generation();- - - match view.edit_lines.get(&i) {- - - Some((g, l)) if *g == generation => l.clone(),- - - _ => {- - - let l = doc.text_blocks(i);- - - view.edit_lines.insert(i, (generation, l.clone()));- - - l- - - }- - - }- - - } else {- - - Vec::new()- - - };- - - let over_source = tool == QuickTool::AddText- - - && pointer.is_some_and(|p| {- - - !crate::content_ui::hits_added(&xf, info, i, &added, p)- - - && lines.iter().any(|line| xf.user_rect(info, i, line.rect.map(|v| v as f32)).expand(2.0).contains(p))- - - });- - - let source_blocked = over_source && view.content.hold_blocked();- - - if over_source && resp.clicked() && !source_blocked {- - - if let Some(edit) = view.content.finish_draft(&added) {- - - view.pending_edit = Some(edit);- - - }- - - view.content.selected = None;- - - }- - - let on_content = !on_objects && editing_content && can_modify && {- - - source_blocked- - - || crate::content_ui::page_input(- - - ui,- - - &resp,- - - &xf,- - - &ptr,- - - i,- - - info,- - - &added,- - - tool == QuickTool::AddText && !over_source,- - - matches!(tool, QuickTool::AddText | QuickTool::EditText),- - - &text_style,- - - view,- - - )- - - || tool == QuickTool::AddText && !over_source- - - };- - - // Added content owns its gesture; its source text must not queue a second edit.- - - // Edit text & images boxes every paragraph and image whenever the tool is on. Only the- - - // input waits while selected objects or added content own the pointer, or while page- - - // input is blocked (another tab, a dialog, the window unfocused): the boxes stay drawn- - - // instead of vanishing until the pointer comes back.- - - let others_own_pointer = on_objects || on_content;- - - let on_edit_text = (tool == QuickTool::EditText || over_source) && can_modify && {- - - let generation = doc.edit_generation();- - - let images = match view.edit_images.get(&i) {- - - Some((g, l)) if *g == generation => l.clone(),- - - _ => {- - - let l = doc.page_images(i);- - - view.edit_images.insert(i, (generation, l.clone()));- - - l- - - }- - - };- - - // Editable text takes precedence over background/overlapping artwork. Both- - - // inventories are painted every frame, even when text owns the pointer.- - - let text_used =- - - crate::edit_text_ui::page_input(ui, &resp, &xf, &ptr, i, doc, &lines, view, !others_own_pointer && !image_owns_pointer);- - - let image_used = crate::edit_text_ui::image_input(- - - ui,- - - &resp,- - - &xf,- - - &ptr,- - - i,- - - info,- - - &images,- - - view,- - - &mut image_action,- - - !others_own_pointer && (image_owns_pointer || !text_used),- - - );- - - !others_own_pointer && (text_used || image_used)- - - };- - - let on_link = tool == QuickTool::Link && can_modify && crate::link_ui::page_input(ui, &resp, &xf, &ptr, i, info, &doc_links, view);- - - if tool == QuickTool::Select- - - && resp.secondary_clicked()- - - && can_modify- - - && let Some(p) = pointer.filter(|p| xf.rect.contains(*p))- - - && let Some(l) = doc.links().iter().find(|l| l.page == i && crate::link_ui::screen_rect(&xf, info, i, l.rect).expand(2.0).contains(p))- - - {- - - view.links.context = Some((i, l.index));- - - }- - - let consumed = on_objects || on_edit_text || on_link || on_content || boxing || on_field || comments::page_input(ui, &resp, &pcx, view);- - -- - - let preview_target =- - - (matches!(tool, QuickTool::Select | QuickTool::Fill(_)) && !comments_hidden).then_some(view.comments.selected).flatten();- - - view.signature_drag.prepare(ui.ctx(), doc, preview_target, scale);- - - view.signature_drag.paint(painter, &pcx, &view.comments, view.pending_edit.as_ref());- - -- - - // Any press on the page ends Select All of the document: text read or not, any tool,- - - // on a link too.- - - // A press that lands on something drawn over the page (a menu, a dialog) is not one.- - - if view.all_text && pressed_page == Some(i) {- - - view.all_text = false;- - - }- - - // Text layer: find matches, selection, I-beam and drag-to-select.- - - let to_screen = |g: [f32; 4]| xf.view_rect(g);- - - if let Some(text) = view.texts.get(&i).cloned() {- - - if let Some(f) = &view.find {- - - for (k, (mp, range)) in f.matches.iter().enumerate() {- - - if *mp != i {- - - continue;- - - }- - - let current = f.current == Some(k);- - - for lr in text.line_rects(range.clone()) {- - - let fill = if current {- - - Color32::from_rgba_unmultiplied(255, 140, 0, 110)- - - } else {- - - Color32::from_rgba_unmultiplied(255, 214, 0, 90)- - - };- - - painter.rect_filled(to_screen(lr).expand(1.0), CornerRadius::same(2), fill);- - - }- - - }- - - }- - - if view.all_text {- - - for lr in text.line_rects(0..text.glyphs.len()) {- - - painter.rect_filled(to_screen(lr), CornerRadius::same(1), Color32::from_rgba_unmultiplied(0x3A, 0x7B, 0xF0, 70));- - - }- - - }- - - if let Some(sel) = view.selection.filter(|s| s.page == i) {- - - for lr in sel.rects(&text) {- - - painter.rect_filled(to_screen(lr), CornerRadius::same(1), Color32::from_rgba_unmultiplied(0x3A, 0x7B, 0xF0, 70));- - - }- - - // The rectangle being drawn, as Acrobat shows it while column-selecting.- - - if let Span::Column { rect } = sel.span- - - && resp.dragged()- - - {- - - let outline = Stroke::new(1.0, Color32::from_rgb(0x3A, 0x7B, 0xF0));- - - painter.rect_stroke(to_screen(rect), CornerRadius::ZERO, outline, egui::StrokeKind::Middle);- - - }- - - }- - - if selects_text- - - && !consumed- - - && let Some(p) = pointer.filter(|p| r.contains(*p))- - - {- - - let (vx, vy) = xf.screen_to_view(p);- - - let over_text = text.glyphs.iter().any(|g| vx >= g.rect[0] && vx <= g.rect[2] && vy >= g.rect[1] && vy <= g.rect[3]);- - - let over_link = info.links.iter().any(|l| l.page == i && xf.user_rect(info, i, l.rect).contains(p));- - - // Column select (#740): the Column select tool, or Alt (Option on macOS) held- - - // while a drag starts, as in Acrobat.- - - let column = tool == QuickTool::ColumnSelect || ui.input(|inp| inp.modifiers.alt);- - - // A link or a form field under the pointer keeps its own cursor: a check box- - - // drawn with a glyph, or set on printed text, shows the hand, not the I-beam.- - - // So do the mode bar and side panels over a page scrolled under them (#2755),- - - // unless a selection is being dragged there.- - - let cursor_free = !over_link && !over_field && (resp.contains_pointer() || resp.dragged());- - - if column && cursor_free {- - - ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair);- - - } else if over_text && cursor_free {- - - ui.ctx().set_cursor_icon(egui::CursorIcon::Text);- - - }- - - // The pages' press, kept when its release came in the same frame (#2100): it- - - // still starts multi-click selection.- - - let press_here = ptr.origin.is_some_and(|o| r.contains(o));- - - let pressed = ptr.pressed().is_some();- - - if pressed && press_here && !over_link {- - - let now = ui.input(|inp| inp.time);- - - // The same limits egui uses to count clicks on release.- - - let (max_delay, max_dist) = ui.ctx().options(|o| (o.input_options.max_double_click_delay, o.input_options.max_click_dist));- - - let is_consecutive =- - - now - view.last_press_time <= max_delay && view.last_press_pos.is_some_and(|pos| pos.distance(p) <= max_dist);- - - view.clicks = if is_consecutive { view.clicks.saturating_add(1) } else { 1 };- - - view.last_press_time = now;- - - view.last_press_pos = Some(p);- - -- - - // Multi-click highlights immediately on pointer press instead of release (#1024).- - - let clicks = if view.clicks > 2 && tool != QuickTool::Select { 1 } else { view.clicks };- - - if clicks >= 2 && over_text {- - - let span = text.nearest(vx, vy).and_then(|a| click_unit(&text, clicks, a));- - - if let Some((first, last)) = span {- - - view.selection = Some(Selection::run(i, first, last));- - - }- - - }- - - }- - - if resp.drag_started() && press_here && !over_link {- - - // A drag replaces the selection without passing through none, so a- - - // re-drag over text whose bar Copy closed would keep the bar hidden.- - - view.actions_dismissed = None;- - - view.selection_drag = true;- - - let origin = ptr.origin.unwrap_or(p);- - - let (ox, oy) = xf.screen_to_view(origin);- - - if view.clicks < 2 {- - - view.selection = if column {- - - Some(Selection { page: i, span: Span::Column { rect: [ox, oy, vx, vy] } })- - - } else {- - - text.nearest(ox, oy).map(|a| Selection::run(i, a, a))- - - };- - - }- - - }- - - let clicks = if view.clicks > 2 && tool != QuickTool::Select { 1 } else { view.clicks };- - - if resp.dragged()- - - && let Some(sel) = view.selection.as_mut().filter(|s| s.page == i)- - - {- - - match &mut sel.span {- - - // After a multi-click the drag extends by its unit (#1685), as in- - - // Acrobat and browsers: whole words or lines, always keeping the one- - - // clicked, which holds the anchor whichever way the drag went.- - - Span::Run { anchor, head } if clicks >= 2 => {- - - if let Some(h) = text.nearest(vx, vy)- - - && let Some((first, last)) = click_unit(&text, clicks, *anchor)- - - {- - - let (to_first, to_last) = click_unit(&text, clicks, h).unwrap_or((h, h));- - - (*anchor, *head) = if to_first < first { (last, to_first) } else { (first, to_last.max(last)) };- - - }- - - }- - - Span::Run { head, .. } => {- - - if let Some(h) = text.nearest(vx, vy) {- - - *head = h;- - - }- - - }- - - Span::Column { rect } => {- - - rect[2] = vx;- - - rect[3] = vy;- - - }- - - }- - - }- - - // A rectangle around no text selects nothing.- - - if resp.drag_stopped()- - - && view.selection.is_some_and(|s| s.page == i && matches!(s.span, Span::Column { .. }) && s.text(&text).is_empty())- - - {- - - view.selection = None;- - - }- - - // Quick clicks widen the selection: two a word, three the line, four the page.- - - // Release-based fallback for platforms or synthetic events that report double_clicked.- - - let release_clicks = if resp.triple_clicked() {- - - view.clicks.max(2).saturating_add(1)- - - } else if resp.double_clicked() {- - - view.clicks.max(2)- - - } else {- - - 0- - - };- - - if release_clicks > 0 {- - - view.clicks = release_clicks;- - - }- - - let clicks = if view.clicks > 2 && tool != QuickTool::Select { 1 } else { view.clicks };- - - // Only on the frame egui reports the multi-click: `view.clicks` outlives it, and- - - // acting on every frame re-selected the word as soon as a selection was cleared- - - // (a highlight made by the double-click left its word selected).- - - if release_clicks > 0 && clicks >= 2 && over_text {- - - if view.selection.is_none() {- - - let span = text.nearest(vx, vy).and_then(|a| click_unit(&text, clicks, a));- - - if let Some((first, last)) = span {- - - view.selection = Some(Selection::run(i, first, last));- - - }- - - }- - - } else if resp.clicked() && view.clicks < 2 && !over_link {- - - // ⇧-click extends a selection on this page to the click, keeping its- - - // anchor (#527). Otherwise (no shift, no selection on this page, or a- - - // column selection, which has no anchor glyph; a selection cannot yet- - - // span pages) a click clears the selection.- - - let shift = ui.input(|inp| inp.modifiers.shift);- - - match (view.selection.as_mut().filter(|s| shift && s.page == i).map(|s| &mut s.span), text.nearest(vx, vy)) {- - - (Some(Span::Run { head, .. }), Some(h)) => *head = h,- - - _ => view.selection = None,- - - }- - - }- - - }+ + + /// Everything drawn over the page after its text: pictures, comments, content, links, fields, marks+ + + /// and badges.+ + + fn page_overlays(ui: &mut egui::Ui, view: &mut DocView, frame: &mut PageFrame<'_>, slot: &PageSlot, input: &PageInput) {+ + + let PageEnv {+ + + added,+ + + allowed,+ + + calc_order,+ + + can_modify,+ + + comments_hidden,+ + + doc,+ + + doc_links,+ + + editing_content,+ + + form,+ + + generation,+ + + info,+ + + prefs,+ + + preparing,+ + + redact_mark,+ + + table_preview,+ + + tool,+ + + unobstructed,+ + + ..+ + + } = frame.env;+ + + let PageSlot { i, xf, .. } = *slot;+ + + let PageFrame { resp, ptr, pointer, .. } = *frame;+ + + let painter = ui.painter();+ + + let tool_cx = PageToolContext { ui, resp, xf: &xf, ptr, page: i, doc, info };+ + + let pcx = comments::PageCx { page: i, xf: &xf, ptr, info, tool, prefs, allowed, hidden: comments_hidden, redact_mark };+ + + if tool == QuickTool::Select && !input.consumed {+ + + crate::image_pick::page_input(resp, &xf, i, info, doc, pointer, view);+ + + }+ + + crate::image_pick::drop_stale(doc, view);+ + + crate::image_pick::paint(painter, &xf, i, info, view);----- --- ------- --- comments::page_after_text(resp, &pcx, view);----- --- ------- --- if tool == QuickTool::Redact && can_modify {----- --- ------- --- crate::redact_ui::after_text(resp, i, info, view);++++++ +++++++++++++++ // A cancelled press ends no selection: no markup or redaction is made from it.++++++ +++++++++++++++ if !view.press_cancelled {++++++ +++++++++++++++ comments::page_after_text(resp, &pcx, view);++++++ +++++++++++++++ if tool == QuickTool::Redact && can_modify {++++++ +++++++++++++++ crate::redact_ui::after_text(resp, i, info, view);++++++ +++++++++++++++ }+ + + }+ + + if input.area_tool {+ + + crate::redact_ui::paint(painter, i, view, pointer);+ + + }+ + + comments::paint_page(ui, painter, &pcx, view);+ + + if editing_content {+ + + crate::content_ui::paint_page(painter, &xf, i, info, added, view, pointer);+ + + }+ + + if tool == QuickTool::EditText {+ + + crate::object_ui::paint(painter, &xf, i, info, &view.objects);+ + + }+ + + if tool == QuickTool::EnhanceCamera {+ + + crate::camera_ui::paint(painter, &xf, i, view);+ + + }+ + + if tool == QuickTool::Link {+ + + crate::link_ui::paint(painter, &xf, i, info, doc_links, view, pointer);+ + + }+ + + if preparing {+ + + crate::prepare::paint_page(tool_cx, form, view);+ + + if let Some(preview) = &table_preview {+ + + crate::field_table_ui::paint_preview(painter, &xf, i, preview);+ + + }+ + + if calc_order {+ + + let selected = view.prepare.selected.as_ref().map(|(name, _)| name.as_str());+ + + if let Some(name) = crate::calc_order_ui::paint_page(tool_cx, form, &view.calc_order, generation, selected) {+ + + frame.calc_hover = Some(name);}+ + + }+ + + } else {+ + + crate::forms_ui::paint_page(painter, &xf, i, info, form, view, pointer);+ + + }- - - if tool == QuickTool::Select && !consumed {- - - crate::image_pick::page_input(&resp, &xf, i, info, doc, pointer, view);- - - }- - - crate::image_pick::drop_stale(doc, view);- - - crate::image_pick::paint(painter, &xf, i, info, view);- - - comments::page_after_text(&resp, &pcx, view);- - - if tool == QuickTool::Redact && can_modify {- - - crate::redact_ui::after_text(&resp, i, info, view);- - - }- - - if area_tool {- - - crate::redact_ui::paint(painter, i, view, pointer);- - - }- - - comments::paint_page(ui, painter, &pcx, view);- - - if editing_content {- - - crate::content_ui::paint_page(painter, &xf, i, info, &added, view, pointer);- - - }- - - if tool == QuickTool::EditText {- - - crate::object_ui::paint(painter, &xf, i, info, &view.objects);- - - }- - - if tool == QuickTool::EnhanceCamera {- - - crate::camera_ui::paint(painter, &xf, i, view);- - - }- - - if tool == QuickTool::Link {- - - crate::link_ui::paint(painter, &xf, i, info, &doc_links, view, pointer);- - - }- - - if preparing {- - - crate::prepare::paint_page(ui, painter, &xf, i, info, &form, view, pointer);- - - if let Some(preview) = &table_preview {- - - crate::field_table_ui::paint_preview(painter, &xf, i, preview);- - - }- - - if calc_order {- - - let selected = view.prepare.selected.as_ref().map(|(name, _)| name.as_str());- - - if let Some(name) =- - - crate::calc_order_ui::paint_page(painter, &xf, i, info, &form, &view.calc_order, generation, selected, pointer)- - - {- - - calc_hover = Some(name);- - - }- - - }+ + + // Form-field highlight (Acrobat's "Highlight existing fields"); required fields get a+ + + // red border. Radio buttons and round XFA check boxes are round, and so is theirs (as+ + + // in Acrobat). Only what can be filled is marked: a read-only widget (its field's, or a+ + + // radio button's own) is left as it is drawn.+ + + paint_field_highlights(painter, &xf, info, form.as_slice(), i, view.highlight_fields);- - - // Fill & Sign keeps its placement cursor clear of link/comment hover feedback. Tips- - - // draw above the palette, so none shows while it is open, even beside it.- - - if !matches!(tool, QuickTool::Fill(_))- - - && unobstructed- - - && let Some(p) = pointer+ + + + ++ // Links: the hand and the link's target, which count only for the tools that follow or+ + + + ++ // edit links (`Layer::reached_by`). Tips draw above the palette, so none shows while it is----- --- --- - - -- // open, even beside it.----- --- --- - - -- if unobstructed && let Some(p) = pointer {----- --- --- - - -- for l in info.links.iter().filter(|l| l.page == i) {----- --- --- - - -- let sr = xf.user_rect(info, i, l.rect);----- --- --- - - -- if sr.contains(p) {----- --- --- - - -- let label = match &l.target {----- --- --- - - -- LinkTarget::Page(n, _) => {----- --- --- - - -- crate::i18n::fmt(tl!("Go to page {p}"), &[("p", info.pages.get(*n).map(|p| p.label.as_str()).unwrap_or("?"))])----- --- --- - - -- }----- --- --- - - -- LinkTarget::Uri(u) => u.clone(),----- --- --- - - -- LinkTarget::SetLayers { .. } => tl!("Set layer visibility").to_string(),----- --- --- - - -- LinkTarget::RemoteGoTo { file, .. } => file.clone(),----- --- --- - - -- LinkTarget::Other(s) => crate::i18n::fmt(tl!("{s} action"), &[("s", s)]),----- --- --- - - -- };----- --- --- - - -- view.cursor.claim_with_tip(Layer::Link, egui::CursorIcon::PointingHand, Some(label));----- --- --- - - -- if resp.clicked() && tool == QuickTool::Select && !input.consumed {----- --- --- - - -- frame.out.clicked_link = Some(l.target.clone());----- --- --- - - -- }----- --- --- - - -- }----- --- --- - - -- }++++++ +++++++++++++++ // open, even beside it. A click follows the link its press was on, released over it: one that++++++ +++++++++++++++ // slips off the link first follows nothing, as a button's does.++++++ +++++++++++++++ if unobstructed++++++ +++++++++++++++ && resp.clicked()++++++ +++++++++++++++ && tool == QuickTool::Select++++++ +++++++++++++++ && !input.consumed++++++ +++++++++++++++ && let Some(owner @ crate::page_router::Owner::Link { index }) = view.router.owner(i)++++++ +++++++++++++++ && pointer.and_then(|p| link_hit(info, &xf, i, p)).is_some_and(|h| h.owner == owner)++++++ +++++++++++++++ && let Some(l) = info.links.get(index)++++++ +++++++ + ++ ++ {- - - for l in info.links.iter().filter(|l| l.page == i) {- - - let sr = xf.user_rect(info, i, l.rect);- - - if sr.contains(p) {- - - ui.ctx().set_cursor_icon(egui::CursorIcon::PointingHand);- - - let label = match &l.target {- - - LinkTarget::Page(n, _) => {- - - crate::i18n::fmt(tl!("Go to page {p}"), &[("p", info.pages.get(*n).map(|p| p.label.as_str()).unwrap_or("?"))])- - - }- - - LinkTarget::Uri(u) => u.clone(),- - - LinkTarget::SetLayers { .. } => tl!("Set layer visibility").to_string(),- - - LinkTarget::RemoteGoTo { file, .. } => file.clone(),- - - LinkTarget::Other(s) => crate::i18n::fmt(tl!("{s} action"), &[("s", s)]),- - - };- - - frame.out.hover_text = Some((p, label));- - - if resp.clicked() && tool == QuickTool::Select && !input.consumed {- - - frame.out.clicked_link = Some(l.target.clone());- - - }- - - }- - - }- - - // Annotation hover shows the comment, as Acrobat's popups do; not while drawing- - - // freehand, where it would cover the next stroke (#429).- - - let freehand = matches!(tool, QuickTool::Comment(comments::CommentTool::Ink | comments::CommentTool::Eraser));- - - let gesturing = view.comments.gesture.is_some() || freehand;- - - // Inspection sorts annotations spatially, but the renderer paints in /Annots- - - // order. Keep the shared list intact and choose the last eligible raw index.- - - if frame.out.hover_text.is_none()- - - && !gesturing- - - && let Some((_, text)) = info- - - .annotations- - - .iter()- - - .filter(|a| a.page == i)- - - .filter(|a| !(prefs.hide_empty_highlight_hover && a.subtype == "Highlight" && a.contents.as_deref().is_none_or(str::is_empty)))- - - .filter(|a| pcx.screen_rects(a).any(|r| r.contains(p)))- - - .filter_map(|a| annotation_hover_text(a).map(|text| (a.index, text)))- - - .max_by_key(|(index, _)| *index)- - - {- - - frame.out.hover_text = Some((p, text));- - - }++++++ +++++++++++++++ frame.out.clicked_link = Some(l.target.clone());+ + + }+ + + + ++ // Comments say what they are with any tool, beside its cursor, as Acrobat's do.+ + + + ++ comments::describe(&pcx, view);+ + + for (mp, mr, mc) in &view.compare_marks {+ + + if *mp == i {+ + + let sr = xf.user_rect(info, i, *mr).expand(1.5);+ + + painter.rect_filled(sr, CornerRadius::same(2), mc.gamma_multiply(0.28));+ + + }+ + + }+ + + if let Some((fp, fr, t0)) = view.flash+ + + && fp == i+ + + {+ + + let now = ui.input(|inp| inp.time);+ + + let t0 = if t0 == 0.0 { now } else { t0 };+ + + view.flash = Some((fp, fr, t0));+ + + let age = (now - t0) as f32;+ + + if age < 1.6 {+ + + let a = ((1.6 - age) / 1.6 * 255.0) as u8;+ + + let sr = xf.user_rect(info, i, fr).expand(4.0);+ + + painter.rect_stroke(+ + + sr,+ + + CornerRadius::same(3),+ + + Stroke::new(2.5, Color32::from_rgba_unmultiplied(0x1B, 0x63, 0xE0, a)),+ + + egui::StrokeKind::Outside,+ + + );+ + + ui.ctx().request_repaint();+ + + } else {+ + + view.flash = None;+ + + }+ + + }+ + + // Validation is viewer chrome over the signer's original artwork, which+ + + // may still say "Signature Not Verified". These badges never enter document+ + + // streams, image/text exports, vector printing or Print as Image.+ + + for badge in signature_badges(&doc.signatures, i) {+ + + let [x0, y0, x1, y1] = badge.rect;+ + + let sr = xf.user_rect(info, i, [x0 as f32, y0 as f32, x1 as f32, y1 as f32]);+ + + let (icon, color) = crate::sign_ui::signature_status_style(badge.status);+ + + painter.rect_stroke(sr, CornerRadius::same(2), Stroke::new(1.5, color), egui::StrokeKind::Outside);+ + + // A widget too small for the mark keeps its outline: the verdict still shows.+ + + if sr.width() < 4.0 || sr.height() < 4.0 {+ + + continue;+ + + }+ + + // Big enough to read at a glance, small enough to leave the signer's own+ + + // text visible around it.+ + + let side = (sr.width().min(sr.height()) * 0.8).clamp(24.0, 192.0);+ + + let mark = Rect::from_center_size(sr.center(), vec2(side, side));+ + + icons::paint(ui, mark, icon, side * 0.64, color);- - - if let Some(p) = pointer.filter(|p| mark.expand(2.0).contains(*p)) {- - - frame.out.badge_hover = Some((p, badge.summary.to_string()));+ + + + ++ // Overlapping widgets paint in order, so the topmost badge's verdict is the tip, with+ + + + ++ // any tool; a link's or a comment's tip wins over any badge.+ + + + ++ if pointer.is_some_and(|p| mark.expand(2.0).contains(p)) {+ + + + ++ view.cursor.describe(Subject::SignatureBadge, badge.summary.to_string());+ + + }+ + + }- - - // Overlapping widgets paint in order, so the topmost badge owns the hover; an- - - // earlier link or annotation hover still wins over any badge.- - - if frame.out.hover_text.is_none() {- - - frame.out.hover_text = frame.out.badge_hover.take();- - - }+ + + }+ + ++ + + fn paint_field_highlights(painter: &egui::Painter, xf: &PageXform, info: &DocInfo, form: &[pdfcraft_engine::FormField], page: usize, enabled: bool) {+ + + if !enabled {+ + + return;+ + + }+ + + for field in form.iter() {+ + + let required = field.has(pdfcraft_engine::field_flags::REQUIRED);+ + + for widget in field.widgets.iter().filter(|widget| widget.page == Some(page) && !widget.hidden && !widget.read_only) {+ + + let rect = widget.rect;+ + + let screen_rect = xf.user_rect(info, page, [rect[0] as f32, rect[1] as f32, rect[2] as f32, rect[3] as f32]);+ + + let tint = Color32::from_rgba_unmultiplied(0x6E, 0x8E, 0xF5, 48);+ + + let (width, color) = if required { (2.0, Color32::from_rgb(0xE3, 0x22, 0x22)) } else { (1.0, Color32::from_rgb(0x6E, 0x8E, 0xF5)) };+ + + if widget.round {+ + + let radius = screen_rect.width().min(screen_rect.height()) / 2.0;+ + + painter.circle_filled(screen_rect.center(), radius, tint);+ + + painter.circle_stroke(screen_rect.center(), radius - width / 2.0, Stroke::new(width, color));} else {- - - crate::forms_ui::paint_page(painter, &xf, i, info, &form, view, pointer);+ + + painter.rect_filled(screen_rect, CornerRadius::same(1), tint);+ + + painter.rect_stroke(screen_rect, CornerRadius::same(1), Stroke::new(width, color), egui::StrokeKind::Inside);}+ + + }+ + + }+ + + }+ + ++ + + fn draw_page(ui: &mut egui::Ui, view: &mut DocView, frame: &mut PageFrame<'_>, i: usize) {+ + + let PageEnv { allowed, comments_hidden, doc, editing_content, info, ppp, prefs, rects, redact_mark, scale, t, tool, .. } = frame.env;+ + + let PageFrame { ptr, origin, visible, pressed, pointer, .. } = *frame;- - - frame.out.badge_hover = None;+ + + let r = snap_to_pixels(rects[i].translate(origin.to_vec2()), ppp);+ + + if !r.intersects(visible.expand(400.0)) {+ + + return;+ + + }+ + + if pressed && frame.pressed_page.is_none() && pointer.is_some_and(|p| r.contains(p)) {+ + + frame.pressed_page = Some(i);+ + + }+ + + if r.intersects(visible) {+ + + frame.visible_now.push(i);+ + + view.screen_rects.push((i, r));+ + + view.screen_xforms.push((i, PageXform { rect: r, rot: view.rotation, pw: info.pages[i].width.max(1.0), ph: info.pages[i].height.max(1.0) }));+ + + }+ + + let overlap = r.intersect(visible).height();+ + + if i == view.current {+ + + frame.current_overlap = overlap;+ + + frame.current_height = r.height();+ + + }+ + + // Pages shown equally (two rows wholly on screen) differ only by rounding: the+ + + // topmost one counts.+ + + if overlap > frame.best_overlap + PAGE_TIE {+ + + frame.best_overlap = overlap;+ + + frame.current = i;+ + + }+ + + let xf = PageXform { rect: r, rot: view.rotation, pw: info.pages[i].width.max(1.0), ph: info.pages[i].height.max(1.0) };+ + + paint_page_surface(ui, view, frame, &PageSlot { i, r, xf });+ + + let painter = ui.painter();+ + + view.text_background.paint(painter, &xf, i, view.line_editor.as_ref(), view.content.draft.as_ref());+ + + if editing_content {+ + + view.move_background.paint(painter, &xf, i, info, &view.content, pointer);+ + + }+ + + if view.show_page_gaps {+ + + painter.rect_stroke(r, CornerRadius::ZERO, Stroke::new(0.5, t.border.gamma_multiply(0.8)), egui::StrokeKind::Outside);+ + + }+ + ++ + + let slot = PageSlot { i, r, xf };----- --- ------- --- let input = page_tool_input(ui, view, frame, &slot);++++++ +++++++++++++++ // A cancelled press takes nothing until the button is up.++++++ +++++++++++++++ let input = if view.press_cancelled { PageInput { consumed: true, area_tool: false } } else { page_tool_input(ui, view, frame, &slot) };+ + + let painter = ui.painter();+ + + let pcx = comments::PageCx { page: i, xf: &xf, ptr, info, tool, prefs, allowed, hidden: comments_hidden, redact_mark };+ + + let preview_target = (matches!(tool, QuickTool::Select | QuickTool::Fill(_)) && !comments_hidden).then_some(view.comments.selected).flatten();+ + + view.signature_drag.prepare(ui.ctx(), doc, preview_target, scale);+ + + view.signature_drag.paint(painter, &pcx, &view.comments, view.pending_edit.as_ref());++++++++ +++++++++++++ // Any other comment being moved: drawn where it goes, over the page that still shows it++++++++ +++++++++++++ // where it was.++++++++ +++++++++++++ let stale = view.signature_drag.moving_page().is_some_and(|p| view.page_out_of_date(p));++++++++ +++++++++++++ view.signature_drag.prepare_move(ui.ctx(), doc, &view.comments, view.pending_edit.as_ref(), stale, scale);++++++++ +++++++++++++ view.signature_drag.paint_move(painter, &pcx, &view.comments, view.pending_edit.as_ref());+ + ++ + + // Any press on the page ends Select All of the document: text read or not, any tool,+ + + // on a link too.+ + + // A press that lands on something drawn over the page (a menu, a dialog) is not one.+ + + if view.all_text && frame.pressed_page == Some(i) {+ + + view.all_text = false;+ + + }+ + + text_layer(ui, view, frame, &slot, &input);+ + + page_overlays(ui, view, frame, &slot, &input);+ + + }+ + +++++++ +++++++++++++++/// The link under `p` on `page`: the hand, and where a click goes. Only the Select tool follows++++++ +++++++++++++++/// links and the Link tool edits them (`Layer::reached_by`).++++++ +++++++++++++++fn link_hit(info: &DocInfo, xf: &PageXform, page: usize, p: Pos2) -> Option<crate::page_router::Hit> {++++++ +++++++++++++++ let (index, l) = info.links.iter().enumerate().rfind(|(_, l)| l.page == page && xf.user_rect(info, page, l.rect).contains(p))?;++++++ +++++++++++++++ let label = match &l.target {++++++ +++++++++++++++ LinkTarget::Page(n, _) => crate::i18n::fmt(tl!("Go to page {p}"), &[("p", info.pages.get(*n).map(|p| p.label.as_str()).unwrap_or("?"))]),++++++ +++++++++++++++ LinkTarget::Uri(u) => u.clone(),++++++ +++++++++++++++ LinkTarget::SetLayers { .. } => tl!("Set layer visibility").to_string(),++++++ +++++++++++++++ LinkTarget::RemoteGoTo { file, .. } => file.clone(),++++++ +++++++++++++++ LinkTarget::Other(s) => crate::i18n::fmt(tl!("{s} action"), &[("s", s)]),++++++ +++++++++++++++ };++++++ +++++++++++++++ let owner = crate::page_router::Owner::Link { index };++++++ +++++++++++++++ Some(crate::page_router::Hit { tip: Some(label), ..crate::page_router::Hit::new(owner, Layer::Link, egui::CursorIcon::PointingHand) })++++++ +++++++++++++++}++++++ +++++++++++++++++++++ +++++++++++++++/// Escape while the pages hold a press abandons the gesture it drives, whichever tool's: nothing is++++++ +++++++++++++++/// placed, drawn, moved, resized or opened, and the press is ignored until the button is up. The++++++ +++++++++++++++/// frame of the release still belongs to the cancelled press.++++++ +++++++++++++++fn cancel_on_escape(ctx: &egui::Context, view: &mut DocView, ptr: &PagePointer) {++++++ +++++++++++++++ // Over once the button is up and its release seen, or when a new press comes (its release and++++++ +++++++++++++++ // the next press can share a frame).++++++ +++++++++++++++ let new_press = matches!(ptr.edges.last(), Some(crate::page_pointer::Edge::Press(_)));++++++ +++++++++++++++ if view.press_cancelled && (new_press || !ptr.any_down && ptr.edges.is_empty()) {++++++ +++++++++++++++ view.press_cancelled = false;++++++ +++++++++++++++ }++++++ +++++++++++++++ if !view.press_cancelled && ptr.origin.is_some() && ptr.primary_down && ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape))++++++ +++++++++++++++ {++++++ +++++++++++++++ // A text selection being dragged goes with its drag: the markup, redaction or Replace++++++ +++++++++++++++ // Text that its end would make is not made.++++++ +++++++++++++++ if view.selection_drag {++++++ +++++++++++++++ view.clear_selection();++++++ +++++++++++++++ }++++++ +++++++++++++++ view.cancel_pointer_gestures();++++++ +++++++++++++++ view.press_cancelled = true;++++++ +++++++++++++++ }++++++ +++++++++++++++}+++++ +++ +++++++ +++- - - // Form-field highlight (Acrobat's "Highlight existing fields"); required fields get a- - - // red border. Radio buttons and round XFA check boxes are round, and so is theirs (as- - - // in Acrobat). Only what can be filled is marked: a read-only widget (its field's, or a- - - // radio button's own) is left as it is drawn.- - - if view.highlight_fields {- - - for f in form.iter() {- - - let required = f.has(pdfcraft_engine::field_flags::REQUIRED);- - - for w in f.widgets.iter().filter(|w| w.page == Some(i) && !w.hidden && !w.read_only) {- - - let r = w.rect;- - - let sr = xf.user_rect(info, i, [r[0] as f32, r[1] as f32, r[2] as f32, r[3] as f32]);- - - let tint = Color32::from_rgba_unmultiplied(0x6E, 0x8E, 0xF5, 48);- - - let (width, color) =- - - if required { (2.0, Color32::from_rgb(0xE3, 0x22, 0x22)) } else { (1.0, Color32::from_rgb(0x6E, 0x8E, 0xF5)) };- - - if w.round {- - - let radius = sr.width().min(sr.height()) / 2.0;- - - painter.circle_filled(sr.center(), radius, tint);- - - painter.circle_stroke(sr.center(), radius - width / 2.0, Stroke::new(width, color));- - - } else {- - - painter.rect_filled(sr, CornerRadius::same(1), tint);- - - painter.rect_stroke(sr, CornerRadius::same(1), Stroke::new(width, color), egui::StrokeKind::Inside);- - - }+ + + fn draw_pages(+ + + ui: &mut egui::Ui,+ + + viewport: Rect,+ + + view: &mut DocView,+ + + env: &PageEnv<'_>,+ + + out: &mut PageOut,+ + + signature_preview: &mut Option<(crate::fill_sign::SavedSig, egui::TextureHandle)>,+ + + ) -> PageRenders {+ + + let PageEnv {+ + + allowed,+ + + auto_delta,+ + + avail,+ + + boost_extra,+ + + calc_order,+ + + can_copy,+ + + can_modify,+ + + content_h,+ + + content_w,+ + + doc,+ + + edge_delta,+ + + form,+ + + generation,+ + + glide,+ + + hand,+ + + info,+ + + key_scroll,+ + + middle_gesture,+ + + modal,+ + + navigation_enabled,+ + + precise_scroll,+ + + prefs,+ + + preparing,+ + + selection_wheel,+ + + single_paging,+ + + + ++ tool,+ + + unobstructed,+ + + visible_pages,+ + + y_shift,+ + + ..+ + + } = *env;+ + + // egui's drag responses accept every pointer button. Keep a wheel gesture from also+ + + // selecting text, drawing a mark, or panning with the Hand tool.+ + + if middle_gesture {+ + + let opacity = ui.opacity();+ + + ui.disable();+ + + // Only interactions pause; the document must keep its original colours.+ + + ui.set_opacity(opacity);+ + + }+ + + // Middle-button auto-scroll, the keyboard, precise touchpad input (#759) and its glide+ + + // (#531), accelerated wheel surplus (#1072), and a drawing's edge scroll; positive y+ + + // moves the content down. All scroll without easing, unlike egui's wheel default.+ + + // ScrollArea ignores wheel input during a widget drag. Defer the wheel contribution+ + + // until after the text widgets when a selection owns that drag.+ + + let wheel_delta = if selection_wheel { Vec2::ZERO } else { precise_scroll + boost_extra };+ + + let delta = auto_delta + edge_delta - vec2(0.0, key_scroll) + wheel_delta + glide;+ + + if delta != Vec2::ZERO && delta.is_finite() {+ + + ui.scroll_with_delta_animation(delta, egui::style::ScrollAnimation::none());+ + + }+ + + let (resp_rect, resp) = ui.allocate_exact_size(vec2(content_w, content_h), Sense::click_and_drag());+ + + view.page_widget = Some(resp.id);+ + + // A drag lasts only while egui reports it, so the mark can't outlive one.+ + + if !resp.dragged_by(egui::PointerButton::Primary) {+ + + view.selection_drag = false;+ + + }+ + + // The Hand tool pans by this widget's drag, before the pages are laid out (above).+ + + if hand {+ + + if resp.dragged() {- - - ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing);+ + + + ++ view.cursor.claim(Layer::Drag, egui::CursorIcon::Grabbing);+ + + } else if resp.hovered() {- - - ui.ctx().set_cursor_icon(egui::CursorIcon::Grab);+ + + + ++ view.cursor.claim(Layer::ToolArea, egui::CursorIcon::Grab);+ + + }+ + + }+ + + let origin = resp_rect.min - vec2(0.0, y_shift);+ + + let visible = viewport.translate(resp_rect.min.to_vec2());+ + + view.screen_rects.clear();+ + + view.screen_xforms.clear();+ + + // The pointer as the pages see it: nothing over them (a dialog from the frame it opens),+ + + // or a press they hold. The page modules read it rather than egui's raw pointer state.+ + + let ptr = PagePointer::read(ui, &resp, modal);++++++ +++++++++++++++ cancel_on_escape(ui.ctx(), view, &ptr);++++++ +++++++++++++++ view.router.settle(ptr.any_down, !ptr.edges.is_empty());++++++ +++++++++++++++ // A new press is no longer the last one's, wherever it lands (the page it is on gives it++++++ +++++++++++++++ // its owner; in the gap between pages it has none).++++++ +++++++++++++++ if ptr.pressed().is_some() {++++++ +++++++++++++++ view.router.cancel();++++++ +++++++++++++++ }+ + + let pointer = ptr.pos;+ + + // A press on a page makes it the current one (as in Acrobat), so a page command with+ + + // no selection (Rotate, Delete) acts on the page the reader pointed at, not on a page+ + + // gone to earlier that still shows whole beside it.+ + + let pressed = unobstructed && ptr.pressed().is_some();+ + + if resp.secondary_clicked() {+ + + // Set again below when the right-click lands on a link.+ + + view.links.context = None;+ + + }+ + + let mut frame = PageFrame {+ + + env: *env,+ + + resp: &resp,+ + + ptr: &ptr,+ + + origin,+ + + visible,+ + + pressed,+ + + pointer,+ + + signature_preview,+ + + out: std::mem::take(out),+ + + wanted: Vec::new(),+ + + visible_now: Vec::new(),+ + + current: view.current,+ + + best_overlap: -1.0,+ + + current_overlap: -1.0,+ + + current_height: f32::INFINITY,+ + + pressed_page: None,+ + + calc_hover: None,+ + + };+ + + for &i in visible_pages {+ + + draw_page(ui, view, &mut frame, i);+ + + }+ + + let PageFrame {+ + + wanted, visible_now, mut current, best_overlap, current_overlap, current_height, pressed_page, calc_hover, out: page_out, ..+ + + } = frame;+ + + let PageOut {- - - badge_hover,+ + + mut canvas_action,+ + + clicked_link,+ + + mut copy_selected,+ + + mut field_menu,+ + + field_placed,+ + + field_props,- - - hover_text,+ + + + ++ hover_text: _,+ + + image_action,+ + + open_boxes,+ + + open_initials,+ + + open_signature,+ + + open_table,+ + + primary_down: _,+ + + refused,+ + + stamp_placed,+ + + } = page_out;+ + + let painter = ui.painter();+ + + if calc_order {+ + + view.calc_order.set_hover_page(calc_hover);+ + + let selected = view.prepare.selected.as_ref().map(|(name, _)| name.as_str());+ + + crate::calc_order_ui::paint_trace(ui, painter, visible, &view.calc_order, generation, selected);+ + + }+ + + + ++ // The pages' one cursor, from the claim on the highest layer the tool reaches, and the tip.+ + + + ++ let hover_text = pointer.filter(|_| unobstructed).zip(view.cursor.resolve(ui.ctx(), tool));+ + + // ScrollArea ignores the wheel while any widget is dragged, so a text-selection drag+ + + // scrolls the page itself (#721). After the page loop, so it keeps scrolling once the+ + + // pointer leaves the selection's page for the gap or the next page; over the whole+ + + // document area, like #759. Combine direct and smoothed motion in one request so mixed+ + + // Point and Line events retain their full contribution.+ + + if selection_wheel {+ + + let smooth = if view.precise_scroll_until == 0.0 { ui.input_mut(|input| std::mem::take(&mut input.smooth_scroll_delta)) } else { Vec2::ZERO };+ + + let delta = precise_scroll + boost_extra + smooth;+ + + if delta != Vec2::ZERO && delta.is_finite() {+ + + ui.scroll_with_delta_animation(delta, egui::style::ScrollAnimation::none());+ + + }+ + + }+ + + // Held at the top or bottom edge, or dragged past it, a text selection scrolls the view+ + + // so it can reach text off screen (#1670); the selection follows the pointer on its page.+ + + if view.selection_drag+ + + && navigation_enabled+ + + && unobstructed+ + + && !single_paging+ + + && let Some(p) = ptr.pos+ + + {+ + + let dy = crate::autoscroll::edge_delta(p.y, avail, ui.input(|i| i.stable_dt));+ + + if dy != 0.0 {+ + + view.end_find_following();+ + + ui.scroll_with_delta_animation(vec2(0.0, dy), egui::style::ScrollAnimation::none());+ + + // Keep scrolling while the pointer rests there and sends no events.+ + + ui.ctx().request_repaint();+ + + }+ + + }+ + + // The page navigated to stays current while no page shows more of itself, so the next+ + + // page step starts from it rather than from a page further down the screen (#188).+ + + // It also stays current while it is wholly on screen: a short page (a cheque) gone to+ + + // from the Pages panel shows less of itself than the tall page below it, and must not+ + + // hand the highlight to that page.+ + + if current_overlap >= best_overlap - PAGE_TIE || current_overlap >= current_height - PAGE_TIE {+ + + current = view.current;+ + + }+ + + if let Some(p) = pressed_page {+ + + current = p;+ + + }+ + + if view.continuous {+ + + view.current = current;+ + + }+ + + resp.context_menu(|ui| {+ + + // Preparing a form: the selected field's menu.+ + + if preparing && let Some((name, wi)) = view.prepare.selected.clone() {+ + + // Several fields: Align, Center, Distribute, Set Fields to Same Size.+ + + if !view.prepare.also.is_empty() {+ + + use crate::prepare::Arrange as A;+ + + let others = view.prepare.also.clone();+ + + let anchor = (name.clone(), wi);+ + + let mut pick = |ui: &mut egui::Ui, op: A, label: &str| {+ + + if ui.add_enabled(can_modify, egui::Button::new(tl!(label))).clicked() {+ + + view.pending_edit = crate::prepare::arrange(form, &anchor, &others, op);+ + + ui.close();}- - - }+ + + };+ + + ui.menu_button(tl!("Align"), |ui| {+ + + pick(ui, A::AlignLeft, "Left");+ + + pick(ui, A::AlignRight, "Right");+ + + pick(ui, A::AlignTop, "Top");+ + + pick(ui, A::AlignBottom, "Bottom");+ + + pick(ui, A::AlignCenterV, "Center vertically");+ + + pick(ui, A::AlignCenterH, "Center horizontally");+ + + });+ + + ui.menu_button(tl!("Distribute"), |ui| {+ + + pick(ui, A::DistributeH, "Horizontally");+ + + pick(ui, A::DistributeV, "Vertically");+ + + });+ + + ui.menu_button(tl!("Set Fields to Same Size"), |ui| {+ + + pick(ui, A::SameHeight, "Height");+ + + pick(ui, A::SameWidth, "Width");+ + + pick(ui, A::SameSize, "Both");+ + + });+ + + ui.separator();}- - - // Fill & Sign keeps its placement cursor clear of link/comment hover feedback. Tips- - - // draw above the palette, so none shows while it is open, even beside it.- - - if !matches!(tool, QuickTool::Fill(_))- - - && unobstructed- - - && let Some(p) = pointer- - - {- - - for l in info.links.iter().filter(|l| l.page == i) {- - - let sr = xf.user_rect(info, i, l.rect);- - - if sr.contains(p) {- - - ui.ctx().set_cursor_icon(egui::CursorIcon::PointingHand);- - - let label = match &l.target {- - - LinkTarget::Page(n, _) => {- - - crate::i18n::fmt(tl!("Go to page {p}"), &[("p", info.pages.get(*n).map(|p| p.label.as_str()).unwrap_or("?"))])- - - }- - - LinkTarget::Uri(u) => u.clone(),- - - LinkTarget::SetLayers { .. } => tl!("Set layer visibility").to_string(),- - - LinkTarget::RemoteGoTo { file, .. } => file.clone(),- - - LinkTarget::Other(s) => crate::i18n::fmt(tl!("{s} action"), &[("s", s)]),- - - };- - - hover_text = Some((p, label));- - - if resp.clicked() && tool == QuickTool::Select && !consumed {- - - clicked_link = Some(l.target.clone());- - - }- - - }- - - }- - - // Annotation hover shows the comment, as Acrobat's popups do; not while drawing- - - // freehand, where it would cover the next stroke (#429).- - - let freehand = matches!(tool, QuickTool::Comment(comments::CommentTool::Ink | comments::CommentTool::Eraser));- - - let gesturing = view.comments.gesture.is_some() || freehand;- - - // Inspection sorts annotations spatially, but the renderer paints in /Annots- - - // order. Keep the shared list intact and choose the last eligible raw index.- - - if hover_text.is_none()- - - && !gesturing- - - && let Some((_, text)) = info- - - .annotations- - - .iter()- - - .filter(|a| a.page == i)- - - .filter(|a| {- - - !(prefs.hide_empty_highlight_hover && a.subtype == "Highlight" && a.contents.as_deref().is_none_or(str::is_empty))- - - })- - - .filter(|a| pcx.screen_rects(a).any(|r| r.contains(p)))- - - .filter_map(|a| annotation_hover_text(a).map(|text| (a.index, text)))- - - .max_by_key(|(index, _)| *index)- - - {- - - hover_text = Some((p, text));- - - }+ + + if ui.button(tl!("Properties…")).clicked() {+ + + field_menu = Some(FieldMenu::Properties);+ + + ui.close();}- - - for (mp, mr, mc) in &view.compare_marks {- - - if *mp == i {- - - let sr = xf.user_rect(info, i, *mr).expand(1.5);- - - painter.rect_filled(sr, CornerRadius::same(2), mc.gamma_multiply(0.28));- - - }+ + + if ui.add_enabled(can_modify, egui::Button::new(tl!("Duplicate…"))).clicked() {+ + + field_menu = Some(FieldMenu::Duplicate(name.clone()));+ + + ui.close();}- - - if let Some((fp, fr, t0)) = view.flash- - - && fp == i- - - {- - - let now = ui.input(|inp| inp.time);- - - let t0 = if t0 == 0.0 { now } else { t0 };- - - view.flash = Some((fp, fr, t0));- - - let age = (now - t0) as f32;- - - if age < 1.6 {- - - let a = ((1.6 - age) / 1.6 * 255.0) as u8;- - - let sr = xf.user_rect(info, i, fr).expand(4.0);- - - painter.rect_stroke(- - - sr,- - - CornerRadius::same(3),- - - Stroke::new(2.5, Color32::from_rgba_unmultiplied(0x1B, 0x63, 0xE0, a)),- - - egui::StrokeKind::Outside,- - - );- - - ui.ctx().request_repaint();- - - } else {- - - view.flash = None;- - - }+ + + ui.separator();+ + + let delete = if view.prepare.also.is_empty() { "Delete" } else { "Delete selected fields" };+ + + if ui.add_enabled(can_modify, egui::Button::new(tl!(delete))).clicked() {+ + + view.pending_edit = crate::prepare::delete_selected(view);+ + + ui.close();}- - - // Validation is viewer chrome over the signer's original artwork, which- - - // may still say "Signature Not Verified". These badges never enter document- - - // streams, image/text exports, vector printing or Print as Image.- - - for badge in signature_badges(&doc.signatures, i) {- - - let [x0, y0, x1, y1] = badge.rect;- - - let sr = xf.user_rect(info, i, [x0 as f32, y0 as f32, x1 as f32, y1 as f32]);- - - let (icon, color) = crate::sign_ui::signature_status_style(badge.status);- - - painter.rect_stroke(sr, CornerRadius::same(2), Stroke::new(1.5, color), egui::StrokeKind::Outside);- - - // A widget too small for the mark keeps its outline: the verdict still shows.- - - if sr.width() < 4.0 || sr.height() < 4.0 {- - - continue;- - - }- - - // Big enough to read at a glance, small enough to leave the signer's own- - - // text visible around it.- - - let side = (sr.width().min(sr.height()) * 0.8).clamp(24.0, 192.0);- - - let mark = Rect::from_center_size(sr.center(), vec2(side, side));- - - icons::paint(ui, mark, icon, side * 0.64, color);- - - if let Some(p) = pointer.filter(|p| mark.expand(2.0).contains(*p)) {- - - badge_hover = Some((p, badge.summary.to_string()));- - - }+ + + return;+ + + }+ + + if let Some((page, index)) = view.links.context {+ + + if ui.button(tl!("Properties…")).clicked() {+ + + view.links.open_existing = Some((page, index));+ + + ui.close();}- - - // Overlapping widgets paint in order, so the topmost badge owns the hover; an- - - // earlier link or annotation hover still wins over any badge.- - - if hover_text.is_none() {- - - hover_text = badge_hover.take();+ + + if ui.add_enabled(can_modify, egui::Button::new(tl!("Delete"))).clicked() {+ + + view.pending_edit = Some(Edit::DeleteLink { page, index });+ + + view.links.selected = None;+ + + view.links.context = None;+ + + ui.close();}- - - }- - - if calc_order {- - - view.calc_order.set_hover_page(calc_hover);- - - let selected = view.prepare.selected.as_ref().map(|(name, _)| name.as_str());- - - crate::calc_order_ui::paint_trace(ui, painter, visible, &view.calc_order, generation, selected);- - - }- - - // ScrollArea ignores the wheel while any widget is dragged, so a text-selection drag- - - // scrolls the page itself (#721). After the page loop, so it keeps scrolling once the- - - // pointer leaves the selection's page for the gap or the next page; over the whole- - - // document area, like #759. Combine direct and smoothed motion in one request so mixed- - - // Point and Line events retain their full contribution.- - - if selection_wheel {- - - let smooth =- - - if view.precise_scroll_until == 0.0 { ui.input_mut(|input| std::mem::take(&mut input.smooth_scroll_delta)) } else { Vec2::ZERO };- - - let delta = precise_scroll + boost_extra + smooth;- - - if delta != Vec2::ZERO && delta.is_finite() {- - - ui.scroll_with_delta_animation(delta, egui::style::ScrollAnimation::none());+ + + ui.separator();+ + + if ui.add_enabled(can_modify, egui::Button::new(tl!("Remove all links"))).clicked() {+ + + view.pending_edit = Some(Edit::RemoveLinks { pages: None });+ + + view.links.selected = None;+ + + view.links.context = None;+ + + ui.close();}+ + + return;}- - - // Held at the top or bottom edge, or dragged past it, a text selection scrolls the view- - - // so it can reach text off screen (#1670); the selection follows the pointer on its page.- - - if view.selection_drag- - - && navigation_enabled- - - && unobstructed- - - && !single_paging- - - && let Some(p) = ptr.pos- - - {- - - let dy = crate::autoscroll::edge_delta(p.y, avail, ui.input(|i| i.stable_dt));- - - if dy != 0.0 {- - - view.end_find_following();- - - ui.scroll_with_delta_animation(vec2(0.0, dy), egui::style::ScrollAnimation::none());- - - // Keep scrolling while the pointer rests there and sends no events.- - - ui.ctx().request_repaint();+ + + if view.comments.selected.is_none() {+ + + let selected = view.selected_text().is_some_and(|t| !t.is_empty());+ + + let key = crate::commands::shortcut_label(ui.ctx(), crate::commands::COPY);+ + + if ui.add_enabled(can_copy && selected, egui::Button::new(tl!("Copy")).shortcut_text(key)).clicked() {+ + + copy_selected = true;+ + + ui.close();}+ + + ui.separator();}- - - // The page navigated to stays current while no page shows more of itself, so the next- - - // page step starts from it rather than from a page further down the screen (#188).- - - // It also stays current while it is wholly on screen: a short page (a cheque) gone to- - - // from the Pages panel shows less of itself than the tall page below it, and must not- - - // hand the highlight to that page.- - - if current_overlap >= best_overlap - TIE || current_overlap >= current_height - TIE {- - - current = view.current;- - - }- - - if let Some(p) = pressed_page {- - - current = p;- - - }- - - if view.continuous {- - - view.current = current;- - - }- - - resp.context_menu(|ui| {- - - // Preparing a form: the selected field's menu.- - - if preparing && let Some((name, wi)) = view.prepare.selected.clone() {- - - // Several fields: Align, Center, Distribute, Set Fields to Same Size.- - - if !view.prepare.also.is_empty() {- - - use crate::prepare::Arrange as A;- - - let others = view.prepare.also.clone();- - - let anchor = (name.clone(), wi);- - - let mut pick = |ui: &mut egui::Ui, op: A, label: &str| {- - - if ui.add_enabled(can_modify, egui::Button::new(tl!(label))).clicked() {- - - view.pending_edit = crate::prepare::arrange(&form, &anchor, &others, op);- - - ui.close();- - - }- - - };- - - ui.menu_button(tl!("Align"), |ui| {- - - pick(ui, A::AlignLeft, "Left");- - - pick(ui, A::AlignRight, "Right");- - - pick(ui, A::AlignTop, "Top");- - - pick(ui, A::AlignBottom, "Bottom");- - - pick(ui, A::AlignCenterV, "Center vertically");- - - pick(ui, A::AlignCenterH, "Center horizontally");- - - });- - - ui.menu_button(tl!("Distribute"), |ui| {- - - pick(ui, A::DistributeH, "Horizontally");- - - pick(ui, A::DistributeV, "Vertically");- - - });- - - ui.menu_button(tl!("Set Fields to Same Size"), |ui| {- - - pick(ui, A::SameHeight, "Height");- - - pick(ui, A::SameWidth, "Width");- - - pick(ui, A::SameSize, "Both");- - - });- - - ui.separator();- - - }- - - if ui.button(tl!("Properties…")).clicked() {- - - field_menu = Some(FieldMenu::Properties);- - - ui.close();- - - }- - - if ui.add_enabled(can_modify, egui::Button::new(tl!("Duplicate…"))).clicked() {- - - field_menu = Some(FieldMenu::Duplicate(name.clone()));- - - ui.close();- - - }- - - ui.separator();- - - let delete = if view.prepare.also.is_empty() { "Delete" } else { "Delete selected fields" };- - - if ui.add_enabled(can_modify, egui::Button::new(tl!(delete))).clicked() {- - - view.pending_edit = crate::prepare::delete_selected(view);- - - ui.close();- - - }- - - return;- - - }- - - if let Some((page, index)) = view.links.context {- - - if ui.button(tl!("Properties…")).clicked() {- - - view.links.open_existing = Some((page, index));- - - ui.close();- - - }- - - if ui.add_enabled(can_modify, egui::Button::new(tl!("Delete"))).clicked() {- - - view.pending_edit = Some(Edit::DeleteLink { page, index });- - - view.links.selected = None;- - - view.links.context = None;- - - ui.close();+ + + // Over a picture (and no comment): Copy Image, as in Acrobat's page menu.+ + + let mut copy_image = None;+ + + if view.comments.selected.is_none()+ + + && let Some((page, at)) = view.comments.context_at+ + + {+ + + // The page's content is parsed once per right-click, not on every frame the menu is open.+ + + let key = egui::Id::unique("copy-image-under-menu");+ + + let cached = ui.data(|d| d.get_temp::<(usize, [f64; 2], Option<usize>)>(key)).filter(|c| c.0 == page && c.1 == at);+ + + let hit = match cached {+ + + Some(c) => c.2,+ + + None => {+ + + let hit = doc.page_image_at(page, at);+ + + ui.data_mut(|d| d.insert_temp(key, (page, at, hit)));+ + + hit}- - - ui.separator();- - - if ui.add_enabled(can_modify, egui::Button::new(tl!("Remove all links"))).clicked() {- - - view.pending_edit = Some(Edit::RemoveLinks { pages: None });- - - view.links.selected = None;- - - view.links.context = None;+ + + };+ + + if let Some(image) = hit {+ + + if ui.button(tl!("Copy Image")).clicked() {+ + + copy_image = Some(comments::CanvasAction::CopyImage(page, image));ui.close();}- - - return;- - - }- - - if view.comments.selected.is_none() {- - - let selected = view.selected_text().is_some_and(|t| !t.is_empty());- - - let key = crate::commands::shortcut_label(ui.ctx(), crate::commands::COPY);- - - if ui.add_enabled(can_copy && selected, egui::Button::new(tl!("Copy")).shortcut_text(key)).clicked() {- - - copy_selected = true;+ + + if ui.button(tl!("Copy Image in Original Format")).clicked() {+ + + copy_image = Some(comments::CanvasAction::CopyImageFile(page, image));ui.close();}ui.separator();}- - - // Over a picture (and no comment): Copy Image, as in Acrobat's page menu.- - - let mut copy_image = None;- - - if view.comments.selected.is_none()- - - && let Some((page, at)) = view.comments.context_at- - - {- - - // The page's content is parsed once per right-click, not on every frame the menu is open.- - - let key = egui::Id::unique("copy-image-under-menu");- - - let cached = ui.data(|d| d.get_temp::<(usize, [f64; 2], Option<usize>)>(key)).filter(|c| c.0 == page && c.1 == at);- - - let hit = match cached {- - - Some(c) => c.2,- - - None => {- - - let hit = doc.page_image_at(page, at);- - - ui.data_mut(|d| d.insert_temp(key, (page, at, hit)));- - - hit- - - }- - - };- - - if let Some(image) = hit {- - - if ui.button(tl!("Copy Image")).clicked() {- - - copy_image = Some(comments::CanvasAction::CopyImage(page, image));- - - ui.close();- - - }- - - if ui.button(tl!("Copy Image in Original Format")).clicked() {- - - copy_image = Some(comments::CanvasAction::CopyImageFile(page, image));- - - ui.close();+ + + }----- - -- ------- --- canvas_action = comments::context_menu(ui, view, info, prefs, allowed, can_modify).or(copy_image);+++++++ ++++++++++++++ canvas_action =+++++++ ++++++++++++++ comments::context_menu(ui, view, info, &|page, index| doc.annotation_deletable(page, index), prefs, allowed, can_modify).or(copy_image);+ + + });+ + + *out = PageOut {- - - badge_hover,+ + + canvas_action,+ + + clicked_link,+ + + copy_selected,+ + + field_menu,+ + + field_placed,+ + + field_props,+ + + hover_text,+ + + image_action,+ + + open_boxes,+ + + open_initials,+ + + open_signature,+ + + open_table,+ + + primary_down: ptr.primary_down,+ + + refused,+ + + stamp_placed,+ + + };+ + + (wanted, visible_now)+ + + }+ + ++ + + /// A zoom the fit mode changed keeps the page at the top of the view in place.+ + + fn anchor_zoom_change(view: &mut DocView, avail_width: f32, old_zoom: f32) {+ + + if view.shown && view.zoom_anchor.is_none() && view.goto.is_none() && view.goto_point.is_none() && (view.zoom - old_zoom).abs() > 1e-4 {+ + + let prev_viewport = view.viewport_screen;+ + + let top_y = prev_viewport.min.y;+ + + let anchor = view+ + + .screen_rects+ + + .iter()+ + + .find(|(_, r)| r.min.y <= top_y && r.max.y > top_y)+ + + .map(|(p, r)| {+ + + let fy = if r.height() > 0.0 { ((top_y - r.min.y) / r.height()).clamp(0.0, 1.0) } else { 0.0 };+ + + (*p, fy, 0.0f32)+ + + })+ + + .or_else(|| view.screen_rects.iter().find(|(_, r)| r.min.y >= top_y).map(|(p, r)| (*p, 0.0f32, (r.min.y - top_y).max(0.0))))+ + + .or_else(|| view.screen_rects.last().map(|(p, r)| (*p, 1.0f32, (r.max.y - top_y).max(0.0))));+ + + if let Some((page, fy, rel_y)) = anchor {+ + + view.zoom_anchor = Some((page, 0.5, fy, vec2(avail_width / 2.0, rel_y)));+ + + } else {+ + + view.zoom_anchor = Some((view.current, 0.5, 0.0, vec2(avail_width / 2.0, MARGIN)));+ + + }+ + + }+ + + }+ + ++ + + /// What the pager needs to know about the page row on screen.+ + + #[derive(Clone, Copy)]+ + + struct PagingCx<'a> {+ + + row: &'a [usize],+ + + rects: &'a [Rect],+ + + avail: Rect,+ + + middle_gesture: bool,+ + + unobstructed: bool,+ + + }+ + ++ + + /// Not scrolling: when the whole page or spread fits, the wheel turns pages instead. Returns whether+ + + /// paging owns the wheel, and whether it turned the page at an edge.+ + + fn single_page_paging(ui: &egui::Ui, view: &mut DocView, cx: &PagingCx<'_>) -> (bool, bool) {+ + + let (mut single_paging, mut edge_turned) = (false, false);+ + + let PagingCx { row, rects, avail, middle_gesture, unobstructed } = *cx;+ + + if !view.continuous {+ + + // The row's bounding box on screen (one page, or a two-page spread).+ + + let row_rect = row.iter().filter_map(|&i| rects.get(i)).copied().reduce(Rect::union);+ + + // Within a point, so layout rounding can't stop a fitting page from turning.+ + + let fits = row_rect.is_some_and(|r| r.height() + 2.0 * MARGIN <= avail.height() + 1.0);+ + + let can_turn = !middle_gesture && unobstructed && ui.rect_contains_pointer(avail);+ + + single_paging = can_turn && fits;+ + + // Every wheel event goes to the pager, so it follows each trackpad touch to its end+ + + // even while the page can't turn.+ + + ui.input(|i| {+ + + for e in &i.events {+ + + if let egui::Event::MouseWheel { unit, delta, phase, modifiers, .. } = e {+ + + // Zooming (⌘ or Ctrl) and sideways scrolling (Shift) never turn pages.+ + + let dy = if modifiers.command || modifiers.ctrl || modifiers.shift { 0.0 } else { delta.y };+ + + if fits {+ + + view.single_page_wheel(*unit, dy, *phase, i.time, can_turn);+ + + } else {+ + + edge_turned |= view.single_page_wheel_edge(*unit, dy, *phase, i.time, can_turn);}- - - ui.separator();}}- - - canvas_action = comments::context_menu(ui, view, info, prefs, allowed, can_modify).or(copy_image);});- - - (wanted, visible_now)+ + + if single_paging {+ + + // Paging owns vertical wheel motion here. A diagonal gesture keeps its sideways+ + + // part, as `ScrollArea` itself handles each axis.+ + + ui.input_mut(|i| i.smooth_scroll_delta.y = 0.0);+ + + }+ + + }+ + + (single_paging, edge_turned)+ + + }+ + ++ + + /// This frame's wheel motion over the page view, after paging and point/line suppression.+ + + struct Wheel {+ + + precise_scroll: Vec2,+ + + line_base: Vec2,+ + + boost_extra: Vec2,+ + + has_page: bool,+ + + /// The pager owns the vertical axis (single-page view, or the rest of a gesture that turned the page).+ + + paging_owns_vertical: bool,+ + + }+ + ++ + + /// Point input bypasses egui smoothing for 1:1 motion. Line input keeps egui's configured, smoothed+ + + /// base and adds only the accelerated surplus. While point suppression is active, line and page+ + + /// input are reconstructed so current coarse events survive without exposing an older eased tail.+ + + fn read_wheel(ui: &mut egui::Ui, view: &mut DocView, avail: Rect, single_paging: bool, edge_turned: bool) -> Wheel {+ + + let now = ui.input(|i| i.time);+ + + let input = if ui.rect_contains_pointer(avail) {+ + + // Match the line distance used by egui's other scroll areas.+ + + let live = ui.ctx().options(|o| o.input_options.line_scroll_speed);+ + + let line_points = if live.is_finite() && live > 0.0 { live } else { crate::scroll_speed::EGUI_LINE_POINTS };+ + + ui.input(|i| crate::wheel_boost::accumulate(&i.events, line_points, single_paging))+ + + } else {+ + + crate::wheel_boost::FrameInput::default()+ + + };+ + + let mut precise_scroll = input.precise;+ + + let mut line_base = input.line;+ + + let mut boost_extra = crate::wheel_boost::boost_extra(input, &mut view.wheel_boost_x, &mut view.wheel_boost_y, now);+ + + let has_page = input.page != Vec2::ZERO;+ + + if now.is_finite() && precise_scroll != Vec2::ZERO && !has_page {+ + + view.precise_scroll_until = now + SUPPRESS_SECS;+ + + }+ + + if edge_turned {+ + + // The turn leaves egui's eased copy of the notch to decay for a few frames; it must not+ + + // scroll the page just shown away from its top (or bottom).+ + + view.precise_scroll_until = now + 0.25;+ + + }+ + + // Paging owns the vertical axis in single-page view; leave it to the pager.+ + + // The rest of a gesture that turned the page is swallowed too, or it would pan the new page+ + + // away from the edge it was shown at.+ + + let paging_owns_vertical = single_paging || (!view.continuous && view.wheel.gesture_turned());+ + + if paging_owns_vertical {+ + + precise_scroll.y = 0.0;+ + + line_base.y = 0.0;+ + + boost_extra.y = 0.0;+ + + }+ + + // egui smooths a Point event that moved at least 8 points, keeping part of it for later+ + + // passes. Suppression must outlive that whole action: once it expired after a fixed 0.25 s,+ + + // the last few eased points leaked through the ScrollArea after a precise 1:1 scroll (held+ + + // point input measured 33 points for a 30-point event). Keep hiding the eased copy until+ + + // egui says the action is over, then forget the suppression.+ + + let scrolling = ui.input(|i| i.is_scrolling());+ + + if now < view.precise_scroll_until || (view.precise_scroll_until != 0.0 && scrolling) {+ + + if scrolling {+ + + // Keep hiding egui's unprocessed copy until it has drained. The short rolling grace+ + + // avoids a delayed duplicate without prolonging suppression after the tail is gone.+ + + view.precise_scroll_until = view.precise_scroll_until.max(now + SUPPRESS_TAIL_SECS);+ + + }+ + + ui.input_mut(|i| i.smooth_scroll_delta = Vec2::ZERO);+ + + // The point path suppresses every eased wheel delta. Restore the line base through the+ + + // same un-eased path as its surplus; paging-owned axes were cleared above.+ + + boost_extra = crate::wheel_boost::cap_frame(boost_extra + line_base);+ + + if has_page {+ + + // Page units normally stay on egui's viewport-sized path. During suppression only,+ + + // reproduce the current event directly so an older hidden tail stays hidden.+ + + let page_scale = ui.input(|i| i.viewport_rect().height());+ + + let mut page_delta =+ + + if page_scale.is_finite() && page_scale > 0.0 { crate::wheel_boost::cap_frame(input.page * page_scale) } else { Vec2::ZERO };+ + + if paging_owns_vertical {+ + + page_delta.y = 0.0;+ + + }+ + + boost_extra = crate::wheel_boost::cap_frame(boost_extra + page_delta);+ + + }+ + + } else {+ + + precise_scroll = Vec2::ZERO;+ + + // Selection handling below uses zero to distinguish an inactive window. Clearing a past+ + + // deadline also keeps a later line/page action from being mistaken for the old tail.+ + + view.precise_scroll_until = 0.0;+ + + }+ + + if has_page && paging_owns_vertical {+ + + // Page input belongs to egui on the free axis; the pager still owns vertical motion.+ + + ui.input_mut(|i| i.smooth_scroll_delta.y = 0.0);+ + + }+ + + Wheel { precise_scroll, line_base, boost_extra, has_page, paging_owns_vertical }+ + + }+ + ++ + + /// What decides which renders a frame asks for.+ + + #[derive(Clone, Copy)]+ + + struct RenderPlan<'a> {+ + + visible_pages: &'a [usize],+ + + tag: u64,+ + + scale: f32,+ + + sharp_held: bool,+ + + pan_held: bool,+ + + hand: bool,+ + + }+ + ++ + + /// Queues the renders for the pages and tiles `renders` wants (nearest the view first), prefetches the+ + + /// rows either side, frees tiles of far pages and old zooms, and asks for the text layers.+ + + fn plan_renders(ui: &egui::Ui, view: &mut DocView, info: &DocInfo, renders: PageRenders, plan: &RenderPlan<'_>) {+ + + let (mut wanted, visible_now) = renders;+ + + let RenderPlan { visible_pages, tag, scale, sharp_held, pan_held, hand } = *plan;+ + + // Single-page and two-page views draw only the current row, so the next one was first asked+ + + // for on the turn and showed blank paper until it rendered. Prefetch the rows either side,+ + + // as continuous scrolling does for the pages just off screen.+ + + if !view.continuous+ + + && let (Some(&first), Some(&last)) = (visible_pages.first(), visible_pages.last())+ + + {+ + + let n = if view.layout == PageLayout::Single { 1 } else { 2 };+ + + let max_side = ui.ctx().input(|inp| inp.max_texture_side) as f32;+ + + for i in (last.saturating_add(1)..=last.saturating_add(n)).chain(first.saturating_sub(n)..first) {+ + + let Some(p) = info.pages.get(i).filter(|_| !view.errors.contains_key(&i)) else { continue };+ + + // As drawn: the whole page at this scale, or the backdrop of a tiled page.+ + + let side = p.width.max(p.height).max(1.0);+ + + wanted.push(if side * scale > TILE_THRESHOLD.min(max_side) {+ + + let bs = BASE_SIDE.min(max_side) / side;+ + + (i, bs, scale_tag(bs), None)+ + + } else {+ + + (i, scale, tag, None)+ + + });+ + + }+ + + }+ + + let cur = view.current;+ + + wanted.sort_by_key(|w| (!visible_now.contains(&w.0), w.0.abs_diff(cur), w.3.is_some()));+ + + // Tiles of far-away pages are useless: free them. Tiles of an earlier zoom stay for a page+ + + // that is on screen, whether or not the page is tiled at this zoom (#2196): a zoom out below+ + + // the tiling threshold used to drop the tiles of the zoom just left, so coming back to it+ + + // was a cold miss and the page re-blurred through the backdrop while every tile was+ + + // interpreted again. `OLD_TILES` still bounds how many older tiles are kept, nearest scale+ + + // first, and admission keeps them inside `TILE_BYTES`.+ + + let missing: HashSet<usize> = wanted.iter().filter(|w| w.3.is_some()).map(|w| w.0).collect();+ + + let on_screen: HashSet<usize> = visible_now.iter().copied().collect();+ + + view.tiles.retain(|(p, t, _, _), _| p.abs_diff(cur) <= 2 && (*t == tag || missing.contains(p) || on_screen.contains(p)));+ + + let mut older: Vec<(f32, (usize, u64, u32, u32))> =+ + + view.tiles.keys().filter(|k| k.1 != tag).map(|k| ((tag_scale(k.1) / scale).ln().abs(), *k)).collect();+ + + // Tiles of earlier zooms are kept nearest scale first, and bounded by count *and* bytes: a+ + + // large scan renders a tile up to 4096² (about 67 MiB), so a count alone let a few tiles of+ + + // a few zooms run far past the tile allowance. #2196 keeps a zoom already visited, which+ + + // makes that reachable in ordinary zooming, so the byte bound has to be here too.+ + + older.sort_by(|a, b| a.0.total_cmp(&b.0));+ + + let mut kept = 0usize;+ + + let mut kept_bytes = 0usize;+ + + let mut drop: Vec<(usize, u64, u32, u32)> = Vec::new();+ + + for (_dist, key) in older {+ + + let bytes = view.tiles.get(&key).map_or(0, texture_bytes);+ + + if kept >= OLD_TILES || kept_bytes.saturating_add(bytes) > TILE_BYTES {+ + + drop.push(key);+ + + } else {+ + + kept = kept.saturating_add(1);+ + + kept_bytes = kept_bytes.saturating_add(bytes);+ + + }+ + + }+ + + for key in drop {+ + + view.tiles.remove(&key);+ + + }+ + + let mut queue: Vec<RenderRequest> = wanted+ + + .iter()+ + + .map(|&(page, wanted_scale, wanted_tag, tile)| RenderRequest {+ + + page,+ + + kind: RequestKind::Pixels,+ + + tile,+ + + scale: wanted_scale,+ + + tag: wanted_tag,+ + + // The low-res backdrop under tiles is a preview: tiny images are skipped for it.+ + + // It is the whole-page request whose scale is not the current one; sharp tiles+ + + // and whole-page finals always draw everything.+ + + preview: tile.is_none() && (wanted_scale != scale || wanted_tag != tag),+ + + })+ + + .collect();+ + + // While the zoom or pan is settling, hold back sharp re-renders of pages that already+ + + // show something (a stale whole-page raster or older tiles, drawn stretched): each new+ + + // scale would cancel the running full-page interpret and restart it from scratch, and+ + + // each pan frame would queue a storm of full-page tile interprets.+ + + // Pages with nothing on screen yet still queue, so panning to a fresh page draws it.+ + + if sharp_held || pan_held {+ + + let main_tag = tag;+ + + queue.retain(|req| {+ + + // Fast pages render straight through: the hold only protects heavy pages+ + + // whose full-page interpret costs seconds.+ + + if !view.slow_pages.contains(&req.page) {+ + + return true;+ + + }+ + + if req.tile.is_some() {+ + + let has_current_tile = view.tiles.keys().any(|(p, t, _, _)| *p == req.page && *t == req.tag);+ + + if has_current_tile {+ + + return false;+ + + }+ + + let has_any_surface = view.pages.contains_key(&req.page) || view.tiles.keys().any(|(p, _, _, _)| *p == req.page);+ + + !has_any_surface+ + + } else if req.tag != main_tag {+ + + // The low-res backdrop under tiles is zoom-independent: let it through,+ + + // it is the stretched surface the hold relies on.+ + + true+ + + } else {+ + + // The stale raster stays stretched until the zoom or pan settles; a page with+ + + // nothing on screen yet still renders.+ + + !view.pages.contains_key(&req.page)+ + + }+ + + });+ + + }+ + + // Text layers: visible pages for selection, every page while a search is active. (Select All+ + + // of the document needs no more: shown pages highlight as their text comes, and Copy reads+ + + // the rest, as text far away is let go to bound memory.)+ + + let need_text = |p: &usize| !view.texts.contains_key(p) && !view.text_failed.contains(p);+ + + let mut text_pages: Vec<usize> = if hand { Vec::new() } else { visible_now.iter().copied().filter(need_text).collect() };+ + + if view.find.as_ref().is_some_and(|f| !f.case_query.trim().is_empty()) {+ + + let n = info.pages.len();+ + + let rest: Vec<usize> = (0..n).map(|k| (cur + k) % n).filter(need_text).filter(|p| !text_pages.contains(p)).collect();+ + + text_pages.extend(rest);+ + + }+ + + queue.extend(text_pages.into_iter().map(|page| RenderRequest {+ + + page,+ + + kind: RequestKind::Text,+ + + tile: None,+ + + scale: 1.0,+ + + tag: TEXT_TAG,+ + + preview: false,+ + + }));+ + + view.frame_queue = queue;+ + + view.frame_visible = visible_now.iter().copied().collect();+ + + }+ + ++ + + /// Acts on the notice bar button that was clicked.+ + + fn apply_notice(app: &mut PdfCraftApp, index: usize, notice: Option<Notice>) {+ + + match notice {+ + + #[cfg(not(target_arch = "wasm32"))]+ + + Some(Notice::Reload) => app.watch.reload_request = app.views.get(index).map(|view| view.id),+ + + #[cfg(target_arch = "wasm32")]+ + + Some(Notice::Reload) => {}+ + + Some(Notice::Repairs) => app.dialog = Some(crate::Dialog::Properties(crate::PropsTab::Advanced)),+ + + Some(Notice::Security) => app.dialog = Some(crate::Dialog::Properties(crate::PropsTab::Security)),+ + + Some(Notice::Unlock) => {+ + + if let Some(doc) = app.views.get(index).and_then(|view| app.session.get(view.id)) {+ + + app.unlock_prompt = Some(crate::UnlockPrompt::new(doc, None));+ + + }+ + + }+ + + // Flags the view: the tab closes at the top of the next frame, where no document+ + + // borrow is held.+ + + Some(Notice::Close) => {+ + + if let Some(view) = app.views.get_mut(index) {+ + + view.close_requested = true;+ + + }+ + + }+ + + Some(Notice::Signatures) => app.right = Some(RightPanel::Signatures),+ + + Some(Notice::FieldHighlights(on)) => app.view_defaults.highlight_fields = on,+ + + Some(Notice::Console) => app.dialog = Some(crate::Dialog::JsConsole),+ + + // Back on in Preferences ▸ General.+ + + Some(Notice::HideSecured) => app.show_secured_notice = false,+ + + None => {}+ + + }+ + + }+ + ++ + + /// The snapshot notice bar's Close was clicked: close here, where no document borrow is held. The+ + + /// tab is looked up by id: indices may have shifted since the click, and the flag rides its own+ + + /// view, so a stale flag can never close the wrong tab. Whether a tab was closed (or asked about).+ + + fn close_requested_tab(app: &mut PdfCraftApp, index: usize) -> bool {+ + + let pending = app.views.get(index).filter(|v| v.close_requested).map(|v| v.id).and_then(|id| app.views.iter().position(|v| v.id == id));+ + + let Some(i) = pending else { return false };+ + + app.views[i].close_requested = false;+ + + if app.has_unsaved_work(i) {+ + + app.close_request = Some(crate::CloseRequest::Tab(app.views[i].id));+ + + } else {+ + + app.close_tab(i);+ + + }+ + + true+ + + }+ + ++ + + /// Where the pages are laid out, for placing the scroll area.+ + + #[derive(Clone, Copy)]+ + + struct ScrollGeometry<'a> {+ + + rects: &'a [Rect],+ + + y_shift: f32,+ + + content_w: f32,+ + + content_h: f32,+ + + avail: Rect,+ + + middle_gesture: bool,+ + + hand: bool,+ + + }+ + ++ + + /// The page view's scroll area, with the offset this frame's jumps, drags and zoom anchor ask for.+ + + fn page_scroll_area(ui: &egui::Ui, view: &mut DocView, geometry: &ScrollGeometry<'_>) -> egui::ScrollArea {+ + + let ScrollGeometry { rects, y_shift, content_w, content_h, avail, middle_gesture, hand } = *geometry;+ + + let mut scroll = egui::ScrollArea::both().auto_shrink([false, false]).scroll_source(egui::scroll_area::ScrollSource {+ + + drag: if middle_gesture {+ + + egui::scroll_area::DragScroll::Never+ + + } else if hand {+ + + egui::scroll_area::DragScroll::Always+ + + } else {+ + + egui::scroll_area::DragScroll::OnTouch+ + + },+ + + ..Default::default()+ + + });+ + + // Each document keeps its own scroll position when switching tabs (#189).+ + + scroll = scroll.id_salt(("page-view", view.id));+ + + // Every scroll here asks for no animation. An animated area would still queue a zero-length+ + + // offset target for the next frame, which overwrites the jump a page turn just set.+ + + scroll = scroll.animated(false);+ + + // A newly opened document starts at the top. eframe saves egui's memory with the settings+ + + // and document ids start again at 1 every launch, so the offset stored under this id can be+ + + // where an earlier session left another document.+ + + if !std::mem::replace(&mut view.shown, true) {+ + + scroll = scroll.scroll_offset(Vec2::ZERO);+ + + }+ + + // The Hand tool pans here, before the pages are laid out, so the page moves with the pointer+ + + // in the frame the pointer moves (#924). Scrolling by the drag from inside the area moved the+ + + // page only after that frame was drawn, a frame behind. The frame egui tells the drag from a+ + + // click, the page catches up with all the pointer has moved since the press. A jump asked for+ + + // below still wins.+ + + if hand+ + + && !middle_gesture+ + + && let Some(id) = view.page_widget.filter(|id| ui.ctx().is_being_dragged(*id))+ + + {+ + + let moved = if ui.ctx().drag_started_id() == Some(id) {+ + + ui.input(|i| i.pointer.total_drag_delta()).unwrap_or(Vec2::ZERO)+ + + } else {+ + + ui.input(|i| i.pointer.delta())+ + + };+ + + if moved != Vec2::ZERO {+ + + view.end_find_following();+ + + }+ + + // Within the content, as egui keeps it: past an end the page would show there for a+ + + // frame and spring back. `max` is never NaN or below zero, so the clamp can't panic.+ + + let max = vec2((content_w - avail.width()).max(0.0), (content_h - avail.height()).max(0.0));+ + + scroll = scroll.scroll_offset((view.last_scroll - moved).clamp(Vec2::ZERO, max));+ + + }+ + + if let Some(v) = view.sync_scroll.take() {+ + + scroll = scroll.scroll_offset(v);+ + + }+ + + if let Some((page, fx, fy, rel)) = view.zoom_anchor.take() {+ + + let r = rects[page.min(rects.len() - 1)];+ + + let point = pos2(r.left() + fx * r.width(), r.top() - y_shift + fy * r.height());+ + + scroll = scroll.scroll_offset(anchored_scroll(point, rel, vec2(content_w, content_h), avail.size()));+ + + } else if let Some((page, frac)) = view.goto.take() {+ + + let page = page.min(rects.len() - 1);+ + + let r = rects[page];+ + + // Clamped here: egui clamps only after drawing, so a page that fits was drawn MARGIN - page_gap()+ + + // too high for a frame and then hopped into place. (`avail` is the viewport, as the+ + + // scroll bars float.)+ + + let max_y = (content_h - avail.height()).max(0.0);+ + + scroll = scroll.vertical_scroll_offset((r.top() - y_shift - view.page_gap() + frac * r.height()).max(0.0).min(max_y));+ + + // Horizontally too, as Acrobat does (#2665): beside a much wider page the others sit off+ + + // to one side. A page already shown whole, or one filling the window's width, keeps the+ + + // scroll, so paging through a zoomed-in document stays on the same column. Otherwise a+ + + // page that fits is centred, and a wider one scrolled just far enough to fill the window.+ + + // The page counts with its side gutters, which keep its edge clear of the floating+ + + // quick-action bar as the layout does.+ + + let (x, w) = (view.last_scroll.x, avail.width());+ + + let (left, right) = (r.left() - SIDE, r.right() + SIDE);+ + + let target = if right - left <= w { if left >= x && right <= x + w { x } else { r.center().x - w / 2.0 } } else { x.clamp(left, right - w) };+ + + if (target - x).abs() > 0.5 {+ + + scroll = scroll.horizontal_scroll_offset(target.clamp(0.0, (content_w - w).max(0.0)));+ + + }+ + + }+ + + scroll+ + + }+ + ++ + + /// Notes how far the page view scrolled this frame: reader-owned scrolling ends search following,+ + + /// a pan holds back fresh tile renders until it settles, and a glide keeps going or stops. Whether+ + + /// a pan is still settling.+ + + fn track_scroll<T>(ui: &egui::Ui, view: &mut DocView, out: &egui::containers::scroll_area::ScrollAreaOutput<T>, glide: Vec2) -> bool {+ + + let scroll_offset = out.state.clamped_offset();+ + + // The document ScrollArea's own scroll surfaces move the offset without the wheel deltas+ + + // above: its two scroll-bar tracks/handles and, for touch or the Hand tool, its drag+ + + // background. The output gives us the area id, and egui's pinned ScrollArea registers those+ + + // widgets under `id.with(0)` (horizontal), `id.with(1)` (vertical) and `id.with("area")`.+ + + // Ask for their exact responses instead of treating any held drag as scrolling: a text+ + + // selection, a panel splitter or another widget's drag must not excuse the programmatic jump+ + + // a search flash makes, while a track click (which moves the offset with no pointer motion)+ + + // must still count as the reader scrolling.+ + + let scroll_surface = |id: egui::Id| ui.ctx().read_response(id).is_some_and(|r| r.is_pointer_button_down_on() || r.dragged() || r.clicked());+ + + let pointer_scrolling = scroll_surface(out.id.with(0usize)) || scroll_surface(out.id.with(1usize)) || scroll_surface(out.id.with("area"));+ + + if pointer_scrolling && (scroll_offset - view.last_scroll).length() > 2.0 {+ + + view.end_find_following();+ + + }+ + + let now_settle = ui.input(|i| i.time);+ + + if (scroll_offset - view.last_scroll).length() > 2.0 {+ + + view.pan_hold_until = now_settle + 0.25;+ + + ui.ctx().request_repaint_after(std::time::Duration::from_millis(280));+ + + }+ + + if glide != Vec2::ZERO {+ + + view.fling.moved((scroll_offset - view.last_scroll).length() > 0.01);+ + + }+ + + view.last_scroll = scroll_offset;+ + + now_settle < view.pan_hold_until+ + + }+ + ++ + + /// The hover tip, find bar, size hint and the in-place editors drawn over the pages. Whether the+ + + /// text editor was finished.+ + + fn frame_overlays(ui: &mut egui::Ui, view: &mut DocView, env: &PageEnv<'_>, primary_down: bool, hover_text: Option<(Pos2, String)>) -> bool {+ + + let PageEnv { added, author, avail, can_modify, doc, form, info, prefs, t, today, tool, units, unobstructed, .. } = *env;+ + + if let Some((pos, text)) = hover_text {+ + + // Click-through, as a tooltip is: the pages lose the pointer under anything that isn't.+ + + let tip = egui::Area::new(egui::Id::unique("canvas-hover")).order(egui::Order::Tooltip).interactable(false);+ + + tip.fixed_pos(pos + vec2(14.0, 16.0)).show(ui.ctx(), |ui| {+ + + egui::Frame::popup(ui.style()).show(ui, |ui| {+ + + ui.set_max_width(320.0);+ + + ui.label(text);+ + + });+ + + });+ + + }+ + + find_bar(view, info.pages.len(), avail, ui, t);+ + + page_size_hint(view, info, units, avail, unobstructed, ui, t);+ + + if tool == QuickTool::EnhanceCamera {+ + + crate::camera_ui::bar(ui.ctx(), view, avail, t, can_modify);+ + + }+ + + if let Some(e) = comments::composer(ui.ctx(), view, info, prefs) {+ + + view.pending_edit = Some(e);+ + + }+ + + if let Some(e) = crate::edit_text_ui::overlay(ui.ctx(), view, info) {+ + + view.pending_edit = Some(e);+ + + }+ + + let text_box = crate::forms_ui::text_box(doc, view, form);+ + + if let Some(e) = crate::forms_ui::overlay(ui.ctx(), view, info, form, primary_down, text_box.as_ref(), today) {+ + + view.pending_edit = Some(e);+ + + }+ + + if let Some(e) = crate::fill_sign::type_box(ui.ctx(), view, info, author) {+ + + view.pending_edit = Some(e);+ + + }+ + + let (typed, text_done) = crate::content_ui::editor(ui.ctx(), view, info, added);+ + + if typed.is_some() {+ + + view.pending_edit = typed;+ + + }+ + + text_done+ + + }+ + ++ + + /// Full screen: the click turns the page unless it did something else first. It waits out the+ + + /// double-click time: turning on the first click's release sent a double-click's second click,+ + + /// meant to select a word, to the next page (review on #2070). A selection cancels it, and so do a+ + + /// link followed meanwhile and leaving full screen; a double-click elsewhere still turns once.+ + + /// `click` is `Some(back)` on the frame of a click, `back` when it was a shift-click.+ + + fn schedule_presentation_turn(ui: &egui::Ui, view: &mut DocView, click: Option<bool>, link_followed: bool) {+ + + let now = ui.input(|i| i.time);+ + + if let Some(back) = click+ + + && !link_followed+ + + && view.selection.is_none()+ + + && view.clicks < 2+ + + {+ + + let delay = ui.ctx().options(|o| o.input_options.max_double_click_delay);+ + + view.present_turn = Some((now + delay, !back));+ + + }+ + + if let Some((due, forward)) = view.present_turn {+ + + if link_followed || view.selection.is_some() || view.presentation.is_none() {+ + + view.present_turn = None;+ + + } else if now >= due {+ + + view.present_turn = None;+ + + view.step_page(forward);+ + + } else {+ + + ui.ctx().request_repaint_after(std::time::Duration::from_secs_f64((due - now).max(0.0)));+ + + }+ + + }+ + + }+ + ++ + + /// Follows the link that was clicked. A link to another file comes back, to be opened once the+ + + /// document is no longer borrowed.+ + + fn follow_link(+ + + app: &mut PdfCraftApp,+ + + index: usize,+ + + target: Option<LinkTarget>,+ + + ) -> Option<(pdfcraft_engine::DocId, String, pdfcraft_render::RemoteDestination)> {+ + + let view_id = app.views[index].id;+ + + match target? {+ + + LinkTarget::Page(p, dest) => {+ + + let view = &mut app.views[index];+ + + if let Some(doc) = app.session.get(view.id) {+ + + view.go_to_dest(p, dest, &doc.info);+ + + }+ + + }+ + + LinkTarget::Uri(u) => app.request_document_url(&u, crate::LinkOrigin::Link),+ + + LinkTarget::SetLayers { changes, preserve_rb } => set_layers(app, index, &changes, preserve_rb),+ + + LinkTarget::RemoteGoTo { file, destination, .. } => return Some((view_id, file, destination)),+ + + LinkTarget::Other(s) => app.notify_fmt("This PDF uses the unsupported {s} action.", &[("s", &s)]),+ + + }+ + + None+ + + }+ + ++ + + /// A finished marquee zoom, a signature rectangle drawn, or an empty signature field clicked.+ + + /// Returns the tool to go on with.+ + + fn finish_sign_requests(app: &mut PdfCraftApp, index: usize, mut tool: QuickTool) -> QuickTool {+ + + if let Some(done) = app.views[index].marquee_done.take() {+ + + app.finish_marquee(index, done);+ + + }+ + + // A signature rectangle was drawn, or an empty signature field clicked.+ + + let drawn = app.views[index].sign.drawn.take();+ + + if let (Some((page, rect)), QuickTool::SignArea { certify }) = (drawn, tool) {+ + + tool = QuickTool::Select;+ + + app.quick_tool = tool;+ + + app.start_signing(page, Some(rect), None, certify.then_some(2));+ + + }+ + + if let Some(field) = app.views[index].sign.field.take() {+ + + let signed = app.session.get(app.views[index].id).is_some_and(|d| d.signatures.iter().any(|s| s.field == field && s.signed));+ + + if signed {+ + + app.right = Some(RightPanel::Signatures);+ + + if !app.sig_expanded.contains(&field) {+ + + app.sig_expanded.push(field);+ + + }+ + + } else {+ + + let page = app.views[index].current;+ + + app.start_signing(page, None, Some(field), None);+ + + }+ + + }+ + + tool+ + + }+ + ++ + + /// When not scrolling continuously, only one row is shown at a time: the current page, or the+ + + /// current two-page spread (with the cover rule). These indices drive paging, which pages are+ + + /// drawn, and the content height (#752). Empty for a document with no pages.+ + + fn shown_row(view: &DocView, rects: &[Rect]) -> Vec<usize> {+ + + if rects.is_empty() {+ + + return Vec::new();+ + + }+ + + let last = rects.len() - 1;+ + + let cur = view.current.min(last);+ + + match view.layout {+ + + PageLayout::Single => vec![cur],+ + + PageLayout::TwoUp if view.cover && cur == 0 => vec![0],+ + + PageLayout::TwoUp => {+ + + let first = if view.cover { cur - (cur + 1) % 2 } else { cur - cur % 2 };+ + + if first < last { vec![first, first + 1] } else { vec![first] }+ + + }+ + + }+ + + }+ + ++ + + /// Full screen: a click on the document goes forward a page and a shift-click back, as in+ + + /// Acrobat, unless the click did something else (a link, a word selected). Decided once the pages+ + + /// have had the click. `Some(back)` on the frame of a click, `back` when it was a shift-click.+ + + fn presentation_click_state(ui: &egui::Ui, view: &DocView, navigation_rect: Rect, enabled: bool) -> Option<bool> {+ + + let clicked = view.presentation.is_some() && enabled && presentation_click(ui, navigation_rect);+ + + // Shift as held now, or as the click's own event carried it (a synthetic click).+ + + clicked.then(|| {+ + + ui.input(|i| {+ + + i.modifiers.shift+ + + || i.events.iter().any(|e| {+ + + matches!(e, egui::Event::PointerButton { button: egui::PointerButton::Primary, pressed: false, modifiers, .. } if modifiers.shift)+ + + })+ + + })+ + + })+ + + }+ + ++ + + /// Pinch / ctrl+scroll zoom, anchored on the pointer or the current page.+ + + fn pinch_zoom(ui: &egui::Ui, view: &mut DocView, zoom_delta: f32, navigation_rect: Rect, enabled: bool) {+ + + if zoom_delta.is_finite() && zoom_delta > 0.0 && zoom_delta != 1.0 && enabled && ui.rect_contains_pointer(navigation_rect) {+ + + let z = view.zoom * zoom_delta;+ + + match zoom_anchor(ui) {+ + + Some(p) => view.zoom_at(z, p),+ + + None => view.set_zoom(z),+ + + }+ + + }+ + + }+ + ++ + + /// The middle-button auto-scroll's delta, and the edge scroll a drawing in progress asks for: the+ + + /// pointer in a band along any edge (or just past it) scrolls the view that way, so a point+ + + /// beyond what is shown can be reached without letting go of the tool.+ + + fn auto_scroll_deltas(ui: &egui::Ui, view: &mut DocView, avail: Rect, unobstructed: bool) -> (Vec2, Vec2) {+ + + let auto_delta = if unobstructed {+ + + view.auto_scroll.update(ui, avail, false)+ + + } else {+ + + view.auto_scroll.cancel();+ + + Vec2::ZERO+ + + };+ + ++ + + // Drawing a comment: the pointer in a band along any edge (or just past it) scrolls the view+ + + // that way, so a point beyond what is shown can be reached without letting go of the tool.+ + + let edge_delta = if unobstructed && matches!(view.comments.gesture, Some(comments::Gesture::Draw { .. })) {+ + + let (pointer, dt) = drawing_edge_pointer(ui);+ + + crate::autoscroll::edge_scroll(pointer, avail, dt)+ + + } else {+ + + Vec2::ZERO+ + + };+ + + if edge_delta != Vec2::ZERO {+ + + ui.ctx().request_repaint();+ + + }+ + + (auto_delta, edge_delta)+ + + }+ + ++ + + /// What decides whether touchpad momentum goes on.+ + + #[derive(Clone, Copy)]+ + + struct GlideCx {+ + + now: f64,+ + + may_glide: bool,+ + + key_scroll: f32,+ + + auto_delta: Vec2,+ + + zoom_delta: f32,+ + + edge_delta: Vec2,+ + + wheel_scrolled: bool,+ + + }+ + ++ + + /// Touchpad momentum (#531): a swipe over the page lifted at speed glides on and slows to a stop,+ + + /// through the same un-eased path. Never while the pager owns the wheel, a gesture or dialog has+ + + /// the input, or animations are off; any click, key, zoom or other scrolling ends it. Any+ + + /// reader-owned motion ends automatic search following, even when it stays on the same page; the+ + + /// automatic flash uses `goto`, not these deltas, so its programmatic scroll is never mistaken for+ + + /// a reader action. Returns this frame's glide.+ + + fn step_glide(ui: &egui::Ui, view: &mut DocView, avail: Rect, cx: &GlideCx) -> Vec2 {+ + + let GlideCx { now, may_glide, key_scroll, auto_delta, zoom_delta, edge_delta, wheel_scrolled } = *cx;+ + + let over_page = ui.rect_contains_pointer(avail);+ + + ui.input(|i| view.fling.read(&i.events, now, may_glide && over_page));+ + + let interrupted = glide_interrupted(ui);+ + + if !may_glide || interrupted || key_scroll != 0.0 || auto_delta != Vec2::ZERO || zoom_delta != 1.0 {+ + + view.fling.stop();+ + + }+ + + let glide = view.fling.step(now);+ + + if view.fling.gliding() {+ + + ui.ctx().request_repaint();+ + + }+ + + if wheel_scrolled || auto_delta != Vec2::ZERO || edge_delta != Vec2::ZERO || glide != Vec2::ZERO {+ + + view.end_find_following();+ + + }+ + + glide+ + + }+ + ++ + + /// Text selection runs for the Select tool and for the markup tools (highlight…).+ + + fn tool_selects_text(tool: QuickTool, preparing: bool) -> bool {+ + + match tool {+ + + QuickTool::Comment(t) => t.markup().is_some() || t == comments::CommentTool::ReplaceText,+ + + QuickTool::Select => !preparing,+ + + QuickTool::Redact | QuickTool::ColumnSelect => true,+ + + QuickTool::Hand+ + + | QuickTool::Measure(_)+ + + | QuickTool::Crop+ + + | QuickTool::EnhanceCamera+ + + | QuickTool::Fill(_)+ + + | QuickTool::Field(_)+ + + | QuickTool::AddText+ + + | QuickTool::EditText+ + + | QuickTool::Stamp(_)+ + + | QuickTool::CustomStamp(_)+ + + | QuickTool::Link+ + + | QuickTool::SignArea { .. }+ + + | QuickTool::MarqueeZoom+ + + | QuickTool::Snapshot => false,+ + + }+ + + }+ + ++ + + /// Holds sharp re-renders while the zoom is still moving: a new scale every frame would cancel the+ + + /// in-flight full-page interpret and restart it, so on a heavy page (a CAD plot with ~1000 images+ + + /// renders for seconds) the sharp raster never arrives and the view looks stuck on a soft image.+ + + /// The stale raster stays stretched meanwhile; the sharp request goes out once the zoom settles.+ + + fn hold_sharp_renders(ui: &egui::Ui, view: &mut DocView, scale: f32) -> bool {+ + + let now_scale = ui.input(|i| i.time);+ + + if (scale - view.last_scale).abs() > f32::EPSILON {+ + + view.last_scale = scale;+ + + view.sharp_hold_until = now_scale + 0.35;+ + + ui.ctx().request_repaint_after(std::time::Duration::from_millis(380));+ + + }+ + + now_scale < view.sharp_hold_until+ + + }+ + ++ + + /// A destination's position (bookmarks, links) refines `goto`: its point at the window's top-left,+ + + /// or the centre of a /FitR rectangle at the window's centre.+ + + fn refine_goto_point(mut scroll: egui::ScrollArea, view: &mut DocView, geometry: &ScrollGeometry<'_>) -> egui::ScrollArea {+ + + let ScrollGeometry { rects, y_shift, content_w, content_h, avail, .. } = *geometry;+ + + if let Some((page, fx, fy, rel)) = view.goto_point.take() {+ + + let r = rects[page.min(rects.len() - 1)];+ + + // Within the content, so an unreachable point never shows a frame scrolled past the end.+ + + let (max_x, max_y) = ((content_w - avail.width()).max(0.0), (content_h - avail.height()).max(0.0));+ + + if let Some(fx) = fx {+ + + scroll = scroll.horizontal_scroll_offset((r.left() + fx * r.width() - rel.x).clamp(0.0, max_x));+ + + }+ + + if let Some(fy) = fy {+ + + scroll = scroll.vertical_scroll_offset((r.top() - y_shift + fy * r.height() - rel.y).clamp(0.0, max_y));+ + + }+ + + }+ + + scroll+ + + }+ + ++ + + /// 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;+ + + }+ + + if close_requested_tab(app, index) {+ + + 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();+ + + let notice = notices(view, doc, secured, repaired, crate::sign_ui::banner(&doc.signatures), ui, &t);+ + + apply_notice(app, index, notice);+ + + let Some(doc) = app.session.get(app.views[index].id) else { return };+ + + let info = &doc.info;+ + + // No dialog, close prompt or palette over the page: only then does page input count.+ + + let modal = app.modal_open();+ + + let unobstructed = !modal && !app.palette_open;+ + + let organize_zoom = app.organize_zoom;+ + + let view = &mut app.views[index];+ + + if view.organize {+ + + // One remembered grid size for every document, kept in the settings.+ + + view.set_grid_zoom(organize_zoom);+ + + organize_grid(view, info, doc.allows_assembly(), doc.dirty, unobstructed, ui, &t);+ + + app.organize_zoom = view.grid_zoom();+ + + return;+ + + }+ + ++ + + let avail = ui.available_rect_before_wrap();+ + + view.viewport_w = avail.width();+ + + view.viewport_h = avail.height();+ + + let old_zoom = view.zoom;+ + + view.fit_zoom(info);+ + + anchor_zoom_change(view, avail.width(), old_zoom);+ + ++ + + // Pinch / ctrl+scroll zoom, anchored on the current page.+ + + let zoom_delta = crate::motion::zoom_delta(ui.ctx());+ + + // Exclude the previous frame's scrollbar tracks from gesture activation.+ + + let navigation_rect = if view.viewport_screen.is_positive() { avail.intersect(view.viewport_screen) } else { avail };+ + + let navigation_enabled = app.dialog.is_none() && app.close_request.is_none() && !app.palette_open && ui.is_enabled() && ui.input(|i| i.focused);+ + + let present = presentation_click_state(ui, view, navigation_rect, navigation_enabled && app.quick_tool == QuickTool::Select);+ + + pinch_zoom(ui, view, zoom_delta, navigation_rect, navigation_enabled);+ + + view.viewport_screen = avail;+ + + let (auto_delta, edge_delta) = auto_scroll_deltas(ui, view, avail, unobstructed);+ + ++ + + let content_w = view.content_width(info, avail.width());+ + + let rects = view.layout(info, content_w, ui.ctx().pixels_per_point());+ + + // When not scrolling continuously, only one row is shown at a time: the current page, or the+ + + // current two-page spread (with the cover rule). These indices drive paging, which pages are+ + + // drawn, and the content height (#752). Empty for a document with no pages.+ + + let row = shown_row(view, &rects);+ + + let middle_gesture = view.auto_scroll.blocks_input();+ + + // Not scrolling: when the whole page or spread fits, the wheel would do nothing, so it turns+ + + // pages instead; zoomed in far enough to pan, it pans, and at the edge it turns the page on+ + + // (#1924, `single_page_wheel_edge`). Touch drags are untouched: with+ + + // nothing to pan, touch users turn pages with the rail buttons, the page box and the arrow+ + + // keys. Runs before `visible_pages` so the frame that turns the page draws it.+ + + let (single_paging, edge_turned) = single_page_paging(ui, view, &PagingCx { row: &row, rects: &rects, avail, middle_gesture, unobstructed });+ + + // Point input bypasses egui smoothing for 1:1 motion. Line input keeps egui's configured,+ + + // smoothed base and adds only the accelerated surplus. While point suppression is active,+ + + // reconstruct line and page input here so current coarse events survive without exposing an+ + + // older eased tail.+ + + let now = ui.input(|i| i.time);+ + + let Wheel { precise_scroll, line_base, boost_extra, has_page, paging_owns_vertical } = read_wheel(ui, view, avail, single_paging, edge_turned);+ + + let animates = app.animation_effects.animates(app.motion.reduced);+ + + let may_glide = !paging_owns_vertical && !middle_gesture && navigation_enabled && unobstructed && animates;+ + + let wheel_scrolled = precise_scroll != Vec2::ZERO || line_base != Vec2::ZERO || boost_extra != Vec2::ZERO || has_page;+ + + let motion = GlideCx { now, may_glide, key_scroll, auto_delta, zoom_delta, edge_delta, wheel_scrolled };+ + + let glide = step_glide(ui, view, avail, &motion);+ + + // The wheel may have turned the page above: draw the row it turned to. Measured from the old+ + + // row, the jump to the new page scrolled both out of view, a blank frame on every turn forward.+ + + let row = shown_row(view, &rects);+ + + let visible_pages: Vec<usize> = if view.continuous { (0..rects.len()).collect() } else { row.clone() };+ + + let (y_shift, content_h) = if view.continuous {+ + + (0.0, rects.iter().map(|r| r.bottom()).reduce(f32::max).map(|bottom| bottom + MARGIN).unwrap_or(0.0))+ + + } else {+ + + // Only the current row scrolls into view; the content is its bounding box plus margins.+ + + match row.iter().filter_map(|&i| rects.get(i)).copied().reduce(Rect::union) {+ + + Some(r) => (r.top() - MARGIN, r.height() + 2.0 * MARGIN),+ + + None => (0.0, 0.0),+ + + }+ + + };+ + ++ + + let mut scroll = page_scroll_area(+ + + ui,+ + + view,+ + + &ScrollGeometry { rects: &rects, y_shift, content_w, content_h, avail, middle_gesture, hand: app.quick_tool == QuickTool::Hand },+ + + );+ + + let ppp = ui.ctx().pixels_per_point();+ + + let scale = view.render_scale(ppp);+ + + let tag = scale_tag(scale);+ + + // Hold sharp re-renders while the zoom is still moving: a new scale every frame would+ + + // cancel the in-flight full-page interpret and restart it, so on a heavy page (a CAD+ + + // plot with ~1000 images renders for seconds) the sharp raster never arrives and the+ + + // view looks stuck on a soft image. The stale raster stays stretched meanwhile; the+ + + // sharp request goes out once the zoom settles.+ + + let sharp_held = hold_sharp_renders(ui, view, scale);+ + + view.current_scale_tag = tag;+ + + let hand = app.quick_tool == QuickTool::Hand;+ + + let tool = app.quick_tool;+ + + // Text selection runs for the Select tool and for the markup tools (highlight…).+ + + let selects_text = tool_selects_text(tool, preparing);+ + + let prefs = &app.comment_prefs;+ + + let redact_mark = (app.redact_prefs.hover_fill, app.redact_prefs.opacity);+ + + let units = app.units;+ + + let allowed = doc.allows_annotation();+ + + let can_copy = doc.allows_copying();+ + + let comments_hidden = doc.comments_hidden();+ + + let form = doc.form.clone();+ + + let generation = doc.edit_generation();+ + + let can_fill = doc.allows_form_filling();+ + + let can_crop = doc.allows_assembly();+ + + let signature = app.signature.clone();+ + + let initials = app.initials.clone();+ + + let author = app.comment_prefs.author.clone();+ + + let today = app.session.today();+ + + // In Preferences ▸ Date format, or why it can't be stamped into the PDF.+ + + let date_text = crate::date_text_for_pdf(&app.session);+ + + let by_line = app.session.stamp_by_line(&author);+ + + let custom_stamp = match app.quick_tool {+ + + QuickTool::CustomStamp(i) => app.custom_stamps.get(i).cloned(),+ + + _ => None,+ + + };+ + + let mut open_props: Option<(usize, usize)> = None;+ + + // The table being set up in its window, shown on its own document's page.+ + + let table_preview = app.field_table_draft.as_mut().filter(|d| d.doc == view.id).and_then(|d| Some(d.preview(info.pages.get(d.page)?, &form)));+ + + let can_modify = doc.allows_modification();+ + + if preparing {+ + + crate::prepare::after_refresh(view, &form);+ + + } else {+ + + view.prepare.selected = None;+ + + }+ + + view.objects.prepare(doc, tool == QuickTool::EditText && can_modify, ui.ctx());+ + + view.text_background.prepare(ui.ctx(), doc, view.line_editor.as_ref(), view.content.draft.as_ref(), scale);+ + + let added = if editing_content { doc.added().to_vec() } else { Vec::new() };+ + + let doc_links = if tool == QuickTool::Link { doc.links().to_vec() } else { Vec::new() };+ + + if editing_content {+ + + crate::content_ui::after_refresh(view, &added);+ + + } else {+ + + view.content.selected = None;+ + + }+ + + view.move_background.prepare(ui.ctx(), doc, &view.content, scale);+ + ++ + + scroll = refine_goto_point(scroll, view, &ScrollGeometry { rects: &rects, y_shift, content_w, content_h, avail, middle_gesture, hand });+ + + let selection_wheel = view.selection_drag && navigation_enabled && unobstructed && !single_paging && ui.rect_contains_pointer(avail);+ + + let env = PageEnv {+ + + added: &added,+ + + allowed,+ + + author: &author,+ + + auto_delta,+ + + avail,+ + + boost_extra,+ + + by_line: &by_line,+ + + calc_order,+ + + can_copy,+ + + can_crop,+ + + can_fill,+ + + can_modify,+ + + comments_hidden,+ + + content_h,+ + + content_w,+ + + custom_stamp: &custom_stamp,+ + + date_text: &date_text,+ + + doc,+ + + doc_links: &doc_links,+ + + edge_delta,+ + + editing_content,+ + + form: &form,+ + + generation,+ + + glide,+ + + hand,+ + + info,+ + + initials: &initials,+ + + key_scroll,+ + + middle_gesture,+ + + modal,+ + + navigation_enabled,+ + + paper,+ + + ppp,+ + + precise_scroll,+ + + prefs,+ + + preparing,+ + + rects: &rects,+ + + redact_mark,+ + + scale,+ + + selection_wheel,+ + + selects_text,+ + + signature: &signature,+ + + single_paging,+ + + t: &t,+ + + table_preview: &table_preview,+ + + tag,+ + + text_style: &text_style,+ + + tool,+ + + units,+ + + unobstructed,+ + + visible_pages: &visible_pages,+ + + y_shift,+ + + fill_text_size: app.fill_text_size,+++++++++++++++++++++ fill_text_color: app.fill_text_color,+ + + today,+ + + };+ + + let mut page_out = PageOut::default();+ + + let out = page_scroll(ui, scroll, egui::Id::unique(("page-view-scope", view.id)), |ui, viewport| {+ + + draw_pages(ui, viewport, view, &env, &mut page_out, &mut app.signature_preview)});+ + + let PageOut {- - - badge_hover: _,+ + + canvas_action,+ + + clicked_link,+ + + mut copy_selected,+ + + field_menu,+ + + field_placed,+ + + mut field_props,+ + + hover_text,+ + + mut image_action,+ + + open_boxes,+ + + open_initials,+ + + open_signature,+ + + open_table,+ + + primary_down,+ + + mut refused,+ + + stamp_placed,+ + + } = page_out;view.single_edges = visible_pages.first().copied().filter(|_| !view.continuous).map(|page| {// At the top once the page's top edge shows where going to a page puts it (a gap// below the window's top). Within a point, as for wheel paging, so layout roundingdiff --cc crates/ui-egui/src/commands.rsindex d8c51b0e9,d8c51b0e9,d8c51b0e9,d8c51b0e9,d8c51b0e9,c6bcb5941,d8c51b0e9,d8c51b0e9,d8c51b0e9,ec8bd8c87,26fad6f77,d8c51b0e9,d8c51b0e9,d8c51b0e9,acccbcc55,d8c51b0e9,acccbcc55,d8c51b0e9,26fad6f77,acccbcc55,d8c51b0e9,d8c51b0e9..08d2040e2--- a/crates/ui-egui/src/commands.rs+++ b/crates/ui-egui/src/commands.rs@@@@@@@@@@@@@@@@@@@@@@@ -330,48 -330,48 -330,48 -330,48 -330,48 -304,54 -330,48 -330,48 -330,48 -330,48 -300,54 -330,48 -330,48 -330,48 -330,33 -330,48 -330,33 -330,48 -300,54 -330,33 -330,48 -330,48 +334,48 @@@@@@@@@@@@@@@@@@@@@@@ impl PdfCraftApp"view.theme.system" => self.set_theme_preference(ThemePreference::System),"view.theme.light" => self.set_theme_preference(ThemePreference::Light),"view.theme.dark" => self.set_theme_preference(ThemePreference::Dark),- - - "comment.list" => self.choose_right_panel(Some(RightPanel::Comments)),- - - tool if crate::comments::CommentTool::from_command(tool).is_some() => {- - - let Some(tool) = crate::comments::CommentTool::from_command(tool) else { return false };- - - self.comment_prefs.group_tool[tool.group()] = tool;- - - self.quick_tool = crate::QuickTool::Comment(tool);- - - // Acrobat opens the Comments panel with the commenting tools, unless the user closed it.- - - if self.right.is_none() && !self.comments_panel_closed {- - - self.choose_right_panel(Some(RightPanel::Comments));- - - }- - - // A text selection made before picking a markup tool is marked right away.- - - if let (Some(kind), Some(i)) = (tool.markup(), active)- - - && let Some(doc) = self.session.get(self.views[i].id)+ + + "view.fit_visible" => {+ + + if let Some(i) = self.active+ + + && let Err(e) = self.fit_visible(i){- - - let info = &doc.info;- - - if let Some((page, quads)) = self.views[i].selection_quads(info) {- - - self.views[i].clear_selection();- - - let style = self.comment_prefs.style(tool);- - - let author = self.comment_prefs.author.clone();- - - let shape = pdfcraft_engine::Shape::TextMarkup { kind, quads };- - - self.apply_edit(Edit::AddAnnotation(pdfcraft_engine::NewAnnotation { page, shape, style, contents: String::new(), author }));- - - }- - - }- - - }- - - "form.fields" => self.choose_right_panel(Some(RightPanel::Fields)),- - - "form.calculation_order" => {- - - self.left = crate::LeftPanel::CalculationOrder;- - - // The page edits the fields, so Preview ends; the page grid closes, as for a tool.- - - self.form_preview = false;- - - if let Some(v) = active.and_then(|i| self.views.get_mut(i)) {- - - v.organize = false;+ + + self.notify_fmt("Couldn't fit the visible content: {e}", &[("e", &e.to_string())]);}- - - self.reveal_tools();}- - - "comment.flatten" => {- - - self.apply_edit(Edit::Flatten { comments: true, fields: false });- - - }- - - "form.flatten" => {- - - // Flatten what's typed in a field too (#166); a refused value flattens nothing.- - - if self.commit_form_typing() {- - - self.apply_edit(Edit::Flatten { comments: false, fields: true });+ + + "view.marquee_zoom" => self.quick_tool = crate::QuickTool::MarqueeZoom,+ + + _ => return None,+ + + }+ + + Some(true)+ + + }+ + ++ + + fn run_page_command(&mut self, id: &str, active: Option<usize>, targets: Vec<usize>) -> Option<bool> {+ + + match id {+ + + "page.combine" => self.open_combine_tab(),+ + + "page.number" => {+ + + if let Some(i) = active {+ + + let v = &self.views[i];+ + + let pages: Vec<usize> = if v.selected.is_empty() { vec![v.current] } else { v.selected.iter().copied().collect() };+ + + let (lo, hi) = (pages.iter().min().copied().unwrap_or(0), pages.iter().max().copied().unwrap_or(0));+ + + self.number_draft = crate::NumberDraft { from: lo + 1, to: hi + 1, ..self.number_draft.clone() };}+ + + self.dialog = Some(Dialog::NumberPages);}- - - "form.clear" => {- - - if let Some(i) = active {- - - self.views[i].forms.focus = None;+ + + + ++ "page.properties" => {+ + + + ++ if let Some(i) = active+ + + + ++ && let Some(doc) = self.session.get(self.views[i].id)+ + + + ++ {+ + + + ++ let pages = self.views[i].target_pages();+ + + + ++ let orders = doc.tab_orders();+ + + + ++ let mut theirs = pages.iter().map(|p| orders.get(*p).copied());+ + + + ++ let first = theirs.next().flatten();+ + + + ++ let before = if theirs.all(|o| o == first) { first } else { None };+ + + + ++ let generation = doc.edit_generation();+ + + + ++ self.page_props_draft = Some(crate::PagePropsDraft { doc: self.views[i].id, generation, pages, before, tab_order: before });+ + + + ++ self.dialog = Some(Dialog::PageProps);+ + + }- - - self.apply_edit(Edit::ResetForm { names: None });+ + + }+ + + "bookmark.add" => self.bookmark_action(crate::panels::BmAction::New),+ + + "bookmark.from_structure" => self.bookmark_action(crate::panels::BmAction::FromStructure),+ + + + ++ "bookmark.from_text_styles" => self.bookmark_action(crate::panels::BmAction::FromTextStyles),"page.organize" => {if let Some(v) = active.and_then(|i| self.views.get_mut(i)) {if v.organize {@@@@@@@@@@@@@@@@@@@@@@@ -543,83 -543,83 -543,83 -543,83 -543,83 -467,50 -543,83 -543,83 -543,83 -544,83 -463,50 -543,83 -543,83 -543,83 -528,82 -543,83 -528,82 -543,83 -463,50 -528,82 -543,83 -543,83 +548,83 @@@@@@@@@@@@@@@@@@@@@@@}"edit.links_from_urls" => self.links_from_urls(),"edit.remove_links" => self.remove_all_links(),- - - "redact.mark" => {- - - self.quick_tool = crate::QuickTool::Redact;- - - self.left = crate::LeftPanel::Tool("redact");- - - "comment.import" | "form.import_data" => self.import_data_dialog(),+ + + + ++ "comment.import" => self.import_comments_dialog(),+ + + + ++ "form.import_data" => self.import_data_dialog(),+ + + "comment.stamp" => {+ + + self.left = crate::LeftPanel::Tool("stamp");self.reveal_tools();- - - // A text selection made first is marked right away.- - - if let Some(i) = active- - - && let Some(doc) = self.session.get(self.views[i].id)- - - {- - - let info = &doc.info;- - - if let Some((page, quads)) = self.views[i].selection_quads(info) {- - - self.views[i].clear_selection();- - - let author = self.comment_prefs.author.clone();- - - self.apply_edit(self.redact_prefs.mark(page, quads, &author));- - - }+ + + }+ + + "comment.export" => self.export_data_dialog(true, false),+ + + "comment.summarize" => self.dialog = Some(Dialog::SummarizeComments),+ + + "edit.column_select" => self.quick_tool = crate::QuickTool::ColumnSelect,+ + + "edit.snapshot" => {+ + + self.quick_tool = crate::QuickTool::Snapshot;+ + + self.notify_tr("Drag a rectangle around the area to copy");+ + + }+ + + "edit.copy" => {+ + + if let (Some(i), Some(ctx)) = (active, self.ctx.clone()) {+ + + return Some(self.copy_selected_text(i, &ctx));}+ + + return Some(false);}- - - "redact.pages" => {+ + + "comment.hide_all" => {if let Some(i) = active {- - - let n = self.session.get(self.views[i].id).map_or(1, |d| d.info.pages.len());- - - self.redact_pages_draft = crate::RedactPagesDraft { current: true, from: self.views[i].current + 1, to: n };+ + + let id = self.views[i].id;+ + + let hide = !self.session.get(id).is_some_and(|d| d.comments_hidden());+ + + if self.session.set_hide_comments(id, hide) {+ + + self.views[i].invalidate_content();+ + + }}- - - self.dialog = Some(Dialog::RedactPages);}- - - "redact.search" => {- - - self.redact_search.found = None;- - - self.dialog = Some(Dialog::RedactSearch);+ + + "export.docx" => self.export_office_dialog(pdfcraft_engine::compare::OfficeFormat::Docx),+ + + "export.pptx" => self.export_office_dialog(pdfcraft_engine::compare::OfficeFormat::Pptx),+ + + "export.html" => self.export_office_dialog(pdfcraft_engine::compare::OfficeFormat::Html),+ + + "export.rtf" => self.export_office_dialog(pdfcraft_engine::compare::OfficeFormat::Rtf),+ + + "ocr.enhance_camera" => {+ + + // The corners start on the document's edges when they can be found, else+ + + // inset on the current page (camera_ui::page_input).+ + + self.quick_tool = crate::QuickTool::EnhanceCamera;+ + + if let Some(i) = self.active+ + + && let Some(view) = self.views.get_mut(i)+ + + && let Some(page) = self.session.get(view.id).and_then(|d| d.info.pages.get(view.current).cloned())+ + + {+ + + view.camera_done = None;+ + + view.camera = self.session.detect_camera_corners(view.id, view.current).map(|found| crate::camera_ui::CameraQuad {+ + + page: view.current,+ + + corners: found.map(|[x, y]| page.user_to_view(x as f32, y as f32)),+ + + grab: None,+ + + });+ + + }+ + + self.notify_tr("Drag the corners onto the document's edges, then choose Enhance page.");}- - - "redact.properties" => {- - - self.redact_before = Some(self.redact_prefs.clone());- - - self.dialog = Some(Dialog::RedactProps);+ + + _ => return None,+ + + }+ + + Some(true)+ + + }+ + ++ + + fn run_form_command(&mut self, id: &str, active: Option<usize>) -> Option<bool> {+ + + match id {+ + + "form.fields" => self.choose_right_panel(Some(RightPanel::Fields)),+ + + "form.calculation_order" => {+ + + self.left = crate::LeftPanel::CalculationOrder;+ + + // The page edits the fields, so Preview ends; the page grid closes, as for a tool.+ + + self.form_preview = false;+ + + if let Some(v) = active.and_then(|i| self.views.get_mut(i)) {+ + + v.organize = false;+ + + }+ + + self.reveal_tools();}- - - "redact.apply" => {- - - let marks = active.and_then(|i| self.session.get(self.views[i].id)).map_or(0, |d| d.redaction_marks());- - - if marks == 0 {- - - self.notify_tr("There are no redaction marks to apply");- - - } else {- - - self.dialog = Some(Dialog::RedactApply);+ + + "form.flatten" => {+ + + // Flatten what's typed in a field too (#166); a refused value flattens nothing.+ + + if self.commit_form_typing() {+ + + self.apply_edit(Edit::Flatten { comments: false, fields: true });}}- - - "protect.remove_hidden" => self.open_remove_hidden(),- - - "print.dialog" => self.open_print(),- - - "redact.sanitize" => self.dialog = Some(Dialog::Sanitize),- - - "redact.clear" => {- - - self.apply_edit(Edit::ClearRedactions);+ + + "form.clear" => {+ + + if let Some(i) = active {+ + + self.views[i].forms.focus = None;+ + + }+ + + self.apply_edit(Edit::ResetForm { names: None });}"form.tab_order.row" | "form.tab_order.column" | "form.tab_order.structure" => {let order = match id {diff --cc crates/ui-egui/src/dialogs.rsindex e57299fdc,e57299fdc,e57299fdc,e57299fdc,e57299fdc,d0e9482d0,e57299fdc,e57299fdc,e57299fdc,138b18e1c,d0e9482d0,ebe5110cf,138b18e1c,e57299fdc,c21604a4d,e57299fdc,c21604a4d,e57299fdc,d0e9482d0,c21604a4d,e57299fdc,e57299fdc..0e4316445--- a/crates/ui-egui/src/dialogs.rs+++ b/crates/ui-egui/src/dialogs.rs@@@@@@@@@@@@@@@@@@@@@@@ -24,49 -24,49 -24,49 -24,49 -24,49 -23,6 -24,49 -24,49 -24,49 -24,49 -23,6 -24,49 -24,49 -24,49 -23,48 -24,49 -23,48 -24,49 -23,6 -23,48 -24,49 -24,49 +24,49 @@@@@@@@@@@@@@@@@@@@@@@ use prompts::{full_screen_prompt, link_const INFO_KEYS: [&str; 4] = ["Title", "Author", "Subject", "Keywords"];+ + + /// What the dialog's widgets asked for this frame; acted on after the modal is drawn.+ + + #[derive(Default)]+ + + struct Pending {+ + + apply: bool,+ + + split_now: Option<crate::SplitPlan>,+ + + split_ready: Option<crate::SplitPlan>,+ + + extract_now: bool,+ + + rotate_now: bool,+ + + link_now: Option<Edit>,+ + + recover: Option<bool>,+ + + number_now: Option<Edit>,+ + + apply_number: bool,+ + + link_command: Option<&'static str>,+ + + protect_now: bool,+ + + boxes_now: bool,+ + + marks_now: bool,+ + + export_now: bool,+ + + props_now: bool,+ + + field_props_now: bool,+ + + bulk_field_props_now: bool,+ + + redact_now: Option<Dialog>,+ + + import_words: bool,+ + + print_go: bool,+ + + revert_now: bool,+ + + overwrite_now: bool,+ + + overwrite_elsewhere: bool,+ + + summarize_now: bool,+ + + optimize_now: bool,+ + + duplicate_now: Option<Edit>,+ + + + ++ page_props_now: Option<(pdfcraft_engine::DocId, u64, Edit)>,+ + + replace_now: bool,+ + + open_revision: Option<usize>,+ + + a11y_now: bool,+ + + ocr_now: bool,+ + + compare_now: bool,+ + + images_now: bool,+ + + stamp_now: bool,+ + + alt_now: bool,+ + + close: bool,+ + + /// The dialog to switch to, when a widget asked for another one.+ + + next: Option<Dialog>,+ + + }+ + +pub fn show(app: &mut PdfCraftApp, ctx: &egui::Context) {// The page sets hover cursors from the raw pointer position (form fields, links, comments)// before any dialog is drawn, and nothing under a modal's backdrop takes clicks. Start from@@@@@@@@@@@@@@@@@@@@@@@ -130,1480 -130,1480 -130,1480 -130,1480 -130,1480 -122,1302 -130,1480 -130,1480 -130,1480 -130,1480 -122,1302 -130,1488 -130,1480 -130,1480 -128,1463 -130,1480 -128,1463 -130,1480 -122,1302 -128,1463 -130,1480 -130,1480 +130,1488 @@@@@@@@@@@@@@@@@@@@@@@ fn dialogs(app: &mut PdfCraftApp, ctx:Dialog::About => 780.0,_ => 520.0,});- - - match dialog {- - - Dialog::WordCount => {- - - close = crate::word_count_ui::body(ui, app);+ + + if dialog_body(ui, app, dialog, &mut req) {+ + + dialog_footer(ui, app, dialog, &mut req);+ + + }+ + + });+ + + finish_dialog(app, dialog, modal.should_close(), &mut req);+ + + }+ + ++ + + /// The dialog's content. Returns `false` when it has its own buttons and no footer is wanted.+ + + fn dialog_body(ui: &mut egui::Ui, app: &mut PdfCraftApp, dialog: Dialog, req: &mut Pending) -> bool {+ + + let t = Tokens::get(ui.ctx());+ + + match dialog {+ + + Dialog::WordCount => {+ + + req.close = crate::word_count_ui::body(ui, app);+ + + }+ + + Dialog::CreateImages => {+ + + let (go, cancel) = crate::create_ui::image_import_body(ui, app);+ + + req.images_now = go;+ + + req.close = go || cancel;+ + + return false;+ + + }+ + + Dialog::Properties(tab) => {+ + + if !dialog_properties(ui, app, req, tab) {+ + + return false;+ + + }+ + + }+ + + Dialog::Split => {+ + + if !dialog_split(ui, app, req) {+ + + return false;+ + + }+ + + }+ + + Dialog::ReplacePages => {+ + + if !dialog_replace_pages(ui, app, req) {+ + + return false;+ + + }+ + + }+ + + Dialog::RedactPages => {+ + + let n = app.active_ids().and_then(|(_, id)| app.session.get(id)).map_or(1, |d| d.info.pages.len());+ + + let (ok, cancel) = crate::redact_ui::pages_body(ui, &mut app.redact_pages_draft, n, &t);+ + + if ok {+ + + req.redact_now = Some(dialog);+ + + }+ + + req.close = ok || cancel;+ + + return false;+ + + }+ + + Dialog::RedactSearch => {+ + + let (go, cancel, import) = crate::redact_ui::search_body(ui, &mut app.redact_search, &t);+ + + if go {+ + + req.redact_now = Some(dialog);+ + + }+ + + req.import_words = import;+ + + req.close = cancel;+ + + return false;+ + + }+ + + Dialog::RedactProps => {+ + + if !dialog_redact_props(ui, app, req) {+ + + return false;+ + + }+ + + }+ + + Dialog::RedactApply => {+ + + let marks = app.active_ids().and_then(|(_, id)| app.session.get(id)).map_or(0, |d| d.redaction_marks());+ + + let (ok, cancel) = crate::redact_ui::apply_body(ui, marks, &t);+ + + if ok {+ + + req.redact_now = Some(dialog);+ + + }+ + + req.close = ok || cancel;+ + + return false;+ + + }+ + + Dialog::LinkProps => {+ + + let pages = app.active_ids().and_then(|(_, id)| app.session.get(id)).map_or(1, |d| d.info.pages.len());+ + + let Some(d) = app.link_draft.as_mut() else {+ + + req.close = true;+ + + return false;+ + + };+ + + let (ok, cancel) = crate::link_ui::body(ui, d, pages, &t);+ + + if ok {+ + + req.link_now = Some(crate::link_ui::edit_for(d));+ + + }+ + + req.close = ok || cancel;+ + + return false;+ + + }+ + + Dialog::Extract => {+ + + if !dialog_extract(ui, app, req) {+ + + return false;+ + + }+ + + }+ + + Dialog::RotatePages => {+ + + if !dialog_rotate_pages(ui, app, req) {+ + + return false;+ + + }+ + + }+ + + + ++ Dialog::PageProps => {+ + + + ++ let Some(d) = app.page_props_draft.as_mut() else {+ + + + ++ req.close = true;+ + + + ++ return false;+ + + + ++ };+ + + + ++ let (ok, cancel) = crate::organize_panel::page_props_body(ui, d);+ + + + ++ // An order every page already has adds no undo step.+ + + + ++ if ok && let Some(order) = d.tab_order.filter(|o| d.before != Some(*o)) {+ + + + ++ req.page_props_now = Some((d.doc, d.generation, Edit::SetTabOrder { pages: d.pages.clone(), order }));+ + + + ++ }+ + + + ++ req.close = ok || cancel;+ + + + ++ return false;+ + + + ++ }+ + + Dialog::DuplicateField => {+ + + if !dialog_duplicate_field(ui, app, req) {+ + + return false;+ + + }+ + + }+ + + // Never reached: `dialogs` shows this movable window above and returns before the modal.+ + + // The arm keeps the match exhaustive.+ + + Dialog::FieldTable => req.close = true,+ + + Dialog::Optimize => {+ + + let (ok, cancel) = crate::optimize_ui::body(ui, &mut app.optimize_draft, &t);+ + + req.optimize_now = ok;+ + + req.close = ok || cancel;+ + + if std::mem::take(&mut app.optimize_draft.audit) {+ + + app.refresh_space_audit();+ + + req.next = Some(Dialog::AuditSpace);+ + + }+ + + return false;+ + + }+ + + Dialog::CertificateViewer => {+ + + if !dialog_certificate_viewer(ui, app, req) {+ + + return false;+ + + }+ + + }+ + + Dialog::AuditSpace => {+ + + if crate::optimize_ui::audit_body(ui, &app.space_audit, &t) {+ + + req.next = Some(Dialog::Optimize);+ + + }+ + + return false;+ + + }+ + + Dialog::Sign => {+ + + if crate::sign_ui::dialog(ui, app, &t) {+ + + app.sign_draft = None;+ + + req.close = true;+ + + }+ + + return false;+ + + }+ + + Dialog::SummarizeComments => {+ + + if !dialog_summarize_comments(ui, app, req) {+ + + return false;+ + + }+ + + }+ + + Dialog::Revert => {+ + + if !dialog_revert(ui, app, req) {+ + + return false;+ + + }+ + + }+ + + Dialog::OverwriteChanged => {+ + + if !dialog_overwrite_changed(ui, app, req) {+ + + return false;+ + + }+ + + }+ + + Dialog::Print => {+ + + if !dialog_print(ui, app, req) {+ + + return false;+ + + }+ + + }+ + + Dialog::RemoveHidden => {+ + + let (ok, cancel) = crate::redact_ui::hidden_body(ui, &mut app.hidden_draft, &t);+ + + if ok {+ + + req.redact_now = Some(dialog);+ + + }+ + + req.close = ok || cancel;+ + + return false;+ + + }+ + + Dialog::Sanitize => {+ + + let (ok, cancel) = crate::redact_ui::sanitize_body(ui, &t);+ + + if ok {+ + + req.redact_now = Some(dialog);+ + + }+ + + req.close = ok || cancel;+ + + return false;+ + + }+ + + Dialog::FieldProps => {+ + + let Some(d) = app.field_props.as_mut() else {+ + + req.close = true;+ + + return false;+ + + };+ + + let (go, cancel) = crate::prepare::body(ui, d, &t);+ + + req.apply = go;+ + + req.field_props_now = req.apply;+ + + req.close = req.apply || cancel;+ + + return false;+ + + }+ + + Dialog::BulkFieldProps => {+ + + let Some(d) = app.bulk_field_props.as_mut() else {+ + + req.close = true;+ + + return false;+ + + };+ + + let (go, cancel) = crate::bulk_fields::body(ui, d, &t);+ + + req.apply = go;+ + + req.bulk_field_props_now = req.apply;+ + + req.close = cancel;+ + + return false;+ + + }+ + + Dialog::CommentProps => {+ + + let (go, cancel) = crate::comment_props::body(ui, app, &t);+ + + req.apply = go;+ + + req.props_now = req.apply;+ + + req.close = req.apply || cancel;+ + + return false;+ + + }+ + + Dialog::Signature => {+ + + if !dialog_signature(ui, app, req) {+ + + return false;+ + + }+ + + }+ + + Dialog::AltText => {+ + + let (save, cancel) = crate::a11y_ui::alt_body(ui, app, &t);+ + + req.alt_now = save;+ + + req.close = save || cancel;+ + + return false;+ + + }+ + + Dialog::CreateStamp => {+ + + let (save, cancel) = crate::stamps_ui::create_body(ui, app, &t);+ + + req.stamp_now = save;+ + + req.close = save || cancel;+ + + return false;+ + + }+ + + Dialog::PdfA => {+ + + req.close = crate::standards_ui::body(ui, app, &t);+ + + return false;+ + + }+ + + Dialog::ActionWizard => {+ + + ui.set_width(620.0);+ + + req.close = crate::actions_ui::body(ui, app, &t);+ + + return false;+ + + }+ + + Dialog::CompareFiles => {+ + + let (go, cancel) = crate::compare_ui::body(ui, app, &t);+ + + req.compare_now = go;+ + + req.close = go || cancel;+ + + return false;+ + + }+ + + Dialog::JsConsole => {+ + + ui.set_width(640.0);+ + + req.close = crate::js_ui::console_body(ui, app, &t);+ + + return false;+ + + }+ + + Dialog::DocumentJs => {+ + + ui.set_width(640.0);+ + + req.close = crate::js_ui::document_js_body(ui, app, &t);+ + + return false;+ + + }+ + + Dialog::Preferences => {+ + + if !dialog_preferences(ui, app, req) {+ + + return false;+ + + }+ + + }+ + + Dialog::RecognizeText => {+ + + let (go, cancel) = crate::ocr_ui::body(ui, app, &t);+ + + req.ocr_now = go;+ + + req.close = go || cancel;+ + + return false;+ + + }+ + + Dialog::AccessibilityOptions => {+ + + let (start, cancel) = crate::a11y_ui::options_body(ui, app, &t);+ + + req.a11y_now = start;+ + + req.close = start || cancel;+ + + return false;+ + + }+ + + Dialog::Export(kind) => {+ + + let (go, cancel) = crate::export_ui::body(ui, app, &t, kind);+ + + req.apply = go;+ + + req.export_now = req.apply;+ + + req.close = req.apply || cancel;+ + + return false;+ + + }+ + + Dialog::Marks(kind) => {+ + + ui.set_width(720.0);+ + + let (go, cancel) = crate::marks_ui::body(ui, app, &t, kind);+ + + req.apply = go;+ + + req.marks_now = req.apply;+ + + req.close = req.apply || cancel;+ + + return false;+ + + }+ + + Dialog::PageBoxes => {+ + + let (go, cancel) = crate::pageboxes::body(ui, app, &t);+ + + req.apply = go;+ + + req.boxes_now = req.apply;+ + + req.close = req.apply || cancel;+ + + return false;+ + + }+ + + Dialog::Protect => {+ + + let (go, cancel) = crate::protect::body(ui, app, &t);+ + + req.apply = go;+ + + req.protect_now = req.apply;+ + + req.close = req.apply || cancel;+ + + return false;+ + + }+ + + + ++ Dialog::BookmarksFromTextStyles => {+ + + + ++ req.close = crate::bookmark_styles_ui::body(ui, app, &t);+ + + + ++ return false;+ + + + ++ }+ + + Dialog::NumberPages => {+ + + if !dialog_number_pages(ui, app, req) {+ + + return false;+ + + }+ + + }+ + + Dialog::Recovery => {+ + + if !dialog_recovery(ui, app) {+ + + return false;+ + + }+ + + }+ + + Dialog::Shortcuts => {+ + + if !dialog_shortcuts(ui) {+ + + return false;+ + + }+ + + }+ + + Dialog::About => {+ + + if !dialog_about(ui, req) {+ + + return false;+ + + }+ + + }+ + + }+ + + true+ + + }+ + ++ + + /// `Dialog::Properties(tab)` content. Returns `false` when it has its own buttons and no footer is wanted.+ + + fn dialog_properties(ui: &mut egui::Ui, app: &mut PdfCraftApp, req: &mut Pending, tab: PropsTab) -> bool {+ + + let t = Tokens::get(ui.ctx());+ + + ui.label(egui::RichText::new(tl!("Document Properties")).font(theme::semibold(18.0)));+ + + ui.add_space(8.0);+ + + ui.horizontal_wrapped(|ui| {+ + + for (tb, label) in [+ + + (PropsTab::Description, tl!("Description")),+ + + (PropsTab::InitialView, tl!("Initial View")),+ + + (PropsTab::Security, tl!("Security")),+ + + (PropsTab::Fonts, tl!("Fonts")),+ + + (PropsTab::Custom, tl!("Custom")),+ + + (PropsTab::Advanced, tl!("Advanced")),+ + + (PropsTab::SpaceAudit, tl!("Space Audit")),+ + + ] {+ + + if widgets::mode_tab(ui, label, tab == tb).clicked() {+ + + req.next = Some(Dialog::Properties(tb));}- - - Dialog::CreateImages => {- - - let (go, cancel) = crate::create_ui::image_import_body(ui, app);- - - images_now = go;- - - close = go || cancel;- - - return;+ + + }+ + + });+ + + ui.separator();+ + + let units = app.units;+ + + let Some((_, id)) = app.active_ids() else { return false };+ + + let Some(doc) = app.session.get(id) else { return false };+ + + let i = &doc.info;+ + + // Description shows plain values among text fields; they start where the fields' text does.+ + + let editable_info = tab == PropsTab::Description && doc.allows_modification() && app.props_draft.is_some();+ + + let inset = if editable_info { widgets::FIELD_TEXT_INSET } else { 0.0 };+ + + let row = |ui: &mut egui::Ui, k: &str, v: String| {+ + + // Row labels are UI chrome; values are document data and stay as they are.+ + + ui.label(egui::RichText::new(tl!(k)).color(t.text_muted));+ + + ui.horizontal(|ui| {+ + + ui.add_space(inset);+ + + ui.add(egui::Label::new(if v.is_empty() { egui::RichText::new("—").color(t.text_faint) } else { egui::RichText::new(v) }).wrap());+ + + });+ + + ui.end_row();+ + + };+ + + // A file name or path is read left to right even in an RTL UI: the extension+ + + // stays at its visual end, as in the tab strip.+ + + let path_row = |ui: &mut egui::Ui, k: &str, v: String| {+ + + ui.label(egui::RichText::new(tl!(k)).color(t.text_muted));+ + + ui.scope(|ui| {+ + + ui.set_max_width(420.0);+ + + // Align path text with editable fields while keeping its LTR text order.+ + + ui.add_space(inset);+ + + if v.is_empty() {+ + + ui.label(egui::RichText::new("—").color(t.text_faint));+ + + } else {+ + + crate::widgets::label_ltr(ui, v, crate::theme::regular(13.0), t.text);}- - - Dialog::Properties(tab) => {- - - ui.label(egui::RichText::new(tl!("Document Properties")).font(theme::semibold(18.0)));- - - ui.add_space(8.0);- - - ui.horizontal_wrapped(|ui| {- - - for (tb, label) in [- - - (PropsTab::Description, tl!("Description")),- - - (PropsTab::InitialView, tl!("Initial View")),- - - (PropsTab::Security, tl!("Security")),- - - (PropsTab::Fonts, tl!("Fonts")),- - - (PropsTab::Custom, tl!("Custom")),- - - (PropsTab::Advanced, tl!("Advanced")),- - - (PropsTab::SpaceAudit, tl!("Space Audit")),- - - ] {- - - if widgets::mode_tab(ui, label, tab == tb).clicked() {- - - next = Dialog::Properties(tb);+ + + });+ + + ui.end_row();+ + + };+ + + egui::ScrollArea::vertical().max_height(460.0).auto_shrink([false, true]).show(ui, |ui| {+ + + if tab == PropsTab::SpaceAudit {+ + + ui.add_space(4.0);+ + + crate::optimize_ui::audit_table(ui, &app.space_audit, &t);+ + + return;+ + + }+ + + egui::Grid::new("props").num_columns(2).spacing([18.0, 8.0]).min_col_width(140.0).show(ui, |ui| match tab {+ + + PropsTab::Description => {+ + + path_row(ui, "File", doc.name.clone());+ + + match app.props_draft.as_mut() {+ + + Some((_, draft)) if editable_info => {+ + + for (k, v) in INFO_KEYS.iter().zip(draft.iter_mut()) {+ + + let l = ui.label(egui::RichText::new(tl!(k)).color(t.text_muted));+ + + // Subject and Keywords are often a sentence or a list: they wrap and grow+ + + // instead of hiding most of the value past the field's edge.+ + + let field = if matches!(*k, "Subject" | "Keywords") { widgets::block(v).desired_rows(1) } else { widgets::line(v) };+ + + ui.add(field.desired_width(f32::INFINITY).background_color(t.field).id_salt(("info", *k))).labelled_by(l.id);+ + + ui.end_row();}}- - - });- - - ui.separator();- - - let units = app.units;- - - let Some((_, id)) = app.active_ids() else { return };- - - let Some(doc) = app.session.get(id) else { return };- - - let i = &doc.info;- - - // Description shows plain values among text fields; they start where the fields' text does.- - - let editable_info = tab == PropsTab::Description && doc.allows_modification() && app.props_draft.is_some();- - - let inset = if editable_info { widgets::FIELD_TEXT_INSET } else { 0.0 };- - - let row = |ui: &mut egui::Ui, k: &str, v: String| {- - - // Row labels are UI chrome; values are document data and stay as they are.- - - ui.label(egui::RichText::new(tl!(k)).color(t.text_muted));- - - ui.horizontal(|ui| {- - - ui.add_space(inset);- - - ui.add(- - - egui::Label::new(if v.is_empty() { egui::RichText::new("—").color(t.text_faint) } else { egui::RichText::new(v) }).wrap(),- - - );- - - });- - - ui.end_row();- - - };- - - // A file name or path is read left to right even in an RTL UI: the extension- - - // stays at its visual end, as in the tab strip.- - - let path_row = |ui: &mut egui::Ui, k: &str, v: String| {- - - ui.label(egui::RichText::new(tl!(k)).color(t.text_muted));- - - ui.scope(|ui| {- - - ui.set_max_width(420.0);- - - // Align path text with editable fields while keeping its LTR text order.- - - ui.add_space(inset);- - - if v.is_empty() {- - - ui.label(egui::RichText::new("—").color(t.text_faint));- - - } else {- - - crate::widgets::label_ltr(ui, v, crate::theme::regular(13.0), t.text);- - - }- - - });- - - ui.end_row();- - - };- - - egui::ScrollArea::vertical().max_height(460.0).auto_shrink([false, true]).show(ui, |ui| {- - - if tab == PropsTab::SpaceAudit {- - - ui.add_space(4.0);- - - crate::optimize_ui::audit_table(ui, &app.space_audit, &t);- - - return;+ + + _ => {+ + + row(ui, "Title", i.title.clone().unwrap_or_default());+ + + row(ui, "Author", i.author.clone().unwrap_or_default());+ + + row(ui, "Subject", i.subject.clone().unwrap_or_default());+ + + row(ui, "Keywords", i.keywords.clone().unwrap_or_default());}- - - egui::Grid::new("props").num_columns(2).spacing([18.0, 8.0]).min_col_width(140.0).show(ui, |ui| match tab {- - - PropsTab::Description => {- - - path_row(ui, "File", doc.name.clone());- - - match app.props_draft.as_mut() {- - - Some((_, draft)) if editable_info => {- - - for (k, v) in INFO_KEYS.iter().zip(draft.iter_mut()) {- - - let l = ui.label(egui::RichText::new(tl!(k)).color(t.text_muted));- - - // Subject and Keywords are often a sentence or a list: they wrap and grow- - - // instead of hiding most of the value past the field's edge.- - - let field =- - - if matches!(*k, "Subject" | "Keywords") { widgets::block(v).desired_rows(1) } else { widgets::line(v) };- - - ui.add(field.desired_width(f32::INFINITY).background_color(t.field).id_salt(("info", *k))).labelled_by(l.id);- - - ui.end_row();- - - }- - - }- - - _ => {- - - row(ui, "Title", i.title.clone().unwrap_or_default());- - - row(ui, "Author", i.author.clone().unwrap_or_default());- - - row(ui, "Subject", i.subject.clone().unwrap_or_default());- - - row(ui, "Keywords", i.keywords.clone().unwrap_or_default());- - - }- - - }- - - row(ui, "Application", i.creator.clone().unwrap_or_default());- - - row(ui, "PDF producer", i.producer.clone().unwrap_or_default());- - - }- - - PropsTab::InitialView => {- - - use pdfcraft_engine::{InitialLayout as L, Magnification as M, Navigation as N};- - - let editable = doc.allows_modification();- - - let pages = i.pages.len();- - - let Some((_, v)) = app.view_draft.as_mut() else { return };- - - ui.label(egui::RichText::new(tl!("Layout and Magnification")).font(theme::semibold(12.5)));- - - ui.end_row();- - - let label = ui.label(tl!("Navigation tab"));- - - ui.add_enabled_ui(editable, |ui| {- - - egui::ComboBox::from_id_salt("iv-nav")- - - .selected_text(tl!(format!("{:?}", v.navigation)- - - .replace("PageOnly", "Page Only")- - - .replace("Pages", "Pages Panel and Page")- - - .as_str()))- - - .show_ui(ui, |ui| {- - - for (n, l) in [- - - (N::PageOnly, tl!("Page Only")),- - - (N::Bookmarks, tl!("Bookmarks Panel and Page")),- - - (N::Pages, tl!("Pages Panel and Page")),- - - (N::Attachments, tl!("Attachments Panel and Page")),- - - (N::Layers, tl!("Layers Panel and Page")),- - - ] {- - - ui.selectable_value(&mut v.navigation, n, l);- - - }- - - })- - - .response- - - .labelled_by(label.id);- - - });- - - ui.end_row();- - - let label = ui.label(tl!("Page layout"));- - - ui.add_enabled_ui(editable, |ui| {- - - let names = [- - - (L::Default, tl!("Default")),- - - (L::SinglePage, tl!("Single Page")),- - - (L::SinglePageContinuous, tl!("Single Page Continuous")),- - - (L::TwoUp, tl!("Two-Up (Facing)")),- - - (L::TwoUpContinuous, tl!("Two-Up Continuous (Facing)")),- - - (L::TwoUpCoverPage, tl!("Two-Up (Cover Page)")),- - - (L::TwoUpContinuousCoverPage, tl!("Two-Up Continuous (Cover Page)")),- - - ];- - - let shown = names.iter().find(|(l, _)| *l == v.layout).map_or(tl!("Default"), |(_, n)| n);- - - egui::ComboBox::from_id_salt("iv-layout")- - - .selected_text(shown)- - - .show_ui(ui, |ui| {- - - for (l, n) in names {- - - ui.selectable_value(&mut v.layout, l, n);- - - }- - - })- - - .response- - - .labelled_by(label.id);- - - });- - - ui.end_row();- - - let label = ui.label(tl!("Magnification"));- - - ui.add_enabled_ui(editable, |ui| {- - - ui.horizontal(|ui| {- - - let names = [- - - (M::Default, tl!("Default")),- - - (M::ActualSize, tl!("Actual Size")),- - - (M::FitPage, tl!("Fit Page")),- - - (M::FitWidth, tl!("Fit Width")),- - - (M::FitHeight, tl!("Fit Height")),- - - (M::FitVisible, tl!("Fit Visible")),- - - ];- - - let shown = match v.magnification {- - - M::Percent(p) => format!("{p:.0}%"),- - - m => names.iter().find(|(x, _)| *x == m).map_or(tl!("Default").to_string(), |(_, n)| n.to_string()),- - - };- - - egui::ComboBox::from_id_salt("iv-mag")- - - .selected_text(shown)- - - .show_ui(ui, |ui| {- - - for (m, n) in names {- - - ui.selectable_value(&mut v.magnification, m, n);- - - }- - - for p in [50.0, 75.0, 125.0, 150.0, 200.0] {- - - ui.selectable_value(&mut v.magnification, M::Percent(p), format!("{p:.0}%"));- - - }- - - })- - - .response- - - .labelled_by(label.id);- - - });- - - });- - - ui.end_row();- - - let label = ui.label(tl!("Open to page"));- - - ui.add_enabled_ui(editable, |ui| {- - - let mut p = v.page + 1;- - - if ui.add(egui::DragValue::new(&mut p).range(1..=pages.max(1))).labelled_by(label.id).changed() {- - - v.page = p - 1;- - - }- - - ui.label(crate::i18n::fmt(tl!("of {pages}"), &[("pages", &pages.to_string())]));- - - });- - - ui.end_row();- - - ui.label(egui::RichText::new(tl!("Window Options")).font(theme::semibold(12.5)));- - - ui.end_row();- - - ui.label("");- - - ui.add_enabled_ui(editable, |ui| {- - - ui.vertical(|ui| {- - - ui.add(widgets::checkbox(&mut v.fit_window, tl!("Resize window to initial page")));- - - ui.add(widgets::checkbox(&mut v.center_window, tl!("Center window on screen")));- - - ui.add(widgets::checkbox(&mut v.full_screen, tl!("Open in Full Screen mode")));- - - ui.horizontal(|ui| {- - - ui.label(tl!("Show:"));- - - widgets::radio_value(ui, &mut v.display_title, false, tl!("File Name"));- - - widgets::radio_value(ui, &mut v.display_title, true, tl!("Document Title"));- - - });- - - });- - - });- - - ui.end_row();- - - ui.label(egui::RichText::new(tl!("User Interface Options")).font(theme::semibold(12.5)));- - - ui.end_row();- - - ui.label("");- - - ui.add_enabled_ui(editable, |ui| {- - - ui.vertical(|ui| {- - - ui.add(widgets::checkbox(&mut v.hide_menubar, tl!("Hide menu bar")));- - - ui.add(widgets::checkbox(&mut v.hide_toolbar, tl!("Hide toolbars")));- - - ui.add(widgets::checkbox(&mut v.hide_window_ui, tl!("Hide window controls")));- - - });- - - });- - - ui.end_row();- - - }- - - PropsTab::Security => match doc.security_summary() {- - - None => {- - - row(ui, "Security method", tl!("No security").to_string());- - - row(ui, "Restrictions", tl!("None — everything is allowed").to_string());- - - if doc.allows_security_change() && ui.button(tl!("Protect using password…")).clicked() {- - - link_command = Some("protect.password");- - - }- - - }- - - Some(sec) => {- - - row(ui, "Security method", tl!("Password security").to_string());- - - row(ui, "Encryption", sec.method.clone());- - - row(- - - ui,- - - "Opened with",- - - if sec.pending {- - - tl!("— (protection is applied when you save)").to_string()- - - } else if sec.owner {- - - tl!("Owner password (no restrictions apply)").to_string()- - - } else {- - - tl!("User password").to_string()- - - },- - - );- - - // A restricted document asks for its permissions password first.- - - if doc.allows_security_change() || doc.can_unlock() {- - - ui.horizontal(|ui| {- - - if doc.can_unlock() && ui.button(tl!("Unlock…")).clicked() {- - - link_command = Some("protect.unlock");- - - }- - - if ui.button(tl!("Change settings…")).clicked() {- - - link_command = Some("protect.password");- - - }- - - if ui.button(tl!("Remove security")).clicked() {- - - link_command = Some("protect.remove");- - - }- - - });- - - }- - - let p = sec.permissions;- - - let yes = |b: bool| tl!(if b { "Allowed" } else { "Not allowed" }).to_string();- - - row(- - - ui,- - - "Printing",- - - if !p.print() {- - - tl!("Not allowed").to_string()- - - } else if p.print_high_quality() {- - - tl!("High resolution").to_string()- - - } else {- - - tl!("Low resolution").to_string()- - - },- - - );- - - row(ui, "Changing the document", yes(p.modify()));- - - row(ui, "Document assembly", yes(p.assemble()));- - - row(ui, "Content copying", yes(p.copy()));- - - row(ui, "Content copying for accessibility", yes(p.extract_for_accessibility()));- - - row(ui, "Commenting", yes(p.annotate()));- - - row(ui, "Filling of form fields", yes(p.fill_forms()));- - - }- - - },- - - PropsTab::Fonts => {- - - if i.fonts.is_empty() {- - - row(ui, "Fonts", tl!("No fonts are referenced by the pages.").to_string());- - - }- - - for f in &i.fonts {- - - let mut detail = f.kind.clone();- - - if let Some(e) = &f.encoding {- - - detail.push_str(&format!(" · {e}"));- - - }- - - detail.push_str(if f.subset {- - - " · Embedded subset"- - - } else if f.embedded {- - - " · Embedded"- - - } else {- - - " · Not embedded (substituted)"- - - });- - - row(ui, &f.name, detail);+ + + }+ + + row(ui, "Application", i.creator.clone().unwrap_or_default());+ + + row(ui, "PDF producer", i.producer.clone().unwrap_or_default());+ + + }+ + + PropsTab::InitialView => {+ + + use pdfcraft_engine::{InitialLayout as L, Magnification as M, Navigation as N};+ + + let editable = doc.allows_modification();+ + + let pages = i.pages.len();+ + + let Some((_, v)) = app.view_draft.as_mut() else { return };+ + + ui.label(egui::RichText::new(tl!("Layout and Magnification")).font(theme::semibold(12.5)));+ + + ui.end_row();+ + + let label = ui.label(tl!("Navigation tab"));+ + + ui.add_enabled_ui(editable, |ui| {+ + + craft_ui::ComboBox::from_id_salt("iv-nav")+ + + .selected_text(tl!(format!("{:?}", v.navigation)+ + + .replace("PageOnly", "Page Only")+ + + .replace("Pages", "Pages Panel and Page")+ + + .as_str()))+ + + .show_ui(ui, |ui| {+ + + for (n, l) in [+ + + (N::PageOnly, tl!("Page Only")),+ + + (N::Bookmarks, tl!("Bookmarks Panel and Page")),+ + + (N::Pages, tl!("Pages Panel and Page")),+ + + (N::Attachments, tl!("Attachments Panel and Page")),+ + + (N::Layers, tl!("Layers Panel and Page")),+ + + ] {+ + + ui.selectable_value(&mut v.navigation, n, l);}- - - }- - - PropsTab::Custom => {- - - // Add takes a new name, Update changes the value of the listed property the- - - // Name field names, Delete removes it; OK writes the changes as one step.- - - let editable = doc.allows_modification();- - - let Some((_, d)) = app.custom_draft.as_mut() else { return };- - - let l = ui.label(egui::RichText::new(tl!("Name:")).color(t.text_muted));- - - ui.add_enabled(- - - editable,- - - widgets::line(&mut d.name).desired_width(420.0).background_color(t.field).id_salt("custom-name"),- - - )- - - .labelled_by(l.id);- - - ui.end_row();- - - let l = ui.label(egui::RichText::new(tl!("Value:")).color(t.text_muted));- - - ui.add_enabled(- - - editable,- - - widgets::line(&mut d.value).desired_width(420.0).background_color(t.field).id_salt("custom-value"),- - - )- - - .labelled_by(l.id);- - - ui.end_row();- - - // Untrimmed: a file's `/Project#20` is not `/Project`, and a typed space is refused.- - - let name = d.name.clone();- - - let value = d.value.trim().to_owned();- - - let listed = d.props.iter().position(|(k, _)| *k == name);- - - // An entry the list leaves out (not text, only padding, or past its 256) keeps its value.- - - let file_props = doc.custom_info();- - - let unlisted = doc.has_info(&name) && !file_props.iter().any(|(k, _)| *k == name);- - - let refused = pdfcraft_engine::check_custom_key(&name).err().filter(|_| !name.is_empty()).map(|e| e.to_string());- - - ui.label("");- - - // A file can hold a custom name that `check_custom_key` refuses, such as one- - - // with a space: the tab lists it, and Add, Update and Delete stay off for it.- - - let why = |b: egui::Response| match &refused {- - - Some(why) => b.on_disabled_hover_text(crate::i18n::words(why)),- - - None => b,- - - };- - - // A name that isn't UTF-8 is listed with U+FFFD and can't be written back as it is.- - - let editable = editable && refused.is_none() && !name.contains(char::REPLACEMENT_CHARACTER);- - - // `custom_info` lists at most 256 properties, and a new name goes after the file's- - - // entries, so Add is off once the draft or the file's own list holds 256.- - - let room = d.props.len() < 256 && file_props.len() < 256;- - - ui.horizontal(|ui| {- - - let add = editable && room && listed.is_none() && !unlisted && !name.is_empty() && !value.is_empty();- - - if why(ui.add_enabled(add, egui::Button::new(tl!("Add")))).clicked() {- - - d.props.push((name.clone(), value.clone()));- - - d.name.clear();- - - d.value.clear();- - - }- - - let update = editable && !value.is_empty() && listed.and_then(|n| d.props.get(n)).is_some_and(|(_, v)| *v != value);- - - if why(ui.add_enabled(update, egui::Button::new(tl!("Update")))).clicked()- - - && let Some(p) = listed.and_then(|n| d.props.get_mut(n))- - - {- - - p.1 = value.clone();- - - }- - - if why(ui.add_enabled(editable && listed.is_some(), egui::Button::new(tl!("Delete")))).clicked()- - - && let Some(n) = listed.filter(|n| *n < d.props.len())- - - {- - - d.props.remove(n);- - - d.name.clear();- - - d.value.clear();- - - }- - - });- - - ui.end_row();- - - if d.props.is_empty() {- - - ui.label("");- - - ui.label(egui::RichText::new(tl!("None")).color(t.text_faint));- - - ui.end_row();+ + + })+ + + .response+ + + .labelled_by(label.id);+ + + });+ + + ui.end_row();+ + + let label = ui.label(tl!("Page layout"));+ + + ui.add_enabled_ui(editable, |ui| {+ + + let names = [+ + + (L::Default, tl!("Default")),+ + + (L::SinglePage, tl!("Single Page")),+ + + (L::SinglePageContinuous, tl!("Single Page Continuous")),+ + + (L::TwoUp, tl!("Two-Up (Facing)")),+ + + (L::TwoUpContinuous, tl!("Two-Up Continuous (Facing)")),+ + + (L::TwoUpCoverPage, tl!("Two-Up (Cover Page)")),+ + + (L::TwoUpContinuousCoverPage, tl!("Two-Up Continuous (Cover Page)")),+ + + ];+ + + let shown = names.iter().find(|(l, _)| *l == v.layout).map_or(tl!("Default"), |(_, n)| n);+ + + craft_ui::ComboBox::from_id_salt("iv-layout")+ + + .selected_text(shown)+ + + .show_ui(ui, |ui| {+ + + for (l, n) in names {+ + + ui.selectable_value(&mut v.layout, l, n);}- - - // A click on a property fills the fields with it; values are document data.- - - let mut picked = None;- - - for (k, v) in &d.props {- - - if ui.selectable_label(*k == name, k.as_str()).clicked() {- - - picked = Some((k.clone(), v.clone()));+ + + })+ + + .response+ + + .labelled_by(label.id);+ + + });+ + + ui.end_row();+ + + let label = ui.label(tl!("Magnification"));+ + + ui.add_enabled_ui(editable, |ui| {+ + + ui.horizontal(|ui| {+ + + let names = [+ + + (M::Default, tl!("Default")),+ + + (M::ActualSize, tl!("Actual Size")),+ + + (M::FitPage, tl!("Fit Page")),+ + + (M::FitWidth, tl!("Fit Width")),+ + + (M::FitHeight, tl!("Fit Height")),+ + + (M::FitVisible, tl!("Fit Visible")),+ + + ];+ + + let shown = match v.magnification {+ + + M::Percent(p) => format!("{p:.0}%"),+ + + m => names.iter().find(|(x, _)| *x == m).map_or(tl!("Default").to_string(), |(_, n)| n.to_string()),+ + + };+ + + craft_ui::ComboBox::from_id_salt("iv-mag")+ + + .selected_text(shown)+ + + .show_ui(ui, |ui| {+ + + for (m, n) in names {+ + + ui.selectable_value(&mut v.magnification, m, n);}- - - ui.scope(|ui| {- - - ui.set_max_width(420.0);- - - ui.add(egui::Label::new(v.as_str()).wrap());- - - });- - - ui.end_row();- - - }- - - if let Some((k, v)) = picked {- - - d.name = k;- - - d.value = v;- - - }- - - }- - - PropsTab::Advanced => {- - - row(ui, "PDF version", i.pdf_version.clone());- - - path_row(ui, "Location", doc.path.clone().unwrap_or_default());- - - row(ui, "File size", format!("{} ({})", human_size(i.file_size), crate::panels::byte_count(i.file_size)));- - - let p = &i.pages[0];- - - row(ui, "Page size", units.size(f64::from(p.width), f64::from(p.height)));- - - row(ui, "Number of pages", i.pages.len().to_string());- - - row(ui, "Tagged PDF", yes(i.tagged));- - - row(ui, "Form fields", i.fields.len().to_string());- - - row(ui, "Comments", i.annotations.len().to_string());- - - row(ui, "Layers", i.layers.len().to_string());- - - row(ui, "Attachments", i.attachments.len().to_string());- - - row(ui, "JavaScript", yes(i.has_javascript));- - - // Each incremental update is a revision; earlier ones open as their own document.- - - let ends = doc.revision_ends();- - - if ends.len() > 1 {- - - ui.label(egui::RichText::new(tl!("Revisions")).color(t.text_muted));- - - // Reserve the full wrapped height before the grid starts the next row.- - - ui.vertical(|ui| {- - - ui.horizontal_wrapped(|ui| {- - - ui.label(ends.len().to_string());- - - for n in (1..ends.len()).rev().take(12) {- - - if ui- - - .small_button(crate::i18n::fmt(tl!("View revision {n}"), &[("n", &n.to_string())]))- - - .on_hover_text(tl!("Open the file as it was saved then"))- - - .clicked()- - - {- - - open_revision = Some(n);- - - }- - - }- - - });- - - });- - - ui.end_row();- - - }- - - // Reading Options: binding and language.- - - if let Some((_, v)) = app.view_draft.as_mut() {- - - let editable = doc.allows_modification();- - - ui.label(egui::RichText::new(tl!("Binding")).color(t.text_muted));- - - ui.add_enabled_ui(editable, |ui| {- - - ui.horizontal(|ui| {- - - widgets::radio_value(ui, &mut v.right_to_left, false, tl!("Left Edge"));- - - widgets::radio_value(ui, &mut v.right_to_left, true, tl!("Right Edge"));- - - });- - - });- - - ui.end_row();- - - let l = ui.label(egui::RichText::new(tl!("Language")).color(t.text_muted));- - - let mut lang = v.language.clone().unwrap_or_default();- - - if ui- - - .add_enabled(editable, widgets::line(&mut lang).hint_text(tl!("e.g. en-US")).desired_width(160.0))- - - .labelled_by(l.id)- - - .changed()- - - {- - - v.language = (!lang.trim().is_empty()).then(|| lang.trim().to_string());+ + + for p in [50.0, 75.0, 125.0, 150.0, 200.0] {+ + + ui.selectable_value(&mut v.magnification, M::Percent(p), format!("{p:.0}%"));}- - - ui.end_row();- - - }- - - // What was repaired while reading a damaged file (fidelity: never silent).- - - let repairs = doc.repair_log();- - - row(ui, "Repairs", if repairs.is_empty() { tl!("None").to_string() } else { repairs.len().to_string() });- - - if !repairs.is_empty() {- - - ui.label("");- - - egui::CollapsingHeader::new(tl!("Repair log")).show(ui, |ui| {- - - for r in &repairs {- - - ui.add(egui::Label::new(egui::RichText::new(r).small()).wrap());- - - }- - - });- - - ui.end_row();- - - }- - - }- - - // Laid out above, outside the two-column grid.- - - PropsTab::SpaceAudit => {}+ + + })+ + + .response+ + + .labelled_by(label.id);});});- - - }- - - Dialog::Split => {- - - ui.label(egui::RichText::new(tl!("Split document")).font(theme::semibold(18.0)));- - - ui.add_space(8.0);- - - let Some((vi, id)) = app.active_ids() else { return };- - - let n = app.session.get(id).map(|d| d.info.pages.len()).unwrap_or(0);- - - let selected: Vec<usize> = app.views[vi].selected.iter().copied().filter(|p| *p > 0).collect();- - - let marks = app.session.bookmark_splits(id);- - - let draft = &mut app.split_draft;- - - use crate::SplitMode as M;- - - if selected.is_empty() && draft.mode == M::Selection {- - - draft.mode = M::Pages;- - - }- - - widgets::radio_value(ui, &mut draft.mode, M::Pages, tl!("Number of pages"));- - - ui.add_enabled_ui(draft.mode == M::Pages, |ui| {- - - ui.horizontal(|ui| {- - - ui.add_space(24.0);- - - ui.label(tl!("Pages per file"));- - - ui.add(egui::DragValue::new(&mut draft.every).range(1..=n.max(1)));- - - });+ + + ui.end_row();+ + + let label = ui.label(tl!("Open to page"));+ + + ui.add_enabled_ui(editable, |ui| {+ + + let mut p = v.page + 1;+ + + if ui.add(egui::DragValue::new(&mut p).range(1..=pages.max(1))).labelled_by(label.id).changed() {+ + + v.page = p - 1;+ + + }+ + + ui.label(crate::i18n::fmt(tl!("of {pages}"), &[("pages", &pages.to_string())]));});- - - widgets::radio_value(ui, &mut draft.mode, M::Size, tl!("File size"));- - - ui.add_enabled_ui(draft.mode == M::Size, |ui| {- - - ui.horizontal(|ui| {- - - ui.add_space(24.0);- - - ui.label(tl!("At most"));- - - ui.add(egui::DragValue::new(&mut draft.size_mb).range(0.05..=2000.0).speed(0.1).suffix(" MB"));+ + + ui.end_row();+ + + ui.label(egui::RichText::new(tl!("Window Options")).font(theme::semibold(12.5)));+ + + ui.end_row();+ + + ui.label("");+ + + ui.add_enabled_ui(editable, |ui| {+ + + ui.vertical(|ui| {+ + + ui.add(widgets::checkbox(&mut v.fit_window, tl!("Resize window to initial page")));+ + + ui.add(widgets::checkbox(&mut v.center_window, tl!("Center window on screen")));+ + + ui.add(widgets::checkbox(&mut v.full_screen, tl!("Open in Full Screen mode")));+ + + ui.horizontal(|ui| {+ + + ui.label(tl!("Show:"));+ + + widgets::radio_value(ui, &mut v.display_title, false, tl!("File Name"));+ + + widgets::radio_value(ui, &mut v.display_title, true, tl!("Document Title"));+ + + });});});- - - ui.add_enabled_ui(!marks.is_empty(), |ui| {- - - widgets::radio_value(- - - ui,- - - &mut draft.mode,- - - M::Bookmarks,- - - crate::i18n::fmt(tl!("Top-level bookmarks ({n})"), &[("n", &marks.len().to_string())]),- - - )- - - });- - - ui.add_enabled_ui(!selected.is_empty(), |ui| {- - - widgets::radio_value(ui, &mut draft.mode, M::Selection, tl!("Before each selected page (select pages in Organize)"))+ + + ui.end_row();+ + + ui.label(egui::RichText::new(tl!("User Interface Options")).font(theme::semibold(12.5)));+ + + ui.end_row();+ + + ui.label("");+ + + ui.add_enabled_ui(editable, |ui| {+ + + ui.vertical(|ui| {+ + + ui.add(widgets::checkbox(&mut v.hide_menubar, tl!("Hide menu bar")));+ + + ui.add(widgets::checkbox(&mut v.hide_toolbar, tl!("Hide toolbars")));+ + + ui.add(widgets::checkbox(&mut v.hide_window_ui, tl!("Hide window controls")));+ + + });});- - - let plan = match draft.mode {- - - M::Pages => crate::SplitPlan::By(pdfcraft_engine::SplitBy::PageCount(draft.every)),- - - M::Selection => crate::SplitPlan::By(pdfcraft_engine::SplitBy::Before(selected)),- - - M::Size => crate::SplitPlan::Size((draft.size_mb * 1_048_576.0) as usize),- - - M::Bookmarks => crate::SplitPlan::Bookmarks,- - - };- - - let files = match &plan {- - - crate::SplitPlan::By(by) => Some(pdfcraft_engine::split_ranges(n, by).len()),- - - crate::SplitPlan::Bookmarks => {- - - Some(pdfcraft_engine::split_ranges(n, &pdfcraft_engine::SplitBy::Before(marks.iter().map(|m| m.0).collect())).len())+ + + ui.end_row();+ + + }+ + + PropsTab::Security => match doc.security_summary() {+ + + None => {+ + + row(ui, "Security method", tl!("No security").to_string());+ + + row(ui, "Restrictions", tl!("None — everything is allowed").to_string());+ + + if doc.allows_security_change() && ui.button(tl!("Protect using password…")).clicked() {+ + + req.link_command = Some("protect.password");}- - - crate::SplitPlan::Size(_) => None,- - - };- - - ui.add_space(8.0);- - - let text = match files {- - - Some(f) => {- - - if f == 1 {- - - crate::i18n::fmt(tl!("Creates 1 file from {n} pages."), &[("n", &n.to_string())])+ + + }+ + + Some(sec) => {+ + + row(ui, "Security method", tl!("Password security").to_string());+ + + row(ui, "Encryption", sec.method.clone());+ + + row(+ + + ui,+ + + "Opened with",+ + + if sec.pending {+ + + tl!("— (protection is applied when you save)").to_string()+ + + } else if sec.owner {+ + + tl!("Owner password (no restrictions apply)").to_string()} else {- - - crate::i18n::fmt(tl!("Creates {f} files from {n} pages."), &[("f", &f.to_string()), ("n", &n.to_string())])- - - }+ + + tl!("User password").to_string()+ + + },+ + + );+ + + // A restricted document asks for its permissions password first.+ + + if doc.allows_security_change() || doc.can_unlock() {+ + + ui.horizontal(|ui| {+ + + if doc.can_unlock() && ui.button(tl!("Unlock…")).clicked() {+ + + req.link_command = Some("protect.unlock");+ + + }+ + + if ui.button(tl!("Change settings…")).clicked() {+ + + req.link_command = Some("protect.password");+ + + }+ + + if ui.button(tl!("Remove security")).clicked() {+ + + req.link_command = Some("protect.remove");+ + + }+ + + });}- - - None => crate::i18n::fmt(tl!("Each file holds as many of the {n} pages as fit."), &[("n", &n.to_string())]),- - - };- - - ui.label(egui::RichText::new(text).color(t.text_muted));- - - if files.is_none_or(|f| f > 1) {- - - split_ready = Some(plan);+ + + let p = sec.permissions;+ + + let yes = |b: bool| tl!(if b { "Allowed" } else { "Not allowed" }).to_string();+ + + row(+ + + ui,+ + + "Printing",+ + + if !p.print() {+ + + tl!("Not allowed").to_string()+ + + } else if p.print_high_quality() {+ + + tl!("High resolution").to_string()+ + + } else {+ + + tl!("Low resolution").to_string()+ + + },+ + + );+ + + row(ui, "Changing the document", yes(p.modify()));+ + + row(ui, "Document assembly", yes(p.assemble()));+ + + row(ui, "Content copying", yes(p.copy()));+ + + row(ui, "Content copying for accessibility", yes(p.extract_for_accessibility()));+ + + row(ui, "Commenting", yes(p.annotate()));+ + + row(ui, "Filling of form fields", yes(p.fill_forms()));}- - - }- - - Dialog::ReplacePages => {- - - let count = app.active_ids().and_then(|(_, id)| app.session.get(id)).map(|d| d.info.pages.len()).unwrap_or(1).max(1);- - - let Some(d) = app.replace_draft.as_mut() else {- - - close = true;- - - return;- - - };- - - ui.label(egui::RichText::new(tl!("Replace Pages")).font(theme::semibold(18.0)));- - - ui.add_space(8.0);- - - d.to = d.to.clamp(1, count);- - - d.from = d.from.clamp(1, d.to);- - - ui.horizontal(|ui| {- - - let from_label = ui.label(tl!("Original: replace pages"));- - - let from = ui.add(egui::DragValue::new(&mut d.from).range(1..=count)).labelled_by(from_label.id);- - - let to_label = ui.label(tl!("to"));- - - let to = ui.add(egui::DragValue::new(&mut d.to).range(1..=count)).labelled_by(to_label.id);- - - if from.changed() || to.changed() {- - - d.range_edited = true;+ + + },+ + + PropsTab::Fonts => {+ + + if i.fonts.is_empty() {+ + + row(ui, "Fonts", tl!("No fonts are referenced by the pages.").to_string());+ + + }+ + + for f in &i.fonts {+ + + let mut detail = f.kind.clone();+ + + if let Some(e) = &f.encoding {+ + + detail.push_str(&format!(" · {e}"));}- - - ui.label(egui::RichText::new(crate::i18n::fmt(tl!("of {name}"), &[("name", &count.to_string())])).color(t.text_muted));- - - });- - - let n = if d.range_edited { d.to - d.from + 1 } else { d.pages.len().max(1) };- - - let max_start = d.src_pages.saturating_sub(n) + 1;- - - d.src_from = d.src_from.clamp(1, max_start.max(1));- - - ui.horizontal(|ui| {- - - let replacement_label = ui.label(crate::i18n::fmt(tl!("Replacement: pages of {name}"), &[("name", &d.name)]));- - - ui.add(egui::DragValue::new(&mut d.src_from).range(1..=max_start.max(1))).labelled_by(replacement_label.id);- - - ui.label(crate::i18n::fmt(tl!("to {n}"), &[("n", &(d.src_from + n - 1).to_string())]));- - - ui.label(egui::RichText::new(crate::i18n::fmt(tl!("of {name}"), &[("name", &d.src_pages.to_string())])).color(t.text_muted));- - - });- - - let fits = n <= d.src_pages;- - - ui.add_space(6.0);- - - ui.label(- - - egui::RichText::new(if fits {- - - tl!("Only the page content changes: links, comments, form fields and bookmarks on the original pages stay.")+ + + detail.push_str(if f.subset {+ + + " · Embedded subset"+ + + } else if f.embedded {+ + + " · Embedded"} else {- - - tl!("The replacement file doesn't have that many pages.")- - - })- - - .small()- - - .color(t.text_faint),- - - );- - - ui.add_space(10.0);- - - ui.with_layout(Layout::right_to_left(Align::Center), |ui| {- - - if ui.add_enabled_ui(fits, |ui| widgets::pill_button(ui, tl!("OK"), true)).inner.clicked() {- - - replace_now = true;- - - close = true;- - - }- - - if widgets::pill_button(ui, tl!("Cancel"), false).clicked() {- - - close = true;- - - }- - - });- - - return;- - - }- - - Dialog::RedactPages => {- - - let n = app.active_ids().and_then(|(_, id)| app.session.get(id)).map_or(1, |d| d.info.pages.len());- - - let (ok, cancel) = crate::redact_ui::pages_body(ui, &mut app.redact_pages_draft, n, &t);- - - if ok {- - - redact_now = Some(dialog);- - - }- - - close = ok || cancel;- - - return;- - - }- - - Dialog::RedactSearch => {- - - let (go, cancel, import) = crate::redact_ui::search_body(ui, &mut app.redact_search, &t);- - - if go {- - - redact_now = Some(dialog);- - - }- - - import_words = import;- - - close = cancel;- - - return;- - - }- - - Dialog::RedactProps => {- - - let mut prefs = app.redact_prefs.clone();- - - let (ok, cancel) = crate::redact_ui::props_body(ui, &mut prefs, &t);- - - app.redact_prefs = prefs;- - - if ok && app.redact_prefs.remember {- - - app.redact_defaults = app.redact_prefs.clone();- - - }- - - if cancel && let Some(before) = app.redact_before.take() {- - - app.redact_prefs = before;- - - }- - - if ok {- - - app.redact_before = None;- - - }- - - close = ok || cancel;- - - return;- - - }- - - Dialog::RedactApply => {- - - let marks = app.active_ids().and_then(|(_, id)| app.session.get(id)).map_or(0, |d| d.redaction_marks());- - - let (ok, cancel) = crate::redact_ui::apply_body(ui, marks, &t);- - - if ok {- - - redact_now = Some(dialog);- - - }- - - close = ok || cancel;- - - return;- - - }- - - Dialog::LinkProps => {- - - let pages = app.active_ids().and_then(|(_, id)| app.session.get(id)).map_or(1, |d| d.info.pages.len());- - - let Some(d) = app.link_draft.as_mut() else {- - - close = true;- - - return;- - - };- - - let (ok, cancel) = crate::link_ui::body(ui, d, pages, &t);- - - if ok {- - - link_now = Some(crate::link_ui::edit_for(d));+ + + " · Not embedded (substituted)"+ + + });+ + + row(ui, &f.name, detail);}- - - close = ok || cancel;- - - return;}- - - Dialog::Extract => {- - - let (selected, total) = app.active_ids().map_or((Vec::new(), 0), |(i, _)| (app.views[i].target_pages(), app.views[i].page_count()));- - - ui.label(egui::RichText::new(tl!("Extract pages")).font(theme::semibold(18.0)));- - - ui.add_space(8.0);- - - // Page ranges to take instead of the selection (#3593); the hint is the selection.- - - let hint = match crate::combine_ui::range_of(&selected, total) {- - - all if all.is_empty() && total > 1 => format!("1-{total}"),- - - all if all.is_empty() => "1".to_string(),- - - some => some,+ + + PropsTab::Custom => {+ + + // Add takes a new name, Update changes the value of the listed property the+ + + // Name field names, Delete removes it; OK writes the changes as one step.+ + + let editable = doc.allows_modification();+ + + let Some((_, d)) = app.custom_draft.as_mut() else { return };+ + + let l = ui.label(egui::RichText::new(tl!("Name:")).color(t.text_muted));+ + + ui.add_enabled(editable, widgets::line(&mut d.name).desired_width(420.0).background_color(t.field).id_salt("custom-name"))+ + + .labelled_by(l.id);+ + + ui.end_row();+ + + let l = ui.label(egui::RichText::new(tl!("Value:")).color(t.text_muted));+ + + ui.add_enabled(editable, widgets::line(&mut d.value).desired_width(420.0).background_color(t.field).id_salt("custom-value"))+ + + .labelled_by(l.id);+ + + ui.end_row();+ + + // Untrimmed: a file's `/Project#20` is not `/Project`, and a typed space is refused.+ + + let name = d.name.clone();+ + + let value = d.value.trim().to_owned();+ + + let listed = d.props.iter().position(|(k, _)| *k == name);+ + + // An entry the list leaves out (not text, only padding, or past its 256) keeps its value.+ + + let file_props = doc.custom_info();+ + + let unlisted = doc.has_info(&name) && !file_props.iter().any(|(k, _)| *k == name);+ + + let refused = pdfcraft_engine::check_custom_key(&name).err().filter(|_| !name.is_empty()).map(|e| e.to_string());+ + + ui.label("");+ + + // A file can hold a custom name that `check_custom_key` refuses, such as one+ + + // with a space: the tab lists it, and Add, Update and Delete stay off for it.+ + + let why = |b: egui::Response| match &refused {+ + + Some(why) => b.on_disabled_hover_text(crate::i18n::words(why)),+ + + None => b,};+ + + // A name that isn't UTF-8 is listed with U+FFFD and can't be written back as it is.+ + + let editable = editable && refused.is_none() && !name.contains(char::REPLACEMENT_CHARACTER);+ + + // `custom_info` lists at most 256 properties, and a new name goes after the file's+ + + // entries, so Add is off once the draft or the file's own list holds 256.+ + + let room = d.props.len() < 256 && file_props.len() < 256;ui.horizontal(|ui| {- - - let l = ui.label(tl!("Pages"));- - - ui.add(egui::TextEdit::singleline(&mut app.extract_draft.pages).hint_text(hint).desired_width(240.0)).labelled_by(l.id);- - - });- - - let chosen = app.extract_draft.pages_to_extract(selected, total);- - - match &chosen {- - - Ok(pages) if pages.len() == 1 => {- - - ui.label(tl!("1 page selected."));+ + + let add = editable && room && listed.is_none() && !unlisted && !name.is_empty() && !value.is_empty();+ + + if why(ui.add_enabled(add, egui::Button::new(tl!("Add")))).clicked() {+ + + d.props.push((name.clone(), value.clone()));+ + + d.name.clear();+ + + d.value.clear();}- - - Ok(pages) => {- - - ui.label(crate::i18n::fmt(tl!("{n} pages selected."), &[("n", &pages.len().to_string())]));+ + + let update = editable && !value.is_empty() && listed.and_then(|n| d.props.get(n)).is_some_and(|(_, v)| *v != value);+ + + if why(ui.add_enabled(update, egui::Button::new(tl!("Update")))).clicked()+ + + && let Some(p) = listed.and_then(|n| d.props.get_mut(n))+ + + {+ + + p.1 = value.clone();}- - - Err(e) => {- - - ui.colored_label(ui.visuals().error_fg_color, e);+ + + if why(ui.add_enabled(editable && listed.is_some(), egui::Button::new(tl!("Delete")))).clicked()+ + + && let Some(n) = listed.filter(|n| *n < d.props.len())+ + + {+ + + d.props.remove(n);+ + + d.name.clear();+ + + d.value.clear();}- - - }- - - ui.add_space(4.0);- - - // The name the pages are saved under (#737); separate files add " (page N)".- - - ui.horizontal(|ui| {- - - let l = ui.label(tl!("File name"));- - - ui.add(egui::TextEdit::singleline(&mut app.extract_draft.name).desired_width(240.0)).labelled_by(l.id);});- - - ui.add(widgets::checkbox(&mut app.extract_draft.delete, tl!("Delete pages after extracting")));- - - ui.add(widgets::checkbox(&mut app.extract_draft.separate, tl!("Extract pages as separate files")));- - - ui.add_space(12.0);- - - ui.with_layout(Layout::right_to_left(Align::Center), |ui| {- - - if ui.add_enabled_ui(chosen.is_ok(), |ui| widgets::pill_button(ui, tl!("Extract"), true)).inner.clicked() {- - - extract_now = true;- - - close = true;- - - }- - - if widgets::pill_button(ui, tl!("Cancel"), false).clicked() {- - - close = true;+ + + ui.end_row();+ + + if d.props.is_empty() {+ + + ui.label("");+ + + ui.label(egui::RichText::new(tl!("None")).color(t.text_faint));+ + + ui.end_row();+ + + }+ + + // A click on a property fills the fields with it; values are document data.+ + + let mut picked = None;+ + + for (k, v) in &d.props {+ + + if ui.selectable_label(*k == name, k.as_str()).clicked() {+ + + picked = Some((k.clone(), v.clone()));}- - - });- - - return;+ + + ui.scope(|ui| {+ + + ui.set_max_width(420.0);+ + + ui.add(egui::Label::new(v.as_str()).wrap());+ + + });+ + + ui.end_row();+ + + }+ + + if let Some((k, v)) = picked {+ + + d.name = k;+ + + d.value = v;+ + + }}- - - Dialog::RotatePages => {- - - use pdfcraft_engine::{PageOrientation as O, PageParity as P};- - - let n = app.active_ids().and_then(|(_, id)| app.session.get(id)).map_or(1, |d| d.info.pages.len());- - - let d = &mut app.rotate_draft;- - - ui.label(egui::RichText::new(tl!("Rotate Pages")).font(theme::semibold(18.0)));- - - ui.add_space(8.0);- - - egui::Grid::new("rotate-pages").num_columns(2).spacing([12.0, 8.0]).show(ui, |ui| {- - - ui.label(tl!("Direction:"));- - - egui::ComboBox::from_id_salt("rotate-dir")- - - .selected_text(match d.degrees {- - - 270 => tl!("Counterclockwise 90 degrees"),- - - 180 => tl!("180 degrees"),- - - _ => tl!("Clockwise 90 degrees"),- - - })- - - .show_ui(ui, |ui| {- - - ui.selectable_value(&mut d.degrees, 90, tl!("Clockwise 90 degrees"));- - - ui.selectable_value(&mut d.degrees, 270, tl!("Counterclockwise 90 degrees"));- - - ui.selectable_value(&mut d.degrees, 180, tl!("180 degrees"));+ + + PropsTab::Advanced => {+ + + row(ui, "PDF version", i.pdf_version.clone());+ + + path_row(ui, "Location", doc.path.clone().unwrap_or_default());+ + + row(ui, "File size", format!("{} ({})", human_size(i.file_size), crate::panels::byte_count(i.file_size)));+ + + let p = &i.pages[0];+ + + row(ui, "Page size", units.size(f64::from(p.width), f64::from(p.height)));+ + + row(ui, "Number of pages", i.pages.len().to_string());+ + + row(ui, "Tagged PDF", yes(i.tagged));+ + + row(ui, "Form fields", i.fields.len().to_string());+ + + row(ui, "Comments", i.annotations.len().to_string());+ + + row(ui, "Layers", i.layers.len().to_string());+ + + row(ui, "Attachments", i.attachments.len().to_string());+ + + row(ui, "JavaScript", yes(i.has_javascript));+ + + // Each incremental update is a revision; earlier ones open as their own document.+ + + let ends = doc.revision_ends();+ + + if ends.len() > 1 {+ + + ui.label(egui::RichText::new(tl!("Revisions")).color(t.text_muted));+ + + // Reserve the full wrapped height before the grid starts the next row.+ + + ui.vertical(|ui| {+ + + ui.horizontal_wrapped(|ui| {+ + + ui.label(ends.len().to_string());+ + + for n in (1..ends.len()).rev().take(12) {+ + + if ui+ + + .small_button(crate::i18n::fmt(tl!("View revision {n}"), &[("n", &n.to_string())]))+ + + .on_hover_text(tl!("Open the file as it was saved then"))+ + + .clicked()+ + + {+ + + req.open_revision = Some(n);+ + + }+ + + }});+ + + });ui.end_row();- - - ui.label(tl!("Pages:"));- - - ui.vertical(|ui| {- - - widgets::radio_value(ui, &mut d.which, 0, tl!("All"));- - - widgets::radio_value(ui, &mut d.which, 1, tl!("Selection"));+ + + }+ + + // Reading Options: binding and language.+ + + if let Some((_, v)) = app.view_draft.as_mut() {+ + + let editable = doc.allows_modification();+ + + ui.label(egui::RichText::new(tl!("Binding")).color(t.text_muted));+ + + ui.add_enabled_ui(editable, |ui| {ui.horizontal(|ui| {- - - widgets::radio_value(ui, &mut d.which, 2, tl!("From"));- - - ui.add_enabled(d.which == 2, egui::DragValue::new(&mut d.from).range(1..=n));- - - ui.label(tl!("to"));- - - ui.add_enabled(d.which == 2, egui::DragValue::new(&mut d.to).range(1..=n));- - - ui.label(crate::i18n::fmt(tl!("of {name}"), &[("name", &n.to_string())]));+ + + widgets::radio_value(ui, &mut v.right_to_left, false, tl!("Left Edge"));+ + + widgets::radio_value(ui, &mut v.right_to_left, true, tl!("Right Edge"));});});ui.end_row();- - - ui.label(tl!("Rotate:"));- - - egui::ComboBox::from_id_salt("rotate-parity")- - - .selected_text(match d.parity {- - - P::Both => tl!("Even and Odd Pages"),- - - P::Even => tl!("Even Pages Only"),- - - P::Odd => tl!("Odd Pages Only"),- - - })- - - .show_ui(ui, |ui| {- - - ui.selectable_value(&mut d.parity, P::Both, tl!("Even and Odd Pages"));- - - ui.selectable_value(&mut d.parity, P::Even, tl!("Even Pages Only"));- - - ui.selectable_value(&mut d.parity, P::Odd, tl!("Odd Pages Only"));- - - });+ + + let l = ui.label(egui::RichText::new(tl!("Language")).color(t.text_muted));+ + + let mut lang = v.language.clone().unwrap_or_default();+ + + if ui+ + + .add_enabled(editable, widgets::line(&mut lang).hint_text(tl!("e.g. en-US")).desired_width(160.0))+ + + .labelled_by(l.id)+ + + .changed()+ + + {+ + + v.language = (!lang.trim().is_empty()).then(|| lang.trim().to_string());+ + + }ui.end_row();+ + + }+ + + // What was repaired while reading a damaged file (fidelity: never silent).+ + + let repairs = doc.repair_log();+ + + row(ui, "Repairs", if repairs.is_empty() { tl!("None").to_string() } else { repairs.len().to_string() });+ + + if !repairs.is_empty() {ui.label("");- - - egui::ComboBox::from_id_salt("rotate-orient")- - - .selected_text(match d.orientation {- - - O::Both => tl!("Landscape and Portrait Pages"),- - - O::Landscape => tl!("Landscape Pages"),- - - O::Portrait => tl!("Portrait Pages"),- - - })- - - .show_ui(ui, |ui| {- - - ui.selectable_value(&mut d.orientation, O::Both, tl!("Landscape and Portrait Pages"));- - - ui.selectable_value(&mut d.orientation, O::Landscape, tl!("Landscape Pages"));- - - ui.selectable_value(&mut d.orientation, O::Portrait, tl!("Portrait Pages"));- - - });+ + + egui::CollapsingHeader::new(tl!("Repair log")).show(ui, |ui| {+ + + for r in &repairs {+ + + ui.add(egui::Label::new(egui::RichText::new(r).small()).wrap());+ + + }+ + + });ui.end_row();- - - });- - - d.to = d.to.max(d.from);- - - ui.add_space(12.0);- - - ui.with_layout(Layout::right_to_left(Align::Center), |ui| {- - - if widgets::pill_button(ui, tl!("OK"), true).clicked() {- - - rotate_now = true;- - - close = true;- - - }- - - if widgets::pill_button(ui, tl!("Cancel"), false).clicked() {- - - close = true;- - - }- - - });- - - return;- - - }- - - Dialog::DuplicateField => {- - - let n = app.active_ids().and_then(|(_, id)| app.session.get(id)).map_or(1, |d| d.info.pages.len());- - - let Some(d) = app.duplicate_draft.as_mut() else {- - - close = true;- - - return;- - - };- - - ui.label(egui::RichText::new(tl!("Duplicate Field")).font(theme::semibold(18.0)));- - - ui.add_space(8.0);- - - ui.label(crate::i18n::fmt(tl!("Duplicate \"{name}\" onto:"), &[("name", &d.name)]));- - - widgets::radio_value(ui, &mut d.all, true, tl!("All pages"));- - - ui.horizontal(|ui| {- - - widgets::radio_value(ui, &mut d.all, false, tl!("From"));- - - ui.add_enabled(!d.all, egui::DragValue::new(&mut d.from).range(1..=n));- - - ui.label(tl!("to"));- - - ui.add_enabled(!d.all, egui::DragValue::new(&mut d.to).range(1..=n));- - - ui.label(crate::i18n::fmt(tl!("of {name}"), &[("name", &n.to_string())]));- - - });- - - d.to = d.to.max(d.from);- - - ui.add_space(12.0);- - - ui.with_layout(Layout::right_to_left(Align::Center), |ui| {- - - if widgets::pill_button(ui, tl!("OK"), true).clicked() {- - - let pages: Vec<usize> = if d.all { (0..n).collect() } else { (d.from - 1..d.to.min(n)).collect() };- - - duplicate_now = Some(Edit::DuplicateField { name: d.name.clone(), pages });- - - close = true;- - - }- - - if widgets::pill_button(ui, tl!("Cancel"), false).clicked() {- - - close = true;- - - }- - - });- - - return;- - - }- - - // Never reached: `dialogs` shows this movable window above and returns before the modal.- - - // The arm keeps the match exhaustive.- - - Dialog::FieldTable => close = true,- - - Dialog::Optimize => {- - - let (ok, cancel) = crate::optimize_ui::body(ui, &mut app.optimize_draft, &t);- - - optimize_now = ok;- - - close = ok || cancel;- - - if std::mem::take(&mut app.optimize_draft.audit) {- - - app.refresh_space_audit();- - - next = Dialog::AuditSpace;}- - - return;}- - - Dialog::CertificateViewer => {- - - ui.set_width(700.0);- - - let trusted = app.session.trusted_certificates().to_vec();- - - let Some(v) = app.cert_viewer.as_mut() else {- - - close = true;- - - return;- - - };- - - let (done, action) = crate::sign_ui::cert_viewer(ui, v, &trusted, &t);- - - close = done;- - - match action {- - - Some(crate::sign_ui::CertAction::Trust(c)) => app.trust_certificate(*c),- - - Some(crate::sign_ui::CertAction::Export(c)) => {- - - app.export_certificate(&c);- - - }- - - None => {}- - - }- - - return;+ + + // Laid out above, outside the two-column grid.+ + + PropsTab::SpaceAudit => {}+ + + });+ + + });+ + + true+ + + }+ + ++ + + /// `Dialog::Split` content. Returns `false` when it has its own buttons and no footer is wanted.+ + + fn dialog_split(ui: &mut egui::Ui, app: &mut PdfCraftApp, req: &mut Pending) -> bool {+ + + let t = Tokens::get(ui.ctx());+ + + ui.label(egui::RichText::new(tl!("Split document")).font(theme::semibold(18.0)));+ + + ui.add_space(8.0);+ + + let Some((vi, id)) = app.active_ids() else { return false };+ + + let n = app.session.get(id).map(|d| d.info.pages.len()).unwrap_or(0);+ + + let selected: Vec<usize> = app.views[vi].selected.iter().copied().filter(|p| *p > 0).collect();+ + + let marks = app.session.bookmark_splits(id);+ + + let draft = &mut app.split_draft;+ + + use crate::SplitMode as M;+ + + if selected.is_empty() && draft.mode == M::Selection {+ + + draft.mode = M::Pages;+ + + }+ + + widgets::radio_value(ui, &mut draft.mode, M::Pages, tl!("Number of pages"));+ + + ui.add_enabled_ui(draft.mode == M::Pages, |ui| {+ + + ui.horizontal(|ui| {+ + + ui.add_space(24.0);+ + + ui.label(tl!("Pages per file"));+ + + ui.add(egui::DragValue::new(&mut draft.every).range(1..=n.max(1)));+ + + });+ + + });+ + + widgets::radio_value(ui, &mut draft.mode, M::Size, tl!("File size"));+ + + ui.add_enabled_ui(draft.mode == M::Size, |ui| {+ + + ui.horizontal(|ui| {+ + + ui.add_space(24.0);+ + + ui.label(tl!("At most"));+ + + ui.add(egui::DragValue::new(&mut draft.size_mb).range(0.05..=2000.0).speed(0.1).suffix(" MB"));+ + + });+ + + });+ + + ui.add_enabled_ui(!marks.is_empty(), |ui| {+ + + widgets::radio_value(+ + + ui,+ + + &mut draft.mode,+ + + M::Bookmarks,+ + + crate::i18n::fmt(tl!("Top-level bookmarks ({n})"), &[("n", &marks.len().to_string())]),+ + + )+ + + });+ + + ui.add_enabled_ui(!selected.is_empty(), |ui| {+ + + widgets::radio_value(ui, &mut draft.mode, M::Selection, tl!("Before each selected page (select pages in Organize)"))+ + + });+ + + let plan = match draft.mode {+ + + M::Pages => crate::SplitPlan::By(pdfcraft_engine::SplitBy::PageCount(draft.every)),+ + + M::Selection => crate::SplitPlan::By(pdfcraft_engine::SplitBy::Before(selected)),+ + + M::Size => crate::SplitPlan::Size((draft.size_mb * 1_048_576.0) as usize),+ + + M::Bookmarks => crate::SplitPlan::Bookmarks,+ + + };+ + + let files = match &plan {+ + + crate::SplitPlan::By(by) => Some(pdfcraft_engine::split_ranges(n, by).len()),+ + + crate::SplitPlan::Bookmarks => {+ + + Some(pdfcraft_engine::split_ranges(n, &pdfcraft_engine::SplitBy::Before(marks.iter().map(|m| m.0).collect())).len())+ + + }+ + + crate::SplitPlan::Size(_) => None,+ + + };+ + + ui.add_space(8.0);+ + + let text = match files {+ + + Some(f) => {+ + + if f == 1 {+ + + crate::i18n::fmt(tl!("Creates 1 file from {n} pages."), &[("n", &n.to_string())])+ + + } else {+ + + crate::i18n::fmt(tl!("Creates {f} files from {n} pages."), &[("f", &f.to_string()), ("n", &n.to_string())])}- - - Dialog::AuditSpace => {- - - if crate::optimize_ui::audit_body(ui, &app.space_audit, &t) {- - - next = Dialog::Optimize;- - - }- - - return;+ + + }+ + + None => crate::i18n::fmt(tl!("Each file holds as many of the {n} pages as fit."), &[("n", &n.to_string())]),+ + + };+ + + ui.label(egui::RichText::new(text).color(t.text_muted));+ + + if files.is_none_or(|f| f > 1) {+ + + req.split_ready = Some(plan);+ + + }+ + + true+ + + }+ + ++ + + /// `Dialog::ReplacePages` content. Returns `false` when it has its own buttons and no footer is wanted.+ + + fn dialog_replace_pages(ui: &mut egui::Ui, app: &mut PdfCraftApp, req: &mut Pending) -> bool {+ + + let t = Tokens::get(ui.ctx());+ + + let count = app.active_ids().and_then(|(_, id)| app.session.get(id)).map(|d| d.info.pages.len()).unwrap_or(1).max(1);+ + + let Some(d) = app.replace_draft.as_mut() else {+ + + req.close = true;+ + + return false;+ + + };+ + + ui.label(egui::RichText::new(tl!("Replace Pages")).font(theme::semibold(18.0)));+ + + ui.add_space(8.0);+ + + d.to = d.to.clamp(1, count);+ + + d.from = d.from.clamp(1, d.to);+ + + ui.horizontal(|ui| {+ + + let from_label = ui.label(tl!("Original: replace pages"));+ + + let from = ui.add(egui::DragValue::new(&mut d.from).range(1..=count)).labelled_by(from_label.id);+ + + let to_label = ui.label(tl!("to"));+ + + let to = ui.add(egui::DragValue::new(&mut d.to).range(1..=count)).labelled_by(to_label.id);+ + + if from.changed() || to.changed() {+ + + d.range_edited = true;+ + + }+ + + ui.label(egui::RichText::new(crate::i18n::fmt(tl!("of {name}"), &[("name", &count.to_string())])).color(t.text_muted));+ + + });+ + + let n = if d.range_edited { d.to - d.from + 1 } else { d.pages.len().max(1) };+ + + let max_start = d.src_pages.saturating_sub(n) + 1;+ + + d.src_from = d.src_from.clamp(1, max_start.max(1));+ + + ui.horizontal(|ui| {+ + + let replacement_label = ui.label(crate::i18n::fmt(tl!("Replacement: pages of {name}"), &[("name", &d.name)]));+ + + ui.add(egui::DragValue::new(&mut d.src_from).range(1..=max_start.max(1))).labelled_by(replacement_label.id);+ + + ui.label(crate::i18n::fmt(tl!("to {n}"), &[("n", &(d.src_from + n - 1).to_string())]));+ + + ui.label(egui::RichText::new(crate::i18n::fmt(tl!("of {name}"), &[("name", &d.src_pages.to_string())])).color(t.text_muted));+ + + });+ + + let fits = n <= d.src_pages;+ + + ui.add_space(6.0);+ + + ui.label(+ + + egui::RichText::new(if fits {+ + + tl!("Only the page content changes: links, comments, form fields and bookmarks on the original pages stay.")+ + + } else {+ + + tl!("The replacement file doesn't have that many pages.")+ + + })+ + + .small()+ + + .color(t.text_faint),+ + + );+ + + ui.add_space(10.0);+ + + ui.with_layout(Layout::right_to_left(Align::Center), |ui| {+ + + if ui.add_enabled_ui(fits, |ui| widgets::pill_button(ui, tl!("OK"), true)).inner.clicked() {+ + + req.replace_now = true;+ + + req.close = true;+ + + }+ + + if widgets::pill_button(ui, tl!("Cancel"), false).clicked() {+ + + req.close = true;+ + + }+ + + });+ + + false+ + + }+ + ++ + + /// `Dialog::RedactProps` content. Returns `false` when it has its own buttons and no footer is wanted.+ + + fn dialog_redact_props(ui: &mut egui::Ui, app: &mut PdfCraftApp, req: &mut Pending) -> bool {+ + + let t = Tokens::get(ui.ctx());+ + + let mut prefs = app.redact_prefs.clone();+ + + let (ok, cancel) = crate::redact_ui::props_body(ui, &mut prefs, &t);+ + + app.redact_prefs = prefs;+ + + if ok && app.redact_prefs.remember {+ + + app.redact_defaults = app.redact_prefs.clone();+ + + }+ + + if cancel && let Some(before) = app.redact_before.take() {+ + + app.redact_prefs = before;+ + + }+ + + if ok {+ + + app.redact_before = None;+ + + }+ + + req.close = ok || cancel;+ + + false+ + + }+ + ++ + + /// `Dialog::Extract` content. Returns `false` when it has its own buttons and no footer is wanted.+ + + fn dialog_extract(ui: &mut egui::Ui, app: &mut PdfCraftApp, req: &mut Pending) -> bool {+ + + let (selected, total) = app.active_ids().map_or((Vec::new(), 0), |(i, _)| (app.views[i].target_pages(), app.views[i].page_count()));+ + + ui.label(egui::RichText::new(tl!("Extract pages")).font(theme::semibold(18.0)));+ + + ui.add_space(8.0);+ + + // Page ranges to take instead of the selection (#3593); the hint is the selection.+ + + let hint = match crate::combine_ui::range_of(&selected, total) {+ + + all if all.is_empty() && total > 1 => format!("1-{total}"),+ + + all if all.is_empty() => "1".to_string(),+ + + some => some,+ + + };+ + + ui.horizontal(|ui| {+ + + let l = ui.label(tl!("Pages"));+ + + ui.add(egui::TextEdit::singleline(&mut app.extract_draft.pages).hint_text(hint).desired_width(240.0)).labelled_by(l.id);+ + + });+ + + let chosen = app.extract_draft.pages_to_extract(selected, total);+ + + match &chosen {+ + + Ok(pages) if pages.len() == 1 => {+ + + ui.label(tl!("1 page selected."));+ + + }+ + + Ok(pages) => {+ + + ui.label(crate::i18n::fmt(tl!("{n} pages selected."), &[("n", &pages.len().to_string())]));+ + + }+ + + Err(e) => {+ + + ui.colored_label(ui.visuals().error_fg_color, e);+ + + }+ + + }+ + + ui.add_space(4.0);+ + + // The name the pages are saved under (#737); separate files add " (page N)".+ + + ui.horizontal(|ui| {+ + + let l = ui.label(tl!("File name"));+ + + ui.add(egui::TextEdit::singleline(&mut app.extract_draft.name).desired_width(240.0)).labelled_by(l.id);+ + + });+ + + ui.add(widgets::checkbox(&mut app.extract_draft.delete, tl!("Delete pages after extracting")));+ + + ui.add(widgets::checkbox(&mut app.extract_draft.separate, tl!("Extract pages as separate files")));+ + + ui.add_space(12.0);+ + + ui.with_layout(Layout::right_to_left(Align::Center), |ui| {+ + + if ui.add_enabled_ui(chosen.is_ok(), |ui| widgets::pill_button(ui, tl!("Extract"), true)).inner.clicked() {+ + + req.extract_now = true;+ + + req.close = true;+ + + }+ + + if widgets::pill_button(ui, tl!("Cancel"), false).clicked() {+ + + req.close = true;+ + + }+ + + });+ + + false+ + + }+ + ++ + + /// `Dialog::RotatePages` content. Returns `false` when it has its own buttons and no footer is wanted.+ + + fn dialog_rotate_pages(ui: &mut egui::Ui, app: &mut PdfCraftApp, req: &mut Pending) -> bool {+ + + use pdfcraft_engine::{PageOrientation as O, PageParity as P};+ + + let n = app.active_ids().and_then(|(_, id)| app.session.get(id)).map_or(1, |d| d.info.pages.len());+ + + let d = &mut app.rotate_draft;+ + + ui.label(egui::RichText::new(tl!("Rotate Pages")).font(theme::semibold(18.0)));+ + + ui.add_space(8.0);+ + + egui::Grid::new("rotate-pages").num_columns(2).spacing([12.0, 8.0]).show(ui, |ui| {+ + + ui.label(tl!("Direction:"));+ + + craft_ui::ComboBox::from_id_salt("rotate-dir")+ + + .selected_text(match d.degrees {+ + + 270 => tl!("Counterclockwise 90 degrees"),+ + + 180 => tl!("180 degrees"),+ + + _ => tl!("Clockwise 90 degrees"),+ + + })+ + + .show_ui(ui, |ui| {+ + + ui.selectable_value(&mut d.degrees, 90, tl!("Clockwise 90 degrees"));+ + + ui.selectable_value(&mut d.degrees, 270, tl!("Counterclockwise 90 degrees"));+ + + ui.selectable_value(&mut d.degrees, 180, tl!("180 degrees"));+ + + });+ + + ui.end_row();+ + + ui.label(tl!("Pages:"));+ + + ui.vertical(|ui| {+ + + widgets::radio_value(ui, &mut d.which, 0, tl!("All"));+ + + widgets::radio_value(ui, &mut d.which, 1, tl!("Selection"));+ + + ui.horizontal(|ui| {+ + + widgets::radio_value(ui, &mut d.which, 2, tl!("From"));+ + + ui.add_enabled(d.which == 2, egui::DragValue::new(&mut d.from).range(1..=n));+ + + ui.label(tl!("to"));+ + + ui.add_enabled(d.which == 2, egui::DragValue::new(&mut d.to).range(1..=n));+ + + ui.label(crate::i18n::fmt(tl!("of {name}"), &[("name", &n.to_string())]));+ + + });+ + + });+ + + ui.end_row();+ + + ui.label(tl!("Rotate:"));+ + + craft_ui::ComboBox::from_id_salt("rotate-parity")+ + + .selected_text(match d.parity {+ + + P::Both => tl!("Even and Odd Pages"),+ + + P::Even => tl!("Even Pages Only"),+ + + P::Odd => tl!("Odd Pages Only"),+ + + })+ + + .show_ui(ui, |ui| {+ + + ui.selectable_value(&mut d.parity, P::Both, tl!("Even and Odd Pages"));+ + + ui.selectable_value(&mut d.parity, P::Even, tl!("Even Pages Only"));+ + + ui.selectable_value(&mut d.parity, P::Odd, tl!("Odd Pages Only"));+ + + });+ + + ui.end_row();+ + + ui.label("");+ + + craft_ui::ComboBox::from_id_salt("rotate-orient")+ + + .selected_text(match d.orientation {+ + + O::Both => tl!("Landscape and Portrait Pages"),+ + + O::Landscape => tl!("Landscape Pages"),+ + + O::Portrait => tl!("Portrait Pages"),+ + + })+ + + .show_ui(ui, |ui| {+ + + ui.selectable_value(&mut d.orientation, O::Both, tl!("Landscape and Portrait Pages"));+ + + ui.selectable_value(&mut d.orientation, O::Landscape, tl!("Landscape Pages"));+ + + ui.selectable_value(&mut d.orientation, O::Portrait, tl!("Portrait Pages"));+ + + });+ + + ui.end_row();+ + + });+ + + d.to = d.to.max(d.from);+ + + ui.add_space(12.0);+ + + ui.with_layout(Layout::right_to_left(Align::Center), |ui| {+ + + if widgets::pill_button(ui, tl!("OK"), true).clicked() {+ + + req.rotate_now = true;+ + + req.close = true;+ + + }+ + + if widgets::pill_button(ui, tl!("Cancel"), false).clicked() {+ + + req.close = true;+ + + }+ + + });+ + + false+ + + }+ + ++ + + /// `Dialog::DuplicateField` content. Returns `false` when it has its own buttons and no footer is wanted.+ + + fn dialog_duplicate_field(ui: &mut egui::Ui, app: &mut PdfCraftApp, req: &mut Pending) -> bool {+ + + let n = app.active_ids().and_then(|(_, id)| app.session.get(id)).map_or(1, |d| d.info.pages.len());+ + + let Some(d) = app.duplicate_draft.as_mut() else {+ + + req.close = true;+ + + return false;+ + + };+ + + ui.label(egui::RichText::new(tl!("Duplicate Field")).font(theme::semibold(18.0)));+ + + ui.add_space(8.0);+ + + ui.label(crate::i18n::fmt(tl!("Duplicate \"{name}\" onto:"), &[("name", &d.name)]));+ + + widgets::radio_value(ui, &mut d.all, true, tl!("All pages"));+ + + ui.horizontal(|ui| {+ + + widgets::radio_value(ui, &mut d.all, false, tl!("From"));+ + + ui.add_enabled(!d.all, egui::DragValue::new(&mut d.from).range(1..=n));+ + + ui.label(tl!("to"));+ + + ui.add_enabled(!d.all, egui::DragValue::new(&mut d.to).range(1..=n));+ + + ui.label(crate::i18n::fmt(tl!("of {name}"), &[("name", &n.to_string())]));+ + + });+ + + d.to = d.to.max(d.from);+ + + ui.add_space(12.0);+ + + ui.with_layout(Layout::right_to_left(Align::Center), |ui| {+ + + if widgets::pill_button(ui, tl!("OK"), true).clicked() {+ + + let pages: Vec<usize> = if d.all { (0..n).collect() } else { (d.from - 1..d.to.min(n)).collect() };+ + + req.duplicate_now = Some(Edit::DuplicateField { name: d.name.clone(), pages });+ + + req.close = true;+ + + }+ + + if widgets::pill_button(ui, tl!("Cancel"), false).clicked() {+ + + req.close = true;+ + + }+ + + });+ + + false+ + + }+ + ++ + + /// `Dialog::CertificateViewer` content. Returns `false` when it has its own buttons and no footer is wanted.+ + + fn dialog_certificate_viewer(ui: &mut egui::Ui, app: &mut PdfCraftApp, req: &mut Pending) -> bool {+ + + let t = Tokens::get(ui.ctx());+ + + ui.set_width(700.0);+ + + let trusted = app.session.trusted_certificates().to_vec();+ + + let Some(v) = app.cert_viewer.as_mut() else {+ + + req.close = true;+ + + return false;+ + + };+ + + let (done, action) = crate::sign_ui::cert_viewer(ui, v, &trusted, &t);+ + + req.close = done;+ + + match action {+ + + Some(crate::sign_ui::CertAction::Trust(c)) => app.trust_certificate(*c),+ + + Some(crate::sign_ui::CertAction::Export(c)) => {+ + + app.export_certificate(&c);+ + + }+ + + None => {}+ + + }+ + + false+ + + }+ + ++ + + /// `Dialog::SummarizeComments` content. Returns `false` when it has its own buttons and no footer is wanted.+ + + fn dialog_summarize_comments(ui: &mut egui::Ui, app: &mut PdfCraftApp, req: &mut Pending) -> bool {+ + + ui.label(egui::RichText::new(tl!("Summarize Options")).font(theme::semibold(18.0)));+ + + ui.add_space(8.0);+ + + ui.label(tl!("Choose a layout:"));+ + + let _ = ui.add(widgets::radio(true, tl!("Comments only")));+ + + ui.add_space(6.0);+ + + ui.horizontal(|ui| {+ + + ui.label(tl!("Sort comments by:"));+ + + craft_ui::ComboBox::from_id_salt("summary-sort").selected_text(tl!(app.summary_sort.name())).show_ui(ui, |ui| {+ + + for s in pdfcraft_engine::SummarySort::ALL {+ + + ui.selectable_value(&mut app.summary_sort, s, tl!(s.name()));}- - - Dialog::Sign => {- - - if crate::sign_ui::dialog(ui, app, &t) {- - - app.sign_draft = None;- - - close = true;- - - }- - - return;+ + + });+ + + });+ + + ui.add_space(12.0);+ + + ui.with_layout(Layout::right_to_left(Align::Center), |ui| {+ + + if widgets::pill_button(ui, tl!("Create PDF Comment Summary"), true).clicked() {+ + + req.summarize_now = true;+ + + req.close = true;+ + + }+ + + if widgets::pill_button(ui, tl!("Cancel"), false).clicked() {+ + + req.close = true;+ + + }+ + + });+ + + false+ + + }+ + ++ + + /// `Dialog::Revert` content. Returns `false` when it has its own buttons and no footer is wanted.+ + + fn dialog_revert(ui: &mut egui::Ui, app: &mut PdfCraftApp, req: &mut Pending) -> bool {+ + + let name = app.active_ids().and_then(|(_, id)| app.session.get(id)).map(|d| d.name.clone()).unwrap_or_default();+ + + ui.label(egui::RichText::new(tl!("Revert")).font(theme::semibold(18.0)));+ + + ui.add_space(8.0);+ + + ui.label(crate::i18n::fmt(+ + + tl!("Revert to the previously saved version of “{name}”? Changes since then can't be undone afterwards."),+ + + &[("name", &name)],+ + + ));+ + + ui.add_space(12.0);+ + + ui.with_layout(Layout::right_to_left(Align::Center), |ui| {+ + + if widgets::pill_button(ui, tl!("Revert"), true).clicked() {+ + + req.revert_now = true;+ + + req.close = true;+ + + }+ + + if widgets::pill_button(ui, tl!("Cancel"), false).clicked() {+ + + req.close = true;+ + + }+ + + });+ + + false+ + + }+ + ++ + + /// `Dialog::OverwriteChanged` content. Returns `false` when it has its own buttons and no footer is wanted.+ + + fn dialog_overwrite_changed(ui: &mut egui::Ui, app: &mut PdfCraftApp, req: &mut Pending) -> bool {+ + + #[cfg(not(target_arch = "wasm32"))]+ + + let name = app.pending_overwrite.as_ref().and_then(|p| app.session.get(p.id)).map(|d| d.name.clone()).unwrap_or_default();+ + + #[cfg(target_arch = "wasm32")]+ + + let name = String::new();+ + + ui.label(egui::RichText::new(tl!("Save over the changed file?")).font(theme::semibold(18.0)));+ + + ui.add_space(8.0);+ + + ui.label(crate::i18n::fmt(+ + + tl!("“{name}” changed on disk after it was opened or last saved. Saving now replaces that newer version with this one."),+ + + &[("name", &name)],+ + + ));+ + + ui.add_space(12.0);+ + + ui.with_layout(Layout::right_to_left(Align::Center), |ui| {+ + + if widgets::pill_button(ui, tl!("Save anyway"), true).clicked() {+ + + req.overwrite_now = true;+ + + req.close = true;+ + + }+ + + if widgets::pill_button(ui, tl!("Save as…"), false).clicked() {+ + + req.overwrite_elsewhere = true;+ + + req.close = true;+ + + }+ + + if widgets::pill_button(ui, tl!("Cancel"), false).clicked() {+ + + req.close = true;+ + + }+ + + });+ + + false+ + + }+ + ++ + + /// `Dialog::Print` content. Returns `false` when it has its own buttons and no footer is wanted.+ + + fn dialog_print(ui: &mut egui::Ui, app: &mut PdfCraftApp, req: &mut Pending) -> bool {+ + + let t = Tokens::get(ui.ctx());+ + + let Some((i, id)) = app.active_ids() else {+ + + req.close = true;+ + + return false;+ + + };+ + + if app.print_draft.handling == crate::print_ui::Handling::Label {+ + + app.read_label_crops(id);+ + + }+ + + let Some(doc) = app.session.get(id) else { return false };+ + + let sizes: Vec<(f64, f64)> = doc.info.pages.iter().map(|p| (p.width as f64, p.height as f64)).collect();+ + + let labels: Vec<String> = doc.info.pages.iter().map(|p| p.label.clone()).collect();+ + + let rasters = crate::print_ui::preview_rasters(+ + + &app.print_draft,+ + + &sizes,+ + + &labels,+ + + ui.ctx().pixels_per_point(),+ + + ui.ctx().input(|i| i.max_texture_side) as f32,+ + + );+ + + let view = &mut app.views[i];+ + + view.set_print_grayscale(app.print_draft.grayscale);+ + + view.queue_print_previews(&rasters);+ + + let (go, cancel) = crate::print_ui::body(ui, &mut app.print_draft, &t, &sizes, &labels, &mut |p| {+ + + view.need_thumbnail(p, true);+ + + view.page_preview(p)+ + + });+ + + req.print_go = go;+ + + req.close = go || cancel;+ + + false+ + + }+ + ++ + + /// `Dialog::Signature` content. Returns `false` when it has its own buttons and no footer is wanted.+ + + fn dialog_signature(ui: &mut egui::Ui, app: &mut PdfCraftApp, req: &mut Pending) -> bool {+ + + let t = Tokens::get(ui.ctx());+ + + let (go, cancel, browse) =+ + + crate::fill_sign::signature_pad(ui, &t, &mut app.signature_draft, &mut app.signature_preview, &mut app.signature_photo);+ + + req.apply = go;+ + + if browse {+ + + app.pick_signature_image();+ + + }+ + + if req.apply {+ + + let d = std::mem::take(&mut app.signature_draft);+ + + let tool = if d.initials {+ + + app.initials = d.saved();+ + + crate::fill_sign::FillTool::Initials+ + + } else {+ + + app.signature = d.saved();+ + + crate::fill_sign::FillTool::Signature+ + + };+ + + app.quick_tool = crate::QuickTool::Fill(tool);+ + + app.toast = None;+ + + }+ + + req.close = req.apply || cancel;+ + + false+ + + }+ + ++ + + /// `Dialog::Preferences` content. Returns `false` when it has its own buttons and no footer is wanted.+ + + fn dialog_preferences(ui: &mut egui::Ui, app: &mut PdfCraftApp, req: &mut Pending) -> bool {+ + + let t = Tokens::get(ui.ctx());+ + + // The settings outgrow a short window: scroll them rather than run off the screen.+ + + // The OK row stays below the scroll, in reach however far the settings are scrolled.+ + + let max = (ui.ctx().content_rect().height() - 120.0 - crate::js_ui::PREFERENCES_BUTTON_ROW).max(crate::js_ui::PREFERENCES_MIN_SCROLL);+ + + // A scroll area starts from the room the dialog offers it, and a modal offers more+ + + // each frame for the first few, so with OK outside the scroll the dialog would grow+ + + // over those frames. Asking for the full height as the least it may scroll in+ + + // (which only applies when the settings overflow it) opens the dialog at full size.+ + + // A scrollbar of its own: the floating one lies over the right edge of the theme+ + + // cards and other full-width rows (#3557).+ + + ui.scope(|ui| {+ + + ui.spacing_mut().scroll.floating = false;+ + + egui::ScrollArea::vertical().max_height(max).min_scrolled_height(max).show(ui, |ui| crate::js_ui::preferences_body(ui, app, &t));+ + + });+ + + req.close = crate::js_ui::preferences_buttons(ui);+ + + false+ + + }+ + ++ + + /// `Dialog::NumberPages` content. Returns `false` when it has its own buttons and no footer is wanted.+ + + fn dialog_number_pages(ui: &mut egui::Ui, app: &mut PdfCraftApp, req: &mut Pending) -> bool {+ + + let t = Tokens::get(ui.ctx());+ + + use pdfcraft_engine::LabelStyle as L;+ + + ui.label(egui::RichText::new(tl!("Number pages")).font(theme::semibold(18.0)));+ + + ui.add_space(8.0);+ + + let Some((_, id)) = app.active_ids() else { return false };+ + + let n = app.session.get(id).map(|d| d.info.pages.len()).unwrap_or(1).max(1);+ + + let d = &mut app.number_draft;+ + + d.to = d.to.clamp(1, n);+ + + d.from = d.from.clamp(1, d.to);+ + + egui::Grid::new("number_pages").num_columns(2).spacing([12.0, 8.0]).show(ui, |ui| {+ + + ui.label(tl!("Pages"));+ + + ui.horizontal(|ui| {+ + + ui.add(egui::DragValue::new(&mut d.from).range(1..=n));+ + + ui.label(tl!("to"));+ + + ui.add(egui::DragValue::new(&mut d.to).range(1..=n));+ + + ui.label(egui::RichText::new(crate::i18n::fmt(tl!("of {name}"), &[("name", &n.to_string())])).color(t.text_muted));+ + + });+ + + ui.end_row();+ + + ui.label(tl!("Style"));+ + + let styles = [+ + + (L::Decimal, "1, 2, 3"),+ + + (L::LowerRoman, "i, ii, iii"),+ + + (L::UpperRoman, "I, II, III"),+ + + (L::LowerAlpha, "a, b, c"),+ + + (L::UpperAlpha, "A, B, C"),+ + + (L::None, tl!("None (prefix only)")),+ + + ];+ + + let current = styles.iter().find(|(s, _)| *s == d.style).map_or("1, 2, 3", |(_, l)| *l);+ + + craft_ui::ComboBox::from_id_salt("label_style").selected_text(current).show_ui(ui, |ui| {+ + + for (s, l) in styles {+ + + ui.selectable_value(&mut d.style, s, l);}- - - Dialog::SummarizeComments => {- - - ui.label(egui::RichText::new(tl!("Summarize Options")).font(theme::semibold(18.0)));- - - ui.add_space(8.0);- - - ui.label(tl!("Choose a layout:"));- - - let _ = ui.add(widgets::radio(true, tl!("Comments only")));- - - ui.add_space(6.0);- - - ui.horizontal(|ui| {- - - ui.label(tl!("Sort comments by:"));- - - egui::ComboBox::from_id_salt("summary-sort").selected_text(tl!(app.summary_sort.name())).show_ui(ui, |ui| {- - - for s in pdfcraft_engine::SummarySort::ALL {- - - ui.selectable_value(&mut app.summary_sort, s, tl!(s.name()));- - - }- - - });- - - });- - - ui.add_space(12.0);- - - ui.with_layout(Layout::right_to_left(Align::Center), |ui| {- - - if widgets::pill_button(ui, tl!("Create PDF Comment Summary"), true).clicked() {- - - summarize_now = true;- - - close = true;- - - }- - - if widgets::pill_button(ui, tl!("Cancel"), false).clicked() {- - - close = true;- - - }- - - });- - - return;+ + + });+ + + ui.end_row();+ + + let l = ui.label(tl!("Prefix"));+ + + ui.add(widgets::line(&mut d.prefix).desired_width(160.0)).labelled_by(l.id);+ + + ui.end_row();+ + + ui.label(tl!("Start"));+ + + ui.add(egui::DragValue::new(&mut d.start).range(1..=99_999));+ + + ui.end_row();+ + + });+ + + d.to = d.to.max(d.from);+ + + let label = |k: u32| format!("{}{}", d.prefix, d.style.format(k));+ + + ui.add_space(8.0);+ + + let preview = if d.from == d.to {+ + + label(d.start)+ + + } else {+ + + format!("{}, {} … {}", label(d.start), label(d.start + 1), label(d.start + (d.to - d.from) as u32))+ + + };+ + + ui.label(+ + + egui::RichText::new(crate::i18n::fmt(tl!("Labels: {preview}. Later pages keep their labels."), &[("preview", &preview)])).color(t.text_muted),+ + + );+ + + req.number_now = Some(Edit::NumberPages { from: d.from - 1, to: d.to - 1, style: d.style, prefix: d.prefix.clone(), first: d.start });+ + + true+ + + }+ + ++ + + /// `Dialog::Recovery` content. Returns `false` when it has its own buttons and no footer is wanted.+ + + fn dialog_recovery(ui: &mut egui::Ui, app: &mut PdfCraftApp) -> bool {+ + + let t = Tokens::get(ui.ctx());+ + + ui.horizontal(|ui| {+ + + ui.add(crate::icons::image("clock-3", 22.0, t.accent));+ + + ui.label(egui::RichText::new(tl!("Recover unsaved documents?")).font(theme::semibold(18.0)));+ + + });+ + + ui.add_space(6.0);+ + + ui.label(tl!("PdfCraft didn't shut down normally. These documents had changes that were autosaved:"));+ + + ui.add_space(8.0);+ + + let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0);+ + + egui::Grid::new("recoverable").num_columns(2).spacing([18.0, 6.0]).show(ui, |ui| {+ + + for m in &app.recoverable {+ + + ui.label(egui::RichText::new(&m.name).font(theme::medium(13.0)));+ + + let mins = now.saturating_sub(m.saved_at) / 60;+ + + let when = match mins {+ + + 0 => tl!("just now").to_string(),+ + + 1..=59 => crate::i18n::fmt(tl!("{n} min ago"), &[("n", &mins.to_string())]),+ + + _ => crate::i18n::fmt(tl!("{n} h ago"), &[("n", &(mins / 60).to_string())]),+ + + };+ + + let lock = if m.encrypted { tl!(" · password-protected") } else { "" };+ + + ui.label(egui::RichText::new(format!("{when}{lock}")).color(t.text_muted));+ + + ui.end_row();+ + + }+ + + });+ + + true+ + + }+ + ++ + + /// `Dialog::Shortcuts` content. Returns `false` when it has its own buttons and no footer is wanted.+ + + fn dialog_shortcuts(ui: &mut egui::Ui) -> bool {+ + + ui.label(egui::RichText::new(tl!("Keyboard shortcuts")).font(theme::semibold(18.0)));+ + + ui.add_space(8.0);+ + + use crate::commands::{+ + + ACTUAL_SIZE, COPY, FIND_NEXT, FIND_PREV, FIT_WIDTH, PAGE_LEVEL, PAGE_NEXT, PAGE_PREV, ROTATE_CCW, ROTATE_CW, SELECT_ALL, ZOOM_IN, ZOOM_OUT,+ + + };+ + + // Registered commands first (always in sync with the real bindings), then the+ + + // keys the document view handles itself.+ + + let mut rows: Vec<(String, String)> = pdfcraft_engine::commands::COMMANDS+ + + .iter()+ + + .filter_map(|c| c.shortcut.map(|k| (crate::commands::shortcut_label(ui.ctx(), k), tl!(c.label).trim_end_matches('…').to_string())))+ + + .collect();+ + + let key = |s: pdfcraft_engine::commands::Shortcut| crate::commands::shortcut_label(ui.ctx(), s);+ + + let pair = |a, b| format!("{} / {}", key(a), key(b));+ + + // Key names, translated where a catalog has them (not scanned as UI literals).+ + + let named = |k: &str| tl!(k).to_string();+++++++++++ ++++++++++ // Alt+← / Alt+→ (`canvas::shortcuts`): not a registered command, which has no Alt.+++++++++++ ++++++++++ let alt_arrows = if crate::commands::mac_shortcuts(ui.ctx()) {+++++++++++ ++++++++++ "⌥← / ⌥→".to_owned()+++++++++++ ++++++++++ } else {+++++++++++ ++++++++++ let alt = crate::i18n::key_name("Alt");+++++++++++ ++++++++++ format!("{alt}+← / {alt}+→")+++++++++++ ++++++++++ };+ + + let scroll = crate::i18n::fmt(tl!("Zoom in / out (also pinch or {key}-scroll)"), &[("key", crate::commands::command_modifier_label(ui.ctx()))]);+ + + for (k, v) in [+ + + (pair(FIND_NEXT, FIND_PREV), tl!("Next / previous match").to_string()),+ + + (key(COPY), tl!("Copy selected text").to_string()),+ + + (named("Double-click"), tl!("Select a word").to_string()),+ + + (crate::i18n::key_name("Esc").to_string(), tl!("Clear selection / close find").to_string()),+ + + (key(ACTUAL_SIZE), tl!("Actual size").to_string()),+ + + (key(PAGE_LEVEL), tl!("Zoom to page level").to_string()),+ + + (key(FIT_WIDTH), tl!("Fit to width").to_string()),+ + + (pair(ZOOM_IN, ZOOM_OUT), scroll),+ + + (pair(ROTATE_CW, ROTATE_CCW), tl!("Rotate view").to_string()),+ + + (format!("{} / {}", crate::i18n::key_name("Home"), crate::i18n::key_name("End")), tl!("First / last page").to_string()),+ + + (format!("← / →, {}", pair(PAGE_PREV, PAGE_NEXT)), tl!("Previous / next page").to_string()),+++++++++++ ++++++++++ (alt_arrows, format!("{} / {}", tl!("Previous view"), tl!("Next view"))),+ + + (named("V"), tl!("Select (V)").to_string()),+ + + (named("H / Space (hold)"), tl!("Hand (H)").to_string()),+ + + (crate::i18n::key_name("Delete").to_string(), tl!("Delete selected pages (Organize)").to_string()),+ + + (key(SELECT_ALL), tl!("Select all pages (Organize)").to_string()),+ + + ] {+ + + rows.push((k, v));+ + + }+ + + egui::ScrollArea::vertical().max_height(460.0).show(ui, |ui| {+ + + egui::Grid::new("keys").num_columns(2).spacing([24.0, 6.0]).show(ui, |ui| {+ + + for (k, v) in &rows {+ + + ui.label(egui::RichText::new(k).font(egui::FontId::monospace(12.5)));+ + + ui.label(v);+ + + ui.end_row();}- - - Dialog::Revert => {- - - let name = app.active_ids().and_then(|(_, id)| app.session.get(id)).map(|d| d.name.clone()).unwrap_or_default();- - - ui.label(egui::RichText::new(tl!("Revert")).font(theme::semibold(18.0)));- - - ui.add_space(8.0);- - - ui.label(crate::i18n::fmt(- - - tl!("Revert to the previously saved version of “{name}”? Changes since then can't be undone afterwards."),- - - &[("name", &name)],- - - ));- - - ui.add_space(12.0);- - - ui.with_layout(Layout::right_to_left(Align::Center), |ui| {- - - if widgets::pill_button(ui, tl!("Revert"), true).clicked() {- - - revert_now = true;- - - close = true;- - - }- - - if widgets::pill_button(ui, tl!("Cancel"), false).clicked() {- - - close = true;- - - }- - - });- - - return;+ + + });+ + + });+ + + true+ + + }+ + ++ + + /// `Dialog::About` content. Returns `false` when it has its own buttons and no footer is wanted.+ + + fn dialog_about(ui: &mut egui::Ui, req: &mut Pending) -> bool {+ + + let t = Tokens::get(ui.ctx());+ + + // Tabs About · Contributors · Models (craftrules standards/contributors.md).+ + + let tab_id = egui::Id::unique("about_tab");+ + + let mut tab = ui.data_mut(|d| d.get_temp::<u8>(tab_id)).unwrap_or(0);+ + + ui.horizontal_wrapped(|ui| {+ + + for (i, label) in ["About", "Contributors", "Models"].into_iter().enumerate() {+ + + let i = i as u8;+ + + if widgets::mode_tab(ui, tl!(label), tab == i).clicked() {+ + + tab = i;}- - - Dialog::OverwriteChanged => {- - - #[cfg(not(target_arch = "wasm32"))]- - - let name = app.pending_overwrite.as_ref().and_then(|p| app.session.get(p.id)).map(|d| d.name.clone()).unwrap_or_default();- - - #[cfg(target_arch = "wasm32")]- - - let name = String::new();- - - ui.label(egui::RichText::new(tl!("Save over the changed file?")).font(theme::semibold(18.0)));- - - ui.add_space(8.0);- - - ui.label(crate::i18n::fmt(- - - tl!("“{name}” changed on disk after it was opened or last saved. Saving now replaces that newer version with this one."),- - - &[("name", &name)],- - - ));- - - ui.add_space(12.0);- - - ui.with_layout(Layout::right_to_left(Align::Center), |ui| {- - - if widgets::pill_button(ui, tl!("Save anyway"), true).clicked() {- - - overwrite_now = true;- - - close = true;- - - }- - - if widgets::pill_button(ui, tl!("Save as…"), false).clicked() {- - - overwrite_elsewhere = true;- - - close = true;- - - }- - - if widgets::pill_button(ui, tl!("Cancel"), false).clicked() {- - - close = true;- - - }+ + + }+ + + });+ + + ui.data_mut(|d| d.insert_temp(tab_id, tab));+ + + ui.separator();+ + + match tab {+ + + 1 => crate::credits::contributors_ui(ui),+ + + 2 => crate::credits::models_ui(ui),+ + + _ => {+ + + ui.horizontal(|ui| {+ + + widgets::artcraft_mark(ui, 40.0);+ + + ui.vertical(|ui| {+ + + ui.label(egui::RichText::new("PdfCraft").font(theme::semibold(20.0)));+ + + ui.label(crate::i18n::fmt(tl!("Version {v}"), &[("v", &pdfcraft_engine::build_info::version())]));});- - - return;+ + + });+ + + ui.add_space(6.0);+ + + ui.label(tl!("A clean-room, open-source PDF application written in Rust. MIT OR Apache-2.0."));+ + + ui.label(+ + + egui::RichText::new(+ + + "Rendering: hayro (bootstrap) · UI: egui · Icons: Lucide (ISC) · Fonts: Inter, JetBrains Mono, Dancing Script (OFL)",+ + + )+ + + .color(t.text_muted)+ + + .small(),+ + + );+ + + ui.add_space(12.0);+ + + ui.horizontal(|ui| {+ + + ui.label(egui::RichText::new(tl!("Part of")).color(t.text_muted));+ + + widgets::artcraft_logo(ui, 16.0);+ + + });+ + + ui.add_space(6.0);+ + + if let Some(cmd) = widgets::community_links(ui) {+ + + req.link_command = Some(cmd);}- - - Dialog::Print => {- - - let Some((i, id)) = app.active_ids() else {- - - close = true;- - - return;- - - };- - - if app.print_draft.handling == crate::print_ui::Handling::Label {- - - app.read_label_crops(id);+ + + }+ + + }+ + + true+ + + }+ + ++ + + fn dialog_footer(ui: &mut egui::Ui, app: &mut PdfCraftApp, dialog: Dialog, req: &mut Pending) {+ + + ui.add_space(16.0);+ + + let changed = draft_changes(app).is_some_and(|c| !c.is_empty());+ + + // One row high: on its own, a right-to-left layout centres the buttons in all the height+ + + // left, which after a taller Properties tab is the room that tab left behind.+ + + ui.horizontal(|ui| {+ + + ui.with_layout(Layout::right_to_left(Align::Center), |ui| {+ + + if dialog == Dialog::Recovery {+ + + if widgets::pill_button(ui, tl!("Recover"), true).clicked() {+ + + req.recover = Some(true);+ + + req.close = true;}- - - let Some(doc) = app.session.get(id) else { return };- - - let sizes: Vec<(f64, f64)> = doc.info.pages.iter().map(|p| (p.width as f64, p.height as f64)).collect();- - - let labels: Vec<String> = doc.info.pages.iter().map(|p| p.label.clone()).collect();- - - let rasters = crate::print_ui::preview_rasters(- - - &app.print_draft,- - - &sizes,- - - &labels,- - - ui.ctx().pixels_per_point(),- - - ui.ctx().input(|i| i.max_texture_side) as f32,- - - );- - - let view = &mut app.views[i];- - - view.set_print_grayscale(app.print_draft.grayscale);- - - view.queue_print_previews(&rasters);- - - let (go, cancel) = crate::print_ui::body(ui, &mut app.print_draft, &t, &sizes, &labels, &mut |p| {- - - view.need_thumbnail(p, true);- - - view.page_preview(p)- - - });- - - print_go = go;- - - close = go || cancel;- - - return;- - - }- - - Dialog::RemoveHidden => {- - - let (ok, cancel) = crate::redact_ui::hidden_body(ui, &mut app.hidden_draft, &t);- - - if ok {- - - redact_now = Some(dialog);+ + + if widgets::pill_button(ui, tl!("Discard"), false).clicked() {+ + + req.recover = Some(false);+ + + req.close = true;}- - - close = ok || cancel;- - - return;- - - }- - - Dialog::Sanitize => {- - - let (ok, cancel) = crate::redact_ui::sanitize_body(ui, &t);- - - if ok {- - - redact_now = Some(dialog);+ + + } else if dialog == Dialog::NumberPages {+ + + if widgets::pill_button(ui, tl!("OK"), true).clicked() {+ + + req.apply_number = true;+ + + req.close = true;}- - - close = ok || cancel;- - - return;- - - }- - - Dialog::FieldProps => {- - - let Some(d) = app.field_props.as_mut() else {- - - close = true;- - - return;- - - };- - - let (apply, cancel) = crate::prepare::body(ui, d, &t);- - - field_props_now = apply;- - - close = apply || cancel;- - - return;- - - }- - - Dialog::BulkFieldProps => {- - - let Some(d) = app.bulk_field_props.as_mut() else {- - - close = true;- - - return;- - - };- - - let (apply, cancel) = crate::bulk_fields::body(ui, d, &t);- - - bulk_field_props_now = apply;- - - close = cancel;- - - return;- - - }- - - Dialog::CommentProps => {- - - let (apply, cancel) = crate::comment_props::body(ui, app, &t);- - - props_now = apply;- - - close = apply || cancel;- - - return;- - - }- - - Dialog::Signature => {- - - let (apply, cancel, browse) =- - - crate::fill_sign::signature_pad(ui, &t, &mut app.signature_draft, &mut app.signature_preview, &mut app.signature_photo);- - - if browse {- - - app.pick_signature_image();+ + + if widgets::pill_button(ui, tl!("Cancel"), false).clicked() {+ + + req.close = true;}- - - if apply {- - - let d = std::mem::take(&mut app.signature_draft);- - - let tool = if d.initials {- - - app.initials = d.saved();- - - crate::fill_sign::FillTool::Initials- - - } else {- - - app.signature = d.saved();- - - crate::fill_sign::FillTool::Signature- - - };- - - app.quick_tool = crate::QuickTool::Fill(tool);- - - app.toast = None;+ + + } else if dialog == Dialog::Split {+ + + if ui.add_enabled_ui(req.split_ready.is_some(), |ui| widgets::pill_button(ui, tl!("Split"), true)).inner.clicked() {+ + + req.split_now = req.split_ready.clone();+ + + req.close = true;}- - - close = apply || cancel;- - - return;- - - }- - - Dialog::AltText => {- - - let (save, cancel) = crate::a11y_ui::alt_body(ui, app, &t);- - - alt_now = save;- - - close = save || cancel;- - - return;- - - }- - - Dialog::CreateStamp => {- - - let (save, cancel) = crate::stamps_ui::create_body(ui, app, &t);- - - stamp_now = save;- - - close = save || cancel;- - - return;- - - }- - - Dialog::PdfA => {- - - close = crate::standards_ui::body(ui, app, &t);- - - return;- - - }- - - Dialog::ActionWizard => {- - - ui.set_width(620.0);- - - close = crate::actions_ui::body(ui, app, &t);- - - return;- - - }- - - Dialog::CompareFiles => {- - - let (go, cancel) = crate::compare_ui::body(ui, app, &t);- - - compare_now = go;- - - close = go || cancel;- - - return;- - - }- - - Dialog::JsConsole => {- - - ui.set_width(640.0);- - - close = crate::js_ui::console_body(ui, app, &t);- - - return;- - - }- - - Dialog::DocumentJs => {- - - ui.set_width(640.0);- - - close = crate::js_ui::document_js_body(ui, app, &t);- - - return;- - - }- - - Dialog::Preferences => {- - - // The settings outgrow a short window: scroll them rather than run off the screen.- - - // The OK row stays below the scroll, in reach however far the settings are scrolled.- - - let max = (ui.ctx().content_rect().height() - 120.0 - crate::js_ui::PREFERENCES_BUTTON_ROW).max(crate::js_ui::PREFERENCES_MIN_SCROLL);- - - // A scroll area starts from the room the dialog offers it, and a modal offers more- - - // each frame for the first few, so with OK outside the scroll the dialog would grow- - - // over those frames. Asking for the full height as the least it may scroll in- - - // (which only applies when the settings overflow it) opens the dialog at full size.- - - // A scrollbar of its own: the floating one lies over the right edge of the theme- - - // cards and other full-width rows (#3557).- - - ui.scope(|ui| {- - - ui.spacing_mut().scroll.floating = false;- - - egui::ScrollArea::vertical().max_height(max).min_scrolled_height(max).show(ui, |ui| crate::js_ui::preferences_body(ui, app, &t));- - - });- - - close = crate::js_ui::preferences_buttons(ui);- - - return;- - - }- - - Dialog::RecognizeText => {- - - let (go, cancel) = crate::ocr_ui::body(ui, app, &t);- - - ocr_now = go;- - - close = go || cancel;- - - return;- - - }- - - Dialog::AccessibilityOptions => {- - - let (start, cancel) = crate::a11y_ui::options_body(ui, app, &t);- - - a11y_now = start;- - - close = start || cancel;- - - return;- - - }- - - Dialog::Export(kind) => {- - - let (apply, cancel) = crate::export_ui::body(ui, app, &t, kind);- - - export_now = apply;- - - close = apply || cancel;- - - return;- - - }- - - Dialog::Marks(kind) => {- - - ui.set_width(720.0);- - - let (apply, cancel) = crate::marks_ui::body(ui, app, &t, kind);- - - marks_now = apply;- - - close = apply || cancel;- - - return;- - - }- - - Dialog::PageBoxes => {- - - let (apply, cancel) = crate::pageboxes::body(ui, app, &t);- - - boxes_now = apply;- - - close = apply || cancel;- - - return;- - - }- - - Dialog::Protect => {- - - let (apply, cancel) = crate::protect::body(ui, app, &t);- - - protect_now = apply;- - - close = apply || cancel;- - - return;- - - }- - - Dialog::NumberPages => {- - - use pdfcraft_engine::LabelStyle as L;- - - ui.label(egui::RichText::new(tl!("Number pages")).font(theme::semibold(18.0)));- - - ui.add_space(8.0);- - - let Some((_, id)) = app.active_ids() else { return };- - - let n = app.session.get(id).map(|d| d.info.pages.len()).unwrap_or(1).max(1);- - - let d = &mut app.number_draft;- - - d.to = d.to.clamp(1, n);- - - d.from = d.from.clamp(1, d.to);- - - egui::Grid::new("number_pages").num_columns(2).spacing([12.0, 8.0]).show(ui, |ui| {- - - ui.label(tl!("Pages"));- - - ui.horizontal(|ui| {- - - ui.add(egui::DragValue::new(&mut d.from).range(1..=n));- - - ui.label(tl!("to"));- - - ui.add(egui::DragValue::new(&mut d.to).range(1..=n));- - - ui.label(egui::RichText::new(crate::i18n::fmt(tl!("of {name}"), &[("name", &n.to_string())])).color(t.text_muted));- - - });- - - ui.end_row();- - - ui.label(tl!("Style"));- - - let styles = [- - - (L::Decimal, "1, 2, 3"),- - - (L::LowerRoman, "i, ii, iii"),- - - (L::UpperRoman, "I, II, III"),- - - (L::LowerAlpha, "a, b, c"),- - - (L::UpperAlpha, "A, B, C"),- - - (L::None, tl!("None (prefix only)")),- - - ];- - - let current = styles.iter().find(|(s, _)| *s == d.style).map_or("1, 2, 3", |(_, l)| *l);- - - egui::ComboBox::from_id_salt("label_style").selected_text(current).show_ui(ui, |ui| {- - - for (s, l) in styles {- - - ui.selectable_value(&mut d.style, s, l);- - - }- - - });- - - ui.end_row();- - - let l = ui.label(tl!("Prefix"));- - - ui.add(widgets::line(&mut d.prefix).desired_width(160.0)).labelled_by(l.id);- - - ui.end_row();- - - ui.label(tl!("Start"));- - - ui.add(egui::DragValue::new(&mut d.start).range(1..=99_999));- - - ui.end_row();- - - });- - - d.to = d.to.max(d.from);- - - let label = |k: u32| format!("{}{}", d.prefix, d.style.format(k));- - - ui.add_space(8.0);- - - let preview = if d.from == d.to {- - - label(d.start)- - - } else {- - - format!("{}, {} … {}", label(d.start), label(d.start + 1), label(d.start + (d.to - d.from) as u32))- - - };- - - ui.label(- - - egui::RichText::new(crate::i18n::fmt(tl!("Labels: {preview}. Later pages keep their labels."), &[("preview", &preview)]))- - - .color(t.text_muted),- - - );- - - number_now = Some(Edit::NumberPages { from: d.from - 1, to: d.to - 1, style: d.style, prefix: d.prefix.clone(), first: d.start });- - - }- - - Dialog::Recovery => {- - - ui.horizontal(|ui| {- - - ui.add(crate::icons::image("clock-3", 22.0, t.accent));- - - ui.label(egui::RichText::new(tl!("Recover unsaved documents?")).font(theme::semibold(18.0)));- - - });- - - ui.add_space(6.0);- - - ui.label(tl!("PdfCraft didn't shut down normally. These documents had changes that were autosaved:"));- - - ui.add_space(8.0);- - - let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0);- - - egui::Grid::new("recoverable").num_columns(2).spacing([18.0, 6.0]).show(ui, |ui| {- - - for m in &app.recoverable {- - - ui.label(egui::RichText::new(&m.name).font(theme::medium(13.0)));- - - let mins = now.saturating_sub(m.saved_at) / 60;- - - let when = match mins {- - - 0 => tl!("just now").to_string(),- - - 1..=59 => crate::i18n::fmt(tl!("{n} min ago"), &[("n", &mins.to_string())]),- - - _ => crate::i18n::fmt(tl!("{n} h ago"), &[("n", &(mins / 60).to_string())]),- - - };- - - let lock = if m.encrypted { tl!(" · password-protected") } else { "" };- - - ui.label(egui::RichText::new(format!("{when}{lock}")).color(t.text_muted));- - - ui.end_row();- - - }- - - });- - - }- - - Dialog::Shortcuts => {- - - ui.label(egui::RichText::new(tl!("Keyboard shortcuts")).font(theme::semibold(18.0)));- - - ui.add_space(8.0);- - - use crate::commands::{- - - ACTUAL_SIZE, COPY, FIND_NEXT, FIND_PREV, FIT_WIDTH, PAGE_LEVEL, PAGE_NEXT, PAGE_PREV, ROTATE_CCW, ROTATE_CW, SELECT_ALL, ZOOM_IN,- - - ZOOM_OUT,- - - };- - - // Registered commands first (always in sync with the real bindings), then the- - - // keys the document view handles itself.- - - let mut rows: Vec<(String, String)> = pdfcraft_engine::commands::COMMANDS- - - .iter()- - - .filter_map(|c| {- - - c.shortcut.map(|k| (crate::commands::shortcut_label(ui.ctx(), k), tl!(c.label).trim_end_matches('…').to_string()))- - - })- - - .collect();- - - let key = |s: pdfcraft_engine::commands::Shortcut| crate::commands::shortcut_label(ui.ctx(), s);- - - let pair = |a, b| format!("{} / {}", key(a), key(b));- - - // Key names, translated where a catalog has them (not scanned as UI literals).- - - let named = |k: &str| tl!(k).to_string();- - - let scroll = crate::i18n::fmt(- - - tl!("Zoom in / out (also pinch or {key}-scroll)"),- - - &[("key", crate::commands::command_modifier_label(ui.ctx()))],- - - );- - - for (k, v) in [- - - (pair(FIND_NEXT, FIND_PREV), tl!("Next / previous match").to_string()),- - - (key(COPY), tl!("Copy selected text").to_string()),- - - (named("Double-click"), tl!("Select a word").to_string()),- - - (crate::i18n::key_name("Esc").to_string(), tl!("Clear selection / close find").to_string()),- - - (key(ACTUAL_SIZE), tl!("Actual size").to_string()),- - - (key(PAGE_LEVEL), tl!("Zoom to page level").to_string()),- - - (key(FIT_WIDTH), tl!("Fit to width").to_string()),- - - (pair(ZOOM_IN, ZOOM_OUT), scroll),- - - (pair(ROTATE_CW, ROTATE_CCW), tl!("Rotate view").to_string()),- - - (format!("{} / {}", crate::i18n::key_name("Home"), crate::i18n::key_name("End")), tl!("First / last page").to_string()),- - - (format!("← / →, {}", pair(PAGE_PREV, PAGE_NEXT)), tl!("Previous / next page").to_string()),- - - (named("V"), tl!("Select (V)").to_string()),- - - (named("H / Space (hold)"), tl!("Hand (H)").to_string()),- - - (crate::i18n::key_name("Delete").to_string(), tl!("Delete selected pages (Organize)").to_string()),- - - (key(SELECT_ALL), tl!("Select all pages (Organize)").to_string()),- - - ] {- - - rows.push((k, v));+ + + if widgets::pill_button(ui, tl!("Cancel"), false).clicked() {+ + + req.close = true;}- - - egui::ScrollArea::vertical().max_height(460.0).show(ui, |ui| {- - - egui::Grid::new("keys").num_columns(2).spacing([24.0, 6.0]).show(ui, |ui| {- - - for (k, v) in &rows {- - - ui.label(egui::RichText::new(k).font(egui::FontId::monospace(12.5)));- - - ui.label(v);- - - ui.end_row();- - - }- - - });- - - });- - - }- - - Dialog::About => {- - - // Tabs About · Contributors · Models (craftrules standards/contributors.md).- - - let tab_id = egui::Id::unique("about_tab");- - - let mut tab = ui.data_mut(|d| d.get_temp::<u8>(tab_id)).unwrap_or(0);- - - ui.horizontal_wrapped(|ui| {- - - for (i, label) in ["About", "Contributors", "Models"].into_iter().enumerate() {- - - let i = i as u8;- - - if widgets::mode_tab(ui, tl!(label), tab == i).clicked() {- - - tab = i;- - - }- - - }- - - });- - - ui.data_mut(|d| d.insert_temp(tab_id, tab));- - - ui.separator();- - - match tab {- - - 1 => crate::credits::contributors_ui(ui),- - - 2 => crate::credits::models_ui(ui),- - - _ => {- - - ui.horizontal(|ui| {- - - widgets::artcraft_mark(ui, 40.0);- - - ui.vertical(|ui| {- - - ui.label(egui::RichText::new("PdfCraft").font(theme::semibold(20.0)));- - - ui.label(crate::i18n::fmt(tl!("Version {v}"), &[("v", &pdfcraft_engine::build_info::version())]));- - - });- - - });- - - ui.add_space(6.0);- - - ui.label(tl!("A clean-room, open-source PDF application written in Rust. MIT OR Apache-2.0."));- - - ui.label(- - - egui::RichText::new(- - - "Rendering: hayro (bootstrap) · UI: egui · Icons: Lucide (ISC) · Fonts: Inter, JetBrains Mono, Dancing Script (OFL)",- - - )- - - .color(t.text_muted)- - - .small(),- - - );- - - ui.add_space(12.0);- - - ui.horizontal(|ui| {- - - ui.label(egui::RichText::new(tl!("Part of")).color(t.text_muted));- - - widgets::artcraft_logo(ui, 16.0);- - - });- - - ui.add_space(6.0);- - - if let Some(cmd) = widgets::community_links(ui) {- - - link_command = Some(cmd);- - - }- - - }+ + + } else if changed {+ + + if widgets::pill_button(ui, tl!("OK"), true).clicked() {+ + + req.apply = true;+ + + req.close = true;}- - - }- - - }- - - ui.add_space(16.0);- - - let changed = draft_changes(app).is_some_and(|c| !c.is_empty());- - - // One row high: on its own, a right-to-left layout centres the buttons in all the height- - - // left, which after a taller Properties tab is the room that tab left behind.- - - ui.horizontal(|ui| {- - - ui.with_layout(Layout::right_to_left(Align::Center), |ui| {- - - if dialog == Dialog::Recovery {- - - if widgets::pill_button(ui, tl!("Recover"), true).clicked() {- - - recover = Some(true);- - - close = true;- - - }- - - if widgets::pill_button(ui, tl!("Discard"), false).clicked() {- - - recover = Some(false);- - - close = true;- - - }- - - } else if dialog == Dialog::NumberPages {- - - if widgets::pill_button(ui, tl!("OK"), true).clicked() {- - - apply_number = true;- - - close = true;- - - }- - - if widgets::pill_button(ui, tl!("Cancel"), false).clicked() {- - - close = true;- - - }- - - } else if dialog == Dialog::Split {- - - if ui.add_enabled_ui(split_ready.is_some(), |ui| widgets::pill_button(ui, tl!("Split"), true)).inner.clicked() {- - - split_now = split_ready.clone();- - - close = true;- - - }- - - if widgets::pill_button(ui, tl!("Cancel"), false).clicked() {- - - close = true;- - - }- - - } else if changed {- - - if widgets::pill_button(ui, tl!("OK"), true).clicked() {- - - apply = true;- - - close = true;- - - }- - - if widgets::pill_button(ui, tl!("Cancel"), false).clicked() {- - - close = true;- - - }- - - } else if widgets::pill_button(ui, tl!("Close"), true).clicked() {- - - close = true;+ + + if widgets::pill_button(ui, tl!("Cancel"), false).clicked() {+ + + req.close = true;}- - - })- - - });+ + + } else if widgets::pill_button(ui, tl!("Close"), true).clicked() {+ + + req.close = true;+ + + }+ + + })});- - - if let Some(yes) = recover {+ + + }+ + ++ + + /// Acts on what the dialog asked for, once the modal is drawn.+ + + fn finish_dialog(app: &mut PdfCraftApp, dialog: Dialog, modal_closed: bool, req: &mut Pending) {+ + + finish_requests(app, dialog, modal_closed, req);+ + + finish_actions(app, req);+ + + finish_redactions_and_fields(app, req);+ + + finish_edits(app, dialog, req);+ + + finish_close(app, dialog, modal_closed, req);+ + + }+ + ++ + + /// Runs the one-shot requests the dialog made.+ + + fn finish_requests(app: &mut PdfCraftApp, dialog: Dialog, modal_closed: bool, req: &mut Pending) {+ + + if let Some(yes) = req.recover {let keys: Vec<String> = app.recoverable.iter().map(|m| m.key.clone()).collect();if yes {app.recover(&keys);@@@@@@@@@@@@@@@@@@@@@@@ -1662,19 -1662,19 -1662,19 -1662,19 -1662,19 -1472,10 -1662,19 -1662,19 -1662,19 -1662,19 -1472,10 -1670,19 -1662,19 -1662,19 -1643,10 -1662,19 -1643,10 -1662,19 -1472,10 -1643,10 -1662,19 -1662,19 +1670,19 @@@@@@@@@@@@@@@@@@@@@@@ fn finish_actions(app: &mut PdfCraftAppapp.duplicate_draft = None;app.apply_edit(e);}- - - if extract_now {+ + + + ++ // Another document became active, or the document changed, while the dialog was open: the+ + + + ++ // pages at those indices may not be the ones chosen.+ + + + ++ if let Some((doc, generation, e)) = req.page_props_now.take() {+ + + + ++ if app.active_ids().is_some_and(|(_, id)| id == doc) && app.session.get(doc).is_some_and(|d| d.edit_generation() == generation) {+ + + + ++ app.apply_edit(e);+ + + + ++ } else {+ + + + ++ app.notify_tr("The document changed while the dialog was open, so nothing was changed. Open Page properties again to set the tab order.");+ + + + ++ }+ + + + ++ }+ + + if req.extract_now {app.extract_selection();}- - - if let Some(e) = link_now {+ + + if let Some(e) = req.link_now.take() {app.apply_edit(e);app.link_draft = None;}@@@@@@@@@@@@@@@@@@@@@@@ -1755,16 -1755,16 -1755,16 -1755,16 -1755,16 -1546,10 -1755,16 -1755,16 -1755,16 -1749,16 -1546,10 -1757,16 -1749,16 -1755,16 -1721,16 -1755,16 -1721,16 -1755,16 -1546,10 -1721,16 -1755,16 -1755,16 +1763,16 @@@@@@@@@@@@@@@@@@@@@@@ fn finish_redactions_and_fields(app: &m));}}- ---- - - -- app.views[i].prepare.selected = Some((name, d.widget));+ ++++ + + ++ app.views[i].prepare.selected = Some((name, index));}}- - - if props_now && let Some(d) = app.comment_props.take() {+ + + }+ + ++ + + /// Edits built from the dialog's drafts.+ + + fn finish_edits(app: &mut PdfCraftApp, dialog: Dialog, req: &mut Pending) {+ + + if req.props_now+ + + && let Some(d) = app.comment_props.take()+ + + {let mut edits = crate::comment_props::edits(&d);match edits.len() {0 => {}@@@@@@@@@@@@@@@@@@@@@@@ -1829,23 -1829,23 -1829,23 -1829,23 -1829,23 -1600,22 -1829,23 -1829,23 -1829,23 -1823,23 -1600,22 -1831,23 -1823,23 -1829,23 -1795,22 -1829,23 -1795,22 -1829,23 -1600,22 -1795,22 -1829,23 -1829,23 +1837,23 @@@@@@@@@@@@@@@@@@@@@@@ fn finish_close(app: &mut PdfCraftApp,app.view_draft = None;app.custom_draft = None;app.bulk_field_props = None;+ + + + ++ app.unmarked_page = Default::default();} else {- - - app.dialog = Some(next);+ + + app.dialog = Some(req.next.unwrap_or(dialog));}- - - if let Some(cmd) = link_command {+ + + if let Some(cmd) = req.link_command {app.execute(cmd);}- - - if let Some(n) = open_revision {+ + + if let Some(n) = req.open_revision {app.open_revision(n);}- - - if alt_now {+ + + if req.alt_now {app.save_alt_text();}- - - if stamp_now {+ + + if req.stamp_now {app.save_custom_stamp();}- - - if images_now {+ + + if req.images_now {app.finish_image_import();} else if dialog == Dialog::CreateImages && app.dialog != Some(Dialog::CreateImages) {app.image_import = None;diff --cc crates/ui-egui/src/editing.rsindex ab6d49f42,ab6d49f42,ab6d49f42,ab6d49f42,ab6d49f42,e4b6da9d4,ab6d49f42,7e5ea8ed6,ab6d49f42,df2b4da6a,ba2d3cbf9,ab6d49f42,ab6d49f42,ab6d49f42,4d09b5cf4,ab6d49f42,4d09b5cf4,ab6d49f42,ba2d3cbf9,4d09b5cf4,ab6d49f42,649c72c8e..6dde2dfcd--- a/crates/ui-egui/src/editing.rs+++ b/crates/ui-egui/src/editing.rs@@@@@@@@@@@@@@@@@@@@@@@ -27,79 -27,79 -27,79 -27,79 -27,79 -27,6 -27,79 -27,86 -27,79 -27,79 -27,6 -27,79 -27,79 -27,79 -27,79 -27,79 -27,79 -27,79 -27,6 -27,79 -27,79 -27,79 +27,86 @@@@@@@@@@@@@@@@@@@@@@@ fn new_text_typed(v: &crate::DocView) -v.content.draft.as_ref().is_some_and(|d| d.index.is_none() && !d.text.trim().is_empty())}----- - -- ------- ---/// Keeps the pages (or comment) the user acted on selected, where they now are.----- - -- ------- ---fn select_after_edit(view: &mut crate::DocView, edit: Edit, info: &pdfcraft_render::DocInfo, quick_tool: crate::QuickTool) {+++++++ ++++++++++++++/// Keeps the pages (or comment) the user acted on selected, where they now are. `annots_before`+++++++ ++++++++++++++/// is a deleted annotation's page's annotations before the delete (empty for other edits).+++++++ ++++++++++++++fn select_after_edit(+++++++ ++++++++++++++ view: &mut crate::DocView,+++++++ ++++++++++++++ edit: Edit,+++++++ ++++++++++++++ info: &pdfcraft_render::DocInfo,+++++++ ++++++++++++++ annots_before: &[pdfcraft_render::Annotation],+++++++ ++++++++++++++ quick_tool: crate::QuickTool,+++++++ ++++++++++++++) {+ + + match edit {+ + + Edit::MovePages { pages, to } => {+ + + let n = pages.iter().collect::<std::collections::BTreeSet<_>>().len();+ + + let to = to.min(info.pages.len() - n);+ + + view.select_pages(&(to..to + n).collect::<Vec<_>>());+ + + }+ + + Edit::DuplicatePages { pages, at: Some(at) } => {+ + + let n = pages.iter().collect::<std::collections::BTreeSet<_>>().len();+ + + let at = at.min(info.pages.len().saturating_sub(n));+ + + view.select_pages(&(at..at + n).collect::<Vec<_>>());+ + + }+ + + Edit::InsertBlankPage { at, .. } => view.select_pages(&[at.min(info.pages.len() - 1)]),+ + + Edit::DeletePages { .. } => view.select_pages(&[]),+ + + // A stroke drawn with the pen stays unselected, so the selection box and+ + + // author popup don't sit over the next stroke (#429).+ + + Edit::AddAnnotation(a)+ + + if matches!(a.shape, pdfcraft_engine::Shape::Ink { .. })+ + + && quick_tool == crate::QuickTool::Comment(crate::comments::CommentTool::Ink) =>+ + + {+ + + view.comments.selected = None;+ + + }+ + + Edit::AddAnnotation(a) => {+ + + // Select the new comment (appended last among the page's comments).+ + + let newest = info.annotations.iter().filter(|x| x.page == a.page && !x.is_reply()).map(|x| x.index).max();+ + + view.comments.selected = newest.map(|n| (a.page, n));+ + + view.comments.reveal = true;+ + + // A new highlight opens its note for typing straight away, as in Acrobat,+ + + // unless a note typed into another card is still unsaved.+ + + if let (pdfcraft_engine::Shape::TextMarkup { kind: pdfcraft_engine::Markup::Highlight, .. }, Some(n)) = (&a.shape, newest)+ + + && a.contents.is_empty()+ + + && view.comments.editing.is_none()+ + + {+ + + view.comments.open_editor(a.page, n, String::new());+ + + }+ + + }----- - -- ------- --- Edit::DeleteAnnotation { .. } => view.comments.selected = None,+++++++ ++++++++++++++ Edit::DeleteAnnotation { page, index } => view.comments.annotation_deleted(annots_before, &info.annotations, (page, index)),+ + + _ => {}+ + + }+ + + }+ + ++ + + /// The pages whose widgets differ between two form states, and the (field, page) pairs whose+ + + /// value changed and so must not be drawn from the baked page.+ + + fn form_edit_pages(+ + + before: &[pdfcraft_engine::FormField],+ + + after: &[pdfcraft_engine::FormField],+ + + ) -> (std::collections::BTreeSet<usize>, Vec<(String, usize)>) {+ + + let mut changed_pages = std::collections::BTreeSet::new();+ + + let mut unbaked = Vec::new();+ + + for f in after {+ + + let pages = |field: &pdfcraft_engine::FormField| field.widgets.iter().filter_map(|w| w.page).collect::<Vec<_>>();+ + + match before.iter().find(|old| old.name == f.name) {+ + + Some(old) if old == f => {}+ + + Some(old) => {+ + + changed_pages.extend(pages(f));+ + + changed_pages.extend(pages(old));+ + + if old.value != f.value {+ + + unbaked.extend(pages(f).into_iter().map(|p| (f.name.clone(), p)));+ + + }+ + + }+ + + None => {+ + + changed_pages.extend(pages(f));+ + + unbaked.extend(pages(f).into_iter().map(|p| (f.name.clone(), p)));+ + + }+ + + }+ + + }+ + + for old in before.iter().filter(|old| !after.iter().any(|f| f.name == old.name)) {+ + + changed_pages.extend(old.widgets.iter().filter_map(|w| w.page));+ + + }+ + + (changed_pages, unbaked)+ + + }+ + +impl PdfCraftApp {/// Apply an edit to the active document. Returns `true` on success; failures are shown.pub fn apply_edit(&mut self, edit: Edit) -> bool {@@@@@@@@@@@@@@@@@@@@@@@ -153,7 -153,7 -153,7 -153,7 -153,7 -121,44 -153,7 -166,7 -153,7 -153,7 -121,44 -153,7 -153,7 -153,7 -153,7 -153,7 -153,7 -153,7 -121,44 -153,7 -153,7 -153,7 +166,7 @@@@@@@@@@@@@@@@@@@@@@@view.comments.comment_added();}// Keep the pages the user acted on selected, where they now are.----- - -- ------- --- select_after_edit(view, edit, info, self.quick_tool);- - - match edit {- - - Edit::MovePages { pages, to } => {- - - let n = pages.iter().collect::<std::collections::BTreeSet<_>>().len();- - - let to = to.min(info.pages.len() - n);- - - view.select_pages(&(to..to + n).collect::<Vec<_>>());- - - }- - - Edit::DuplicatePages { pages, at: Some(at) } => {- - - let n = pages.iter().collect::<std::collections::BTreeSet<_>>().len();- - - let at = at.min(info.pages.len().saturating_sub(n));- - - view.select_pages(&(at..at + n).collect::<Vec<_>>());- - - }- - - Edit::InsertBlankPage { at, .. } => view.select_pages(&[at.min(info.pages.len() - 1)]),- - - Edit::DeletePages { .. } => view.select_pages(&[]),- - - // A stroke drawn with the pen stays unselected, so the selection box and- - - // author popup don't sit over the next stroke (#429).- - - Edit::AddAnnotation(a)- - - if matches!(a.shape, pdfcraft_engine::Shape::Ink { .. })- - - && self.quick_tool == crate::QuickTool::Comment(crate::comments::CommentTool::Ink) =>- - - {- - - view.comments.selected = None;- - - }- - - Edit::AddAnnotation(a) => {- - - // Select the new comment (appended last among the page's comments).- - - let newest = info.annotations.iter().filter(|x| x.page == a.page && !x.is_reply()).map(|x| x.index).max();- - - view.comments.selected = newest.map(|n| (a.page, n));- - - view.comments.reveal = true;- - - // A new highlight opens its note for typing straight away, as in Acrobat,- - - // unless a note typed into another card is still unsaved.- - - if let (pdfcraft_engine::Shape::TextMarkup { kind: pdfcraft_engine::Markup::Highlight, .. }, Some(n)) = (&a.shape, newest)- - - && a.contents.is_empty()- - - && view.comments.editing.is_none()- - - {- - - view.comments.open_editor(a.page, n, String::new());- - - }- - - }- - - Edit::DeleteAnnotation { .. } => view.comments.selected = None,- - - _ => {}- - - }+++++++ ++++++++++++++ select_after_edit(view, edit, info, &annots_before, self.quick_tool);if std::mem::take(&mut view.comments.tool_done) && !self.comment_prefs.pinned {self.quick_tool = crate::QuickTool::Select;}diff --cc crates/ui-egui/src/lib.rsindex 440c0d13c,8a8c51775,8a8c51775,8a8c51775,8a8c51775,65bc7e4b1,317c2b45c,8a8c51775,8a8c51775,8a8c51775,65bc7e4b1,8a8c51775,f8237f7fa,8a8c51775,65bc7e4b1,8a8c51775,65bc7e4b1,8a8c51775,65bc7e4b1,65bc7e4b1,440c0d13c,c2ba05ad9..222bb988e--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@@@@@@@@@@@@@@@@@@@@@@ -84,8 -75,8 -75,8 -75,8 -75,8 -75,7 -75,9 -75,8 -75,8 -75,8 -75,7 -75,8 -75,8 -75,8 -75,7 -75,8 -75,7 -75,8 -75,7 -75,7 -84,8 -84,8 +84,9 @@@@@@@@@@@@@@@@@@@@@@@ use canvas::autoscrolluse canvas::crop;use canvas::fling;use canvas::image_pick;+ + + + ++ use canvas::page_cursor;use canvas::page_pointer;++++++ +++++++++++++++use canvas::page_router;pub use canvas::scroll_speed;use canvas::signature_drag;use canvas::wheel_boost;diff --cc crates/ui-egui/src/tools/comments.rsindex 5909fdd42,5909fdd42,5909fdd42,5909fdd42,5909fdd42,674a3b4ea,a6e718ce7,38a354014,5909fdd42,5909fdd42,674a3b4ea,5909fdd42,5909fdd42,5909fdd42,674a3b4ea,5909fdd42,674a3b4ea,5909fdd42,674a3b4ea,674a3b4ea,5909fdd42,5909fdd42..e9956e5f9--- a/crates/ui-egui/src/tools/comments.rs+++ b/crates/ui-egui/src/tools/comments.rs@@@@@@@@@@@@@@@@@@@@@@@ -35,9 -35,9 -35,9 -35,9 -35,9 -35,7 -35,9 -35,9 -35,9 -35,9 -35,7 -35,9 -35,9 -35,9 -35,7 -35,9 -35,7 -35,9 -35,7 -35,7 -35,9 -35,9 +35,9 @@@@@@@@@@@@@@@@@@@@@@@ use geometry::handle_pospub(crate) use geometry::{caret_snap, snapped_caret};pub(crate) use geometry::{corner_ratio, page_rotation, resized};pub use geometry::{drawn_text_box_rect, text_box_rect};- - - - -- pub(crate) use input::{fill_grabs, keys, nudge_keys, page_after_text, page_input, select_grabs};+ + + + ++ #[cfg(test)]+ + + + ++ use input::hover_tip;----- --- --- - - --pub(crate) use input::{describe, fill_grabs, keys, nudge_keys, page_after_text, page_input, select_grabs};++++++ +++++++++++++++pub(crate) use input::{describe, fill_grabs, hit, keys, nudge_keys, page_after_text, page_input};pub use menu::{CanvasAction, fill_picker, recent_custom_colours, remember_custom_colour, status_badge, swatch_grid};#[cfg(test)]use menu::{RECENT_CUSTOM, same_colour};diff --cc crates/ui-egui/src/tools/comments/input.rsindex af78a1e46,af78a1e46,af78a1e46,af78a1e46,af78a1e46,d8cc33400,17e1e102c,af78a1e46,af78a1e46,af78a1e46,d8cc33400,2c4f4f059,af78a1e46,af78a1e46,ef0341b71,af78a1e46,ef0341b71,af78a1e46,d8cc33400,ef0341b71,af78a1e46,af78a1e46..5e74fdf56--- a/crates/ui-egui/src/tools/comments/input.rs+++ b/crates/ui-egui/src/tools/comments/input.rs@@@@@@@@@@@@@@@@@@@@@@@ -4,8 -4,8 -4,8 -4,8 -4,8 -4,7 -4,9 -4,8 -4,8 -4,8 -4,7 -4,8 -4,8 -4,8 -4,7 -4,8 -4,7 -4,8 -4,7 -4,7 -4,8 -4,8 +4,9 @@@@@@@@@@@@@@@@@@@@@@@ use super::geometry::};use super::paint::{drawn_shape, edit_anchor, erase, new_comment};use super::state::{Composer, ComposerKind, Gesture, PageCx};- - - use super::*;- - - use super::{Annotation, CommentTool, DocInfo, DocView, Edit, Pos2, QuickTool, Rect, Shape, vec2};+ + + + ++ use super::{Annotation, CommentPrefs, CommentTool, DocInfo, DocView, Edit, Pos2, QuickTool, Rect, Shape, vec2};+ + + + ++ use crate::page_cursor::{Layer, Subject};++++++ +++++++++++++++use crate::page_router::{CommentPart, Hit, Owner};/// Comment input on one page, before text selection runs. Returns `true` when the pointer/// gesture belongs to commenting (text selection must ignore it).@@@@@@@@@@@@@@@@@@@@@@@ -32,197 -32,197 -32,197 -32,197 -32,197 -31,380 -33,182 -32,197 -32,197 -32,197 -31,380 -32,197 -32,197 -32,197 -31,148 -32,197 -31,148 -32,197 -31,380 -31,148 -32,197 -32,197 +33,182 @@@@@@@@@@@@@@@@@@@@@@@ pub(crate) fn page_input(ui: &egui::Uicv.context_at = Some((cx.page, cx.to_user(p)));cv.selected = cx.hit(p).map(|a| (cx.page, a.index));}+ + + let gestures = Gestures { ui, resp, cx, pointer, origin, page_rect, pressed_here, over_page };match cx.tool {- - - // The shape just drawn is selected with its handles showing: they resize it without a- - - // trip to the Select tool (#2338). Anywhere else the tool keeps drawing.------ --------------- QuickTool::Comment(_) if draw_grab => select_input(ui, resp, cx, view, pointer, origin, pressed_here),- - - QuickTool::Comment(tool) if tool.draws() => {- - - if !cx.allowed {- - - return false;- - - }- - - if over_page {- - - ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair);- - - }- - - if resp.drag_started()- - - && pressed_here- - - && let Some(o) = origin- - - {- - - cv.gesture = Some(Gesture::Draw { page: cx.page, tool, points: vec![cx.to_user(o)] });- - - cv.selected = None;- - - }- - - if let Some(Gesture::Draw { page, tool, points }) = cv.gesture.as_mut()- - - && *page == cx.page- - - && let Some(p) = pointer- - - {- - - let p = clamp_to(page_rect, p);- - - let u = cx.to_user(p);- - - if matches!(*tool, CommentTool::Ink | CommentTool::Eraser) {- - - let last = points.last().map(|l| cx.to_screen(*l)).unwrap_or(p);- - - if last.distance(p) >= 1.5 {- - - points.push(u);- - - }- - - } else {- - - points.truncate(1);- - - points.push(u);- - - }- - - }- - - if resp.drag_stopped()- - - && let Some(Gesture::Draw { page, tool, points }) = cv.gesture.clone()- - - && page == cx.page- - - {- - - cv.gesture = None;- - - if tool == CommentTool::Eraser {- - - view.pending_edit = erase(cx, &points);- - - } else if let Some(shape) = drawn_shape(tool, &points) {- - - let now = ui.input(|i| i.time);- - - cv.settle(now, page, tool, &points);- - - view.pending_edit = Some(new_comment(cx, tool, shape, String::new()));- - - }- - - }- - - // A quick press/release does not start an egui drag, but Acrobat's Draw tool treats- - - // it as a one-point ink stroke (a dot). The appearance uses round line caps, so a- - - // single PDF point is visible and remains editable like any other drawing.- - - if tool == CommentTool::Ink- - - && resp.clicked()- - - && over_page- - - && let Some(p) = pointer- - - && let Some(shape) = drawn_shape(tool, &[cx.to_user(p)])- - - {- - - cv.selected = None;- - - let now = ui.input(|i| i.time);- - - cv.settle(now, cx.page, tool, &[cx.to_user(p)]);- - - view.pending_edit = Some(new_comment(cx, tool, shape, String::new()));- - - }- - - true- - - }- - - QuickTool::Comment(tool) if tool.clicks_points() => {- - - if !cx.allowed {- - - return false;- - - }- - - if over_page {- - - ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair);- - - }- - - let finish = resp.double_clicked() || ui.input(|i| i.key_pressed(egui::Key::Enter));- - - // Backspace (or Delete) takes back the last point, e.g. after a wrong click; Undo does too.- - - // Only while a drawing is in progress: otherwise Delete belongs to the selected comment.- - - if matches!(cv.gesture, Some(Gesture::Draw { page, .. }) if page == cx.page)- - - && !ui.ctx().egui_wants_keyboard_input()- - - && ui.input_mut(|i| {- - - i.consume_key(egui::Modifiers::NONE, egui::Key::Backspace) || i.consume_key(egui::Modifiers::NONE, egui::Key::Delete)- - - })- - - {- - - cv.undo_point();- - - return true;- - - }- - - if resp.clicked()- - - && over_page- - - && let Some(p) = pointer- - - {- - - let u = cx.to_user(p);- - - match cv.gesture.as_mut() {- - - Some(Gesture::Draw { page, tool: t, points }) if *page == cx.page && *t == tool => {- - - // Clicking the first point again closes a polygon.- - - let closes = points.len() >= 3 && tool != CommentTool::PolyLine && cx.to_screen(points[0]).distance(p) <= 6.0;- - - let repeat = points.last().is_some_and(|l| cx.to_screen(*l).distance(p) < 2.0);- - - if closes {- - - let pts = std::mem::take(points);- - - cv.gesture = None;- - - if let Some(shape) = drawn_shape(tool, &pts) {- - - view.pending_edit = Some(new_comment(cx, tool, shape, String::new()));- - - }- - - return true;- - - }- - - if !repeat {- - - points.push(u);- - - }- - - }- - - _ => {- - - cv.gesture = Some(Gesture::Draw { page: cx.page, tool, points: vec![u] });- - - cv.selected = None;- - - }- - - }- - - }- - - if finish- - - && let Some(Gesture::Draw { page, tool: t, points }) = cv.gesture.clone()- - - && page == cx.page- - - && t == tool- - - {- - - cv.gesture = None;- - - if let Some(shape) = drawn_shape(tool, &points) {- - - view.pending_edit = Some(new_comment(cx, tool, shape, String::new()));- - - }- - - }- - - true- - - }- - - QuickTool::Comment(CommentTool::Callout) => {- - - // Drag from what the callout points at to where its text box goes.- - - if !cx.allowed {- - - return false;- - - }- - - if over_page {- - - ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair);- - - }- - - if resp.drag_started()- - - && pressed_here- - - && let Some(o) = origin- - - {- - - cv.gesture = Some(Gesture::Draw { page: cx.page, tool: CommentTool::Callout, points: vec![cx.to_user(o)] });- - - cv.selected = None;- - - }- - - if let Some(Gesture::Draw { page, points, .. }) = cv.gesture.as_mut()- - - && *page == cx.page- - - && let Some(p) = pointer- - - {- - - points.truncate(1);- - - points.push(cx.to_user(clamp_to(page_rect, p)));- - - }- - - if resp.drag_stopped()- - - && let Some(Gesture::Draw { page, points, .. }) = cv.gesture.clone()- - - && page == cx.page- - - {- - - cv.gesture = None;- - - if let [point, at] = points[..]- - - && (point[0] - at[0]).hypot(point[1] - at[1]) >= 8.0- - - {- - - cv.composer = Some(Composer { page, at, kind: ComposerKind::Callout { point }, text: String::new(), focus: true });- - - }- - - }- - - true- - - }- - - QuickTool::Comment(CommentTool::Attach) => {- - - if !cx.allowed {- - - return false;- - - }- - - if over_page {- - - ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair);- - - }- - - if resp.clicked()- - - && over_page- - - && let Some(p) = pointer- - - {- - - cv.attach_at = Some((cx.page, cx.to_user(p)));- - - cv.selected = None;- - - }- - - true- - - }- - - QuickTool::Comment(CommentTool::Caret) => {- - - if !cx.allowed {- - - return false;- - - }- - - if over_page {- - - ui.ctx().set_cursor_icon(egui::CursorIcon::Text);- - - }- - - if resp.clicked()- - - && over_page- - - && let Some(p) = pointer- - - {- - - let (vx, vy) = cx.xf.screen_to_view(p);- - - let snapped = cx.info.pages.get(cx.page).zip(caret_text.as_deref()).and_then(|(page, t)| snapped_caret(page, t, vx, vy));- - - let (at, size) = snapped.unwrap_or_else(|| (cx.to_user(p), CARET_SIZE));- - - cv.composer = Some(Composer { page: cx.page, at, kind: ComposerKind::Caret { size }, text: String::new(), focus: true });- - - cv.selected = None;- - - }- - - true- - - }- - - QuickTool::Comment(tool @ (CommentTool::Note | CommentTool::TextBox)) => {- - - if !cx.allowed {- - - return false;- - - }- - - if over_page {- - - ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair);- - - }- - - // A text box also takes a drag, as in Acrobat: the box is drawn at that size and its- - - // text wraps inside it (#2669).- - - if tool == CommentTool::TextBox {- - - if resp.drag_started()- - - && pressed_here- - - && let Some(o) = origin- - - {- - - cv.gesture = Some(Gesture::Draw { page: cx.page, tool, points: vec![cx.to_user(o)] });- - - cv.selected = None;- - - }- - - if let Some(Gesture::Draw { page, points, .. }) = cv.gesture.as_mut()- - - && *page == cx.page- - - && let Some(p) = pointer- - - {- - - points.truncate(1);- - - points.push(cx.to_user(clamp_to(page_rect, p)));- - - }- - - if resp.drag_stopped()- - - && let Some(Gesture::Draw { page, points, .. }) = cv.gesture.clone()- - - && page == cx.page- - - {- - - cv.gesture = None;- - - if let (Some(first), Some(last)) = (points.first(), points.last()) {- - - let r = Rect::from_two_pos(cx.to_screen(*first), cx.to_screen(*last));- - - // A drag of a few pixels is a click: the box fits its text.- - - let drawn =- - - (r.width() >= 6.0 && r.height() >= 6.0).then(|| cx.info.pages.get(page)).flatten().map(|p| drawn_box(p, *first, *last));- - - let (at, size) = drawn.map_or((*first, None), |(at, size)| (at, Some(size)));- - - cv.composer = Some(Composer { page, at, kind: ComposerKind::TextBox { size }, text: String::new(), focus: true });- - - }- - - }- - - }- - - if resp.clicked()- - - && over_page- - - && let Some(p) = pointer- - - {- - - let kind = if tool == CommentTool::Note { ComposerKind::Note } else { ComposerKind::TextBox { size: None } };- - - cv.composer = Some(Composer { page: cx.page, at: cx.to_user(p), kind, text: String::new(), focus: true });- - - cv.selected = None;- - - }- - - true- - - }- - - QuickTool::Select => select_input(ui, resp, cx, view, pointer, origin, pressed_here),- - - QuickTool::Fill(_) if fill_grab => select_input(ui, resp, cx, view, pointer, origin, pressed_here),++++++ +++++++++++++++ QuickTool::Comment(_) if draw_grab => select_input(ui, resp, cx, view, pointer, origin),+ + + QuickTool::Comment(tool) if tool.draws() => gestures.draw_shape(view, tool),+ + + QuickTool::Comment(tool) if tool.clicks_points() => gestures.click_points(view, tool),+ + + QuickTool::Comment(CommentTool::Callout) => gestures.callout(view),+ + + QuickTool::Comment(CommentTool::Attach) => gestures.attach(view),+ + + QuickTool::Comment(CommentTool::Caret) => gestures.caret(view, caret_text.as_deref()),+ + + QuickTool::Comment(tool @ (CommentTool::Note | CommentTool::TextBox)) => gestures.note_or_box(view, tool),----- --- ------- --- QuickTool::Select => select_input(ui, resp, cx, view, pointer, origin, pressed_here),----- --- ------- --- QuickTool::Fill(_) if fill_grab => select_input(ui, resp, cx, view, pointer, origin, pressed_here),++++++ +++++++++++++++ QuickTool::Select => select_input(ui, resp, cx, view, pointer, origin),++++++ +++++++++++++++ QuickTool::Fill(_) if fill_grab => select_input(ui, resp, cx, view, pointer, origin),_ => false,}}------ ---------------/// With a Fill & Sign tool, the Fill & Sign marks already on the page are picked up as with the------ ---------------/// Select tool, as in Acrobat: hovering one shows the move cursor, a click selects it, a drag------ ---------------/// moves it and the selected one's handles resize it. Elsewhere the tool places its mark. While------ ---------------/// the button is down the press decides; otherwise the pointer (egui clears the press origin on------ ---------------/// release, so a click is located by the pointer).------ ---------------pub(crate) fn fill_grabs(cx: &PageCx<'_>, view: &DocView) -> bool {------ --------------- matches!(cx.tool, QuickTool::Fill(_)) && grabs(cx, view, |a| a.fill_sign)------ ---------------}------ --------------------- ---------------/// With the Select tool, a comment that would move (not text markup) is picked up before a form------ ---------------/// field under it, so a signature placed over a field can still be dragged off it.------ ---------------pub(crate) fn select_grabs(cx: &PageCx<'_>, view: &DocView) -> bool {------ --------------- cx.tool == QuickTool::Select && grabs(cx, view, |a| !is_markup(&a.subtype))------ ------- - -- --}------ ------- - -- -------- ------- - -- --/// With a shape tool (rectangle, oval, line, polygon…), the selected comment's resize handles------ ------- - -- --/// are picked up as with the Select tool, so the shape just drawn can be resized straight away------ ------- - -- --/// (#2338). Only the handles: a press anywhere else, the shape itself included, still draws.------ ------- - -- --pub(crate) fn draw_grabs(cx: &PageCx<'_>, view: &DocView) -> bool {------ ------- - -- -- let QuickTool::Comment(tool) = cx.tool else { return false };------ ------- - -- -- if !(tool.draws() || tool.clicks_points()) || tool == CommentTool::Eraser || cx.hidden {------ ------- - -- -- return false;----- --- -- - - -- }----- --- -- - - -- let cv = &view.comments;----- --- -- - - -- if matches!(cv.gesture, Some(Gesture::Resize { page, .. } | Gesture::Reshape { page, .. }) if page == cx.page) {----- --- -- - - -- return true;++++++ +++++++++++++++/// What of the comments lies under `p`, for the cursor, the tip and the press: the one hit test++++++ +++++++++++++++/// of this module. With the Select tool, the selected comment's point handles, then its resize++++++ +++++++++++++++/// handles, then the topmost comment. With a Fill & Sign tool, the same over Fill & Sign's marks++++++ +++++++++++++++/// only, as Acrobat picks them up: a press anywhere else places the tool's mark. With a shape++++++ +++++++++++++++/// tool (rectangle, oval, line, polygon…), only the selected comment's handles, so the shape just++++++ +++++++++++++++/// drawn can be resized straight away (#2338); a press anywhere else, the shape itself included,++++++ +++++++++++++++/// draws. `None` with other tools, off the page, or with comments hidden.++++++ +++++++++++++++pub(crate) fn hit(cx: &PageCx<'_>, view: &DocView, p: Pos2) -> Option<Hit> {++++++ +++++++++++++++ if cx.hidden || !cx.xf.rect.contains(p) {++++++ +++++++++++++++ return None;+ + + }----- --- -- - - -- // A polygon being clicked out keeps its clicks, even near an old shape's handle.----- --- -- - - -- if cv.gesture.is_some() {----- --- -- - - -- return false;- -- - let cv = &view.comments;- -- - if matches!(cv.gesture, Some(Gesture::Resize { page, .. } | Gesture::Reshape { page, .. }) if page == cx.page) {- -- - return true;++++++ +++++++++++++++ let pick: fn(&Annotation) -> bool = match cx.tool {++++++ +++++++++++++++ QuickTool::Select => |_| true,++++++ +++++++++++++++ QuickTool::Fill(_) => |a| a.fill_sign,++++++ +++++++++++++++ QuickTool::Comment(tool) if (tool.draws() || tool.clicks_points()) && tool != CommentTool::Eraser => {++++++ +++++++++++++++ // A polygon being clicked out keeps its clicks, even near an old shape's handle.++++++ +++++++++++++++ if view.comments.gesture.is_some() {++++++ +++++++++++++++ return None;++++++ +++++++++++++++ }++++++ +++++++++++++++ |_| true++++++ +++++++++++++++ }++++++ +++++++++++++++ _ => return None,++++++ +++++++++++++++ };++++++ +++++++++++++++ let bodies = matches!(cx.tool, QuickTool::Select | QuickTool::Fill(_));++++++ +++++++++++++++ if let Some(a) = view.comments.selected.filter(|(page, _)| *page == cx.page).and_then(|(_, i)| cx.get(i)).filter(|a| pick(a) && cx.allowed) {++++++ +++++++++++++++ if grabs_points(cx.tool)++++++ +++++++++++++++ && reshapable(a)++++++ +++++++++++++++ && let Some(point) = point_handle(cx, a, p)++++++ +++++++++++++++ {++++++ +++++++++++++++ return Some(Hit::new(Owner::Comment { index: a.index, part: CommentPart::Point(point) }, Layer::Handle, egui::CursorIcon::Crosshair));++++++ +++++++++++++++ }++++++ +++++++++++++++ if resizable(a)++++++ +++++++++++++++ && let Some((x, y)) = HANDLES.into_iter().find(|h| handle_pos(cx.screen_rect(a), *h).distance(p) <= 7.0)++++++ +++++++++++++++ {++++++ +++++++++++++++ let icon = match (x, y) {++++++ +++++++++++++++ (0, _) => egui::CursorIcon::ResizeVertical,++++++ +++++++++++++++ (_, 0) => egui::CursorIcon::ResizeHorizontal,++++++ +++++++++++++++ (-1, -1) | (1, 1) => egui::CursorIcon::ResizeNwSe,++++++ +++++++++++++++ _ => egui::CursorIcon::ResizeNeSw,++++++ +++++++++++++++ };++++++ +++++++++++++++ return Some(Hit::new(Owner::Comment { index: a.index, part: CommentPart::Handle(x, y) }, Layer::Handle, icon));++++++ +++++++++++++++ }+++++ +++ ++++++ +++ }- -- - // A polygon being clicked out keeps its clicks, even near an old shape's handle.- -- - if cv.gesture.is_some() {- -- - return false;++++++ +++++++++++++++ let a = cx.hit(p).filter(|a| bodies && pick(a))?;++++++ +++++++++++++++ // A click on a highlight over a link follows the link, so the link's hand and tip show there.++++++ +++++++++++++++ if cx.tool == QuickTool::Select && a.subtype == "Highlight" && on_link(cx, p) {++++++ +++++++++++++++ return None;+ + + }------ ------- - -- -- press_point(cx).is_some_and(|p| on_handle(cx, view, p, |_| true))++++++ +++++++++++++++ let markup = is_markup(&a.subtype);++++++ +++++++++++++++ let icon = if cx.allowed && !markup { egui::CursorIcon::Move } else { egui::CursorIcon::PointingHand };++++++ +++++++++++++++ // What a drag moves whole (a note, a shape, a signature, a Fill & Sign mark) is placed on the++++++ +++++++++++++++ // page, over a form field; text markup lies on the text, under one.++++++ +++++++++++++++ let layer = if a.fill_sign || !markup { Layer::Placed } else { Layer::Comment };++++++ +++++++++++++++ // Text markup does not move: a click selects it, a drag across it selects the text.++++++ +++++++++++++++ Some(Hit { declines_drag: markup, ..Hit::new(Owner::Comment { index: a.index, part: CommentPart::Body }, layer, icon) })}------ ------- - -- --/// Whether the press (or, with no button down, the pointer) is on a `pick` comment or on the------ ------- - -- --/// selected one's resize handles.------ ------- - -- --fn grabs(cx: &PageCx<'_>, view: &DocView, pick: impl Fn(&Annotation) -> bool) -> bool {------ ------- - -- -- if cx.hidden {- - - /// With a shape tool (rectangle, oval, line, polygon…), the selected comment's resize handles- - - /// are picked up as with the Select tool, so the shape just drawn can be resized straight away- - - /// (#2338). Only the handles: a press anywhere else, the shape itself included, still draws.- - - pub(crate) fn draw_grabs(cx: &PageCx<'_>, view: &DocView) -> bool {- - - let QuickTool::Comment(tool) = cx.tool else { return false };- - - if !(tool.draws() || tool.clicks_points()) || tool == CommentTool::Eraser || cx.hidden {------ --------------- return false;------ --------------- }- - - let cv = &view.comments;- - - if matches!(cv.gesture, Some(Gesture::Resize { page, .. } | Gesture::Reshape { page, .. }) if page == cx.page) {++++++ +++++++++++++++/// Whether the comments take the press on this page (or, with no button down, would take one++++++ +++++++++++++++/// under the pointer), so the tools beneath leave it: a live move, resize or reshape, or a press++++++ +++++++++++++++/// held by a comment that keeps its drag.++++++ +++++++++++++++fn grabs(cx: &PageCx<'_>, view: &DocView) -> bool {+ + + if matches!(view.comments.gesture, Some(Gesture::Move { page, .. } | Gesture::Resize { page, .. } | Gesture::Reshape { page, .. }) if page == cx.page)+ + + {return true;}------ ------- - -- -- let Some(p) = press_point(cx) else { return false };------ ------- - -- -- on_handle(cx, view, p, &pick) || cx.hit(p).is_some_and(pick)- - - // A polygon being clicked out keeps its clicks, even near an old shape's handle.- - - if cv.gesture.is_some() {- - - return false;++++++ +++++++++++++++ if cx.ptr.any_down {++++++ +++++++++++++++ return matches!(view.router.owner(cx.page), Some(Owner::Comment { .. })) && view.router.keeps_drag();++++++ +++++++ + ++ ++ }- - - press_point(cx).is_some_and(|p| on_handle(cx, view, p, |_| true))++++++ +++++++++++++++ cx.ptr.pos.and_then(|p| hit(cx, view, p)).is_some_and(|h| !h.declines_drag)}------ ------- - -- --/// Where a gesture on this page is decided: the press while the button is down, otherwise the------ ------- - -- --/// pointer (egui clears the press origin on release). `None` off the page.------ ------- - -- --fn press_point(cx: &PageCx<'_>) -> Option<Pos2> {------ ------- - -- -- (if cx.ptr.any_down { cx.ptr.origin } else { cx.ptr.pos }).filter(|p| cx.xf.rect.contains(*p))- - - /// Whether the press (or, with no button down, the pointer) is on a `pick` comment or on the- - - /// selected one's resize handles.- - - fn grabs(cx: &PageCx<'_>, view: &DocView, pick: impl Fn(&Annotation) -> bool) -> bool {- - - if cx.hidden {- - - return false;- - - }- - - if matches!(view.comments.gesture, Some(Gesture::Move { page, .. } | Gesture::Resize { page, .. } | Gesture::Reshape { page, .. }) if page == cx.page)- - - {- - - return true;- - - }- - - let Some(p) = press_point(cx) else { return false };- - - on_handle(cx, view, p, &pick) || cx.hit(p).is_some_and(pick)++++++ +++++++++++++++/// With a Fill & Sign tool, a Fill & Sign mark already on the page is picked up as with the Select++++++ +++++++++++++++/// tool ([`hit`]), so the tool does not place a mark there.++++++ +++++++++++++++pub(crate) fn fill_grabs(cx: &PageCx<'_>, view: &DocView) -> bool {++++++ +++++++++++++++ matches!(cx.tool, QuickTool::Fill(_)) && grabs(cx, view)}------ ------- - -- --/// Whether `p` is on a resize handle of the selected comment, when it is a resizable `pick`.------ ------- - -- --fn on_handle(cx: &PageCx<'_>, view: &DocView, p: Pos2, pick: impl Fn(&Annotation) -> bool) -> bool {------ ------- - -- -- view.comments.selected.filter(|(page, _)| *page == cx.page).and_then(|(_, i)| cx.get(i)).filter(|a| pick(a) && cx.allowed).is_some_and(|a| {------ ------- - -- -- (resizable(a) && HANDLES.into_iter().any(|h| handle_pos(cx.screen_rect(a), h).distance(p) <= 7.0))------ ------- - -- -- || (grabs_points(cx.tool) && reshapable(a) && point_handle(cx, a, p).is_some())------ ------- - -- -- })- - - /// Where a gesture on this page is decided: the press while the button is down, otherwise the- - - /// pointer (egui clears the press origin on release). `None` off the page.- - - fn press_point(cx: &PageCx<'_>) -> Option<Pos2> {- - - (if cx.ptr.any_down { cx.ptr.origin } else { cx.ptr.pos }).filter(|p| cx.xf.rect.contains(*p))++++++ +++++++++++++++/// With a shape tool, the selected comment's handles are picked up ([`hit`]).++++++ +++++++++++++++fn draw_grabs(cx: &PageCx<'_>, view: &DocView) -> bool {++++++ +++++++++++++++ matches!(cx.tool, QuickTool::Comment(_)) && grabs(cx, view)}- - - /// The Select tool: hover, select, move, resize, edit, delete.- - - fn select_input(- - - ui: &egui::Ui,- - - resp: &egui::Response,- - - cx: &PageCx<'_>,- - - view: &mut DocView,- - - pointer: Option<Pos2>,- - - origin: Option<Pos2>,- - - pressed_here: bool,- - - ) -> bool {- - - let cv = &mut view.comments;- - - let selected = cv.selected.filter(|(p, _)| *p == cx.page).and_then(|(_, i)| cx.get(i));- - - // Handles of a selected, resizable comment.- - - let handle_at = |p: Pos2| -> Option<(i8, i8)> {- - - let a = selected.filter(|a| cx.allowed && resizable(a))?;- - - let r = cx.screen_rect(a);- - - HANDLES.into_iter().find(|h| handle_pos(r, *h).distance(p) <= 7.0)- - - /// Whether `p` is on a resize handle of the selected comment, when it is a resizable `pick`.- - - fn on_handle(cx: &PageCx<'_>, view: &DocView, p: Pos2, pick: impl Fn(&Annotation) -> bool) -> bool {- - - view.comments.selected.filter(|(page, _)| *page == cx.page).and_then(|(_, i)| cx.get(i)).filter(|a| pick(a) && cx.allowed).is_some_and(|a| {- - - (resizable(a) && HANDLES.into_iter().any(|h| handle_pos(cx.screen_rect(a), h).distance(p) <= 7.0))- - - || (grabs_points(cx.tool) && reshapable(a) && point_handle(cx, a, p).is_some())- - - })+ + + + ++ /// Whether `p` is on one of this page's links.+ + + + ++ fn on_link(cx: &PageCx<'_>, p: Pos2) -> bool {+ + + + ++ cx.info.links.iter().any(|link| link.page == cx.page && cx.xf.user_rect(cx.info, cx.page, link.rect).contains(p))+ + + }+ + +- - - /// The Select tool: hover, select, move, resize, edit, delete.- - - fn select_input(- - - ui: &egui::Ui,- - - resp: &egui::Response,- - - cx: &PageCx<'_>,- - - view: &mut DocView,- - - pointer: Option<Pos2>,- - - origin: Option<Pos2>,- - - pressed_here: bool,- - - ) -> bool {- - - let cv = &mut view.comments;- - - let selected = cv.selected.filter(|(p, _)| *p == cx.page).and_then(|(_, i)| cx.get(i));- - - // Handles of a selected, resizable comment.- - - let handle_at = |p: Pos2| -> Option<(i8, i8)> {- - - let a = selected.filter(|a| cx.allowed && resizable(a))?;- - - let r = cx.screen_rect(a);- - - HANDLES.into_iter().find(|h| handle_pos(r, *h).distance(p) <= 7.0)+ + + + ++ /// The tip for the comment under the pointer, with any tool, beside that tool's own cursor: Acrobat+ + + + ++ /// shows a comment's tooltip whatever tool is active. Not with Fill & Sign, whose placement stays+ + + + ++ /// clear; not while drawing freehand, where it would cover the next stroke (#429); and not while a+ + + + ++ /// comment is moved, resized or drawn.+ + + + ++ pub(crate) fn describe(cx: &PageCx<'_>, view: &mut DocView) {+ + + + ++ let freehand = matches!(cx.tool, QuickTool::Comment(CommentTool::Ink | CommentTool::Eraser));+ + + + ++ if matches!(cx.tool, QuickTool::Fill(_)) || freehand || view.comments.gesture.is_some() {+ + + + ++ return;+ + + + ++ }+ + + + ++ let Some(p) = cx.ptr.pos else { return };+ + + + ++ // Inspection sorts comments by position, but the renderer paints them in `/Annots` order: the+ + + + ++ // tip is that of the one drawn on top, among those with something to say (#3620).+ + + + ++ let top = cx+ + + + ++ .comments()+ + + + ++ .filter(|a| cx.screen_rects(a).any(|r| r.contains(p)))+ + + + ++ .filter_map(|a| hover_tip(a, cx.prefs).map(|text| (a.index, text)))+ + + + ++ .max_by_key(|(index, _)| *index);+ + + + ++ if let Some((_, text)) = top {+ + + + ++ view.cursor.describe(Subject::Comment, text);+ + + + ++ }+ + + + ++ }+ + + + +++ + + + ++ /// What hovering `a` says, as Acrobat's popups do. Replies and Fill & Sign's marks (typed text,+ + + + ++ /// checks, signatures) say nothing: they are page content being edited, not comments. Neither+ + + + ++ /// does a highlight with no text of its own, when the preferences say so.+ + + + ++ pub(super) fn hover_tip(a: &Annotation, prefs: &CommentPrefs) -> Option<String> {+ + + + ++ let empty_highlight = a.subtype == "Highlight" && a.contents.as_deref().is_none_or(str::is_empty);+ + + + ++ if a.is_reply() || a.fill_sign || prefs.hide_empty_highlight_hover && empty_highlight {+ + + + ++ return None;+ + + + ++ }+ + + + ++ let who = a.author.clone().unwrap_or_else(|| a.subtype.clone());+ + + + ++ let body = a.contents.clone().unwrap_or_default();+ + + + ++ Some(if body.is_empty() { who } else { format!("{who}\n{body}") })+ + + + ++ }+ + + + ++----- --- --- - - --/// The Select tool: hover, select, move, resize, edit, delete.----- --- --- - - --fn select_input(----- --- --- - - -- ui: &egui::Ui,----- --- --- - - -- resp: &egui::Response,----- --- --- - - -- cx: &PageCx<'_>,----- --- --- - - -- view: &mut DocView,----- --- --- - - -- pointer: Option<Pos2>,----- --- --- - - -- origin: Option<Pos2>,----- --- --- - - -- pressed_here: bool,----- --- --- - - --) -> bool {----- --- --- - - -- let cv = &mut view.comments;----- --- --- - - -- let selected = cv.selected.filter(|(p, _)| *p == cx.page).and_then(|(_, i)| cx.get(i));----- --- --- - - -- // Handles of a selected, resizable comment.----- --- --- - - -- let handle_at = |p: Pos2| -> Option<(i8, i8)> {----- --- --- - - -- let a = selected.filter(|a| cx.allowed && resizable(a))?;----- --- --- - - -- let r = cx.screen_rect(a);----- --- --- - - -- HANDLES.into_iter().find(|h| handle_pos(r, *h).distance(p) <= 7.0)++++++ +++++++++++++++/// The Select tool: select, move, resize, edit, delete, on the comment the press was on (its++++++ +++++++++++++++/// owner, from [`hit`]). The cursor comes from [`hit`] too.++++++ +++++++++++++++fn select_input(ui: &egui::Ui, resp: &egui::Response, cx: &PageCx<'_>, view: &mut DocView, pointer: Option<Pos2>, origin: Option<Pos2>) -> bool {++++++ +++++++++++++++ let owner = match view.router.owner(cx.page) {++++++ +++++++++++++++ Some(Owner::Comment { index, part }) => cx.get(index).map(|a| (a, part)),++++++ +++++++++++++++ _ => None,};------ --------------- // Ends and corners of a selected line, connected lines, polygon or cloud.------ --------------- let point_at =------ --------------- |p: Pos2| -> Option<usize> { selected.filter(|a| cx.allowed && grabs_points(cx.tool) && reshapable(a)).and_then(|a| point_handle(cx, a, p)) };++++++ +++++++++++++++ let cv = &mut view.comments;let mut consumed = false;------ --------------- if let Some(p) = pointer {------ --------------- if point_at(p).is_some() {----- --- --- - - -- view.cursor.claim(Layer::Handle, egui::CursorIcon::Crosshair);- - - - -- ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair);------ --------------- } else if let Some(h) = handle_at(p) {----- --- --- - - -- view.cursor.claim(----- --- --- - - -- Layer::Handle,----- --- --- - - -- match h {----- --- --- - - -- (0, _) => egui::CursorIcon::ResizeVertical,----- --- --- - - -- (_, 0) => egui::CursorIcon::ResizeHorizontal,----- --- --- - - -- (-1, -1) | (1, 1) => egui::CursorIcon::ResizeNwSe,----- --- --- - - -- _ => egui::CursorIcon::ResizeNeSw,----- --- --- - - -- },----- --- --- - - -- );----- --- --- - - -- } else if let Some(a) = cx.hit(p)----- --- --- - - -- // A click on a highlight over a link follows the link, so the link's hand and tip----- --- --- - - -- // show there.----- --- --- - - -- && !(a.subtype == "Highlight" && on_link(cx, p))----- --- --- - - -- {- - - - -- ui.ctx().set_cursor_icon(match h {- - - - -- (0, _) => egui::CursorIcon::ResizeVertical,- - - - -- (_, 0) => egui::CursorIcon::ResizeHorizontal,- - - - -- (-1, -1) | (1, 1) => egui::CursorIcon::ResizeNwSe,- - - - -- _ => egui::CursorIcon::ResizeNeSw,- - - - -- });- - - - -- } else if let Some(a) = cx.hit(p) {------ --------------- let movable = cx.allowed && !is_markup(&a.subtype);----- --- --- - - -- let icon = if movable { egui::CursorIcon::Move } else { egui::CursorIcon::PointingHand };----- --- --- - - -- // Signatures and Fill & Sign's marks are placed on the page rather than comments on it.----- --- --- - - -- view.cursor.claim(if a.fill_sign { Layer::Placed } else { Layer::Comment }, icon);- - - - -- ui.ctx().set_cursor_icon(if movable { egui::CursorIcon::Move } else { egui::CursorIcon::PointingHand });------ --------------- }------ --------------- }if resp.drag_started()------ --------------- && pressed_here------ --------------- && let Some(o) = origin++++++ +++++++++++++++ && let (Some((a, part)), Some(o)) = (owner, origin){------ --------------- if let (Some(point), Some(a)) = (point_at(o), selected) {------ --------------- let points = a.points.iter().map(|q| [f64::from(q[0]), f64::from(q[1])]).collect();------ --------------- cv.gesture = Some(Gesture::Reshape { page: cx.page, index: a.index, point, points });------ --------------- consumed = true;------ --------------- } else if let (Some(h), Some(a)) = (handle_at(o), selected) {------ --------------- // On screen, the image is also turned by the view's rotation.------ --------------- let turned = !cx.xf.rot.is_multiple_of(180);------ --------------- let aspect_ratio = view.signature_drag.aspect_ratio(cx.page, a.index).map(|ratio| if turned { ratio.recip() } else { ratio });------ --------------- // A drawn signature keeps its shape from the corners, as image signatures do.------ --------------- let aspect_ratio = aspect_ratio.or_else(|| {------ --------------- let r = cx.screen_rect(a);------ --------------- (a.fill_sign && a.subtype == "Ink" && r.height() > 0.0).then(|| r.width() / r.height())------ --------------- });------ --------------- cv.gesture = Some(Gesture::Resize { page: cx.page, index: a.index, handle: h, from: o, aspect_ratio });------ --------------- consumed = true;------ --------------- } else if let Some(a) = cx.hit(o)------ --------------- && !is_markup(&a.subtype)------ --------------- {------ --------------- cv.selected = Some((cx.page, a.index));------ --------------- cv.reveal = true;------ --------------- if cx.allowed {------ --------------- cv.gesture = Some(Gesture::Move { page: cx.page, index: a.index, from: o });++++++ +++++++++++++++ match part {++++++ +++++++++++++++ CommentPart::Point(point) => {++++++ +++++++++++++++ let points = a.points.iter().map(|q| [f64::from(q[0]), f64::from(q[1])]).collect();++++++ +++++++++++++++ cv.gesture = Some(Gesture::Reshape { page: cx.page, index: a.index, point, points });++++++ +++++++++++++++ consumed = true;+++++ +++ ++++++ +++ }- -- - consumed = true;++++++ +++++++++++++++ CommentPart::Handle(x, y) => {++++++ +++++++++++++++ // On screen, the image is also turned by the view's rotation.++++++ +++++++++++++++ let turned = !cx.xf.rot.is_multiple_of(180);++++++ +++++++++++++++ let aspect_ratio = view.signature_drag.aspect_ratio(cx.page, a.index).map(|ratio| if turned { ratio.recip() } else { ratio });++++++ +++++++++++++++ // A drawn signature keeps its shape from the corners, as image signatures do.++++++ +++++++++++++++ let aspect_ratio = aspect_ratio.or_else(|| {++++++ +++++++++++++++ let r = cx.screen_rect(a);++++++ +++++++++++++++ (a.fill_sign && a.subtype == "Ink" && r.height() > 0.0).then(|| r.width() / r.height())++++++ +++++++++++++++ });++++++ +++++++++++++++ cv.gesture = Some(Gesture::Resize { page: cx.page, index: a.index, handle: (x, y), from: o, aspect_ratio });++++++ +++++++++++++++ consumed = true;+ ++ + }----- --- ------ --- consumed = true;++++++ +++++++++++++++ CommentPart::Body if !is_markup(&a.subtype) => {++++++ +++++++++++++++ cv.selected = Some((cx.page, a.index));++++++ +++++++++++++++ cv.reveal = true;++++++ +++++++++++++++ if cx.allowed {++++++ +++++++++++++++ cv.gesture = Some(Gesture::Move { page: cx.page, index: a.index, from: o });++++++ +++++++++++++++ }++++++ +++++++++++++++ consumed = true;++++++ +++++++++++++++ }++++++ +++++++++++++++ CommentPart::Body => {}}}if matches!(cv.gesture, Some(Gesture::Move { page, .. } | Gesture::Resize { page, .. } | Gesture::Reshape { page, .. }) if page == cx.page) {@@@@@@@@@@@@@@@@@@@@@@@ -266,15 -266,15 -266,15 -266,15 -266,15 -448,19 -252,10 -266,15 -266,15 -266,15 -448,19 -266,15 -266,15 -266,15 -216,19 -266,15 -216,19 -266,15 -448,19 -216,19 -266,15 -266,15 +252,10 @@@@@@@@@@@@@@@@@@@@@@@// (egui clears the press origin on release, so clicks are located by the pointer.)let on_page = pointer.is_some_and(|p| cx.xf.rect.contains(p));if resp.clicked() && on_page {----- --- --- - - -- let follow_link =----- --- --- - - -- cx.tool == QuickTool::Select && !consumed && cv.gesture.is_none() && !resp.double_clicked() && pointer.is_some_and(|p| on_link(cx, p));- - - - -- let follow_link = cx.tool == QuickTool::Select- - - - -- && !consumed- - - - -- && cv.gesture.is_none()- - - - -- && !resp.double_clicked()- - - - -- && pointer- - - - -- .is_some_and(|p| cx.info.links.iter().any(|link| link.page == cx.page && cx.xf.user_rect(cx.info, cx.page, link.rect).contains(p)));------ --------------- match pointer.and_then(|p| cx.hit(p)) {------ --------------- Some(a) if a.subtype == "Highlight" && follow_link => {------ --------------- // A plain click follows the link beneath text highlighting. Keep other------ --------------- // annotations and active gestures in control of their own input.------ --------------- cv.selected = None;------ --------------- }------ --------------- Some(a) => {++++++ +++++++++++++++ // A click elsewhere (a link beneath text highlighting included: it follows the link)++++++ +++++++++++++++ // leaves comments unselected.++++++ +++++++++++++++ match owner {++++++ +++++++++++++++ Some((a, _)) => {cv.selected = Some((cx.page, a.index));cv.reveal = true;consumed = true;@@@@@@@@@@@@@@@@@@@@@@@ -326,274 -326,274 -326,274 -326,274 -326,274 -512,6 -307,274 -326,274 -326,274 -326,274 -512,6 -326,274 -326,274 -326,274 -280,274 -326,274 -280,274 -326,274 -512,6 -280,274 -326,274 -326,274 +307,274 @@@@@@@@@@@@@@@@@@@@@@@ pub(crate) fn page_after_text(resp: &eg}}+ + + /// What the pointer is doing on one page, for the comment tools that draw or place things.+ + + #[derive(Clone, Copy)]+ + + struct Gestures<'a> {+ + + ui: &'a egui::Ui,+ + + resp: &'a egui::Response,+ + + cx: &'a PageCx<'a>,+ + + pointer: Option<Pos2>,+ + + origin: Option<Pos2>,+ + + page_rect: Rect,+ + + pressed_here: bool,+ + + over_page: bool,+ + + }+ + ++ + + impl Gestures<'_> {+ + + fn draw_shape(&self, view: &mut DocView, tool: CommentTool) -> bool {+ + + let Self { ui, resp, cx, pointer, origin, page_rect, pressed_here, over_page } = *self;+ + + let cv = &mut view.comments;+ + + if !cx.allowed {+ + + return false;+ + + }+ + + if over_page {- - - ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair);+ + + + ++ view.cursor.claim(Layer::ToolArea, egui::CursorIcon::Crosshair);+ + + }+ + + if resp.drag_started()+ + + && pressed_here+ + + && let Some(o) = origin+ + + {+ + + cv.gesture = Some(Gesture::Draw { page: cx.page, tool, points: vec![cx.to_user(o)] });+ + + cv.selected = None;+ + + }+ + + if let Some(Gesture::Draw { page, tool, points }) = cv.gesture.as_mut()+ + + && *page == cx.page+ + + && let Some(p) = pointer+ + + {+ + + let p = clamp_to(page_rect, p);+ + + let u = cx.to_user(p);+ + + if matches!(*tool, CommentTool::Ink | CommentTool::Eraser) {+ + + let last = points.last().map(|l| cx.to_screen(*l)).unwrap_or(p);+ + + if last.distance(p) >= 1.5 {+ + + points.push(u);+ + + }+ + + } else {+ + + points.truncate(1);+ + + points.push(u);+ + + }+ + + }+ + + if resp.drag_stopped()+ + + && let Some(Gesture::Draw { page, tool, points }) = cv.gesture.clone()+ + + && page == cx.page+ + + {+ + + cv.gesture = None;+ + + if tool == CommentTool::Eraser {+ + + view.pending_edit = erase(cx, &points);+ + + } else if let Some(shape) = drawn_shape(tool, &points) {+ + + let now = ui.input(|i| i.time);+ + + cv.settle(now, page, tool, &points);+ + + view.pending_edit = Some(new_comment(cx, tool, shape, String::new()));+ + + }+ + + }+ + + // A quick press/release does not start an egui drag, but Acrobat's Draw tool treats+ + + // it as a one-point ink stroke (a dot). The appearance uses round line caps, so a+ + + // single PDF point is visible and remains editable like any other drawing.+ + + if tool == CommentTool::Ink+ + + && resp.clicked()+ + + && over_page+ + + && let Some(p) = pointer+ + + && let Some(shape) = drawn_shape(tool, &[cx.to_user(p)])+ + + {+ + + cv.selected = None;+ + + let now = ui.input(|i| i.time);+ + + cv.settle(now, cx.page, tool, &[cx.to_user(p)]);+ + + view.pending_edit = Some(new_comment(cx, tool, shape, String::new()));+ + + }+ + + true+ + + }+ + ++ + + fn click_points(&self, view: &mut DocView, tool: CommentTool) -> bool {+ + + let Self { ui, resp, cx, pointer, over_page, .. } = *self;+ + + let cv = &mut view.comments;+ + + if !cx.allowed {+ + + return false;+ + + }+ + + if over_page {- - - ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair);+ + + + ++ view.cursor.claim(Layer::ToolArea, egui::CursorIcon::Crosshair);+ + + }+ + + let finish = resp.double_clicked() || ui.input(|i| i.key_pressed(egui::Key::Enter));+ + + // Backspace (or Delete) takes back the last point, e.g. after a wrong click; Undo does too.+ + + // Only while a drawing is in progress: otherwise Delete belongs to the selected comment.+ + + if matches!(cv.gesture, Some(Gesture::Draw { page, .. }) if page == cx.page)+ + + && !ui.ctx().egui_wants_keyboard_input()+ + + && ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Backspace) || i.consume_key(egui::Modifiers::NONE, egui::Key::Delete))+ + + {+ + + cv.undo_point();+ + + return true;+ + + }+ + + if resp.clicked()+ + + && over_page+ + + && let Some(p) = pointer+ + + {+ + + let u = cx.to_user(p);+ + + match cv.gesture.as_mut() {+ + + Some(Gesture::Draw { page, tool: t, points }) if *page == cx.page && *t == tool => {+ + + // Clicking the first point again closes a polygon.+ + + let closes = points.len() >= 3 && tool != CommentTool::PolyLine && cx.to_screen(points[0]).distance(p) <= 6.0;+ + + let repeat = points.last().is_some_and(|l| cx.to_screen(*l).distance(p) < 2.0);+ + + if closes {+ + + let pts = std::mem::take(points);+ + + cv.gesture = None;+ + + if let Some(shape) = drawn_shape(tool, &pts) {+ + + view.pending_edit = Some(new_comment(cx, tool, shape, String::new()));+ + + }+ + + return true;+ + + }+ + + if !repeat {+ + + points.push(u);+ + + }+ + + }+ + + _ => {+ + + cv.gesture = Some(Gesture::Draw { page: cx.page, tool, points: vec![u] });+ + + cv.selected = None;+ + + }+ + + }+ + + }+ + + if finish+ + + && let Some(Gesture::Draw { page, tool: t, points }) = cv.gesture.clone()+ + + && page == cx.page+ + + && t == tool+ + + {+ + + cv.gesture = None;+ + + if let Some(shape) = drawn_shape(tool, &points) {+ + + view.pending_edit = Some(new_comment(cx, tool, shape, String::new()));+ + + }+ + + }+ + + true+ + + }+ + ++ + + fn callout(&self, view: &mut DocView) -> bool {- - - let Self { ui, resp, cx, pointer, origin, page_rect, pressed_here, over_page } = *self;+ + + + ++ let Self { resp, cx, pointer, origin, page_rect, pressed_here, over_page, .. } = *self;+ + + let cv = &mut view.comments;+ + + // Drag from what the callout points at to where its text box goes.+ + + if !cx.allowed {+ + + return false;+ + + }+ + + if over_page {- - - ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair);+ + + + ++ view.cursor.claim(Layer::ToolArea, egui::CursorIcon::Crosshair);+ + + }+ + + if resp.drag_started()+ + + && pressed_here+ + + && let Some(o) = origin+ + + {+ + + cv.gesture = Some(Gesture::Draw { page: cx.page, tool: CommentTool::Callout, points: vec![cx.to_user(o)] });+ + + cv.selected = None;+ + + }+ + + if let Some(Gesture::Draw { page, points, .. }) = cv.gesture.as_mut()+ + + && *page == cx.page+ + + && let Some(p) = pointer+ + + {+ + + points.truncate(1);+ + + points.push(cx.to_user(clamp_to(page_rect, p)));+ + + }+ + + if resp.drag_stopped()+ + + && let Some(Gesture::Draw { page, points, .. }) = cv.gesture.clone()+ + + && page == cx.page+ + + {+ + + cv.gesture = None;+ + + if let [point, at] = points[..]+ + + && (point[0] - at[0]).hypot(point[1] - at[1]) >= 8.0+ + + {+ + + cv.composer = Some(Composer { page, at, kind: ComposerKind::Callout { point }, text: String::new(), focus: true });+ + + }+ + + }+ + + true+ + + }+ + ++ + + fn attach(&self, view: &mut DocView) -> bool {- - - let Self { ui, resp, cx, pointer, over_page, .. } = *self;+ + + + ++ let Self { resp, cx, pointer, over_page, .. } = *self;+ + + let cv = &mut view.comments;+ + + if !cx.allowed {+ + + return false;+ + + }+ + + if over_page {- - - ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair);+ + + + ++ view.cursor.claim(Layer::ToolArea, egui::CursorIcon::Crosshair);+ + + }+ + + if resp.clicked()+ + + && over_page+ + + && let Some(p) = pointer+ + + {+ + + cv.attach_at = Some((cx.page, cx.to_user(p)));+ + + cv.selected = None;+ + + }+ + + true+ + + }+ + ++ + + fn caret(&self, view: &mut DocView, caret_text: Option<&pdfcraft_render::PageText>) -> bool {- - - let Self { ui, resp, cx, pointer, over_page, .. } = *self;+ + + + ++ let Self { resp, cx, pointer, over_page, .. } = *self;+ + + let cv = &mut view.comments;+ + + if !cx.allowed {+ + + return false;+ + + }+ + + if over_page {- - - ui.ctx().set_cursor_icon(egui::CursorIcon::Text);+ + + + ++ view.cursor.claim(Layer::ToolArea, egui::CursorIcon::Text);+ + + }+ + + if resp.clicked()+ + + && over_page+ + + && let Some(p) = pointer+ + + {+ + + let (vx, vy) = cx.xf.screen_to_view(p);+ + + let snapped = cx.info.pages.get(cx.page).zip(caret_text).and_then(|(page, t)| snapped_caret(page, t, vx, vy));+ + + let (at, size) = snapped.unwrap_or_else(|| (cx.to_user(p), CARET_SIZE));+ + + cv.composer = Some(Composer { page: cx.page, at, kind: ComposerKind::Caret { size }, text: String::new(), focus: true });+ + + cv.selected = None;+ + + }+ + + true+ + + }+ + ++ + + fn note_or_box(&self, view: &mut DocView, tool: CommentTool) -> bool {- - - let Self { ui, resp, cx, pointer, origin, page_rect, pressed_here, over_page } = *self;+ + + + ++ let Self { resp, cx, pointer, origin, page_rect, pressed_here, over_page, .. } = *self;+ + + let cv = &mut view.comments;+ + + if !cx.allowed {+ + + return false;+ + + }+ + + if over_page {- - - ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair);+ + + + ++ view.cursor.claim(Layer::ToolArea, egui::CursorIcon::Crosshair);+ + + }+ + + // A text box also takes a drag, as in Acrobat: the box is drawn at that size and its+ + + // text wraps inside it (#2669).+ + + if tool == CommentTool::TextBox {+ + + if resp.drag_started()+ + + && pressed_here+ + + && let Some(o) = origin+ + + {+ + + cv.gesture = Some(Gesture::Draw { page: cx.page, tool, points: vec![cx.to_user(o)] });+ + + cv.selected = None;+ + + }+ + + if let Some(Gesture::Draw { page, points, .. }) = cv.gesture.as_mut()+ + + && *page == cx.page+ + + && let Some(p) = pointer+ + + {+ + + points.truncate(1);+ + + points.push(cx.to_user(clamp_to(page_rect, p)));+ + + }+ + + if resp.drag_stopped()+ + + && let Some(Gesture::Draw { page, points, .. }) = cv.gesture.clone()+ + + && page == cx.page+ + + {+ + + cv.gesture = None;+ + + if let (Some(first), Some(last)) = (points.first(), points.last()) {+ + + let r = Rect::from_two_pos(cx.to_screen(*first), cx.to_screen(*last));+ + + // A drag of a few pixels is a click: the box fits its text.+ + + let drawn =+ + + (r.width() >= 6.0 && r.height() >= 6.0).then(|| cx.info.pages.get(page)).flatten().map(|p| drawn_box(p, *first, *last));+ + + let (at, size) = drawn.map_or((*first, None), |(at, size)| (at, Some(size)));+ + + cv.composer = Some(Composer { page, at, kind: ComposerKind::TextBox { size }, text: String::new(), focus: true });+ + + }+ + + }+ + + }+ + + if resp.clicked()+ + + && over_page+ + + && let Some(p) = pointer+ + + {+ + + let kind = if tool == CommentTool::Note { ComposerKind::Note } else { ComposerKind::TextBox { size: None } };+ + + cv.composer = Some(Composer { page: cx.page, at: cx.to_user(p), kind, text: String::new(), focus: true });+ + + cv.selected = None;+ + + }+ + + true+ + + }+ + + }+ + +/// Delete / Escape handling for comments (only while no text field has focus).pub(crate) fn keys(ctx: &egui::Context, view: &mut DocView, tool: &mut QuickTool, allowed: bool) {if !ctx.input(|i| i.pointer.any_down()) {diff --cc crates/ui-egui/src/tools/comments/state.rsindex 36149bb2a,36149bb2a,36149bb2a,36149bb2a,36149bb2a,97ccb365a,3bcb12f90,a886e2dfd,36149bb2a,36149bb2a,97ccb365a,36149bb2a,36149bb2a,36149bb2a,36149bb2a,36149bb2a,36149bb2a,36149bb2a,97ccb365a,36149bb2a,36149bb2a,36149bb2a..ab2435225--- a/crates/ui-egui/src/tools/comments/state.rs+++ b/crates/ui-egui/src/tools/comments/state.rs@@@@@@@@@@@@@@@@@@@@@@@ -1,5 -1,5 -1,5 -1,5 -1,5 -1,5 -1,5 -1,7 -1,5 -1,5 -1,5 -1,5 -1,5 -1,5 -1,5 -1,5 -1,5 -1,5 -1,5 -1,5 -1,5 -1,5 +1,7 @@@@@@@@@@@@@@@@@@@@@@@+++++++ ++++++++++++++use std::collections::HashMap;+++++++ ++++++++++++++use super::geometry::{corner_ratio, is_markup, resized};- - - use super::*;+ + + use super::{Annotation, CommentPrefs, CommentTool, DocInfo, Edit, PagePointer, PageXform, Pos2, QuickTool, Rect};/// The user's login name, which Acrobat uses as the default comment author.pub(super) fn login_name() -> String {diff --cc crates/ui-egui/src/tools/content_ui.rsindex a0d9cefa1,a0d9cefa1,a0d9cefa1,a0d9cefa1,a0d9cefa1,23f9377a6,fdc6e3f98,a0d9cefa1,a0d9cefa1,a0d9cefa1,0da3b235c,a0d9cefa1,a0d9cefa1,a0d9cefa1,ee99ee0a2,a0d9cefa1,ee99ee0a2,a0d9cefa1,0da3b235c,ee99ee0a2,a0d9cefa1,a0d9cefa1..6a0d93b34--- a/crates/ui-egui/src/tools/content_ui.rs+++ b/crates/ui-egui/src/tools/content_ui.rs@@@@@@@@@@@@@@@@@@@@@@@ -7,9 -7,9 -7,9 -7,9 -7,9 -7,8 -7,9 -7,9 -7,9 -7,9 -7,8 -7,9 -7,9 -7,9 -7,8 -7,9 -7,8 -7,9 -7,8 -7,8 -7,9 -7,9 +7,9 @@@@@@@@@@@@@@@@@@@@@@@ use egui::{Color32, CornerRadius, Pos2use pdfcraft_engine::{Added, AddedContent, AddedText, Edit};use pdfcraft_render::DocInfo;- - - use crate::canvas::{DocView, PageXform};- - - use crate::page_pointer::PagePointer;+ + + use crate::canvas::{DocView, PageToolContext, PageXform};- - - use crate::page_pointer::PagePointer;+ + + + ++ use crate::page_cursor::Layer;----- --- --- - - --use crate::page_pointer::PagePointer;++++++ +++++++++++++++use crate::page_router::{Hit, Owner};use crate::theme::Tokens;use crate::widgets;@@@@@@@@@@@@@@@@@@@@@@@ -354,7 -354,7 -354,7 -354,7 -354,7 -375,6 -358,7 -354,7 -354,7 -354,7 -359,6 -354,7 -354,7 -354,7 -353,7 -354,7 -353,7 -354,7 -359,6 -353,7 -354,7 -354,7 +374,7 @@@@@@@@@@@@@@@@@@@@@@@ pub(crate) fn page_inputstyle: &AddedText,view: &mut DocView,) -> bool {- - - let PageToolContext { ui, resp, xf, ptr, page, info, .. } = cx;+ + + + ++ let PageToolContext { resp, xf, ptr, page, info, .. } = cx;let mut consumed = false;let pointer = ptr.pos;let cv = &mut view.content;@@@@@@@@@@@@@@@@@@@@@@@ -394,9 -394,9 -394,9 -394,9 -394,9 -414,14 -398,10 -394,9 -394,9 -394,9 -398,14 -394,9 -394,9 -394,9 -393,14 -394,9 -393,14 -394,9 -398,14 -393,14 -394,9 -394,9 +414,10 @@@@@@@@@@@@@@@@@@@@@@@.and_then(|(_, si)| items.iter().find(|(i, _)| *i == si)).map(|(_, a)| screen_rect(xf, info, page, a.content.rect()));let corner = selected_rect.and_then(|r| handles(r).into_iter().find(|(c, ..)| c.distance(p) <= 6.0));- - - - -- // Cursors only where the page shows: the mode bar and side panels over a page scrolled under- - - - -- // them keep their own (#2755).- - - - -- let shows = resp.contains_pointer();if adding_text && hit.is_none() {- - - - -- if shows {- - - - -- ui.ctx().set_cursor_icon(egui::CursorIcon::Text);- - - - -- }- - - - -- if resp.clicked() {+ + + + ++ view.cursor.claim(Layer::ToolArea, egui::CursorIcon::Text);----- --- --- - - -- if resp.clicked() {++++++ +++++++++++++++ // A new box where nothing drawn over the page holds the press.++++++ +++++++++++++++ if resp.clicked() && view.router.owner(page).is_none() {// Text that can't be drawn stays where it is being typed (#125).if cv.hold_blocked() {return true;@@@@@@@@@@@@@@@@@@@@@@@ -420,20 -420,20 -420,20 -420,20 -420,20 -445,20 -425,21 -420,20 -420,20 -420,20 -429,20 -420,20 -420,20 -420,20 -424,20 -420,20 -424,20 -420,20 -429,20 -424,20 -420,20 -420,20 +441,21 @@@@@@@@@@@@@@@@@@@@@@@}return consumed;}----- --- --- - - -- if let Some((_, left, top)) = corner {----- --- --- - - -- view.cursor.claim(Layer::Handle, if left == top { egui::CursorIcon::ResizeNwSe } else { egui::CursorIcon::ResizeNeSw });----- --- --- - - -- } else if hit.is_some() {----- --- --- - - -- view.cursor.claim(Layer::Placed, egui::CursorIcon::Move);- - - - -- if let Some((_, left, top)) = corner.filter(|_| shows) {- - - - -- ui.ctx().set_cursor_icon(if left == top { egui::CursorIcon::ResizeNwSe } else { egui::CursorIcon::ResizeNeSw });- - - - -- } else if hit.is_some() && shows {- - - - -- ui.ctx().set_cursor_icon(egui::CursorIcon::Move);------ --------------- }++++++ +++++++++++++++ // A drag on what the press was on ([`hit`]): a corner resizes the selected item, the item++++++ +++++++++++++++ // itself moves.if resp.drag_started() {let origin = ptr.origin.unwrap_or(p);------ --------------- if let Some((_, left, top)) = selected_rect.and_then(|r| handles(r).into_iter().find(|(c, ..)| c.distance(origin) <= 6.0)) {------ --------------- cv.grab = Some((page, Grab::Corner(left, top), origin));------ --------------- consumed = true;------ --------------- } else if let Some((i, _)) = items.iter().rev().find(|(_, a)| screen_rect(xf, info, page, a.content.rect()).expand(2.0).contains(origin)) {------ --------------- cv.selected = Some((page, *i));------ --------------- cv.grab = Some((page, Grab::Move, origin));------ --------------- consumed = true;++++++ +++++++++++++++ match view.router.owner(page) {++++++ +++++++++++++++ Some(Owner::Added { corner: Some((left, top)), .. }) => {++++++ +++++++++++++++ cv.grab = Some((page, Grab::Corner(left, top), origin));++++++ +++++++++++++++ consumed = true;++++++ +++++++++++++++ }++++++ +++++++++++++++ Some(Owner::Added { index, corner: None }) => {++++++ +++++++++++++++ cv.selected = Some((page, index));++++++ +++++++++++++++ cv.grab = Some((page, Grab::Move, origin));++++++ +++++++++++++++ consumed = true;++++++ +++++++++++++++ }++++++ +++++++++++++++ _ => {}}return consumed;}diff --cc crates/ui-egui/src/tools/edit_text_ui.rsindex 224bc3f54,224bc3f54,224bc3f54,224bc3f54,224bc3f54,7c5410602,f5f19582d,224bc3f54,224bc3f54,224bc3f54,11bf52fbb,224bc3f54,224bc3f54,224bc3f54,a14e4e661,224bc3f54,a14e4e661,224bc3f54,66daa6edb,a14e4e661,224bc3f54,224bc3f54..2f157f5f5--- a/crates/ui-egui/src/tools/edit_text_ui.rs+++ b/crates/ui-egui/src/tools/edit_text_ui.rs@@@@@@@@@@@@@@@@@@@@@@@ -11,9 -11,9 -11,9 -11,9 -11,9 -11,8 -11,10 -11,9 -11,9 -11,9 -11,8 -11,9 -11,9 -11,9 -11,8 -11,9 -11,8 -11,9 -11,8 -11,8 -11,9 -11,9 +11,10 @@@@@@@@@@@@@@@@@@@@@@@ use egui::{Color32, CornerRadius, FontFuse pdfcraft_engine::{Edit, ObjectKind, ObjectTarget};use pdfcraft_render::DocInfo;- - - use crate::canvas::{DocView, PageXform};+ + + use crate::canvas::{DocView, PageToolContext, PageXform};+ + + + ++ use crate::page_cursor::Layer;use crate::page_pointer::PagePointer;++++++ +++++++++++++++use crate::page_router::{Hit, Owner, ParagraphPart};mod background;mod image;@@@@@@@@@@@@@@@@@@@@@@@ -21,7 -21,7 -21,7 -21,7 -21,7 -20,7 -22,7 -21,7 -21,7 -21,7 -20,7 -21,7 -21,7 -21,7 -20,7 -21,7 -20,7 -21,7 -20,7 -20,7 -21,7 -21,7 +22,7 @@@@@@@@@@@@@@@@@@@@@@@ mod layoutpub(crate) use background::TextBackground;pub use image::{CropMode, ImageSelection};----- --- ------- ---pub(crate) use image::{ImageAction, ImageCx, image_input, image_owns_pointer};- - - pub(crate) use image::{ImageAction, image_input, image_owns_pointer};++++++ +++++++++++++++pub(crate) use image::{ImageAction, ImageCx, body_hit as picture_hit, handle_hit as picture_handle_hit, image_input};#[cfg(test)]use image::{rotate_knob, turn_degrees};#[cfg(test)]@@@@@@@@@@@@@@@@@@@@@@@ -428,23 -428,23 -428,23 -428,23 -428,23 -500,27 -460,16 -428,23 -428,23 -428,23 -446,27 -428,23 -428,23 -428,23 -427,27 -428,23 -427,27 -428,23 -446,27 -427,27 -428,23 -428,23 +514,16 @@@@@@@@@@@@@@@@@@@@@@@ pub(crate) fn page_input(cx: PageToolCoreturn true;}let Some(p) = ptr.within(xf.rect) else { return false };------ --------------- let Some((hit, grip)) = grab_at(&boxes, p, upright) else { return false };------ --------------- if active != Some(hit) {------ --------------- painter.rect_stroke(boxes[hit], CornerRadius::same(2), Stroke::new(1.5, ACCENT), egui::StrokeKind::Outside);++++++ +++++++++++++++ // The paragraph under the pointer: outlined, with its width handles when closed.++++++ +++++++++++++++ let Some((hovered, _)) = grab_at(&boxes, p, upright) else { return false };++++++ +++++++++++++++ if active != Some(hovered) {++++++ +++++++++++++++ painter.rect_stroke(boxes[hovered], CornerRadius::same(2), Stroke::new(1.5, ACCENT), egui::StrokeKind::Outside);}------ --------------- let on_edge = active.is_none() && grip != Grip::Move;if upright && active.is_none() {------ --------------- draw_handles(boxes[hit]);------ --------------- }------ --------------- // A closed paragraph moves when dragged (the four-way arrow says so; a click still opens it----- --- --- - - -- // for typing); an edge rewraps it. The open one takes the text cursor.----- --- --- - - -- if on_edge {----- --- --- - - -- view.cursor.claim(Layer::Handle, egui::CursorIcon::ResizeHorizontal);----- --- --- - - -- } else if active.is_none() {----- --- --- - - -- view.cursor.claim(Layer::Text, egui::CursorIcon::Move);----- --- --- - - -- } else {----- --- --- - - -- view.cursor.claim(if active == Some(hit) { Layer::Editor } else { Layer::Text }, egui::CursorIcon::Text);- - - - -- // for typing); an edge rewraps it. The open one takes the text cursor. Only where the page- - - - -- // shows, so the mode bar and side panels over a paragraph scrolled under them keep their own- - - - -- // cursor (#2755).- - - - -- if resp.contains_pointer() {- - - - -- ui.ctx().set_cursor_icon(if on_edge {- - - - -- egui::CursorIcon::ResizeHorizontal- - - - -- } else if active.is_none() {- - - - -- egui::CursorIcon::Move- - - - -- } else {- - - - -- egui::CursorIcon::Text- - - - -- });++++++ +++++++++++++++ draw_handles(boxes[hovered]);}++++++ +++++++++++++++ // A click opens the paragraph the press was on.++++++ +++++++++++++++ let Some((hit, _)) = owner else { return true };if resp.clicked() {view.image_selection = None;// A click that moves the editor to another paragraph applies the open one first, so itsdiff --cc crates/ui-egui/src/tools/object_ui.rsindex 96cc0adf2,96cc0adf2,96cc0adf2,96cc0adf2,96cc0adf2,d495116c6,db3982cd2,96cc0adf2,96cc0adf2,96cc0adf2,e54446297,114ccbd43,96cc0adf2,96cc0adf2,be23b86d4,96cc0adf2,be23b86d4,96cc0adf2,d495116c6,be23b86d4,96cc0adf2,96cc0adf2..17aea394f--- a/crates/ui-egui/src/tools/object_ui.rs+++ b/crates/ui-egui/src/tools/object_ui.rs@@@@@@@@@@@@@@@@@@@@@@@ -7,8 -7,8 -7,8 -7,8 -7,8 -7,8 -7,9 -7,8 -7,8 -7,8 -7,8 -7,8 -7,8 -7,8 -7,7 -7,8 -7,7 -7,8 -7,8 -7,7 -7,8 -7,8 +7,9 @@@@@@@@@@@@@@@@@@@@@@@ use egui::{Color32, Pos2, Rect, Stroke}use pdfcraft_engine::{Document, Edit, EditableObject, MAX_MOVE_OBJECTS, ObjectKind, ObjectTarget};use pdfcraft_render::DocInfo;- - - use crate::canvas::{DocView, PageXform};- - - use crate::page_pointer::PagePointer;+ + + use crate::canvas::{DocView, PageToolContext, PageXform};+ + + + ++ use crate::page_cursor::Layer;++++++ +++++++++++++++use crate::page_router::{Hit, ObjectsPart, Owner};const BLUE: Color32 = Color32::from_rgb(0x14, 0x73, 0xE6);@@@@@@@@@@@@@@@@@@@@@@@ -161,10 -161,10 -161,10 -161,10 -161,10 -161,17 -162,23 -161,10 -161,10 -161,10 -181,17 -161,10 -161,10 -161,10 -160,10 -161,10 -160,10 -161,10 -161,17 -160,10 -161,10 -161,10 +182,23 @@@@@@@@@@@@@@@@@@@@@@@ fn leave_single(view: &mut DocView)view.block_drag = None;}++++++ +++++++++++++++/// What of the objects lies under `p` on `page`: the objects selected together (a drag moves++++++ +++++++++++++++/// them), or the frame around the paragraph open for typing (`open`: its box on screen), which++++++ +++++++++++++++/// takes hold of the box as in Acrobat: a click selects it, a drag moves it, its text keeps the++++++ +++++++++++++++/// caret.++++++ +++++++++++++++pub(crate) fn hit(view: &DocView, xf: &PageXform, info: &DocInfo, page: usize, open: Option<Rect>, p: Pos2) -> Option<Hit> {++++++ +++++++++++++++ let s = &view.objects;++++++ +++++++++++++++ if s.page == Some(page) && !s.selected.is_empty() && s.selected.iter().fold(Rect::NOTHING, |r, o| r.union(screen(xf, info, page, o))).contains(p)++++++ +++++++++++++++ {++++++ +++++++++++++++ return Some(Hit::new(Owner::Objects { part: ObjectsPart::Selection }, Layer::Placed, egui::CursorIcon::Move));++++++ +++++++++++++++ }++++++ +++++++++++++++ open.filter(|r| on_frame(r.shrink(2.0), p)).map(|_| Hit::new(Owner::Objects { part: ObjectsPart::Frame }, Layer::Handle, egui::CursorIcon::Move))++++++ +++++++++++++++}++++++ +++++++++++++++/// Returns true while group selection owns the interaction. Ordinary clicks still reach the/// single-object text/resize tools. A text draft is finished or discarded through its editor.- - - pub(crate) fn page_input(- - - ui: &egui::Ui,- - - resp: &egui::Response,- - - xf: &PageXform,- - - ptr: &PagePointer,- - - page: usize,- - - doc: &Document,- - - view: &mut DocView,- - - ) -> bool {+ + + pub(crate) fn page_input(cx: PageToolContext<'_>, view: &mut DocView) -> bool {+ + + let PageToolContext { ui, xf, ptr, page, .. } = cx;if view.objects.input_blocked {return true;}@@@@@@@@@@@@@@@@@@@@@@@ -246,14 -246,14 -246,14 -246,14 -246,14 -262,14 -260,7 -246,14 -246,14 -246,14 -282,14 -246,14 -246,14 -246,14 -245,14 -246,14 -245,14 -246,14 -262,14 -245,14 -246,14 -246,14 +280,7 @@@@@@@@@@@@@@@@@@@@@@@ fn input(s: &mut ObjectSelection, cx: Preturn s.page == Some(page) && !s.selected.is_empty();};if !pressed {------ --------------- if s.page == Some(page) && !s.selected.is_empty() {------ --------------- let union = s.selected.iter().fold(Rect::NOTHING, |r, o| r.union(screen(xf, info, page, o)));------ --------------- if union.contains(p) {----- --- --- - - -- view.cursor.claim(Layer::Placed, egui::CursorIcon::Move);- - - - -- ui.ctx().set_cursor_icon(egui::CursorIcon::Move);------ --------------- }------ --------------- return true;------ --------------- }------ --------------- return false;++++++ +++++++++++++++ return s.page == Some(page) && !s.selected.is_empty();}let objects = match s.inventory(doc, page) {Ok(objects) => objects,diff --cc crates/ui-egui/src/tools/prepare.rsindex c5fa2b684,c5fa2b684,c5fa2b684,c5fa2b684,c5fa2b684,9713791e3,e8861b5cf,c5fa2b684,c5fa2b684,c5fa2b684,9713791e3,e54bdd046,c5fa2b684,c5fa2b684,88f0b1d2b,c5fa2b684,88f0b1d2b,c5fa2b684,9713791e3,88f0b1d2b,c5fa2b684,c5fa2b684..cc4b81441--- a/crates/ui-egui/src/tools/prepare.rs+++ b/crates/ui-egui/src/tools/prepare.rs@@@@@@@@@@@@@@@@@@@@@@@ -10,9 -10,9 -10,9 -10,9 -10,9 -10,9 -10,10 -10,9 -10,9 -10,9 -10,9 -10,9 -10,9 -10,9 -10,8 -10,9 -10,8 -10,9 -10,9 -10,8 -10,9 -10,9 +10,10 @@@@@@@@@@@@@@@@@@@@@@@ use pdfcraft_engine::form_scripts::{Caluse pdfcraft_engine::{BorderStyle, Document, Edit, FieldFont, FieldLook, FieldProps, FormField, FormFieldKind, NewField};use pdfcraft_render::DocInfo;- - - use crate::canvas::{DocView, PageXform};+ + + use crate::canvas::{DocView, PageToolContext, PageXform};use crate::comments;- - - use crate::page_pointer::PagePointer;+ + + + ++ use crate::page_cursor::Layer;++++++ +++++++++++++++use crate::page_router::{Hit, Owner};use crate::theme;use crate::widgets;@@@@@@@@@@@@@@@@@@@@@@@ -252,9 -252,9 -252,9 -252,9 -252,9 -252,20 -253,41 -252,9 -252,9 -252,9 -252,20 -252,9 -252,9 -252,9 -251,9 -252,9 -251,9 -252,9 -252,20 -251,9 -252,9 -252,9 +253,41 @@@@@@@@@@@@@@@@@@@@@@@ pub(crate) struct Outcomepub table: Option<(usize, [f64; 4])>,}- - - /// Pointer input on one page while preparing a form.++++++ +++++++++++++++/// What Prepare Form's Select tool has under `p` on `page`: the selected field's corner handles,++++++ +++++++++++++++/// then a field. A field being moved is placed on the page over the comments; nothing with a field++++++ +++++++++++++++/// tool, which draws anywhere.+++++ +++ +++++++ +++#[allow(clippy::too_many_arguments)]- - - pub(crate) fn page_input(- - - ui: &egui::Ui,- - - resp: &egui::Response,++++++ +++++++++++++++pub(crate) fn hit(+++++ +++ +++++++ +++ xf: &PageXform,- - - ptr: &PagePointer,- - - page: usize,+++++ +++ +++++++ +++ info: &DocInfo,++++++ +++++++++++++++ page: usize,+++++ +++ +++++++ +++ form: &[FormField],+++++ +++ +++++++ +++ tool: Option<FieldTool>,+++++ +++ +++++++ +++ allowed: bool,- - - view: &mut DocView,- - - ) -> Outcome {++++++ +++++++++++++++ prep: &PrepareView,++++++ +++++++++++++++ p: Pos2,++++++ +++++++++++++++) -> Option<Hit> {++++++ +++++++++++++++ if tool.is_some() || !allowed || !xf.rect.contains(p) {++++++ +++++++++++++++ return None;++++++ +++++++++++++++ }++++++ +++++++++++++++ let selected_rect = prep++++++ +++++++++++++++ .selected++++++ +++++++++++++++ .as_ref()++++++ +++++++++++++++ .and_then(|(n, wi)| form.iter().find(|f| &f.name == n)?.widgets.get(*wi).filter(|w| w.page == Some(page)))++++++ +++++++++++++++ .map(|w| screen_rect(xf, info, page, w.rect));++++++ +++++++++++++++ if let Some((_, left, top)) = selected_rect.and_then(|r| handles(r).into_iter().find(|(c, ..)| c.distance(p) <= 6.0)) {++++++ +++++++++++++++ let icon = if left == top { egui::CursorIcon::ResizeNwSe } else { egui::CursorIcon::ResizeNeSw };++++++ +++++++++++++++ return Some(Hit::new(Owner::PrepareCorner { left, top }, Layer::Handle, icon));++++++ +++++++++++++++ }++++++ +++++++++++++++ let (field, widget) = form.iter().enumerate().find_map(|(fi, f)| {++++++ +++++++++++++++ f.widgets.iter().enumerate().find(|(_, w)| w.page == Some(page) && screen_rect(xf, info, page, w.rect).contains(p)).map(|(wi, _)| (fi, wi))++++++ +++++++++++++++ })?;++++++ +++++++++++++++ Some(Hit::new(Owner::PrepareField { field, widget }, Layer::Placed, egui::CursorIcon::Move))++++++ +++++++++++++++}++++++ ++++++++++++++++ + + /// Pointer input on one page while preparing a form.+ + + pub(crate) fn page_input(cx: PageToolContext<'_>, form: &[FormField], tool: Option<FieldTool>, allowed: bool, view: &mut DocView) -> Outcome {+ + + let PageToolContext { ui, resp, xf, ptr, page, info, .. } = cx;let mut out = Outcome { consumed: false, properties: false, placed: false, table: None };let pointer = ptr.pos;let prep = &mut view.prepare;@@@@@@@@@@@@@@@@@@@@@@@ -383,33 -383,33 -383,33 -383,33 -383,33 -394,33 -416,21 -383,33 -383,33 -383,33 -394,33 -383,33 -383,33 -383,33 -382,33 -383,33 -382,33 -383,33 -394,33 -382,33 -383,33 -383,33 +416,21 @@@@@@@@@@@@@@@@@@@@@@@prep.also.clear();}}------ --------------- // The Select tool: corner handles of the selection, then fields.------ --------------- let selected_rect = prep------ --------------- .selected------ --------------- .as_ref()------ --------------- .and_then(|(n, wi)| form.iter().find(|f| &f.name == n)?.widgets.get(*wi).filter(|w| w.page == Some(page)))------ --------------- .map(|w| screen_rect(xf, info, page, w.rect));------ --------------- let corner = selected_rect.and_then(|r| handles(r).into_iter().find(|(c, ..)| c.distance(p) <= 6.0));------ --------------- let hit = form.iter().find_map(|f| {------ --------------- f.widgets.iter().enumerate().find(|(_, w)| w.page == Some(page) && screen_rect(xf, info, page, w.rect).contains(p)).map(|(i, _)| (f, i))------ --------------- });------ --------------- if let Some((_, left, top)) = corner {----- --- --- - - -- view.cursor.claim(Layer::Handle, if left == top { egui::CursorIcon::ResizeNwSe } else { egui::CursorIcon::ResizeNeSw });- - - - -- ui.ctx().set_cursor_icon(if left == top { egui::CursorIcon::ResizeNwSe } else { egui::CursorIcon::ResizeNeSw });------ --------------- } else if hit.is_some() {----- --- --- - - -- view.cursor.claim(Layer::Field, egui::CursorIcon::Move);- - - - -- ui.ctx().set_cursor_icon(egui::CursorIcon::Move);------ --------------- }------ --------------- if resp.drag_started() {++++++ +++++++++++++++ // The Select tool: what the press was on ([`hit`]), a corner handle or a field; elsewhere a++++++ +++++++++++++++ // drag draws a selection rectangle. A press held by something drawn over the fields (a++++++ +++++++++++++++ // comment) is not Prepare's.++++++ +++++++++++++++ let owner = view.router.owner(page);++++++ +++++++++++++++ let held = matches!(owner, Some(Owner::PrepareField { .. } | Owner::PrepareCorner { .. }));++++++ +++++++++++++++ let hit = match owner {++++++ +++++++++++++++ Some(Owner::PrepareField { field, widget }) => form.get(field).map(|f| (f, widget)),++++++ +++++++++++++++ _ => None,++++++ +++++++++++++++ };++++++ +++++++++++++++ if resp.drag_started() && (held || owner.is_none()) {let origin = ptr.origin.unwrap_or(p);------ --------------- if let Some((_, left, top)) = selected_rect.and_then(|r| handles(r).into_iter().find(|(c, ..)| c.distance(origin) <= 6.0)) {++++++ +++++++++++++++ if let Some(Owner::PrepareCorner { left, top }) = owner {prep.grab = Some((page, Grab::Corner(left, top), origin));out.consumed = true;------ --------------- } else if let Some((f, wi)) = form.iter().find_map(|f| {------ --------------- f.widgets------ --------------- .iter()------ --------------- .enumerate()------ --------------- .find(|(_, w)| w.page == Some(page) && screen_rect(xf, info, page, w.rect).contains(origin))------ --------------- .map(|(i, _)| (f, i))------ --------------- }) {++++++ +++++++++++++++ } else if let Some((f, wi)) = hit {prep.selected = Some((f.name.clone(), wi));prep.grab = Some((page, Grab::Move, origin));out.consumed = true;diff --cc docs/integration-20261030.mdindex 000000000,000000000,000000000,000000000,000000000,000000000,000000000,000000000,000000000,000000000,000000000,000000000,000000000,000000000,000000000,000000000,000000000,000000000,000000000,000000000,000000000,000000000..3f6bb9fefnew file mode 100644--- /dev/null+++ b/docs/integration-20261030.md@@@@@@@@@@@@@@@@@@@@@@@ -1,0 -1,0 -1,0 -1,0 -1,0 -1,0 -1,0 -1,0 -1,0 -1,0 -1,0 -1,0 -1,0 -1,0 -1,0 -1,0 -1,0 -1,0 -1,0 -1,0 -1,0 -1,0 +1,41 @@@@@@@@@@@@@@@@@@@@@@@++++++++++++++++++++++# PdfCraft integration candidate, 2026-10-30++++++++++++++++++++++++++++++++++++++++++++Base: 1d1cbc4ec92012767f5b48c92b451e15eb401c42++++++++++++++++++++++++++++++++++++++++++++Validation: pending combined GitHub CI. No fresh manual GUI pass has been performed.++++++++++++++++++++++All included source heads are preserved as merge parents, retaining original authorship. No upstream PR was merged. No conflicts were manually resolved.++++++++++++++++++++++++++++++++++++++++++++## Included++++++++++++++++++++++- [#4304](https://github.com/storytold/pdfcraft/pull/4304): M11: PDF Optimizer stores black-and-white images as CCITT Group 4 (optimize.mono-compression) (1b7164cab1fc187c5385c30f94449542fe284280)++++++++++++++++++++++- [#4335](https://github.com/storytold/pdfcraft/pull/4335): M11: black-and-white pictures stay one bit: Create PDF, the optimizer, and CCITT image export (210ba20fe69e701286bbfdbd924cfc01d9aaa9f4)++++++++++++++++++++++- [#4384](https://github.com/storytold/pdfcraft/pull/4384): M11: Monochrome Images ▸ Downsample: black-and-white images above 450 ppi are averaged down to 300, Group 4 scans included (1ad951e25bac86f77e75e060dcce34cc32a0f9a3)++++++++++++++++++++++- [#4404](https://github.com/storytold/pdfcraft/pull/4404): M11: the optimizer stores Group 3 fax as Group 4, and packs black-and-white RGB and two-entry indexed images to one bit (2d0a7b22411d4b61f130f6175cec918153858593)++++++++++++++++++++++- [#4179](https://github.com/storytold/pdfcraft/pull/4179): fix(ui): Ctrl+Z in an open paragraph undoes the document, not stale text (296b9300988fe3ef8d5bcdcb439705e80d6d7321)++++++++++++++++++++++- [#5300](https://github.com/storytold/pdfcraft/pull/5300): fix(ui): a press on the page belongs to what its one hit test finds, until the button is up (11bc8c56528fc3a820669d41c0eec29310cdad24)++++++++++++++++++++++- [#4719](https://github.com/storytold/pdfcraft/pull/4719): fix(comments): delete or edit one reply from its own menu, keeping the thread (adeb9c1cf2336c10639d8172325e708edf515856)++++++++++++++++++++++- [#4541](https://github.com/storytold/pdfcraft/pull/4541): M5: a moved comment is drawn where it goes while it is dragged (f0cd96e90bf696099b02201ac68f9ccb8a00c7d2)++++++++++++++++++++++- [#2815](https://github.com/storytold/pdfcraft/pull/2815): fix(edit): show backgrounds on pages that paint their own white backdrop (9aaac56417a2260338c7e7edb41615f1bb42b45e)++++++++++++++++++++++- [#4620](https://github.com/storytold/pdfcraft/pull/4620): feat(edit): Esc in an open paragraph selects its box, so Delete removes it (64fba7d177032170939861dc7eb51d8486a43264)++++++++++++++++++++++- [#3789](https://github.com/storytold/pdfcraft/pull/3789): Alt+Left / Alt+Right go back and forward through the view history (#3632) (08f3991ab9808b71fa015f22d49dbc4720044c78)++++++++++++++++++++++- [#3779](https://github.com/storytold/pdfcraft/pull/3779): Window title: mark unsaved changes, and set it on the web (#3640) (3850c9f52e073e51f8e4a1665b3ae36fae6f8e66)++++++++++++++++++++++- [#2960](https://github.com/storytold/pdfcraft/pull/2960): Keep lines with footnote references in paragraph reading order (#2929) (2a7e5bda268b3862b9b2329df16191473966c90e)++++++++++++++++++++++- [#5208](https://github.com/storytold/pdfcraft/pull/5208): M10: export a PDF to Markdown (#1595) (20d396d180a33139908a3a1fad6178ab77b90eff)++++++++++++++++++++++- [#4596](https://github.com/storytold/pdfcraft/pull/4596): fix(organize,print): join /Contents array pieces with a space (#3502) (d58d121170f2d650196263492c6c54a89aad39b3)++++++++++++++++++++++- [#3636](https://github.com/storytold/pdfcraft/pull/3636): Content streams: step over a malformed token instead of ending the page (43337c7fd5f7b5123efcebcc84de35c394726e7a)++++++++++++++++++++++- [#4494](https://github.com/storytold/pdfcraft/pull/4494): M2: page_render and render_preview report the render warnings next to the PNG (#4340) (5ada1249e9cdb98a438e26f8fe53c82aba9b8cc1)++++++++++++++++++++++- [#4013](https://github.com/storytold/pdfcraft/pull/4013): fix(engine): generate Protect keys and salts with getrandom (#4000) (c580b550555837ad6f2c1aa4152bdb5cb96cf337)++++++++++++++++++++++- [#5134](https://github.com/storytold/pdfcraft/pull/5134): fix(ui): keep the All tools rows clear of the scrollbar (#5133) (0c5119791db7de268258b9d25f1286b82b563f8a)++++++++++++++++++++++- [#2133](https://github.com/storytold/pdfcraft/pull/2133): Fix Pages sidebar select-all keyboard shortcut (#2052) (7227eb68ab383e47413f1a980f340f5132cf4144)++++++++++++++++++++++- [#2635](https://github.com/storytold/pdfcraft/pull/2635): Allow typed font sizes and Fill & Sign text colours (4b319bb3835709626c663b8d41b72d2f9574acc0)++++++++++++++++++++++++++++++++++++++++++++## Excluded++++++++++++++++++++++- [#4320](https://github.com/storytold/pdfcraft/pull/4320): conflict.++++++++++++++++++++++- [#4805](https://github.com/storytold/pdfcraft/pull/4805): conflict.++++++++++++++++++++++- [#4325](https://github.com/storytold/pdfcraft/pull/4325): conflict.++++++++++++++++++++++- [#4180](https://github.com/storytold/pdfcraft/pull/4180): conflict.++++++++++++++++++++++- [#1952](https://github.com/storytold/pdfcraft/pull/1952): conflict.++++++++++++++++++++++- [#2529](https://github.com/storytold/pdfcraft/pull/2529): conflict with main.++++++++++++++++++++++++++++++++++++++++++++Additional previously reviewed parity fixes: #2133 and #2635. #1952 was considered but conflicts.++++++++++++++++++++++Excluded held PRs #4648, #2877 and #3762 were not included.++++++++++++++++++++++Source reviews and individual hosted CI do not establish combined-build safety; the integration gate must pass.diff --cc docs/roadmap.mdindex 25205e92c,75be8e383,3e4c971b2,56b10853a,f5d3d1b44,40fa711c2,25205e92c,daa80cdde,25205e92c,25205e92c,40fa711c2,25205e92c,25205e92c,25205e92c,25205e92c,25205e92c,25205e92c,25205e92c,40fa711c2,25205e92c,c36e67c62,25205e92c..c8aae0ba8--- a/docs/roadmap.md+++ b/docs/roadmap.md@@@@@@@@@@@@@@@@@@@@@@@ -1,7 -1,8 -1,9 -1,10 -1,11 -1,6 -1,7 -1,8 -1,7 -1,7 -1,6 -1,7 -1,7 -1,7 -1,7 -1,7 -1,7 -1,7 -1,6 -1,7 -1,7 -1,7 +1,12 @@@@@@@@@@@@@@@@@@@@@@@# PdfCraft roadmap: milestones and what's next+ + + > **Last reviewed:** 2026-10-27 | **Last updated:** 2026-10-27 | **Change:** minor (M10: OCR model downloads use verified ONNX pairs with legacy discovery fallback; estimates unchanged)+++++++ ++++++++++++++> **Last reviewed:** 2026-10-25 | **Last updated:** 2026-10-25 | **Change:** minor (M5: one reply in the Comments panel is edited, copied or deleted from its own "…" menu; estimates unchanged)> **Last reviewed:** 2026-10-25 | **Last updated:** 2026-10-25 | **Change:** minor (M14 localization current state: Arabic logical catalog, explicit RTL label direction and mirrored stock chrome; native/browser RTL workflows unqualified. Native release Hans face via LXGW WenKai Lite; estimates unchanged)++++ +++++++++++++++++> **Last reviewed:** 2026-10-24 · **Last updated:** 2026-10-24 · **Change:** minor (M11: the optimizer stores Group 3 fax images as Group 4, and packs black-and-white RGB and indexed images that use only palette entries 0 and 1 to one bit; estimates unchanged)+++ +++++++++++++++++> **Last reviewed:** 2026-10-24 · **Last updated:** 2026-10-24 · **Change:** minor (M11: black-and-white images above 450 ppi are averaged down to 300 ppi by the optimizer; estimates unchanged)++ +++++++++++++++++> **Last reviewed:** 2026-10-24 · **Last updated:** 2026-10-24 · **Change:** minor (M11: black-and-white pictures stay one bit when PDFs are created and optimized; CCITT images export; estimates unchanged)+ +++++++++++++++++> **Last reviewed:** 2026-10-23 · **Last updated:** 2026-10-23 · **Change:** minor (M11: the PDF Optimizer and Reduce File Size store black-and-white images as CCITT Group 4 when smaller; estimates unchanged)> **Last reviewed:** 2026-10-23 · **Last updated:** 2026-10-23 · **Change:** minor (M7, #2636 partial: pasting added text boxes and images in the engine and through `content_copy`; estimates unchanged)> **Last reviewed:** 2026-10-23 · **Last updated:** 2026-10-23 · **Change:** minor (M11: image optimization accounts for page-local UserUnit; estimates unchanged)@@@@@@@@@@@@@@@@@@@@@@@ -194,8 -195,8 -196,8 -197,8 -198,8 -193,8 -194,8 -195,8 -194,8 -194,8 -193,8 -194,8 -194,8 -194,8 -194,8 -194,8 -194,8 -194,8 -193,8 -194,8 -194,8 -194,8 +199,8 @@@@@@@@@@@@@@@@@@@@@@@ total matches the parity estimate| M7 | Content editing (text, images, header/footer, watermark) | 250–500 | 20% | 100–180 | Done: header & footer, watermarks, backgrounds, Bates; added text and images that stay editable (move, resize, format, rotate, flip, crop, replace); links (Link tool, Link Properties, create from URLs, remove all). Missing: editing existing text and images in place (the longest pole), image/PDF watermarks || M8 | Security + redaction | 100–180 | 68% | 15–30 | Done: opening protected documents, permissions, Protect Using Password, Remove security; redaction (mark text/areas/pages, Search & Redact with patterns, apply removing glyphs, image pixels, vectors, XObject content, annotations and fields, verification, full rewrite on save); Remove hidden information and Sanitize.<br>Done since: redaction codes (U.S. FOIA and Privacy Act sets as overlay text, in Redaction properties and `redact_mark`). Redaction cleans indirect and form structure references, preserving surviving form tags. Redaction retires inherited resource dictionaries, so a parent `/Pages` can't keep a removed XObject reachable; unredacted pages are left untouched. Image redaction removes alternate images and unsupported masks only on affected images. Changed marked-content spans lose replacement descriptions; untouched spans keep theirs. Hidden-text cleanup retires unused named descriptions across inherited/shared page and form resources (64 focused tests and scoped Rust 1.96 Clippy/wasm checks pass; publication CI pending). The redaction audit counts a filled cover that hides half of any one word of a long line (#2662), applied or not. Phone-pattern redaction also matches labelled Italian geographic numbers with `+39` and a slash after the area code (#3205 follow-up); unlabelled international slash numbers remain unsupported. Missing: certificate security, custom redaction code sets and pattern locales, DCT re-encoding || M9 | Signatures (PAdES, validation) | 160–280 | 60% | 40–70 | Done: new `sign` crate (DER, X.509, CMS, PKCS #12 on RustCrypto; aws-lc-rs for RSA private keys); PAdES B-B signing (visible, invisible, existing fields, certification with DocMDP); validation with trust store and changes-after-signing classification; self-signed digital IDs; Signatures panel, message bar, sign dialogs; agent tools. Checked with pdfsig and OpenSSL.<br>Done since: macOS Keychain and Windows Current User Personal store signing (software-backed CNG keys), certificate viewer, signed documents protected from rewrites, page validation overlays separate from original signature artwork (baked Not Verified captions remain; #79 open), snapshot tabs that reuse instead of multiplying. Missing: timestamps (B-T), LTV (DSS, OCSP, CRL), FieldMDP, smart cards, PKCS #11 |- - - | M10 | OCR, create, export, print | 200–350 | 33% | 120–215 | Done: create from blank/text/PNG/JPEG/TIFF (multi-page)/GIF/BMP; export PNG/JPEG/TIFF and text; Print (Acrobat's sizing, n-up, booklet, poster, comments & forms, preview, the CUPS and Windows spoolers, print-ready PDF).<br>Done since: embedded/72/custom DPI choices for image imports; export all images; OCR (searchable image for pages, ranges and multiple files); single-sided cut-and-stack imposition with cut marks, through Print and doc_print; architectural/ANSI/large ISO sheet presets, Match page at 100% and PDF-scale preview (#599 follow-up); Create PDF from multiple files (PDFs, images and text, edited as pages in the grid); OCR can also read pictures on pages that have text, without adding that text twice (#1028). Done since: Word invoice export uses borderless inferred tables, floating positioned text/artwork only where text overlaps an image or is rotated, and per-page sizes, covered by synthetic invoice automation regressions (#773); printing on the web through the browser's print dialog, sheets drawn by PdfCraft (gap 4). Lossless image export applies per-component Decode, including Indexed mapping (#1201 partial). Existing 16-bit precision and color-management limits remain. #3532 partial: vector printing retains existing appearances with absent Subtype through a print-owned Form copy; source artwork stays unchanged. #3120: Office export reads form XObjects 50 levels deep, as the renderer does, and up to 50 000 a page; pages past that are listed in `truncated_pages`. Word table cells use the grid columns they span, including cells after a merged cell. Done since: text in a table slot covered by another cell's span remains as paragraph text in Word, HTML, RTF and PowerPoint. Missing: OCR languages beyond Latin, editable-text OCR output, full Office layout fidelity/import. Done since: dotted-leader contents entries stay in separate complete paragraphs (#1757) #2156 candidate: last selected print paper persists across sessions; other print preferences unchanged. Image export applies soft-mask Decode opacity intervals before resizing, including indirect entries and inverted ranges. Vector printing gives annotation appearances unoccupied XObject names so existing page artwork survives. |- - - | M11 | Optimize, preflight, PDF/A/X/UA, print production | 200–350 | 18% | 80–140 | Done: new `optimize` crate: Reduce File Size and the PDF Optimizer (images measured where drawn, bicubic downsampling, JPEG/ZIP recompression only when smaller, discard objects and user data, Flate clean-up, resource merging, object streams). Target-version compatibility is partial: newer content is not detected or converted. Content stream boundaries preserve comments, split operands and graphics state when image fragments merge. Image downsampling includes page-local `/UserUnit` scaling when measuring physical resolution. Done since: reject invalid image and soft-mask dimensions with checked sizing (#2178). Missing: fonts and transparency panels, space audit, preflight, PDF/A/X/UA |+ + + | M10 | OCR, create, export, print | 200–350 | 33% | 120–215 | Done: create from blank/text/PNG/JPEG/TIFF (multi-page)/GIF/BMP; export PNG/JPEG/TIFF and text; Print (Acrobat's sizing, n-up, booklet, poster, comments & forms, preview, the CUPS and Windows spoolers, print-ready PDF).<br>Done since: embedded/72/custom DPI choices for image imports; export all images; OCR (searchable image for pages, ranges and multiple files); single-sided cut-and-stack imposition with cut marks, through Print and doc_print; architectural/ANSI/large ISO sheet presets, Match page at 100% and PDF-scale preview (#599 follow-up); Create PDF from multiple files (PDFs, images and text, edited as pages in the grid); OCR can also read pictures on pages that have text, without adding that text twice (#1028). Model staging fetches SHA-256-verified ONNX detection/recognition files after the upstream RTEN URL brownout; runtime discovery prefers complete ONNX pairs per directory, then complete legacy RTEN pairs, without mixing formats or changing directory precedence. Done since: Word invoice export uses borderless inferred tables, floating positioned text/artwork only where text overlaps an image or is rotated, and per-page sizes, covered by synthetic invoice automation regressions (#773); printing on the web through the browser's print dialog, sheets drawn by PdfCraft (gap 4). Lossless image export applies per-component Decode, including Indexed mapping (#1201 partial). Existing 16-bit precision and color-management limits remain. #3532 partial: vector printing retains existing appearances with absent Subtype through a print-owned Form copy; source artwork stays unchanged. #3120: Office export reads form XObjects 50 levels deep, as the renderer does, and up to 50 000 a page; pages past that are listed in `truncated_pages`. Word table cells use the grid columns they span, including cells after a merged cell. Done since: text in a table slot covered by another cell's span remains as paragraph text in Word, HTML, RTF and PowerPoint. Missing: OCR languages beyond Latin, editable-text OCR output, full Office layout fidelity/import. Done since: dotted-leader contents entries stay in separate complete paragraphs (#1757) #2156 candidate: last selected print paper persists across sessions; other print preferences unchanged. Image export applies soft-mask Decode opacity intervals before resizing, including indirect entries and inverted ranges. Vector printing gives annotation appearances unoccupied XObject names so existing page artwork survives. |- ---- ------- ---| M11 | Optimize, preflight, PDF/A/X/UA, print production | 200–350 | 18% | 80–140 | Done: new `optimize` crate: Reduce File Size and the PDF Optimizer (images measured where drawn, bicubic downsampling, JPEG/ZIP recompression only when smaller, discard objects and user data, Flate clean-up, resource merging, object streams). Target-version compatibility is partial: newer content is not detected or converted. Content stream boundaries preserve comments, split operands and graphics state when image fragments merge. Image downsampling includes page-local `/UserUnit` scaling when measuring physical resolution. Done since: reject invalid image and soft-mask dimensions with checked sizing (#2178). Missing: fonts and transparency panels, space audit, preflight, PDF/A/X/UA |--- | M11 | Optimize, preflight, PDF/A/X/UA, print production | 200–350 | 18% | 80–140 | Done: new `optimize` crate: Reduce File Size and the PDF Optimizer (images measured where drawn, bicubic downsampling, JPEG/ZIP recompression only when smaller, discard objects and user data, Flate clean-up, resource merging, object streams). Target-version compatibility is partial: newer content is not detected or converted. Content stream boundaries preserve comments, split operands and graphics state when image fragments merge. Image downsampling includes page-local `/UserUnit` scaling when measuring physical resolution. Done since: reject invalid image and soft-mask dimensions with checked sizing (#2178); black-and-white images stored losslessly as CCITT Group 4 when smaller. Missing: fonts and transparency panels, space audit, preflight, PDF/A/X/UA |++++ +++++++++++++++++| M11 | Optimize, preflight, PDF/A/X/UA, print production | 200–350 | 18% | 80–140 | Done: new `optimize` crate: Reduce File Size and the PDF Optimizer (images measured where drawn, bicubic downsampling, JPEG/ZIP recompression only when smaller, discard objects and user data, Flate clean-up, resource merging, object streams). Target-version compatibility is partial: newer content is not detected or converted. Content stream boundaries preserve comments, split operands and graphics state when image fragments merge. Image downsampling includes page-local `/UserUnit` scaling when measuring physical resolution. Done since: reject invalid image and soft-mask dimensions with checked sizing (#2178); black-and-white images stored losslessly as CCITT Group 4 when smaller, averaged down to 300 ppi above 450 (halftones aside), Group 3 stored again as Group 4, and black-and-white RGB and indexed images that use only palette entries 0 and 1 packed to one bit. Missing: fonts and transparency panels, space audit, preflight, PDF/A/X/UA || M12 | Accessibility, compare, measure, search, XFA | 200–380 | 30% | 90–160 | Done: new `a11y` crate with the Accessibility Checker (all 32 rules, report, Fix/Skip/Explain, options dialog and results panel, agent tools). Locatable figure, annotation and form findings highlight their page bounds. Character encoding accepts Identity-H/V with Adobe CJK collections and predefined CJK CMaps independently (#3673); per-glyph validation and embedded-font extraction remain separate.<br>Done since: 2D distance, perimeter and area measurements with persistent viewport calibration, snapping, live information and CSV export; a bounded, text-only auto-tag proposal tool for one page. Marking a figure decorative rewrites only that stream (#1324). An XFA radio item whose value contains a space is written back unchanged (#1319). Done since: #2569: Growable multiline XFA text reflows after edits, with undo/redo, save/reopen and print coverage; oversized fields still become read-only page text. Structured-data synchronization warnings retain accepted whitespace without relayout from stale data. Done since: #2572: Every repeated page-master button resolves its own field to the shared XFA click script, including print buttons. Done since: #2570: Dynamic XFA rich-text fields carry exData/maxLength into AcroForm MaxLen for reported and enforced Unicode character limits, retained after save/reopen. Done since: #2589: Active XFA skips PDF-container fallback scripts while retaining requested messages and saved scripts; ordinary/static/unlaid-out documents and explicit console/field calls keep their existing behavior. Missing: writing proposed tags and parent tree, field autotag, visual Tags/Order/Content panels, Reading Order tool, compare, geospatial/3D measurement, search index, XFA<br>Reading colours: pending page backgrounds follow the configured colour (#2059). || M13 | Automation (MCP, Action Wizard, CLI) + AI providers | 60–120 | 45% | 25–45 | Done: MCP resources (document info, text, page images); headless tool table (123 tools incl. signing, optimizing, initial view, links, stamps, data exchange, comment review, forms authoring and scripts, redaction, sanitize, print, add content), opt-in MCP server over stdio, CLI `run`/`tools` (closed stdout pipes exit cleanly), UI control channel with drag. Missing: Action Wizard, AI providers<br>Done since: CLI run and MCP reject missing, empty, repeated and option-valued --root arguments before any tool/script execution or MCP initialization. A single-hyphen directory name remains valid; synthetic CLI regressions preserve a would-be overwritten file. `text_find` also caps the per-page match ranges it materializes at the remaining result limit plus one continuation match. CLI robustness scans visit each directory once through overlapping roots and symlink aliases. || M12 | Accessibility, compare, measure, search, XFA | 200–380 | 30% | 90–160 | Done: new `a11y` crate with the Accessibility Checker (all 32 rules, report, Fix/Skip/Explain, options dialog and results panel, agent tools). Locatable figure, annotation and form findings highlight their page bounds. Character encoding accepts Identity-H/V with Adobe CJK collections and predefined CJK CMaps independently (#3673); per-glyph validation and embedded-font extraction remain separate.<br>Done since: 2D distance, perimeter and area measurements with persistent viewport calibration, snapping, live information and CSV export; a bounded text-only auto-tag proposal tool; text-only Apply writes marked content, paragraph tags and a parent tree, then opens the Tags panel for review. Missing: mixed-content and field autotag, heading/list/table/figure classification, Order/Content panels, Reading Order tool, compare, geospatial/3D measurement, search index, XFA<br>Done since: CLI info, text and render use dynamic XFA layout pages, with synthetic count/text/pixel and copy-permission regressions (#1645).<br>Reading colours: pending page backgrounds follow the configured colour (#2059). |@@@@@@@@@@@@@@@@@@@@@@@ -255,7 -256,8 -257,9 -258,10 -259,11 -254,6 -255,7 -256,7 -255,7 -255,7 -254,6 -255,7 -255,7 -255,7 -255,7 -255,7 -255,7 -255,7 -254,6 -255,7 -255,7 -255,7 +260,11 @@@@@@@@@@@@@@@@@@@@@@@ Estimates unchanged| Date | Change | Summary ||---|---|---|++++ +++++++++++++++++| 2026-10-24 | minor | M11: the PDF Optimizer and Reduce File Size store Group 3 fax images as Group 4 when smaller (`Document::fax_params`), and pack eight-bit `DeviceRGB` of only black and white (as grey) and indexed images of 2, 4 or 8 bits that use only palette entries 0 and 1 (keeping the palette) to one bit, so Monochrome Images compresses and downsamples them. Estimates unchanged. |+++ +++++++++++++++++| 2026-10-24 | minor | M11: monochrome downsampling: the PDF Optimizer and Reduce File Size average black-and-white images (1-bit, CCITT fax, eight-bit black-and-white grey) above 450 ppi down to 300 ppi, by area with ties black, as Monochrome Images ▸ Downsample to and `doc_optimize` `mono: { downsample, ppi, above_ppi }`; CCITT decoding moves into `pdfcraft-filters` (`decode_ccitt`) behind `Document::decoded_image`. Estimates unchanged. |++ +++++++++++++++++| 2026-10-24 | minor | M11: Create PDF stores pictures of only black and white at one bit (Group 4 or Flate, whichever is smaller) instead of eight-bit grey; the optimizer packs eight-bit black-and-white grey images to one bit before Monochrome Images compresses them, unless the grey settings make them smaller, as they can a dithered scan, soft mask counted; Export ▸ Images decodes CCITT fax images. Estimates unchanged. |+ +++++++++++++++++| 2026-10-23 | minor | M11: black-and-white images (1-bit, and image masks) are stored losslessly as CCITT Group 4 when that is smaller: PDF Optimizer ▸ Images ▸ Monochrome Images (on by default, so Reduce File Size too), `doc_optimize` `mono`; `pdfcraft_filters::encode_g4`. JBIG2 and monochrome downsampling not yet. Estimates unchanged. |+ + + | 2026-10-27 | minor | M10: OCR stages SHA-256-verified ONNX models after the upstream RTEN URL brownout; discovery prefers a complete ONNX pair per directory, falls back to a complete RTEN pair, and never mixes formats or directories; language/web limits and estimates unchanged. || 2026-10-24 | minor | M3, #3970 follow-up: the button release given back after a window move or resize goes before the pointer leaving, so hover doesn't stick. Estimates unchanged. || 2026-10-23 | minor | M8, #3205 follow-up: phone-pattern redaction includes the +39 country code on labelled Italian geographic numbers with a slash; dates, protocol identifiers and whole-run guards remain. Estimates unchanged. || 2026-10-23 | minor | M10: Word table cells use the grid columns they span, including cells after a merged cell; synthetic export regression and CLI reproduction. Estimates unchanged. |diff --cc parity/acrobat-features.tomlindex 3b8dba920,02d7219ab,376131a97,ea60fc285,26e94eda0,bcba7a0ec,3b8dba920,f7e95de61,98e9f2bb2,a9aaf06d1,6ec28519a,897ed017b,51b4f55ae,3b8dba920,3ba6f85cf,3b8dba920,47ac06fdd,3b8dba920,bcba7a0ec,47ac06fdd,472a694f7,8383b2a29..ca7a44a58--- a/parity/acrobat-features.toml+++ b/parity/acrobat-features.toml@@@@@@@@@@@@@@@@@@@@@@@ -2530,9 -2530,9 -2530,9 -2530,9 -2530,9 -2530,9 -2530,9 -2530,9 -2530,9 -2530,9 -2530,9 -2530,9 -2530,9 -2530,9 -2530,9 -2530,9 -2530,9 -2530,9 -2530,9 -2530,9 -2530,9 -2530,9 +2530,9 @@@@@@@@@@@@@@@@@@@@@@@ tier = "P0milestone = "M7"status = "shipped"commands = ["edit.background"]--------- ------------tools = ["doc_background"]----- --- --- - - --evidence = ["crates/ui-egui/tests/it/marks.rs::watermark_and_background_dialogs", "crates/engine/src/tests.rs::headers_footers_watermarks_and_backgrounds_show_update_and_remove", "crates/engine/src/tests.rs::backgrounds_and_watermarks_from_files", "crates/ui-egui/tests/it/marks.rs::backgrounds_and_watermarks_from_a_file", "crates/organize/src/tests.rs::a_page_becomes_a_form_xobject_upright", "crates/ui-egui/tests/it/marks.rs::the_preview_shows_the_page_the_range_selects_under_the_marks", "crates/ui-egui/tests/it/marks.rs::update_previews_the_page_without_the_marks_it_replaces", "crates/engine/src/tests.rs::update_previews_on_the_page_without_the_marks_it_replaces"]----- --- --- - - --notes = "colour, or a picture from a file (an image or a page of a PDF) scaled relative to the page; the dialog previews a colour as a tint of the page's own thumbnail (opaque pictures on the page are tinted there too, not in the result), a file as its frame and name; Update previews on the page without the backgrounds it replaces, not tinting the old one"- - - - -- evidence = ["crates/ui-egui/tests/it/marks.rs::watermark_and_background_dialogs", "crates/engine/src/tests.rs::headers_footers_watermarks_and_backgrounds_show_update_and_remove", "crates/engine/src/tests.rs::backgrounds_and_watermarks_from_files", "crates/ui-egui/tests/it/marks.rs::backgrounds_and_watermarks_from_a_file", "crates/organize/src/tests.rs::a_page_becomes_a_form_xobject_upright", "crates/ui-egui/tests/it/marks.rs::the_preview_shows_the_page_the_range_selects_under_the_marks"]- - - - -- notes = "colour, or a picture from a file (an image or a page of a PDF) scaled relative to the page; the dialog previews a colour as a tint of the page's own thumbnail (opaque pictures on the page are tinted there too, not in the result), a file as its frame and name"+++++++++ ++++++++++++tools = ["doc_background", "doc_backdrops"]+++++++++ ++++++++++++evidence = ["crates/ui-egui/tests/it/marks.rs::watermark_and_background_dialogs", "crates/engine/src/tests.rs::headers_footers_watermarks_and_backgrounds_show_update_and_remove", "crates/engine/src/tests.rs::backgrounds_and_watermarks_from_files", "crates/ui-egui/tests/it/marks.rs::backgrounds_and_watermarks_from_a_file", "crates/organize/src/tests.rs::a_page_becomes_a_form_xobject_upright", "crates/automation/tests/it/backdrop.rs::a_background_shows_on_a_page_that_paints_its_own_white_backdrop", "crates/ui-egui/tests/it/marks.rs::the_background_dialog_offers_to_replace_a_white_backdrop_and_warns_about_scans", "crates/ui-egui/tests/it/marks.rs::the_background_preview_follows_the_replace_checkbox", "crates/edit/src/backdrop_tests.rs::content_that_is_not_a_page_backdrop_is_left_alone", "crates/ui-egui/tests/it/marks.rs::the_preview_shows_the_page_the_range_selects_under_the_marks", "crates/ui-egui/tests/it/marks.rs::update_previews_the_page_without_the_marks_it_replaces", "crates/engine/src/tests.rs::update_previews_on_the_page_without_the_marks_it_replaces"]+++++++++ ++++++++++++notes = "colour, or a picture from a file (an image or a page of a PDF) scaled relative to the page. A page that paints its own opaque white backdrop (browsers' Save as PDF, print drivers) used to hide the background entirely; the dialog now offers to replace that fill (on by default; Remove turns it back on, after edits and redactions too, unless the operators before it changed or it would no longer be painted first, and then says which pages keep it off). The replaced copy's tag holds no page content or reference, so text a redaction or Remove Hidden Information takes off such a page leaves the file. Our own choice: Acrobat's behaviour on such pages has not been observed. Still hidden: scanned pages (warned), backdrops drawn inside a form XObject, by a non-rectangular path, or in a named colour space, and white fills drawn translucent, through a soft mask, a non-Normal blend mode or a transfer function (TR/TR2) as the graphics state stands after every gs, which are real content and stay. The dialog previews a colour as a tint of the page's own thumbnail (opaque pictures on the page are tinted there too, not in the result), a file as its frame and name; a page that will still hide the background (a scan, or a white backdrop with Replace unticked) previews without the colour; Update previews on the page without the backgrounds it replaces, not tinting the old one"[[feature]]id = "edit.background-update-remove"@@@@@@@@@@@@@@@@@@@@@@@ -6884,8 -6884,8 -6884,8 -6884,8 -6884,8 -6872,8 -6884,8 -6884,8 -6896,8 -6884,8 -6872,8 -6884,8 -6884,8 -6884,8 -6872,8 -6884,8 -6872,8 -6884,8 -6872,8 -6872,8 -6884,8 -6884,8 +6896,8 @@@@@@@@@@@@@@@@@@@@@@@ milestone = "M10status = "shipped"commands = ["create.images"]tools = ["doc_create"]-- -----------------evidence = ["crates/create/src/tests.rs::jpeg_2000_images_are_embedded_as_is", "crates/create/src/tests.rs::images_export_as_jpeg_unchanged_and_others_as_png", "crates/create/src/tests.rs::embedded_icc_profiles_tag_the_image_colour_space"]-- -----------------notes = "PNG, JPEG, TIFF (multi-page), GIF (first frame), BMP, and JPEG 2000 (JP2 or codestream, embedded as JPXDecode with its capture resolution). JPEG and PNG ICC profiles are kept as /ICCBased; TIFF profiles are not read yet"++ +++++++++++++++++evidence = ["crates/create/src/tests.rs::black_and_white_images_are_stored_at_one_bit", "crates/create/src/tests.rs::jpeg_2000_images_are_embedded_as_is", "crates/create/src/tests.rs::images_export_as_jpeg_unchanged_and_others_as_png", "crates/create/src/tests.rs::embedded_icc_profiles_tag_the_image_colour_space"]- notes = "PNG, JPEG, TIFF (multi-page), GIF (first frame), BMP, and JPEG 2000 (JP2 or codestream, embedded as JPXDecode with its capture resolution). JPEG and PNG ICC profiles are kept as /ICCBased; TIFF profiles are not read yet. A picture of only pure black and white (a 1-bit PNG or TIFF, eight-bit grey, a two-colour palette, RGB without a profile) is stored at one bit per pixel, as CCITT Group 4 or Flate, whichever is smaller. Redaction doesn't decode Group 4 yet: a mark over part of such a picture removes it whole (nothing leaks)"+++ +++++++++++++++++notes = "PNG, JPEG, TIFF (multi-page), GIF (first frame), BMP, and JPEG 2000 (JP2 or codestream, embedded as JPXDecode with its capture resolution). JPEG and PNG ICC profiles are kept as /ICCBased; TIFF profiles are not read yet. A picture of only pure black and white (a 1-bit PNG or TIFF, eight-bit grey, a two-colour palette, RGB without a profile) is stored at one bit per pixel, as CCITT Group 4 or Flate, whichever is smaller"[[feature]]id = "create.from-multipage-tiff"@@@@@@@@@@@@@@@@@@@@@@@ -7325,7 -7325,7 -7325,7 -7325,7 -7325,7 -7313,7 -7325,7 -7325,7 -7337,7 -7325,7 -7313,7 -7325,7 -7325,7 -7325,7 -7325,7 -7325,7 -7313,7 -7325,7 -7313,7 -7313,7 -7325,7 -7325,7 +7349,7 @@@@@@@@@@@@@@@@@@@@@@@ status = "shippedcommands = ["optimize.reduce"]tools = ["doc_reduce"]evidence = ["crates/ui-egui/tests/it/create.rs::reduce_file_size_writes_a_compact_copy", "crates/ui-egui/tests/it/create.rs::reduce_file_size_saves_nothing_when_the_file_is_already_small", "crates/engine/src/tests.rs::create_and_reduce", "crates/automation/tests/it/automation.rs::creating_and_reducing_through_tools", "crates/automation/tests/it/automation.rs::optimizing_through_tools", "crates/optimize/tests/optimize.rs::an_identity_decode_array_does_not_stop_reduce"]- -----------------notes = "images above 225 ppi to 150 ppi JPEG medium (after merging page pictures printed as one-pixel strips into one image), thumbnails dropped, resources merged, object streams; scanner images with the default decode array are included; a copy that isn't smaller is not saved (\"already as small as it can be made\"); runs in the background with a progress bar and Cancel"-- notes = "images above 225 ppi to 150 ppi JPEG medium (after merging page pictures printed as one-pixel strips into one image), black-and-white images to CCITT Group 4 when that is smaller, thumbnails dropped, resources merged, object streams; scanner images with the default decode array are included; a copy that isn't smaller is not saved (\"already as small as it can be made\"); runs in the background with a progress bar and Cancel"+++ +++++++++++++++++notes = "images above 225 ppi to 150 ppi JPEG medium (after merging page pictures printed as one-pixel strips into one image), black-and-white images averaged down to 300 ppi above 450 ppi, and stored as CCITT Group 4 whenever that is smaller, thumbnails dropped, resources merged, object streams; scanner images with the default decode array are included; a copy that isn't smaller is not saved (\"already as small as it can be made\"); runs in the background with a progress bar and Cancel"[[feature]]id = "optimize.compatibility-level"@@@@@@@@@@@@@@@@@@@@@@@ -7360,8 -7360,8 -7360,8 -7360,8 -7360,8 -7348,8 -7360,8 -7360,8 -7372,8 -7360,8 -7348,8 -7360,8 -7360,8 -7360,8 -7360,8 -7360,8 -7348,8 -7360,8 -7348,8 -7348,8 -7360,8 -7360,8 +7384,8 @@@@@@@@@@@@@@@@@@@@@@@ milestone = "M11status = "partial"commands = ["optimize.advanced"]tools = ["doc_optimize"]--- -----------------evidence = ["crates/optimize/tests/optimize.rs::images_are_measured_where_drawn_and_downsampled", "crates/optimize/tests/optimize.rs::settings_choose_what_happens", "crates/automation/tests/it/automation.rs::optimizing_through_tools", "crates/optimize/tests/optimize.rs::a_page_picture_printed_as_one_pixel_strips_is_merged_into_one_image", "crates/optimize/tests/optimize.rs::images_that_do_not_tile_a_picture_are_left_alone", "crates/optimize/tests/optimize.rs::a_deeply_nested_form_is_measured_at_its_largest_use", "crates/optimize/tests/optimize.rs::images_are_not_resampled_when_some_uses_could_not_be_measured", "crates/optimize/tests/optimize.rs::image_resolution_uses_the_pages_physical_unit", "crates/optimize/tests/optimize.rs::optimization_retains_an_image_below_threshold_on_a_scaled_page", "crates/optimize/tests/optimize.rs::shared_forms_are_measured_in_each_pages_physical_units"]--- -----------------notes = "colour and grayscale, bicubic, effective resolution measured where drawn (every use, with page-local UserUnit scaling, through nested forms up to 12 deep; when a use can't be measured, nothing is resampled); image fragments stacked edge to edge are merged first (side-by-side tiles not yet); monochrome not yet"+++ +++++++++++++++++evidence = ["crates/optimize/tests/optimize.rs::images_are_measured_where_drawn_and_downsampled", "crates/optimize/tests/optimize.rs::settings_choose_what_happens", "crates/automation/tests/it/automation.rs::optimizing_through_tools", "crates/optimize/tests/optimize.rs::a_page_picture_printed_as_one_pixel_strips_is_merged_into_one_image", "crates/optimize/tests/optimize.rs::images_that_do_not_tile_a_picture_are_left_alone", "crates/optimize/tests/optimize.rs::a_deeply_nested_form_is_measured_at_its_largest_use", "crates/optimize/tests/optimize.rs::images_are_not_resampled_when_some_uses_could_not_be_measured", "crates/optimize/tests/optimize.rs::image_resolution_uses_the_pages_physical_unit", "crates/optimize/tests/optimize.rs::optimization_retains_an_image_below_threshold_on_a_scaled_page", "crates/optimize/tests/optimize.rs::shared_forms_are_measured_in_each_pages_physical_units", "crates/optimize/tests/optimize.rs::black_and_white_images_above_450_ppi_are_averaged_down_to_300", "crates/optimize/src/images.rs::it_matches_the_slow_way", "crates/automation/tests/it/automation.rs::doc_optimize_averages_black_and_white_scans_down", "crates/ui-egui/tests/it/create.rs::the_pdf_optimizer_dialog_saves_an_optimized_copy"]- notes = "colour and grayscale, bicubic, effective resolution measured where drawn (every use, with page-local UserUnit scaling, through nested forms up to 12 deep; when a use can't be measured, nothing is resampled); image fragments stacked edge to edge are merged first (side-by-side tiles not yet); monochrome (1-bit, CCITT fax and eight-bit black-and-white grey) averaged by area to 300 ppi above 450 ppi by default, a tie to the dark sample (black in grey, painted in a mask, ink in a separation, after the decode array; an indexed image's entry 0, its palette not read yet), then stored as Group 4 or 1-bit Flate (Monochrome Images ▸ Downsample to; doc_optimize mono); not monochrome images with a soft mask, halftones and dithers (most of their new pixels would cover both black and white, and their tones turn solid), or images wider than a fax row (1,048,576 samples), and Acrobat's bicubic and subsampling choices for monochrome aren't offered"++++ +++++++++++++++++notes = "colour and grayscale, bicubic, effective resolution measured where drawn (every use, with page-local UserUnit scaling, through nested forms up to 12 deep; when a use can't be measured, nothing is resampled); image fragments stacked edge to edge are merged first (side-by-side tiles not yet); monochrome (1-bit, CCITT fax, and eight-bit black-and-white grey and RGB, and indexed images that use only palette entries 0 and 1) averaged by area to 300 ppi above 450 ppi by default, a tie to the dark sample (black in grey, painted in a mask, ink in a separation, after the decode array; an indexed image's entry 0, its palette not read yet), then stored as Group 4 or 1-bit Flate (Monochrome Images ▸ Downsample to; doc_optimize mono); not monochrome images with a soft mask, halftones and dithers (most of their new pixels would cover both black and white, and their tones turn solid), or images wider than a fax row (1,048,576 samples), and Acrobat's bicubic and subsampling choices for monochrome aren't offered"[[feature]]id = "optimize.recompress-images"@@@@@@@@@@@@@@@@@@@@@@@ -7381,11 -7381,11 -7381,11 -7381,11 -7381,11 -7369,11 -7381,11 -7381,11 -7393,11 -7381,11 -7369,11 -7381,11 -7381,11 -7381,11 -7381,11 -7381,11 -7369,11 -7381,11 -7369,11 -7369,11 -7381,11 -7381,11 +7405,11 @@@@@@@@@@@@@@@@@@@@@@@ title = "Monochrome compression (JBIG2area = "K"tier = "P1"milestone = "M11"- -----------------status = "planned"- -----------------commands = []- -----------------tools = []- -----------------evidence = []- -----------------notes = ""+ +++++++++++++++++status = "partial"+ +++++++++++++++++commands = ["optimize.advanced", "optimize.reduce"]+ +++++++++++++++++tools = ["doc_optimize", "doc_reduce"]- evidence = ["crates/filters/src/ccitt.rs::bitmaps_round_trip", "crates/filters/src/ccitt.rs::a_page_of_text_like_marks_round_trips_and_shrinks", "crates/filters/src/ccitt.rs::what_it_cannot_encode_is_an_error", "crates/optimize/tests/optimize.rs::black_and_white_images_become_ccitt_group_4", "crates/automation/tests/it/automation.rs::doc_optimize_stores_black_and_white_images_as_ccitt_group_4", "crates/ui-egui/tests/it/create.rs::the_pdf_optimizer_dialog_saves_an_optimized_copy"]- notes = "CCITT Group 4, lossless: PDF Optimizer ▸ Images ▸ Monochrome Images (on by default, so Reduce File Size does it too; doc_optimize mono) stores a 1-bit image of one colour component (grey, indexed, a separation) or an image mask, kept with no filter or general-purpose ones, as Group 4 when that is smaller as stored; the samples decode to the same bits, so colour space, decode array and masks stay. Group 4 wins on scans; on clean computer-drawn 1-bit art Flate can be smaller, and the image then stays. Not yet: JBIG2 (lossless or lossy, which Adobe's help says beats CCITT for monochrome), monochrome downsampling, inline images, soft masks and /Mask images, rows wider than 32,767 samples. Redaction doesn't decode Group 4 yet (a mark over part of such an image removes it whole; nothing leaks), nor does anything that exports an image: Export ▸ Images and Save Image As refuse it, Copy Image fails, and Word, PowerPoint and HTML export leave the picture out."-- evidence = ["crates/optimize/tests/optimize.rs::eight_bit_black_and_white_images_become_one_bit", "crates/filters/src/ccitt.rs::bitmaps_round_trip", "crates/filters/src/ccitt.rs::a_page_of_text_like_marks_round_trips_and_shrinks", "crates/filters/src/ccitt.rs::what_it_cannot_encode_is_an_error", "crates/optimize/tests/optimize.rs::black_and_white_images_become_ccitt_group_4", "crates/automation/tests/it/automation.rs::doc_optimize_stores_black_and_white_images_as_ccitt_group_4", "crates/ui-egui/tests/it/create.rs::the_pdf_optimizer_dialog_saves_an_optimized_copy"]- notes = "CCITT Group 4, lossless: PDF Optimizer ▸ Images ▸ Monochrome Images (on by default, so Reduce File Size does it too; doc_optimize mono) stores a 1-bit image of one colour component (grey, indexed, a separation) or an image mask, kept with no filter or general-purpose ones, as Group 4 when that is smaller as stored; the samples decode to the same bits, so colour space, decode array and masks stay. An eight-bit grey image of only black and white is packed to one bit first, then stored the same way (indexed images and colour-key masks aside), unless the grey settings make it smaller still, as they can a dithered scan downsampled to JPEG, its soft mask counted. Group 4 wins on scans; on clean computer-drawn 1-bit art Flate can be smaller, and the image then stays. Not yet: JBIG2 (lossless or lossy, which Adobe's help says beats CCITT for monochrome), monochrome downsampling, inline images, soft masks and /Mask images, rows wider than 32,767 samples. Redaction doesn't decode Group 4 yet (a mark over part of such an image removes it whole; nothing leaks)."- notes = "CCITT Group 4, lossless: PDF Optimizer ▸ Images ▸ Monochrome Images (on by default, so Reduce File Size does it too; doc_optimize mono) stores a 1-bit image of one colour component (grey, indexed, a separation) or an image mask, kept with no filter or general-purpose ones, as Group 4 when that is smaller as stored; the samples decode to the same bits, so colour space, decode array and masks stay. An eight-bit grey image of only black and white is packed to one bit first, then stored the same way (indexed images and colour-key masks aside), unless the grey settings make it smaller still, as they can a dithered scan downsampled to JPEG, its soft mask counted. Group 4 wins on scans; on clean computer-drawn 1-bit art Flate can be smaller, and the image then stays. CCITT fax images are decoded to be downsampled (optimize.downsample-images), and a resampled image is stored as Group 4 or 1-bit Flate, whichever is smaller. Not yet: JBIG2 (lossless or lossy, which Adobe's help says beats CCITT for monochrome), a lone Group 3 image to Group 4 without resampling (one behind another filter is stored again as Group 4; byte-aligned Group 3 with end-of-line codes but none before the first row, not as T.4 sends them, as PdfCraft draws it, which at /K 0 may be other rows than were coded), inline images, soft masks and /Mask images, Group 4 for rows wider than 32,767 samples."++++ +++++++++++++++++evidence = ["crates/optimize/tests/optimize.rs::eight_bit_black_and_white_images_become_one_bit", "crates/filters/src/ccitt.rs::bitmaps_round_trip", "crates/filters/src/ccitt.rs::a_page_of_text_like_marks_round_trips_and_shrinks", "crates/filters/src/ccitt.rs::what_it_cannot_encode_is_an_error", "crates/optimize/tests/optimize.rs::black_and_white_images_become_ccitt_group_4", "crates/optimize/tests/optimize.rs::group_3_fax_images_become_group_4", "crates/optimize/tests/optimize.rs::rgb_and_two_colour_indexed_black_and_white_images_become_one_bit", "crates/optimize/tests/optimize.rs::black_and_white_rgb_used_beyond_the_page_content_read_stays_rgb", "crates/optimize/tests/optimize.rs::black_and_white_rgb_drawn_only_where_the_optimizer_reads_becomes_grey", "crates/optimize/tests/optimize.rs::black_and_white_rgb_in_resources_its_page_tree_and_a_form_share_becomes_grey", "crates/automation/tests/it/automation.rs::doc_optimize_stores_black_and_white_images_as_ccitt_group_4", "crates/ui-egui/tests/it/create.rs::the_pdf_optimizer_dialog_saves_an_optimized_copy"]++++ +++++++++++++++++notes = "CCITT Group 4, lossless: PDF Optimizer ▸ Images ▸ Monochrome Images (on by default, so Reduce File Size does it too; doc_optimize mono) stores a 1-bit image of one colour component (grey, indexed, a separation) or an image mask, kept with no filter or general-purpose ones, as Group 4 when that is smaller as stored; the samples decode to the same bits, so colour space, decode array and masks stay. Packed to one bit first, then stored the same way (colour-key masks aside): eight-bit grey of only black and white, eight-bit DeviceRGB of only black and white (as DeviceGray; calibrated RGB, RGB with a profile, RGB drawn or listed where /DefaultGray or /DefaultRGB is in force or referred to from anywhere but the page and form resources read (an annotation's appearance or a pattern drawing it, directly or through resources or a form shared with a page; another image's /Alternates), and RGB whose soft mask has a /Matte aside), and an indexed image of 2, 4 or 8 bits that uses only palette entries 0 and 1 (keeping its palette), unless the grey or colour settings make it smaller still, as they can a dithered scan downsampled to JPEG, its soft mask counted. Group 4 wins on scans; on clean computer-drawn 1-bit art Flate can be smaller, and the image then stays. Group 3 fax images are stored again as Group 4 when that is smaller (damaged Group 3 with end-of-line codes as the decoder recovers it, as it reports no damage there; byte-aligned Group 3 with end-of-line codes but none before the first row, not as T.4 sends them, as PdfCraft draws it, which at /K 0 may be other rows than were coded). CCITT fax images are decoded to be downsampled (optimize.downsample-images), and a resampled image is stored as Group 4 or 1-bit Flate, whichever is smaller. Not yet: JBIG2 (lossless or lossy, which Adobe's help says beats CCITT for monochrome), inline images, soft masks and /Mask images, Group 4 for rows wider than 32,767 samples."[[feature]]id = "optimize.only-if-smaller"