PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust
M10.5: Preserve main duplex-driver warnings through craft-print
skylar taylor-barrick00184a10067e
diff --cc Cargo.lockindex 2641fccc0,4fd9e89a9..33ece4c08--- a/Cargo.lock+++ b/Cargo.lock@@@ -1090,14 -1090,6 +1090,14 @@@ dependencies ="libc",]+[[package]]+name = "craft-print"+version = "0.1.0"- source = "git+https://github.com/storytold/craft-libs?rev=32bcac12db98113d18d8f56bc47fb6ddabe4d54f#32bcac12db98113d18d8f56bc47fb6ddabe4d54f"++source = "git+https://github.com/storytold/craft-libs?rev=d991bf6792f8ade99c51358bf3c1d902c8cd96b5#d991bf6792f8ade99c51358bf3c1d902c8cd96b5"+dependencies = [+ "tempfile",+]+[[package]]name = "craft-ui"version = "0.1.0"@@@ -1749,7 -1741,7 +1749,7 @@@ source = "registry+https://github.com/rchecksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"dependencies = ["libc",- "windows-sys 0.52.0",- "windows-sys 0.61.2",++ "windows-sys 0.59.0",][[package]]@@@ -4908,7 -4899,7 +4908,7 @@@ dependencies ="errno","libc","linux-raw-sys 0.12.1",- "windows-sys 0.52.0",- "windows-sys 0.61.2",++ "windows-sys 0.59.0",][[package]]@@@ -5531,10 -5522,10 +5531,10 @@@ source = "registry+https://github.com/rchecksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"dependencies = ["fastrand",- "getrandom 0.3.4",+ "getrandom 0.4.3","once_cell","rustix 1.1.5",- "windows-sys 0.52.0",- "windows-sys 0.61.2",++ "windows-sys 0.59.0",][[package]]@@@ -6494,7 -6485,7 +6494,7 @@@ version = "0.1.11source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"dependencies = [- "windows-sys 0.52.0",- "windows-sys 0.61.2",++ "windows-sys 0.59.0",][[package]]diff --cc Cargo.tomlindex bad4eda2e,ddea910f4..84650ac3c--- a/Cargo.toml+++ b/Cargo.toml@@@ -14,8 -14,6 +14,8 @@@ repository = "https://github.com/storyt[workspace.dependencies]# Shared frontend components; engines remain independent of egui.craft-ui = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "5c874d51eeb3de70e735c8ce87a59a7dedd47675", features = ["serde"] }+# Shared system spooler; document composition remains in pdfcraft-print.- craft-print = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "32bcac12db98113d18d8f56bc47fb6ddabe4d54f" }++craft-print = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "d991bf6792f8ade99c51358bf3c1d902c8cd96b5" }# internalpdfcraft-geom = { path = "crates/geom", version = "0.6.0" }pdfcraft-filters = { path = "crates/filters", version = "0.6.0" }diff --cc ROADMAP.mdindex 6f41d111e,561932a9b..bbc802414--- a/ROADMAP.md+++ b/ROADMAP.md@@@ -2,8 -2,9 +2,9 @@@**Stage: alpha** · next: beta, ~26% (ready for real work 49% → 75%) and ~400–700 h away- > **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-12 · **Change:** minor (shared craft-print spooler with passing Windows CI; architectural paper controls from #599; localized shortcut labels, #496; readiness table with hours per audience; full number as weighted sum 49%; earlier: second look: ready 40% → 47%, mainstream 55% added; core-workflow gate applied → alpha) · **Target:** Adobe Acrobat Pro (Acrobat DC, continuous track 26.002.21931, macOS)- > **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-11 · **Change:** M14 #307 Plan 3 uses one marker traversal on open and full refresh, and the combined scanner borrows metadata instead of cloning scan-only containers; includes a behavior-preserving `organize` binding for the workspace Clippy gate · earlier: minor (localized shortcut labels, #496; readiness table with hours per audience; full number as weighted sum 49%; second look: ready 40% → 47%, mainstream 55% added; core-workflow gate applied → alpha) · **Target:** Adobe Acrobat Pro (Acrobat DC, continuous track 26.002.21931, macOS)-> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-11 · **Change:** minor (M10, #1028: OCR reads pictures on pages that have text, on request); earlier: M14 #307 Plan 3 uses one marker traversal on open and full refresh, and the combined scanner borrows metadata instead of cloning scan-only containers; includes a behavior-preserving `organize` binding for the workspace Clippy gate · earlier: minor (localized shortcut labels, #496; readiness table with hours per audience; full number as weighted sum 49%; second look: ready 40% → 47%, mainstream 55% added; core-workflow gate applied → alpha) · **Target:** Adobe Acrobat Pro (Acrobat DC, continuous track 26.002.21931, macOS)++> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-12 · **Change:** minor (shared print CI reconciliation and driver duplex capability; M10, #1028: OCR reads pictures on pages that have text, on request); earlier: M14 #307 Plan 3 uses one marker traversal on open and full refresh, and the combined scanner borrows metadata instead of cloning scan-only containers; includes a behavior-preserving `organize` binding for the workspace Clippy gate · earlier: minor (localized shortcut labels, #496; readiness table with hours per audience; full number as weighted sum 49%; second look: ready 40% → 47%, mainstream 55% added; core-workflow gate applied → alpha) · **Target:** Adobe Acrobat Pro (Acrobat DC, continuous track 26.002.21931, macOS)+ > **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-11 · **Change:** minor (#594 paragraph drags validated in the Linux test environment; localized shortcut labels, #496; readiness table with hours per audience; full number as weighted sum 49%; earlier: second look: ready 40% → 47%, mainstream 55% added; core-workflow gate applied → alpha) · **Target:** Adobe Acrobat Pro (Acrobat DC, continuous track 26.002.21931, macOS)+ > **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-11 · **Change:** minor (architectural paper controls from #599; localized shortcut labels, #496; readiness table with hours per audience; full number as weighted sum 49%; earlier: second look: ready 40% → 47%, mainstream 55% added; core-workflow gate applied → alpha) · **Target:** Adobe Acrobat Pro (Acrobat DC, continuous track 26.002.21931, macOS)> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-11 · **Change:** minor (closed issues synced: #774, #756 and the #799–#821 batch; earlier: localized shortcut labels, #496; readiness table with hours per audience; full number as weighted sum 49%; earlier: second look: ready 40% → 47%, mainstream 55% added; core-workflow gate applied → alpha) · **Target:** Adobe Acrobat Pro (Acrobat DC, continuous track 26.002.21931, macOS)PdfCraft's one-page summary: how close it is to Adobe Acrobat Pro's offline feature set, and what@@@ -139,8 -140,12 +140,14 @@@ Ranked; detail and the full milestone tNewest first: the date, what moved, and the new overall estimate.+- **2026-10-12 (M10.5, hosted CI):** Integrated current main, including its date-table formatting and static-storage fixes. The Arabic synthetic drawing regression now checks the original serialized-output golden with and without the optional font face: the face-dependent FontName and FontFamily are checked separately and normalized only in the fixture. The hosted FreeBSD fingerprint is reproduced by those two metadata fields alone. Drawing bytes and all other fields retain the original golden; no printing behavior or readiness estimate changes.+- **2026-10-11 (M10.5):** Extracted printer discovery, options and PDF submission into craft-libs/craft-print, shared with DesignCraft. Windows preserves composed sheet size and orientation without fitting into default margins; duplex binding edges are corrected. PdfCraft retains permission checks and imposition. Shared transport and local composition, engine, automation and UI coverage validate the boundary; native Windows CI passes, including paused-queue submission and cleanup; physical printer fidelity remains a hardware check. Rust 1.95 is required by the shared crate. No readiness percentage change.+ - **2026-10-11 (M10, #1028):** Recognize Text can read pages that already have text: "Also recognize pages that already have text" in the dialog (remembered with the other choices, and used by Recognize text in multiple files) and `skip_text_pages: false` on `ocr_recognize` and, newly, `ocr_recognize_files`. A picture on such a page becomes searchable, and a recognised word at least half covered by the page's own text (an earlier OCR layer included) is left out, so nothing is found twice; `ocr_recognize` reports how many were left out as `already_on_page`. Before, the option existed only for agents and added the page's text a second time. The default still skips pages with text. Synthetic tests (a picture of a sentence plus real text) cover the engine, the tool and the dialog, and fail with the filter turned off. Still missing: reading only the picture areas (the whole page is read, as for a scan). Separately, `recognize_text_makes_a_scanned_page_searchable` fails on main wherever the models are installed (the model reads "quick" as "auick"). Estimates unchanged.+ - **2026-10-11 (M2, page-label prefixes):** The page-label readers bound the total size of decoded prefixes. Each range decodes its own prefix, and ranges may share one prefix object, so a small file could ask for a copy per range: within the 200,000-entry tree limit, about 200 MiB of copies of one 1,024-byte prefix. Inspection and Organize now refuse a tree whose decoded prefixes pass 4 MiB in total (`MAX_PREFIX_TOTAL_BYTES`), before any label is made, as the other tree limits do; relabelling such a tree changes nothing. Synthetic tests share one 1,000-byte prefix across 5,000 ranges and keep exactly 4 MiB of prefixes readable. Overall estimate unchanged.+ - **2026-10-11 (UI, checkboxes and radio buttons):** Checkboxes no longer look like radio buttons, and on the light theme neither is invisible. With the theme's 6 px widget radius egui drew a checkbox's 14 px box as a circle, so View ▸ Page display's Continuous scrolling and Show cover page read as two more layout choices; on the light theme an unticked box or an unselected radio button was white on white with no edge. Every checkbox (81) and radio button (79) now goes through `widgets::checkbox` / `widgets::radio` / `widgets::radio_value`: a 1 px outline (darker on hover), the plain fill on the light theme as dialogs already had, and for checkboxes a rounded-square box (3 px), keeping what the caller set (dialogs, the search panel). `clippy.toml` disallows `ui.checkbox`, `ui.radio`, `ui.radio_value`, `egui::Checkbox` and `egui::RadioButton` so new ones use them too. Estimates unchanged.+ - **2026-10-11 (M13, #971):** `text_find` now bounds each page's temporary match-range list to the remaining result limit plus one, which is enough to detect and return a continuation without allocating every match on a dense page. Added limited-search coverage; the existing end-to-end continuation test passes. The text cache byte budget and per-page extraction warnings remain open.+ - **2026-10-11 (M7, #594):** Ordinary paragraph body drags now use the existing source-preserving object translation path; edge drags still rewrap. An in-progress drag is discarded if the document generation changes, and added-content gestures keep their own edit handler. Added real-shell source regressions for overlapping and identical labels, history, save/reopen, partial overlap, kerning, rotation/crop/UserUnit and atomic refusal. Linux validation passed: focused UI/engine regressions, exact-base source-loss failures, native drag/undo/redo/save/reopen with independent Poppler renders, and all eight CI gates. Text replacement and resizing over unrelated overlapping content remain outside this repair. Estimates unchanged.+- **2026-10-10 (community, M7, Thai Add Text):** Optional craft-fonts Thai face (Noto Sans Thai) for the UI and shaped Add Text through the engine, CLI and MCP. Stacked marks and Sara Am are kept through Type 3 clusters with ToUnicode; regular style, and wrapping at cluster boundaries (no dictionary word segmentation). The craft-fonts pin for CI and releases moves to the revision with the Thai face. Forms and Fill & Sign are outside this change. Estimates unchanged.- **2026-10-11 (#995, #1077, permissions password after opening):** A PDF with only a permissions password opens without asking, restricted, and nothing let the user enter that password afterwards: the notice and the hint pointed at reopening with it. Now the security notice and Properties ▸ Security offer Unlock…, and Change settings / Remove security on a restricted document ask for the permissions password first and then carry on (as Acrobat does). The open password is refused there. `Session::unlock` upgrades the open document in place (owner and user passwords unlock the same file key, so nothing is re-read), unlocks the undo and redo states and reopens saves as owner; it is not an edit and doesn't mark the document unsaved. New command `protect.unlock`; the new strings are in all 15 full catalogs. Tests cover crypt, cos, engine (undo, redo, save, separate open password) and the UI. Still missing: an automation tool for it. Estimates unchanged.- **2026-10-11 (M14, #307 Plan 3):** Engine open and full refresh use one page/content traversal to populate marks and added content. The independent public scans remain available; the combined scanner borrows direct objects and holds referenced objects through `Arc<Object>` instead of cloning scan-only `/Contents` arrays or `/PCAdded` dictionaries. Differential tests cover an indirect `/PCAdded` dictionary as well as ordering, malformed/direct/indirect/repeated entries and `/UserUnit`. Exact `bbbe600`→final release CLI measurements used 10 alternating pairs: wall-time medians were 183.645→174.440 ms on 10,000 marker-free pages (10/10 wins), 33.587→32.752 ms on 1,500 mixed pages (8/10), and 24.331→20.133 ms on the 100,000-entry array stress fixture (10/10). The stress fixture's maximum-RSS median fell 28,655,616→19,038,208 B; peak-footprint medians were 14,747,136→14,673,408 B. From P0, the follow-up stress run was 20.886→20.201 ms (10/10), with RSS 23,953,408→19,087,360 B and peak footprint 14,706,144→14,697,952 B. `doc_open` stdout hashes matched every pair. The ancillary `organize` binding preserves the prior `prune_legacy` update condition. Estimates unchanged.diff --cc crates/print/src/tests.rsindex 7f49df035,bf186fb7d..dd4dbbbb3--- a/crates/print/src/tests.rs+++ b/crates/print/src/tests.rs@@@ -360,14 -449,147 +366,19 @@@ fn windows_printers_carry_one_default_a// Windows marks the system default with a `*` no queue name may contain; names hold spaces,// parentheses and non-ASCII letters, and the lines end with CRLF.let printers = parse_windows_printers("*Microsoft Print to PDF\r\nHP LaserJet 400 (Copy 2)\r\nКопир Canon iR\r\n\r\n*XPS via USB\r\n");- assert_eq!(printers[0], Printer { name: "Microsoft Print to PDF".into(), default: true });- assert_eq!(printers[1], Printer { name: "HP LaserJet 400 (Copy 2)".into(), default: false });- assert_eq!(printers[2], Printer { name: "Копир Canon iR".into(), default: false });+ assert_eq!(printers[0], Printer { name: "Microsoft Print to PDF".into(), default: true, two_sided: None });+ assert_eq!(printers[1], Printer { name: "HP LaserJet 400 (Copy 2)".into(), default: false, two_sided: None });+ assert_eq!(printers[2], Printer { name: "Копир Canon iR".into(), default: false, two_sided: None });// A spooler marking two defaults: the first still wins, so the dialog has one to preselect.- assert_eq!(printers[3], Printer { name: "XPS via USB".into(), default: false });+ assert_eq!(printers[3], Printer { name: "XPS via USB".into(), default: false, two_sided: None });assert_eq!(parse_windows_printers("\r\n"), Vec::new());+ // After a tab, whether the driver reports two-sided printing; a tab inside a name stays.+ let sided = parse_windows_printers("*Office PCL\t2\r\nOffice PS\t1\r\nTab\tName\t2\r\n");+ assert_eq!(sided[0], Printer { name: "Office PCL".into(), default: true, two_sided: Some(true) });+ assert_eq!(sided[1], Printer { name: "Office PS".into(), default: false, two_sided: Some(false) });+ assert_eq!(sided[2], Printer { name: "Tab\tName".into(), default: false, two_sided: Some(true) });}-#[test]-fn the_windows_print_script_binds_long_edge_on_the_long_edge() {- // System.Drawing's Duplex values are DEVMODE's: Vertical binds a portrait page on its long- // edge, Horizontal on its short edge (checked against a PCL driver's @PJL SET BINDING).- let script = include_str!("windows_print.ps1").replace("\r\n", "\n");- assert!(script.contains("'long-edge' { [System.Drawing.Printing.Duplex]::Vertical }"));- assert!(script.contains("'short-edge' { [System.Drawing.Printing.Duplex]::Horizontal }"));-}--#[test]-fn the_windows_job_is_the_environment_of_the_print_script() {- let path = std::path::Path::new("C:\\Users\\me\\AppData\\Local\\Temp\\pdfcraft-print-42.pdf");- let job = Job {- printer: Some("HP \"Laser\" Jet".into()),- copies: 3,- duplex: Duplex::ShortEdge,- grayscale: true,- title: "Angebot.pdf".into(),- ..Job::default()- };- let vars = windows_env_vars(path, &job);- let env = |key: &str| vars.iter().find(|(k, _)| k == key).map(|(_, v)| v.as_str()).unwrap();- assert_eq!(env("PDFCRAFT_PRINT_FILE"), "C:\\Users\\me\\AppData\\Local\\Temp\\pdfcraft-print-42.pdf");- // Quotes and spaces in a printer name survive because nothing goes on the command line.- assert_eq!(env("PDFCRAFT_PRINT_PRINTER"), "HP \"Laser\" Jet");- assert_eq!(env("PDFCRAFT_PRINT_COPIES"), "3");- assert_eq!(env("PDFCRAFT_PRINT_COLLATE"), "1");- assert_eq!(env("PDFCRAFT_PRINT_DUPLEX"), "short-edge");- assert_eq!(env("PDFCRAFT_PRINT_GRAYSCALE"), "1");- assert_eq!(env("PDFCRAFT_PRINT_TITLE"), "Angebot.pdf");- // No printer chosen means the system default: an empty name, not the word "default".- let one = |j: &Job, key: &str| windows_env_vars(path, j).into_iter().find(|(k, _)| k == key).unwrap().1;- assert_eq!(one(&Job::default(), "PDFCRAFT_PRINT_PRINTER"), "");- assert_eq!(one(&Job { duplex: Duplex::Off, ..Job::default() }, "PDFCRAFT_PRINT_DUPLEX"), "off");- assert_eq!(one(&Job { duplex: Duplex::LongEdge, ..Job::default() }, "PDFCRAFT_PRINT_DUPLEX"), "long-edge");-}--/// Run a PowerShell script for the Windows-only tests: its stdout, or everything it said when-/// it failed — the tests print that as the skip reason.-#[cfg(windows)]-fn windows_powershell(script: &str, envs: &[(&str, &str)]) -> Result<String, String> {- let mut c = std::process::Command::new("powershell");- c.args(["-NoProfile", "-NonInteractive", "-Command", script]);- for (k, v) in envs {- c.env(k, v);- }- match c.output() {- Ok(o) if o.status.success() => Ok(String::from_utf8_lossy(&o.stdout).into_owned()),- Ok(o) => Err(format!("{} {}", String::from_utf8_lossy(&o.stderr).trim(), String::from_utf8_lossy(&o.stdout).trim())),- Err(e) => Err(e.to_string()),- }-}--/// Windows: the printer list comes from the spooler. A bare machine may have no printer; the-/// list that exists has real names and at most one default.-#[cfg(windows)]-#[test]-fn windows_lists_the_printers_the_system_knows() {- let printers = spool::printers();- assert!(printers.iter().all(|p| !p.name.trim().is_empty()), "{printers:?}");- assert!(printers.iter().filter(|p| p.default).count() <= 1, "{printers:?}");-}--/// Windows: PowerShell is started by its full path under System32, never by its bare name.-/// Rust resolves a bare name in the app's own folder first, so a `powershell.exe` beside a-/// portable install would run instead, for every printer list and every job.-#[cfg(windows)]-#[test]-fn windows_starts_powershell_by_its_full_path() {- let c = crate::spool::powershell_command("$null");- let program = std::path::Path::new(c.get_program());- assert!(program.is_absolute(), "{program:?}");- assert!(program.ends_with("System32/WindowsPowerShell/v1.0/powershell.exe"), "{program:?}");- assert!(program.is_file(), "{program:?}");-}--/// Windows: the embedded print script is valid PowerShell, checked on every machine — including-/// runners that have no printer to print to.-#[cfg(windows)]-#[test]-fn the_windows_print_script_parses() {- let path = std::env::temp_dir().join(format!("pdfcraft-print-script-{}.ps1", std::process::id()));- std::fs::write(&path, spool::WINDOWS_PRINT_SCRIPT).unwrap();- let errors = windows_powershell(- "$tokens = $null; $errors = $null; [System.Management.Automation.Language.Parser]::ParseFile($env:PDFCRAFT_TEST_SCRIPT, [ref]$tokens, [ref]$errors) > $null; $errors.Count",- &[("PDFCRAFT_TEST_SCRIPT", path.to_str().unwrap())],- );- let _ = std::fs::remove_file(&path);- assert_eq!(errors.as_deref().map(str::trim), Ok("0"), "parse errors: {errors:?}");-}--/// Windows, end to end: the script renders the job's sheets with Windows.Data.Pdf on any-/// machine — CI included, no printer needed (the dry run writes the PNGs to the temporary-/// folder) — and, where a paused test printer can be added, a real job lands in its queue.-/// Its driver is the inbox "Generic / Text Only"; a machine that cannot add one (no rights, no-/// driver) skips that half, as the CUPS tests skip where CUPS isn't running.-#[cfg(windows)]-#[test]-fn the_print_script_renders_the_job_and_reaches_the_spooler() {- let pdf = impose(&fixture(2), &settings(vec![0, 1], Layout::Size(SizeMode::Fit))).unwrap();- // The printer name is deliberately wrong: the dry run stops before the driver is touched.- let job = Job { printer: Some("no such printer".into()), title: "test.pdf".into(), ..Job::default() };- let dry = spool::windows_submit(&pdf, &job, &[("PDFCRAFT_PRINT_DRYRUN", "1")]);- assert_eq!(dry.as_deref(), Ok("rendered 2 sheet(s)"), "{dry:?}");-- const NAME: &str = "PdfCraft Test Print";- let added = windows_powershell(- &format!(- "if (-not (Get-Printer -Name '{NAME}' -ErrorAction SilentlyContinue)) {{ Add-Printer -Name '{NAME}' -DriverName 'Generic / Text Only' -PortName 'FILE:' }}; Set-Printer -Name '{NAME}' -IsPaused $true"- ),- &[],- );- if let Err(why) = added {- eprintln!("skipping the real print: the test printer could not be prepared: {why}");- return;- }- let job = Job { printer: Some(NAME.into()), title: "test.pdf".into(), ..Job::default() };- let sent = spool::submit(&pdf, &job);- let queued = windows_powershell(- "if (Get-PrintJob -Name 'PdfCraft Test Print') { (Get-PrintJob -Name 'PdfCraft Test Print' | Measure-Object).Count } else { 0 }",- &[],- );- let cleaned = windows_powershell("Get-PrintJob -Name 'PdfCraft Test Print' | Remove-PrintJob; Remove-Printer -Name 'PdfCraft Test Print'", &[]);- assert!(sent.is_ok(), "{sent:?}");- assert_eq!(queued.as_deref().map(str::trim), Ok("1"), "the job is in the paused printer's queue: {queued:?}");- assert!(cleaned.is_ok(), "the test printer is removed again: {cleaned:?}");-}-/// A PPD shaped like a Fiery's: installable options, multi-line PostScript in the choices, Latin-1/// labels, options the Print dialog sets itself.const FIERY_PPD: &[u8] = b"*PPD-Adobe: \"4.3\"\n\