diff --git a/ROADMAP.md b/ROADMAP.md index 95a8a1a42f..a1578f2998 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -5,6 +5,8 @@ - 2026-11-04 (M6, PR #5699 reset estimate): Charge expanded-name scans and field-name copy/comparison bytes; add three negative regressions and byte-exact refusal checks. # PdfCraft roadmap +> **Last reviewed:** 2026-11-04 | **Last updated:** 2026-11-04 | **Change:** minor (M7: paragraph boundaries respect row typography and page-wide filled panels; estimates unchanged) + > **Last reviewed:** 2026-11-16 | **Last updated:** 2026-11-16 | **Change:** patch (M5 #3741: Ctrl+M opens Comments on Windows/Linux without toggling it closed; macOS leaves Command+M for Minimize; platform-specific shortcut surfaces and regressions retained; estimates unchanged) > **Last reviewed:** 2026-11-15 | **Last updated:** 2026-11-15 | **Change:** minor (craft-libs cutover for codecs, XFA XML, crypt/filters/COS/export/XFDF, PRC and ZIP; print colour management for pictures; M7 line replacement keeps source fonts; auto-tag headings by size and weight; arrow-key comment moves; stream-filter JPEG export; form, signature, optimize, redaction, measurement, PRC-normal and CMYK fixes; v0.21.1 Flatpak fix; estimates unchanged) @@ -304,6 +306,8 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md - **2026-10-28 (M10, #4119 partial):** Scan & OCR ▸ Enhance scanned file cleans scanned pages in place: background removal (level 0–100, as the camera clean-up), edge shadow removal (book gutters, copier borders) and despeckle. Each scan image is decoded, cleaned and written back into its own object at the same size and colour space (JPEG stays JPEG, others lossless, 1-bit stays 1-bit), so the OCR text layer, comments and links stay; one undo step, shared images once, unsupported images (CMYK, indexed, JPEG 2000, JBIG2, CCITT, broken data) reported. `page_enhance_scan` drives it headlessly. Not yet an option of Recognize text. Estimates unchanged. - **2026-11-07 (M10, `ocr.ocr-web`, port onto #977):** Web OCR rebuilt on main's engines and preprocessing (#977). `OcrJob::run` is now `OcrJob::steps` a page at a time: the page renders, crops to the region and cleans each page, a Web Worker runs ocrs on the result, and `OcrShot::place` maps the words back through the region and preprocessing. Every strategy reads like this when only one engine is present, and the web build has only ocrs. The downloaded models are installed into the engine cache (`ocr::install`), so the Verify screen and the engine-status checks see them too. The batch keeps main's skipped-files bucket, low-confidence notes and cancel. The translations moved to craft-i18n (storytold/craft-i18n#141). The Verify screen starts the model download itself and runs once the models land; before, on a fresh page it failed with the desktop's "set PDFCRAFT_MODELS" message. Known limits: the cleaning steps, and the Verify screen's Run OCR and re-reads, run on the page. Estimates unchanged. +- **2026-11-04 (M7, paragraph boundaries):** Editable paragraphs separate across large row-size changes, font-family changes and filled rectangular panel boundaries, while compatible multiline text and inline style runs stay together. Panel identity is page-wide across content streams and transformed form invocations; rectangle construction/fill splits retain their transforms and path semantics. Synthetic regressions cover isolated-panel edits through save/reopen and preserve the delayed-background rewrite checks for #2377. Estimates unchanged. + - **2026-11-03 (M11, shared JBIG2 dictionary):** With Monochrome Images set to JBIG2, Optimize has up to 16 JBIG2 images share one symbol dictionary (`/JBIG2Globals`), the letters found on more than one page stored once, when that is smaller (`pdfcraft_filters::encode_jbig2_shared`). Eight pages of 10 pt text rendered at 300 dpi take 41% less in Helvetica and 42% in Times than coded alone, 10% in Courier; groups of 16 save 45%, of 32 only 47%. Only images redaction can store again without the dictionary share one (image masks and DeviceGray named directly, at most 64 Mi pixels), and redacting one stores the rest of its group so, which the group bounds to 15. - **2026-11-03 (M5, #5850 review):** Resolve indirect IT when recognizing typewriter contents and Fill & Sign marks. Comment listing and property lookup retain their existing direct-Subtype behavior. A real double-click Edit composer preserves the typewriter’s text as written; ordinary comment edits keep trimming. Regressions cover direct Subtype with indirect intent, save/reopen, raw posted contents and same-index comments on different pages. The existing live-movement test now commits its setup with an outside click rather than Enter. Estimates unchanged. diff --git a/clippy.toml b/clippy.toml index 31e54da30f..16518d262e 100644 --- a/clippy.toml +++ b/clippy.toml @@ -12,9 +12,41 @@ disallowed-methods = [ { path = "egui::Ui::radio", reason = "use radio from crates/ui-egui/src/widgets.rs, which is outlined and filled" }, { path = "egui::Ui::radio_value", reason = "use radio_value from crates/ui-egui/src/widgets.rs, which is outlined and filled" }, { path = "egui::RadioButton::new", reason = "use radio from crates/ui-egui/src/widgets.rs, which is outlined and filled" }, + # The raw RSA private-key operations: see disallowed-types below. + { path = "rsa::hazmat::rsa_decrypt", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" }, + { path = "rsa::hazmat::rsa_decrypt_and_check", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" }, + # The ways to make or use an `rsa` private key, so a key whose type is never named (one + # returned by another crate, or a generic over these traits) is caught too. The generic + # `signature` and `pkcs8` traits are left out: the ECDSA keys use them as well. + { path = "rsa::RsaPrivateKey::new", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" }, + { path = "rsa::RsaPrivateKey::new_unchecked", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" }, + { path = "rsa::RsaPrivateKey::new_with_exp", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" }, + { path = "rsa::RsaPrivateKey::new_with_exp_unchecked", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" }, + { path = "rsa::RsaPrivateKey::from_components", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" }, + { path = "rsa::RsaPrivateKey::from_components_with_large_exponent", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" }, + { path = "rsa::RsaPrivateKey::from_p_q", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" }, + { path = "rsa::RsaPrivateKey::from_primes", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" }, + { path = "rsa::RsaPrivateKey::decrypt", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" }, + { path = "rsa::RsaPrivateKey::decrypt_blinded", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" }, + { path = "rsa::RsaPrivateKey::sign", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" }, + { path = "rsa::RsaPrivateKey::sign_with_rng", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" }, + { path = "rsa::traits::Decryptor::decrypt", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" }, + { path = "rsa::traits::RandomizedDecryptor::decrypt_with_rng", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" }, + { path = "rsa::traits::PaddingScheme::decrypt", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" }, + { path = "rsa::traits::SignatureScheme::sign", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" }, ] -cognitive-complexity-threshold = 30 +# deny.toml ignores the Marvin advisory (RUSTSEC-2023-0071) because `rsa` is only used to verify +# signatures; RSA private-key operations use aws-lc-rs (ADR-0009). These are the `rsa` types +# that hold a private key, and above are the functions and methods that make or use one, so a +# private-key operation through `rsa` fails clippy instead. disallowed-types = [ + { path = "rsa::RsaPrivateKey", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" }, + { path = "rsa::pkcs1v15::SigningKey", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" }, + { path = "rsa::pkcs1v15::DecryptingKey", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" }, + { path = "rsa::pss::SigningKey", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" }, + { path = "rsa::pss::BlindedSigningKey", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" }, + { path = "rsa::oaep::DecryptingKey", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" }, { path = "egui::ComboBox", reason = "use craft_ui::ComboBox: egui's combo box menu can't grow back while open (egui#5225)" }, ] +cognitive-complexity-threshold = 30 diff --git a/contributors/people.toml b/contributors/people.toml index fb2c1f2931..bc38c2967c 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -198,5 +198,10 @@ sync_github_name = true [people.Yousef-Dev921] sync_github_name = true +[people.marcoarnulfo] +real_name = "Marco Arnulfo" +display_name = "Marco Arnulfo" +sync_github_name = false + [people.gmrmad1] real_name = "Madhav Agarwal" diff --git a/crates/automation/src/comments.rs b/crates/automation/src/comments.rs index 88541466e1..4e7d2c491a 100644 --- a/crates/automation/src/comments.rs +++ b/crates/automation/src/comments.rs @@ -470,7 +470,10 @@ impl Automation { } style.fill = a.color("fill")?; if let Some(o) = a.opt_num("opacity")? { - style.opacity = o.clamp(0.0, 1.0); + if !(0.0..=1.0).contains(&o) { + return Err(ToolError::InvalidArgs(format!("opacity must be between 0 and 1, got {o}"))); + } + style.opacity = o; } // The fill's and a text box's text's own opacities (the line keeps `opacity`). let (fill_opacity, text_opacity) = (a.opt_num("fill_opacity")?, a.opt_num("text_opacity")?); @@ -758,6 +761,9 @@ impl Automation { edits.push(Edit::SetAnnotationContents { page, index, text: text.to_string() }); } let (color, opacity, width) = (a.color("color")?, a.opt_num("opacity")?, a.opt_num("width")?); + if let Some(o) = opacity.filter(|&o| !(0.0..=1.0).contains(&o)) { + return Err(ToolError::InvalidArgs(format!("opacity must be between 0 and 1, got {o}"))); + } if color.is_some() || opacity.is_some() || width.is_some() { edits.push(Edit::StyleAnnotation { page, index, color, opacity, width, endings: None }); } diff --git a/crates/automation/src/documents.rs b/crates/automation/src/documents.rs index 47ffb8583f..8bfdac1c87 100644 --- a/crates/automation/src/documents.rs +++ b/crates/automation/src/documents.rs @@ -116,6 +116,7 @@ impl Automation { let bytes = read_input(&path)?; let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); let id = self.session.open(name, Some(path.to_string_lossy().into_owned()), Arc::new(bytes), a.opt_str("password")?).map_err(failed)?; + let errors = self.session.take_js_errors(id); let doc = self.session.get(id).ok_or_else(|| failed("the document vanished"))?; let mut value = summary(doc); if let Some(destination) = destination { @@ -124,6 +125,10 @@ impl Automation { value["destination"] = destination; value["warning"] = json!(warning); } + // warnings lists the errors of the form's scripts that ran on open, including the messages that the scripts were stopped or turned off. + if !errors.is_empty() { + value["warnings"] = json!(errors); + } Ok(value) } @@ -577,11 +582,16 @@ impl Automation { /// The document's summary after an edit, with what it stored as typed but drew with `?`. fn applied(&mut self, a: &Args) -> Result { + let id = self.doc(a)?.id; + let errors = self.session.take_js_errors(id); let doc = self.doc(a)?; let mut out = summary(doc); // Text the edit stored as typed but drew with `?` (its font can't draw it): said, not silent. - if !doc.edit_notices.is_empty() { - out["warnings"] = json!(doc.edit_notices.iter().map(ToString::to_string).collect::>()); + let mut warnings: Vec = doc.edit_notices.iter().map(ToString::to_string).collect(); + // The errors of the scripts the edit ran follow the notices, including the messages that a form's scripts were stopped or turned off. + warnings.extend(errors); + if !warnings.is_empty() { + out["warnings"] = json!(warnings); } Ok(out) } @@ -659,7 +669,13 @@ impl Automation { scale: a.opt_num("scale")?.unwrap_or(d.scale).clamp(0.01, 1.0), font_size: a.opt_num("font_size")?.unwrap_or(0.0), color: color("color", d.color)?, - opacity: a.opt_num("opacity")?.unwrap_or(d.opacity), + opacity: match a.opt_num("opacity")? { + Some(o) if !(0.0..=1.0).contains(&o) => { + return Err(ToolError::InvalidArgs(format!("opacity must be between 0 and 1, got {o}"))); + } + Some(o) => o, + None => d.opacity, + }, rotation: a.opt_num("rotation")?.unwrap_or(d.rotation), behind: a.opt_bool("behind")?.unwrap_or(false), offset: [ @@ -673,7 +689,13 @@ impl Automation { pages, settings: Background { color: color("color", [1.0; 3])?, - opacity: a.opt_num("opacity")?.unwrap_or(1.0), + opacity: match a.opt_num("opacity")? { + Some(o) if !(0.0..=1.0).contains(&o) => { + return Err(ToolError::InvalidArgs(format!("opacity must be between 0 and 1, got {o}"))); + } + Some(o) => o, + None => 1.0, + }, scale: a.opt_num("scale")?.unwrap_or(1.0).clamp(0.01, 1.0), replace_backdrop: a.opt_bool("replace_backdrop")?.unwrap_or(true), ..Background::default() diff --git a/crates/automation/src/tools.rs b/crates/automation/src/tools.rs index 992d24c8cc..b148baec04 100644 --- a/crates/automation/src/tools.rs +++ b/crates/automation/src/tools.rs @@ -183,7 +183,7 @@ pub fn tools() -> Vec { )), t("attachment_edit", "Edit an attachment description", "Change the description of a document attachment by its exact key from doc_info, or by a unique displayed name. An empty description clears it. The file and other attachment data are preserved. Undoable.") .with(schema(json!({"doc": doc(), "key": {"type": "string"}, "name": {"type": "string"}, "description": {"type": "string"}}), &["doc", "description"])), - t("doc_open", "Open a PDF", "Open a PDF file and return its document id, page count and whether it can be edited. A path that ends in open parameters, as help systems pass them (`manual.pdf#page=12`, `#nameddest=Intro` or `#Intro`), opens the file and reports its destination as link_open does; a path that names a file opens as it is.") + t("doc_open", "Open a PDF", "Open a PDF file and return its document id, page count and whether it can be edited. A path that ends in open parameters, as help systems pass them (`manual.pdf#page=12`, `#nameddest=Intro` or `#Intro`), opens the file and reports its destination as link_open does; a path that names a file opens as it is. `warnings` lists the errors of the form's scripts on open, including the messages that they were stopped or turned off.") .cmd("file.open") .with(schema(json!({ "path": { "type": "string" }, "password": { "type": "string", "description": "User or owner password for encrypted files." } }), &["path"])), t("doc_list", "List open documents", "List the open documents with their ids, page counts and unsaved state.").ro().with(schema(json!({}), &[])), @@ -551,7 +551,7 @@ pub fn tools() -> Vec { t( "form_fill", "Fill in form fields", - "Set several fields at once (one undo step). values maps field names (from form_fields) to: a string for text fields, combo boxes and radio groups (an option), true/false for check boxes (or one of a check box's options, to check that widget and clear the others), an array of strings for multi-select lists; {\"widget\": n} turns on button n (1-based) of a check box or radio group and never turns it off (to clear, use null for a radio group that allows it, false for a check box); of radio buttons sharing an option only that one is on unless the group has RadiosInUnison. A radio option is an export value as form_fields lists it in options; where one button's on-state name equals another button's export value, the export value wins, and an on-state name that no export value matches still selects its button. A radio option may also be a JSON number: a whole number names the option spelled as that integer (1, 1.0 and 1e0 all name \"1\"), any other number only an option spelled exactly as JSON prints it (1.5). A value that names no option is refused with the options listed. Appearances are regenerated so every viewer shows the values. Thai the field's font can't hold is drawn from PdfCraft's built-in Thai face (a build without one refuses it). Any other value whose characters the field's font can't draw (Chinese in a Helvetica field) is still saved; `warnings` in the result names the field and character: PdfCraft draws `?` there and asks other viewers to redraw the field from its value.", + "Set several fields at once (one undo step). values maps field names (from form_fields) to: a string for text fields, combo boxes and radio groups (an option), true/false for check boxes (or one of a check box's options, to check that widget and clear the others), an array of strings for multi-select lists; {\"widget\": n} turns on button n (1-based) of a check box or radio group and never turns it off (to clear, use null for a radio group that allows it, false for a check box); of radio buttons sharing an option only that one is on unless the group has RadiosInUnison. A radio option is an export value as form_fields lists it in options; where one button's on-state name equals another button's export value, the export value wins, and an on-state name that no export value matches still selects its button. A radio option may also be a JSON number: a whole number names the option spelled as that integer (1, 1.0 and 1e0 all name \"1\"), any other number only an option spelled exactly as JSON prints it (1.5). A value that names no option is refused with the options listed. Appearances are regenerated so every viewer shows the values. Thai the field's font can't hold is drawn from PdfCraft's built-in Thai face (a build without one refuses it). Any other value whose characters the field's font can't draw (Chinese in a Helvetica field) is still saved; `warnings` in the result names the field and character: PdfCraft draws `?` there and asks other viewers to redraw the field from its value. `warnings` also lists the errors of the form's scripts that the change ran, including the messages that they were stopped or turned off.", ) .with(schema(json!({ "doc": doc(), "values": { "type": "object", "description": "Field name → value." } }), &["doc", "values"])), t( diff --git a/crates/automation/tests/it/automation.rs b/crates/automation/tests/it/automation.rs index 14b5738113..bccbda1af7 100644 --- a/crates/automation/tests/it/automation.rs +++ b/crates/automation/tests/it/automation.rs @@ -2820,6 +2820,19 @@ fn verify_comment_errors(a: &mut Automation, doc: u64, id: &str) { Err(ToolError::InvalidArgs(_)) )); assert!(matches!(a.call("comment_edit", &json!({ "doc": doc, "page": 1, "index": 1 })), Err(ToolError::InvalidArgs(_)))); + // #2670: opacity must be between 0 and 1. + assert!(matches!( + a.call("comment_add", &json!({ "doc": doc, "page": 1, "type": "note", "at": [1, 1], "opacity": -3 })), + Err(ToolError::InvalidArgs(_)) + )); + assert!(matches!( + a.call("comment_add", &json!({ "doc": doc, "page": 1, "type": "note", "at": [1, 1], "opacity": 1.5 })), + Err(ToolError::InvalidArgs(_)) + )); + let first = ok(a, "comment_list", json!({ "doc": doc }))["comments"][0].clone(); + let (page, index) = (first["page"].as_u64().unwrap(), first["index"].as_u64().unwrap()); + assert!(matches!(a.call("comment_edit", &json!({ "doc": doc, "page": page, "index": index, "opacity": -1 })), Err(ToolError::InvalidArgs(_)))); + assert!(matches!(a.call("comment_edit", &json!({ "doc": doc, "page": page, "index": index, "opacity": 2.0 })), Err(ToolError::InvalidArgs(_)))); } fn save_and_reopen_comments(dir: &Path, a: &mut Automation, doc: u64) { @@ -4088,6 +4101,8 @@ fn watermarks_move_from_the_page_centre_through_tools() { // Huge offsets are clamped, and a value that isn't a number is refused. ok(&mut a, "doc_watermark", json!({ "doc": doc, "pages": [1], "text": "DRAFT", "offset_y": 1e300, "replace": true })); assert!(matches!(a.call("doc_watermark", &json!({ "doc": doc, "text": "X", "offset_x": "left" })), Err(ToolError::InvalidArgs(_)))); + assert!(matches!(a.call("doc_watermark", &json!({ "doc": doc, "text": "X", "opacity": -1 })), Err(ToolError::InvalidArgs(_)))); + assert!(matches!(a.call("doc_background", &json!({ "doc": doc, "color": "yellow", "opacity": -1 })), Err(ToolError::InvalidArgs(_)))); } #[test] @@ -11290,11 +11305,42 @@ fn doc_info_says_when_a_runaway_script_turned_the_forms_scripts_off() { ); std::fs::write(dir.join("runaway.pdf"), pdfcraft_xfa::fixtures::shell(&tpl)).unwrap(); let mut a = auto(&dir); - let doc = ok(&mut a, "doc_open", json!({ "path": "runaway.pdf" }))["doc"].as_u64().unwrap(); + let opened = ok(&mut a, "doc_open", json!({ "path": "runaway.pdf" })); + let doc = opened["doc"].as_u64().unwrap(); + // doc_open's warnings also hold the message that the form's scripts are off. + let warnings = opened["warnings"].as_array().unwrap_or_else(|| panic!("{opened}")); + assert!(warnings.iter().any(|w| w.as_str().is_some_and(|w| w.contains("the form's scripts are off"))), "{opened}"); assert_eq!(ok(&mut a, "doc_info", json!({ "doc": doc }))["xfa_scripts_off"], true); let _ = std::fs::remove_dir_all(dir); } +#[test] +fn doc_open_and_form_fill_report_the_errors_of_the_forms_scripts() { + let dir = workdir("xfa-script-errors"); + // The initialize script fails on open; the total's calculation fails once qty is 4. + let tpl = pdfcraft_xfa::fixtures::scripted_template() + .replace("if (qty.rawValue === null) qty.rawValue = 2;", "qty.rawValue = 2; throw new Error('open failed');") + .replace( + "", + "", + ); + std::fs::write(dir.join("errors.pdf"), pdfcraft_xfa::fixtures::shell(&tpl)).unwrap(); + // Raised time limits: a busy machine does not stop the scripts this checks. + let mut a = auto(&dir).with_xfa_time_scale(100); + let warns = |out: &Value, text: &str| out["warnings"].as_array().is_some_and(|w| w.iter().any(|w| w.as_str().is_some_and(|w| w.contains(text)))); + let opened = ok(&mut a, "doc_open", json!({ "path": "errors.pdf" })); + let doc = opened["doc"].as_u64().unwrap(); + assert!(warns(&opened, "open failed"), "{opened}"); + // A button click after the open returns no error, because doc_open took the open's error. + let r = ok(&mut a, "js_run", json!({ "doc": doc, "script": "", "field": "hello" })); + assert!(r["error"].is_null(), "{r}"); + assert_eq!(r["alerts"], json!([{ "message": "Hello 2", "title": null, "icon": "error", "buttons": "ok" }]), "{r}"); + let filled = ok(&mut a, "form_fill", json!({ "doc": doc, "values": { "qty": "4" } })); + assert!(warns(&filled, "fill failed"), "{filled}"); + assert!(!warns(&filled, "open failed"), "{filled}"); + let _ = std::fs::remove_dir_all(dir); +} + /// doc_info describes a link's set-layer-visibility action by layer name, and each layer's /// visibility now and as the file opens. #[test] diff --git a/crates/edit/src/flatten.rs b/crates/edit/src/flatten.rs index 03ed272f3c..09cc4121a8 100644 --- a/crates/edit/src/flatten.rs +++ b/crates/edit/src/flatten.rs @@ -621,6 +621,22 @@ thread_local! { /// Remove flattened widgets from the AcroForm field tree, and fields left without widgets. With /// `on_page`, also the widgets (fields without kids) that are on no page. +/// Whether the field at `r` is a signature field: its `/FT`, or the nearest one up its `/Parent` +/// chain (field types are inherited). The walk stops after 64 parents, so a cycle ends. +fn is_signature_field(doc: &Document, r: ObjRef) -> bool { + let mut node = r; + for _ in 0..=64 { + let obj = doc.get(node); + let Some(d) = obj.as_dict() else { return false }; + if let Some(ft) = d.get(b"FT").map(|v| doc.resolve(v)).and_then(|v| v.as_name().map(|n| n.to_vec())) { + return ft == b"Sig"; + } + let Some(parent) = d.get(b"Parent").and_then(|p| p.as_ref()) else { return false }; + node = parent; + } + false +} + fn prune_fields(doc: &mut Document, widgets: &HashSet, on_page: Option<&HashSet>) -> Result<(), EditError> { let Some(root) = doc.root() else { return Ok(()) }; let Some(af) = doc.get(root).as_dict().and_then(|d| d.get(b"AcroForm").cloned()) else { return Ok(()) }; @@ -680,10 +696,45 @@ fn prune_fields(doc: &mut Document, widgets: &HashSet, on_page: Option<& let mut known = HashMap::new(); let survivors: Vec = fields.iter().filter(|f| f.as_ref().is_none_or(|r| keep(doc, r, widgets, on_page, &mut known, 0).0)).cloned().collect(); - if survivors.len() == fields.len() && widgets.is_empty() { + // A field taken out of a kept parent's `/Kids` leaves `/Fields` as long as it was, and still + // needs `/CO` and `/SigFlags` cleaned. + let removed_any = known.values().any(|&(survives, _)| !survives); + if survivors.len() == fields.len() && widgets.is_empty() && !removed_any { return Ok(()); // only looked for fields on no page, and there were none } + // Every field left in the tree, however deep: `known` stops at the depth cutoff, so walk the + // kept tree again from `/Fields`, each node once (a cycle ends where it began). + let mut surviving: HashSet = HashSet::new(); + let mut stack: Vec = survivors.iter().filter_map(Object::as_ref).collect(); + while let Some(r) = stack.pop() { + if widgets.contains(&r) || matches!(known.get(&r), Some(&(false, _))) || !surviving.insert(r) { + continue; + } + let Some(d) = doc.get(r).as_dict().cloned() else { continue }; + if let Some(kids) = d.get(b"Kids").map(|k| doc.resolve(k)).and_then(|k| k.as_array().cloned()) { + stack.extend(kids.iter().filter_map(Object::as_ref)); + } + } af_dict.set(b"Fields".to_vec(), Object::Array(survivors)); + // #2670: the calculation order keeps only the fields that are left, and goes once it is empty. + // Only the form's keys change: an indirect `/CO` or `/SigFlags` may be shared, so it is neither + // freed (that would null the other references) nor rewritten (they would see the shorter + // list). A shortened order is the form's own direct array; once nothing refers to the old + // object, a full save leaves it out. + if let Some(co_obj) = af_dict.get(b"CO").cloned() { + let co_array = doc.resolve(&co_obj).as_array().cloned().unwrap_or_default(); + let before = co_array.len(); + let co_survivors: Vec = co_array.into_iter().filter(|item| item.as_ref().is_some_and(|r| surviving.contains(&r))).collect(); + if co_survivors.is_empty() { + af_dict.remove(b"CO"); + } else if co_survivors.len() != before { + af_dict.set(b"CO".to_vec(), Object::Array(co_survivors)); + } + } + // #2670: with no signature field left, the form no longer claims to hold signatures. + if !surviving.iter().any(|&r| is_signature_field(doc, r)) { + af_dict.remove(b"SigFlags"); + } match af_ref { Some(r) => doc.set(r, Object::Dict(af_dict)), None => doc.update_dict(root, |d| d.set(b"AcroForm".to_vec(), Object::Dict(af_dict)))?, diff --git a/crates/edit/src/images.rs b/crates/edit/src/images.rs index e269fda375..97489de36e 100644 --- a/crates/edit/src/images.rs +++ b/crates/edit/src/images.rs @@ -1012,19 +1012,24 @@ pub(crate) fn extract_scope_state(ops: &[Op], start: usize, target: usize, initi } /// The unit `order` puts the image's unit `target_idx` next to, and whether after it. An image that -/// shares its unit with other paint at the limit moves within that unit, past or behind the paint. +/// shares its unit with other paint at the limit moves within that unit, past or behind the paint, +/// but only when that paint is on the side the move crosses: paint after it for a forward move, +/// paint before it for a backward move. Otherwise the move would leave paint order unchanged and +/// is refused, including when that is the only unit. fn target_destination_unit<'a>( units: &'a [std::ops::Range], target_idx: usize, target_unit: &'a std::ops::Range, order: ArrangeOrder, - has_other_paint: bool, + has_paint_before: bool, + has_paint_after: bool, ) -> Result<(&'a std::ops::Range, bool), EditError> { let forward = matches!(order, ArrangeOrder::BringToFront | ArrangeOrder::BringForward); let refused = || EditError::Invalid(if forward { "the image is already in front" } else { "the image is already at the back" }.into()); let at_limit = if forward { target_idx.saturating_add(1) >= units.len() } else { target_idx == 0 }; if at_limit { - return if has_other_paint { Ok((target_unit, forward)) } else { Err(refused()) }; + let effective_in_unit = if forward { has_paint_after } else { has_paint_before }; + return if effective_in_unit { Ok((target_unit, forward)) } else { Err(refused()) }; } let dest = match order { ArrangeOrder::BringToFront => units.last(), @@ -1204,6 +1209,34 @@ fn build_relocated_unit_ops( Ok(unit_ops) } +/// Paint inside `target_unit` other than the image at `target`, as `(any, before, after)`: whether +/// there is any, and whether some of it comes before the image or after it. +fn arrange_paint_flags(ops: &[Op], target: usize, target_unit: &std::ops::Range) -> (bool, bool, bool) { + let mut has_other_paint = false; + let mut has_paint_before = false; + let mut has_paint_after = false; + // A Form XObject counts as paint whatever the text rendering mode: `Tr 3` hides only the + // text it shows, and its paths and images still paint. + for (i, op) in ops.iter().enumerate() { + if i < target_unit.start || i >= target_unit.end || i == target { + continue; + } + let is_paint = matches!( + op.op.as_slice(), + b"Do" | b"Tj" | b"TJ" | b"'" | b"\"" | b"sh" | b"BI" | b"S" | b"s" | b"f" | b"F" | b"f*" | b"B" | b"B*" | b"b" | b"b*" + ); + if is_paint { + has_other_paint = true; + if i < target { + has_paint_before = true; + } else { + has_paint_after = true; + } + } + } + (has_other_paint, has_paint_before, has_paint_after) +} + /// Change the stacking order of `img`, drawn on page `p` by its content streams `all`. fn arrange_image(doc: &mut Document, p: &pdfcraft_model::Page, all: &[ContentStream], img: &PageImage, order: ArrangeOrder) -> Result<(), EditError> { let pieces = joined(all); @@ -1217,20 +1250,12 @@ fn arrange_image(doc: &mut Document, p: &pdfcraft_model::Page, all: &[ContentStr let Some((target_idx, target_unit)) = units.iter().enumerate().find(|(_, u)| u.contains(&target)) else { return Err(EditError::Invalid("the image content unit could not be located".into())); }; - let has_other_paint = ops.iter().enumerate().any(|(i, op)| { - i >= target_unit.start - && i < target_unit.end - && i != target - && matches!( - op.op.as_slice(), - b"Do" | b"Tj" | b"TJ" | b"'" | b"\"" | b"sh" | b"BI" | b"S" | b"s" | b"f" | b"F" | b"f*" | b"B" | b"B*" | b"b" | b"b*" - ) - }); - if units.len() <= 1 && !has_other_paint { - return Err(EditError::Invalid("the page has only one content unit to arrange".into())); - } + // Units are counted inside a page-wide q … Q wrapper, so separate balanced inner units are not + // mistaken for one shared unit. A sole shared unit is handled by the directional at-limit check + // in `target_destination_unit`: an effective move within it is allowed, an ineffective one is refused. + let (has_other_paint, has_paint_before, has_paint_after) = arrange_paint_flags(&ops, target, target_unit); - let (dest_unit, insert_after) = target_destination_unit(&units, target_idx, target_unit, order, has_other_paint)?; + let (dest_unit, insert_after) = target_destination_unit(&units, target_idx, target_unit, order, has_paint_before, has_paint_after)?; if !balanced_arrange_span(&ops, target_unit.clone()) || !balanced_arrange_span(&ops, dest_unit.clone()) { return Err(EditError::Invalid("cannot arrange an image across graphics or marked-content boundaries".into())); } @@ -1633,10 +1658,15 @@ fn remove_image_crop(doc: &mut Document, p: &pdfcraft_model::Page, all: &[Conten let crops_there = crops(crate::text::first_op_after_damage(all, &pieces, &ops))?; if crops_there.is_empty() { // A crop in a scope that closes past a stream not read whole may clip what that stream draws. - return Err(EditError::Invalid(if crops(ops.len())?.is_empty() { - "the image has no PdfCraft crop to remove".into() - } else { + // Enumeration can also see a PdfCraft crop marker whose path (`W q Q n`, for example) + // scope detection does not treat as a removable crop; say it cannot be removed rather + // than that no crop exists. + return Err(EditError::Invalid(if !crops(ops.len())?.is_empty() { "the image's crop may also clip what a content stream that is damaged or can't be decoded draws, so it isn't removed".into() + } else if img.has_editor_crop() { + "the image's PdfCraft crop cannot be safely removed from its current scope".into() + } else { + "the image has no PdfCraft crop to remove".into() })); } let crops = crops_there; @@ -2084,4 +2114,12 @@ mod allocation_tests { tracker.step(&op, &states, &doc, Matrix::translate(50.0, 0.0)).unwrap(); assert!(before.visually_differs(&tracker.current_state), "the same mask established under a different CTM is a different effective mask"); } + + #[test] + fn arrange_paint_flags_counts_a_form_drawn_in_invisible_text_mode() { + // `Tr 3` hides text, not the paths and images a Form draws. + let ops = + vec![Op::new("Do", vec![Object::name("Target")]), Op::new("Tr", vec![Object::Real(3.0)]), Op::new("Do", vec![Object::name("Form")])]; + assert_eq!(arrange_paint_flags(&ops, 0, &(0..ops.len())), (true, false, true)); + } } diff --git a/crates/edit/src/paragraph_grouping_tests.rs b/crates/edit/src/paragraph_grouping_tests.rs new file mode 100644 index 0000000000..f9d6f51d54 --- /dev/null +++ b/crates/edit/src/paragraph_grouping_tests.rs @@ -0,0 +1,347 @@ +use super::*; + +fn page(content: &str, second_face: &str) -> Document { + let mut doc = text_page(content); + doc.update_dict(pdfcraft_cos::ObjRef::new(6, 0), |font| { + *font = Dict::new(); + font.set(b"Type".to_vec(), Object::name("Font")); + font.set(b"Subtype".to_vec(), Object::name("Type1")); + font.set(b"BaseFont".to_vec(), Object::name(second_face)); + font.set(b"Encoding".to_vec(), Object::name("WinAnsiEncoding")); + }) + .unwrap(); + doc +} + +fn multi_stream_page(contents: &[&str]) -> Document { + let mut doc = page("", "Helvetica"); + let streams = + contents.iter().map(|content| Object::Ref(doc.add(Object::Stream(Stream::from_raw(Dict::new(), content.as_bytes().to_vec()))))).collect(); + set_page_contents(&mut doc, Object::Array(streams), None); + doc +} + +fn panel_form(doc: &mut Document, content: &str, matrix: [i64; 6]) { + let mut dict = Dict::new(); + dict.set(b"Subtype".to_vec(), Object::name("Form")); + dict.set(b"BBox".to_vec(), Object::Array([0, 0, 600, 800].map(Object::Int).to_vec())); + dict.set(b"Matrix".to_vec(), Object::Array(matrix.map(Object::Int).to_vec())); + let form = doc.add(Object::Stream(Stream::from_raw(dict, content.as_bytes().to_vec()))); + let page = pdfcraft_model::pages(doc)[0].obj; + doc.update_dict(page, |page| { + let mut resources = page.get(b"Resources").and_then(Object::as_dict).cloned().unwrap(); + let mut xobjects = Dict::new(); + xobjects.set(b"Panel".to_vec(), Object::Ref(form)); + resources.set(b"XObject".to_vec(), Object::Dict(xobjects)); + page.set(b"Resources".to_vec(), Object::Dict(resources)); + }) + .unwrap(); +} + +#[test] +fn separates_rows_when_background_is_in_a_separate_stream() { + let doc = multi_stream_page(&["q 60 690 200 25 re f Q", "BT /F1 12 Tf 72 700 Td (Panel) Tj 0 -18 Td (Outside) Tj ET"]); + + let blocks = text::text_blocks(&doc, 0).unwrap(); + + assert_eq!(blocks.iter().map(|b| b.text.as_str()).collect::>(), ["Panel", "Outside"]); +} + +#[test] +fn separates_rows_when_distinct_panels_are_in_separate_streams() { + let doc = + multi_stream_page(&["60 690 200 25 re f BT /F1 12 Tf 72 700 Td (Upper) Tj ET", "60 670 200 20 re f BT /F1 12 Tf 72 682 Td (Lower) Tj ET"]); + + let blocks = text::reading_blocks(&doc, 0).unwrap(); + + assert_eq!(blocks.iter().map(|b| b.text.as_str()).collect::>(), ["Upper", "Lower"]); +} + +#[test] +fn joins_rows_when_same_panel_spans_separate_streams() { + let doc = multi_stream_page(&["60 650 200 65 re f BT /F1 12 Tf 72 700 Td (First) Tj ET", "BT /F1 12 Tf 72 682 Td (Second) Tj ET"]); + + let blocks = text::text_blocks(&doc, 0).unwrap(); + + assert_eq!(blocks.iter().map(|b| b.editor_text.as_str()).collect::>(), ["First\nSecond"]); +} + +#[test] +fn separates_rows_when_rectangle_and_fill_are_in_separate_streams() { + let doc = multi_stream_page(&["q 2 0 0 2 20 10 cm 120 352.5 -100 -12.5 re", "f Q BT /F1 12 Tf 72 700 Td (Panel) Tj 0 -18 Td (Outside) Tj ET"]); + + let blocks = text::text_blocks(&doc, 0).unwrap(); + + assert_eq!(blocks.iter().map(|b| b.text.as_str()).collect::>(), ["Panel", "Outside"]); +} + +#[test] +fn separates_page_rows_when_transformed_background_is_in_a_form_stream() { + let mut doc = multi_stream_page(&["/Panel Do", "BT /F1 12 Tf 72 700 Td (Panel) Tj 0 -18 Td (Outside) Tj ET"]); + panel_form(&mut doc, "20 340 100 12.5 re f", [2, 0, 0, 2, 20, 10]); + + let blocks = text::text_blocks(&doc, 0).unwrap(); + + assert_eq!(blocks.iter().map(|b| b.text.as_str()).collect::>(), ["Panel", "Outside"]); +} + +#[test] +fn separates_rows_when_distinct_panels_are_in_form_streams() { + let mut doc = multi_stream_page(&["/Panel Do q 1 0 0 1 0 -18 cm /Panel Do Q"]); + panel_form(&mut doc, "60 690 200 17 re f BT /F1 12 Tf 72 700 Td (Row) Tj ET", [1, 0, 0, 1, 0, 0]); + + let blocks = text::reading_blocks(&doc, 0).unwrap(); + + assert_eq!(blocks.iter().map(|b| b.text.as_str()).collect::>(), ["Row", "Row"]); +} + +#[test] +fn joins_rows_when_page_panel_contains_form_text() { + let mut doc = multi_stream_page(&["60 650 200 65 re f BT /F1 12 Tf 72 700 Td (First) Tj ET", "/Panel Do"]); + panel_form(&mut doc, "BT /F1 12 Tf 72 682 Td (Second) Tj ET", [1, 0, 0, 1, 0, 0]); + + let blocks = text::reading_blocks(&doc, 0).unwrap(); + + assert_eq!(blocks.iter().map(|b| b.editor_text.as_str()).collect::>(), ["First\nSecond"]); +} + +#[test] +fn separates_rows_when_size_change_is_large() { + let doc = page("BT /F1 24 Tf 72 700 Td (Heading) Tj /F1 10 Tf 0 -24 Td (Body) Tj ET", "Helvetica"); + + let blocks = text::text_blocks(&doc, 0).unwrap(); + + assert_eq!(blocks.iter().map(|b| b.text.as_str()).collect::>(), ["Heading", "Body"]); +} + +#[test] +fn separates_equal_size_rows_when_families_differ() { + let doc = page("BT /F1 12 Tf 72 700 Td (Heading) Tj /F2 12 Tf 0 -16 Td (Body) Tj ET", "Courier"); + + let blocks = text::text_blocks(&doc, 0).unwrap(); + + assert_eq!(blocks.iter().map(|b| b.text.as_str()).collect::>(), ["Heading", "Body"]); +} + +#[test] +fn separates_equal_style_rows_when_crossing_a_filled_container() { + let doc = page("q 0.9 g 60 690 200 25 re f Q BT /F1 12 Tf 72 700 Td (Panel) Tj 0 -18 Td (Outside) Tj ET", "Helvetica"); + + let blocks = text::text_blocks(&doc, 0).unwrap(); + + assert_eq!(blocks.iter().map(|b| b.text.as_str()).collect::>(), ["Panel", "Outside"]); +} + +#[test] +fn separates_rows_when_containers_are_adjacent() { + let doc = page("q 60 690 200 25 re f 60 670 200 20 re f Q BT /F1 12 Tf 72 700 Td (Upper) Tj 0 -18 Td (Lower) Tj ET", "Helvetica"); + + let blocks = text::text_blocks(&doc, 0).unwrap(); + + assert_eq!(blocks.len(), 2); +} + +#[test] +fn joins_multiline_when_inside_the_same_filled_container() { + let doc = page("q 0.9 g 60 650 200 65 re f Q BT /F1 12 Tf 72 700 Td (First) Tj 0 -18 Td (Second) Tj 0 -18 Td (Third) Tj ET", "Helvetica"); + + let blocks = text::text_blocks(&doc, 0).unwrap(); + + assert_eq!(blocks.iter().map(|b| b.editor_text.as_str()).collect::>(), ["First\nSecond\nThird"]); +} + +#[test] +fn joins_rows_when_a_fill_is_painted_over_one_of_them() { + // A box painted after the text covers it (a redaction); it is not a panel behind the text. + let doc = page("BT /F1 12 Tf 72 700 Td (First) Tj 0 -18 Td (Second) Tj ET 0 g 70 696 60 20 re f", "Helvetica"); + + let blocks = text::text_blocks(&doc, 0).unwrap(); + + assert_eq!(blocks.iter().map(|b| b.editor_text.as_str()).collect::>(), ["First\nSecond"]); +} + +#[test] +fn joins_rows_when_their_panel_is_repainted_behind_each_row() { + let doc = page( + "0.9 g 60 650 200 65 re f BT /F1 12 Tf 0 g 72 700 Td (First) Tj ET 0.9 g 60 650 200 65 re f BT /F1 12 Tf 0 g 72 682 Td (Second) Tj ET", + "Helvetica", + ); + + let blocks = text::text_blocks(&doc, 0).unwrap(); + + assert_eq!(blocks.iter().map(|b| b.editor_text.as_str()).collect::>(), ["First\nSecond"]); +} + +#[test] +fn joins_rows_when_an_edit_wraps_a_fallback_word_onto_its_own_row() { + // The bundled Inter face draws the Cyrillic Helvetica lacks; wrapped alone onto a row, the + // word is still part of the paragraph that was edited. + let mut doc = page( + "BT /F1 12 Tf 14.4 TL 72 700 Td (The quick brown fox jumps over the lazy dog) Tj T* (and keeps running through the long field.) Tj ET", + "Helvetica", + ); + let edited = "The quick brown fox jumps over the lazy dog \u{049b}\u{0438}\u{0437}\u{0438}\u{043b}\nand keeps running through the long field."; + text::rewrite_block(&mut doc, 0, 0, Some(edited), &text::BlockStyle::default()).unwrap(); + + let blocks = text::text_blocks(&reopen(&doc), 0).unwrap(); + + assert_eq!(blocks.len(), 1, "{:?}", blocks.iter().map(|b| &b.editor_text).collect::>()); + assert!(blocks[0].rows.len() > 2, "the word wraps onto a row of its own: {:?}", blocks[0].editor_text); +} + +#[test] +fn joins_plain_multiline_when_no_container_exists() { + let doc = page("BT /F1 12 Tf 72 700 Td (First) Tj 0 -18 Td (Second) Tj ET", "Helvetica"); + + let blocks = text::text_blocks(&doc, 0).unwrap(); + + assert_eq!(blocks.iter().map(|b| b.editor_text.as_str()).collect::>(), ["First\nSecond"]); +} + +#[test] +fn joins_inline_styles_when_family_and_size_change() { + let doc = page("BT /F1 12 Tf 72 700 Td (Plain ) Tj /F2 20 Tf (mixed) Tj ET", "Courier-Bold"); + + let blocks = text::text_blocks(&doc, 0).unwrap(); + + assert_eq!(blocks.iter().map(|b| b.editor_text.as_str()).collect::>(), ["Plain mixed"]); +} + +#[test] +fn joins_rows_when_subset_and_weight_names_differ() { + let mut doc = page("BT /F1 12 Tf 72 700 Td (First) Tj /F2 12 Tf 0 -18 Td (Second) Tj ET", "GHIJKL+Helvetica-Bold"); + doc.update_dict(pdfcraft_cos::ObjRef::new(5, 0), |font| font.set(b"BaseFont".to_vec(), Object::name("ABCDEF+Helvetica"))).unwrap(); + + let blocks = text::text_blocks(&doc, 0).unwrap(); + + assert_eq!(blocks.iter().map(|b| b.editor_text.as_str()).collect::>(), ["First\nSecond"]); +} + +#[test] +fn joins_rows_when_stacked_weight_suffixes_differ() { + for (regular, bold) in [("TimesNewRomanPSMT", "TimesNewRomanPS-BoldMT"), ("MinionPro-Regular", "MinionPro-BoldIt")] { + let mut doc = page("BT /F1 12 Tf 72 700 Td (First) Tj /F2 12 Tf 0 -18 Td (Second) Tj ET", bold); + doc.update_dict(pdfcraft_cos::ObjRef::new(5, 0), |font| font.set(b"BaseFont".to_vec(), Object::name(regular))).unwrap(); + + let blocks = text::text_blocks(&doc, 0).unwrap(); + + assert_eq!(blocks.iter().map(|b| b.editor_text.as_str()).collect::>(), ["First\nSecond"], "{regular} / {bold}"); + } +} + +#[test] +fn joins_rows_when_a_highlight_hugs_one_word() { + let doc = page("q 1 1 0 rg 98 697 36 12 re f Q BT /F1 12 Tf 72 700 Td (Plain ) Tj (word) Tj ( rest) Tj 0 -18 Td (Second row) Tj ET", "Helvetica"); + + let blocks = text::text_blocks(&doc, 0).unwrap(); + + assert_eq!(blocks.iter().map(|b| b.editor_text.as_str()).collect::>(), ["Plain word rest\nSecond row"]); +} + +#[test] +fn joins_rows_when_a_padded_highlight_surrounds_one_word() { + // Highlighters pad the box past the glyphs; it is still a highlight, not a panel. + for padded in ["98 695 36 16 re", "98 694 36 18 re", "96 693 40 20 re"] { + let doc = page( + &format!("q 1 1 0 rg {padded} f Q BT /F1 12 Tf 72 700 Td (Plain ) Tj (word) Tj ( rest) Tj 0 -18 Td (Second row) Tj ET"), + "Helvetica", + ); + + let blocks = text::text_blocks(&doc, 0).unwrap(); + + assert_eq!(blocks.iter().map(|b| b.editor_text.as_str()).collect::>(), ["Plain word rest\nSecond row"], "{padded}"); + } +} + +#[test] +fn joins_rows_when_a_padded_highlight_sits_inside_a_one_run_line() { + // One `Tj` draws the whole line, so the highlight's word is not a run of its own. + let doc = page("q 1 1 0 rg 98 695 36 16 re f Q BT /F1 12 Tf 72 700 Td (Plain word rest) Tj 0 -18 Td (Second row) Tj ET", "Helvetica"); + + let blocks = text::text_blocks(&doc, 0).unwrap(); + + assert_eq!(blocks.iter().map(|b| b.editor_text.as_str()).collect::>(), ["Plain word rest\nSecond row"]); +} + +#[test] +fn joins_rows_when_only_right_edges_align() { + let doc = page("BT /F1 12 Tf 72 700 Td (Long first row) Tj ET BT /F1 12 Tf 300 682 Td (Short) Tj ET", "Helvetica"); + let lines = text::text_lines(&doc, 0).unwrap(); + let x = lines[0].rect[2] - (lines[1].rect[2] - lines[1].rect[0]); + let doc = page(&format!("BT /F1 12 Tf 72 700 Td (Long first row) Tj ET BT /F1 12 Tf {x} 682 Td (Short) Tj ET"), "Helvetica"); + + let blocks = text::text_blocks(&doc, 0).unwrap(); + + assert_eq!(blocks.iter().map(|b| b.editor_text.as_str()).collect::>(), ["Long first row\nShort"]); +} + +#[test] +fn keeps_outside_text_when_editing_a_container_paragraph() { + let mut doc = page("q 0.9 g 60 690 200 25 re f Q BT /F1 12 Tf 72 700 Td (Panel) Tj 0 -18 Td (Outside) Tj ET", "Helvetica"); + let outside = text::text_lines(&doc, 0).unwrap()[1].clone(); + + text::replace_block(&mut doc, 0, 0, "Edited").unwrap(); + + let reopened = reopen(&doc); + let lines = text::text_lines(&reopened, 0).unwrap(); + let kept = lines.iter().find(|line| line.text == "Outside").expect("outside paragraph survives"); + assert_eq!((kept.rect, kept.size, &kept.base_font), (outside.rect, outside.size, &outside.base_font)); +} + +#[test] +fn keeps_neighboring_panel_when_editing_an_isolated_panel() { + let mut doc = + multi_stream_page(&["60 690 200 25 re f BT /F1 12 Tf 72 700 Td (Upper) Tj ET", "60 670 200 20 re f BT /F1 12 Tf 72 682 Td (Lower) Tj ET"]); + assert_eq!(text::text_blocks(&doc, 0).unwrap().len(), 2); + let neighbor = text::text_lines(&doc, 0).unwrap()[1].clone(); + + text::replace_block(&mut doc, 0, 0, "Edited").unwrap(); + + let reopened = reopen(&doc); + let blocks = text::text_blocks(&reopened, 0).unwrap(); + assert_eq!(blocks.iter().map(|block| block.text.as_str()).collect::>(), ["Edited", "Lower"]); + let lines = text::text_lines(&reopened, 0).unwrap(); + let kept = lines.iter().find(|line| line.text == "Lower").expect("neighboring panel survives"); + assert_eq!( + (kept.rect, kept.baseline(), kept.size, &kept.base_font, kept.color), + (neighbor.rect, neighbor.baseline(), neighbor.size, &neighbor.base_font, neighbor.color) + ); +} + +#[test] +fn separates_rows_when_container_has_a_transformed_negative_rectangle() { + let doc = page("q 2 0 0 2 20 10 cm 120 352.5 -100 -12.5 re B Q BT /F1 12 Tf 72 700 Td (Panel) Tj 0 -18 Td (Outside) Tj ET", "Helvetica"); + + let blocks = text::text_blocks(&doc, 0).unwrap(); + + assert_eq!(blocks.iter().map(|b| b.text.as_str()).collect::>(), ["Panel", "Outside"]); +} + +#[test] +fn joins_rows_when_rectangle_is_only_stroked_or_clipped() { + for paint in ["S", "W n", "W* n"] { + let doc = page(&format!("q 60 690 200 25 re {paint} Q BT /F1 12 Tf 72 700 Td (First) Tj 0 -18 Td (Second) Tj ET"), "Helvetica"); + + let blocks = text::text_blocks(&doc, 0).unwrap(); + + assert_eq!(blocks.iter().map(|b| b.editor_text.as_str()).collect::>(), ["First\nSecond"], "{paint}"); + } +} + +#[test] +fn joins_multiline_with_inline_mixed_families() { + let doc = page("BT /F1 12 Tf 72 700 Td (Ordinary text ) Tj /F2 12 Tf (code) Tj /F1 12 Tf 0 -18 Td (Following row) Tj ET", "Courier-Bold"); + + let blocks = text::text_blocks(&doc, 0).unwrap(); + + assert_eq!(blocks.iter().map(|b| b.editor_text.as_str()).collect::>(), ["Ordinary text code\nFollowing row"]); +} + +#[test] +fn separates_inline_labels_when_a_container_edge_is_between_them() { + let doc = page("q 60 690 50 25 re f Q BT /F1 12 Tf 72 700 Td (Panel) Tj 1 0 0 1 112 700 Tm (Outside) Tj ET", "Helvetica"); + + let blocks = text::text_blocks(&doc, 0).unwrap(); + + assert_eq!(blocks.iter().map(|b| b.text.as_str()).collect::>(), ["Panel", "Outside"]); +} diff --git a/crates/edit/src/tests.rs b/crates/edit/src/tests.rs index 893e598f6e..9b5dbc876e 100644 --- a/crates/edit/src/tests.rs +++ b/crates/edit/src/tests.rs @@ -6,6 +6,8 @@ use super::*; #[path = "mark_transaction_tests.rs"] mod mark_transactions; +#[path = "paragraph_grouping_tests.rs"] +mod paragraph_grouping; /// Three pages: an upright page with content that leaves the graphics state changed (an /// unbalanced `cm`), a page rotated 90° and one with inherited, shared resources. @@ -726,6 +728,173 @@ fn flattening_fields_drops_the_ones_on_no_page() { assert_eq!(left, [pdfcraft_cos::ObjRef::new(7, 0)], "only the hidden field on the page stays"); } +/// #2670: flattening form fields drops removed fields from `/AcroForm /CO` (calculation order) +/// and removes `/CO` once empty, and drops `/SigFlags` once no signature fields remain. +#[test] +fn flattening_fields_cleans_calculation_order_and_sigflags() { + let page = stream("", " "); + // Test 1: both fields flattened -> /Fields becomes empty, /CO and /SigFlags are removed. + let mut doc = build(&[ + "<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [5 0 R 6 0 R] /CO [5 0 R] /SigFlags 1 >> >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Resources << >> /Contents 4 0 R /Annots [5 0 R 6 0 R] >>", + &page, + "<< /Type /Annot /Subtype /Widget /FT /Tx /T (calc) /Rect [10 10 150 40] /F 4 /AP << /N 7 0 R >> >>", + "<< /Type /Annot /Subtype /Widget /FT /Sig /T (sig) /Rect [10 50 150 80] /F 4 /AP << /N 7 0 R >> >>", + "<< /Type /XObject /Subtype /Form /BBox [0 0 140 30] /Length 0 >>\nstream\n\nendstream", + ]); + assert_eq!(flatten(&mut doc, &[0], false, true).unwrap(), 2); + let doc = reopen(&doc); + let root = doc.root().unwrap(); + let af = doc.resolve(doc.get(root).as_dict().unwrap().get(b"AcroForm").unwrap()); + let af_dict = af.as_dict().unwrap(); + let fields = doc.resolve(af_dict.get(b"Fields").unwrap()); + assert_eq!(fields.as_array().unwrap().len(), 0, "no fields remain"); + assert!(!af_dict.contains(b"CO"), "empty calculation order was removed"); + assert!(!af_dict.contains(b"SigFlags"), "SigFlags was removed with no signature fields"); + + // Test 2: one field flattened, one surviving field -> /CO retains surviving field, SigFlags kept. + // The signature field has no appearance but is signed (a value), so it stays (#1794, #4017). + let mut doc2 = build(&[ + "<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [5 0 R 6 0 R] /CO [5 0 R 6 0 R] /SigFlags 1 >> >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Resources << >> /Contents 4 0 R /Annots [5 0 R 6 0 R] >>", + &page, + "<< /Type /Annot /Subtype /Widget /FT /Tx /T (calc1) /Rect [10 10 150 40] /F 4 /AP << /N 7 0 R >> >>", + "<< /Type /Annot /Subtype /Widget /FT /Sig /T (sig_undrawable) /V << /Type /Sig >> /Rect [10 50 150 80] /F 4 >>", + "<< /Type /XObject /Subtype /Form /BBox [0 0 140 30] /Length 0 >>\nstream\n\nendstream", + ]); + assert_eq!(flatten(&mut doc2, &[0], false, true).unwrap(), 1, "only calc1 with appearance is drawn"); + let doc2 = reopen(&doc2); + let root2 = doc2.root().unwrap(); + let af2 = doc2.resolve(doc2.get(root2).as_dict().unwrap().get(b"AcroForm").unwrap()); + let af_dict2 = af2.as_dict().unwrap(); + let co2 = doc2.resolve(af_dict2.get(b"CO").unwrap()); + let co_refs: Vec = co2.as_array().unwrap().iter().filter_map(|f| f.as_ref()).collect(); + assert_eq!(co_refs, [pdfcraft_cos::ObjRef::new(6, 0)], "only surviving field remains in /CO"); + assert!(af_dict2.contains(b"SigFlags"), "SigFlags kept because signature field survived"); +} + +/// #2670: removing an emptied `/CO` or an unneeded `/SigFlags` drops the key only. Both may be +/// indirect objects that something else also refers to, and those references must still resolve. +#[test] +fn flattening_keeps_shared_calculation_order_and_sigflags_objects() { + let page = stream("", " "); + let mut doc = build(&[ + "<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [5 0 R 6 0 R] /CO 9 0 R /SigFlags 8 0 R >> >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Resources << >> /Contents 4 0 R /Annots [5 0 R 6 0 R] >>", + &page, + "<< /Type /Annot /Subtype /Widget /FT /Tx /T (calc) /Rect [10 10 150 40] /F 4 /AP << /N 7 0 R >> >>", + "<< /Type /Annot /Subtype /Widget /FT /Tx /T (kept) /V (Ada) /Ff 8 0 R /Order 9 0 R /Rect [10 50 150 80] /F 4 >>", + "<< /Type /XObject /Subtype /Form /BBox [0 0 140 30] /Length 0 >> +stream + +endstream", + "3", + "[5 0 R]", + ]); + assert_eq!(flatten(&mut doc, &[0], false, true).unwrap(), 1, "only calc is drawn; kept has no appearance"); + let doc = reopen(&doc); + let root = doc.root().unwrap(); + let af = doc.resolve(doc.get(root).as_dict().unwrap().get(b"AcroForm").unwrap()); + let af_dict = af.as_dict().unwrap(); + assert!(!af_dict.contains(b"CO"), "the emptied calculation order was removed"); + assert!(!af_dict.contains(b"SigFlags"), "SigFlags was removed with no signature field left"); + let kept = doc.get(pdfcraft_cos::ObjRef::new(6, 0)); + let kept = kept.as_dict().unwrap(); + assert_eq!(doc.resolve(kept.get(b"Ff").unwrap()).as_int(), Some(3), "the shared /SigFlags object still resolves"); + assert!(doc.resolve(kept.get(b"Order").unwrap()).as_array().is_some(), "the shared /CO array still resolves"); +} + +/// #2670: a calculation order that loses some fields but not all is shortened for the form alone. +/// Its indirect array may be shared, and the other references must still see the whole list. +#[test] +fn flattening_shortens_a_shared_calculation_order_without_changing_it() { + let page = stream("", " "); + let mut doc = build(&[ + "<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [5 0 R 6 0 R] /CO 8 0 R >> >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Resources << >> /Contents 4 0 R /Annots [5 0 R 6 0 R] >>", + &page, + "<< /Type /Annot /Subtype /Widget /FT /Tx /T (calc) /Rect [10 10 150 40] /F 4 /AP << /N 7 0 R >> >>", + "<< /Type /Annot /Subtype /Widget /FT /Tx /T (kept) /V (Ada) /Order 8 0 R /Rect [10 50 150 80] /F 4 >>", + "<< /Type /XObject /Subtype /Form /BBox [0 0 140 30] /Length 0 >> +stream + +endstream", + "[5 0 R 6 0 R]", + ]); + assert_eq!(flatten(&mut doc, &[0], false, true).unwrap(), 1, "only calc is drawn; kept has no appearance"); + let doc = reopen(&doc); + let root = doc.root().unwrap(); + let af = doc.resolve(doc.get(root).as_dict().unwrap().get(b"AcroForm").unwrap()); + let co = doc.resolve(af.as_dict().unwrap().get(b"CO").expect("one field is left in the calculation order")); + let co: Vec<_> = co.as_array().unwrap().iter().map(|o| o.as_ref()).collect(); + assert_eq!(co, [Some(pdfcraft_cos::ObjRef::new(6, 0))], "the form's order keeps only the field that is left"); + let kept = doc.get(pdfcraft_cos::ObjRef::new(6, 0)); + let order = doc.resolve(kept.as_dict().unwrap().get(b"Order").unwrap()); + assert_eq!(order.as_array().map(|a| a.len()), Some(2), "the shared array still lists both fields"); +} + +/// #2670: a signature field kept deeper than the pruning cutoff still counts as left, so it keeps +/// its `/CO` entry and the form keeps `/SigFlags`. +#[test] +fn flattening_keeps_a_deep_signature_field_in_the_calculation_order_and_sigflags() { + let levels = 66; + let page = stream("", " "); + // 5: the flattened widget; 6…: the chain; then the signed widget at its end, on the page. + let leaf = 6 + levels; + let mut objs: Vec = vec![ + format!("<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [5 0 R 6 0 R] /CO [5 0 R {leaf} 0 R] /SigFlags 3 >> >>"), + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>".into(), + format!("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Resources << >> /Contents 4 0 R /Annots [5 0 R {leaf} 0 R] >>"), + page, + format!("<< /Type /Annot /Subtype /Widget /FT /Tx /T (calc) /Rect [10 10 150 40] /F 4 /AP << /N {} 0 R >> >>", leaf + 1), + ]; + for i in 0..levels { + objs.push(format!("<< /T (n{i}) /Kids [{} 0 R] >>", 7 + i)); + } + objs.push("<< /Type /Annot /Subtype /Widget /FT /Sig /T (sig) /V << /Type /Sig >> /Rect [10 50 150 80] /F 4 >>".into()); + objs.push("<< /Type /XObject /Subtype /Form /BBox [0 0 140 30] /Length 0 >>\nstream\n\nendstream".into()); + let objs: Vec<&str> = objs.iter().map(String::as_str).collect(); + let mut doc = build(&objs); + assert_eq!(flatten(&mut doc, &[0], false, true).unwrap(), 1, "only calc is drawn; the signed field has no appearance"); + let doc = reopen(&doc); + let root = doc.root().unwrap(); + let af = doc.resolve(doc.get(root).as_dict().unwrap().get(b"AcroForm").unwrap()); + let af_dict = af.as_dict().unwrap(); + let co = doc.resolve(af_dict.get(b"CO").expect("the deep field stays in the calculation order")); + let co: Vec<_> = co.as_array().unwrap().iter().filter_map(|o| o.as_ref()).collect(); + assert_eq!(co, [pdfcraft_cos::ObjRef::new(leaf as u32, 0)]); + assert!(af_dict.contains(b"SigFlags"), "the deep signature field is still there"); +} + +/// #2670: flattening every page takes a field on no page out of its kept parent's `/Kids`. Nothing +/// is drawn and `/Fields` keeps its length, but `/CO` and `/SigFlags` still lose that field. +#[test] +fn flattening_cleans_the_calculation_order_and_sigflags_of_an_orphan_under_a_kept_parent() { + let page = stream("", " "); + let mut doc = build(&[ + "<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [5 0 R] /CO [6 0 R 7 0 R] /SigFlags 1 >> >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Resources << >> /Contents 4 0 R /Annots [6 0 R] >>", + &page, + "<< /FT /Tx /T (parent) /Kids [6 0 R 7 0 R] >>", + "<< /Type /Annot /Subtype /Widget /Parent 5 0 R /V (Ada) /Rect [10 10 150 40] /F 4 >>", + "<< /Type /Annot /Subtype /Widget /FT /Sig /T (orphan) /Parent 5 0 R /Rect [10 50 150 80] /F 4 >>", + ]); + assert_eq!(flatten(&mut doc, &[0], false, true).unwrap(), 0, "the kept widget has no appearance to draw"); + let doc = reopen(&doc); + let root = doc.root().unwrap(); + let af = doc.resolve(doc.get(root).as_dict().unwrap().get(b"AcroForm").unwrap()); + let af_dict = af.as_dict().unwrap(); + let co = doc.resolve(af_dict.get(b"CO").expect("the kept widget stays in the calculation order")); + let co: Vec<_> = co.as_array().unwrap().iter().filter_map(|o| o.as_ref()).collect(); + assert_eq!(co, [pdfcraft_cos::ObjRef::new(6, 0)], "the orphan left the calculation order"); + assert!(!af_dict.contains(b"SigFlags"), "no signature field is left"); +} + /// #1794: a form field whose widget has no usable appearance (none stored, or none for its /// selected state) has nothing to draw. Flattening used to remove it anyway, losing its value /// with no ink in its place. It stays, in the page and in the form, like a comment that can't be @@ -9590,12 +9759,13 @@ fn japanese_paragraphs_wrap_between_characters_without_closing_marks_at_a_row_st #[test] fn rewritten_paragraph_is_drawn_after_backgrounds_between_its_rows() { - // Each row has its own background box drawn immediately before its BT..ET, as cards and - // highlighted headings exported from LibreOffice or browsers do (#2377). - let card = "0 0.45 0.25 rg 60 696 240 16 re f BT /F1 10 Tf 1 1 1 rg 64 700 Td (SEMINARIO ONLINE) Tj ET \ - 0 0.45 0.25 rg 60 668 240 24 re f BT /F1 16 Tf 1 1 1 rg 64 674 Td (Dalla teoria alla pratica:) Tj ET \ - 0 0.45 0.25 rg 60 632 240 32 re f BT /F1 24 Tf 1 1 1 rg 64 640 Td (gestire con metodo) Tj ET \ - 0 0.45 0.25 rg 60 596 240 32 re f BT /F1 24 Tf 1 1 1 rg 64 604 Td (un progetto complesso) Tj ET"; + // Layered paragraph-wide backgrounds still paint between rows (#2377), but every row has + // the same container membership. Compatible size changes retain the mixed-style rewrite + // without asking the grouping heuristic to merge independent panels or headings. + let card = "0 0.45 0.25 rg 60 540 240 180 re f BT /F1 16 Tf 1 1 1 rg 64 700 Td (SEMINARIO ONLINE) Tj ET \ + 0 0.45 0.25 rg 60 540 240 180 re f BT /F1 20 Tf 1 1 1 rg 64 674 Td (Dalla teoria alla pratica:) Tj ET \ + 0 0.45 0.25 rg 60 540 240 180 re f BT /F1 24 Tf 1 1 1 rg 64 640 Td (gestire con metodo) Tj ET \ + 0 0.45 0.25 rg 60 540 240 180 re f BT /F1 24 Tf 1 1 1 rg 64 604 Td (un progetto complesso) Tj ET"; let shown_at = |ops: &[pdfcraft_content::Op], needle: &str| { ops.iter() .position(|op| { @@ -9608,6 +9778,13 @@ fn rewritten_paragraph_is_drawn_after_backgrounds_between_its_rows() { // 1. Editing the title rows emits all rewritten rows after all four background fills. let mut doc = text_page(card); assert_eq!(text::text_blocks(&doc, 0).unwrap().len(), 1); + let source_ops = pdfcraft_content::parse(&page_content_bytes(&doc, 0)).ops; + let source_fills: Vec = source_ops.iter().enumerate().filter_map(|(i, op)| op.is("f").then_some(i)).collect(); + assert_eq!(source_fills.len(), 4); + for (row, needle) in ["SEMINARIO", "pratica:", "metodo", "complesso"].iter().enumerate() { + let shown = shown_at(&source_ops, needle); + assert!(source_fills[row] < shown && source_fills.get(row + 1).is_none_or(|next| shown < *next), "backgrounds must stay interleaved"); + } let edited = "SEMINARIO ONLINE\nDalla teoria alla pratica:\ngestire con criterio\nun progetto nuovo"; text::rewrite_block(&mut doc, 0, 0, Some(edited), &text::BlockStyle::default()).unwrap(); let doc = reopen(&doc); @@ -9643,6 +9820,9 @@ fn rewritten_paragraph_is_drawn_after_backgrounds_between_its_rows() { let wrapped_edit = "SEMINARIO ONLINE\nDalla teoria alla pratica:\ngestire con criterio e metodo approfondito\nun progetto complesso"; text::rewrite_block(&mut doc, 0, 0, Some(wrapped_edit), &text::BlockStyle::default()).unwrap(); let doc = reopen(&doc); + let wrapped = text::text_blocks(&doc, 0).unwrap(); + assert!(wrapped[0].rows.len() > 4, "the long edit must wrap and push the suffix row down"); + assert_eq!(wrapped[0].text, wrapped_edit.replace('\n', " ")); let ops = pdfcraft_content::parse(&page_content_bytes(&doc, 0)).ops; let last_fill = ops.iter().rposition(|op| op.is("f")).unwrap(); assert!( @@ -9652,8 +9832,8 @@ fn rewritten_paragraph_is_drawn_after_backgrounds_between_its_rows() { // 4. Single-style paragraph path across a CTM change between rows, with movement, underline, // and a trailing unrelated line sharing the second row's BT..ET. - let cross_ctm = "0.9 0.9 0.2 rg 60 696 240 18 re f BT /F1 12 Tf 0 0 0 rg 64 700 Td (First highlighted row) Tj ET \ - q 1 0 0 1 10 12 cm 0.9 0.9 0.2 rg 50 668 240 18 re f \ + let cross_ctm = "0.9 0.9 0.2 rg 60 676 240 38 re f BT /F1 12 Tf 0 0 0 rg 64 700 Td (First highlighted row) Tj ET \ + q 1 0 0 1 10 12 cm 0.9 0.9 0.2 rg 50 664 240 38 re f \ BT /F1 12 Tf 0 0 0 rg 54 672 Td (Second highlighted row) Tj 246 -40 Td (Side footer) Tj ET Q"; let mut doc = text_page(cross_ctm); let para = text::text_blocks(&doc, 0).unwrap().into_iter().position(|b| b.text.starts_with("First highlighted")).unwrap(); @@ -10867,6 +11047,225 @@ fn reading_keeps_dotted_leader_entries_whole_and_in_order() { ); } +/// #3803: Tesseract and PDFium write invisible (`3 Tr`) OCR layers in a `/Glyphless` CIDFontType2 +/// whose `/ToUnicode` and `/W` cover Latin text while `/CIDToGIDMap` maps every CID to GID 1 (a +/// solid rectangle). Rewriting such text as visible (`0 Tr`) must substitute a real font rather +/// than drawing the replacement in `/Glyphless` rectangles. +#[test] +fn editing_glyphless_ocr_text_substitutes_a_visible_font() { + let mut one_glyph_ttf = include_bytes!("../../../assets/fonts/Inter-Regular.ttf").to_vec(); + let count = u16::from_be_bytes(one_glyph_ttf[4..6].try_into().unwrap()) as usize; + let loca_rec = (0..count).map(|i| 12 + i * 16).find(|i| &one_glyph_ttf[*i..*i + 4] == b"loca").unwrap(); + let loca_off = u32::from_be_bytes(one_glyph_ttf[loca_rec + 8..loca_rec + 12].try_into().unwrap()) as usize; + let loca_len = u32::from_be_bytes(one_glyph_ttf[loca_rec + 12..loca_rec + 16].try_into().unwrap()) as usize; + one_glyph_ttf[loca_off..loca_off + 8].fill(0); + for chunk in one_glyph_ttf[loca_off + 8..loca_off + loca_len].as_chunks_mut::<4>().0 { + *chunk = 4u32.to_be_bytes(); + } + + let make_page = |content: &str, base: &str| { + let mut doc = text_page(content); + let program = doc.add(Object::Stream(Stream::flate(Dict::new(), &one_glyph_ttf))); + let cid_to_gid = doc.add(Object::Stream(Stream::flate(Dict::new(), &[0, 1].repeat(256)))); + let cmap = b"1 begincodespacerange <0000> endcodespacerange 1 beginbfrange <0000> <00FF> <0000> endbfrange"; + let unicode = doc.add(Object::Stream(Stream::flate(Dict::new(), cmap))); + let descriptor = Dict::from_iter([ + (b"Type".to_vec(), Object::name("FontDescriptor")), + (b"FontName".to_vec(), Object::name(base)), + (b"Flags".to_vec(), Object::Int(5)), + (b"FontBBox".to_vec(), Object::Array([0, -207, 500, 718].map(Object::Int).to_vec())), + (b"Ascent".to_vec(), Object::Int(718)), + (b"Descent".to_vec(), Object::Int(-207)), + (b"FontFile2".to_vec(), Object::Ref(program)), + ]); + let cid_font = Dict::from_iter([ + (b"Type".to_vec(), Object::name("Font")), + (b"Subtype".to_vec(), Object::name("CIDFontType2")), + (b"BaseFont".to_vec(), Object::name(base)), + (b"CIDToGIDMap".to_vec(), Object::Ref(cid_to_gid)), + (b"DW".to_vec(), Object::Int(500)), + (b"W".to_vec(), Object::Array(vec![Object::Int(32), Object::Array(vec![Object::Int(285)])])), + (b"FontDescriptor".to_vec(), Object::Dict(descriptor)), + ]); + let font = Dict::from_iter([ + (b"Type".to_vec(), Object::name("Font")), + (b"Subtype".to_vec(), Object::name("Type0")), + (b"BaseFont".to_vec(), Object::name(base)), + (b"Encoding".to_vec(), Object::name("Identity-H")), + (b"DescendantFonts".to_vec(), Object::Array(vec![Object::Dict(cid_font)])), + (b"ToUnicode".to_vec(), Object::Ref(unicode)), + ]); + let p = pdfcraft_model::pages(&doc)[0].obj; + let fonts = Dict::from_iter([(b"F0".to_vec(), Object::Dict(font))]); + doc.update_dict(p, |d| d.set(b"Resources".to_vec(), Object::Dict(Dict::from_iter([(b"Font".to_vec(), Object::Dict(fonts))])))).unwrap(); + doc + }; + + // Single-line OCR paragraph (rewrite_block_from path) and replace_line path. + let single = "BT 3 Tr 0.055 Tw -0.581 Tc 100 Tz /F0 15.75 Tf 1 0 0 1 114.75 568.8 Tm \ + [<0044> -27 <0065> -23 <0020> -22 <006B> -29 <0069> -28 <006E> -27 <0064> -29 <0065> -23 <0072> -28 <0065> -23 <006E>] TJ ET"; + for base in ["Glyphless", "CustomOCR"] { + let mut doc = make_page(single, base); + assert!(text::text_editor_fonts(&doc, 0).unwrap().iter().all(|f| f.choice_only), "{base} must not be loaded into the inline editor"); + let before = text::text_blocks(&doc, 0).unwrap(); + assert_eq!(before.len(), 1); + assert_eq!(before[0].text, "De kinderen"); + assert!(before[0].invisible); + + let edit = text::replace_block(&mut doc, 0, 0, "De Kinderen").unwrap(); + assert_eq!(edit.substituted.as_deref(), Some("Helvetica"), "{base} must substitute Helvetica instead of drawing in /F0"); + let after = text::text_blocks(&reopen(&doc), 0).unwrap(); + assert_eq!(after.len(), 1); + assert_eq!(after[0].text, "De Kinderen"); + assert!(!after[0].invisible, "the edited OCR paragraph is now visible"); + assert_eq!(after[0].base_font, "Helvetica"); + + let mut line_doc = make_page(single, base); + let line_edit = text::replace_line(&mut line_doc, 0, 0, "De Kinderen").unwrap(); + assert_eq!(line_edit.substituted.as_deref(), Some("Helvetica"), "{base} replace_line must also substitute"); + assert_eq!(text::text_lines(&reopen(&line_doc), 0).unwrap()[0].base_font, "Helvetica"); + } + + // Multi-run OCR phrase on one row with slightly different OCR font sizes (rewrite_styled_block + // path): both runs switch to the visible substitute font and keep calibrated widths without + // stretching spaces to 200%. + let multi_run = "BT 3 Tr /F0 15.75 Tf 1 0 0 1 114.75 568.8 Tm <004400650020006B0069006E0064006500720065006E> Tj ET \ + BT 3 Tr /F0 15.5 Tf 1 0 0 1 205.0 568.8 Tm <006B0075006E006E0065006E> Tj ET"; + let mut doc = make_page(multi_run, "Glyphless"); + let before_lines = text::text_lines(&doc, 0).unwrap(); + let before = text::text_blocks(&doc, 0).unwrap(); + assert_eq!(before.len(), 1); + assert_eq!(before[0].lines.len(), 2, "two runs on one OCR row"); + let edit = text::replace_block(&mut doc, 0, 0, "De kinderen Kunnen").unwrap(); + assert_eq!(edit.substituted.as_deref(), Some("Helvetica")); + let lines = text::text_lines(&reopen(&doc), 0).unwrap(); + assert_eq!(lines.iter().map(|l| l.text.trim()).collect::>(), ["De kinderen", "Kunnen"]); + for line in &lines { + assert_eq!(line.base_font, "Helvetica", "every run must use the visible substitute font: {line:?}"); + } + let old_w = before_lines[0].rect[2] - before_lines[0].rect[0]; + let new_w = lines[0].rect[2] - lines[0].rect[0]; + assert!((new_w - old_w).abs() < 5.0, "calibrated first run keeps its width ({old_w} -> {new_w}): {lines:?}"); + assert!(lines[1].rect[0] >= lines[0].rect[2] - 1.0, "calibrated first run does not stretch into the second: {lines:?}"); + let blocks = text::text_blocks(&reopen(&doc), 0).unwrap(); + assert!(!blocks[0].invisible, "the whole rewritten paragraph is visible"); + + // High WinAnsi characters on a glyphless OCR line also use the Helvetica substitute rather + // than /F0, and explicitly selecting the glyphless resource is refused. + let mut win_ansi_doc = make_page(single, "Glyphless"); + let win_edit = text::replace_block(&mut win_ansi_doc, 0, 0, "De kinderen € — café").unwrap(); + assert_eq!(win_edit.substituted.as_deref(), Some("Helvetica")); + assert_eq!(text::text_blocks(&reopen(&win_ansi_doc), 0).unwrap()[0].text, "De kinderen € — café"); + + let mut explicit = make_page(single, "Glyphless"); + let explicit_err = + text::rewrite_block(&mut explicit, 0, 0, Some("De Kinderen"), &BlockStyle { resource: Some("F0".into()), ..Default::default() }); + assert!(explicit_err.is_err(), "explicitly selecting a glyphless font resource must be refused"); + + // Legitimate whitespace-only subsets and 1-glyph subsets with intentional CID aliases remain + // exposed to the inline editor and accepted when explicitly selected as a resource. + let mut zero_glyph_ttf = one_glyph_ttf.clone(); + zero_glyph_ttf[loca_off..loca_off + loca_len].fill(0); + let mut ws_doc = text_page("BT /F0 12 Tf 1 0 0 1 72 700 Tm <0001> Tj /WS 12 Tf ( ) Tj ET"); + let ws_prog = ws_doc.add(Object::Stream(Stream::flate(Dict::new(), &zero_glyph_ttf))); + let ws_desc = Dict::from_iter([(b"FontName".to_vec(), Object::name("ABCDEF+SpaceOnly")), (b"FontFile2".to_vec(), Object::Ref(ws_prog))]); + let ws_font = Dict::from_iter([ + (b"Type".to_vec(), Object::name("Font")), + (b"Subtype".to_vec(), Object::name("TrueType")), + (b"BaseFont".to_vec(), Object::name("ABCDEF+SpaceOnly")), + (b"Encoding".to_vec(), Object::name("WinAnsiEncoding")), + (b"FirstChar".to_vec(), Object::Int(32)), + (b"LastChar".to_vec(), Object::Int(32)), + (b"Widths".to_vec(), Object::Array(vec![Object::Int(250)])), + (b"FontDescriptor".to_vec(), Object::Dict(ws_desc)), + ]); + let alias_prog = ws_doc.add(Object::Stream(Stream::flate(Dict::new(), &one_glyph_ttf))); + let alias_map = ws_doc.add(Object::Stream(Stream::flate(Dict::new(), &[0, 0, 0, 1, 0, 1, 0, 1]))); + let alias_tu = ws_doc.add(Object::Stream(Stream::flate(Dict::new(), b"2 beginbfchar <0001> <0041> <0002> <0061> endbfchar"))); + let alias_desc = Dict::from_iter([(b"FontName".to_vec(), Object::name("ABCDEF+AliasOne")), (b"FontFile2".to_vec(), Object::Ref(alias_prog))]); + let alias_cid = Dict::from_iter([ + (b"Type".to_vec(), Object::name("Font")), + (b"Subtype".to_vec(), Object::name("CIDFontType2")), + (b"BaseFont".to_vec(), Object::name("ABCDEF+AliasOne")), + (b"CIDToGIDMap".to_vec(), Object::Ref(alias_map)), + (b"W".to_vec(), Object::Array(vec![Object::Int(1), Object::Array(vec![Object::Int(600), Object::Int(600)])])), + (b"FontDescriptor".to_vec(), Object::Dict(alias_desc)), + ]); + let alias_font = Dict::from_iter([ + (b"Type".to_vec(), Object::name("Font")), + (b"Subtype".to_vec(), Object::name("Type0")), + (b"BaseFont".to_vec(), Object::name("ABCDEF+AliasOne")), + (b"Encoding".to_vec(), Object::name("Identity-H")), + (b"DescendantFonts".to_vec(), Object::Array(vec![Object::Dict(alias_cid)])), + (b"ToUnicode".to_vec(), Object::Ref(alias_tu)), + ]); + let p = pdfcraft_model::pages(&ws_doc)[0].obj; + let fonts = Dict::from_iter([(b"F0".to_vec(), Object::Dict(alias_font)), (b"WS".to_vec(), Object::Dict(ws_font))]); + ws_doc.update_dict(p, |d| d.set(b"Resources".to_vec(), Object::Dict(Dict::from_iter([(b"Font".to_vec(), Object::Dict(fonts))])))).unwrap(); + let editor_resources: Vec<_> = text::text_editor_fonts(&ws_doc, 0).unwrap().into_iter().map(|f| f.resource).collect(); + assert!(editor_resources.contains(&"F0".to_string()) && editor_resources.contains(&"WS".to_string()), "{editor_resources:?}"); + let mut ws_only = ws_doc.clone(); + text::rewrite_block(&mut ws_only, 0, 0, Some(" "), &BlockStyle { resource: Some("WS".into()), ..Default::default() }).unwrap(); + text::rewrite_block(&mut ws_doc, 0, 0, Some("Aa"), &BlockStyle { resource: Some("F0".into()), ..Default::default() }).unwrap(); + assert_eq!(text::text_blocks(&reopen(&ws_doc), 0).unwrap()[0].text, "Aa"); +} + +/// Same-face generated subsets share a source line; TJ adjustment must survive a style edit. +#[test] +fn split_subset_source_keeps_calibrated_advance() { + let mut doc = text_page("BT /A 12 Tf 72 700 Td [<01> -100] TJ /B 12 Tf <01> Tj ET BT /F1 13 Tf 1 0 0 1 85.2 700 Tm (X) Tj ET"); + let mut fonts = Dict::new(); + // AA sorts before B and encodes B too, but its unrelated face must not supply metrics. + for (name, unicode, face, width) in + [("A", "0041", "SyntheticSubset", 500), ("AA", "0042", "OtherFace", 900), ("B", "0042", "SyntheticSubset", 500)] + { + let cmap = format!("1 begincodespacerange <01> endcodespacerange 1 beginbfchar <01> <{unicode}> endbfchar"); + let tu = doc.add(Object::Stream(Stream::flate(Dict::new(), cmap.as_bytes()))); + let proc = doc.add(Object::Stream(Stream::flate(Dict::new(), b"500 0 d0 0 0 400 700 re f"))); + let font = Dict::from_iter([ + (b"Type".to_vec(), Object::name("Font")), + (b"Subtype".to_vec(), Object::name("Type3")), + (b"Name".to_vec(), Object::name("PCJapanese")), + (b"BaseFont".to_vec(), Object::name(face)), + (b"FontBBox".to_vec(), Object::Array([0, 0, 500, 700].map(Object::Int).to_vec())), + (b"FontMatrix".to_vec(), Object::Array([0.001, 0.0, 0.0, 0.001, 0.0, 0.0].map(Object::Real).to_vec())), + (b"FirstChar".to_vec(), Object::Int(1)), + (b"LastChar".to_vec(), Object::Int(1)), + (b"Widths".to_vec(), Object::Array(vec![Object::Int(width)])), + ( + b"Encoding".to_vec(), + Object::Dict(Dict::from_iter([(b"Differences".to_vec(), Object::Array(vec![Object::Int(1), Object::name("g01")]))])), + ), + (b"CharProcs".to_vec(), Object::Dict(Dict::from_iter([(b"g01".to_vec(), Object::Ref(proc))]))), + (b"ToUnicode".to_vec(), Object::Ref(tu)), + ]); + fonts.set(name.as_bytes().to_vec(), Object::Dict(font)); + } + fonts.set( + b"F1".to_vec(), + Object::Dict(Dict::from_iter([ + (b"Type".to_vec(), Object::name("Font")), + (b"Subtype".to_vec(), Object::name("Type1")), + (b"BaseFont".to_vec(), Object::name("Helvetica")), + ])), + ); + let page = pdfcraft_model::pages(&doc)[0].obj; + doc.update_dict(page, |d| d.set(b"Resources".to_vec(), Object::Dict(Dict::from_iter([(b"Font".to_vec(), Object::Dict(fonts))])))).unwrap(); + let before = text::text_lines(&doc, 0).unwrap(); + assert_eq!(before[0].text, "AB"); + let blocks = text::text_blocks(&doc, 0).unwrap(); + assert_eq!(blocks.len(), 1, "{blocks:?}"); + assert_eq!(blocks[0].lines.len(), 2); + let original_width = before[0].rect[2] - before[0].rect[0]; + for (draft, factor) in [("ABX", 1.0), ("ABAX", 1.5)] { + let mut edited = doc.clone(); + text::rewrite_block(&mut edited, 0, 0, Some(draft), &BlockStyle { color: Some([0.0, 0.0, 1.0]), ..Default::default() }).unwrap(); + let after = text::text_lines(&reopen(&edited), 0).unwrap(); + let width = after[0].rect[2] - after[0].rect[0]; + assert!((width - original_width * factor).abs() < 0.01, "{draft}: original {original_width}, rewritten {width}; {after:?}"); + } +} + #[cfg(test)] mod proptests { use super::*; @@ -11001,6 +11400,53 @@ fn noop_arrange_is_not_ok_without_change() { assert!(r.is_err() || before != after, "Ok with no change"); } +/// Bring to front on an at-limit image that shares its only content unit with paint +/// already before it is a no-op, so it is refused instead of rebuilding the same placement. +#[test] +fn arrange_front_image_in_single_shared_unit_is_refused() { + let mut doc = image_page_with("q 0 0 10 10 re f 100 0 0 100 50 50 cm /Im0 Do Q"); + let before = page_content_bytes(&doc, 0); + assert!(arrange(&mut doc, 0, 0, images::ArrangeOrder::BringToFront).is_err()); + assert_eq!(page_content_bytes(&doc, 0), before); +} + +#[test] +fn arrange_front_image_in_single_shared_unit_moves_past_following_paint() { + let mut doc = image_page_with("q 100 0 0 100 50 50 cm /Im0 Do 0 0 10 10 re f Q"); + assert!( + arrange(&mut doc, 0, 0, images::ArrangeOrder::BringToFront).is_ok(), + "an image before following paint in one shared unit can be brought to front" + ); + let s = String::from_utf8_lossy(&page_content_bytes(&doc, 0)).into_owned(); + assert!(s.find("re f").unwrap() < s.rfind("/Im0 Do").unwrap(), "{s}"); + let mut doc = image_page_with("q q 100 0 0 100 50 50 cm /Im0 Do Q q 50 50 10 10 re f Q Q"); + assert!(arrange(&mut doc, 0, 0, images::ArrangeOrder::BringToFront).is_ok(), "separate inner units inside a page wrapper can be reordered"); + let s = String::from_utf8_lossy(&page_content_bytes(&doc, 0)).into_owned(); + assert!(s.find("re f").unwrap() < s.rfind("/Im0 Do").unwrap(), "{s}"); + let mut doc = image_page_with("q 0 0 10 10 re f 100 0 0 100 50 50 cm /Im0 Do Q"); + let before = page_content_bytes(&doc, 0); + assert!(arrange(&mut doc, 0, 0, images::ArrangeOrder::BringForward).is_err()); + assert_eq!(page_content_bytes(&doc, 0), before); +} + +#[test] +fn arrange_backward_in_single_shared_unit_moves_before_paint_and_refuses_without_it() { + for order in [images::ArrangeOrder::SendToBack, images::ArrangeOrder::SendBackward] { + let mut doc = image_page_with("q q 0 0 10 10 re f 100 0 0 100 50 50 cm /Im0 Do Q Q"); + arrange(&mut doc, 0, 0, order).unwrap(); + let doc = reopen(&doc); + let s = String::from_utf8_lossy(&page_content_bytes(&doc, 0)).into_owned(); + assert!(s.find("/Im0 Do").unwrap() < s.find("re f").unwrap(), "{order:?}: {s}"); + assert_eq!(images::page_images(&doc, 0).unwrap()[0].rect, [50.0, 50.0, 150.0, 150.0]); + } + for order in [images::ArrangeOrder::SendToBack, images::ArrangeOrder::SendBackward] { + let mut doc = image_page_with("q q 100 0 0 100 50 50 cm /Im0 Do 0 0 10 10 re f Q Q"); + let before = page_content_bytes(&doc, 0); + assert!(arrange(&mut doc, 0, 0, order).is_err(), "{order:?}"); + assert_eq!(page_content_bytes(&doc, 0), before); + } +} + /// Cropping a turned image keeps the requested upright box in user space, rather than expanding /// to the bounding box of the turned image coordinates. #[test] @@ -13963,6 +14409,19 @@ fn remove_crop_refuses_an_unmarked_author_clip_without_changes() { assert_eq!(page_content_bytes(&doc, 0), before); } +/// A PdfCraft crop marker whose clip is written as `W q Q n` is still recorded on the image, but +/// scope detection does not treat that path as a removable crop. The error says the crop cannot +/// be removed, not that none exists. +#[test] +fn remove_crop_reports_a_recorded_crop_it_cannot_strip() { + let mut doc = image_page_with("q /PdfCraftImageCrop MP 100 100 50 50 re W q Q n 200 0 0 100 100 100 cm /Im0 Do Q"); + assert!(images::page_images(&doc, 0).unwrap()[0].has_editor_crop()); + let before = page_content_bytes(&doc, 0); + let err = remove_crop(&mut doc, 0, 0).unwrap_err().to_string(); + assert!(err.contains("cannot be safely removed") && !err.contains("has no PdfCraft crop"), "{err}"); + assert_eq!(page_content_bytes(&doc, 0), before); +} + #[test] fn arrange_refuses_unrestorable_extended_print_state() { let mut unexpectedly_moved = Vec::new(); diff --git a/crates/edit/src/text.rs b/crates/edit/src/text.rs index 0bcd48cc8e..01a736ef9f 100644 --- a/crates/edit/src/text.rs +++ b/crates/edit/src/text.rs @@ -29,6 +29,11 @@ pub use fallback::strip_subset_tag; use regions::{alignment_frame, existing_gap, group_blocks, is_centred, rewrite_changed_words, rewrite_styled_block, row_sources, source_row_step}; pub use session::TextSession; +#[path = "text_containers.rs"] +mod containers; +#[path = "text_row_style.rs"] +mod row_style; + mod blocks; mod editor; mod fallback; @@ -112,6 +117,7 @@ pub struct TextLine { scope: Option, /// The layers and graphics state parameters it is drawn in; see [`Paint`]. paint: Paint, + containers: Vec, /// Right-to-left `/ActualText` already supplies typing order; glyph text still needs bidi /// recovery. Left-to-right ActualText (e.g. a Latin ligature) joins its line as usual. logical_order: bool, diff --git a/crates/edit/src/text/interp.rs b/crates/edit/src/text/interp.rs index cf9e0beef2..284914d4fa 100644 --- a/crates/edit/src/text/interp.rs +++ b/crates/edit/src/text/interp.rs @@ -479,6 +479,7 @@ pub(super) struct Shown { pub(super) decodable: bool, pub(super) scope: Option, pub(super) paint: Paint, + pub(super) containers: Vec, pub(super) logical_order: bool, pub(super) actual_text: bool, /// Set when a `/PCSoft` or `/PCHard` marker was seen since the previous text line. @@ -623,6 +624,9 @@ pub(super) struct Carry { pub(super) layers: Vec>>, /// Bytes of glyph text the rest of the page may still produce (see [`MAX_PAGE_TEXT`]). pub(super) text_left: usize, + pub(super) containers: Rc, + /// The operator indices of the `Do`s, from the page down, that draw these operators. + pub(super) at: Vec, /// Whether the last run ended in a space read from a gap, with the next operator a `Tj` or /// `TJ` that may start with the space glyph that gap widened. pub(super) gap_space: bool, @@ -657,7 +661,16 @@ impl Carry { dash: (Vec::new(), 0.0), line_cap: 0, }; - Carry { ts, stack: Vec::new(), marked: Vec::new(), layers: Vec::new(), text_left: MAX_PAGE_TEXT, gap_space: false } + Carry { + ts, + stack: Vec::new(), + marked: Vec::new(), + layers: Vec::new(), + text_left: MAX_PAGE_TEXT, + containers: Rc::default(), + at: Vec::new(), + gap_space: false, + } } } @@ -964,6 +977,7 @@ fn show_text(op: &Op, i: usize, state: &mut TextRunState<'_>) -> Result<(), Edit decodable, scope: marked.regions.last().copied().flatten(), paint: Paint { layers: marked.layers.iter().flatten().cloned().collect(), gs: ts.gs.clone() }, + containers: Vec::new(), logical_order: false, actual_text: false, soft_break: state.soft_break, @@ -1233,5 +1247,52 @@ pub(super) fn interpret( carry.layers = marked.layers; out.retain(|s| s.glyph_count > 0 || s.actual_text); positioned_tracking(&mut out); + assign_containers(&mut out, carry); Ok(out) } + +/// The filled panels each piece of text sits in: its `membership`, less a box a highlight's +/// height that only part of the text or of its line is in. +fn assign_containers(out: &mut [Shown], carry: &Carry) { + for shown in out.iter_mut() { + shown.containers = carry.containers.membership(shown.rect, &[carry.at.as_slice(), &[shown.op]].concat()); + } + // A box a highlight's height that does not reach across the text is a highlight behind part + // of it, as when one `Tj` draws the whole line. + for shown in out.iter_mut() { + let rect = shown.rect; + shown.containers.retain(|panel| carry.containers.spans(*panel, rect) || !carry.containers.hugs(*panel, rect)); + } + // Text that runs on along its line keeps a box only part of it is in when the box is a + // panel's height: a highlight padded around one word of the line is not a panel. + let mut start = 0; + while start < out.len() { + let mut end = start + 1; + while out.get(end).is_some_and(|next| runs_on(&out[end - 1].rect, &next.rect)) { + end += 1; + } + if end - start > 1 { + // How many of the run's pieces each box holds (`membership` lists a box once per piece), + // counted in one pass: a hostile page can chain thousands of runs into one line. + let mut held: HashMap = HashMap::new(); + for shown in &out[start..end] { + for panel in &shown.containers { + *held.entry(*panel).or_default() += 1; + } + } + for shown in &mut out[start..end] { + let rect = shown.rect; + shown.containers.retain(|panel| held.get(panel) == Some(&(end - start)) || !carry.containers.hugs(*panel, rect)); + } + } + start = end; + } +} + +/// Whether text in `next` continues `previous` along its line: about the same height across it, +/// and starting at or after it with less than a line's height between them. +fn runs_on(previous: &[f64; 4], next: &[f64; 4]) -> bool { + let height = (previous[3] - previous[1]).max(next[3] - next[1]); + let centre = |r: &[f64; 4]| (r[1] + r[3]) / 2.0; + (centre(previous) - centre(next)).abs() < height / 2.0 && next[0] >= previous[0] && next[0] - previous[2] < height +} diff --git a/crates/edit/src/text/lines.rs b/crates/edit/src/text/lines.rs index 43b2c84d4e..12f560a550 100644 --- a/crates/edit/src/text/lines.rs +++ b/crates/edit/src/text/lines.rs @@ -460,6 +460,7 @@ fn text_lines_in(doc: &Document, p: &pdfcraft_model::Page, actual_text: bool, in let pieces = joined(&content_streams(doc, &p.dict)?); let ops = pieces.parse().ops; let properties = res.get(b"Properties").and_then(|o| doc.dict(o)).unwrap_or_default(); + carry.containers = std::rc::Rc::new(super::containers::Containers::collect(doc, &ops, &res)); let shown = interpret(doc, &ops, &res, &mut cache, &mut carry, None, actual_text.then_some(&properties))?; let mut last: Option<(usize, Pen)> = None; // the stream piece and where its last run ended for mut s in shown { @@ -478,7 +479,9 @@ fn text_lines_in(doc: &Document, p: &pdfcraft_model::Page, actual_text: bool, in let bt = pen.bt; let (near, gap) = pen.continues(&s, if bt == s.bt { 3.0 } else { 1.5 }); piece == si - && lines.last().is_some_and(|l| l.scope == s.scope && l.paint == s.paint && l.logical_order == s.logical_order) + && lines.last().is_some_and(|l| { + l.scope == s.scope && l.paint == s.paint && l.containers == s.containers && l.logical_order == s.logical_order + }) && (bt == s.bt || lines.last().is_some_and(|l| compatible_word(l, &s))) && (s.text.trim().is_empty() || lines.last().is_some_and(|l| continues_font(l, &s))) && (s.text.trim().is_empty() @@ -534,6 +537,7 @@ fn text_lines_in(doc: &Document, p: &pdfcraft_model::Page, actual_text: bool, in stream: si, scope: s.scope, paint: s.paint.clone(), + containers: s.containers.clone(), logical_order: s.logical_order, actual_text: s.actual_text, clips: s.state.render_mode >= 4, @@ -601,7 +605,7 @@ fn compatible_word(line: &TextLine, shown: &Shown) -> bool { fn add_shown(lines: &mut Vec, last: &mut Option, s: Shown, stream: usize) { let joins = last.is_some_and(|pen| { let bt = pen.bt; - lines.last().is_some_and(|l| l.scope == s.scope && l.paint == s.paint && l.logical_order == s.logical_order) + lines.last().is_some_and(|l| l.scope == s.scope && l.paint == s.paint && l.containers == s.containers && l.logical_order == s.logical_order) && (bt == s.bt || lines.last().is_some_and(|l| compatible_word(l, &s))) && (s.text.trim().is_empty() || lines.last().is_some_and(|l| continues_font(l, &s))) && (s.text.trim().is_empty() @@ -653,6 +657,7 @@ fn add_shown(lines: &mut Vec, last: &mut Option, s: Shown, stream stream, scope: s.scope, paint: s.paint.clone(), + containers: s.containers.clone(), logical_order: s.logical_order, actual_text: s.actual_text, clips: s.state.render_mode >= 4, @@ -832,8 +837,8 @@ pub(super) fn reading_lines(doc: &Document, page: usize) -> Result<(Vec Result<(Vec Result<(), EditError> { + fn enter( + w: &mut Walk, + resources: &Dict, + name: &[u8], + ts: Ts, + text_left: &mut usize, + containers: std::rc::Rc, + at: Vec, + ) -> Result<(), EditError> { let Some(form) = form_call(w.doc, resources, name, ts.ctm, &w.path, &mut w.budget) else { return Ok(()) }; let ops = parse(&form.data).ops; // The form starts with the graphics state at its `Do`, its own matrix applied. @@ -873,6 +886,8 @@ pub(super) fn reading_lines(doc: &Document, page: usize) -> Result<(Vec Result<(Vec, + /// Its bounding box on the page, whatever matrix drew it. + page: [f64; 4], + /// The first container with the same box on the page: a panel painted again behind each of + /// its rows, under any matrix, is still one panel. + id: usize, +} + +#[derive(Default)] +pub(super) struct Containers { + filled: Vec, + pending: Option, + complex: bool, +} + +impl Containers { + pub(super) fn collect(doc: &Document, ops: &[Op], resources: &Dict) -> Self { + let mut collector = Collector { + doc, + containers: Self::default(), + path: Vec::new(), + budget: super::lines::FormBudget::new(pdfcraft_cos::DecodeBudget::page()), + }; + collector.walk(ops, resources, Matrix::IDENTITY, &[]); + let mut first = std::collections::HashMap::new(); + for (index, container) in collector.containers.filled.iter_mut().enumerate() { + let key = container.page.map(|v| (v * 1000.0).round() as i64); + container.id = *first.entry(key).or_insert(index); + } + collector.containers + } + + fn observe(&mut self, op: &Op, ctm: Matrix, at: &[usize]) { + match op.op.as_slice() { + b"re" => { + if self.pending.is_some() { + self.complex = true; + } + self.pending = op.nums::<4>().zip(ctm.invert()).and_then(|([x, y, width, height], inverse)| { + let rect = [x.min(x + width), y.min(y + height), x.max(x + width), y.max(y + height)]; + (rect.iter().all(|v| v.is_finite()) && rect[2] > rect[0] && rect[3] > rect[1]).then_some(Container { + inverse, + rect, + at: Vec::new(), + page: page_box(rect, ctm), + id: 0, + }) + }); + } + b"m" | b"l" | b"c" | b"v" | b"y" => self.complex = true, + b"f" | b"F" | b"f*" | b"B" | b"B*" | b"b" | b"b*" => { + if !self.complex + && self.filled.len() < 4096 + && let Some(mut rect) = self.pending.take() + { + rect.at = at.to_vec(); + self.filled.push(rect); + } + self.pending = None; + self.complex = false; + } + b"n" | b"S" | b"s" => { + self.pending = None; + self.complex = false; + } + _ => {} + } + } + + /// The panels that hold `rect`'s centre and are taller than it. A highlight or inline shading + /// drawn to the height of its glyphs is not a panel, and neither is a fill painted after the + /// text (a redaction cover): `at` is the text's place in the drawing order, the operator + /// indices from the page down through the forms that draw it. + pub(super) fn membership(&self, rect: [f64; 4], at: &[usize]) -> Vec { + let (x, y) = ((rect[0] + rect[2]) / 2.0, (rect[1] + rect[3]) / 2.0); + let mut ids: Vec = self + .filled + .iter() + .filter_map(|container| { + let ys = + [(rect[0], rect[1]), (rect[2], rect[1]), (rect[0], rect[3]), (rect[2], rect[3])].map(|(x, y)| container.inverse.apply(x, y).1); + let height = ys.iter().copied().fold(f64::NEG_INFINITY, f64::max) - ys.iter().copied().fold(f64::INFINITY, f64::min); + let (x, y) = container.inverse.apply(x, y); + let [left, bottom, right, top] = container.rect; + (container.at.as_slice() < at && x >= left && x <= right && y >= bottom && y <= top && top - bottom >= height * 1.15) + .then_some(container.id) + }) + .collect(); + ids.sort_unstable(); + ids.dedup(); + ids + } +} + +fn page_box([left, bottom, right, top]: [f64; 4], ctm: Matrix) -> [f64; 4] { + let corners = [(left, bottom), (right, bottom), (left, top), (right, top)].map(|(x, y)| ctm.apply(x, y)); + corners.iter().fold([f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY], |[x0, y0, x1, y1], &(x, y)| { + [x0.min(x), y0.min(y), x1.max(x), y1.max(y)] + }) +} + +impl Containers { + /// Whether panel `id` (from [`Containers::membership`]) is no more than a padded highlight + /// around `rect`: under 1.75 times its height on the page. + pub(super) fn hugs(&self, id: usize, rect: [f64; 4]) -> bool { + self.filled.get(id).is_some_and(|panel| panel.page[3] - panel.page[1] < (rect[3] - rect[1]) * 1.75) + } + + /// Whether panel `id` reaches across `rect` from its left edge to its right one on the page. + pub(super) fn spans(&self, id: usize, rect: [f64; 4]) -> bool { + let tolerance = (rect[3] - rect[1]) * 0.25; + self.filled.get(id).is_some_and(|panel| panel.page[0] <= rect[0] + tolerance && panel.page[2] >= rect[2] - tolerance) + } +} + +struct Collector<'a> { + doc: &'a Document, + containers: Containers, + path: Vec, + budget: super::lines::FormBudget, +} + +impl Collector<'_> { + fn walk(&mut self, ops: &[Op], resources: &Dict, initial: Matrix, prefix: &[usize]) { + let mut local = Containers::default(); + let mut ctm = initial; + let mut stack = Vec::new(); + for (i, op) in ops.iter().enumerate() { + let at = [prefix, &[i]].concat(); + local.observe(op, ctm, &at); + match op.op.as_slice() { + b"q" => stack.push(ctm), + b"Q" => { + if let Some(saved) = stack.pop() { + ctm = saved; + } + } + b"cm" => { + if let Some(matrix) = op.nums::<6>() { + ctm = Matrix(matrix).then(&ctm); + } + } + b"Do" => { + if let Some(name) = op.name(0) + && let Some(form) = super::lines::form_call(self.doc, resources, name, ctm, &self.path, &mut self.budget) + { + if let Some(obj) = form.obj { + self.path.push(obj); + } + self.walk(&pdfcraft_content::parse(&form.data).ops, form.resources(resources), form.ctm, &at); + if form.obj.is_some() { + self.path.pop(); + } + } + } + _ => {} + } + } + let remaining = 4096_usize.saturating_sub(self.containers.filled.len()); + self.containers.filled.extend(local.filled.into_iter().take(remaining)); + } +} diff --git a/crates/edit/src/text_regions/grouping.rs b/crates/edit/src/text_regions/grouping.rs index 72a516292d..2195c6c6ae 100644 --- a/crates/edit/src/text_regions/grouping.rs +++ b/crates/edit/src/text_regions/grouping.rs @@ -5,6 +5,7 @@ fn same_plane(a: &TextLine, b: &TextLine) -> bool { let bt = Matrix(b.origin.tm).then(&Matrix(b.origin.ctm)); a.scope == b.scope && a.paint == b.paint + && a.containers == b.containers && [0, 2].iter().all(|axis| { let ax = at.0.get(*axis).copied().unwrap_or(0.0); let ay = at.0.get(axis + 1).copied().unwrap_or(0.0); @@ -351,7 +352,7 @@ fn group_layout(lines: &[TextLine], mixed: bool) -> Vec { // The rewrite sets every row in the first one's horizontal scale. && (prev.origin.state.scale - first.origin.state.scale).abs() < 1e-6 && aligned - && first.size.min(prev.size) >= first.size.max(prev.size) * 0.4 + && super::super::row_style::compatible(prev_row, row, lines) && gap > first.size.min(prev.size) * 0.8 && gap < max_gap }); diff --git a/crates/edit/src/text_regions/styled.rs b/crates/edit/src/text_regions/styled.rs index f257020a22..ff475f4e22 100644 --- a/crates/edit/src/text_regions/styled.rs +++ b/crates/edit/src/text_regions/styled.rs @@ -565,8 +565,51 @@ fn validate_contextual_rows(rows: &[Vec], kept: &[bool]) -> Result<( Ok(()) } +fn line_nominal_width( + index: usize, + source: &TextLine, + chars: &[(char, usize, String)], + metrics: &std::collections::BTreeMap, + space_of: &impl Fn(&str, &Metrics) -> f64, +) -> Option { + let font_name = metrics + .get(&source.font) + .filter(|m| source_encodes(m, &source.text)) + .map(|_| &source.font) + .or_else(|| chars.iter().find(|c| c.1 == index && c.0 != '\n').map(|c| &c.2)); + let width_in = |name: &str, m: &Metrics, text: &str| { + source_width( + m, + text, + source.origin.state.font.as_ref().map_or(1.0, |(_, s)| *s), + space_of(name, m), + source.origin.state.char_spacing, + source.origin.state.word_spacing, + ) + }; + font_name.and_then(|name| metrics.get(name).filter(|m| source_encodes(m, &source.text)).map(|m| width_in(name, m, &source.text))).or_else(|| { + // Generated same-face subsets can form one source line even though no one + // subset encodes it all. Measure the ORIGINAL text, not the edited draft: + // adding characters must retain the source's spacing, not squeeze to its width. + // Shaped text has a separate authoritative advance below. + if source.face.is_none() || pdfcraft_fonts::source_shaping::required(&source.text) { + return None; + } + let face = pdfcraft_fonts::embedding::face_key(&source.base_font); + source.text.chars().try_fold(0.0, |width, ch| { + let text = ch.to_string(); + let (name, m) = metrics + .get_key_value(&source.font) + .filter(|(_, m)| source_encodes(m, &text)) + .or_else(|| metrics.iter().find(|(_, m)| pdfcraft_fonts::embedding::face_key(&m.base_font) == face && source_encodes(m, &text)))?; + Some(width + width_in(name, m, &text)) + }) + }) +} + fn calibration_factors( lines: &[TextLine], + chars: &[(char, usize, String)], metrics: &std::collections::BTreeMap, style: &BlockStyle, overrides: &HashMap, @@ -574,16 +617,8 @@ fn calibration_factors( ) -> HashMap { let mut calibration = HashMap::new(); for (index, source) in lines.iter().enumerate() { - if let Some(metrics) = metrics.get(&source.font) { - let nominal = source_width( - metrics, - &source.text, - source.origin.state.font.as_ref().map_or(1.0, |(_, size)| *size), - space_of(&source.font, metrics), - source.origin.state.char_spacing, - source.origin.state.word_spacing, - ) * source.origin.state.scale - * across(source); + if let Some(nominal) = line_nominal_width(index, source, chars, metrics, &space_of) { + let nominal = nominal * source.origin.state.scale * across(source); let changed_face = style.resource.is_some() || overrides.get(&index).is_some_and(|range| range.family.is_some() || range.resource.is_some()); let factor = if nominal > 0.0 && !changed_face { ((source.rect[2] - source.rect[0]) / nominal).clamp(0.5, 2.0) } else { 1.0 }; @@ -1917,7 +1952,7 @@ pub(crate) fn rewrite_styled_block( spaces.borrow_mut().insert(name.to_owned(), w); w }; - let mut calibration = calibration_factors(lines, &metrics, style, &overrides, space_of); + let mut calibration = calibration_factors(lines, &chars, &metrics, style, &overrides, space_of); fit_to_phrase(&mut calibration, lines, phrase_size); let advance = |item: &(char, usize, String)| -> f64 { let source = lines.get(item.1).unwrap_or(first); diff --git a/crates/edit/src/text_row_style.rs b/crates/edit/src/text_row_style.rs new file mode 100644 index 0000000000..d4db725065 --- /dev/null +++ b/crates/edit/src/text_row_style.rs @@ -0,0 +1,44 @@ +//! Row-level typography compatibility, independent of inline style boundaries. + +use super::TextLine; + +fn family(line: &TextLine) -> String { + const SUFFIXES: [&str; 16] = [ + "bolditalic", + "boldoblique", + "semibold", + "demibold", + "regular", + "boldit", + "italic", + "oblique", + "medium", + "light", + "bold", + "roman", + "psmt", + "mt", + "ps", + "it", + ]; + let mut key = pdfcraft_fonts::embedding::face_key(&line.base_font); + // Weight and style suffixes stack (TimesNewRomanPS-BoldMT), so strip until none is left. + while let Some(base) = SUFFIXES.iter().find_map(|suffix| key.strip_suffix(suffix)).filter(|base| !base.is_empty()) { + key = base.to_owned(); + } + key +} + +pub(super) fn compatible(previous: &[usize], next: &[usize], lines: &[TextLine]) -> bool { + let representative = + |row: &[usize]| row.iter().filter_map(|index| lines.get(*index)).max_by(|a, b| (a.rect[2] - a.rect[0]).total_cmp(&(b.rect[2] - b.rect[0]))); + match (representative(previous), representative(next)) { + (Some(previous), Some(next)) => { + // A row in one of the generated fallback faces holds characters the paragraph's own + // font lacks; the edit chose that face, so it is no change of family. + previous.size.min(next.size) >= previous.size.max(next.size) * 0.65 + && (previous.face.is_some() || next.face.is_some() || family(previous) == family(next)) + } + _ => false, + } +} diff --git a/crates/engine/src/js.rs b/crates/engine/src/js.rs index 6772e9828d..2b20290f6f 100644 --- a/crates/engine/src/js.rs +++ b/crates/engine/src/js.rs @@ -1353,6 +1353,15 @@ impl Session { self.after_script(id, &o, &written); Ok(o) } + + /// The script errors not taken yet, out of what [`Session::take_js_output`] returns; the + /// alerts, console lines and requests stay for that call. A document script's error taken + /// here is reported again when the document scripts fail again on a later edit. + pub fn take_js_errors(&mut self, id: DocId) -> Vec { + let Some(d) = self.docs.iter_mut().find(|d| d.id == id) else { return Vec::new() }; + d.js_output.doc_errors.clear(); + std::mem::take(&mut d.js_output.errors) + } } /// A page's words for form-field detection, in user space (underscore runs split from the diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 3dc4eff088..bec706b6bc 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -7502,6 +7502,38 @@ fn active_xfa_does_not_run_pdf_container_scripts_but_keeps_requested_alerts() { assert!(s.run_javascript(id, "", None).unwrap().alerts.is_empty()); } +#[test] +fn take_js_errors_leaves_the_alerts_for_take_js_output() { + let template = pdfcraft_xfa::fixtures::scripted_template() + .replace("if (qty.rawValue === null) qty.rawValue = 2;", "qty.rawValue = 2; xfa.host.messageBox('opened'); throw new Error('open failed');"); + // Raised time limits: a busy machine does not stop the scripts this checks. + let mut s = Session::new().with_xfa_time_scale(100); + let id = s.open("xfa.pdf", None, Arc::new(pdfcraft_xfa::fixtures::shell(&template)), None).unwrap(); + let errors = s.take_js_errors(id); + assert!(errors.iter().any(|e| e.contains("open failed")), "{errors:?}"); + assert!(s.take_js_errors(id).is_empty()); + let out = s.take_js_output(id); + assert!(out.errors.is_empty(), "{out:?}"); + assert_eq!(out.alerts, [js::Message::plain("opened")]); +} + +#[test] +fn take_js_errors_reports_a_document_scripts_error_again_on_the_next_edit() { + let helpers = "function times\\(a, b\\) { return a * b; } this.getField\\('go'\\).missingTestMethod\\(\\);"; + let mut s = Session::new().with_clock(|| 1_700_000_000); + let id = s.open("order.pdf", None, Arc::new(scripted_form_with(helpers)), None).unwrap(); + assert_eq!(s.take_js_errors(id).len(), 1, "the document script fails at open"); + // The document scripts run again when the script list changes, which each pass does. + for qty in ["4", "5"] { + let script = format!("/* {qty} */ function times(a, b) {{ return a * b; }} this.getField('go').missingTestMethod();"); + s.apply(id, Edit::SetDocumentScript { name: "helpers".into(), script: Some(script) }).unwrap(); + s.apply(id, Edit::SetFieldValue { name: "qty".into(), value: FieldValue::Text(qty.into()) }).unwrap(); + let errors = s.take_js_errors(id); + assert_eq!(errors.len(), 1, "qty {qty}: {errors:?}"); + assert!(errors[0].starts_with("document script 1: TypeError"), "qty {qty}: {errors:?}"); + } +} + #[test] fn active_xfa_without_template_scripts_does_not_initialize_pdf_fallback_scripts() { let template = r#"