PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust
Integrate remaining six PdfCraft parity PRs with conflict resolutions
FredApps7d3d4830e5ef
diff --cc Cargo.lockindex 62a997067,8fd7c9133,c4f57c026,4f8e8ac8c,8fd7c9133,efe448b11,efe448b11..cfcb9dc36--- a/Cargo.lock+++ b/Cargo.lock@@@@@@@@ -4331,17 -4330,15 -4331,15 -4330,14 -4330,15 -4331,17 -4331,17 +4332,18 @@@@@@@@ dependencies =[[package]]name = "pdfcraft-create"- version = "0.14.0"+ version = "0.15.0"dependencies = ["encoding_rs",++++++ "hayro-ccitt",+++++ "hayro-jbig2","hayro-syntax","image","pdfcraft-cos",++++ "pdfcraft-filters","pdfcraft-fonts","pdfcraft-model",+ "pdfcraft-xfa","png 0.18.1","thiserror 2.0.21","tiff",@@@@@@@@ -4427,11 -4422,9 -4423,9 -4421,9 -4422,9 -4425,12 -4425,12 +4429,12 @@@@@@@@ dependencies =[[package]]name = "pdfcraft-filters"- version = "0.14.0"+ version = "0.15.0"dependencies = [++++ "fax","flate2",++++ "hayro-ccitt",+++++ "hayro-jbig2","proptest","thiserror 2.0.21","weezl 0.2.1",diff --cc Cargo.tomlindex d374218fd,64a3cf5b6,493896336,f86ebaa15,64a3cf5b6,6dafba9ee,6dafba9ee..1b04ab526--- a/Cargo.toml+++ b/Cargo.toml@@@@@@@@ -23,42 -23,41 -23,42 -23,41 -23,41 -23,41 -23,41 +23,42 @@@@@@@@ craft-keymap = { git = "https://github.craft-print = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545" }# Whether a path stored in a document may be opened (GoToR link targets).craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545" }- ----craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545", features = ["egui"] }+ ++++# craft-update: app-specific pretend versions apply to startup and manual checks.+ ++++craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "04aa1703b32d299e54f78fcde4182f2b393a9116", features = ["egui"] }# internal- pdfcraft-geom = { path = "crates/geom", version = "0.14.0" }- pdfcraft-filters = { path = "crates/filters", version = "0.14.0" }- pdfcraft-cos = { path = "crates/cos", version = "0.14.0" }- pdfcraft-crypt = { path = "crates/crypt", version = "0.14.0" }- pdfcraft-organize = { path = "crates/organize", version = "0.14.0" }- pdfcraft-measure = { path = "crates/measure", version = "0.14.0" }- pdfcraft-annot = { path = "crates/annot", version = "0.14.0" }- pdfcraft-audit = { path = "crates/audit", version = "0.14.0" }- pdfcraft-fonts = { path = "crates/fonts", version = "0.14.0" }- pdfcraft-model = { path = "crates/model", version = "0.14.0" }- pdfcraft-content = { path = "crates/content", version = "0.14.0" }- pdfcraft-redact = { path = "crates/redact", version = "0.14.0" }- pdfcraft-print = { path = "crates/print", version = "0.14.0" }- pdfcraft-xfdf = { path = "crates/xfdf", version = "0.14.0" }- pdfcraft-sign = { path = "crates/sign", version = "0.14.0" }- pdfcraft-optimize = { path = "crates/optimize", version = "0.14.0" }- pdfcraft-a11y = { path = "crates/a11y", version = "0.14.0" }- pdfcraft-oracle = { path = "crates/oracle", version = "0.14.0" }- pdfcraft-testkit = { path = "crates/testkit", version = "0.14.0" }- pdfcraft-ocr = { path = "crates/ocr", version = "0.14.0" }- pdfcraft-js = { path = "crates/js", version = "0.14.0" }- pdfcraft-compare = { path = "crates/compare", version = "0.14.0" }- pdfcraft-preflight = { path = "crates/preflight", version = "0.14.0" }- pdfcraft-export = { path = "crates/export", version = "0.14.0" }- pdfcraft-edit = { path = "crates/edit", version = "0.14.0" }- pdfcraft-create = { path = "crates/create", version = "0.14.0" }- pdfcraft-forms = { path = "crates/forms", version = "0.14.0" }- pdfcraft-xfa = { path = "crates/xfa", version = "0.14.0" }- pdfcraft-render = { path = "crates/render", version = "0.14.0" }- pdfcraft-engine = { path = "crates/engine", version = "0.14.0" }- pdfcraft-platform = { path = "crates/platform", version = "0.14.0" }- pdfcraft-ui-egui = { path = "crates/ui-egui", version = "0.14.0" }- pdfcraft-automation = { path = "crates/automation", version = "0.14.0", default-features = false }+ pdfcraft-geom = { path = "crates/geom", version = "0.15.0" }+ pdfcraft-filters = { path = "crates/filters", version = "0.15.0" }+ pdfcraft-cos = { path = "crates/cos", version = "0.15.0" }+ pdfcraft-crypt = { path = "crates/crypt", version = "0.15.0" }+ pdfcraft-organize = { path = "crates/organize", version = "0.15.0" }+ pdfcraft-measure = { path = "crates/measure", version = "0.15.0" }+ pdfcraft-annot = { path = "crates/annot", version = "0.15.0" }+ pdfcraft-audit = { path = "crates/audit", version = "0.15.0" }+ pdfcraft-fonts = { path = "crates/fonts", version = "0.15.0" }+ pdfcraft-model = { path = "crates/model", version = "0.15.0" }+ pdfcraft-content = { path = "crates/content", version = "0.15.0" }+ pdfcraft-redact = { path = "crates/redact", version = "0.15.0" }+ pdfcraft-print = { path = "crates/print", version = "0.15.0" }+ pdfcraft-xfdf = { path = "crates/xfdf", version = "0.15.0" }+ pdfcraft-sign = { path = "crates/sign", version = "0.15.0" }+ pdfcraft-optimize = { path = "crates/optimize", version = "0.15.0" }+ pdfcraft-a11y = { path = "crates/a11y", version = "0.15.0" }+ pdfcraft-oracle = { path = "crates/oracle", version = "0.15.0" }+ pdfcraft-testkit = { path = "crates/testkit", version = "0.15.0" }+ pdfcraft-ocr = { path = "crates/ocr", version = "0.15.0" }+ pdfcraft-js = { path = "crates/js", version = "0.15.0" }+ pdfcraft-compare = { path = "crates/compare", version = "0.15.0" }+ pdfcraft-preflight = { path = "crates/preflight", version = "0.15.0" }+ pdfcraft-export = { path = "crates/export", version = "0.15.0" }+ pdfcraft-edit = { path = "crates/edit", version = "0.15.0" }+ pdfcraft-create = { path = "crates/create", version = "0.15.0" }+ pdfcraft-forms = { path = "crates/forms", version = "0.15.0" }+ pdfcraft-xfa = { path = "crates/xfa", version = "0.15.0" }+ pdfcraft-render = { path = "crates/render", version = "0.15.0" }+ pdfcraft-engine = { path = "crates/engine", version = "0.15.0" }+ pdfcraft-platform = { path = "crates/platform", version = "0.15.0" }+ pdfcraft-ui-egui = { path = "crates/ui-egui", version = "0.15.0" }+ pdfcraft-automation = { path = "crates/automation", version = "0.15.0", default-features = false }hayro = "0.7.1"@@@@@@@@ -66,11 -65,6 -66,6 -65,6 -65,6 -65,12 -65,12 +66,11 @@@@@@@@ hayro-syntax = "0.7.2lopdf = "0.45"flate2 = { version = "1.1", default-features = false, features = ["rust_backend"] }weezl = "0.2"++++ # CCITT Group 4 encoding (pdfcraft-filters); already in the tree through tiff.++++ fax = "0.2.7"- # CCITT fax decoding (pdfcraft-filters' decode_ccitt), also the independent decoder in its- # encoder's round-trip tests; already in the tree through hayro.--# CCITT and JBIG2 decoders, already in the tree through hayro: independent decoders for round-trip--# tests, and JBIG2 for Export ▸ Images.+++++++# Independent CCITT and JBIG2 codecs, already in the tree through hayro.++++ hayro-ccitt = "0.3"+++++ hayro-jbig2 = "0.3"# foundationthiserror = "2"diff --cc ROADMAP.mdindex 6d261cc1f,795dff292,b65b677da,f5de8044e,858ab719c,f2fa3e25a,6ae5a40a2..069612ba3--- a/ROADMAP.md+++ b/ROADMAP.md@@@@@@@@ -1,9 -1,7 -1,7 -1,7 -1,8 -1,7 -1,7 +1,10 @@@@@@@@# PdfCraft roadmap++++++> **Last reviewed:** 2026-10-15 · **Last updated:** 2026-10-15 · **Change:** minor (typed small Edit font sizes and Fill & Sign text/date colour, #2444/#2496; estimates unchanged)++++++**Stage: alpha** · next: beta, ~25% (ready for real work 50% → 75%) and ~400–700 h away++++ ++> **Last reviewed:** 2026-10-29 | **Last updated:** 2026-10-29 | **Change:** minor (M7 #2517: a narrowed then widened paragraph keeps the typed spaces the wrap consumed, after save and reopen; estimates unchanged)> **Last reviewed:** 2026-10-27 | **Last updated:** 2026-10-27 | **Change:** minor (M10: OCR model downloads use verified ONNX pairs with legacy discovery fallback; estimates unchanged)> **Last reviewed:** 2026-10-25 | **Last updated:** 2026-10-25 | **Change:** minor (M14 localization current state: Arabic logical catalog, explicit RTL label direction and mirrored stock chrome; native/browser RTL workflows unqualified. Native release Hans face via LXGW WenKai Lite; estimates unchanged)> **Last reviewed:** 2026-10-23 · **Last updated:** 2026-10-23 · **Change:** minor (M7, #2636 partial: pasting added text boxes and images in the engine and through `content_copy`; estimates unchanged)@@@@@@@@ -202,16 -200,12 -200,11 -200,11 -202,14 -200,13 -200,14 +204,22 @@@@@@@@ Ranked; detail and the full milestone t## Progress log++++ ++- **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-27 (M10, OCR models):** Model staging downloads and verifies the ONNX pair after the upstream RTEN URL brownout; runtime discovery prefers complete ONNX pairs per directory, retains complete RTEN fallback and preserves directory precedence.++++++- **2026-10-25 (M5, comment replies):** One reply can be deleted from the Comments panel without its thread. On the selected card each reply has its own "…" menu (Edit, Copy text, Delete); Delete takes that reply with its pop-up and the replies to it, as `comment_delete` already did headlessly, and the comment and its other replies stay. The card stays selected, and the panel's editor stays open, on what they were on though the delete moved it in `/Annots`. Undo and Redo close the editor, since either can move what it was open on. A locked reply can't be deleted. Estimates unchanged.- **2026-10-24 (M10, #4158 partial):** Word, HTML, RTF and PowerPoint export keep a block that continues another on its line (an italic case name, a link, a superscript) as a run in its own style inside that paragraph, with the source's word space, instead of a paragraph of its own. Style changes that wrap onto the next line still split paragraphs (the reading blocks keep style boundaries). Estimates unchanged.- **2026-10-24 (M3, window move on Wayland, #3970 follow-up):** After a move or resize by PdfCraft's own title bar or edges, the button release given back to egui goes before the pointer leaving the window, so hover no longer sticks at the old place until the pointer moves. Found by CodeRabbit in review of #3970; a unit test covers it. Estimates unchanged.- **2026-10-24 (M14, #4253):** The annotation quick bar remembers Keep tool selected across restarts, including unpinning. Old and malformed settings keep safe defaults; the opt-in UI control channel reads and changes the same preference. Estimates unchanged.---++++ ++- **2026-10-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.@@@@@@@@ -758,7 -749,3 -748,7 -748,3 -753,3 -750,3 -751,3 +766,10 @@@@@@@@ Newest first: the date, what moved, an- **2026-10-18 (renderer, hayro patches 19/35):** A mesh shading (types 4–7) is sampled over its own triangles instead of the whole path: a BricsCAD plan with 310 one-triangle `sh` fills took 2 s per 1024 px tile at every zoom (and hit the 20 s watchdog on a busy machine); now about 70 ms, so zooming into dense topology drawings stays fluid. Estimates unchanged.- **2026-10-22 (PR #3227 integration):** M11: integrate upstream `80b7d215`; retain partial target-version compatibility and upstream content-boundary and image-size regression coverage. Scope and estimates unchanged.+ ++++++++++## Pages sidebar keyboard refresh (2026-10-30)++++++++++++PR #2133 retains document-local Pages sidebar focus for Ctrl/Cmd+A and Escape after the UI module split. The selection does not navigate. The focused regression is in `crates/ui-egui/tests/it/view.rs`; current-head hosted validation is pending. Feature counts and estimates are unchanged.++ ++++## Button export-value refresh (2026-10-30)++ ++++++ ++++PR #1952 retains per-widget checkbox/radio export-value editing in the split form-authoring and Prepare modules. Caption editing remains supported. Tests cover preserved appearances and selection, invalid/locked refusals, data-format round trips, and Apply/Cancel/Undo. Current-head hosted validation is pending; feature estimates are unchanged.diff --cc crates/automation/src/dispatch.rsindex 63602e52d,b136076bc,b136076bc,52af9bda1,b56b04d92,b136076bc,b136076bc..36e0d0045--- a/crates/automation/src/dispatch.rs+++ b/crates/automation/src/dispatch.rs@@@@@@@@ -1,7 -1,7 -1,7 -1,7 -1,7 -1,7 -1,7 +1,7 @@@@@@@@use super::error::{Result, ToolError, failed};- use super::json::{Args, document_attachment_keys, info, one_based, parse_style_ranges, security, summary};+ use super::json::{Args, document_attachment_keys, info, one_based, parse_style_ranges, security, summary, text_style_levels};use super::paths::{read_input, write_atomic};--- ---use super::{Arc, Automation, Edit, Value, block_overlapping, comments, json, tools};+++ +++use super::{Arc, Automation, Edit, Value, block_overlapping, comments, content, json, tools};/// One piece of a tool's result.#[derive(Clone, Debug, PartialEq)]@@@@@@@@ -538,7 -538,7 -538,7 -510,10 -538,17 -538,7 -538,7 +538,15 @@@@@@@@ impl Automation};let index = self.paragraph_index(id, page, k, &blocks)?;let block = blocks.get(index).cloned().ok_or_else(|| ToolError::InvalidArgs(format!("paragraph {k} is out of range")))?;--- -- let text = a.opt_str("text")?.map(str::to_owned).unwrap_or(block.text);- // `aligns` counts rows, so without new text the paragraph keeps its rows (the- // editor text); otherwise its text joined with spaces is rewrapped.- let own = if a.get("aligns").is_some() { block.editor_text } else { block.text };- let text = a.opt_str("text")?.map(str::to_owned).unwrap_or(own);++++ ++ let width = a.opt_num("width")?;- // A width change with no new text is the box-edge drag. `reflow_text` rejoins a- // wrap with the spaces it consumed and keeps a newline that was typed. `text`- // joins every row with one space, so that drag would turn two typed spaces into- // one (#2529). A move or a formatting change still uses `text`: those edits are- // what the stale-paragraph checks regroup with, and they are not a reflow.+++++++ // Explicit row alignments keep the editor's row boundaries; a width-only+++++++ // reflow rejoins soft wraps while retaining typed newlines and spaces.++++ ++ let text = match a.opt_str("text")? {++++ ++ Some(text) => text.to_owned(),+++++++ None if a.get("aligns").is_some() => block.editor_text,++++ ++ None if width.is_some() => block.reflow_text.clone(),++++ ++ None => block.text,++++ ++ };let mut style = pdfcraft_engine::BlockStyle {ranges: parse_style_ranges(a.get("ranges"))?,resource: a.opt_str("font_resource")?.map(str::to_owned),diff --cc crates/automation/src/documents.rsindex 835547968,476c45102,476c45102,476c45102,476c45102,83790afed,83790afed..859c92da4--- a/crates/automation/src/documents.rs+++ b/crates/automation/src/documents.rs@@@@@@@@ -279,8 -279,7 -279,7 -279,7 -279,7 -279,7 -279,7 +279,8 @@@@@@@@ impl Automation}pub(crate) fn doc_optimize(&mut self, a: &Args) -> Result<Value> {---- use pdfcraft_engine::optimize::{Compatibility, Compression, ImageSettings, Preset};++++ use pdfcraft_engine::optimize::{Compatibility, Compression, ImageSettings, MonoCompression, Preset};++++++ const MONO_KEYS: [&str; 4] = ["downsample", "ppi", "above_ppi", "compression"];let id = self.doc(a)?.id;let before = self.doc(a)?.bytes.len();let path = self.resolve(a.str("path")?, true)?;@@@@@@@@ -318,37 -317,6 -317,6 -317,6 -317,6 -317,23 -317,23 +318,38 @@@@@@@@};settings.color = images("color", settings.color)?;settings.gray = images("gray", settings.gray)?;++++ if let Some(mono) = a.get("mono") {- let unknown = |c: &Value| ToolError::InvalidArgs(format!("unknown mono compression {c} (ccitt_g4, retain)"));+++++ let unknown = |c: &Value| ToolError::InvalidArgs(format!("unknown mono compression {c} (ccitt_g4, jbig2, retain)"));-- let mono =-- mono.as_object().ok_or_else(|| ToolError::InvalidArgs("mono must be an object: { compression: ccitt_g4|jbig2|retain }".into()))?;++++++ let mono = mono.as_object().ok_or_else(|| {- ToolError::InvalidArgs("mono must be an object: { downsample, ppi, above_ppi, compression: ccitt_g4|retain }".into())+++++++ ToolError::InvalidArgs("mono must be an object: { downsample, ppi, above_ppi, compression: ccitt_g4|jbig2|retain }".into())++++++ })?;++++ // A misspelled key would otherwise leave the preset's setting in place unnoticed.-- if let Some(key) = mono.keys().find(|k| *k != "compression") {-- return Err(ToolError::InvalidArgs(format!("unknown mono key {key:?} (compression)")));++++++ if let Some(key) = mono.keys().find(|k| !MONO_KEYS.contains(&k.as_str())) {++++++ return Err(ToolError::InvalidArgs(format!("unknown mono key {key:?} ({})", MONO_KEYS.join(", "))));++++ }++++++ let m = &mut settings.mono;++++++ if let Some(d) = mono.get("downsample") {++++++ m.downsample = d.as_bool().ok_or_else(|| ToolError::InvalidArgs(format!("mono downsample must be true or false, not {d}")))?;++++++ }++++++ for (key, ppi) in [("ppi", &mut m.target_ppi), ("above_ppi", &mut m.above_ppi)] {++++++ if let Some(p) = mono.get(key) {++++++ *ppi = p++++++ .as_f64()++++++ .filter(|p| p.is_finite())++++++ .ok_or_else(|| ToolError::InvalidArgs(format!("mono {key} must be a number, not {p}")))?++++++ .clamp(9.0, 2400.0);++++++ }++++++ }++++++ m.above_ppi = m.above_ppi.max(m.target_ppi);++++ if let Some(c) = mono.get("compression") {-- settings.mono = match c.as_str() {++++++ m.compression = match c.as_str() {++++ Some("ccitt_g4" | "ccitt" | "g4") => MonoCompression::CcittG4,+++++ Some("jbig2") => MonoCompression::Jbig2,++++ Some("retain") => MonoCompression::Retain,++++ _ => return Err(unknown(c)),++++ };++++ }++++ }for (key, flag) in [("merge_fragments", &mut settings.merge_fragments),("discard_thumbnails", &mut settings.discard_thumbnails),diff --cc crates/automation/src/tools.rsindex 554496b4b,ceb64fa17,308db977d,196808130,53c4582af,ffc17cb45,ffc17cb45..c6c200cec--- a/crates/automation/src/tools.rs+++ b/crates/automation/src/tools.rs@@@@@@@@ -1278,7 -1274,7 -1275,7 -1243,7 -1274,7 -1274,7 -1274,7 +1281,7 @@@@@@@@ pub fn tools() -> Vec<ToolDef>.ro().cmd("ocr.recognize").with(schema(json!({}), &[])),- t("doc_export_all_images", "Export all images", "Write the images that pages use into a folder (`<name>_Page_<n>_Image_<k>.jpg|png`, n zero-padded to the page count's digits), each once: JPEG images unchanged, others as PNG with their soft mask as alpha. min_size skips images with fewer pixels on their shorter side. Images that can't be decoded yet (JPEG 2000, JBIG2, separations) are listed under skipped. Includes unsaved edits.")---- t("doc_export_all_images", "Export all images", "Write the images that pages use into a folder (`<name>_Page_<n>_Image_<k>.jpg|png`, n zero-padded to the page count's digits), each once: JPEG images unchanged, others as PNG with their soft mask as alpha. min_size skips images with fewer pixels on their shorter side. Images that can't be decoded yet (JPEG 2000, JBIG2, CCITT, separations) are listed under skipped. Includes unsaved edits.")-- t("doc_export_all_images", "Export all images", "Write the images that pages use into a folder (`<name>_Page_<n>_Image_<k>.jpg|png`, n zero-padded to the page count's digits), each once: JPEG images unchanged, others as PNG with their soft mask as alpha. min_size skips images with fewer pixels on their shorter side. Images that can't be decoded yet (JPEG 2000, CCITT, separations) are listed under skipped. Includes unsaved edits.")+++++++ t("doc_export_all_images", "Export all images", "Write the images that pages use into a folder (`<name>_Page_<n>_Image_<k>.jpg|png`, n zero-padded to the page count's digits), each once: JPEG images unchanged, others as PNG with their soft mask as alpha. min_size skips images with fewer pixels on their shorter side. Images that can't be decoded yet (JPEG 2000, JBIG2 inside other filters, separations) are listed under skipped. Includes unsaved edits.").cmd("export.all_images").with(schema(json!({@@@@@@@@ -1337,7 -1332,7 -1333,7 -1301,7 -1332,7 -1332,7 -1332,7 +1340,7 @@@@@@@@}),&["from"],)),---- t("doc_reduce", "Reduce file size", "Write a smaller copy of the document to `path` with Acrobat's Reduce File Size choices: images above 225 ppi downsampled to 150 ppi and JPEG-compressed (medium quality), thumbnails dropped, identical fonts and images merged, unused objects dropped, compressed object streams. If the copy wouldn't be smaller, nothing is written and `written` is false. The open document is unchanged.")-- t("doc_reduce", "Reduce file size", "Write a smaller copy of the document to `path` with Acrobat's Reduce File Size choices: colour and grey images above 225 ppi downsampled to 150 ppi and JPEG-compressed (medium quality), black-and-white images stored as CCITT Group 4 whenever that is smaller, thumbnails dropped, identical fonts and images merged, unused objects dropped, compressed object streams. If the copy wouldn't be smaller, nothing is written and `written` is false. The open document is unchanged.")++++++ t("doc_reduce", "Reduce file size", "Write a smaller copy of the document to `path` with Acrobat's Reduce File Size choices: colour and grey images above 225 ppi downsampled to 150 ppi and JPEG-compressed (medium quality), black-and-white images averaged down to 300 ppi above 450 ppi and each stored as CCITT Group 4 (or 1-bit Flate, once resampled or packed from more bits) whenever that is smaller, thumbnails dropped, identical fonts and images merged, unused objects dropped, compressed object streams. If the copy wouldn't be smaller, nothing is written and `written` is false. The open document is unchanged.").cmd("optimize.reduce").with(schema(json!({ "doc": doc(), "path": { "type": "string" } }), &["doc", "path"])),t("doc_initial_view", "Initial view", "Read or change how the document opens (Document Properties ▸ Initial View) and its reading options: navigation (page, bookmarks, pages, attachments, layers), layout (default, single, continuous, two_up, two_up_continuous, two_up_cover, two_up_continuous_cover), magnification (default, actual, fit_page, fit_width, fit_height, fit_visible, or a percentage), page, window options (fit_window, center_window, full_screen, display_title), interface options (hide_menubar, hide_toolbar, hide_window_ui), language and binding (left, right). Only the given ones change; returns the result. Undoable.").with(schema(@@@@@@@@ -1438,7 -1433,7 -1434,7 -1403,7 -1433,7 -1433,7 -1433,7 +1442,7 @@@@@@@@.with(schema(json!({ "doc": doc() }), &["doc"])),t("doc_open_revision", "Open a revision", "Open saved revision `revision` (1 = the oldest) of a document as a new, unsaved document, to see the file as it was then.").with(schema(json!({ "doc": doc(), "revision": { "type": "integer", "minimum": 1 } }), &["doc", "revision"])),- t("doc_optimize", "Optimize PDF", "Write an optimized copy to `path` (Acrobat's PDF Optimizer). preset: standard (default; Reduce File Size's choices) or mobile (images to 96 ppi above 144, JPEG high quality); the options below change it. compatibility: retain (default; keeps the document's version, or 1.5 when object streams are written), 1.4, 1.5, 1.6, 1.7 or 2.0. merge_fragments (default true) first puts a page picture drawn as many stacked image strips (as some PDF printers write it) back together into one image, so it can be resampled (merged_images, fragments_merged). color / gray: { downsample, ppi, above_ppi, compression: jpeg|zip|retain, quality 1–100 } (defaults: downsample to 150 ppi above 225, JPEG 60). mono: { downsample, ppi, above_ppi, compression: ccitt_g4|retain } for black-and-white images and image masks (default: averaged down to 300 ppi above 450 ppi, counted in images_resampled; stored losslessly as CCITT Group 4 (or 1-bit Flate, once resampled or packed from more bits) when that is smaller, Group 3 fax images, black-and-white RGB and indexed images using only palette entries 0 and 1 among them, counted in images_recompressed; retain resamples only, a CCITT image staying CCITT and any other becoming Flate). Images are measured where pages draw them and replaced only when smaller. discard_*: thumbnails (default true), alternate_images (true), tags, print_settings; flate_unencoded (true); object_streams (default true; always off for 1.4); lzw_to_flate (true) decodes LZW streams and stores them with Flate instead, leaving any it cannot decode unchanged (lzw_streams counts the streams converted); remove_invalid_links and remove_unreferenced_dests (true); images and forms the pages list but never draw are always dropped (unused_xobjects). discard: Remove Hidden Information categories (metadata, attachments, comments, form-fields, hidden-text, hidden-layers, bookmarks, links-actions-scripts, private-data). Signed documents are refused. The open document is unchanged.")---- t("doc_optimize", "Optimize PDF", "Write an optimized copy to `path` (Acrobat's PDF Optimizer). preset: standard (default; Reduce File Size's choices) or mobile (images to 96 ppi above 144, JPEG high quality); the options below change it. compatibility: retain (default; keeps the document's version, or 1.5 when object streams are written), 1.4, 1.5, 1.6, 1.7 or 2.0. merge_fragments (default true) first puts a page picture drawn as many stacked image strips (as some PDF printers write it) back together into one image, so it can be resampled (merged_images, fragments_merged). color / gray: { downsample, ppi, above_ppi, compression: jpeg|zip|retain, quality 1–100 } (defaults: downsample to 150 ppi above 225, JPEG 60). Images are measured where pages draw them and replaced only when smaller. discard_*: thumbnails (default true), alternate_images (true), tags, print_settings; flate_unencoded (true); object_streams (default true; always off for 1.4); lzw_to_flate (true) decodes LZW streams and stores them with Flate instead, leaving any it cannot decode unchanged (lzw_streams counts the streams converted); remove_invalid_links and remove_unreferenced_dests (true); images and forms the pages list but never draw are always dropped (unused_xobjects). discard: Remove Hidden Information categories (metadata, attachments, comments, form-fields, hidden-text, hidden-layers, bookmarks, links-actions-scripts, private-data). Signed documents are refused. The open document is unchanged.")-- t("doc_optimize", "Optimize PDF", "Write an optimized copy to `path` (Acrobat's PDF Optimizer). preset: standard (default; Reduce File Size's choices) or mobile (images to 96 ppi above 144, JPEG high quality); the options below change it. compatibility: retain (default; keeps the document's version, or 1.5 when object streams are written), 1.4, 1.5, 1.6, 1.7 or 2.0. merge_fragments (default true) first puts a page picture drawn as many stacked image strips (as some PDF printers write it) back together into one image, so it can be resampled (merged_images, fragments_merged). color / gray: { downsample, ppi, above_ppi, compression: jpeg|zip|retain, quality 1–100 } (defaults: downsample to 150 ppi above 225, JPEG 60). mono: { compression: ccitt_g4|jbig2|retain } (default ccitt_g4: black-and-white images and image masks are stored losslessly as CCITT Group 4, or with jbig2 as lossless JBIG2, usually smaller still, when that is smaller than the image as it is; counted in images_recompressed). Images are measured where pages draw them and replaced only when smaller. discard_*: thumbnails (default true), alternate_images (true), tags, print_settings; flate_unencoded (true); object_streams (default true; always off for 1.4); lzw_to_flate (true) decodes LZW streams and stores them with Flate instead, leaving any it cannot decode unchanged (lzw_streams counts the streams converted); remove_invalid_links and remove_unreferenced_dests (true); images and forms the pages list but never draw are always dropped (unused_xobjects). discard: Remove Hidden Information categories (metadata, attachments, comments, form-fields, hidden-text, hidden-layers, bookmarks, links-actions-scripts, private-data). Signed documents are refused. The open document is unchanged.")+++++++ t("doc_optimize", "Optimize PDF", "Write an optimized copy to `path` (Acrobat's PDF Optimizer). preset: standard (default; Reduce File Size's choices) or mobile (images to 96 ppi above 144, JPEG high quality); the options below change it. compatibility: retain (default; keeps the document's version, or 1.5 when object streams are written), 1.4, 1.5, 1.6, 1.7 or 2.0. merge_fragments (default true) first puts a page picture drawn as many stacked image strips (as some PDF printers write it) back together into one image, so it can be resampled (merged_images, fragments_merged). color / gray: { downsample, ppi, above_ppi, compression: jpeg|zip|retain, quality 1–100 } (defaults: downsample to 150 ppi above 225, JPEG 60). mono: { downsample, ppi, above_ppi, compression: ccitt_g4|jbig2|retain } for black-and-white images and image masks (default: averaged down to 300 ppi above 450 ppi, counted in images_resampled; stored losslessly as CCITT Group 4 or JBIG2 (or 1-bit Flate, once resampled or packed from more bits) when that is smaller, Group 3 fax images, black-and-white RGB and indexed images using only palette entries 0 and 1 among them, counted in images_recompressed; retain resamples only, a CCITT image staying CCITT and any other becoming Flate). Images are measured where pages draw them and replaced only when smaller. discard_*: thumbnails (default true), alternate_images (true), tags, print_settings; flate_unencoded (true); object_streams (default true; always off for 1.4); lzw_to_flate (true) decodes LZW streams and stores them with Flate instead, leaving any it cannot decode unchanged (lzw_streams counts the streams converted); remove_invalid_links and remove_unreferenced_dests (true); images and forms the pages list but never draw are always dropped (unused_xobjects). discard: Remove Hidden Information categories (metadata, attachments, comments, form-fields, hidden-text, hidden-layers, bookmarks, links-actions-scripts, private-data). Signed documents are refused. The open document is unchanged.").cmd("optimize.advanced").with(schema(json!({diff --cc crates/automation/tests/it/automation.rsindex a3cd8dcd3,040d20ae5,01d0d1eb2,e3114dfe3,3772f2fb7,f41519aff,f41519aff..d6c058b8f--- a/crates/automation/tests/it/automation.rs+++ b/crates/automation/tests/it/automation.rs@@@@@@@@ -5119,23 -5058,168 -5058,23 -4940,6 -5058,23 -5058,23 -5058,23 +5119,168 @@@@@@@@ fn the_calculation_order_is_read_fixed_assert_eq!((value(&mut a, "total"), value(&mut a, "tax")), (json!("0"), json!("0")), "undone with the values it recalculated");}+ +++++/// A malformed form with two calculated fields named `dup`, one summing `src`, the other `x`.+ +++++fn two_calculations_with_one_name() -> Vec<u8> {+ +++++ let widget = |name: &str, y: u32, reads: &str| {+ +++++ format!(+ +++++ "<< /Type /Annot /Subtype /Widget /FT /Tx /T ({name}) /Rect [50 {y} 250 {}] /P 3 0 R /AA << /C << /S /JavaScript /JS (AFSimple_Calculate\\(\"SUM\", \"{reads}\"\\);) >> >> >>",+ +++++ y + 20+ +++++ )+ +++++ };+ +++++ pdf_of(&[+ +++++ "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>",+ +++++ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>",+ +++++ "<< /Type /Page /Parent 2 0 R /Annots [5 0 R 6 0 R 7 0 R 8 0 R] >>",+ +++++ "<< /Fields [5 0 R 6 0 R 7 0 R 8 0 R] /DA (/Helv 0 Tf 0 g) /CO [6 0 R 7 0 R 5 0 R] >>",+ +++++ &widget("dup", 700, "x"),+ +++++ &widget("dup", 660, "src"),+ +++++ &widget("src", 620, "x"),+ +++++ "<< /Type /Annot /Subtype /Widget /FT /Tx /T (x) /Rect [50 580 250 600] /P 3 0 R /V (3) >>",+ +++++ ])+ +++++}+ ++++++ +++++/// Each row of the calculation order gets its own field's formula, even where two fields share a+ +++++/// name (a malformed form): the first dup sums src, the second x.+ +++++#[test]+ +++++fn the_calculation_order_gives_each_field_its_own_formula() {+ +++++ let dir = workdir("calcdup");+ +++++ std::fs::write(dir.join("dup.pdf"), two_calculations_with_one_name()).unwrap();+ +++++ let mut a = auto(&dir);+ +++++ let doc = ok(&mut a, "doc_open", json!({ "path": "dup.pdf" }))["doc"].as_u64().unwrap();+ +++++ let r = ok(&mut a, "form_calculation_order", json!({ "doc": doc }));+ +++++ assert_eq!(r["calculation_order"], json!(["dup", "src", "dup"]));+ +++++ let formulas: Vec<Value> = r["fields"].as_array().unwrap().iter().map(|f| f["formula"].clone()).collect();+ +++++ assert_eq!(+ +++++ formulas,+ +++++ [json!({ "op": "sum", "fields": ["src"] }), json!({ "op": "sum", "fields": ["x"] }), json!({ "op": "sum", "fields": ["x"] })]+ +++++ );+ +++++}+ ++++++ +++++/// The calculation order through the tool shows each formula, in form_set_props's shape or as a+ +++++/// script, and flags a read of a field the form doesn't have and a script that builds the names+ +++++/// it reads; form_fields shows a custom script too.+ +++++#[test]+ +++++fn the_calculation_order_shows_formulas_and_what_they_cannot_read() {+ +++++ let dir = workdir("calcformulas");+ +++++ let mut a = auto(&dir);+ +++++ let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap();+ +++++ for (i, name) in ["qty", "price", "sub", "tax", "total"].into_iter().enumerate() {+ +++++ let y = 20 + 30 * i;+ +++++ ok(&mut a, "form_add_field", json!({ "doc": doc, "page": 1, "type": "text", "rect": [20, y, 180, y + 22], "name": name }));+ +++++ }+ +++++ let script = "event.value = getField(\"sub\").value / 10 + getField(\"row\" + 1).value;";+ +++++ ok(&mut a, "form_set_props", json!({ "doc": doc, "field": "sub", "calculate": { "notation": "qty * pric" } }));+ +++++ ok(&mut a, "form_set_script", json!({ "doc": doc, "field": "tax", "event": "calculate", "script": script }));+ +++++ ok(&mut a, "form_set_props", json!({ "doc": doc, "field": "total", "calculate": { "op": "sum", "fields": ["sub", "tax"] } }));+ +++++ let r = ok(&mut a, "form_calculation_order", json!({ "doc": doc }));+ +++++ assert_eq!(r["calculation_order"], json!(["sub", "tax", "total"]));+ +++++ let formulas: Vec<Value> = r["fields"].as_array().unwrap().iter().map(|f| f["formula"].clone()).collect();+ +++++ assert_eq!(formulas, [json!({ "notation": "qty * pric" }), json!({ "script": script }), json!({ "op": "sum", "fields": ["sub", "tax"] })]);+ +++++ assert_eq!(r["fields"][0]["issues"], json!([{ "issue": "missing_field", "field": "pric" }]));+ +++++ assert_eq!(r["fields"][1]["reads"], json!(["sub"]));+ +++++ assert_eq!(r["fields"][1]["issues"], json!([{ "issue": "built_names" }]));+ +++++ assert_eq!(r["fields"][2]["issues"], json!([]));+ +++++ assert_eq!(r["fixable"], false, "neither is an order to fix");+ +++++ let fields = ok(&mut a, "form_fields", json!({ "doc": doc }));+ +++++ let tax = fields["fields"].as_array().unwrap().iter().find(|f| f["name"] == "tax").unwrap();+ +++++ assert_eq!(tax["calculate"], json!({ "script": script }));+ +++++ // A script is set with form_set_script, and form_set_props says so, also when a notation+ +++++ // comes with it.+ +++++ for calculate in [json!({ "script": script }), json!({ "notation": "qty * 2", "script": script })] {+ +++++ let e = err(&mut a, "form_set_props", json!({ "doc": doc, "field": "tax", "calculate": calculate }));+ +++++ assert!(e.to_string().contains("form_set_script"), "{calculate}: {e}");+ +++++ }+ +++++}+ ++++++ +++++/// Every operation comes back from form_fields and form_calculation_order as form_set_props takes+ +++++/// it, so a formula can be read and given back: product and average came back as prd and avg,+ +++++/// which it refused.+ +++++#[test]+ +++++fn every_calculation_op_can_be_read_and_given_back() {+ +++++ let dir = workdir("calcops");+ +++++ let mut a = auto(&dir);+ +++++ let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap();+ +++++ for (name, y) in [("a", 20), ("b", 60), ("total", 100)] {+ +++++ ok(&mut a, "form_add_field", json!({ "doc": doc, "page": 1, "type": "text", "rect": [20, y, 180, y + 22], "name": name }));+ +++++ }+ +++++ for op in ["sum", "product", "average", "min", "max"] {+ +++++ let calculate = json!({ "op": op, "fields": ["a", "b"] });+ +++++ ok(&mut a, "form_set_props", json!({ "doc": doc, "field": "total", "calculate": calculate }));+ +++++ let fields = ok(&mut a, "form_fields", json!({ "doc": doc }));+ +++++ let shown = fields["fields"].as_array().unwrap().iter().find(|f| f["name"] == "total").unwrap()["calculate"].clone();+ +++++ let order = ok(&mut a, "form_calculation_order", json!({ "doc": doc }));+ +++++ assert_eq!((&shown, &order["fields"][0]["formula"]), (&calculate, &calculate), "{op}");+ +++++ ok(&mut a, "form_set_props", json!({ "doc": doc, "field": "total", "calculate": shown }));+ +++++ }+ +++++}+ ++++++ +++++/// form_set_props refuses a calculate or validate it would only partly apply (a key it doesn't+ +++++/// know, a value of the wrong type, a notation beside op and fields) as a bad argument, before+ +++++/// the edit runs, and changes nothing. A validate read back from form_fields, with null for the+ +++++/// bound it doesn't have, is taken back.+ +++++#[test]+ +++++fn calculate_and_validate_refuse_what_they_would_drop() {+ +++++ let dir = workdir("calcstrict");+ +++++ let mut a = auto(&dir);+ +++++ let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap();+ +++++ for (name, y) in [("a", 20), ("b", 60), ("total", 100)] {+ +++++ ok(&mut a, "form_add_field", json!({ "doc": doc, "page": 1, "type": "text", "rect": [20, y, 180, y + 22], "name": name }));+ +++++ }+ +++++ let set = json!({ "op": "sum", "fields": ["a", "b"] });+ +++++ ok(&mut a, "form_set_props", json!({ "doc": doc, "field": "total", "calculate": set, "validate": { "min": 0, "max": 10 } }));+ +++++ let total = |a: &mut Automation| {+ +++++ let fields = ok(a, "form_fields", json!({ "doc": doc }));+ +++++ fields["fields"].as_array().unwrap().iter().find(|f| f["name"] == "total").unwrap().clone()+ +++++ };+ +++++ for (calculate, says) in [+ +++++ (json!({ "notation": "a", "op": "sum", "fields": ["b"] }), "not both"),+ +++++ (json!({ "notation": "a", "op": "sum" }), "not both"),+ +++++ (json!({ "notation": "a", "fields": ["b"] }), "not both"),+ +++++ // A notation that wouldn't read back as itself from the script's comment.+ +++++ (json!({ "notation": "a EVCALC b" }), "can't be stored"),+ +++++ (json!({ "notation": "a */ x /*" }), "can't be stored"),+ +++++ (json!({ "notation": " " }), "can't be stored"),+ +++++ (json!({ "op": "sum", "fields": ["a", 5] }), "field names"),+ +++++ (json!({ "op": "sum", "fields": "a" }), "list of field names"),+ +++++ (json!({ "notation": 5 }), "notation must be a string"),+ +++++ (json!({ "op": 5, "fields": ["a"] }), "op must be"),+ +++++ (json!({ "fields": ["a"] }), "needs op"),+ +++++ (json!({ "op": "sum", "feilds": ["a"] }), "unknown key \"feilds\""),+ +++++ ] {+ +++++ // InvalidArgs, not Failed: an unstorable notation is refused by the tool itself, not+ +++++ // only by the edit underneath it.+ +++++ let e = err(&mut a, "form_set_props", json!({ "doc": doc, "field": "total", "calculate": calculate }));+ +++++ assert!(matches!(e, ToolError::InvalidArgs(_)) && e.to_string().contains(says), "{calculate}: {e:?}");+ +++++ }+ +++++ for (validate, says) in [(json!({ "min": 0, "max": "100" }), "max must be a number"), (json!({ "min": 0, "mxa": 5 }), "unknown key \"mxa\"")] {+ +++++ let e = err(&mut a, "form_set_props", json!({ "doc": doc, "field": "total", "validate": validate }));+ +++++ assert!(matches!(e, ToolError::InvalidArgs(_)) && e.to_string().contains(says), "{validate}: {e:?}");+ +++++ }+ +++++ let t = total(&mut a);+ +++++ assert_eq!((&t["calculate"], &t["validate"]), (&set, &json!({ "min": 0.0, "max": 10.0 })), "nothing changed");+ +++++ ok(&mut a, "form_set_props", json!({ "doc": doc, "field": "total", "validate": { "min": null, "max": 5 } }));+ +++++ let shown = total(&mut a)["validate"].clone();+ +++++ assert_eq!(shown, json!({ "min": null, "max": 5.0 }));+ +++++ ok(&mut a, "form_set_props", json!({ "doc": doc, "field": "total", "validate": shown }));+ +++++}+ ++++++ #[test]+ fn page_tab_orders_are_read_and_set_per_page_through_tools() {+ let dir = workdir("pagetabs");+ let mut a = auto(&dir);+ let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap();+ let r = ok(&mut a, "form_tab_order", json!({ "doc": doc }));+ assert_eq!(r["page_tabs"], json!(["annotations", "annotations", "annotations"]));+ assert!(r["undo"].is_null(), "reading changes nothing: {r}");+ let r = ok(&mut a, "form_tab_order", json!({ "doc": doc, "order": "column", "pages": [1, 3] }));+ assert_eq!(r["page_tabs"], json!(["column", "annotations", "column"]));+ assert_eq!((r["undo"].as_str(), r["dirty"].as_bool()), (Some("Set tab order"), Some(true)));+ let r = ok(&mut a, "form_tab_order", json!({ "doc": doc, "order": "structure", "pages": [2] }));+ assert_eq!(r["page_tabs"], json!(["column", "structure", "column"]));+ let r = ok(&mut a, "form_tab_order", json!({ "doc": doc, "order": "unspecified", "pages": [1] }));+ assert_eq!(r["page_tabs"], json!(["annotations", "structure", "column"]));+ }+#[test]fn tab_order_and_field_appearance_through_tools() {let dir = workdir("taborder");@@@@@@@@ -6433,207 -6517,6 -6372,6 -6237,6 -6372,6 -6381,129 -6381,129 +6587,240 @@@@@@@@ fn lzw_streams_are_stored_with_flate_thassert_eq!(filters("kept.pdf"), (Some(Object::name("LZWDecode")), ops));}++++ /// A one-page PDF drawing a 1-bit scan of text (glyph strokes with ragged edges, as a scanner++++ /// leaves them) of 1000 × 400 samples, stored with Flate.++++ fn scanned_page() -> Vec<u8> {++++++ scan_drawn(b"q 500 0 0 200 50 500 cm /Scan Do Q")++++++}++++++++++++/// [`scanned_page`]'s scan, drawn by `content` (which names it `/Scan`).++++++fn scan_drawn(content: &[u8]) -> Vec<u8> {++++ use pdfcraft_cos::{Dict, Document, Object, SaveOptions, Stream, write_full};++++ let (w, h) = (1000usize, 400usize);++++ let stride = w.div_ceil(8);++++ let mut data = vec![0xFFu8; stride * h];++++ let mut seed = 0x2545_F491_4F6C_DD1Du64;++++ let mut next = move || {++++ seed ^= seed << 13;++++ seed ^= seed >> 7;++++ seed ^= seed << 17;++++ seed++++ };++++ for line in (4..h - 20).step_by(24) {++++ let mut x = 8;++++ while x + 12 < w {++++ let wide = 3 + (next() % 5) as usize;++++ let (top, bottom) = (line + (next() % 4) as usize, line + 14);++++ for y in top..bottom {++++ let left = x + usize::from(next() % 8 == 0);++++ let right = x + wide - usize::from(next() % 8 == 0);++++ for xx in left..right {++++ data[y * stride + xx / 8] &= !(0x80 >> (xx % 8));++++ }++++ }++++ x += wide + 2 + (next() % 4) as usize;++++ }++++ }++++ let mut doc = Document::new_empty();++++ let mut d = Dict::new();++++ d.set(b"Type".to_vec(), Object::name("XObject"));++++ d.set(b"Subtype".to_vec(), Object::name("Image"));++++ d.set(b"Width".to_vec(), Object::Int(w as i64));++++ d.set(b"Height".to_vec(), Object::Int(h as i64));++++ d.set(b"BitsPerComponent".to_vec(), Object::Int(1));++++ d.set(b"ColorSpace".to_vec(), Object::name("DeviceGray"));++++ let image = doc.add(Object::Stream(Stream::flate(d, &data)));++++ let pages = doc.root().and_then(|r| doc.get(r).as_dict().and_then(|d| d.reference(b"Pages"))).unwrap();++++ let mut x = Dict::new();++++ x.set(b"Scan".to_vec(), Object::Ref(image));++++ let mut res = Dict::new();++++ res.set(b"XObject".to_vec(), Object::Dict(x));-- let content = doc.add(Object::Stream(Stream::from_raw(Dict::new(), b"q 500 0 0 200 50 500 cm /Scan Do Q".to_vec())));++++++ let content = doc.add(Object::Stream(Stream::from_raw(Dict::new(), content.to_vec())));++++ let mut p = Dict::new();++++ p.set(b"Type".to_vec(), Object::name("Page"));++++ p.set(b"Parent".to_vec(), Object::Ref(pages));++++ p.set(b"MediaBox".to_vec(), Object::Array(vec![0.into(), 0.into(), 612.into(), 792.into()]));++++ p.set(b"Resources".to_vec(), Object::Dict(res));++++ p.set(b"Contents".to_vec(), Object::Ref(content));++++ let page = doc.add(Object::Dict(p));++++ doc.update_dict(pages, |d| {++++ d.set(b"Kids".to_vec(), Object::Array(vec![Object::Ref(page)]));++++ d.set(b"Count".to_vec(), Object::Int(1));++++ })++++ .unwrap();++++ write_full(&doc, &SaveOptions::default()).unwrap()++++ }++++++++++/// A scan saved as a 1-bit PNG becomes a page whose picture stays one bit per pixel (not the eight++++++/// bits the PNG decodes to), and Export all images gives the picture back.++++++#[test]++++++fn a_one_bit_scan_stays_one_bit_and_exports() {++++++ let dir = workdir("bilevel");++++++ let (w, h) = (800u32, 200u32);++++++ let stride = (w as usize).div_ceil(8);++++++ let mut bits = vec![0xFFu8; stride * h as usize];++++++ for y in 0..h as usize {++++++ for x in 0..w as usize {++++++ if y % 25 >= 6 && y % 25 < 18 && (x * 7 + y / 25 * 13) % 11 < 4 {++++++ bits[y * stride + x / 8] &= !(0x80 >> (x % 8));++++++ }++++++ }++++++ }++++++ let mut png_bytes = Vec::new();++++++ {++++++ let mut enc = png::Encoder::new(&mut png_bytes, w, h);++++++ enc.set_color(png::ColorType::Grayscale);++++++ enc.set_depth(png::BitDepth::One);++++++ enc.write_header().unwrap().write_image_data(&bits).unwrap();++++++ }++++++ std::fs::write(dir.join("scan.png"), &png_bytes).unwrap();++++++ let mut a = auto(&dir);++++++ let doc = ok(&mut a, "doc_create", json!({ "from": "images", "paths": ["scan.png"] }))["doc"].as_u64().unwrap();++++++ ok(&mut a, "doc_save", json!({ "doc": doc, "path": "scan.pdf" }));++++++ let saved = pdfcraft_cos::Document::open(std::sync::Arc::new(std::fs::read(dir.join("scan.pdf")).unwrap())).unwrap();++++++ let images: Vec<Option<i64>> = saved++++++ .object_numbers()++++++ .into_iter()++++++ .filter_map(|num| match &*saved.get(pdfcraft_cos::ObjRef { num, generation: saved.generation(num) }) {++++++ pdfcraft_cos::Object::Stream(s) if s.dict.name(b"Subtype") == Some(b"Image") => Some(s.dict.int(b"BitsPerComponent")),++++++ _ => None,++++++ })++++++ .collect();++++++ assert_eq!(images, [Some(1)]);++++++ let r = ok(&mut a, "doc_export_all_images", json!({ "doc": doc, "folder": "out" }));++++++ let files = r["files"].as_array().unwrap();++++++ assert_eq!(files.len(), 1, "{r}");++++++ let exported = std::fs::read(files[0]["path"].as_str().unwrap()).unwrap();++++++ let mut reader = png::Decoder::new(std::io::Cursor::new(exported)).read_info().unwrap();++++++ let mut buf = vec![0; reader.output_buffer_size().unwrap()];++++++ let frame = reader.next_frame(&mut buf).unwrap();++++++ let white: Vec<bool> = buf[..frame.buffer_size()].as_chunks::<3>().0.iter().map(|p| *p == [255, 255, 255]).collect();++++++ let expected: Vec<bool> =++++++ (0..h as usize).flat_map(|y| (0..w as usize).map(move |x| (y, x))).map(|(y, x)| bits[y * stride + x / 8] & (0x80 >> (x % 8)) != 0).collect();++++++ assert_eq!(white, expected);++++++}+++++++++++ /// With `mono: { compression: jbig2 }` a scan's black-and-white image is stored as lossless JBIG2,+++++ /// smaller than as Group 4, and exports as the same picture.+++++ #[test]+++++ fn doc_optimize_stores_black_and_white_images_as_jbig2() {+++++ let dir = workdir("optimize-jbig2");+++++ std::fs::write(dir.join("scan.pdf"), scanned_page()).unwrap();+++++ let mut a = auto(&dir);+++++ let doc = ok(&mut a, "doc_open", json!({ "path": "scan.pdf" }))["doc"].as_u64().unwrap();+++++ let g4 = ok(&mut a, "doc_optimize", json!({ "doc": doc, "path": "g4.pdf" }));+++++ let r = ok(&mut a, "doc_optimize", json!({ "doc": doc, "path": "jbig2.pdf", "mono": { "compression": "jbig2" } }));+++++ assert_eq!((r["images"].as_u64(), r["images_recompressed"].as_u64()), (Some(1), Some(1)), "{r}");+++++ assert!(r["image_bytes_after"].as_u64() < g4["image_bytes_after"].as_u64(), "JBIG2 {r}, Group 4 {g4}");+++++ let written = pdfcraft_cos::Document::open(std::sync::Arc::new(std::fs::read(dir.join("jbig2.pdf")).unwrap())).unwrap();+++++ let filters: Vec<Vec<u8>> = written+++++ .object_numbers()+++++ .into_iter()+++++ .filter_map(|num| match &*written.get(pdfcraft_cos::ObjRef { num, generation: written.generation(num) }) {+++++ pdfcraft_cos::Object::Stream(s) if s.dict.name(b"Subtype") == Some(b"Image") => s.dict.name(b"Filter").map(<[u8]>::to_vec),+++++ _ => None,+++++ })+++++ .collect();+++++ assert_eq!(filters, [b"JBIG2Decode".to_vec()]);+++++ // Export ▸ Images gives the copy's picture back as it gives the scan's.+++++ let copy = ok(&mut a, "doc_open", json!({ "path": "jbig2.pdf" }))["doc"].as_u64().unwrap();+++++ let mut exported = |doc: u64, folder: &str| {+++++ let r = ok(&mut a, "doc_export_all_images", json!({ "doc": doc, "folder": folder }));+++++ let files = r["files"].as_array().unwrap();+++++ assert_eq!(files.len(), 1, "{r}");+++++ std::fs::read(files[0]["path"].as_str().unwrap()).unwrap()+++++ };+++++ assert_eq!(exported(copy, "from-jbig2"), exported(doc, "from-scan"));+++++ }+++++++++ /// A scan's black-and-white image is stored as CCITT Group 4 by default, and kept as it is with++++ /// `mono: { compression: retain }`.++++ #[test]++++ fn doc_optimize_stores_black_and_white_images_as_ccitt_group_4() {++++ let dir = workdir("optimize-mono");++++ std::fs::write(dir.join("scan.pdf"), scanned_page()).unwrap();++++ let mut a = auto(&dir);++++ let doc = ok(&mut a, "doc_open", json!({ "path": "scan.pdf" }))["doc"].as_u64().unwrap();++++ let kept = ok(&mut a, "doc_optimize", json!({ "doc": doc, "path": "kept.pdf", "mono": { "compression": "retain" } }));++++ assert_eq!((kept["images"].as_u64(), kept["images_recompressed"].as_u64()), (Some(1), Some(0)), "{kept}");++++ let r = ok(&mut a, "doc_optimize", json!({ "doc": doc, "path": "small.pdf" }));++++ assert_eq!((r["images"].as_u64(), r["images_recompressed"].as_u64()), (Some(1), Some(1)), "{r}");++++ assert!(r["image_bytes_after"].as_u64() < r["image_bytes_before"].as_u64(), "{r}");++++ // The copy written stores the image as Group 4.++++ let small = pdfcraft_cos::Document::open(std::sync::Arc::new(std::fs::read(dir.join("small.pdf")).unwrap())).unwrap();++++ let filters: Vec<Vec<u8>> = small++++ .object_numbers()++++ .into_iter()++++ .filter_map(|num| match &*small.get(pdfcraft_cos::ObjRef { num, generation: small.generation(num) }) {++++ pdfcraft_cos::Object::Stream(s) if s.dict.name(b"Subtype") == Some(b"Image") => s.dict.name(b"Filter").map(<[u8]>::to_vec),++++ _ => None,++++ })++++ .collect();++++ assert_eq!(filters, [b"CCITTFaxDecode".to_vec()]);++++ // An unknown compression, one that isn't a name, a misspelled key, or a mono that isn't an++++ // object is refused, not read as the default.- for mono in [json!({ "compression": "jbig2" }), json!({ "compression": false }), json!({ "compresson": "retain" }), json!("retain")] {+++++ for mono in [json!({ "compression": "jpeg" }), json!({ "compression": false }), json!({ "compresson": "retain" }), json!("retain")] {++++ assert!(matches!(a.call("doc_optimize", &json!({ "doc": doc, "path": "x.pdf", "mono": mono })), Err(ToolError::InvalidArgs(_))), "{mono}");++++ }++++ }++++++++++/// A scan drawn at 600 ppi is averaged down to 300 ppi by default. `mono: { downsample: false }`++++++/// keeps its size, `ppi` and `above_ppi` choose others, and values of the wrong type are refused.++++++#[test]++++++fn doc_optimize_averages_black_and_white_scans_down() {++++++ let dir = workdir("optimize-mono-downsample");++++++ // 1000 × 400 samples on 120 × 48 pt: 600 ppi.++++++ std::fs::write(dir.join("scan.pdf"), scan_drawn(b"q 120 0 0 48 50 500 cm /Scan Do Q")).unwrap();++++++ let mut a = auto(&dir);++++++ let doc = ok(&mut a, "doc_open", json!({ "path": "scan.pdf" }))["doc"].as_u64().unwrap();++++++ let sizes = |name: &str| image_sizes(&dir.join(name));++++++ let r = ok(&mut a, "doc_optimize", json!({ "doc": doc, "path": "small.pdf" }));++++++ assert_eq!(r["images_resampled"].as_u64(), Some(1), "{r}");++++++ assert_eq!(sizes("small.pdf"), [(Some(500), Some(200))]);++++++ let r = ok(&mut a, "doc_optimize", json!({ "doc": doc, "path": "kept.pdf", "mono": { "downsample": false } }));++++++ assert_eq!(r["images_resampled"].as_u64(), Some(0), "{r}");++++++ assert_eq!(sizes("kept.pdf"), [(Some(1000), Some(400))]);++++++ ok(&mut a, "doc_optimize", json!({ "doc": doc, "path": "200.pdf", "mono": { "ppi": 200, "above_ppi": 250 } }));++++++ assert_eq!(sizes("200.pdf"), [(Some(333), Some(133))]);++++++ for mono in [json!({ "downsample": "yes" }), json!({ "ppi": "300" }), json!({ "above": 450 })] {++++++ assert!(matches!(a.call("doc_optimize", &json!({ "doc": doc, "path": "x.pdf", "mono": mono })), Err(ToolError::InvalidArgs(_))), "{mono}");++++++ }++++++}++++++++++++/// The width and height of every image in the PDF at `path`.++++++fn image_sizes(path: &std::path::Path) -> Vec<(Option<i64>, Option<i64>)> {++++++ let written = pdfcraft_cos::Document::open(std::sync::Arc::new(std::fs::read(path).unwrap())).unwrap();++++++ written++++++ .object_numbers()++++++ .into_iter()++++++ .filter_map(|num| match &*written.get(pdfcraft_cos::ObjRef { num, generation: written.generation(num) }) {++++++ pdfcraft_cos::Object::Stream(s) if s.dict.name(b"Subtype") == Some(b"Image") => Some((s.dict.int(b"Width"), s.dict.int(b"Height"))),++++++ _ => None,++++++ })++++++ .collect()++++++}++++++++++++/// The batch optimize step's `ppi` reaches black-and-white images too: they go to the larger of++++++/// it and Reduce File Size's 300 ppi. Before, a batch run took every scan to 300 ppi whatever++++++/// `ppi` said, so `ppi: 600` halved 600 ppi scans.++++++#[test]++++++fn batch_ppi_bounds_how_far_black_and_white_scans_are_resampled() {++++++ let dir = workdir("batch-mono-ppi");++++++ // 1000 × 400 samples on 120 × 48 pt: 600 ppi.++++++ std::fs::write(dir.join("scan.pdf"), scan_drawn(b"q 120 0 0 48 50 500 cm /Scan Do Q")).unwrap();++++++ let mut a = auto(&dir);++++++ for (ppi, size) in [(None, (500, 200)), (Some(600), (1000, 400)), (Some(96), (500, 200))] {++++++ let out = format!("out-{ppi:?}");++++++ let mut args = json!({ "paths": ["scan.pdf"], "steps": ["optimize"], "out_dir": out });++++++ if let Some(ppi) = ppi {++++++ args["ppi"] = json!(ppi);++++++ }++++++ let report = ok(&mut a, "doc_batch", args);++++++ assert_eq!(report["completed"], 1, "{report}");++++++ assert_eq!(image_sizes(&dir.join(&out).join("scan.pdf")), [(Some(size.0), Some(size.1))], "ppi {ppi:?}");++++++ }++++++}++++++/// A one-page PDF whose page picture is drawn as `rows` grey images one pixel row high, 600 px/// wide on a 72 pt square (600 ppi), as some PDF printers write it.fn printed_in_strips(rows: usize) -> Vec<u8> {@@@@@@@@ -9651,75 -9530,75 -9385,75 -9282,3 -9381,297 -9517,75 -9517,75 +9877,297 @@@@@@@@ fn page_render_draws_stamps_without_an_let grey = custom.iter().filter(|p| p[0].abs_diff(p[1]) < 24 && p[1].abs_diff(p[2]) < 24).count();assert!(grey > 100 && grey == custom.len(), "an unknown name is a grey placeholder: {grey} of {}", custom.len());}++ #[test]+ fn deleting_one_radio_button_through_tools_keeps_the_group() {+ let dir = workdir("delete-radio");+ let mut a = auto(&dir);+ let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap();+ for (x, export) in [(20, "S"), (40, "M"), (60, "L")] {+ let args = json!({ "doc": doc, "page": 1, "type": "radio", "rect": [x, 100, x + 14, 114], "group": "size", "export": export });+ ok(&mut a, "form_add_field", args);+ }+ ok(&mut a, "form_fill", json!({ "doc": doc, "values": { "size": "L" } }));+ ok(&mut a, "form_delete_field", json!({ "doc": doc, "field": "size", "widget": 2 }));+ let size = |a: &mut Automation| ok(a, "form_fields", json!({ "doc": doc }))["fields"][0].clone();+ assert_eq!((size(&mut a)["options"].clone(), size(&mut a)["value"].clone()), (json!(["S", "L"]), json!("L")), "only M is gone");+ for widget in [0, 3, -1] {+ let r = a.call("form_delete_field", &json!({ "doc": doc, "field": "size", "widget": widget }));+ assert!(matches!(r, Err(ToolError::InvalidArgs(_))), "widget {widget}: {r:?}");+ }+ ok(&mut a, "edit_undo", json!({ "doc": doc }));+ assert_eq!(size(&mut a)["options"], json!(["S", "M", "L"]), "one undo step brings it back");+ }+ /// `/I` of the top-level field `name` in the saved file `path`.+ fn saved_selection_indices(path: &Path, name: &str) -> Option<Vec<i64>> {+ let d = pdfcraft_cos::Document::open(std::sync::Arc::new(std::fs::read(path).unwrap())).unwrap();+ let root = d.get(d.root().unwrap()).as_dict().cloned().unwrap();+ let form = d.resolve(root.get(b"AcroForm").unwrap()).as_dict().cloned().unwrap();+ let all = d.resolve(form.get(b"Fields").unwrap()).as_array().cloned().unwrap();+ let f = all+ .iter()+ .filter_map(|o| d.resolve(o).as_dict().cloned())+ .find(|f| f.get(b"T").and_then(|t| d.resolve(t).as_string().map(|s| s.to_text())).as_deref() == Some(name))+ .unwrap();+ f.get(b"I").map(|i| d.resolve(i).as_array().unwrap().iter().map(|o| o.as_int().unwrap()).collect())+ }++ #[test]+ fn changing_a_lists_options_through_tools_keeps_its_saved_selection_on_the_same_items() {+ let dir = workdir("choice-index");+ let mut a = auto(&dir);+ let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap();+ let args = json!({ "doc": doc, "page": 1, "type": "list", "rect": [20, 60, 180, 140], "options": ["A", "B", "C"], "multi_select": true, "name": "letters" });+ ok(&mut a, "form_add_field", args);+ ok(&mut a, "form_fill", json!({ "doc": doc, "values": { "letters": ["B", "C"] } }));+ ok(&mut a, "form_set_props", json!({ "doc": doc, "field": "letters", "options": ["B", "C", "D"] }));+ ok(&mut a, "doc_save", json!({ "doc": doc, "path": "letters.pdf" }));+ assert_eq!(saved_selection_indices(&dir.join("letters.pdf"), "letters"), Some(vec![0, 1]), "B and C are now items 0 and 1");+ }++ /// Clearing a field's default through `form_set_props` (`"default": ""`) leaves it with none,+ /// even when its parent field has one it would otherwise inherit.+ #[test]+ fn clearing_a_kids_default_through_tools_does_not_bring_back_its_parents() {+ let objs = [+ "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>",+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 400 300] >>",+ "<< /Type /Page /Parent 2 0 R /Annots [6 0 R] >>",+ "<< /Fields [5 0 R] /DA (/Helv 12 Tf 0 g) /DR << /Font << /Helv 7 0 R >> >> >>",+ "<< /T (address) /FT /Tx /DV (Main St) /Kids [6 0 R] >>",+ "<< /Type /Annot /Subtype /Widget /T (city) /Parent 5 0 R /DV (Elm) /V (Elm) /Rect [10 250 150 268] /P 3 0 R >>",+ "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>",+ ];+ let dir = workdir("kid-default");+ std::fs::write(dir.join("form.pdf"), pdf_of(&objs)).unwrap();+ let mut a = auto(&dir);+ let doc = ok(&mut a, "doc_open", json!({ "path": "form.pdf" }))["doc"].as_u64().unwrap();+ ok(&mut a, "form_set_props", json!({ "doc": doc, "field": "address.city", "default": "" }));+ ok(&mut a, "form_fill", json!({ "doc": doc, "values": { "address.city": "Oak" } }));+ ok(&mut a, "form_reset", json!({ "doc": doc }));+ let fields = ok(&mut a, "form_fields", json!({ "doc": doc }));+ let city = fields["fields"].as_array().unwrap().iter().find(|f| f["name"] == "address.city").unwrap().clone();+ assert!(city["value"].is_null() || city["value"] == "", "reset clears it rather than restoring the parent's Main St: {}", city["value"]);+ }++++ ++++++ ++/// #2517, through the same tools as the report. One blank line is two paragraphs, and editing++++ ++/// the first leaves the second. The neighbour at y=656.8 is one blank line below (two 14.4 pt++++ ++/// leadings under the second row). Growing the first paragraph, saving, reopening and editing++++ ++/// again leaves that neighbour in place. An explicit TL of 27.6 pt stays one paragraph.++++ ++#[test]++++ ++fn a_blank_line_stays_a_separate_paragraph_through_tools() {++++ ++ let dir = workdir("blank-line");++++ ++ let body = "BT /F1 12 Tf 14.4 TL 1 0 0 1 72 700 Tm (First paragraph, first row.) Tj T* (First paragraph, second row.) Tj ET \++++ ++ BT /F1 12 Tf 14.4 TL 1 0 0 1 72 656.8 Tm (Second paragraph, first row.) Tj T* (Second paragraph, second row.) Tj ET";++++ ++ std::fs::write(dir.join("a.pdf"), helvetica_page(body)).unwrap();++++ ++ let mut a = auto(&dir);++++ ++ let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap();++++ ++ let before = ok(&mut a, "text_paragraphs", json!({ "doc": doc, "page": 1 }));++++ ++ assert_eq!(before["count"], 2, "{before}");++++ ++ ok(&mut a, "text_edit", json!({ "doc": doc, "page": 1, "paragraph": 1, "text": "First paragraph, edited row.\nFirst paragraph, second row." }));++++ ++ let after = ok(&mut a, "text_paragraphs", json!({ "doc": doc, "page": 1 }));++++ ++ assert_eq!(after["count"], 2, "{after}");++++ ++ let second = after["paragraphs"][1]["text"].as_str().unwrap();++++ ++ assert!(second.contains("Second paragraph"), "{second}");++++ ++++++ ++ let grown = "BT /F1 12 Tf 14.4 TL 1 0 0 1 72 700 Tm (One) Tj T* (Two) Tj ET \++++ ++ BT /F1 12 Tf 14.4 TL 1 0 0 1 72 656.8 Tm (Neighbour) Tj ET";++++ ++ std::fs::write(dir.join("grown.pdf"), helvetica_page(grown)).unwrap();++++ ++ let grown_doc = ok(&mut a, "doc_open", json!({ "path": "grown.pdf" }))["doc"].as_u64().unwrap();++++ ++ assert_eq!(ok(&mut a, "text_paragraphs", json!({ "doc": grown_doc, "page": 1 }))["count"], 2);++++ ++ ok(&mut a, "text_edit", json!({ "doc": grown_doc, "page": 1, "paragraph": 1, "text": "One\nTwo\nThree" }));++++ ++ ok(&mut a, "doc_save", json!({ "doc": grown_doc, "path": "grown-out.pdf" }));++++ ++ let saved = ok(&mut a, "doc_open", json!({ "path": "grown-out.pdf" }))["doc"].as_u64().unwrap();++++ ++ let after = ok(&mut a, "text_paragraphs", json!({ "doc": saved, "page": 1 }));++++ ++ assert_eq!(after["count"], 2, "{after}");++++ ++ assert!(after["paragraphs"][1]["text"].as_str().unwrap().contains("Neighbour"), "{after}");++++ ++ ok(&mut a, "text_edit", json!({ "doc": saved, "page": 1, "paragraph": 1, "text": "One\nTwo\nFour" }));++++ ++ let after = ok(&mut a, "text_paragraphs", json!({ "doc": saved, "page": 1 }));++++ ++ assert_eq!(after["count"], 2, "{after}");++++ ++ assert!(after["paragraphs"][1]["text"].as_str().unwrap().contains("Neighbour"), "{after}");++++ ++++++ ++ let spaced = "BT /F1 12 Tf 27.6 TL 1 0 0 1 72 700 Tm (One) Tj T* (Two) Tj T* (Three) Tj ET";++++ ++ std::fs::write(dir.join("spaced.pdf"), helvetica_page(spaced)).unwrap();++++ ++ let spaced_doc = ok(&mut a, "doc_open", json!({ "path": "spaced.pdf" }))["doc"].as_u64().unwrap();++++ ++ assert_eq!(ok(&mut a, "text_paragraphs", json!({ "doc": spaced_doc, "page": 1 }))["count"], 1);++++ ++}++++ ++++++ ++/// #2529, through the same tools as a width drag. The typed double space falls on the wrap.++++ ++/// Omitting `text` reflows with the saved gap count. An incremental save and a full rewrite++++ ++/// both still have both spaces after the box is widened again.++++ ++#[test]++++ ++fn narrowing_then_widening_keeps_a_typed_double_space_through_tools() {++++ ++ let dir = workdir("double-space-width");++++ ++ std::fs::write(dir.join("a.pdf"), helvetica_page("BT /F1 24 Tf 20 150 Td (One Two) Tj ET")).unwrap();++++ ++ let mut a = auto(&dir);++++ ++ let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap();++++ ++ assert_eq!(ok(&mut a, "text_paragraphs", json!({ "doc": doc, "page": 1 }))["paragraphs"][0]["editor_text"], "One Two");++++ ++ ok(&mut a, "text_edit", json!({ "doc": doc, "page": 1, "paragraph": 1, "width": 45.0 }));++++ ++ let narrow = &ok(&mut a, "text_paragraphs", json!({ "doc": doc, "page": 1 }))["paragraphs"][0];++++ ++ assert_eq!(narrow["editor_text"], "One\nTwo", "{narrow}");++++ ++ for (name, full) in [("narrow-inc.pdf", false), ("narrow-full.pdf", true)] {++++ ++ ok(&mut a, "doc_save", json!({ "doc": doc, "path": name, "full": full }));++++ ++ let saved = ok(&mut a, "doc_open", json!({ "path": name }))["doc"].as_u64().unwrap();++++ ++ let block = &ok(&mut a, "text_paragraphs", json!({ "doc": saved, "page": 1 }))["paragraphs"][0];++++ ++ assert_eq!(block["editor_text"], "One\nTwo", "{name}: {block}");++++ ++ ok(&mut a, "text_edit", json!({ "doc": saved, "page": 1, "paragraph": 1, "width": 200.0 }));++++ ++ let wide_name = format!("wide-{name}");++++ ++ ok(&mut a, "doc_save", json!({ "doc": saved, "path": wide_name, "full": full }));++++ ++ let wide = ok(&mut a, "doc_open", json!({ "path": wide_name }))["doc"].as_u64().unwrap();++++ ++ let block = &ok(&mut a, "text_paragraphs", json!({ "doc": wide, "page": 1 }))["paragraphs"][0];++++ ++ assert_eq!(block["editor_text"], "One Two", "{name}: the second typed space was lost: {block}");++++ ++ }++++ ++}++++ ++++++ ++fn paragraph_texts(a: &mut Automation, doc: u64) -> Vec<String> {++++ ++ ok(a, "text_paragraphs", json!({ "doc": doc, "page": 1 }))["paragraphs"]++++ ++ .as_array()++++ ++ .unwrap()++++ ++ .iter()++++ ++ .map(|p| p["text"].as_str().unwrap().to_string())++++ ++ .collect()++++ ++}++++ ++++++ ++/// The reported edits, through open / text_paragraphs / text_edit / save / reopen / text_extract.++++ ++/// Covers an explicit TL, the three ways a file moves rows without TL, a blank line written with++++ ++/// Td, a two-row file that must stay split, and a partial rewrite that adds a row.++++ ++#[test]++++ ++fn paragraph_grouping_survives_save_and_reopen_through_tools() {++++ ++ let dir = workdir("paragraph-grouping");++++ ++ let mut a = auto(&dir);++++ ++ for step in [27.6_f64, 28.8] {++++ ++ let y2 = 700.0 - step;++++ ++ let y3 = 700.0 - 2.0 * step;++++ ++ let bodies = [++++ ++ format!("BT /F1 12 Tf 1 0 0 1 72 700 Tm (One) Tj 0 -{step} Td (Two) Tj 0 -{step} Td (Three) Tj ET"),++++ ++ format!(++++ ++ "BT /F1 12 Tf 1 0 0 1 72 700 Tm (One) Tj ET BT /F1 12 Tf 1 0 0 1 72 {y2} Tm (Two) Tj ET BT /F1 12 Tf 1 0 0 1 72 {y3} Tm (Three) Tj ET"++++ ++ ),++++ ++ format!("BT /F1 12 Tf 72 700 Td (One) Tj ET BT /F1 12 Tf 72 {y2} Td (Two) Tj ET BT /F1 12 Tf 72 {y3} Td (Three) Tj ET"),++++ ++ ];++++ ++ for (i, body) in bodies.iter().enumerate() {++++ ++ let path = format!("step-{step}-{i}.pdf");++++ ++ std::fs::write(dir.join(&path), helvetica_page(body)).unwrap();++++ ++ let doc = ok(&mut a, "doc_open", json!({ "path": path }))["doc"].as_u64().unwrap();++++ ++ let paras = paragraph_texts(&mut a, doc);++++ ++ assert_eq!(paras.len(), 1, "{path}: {paras:?}");++++ ++ assert!(paras[0].contains("One") && paras[0].contains("Two") && paras[0].contains("Three"), "{path}: {paras:?}");++++ ++ let extracted = page_text(&mut a, doc);++++ ++ assert!(extracted[0].contains("One") && extracted[0].contains("Three"), "{path}: {extracted:?}");++++ ++ }++++ ++ }++++ ++++++ ++ // One gap and no third row: still two paragraphs.++++ ++ let pair = format!("BT /F1 12 Tf 72 700 Td (One) Tj ET BT /F1 12 Tf 72 {} Td (Two) Tj ET", 700.0 - 27.6);++++ ++ std::fs::write(dir.join("pair.pdf"), helvetica_page(&pair)).unwrap();++++ ++ let pair_doc = ok(&mut a, "doc_open", json!({ "path": "pair.pdf" }))["doc"].as_u64().unwrap();++++ ++ assert_eq!(paragraph_texts(&mut a, pair_doc).len(), 2);++++ ++++++ ++ // Blank line written with Td, not TL. The inner step repeats; the break does not.++++ ++ let inner = 14.4_f64;++++ ++ let blank = format!(++++ ++ "BT /F1 12 Tf 72 700 Td (One) Tj ET BT /F1 12 Tf 72 {} Td (Two) Tj ET \++++ ++ BT /F1 12 Tf 72 {} Td (Neighbour) Tj ET BT /F1 12 Tf 72 {} Td (Line) Tj ET",++++ ++ 700.0 - inner,++++ ++ 700.0 - 3.0 * inner,++++ ++ 700.0 - 4.0 * inner++++ ++ );++++ ++ std::fs::write(dir.join("blank.pdf"), helvetica_page(&blank)).unwrap();++++ ++ let blank_doc = ok(&mut a, "doc_open", json!({ "path": "blank.pdf" }))["doc"].as_u64().unwrap();++++ ++ let blank_paras = paragraph_texts(&mut a, blank_doc);++++ ++ assert_eq!(blank_paras.len(), 2, "{blank_paras:?}");++++ ++ assert!(blank_paras[0].contains("One") && blank_paras[0].contains("Two"), "{blank_paras:?}");++++ ++ assert!(blank_paras[1].contains("Neighbour") && blank_paras[1].contains("Line"), "{blank_paras:?}");++++ ++++++ ++ // The first row is unchanged. Save incremental, reopen, edit again, save in full, reopen.++++ ++ let partial = "BT /F1 12 Tf 14.4 TL 1 0 0 1 72 700 Tm (Alpha first row.) Tj T* (Alpha next row.) Tj ET \++++ ++ BT /F1 12 Tf 14.4 TL 1 0 0 1 72 656.8 Tm (Neighbor stays.) Tj ET";++++ ++ std::fs::write(dir.join("partial.pdf"), helvetica_page(partial)).unwrap();++++ ++ let doc = ok(&mut a, "doc_open", json!({ "path": "partial.pdf" }))["doc"].as_u64().unwrap();++++ ++ assert_eq!(paragraph_texts(&mut a, doc).len(), 2);++++ ++ ok(&mut a, "text_edit", json!({ "doc": doc, "page": 1, "paragraph": 1, "text": "Alpha first row.\nTwo\nThree" }));++++ ++ let incremental = ok(&mut a, "doc_save", json!({ "doc": doc, "path": "partial.pdf" }));++++ ++ assert_eq!(incremental["incremental"], true, "{incremental}");++++ ++ let reopened = ok(&mut a, "doc_open", json!({ "path": "partial.pdf" }))["doc"].as_u64().unwrap();++++ ++ assert_eq!(paragraph_texts(&mut a, reopened), ["Alpha first row. Two Three", "Neighbor stays."]);++++ ++ ok(&mut a, "text_edit", json!({ "doc": reopened, "page": 1, "paragraph": 1, "text": "Alpha first row.\nTwo\nFour" }));++++ ++ let full = ok(&mut a, "doc_save", json!({ "doc": reopened, "path": "partial-full.pdf", "full": true }));++++ ++ assert_eq!(full["incremental"], false, "{full}");++++ ++ let again = ok(&mut a, "doc_open", json!({ "path": "partial-full.pdf" }))["doc"].as_u64().unwrap();++++ ++ assert_eq!(paragraph_texts(&mut a, again), ["Alpha first row. Two Four", "Neighbor stays."]);++++ ++ let extracted = page_text(&mut a, again);++++ ++ assert!(extracted[0].contains("Neighbor stays.") && extracted[0].contains("Four"), "{extracted:?}");++++ ++}++++ ++++++ ++/// Editing the only paragraph on the page, while leaving its second row in the source, stays++++ ++/// one paragraph through save and reopen. A neighbour in a different marked region stays in++++ ++/// its own paragraph.++++ ++#[test]++++ ++fn a_partial_rewrite_of_the_last_paragraph_stays_one_through_tools() {++++ ++ let dir = workdir("paragraph-tail");++++ ++ let mut a = auto(&dir);++++ ++ let only = "BT /F1 12 Tf 14.4 TL 1 0 0 1 72 700 Tm (Alpha first row.) Tj T* (Alpha next row.) Tj ET";++++ ++ std::fs::write(dir.join("only.pdf"), helvetica_page(only)).unwrap();++++ ++ let doc = ok(&mut a, "doc_open", json!({ "path": "only.pdf" }))["doc"].as_u64().unwrap();++++ ++ assert_eq!(paragraph_texts(&mut a, doc), ["Alpha first row. Alpha next row."]);++++ ++ ok(&mut a, "text_edit", json!({ "doc": doc, "page": 1, "paragraph": 1, "text": "One.\nAlpha next row." }));++++ ++ assert_eq!(paragraph_texts(&mut a, doc), ["One. Alpha next row."]);++++ ++ ok(&mut a, "doc_save", json!({ "doc": doc, "path": "only.pdf" }));++++ ++ let reopened = ok(&mut a, "doc_open", json!({ "path": "only.pdf" }))["doc"].as_u64().unwrap();++++ ++ assert_eq!(paragraph_texts(&mut a, reopened), ["One. Alpha next row."]);++++ ++ ok(&mut a, "text_edit", json!({ "doc": reopened, "page": 1, "paragraph": 1, "text": "One.\nTwo." }));++++ ++ assert_eq!(paragraph_texts(&mut a, reopened), ["One. Two."]);++++ ++++++ ++ let marked = "/H1 << /MCID 0 >> BDC BT /F1 12 Tf 14.4 TL 1 0 0 1 72 700 Tm (Alpha first row.) Tj T* (Alpha next row.) Tj ET EMC \++++ ++ /P << /MCID 1 >> BDC BT /F1 12 Tf 14.4 TL 1 0 0 1 72 656.8 Tm (Neighbor stays.) Tj ET EMC";++++ ++ std::fs::write(dir.join("marked.pdf"), helvetica_page(marked)).unwrap();++++ ++ let doc = ok(&mut a, "doc_open", json!({ "path": "marked.pdf" }))["doc"].as_u64().unwrap();++++ ++ assert_eq!(paragraph_texts(&mut a, doc).len(), 2);++++ ++ ok(&mut a, "text_edit", json!({ "doc": doc, "page": 1, "paragraph": 1, "text": "One.\nAlpha next row." }));++++ ++ assert_eq!(paragraph_texts(&mut a, doc), ["One. Alpha next row.", "Neighbor stays."]);++++ ++ ok(&mut a, "doc_save", json!({ "doc": doc, "path": "marked.pdf" }));++++ ++ let reopened = ok(&mut a, "doc_open", json!({ "path": "marked.pdf" }))["doc"].as_u64().unwrap();++++ ++ assert_eq!(paragraph_texts(&mut a, reopened), ["One. Alpha next row.", "Neighbor stays."]);++++ ++ ok(&mut a, "text_edit", json!({ "doc": reopened, "page": 1, "paragraph": 1, "text": "One.\nTwo." }));++++ ++ assert_eq!(paragraph_texts(&mut a, reopened), ["One. Two.", "Neighbor stays."]);++++ ++}++++ ++++++ ++/// Both ends of one text object, through open / text_edit / save / reopen / text_extract.++++ ++/// Editing the last paragraph must not take the one before it, and editing the first must++++ ++/// not take the one after it. Incremental and full saves.++++ ++#[test]++++ ++fn a_shared_text_object_keeps_both_paragraphs_through_tools() {++++ ++ let dir = workdir("shared-text-object");++++ ++ let mut a = auto(&dir);++++ ++ let body =++++ ++ "BT /F1 12 Tf 14.4 TL 1 0 0 1 72 700 Tm (Alpha first row.) Tj T* (Alpha next row.) Tj T* T* (Neighbor stays.) Tj T* (Neighbor next.) Tj ET";++++ ++ std::fs::write(dir.join("last.pdf"), helvetica_page(body)).unwrap();++++ ++ let doc = ok(&mut a, "doc_open", json!({ "path": "last.pdf" }))["doc"].as_u64().unwrap();++++ ++ assert_eq!(paragraph_texts(&mut a, doc), ["Alpha first row. Alpha next row.", "Neighbor stays. Neighbor next."]);++++ ++ ok(&mut a, "text_edit", json!({ "doc": doc, "page": 1, "paragraph": 2, "text": "Neighbor stays.\nChanged." }));++++ ++ assert_eq!(paragraph_texts(&mut a, doc), ["Alpha first row. Alpha next row.", "Neighbor stays. Changed."]);++++ ++ let incremental = ok(&mut a, "doc_save", json!({ "doc": doc, "path": "last.pdf" }));++++ ++ assert_eq!(incremental["incremental"], true, "{incremental}");++++ ++ let reopened = ok(&mut a, "doc_open", json!({ "path": "last.pdf" }))["doc"].as_u64().unwrap();++++ ++ assert_eq!(paragraph_texts(&mut a, reopened), ["Alpha first row. Alpha next row.", "Neighbor stays. Changed."]);++++ ++ ok(&mut a, "text_edit", json!({ "doc": reopened, "page": 1, "paragraph": 2, "text": "Neighbor stays.\nEdited." }));++++ ++ let full = ok(&mut a, "doc_save", json!({ "doc": reopened, "path": "last-full.pdf", "full": true }));++++ ++ assert_eq!(full["incremental"], false, "{full}");++++ ++ let again = ok(&mut a, "doc_open", json!({ "path": "last-full.pdf" }))["doc"].as_u64().unwrap();++++ ++ assert_eq!(paragraph_texts(&mut a, again), ["Alpha first row. Alpha next row.", "Neighbor stays. Edited."]);++++ ++ let extracted = page_text(&mut a, again);++++ ++ assert!(extracted[0].contains("Alpha first row.") && extracted[0].contains("Edited."), "{extracted:?}");++++ ++++++ ++ std::fs::write(dir.join("first.pdf"), helvetica_page(body)).unwrap();++++ ++ let doc = ok(&mut a, "doc_open", json!({ "path": "first.pdf" }))["doc"].as_u64().unwrap();++++ ++ ok(&mut a, "text_edit", json!({ "doc": doc, "page": 1, "paragraph": 1, "text": "Alpha first row.\nTwo\nThree" }));++++ ++ ok(&mut a, "doc_save", json!({ "doc": doc, "path": "first.pdf" }));++++ ++ let reopened = ok(&mut a, "doc_open", json!({ "path": "first.pdf" }))["doc"].as_u64().unwrap();++++ ++ assert_eq!(paragraph_texts(&mut a, reopened), ["Alpha first row. Two Three", "Neighbor stays. Neighbor next."]);++++ ++ ok(&mut a, "text_edit", json!({ "doc": reopened, "page": 1, "paragraph": 1, "text": "Alpha first row.\nTwo\nFour" }));++++ ++ ok(&mut a, "doc_save", json!({ "doc": reopened, "path": "first-full.pdf", "full": true }));++++ ++ let again = ok(&mut a, "doc_open", json!({ "path": "first-full.pdf" }))["doc"].as_u64().unwrap();++++ ++ assert_eq!(paragraph_texts(&mut a, again), ["Alpha first row. Two Four", "Neighbor stays. Neighbor next."]);++++ ++ let extracted = page_text(&mut a, again);++++ ++ assert!(extracted[0].contains("Four") && extracted[0].contains("Neighbor stays."), "{extracted:?}");++++ ++}diff --cc crates/create/Cargo.tomlindex 3648c3be0,12daad621,12daad621,fa649de47,12daad621,a7f3df0de,a7f3df0de..b41caa2b8--- a/crates/create/Cargo.toml+++ b/crates/create/Cargo.toml@@@@@@@@ -10,11 -10,10 -10,10 -10,8 -10,10 -10,12 -10,12 +10,13 @@@@@@@@ workspace = tru[dependencies]pdfcraft-cos = { workspace = true }++++++pdfcraft-filters = { workspace = true }pdfcraft-model = { workspace = true }pdfcraft-fonts = { workspace = true }+ # For `image::bmp_with_pixel_offset`, shared with XFA pictures.+ pdfcraft-xfa = { workspace = true }+++++ # Already in the graph through hayro: decodes JBIG2 images for Export ▸ Images.+++++ hayro-jbig2.workspace = truepng = "0.18"tiff = "0.11"image = { version = "0.25", default-features = false, features = ["bmp", "gif", "jpeg"] }@@@@@@@@ -25,7 -24,5 -24,5 -22,5 -24,5 -26,6 -26,6 +27,8 @@@@@@@@ thiserror = { workspace = trueencoding_rs = "0.8"[dev-dependencies]++++++# An independent CCITT decoder, to check Create PDF's Group 4 images.++++++hayro-ccitt.workspace = trueimage = { version = "0.25", default-features = false, features = ["bmp", "gif", "jpeg"] }hayro-syntax = { workspace = true }+++++ pdfcraft-filters = { workspace = true }diff --cc crates/create/src/extract.rsindex e62eae31d,7828952ed,7828952ed,7828952ed,7828952ed,f7fd7f122,f7fd7f122..b12bd50ec--- a/crates/create/src/extract.rs+++ b/crates/create/src/extract.rs@@@@@@@@ -1,7 -1,7 -1,7 -1,7 -1,7 -1,7 -1,7 +1,7 @@@@@@@@//! Export a PDF ▸ Image ▸ Export all images, and Edit ▸ Save image as: the images that pages//! use, as files. JPEG images are written unchanged; other images, and JPEG images with//! transparency or with CMYK samples a viewer would read inverted, are decoded and written as PNG with their soft mask, stencil mask or colour- //! key as alpha. Images PdfCraft can't decode yet (JPEG 2000, JBIG2, separations) are---- //! key as alpha. Images PdfCraft can't decode yet (JPEG 2000, JBIG2, CCITT, separations) are--//! key as alpha. Images PdfCraft can't decode yet (JPEG 2000, CCITT, separations) are+++++++//! key as alpha. Images PdfCraft can't decode yet (JPEG 2000, separations) are//! reported, never silently left out.use std::collections::HashSet;@@@@@@@@ -100,6 -100,6 -100,6 -100,6 -100,6 -100,116 -100,116 +100,116 @@@@@@@@ fn filters(s: &Stream) -> Vec<Vec<u8>>}}+++++ /// The samples of image `s`, decoded: through its filters, with a `/DecodeParms` dictionary given+++++ /// by reference, or as an array's entry, or with numbers inside by reference, read too (a predictor+++++ /// given so would otherwise be lost), or, for a JBIG2 image+++++ /// (its only filter), through a JBIG2 decoder with its `/JBIG2Globals`, as rows of one-bit samples+++++ /// each starting on a byte, with black as 0, as `JBIG2Decode` gives them (ISO 32000-2 §7.4.7).+++++ fn decoded(doc: &Document, s: &Stream) -> Result<Vec<u8>, String> {+++++ match filters(s).as_slice() {+++++ [f] if f == b"JBIG2Decode" => jbig2(doc, s),-- _ => doc.with_direct_parms(s).decoded().map_err(|e| e.to_string()),+++++++ _ => doc.decoded_image(s).map_err(|e| e.to_string()),+++++ }+++++ }++++++++++ /// The `/DecodeParms` of a stream with one filter: a dictionary, or the one in an array (7.4.2).+++++ fn decode_parms(doc: &Document, s: &Stream) -> Dict {+++++ let Some(p) = s.dict.get(b"DecodeParms").map(|p| doc.resolve(p)) else { return Dict::default() };+++++ let p = match &*p {+++++ Object::Array(a) => match a.first() {+++++ Some(first) => doc.resolve(first),+++++ None => return Dict::default(),+++++ },+++++ _ => p,+++++ };+++++ p.as_dict().cloned().unwrap_or_default()+++++ }++++++++++ /// The most an image's `/JBIG2Globals` decode to: the symbol and pattern dictionaries an encoder+++++ /// shares between pages, themselves coded, so far less than any stream may decode to+++++ /// ([`pdfcraft_cos::MAX_DECODED`], 1 GiB). Globals past it refuse the image.+++++ const MAX_GLOBALS: usize = 32 << 20;++++++++++ /// [`decoded`] for a JBIG2 image. Its JBIG2 page has to be the image's width, which the caller+++++ /// checked against the export's size limit, and within that limit itself: the decoder decodes the+++++ /// whole page, rows past the image's height too, so a small `/Height` over a far taller page+++++ /// would cost more than the limit allows. Rows past the image's height are dropped, and too few+++++ /// rows are refused by the caller. Globals that can't be read refuse the image, rather than+++++ /// decoding it without them. They are decoded before the page's size is known, so the page's+++++ /// limit can't bound them; they have [`MAX_GLOBALS`] of their own.+++++ fn jbig2(doc: &Document, s: &Stream) -> Result<Vec<u8>, String> {+++++ let globals = match decode_parms(doc, s).get(b"JBIG2Globals").map(|g| doc.resolve(g)).as_deref() {+++++ Some(Object::Stream(g)) => {+++++ Some(doc.with_direct_parms(g).decoded_within(MAX_GLOBALS).map_err(|e| format!("the JBIG2 globals can't be read: {e}"))?)+++++ }+++++ _ => None,+++++ };+++++ let image = hayro_jbig2::Image::new_embedded(&s.raw, globals.as_deref()).map_err(|e| format!("the JBIG2 image can't be read: {e}"))?;+++++ if s.dict.int(b"Width") != Some(i64::from(image.width())) {+++++ return Err("the JBIG2 image's width isn't the image's width".into());+++++ }+++++ if u64::from(image.width()).saturating_mul(u64::from(image.height())) > MAX_PIXELS {+++++ return Err(format!("the JBIG2 page, {} × {}, is too large to export", image.width(), image.height()));+++++ }+++++ let height = s.dict.int(b"Height").and_then(|h| usize::try_from(h).ok()).unwrap_or(0);+++++ let mut rows = Rows::new(image.width() as usize, height);+++++ image.decode(&mut rows).map_err(|e| format!("the JBIG2 image can't be decoded: {e}"))?;+++++ Ok(rows.out)+++++ }++++++++++ /// Rows of one-bit samples, each starting on a byte, filled from a decoder's pixels: `columns`+++++ /// a row and at most `rows` rows. Pixels past a row's end and rows past the last are dropped, so+++++ /// the output is bounded by the size the caller gave.+++++ struct Rows {+++++ out: Vec<u8>,+++++ row: Vec<u8>,+++++ x: usize,+++++ columns: usize,+++++ rows: usize,+++++ done: usize,+++++ }++++++++++ impl Rows {+++++ fn new(columns: usize, rows: usize) -> Self {+++++ Rows { out: Vec::new(), row: vec![0; columns.div_ceil(8)], x: 0, columns, rows, done: 0 }+++++ }++++++++++ /// `count` pixels, as 1 samples when `one`.+++++ fn push(&mut self, one: bool, count: usize) {+++++ let end = self.x.saturating_add(count);+++++ if one {+++++ for x in self.x..end.min(self.columns) {+++++ if let Some(b) = self.row.get_mut(x / 8) {+++++ *b |= 0x80 >> (x % 8);+++++ }+++++ }+++++ }+++++ self.x = end;+++++ }++++++++++ fn end_row(&mut self) {+++++ if self.done < self.rows {+++++ self.out.extend_from_slice(&self.row);+++++ self.done += 1;+++++ }+++++ self.row.fill(0);+++++ self.x = 0;+++++ }+++++ }++++++++++ /// JBIG2 codes black as 1, which `JBIG2Decode` gives as 0.+++++ impl hayro_jbig2::Decoder for Rows {+++++ fn push_pixel(&mut self, black: bool) {+++++ self.push(!black, 1);+++++ }+++++ fn push_pixel_chunk(&mut self, black: bool, chunks: u32) {+++++ self.push(!black, (chunks as usize).saturating_mul(8));+++++ }+++++ fn next_line(&mut self) {+++++ self.end_row();+++++ }+++++ }+++++/// The file for one image: its JPEG data as is, or a PNG. An image with transparency (a soft/// mask, a stencil `/Mask` or a colour-key `/Mask`) is always a PNG with that transparency as/// alpha, JPEG images included, so cut-out images keep their transparent background.@@@@@@@@ -108,7 -108,8 -108,8 -108,8 -108,8 -218,8 -218,8 +218,7 @@@@@@@@ fn image(doc: &Document, s: &Stream) -let jpeg = matches!(f.last().map(Vec::as_slice), Some(b"DCTDecode" | b"DCT")) && f.len() == 1;match f.last().map(Vec::as_slice) {Some(b"JPXDecode") => return Err("JPEG 2000 images can't be exported yet".into()),----- Some(b"JBIG2Decode") => return Err("JBIG2 images can't be exported yet".into()),---- Some(b"CCITTFaxDecode" | b"CCF") => return Err("CCITT fax images can't be exported yet".into()),+++++ Some(b"JBIG2Decode") if f.len() > 1 => return Err("JBIG2 images inside other filters can't be exported yet".into()),-- Some(b"CCITTFaxDecode" | b"CCF") => return Err("CCITT fax images can't be exported yet".into()),Some(b"DCTDecode" | b"DCT") if !jpeg => return Err("JPEG images inside other filters can't be exported yet".into()),_ => {}}@@@@@@@@ -147,7 -148,7 -148,7 -148,7 -148,7 -258,7 -258,7 +257,7 @@@@@@@@space = decoded;(samples, 8)} else {- let data = doc.decoded_image(s).map_err(|e| e.to_string())?;---- let data = s.decoded().map_err(|e| e.to_string())?;+++++ let data = decoded(doc, s)?;let bpc = if mask { 1 } else { s.dict.int(b"BitsPerComponent").unwrap_or(8) };let bpc = match bpc {1 => 1,@@@@@@@@ -402,11 -403,9 -403,9 -403,9 -403,9 -513,10 -513,10 +512,11 @@@@@@@@ fn space(doc: &Document, cs: Option<&Ob};let table = match a.get(3).map(|t| doc.resolve(t)).as_deref() {Some(Object::String(s)) => s.bytes.clone(),---- Some(Object::Stream(t)) => {---- t.decoded_within(MAX_LOOKUP).map_err(|_| "an indexed colour space with an oversized or damaged lookup table".to_string())?---- }++++++ // Through its parameters given by reference too, as the image's samples.++++ Some(Object::Stream(t)) => doc++++ .with_direct_parms(t)++++ .decoded_within(MAX_LOOKUP)++++ .map_err(|_| "an indexed colour space with an oversized or damaged lookup table".to_string())?,_ => return Err("an indexed colour space without a lookup table".into()),};Ok(Space::Indexed(Box::new(base), hival, table))@@@@@@@@ -467,7 -466,7 -466,7 -466,7 -466,7 -577,7 -577,7 +577,7 @@@@@@@@ fn stencil_mask(doc: &Document, s: &Str}/// A one-component mask image as 8-bit values (its `/Decode` interval applied), scaled to- /// `w` × `h`. `None` when it can't be decoded (JPEG 2000 and JBIG2 masks).---- /// `w` × `h`. `None` when it can't be decoded (JPEG 2000, JBIG2 and CCITT masks).--/// `w` × `h`. `None` when it can't be decoded (JPEG 2000 and CCITT masks).+++++++/// `w` × `h`. `None` when it can't be decoded (JPEG 2000 masks).fn gray_plane(doc: &Document, m: &Stream, w: usize, h: usize) -> Option<Vec<u8>> {let (mw, mh) = size(m.dict.int(b"Width")?, m.dict.int(b"Height")?)?;let stencil = m.dict.get(b"ImageMask").is_some_and(|v| matches!(&*doc.resolve(v), Object::Bool(true)));@@@@@@@@ -477,7 -476,7 -476,7 -476,7 -476,7 -587,7 -587,7 +587,7 @@@@@@@@let img = image::load_from_memory_with_format(&m.raw, image::ImageFormat::Jpeg).ok()?.into_luma8();(img.width() as usize == mw && img.height() as usize == mh).then(|| img.into_raw())?}- Some(b"DCTDecode" | b"DCT" | b"JPXDecode" | b"JBIG2Decode") => return None,---- Some(b"DCTDecode" | b"DCT" | b"JPXDecode" | b"JBIG2Decode" | b"CCITTFaxDecode" | b"CCF") => return None,-- Some(b"DCTDecode" | b"DCT" | b"JPXDecode" | b"CCITTFaxDecode" | b"CCF") => return None,+++++++ Some(b"DCTDecode" | b"DCT" | b"JPXDecode") => return None,_ => {let bpc = if stencil { 1 } else { m.dict.int(b"BitsPerComponent").unwrap_or(8) };let bpc = match bpc {@@@@@@@@ -489,7 -488,7 -488,7 -488,7 -488,7 -599,7 -599,7 +599,7 @@@@@@@@_ => return None,};let max = (1u32 << bpc.min(8)) - 1;- unpack(&doc.decoded_image(m).ok()?, mw, mh, 1, bpc)?.into_iter().map(|v| (v as u32 * 255 / max) as u8).collect()---- unpack(&m.decoded().ok()?, mw, mh, 1, bpc)?.into_iter().map(|v| (v as u32 * 255 / max) as u8).collect()+++++ unpack(&decoded(doc, m).ok()?, mw, mh, 1, bpc)?.into_iter().map(|v| (v as u32 * 255 / max) as u8).collect()}};if let Some([lo, hi]) = decode(doc, m, 1).and_then(|pairs| pairs.first().copied()) {diff --cc crates/create/src/tests.rsindex fc47e78ad,5cd34a0f1,5cd34a0f1,3c9aa42a0,5cd34a0f1,9bff0c311,352ff14eb..03c93d4a5--- a/crates/create/src/tests.rs+++ b/crates/create/src/tests.rs@@@@@@@@ -1380,557 -1338,3 -1338,3 -1318,3 -1338,3 -1338,239 -1338,278 +1380,832 @@@@@@@@ fn a_tiny_gif_on_a_huge_screen_is_refuslet doc = reopen(&from_images(&[("small.gif".into(), gif_on_screen(40, 30))]).unwrap());assert_eq!(media(&pages(&doc)[0]), [0.0, 0.0, 40.0, 30.0]);}++++++++++/// A PNG of `w` × `h` samples `data` in `color` at `depth`, with a palette or an ICC profile.++++++fn png_of(w: u32, h: u32, color: png::ColorType, depth: png::BitDepth, data: &[u8], palette: Option<Vec<u8>>, icc: Option<Vec<u8>>) -> Vec<u8> {++++++ let mut out = Vec::new();++++++ {++++++ let mut info = png::Info::with_size(w, h);++++++ info.color_type = color;++++++ info.bit_depth = depth;++++++ info.palette = palette.map(Into::into);++++++ info.icc_profile = icc.map(Into::into);++++++ let mut writer = png::Encoder::with_info(&mut out, info).unwrap().write_header().unwrap();++++++ writer.write_image_data(data).unwrap();++++++ }++++++ out++++++}++++++++++++/// Rows of `w` one-bit samples (1 white), each on a new byte: lines of glyphs drawn from a few++++++/// shapes at uneven spacing, whose edges move a pixel now and then, as a scan of text has them.++++++/// (Clean, evenly spaced strokes favour Flate over Group 4.)++++++fn strokes(w: u32, h: u32) -> Vec<u8> {++++++ let stride = (w as usize).div_ceil(8);++++++ let mut data = vec![0xFF; stride * h as usize];++++++ let mut seed = 0x9E37_79B9_7F4A_7C15u64;++++++ let mut next = move || {++++++ seed ^= seed << 13;++++++ seed ^= seed >> 7;++++++ seed ^= seed << 17;++++++ seed++++++ };++++++ let (w, h) = (w as usize, h as usize);++++++ for line in (4..h.saturating_sub(18)).step_by(24) {++++++ let mut x = 8;++++++ while x + 16 < w {++++++ let wide = 5 + (next() % 4) as usize;++++++ let shape = next() % 4;++++++ let mut fill = |x0: usize, x1: usize, y0: usize, y1: usize| {++++++ for y in line + y0..line + y1 {++++++ let ragged = |r: u64| match r % 8 {++++++ 0 => 0,++++++ 1 => 2,++++++ _ => 1,++++++ };++++++ let (left, right) = ((x + x0 + 1).saturating_sub(ragged(next())), x + x1 + ragged(next()));++++++ for xx in left..right.saturating_sub(1).min(w) {++++++ data[y * stride + xx / 8] &= !(0x80 >> (xx % 8));++++++ }++++++ }++++++ };++++++ match shape {++++++ 0 => fill(0, 2, 0, 14),++++++ 1 => {++++++ fill(0, wide, 4, 6);++++++ fill(0, wide, 12, 14);++++++ fill(0, 2, 4, 14);++++++ fill(wide - 2, wide, 4, 14);++++++ }++++++ 2 => {++++++ fill(0, 2, 4, 14);++++++ fill(wide - 2, wide, 6, 14);++++++ fill(0, wide - 1, 4, 6);++++++ }++++++ _ => {++++++ fill(0, 2, 7, 14);++++++ fill(0, 2, 2, 4);++++++ }++++++ }++++++ x += wide + 2 + (next() % 2) as usize + if next() % 6 == 0 { 7 } else { 0 };++++++ }++++++ }++++++ data++++++}++++++++++++/// The one-bit samples (true for white) a Group 4 image stream decodes to, through an++++++/// independent decoder.++++++fn g4_rows(s: &Stream) -> Vec<Vec<bool>> {++++++ struct Rows(Vec<Vec<bool>>, Vec<bool>, usize);++++++ impl hayro_ccitt::Decoder for Rows {++++++ fn push_pixel(&mut self, white: bool) {++++++ self.1.push(white);++++++ }++++++ fn push_pixel_chunk(&mut self, white: bool, chunks: u32) {++++++ self.1.extend(std::iter::repeat_n(white, chunks as usize * 8));++++++ }++++++ fn next_line(&mut self) {++++++ let mut row = std::mem::take(&mut self.1);++++++ row.truncate(self.2);++++++ self.0.push(row);++++++ }++++++ }++++++ let (w, h) = (s.dict.int(b"Width").unwrap() as u32, s.dict.int(b"Height").unwrap() as u32);++++++ let settings = hayro_ccitt::DecodeSettings {++++++ columns: w,++++++ rows: h,++++++ end_of_block: true,++++++ end_of_line: false,++++++ rows_are_byte_aligned: false,++++++ encoding: hayro_ccitt::EncodingMode::Group4,++++++ invert_black: false,++++++ };++++++ let mut out = Rows(Vec::new(), Vec::new(), w as usize);++++++ hayro_ccitt::decode(&s.raw, &mut out, &mut hayro_ccitt::DecoderContext::new(settings)).unwrap();++++++ out.0++++++}++++++++++++fn image_stream(doc: &Document, page: usize) -> Stream {++++++ let p = &pages(doc)[page];++++++ let res = doc.resolve(p.get(b"Resources").unwrap()).as_dict().cloned().unwrap();++++++ let xo = doc.resolve(res.get(b"XObject").unwrap()).as_dict().cloned().unwrap();++++++ match &*doc.resolve(xo.get(b"Im0").unwrap()) {++++++ Object::Stream(s) => s.clone(),++++++ _ => panic!("not an image"),++++++ }++++++}++++++++++++/// Black-and-white pictures are stored at one bit per pixel, as CCITT Group 4 when that is++++++/// smaller, whichever way the file holds them: a 1-bit PNG (which decodes to eight bits), eight-bit++++++/// grey of only black and white, a two-colour palette, black-and-white RGB. The bits are the++++++/// picture's. A grey profile stays; a picture with any other shade, colour, or an RGB profile is++++++/// stored as before.++++++#[test]++++++fn black_and_white_images_are_stored_at_one_bit() {++++++ use png::{BitDepth, ColorType};++++++ let (w, h) = (1200u32, 240u32);++++++ let bits = strokes(w, h);++++++ let stride = (w as usize).div_ceil(8);++++++ let white = |x: usize, y: usize| bits[y * stride + x / 8] & (0x80 >> (x % 8)) != 0;++++++ let expected: Vec<Vec<bool>> = (0..h as usize).map(|y| (0..w as usize).map(|x| white(x, y)).collect()).collect();++++++ let grey: Vec<u8> = expected.iter().flatten().map(|&wh| if wh { 255 } else { 0 }).collect();++++++ let rgb: Vec<u8> = grey.iter().flat_map(|&v| [v, v, v]).collect();++++++ let pictures = [++++++ png_of(w, h, ColorType::Grayscale, BitDepth::One, &bits, None, None),++++++ png_of(w, h, ColorType::Grayscale, BitDepth::Eight, &grey, None, None),++++++ png_of(w, h, ColorType::Indexed, BitDepth::One, &bits.iter().map(|b| !b).collect::<Vec<_>>(), Some(vec![255, 255, 255, 0, 0, 0]), None),++++++ png_of(w, h, ColorType::Rgb, BitDepth::Eight, &rgb, None, None),++++++ png_of(w, h, ColorType::Grayscale, BitDepth::One, &bits, None, Some(icc_profile(b"GRAY"))),++++++ ];++++++ let files: Vec<(String, Vec<u8>)> = pictures.into_iter().enumerate().map(|(i, p)| (format!("{i}.png"), p)).collect();++++++ let doc = reopen(&from_images(&files).unwrap());++++++ for page in 0..5 {++++++ let s = image_stream(&doc, page);++++++ assert_eq!((s.dict.int(b"BitsPerComponent"), s.dict.name(b"Filter")), (Some(1), Some(&b"CCITTFaxDecode"[..])), "page {page}");++++++ assert_eq!(g4_rows(&s), expected, "page {page}");++++++ assert!(s.raw.len() < bits.len(), "page {page}: {} bytes, smaller than its one-bit samples", s.raw.len());++++++ }++++++ assert_eq!(image_of(&doc, 3).name(b"ColorSpace"), Some(&b"DeviceGray"[..]), "black-and-white RGB becomes grey");++++++ assert_eq!(icc_of(&doc, &image_of(&doc, 4)).map(|(n, ..)| n), Some(1), "the grey profile stays");++++++++++++ // Another shade, colour, an RGB profile: as before. A tiny picture: one bit, but Flate.++++++ let mut shaded = grey.clone();++++++ shaded[5] = 128;++++++ let mut coloured = rgb.clone();++++++ coloured[0] = 200;++++++ let others = [++++++ png_of(w, h, ColorType::Grayscale, BitDepth::Eight, &shaded, None, None),++++++ png_of(w, h, ColorType::Rgb, BitDepth::Eight, &coloured, None, None),++++++ png_of(w, h, ColorType::Rgb, BitDepth::Eight, &rgb, None, Some(icc_profile(b"RGB "))),++++++ png_of(2, 2, ColorType::Grayscale, BitDepth::Eight, &[0, 255, 255, 0], None, None),++++++ ];++++++ let files: Vec<(String, Vec<u8>)> = others.into_iter().enumerate().map(|(i, p)| (format!("o{i}.png"), p)).collect();++++++ let doc = reopen(&from_images(&files).unwrap());++++++ let kept: Vec<(Option<i64>, Option<Vec<u8>>)> =++++++ (0..4).map(|p| (image_of(&doc, p).int(b"BitsPerComponent"), image_of(&doc, p).name(b"Filter").map(<[u8]>::to_vec))).collect();++++++ assert_eq!(++++++ kept[..3],++++++ [(Some(8), Some(b"FlateDecode".to_vec())), (Some(8), Some(b"FlateDecode".to_vec())), (Some(8), Some(b"FlateDecode".to_vec()))]++++++ );++++++ assert_eq!(kept[3], (Some(1), Some(b"FlateDecode".to_vec())), "Group 4 isn't smaller for 2 × 2");++++++}++++++++++++/// The pixels of an exported PNG (RGB), as true for white.++++++fn exported_white(png_data: &[u8]) -> Vec<bool> {++++++ let mut reader = png::Decoder::new(std::io::Cursor::new(png_data.to_vec())).read_info().unwrap();++++++ let mut buf = vec![0; reader.output_buffer_size().unwrap()];++++++ let frame = reader.next_frame(&mut buf).unwrap();++++++ assert_eq!(frame.color_type, png::ColorType::Rgb);++++++ buf[..frame.buffer_size()].as_chunks::<3>().0.iter().map(|p| *p == [255, 255, 255]).collect()++++++}++++++++++++/// Export ▸ Images reads CCITT fax images: a page created from a 1-bit PNG (Group 4 now) exports as++++++/// the picture, as does the picture coded the other way round with /BlackIs1, the picture with its++++++/// filter and parameters in arrays, with /K and /Columns given by reference, with a /Rows below its++++++/// height, and behind another filter (its parameters by reference too). One whose /Columns aren't++++++/// its width is skipped, not misread.++++++#[test]++++++fn ccitt_fax_images_export_as_their_picture() {++++++ use png::{BitDepth, ColorType};++++++ let (w, h) = (1200u32, 240u32);++++++ let bits = strokes(w, h);++++++ let stride = (w as usize).div_ceil(8);++++++ let picture: Vec<bool> =++++++ (0..h as usize).flat_map(|y| (0..w as usize).map(move |x| (y, x))).map(|(y, x)| bits[y * stride + x / 8] & (0x80 >> (x % 8)) != 0).collect();++++++ let mut doc = from_images(&[("scan.png".into(), png_of(w, h, ColorType::Grayscale, BitDepth::One, &bits, None, None))]).unwrap();++++++ assert_eq!(image_of(&doc, 0).name(b"Filter"), Some(&b"CCITTFaxDecode"[..]));++++++ let out = extract_images(&doc, &[0], 0);++++++ assert!(out.skipped.is_empty(), "{:?}", out.skipped);++++++ assert_eq!(exported_white(&out.images[0].data), picture);++++++++++++ // The same picture coded with 1 for black, which /BlackIs1 says.++++++ let r = {++++++ let page = pdfcraft_model::pages(&doc)[0].clone();++++++ let res = doc.resolve(page.dict.get(b"Resources").unwrap()).as_dict().cloned().unwrap();++++++ let xo = doc.resolve(res.get(b"XObject").unwrap()).as_dict().cloned().unwrap();++++++ xo.get(b"Im0").and_then(Object::as_ref).unwrap()++++++ };++++++ let base = image_of(&doc, 0);++++++ let with = |black_is_1: bool, columns: i64, data: Vec<u8>| {++++++ let mut d = base.clone();++++++ let mut parms = Dict::new();++++++ parms.set(b"K".to_vec(), Object::Int(-1));++++++ parms.set(b"Columns".to_vec(), Object::Int(columns));++++++ parms.set(b"Rows".to_vec(), Object::Int(i64::from(h)));++++++ parms.set(b"BlackIs1".to_vec(), Object::Bool(black_is_1));++++++ d.set(b"DecodeParms".to_vec(), Object::Dict(parms));++++++ d.remove(b"Length");++++++ Stream::from_raw(d, data)++++++ };++++++ let inverted: Vec<u8> = bits.iter().map(|b| !b).collect();++++++ let stream = with(true, i64::from(w), pdfcraft_filters::encode_g4(&inverted, w, h).unwrap());++++++ doc.set(r, Object::Stream(stream));++++++ let out = extract_images(&doc, &[0], 0);++++++ assert_eq!(exported_white(&out.images[0].data), picture, "BlackIs1");++++++++++++ let mut stream = with(false, i64::from(w), pdfcraft_filters::encode_g4(&bits, w, h).unwrap());++++++ let parms = stream.dict.get(b"DecodeParms").cloned().unwrap();++++++ stream.dict.set(b"DecodeParms".to_vec(), Object::Array(vec![parms]));++++++ stream.dict.set(b"Filter".to_vec(), Object::Array(vec![Object::name("CCITTFaxDecode")]));++++++ doc.set(r, Object::Stream(stream));++++++ let out = extract_images(&doc, &[0], 0);++++++ assert!(out.skipped.is_empty(), "{:?}", out.skipped);++++++ assert_eq!(exported_white(&out.images[0].data), picture, "in arrays");++++++++++++ let mut stream = with(false, i64::from(w), pdfcraft_filters::encode_g4(&bits, w, h).unwrap());++++++ let mut parms = stream.dict.get(b"DecodeParms").and_then(Object::as_dict).cloned().unwrap();++++++ parms.set(b"K".to_vec(), Object::Ref(doc.add(Object::Int(-1))));++++++ parms.set(b"Columns".to_vec(), Object::Ref(doc.add(Object::Int(i64::from(w)))));++++++ parms.set(b"Rows".to_vec(), Object::Int(1));++++++ stream.dict.set(b"DecodeParms".to_vec(), Object::Dict(parms));++++++ doc.set(r, Object::Stream(stream));++++++ let out = extract_images(&doc, &[0], 0);++++++ assert!(out.skipped.is_empty(), "{:?}", out.skipped);++++++ assert_eq!(exported_white(&out.images[0].data), picture, "/K and /Columns by reference, /Rows 1");++++++++++++ // Behind another filter, with its parameters second in the array, as 7.4.1 pairs them.++++++ let g4 = pdfcraft_filters::encode_g4(&bits, w, h).unwrap();++++++ let hex = g4.iter().map(|b| format!("{b:02x}")).chain([">".to_string()]).collect::<String>().into_bytes();++++++ for (outer, data) in [("ASCIIHexDecode", hex), ("FlateDecode", pdfcraft_filters::encode_flate(&g4))] {++++++ let mut stream = with(false, i64::from(w), data);++++++ let parms = stream.dict.get(b"DecodeParms").cloned().unwrap();++++++ stream.dict.set(b"DecodeParms".to_vec(), Object::Array(vec![Object::Null, parms]));++++++ stream.dict.set(b"Filter".to_vec(), Object::Array(vec![Object::name(outer), Object::name("CCITTFaxDecode")]));++++++ doc.set(r, Object::Stream(stream));++++++ let out = extract_images(&doc, &[0], 0);++++++ assert!(out.skipped.is_empty(), "{outer}: {:?}", out.skipped);++++++ assert_eq!(exported_white(&out.images[0].data), picture, "behind {outer}");++++++ }++++++ // Behind Flate with a PNG predictor, whose parameters are given by reference.++++++ let padded: Vec<u8> = g4.iter().copied().chain(std::iter::repeat_n(0, 16 - g4.len() % 16)).collect();++++++ let params = pdfcraft_filters::Params { predictor: 12, colors: 1, bits_per_component: 8, columns: 16, early_change: 1 };++++++ let predicted = pdfcraft_filters::encode(&pdfcraft_filters::Filter::Flate, ¶ms, &padded).unwrap();++++++ let mut flate_parms = Dict::new();++++++ flate_parms.set(b"Predictor".to_vec(), Object::Int(12));++++++ flate_parms.set(b"Columns".to_vec(), Object::Int(16));++++++ let flate_parms = doc.add(Object::Dict(flate_parms));++++++ let mut stream = with(false, i64::from(w), predicted);++++++ let parms = stream.dict.get(b"DecodeParms").cloned().unwrap();++++++ stream.dict.set(b"DecodeParms".to_vec(), Object::Array(vec![Object::Ref(flate_parms), parms]));++++++ stream.dict.set(b"Filter".to_vec(), Object::Array(vec![Object::name("FlateDecode"), Object::name("CCITTFaxDecode")]));++++++ doc.set(r, Object::Stream(stream));++++++ let out = extract_images(&doc, &[0], 0);++++++ assert!(out.skipped.is_empty(), "{:?}", out.skipped);++++++ assert_eq!(exported_white(&out.images[0].data), picture, "behind Flate with a predictor given by reference");++++++ // CCITT before another filter isn't a picture yet.++++++ let mut stream = with(false, i64::from(w), pdfcraft_filters::encode_flate(&g4));++++++ stream.dict.set(b"Filter".to_vec(), Object::Array(vec![Object::name("CCITTFaxDecode"), Object::name("FlateDecode")]));++++++ doc.set(r, Object::Stream(stream));++++++ let out = extract_images(&doc, &[0], 0);++++++ assert!(out.images.is_empty() && out.skipped.len() == 1, "CCITT, then Flate: skipped");++++++++++++ let stream = with(false, i64::from(w) + 8, pdfcraft_filters::encode_g4(&bits, w, h).unwrap());++++++ doc.set(r, Object::Stream(stream));++++++ let out = extract_images(&doc, &[0], 0);++++++ assert!(out.images.is_empty() && out.skipped.len() == 1, "columns other than the width: skipped");++++++}++++++++++++/// Group 3 data: rows of run lengths below 64, white first, coded one-dimensionally with T.4's++++++/// terminating codes (ITU-T T.4 Tables 2 and 3). Each row starts with an end-of-line code with++++++/// `eol`, then with `tag` a 1 bit (the next row one-dimensional, as `/K` above 0 has it). Fill bits++++++/// (0s) go where `fill` says.++++++fn group_3(rows: &[impl AsRef<[u32]>], eol: bool, tag: bool, fill: Fill) -> Vec<u8> {++++++ // The codes for runs 0 to 63, in order.++++++ const WHITE: &str = concat!(++++++ "00110101 000111 0111 1000 1011 1100 1110 1111 10011 10100 00111 01000 001000 000011 110100 110101 101010 101011 ",++++++ "0100111 0001100 0001000 0010111 0000011 0000100 0101000 0101011 0010011 0100100 0011000 00000010 00000011 00011010 ",++++++ "00011011 00010010 00010011 00010100 00010101 00010110 00010111 00101000 00101001 00101010 00101011 00101100 00101101 ",++++++ "00000100 00000101 00001010 00001011 01010010 01010011 01010100 01010101 00100100 00100101 01011000 01011001 01011010 ",++++++ "01011011 01001010 01001011 00110010 00110011 00110100",++++++ );++++++ const BLACK: &str = concat!(++++++ "0000110111 010 11 10 011 0011 0010 00011 000101 000100 0000100 0000101 0000111 00000100 00000111 000011000 0000010111 ",++++++ "0000011000 0000001000 00001100111 00001101000 00001101100 00000110111 00000101000 00000010111 00000011000 ",++++++ "000011001010 000011001011 000011001100 000011001101 000001101000 000001101001 000001101010 000001101011 000011010010 ",++++++ "000011010011 000011010100 000011010101 000011010110 000011010111 000001101100 000001101101 000011011010 000011011011 ",++++++ "000001010100 000001010101 000001010110 000001010111 000001100100 000001100101 000001010010 000001010011 000000100100 ",++++++ "000000110111 000000111000 000000100111 000000101000 000001011000 000001011001 000000101011 000000101100 000001011010 ",++++++ "000001100110 000001100111",++++++ );++++++ let code = |white: bool, run: u32| (if white { WHITE } else { BLACK }).split(' ').nth(run as usize).expect("a run below 64");++++++ let mut bits = String::new();++++++ for row in rows {++++++ // The end-of-line code is 12 bits.++++++ let ends_code = if fill == Fill::CodeEnd && eol { 12 } else { 0 };++++++ while fill != Fill::None && !(bits.len() + ends_code).is_multiple_of(8) {++++++ bits.push('0');++++++ }++++++ if eol {++++++ bits.push_str("000000000001");++++++ }++++++ if tag {++++++ bits.push('1');++++++ }++++++ row.as_ref().iter().enumerate().for_each(|(i, run)| bits.push_str(code(i % 2 == 0, *run)));++++++ }++++++ bits.as_bytes().chunks(8).map(|c| c.iter().enumerate().fold(0u8, |b, (i, d)| b | (u8::from(*d == b'1') << (7 - i)))).collect()++++++}++++++++++++/// `count` text-like pictures `w` by `h` for [`group_3`], from a fixed seed: rows of random runs,++++++/// long white ones and short black ones, and a row may start black.++++++fn random_pictures(w: u32, h: u32, count: usize) -> Vec<Vec<Vec<u32>>> {++++++ let mut seed = 0x9E37_79B9_7F4A_7C15u64;++++++ let mut random = |n: u64| {++++++ seed ^= seed << 13;++++++ seed ^= seed >> 7;++++++ seed ^= seed << 17;++++++ (seed % n) as u32++++++ };++++++ let mut row = || {++++++ let (mut runs, mut left) = (Vec::new(), w);++++++ while left > 0 {++++++ let run = match runs.len() % 2 {++++++ 0 if runs.is_empty() => random(31),++++++ 0 => 1 + random(30),++++++ _ => 1 + random(5),++++++ };++++++ runs.push(run.min(left));++++++ left -= run.min(left);++++++ }++++++ runs++++++ };++++++ (0..count).map(|_| (0..h).map(|_| row()).collect()).collect()++++++}++++++++++++/// The picture `rows` of runs (white first) make, `w` by `h`, true where white.++++++fn white_of(rows: &[Vec<u32>], w: u32, h: u32) -> Vec<bool> {++++++ let mut white = vec![false; (w * h) as usize];++++++ for (y, row) in rows.iter().enumerate() {++++++ let mut x = y * w as usize;++++++ for (i, run) in row.iter().enumerate() {++++++ white[x..x + *run as usize].fill(i % 2 == 0);++++++ x += *run as usize;++++++ }++++++ }++++++ white++++++}++++++++++++/// Where [`group_3`] puts fill bits: none; so each row, its end-of-line code first, starts on a++++++/// byte; or so each end-of-line code ends on one (T.4's fill, as TIFF writes it).++++++#[derive(Clone, Copy, Debug, PartialEq)]++++++enum Fill {++++++ None,++++++ RowStart,++++++ CodeEnd,++++++}++++++++++++/// What Export ▸ Images claims for CCITT and for parameters given by reference, each checked++++++/// against the same picture stored another way: Group 3 one-dimensional data (`/K 0`) exports as++++++/// its picture; a CCITT soft mask and a CCITT stencil `/Mask` export as the same masks in Flate;++++++/// and a Flate image's PNG predictor, and an indexed image's lookup table stream with one, read++++++/// the same with their `/DecodeParms` given by reference as direct.++++++#[test]++++++fn group_3_ccitt_masks_and_parameters_by_reference_export_as_their_picture() {++++++ use png::{BitDepth, ColorType};++++++ let (w, h) = (64u32, 16u32);++++++ let rows: Vec<&[u32]> = (0..h).map(|y| if y % 2 == 0 { &[32u32, 32][..] } else { &[16, 16, 32][..] }).collect();++++++ let mut bits = vec![0u8; 8 * h as usize];++++++ for (y, runs) in rows.iter().enumerate() {++++++ let mut x = 0;++++++ for (i, run) in runs.iter().enumerate() {++++++ if i % 2 == 0 {++++++ (x..x + *run as usize).for_each(|xx| bits[y * 8 + xx / 8] |= 0x80 >> (xx % 8));++++++ }++++++ x += *run as usize;++++++ }++++++ }++++++ let picture: Vec<bool> = (0..(w * h) as usize).map(|i| bits[i / 8] & (0x80 >> (i % 8)) != 0).collect();++++++ let mut doc = from_images(&[("scan.png".into(), png_of(w, h, ColorType::Grayscale, BitDepth::One, &bits, None, None))]).unwrap();++++++ let r = {++++++ let page = pdfcraft_model::pages(&doc)[0].clone();++++++ let res = doc.resolve(page.dict.get(b"Resources").unwrap()).as_dict().cloned().unwrap();++++++ let xo = doc.resolve(res.get(b"XObject").unwrap()).as_dict().cloned().unwrap();++++++ xo.get(b"Im0").and_then(Object::as_ref).unwrap()++++++ };++++++ let image = |entries: &[(&str, Object)]| {++++++ let mut d = Dict::new();++++++ d.set(b"Type".to_vec(), Object::name("XObject"));++++++ d.set(b"Subtype".to_vec(), Object::name("Image"));++++++ d.set(b"Width".to_vec(), Object::Int(w.into()));++++++ d.set(b"Height".to_vec(), Object::Int(h.into()));++++++ for (k, v) in entries {++++++ d.set(k.as_bytes().to_vec(), v.clone());++++++ }++++++ d++++++ };++++++ let fax = |k: i64| {++++++ let mut parms = Dict::new();++++++ parms.set(b"K".to_vec(), Object::Int(k));++++++ parms.set(b"Columns".to_vec(), Object::Int(w.into()));++++++ parms.set(b"Rows".to_vec(), Object::Int(h.into()));++++++ [("Filter", Object::name("CCITTFaxDecode")), ("DecodeParms", Object::Dict(parms))]++++++ };++++++ let grey = |bits: i64| [("BitsPerComponent", Object::Int(bits)), ("ColorSpace", Object::name("DeviceGray"))];++++++++++++ // One-dimensional (/K 0) plain, with end-of-line codes, with each row on a byte, and with++++++ // both; mixed (/K 1, each row tagged one-dimensional) with end-of-line codes and without.++++++ // Byte-aligned with end-of-line codes either way: each code starting on a byte, or ending on++++++ // one (T.4's fill, as TIFF writes it). /EncodedByteAlign is given by reference once, and so is++++++ // a /BlackIs1 that inverts the picture.++++++ let inverted: Vec<bool> = picture.iter().map(|white| !white).collect();++++++ for (k, eol, fill, align_by_reference, black_is_1) in [++++++ (0, false, Fill::None, false, false),++++++ (0, true, Fill::None, false, false),++++++ (0, false, Fill::RowStart, true, false),++++++ (0, true, Fill::RowStart, false, false),++++++ (0, true, Fill::CodeEnd, false, false),++++++ (1, true, Fill::None, false, false),++++++ (1, false, Fill::None, false, false),++++++ (1, true, Fill::CodeEnd, false, false),++++++ (0, false, Fill::None, false, true),++++++ ] {++++++ let mut d = image(&[&grey(1)[..], &fax(k)].concat());++++++ let align = Object::Bool(fill != Fill::None);++++++ let align = if align_by_reference { Object::Ref(doc.add(align)) } else { align };++++++ let inverts = Object::Ref(doc.add(Object::Bool(black_is_1)));++++++ if let Some(Object::Dict(parms)) = d.get_mut(b"DecodeParms") {++++++ parms.set(b"EndOfLine".to_vec(), Object::Bool(eol));++++++ parms.set(b"EncodedByteAlign".to_vec(), align);++++++ parms.set(b"BlackIs1".to_vec(), inverts);++++++ }++++++ doc.set(r, Object::Stream(Stream::from_raw(d, group_3(&rows, eol, k > 0, fill))));++++++ let case = format!("/K {k}, EndOfLine {eol}, fill {fill:?}, BlackIs1 {black_is_1}");++++++ let out = extract_images(&doc, &[0], 0);++++++ assert!(out.skipped.is_empty(), "{case}: {:?}", out.skipped);++++++ assert_eq!(exported_white(&out.images[0].data), if black_is_1 { inverted.clone() } else { picture.clone() }, "{case}");++++++ }++++++ // Byte-aligned rows against /EndOfLine, over several pictures, as how a misreading comes out++++++ // depends on the picture: no codes (as TIFF's Modified Huffman has it), and /EndOfLine without++++++ // them; codes, each starting on a byte or ending on one, /EndOfLine or not. Each exports as its++++++ // picture, and a byte short is reported. The first picture is stripes, every row 32 white then++++++ // 32 black; the others are text-like rows of random runs.++++++ let image_with = |doc: &mut Document, k: i64, eol: bool, data: Vec<u8>| {++++++ let mut d = image(&[&grey(1)[..], &fax(k)].concat());++++++ if let Some(Object::Dict(parms)) = d.get_mut(b"DecodeParms") {++++++ parms.set(b"EndOfLine".to_vec(), Object::Bool(eol));++++++ parms.set(b"EncodedByteAlign".to_vec(), Object::Bool(true));++++++ }++++++ doc.set(r, Object::Stream(Stream::from_raw(d, data)));++++++ extract_images(doc, &[0], 0)++++++ };++++++ let mut pictures = vec![vec![vec![32u32, 32]; h as usize]];++++++ pictures.extend(random_pictures(w, h, 8));++++++ for (n, runs) in pictures.iter().enumerate() {++++++ let white = white_of(runs, w, h);++++++ for k in [0, 1] {++++++ for (codes, fill, eol) in [++++++ (false, Fill::RowStart, false),++++++ (false, Fill::RowStart, true),++++++ (true, Fill::RowStart, false),++++++ (true, Fill::RowStart, true),++++++ (true, Fill::CodeEnd, false),++++++ (true, Fill::CodeEnd, true),++++++ ] {++++++ let out = image_with(&mut doc, k, eol, group_3(runs, codes, k > 0, fill));++++++ let case = format!("picture {n}, /K {k}, codes {codes}, fill {fill:?}, /EndOfLine {eol}");++++++ assert!(out.skipped.is_empty(), "{case}: {:?}", out.skipped);++++++ assert_eq!(exported_white(&out.images[0].data), white, "{case}");++++++ // A byte short, it is reported, not read the other way into other rows.++++++ let mut short = group_3(runs, codes, k > 0, fill);++++++ short.pop();++++++ let out = image_with(&mut doc, k, eol, short);++++++ assert!(out.images.is_empty() && out.skipped.len() == 1, "{case}, a byte short: {:?}", out.skipped);++++++ // At /K 1, codes with none before the first row (the first code and its fill are 2++++++ // bytes here) are read on bytes: the picture or reported, never another picture.++++++ if k == 1 && fill == Fill::CodeEnd {++++++ let out = image_with(&mut doc, k, eol, group_3(runs, codes, true, fill).split_off(2));++++++ assert!(out.images.iter().all(|i| exported_white(&i.data) == white), "{case}, no code first");++++++ }++++++ }++++++ }++++++ }++++++ // Group 4 rows on bytes keep their aligned read, /EndOfLine or not: here white rows, each the++++++ // one code 1 (vertical, no change) and its fill.++++++ for eol in [false, true] {++++++ let out = image_with(&mut doc, -1, eol, vec![0x80; h as usize]);++++++ assert!(out.skipped.is_empty(), "byte-aligned Group 4, /EndOfLine {eol}: {:?}", out.skipped);++++++ assert!(exported_white(&out.images[0].data).iter().all(|white| *white), "byte-aligned Group 4, /EndOfLine {eol}");++++++ }++++++++++++ // A grey picture under the same bits as a soft mask, then as a stencil mask: CCITT against Flate.++++++ let g4 = pdfcraft_filters::encode_g4(&bits, w, h).unwrap();++++++ for (key, mask) in [("SMask", grey(1).to_vec()), ("Mask", vec![("ImageMask", Object::Bool(true))])] {++++++ let mut exported = Vec::new();++++++ for coded in [true, false] {++++++ let m = if coded { Stream::from_raw(image(&[&mask[..], &fax(-1)].concat()), g4.clone()) } else { Stream::flate(image(&mask), &bits) };++++++ let m = doc.add(Object::Stream(m));++++++ let d = image(&[&grey(8)[..], &[(key, Object::Ref(m))]].concat());++++++ doc.set(r, Object::Stream(Stream::flate(d, &vec![100u8; (w * h) as usize])));++++++ exported.push(exported_rgba(&doc));++++++ }++++++ assert!(exported[0].1.chunks(4).any(|p| p[3] == 0), "{key}: masked somewhere");++++++ assert_eq!(exported[0], exported[1], "{key}: CCITT as Flate");++++++ }++++++++++++ // A PNG predictor given by reference, for the samples and for a lookup table.++++++ let predicted = |rows: &[u8], columns: i64| {++++++ let params = pdfcraft_filters::Params { predictor: 12, colors: 1, bits_per_component: 8, columns, early_change: 1 };++++++ let mut parms = Dict::new();++++++ parms.set(b"Predictor".to_vec(), Object::Int(12));++++++ parms.set(b"Columns".to_vec(), Object::Int(columns));++++++ (pdfcraft_filters::encode(&pdfcraft_filters::Filter::Flate, ¶ms, rows).unwrap(), parms)++++++ };++++++ let shades: Vec<u8> = (0..w * h).map(|i| (i * 7 % 256) as u8).collect();++++++ let (table, table_parms) = predicted(&[255, 0, 0, 0, 0, 255], 3);++++++ let indices: Vec<u8> = (0..w * h).map(|i| (i % 3 % 2) as u8).collect();++++++ let mut exported = Vec::new();++++++ for by_reference in [false, true] {++++++ let parms = |doc: &mut Document, p: &Dict| if by_reference { Object::Ref(doc.add(Object::Dict(p.clone()))) } else { Object::Dict(p.clone()) };++++++ let (samples, sample_parms) = predicted(&shades, w.into());++++++ let sample_parms = parms(&mut doc, &sample_parms);++++++ let d = image(&[&grey(8)[..], &[("Filter", Object::name("FlateDecode")), ("DecodeParms", sample_parms)]].concat());++++++ doc.set(r, Object::Stream(Stream::from_raw(d, samples)));++++++ let plain = exported_rgba(&doc);++++++++++++ let mut lookup = Dict::new();++++++ lookup.set(b"Filter".to_vec(), Object::name("FlateDecode"));++++++ lookup.set(b"DecodeParms".to_vec(), parms(&mut doc, &table_parms));++++++ let lookup = doc.add(Object::Stream(Stream::from_raw(lookup, table.clone())));++++++ let cs = Object::Array(vec![Object::name("Indexed"), Object::name("DeviceRGB"), 1.into(), Object::Ref(lookup)]);++++++ let d = image(&[("BitsPerComponent", Object::Int(8)), ("ColorSpace", cs)]);++++++ doc.set(r, Object::Stream(Stream::flate(d, &indices)));++++++ exported.push((plain, exported_rgba(&doc)));++++++ }++++++ assert_eq!(exported[0].0.1.chunks(4).map(|p| p[0]).collect::<Vec<_>>(), shades, "the samples, direct");++++++ assert_eq!(exported[0].1.1.get(..8), Some(&[255, 0, 0, 255, 0, 0, 255, 255][..]), "red, then blue");++++++ assert_eq!(exported[1], exported[0], "by reference as direct");++++++}++++++++++++ /// An image whose PNG predictor is given by reference exports as its picture: its `/DecodeParms`+++++ /// dictionary given by reference, as an array's entry, or direct with its numbers by reference. So+++++ /// do an indexed image whose lookup table is a stream with its `/DecodeParms` given by reference,+++++ /// and a JBIG2 image whose `/JBIG2Globals` stream has them so. `Stream::decoded` reads only a+++++ /// direct `/DecodeParms` with direct numbers: the row tags stayed in the samples, and the picture+++++ /// came out shifted.+++++ #[test]+++++ fn images_whose_predictor_is_given_by_reference_export_as_their_picture() {+++++ // PNG predictor parameters for `columns` one-byte samples a row.+++++ let parms = |columns: i64| {+++++ let mut p = Dict::new();+++++ p.set(b"Predictor".to_vec(), Object::Int(15));+++++ p.set(b"Colors".to_vec(), Object::Int(1));+++++ p.set(b"BitsPerComponent".to_vec(), Object::Int(8));+++++ p.set(b"Columns".to_vec(), Object::Int(columns));+++++ p+++++ };+++++ // Two rows of four grey samples, each behind a PNG "None" row tag.+++++ let predicted = pdfcraft_filters::encode_flate(&[0, 10, 20, 30, 40, 0, 50, 60, 70, 80]);+++++ let grey: Vec<u8> = [10u8, 20, 30, 40, 50, 60, 70, 80].iter().flat_map(|v| [*v, *v, *v, 255]).collect();+++++ for form in ["a reference", "an array of a reference", "numbers by reference"] {+++++ let mut doc = from_images(&[("flat.png".into(), png_bytes(false))]).unwrap();+++++ with_image(&mut doc, |doc| {+++++ let mut d = image_dict(4, 2, "DeviceGray", 8);+++++ d.set(b"Filter".to_vec(), Object::name("FlateDecode"));+++++ let decode_parms = match form {+++++ "numbers by reference" => {+++++ let mut p = parms(4);+++++ for key in [&b"Predictor"[..], b"Columns"] {+++++ let v = p.get(key).cloned().unwrap();+++++ p.set(key.to_vec(), Object::Ref(doc.add(v)));+++++ }+++++ Object::Dict(p)+++++ }+++++ "a reference" => Object::Ref(doc.add(Object::Dict(parms(4)))),+++++ _ => Object::Array(vec![Object::Ref(doc.add(Object::Dict(parms(4))))]),+++++ };+++++ d.set(b"DecodeParms".to_vec(), decode_parms);+++++ Stream::from_raw(d, predicted.clone())+++++ });+++++ assert_eq!(exported_rgba(&doc), ("png", grey.clone()), "/DecodeParms as {form}");+++++ }+++++ // An indexed image's lookup table, red then blue, as a stream behind a "None" row tag.+++++ let mut doc = from_images(&[("flat.png".into(), png_bytes(false))]).unwrap();+++++ with_image(&mut doc, |doc| {+++++ let mut t = Dict::new();+++++ t.set(b"Filter".to_vec(), Object::name("FlateDecode"));+++++ t.set(b"DecodeParms".to_vec(), Object::Ref(doc.add(Object::Dict(parms(6)))));+++++ let table = doc.add(Object::Stream(Stream::from_raw(t, pdfcraft_filters::encode_flate(&[0, 255, 0, 0, 0, 0, 255]))));+++++ let mut d = image_dict(4, 1, "DeviceGray", 8);+++++ d.set(b"ColorSpace".to_vec(), Object::Array(vec![Object::name("Indexed"), Object::name("DeviceRGB"), Object::Int(1), Object::Ref(table)]));+++++ Stream::from_raw(d, vec![0, 1, 0, 1])+++++ });+++++ let (red, blue) = ([255, 0, 0, 255], [0, 0, 255, 255]);+++++ assert_eq!(exported_rgba(&doc), ("png", [red, blue, red, blue].concat()), "the lookup table's /DecodeParms by reference");+++++ // A JBIG2 image whose globals hold one extension segment (ISO/IEC 14492 7.4.14) a decoder+++++ // ignores, behind a "None" row tag. With the tag left in, the globals can't be read and the+++++ // image is skipped.+++++ let segment = [0, 0, 0, 0, 0x3E, 0, 0, 0, 0, 0, 4, 0, 0, 0, 1];+++++ let bits = [0xF0u8, 0x0F, 0xAA, 0x55];+++++ let mut doc = from_images(&[("flat.png".into(), png_bytes(false))]).unwrap();+++++ with_image(&mut doc, |doc| {+++++ let mut g = Dict::new();+++++ g.set(b"Filter".to_vec(), Object::name("FlateDecode"));+++++ g.set(b"DecodeParms".to_vec(), Object::Ref(doc.add(Object::Dict(parms(segment.len() as i64)))));+++++ let tagged: Vec<u8> = [0].iter().chain(&segment).copied().collect();+++++ let globals = doc.add(Object::Stream(Stream::from_raw(g, pdfcraft_filters::encode_flate(&tagged))));+++++ let mut decode_parms = Dict::new();+++++ decode_parms.set(b"JBIG2Globals".to_vec(), Object::Ref(globals));+++++ let mut d = image_dict(16, 2, "DeviceGray", 1);+++++ d.set(b"Filter".to_vec(), Object::name("JBIG2Decode"));+++++ d.set(b"DecodeParms".to_vec(), Object::Dict(decode_parms));+++++ Stream::from_raw(d, pdfcraft_filters::encode_jbig2_generic(&bits, 16, 2).unwrap())+++++ });+++++ let picture: Vec<u8> = (0..32).flat_map(|i| if bits[i / 8] & (0x80 >> (i % 8)) != 0 { [255, 255, 255, 255] } else { [0, 0, 0, 255] }).collect();+++++ assert_eq!(exported_rgba(&doc), ("png", picture), "the JBIG2 globals' /DecodeParms by reference");+++++ }+++++++++++ /// An image the optimizer stored as JBIG2 symbols (a symbol dictionary and text regions, rather++++++ /// than one generic region) exports as its picture.++++++ #[test]++++++ fn symbol_coded_jbig2_images_export_as_their_picture() {++++++ const LETTERS: [[&str; 7]; 3] = [++++++ ["#####", "#....", "####.", "#....", "#....", "#....", "#####"],++++++ [".###.", "#...#", "#....", "#....", "#....", "#...#", ".###."],++++++ ["#...#", "#...#", "#####", "#...#", "#...#", "#...#", "#...#"],++++++ ];++++++ let (w, h) = (400usize, 40usize);++++++ let stride = w.div_ceil(8);++++++ // 1 samples white, as a grey image's are; the letters' pixels 0.++++++ let mut bits = vec![0xFFu8; stride * h];++++++ for (line, top) in [2usize, 12, 22, 32].into_iter().enumerate() {++++++ for (k, x) in (3..w - 6).step_by(7).enumerate() {++++++ for (dy, row) in LETTERS[(k + line) % 3].iter().enumerate() {++++++ for (dx, c) in row.bytes().enumerate() {++++++ if c == b'#' {++++++ bits[(top + dy) * stride + (x + dx) / 8] &= !(0x80 >> ((x + dx) % 8));++++++ }++++++ }++++++ }++++++ }++++++ }++++++ let jbig2 = pdfcraft_filters::encode_jbig2(&bits, w as u32, h as u32).unwrap();++++++ let generic = pdfcraft_filters::encode_jbig2_generic(&bits, w as u32, h as u32).unwrap();++++++ assert!(jbig2.len() < generic.len(), "symbol coded: {} bytes, generic {}", jbig2.len(), generic.len());++++++ let mut doc = from_images(&[("flat.png".into(), png_bytes(false))]).unwrap();++++++ with_image(&mut doc, |_| {++++++ let mut d = image_dict(w as i64, h as i64, "DeviceGray", 1);++++++ d.set(b"Filter".to_vec(), Object::name("JBIG2Decode"));++++++ Stream::from_raw(d, jbig2)++++++ });++++++ let picture: Vec<u8> = (0..w * h)++++++ .flat_map(|i| if bits[i / w * stride + i % w / 8] & (0x80 >> (i % w % 8)) != 0 { [255, 255, 255, 255] } else { [0, 0, 0, 255] })++++++ .collect();++++++ assert_eq!(exported_rgba(&doc), ("png", picture));++++++ }+++++++++++ /// Export ▸ Images reads JBIG2 images (ISO 32000-2 §7.4.7), JBIG2 black as 0: as the image, and as+++++ /// a stencil `/Mask` of another. Their `/JBIG2Globals` are read, from a dictionary or the one in+++++ /// an array, so globals that can't be read skip the image rather than being ignored. Rows past the+++++ /// image's height are left out; a JBIG2 page of another width, or with fewer rows than the image,+++++ /// or larger than an exported image may be (however small the image's `/Height`), or data that+++++ /// isn't JBIG2, skips the image.+++++ #[test]+++++ fn jbig2_images_export_as_their_picture() {+++++ let (w, h) = (203i64, 41i64);+++++ let stride = 26;+++++ let mut seed = 0x2545_F491_4F6C_DD1Du64;+++++ let bits: Vec<u8> = (0..stride * h as usize)+++++ .map(|_| {+++++ seed ^= seed << 13;+++++ seed ^= seed >> 7;+++++ seed ^= seed << 17;+++++ seed as u8+++++ })+++++ .collect();+++++ // The first `rows` rows as RGBA: a 1 sample white, a 0 black.+++++ let picture = |rows: i64| -> Vec<u8> {+++++ (0..rows as usize)+++++ .flat_map(|y| (0..w as usize).map(move |x| (x, y)))+++++ .flat_map(|(x, y)| {+++++ let v = if bits[y * stride + x / 8] & (0x80 >> (x % 8)) != 0 { 255 } else { 0 };+++++ [v, v, v, 255]+++++ })+++++ .collect()+++++ };+++++ let jbig2 = pdfcraft_filters::encode_jbig2_generic(&bits, w as u32, h as u32).unwrap();+++++ // A page whose image is `data` as JBIG2, `width` × `height`. With `globals`, its /DecodeParms+++++ // (an array when `.1`) name a globals stream; with `mask`, it is the stencil /Mask of a grey+++++ // image.+++++ let page = |width: i64, height: i64, data: &[u8], globals: Option<(&[u8], bool)>, mask: bool| {+++++ let mut doc = from_images(&[("flat.png".into(), png_bytes(false))]).unwrap();+++++ with_image(&mut doc, |doc| {+++++ let mut d = image_dict(width, height, "DeviceGray", 1);+++++ d.set(b"Filter".to_vec(), Object::name("JBIG2Decode"));+++++ if let Some((g, in_array)) = globals {+++++ let g = doc.add(Object::Stream(Stream::from_raw(Dict::new(), g.to_vec())));+++++ let mut parms = Dict::new();+++++ parms.set(b"JBIG2Globals".to_vec(), Object::Ref(g));+++++ d.set(b"DecodeParms".to_vec(), if in_array { Object::Array(vec![Object::Dict(parms)]) } else { Object::Dict(parms) });+++++ }+++++ if !mask {+++++ return Stream::from_raw(d, data.to_vec());+++++ }+++++ d.remove(b"ColorSpace");+++++ d.set(b"ImageMask".to_vec(), Object::Bool(true));+++++ let m = doc.add(Object::Stream(Stream::from_raw(d, data.to_vec())));+++++ let mut image = image_dict(width, height, "DeviceGray", 8);+++++ image.set(b"Mask".to_vec(), Object::Ref(m));+++++ Stream::from_raw(image, vec![128; (width * height) as usize])+++++ });+++++ doc+++++ };+++++ let skipped = |doc: &Document| {+++++ let out = extract_images(doc, &[0], 0);+++++ out.images.is_empty() && out.skipped.len() == 1+++++ };++++++++++ assert_eq!(exported_rgba(&page(w, h, &jbig2, None, false)), ("png", picture(h)));+++++ assert_eq!(exported_rgba(&page(w, h, &jbig2, Some((&[][..], false)), false)).1, picture(h), "empty globals");+++++ for in_array in [false, true] {+++++ assert!(skipped(&page(w, h, &jbig2, Some((&b"not JBIG2"[..], in_array)), false)), "unreadable globals, in an array: {in_array}");+++++ }+++++ assert_eq!(exported_rgba(&page(w, h - 5, &jbig2, None, false)).1, picture(h - 5), "rows past the height");+++++ for (width, height, data) in [(w + 8, h, &jbig2[..]), (w - 1, h, &jbig2[..]), (w, h + 1, &jbig2[..]), (w, h, &b"not JBIG2"[..])] {+++++ assert!(skipped(&page(width, height, data, None, false)), "{width} × {height}, {} bytes", data.len());+++++ }+++++ // The same stream with its page information (the first segment's data, after its 11-byte+++++ // header: width, then height) claiming a 20,000 × 10,000 page: 200 million pixels, over the+++++ // export's 100 million, behind an image of 20,000 × 4. The decoder would decode the whole page+++++ // (it takes pages of up to about 2^28 pixels), so it is refused first.+++++ let mut large = jbig2.clone();+++++ large[11..15].copy_from_slice(&20_000u32.to_be_bytes());+++++ large[15..19].copy_from_slice(&10_000u32.to_be_bytes());+++++ assert!(skipped(&page(20_000, 4, &large, None, false)), "a page over the export's size");+++++ // Refused the same ways as a stencil /Mask, it is left out: the image exports opaque.+++++ for (width, height, mask) in [(w + 8, h, &jbig2), (20_000, 4, &large)] {+++++ let rgba = exported_rgba(&page(width, height, mask, None, true)).1;+++++ assert_eq!(rgba.len() as i64, width * height * 4, "a {width}-wide mask");+++++ assert!(alphas(&rgba).iter().all(|a| *a == 255), "a refused {width}-wide mask is left out");+++++ }+++++ // A page of exactly the budget, 20,000 × 5,000, is decoded; one row more is refused.+++++ for (rows, refused) in [(5_000u32, false), (5_001, true)] {+++++ large[15..19].copy_from_slice(&rows.to_be_bytes());+++++ let doc = page(20_000, 4, &large, None, false);+++++ assert_eq!(skipped(&doc), refused, "a page of 20,000 × {rows}");+++++ if !refused {+++++ assert_eq!(exported_rgba(&doc).1.len(), 20_000 * 4 * 4);+++++ }+++++ }+++++ // Damaged data never panics.+++++ for end in [0, 1, 10, 20, 30, jbig2.len() / 2] {+++++ let _ = extract_images(&page(w, h, &jbig2[..end], None, false), &[0], 0);+++++ }++++++++++ // As a stencil /Mask, its 1 samples (JBIG2 white) hide the image.+++++ let alpha: Vec<u8> = picture(h).as_chunks::<4>().0.iter().map(|p| 255 - p[0]).collect();+++++ assert_eq!(alphas(&exported_rgba(&page(w, h, &jbig2, None, true)).1), alpha);+++++ }++++++++++ /// A JBIG2 image's `/JBIG2Globals` are decoded before its JBIG2 page's size is known, so they have+++++ /// a limit of their own, 32 MiB, far below the 1 GiB of any stream: globals that Flate-decode to+++++ /// one byte more skip the image, with the limit in the reason, though they take a few kilobytes+++++ /// in the file. Globals of exactly the limit are read, and the limit is the same through an+++++ /// indirect `/DecodeParms`, in an array or not.+++++ #[test]+++++ fn jbig2_globals_are_decoded_within_a_limit_of_their_own() {+++++ const LIMIT: usize = 32 << 20;+++++ let bits = [0xF0u8, 0x0F, 0xAA, 0x55];+++++ let jbig2 = pdfcraft_filters::encode_jbig2_generic(&bits, 16, 2).unwrap();+++++ let picture: Vec<u8> = (0..32).flat_map(|i| if bits[i / 8] & (0x80 >> (i % 8)) != 0 { [255; 4] } else { [0, 0, 0, 255] }).collect();+++++ // Globals of `len` bytes, Flate-encoded: one extension segment (ISO/IEC 14492 7.4.14), which a+++++ // decoder skips; its 11-byte header gives the length of the data after it.+++++ let globals = |len: usize| {+++++ let mut g = vec![0, 0, 0, 0, 0x3E, 0, 0];+++++ g.extend_from_slice(&u32::try_from(len - 11).unwrap().to_be_bytes());+++++ g.extend_from_slice(&[0, 0, 0, 1]);+++++ g.resize(len, 0);+++++ pdfcraft_filters::encode_flate(&g)+++++ };+++++ // The image, its /DecodeParms naming `flated` as its globals: direct (0), by reference (1), or+++++ // by reference in an array (2).+++++ let page = |flated: &[u8], form: usize| {+++++ let mut doc = from_images(&[("flat.png".into(), png_bytes(false))]).unwrap();+++++ with_image(&mut doc, |doc| {+++++ let mut g = Dict::new();+++++ g.set(b"Filter".to_vec(), Object::name("FlateDecode"));+++++ let g = doc.add(Object::Stream(Stream::from_raw(g, flated.to_vec())));+++++ let mut parms = Dict::new();+++++ parms.set(b"JBIG2Globals".to_vec(), Object::Ref(g));+++++ let parms = match form {+++++ 0 => Object::Dict(parms),+++++ 1 => Object::Ref(doc.add(Object::Dict(parms))),+++++ _ => Object::Array(vec![Object::Ref(doc.add(Object::Dict(parms)))]),+++++ };+++++ let mut d = image_dict(16, 2, "DeviceGray", 1);+++++ d.set(b"Filter".to_vec(), Object::name("JBIG2Decode"));+++++ d.set(b"DecodeParms".to_vec(), parms);+++++ Stream::from_raw(d, jbig2.clone())+++++ });+++++ doc+++++ };++++++++++ let (small, full, over) = (globals(15), globals(LIMIT), globals(LIMIT + 1));+++++ assert!(over.len() < 64 << 10, "the oversized globals take {} bytes in the file", over.len());+++++ assert_eq!(exported_rgba(&page(&full, 0)).1, picture, "globals of exactly the limit");+++++ for form in 0..3 {+++++ assert_eq!(exported_rgba(&page(&small, form)).1, picture, "small globals, form {form}");+++++ let out = extract_images(&page(&over, form), &[0], 0);+++++ assert!(out.images.is_empty(), "globals over the limit, form {form}");+++++ let why = &out.skipped.first().expect("the image is skipped").2;+++++ assert!(why.starts_with("the JBIG2 globals can't be read") && why.contains(&format!("limit of {LIMIT} bytes")), "{why}");+++++ }+++++ }diff --cc crates/edit/src/tests.rsindex 359155015,359155015,359155015,f74bb0292,b601db565,359155015,359155015..64bc9e8da--- a/crates/edit/src/tests.rs+++ b/crates/edit/src/tests.rs@@@@@@@@ -7536,24 -7536,24 -7536,24 -7839,3 -8173,24 -7536,24 -7536,24 +8512,47 @@@@@@@@ fn a_run_of_spaces_in_a_subset_without_let content = String::from_utf8_lossy(&page_content_bytes(&reopen(&doc), 0)).into_owned();assert_eq!(content.matches("[-330] TJ").count(), 5, "{content}");}++ /// Inside a text object `q`/`Q` save and restore the text and text line matrices (ISO 32000-2+ /// §9.4.1, as corrected by the PDF Association's errata, issue 368), as the renderer does: the+ /// text after `Q` is found, and stays, where it is drawn.+ #[test]+ fn q_inside_a_text_object_restores_the_text_matrices() {+ for (content, text, baseline) in [+ ("BT /F1 12 Tf 72 700 Td q 0 -100 Td Q (After) Tj ET", "After", [72.0, 700.0]),+ ("BT /F1 12 Tf 72 700 Td q 1 0 0 1 300 300 Tm Q (After) Tj ET", "After", [72.0, 700.0]),+ // `T*` moves from the restored line, not the one set inside q/Q.+ ("BT /F1 12 Tf 14 TL 72 700 Td q 0 -100 Td Q T* (Next) Tj ET", "Next", [72.0, 686.0]),+ ] {+ let mut doc = text_page(content);+ let lines = text::text_lines(&doc, 0).unwrap();+ assert_eq!((lines[0].text.as_str(), lines[0].baseline()), (text, baseline), "{content}");+ text::replace_line(&mut doc, 0, 0, "Edited").unwrap();+ let doc = reopen(&doc);+ let lines = text::text_lines(&doc, 0).unwrap();+ assert_eq!((lines[0].text.as_str(), lines[0].baseline()), ("Edited", baseline), "{content} after editing");+ }+ }++++++++++++++/// Integration of #4180 and #2529: soft wraps retain the source paragraph's alignment,+++++++/// while a typed newline advances to the next alignment and survives a save/reopen.+++++++#[test]+++++++fn wrapped_rows_keep_alignment_separate_from_hard_break_markers() {+++++++ let mut doc = text_page("BT /F1 10 Tf 12 TL 72 700 Td (Old) Tj ET");+++++++ let style = text::BlockStyle {+++++++ width: Some(60.0),+++++++ aligns: vec![Some(added::Align::Left), Some(added::Align::Right)],+++++++ ..Default::default()+++++++ };+++++++ text::rewrite_block(&mut doc, 0, 0, Some("One two three four five six\nTail"), &style).unwrap();+++++++ let doc = reopen(&doc);+++++++ let lines = text::text_lines(&doc, 0).unwrap();+++++++ assert!(lines.len() > 2, "the first logical row must wrap");+++++++ let tail = lines.iter().find(|line| line.text == "Tail").unwrap();+++++++ assert!((tail.rect[2] - 132.0).abs() < 1.0, "the second logical row stays right-aligned: {:?}", tail.rect);+++++++ for line in lines.iter().filter(|line| line.text != "Tail") {+++++++ assert!((line.rect[0] - 72.0).abs() < 1.0, "soft-wrapped rows stay left-aligned: {:?}", line.rect);+++++++ }+++++++ let content = String::from_utf8_lossy(&page_content_bytes(&doc, 0)).into_owned();+++++++ assert!(content.contains("/PCSoft") && content.contains("/PCHard"), "both break kinds survive: {content}");+++++++}diff --cc crates/edit/src/text.rsindex eb4520935,eb4520935,eb4520935,ece164c79,b366e36f4,eb4520935,eb4520935..98824c769--- a/crates/edit/src/text.rs+++ b/crates/edit/src/text.rs@@@@@@@@ -204,40 -204,40 -204,40 -204,44 -213,62 -204,40 -204,40 +213,62 @@@@@@@@ mod testsassert!(!same_base_font("Arial", ""));}- fn rows(lines: Vec<(String, usize)>) -> Vec<String> {- lines.into_iter().map(|(line, _)| line).collect()++++ ++ fn wrapped(text: &str, width: f64) -> Vec<String> {++++ ++ wrap(text, width, |s| s.chars().count() as f64).into_iter().map(|(line, _, _)| line).collect()+++ ++ }+++ ++#[test]fn paragraph_wrapping_keeps_ideographic_spaces() {++++ ++ assert_eq!(wrapped("A B C", 4.0), ["A B", "C"]);++++ ++ assert_eq!(wrapped("A\u{a0}B C", 3.0), ["A B", "C"]);++++ ++ assert_eq!(wrapped("A\u{2028}B C", 3.0), ["A B", "C"]);++++ ++ // `wrap` treats every whitespace character, including `\r`, as a separator to keep++++ ++ // (#4199); the caller turns `\r\n` and `\r` into `\n` before calling it.++++ ++ assert_eq!(wrapped(" \tA B\r\nC ", 3.0), [" A", "B ", "C "]);++++ ++ }++++ ++++++ ++ #[test]++++ ++ fn a_wrap_is_marked_soft_and_a_newline_is_not() {let width = |s: &str| s.chars().count() as f64;--- -- assert_eq!(wrap("A B C", 4.0, width), ["A B", "C"]);--- -- assert_eq!(wrap("A\u{a0}B C", 3.0, width), ["A B", "C"]);--- -- assert_eq!(wrap("A\u{2028}B C", 3.0, width), ["A B", "C"]);- assert_eq!(rows(wrap("A B C", 4.0, width)), ["A B", "C"]);- assert_eq!(rows(wrap("A\u{a0}B C", 3.0, width)), ["A B", "C"]);- assert_eq!(rows(wrap("A\u{2028}B C", 3.0, width)), ["A B", "C"]);++++ ++ assert_eq!(wrap("Page 1", 5.0, width), [("Page".into(), false, 0), ("1".into(), true, 1)]);++++ ++ assert_eq!(wrap("One\nTwo", 10.0, width), [("One".into(), false, 0), ("Two".into(), false, 0)]);++++ ++ }++++ ++++++ ++ /// #2529: a run of spaces that happens to fall at a wrap point is recorded exactly, not++++ ++ /// assumed to be one space; a Chinese/Japanese word split, which has no space of its own,++++ ++ /// is recorded as none.++++ ++ #[test]++++ ++ fn a_wrap_records_how_many_spaces_it_consumed() {++++ ++ let width = |s: &str| s.chars().count() as f64;++++ ++ assert_eq!(wrap("One Two", 5.0, width), [("One".into(), false, 0), ("Two".into(), true, 2)]);++++ ++ assert_eq!(wrap("One Two", 5.0, width), [("One".into(), false, 0), ("Two".into(), true, 3)]);++++ ++ assert_eq!(wrap("日本語の文章です", 3.0, width), [("日本語".into(), false, 0), ("の文章".into(), true, 0), ("です".into(), true, 0)]);}/// #4199: a run of spaces stays a run, before, between and after words; the spaces where a/// row wraps go, and each other white-space character is one space.#[test]fn paragraph_wrapping_keeps_every_space_typed() {---- -- let width = |s: &str| s.chars().count() as f64;--- -- assert_eq!(wrap("a b c", 20.0, width), ["a b c"]);--- -- assert_eq!(wrap(" a b ", 20.0, width), [" a b "]);--- -- assert_eq!(wrap("a\t\tb", 20.0, width), ["a b"]);--- -- assert_eq!(wrap("aa bb cc", 6.0, width), ["aa bb", "cc"]);- assert_eq!(rows(wrap("a b c", 20.0, width)), ["a b c"]);- assert_eq!(rows(wrap(" a b ", 20.0, width)), [" a b "]);- assert_eq!(rows(wrap("a\t\tb", 20.0, width)), ["a b"]);- assert_eq!(rows(wrap("aa bb cc", 6.0, width)), ["aa bb", "cc"]);++++ ++ assert_eq!(wrapped("a b c", 20.0), ["a b c"]);++++ ++ assert_eq!(wrapped(" a b ", 20.0), [" a b "]);++++ ++ assert_eq!(wrapped("a\t\tb", 20.0), ["a b"]);++++ ++ assert_eq!(wrapped("aa bb cc", 6.0), ["aa bb", "cc"]);// An indent alone on a row doesn't wrap before its first word.--- -- assert_eq!(wrap(" abc", 3.0, width), [" abc"]);- assert_eq!(rows(wrap(" abc", 3.0, width)), [" abc"]);++++ ++ assert_eq!(wrapped(" abc", 3.0), [" abc"]);// The rewrite turns `\r\n` and `\r` into `\n` before wrapping.--- -- assert_eq!(wrap(" \tA B\nC ", 3.0, width), [" A", "B", "C "]);--- -- assert_eq!(wrap(" ", 3.0, width), [" "]);--- -- assert_eq!(wrap("", 3.0, width), [""]);- assert_eq!(rows(wrap(" \tA B\nC ", 3.0, width)), [" A", "B", "C "]);- assert_eq!(rows(wrap(" ", 3.0, width)), [" "]);- assert_eq!(rows(wrap("", 3.0, width)), [""]);++++ ++ assert_eq!(wrapped(" \tA B\nC ", 3.0), [" A", "B", "C "]);++++ ++ assert_eq!(wrapped(" ", 3.0), [" "]);++++ ++ assert_eq!(wrapped("", 3.0), [""]);}#[test]fn japanese_text_wraps_between_characters_but_not_before_closing_marks() {---- -- let width = |s: &str| s.chars().count() as f64;--- -- assert_eq!(wrap("日本語の文章です。", 3.0, width), ["日本語", "の文章", "です。"]);- assert_eq!(rows(wrap("日本語の文章です。", 3.0, width)), ["日本語", "の文章", "です。"]);++++ ++ assert_eq!(wrapped("日本語の文章です。", 3.0), ["日本語", "の文章", "です。"]);// The comma can't begin a row, so the character before it moves down with it.--- -- assert_eq!(wrap("あいう、えお", 3.0, width), ["あい", "う、え", "お"]);- assert_eq!(rows(wrap("あいう、えお", 3.0, width)), ["あい", "う、え", "お"]);++++ ++ assert_eq!(wrapped("あいう、えお", 3.0), ["あい", "う、え", "お"]);// Pieces of one word join without a space; separate words keep theirs.--- -- assert_eq!(wrap("Edit PDFを編集", 6.0, width), ["Edit", "PDFを編集"]);--- -- assert_eq!(wrap("一行目 二行目", 4.0, width), ["一行目 ", "二行目"]);- assert_eq!(rows(wrap("Edit PDFを編集", 6.0, width)), ["Edit", "PDFを編集"]);- assert_eq!(rows(wrap("一行目 二行目", 4.0, width)), ["一行目 ", "二行目"]);++++ ++ assert_eq!(wrapped("Edit PDFを編集", 6.0), ["Edit", "PDFを編集"]);++++ ++ assert_eq!(wrapped("一行目 二行目", 4.0), ["一行目 ", "二行目"]);}#[test]diff --cc crates/edit/src/text/blocks.rsindex 615e7699a,615e7699a,615e7699a,2b76c8ab1,d6dcc585f,615e7699a,615e7699a..9ddf4db4b--- a/crates/edit/src/text/blocks.rs+++ b/crates/edit/src/text/blocks.rs@@@@@@@@ -337,11 -337,11 -337,11 -337,11 -340,18 -337,11 -337,11 +340,18 @@@@@@@@ pub(crate) fn paragraph_separator(c: ch/// new line. A row may also end inside a word of Chinese or Japanese text ([`crate::linebreak`]);/// those pieces join without a space. Every white-space character is written as one space, so/// a run of spaces typed between, before or after words stays (#4199); only the spaces where a--- --/// row wraps are dropped.--- --pub(super) fn wrap(text: &str, width: f64, advance: impl Fn(&str) -> f64) -> Vec<String> {- /// row wraps are dropped. Each line comes with the `\n`-separated row it is from.- pub(super) fn wrap(text: &str, width: f64, advance: impl Fn(&str) -> f64) -> Vec<(String, usize)> {++++ ++/// row wraps are dropped (recorded as the third value, so a later rejoin can restore the exact++++ ++/// count instead of guessing one, #2529). The bool is true when the line continues the previous++++ ++/// one because the next word did not fit, rather than because of a newline; the number is how++++ ++/// many separator characters stood where that wrap fell (0 for a Chinese/Japanese word split,++++ ++/// which has no space of its own; meaningless when the bool is false).++++ ++pub(super) fn wrap(text: &str, width: f64, advance: impl Fn(&str) -> f64) -> Vec<(String, bool, usize)> {let mut out = Vec::new();- for (index, row) in text.split('\n').enumerate() {+ for row in text.split('\n') {let mut line = String::new();++++ ++ let mut soft = false;++++ ++ // The gap consumed right before `line` started: 0 until a wrap sets it.++++ ++ let mut wrap_gap = 0usize;let start = out.len();// The separators read since the last word: each one boundary between `split` pieces.let mut gap = 0usize;@@@@@@@@ -357,7 -357,7 -357,7 -357,7 -368,11 -357,7 -357,7 +368,11 @@@@@@@@let candidate = if i == 0 { format!("{line}{spaces}{piece}") } else { format!("{line}{piece}") };// A row holding only the spaces that indent it doesn't wrap before its first word.if line.chars().any(|c| c != ' ') && advance(&candidate) > width {--- -- out.push(std::mem::take(&mut line));- out.push((std::mem::take(&mut line), index));++++ ++ out.push((std::mem::take(&mut line), soft, wrap_gap));++++ ++ soft = true;++++ ++ // A mid-word piece (i > 0) had no separator of its own; the first piece of a++++ ++ // word had exactly the separators just taken.++++ ++ wrap_gap = if i == 0 { gap_here } else { 0 };line = piece.to_string();} else {line = candidate;@@@@@@@@ -366,7 -366,7 -366,7 -366,7 -381,7 -366,7 -366,7 +381,7 @@@@@@@@}line.push_str(&" ".repeat(gap));if !line.is_empty() || out.len() == start {--- -- out.push(line);- out.push((line, index));++++ ++ out.push((line, soft, wrap_gap));}}outdiff --cc crates/edit/src/text/rewrite.rsindex 513077a02,513077a02,513077a02,97712858a,4b6944dee,513077a02,513077a02..976f8a1b1--- a/crates/edit/src/text/rewrite.rs+++ b/crates/edit/src/text/rewrite.rs@@@@@@@@ -578,14 -578,14 -578,14 -585,23 -578,40 -578,14 -578,14 +585,41 @@@@@@@@ impl LineWriter<'_>}}--- -- /// Writes one wrapped line, returning its underline (x0, x1, y) in text space.--- -- fn write_line(&self, index: usize, line: &str, last: bool, cursor: &mut LineCursor, ops: &mut Vec<Op>) -> Result<(f64, f64, f64), EditError> {- /// Writes one wrapped line of row `row`, returning its underline (x0, x1, y) in text space.- /// Writes one wrapped line, returning its underline (x0, x1, y) in text space. `wrap`: whether+++++++ /// Writes one wrapped line of its logical draft row, returning its underline (x0, x1, y) in text space. `wrap`: whether++++ ++ /// this line continues the previous one because a word did not fit, and, when it does, how++++ ++ /// many separator characters the wrap consumed (0 for a Chinese/Japanese word split).+++ ++ fn write_line(+++ ++ &self,+++ ++ index: usize,- row: usize,+++ ++ line: &str,- wrap: (bool, usize),+++++++ wrap: (usize, bool, usize),+++ ++ last: bool,+++ ++ cursor: &mut LineCursor,+++ ++ ops: &mut Vec<Op>,+++ ++ ) -> Result<(f64, f64, f64), EditError> {let n = pdfcraft_content::num;- let (soft, gap) = wrap;+++++++ let (row, soft, gap) = wrap;+++ +++ let line_align = self.align_of(row);let body = line.trim_matches(' ');let interior = body.matches(' ').count();--- --- let tw = self.stretch(body, last);+++ +++ let tw = self.stretch(body, last, line_align == Some(crate::added::Align::Justify));let (shown, visible) = self.shown(line, body, tw);--- --- let dx = if tw > 0.0 { 0.0 } else { self.alignment.offset(visible) };+++ +++ let dx = if tw > 0.0 { 0.0 } else { self.alignment.offset(visible, line_align) };++++ ++ if index > 0 {++++ ++ // Inside this text object, so the marker starts and ends here. `/PCHard` is a newline++++ ++ // that was already in the text. `/PCSoft` rejoins when the box widens, with `/N` the++++ ++ // exact number of separator characters the wrap consumed (0 for a Chinese/Japanese++++ ++ // word split), so a rejoin restores what was actually there instead of guessing a++++ ++ // single space and silently dropping the rest of a typed run (#2529).++++ ++ if soft {++++ ++ let mut properties = Dict::new();++++ ++ properties.set(b"N".to_vec(), Object::Int(i64::try_from(gap).unwrap_or(i64::MAX)));++++ ++ ops.push(Op::new("BDC", vec![Object::name("PCSoft"), Object::Dict(properties)]));++++ ++ } else {++++ ++ ops.push(Op::new("BMC", vec![Object::name("PCHard")]));++++ ++ }++++ ++ ops.push(Op::new("EMC", vec![]));++++ ++ }if index > 0 || dx != 0.0 {ops.push(Op::new("Td", vec![n(dx - cursor.x), n(if index > 0 { -self.lead } else { 0.0 })]));}@@@@@@@@ -633,8 -633,8 -633,8 -649,8 -659,12 -633,8 -633,8 +667,18 @@@@@@@@}/// Writes every wrapped line, returning their underlines.--- -- fn write_all(&self, wrapped: &[String], cursor: &mut LineCursor, ops: &mut Vec<Op>) -> Result<Vec<(f64, f64, f64)>, EditError> {--- -- wrapped.iter().enumerate().map(|(i, line)| self.write_line(i, line, i + 1 == wrapped.len(), cursor, ops)).collect()- fn write_all(&self, wrapped: &[(String, usize)], cursor: &mut LineCursor, ops: &mut Vec<Op>) -> Result<Vec<(f64, f64, f64)>, EditError> {- wrapped.iter().enumerate().map(|(i, (line, row))| self.write_line(i, *row, line, i + 1 == wrapped.len(), cursor, ops)).collect()++++ ++ fn write_all(&self, wrapped: &[(String, bool, usize)], cursor: &mut LineCursor, ops: &mut Vec<Op>) -> Result<Vec<(f64, f64, f64)>, EditError> {+++++++ let mut row = 0usize;++++ ++ wrapped++++ ++ .iter()++++ ++ .enumerate()- .map(|(i, (line, soft, gap))| self.write_line(i, line, (*soft, *gap), i + 1 == wrapped.len(), cursor, ops))+++++++ .map(|(i, (line, soft, gap))| {+++++++ if i > 0 && !soft {+++++++ row = row.saturating_add(1);+++++++ }+++++++ self.write_line(i, line, (row, *soft, *gap), i + 1 == wrapped.len(), cursor, ops)+++++++ })++++ ++ .collect()}}@@@@@@@@ -653,7 -653,7 -653,7 -669,7 -683,7 -653,7 -653,7 +697,7 @@@@@@@@ struct BlockPlan<'a>underline: bool,}--- --fn block_ops(plan: &BlockPlan<'_>, writer: &LineWriter<'_>, wrapped: &[String], show_font: String) -> Result<Vec<Op>, EditError> {- fn block_ops(plan: &BlockPlan<'_>, writer: &LineWriter<'_>, wrapped: &[(String, usize)], show_font: String) -> Result<Vec<Op>, EditError> {++++ ++fn block_ops(plan: &BlockPlan<'_>, writer: &LineWriter<'_>, wrapped: &[(String, bool, usize)], show_font: String) -> Result<Vec<Op>, EditError> {let n = pdfcraft_content::num;let mut ops = vec![Op::new("q", vec![])];ops.extend(reveal_ops(plan.block, plan.lines, plan.style, plan.emit.ctm)?);diff --cc crates/edit/src/text_regions/styled.rsindex e8b3b683d,e8b3b683d,e8b3b683d,40318dc35,ea18a2a21,e8b3b683d,e8b3b683d..885a0a715--- a/crates/edit/src/text_regions/styled.rs+++ b/crates/edit/src/text_regions/styled.rs@@@@@@@@ -401,13 -401,13 -401,13 -401,16 -401,21 -401,13 -401,13 +401,26 @@@@@@@@ fn paragraph_geometry(doc: &Document, pOk((dx, dy, style.width.unwrap_or(natural).clamp(1.0, 14_400.0)))}+++++++type WrappedStyledRows = (StyledRows, RowRanges, Vec<usize>, Vec<bool>, Vec<usize>);+++++++fn wrap_styled_rows(chars: &[StyledChar],width: f64,measure: impl Fn(&[StyledChar]) -> Result<f64, EditError>,--- --) -> Result<(StyledRows, RowRanges), EditError> {- ) -> Result<(StyledRows, RowRanges, Vec<usize>), EditError> {- ) -> Result<(StyledRows, RowRanges, Vec<bool>, Vec<usize>), EditError> {+++++++) -> Result<WrappedStyledRows, EditError> {let mut rows: Vec<Vec<StyledChar>> = Vec::new();let mut row_ranges = Vec::new();- // Each row's line in the draft (its '\n'-separated part), which [`BlockStyle::aligns`] counts.++++ ++ // True when this row starts because the previous word did not fit, not because of a newline.++++ ++ let mut row_soft = Vec::new();++++ ++ let mut next_soft = false;++++ ++ // How many separator characters a wrap trimmed off the row that just ended, for the row++++ ++ // about to start (0 for a Chinese/Japanese word split, which trims none; meaningless unless++++ ++ // the row it belongs to is soft). Mirrors `next_soft`.++++ ++ let mut row_gap = Vec::new();++++ ++ let mut next_gap = 0usize;+++++++ // Logical draft rows drive per-paragraph alignment independently of soft wraps.+++ +++ let mut row_lines: Vec<usize> = Vec::new();+++ +++ let mut draft_line = 0usize;let mut row_start = 0;let mut row = Vec::new();let mut row_width = 0.0;@@@@@@@@ -419,7 -419,7 -419,7 -422,9 -427,11 -419,7 -419,7 +432,13 @@@@@@@@continue;}if item.0 == '\n' {++++ ++ row_soft.push(next_soft);++++ ++ next_soft = false;++++ ++ row_gap.push(next_gap);++++ ++ next_gap = 0;row_ranges.push(row_start..row_start + row.len());+++ +++ row_lines.push(draft_line);+++ +++ draft_line = draft_line.saturating_add(1);rows.push(std::mem::take(&mut row));row_width = 0.0;at += 1;@@@@@@@@ -439,10 -439,10 -439,10 -444,11 -451,16 -439,10 -439,10 +458,17 @@@@@@@@let word = chars.get(at..end).unwrap_or_default();let word_width = measure(word)?;if !row.is_empty() && !item.0.is_whitespace() && row_width + word_width > width + 0.5 {++++ ++ let mut trimmed = 0usize;while row.last().is_some_and(|c: &StyledChar| c.0.is_whitespace()) {row.pop();++++ ++ trimmed += 1;}++++ ++ row_soft.push(next_soft);++++ ++ next_soft = true;++++ ++ row_gap.push(next_gap);++++ ++ next_gap = trimmed;row_ranges.push(row_start..row_start + row.len());+++ +++ row_lines.push(draft_line);rows.push(std::mem::take(&mut row));row_width = 0.0;row_start = at;@@@@@@@@ -452,10 -452,10 -452,10 -458,11 -470,12 -452,10 -452,10 +478,13 @@@@@@@@at = end;}if !row.is_empty() {++++ ++ row_soft.push(next_soft);++++ ++ row_gap.push(next_gap);row_ranges.push(row_start..row_start + row.len());+++ +++ row_lines.push(draft_line);rows.push(row);}--- -- Ok((rows, row_ranges))- Ok((rows, row_ranges, row_lines))- Ok((rows, row_ranges, row_soft, row_gap))+++++++ Ok((rows, row_ranges, row_lines, row_soft, row_gap))}fn apply_range_styles<'a>(@@@@@@@@ -762,7 -762,7 -762,7 -769,7 -940,7 -762,7 -762,7 +949,7 @@@@@@@@ pub(crate) fn rewrite_styled_block}Ok(width)};--- -- let (rows, row_ranges) = wrap_styled_rows(&chars, width, measure)?;- let (rows, row_ranges, row_lines) = wrap_styled_rows(&chars, width, measure)?;- let (rows, row_ranges, row_soft, row_gap) = wrap_styled_rows(&chars, width, measure)?;+++++++ let (rows, row_ranges, row_lines, row_soft, row_gap) = wrap_styled_rows(&chars, width, measure)?;let streams = content_streams(doc, &p.dict)?;let pieces = Pieces::join(&streams.iter().map(|(_, d)| d.as_slice()).collect::<Vec<_>>());let ops = pieces.parse().ops;@@@@@@@@ -823,11 -823,11 -823,11 -836,13 -1007,14 -823,11 -823,11 +1022,16 @@@@@@@@baseline -= source_leading;continue;}++++ ++ if !row.is_empty() && row_index > 0 {++++ ++ push_row_break_marker(&mut block_ops, &row_soft, &row_gap, row_index);++++ ++ }let w = measured.get(row_index).copied().unwrap_or(0.0);--- --- let align = style.align.unwrap_or(if centered { crate::added::Align::Center } else { crate::added::Align::Left });+++ +++ // The row's own alignment, or the paragraph's.+++ +++ let asked = row_lines.get(row_index).and_then(|l| style.aligns.get(*l)).copied().flatten().or(style.align);+++ +++ let align = asked.unwrap_or(if centered { crate::added::Align::Center } else { crate::added::Align::Left });let original_rect = block.rows.get(row_index).and_then(|row| row_rect(row, lines)).unwrap_or(block.rect);--- --- let left = if style.width.is_none() && style.align.is_none() { original_rect[0] } else { block.rect[0] };--- --- let available = if style.width.is_none() && style.align.is_none() { original_rect[2] - original_rect[0] } else { width };+++ +++ let left = if style.width.is_none() && asked.is_none() { original_rect[0] } else { block.rect[0] };+++ +++ let available = if style.width.is_none() && asked.is_none() { original_rect[2] - original_rect[0] } else { width };let mut x = left+ match align {crate::added::Align::Center => (available - w) / 2.0,diff --cc crates/engine/src/lib.rsindex c8744c4a0,c41c0466c,c41c0466c,ee4383eb3,c41c0466c,c41c0466c,c41c0466c..7cd2f96a9--- a/crates/engine/src/lib.rs+++ b/crates/engine/src/lib.rs@@@@@@@@ -66,8 -66,8 -66,8 -65,8 -66,8 -66,8 -66,8 +66,8 @@@@@@@@ pub use links::};pub use signature_image::{ImageSignaturePreview, SignatureImage};pub use signature_scan::{PhotoRect, ScanError, SignaturePhoto, Turn};------pub use stamp_preview::StampPreview;- pub use text_preview::TextEditPreview;++++++pub use stamp_preview::{CommentLayer, StampPreview};+ pub use text_preview::{TextEditPreview, UnmarkedPages};pub use pdfcraft_organize::{BoxSpec, FieldConflicts, PageBox, SplitBy, Transition, TransitionSpec, mime_for_name, split_ranges};diff --cc crates/engine/src/tests.rsindex 174433236,6a68916df,6a68916df,35d743360,6a68916df,6a68916df,6a68916df..7147af2d4--- a/crates/engine/src/tests.rs+++ b/crates/engine/src/tests.rs@@@@@@@@ -3227,98 -3149,45 -3149,45 -3002,6 -3149,45 -3149,45 -3149,45 +3227,98 @@@@@@@@ fn headers_footers_watermarks_and_backgassert_eq!(s.get(id).unwrap().can_undo(), Some("Remove background"));}++++++/// One 100 × 100 page under a background (`/PCMark /Background`), its own content painting a++++++/// white backdrop first. With `copy`, that content is a backdrop copy whose tag is `copy`.++++++fn backdrop_pdf(copy: Option<&str>) -> Vec<u8> {++++++ let bg = "q 1 0 0 rg 0 0 100 100 re f Q";++++++ let (tag, fill) = match copy {++++++ Some(tag) => (format!("/PCBackdrop {tag} "), "n"),++++++ None => (String::new(), "f"),++++++ };++++++ let content = format!("1 g 0 0 100 100 re {fill} 0 g BT /F1 12 Tf 10 50 Td (Hi) Tj ET");++++++ format!(++++++ "%PDF-1.7\n\++++++ 1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n\++++++ 2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj\n\++++++ 3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] /Contents [4 0 R 5 0 R] /Resources << /Font << /F1 << /Type /Font /Subtype /Type1 /BaseFont /Helvetica >> >> >> >> endobj\n\++++++ 4 0 obj << /PCMark /Background /Length {} >> stream\n{bg}\nendstream endobj\n\++++++ 5 0 obj << {tag}/Length {} >> stream\n{content}\nendstream endobj\n\++++++ trailer << /Root 1 0 R >>\n%%EOF",++++++ bg.len(),++++++ content.len()++++++ )++++++ .into_bytes()++++++}++++++++++++/// Remove background says which pages keep their own white backdrop off (it couldn't be turned++++++/// back on safely), and says nothing when every backdrop comes back.++++++#[test]++++++fn remove_background_names_the_pages_whose_own_backdrop_stays_off() {++++++ let mut s = Session::new();++++++ // A tag whose hash doesn't match the bytes before the fill: something changed them since.++++++ let tag = format!("<< /Index 2 /Op (f) /Before <{}> >>", "00".repeat(32));++++++ let id = s.open("a.pdf", None, Arc::new(backdrop_pdf(Some(&tag))), None).unwrap();++++++ s.apply(id, Edit::RemoveMarks { kind: MarkKind::Background }).unwrap();++++++ let d = s.get(id).unwrap();++++++ assert_eq!(d.edit_notices, [EditNotice::BackdropsLeftOff { pages: vec![0] }]);++++++ let said = d.edit_notices[0].to_string();++++++ assert!(said.starts_with("page 1 changed after the background was added"), "{said}");++++++ // An unrelated edit after it says nothing.++++++ s.apply(id, Edit::RotatePages { pages: vec![0], degrees: 90 }).unwrap();++++++ assert!(s.get(id).unwrap().edit_notices.is_empty());++++++++++++ // Added and removed here: the backdrop comes back, and nothing is said.++++++ let id = s.open("b.pdf", None, Arc::new(backdrop_pdf(None)), None).unwrap();++++++ s.apply(id, Edit::RemoveMarks { kind: MarkKind::Background }).unwrap();++++++ let background = Background { color: [1.0, 0.0, 0.0], ..Background::default() };++++++ s.apply(id, Edit::AddBackground { pages: vec![0], settings: background, replace: false, file: None }).unwrap();++++++ assert_eq!(s.get(id).unwrap().page_backdrops(&[0]), [None], "replaced");++++++ s.apply(id, Edit::RemoveMarks { kind: MarkKind::Background }).unwrap();++++++ assert!(s.get(id).unwrap().edit_notices.is_empty());++++++ assert_eq!(s.get(id).unwrap().page_backdrops(&[0]), [Some(Backdrop::Fill)], "turned back on");++++++ assert_eq!(page_runs(&[0, 1, 2, 5, 7, 8]), "1-3, 6, 8-9");++++++ assert_eq!(page_runs(&[]), "");++++++}+++++++ /// Update previews its marks on the page without the ones it replaces: a yellow background+ /// updated to blue isn't previewed as blue over yellow, nor a new watermark over the old one.+ /// The other kinds of mark and the page's own content stay, every page is prepared at once (the+ /// dialog steps through them), a document without that kind has nothing to prepare, and+ /// preparing changes nothing in the document.+ #[test]+ fn update_previews_on_the_page_without_the_marks_it_replaces() {+ let (mut s, id) = session_with(2);+ let yellow = Background { color: [1.0, 1.0, 0.0], ..Background::default() };+ s.apply(id, Edit::AddBackground { pages: vec![0, 1], settings: yellow, replace: false, file: None }).unwrap();+ let red = Watermark { text: "SECRET".into(), color: [1.0, 0.0, 0.0], opacity: 1.0, ..Watermark::default() };+ s.apply(id, Edit::AddWatermark { pages: vec![0], settings: red, replace: false, file: None }).unwrap();+ let doc = s.get(id).unwrap();+ let (generation, dirty) = (doc.edit_generation(), doc.dirty);+ let px = |p: &pdfcraft_render::RenderedPage, x: u32, y: u32| -> [u8; 3] {+ p.rgba[(((300 - y) * p.width + x) * 4) as usize..][..3].try_into().unwrap()+ };+ let reds = |p: &pdfcraft_render::RenderedPage| p.rgba.as_chunks::<4>().0.iter().filter(|[r, g, b, _]| *r > 200 && *g < 80 && *b < 80).count();+ let dark = |p: &pdfcraft_render::RenderedPage| p.rgba.as_chunks::<4>().0.iter().filter(|[r, g, b, _]| *r < 100 && *g < 100 && *b < 100).count();+ assert_eq!(pixel(&s, id, 0, 5, 5)[..3], [255, 255, 0], "the page has the yellow background");++ let mut unmarked = doc.without_marks(MarkKind::Background).unwrap().expect("the pages have a background");+ let page = unmarked.render_page(0, 1.0).unwrap();+ assert_eq!(px(&page, 5, 5), [255, 255, 255], "without the background the page is white");+ assert!(reds(&page) > 50, "the watermark stays");+ assert!(dark(&page) > 10, "the page text stays");++ let page = doc.without_marks(MarkKind::Watermark).unwrap().expect("page 1 has a watermark").render_page(0, 1.0).unwrap();+ assert_eq!(reds(&page), 0, "without the watermark");+ assert_eq!(px(&page, 5, 5), [255, 255, 0], "the background stays");++ assert_eq!(px(&unmarked.render_page(1, 1.0).unwrap(), 5, 5), [255, 255, 255], "made once, for every page: page 2 is white too");+ assert_eq!(unmarked.parser_builds(), 1, "parsed once for both pages");+ assert!(doc.without_marks(MarkKind::HeaderFooter).unwrap().is_none(), "the document has no header");+ assert!(unmarked.render_page(9, 1.0).is_err(), "no page 10");+ let doc = s.get(id).unwrap();+ assert_eq!((doc.edit_generation(), doc.dirty, doc.can_undo()), (generation, dirty, Some("Add watermark")), "the document is unchanged");+ }+#[test]fn marker_indexes_match_after_open_and_save_when_requested() {let (mut source, source_id) = session_with(1);diff --cc crates/filters/Cargo.tomlindex fd63ac2b0,9d2ae34b9,9d2ae34b9,9d2ae34b9,9d2ae34b9,876a8c281,876a8c281..aa8aaa0c4--- a/crates/filters/Cargo.toml+++ b/crates/filters/Cargo.toml@@@@@@@@ -1,6 -1,6 -1,6 -1,6 -1,6 -1,6 -1,6 +1,6 @@@@@@@@[package]name = "pdfcraft-filters"---- description = "PDF stream filters (ISO 32000-2 §7.4): Flate, LZW, predictors, ASCII85, ASCIIHex, RunLength"--description = "PDF stream filters (ISO 32000-2 §7.4): Flate, LZW, predictors, ASCII85, ASCIIHex, RunLength, CCITT Group 4 encoding"++++++description = "PDF stream filters (ISO 32000-2 §7.4): Flate, LZW, predictors, ASCII85, ASCIIHex, RunLength, CCITT Group 4 encoding and Group 3 and 4 decoding"version.workspace = trueedition.workspace = truelicense.workspace = true@@@@@@@@ -11,9 -11,6 -11,6 -11,6 -11,6 -11,7 -11,7 +11,9 @@@@@@@@ repository.workspace = truworkspace = true[dependencies]++++ fax.workspace = true++++++# CCITT fax decoding (`decode_ccitt`); already in the tree through hayro.++++++hayro-ccitt.workspace = trueflate2.workspace = truethiserror.workspace = truediff --cc crates/filters/README.mdindex b8c1d2281,959180d87,959180d87,959180d87,959180d87,98363e33d,333ee1e59..e52a6cb33--- a/crates/filters/README.md+++ b/crates/filters/README.md@@@@@@@@ -3,7 -3,7 -3,7 -3,7 -3,7 -3,7 -3,7 +3,9 @@@@@@@@PDF stream filters: the decoders and encoders behind `/Filter` and `/DecodeParms`.- **Layer:** L0, standalone. No dependency on any other PdfCraft crate. `cos` depends on it (architecture §3 rule 3).- - **Licence:** MIT OR Apache-2.0. Clean-room: written from ISO 32000-2 §7.4, RFC 1950/1951 (through `flate2` with the pure-Rust `miniz_oxide` backend), TIFF 6.0 §14 (predictor 2) and RFC 2083 §6 (PNG filters). CCITT Group 4 encoding (ITU-T T.6) is the `fax` crate's (MIT, already in the tree through `tiff`), checked here by round trips through an independent decoder; CCITT decoding (T.4 and T.6) is the `hayro-ccitt` crate's (MIT OR Apache-2.0, already in the tree through hayro), bounded here.---- - **Licence:** MIT OR Apache-2.0. Clean-room: written from ISO 32000-2 §7.4, RFC 1950/1951 (through `flate2` with the pure-Rust `miniz_oxide` backend), TIFF 6.0 §14 (predictor 2) and RFC 2083 §6 (PNG filters).- - **Licence:** MIT OR Apache-2.0. Clean-room: written from ISO 32000-2 §7.4, RFC 1950/1951 (through `flate2` with the pure-Rust `miniz_oxide` backend), TIFF 6.0 §14 (predictor 2) and RFC 2083 §6 (PNG filters). CCITT Group 4 encoding (ITU-T T.6) is the `fax` crate's (MIT, already in the tree through `tiff`), checked here by round trips through an independent decoder. JBIG2 generic region encoding is written here from the JBIG committee's ISO/IEC 14492 Final Committee Draft (WG1 N1359, 1999), the public draft of ITU-T T.88; its Annex H.2 test sequence checks the arithmetic coder byte for byte.-- **Licence:** MIT OR Apache-2.0. Clean-room: written from ISO 32000-2 §7.4, RFC 1950/1951 (through `flate2` with the pure-Rust `miniz_oxide` backend), TIFF 6.0 §14 (predictor 2) and RFC 2083 §6 (PNG filters). CCITT Group 4 encoding (ITU-T T.6) is the `fax` crate's (MIT, already in the tree through `tiff`), checked here by round trips through an independent decoder. JBIG2 encoding (generic regions, symbol dictionaries and text regions) is written here from the JBIG committee's ISO/IEC 14492 Final Committee Draft (WG1 N1359, 1999), the public draft of ITU-T T.88; its Annex H.2 test sequence checks the arithmetic coder byte for byte, and its Annex A example the integer coders.+++++++- **Licence:** MIT OR Apache-2.0. Clean-room: written from ISO 32000-2 §7.4, RFC 1950/1951 (through `flate2` with the pure-Rust `miniz_oxide` backend), TIFF 6.0 §14 (predictor 2) and RFC 2083 §6 (PNG filters). CCITT Group 4 encoding (ITU-T T.6) is the `fax` crate's (MIT, already in the tree through `tiff`), checked here by round trips through an independent decoder; CCITT decoding (T.4 and T.6) is the `hayro-ccitt` crate's (MIT OR Apache-2.0, already in the tree through hayro), bounded here. JBIG2 generic region encoding is written from the public ISO/IEC 14492 Final Committee Draft (WG1 N1359, 1999); Annex H.2 checks the arithmetic coder byte for byte.++++++++++++++Lossless symbol coding is also implemented: exact-copy dictionaries/text regions, bounded by the encoder; no approximate or lossy symbol substitution.- `#![forbid(unsafe_code)]`. Builds for `wasm32-unknown-unknown`.## API@@@@@@@@ -22,9 -22,6 -22,6 -22,6 -22,6 -22,8 -22,9 +24,12 @@@@@@@@ decode_tolerant(chain, data, max_outputdecode_tolerant_counted(chain, data, max_output) -> Result<(Vec<u8>, bool /*partial*/, usize /*decoded*/), (FilterError, usize /*decoded*/)>encode(filter, params, data) -> Result<Vec<u8>, FilterError>encode_flate(data) -> Vec<u8> // zlib, level 6++++ encode_g4(data, columns, rows) -> Result<Vec<u8>, FilterError> // 1-bit rows as CCITT Group 4; columns <= MAX_G4_COLUMNS++++++pub struct CcittParams { k, columns, rows, end_of_line, encoded_byte_align, end_of_block, black_is_1 } // Table 11; Default = its defaults++++++decode_ccitt(data, ¶ms, max_rows) -> Result<Vec<u8>, FilterError> // CCITT fax as CCITTFaxDecode gives it; columns <= MAX_CCITT_COLUMNS+++++ +encode_jbig2_generic(data, columns, rows) -> Result<Vec<u8>, FilterError> // 1-bit rows as lossless JBIG2 for JBIG2Decode; columns <= MAX_JBIG2_COLUMNS++++++ encode_jbig2(data, columns, rows) -> Result<Vec<u8>, FilterError> // 1-bit rows as lossless JBIG2 for JBIG2Decode, symbol coded when that is smaller; columns <= MAX_JBIG2_COLUMNS++++++ encode_jbig2_generic(data, columns, rows) -> Result<Vec<u8>, FilterError> // the same as one generic region```- `chain` is applied first to last, as in a `/Filter` array.@@@@@@@@ -43,16 -40,14 -40,14 -40,14 -40,14 -42,19 -43,20 +48,23 @@@@@@@@| ASCIIHexDecode | white space ignored, odd digit padded with 0, `>` EOD (optional), other characters → Corrupt | upper case, newline every 64 digits, `>` || ASCII85Decode | `<~` prefix, `z`, white space, `~>` (or bare `~`, or none) EOD, final partial group; `z` inside a group, a 1-char final group, overflow or bad characters → Corrupt | `z` for zero groups, newline every 75 characters, `~>` || RunLengthDecode | 0–127 literal, 129–255 repeat, 128 EOD (optional); truncated run → Corrupt | runs of ≥2 repeat, literals up to 128, 128 |--| CCITTFaxDecode | not here (`Unsupported`; renderers decode it) | `encode_g4`: Group 4 (`/K -1`) with an end-of-block mark, 0 bits coded black so `/BlackIs1 false` decodes the same bits; rows packed MSB first, each on a new byte, padding bits and trailing bytes ignored; up to 32,767 samples a row (the encoder counts positions in 16 bits); no rows or columns, or too wide → Unsupported, too few bytes → Corrupt |++++++| CCITTFaxDecode | not in a chain (`Unsupported`); `decode_ccitt` decodes Group 3 and Group 4 on its own, as rows of 1-bit samples each on a new byte, black 0 unless `black_is_1`, at most `max_rows` rows (fewer with `/Rows`), the rows before any damage, up to 1,048,576 samples a row; Group 3 rows on bytes are read by their end-of-line codes when the data starts with one and on bytes otherwise, whatever `end_of_line` says, so data with codes but none before the first row (not as T.4 sends them) is read on bytes, as the renderer draws it, and at `k` 0 may come out as other rows (`pdfcraft_cos::Document::decoded_image` calls it for a fax image, after the filters before it) | `encode_g4`: Group 4 (`/K -1`) with an end-of-block mark, 0 bits coded black so `/BlackIs1 false` decodes the same bits; rows packed MSB first, each on a new byte, padding bits and trailing bytes ignored; up to 32,767 samples a row (the encoder counts positions in 16 bits); no rows or columns, or too wide → Unsupported, too few bytes → Corrupt |+++++ +| JBIG2Decode | not here (`Unsupported`; the renderer and image export decode it with `hayro-jbig2`) | `encode_jbig2_generic`: the embedded organisation (D.3) with a page information segment and an immediate lossless generic region (7.4.6), no `/JBIG2Globals`; template 0 with its nominal AT pixels and typical prediction (6.2.5), coded with the MQ arithmetic coder (Annex E, Table E.1) and ended by its 0xFF 0xAC marker. A 0 sample is coded as a JBIG2 1 (black), since `JBIG2Decode` gives black as 0, so the stream decodes to the same bits; rows packed MSB first, each on a new byte, padding bits and trailing bytes ignored; up to 1,048,576 samples a row; no rows or columns, or too wide → Unsupported, too few bytes → Corrupt |++++++ | JBIG2Decode | not here (`Unsupported`; the renderer and image export decode it with `hayro-jbig2`) | `encode_jbig2_generic`: the embedded organisation (D.3) with a page information segment and an immediate lossless generic region (7.4.6), no `/JBIG2Globals`; template 0 with its nominal AT pixels and typical prediction (6.2.5), coded with the MQ arithmetic coder (Annex E, Table E.1) and ended by its 0xFF 0xAC marker. A 0 sample is coded as a JBIG2 1 (black), since `JBIG2Decode` gives black as 0, so the stream decodes to the same bits; rows packed MSB first, each on a new byte, padding bits and trailing bytes ignored; up to 1,048,576 samples a row; no rows or columns, or too wide → Unsupported, too few bytes → Corrupt. `encode_jbig2`: the smaller of that and symbol coding (`jbig2/symbols.rs`): each distinct mark (8-connected black pixels, at most 256 a side) stored once in a symbol dictionary (7.4.2; arithmetic coded, each bitmap a template 0 generic region without typical prediction, the bitmaps sharing their contexts) and placed by immediate lossless text regions referring to it (7.4.3; bottom-left reference corner, strips of 1, 2, 4 or 8 rows, whichever is smallest), each of at most 10,000 instances over a band of rows, as the decoder PdfCraft renders with (`hayro-jbig2`) takes no more in one region, with larger marks, and in a second plan marks that occur once, in a generic region over their box. Only exact copies share a symbol (no refinement), so the stream decodes to the same bits; fewer than two symbols, more than 2^20 black runs, 65,536 distinct marks or 16 MiB of their pixels, or more than 2^24 rows, and the generic coding is used; a plan of more than 32,767 symbols (that decoder refuses more) isn't made |## Tests- Unit tests per filter with hand-computed vectors (the ISO 32000-2 LZW example, RFC 1951 stored blocks, PNG/TIFF rows).- LZW is cross-checked against `weezl` (dev-dependency) in both directions for both early-change settings.- `tests/proptests.rs`: encode→decode round trips for every encodable filter × predictor × colors × bpc × columns, two-filter chains, output-limit checks, and fuzz-style no-panic tests (random bytes, random/nonsense params, bit-flipped valid streams).--- `ccitt.rs`: Group 4 output decoded by `hayro-ccitt` (dev-dependency, an independent decoder) matches the input bits: a text-like page, padding bits, the widest row, and property tests over bitmaps of noise and of runs; any input returns rather than panics.++++++- `ccitt.rs`: `decode_ccitt` gives back the rows `encode_g4` was given (with `/BlackIs1`, `/Rows` and a row limit), refuses bad widths, and bounds its output for any input; byte-aligned Group 3 in each layout, over 32 seeded pictures, decodes to its picture, and a byte short to fewer rows. Group 4 output decoded by `hayro-ccitt` (an independent decoder) matches the input bits: a text-like page, padding bits, the widest row, and property tests over bitmaps of noise and of runs; any input returns rather than panics.+++++ - `mq.rs`: the arithmetic coder reproduces Annex H.2's 30 bytes from its 256 decisions.+++++ - `jbig2.rs`: output decoded by `hayro-jbig2` (dev-dependency, an independent decoder) matches the input bits: a text-like page (smaller than Group 4), edges, padding, all-white and all-black regions (typical rows), and property tests over bitmaps of noise and of runs; any input returns rather than panics.++++++ - `jbig2/symbols.rs`: the integer coders against Annex A's example and Table A.1; symbol-coded output decoded by `hayro-jbig2` matches the input bits for every plan and strip size: text whose letters repeat (under half the generic coding's size, the dictionary retained and referred to), large and lone marks left to a generic region, marks on the edges, touching at corners and inside each other's boxes, and property tests over glyphs scattered over each other and the edges with stray pixels (never larger than the generic coding); one shape, a blank page and noise are coded generically; marks joined at a corner, either way, are one mark, and 256 pixels a side is a symbol while 257 wide or tall is left out; black padding bits are ignored; coordinates past 4,435 use Annex A's 32-bit range and PREV stays below 512; past 2^20 runs, 2^24 rows, 65,536 distinct marks or 2^24 symbol pixels the image is coded generically, and at each cap it is still looked at; a plan codes at most 32,767 symbols, which decode, and past that the second plan still codes the repeated ones; more than 10,000 marks are placed by several text regions, numbered in turn, the dictionary retained for each but the last; any input returns rather than panics.- `fuzz/`: a detached cargo-fuzz crate (`cargo +nightly fuzz run decode`, run from `crates/filters/`).## Status---- M1.1/M1.2 for the general-purpose filters are done. Not yet here: the image codecs (DCT via zune-jpeg, JPX via hayro-jpeg2000, JBIG2, CCITT G3/G4 decode and G4 encode, DCT encode) and Flate encode levels other than 6.- M1.1/M1.2 for the general-purpose filters are done. Not yet here: the image codecs (DCT via zune-jpeg, JPX via hayro-jpeg2000, JBIG2 and CCITT decode, DCT encode), CCITT Group 3 encoding, JBIG2 symbol coding (text regions, symbol dictionaries, lossy) and Flate encode levels other than 6.-M1.1/M1.2 for the general-purpose filters are done. Not yet here: the image codecs (DCT via zune-jpeg, JPX via hayro-jpeg2000, JBIG2 and CCITT decode, DCT encode), CCITT Group 3 encoding, JBIG2 refinement coding (near-copies of a symbol), symbol dictionaries shared between images (`/JBIG2Globals`) and lossy JBIG2, and Flate encode levels other than 6.++++++M1.1/M1.2 for the general-purpose filters are done. Not yet here: the image codecs (DCT via zune-jpeg, JPX via hayro-jpeg2000, JBIG2, DCT encode), CCITT Group 3 encoding and Flate encode levels other than 6.++++++++++++++Lossless symbol coding is also implemented: exact-copy dictionaries/text regions, bounded by the encoder; no approximate or lossy symbol substitution.diff --cc crates/filters/src/lib.rsindex 63daefc4e,22a78aefd,22a78aefd,22a78aefd,22a78aefd,da675a024,30094e652..7eac1a83e--- a/crates/filters/src/lib.rs+++ b/crates/filters/src/lib.rs@@@@@@@@ -6,8 -6,7 -6,7 -6,7 -6,7 -6,8 -6,8 +6,8 @@@@@@@@//! TIFF/PNG predictors, `ASCIIHexDecode`, `ASCII85Decode`, `RunLengthDecode`).//! Image codecs (`DCTDecode`, `JPXDecode`, `JBIG2Decode`, `CCITTFaxDecode`),//! `Crypt` and unknown filters are reported as [`FilterError::Unsupported`] so---- //! callers keep such data encoded.++++ //! callers keep such data encoded. 1-bit samples can be encoded as CCITT Group 4- - //! ([`encode_g4`]).++++++ //! ([`encode_g4`]) or lossless JBIG2 ([`encode_jbig2`]).//!//! Every decoder is bounded by a caller-supplied `max_output` (decompression-bomb//! defence) and never panics on malformed input.@@@@@@@@ -16,16 -15,13 -15,13 -15,13 -15,13 -16,19 -16,19 +16,19 @@@@@@@@mod ascii85;mod asciihex;++++ mod ccitt;mod flate;+++++ mod jbig2;mod lzw;+++++ mod mq;mod predictor;mod runlength;use std::borrow::Cow;--pub use ccitt::{MAX_G4_COLUMNS, encode_g4};- pub use jbig2::{MAX_JBIG2_COLUMNS, encode_jbig2_generic};++++++pub use ccitt::{CcittParams, MAX_CCITT_COLUMNS, MAX_G4_COLUMNS, decode_ccitt, encode_g4};++++++ pub use jbig2::{MAX_JBIG2_COLUMNS, encode_jbig2, encode_jbig2_generic};++++/// A PDF stream filter, identified by its `/Filter` name.#[derive(Clone, Debug, PartialEq, Eq, Hash)]pub enum Filter {diff --cc crates/forms/src/author/edit.rsindex 54a05f3db,4f1a1a863,66cc53e7c,d61cfe28f,54a05f3db,54a05f3db,54a05f3db..2d05600ae--- a/crates/forms/src/author/edit.rs+++ b/crates/forms/src/author/edit.rs@@@@@@@@ -15,68 -15,68 -15,97 -14,6 -15,68 -15,68 -15,68 +15,97 @@@@@@@@ fn swapped_around_center(r: [f64; 4]) -(out.iter().all(|v| v.is_finite()) && out[2] - out[0] >= MIN_FIELD_SIDE && out[3] - out[1] >= MIN_FIELD_SIDE).then_some(out)}+ /// Re-point a choice field's `/I`, positions in `/Opt`, at the new list `exports` after `/Opt` was+ /// replaced (ISO 32000-2 §12.7.5.4): the positions of the selected `values` still offered. `kept`+ /// are the old `/I` positions carried into the new list, which tell apart options sharing an+ /// export value; a selected value none of them covers takes its first position, by `set_value`'s+ /// rule. Returns them.+ fn repoint_selection(d: &mut Dict, values: &[String], exports: &[String], kept: &[usize]) -> Vec<usize> {+ let mut indices: Vec<usize> = kept.iter().copied().filter(|&i| exports.get(i).is_some_and(|e| values.contains(e))).collect();+ for v in values {+ if !indices.iter().any(|&i| exports.get(i) == Some(v)) {+ indices.extend(exports.iter().position(|e| e == v));+ }+ }+ indices.sort_unstable();+ indices.dedup();+ if indices.is_empty() {+ d.remove(b"I");+ } else {+ d.set(b"I".to_vec(), Object::Array(indices.iter().map(|&i| Object::Int(i64::try_from(i).unwrap_or(i64::MAX))).collect()));+ }+ indices+ }++ /// The positions in `/Opt` that a choice field's `/I` holds, those below `count`.+ fn selected_indices(doc: &Document, field: ObjRef, count: usize) -> Vec<usize> {+ let Some(i) = doc.get(field).as_dict().and_then(|d| d.get(b"I").cloned()) else {+ return Vec::new();+ };+ let positions = doc.resolve(&i);+ positions.as_array().map(|a| a.iter().filter_map(|o| usize::try_from(o.as_int()?).ok()).filter(|&n| n < count).collect()).unwrap_or_default()+ }++ /// The items (export value, display text) "Sort items" orders: the new `props.options`, or else+ /// the field's own, whose selection, `/I` included, moves with them.+ fn items_to_sort(doc: &Document, f: &Field, props: &FieldProps) -> (Vec<(String, String)>, Vec<usize>) {+ match &props.options {+ Some(o) => (o.iter().map(|x| (x.clone(), x.clone())).collect(), Vec::new()),+ None => (f.options.clone(), selected_indices(doc, f.obj, f.options.len())),+ }+ }++ /// Sort a choice field's items (export value, display text) by display text, ignoring case, and+ /// write them as `/Opt`; export values stay with their items. Returns the export values in their+ /// new order and the `old` positions carried through the sort.+ fn write_sorted_opt(d: &mut Dict, items: &[(String, String)], old: &[usize]) -> (Vec<String>, Vec<usize>) {+ let mut order: Vec<usize> = (0..items.len()).collect();+ order.sort_by_key(|&i| items.get(i).map(|(_, display)| display.to_lowercase()));+ let sorted: Vec<&(String, String)> = order.iter().filter_map(|&i| items.get(i)).collect();+ let opt = sorted+ .iter()+ .map(|(e, disp)| {+ if e == disp {+ Object::String(PdfString::text(disp))+ } else {+ Object::Array(vec![Object::String(PdfString::text(e)), Object::String(PdfString::text(disp))])+ }+ })+ .collect();+ d.set(b"Opt".to_vec(), Object::Array(opt));+ let carried = old.iter().filter_map(|o| order.iter().position(|i| i == o)).collect();+ (sorted.into_iter().map(|(e, _)| e.clone()).collect(), carried)+ }+++ ++++/// Build /Opt before modifying the document, preserving appearance states and selection.++ ++++fn button_export_options(f: &Field, index: usize, value: &str) -> Result<Vec<Object>, FormError> {++ ++++ if !matches!(f.kind, FieldKind::CheckBox | FieldKind::Radio) {++ ++++ return invalid("only check boxes and radio buttons have an export value");++ ++++ }++ ++++ if value.is_empty() || value == "Off" || value.len() > 4096 {++ ++++ return invalid("export value must be non-empty, at most 4096 bytes, and not Off");++ ++++ }++ ++++ let widget = f.widgets.get(index).ok_or_else(|| FormError::Invalid("button widget index is out of range".into()))?;++ ++++ let state = widget.on_state.as_deref().ok_or_else(|| FormError::Invalid("button has no on appearance state".into()))?;++ ++++ if !f.options.is_empty() && f.options.len() != f.widgets.len() {++ ++++ return invalid("button export options do not match its widgets");++ ++++ }++ ++++ let previous = f.export_of(index);++ ++++ let mut out = Vec::with_capacity(f.widgets.len());++ ++++ for (i, w) in f.widgets.iter().enumerate() {++ ++++ let export = f.export_of(i).ok_or_else(|| FormError::Invalid("button has no on appearance state".into()))?;++ ++++ let same_state = w.on_state.as_deref() == Some(state);++ ++++ if !same_state && (export == value || w.on_state.as_deref() == Some(value)) {++ ++++ return invalid("export value conflicts with another button choice");++ ++++ }++ ++++ if same_state && Some(export) != previous {++ ++++ return invalid("widgets with the same appearance state have conflicting export values");++ ++++ }++ ++++ out.push(Object::String(PdfString::text(if same_state { value } else { export })));++ ++++ }++ ++++ Ok(out)++ ++++}++ ++++/// Change a field's properties (General and Options tabs) and redraw it.pub fn set_props(doc: &mut Document, name: &str, props: &FieldProps) -> Result<String, FormError> {if props.font_size.is_some_and(|size| !size.is_finite() || size < 0.0) {@@@@@@@@ -88,8 -88,14 -117,12 -25,8 -88,8 -88,8 -88,8 +117,18 @@@@@@@@}patch.validate()?;}+ +++++ // Refused here, before anything is written, rather than stored as a different formula.+ +++++ if let Some(crate::af::Calculate::Notation(n)) = &props.calculate+ +++++ && !crate::af::notation_storable(n)+ +++++ {+ +++++ return invalid(crate::af::NOTATION_NOT_STORABLE);+ +++++ }let all = fields(doc);let f = all.iter().find(|f| f.name == name).ok_or_else(|| FormError::NoSuchField(name.into()))?.clone();++ ++++ let export_options = props.export_value.as_ref().map(|(index, value)| button_export_options(&f, *index, value)).transpose()?;++ ++++ if props.export_value.is_some() && props.options.is_some() {++ ++++ return invalid("give export_value or options, not both");++ ++++ }// Refuse a wrong type/index before any other requested property is written.if let Some((wi, _)) = &props.caption {if f.kind != FieldKind::PushButton {@@@@@@@@ -206,12 -212,12 -245,15 -138,8 -206,12 -206,12 -206,12 +251,15 @@@@@@@@}}}+ // The export values in `/Opt` order once it is rewritten, for re-pointing `/I`.+ let mut new_exports: Option<Vec<String>> = None;+ let mut kept = Vec::new();++ ++++ if let Some(options) = &export_options {++ ++++ d.set(b"Opt".to_vec(), Object::Array(options.clone()));++ ++++ }if let Some(opts) = &props.options {d.set(b"Opt".to_vec(), Object::Array(opts.iter().map(|o| Object::String(PdfString::text(o))).collect()));+ new_exports = Some(opts.clone());}// "Sort items": the list itself is kept in order (export values stay with their items).if ff & flags::SORT != 0 && matches!(f.kind, FieldKind::Combo | FieldKind::List) {diff --cc crates/forms/src/tests.rsindex ac414af2a,95afee7c9,5d05659cf,d8199f15d,ac414af2a,ac414af2a,ac414af2a..cca4cb488--- a/crates/forms/src/tests.rs+++ b/crates/forms/src/tests.rs@@@@@@@@ -4693,666 -4766,666 -4693,722 -4620,3 -4693,666 -4693,666 -4693,666 +4766,722 @@@@@@@@ fn set_values_reads_the_form_once_not_plet reads = form_reads() - before;assert_eq!(reads, 3, "one to fill, one when f0 comes again, one to recalculate");}++ /// A radio group `size` with the buttons Small (on), Medium and Large, a per-widget `/Opt`, and+ /// the group's buttons in the calculation order; and a text field `name` with two widgets.+ fn radio_group_form() -> Document {+ let objs: Vec<String> = vec![+ "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(), // 1+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(), // 2+ "<< /Type /Page /Parent 2 0 R /Annots [6 0 R 7 0 R 8 0 R 10 0 R 11 0 R] >>".into(), // 3+ "<< /Fields [5 0 R 9 0 R] /DA (/Helv 0 Tf 0 g) /CO [7 0 R] >>".into(), // 4+ "<< /FT /Btn /Ff 49152 /T (size) /V /S /Opt [(small) (medium) (large)] /Kids [6 0 R 7 0 R 8 0 R] >>".into(), // 5+ "<< /Type /Annot /Subtype /Widget /Parent 5 0 R /Rect [50 700 64 714] /P 3 0 R /AS /S /AP << /N << /S 12 0 R /Off 12 0 R >> >> >>".into(), // 6+ "<< /Type /Annot /Subtype /Widget /Parent 5 0 R /Rect [80 700 94 714] /P 3 0 R /AS /Off /AP << /N << /M 12 0 R /Off 12 0 R >> >> >>".into(), // 7+ "<< /Type /Annot /Subtype /Widget /Parent 5 0 R /Rect [110 700 124 714] /P 3 0 R /AS /Off /AP << /N << /L 12 0 R /Off 12 0 R >> >> >>".into(), // 8+ "<< /FT /Tx /T (name) /V (Ann) /Kids [10 0 R 11 0 R] >>".into(), // 9+ "<< /Type /Annot /Subtype /Widget /Parent 9 0 R /Rect [50 600 250 620] /P 3 0 R >>".into(), // 10+ "<< /Type /Annot /Subtype /Widget /Parent 9 0 R /Rect [300 600 500 620] /P 3 0 R >>".into(), // 11+ "<< /Length 0 >>\nstream\n\nendstream".into(), // 12+ ];+ document(&objs)+ }++ fn annots(doc: &Document) -> Vec<u32> {+ let p = page_refs(doc)[0];+ let a = doc.resolve(doc.get(p).as_dict().unwrap().get(b"Annots").unwrap());+ a.as_array().unwrap().iter().map(|o| o.as_ref().unwrap().num).collect()+ }++ #[test]+ fn deleting_one_radio_button_keeps_the_group_and_its_other_buttons() {+ let mut doc = radio_group_form();+ delete_widget(&mut doc, "size", 1).unwrap();+ let doc = reopen(&doc);+ let all = fields(&doc);+ let size = field(&all, "size");+ assert_eq!(size.widgets.iter().map(|w| w.obj.num).collect::<Vec<_>>(), [6, 8], "only Medium is gone");+ assert_eq!(size.value, ["S"], "the group keeps its choice");+ // The per-widget /Opt loses Medium's entry, so the others keep their export values.+ assert_eq!((size.export_of(0), size.export_of(1)), (Some("small"), Some("large")));+ assert_eq!(annots(&doc), [6, 8, 10, 11], "the button left the page");+ let co = doc.resolve(doc.get(ObjRef::new(4, 0)).as_dict().unwrap().get(b"CO").unwrap()).as_array().cloned().unwrap();+ assert!(co.is_empty(), "and the calculation order");+ assert!(field(&all, "name").widgets.len() == 2, "other fields are untouched");+ }++ #[test]+ fn deleting_the_chosen_radio_button_turns_the_group_off() {+ let mut doc = radio_group_form();+ delete_widget(&mut doc, "size", 0).unwrap();+ let all = fields(&reopen(&doc));+ let size = field(&all, "size");+ assert_eq!(size.widgets.iter().map(|w| w.obj.num).collect::<Vec<_>>(), [7, 8]);+ assert!(size.value.is_empty(), "no button is on any more: {:?}", size.value);+ assert_eq!((size.export_of(0), size.export_of(1)), (Some("medium"), Some("large")));+ }++ #[test]+ fn deleting_the_chosen_radio_button_turns_the_group_off_when_a_twin_is_not_shown_on() {+ // Medium shares Small's on-state name but shows Off: once Small is gone, no button shows+ // the group's /V, so the group must not keep reporting it.+ let mut doc = radio_group_form();+ let twin = ObjRef::new(7, 0);+ let blank = Object::Ref(ObjRef::new(12, 0));+ let mut n = Dict::new();+ n.set(b"S".to_vec(), blank.clone());+ n.set(b"Off".to_vec(), blank);+ let mut ap = Dict::new();+ ap.set(b"N".to_vec(), Object::Dict(n));+ let mut w = doc.get(twin).as_dict().cloned().unwrap();+ w.set(b"AP".to_vec(), Object::Dict(ap));+ doc.set(twin, Object::Dict(w));+ delete_widget(&mut doc, "size", 0).unwrap();+ let all = fields(&reopen(&doc));+ let size = field(&all, "size");+ assert_eq!(size.widgets.iter().map(|w| w.obj.num).collect::<Vec<_>>(), [7, 8]);+ assert!(size.value.is_empty(), "no button shows S any more: {:?}", size.value);+ }++ #[test]+ fn deleting_the_default_radio_button_clears_the_default_too() {+ // The group is off, but Reset would put back Small, which no button has once it is gone.+ let mut doc = radio_group_form();+ let size = ObjRef::new(5, 0);+ let mut d = doc.get(size).as_dict().cloned().unwrap();+ d.set(b"V".to_vec(), Object::name("Off"));+ d.set(b"DV".to_vec(), Object::name("S"));+ doc.set(size, Object::Dict(d));+ delete_widget(&mut doc, "size", 0).unwrap();+ let doc = reopen(&doc);+ let dv = doc.get(size).as_dict().and_then(|d| d.get(b"DV").cloned());+ assert_eq!(dv, Some(Object::name("Off")));+ // A default another button still has stays.+ let mut doc = radio_group_form();+ let mut d = doc.get(size).as_dict().cloned().unwrap();+ d.set(b"DV".to_vec(), Object::name("S"));+ doc.set(size, Object::Dict(d));+ delete_widget(&mut doc, "size", 1).unwrap();+ assert_eq!(doc.get(size).as_dict().and_then(|d| d.get(b"DV").cloned()), Some(Object::name("S")));+ }++ #[test]+ fn deleting_one_copy_of_a_field_keeps_the_field_and_its_value() {+ let mut doc = radio_group_form();+ delete_widget(&mut doc, "name", 0).unwrap();+ let doc = reopen(&doc);+ let all = fields(&doc);+ let name = field(&all, "name");+ assert_eq!((name.widgets.iter().map(|w| w.obj.num).collect::<Vec<_>>(), name.value.clone()), (vec![11], vec!["Ann".to_string()]));+ assert_eq!(annots(&doc), [6, 7, 8, 11]);+ // The last widget takes the field with it, as deleting the field does.+ let mut doc = doc;+ delete_widget(&mut doc, "name", 0).unwrap();+ let doc = reopen(&doc);+ assert!(!fields(&doc).iter().any(|f| f.name == "name"));+ assert_eq!(annots(&doc), [6, 7, 8]);+ }++ #[test]+ fn deleting_a_radio_button_without_its_parent_link_takes_it_out_of_the_group() {+ // A damaged file: the group lists Medium in its /Kids, but Medium has no /Parent.+ for parent in [None, Some(Object::Ref(ObjRef::new(9, 0)))] {+ let mut doc = radio_group_form();+ let medium = ObjRef::new(7, 0);+ let mut w = doc.get(medium).as_dict().cloned().unwrap();+ w.remove(b"Parent");+ if let Some(p) = parent.clone() {+ w.set(b"Parent".to_vec(), p);+ }+ doc.set(medium, Object::Dict(w));+ delete_widget(&mut doc, "size", 1).unwrap();+ let doc = reopen(&doc);+ let all = fields(&doc);+ assert_eq!(field(&all, "size").widgets.iter().map(|w| w.obj.num).collect::<Vec<_>>(), [6, 8], "/Parent {parent:?}");+ let kids = doc.resolve(doc.get(ObjRef::new(5, 0)).as_dict().unwrap().get(b"Kids").unwrap()).as_array().cloned().unwrap();+ assert!(!kids.iter().any(|k| k.as_ref() == Some(medium)), "/Parent {parent:?}: {kids:?}");+ assert_eq!(field(&all, "name").widgets.len(), 2, "/Parent {parent:?}: the other field is untouched");+ assert_eq!(annots(&doc), [6, 8, 10, 11]);+ }+ }++ #[test]+ fn deleting_a_widget_that_is_not_there_changes_nothing() {+ let mut doc = radio_group_form();+ assert_eq!(delete_widget(&mut doc, "size", 3), Err(FormError::Invalid("size has no widget 4".into())));+ assert_eq!(delete_widget(&mut doc, "nope", 0), Err(FormError::NoSuchField("nope".into())));+ assert_eq!(delete_widget(&mut doc, "size", usize::MAX), Err(FormError::Invalid(format!("size has no widget {}", usize::MAX))));+ assert_eq!(field(&fields(&doc), "size").widgets.len(), 3);+ }+ /// Two new radio groups on one page, "Group1" (export `a`) and "Group2" (export `b`).+ fn two_radio_groups(a: &str, b: &str) -> Document {+ let mut doc = one_page();+ let radio = |export: &str| NewField::Radio { group: None, export: export.into() };+ assert_eq!(add_field(&mut doc, 0, [50.0, 600.0, 64.0, 614.0], &radio(a), None).unwrap(), "Group1");+ assert_eq!(add_field(&mut doc, 0, [80.0, 600.0, 94.0, 614.0], &radio(b), None).unwrap(), "Group2");+ doc+ }++ fn rename_to(doc: &mut Document, from: &str, to: &str) -> Result<String, FormError> {+ set_props(doc, from, &FieldProps { name: Some(to.into()), ..FieldProps::default() })+ }++ fn page_widgets(doc: &Document) -> Vec<ObjRef> {+ let page = page_refs(doc)[0];+ let annots = doc.get(page).as_dict().unwrap().get(b"Annots").cloned().unwrap();+ doc.resolve(&annots).as_array().unwrap().iter().filter_map(|o| o.as_ref()).collect()+ }++ /// #4949: a radio button given its group's name is one of the group's buttons, so the group can+ /// be built up by naming buttons alike, as in Acrobat.+ #[test]+ fn a_radio_button_renamed_to_a_groups_name_joins_the_group() {+ let mut doc = two_radio_groups("Yes", "No");+ set_value(&mut doc, "Group1", &FieldValue::Radio(Some("Yes".into()))).unwrap();+ let before = page_widgets(&doc);+ assert_eq!(rename_to(&mut doc, "Group2", "Group1").unwrap(), "Group1");+ assert_eq!(page_widgets(&doc), before, "the buttons stay on the page where they were");+ let mut doc = reopen(&doc);+ let all = fields(&doc);+ assert_eq!(all.iter().map(|f| f.name.as_str()).collect::<Vec<_>>(), ["Group1"]);+ let group = field(&all, "Group1");+ assert_eq!(group.widgets.iter().filter_map(|w| w.on_state.clone()).collect::<Vec<_>>(), ["Yes", "No"]);+ assert_eq!(group.value, ["Yes"], "the group keeps its value");+ assert_eq!(group.widgets.iter().map(|w| w.state.clone()).collect::<Vec<_>>(), [Some("Yes".into()), Some("Off".into())]);+ assert_eq!(page_widgets(&doc), group.widgets.iter().map(|w| w.obj).collect::<Vec<_>>());+ // Choosing the moved button turns the other off: they are one group.+ set_value(&mut doc, "Group1", &FieldValue::Radio(Some("No".into()))).unwrap();+ let group = field(&fields(&doc), "Group1").clone();+ assert_eq!(group.widgets.iter().map(|w| w.state.clone()).collect::<Vec<_>>(), [Some("Off".into()), Some("No".into())]);+ }++ /// Joining redraws only the buttons that moved: the group's own keep their appearances, which may+ /// be custom ones a redraw would replace.+ #[test]+ fn joining_a_group_leaves_its_own_buttons_appearances_as_they_are() {+ let mut doc = two_radio_groups("Yes", "No");+ let own = field(&fields(&doc), "Group1").widgets[0].obj;+ let look = |doc: &Document| doc.get(own).as_dict().and_then(|d| d.get(b"AP").cloned());+ let before = look(&doc);+ assert!(before.is_some());+ rename_to(&mut doc, "Group2", "Group1").unwrap();+ assert_eq!(look(&doc), before);+ let group = field(&fields(&doc), "Group1").clone();+ assert!(group.widgets[1].on_state.as_deref() == Some("No"), "the moved button is drawn with its states");+ }++ /// A joining button whose export value a button of the group already has takes the next free+ /// "ChoiceN", in its appearance states too, so the two can be chosen apart.+ #[test]+ fn a_joining_radio_button_with_a_taken_export_value_takes_a_free_one() {+ let mut doc = two_radio_groups("Choice1", "Choice1");+ rename_to(&mut doc, "Group2", "Group1").unwrap();+ let doc = reopen(&doc);+ let all = fields(&doc);+ let group = field(&all, "Group1");+ assert_eq!(group.widgets.iter().filter_map(|w| w.on_state.clone()).collect::<Vec<_>>(), ["Choice1", "Choice2"]);+ let moved = doc.get(group.widgets[1].obj).as_dict().unwrap().clone();+ let normal = doc.resolve(moved.get(b"AP").unwrap()).as_dict().unwrap().get(b"N").cloned().unwrap();+ let normal = doc.resolve(&normal).as_dict().unwrap().clone();+ assert!(normal.contains(b"Choice2") && !normal.contains(b"Choice1"));+ }++ /// A group whose `/Kids` is an indirect array keeps its own buttons when another joins it.+ #[test]+ fn a_group_with_indirect_kids_keeps_its_buttons_when_joined() {+ let mut doc = two_radio_groups("Yes", "No");+ let group = field(&fields(&doc), "Group1").obj;+ let kids = doc.get(group).as_dict().unwrap().get(b"Kids").cloned().unwrap();+ let held = doc.add(kids);+ doc.update_dict(group, |d| d.set(b"Kids".to_vec(), Object::Ref(held))).unwrap();+ rename_to(&mut doc, "Group2", "Group1").unwrap();+ let doc = reopen(&doc);+ let all = fields(&doc);+ assert_eq!(field(&all, "Group1").widgets.iter().filter_map(|w| w.on_state.clone()).collect::<Vec<_>>(), ["Yes", "No"]);+ }++ /// Buttons of the joining group that share an export value (a button repeated on another page,+ /// on together) still share it after the join, under one fresh name.+ #[test]+ fn joining_radio_buttons_that_share_a_value_keep_sharing_it() {+ let mut doc = two_radio_groups("Choice1", "Choice1");+ let pages = doc.get(doc.root().unwrap()).as_dict().unwrap().reference(b"Pages").unwrap();+ let mut p = pdfcraft_cos::Dict::new();+ p.set(b"Type".to_vec(), Object::name("Page"));+ p.set(b"Parent".to_vec(), Object::Ref(pages));+ p.set(b"MediaBox".to_vec(), Object::Array(vec![0.into(), 0.into(), 600.into(), 800.into()]));+ let r = doc.add(Object::Dict(p));+ doc.update_dict(pages, |d| {+ let mut kids = d.get(b"Kids").unwrap().as_array().unwrap().clone();+ kids.push(Object::Ref(r));+ d.set(b"Count".to_vec(), Object::Int(kids.len() as i64));+ d.set(b"Kids".to_vec(), Object::Array(kids));+ })+ .unwrap();+ assert_eq!(duplicate_field(&mut doc, "Group2", &[1]).unwrap(), 1);+ rename_to(&mut doc, "Group2", "Group1").unwrap();+ let doc = reopen(&doc);+ let all = fields(&doc);+ let group = field(&all, "Group1");+ assert_eq!(group.widgets.iter().filter_map(|w| w.on_state.clone()).collect::<Vec<_>>(), ["Choice1", "Choice2", "Choice2"]);+ }++ /// One page holding radio fields that are each their own only widget, as other writers make+ /// one-button groups: `(name, export value, x)`.+ fn merged_radios(specs: &[(&str, &str, f64)]) -> Document {+ let mut doc = one_page();+ let page = page_refs(&doc)[0];+ let af = crate::author::ensure_form(&mut doc).unwrap();+ let mut made = Vec::new();+ for &(name, state, x) in specs {+ let look = doc.add(Object::Stream(pdfcraft_cos::Stream::from_raw(pdfcraft_cos::Dict::new(), b"0 g".to_vec())));+ let mut n = pdfcraft_cos::Dict::new();+ n.set(state.as_bytes().to_vec(), Object::Ref(look));+ n.set(b"Off".to_vec(), Object::Ref(look));+ let mut ap = pdfcraft_cos::Dict::new();+ ap.set(b"N".to_vec(), Object::Dict(n));+ let mut d = pdfcraft_cos::Dict::new();+ d.set(b"Type".to_vec(), Object::name("Annot"));+ d.set(b"Subtype".to_vec(), Object::name("Widget"));+ d.set(b"FT".to_vec(), Object::name("Btn"));+ d.set(b"Ff".to_vec(), Object::Int(i64::from(flags::RADIO)));+ d.set(b"T".to_vec(), pdfcraft_cos::PdfString::text(name));+ d.set(b"Rect".to_vec(), Object::Array(vec![x.into(), 600.into(), (x + 14.0).into(), 614.into()]));+ d.set(b"P".to_vec(), Object::Ref(page));+ d.set(b"AP".to_vec(), Object::Dict(ap));+ d.set(b"AS".to_vec(), Object::name("Off"));+ let r = doc.add(Object::Dict(d));+ doc.update_dict(af, |a| {+ let mut list = a.get(b"Fields").and_then(|l| l.as_array().cloned()).unwrap_or_default();+ list.push(Object::Ref(r));+ a.set(b"Fields".to_vec(), Object::Array(list));+ })+ .unwrap();+ made.push(r);+ }+ doc.update_dict(page, |p| p.set(b"Annots".to_vec(), Object::Array(made.iter().map(|r| Object::Ref(*r)).collect()))).unwrap();+ doc+ }++ /// A radio field that is its own (only) widget, as other writers make one-button groups, can+ /// both join a group and be joined.+ #[test]+ fn radio_fields_that_are_their_own_widget_join_and_are_joined() {+ let mut doc = merged_radios(&[("solo", "A", 50.0), ("other", "B", 80.0)]);+ assert_eq!(rename_to(&mut doc, "other", "solo").unwrap(), "solo");+ let doc = reopen(&doc);+ let all = fields(&doc);+ assert_eq!(all.iter().map(|f| f.name.as_str()).collect::<Vec<_>>(), ["solo"]);+ let group = field(&all, "solo");+ assert_eq!(group.widgets.iter().filter_map(|w| w.on_state.clone()).collect::<Vec<_>>(), ["A", "B"]);+ // The joined field's widget became a kid; the moved one shed its field entries.+ let kids: Vec<ObjRef> = group.widgets.iter().map(|w| w.obj).collect();+ assert!(!kids.contains(&group.obj));+ let moved = doc.get(group.widgets[1].obj).as_dict().unwrap().clone();+ assert!(!moved.contains(b"T") && !moved.contains(b"FT") && moved.reference(b"Parent") == Some(group.obj));+ let mut on_page = page_widgets(&doc);+ on_page.sort();+ let mut kids = kids;+ kids.sort();+ assert_eq!(on_page, kids, "the page lists the widgets, not the field");+ }++ /// A group that is its own only widget keeps its button's actions when another button joins+ /// it: the new widget takes `/A` and the widget triggers of `/AA`, and the field keeps its own.+ #[test]+ fn a_joined_merged_groups_button_keeps_its_actions() {+ let mut doc = merged_radios(&[("solo", "A", 50.0), ("other", "B", 80.0)]);+ let solo = field(&fields(&doc), "solo").obj;+ let js = |code: &str| {+ let mut a = pdfcraft_cos::Dict::new();+ a.set(b"S".to_vec(), Object::name("JavaScript"));+ a.set(b"JS".to_vec(), pdfcraft_cos::PdfString::text(code));+ Object::Dict(a)+ };+ let mut aa = pdfcraft_cos::Dict::new();+ aa.set(b"Fo".to_vec(), js("focus();"));+ aa.set(b"V".to_vec(), js("validate();"));+ let aa = doc.add(Object::Dict(aa));+ doc.update_dict(solo, |d| {+ d.set(b"A".to_vec(), js("up();"));+ d.set(b"AA".to_vec(), Object::Ref(aa));+ })+ .unwrap();+ rename_to(&mut doc, "other", "solo").unwrap();+ let doc = reopen(&doc);+ assert_eq!(+ field_actions(&doc, "solo").unwrap(),+ [(Trigger::MouseUp, FieldAction::JavaScript("up();".into())), (Trigger::OnFocus, FieldAction::JavaScript("focus();".into()))]+ );+ let group = field(&fields(&doc), "solo").clone();+ let fd = doc.get(group.obj).as_dict().unwrap().clone();+ let field_aa = doc.resolve(fd.get(b"AA").unwrap()).as_dict().unwrap().clone();+ assert!(!fd.contains(b"A") && field_aa.contains(b"V") && !field_aa.contains(b"Fo"), "the field keeps only its own trigger");+ let wd = doc.get(group.widgets[0].obj).as_dict().unwrap().clone();+ let widget_aa = doc.resolve(wd.get(b"AA").unwrap()).as_dict().unwrap().clone();+ assert!(widget_aa.contains(b"Fo") && !widget_aa.contains(b"V"));+ }++ /// A joining button that was its own field keeps its widget triggers and drops the field's.+ #[test]+ fn a_joining_merged_button_sheds_its_fields_triggers() {+ let mut doc = merged_radios(&[("solo", "A", 50.0), ("other", "B", 80.0)]);+ let other = field(&fields(&doc), "other").obj;+ let js = |code: &str| {+ let mut a = pdfcraft_cos::Dict::new();+ a.set(b"S".to_vec(), Object::name("JavaScript"));+ a.set(b"JS".to_vec(), pdfcraft_cos::PdfString::text(code));+ Object::Dict(a)+ };+ let mut aa = pdfcraft_cos::Dict::new();+ aa.set(b"U".to_vec(), js("up();"));+ aa.set(b"V".to_vec(), js("validate();"));+ aa.set(b"C".to_vec(), js("calc();"));+ let aa = doc.add(Object::Dict(aa));+ doc.update_dict(other, |d| d.set(b"AA".to_vec(), Object::Ref(aa))).unwrap();+ rename_to(&mut doc, "other", "solo").unwrap();+ let doc = reopen(&doc);+ let group = field(&fields(&doc), "solo").clone();+ let moved = group.widgets.iter().find(|w| w.on_state.as_deref() == Some("B")).unwrap();+ let wd = doc.get(moved.obj).as_dict().unwrap().clone();+ let widget_aa = doc.resolve(wd.get(b"AA").unwrap()).as_dict().unwrap().clone();+ assert!(widget_aa.contains(b"U") && !widget_aa.contains(b"V") && !widget_aa.contains(b"C"), "only the widget's trigger stays");+ let mut once = merged_radios(&[("solo", "A", 50.0), ("other", "B", 80.0)]);+ let other = field(&fields(&once), "other").obj;+ let mut aa = pdfcraft_cos::Dict::new();+ aa.set(b"V".to_vec(), js("validate();"));+ once.update_dict(other, |d| d.set(b"AA".to_vec(), Object::Dict(aa))).unwrap();+ rename_to(&mut once, "other", "solo").unwrap();+ let once = reopen(&once);+ let group = field(&fields(&once), "solo").clone();+ let moved = group.widgets.iter().find(|w| w.on_state.as_deref() == Some("B")).unwrap();+ let wd = once.get(moved.obj).as_dict().unwrap().clone();+ assert!(!wd.contains(b"AA"), "a widget left with no trigger has no /AA");+ }++ /// However many "ChoiceN" names a group already uses, a joining button with a clashing export+ /// value gets a free one, so the two buttons can still be chosen apart.+ #[test]+ fn a_joining_button_gets_a_free_export_value_when_choice_names_run_long() {+ let mut doc = two_radio_groups("Choice1", "Choice1");+ let group = field(&fields(&doc), "Group1").clone();+ let model = doc.get(group.widgets[0].obj).as_dict().unwrap().clone();+ let look = doc.add(Object::Stream(pdfcraft_cos::Stream::from_raw(pdfcraft_cos::Dict::new(), b"0 g".to_vec())));+ let mut kids = vec![Object::Ref(group.widgets[0].obj)];+ for i in 2..=10_000 {+ let mut n = pdfcraft_cos::Dict::new();+ n.set(format!("Choice{i}").into_bytes(), Object::Ref(look));+ n.set(b"Off".to_vec(), Object::Ref(look));+ let mut ap = pdfcraft_cos::Dict::new();+ ap.set(b"N".to_vec(), Object::Dict(n));+ let mut w = model.clone();+ w.set(b"AP".to_vec(), Object::Dict(ap));+ w.remove(b"P");+ kids.push(Object::Ref(doc.add(Object::Dict(w))));+ }+ doc.update_dict(group.obj, |d| d.set(b"Kids".to_vec(), Object::Array(kids))).unwrap();+ rename_to(&mut doc, "Group2", "Group1").unwrap();+ let group = field(&fields(&doc), "Group1").clone();+ let states: Vec<String> = group.widgets.iter().filter_map(|w| w.on_state.clone()).collect();+ assert_eq!(states.len(), 10_001);+ assert_eq!(states.last().map(String::as_str), Some("Choice10001"));+ }++ /// Only a radio button joins by name: other clashes are refused as before, and a locked group+ /// isn't changed.+ #[test]+ fn joining_by_name_is_only_for_radio_buttons_and_unlocked_groups() {+ let mut doc = two_radio_groups("Yes", "No");+ add_field(&mut doc, 0, [50.0, 700.0, 250.0, 720.0], &NewField::Text { multiline: false }, Some("note")).unwrap();+ assert!(rename_to(&mut doc, "note", "Group1").is_err(), "a text field doesn't join a radio group");+ assert!(rename_to(&mut doc, "Group2", "note").is_err(), "a radio button doesn't join a text field");+ set_props(&mut doc, "Group1", &FieldProps { locked: Some(true), ..FieldProps::default() }).unwrap();+ assert!(rename_to(&mut doc, "Group2", "Group1").is_err(), "a locked group");+ assert_eq!(fields(&doc).len(), 3);+ }++ /// `/I` of field `name`: the selected positions in `/Opt`, or `None` when absent.+ fn selection_indices(doc: &Document, name: &str) -> Option<Vec<i64>> {+ let f = field(&fields(doc), name).clone();+ let d = doc.get(f.obj).as_dict().cloned().unwrap();+ d.get(b"I").map(|i| doc.resolve(i).as_array().unwrap().iter().map(|o| o.as_int().unwrap()).collect())+ }++ #[test]+ fn changing_a_lists_options_repoints_its_selected_indices() {+ let mut doc = one_page();+ let list =+ add_field(&mut doc, 0, [50.0, 600.0, 250.0, 680.0], &NewField::List { options: vec!["A".into(), "B".into(), "C".into()], multi: true }, None)+ .unwrap();+ set_value(&mut doc, &list, &FieldValue::Choice(vec!["C".into(), "B".into()])).unwrap();+ assert_eq!(selection_indices(&doc, &list), Some(vec![1, 2]));+ let f = field(&fields(&doc), &list).clone();+ doc.update_dict(f.obj, |d| d.set(b"TI".to_vec(), Object::Int(2))).unwrap();+ // Removing A moves B and C up one place.+ let opts = |o: &[&str]| FieldProps { options: Some(o.iter().map(|s| s.to_string()).collect()), ..FieldProps::default() };+ set_props(&mut doc, &list, &opts(&["B", "C", "D"])).unwrap();+ assert_eq!(selection_indices(&doc, &list), Some(vec![0, 1]));+ // Removing B leaves only C selected; the top row would point past the end.+ set_props(&mut doc, &list, &opts(&["C"])).unwrap();+ assert_eq!(selection_indices(&doc, &list), Some(vec![0]));+ assert_eq!(top_row(&doc, f.obj), Some(0), "the list scrolls back to its only row");+ // No selected value is offered any more.+ set_props(&mut doc, &list, &opts(&["X", "Y"])).unwrap();+ assert_eq!(selection_indices(&doc, &list), None);+ let doc = reopen(&doc);+ assert_eq!(selection_indices(&doc, &list), None);+ }++ fn top_row(doc: &Document, obj: ObjRef) -> Option<i64> {+ doc.get(obj).as_dict().and_then(|d| d.get(b"TI")).and_then(|o| o.as_int())+ }++ #[test]+ fn shrinking_a_lists_options_scrolls_a_widget_with_its_own_top_row() {+ let objs: Vec<String> = vec![+ "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(),+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(),+ "<< /Type /Page /Parent 2 0 R /Annots [7 0 R] >>".into(),+ "<< /Fields [6 0 R] /DA (/Helv 10 Tf 0 g) /DR << /Font << /Helv 5 0 R >> >> >>".into(),+ "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>".into(),+ "<< /FT /Ch /T (pick) /Opt [(A) (B) (C) (D) (E) (F)] /V (F) /I [5] /Kids [7 0 R] >>".into(),+ "<< /Type /Annot /Subtype /Widget /Parent 6 0 R /TI 5 /Rect [50 700 250 720] /P 3 0 R >>".into(),+ ];+ let mut doc = document(&objs);+ let widget = ObjRef::new(7, 0);+ set_props(&mut doc, "pick", &FieldProps { options: Some(vec!["F".into(), "A".into()]), ..FieldProps::default() }).unwrap();+ assert_eq!(selection_indices(&doc, "pick"), Some(vec![0]));+ // The widget's own /TI is read before the field's; row 5 no longer exists.+ assert_eq!(top_row(&doc, widget), Some(0), "the widget scrolls to F, now row 0");+ let doc = reopen(&doc);+ assert_eq!(top_row(&doc, widget), Some(0));+ }++ #[test]+ fn each_widget_with_its_own_top_row_scrolls_by_itself() {+ // Widget 7 shows from the field's top row; widget 8 keeps its own /TI 4.+ let objs = |v: &str| -> Vec<String> {+ vec![+ "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(),+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(),+ "<< /Type /Page /Parent 2 0 R /Annots [7 0 R 8 0 R] >>".into(),+ "<< /Fields [6 0 R] /DA (/Helv 10 Tf 0 g) /DR << /Font << /Helv 5 0 R >> >> >>".into(),+ "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>".into(),+ format!("<< /FT /Ch /T (pick) /Opt [(A) (B) (C) (D) (E) (F)] {v} /Kids [7 0 R 8 0 R] >>"),+ "<< /Type /Annot /Subtype /Widget /Parent 6 0 R /Rect [50 700 250 740] /P 3 0 R >>".into(),+ "<< /Type /Annot /Subtype /Widget /Parent 6 0 R /TI 4 /Rect [50 600 250 620] /P 3 0 R >>".into(),+ ]+ };+ let (first, other) = (ObjRef::new(7, 0), ObjRef::new(8, 0));+ // The options shrink: the first widget already shows A, the other's row 4 is gone.+ let mut doc = document(&objs("/V (A) /I [0]"));+ set_props(&mut doc, "pick", &FieldProps { options: Some(vec!["A".into(), "B".into()]), ..FieldProps::default() }).unwrap();+ assert_eq!(top_row(&doc, first), None);+ assert_eq!(top_row(&reopen(&doc), other), Some(0), "options: the other widget scrolls to A");+ // A new value the first widget already shows, below the other's view.+ let mut doc = document(&objs("/V (B) /I [1]"));+ set_value(&mut doc, "pick", &FieldValue::Choice(vec!["A".into()])).unwrap();+ assert_eq!(top_row(&doc, ObjRef::new(6, 0)), None, "the field's top row did not move");+ assert_eq!(top_row(&reopen(&doc), other), Some(0), "value: the other widget scrolls to A");+ }++ /// A list box's top row is chosen with the font size set in the same edit: at the larger size+ /// fewer rows fit, so it scrolls further to keep the selection in view.+ #[test]+ fn a_list_boxs_top_row_follows_a_font_size_changed_with_its_items() {+ let mut doc = document(&[+ "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(),+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(),+ "<< /Type /Page /Parent 2 0 R /Annots [6 0 R] >>".into(),+ "<< /Fields [6 0 R] /DA (/Helv 10 Tf 0 g) /DR << /Font << /Helv 5 0 R >> >> >>".into(),+ "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>".into(),+ "<< /FT /Ch /T (pick) /Opt [(A) (B) (C) (D) (E)] /V (C) /I [2] /Type /Annot /Subtype /Widget /Rect [50 700 250 740] /P 3 0 R >>".into(),+ ]);+ let items = ["Z", "A", "B", "C", "D"].map(String::from).to_vec();+ set_props(&mut doc, "pick", &FieldProps { options: Some(items), font_size: Some(20.0), ..FieldProps::default() }).unwrap();+ let doc = reopen(&doc);+ let g = field(&fields(&doc), "pick").clone();+ let w = &g.widgets[0];+ let rows = w.list.unwrap();+ let shown = rows.top..rows.top + rows.visible(w.rect[3] - w.rect[1]);+ assert!(shown.contains(&3), "C is row 3; rows {shown:?} show");+ }++ #[test]+ fn sorting_a_combo_boxs_items_repoints_its_selected_index() {+ let mut doc = one_page();+ let combo = add_field(+ &mut doc,+ 0,+ [50.0, 600.0, 250.0, 620.0],+ &NewField::Combo { options: vec!["Pear".into(), "apple".into(), "Fig".into()], editable: false },+ None,+ )+ .unwrap();+ set_value(&mut doc, &combo, &FieldValue::Choice(vec!["Pear".into()])).unwrap();+ assert_eq!(selection_indices(&doc, &combo), Some(vec![0]));+ set_props(&mut doc, &combo, &FieldProps { flags: vec![(flags::SORT, true)], ..FieldProps::default() }).unwrap();+ // apple, Fig, Pear: the selection follows Pear to the end.+ assert_eq!(selection_indices(&doc, &combo), Some(vec![2]));+ assert_eq!(field(&fields(&doc), &combo).value, vec!["Pear".to_string()]);+ }++ #[test]+ fn sorting_keeps_which_of_two_items_with_one_export_value_is_selected() {+ let mut doc = one_page();+ let list = add_field(&mut doc, 0, [50.0, 600.0, 250.0, 680.0], &NewField::List { options: vec!["a".into()], multi: false }, None).unwrap();+ let f = field(&fields(&doc), &list).clone();+ let item = |e: &str, shown: &str| Object::Array(vec![Object::String(PdfString::text(e)), Object::String(PdfString::text(shown))]);+ // Zeta and Alpha both export "x"; `/I` says Zeta is the one selected.+ doc.update_dict(f.obj, |d| {+ d.set(b"Opt".to_vec(), Object::Array(vec![item("x", "Zeta"), item("x", "Alpha"), item("y", "Mid")]));+ d.set(b"V".to_vec(), PdfString::text("x"));+ d.set(b"I".to_vec(), Object::Array(vec![Object::Int(0)]));+ })+ .unwrap();+ set_props(&mut doc, &list, &FieldProps { flags: vec![(flags::SORT, true)], ..FieldProps::default() }).unwrap();+ // Alpha, Mid, Zeta: the selection follows Zeta, not the first item exporting "x".+ assert_eq!(selection_indices(&doc, &list), Some(vec![2]));+ }++ #[test]+ fn clearing_a_kids_default_does_not_bring_back_its_parents() {+ let mut doc = fixture();+ let all = fields(&doc);+ let city = field(&all, "address.city").clone();+ let parent = doc.get(city.obj).as_dict().unwrap().reference(b"Parent").unwrap();+ doc.update_dict(parent, |d| d.set(b"DV".to_vec(), PdfString::text("Main St"))).unwrap();+ set_props(&mut doc, "address.city", &FieldProps { default_value: Some(Some("Elm".into())), ..FieldProps::default() }).unwrap();+ assert_eq!(field(&fields(&doc), "address.city").default, ["Elm"]);+ set_props(&mut doc, "address.city", &FieldProps { default_value: Some(None), ..FieldProps::default() }).unwrap();+ let mut doc = reopen(&doc);+ let f = field(&fields(&doc), "address.city").clone();+ assert!(f.default.iter().all(String::is_empty), "no default, not the parent's: {:?}", f.default);+ let own = doc.get(f.obj).as_dict().and_then(|d| d.get(b"DV")).and_then(|o| o.as_string()).map(PdfString::to_text);+ assert_eq!(own.as_deref(), Some(""), "the kid holds an empty default of its own");+ set_value(&mut doc, "address.city", &FieldValue::Text("Oak".into())).unwrap();+ reset(&mut doc, None).unwrap();+ assert!(field(&fields(&doc), "address.city").value.iter().all(String::is_empty), "reset clears it");+ // Without a parent default, clearing still removes the key.+ set_props(&mut doc, "name", &FieldProps { default_value: Some(None), ..FieldProps::default() }).unwrap();+ let name = field(&fields(&doc), "name").clone();+ assert!(doc.get(name.obj).as_dict().unwrap().get(b"DV").is_none());+ }++ #[test]+ fn clearing_a_kids_value_does_not_bring_back_its_parents() {+ // A text kid, then a list box kid, under a parent with both a value and a default.+ for (ft, set) in [("/FT /Tx", FieldValue::Text("Oak".into())), ("/FT /Ch /Opt [(Main St) (Oak)]", FieldValue::Choice(vec!["Oak".into()]))] {+ let mut doc = document(&[+ "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(),+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(),+ "<< /Type /Page /Parent 2 0 R /Annots [6 0 R] >>".into(),+ "<< /Fields [5 0 R] /DA (/Helv 0 Tf 0 g) >>".into(),+ format!("<< /T (address) {ft} /V (Main St) /DV (Main St) /Kids [6 0 R] >>"),+ "<< /Type /Annot /Subtype /Widget /T (city) /Parent 5 0 R /Rect [10 10 110 60] /P 3 0 R >>".into(),+ ]);+ set_props(&mut doc, "address.city", &FieldProps { default_value: Some(None), ..FieldProps::default() }).unwrap();+ set_value(&mut doc, "address.city", &set).unwrap();+ assert_eq!(field(&fields(&doc), "address.city").value, ["Oak"], "{ft}");+ reset(&mut doc, None).unwrap();+ let doc = reopen(&doc);+ let f = field(&fields(&doc), "address.city").clone();+ assert!(f.value.iter().all(String::is_empty), "{ft}: reset leaves it empty, not the parent's: {:?}", f.value);+ let mut doc = doc;+ set_value(&mut doc, "address.city", &set).unwrap();+ let clear = if ft.contains("Ch") { FieldValue::Choice(Vec::new()) } else { FieldValue::Text(String::new()) };+ set_value(&mut doc, "address.city", &clear).unwrap();+ let f = field(&fields(&reopen(&doc)), "address.city").clone();+ if ft.contains("Ch") {+ assert!(f.value.is_empty(), "{ft}: clearing leaves no choice selected: {:?}", f.value);+ } else {+ assert!(f.value.iter().all(String::is_empty), "{ft}: clearing leaves it empty: {:?}", f.value);+ }+ }+ }++ #[test]+ fn clearing_a_buttons_default_under_a_parent_with_one_leaves_it_off() {+ // A check box, then a radio button (flags 49152, inherited from the parent).+ for flags in ["", "/Ff 49152"] {+ let mut doc = document(&[+ "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(),+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(),+ "<< /Type /Page /Parent 2 0 R /Annots [6 0 R] >>".into(),+ "<< /Fields [5 0 R] /DA (/Helv 0 Tf 0 g) >>".into(),+ format!("<< /T (opts) /FT /Btn {flags} /DV /Yes /Kids [6 0 R] >>"),+ "<< /Type /Annot /Subtype /Widget /T (a) /Parent 5 0 R /V /Off /AS /Off /Rect [10 10 25 25] /P 3 0 R /AP << /N << /Yes 7 0 R /Off 7 0 R >> >> >>".into(),+ "<< /Length 0 >>+ stream++ endstream".into(),+ ]);+ let kind = field(&fields(&doc), "opts.a").kind;+ assert_eq!(kind == FieldKind::Radio, !flags.is_empty());+ set_props(&mut doc, "opts.a", &FieldProps { default_value: Some(None), ..FieldProps::default() }).unwrap();+ let f = field(&fields(&doc), "opts.a").clone();+ assert_eq!(doc.get(f.obj).as_dict().and_then(|d| d.get(b"DV")).and_then(|o| o.as_name()), Some(&b"Off"[..]), "{kind:?}");+ let on = if kind == FieldKind::Radio { FieldValue::Radio(Some("Yes".into())) } else { FieldValue::Check(true) };+ set_value(&mut doc, "opts.a", &on).unwrap();+ assert_eq!(field(&fields(&doc), "opts.a").value, ["Yes"]);+ reset(&mut doc, None).unwrap();+ let f = field(&fields(&doc), "opts.a").clone();+ assert!(f.value.iter().all(String::is_empty), "{kind:?}: reset leaves it off, not the parent's Yes: {:?}", f.value);+ }+ }++ ++++++ ++++#[test]++ ++++fn editing_button_export_values_preserves_selection_and_appearance() {++ ++++ let mut doc = fixture();++ ++++ set_value(&mut doc, "size", &FieldValue::Radio(Some("S".into()))).unwrap();++ ++++ let before = field(&fields(&doc), "size").clone();++ ++++ let appearances: Vec<_> = before.widgets.iter().map(|w| doc.get(w.obj).as_dict().unwrap().get(b"AP").cloned()).collect();++ ++++ set_props(&mut doc, "size", &FieldProps { export_value: Some((0, "Small å".into())), ..Default::default() }).unwrap();++ ++++ let after = field(&fields(&doc), "size").clone();++ ++++ assert_eq!(after.value, before.value);++ ++++ assert_eq!(after.default, before.default);++ ++++ assert_eq!(after.widgets, before.widgets);++ ++++ assert_eq!(after.export_of(0), Some("Small å"));++ ++++ assert_eq!(after.export_of(1), before.export_of(1));++ ++++ assert_eq!(after.export_values(), vec!["Small å"]);++ ++++ assert_eq!(appearances, after.widgets.iter().map(|w| doc.get(w.obj).as_dict().unwrap().get(b"AP").cloned()).collect::<Vec<_>>());++ ++++ let mut saved = reopen(&doc);++ ++++ assert_eq!(field(&fields(&saved), "size").export_of(0), Some("Small å"));++ ++++ set_value(&mut saved, "size", &FieldValue::Radio(Some("Small å".into()))).unwrap();++ ++++ reset(&mut saved, None).unwrap();++ ++++ assert_eq!(field(&fields(&saved), "size").value, before.default);++ ++++++ ++++ set_value(&mut doc, "agree", &FieldValue::Check(true)).unwrap();++ ++++ set_props(&mut doc, "agree", &FieldProps { export_value: Some((0, "Accepted".into())), ..Default::default() }).unwrap();++ ++++ let check = field(&fields(&doc), "agree").clone();++ ++++ assert_eq!(check.value, vec!["Yes"]);++ ++++ assert_eq!(check.export_values(), vec!["Accepted"]);++ ++++ assert_eq!(field(&fields(&reopen(&doc)), "agree").export_of(0), Some("Accepted"));++ ++++}++ ++++++ ++++#[test]++ ++++fn invalid_button_export_edits_leave_document_unchanged() {++ ++++ let mut doc = fixture();++ ++++ let before = write_incremental(&doc, &SaveOptions::default()).unwrap();++ ++++ for (field_name, index, value) in [("size", 99, "new"), ("size", 0, ""), ("size", 0, "Off"), ("size", 0, "L"), ("name", 0, "new")] {++ ++++ assert!(set_props(&mut doc, field_name, &FieldProps { export_value: Some((index, value.into())), ..Default::default() }).is_err());++ ++++ assert_eq!(write_incremental(&doc, &SaveOptions::default()).unwrap(), before);++ ++++ }++ ++++}++ ++++++ ++++#[test]++ ++++fn locked_button_export_edits_leave_the_document_unchanged() {++ ++++ for name in ["agree", "size"] {++ ++++ let mut doc = fixture();++ ++++ set_props(&mut doc, name, &FieldProps { locked: Some(true), ..Default::default() }).unwrap();++ ++++ let before = write_incremental(&doc, &SaveOptions::default()).unwrap();++ ++++ let error = set_props(++ ++++ &mut doc,++ ++++ name,++ ++++ &FieldProps { export_value: Some((0, "Changed".into())), tooltip: Some("Must not change".into()), ..Default::default() },++ ++++ )++ ++++ .unwrap_err();++ ++++ assert!(error.to_string().contains("locked"));++ ++++ assert_eq!(write_incremental(&doc, &SaveOptions::default()).unwrap(), before);++ ++++ }++ ++++}diff --cc crates/optimize/README.mdindex dec417867,cbe37f6b7,cbe37f6b7,cbe37f6b7,cbe37f6b7,a1c47697b,928a2fbac..388345be7--- a/crates/optimize/README.md+++ b/crates/optimize/README.md@@@@@@@@ -29,60 -27,11 -27,11 -27,11 -27,11 -27,27 -27,33 +29,64 @@@@@@@@ let report = optimize_with_progress(&mumeasured (forms nested deeper, or drawn too many times), no image is resampled. Colour and grayscale images above athreshold are resampled with a bicubic (Catmull-Rom) filter to a target resolution andstored as JPEG (Acrobat's quality steps) or ZIP; soft masks are resampled with their image.------ An image is replaced only if the result is smaller. Left alone: CMYK and other colour spaces,------ image masks, decode arrays, more than 8 bits, JPEG 2000, JBIG2 and CCITT. A JPEG is read with++++++ An image is replaced only if the result is smaller. Left alone by these colour and grey++++++ settings: CMYK and other colour spaces, image masks, decode arrays, more than 8 bits, JPEG 2000,++++++ JBIG2 and CCITT (black-and-white images, CCITT among them, are below). A JPEG is read withits colour transform (an Adobe marker's, else `/ColorTransform`, ISO 32000-2 §7.4.8), so onestored untransformed keeps its colours; one whose marker and `/ColorTransform` disagree is left---- alone, since readers differ on which wins.++++ alone, since readers differ on which wins. Samples are read with `/DecodeParms` given by++++ reference too, the numbers inside included (`Document::with_direct_parms`), here and below:++++ without them a predictor's tag bytes would shift every row of an image written back.--- **Monochrome images** (`Settings::mono`, CCITT Group 4 by default, or JBIG2): a 1-bit image-- with one colour component (grey, indexed, a separation) or an image mask, stored with no filter-- or with general-purpose ones, is stored again as CCITT Group 4 (`pdfcraft_filters::encode_g4`)- or lossless JBIG2 (`encode_jbig2_generic`; a document below PDF 1.4 gets `/Version /1.4` in- its catalog) when that is smaller as stored. On 300 dpi text JBIG2 is about a third smaller- than Group 4. It is lossless: the samples decode to the same bits, so the colour- space, decode array and masks stay. Group 4 wins on scans, whose ragged edges defeat Flate;- on clean computer-drawn 1-bit art Flate can be smaller, and the image then stays. Not yet:- JBIG2 symbol coding (lossy or lossless), monochrome downsampling, inline images, soft masks and- or lossless JBIG2 (`encode_jbig2`; a document below PDF 1.4 gets `/Version /1.4` in- its catalog) when that is smaller as stored. JBIG2 stores each distinct mark once, as a- symbol, when the image's marks repeat exactly, as rendered text's do: on six pages of- 300 dpi text that came to 28% of a generic region's size and 17% of Group 4's. On scans,- whose copies of a letter are seldom identical, symbols gain little: on the same pages with 2%- or more of the letters' edge pixels flipped at random, at most 8% below a generic region in- total (20% on one page), and the generic region was 27–33% below Group 4. It is lossless: the- samples decode to the same bits, so the colour space, decode array and masks stay. Group 4- wins on scans, whose ragged edges defeat Flate; on clean computer-drawn 1-bit art Flate can- be smaller, and the image then stays. Not yet:- JBIG2 refinement coding (lossless gains on scans), a symbol dictionary shared between images- (`/JBIG2Globals`), lossy JBIG2, monochrome downsampling, inline images, soft masks and-- `/Mask` images, and Group 4 for rows wider than 32,767 samples (JBIG2 takes rows of up to-- 1,048,576). Redaction doesn't decode JBIG2 or Group 4 yet: a mark over part of such an image-- removes the whole image (nothing leaks). Export reads JBIG2, but nothing that exports an image-- reads Group 4 yet: Export ▸ Images and Save Image As refuse it, Copy Image fails, and Word,-- PowerPoint and HTML export leave the picture out.++++++- **Monochrome images** (`Settings::mono`, `MonoSettings::REDUCE` by default: to 300 ppi above++++++ 450 ppi, CCITT Group 4). Black-and-white images are a 1-bit image with one colour component++++++ (grey, indexed, a separation) or an image mask, stored with no filter, with general-purpose ones++++++ or with CCITT fax after any of those (decoded by `Document::decoded_image_within`, no further++++++ than its rows can need; byte-aligned Group 3 with end-of-line codes but none before the first++++++ row, not as T.4 sends them, is read as PdfCraft draws it, which at `/K 0` may be other rows than++++++ were coded, and an image stored again keeps them). Packed to one bit first, unless a colour-key `/Mask` is in the image's++++++ own values: eight-bit grey of only 0 and 255; eight-bit `DeviceRGB` of only black and white,++++++ which becomes `DeviceGray` (not calibrated RGB or RGB with a profile, nor one drawn or listed++++++ where `/DefaultGray` or `/DefaultRGB` is in force, which would then draw it otherwise, nor one++++++ referred to from anywhere but the page and form resources the optimizer reads, where they may++++++ be: an annotation's appearance or a pattern drawing it, directly or through resources or a form++++++ it shares with a page, or another image's `/Alternates`; nor one whose soft mask has a++++++ `/Matte`); and an indexed image of 2, 4 or 8 bits that uses only palette entries++++++ 0 and 1, which keeps its palette, whatever its two colours. A decode array stays when it means++++++ the same at one bit (grey's, or RGB's if the same for each component, as grey's), and an indexed++++++ image's default one goes, as the default at one bit; otherwise the image is left alone. The grey++++++ or colour settings take a packed image instead when they make it smaller still, its soft mask++++++ counted (resampled with it there, kept as it is here), as they can a dithered scan by++++++ downsampling it to JPEG.++++++ - **Downsampling:** one whose effective resolution is above `above_ppi` is averaged down to++++++ `target_ppi`: each new pixel takes the sample covering more of its area, and the dark one on a++++++ tie, so a dark line half a new pixel wide stays: black in grey and the painted part of an image++++++ mask (a 0, or a 1 with an inverting decode array), full ink in a separation (a 1, or a 0), and++++++ entry 0 of an indexed image, whatever colour its palette gives it (the palette isn't read yet).++++++ Not one with a soft mask, whose own size would have to follow; not a halftone or a dither,++++++ most of whose new pixels would cover both black and white, so that taking the sample covering++++++ more would turn its tones solid (a 50% screen black, a 25% one white); and not one wider than++++++ a fax row (`pdfcraft_filters::MAX_CCITT_COLUMNS`), as the averaging keeps a counter for each++++++ column. On a 600 ppi text page, Group 4 at 300 ppi is half the size.++++++ - **Compression:** CCITT Group 4 (`pdfcraft_filters::encode_g4`), or 1-bit Flate when that is++++++ smaller, which only a resampled image or one packed from more bits may be: a 1-bit image that++++++ is only stored again becomes Group 4 or stays. Group 4 alone is only decoded to be resampled;++++++ Group 3, or Group 4 inside another filter such as `ASCII85Decode`, is stored again as Group 4++++++ alone when that is smaller. Damaged Group 3 with end-of-line codes is stored as the decoder++++++ recovers it, a bad row picked up again at the next code, as it reports no damage there; without++++++ them, damage stops the decoding and the image is left alone. With Retain, a resampled image++++++ keeps its kind of compression (CCITT, or Flate) and nothing else changes; an image of more bits++++++ is then left to the grey or colour settings. Every change is kept only when it is smaller as++++++ stored.++++++ - Apart from the downsampling it is lossless: the samples keep their meaning, so the colour++++++ space, decode array and `/Mask` stay, but for packed RGB, which becomes grey with one decode++++++ pair. Group 4 wins on scans, whose ragged edges defeat Flate; on clean computer-drawn 1-bit++++++ art Flate can be smaller. Not yet: JBIG2, inline images, an image's own `/SMask` or `/Mask`++++++ image (only images drawn on a page are visited), and Group 4 for rows wider than 32,767++++++ samples.++++++++++++++Lossless JBIG2 is also available as Monochrome Images compression, with a bounded generic-region encoder and no symbol substitution. Export reads its embedded images and bounded shared globals.++++++++++++++The JBIG2 choice now uses a bounded exact-copy symbol dictionary when smaller than the generic-region result; lossy symbol substitution is not used.- **Discard objects:** thumbnails, alternate images, document tags, print settings.- **Clean up:** Flate for streams with no filter; for streams with an outer ASCII85 or ASCIIHexlayer, that layer is removed when the result is smaller (the inner filters keep their encodeddiff --cc crates/optimize/src/images.rsindex 54e382d13,b9761b85f,b9761b85f,b9761b85f,b9761b85f,cf668d0fb,392e9145e..65cecfffd--- a/crates/optimize/src/images.rs+++ b/crates/optimize/src/images.rs@@@@@@@@ -5,7 -5,7 -5,7 -5,7 -5,7 -5,7 -5,7 +5,7 @@@@@@@@ use std::collections::{HashMap, HashSetuse pdfcraft_content::{Matrix, Pieces};use pdfcraft_cos::{DecodeBudget, Dict, Document, ObjRef, Object, Stream};---- use crate::{Compression, ImageSettings, OptimizeError, Report, Settings, Stage};--use crate::{Compression, ImageSettings, MonoCompression, OptimizeError, Report, Settings, Stage};++++++use crate::{Compression, ImageSettings, MonoCompression, MonoSettings, OptimizeError, Report, Settings, Stage};/// Images with more pixels than this are left alone (memory).const MAX_PIXELS: u64 = 80_000_000;@@@@@@@@ -284,99 -173,8 -173,8 -173,8 -173,8 -173,8 -173,8 +284,99 @@@@@@@@ fn walk_pages(doc: &Document, pages: &[}if !walk.complete {walk.out.values_mut().for_each(|v| *v = f64::INFINITY);++++++ walk.defaults.extend(walk.out.keys().map(|r| r.num));++++++ }++++++ (walk.out, walk.defaults, walk.read)++++++}++++++++++++/// Whether image `r` is one [`one_bit`] may make grey: eight-bit `DeviceRGB`, not in an image codec.++++++fn device_rgb(doc: &Document, r: ObjRef) -> bool {++++++ let Object::Stream(s) = &*doc.get(r) else { return false };++++++ let cs = s.dict.get(b"ColorSpace").map(|cs| doc.resolve(cs));++++++ let codec =++++++ s.filters().iter().any(|(f, _)| matches!(f, pdfcraft_filters::Filter::Dct | pdfcraft_filters::Filter::Jpx | pdfcraft_filters::Filter::Jbig2));++++++ s.dict.int(b"BitsPerComponent") == Some(8)++++++ && !codec++++++ && cs.as_deref().and_then(Object::as_name).is_some_and(|n| matches!(n, b"DeviceRGB" | b"RGB"))++++++}++++++++++++/// Call `f` with every reference in `o`, a dictionary's or array's included, a stream's dictionary++++++/// too, but not those in objects referred to.++++++fn each_ref(o: &Object, mut f: impl FnMut(ObjRef)) {++++++ // Direct objects nest finitely (the parser builds trees), so this ends.++++++ let mut stack = vec![o];++++++ while let Some(o) = stack.pop() {++++++ match o {++++++ Object::Ref(r) => f(*r),++++++ Object::Dict(d) => stack.extend(d.iter().map(|(_, v)| v)),++++++ Object::Array(a) => stack.extend(a),++++++ Object::Stream(s) => stack.extend(s.dict.iter().map(|(_, v)| v)),++++++ _ => {}++++++ }++++ }-- walk.out++++++}++++++++++++/// The images among `images` (by object number) that may be drawn beyond what the walk read:++++++/// some object the document uses refers to the image, or to an object on the way to it from a++++++/// page (an `/XObject` dictionary, resources, a form), other than as the page and form resources++++++/// the walk read do. So an annotation's appearance, a pattern, a Type3 glyph or a soft mask's++++++/// group drawing it, directly or through resources or a form it shares with a page, counts, as++++++/// other default colour spaces may be in force there, and so does any other reference (another++++++/// image's `/Alternates`, say). Objects nothing reaches from the trailer don't count.++++++fn used_elsewhere(doc: &Document, images: &HashSet<u32>, read: &Read) -> HashSet<u32> {++++++ if images.is_empty() {++++++ return HashSet::new();++++++ }++++++ let targets: HashSet<u32> = read.entries.iter().map(|(target, ..)| *target).collect();++++++ // References to each object the walk followed, by the object holding them.++++++ let mut held: HashMap<u32, HashMap<u32, usize>> = HashMap::new();++++++ let mut queue: Vec<u32> = Vec::new();++++++ let mut visited = HashSet::new();++++++ for (_, v) in doc.trailer().iter() {++++++ each_ref(v, |r| queue.push(r.num));++++++ }++++++ while let Some(num) = queue.pop() {++++++ if !visited.insert(num) {++++++ continue;++++++ }++++++ let obj = doc.get(ObjRef::new(num, doc.generation(num)));++++++ each_ref(&obj, |r| {++++++ if targets.contains(&r.num) {++++++ *held.entry(r.num).or_default().entry(num).or_default() += 1;++++++ }++++++ if !visited.contains(&r.num) {++++++ queue.push(r.num);++++++ }++++++ });++++++ }++++++ let mut seen: HashMap<(u32, u32), usize> = HashMap::new();++++++ for (target, holder, _) in &read.entries {++++++ *seen.entry((*target, *holder)).or_default() += 1;++++++ }++++++ // Covered: every reference to it is one the walk followed, held by a page or node, or by an++++++ // object covered in turn. Everything the walk reached starts covered, and whatever has a++++++ // reference it didn't follow, or is held by an object taken out, is taken out, until nothing++++++ // more is. Content beyond what the walk read has to refer to an object on its way to the++++++ // image, which takes out everything after it; a cycle the walk read whole stays covered.++++++ let mut holds: HashMap<u32, Vec<u32>> = HashMap::new();++++++ for (target, holders) in &held {++++++ for h in holders.keys() {++++++ holds.entry(*h).or_default().push(*target);++++++ }++++++ }++++++ let mut covered: HashSet<u32> = held.keys().copied().collect();++++++ let passes = |t: u32, covered: &HashSet<u32>| {++++++ held.get(&t)++++++ .is_some_and(|holders| holders.iter().all(|(h, n)| seen.get(&(t, *h)) == Some(n) && (read.roots.contains(h) || covered.contains(h))))++++++ };++++++ let mut check: Vec<u32> = covered.iter().copied().collect();++++++ while let Some(t) = check.pop() {++++++ if covered.contains(&t) && !passes(t, &covered) {++++++ covered.remove(&t);++++++ check.extend(holds.get(&t).into_iter().flatten().copied());++++++ }++ }---- walk.out++++++ images.iter().copied().filter(|i| !covered.contains(i)).collect()}/// Colour components of a colour space PdfCraft resamples: gray (1) or RGB (3).@@@@@@@@ -745,329 -532,6 -532,6 -532,6 -532,6 -543,76 -543,77 +745,338 @@@@@@@@ fn process(doc: &Document, s: &Stream,(after < before).then_some((new, smask))}++++ /// Whether colour space `cs` has one colour component, so a 1-bit image in it has one bit per++++ /// pixel: grey, a separation, an indexed space or a DeviceN of one colourant. Of names, only++++ /// DeviceGray counts, with `/G`, its abbreviation, which readers take as grey too: another name++++ /// is no colour space on its own (`/Indexed` and `/CalGray` need their parameters), so it can only++++ /// name a resource, which might be RGB.++++ fn one_component(doc: &Document, cs: &Object) -> bool {++++ let cs = doc.resolve(cs);++++ match &*cs {++++ Object::Name(n) => matches!(n.as_slice(), b"DeviceGray" | b"G"),++++ Object::Array(a) => match a.first().and_then(Object::as_name) {++++ Some(b"CalGray" | b"Separation" | b"Indexed" | b"I") => true,++++ Some(b"ICCBased") => a.get(1).is_some_and(|icc| matches!(&*doc.resolve(icc), Object::Stream(s) if s.dict.int(b"N") == Some(1))),++++ Some(b"DeviceN") => a.get(1).is_some_and(|names| doc.resolve(names).as_array().is_some_and(|n| n.len() == 1)),++++ _ => false,++++ },++++ _ => false,++++ }++++ }++++--/// A black-and-white image (one bit per pixel, or an image mask) stored again as `compression`--/// asks (CCITT Group 4 or JBIG2), if the result is smaller as stored. Only images whose samples--/// PdfCraft decodes (no filter, or general-purpose filters: image codecs don't decode here)--/// qualify. The samples decode to the same bits, so the colour space, decode array and masks stay--/// as they are.--fn mono(doc: &Document, s: &Stream, compression: MonoCompression) -> Option<Stream> {-- let widest = match compression {-- MonoCompression::CcittG4 => pdfcraft_filters::MAX_G4_COLUMNS,-- MonoCompression::Jbig2 => pdfcraft_filters::MAX_JBIG2_COLUMNS,-- MonoCompression::Retain => return None,-- };++++++/// A pixel's samples as a 1 or a 0, or `None` for a colour that is neither.++++++type Pixel = fn(&[u8]) -> Option<bool>;++++++++++++/// The samples of a black-and-white image, as rows of 1-bit samples each starting on a new byte,++++++/// with its width and height, and, when they were packed from more bits, its dictionary as a 1-bit++++++/// image. These count:++++++/// - one bit per pixel in one colour component, or an image mask, stored with no filter, with++++++/// general-purpose ones, or with CCITT fax last ([`Document::decoded_image_within`], no further++++++/// than its rows can need);++++++/// - with `pack`, and with no colour-key `/Mask` (its ranges are in the image's own values):++++++/// - eight-bit grey (one component, not indexed) whose every sample is 0 or 255. A decode array++++++/// maps 0 and 255 at eight bits as it maps 0 and 1 at one bit, so it stays;++++++/// - eight-bit `DeviceRGB` whose every pixel is black or white, which becomes `DeviceGray`. A++++++/// decode array the same for all three components becomes that one pair; another stops it.++++++/// Calibrated RGB and RGB with a profile are left out, as the profile could make them other++++++/// than black and white; so is one drawn where `/DefaultGray` or `/DefaultRGB` is or may be in++++++/// force (`defaults`), which would draw it otherwise as grey, and one whose soft mask has a++++++/// `/Matte` of three components;++++++/// - an indexed image of 2, 4 or 8 bits that uses only palette entries 0 and 1, which stay 0 and++++++/// 1 at one bit, whatever their colours, so the colour space stays. A decode array other than++++++/// the default stops it: in index units it would mean something else at one bit.++++++fn one_bit(doc: &Document, s: &Stream, pack: bool, defaults: bool) -> Option<(Vec<u8>, u32, u32, Option<Dict>)> {++++ let d = &s.dict;++++++ // Through u32 first, as everywhere here, so the product can't overflow.++++++ let (w, h) = (u32::try_from(d.int(b"Width")?).ok()?, u32::try_from(d.int(b"Height")?).ok()?);++++++ if w == 0 || h == 0 || u64::from(w) * u64::from(h) > MAX_PIXELS {++++++ return None;++++++ }++++++ let (wu, hu) = (usize::try_from(w).ok()?, usize::try_from(h).ok()?);++++++ let stride = wu.div_ceil(8);++++ let bits = d.int(b"BitsPerComponent");-- let qualifies = if matches!(d.get(b"ImageMask"), Some(Object::Bool(true))) {-- bits.is_none_or(|b| b == 1)-- } else {-- bits == Some(1) && d.get(b"ColorSpace").is_some_and(|cs| one_component(doc, cs))++++++ let mask = matches!(d.get(b"ImageMask"), Some(Object::Bool(true)));++++++ if (mask && bits.is_none_or(|b| b == 1)) || (bits == Some(1) && d.get(b"ColorSpace").is_some_and(|cs| one_component(doc, cs))) {++++++ // No further than its rows can need: a fax image's code (the filters before its decoder++++++ // produce it) takes at most about a byte a pixel and each row's end, as redaction allows.++++++ let len = stride.checked_mul(hu)?;++++++ let max = match s.filters().last() {++++++ Some((pdfcraft_filters::Filter::CcittFax, _)) => wu.checked_mul(hu)?.checked_add(hu.checked_mul(4)?)?.checked_add(4096)?,++++++ _ => allowance(len, h)?,++++++ };++++++ let mut data = doc.decoded_image_within(s, max).ok()?;++++++ if data.len() < len {++++++ return None;++++++ }++++++ data.truncate(len);++++++ return Some((data, w, h, None));++++++ }++++++ let colour_key = d.get(b"Mask").is_some_and(|m| doc.resolve(m).as_array().is_some());++++++ if !pack || mask || colour_key {++++++ return None;++++++ }++++++ let cs = d.get(b"ColorSpace")?;++++++ // The decode array's numbers, each given directly or by reference, as integers or reals; `None`++++++ // when it has something else.++++++ let decode = match d.get(b"Decode").map(|v| doc.resolve(v)).as_deref() {++++++ None => None,++++++ Some(Object::Array(v)) => Some(v.iter().map(|e| doc.resolve(e).as_f64()).collect::<Option<Vec<f64>>>()?),++++++ Some(_) => return None,++++++ };++++++ let mut packed = d.clone();++++++ packed.set(b"BitsPerComponent".to_vec(), Object::Int(1));++++++ // Components a pixel, bits a component, and a pixel's samples as 1 or 0.++++++ let (n, bpc, white): (usize, usize, Pixel) = match &*doc.resolve(cs) {++++++ Object::Array(a) if matches!(a.first().and_then(Object::as_name), Some(b"Indexed" | b"I")) => {++++++ let bpc = bits.filter(|b| matches!(b, 2 | 4 | 8))?;++++++ match decode.as_deref() {++++++ None => {}++++++ Some([d0, d1]) if *d0 == 0.0 && *d1 == f64::from((1u32 << bpc) - 1) => {++++++ packed.remove(b"Decode");++++++ }++++++ Some(_) => return None,++++++ }++++++ (1, usize::try_from(bpc).ok()?, |v| match v {++++++ [0] => Some(false),++++++ [1] => Some(true),++++++ _ => None,++++++ })++++++ }++++++ Object::Name(name) if matches!(name.as_slice(), b"DeviceRGB" | b"RGB") && bits == Some(8) => {++++++ let matte = |m: &Object| matches!(&*doc.resolve(m), Object::Stream(m) if m.dict.contains(b"Matte"));++++++ if defaults || d.get(b"SMask").is_some_and(matte) {++++++ return None;++++++ }++++++ match decode.as_deref() {++++++ None => {}++++++ Some(v @ [d0, d1, ..]) if v.len() == 6 && v.chunks(2).all(|pair| pair == [*d0, *d1]) => {++++++ let number = |n: f64| if n.fract() == 0.0 { Object::Int(n as i64) } else { Object::Real(n) };++++++ packed.set(b"Decode".to_vec(), Object::Array(vec![number(*d0), number(*d1)]));++++++ }++++++ Some(_) => return None,++++++ }++++++ packed.set(b"ColorSpace".to_vec(), Object::name("DeviceGray"));++++++ (3, 8, |v| match v {++++++ [0, 0, 0] => Some(false),++++++ [255, 255, 255] => Some(true),++++++ _ => None,++++++ })++++++ }++++++ _ if bits == Some(8) && one_component(doc, cs) => (1, 8, |v| match v {++++++ [0] => Some(false),++++++ [255] => Some(true),++++++ _ => None,++++++ }),++++++ _ => return None,++++ };-- if !qualifies {++++++ let row_len = wu.checked_mul(n)?.checked_mul(bpc)?.div_ceil(8);++++++ // Through its parameters given by reference too: without a PNG predictor's tag bytes taken++++++ // off, rows of 0 and 255 (or palette entries 0 and 1) would still pass below, each shifted.++++++ let samples = doc.with_direct_parms(s).decoded_within(allowance(row_len.checked_mul(hu)?, h)?).ok()?;++++++ Some((packed_rows(&samples, row_len, wu, hu, (n, bpc, white))?, w, h, Some(packed)))++++++}++++++++++++/// `h` rows of `w` pixels, each row `row_len` bytes of `n` samples a pixel at `bpc` bits (8, or++++++/// a divisor of 8 with `n` 1), as rows of 1-bit samples each starting on a new byte: 1 where++++++/// `white` says the pixel is white. `None` when a pixel is neither, `samples` is short, or the++++++/// rows have another shape: no pixels in a row, other sample sizes, or too few bytes for their++++++/// pixels.++++++fn packed_rows(samples: &[u8], row_len: usize, w: usize, h: usize, (n, bpc, white): (usize, usize, Pixel)) -> Option<Vec<u8>> {++++++ let stride = w.div_ceil(8);++++++ let shape = (n > 0 && bpc == 8) || (n == 1 && matches!(bpc, 1 | 2 | 4));++++++ if stride == 0 || !shape || row_len < w.checked_mul(n)?.checked_mul(bpc)?.div_ceil(8) {++++ return None;++++ }-- let (w, h) = (u32::try_from(d.int(b"Width")?).ok()?, u32::try_from(d.int(b"Height")?).ok()?);-- if w == 0 || h == 0 || w > widest || u64::from(w) * u64::from(h) > MAX_PIXELS {++++++ // From here no row is empty and x·n·bpc stays within one, and the output is no larger than++++++ // the samples it is read from.++++++ let samples = samples.get(..row_len.checked_mul(h)?)?;++++++ let mut out = vec![0u8; stride.checked_mul(h)?];++++++ for (row, out_row) in samples.chunks(row_len).zip(out.chunks_mut(stride)) {++++++ for x in 0..w {++++++ let on = if bpc == 8 {++++++ white(row.get(x * n..x * n + n)?)?++++++ } else {++++++ // Samples narrower than a byte, the first in its high bits; bpc divides 8.++++++ let at = x * bpc;++++++ white(&[(row.get(at / 8)? >> (8 - bpc - at % 8)) & ((1u8 << bpc) - 1)])?++++++ };++++++ if on {++++++ *out_row.get_mut(x / 8)? |= 0x80 >> (x % 8);++++++ }++++++ }++++++ }++++++ Some(out)++++++}++++++++++++/// Whether sample 1 is the dark one of the 1-bit image `d` describes, after its decode array++++++/// (`[0 1]` when it has none of two numbers): the painted part of an image mask and black in grey++++++/// decode to 0, and full ink in a separation (or a DeviceN of one colourant) to 1. An indexed image++++++/// says the sample that decodes to entry 0 (its decode array maps samples to entries, ISO 32000-2++++++/// §8.9.5.2): its palette says which entry is darker, and the palette isn't read yet, so a tie goes++++++/// to entry 0 whatever its colour.++++++fn dark_is_one(doc: &Document, d: &Dict) -> bool {++++++ let number = |v: Option<&Object>| v.and_then(|v| doc.resolve(v).as_f64());++++++ let (d0, d1) = match d.get(b"Decode").map(|v| doc.resolve(v)).as_deref() {++++++ Some(Object::Array(a)) => number(a.first()).zip(number(a.get(1))).unwrap_or((0.0, 1.0)),++++++ _ => (0.0, 1.0),++++++ };++++++ if matches!(d.get(b"ImageMask"), Some(Object::Bool(true))) {++++++ return d1 < d0;++++++ }++++++ match d.get(b"ColorSpace").map(|cs| doc.resolve(cs)).as_deref() {++++++ Some(Object::Array(a)) => match a.first().and_then(Object::as_name) {++++++ Some(b"Separation" | b"DeviceN") => d1 > d0,++++++ _ => d1 < d0,++++++ },++++++ _ => d1 < d0,++++++ }++++++}++++++++++++/// `w` × `h` 1-bit rows (each starting on a new byte) averaged down to `nw` × `nh`, no larger:++++++/// each new pixel takes the sample that covers more of its area, and the dark one when the two tie++++++/// (1 if `dark_is_one`, see [`dark_is_one`]), so a dark line half a new pixel wide stays. `None`++++++/// when the rows are short or the new size isn't smaller in both directions or empty. Also says++++++/// how many new pixels cover both samples.++++++pub(crate) fn downsample_bits(data: &[u8], w: u32, h: u32, nw: u32, nh: u32, dark_is_one: bool) -> Option<(Vec<u8>, u64)> {++++++ if nw == 0 || nh == 0 || nw > w || nh > h {++++ return None;++++ }-- // Through its parameters given by reference too, as `pixels` reads, and no further than its-- // rows can need.-- let bytes = usize::try_from(w).ok()?.div_ceil(8).checked_mul(usize::try_from(h).ok()?)?;-- let samples = doc.with_direct_parms(s).decoded_within(allowance(bytes, h)?).ok()?;-- let mut new = d.clone();-- for k in [&b"Filter"[..], b"DecodeParms", b"Length", b"DL"] {-- new.remove(k);-- }-- let data = if compression == MonoCompression::Jbig2 {- // One embedded JBIG2 stream with its own page; no /JBIG2Globals.- // One embedded JBIG2 stream with its own page (and symbol dictionary, when the image's- // marks repeat); no /JBIG2Globals.-- new.set(b"Filter".to_vec(), Object::name("JBIG2Decode"));- pdfcraft_filters::encode_jbig2_generic(&samples, w, h).ok()?- pdfcraft_filters::encode_jbig2(&samples, w, h).ok()?++++++ let (stride, nstride) = (usize::try_from(w).ok()?.div_ceil(8), usize::try_from(nw).ok()?.div_ceil(8));++++++ let data = data.get(..stride.checked_mul(usize::try_from(h).ok()?)?)?;++++++ let mut out = vec![0u8; nstride.checked_mul(usize::try_from(nh).ok()?)?];++++++ // In units of 1/nw of a source column, source column x spans [x·nw, (x+1)·nw) and new column i++++++ // spans [i·w, (i+1)·w); rows likewise with h and nh. A new pixel's area is then w·h.++++++ let (w, h, nw, nh) = (u64::from(w), u64::from(h), u64::from(nw), u64::from(nh));++++++ let overlap = |a0: u64, a1: u64, b0: u64, b1: u64| a1.min(b1).saturating_sub(a0.max(b0));++++++ // Per source column, the area its 1 samples cover in the new row.++++++ let mut ones = vec![0u64; usize::try_from(w).ok()?];++++++ let mut mixed = 0u64;++++++ for j in 0..nh {++++++ ones.fill(0);++++++ let (y0, y1) = (j * h, (j + 1) * h);++++++ for y in y0 / nh..y1.div_ceil(nh).min(h) {++++++ let weight = overlap(y0, y1, y * nh, (y + 1) * nh);++++++ let row = data.get(usize::try_from(y).ok()? * stride..)?;++++++ for (x, sum) in ones.iter_mut().enumerate() {++++++ if row.get(x / 8).is_some_and(|b| b & (0x80 >> (x % 8)) != 0) {++++++ *sum += weight;++++++ }++++++ }++++++ }++++++ let out_row = out.get_mut(usize::try_from(j).ok()? * nstride..)?;++++++ for i in 0..nw {++++++ let (x0, x1) = (i * w, (i + 1) * w);++++++ let covered: u64 = (x0 / nw..x1.div_ceil(nw).min(w))++++++ .map(|x| overlap(x0, x1, x * nw, (x + 1) * nw) * usize::try_from(x).ok().and_then(|x| ones.get(x)).copied().unwrap_or(0))++++++ .sum();++++++ // Against what the 0 samples cover: covered is at most w·h, which can't overflow++++++ // (w·h < 2^64 for u32 sizes).++++++ let zeros = w * h - covered;++++++ mixed += u64::from(covered > 0 && zeros > 0);++++++ if covered > zeros || (dark_is_one && covered == zeros) {++++++ let i = usize::try_from(i).ok()?;++++++ *out_row.get_mut(i / 8)? |= 0x80 >> (i % 8);++++++ }++++++ }++++++ }++++++ Some((out, mixed))++++++}++++++++++++/// A black-and-white image (see [`one_bit`]) resampled and stored again per `settings`, if that is++++++/// smaller as stored; `ppi` is its effective resolution, and `defaults` says it is drawn where++++++/// `/DefaultGray` or `/DefaultRGB` is or may be in force. Also says whether it was resampled.++++++///++++++/// - **Resampled** ([`downsample_bits`]) when its resolution is above `above_ppi`, to `target_ppi`,++++++/// unless it has a soft mask, whose own size would then have to follow, or is a halftone or a++++++/// dither: most of its new pixels would cover both black and white, and taking the sample that++++++/// covers more would turn its tones solid (a 50% screen black, a 25% one white).++++++/// - **Stored** as CCITT Group 4 with `CcittG4`, or as 1-bit Flate when that is smaller, which only++++++/// a resampled image or one packed from more bits may be: a 1-bit image that is only stored again++++++/// becomes Group 4 or stays. Group 4 alone is only decoded to be resampled; Group 3 is stored++++++/// again like any other. With `Retain`, a resampled image keeps its kind of compression++++++/// (CCITT, or Flate), and nothing else changes: an image of more bits stays as it is, for the++++++/// grey or colour settings.++++++///++++++/// The samples keep their meaning, so the colour space, decode array and `/Mask` stay, but for++++++/// black-and-white RGB, which becomes grey with one decode pair, and an indexed image's default++++++/// decode array, which goes as the default at one bit.++++++fn mono(doc: &Document, s: &Stream, ppi: f64, defaults: bool, settings: &MonoSettings) -> Option<(Stream, bool)> {++++++ let d = &s.dict;++++++ let downsample = settings.downsample && ppi.is_finite() && ppi > settings.above_ppi && settings.target_ppi > 0.0 && !d.contains(b"SMask");++++++ let retain = settings.compression == MonoCompression::Retain;++++++ let fax = doc.fax_params(s);++++++ // Its kind of compression, which Retain keeps, behind any other filters.++++++ let ccitt = fax.is_some();++++++ // Group 4 alone is only worth decoding to resample it. Group 3, or Group 4 behind++++++ // ASCII85Decode, say, can be smaller stored again as Group 4 alone.++++++ let g4_alone = fax.is_some_and(|p| p.k < 0) && s.filters().len() == 1;- if (retain || g4_alone) && !downsample {+++++++ if (retain || (g4_alone && settings.compression == MonoCompression::CcittG4)) && !downsample {++++++ return None;++++++ }++++++ let (data, w, h, packed) = one_bit(doc, s, !retain, defaults)?;++++++ let packed_from_more = packed.is_some();++++++ let k = settings.target_ppi / ppi;++++++ // `downsample_bits` keeps a counter for each column: no more columns than a fax row may have,++++++ // so a hostile strip of 80 million can't make it 640 MB.++++++ let narrow = w <= pdfcraft_filters::MAX_CCITT_COLUMNS;++++++ // At most `w` × `h`, as k < 1: no overflow.++++++ let (nw, nh) = if downsample && narrow && k < 1.0 {++++++ (((f64::from(w) * k).round() as u32).max(1), ((f64::from(h) * k).round() as u32).max(1))++++++ } else {++++++ (w, h)++++++ };++++++ let averaged = if (nw, nh) != (w, h) {++++++ // The dark sample of the image as it ends up: packed RGB is grey, with grey's decode pair.++++++ let (out, mixed) = downsample_bits(&data, w, h, nw, nh, dark_is_one(doc, packed.as_ref().unwrap_or(d)))?;++++++ // A halftone or dither: most new pixels cover both samples. Text covers both only along++++++ // its edges.++++++ (mixed.saturating_mul(2) <= u64::from(nw) * u64::from(nh)).then_some(out)++++++ } else {++++++ None++++++ };++++++ let resampled = averaged.is_some();++++++ let (data, nw, nh) = match averaged {++++++ Some(out) => (out, nw, nh),++++++ None => (data, w, h),++++++ };- if (retain || g4_alone) && !resampled {+++++++ if (retain || (g4_alone && settings.compression == MonoCompression::CcittG4)) && !resampled {++++++ return None;++++++ }++++++ let mut dict = packed.unwrap_or_else(|| d.clone());++++++ for key in [&b"Filter"[..], b"DecodeParms", b"Length", b"DL"] {++++++ dict.remove(key);++++++ }++++++ dict.set(b"Width".to_vec(), Object::Int(i64::from(nw)));++++++ dict.set(b"Height".to_vec(), Object::Int(i64::from(nh)));++++++ let g4 = if settings.compression == MonoCompression::CcittG4 || (retain && ccitt) {++++++ pdfcraft_filters::encode_g4(&data, nw, nh).ok().map(|coded| {++++++ let mut dict = dict.clone();++++++ let mut parms = Dict::new();++++++ parms.set(b"K".to_vec(), Object::Int(-1));++++++ parms.set(b"Columns".to_vec(), Object::Int(i64::from(nw)));++++++ parms.set(b"Rows".to_vec(), Object::Int(i64::from(nh)));++++++ dict.set(b"Filter".to_vec(), Object::name("CCITTFaxDecode"));++++++ dict.set(b"DecodeParms".to_vec(), Object::Dict(parms));++++++ Stream::from_raw(dict, coded)++++++ })++++ } else {-- let mut parms = Dict::new();-- parms.set(b"K".to_vec(), Object::Int(-1));-- parms.set(b"Columns".to_vec(), Object::Int(i64::from(w)));-- parms.set(b"Rows".to_vec(), Object::Int(i64::from(h)));-- new.set(b"Filter".to_vec(), Object::name("CCITTFaxDecode"));-- new.set(b"DecodeParms".to_vec(), Object::Dict(parms));-- pdfcraft_filters::encode_g4(&samples, w, h).ok()?++++++ None++++ };-- let new = Stream::from_raw(new, data);-- // Smaller as stored, counting the larger dictionary: a tiny image can lose by it.-- (crate::stored_len(&new)? < crate::stored_len(s)?).then_some(new)+++++++ let jbig = if settings.compression == MonoCompression::Jbig2 {+++++++ pdfcraft_filters::encode_jbig2(&data, nw, nh).ok().map(|coded| {+++++++ let mut dict = dict.clone();+++++++ dict.set(b"Filter".to_vec(), Object::name("JBIG2Decode"));+++++++ Stream::from_raw(dict, coded)+++++++ })+++++++ } else {+++++++ None+++++++ };++++++ let flate = ((resampled || packed_from_more) && !(retain && ccitt)).then(|| Stream::flate(dict, &data));++++++ // Smaller as stored, counting the dictionary: a tiny image can lose by Group 4's parameters.- let best = [g4, flate].into_iter().flatten().filter_map(|c| Some((crate::stored_len(&c)?, c))).min_by_key(|(len, _)| *len)?;+++++++ let best = [g4, jbig, flate].into_iter().flatten().filter_map(|c| Some((crate::stored_len(&c)?, c))).min_by_key(|(len, _)| *len)?;++++++ (best.0 < crate::stored_len(s)?).then_some((best.1, resampled))++++ }++++pub(crate) fn run(doc: &mut Document,pages: &[ObjRef],@@@@@@@@ -1099,51 -558,9 -558,9 -558,9 -558,9 -640,17 -641,17 +1109,53 @@@@@@@@let obj = doc.get(r);let Object::Stream(s) = &*obj else { continue };report.images += 1;---- let Some(n) = s.dict.get(b"ColorSpace").and_then(|cs| components(doc, cs)) else { continue };---- let st = if n == 1 { &settings.gray } else { &settings.color };---- let Some((new, smask)) = process(doc, s, ppi, st, n) else { continue };-- if let Some(new) = mono(doc, s, settings.mono) {++++++ // Packed from more bits a sample, it is lossless at one bit, but the grey or colour++++++ // settings can make it smaller still (below).++++++ let packed_from_more = s.dict.int(b"BitsPerComponent").is_some_and(|b| b > 1);++++++ let (packed, mono) = match mono(doc, s, ppi, defaults.contains(&r.num), &settings.mono) {++++++ Some(m) if packed_from_more => (Some(m), None),++++++ m => (None, m),++++++ };++++++ if let Some((new, resampled)) = mono {++++ report.image_bytes_before += s.raw.len();++++ report.image_bytes_after += new.raw.len();-- report.images_recompressed += 1;++++++ if resampled {++++++ report.images_resampled += 1;++++++ } else {++++++ report.images_recompressed += 1;++++++ }+++++ jbig2 |= new.dict.name(b"Filter") == Some(b"JBIG2Decode");++++ doc.set(r, Object::Stream(new));++++ continue;++++ }-- let Some(n) = s.dict.get(b"ColorSpace").and_then(|cs| components(doc, cs)) else { continue };-- let st = if n == 1 { &settings.gray } else { &settings.color };-- let Some((new, smask)) = process(doc, s, ppi, st, n) else { continue };++++++ let n = s.dict.get(b"ColorSpace").and_then(|cs| components(doc, cs));++++++ let processed = n.and_then(|n| process(doc, s, ppi, if n == 1 { &settings.gray } else { &settings.color }, n));++++++ // A dithered scan, say, downsampled and JPEG-compressed: the smaller wins, counting a soft++++++ // mask resampled with it.++++++ let smask_len = |smask: Option<&(ObjRef, Stream)>| match smask {++++++ Some((_, m)) => Some(m.raw.len()),++++++ None => s.dict.reference(b"SMask").map(|m| match &*doc.get(m) {++++++ Object::Stream(m) => m.raw.len(),++++++ _ => 0,++++++ }),++++++ };++++++ let total = |new: &Stream, smask: Option<&(ObjRef, Stream)>| Some(crate::stored_len(new)?.saturating_add(smask_len(smask).unwrap_or(0)));++++++ let packed_wins = packed.as_ref().is_some_and(|(p, _)| {++++++ processed.as_ref().is_none_or(|(new, smask)| total(p, None).zip(total(new, smask.as_ref())).is_some_and(|(a, b)| a <= b))++++++ });++++++ if let Some((new, resampled)) = packed.filter(|_| packed_wins) {+++++++ jbig2 |= new.dict.name(b"Filter") == Some(b"JBIG2Decode");++++++ report.image_bytes_before += s.raw.len();++++++ report.image_bytes_after += new.raw.len();++++++ if resampled {++++++ report.images_resampled += 1;++++++ } else {++++++ report.images_recompressed += 1;++++++ }++++++ doc.set(r, Object::Stream(new));++++++ continue;++++++ }++++++ let Some((new, smask)) = processed else { continue };let resized = new.dict.int(b"Width") != s.dict.int(b"Width") || new.dict.int(b"Height") != s.dict.int(b"Height");report.image_bytes_before += s.raw.len();report.image_bytes_after += new.raw.len();diff --cc crates/optimize/src/lib.rsindex 3a920d1f1,9f9fcdf2b,9f9fcdf2b,9f9fcdf2b,9f9fcdf2b,09c487989,7ef159d22..76e30da7a--- a/crates/optimize/src/lib.rs+++ b/crates/optimize/src/lib.rs@@@@@@@@ -7,14 -7,10 -7,10 -7,10 -7,10 -7,11 -7,11 +7,14 @@@@@@@@//! - **Images:** each image's effective resolution is measured where pages draw it (the//! smallest over its uses, through form XObjects); colour and grayscale images above a//! threshold are resampled (bicubic) to a target resolution and recompressed as JPEG or Flate.------//! A new image replaces the old one only if it is smaller. Images PdfCraft can't decode------//! faithfully (CMYK and other colour spaces, masks, decode arrays other than the default,------//! JPEG 2000, JBIG2, CCITT, other than 8 bits, JPEGs whose Adobe marker and `/ColorTransform`---- //! disagree) are left alone.--//! disagree) are left alone. Black-and-white (1-bit) images are stored again as CCITT Group 4--//! or JBIG2, losslessly, when that is smaller.++++++//! A new image replaces the old one only if it is smaller. The colour and grey settings leave++++++//! alone images they can't decode faithfully (CMYK and other colour spaces, masks, decode arrays++++++//! other than the default, JPEG 2000, JBIG2, CCITT, other than 8 bits, JPEGs whose Adobe marker++++++//! and `/ColorTransform` disagree). Black-and-white images (1-bit, image masks and CCITT fax,++++++//! Group 3 among them; and eight-bit grey and RGB of only black and white, and indexed images++++++//! that use only palette entries 0 and 1, packed to one bit) above a threshold are averaged down to a- //! target resolution, halftones and dithers aside, and are stored as CCITT Group 4, or 1-bit+++++++//! target resolution, halftones and dithers aside, and are stored as CCITT Group 4 or lossless JBIG2, or 1-bit++++++//! Flate once resampled or packed, when that is smaller.//! - **Discard objects:** page thumbnails, alternate images, document tags (structure tree),//! print settings.//! - **Clean up:** drop images and forms that pages list but never draw (such as a deleted@@@@@@@@ -122,33 -118,6 -118,6 -118,6 -118,6 -119,18 -119,19 +122,37 @@@@@@@@ pub enum CompressionRetain,}++++ /// How black-and-white (1-bit) images are stored.++++ #[derive(Clone, Copy, Debug, PartialEq, Eq)]++++ pub enum MonoCompression {++++ /// CCITT Group 4 (lossless), when smaller than the image as it is.++++ CcittG4,- /// JBIG2, lossless (a generic region), when smaller than the image as it is. JBIG2Decode is- /// PDF 1.4: an older document gets `/Version /1.4` in its catalog.++++++ /// JBIG2, lossless (a generic region, or symbols when the image's marks repeat), when smaller++++++ /// than the image as it is. JBIG2Decode is PDF 1.4: an older document gets `/Version /1.4` in++++++ /// its catalog.+++++ Jbig2,++++ /// Keep each image's own compression.++++ Retain,++++ }++++++++++/// How black-and-white images (1-bit, CCITT fax among them; and eight-bit grey and RGB of only black++++++/// and white, and indexed images that use only palette entries 0 and 1, packed to one bit), and++++++/// image masks, are resampled and stored.++++++#[derive(Clone, Copy, Debug, PartialEq)]++++++pub struct MonoSettings {++++++ /// Average images whose effective resolution is above `above_ppi` down to `target_ppi`.++++++ pub downsample: bool,++++++ pub target_ppi: f64,++++++ pub above_ppi: f64,++++++ pub compression: MonoCompression,++++++}++++++++++++impl MonoSettings {++++++ /// Reduce File Size and the presets: to 300 ppi above 450 ppi, CCITT Group 4. Text in a scan++++++ /// stays sharp at 300 ppi.++++++ pub const REDUCE: MonoSettings = MonoSettings { downsample: true, target_ppi: 300.0, above_ppi: 450.0, compression: MonoCompression::CcittG4 };++++++}++++++/// Acrobat's JPEG quality steps.pub const QUALITIES: [(&str, u8); 5] = [("Minimum", 25), ("Low", 45), ("Medium", 60), ("High", 80), ("Maximum", 95)];@@@@@@@@ -178,8 -147,6 -147,6 -147,6 -147,6 -160,8 -161,8 +182,8 @@@@@@@@ pub struct Settingspub merge_fragments: bool,pub color: ImageSettings,pub gray: ImageSettings,-- /// Black-and-white (1-bit) images, and image masks.-- pub mono: MonoCompression,++++++ /// Black-and-white images, and image masks.++++++ pub mono: MonoSettings,pub discard_thumbnails: bool,pub discard_alternate_images: bool,pub discard_tags: bool,@@@@@@@@ -214,7 -181,6 -181,6 -181,6 -181,6 -196,7 -197,7 +218,7 @@@@@@@@ impl Default for Settingsmerge_fragments: true,color: ImageSettings::REDUCE,gray: ImageSettings::REDUCE,-- mono: MonoCompression::CcittG4,++++++ mono: MonoSettings::REDUCE,discard_thumbnails: true,discard_alternate_images: true,discard_tags: false,diff --cc crates/optimize/tests/optimize.rsindex d8fe601a3,3e69e27cb,3e69e27cb,3e69e27cb,3e69e27cb,9a0990286,f8e28506a..3e8b5b9b1--- a/crates/optimize/tests/optimize.rs+++ b/crates/optimize/tests/optimize.rs@@@@@@@@ -5,8 -5,7 -5,7 -5,7 -5,7 -5,7 -5,7 +5,8 @@@@@@@@ use std::sync::Arcuse pdfcraft_cos::{Dict, Document, ObjRef, Object, SaveOptions, Stream, write_full};use pdfcraft_filters::{Filter, Params};use pdfcraft_optimize::{---- Compatibility, Compression, ImageSettings, OptimizeError, Settings, SpaceCategory, audit_space, effective_resolutions, optimize,-- Compatibility, Compression, ImageSettings, MonoCompression, OptimizeError, Settings, SpaceCategory, audit_space, effective_resolutions, optimize,++++++ Compatibility, Compression, ImageSettings, MonoCompression, MonoSettings, OptimizeError, Settings, SpaceCategory, audit_space,++++++ effective_resolutions, optimize,};fn image(doc: &mut Document, w: u32, h: u32, n: usize, jpeg: bool, smask: Option<ObjRef>) -> ObjRef {@@@@@@@@ -219,1698 -218,6 -218,6 -218,6 -218,6 -218,462 -218,551 +219,1882 @@@@@@@@ fn an_identity_decode_array_does_not_stassert_eq!(stream(&doc, odd).dict.int(b"Width"), Some(900));}++++ /// Rows of `w` 1-bit samples (1 white, 0 black), each starting on a byte: lines of text-like++++ /// glyphs; or, with `noise`, random bits.++++ fn bilevel(w: u32, h: u32, noise: bool) -> Vec<u8> {++++ let stride = (w as usize).div_ceil(8);++++ let mut data = vec![0xFF; stride * h as usize];++++ let mut seed = 0x9E37_79B9_7F4A_7C15u64;++++ let mut next = move || {++++ seed ^= seed << 13;++++ seed ^= seed >> 7;++++ seed ^= seed << 17;++++ seed++++ };++++ let mut black = |x: usize, y: usize| {++++ if x < w as usize && y < h as usize {++++ data[y * stride + x / 8] &= !(0x80 >> (x % 8));++++ }++++ };++++ if noise {++++ for y in 0..h as usize {++++ for x in 0..w as usize {++++ if next() & 1 == 0 {++++ black(x, y);++++ }++++ }++++ }++++ return data;++++ }++++ // Lines 24 rows apart, of glyphs drawn from a few shapes (a stem, a bowl, an arch, a dotted++++ // stem) at any column, 1–3 columns apart with a wider gap between words: text as a scanner++++ // sees it. Clean, identical rows would favour Flate; a scan's ragged edges favour Group 4.++++ for line in (4..h as usize).step_by(24) {++++ let mut x = 8;++++ while x + 16 < w as usize {++++ let wide = 5 + (next() % 4) as usize;++++ let shape = next() % 4;++++ // Now and then a row of a stroke is a column wider or narrower at an edge, as a scan's++++ // edges are.++++ let mut ragged = || match next() % 8 {++++ 0 => 0,++++ 1 => 2,++++ _ => 1,++++ };++++ let mut fill = |x0: usize, x1: usize, y0: usize, y1: usize| {++++ for y in line + y0..line + y1 {++++ let (left, right) = ((x + x0 + 1).saturating_sub(ragged()), x + x1 + ragged());++++ for xx in left..right.saturating_sub(1) {++++ black(xx, y);++++ }++++ }++++ };++++ match shape {++++ 0 => fill(0, 2, 0, 14),++++ 1 => {++++ fill(0, wide, 4, 6);++++ fill(0, wide, 12, 14);++++ fill(0, 2, 4, 14);++++ fill(wide - 2, wide, 4, 14);++++ }++++ 2 => {++++ fill(0, 2, 4, 14);++++ fill(wide - 2, wide, 6, 14);++++ fill(0, wide - 1, 4, 6);++++ }++++ _ => {++++ fill(0, 2, 7, 14);++++ fill(0, 2, 2, 4);++++ }++++ }++++ x += wide + 2 + (next() % 2) as usize + if next() % 6 == 0 { 7 } else { 0 };++++ }++++ }++++ data++++ }++++++++ /// A 1-bit image of `data`, Flate-compressed (with `predictor`, a PNG predictor, if any), with++++ /// `entries` added to its dictionary.++++ fn mono_image(doc: &mut Document, w: u32, h: u32, data: &[u8], predictor: Option<i64>, entries: &[(&str, Object)]) -> ObjRef {++++ let mut d = Dict::new();++++ d.set(b"Type".to_vec(), Object::name("XObject"));++++ d.set(b"Subtype".to_vec(), Object::name("Image"));++++ d.set(b"Width".to_vec(), Object::Int(w as i64));++++ d.set(b"Height".to_vec(), Object::Int(h as i64));++++ for (k, v) in entries {++++ d.set(k.as_bytes().to_vec(), v.clone());++++ }++++ let s = match predictor {++++ None => Stream::flate(d, data),++++ Some(predictor) => {++++ let params = pdfcraft_filters::Params { predictor, colors: 1, bits_per_component: 1, columns: w as i64, early_change: 1 };++++ let mut parms = Dict::new();++++ parms.set(b"Predictor".to_vec(), Object::Int(predictor));++++ parms.set(b"BitsPerComponent".to_vec(), Object::Int(1));++++ parms.set(b"Columns".to_vec(), Object::Int(w as i64));++++ d.set(b"Filter".to_vec(), Object::name("FlateDecode"));++++ d.set(b"DecodeParms".to_vec(), Object::Dict(parms));++++ Stream::from_raw(d, pdfcraft_filters::encode(&pdfcraft_filters::Filter::Flate, ¶ms, data).unwrap())++++ }++++ };++++ doc.add(Object::Stream(s))++++ }++++++++ fn render(doc: &Document) -> Vec<u8> {++++ let bytes = write_full(doc, &SaveOptions::default()).unwrap();++++ let mut r = pdfcraft_render::PageRenderer::new(Arc::new(bytes), pdfcraft_render::RenderConfig::default());++++ let out = r.render(pdfcraft_render::RenderRequest { page: 0, scale: 1.0, ..Default::default() });++++ assert!(out.error.is_none(), "{:?}", out.error);++++ out.rgba.to_vec()++++ }++++++++ /// Black-and-white images become CCITT Group 4, losslessly: the page looks the same to the pixel.++++ /// Grey, an image mask (with a decode array that inverts it), an indexed image of two colours and++++ /// one stored with a PNG predictor qualify; noise (bigger as G4), a 1-bit RGB image, one whose++++ /// colour space is a resource name, one wider than Group 4 encodes and a tiny one (bigger as++++ /// stored) are left alone, as is everything with `mono: Retain`.++++ #[test]++++ fn black_and_white_images_become_ccitt_group_4() {++++ let mut doc = Document::new_empty();++++ let (w, h) = (1200, 480);++++ let text = bilevel(w, h, false);++++ let gray = mono_image(&mut doc, w, h, &text, None, &[("BitsPerComponent", 1.into()), ("ColorSpace", Object::name("DeviceGray"))]);++++ let decode = Object::Array(vec![1.into(), 0.into()]);++++ let mask = mono_image(&mut doc, w, h, &text, None, &[("ImageMask", Object::Bool(true)), ("Decode", decode.clone())]);++++ let indexed_cs = Object::Array(vec![++++ Object::name("Indexed"),++++ Object::name("DeviceRGB"),++++ 1.into(),++++ Object::String(pdfcraft_cos::PdfString::literal(vec![0xC0, 0x10, 0x10, 0xF8, 0xF0, 0xE0])),++++ ]);++++ let indexed = mono_image(&mut doc, w, h, &text, None, &[("BitsPerComponent", 1.into()), ("ColorSpace", indexed_cs.clone())]);++++ let predicted = mono_image(&mut doc, w, h, &text, Some(15), &[("BitsPerComponent", 1.into()), ("ColorSpace", Object::name("DeviceGray"))]);++++ let noise =++++ mono_image(&mut doc, 400, 200, &bilevel(400, 200, true), None, &[("BitsPerComponent", 1.into()), ("ColorSpace", Object::name("DeviceGray"))]);++++ let rgb = mono_image(++++ &mut doc,++++ 400,++++ 160,++++ &bilevel(1200, 160, false),++++ None,++++ &[("BitsPerComponent", 1.into()), ("ColorSpace", Object::name("DeviceRGB"))],++++ );++++ let wide = mono_image(++++ &mut doc,++++ 40_000,++++ 2,++++ &bilevel(40_000, 2, false),++++ None,++++ &[("BitsPerComponent", 1.into()), ("ColorSpace", Object::name("DeviceGray"))],++++ );++++ // A bare /Indexed is no colour space on its own: it names the page's resource, here RGB, so++++ // these samples are three to a pixel.++++ let named =++++ mono_image(&mut doc, 400, 160, &bilevel(1200, 160, false), None, &[("BitsPerComponent", 1.into()), ("ColorSpace", Object::name("Indexed"))]);++++ // 64 × 8 white: its Group 4 data is smaller than its Flate data, but not by the longer++++ // dictionary Group 4 needs.++++ let tiny = mono_image(&mut doc, 64, 8, &[0xFF; 64], None, &[("BitsPerComponent", 1.into()), ("ColorSpace", Object::name("DeviceGray"))]);++++ let tiny_g4 = pdfcraft_filters::encode_g4(&[0xFF; 64], 64, 8).unwrap();++++ assert!(tiny_g4.len() < stream(&doc, tiny).raw.len(), "{} against {}", tiny_g4.len(), stream(&doc, tiny).raw.len());++++ let p = page(++++ &mut doc,++++ &[("G", gray), ("M", mask), ("I", indexed), ("P", predicted), ("N", noise), ("R", rgb), ("W", wide), ("T", tiny), ("X", named)],++++ "q 300 0 0 120 20 660 cm /G Do Q q 0 0.4 0.8 rg 300 0 0 120 320 660 cm /M Do Q q 300 0 0 120 20 520 cm /I Do Q \++++ q 300 0 0 120 320 520 cm /P Do Q q 200 0 0 100 20 400 cm /N Do Q q 200 0 0 80 240 400 cm /R Do Q q 560 0 0 4 20 380 cm /W Do Q q 64 0 0 8 460 400 cm /T Do Q q 200 0 0 80 240 300 cm /X Do Q",++++ );++++ doc.update_dict(p, |d| {++++ if let Some(Object::Dict(res)) = d.get_mut(b"Resources") {++++ let mut cs = Dict::new();++++ cs.set(b"Indexed".to_vec(), Object::name("DeviceRGB"));++++ res.set(b"ColorSpace".to_vec(), Object::Dict(cs));++++ }++++ })++++ .unwrap();++++ let before = render(&doc);++++ let raw = |doc: &Document, r: ObjRef| stream(doc, r).raw;++++ let untouched = [noise, rgb, wide, tiny, named].map(|r| raw(&doc, r));++++++++ let mut kept = doc.clone();-- let r = optimize(&mut kept, &Settings { mono: MonoCompression::Retain, ..Settings::default() }).unwrap();++++++ let r = optimize(&mut kept, &Settings { mono: RETAIN, ..Settings::default() }).unwrap();++++ assert_eq!(r.images_recompressed, 0, "Retain keeps every image as it is");++++ assert!([gray, mask, indexed, predicted].iter().all(|i| raw(&kept, *i) == raw(&doc, *i)));++++++++ let r = optimize(&mut doc, &Settings::default()).unwrap();++++ assert_eq!(r.images_recompressed, 4);++++ assert!(r.image_bytes_after < r.image_bytes_before, "{} → {}", r.image_bytes_before, r.image_bytes_after);++++ for i in [gray, mask, indexed, predicted] {++++ let s = stream(&doc, i);++++ assert_eq!(s.dict.name(b"Filter"), Some(&b"CCITTFaxDecode"[..]));++++ let parms = s.dict.get(b"DecodeParms").and_then(Object::as_dict).cloned().unwrap();++++ assert_eq!((parms.int(b"K"), parms.int(b"Columns"), parms.int(b"Rows")), (Some(-1), Some(w as i64), Some(h as i64)));++++ }++++ assert_eq!(stream(&doc, mask).dict.get(b"Decode"), Some(&decode), "the decode array stays");++++ assert_eq!(stream(&doc, indexed).dict.get(b"ColorSpace"), Some(&indexed_cs), "the colour space stays");++++ assert_eq!([noise, rgb, wide, tiny, named].map(|r| raw(&doc, r)), untouched);++++ assert!(render(&doc) == before, "the page looks the same");++++ }++++++++ /// Which 1-bit images qualify for Group 4: those of one colour component, an ICC profile of one++++ /// component and a DeviceN of one colourant among them, but not one of three components or two++++ /// colourants (more than a bit a pixel); image masks of one bit, as `/BitsPerComponent 1` says or++++ /// by default, but not one that says 8; and images of up to 80 million pixels, not one row more.++++ /// The byte totals count exactly the images stored again.++++ #[test]++++ fn group_4_takes_images_of_one_bit_a_pixel_up_to_the_pixel_limit() {++++ let mut doc = Document::new_empty();++++ let (w, h) = (1200u32, 480u32);++++ let text = bilevel(w, h, false);++++ let icc = |doc: &mut Document, n: i64| {++++ let mut d = Dict::new();++++ d.set(b"N".to_vec(), Object::Int(n));++++ Object::Array(vec![Object::name("ICCBased"), Object::Ref(doc.add(Object::Stream(Stream::from_raw(d, Vec::new()))))])++++ };++++ let device_n = |colourants: &[&str]| {++++ let mut tint = Dict::new();++++ tint.set(b"FunctionType".to_vec(), Object::Int(2));++++ tint.set(b"Domain".to_vec(), Object::Array(vec![0.into(), 1.into()]));++++ tint.set(b"N".to_vec(), Object::Int(1));++++ Object::Array(vec![++++ Object::name("DeviceN"),++++ Object::Array(colourants.iter().map(|c| Object::name(c)).collect()),++++ Object::name("DeviceGray"),++++ Object::Dict(tint),++++ ])++++ };++++ let one_bit = |cs: Object| [("BitsPerComponent", 1.into()), ("ColorSpace", cs)];++++ let icc_1 = icc(&mut doc, 1);++++ let icc_1 = mono_image(&mut doc, w, h, &text, None, &one_bit(icc_1));++++ let icc_3 = icc(&mut doc, 3);++++ let icc_3 = mono_image(&mut doc, w, h, &bilevel(3 * w, h, false), None, &one_bit(icc_3));++++ let spot = mono_image(&mut doc, w, h, &text, None, &one_bit(device_n(&["Spot"])));++++ let two_spots = mono_image(&mut doc, w, h, &bilevel(2 * w, h, false), None, &one_bit(device_n(&["Spot", "Other"])));++++ let mask = |bits: i64| [("ImageMask", Object::Bool(true)), ("BitsPerComponent", bits.into())];++++ let mask_1 = mono_image(&mut doc, w, h, &text, None, &mask(1));++++ let mask_8 = mono_image(&mut doc, w, h, &bilevel(8 * w, h, false), None, &mask(8));++++ // 10,000 × 8,000 is the limit itself.++++ let grey = one_bit(Object::name("DeviceGray"));++++ let at_limit = mono_image(&mut doc, 10_000, 8_000, &bilevel(10_000, 8_000, false), None, &grey);++++ let past_limit = mono_image(&mut doc, 10_000, 8_001, &bilevel(10_000, 8_001, false), None, &grey);++++ let all = [icc_1, icc_3, spot, two_spots, mask_1, mask_8, at_limit, past_limit];++++ let names: Vec<String> = (0..all.len()).map(|i| format!("Im{i}")).collect();-- let content: String = (0..all.len()).map(|i| format!("q 200 0 0 80 {} {} cm /Im{i} Do Q ", 6 + 200 * (i % 3), 690 - 100 * (i / 3))).collect();++++++ // 200 × 80 pt is 432 ppi, 1800 × 1440 pt 400 ppi: below where monochrome downsampling starts.++++++ let content: String = (0..all.len())++++++ .map(|i| {++++++ if i < 6 {++++++ format!("q 200 0 0 80 {} {} cm /Im{i} Do Q ", 6 + 200 * (i % 3), 690 - 100 * (i / 3))++++++ } else {++++++ format!("q 1800 0 0 1440 0 0 cm /Im{i} Do Q ")++++++ }++++++ })++++++ .collect();++++ page(&mut doc, &names.iter().map(String::as_str).zip(all).collect::<Vec<_>>(), &content);++++ let converted = [icc_1, spot, mask_1, at_limit];++++ let left = [icc_3, two_spots, mask_8, past_limit];++++ let before = |doc: &Document, refs: &[ObjRef]| refs.iter().map(|r| stream(doc, *r).raw).collect::<Vec<_>>();++++ let (old, untouched) = (before(&doc, &converted), before(&doc, &left));++++ let r = optimize(&mut doc, &Settings::default()).unwrap();++++ assert_eq!(r.images_recompressed, converted.len(), "{r:?}");++++ for i in converted {++++ assert_eq!(stream(&doc, i).dict.name(b"Filter"), Some(&b"CCITTFaxDecode"[..]), "{i:?}");++++ }++++ assert_eq!(before(&doc, &left), untouched);++++ let new = before(&doc, &converted);++++ assert_eq!((r.image_bytes_before, r.image_bytes_after), (old.iter().map(|b| b.len()).sum(), new.iter().map(|b| b.len()).sum()));++++ }++++++++ /// An image whose /DecodeParms are a reference, or hold numbers given by reference++++ /// (`/Predictor 9 0 R`, which `Dict::int` doesn't follow), is read through them, as one with them++++ /// direct: a predictor's tag bytes would otherwise shift every row, and the image would be stored--/// again wrong. Here a 1-bit image with a PNG predictor (stored again as Group 4) and an eight-bit--/// grey one with a PNG predictor at 600 ppi (resampled) come out byte for byte as with direct--/// parameters.++++++/// again wrong. Here a 1-bit image with a PNG predictor (stored again as Group 4), an eight-bit++++++/// grey one with a PNG predictor at 600 ppi (resampled), an eight-bit one of only black and white++++++/// with PNG predictor 10 (each row's tag a 0, so the shifted rows would still be black and white;++++++/// packed to one bit), and a two-entry indexed one the same way come out byte for byte as with++++++/// direct parameters.++++ #[test]++++ fn images_whose_decode_parms_are_references_come_out_as_with_them_direct() {++++ let build = |how: &str| {++++ let mut doc = Document::new_empty();++++ let (w, h) = (1200u32, 480u32);++++ let grey = [("BitsPerComponent", 1.into()), ("ColorSpace", Object::name("DeviceGray"))];++++ let one_bit = mono_image(&mut doc, w, h, &bilevel(w, h, false), Some(15), &grey);++++++ let black_and_white_samples = eight_bit(&bilevel(w, h, false), w, h);++++ let shades: Vec<u8> = (0..w * h).map(|i| ((i % w) * 255 / w) as u8 ^ ((i / w) as u8 & 0x0F)).collect();++++ let params = pdfcraft_filters::Params { predictor: 15, colors: 1, bits_per_component: 8, columns: w as i64, early_change: 1 };++++ let mut parms = Dict::new();++++ parms.set(b"Predictor".to_vec(), Object::Int(15));++++ parms.set(b"Columns".to_vec(), Object::Int(w as i64));++++ let mut d = Dict::new();++++ d.set(b"Type".to_vec(), Object::name("XObject"));++++ d.set(b"Subtype".to_vec(), Object::name("Image"));++++ d.set(b"Width".to_vec(), Object::Int(w as i64));++++ d.set(b"Height".to_vec(), Object::Int(h as i64));++++ d.set(b"BitsPerComponent".to_vec(), Object::Int(8));++++ d.set(b"ColorSpace".to_vec(), Object::name("DeviceGray"));++++ d.set(b"Filter".to_vec(), Object::name("FlateDecode"));++++ d.set(b"DecodeParms".to_vec(), Object::Dict(parms));++++ let coded = pdfcraft_filters::encode(&pdfcraft_filters::Filter::Flate, ¶ms, &shades).unwrap();-- let eight_bit = doc.add(Object::Stream(Stream::from_raw(d, coded)));-- for r in [one_bit, eight_bit] {++++++ let eight_bit = doc.add(Object::Stream(Stream::from_raw(d.clone(), coded)));++++++ let params = pdfcraft_filters::Params { predictor: 10, ..params };++++++ let mut parms = Dict::new();++++++ parms.set(b"Predictor".to_vec(), Object::Int(10));++++++ parms.set(b"Columns".to_vec(), Object::Int(w as i64));++++++ d.set(b"DecodeParms".to_vec(), Object::Dict(parms));++++++ let black_and_white = pdfcraft_filters::encode(&pdfcraft_filters::Filter::Flate, ¶ms, &black_and_white_samples).unwrap();++++++ let packed = doc.add(Object::Stream(Stream::from_raw(d.clone(), black_and_white)));++++++ let palette = vec![0, 0, 255, 255, 255, 255];++++++ d.set(++++++ b"ColorSpace".to_vec(),++++++ Object::Array(vec![++++++ Object::name("Indexed"),++++++ Object::name("DeviceRGB"),++++++ 1.into(),++++++ Object::String(pdfcraft_cos::PdfString::literal(palette)),++++++ ]),++++++ );++++++ let entries = samples_of(&bilevel(w, h, false), w, h, [&[0], &[1]], 8);++++++ let entries = pdfcraft_filters::encode(&pdfcraft_filters::Filter::Flate, ¶ms, &entries).unwrap();++++++ let indexed = doc.add(Object::Stream(Stream::from_raw(d, entries)));++++++ for r in [one_bit, eight_bit, packed, indexed] {++++ let mut s = stream(&doc, r);++++ let Some(Object::Dict(mut parms)) = s.dict.get(b"DecodeParms").cloned() else { panic!("{:?}", s.dict) };++++ let made = match how {++++ "whole" => Object::Ref(doc.add(Object::Dict(parms))),++++ "numbers" => {++++ for k in [&b"Predictor"[..], b"Columns"] {++++ let v = parms.get(k).cloned().unwrap();++++ parms.set(k.to_vec(), Object::Ref(doc.add(v)));++++ }++++ Object::Dict(parms)++++ }++++ _ => continue,++++ };++++ s.dict.set(b"DecodeParms".to_vec(), made);++++ doc.set(r, Object::Stream(s));++++ }++++ // 300 × 120 pt is 288 ppi; 144 × 57.6 pt is 600 ppi.-- page(&mut doc, &[("A", one_bit), ("B", eight_bit)], "q 300 0 0 120 20 600 cm /A Do Q q 144 0 0 57.6 20 400 cm /B Do Q");-- let before = [one_bit, eight_bit].map(|r| stream(&doc, r).raw);++++++ page(++++++ &mut doc,++++++ &[("A", one_bit), ("B", eight_bit), ("C", packed), ("D", indexed)],++++++ "q 300 0 0 120 20 600 cm /A Do Q q 144 0 0 57.6 20 400 cm /B Do Q q 300 0 0 120 20 200 cm /C Do Q \++++++ q 280 0 0 112 325 200 cm /D Do Q",++++++ );++++++ let before = [one_bit, eight_bit, packed, indexed].map(|r| stream(&doc, r).raw);++++ let r = optimize(&mut doc, &Settings::default()).unwrap();-- assert_eq!((r.images_resampled, r.images_recompressed), (1, 1), "{r:?}");-- let after = [one_bit, eight_bit].map(|r| stream(&doc, r));-- assert!(before.iter().zip(&after).all(|(b, a)| *b != a.raw), "both stored again");++++++ assert_eq!((r.images_resampled, r.images_recompressed), (1, 3), "{r:?}");++++++ let after = [one_bit, eight_bit, packed, indexed].map(|r| stream(&doc, r));++++++ assert!(before.iter().zip(&after).all(|(b, a)| *b != a.raw), "all stored again");++++ assert_eq!(after[0].dict.name(b"Filter"), Some(&b"CCITTFaxDecode"[..]));++++++ for s in &after[2..] {++++++ assert_eq!((s.dict.int(b"BitsPerComponent"), s.dict.name(b"Filter")), (Some(1), Some(&b"CCITTFaxDecode"[..])));++++++ }++++ after.map(|s| s.raw)++++ };++++ let direct = build("direct");++++ assert_eq!(build("whole"), direct, "the dictionary by reference");++++ assert_eq!(build("numbers"), direct, "the numbers inside by reference");++++ }++++++++ /// An image whose data decodes far past what its samples can need (a decompression bomb) is left--/// alone rather than decoded up to the 1 GiB limit: a 1-bit one that would become Group 4, and an--/// eight-bit one that would be resampled, each with four megabytes of zeros after its samples. Stored--/// as ASCIIHex text under Flate, broken into lines of 64 digits, their samples aren't a bomb.++++++/// alone rather than decoded up to the 1 GiB limit: a 1-bit one that would become Group 4, an++++++/// eight-bit one that would be resampled, and an eight-bit one of only black and white that would++++++/// be packed to one bit, each with four megabytes of zeros after its samples. Stored as ASCIIHex++++++/// text under Flate, broken into lines of 64 digits, their samples aren't a bomb.++++ #[test]++++ fn images_whose_data_decodes_far_past_their_samples_are_left_alone() {++++ let (w, h) = (1200u32, 480u32);++++ let text = bilevel(w, h, false);++++ let shades: Vec<u8> = (0..w * h).map(|i| ((i % w) * 255 / w) as u8 ^ ((i / w) as u8 & 0x0F)).collect();++++ for padding in [0, 4 << 20] {++++ let mut doc = Document::new_empty();++++ let padded = |data: &[u8]| data.iter().copied().chain(std::iter::repeat_n(0, padding)).collect::<Vec<u8>>();++++ let grey = |bits: i64| [("BitsPerComponent", bits.into()), ("ColorSpace", Object::name("DeviceGray"))];++++ let one_bit = mono_image(&mut doc, w, h, &padded(&text), None, &grey(1));++++ let eight_bit = mono_image(&mut doc, w, h, &padded(&shades), None, &grey(8));++++++ let packed = mono_image(&mut doc, w, h, &padded(&self::eight_bit(&text, w, h)), None, &grey(8));++++ // 300 × 120 pt is 288 ppi; 144 × 57.6 pt is 600 ppi.-- page(&mut doc, &[("A", one_bit), ("B", eight_bit)], "q 300 0 0 120 20 600 cm /A Do Q q 144 0 0 57.6 20 400 cm /B Do Q");-- let before = [one_bit, eight_bit].map(|r| stream(&doc, r).raw);++++++ page(++++++ &mut doc,++++++ &[("A", one_bit), ("B", eight_bit), ("C", packed)],++++++ "q 300 0 0 120 20 600 cm /A Do Q q 144 0 0 57.6 20 400 cm /B Do Q q 300 0 0 120 20 200 cm /C Do Q",++++++ );++++++ let before = [one_bit, eight_bit, packed].map(|r| stream(&doc, r).raw);++++ let r = optimize(&mut doc, &Settings::default()).unwrap();-- let after = [one_bit, eight_bit].map(|r| stream(&doc, r).raw);++++++ let after = [one_bit, eight_bit, packed].map(|r| stream(&doc, r).raw);++++ if padding == 0 {-- assert_eq!((r.images_resampled, r.images_recompressed), (1, 1), "{r:?}");++++++ assert_eq!((r.images_resampled, r.images_recompressed), (1, 2), "{r:?}");++++ } else {++++ assert_eq!((r.images_resampled, r.images_recompressed), (0, 0), "{r:?}");++++ assert_eq!(after, before);++++ }++++ }++++ let hex_lines = |data: &[u8]| {++++ let digits: Vec<u8> = data.iter().flat_map(|b| format!("{b:02X}").into_bytes()).collect();++++ let mut text: Vec<u8> = digits.chunks(64).flat_map(|line| line.iter().copied().chain(*b"\n")).collect();++++ text.push(b'>');++++ pdfcraft_filters::encode_flate(&text)++++ };++++ let mut doc = Document::new_empty();++++ let as_hex = |doc: &mut Document, data: &[u8], bits: i64, (w, h): (u32, u32)| {++++ let mut d = Dict::new();++++ d.set(b"Subtype".to_vec(), Object::name("Image"));++++ d.set(b"Width".to_vec(), Object::Int(w.into()));++++ d.set(b"Height".to_vec(), Object::Int(h.into()));++++ d.set(b"BitsPerComponent".to_vec(), Object::Int(bits));++++ d.set(b"ColorSpace".to_vec(), Object::name("DeviceGray"));++++ d.set(b"Filter".to_vec(), Object::Array(vec![Object::name("FlateDecode"), Object::name("ASCIIHexDecode")]));++++ doc.add(Object::Stream(Stream::from_raw(d, hex_lines(data))))++++ };++++ // Large enough that its hex text in lines is more than twice its samples and a byte a row++++ // plus 4 KiB: 2560 × 1200, drawn at 400 ppi.++++ let page_scan = bilevel(2560, 1200, false);++++ let one_bit = as_hex(&mut doc, &page_scan, 1, (2560, 1200));++++ let eight_bit = as_hex(&mut doc, &shades, 8, (w, h));-- page(&mut doc, &[("A", one_bit), ("B", eight_bit)], "q 460.8 0 0 216 20 500 cm /A Do Q q 144 0 0 57.6 20 400 cm /B Do Q");++++++ let packed = as_hex(&mut doc, &self::eight_bit(&text, w, h), 8, (w, h));++++++ page(++++++ &mut doc,++++++ &[("A", one_bit), ("B", eight_bit), ("C", packed)],++++++ "q 460.8 0 0 216 20 500 cm /A Do Q q 144 0 0 57.6 20 400 cm /B Do Q q 300 0 0 120 20 200 cm /C Do Q",++++++ );++++ optimize(&mut doc, &Settings::default()).unwrap();++++ assert_eq!(stream(&doc, one_bit).dict.name(b"Filter"), Some(&b"CCITTFaxDecode"[..]), "1-bit hex text in lines: Group 4");++++ assert!(stream(&doc, eight_bit).dict.int(b"Width").is_some_and(|nw| nw < i64::from(w)), "8-bit hex text in lines: resampled");++++++ assert_eq!(stream(&doc, packed).dict.int(b"BitsPerComponent"), Some(1), "8-bit black-and-white hex text in lines: packed");++++++}++++++++++++/// Monochrome Images keeping each image's compression (and resampling as by default).++++++const RETAIN: MonoSettings = MonoSettings { compression: MonoCompression::Retain, ..MonoSettings::REDUCE };++++++++++++/// Eight-bit samples (0 or 255) from rows of one-bit ones.++++++fn eight_bit(bits: &[u8], w: u32, h: u32) -> Vec<u8> {++++++ let stride = (w as usize).div_ceil(8);++++++ (0..h as usize).flat_map(|y| (0..w as usize).map(move |x| if bits[y * stride + x / 8] & (0x80 >> (x % 8)) != 0 { 255 } else { 0 })).collect()++++++}++++++++++++/// Eight-bit samples of only 0 and 255, dithered (Floyd–Steinberg) from a smooth picture as a++++++/// scanner's halftone mode gives them: no shade but black and white, in short runs.++++++fn dithered(w: u32, h: u32) -> Vec<u8> {++++++ let (w, h) = (w as usize, h as usize);++++++ let mut level: Vec<f32> = (0..w * h).map(|i| 127.5 + 127.5 * ((i % w) as f32 / 37.0).sin() * ((i / w) as f32 / 53.0).cos()).collect();++++++ let mut out = vec![0u8; w * h];++++++ for y in 0..h {++++++ for x in 0..w {++++++ let i = y * w + x;++++++ let v = if level[i] < 128.0 { 0.0 } else { 255.0 };++++++ out[i] = v as u8;++++++ let e = level[i] - v;++++++ if x + 1 < w {++++++ level[i + 1] += e * 7.0 / 16.0;++++++ }++++++ if y + 1 < h {++++++ if x > 0 {++++++ level[i + w - 1] += e * 3.0 / 16.0;++++++ }++++++ level[i + w] += e * 5.0 / 16.0;++++++ if x + 1 < w {++++++ level[i + w + 1] += e / 16.0;++++++ }++++++ }++++++ }++++++ }++++++ out++++++}++++++++++++/// A dithered scan stored as eight-bit grey of only black and white is smaller downsampled and++++++/// JPEG-compressed by the grey settings than packed to one bit, which can't shrink its dots: the++++++/// smaller wins, so Reduce File Size makes it no larger than with Monochrome Images on Retain.++++++/// Clean text is still packed to one bit at the same resolution.++++++#[test]++++++fn eight_bit_black_and_white_takes_the_smaller_of_one_bit_and_the_grey_settings() {++++++ let (w, h) = (1200u32, 1500u32);++++++ for (what, samples) in [("dither", dithered(w, h)), ("text", eight_bit(&bilevel(w, h, false), w, h))] {++++++ let build = || {++++++ let mut doc = Document::new_empty();++++++ let img = mono_image(&mut doc, w, h, &samples, None, &[("BitsPerComponent", 8.into()), ("ColorSpace", Object::name("DeviceGray"))]);++++++ // 288 × 360 pt is 300 ppi, above where the grey settings downsample.++++++ page(&mut doc, &[("A", img)], "q 288 0 0 360 20 400 cm /A Do Q");++++++ (doc, img)++++++ };++++++ let (mut doc, img) = build();++++++ optimize(&mut doc, &Settings::default()).unwrap();++++++ let (mut retained, _) = build();++++++ optimize(&mut retained, &Settings { mono: RETAIN, ..Settings::default() }).unwrap();++++++ let (s, kept) = (stream(&doc, img), stream(&retained, img));++++++ let bits = if what == "dither" { 8 } else { 1 };++++++ assert_eq!(s.dict.int(b"BitsPerComponent"), Some(bits), "{what}: {} bytes, {} with Retain", s.raw.len(), kept.raw.len());++++++ if what == "dither" {++++++ assert!(s.raw.len() <= kept.raw.len(), "{what}: {} bytes, {} with Retain", s.raw.len(), kept.raw.len());++++++ }++++++ }++++++}++++++++++++/// The smaller of one bit and the grey settings counts the soft mask each leaves: packed, the++++++/// image keeps its mask as it is; resampled by the grey settings, the mask is resampled with it.++++++/// Clean text, 1200 × 1500 at 300 ppi, under a noisy mask. A mask as large: the grey settings++++++/// shrink it by far more than packing saves on the image, and win. A mask of 640 × 800 (a soft++++++/// mask may be another size than its image): resampled to the image's new size it shrinks only a++++++/// little, by less than the grey settings' JPEG adds over the packed image, and packing wins.++++++#[test]++++++fn eight_bit_black_and_white_with_a_soft_mask_counts_the_mask() {++++++ let (w, h) = (1200u32, 1500u32);++++++ for ((mw, mh), grey_wins) in [((w, h), true), ((640, 800), false)] {++++++ let mut doc = Document::new_empty();++++++ let mut seed = 0x2545_F491_4F6C_DD1Du64;++++++ let noise: Vec<u8> = (0..mw * mh)++++++ .map(|_| {++++++ seed ^= seed << 13;++++++ seed ^= seed >> 7;++++++ seed ^= seed << 17;++++++ (seed >> 24) as u8++++++ })++++++ .collect();++++++ let mask = mono_image(&mut doc, mw, mh, &noise, None, &[("BitsPerComponent", 8.into()), ("ColorSpace", Object::name("DeviceGray"))]);++++++ let grey = [("BitsPerComponent", 8.into()), ("ColorSpace", Object::name("DeviceGray")), ("SMask", Object::Ref(mask))];++++++ let img = mono_image(&mut doc, w, h, &eight_bit(&bilevel(w, h, false), w, h), None, &grey);++++++ page(&mut doc, &[("A", img)], "q 288 0 0 360 20 400 cm /A Do Q");++++++ optimize(&mut doc, &Settings::default()).unwrap();++++++ let s = stream(&doc, img);++++++ let expected = if grey_wins { (Some(8), Some(&b"DCTDecode"[..])) } else { (Some(1), Some(&b"CCITTFaxDecode"[..])) };++++++ assert_eq!((s.dict.int(b"BitsPerComponent"), s.dict.name(b"Filter")), expected, "mask {mw} × {mh}: {:?}", s.dict);++++++ }++++++}++++++++++++/// Eight-bit grey images of only black and white (as some scanners and converters write scans)++++++/// become one-bit Group 4, losslessly: the page looks the same, an inverting decode array++++++/// included. Not touched by this: a grey image with any other shade, an indexed image (its samples++++++/// are palette indices), one masked by colour key, and everything with `mono: Retain`.++++++#[test]++++++fn eight_bit_black_and_white_images_become_one_bit() {++++++ let mut doc = Document::new_empty();++++++ let (w, h) = (1200, 480);++++++ let grey = eight_bit(&bilevel(w, h, false), w, h);++++++ let image = |doc: &mut Document, data: &[u8], entries: &[(&str, Object)]| {++++++ let mut d = Dict::new();++++++ d.set(b"Type".to_vec(), Object::name("XObject"));++++++ d.set(b"Subtype".to_vec(), Object::name("Image"));++++++ d.set(b"Width".to_vec(), Object::Int(w as i64));++++++ d.set(b"Height".to_vec(), Object::Int(h as i64));++++++ d.set(b"BitsPerComponent".to_vec(), Object::Int(8));++++++ for (k, v) in entries {++++++ d.set(k.as_bytes().to_vec(), v.clone());++++++ }++++++ doc.add(Object::Stream(Stream::flate(d, data)))++++++ };++++++ let gray_cs = ("ColorSpace", Object::name("DeviceGray"));++++++ let plain = image(&mut doc, &grey, std::slice::from_ref(&gray_cs));++++++ let decode = Object::Array(vec![1.into(), 0.into()]);++++++ let inverted = image(&mut doc, &grey, &[gray_cs.clone(), ("Decode", decode.clone())]);++++++ let mut shaded = grey.clone();++++++ shaded[1000] = 128;++++++ let shade = image(&mut doc, &shaded, std::slice::from_ref(&gray_cs));++++++ let palette = Object::Array(vec![++++++ Object::name("Indexed"),++++++ Object::name("DeviceGray"),++++++ 255.into(),++++++ Object::String(pdfcraft_cos::PdfString::literal((0..=255u8).rev().collect::<Vec<_>>())),++++++ ]);++++++ let indexed = image(&mut doc, &grey, &[("ColorSpace", palette)]);++++++ let keyed = image(&mut doc, &grey, &[gray_cs, ("Mask", Object::Array(vec![0.into(), 0.into()]))]);++++++ page(++++++ &mut doc,++++++ &[("A", plain), ("B", inverted), ("C", shade), ("D", indexed), ("E", keyed)],++++++ "q 300 0 0 120 20 660 cm /A Do Q q 300 0 0 120 320 660 cm /B Do Q q 300 0 0 120 20 520 cm /C Do Q \++++++ q 300 0 0 120 320 520 cm /D Do Q q 300 0 0 120 20 380 cm /E Do Q",++++++ );++++++ let before = render(&doc);++++++ let raw = |doc: &Document, r: ObjRef| stream(doc, r).raw;++++++ // Grey settings that leave grey images alone, so only this conversion acts.++++++ let keep = ImageSettings { downsample: false, target_ppi: 150.0, above_ppi: 225.0, compression: Compression::Retain };++++++ let settings = Settings { gray: keep, ..Settings::default() };++++++++++++ let mut kept = doc.clone();++++++ let r = optimize(&mut kept, &Settings { mono: RETAIN, ..settings.clone() }).unwrap();++++++ assert_eq!(r.images_recompressed, 0, "Retain keeps every image as it is");++++++++++++ let untouched = [shade, indexed, keyed].map(|r| raw(&doc, r));++++++ let old: usize = [plain, inverted].map(|r| raw(&doc, r).len()).iter().sum();++++++ let r = optimize(&mut doc, &settings).unwrap();++++++ assert_eq!(r.images_recompressed, 2);++++++ let new: usize = [plain, inverted].map(|r| raw(&doc, r).len()).iter().sum();++++++ assert_eq!((r.image_bytes_before, r.image_bytes_after), (old, new), "the byte totals count both");++++++ for i in [plain, inverted] {++++++ let s = stream(&doc, i);++++++ assert_eq!((s.dict.int(b"BitsPerComponent"), s.dict.name(b"Filter")), (Some(1), Some(&b"CCITTFaxDecode"[..])));++++++ }++++++ assert_eq!(stream(&doc, inverted).dict.get(b"Decode"), Some(&decode), "the decode array stays");++++++ assert_eq!([shade, indexed, keyed].map(|r| raw(&doc, r)), untouched);++++++ assert!(render(&doc) == before, "the page looks the same");++++++}++++++++++++/// `bits` (1-bit rows) with each 0 as `values[0]` and each 1 as `values[1]`, at `bpc` bits a sample++++++/// (each row starting on a new byte).++++++fn samples_of(bits: &[u8], w: u32, h: u32, values: [&[u8]; 2], bpc: usize) -> Vec<u8> {++++++ let (w, h) = (w as usize, h as usize);++++++ let stride = w.div_ceil(8);++++++ let mut out = Vec::new();++++++ for y in 0..h {++++++ let row: Vec<u8> = (0..w).flat_map(|x| values[usize::from(bits[y * stride + x / 8] & (0x80 >> (x % 8)) != 0)].iter().copied()).collect();++++++ let mut packed = vec![0u8; (row.len() * bpc).div_ceil(8)];++++++ for (i, s) in row.iter().enumerate() {++++++ packed[i * bpc / 8] |= if bpc == 8 { *s } else { s << (8 - bpc - i * bpc % 8) };++++++ }++++++ out.extend(packed);++++++ }++++++ out++++++}++++++++++++/// Eight-bit RGB of only black and white becomes one-bit grey, and an indexed image that uses only++++++/// palette entries 0 and 1 becomes one bit with its palette (here blue and white), at 8 bits or 4,++++++/// both as Group 4 and losslessly: the page looks the same to the pixel. An RGB decode array the++++++/// same for each component becomes grey's, and an indexed image's default one goes. Not touched:++++++/// RGB with any other colour, a decode array that differs between components, a colour-key mask or++++++/// calibrated RGB; an indexed image that uses a third entry or has another decode array; and++++++/// everything with `mono: Retain`.++++++#[test]++++++fn rgb_and_two_colour_indexed_black_and_white_images_become_one_bit() {++++++ let mut doc = Document::new_empty();++++++ let (w, h) = (1200u32, 480u32);++++++ let text = bilevel(w, h, false);++++++ let image = |doc: &mut Document, data: &[u8], bpc: i64, cs: Object, entries: &[(&str, Object)]| {++++++ let mut d = Dict::new();++++++ d.set(b"Type".to_vec(), Object::name("XObject"));++++++ d.set(b"Subtype".to_vec(), Object::name("Image"));++++++ d.set(b"Width".to_vec(), Object::Int(w.into()));++++++ d.set(b"Height".to_vec(), Object::Int(h.into()));++++++ d.set(b"BitsPerComponent".to_vec(), Object::Int(bpc));++++++ d.set(b"ColorSpace".to_vec(), cs);++++++ for (k, v) in entries {++++++ d.set(k.as_bytes().to_vec(), v.clone());++++++ }++++++ doc.add(Object::Stream(Stream::flate(d, data)))++++++ };++++++ let rgb_cs = Object::name("DeviceRGB");++++++ let rgb_data = samples_of(&text, w, h, [&[0, 0, 0], &[255, 255, 255]], 8);++++++ let rgb = image(&mut doc, &rgb_data, 8, rgb_cs.clone(), &[]);++++++ let pairs = |p: [i64; 6]| Object::Array(p.into_iter().map(Object::Int).collect());++++++ let rgb_inverted = image(&mut doc, &rgb_data, 8, rgb_cs.clone(), &[("Decode", pairs([1, 0, 1, 0, 1, 0]))]);++++++ let rgb_mixed = image(&mut doc, &rgb_data, 8, rgb_cs.clone(), &[("Decode", pairs([1, 0, 0, 1, 0, 1]))]);++++++ let mut red = rgb_data.clone();++++++ red[3000..3003].copy_from_slice(&[255, 0, 0]);++++++ let rgb_red = image(&mut doc, &red, 8, rgb_cs.clone(), &[]);++++++ let mut white_point = Dict::new();++++++ white_point.set(b"WhitePoint".to_vec(), Object::Array(vec![Object::Real(0.9505), 1.into(), Object::Real(1.089)]));++++++ let cal_rgb = image(&mut doc, &rgb_data, 8, Object::Array(vec![Object::name("CalRGB"), Object::Dict(white_point)]), &[]);++++++ let rgb_keyed = image(&mut doc, &rgb_data, 8, rgb_cs, &[("Mask", pairs([0, 0, 0, 0, 0, 0]))]);++++++ let palette = |entries: &[u8]| {++++++ Object::Array(vec![++++++ Object::name("Indexed"),++++++ Object::name("DeviceRGB"),++++++ (entries.len() as i64 / 3 - 1).into(),++++++ Object::String(pdfcraft_cos::PdfString::literal(entries.to_vec())),++++++ ])++++++ };++++++ let blue_white = palette(&[0, 0, 255, 255, 255, 255]);++++++ let indices = samples_of(&text, w, h, [&[0], &[1]], 8);++++++ let blue = image(&mut doc, &indices, 8, blue_white.clone(), &[]);++++++ let default_decode = Object::Array(vec![0.into(), 255.into()]);++++++ let blue_decoded = image(&mut doc, &indices, 8, blue_white.clone(), &[("Decode", default_decode)]);++++++ let blue_4 = image(&mut doc, &samples_of(&text, w, h, [&[0], &[1]], 4), 4, blue_white.clone(), &[]);++++++ let mut third = indices.clone();++++++ third[3000] = 2;++++++ let three = image(&mut doc, &third, 8, palette(&[0, 0, 255, 255, 255, 255, 255, 0, 0]), &[]);++++++ let other_decode = image(&mut doc, &indices, 8, blue_white.clone(), &[("Decode", Object::Array(vec![0.into(), 1.into()]))]);++++++ let all = [rgb, rgb_inverted, rgb_mixed, rgb_red, cal_rgb, rgb_keyed, blue, blue_decoded, blue_4, three, other_decode];++++++ // 200 × 80 pt is 432 ppi: below where monochrome downsampling starts.++++++ let names: Vec<String> = (0..all.len()).map(|i| format!("Im{i}")).collect();++++++ let content: String =++++++ (0..all.len()).map(|i| format!("q 200 0 0 80 {} {} cm /Im{i} Do Q ", 6 + 200 * (i % 3), 690 - 100 * (i / 3) as i64)).collect();++++++ page(&mut doc, &names.iter().map(String::as_str).zip(all).collect::<Vec<_>>(), &content);++++++ let before = render(&doc);++++++ let raw = |doc: &Document, r: ObjRef| stream(doc, r).raw;++++++ // Colour and grey settings that leave images alone, so only this conversion acts.++++++ let keep = ImageSettings { downsample: false, target_ppi: 150.0, above_ppi: 225.0, compression: Compression::Retain };++++++ let settings = Settings { color: keep, gray: keep, ..Settings::default() };++++++++++++ let mut kept = doc.clone();++++++ let r = optimize(&mut kept, &Settings { mono: RETAIN, ..settings.clone() }).unwrap();++++++ assert_eq!((r.images_resampled, r.images_recompressed), (0, 0), "Retain keeps every image as it is");++++++++++++ let untouched = [rgb_mixed, rgb_red, cal_rgb, rgb_keyed, three, other_decode].map(|r| raw(&doc, r));++++++ let r = optimize(&mut doc, &settings).unwrap();++++++ assert_eq!((r.images_resampled, r.images_recompressed), (0, 5), "{r:?}");++++++ for (i, cs) in [++++++ (rgb, Object::name("DeviceGray")),++++++ (rgb_inverted, Object::name("DeviceGray")),++++++ (blue, blue_white.clone()),++++++ (blue_decoded, blue_white.clone()),++++++ (blue_4, blue_white),++++++ ] {++++++ let s = stream(&doc, i);++++++ assert_eq!(++++++ (s.dict.int(b"BitsPerComponent"), s.dict.name(b"Filter"), s.dict.get(b"ColorSpace")),++++++ (Some(1), Some(&b"CCITTFaxDecode"[..]), Some(&cs)),++++++ "{i:?}"++++++ );++++++ assert_eq!(doc.decoded_image(&s).unwrap(), text, "{i:?}");++++++ let decode = if i == rgb_inverted { Some(Object::Array(vec![1.into(), 0.into()])) } else { None };++++++ assert_eq!(s.dict.get(b"Decode").cloned(), decode, "{i:?}");++++++ }++++++ assert_eq!([rgb_mixed, rgb_red, cal_rgb, rgb_keyed, three, other_decode].map(|r| raw(&doc, r)), untouched);++++++ assert!(render(&doc) == before, "the page looks the same");++++++}++++++++++++/// Eight-bit black-and-white images in other one-component spaces are packed too: calibrated++++++/// grey, an ICC profile of one component, a separation, each keeping its colour space. Calibrated++++++/// RGB whose samples are only 0 and 1 is no indexed image, and stays as it is.++++++#[test]++++++fn eight_bit_black_and_white_in_other_one_component_spaces_is_packed() {++++++ let mut doc = Document::new_empty();++++++ let (w, h) = (1200u32, 480u32);++++++ let text = bilevel(w, h, false);++++++ let image = |doc: &mut Document, data: &[u8], cs: Object| {++++++ let mut d = Dict::new();++++++ d.set(b"Subtype".to_vec(), Object::name("Image"));++++++ d.set(b"Width".to_vec(), Object::Int(w.into()));++++++ d.set(b"Height".to_vec(), Object::Int(h.into()));++++++ d.set(b"BitsPerComponent".to_vec(), Object::Int(8));++++++ d.set(b"ColorSpace".to_vec(), cs);++++++ doc.add(Object::Stream(Stream::flate(d, data)))++++++ };++++++ let mut white_point = Dict::new();++++++ white_point.set(b"WhitePoint".to_vec(), Object::Array(vec![Object::Real(0.9505), 1.into(), Object::Real(1.089)]));++++++ let mut profile = Dict::new();++++++ profile.set(b"N".to_vec(), Object::Int(1));++++++ let profile = doc.add(Object::Stream(Stream::from_raw(profile, Vec::new())));++++++ let mut tint = Dict::new();++++++ tint.set(b"FunctionType".to_vec(), Object::Int(2));++++++ tint.set(b"Domain".to_vec(), Object::Array(vec![0.into(), 1.into()]));++++++ tint.set(b"N".to_vec(), Object::Int(1));++++++ let spaces = [++++++ Object::Array(vec![Object::name("CalGray"), Object::Dict(white_point.clone())]),++++++ Object::Array(vec![Object::name("ICCBased"), Object::Ref(profile)]),++++++ Object::Array(vec![Object::name("Separation"), Object::name("Spot"), Object::name("DeviceGray"), Object::Dict(tint)]),++++++ ];++++++ let grey = samples_of(&text, w, h, [&[0], &[255]], 8);++++++ let packed = spaces.clone().map(|cs| image(&mut doc, &grey, cs));++++++ let cal_rgb = Object::Array(vec![Object::name("CalRGB"), Object::Dict(white_point)]);++++++ let cal_rgb = image(&mut doc, &samples_of(&text, w, h, [&[0, 0, 0], &[1, 1, 1]], 8), cal_rgb);++++++ let names = ["A", "B", "C", "D"];++++++ // 200 × 80 pt is 432 ppi: below where monochrome downsampling starts.++++++ let content: String = (0..4).map(|i| format!("q 200 0 0 80 6 {} cm /{} Do Q ", 690 - 100 * i, names[i])).collect();++++++ page(&mut doc, &names.into_iter().zip([packed[0], packed[1], packed[2], cal_rgb]).collect::<Vec<_>>(), &content);++++++ let untouched = stream(&doc, cal_rgb).raw;++++++ // Colour and grey settings that leave images alone, so only the packing acts.++++++ let keep = ImageSettings { downsample: false, target_ppi: 150.0, above_ppi: 225.0, compression: Compression::Retain };++++++ optimize(&mut doc, &Settings { color: keep, gray: keep, ..Settings::default() }).unwrap();++++++ for (r, cs) in packed.iter().zip(&spaces) {++++++ let s = stream(&doc, *r);++++++ assert_eq!((s.dict.int(b"BitsPerComponent"), s.dict.get(b"ColorSpace")), (Some(1), Some(cs)), "{cs:?}");++++++ }++++++ assert_eq!(stream(&doc, cal_rgb).raw, untouched, "calibrated RGB");++++++}++++++++++++/// A resampled Group 4 image is stored as 1-bit Flate when that is smaller, as any resampled image++++++/// may be: here vertical stripes, whose identical rows Flate takes for almost nothing.++++++#[test]++++++fn a_resampled_group_4_image_is_stored_as_flate_when_smaller() {++++++ let (w, h) = (1200u32, 480u32);++++++ let stripes = vec![0x0Fu8; (w as usize).div_ceil(8) * h as usize];++++++ let mut doc = Document::new_empty();++++++ let mut d = Dict::new();++++++ d.set(b"Subtype".to_vec(), Object::name("Image"));++++++ d.set(b"Width".to_vec(), Object::Int(w.into()));++++++ d.set(b"Height".to_vec(), Object::Int(h.into()));++++++ d.set(b"BitsPerComponent".to_vec(), Object::Int(1));++++++ d.set(b"ColorSpace".to_vec(), Object::name("DeviceGray"));++++++ d.set(b"Filter".to_vec(), Object::name("CCITTFaxDecode"));++++++ let mut parms = Dict::new();++++++ parms.set(b"K".to_vec(), Object::Int(-1));++++++ parms.set(b"Columns".to_vec(), Object::Int(w.into()));++++++ d.set(b"DecodeParms".to_vec(), Object::Dict(parms));++++++ let img = doc.add(Object::Stream(Stream::from_raw(d, pdfcraft_filters::encode_g4(&stripes, w, h).unwrap())));++++++ // 144 × 57.6 pt is 600 ppi.++++++ page(&mut doc, &[("A", img)], "q 144 0 0 57.6 20 600 cm /A Do Q");++++++ let r = optimize(&mut doc, &Settings::default()).unwrap();++++++ assert_eq!(r.images_resampled, 1, "{r:?}");++++++ let s = stream(&doc, img);++++++ assert_eq!((s.dict.int(b"Width"), s.dict.name(b"Filter")), (Some(600), Some(&b"FlateDecode"[..])));++++++}++++++++++++/// A decode array is read as numbers, whichever way they are written: an indexed image's default++++++/// as `[0 255.0]` or with an entry by reference, and RGB's inverting pairs with a real among them,++++++/// pack as when written as integers.++++++#[test]++++++fn decode_arrays_read_as_numbers_however_written() {++++++ let mut doc = Document::new_empty();++++++ let (w, h) = (1200u32, 480u32);++++++ let text = bilevel(w, h, false);++++++ let image = |doc: &mut Document, data: &[u8], cs: Object, decode: Object| {++++++ let mut d = Dict::new();++++++ d.set(b"Subtype".to_vec(), Object::name("Image"));++++++ d.set(b"Width".to_vec(), Object::Int(w.into()));++++++ d.set(b"Height".to_vec(), Object::Int(h.into()));++++++ d.set(b"BitsPerComponent".to_vec(), Object::Int(8));++++++ d.set(b"ColorSpace".to_vec(), cs);++++++ d.set(b"Decode".to_vec(), decode);++++++ doc.add(Object::Stream(Stream::flate(d, data)))++++++ };++++++ let palette = Object::Array(vec![++++++ Object::name("Indexed"),++++++ Object::name("DeviceRGB"),++++++ 1.into(),++++++ Object::String(pdfcraft_cos::PdfString::literal(vec![0, 0, 255, 255, 255, 255])),++++++ ]);++++++ let indices = samples_of(&text, w, h, [&[0], &[1]], 8);++++++ let max = doc.add(Object::Int(255));++++++ let real = image(&mut doc, &indices, palette.clone(), Object::Array(vec![0.into(), Object::Real(255.0)]));++++++ let referred = image(&mut doc, &indices, palette, Object::Array(vec![0.into(), Object::Ref(max)]));++++++ let rgb = samples_of(&text, w, h, [&[0, 0, 0], &[255, 255, 255]], 8);++++++ let pairs = Object::Array(vec![1.into(), 0.into(), 1.into(), 0.into(), Object::Real(1.0), 0.into()]);++++++ let inverted = image(&mut doc, &rgb, Object::name("DeviceRGB"), pairs);++++++ page(++++++ &mut doc,++++++ &[("A", real), ("B", referred), ("C", inverted)],++++++ "q 200 0 0 80 6 690 cm /A Do Q q 200 0 0 80 6 590 cm /B Do Q q 200 0 0 80 6 490 cm /C Do Q",++++++ );++++++ let keep = ImageSettings { downsample: false, target_ppi: 150.0, above_ppi: 225.0, compression: Compression::Retain };++++++ optimize(&mut doc, &Settings { color: keep, gray: keep, ..Settings::default() }).unwrap();++++++ for r in [real, referred] {++++++ let s = stream(&doc, r);++++++ assert_eq!((s.dict.int(b"BitsPerComponent"), s.dict.get(b"Decode")), (Some(1), None), "{r:?}");++++++ }++++++ let s = stream(&doc, inverted);++++++ let decode = Object::Array(vec![1.into(), 0.into()]);++++++ assert_eq!((s.dict.int(b"BitsPerComponent"), s.dict.get(b"Decode")), (Some(1), Some(&decode)));++++++}++++++++++++/// With Retain, a Group 3 halftone above 450 ppi, which isn't resampled, stays Group 3 byte for++++++/// byte: Retain stores nothing again that it doesn't resample.++++++#[test]++++++fn retain_keeps_a_group_3_halftone_as_it_is() {++++++ let (w, h) = (64u32, 64u32);++++++ let a: Vec<u32> = vec![1; 64];++++++ let b: Vec<u32> = std::iter::once(0).chain(std::iter::repeat_n(1, 64)).collect();++++++ let runs: Vec<&[u32]> = (0..h).map(|y| if y % 2 == 0 { &a[..] } else { &b[..] }).collect();++++++ let g3 = group_3(&runs, false, None);++++++ let mut doc = Document::new_empty();++++++ let mut d = Dict::new();++++++ d.set(b"Subtype".to_vec(), Object::name("Image"));++++++ d.set(b"Width".to_vec(), Object::Int(w.into()));++++++ d.set(b"Height".to_vec(), Object::Int(h.into()));++++++ d.set(b"BitsPerComponent".to_vec(), Object::Int(1));++++++ d.set(b"ColorSpace".to_vec(), Object::name("DeviceGray"));++++++ d.set(b"Filter".to_vec(), Object::name("CCITTFaxDecode"));++++++ let mut parms = Dict::new();++++++ parms.set(b"K".to_vec(), Object::Int(0));++++++ parms.set(b"Columns".to_vec(), Object::Int(w.into()));++++++ d.set(b"DecodeParms".to_vec(), Object::Dict(parms));++++++ let fax = doc.add(Object::Stream(Stream::from_raw(d, g3.clone())));++++++ // 7.68 pt for 64 samples is 600 ppi.++++++ page(&mut doc, &[("A", fax)], "q 7.68 0 0 7.68 100 600 cm /A Do Q");++++++ assert_eq!(doc.decoded_image(&stream(&doc, fax)).unwrap().len(), 64 * 8, "the fixture decodes");++++++ let r = optimize(&mut doc, &Settings { mono: RETAIN, ..Settings::default() }).unwrap();++++++ assert_eq!((r.images_resampled, r.images_recompressed), (0, 0), "{r:?}");++++++ assert_eq!(stream(&doc, fax).raw[..], g3[..]);++++++}++++++++++++/// Black-and-white RGB stays RGB where grey would be drawn otherwise: drawn, on any of its uses,++++++/// where `/DefaultGray` or `/DefaultRGB` is in force (ISO 32000-2 §8.6.5.6), from a page's++++++/// resources or a form's own, as grey would then go through DefaultGray, or no longer through++++++/// DefaultRGB; or with a soft mask whose `/Matte` has three components, one for each of RGB's. A++++++/// form drawn where they are in force counts too, though it has resources of its own. The same++++++/// image drawn plainly, or with a soft mask and no `/Matte`, becomes grey.++++++#[test]++++++fn black_and_white_rgb_stays_rgb_where_grey_would_be_drawn_otherwise() {++++++ let mut doc = Document::new_empty();++++++ let (w, h) = (1200u32, 480u32);++++++ let rgb_data = samples_of(&bilevel(w, h, false), w, h, [&[0, 0, 0], &[255, 255, 255]], 8);++++++ let image = |doc: &mut Document, cs: &str, data: &[u8], entries: &[(&str, Object)]| {++++++ let mut d = Dict::new();++++++ d.set(b"Type".to_vec(), Object::name("XObject"));++++++ d.set(b"Subtype".to_vec(), Object::name("Image"));++++++ d.set(b"Width".to_vec(), Object::Int(w.into()));++++++ d.set(b"Height".to_vec(), Object::Int(h.into()));++++++ d.set(b"BitsPerComponent".to_vec(), Object::Int(8));++++++ d.set(b"ColorSpace".to_vec(), Object::name(cs));++++++ for (k, v) in entries {++++++ d.set(k.as_bytes().to_vec(), v.clone());++++++ }++++++ doc.add(Object::Stream(Stream::flate(d, data)))++++++ };++++++ let opaque = vec![255u8; (w * h) as usize];++++++ let plain_mask = image(&mut doc, "DeviceGray", &opaque, &[]);++++++ let matte_mask = image(&mut doc, "DeviceGray", &opaque, &[("Matte", Object::Array(vec![0.into(); 3]))]);++++++ let plain = image(&mut doc, "DeviceRGB", &rgb_data, &[]);++++++ let masked = image(&mut doc, "DeviceRGB", &rgb_data, &[("SMask", Object::Ref(plain_mask))]);++++++ let matted = image(&mut doc, "DeviceRGB", &rgb_data, &[("SMask", Object::Ref(matte_mask))]);++++++ let [under_gray, under_rgb, shared, in_form, nested] = [(); 5].map(|_| image(&mut doc, "DeviceRGB", &rgb_data, &[]));++++++ let mut white_point = Dict::new();++++++ white_point.set(b"WhitePoint".to_vec(), Object::Array(vec![Object::Real(0.9505), 1.into(), Object::Real(1.089)]));++++++ let spaces = |key: &str| {++++++ let family = if key == "DefaultGray" { "CalGray" } else { "CalRGB" };++++++ let mut c = Dict::new();++++++ c.set(key.as_bytes().to_vec(), Object::Array(vec![Object::name(family), Object::Dict(white_point.clone())]));++++++ Object::Dict(c)++++++ };++++++ let draw = |names: &[&str]| names.iter().enumerate().map(|(i, n)| format!("q 200 0 0 80 6 {} cm /{n} Do Q ", 690 - 100 * i)).collect::<String>();++++++ let form = |doc: &mut Document, im: ObjRef, spaces: Option<Object>| {++++++ let mut xobjects = Dict::new();++++++ xobjects.set(b"Im".to_vec(), Object::Ref(im));++++++ let mut resources = Dict::new();++++++ resources.set(b"XObject".to_vec(), Object::Dict(xobjects));++++++ if let Some(spaces) = spaces {++++++ resources.set(b"ColorSpace".to_vec(), spaces);++++++ }++++++ let mut f = Dict::new();++++++ f.set(b"Type".to_vec(), Object::name("XObject"));++++++ f.set(b"Subtype".to_vec(), Object::name("Form"));++++++ f.set(b"BBox".to_vec(), Object::Array(vec![0.into(), 0.into(), 612.into(), 792.into()]));++++++ f.set(b"Resources".to_vec(), Object::Dict(resources));++++++ doc.add(Object::Stream(Stream::from_raw(f, draw(&["Im"]).into_bytes())))++++++ };++++++ // Drawn plainly first, then where DefaultGray is in force: the second walk must happen.++++++ let plain_form = form(&mut doc, nested, None);++++++ page(&mut doc, &[("A", plain), ("B", masked), ("C", matted), ("D", shared), ("E", plain_form)], &draw(&["A", "B", "C", "D", "E"]));++++++ for (key, xobjects) in [("DefaultGray", vec![("A", under_gray), ("B", shared), ("C", plain_form)]), ("DefaultRGB", vec![("A", under_rgb)])] {++++++ let names: Vec<&str> = xobjects.iter().map(|(n, _)| *n).collect();++++++ let p = page(&mut doc, &xobjects, &draw(&names));++++++ doc.update_dict(p, |d| {++++++ let mut res = d.get(b"Resources").and_then(Object::as_dict).cloned().unwrap();++++++ res.set(b"ColorSpace".to_vec(), spaces(key));++++++ d.set(b"Resources".to_vec(), Object::Dict(res));++++++ })++++++ .unwrap();++++++ }++++++ // A form with its own resources, DefaultGray among them, on a page without any.++++++ let gray_form = form(&mut doc, in_form, Some(spaces("DefaultGray")));++++++ page(&mut doc, &[("F", gray_form)], "/F Do");++++++ let kept = [under_gray, under_rgb, shared, in_form, nested, matted];++++++ let before = kept.map(|r| stream(&doc, r));++++++ // Colour and grey settings that leave images alone, so only this conversion acts.++++++ let keep = ImageSettings { downsample: false, target_ppi: 150.0, above_ppi: 225.0, compression: Compression::Retain };++++++ let settings = Settings { color: keep, gray: keep, ..Settings::default() };++++++ let r = optimize(&mut doc, &settings).unwrap();++++++ assert_eq!((r.images_resampled, r.images_recompressed), (0, 2), "{r:?}");++++++ for i in [plain, masked] {++++++ let s = stream(&doc, i);++++++ assert_eq!((s.dict.get(b"ColorSpace"), s.dict.int(b"BitsPerComponent")), (Some(&Object::name("DeviceGray")), Some(1)), "{i:?}");++++++ }++++++ for (i, b) in kept.iter().zip(&before) {++++++ let s = stream(&doc, *i);++++++ assert_eq!((&s.dict, &s.raw), (&b.dict, &b.raw), "{i:?}");++++++ }++++++++++++ // A use that couldn't be followed (forms nested too deep) may be where DefaultGray is in force.++++++ let mut doc = Document::new_empty();++++++ let img = image(&mut doc, "DeviceRGB", &rgb_data, &[]);++++++ let deep = nested_forms(&mut doc, img, 13);++++++ page(&mut doc, &[("Im", img), ("F", deep)], &draw(&["Im", "F"]));++++++ let before = stream(&doc, img);++++++ optimize(&mut doc, &settings).unwrap();++++++ assert_eq!(stream(&doc, img).raw, before.raw, "a use not followed");++++++}++++++++++++/// An empty document, and a maker of images of only black and white as eight-bit `DeviceRGB`.++++++fn rgb_page_fixture() -> (Document, impl Fn(&mut Document) -> ObjRef) {++++++ let (w, h) = (1200u32, 480u32);++++++ let rgb_data = samples_of(&bilevel(w, h, false), w, h, [&[0, 0, 0], &[255, 255, 255]], 8);++++++ let image = move |doc: &mut Document| {++++++ let mut d = Dict::new();++++++ d.set(b"Type".to_vec(), Object::name("XObject"));++++++ d.set(b"Subtype".to_vec(), Object::name("Image"));++++++ d.set(b"Width".to_vec(), Object::Int(w.into()));++++++ d.set(b"Height".to_vec(), Object::Int(h.into()));++++++ d.set(b"BitsPerComponent".to_vec(), Object::Int(8));++++++ d.set(b"ColorSpace".to_vec(), Object::name("DeviceRGB"));++++++ doc.add(Object::Stream(Stream::flate(d, &rgb_data)))++++++ };++++++ (Document::new_empty(), image)++++++}++++++++++++/// `q … cm /N Do Q` for each name, one under the other.++++++fn draw_each(names: &[&str]) -> String {++++++ names.iter().enumerate().map(|(i, n)| format!("q 200 0 0 80 6 {} cm /{n} Do Q ", 690 - 100 * i)).collect()++++++}++++++++++++/// An `/XObject` dictionary of `names`.++++++fn xobject_dict(names: &[(&str, ObjRef)]) -> Dict {++++++ let mut x = Dict::new();++++++ for (n, r) in names {++++++ x.set(n.as_bytes().to_vec(), Object::Ref(*r));++++++ }++++++ x++++++}++++++++++++/// A stream drawing `/Im` (or nothing) whose `/Resources` is `resources`, with `extra` in its++++++/// dictionary: a form, an appearance or a tiling pattern.++++++fn drawing(doc: &mut Document, resources: Option<Object>, extra: &[(&str, Object)]) -> ObjRef {++++++ let mut f = Dict::new();++++++ f.set(b"BBox".to_vec(), Object::Array(vec![0.into(), 0.into(), 612.into(), 792.into()]));++++++ if let Some(resources) = resources {++++++ f.set(b"Resources".to_vec(), resources);++++++ }++++++ for (k, v) in extra {++++++ f.set(k.as_bytes().to_vec(), v.clone());++++++ }++++++ doc.add(Object::Stream(Stream::from_raw(f, draw_each(&["Im"]).into_bytes())))++++++}++++++++++++fn form_entries() -> [(&'static str, Object); 2] {++++++ [("Type", Object::name("XObject")), ("Subtype", Object::name("Form"))]++++++}++++++++++++/// Resources of `entries`.++++++fn resources_of(entries: Vec<(&str, Object)>) -> Dict {++++++ let mut res = Dict::new();++++++ for (k, v) in entries {++++++ res.set(k.as_bytes().to_vec(), v);++++++ }++++++ res++++++}++++++++++++/// Give page `p` an annotation whose normal appearance is `appearance`.++++++fn annotate(doc: &mut Document, p: ObjRef, appearance: ObjRef) {++++++ let mut ap = Dict::new();++++++ ap.set(b"N".to_vec(), Object::Ref(appearance));++++++ let mut annotation = Dict::new();++++++ annotation.set(b"Subtype".to_vec(), Object::name("Square"));++++++ annotation.set(b"Rect".to_vec(), Object::Array(vec![0.into(), 0.into(), 100.into(), 100.into()]));++++++ annotation.set(b"AP".to_vec(), Object::Dict(ap));++++++ let annotation = doc.add(Object::Dict(annotation));++++++ let mut annots = doc.get(p).as_dict().and_then(|d| d.get(b"Annots").and_then(|a| a.as_array().cloned())).unwrap_or_default();++++++ annots.push(Object::Ref(annotation));++++++ doc.update_dict(p, |d| d.set(b"Annots".to_vec(), Object::Array(annots))).unwrap();++++++}++++++++++++/// `/DefaultGray` as a calibrated grey, in a `/ColorSpace` resource dictionary.++++++fn default_gray() -> Object {++++++ let mut white_point = Dict::new();++++++ white_point.set(b"WhitePoint".to_vec(), Object::Array(vec![Object::Real(0.9505), 1.into(), Object::Real(1.089)]));++++++ let mut c = Dict::new();++++++ c.set(b"DefaultGray".to_vec(), Object::Array(vec![Object::name("CalGray"), Object::Dict(white_point)]));++++++ Object::Dict(c)++++++}++++++++++++/// Optimize with colour and grey settings that leave images alone, so only packing acts; the++++++/// report's images resampled and stored again.++++++fn pack_only(doc: &mut Document) -> (usize, usize) {++++++ let keep = ImageSettings { downsample: false, target_ppi: 150.0, above_ppi: 225.0, compression: Compression::Retain };++++++ let r = optimize(doc, &Settings { color: keep, gray: keep, ..Settings::default() }).unwrap();++++++ (r.images_resampled, r.images_recompressed)++++++}++++++++++++/// Black-and-white RGB becomes grey for every use at once, so it stays RGB, byte for byte, when++++++/// any use may be beyond the page content and forms the optimizer reads, where other default++++++/// colour spaces may be in force: drawn by an annotation's appearance whose resources make++++++/// `/DefaultGray` the grey it would be drawn in; by a tiling pattern; through an `/XObject`++++++/// dictionary, or a form, that a page shares with such an appearance;++++++/// referred to with another generation by the page than by such an appearance; drawn plainly on++++++/// one page and, named with another generation, on a page whose resources set `/DefaultGray`;++++++/// drawn plainly and only listed (not drawn) where `/DefaultGray` is in force, under the same++++++/// generation or another, as a Type3 glyph without resources could draw it there; or held in an++++++/// array elsewhere (another image's `/Alternates`).++++++#[test]++++++fn black_and_white_rgb_used_beyond_the_page_content_read_stays_rgb() {++++++ let (mut doc, image) = rgb_page_fixture();++++++ let [in_annotation, in_pattern, shared_xobjects, shared_form, other_generation, generation_under_defaults, listed, listed_as_1, in_array] =++++++ [(); 9].map(|_| image(&mut doc));++++++ let gray_resources = |im: Object| Some(Object::Dict(resources_of(vec![("XObject", im), ("ColorSpace", default_gray())])));++++++ let direct = |im: ObjRef| Object::Dict(xobject_dict(&[("Im", im)]));++++++++++++ let appearance = drawing(&mut doc, gray_resources(direct(in_annotation)), &form_entries());++++++ let pattern_entries =++++++ [("PatternType", 1.into()), ("PaintType", 1.into()), ("TilingType", 1.into()), ("XStep", 612.into()), ("YStep", 792.into())];++++++ let pattern = drawing(&mut doc, Some(Object::Dict(resources_of(vec![("XObject", direct(in_pattern))]))), &pattern_entries);++++++ let p = page(&mut doc, &[("A", in_annotation), ("B", in_pattern)], &(draw_each(&["A", "B"]) + "/Pattern cs /P scn 0 0 10 10 re f"));++++++ annotate(&mut doc, p, appearance);++++++ doc.update_dict(p, |d| {++++++ let mut res = d.get(b"Resources").and_then(Object::as_dict).cloned().unwrap();++++++ let mut patterns = Dict::new();++++++ patterns.set(b"P".to_vec(), Object::Ref(pattern));++++++ res.set(b"Pattern".to_vec(), Object::Dict(patterns));++++++ d.set(b"Resources".to_vec(), Object::Dict(res));++++++ })++++++ .unwrap();++++++++++++ // An /XObject dictionary of its own, read for a page, and a form drawn by a page, each also++++++ // used by an appearance under DefaultGray.++++++ let x = doc.add(Object::Dict(xobject_dict(&[("Im", shared_xobjects)])));++++++ let q = page(&mut doc, &[], &draw_each(&["Im"]));++++++ doc.update_dict(q, |d| d.set(b"Resources".to_vec(), Object::Dict(resources_of(vec![("XObject", Object::Ref(x))])))).unwrap();++++++ let appearance = drawing(&mut doc, gray_resources(Object::Ref(x)), &form_entries());++++++ annotate(&mut doc, q, appearance);++++++ let form = drawing(&mut doc, Some(Object::Dict(resources_of(vec![("XObject", direct(shared_form))]))), &form_entries());++++++ let q = page(&mut doc, &[("F", form)], &draw_each(&["F"]));++++++ let appearance = drawing(&mut doc, gray_resources(Object::Dict(xobject_dict(&[("Im", form)]))), &form_entries());++++++ annotate(&mut doc, q, appearance);++++++++++++ // The page names it with generation 1 (it is 0); the appearance with 0.++++++ let q = page(&mut doc, &[("Im", ObjRef { generation: 1, ..other_generation })], &draw_each(&["Im"]));++++++ let appearance = drawing(&mut doc, gray_resources(direct(other_generation)), &form_entries());++++++ annotate(&mut doc, q, appearance);++++++++++++ // Drawn plainly as 0, and as 1 where DefaultGray is in force.++++++ page(&mut doc, &[("Im", generation_under_defaults)], &draw_each(&["Im"]));++++++ let q = page(&mut doc, &[], &draw_each(&["Im"]));++++++ let gray = resources_of(vec![++++++ ("XObject", Object::Dict(xobject_dict(&[("Im", ObjRef { generation: 1, ..generation_under_defaults })]))),++++++ ("ColorSpace", default_gray()),++++++ ]);++++++ doc.update_dict(q, |d| d.set(b"Resources".to_vec(), Object::Dict(gray))).unwrap();++++++++++++ // Drawn plainly, and only listed where DefaultGray is in force, as 0 and as 1.++++++ page(&mut doc, &[("A", listed), ("B", listed_as_1)], &draw_each(&["A", "B"]));++++++ let q = page(&mut doc, &[], "");++++++ let gray = resources_of(vec![++++++ ("XObject", Object::Dict(xobject_dict(&[("A", listed), ("B", ObjRef { generation: 1, ..listed_as_1 })]))),++++++ ("ColorSpace", default_gray()),++++++ ]);++++++ doc.update_dict(q, |d| d.set(b"Resources".to_vec(), Object::Dict(gray))).unwrap();++++++++++++ // Another image drawn on the page lists it as an alternate.++++++ let mut alternate = Dict::new();++++++ alternate.set(b"Image".to_vec(), Object::Ref(in_array));++++++ let holder = image(&mut doc);++++++ doc.update_dict(holder, |d| {++++++ d.set(b"ColorSpace".to_vec(), Object::name("DeviceGray"));++++++ d.set(b"Alternates".to_vec(), Object::Array(vec![Object::Dict(alternate)]));++++++ })++++++ .unwrap();++++++ page(&mut doc, &[("Im", in_array), ("Alt", holder)], &draw_each(&["Im"]));++++++++++++ let kept = [in_annotation, in_pattern, shared_xobjects, shared_form, other_generation, generation_under_defaults, listed, listed_as_1, in_array];++++++ let before = kept.map(|r| stream(&doc, r));++++++ pack_only(&mut doc);++++++ for (i, b) in kept.iter().zip(&before) {++++++ let s = stream(&doc, *i);++++++ assert_eq!((&s.dict, &s.raw), (&b.dict, &b.raw), "{i:?}");++++++ }++++++}++++++++++++/// Black-and-white RGB that the page content and forms the optimizer reads are the only uses of++++++/// becomes grey, however its resources are written: drawn on two pages, by a form, under two++++++/// names on one page; through resources that are an object of their own, shared by two pages,++++++/// whose `/XObject` dictionary is one too; through resources an object of their own with a direct++++++/// `/XObject` dictionary; through resources a page inherits from the page tree; by a form whose++++++/// `/Resources` is a reference; by a form without resources, through its page's; listed under a++++++/// second name nothing draws; through resources an object of their own that a page without++++++/// content lists too; and with an object nothing in the document reaches referring to it as well.++++++#[test]++++++fn black_and_white_rgb_drawn_only_where_the_optimizer_reads_becomes_grey() {++++++ let (mut doc, image) = rgb_page_fixture();++++++ let [everywhere, shared_resources, resources_object, inherited, form_resources_object, no_resources, spare_name, no_contents, unreachable] =++++++ [(); 9].map(|_| image(&mut doc));++++++ let set_resources = |doc: &mut Document, q: ObjRef, res: Object| doc.update_dict(q, |d| d.set(b"Resources".to_vec(), res)).unwrap();++++++++++++ let form =++++++ drawing(&mut doc, Some(Object::Dict(resources_of(vec![("XObject", Object::Dict(xobject_dict(&[("Im", everywhere)])))]))), &form_entries());++++++ page(&mut doc, &[("E", everywhere), ("F", form)], &draw_each(&["E", "F"]));++++++ page(&mut doc, &[("E", everywhere), ("G", everywhere)], &draw_each(&["E", "G"]));++++++++++++ let x = doc.add(Object::Dict(xobject_dict(&[("Im", shared_resources)])));++++++ let res = doc.add(Object::Dict(resources_of(vec![("XObject", Object::Ref(x))])));++++++ for _ in 0..2 {++++++ let q = page(&mut doc, &[], &draw_each(&["Im"]));++++++ set_resources(&mut doc, q, Object::Ref(res));++++++ }++++++ let res = doc.add(Object::Dict(resources_of(vec![("XObject", Object::Dict(xobject_dict(&[("Im", resources_object)])))])));++++++ let q = page(&mut doc, &[], &draw_each(&["Im"]));++++++ set_resources(&mut doc, q, Object::Ref(res));++++++++++++ let q = page(&mut doc, &[], &draw_each(&["I"]));++++++ doc.update_dict(q, |d| {++++++ d.remove(b"Resources");++++++ })++++++ .unwrap();++++++ let pages = doc.root().and_then(|r| doc.get(r).as_dict().and_then(|d| d.reference(b"Pages"))).unwrap();++++++ set_resources(&mut doc, pages, Object::Dict(resources_of(vec![("XObject", Object::Dict(xobject_dict(&[("I", inherited)])))])));++++++++++++ let res = doc.add(Object::Dict(resources_of(vec![("XObject", Object::Dict(xobject_dict(&[("Im", form_resources_object)])))])));++++++ let form = drawing(&mut doc, Some(Object::Ref(res)), &form_entries());++++++ page(&mut doc, &[("F", form)], &draw_each(&["F"]));++++++ let form = drawing(&mut doc, None, &form_entries());++++++ page(&mut doc, &[("F", form), ("Im", no_resources)], &draw_each(&["F"]));++++++++++++ page(&mut doc, &[("C", spare_name), ("D", spare_name)], &draw_each(&["C"]));++++++ let res = doc.add(Object::Dict(resources_of(vec![("XObject", Object::Dict(xobject_dict(&[("Im", no_contents)])))])));++++++ for drawn in [true, false] {++++++ let q = page(&mut doc, &[], &draw_each(&["Im"]));++++++ set_resources(&mut doc, q, Object::Ref(res));++++++ if !drawn {++++++ doc.update_dict(q, |d| {++++++ d.remove(b"Contents");++++++ })++++++ .unwrap();++++++ }++++++ }++++++++++++ page(&mut doc, &[("Im", unreachable)], &draw_each(&["Im"]));++++++ // A form nothing refers to, drawing it under DefaultGray.++++++ let orphan = resources_of(vec![("XObject", Object::Dict(xobject_dict(&[("Im", unreachable)]))), ("ColorSpace", default_gray())]);++++++ drawing(&mut doc, Some(Object::Dict(orphan)), &form_entries());++++++++++++ let grey = [everywhere, shared_resources, resources_object, inherited, form_resources_object, no_resources, spare_name, no_contents, unreachable];++++++ assert_eq!(pack_only(&mut doc), (0, grey.len()));++++++ for i in grey {++++++ let s = stream(&doc, i);++++++ assert_eq!((s.dict.get(b"ColorSpace"), s.dict.int(b"BitsPerComponent")), (Some(&Object::name("DeviceGray")), Some(1)), "{i:?}");++++++ }++++++}++++++++++++/// LibreOffice writes one resources object for a page and its `/Pages` node, and a transparency++++++/// group's form whose `/Resources` is that same object, which the object lists in turn. Black-++++++/// and-white RGB in it becomes grey: every reference is one the page walk reads, the cycle++++++/// included. Drawn from outside as well, by an appearance under `/DefaultGray` that draws the++++++/// form, it stays RGB.++++++#[test]++++++fn black_and_white_rgb_in_resources_its_page_tree_and_a_form_share_becomes_grey() {++++++ for outside in [false, true] {++++++ let (mut doc, image) = rgb_page_fixture();++++++ let img = image(&mut doc);++++++ let res = doc.add(Object::Dict(Dict::new()));++++++ let form = drawing(&mut doc, Some(Object::Ref(res)), &form_entries());++++++ doc.update_dict(res, |d| d.set(b"XObject".to_vec(), Object::Dict(xobject_dict(&[("Im", img), ("Tr", form)])))).unwrap();++++++ let p = page(&mut doc, &[], &draw_each(&["Im", "Tr"]));++++++ let pages = doc.root().and_then(|r| doc.get(r).as_dict().and_then(|d| d.reference(b"Pages"))).unwrap();++++++ for holder in [p, pages] {++++++ doc.update_dict(holder, |d| d.set(b"Resources".to_vec(), Object::Ref(res))).unwrap();++++++ }++++++ if outside {++++++ let gray = resources_of(vec![("XObject", Object::Dict(xobject_dict(&[("Im", form)]))), ("ColorSpace", default_gray())]);++++++ let appearance = drawing(&mut doc, Some(Object::Dict(gray)), &form_entries());++++++ annotate(&mut doc, p, appearance);++++++ }++++++ let before = stream(&doc, img);++++++ pack_only(&mut doc);++++++ let s = stream(&doc, img);++++++ if outside {++++++ assert_eq!((&s.dict, &s.raw), (&before.dict, &before.raw), "drawn from outside too");++++++ } else {++++++ assert_eq!((s.dict.get(b"ColorSpace"), s.dict.int(b"BitsPerComponent")), (Some(&Object::name("DeviceGray")), Some(1)));++++++ }++++++ }++++++}++++++++++++/// Black-and-white images above 450 ppi are averaged down to 300 ppi, by default: 1-bit Flate, CCITT++++++/// Group 4 (alone and behind ASCIIHexDecode), an image mask (its inverting decode array stays), and++++++/// eight-bit grey and RGB of only black and white (the RGB also the other way round, with a decode++++++/// array that inverts it, so its ties are 1s), all drawn at 600 ppi, are stored at half the size (as++++++/// Group 4, or 1-bit Flate when that is smaller, as it is on this clean text), each new pixel the++++++/// majority of the 2 × 2 it covers (a tie black, or for the mask painted). Left at their size: an image at 400 ppi (stored++++++/// again as Group 4), a Group 4 one at 400 ppi (not even decoded), one behind ASCIIHexDecode at++++++/// 400 ppi (stored again as Group 4 alone), and one with a soft mask. The page looks the same at++++++/// screen size. With `downsample` off nothing is resampled; with Retain, Flate stays Flate, CCITT++++++/// stays CCITT, and eight-bit grey and RGB are left to the grey and colour settings.++++++#[test]++++++fn black_and_white_images_above_450_ppi_are_averaged_down_to_300() {++++++ let mut doc = Document::new_empty();++++++ let (w, h) = (1200u32, 480u32);++++++ let text = bilevel(w, h, false);++++++ let grey = [("BitsPerComponent", 1.into()), ("ColorSpace", Object::name("DeviceGray"))];++++++ let g4 = |doc: &mut Document, entries: &[(&str, Object)]| {++++++ let mut d = Dict::new();++++++ d.set(b"Subtype".to_vec(), Object::name("Image"));++++++ d.set(b"Width".to_vec(), Object::Int(w.into()));++++++ d.set(b"Height".to_vec(), Object::Int(h.into()));++++++ d.set(b"Filter".to_vec(), Object::Array(vec![Object::name("CCITTFaxDecode")]));++++++ let mut parms = Dict::new();++++++ parms.set(b"K".to_vec(), Object::Int(-1));++++++ parms.set(b"Columns".to_vec(), Object::Int(w.into()));++++++ d.set(b"DecodeParms".to_vec(), Object::Array(vec![Object::Dict(parms)]));++++++ for (k, v) in entries {++++++ d.set(k.as_bytes().to_vec(), v.clone());++++++ }++++++ doc.add(Object::Stream(Stream::from_raw(d, pdfcraft_filters::encode_g4(&text, w, h).unwrap())))++++++ };++++++ // Group 4 behind ASCIIHexDecode, its parameters second in the array.++++++ let behind_hex = |doc: &mut Document| {++++++ let r = g4(doc, &grey);++++++ let s = stream(doc, r);++++++ let mut d = s.dict.clone();++++++ let parms = d.get(b"DecodeParms").and_then(Object::as_array).and_then(|a| a.first()).cloned().unwrap();++++++ d.set(b"Filter".to_vec(), Object::Array(vec![Object::name("ASCIIHexDecode"), Object::name("CCITTFaxDecode")]));++++++ d.set(b"DecodeParms".to_vec(), Object::Array(vec![Object::Null, parms]));++++++ let hex = s.raw.iter().map(|b| format!("{b:02x}")).chain([">".to_string()]).collect::<String>().into_bytes();++++++ doc.set(r, Object::Stream(Stream::from_raw(d, hex)));++++++ r++++++ };++++++ let flate = mono_image(&mut doc, w, h, &text, None, &grey);++++++ let fax = g4(&mut doc, &grey);++++++ let hex_fax = behind_hex(&mut doc);++++++ let hex_at_400 = behind_hex(&mut doc);++++++ let decode = Object::Array(vec![1.into(), 0.into()]);++++++ let mask = mono_image(&mut doc, w, h, &text, None, &[("ImageMask", Object::Bool(true)), ("Decode", decode.clone())]);++++++ let mut d = Dict::new();++++++ d.set(b"Subtype".to_vec(), Object::name("Image"));++++++ d.set(b"Width".to_vec(), Object::Int(w.into()));++++++ d.set(b"Height".to_vec(), Object::Int(h.into()));++++++ d.set(b"BitsPerComponent".to_vec(), Object::Int(8));++++++ d.set(b"ColorSpace".to_vec(), Object::name("DeviceGray"));++++++ let eight = doc.add(Object::Stream(Stream::flate(d.clone(), &eight_bit(&text, w, h))));++++++ d.set(b"ColorSpace".to_vec(), Object::name("DeviceRGB"));++++++ let rgb = doc.add(Object::Stream(Stream::flate(d.clone(), &samples_of(&text, w, h, [&[0, 0, 0], &[255, 255, 255]], 8))));++++++ d.set(b"Decode".to_vec(), Object::Array([1, 0, 1, 0, 1, 0].map(Object::Int).to_vec()));++++++ let rgb_inverted = doc.add(Object::Stream(Stream::flate(d, &samples_of(&text, w, h, [&[255, 255, 255], &[0, 0, 0]], 8))));++++++ let at_400 = mono_image(&mut doc, w, h, &text, None, &grey);++++++ let fax_at_400 = g4(&mut doc, &grey);++++++ let mut sm = Dict::new();++++++ sm.set(b"Subtype".to_vec(), Object::name("Image"));++++++ sm.set(b"Width".to_vec(), Object::Int(2));++++++ sm.set(b"Height".to_vec(), Object::Int(1));++++++ sm.set(b"BitsPerComponent".to_vec(), Object::Int(8));++++++ sm.set(b"ColorSpace".to_vec(), Object::name("DeviceGray"));++++++ let smask = doc.add(Object::Stream(Stream::flate(sm, &[255, 200])));++++++ let soft = mono_image(&mut doc, w, h, &text, None, &[grey[0].clone(), grey[1].clone(), ("SMask", Object::Ref(smask))]);++++++ // 144 × 57.6 pt is 2 × 0.8 in: 600 ppi. 216 × 86.4 pt is 400 ppi.++++++ page(++++++ &mut doc,++++++ &[++++++ ("A", flate),++++++ ("B", fax),++++++ ("C", mask),++++++ ("D", eight),++++++ ("E", at_400),++++++ ("F", fax_at_400),++++++ ("G", soft),++++++ ("H", hex_fax),++++++ ("I", hex_at_400),++++++ ("J", rgb),++++++ ("K", rgb_inverted),++++++ ],++++++ "q 144 0 0 57.6 20 700 cm /A Do Q q 144 0 0 57.6 200 700 cm /B Do Q q 0 0 1 rg 144 0 0 57.6 380 700 cm /C Do Q \++++++ q 144 0 0 57.6 20 600 cm /D Do Q q 216 0 0 86.4 200 580 cm /E Do Q q 216 0 0 86.4 20 480 cm /F Do Q \++++++ q 144 0 0 57.6 260 480 cm /G Do Q q 144 0 0 57.6 430 600 cm /H Do Q q 216 0 0 86.4 20 360 cm /I Do Q q 144 0 0 57.6 260 380 cm /J Do Q \++++++ q 144 0 0 57.6 430 480 cm /K Do Q",++++++ );++++++ let before = render(&doc);++++++ let raw = |doc: &Document, r: ObjRef| stream(doc, r).raw;++++++ let size = |doc: &Document, r: ObjRef| {++++++ let d = stream(doc, r).dict;++++++ (d.int(b"Width").unwrap(), d.int(b"Height").unwrap())++++++ };++++++ // Each new pixel: 1 when more than two of the 2 × 2 it covers are, or two when 1 is the dark++++++ // sample (the mask's decode array inverts it, so its painted part is 1).++++++ let stride = (w as usize).div_ceil(8);++++++ let bit = |x: usize, y: usize| text[y * stride + x / 8] & (0x80 >> (x % 8)) != 0;++++++ let halve = |dark_one: bool| {++++++ let mut out = vec![0u8; (w as usize / 2).div_ceil(8) * h as usize / 2];++++++ for y in 0..h as usize / 2 {++++++ for x in 0..w as usize / 2 {++++++ let ones = [(0, 0), (1, 0), (0, 1), (1, 1)].iter().filter(|(dx, dy)| bit(2 * x + dx, 2 * y + dy)).count();++++++ if ones > 2 || (dark_one && ones == 2) {++++++ out[y * (w as usize / 2).div_ceil(8) + x / 8] |= 0x80 >> (x % 8);++++++ }++++++ }++++++ }++++++ out++++++ };++++++ let (halved, halved_mask) = (halve(false), halve(true));++++++ assert_ne!(halved, halved_mask, "the picture has ties");++++++++++++ // The grey and colour settings left alone too: an image of more bits would otherwise take++++++ // them when smaller.++++++ let mut off = doc.clone();++++++ let keep = ImageSettings { downsample: false, target_ppi: 150.0, above_ppi: 225.0, compression: Compression::Retain };++++++ let mono = MonoSettings { downsample: false, ..MonoSettings::REDUCE };++++++ let r = optimize(&mut off, &Settings { mono, gray: keep, color: keep, ..Settings::default() }).unwrap();++++++ assert_eq!(r.images_resampled, 0, "{r:?}");++++++ assert!([flate, fax, mask, eight, hex_fax, rgb, rgb_inverted].iter().all(|i| size(&off, *i) == (1200, 480)));++++++++++++ let mut kept = doc.clone();++++++ let r = optimize(&mut kept, &Settings { mono: RETAIN, ..Settings::default() }).unwrap();++++++ // Not the inverted RGB: the colour settings leave an image with a decode array alone.++++++ assert_eq!(r.images_resampled, 6, "{r:?}");++++++ assert_eq!(stream(&kept, flate).dict.name(b"Filter"), Some(&b"FlateDecode"[..]), "Retain: Flate stays Flate");++++++ for i in [fax, hex_fax] {++++++ assert_eq!(stream(&kept, i).dict.name(b"Filter"), Some(&b"CCITTFaxDecode"[..]), "and CCITT stays CCITT: {i:?}");++++++ }++++++ assert_eq!(raw(&kept, hex_at_400), raw(&doc, hex_at_400), "and nothing else changes");++++++ for i in [flate, fax, hex_fax] {++++++ assert_eq!((size(&kept, i), kept.decoded_image(&stream(&kept, i)).unwrap()), ((600, 240), halved.clone()), "{i:?}");++++++ }++++++ let bits = [eight, rgb, rgb_inverted].map(|i| stream(&kept, i).dict.int(b"BitsPerComponent"));++++++ assert_eq!(bits, [Some(8); 3], "Retain leaves eight bits to the grey and colour settings");++++++++++++ let untouched = [fax_at_400].map(|r| raw(&doc, r));++++++ let hex_len = raw(&doc, hex_at_400).len();++++++ let r = optimize(&mut doc, &Settings::default()).unwrap();++++++ assert_eq!((r.images_resampled, r.images_recompressed), (7, 3), "{r:?}");++++++ assert_eq!(stream(&doc, rgb).dict.get(b"ColorSpace"), Some(&Object::name("DeviceGray")));++++++ for i in [flate, fax, mask, eight, hex_fax, rgb] {++++++ let s = stream(&doc, i);++++++ assert_eq!((size(&doc, i), s.dict.int(b"BitsPerComponent")), ((600, 240), if i == mask { None } else { Some(1) }));++++++ assert!(matches!(s.dict.name(b"Filter"), Some(b"CCITTFaxDecode" | b"FlateDecode")), "{i:?}");++++++ assert_eq!(doc.decoded_image(&s).unwrap(), if i == mask { halved_mask.clone() } else { halved.clone() }, "{i:?}");++++++ }++++++ assert_eq!(stream(&doc, mask).dict.get(b"Decode"), Some(&decode), "the decode array stays");++++++ // Grey now, with grey's decode pair, which makes 1 black: its ties are black too.++++++ let s = stream(&doc, rgb_inverted);++++++ let inverting = Object::Array(vec![1.into(), 0.into()]);++++++ assert_eq!(++++++ (size(&doc, rgb_inverted), s.dict.get(b"ColorSpace"), s.dict.get(b"Decode")),++++++ ((600, 240), Some(&Object::name("DeviceGray")), Some(&inverting))++++++ );++++++ assert_eq!(doc.decoded_image(&s).unwrap(), halved.iter().map(|b| !b).collect::<Vec<u8>>(), "the same picture, ties black");++++++ for i in [at_400, soft, hex_at_400] {++++++ assert_eq!((size(&doc, i), stream(&doc, i).dict.name(b"Filter")), ((1200, 480), Some(&b"CCITTFaxDecode"[..])), "{i:?}");++++++ }++++++ assert!(raw(&doc, hex_at_400).len() < hex_len, "the ASCIIHexDecode is dropped");++++++ assert_eq!(doc.decoded_image(&stream(&doc, hex_at_400)).unwrap(), text, "and the picture kept");++++++ assert_eq!([fax_at_400].map(|r| raw(&doc, r)), untouched);++++++ let after = render(&doc);++++++ let differ = before.iter().zip(&after).filter(|(a, b)| a.abs_diff(**b) > 64).count();++++++ assert!(differ * 200 < before.len(), "{differ} of {} channel values differ visibly", before.len());++++++}++++++++++++/// Monochrome downsampling leaves a halftone or a dither at its resolution, as most new pixels++++++/// would cover both black and white and taking the sample covering more would turn its tones++++++/// solid: a 50% checkerboard, a 25% ordered dither and an error-diffused one, each at 600 ppi.++++++/// Text at 600 ppi, which covers both only along its edges, is averaged down. Rows no wider than++++++/// a fax row (`MAX_CCITT_COLUMNS`) are averaged down too, but not one column wider: the averaging++++++/// keeps a counter for each column.++++++#[test]++++++fn monochrome_downsampling_leaves_halftones_and_overwide_rows_at_their_resolution() {++++++ let (w, h) = (1200u32, 480u32);++++++ let stride = (w as usize).div_ceil(8);++++++ let pattern = |white: &dyn Fn(usize, usize) -> bool| {++++++ let mut data = vec![0u8; stride * h as usize];++++++ for y in 0..h as usize {++++++ for x in 0..w as usize {++++++ if white(x, y) {++++++ data[y * stride + x / 8] |= 0x80 >> (x % 8);++++++ }++++++ }++++++ }++++++ data++++++ };++++++ let diffused = dithered(w, h);++++++ let grey = [("BitsPerComponent", 1.into()), ("ColorSpace", Object::name("DeviceGray"))];++++++ let mut doc = Document::new_empty();++++++ let text = mono_image(&mut doc, w, h, &bilevel(w, h, false), None, &grey);++++++ let halftones =++++++ [pattern(&|x, y| (x + y) % 2 == 0), pattern(&|x, y| x % 2 == 1 || y % 2 == 1), pattern(&|x, y| diffused[y * w as usize + x] == 255)]++++++ .map(|data| mono_image(&mut doc, w, h, &data, None, &grey));++++++ // 144 × 57.6 pt is 600 ppi.++++++ let names = ["T", "A", "B", "C"];++++++ let content: String = (0..4).map(|i| format!("q 144 0 0 57.6 {} 600 cm /{} Do Q ", 6 + 150 * i, names[i])).collect();++++++ page(&mut doc, &names.into_iter().zip([text, halftones[0], halftones[1], halftones[2]]).collect::<Vec<_>>(), &content);++++++ optimize(&mut doc, &Settings::default()).unwrap();++++++ let size = |r: ObjRef| {++++++ let d = stream(&doc, r).dict;++++++ (d.int(b"Width"), d.int(b"Height"))++++++ };++++++ assert_eq!(size(text), (Some(600), Some(240)), "text");++++++ for (i, r) in halftones.iter().enumerate() {++++++ assert_eq!(size(*r), (Some(1200), Some(480)), "halftone {i}");++++++ }++++++++++++ for (columns, resampled) in [(pdfcraft_filters::MAX_CCITT_COLUMNS, 1), (pdfcraft_filters::MAX_CCITT_COLUMNS + 1, 0)] {++++++ let mut doc = Document::new_empty();++++++ let white = vec![0xFF; (columns as usize).div_ceil(8) * 2];++++++ let img = mono_image(&mut doc, columns, 2, &white, None, &grey);++++++ // Far above 450 ppi both ways.++++++ page(&mut doc, &[("A", img)], "q 612 0 0 0.1 0 400 cm /A Do Q");++++++ let r = optimize(&mut doc, &Settings::default()).unwrap();++++++ assert_eq!(r.images_resampled, resampled, "{columns} columns: {r:?}");++++++ }++++++}++++++++++++/// A fax image behind a decompression bomb is left alone: the filters before its decoder may++++++/// produce no more than a fax code of its size can take (about a byte a pixel), not the 1 GiB++++++/// limit. Here a Group 4 page at 600 ppi behind Flate, with four megabytes of zeros after its++++++/// code; without them it is averaged down.++++++#[test]++++++fn a_fax_image_behind_a_decompression_bomb_is_left_alone() {++++++ let (w, h) = (1200u32, 480u32);++++++ let g4 = pdfcraft_filters::encode_g4(&bilevel(w, h, false), w, h).unwrap();++++++ for padding in [0, 4 << 20] {++++++ let mut doc = Document::new_empty();++++++ let mut code = g4.clone();++++++ code.resize(g4.len() + padding, 0);++++++ let mut d = Dict::new();++++++ d.set(b"Subtype".to_vec(), Object::name("Image"));++++++ d.set(b"Width".to_vec(), Object::Int(w.into()));++++++ d.set(b"Height".to_vec(), Object::Int(h.into()));++++++ d.set(b"BitsPerComponent".to_vec(), Object::Int(1));++++++ d.set(b"ColorSpace".to_vec(), Object::name("DeviceGray"));++++++ d.set(b"Filter".to_vec(), Object::Array(vec![Object::name("FlateDecode"), Object::name("CCITTFaxDecode")]));++++++ let mut parms = Dict::new();++++++ parms.set(b"K".to_vec(), Object::Int(-1));++++++ parms.set(b"Columns".to_vec(), Object::Int(w.into()));++++++ d.set(b"DecodeParms".to_vec(), Object::Array(vec![Object::Null, Object::Dict(parms)]));++++++ let img = doc.add(Object::Stream(Stream::from_raw(d, pdfcraft_filters::encode_flate(&code))));++++++ // 144 × 57.6 pt is 600 ppi.++++++ page(&mut doc, &[("A", img)], "q 144 0 0 57.6 20 600 cm /A Do Q");++++++ let before = stream(&doc, img).raw;++++++ let r = optimize(&mut doc, &Settings::default()).unwrap();++++++ if padding == 0 {++++++ assert_eq!(r.images_resampled, 1, "{r:?}");++++++ } else {++++++ assert_eq!((r.images_resampled, r.images_recompressed), (0, 0), "{r:?}");++++++ assert_eq!(stream(&doc, img).raw, before);++++++ }++++++ }++++++}++++++++++++/// A CCITT image `w` × `h` coded as Group 4 from `bits`, behind ASCIIHexDecode when `hex`.++++++fn g4_image(doc: &mut Document, bits: &[u8], (w, h): (u32, u32), hex: bool) -> ObjRef {++++++ let g4 = pdfcraft_filters::encode_g4(bits, w, h).unwrap();++++++ let mut d = Dict::new();++++++ d.set(b"Subtype".to_vec(), Object::name("Image"));++++++ d.set(b"Width".to_vec(), Object::Int(w.into()));++++++ d.set(b"Height".to_vec(), Object::Int(h.into()));++++++ d.set(b"BitsPerComponent".to_vec(), Object::Int(1));++++++ d.set(b"ColorSpace".to_vec(), Object::name("DeviceGray"));++++++ let mut parms = Dict::new();++++++ parms.set(b"K".to_vec(), Object::Int(-1));++++++ parms.set(b"Columns".to_vec(), Object::Int(w.into()));++++++ let data = if hex {++++++ d.set(b"Filter".to_vec(), Object::Array(vec![Object::name("ASCIIHexDecode"), Object::name("CCITTFaxDecode")]));++++++ d.set(b"DecodeParms".to_vec(), Object::Array(vec![Object::Null, Object::Dict(parms)]));++++++ g4.iter().flat_map(|b| format!("{b:02x}").into_bytes()).chain(*b">").collect()++++++ } else {++++++ d.set(b"Filter".to_vec(), Object::name("CCITTFaxDecode"));++++++ d.set(b"DecodeParms".to_vec(), Object::Dict(parms));++++++ g4++++++ };++++++ doc.add(Object::Stream(Stream::from_raw(d, data)))++++++}++++++++++++/// What Monochrome Images leaves alone and what it may still do. A Group 4 halftone above 450 ppi++++++/// isn't resampled, so it stays byte for byte: alone, by default; behind ASCIIHexDecode, with++++++/// Retain (by default it is stored again as Group 4 alone). Under Retain a resampled Flate scan++++++/// stays Flate though Group 4 would be smaller. A busy Group 4 image behind ASCIIHexDecode, whose++++++/// code is more than three times its raster, decodes within a fax code's bound and is stored++++++/// again as Group 4 alone. Sixteen-bit grey of only 0x0000 and 0xFFFF isn't eight-bit black and++++++/// white, and keeps its bytes.++++++#[test]++++++fn monochrome_images_keep_what_they_should() {++++++ let (w, h) = (1200u32, 480u32);++++++ let stride = (w as usize).div_ceil(8);++++++ let checker: Vec<u8> = (0..h as usize).flat_map(|y| vec![if y % 2 == 0 { 0xAA } else { 0x55 }; stride]).collect();++++++ let mut seed = 0x2545_F491_4F6C_DD1Du64;++++++ let mut next = move || {++++++ seed ^= seed << 13;++++++ seed ^= seed >> 7;++++++ seed ^= seed << 17;++++++ seed++++++ };++++++ // Twelve dark bands a row, their edges ragged by up to five samples, as a scan's are.++++++ let mut ragged = vec![0xFFu8; stride * h as usize];++++++ for y in 0..h as usize {++++++ for band in 0..12 {++++++ let (x0, x1) = (band * 100 + (next() % 5) as usize, band * 100 + 50 + (next() % 5) as usize);++++++ for x in x0..x1.min(w as usize) {++++++ ragged[y * stride + x / 8] &= !(0x80 >> (x % 8));++++++ }++++++ }++++++ }++++++ let busy: Vec<u8> = (0..256).flat_map(|y| [if y % 2 == 0 { 0xAA } else { 0xFF }; 32]).collect();++++++ let build = || {++++++ let mut doc = Document::new_empty();++++++ let alone = g4_image(&mut doc, &checker, (w, h), false);++++++ let wrapped = g4_image(&mut doc, &checker, (w, h), true);++++++ let grey = [("BitsPerComponent", 1.into()), ("ColorSpace", Object::name("DeviceGray"))];++++++ let scan = mono_image(&mut doc, w, h, &ragged, None, &grey);++++++ let fax = g4_image(&mut doc, &busy, (256, 256), true);++++++ let mut d = Dict::new();++++++ d.set(b"Subtype".to_vec(), Object::name("Image"));++++++ d.set(b"Width".to_vec(), Object::Int(w.into()));++++++ d.set(b"Height".to_vec(), Object::Int(h.into()));++++++ d.set(b"BitsPerComponent".to_vec(), Object::Int(16));++++++ d.set(b"ColorSpace".to_vec(), Object::name("DeviceGray"));++++++ let samples: Vec<u8> = eight_bit(&bilevel(w, h, false), w, h).iter().flat_map(|v| [*v, *v]).collect();++++++ let deep = doc.add(Object::Stream(Stream::flate(d, &samples)));++++++ // 144 × 57.6 pt is 600 ppi; 46.08 pt for 256 samples is 400 ppi.++++++ page(++++++ &mut doc,++++++ &[("A", alone), ("B", wrapped), ("C", scan), ("D", fax), ("E", deep)],++++++ "q 144 0 0 57.6 20 700 cm /A Do Q q 144 0 0 57.6 200 700 cm /B Do Q q 144 0 0 57.6 20 600 cm /C Do Q \++++++ q 46.08 0 0 46.08 200 600 cm /D Do Q q 144 0 0 57.6 20 500 cm /E Do Q",++++++ );++++++ (doc, [alone, wrapped, scan, fax, deep])++++++ };++++++ let raw = |doc: &Document, r: ObjRef| stream(doc, r).raw;++++++ let filters = |doc: &Document, r: ObjRef| stream(doc, r).filters().len();++++++++++++ let (mut doc, [alone, wrapped, scan, fax, deep]) = build();++++++ let before = [alone, deep].map(|r| raw(&doc, r));++++++ optimize(&mut doc, &Settings::default()).unwrap();++++++ assert_eq!([alone, deep].map(|r| raw(&doc, r)), before, "a Group 4 halftone alone, and sixteen-bit grey");++++++ assert_eq!(filters(&doc, wrapped), 1, "a wrapped Group 4 halftone is stored again alone by default");++++++ assert_eq!(stream(&doc, scan).dict.name(b"Filter"), Some(&b"CCITTFaxDecode"[..]), "the scan: Group 4 is smaller");++++++ assert_eq!((stream(&doc, fax).dict.name(b"Filter"), filters(&doc, fax)), (Some(&b"CCITTFaxDecode"[..]), 1), "the busy fax image");++++++++++++ let (mut doc, [_, wrapped, scan, _, _]) = build();++++++ let before = raw(&doc, wrapped);++++++ let r = optimize(&mut doc, &Settings { mono: RETAIN, ..Settings::default() }).unwrap();++++++ assert_eq!(raw(&doc, wrapped), before, "Retain: a wrapped Group 4 halftone stays as it is");++++++ let s = stream(&doc, scan);++++++ assert_eq!((s.dict.int(b"Width"), s.dict.name(b"Filter")), (Some(600), Some(&b"FlateDecode"[..])), "Retain: Flate stays Flate: {r:?}");++++++}++++++++++++/// `rows` coded as CCITT Group 3, one-dimensional (`/K 0`): each row its runs in turn, white first,++++++/// with ITU-T T.4's terminating codes for the few lengths used here. With `on_bytes`, each row++++++/// starts on a byte: `Some(false)`, with no end-of-line codes (TIFF's Modified Huffman); `Some(true)`,++++++/// after an end-of-line code that the fill ends on a byte (T.4's fill, as TIFF writes it).++++++fn group_3(rows: &[&[u32]], mixed: bool, on_bytes: Option<bool>) -> Vec<u8> {++++++ let code = |white: bool, run: u32| match (white, run) {++++++ (true, 0) => "00110101",++++++ (true, 1) => "000111",++++++ (false, 1) => "010",++++++ (true, 8) => "10011",++++++ (true, 16) => "101010",++++++ (true, 32) => "00011011",++++++ (false, 8) => "000101",++++++ (false, 16) => "0000010111",++++++ (false, 32) => "000001101010",++++++ _ => panic!("no code here for a run of {run}"),++++++ };++++++ let mut bits = String::new();++++++ for row in rows {++++++ let codes = mixed || on_bytes == Some(true);++++++ if on_bytes.is_some() {++++++ // The end-of-line code is 12 bits.++++++ while !(bits.len() + if codes { 12 } else { 0 }).is_multiple_of(8) {++++++ bits.push('0');++++++ }++++++ }++++++ if codes {++++++ bits.push_str("000000000001");++++++ }++++++ // Mixed coding (/K above 0): a 1 bit after the code, the row one-dimensional.++++++ if mixed {++++++ bits.push('1');++++++ }++++++ row.iter().enumerate().for_each(|(i, run)| bits.push_str(code(i % 2 == 0, *run)));++++++ }++++++ bits.as_bytes().chunks(8).map(|c| c.iter().enumerate().fold(0u8, |b, (i, d)| b | (u8::from(*d == b'1') << (7 - i)))).collect()++++++}++++++++++++/// A Group 3 fax image is stored again as Group 4 when that is smaller, the same picture (to the++++++/// pixel on the page, against the picture in Flate); with Retain it stays Group 3. One-dimensional (/K 0) and mixed (/K 1, with++++++/// end-of-line codes) alike, and rows on bytes, with no codes and with codes the fill ends on a byte++++++/// (without `/EndOfLine`, which reading by the flag misread).++++++#[test]++++++fn group_3_fax_images_become_group_4() {++++++ let (w, h) = (64u32, 64u32);++++++ let runs: Vec<&[u32]> = [&[32, 32][..], &[16; 4], &[8; 8], &[0, 16, 16, 32]].into_iter().flat_map(|r| std::iter::repeat_n(r, 16)).collect();++++++ // White is 1, as CCITTFaxDecode gives it without /BlackIs1.++++++ let mut bits = Vec::new();++++++ for row in &runs {++++++ let mut packed = [0u8; 8];++++++ let mut x = 0;++++++ for (i, run) in row.iter().enumerate() {++++++ for p in x..x + *run as usize {++++++ if i % 2 == 0 {++++++ packed[p / 8] |= 0x80 >> (p % 8);++++++ }++++++ }++++++ x += *run as usize;++++++ }++++++ bits.extend(packed);++++++ }++++++ for (k, on_bytes) in [(0, None), (1, None), (0, Some(false)), (0, Some(true)), (1, Some(true))] {++++++ let g3 = group_3(&runs, k > 0, on_bytes);++++++ let (end_of_line, encoded_byte_align) = (k > 0 && on_bytes.is_none(), on_bytes.is_some());++++++ let p = pdfcraft_filters::CcittParams { k, columns: w.into(), end_of_line, encoded_byte_align, ..Default::default() };++++++ assert_eq!(pdfcraft_filters::decode_ccitt(&g3, &p, h).unwrap(), bits, "/K {k}, on bytes {on_bytes:?}: the Group 3 data is the picture");++++++++++++ let mut doc = Document::new_empty();++++++ let mut d = Dict::new();++++++ d.set(b"Subtype".to_vec(), Object::name("Image"));++++++ d.set(b"Width".to_vec(), Object::Int(w.into()));++++++ d.set(b"Height".to_vec(), Object::Int(h.into()));++++++ d.set(b"BitsPerComponent".to_vec(), Object::Int(1));++++++ d.set(b"ColorSpace".to_vec(), Object::name("DeviceGray"));++++++ // The page with the picture in Flate, as it should look.++++++ let mut control = Document::new_empty();++++++ let flate = control.add(Object::Stream(Stream::flate(d.clone(), &bits)));++++++ page(&mut control, &[("A", flate)], "q 64 0 0 64 100 600 cm /A Do Q");++++++ d.set(b"Filter".to_vec(), Object::name("CCITTFaxDecode"));++++++ let mut parms = Dict::new();++++++ parms.set(b"K".to_vec(), Object::Int(k));++++++ parms.set(b"EndOfLine".to_vec(), Object::Bool(end_of_line));++++++ parms.set(b"EncodedByteAlign".to_vec(), Object::Bool(encoded_byte_align));++++++ parms.set(b"Columns".to_vec(), Object::Int(w.into()));++++++ parms.set(b"Rows".to_vec(), Object::Int(h.into()));++++++ d.set(b"DecodeParms".to_vec(), Object::Dict(parms));++++++ let fax = doc.add(Object::Stream(Stream::from_raw(d, g3.clone())));++++++ page(&mut doc, &[("A", fax)], "q 64 0 0 64 100 600 cm /A Do Q");++++++++++++ let mut kept = doc.clone();++++++ optimize(&mut kept, &Settings { mono: RETAIN, ..Settings::default() }).unwrap();++++++ assert_eq!(stream(&kept, fax).raw[..], g3[..], "/K {k}, on bytes {on_bytes:?}: Retain keeps Group 3");++++++++++++ let r = optimize(&mut doc, &Settings::default()).unwrap();++++++ assert_eq!((r.images_resampled, r.images_recompressed), (0, 1), "/K {k}, on bytes {on_bytes:?}: {r:?}");++++++ let s = stream(&doc, fax);++++++ assert_eq!(doc.fax_params(&s).map(|p| p.k), Some(-1), "/K {k}, on bytes {on_bytes:?}: Group 4");++++++ assert!(s.raw.len() < g3.len(), "{} bytes, from {}", s.raw.len(), g3.len());++++++ assert_eq!(doc.decoded_image(&s).unwrap(), bits, "/K {k}, on bytes {on_bytes:?}: the same picture");++++++ assert!(render(&doc) == render(&control), "/K {k}, on bytes {on_bytes:?}: the page looks as the picture does");++++++ }++++ }+++++++++ /// The images of a document that are images, by object number.+++++ fn image_refs(doc: &Document) -> Vec<ObjRef> {+++++ doc.object_numbers()+++++ .into_iter()+++++ .map(|num| ObjRef { num, generation: doc.generation(num) })+++++ .filter(|r| matches!(&*doc.get(*r), Object::Stream(s) if s.dict.name(b"Subtype") == Some(b"Image")))+++++ .collect()+++++ }++++++++++ /// Black-and-white images as lossless JBIG2: the page looks the same to the pixel (so+++++ /// JBIG2Decode gives black as 0, as the encoder assumes), and scan-like text comes out smaller+++++ /// than as Group 4. JBIG2Decode is PDF 1.4, so a PDF 1.3 document gets `/Version /1.4` in its+++++ /// catalog.+++++ #[test]+++++ fn black_and_white_images_become_jbig2() {+++++ let mut doc = Document::new_empty();+++++ let (w, h) = (1200, 480);+++++ let text = bilevel(w, h, false);+++++ let gray = mono_image(&mut doc, w, h, &text, None, &[("BitsPerComponent", 1.into()), ("ColorSpace", Object::name("DeviceGray"))]);+++++ let decode = Object::Array(vec![1.into(), 0.into()]);+++++ let mask = mono_image(&mut doc, w, h, &text, None, &[("ImageMask", Object::Bool(true)), ("Decode", decode.clone())]);+++++ let indexed_cs = Object::Array(vec![+++++ Object::name("Indexed"),+++++ Object::name("DeviceRGB"),+++++ 1.into(),+++++ Object::String(pdfcraft_cos::PdfString::literal(vec![0xC0, 0x10, 0x10, 0xF8, 0xF0, 0xE0])),+++++ ]);+++++ let indexed = mono_image(&mut doc, w, h, &text, None, &[("BitsPerComponent", 1.into()), ("ColorSpace", indexed_cs.clone())]);+++++ page(+++++ &mut doc,+++++ &[("G", gray), ("M", mask), ("I", indexed)],+++++ "q 300 0 0 120 20 660 cm /G Do Q q 0 0.4 0.8 rg 300 0 0 120 320 660 cm /M Do Q q 300 0 0 120 20 520 cm /I Do Q",+++++ );+++++ // The same document, as PDF 1.3.+++++ let mut bytes = write_full(&doc, &SaveOptions { object_streams: false, ..SaveOptions::default() }).unwrap();+++++ bytes[..8].copy_from_slice(b"%PDF-1.3");+++++ let doc = Document::open(Arc::new(bytes)).unwrap();+++++ assert_eq!(doc.version(), "1.3");+++++ let before = render(&doc);++++++++++ let mut g4 = doc.clone();+++++ let as_g4 = optimize(&mut g4, &Settings::default()).unwrap();+++++ let mut jbig2 = doc.clone();-- let r = optimize(&mut jbig2, &Settings { mono: MonoCompression::Jbig2, ..Settings::default() }).unwrap();+++++++ let settings = Settings { mono: MonoSettings { compression: MonoCompression::Jbig2, ..MonoSettings::REDUCE }, ..Settings::default() };+++++++ let r = optimize(&mut jbig2, &settings).unwrap();+++++ assert_eq!(r.images_recompressed, 3);+++++ assert!(r.image_bytes_after < as_g4.image_bytes_after, "JBIG2 {} bytes, Group 4 {}", r.image_bytes_after, as_g4.image_bytes_after);+++++ let images: Vec<Stream> = image_refs(&jbig2).into_iter().map(|i| stream(&jbig2, i)).collect();+++++ assert_eq!(images.len(), 3);+++++ for s in &images {+++++ assert_eq!((s.dict.name(b"Filter"), s.dict.contains(b"DecodeParms")), (Some(&b"JBIG2Decode"[..]), false));+++++ }+++++ assert!(images.iter().any(|s| s.dict.get(b"Decode") == Some(&decode)), "the decode array stays");+++++ let indexed_kept =+++++ |s: &Stream| s.dict.get(b"ColorSpace").and_then(Object::as_array).and_then(|a| a.first()).and_then(Object::as_name) == Some(b"Indexed");+++++ assert!(images.iter().any(indexed_kept), "the colour space stays");+++++ let catalog = jbig2.root().and_then(|r| jbig2.get(r).as_dict().cloned()).unwrap();+++++ assert_eq!(catalog.name(b"Version"), Some(&b"1.4"[..]));+++++ assert!(g4.root().and_then(|r| g4.get(r).as_dict().cloned()).is_some_and(|c| !c.contains(b"Version")), "Group 4 is PDF 1.0");+++++ assert!(render(&jbig2) == before, "the page looks the same");+++++++ // The integration also supports changing an already-CCITT image to lossless JBIG2.+++++++ let mut from_g4 = g4.clone();+++++++ let converted = optimize(&mut from_g4, &settings).unwrap();+++++++ assert_eq!(converted.images_recompressed, 3);+++++++ assert!(render(&from_g4) == before, "CCITT decoded and re-encoded as JBIG2 keeps the picture");+++++ }++++++++++ /// A catalog `/Version` given by reference is read through it: a PDF 1.3 file whose catalog says+++++ /// 1.7 by reference keeps 1.7 when its images become JBIG2, rather than being lowered to 1.4; one+++++ /// whose catalog says 1.3 by reference gets 1.4.+++++ #[test]+++++ fn a_catalog_version_given_by_reference_is_read() {+++++ for (catalog, after) in [("1.7", "1.7"), ("1.3", "1.4")] {+++++ let mut doc = Document::new_empty();+++++ let (w, h) = (1200, 480);+++++ let text = bilevel(w, h, false);+++++ let im = mono_image(&mut doc, w, h, &text, None, &[("BitsPerComponent", 1.into()), ("ColorSpace", Object::name("DeviceGray"))]);+++++ page(&mut doc, &[("Im", im)], "q 300 0 0 120 20 660 cm /Im Do Q");+++++ let version = doc.add(Object::name(catalog));+++++ let root = doc.root().unwrap();+++++ doc.update_dict(root, |c| c.set(b"Version".to_vec(), Object::Ref(version))).unwrap();+++++ let mut bytes = write_full(&doc, &SaveOptions { object_streams: false, ..SaveOptions::default() }).unwrap();+++++ bytes[..8].copy_from_slice(b"%PDF-1.3");+++++ let mut doc = Document::open(Arc::new(bytes)).unwrap();-- let r = optimize(&mut doc, &Settings { mono: MonoCompression::Jbig2, ..Settings::default() }).unwrap();+++++++ let settings = Settings { mono: MonoSettings { compression: MonoCompression::Jbig2, ..MonoSettings::REDUCE }, ..Settings::default() };+++++++ let r = optimize(&mut doc, &settings).unwrap();+++++ assert_eq!(r.images_recompressed, 1);+++++ let root = doc.root().unwrap();+++++ let v = doc.get(root).as_dict().and_then(|c| c.get(b"Version").cloned()).unwrap();+++++ assert_eq!(doc.resolve(&v).as_name(), Some(after.as_bytes()), "catalog {catalog} by reference");+++++ }+++++ }+++++++++++ /// Text as a renderer draws it at 300 dpi: lines 48 rows apart of a few letter shapes, each++++++ /// `#` a 3 × 3 block, three columns apart with a wider gap between words, every copy of a letter++++++ /// the same to the pixel.++++++ fn rendered_text(w: u32, h: u32) -> Vec<u8> {++++++ const LETTERS: [&[&str]; 5] = [++++++ &["##", "##", "##", "##", "##", "##", "##", "##", "##", "##"],++++++ &["......", ".####.", "##..##", "##..##", "##..##", "##..##", ".####."],++++++ &["##....", "##....", "##....", "#####.", "##..##", "##..##", "##..##", "#####."],++++++ &["##..##", "##..##", "##..##", "##..##", ".#####"],++++++ &["##", "##", "..", "##", "##", "##", "##", "##"],++++++ ];++++++ let stride = (w as usize).div_ceil(8);++++++ let mut data = vec![0xFF; stride * h as usize];++++++ let mut seed = 0x2545_F491_4F6C_DD1Du64;++++++ let mut next = move || {++++++ seed ^= seed << 13;++++++ seed ^= seed >> 7;++++++ seed ^= seed << 17;++++++ seed++++++ };++++++ for baseline in (32..h as usize).step_by(48) {++++++ let mut x = 8;++++++ while x + 20 < w as usize {++++++ let letter = LETTERS[(next() % 5) as usize];++++++ for (dy, row) in letter.iter().enumerate() {++++++ for (dx, c) in row.bytes().enumerate() {++++++ for (py, px) in (0..9).map(|k| (baseline + 1 + 3 * dy + k / 3 - 3 * letter.len(), x + 3 * dx + k % 3)) {++++++ if c == b'#' {++++++ data[py * stride + px / 8] &= !(0x80 >> (px % 8));++++++ }++++++ }++++++ }++++++ }++++++ x += 3 * letter[0].len() + 3 + if next() % 5 == 0 { 12 } else { 0 };++++++ }++++++ }++++++ data++++++ }++++++++++++ /// Text whose letters repeat exactly, as rendered text does, becomes JBIG2 symbols: each letter++++++ /// stored once and its copies placed, several times smaller than JBIG2's generic coding of the++++++ /// same image, and the page looks the same.++++++ #[test]++++++ fn rendered_text_becomes_jbig2_symbols() {++++++ let mut doc = Document::new_empty();++++++ let (w, h) = (600, 480);++++++ let text = rendered_text(w, h);++++++ let im = mono_image(&mut doc, w, h, &text, None, &[("BitsPerComponent", 1.into()), ("ColorSpace", Object::name("DeviceGray"))]);++++++ // One image pixel a device pixel at scale 1, so a wrong pixel shows.++++++ page(&mut doc, &[("Im", im)], "q 600 0 0 480 6 300 cm /Im Do Q");++++++ let before = render(&doc);- let r = optimize(&mut doc, &Settings { mono: MonoCompression::Jbig2, ..Settings::default() }).unwrap();+++++++ let settings = Settings { mono: MonoSettings { compression: MonoCompression::Jbig2, ..MonoSettings::REDUCE }, ..Settings::default() };+++++++ let r = optimize(&mut doc, &settings).unwrap();++++++ assert_eq!(r.images_recompressed, 1);++++++ let s = stream(&doc, im);++++++ assert_eq!(s.dict.name(b"Filter"), Some(&b"JBIG2Decode"[..]));++++++ let generic = pdfcraft_filters::encode_jbig2_generic(&text, w, h).unwrap();++++++ assert!(s.raw.len() * 2 < generic.len(), "symbols {} bytes, generic {}", s.raw.len(), generic.len());++++++ assert!(render(&doc) == before, "the page looks the same");++++++ }++++++++++++ /// A whole 300 dpi letter page of rendered text, more marks than one JBIG2 text region of the++++++ /// decoder PdfCraft renders with takes, still looks the same as JBIG2 symbols.++++++ #[test]++++++ fn a_dense_page_of_rendered_text_looks_the_same_as_jbig2_symbols() {++++++ let mut doc = Document::new_empty();++++++ let (w, h) = (2550, 3300);++++++ let text = rendered_text(w, h);++++++ let im = mono_image(&mut doc, w, h, &text, None, &[("BitsPerComponent", 1.into()), ("ColorSpace", Object::name("DeviceGray"))]);++++++ page(&mut doc, &[("Im", im)], "q 612 0 0 792 0 0 cm /Im Do Q");++++++ let before = render(&doc);- let r = optimize(&mut doc, &Settings { mono: MonoCompression::Jbig2, ..Settings::default() }).unwrap();+++++++ let settings = Settings { mono: MonoSettings { compression: MonoCompression::Jbig2, ..MonoSettings::REDUCE }, ..Settings::default() };+++++++ let r = optimize(&mut doc, &settings).unwrap();++++++ assert_eq!(r.images_recompressed, 1);++++++ let s = stream(&doc, im);++++++ assert_eq!(s.dict.name(b"Filter"), Some(&b"JBIG2Decode"[..]));++++++ assert!(s.raw.len() * 2 < pdfcraft_filters::encode_jbig2_generic(&text, w, h).unwrap().len(), "symbol coded");++++++ // The copies take several text regions (segment type 7, ISO/IEC 14492 7.3), read from the++++++ // segment headers (7.2): number, flags, referred-to count and numbers, page, data length.++++++ let mut regions = 0;++++++ let mut at = 0;++++++ while let Some(header) = s.raw.get(at..at + 6) {++++++ let refers = usize::from(header[5] >> 5);++++++ let length = u32::from_be_bytes(s.raw[at + 7 + refers..at + 11 + refers].try_into().unwrap()) as usize;++++++ regions += usize::from(header[4] & 0x3F == 7);++++++ at += 11 + refers + length;++++++ }++++++ assert!(regions > 1, "{regions} text regions");++++++ assert!(render(&doc) == before, "the page looks the same");++++++ }++++++#[test]fn settings_choose_what_happens() {let mut doc = Document::new_empty();diff --cc crates/ui-egui/src/canvas.rsindex 5269383b5,6de219e89,91d2c4136,ea37eb0df,91d2c4136,91d2c4136,91d2c4136..3bbc91ef2--- a/crates/ui-egui/src/canvas.rs+++ b/crates/ui-egui/src/canvas.rs@@@@@@@@ -27,9 -27,8 -27,8 -26,7 -27,8 -27,8 -27,8 +27,9 @@@@@@@@ pub(super) mod flingpub(super) mod image_pick;mod navigation;mod organize;+ pub(super) mod page_cursor;pub(super) mod page_pointer;++++++pub(super) mod page_router;pub mod scroll_speed;mod selection;pub(super) mod signature_drag;@@@@@@@@ -474,13 -471,8 -471,8 -470,6 -471,8 -471,8 -471,8 +474,13 @@@@@@@@ pub struct DocView/// A queued Fill & Sign signature: select it after its edit succeeds, then leave placement.pub(crate) fill_signature_page: Option<usize>,pub(crate) signature_drag: crate::signature_drag::SignatureDrag,+ /// What the page modules claim for the cursor this frame; `document_area` sets it once.+ pub(crate) cursor: crate::page_cursor::PageCursor,++++++ /// Who the press the pages hold belongs to.++++++ pub(crate) router: crate::page_router::PageRouter,++++++ /// Escape cancelled the press the pages hold: the page ignores it until the button is up, so++++++ /// its release neither clicks nor ends a drag.++++++ pub(crate) press_cancelled: bool,/// A non-edit action requested by the organize toolbar, handled by the app.pub pending_action: Option<ViewAction>,/// The grid gap the next inserted files go to (set by a "+" between pages); otherwise they@@@@@@@@ -735,9 -725,7 -725,7 -722,6 -725,7 -725,7 -725,7 +735,9 @@@@@@@@ impl DocViewfill_text: None,fill_signature_page: None,signature_drag: Default::default(),+ cursor: Default::default(),++++++ router: Default::default(),++++++ press_cancelled: false,}}@@@@@@@@ -1174,9 -1130,8 -1130,8 -1129,8 -1130,8 -1130,8 -1130,8 +1174,9 @@@@@@@@ fn page_tool_input(ui: &mut egui::Ui, v&& allowed&& let Some(p) = ptr.within(xf.rect){- ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair);- if resp.clicked() {+ view.cursor.claim(Layer::ToolArea, egui::CursorIcon::Crosshair);-- --- if resp.clicked() {++++++ // The tool's own click: nothing drawn over the page here holds the press.++++++ if resp.clicked() && view.router.owner(i).is_none() {// Centred on the click, upright as the page is shown.let (vx, vy) = xf.screen_to_view(p);let (w, h) = kind.size();@@@@@@@@ -1199,9 -1154,8 -1154,8 -1153,8 -1154,8 -1154,8 -1154,8 +1199,9 @@@@@@@@&& allowed&& let Some(p) = ptr.within(xf.rect){- ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair);- if resp.clicked() {+ view.cursor.claim(Layer::ToolArea, egui::CursorIcon::Crosshair);-- --- if resp.clicked() {++++++ // The tool's own click: nothing drawn over the page here holds the press.++++++ if resp.clicked() && view.router.owner(i).is_none() {// Centred on the click at its natural size (the engine sizes it).let (vx, vy) = xf.screen_to_view(p);let u = info.pages[i].view_to_user(vx, vy);@@@@@@@@ -1261,14 -1214,23 -1214,23 -1213,30 -1214,23 -1214,23 -1214,23 +1261,14 @@@@@@@@view.current = i;frame.out.open_boxes = true;}- // `over_field`: a form field is under the pointer and has set its cursor.- let (on_field, over_field) = if preparing {- let field_tool = match tool {- QuickTool::Field(f) => Some(f),- _ => None,- };- // While a table is being set up, nothing else is drawn or moved.- let allowed = can_modify && table_preview.is_none() && frame.out.open_table.is_none();- let o = crate::prepare::page_input(cx, form, field_tool, allowed, view);+ let on_field = if preparing {-- --- let field_tool = match tool {-- --- QuickTool::Field(f) => Some(f),-- --- _ => None,-- --- };-- --- // While a table is being set up, nothing else is drawn or moved.-- --- let allowed = can_modify && table_preview.is_none() && frame.out.open_table.is_none();-- --- let o = crate::prepare::page_input(cx, form, field_tool, allowed, view);++++++ let o = crate::prepare::page_input(cx, form, field_tool, prepare_allowed, view);frame.out.field_props |= o.properties;frame.out.field_placed |= o.placed;frame.out.open_table = frame.out.open_table.or(o.table);- (o.consumed || field_tool.is_some(), false)+ o.consumed || field_tool.is_some()} else {-- --- tool == QuickTool::Select- use crate::forms_ui::FieldPointer;- let field = if tool == QuickTool::Select------ && !(editing_content && can_modify && crate::content_ui::select_grabs(&xf, ptr, i, info, added, view))------ && !comments::select_grabs(&pcx, view)-- --- && crate::forms_ui::page_input(cx, form, can_fill, view)- {- crate::forms_ui::page_input(cx, form, can_fill, view)- } else {- FieldPointer::Away- };- (field == FieldPointer::Owned, field == FieldPointer::Over)++++++ tool == QuickTool::Select && crate::forms_ui::page_input(cx, form, can_fill, view)};// Redact draws boxes off text; so does Highlight (an area highlight, as in Acrobat).let area_tool = tool == QuickTool::Redact && can_modify || tool == QuickTool::Comment(comments::CommentTool::Highlight) && allowed;@@@@@@@@ -1339,133 -1322,9 -1322,9 -1328,9 -1322,9 -1322,9 -1322,9 +1339,133 @@@@@@@@view.links.context = Some((i, l.index));}let consumed = on_objects || on_edit_text || on_link || on_content || boxing || on_field || comments::page_input(ui, resp, &pcx, view);- PageInput { consumed, over_field, area_tool }++++++ // The cursor and the tip from what lies under the pointer, after the tools claimed theirs (the++++++ // last claim on a layer stands).++++++ if frame.env.unobstructed++++++ && let Some(p) = pointer++++++ {++++++ for h in hits.at(view, p) {++++++ view.cursor.claim_with_tip(h.layer, h.icon, h.tip);++++++ }++++++ }+ PageInput { consumed, area_tool }+ }+++++++/// Edit text's paragraphs and pictures on page `i`, kept while the document is unchanged.++++++fn edit_inventory(++++++ view: &mut DocView,++++++ doc: &pdfcraft_engine::Document,++++++ i: usize,++++++) -> (Vec<pdfcraft_engine::TextBlock>, Vec<pdfcraft_engine::PageImage>) {++++++ let generation = doc.edit_generation();++++++ let lines = match view.edit_lines.get(&i) {++++++ Some((g, l)) if *g == generation => l.clone(),++++++ _ => {++++++ let l = doc.text_blocks(i);++++++ view.edit_lines.insert(i, (generation, l.clone()));++++++ l++++++ }++++++ };++++++ let images = match view.edit_images.get(&i) {++++++ Some((g, l)) if *g == generation => l.clone(),++++++ _ => {++++++ let l = doc.page_images(i);++++++ view.edit_images.insert(i, (generation, l.clone()));++++++ l++++++ }++++++ };++++++ (lines, images)++++++}++++++++++++/// What the page modules have under a point on one page, for the page router.++++++struct PageHits<'a> {++++++ page: usize,++++++ xf: &'a PageXform,++++++ info: &'a DocInfo,++++++ tool: QuickTool,++++++ pcx: &'a comments::PageCx<'a>,++++++ form: &'a [pdfcraft_engine::FormField],++++++ can_fill: bool,++++++ can_modify: bool,++++++ /// Edit a PDF is open: added text and pictures can be picked up.++++++ editing_content: bool,++++++ preparing: bool,++++++ field_tool: Option<crate::prepare::FieldTool>,++++++ /// Prepare may draw and move fields (not while a table is being set up).++++++ prepare_allowed: bool,++++++ added: &'a [pdfcraft_engine::Added],++++++ lines: &'a [pdfcraft_engine::TextBlock],++++++ images: &'a [pdfcraft_engine::PageImage],++++++ /// The pages' visible area (the picture's rotate knob stays inside it).++++++ clip: Rect,++++++}++++++++++++impl PageHits<'_> {++++++ /// The hits at `p`, bottom up: links, comments; Edit text's pictures under its paragraphs (text++++++ /// on top of artwork takes the press), added content, the objects selected together and the++++++ /// open paragraph's frame, the selected picture's grips over them all; then form fields++++++ /// (Prepare's, being moved, over the comments; filled ones under added content and the++++++ /// comments that move).++++++ fn at(&self, view: &DocView, p: Pos2) -> Vec<crate::page_router::Hit> {++++++ let PageHits {++++++ page,++++++ xf,++++++ info,++++++ tool,++++++ pcx,++++++ form,++++++ can_fill,++++++ can_modify,++++++ editing_content,++++++ preparing,++++++ field_tool,++++++ prepare_allowed,++++++ added,++++++ lines,++++++ images,++++++ clip,++++++ } = *self;++++++ let fields = if preparing {++++++ crate::prepare::hit(xf, info, page, form, field_tool, prepare_allowed, &view.prepare, p)++++++ } else if tool == QuickTool::Select {++++++ crate::forms_ui::hit(xf, info, page, form, can_fill, p)++++++ } else {++++++ None++++++ };++++++ // With Add text, only the paragraphs and pictures not under added content.++++++ let editing =++++++ can_modify && (tool == QuickTool::EditText || tool == QuickTool::AddText && !crate::content_ui::hits_added(xf, info, page, added, p));++++++ let (pictures, paragraphs, objects, grips) = if editing {++++++ let open = view.line_editor.as_ref().filter(|e| e.page == page);++++++ let frame = open++++++ .filter(|e| !e.has_changes())++++++ .and_then(|e| lines.get(e.block))++++++ .map(|l| xf.user_rect(info, page, l.rect.map(|v| v as f32)).expand(2.0));++++++ // Add text acts on the page's paragraphs only in their boxes, edges included (it++++++ // finishes the box being typed there, `over_source`): not on pictures, nor beside a++++++ // paragraph, where a click starts a new box.++++++ let edit_text = tool == QuickTool::EditText;++++++ let on_paragraphs = edit_text || crate::edit_text_ui::over_paragraph(xf, info, page, lines, p);++++++ (++++++ edit_text.then(|| crate::edit_text_ui::picture_hit(xf, page, info, images, view, p)).flatten(),++++++ on_paragraphs.then(|| crate::edit_text_ui::hit(xf, info, page, lines, open.map(|e| e.block), p)).flatten(),++++++ edit_text.then(|| crate::object_ui::hit(view, xf, info, page, frame, p)).flatten(),++++++ edit_text.then(|| crate::edit_text_ui::picture_handle_hit(clip, xf, page, info, images, view, p)).flatten(),++++++ )++++++ } else {++++++ (None, None, None, None)++++++ };++++++ // Added text and pictures, over the page's own paragraphs and under the objects selected++++++ // together.++++++ let picks_up = matches!(tool, QuickTool::Select | QuickTool::AddText | QuickTool::EditText);++++++ let added = (editing_content && can_modify && picks_up).then(|| crate::content_ui::hit(xf, info, page, added, view, p)).flatten();++++++ [link_hit(info, xf, page, p), comments::hit(pcx, view, p), pictures, paragraphs, added, objects, grips, fields]++++++ .into_iter()++++++ .flatten()++++++ .collect()++++++ }++ +++}++ +++/// Text layer: find matches, selection, I-beam and drag-to-select.fn text_layer(ui: &mut egui::Ui, view: &mut DocView, frame: &mut PageFrame<'_>, slot: &PageSlot, input: &PageInput) {let PageEnv { info, selects_text, tool, .. } = frame.env;@@@@@@@@ -1745,22 -1599,31 -1599,31 -1611,51 -1599,31 -1599,31 -1599,31 +1745,22 @@@@@@@@ fn page_overlays(ui: &mut egui::Ui, vie// in Acrobat). Only what can be filled is marked: a read-only widget (its field's, or a// radio button's own) is left as it is drawn.paint_field_highlights(painter, &xf, info, form.as_slice(), i, view.highlight_fields);- // Fill & Sign keeps its placement cursor clear of link/comment hover feedback. Tips- // draw above the palette, so none shows while it is open, even beside it.- if !matches!(tool, QuickTool::Fill(_))- && unobstructed- && let Some(p) = pointer+ // Links: the hand and the link's target, which count only for the tools that follow or+ // edit links (`Layer::reached_by`). Tips draw above the palette, so none shows while it is-- --- // open, even beside it.-- --- if unobstructed && let Some(p) = pointer {-- --- for l in info.links.iter().filter(|l| l.page == i) {-- --- let sr = xf.user_rect(info, i, l.rect);-- --- if sr.contains(p) {-- --- let label = match &l.target {-- --- LinkTarget::Page(n, _) => {-- --- crate::i18n::fmt(tl!("Go to page {p}"), &[("p", info.pages.get(*n).map(|p| p.label.as_str()).unwrap_or("?"))])-- --- }-- --- LinkTarget::Uri(u) => u.clone(),-- --- LinkTarget::SetLayers { .. } => tl!("Set layer visibility").to_string(),-- --- LinkTarget::RemoteGoTo { file, .. } => file.clone(),-- --- LinkTarget::Other(s) => crate::i18n::fmt(tl!("{s} action"), &[("s", s)]),-- --- };-- --- view.cursor.claim_with_tip(Layer::Link, egui::CursorIcon::PointingHand, Some(label));-- --- if resp.clicked() && tool == QuickTool::Select && !input.consumed {-- --- frame.out.clicked_link = Some(l.target.clone());-- --- }-- --- }-- --- }++++++ // open, even beside it. A click follows the link its press was on, released over it: one that++++++ // slips off the link first follows nothing, as a button's does.++++++ if unobstructed++++++ && resp.clicked()++++++ && tool == QuickTool::Select++++++ && !input.consumed++++++ && let Some(owner @ crate::page_router::Owner::Link { index }) = view.router.owner(i)++++++ && pointer.and_then(|p| link_hit(info, &xf, i, p)).is_some_and(|h| h.owner == owner)++++++ && let Some(l) = info.links.get(index)++ +++ {- for l in info.links.iter().filter(|l| l.page == i) {- let sr = xf.user_rect(info, i, l.rect);- if sr.contains(p) {- ui.ctx().set_cursor_icon(egui::CursorIcon::PointingHand);- let label = match &l.target {- LinkTarget::Page(n, _) => {- crate::i18n::fmt(tl!("Go to page {p}"), &[("p", info.pages.get(*n).map(|p| p.label.as_str()).unwrap_or("?"))])- }- LinkTarget::Uri(u) => u.clone(),- LinkTarget::SetLayers { .. } => tl!("Set layer visibility").to_string(),- LinkTarget::RemoteGoTo { file, .. } => file.clone(),- LinkTarget::Other(s) => crate::i18n::fmt(tl!("{s} action"), &[("s", s)]),- };- frame.out.hover_text = Some((p, label));- if resp.clicked() && tool == QuickTool::Select && !input.consumed {- frame.out.clicked_link = Some(l.target.clone());- }- }- }- // Annotation hover shows the comment, as Acrobat's popups do; not while drawing- // freehand, where it would cover the next stroke (#429).- let freehand = matches!(tool, QuickTool::Comment(comments::CommentTool::Ink | comments::CommentTool::Eraser));- let gesturing = view.comments.gesture.is_some() || freehand;- // Inspection sorts annotations spatially, but the renderer paints in /Annots- // order. Keep the shared list intact and choose the last eligible raw index.- if frame.out.hover_text.is_none()- && !gesturing- && let Some((_, text)) = info- .annotations- .iter()- .filter(|a| a.page == i)- .filter(|a| !(prefs.hide_empty_highlight_hover && a.subtype == "Highlight" && a.contents.as_deref().is_none_or(str::is_empty)))- .filter(|a| pcx.screen_rects(a).any(|r| r.contains(p)))- .filter_map(|a| annotation_hover_text(a).map(|text| (a.index, text)))- .max_by_key(|(index, _)| *index)- {- frame.out.hover_text = Some((p, text));- }++++++ frame.out.clicked_link = Some(l.target.clone());}+ // Comments say what they are with any tool, beside its cursor, as Acrobat's do.+ comments::describe(&pcx, view);for (mp, mr, mc) in &view.compare_marks {if *mp == i {let sr = xf.user_rect(info, i, *mr).expand(1.5);@@@@@@@@ -2227,10 -2040,9 -2040,9 -2074,10 -2040,9 -2040,9 -2040,9 +2227,10 @@@@@@@@ fn draw_pagesui.separator();}}------ canvas_action = comments::context_menu(ui, view, info, prefs, allowed, can_modify).or(copy_image);++++++ canvas_action =++++++ comments::context_menu(ui, view, info, &|page, index| doc.annotation_deletable(page, index), prefs, allowed, can_modify).or(copy_image);});*out = PageOut {- badge_hover,canvas_action,clicked_link,copy_selected,diff --cc crates/ui-egui/src/dialogs.rsindex 0e4316445,4e0ba2137,e57299fdc,c21604a4d,e57299fdc,e57299fdc,e57299fdc..d24e62cb7--- a/crates/ui-egui/src/dialogs.rs+++ b/crates/ui-egui/src/dialogs.rs@@@@@@@@ -1738,12 -1730,16 -1730,12 -1702,9 -1730,12 -1730,12 -1730,12 +1738,16 @@@@@@@@ fn finish_redactions_and_fields(app: &mlet form = |app: &PdfCraftApp| app.active_ids().and_then(|(_, id)| app.session.get(id)).map(|doc| doc.form.clone());// A rename also renames the field in the formulas that read it.let before = props.name.as_ref().and_then(|_| form(app));- if app.apply_edit(Edit::SetFieldProps { name: d.field.clone(), props: Box::new(props) })- && let Some(i) = app.active- {+ // The widget being edited, by object: a radio button that joins a group by its new name+ // is appended after the group's own buttons, so its index changes.+ let widget = before.as_ref().and_then(|all| all.iter().find(|f| f.name == d.field)?.widgets.get(d.widget).map(|w| w.obj));- - --- if app.apply_edit(Edit::SetFieldProps { name: d.field.clone(), props: Box::new(props) })- - --- && let Some(i) = app.active- - --- {+ +++++ let applied = app.apply_edit(Edit::SetFieldProps { name: d.field.clone(), props: Box::new(props) });+ +++++ if !applied && app.active_ids().is_some() {+ +++++ // A refused edit (its reason is in the notice) leaves the dialog open with what was+ +++++ // typed into it, as the several-fields dialog does, so nothing is lost meanwhile.+ +++++ app.field_props = Some(d);+ +++++ req.close = false;+ +++++ } else if applied && let Some(i) = app.active {// Keep the (possibly renamed) field selected.// A dotted name is the full name; a plain one renames the field within its parent.let typed = d.name.trim();diff --cc crates/ui-egui/src/editing.rsindex 6dde2dfcd,ab6d49f42,ab6d49f42,bf52c2ef5,ab6d49f42,ab6d49f42,ab6d49f42..8def569f5--- a/crates/ui-egui/src/editing.rs+++ b/crates/ui-egui/src/editing.rs@@@@@@@@ -220,29 -203,6 -203,6 -203,33 -203,6 -203,6 -203,6 +220,33 @@@@@@@@ impl PdfCraftApp}}++ +++ /// Undo from the menu or toolbar while a box on the page holds typing the page doesn't have++ +++ /// yet: the box takes the step, as it does for the key, one step of its typing at a time.++ +++ /// Applying the typing first was a new edit, which dropped the document's Redo, and then the++ +++ /// typing was taken back all at once. True when the box took the step.++ +++ fn undo_in_page_box(&mut self) -> bool {++ +++ let Some(ctx) = self.ctx.clone() else { return false };++ +++ let Some(view) = self.active.and_then(|i| self.views.get_mut(i)) else { return false };++ +++ let doc = view.id;++ +++ if let Some(ed) = view.line_editor.as_mut().filter(|ed| ed.has_unsaved_text()) {++ +++ ed.claim_typing(&ctx, doc);++ +++ let Some(text) = typing_step(&ctx, crate::edit_text_ui::input_id(), &ed.text, true) else { return false };- ed.text = text;+++ +++ let before = std::mem::replace(&mut ed.text, text);+++ +++ ed.selection = None;+++ +++ ed.follow_typed_rows(&ctx, &before);++ +++ return true;++ +++ }++ +++ if let Some(d) = view.content.draft.as_mut().filter(|d| d.has_unapplied_typing()) {++ +++ d.claim_typing(&ctx, doc);++ +++ let Some(text) = typing_step(&ctx, crate::content_ui::input_id(), &d.text, true) else { return false };- d.text = text;+++ +++ let before = std::mem::replace(&mut d.text, text);+++ +++ d.selection = None;+++ +++ crate::edit_text_ui::follow_typing(&ctx, crate::content_ui::input_id(), &before, &d.text, &mut [&mut d.style.aligns]);++ +++ return true;++ +++ }++ +++ false++ +++ }++ +++pub fn redo(&mut self) {if self.combine_showing() {self.combine_history_step(false);@@@@@@@@ -251,34 -211,8 -211,8 -238,38 -211,8 -211,8 -211,8 +255,38 @@@@@@@@}}++ +++ /// Redo from the menu or toolbar while a box on the page has typing of its own: the step is++ +++ /// the box's, as the key's is. What Undo took back in the box comes back; typing the page++ +++ /// doesn't have yet stays as it is, since applying it first is a new edit, which drops the++ +++ /// document's Redo. True when the box took the step.++ +++ fn redo_in_page_box(&mut self) -> bool {++ +++ let Some(ctx) = self.ctx.clone() else { return false };++ +++ let Some(view) = self.active.and_then(|i| self.views.get_mut(i)) else { return false };++ +++ let doc = view.id;++ +++ if let Some(ed) = view.line_editor.as_mut() {++ +++ ed.claim_typing(&ctx, doc);++ +++ let Some(text) = typing_step(&ctx, crate::edit_text_ui::input_id(), &ed.text, false) else { return ed.has_unsaved_text() };- ed.text = text;+++ +++ let before = std::mem::replace(&mut ed.text, text);+++ +++ ed.selection = None;+++ +++ ed.follow_typed_rows(&ctx, &before);++ +++ return true;++ +++ }++ +++ if let Some(d) = view.content.draft.as_mut() {++ +++ d.claim_typing(&ctx, doc);++ +++ let Some(text) = typing_step(&ctx, crate::content_ui::input_id(), &d.text, false) else { return d.has_unapplied_typing() };- d.text = text;+++ +++ let before = std::mem::replace(&mut d.text, text);+++ +++ d.selection = None;+++ +++ crate::edit_text_ui::follow_typing(&ctx, crate::content_ui::input_id(), &before, &d.text, &mut [&mut d.style.aligns]);++ +++ return true;++ +++ }++ +++ false++ +++ }++ +++fn history_step(&mut self, undo: bool) {let Some((i, id)) = self.active_ids() else { return };++ +++ if !self.close_text_editors(i, id) {++ +++ return;++ +++ }let result = if undo { self.session.undo(id) } else { self.session.redo(id) };match result {Ok(label) => {@@@@@@@@ -1030,15 -860,7 -860,7 -1015,16 -860,7 -860,7 -860,7 +1038,16 @@@@@@@@ mod revert_draft_testsfn text_typed_into_a_new_text_box_counts_as_unsaved_work() {use crate::content_ui::{TextDraft, default_style};let mut app = app();-- --- let draft = |text: &str| TextDraft { page: 0, index: None, rect: [0.0; 4], text: text.into(), style: default_style(), focus: true };++ +++ let draft = |text: &str| TextDraft {++ +++ page: 0,++ +++ index: None,++ +++ rect: [0.0; 4],++ +++ text: text.into(),++ +++ style: default_style(),++ +++ focus: true,+++ +++ selection: None,++ +++ typing_from: None,++ +++ };assert!(!app.has_unsaved_work(0));app.views[0].content.draft = Some(draft(" \n"));assert!(!app.has_unsaved_work(0));@@@@@@@@ -1063,8 -885,7 -885,7 -1049,16 -885,7 -885,7 -885,7 +1072,16 @@@@@@@@let mut app = PdfCraftApp::new();app.open_bytes("source.pdf", Some(path.clone()), bytes).unwrap();let rect = [72.0, 72.0, 272.0, 92.0];- app.views[0].content.draft =- Some(TextDraft { page: 0, index: None, rect, text: "Typed".into(), style: default_style(), focus: true, typing_from: None });-- --- app.views[0].content.draft = Some(TextDraft { page: 0, index: None, rect, text: "Typed".into(), style: default_style(), focus: true });+++ +++ app.views[0].content.draft = Some(TextDraft {+++ +++ page: 0,+++ +++ index: None,+++ +++ rect,+++ +++ text: "Typed".into(),+++ +++ style: default_style(),+++ +++ focus: true,+++ +++ selection: None,+++ +++ typing_from: None,+++ +++ });let ctx = egui::Context::default();if quit {assert!(!app.request_quit(&ctx));diff --cc crates/ui-egui/src/i18n/ar.tsvindex ad84f9fe5,bc2091e02,6506d2733,3e6d73552,3e6d73552,65432242f,65432242f..ce5bf387b--- a/crates/ui-egui/src/i18n/ar.tsv+++ b/crates/ui-egui/src/i18n/ar.tsv@@@@@@@@ -597,8 -603,6 -597,6 -597,6 -597,6 -597,9 -597,9 +603,9 @@@@@@@@Clean Up تنظيفColor Images الصور الملونةGrayscale Images الصور الرمادية++++ Monochrome Images الصور أحادية اللون++++ CCITT Group 4 CCITT المجموعة 4+++++ JBIG2 (lossless) JBIG2 (بدون فقدان)Bicubic downsampling to تقليل العينات بطريقة Bicubic إلىfor images above للصور التي تتجاوزCompression الضغط@@@@@@@@ -2843,6 -2844,3 -2833,4 -2833,3 -2833,3 -2836,3 -2836,3 +2855,7 @@@@@@@@ certificate Version الإصدا�Rotate the selected pages clockwise تدوير الصفحات المحددة باتجاه عقارب الساعةExtract the selected pages… استخراج الصفحات المحددة…Delete the selected pages حذف الصفحات المحددة++++++++++++# Comments panel: each reply's own "…" menu (AI-assisted, not separately native-reviewed)++++++ Options for this reply خيارات هذا الرد++ ++++ Export value قيمة التصديرdiff --cc crates/ui-egui/src/i18n/bg.tsvindex 213ef5e60,a41f559a4,34ee45220,ec0339f18,ec0339f18,7c3d6ca60,7c3d6ca60..eb37bdd77--- a/crates/ui-egui/src/i18n/bg.tsv+++ b/crates/ui-egui/src/i18n/bg.tsv@@@@@@@@ -259,8 -265,6 -259,6 -259,6 -259,6 -259,9 -259,9 +265,9 @@@@@@@@Clean Up ПочистванеColor Images Цветни изображенияGrayscale Images Изображения в сива скала++++ Monochrome Images Монохромни изображения++++ CCITT Group 4 CCITT група 4+++++ JBIG2 (lossless) JBIG2 (без загуби)Bicubic downsampling to Бикубично понижаване на резолюцията доfor images above за изображения надCompression Компресия@@@@@@@@ -2530,6 -2531,3 -2520,4 -2520,3 -2520,3 -2523,3 -2523,3 +2542,7 @@@@@@@@ animation effects Off Изключен�Rotate the selected pages clockwise Завъртане на избраните страници по часовниковата стрелкаExtract the selected pages… Извличане на избраните страници…Delete the selected pages Изтриване на избраните страници++++++++++++# Comments panel: each reply's own "…" menu (AI-assisted, not separately native-reviewed)++++++ Options for this reply Опции за този отговор++ ++++ Export value Стойност за експортиранеdiff --cc crates/ui-egui/src/i18n/ca.tsvindex 551323423,2492fbdf9,0cacae3c2,0cacae3c2,0cacae3c2,0b6b545f2,0b6b545f2..513016faf--- a/crates/ui-egui/src/i18n/ca.tsv+++ b/crates/ui-egui/src/i18n/ca.tsv@@@@@@@@ -560,8 -560,6 -560,6 -560,6 -560,6 -560,9 -560,9 +560,9 @@@@@@@@Clean Up NetejaColor Images Imatges en colorGrayscale Images Imatges en escala de grisos++++ Monochrome Images Imatges monocromes++++ CCITT Group 4 CCITT grup 4+++++ JBIG2 (lossless) JBIG2 (sense pèrdua)Bicubic downsampling to Reducció bicúbica de resolució afor images above per a imatges de més deCompression Compressiódiff --cc crates/ui-egui/src/i18n/ckb.tsvindex ff2208897,e97cb2f7a,71c0c6286,71c0c6286,71c0c6286,0b9135240,0b9135240..645f17441--- a/crates/ui-egui/src/i18n/ckb.tsv+++ b/crates/ui-egui/src/i18n/ckb.tsv@@@@@@@@ -567,8 -567,6 -567,6 -567,6 -567,6 -567,9 -567,9 +567,9 @@@@@@@@Clean Up پاککردنەوەColor Images وێنە ڕەنگاوڕەنگەکانGrayscale Images وێنە خۆڵەمێشییەکان++++ Monochrome Images وێنە یەکڕەنگەکان++++ CCITT Group 4 CCITT گرووپی 4+++++ JBIG2 (lossless) JBIG2 (بێ لەدەستدان)Bicubic downsampling to کەمکردنەوەی نموونە بە شێوازی Bicubic بۆfor images above بۆ ئەو وێنانەی سەروویCompression پەستاندن@@@@@@@@ -2759,6 -2749,16 -2749,3 -2749,3 -2749,3 -2752,3 -2752,3 +2760,18 @@@@@@@@ certificate Version وەشا�Rotate the selected pages clockwise پەڕە هەڵبژێردراوەکان بە ئاڕاستەی میلی کاتژمێر بسوڕێنەExtract the selected pages… پەڕە هەڵبژێردراوەکان دەربهێنە…Delete the selected pages پەڕە هەڵبژێردراوەکان بسڕەوە+++++++++++# Comments panel: each reply's own "…" menu (AI-assisted, not separately native-reviewed)++++++ Options for this reply هەڵبژاردەکانی ئەم وەڵامە+ +++++# Untranslated: English text until a translator fills these in.+ +++++ Reads {name}, which the form doesn't have, so it gets no value there. Reads {name}, which the form doesn't have, so it gets no value there.+ +++++ Its script also reads fields whose names it builds as it runs, so those reads can't be checked. Its script also reads fields whose names it builds as it runs, so those reads can't be checked.+ +++++ Missing field Missing field+ +++++ Unchecked reads Unchecked reads+ +++++ {field} reads fields named as it runs {field} reads fields named as it runs+ +++++ Some names are built as it runs Some names are built as it runs+ +++++@plural {n} formula reads a field the form doesn't have|{n} formulas read fields the form doesn't have {n} formula reads a field the form doesn't have|{n} formulas read fields the form doesn't have+ +++++@plural {field} reads {fields}, which the form doesn't have.|{field} reads {fields}, which the form doesn't have. {field} reads {fields}, which the form doesn't have.|{field} reads {fields}, which the form doesn't have.+ +++++@plural {n} more formula reads a missing field.|{n} more formulas read missing fields. {n} more formula reads a missing field.|{n} more formulas read missing fields.+ +++++@plural {fields} builds some field names as it runs, so those reads aren't checked.|{fields} build some field names as they run, so those reads aren't checked. {fields} builds some field names as it runs, so those reads aren't checked.|{fields} build some field names as they run, so those reads aren't checked.+ +++++@plural {fields} is missing|{fields} are missing {fields} is missing|{fields} are missingdiff --cc crates/ui-egui/src/i18n/cs.tsvindex 2d7cc4c0d,9bce9d152,a99c62623,ed6d051b5,ed6d051b5,2b50b6a94,2b50b6a94..4ab47a4c3--- a/crates/ui-egui/src/i18n/cs.tsv+++ b/crates/ui-egui/src/i18n/cs.tsv@@@@@@@@ -681,8 -687,6 -681,6 -681,6 -681,6 -681,9 -681,9 +687,9 @@@@@@@@ key Space MezerníClean Up VyčištěníColor Images Barevné obrázkyGrayscale Images Obrázky ve stupních šedi++++ Monochrome Images Monochromatické obrázky++++ CCITT Group 4 CCITT skupina 4+++++ JBIG2 (lossless) JBIG2 (bezeztrátová)Bicubic downsampling to Bikubické převzorkování nafor images above u obrázků nadCompression Komprese@@@@@@@@ -2874,6 -2875,3 -2864,4 -2864,3 -2864,3 -2867,3 -2867,3 +2886,7 @@@@@@@@ certificate Version VerzRotate the selected pages clockwise Otočit vybrané stránky po směru hodinových ručičekExtract the selected pages… Extrahovat vybrané stránky…Delete the selected pages Odstranit vybrané stránky++++++++++++# Comments panel: each reply's own "…" menu (AI-assisted, not separately native-reviewed)++++++ Options for this reply Možnosti této odpovědi++ ++++ Export value Exportní hodnotadiff --cc crates/ui-egui/src/i18n/de.tsvindex d806d2086,b65e5870f,cdc647ede,8586a21d4,8586a21d4,69d8030d3,69d8030d3..fab8b0bff--- a/crates/ui-egui/src/i18n/de.tsv+++ b/crates/ui-egui/src/i18n/de.tsv@@@@@@@@ -570,8 -576,6 -570,6 -570,6 -570,6 -570,9 -570,9 +576,9 @@@@@@@@Clean Up AufräumenColor Images FarbbilderGrayscale Images Graustufenbilder++++ Monochrome Images Monochrome Bilder++++ CCITT Group 4 CCITT Gruppe 4+++++ JBIG2 (lossless) JBIG2 (verlustfrei)Bicubic downsampling to Bikubische Neuberechnung auffor images above für Bilder überCompression Komprimierung@@@@@@@@ -2568,6 -2569,3 -2558,4 -2558,3 -2558,3 -2561,3 -2561,3 +2580,7 @@@@@@@@ animation effects Off AuRotate the selected pages clockwise Ausgewählte Seiten im Uhrzeigersinn drehenExtract the selected pages… Ausgewählte Seiten extrahieren…Delete the selected pages Ausgewählte Seiten löschen++++++++++++# Comments panel: each reply's own "…" menu (AI-assisted, not separately native-reviewed)++++++ Options for this reply Optionen für diese Antwort++ ++++ Export value Exportwertdiff --cc crates/ui-egui/src/i18n/el.tsvindex 3ab45f5dd,b292363bf,f809f9812,e3eac77ca,e3eac77ca,3599744eb,3599744eb..707f15f99--- a/crates/ui-egui/src/i18n/el.tsv+++ b/crates/ui-egui/src/i18n/el.tsv@@@@@@@@ -1914,8 -1912,6 -1906,6 -1906,6 -1906,6 -1906,9 -1906,9 +1920,9 @@@@@@@@Clean Up ΕκκαθάρισηColor Images Έγχρωμες εικόνεςGrayscale Images Εικόνες σε κλίμακα του γκρι++++ Monochrome Images Μονόχρωμες εικόνες++++ CCITT Group 4 CCITT Ομάδα 4+++++ JBIG2 (lossless) JBIG2 (χωρίς απώλειες)Bicubic downsampling to Δικυβική μείωση ανάλυσης σεfor images above για εικόνες πάνω απόZIP ZIP@@@@@@@@ -2573,6 -2574,3 -2563,4 -2563,3 -2563,3 -2566,3 -2566,3 +2585,7 @@@@@@@@ animation effects Off Ανενεργ�Rotate the selected pages clockwise Περιστροφή των επιλεγμένων σελίδων δεξιόστροφαExtract the selected pages… Εξαγωγή των επιλεγμένων σελίδων…Delete the selected pages Διαγραφή των επιλεγμένων σελίδων++++++++++++# Comments panel: each reply's own "…" menu (AI-assisted, not separately native-reviewed)++++++ Options for this reply Επιλογές για αυτήν την απάντηση++ ++++ Export value Τιμή εξαγωγήςdiff --cc crates/ui-egui/src/i18n/es.tsvindex 22036e648,a39fe15a1,4255a650d,0d4e505a7,0d4e505a7,1665279bc,1665279bc..a465e5a1f--- a/crates/ui-egui/src/i18n/es.tsv+++ b/crates/ui-egui/src/i18n/es.tsv@@@@@@@@ -593,8 -599,6 -593,6 -593,6 -593,6 -593,9 -593,9 +599,9 @@@@@@@@Clean Up LimpiezaColor Images Imágenes en colorGrayscale Images Imágenes en escala de grises++++ Monochrome Images Imágenes monocromas++++ CCITT Group 4 CCITT grupo 4+++++ JBIG2 (lossless) JBIG2 (sin pérdida)Bicubic downsampling to Reducción de resolución bicúbica afor images above para imágenes por encima deCompression Compresión@@@@@@@@ -2890,6 -2891,3 -2880,4 -2880,3 -2880,3 -2883,3 -2883,3 +2902,7 @@@@@@@@ theme Appearance AspectRotate the selected pages clockwise Girar las páginas seleccionadas en sentido horarioExtract the selected pages… Extraer las páginas seleccionadas…Delete the selected pages Eliminar las páginas seleccionadas++++++++++++# Comments panel: each reply's own "…" menu (AI-assisted, not separately native-reviewed)++++++ Options for this reply Opciones de esta respuesta++ ++++ Export value Valor de exportacióndiff --cc crates/ui-egui/src/i18n/fa.tsvindex 6c0b5fe15,21efeb644,5cfc21753,5cfc21753,5cfc21753,961307a35,961307a35..99a156bc5--- a/crates/ui-egui/src/i18n/fa.tsv+++ b/crates/ui-egui/src/i18n/fa.tsv@@@@@@@@ -594,8 -600,6 -594,6 -594,6 -594,6 -594,9 -594,9 +600,9 @@@@@@@@Clean Up پاکسازیColor Images تصاویر رنگیGrayscale Images تصاویر خاکستری++++ Monochrome Images تصاویر تکرنگ++++ CCITT Group 4 CCITT گروه ۴+++++ JBIG2 (lossless) JBIG2 (بدون اتلاف)Bicubic downsampling to نمونه برداری کاهشی دو مکعبی بهfor images above برای تصاویر بالاتر ازCompression فشردهسازیdiff --cc crates/ui-egui/src/i18n/fi.tsvindex 1664001ce,e18d18d56,a542ee9b9,a542ee9b9,a542ee9b9,94e7fe011,94e7fe011..b1dbaffc1--- a/crates/ui-egui/src/i18n/fi.tsv+++ b/crates/ui-egui/src/i18n/fi.tsv@@@@@@@@ -560,8 -560,6 -560,6 -560,6 -560,6 -560,9 -560,9 +560,9 @@@@@@@@Clean Up SiivoaColor Images VärikuvatGrayscale Images Harmaasävykuvat++++ Monochrome Images Mustavalkokuvat++++ CCITT Group 4 CCITT ryhmä 4+++++ JBIG2 (lossless) JBIG2 (häviötön)Bicubic downsampling to Bikuubinen alinäytteistys tarkkuuteenfor images above kuville, joiden tarkkuus yliCompression Pakkausdiff --cc crates/ui-egui/src/i18n/fr.tsvindex 380965efa,34c8ce8d2,59175685a,61c8b5171,61c8b5171,7e6ca64ae,7e6ca64ae..513ba27b3--- a/crates/ui-egui/src/i18n/fr.tsv+++ b/crates/ui-egui/src/i18n/fr.tsv@@@@@@@@ -570,8 -576,6 -570,6 -570,6 -570,6 -570,9 -570,9 +576,9 @@@@@@@@Clean Up NettoyerColor Images Images couleurGrayscale Images Images en niveaux de gris++++ Monochrome Images Images monochromes++++ CCITT Group 4 CCITT groupe 4+++++ JBIG2 (lossless) JBIG2 (sans perte)Bicubic downsampling to Sous-échantillonnage bicubique àfor images above pour les images au-dessus deCompression Compression@@@@@@@@ -2833,6 -2834,3 -2823,4 -2823,3 -2823,3 -2826,3 -2826,3 +2845,7 @@@@@@@@ certificate Version VersioRotate the selected pages clockwise Faire pivoter les pages sélectionnées dans le sens horaireExtract the selected pages… Extraire les pages sélectionnées…Delete the selected pages Supprimer les pages sélectionnées++++++++++++# Comments panel: each reply's own "…" menu (AI-assisted, not separately native-reviewed)++++++ Options for this reply Options de cette réponse++ ++++ Export value Valeur d’exportationdiff --cc crates/ui-egui/src/i18n/hi.tsvindex dabd13849,d11767a51,e9d627aca,e9d627aca,e9d627aca,fadf4fbad,fadf4fbad..fa59df3a1--- a/crates/ui-egui/src/i18n/hi.tsv+++ b/crates/ui-egui/src/i18n/hi.tsv@@@@@@@@ -544,8 -544,6 -544,6 -544,6 -544,6 -544,9 -544,9 +544,9 @@@@@@@@Clean Up सफ़ाईColor Images रंगीन छवियाँGrayscale Images ग्रेस्केल छवियाँ++++ Monochrome Images मोनोक्रोम छवियाँ++++ CCITT Group 4 CCITT समूह 4+++++ JBIG2 (lossless) JBIG2 (हानिरहित)Bicubic downsampling to बाइक्यूबिक डाउनसैंपलिंग तकfor images above इससे बड़ी छवियों के लिएCompression संपीड़नdiff --cc crates/ui-egui/src/i18n/hu.tsvindex af29ea62e,dc08ffae0,ae09671c0,6b37b9169,6b37b9169,d16aa23dc,d16aa23dc..bc4614e10--- a/crates/ui-egui/src/i18n/hu.tsv+++ b/crates/ui-egui/src/i18n/hu.tsv@@@@@@@@ -568,8 -574,6 -568,6 -568,6 -568,6 -568,9 -568,9 +574,9 @@@@@@@@Clean Up TisztításColor Images Színes képekGrayscale Images Szürkeárnyalatos képek++++ Monochrome Images Monokróm képek++++ CCITT Group 4 CCITT 4. csoport+++++ JBIG2 (lossless) JBIG2 (veszteségmentes)Bicubic downsampling to Kettős köbös újramintázás errefor images above az ennél nagyobb képeknélCompression Tömörítés@@@@@@@@ -2566,6 -2567,3 -2556,4 -2556,3 -2556,3 -2559,3 -2559,3 +2578,7 @@@@@@@@ animation effects Off KRotate the selected pages clockwise A kijelölt oldalak forgatása az óramutató járásával megegyezőenExtract the selected pages… A kijelölt oldalak kibontása…Delete the selected pages A kijelölt oldalak törlése++++++++++++# Comments panel: each reply's own "…" menu (AI-assisted, not separately native-reviewed)++++++ Options for this reply A válasz beállításai++ ++++ Export value Exportértékdiff --cc crates/ui-egui/src/i18n/id.tsvindex f9c1ca59f,568450aaa,292b336e1,292b336e1,292b336e1,d737f093b,d737f093b..52b2dfbe4--- a/crates/ui-egui/src/i18n/id.tsv+++ b/crates/ui-egui/src/i18n/id.tsv@@@@@@@@ -2063,8 -2055,6 -2055,6 -2055,6 -2055,6 -2055,9 -2055,9 +2063,9 @@@@@@@@ comment menu Edit EdiFormulas and similar non-text elements need alternate text. Add alternate text to them. Rumus dan elemen non-teks serupa memerlukan teks alternatif. Tambahkan teks alternatif ke elemen tersebut.Gray Abu-abuGrayscale Images Gambar Skala Abu-abu++++ Monochrome Images Gambar Monokrom++++ CCITT Group 4 CCITT Grup 4+++++ JBIG2 (lossless) JBIG2 (tanpa kehilangan)Green HijauGreen on black Hijau di atas hitamH / Space (hold) H / Space (tahan)diff --cc crates/ui-egui/src/i18n/it.tsvindex 9a59150ac,cc6651c48,9ecf3c9d4,20729bae6,20729bae6,95b83f1a3,95b83f1a3..3228312cc--- a/crates/ui-egui/src/i18n/it.tsv+++ b/crates/ui-egui/src/i18n/it.tsv@@@@@@@@ -594,8 -600,6 -594,6 -594,6 -594,6 -594,9 -594,9 +600,9 @@@@@@@@Clean Up PuliziaColor Images Immagini a coloriGrayscale Images Immagini in scala di grigi++++ Monochrome Images Immagini monocromatiche++++ CCITT Group 4 CCITT gruppo 4+++++ JBIG2 (lossless) JBIG2 (senza perdita)Bicubic downsampling to Sottocampionamento bicubico afor images above per immagini oltreCompression Compressione@@@@@@@@ -2799,6 -2800,3 -2789,4 -2789,3 -2789,3 -2792,3 -2792,3 +2811,7 @@@@@@@@ certificate SHA-256 digest Impronta SHARotate the selected pages clockwise Ruota le pagine selezionate in senso orarioExtract the selected pages… Estrai le pagine selezionate…Delete the selected pages Elimina le pagine selezionate++++++++++++# Comments panel: each reply's own "…" menu (AI-assisted, not separately native-reviewed)++++++ Options for this reply Opzioni per questa risposta++ ++++ Export value Valore di esportazionediff --cc crates/ui-egui/src/i18n/ja.tsvindex 8f9990242,e135e5e1d,303403359,1ed4d43b6,1ed4d43b6,92b78ef14,92b78ef14..37ddfd4c5--- a/crates/ui-egui/src/i18n/ja.tsv+++ b/crates/ui-egui/src/i18n/ja.tsv@@@@@@@@ -597,8 -603,6 -597,6 -597,6 -597,6 -597,9 -597,9 +603,9 @@@@@@@@Clean Up クリーンアップColor Images カラー画像Grayscale Images グレースケール画像++++ Monochrome Images 白黒画像++++ CCITT Group 4 CCITT グループ 4+++++ JBIG2 (lossless) JBIG2(可逆)Bicubic downsampling to バイキュービック法でダウンサンプル:for images above 対象画像の解像度:Compression 圧縮@@@@@@@@ -2567,6 -2568,3 -2557,4 -2557,3 -2557,3 -2560,3 -2560,3 +2579,7 @@@@@@@@ animation effects Off オ�Rotate the selected pages clockwise 選択したページを時計回りに回転Extract the selected pages… 選択したページを抽出…Delete the selected pages 選択したページを削除++++++++++++# Comments panel: each reply's own "…" menu (AI-assisted, not separately native-reviewed)++++++ Options for this reply この返信のオプション++ ++++ Export value 書き出し値diff --cc crates/ui-egui/src/i18n/kk.tsvindex 03093ca04,6fd915769,76ef21cd4,9022c3591,9022c3591,f5147c8b4,f5147c8b4..a28d53249--- a/crates/ui-egui/src/i18n/kk.tsv+++ b/crates/ui-egui/src/i18n/kk.tsv@@@@@@@@ -557,8 -563,6 -557,6 -557,6 -557,6 -557,9 -557,9 +563,9 @@@@@@@@Clean Up ТазалауColor Images Түсті кескіндерGrayscale Images Сұр реңкті кескіндер++++ Monochrome Images Монохромды кескіндер++++ CCITT Group 4 CCITT 4-топ+++++ JBIG2 (lossless) JBIG2 (шығынсыз)Bicubic downsampling to Бикубтық төмендетуfor images above мұнан асатын кескіндер үшінCompression Сығымдау@@@@@@@@ -2565,6 -2566,3 -2555,4 -2555,3 -2555,3 -2558,3 -2558,3 +2577,7 @@@@@@@@ animation effects Off Өшірул�Rotate the selected pages clockwise Таңдалған беттерді сағат тілімен бұруExtract the selected pages… Таңдалған беттерді шығарып алу…Delete the selected pages Таңдалған беттерді жою++++++++++++# Comments panel: each reply's own "…" menu (AI-assisted, not separately native-reviewed)++++++ Options for this reply Осы жауаптың параметрлері++ ++++ Export value Экспорт мәніdiff --cc crates/ui-egui/src/i18n/ko.tsvindex c66d7b16b,742cf4b3c,09b9cad9f,09b9cad9f,09b9cad9f,3807c0a38,3807c0a38..ecf2b20fa--- a/crates/ui-egui/src/i18n/ko.tsv+++ b/crates/ui-egui/src/i18n/ko.tsv@@@@@@@@ -544,8 -544,6 -544,6 -544,6 -544,6 -544,9 -544,9 +544,9 @@@@@@@@Clean Up 정리Color Images 컬러 이미지Grayscale Images 회색조 이미지++++ Monochrome Images 흑백 이미지++++ CCITT Group 4 CCITT 그룹 4+++++ JBIG2 (lossless) JBIG2(무손실)Bicubic downsampling to 다음 값으로 바이큐빅 다운샘플링for images above 다음 값을 초과하는 이미지에 적용Compression 압축diff --cc crates/ui-egui/src/i18n/lo.tsvindex b163feb62,219815d16,964467d82,964467d82,964467d82,270464b87,270464b87..ca2d8bc7e--- a/crates/ui-egui/src/i18n/lo.tsv+++ b/crates/ui-egui/src/i18n/lo.tsv@@@@@@@@ -565,8 -565,6 -565,6 -565,6 -565,6 -565,9 -565,9 +565,9 @@@@@@@@Clean Up ອະນາໄມColor Images ຮູບພາບສີGrayscale Images ຮູບພາບລະດັບສີເທົາ++++ Monochrome Images ຮູບພາບຂາວດຳ++++ CCITT Group 4 CCITT ກຸ່ມ 4+++++ JBIG2 (lossless) JBIG2 (ບໍ່ສູນເສຍ)Bicubic downsampling to ຫຼຸດຄວາມລະອຽດແບບ Bicubic ລົງເປັນ:for images above ສຳລັບຮູບພາບທີ່ເກີນ:Compression ການບີບອັດ@@@@@@@@ -2475,6 -2465,11 -2465,3 -2465,3 -2465,3 -2468,3 -2468,3 +2476,13 @@@@@@@@ animation effects Off ປິ�Rotate the selected pages clockwise ໝູນໜ້າທີ່ເລືອກຕາມເຂັມໂມງExtract the selected pages… ແຍກໜ້າທີ່ເລືອກອອກ…Delete the selected pages ລຶບໜ້າທີ່ເລືອກ+++++++++++# Comments panel: each reply's own "…" menu (AI-assisted, not separately native-reviewed)++++++ Options for this reply ຕົວເລືອກຂອງການຕອບກັບນີ້+ +++++# Untranslated: English text until a translator fills these in.+ +++++ Reads {name}, which the form doesn't have, so it gets no value there. Reads {name}, which the form doesn't have, so it gets no value there.+ +++++ Its script also reads fields whose names it builds as it runs, so those reads can't be checked. Its script also reads fields whose names it builds as it runs, so those reads can't be checked.+ +++++ Missing field Missing field+ +++++ Unchecked reads Unchecked reads+ +++++ {field} reads fields named as it runs {field} reads fields named as it runs+ +++++ Some names are built as it runs Some names are built as it runsdiff --cc crates/ui-egui/src/i18n/lt.tsvindex 2ede0e846,57a83db82,ab208e3b3,43749f4ec,43749f4ec,75ed16913,75ed16913..b2e588c48--- a/crates/ui-egui/src/i18n/lt.tsv+++ b/crates/ui-egui/src/i18n/lt.tsv@@@@@@@@ -2131,8 -2129,6 -2123,6 -2123,6 -2123,6 -2123,9 -2123,9 +2137,9 @@@@@@@@ comment menu Edit RedaguotFormulas and similar non-text elements need alternate text. Add alternate text to them. Formulėms ir panašiems netekstiniams elementams reikia alternatyviojo teksto. Pridėkite jį.Gray PilkaGrayscale Images Pilkų atspalvių paveikslėliai++++ Monochrome Images Vienspalviai paveikslėliai++++ CCITT Group 4 CCITT 4 grupė+++++ JBIG2 (lossless) JBIG2 (be nuostolių)Green ŽaliaGreen on black Žalia juodame foneH / Space (hold) H / tarpo klavišas (laikyti)@@@@@@@@ -2828,6 -2829,3 -2818,4 -2818,3 -2818,3 -2821,3 -2821,3 +2840,7 @@@@@@@@ theme Appearance IšvaizdRotate the selected pages clockwise Pasukti pasirinktus puslapius pagal laikrodžio rodyklęExtract the selected pages… Išskleisti pasirinktus puslapius…Delete the selected pages Ištrinti pasirinktus puslapius++++++++++++# Comments panel: each reply's own "…" menu (AI-assisted, not separately native-reviewed)++++++ Options for this reply Šio atsakymo parinktys++ ++++ Export value Eksporto reikšmėdiff --cc crates/ui-egui/src/i18n/nb.tsvindex b96b2b0fc,96d5be7de,6f1739974,6f1739974,6f1739974,bceb1d1e8,bceb1d1e8..c196fd239--- a/crates/ui-egui/src/i18n/nb.tsv+++ b/crates/ui-egui/src/i18n/nb.tsv@@@@@@@@ -2068,8 -2060,6 -2060,6 -2060,6 -2060,6 -2060,9 -2060,9 +2068,9 @@@@@@@@Formulas and similar non-text elements need alternate text. Add alternate text to them. Formler og lignende elementer som ikke er tekst, trenger alternativ tekst. Legg til alternativ tekst på dem.Gray GråGrayscale Images Gråtonebilder++++ Monochrome Images Svart-hvitt-bilder++++ CCITT Group 4 CCITT gruppe 4+++++ JBIG2 (lossless) JBIG2 (tapsfri)Green GrønnGreen on black Grønn på svartH / Space (hold) H / Mellomrom (hold)@@@@@@@@ -2743,6 -2733,16 -2733,3 -2733,3 -2733,3 -2736,3 -2736,3 +2744,18 @@@@@@@@ key Space MellomroRotate the selected pages clockwise Roter de valgte sidene med klokkenExtract the selected pages… Trekk ut de valgte sidene…Delete the selected pages Slett de valgte sidene+++++++++++# Comments panel: each reply's own "…" menu (AI-assisted, not separately native-reviewed)++++++ Options for this reply Alternativer for dette svaret+ +++++# Untranslated: English text until a translator fills these in.+ +++++ Reads {name}, which the form doesn't have, so it gets no value there. Reads {name}, which the form doesn't have, so it gets no value there.+ +++++ Its script also reads fields whose names it builds as it runs, so those reads can't be checked. Its script also reads fields whose names it builds as it runs, so those reads can't be checked.+ +++++ Missing field Missing field+ +++++ Unchecked reads Unchecked reads+ +++++ {field} reads fields named as it runs {field} reads fields named as it runs+ +++++ Some names are built as it runs Some names are built as it runs+ +++++@plural {n} formula reads a field the form doesn't have|{n} formulas read fields the form doesn't have {n} formula reads a field the form doesn't have|{n} formulas read fields the form doesn't have+ +++++@plural {field} reads {fields}, which the form doesn't have.|{field} reads {fields}, which the form doesn't have. {field} reads {fields}, which the form doesn't have.|{field} reads {fields}, which the form doesn't have.+ +++++@plural {n} more formula reads a missing field.|{n} more formulas read missing fields. {n} more formula reads a missing field.|{n} more formulas read missing fields.+ +++++@plural {fields} builds some field names as it runs, so those reads aren't checked.|{fields} build some field names as they run, so those reads aren't checked. {fields} builds some field names as it runs, so those reads aren't checked.|{fields} build some field names as they run, so those reads aren't checked.+ +++++@plural {fields} is missing|{fields} are missing {fields} is missing|{fields} are missingdiff --cc crates/ui-egui/src/i18n/pl.tsvindex 5138118de,fa5c1b550,92af29dbe,963d71758,963d71758,480c584c1,480c584c1..ae6463a15--- a/crates/ui-egui/src/i18n/pl.tsv+++ b/crates/ui-egui/src/i18n/pl.tsv@@@@@@@@ -592,8 -598,6 -592,6 -592,6 -592,6 -592,9 -592,9 +598,9 @@@@@@@@Clean Up PorządkowanieColor Images Obrazy koloroweGrayscale Images Obrazy w skali szarości++++ Monochrome Images Obrazy monochromatyczne++++ CCITT Group 4 CCITT grupa 4+++++ JBIG2 (lossless) JBIG2 (bezstratna)Bicubic downsampling to Zmniejsz rozdzielczość metodą dwusześcienną dofor images above dla obrazów powyżejCompression Kompresja@@@@@@@@ -2663,6 -2664,3 -2653,4 -2653,3 -2653,3 -2656,3 -2656,3 +2675,7 @@@@@@@@ animation effects Off WyłączonRotate the selected pages clockwise Obróć zaznaczone strony w prawoExtract the selected pages… Wyodrębnij zaznaczone strony…Delete the selected pages Usuń zaznaczone strony++++++++++++# Comments panel: each reply's own "…" menu (AI-assisted, not separately native-reviewed)++++++ Options for this reply Opcje tej odpowiedzi++ ++++ Export value Wartość eksportowadiff --cc crates/ui-egui/src/i18n/pt-br.tsvindex 6b4807621,dfe0496f9,45d00348b,c34ae83bc,c34ae83bc,da198aa84,da198aa84..70309ffc1--- a/crates/ui-egui/src/i18n/pt-br.tsv+++ b/crates/ui-egui/src/i18n/pt-br.tsv@@@@@@@@ -216,8 -222,6 -216,6 -216,6 -216,6 -216,9 -216,9 +222,9 @@@@@@@@Clean Up LimparColor Images Imagens coloridasGrayscale Images Imagens em escala de cinza++++ Monochrome Images Imagens monocromáticas++++ CCITT Group 4 CCITT grupo 4+++++ JBIG2 (lossless) JBIG2 (sem perdas)Bicubic downsampling to Redução bicúbica de amostragem parafor images above para imagens acima deCompression Compactação@@@@@@@@ -2852,6 -2853,3 -2842,4 -2842,3 -2842,3 -2845,3 -2845,3 +2864,7 @@@@@@@@ theme Appearance AparênciRotate the selected pages clockwise Girar as páginas selecionadas no sentido horárioExtract the selected pages… Extrair as páginas selecionadas…Delete the selected pages Excluir as páginas selecionadas++++++++++++# Comments panel: each reply's own "…" menu (AI-assisted, not separately native-reviewed)++++++ Options for this reply Opções desta resposta++ ++++ Export value Valor de exportaçãodiff --cc crates/ui-egui/src/i18n/ro.tsvindex 382e44d41,413bd022d,78d2298b9,78d2298b9,78d2298b9,e371d5746,e371d5746..f8a2deb83--- a/crates/ui-egui/src/i18n/ro.tsv+++ b/crates/ui-egui/src/i18n/ro.tsv@@@@@@@@ -2074,8 -2066,6 -2066,6 -2066,6 -2066,6 -2066,9 -2066,9 +2074,9 @@@@@@@@ comment menu Edit EditarFormulas and similar non-text elements need alternate text. Add alternate text to them. Formulele și alte elemente non-text similare au nevoie de text alternativ. Adăugați-le text alternativ.Gray GriGrayscale Images Imagini în tonuri de gri++++ Monochrome Images Imagini monocrome++++ CCITT Group 4 CCITT grupa 4+++++ JBIG2 (lossless) JBIG2 (fără pierderi)Green VerdeGreen on black Verde pe negruH / Space (hold) H / Spațiu (ținut apăsat)diff --cc crates/ui-egui/src/i18n/ru.tsvindex 50b1d71c3,be3625bc6,c56e30982,274232d58,274232d58,43314090b,43314090b..87042f7bd--- a/crates/ui-egui/src/i18n/ru.tsv+++ b/crates/ui-egui/src/i18n/ru.tsv@@@@@@@@ -590,8 -596,6 -590,6 -590,6 -590,6 -590,9 -590,9 +596,9 @@@@@@@@Clean Up ОчиститьColor Images Цветные изображенияGrayscale Images Изображения в оттенках серого++++ Monochrome Images Монохромные изображения++++ CCITT Group 4 CCITT группа 4+++++ JBIG2 (lossless) JBIG2 (без потерь)Bicubic downsampling to Бикубическое уменьшение доfor images above для изображений вышеCompression Сжатие@@@@@@@@ -2480,6 -2481,3 -2470,4 -2470,3 -2470,3 -2473,3 -2473,3 +2492,7 @@@@@@@@ animation effects Off Вык�Rotate the selected pages clockwise Повернуть выбранные страницы по часовой стрелкеExtract the selected pages… Извлечь выбранные страницы…Delete the selected pages Удалить выбранные страницы++++++++++++# Comments panel: each reply's own "…" menu (AI-assisted, not separately native-reviewed)++++++ Options for this reply Параметры этого ответа++ ++++ Export value Значение экспортаdiff --cc crates/ui-egui/src/i18n/sl.tsvindex c9c3b1334,94d7f91b1,672065adf,420e6a599,420e6a599,0cbb9fca3,0cbb9fca3..57d31bd66--- a/crates/ui-egui/src/i18n/sl.tsv+++ b/crates/ui-egui/src/i18n/sl.tsv@@@@@@@@ -891,8 -891,6 -891,6 -891,6 -891,6 -891,9 -891,9 +891,9 @@@@@@@@Grab bag RaznoGray SivaGrayscale Images Sivinske slike++++ Monochrome Images Enobarvne slike++++ CCITT Group 4 CCITT skupina 4+++++ JBIG2 (lossless) JBIG2 (brez izgub)Green ZelenaH / Space (hold) H / preslednica (drži)HTML web page Spletna stran HTML@@@@@@@@ -2572,6 -2573,3 -2562,4 -2562,3 -2562,3 -2565,3 -2565,3 +2584,7 @@@@@@@@ animation effects Off IzklopljenRotate the selected pages clockwise Zavrti izbrane strani v smeri urnega kazalcaExtract the selected pages… Izvleci izbrane strani…Delete the selected pages Izbriši izbrane strani++++++++++++# Comments panel: each reply's own "…" menu (AI-assisted, not separately native-reviewed)++++++ Options for this reply Možnosti tega odgovora++ ++++ Export value Izvozna vrednostdiff --cc crates/ui-egui/src/i18n/sq.tsvindex b60015859,76c7e51bd,ba7c9dc5b,ba7c9dc5b,ba7c9dc5b,ef0d3e571,ef0d3e571..4b1769c0f--- a/crates/ui-egui/src/i18n/sq.tsv+++ b/crates/ui-egui/src/i18n/sq.tsv@@@@@@@@ -880,8 -880,6 -880,6 -880,6 -880,6 -880,9 -880,9 +880,9 @@@@@@@@Grab bag Të ndryshmeGray GriGrayscale Images Imazhe në nuanca gri++++ Monochrome Images Imazhe bardhezi++++ CCITT Group 4 CCITT grupi 4+++++ JBIG2 (lossless) JBIG2 (pa humbje)Green JeshileH / Space (hold) H / Hapësira (mbaje shtypur)HTML web page Faqe interneti HTMLdiff --cc crates/ui-egui/src/i18n/te.tsvindex 2de096de0,4c4106fac,16f750da4,7f339989e,7f339989e,a42f6947b,a42f6947b..5b4ba6434--- a/crates/ui-egui/src/i18n/te.tsv+++ b/crates/ui-egui/src/i18n/te.tsv@@@@@@@@ -574,8 -580,6 -574,6 -574,6 -574,6 -574,9 -574,9 +580,9 @@@@@@@@ comment menu Edit సవరించ�Clean Up చక్కదిద్దడంColor Images రంగు చిత్రాలుGrayscale Images గ్రేస్కేల్ చిత్రాలు++++ Monochrome Images మోనోక్రోమ్ చిత్రాలు++++ CCITT Group 4 CCITT గ్రూప్ 4+++++ JBIG2 (lossless) JBIG2 (నష్టరహితం)Bicubic downsampling to బైక్యూబిక్ డౌన్శాంప్లింగ్, లక్ష్యం:for images above ఈ రిజల్యూషన్ మించిన చిత్రాలకు:Compression కుదింపు@@@@@@@@ -2476,6 -2477,3 -2466,4 -2466,3 -2466,3 -2469,3 -2469,3 +2488,7 @@@@@@@@ animation effects Off ఆఫ�Rotate the selected pages clockwise ఎంచుకున్న పేజీలను సవ్య దిశలో తిప్పుExtract the selected pages… ఎంచుకున్న పేజీలను సంగ్రహించు…Delete the selected pages ఎంచుకున్న పేజీలను తొలగించు++++++++++++# Comments panel: each reply's own "…" menu (AI-assisted, not separately native-reviewed)++++++ Options for this reply ఈ ప్రత్యుత్తరం ఎంపికలు++ ++++ Export value ఎగుమతి విలువdiff --cc crates/ui-egui/src/i18n/th.tsvindex 8a772ae3e,8949dcda0,2c9b892ed,2c9b892ed,2c9b892ed,49b81aee5,49b81aee5..71c7d38fe--- a/crates/ui-egui/src/i18n/th.tsv+++ b/crates/ui-egui/src/i18n/th.tsv@@@@@@@@ -554,8 -554,6 -554,6 -554,6 -554,6 -554,9 -554,9 +554,9 @@@@@@@@Clean Up ล้างข้อมูลColor Images รูปภาพสีGrayscale Images รูปภาพระดับสีเทา++++ Monochrome Images รูปภาพขาวดำ++++ CCITT Group 4 CCITT กลุ่ม 4+++++ JBIG2 (lossless) JBIG2 (ไม่สูญเสียข้อมูล)Bicubic downsampling to ลดความละเอียดแบบ Bicubic เป็นfor images above สำหรับรูปภาพที่สูงกว่าCompression การบีบอัด@@@@@@@@ -2730,6 -2720,11 -2720,3 -2720,3 -2720,3 -2723,3 -2723,3 +2731,13 @@@@@@@@ theme Appearance ลักษณะท�Rotate the selected pages clockwise หมุนหน้าที่เลือกตามเข็มนาฬิกาExtract the selected pages… แยกหน้าที่เลือกออก…Delete the selected pages ลบหน้าที่เลือก+++++++++++# Comments panel: each reply's own "…" menu (AI-assisted, not separately native-reviewed)++++++ Options for this reply ตัวเลือกของการตอบกลับนี้+ +++++# Untranslated: English text until a translator fills these in.+ +++++ Reads {name}, which the form doesn't have, so it gets no value there. Reads {name}, which the form doesn't have, so it gets no value there.+ +++++ Its script also reads fields whose names it builds as it runs, so those reads can't be checked. Its script also reads fields whose names it builds as it runs, so those reads can't be checked.+ +++++ Missing field Missing field+ +++++ Unchecked reads Unchecked reads+ +++++ {field} reads fields named as it runs {field} reads fields named as it runs+ +++++ Some names are built as it runs Some names are built as it runsdiff --cc crates/ui-egui/src/i18n/tr.tsvindex 84a301987,1c6f21f1e,5f84355d3,a2ecaea17,a2ecaea17,42548981e,42548981e..f76f7f5cd--- a/crates/ui-egui/src/i18n/tr.tsv+++ b/crates/ui-egui/src/i18n/tr.tsv@@@@@@@@ -555,8 -561,6 -555,6 -555,6 -555,6 -555,9 -555,9 +561,9 @@@@@@@@Clean Up TemizleColor Images Renkli ResimlerGrayscale Images Gri Tonlamalı Resimler++++ Monochrome Images Tek Renkli Resimler++++ CCITT Group 4 CCITT Grup 4+++++ JBIG2 (lossless) JBIG2 (kayıpsız)Bicubic downsampling to Şu değere bikübik alt örnekleme:for images above bundan büyük resimler için:Compression Sıkıştırma@@@@@@@@ -2563,6 -2564,3 -2553,4 -2553,3 -2553,3 -2556,3 -2556,3 +2575,7 @@@@@@@@ animation effects Off Kapal�Rotate the selected pages clockwise Seçili sayfaları saat yönünde döndürExtract the selected pages… Seçili sayfaları ayıkla…Delete the selected pages Seçili sayfaları sil++++++++++++# Comments panel: each reply's own "…" menu (AI-assisted, not separately native-reviewed)++++++ Options for this reply Bu yanıtın seçenekleri++ ++++ Export value Dışa aktarma değeridiff --cc crates/ui-egui/src/i18n/uk.tsvindex 3be7e487c,c1b08a7fc,4395a0383,9c7686883,9c7686883,83f25e0b3,83f25e0b3..eb7bb2ec4--- a/crates/ui-egui/src/i18n/uk.tsv+++ b/crates/ui-egui/src/i18n/uk.tsv@@@@@@@@ -595,8 -601,6 -595,6 -595,6 -595,6 -595,9 -595,9 +601,9 @@@@@@@@Clean Up ОчищенняColor Images Кольорові зображенняGrayscale Images Зображення у відтінках сірого++++ Monochrome Images Монохромні зображення++++ CCITT Group 4 CCITT група 4+++++ JBIG2 (lossless) JBIG2 (без втрат)Bicubic downsampling to Бікубічне зниження роздільної здатності доfor images above для зображень із роздільною здатністю понадCompression Стиснення@@@@@@@@ -2589,6 -2590,3 -2579,4 -2579,3 -2579,3 -2582,3 -2582,3 +2601,7 @@@@@@@@ animation effects Off Вимкнен�Rotate the selected pages clockwise Повернути вибрані сторінки за годинниковою стрілкоюExtract the selected pages… Витягнути вибрані сторінки…Delete the selected pages Видалити вибрані сторінки++++++++++++# Comments panel: each reply's own "…" menu (AI-assisted, not separately native-reviewed)++++++ Options for this reply Параметри цієї відповіді++ ++++ Export value Значення експортуdiff --cc crates/ui-egui/src/i18n/vi.tsvindex e409ca84e,ea218959d,99eb14e8b,973ba870e,973ba870e,9201a1feb,9201a1feb..860884ae4--- a/crates/ui-egui/src/i18n/vi.tsv+++ b/crates/ui-egui/src/i18n/vi.tsv@@@@@@@@ -2119,8 -2117,6 -2111,6 -2111,6 -2111,6 -2111,9 -2111,9 +2125,9 @@@@@@@@ comment menu Edit SửFormulas and similar non-text elements need alternate text. Add alternate text to them. Công thức và các phần tử không phải văn bản tương tự cần có văn bản thay thế. Hãy thêm văn bản thay thế cho chúng.Gray XámGrayscale Images Ảnh thang xám++++ Monochrome Images Ảnh đơn sắc++++ CCITT Group 4 CCITT nhóm 4+++++ JBIG2 (lossless) JBIG2 (không mất dữ liệu)Green Xanh láGreen on black Xanh lá trên nền đenH / Space (hold) H / Space (giữ)@@@@@@@@ -2834,6 -2835,3 -2824,4 -2824,3 -2824,3 -2827,3 -2827,3 +2846,7 @@@@@@@@ key Space SpacRotate the selected pages clockwise Xoay các trang đã chọn theo chiều kim đồng hồExtract the selected pages… Trích xuất các trang đã chọn…Delete the selected pages Xóa các trang đã chọn++++++++++++# Comments panel: each reply's own "…" menu (AI-assisted, not separately native-reviewed)++++++ Options for this reply Tùy chọn cho câu trả lời này++ ++++ Export value Giá trị xuấtdiff --cc crates/ui-egui/src/i18n/zh-hans.tsvindex addc54905,7eaf75315,608a73839,d77c8f642,d77c8f642,0d670e598,0d670e598..995acc78e--- a/crates/ui-egui/src/i18n/zh-hans.tsv+++ b/crates/ui-egui/src/i18n/zh-hans.tsv@@@@@@@@ -265,8 -271,6 -265,6 -265,6 -265,6 -265,9 -265,9 +271,9 @@@@@@@@Clean Up 清理Color Images 彩色图像Grayscale Images 灰度图像++++ Monochrome Images 单色图像++++ CCITT Group 4 CCITT 第 4 组+++++ JBIG2 (lossless) JBIG2(无损)Bicubic downsampling to 双三次降采样至for images above (高于此分辨率的图像)Compression 压缩@@@@@@@@ -2531,6 -2532,3 -2521,4 -2521,3 -2521,3 -2524,3 -2524,3 +2543,7 @@@@@@@@ animation effects Off �Rotate the selected pages clockwise 顺时针旋转所选页面Extract the selected pages… 提取所选页面…Delete the selected pages 删除所选页面++++++++++++# Comments panel: each reply's own "…" menu (AI-assisted, not separately native-reviewed)++++++ Options for this reply 此回复的选项++ ++++ Export value 导出值diff --cc crates/ui-egui/src/i18n/zh-hant.tsvindex 43436a595,d977c1295,25939791f,ce3b939f1,ce3b939f1,11db509b8,11db509b8..79b67e6e7--- a/crates/ui-egui/src/i18n/zh-hant.tsv+++ b/crates/ui-egui/src/i18n/zh-hant.tsv@@@@@@@@ -221,8 -227,6 -221,6 -221,6 -221,6 -221,9 -221,9 +227,9 @@@@@@@@Clean Up 清理Color Images 彩色圖片Grayscale Images 灰階圖片++++ Monochrome Images 單色圖片++++ CCITT Group 4 CCITT 第 4 組+++++ JBIG2 (lossless) JBIG2(無損)Bicubic downsampling to 雙三次降取樣至for images above (高於此解析度的圖片)Compression 壓縮@@@@@@@@ -2517,6 -2518,3 -2507,4 -2507,3 -2507,3 -2510,3 -2510,3 +2529,7 @@@@@@@@ animation effects Off �Rotate the selected pages clockwise 順時針旋轉所選頁面Extract the selected pages… 擷取所選頁面…Delete the selected pages 刪除所選頁面++++++++++++# Comments panel: each reply's own "…" menu (AI-assisted, not separately native-reviewed)++++++ Options for this reply 此回覆的選項++ ++++ Export value 匯出值diff --cc crates/ui-egui/src/tools/content_ui.rsindex 6a0d93b34,a0d9cefa1,a0d9cefa1,d7b4bd8cc,a0d9cefa1,a0d9cefa1,a0d9cefa1..e28f20e23--- a/crates/ui-egui/src/tools/content_ui.rs+++ b/crates/ui-egui/src/tools/content_ui.rs@@@@@@@@ -8,8 -8,8 -8,8 -8,7 -8,8 -8,8 -8,8 +8,8 @@@@@@@@ use pdfcraft_engine::{Added, AddedConteuse pdfcraft_render::DocInfo;use crate::canvas::{DocView, PageToolContext, PageXform};- use crate::page_pointer::PagePointer;+ use crate::page_cursor::Layer;-- ---use crate::page_pointer::PagePointer;++++++use crate::page_router::{Hit, Owner};use crate::theme::Tokens;use crate::widgets;@@@@@@@@ -68,24 -68,8 -68,8 -67,27 -68,8 -68,8 -68,8 +68,27 @@@@@@@@ pub struct TextDraft/// Display space.pub rect: [f64; 4],pub text: String,- /// The box's formatting; its `text` is what the page has (empty for new text).+++ +++ /// The box's formatting; its `text` and `rect` are what the page has (empty for new text), and+++ +++ /// its `aligns` follow `text` as it is typed.pub style: AddedText,pub focus: bool,+++ +++ /// The selected bytes of `text` (empty: the caret), for aligning the lines it touches.+++ +++ pub selection: Option<std::ops::Range<usize>>,++ +++ /// The text the box's own Undo history starts from ([`crate::edit_text_ui::forget_typing_before`]).++ +++ pub typing_from: Option<String>,++ +++}++ +++++ +++impl TextDraft {++ +++ /// Take the shared text box for this box ([`crate::edit_text_ui::forget_typing_before`]): its++ +++ /// own history, or none once the page has its text.++ +++ pub(crate) fn claim_typing(&mut self, ctx: &egui::Context, doc: pdfcraft_engine::DocId) {++ +++ crate::edit_text_ui::forget_typing_before(ctx, input_id(), doc, &mut self.typing_from, &self.style.text);++ +++ }++ +++++ +++ /// Typing the page doesn't have yet: Undo takes it back in the box before touching the document.++ +++ pub(crate) fn has_unapplied_typing(&self) -> bool {++ +++ self.text != self.style.text++ +++ }}#[derive(Clone, Copy, Debug, PartialEq)]@@@@@@@@ -414,10 -394,9 -394,9 -412,14 -394,9 -394,9 -394,9 +417,10 @@@@@@@@ pub(crate) fn page_input.and_then(|(_, si)| items.iter().find(|(i, _)| *i == si)).map(|(_, a)| screen_rect(xf, info, page, a.content.rect()));let corner = selected_rect.and_then(|r| handles(r).into_iter().find(|(c, ..)| c.distance(p) <= 6.0));- // Cursors only where the page shows: the mode bar and side panels over a page scrolled under- // them keep their own (#2755).- let shows = resp.contains_pointer();if adding_text && hit.is_none() {- if shows {- ui.ctx().set_cursor_icon(egui::CursorIcon::Text);- }- if resp.clicked() {+ view.cursor.claim(Layer::ToolArea, egui::CursorIcon::Text);-- --- if resp.clicked() {++++++ // A new box where nothing drawn over the page holds the press.++++++ if resp.clicked() && view.router.owner(page).is_none() {// Text that can't be drawn stays where it is being typed (#125).if cv.hold_blocked() {return true;@@@@@@@@ -433,7 -412,7 -412,7 -435,7 -412,7 -412,7 -412,7 +436,7 @@@@@@@@let page_width = info.pages.get(page).map_or(f64::INFINITY, |p| p.width as f64);let rect = [at[0], at[1] - style.size * 1.2, (at[0] + 200.0).min(page_width), at[1]];style.rect = rect;- cv.draft = Some(TextDraft { page, index: None, rect, text: String::new(), style, focus: true, typing_from: None });-- --- cv.draft = Some(TextDraft { page, index: None, rect, text: String::new(), style, focus: true });+++ +++ cv.draft = Some(TextDraft { page, index: None, rect, text: String::new(), style, focus: true, selection: None, typing_from: None });consumed = true;if typed.is_some() {view.pending_edit = typed;@@@@@@@@ -441,21 -420,20 -420,20 -443,20 -420,20 -420,20 -420,20 +444,21 @@@@@@@@}return consumed;}-- --- if let Some((_, left, top)) = corner {-- --- view.cursor.claim(Layer::Handle, if left == top { egui::CursorIcon::ResizeNwSe } else { egui::CursorIcon::ResizeNeSw });-- --- } else if hit.is_some() {-- --- view.cursor.claim(Layer::Placed, egui::CursorIcon::Move);- if let Some((_, left, top)) = corner.filter(|_| shows) {- ui.ctx().set_cursor_icon(if left == top { egui::CursorIcon::ResizeNwSe } else { egui::CursorIcon::ResizeNeSw });- } else if hit.is_some() && shows {- ui.ctx().set_cursor_icon(egui::CursorIcon::Move);------ }++++++ // A drag on what the press was on ([`hit`]): a corner resizes the selected item, the item++++++ // itself moves.if resp.drag_started() {let origin = ptr.origin.unwrap_or(p);------ if let Some((_, left, top)) = selected_rect.and_then(|r| handles(r).into_iter().find(|(c, ..)| c.distance(origin) <= 6.0)) {------ cv.grab = Some((page, Grab::Corner(left, top), origin));------ consumed = true;------ } else if let Some((i, _)) = items.iter().rev().find(|(_, a)| screen_rect(xf, info, page, a.content.rect()).expand(2.0).contains(origin)) {------ cv.selected = Some((page, *i));------ cv.grab = Some((page, Grab::Move, origin));------ consumed = true;++++++ match view.router.owner(page) {++++++ Some(Owner::Added { corner: Some((left, top)), .. }) => {++++++ cv.grab = Some((page, Grab::Corner(left, top), origin));++++++ consumed = true;++++++ }++++++ Some(Owner::Added { index, corner: None }) => {++++++ cv.selected = Some((page, index));++++++ cv.grab = Some((page, Grab::Move, origin));++++++ consumed = true;++++++ }++++++ _ => {}}return consumed;}@@@@@@@@ -472,7 -450,7 -450,7 -473,16 -450,7 -450,7 -450,7 +475,16 @@@@@@@@if let Some(edit) = cv.finish_draft(added) {view.pending_edit = Some(edit);}- cv.draft = Some(TextDraft { page, index: Some(i), rect: t.rect, text: t.text.clone(), style: t.clone(), focus: true, typing_from: None });-- --- cv.draft = Some(TextDraft { page, index: Some(i), rect: t.rect, text: t.text.clone(), style: t.clone(), focus: true });+++ +++ cv.draft = Some(TextDraft {+++ +++ page,+++ +++ index: Some(i),+++ +++ rect: t.rect,+++ +++ text: t.text.clone(),+++ +++ style: t.clone(),+++ +++ focus: true,+++ +++ selection: None,+++ +++ typing_from: None,+++ +++ });cv.selected = Some((page, i));consumed = true;return consumed;@@@@@@@@ -619,41 -596,39 -596,39 -640,51 -596,39 -596,39 -596,39 +642,51 @@@@@@@@ pub(crate) fn editor(ctx: &egui::Contex// The box is white in every theme, so the caret must not follow the theme (pale in dark mode) (#655).ui.visuals_mut().text_cursor.stroke.color = crate::edit_text_ui::caret_color_on(Color32::WHITE);let [cr, cg, cb] = t.style.color.map(|v| (v.clamp(0.0, 1.0) * 255.0) as u8);--- --- // Laid out as the page draws it, so opening the box doesn't show it realigned.--- --- // shortcut: justified text is shown left-aligned here (TextEdit can't justify), until the editor gets its own layouter.--- --- let halign = match t.style.align {--- --- pdfcraft_engine::TextAlign::Center => egui::Align::Center,--- --- pdfcraft_engine::TextAlign::Right => egui::Align::Max,--- --- pdfcraft_engine::TextAlign::Left | pdfcraft_engine::TextAlign::Justify => egui::Align::Min,--- --- };+++ +++ let color = Color32::from_rgb(cr, cg, cb);// Character spacing shows as the page will draw it, scaled like the font.let letter_spacing = (t.style.char_spacing * f64::from(zoom)) as f32;--- --- let mut spaced = |ui: &egui::Ui, text: &dyn egui::TextBuffer, wrap_width: f32| {--- --- let job = spaced_job(text.as_str(), &font, Color32::from_rgb(cr, cg, cb), letter_spacing, wrap_width, halign);--- --- ui.fonts_mut(|f| f.layout_job(job))+++ +++ // Laid out as the page draws it, each paragraph with its own alignment, so opening the+++ +++ // box doesn't show it realigned.+++ +++ let style = t.style.clone();+++ +++ let line_font = font.clone();+++ +++ let mut layouter = |ui: &egui::Ui, text: &dyn egui::TextBuffer, wrap: f32| {+++ +++ aligned_galley(ui, text.as_str(), &style, &line_font, color, letter_spacing, wrap)};+++ +++ let before = t.text.clone();++ +++ let input = input_id();++ +++ t.claim_typing(ui.ctx(), doc_id);ui.horizontal_top(|ui| {ui.spacing_mut().item_spacing.x = 4.0;--- --- let mut edit = egui::TextEdit::multiline(&mut t.text)--- --- .font(font.clone())+++ +++ let output = egui::TextEdit::multiline(&mut t.text)+++ +++ .font(font).desired_width(width).desired_rows(1)--- --- .align(egui::Align2::new(halign, egui::Align::TOP))+++ +++ .layouter(&mut layouter)// Keep the page editor's original inset; the theme's larger button padding// otherwise shifts narrow right-aligned boxes away from their text edge..margin(egui::Margin::symmetric(4, 2)).background_color(if background_ready { Color32::TRANSPARENT } else { Color32::WHITE })--- --- .text_color(Color32::from_rgb(cr, cg, cb))+++ +++ .text_color(color).hint_text(tl!("Type text"))- .id(input);-- --- .id_salt("added-text-edit");--- --- if letter_spacing != 0.0 {--- --- edit = edit.layouter(&mut spaced);+++ +++ .id(input)+++ +++ .show(ui);+++ +++ let resp = output.response;+++ +++ if let Some(cursor) = output.cursor_range {+++ +++ let chars = cursor.as_sorted_char_range();+++ +++ let byte = |index: usize| t.text.char_indices().nth(index).map_or(t.text.len(), |(at, _)| at);+++ +++ t.selection = Some(byte(chars.start.into())..byte(chars.end.into()));++ +++ }- let resp = ui.add(edit).accessible_name(tl!("Added text"));+++ +++ // Each paragraph keeps its own alignment through the typing.+++ +++ if t.text != before {+++ +++ crate::edit_text_ui::follow_typing(ui.ctx(), input, &before, &t.text, &mut [&mut t.style.aligns]);+ }-- --- let resp = ui.add(edit).accessible_name(tl!("Added text"));+++ +++ // The editor has no visible label; name it for assistive tech.+++ +++ resp.response.clone().accessible_name(tl!("Added text"));if t.focus {resp.request_focus();+++ +++ if let Some(range) = &t.selection {+++ +++ crate::edit_text_ui::reselect(ui.ctx(), input, &t.text, range);+++ +++ }t.focus = false;}let buttons = egui::Frame::NONE@@@@@@@@ -717,11 -688,6 -688,6 -756,63 -688,6 -688,6 -688,6 +762,63 @@@@@@@@ fn finish(cv: &mut ContentView, d: Text}}++ +++/// The added-text box's text field.++ +++pub(crate) fn input_id() -> egui::Id {++ +++ egui::Id::unique("added-text-input")++ +++}++ ++++++ +++/// `text` laid out as added text with `style` is drawn: each paragraph (line typed with Enter) wrapped+++ +++/// to `wrap` and placed by its own alignment, a justified one with every row but its last+++ +++/// stretched.+++ +++fn aligned_galley(+++ +++ ui: &egui::Ui,+++ +++ text: &str,+++ +++ style: &AddedText,+++ +++ font: &egui::FontId,+++ +++ color: Color32,+++ +++ letter_spacing: f32,+++ +++ wrap: f32,+++ +++) -> std::sync::Arc<egui::Galley> {+++ +++ use pdfcraft_engine::TextAlign;+++ +++ let job = |text: &str, align: TextAlign| {+++ +++ let mut job = spaced_job(text, font, color, letter_spacing, wrap, egui::Align::Min);+++ +++ job.justify = align == TextAlign::Justify;+++ +++ job+++ +++ };+++ +++ let uniform = text.split('\n').enumerate().all(|(i, _)| style.paragraph_align(i) == style.align);+++ +++ if uniform && style.align != TextAlign::Center && style.align != TextAlign::Right {+++ +++ return ui.fonts_mut(|f| f.layout_job(job(text, style.align)));+++ +++ }+++ +++ // Each paragraph on its own (egui aligns a whole job one way), its rows moved within the+++ +++ // box's width, then joined in order: the caret and selection see one text.+++ +++ let mut galleys = Vec::new();+++ +++ let mut start = 0;+++ +++ for (i, paragraph) in text.split('\n').enumerate() {+++ +++ let end = start + paragraph.len();+++ +++ // The last paragraph keeps a trailing break, as egui's own split does.+++ +++ let last = end + 1 == text.len();+++ +++ let piece = if last { text.get(start..).unwrap_or_default() } else { paragraph };+++ +++ let mut galley = ui.fonts_mut(|f| f.layout_job(job(piece, style.paragraph_align(i))));+++ +++ let g = std::sync::Arc::make_mut(&mut galley);+++ +++ for placed in &mut g.rows {+++ +++ let free = (wrap - placed.row.size.x).max(0.0);+++ +++ placed.pos.x = match style.paragraph_align(i) {+++ +++ TextAlign::Center => free / 2.0,+++ +++ TextAlign::Right => free,+++ +++ TextAlign::Left | TextAlign::Justify => 0.0,+++ +++ };+++ +++ }+++ +++ g.rect = Rect::from_min_max(Pos2::ZERO, Pos2::new(g.rect.width().max(wrap), g.rect.height()));+++ +++ galleys.push(galley);+++ +++ if last {+++ +++ break;+++ +++ }+++ +++ start = end + 1;+++ +++ }+++ +++ let whole = std::sync::Arc::new(spaced_job(text, font, color, letter_spacing, wrap, egui::Align::Min));+++ +++ std::sync::Arc::new(egui::Galley::concat(whole, &galleys, ui.ctx().pixels_per_point()))+++ +++}+++ +++/// How to use the tools, under the Add content list.pub(crate) fn hint(ui: &mut egui::Ui, t: &Tokens) {ui.label(diff --cc crates/ui-egui/src/tools/edit_text_ui.rsindex 2f157f5f5,224bc3f54,224bc3f54,f5ba4e0b6,c8bf9867b,224bc3f54,224bc3f54..768af2059--- a/crates/ui-egui/src/tools/edit_text_ui.rs+++ b/crates/ui-egui/src/tools/edit_text_ui.rs@@@@@@@@ -12,9 -12,8 -12,8 -12,7 -12,8 -12,8 -12,8 +12,9 @@@@@@@@ use pdfcraft_engine::{Edit, ObjectKinduse pdfcraft_render::DocInfo;use crate::canvas::{DocView, PageToolContext, PageXform};+ use crate::page_cursor::Layer;use crate::page_pointer::PagePointer;++++++use crate::page_router::{Hit, Owner, ParagraphPart};mod background;mod image;@@@@@@@@ -82,53 -81,8 -81,8 -80,124 -81,8 -81,8 -81,8 +82,124 @@@@@@@@ pub struct LineEditor/// horizontal scale (%), and what they were.pub extras: Extras,extras0: Extras,++ +++ /// The text the box's own Undo history starts from; see [`forget_typing_before`].++ +++ typing_from: Option<String>,++ +++}++ +++++ +++/// The paragraph editor's text box.++ +++pub(crate) fn input_id() -> egui::Id {++ +++ egui::Id::unique("edit-text-line-input")++ +++}++ +++++ +++/// The page text box `id` keeps its own Undo history, across every paragraph or box it has shown++ +++/// in every tab (they share the id). Once the page has `text` (the box opened on it, or formatting++ +++/// applied it), that history is cleared: Undo in the box takes back only what was typed since, and++ +++/// then reaches the document. Kept, it put back text from another paragraph, or the whole paragraph++ +++/// as it was before a format change, into a box showing the page as it is now. `from` is the box's++ +++/// own record of that; which document `doc` last used the history is kept beside it, since a box++ +++/// in another tab on the same text would otherwise take that document's typing with its Redo.++ +++/// When another document's box takes the text box, the box it leaves keeps its history (and++ +++/// caret) aside, and gets it back on its return, so its typing can still be undone there. Each++ +++/// box claims the text box when it is drawn, and Undo and Redo from the menu claim it first too,++ +++/// since they can run before the box is drawn again after a tab switch.++ +++pub(crate) fn forget_typing_before(ctx: &egui::Context, id: egui::Id, doc: pdfcraft_engine::DocId, from: &mut Option<String>, text: &str) {++ +++ let owner = id.with("typing-doc");++ +++ let last = ctx.data(|d| d.get_temp::<pdfcraft_engine::DocId>(owner));++ +++ if from.as_deref() == Some(text) && last == Some(doc) {++ +++ return;++ +++ }++ +++ let aside = |doc: pdfcraft_engine::DocId| id.with(("typing-aside", doc));+++ +++ let aligns = id.with(ALIGN_HISTORY);++ +++ if let Some(left) = last.filter(|l| *l != doc)++ +++ && let Some(state) = egui::TextEdit::load_state(ctx, id)++ +++ {++ +++ // A copy of its own: a state's history is shared between its clones, and the next box- // clears it in place.+++ +++ // clears it in place. The rows' alignments by text go with it.++ +++ let mut kept = egui::text_edit::TextEditState::default();++ +++ kept.cursor = state.cursor;++ +++ kept.set_undoer(state.undoer());- ctx.data_mut(|d| d.insert_temp(aside(left), kept));+++ +++ ctx.data_mut(|d| {+++ +++ let rows = d.get_temp::<AlignHistory>(aligns).unwrap_or_default();+++ +++ d.insert_temp(aside(left), (kept, rows));+++ +++ });++ +++ }++ +++ // Only the same box, still on the text it opened on, takes its history back.- let back = ctx.data_mut(|d| d.remove_temp::<egui::text_edit::TextEditState>(aside(doc))).filter(|_| from.as_deref() == Some(text));- // A box new to the text box starts with nothing of the last one's: no history, caret or- // selection.- let state = back.unwrap_or_default();+++ +++ let back =+++ +++ ctx.data_mut(|d| d.remove_temp::<(egui::text_edit::TextEditState, AlignHistory)>(aside(doc))).filter(|_| from.as_deref() == Some(text));+++ +++ // A box new to the text box starts with nothing of the last one's: no history, caret,+++ +++ // selection or rows' alignments by text.+++ +++ let (state, rows) = back.unwrap_or_default();++ +++ egui::TextEdit::store_state(ctx, id, state);- ctx.data_mut(|d| d.insert_temp(owner, doc));+++ +++ ctx.data_mut(|d| {+++ +++ d.insert_temp(owner, doc);+++ +++ d.insert_temp(aligns, rows);+++ +++ });++ +++ *from = Some(text.to_owned());++ +++}++ ++++++ +++/// Each text a page box has shown through its own typing, with its rows' alignments then, oldest+++ +++/// last: egui's history keeps only the text and the caret.+++ +++type AlignHistory = Vec<(String, Vec<Vec<Option<pdfcraft_engine::TextAlign>>>)>;+++ +++const ALIGN_HISTORY: &str = "aligns-by-text";+++ +++/// As many texts as egui's own history keeps.+++ +++const ALIGN_HISTORY_LEN: usize = 100;+++ ++++++ +++/// The page text box `id` went from `before` to `after` through its own typing (typing, Undo or+++ +++/// Redo), and each list of row alignments in `aligns` follows. A text the box showed before gets+++ +++/// back the alignments it had then, so Undo bringing back a deleted row brings back its+++ +++/// alignment; a new text follows the edit ([`pdfcraft_engine::paragraph_align::remap`]). An+++ +++/// alignment picked since makes the older texts' alignments stale, and they are dropped.+++ +++pub(crate) fn follow_typing(+++ +++ ctx: &egui::Context,+++ +++ id: egui::Id,+++ +++ before: &str,+++ +++ after: &str,+++ +++ aligns: &mut [&mut Vec<Option<pdfcraft_engine::TextAlign>>],+++ +++) {+++ +++ let now: Vec<Vec<_>> = aligns.iter().map(|a| a.to_vec()).collect();+++ +++ // Where the edit left the caret, as a byte of `after`: it says which of two same rows changed.+++ +++ let caret = egui::TextEdit::load_state(ctx, id)+++ +++ .and_then(|s| s.cursor.char_range())+++ +++ .map(|r| after.char_indices().nth(r.primary.index.into()).map_or(after.len(), |(at, _)| at));+++ +++ let next = ctx.data_mut(|d| {+++ +++ let seen = d.get_temp_mut_or_default::<AlignHistory>(id.with(ALIGN_HISTORY));+++ +++ if seen.iter().any(|(text, was)| text == before && *was != now) {+++ +++ seen.clear();+++ +++ }+++ +++ remember(seen, before, now.clone());+++ +++ let next = match seen.iter().rev().find(|(text, _)| text == after) {+++ +++ Some((_, was)) if was.len() == now.len() => was.clone(),+++ +++ _ => now.iter().map(|a| pdfcraft_engine::paragraph_align::remap_at(before, after, a, caret)).collect(),+++ +++ };+++ +++ remember(seen, after, next.clone());+++ +++ next+++ +++ });+++ +++ for (slot, a) in aligns.iter_mut().zip(next) {+++ +++ **slot = a;+++ +++ }+++ +++}+++ ++++++ +++fn remember(seen: &mut AlignHistory, text: &str, aligns: Vec<Vec<Option<pdfcraft_engine::TextAlign>>>) {+++ +++ seen.retain(|(t, _)| t != text);+++ +++ seen.push((text.to_owned(), aligns));+++ +++ if seen.len() > ALIGN_HISTORY_LEN {+++ +++ seen.remove(0);+++ +++ }+++ +++}+++ ++++++ +++/// Select `range` (bytes of `text`) in the page text box `id` again. egui keeps a box's selection+++ +++/// only while it has the focus, so a click on Format text drops it; given back as formatting+++ +++/// returns the focus, it stays shown, and a second choice reaches the same text.+++ +++pub(crate) fn reselect(ctx: &egui::Context, id: egui::Id, text: &str, range: &std::ops::Range<usize>) {+++ +++ let chars = |at: usize| text.get(..at).map(|s| s.chars().count());+++ +++ let (Some(start), Some(end)) = (chars(range.start), chars(range.end)) else { return };+++ +++ if start < end {+++ +++ let mut state = egui::TextEdit::load_state(ctx, id).unwrap_or_default();+++ +++ state.cursor.set_char_range(Some(egui::text::CCursorRange::two(egui::text::CCursor::new(start), egui::text::CCursor::new(end))));+++ +++ egui::TextEdit::store_state(ctx, id, state);+++ +++ }+ }+#[derive(Clone, Copy, Debug, PartialEq)]pub struct Extras {pub underline: bool,@@@@@@@@ -243,8 -197,6 -197,6 -320,9 -197,6 -197,6 -197,6 +322,9 @@@@@@@@ impl LineEditorself.look0 = self.look.clone();self.extras0 = self.extras;self.original = self.text.clone();- // Formatting commits the baseline even when the text is unchanged.+++ +++ // The page now has this text: the box's history restarts, even when the format left the+++ +++ // text as it was, so a Redo from before can't put undone typing back on top of it.++ +++ self.typing_from = None;self.focus = true;}@@@@@@@@ -514,16 -428,23 -428,23 -579,27 -431,23 -428,23 -428,23 +615,16 @@@@@@@@ pub(crate) fn page_input(cx: PageToolCoreturn true;}let Some(p) = ptr.within(xf.rect) else { return false };------ let Some((hit, grip)) = grab_at(&boxes, p, upright) else { return false };------ if active != Some(hit) {------ painter.rect_stroke(boxes[hit], CornerRadius::same(2), Stroke::new(1.5, ACCENT), egui::StrokeKind::Outside);++++++ // The paragraph under the pointer: outlined, with its width handles when closed.++++++ let Some((hovered, _)) = grab_at(&boxes, p, upright) else { return false };++++++ if active != Some(hovered) {++++++ painter.rect_stroke(boxes[hovered], CornerRadius::same(2), Stroke::new(1.5, ACCENT), egui::StrokeKind::Outside);}------ let on_edge = active.is_none() && grip != Grip::Move;if upright && active.is_none() {------ draw_handles(boxes[hit]);------ }------ // A closed paragraph moves when dragged (the four-way arrow says so; a click still opens it-- --- // for typing); an edge rewraps it. The open one takes the text cursor.-- --- if on_edge {-- --- view.cursor.claim(Layer::Handle, egui::CursorIcon::ResizeHorizontal);-- --- } else if active.is_none() {-- --- view.cursor.claim(Layer::Text, egui::CursorIcon::Move);-- --- } else {-- --- view.cursor.claim(if active == Some(hit) { Layer::Editor } else { Layer::Text }, egui::CursorIcon::Text);- // for typing); an edge rewraps it. The open one takes the text cursor. Only where the page- // shows, so the mode bar and side panels over a paragraph scrolled under them keep their own- // cursor (#2755).- if resp.contains_pointer() {- ui.ctx().set_cursor_icon(if on_edge {- egui::CursorIcon::ResizeHorizontal- } else if active.is_none() {- egui::CursorIcon::Move- } else {- egui::CursorIcon::Text- });++++++ draw_handles(boxes[hovered]);}++++++ // A click opens the paragraph the press was on.++++++ let Some((hit, _)) = owner else { return true };if resp.clicked() {view.image_selection = None;// A click that moves the editor to another paragraph applies the open one first, so its@@@@@@@@ -551,10 -472,9 -472,9 -627,12 -475,9 -472,9 -472,9 +652,12 @@@@@@@@/// The inline editor; returns the edit once the text is applied.pub(crate) fn overlay(ctx: &egui::Context, view: &mut DocView, info: &DocInfo) -> Option<Edit> {-- --- // Clicks outside the document (the Format text panel) keep the paragraph open. Where the-- --- // click landed is `interact_pos`: `latest_pos` is gone on the frame a tap lifts.-- --- let outside = ctx.input(|i| i.pointer.interact_pos()).is_some_and(|p| !view.viewport_rect().contains(p));++ +++ let view_id = view.id;- // Clicks outside the document (the Format text panel) keep the paragraph open. Where the- // click landed is `interact_pos`: `latest_pos` is gone on the frame a tap lifts.- let outside = ctx.input(|i| i.pointer.interact_pos()).is_some_and(|p| !view.viewport_rect().contains(p));+++ +++ // Clicks outside the document (the Format text panel) keep the paragraph open, as does the+++ +++ // keyboard moving there. Where the click landed is `interact_pos`: `latest_pos` is gone on the+++ +++ // frame a tap lifts.+++ +++ let away = |p: egui::Pos2| !view.viewport_rect().contains(p);+++ +++ let outside = ctx.input(|i| i.pointer.interact_pos()).is_some_and(away) || focus_pos(ctx).is_some_and(away);let page = view.line_editor.as_ref()?.page;let xf = view.page_xform(page)?;let hold = view.objects.hold_editor;@@@@@@@@ -668,10 -588,8 -588,8 -746,11 -591,8 -588,8 -588,8 +771,11 @@@@@@@@let galley = editor_galley(ui, &snapshot, text.as_str(), scale, wrap_width);if snapshot.changes_with(text.as_str()) { galley } else { unseen(galley) }};+++ +++ let before = ed.text.clone();++ +++ let input = input_id();++ +++ ed.claim_typing(ui.ctx(), view_id);let output = egui::TextEdit::multiline(&mut ed.text)-- --- .id(egui::Id::unique("edit-text-line-input"))++ +++ .id(input).font(font.clone()).margin(egui::Margin::ZERO).layouter(&mut layouter)@@@@@@@@ -882,7 -796,6 -796,6 -1072,8 -799,6 -796,6 -796,6 +1100,8 @@@@@@@@ C", &picketext: "Typed text".into(),style: crate::content_ui::default_style(),focus: true,+++ +++ selection: None,++ +++ typing_from: None,};app.views[0].content.draft = Some(draft.clone());diff --cc crates/ui-egui/src/workflows/optimize_ui.rsindex d937592ab,3bb80ac43,3bb80ac43,3bb80ac43,3bb80ac43,32052eb1f,32052eb1f..8b428a972--- a/crates/ui-egui/src/workflows/optimize_ui.rs+++ b/crates/ui-egui/src/workflows/optimize_ui.rs@@@@@@@@ -8,7 -8,7 -8,7 -8,7 -8,7 -8,7 -8,7 +8,7 @@@@@@@@use std::sync::{Arc, Mutex};use egui::{Align, Layout, RichText};---- use pdfcraft_engine::optimize::{Compatibility, Compression, ImageSettings, Preset, QUALITIES, Settings};--use pdfcraft_engine::optimize::{Compatibility, Compression, ImageSettings, MonoCompression, Preset, QUALITIES, Settings};++++++use pdfcraft_engine::optimize::{Compatibility, Compression, ImageSettings, MonoCompression, MonoSettings, Preset, QUALITIES, Settings};use pdfcraft_engine::optimizer::{OptimizeStage, Optimized};use pdfcraft_engine::{DocId, EditError, Hidden, OptimizeReport};@@@@@@@@ -143,30 -143,6 -143,6 -143,6 -143,6 -143,25 -143,25 +143,32 @@@@@@@@ fn image_row(ui: &mut egui::Ui, id: &stui.add_space(8.0);}--/// Monochrome Images: how 1-bit images and image masks are stored.--fn mono_row(ui: &mut egui::Ui, m: &mut MonoCompression) {++++++/// Monochrome Images: how black-and-white images and image masks are resampled and stored.++++++fn mono_row(ui: &mut egui::Ui, m: &mut MonoSettings) {++++ ui.label(egui::RichText::new(tl!("Monochrome Images")).font(theme::semibold(13.0)));++++++ ui.horizontal(|ui| {++++++ ui.add(widgets::checkbox(&mut m.downsample, tl!("Downsample to")));++++++ ui.add_enabled(m.downsample, egui::DragValue::new(&mut m.target_ppi).range(9.0..=2400.0).suffix(" ppi"));++++++ ui.label(tl!("for images above"));++++++ ui.add_enabled(m.downsample, egui::DragValue::new(&mut m.above_ppi).range(9.0..=2400.0).suffix(" ppi"));++++++ });++++++ m.above_ppi = m.above_ppi.max(m.target_ppi);++++ ui.horizontal(|ui| {++++ ui.label(tl!("Compression"));-- let label = match m {++++++ let label = match m.compression {++++ MonoCompression::CcittG4 => tl!("CCITT Group 4"),+++++ MonoCompression::Jbig2 => tl!("JBIG2 (lossless)"),++++ MonoCompression::Retain => tl!("Retain existing"),++++ };++++ craft_ui::ComboBox::from_id_salt(("mono", "compression")).selected_text(label).show_ui(ui, |ui| {-- ui.selectable_value(m, MonoCompression::CcittG4, tl!("CCITT Group 4"));-- ui.selectable_value(m, MonoCompression::Jbig2, tl!("JBIG2 (lossless)"));-- ui.selectable_value(m, MonoCompression::Retain, tl!("Retain existing"));++++++ ui.selectable_value(&mut m.compression, MonoCompression::CcittG4, tl!("CCITT Group 4"));+++++++ ui.selectable_value(&mut m.compression, MonoCompression::Jbig2, tl!("JBIG2 (lossless)"));++++++ ui.selectable_value(&mut m.compression, MonoCompression::Retain, tl!("Retain existing"));++++ });++++ });++++ ui.add_space(8.0);++++ }++++fn discard_box(ui: &mut egui::Ui, list: &mut Vec<Hidden>, h: Hidden, label: &str) {let mut on = list.contains(&h);if ui.add(widgets::checkbox(&mut on, tl!(label))).changed() {diff --cc crates/ui-egui/tests/it/content.rsindex cfb469e75,4a7927f69,4a7927f69,49ce6e4d0,4a7927f69,4a7927f69,4a7927f69..cb29ba99b--- a/crates/ui-egui/tests/it/content.rs+++ b/crates/ui-egui/tests/it/content.rs@@@@@@@@ -946,252 -946,3 -946,3 -973,455 -946,3 -946,3 -946,3 +973,455 @@@@@@@@ fn a_resized_added_picture_shows_only_alet pixels = h.render().unwrap();assert!(red(&pixels, kept) > 100 && red(&pixels, gone) == 0, "the page raster has the picture at its new size");}++ ++++++ +++/// Bug A for added text: with one line of the box selected, an alignment applies to that line+++ +++/// only, as does a second one, the box stays open, and Undo puts it back and closes the box.+++ +++#[test]+++ +++fn aligning_a_selected_line_of_added_text_aligns_only_that_line() {+++ +++ let mut h = harness();+++ +++ let rect = [40.0, 195.0, 240.0, 220.0];+++ +++ let text = pdfcraft_engine::AddedText { rect, text: "Line one\nLine two".into(), ..Default::default() };+++ +++ assert!(h.state_mut().apply_edit(pdfcraft_engine::Edit::AddText { page: 0, text }));+++ +++ assert!(h.state_mut().execute("edit.text"));+++ +++ h.run_steps(3);+++ +++ let point = at(&h, 45.0, 195.0);+++ +++ click(&mut h, point);+++ +++ assert_eq!(h.state().views[0].content.draft.as_ref().and_then(|d| d.index), Some(0), "the editor opened on the text");+++ +++ h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::End);+++ +++ h.key_press_modifiers(egui::Modifiers::SHIFT, egui::Key::Home);+++ +++ h.run_steps(2);+++ +++ let button = h.get_by_label("Alignment").rect().center();+++ +++ click(&mut h, button);+++ +++ let item = h.get_by_label("Align right").rect().center();+++ +++ click(&mut h, item);+++ +++ let aligns = |h: &Harness<'static, PdfCraftApp>| match &added(h)[0].content {+++ +++ pdfcraft_engine::AddedContent::Text(t) => (t.align, t.aligns.clone()),+++ +++ _ => panic!(),+++ +++ };+++ +++ assert_eq!(aligns(&h), (pdfcraft_engine::TextAlign::Left, vec![None, Some(pdfcraft_engine::TextAlign::Right)]));+++ +++ assert!(h.state().views[0].content.draft.is_some(), "the box stays open");+++ +++ // A second choice, the line still selected, is for that line again.+++ +++ let button = h.get_by_label("Alignment").rect().center();+++ +++ click(&mut h, button);+++ +++ let item = h.get_by_label("Centre").rect().center();+++ +++ click(&mut h, item);+++ +++ assert_eq!(aligns(&h), (pdfcraft_engine::TextAlign::Left, vec![None, Some(pdfcraft_engine::TextAlign::Center)]));+++ +++ h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::Z);+++ +++ h.run_steps(4);+++ +++ assert_eq!(aligns(&h), (pdfcraft_engine::TextAlign::Left, vec![None, Some(pdfcraft_engine::TextAlign::Right)]), "Undo puts it back");+++ +++ assert!(h.state().views[0].content.draft.is_none(), "and closes the box");+++ +++ assert!(h.state_mut().execute("edit.undo"));+++ +++ assert_eq!(aligns(&h), (pdfcraft_engine::TextAlign::Left, vec![]));+++ +++}+++ ++++++ +++/// Two lines of added text with the same words, each aligned its own way: deleting the first line+++ +++/// with its break leaves the second line's alignment, not the deleted one's (CodeRabbit on+++ +++/// 648dd428).+++ +++#[test]+++ +++fn deleting_the_first_of_two_same_lines_keeps_the_second_lines_alignment() {+++ +++ use pdfcraft_engine::TextAlign::{Center, Right};+++ +++ let mut h = harness();+++ +++ let rect = [40.0, 195.0, 240.0, 220.0];+++ +++ let text = pdfcraft_engine::AddedText { rect, text: "Same\nSame".into(), aligns: vec![Some(Center), Some(Right)], ..Default::default() };+++ +++ assert!(h.state_mut().apply_edit(pdfcraft_engine::Edit::AddText { page: 0, text }));+++ +++ assert!(h.state_mut().execute("edit.text"));+++ +++ h.run_steps(3);+++ +++ let point = at(&h, 120.0, 195.0);+++ +++ click(&mut h, point);+++ +++ assert_eq!(h.state().views[0].content.draft.as_ref().and_then(|d| d.index), Some(0), "the editor opened on the text");+++ +++ // Select the first line with its break, and delete it.+++ +++ h.key_press(egui::Key::ArrowUp);+++ +++ h.key_press(egui::Key::Home);+++ +++ // "Same" and its line break.+++ +++ for _ in 0..5 {+++ +++ h.key_press_modifiers(egui::Modifiers::SHIFT, egui::Key::ArrowRight);+++ +++ }+++ +++ h.key_press(egui::Key::Backspace);+++ +++ h.run_steps(2);+++ +++ let d = h.state().views[0].content.draft.as_ref().expect("still typing");+++ +++ assert_eq!((d.text.as_str(), d.style.aligns.clone()), ("Same", vec![Some(Right)]), "the second line's alignment stays");+++ +++}+++ ++++++ +++/// The same with the alignment controls reached by keyboard or a screen reader (focused, then+++ +++/// pressed, with no pointer): the box stays open when the focus leaves it for the Format text+++ +++/// panel, and both choices are for the selected line.+++ +++#[test]+++ +++fn aligning_a_selected_line_of_added_text_by_keyboard_keeps_the_box_open() {+++ +++ let mut h = harness();+++ +++ let rect = [40.0, 195.0, 240.0, 220.0];+++ +++ let text = pdfcraft_engine::AddedText {+++ +++ rect,+++ +++ text: "Line one+++ +++Line two"+++ +++ .into(),+++ +++ ..Default::default()+++ +++ };+++ +++ assert!(h.state_mut().apply_edit(pdfcraft_engine::Edit::AddText { page: 0, text }));+++ +++ assert!(h.state_mut().execute("edit.text"));+++ +++ h.run_steps(3);+++ +++ let point = at(&h, 45.0, 195.0);+++ +++ click(&mut h, point);+++ +++ assert_eq!(h.state().views[0].content.draft.as_ref().and_then(|d| d.index), Some(0), "the editor opened on the text");+++ +++ h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::End);+++ +++ h.key_press_modifiers(egui::Modifiers::SHIFT, egui::Key::Home);+++ +++ h.run_steps(2);+++ +++ let align_by_focus = |h: &mut Harness<'static, PdfCraftApp>, choice: &str| {+++ +++ for label in ["Alignment", choice] {+++ +++ h.get_by_label(label).focus();+++ +++ h.run_steps(2);+++ +++ h.get_by_label(label).click();+++ +++ h.run_steps(3);+++ +++ }+++ +++ };+++ +++ let aligns = |h: &Harness<'static, PdfCraftApp>| match &added(h)[0].content {+++ +++ pdfcraft_engine::AddedContent::Text(t) => (t.align, t.aligns.clone()),+++ +++ _ => panic!(),+++ +++ };+++ +++ align_by_focus(&mut h, "Align right");+++ +++ assert!(h.state().views[0].content.draft.is_some(), "the box stays open");+++ +++ assert_eq!(aligns(&h), (pdfcraft_engine::TextAlign::Left, vec![None, Some(pdfcraft_engine::TextAlign::Right)]));+++ +++ align_by_focus(&mut h, "Centre");+++ +++ assert!(h.state().views[0].content.draft.is_some(), "the box is still open");+++ +++ assert_eq!(aligns(&h), (pdfcraft_engine::TextAlign::Left, vec![None, Some(pdfcraft_engine::TextAlign::Center)]));+++ +++}+++ +++++ +++/// The same in an added text box: Redo after Undo puts the typing back in the box, and the++ +++/// document's own Redo stays waiting.++ +++#[test]++ +++fn redo_after_undoing_typing_in_added_text_puts_it_back() {++ +++ let mut h = harness();++ +++ let rect = [40.0, 195.0, 240.0, 210.0];++ +++ let text = pdfcraft_engine::AddedText { rect, text: "Reviewed".into(), ..Default::default() };++ +++ assert!(h.state_mut().apply_edit(pdfcraft_engine::Edit::AddText { page: 0, text: text.clone() }));++ +++ let bold = pdfcraft_engine::AddedText { bold: true, ..text };++ +++ assert!(h.state_mut().apply_edit(pdfcraft_engine::Edit::UpdateContent { page: 0, index: 0, content: pdfcraft_engine::AddedContent::Text(bold) }));++ +++ assert!(h.state_mut().execute("edit.undo"));++ +++ assert!(h.state_mut().execute("edit.text"));++ +++ h.run_steps(3);++ +++ let point = at(&h, 45.0, 195.0);++ +++ click(&mut h, point);++ +++ assert_eq!(h.state().views[0].content.draft.as_ref().and_then(|d| d.index), Some(0), "the editor opened on the text");++ +++ h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::End);++ +++ h.event(egui::Event::Text(" twice".into()));++ +++ h.run_steps(2);++ +++ h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::Z);++ +++ h.run_steps(3);++ +++ assert_eq!(h.state().views[0].content.draft.as_ref().map(|d| d.text.as_str()), Some("Reviewed"));++ +++ h.key_press_modifiers(egui::Modifiers::COMMAND | egui::Modifiers::SHIFT, egui::Key::Z);++ +++ h.run_steps(3);++ +++ assert_eq!(h.state().views[0].content.draft.as_ref().map(|d| d.text.as_str()), Some("Reviewed twice"), "Redo puts the typing back");++ +++ let s = h.state();++ +++ let doc = s.session.get(s.views[0].id).unwrap();++ +++ assert_eq!(doc.can_redo(), Some("Edit content"), "the document's Redo still waits");++ +++}++ +++++ +++/// Redo from the menu with retyping the page doesn't have yet in an added text box: the typing++ +++/// stays in the box and the document's Redo waits (closing the box first wrote the typing, which++ +++/// dropped that Redo). After Undo in the box, Redo from the menu puts the typing back there.++ +++#[test]++ +++fn redo_from_the_menu_with_retyping_in_the_box_keeps_the_documents_redo() {++ +++ let mut h = harness();++ +++ let rect = [40.0, 195.0, 240.0, 210.0];++ +++ let text = pdfcraft_engine::AddedText { rect, text: "Reviewed".into(), ..Default::default() };++ +++ assert!(h.state_mut().apply_edit(pdfcraft_engine::Edit::AddText { page: 0, text: text.clone() }));++ +++ let bold = pdfcraft_engine::AddedText { bold: true, ..text };++ +++ assert!(h.state_mut().apply_edit(pdfcraft_engine::Edit::UpdateContent { page: 0, index: 0, content: pdfcraft_engine::AddedContent::Text(bold) }));++ +++ assert!(h.state_mut().execute("edit.undo"));++ +++ assert!(h.state_mut().execute("edit.text"));++ +++ h.run_steps(3);++ +++ let point = at(&h, 45.0, 195.0);++ +++ click(&mut h, point);++ +++ assert_eq!(h.state().views[0].content.draft.as_ref().and_then(|d| d.index), Some(0), "the editor opened on the text");++ +++ h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::End);++ +++ h.event(egui::Event::Text(" twice".into()));++ +++ h.run_steps(2);++ +++ assert!(h.state_mut().execute("edit.redo"));++ +++ h.run_steps(3);++ +++ assert_eq!(h.state().views[0].content.draft.as_ref().map(|d| d.text.as_str()), Some("Reviewed twice"), "the typing stays in the box");++ +++ h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::Z);++ +++ h.run_steps(3);++ +++ assert_eq!(h.state().views[0].content.draft.as_ref().map(|d| d.text.as_str()), Some("Reviewed"), "Undo takes it back in the box");++ +++ assert!(h.state_mut().execute("edit.redo"));++ +++ h.run_steps(3);++ +++ assert_eq!(h.state().views[0].content.draft.as_ref().map(|d| d.text.as_str()), Some("Reviewed twice"), "Redo from the menu puts it back");++ +++ let s = h.state();++ +++ assert_eq!(s.session.get(s.views[0].id).unwrap().can_redo(), Some("Edit content"), "the document's Redo still waits");++ +++}++ +++++ +++/// Undo from the menu with retyping the page doesn't have yet in an added text box: the box takes++ +++/// it back and stays open, and the document's waiting Redo stays.++ +++#[test]++ +++fn undo_from_the_menu_takes_back_retyping_in_the_added_text_box() {++ +++ let mut h = harness();++ +++ let rect = [40.0, 195.0, 240.0, 210.0];++ +++ let text = pdfcraft_engine::AddedText { rect, text: "Reviewed".into(), ..Default::default() };++ +++ assert!(h.state_mut().apply_edit(pdfcraft_engine::Edit::AddText { page: 0, text: text.clone() }));++ +++ let bold = pdfcraft_engine::AddedText { bold: true, ..text };++ +++ assert!(h.state_mut().apply_edit(pdfcraft_engine::Edit::UpdateContent { page: 0, index: 0, content: pdfcraft_engine::AddedContent::Text(bold) }));++ +++ assert!(h.state_mut().execute("edit.undo"));++ +++ assert!(h.state_mut().execute("edit.text"));++ +++ h.run_steps(3);++ +++ let point = at(&h, 45.0, 195.0);++ +++ click(&mut h, point);++ +++ assert_eq!(h.state().views[0].content.draft.as_ref().and_then(|d| d.index), Some(0), "the editor opened on the text");++ +++ h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::End);++ +++ h.event(egui::Event::Text(" twice".into()));++ +++ h.run_steps(2);+++ +++ h.key_press_modifiers(egui::Modifiers::SHIFT, egui::Key::Home);+++ +++ h.run_steps(2);+++ +++ assert!(h.state().views[0].content.draft.as_ref().unwrap().selection.is_some());+++ +++ h.event(egui::Event::PointerMoved(egui::pos2(10.0, 10.0)));+++ +++ h.ctx.memory_mut(|m| m.request_focus(egui::Id::unique("test-menu")));++ +++ assert!(h.state_mut().execute("edit.undo"));+++ +++ assert_eq!(h.state().views[0].content.draft.as_ref().unwrap().selection, None, "menu history clears the old byte range before the next frame");++ +++ h.run_steps(3);++ +++ assert_eq!(h.state().views[0].content.draft.as_ref().map(|d| d.text.as_str()), Some("Reviewed"), "Undo takes it back in the box");++ +++ let s = h.state();++ +++ assert_eq!(s.session.get(s.views[0].id).unwrap().can_redo(), Some("Edit content"), "the document's Redo still waits");++ +++}++ +++++ +++/// Redo from the menu after Undo in an added text box, with nothing for the document to redo: the++ +++/// menu item follows the box's own Redo too, and puts the typing back.++ +++#[test]++ +++fn redo_from_the_menu_is_enabled_for_the_added_text_boxs_own_typing() {++ +++ let mut h = harness();++ +++ let rect = [40.0, 195.0, 240.0, 210.0];++ +++ let text = pdfcraft_engine::AddedText { rect, text: "Reviewed".into(), ..Default::default() };++ +++ assert!(h.state_mut().apply_edit(pdfcraft_engine::Edit::AddText { page: 0, text }));++ +++ assert!(h.state_mut().execute("edit.text"));++ +++ h.run_steps(3);++ +++ let point = at(&h, 45.0, 195.0);++ +++ click(&mut h, point);++ +++ assert_eq!(h.state().views[0].content.draft.as_ref().and_then(|d| d.index), Some(0), "the editor opened on the text");++ +++ h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::End);++ +++ h.event(egui::Event::Text(" twice".into()));++ +++ h.run_steps(2);++ +++ h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::Z);++ +++ h.run_steps(3);++ +++ assert_eq!(h.state().views[0].content.draft.as_ref().map(|d| d.text.as_str()), Some("Reviewed"), "Undo takes it back in the box");++ +++ assert_eq!(h.state().session.get(h.state().views[0].id).unwrap().can_redo(), None, "the document has nothing to redo");+++ +++ // A range retained while the unfocused editor still showed its previous text.+++ +++ h.state_mut().views[0].content.draft.as_mut().unwrap().selection = Some(0..1);+++ +++ h.event(egui::Event::PointerMoved(egui::pos2(10.0, 10.0)));+++ +++ h.ctx.memory_mut(|m| m.request_focus(egui::Id::unique("test-menu")));++ +++ assert!(h.state_mut().execute("edit.redo"), "Redo is enabled for the box's own step");+++ +++ assert_eq!(h.state().views[0].content.draft.as_ref().unwrap().selection, None, "menu history clears the old byte range before the next frame");++ +++ h.run_steps(3);++ +++ assert_eq!(h.state().views[0].content.draft.as_ref().map(|d| d.text.as_str()), Some("Reviewed twice"), "Redo puts it back");++ +++}++ ++++++ +++/// Saved added text of three lines aligned Left, Centre and Right: the centred line deleted+++ +++/// with its line break, then brought back with Ctrl+Z, is centred again, and Ctrl+Shift+Z deletes+++ +++/// it again. The box's history keeps only text, so the restored line took the first line's+++ +++/// alignment, and finishing the box would have saved that.+++ +++#[test]+++ +++fn undo_brings_a_deleted_line_of_added_text_back_with_its_alignment() {+++ +++ use pdfcraft_engine::TextAlign::{Center, Right};+++ +++ let mut h = harness();+++ +++ let rect = [40.0, 170.0, 240.0, 215.0];+++ +++ let aligns = vec![None, Some(Center), Some(Right)];+++ +++ let text = pdfcraft_engine::AddedText { rect, text: "A\nB\nC".into(), aligns: aligns.clone(), ..Default::default() };+++ +++ assert!(h.state_mut().apply_edit(pdfcraft_engine::Edit::AddText { page: 0, text }));+++ +++ assert!(h.state_mut().execute("edit.text"));+++ +++ h.run_steps(3);+++ +++ // On the first line, at the top of the box.+++ +++ let point = at(&h, 45.0, 205.0);+++ +++ click(&mut h, point);+++ +++ let draft = |h: &Harness<'static, PdfCraftApp>| h.state().views[0].content.draft.clone().expect("the box is open");+++ +++ assert_eq!((draft(&h).text, draft(&h).style.aligns), ("A\nB\nC".to_string(), aligns.clone()), "the editor opened on the text");+++ +++ // Select the second line with its line break, and delete it.+++ +++ h.run_steps(2);+++ +++ // To the start of the first line, wherever the click put the caret.+++ +++ for _ in 0..3 {+++ +++ h.key_press(egui::Key::ArrowUp);+++ +++ }+++ +++ h.key_press(egui::Key::Home);+++ +++ h.run_steps(1);+++ +++ h.key_press(egui::Key::ArrowDown);+++ +++ h.run_steps(1);+++ +++ h.key_press_modifiers(egui::Modifiers::SHIFT, egui::Key::ArrowDown);+++ +++ h.key_press(egui::Key::Backspace);+++ +++ h.run_steps(2);+++ +++ assert_eq!((draft(&h).text, draft(&h).style.aligns), ("A\nC".to_string(), vec![None, Some(Right)]), "the centred line is gone");+++ +++ h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::Z);+++ +++ h.run_steps(3);+++ +++ assert_eq!((draft(&h).text, draft(&h).style.aligns), ("A\nB\nC".to_string(), aligns), "Undo brings it back centred");+++ +++ h.key_press_modifiers(egui::Modifiers::COMMAND | egui::Modifiers::SHIFT, egui::Key::Z);+++ +++ h.run_steps(3);+++ +++ assert_eq!((draft(&h).text, draft(&h).style.aligns), ("A\nC".to_string(), vec![None, Some(Right)]), "Redo deletes it again");+++ +++}+++ +++++ +++/// Typing in tab A's added text box, the same text opened in tab B, then back to A: Edit ▸ Undo++ +++/// takes the typing back in A's box, which stays open.++ +++#[test]++ +++fn undo_after_a_round_trip_through_another_tab_takes_back_added_text_typing() {++ +++ let mut h = harness();++ +++ h.state_mut().open_bytes("copy.pdf", None, include_bytes!("../data/form.pdf").to_vec()).unwrap();++ +++ h.run_steps(4);++ +++ let text = pdfcraft_engine::AddedText { rect: [40.0, 195.0, 240.0, 210.0], text: "Reviewed".into(), ..Default::default() };++ +++ let open_in = |h: &mut Harness<'static, PdfCraftApp>, tab: usize| {++ +++ h.state_mut().active = Some(tab);++ +++ h.run_steps(2);++ +++ assert!(h.state_mut().execute("edit.text"));++ +++ h.run_steps(3);++ +++ let r = h.state().views[tab].page_screen_rect(0).expect("on screen");++ +++ let k = r.width() / 300.0;++ +++ click(h, r.min + egui::vec2(45.0 * k, 195.0 * k));++ +++ assert_eq!(h.state().views[tab].content.draft.as_ref().and_then(|d| d.index), Some(0), "the editor opened on the text");++ +++ };++ +++ for tab in [0, 1] {++ +++ h.state_mut().active = Some(tab);++ +++ assert!(h.state_mut().apply_edit(pdfcraft_engine::Edit::AddText { page: 0, text: text.clone() }));++ +++ }++ +++ open_in(&mut h, 0);++ +++ h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::End);++ +++ h.event(egui::Event::Text(" twice".into()));++ +++ h.run_steps(2);++ +++ open_in(&mut h, 1);++ +++ h.state_mut().active = Some(0);++ +++ h.run_steps(3);++ +++ let draft = |h: &Harness<'static, PdfCraftApp>| h.state().views[0].content.draft.as_ref().map(|d| d.text.clone());++ +++ assert_eq!(draft(&h).as_deref(), Some("Reviewed twice"), "A's box is still open with the typing");++ +++ assert!(h.state_mut().execute("edit.undo"));++ +++ h.run_steps(3);++ +++ assert_eq!(draft(&h).as_deref(), Some("Reviewed"), "Undo takes the typing back in A's box");++ +++}++ +++++ +++/// Edit ▸ Undo chosen in the same frame as the switch back to tab A's added text box, before it++ +++/// is drawn again: the shared text box still holds tab B's history, from a box on other text, so++ +++/// A's box claims its own back before stepping.++ +++#[test]++ +++fn undo_in_the_frame_of_the_switch_back_takes_back_added_text_typing() {++ +++ let mut h = harness();++ +++ h.state_mut().open_bytes("copy.pdf", None, include_bytes!("../data/form.pdf").to_vec()).unwrap();++ +++ h.run_steps(4);++ +++ let rect = [40.0, 195.0, 240.0, 210.0];++ +++ for (tab, text) in [(0, "Reviewed"), (1, "Approved")] {++ +++ h.state_mut().active = Some(tab);++ +++ let text = pdfcraft_engine::AddedText { rect, text: text.into(), ..Default::default() };++ +++ assert!(h.state_mut().apply_edit(pdfcraft_engine::Edit::AddText { page: 0, text }));++ +++ }++ +++ let open_in = |h: &mut Harness<'static, PdfCraftApp>, tab: usize| {++ +++ h.state_mut().active = Some(tab);++ +++ h.run_steps(2);++ +++ assert!(h.state_mut().execute("edit.text"));++ +++ h.run_steps(3);++ +++ let r = h.state().views[tab].page_screen_rect(0).expect("on screen");++ +++ let k = r.width() / 300.0;++ +++ click(h, r.min + egui::vec2(45.0 * k, 195.0 * k));++ +++ assert_eq!(h.state().views[tab].content.draft.as_ref().and_then(|d| d.index), Some(0), "the editor opened on the text");++ +++ };++ +++ open_in(&mut h, 0);++ +++ h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::End);++ +++ h.event(egui::Event::Text(" twice".into()));++ +++ h.run_steps(2);++ +++ open_in(&mut h, 1);++ +++ // Back to A and Undo at once: no frame draws A's box in between.++ +++ h.state_mut().active = Some(0);++ +++ assert!(h.state_mut().execute("edit.undo"));++ +++ h.run_steps(3);++ +++ assert_eq!(h.state().views[0].content.draft.as_ref().map(|d| d.text.as_str()), Some("Reviewed"), "Undo takes the typing back in A's box");++ +++}++ ++++++ +++/// Retyping taken back with Ctrl+Z, then Bold picked with the added text box still open: the+++ +++/// restyle is applied in place and the page has the box's text, so neither Ctrl+Shift+Z nor the+++ +++/// menu's Redo may bring the undone retyping back on top of the bold (CodeRabbit on a33a8bba).+++ +++#[test]+++ +++fn redo_after_restyling_open_added_text_never_brings_back_typing_undone_before_it() {+++ +++ for route in ["key", "menu"] {+++ +++ let mut h = harness();+++ +++ let rect = [40.0, 195.0, 240.0, 210.0];+++ +++ let text = pdfcraft_engine::AddedText { rect, text: "Reviewed".into(), ..Default::default() };+++ +++ assert!(h.state_mut().apply_edit(pdfcraft_engine::Edit::AddText { page: 0, text }));+++ +++ assert!(h.state_mut().execute("edit.text"));+++ +++ h.run_steps(3);+++ +++ let point = at(&h, 45.0, 195.0);+++ +++ click(&mut h, point);+++ +++ assert_eq!(h.state().views[0].content.draft.as_ref().and_then(|d| d.index), Some(0), "the editor opened on the text");+++ +++ h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::End);+++ +++ h.event(egui::Event::Text(" twice".into()));+++ +++ h.run_steps(2);+++ +++ h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::Z);+++ +++ h.run_steps(3);+++ +++ assert_eq!(h.state().views[0].content.draft.as_ref().map(|d| d.text.as_str()), Some("Reviewed"), "{route}: taken back");+++ +++ h.get_by_label("Bold").click();+++ +++ h.run_steps(4);+++ +++ let pdfcraft_engine::AddedContent::Text(now) = &added(&h)[0].content else { panic!() };+++ +++ assert!(now.bold, "{route}: the bold is applied to the item");+++ +++ assert!(h.state().views[0].content.draft.is_some(), "{route}: the box stays open");+++ +++ if route == "key" {+++ +++ h.key_press_modifiers(egui::Modifiers::COMMAND | egui::Modifiers::SHIFT, egui::Key::Z);+++ +++ } else {+++ +++ // The menu item is off: neither the document nor the box has a Redo.+++ +++ assert!(!h.state_mut().execute("edit.redo"), "menu: Redo is refused, there is nothing to redo");+++ +++ }+++ +++ h.run_steps(3);+++ +++ let draft = h.state().views[0].content.draft.as_ref().map(|d| d.text.clone());+++ +++ assert_eq!(draft.as_deref(), Some("Reviewed"), "{route}: the retyping undone before the bold comes back in the box");+++ +++ let pdfcraft_engine::AddedContent::Text(now) = &added(&h)[0].content else { panic!() };+++ +++ assert_eq!(now.text, "Reviewed", "{route}: nor in the document");+++ +++ }+++ +++}+++ +++++ +++/// Redo with an added text box open and unchanged reaches the document's waiting Redo, even when++ +++/// the box's text ends in a space: closing the unchanged box writes nothing, so it can't clear++ +++/// that Redo first.++ +++#[test]++ +++fn redo_with_an_unchanged_box_open_redoes_the_document() {++ +++ let mut h = harness();++ +++ let rect = [40.0, 195.0, 240.0, 210.0];++ +++ let text = pdfcraft_engine::AddedText { rect, text: "Reviewed ".into(), ..Default::default() };++ +++ assert!(h.state_mut().apply_edit(pdfcraft_engine::Edit::AddText { page: 0, text }));++ +++ let pdfcraft_engine::AddedContent::Text(saved) = added(&h)[0].content.clone() else { panic!() };++ +++ assert_eq!(saved.text, "Reviewed ", "the trailing space is kept");++ +++ let bold = pdfcraft_engine::AddedText { bold: true, ..saved };++ +++ assert!(h.state_mut().apply_edit(pdfcraft_engine::Edit::UpdateContent { page: 0, index: 0, content: pdfcraft_engine::AddedContent::Text(bold) }));++ +++ assert!(h.state_mut().execute("edit.undo"));++ +++ assert!(h.state_mut().execute("edit.text"));++ +++ h.run_steps(3);++ +++ let point = at(&h, 45.0, 195.0);++ +++ click(&mut h, point);++ +++ assert_eq!(h.state().views[0].content.draft.as_ref().and_then(|d| d.index), Some(0), "the editor opened on the text");++ +++ h.key_press_modifiers(egui::Modifiers::COMMAND | egui::Modifiers::SHIFT, egui::Key::Z);++ +++ h.run_steps(4);++ +++ let pdfcraft_engine::AddedContent::Text(now) = &added(&h)[0].content else { panic!() };++ +++ assert!(now.bold, "the waiting Redo was redone");++ +++ assert!(h.state().views[0].content.draft.is_none(), "the box closed with the step");++ +++}++ +++++ +++/// Two copies of a document, the same added text open in each: the boxes share one Undo history,++ +++/// so typing taken back with Undo in one tab came back with Redo in the other.++ +++#[test]++ +++fn typing_in_one_tab_never_reaches_another_tabs_added_text() {++ +++ let mut h = harness();++ +++ h.state_mut().open_bytes("copy.pdf", None, include_bytes!("../data/form.pdf").to_vec()).unwrap();++ +++ h.run_steps(4);++ +++ let text = pdfcraft_engine::AddedText { rect: [40.0, 195.0, 240.0, 210.0], text: "Reviewed".into(), ..Default::default() };++ +++ let open_in = |h: &mut Harness<'static, PdfCraftApp>, tab: usize| {++ +++ h.state_mut().active = Some(tab);++ +++ h.run_steps(2);++ +++ assert!(h.state_mut().execute("edit.text"));++ +++ h.run_steps(3);++ +++ let r = h.state().views[tab].page_screen_rect(0).expect("on screen");++ +++ let k = r.width() / 300.0;++ +++ click(h, r.min + egui::vec2(45.0 * k, 195.0 * k));++ +++ assert_eq!(h.state().views[tab].content.draft.as_ref().and_then(|d| d.index), Some(0), "the editor opened on the text");++ +++ };++ +++ for tab in [0, 1] {++ +++ h.state_mut().active = Some(tab);++ +++ assert!(h.state_mut().apply_edit(pdfcraft_engine::Edit::AddText { page: 0, text: text.clone() }));++ +++ }++ +++ open_in(&mut h, 1);++ +++ open_in(&mut h, 0);++ +++ h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::End);++ +++ h.event(egui::Event::Text(" secret".into()));++ +++ h.run_steps(2);++ +++ h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::Z);++ +++ h.run_steps(3);++ +++ assert_eq!(h.state().views[0].content.draft.as_ref().map(|d| d.text.as_str()), Some("Reviewed"), "taken back");++ +++ h.state_mut().active = Some(1);++ +++ h.run_steps(3);++ +++ h.key_press_modifiers(egui::Modifiers::COMMAND | egui::Modifiers::SHIFT, egui::Key::Z);++ +++ h.run_steps(3);++ +++ assert_eq!(h.state().views[1].content.draft.as_ref().map(|d| d.text.as_str()), Some("Reviewed"), "the other tab's typing stays out");++ +++}diff --cc crates/ui-egui/tests/it/editing.rsindex a5a9c9bf8,0d44f9106,0d44f9106,2087c293a,95ad044b3,0d44f9106,0d44f9106..4f4bbf06b--- a/crates/ui-egui/tests/it/editing.rs+++ b/crates/ui-egui/tests/it/editing.rs@@@@@@@@ -6814,377 -6591,6 -6591,6 -6470,554 -6813,6 -6591,6 -6591,6 +7036,554 @@@@@@@@ fn mode_tabs_keep_the_hand_over_a_paragassert_eq!(h.state().mode, pdfcraft_ui_egui::Mode::Convert, "the tab takes the click, not the paragraph's editor");}++ +++/// The paragraph opened for typing, as a person opens it: a click on its text.++ +++fn open_paragraph(h: &mut Harness<'static, PdfCraftApp>) {++ +++ let r = h.state().views[0].page_screen_rect(0).expect("on screen");++ +++ let at = egui::pos2(r.left() + 40.0 / 200.0 * r.width(), r.top() + (300.0 - 158.0) / 300.0 * r.height());++ +++ click_at(h, at);++ +++ assert!(h.state().views[0].line_editor.is_some(), "the paragraph opens for typing");++ +++}++ +++++ +++/// Ctrl+Z after a formatting change, with the paragraph still open: the change is undone and++ +++/// the editor closes. The box's own Undo used to take the key, putting back the text it had++ +++/// before the change into a box laid out for the page after it, and the document kept the change.++ +++#[test]++ +++fn undo_with_the_paragraph_open_undoes_the_formatting() {++ +++ let mut h = harness(1, |_| {});++ +++ assert!(h.state_mut().execute("edit.edit_text"));++ +++ h.run_steps(2);++ +++ open_paragraph(&mut h);++ +++ h.get_by_label("Bold").click();++ +++ h.run_steps(4);++ +++ {++ +++ let s = h.state();++ +++ let doc = s.session.get(s.views[0].id).unwrap();++ +++ assert_eq!(doc.can_undo(), Some("Edit text"));++ +++ assert_eq!(doc.text_blocks(0)[0].base_font, "Helvetica-Bold");++ +++ assert!(s.views[0].line_editor.is_some(), "still editing");++ +++ }++ +++ h.key_press_modifiers(Modifiers::COMMAND, Key::Z);++ +++ h.run_steps(4);++ +++ let s = h.state();++ +++ let doc = s.session.get(s.views[0].id).unwrap();++ +++ assert_eq!(doc.can_undo(), None, "the formatting is undone");++ +++ assert_eq!(doc.text_blocks(0)[0].base_font, "Helvetica");++ +++ assert!(s.views[0].line_editor.is_none(), "the editor closed with the step it showed");++ +++}++ +++++ +++/// Undo while typing takes back the typing in the box first; the document is left alone.++ +++#[test]++ +++fn undo_while_typing_takes_back_the_typing_first() {++ +++ let mut h = harness(1, |_| {});++ +++ assert!(h.state_mut().execute("edit.edit_text"));++ +++ h.run_steps(2);++ +++ open_paragraph(&mut h);++ +++ let original = h.state().views[0].line_editor.as_ref().unwrap().text.clone();++ +++ h.key_press_modifiers(Modifiers::COMMAND, Key::End);++ +++ h.event(egui::Event::Text(" more".into()));++ +++ h.run_steps(2);++ +++ assert_ne!(h.state().views[0].line_editor.as_ref().unwrap().text, original);++ +++ h.key_press_modifiers(Modifiers::COMMAND, Key::Z);++ +++ h.run_steps(3);++ +++ let s = h.state();++ +++ let ed = s.views[0].line_editor.as_ref().expect("still typing");++ +++ assert_eq!(ed.text, original, "the typing is taken back");++ +++ assert_eq!(s.session.get(s.views[0].id).unwrap().can_undo(), None, "the document is untouched");++ +++}++ ++++++ +++/// A paragraph of a short, a wide and a short row, opened in the paragraph editor.+++ +++fn three_row_paragraph() -> Harness<'static, PdfCraftApp> {+++ +++ let bytes = paragraph_drag_fixture("BT /F1 10 Tf 12 TL 60 400 Td (One two) Tj T* (three four five six seven eight) Tj T* (nine ten) Tj ET", 0, 1);+++ +++ let mut h = paragraph_drag_harness(bytes, 0);+++ +++ let (at, _) = paragraph_drag_points(&h, "One two three four five six seven eight nine ten", [0.0, 0.0]);+++ +++ click_at(&mut h, at);+++ +++ assert!(h.state().views[0].line_editor.is_some(), "the paragraph opens for typing");+++ +++ h+++ +++}+++ ++++++ +++/// Format text's alignment flyout, by pointer.+++ +++fn align_by_pointer(h: &mut Harness<'static, PdfCraftApp>, choice: &str) {+++ +++ let button = h.get_by_label("Alignment").rect().center();+++ +++ click_at(h, button);+++ +++ let item = h.get_by_label(choice).rect().center();+++ +++ click_at(h, item);+++ +++}+++ ++++++ +++fn row_rect(h: &Harness<'static, PdfCraftApp>, starts: &str) -> [f64; 4] {+++ +++ let s = h.state();+++ +++ s.session.get(s.views[0].id).unwrap().text_lines(0).into_iter().find(|l| l.text.starts_with(starts)).expect("the row").rect+++ +++}+++ ++++++ +++/// Bug A: with one row of a paragraph selected, an alignment applies to that row only.+++ +++/// Bug C: Undo then puts the paragraph back and closes the editor, instead of leaving it open on+++ +++/// a text the page no longer has.+++ +++#[test]+++ +++fn aligning_a_selected_row_aligns_only_that_row_and_undo_puts_it_back() {+++ +++ let mut h = three_row_paragraph();+++ +++ let first = row_rect(&h, "One");+++ +++ let wide = row_rect(&h, "three");+++ +++ let last = row_rect(&h, "nine");+++ +++ // Select the last row.+++ +++ h.key_press_modifiers(Modifiers::COMMAND, Key::End);+++ +++ h.key_press_modifiers(Modifiers::SHIFT, Key::Home);+++ +++ h.run_steps(2);+++ +++ align_by_pointer(&mut h, "Align right");+++ +++ {+++ +++ let s = h.state();+++ +++ assert_eq!(s.session.get(s.views[0].id).unwrap().can_undo(), Some("Edit text"));+++ +++ assert!(s.views[0].line_editor.is_some(), "the paragraph stays open");+++ +++ }+++ +++ let moved = row_rect(&h, "nine");+++ +++ assert!((row_rect(&h, "One")[0] - first[0]).abs() < 0.5, "the first row stays put");+++ +++ assert!((moved[2] - wide[2]).abs() < 1.0 && moved[0] > last[0] + 20.0, "the last row is right-aligned: {moved:?}");+++ +++ h.key_press_modifiers(Modifiers::COMMAND, Key::Z);+++ +++ h.run_steps(4);+++ +++ let s = h.state();+++ +++ assert_eq!(s.session.get(s.views[0].id).unwrap().can_undo(), None, "the alignment is undone");+++ +++ assert!(s.views[0].line_editor.is_none(), "the editor closed with the step it showed");+++ +++ assert!((row_rect(&h, "nine")[0] - last[0]).abs() < 0.5, "the last row is back");+++ +++}+++ ++++++ +++/// Format text's alignment flyout by keyboard or screen reader: each control is focused, then+++ +++/// pressed, with no pointer anywhere.+++ +++fn align_by_focus(h: &mut Harness<'static, PdfCraftApp>, choice: &str) {+++ +++ for label in ["Alignment", choice] {+++ +++ h.get_by_label(label).focus();+++ +++ h.run_steps(2);+++ +++ h.get_by_label(label).click();+++ +++ h.run_steps(3);+++ +++ }+++ +++}+++ ++++++ +++/// The same as by pointer, with the alignment controls reached by keyboard or a screen reader:+++ +++/// the paragraph stays open when the focus leaves it for the Format text panel, the selected row+++ +++/// takes the alignment, and a second choice is for that row again.+++ +++#[test]+++ +++fn aligning_a_selected_row_by_keyboard_keeps_the_paragraph_open() {+++ +++ let mut h = three_row_paragraph();+++ +++ let first = row_rect(&h, "One");+++ +++ let wide = row_rect(&h, "three");+++ +++ h.key_press_modifiers(Modifiers::COMMAND, Key::End);+++ +++ h.key_press_modifiers(Modifiers::SHIFT, Key::Home);+++ +++ h.run_steps(2);+++ +++ align_by_focus(&mut h, "Align right");+++ +++ assert!(h.state().views[0].line_editor.is_some(), "the paragraph stays open");+++ +++ let moved = row_rect(&h, "nine");+++ +++ assert!((moved[2] - wide[2]).abs() < 1.0, "the last row is right-aligned: {moved:?}");+++ +++ align_by_focus(&mut h, "Centre");+++ +++ assert!(h.state().views[0].line_editor.is_some(), "the paragraph is still open");+++ +++ assert!((row_rect(&h, "One")[0] - first[0]).abs() < 0.5, "the first row stays put: {:?}", row_rect(&h, "One"));+++ +++ let last = row_rect(&h, "nine");+++ +++ assert!((((last[0] + last[2]) - (wide[0] + wide[2])) / 2.0).abs() < 1.0, "the last row is centred: {last:?} in {wide:?}");+++ +++}+++ ++++++ +++/// A row aligned on its own, deleted by typing, then brought back with Undo from the menu: it+++ +++/// comes back with its alignment, and Redo deletes it again. The box's history keeps only text,+++ +++/// so the restored row took the alignment of the row before it.+++ +++#[test]+++ +++fn undo_brings_a_deleted_row_back_with_its_alignment() {+++ +++ let mut h = three_row_paragraph();+++ +++ // Right-align the last row on its own.+++ +++ h.key_press_modifiers(Modifiers::COMMAND, Key::End);+++ +++ h.key_press_modifiers(Modifiers::SHIFT, Key::Home);+++ +++ h.run_steps(2);+++ +++ align_by_pointer(&mut h, "Align right");+++ +++ let ed = |h: &Harness<'static, PdfCraftApp>| h.state().views[0].line_editor.clone().expect("the paragraph stays open");+++ +++ let (three_rows, aligned) = (ed(&h).text, ed(&h).look.aligns);+++ +++ assert_eq!(aligned.last(), Some(&Some(pdfcraft_engine::TextAlign::Right)), "{aligned:?}");+++ +++ // Delete the last row with the line break before it.+++ +++ h.key_press_modifiers(Modifiers::COMMAND, Key::End);+++ +++ h.key_press_modifiers(Modifiers::SHIFT, Key::Home);+++ +++ h.key_press_modifiers(Modifiers::SHIFT, Key::ArrowLeft);+++ +++ h.key_press(Key::Backspace);+++ +++ h.run_steps(2);+++ +++ let (two_rows, after_delete) = (ed(&h).text, ed(&h).look.aligns);+++ +++ assert_eq!(pdfcraft_engine::paragraph_align::count(&two_rows), 2, "{two_rows:?}");+++ +++ assert!(h.state_mut().execute("edit.undo"));+++ +++ h.run_steps(3);+++ +++ assert_eq!((ed(&h).text, ed(&h).look.aligns), (three_rows, aligned), "Undo brings the row back right-aligned");+++ +++ assert!(h.state_mut().execute("edit.redo"));+++ +++ h.run_steps(3);+++ +++ assert_eq!((ed(&h).text, ed(&h).look.aligns), (two_rows, after_delete), "Redo deletes it again");+++ +++}+++ +++++ +++/// Redo after Undo in the box puts the typing back, in the box: it doesn't reach the document,++ +++/// whose own Redo (a formatting change waiting here) must stay waiting.++ +++#[test]++ +++fn redo_after_undoing_typing_puts_the_typing_back() {++ +++ let mut h = harness(1, |_| {});++ +++ assert!(h.state_mut().execute("edit.edit_text"));++ +++ h.run_steps(2);++ +++ open_paragraph(&mut h);++ +++ h.get_by_label("Bold").click();++ +++ h.run_steps(4);++ +++ // Undo the bold (closing the editor), so the document has it to redo.++ +++ h.key_press_modifiers(Modifiers::COMMAND, Key::Z);++ +++ h.run_steps(4);++ +++ assert_eq!(h.state().session.get(h.state().views[0].id).unwrap().can_redo(), Some("Edit text"));++ +++ open_paragraph(&mut h);++ +++ let original = h.state().views[0].line_editor.as_ref().unwrap().text.clone();++ +++ h.key_press_modifiers(Modifiers::COMMAND, Key::End);++ +++ h.event(egui::Event::Text(" more".into()));++ +++ h.run_steps(2);++ +++ let typed = h.state().views[0].line_editor.as_ref().unwrap().text.clone();++ +++ h.key_press_modifiers(Modifiers::COMMAND, Key::Z);++ +++ h.run_steps(3);++ +++ assert_eq!(h.state().views[0].line_editor.as_ref().unwrap().text, original, "the typing is taken back");++ +++ h.key_press_modifiers(Modifiers::COMMAND | Modifiers::SHIFT, Key::Z);++ +++ h.run_steps(3);++ +++ let s = h.state();++ +++ let ed = s.views[0].line_editor.as_ref().expect("still typing");++ +++ assert_eq!(ed.text, typed, "Redo puts the typing back");++ +++ let doc = s.session.get(s.views[0].id).unwrap();++ +++ assert_eq!((doc.can_redo(), doc.text_blocks(0)[0].base_font.as_str()), (Some("Edit text"), "Helvetica"), "the document's Redo still waits");++ +++}++ ++++++ +++/// A row aligned on its own keeps its alignment when the whole paragraph is then made bold: the+++ +++/// rewrite for the bold carries the rows' alignments too, as nothing in the page records them.+++ +++#[test]+++ +++fn a_row_aligned_on_its_own_keeps_it_through_more_formatting() {+++ +++ let mut h = three_row_paragraph();+++ +++ let wide = row_rect(&h, "three");+++ +++ h.key_press_modifiers(Modifiers::COMMAND, Key::End);+++ +++ h.key_press_modifiers(Modifiers::SHIFT, Key::Home);+++ +++ h.run_steps(2);+++ +++ align_by_pointer(&mut h, "Align right");+++ +++ // Nothing selected: the bold is for the whole paragraph.+++ +++ h.key_press(Key::End);+++ +++ h.run_steps(2);+++ +++ assert_eq!(h.state().views[0].line_editor.as_ref().unwrap().selection, None);+++ +++ h.get_by_label("Bold").click();+++ +++ h.run_steps(4);+++ +++ assert_eq!(h.state().session.get(h.state().views[0].id).unwrap().text_blocks(0)[0].base_font, "Helvetica-Bold");+++ +++ let last = row_rect(&h, "nine");+++ +++ assert!(+++ +++ (last[2] - row_rect(&h, "three")[2].max(wide[2])).abs() < 1.0 && last[0] > wide[0] + 20.0,+++ +++ "the last row is still right-aligned: {last:?}"+++ +++ );+++ +++}+++ ++++++ +++/// A second alignment picked while the same row is still selected applies to that row again, not+++ +++/// the whole paragraph.+++ +++#[test]+++ +++fn a_second_alignment_for_a_selected_row_stays_on_that_row() {+++ +++ let mut h = three_row_paragraph();+++ +++ let first = row_rect(&h, "One");+++ +++ let wide = row_rect(&h, "three");+++ +++ h.key_press_modifiers(Modifiers::COMMAND, Key::End);+++ +++ h.key_press_modifiers(Modifiers::SHIFT, Key::Home);+++ +++ h.run_steps(2);+++ +++ align_by_pointer(&mut h, "Align right");+++ +++ align_by_pointer(&mut h, "Centre");+++ +++ assert!((row_rect(&h, "One")[0] - first[0]).abs() < 0.5, "the first row stays put: {:?}", row_rect(&h, "One"));+++ +++ let last = row_rect(&h, "nine");+++ +++ let (mid, centre) = ((last[0] + last[2]) / 2.0, (wide[0] + wide[2]) / 2.0);+++ +++ assert!((mid - centre).abs() < 1.0, "the last row is centred: {last:?} in {wide:?}");+++ +++}+++ +++++ +++/// Redo from the menu or toolbar with typing in the box the page doesn't have yet. Closing the++ +++/// box first applied the typing, a new edit that dropped the document's waiting Redo, and the++ +++/// Redo itself then failed: the step was gone. The typing now stays in the box and the Redo++ +++/// waits; once Undo in the box takes the typing back, Redo from the menu puts it back there.++ +++#[test]++ +++fn redo_from_the_menu_with_typing_in_the_box_keeps_the_documents_redo() {++ +++ let mut h = harness(1, |_| {});++ +++ assert!(h.state_mut().execute("edit.edit_text"));++ +++ h.run_steps(2);++ +++ open_paragraph(&mut h);++ +++ h.get_by_label("Bold").click();++ +++ h.run_steps(4);++ +++ // Undo the bold (closing the editor), so the document has it to redo.++ +++ h.key_press_modifiers(Modifiers::COMMAND, Key::Z);++ +++ h.run_steps(4);++ +++ open_paragraph(&mut h);++ +++ let original = h.state().views[0].line_editor.as_ref().unwrap().text.clone();++ +++ h.key_press_modifiers(Modifiers::COMMAND, Key::End);++ +++ h.event(egui::Event::Text(" more".into()));++ +++ h.run_steps(2);++ +++ let typed = h.state().views[0].line_editor.as_ref().unwrap().text.clone();++ +++ assert!(h.state_mut().execute("edit.redo"));++ +++ h.run_steps(3);++ +++ {++ +++ let s = h.state();++ +++ let ed = s.views[0].line_editor.as_ref().expect("the box stays open");++ +++ assert_eq!(ed.text, typed, "the typing stays in the box, unapplied");++ +++ let doc = s.session.get(s.views[0].id).unwrap();++ +++ assert_eq!((doc.can_redo(), doc.text_blocks(0)[0].base_font.as_str()), (Some("Edit text"), "Helvetica"), "the document's Redo still waits");++ +++ }++ +++ h.key_press_modifiers(Modifiers::COMMAND, Key::Z);++ +++ h.run_steps(3);++ +++ assert_eq!(h.state().views[0].line_editor.as_ref().unwrap().text, original, "Undo takes the typing back in the box");++ +++ assert!(h.state_mut().execute("edit.redo"));++ +++ h.run_steps(3);++ +++ let s = h.state();++ +++ assert_eq!(s.views[0].line_editor.as_ref().expect("still open").text, typed, "Redo from the menu puts the typing back");++ +++ assert_eq!(s.session.get(s.views[0].id).unwrap().can_redo(), Some("Edit text"), "the document's Redo still waits");++ +++}++ +++++ +++/// Undo from the menu or toolbar with typing in the box the page doesn't have yet: the box takes++ +++/// the typing back, as the key does, and stays open, and the document's waiting Redo stays. The++ +++/// menu applied the typing first (a new edit, which dropped that Redo), closed the box and undid++ +++/// the typing all at once.++ +++#[test]++ +++fn undo_from_the_menu_takes_back_typing_in_the_box() {++ +++ let mut h = harness(1, |_| {});++ +++ assert!(h.state_mut().execute("edit.edit_text"));++ +++ h.run_steps(2);++ +++ open_paragraph(&mut h);++ +++ h.get_by_label("Bold").click();++ +++ h.run_steps(4);++ +++ // Undo the bold (closing the editor), so the document has it to redo and nothing to undo.++ +++ h.key_press_modifiers(Modifiers::COMMAND, Key::Z);++ +++ h.run_steps(4);++ +++ open_paragraph(&mut h);++ +++ let original = h.state().views[0].line_editor.as_ref().unwrap().text.clone();++ +++ h.key_press_modifiers(Modifiers::COMMAND, Key::End);++ +++ h.event(egui::Event::Text(" more".into()));++ +++ h.run_steps(2);+++ +++ h.key_press_modifiers(Modifiers::SHIFT, Key::Home);+++ +++ h.run_steps(2);+++ +++ assert!(h.state().views[0].line_editor.as_ref().unwrap().selection.is_some());+++ +++ h.event(egui::Event::PointerMoved(egui::pos2(10.0, 10.0)));+++ +++ h.ctx.memory_mut(|m| m.request_focus(egui::Id::unique("test-menu")));++ +++ assert!(h.state_mut().execute("edit.undo"), "Undo is enabled for the box's typing");+++ +++ assert_eq!(h.state().views[0].line_editor.as_ref().unwrap().selection, None, "menu history clears the old byte range before the next frame");++ +++ h.run_steps(3);++ +++ let s = h.state();++ +++ let ed = s.views[0].line_editor.as_ref().expect("the box stays open");++ +++ assert_eq!(ed.text, original, "the typing is taken back in the box");++ +++ let doc = s.session.get(s.views[0].id).unwrap();++ +++ assert_eq!((doc.can_redo(), doc.can_undo()), (Some("Edit text"), None), "the document is untouched");++ +++}++ +++++ +++/// Redo from the menu after Undo in the box took the typing back, with nothing for the document++ +++/// to redo: the menu item follows the box's own Redo too, and puts the typing back. It was++ +++/// disabled, as it followed only the document's Redo, and only the key could do it.++ +++#[test]++ +++fn redo_from_the_menu_is_enabled_for_the_boxs_own_typing() {++ +++ let mut h = harness(1, |_| {});++ +++ assert!(h.state_mut().execute("edit.edit_text"));++ +++ h.run_steps(2);++ +++ open_paragraph(&mut h);++ +++ let original = h.state().views[0].line_editor.as_ref().unwrap().text.clone();++ +++ h.key_press_modifiers(Modifiers::COMMAND, Key::End);++ +++ h.event(egui::Event::Text(" more".into()));++ +++ h.run_steps(2);++ +++ let typed = h.state().views[0].line_editor.as_ref().unwrap().text.clone();++ +++ h.key_press_modifiers(Modifiers::COMMAND, Key::Z);++ +++ h.run_steps(3);++ +++ assert_eq!(h.state().views[0].line_editor.as_ref().unwrap().text, original, "the typing is taken back");++ +++ assert_eq!(h.state().session.get(h.state().views[0].id).unwrap().can_redo(), None, "the document has nothing to redo");+++ +++ // A range retained while the unfocused editor still showed its previous text.+++ +++ h.state_mut().views[0].line_editor.as_mut().unwrap().selection = Some(0..1);+++ +++ h.event(egui::Event::PointerMoved(egui::pos2(10.0, 10.0)));+++ +++ h.ctx.memory_mut(|m| m.request_focus(egui::Id::unique("test-menu")));++ +++ assert!(h.state_mut().execute("edit.redo"), "Redo is enabled for the box's own step");+++ +++ assert_eq!(h.state().views[0].line_editor.as_ref().unwrap().selection, None, "menu history clears the old byte range before the next frame");++ +++ h.run_steps(3);++ +++ assert_eq!(h.state().views[0].line_editor.as_ref().expect("still open").text, typed, "Redo puts the typing back");++ +++}++ +++++ +++/// Typing in tab A's paragraph, a paragraph opened in tab B, then back to A: Edit ▸ Undo takes++ +++/// the typing back in A's box. The tabs share one text box, and its history was cleared each time++ +++/// another tab's box took it, so Undo found no step and closed A's paragraph instead++ +++/// (skylartaylor's and FredApps's review of 08ec1db7).++ +++#[test]++ +++fn undo_after_a_round_trip_through_another_tab_takes_back_the_typing() {++ +++ let mut h = harness(1, |app| {++ +++ app.open_bytes("copy.pdf", None, fixture(1)).expect("the copy opens");++ +++ });++ +++ let open_in = |h: &mut Harness<'static, PdfCraftApp>, tab: usize| {++ +++ h.state_mut().active = Some(tab);++ +++ h.run_steps(2);++ +++ if h.state().views[tab].line_editor.is_none() {++ +++ assert!(h.state_mut().execute("edit.edit_text"));++ +++ h.run_steps(2);++ +++ }++ +++ let r = h.state().views[tab].page_screen_rect(0).expect("on screen");++ +++ click_at(h, egui::pos2(r.left() + 40.0 / 200.0 * r.width(), r.top() + (300.0 - 158.0) / 300.0 * r.height()));++ +++ assert!(h.state().views[tab].line_editor.is_some(), "the paragraph opens for typing");++ +++ };++ +++ open_in(&mut h, 0);++ +++ h.get_by_label("Bold").click();++ +++ h.run_steps(4);++ +++ h.key_press_modifiers(Modifiers::COMMAND, Key::Z);++ +++ h.run_steps(4);++ +++ open_in(&mut h, 0);++ +++ let original = h.state().views[0].line_editor.as_ref().unwrap().text.clone();++ +++ h.key_press_modifiers(Modifiers::COMMAND, Key::End);++ +++ h.event(egui::Event::Text(" more".into()));++ +++ h.run_steps(2);++ +++ assert!(h.state().views[0].line_editor.as_ref().unwrap().text.ends_with(" more"));++ +++ open_in(&mut h, 1);++ +++ h.state_mut().active = Some(0);++ +++ h.run_steps(3);++ +++ assert!(h.state().views[0].line_editor.is_some(), "A's paragraph is still open after the round trip");++ +++ assert!(h.state_mut().execute("edit.undo"), "Undo is enabled");++ +++ h.run_steps(3);++ +++ let s = h.state();++ +++ let ed = s.views[0].line_editor.as_ref().expect("the box stays open: Undo takes back the typing");++ +++ assert_eq!(ed.text, original, "the typing is taken back in the box");++ +++ assert_eq!(s.session.get(s.views[0].id).unwrap().can_redo(), Some("Edit text"), "the document's Redo still waits");++ +++}++ +++++ +++/// Typing taken back with Ctrl+Z, then Bold applied with the paragraph still open: Ctrl+Shift+Z++ +++/// must not bring the typing back on top of the bold, as the box's history is cleared once the++ +++/// page has its text. The format left the text as it was, so the box kept its history and its++ +++/// Redo put "Page 1 more" back (FredApps's review of abc378c0).++ +++#[test]++ +++fn redo_after_formatting_never_brings_back_typing_undone_before_it() {++ +++ let mut h = harness(1, |_| {});++ +++ assert!(h.state_mut().execute("edit.edit_text"));++ +++ h.run_steps(2);++ +++ open_paragraph(&mut h);++ +++ let original = h.state().views[0].line_editor.as_ref().unwrap().text.clone();++ +++ h.key_press_modifiers(Modifiers::COMMAND, Key::End);++ +++ h.event(egui::Event::Text(" more".into()));++ +++ h.run_steps(2);++ +++ h.key_press_modifiers(Modifiers::COMMAND, Key::Z);++ +++ h.run_steps(3);++ +++ assert_eq!(h.state().views[0].line_editor.as_ref().unwrap().text, original, "the typing is taken back");++ +++ h.get_by_label("Bold").click();++ +++ h.run_steps(4);++ +++ assert_eq!(h.state().session.get(h.state().views[0].id).unwrap().can_undo(), Some("Edit text"), "the bold is applied");++ +++ h.key_press_modifiers(Modifiers::COMMAND | Modifiers::SHIFT, Key::Z);++ +++ h.run_steps(3);++ +++ let text = h.state().views[0].line_editor.as_ref().map(|ed| ed.text.clone());++ +++ assert_eq!(text.as_deref(), Some(original.as_str()), "the typing undone before the bold stays undone");++ +++ // Nor through what the menu's Redo runs.++ +++ h.state_mut().redo();++ +++ h.run_steps(3);++ +++ let s = h.state();++ +++ let text = s.views[0].line_editor.as_ref().map(|ed| ed.text.clone());++ +++ assert!(!text.as_deref().unwrap_or_default().contains("more"), "the menu's Redo brings it back: {text:?}");++ +++ assert_eq!(s.session.get(s.views[0].id).unwrap().text_blocks(0)[0].base_font, "Helvetica-Bold", "the bold stays");++ +++}++ +++++ +++/// Edit ▸ Undo chosen in the same frame as the switch back to tab A, before A's box is drawn++ +++/// again: the shared text box still holds tab B's history then. Stepping through it put B's++ +++/// typing into A's box; the box now claims its own history back first (CodeRabbit on abc378c0).++ +++#[test]++ +++fn undo_in_the_frame_of_the_switch_back_takes_back_the_typing() {++ +++ let mut h = harness(1, |app| {++ +++ app.open_bytes("copy.pdf", None, fixture(1)).expect("the copy opens");++ +++ });++ +++ let open_in = |h: &mut Harness<'static, PdfCraftApp>, tab: usize| {++ +++ h.state_mut().active = Some(tab);++ +++ h.run_steps(2);++ +++ if h.state().views[tab].line_editor.is_none() {++ +++ assert!(h.state_mut().execute("edit.edit_text"));++ +++ h.run_steps(2);++ +++ }++ +++ let r = h.state().views[tab].page_screen_rect(0).expect("on screen");++ +++ click_at(h, egui::pos2(r.left() + 40.0 / 200.0 * r.width(), r.top() + (300.0 - 158.0) / 300.0 * r.height()));++ +++ assert!(h.state().views[tab].line_editor.is_some(), "the paragraph opens for typing");++ +++ };++ +++ open_in(&mut h, 0);++ +++ let original = h.state().views[0].line_editor.as_ref().unwrap().text.clone();++ +++ h.key_press_modifiers(Modifiers::COMMAND, Key::End);++ +++ h.event(egui::Event::Text(" more".into()));++ +++ h.run_steps(2);++ +++ // In B, a paragraph whose text differs from A's ("Page 1 B", applied with Bold), so B's++ +++ // history can't pass for A's.++ +++ open_in(&mut h, 1);++ +++ h.key_press_modifiers(Modifiers::COMMAND, Key::End);++ +++ h.event(egui::Event::Text(" B".into()));++ +++ h.run_steps(2);++ +++ h.get_by_label("Bold").click();++ +++ h.run_steps(4);++ +++ assert_eq!(h.state().views[1].line_editor.as_ref().map(|ed| ed.text.as_str()), Some("Page 1 B"), "B's paragraph is open on its own text");++ +++ // Back to A and Undo at once: no frame draws A's box in between.++ +++ h.state_mut().active = Some(0);++ +++ assert!(h.state_mut().execute("edit.undo"), "Undo is enabled");++ +++ h.run_steps(3);++ +++ let ed = h.state().views[0].line_editor.clone().expect("the box stays open: Undo takes back the typing");++ +++ assert_eq!(ed.text, original, "the typing is taken back in A's box");++ +++}++ +++++ +++/// Redo from the menu chosen in the same frame as a switch to tab B, whose paragraph is open on++ +++/// the same text as A's: the shared text box still holds A's history then, with A's undone++ +++/// typing to redo, so B's box claims its own history back before stepping.++ +++#[test]++ +++fn redo_in_the_frame_of_a_tab_switch_never_brings_another_tabs_typing() {++ +++ let mut h = harness(1, |app| {++ +++ app.open_bytes("copy.pdf", None, fixture(1)).expect("the copy opens");++ +++ });++ +++ let open_in = |h: &mut Harness<'static, PdfCraftApp>, tab: usize| {++ +++ h.state_mut().active = Some(tab);++ +++ h.run_steps(2);++ +++ assert!(h.state_mut().execute("edit.edit_text"));++ +++ h.run_steps(2);++ +++ let r = h.state().views[tab].page_screen_rect(0).expect("on screen");++ +++ click_at(h, egui::pos2(r.left() + 40.0 / 200.0 * r.width(), r.top() + (300.0 - 158.0) / 300.0 * r.height()));++ +++ assert!(h.state().views[tab].line_editor.is_some(), "the paragraph opens for typing");++ +++ };++ +++ open_in(&mut h, 1);++ +++ open_in(&mut h, 0);++ +++ let original = h.state().views[0].line_editor.as_ref().unwrap().text.clone();++ +++ h.key_press_modifiers(Modifiers::COMMAND, Key::End);++ +++ h.event(egui::Event::Text(" secret".into()));++ +++ h.run_steps(2);++ +++ assert!(h.state_mut().execute("edit.undo"));++ +++ h.run_steps(3);++ +++ assert_eq!(h.state().views[0].line_editor.as_ref().unwrap().text, original, "taken back in A");++ +++ // To B and Redo at once: no frame draws B's box in between.++ +++ h.state_mut().active = Some(1);++ +++ h.state_mut().redo();++ +++ h.run_steps(3);++ +++ let s = h.state();++ +++ let b = s.views[1].line_editor.as_ref().map(|ed| ed.text.clone());++ +++ assert!(!b.as_deref().unwrap_or_default().contains("secret"), "A's typing came back in B: {b:?}");++ +++ assert!(!s.session.get(s.views[1].id).unwrap().text_blocks(0)[0].text.contains("secret"), "A's typing reached B's page");++ +++}++ +++++ +++/// Two copies of a document, the same paragraph open in each. The paragraph boxes share one text++ +++/// box, and so one Undo history: a box opened on the same text as another tab's didn't clear it.- /// Typing in one tab, taken back with Undo, then came back with Redo in the other tab.+++ +++/// Typing in one tab, taken back with Undo, then came back with Redo (the key or the menu) in the+++ +++/// other tab.++ +++#[test]++ +++fn typing_in_one_tab_never_reaches_another_tabs_paragraph() {++ +++ let mut h = harness(1, |app| {++ +++ app.open_bytes("copy.pdf", None, fixture(1)).expect("the copy opens");++ +++ });++ +++ let open_in = |h: &mut Harness<'static, PdfCraftApp>, tab: usize| {++ +++ h.state_mut().active = Some(tab);++ +++ h.run_steps(2);++ +++ assert!(h.state_mut().execute("edit.edit_text"));++ +++ h.run_steps(2);++ +++ let r = h.state().views[tab].page_screen_rect(0).expect("on screen");++ +++ click_at(h, egui::pos2(r.left() + 40.0 / 200.0 * r.width(), r.top() + (300.0 - 158.0) / 300.0 * r.height()));++ +++ assert!(h.state().views[tab].line_editor.is_some(), "the paragraph opens for typing");++ +++ };++ +++ open_in(&mut h, 1);++ +++ let original = h.state().views[1].line_editor.as_ref().unwrap().text.clone();++ +++ open_in(&mut h, 0);++ +++ assert_eq!(h.state().views[0].line_editor.as_ref().unwrap().text, original, "the same paragraph");++ +++ h.key_press_modifiers(Modifiers::COMMAND, Key::End);++ +++ h.event(egui::Event::Text(" secret".into()));++ +++ h.run_steps(2);++ +++ h.key_press_modifiers(Modifiers::COMMAND, Key::Z);++ +++ h.run_steps(3);++ +++ assert_eq!(h.state().views[0].line_editor.as_ref().unwrap().text, original, "taken back");++ +++ // The copy, its paragraph still open: Redo there has nothing of its own to put back.++ +++ h.state_mut().active = Some(1);++ +++ h.run_steps(3);++ +++ assert!(h.state().views[1].line_editor.is_some(), "the copy's paragraph is still open");++ +++ h.key_press_modifiers(Modifiers::COMMAND | Modifiers::SHIFT, Key::Z);++ +++ h.run_steps(3);- let s = h.state();- let text = &s.views[1].line_editor.as_ref().expect("the copy's paragraph stays open through Redo").text;+++ +++ let text = h.state().views[1].line_editor.as_ref().expect("the copy's paragraph stays open through Redo").text.clone();++ +++ assert!(!text.contains("secret"), "the other tab's typing came in: {text:?}");+++ +++ // Nor through what the menu's Redo runs, which reads the box's history itself (the menu item+++ +++ // is off here, as the copy's document has nothing to redo). With no Redo of its own, the box+++ +++ // passes the step to the document and closes, so the page's text is checked too.+++ +++ h.state_mut().redo();+++ +++ h.run_steps(3);+++ +++ let s = h.state();+++ +++ let text = s.views[1].line_editor.as_ref().map(|ed| ed.text.clone());+++ +++ assert!(!text.as_deref().unwrap_or_default().contains("secret"), "the other tab's typing came in from the menu: {text:?}");++ +++ assert_eq!(s.session.get(s.views[1].id).unwrap().text_blocks(0)[0].text, s.session.get(s.views[0].id).unwrap().text_blocks(0)[0].text);++ +++}++ +++/// A paragraph selected by its frame goes with one Delete (or Backspace), as in Acrobat, instead/// of being emptied a typed character at a time, and undo brings it back.#[test]diff --cc crates/ui-egui/tests/it/prepare.rsindex b33791313,99858e3af,53aa7b973,8d565ab69,6ce727a71,6ce727a71,6ce727a71..82e33b29d--- a/crates/ui-egui/tests/it/prepare.rs+++ b/crates/ui-egui/tests/it/prepare.rs@@@@@@@@ -1313,77 -1279,209 -1279,120 -1216,3 -1279,77 -1279,77 -1279,77 +1313,252 @@@@@@@@ fn a_loop_has_its_own_card_that_opens_tlet draft = h.state().field_props.as_ref().map(|d| (d.field.clone(), d.tab));assert_eq!(draft, Some(("a".to_owned(), FieldTab::Calculate)));}++ /// A radio group `shirt` of three buttons, S, M and L, with L chosen, while preparing the form.+ fn radio_group_harness() -> Harness<'static, PdfCraftApp> {+ let mut h = harness();+ for (x, export) in [(20.0, "S"), (60.0, "M"), (100.0, "L")] {+ h.state_mut().apply_edit(pdfcraft_engine::Edit::AddField {+ page: 0,+ rect: [x, 300.0, x + 14.0, 314.0],+ kind: pdfcraft_engine::NewField::Radio { group: Some("shirt".into()), export: export.into() },+ name: Some("shirt".into()),+ });+ }+ h.state_mut()+ .apply_edit(pdfcraft_engine::Edit::SetFieldValue { name: "shirt".into(), value: pdfcraft_engine::FieldValue::Radio(Some("L".into())) });+ assert!(h.state_mut().execute("form.prepare"));+ h.run_steps(3);+ h+ }++ fn buttons(h: &Harness<'static, PdfCraftApp>) -> (Vec<String>, Vec<String>) {+ let s = h.state();+ let doc = s.session.get(s.views[0].id).unwrap();+ let f = doc.form.iter().find(|f| f.name == "shirt").expect("the group is still there");+ (f.widgets.iter().filter_map(|w| w.on_state.clone()).collect(), f.value.clone())+ }++ /// #4609: Delete removes the one radio button clicked, not its whole group, as in Acrobat.+ #[test]+ fn deleting_one_radio_button_keeps_the_rest_of_its_group() {+ let mut h = radio_group_harness();+ assert_eq!(buttons(&h).0, ["S", "M", "L"]);+ let p = {+ let s = h.state();+ let doc = s.session.get(s.views[0].id).unwrap();+ let f = doc.form.iter().find(|f| f.name == "shirt").unwrap();+ pdfcraft_ui_egui::forms_ui::field_screen_rect(&s.views[0], &doc.info, f, 1).expect("on screen").center()+ };+ h.hover_at(p);+ h.run_steps(1);+ h.drag_at(p);+ h.run_steps(1);+ h.drop_at(p);+ h.run_steps(3);+ assert_eq!(h.state().views[0].prepare.selected, Some(("shirt".into(), 1)), "the middle button is selected");+ h.key_press(egui::Key::Delete);+ h.run_steps(3);+ assert_eq!(buttons(&h), (vec!["S".into(), "L".into()], vec!["L".into()]), "only M is gone; L stays chosen");+ assert_eq!(h.state().session.get(h.state().views[0].id).unwrap().can_undo(), Some("Delete field"));+ h.state_mut().execute("edit.undo");+ h.run_steps(2);+ assert_eq!(buttons(&h).0, ["S", "M", "L"]);+ }++ /// Two buttons of one group selected together both go, whichever was selected first.+ #[test]+ fn deleting_two_radio_buttons_of_a_group_at_once() {+ let mut h = radio_group_harness();+ {+ let p = &mut h.state_mut().views[0].prepare;+ p.selected = Some(("shirt".into(), 0));+ p.also = vec![("shirt".into(), 2)];+ }+ h.key_press(egui::Key::Delete);+ h.run_steps(3);+ assert_eq!(buttons(&h), (vec!["M".into()], vec![]), "M is left, and nothing is chosen");+ // Selecting every button deletes the group.+ {+ let p = &mut h.state_mut().views[0].prepare;+ p.selected = Some(("shirt".into(), 0));+ }+ h.key_press(egui::Key::Delete);+ h.run_steps(3);+ assert!(!names(&h).iter().any(|n| n == "shirt"));+ }+ +++++ +++++/// Two calculated fields that share a name (a malformed form) each show their own formula: the+ +++++/// first dup sums src, the second x.+ +++++#[test]+ +++++fn fields_sharing_a_name_each_show_their_own_formula() {+ +++++ let widget = |name: &str, y: u32, reads: &str| {+ +++++ format!(+ +++++ "<< /Type /Annot /Subtype /Widget /FT /Tx /T ({name}) /Rect [50 {y} 250 {}] /P 3 0 R /AA << /C << /S /JavaScript /JS (AFSimple_Calculate\\(\"SUM\", \"{reads}\"\\);) >> >> >>",+ +++++ y + 20+ +++++ )+ +++++ };+ +++++ let objs: Vec<String> = vec![+ +++++ "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(),+ +++++ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(),+ +++++ "<< /Type /Page /Parent 2 0 R /Annots [5 0 R 6 0 R 7 0 R 8 0 R] >>".into(),+ +++++ "<< /Fields [5 0 R 6 0 R 7 0 R 8 0 R] /DA (/Helv 0 Tf 0 g) /CO [6 0 R 7 0 R 5 0 R] >>".into(),+ +++++ widget("dup", 700, "x"),+ +++++ widget("dup", 660, "src"),+ +++++ widget("src", 620, "x"),+ +++++ "<< /Type /Annot /Subtype /Widget /FT /Tx /T (x) /Rect [50 580 250 600] /P 3 0 R /V (3) >>".into(),+ +++++ ];+ +++++ let mut bytes = b"%PDF-1.7\n".to_vec();+ +++++ let mut offsets = Vec::new();+ +++++ for (i, o) in objs.iter().enumerate() {+ +++++ offsets.push(bytes.len());+ +++++ bytes.extend_from_slice(format!("{} 0 obj\n{o}\nendobj\n", i + 1).as_bytes());+ +++++ }+ +++++ let xref = bytes.len();+ +++++ bytes.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes());+ +++++ for o in offsets {+ +++++ bytes.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());+ +++++ }+ +++++ bytes.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes());+ +++++ let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(move |_| {+ +++++ let mut app = PdfCraftApp::new();+ +++++ app.set_option("language", "en").unwrap();+ +++++ app.open_bytes("dup.pdf", None, bytes.clone()).unwrap();+ +++++ app+ +++++ });+ +++++ h.run_steps(4);+ +++++ h.state_mut().execute("form.prepare");+ +++++ h.run_steps(3);+ +++++ h.get_by_label("Calculation order").click();+ +++++ h.run_steps(3);+ +++++ for (row, formula) in [("1. dup", "= sum(src)"), ("3. dup", "= sum(x)")] {+ +++++ h.get_by_label_contains(row).hover();+ +++++ h.run_steps(30);+ +++++ assert!(h.query_by_label_contains(formula).is_some(), "{row} shows {formula}");+ +++++ }+ +++++}+ ++++++ +++++/// Field Properties refuses a notation it couldn't store as written, and stays open with what was+ +++++/// typed into it: the field keeps its formula and nothing in the dialog is lost. Once the notation+ +++++/// is fixed, OK applies it and closes.+ +++++#[test]+ +++++fn a_notation_that_cannot_be_stored_keeps_field_properties_open() {+ +++++ use pdfcraft_engine::form_scripts::Calculate;+ +++++ use pdfcraft_engine::{Edit, FieldProps, NewField};+ +++++ let mut h = harness();+ +++++ for (i, name) in ["qty", "sub"].into_iter().enumerate() {+ +++++ let y = 200.0 + 30.0 * i as f64;+ +++++ let kind = NewField::Text { multiline: false };+ +++++ h.state_mut().apply_edit(Edit::AddField { page: 0, rect: [20.0, y, 120.0, y + 20.0], kind, name: Some(name.into()) });+ +++++ }+ +++++ let props = Box::new(FieldProps { calculate: Some(Calculate::Notation("qty * 2".into())), ..Default::default() });+ +++++ h.state_mut().apply_edit(Edit::SetFieldProps { name: "sub".into(), props });+ +++++ let formula = |h: &Harness<'static, PdfCraftApp>| {+ +++++ let s = h.state();+ +++++ s.session.get(s.views[0].id).unwrap().form.iter().find(|f| f.name == "sub").unwrap().actions.calculate.clone()+ +++++ };+ +++++ h.state_mut().open_field_props("sub", 0);+ +++++ h.run_steps(3);+ +++++ let d = h.state_mut().field_props.as_mut().expect("Field Properties is open");+ +++++ d.calculate = Calculate::Notation("qty EVCALC 2".into());+ +++++ d.tooltip = "Subtotal".into();+ +++++ h.get_by_label("OK").click();+ +++++ h.run_steps(3);+ +++++ let kept = h.state().field_props.as_ref().map(|d| (d.calculate.clone(), d.tooltip.clone()));+ +++++ assert_eq!(kept, Some((Calculate::Notation("qty EVCALC 2".into()), "Subtotal".to_owned())), "the dialog stays open as typed");+ +++++ assert_eq!(formula(&h), Calculate::Notation("qty * 2".into()), "the field keeps its formula");+ +++++ h.state_mut().field_props.as_mut().expect("still open").calculate = Calculate::Notation("qty * 3".into());+ +++++ h.get_by_label("OK").click();+ +++++ h.run_steps(3);+ +++++ assert!(h.state().field_props.is_none(), "applied and closed");+ +++++ assert_eq!(formula(&h), Calculate::Notation("qty * 3".into()));+ +++++}+ ++++++ +++++/// A formula that reads a field the form doesn't have gets a card of its own, in place of "every+ +++++/// field calculates after the fields it reads", and its link opens that formula. A script that+ +++++/// builds the names it reads gets a note.+ +++++#[test]+ +++++fn a_formula_reading_a_missing_field_has_its_own_card() {+ +++++ use pdfcraft_engine::form_scripts::Calculate;+ +++++ use pdfcraft_engine::{Edit, FieldProps, NewField};+ +++++ use pdfcraft_ui_egui::prepare::FieldTab;+ +++++ let mut h = harness();+ +++++ for (i, name) in ["qty", "discount", "sub", "rows"].into_iter().enumerate() {+ +++++ let y = 200.0 + 30.0 * i as f64;+ +++++ let kind = NewField::Text { multiline: false };+ +++++ h.state_mut().apply_edit(Edit::AddField { page: 0, rect: [20.0, y, 120.0, y + 20.0], kind, name: Some(name.into()) });+ +++++ }+ +++++ let props = Box::new(FieldProps { calculate: Some(Calculate::Notation("qty - discount".into())), ..Default::default() });+ +++++ h.state_mut().apply_edit(Edit::SetFieldProps { name: "sub".into(), props });+ +++++ let script = Some("event.value = getField(\"row\" + 1).value;".to_owned());+ +++++ h.state_mut().apply_edit(Edit::SetFieldScript { name: "rows".into(), event: "calculate".into(), script });+ +++++ h.state_mut().execute("form.prepare");+ +++++ h.run_steps(3);+ +++++ h.get_by_label("Calculation order").click();+ +++++ h.run_steps(3);+ +++++ assert!(h.query_by_label("Every field calculates after the fields it reads.").is_some(), "nothing is missing yet");+ +++++ assert!(h.query_by_label("rows builds some field names as it runs, so those reads aren't checked.").is_some());+ +++++ h.state_mut().apply_edit(Edit::DeleteField { name: "discount".into() });+ +++++ h.run_steps(3);+ +++++ assert!(h.query_by_label("1 formula reads a field the form doesn't have").is_some());+ +++++ assert!(h.query_by_label("sub reads discount, which the form doesn't have.").is_some());+ +++++ assert!(h.query_by_label("Every field calculates after the fields it reads.").is_none(), "no all-clear while a formula is broken");+ +++++ // Reordered, the order can be undone from the missing-field card; the all-clear still stays away.+ +++++ h.state_mut().apply_edit(Edit::SetCalculationOrder { names: vec!["rows".into(), "sub".into()] });+ +++++ h.run_steps(3);+ +++++ assert!(h.query_by_label("Every field calculates after the fields it reads.").is_none(), "still no all-clear");+ +++++ h.get_by_label("Undo").click();+ +++++ h.run_steps(3);+ +++++ let order: Vec<String> = {+ +++++ let s = h.state();+ +++++ s.session.get(s.views[0].id).unwrap().calculation_order().fields.into_iter().map(|f| f.name).collect()+ +++++ };+ +++++ assert_eq!(order, ["sub", "rows"], "Undo put the order back");+ +++++ h.get_by_label("Edit sub's formula").click();+ +++++ h.run_steps(3);+ +++++ let draft = h.state().field_props.as_ref().map(|d| (d.field.clone(), d.tab));+ +++++ assert_eq!(draft, Some(("sub".to_owned(), FieldTab::Calculate)));+ +++++}+++++++++ ++++#[test]++ ++++fn button_export_properties_apply_cancel_and_undo() {++ ++++ fn retype(h: &mut Harness<'static, PdfCraftApp>, value: &str) {++ ++++ use egui::accesskit::Role;++ ++++ h.get_by_role_and_label(Role::TextInput, "Export value").click();++ ++++ h.run_steps(1);++ ++++ h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);++ ++++ h.get_by_role_and_label(Role::TextInput, "Export value").type_text(value);++ ++++ h.run_steps(2);++ ++++ }++ ++++ let mut h = harness();++ ++++ h.state_mut().execute("form.prepare");++ ++++ h.run_steps(2);++ ++++ h.state_mut().open_field_props("agree", 0);++ ++++ h.run_steps(2);++ ++++ h.get_by_label("Options").click();++ ++++ h.run_steps(2);++ ++++ let original = h.state().field_props.as_ref().unwrap().export_value.clone();++ ++++ retype(&mut h, "Accepted");++ ++++ h.get_by_label("Cancel").click();++ ++++ h.run_steps(2);++ ++++ h.state_mut().open_field_props("agree", 0);++ ++++ h.run_steps(2);++ ++++ assert_eq!(h.state().field_props.as_ref().unwrap().export_value, original);++ ++++ h.get_by_label("Options").click();++ ++++ h.run_steps(2);++ ++++ retype(&mut h, "Accepted");++ ++++ h.get_by_label("OK").click();++ ++++ h.run_steps(3);++ ++++ {++ ++++ let s = h.state();++ ++++ let f = s.session.get(s.views[0].id).unwrap().form.iter().find(|f| f.name == "agree").unwrap();++ ++++ assert_eq!(f.export_of(0), Some("Accepted"));++ ++++ }++ ++++ h.state_mut().execute("edit.undo");++ ++++ h.run_steps(3);++ ++++ {++ ++++ let s = h.state();++ ++++ let f = s.session.get(s.views[0].id).unwrap().form.iter().find(|f| f.name == "agree").unwrap();++ ++++ assert_eq!(f.export_of(0), Some(original.as_str()));++ ++++ }++ ++++}diff --cc docs/integration-20261030.mdindex 3f6bb9fef,000000000,000000000,000000000,000000000,000000000,000000000..f1d14c5c6mode 100644,000000,000000,000000,000000,000000,000000..100644--- a/docs/integration-20261030.md+++ b/docs/integration-20261030.md@@@@@@@@ -1,41 -1,0 -1,0 -1,0 -1,0 -1,0 -1,0 +1,43 @@@@@@@@++++++# PdfCraft integration candidate, 2026-10-30++++++++++++Base: 1d1cbc4ec92012767f5b48c92b451e15eb401c42++++++++++++Validation: pending combined GitHub CI. No fresh manual GUI pass has been performed.- All included source heads are preserved as merge parents, retaining original authorship. No upstream PR was merged. No conflicts were manually resolved.+++++++All included source heads are preserved as merge parents, retaining original authorship. No upstream PR was merged. Conflicts were resolved after the user requested inclusion despite merge conflicts.++++++++++++## Included++++++- [#4304](https://github.com/storytold/pdfcraft/pull/4304): M11: PDF Optimizer stores black-and-white images as CCITT Group 4 (optimize.mono-compression) (1b7164cab1fc187c5385c30f94449542fe284280)++++++- [#4335](https://github.com/storytold/pdfcraft/pull/4335): M11: black-and-white pictures stay one bit: Create PDF, the optimizer, and CCITT image export (210ba20fe69e701286bbfdbd924cfc01d9aaa9f4)++++++- [#4384](https://github.com/storytold/pdfcraft/pull/4384): M11: Monochrome Images ▸ Downsample: black-and-white images above 450 ppi are averaged down to 300, Group 4 scans included (1ad951e25bac86f77e75e060dcce34cc32a0f9a3)++++++- [#4404](https://github.com/storytold/pdfcraft/pull/4404): M11: the optimizer stores Group 3 fax as Group 4, and packs black-and-white RGB and two-entry indexed images to one bit (2d0a7b22411d4b61f130f6175cec918153858593)++++++- [#4179](https://github.com/storytold/pdfcraft/pull/4179): fix(ui): Ctrl+Z in an open paragraph undoes the document, not stale text (296b9300988fe3ef8d5bcdcb439705e80d6d7321)++++++- [#5300](https://github.com/storytold/pdfcraft/pull/5300): fix(ui): a press on the page belongs to what its one hit test finds, until the button is up (11bc8c56528fc3a820669d41c0eec29310cdad24)++++++- [#4719](https://github.com/storytold/pdfcraft/pull/4719): fix(comments): delete or edit one reply from its own menu, keeping the thread (adeb9c1cf2336c10639d8172325e708edf515856)++++++- [#4541](https://github.com/storytold/pdfcraft/pull/4541): M5: a moved comment is drawn where it goes while it is dragged (f0cd96e90bf696099b02201ac68f9ccb8a00c7d2)++++++- [#2815](https://github.com/storytold/pdfcraft/pull/2815): fix(edit): show backgrounds on pages that paint their own white backdrop (9aaac56417a2260338c7e7edb41615f1bb42b45e)++++++- [#4620](https://github.com/storytold/pdfcraft/pull/4620): feat(edit): Esc in an open paragraph selects its box, so Delete removes it (64fba7d177032170939861dc7eb51d8486a43264)++++++- [#3789](https://github.com/storytold/pdfcraft/pull/3789): Alt+Left / Alt+Right go back and forward through the view history (#3632) (08f3991ab9808b71fa015f22d49dbc4720044c78)++++++- [#3779](https://github.com/storytold/pdfcraft/pull/3779): Window title: mark unsaved changes, and set it on the web (#3640) (3850c9f52e073e51f8e4a1665b3ae36fae6f8e66)++++++- [#2960](https://github.com/storytold/pdfcraft/pull/2960): Keep lines with footnote references in paragraph reading order (#2929) (2a7e5bda268b3862b9b2329df16191473966c90e)++++++- [#5208](https://github.com/storytold/pdfcraft/pull/5208): M10: export a PDF to Markdown (#1595) (20d396d180a33139908a3a1fad6178ab77b90eff)++++++- [#4596](https://github.com/storytold/pdfcraft/pull/4596): fix(organize,print): join /Contents array pieces with a space (#3502) (d58d121170f2d650196263492c6c54a89aad39b3)++++++- [#3636](https://github.com/storytold/pdfcraft/pull/3636): Content streams: step over a malformed token instead of ending the page (43337c7fd5f7b5123efcebcc84de35c394726e7a)++++++- [#4494](https://github.com/storytold/pdfcraft/pull/4494): M2: page_render and render_preview report the render warnings next to the PNG (#4340) (5ada1249e9cdb98a438e26f8fe53c82aba9b8cc1)++++++- [#4013](https://github.com/storytold/pdfcraft/pull/4013): fix(engine): generate Protect keys and salts with getrandom (#4000) (c580b550555837ad6f2c1aa4152bdb5cb96cf337)++++++- [#5134](https://github.com/storytold/pdfcraft/pull/5134): fix(ui): keep the All tools rows clear of the scrollbar (#5133) (0c5119791db7de268258b9d25f1286b82b563f8a)++++++- [#2133](https://github.com/storytold/pdfcraft/pull/2133): Fix Pages sidebar select-all keyboard shortcut (#2052) (7227eb68ab383e47413f1a980f340f5132cf4144)++++++- [#2635](https://github.com/storytold/pdfcraft/pull/2635): Allow typed font sizes and Fill & Sign text colours (4b319bb3835709626c663b8d41b72d2f9574acc0)++++++- ## Excluded- - [#4320](https://github.com/storytold/pdfcraft/pull/4320): conflict.- - [#4805](https://github.com/storytold/pdfcraft/pull/4805): conflict.- - [#4325](https://github.com/storytold/pdfcraft/pull/4325): conflict.- - [#4180](https://github.com/storytold/pdfcraft/pull/4180): conflict.- - [#1952](https://github.com/storytold/pdfcraft/pull/1952): conflict.- - [#2529](https://github.com/storytold/pdfcraft/pull/2529): conflict with main.+++++++## Added after conflict resolution+++++++- [#4320](https://github.com/storytold/pdfcraft/pull/4320): M11: lossless JBIG2 for black-and-white images (optimize.mono-compression) (e18d1bfed38272a33fad1b79b7452494a9f4dfd6).+++++++- [#4805](https://github.com/storytold/pdfcraft/pull/4805): M11: JBIG2 symbol coding for black-and-white images (optimize.mono-compression) (c7f39a4d9a341dcbdacaf3bc131ea2825f030b13).+++++++- [#4325](https://github.com/storytold/pdfcraft/pull/4325): M6: calculation checks: formulas reading missing fields, scripts building names, shown on the Calculation order page (ebad7f849d9dc04f8aa819efd4cfb06460de3d79).+++++++- [#4180](https://github.com/storytold/pdfcraft/pull/4180): M7: align the selected lines of a paragraph or text box on their own (5a86f35210ca98adb23ba53ff9d0871593b0cfdb).+++++++- [#1952](https://github.com/storytold/pdfcraft/pull/1952): feat(forms): edit checkbox and radio export values (#231) (e19f9646906df51c287f9b049feb8199cd645996).+++++++- [#2529](https://github.com/storytold/pdfcraft/pull/2529): M7: keep a blank line as a paragraph break (#2517) (55a933800b94b89c0caae001ec48609cd5f70256).++++++- Additional previously reviewed parity fixes: #2133 and #2635. #1952 was considered but conflicts.+++++++Additional previously reviewed parity fixes: #2133, #2635 and #1952.++++++Excluded held PRs #4648, #2877 and #3762 were not included.++++++Source reviews and individual hosted CI do not establish combined-build safety; the integration gate must pass.++++++++++++++Integration-specific changes: preserve hard/soft wrap metadata together with per-row alignment; share CCITT/JBIG2 export paths with the 32 MiB globals cap retained; keep downsampling and RGB ownership guards with JBIG2 encoding; retain all translation keys and both sets of regression tests.diff --cc docs/pdf-spec-parity.mdindex 458f6a710,8cfe4be47,8cfe4be47,8cfe4be47,8cfe4be47,a1c26eefb,68d26bcce..e34a93127--- a/docs/pdf-spec-parity.md+++ b/docs/pdf-spec-parity.md@@@@@@@@ -1,7 -1,7 -1,7 -1,7 -1,7 -1,7 -1,7 +1,11 @@@@@@@@# PDF specification and standards parity---- > **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-24 · **Change:** minor (§14.3: custom properties edited in Document Properties) · **Target:** Adobe Acrobat Pro (Acrobat DC, continuous track 26.002.21931, macOS)- > **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-26 · **Change:** minor (§7.4: lossless JBIG2 encoding in the Optimizer; JBIG2 images export; earlier, §7.4: CCITT Group 4 encoding in the Optimizer) · **Target:** Adobe Acrobat Pro (Acrobat DC, continuous track 26.002.21931, macOS)-> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-26 · **Change:** minor (§7.4: JBIG2 symbol coding in the Optimizer; earlier, lossless JBIG2 encoding, JBIG2 images export and CCITT Group 4 encoding) · **Target:** Adobe Acrobat Pro (Acrobat DC, continuous track 26.002.21931, macOS)++++++> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-26 · **Change:** minor (§7.4: redaction decodes CCITT fax images, Group 3 on bytes aside; earlier, §7.4: CCITT decoding in `pdfcraft-filters`) · **Target:** Adobe Acrobat Pro (Acrobat DC, continuous track 26.002.21931, macOS)+++++++++++++Lossless JBIG2 encoding and image export are included alongside CCITT decoding and monochrome downsampling; combined validation is pending.++++++++++++++JBIG2 exact-copy symbol dictionaries and text regions are included; lossy substitution is not supported.+How much of ISO 32000-2 (PDF 2.0) and the PDF subset standards PdfCraft implements, set againstwhat Acrobat Pro implements. This is PdfCraft's equivalent of a "geometry" or "codec" checklist:the parts of the format users never see named but always feel. Feature-level detail is in@@@@@@@@ -21,7 -21,7 -21,7 -21,7 -21,7 -21,7 -21,7 +25,11 @@@@@@@@ are borrowed; PDF 2.0 additions and mos|---|---|---|---|---|| §7.2–7.5 | Syntax, objects, file structure, xref tables and streams, object streams, hybrid files, incremental updates | full | **own**, tolerant, repairs damaged files | `crates/cos`; corpus 958 files; fuzzed nightly || §7.4 | Stream filters: Flate, LZW, ASCII85, ASCIIHex, RunLength, predictors | full | **own** | `crates/filters` |---- | §7.4 | Image filters: DCT, JPX, JBIG2, CCITTFax | full | **borrowed** (decode only) | `core.image-filters` partial; own codecs M1.1/M1.2; no JBIG2/CCITT encoding (Optimizer) |- | §7.4 | Image filters: DCT, JPX, JBIG2, CCITTFax | full | **borrowed** (decode); CCITT Group 4 encoding; **own** JBIG2 encoding | `core.image-filters` partial; own codecs M1.1/M1.2; the Optimizer encodes CCITT Group 4 (`pdfcraft_filters::encode_g4`) and lossless JBIG2 (a generic region; no symbol coding), `optimize.mono-compression` |-| §7.4 | Image filters: DCT, JPX, JBIG2, CCITTFax | full | **borrowed** (decode); CCITT Group 4 encoding; **own** JBIG2 encoding | `core.image-filters` partial; own codecs M1.1/M1.2; the Optimizer encodes CCITT Group 4 (`pdfcraft_filters::encode_g4`) and lossless JBIG2 (a generic region, or symbols for exact copies; no refinement, `/JBIG2Globals` or lossy coding), `optimize.mono-compression` |++++++| §7.4 | Image filters: DCT, JPX, JBIG2, CCITTFax | full | **borrowed** (decode); CCITT Group 4 encoding | `core.image-filters` partial; own codecs M1.1/M1.2; CCITT decoding in `pdfcraft-filters` (`decode_ccitt`, through `hayro-ccitt`) for export, redaction and the Optimizer, which encodes Group 4 (`optimize.mono-compression`); no JBIG2 encoding |++++++++++++++Lossless JBIG2 encoding and image export are included alongside CCITT decoding and monochrome downsampling; combined validation is pending.++++++++++++++JBIG2 exact-copy symbol dictionaries and text regions are included; lossy substitution is not supported.| §7.5.8 | Linearization | R W | R only | `core.linearization` planned || §7.6.4 | Standard security handler R2–R6 (RC4 40/128, AES-128, AES-256), crypt filters, `/EncryptMetadata`, SASLprep | full | **own**, read and write | `crates/crypt`; written files open in Acrobat DC since #836 (#774: Acrobat needs the catalog outside object streams) || §7.6.5 | Public-key security handler | full | none | `core.open-public-key`, `protect.certificate-encryption` planned |@@@@@@@@ -130,9 -130,6 -130,6 -130,6 -130,6 -130,8 -130,9 +138,13 @@@@@@@@| Date | Change | Summary ||---|---|---|-| 2026-10-26 | minor | §7.4: lossless JBIG2 symbol coding (symbol dictionaries and text regions, own, from the JBIG2 draft standard) in the Optimizer, used when smaller than the generic region |--| 2026-10-26 | minor | §7.4: lossless JBIG2 generic-region encoding (own, from the JBIG2 draft standard) in the Optimizer; Export ▸ Images decodes JBIG2 |++++++| 2026-10-26 | minor | §7.4: redaction clears pixels in CCITT fax images through the CCITT decoder, instead of removing them whole (Group 4 and Group 3 off bytes; Group 3 on bytes is still removed whole, as the bootstrap renderer may draw it as other rows than the decoder reads) |++++++| 2026-10-26 | minor | §7.4: CCITT decoding (`hayro-ccitt`) in `pdfcraft-filters`, for export and the Optimizer |++++++++++++++Lossless JBIG2 encoding and image export are included alongside CCITT decoding and monochrome downsampling; combined validation is pending.++++++++++++++JBIG2 exact-copy symbol dictionaries and text regions are included; lossy substitution is not supported.++++ | 2026-10-26 | minor | §7.4: CCITT Group 4 encoding (`fax`) in the Optimizer || 2026-10-14 | minor | §12.4.4: `/Trans` and `/Dur` read into `DocInfo::transitions` and reported by `doc_info` || 2026-10-11 | minor | §7.6.4: encrypted files we write open in Acrobat (#774, fixed by #836) || 2026-10-10 | major | Created from the code, `vendor/README.md` and `parity/acrobat-features.toml`, against ISO 32000-2 and Acrobat Pro 26.002.21931's documented capabilities |diff --cc docs/roadmap.mdindex c8aae0ba8,8d922f707,25205e92c,25205e92c,17594ee76,4f376cfb7,f21943c38..ab55c052c--- a/docs/roadmap.md+++ b/docs/roadmap.md@@@@@@@@ -1,12 -1,8 -1,7 -1,7 -1,8 -1,9 -1,10 +1,16 @@@@@@@@# PdfCraft roadmap: milestones and what's next++++ ++> **Last reviewed:** 2026-10-29 | **Last updated:** 2026-10-29 | **Change:** minor (M7 #2517: a narrowed then widened paragraph keeps the typed spaces the wrap consumed, after save and reopen; estimates unchanged)> **Last reviewed:** 2026-10-27 | **Last updated:** 2026-10-27 | **Change:** minor (M10: OCR model downloads use verified ONNX pairs with legacy discovery fallback; estimates unchanged)++++++> **Last reviewed:** 2026-10-25 | **Last updated:** 2026-10-25 | **Change:** minor (M5: one reply in the Comments panel is edited, copied or deleted from its own "…" menu; estimates unchanged)++++++ > **Last reviewed:** 2026-10-26 · **Last updated:** 2026-10-26 · **Change:** minor (M11: lossless JBIG2 stores each distinct mark once, as a symbol; estimates unchanged)> **Last reviewed:** 2026-10-25 | **Last updated:** 2026-10-25 | **Change:** minor (M14 localization current state: Arabic logical catalog, explicit RTL label direction and mirrored stock chrome; native/browser RTL workflows unqualified. Native release Hans face via LXGW WenKai Lite; estimates unchanged)++++++> **Last reviewed:** 2026-10-24 · **Last updated:** 2026-10-24 · **Change:** minor (M11: the optimizer stores Group 3 fax images as Group 4, and packs black-and-white RGB and indexed images that use only palette entries 0 and 1 to one bit; estimates unchanged)++++++> **Last reviewed:** 2026-10-24 · **Last updated:** 2026-10-24 · **Change:** minor (M11: black-and-white images above 450 ppi are averaged down to 300 ppi by the optimizer; estimates unchanged)++++++> **Last reviewed:** 2026-10-24 · **Last updated:** 2026-10-24 · **Change:** minor (M11: black-and-white pictures stay one bit when PDFs are created and optimized; CCITT images export; estimates unchanged)+++++ > **Last reviewed:** 2026-10-23 · **Last updated:** 2026-10-24 · **Change:** minor (M11: the PDF Optimizer can store black-and-white images as lossless JBIG2, and Export ▸ Images reads JBIG2 images; estimates unchanged)++++ > **Last reviewed:** 2026-10-23 · **Last updated:** 2026-10-23 · **Change:** minor (M11: the PDF Optimizer and Reduce File Size store black-and-white images as CCITT Group 4 when smaller; estimates unchanged)+ +++++> **Last reviewed:** 2026-10-23 · **Last updated:** 2026-10-23 · **Change:** minor (M6: the calculation order flags a formula that reads a field the form doesn't have and a script that builds the names it reads; the tools show each formula; estimates unchanged)> **Last reviewed:** 2026-10-23 · **Last updated:** 2026-10-23 · **Change:** minor (M7, #2636 partial: pasting added text boxes and images in the engine and through `content_copy`; estimates unchanged)> **Last reviewed:** 2026-10-23 · **Last updated:** 2026-10-23 · **Change:** minor (M11: image optimization accounts for page-local UserUnit; estimates unchanged)@@@@@@@@ -200,7 -196,7 -195,7 -195,7 -197,7 -197,7 -198,7 +205,7 @@@@@@@@ total matches the parity estimate| M8 | Security + redaction | 100–180 | 68% | 15–30 | Done: opening protected documents, permissions, Protect Using Password, Remove security; redaction (mark text/areas/pages, Search & Redact with patterns, apply removing glyphs, image pixels, vectors, XObject content, annotations and fields, verification, full rewrite on save); Remove hidden information and Sanitize.<br>Done since: redaction codes (U.S. FOIA and Privacy Act sets as overlay text, in Redaction properties and `redact_mark`). Redaction cleans indirect and form structure references, preserving surviving form tags. Redaction retires inherited resource dictionaries, so a parent `/Pages` can't keep a removed XObject reachable; unredacted pages are left untouched. Image redaction removes alternate images and unsupported masks only on affected images. Changed marked-content spans lose replacement descriptions; untouched spans keep theirs. Hidden-text cleanup retires unused named descriptions across inherited/shared page and form resources (64 focused tests and scoped Rust 1.96 Clippy/wasm checks pass; publication CI pending). The redaction audit counts a filled cover that hides half of any one word of a long line (#2662), applied or not. Phone-pattern redaction also matches labelled Italian geographic numbers with `+39` and a slash after the area code (#3205 follow-up); unlabelled international slash numbers remain unsupported. Missing: certificate security, custom redaction code sets and pattern locales, DCT re-encoding || M9 | Signatures (PAdES, validation) | 160–280 | 60% | 40–70 | Done: new `sign` crate (DER, X.509, CMS, PKCS #12 on RustCrypto; aws-lc-rs for RSA private keys); PAdES B-B signing (visible, invisible, existing fields, certification with DocMDP); validation with trust store and changes-after-signing classification; self-signed digital IDs; Signatures panel, message bar, sign dialogs; agent tools. Checked with pdfsig and OpenSSL.<br>Done since: macOS Keychain and Windows Current User Personal store signing (software-backed CNG keys), certificate viewer, signed documents protected from rewrites, page validation overlays separate from original signature artwork (baked Not Verified captions remain; #79 open), snapshot tabs that reuse instead of multiplying. Missing: timestamps (B-T), LTV (DSS, OCSP, CRL), FieldMDP, smart cards, PKCS #11 || M10 | OCR, create, export, print | 200–350 | 33% | 120–215 | Done: create from blank/text/PNG/JPEG/TIFF (multi-page)/GIF/BMP; export PNG/JPEG/TIFF and text; Print (Acrobat's sizing, n-up, booklet, poster, comments & forms, preview, the CUPS and Windows spoolers, print-ready PDF).<br>Done since: embedded/72/custom DPI choices for image imports; export all images; OCR (searchable image for pages, ranges and multiple files); single-sided cut-and-stack imposition with cut marks, through Print and doc_print; architectural/ANSI/large ISO sheet presets, Match page at 100% and PDF-scale preview (#599 follow-up); Create PDF from multiple files (PDFs, images and text, edited as pages in the grid); OCR can also read pictures on pages that have text, without adding that text twice (#1028). Model staging fetches SHA-256-verified ONNX detection/recognition files after the upstream RTEN URL brownout; runtime discovery prefers complete ONNX pairs per directory, then complete legacy RTEN pairs, without mixing formats or changing directory precedence. Done since: Word invoice export uses borderless inferred tables, floating positioned text/artwork only where text overlaps an image or is rotated, and per-page sizes, covered by synthetic invoice automation regressions (#773); printing on the web through the browser's print dialog, sheets drawn by PdfCraft (gap 4). Lossless image export applies per-component Decode, including Indexed mapping (#1201 partial). Existing 16-bit precision and color-management limits remain. #3532 partial: vector printing retains existing appearances with absent Subtype through a print-owned Form copy; source artwork stays unchanged. #3120: Office export reads form XObjects 50 levels deep, as the renderer does, and up to 50 000 a page; pages past that are listed in `truncated_pages`. Word table cells use the grid columns they span, including cells after a merged cell. Done since: text in a table slot covered by another cell's span remains as paragraph text in Word, HTML, RTF and PowerPoint. Missing: OCR languages beyond Latin, editable-text OCR output, full Office layout fidelity/import. Done since: dotted-leader contents entries stay in separate complete paragraphs (#1757) #2156 candidate: last selected print paper persists across sessions; other print preferences unchanged. Image export applies soft-mask Decode opacity intervals before resizing, including indirect entries and inverted ranges. Vector printing gives annotation appearances unoccupied XObject names so existing page artwork survives. |---- | M11 | Optimize, preflight, PDF/A/X/UA, print production | 200–350 | 18% | 80–140 | Done: new `optimize` crate: Reduce File Size and the PDF Optimizer (images measured where drawn, bicubic downsampling, JPEG/ZIP recompression only when smaller, discard objects and user data, Flate clean-up, resource merging, object streams). Target-version compatibility is partial: newer content is not detected or converted. Content stream boundaries preserve comments, split operands and graphics state when image fragments merge. Image downsampling includes page-local `/UserUnit` scaling when measuring physical resolution. Done since: reject invalid image and soft-mask dimensions with checked sizing (#2178). Missing: fonts and transparency panels, space audit, preflight, PDF/A/X/UA |--| M11 | Optimize, preflight, PDF/A/X/UA, print production | 200–350 | 18% | 80–140 | Done: new `optimize` crate: Reduce File Size and the PDF Optimizer (images measured where drawn, bicubic downsampling, JPEG/ZIP recompression only when smaller, discard objects and user data, Flate clean-up, resource merging, object streams). Target-version compatibility is partial: newer content is not detected or converted. Content stream boundaries preserve comments, split operands and graphics state when image fragments merge. Image downsampling includes page-local `/UserUnit` scaling when measuring physical resolution. Done since: reject invalid image and soft-mask dimensions with checked sizing (#2178); black-and-white images stored losslessly as CCITT Group 4 when smaller. Missing: fonts and transparency panels, space audit, preflight, PDF/A/X/UA |++++++| M11 | Optimize, preflight, PDF/A/X/UA, print production | 200–350 | 18% | 80–140 | Done: new `optimize` crate: Reduce File Size and the PDF Optimizer (images measured where drawn, bicubic downsampling, JPEG/ZIP recompression only when smaller, discard objects and user data, Flate clean-up, resource merging, object streams). Target-version compatibility is partial: newer content is not detected or converted. Content stream boundaries preserve comments, split operands and graphics state when image fragments merge. Image downsampling includes page-local `/UserUnit` scaling when measuring physical resolution. Done since: reject invalid image and soft-mask dimensions with checked sizing (#2178); black-and-white images stored losslessly as CCITT Group 4 when smaller, averaged down to 300 ppi above 450 (halftones aside), Group 3 stored again as Group 4, and black-and-white RGB and indexed images that use only palette entries 0 and 1 packed to one bit. Missing: fonts and transparency panels, space audit, preflight, PDF/A/X/UA || M12 | Accessibility, compare, measure, search, XFA | 200–380 | 30% | 90–160 | Done: new `a11y` crate with the Accessibility Checker (all 32 rules, report, Fix/Skip/Explain, options dialog and results panel, agent tools). Locatable figure, annotation and form findings highlight their page bounds. Character encoding accepts Identity-H/V with Adobe CJK collections and predefined CJK CMaps independently (#3673); per-glyph validation and embedded-font extraction remain separate.<br>Done since: 2D distance, perimeter and area measurements with persistent viewport calibration, snapping, live information and CSV export; a bounded, text-only auto-tag proposal tool for one page. Marking a figure decorative rewrites only that stream (#1324). An XFA radio item whose value contains a space is written back unchanged (#1319). Done since: #2569: Growable multiline XFA text reflows after edits, with undo/redo, save/reopen and print coverage; oversized fields still become read-only page text. Structured-data synchronization warnings retain accepted whitespace without relayout from stale data. Done since: #2572: Every repeated page-master button resolves its own field to the shared XFA click script, including print buttons. Done since: #2570: Dynamic XFA rich-text fields carry exData/maxLength into AcroForm MaxLen for reported and enforced Unicode character limits, retained after save/reopen. Done since: #2589: Active XFA skips PDF-container fallback scripts while retaining requested messages and saved scripts; ordinary/static/unlaid-out documents and explicit console/field calls keep their existing behavior. Missing: writing proposed tags and parent tree, field autotag, visual Tags/Order/Content panels, Reading Order tool, compare, geospatial/3D measurement, search index, XFA<br>Reading colours: pending page backgrounds follow the configured colour (#2059). || M13 | Automation (MCP, Action Wizard, CLI) + AI providers | 60–120 | 45% | 25–45 | Done: MCP resources (document info, text, page images); headless tool table (123 tools incl. signing, optimizing, initial view, links, stamps, data exchange, comment review, forms authoring and scripts, redaction, sanitize, print, add content), opt-in MCP server over stdio, CLI `run`/`tools` (closed stdout pipes exit cleanly), UI control channel with drag. Missing: Action Wizard, AI providers<br>Done since: CLI run and MCP reject missing, empty, repeated and option-valued --root arguments before any tool/script execution or MCP initialization. A single-hyphen directory name remains valid; synthetic CLI regressions preserve a would-be overwritten file. `text_find` also caps the per-page match ranges it materializes at the remaining result limit plus one continuation match. CLI robustness scans visit each directory once through overlapping roots and symlink aliases. || M12 | Accessibility, compare, measure, search, XFA | 200–380 | 30% | 90–160 | Done: new `a11y` crate with the Accessibility Checker (all 32 rules, report, Fix/Skip/Explain, options dialog and results panel, agent tools). Locatable figure, annotation and form findings highlight their page bounds. Character encoding accepts Identity-H/V with Adobe CJK collections and predefined CJK CMaps independently (#3673); per-glyph validation and embedded-font extraction remain separate.<br>Done since: 2D distance, perimeter and area measurements with persistent viewport calibration, snapping, live information and CSV export; a bounded text-only auto-tag proposal tool; text-only Apply writes marked content, paragraph tags and a parent tree, then opens the Tags panel for review. Missing: mixed-content and field autotag, heading/list/table/figure classification, Order/Content panels, Reading Order tool, compare, geospatial/3D measurement, search index, XFA<br>Done since: CLI info, text and render use dynamic XFA layout pages, with synthetic count/text/pixel and copy-permission regressions (#1645).<br>Reading colours: pending page backgrounds follow the configured colour (#2059). |@@@@@@@@ -260,10 -256,7 -255,6 -255,6 -257,7 -257,8 -258,9 +265,14 @@@@@@@@ Estimates unchanged| Date | Change | Summary ||---|---|---|++++++| 2026-10-24 | minor | M11: the PDF Optimizer and Reduce File Size store Group 3 fax images as Group 4 when smaller (`Document::fax_params`), and pack eight-bit `DeviceRGB` of only black and white (as grey) and indexed images of 2, 4 or 8 bits that use only palette entries 0 and 1 (keeping the palette) to one bit, so Monochrome Images compresses and downsamples them. Estimates unchanged. |++++++| 2026-10-24 | minor | M11: monochrome downsampling: the PDF Optimizer and Reduce File Size average black-and-white images (1-bit, CCITT fax, eight-bit black-and-white grey) above 450 ppi down to 300 ppi, by area with ties black, as Monochrome Images ▸ Downsample to and `doc_optimize` `mono: { downsample, ppi, above_ppi }`; CCITT decoding moves into `pdfcraft-filters` (`decode_ccitt`) behind `Document::decoded_image`. Estimates unchanged. |++++++| 2026-10-24 | minor | M11: Create PDF stores pictures of only black and white at one bit (Group 4 or Flate, whichever is smaller) instead of eight-bit grey; the optimizer packs eight-bit black-and-white grey images to one bit before Monochrome Images compresses them, unless the grey settings make them smaller, as they can a dithered scan, soft mask counted; Export ▸ Images decodes CCITT fax images. Estimates unchanged. |++++++ | 2026-10-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. |diff --cc docs/target-app-parity.mdindex 33eb64515,6c7920e33,6c7920e33,6c7920e33,6c7920e33,22832f65f,d48333c18..cd018f048--- a/docs/target-app-parity.md+++ b/docs/target-app-parity.md@@@@@@@@ -1,7 -1,5 -1,5 -1,5 -1,5 -1,7 -1,8 +1,11 @@@@@@@@# PdfCraft parity with Adobe Acrobat Pro-> **Last reviewed:** 2026-10-25 · **Last updated:** 2026-10-26 · **Change:** minor (K Optimize and standards no longer lists JBIG2 symbol coding as missing; scores and estimates unchanged)--> **Last reviewed:** 2026-10-25 · **Last updated:** 2026-10-26 · **Change:** minor (K Optimize and standards no longer lists lossless JBIG2 as missing; scores and estimates unchanged)++++++> **Last reviewed:** 2026-10-25 · **Last updated:** 2026-10-26 · **Change:** minor (K Optimize and standards no longer lists monochrome downsampling as missing; scores and estimates unchanged)++++++++++++++Lossless JBIG2 encoding and image export are included alongside CCITT decoding and monochrome downsampling; combined validation is pending.++++++++++++++JBIG2 exact-copy symbol dictionaries and text regions are included; lossy substitution is not supported.++++ > **Last reviewed:** 2026-10-25 · **Last updated:** 2026-10-26 · **Change:** minor (`optimize.mono-compression` partial (CCITT Group 4): K Optimize and standards 15 shipped and 11 partial of 58, 35.3%; breadth 57.0% unweighted (423 + 75 of 808), mainstream 63.3% (292 + 45 of 497); estimates unchanged)> **Last reviewed:** 2026-10-25 · **Last updated:** 2026-10-25 · **Change:** minor (localization current state: Arabic logical catalog, explicit RTL direction and mirrored stock chrome; native/browser RTL workflows unqualified. Native release Hans face via LXGW WenKai Lite. Scores and estimates unchanged)> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-13 · **Change:** minor (localization ≈59% → ≈68%; weighted readiness 49.25 → 49.7 ≈ 50%) · **Target:** Adobe Acrobat Pro (Acrobat DC, continuous track 26.002.21931, macOS)@@@@@@@@ -210,7 -208,7 -208,7 -208,7 -208,7 -210,7 -211,7 +214,11 @@@@@@@@ full parity in that area| H Digital signatures | 45 | 23 | 10 | 62.2% | 45% | 40–70 | PAdES B-B signing and validation (PKCS #12, macOS Keychain, Windows store with PIN prompts), certification, encrypted documents, certificate usage checks; B-T, LTV, OCSP/CRL with caller-supplied evidence. Missing: PKCS #11 and smart cards outside Windows, timestamp-server preferences, online revocation fetching, FieldMDP and field locking, OS trust store, EU Trusted Lists, compare signed version || I Scan and OCR | 26 | 5 | 2 | 23.1% | 15% | 40–75 | Searchable image (ocrs, Latin script without accents) on pages, ranges and many files. Missing: every other language (#744 Dutch; accents, CJK, Cyrillic, Arabic), editable-text output, deskew, rotation, despeckle, camera images beyond straightening (found or placed corners): orientation, clean-up, MRC compression, scanners || J Create and export | 34 | 12 | 3 | 39.7% | 25% | 55–100 | Create from images, multipage TIFF, text, clipboard, blank, many files at once; export PNG/JPEG/TIFF, text, RTF; Word and HTML partial. Missing: Office/HTML/web/PostScript to PDF, Excel and PowerPoint export, Word layout fidelity (#773), SVG/XML/EPS/PS/JPEG 2000 export, accessible text |---- | K Optimize and standards | 58 | 15 | 10 | 34.5% | 20% | 65–115 | Reduce File Size and the Optimizer (images, discards, clean-up, space audit); PDF/A-2b/3b verify and convert (partial). Missing: Preflight (profiles, fixups, reports), PDF/A-1/4 and a/u levels, PDF/X, PDF/UA, PDF/E, PDF/VT, transparency flattening, font unembedding, monochrome JBIG2/CCITT |- | K Optimize and standards | 58 | 15 | 11 | 35.3% | 20% | 65–115 | Reduce File Size and the Optimizer (images, discards, clean-up, space audit); PDF/A-2b/3b verify and convert (partial). Missing: Preflight (profiles, fixups, reports), PDF/A-1/4 and a/u levels, PDF/X, PDF/UA, PDF/E, PDF/VT, transparency flattening, font unembedding, JBIG2 symbol coding and lossy JBIG2, monochrome downsampling |-| K Optimize and standards | 58 | 15 | 11 | 35.3% | 20% | 65–115 | Reduce File Size and the Optimizer (images, discards, clean-up, space audit); PDF/A-2b/3b verify and convert (partial). Missing: Preflight (profiles, fixups, reports), PDF/A-1/4 and a/u levels, PDF/X, PDF/UA, PDF/E, PDF/VT, transparency flattening, font unembedding, lossy JBIG2, JBIG2 refinement coding and a symbol dictionary shared between images, monochrome downsampling |++++++| K Optimize and standards | 58 | 15 | 11 | 35.3% | 20% | 65–115 | Reduce File Size and the Optimizer (images, discards, clean-up, space audit); PDF/A-2b/3b verify and convert (partial). Missing: Preflight (profiles, fixups, reports), PDF/A-1/4 and a/u levels, PDF/X, PDF/UA, PDF/E, PDF/VT, transparency flattening, font unembedding, monochrome JBIG2 |++++++++++++++Lossless JBIG2 encoding and image export are included alongside CCITT decoding and monochrome downsampling; combined validation is pending.++++++++++++++JBIG2 exact-copy symbol dictionaries and text regions are included; lossy substitution is not supported.| L Print | 39 | 15 | 1 | 39.7% | 35% | 30–55 | Acrobat's sizing, n-up, booklet, poster, comments & forms, preview, print-ready PDF, CUPS on macOS/Linux, the Windows spooler (#756) and the browser's print dialog on the web. Missing: print as image, PostScript, all print-production tools (output preview, separations, ink manager, printer marks, colour conversion) || M Accessibility | 61 | 38 | 1 | 63.1% | 30% | 40–70 | Accessibility Checker (all 32 rules, report, fixes), alternate text, title and language. Missing: autotag, Tags/Order/Content panels, Reading Order tool, artifact marking, table editor, Read Out Loud, full keyboard operation of the app, screen-reader audit || N Automation, preferences, misc | 75 | 20 | 5 | 30.0% | 35% | 25–45 | CLI, MCP, UI control channel, 141 automation tools, Action Wizard (run, create), compare (text, visual, report, side by side, Text/Visual filter). Missing: most Preferences pages, Acrobat's finer compare filters, Action Wizard management, custom commands, AI providers, rich media/3D, hosted web app |@@@@@@@@ -296,8 -294,6 -294,6 -294,6 -294,6 -296,8 -297,9 +304,12 @@@@@@@@ licensed OCR or AI model| Date | Change | Summary ||---|---|---|-| 2026-10-26 | minor | K Optimize and standards no longer lists JBIG2 symbol coding as missing (lossless, exact copies); lossy JBIG2, refinement coding and a dictionary shared between images still are. Scores and estimates unchanged. |--| 2026-10-26 | minor | K Optimize and standards no longer lists lossless JBIG2 as missing (a generic region, through the Optimizer's Monochrome Images); symbol coding and lossy JBIG2 still are. Scores and estimates unchanged. |++++++| 2026-10-26 | minor | K Optimize and standards no longer lists monochrome downsampling as missing (black-and-white images above 450 ppi are averaged down to 300). Scores and estimates unchanged. |++++++++++++++Lossless JBIG2 encoding and image export are included alongside CCITT decoding and monochrome downsampling; combined validation is pending.++++++++++++++JBIG2 exact-copy symbol dictionaries and text regions are included; lossy substitution is not supported.++++ | 2026-10-26 | minor | `optimize.mono-compression` became partial (CCITT Group 4), counted on the table's own measurement: K Optimize and standards 15 shipped and 11 partial of 58 (35.3%), no longer listing CCITT as missing; breadth 57.0% unweighted (423 + 75 of 808), mainstream 63.3% (292 + 45 of 497). Estimates unchanged. || 2026-10-25 | minor | Localization current state: Arabic catalogs stay logical, Arabic/Kurdish labels take an explicit RTL direction, and stock chrome mirrors; native/browser RTL input, IME and complex workflows remain unqualified. Native Simplified Chinese uses LXGW WenKai Lite; the web build has no Hans face. Scores and estimates unchanged. || 2026-10-20 | minor | M12 #3673: the Character encoding rule accepts Identity-H/V fonts with Adobe CJK collections, or a predefined non-Identity CMap, while rejecting unknown names and foreign registries. Synthetic checker and read-only automation regressions passed after failing before the fix; per-glyph mapping validation and embedded-font extraction remain separate. Breadth, readiness and hours unchanged. || 2026-10-12 | minor | Exclusive image crops resize with their pixels across nested states, intervening operators and content streams; shared clips remain fixed. Synthetic engine/tool regressions and private image save/reopen checks; estimates unchanged. |diff --cc parity/acrobat-features.tomlindex ca7a44a58,3b7713a3d,3b8dba920,e65d44033,056cb1bfe,7bdf89eca,9e9f1ae80..98ebd7e9a--- a/parity/acrobat-features.toml+++ b/parity/acrobat-features.toml@@@@@@@@ -1599,7 -1599,7 -1599,7 -1599,7 -1599,7 -1599,7 -1599,7 +1599,7 @@@@@@@@ status = "partialcommands = []tools = []evidence = ["crates/ui-egui/tests/it/viewer.rs::a_clicked_picture_is_selected_and_copied_in_its_original_format", "crates/ui-egui/tests/it/viewer.rs::right_click_on_a_picture_copies_it_at_full_size", "crates/ui-egui/tests/it/viewer.rs::a_picture_inside_form_artwork_under_text_is_selected_and_copied", "crates/engine/src/tests.rs::copy_image_finds_a_picture_inside_form_artwork_under_text"]- notes = "Select tool: a click selects a raster image (also inside Form artwork or under text) and ⌘C copies it as a file in its original format (JPEG as stored, else PNG); right-click ▸ Copy Image copies its pixels at full resolution. Missing: inline images (BI/ID/EI), JPEG 2000/JBIG2 images, multi-format clipboard (file and bitmap at once), the web build"---- notes = "Select tool: a click selects a raster image (also inside Form artwork or under text) and ⌘C copies it as a file in its original format (JPEG as stored, else PNG); right-click ▸ Copy Image copies its pixels at full resolution. Missing: inline images (BI/ID/EI), JPEG 2000/JBIG2/CCITT images, multi-format clipboard (file and bitmap at once), the web build"--notes = "Select tool: a click selects a raster image (also inside Form artwork or under text) and ⌘C copies it as a file in its original format (JPEG as stored, else PNG); right-click ▸ Copy Image copies its pixels at full resolution. Missing: inline images (BI/ID/EI), JPEG 2000/CCITT images, JBIG2 inside other filters, multi-format clipboard (file and bitmap at once), the web build"+++++++notes = "Select tool: a click selects a raster image (also inside Form artwork or under text) and ⌘C copies it as a file in its original format (JPEG as stored, else PNG); right-click ▸ Copy Image copies its pixels at full resolution. Missing: inline images (BI/ID/EI), JPEG 2000 images and JBIG2 inside other filters, multi-format clipboard (file and bitmap at once), the web build"[[feature]]id = "view.rulers"@@@@@@@@ -2530,9 -2530,9 -2530,9 -2530,9 -2530,9 -2530,9 -2530,9 +2530,9 @@@@@@@@ tier = "P0milestone = "M7"status = "shipped"commands = ["edit.background"]------tools = ["doc_background"]-- ---evidence = ["crates/ui-egui/tests/it/marks.rs::watermark_and_background_dialogs", "crates/engine/src/tests.rs::headers_footers_watermarks_and_backgrounds_show_update_and_remove", "crates/engine/src/tests.rs::backgrounds_and_watermarks_from_files", "crates/ui-egui/tests/it/marks.rs::backgrounds_and_watermarks_from_a_file", "crates/organize/src/tests.rs::a_page_becomes_a_form_xobject_upright", "crates/ui-egui/tests/it/marks.rs::the_preview_shows_the_page_the_range_selects_under_the_marks", "crates/ui-egui/tests/it/marks.rs::update_previews_the_page_without_the_marks_it_replaces", "crates/engine/src/tests.rs::update_previews_on_the_page_without_the_marks_it_replaces"]-- ---notes = "colour, or a picture from a file (an image or a page of a PDF) scaled relative to the page; the dialog previews a colour as a tint of the page's own thumbnail (opaque pictures on the page are tinted there too, not in the result), a file as its frame and name; Update previews on the page without the backgrounds it replaces, not tinting the old one"- evidence = ["crates/ui-egui/tests/it/marks.rs::watermark_and_background_dialogs", "crates/engine/src/tests.rs::headers_footers_watermarks_and_backgrounds_show_update_and_remove", "crates/engine/src/tests.rs::backgrounds_and_watermarks_from_files", "crates/ui-egui/tests/it/marks.rs::backgrounds_and_watermarks_from_a_file", "crates/organize/src/tests.rs::a_page_becomes_a_form_xobject_upright", "crates/ui-egui/tests/it/marks.rs::the_preview_shows_the_page_the_range_selects_under_the_marks"]- notes = "colour, or a picture from a file (an image or a page of a PDF) scaled relative to the page; the dialog previews a colour as a tint of the page's own thumbnail (opaque pictures on the page are tinted there too, not in the result), a file as its frame and name"++++++tools = ["doc_background", "doc_backdrops"]++++++evidence = ["crates/ui-egui/tests/it/marks.rs::watermark_and_background_dialogs", "crates/engine/src/tests.rs::headers_footers_watermarks_and_backgrounds_show_update_and_remove", "crates/engine/src/tests.rs::backgrounds_and_watermarks_from_files", "crates/ui-egui/tests/it/marks.rs::backgrounds_and_watermarks_from_a_file", "crates/organize/src/tests.rs::a_page_becomes_a_form_xobject_upright", "crates/automation/tests/it/backdrop.rs::a_background_shows_on_a_page_that_paints_its_own_white_backdrop", "crates/ui-egui/tests/it/marks.rs::the_background_dialog_offers_to_replace_a_white_backdrop_and_warns_about_scans", "crates/ui-egui/tests/it/marks.rs::the_background_preview_follows_the_replace_checkbox", "crates/edit/src/backdrop_tests.rs::content_that_is_not_a_page_backdrop_is_left_alone", "crates/ui-egui/tests/it/marks.rs::the_preview_shows_the_page_the_range_selects_under_the_marks", "crates/ui-egui/tests/it/marks.rs::update_previews_the_page_without_the_marks_it_replaces", "crates/engine/src/tests.rs::update_previews_on_the_page_without_the_marks_it_replaces"]++++++notes = "colour, or a picture from a file (an image or a page of a PDF) scaled relative to the page. A page that paints its own opaque white backdrop (browsers' Save as PDF, print drivers) used to hide the background entirely; the dialog now offers to replace that fill (on by default; Remove turns it back on, after edits and redactions too, unless the operators before it changed or it would no longer be painted first, and then says which pages keep it off). The replaced copy's tag holds no page content or reference, so text a redaction or Remove Hidden Information takes off such a page leaves the file. Our own choice: Acrobat's behaviour on such pages has not been observed. Still hidden: scanned pages (warned), backdrops drawn inside a form XObject, by a non-rectangular path, or in a named colour space, and white fills drawn translucent, through a soft mask, a non-Normal blend mode or a transfer function (TR/TR2) as the graphics state stands after every gs, which are real content and stay. The dialog previews a colour as a tint of the page's own thumbnail (opaque pictures on the page are tinted there too, not in the result), a file as its frame and name; a page that will still hide the background (a scan, or a white backdrop with Replace unticked) previews without the colour; Update previews on the page without the backgrounds it replaces, not tinting the old one"[[feature]]id = "edit.background-update-remove"@@@@@@@@ -7188,8 -7164,8 -7164,8 -7152,8 -7164,8 -7164,8 -7164,8 +7188,8 @@@@@@@@ milestone = "M10status = "shipped"commands = ["export.all_images"]tools = ["doc_export_all_images"]- evidence = ["crates/create/src/tests.rs::ccitt_fax_images_export_as_their_picture", "crates/create/src/tests.rs::group_3_ccitt_masks_and_parameters_by_reference_export_as_their_picture", "crates/create/src/tests.rs::images_export_as_jpeg_unchanged_and_others_as_png", "crates/create/src/tests.rs::indexed_and_one_bit_images_decode", "crates/create/src/tests.rs::jpeg_images_with_a_soft_mask_export_as_png_with_alpha", "crates/create/src/tests.rs::soft_masks_of_another_size_and_stencil_and_colour_key_masks_become_alpha", "crates/create/src/tests.rs::soft_mask_decode_ranges_become_exported_alpha", "crates/create/src/tests.rs::soft_mask_decode_maps_packed_and_jpeg_masks_before_resizing", "crates/automation/tests/it/automation.rs::exporting_all_images_through_tools", "crates/ui-egui/tests/it/export.rs::export_dialogs_write_images_and_text", "crates/create/src/tests.rs::lossless_decode_maps_each_component_before_colour_conversion", "crates/create/src/tests.rs::lossless_indexed_decode_rounds_in_index_units_then_clamps"]---- evidence = ["crates/create/src/tests.rs::images_export_as_jpeg_unchanged_and_others_as_png", "crates/create/src/tests.rs::indexed_and_one_bit_images_decode", "crates/create/src/tests.rs::jpeg_images_with_a_soft_mask_export_as_png_with_alpha", "crates/create/src/tests.rs::soft_masks_of_another_size_and_stencil_and_colour_key_masks_become_alpha", "crates/create/src/tests.rs::soft_mask_decode_ranges_become_exported_alpha", "crates/create/src/tests.rs::soft_mask_decode_maps_packed_and_jpeg_masks_before_resizing", "crates/automation/tests/it/automation.rs::exporting_all_images_through_tools", "crates/ui-egui/tests/it/export.rs::export_dialogs_write_images_and_text", "crates/create/src/tests.rs::lossless_decode_maps_each_component_before_colour_conversion", "crates/create/src/tests.rs::lossless_indexed_decode_rounds_in_index_units_then_clamps"]---- notes = "each image once (page resources and nested forms); JPEG unchanged unless it has transparency, others PNG (gray/RGB/CMYK/ICC/Indexed, 1–16 bpc, stencil masks); transparency as PNG alpha: /SMask (scaled to the image size, /Matte un-blended), stencil /Mask and colour-key /Mask, JPEG images included (#645); JPX/JBIG2/CCITT masks are left out (image exported opaque); JPX/JBIG2/CCITT/separations reported as skipped; minimum size filter. Lossless images apply per-component Decode; Indexed values round and clip before palette lookup. Missing, null or malformed Decode arrays keep the default mapping. Soft-mask Decode intervals preserve opacity before resizing, including indirect arrays and endpoints. Still limited: 16-bit samples use high bytes; general JPEG image Decode, ICC transforms, and calibrated colors remain unsupported."- evidence = ["crates/create/src/tests.rs::images_export_as_jpeg_unchanged_and_others_as_png", "crates/create/src/tests.rs::indexed_and_one_bit_images_decode", "crates/create/src/tests.rs::jpeg_images_with_a_soft_mask_export_as_png_with_alpha", "crates/create/src/tests.rs::soft_masks_of_another_size_and_stencil_and_colour_key_masks_become_alpha", "crates/create/src/tests.rs::soft_mask_decode_ranges_become_exported_alpha", "crates/create/src/tests.rs::soft_mask_decode_maps_packed_and_jpeg_masks_before_resizing", "crates/automation/tests/it/automation.rs::exporting_all_images_through_tools", "crates/ui-egui/tests/it/export.rs::export_dialogs_write_images_and_text", "crates/create/src/tests.rs::lossless_decode_maps_each_component_before_colour_conversion", "crates/create/src/tests.rs::lossless_indexed_decode_rounds_in_index_units_then_clamps", "crates/create/src/tests.rs::jbig2_images_export_as_their_picture", "crates/create/src/tests.rs::jbig2_globals_are_decoded_within_a_limit_of_their_own", "crates/automation/tests/it/automation.rs::doc_optimize_stores_black_and_white_images_as_jbig2"]-evidence = ["crates/create/src/tests.rs::images_export_as_jpeg_unchanged_and_others_as_png", "crates/create/src/tests.rs::indexed_and_one_bit_images_decode", "crates/create/src/tests.rs::jpeg_images_with_a_soft_mask_export_as_png_with_alpha", "crates/create/src/tests.rs::soft_masks_of_another_size_and_stencil_and_colour_key_masks_become_alpha", "crates/create/src/tests.rs::soft_mask_decode_ranges_become_exported_alpha", "crates/create/src/tests.rs::soft_mask_decode_maps_packed_and_jpeg_masks_before_resizing", "crates/automation/tests/it/automation.rs::exporting_all_images_through_tools", "crates/ui-egui/tests/it/export.rs::export_dialogs_write_images_and_text", "crates/create/src/tests.rs::lossless_decode_maps_each_component_before_colour_conversion", "crates/create/src/tests.rs::lossless_indexed_decode_rounds_in_index_units_then_clamps", "crates/create/src/tests.rs::jbig2_images_export_as_their_picture", "crates/create/src/tests.rs::jbig2_globals_are_decoded_within_a_limit_of_their_own", "crates/create/src/tests.rs::symbol_coded_jbig2_images_export_as_their_picture", "crates/automation/tests/it/automation.rs::doc_optimize_stores_black_and_white_images_as_jbig2"]--notes = "each image once (page resources and nested forms); JPEG unchanged unless it has transparency, others PNG (gray/RGB/CMYK/ICC/Indexed, 1–16 bpc, stencil masks); transparency as PNG alpha: /SMask (scaled to the image size, /Matte un-blended), stencil /Mask and colour-key /Mask, JPEG images included (#645); JBIG2 images and masks decode (JBIG2 as the only filter, with /JBIG2Globals; an image whose JBIG2 page has another width, or more pixels than an export takes, or whose globals decode to more than 32 MiB, is skipped, and such a mask is left out, the image exported opaque); JPX/CCITT masks are left out (image exported opaque); JPX/CCITT/separations, and JBIG2 inside other filters, reported as skipped; minimum size filter. Lossless images apply per-component Decode; Indexed values round and clip before palette lookup. Missing, null or malformed Decode arrays keep the default mapping. Soft-mask Decode intervals preserve opacity before resizing, including indirect arrays and endpoints. Still limited: 16-bit samples use high bytes; general JPEG image Decode, ICC transforms, and calibrated colors remain unsupported."+++++++evidence = ["crates/create/src/tests.rs::ccitt_fax_images_export_as_their_picture", "crates/create/src/tests.rs::group_3_ccitt_masks_and_parameters_by_reference_export_as_their_picture", "crates/create/src/tests.rs::images_export_as_jpeg_unchanged_and_others_as_png", "crates/create/src/tests.rs::indexed_and_one_bit_images_decode", "crates/create/src/tests.rs::jpeg_images_with_a_soft_mask_export_as_png_with_alpha", "crates/create/src/tests.rs::soft_masks_of_another_size_and_stencil_and_colour_key_masks_become_alpha", "crates/create/src/tests.rs::soft_mask_decode_ranges_become_exported_alpha", "crates/create/src/tests.rs::soft_mask_decode_maps_packed_and_jpeg_masks_before_resizing", "crates/automation/tests/it/automation.rs::exporting_all_images_through_tools", "crates/ui-egui/tests/it/export.rs::export_dialogs_write_images_and_text", "crates/create/src/tests.rs::lossless_decode_maps_each_component_before_colour_conversion", "crates/create/src/tests.rs::lossless_indexed_decode_rounds_in_index_units_then_clamps", "crates/create/src/tests.rs::jbig2_images_export_as_their_picture", "crates/create/src/tests.rs::jbig2_globals_are_decoded_within_a_limit_of_their_own", "crates/automation/tests/it/automation.rs::doc_optimize_stores_black_and_white_images_as_jbig2", "crates/create/src/tests.rs::symbol_coded_jbig2_images_export_as_their_picture"]++++++notes = "each image once (page resources and nested forms); JPEG unchanged unless it has transparency, others PNG (gray/RGB/CMYK/ICC/Indexed, 1–16 bpc, stencil masks); transparency as PNG alpha: /SMask (scaled to the image size, /Matte un-blended), stencil /Mask and colour-key /Mask, JPEG images included (#645); JPX/JBIG2 masks are left out (image exported opaque); JPX/JBIG2/separations reported as skipped; minimum size filter. Lossless images apply per-component Decode; Indexed values round and clip before palette lookup. Missing, null or malformed Decode arrays keep the default mapping. Soft-mask Decode intervals preserve opacity before resizing, including indirect arrays and endpoints. Still limited: 16-bit samples use high bytes; general JPEG image Decode, ICC transforms, and calibrated colors remain unsupported. CCITT fax images (Group 3 and 4, with their /DecodeParms, behind other filters too) export as their picture, masks included; byte-aligned Group 3 is read by the end-of-line codes when the data starts with one and on bytes otherwise, and one cut short is reported. Still limited: byte-aligned Group 3 with codes but none before the first row (not as T.4 sends them) is reported, or at /K 0 may export wrong."[[feature]]id = "create.export-html"@@@@@@@@ -7349,7 -7325,7 -7325,7 -7313,7 -7325,7 -7325,7 -7325,7 +7349,7 @@@@@@@@ status = "shippedcommands = ["optimize.reduce"]tools = ["doc_reduce"]evidence = ["crates/ui-egui/tests/it/create.rs::reduce_file_size_writes_a_compact_copy", "crates/ui-egui/tests/it/create.rs::reduce_file_size_saves_nothing_when_the_file_is_already_small", "crates/engine/src/tests.rs::create_and_reduce", "crates/automation/tests/it/automation.rs::creating_and_reducing_through_tools", "crates/automation/tests/it/automation.rs::optimizing_through_tools", "crates/optimize/tests/optimize.rs::an_identity_decode_array_does_not_stop_reduce"]---- notes = "images above 225 ppi to 150 ppi JPEG medium (after merging page pictures printed as one-pixel strips into one image), thumbnails dropped, resources merged, object streams; scanner images with the default decode array are included; a copy that isn't smaller is not saved (\"already as small as it can be made\"); runs in the background with a progress bar and Cancel"--notes = "images above 225 ppi to 150 ppi JPEG medium (after merging page pictures printed as one-pixel strips into one image), black-and-white images to CCITT Group 4 when that is smaller, thumbnails dropped, resources merged, object streams; scanner images with the default decode array are included; a copy that isn't smaller is not saved (\"already as small as it can be made\"); runs in the background with a progress bar and Cancel"++++++notes = "images above 225 ppi to 150 ppi JPEG medium (after merging page pictures printed as one-pixel strips into one image), black-and-white images averaged down to 300 ppi above 450 ppi, and stored as CCITT Group 4 whenever that is smaller, thumbnails dropped, resources merged, object streams; scanner images with the default decode array are included; a copy that isn't smaller is not saved (\"already as small as it can be made\"); runs in the background with a progress bar and Cancel"[[feature]]id = "optimize.compatibility-level"@@@@@@@@ -7405,11 -7381,11 -7381,11 -7369,11 -7381,11 -7381,11 -7381,11 +7405,11 @@@@@@@@ title = "Monochrome compression (JBIG2area = "K"tier = "P1"milestone = "M11"---- status = "planned"---- commands = []---- tools = []---- evidence = []---- notes = ""++++ status = "partial"++++ commands = ["optimize.advanced", "optimize.reduce"]++++ tools = ["doc_optimize", "doc_reduce"]- evidence = ["crates/optimize/tests/optimize.rs::eight_bit_black_and_white_images_become_one_bit", "crates/filters/src/ccitt.rs::bitmaps_round_trip", "crates/filters/src/ccitt.rs::a_page_of_text_like_marks_round_trips_and_shrinks", "crates/filters/src/ccitt.rs::what_it_cannot_encode_is_an_error", "crates/optimize/tests/optimize.rs::black_and_white_images_become_ccitt_group_4", "crates/optimize/tests/optimize.rs::group_3_fax_images_become_group_4", "crates/optimize/tests/optimize.rs::rgb_and_two_colour_indexed_black_and_white_images_become_one_bit", "crates/optimize/tests/optimize.rs::black_and_white_rgb_used_beyond_the_page_content_read_stays_rgb", "crates/optimize/tests/optimize.rs::black_and_white_rgb_drawn_only_where_the_optimizer_reads_becomes_grey", "crates/optimize/tests/optimize.rs::black_and_white_rgb_in_resources_its_page_tree_and_a_form_share_becomes_grey", "crates/automation/tests/it/automation.rs::doc_optimize_stores_black_and_white_images_as_ccitt_group_4", "crates/ui-egui/tests/it/create.rs::the_pdf_optimizer_dialog_saves_an_optimized_copy"]- notes = "CCITT Group 4, lossless: PDF Optimizer ▸ Images ▸ Monochrome Images (on by default, so Reduce File Size does it too; doc_optimize mono) stores a 1-bit image of one colour component (grey, indexed, a separation) or an image mask, kept with no filter or general-purpose ones, as Group 4 when that is smaller as stored; the samples decode to the same bits, so colour space, decode array and masks stay. Packed to one bit first, then stored the same way (colour-key masks aside): eight-bit grey of only black and white, eight-bit DeviceRGB of only black and white (as DeviceGray; calibrated RGB, RGB with a profile, RGB drawn or listed where /DefaultGray or /DefaultRGB is in force or referred to from anywhere but the page and form resources read (an annotation's appearance or a pattern drawing it, directly or through resources or a form shared with a page; another image's /Alternates), and RGB whose soft mask has a /Matte aside), and an indexed image of 2, 4 or 8 bits that uses only palette entries 0 and 1 (keeping its palette), unless the grey or colour settings make it smaller still, as they can a dithered scan downsampled to JPEG, its soft mask counted. Group 4 wins on scans; on clean computer-drawn 1-bit art Flate can be smaller, and the image then stays. Group 3 fax images are stored again as Group 4 when that is smaller (damaged Group 3 with end-of-line codes as the decoder recovers it, as it reports no damage there; byte-aligned Group 3 with end-of-line codes but none before the first row, not as T.4 sends them, as PdfCraft draws it, which at /K 0 may be other rows than were coded). CCITT fax images are decoded to be downsampled (optimize.downsample-images), and a resampled image is stored as Group 4 or 1-bit Flate, whichever is smaller. Not yet: JBIG2 (lossless or lossy, which Adobe's help says beats CCITT for monochrome), inline images, soft masks and /Mask images, Group 4 for rows wider than 32,767 samples."- evidence = ["crates/filters/src/ccitt.rs::bitmaps_round_trip", "crates/filters/src/ccitt.rs::a_page_of_text_like_marks_round_trips_and_shrinks", "crates/filters/src/ccitt.rs::what_it_cannot_encode_is_an_error", "crates/filters/src/mq.rs::the_annex_h_test_sequence_encodes_to_its_bytes", "crates/filters/src/jbig2.rs::bitmaps_round_trip", "crates/filters/src/jbig2.rs::a_page_of_text_like_marks_round_trips_and_shrinks", "crates/optimize/tests/optimize.rs::black_and_white_images_become_jbig2", "crates/automation/tests/it/automation.rs::doc_optimize_stores_black_and_white_images_as_jbig2", "crates/optimize/tests/optimize.rs::black_and_white_images_become_ccitt_group_4", "crates/automation/tests/it/automation.rs::doc_optimize_stores_black_and_white_images_as_ccitt_group_4", "crates/ui-egui/tests/it/create.rs::the_pdf_optimizer_dialog_saves_an_optimized_copy"]- notes = "CCITT Group 4 (the default, so Reduce File Size does it too) or JBIG2, both lossless: PDF Optimizer ▸ Images ▸ Monochrome Images (doc_optimize mono) stores a 1-bit image of one colour component (grey, indexed, a separation) or an image mask, kept with no filter or general-purpose ones, as Group 4 when that is smaller as stored; the samples decode to the same bits, so colour space, decode array and masks stay. Group 4 wins on scans; on clean computer-drawn 1-bit art Flate can be smaller, and the image then stays. JBIG2 is a generic region (template 0, typical prediction), about a third smaller than Group 4 on 300 dpi text; a document below PDF 1.4 gets /Version 1.4. Not yet: JBIG2 symbol coding (text regions with symbol dictionaries, where JBIG2's larger gains on text come from, and its lossy mode), JBIG2Globals, monochrome downsampling, inline images, soft masks and /Mask images, Group 4 for rows wider than 32,767 samples (JBIG2 takes rows of up to 1,048,576). Redaction doesn't decode JBIG2 or Group 4 yet: a mark over part of such an image removes the whole image (nothing leaks). Export reads JBIG2, but nothing that exports an image reads Group 4 yet: Export ▸ Images and Save Image As refuse it, Copy Image fails, and Word, PowerPoint and HTML export leave the picture out."-evidence = ["crates/filters/src/ccitt.rs::bitmaps_round_trip", "crates/filters/src/ccitt.rs::a_page_of_text_like_marks_round_trips_and_shrinks", "crates/filters/src/ccitt.rs::what_it_cannot_encode_is_an_error", "crates/filters/src/mq.rs::the_annex_h_test_sequence_encodes_to_its_bytes", "crates/filters/src/jbig2.rs::bitmaps_round_trip", "crates/filters/src/jbig2.rs::a_page_of_text_like_marks_round_trips_and_shrinks", "crates/filters/src/jbig2/symbols.rs::repeated_marks_are_stored_once", "crates/filters/src/jbig2/symbols.rs::scattered_marks_round_trip", "crates/optimize/tests/optimize.rs::black_and_white_images_become_jbig2", "crates/optimize/tests/optimize.rs::rendered_text_becomes_jbig2_symbols", "crates/automation/tests/it/automation.rs::doc_optimize_stores_black_and_white_images_as_jbig2", "crates/optimize/tests/optimize.rs::black_and_white_images_become_ccitt_group_4", "crates/automation/tests/it/automation.rs::doc_optimize_stores_black_and_white_images_as_ccitt_group_4", "crates/ui-egui/tests/it/create.rs::the_pdf_optimizer_dialog_saves_an_optimized_copy"]-notes = "CCITT Group 4 (the default, so Reduce File Size does it too) or JBIG2, both lossless: PDF Optimizer ▸ Images ▸ Monochrome Images (doc_optimize mono) stores a 1-bit image of one colour component (grey, indexed, a separation) or an image mask, kept with no filter or general-purpose ones, as Group 4 when that is smaller as stored; the samples decode to the same bits, so colour space, decode array and masks stay. Group 4 wins on scans; on clean computer-drawn 1-bit art Flate can be smaller, and the image then stays. JBIG2 stores each distinct mark once in a symbol dictionary and places its exact copies with text regions (at most 10,000 copies each), larger and lone marks in a generic region (template 0, typical prediction), or the whole image as a generic region, whichever is smaller: on rendered 300 dpi text 28% of the generic region's size and 17% of Group 4's; on scans, whose copies of a letter are seldom identical, little: on the same pages with 2% or more of the letters' edge pixels flipped at random, at most 8% below the generic region in total (20% on one page), and the generic region was 27–33% below Group 4. A document below PDF 1.4 gets /Version 1.4. Not yet: JBIG2 refinement coding of near-copies (where lossless gains on scans would come from), a symbol dictionary shared between images (/JBIG2Globals), JBIG2's lossy mode, monochrome downsampling, inline images, soft masks and /Mask images, Group 4 for rows wider than 32,767 samples (JBIG2 takes rows of up to 1,048,576). Redaction doesn't decode JBIG2 or Group 4 yet: a mark over part of such an image removes the whole image (nothing leaks). Export reads JBIG2, but nothing that exports an image reads Group 4 yet: Export ▸ Images and Save Image As refuse it, Copy Image fails, and Word, PowerPoint and HTML export leave the picture out."+++++++evidence = ["crates/optimize/tests/optimize.rs::eight_bit_black_and_white_images_become_one_bit", "crates/filters/src/ccitt.rs::bitmaps_round_trip", "crates/filters/src/ccitt.rs::a_page_of_text_like_marks_round_trips_and_shrinks", "crates/filters/src/ccitt.rs::what_it_cannot_encode_is_an_error", "crates/optimize/tests/optimize.rs::black_and_white_images_become_ccitt_group_4", "crates/optimize/tests/optimize.rs::group_3_fax_images_become_group_4", "crates/optimize/tests/optimize.rs::rgb_and_two_colour_indexed_black_and_white_images_become_one_bit", "crates/optimize/tests/optimize.rs::black_and_white_rgb_used_beyond_the_page_content_read_stays_rgb", "crates/optimize/tests/optimize.rs::black_and_white_rgb_drawn_only_where_the_optimizer_reads_becomes_grey", "crates/optimize/tests/optimize.rs::black_and_white_rgb_in_resources_its_page_tree_and_a_form_share_becomes_grey", "crates/automation/tests/it/automation.rs::doc_optimize_stores_black_and_white_images_as_ccitt_group_4", "crates/ui-egui/tests/it/create.rs::the_pdf_optimizer_dialog_saves_an_optimized_copy", "crates/filters/src/mq.rs::the_annex_h_test_sequence_encodes_to_its_bytes", "crates/filters/src/jbig2.rs::bitmaps_round_trip", "crates/filters/src/jbig2.rs::a_page_of_text_like_marks_round_trips_and_shrinks", "crates/optimize/tests/optimize.rs::black_and_white_images_become_jbig2", "crates/automation/tests/it/automation.rs::doc_optimize_stores_black_and_white_images_as_jbig2", "crates/filters/src/jbig2/symbols.rs::repeated_marks_are_stored_once", "crates/filters/src/jbig2/symbols.rs::scattered_marks_round_trip", "crates/optimize/tests/optimize.rs::rendered_text_becomes_jbig2_symbols"]+++++++notes = "CCITT Group 4, lossless: PDF Optimizer ▸ Images ▸ Monochrome Images (on by default, so Reduce File Size does it too; doc_optimize mono) stores a 1-bit image of one colour component (grey, indexed, a separation) or an image mask, kept with no filter or general-purpose ones, as Group 4 when that is smaller as stored; the samples decode to the same bits, so colour space, decode array and masks stay. Packed to one bit first, then stored the same way (colour-key masks aside): eight-bit grey of only black and white, eight-bit DeviceRGB of only black and white (as DeviceGray; calibrated RGB, RGB with a profile, RGB drawn or listed where /DefaultGray or /DefaultRGB is in force or referred to from anywhere but the page and form resources read (an annotation's appearance or a pattern drawing it, directly or through resources or a form shared with a page; another image's /Alternates), and RGB whose soft mask has a /Matte aside), and an indexed image of 2, 4 or 8 bits that uses only palette entries 0 and 1 (keeping its palette), unless the grey or colour settings make it smaller still, as they can a dithered scan downsampled to JPEG, its soft mask counted. Group 4 wins on scans; on clean computer-drawn 1-bit art Flate can be smaller, and the image then stays. Group 3 fax images are stored again as Group 4 when that is smaller (damaged Group 3 with end-of-line codes as the decoder recovers it, as it reports no damage there; byte-aligned Group 3 with end-of-line codes but none before the first row, not as T.4 sends them, as PdfCraft draws it, which at /K 0 may be other rows than were coded). CCITT fax images are decoded to be downsampled (optimize.downsample-images), and a resampled image is stored as Group 4 or 1-bit Flate, whichever is smaller. Lossless JBIG2 with bounded exact-copy symbol coding is available too, with image export; lossy JBIG2 remains unsupported. Not yet: inline images, soft masks and /Mask images, Group 4 for rows wider than 32,767 samples."[[feature]]id = "optimize.only-if-smaller"