Skip to content

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

Merge current main into PR1433 and preserve launch override across module splits

FredApps286a3c6eee78
diff --cc ROADMAP.md
index 5e3d79b40,56f6237e8..00622a79b
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@@ -171,7 -213,108 +213,109 @@@ Ranked; detail and the full milestone t
## Progress log
+- **2026-10-18 (M3, #1354, local candidate):** Integrated --two-paged with current main, retaining upstream modal/picker ownership and single-tab reuse. Native launch/opening/password regressions, negative checks against the old wrapper, visual inspection, formatting, strict scoped Clippy, layers, assets, parity and scoped WASM compilation pass. Three existing socket tests are unavailable in this workspace; one existing network test remains ignored. No push or GitHub merge; estimates unchanged.
+ - **2026-10-31 (M2, PR #4172 review):** Added same-machine pixel oracles for GBK Song, Hei, Kai and FangSong, including all four subset-prefixed Founder aliases. Reference PDFs use explicit Unicode mappings and independently selected installed faces; font data and rasters remain in memory. All eight cases ran; wrong-glyph and wrong-family production mutations each failed the new assertion and were restored. Validation: 422 renderer unit tests, renderer all-target Clippy with -D warnings, formatting, layers/assets/parity and renderer WASM checks passed; existing optional-patch/WASM warnings and parity notes remain. Estimates unchanged.
+
+ - **2026-10-31 (M2, PR #4172):** Integrated main fa5f9f8c, retaining both roadmap histories and raster regression groups. Restored display_config and thumbnail_config imports after the upstream explicit-import migration. Validation: 422 renderer unit tests, engine/UI all-target checks, scoped all-target Clippy with -D warnings, formatting, layers, assets, parity and renderer/engine WASM checks passed. Existing optional-patch/WASM warnings and parity notes remain; no full engine/UI runtime test rerun. Display-only font policy and estimates unchanged.
+
+ - **2026-10-28 (M2, PR #4172):** Integrated main 5af10276, preserving both roadmap histories and reviewing auto-merged export tests and accessibility UI changes. Validation: 488 scoped tests passed (18 engine, 412 renderer unit, 43 renderer integration, 15 Combine; one existing renderer integration test ignored); scoped all-target Clippy with -D warnings, formatting, layers, assets, parity and renderer/engine WASM checks passed. Viewer-only CJK fallback and print/output font policy remain unchanged; estimates unchanged.
+
+ - **2026-10-27 (M2, PR #4172 module-split conflicts):** Integrated main 1dd2737b, retaining viewer-only CJK fallback in split session modules and Combine thumbnail workers, and moving renderer regressions to the new test module. Validation: 798 scoped tests passed (371 engine, 412 renderer, 15 Combine; two existing engine tests ignored); scoped all-target Clippy with -D warnings, formatting, layers, assets, parity and renderer/engine WASM checks passed. Estimates unchanged.
+
+ - **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-26 (M2, PR #4172):** Reconciled current main, preserving its Japanese serif/weight selection and both branches' progress records. Installed CJK viewer and preview fallback remains display-only; estimates unchanged.
+
+ - **2026-10-29 (M7, #2517):** Widening a paragraph rejoins a wrap with the number of spaces that wrap consumed, including a typed run and none for a Chinese or Japanese word split. The count survives an incremental save and a full rewrite, and a width-only `text_edit` uses it. Estimates unchanged.
+ - **2026-10-26 (M11, JBIG2 symbols):** Lossless JBIG2 now stores each distinct mark of a black-and-white image once, as a symbol, and places its exact copies, when that is smaller than the generic region: on six pages of rendered 300 dpi text 28% of the generic region's size and 17% of Group 4's, and the same bits back through two independent decoders (hayro-jbig2 and Poppler). Scans, whose letters are seldom identical, gain little until refinement coding; a dictionary shared between pages (`/JBIG2Globals`) is next. Estimates unchanged.
+ - **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-22 (M7, #2517):** A partial rewrite of the last paragraph closes its marker after that paragraph's last `ET`, so a row left in the source stays in the paragraph. When the next paragraph shares the text object, the marker closes before that neighbour instead of after the shared `ET`. The extra marker is not added across two marked-content regions. Estimates unchanged.
+ - **2026-10-15 (M7, #2517):** A blank line between paragraphs stays a paragraph break. An explicit `TL` is the measured baseline gap. Without one, three or more rows at a repeated step stay one paragraph, and a single wider gap stays a break. Adding a row, even when an earlier row is left in the source, does not absorb the next paragraph on a later edit. 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, JBIG2):** The PDF Optimizer can store black-and-white images as lossless JBIG2 (a generic region, written from the JBIG2 draft standard and checked against its arithmetic-coder test sequence), about a third smaller than Group 4 on 300 dpi text, and Export ▸ Images reads JBIG2 images. JBIG2 symbol coding, where its largest gains on text are, is next.
+ - **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 (M6, calculation checks):** The calculation order now flags a formula that reads a field the form doesn't have (a field deleted from under a sum, a typo in notation, a script's `getField`) and a script that builds the names it reads at run time. Prepare a form ▸ Calculation order marks both on the row and in a card that names the broken formulas, in place of its all-clear. `form_calculation_order` gives each field's formula, and `form_fields` shows a custom Calculate script.
+ - **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.
+ - **2026-10-23 (M11, optimizer resolution):** Image downsampling includes each page's `/UserUnit` scale, preserving images already below the physical resolution threshold, including shared nested forms.
+ Synthetic measurement and optimization regressions cover direct and indirect units and page-local defaults.
+ Estimates unchanged.
+ - **2026-10-23 (M10, Word table widths):** Word export sizes each cell from the grid columns it spans, keeping unequal columns and cells after a merged cell consistent with the table grid.
+ - **2026-10-23 (M10, table continuation text):** Office exporters retain text from table slots covered by another cell's span as paragraph text.
+ Synthetic regressions check every input fragment survives exactly once in Word, HTML, RTF and PowerPoint, while ordinary superscripts stay in their table cells.
+ - **2026-10-23 (M10, image export):** Soft-mask Decode intervals preserve partial opacity in Export all images and Save Image As.
+ Synthetic regressions cover direct and indirect ranges, inverted/subrange alpha, packed masks, JPEG masks and unchanged image component Decode.
+ - **2026-10-23 (M10, print resources):** Vector printing preserves original page artwork when existing XObjects use annotation resource names.
+ The regression checks two distinct appearances, inherited resources, print/reopen pixels and unchanged source data.
+ Estimates unchanged.
+ - **2026-10-21 (M3, window resize and move on Wayland):** With PdfCraft's own title bar on GNOME/Wayland, a second resize by a window edge, or a second move by the empty tab strip, works straight after the first; it waited for a click inside the window, because the compositor keeps the button's release from egui. A unit test covers the release given back; checked by hand in a test build. Estimates unchanged.
+ - **2026-10-24 (M5, move preview):** A comment being moved is drawn where it goes while it is dragged (a rectangle or oval showed only its blue frame): the comment is rendered alone once as the drag starts and laid over the page, which shows it where it was until the move is applied. Engine `Document::comment_layer`; synthetic engine and UI regressions. Estimates unchanged.
+ - **2026-10-22 (M4, #3916 partial):** Document edits and Undo/Redo cancel an Organize page drag. Pointer-release regressions check exact page order and save/reopen.
+ - **2026-10-22 (M10, #3752 paper):** CUPS jobs ask for the chosen paper in every size. The 13 sizes the Print dialog sent no paper for (A6, A0–A2, ARCH, ANSI C–E) use PWG 5101.1 names, checked against a synthetic PPD with `cupsfilter`, and `doc_print` to a printer sends the paper too. The macOS tray half (Auto Select instead of the PPD's default tray) is a craft-print change that needs a pin bump here. Estimates unchanged.
+
+ - **2026-10-23 (M2, #234, continuation of #1567):** Reconciled installed CJK viewer fallback with current rendering changes; Windows preserves installed Song/Hei/Kai families and bounds font reads. GBK-EUC-H CIDFontType2 regression coverage includes text extraction; viewer fallback also survives reload with retained preferences. System fonts remain display-only. No overall readiness estimate changed.
+ - **2026-10-22 (M14, macOS association recovery candidate):** Successful desktop open/save/sign can queue recovery of an existing per-file binding to the running PDFCraft bundle through NSWorkspace. Metadata-only watcher changes retain undo and avoid false overwrite prompts; real same-length/same-mtime edits remain protected. Rebased on 0.12.0 and reuses #3042's shared atomic metadata preservation; the bounded recovery parser does not narrow save limits. Prior native Preview TEST-signature and Finder workflows passed on macOS 27.0.1; other versions remain unqualified. Estimates unchanged.
+ - **2026-10-13 (M7, free image rotation):** A selected page image has a rotate knob (Shift: 15 degree steps) and `image_edit` a `rotate_by` action; the angle is written as one undoable `cm`. Snapping to page edges while moving is in #1740; resize snapping is not done. Estimates unchanged.
+
+ - **2026-10-20 (M4, initial view):** Window and interface options read indirect boolean ViewerPreferences values. Synthetic regressions cover true/false, direct/indirect preference dictionaries and save/reopen; malformed entries retain false defaults. Estimates unchanged.
+ - **2026-10-20 (M3, #3535):** Escape with a menu open closes the menu and keeps the text selection; the next Escape clears it, as before. One keypress used to do both. A synthetic UI regression checks it. Estimates unchanged.
+ - **2026-10-16 (M3, close prompt keyboard):** The "Save changes?" prompt opens with Save chosen (Enter saves, as before) and the arrow keys and Tab / Shift+Tab move the choice to Cancel or Don't save, shown with a focus ring; Enter or Space press the chosen button and Escape still cancels. Before, Enter always saved whatever was Tab-focused. Estimates unchanged.
+ - **2026-10-21 (M3, #3808):** Page thumbnails in the Inspector can be resized independently from the document and Organize, with a slider, buttons and `thumbnail-zoom` control option. Selection, page following and reload are covered by regressions. Estimates unchanged.
+ - **2026-10-22 (M5, comment threads):** Replies join the comment their `/IRT` references, not every comment sharing its `/NM`; PyMuPDF names each page's first comment `fitz-A0`, so all replies used to land under page 1. The Comments header counts comments without their replies, with the number of replies in small text under it (in every catalogue), and a reply's thread line runs from the avatar above it to its own. A reply to a reply shows in its thread in the panel too (it was listed nowhere), an `/IRT` that leads to no comment (itself, a loop, a pop-up, an unlisted object) leaves its annotation a comment of its own instead of hiding it (a status or checkmark that leads nowhere is listed nowhere), and a Replace Text caret isn't counted as a reply. The comment tools refuse an `id` several comments share instead of acting on the first (page 1's), and take `page` + `index` for those; `comment_list` reads a status or checkmark from the annotation it was set on, as the panel does, and reports a reply's own on the reply. UI, engine and automation regressions cover it. Estimates unchanged.
+ - **2026-10-22 (M2, #3107 / PR #3438):** Inline-image parsing falls back to the existing EI heuristic when missing declared samples, headers or terminators exceed the content-window budget, instead of waiting for an impossible allocation. Exact-length parsing for available samples and ordinary large streamed images is retained. Estimates unchanged.
+ - **2026-10-21 (M14, Brazilian Portuguese):** Completed the `pt-br` catalog against the current 2,674-key union, including signature validation and accessibility messages; no build or compilation run. Localization remains partial because help and unpredictable engine/OS error details are not translated.
+ - **2026-10-21 (M14, #3557):** Preferences: the OK button stays below the scrolling settings instead of being the last thing in them, so it is in reach in a short window.
+
+ - **2026-10-19 (M11, #2178):** Optimize checks image and soft-mask dimensions and byte counts before decoding; hostile-dimension regressions pass. Estimates unchanged.
+
+ - **2026-10-20 (M11, #3507):** Image merging keeps trailing comments, split operands and graphics state across content streams. Synthetic tool tests check saved text, rendered regions and exact image rows.
+
+ - **2026-10-17 (M8, gap 6, #2662):** A filled cover over a long line counts when it hides half of any one word, not only 40% of the line's words or box, so a black box over one number in a long line — or an unapplied redaction mark over it — no longer audits clean while the number is still extractable; a sliver under half of every word it touches and under 40% of the line is still not flagged
+ - **2026-10-13 (M10, #1757):** Office export keeps each dotted-leader contents entry in one paragraph, with its page number, instead of inferring table cells from its separate text objects.
+ - **2026-10-22 (M6, calculation scripts):** The Calculate tab and a rename read simplified field notation only from a comment, where Acrobat writes it: a string that spells `BVCALC … EVCALC` is no longer taken for the notation, or rewritten by a rename. A `/` after the condition of `if`, `while`, `for` or `with` starts a regular expression, so a rename no longer rewrites a name inside one, and a quote inside one no longer hides the `getField` calls after it. Both found in review of #3550. A `//` comment ends at `\r`, U+2028 or U+2029 as well as `\n`, so in a script with `\r` line endings the code after one is no longer hidden from a rename, or taken for the notation. Estimates unchanged.
+ - **2026-10-20 (M6, calculation order page):** Prepare a form ▸ Calculation order, a page of its own, lists the calculated fields in the order they calculate with their formulas and values, moved with Up/Down arrows (as Acrobat's Set Field Calculation Order), Alt+↑/↓ or by dragging. A card says what is wrong with the order and holds Fix order; a loop has a card of its own that opens one of its formulas. On the page, each calculated field shows its step, and arrows show what the field in focus reads and what reads it. Estimates unchanged.
+ - **2026-10-20 (M6, calculation order):** The order a form's fields calculate in (`/CO`) is read, checked, fixed and set headlessly with `form_calculation_order`: it says which fields read one calculated later (they show stale values), which read each other in a loop, and which the PDF's order leaves out; Fix order moves only what must move, in one undo step, and the form recalculates. Editing a formula no longer moves its field to the end of the order, and a field the order lists twice calculates once. Estimates unchanged.
+ - **2026-10-20 (M2, #3574):** Forms without Resources use page Properties for ActualText and layer visibility. Synthetic tests cover boundaries, nested/shared forms, and save/reopen. Estimates unchanged.
+ - **2026-10-20 (M2, PR #3348 review):** Tracking samples retain short repeated punctuation (up to four glyphs), keeping tracked ellipses intact and searchable while longer TOC leaders still preserve title word spaces. Synthetic regressions cover isolated and surrounded ellipses. Estimates unchanged.
+ - **2026-10-20 (M2, #3601):** A missing spacing glyph in an OpenType substitute uses its ordinary-space glyph. Synthetic Japanese CID renderer tests check blank spaces, `/W` and `/DW` placement, and unchanged Unicode extraction. Font selection and embedded fonts are unchanged. Estimates unchanged.
+ - **2026-10-20 (M12, #3673):** Character encoding accepts Identity-H/V fonts with Adobe CJK collections and recognizes predefined non-Identity CMaps independently. Unknown CMaps and foreign registries remain refused; synthetic checker and read-only automation regressions passed after failing before the fix. Per-glyph mapping validation and embedded-font extraction remain separate. Estimates unchanged.
+ - **2026-10-19 (M6, renames keep formulas):** Renaming a field renames it in every calculation that reads it, in the same undo step: `AFSimple_Calculate` field lists, simplified field notation (the comment and the JavaScript after it) and `getField` calls naming it in one string literal; the rest of each script is kept as written. A sum used to drop the renamed field, notation read it as 0 and a script kept a stale value. Field Properties says how many formulas changed and `form_set_props` lists them as `formulas_updated`. Names built at run time and other events' scripts are not rewritten. Estimates unchanged.
+ - **2026-10-19 (M6, text field table):** Prepare a form ▸ Text field table drags out an area and adds rows and columns of named text fields as one undoable edit, laid out on the page as displayed, with a live preview, per-column name patterns and widths, and refusal before anything is added when a cell would be too small or a name taken; `form_add_field_table` does the same headlessly. `form.multiple-copies` is partial: copying an existing field into a grid is still missing. Estimates unchanged.
+
+ - **2026-10-16 (M7, #2516):** A paragraph number from `text_paragraphs` keeps naming the paragraph it listed after edits regroup the page: `text_edit`, `text_edit_layout` and `page_render`'s `hide_text_block` find it again by its text and box, and refuse one that was merged into a neighbour (the edited paragraph included) instead of rewriting the paragraph that took its number (`stale_paragraphs` lists the numbers gone). The inline editor's switch-paragraph click holds the same key. No stable identity across save and reopen yet (#2508).
+ - **2026-10-19 (M7, #3591):** A background added to a page that already has one is painted over the old one instead of going under it and staying hidden. Behind the content, backgrounds come first, in the order added, and then behind-content watermarks, so a watermark added after a background no longer disappears. Synthetic regressions in `crates/edit` check the order. Estimates unchanged.
+ - **2026-10-19 (M2, radial luminosity masks):** Added synthetic radial-fade coverage for the existing masked-gradient fix (#2132): centre, midpoint, antialiased clip and per-pixel shading reference, including previews, scales and tiles. Removing the existing native-gradient mask guard reproduces an opaque midpoint; restoring it passes. No new renderer behavior or estimate change.
+ - **2026-10-20 (M6, #3502):** Form detection preserves comments across content streams and does not add fields over rectangles hidden by those comments. Synthetic tests cover visible controls, graphics state, and saved field inventories. Estimates unchanged.
+ - **2026-10-20 (M6, #2273 / PR #2279):** Rebased the field-highlight default and Appearance preference onto main, retaining secured-form parity evidence and updating secured AcroForm/XFA toggle expectations. Build and test validation delegated to GitHub CI. Estimates unchanged.
+ - **2026-10-20 (M5, reshape lines):** A line or arrow could only be moved after it was drawn; its length and angle stayed. A selected line, connected lines, polygon or cloud now has a handle on each end or corner: dragging one reshapes it (Shift holds it to 45°), as one undo step, with the new shape drawn while dragging. `pdfcraft_annot::set_points`, `Edit::ReshapeAnnotation`, `comment_edit points`; comment lists carry the points. Estimates unchanged.
+ - **2026-10-20 (M3, #3620):** Overlapping comment hover uses the original annotation index independently of spatial inspection order. A synthetic UI regression covers different annotation upper edges. Estimates unchanged.
+
+ - **2026-10-20 (M3, #3541/#3620):** Comment hover follows the individual marked lines instead of the enclosing multiline rectangle, and overlapping comments follow paint order. Synthetic UI regressions cover all four text-markup kinds, page/view rotations, neighboring highlights, legacy rectangle fallback and unchanged PDF bytes. Estimates unchanged.
+ - **2026-10-20 (M10, #3532 partial):** Vector printing retains existing widget artwork when its appearance lacks Subtype. A print-owned copy adds Form dispatch metadata. The source stream and all explicit subtypes stay unchanged. Synthetic source/output raster checks cover resources, selected/shared appearances, placement, flags and content modes. Appearance regeneration and physical printer validation remain outside this fix. Estimates unchanged.
+
+ - **2026-10-20 (M5, arrow keys move comments):** With a comment selected, the arrow keys move it a screen pixel and ⌘/Ctrl or Shift and an arrow ten, instead of scrolling the view or turning the page; up is up on screen at any zoom and rotation, and each press is one undo step. Text markup and locked comments stay put. Estimates unchanged.
+
+ - **2026-10-19 (M14, #3373):** The main menu and its long submenus scroll in short windows, keeping their commands reachable. Estimates unchanged.
+
+ - **2026-10-19 (M3, #3387):** Save-prompt shortcuts yield to later consent and utility dialogs; a synthetic UI regression checks that an edited document stays open. Estimates unchanged.
+
+ - **2026-10-18 (M3, PR #3101 review):** Gap changes in Organize Pages preserve document scroll position; menu and control changes apply to both comparison panes without changing unrelated tabs. Three synthetic UI regressions were observed failing before the fixes. Readiness estimates unchanged.
+
+ - **2026-10-18 (M3, PR #3101):** Optional gapless continuous page display with persisted defaults and UI control support; both new labels translated in all 22 catalogs. Rebased onto current main, preserving navigation and rendering fixes. Readiness estimates unchanged.
+
+ - **2026-10-18 (M10, #3120):** Export to Word, PowerPoint, HTML and RTF reads text from form XObjects nested as deep as the renderer draws them (50 levels), and up to 50 000 forms a page (the renderer's budget for nested ones); it stopped at 12 levels and 4 096 forms and left the rest out silently. A page past those limits is listed in `doc_export_office`'s `truncated_pages`, with a warning. Estimates unchanged.
+
+ - **2026-10-18 (M5, PR #1971 review):** Nested FDF annotation values that identify a source `/Page` or `/Pages` dictionary become null at every copy depth. A synthetic three-page PDF saved and reopened before export verifies that destination actions cannot pull source page content into the FDF, while unrelated nested metadata and shared references remain intact. FDF import semantics, copied-graph limits and estimates are unchanged.
+ - **2026-10-15 (M5, PR #1971 refresh):** Nested FDF annotation values retain shared or cyclic copied graphs. Discovery borrows direct values and records annotation positions with lazy array owners; retained entries are budgeted before cloning. Synthetic stress fixtures include repeated aliases and saved-PDF cache eviction. Limits cover the copied graph; source parsing and page discovery retain their existing limits, with no total source-memory bound. FDF import semantics and estimates are unchanged.
+ - **2026-10-13 (M5, nested FDF values):** Comment export copies and renumbers nested indirect values, retaining geometry, colours, borders and shared graphs. Graph/data limits return an error before the destination is written; synthetic saved-PDF and automation exchange regressions. Estimates unchanged.
+ - **2026-10-18 (M2, #3086):** Text extraction estimates letter tracking without repeated punctuation gaps so dotted TOC leaders do not swallow word spaces. Synthetic PDF regressions cover leader lengths, phrase search and selection; strongly tracked text stays intact. Estimates unchanged.
- **2026-10-18 (M6, #2892):** Push-button normal labels are editable per widget through Options and form_set_props, independently of field names; rendering, undo/redo and incremental/full save/reopen are covered. Estimates unchanged.
diff --cc apps/pdfcraft/src/main.rs
index d7d4c1be6,814730f34..d2a75c594
--- a/apps/pdfcraft/src/main.rs
+++ b/apps/pdfcraft/src/main.rs
@@@ -1,8 -1,6 +1,8 @@@
//! PdfCraft desktop app.
//!
- //! Usage: `pdfcraft [options] [files…]`
+ //! Usage: `pdfcraft [options] [files…]` (`-h` / `--help` prints a short version of this, [`USAGE`]).
+//! `--two-paged` opens each command-line PDF in noncontinuous two-page view, without changing defaults.
+//! An explicit `--layout` takes precedence for the active document, regardless of argument order.
//! `--create-images [images…]` stages the images in one PDF and asks for the page DPI.
//!
//! View options (applied after the files open; also the seed of the UI control channel):
@@@ -41,9 -40,7 +42,8 @@@ mod motion
mod reopen;
mod settings;
mod single_instance;
+mod startup;
mod text_scale;
- mod updates;
#[cfg(test)]
#[path = "windows_manifest.rs"]
mod windows_manifest;
@@@ -58,6 -55,32 +58,33 @@@ const APP_ICON_PNG: &[u8] = include_byt
#[cfg(not(target_os = "macos"))]
const APP_ICON_PNG: &[u8] = include_bytes!("../../../assets/app-icon/hicolor/256x256/apps/ai.storyteller.pdfcraft.png");
+ /// What `-h` / `--help` prints (#4076): a hint, not the full option list (that is this file's
+ /// doc comment and the README). Scripts want `pdfcraft-cli`, which never opens a window.
+ const USAGE: &str = "\
+ Usage: pdfcraft [options] [files…]
+
+ Opens the files in the PdfCraft desktop app.
+
+ Options:
++ --two-paged open command-line PDFs in noncontinuous two-page view
+ --new-window open a window of its own instead of passing the files to a running PdfCraft
+ --create-images [images…] put the images in one PDF and ask for the page DPI
+ --control <file> enable the UI control channel (pdfcraft-cli ui --control <file> …)
+ --page N, --zoom 150, --layout continuous, --theme dark, …
+ view settings applied once the files are open
+ -h, --help print this and exit
+ --version print the version and exit
+
+ To inspect, convert or edit PDFs from a script, use pdfcraft-cli (pdfcraft-cli --help).";
+
+ /// Print `text` for `--help` and `--version`. `println!` would panic on a full or closed
+ /// standard output; this exits normally instead.
+ fn print_and_exit(text: &str) -> eframe::Result {
+ use std::io::Write;
+ let _ = writeln!(std::io::stdout().lock(), "{text}");
+ Ok(())
+ }
+
/// The app was called PrintCraft before; settings saved then are under this key.
const LEGACY_STORAGE_KEY: &str = "printcraft";
@@@ -190,14 -218,28 +222,16 @@@ fn main() -> eframe::Result
let _ = std::io::Write::write_fmt(&mut std::io::stderr(), format_args!("pdfcraft: {report}\n"));
}
}));
- let mut files = Vec::new();
- let mut options: Vec<(String, String)> = Vec::new();
- let mut control_file: Option<String> = None;
- let mut create_images = false;
- let mut new_window = false;
- let mut args = std::env::args().skip(1);
- while let Some(a) = args.next() {
- match a.as_str() {
- "--version" => return print_and_exit(&format!("pdfcraft {}", pdfcraft_engine::build_info::version())),
- // Before any window or log file, so a scripted call returns (#4076).
- "-h" | "--help" => return print_and_exit(USAGE),
- "--control" => control_file = args.next(),
- "--create-images" => create_images = true,
- "--new-window" => new_window = true,
- flag if flag.starts_with("--") => {
- let value = args.next().unwrap_or_default();
- options.push((flag.trim_start_matches("--").to_string(), value));
- }
- _ => files.push(path_from_arg(a)),
- }
+ let mut startup = startup::Arguments::parse(std::env::args().skip(1));
+ if startup.version {
- println!("pdfcraft {}", pdfcraft_engine::build_info::version());
- return Ok(());
++ return print_and_exit(&format!("pdfcraft {}", pdfcraft_engine::build_info::version()));
+ }
- let files = rejoin_split_paths(files, |p| std::path::Path::new(p).is_file());
++ if startup.help {
++ return print_and_exit(USAGE);
+ }
+ startup.files = rejoin_split_paths(startup.files, |p| std::path::Path::new(p).is_file());
+ let may_hand_off = startup.may_hand_off();
+ let startup::Arguments { files, options, control_file, create_images, two_paged, .. } = startup;
let integrated = cfg!(target_os = "macos");
// GNOME on Wayland leaves the window frame to the app (src/decorations.rs).
let window_controls = if cfg!(any(target_os = "macos", target_os = "windows")) { None } else { decorations::app_drawn() };
diff --cc apps/pdfcraft/src/startup.rs
index 003c6639d,000000000..be25da45b
mode 100644,000000..100644
--- a/apps/pdfcraft/src/startup.rs
+++ b/apps/pdfcraft/src/startup.rs
@@@ -1,231 -1,0 +1,244 @@@
+//! Native launch arguments and per-file view overrides (#1354).
+use pdfcraft_ui_egui::PdfCraftApp;
+
+#[derive(Default)]
+pub(super) struct Arguments {
+ pub files: Vec<String>,
+ pub options: Vec<(String, String)>,
+ pub control_file: Option<String>,
+ pub create_images: bool,
+ pub new_window: bool,
+ pub two_paged: bool,
+ pub version: bool,
++ pub help: bool,
+}
+
+impl Arguments {
+ pub fn may_hand_off(&self) -> bool {
+ !self.new_window && !self.files.is_empty() && self.options.is_empty() && self.control_file.is_none() && !self.create_images && !self.two_paged
+ }
+
+ pub fn parse(args: impl IntoIterator<Item = String>) -> Self {
+ let mut parsed = Self::default();
+ let mut args = args.into_iter();
+ while let Some(a) = args.next() {
+ match a.as_str() {
+ "--version" => {
+ parsed.version = true;
+ break;
+ }
++ "-h" | "--help" => {
++ parsed.help = true;
++ break;
++ }
+ "--control" => parsed.control_file = args.next(),
+ "--create-images" => parsed.create_images = true,
+ "--new-window" => parsed.new_window = true,
+ "--two-paged" => parsed.two_paged = true,
+ flag if flag.starts_with("--two-paged=") => {
+ // It has no value: do not consume the following filename on malformed use.
+ log::warn!("{flag}: use --two-paged without a value");
+ }
+ flag if flag.starts_with("--") => {
+ let value = args.next().unwrap_or_default();
+ parsed.options.push((flag.trim_start_matches("--").to_string(), value));
+ }
+ _ => parsed.files.push(super::path_from_arg(a)),
+ }
+ }
+ parsed
+ }
+}
+
+pub(super) fn open_files(app: &mut PdfCraftApp, files: &[String], two_paged: bool) {
+ for path in files {
+ if two_paged {
+ // The per-file override wins over initial view without changing saved defaults.
+ app.open_path_with_display(path, pdfcraft_ui_egui::canvas::PageLayout::TwoUp, false);
+ } else {
+ app.open_path(path);
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn parse(args: &[&str]) -> Arguments {
+ Arguments::parse(args.iter().map(|s| s.to_string()))
+ }
+
+ #[test]
+ fn standalone_flag_keeps_files_in_either_position() {
+ for args in
+ [["--two-paged", "first.pdf", "second.pdf"], ["first.pdf", "--two-paged", "second.pdf"], ["first.pdf", "second.pdf", "--two-paged"]]
+ {
+ let parsed = parse(&args);
+ assert!(parsed.two_paged);
+ assert_eq!(parsed.files, ["first.pdf", "second.pdf"]);
+ assert!(parsed.options.is_empty());
+ assert!(!parsed.may_hand_off());
+ }
+ let empty = parse(&["--two-paged"]);
+ assert!(empty.two_paged && empty.files.is_empty());
+ let normal = parse(&["first.pdf", "second.pdf"]);
+ assert!(!normal.two_paged);
+ assert!(normal.may_hand_off());
+ for args in [
+ &["--new-window", "first.pdf"][..],
+ &["--layout", "two-page", "first.pdf"],
+ &["--control", "control.json", "first.pdf"],
+ &["--create-images", "first.png"],
+ ] {
+ assert!(!parse(args).may_hand_off());
+ }
+ }
+
+ #[test]
+ fn existing_layout_options_are_preserved_in_either_order() {
+ for args in [["--two-paged", "--layout", "single", "file.pdf"], ["--layout", "single", "--two-paged", "file.pdf"]] {
+ let parsed = parse(&args);
+ assert!(parsed.two_paged);
+ assert_eq!(parsed.files, ["file.pdf"]);
+ assert_eq!(parsed.options, [("layout".into(), "single".into())]);
+ }
+ let parsed = parse(&["--two-paged", "--default-layout", "two-up", "file.pdf"]);
+ assert_eq!(parsed.options, [("default-layout".into(), "two-up".into())]);
+ }
+
+ #[test]
+ fn newer_options_and_version_are_preserved() {
+ let parsed = parse(&["--two-paged", "--new-window", "--grid-zoom", "150", "--default-mode", "read", "file:///tmp/a%20b.pdf"]);
+ assert!(parsed.two_paged && parsed.new_window);
+ assert_eq!(parsed.files, ["/tmp/a b.pdf"]);
+ assert_eq!(parsed.options, [("grid-zoom".into(), "150".into()), ("default-mode".into(), "read".into())]);
+ assert!(!parsed.may_hand_off());
+ let version = parse(&["--two-paged", "--version", "ignored.pdf"]);
+ assert!(version.version && version.files.is_empty());
+ }
+
++ #[test]
++ fn help_keeps_the_headless_early_exit() {
++ for flag in ["-h", "--help"] {
++ let args = parse(&["--two-paged", flag, "ignored.pdf"]);
++ assert!(args.help && args.files.is_empty());
++ }
++ }
++
+ #[test]
+ fn malformed_boolean_does_not_eat_a_file_or_option() {
+ let args = parse(&["--two-paged=false", "first.pdf", "--layout", "single", "second.pdf"]);
+ assert!(!args.two_paged);
+ assert_eq!(args.files, ["first.pdf", "second.pdf"]);
+ assert_eq!(args.options, [("layout".into(), "single".into())]);
+ }
+
+ #[test]
+ fn startup_override_is_per_file_and_does_not_persist() {
+ use std::io::Write as _;
+ let nonce = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
+ let path = std::env::temp_dir().join(format!("pdfcraft-two-paged-{}-{nonce}.pdf", std::process::id()));
+ let mut file = std::fs::OpenOptions::new().create_new(true).write(true).open(&path).unwrap();
+ file.write_all(include_bytes!("../../../crates/ui-egui/tests/data/form.pdf")).unwrap();
+ drop(file);
+ let second_path = path.with_extension("second.pdf");
+ std::fs::copy(&path, &second_path).unwrap();
+ let text = path.to_str().unwrap();
+ let second = second_path.to_str().unwrap();
+ for enabled in [false, true] {
+ let mut app = PdfCraftApp::new();
+ app.set_option("default-layout", "single").unwrap();
+ app.open_bytes("restored.pdf", None, include_bytes!("../../../crates/ui-egui/tests/data/form.pdf").to_vec()).unwrap();
+ let restored = app.views[0].id;
+ open_files(&mut app, &[text.into(), second.into()], enabled);
+ assert_eq!(app.views.len(), 3);
+ assert_eq!(app.views[0].id, restored);
+ assert_eq!(app.views[0].layout, pdfcraft_ui_egui::canvas::PageLayout::Single);
+ for view in app.views.iter().skip(1) {
+ assert_eq!(
+ view.layout,
+ if enabled { pdfcraft_ui_egui::canvas::PageLayout::TwoUp } else { pdfcraft_ui_egui::canvas::PageLayout::Single }
+ );
+ assert!(!view.continuous());
+ }
+ let persisted: serde_json::Value = serde_json::from_str(&app.persist()).unwrap();
+ assert_eq!(persisted["default_layout"], "single");
+ assert!(persisted.get("two_paged").is_none());
+ // Existing --layout applies after the flag to the active document only.
+ if enabled {
+ app.set_launch_layout("continuous").unwrap();
+ } else {
+ app.set_option("layout", "continuous").unwrap();
+ }
+ assert_eq!(app.views[2].layout, pdfcraft_ui_egui::canvas::PageLayout::Single);
+ assert!(app.views[2].continuous());
+ app.set_option("default-layout", "two-up").unwrap();
+ assert_eq!(app.view_defaults.layout, pdfcraft_ui_egui::canvas::PageLayout::TwoUp);
+ assert!(app.view_defaults.continuous);
+ open_files(&mut app, &[], enabled);
+ assert_eq!(app.views.len(), 3);
+ }
+ std::fs::remove_file(path).unwrap();
+ std::fs::remove_file(second_path).unwrap();
+ }
+
+ #[test]
+ fn explicit_launch_layout_preserves_argument_order_and_active_file() {
+ use pdfcraft_ui_egui::canvas::PageLayout;
+ let path = std::env::temp_dir().join(format!("pdfcraft-explicit-layout-{}.pdf", std::process::id()));
+ std::fs::write(&path, include_bytes!("../../../crates/ui-egui/tests/data/form.pdf")).unwrap();
+ let second_path = path.with_extension("second.pdf");
+ std::fs::copy(&path, &second_path).unwrap();
+ let names = [path.to_str().unwrap(), second_path.to_str().unwrap()];
+ for prefix in [["--two-paged", "--layout", "single"], ["--layout", "single", "--two-paged"]] {
+ for count in [1, 2] {
+ let args = Arguments::parse(prefix.into_iter().chain(names.iter().take(count).copied()).map(str::to_owned));
+ let mut app = PdfCraftApp::new();
+ app.set_option("default-layout", "continuous").unwrap();
+ app.open_bytes("restored.pdf", None, include_bytes!("../../../crates/ui-egui/tests/data/form.pdf").to_vec()).unwrap();
+ open_files(&mut app, &args.files, args.two_paged);
+ for (key, value) in args.options {
+ assert_eq!(key, "layout");
+ app.set_launch_layout(&value).unwrap();
+ }
+ assert_eq!(app.active, Some(count));
+ assert!(app.views[0].continuous());
+ for view in app.views.iter().skip(1).take(count - 1) {
+ assert_eq!(view.layout, PageLayout::TwoUp);
+ }
+ assert_eq!(app.views[count].layout, PageLayout::Single);
+ assert!(!app.views[count].continuous());
+ assert!(app.view_defaults.continuous);
+ }
+ }
+ std::fs::remove_file(path).unwrap();
+ std::fs::remove_file(second_path).unwrap();
+ }
+}
+
+#[cfg(test)]
+mod repeated_file_tests {
+ use super::*;
+
+ #[test]
+ fn a_repeated_file_reuses_its_tab_and_receives_the_launch_override() {
+ use pdfcraft_ui_egui::canvas::PageLayout;
+ let path = std::env::temp_dir().join(format!("pdfcraft-repeated-startup-{}.pdf", std::process::id()));
+ std::fs::write(&path, include_bytes!("../../../crates/ui-egui/tests/data/form.pdf")).unwrap();
+ let name = path.to_str().unwrap().to_string();
+ let mut app = PdfCraftApp::new();
+ app.set_option("default-layout", "continuous").unwrap();
+ app.open_path(&name);
+ let original = app.views[0].id;
+ open_files(&mut app, &[name.clone(), name], true);
+ assert_eq!(app.views.len(), 1);
+ assert_eq!(app.views[0].id, original);
+ assert_eq!(app.views[0].layout, PageLayout::TwoUp);
+ assert!(!app.views[0].continuous());
+ app.set_launch_layout("single").unwrap();
+ assert_eq!(app.views[0].layout, PageLayout::Single);
+ assert!(app.view_defaults.continuous);
+ std::fs::remove_file(path).unwrap();
+ }
+}
diff --cc crates/ui-egui/src/app.rs
index 000000000,425c2e26c..dc564c001
mode 000000,100644..100644
--- a/crates/ui-egui/src/app.rs
+++ b/crates/ui-egui/src/app.rs
@@@ -1,0 -1,647 +1,651 @@@
+ use super::hooks::OsEvent;
+ use super::state::{
+ Dialog, DocumentCopyJob, GridFile, LeftPanel, LinkOrigin, Mode, NumberDraft, PasswordPrompt, PendingLink, PropsTab, QuickTool, RecentFile,
+ RightPanel, UnlockPrompt,
+ };
+ #[cfg(not(target_arch = "wasm32"))]
+ use super::state::{OpenOutcome, OpenRequest, PendingRemoteLink};
+ use super::*;
+
+ mod clipboard;
+ mod commands;
+ mod control;
+ mod files;
+ mod frame;
+ mod input;
+ mod keys;
+ mod links;
+ mod prefs;
+ mod window;
+
+ pub(crate) use clipboard::{copy_refused, print_refused};
+ #[cfg(not(target_arch = "wasm32"))]
+ pub(crate) use files::same_file;
+ use frame::migrate_panel_state;
+ pub(crate) use prefs::{MAX_AUTHOR_CHARS, date_text_for_pdf};
+
+ impl Default for PdfCraftApp {
+ fn default() -> Self {
+ Self::new()
+ }
+ }
+
+ impl PdfCraftApp {
+ /// The window's title and, on the web, the page's, from the active document (#3640). Done in
+ /// `logic` too, which also runs while the window or browser tab is hidden: a document opened
+ /// then (a `?file=` download finishing) still names the page an embedding host reads.
+ fn sync_titles(&mut self, ctx: &egui::Context) {
+ // The window shows the active document's name (or title, if it asks for that), with •
+ // while it has unsaved changes, as the other Craft apps write it (#3640). Unsaved means
+ // what closing would ask about, so a draft not yet applied counts too.
+ let dirty = self.active.is_some_and(|i| self.has_unsaved_work(i));
+ let mark = if dirty { " •" } else { "" };
+ let titled = |name: Option<String>| {
+ name.or_else(|| self.combine_showing().then(|| tl!("Combine files").to_owned()))
+ .map_or_else(|| "PdfCraft".to_owned(), |name| format!("{name}{mark} — PdfCraft"))
+ };
+ let title = titled(self.active.and_then(|i| crate::canvas::tab_label(self, i)));
+ // The web page's title is what an embedding host reads to tell which file opened, so it
+ // names the file even when the document asks to show its own title.
+ let page_title = titled(self.active.and_then(|i| self.views.get(i)).and_then(|v| self.session.get(v.id)).map(|d| d.name.clone()));
+ if title != self.window_title {
+ ctx.send_viewport_cmd(egui::ViewportCommand::Title(title.clone()));
+ self.window_title = title;
+ }
+ if page_title != self.page_title {
+ // eframe's web runner ignores Title: set the page's own.
+ #[cfg(target_arch = "wasm32")]
+ if let Some(document) = web_sys::window().and_then(|w| w.document()) {
+ document.set_title(&page_title);
+ }
+ self.page_title = page_title;
+ }
+ }
+
+ /// Construct an application with the default session, panels, theme and control state.
+ pub fn new() -> Self {
+ Self {
+ session: Session::new(),
+ views: Vec::new(),
+ closed_tabs: Vec::new(),
+ active: None,
+ mode: Mode::AllTools,
+ default_mode: Mode::AllTools,
+ view_defaults: Default::default(),
+ units: Default::default(),
+ date_format_draft: None,
+ mode_override: None,
+ left: LeftPanel::AllTools,
+ side_panels: Default::default(),
+ left_open: true,
+ right: None,
+ last_right: RightPanel::Comments,
+ right_before_read: None,
+ comments_panel_closed: false,
+ right_panel_closed: false,
+ quick_tool: QuickTool::Select,
+ space_hand: None,
+ full_screen_tool: None,
+ comment_prefs: Default::default(),
+ theme: ThemeKind::Light,
+ // A fresh install follows the desktop's appearance (#1248); saved settings override.
+ theme_preference: ThemePreference::System,
+ reading_colors: Default::default(),
+ #[cfg(target_os = "linux")]
+ desktop_theme: None,
+ #[cfg(target_os = "linux")]
+ desktop_theme_enabled: false,
+ scroll_speed: scroll_speed::ScrollSpeed::default(),
+ animation_effects: motion::AnimationEffects::default(),
+ motion: motion::Motion::default(),
+ language: i18n::AUTO.to_string(),
+ ui_scale: None,
+ system_text_scale: 1.0,
+ ui_scale_applied: None,
+ flatten_fill_sign_on_save: false,
+ fill_text_size: fill_sign::TEXT_SIZE,
+ fill_text_color: [0.0; 3],
+ dialog: None,
+ updates: updates::Updates::default(),
+ printer_source: None,
+ options_source: None,
+ print_tasks: print_ui::PrintTasks::default(),
+ palette_open: false,
+ palette_query: String::new(),
+ all_tools_expanded: false,
+ all_tools_full: false,
+ all_tools_query: String::new(),
+ all_tools_tab: (None, false),
+ recent: Vec::new(),
+ reopen_last_session: false,
+ restore_last_view: true,
+ last_views: Vec::new(),
+ last_session: Default::default(),
+ quit_session: None,
+ reload_changed_files: true,
+ show_secured_notice: true,
+ always_default_view: false,
+ #[cfg(not(target_arch = "wasm32"))]
+ watch: Default::default(),
+ #[cfg(not(target_arch = "wasm32"))]
+ open_worker: None,
+ #[cfg(not(target_arch = "wasm32"))]
+ pending_opens: Vec::new(),
+ #[cfg(not(target_arch = "wasm32"))]
+ next_open_token: 0,
++ #[cfg(not(target_arch = "wasm32"))]
++ launch_layout: None,
++ #[cfg(not(target_arch = "wasm32"))]
++ launch_display_target: None,
+ #[cfg(all(test, not(target_arch = "wasm32")))]
+ open_prepare_gate: None,
+ pinned: Default::default(),
+ toast: None,
+ toast_script: None,
+ script_messages: std::collections::VecDeque::new(),
+ script_messages_dropped: 0,
+ toast_dropped: 0,
+ integrated_titlebar: false,
+ window_controls: None,
+ system_title_bar: false,
+ app_frame_shown: None,
+ password_prompt: None,
+ document_copy: None,
+ unlock_prompt: None,
+ full_screen: false,
+ inbox: Default::default(),
+ startup_inbox: Default::default(),
+ startup_superseded: false,
+ failed_inbox: Default::default(),
+ unsaved_flag: Default::default(),
+ os_events: None,
+ host_save: None,
+ host_dirty: None,
+ close_request: None,
+ save_prompt_button: Default::default(),
+ save_prompt_seen: false,
+ save_prompt_attention: false,
+ #[cfg(not(target_arch = "wasm32"))]
+ pending_overwrite: None,
+ save_override: None,
+ props_draft: None,
+ view_draft: None,
+ custom_draft: None,
+ requests: Default::default(),
+ #[cfg(not(target_arch = "wasm32"))]
+ pickers: Default::default(),
+ #[cfg(not(target_arch = "wasm32"))]
+ pick_override: None,
+ export_dir_override: None,
+ split_draft: SplitDraft::default(),
+ extract_draft: ExtractDraft::default(),
+ rotate_draft: RotateDraft::default(),
+ summary_sort: Default::default(),
+ sign_draft: None,
+ digital_ids: Vec::new(),
+ sig_expanded: Vec::new(),
+ a11y_options: a11y_ui::A11yOptions::default(),
+ ocr_draft: ocr_ui::OcrDraft::default(),
+ ocr_run: None,
+ ocr_batch: None,
+ run_inline: false,
+ custom_actions: Vec::new(),
+ wizard: Default::default(),
+ action_run: None,
+ action_files_override: None,
+ pdfa: Default::default(),
+ compare_old: None,
+ compare: None,
+ js_console: Default::default(),
+ doc_js: Default::default(),
+ a11y: a11y_ui::A11yState::default(),
+ tags_state: Default::default(),
+ a11y_skipped: Default::default(),
+ alt_draft: Default::default(),
+ os_key_store_ids: false,
+ cert_viewer: None,
+ space_audit: Vec::new(),
+ space_audit_of: None,
+ combine_draft: Vec::new(),
+ combine_conflicts: Default::default(),
+ combine_tab: Default::default(),
+ combine_columns: Default::default(),
+ combine_view: Default::default(),
+ combine_zoom: 1.0,
+ organize_zoom: 1.0,
+ combine_thumbs: Default::default(),
+ image_import: None,
+ custom_stamps: Vec::new(),
+ stamp_draft: Default::default(),
+ optimize_draft: OptimizeDraft::default(),
+ optimize_run: None,
+ progress_notice: None,
+ page_clipboard: None,
+ grid_drop: None,
+ last_snapshot: None,
+ last_copied_image: None,
+ last_copied_file: None,
+ system_clipboard: true,
+ clipboard_override: None,
+ v_pressed: false,
+ attach_override: None,
+ duplicate_draft: None,
+ page_props_draft: None,
+ field_table_draft: None,
+ form_preview: false,
+ window_title: String::new(),
+ page_title: String::new(),
+ recovery: None,
+ recoverable: Vec::new(),
+ recovery_keys: Default::default(),
+ last_autosave: None,
+ allow_quit: false,
+ deferred_commands: Vec::new(),
+ native_menu: None,
+ menu_input: Vec::new(),
+ dialog_seen: None,
+ dialog_epoch: 0,
+ ctx: None,
+ #[cfg(not(target_arch = "wasm32"))]
+ window_state: Default::default(),
+ styled: false,
+ fonts_ready: false,
+ fonts_cjk: theme::CjkPreference::Default,
+ control: None,
+ bookmark_rename: None,
+ last_opened_url: None,
+ community_card_closed: false,
+ pending_link: None,
+ pending_full_screen: None,
+ pending_remote_link: None,
+ protect_draft: Default::default(),
+ text_style_draft: Default::default(),
+ boxes_draft: Default::default(),
+ marks_draft: Default::default(),
+ unmarked_page: Default::default(),
+ export_draft: Default::default(),
+ export_status: None,
+ signature: None,
+ initials: None,
+ signature_draft: Default::default(),
+ signature_preview: None,
+ signature_photo: None,
+ saved_signature_previews: [None, None],
+ sign_graphic: sign_ui::SignGraphic::Name,
+ sign_graphic_preview: None,
+ #[cfg(target_arch = "wasm32")]
+ signature_images: Default::default(),
+ comment_props: None,
+ field_props: None,
+ bulk_field_props: None,
+ redact_prefs: RedactPrefs::default(),
+ redact_defaults: RedactPrefs::default(),
+ redact_before: None,
+ redact_pages_draft: RedactPagesDraft::default(),
+ redact_search: RedactSearchDraft::default(),
+ hidden_draft: HiddenDraft::default(),
+ print_draft: PrintDraft::default(),
+ link_draft: None,
+ text_style: content_ui::default_style(),
+ replace_draft: None,
+ number_draft: NumberDraft { from: 1, to: 1, style: pdfcraft_engine::LabelStyle::Decimal, prefix: String::new(), start: 1 },
+ word_count_draft: word_count_ui::Draft::default(),
+ }
+ }
+
+ /// Fields are being edited (Prepare a form or its Calculation order is open, or a field tool
+ /// is picked), unless the form is being previewed.
+ pub fn is_preparing(&self) -> bool {
+ ((self.left_open && matches!(self.left, LeftPanel::Tool("form") | LeftPanel::CalculationOrder))
+ || matches!(self.quick_tool, QuickTool::Field(_)))
+ && !self.form_preview
+ }
+
+ /// A number that changes whenever the open dialog changes (opened, closed or replaced by
+ /// another), checked every frame. A picker started from a dialog's Browse… button answers
+ /// only into the same showing of that dialog.
+ pub(crate) fn dialog_epoch(&mut self) -> u64 {
+ if self.dialog != self.dialog_seen {
+ self.dialog_seen = self.dialog;
+ self.dialog_epoch = self.dialog_epoch.wrapping_add(1);
+ }
+ self.dialog_epoch
+ }
+
+ pub fn active_ids(&self) -> Option<(usize, DocId)> {
+ self.active.and_then(|i| self.views.get(i).map(|v| (i, v.id)))
+ }
+
+ /// A dialog or prompt is open over the window: the keyboard is its own, and nothing may act
+ /// on the document underneath it.
+ pub(crate) fn modal_open(&self) -> bool {
+ self.dialog.is_some()
+ || self.close_request.is_some()
+ || self.password_prompt.is_some()
+ || self.unlock_prompt.is_some()
+ || self.pending_link.is_some()
+ || self.pending_remote_link.is_some()
+ || self.updates.open
+ }
+
+ /// Show `msg` in the toast now, in place of whatever it showed. Script messages still waiting
+ /// show after it.
+ pub fn notify(&mut self, msg: impl Into<String>) {
+ // A left-out count it replaces is said again once the toast is free.
+ self.script_messages_dropped = self.script_messages_dropped.saturating_add(std::mem::take(&mut self.toast_dropped));
+ self.toast = Some((msg.into(), 0.0));
+ self.toast_script = None;
+ }
+
+ /// Notify with a static message in the UI language.
+ pub fn notify_tr(&mut self, text: &str) {
+ self.notify(tl!(text).to_string());
+ }
+
+ /// Notify with an error's own text. Engine and OS messages are not translated: matching their
+ /// English wording would break silently whenever it changes.
+ pub fn notify_error(&mut self, error: impl std::fmt::Display) {
+ self.notify(error.to_string());
+ }
+
+ /// Notify with a `{name}`-style template in the UI language (placeholders filled once).
+ pub fn notify_fmt(&mut self, template: &str, args: &[(&str, &str)]) {
+ self.notify(i18n::fmt(tl!(template), args));
+ }
+
+ /// `true` while any open document still waits for page renders (used by headless capture).
+ pub fn render_pending(&self) -> bool {
+ self.views.iter().any(|v| v.render_pending())
+ }
+ }
+
+ impl eframe::App for PdfCraftApp {
+ /// While files are dragged over the window the system sends no pointer moves, so egui
+ /// would keep the place the pointer entered at: tell it where the pointer really is, so the
+ /// page grid can show (and use) the gap under it.
+ fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
+ // The button's release a window move or resize kept from egui.
+ window_controls::release_after_desktop_grab(ctx, raw);
+ self.prepare_raw_input(ctx, raw);
+ if raw.hovered_files.is_empty() && raw.dropped_files.is_empty() {
+ return;
+ }
+ if let Some(pos) = drag_pointer::in_window(ctx) {
+ raw.events.push(egui::Event::PointerMoved(pos));
+ }
+ ctx.request_repaint();
+ }
+
+ fn save(&mut self, storage: &mut dyn eframe::Storage) {
+ // eframe has just stored the window as it is now: not while it is minimized.
+ #[cfg(not(target_arch = "wasm32"))]
+ {
+ let minimized = self.ctx.as_ref().is_some_and(|c| c.input(|i| i.viewport().minimized == Some(true)));
+ self.window_state.keep(storage, minimized);
+ }
+ storage.set_string("pdfcraft", self.persist());
+ }
+
+ /// Each frame's work before drawing: opens, operating-system and control-channel requests,
+ /// the quit guard, shortcuts, and the background jobs' results.
+ fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
+ self.ctx = Some(ctx.clone());
+ #[cfg(not(target_arch = "wasm32"))]
+ self.window_state.repair(ctx);
+ self.dialog_epoch();
+ // Notices raised outside `ui` (opened files, OS events, the control channel) translate too.
+ let lang = i18n::Lang::from_pref(&self.language);
+ i18n::set_current(lang);
+ #[cfg(not(target_arch = "wasm32"))]
+ {
+ if let Some(worker) = &self.open_worker {
+ worker.set_context(ctx);
+ }
+ self.poll_pending_opens();
+ }
+ // Chinese wants its own faces before the Japanese ones (one baseline per line).
+ let cjk = theme::CjkPreference::for_language(lang.code());
+ if !self.styled {
+ egui_extras::install_image_loaders(ctx);
+ theme::install_fonts_for(ctx, cjk);
+ self.fonts_cjk = cjk;
+ theme::apply(ctx, self.theme);
+ self.styled = true;
+ } else {
+ self.fonts_ready = true;
+ if cjk != self.fonts_cjk {
+ // Same family names as before, so named fonts stay valid while the new set loads.
+ theme::install_fonts_for(ctx, cjk);
+ self.fonts_cjk = cjk;
+ }
+ }
+ self.sync_theme(ctx);
+ let native = ctx.native_pixels_per_point().unwrap_or(1.0);
+ ui_scale::sync(ctx, ui_scale::zoom(self.ui_scale, self.system_text_scale, native), &mut self.ui_scale_applied);
+ // Remember user work even if its tab is subsequently closed or Home is selected.
+ self.startup_superseded |= !self.views.is_empty() || self.combine_showing() || self.dialog.is_some() || self.password_prompt.is_some();
+ // Also done in `raw_input_hook`, before input; here for hosts that don't call the hook.
+ self.scroll_speed.set_line_speed(ctx);
+ // Motion reads this frame's wheel input, so it begins in `ui`, in a known UI phase:
+ // `logic` also runs alone while hidden, where the input events and time are stale.
+ // Before taking this frame's drop: the grid must be drawn once with the pointer where
+ // the files were let go before the gap is read.
+ self.finish_grid_drop(ctx);
+ // Showing a document hides the Combine files tab.
+ if self.active.is_some() {
+ self.combine_tab.focused = false;
+ }
+ #[cfg(target_arch = "wasm32")]
+ self.process_signature_images();
+ let dropped = ctx.input(|i| i.raw.dropped_files.clone());
+ #[cfg(not(target_arch = "wasm32"))]
+ let dropped = self.drop_on_signature_pad(dropped);
+ #[cfg(not(target_arch = "wasm32"))]
+ let dropped = self.drop_on_grid(dropped, ctx);
+ for f in dropped {
+ // Files dropped on the Combine files tab join its list instead of opening.
+ if self.combine_showing() {
+ self.drop_into_combine(f, ctx);
+ } else {
+ self.open_dropped(f, ctx);
+ }
+ }
+ let arrived: Vec<(String, Vec<u8>)> = self.inbox.lock().map(|mut q| std::mem::take(&mut *q)).unwrap_or_default();
+ for (name, bytes) in arrived {
+ if let Err(e) = self.open_bytes(&name, None, bytes) {
+ self.notify_fmt("Couldn't open {name}: {e}", &[("name", &name), ("e", &e.to_string())]);
+ }
+ }
+ // Don't replace a pending prompt or import. A startup file may need its own password
+ // prompt, so its bytes stay queued until the current interaction finishes.
+ #[cfg(not(target_arch = "wasm32"))]
+ let opening = !self.pending_opens.is_empty();
+ #[cfg(target_arch = "wasm32")]
+ let opening = false;
+ if !opening
+ && self.password_prompt.is_none()
+ && self.image_import.is_none()
+ && self.dialog.is_none()
+ && self.close_request.is_none()
+ && self.pending_link.is_none()
+ && self.pending_remote_link.is_none()
+ {
+ let startup = self.startup_inbox.lock().map(|mut q| std::mem::take(&mut *q)).unwrap_or_default();
+ for (name, bytes) in startup {
+ let activate = !self.startup_superseded;
+ if let Err(e) = self.open_bytes_with_focus(&name, None, bytes, activate) {
+ self.notify_fmt("Couldn't open {name}: {e}", &[("name", &name), ("e", &e)]);
+ }
+ }
+ }
+ let failed: Vec<(String, String)> = self.failed_inbox.lock().map(|mut q| std::mem::take(&mut *q)).unwrap_or_default();
+ for (name, e) in failed {
+ self.notify_fmt("Couldn't open {name}: {e}", &[("name", &name), ("e", &e)]);
+ }
+ let os_events = self.os_events.as_mut().map(|poll| poll()).unwrap_or_default();
+ for e in os_events {
+ match e {
+ #[cfg(not(target_arch = "wasm32"))]
+ OsEvent::Open(paths) => {
+ paths.iter().for_each(|p| {
+ self.open_path(p);
+ });
+ // Files handed to the running app (Finder, or another launch): bring its
+ // window to the front, also when minimized or full screen on another Space.
+ ctx.send_viewport_cmd(egui::ViewportCommand::Minimized(false));
+ ctx.send_viewport_cmd(egui::ViewportCommand::Focus);
+ }
+ #[cfg(target_arch = "wasm32")]
+ OsEvent::Open(_) => {}
+ // Like closing the window: `guard_quit` asks about unsaved changes.
+ OsEvent::Quit => ctx.send_viewport_cmd(egui::ViewportCommand::Close),
+ }
+ }
+ if let Some((_, id)) = self.active_ids() {
+ let out = self.session.take_js_output(id);
+ self.handle_js(id, out);
+ }
+ if let Some(mut control) = self.control.take() {
+ control.tick(ctx, self);
+ self.control = Some(control);
+ }
+ self.guard_quit(ctx);
+ // macOS: quit through `terminate:` instead of dropping the window (Touch Bar crash, #1136).
+ #[cfg(target_os = "macos")]
+ craft_quit::on_close_request(ctx);
+ self.autosave_tick(ctx, web_time::Instant::now());
+ // Reload documents whose files a build rewrote (#431).
+ #[cfg(not(target_arch = "wasm32"))]
+ self.watch_files();
+ if self.host_dirty.is_some() {
+ let dirty = self.first_dirty().is_some();
+ if let Some(report) = self.host_dirty.as_mut() {
+ report(dirty);
+ }
+ }
+ self.poll_updates();
+ self.poll_print();
+ // Shortcuts deferred last frame: the text field has taken that frame's typing since.
+ let deferred = std::mem::take(&mut self.deferred_commands);
+ self.native_menu_clicks(ctx);
+ // The keys a menu click stands for (⌘C, Delete…), before anything reads this frame's keys.
+ if !self.menu_input.is_empty() {
+ let events = std::mem::take(&mut self.menu_input);
+ ctx.input_mut(|i| i.events.extend(events));
+ }
+ self.shortcuts(ctx);
+ // Scrolling and group-drag previews are transient: never resume after changing tabs,
+ // opening a modal/palette, or returning to a window that lost focus.
+ let blocked = self.modal_open() || self.palette_open || !ctx.input(|i| i.focused);
+ for (index, view) in self.views.iter_mut().enumerate() {
+ view.objects.set_input_blocked(blocked || self.active != Some(index));
+ if blocked || self.active != Some(index) {
+ view.auto_scroll.cancel();
+ }
+ }
+ // A field that refused its value this frame keeps the shortcut from saving or printing
+ // behind the user's back; so does a save prompt opened since.
+ if self.process_pending_edits() && self.close_request.is_none() {
+ for (id, doc) in deferred {
+ // Only in the document the shortcut was pressed in.
+ if self.active_ids().map(|(_, active)| active) == doc {
+ self.execute(id);
+ }
+ }
+ }
+ self.poll_export();
+ self.auto_ocr_scanned_page();
+ self.poll_ocr();
+ self.poll_optimize();
+ self.poll_action();
+ self.process_file_requests();
+ #[cfg(not(target_arch = "wasm32"))]
+ self.process_picked();
+ // Last, after everything that can open or answer the "save changes?" question.
+ self.attend_save_prompt(ctx);
+ self.sync_native_menu(ctx);
+ self.sync_titles(ctx);
+ }
+
+ fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
+ let ctx = ui.ctx().clone();
+ i18n::set_current(i18n::Lang::from_pref(&self.language));
+ // A language change switches stock chrome between LTR and RTL before anything is drawn.
+ theme::sync_direction(&ctx);
+ // Fonts registered via set_fonts only take effect next frame; named families would panic now.
+ if !self.fonts_ready {
+ ctx.request_repaint();
+ return;
+ }
+ // Before any widget reads this frame's wheel input or draws.
+ self.motion.begin_pass(&ctx, self.animation_effects);
+ // One-time 0.36 -> 0.37 panel persistence migration, before any panel stores or reads state.
+ migrate_panel_state(ui);
+ for view in &mut self.views {
+ view.begin_render_frame();
+ }
+ self.sync_titles(&ctx);
+ // The accessible window takes the same name, so a screen reader (AT-SPI on Linux, UIA on
+ // Windows) can tell it apart (#4614). egui builds the root node afresh every pass.
+ ctx.accesskit_node_builder(egui::accesskit_root_id(), |root| root.set_label(self.window_title.as_str()));
+ if self.full_screen && self.active.is_some() {
+ // Full screen: the page on black, nothing else, as Acrobat's Full Screen Mode (Esc
+ // or ⌘L to leave).
+ egui::CentralPanel::default().frame(egui::Frame::NONE.fill(egui::Color32::BLACK)).show(ui, |ui| {
+ if let Some(i) = self.active {
+ match compare_ui::side_by_side(self, i) {
+ Some((old, new)) => compare_ui::compare_area(self, old, new, ui),
+ None => canvas::document_area(self, i, ui),
+ }
+ }
+ });
+ dialogs::show(self, &ctx);
+ // Notices too: a refused field value or a failed save must be seen in full screen.
+ self.show_progress(&ctx);
+ widgets::toast(self, &ctx);
+ self.finish_render_frame(&ctx);
+ if let Some(mut control) = self.control.take() {
+ control.finish_frame(&ctx, self);
+ self.control = Some(control);
+ }
+ return;
+ }
+ self.sync_window_frame(&ctx);
+ if self.draws_window_frame() {
+ window_controls::resize_edges(&ctx);
+ }
+ chrome::tab_strip(self, ui);
+ chrome::mode_bar(self, ui);
+ // Whichever way another tab came to the front, it shows instead of the expanded view.
+ if self.all_tools_full && self.all_tools_tab != self.shown_tab() {
+ self.all_tools_full = false;
+ }
+ side_panels::show(self, ui);
+ let t = theme::Tokens::get(&ctx);
+ egui::CentralPanel::default().frame(egui::Frame::NONE.fill(t.pasteboard)).show(ui, |ui| {
+ if self.mode == Mode::AllTools && self.all_tools_full {
+ all_tools_ui::show(self, ui);
+ } else {
+ match self.active {
+ None if self.combine_showing() => combine_ui::page(self, ui),
+ None => home::show(self, ui),
+ Some(index) => match compare_ui::side_by_side(self, index) {
+ Some((old, new)) => compare_ui::compare_area(self, old, new, ui),
+ None => canvas::document_area(self, index, ui),
+ },
+ }
+ }
+ });
+ self.process_pending_edits();
+ palette::show(self, &ctx);
+ dialogs::show(self, &ctx);
+ self.show_progress(&ctx);
+ widgets::toast(self, &ctx);
+ self.finish_render_frame(&ctx);
+ // Screenshots are issued only after a settled pass that really drew the window.
+ if let Some(mut control) = self.control.take() {
+ control.finish_frame(&ctx, self);
+ self.control = Some(control);
+ }
+ }
+ }
diff --cc crates/ui-egui/src/app/files.rs
index 000000000,3c68dc561..5ef110d6a
mode 000000,100644..100644
--- a/crates/ui-egui/src/app/files.rs
+++ b/crates/ui-egui/src/app/files.rs
@@@ -1,0 -1,682 +1,779 @@@
+ use super::*;
+
+ /// Whether `a` and `b` name the same file: equal, or equal once made absolute against the
+ /// current directory (links are not resolved, as in `last_session`).
+ pub(crate) fn same_file(a: &str, b: &str) -> bool {
+ a == b || matches!((std::path::absolute(a), std::path::absolute(b)), (Ok(x), Ok(y)) if x == y)
+ }
+
+ impl PdfCraftApp {
+ /// Open a document the way it asks to be opened: navigation panel, layout, magnification,
+ /// page and the place on it (Document Properties ▸ Initial View, `/OpenAction`). With Always
+ /// use my default zoom and page layout on, the layout and magnification stay at the defaults
+ /// the view opened with, and the view goes to the opening page's top.
+ fn apply_initial_view(&mut self, index: usize, v: &pdfcraft_engine::InitialView) {
+ use pdfcraft_engine::{InitialLayout as L, Magnification as M, Navigation as N};
+ let pages = self.session.get(self.views[index].id).map_or(0, |d| d.info.pages.len());
+ // A right panel the user closed stays closed, whatever the document asks for (#2884).
+ // A document that asks for full screen gets the panel it names for outside it
+ // (`/NonFullScreenPageMode`, Table 147), there when the prompt is declined or full
+ // screen is left.
+ let navigation = if v.full_screen { v.non_full_screen } else { v.navigation };
+ if self.active == Some(index) && !self.right_panel_closed {
+ match navigation {
+ N::PageOnly => {}
+ N::Bookmarks => self.right = Some(RightPanel::Bookmarks),
+ N::Pages => self.right = Some(RightPanel::Pages),
+ N::Attachments => self.right = Some(RightPanel::Attachments),
+ N::Layers => self.right = Some(RightPanel::Layers),
+ }
+ }
+ let view = &mut self.views[index];
+ if !self.always_default_view {
+ match v.layout {
+ // The view opened in Default page display already.
+ L::Default => {}
+ L::SinglePage => (view.layout, view.continuous) = (canvas::PageLayout::Single, false),
+ L::SinglePageContinuous => (view.layout, view.continuous) = (canvas::PageLayout::Single, true),
+ L::TwoUp => (view.layout, view.continuous) = (canvas::PageLayout::TwoUp, false),
+ L::TwoUpContinuous => (view.layout, view.continuous) = (canvas::PageLayout::TwoUp, true),
+ L::TwoUpCoverPage => {
+ (view.layout, view.continuous, view.cover) = (canvas::PageLayout::TwoUp, false, true);
+ }
+ L::TwoUpContinuousCoverPage => {
+ (view.layout, view.continuous, view.cover) = (canvas::PageLayout::TwoUp, true, true);
+ }
+ }
+ match v.magnification {
+ // The view opened at the default zoom already.
+ M::Default => {}
+ M::ActualSize => view.set_zoom(1.0),
+ M::Percent(p) => view.set_zoom((p / 100.0) as f32),
+ M::FitPage | M::FitVisible => view.fit = canvas::Fit::Page,
+ M::FitWidth => view.fit = canvas::Fit::Width,
+ M::FitHeight => view.fit = canvas::Fit::Height,
+ }
+ }
+ // The opening destination (`/OpenAction`, named destinations resolved): its page, and
+ // where on it and how large, as a bookmark or link to it would (ISO 32000-2 Table 149).
+ // With the default view kept, only the page.
+ let info = self.session.get(view.id).map(|d| &d.info);
+ match info.and_then(|i| i.open_dest.filter(|(page, _)| *page < pages).map(|d| (i, d))) {
+ Some((info, (page, dest))) if !self.always_default_view => view.go_to_dest(page, dest, info),
+ Some((_, (page, _))) => {
+ if page > 0 {
+ view.go_to_page(page);
+ }
+ }
+ None if v.page > 0 && v.page < pages => view.go_to_page(v.page),
+ None => {}
+ }
+ }
+
+ /// Open a document and make it the active tab. Encrypted files raise the password prompt.
+ pub fn open_bytes(&mut self, name: &str, path: Option<String>, bytes: Vec<u8>) -> Result<(), String> {
+ self.startup_superseded = true;
+ self.open_bytes_with_focus(name, path, bytes, true)
+ }
+
+ pub(super) fn open_bytes_with_focus(&mut self, name: &str, path: Option<String>, bytes: Vec<u8>, activate: bool) -> Result<(), String> {
+ // Images and text files become new, unsaved PDFs (Create a PDF).
+ let active = self.active;
+ if let Some(r) = self.open_converted(name, &bytes) {
+ if !activate {
+ self.active = active;
+ }
+ return r;
+ }
+ self.try_open(name, path, std::sync::Arc::new(bytes), None, activate)
+ }
+
+ #[cfg(not(target_arch = "wasm32"))]
+ pub(crate) fn schedule_open(&mut self, request: OpenRequest) -> Result<u64, String> {
+ if self.open_worker.is_none() {
+ self.open_worker = Some(
+ open_worker::OpenWorker::new(
+ #[cfg(test)]
+ self.open_prepare_gate.clone(),
+ )
+ .map_err(|e| format!("couldn't start the document-open worker: {e}"))?,
+ );
+ }
+ let token = self.next_open_token.wrapping_add(1);
+ let worker = self.open_worker.as_ref().ok_or("the document-open worker is unavailable")?;
+ if let Some(ctx) = &self.ctx {
+ worker.set_context(ctx);
+ }
+ let receiver =
+ worker.submit(token, self.session.open_context(), request.name.clone(), request.path.clone(), request.password, request.input)?;
+ self.next_open_token = token;
+ self.pending_opens.push(PendingOpen {
+ token,
+ receiver,
+ name: request.name,
+ path: request.path,
+ stamp: request.stamp,
+ activate: request.activate,
+ after_open: request.after_open,
+ recovered: request.recovered,
+ then: request.then,
++ display_override: None,
+ });
+ Ok(token)
+ }
+
+ #[cfg(not(target_arch = "wasm32"))]
+ pub(crate) fn poll_pending_opens(&mut self) {
+ let pending_opens = std::mem::take(&mut self.pending_opens);
+ let mut remaining = pending_opens.into_iter();
+ let mut waiting = Vec::new();
+ while let Some(pending) = remaining.next() {
+ // A tool, password prompt or file picker belongs to the document just admitted.
+ // Keep later replies queued so another open cannot change its recipient.
+ if self.modal_open() || self.pickers.pending() {
+ waiting.push(pending);
+ waiting.extend(remaining);
+ break;
+ }
+ match pending.receiver.try_recv() {
+ Ok(result) if result.token == pending.token => self.finish_pending_open(pending, result.kind),
+ Ok(_) => waiting.push(pending),
+ Err(std::sync::mpsc::TryRecvError::Empty) => waiting.push(pending),
+ Err(std::sync::mpsc::TryRecvError::Disconnected) => {
+ self.notify_fmt("Couldn't open {name}: the background worker stopped", &[("name", &pending.name)]);
+ }
+ }
+ }
+ // A completion may schedule another open; preserve those requests as well as the
+ // earlier waiting replies, without consuming a blocked receiver's result.
+ waiting.append(&mut self.pending_opens);
+ self.pending_opens = waiting;
++ self.settle_launch_layout();
+ }
+
+ #[cfg(not(target_arch = "wasm32"))]
+ fn finish_pending_open(&mut self, pending: PendingOpen, kind: open_worker::ResultKind) {
+ match kind {
+ open_worker::ResultKind::ReadFailed(reason) => {
+ self.notify_fmt("Couldn't read {name}: {e}", &[("name", &pending.name), ("e", &reason)]);
+ }
+ open_worker::ResultKind::RemoteFailed(reason) => {
+ self.notify_fmt("Couldn't follow linked PDF: {reason}", &[("reason", &reason)]);
+ }
+ open_worker::ResultKind::RecoveryFailed(reason) => {
+ self.notify_fmt("Couldn't recover {name}: {e}", &[("name", &pending.name), ("e", &reason)]);
+ }
+ open_worker::ResultKind::Failed(reason) => {
+ self.notify_fmt("Couldn't open {name}: {reason}", &[("name", &pending.name), ("reason", &reason)]);
+ }
+ open_worker::ResultKind::Conversion(bytes) => match self.open_converted(&pending.name, &bytes) {
+ Some(Ok(())) => {
+ if let Some(command) = pending.then {
+ self.execute(command);
+ }
+ }
+ Some(Err(error)) => self.notify_fmt("Couldn't open {name}: {e}", &[("name", &pending.name), ("e", &error)]),
+ None => {}
+ },
+ open_worker::ResultKind::Prepared { bytes, result } => match *result {
+ Ok(prepared) => match self.finish_open(&pending.name, pending.path.clone(), bytes.len(), prepared, pending.activate) {
+ Ok(id) => {
+ if pending.path.is_some() {
+ self.watch.known_as(id, pending.stamp);
+ }
+ if let Some(destination) = pending.after_open {
+ self.apply_remote_destination(destination);
+ }
++ if let Some((layout, continuous)) = pending.display_override
++ && let Some(view) = self.views.iter_mut().find(|view| view.id == id)
++ {
++ view.set_display(layout, continuous);
++ self.launch_display_target = Some(id);
++ }
+ if let Some(meta) = &pending.recovered {
+ self.finish_recovery(meta);
+ }
+ if let Some(command) = pending.then {
+ self.execute(command);
+ }
+ }
+ Err(error) => self.notify_fmt("Couldn't open {name}: {e}", &[("name", &pending.name), ("e", &error)]),
+ },
+ Err(error @ (pdfcraft_render::OpenError::NeedsPassword | pdfcraft_render::OpenError::WrongPassword)) => {
+ let password_error =
+ matches!(error, pdfcraft_render::OpenError::WrongPassword).then(|| "Incorrect password. Try again.".to_string());
+ self.password_prompt = Some(PasswordPrompt {
+ name: pending.name,
+ path: pending.path,
+ bytes,
+ stamp: pending.stamp,
+ input: String::new(),
+ error: password_error,
+ activate: pending.activate,
+ recovered: pending.recovered,
+ then: pending.then,
+ after_open: pending.after_open,
++ display_override: pending.display_override,
+ });
+ }
+ Err(error) => self.notify_fmt("Couldn't open {name}: {e}", &[("name", &pending.name), ("e", &error.to_string())]),
+ },
+ }
+ }
+
+ fn try_open(
+ &mut self,
+ name: &str,
+ path: Option<String>,
+ bytes: std::sync::Arc<Vec<u8>>,
+ password: Option<&str>,
+ activate: bool,
+ ) -> Result<(), String> {
+ use pdfcraft_render::OpenError;
+ let prepared = match self.session.prepare_open(name, path.clone(), bytes.clone(), password) {
+ Ok(prepared) => prepared,
+ Err(e @ (OpenError::NeedsPassword | OpenError::WrongPassword)) => {
+ let error = matches!(e, OpenError::WrongPassword).then(|| "Incorrect password. Try again.".to_string());
+ #[cfg(not(target_arch = "wasm32"))]
+ let stamp = path.as_deref().and_then(file_watch::Stamp::at);
+ self.password_prompt = Some(PasswordPrompt {
+ name: name.to_string(),
+ path,
+ bytes,
+ #[cfg(not(target_arch = "wasm32"))]
+ stamp,
+ input: String::new(),
+ error,
+ activate,
+ recovered: None,
+ then: None,
+ after_open: None,
++ display_override: None,
+ });
+ return Ok(());
+ }
+ Err(e) => return Err(e.to_string()),
+ };
+ self.finish_open(name, path, bytes.len(), prepared, activate).map(|_| ())
+ }
+
+ fn finish_open(
+ &mut self,
+ name: &str,
+ path: Option<String>,
+ size: usize,
+ prepared: pdfcraft_engine::PreparedDocument,
+ activate: bool,
+ ) -> Result<DocId, String> {
+ let id = self.session.commit_open(prepared);
+ self.password_prompt = None;
+ // The reading-colours preference is app-wide: a newly opened document starts with it.
+ // Idempotent: the engine returns `false` when the document has the setting already.
+ self.session.set_reading_colors(id, self.reading_colors);
+ let doc = self.session.get(id).ok_or("the document could not be opened")?;
+ let pages = doc.info.pages.len();
+ // Acrobat opens straight to the Comments panel when a document has comments.
+ // Read mode opens with the panes closed; the rail still opens them (#932). A right panel
+ // the user closed stays closed (#1590).
+ let opening_mode = self.mode_override.unwrap_or(self.default_mode);
+ let initial = doc.initial_view();
+ if activate && self.right.is_none() && !self.right_panel_closed && opening_mode != Mode::Read {
+ self.right = if !doc.info.annotations.is_empty() {
+ Some(RightPanel::Comments)
+ // A full-screen document names its panel for outside full screen, and with
+ // `/NonFullScreenPageMode /UseNone` (the default) no outline is visible (Table 147).
+ } else if !doc.info.outline.is_empty() && !initial.full_screen {
+ Some(RightPanel::Bookmarks)
+ } else {
+ None
+ };
+ }
+ let view = DocView::new(id, &doc.info, self.view_defaults);
+ self.views.push(view);
+ if activate {
+ self.active = Some(self.views.len() - 1);
+ }
+ self.apply_initial_view(self.views.len() - 1, &initial);
+ // Where the reader left off wins over the file's own initial view (#1767).
+ self.apply_last_view(self.views.len() - 1);
+ // After both, so full screen shows one fitted page and leaving it comes back to them.
+ if self.full_screen
+ && let Some(view) = self.views.last_mut()
+ {
+ view.enter_presentation();
+ }
+ // Full screen is asked for, never taken: a document can't put the app in full screen on
+ // its own (the prompt is `dialogs::full_screen_prompt`).
+ if activate && initial.full_screen {
+ self.pending_full_screen = Some(id);
+ }
+ if activate
+ && self.left_open
+ && self.left == LeftPanel::Tool("organize")
+ && let Some(view) = self.views.last_mut()
+ {
+ view.open_organize();
+ }
+ // The document shows, not the expanded All tools view over it (whichever workspace opens).
+ if activate {
+ self.all_tools_full = false;
+ }
+ if activate && let Some(mode) = self.mode_override {
+ // Explicit mode options do not reset independent --tool / --left choices.
+ self.mode = mode;
+ } else if activate && self.mode != self.default_mode {
+ // Switch workspace like the mode bar, but a left panel the user (or `--left closed`)
+ // closed stays closed, and an unchanged mode keeps the tool panel the user chose.
+ let left_open = self.left_open;
+ self.select_mode(self.default_mode);
+ self.left_open = left_open;
+ }
+ if let Some(p) = path {
+ #[cfg(target_os = "macos")]
+ macos_association::repair(std::path::Path::new(&p));
+ self.recent.retain(|r| r.path != p);
+ self.recent.insert(0, RecentFile { name: name.to_string(), path: p, pages, size });
+ self.recent.truncate(12);
+ }
+ // What the form's scripts said while it opened (messages, errors) shows now, not with
+ // the next edit.
+ // Background documents keep their script output until their tab is selected: a print
+ // or save request must never act on the current document instead.
+ if activate {
+ let out = self.session.take_js_output(id);
+ self.handle_js(id, out);
+ }
+ Ok(id)
+ }
+
+ /// Edit ▸ Attach a file…: choose a file, then attach it to the active document and show
+ /// the Attachments panel with it.
+ pub fn attach_file_dialog(&mut self) {
+ if self.active_ids().is_none() {
+ return;
+ }
+ #[cfg(not(target_arch = "wasm32"))]
+ {
+ let dialog = rfd::AsyncFileDialog::new().set_title(tl!("Attach a file").to_string());
+ let target = self.active_ids().map(|(_, id)| id);
+ self.ask_one(pickers::Ask::File(dialog), target, |app, path| app.attach_file(&path));
+ }
+ #[cfg(target_arch = "wasm32")]
+ self.notify_tr("Attaching files is not available on the web yet");
+ }
+
+ /// Attach the file at `path` to the active document (document level: the Attachments
+ /// panel, not a paper-clip comment on a page).
+ pub fn attach_file(&mut self, path: &std::path::Path) {
+ let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
+ let bytes = match std::fs::read(path) {
+ Ok(b) => b,
+ Err(e) => {
+ self.notify_fmt("Couldn't read {name}: {e}", &[("name", &name), ("e", &e.to_string())]);
+ return;
+ }
+ };
+ let mime = pdfcraft_engine::mime_for_name(&name).map(str::to_string);
+ if self.apply_edit(pdfcraft_engine::Edit::AddAttachment { name, bytes, description: None, mime }) {
+ self.choose_right_panel(Some(RightPanel::Attachments));
+ }
+ }
+
+ /// Save an attachment to disk, or open a PDF attachment in a new tab.
+ pub fn attachment_action(&mut self, doc: DocId, index: usize, open: bool) {
+ let Some(d) = self.session.get(doc) else { return };
+ let Some(att) = d.info.attachments.get(index).cloned() else { return };
+ let data = pdfcraft_render::attachment_data(&d.bytes, d.password.as_deref(), &att);
+ match (data, open) {
+ (Err(e), _) => self.notify_fmt("Couldn't read {name}: {e}", &[("name", &att.name), ("e", &e.to_string())]),
+ (Ok(bytes), true) => {
+ // The tab name later names files written from the tab (Split, Extract pages).
+ if let Err(e) = self.open_bytes(&crate::files::attachment_file_name(&att.name), None, bytes) {
+ self.notify_fmt("Couldn't open {name}: {e}", &[("name", &att.name), ("e", &e.to_string())]);
+ }
+ }
+ (Ok(bytes), false) => {
+ #[cfg(not(target_arch = "wasm32"))]
+ self.ask_one(
+ pickers::Ask::Save(rfd::AsyncFileDialog::new().set_file_name(crate::files::attachment_file_name(&att.name))),
+ None,
+ move |app, path| match crate::editing::write_atomically(&path.to_string_lossy(), &bytes) {
+ Ok(()) => app.notify_fmt("Saved {name}", &[("name", &path.display().to_string())]),
+ Err(e) => app.notify_fmt("Couldn't save: {e}", &[("e", &e.to_string())]),
+ },
+ );
+ #[cfg(target_arch = "wasm32")]
+ self.notify_fmt("Downloading attachments on the web arrives with M3.10 ({n} bytes ready)", &[("n", &bytes.len().to_string())]);
+ }
+ }
+ }
+
+ /// [`Self::attachment_action`] for the file of the attachment comment at (page, index).
+ pub fn comment_attachment_action(&mut self, doc: DocId, page: usize, index: usize, open: bool) {
+ let source = pdfcraft_render::AttachmentSource::Annotation { page, index };
+ // The menus offer the items only for a listed file, so a miss is a comment gone since.
+ if let Some(i) = self.session.get(doc).and_then(|d| d.info.attachments.iter().position(|a| a.source == source)) {
+ self.attachment_action(doc, i, open);
+ }
+ }
+
+ /// Answer the password prompt (`None` cancels).
+ pub fn submit_password(&mut self, password: Option<String>) {
+ let Some(p) = self.password_prompt.take() else { return };
+ let Some(pw) = password else {
+ // A cancelled recovery goes back on offer; its snapshot stays in the store and must
+ // not attach itself to whatever document is unlocked next (#813).
+ if let Some(meta) = p.recovered {
+ self.recoverable.push(meta);
+ }
++ #[cfg(not(target_arch = "wasm32"))]
++ self.settle_launch_layout();
+ return;
+ };
+ #[cfg(not(target_arch = "wasm32"))]
+ if self.ctx.is_some() && !self.run_inline {
+ let result = self.schedule_open(OpenRequest {
+ name: p.name.clone(),
+ path: p.path.clone(),
+ stamp: p.stamp,
+ input: open_worker::Input::Bytes(p.bytes.clone()),
+ password: Some(pw),
+ activate: p.activate,
+ after_open: p.after_open.clone(),
+ recovered: p.recovered.clone(),
+ then: p.then,
+ });
++ if let Ok(token) = &result
++ && let Some(pending) = self.pending_opens.iter_mut().find(|pending| pending.token == *token)
++ {
++ pending.display_override = p.display_override;
++ }
+ if let Err(error) = result {
+ let mut prompt = p;
+ prompt.error = Some(error);
+ self.password_prompt = Some(prompt);
+ }
+ return;
+ }
+ #[cfg(not(target_arch = "wasm32"))]
+ let (path_for_watch, stamp_for_watch) = (p.path.clone(), p.stamp);
+ let after_open = p.after_open.clone();
+ match self.try_open(&p.name, p.path, p.bytes, Some(&pw), p.activate) {
+ Err(e) => self.notify_fmt("Couldn't open {name}: {e}", &[("name", &p.name), ("e", &e.to_string())]),
+ // A recovered encrypted document is open once its prompt is gone.
+ Ok(()) if self.password_prompt.is_none() => {
+ #[cfg(not(target_arch = "wasm32"))]
+ if let Some(path) = path_for_watch.as_deref()
+ && let Some(id) = self
+ .views
+ .iter()
+ .rev()
+ .find_map(|view| self.session.get(view.id).and_then(|doc| (doc.path.as_deref() == Some(path)).then_some(view.id)))
+ {
+ self.watch.known_as(id, stamp_for_watch);
+ }
+ if let Some(destination) = after_open {
+ self.apply_remote_destination(destination);
+ }
++ if let Some((layout, continuous)) = p.display_override
++ && let Some(view) = self.views.last_mut()
++ {
++ view.set_display(layout, continuous);
++ #[cfg(not(target_arch = "wasm32"))]
++ {
++ self.launch_display_target = Some(view.id);
++ }
++ }
+ if let Some(meta) = &p.recovered {
+ self.finish_recovery(meta);
+ }
+ if let Some(command) = p.then {
+ self.execute(command);
+ }
+ }
+ // Wrong password: the new prompt is for the same bytes, so it keeps the snapshot
+ // and the tool waiting for it.
+ Ok(()) => {
+ if let Some(prompt) = self.password_prompt.as_mut() {
+ prompt.recovered = p.recovered;
+ prompt.then = p.then;
+ prompt.after_open = after_open;
++ prompt.display_override = p.display_override;
+ }
+ }
+ }
++ #[cfg(not(target_arch = "wasm32"))]
++ self.settle_launch_layout();
+ }
+
+ /// Ask for the active document's permissions password, then run `then` (if any).
+ pub(crate) fn request_unlock(&mut self, then: Option<&'static str>) {
+ let Some(doc) = self.active_ids().and_then(|(_, id)| self.session.get(id)) else { return };
+ self.unlock_prompt = Some(UnlockPrompt::new(doc, then));
+ }
+
+ /// Answer the permissions password prompt (`None` cancels).
+ pub fn submit_unlock(&mut self, password: Option<String>) {
+ let Some(mut p) = self.unlock_prompt.take() else { return };
+ let Some(pw) = password else { return };
+ match self.session.unlock(p.doc, &pw) {
+ // Carry on with what asked for the password, if its document is still the one shown.
+ Ok(()) => match p.then {
+ Some(command) if self.active_ids().is_some_and(|(_, id)| id == p.doc) => {
+ self.execute(command);
+ }
+ _ => self.notify_tr("Restrictions lifted"),
+ },
+ Err(pdfcraft_engine::EditError::WrongPassword) => {
+ p.input.clear();
+ p.error = Some("Incorrect password. Try again.".to_string());
+ self.unlock_prompt = Some(p);
+ }
+ Err(e) => self.notify_fmt("Couldn't unlock {name}: {e}", &[("name", &p.name), ("e", &e.to_string())]),
+ }
+ }
+
+ /// The tab already showing the file at `path` (the same path, or one that names the same
+ /// file once made absolute).
+ pub(crate) fn tab_showing(&self, path: &str) -> Option<usize> {
+ self.views.iter().position(|v| self.session.get(v.id).and_then(|d| d.path.as_deref()).is_some_and(|p| same_file(p, path)))
+ }
+
+ /// Open a file from a recent list: focus the tab already showing it, else open it (File ▸
+ /// Open Recent and the Home view's list share this).
+ pub fn open_recent(&mut self, path: &str) {
+ if let Some(i) = self.tab_showing(path) {
+ self.active = Some(i);
+ } else {
+ #[cfg(not(target_arch = "wasm32"))]
+ self.open_path(path);
+ }
+ #[cfg(target_arch = "wasm32")]
+ let _ = path;
+ }
+
+ #[cfg(not(target_arch = "wasm32"))]
+ pub fn open_path(&mut self, path: &str) -> OpenOutcome {
+ self.open_path_then(path, None)
+ }
+
+ /// Keep a chosen tool with its file until preparation and any password entry finish. The
+ /// return value is the programmatic open contract (#1620): callers that must know whether
+ /// the file opened, focused its tab, was handed to the background worker, or failed.
+ #[cfg(not(target_arch = "wasm32"))]
+ pub(crate) fn open_path_then(&mut self, path: &str, then: Option<&'static str>) -> OpenOutcome {
++ self.open_path_request(path, then, None)
++ }
++
++ #[cfg(not(target_arch = "wasm32"))]
++ fn open_path_request(&mut self, path: &str, then: Option<&'static str>, display_override: Option<(canvas::PageLayout, bool)>) -> OpenOutcome {
+ // One file, one tab (#2166): a file that is open already comes to the front instead,
+ // and the tool it was opened for runs on it. One still being opened is left to that.
+ if let Some(i) = self.tab_showing(path) {
+ self.startup_superseded = true;
+ self.active = Some(i);
++ if let Some((layout, continuous)) = display_override
++ && let Some(view) = self.views.get_mut(i)
++ {
++ view.set_display(layout, continuous);
++ self.launch_display_target = Some(view.id);
++ }
+ if let Some(command) = then {
+ self.execute(command);
+ }
+ return OpenOutcome::Focused;
+ }
- if self.pending_opens.iter().any(|p| p.path.as_deref().is_some_and(|p| same_file(p, path))) {
++ if let Some(pending) = self.pending_opens.iter_mut().find(|p| p.path.as_deref().is_some_and(|p| same_file(p, path))) {
++ if display_override.is_some() {
++ pending.display_override = display_override;
++ }
++ return OpenOutcome::Pending;
++ }
++ if display_override.is_some()
++ && let Some(prompt) = self.password_prompt.as_mut().filter(|p| p.path.as_deref().is_some_and(|p| same_file(p, path)))
++ {
++ prompt.display_override = display_override;
+ return OpenOutcome::Pending;
+ }
+ let name = std::path::Path::new(path).file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| path.to_string());
+ // Taken before reading: a build that rewrites the file meanwhile still counts as a change.
+ let stamp = file_watch::Stamp::at(path);
+ // Before the first frame there is no interaction to keep responsive; this also preserves
+ // deterministic inline startup and test flows. Once live, reading and preparation use
+ // the bounded worker and commit on the UI thread.
- if self.ctx.is_none() || self.run_inline {
++ // Keep flagged launch files behind an existing password prompt or picker.
++ if (self.ctx.is_none() || self.run_inline) && !(display_override.is_some() && (self.modal_open() || self.pickers.pending())) {
+ match std::fs::read(path) {
+ Ok(bytes) => {
+ let before = self.views.len();
++ let previous_prompt = self.password_prompt.as_ref().map(|p| p.bytes.clone());
+ if let Err(error) = self.open_bytes(&name, Some(path.to_string()), bytes) {
+ self.notify_fmt("Couldn't open {name}: {e}", &[("name", &name), ("e", &error)]);
+ return OpenOutcome::Failed;
+ }
- if let Some(prompt) = self.password_prompt.as_mut().filter(|p| p.path.as_deref() == Some(path)) {
++ if let Some(prompt) = self.password_prompt.as_mut().filter(|p| {
++ p.path.as_deref() == Some(path) && previous_prompt.as_ref().is_none_or(|bytes| !std::sync::Arc::ptr_eq(bytes, &p.bytes))
++ }) {
+ // Encrypted: the tool runs once the password is in.
+ prompt.then = then;
++ prompt.display_override = display_override;
+ } else if self.views.len() > before {
++ if let Some((layout, continuous)) = display_override
++ && let Some(view) = self.views.last_mut()
++ {
++ view.set_display(layout, continuous);
++ self.launch_display_target = Some(view.id);
++ }
+ if let Some(doc) = self.views.last().map(|view| view.id) {
+ self.watch.known_as(doc, stamp);
+ }
+ if let Some(command) = then {
+ self.execute(command);
+ }
+ } else {
+ // Open reported success but added no tab and raised no prompt; the
+ // control channel answers this as a failure to open.
+ return OpenOutcome::Failed;
+ }
+ OpenOutcome::Opened
+ }
+ Err(error) => {
+ self.notify_fmt("Couldn't read {name}: {e}", &[("name", &name), ("e", &error.to_string())]);
+ OpenOutcome::Failed
+ }
+ }
+ } else {
+ self.startup_superseded = true;
+ match self.schedule_open(OpenRequest {
+ name: name.clone(),
+ path: Some(path.to_string()),
+ stamp,
+ input: open_worker::Input::Path(std::path::PathBuf::from(path)),
+ password: None,
+ activate: true,
+ after_open: None,
+ recovered: None,
+ then,
+ }) {
- Ok(_) => OpenOutcome::Pending,
++ Ok(token) => {
++ if let Some(pending) = self.pending_opens.iter_mut().find(|pending| pending.token == token) {
++ pending.display_override = display_override;
++ }
++ OpenOutcome::Pending
++ }
+ Err(error) => {
+ self.notify_fmt("Couldn't open {name}: {e}", &[("name", &name), ("e", &error)]);
+ OpenOutcome::Failed
+ }
+ }
+ }
+ }
+
++ /// Apply an explicit launch layout after the command-line display overrides settle.
++ #[cfg(not(target_arch = "wasm32"))]
++ pub fn set_launch_layout(&mut self, value: &str) -> Result<(), String> {
++ let (layout, continuous) = canvas::parse_display_token(value).ok_or("layout must be single, continuous, two-up or two-page")?;
++ self.launch_layout = Some((layout, continuous));
++ self.settle_launch_layout();
++ Ok(())
++ }
++
++ #[cfg(not(target_arch = "wasm32"))]
++ fn settle_launch_layout(&mut self) {
++ if self.pending_opens.iter().any(|open| open.display_override.is_some())
++ || self.password_prompt.as_ref().is_some_and(|prompt| prompt.display_override.is_some())
++ {
++ return;
++ }
++ // Follow the existing completion/activation order, not a guessed tab index or path.
++ // Failed or cancelled opens cannot cause the layout to land on a restored document.
++ if let Some((layout, continuous)) = self.launch_layout.take()
++ && let Some(id) = self.launch_display_target
++ && let Some(view) = self.views.iter_mut().find(|view| view.id == id)
++ {
++ view.set_display(layout, continuous);
++ }
++ }
++
++ /// Open one native file with a transient display override, including after a password prompt.
++ #[cfg(not(target_arch = "wasm32"))]
++ pub fn open_path_with_display(&mut self, path: &str, layout: canvas::PageLayout, continuous: bool) {
++ self.open_path_request(path, None, Some((layout, continuous)));
++ }
++
+ /// The File ▸ Open picker: PDFs, and images and text that become PDFs.
+ #[cfg(not(target_arch = "wasm32"))]
+ pub(super) fn open_picker() -> rfd::AsyncFileDialog {
+ rfd::AsyncFileDialog::new().add_filter("PDF", &["pdf"]).add_filter(tl!("Images and text (converted to PDF)"), &create_ui::CONVERTIBLE)
+ }
+
+ pub fn open_dialog(&mut self) {
+ self.startup_superseded = true;
+ #[cfg(not(target_arch = "wasm32"))]
+ self.pick(
+ pickers::PickFor::Open,
+ rfd::AsyncFileDialog::new().add_filter("PDF", &["pdf"]).add_filter(tl!("Images and text (converted to PDF)"), &create_ui::CONVERTIBLE),
+ true,
+ );
+ // Browsers pick files asynchronously; the bytes arrive through `inbox`.
+ #[cfg(target_arch = "wasm32")]
+ {
+ let inbox = self.inbox.clone();
+ let ctx = self.ctx.clone();
+ wasm_bindgen_futures::spawn_local(async move {
+ if let Some(h) = rfd::AsyncFileDialog::new()
+ .add_filter("PDF", &["pdf"])
+ .add_filter(tl!("Images and text"), &create_ui::CONVERTIBLE)
+ .pick_file()
+ .await
+ {
+ let bytes = h.read().await;
+ if let Ok(mut q) = inbox.lock() {
+ q.push((h.file_name(), bytes));
+ }
+ // The read may finish while the app is idle: wake it to open the file.
+ if let Some(ctx) = ctx {
+ ctx.request_repaint();
+ }
+ }
+ });
+ }
+ }
+
+ pub fn close_tab(&mut self, index: usize) {
+ if index >= self.views.len() {
+ return;
+ }
+ self.remember_view(index);
+ let id = self.views.remove(index).id;
+ #[cfg(not(target_arch = "wasm32"))]
+ if let Some(path) = self.session.get(id).and_then(|d| d.path.clone()) {
+ if self.closed_tabs.len() == 10 {
+ self.closed_tabs.remove(0);
+ }
+ self.closed_tabs.push(path);
+ }
+ self.forget_recovery(id);
+ self.session.close(id);
+ self.active = match self.active {
+ _ if self.views.is_empty() => None,
+ Some(a) if a > index => Some(a - 1),
+ Some(a) if a >= self.views.len() => Some(self.views.len() - 1),
+ other => other,
+ };
+ }
+
+ /// Moves the tab at `from` so it sits at `to` (#1537). The same document stays active
+ /// wherever it lands; an index out of range changes nothing.
+ pub fn move_tab(&mut self, from: usize, to: usize) {
+ if from >= self.views.len() || to >= self.views.len() || from == to {
+ return;
+ }
+ let active = self.active_ids().map(|(_, id)| id);
+ let view = self.views.remove(from);
+ self.views.insert(to, view);
+ if let Some(id) = active {
+ self.active = self.views.iter().position(|v| v.id == id);
+ }
+ }
+ }
diff --cc crates/ui-egui/src/lib.rs
index 166b2b392,222bb988e..4f2a87660
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@@ -445,50 -239,11 +239,12 @@@ struct PendingOpen
after_open: Option<pdfcraft_render::RemoteDestination>,
recovered: Option<RecoveryMeta>,
then: Option<&'static str>,
+ display_override: Option<(canvas::PageLayout, bool)>,
}
- #[cfg(not(target_arch = "wasm32"))]
- struct OpenRequest {
- name: String,
- path: Option<String>,
- stamp: Option<file_watch::Stamp>,
- input: open_worker::Input,
- password: Option<String>,
- activate: bool,
- after_open: Option<pdfcraft_render::RemoteDestination>,
- recovered: Option<RecoveryMeta>,
- then: Option<&'static str>,
- }
-
- /// Asks for the permissions password of an open document whose security restricts it, which
- /// lifts the restrictions (#995). Acrobat asks for it when such a document's security is changed.
- pub struct UnlockPrompt {
- pub doc: DocId,
- pub name: String,
- pub input: String,
- pub error: Option<String>,
- /// The command to run once unlocked (Protect using password, Remove security), if any.
- pub then: Option<&'static str>,
- }
-
- impl UnlockPrompt {
- pub(crate) fn new(doc: &pdfcraft_engine::Document, then: Option<&'static str>) -> Self {
- Self { doc: doc.id, name: doc.name.clone(), input: String::new(), error: None, then }
- }
- }
-
- #[derive(serde::Serialize, serde::Deserialize)]
- pub struct RecentFile {
- pub name: String,
- pub path: String,
- pub pages: usize,
- pub size: usize,
- }
-
pub struct PdfCraftApp {
- pub docking: docking::Workspace,
- pub(crate) pending_panel_reveals: Vec<docking::Panel>,
+ /// Tools side and pane widths; which panes are open is `left_open` and `right`.
+ pub side_panels: side_panels::SidePanels,
pub session: Session,
pub views: Vec<DocView>,
pub(crate) closed_tabs: Vec<String>,
diff --cc crates/ui-egui/src/platform/open_worker/tests.rs
index b7037bd6b,fe2a0ae41..c0fe2f03a
--- a/crates/ui-egui/src/platform/open_worker/tests.rs
+++ b/crates/ui-egui/src/platform/open_worker/tests.rs
@@@ -671,142 -733,34 +733,174 @@@ fn startup_files_wait_for_absolute_link
let _ = std::fs::remove_file(path);
}
+#[test]
+fn launch_layout_waits_for_cli_opens_and_preserves_restored_tabs() {
+ use crate::canvas::PageLayout;
+ // Controlled worker replies exercise both completion orders without scheduling races.
+ for reverse in [false, true] {
+ for count in [1, 2] {
+ for restored in [false, true] {
+ let mut app = PdfCraftApp::new();
+ app.set_option("default-layout", "continuous").unwrap();
+ if restored {
+ app.open_bytes("restored.pdf", None, fixture(1)).unwrap();
+ }
+ let offset = usize::from(restored);
+ let mut replies = Vec::new();
+ for token in 0..count {
+ let name = format!("cli-{token}.pdf");
+ let bytes = Arc::new(fixture(2));
+ let prepared = app.session.prepare_open(&name, None, bytes.clone(), None);
+ let (sender, receiver) = std::sync::mpsc::channel();
+ app.pending_opens.push(crate::PendingOpen {
+ token,
+ receiver,
+ name,
+ path: None,
+ stamp: None,
+ activate: true,
+ after_open: None,
+ recovered: None,
+ then: None,
+ display_override: Some((PageLayout::TwoUp, false)),
+ });
+ replies.push((
+ sender,
+ open_worker::ResultMessage { token, kind: open_worker::ResultKind::Prepared { bytes, result: Box::new(prepared) } },
+ ));
+ }
+ app.set_launch_layout("single").unwrap();
+ if restored {
+ assert!(app.views[0].continuous(), "pending --layout must not target the restored tab");
+ }
+ if reverse {
+ replies.reverse();
+ }
+ for (index, (sender, reply)) in replies.into_iter().enumerate() {
+ let name = format!("cli-{}.pdf", reply.token);
+ sender.send(reply).unwrap();
+ app.poll_pending_opens();
+ let view = &app.views[index + offset];
+ assert_eq!(view.layout, if index + 1 == count as usize { PageLayout::Single } else { PageLayout::TwoUp });
+ assert!(!view.continuous());
+ assert_eq!(app.session.get(view.id).unwrap().name, name);
+ }
+ assert_eq!(app.active, Some(count as usize + offset - 1));
+ if restored {
+ assert_eq!(app.views[0].layout, PageLayout::Single);
+ assert!(app.views[0].continuous());
+ }
+ assert_eq!(app.view_defaults.layout, PageLayout::Single);
+ assert!(app.view_defaults.continuous);
+ assert_eq!(serde_json::from_str::<Value>(&app.persist()).unwrap()["default_layout"], "continuous");
+ // Ordinary later opens cannot inherit either launch override.
+ app.open_bytes("later.pdf", None, fixture(1)).unwrap();
+ assert!(app.views.last().unwrap().continuous());
+ }
+ }
+ }
+}
+
+#[test]
+fn launch_layout_failed_or_cancelled_opens_do_not_target_existing_documents() {
+ use crate::canvas::PageLayout;
+ for cancel in [false, true] {
+ let mut app = PdfCraftApp::new();
+ app.set_option("default-layout", "continuous").unwrap();
+ app.open_bytes("restored.pdf", None, fixture(1)).unwrap();
+ let (sender, receiver) = std::sync::mpsc::channel();
+ app.pending_opens.push(crate::PendingOpen {
+ token: 0,
+ receiver,
+ name: "cli.pdf".into(),
+ path: None,
+ stamp: None,
+ activate: true,
+ after_open: None,
+ recovered: None,
+ then: None,
+ display_override: Some((PageLayout::TwoUp, false)),
+ });
+ app.set_launch_layout("single").unwrap();
+ assert!(app.set_launch_layout("invalid").is_err());
+ let kind = if cancel {
+ open_worker::ResultKind::Prepared { bytes: Arc::new(fixture(1)), result: Box::new(Err(pdfcraft_render::OpenError::NeedsPassword)) }
+ } else {
+ open_worker::ResultKind::ReadFailed("synthetic read failure".into())
+ };
+ sender.send(open_worker::ResultMessage { token: 0, kind }).unwrap();
+ app.poll_pending_opens();
+ if cancel {
+ app.submit_password(None);
+ }
+ assert!(app.launch_layout.is_none());
+ assert_eq!(app.views.len(), 1);
+ assert!(app.views[0].continuous());
+ app.open_bytes("later.pdf", None, fixture(1)).unwrap();
+ assert!(app.views[1].continuous());
+ }
+}
+
+#[test]
+fn flagged_startup_opens_wait_for_password_ownership_before_the_first_frame() {
+ use crate::canvas::PageLayout;
+ let locked = tool_open_file("launch-locked", "pdf", &encrypted_tool_fixture());
+ let second = tool_open_file("launch-second", "pdf", &fixture(2));
+ let mut app = PdfCraftApp::new();
+ app.set_option("default-layout", "continuous").unwrap();
+ app.open_path_with_display(locked.0.to_str().unwrap(), PageLayout::TwoUp, false);
+ let bytes = app.password_prompt.as_ref().unwrap().bytes.clone();
+ app.open_path_with_display(locked.0.to_str().unwrap(), PageLayout::TwoUp, false);
+ assert!(app.pending_opens.is_empty(), "repeating the locked file keeps its original prompt");
+ app.open_path_with_display(second.0.to_str().unwrap(), PageLayout::TwoUp, false);
+ assert_eq!(app.pending_opens.len(), 1);
+ assert!(Arc::ptr_eq(&app.password_prompt.as_ref().unwrap().bytes, &bytes));
+ app.set_launch_layout("single").unwrap();
+ app.submit_password(Some("wrong".into()));
+ assert!(app.password_prompt.as_ref().unwrap().error.is_some());
+ app.submit_password(Some("tool-password".into()));
+ assert_eq!(app.views.len(), 1);
+ assert_eq!(app.views[0].layout, PageLayout::TwoUp);
+ let deadline = std::time::Instant::now() + Duration::from_secs(5);
+ while !app.pending_opens.is_empty() {
+ assert!(std::time::Instant::now() < deadline);
+ app.poll_pending_opens();
+ std::thread::sleep(Duration::from_millis(5));
+ }
+ assert_eq!(app.views.len(), 2);
+ assert_eq!(app.views[1].layout, PageLayout::Single);
+ assert!(!app.views[1].continuous());
+ assert!(app.view_defaults.continuous);
+}
++
+ /// #1928: a new file handed over by the OS (Finder, or another launch) raises the window at once,
+ /// before it is prepared, and is the selected tab once it opens.
+ #[test]
+ #[allow(clippy::expect_used, clippy::panic, clippy::unwrap_used)]
+ fn a_new_file_from_the_os_brings_the_window_forward_before_it_is_prepared() {
+ let (mut harness, _client) = harness();
+ let (gate, started, release, finished) = open_worker::prepare_gate();
+ harness.state_mut().open_prepare_gate = Some(gate);
+ let path = std::env::temp_dir().join(format!("pdfcraft-os-open-worker-{}.pdf", std::process::id()));
+ std::fs::write(&path, fixture(2)).expect("write the handed-over PDF");
+ let mut queue = vec![crate::OsEvent::Open(vec![path.to_string_lossy().into_owned()])];
+ harness.state_mut().os_events = Some(Box::new(move || std::mem::take(&mut queue)));
+ harness.step();
+ started.recv_timeout(Duration::from_secs(5)).expect("the handed-over PDF reached preparation");
+ let commands: Vec<_> = harness.output().viewport_output.values().flat_map(|v| v.commands.clone()).collect();
+ let visible = harness.state().views.len();
+ // Always release before asserting: a failure must not strand the worker at the barrier.
+ release.send(()).expect("release the handed-over PDF");
+ finished.recv_timeout(Duration::from_secs(5)).expect("the handed-over PDF prepared");
+ assert!(commands.contains(&egui::ViewportCommand::Minimized(false)), "{commands:?}");
+ assert!(commands.contains(&egui::ViewportCommand::Focus), "{commands:?}");
+ assert_eq!(visible, 1, "the window comes forward while the file is still preparing");
+ harness.step();
+ let app = harness.state();
+ assert_eq!(app.views.len(), 2);
+ let active = app.active.expect("a selected document");
+ let doc = app.session.get(app.views[active].id).expect("the handed-over document");
+ assert_eq!(doc.path.as_deref(), Some(path.to_string_lossy().as_ref()), "the new file is the selected tab");
+ assert_eq!(doc.info.pages.len(), 2);
+ let _ = std::fs::remove_file(path);
+ }
diff --cc crates/ui-egui/src/state.rs
index 000000000,03df25f20..9cfc2fd24
mode 000000,100644..100644
--- a/crates/ui-egui/src/state.rs
+++ b/crates/ui-egui/src/state.rs
@@@ -1,0 -1,433 +1,435 @@@
+ use super::*;
+
+ /// Top-level workspace modes (Acrobat's mode bar).
+ #[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
+ #[serde(rename_all = "lowercase")]
+ pub enum Mode {
+ #[serde(rename = "all")]
+ AllTools,
+ Read,
+ Edit,
+ Convert,
+ Sign,
+ }
+
+ impl Mode {
+ pub(crate) fn parse(value: &str) -> Option<Self> {
+ match value {
+ "all" => Some(Self::AllTools),
+ "read" => Some(Self::Read),
+ "edit" => Some(Self::Edit),
+ "convert" => Some(Self::Convert),
+ "sign" => Some(Self::Sign),
+ _ => None,
+ }
+ }
+ }
+
+ /// What the left panel shows.
+ #[derive(Clone, Copy, Debug, PartialEq, Eq)]
+ pub enum LeftPanel {
+ AllTools,
+ Tool(&'static str),
+ /// Prepare a form ▸ Calculation order, a page of its own; Back returns to Prepare a form.
+ CalculationOrder,
+ }
+
+ /// Right-hand panels, opened from the rail.
+ #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
+ pub enum RightPanel {
+ Comments,
+ Bookmarks,
+ Pages,
+ Fields,
+ Layers,
+ Attachments,
+ Signatures,
+ /// Accessibility Checker results.
+ Accessibility,
+ /// Reachable PDF structure tags and their properties.
+ Tags,
+ /// Advanced Search results.
+ Search,
+ /// Compare files: the differences.
+ Compare,
+ }
+
+ /// Quick-action bar tools (the vertical floating strip).
+ #[derive(Clone, Copy, Debug, PartialEq, Eq)]
+ pub enum QuickTool {
+ Select,
+ Hand,
+ /// A commenting tool (Add comments).
+ Comment(comments::CommentTool),
+ Measure(measure_ui::Tool),
+ /// Crop pages by dragging a rectangle.
+ Crop,
+ /// Scan & OCR ▸ Enhance ▸ Camera image: drag four corners, then Enhance page.
+ EnhanceCamera,
+ /// A Fill & Sign tool.
+ Fill(fill_sign::FillTool),
+ /// A Prepare a form field tool.
+ Field(prepare::FieldTool),
+ /// Redact text and images (drag across text or draw a box).
+ Redact,
+ /// Edit a PDF ▸ Add content ▸ Text.
+ AddText,
+ /// Edit a PDF ▸ Edit text: click a line of existing text to edit it.
+ EditText,
+ /// Add a stamp: click to place this stamp.
+ Stamp(pdfcraft_engine::StampKind),
+ /// A custom stamp from the library (its index).
+ CustomStamp(usize),
+ /// Edit a PDF ▸ Link: draw link areas, select and edit links.
+ Link,
+ /// Use a certificate ▸ Digitally sign / Certify (visible): drag the signature's rectangle.
+ SignArea {
+ certify: bool,
+ },
+ /// View ▸ Zoom ▸ Marquee Zoom.
+ MarqueeZoom,
+ /// Edit ▸ Take a Snapshot.
+ Snapshot,
+ /// Edit ▸ Column Select: drag a rectangle to select only the text inside it (#740). The
+ /// Select tool does the same while Alt/Option is held at the start of a drag.
+ ColumnSelect,
+ }
+
+ /// A file dropped on a page grid: its name, and its bytes or, for a file on disk, the path they are
+ /// read from when the file's turn to be inserted comes (so a long drop holds one file at a time).
+ pub(crate) type GridFile = (String, Result<Vec<u8>, std::path::PathBuf>);
+
+ #[derive(Clone, Copy, Debug, PartialEq, Eq)]
+ pub enum Dialog {
+ WordCount,
+ CreateImages,
+ Properties(PropsTab),
+ About,
+ Shortcuts,
+ Split,
+ /// Pages ▸ Number pages… (page labels).
+ NumberPages,
+ /// Organize pages ▸ Page properties (the tab order of the selected pages).
+ PageProps,
+ /// Protect Using Password.
+ Protect,
+ /// Bookmarks ▸ New bookmarks from text styles (#1693).
+ BookmarksFromTextStyles,
+ /// Set Page Boxes (crop, trim, bleed, art, media).
+ PageBoxes,
+ /// Add / Update Header and Footer, Watermark, Background.
+ Marks(pdfcraft_engine::MarkKind),
+ /// Export a PDF ▸ Image / Text.
+ Export(export_ui::ExportKind),
+ /// Fill & Sign ▸ Create signature (the drawing pad).
+ Signature,
+ /// Comment Properties.
+ CommentProps,
+ /// Replace Pages (after choosing the file).
+ ReplacePages,
+ /// Prepare a form ▸ Field Properties.
+ FieldProps,
+ /// Shared properties of several selected form fields.
+ BulkFieldProps,
+ /// Redact a PDF ▸ Redact pages, Find text and redact, Set properties, apply confirmation.
+ RedactPages,
+ RedactSearch,
+ RedactProps,
+ RedactApply,
+ /// File ▸ Print.
+ Print,
+ /// File ▸ Revert confirmation.
+ Revert,
+ /// Save over a file that changed on disk since the document came from it (#2166).
+ OverwriteChanged,
+ /// Link Properties.
+ LinkProps,
+ /// Organize ▸ Extract (options), Rotate Pages.
+ Extract,
+ RotatePages,
+ /// Remove Hidden Information and Sanitize Document.
+ RemoveHidden,
+ Sanitize,
+ /// Documents from a session that ended unexpectedly.
+ Recovery,
+ /// Comments ▸ Summarize comments (options).
+ SummarizeComments,
+ /// Sign with a Digital ID ▸ Configure ▸ Sign as.
+ Sign,
+ /// Optimize PDF ▸ Advanced optimization.
+ Optimize,
+ /// Prepare a form ▸ right-click a field ▸ Duplicate.
+ DuplicateField,
+ /// Prepare a form ▸ Text field table: a movable window rather than a modal (`field_table_ui`).
+ FieldTable,
+ /// Check for accessibility ▸ Accessibility Checker Options.
+ AccessibilityOptions,
+ /// Scan & OCR ▸ Recognize text.
+ RecognizeText,
+ /// The JavaScript console (⌘J).
+ JsConsole,
+ /// Document JavaScripts.
+ DocumentJs,
+ /// Preferences.
+ Preferences,
+ /// Compare files: choose the older version.
+ CompareFiles,
+ /// Action Wizard.
+ ActionWizard,
+ /// Standards ▸ PDF/A.
+ PdfA,
+ /// Custom stamps ▸ Create.
+ CreateStamp,
+ /// Prepare for accessibility ▸ Add alternate text.
+ AltText,
+ /// PDF Optimizer ▸ Audit space usage (then back to the optimizer).
+ AuditSpace,
+ /// Signatures ▸ Show certificate.
+ CertificateViewer,
+ }
+
+ #[derive(Clone, Copy, Debug, PartialEq, Eq)]
+ pub enum PropsTab {
+ Description,
+ InitialView,
+ Security,
+ Fonts,
+ Custom,
+ Advanced,
+ SpaceAudit,
+ }
+
+ /// Document Properties ▸ Custom being edited: the properties as they will be after OK, in order,
+ /// and the Name and Value fields.
+ #[derive(Clone, Debug, Default, PartialEq)]
+ pub struct CustomDraft {
+ pub props: Vec<(String, String)>,
+ pub name: String,
+ pub value: String,
+ }
+
+ /// Duplicate Field: the field and the pages (all, or a range, 1-based).
+ #[derive(Clone, Debug, PartialEq)]
+ pub struct DuplicateDraft {
+ pub name: String,
+ pub all: bool,
+ pub from: usize,
+ pub to: usize,
+ }
+
+ /// Page Properties: the document and pages it applies to (0-based), the document's edit
+ /// generation when the dialog opened, and the pages' tab order as they have it (`None` when they
+ /// differ) and as chosen (`None` until one is chosen).
+ #[derive(Clone, Debug, PartialEq)]
+ pub struct PagePropsDraft {
+ pub doc: DocId,
+ pub generation: u64,
+ pub pages: Vec<usize>,
+ pub before: Option<pdfcraft_engine::TabOrder>,
+ pub tab_order: Option<pdfcraft_engine::TabOrder>,
+ }
+
+ /// Copied pages: their document's name and bytes (as it was when copied) and the pages.
+ #[derive(Clone, Debug)]
+ pub struct PageClip {
+ /// The document the pages were copied from: pasting back into it keeps field names.
+ pub from: DocId,
+ pub name: String,
+ pub bytes: std::sync::Arc<Vec<u8>>,
+ pub pages: Vec<usize>,
+ }
+
+ /// One page of a whole-document copy: its text as read for display, to read, or not to try
+ /// (reading it failed before).
+ pub(crate) enum CopyPage {
+ Read(std::sync::Arc<pdfcraft_render::PageText>),
+ ToRead,
+ Skip,
+ }
+
+ /// What a whole-document copy needs, taken from the view on the UI thread: each page's text
+ /// layer as far as it was read, and the document to read the others from.
+ pub(crate) struct DocumentCopyJob {
+ pub(crate) pages: Vec<CopyPage>,
+ bytes: std::sync::Arc<Vec<u8>>,
+ password: Option<std::sync::Arc<str>>,
+ }
+
+ impl DocumentCopyJob {
+ pub(crate) fn of(v: &DocView, doc: &pdfcraft_engine::Document) -> DocumentCopyJob {
+ let pages = (0..v.page_count())
+ .map(|p| match v.texts.get(&p) {
+ Some(t) => CopyPage::Read(t.clone()),
+ None if v.text_failed.contains(&p) => CopyPage::Skip,
+ None => CopyPage::ToRead,
+ })
+ .collect();
+ DocumentCopyJob { pages, bytes: doc.bytes.clone(), password: doc.password.as_deref().map(std::sync::Arc::from) }
+ }
+
+ /// The document's text in page order, a page per line run. Each page read here is let go
+ /// once its text is taken, so a large document never holds every page's text layer at once.
+ /// `None` when `cancel` was set.
+ pub(crate) fn text(self, cancel: &std::sync::atomic::AtomicBool) -> Option<String> {
+ let mut renderer: Option<pdfcraft_render::PageRenderer> = None;
+ let mut out = String::new();
+ let mut push = |text: String| {
+ if !text.is_empty() {
+ if !out.is_empty() {
+ out.push('\n');
+ }
+ out.push_str(&text);
+ }
+ };
+ for (page, p) in self.pages.into_iter().enumerate() {
+ if cancel.load(std::sync::atomic::Ordering::Relaxed) {
+ return None;
+ }
+ match p {
+ CopyPage::Read(t) => push(t.text_of(0..t.glyphs.len())),
+ CopyPage::ToRead => {
+ let r = renderer.get_or_insert_with(|| {
+ let config = pdfcraft_render::RenderConfig { password: self.password.clone(), ..Default::default() };
+ pdfcraft_render::PageRenderer::new(self.bytes.clone(), config)
+ });
+ let req = pdfcraft_render::RenderRequest {
+ page,
+ kind: pdfcraft_render::RequestKind::Text,
+ tile: None,
+ scale: 1.0,
+ tag: 0,
+ preview: false,
+ };
+ if let Some(t) = r.render(req).text {
+ push(t.text_of(0..t.glyphs.len()));
+ }
+ }
+ CopyPage::Skip => {}
+ }
+ }
+ Some(out)
+ }
+ }
+
+ pub struct PasswordPrompt {
+ pub name: String,
+ pub path: Option<String>,
+ pub bytes: std::sync::Arc<Vec<u8>>,
+ #[cfg(not(target_arch = "wasm32"))]
+ pub(crate) stamp: Option<file_watch::Stamp>,
+ pub input: String,
+ pub error: Option<String>,
+ /// A late startup file must stay in the background even after it is unlocked.
+ pub(crate) activate: bool,
+ /// The bytes are a recovery snapshot: once the document is open it takes the snapshot's
+ /// path and recovery entry. Cancelling the prompt drops the association with it (#813).
+ pub(crate) recovered: Option<RecoveryMeta>,
+ /// The tool that asked for this file (a tool chosen with no document open): it runs once
+ /// the document is unlocked.
+ pub(crate) then: Option<&'static str>,
+ /// A link destination to apply after the linked PDF is unlocked.
+ pub(crate) after_open: Option<pdfcraft_render::RemoteDestination>,
++ /// A launch-time display override, applied only after this PDF is unlocked.
++ pub(crate) display_override: Option<(canvas::PageLayout, bool)>,
+ }
+
+ #[cfg(not(target_arch = "wasm32"))]
+ pub(crate) struct OpenRequest {
+ pub(crate) name: String,
+ pub(crate) path: Option<String>,
+ pub(crate) stamp: Option<file_watch::Stamp>,
+ pub(crate) input: open_worker::Input,
+ pub(crate) password: Option<String>,
+ pub(crate) activate: bool,
+ pub(crate) after_open: Option<pdfcraft_render::RemoteDestination>,
+ pub(crate) recovered: Option<RecoveryMeta>,
+ pub(crate) then: Option<&'static str>,
+ }
+
+ /// Asks for the permissions password of an open document whose security restricts it, which
+ /// lifts the restrictions (#995). Acrobat asks for it when such a document's security is changed.
+ pub struct UnlockPrompt {
+ pub doc: DocId,
+ pub name: String,
+ pub input: String,
+ pub error: Option<String>,
+ /// The command to run once unlocked (Protect using password, Remove security), if any.
+ pub then: Option<&'static str>,
+ }
+
+ impl UnlockPrompt {
+ pub(crate) fn new(doc: &pdfcraft_engine::Document, then: Option<&'static str>) -> Self {
+ Self { doc: doc.id, name: doc.name.clone(), input: String::new(), error: None, then }
+ }
+ }
+
+ #[derive(serde::Serialize, serde::Deserialize)]
+ pub struct RecentFile {
+ pub name: String,
+ pub path: String,
+ pub pages: usize,
+ pub size: usize,
+ }
+
+ /// Where in a document a request to open an address came from.
+ #[derive(Clone, Copy, Debug, PartialEq, Eq)]
+ pub enum LinkOrigin {
+ /// A link on the page.
+ Link,
+ /// A push button's URI action.
+ Button,
+ /// A script (`app.launchURL`).
+ Script,
+ }
+
+ impl LinkOrigin {
+ pub(crate) fn noun(self) -> &'static str {
+ match self {
+ Self::Link => "A link",
+ Self::Button => "A button",
+ Self::Script => "A script",
+ }
+ }
+ }
+
+ /// An address a document asked to open, waiting for the user to allow or cancel it.
+ #[derive(Clone, Debug, PartialEq, Eq)]
+ pub struct PendingLink {
+ pub url: String,
+ pub origin: LinkOrigin,
+ }
+
+ /// A resolved local target and its original source/destination, independent of the active tab.
+ #[derive(Clone, Debug)]
+ pub struct PendingRemoteLink {
+ pub source: DocId,
+ pub path: std::path::PathBuf,
+ pub destination: pdfcraft_render::RemoteDestination,
+ }
+
+ /// Settings for the Number pages dialog.
+ #[derive(Clone, Debug, PartialEq)]
+ pub struct NumberDraft {
+ pub from: usize,
+ pub to: usize,
+ pub style: pdfcraft_engine::LabelStyle,
+ pub prefix: String,
+ pub start: u32,
+ }
+
+ /// What [`PdfCraftApp::open_path`] did: opened the file in a new tab, focused the tab already
+ /// showing it, handed it to the background open worker, or failed. Failures tell the user
+ /// through a toast; this is the programmatic contract for callers that must know (the control
+ /// channel, tools that wait for a file) (#1620).
+ #[derive(Clone, Copy, Debug, PartialEq, Eq)]
+ pub enum OpenOutcome {
+ /// The file opened in a new tab (or raised its password prompt).
+ Opened,
+ /// A tab already showed the file; it was focused and no tab was added.
+ Focused,
+ /// The file was accepted for opening in the background; its tab appears when the open
+ /// completes (`ui.state.pending_opens` lists the files on the way).
+ Pending,
+ /// The file could not be read or opened; the user was told.
+ Failed,
+ }
diff --cc crates/ui-egui/tests/it/editing.rs
index 645910809,bdb0720dd..9cec89e7d
--- a/crates/ui-egui/tests/it/editing.rs
+++ b/crates/ui-egui/tests/it/editing.rs
@@@ -2038,130 -2531,77 +2531,202 @@@ fn split_from_pages_panel_context_menu(
}
#[test]
- fn launch_display_override_survives_password_retry_without_changing_defaults() {
- use pdfcraft_ui_egui::canvas::PageLayout;
- use std::io::Write as _;
- let nonce = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
- let path = temp_path(&format!("startup-layout-{nonce}.pdf"));
- let mut file = std::fs::OpenOptions::new().write(true).create_new(true).open(&path).unwrap();
- file.write_all(&protected("reader", "owner", -4)).unwrap();
+ fn split_from_pages_panel_context_menu_on_current_page_without_selection() {
+ let mut h = harness(4, |app| app.right = Some(pdfcraft_ui_egui::RightPanel::Pages));
+ // Navigate to Page 2 (0-indexed 1) so it is current, but keep selected empty
+ h.state_mut().views[0].go_to_page(1);
+ h.state_mut().views[0].selected.clear();
+ h.run_steps(2);
+ assert_eq!(h.state().views[0].current, 1);
+ assert!(h.state().views[0].selected.is_empty());
+ let thumb = h.get_all_by_label("Page 2").max_by(|a, b| a.rect().left().total_cmp(&b.rect().left())).unwrap();
+ thumb.click_button(egui::PointerButton::Secondary);
+ h.run_steps(2);
+ h.get_all_by_label("Split document…").last().unwrap().click();
+ h.run_steps(3);
+ assert_eq!(h.state().dialog, Some(pdfcraft_ui_egui::Dialog::Split));
+ assert_eq!(h.state().split_draft.mode, pdfcraft_ui_egui::SplitMode::Selection);
+ h.get_by_label_contains("Creates 2 files from 4 pages");
+ }
+
+ #[test]
+ fn split_from_pages_panel_context_menu_on_page_one_falls_back_to_pages() {
+ let mut h = harness(4, |app| app.right = Some(pdfcraft_ui_egui::RightPanel::Pages));
+ let thumb = h.get_all_by_label("Page 1").max_by(|a, b| a.rect().left().total_cmp(&b.rect().left())).unwrap();
+ thumb.click_button(egui::PointerButton::Secondary);
+ h.run_steps(2);
+ h.get_all_by_label("Split document…").last().unwrap().click();
+ h.run_steps(3);
+ assert_eq!(h.state().dialog, Some(pdfcraft_ui_egui::Dialog::Split));
+ assert_eq!(h.state().split_draft.mode, pdfcraft_ui_egui::SplitMode::Pages);
+ }
+
+ #[test]
+ fn split_from_pages_panel_context_menu_with_multi_selection() {
+ let mut h = harness(4, |app| app.right = Some(pdfcraft_ui_egui::RightPanel::Pages));
+ // Select pages 2 and 4 (indices 1 and 3)
+ h.state_mut().views[0].select_pages(&[1, 3]);
+ h.run_steps(2);
+ let thumb = h.get_all_by_label("Page 2").max_by(|a, b| a.rect().left().total_cmp(&b.rect().left())).unwrap();
+ thumb.click_button(egui::PointerButton::Secondary);
+ h.run_steps(2);
+ h.get_all_by_label("Split document…").last().unwrap().click();
+ h.run_steps(3);
+ assert_eq!(h.state().dialog, Some(pdfcraft_ui_egui::Dialog::Split));
+ assert_eq!(h.state().split_draft.mode, pdfcraft_ui_egui::SplitMode::Selection);
+ h.get_by_label_contains("Creates 3 files from 4 pages");
+ }
+
+ // ── Encrypted documents ───────────────────────────────────────────────────────────────────────
+
+ fn protected(user: &str, owner: &str, permissions: i32) -> Vec<u8> {
+ protected_with(pdfcraft_cos::Algorithm::Aes256, user, owner, permissions)
+ }
+
+ fn protected_with(algorithm: pdfcraft_cos::Algorithm, user: &str, owner: &str, permissions: i32) -> Vec<u8> {
+ encrypted(fixture(2), algorithm, user, owner, permissions)
+ }
+
+ /// `bytes` rewritten encrypted.
+ fn encrypted(bytes: Vec<u8>, algorithm: pdfcraft_cos::Algorithm, user: &str, owner: &str, permissions: i32) -> Vec<u8> {
+ let mut doc = pdfcraft_cos::Document::open(std::sync::Arc::new(bytes)).unwrap();
+ doc.set_encryption(&pdfcraft_cos::NewEncryption {
+ algorithm,
+ user_password: user,
+ owner_password: owner,
+ permissions,
+ encrypt_metadata: true,
+ seed: [4; 32],
+ })
+ .unwrap();
+ pdfcraft_cos::write_full(&doc, &Default::default()).unwrap()
+ }
+
++#[test]
++fn launch_display_override_survives_password_retry_without_changing_defaults() {
++ use pdfcraft_ui_egui::canvas::PageLayout;
++ use std::io::Write as _;
++ let nonce = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
++ let path = temp_path(&format!("startup-layout-{nonce}.pdf"));
++ let mut file = std::fs::OpenOptions::new().write(true).create_new(true).open(&path).unwrap();
++ file.write_all(&protected("reader", "owner", -4)).unwrap();
+ drop(file);
+ let mut app = PdfCraftApp::new();
+ app.set_option("default-layout", "continuous").unwrap();
+ app.open_path_with_display(path.to_str().unwrap(), PageLayout::TwoUp, false);
+ assert!(app.views.is_empty() && app.password_prompt.is_some());
+ app.submit_password(Some("wrong".into()));
+ assert!(app.views.is_empty() && app.password_prompt.is_some());
+ app.submit_password(Some("reader".into()));
+ assert_eq!(app.views.len(), 1);
+ assert_eq!(app.views[0].layout, PageLayout::TwoUp);
+ assert!(!app.views[0].continuous());
+ let persisted: serde_json::Value = serde_json::from_str(&app.persist()).unwrap();
+ assert_eq!(persisted["default_layout"], "continuous");
+ std::fs::remove_file(path).unwrap();
+}
+
+#[test]
+fn asynchronous_launch_display_override_survives_retries_and_cancel() {
+ asynchronous_launch_display(false);
+}
+
+#[test]
+fn asynchronous_launch_display_explicit_layout_survives_retries_and_cancel() {
+ asynchronous_launch_display(true);
+}
+
+fn asynchronous_launch_display(explicit: bool) {
+ use pdfcraft_ui_egui::canvas::PageLayout;
+ fn wait(h: &mut Harness<'static, PdfCraftApp>, stage: &str, ready: impl Fn(&PdfCraftApp) -> bool) {
+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
+ while !ready(h.state()) {
+ assert!(
+ std::time::Instant::now() < deadline,
+ "{stage}: views={}, prompt={}, error={}, notice={}",
+ h.state().views.len(),
+ h.state().password_prompt.is_some(),
+ h.state().password_prompt.as_ref().is_some_and(|p| p.error.is_some()),
+ h.state().toast.is_some()
+ );
+ h.run_steps(2);
+ std::thread::sleep(std::time::Duration::from_millis(5));
+ }
+ }
+ let path = temp_path(&format!("async-startup-layout-{explicit}.pdf"));
+ std::fs::write(&path, protected("reader", "owner", -4)).unwrap();
+ let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(|_| {
+ let mut app = PdfCraftApp::new();
+ app.set_option("language", "en").unwrap();
+ app.set_option("default-layout", "continuous").unwrap();
+ app.open_bytes("other.pdf", None, fixture(2)).unwrap();
+ app
+ });
+ h.run_steps(2);
+ assert!(!h.state().run_inline, "exercise upstream's actual background-opening path");
+ let other = h.state().views[0].id;
+ h.state_mut().open_path_with_display(path.to_str().unwrap(), PageLayout::TwoUp, false);
+ if explicit {
+ h.state_mut().set_launch_layout("single").unwrap();
+ }
+ wait(&mut h, "password prompt", |app| app.password_prompt.is_some());
+ // The existing document keeps its default view while this request is pending.
+ h.state_mut().submit_password(Some("wrong".into()));
+ wait(&mut h, "wrong-password result", |app| app.password_prompt.as_ref().is_some_and(|p| p.error.is_some()));
+ assert_eq!(h.state().views.len(), 1);
+ h.state_mut().submit_password(Some("reader".into()));
+ wait(&mut h, "first unlock", |app| app.views.len() == 2);
+ assert_eq!(h.state().views[0].id, other);
+ assert_eq!(h.state().views[0].layout, PageLayout::Single);
+ assert!(h.state().views[0].continuous());
+ assert_eq!(h.state().views[1].layout, if explicit { PageLayout::Single } else { PageLayout::TwoUp });
+ assert!(!h.state().views[1].continuous());
+ let second_path = path.with_extension("second.pdf");
+ std::fs::copy(&path, &second_path).unwrap();
+ h.state_mut().open_path_with_display(second_path.to_str().unwrap(), PageLayout::TwoUp, false);
+ wait(&mut h, "password prompt", |app| app.password_prompt.is_some());
+ h.state_mut().submit_password(None);
+ h.state_mut().open_path(second_path.to_str().unwrap());
+ wait(&mut h, "password prompt", |app| app.password_prompt.is_some());
+ h.state_mut().submit_password(Some("reader".into()));
+ wait(&mut h, "normal unlock after cancel", |app| app.views.len() == 3);
+ assert_eq!(h.state().views[2].layout, PageLayout::Single);
+ assert!(h.state().views[2].continuous());
+ let persisted: serde_json::Value = serde_json::from_str(&h.state().persist()).unwrap();
+ assert_eq!(persisted["default_layout"], "continuous");
+ std::fs::remove_file(path).unwrap();
+ std::fs::remove_file(second_path).unwrap();
+}
+
+#[test]
+fn canceling_launch_display_override_does_not_affect_later_documents() {
+ use pdfcraft_ui_egui::canvas::PageLayout;
+ use std::io::Write as _;
+ let nonce = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
+ let path = temp_path(&format!("startup-cancel-layout-{nonce}.pdf"));
+ let mut file = std::fs::OpenOptions::new().write(true).create_new(true).open(&path).unwrap();
+ file.write_all(&protected("reader", "owner", -4)).unwrap();
+ drop(file);
+ let mut app = PdfCraftApp::new();
+ app.set_option("default-layout", "continuous").unwrap();
+ app.open_path_with_display(path.to_str().unwrap(), PageLayout::TwoUp, false);
+ assert!(app.views.is_empty() && app.password_prompt.is_some());
+ app.submit_password(None);
+ assert!(app.views.is_empty() && app.password_prompt.is_none());
+ app.open_bytes("next.pdf", None, fixture(2)).unwrap();
+ assert_eq!(app.views[0].layout, PageLayout::Single);
+ assert!(app.views[0].continuous());
+ // Reopening the same protected file normally must not resurrect the canceled override.
+ app.open_path(path.to_str().unwrap());
+ app.submit_password(Some("reader".into()));
+ assert_eq!(app.views.len(), 2);
+ assert_eq!(app.views[1].layout, PageLayout::Single);
+ assert!(app.views[1].continuous());
+ let persisted: serde_json::Value = serde_json::from_str(&app.persist()).unwrap();
+ assert_eq!(persisted["default_layout"], "continuous");
+ std::fs::remove_file(path).unwrap();
+}
+
#[test]
fn password_prompt_opens_and_security_tab_reports_the_details() {
let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(|_cc| {
diff --cc docs/roadmap.md
index 444d7b063,0f1fb6f4d..e3987182e
--- a/docs/roadmap.md
+++ b/docs/roadmap.md
@@@ -109,11 -190,11 +190,11 @@@ total matches the parity estimate
| M | Milestone | Plan size (h) | Done | Remaining (h, 2026-10-10) | Notes |
|---|---|---|---|---|---|
| M0 | Skeleton: workspace, xtask gates, CI | 15–30 | 98% | 1–2 | GitHub workflow, `deny.toml` (licence audit of every dependency), parity checklist (826 features, `xtask parity`) done. Missing: remaining crate stubs, testkit/oracle crates |
- | M1 | COS: filters, crypt, parser, xref, writer | 120–200 | 80% | 20–40 | Done:<br>- filters and crypt: every standard-security revision R2–R6 (RC4, AES-128/256), SASLprep, permissions, creating encryption;<br>- cos: parse and repair (including invalid xref object-number ranges), decoded-stream limits including unfiltered data, decrypt on load, re-encrypt on save, incremental and full writing.<br>Corpus: open/edit/save passes on 958 files, and all 7 password-protected files open.<br>Full saves now pack objects into compressed object streams. An unchanged incremental save of a classic table writes a zero-length cross-reference subsection instead of a section with no subsections (#1339). A full rewrite keeps unknown trailer entries, including objects reachable only from them (#1338). Fuzzing runs nightly (`xtask fuzz`). Raw-deflate fallback preserves decoding-limit errors, including through tolerant COS stream decoding. Missing: ≥ 250 tests, own image codecs |
- | M2 | Model, render, text | 200–350 | 15% | 130–230 | hayro bootstrap renderer (vendored patches); inspector predictor scratch is bounded by available input, and JPX sample rescaling handles 1–32 bits safely. Text extraction reaches word-F1 0.98 against pdftotext. Short same-line redraws split before placement rather than interleaving. Missing: model crate, fonts, DisplayList, renderer independent of hayro. Inspector page-label traversal and output are resource-bounded, with physical-number fallback warnings. Packed TIFF-predictor RGB rows retain later rows in decoding and rendering. Page marks, added content and print output retain small page-unit transform coefficients when serialized. |
+ | M1 | COS: filters, crypt, parser, xref, writer | 120–200 | 80% | 20–40 | Done:<br>- filters and crypt: every standard-security revision R2–R6 (RC4, AES-128/256), SASLprep, permissions, creating encryption;<br>- cos: parse and repair (including invalid xref object-number ranges), decoded-stream limits including unfiltered data, decrypt on load, re-encrypt on save, incremental and full writing.<br>Corpus: open/edit/save passes on 958 files, and all 7 password-protected files open.<br>Full saves now pack objects into compressed object streams. An unchanged incremental save of a classic table writes a zero-length cross-reference subsection instead of a section with no subsections (#1339). A full rewrite keeps unknown trailer entries, including objects reachable only from them (#1338). Fuzzing runs nightly (`xtask fuzz`). Raw-deflate fallback preserves decoding-limit errors, including through tolerant COS stream decoding. Done since: #2658: macOS atomic saves retain destination extended attributes, including Finder tags, and reject partial resource-fork reads after size changes. Metadata failures retain the original PDF and unsaved edit. Missing: ≥ 250 tests, own image codecs |
+ | M2 | Model, render, text | 200–350 | 15% | 130–230 | hayro bootstrap renderer (vendored patches); inspector predictor scratch is bounded by available input, and JPX sample rescaling handles 1–32 bits safely. Text extraction reaches word-F1 0.98 against pdftotext. Short same-line redraws split before placement rather than interleaving. Missing: model crate, fonts, DisplayList, renderer independent of hayro. Inspector page-label traversal and output are resource-bounded, with physical-number fallback warnings. Packed TIFF-predictor RGB rows retain later rows in decoding and rendering. Page marks, added content and print output retain small page-unit transform coefficients when serialized. Forms without Resources use page Properties for ActualText and layer visibility; own dictionaries stop fallback. Oversized missing inline-image samples, including header and terminator overhead, no longer pin the content window (#3107 / PR #3438); normal large streamed images retain deterministic sample boundaries. Radial luminosity fades have synthetic coverage for the existing #2132 mask guard, including per-pixel references, antialiased clips, previews, scales and tiles; no additional production fix was needed. Dotted TOC leaders no longer inflate letter tracking or hide word spaces (#3086); phrase search and selection are covered. Short tracked ellipses retain their gap samples and remain searchable. Missing spacing glyphs in non-embedded Japanese CID substitutes render blank without changing PDF advances or Unicode (#3601). The desktop viewer can use installed CJK fonts, including Windows GBK Song/Hei/Kai/FangSong and subset-prefixed Founder names; Combine thumbnails and accessibility figure previews use the same display-only fallback, without changing export or print font policy (#234, continuation of #1567, review #4172). Print previews exclude installed faces and isolate their font cache; GBK regressions cover view/print switching for inline and pooled whole-page/tile rendering. Installed-font helpers and their regression contracts have function documentation. GBK regression rasters match explicit-Unicode references with independently selected installed faces; wrong-glyph and wrong-family negative controls fail. Integration with main fa5f9f8c retains viewer fallback across the split engine session modules, renderer tests and Combine thumbnail workers. |
| M2 | Model, render, text | 200–350 | 15% | 130–230 | hayro bootstrap renderer (vendored patches); inspector predictor scratch is bounded by available input, and JPX sample rescaling handles 1–32 bits safely. Text extraction reaches word-F1 0.98 against pdftotext. Short same-line redraws split before placement rather than interleaving. Missing: model crate, fonts, DisplayList, renderer independent of hayro. Inspector page-label traversal and output are resource-bounded, with physical-number fallback warnings. Packed TIFF-predictor RGB rows retain later rows in decoding and rendering. The renderer keeps its one-point crop-size floor in physical points after UserUnit scaling, with regression coverage for crop origins, rotations and f32 reciprocal rounding. Existing unit policy and nearly-zero fallback are retained. |
| M2 | Model, render, text | 200–350 | 15% | 130–230 | hayro bootstrap renderer (vendored patches); inspector predictor scratch is bounded by available input, and JPX sample rescaling handles 1–32 bits safely. Text extraction reaches word-F1 0.98 against pdftotext. Short same-line redraws split before placement rather than interleaving. Missing: model crate, fonts, DisplayList, renderer independent of hayro. Inspector page-label traversal and output are resource-bounded, with physical-number fallback warnings |
- | M3 | Viewer app (native + web) | 80–150 | 90% | 10–20 | Acrobat-style shell, find, select, panels, tiles, web build, UI control channel for agents (opt-in). Missing: 60 fps test on a 500-page document, snapshot tests of every panel<br>Done since: fit visible, document title in the window; Linux middle-button scrolling; shared three-state theme preferences in the toolbar, View menu and control channel; numeric Linux portal events and idle wakeups completing #881, with native appearance inheritance retained (#446); late browser startup downloads preserve the current document and Save target (#171). Selected-text Copy in Edit and the canvas context menu is covered by focused regressions and native clipboard checks (#1225); document copy restrictions apply to the floating action too. #1364 candidate: absolute local GoToR links ask before target access; headless callers explicitly opt in. Native-opening candidate: chosen tools survive preparation and password retries; startup intake waits for pending preparation. Page-label navigation displays logical labels, retains the current page on unchanged submission and refreshes focused same-document replacements; clean file-watcher reload preserves the chosen scrolling mode, preventing a Single Page reader from jumping to page 1 during replacement. Synthetic control regressions cover these behaviors. #3149: page-list changes discard render demand based on old geometry; actual raster dimensions are checked against the GPU limit before upload. Synthetic crash and continued-rendering regressions cover the replacement path. #1354 local candidate: --two-paged overrides follow named PDFs through background opens and password retries, preserve defaults and respect single-tab reuse. Native regressions, visual inspection, strict scoped Clippy and scoped WASM compilation pass; three existing Unix-socket tests require an unrestricted runtime. The PR branch is pushed but not merged into upstream. |
-| M3 | Viewer app (native + web) | 80–150 | 90% | 10–20 | Acrobat-style shell, find, select, panels, tiles, web build, UI control channel for agents (opt-in). #3808: the Pages inspector offers a 50–150% thumbnail slider and buttons, also available through `ui.set`. Missing: 60 fps test on a 500-page document, snapshot tests of every panel<br>Done since: fit visible, document title in the window; Linux middle-button scrolling; shared three-state theme preferences in the toolbar, View menu and control channel; numeric Linux portal events and idle wakeups completing #881, with native appearance inheritance retained (#446); late browser startup downloads preserve the current document and Save target (#171). Selected-text Copy in Edit and the canvas context menu is covered by focused regressions and native clipboard checks (#1225); document copy restrictions apply to the floating action too. #1364 candidate: absolute local GoToR links ask before target access; headless callers explicitly opt in. Native-opening candidate: chosen tools survive preparation and password retries; startup intake waits for pending preparation. Page-label navigation displays logical labels, retains the current page on unchanged submission and refreshes focused same-document replacements; clean file-watcher reload preserves the chosen scrolling mode, preventing a Single Page reader from jumping to page 1 during replacement. Synthetic control regressions cover these behaviors. #3149: page-list changes discard render demand based on old geometry; actual raster dimensions are checked against the GPU limit before upload. Synthetic crash and continued-rendering regressions cover the replacement path. Save-prompt shortcuts yield to dialogs above them; stacked link-consent UI regression covers Escape and Return. Comment hover follows individual marked lines and original annotation paint order (#3541/#3620), independently of spatial inspection sorting; synthetic rotation, differing-upper-edge overlap and unchanged-document regressions. Optional page gaps join page edges without cropping PDF margins; current-document toggle, persisted default and UI control options are covered by viewer tests. Gap changes in Organize Pages preserve document scroll position, and both comparison panes follow menu and control choices. Repeated window resizes by an edge and moves by the tab strip on GNOME/Wayland work without a click in between. |
++| M3 | Viewer app (native + web) | 80–150 | 90% | 10–20 | Acrobat-style shell, find, select, panels, tiles, web build, UI control channel for agents (opt-in). #3808: the Pages inspector offers a 50–150% thumbnail slider and buttons, also available through `ui.set`. Missing: 60 fps test on a 500-page document, snapshot tests of every panel<br>Done since: fit visible, document title in the window; Linux middle-button scrolling; shared three-state theme preferences in the toolbar, View menu and control channel; numeric Linux portal events and idle wakeups completing #881, with native appearance inheritance retained (#446); late browser startup downloads preserve the current document and Save target (#171). Selected-text Copy in Edit and the canvas context menu is covered by focused regressions and native clipboard checks (#1225); document copy restrictions apply to the floating action too. #1364 candidate: absolute local GoToR links ask before target access; headless callers explicitly opt in. Native-opening candidate: chosen tools survive preparation and password retries; startup intake waits for pending preparation. Page-label navigation displays logical labels, retains the current page on unchanged submission and refreshes focused same-document replacements; clean file-watcher reload preserves the chosen scrolling mode, preventing a Single Page reader from jumping to page 1 during replacement. Synthetic control regressions cover these behaviors. #3149: page-list changes discard render demand based on old geometry; actual raster dimensions are checked against the GPU limit before upload. Synthetic crash and continued-rendering regressions cover the replacement path. Save-prompt shortcuts yield to dialogs above them; stacked link-consent UI regression covers Escape and Return. Comment hover follows individual marked lines and original annotation paint order (#3541/#3620), independently of spatial inspection sorting; synthetic rotation, differing-upper-edge overlap and unchanged-document regressions. Optional page gaps join page edges without cropping PDF margins; current-document toggle, persisted default and UI control options are covered by viewer tests. Gap changes in Organize Pages preserve document scroll position, and both comparison panes follow menu and control choices. Repeated window resizes by an edge and moves by the tab strip on GNOME/Wayland work without a click in between. Optional --two-paged applies noncontinuous two-page layout to explicitly opened CLI files without changing defaults; explicit --layout wins. |
| M3 | Viewer app (native + web) | 80–150 | 90% | 10–20 | Acrobat-style shell, find, select, panels, tiles, web build, UI control channel for agents (opt-in). Missing: 60 fps test on a 500-page document, snapshot tests of every panel<br>Done since: fit visible, document title in the window; Linux middle-button scrolling; shared three-state theme preferences in the toolbar, View menu and control channel; numeric Linux portal events and idle wakeups completing #881, with native appearance inheritance retained (#446); late browser startup downloads preserve the current document and Save target (#171). Selected-text Copy in Edit and the canvas context menu is covered by focused regressions and native clipboard checks (#1225); document copy restrictions apply to the floating action too. #1364 candidate: absolute local GoToR links ask before target access; headless callers explicitly opt in. Native-opening candidate: chosen tools survive preparation and password retries; startup intake waits for pending preparation. Page-label navigation displays logical labels, retains the current page on unchanged submission and refreshes focused same-document replacements; clean file-watcher reload preserves the chosen scrolling mode, preventing a Single Page reader from jumping to page 1 during replacement. Synthetic control regressions cover these behaviors. Wrapped revision buttons stay above Binding in Document Properties (#2739); a synthetic UI test checks layout and saved revision content. |
| M3 | Viewer app (native + web) | 80–150 | 90% | 10–20 | Acrobat-style shell, find, select, panels, tiles, web build, UI control channel for agents (opt-in). Missing: 60 fps test on a 500-page document, snapshot tests of every panel<br>Done since: fit visible, document title in the window; Linux middle-button scrolling; shared three-state theme preferences in the toolbar, View menu and control channel; numeric Linux portal events and idle wakeups completing #881, with native appearance inheritance retained (#446); late browser startup downloads preserve the current document and Save target (#171). #1364 candidate: absolute local GoToR links ask before target access; headless callers explicitly opt in. Native-opening candidate: chosen tools survive preparation and password retries; startup intake waits for pending preparation. Later native-open replies stay queued while a modal or picker owns the foreground; regressions cover recipient ownership, completion/cancellation and one-shot wakes. |
| M3 | Viewer app (native + web) | 80–150 | 90% | 10–20 | Acrobat-style shell, find, select, panels, tiles, web build, UI control channel for agents (opt-in). Missing: 60 fps test on a 500-page document, snapshot tests of every panel<br>Done since: fit visible, document title in the window; Linux middle-button scrolling; shared three-state theme preferences in the toolbar, View menu and control channel; numeric Linux portal events and idle wakeups completing #881, with native appearance inheritance retained (#446); late browser startup downloads preserve the current document and Save target (#171). #1364 candidate: absolute local GoToR links ask before target access; headless callers explicitly opt in. Native-opening candidate: chosen tools survive preparation and password retries; startup intake waits for pending preparation. #1980: exact quit modifiers preserve Ctrl+Alt+Q email input; Ctrl+Q/Cmd+Q asks before discarding unsaved documents. |
@@@ -199,8 -290,49 +290,50 @@@ Estimates unchanged
| Date | Change | Summary |
|---|---|---|
- | 2026-10-18 | minor | M3 #1354 local candidate: launch override integrated with current main; repeated-file and password-owned startup regressions, old-wrapper negative checks and visual verification; native scoped checks and WASM compilation pass. Socket tests remain environment-limited; no push or GitHub merge. |
++| 2026-10-31 | patch | M3 #1354: reconcile the launch override with split app/file modules and the structured open result; preserve headless help/version exits. CI validation pending. |
+ | 2026-10-31 | patch | M2, PR #4172: eight GBK font/alias cases compare exact pixels with independent installed-face and explicit-Unicode references; wrong-glyph and wrong-family negative controls fail. Estimates unchanged. |
+ | 2026-10-31 | patch | M2, PR #4172: integrate main fa5f9f8c, preserve both raster test groups and restore explicit display_config imports; display-only CJK policy and estimates unchanged. |
+ | 2026-10-28 | patch | M2, PR #4172: integrate main 5af10276 and retain both roadmap histories; viewer-only CJK and print/output font policies and estimates unchanged. |
+ | 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-26 | minor | M11: lossless JBIG2 symbol coding (`pdfcraft_filters::encode_jbig2`): each distinct mark stored once in a symbol dictionary and its exact copies placed by a text region, larger and lone marks in a generic region, used when smaller than the generic coding; on six pages of rendered 300 dpi text 28% of the generic region's size and 17% of Group 4's. Scans gain little until refinement coding; `/JBIG2Globals` and lossy coding not yet. Estimates unchanged. |
+ | 2026-10-23 | minor | M11: lossless JBIG2 for black-and-white images (`pdfcraft_filters::encode_jbig2_generic`, a generic region coded with the MQ coder, written from the JBIG2 draft standard), as Monochrome Images ▸ JBIG2 (lossless) and `doc_optimize` `mono: jbig2`; about a third smaller than Group 4 on 300 dpi text. Export ▸ Images reads JBIG2 images (`hayro-jbig2`, with `/JBIG2Globals`). Symbol coding not yet. 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-23 | minor | M6: calculation checks: a formula reading a field the form doesn't have, and a script building the names it reads, are flagged by `form_calculation_order` and on the Calculation order page (a red mark, a card naming the broken formulas, a note for built names); `form_calculation_order` gives each formula and `form_fields` a custom Calculate script. Estimates unchanged. |
+ | 2026-10-29 | minor | M7 #2517: widening a paragraph rejoins a wrap with the spaces that wrap consumed, including a typed run and none for a Chinese or Japanese word split, after an incremental save and a full rewrite. 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. |
+ | 2026-10-23 | minor | M10: covered table slots retain their text in paragraph flow across Office exporters; emitted superscripts remain in their cells. Synthetic source and CLI regressions; estimates unchanged. |
+ | 2026-10-23 | minor | M10: Export all images and Save Image As apply soft-mask Decode intervals to PNG alpha before resizing, including inverted/subrange, indirect, packed and JPEG masks. Estimates unchanged. |
+ | 2026-10-23 | minor | M10: annotation appearances use unoccupied XObject names, preserving original page artwork and distinct appearances through inherited resources and print/reopen. Estimates unchanged. |
+ | 2026-10-21 | minor | M3: on GNOME/Wayland, a second resize by an edge or move by the tab strip works without a click in between (the compositor kept the button's release from egui). Estimates unchanged. |
+ | 2026-10-22 | minor | M4, #3916 partial: edits and Undo/Redo cancel Organize page drags. Pointer-release and save/reopen regressions check page order. Estimates unchanged. |
+ | 2026-10-22 | minor | M14 #3558: rebased macOS association recovery; reuse #3042 shared metadata preservation instead of a duplicate save wrapper. Estimates unchanged. |
+ | 2026-10-22 | minor | M7 #2517: a partial rewrite of two paragraphs that share one text object closes the marker before the neighbour, so a later edit does not delete it. Estimates unchanged. |
+ | 2026-10-18 | minor | M7 #2517: a partial rewrite of the last paragraph closes its marker after the last `ET`, and does not close a following marked region early. Estimates unchanged. |
+ | 2026-10-15 | minor | M7 #2517: a blank line between paragraphs stays a paragraph break, and growing the first paragraph does not absorb the next one. Estimates unchanged. |
+ | 2026-10-20 | minor | M4: initial-view window and interface options resolve indirect boolean ViewerPreferences values; synthetic true/false and save/reopen regressions retain defaults for malformed entries. Estimates unchanged. |
+ | 2026-10-21 | minor | M3, #3808: the Pages inspector has an independent 50–150% thumbnail size slider and buttons; selection and current-page following are retained, with headless ui.set coverage. Estimates unchanged. |
+ | 2026-10-20 | minor | M11 #3507: image merging preserves comments and state across content streams. Estimates unchanged. |
+ | 2026-10-17 | minor | M8, gap 6 #2662: a filled cover that hides half of any one word of a long line counts as a redaction-audit finding, applied or not; a sliver under half of every word stays unflagged. Estimates unchanged. |
+ | 2026-10-13 | minor | M10: dotted-leader contents entries retain titles and page numbers in separate paragraphs (#1757); estimates unchanged. |
+ | 2026-10-22 | minor | M6: calculation scripts: simplified field notation is read only from a comment, and a regular expression after `if (…)`, `while (…)`, `for (…)` or `with (…)` as one, so a rename leaves strings and regular expressions alone; a `//` comment ends at any line terminator, not only `\n`. Estimates unchanged. |
+ | 2026-10-20 | minor | M6: Prepare a form ▸ Calculation order: formulas and values, what is wrong and Fix order, Up/Down, Alt+↑/↓ and drag, links on the page. Estimates unchanged. |
+ | 2026-10-20 | minor | M6: `form_calculation_order` reads, checks, fixes and sets the calculation order; an edited formula keeps its place in `/CO`. Estimates unchanged. |
+ | 2026-10-20 | minor | M12 #3673: Character encoding accepts Identity-H/V with Adobe CJK collections, or a predefined non-Identity CMap; unknown names and foreign registries do not establish a mapping route. Synthetic checker and read-only automation regressions passed after failing before the fix. Per-glyph validation and embedded-font extraction remain separate; estimates unchanged. |
+ | 2026-10-19 | minor | M6: renaming a field renames it in the calculations that read it; `form_set_props` returns `formulas_updated` and Field Properties says how many changed. Estimates unchanged. |
+ | 2026-10-20 | minor | M6, #3502: form detection preserves comments across content streams; estimates unchanged. |
+ | 2026-10-20 | minor | M3/#3620: overlapping comment hover follows original annotation indices independently of spatial inspection sorting; a synthetic differing-upper-edge regression covers paint order. Estimates unchanged. |
+ | 2026-10-20 | minor | M10, #3532 partial: vector printing retains existing appearances with absent Subtype; estimates unchanged. |
+ | 2026-10-19 | minor | M4 #3309: named-destination pruning keeps large documents usable; 60,000-name and deep-tree regressions verify targets through undo/redo and both save modes. Estimates unchanged. |
+ | 2026-10-19 | minor | M6: Text field table (rows and columns of text fields as one edit, `form_add_field_table`); estimates unchanged |
+ | 2026-10-18 | minor | M5, PR #1971: nested source `/Page` and `/Pages` dictionaries export as null without traversing page content or the page tree. Synthetic saved/reopened three-page regression retains unrelated metadata and aliases. FDF import semantics, copied-graph limits and estimates unchanged. |
+ | 2026-10-15 | minor | M5: budget retained FDF entries before cloning; discovery keeps lazy array owners and annotation positions, with alias/cache-eviction stress fixtures. Limits cover the copied graph; source parsing/page discovery retain existing COS/parser limits, with no total source-memory bound. FDF import semantics and estimates unchanged. |
| 2026-10-15 | minor | M7: Edit text caret height follows its row, with a kittest regression; estimates unchanged |
+ | 2026-10-19 | minor | M3 #3360: retain each document’s scroll position when switching Read and the docking workspace at fixed zoom. Estimates unchanged. |
| 2026-10-18 | minor | M4, PR #1919 review: repeated page indices apply each rotation to the latest page-local value, preserving indirect/inherited angles. Synthetic adjacent/interleaved duplicates retain siblings and page contents through incremental and full saves. Estimates unchanged. |
| 2026-10-18 | minor | M3, #3149: page replacement cancels render demand collected for the previous geometry; all viewer raster upload paths reject empty or oversized textures before cache eviction. Synthetic regressions reproduce the reported 1880×2350 upload at a 2048 limit, retain cached images and unsaved edits, and resume bounded backdrops and tiles. Estimates unchanged. |
| 2026-10-17 | minor | M4 #2997: Ctrl-drag (Option on macOS) in the Organize grid copies the dragged pages into the drop gap (a "+" badge says so; the copies land selected, one undo step); `page_duplicate` takes `at`, and the UI control channel's `ui.drag` modifiers reach the input state. Estimates unchanged. |
diff --cc parity/acrobat-features.toml
index 35442678b,0b6f658dd..3484f35fc
--- a/parity/acrobat-features.toml
+++ b/parity/acrobat-features.toml
@@@ -878,8 -890,8 +890,8 @@@ milestone = "M3
status = "shipped"
commands = ["view.layout.two_up"]
tools = []
- evidence = ["crates/ui-egui/tests/view.rs::two_up_layout_places_pages_side_by_side", "crates/ui-egui/tests/viewer.rs::two_page_view_steps_a_spread_at_a_time", "apps/pdfcraft/src/startup.rs::startup_override_is_per_file_and_does_not_persist", "crates/ui-egui/src/open_worker_tests.rs::flagged_startup_opens_wait_for_password_ownership_before_the_first_frame"]
-evidence = ["crates/ui-egui/tests/it/view.rs::two_up_layout_places_pages_side_by_side", "crates/ui-egui/tests/it/viewer.rs::two_page_view_steps_a_spread_at_a_time"]
-notes = "next/previous page step a spread at a time"
++evidence = ["crates/ui-egui/tests/it/view.rs::two_up_layout_places_pages_side_by_side", "crates/ui-egui/tests/it/viewer.rs::two_page_view_steps_a_spread_at_a_time", "apps/pdfcraft/src/startup.rs::startup_override_is_per_file_and_does_not_persist", "crates/ui-egui/src/platform/open_worker/tests.rs::flagged_startup_opens_wait_for_password_ownership_before_the_first_frame"]
+notes = "Next/previous page step a spread at a time. Optional desktop --two-paged launches named PDFs in noncontinuous two-page view without changing saved defaults or unrelated restored tabs. Explicit --layout wins after flagged opens settle, including password retries; repeated files reuse their tab. This is a launch override, not a declarative configuration module."
[[feature]]
id = "view.layout-two-up-scrolling"