mirror of
https://github.com/storytold/pdfcraft.git
synced 2026-12-01 02:36:02 +01:00
Merge remote-tracking branch 'origin/main' into ic51-3242
# Conflicts: # crates/render/src/text/layout.rs
This commit is contained in:
commit
ea25e82618
26 files changed
+2107
-98
No files matched your search
@@ -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.
|
||||
|
||||
+33
-1
@@ -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
|
||||
@@ -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"
|
||||
@@ -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 });
|
||||
}
|
||||
|
||||
@@ -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<Value> {
|
||||
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::<Vec<_>>());
|
||||
let mut warnings: Vec<String> = 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()
|
||||
|
||||
@@ -183,7 +183,7 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
)),
|
||||
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<ToolDef> {
|
||||
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(
|
||||
|
||||
@@ -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(
|
||||
"<calculate><script contentType=\"application/x-javascript\">qty.rawValue * price.rawValue</script></calculate>",
|
||||
"<calculate><script contentType=\"application/x-javascript\">if (qty.rawValue == 4) throw new Error('fill failed'); qty.rawValue * price.rawValue</script></calculate>",
|
||||
);
|
||||
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]
|
||||
|
||||
@@ -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<ObjRef>, on_page: Option<&HashSet<ObjRef>>) -> 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<ObjRef>, on_page: Option<&
|
||||
let mut known = HashMap::new();
|
||||
let survivors: Vec<Object> =
|
||||
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<ObjRef> = HashSet::new();
|
||||
let mut stack: Vec<ObjRef> = 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<Object> = 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)))?,
|
||||
|
||||
+57
-19
@@ -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<usize>],
|
||||
target_idx: usize,
|
||||
target_unit: &'a std::ops::Range<usize>,
|
||||
order: ArrangeOrder,
|
||||
has_other_paint: bool,
|
||||
has_paint_before: bool,
|
||||
has_paint_after: bool,
|
||||
) -> Result<(&'a std::ops::Range<usize>, 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<usize>) -> (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));
|
||||
}
|
||||
}
|
||||
@@ -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::<Vec<_>>(), ["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::<Vec<_>>(), ["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::<Vec<_>>(), ["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::<Vec<_>>(), ["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::<Vec<_>>(), ["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::<Vec<_>>(), ["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::<Vec<_>>(), ["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::<Vec<_>>(), ["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::<Vec<_>>(), ["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::<Vec<_>>(), ["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::<Vec<_>>(), ["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::<Vec<_>>(), ["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::<Vec<_>>(), ["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::<Vec<_>>());
|
||||
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::<Vec<_>>(), ["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::<Vec<_>>(), ["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::<Vec<_>>(), ["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::<Vec<_>>(), ["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::<Vec<_>>(), ["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::<Vec<_>>(), ["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::<Vec<_>>(), ["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::<Vec<_>>(), ["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::<Vec<_>>(), ["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::<Vec<_>>(), ["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::<Vec<_>>(), ["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::<Vec<_>>(), ["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::<Vec<_>>(), ["Panel", "Outside"]);
|
||||
}
|
||||
+467
-8
@@ -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<pdfcraft_cos::ObjRef> = 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<String> = 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<usize> = 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> <FFFF> 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::<Vec<_>>(), ["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> <FF> 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();
|
||||
|
||||
@@ -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<usize>,
|
||||
/// The layers and graphics state parameters it is drawn in; see [`Paint`].
|
||||
paint: Paint,
|
||||
containers: Vec<usize>,
|
||||
/// 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,
|
||||
|
||||
@@ -479,6 +479,7 @@ pub(super) struct Shown {
|
||||
pub(super) decodable: bool,
|
||||
pub(super) scope: Option<usize>,
|
||||
pub(super) paint: Paint,
|
||||
pub(super) containers: Vec<usize>,
|
||||
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<Option<Vec<u8>>>,
|
||||
/// 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<super::containers::Containers>,
|
||||
/// The operator indices of the `Do`s, from the page down, that draw these operators.
|
||||
pub(super) at: Vec<usize>,
|
||||
/// 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<usize, usize> = 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
|
||||
}
|
||||
@@ -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<TextLine>, last: &mut Option<Pen>, 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<TextLine>, last: &mut Option<Pen>, 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<TextLine
|
||||
let mut last_stream = None;
|
||||
let mut forms = invoked.into_iter().peekable();
|
||||
for s in shown {
|
||||
while let Some((_, name, ts)) = forms.next_if(|f| f.0 < s.op) {
|
||||
enter(w, resources, &name, ts, &mut carry.text_left)?;
|
||||
while let Some((i, name, ts)) = forms.next_if(|f| f.0 < s.op) {
|
||||
enter(w, resources, &name, ts, &mut carry.text_left, carry.containers.clone(), [carry.at.as_slice(), &[i]].concat())?;
|
||||
// Text after a form starts a new line.
|
||||
last = None;
|
||||
}
|
||||
@@ -850,13 +855,21 @@ pub(super) fn reading_lines(doc: &Document, page: usize) -> Result<(Vec<TextLine
|
||||
}
|
||||
add_shown(&mut w.lines, &mut last, s, si);
|
||||
}
|
||||
for (_, name, ts) in forms {
|
||||
enter(w, resources, &name, ts, &mut carry.text_left)?;
|
||||
for (i, name, ts) in forms {
|
||||
enter(w, resources, &name, ts, &mut carry.text_left, carry.containers.clone(), [carry.at.as_slice(), &[i]].concat())?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// `text_left`: the page's text budget, shared with the forms the page draws.
|
||||
fn enter(w: &mut Walk, resources: &Dict, name: &[u8], ts: Ts, text_left: &mut usize) -> Result<(), EditError> {
|
||||
fn enter(
|
||||
w: &mut Walk,
|
||||
resources: &Dict,
|
||||
name: &[u8],
|
||||
ts: Ts,
|
||||
text_left: &mut usize,
|
||||
containers: std::rc::Rc<super::containers::Containers>,
|
||||
at: Vec<usize>,
|
||||
) -> 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<TextLine
|
||||
layers: Vec::new(),
|
||||
text_left: *text_left,
|
||||
gap_space: false,
|
||||
containers,
|
||||
at,
|
||||
};
|
||||
let stream = w.next_stream;
|
||||
w.next_stream = w.next_stream.saturating_add(1);
|
||||
@@ -899,6 +914,7 @@ pub(super) fn reading_lines(doc: &Document, page: usize) -> Result<(Vec<TextLine
|
||||
let pieces = joined(&streams);
|
||||
let ops = pieces.parse().ops;
|
||||
let stream_of = |i: usize| ops.get(i).map_or(0, |op| pieces.pieces_of(op).0);
|
||||
carry.containers = std::rc::Rc::new(super::containers::Containers::collect(doc, &ops, &res));
|
||||
walk(&mut w, &ops, &res, &mut carry, &stream_of)?;
|
||||
let mut lines = w.lines;
|
||||
// A visual-order Indic font draws pre-base vowel signs before their consonant.
|
||||
|
||||
@@ -0,0 +1,171 @@
|
||||
//! Filled rectangular panel boundaries used by editable text grouping.
|
||||
|
||||
use pdfcraft_content::{Matrix, Op};
|
||||
use pdfcraft_cos::{Dict, Document, ObjRef};
|
||||
|
||||
struct Container {
|
||||
inverse: Matrix,
|
||||
rect: [f64; 4],
|
||||
/// Where it is painted in the page's drawing order (see [`Containers::membership`]).
|
||||
at: Vec<usize>,
|
||||
/// 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<Container>,
|
||||
pending: Option<Container>,
|
||||
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<usize> {
|
||||
let (x, y) = ((rect[0] + rect[2]) / 2.0, (rect[1] + rect[3]) / 2.0);
|
||||
let mut ids: Vec<usize> = 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<ObjRef>,
|
||||
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));
|
||||
}
|
||||
}
|
||||
@@ -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<TextBlock> {
|
||||
// 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
|
||||
});
|
||||
|
||||
@@ -565,8 +565,51 @@ fn validate_contextual_rows(rows: &[Vec<StyledChar>], kept: &[bool]) -> Result<(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn line_nominal_width(
|
||||
index: usize,
|
||||
source: &TextLine,
|
||||
chars: &[(char, usize, String)],
|
||||
metrics: &std::collections::BTreeMap<String, Metrics>,
|
||||
space_of: &impl Fn(&str, &Metrics) -> f64,
|
||||
) -> Option<f64> {
|
||||
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<String, Metrics>,
|
||||
style: &BlockStyle,
|
||||
overrides: &HashMap<usize, &RangeStyle>,
|
||||
@@ -574,16 +617,8 @@ fn calibration_factors(
|
||||
) -> HashMap<usize, f64> {
|
||||
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);
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
@@ -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<String> {
|
||||
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
|
||||
|
||||
@@ -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#"<template xmlns="http://www.xfa.org/schema/xfa-template/3.3/">
|
||||
|
||||
+168
-27
@@ -69,6 +69,8 @@ pub struct Metrics {
|
||||
/// Subset CIDFontType2 only: one bit per CID (below 65 536) whose glyph has an outline in the
|
||||
/// embedded program. See [`cids_with_outlines`].
|
||||
outlined_cids: Vec<u64>,
|
||||
/// Whether this font is an OCR placeholder font with no real letterforms (e.g. `/Glyphless`).
|
||||
glyphless: bool,
|
||||
/// A stream these metrics come from (a CMap, the program, `/CIDToGIDMap`, a Type 3 glyph
|
||||
/// description) was left unread because the decode allowance [`Metrics::from_dict_within`]
|
||||
/// was given was spent: what it would have decided (code lengths, CIDs, widths, meanings, a
|
||||
@@ -93,6 +95,79 @@ fn dict(doc: &Document, o: Option<&Object>) -> Option<Dict> {
|
||||
o.and_then(|o| doc.resolve(o).as_dict().cloned())
|
||||
}
|
||||
|
||||
/// Strip a six-letter uppercase `ABCDEF+` subset prefix, if present.
|
||||
fn strip_subset_prefix(name: &str) -> &str {
|
||||
name.split_once('+').filter(|(tag, _)| tag.len() == 6 && tag.bytes().all(|b| b.is_ascii_uppercase())).map_or(name, |(_, rest)| rest)
|
||||
}
|
||||
|
||||
/// Whether `name` identifies an OCR placeholder font that carries widths and Unicode mappings
|
||||
/// for invisible (`3 Tr`) text selection but no real letterforms.
|
||||
fn glyphless_font_name(name: &str) -> bool {
|
||||
let stem = strip_subset_prefix(name).to_ascii_lowercase();
|
||||
stem.starts_with("glyphless") || stem.starts_with("hiddenhorzocr") || stem.starts_with("hiddenvertocr")
|
||||
}
|
||||
|
||||
/// Whether `font` carries a known OCR placeholder font name (`Glyphless*`, `HiddenHorzOCR`,
|
||||
/// `HiddenVertOCR`, with optional six-letter `ABCDEF+` subset prefix).
|
||||
fn has_glyphless_font_name(doc: &Document, font: &Dict) -> bool {
|
||||
let descendant = dict(doc, font.get(b"DescendantFonts").and_then(|o| doc.resolve(o).as_array().and_then(|a| a.first()).cloned()).as_ref());
|
||||
let descriptor = dict(doc, descendant.as_ref().unwrap_or(font).get(b"FontDescriptor"));
|
||||
[font.name(b"BaseFont"), descendant.as_ref().and_then(|d| d.name(b"BaseFont")), descriptor.as_ref().and_then(|d| d.name(b"FontName"))]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.any(|name| glyphless_font_name(&String::from_utf8_lossy(name)))
|
||||
}
|
||||
|
||||
/// If every non-zero `/CIDToGIDMap` entry (skipping CID 0) maps to the exact same glyph ID and
|
||||
/// there are at least 64 such entries, returns that shared glyph ID.
|
||||
fn shared_single_gid(map: &[u8]) -> Option<usize> {
|
||||
let mut gids = map.as_chunks::<2>().0.iter().skip(1).map(|gid| usize::from(u16::from_be_bytes(*gid))).filter(|&gid| gid != 0);
|
||||
let mapped_gid = gids.next()?;
|
||||
let mut mapped = 1usize;
|
||||
for gid in gids {
|
||||
if gid != mapped_gid {
|
||||
return None;
|
||||
}
|
||||
mapped += 1;
|
||||
}
|
||||
(mapped >= 64).then_some(mapped_gid)
|
||||
}
|
||||
|
||||
/// Returns `Some(gid)` when `loca` has exactly one outlined glyph ID (`>= 1`), stopping at the
|
||||
/// second outlined glyph.
|
||||
fn only_outlined_gid_from_loca(loca: &skrifa::raw::tables::loca::Loca<'_>) -> Option<usize> {
|
||||
let mut outlined =
|
||||
(1..loca.len().min(0x1_0000)).filter(|&gid| loca.get_raw(gid).zip(loca.get_raw(gid + 1)).is_some_and(|(start, end)| end > start));
|
||||
let gid = outlined.next()?;
|
||||
outlined.next().is_none().then_some(gid)
|
||||
}
|
||||
|
||||
/// Returns `Some(gid)` when the TrueType program in `face` has exactly one outlined glyph ID.
|
||||
fn only_outlined_gid(face: &skrifa::FontRef<'_>) -> Option<usize> {
|
||||
use skrifa::raw::TableProvider as _;
|
||||
let loca = face.loca(None).ok()?;
|
||||
only_outlined_gid_from_loca(&loca)
|
||||
}
|
||||
|
||||
/// Whether `descendant`'s `/CIDToGIDMap` stream maps at least 64 CIDs solely to `mapped_gid`.
|
||||
/// Returns `None` if decoding failed or spent the allowance.
|
||||
fn stream_shares_single_gid(doc: &Document, descendant: Option<&Dict>, mapped_gid: usize, budget: &mut DecodeBudget) -> Option<bool> {
|
||||
let cid_to_gid = descendant.and_then(|d| d.get(b"CIDToGIDMap")).map(|o| doc.resolve(o));
|
||||
let Some(Object::Stream(map)) = cid_to_gid.as_deref() else { return Some(false) };
|
||||
let mut reads = Reads::new(doc, budget);
|
||||
let Some(map) = reads.decode(map, MAX_CID_TO_GID) else {
|
||||
return (!reads.refused).then_some(false);
|
||||
};
|
||||
Some(shared_single_gid(&map) == Some(mapped_gid))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn is_glyphless(doc: &Document, font: &Dict) -> bool {
|
||||
let mut budget = DecodeBudget::new(usize::MAX, 0);
|
||||
let mut reads = Reads::new(doc, &mut budget);
|
||||
has_glyphless_font_name(doc, font) || composite_outlines_and_glyphless(doc, font, false, None, &mut reads).1
|
||||
}
|
||||
|
||||
/// Whether `font`'s `/Encoding` is the name Identity-H, given directly or through a reference,
|
||||
/// as [`Metrics::from_dict`] reads it (a Type 0 font's `/Encoding` may be indirect).
|
||||
fn identity_h(doc: &Document, font: &Dict) -> bool {
|
||||
@@ -102,9 +177,7 @@ fn identity_h(doc: &Document, font: &Dict) -> bool {
|
||||
/// Whether `base_font` (subset tag allowed) names a legacy Indic font family that is laid out in
|
||||
/// visual order (Kruti Dev, DevLys, Chanakya, Shusha, Shivaji, Walkman, Akruti, APS-DV, DV-TT…).
|
||||
fn legacy_indic_font(base_font: &str) -> bool {
|
||||
let name =
|
||||
base_font.split_once('+').filter(|(tag, _)| tag.len() == 6 && tag.bytes().all(|b| b.is_ascii_uppercase())).map_or(base_font, |(_, n)| n);
|
||||
let name = name.to_ascii_lowercase();
|
||||
let name = strip_subset_prefix(base_font).to_ascii_lowercase();
|
||||
["kruti", "devlys", "chanakya", "shusha", "shivaji", "walkman", "akruti"].iter().any(|n| name.contains(n))
|
||||
|| ["aps-", "dv-"].iter().any(|p| name.starts_with(p))
|
||||
}
|
||||
@@ -125,6 +198,9 @@ const MAX_SFNT: usize = 16 << 20;
|
||||
/// streams of the metrics read that adapts a program without a Unicode cmap.
|
||||
pub fn embedded_sfnt_within(doc: &Document, font: &Dict, budget: &mut DecodeBudget) -> Option<Vec<u8>> {
|
||||
use skrifa::{MetadataProvider as _, raw::TableProvider as _};
|
||||
if has_glyphless_font_name(doc, font) {
|
||||
return None;
|
||||
}
|
||||
let descendant = dict(doc, font.get(b"DescendantFonts").and_then(|o| doc.resolve(o).as_array().and_then(|a| a.first()).cloned()).as_ref());
|
||||
let descriptor = dict(doc, descendant.as_ref().unwrap_or(font).get(b"FontDescriptor"))?;
|
||||
for key in [b"FontFile2".as_slice(), b"FontFile3".as_slice()] {
|
||||
@@ -140,10 +216,16 @@ pub fn embedded_sfnt_within(doc: &Document, font: &Dict, budget: &mut DecodeBudg
|
||||
continue;
|
||||
}
|
||||
let own_cmap = face.charmap().mappings().next().is_some();
|
||||
let single_gid = only_outlined_gid(&face);
|
||||
// A legacy THSarabunPSK subset may keep a Latin-only cmap beside its Thai glyphs, which
|
||||
// only the PDF's verified maps reach (`composite_glyph_maps`); other programs keep theirs.
|
||||
let base_font = font.name(b"BaseFont").map(String::from_utf8_lossy).unwrap_or_default();
|
||||
if own_cmap && !base_font.rsplit('+').next().is_some_and(|f| f.starts_with("THSarabunPSK")) {
|
||||
if let Some(gid) = single_gid
|
||||
&& stream_shares_single_gid(doc, descendant.as_ref(), gid, budget) != Some(false)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
return Some(bytes);
|
||||
}
|
||||
// A composite font's cmap is rebuilt only through Identity-H codes (`composite_glyph_maps`):
|
||||
@@ -151,6 +233,11 @@ pub fn embedded_sfnt_within(doc: &Document, font: &Dict, budget: &mut DecodeBudg
|
||||
// cmap of its own is kept as it is, as when the rebuild finds nothing.
|
||||
if font.name(b"Subtype") == Some(b"Type0") && !identity_h(doc, font) {
|
||||
if own_cmap {
|
||||
if let Some(gid) = single_gid
|
||||
&& stream_shares_single_gid(doc, descendant.as_ref(), gid, budget) != Some(false)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
return Some(bytes);
|
||||
}
|
||||
continue;
|
||||
@@ -158,9 +245,10 @@ pub fn embedded_sfnt_within(doc: &Document, font: &Dict, budget: &mut DecodeBudg
|
||||
// PDF subsets may remove the Unicode cmap entirely. Rebuild an editor-only
|
||||
// cmap from ToUnicode and the actual CID-to-glyph map; source bytes stay unchanged.
|
||||
// Metrics read past the allowance, its widths' read of the program again included,
|
||||
// adapt no copy.
|
||||
let metrics = Metrics::from_dict_within(doc, font, budget);
|
||||
if metrics.past_allowance {
|
||||
// adapt no copy. Skip redundant structural glyphless check when >=2 (or 0) outlined glyphs exist.
|
||||
let known_glyphless = single_gid.is_none().then_some(false);
|
||||
let metrics = Metrics::from_dict_with_glyphless(doc, font, budget, known_glyphless);
|
||||
if metrics.glyphless || metrics.past_allowance {
|
||||
continue;
|
||||
}
|
||||
let mut mappings = std::collections::BTreeMap::new();
|
||||
@@ -208,35 +296,66 @@ pub fn embedded_sfnt_within(doc: &Document, font: &Dict, budget: &mut DecodeBudg
|
||||
None
|
||||
}
|
||||
|
||||
/// The CIDs (below 65 536) of a Type 0 font over an embedded TrueType program whose glyph has
|
||||
/// outline data, through `/CIDToGIDMap`; empty when the program or the map can't be read.
|
||||
/// Subsetters keep glyph ids and empty the glyphs they drop, so an empty glyph is a missing one.
|
||||
fn cids_with_outlines(doc: &Document, font: &Dict, reads: &mut Reads<'_>) -> Vec<u64> {
|
||||
/// The CIDs (below 65 536) of a subset Type 0 font over an embedded TrueType program whose glyph
|
||||
/// has outline data, plus whether the font is a shared-glyph placeholder font. Decodes
|
||||
/// `FontFile2` and `/CIDToGIDMap` at most once each against `reads`.
|
||||
fn composite_outlines_and_glyphless(
|
||||
doc: &Document,
|
||||
font: &Dict,
|
||||
is_subset: bool,
|
||||
known_glyphless: Option<bool>,
|
||||
reads: &mut Reads<'_>,
|
||||
) -> (Vec<u64>, bool) {
|
||||
use skrifa::raw::TableProvider as _;
|
||||
if known_glyphless == Some(true) {
|
||||
return (Vec::new(), true);
|
||||
}
|
||||
let Some(descendant) = dict(doc, font.get(b"DescendantFonts").and_then(|o| doc.resolve(o).as_array().and_then(|a| a.first()).cloned()).as_ref())
|
||||
else {
|
||||
return Vec::new();
|
||||
return (Vec::new(), false);
|
||||
};
|
||||
let Some(program) = dict(doc, descendant.get(b"FontDescriptor")).and_then(|d| d.get(b"FontFile2").cloned()) else { return Vec::new() };
|
||||
let program = doc.resolve(&program);
|
||||
let Object::Stream(stream) = program.as_ref() else { return Vec::new() };
|
||||
let Some(bytes) = reads.decode(stream, MAX_SFNT) else { return Vec::new() };
|
||||
let Some(loca) = skrifa::FontRef::from_index(&bytes, 0).ok().and_then(|face| face.loca(None).ok()) else { return Vec::new() };
|
||||
let font_file2 = |doc: &Document, reads: &mut Reads<'_>| {
|
||||
let program = dict(doc, descendant.get(b"FontDescriptor")).and_then(|d| d.get(b"FontFile2").cloned())?;
|
||||
let program = doc.resolve(&program);
|
||||
let Object::Stream(stream) = program.as_ref() else { return None };
|
||||
reads.decode(stream, MAX_SFNT)
|
||||
};
|
||||
if !is_subset {
|
||||
if known_glyphless == Some(false) {
|
||||
return (Vec::new(), false);
|
||||
}
|
||||
let cid_to_gid = descendant.get(b"CIDToGIDMap").map(|o| doc.resolve(o));
|
||||
let Some(Object::Stream(map)) = cid_to_gid.as_deref() else { return (Vec::new(), false) };
|
||||
let Some(map) = reads.decode(map, MAX_CID_TO_GID) else { return (Vec::new(), false) };
|
||||
let Some(mapped_gid) = shared_single_gid(&map) else { return (Vec::new(), false) };
|
||||
let Some(bytes) = font_file2(doc, reads) else { return (Vec::new(), false) };
|
||||
let glyphless = skrifa::FontRef::from_index(&bytes, 0).ok().and_then(|face| only_outlined_gid(&face)) == Some(mapped_gid);
|
||||
return (Vec::new(), glyphless);
|
||||
}
|
||||
let Some(bytes) = font_file2(doc, reads) else { return (Vec::new(), false) };
|
||||
let Some(loca) = skrifa::FontRef::from_index(&bytes, 0).ok().and_then(|face| face.loca(None).ok()) else { return (Vec::new(), false) };
|
||||
let outlined = |gid: u32| loca.get_raw(gid as usize).zip(loca.get_raw(gid as usize + 1)).is_some_and(|(start, end)| end > start);
|
||||
match descendant.get(b"CIDToGIDMap").map(|o| doc.resolve(o)).as_deref() {
|
||||
None | Some(Object::Name(_)) => bit_set_below_64k((0..loca.len().min(0x1_0000) as u32).filter(|&gid| outlined(gid))),
|
||||
None | Some(Object::Name(_)) => (bit_set_below_64k((0..loca.len().min(0x1_0000) as u32).filter(|&gid| outlined(gid))), false),
|
||||
Some(Object::Stream(map)) => {
|
||||
let Some(map) = reads.decode(map, MAX_CID_TO_GID) else { return Vec::new() };
|
||||
bit_set_below_64k(
|
||||
let Some(map) = reads.decode(map, MAX_CID_TO_GID) else { return (Vec::new(), false) };
|
||||
if known_glyphless.is_none()
|
||||
&& let Some(single_gid) = only_outlined_gid_from_loca(&loca)
|
||||
&& shared_single_gid(&map) == Some(single_gid)
|
||||
{
|
||||
return (Vec::new(), true);
|
||||
}
|
||||
let cids = bit_set_below_64k(
|
||||
map.as_chunks::<2>()
|
||||
.0
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, gid)| outlined(u32::from(u16::from_be_bytes(**gid))))
|
||||
.map(|(cid, _)| cid as u32),
|
||||
)
|
||||
);
|
||||
(cids, false)
|
||||
}
|
||||
Some(_) => Vec::new(),
|
||||
Some(_) => (Vec::new(), false),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -915,6 +1034,7 @@ impl Metrics {
|
||||
code_len: 1,
|
||||
explicit_reverse: (32..127u8).map(|c| (char::from(c), u32::from(c))).collect(),
|
||||
outlined_cids: Vec::new(),
|
||||
glyphless: false,
|
||||
past_allowance: false,
|
||||
codespaces_dropped: false,
|
||||
}
|
||||
@@ -933,6 +1053,10 @@ impl Metrics {
|
||||
/// it reads (a page's, say): each stream pays for what it decodes, usable or not. A stream the
|
||||
/// allowance can't pay for is left unread, and [`Metrics::past_allowance`] says so.
|
||||
pub fn from_dict_within(doc: &Document, font: &Dict, budget: &mut DecodeBudget) -> Self {
|
||||
Self::from_dict_with_glyphless(doc, font, budget, None)
|
||||
}
|
||||
|
||||
fn from_dict_with_glyphless(doc: &Document, font: &Dict, budget: &mut DecodeBudget, known_glyphless: Option<bool>) -> Self {
|
||||
let mut reads = Reads::new(doc, budget);
|
||||
let mut m = Self::read_metrics(doc, font, &mut reads);
|
||||
let base = base_font_name(doc, font);
|
||||
@@ -941,8 +1065,11 @@ impl Metrics {
|
||||
m.bold |= bold;
|
||||
m.italic |= italic;
|
||||
m.base_font = base;
|
||||
if m.composite && m.subset {
|
||||
m.outlined_cids = cids_with_outlines(doc, font, &mut reads);
|
||||
m.glyphless = has_glyphless_font_name(doc, font);
|
||||
if m.composite && !m.glyphless {
|
||||
let (outlines, structural_glyphless) = composite_outlines_and_glyphless(doc, font, m.subset, known_glyphless, &mut reads);
|
||||
m.outlined_cids = outlines;
|
||||
m.glyphless = structural_glyphless;
|
||||
}
|
||||
m.code_len = match &m.codes {
|
||||
Codes::One => 1,
|
||||
@@ -950,7 +1077,7 @@ impl Metrics {
|
||||
Codes::Ranges(r) => r.last().map_or(2, |x| x.0.clamp(1, 4)),
|
||||
};
|
||||
m.unicode = unicode_map(doc, font, m.composite, &mut reads);
|
||||
if m.std14.is_some() {
|
||||
if m.std14.is_some() && !m.glyphless {
|
||||
embedded_widths(doc, font, &mut m, &mut reads);
|
||||
}
|
||||
m.past_allowance = reads.refused;
|
||||
@@ -1200,6 +1327,9 @@ impl Metrics {
|
||||
/// Only asked for codes the font's Unicode mapping gives: a subset's `ToUnicode` lists the
|
||||
/// glyphs it kept, while its `/W` leaves out those of the default width (#1443).
|
||||
fn has_glyph(&self, code: u32) -> bool {
|
||||
if self.glyphless {
|
||||
return false;
|
||||
}
|
||||
if self.composite {
|
||||
let cid = self.cid(code);
|
||||
// CID 0 is `.notdef` (an unmapped code lands there too), whatever ToUnicode says: Word
|
||||
@@ -1249,9 +1379,9 @@ impl Metrics {
|
||||
/// no glyph in it, or the metrics were read past their allowance (the caller then substitutes
|
||||
/// another font). Empty text needs no verified glyph and always encodes.
|
||||
pub fn encode(&self, text: &str) -> Option<Vec<u8>> {
|
||||
// A refused read cannot establish the mappings or glyphs needed to write new text.
|
||||
// Empty text needs neither and remains usable for erasing existing text.
|
||||
if self.past_allowance && !text.is_empty() {
|
||||
// A glyphless OCR font has no real letterforms; a refused read cannot establish the mappings
|
||||
// or glyphs needed to write new text (empty text still encodes unless glyphless).
|
||||
if self.glyphless || (self.past_allowance && !text.is_empty()) {
|
||||
return None;
|
||||
}
|
||||
// The lowest code showing each wanted character. Explicit entries and the encoding are
|
||||
@@ -2067,6 +2197,17 @@ mod encoding_tests {
|
||||
}
|
||||
assert_eq!(budget.remaining(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn named_glyphless_ocr_fonts_are_recognised_without_a_shared_gid_map() {
|
||||
for base in ["GlyphlessFont", "ABCDEF+Glyphless", "HiddenHorzOCR", "ABCDEF+HiddenVertOCR"] {
|
||||
let (doc, d) = simple(base, None, Some(Object::name("WinAnsiEncoding")));
|
||||
let m = Metrics::from_dict(&doc, &d);
|
||||
assert!(m.glyphless && is_glyphless(&doc, &d), "{base} must be marked glyphless by name alone");
|
||||
assert!(!m.has_glyph(b'A'.into()), "{base} must not claim visible glyph outlines");
|
||||
assert!(m.encode("A").is_none(), "{base} must not encode replacement text");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
mod thai;
|
||||
|
||||
@@ -135,6 +135,161 @@ fn embedded_editor_fonts_are_validated_without_installing_or_exporting() {
|
||||
assert!(embedded_sfnt(&doc, &Dict::new()).is_none());
|
||||
}
|
||||
|
||||
/// #3803: OCR placeholder fonts (`/Glyphless`, `/GlyphlessFont`, `/HiddenHorzOCR`, or a
|
||||
/// dummy TrueType program whose non-zero CIDs all share a single rectangle glyph) still decode
|
||||
/// and measure the invisible OCR layer, but never encode replacement text or expose their
|
||||
/// dummy program to the inline editor.
|
||||
#[test]
|
||||
fn glyphless_ocr_fonts_decode_and_measure_without_encoding_or_exposing_sfnt() {
|
||||
use pdfcraft_cos::Stream;
|
||||
// Build a 1-outline TrueType program (only GID 1 has an outline) from Inter-Regular.ttf.
|
||||
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;
|
||||
let mut zero_glyph_ttf = one_glyph_ttf.clone();
|
||||
zero_glyph_ttf[loca_off..loca_off + loca_len].fill(0);
|
||||
// Set loca[0] = 0, loca[1] = 0, and loca[2..] = 4 so only GID 1 has start < end.
|
||||
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();
|
||||
}
|
||||
|
||||
for base in ["Glyphless", "GlyphlessFont", "ABCDEF+GlyphlessFont", "HiddenHorzOCR", "HiddenVertOCR", "CustomOCR"] {
|
||||
let mut doc = Document::new_empty();
|
||||
let program = doc.add(Object::Stream(Stream::flate(Dict::new(), &one_glyph_ttf)));
|
||||
let cmap = b"1 begincodespacerange <0000> <FFFF> endcodespacerange 1 beginbfrange <0000> <00FF> <0000> endbfrange";
|
||||
let tu = doc.add(Object::Stream(Stream::flate(Dict::new(), cmap)));
|
||||
let mut descriptor = Dict::new();
|
||||
descriptor.set(b"Type".to_vec(), Object::name("FontDescriptor"));
|
||||
descriptor.set(b"FontName".to_vec(), Object::name(base));
|
||||
descriptor.set(b"FontFile2".to_vec(), Object::Ref(program));
|
||||
let mut desc = Dict::new();
|
||||
desc.set(b"Type".to_vec(), Object::name("Font"));
|
||||
desc.set(b"Subtype".to_vec(), Object::name("CIDFontType2"));
|
||||
desc.set(b"BaseFont".to_vec(), Object::name(base));
|
||||
if base == "CustomOCR" {
|
||||
let cid_to_gid = doc.add(Object::Stream(Stream::flate(Dict::new(), &[0, 1].repeat(256))));
|
||||
desc.set(b"CIDToGIDMap".to_vec(), Object::Ref(cid_to_gid));
|
||||
}
|
||||
desc.set(b"DW".to_vec(), Object::Int(500));
|
||||
desc.set(b"W".to_vec(), Object::Array(vec![Object::Int(32), Object::Array(vec![Object::Int(285)])]));
|
||||
desc.set(b"FontDescriptor".to_vec(), Object::Dict(descriptor));
|
||||
let f = font(
|
||||
&mut doc,
|
||||
vec![
|
||||
("Subtype", Object::name("Type0")),
|
||||
("BaseFont", Object::name(base)),
|
||||
("Encoding", Object::name("Identity-H")),
|
||||
("DescendantFonts", Object::Array(vec![Object::Dict(desc)])),
|
||||
("ToUnicode", Object::Ref(tu)),
|
||||
],
|
||||
);
|
||||
assert!(embedded_sfnt(&doc, &f).is_none(), "{base} must not be exposed as an editor sfnt");
|
||||
let m = Metrics::from_dict(&doc, &f);
|
||||
assert_eq!(m.decode(b"\x00D\x00e\x00 \x00k"), "De k", "{base} still decodes OCR text");
|
||||
assert!((m.width(32) - 0.285).abs() < 1e-9 && (m.width(68) - 0.5).abs() < 1e-9, "{base} still measures OCR widths");
|
||||
assert_eq!(m.encode("De"), None, "{base} must not encode visible replacement text");
|
||||
assert_eq!(m.encode(" "), None, "{base} must not encode spaces");
|
||||
assert_eq!(m.encode(""), None, "{base} must not claim empty words");
|
||||
}
|
||||
|
||||
// Regression fixture 1: a valid whitespace-only subset (0 outlined glyphs in `loca` because
|
||||
// space has no contours) remains exposed as an editor sfnt and encodes whitespace.
|
||||
let mut doc = Document::new_empty();
|
||||
let program = doc.add(Object::Stream(Stream::flate(Dict::new(), &zero_glyph_ttf)));
|
||||
let mut descriptor = Dict::new();
|
||||
descriptor.set(b"FontName".to_vec(), Object::name("ABCDEF+WhitespaceSubset"));
|
||||
descriptor.set(b"FontFile2".to_vec(), Object::Ref(program));
|
||||
let whitespace_subset = font(
|
||||
&mut doc,
|
||||
vec![
|
||||
("Subtype", Object::name("TrueType")),
|
||||
("BaseFont", Object::name("ABCDEF+WhitespaceSubset")),
|
||||
("Encoding", Object::name("WinAnsiEncoding")),
|
||||
("FirstChar", Object::Int(32)),
|
||||
("LastChar", Object::Int(32)),
|
||||
("Widths", Object::Array(vec![Object::Int(250)])),
|
||||
("FontDescriptor", Object::Dict(descriptor)),
|
||||
],
|
||||
);
|
||||
assert!(embedded_sfnt(&doc, &whitespace_subset).is_some(), "whitespace-only subset keeps its sfnt");
|
||||
assert_eq!(Metrics::from_dict(&doc, &whitespace_subset).encode(" ").as_deref(), Some(&[32][..]));
|
||||
|
||||
// Regression fixture 2: a 1-glyph font with intentional cmap aliases (e.g. U+002D, U+2010,
|
||||
// U+2011 hyphen variants sharing GID 1) remains exposed and encodes its characters.
|
||||
let mut alias_cmap_ttf = one_glyph_ttf.clone();
|
||||
append_editor_cmap(&mut alias_cmap_ttf, &std::collections::BTreeMap::from([(0x002D, 1), (0x2010, 1), (0x2011, 1)])).unwrap();
|
||||
let program = doc.add(Object::Stream(Stream::flate(Dict::new(), &alias_cmap_ttf)));
|
||||
let mut descriptor = Dict::new();
|
||||
descriptor.set(b"FontName".to_vec(), Object::name("ABCDEF+HyphenSubset"));
|
||||
descriptor.set(b"FontFile2".to_vec(), Object::Ref(program));
|
||||
let cmap_alias_font = font(
|
||||
&mut doc,
|
||||
vec![
|
||||
("Subtype", Object::name("TrueType")),
|
||||
("BaseFont", Object::name("ABCDEF+HyphenSubset")),
|
||||
("Encoding", Object::name("WinAnsiEncoding")),
|
||||
("FirstChar", Object::Int(45)),
|
||||
("LastChar", Object::Int(45)),
|
||||
("Widths", Object::Array(vec![Object::Int(333)])),
|
||||
("FontDescriptor", Object::Dict(descriptor)),
|
||||
],
|
||||
);
|
||||
assert!(embedded_sfnt(&doc, &cmap_alias_font).is_some(), "intentional cmap alias subset keeps its sfnt");
|
||||
assert_eq!(Metrics::from_dict(&doc, &cmap_alias_font).encode("-").as_deref(), Some(&[45][..]));
|
||||
|
||||
// Regression fixture 3: a legitimate 1-glyph composite subset with intentional CIDToGIDMap
|
||||
// aliases (CIDs 1..=3 all mapping to GID 1) stays usable and keeps its sfnt.
|
||||
let mut single_char_ttf = one_glyph_ttf;
|
||||
append_editor_cmap(&mut single_char_ttf, &std::collections::BTreeMap::from([(65, 1), (0xFF21, 1)])).unwrap();
|
||||
let program = doc.add(Object::Stream(Stream::flate(Dict::new(), &single_char_ttf)));
|
||||
let cid_to_gid = doc.add(Object::Stream(Stream::flate(Dict::new(), &[0, 0, 0, 1, 0, 1, 0, 1])));
|
||||
let tu = doc.add(Object::Stream(Stream::flate(Dict::new(), b"2 beginbfchar <0001> <0041> <0002> <FF21> endbfchar")));
|
||||
let mut descriptor = Dict::new();
|
||||
descriptor.set(b"FontName".to_vec(), Object::name("ABCDEF+SingleCharSubset"));
|
||||
descriptor.set(b"FontFile2".to_vec(), Object::Ref(program));
|
||||
let mut desc = Dict::new();
|
||||
desc.set(b"Subtype".to_vec(), Object::name("CIDFontType2"));
|
||||
desc.set(b"BaseFont".to_vec(), Object::name("ABCDEF+SingleCharSubset"));
|
||||
desc.set(b"CIDToGIDMap".to_vec(), Object::Ref(cid_to_gid));
|
||||
desc.set(b"W".to_vec(), Object::Array(vec![Object::Int(1), Object::Array(vec![Object::Int(600), Object::Int(600)])]));
|
||||
desc.set(b"FontDescriptor".to_vec(), Object::Dict(descriptor));
|
||||
let valid_subset = font(
|
||||
&mut doc,
|
||||
vec![
|
||||
("Subtype", Object::name("Type0")),
|
||||
("BaseFont", Object::name("ABCDEF+SingleCharSubset")),
|
||||
("Encoding", Object::name("Identity-H")),
|
||||
("DescendantFonts", Object::Array(vec![Object::Dict(desc)])),
|
||||
("ToUnicode", Object::Ref(tu)),
|
||||
],
|
||||
);
|
||||
assert!(embedded_sfnt(&doc, &valid_subset).is_some(), "legitimate 1-glyph subset with CID aliases keeps its sfnt");
|
||||
assert_eq!(Metrics::from_dict(&doc, &valid_subset).encode("A").as_deref(), Some(&[0, 1][..]));
|
||||
|
||||
// Distinct non-zero GIDs across >= 64 CIDs, or a single-GID map whose FontFile2 has 0 or
|
||||
// multiple outlined glyphs (or a different outlined GID), are not classified as glyphless.
|
||||
let mut multi_gid_map = [0u8, 1].repeat(65);
|
||||
multi_gid_map.extend_from_slice(&[0, 2]);
|
||||
let multi_gid = doc.add(Object::Stream(Stream::flate(Dict::new(), &multi_gid_map)));
|
||||
let single_gid_64 = doc.add(Object::Stream(Stream::flate(Dict::new(), &[0u8, 1].repeat(65))));
|
||||
let single_gid_2_64 = doc.add(Object::Stream(Stream::flate(Dict::new(), &[0u8, 2].repeat(65))));
|
||||
let full_ttf = doc.add(Object::Stream(Stream::flate(Dict::new(), include_bytes!("../../../../assets/fonts/Inter-Regular.ttf"))));
|
||||
let zero_ttf = doc.add(Object::Stream(Stream::flate(Dict::new(), &zero_glyph_ttf)));
|
||||
for (map_ref, prog_ref) in [(multi_gid, program), (single_gid_64, full_ttf), (single_gid_64, zero_ttf), (single_gid_2_64, program)] {
|
||||
let mut fd = Dict::new();
|
||||
fd.set(b"FontFile2".to_vec(), Object::Ref(prog_ref));
|
||||
let mut desc = Dict::new();
|
||||
desc.set(b"Subtype".to_vec(), Object::name("CIDFontType2"));
|
||||
desc.set(b"CIDToGIDMap".to_vec(), Object::Ref(map_ref));
|
||||
desc.set(b"FontDescriptor".to_vec(), Object::Dict(fd));
|
||||
let d = font(&mut doc, vec![("Subtype", Object::name("Type0")), ("DescendantFonts", Object::Array(vec![Object::Dict(desc)]))]);
|
||||
assert!(!is_glyphless(&doc, &d));
|
||||
}
|
||||
}
|
||||
|
||||
/// #2130: with no `/Widths`, an embedded program's advances win over a guess from the name
|
||||
/// ("Mono" would mean Courier, 600 units for every glyph), the program's `/DecodeParms` given
|
||||
/// directly or by reference.
|
||||
@@ -299,13 +454,14 @@ fn a_fonts_streams_are_paid_for_from_its_allowance() {
|
||||
let m = Metrics::from_dict_within(&doc, &f, &mut budget);
|
||||
assert!(m.past_allowance && m.outlined_cids.is_empty());
|
||||
assert_eq!(m.codes, Codes::Two, "the Encoding CMap was left unread");
|
||||
// Only a subset's program says which glyphs it lacks: the whole font pays for its CMaps alone.
|
||||
// Only a subset's program says which glyphs it lacks: the whole font inspects `/CIDToGIDMap`
|
||||
// once for shared-glyph placeholders and leaves the `FontFile2` program unread.
|
||||
let mut whole_font = f.clone();
|
||||
whole_font.set(b"BaseFont".to_vec(), Object::name("Inter"));
|
||||
let mut budget = DecodeBudget::new(cost, 0);
|
||||
let m = Metrics::from_dict_within(&doc, &whole_font, &mut budget);
|
||||
assert!(!m.past_allowance && m.outlined_cids.is_empty());
|
||||
assert_eq!(cost - budget.remaining(), sizes[0] + sizes[3]);
|
||||
assert_eq!(cost - budget.remaining(), sizes[0] + sizes[2] + sizes[3]);
|
||||
}
|
||||
|
||||
/// With nothing left, an empty stream still reads, as the allowance reads one, and is no reason to
|
||||
|
||||
@@ -105,6 +105,15 @@ fn is_complex(c: char) -> bool {
|
||||
matches!(c as u32, 0x0300..=0x036F | 0x0900..=0x0DFF | 0x0E00..=0x0EFF | 0x1000..=0x109F | 0x1780..=0x17FF)
|
||||
}
|
||||
|
||||
/// Hangul, which [`is_cjk`] counts as CJK: syllables, the two jamo blocks, the compatibility
|
||||
/// jamo and the halfwidth jamo. Korean is written with spaces between its words (띄어쓰기), unlike Chinese and Japanese,
|
||||
/// so a gap between two Korean syllables may be a word gap and is read as one from half a line
|
||||
/// height upwards -- a document that writes its spaces as position rather than as space
|
||||
/// characters would otherwise lose them (#3722 review).
|
||||
fn is_hangul(c: char) -> bool {
|
||||
matches!(c as u32, 0x1100..=0x11FF | 0x3130..=0x318F | 0xA960..=0xA97F | 0xAC00..=0xD7AF | 0xFFA0..=0xFFDC)
|
||||
}
|
||||
|
||||
/// Whether `text` is only combining marks (Unicode Mn and Me, which take bidi class NSM) of a
|
||||
/// left-to-right script: Thai tone marks and above or below vowels, Indic signs such as virama,
|
||||
/// Latin combining accents. Right-to-left marks are ordered with their script by [`reverse_rtl`].
|
||||
@@ -213,27 +222,105 @@ fn pair_threshold(p: &TextGlyph, c: &TextGlyph, typical: f32, threshold: f32) ->
|
||||
(typical + h * WORD_GAP).max(h * WORD_GAP).min(threshold)
|
||||
}
|
||||
|
||||
/// [`layout`] as the reading order of indices into `glyphs`, with each one's line and word gap.
|
||||
fn arrange(glyphs: &[TextGlyph]) -> (Vec<usize>, Vec<u32>, Vec<bool>) {
|
||||
/// How many grid cells around a glyph the far redraw check looks at in each direction, however large the glyph is next to
|
||||
/// the page's median glyph.
|
||||
const MAX_REDRAW_REACH: i32 = 8;
|
||||
|
||||
/// A 64-bit FNV-1a hash of one glyph text.
|
||||
fn text_hash(text: &str) -> u64 {
|
||||
text.bytes().fold(0xcbf2_9ce4_8422_2325, |h, b| (h ^ u64::from(b)).wrapping_mul(0x0000_0100_0000_01b3))
|
||||
}
|
||||
|
||||
/// Marks glyphs retained after the bounded near and far redraw checks.
|
||||
fn glyphs_without_redraws(glyphs: &[TextGlyph]) -> Vec<bool> {
|
||||
// Drop "fake bold" duplicates: the same character redrawn at (almost) the same place. A redraw
|
||||
// also overlaps most of its own width: a narrow letter in condensed text (80 Tz and below) sits
|
||||
// closer than a fifth of its height to its double, as the second "l" of "Alle" (#1467), and
|
||||
// OCR layers squeeze words to 20 Tz and below (#2457). Only a zero-width mark, which has no
|
||||
// width to overlap, is matched by its height alone.
|
||||
//
|
||||
// The twin is usually among the last few glyphs. A page drawn once per column clip also redraws the glyph on the clip
|
||||
// edge thousands of glyphs later: the last glyph of one run is the first of another (#3173). So a glyph that starts a
|
||||
// run is also checked against the kept glyphs of its text in the grid cells around it, if one of them ends a run. A
|
||||
// glyph inside a run stays for the redraw check on whole runs below, which keeps a run that only starts like an
|
||||
// earlier one. The grid has one cell size for the whole page (a fifth of the median glyph height), so equal places
|
||||
// land in equal cells whatever the glyph sizes. `older[k]` links each kept glyph to the previous one with the same
|
||||
// key, so the earlier candidates are checked newest first, up to `REDRAW_CANDIDATES`, as the runs are below.
|
||||
let mut keep = vec![true; glyphs.len()];
|
||||
for i in 1..glyphs.len() {
|
||||
// `q` continues the run of `p` as `arrange` joins glyphs into a segment: a sub- or superscript right next to
|
||||
// its glyph may sit off the line by up to half the taller one's height.
|
||||
let follows = |p: usize, q: usize| {
|
||||
let (a, b) = (&glyphs[p].rect, &glyphs[q].rect);
|
||||
let (ha, hb) = ((a[3] - a[1]).max(0.1), (b[3] - b[1]).max(0.1));
|
||||
let ph = ha.min(hb);
|
||||
let gap = b[0] - a[2];
|
||||
let centre_limit = if gap.abs() < ph { ha.max(hb) * 0.5 } else { ph * 0.5 };
|
||||
((a[1] + a[3]) / 2.0 - (b[1] + b[3]) / 2.0).abs() < centre_limit && gap < ph * 3.0 && b[0] > a[0] - ph * 2.0
|
||||
};
|
||||
let mut heights: Vec<f32> = glyphs.iter().map(|g| (g.rect[3] - g.rect[1]).max(0.1)).collect();
|
||||
let cell = match heights.len() {
|
||||
0 => 0.02,
|
||||
n => 0.2 * *heights.select_nth_unstable_by(n / 2, f32::total_cmp).1,
|
||||
};
|
||||
let mut latest: HashMap<(u64, i32, i32), usize> = HashMap::new();
|
||||
let mut older = vec![NONE; glyphs.len()];
|
||||
// `next_kept[j]`: the kept glyph after kept glyph `j`, recorded when it is kept, so a dropped
|
||||
// fake-bold copy does not count and no lookup rescans the dropped glyphs in between.
|
||||
let mut next_kept = vec![NONE; glyphs.len()];
|
||||
let mut prev_kept: Option<usize> = None;
|
||||
for i in 0..glyphs.len() {
|
||||
let g = &glyphs[i];
|
||||
let h = (g.rect[3] - g.rect[1]).max(0.1);
|
||||
let w = g.rect[2] - g.rect[0];
|
||||
let dx = if w > 0.0 { (h * 0.2).min(w * 0.5) } else { h * 0.2 };
|
||||
for j in (i.saturating_sub(4)..i).rev() {
|
||||
let same = |j: usize| {
|
||||
let p = &glyphs[j];
|
||||
if keep[j] && p.text == g.text && (p.rect[0] - g.rect[0]).abs() < dx && (p.rect[1] - g.rect[1]).abs() < h * 0.2 {
|
||||
keep[i] = false;
|
||||
break;
|
||||
keep[j] && p.text == g.text && (p.rect[0] - g.rect[0]).abs() < dx && (p.rect[1] - g.rect[1]).abs() < h * 0.2
|
||||
};
|
||||
// The last kept glyph is checked too: copies of it drawn more than four times in a row
|
||||
// are all past the window, and the far check is skipped for a glyph that follows it.
|
||||
let near = (i.saturating_sub(4)..i).rev().any(&same) || prev_kept.is_some_and(&same);
|
||||
let (fp, cx, cy_) = (text_hash(&g.text), (g.rect[0] / cell).floor() as i32, (g.rect[1] / cell).floor() as i32);
|
||||
// The glyph after a kept one is the next kept glyph (or this one, while it has none).
|
||||
let next_of = |j: usize| next_kept.get(j).copied().filter(|&k| k != NONE).unwrap_or(i);
|
||||
let mut far = false;
|
||||
if prev_kept.is_none_or(|p| !follows(p, i)) {
|
||||
// `same` takes a horizontal offset below `dx` and a vertical one below a fifth of the height.
|
||||
let reach = ((dx.max(h * 0.2) / cell).ceil() as i32).clamp(1, MAX_REDRAW_REACH);
|
||||
let mut checks = REDRAW_CANDIDATES;
|
||||
'cells: for ox in -reach..=reach {
|
||||
for oy in -reach..=reach {
|
||||
let mut link = latest.get(&(fp, cx.saturating_add(ox), cy_.saturating_add(oy))).copied();
|
||||
while let Some(j) = link {
|
||||
if checks == 0 {
|
||||
break 'cells;
|
||||
}
|
||||
checks -= 1;
|
||||
if same(j) && !follows(j, next_of(j)) {
|
||||
far = true;
|
||||
break 'cells;
|
||||
}
|
||||
link = older.get(j).copied().filter(|&o| o != NONE);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if near || far {
|
||||
keep[i] = false;
|
||||
} else {
|
||||
older[i] = latest.insert((fp, cx, cy_), i).unwrap_or(NONE);
|
||||
if let Some(slot) = prev_kept.and_then(|p| next_kept.get_mut(p)) {
|
||||
*slot = i;
|
||||
}
|
||||
prev_kept = Some(i);
|
||||
}
|
||||
}
|
||||
keep
|
||||
}
|
||||
|
||||
/// [`layout`] as the reading order of indices into `glyphs`, with each one's line and word gap.
|
||||
fn arrange(glyphs: &[TextGlyph]) -> (Vec<usize>, Vec<u32>, Vec<bool>) {
|
||||
let keep = glyphs_without_redraws(glyphs);
|
||||
let kept: Vec<usize> = (0..glyphs.len()).filter(|i| keep[*i]).collect();
|
||||
let glyphs: Vec<&TextGlyph> = kept.iter().map(|i| &glyphs[*i]).collect();
|
||||
let n = glyphs.len();
|
||||
@@ -531,7 +618,27 @@ fn arrange(glyphs: &[TextGlyph]) -> (Vec<usize>, Vec<u32>, Vec<bool>) {
|
||||
let Some(&Some(gap)) = sc.cluster_gap.get(w + 1) else { continue };
|
||||
let pair_threshold = pair_threshold(glyphs[p], glyphs[c], typical, threshold);
|
||||
let (pt, ct) = (cluster_text(p), cluster_text(c));
|
||||
let cjk = pt.chars().any(is_cjk) && ct.chars().any(is_cjk) && gap < h * 0.5;
|
||||
// Character spacing is added after every glyph of a show (`Tc`, ISO 32000-2 §9.3.2), so text spread to a
|
||||
// wider column -- a Chinese label on a form, 分散對齊 -- repeats one gap, while the gap between two cells
|
||||
// of a row stands on its own. A repeated gap is therefore spacing at any width. Chinese and Japanese
|
||||
// write no spaces between these characters, so a space inferred inside a label changes what Copy gives
|
||||
// and stops Find matching it (#3713). The whole-line typical gap cannot tell the two apart: on these
|
||||
// lines most gaps are the zero of the value beside the label.
|
||||
//
|
||||
// A gap of its own is read as spacing only below half a line height, the same width Hangul uses. A
|
||||
// whole line height swallowed the gap between two cells of a form row whenever it was under one em --
|
||||
// 9pt on a 12pt line -- so 姓名 followed by 王小明 copied as 姓名王小明 (noted in review). Repetition,
|
||||
// not width, is what tells spread text apart from two cells.
|
||||
// `cluster_gap[w + 1]` is this pair's gap, so the pairs beside it are at `w` and `w + 2`.
|
||||
let spread = |w: usize| {
|
||||
let same = |other: Option<&Option<f32>>| other.copied().flatten().is_some_and(|o| (o - gap).abs() <= h * 0.02);
|
||||
same(sc.cluster_gap.get(w)) || same(sc.cluster_gap.get(w + 2))
|
||||
};
|
||||
// Korean keeps the narrower tolerance and no repetition: its words are separated by spaces, which
|
||||
// a file may write as position rather than as space characters. Measured on three Korean words at
|
||||
// one em, drawn without space glyphs: with the Chinese rule they read as 안녕하세요여러분.
|
||||
let hangul = pt.chars().any(is_hangul) || ct.chars().any(is_hangul);
|
||||
let cjk = pt.chars().any(is_cjk) && ct.chars().any(is_cjk) && (gap < h * 0.5 || (!hangul && spread(w)));
|
||||
// A combining sign that rides on no glyph before it (drawn apart from its base, or in a run of its own)
|
||||
// may sit anywhere over its base, so it never takes a space next to it. Two base letters of these
|
||||
// scripts are measured like any others: a Thai or Indic word gap is narrower than half an em.
|
||||
|
||||
@@ -1405,6 +1405,122 @@ fn fake_bold_duplicates_are_removed() {
|
||||
assert_eq!(layout(v).plain_text(), "e\u{301}");
|
||||
}
|
||||
|
||||
/// Text drawn once per column clip: "WO" and the `edge` glyphs, lots of other text, then the `second_pass`.
|
||||
fn column_passes(edge: &[TextGlyph], second_pass: &[TextGlyph]) -> String {
|
||||
let mut v = Vec::new();
|
||||
word(&mut v, "WO", 10.0, 10.0, 6.0);
|
||||
v.extend_from_slice(edge);
|
||||
for k in 0..50 {
|
||||
word(&mut v, "xx", 100.0, 40.0 + 14.0 * k as f32, 6.0);
|
||||
}
|
||||
v.extend_from_slice(second_pass);
|
||||
layout(v).plain_text()
|
||||
}
|
||||
|
||||
/// #3173: a page drawn once per column clip draws a glyph on the clip edge in both passes, far apart in drawing order.
|
||||
#[test]
|
||||
fn a_glyph_redrawn_by_the_other_column_pass_is_dropped() {
|
||||
let mut v = Vec::new();
|
||||
word(&mut v, "WO", 10.0, 10.0, 6.0);
|
||||
v.push(g("R", 22.0, 10.0, 28.0));
|
||||
word(&mut v, "illu", 10.0, 30.0, 6.0);
|
||||
v.push(g("s", 34.0, 30.0, 40.0));
|
||||
// The other pass: lots of other text, then the same glyphs at (almost) the same place and the rest of each word.
|
||||
for k in 0..50 {
|
||||
word(&mut v, "xx", 100.0, 40.0 + 14.0 * k as f32, 6.0);
|
||||
}
|
||||
v.push(g("R", 22.0, 10.0, 28.0));
|
||||
word(&mut v, "LD", 28.0, 10.0, 6.0);
|
||||
v.push(g("s", 33.99, 30.0, 39.99));
|
||||
word(&mut v, "trated", 40.0, 30.0, 6.0);
|
||||
let text = layout(v).plain_text();
|
||||
assert!(text.lines().any(|l| l == "WORLD"), "{text}");
|
||||
assert!(text.lines().any(|l| l == "illustrated"), "{text}");
|
||||
}
|
||||
|
||||
/// #3173: the second pass draws the glyph a little taller, so its grid cell must still be the one of the first copy.
|
||||
#[test]
|
||||
fn a_redrawn_glyph_of_slightly_different_height_is_dropped() {
|
||||
// Far from the page origin, a grid cell sized by each glyph's own height would put the two copies three cells apart.
|
||||
let mut v = Vec::new();
|
||||
word(&mut v, "WO", 150.0, 150.0, 6.0);
|
||||
v.push(em_box("R", 162.0, 150.0, 168.0, 160.0));
|
||||
for k in 0..50 {
|
||||
word(&mut v, "xx", 300.0, 200.0 + 14.0 * k as f32, 6.0);
|
||||
}
|
||||
v.push(em_box("R", 162.0, 150.0, 168.0, 160.3));
|
||||
word(&mut v, "LD", 168.0, 150.0, 6.0);
|
||||
let text = layout(v).plain_text();
|
||||
assert!(text.lines().any(|l| l == "WORLD"), "{text}");
|
||||
}
|
||||
|
||||
/// #3173: a fake-bold copy after the last glyph of a pass does not hide that the glyph ends its run.
|
||||
#[test]
|
||||
fn a_fake_bold_copy_at_the_end_of_a_pass_does_not_hide_the_run_end() {
|
||||
let mut second = vec![g("R", 22.0, 10.0, 28.0)];
|
||||
word(&mut second, "LD", 28.0, 10.0, 6.0);
|
||||
let text = column_passes(&[g("R", 22.0, 10.0, 28.0), g("R", 22.1, 10.0, 28.1)], &second);
|
||||
assert!(text.lines().any(|l| l == "WORLD"), "{text}");
|
||||
}
|
||||
|
||||
/// A glyph redrawn five or more times in a row at its own place prints once: the copies past the
|
||||
/// four-glyph window still match the kept glyph they follow.
|
||||
#[test]
|
||||
fn many_copies_of_a_glyph_in_a_row_print_once() {
|
||||
let mut v = Vec::new();
|
||||
word(&mut v, "WOR", 10.0, 10.0, 6.0);
|
||||
for _ in 0..7 {
|
||||
v.push(g("L", 28.0, 10.0, 34.0));
|
||||
}
|
||||
v.push(g("D", 34.0, 10.0, 40.0));
|
||||
assert_eq!(layout(v).plain_text(), "WORLD");
|
||||
}
|
||||
|
||||
/// #3173: the far redraw check reaches as far as a redraw may sit vertically, for a tall, narrow
|
||||
/// glyph whose horizontal tolerance is much smaller than its vertical one.
|
||||
#[test]
|
||||
fn a_tall_narrow_glyph_redrawn_a_little_higher_is_dropped() {
|
||||
let mut v = vec![em_box("|", 10.0, 100.0, 11.0, 140.0)];
|
||||
for k in 0..50 {
|
||||
word(&mut v, "xx", 100.0, 200.0 + 14.0 * k as f32, 6.0);
|
||||
}
|
||||
v.push(em_box("|", 10.0, 107.0, 11.0, 147.0));
|
||||
let text = layout(v).plain_text();
|
||||
assert_eq!(text.matches('|').count(), 1, "{text}");
|
||||
}
|
||||
|
||||
/// #3173: a glyph followed by its superscript is inside a run, so a later run starting at its place is not its redraw.
|
||||
#[test]
|
||||
fn a_glyph_followed_by_its_superscript_is_not_a_run_end() {
|
||||
let mut v = vec![em_box("H", 10.0, 10.0, 16.0, 20.0), em_box("2", 16.0, 16.0, 19.0, 22.0)];
|
||||
for k in 0..50 {
|
||||
word(&mut v, "xx", 100.0, 40.0 + 14.0 * k as f32, 6.0);
|
||||
}
|
||||
v.push(em_box("H", 10.0, 10.0, 16.0, 20.0));
|
||||
v.push(em_box("O", 16.0, 10.0, 22.0, 20.0));
|
||||
let text = layout(v).plain_text();
|
||||
assert_eq!(text.matches('H').count(), 2, "{text}");
|
||||
}
|
||||
|
||||
/// #3173: a glyph kept in a cell does not hide the earlier glyph there that the redraw matches.
|
||||
#[test]
|
||||
fn a_redraw_is_matched_against_earlier_glyphs_of_the_same_cell() {
|
||||
// A narrow "l" at 10 ends its line, a second one 0.8 pt to the right (more than a half of its width) is its own letter,
|
||||
// and the last one, more than 4 glyphs later, redraws the first.
|
||||
let v = vec![
|
||||
g("l", 10.0, 10.0, 11.0),
|
||||
g("Z", 200.0, 100.0, 206.0),
|
||||
g("l", 10.8, 10.0, 11.8),
|
||||
g("Y", 300.0, 200.0, 306.0),
|
||||
g("Z", 300.0, 300.0, 306.0),
|
||||
g("Y", 300.0, 400.0, 306.0),
|
||||
g("Z", 300.0, 500.0, 306.0),
|
||||
g("l", 10.0, 10.0, 11.0),
|
||||
];
|
||||
let text = layout(v).plain_text();
|
||||
assert_eq!(text.matches('l').count(), 2, "{text}");
|
||||
}
|
||||
|
||||
/// #1467: condensed text (80 Tz and below, OCR layers fitted to the scan) sets narrow letters
|
||||
/// closer than a fifth of their height apart; a doubled letter there is two letters, not a redraw.
|
||||
#[test]
|
||||
@@ -3241,6 +3357,104 @@ fn truetype_without_an_encoding_reads_its_codes_as_win_ansi() {
|
||||
assert_eq!(ocr_layer_text(32, true), expected, "nonsymbolic, /ToUnicode for ASCII only");
|
||||
}
|
||||
|
||||
/// #3713: a Chinese label spread to the width of a longer one (分散對齊, as on Taiwanese forms)
|
||||
/// is one show with character spacing, so every gap of the label is the same, while the value
|
||||
/// beside it has none. The line's typical gap is therefore the value's zero, and from half a
|
||||
/// line height upwards each of the label's gaps read as a word gap: 「受文者」 copied as
|
||||
/// 「受 文 者」 and Find no longer matched it. A repeated gap is spacing, whatever its width.
|
||||
#[test]
|
||||
fn a_chinese_label_spread_by_character_spacing_keeps_its_characters_together() {
|
||||
// `Tc` is added after every glyph of the string (ISO 32000-2 §9.3.2), so the gap before
|
||||
// the value is the spacing too; the value's own glyphs follow at `0 Tc`.
|
||||
let line = |tc: f32| {
|
||||
let mut v = Vec::new();
|
||||
let mut x = 0.0;
|
||||
for ch in ["受", "文", "者"] {
|
||||
v.push(em_box(ch, x, 0.0, x + 12.0, 12.0));
|
||||
x += 12.0 + tc;
|
||||
}
|
||||
for ch in ["如", "正", "本"] {
|
||||
v.push(em_box(ch, x, 0.0, x + 12.0, 12.0));
|
||||
x += 12.0;
|
||||
}
|
||||
layout(v).plain_text()
|
||||
};
|
||||
// A tenth of the font size up to a whole em: the issue's nine steps, the last three of
|
||||
// which used to break.
|
||||
for tc in [1.2, 2.4, 3.0, 3.6, 4.2, 4.8, 6.0, 9.0, 12.0] {
|
||||
assert_eq!(line(tc), "受文者如正本", "{tc} pt of character spacing");
|
||||
}
|
||||
|
||||
// A gap that stands on its own is still a word gap. The width is what the review caught: a
|
||||
// whole line height swallowed any isolated gap under one em, so two cells of a form row set
|
||||
// 9pt apart on a 12pt line copied as one word. Half a line height upwards is a gap, which is
|
||||
// the width Hangul already used; below it is still spacing.
|
||||
let cells = |gap: f32| {
|
||||
let mut v = Vec::new();
|
||||
for (i, ch) in ["姓", "名"].iter().enumerate() {
|
||||
let x = i as f32 * 12.0;
|
||||
v.push(em_box(ch, x, 0.0, x + 12.0, 12.0));
|
||||
}
|
||||
for (i, ch) in ["王", "小", "明"].iter().enumerate() {
|
||||
let x = 24.0 + gap + i as f32 * 12.0;
|
||||
v.push(em_box(ch, x, 0.0, x + 12.0, 12.0));
|
||||
}
|
||||
layout(v).plain_text()
|
||||
};
|
||||
// Two character widths, as before, and then the band that used to be lost: half a line
|
||||
// height and up. 6.0 is the boundary itself, which is a gap.
|
||||
for gap in [24.0, 18.0, 12.0, 9.0, 7.2, 6.0] {
|
||||
assert_eq!(cells(gap), "姓名 王小明", "{gap} pt between the two cells");
|
||||
}
|
||||
// And below it, still spacing rather than a gap -- one isolated narrow gap must not start
|
||||
// splitting a label that happens to carry one.
|
||||
for gap in [5.4, 3.0, 1.2, 0.0] {
|
||||
assert_eq!(cells(gap), "姓名王小明", "{gap} pt is spacing, not a gap");
|
||||
}
|
||||
}
|
||||
|
||||
/// Korean is written with spaces between words (띄어쓰기), and a file may write them as
|
||||
/// position rather than as space characters, so the rule for Chinese and Japanese -- where a
|
||||
/// gap between two characters is never a word gap -- must not reach Hangul (#3722 review).
|
||||
#[test]
|
||||
fn korean_words_separated_by_position_keep_their_spaces() {
|
||||
let line = |gap: f32| {
|
||||
let mut v = Vec::new();
|
||||
let mut x = 0.0;
|
||||
for word in ["안녕", "하세요", "여러분"] {
|
||||
for ch in word.chars() {
|
||||
v.push(em_box(&ch.to_string(), x, 0.0, x + 12.0, 12.0));
|
||||
x += 12.0;
|
||||
}
|
||||
x += gap;
|
||||
}
|
||||
layout(v).plain_text()
|
||||
};
|
||||
// Half the line height upwards is a word gap, as it was before the Chinese rule changed.
|
||||
for gap in [6.0, 7.0, 9.0, 12.0] {
|
||||
assert_eq!(line(gap), "안녕 하세요 여러분", "{gap} pt between the words");
|
||||
}
|
||||
// Below that it is letter spacing, which is unchanged.
|
||||
assert_eq!(line(3.0), "안녕하세요여러분");
|
||||
}
|
||||
|
||||
/// Halfwidth Hangul jamo are Hangul too: equal gaps between them from half a line height up are
|
||||
/// word gaps, not the character spacing of spread Chinese text.
|
||||
#[test]
|
||||
fn halfwidth_hangul_separated_by_equal_gaps_keeps_its_spaces() {
|
||||
let mut v = Vec::new();
|
||||
let mut x = 0.0;
|
||||
// A one-letter word between two others: its two word gaps repeat each other.
|
||||
for word in ["\u{FFA1}\u{FFA2}", "\u{FFA4}", "\u{FFA7}\u{FFA8}"] {
|
||||
for ch in word.chars() {
|
||||
v.push(em_box(&ch.to_string(), x, 0.0, x + 6.0, 12.0));
|
||||
x += 6.0;
|
||||
}
|
||||
x += 7.0;
|
||||
}
|
||||
assert_eq!(layout(v).plain_text(), "\u{FFA1}\u{FFA2} \u{FFA4} \u{FFA7}\u{FFA8}");
|
||||
}
|
||||
|
||||
/// Issue #2929: a footnote reference (superscript) on a line stays in that line instead of
|
||||
/// splitting out as a raised segment that steals the block's tail and pushes the host line
|
||||
/// after the paragraph.
|
||||
|
||||
@@ -6459,7 +6459,7 @@ fn host_dirty_hears_when_unsaved_work_appears_and_goes() {
|
||||
fn one_editor_contains_mixed_styles_and_visual_rows() {
|
||||
let _gpu = gpu();
|
||||
let bytes = source_font_fixture_with_text(
|
||||
"BT 0 0.2 0.5 rg /F1 1 Tf 18 0 0 18 20 240 Tm (Heading) Tj ET \
|
||||
"BT 0 0.2 0.5 rg /F2 1 Tf 18 0 0 18 20 240 Tm (Heading) Tj ET \
|
||||
BT 0 g /F2 12 Tf 20 215 Td (Plain ) Tj /F1 12 Tf 0 0.2 0.5 rg (bold) Tj /F2 12 Tf 0 g ( words) Tj ET \
|
||||
BT /F2 10 Tf 20 195 Td (Last row) Tj ET",
|
||||
);
|
||||
@@ -6546,7 +6546,7 @@ fn one_editor_contains_mixed_styles_and_visual_rows() {
|
||||
fn the_caret_on_a_small_row_is_as_tall_as_that_row() {
|
||||
// It was one row of the region's first (18 pt) size tall, reaching into the row below.
|
||||
let bytes = source_font_fixture_with_text(
|
||||
"BT 0 0.2 0.5 rg /F1 1 Tf 18 0 0 18 20 240 Tm (Heading) Tj ET \
|
||||
"BT 0 0.2 0.5 rg /F2 1 Tf 18 0 0 18 20 240 Tm (Heading) Tj ET \
|
||||
BT 0 g /F2 12 Tf 20 215 Td (Plain ) Tj /F1 12 Tf 0 0.2 0.5 rg (bold) Tj /F2 12 Tf 0 g ( words) Tj ET \
|
||||
BT /F2 10 Tf 20 195 Td (Last row) Tj ET",
|
||||
);
|
||||
@@ -10368,7 +10368,10 @@ fn format_panel_shows_selection_size_and_updates_after_font_applied() {
|
||||
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>".into(),
|
||||
"<< /Type /Page /Parent 2 0 R /Contents 5 0 R /Resources << /Font << /F1 3 0 R >> >> >>".into(),
|
||||
];
|
||||
let body = "BT /F1 24 Tf 20 200 Td (Heading) Tj /F1 12 Tf 0 -25 Td (Paragraph) Tj ET";
|
||||
// The heading is close enough in size to stay in the paragraph (a much larger one is a block
|
||||
// of its own), and Times goes on one word of the second row: a row set wholly in another
|
||||
// family is a paragraph of its own.
|
||||
let body = "BT /F1 16 Tf 20 200 Td (Heading) Tj /F1 12 Tf 0 -25 Td (Body text in a Paragraph) Tj ET";
|
||||
objs.push(format!("<< /Length {} >>\nstream\n{body}\nendstream", body.len()));
|
||||
let mut pdf = Vec::from(b"%PDF-1.7\n");
|
||||
let mut xref = Vec::new();
|
||||
|
||||
+4
-1
@@ -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: milestones and what's next
|
||||
|
||||
> **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-18 · **Last updated:** 2026-11-18 · **Change:** patch (M7 #7687: PDF-page watermarks use the visible source bounds; 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)
|
||||
@@ -282,7 +284,7 @@ total matches the parity estimate.
|
||||
| M6 | Forms + JavaScript | 160–320 | 50% | 40–75 | Done: filling all field types with regenerated appearances; Prepare a form (every field type, multi-select/shared properties, move/resize/delete, Field Properties General/Appearance/Position/Options/Format/Validate/Calculate); Acrobat's AF format/keystroke/validate/calculate functions and simplified field notation run natively in Acrobat's event order; tab order; push-button actions; flatten; agent tools. Form data exchange (FDF, XFDF, XML, CSV, text) done; XFDF values retain text across XML comments and processing instructions. XML/XFDF exports preserve tabs and line breaks in names and comment metadata. Plain AcroForm XML imports retain all direct text around comments and processing instructions, including CDATA and character references. CSV export and spreadsheet merging quote tabs, and import distinguishes quoted tabs from TSV delimiters without changing field identities.<br>Done since: JavaScript engine (boa, sandboxed) running custom keystroke/validate/calculate/format and button scripts, document JavaScripts, console. Missing: Actions tab, wider object model (annotations, layers, dialogs), XFA<br>Done since: Multi-select choice fields write ascending `/I` option indices while preserving `/V` selection order; synthetic forms/engine regressions cover reverse selection and save/reopen. CSV export preserves carriage returns in names and values. |
|
||||
| M7 | Content editing (text, images, header/footer, watermark) | 250–500 | 20% | 100–180 | Done: header & footer, text/image/PDF-page watermarks, backgrounds, Bates; added text and images that stay editable (move, resize, format, rotate, flip, crop, replace); links (Link tool, Link Properties, create from URLs, remove all). Done since: Edit text preserves Arabic/Hebrew `/ActualText` typing order, with font-independent regressions; single-glyph RTL ligature spans (including lam-alef) join their surrounding word. Done since (#1116): editable text regions grouped across compatible words and subset fonts, one rich-text editor over a background with the source text removed, embedded sfnt faces reused as editor faces, and visible (clipped) bounds for cropped-image selection and resize. Exclusive crops now resize across nested states and content streams, with shared clips fixed.<br>Done since: #594 ordinary paragraph drags preserve overlapping source text; UI/engine regressions, native save/reopen, independent-reader checks and full CI passed in the Linux test environment. #1200 candidate: local GoToR links open in desktop tabs and through root-confined automation; appearance-only edits preserve existing actions. Named destinations remain unapplied and `/NewWindow` is a tab hint. Done since: #3187: Added-image automation normalizes extreme signed rotation angles before combining them with the current orientation; integer bounds, history, pixels, save/reopen and MCP have regressions. Done since: #2592: Styled fallback fonts batch up to 240 glyphs per actual face and retain source styles. Budget refusal and distinct same-BaseFont descriptor weights have mutation-checked regressions; coverage and complex mixed runs remain limited. Done since: #5657 page-mark operations are atomic across selected pages, including shared/inherited resources and existing unsaved edits. Missing: editing existing text and images in place (the longest pole), watermark picture previews, edge-relative positioning, and print/screen-only visibility. PR #2155 candidate: editor-owned crops preserve original clips through group moves; Arrange preserves added-item stream ownership and refuses unsafe scope/state/tag extraction; image handles and flips follow page orientation; general transforms and Unicode script toggles have headless tools. Clipboard, mixed-size formatting, Home pins and reloadable installed-font discovery have review regressions. Latest follow-up uses explicit image-paste events, refreshes the mixed-size display, and documents script normalization with Undo. Further review covers inherited Form text and mask chronology, scoped transform composition, affine resize/rotation pivots, paste/selection ownership, no-op scripts and page-menu permissions. Done since: #5835 a right-click on an image in crop mode keeps the crop and opens no menu, also over overlapping and rotated images. Thai editing (#2964, #3185): supported Form text is editable; legacy Thai retains source fonts and text settings. Cross-family replacement is explicit; unsafe groups and mixed contextual styles remain partial. Candidate #2750: Single-style Keep source fonts edits retain source glyphs and batch only missing glyphs in fallback fonts. Per-rewrite character eligibility and widths are cached; source and fallback edge spaces stay extractable. PDF-page watermark source bounds follow the visible CropBox/MediaBox intersection (#7687). |
|
||||
| M7 | Content editing (text, images, header/footer, watermark) | 250–500 | 20% | 100–180 | Done: header & footer, text/image/PDF-page watermarks, backgrounds, Bates; added text and images that stay editable (move, resize, format, rotate, flip, crop, replace); links (Link tool, Link Properties, create from URLs, remove all). Done since: Edit text preserves Arabic/Hebrew `/ActualText` typing order, with font-independent regressions. Done since (#1116): editable text regions grouped across compatible words and subset fonts, one rich-text editor over a background with the source text removed, embedded sfnt faces reused as editor faces, and visible (clipped) bounds for cropped-image selection and resize. Exclusive crops now resize across nested states and content streams, with shared clips fixed.<br>Done since: #594 ordinary paragraph drags preserve overlapping source text; UI/engine regressions, native save/reopen, independent-reader checks and full CI passed in the Linux test environment. #1200 candidate: local GoToR links open in desktop tabs and through root-confined automation; appearance-only edits preserve existing actions. Named destinations remain unapplied and `/NewWindow` is a tab hint. #1316: replacing a line or paragraph keeps a neighbouring line whose glyph box overlaps when the baselines differ; a second copy on the same baseline is still replaced. Missing: editing existing text and images in place (the longest pole), watermark picture previews, edge-relative positioning, and print/screen-only visibility |
|
||||
| M7 | Content editing (text, images, header/footer, watermark) | 250–500 | 20% | 100–180 | Done: header & footer, text/image/PDF-page watermarks, backgrounds, Bates; added text and images that stay editable (move, resize, format, rotate, flip, crop, replace); links (Link tool, Link Properties, create from URLs, remove all). #3212: Headers, Bates numbers, watermarks and added text stay visible after unfinished marked content, without revealing hidden content. Tracked editable text distinguishes repeated glyph spacing from word gaps, with synthetic paragraph/object regressions. Missing: editing existing text and images in place (the longest pole), watermark print/screen visibility and repeat |
|
||||
| M7 | Content editing (text, images, header/footer, watermark) | 250–500 | 20% | 100–180 | Done: header & footer, text/image/PDF-page watermarks, backgrounds, Bates; added text and images that stay editable (move, resize, format, rotate, flip, crop, replace); links (Link tool, Link Properties, create from URLs, remove all). #3212: Headers, Bates numbers, watermarks and added text stay visible after unfinished marked content, without revealing hidden content. Tracked editable text distinguishes repeated glyph spacing from word gaps, with synthetic paragraph/object regressions. Paragraphs separate across large row-size changes, font-family changes and filled rectangular panels without splitting compatible multiline text or inline styles. Panel membership is page-wide across content streams and transformed forms, with split-path and isolated-panel save/reopen regressions; delayed-background rewrite checks (#2377) remain coveredMissing: editing existing text and images in place (the longest pole), watermark print/screen visibility and repeat |
|
||||
| M6 | Forms + JavaScript | 160–320 | 50% | 40–75 | Done: filling all field types with regenerated appearances; Prepare a form (every field type, multi-select/shared properties, move/resize/delete, Field Properties General/Appearance/Position/Options/Format/Validate/Calculate); Acrobat's AF format/keystroke/validate/calculate functions and simplified field notation run natively in Acrobat's event order; tab order; push-button actions; flatten; agent tools. Form data exchange (FDF, XFDF, XML, CSV, text) done; XFDF values retain text across XML comments and processing instructions.<br>Done since: JavaScript engine (boa, sandboxed) running custom keystroke/validate/calculate/format and button scripts, document JavaScripts, console. Missing: Actions tab, wider object model (annotations, layers, dialogs), XFA<br>Done since: Existing simple field-font encodings and Differences are respected when generating appearances; an unencodable value uses a separate Helvetica appearance font without changing the source font. Synthetic reopen regressions cover punctuation, subset fallback and multiline text. Exact font metrics/layout and broader Unicode fallback remain incomplete. |
|
||||
| M6 | Forms + JavaScript | 160–320 | 50% | 40–75 | Done: filling all field types with regenerated appearances; Prepare a form (every field type, multi-select/shared properties, move/resize/delete, Field Properties General/Appearance/Position/Options/Format/Validate/Calculate); Acrobat's AF format/keystroke/validate/calculate functions and simplified field notation run natively in Acrobat's event order; tab order; push-button actions; flatten; agent tools. Form data exchange (FDF, XFDF, XML, CSV, text) done; XFDF values retain text across XML comments and processing instructions.<br>Done since: JavaScript engine (boa, sandboxed) running custom keystroke/validate/calculate/format and button scripts, document JavaScripts, console. Missing: Actions tab, wider object model (annotations, layers, dialogs), XFA<br>Done since: Tab and Shift-Tab wrapping to the same field or another widget of that field refresh the newly opened editor from the accepted value before Save. Synthetic UI regressions cover both directions, same-frame Save, validation refusal and undo/redo. Renaming a field renames it in the calculations that read it (field lists, notation, literal `getField` names), in one undo step, and says how many changed. Prepare a form ▸ Calculation order, a page of its own: each calculated field's formula and value, what is wrong (fields that calculate too early, loops, fields missing from `/CO`) and Fix order, Up/Down, Alt+↑/↓ and drag, and on the page each field's step and arrows to and from the field in focus (`form_calculation_order` headlessly).<br>Done since (#4088): automatic AcroForm field scripts ignore Print with a console diagnostic; explicit button and console printing remain available. Integrated main f137a289 (0.16.1) on 2026-10-31; ShowPanel/SaveAs filtering, all three engine regressions, the headless regression, field effects and document-error provenance are retained. Windows x64 / Rust 1.95 validation: 761 engine/automation tests passed, zero failed and four existing ignored; formatting, scoped all-target Clippy with -D warnings, layers/assets/parity and the engine/automation WebAssembly check passed. A fresh CLI build and the 13-step synthetic form exercise passed; the inspected render shows Qty=4 and Total=8, and explicit button/console Print requests are retained. Main's 100 headless parity notices, five renderer WebAssembly warnings and three optional egui patch notices remain. Estimates unchanged. |
|
||||
| M7 | Content editing (text, images, header/footer, watermark) | 250–500 | 20% | 100–180 | Done: header & footer, text/image/PDF-page watermarks, backgrounds, Bates; added text and images that stay editable (move, resize, format, rotate, flip, crop, replace); links (Link tool, Link Properties, create from URLs, remove all). Missing: editing existing text and images in place (the longest pole), watermark picture previews, edge-relative positioning, and print/screen-only visibility |
|
||||
@@ -379,6 +381,7 @@ Estimates unchanged.
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-04 | minor | M7: row typography and page-wide filled panels define paragraph boundaries across content streams and transformed forms; compatible multiline/inline styles, isolated-panel edits and delayed-background rewriting remain covered. Estimates unchanged. |
|
||||
| 2026-11-18 | patch | M7 #7687: PDF-page watermarks clip source crops to MediaBox before sizing and rotation; synthetic geometry and save/reopen render coverage. Estimates unchanged. |
|
||||
|
||||
| 2026-10-16 | patch | M4: Insert from File retains catalog attachments with native undo/redo; existing name trees and encoded duplicate keys survive. Estimates unchanged. |
|
||||
|
||||
Reference in new issue
Block a user