Merge main into #4522

This commit is contained in:
FredApps committed 2026-11-26 23:20:14 +07:00
commit cb061454b2
61 files changed
+4036 -302

No files matched your search

+1
View File
@@ -27,3 +27,4 @@ jobs:
uses: storytold/craft-common-actions/.github/workflows/freebsd.yml@main
with:
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
cargo-test-extra-args: --no-fail-fast
+4
View File
@@ -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
View File
@@ -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
+5
View File
@@ -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"
+7 -1
View File
@@ -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 });
}
+26 -4
View File
@@ -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()
+68 -1
View File
@@ -1,6 +1,7 @@
//! Printing tools: list printers, and print (or save the print-ready PDF) with Acrobat's Print
//! dialog options.
use pdfcraft_engine::PrinterMarks;
use pdfcraft_engine::print::{self, Binding, BookletSubset, Layout, Orientation, PAPERS, PageOrder, SizeMode, Subset, spool};
use serde_json::{Value, json};
@@ -41,6 +42,48 @@ fn printer_in(printers: Vec<spool::Printer>, printer: &str) -> Option<spool::Pri
printers.into_iter().find(|p| if printer == "default" { p.default } else { p.name == printer })
}
/// What `doc_print`'s `marks` may name.
const MARK_NAMES: &str = "marks must be a list of all, trim, bleed, registration, color_bars and page_info";
/// `doc_print`'s `marks` and `marks_weight`: the printer's marks to print around each page, or
/// `None` when none are asked for. The information line names the document (`name`) and the
/// date (`today`, year, month, day).
fn printer_marks(a: &Args, layout: &Layout, name: &str, (y, m, d): (i64, u32, u32)) -> Result<Option<PrinterMarks>> {
let Some(asked) = a.get("marks") else {
return if a.get("marks_weight").is_some() { Err(bad("marks_weight needs marks")) } else { Ok(None) };
};
let names = asked.as_array().filter(|names| !names.is_empty()).ok_or_else(|| bad(MARK_NAMES))?;
let mut marks = PrinterMarks {
trim: false,
bleed: false,
registration: false,
color_bars: false,
page_info: false,
label: name.to_string(),
date: format!("{y:04}-{m:02}-{d:02}"),
..PrinterMarks::default()
};
for mark in names {
match mark.as_str() {
Some("all") => (marks.trim, marks.bleed, marks.registration, marks.color_bars, marks.page_info) = (true, true, true, true, true),
Some("trim") => marks.trim = true,
Some("bleed") => marks.bleed = true,
Some("registration") => marks.registration = true,
Some("color_bars") => marks.color_bars = true,
Some("page_info") => marks.page_info = true,
_ => return Err(bad(MARK_NAMES)),
}
}
marks.line_weight = a.opt_num("marks_weight")?.unwrap_or(0.25);
if !PrinterMarks::WEIGHTS.contains(&marks.line_weight) {
return Err(bad(format!("marks_weight must be from {} to {} points", PrinterMarks::WEIGHTS.start(), PrinterMarks::WEIGHTS.end())));
}
if !matches!(layout, Layout::Size(_)) {
return Err(bad("printer marks print one page a sheet: use layout fit, actual, shrink or custom"));
}
Ok(Some(marks))
}
/// An invalid-arguments error saying `m`.
fn bad(m: impl Into<String>) -> ToolError {
ToolError::InvalidArgs(m.into())
@@ -306,6 +349,7 @@ impl Automation {
},
l => Layout::Size(print::names::parse_size_mode(l, 100.0).ok_or_else(|| bad(format!("unknown layout {l:?}")))?),
};
let marks = printer_marks(a, &layout, &self.doc(a)?.name, self.session.today())?;
let printer = a.opt_str("printer")?;
// The printer whose driver a booklet's both sides were decided for. The job goes to it by
// name, so "default" can't become another printer while the document is rendered. The
@@ -359,6 +403,19 @@ impl Automation {
} else {
None
};
if marks.is_some() && raster.is_some() {
return Err(bad("printer marks print with the pages as they are: leave out as_image and color_management app"));
}
// A document that allows only low-resolution printing is later forced to print as
// pictures in Session::print_pdf_marked. Refuse marks here, before Will Print runs
// and could change the document for a print that then fails. A document that allows
// no printing gets the engine's permission error instead.
let doc = self.doc(a)?;
if marks.is_some() && doc.allows_printing() && doc.permissions().is_some_and(|p| !p.print_high_quality()) {
return Err(bad(
"printer marks print with the pages as they are, not as pictures: a document that allows only low-resolution printing always prints as pictures",
));
}
let sizes: Vec<(f64, f64)> = self.doc(a)?.info.pages.iter().map(|p| (p.width as f64, p.height as f64)).collect();
// Print a selected area: points from the top-left of the displayed page, as other tools
// take rectangles; the print crate takes it y up.
@@ -370,6 +427,9 @@ impl Automation {
Some([r[0].min(r[2]), h - r[1].max(r[3]), r[0].max(r[2]), h - r[1].min(r[3])])
}
};
if marks.is_some() && area.is_some() {
return Err(bad("area prints part of a page, without printer marks: leave out one or the other"));
}
let settings = print::Settings { pages, paper, orientation, layout, content, raster, crops: Vec::new(), area };
let laid_out = print::layout(&sizes, &settings).map_err(|e| bad(e.to_string()))?;
let sheets = laid_out.len();
@@ -391,13 +451,20 @@ impl Automation {
}
_ => return Err(bad("pass either path (save the print-ready PDF) or printer (a name from printers, or \"default\")")),
};
// Marks that would widen a page past the largest page a PDF can have fail here, before
// the Will Print actions run and could change the document for a print that then fails.
if let Some(m) = marks.as_ref()
&& self.doc(a)?.allows_printing()
{
self.session.check_printer_marks(id, &settings.pages, m).map_err(failed)?;
}
// The document's Will Print actions run first: what they change is printed (#269).
let scripts = if self.doc(a)?.allows_printing() {
self.session.run_document_actions(id, pdfcraft_engine::js::DocumentScriptEvent::WillPrint)
} else {
Default::default()
};
let bytes = self.session.print_pdf(id, &settings).map_err(failed)?;
let bytes = self.session.print_pdf_marked(id, &settings, marks.as_ref()).map_err(failed)?;
let mut out = json!({ "sheets": sheets, "pages": settings.pages.len(), "bytes": bytes.len() });
if let Some(c) = settings.raster.as_ref().and_then(|r| r.colour.as_ref()) {
out["color_management"] =
+5 -3
View File
@@ -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(
@@ -781,7 +781,7 @@ pub fn tools() -> Vec<ToolDef> {
t(
"doc_print",
"Print",
"Print with Acrobat's Print dialog options, or save the print-ready PDF. pages: a range such as \"1-3, 6, 9-\" (page labels allowed, \"(n)\" for the nth page whatever its label, unless a page is labelled exactly \"(n)\", since labels are looked up first; default all); subset odd/even (by page number, as Acrobat counts them: pages 2, 7-10 with even prints 2, 8 and 10, not every second page of the range); reverse. layout: fit (default), actual, shrink, custom (scale %), multiple (per_sheet 2/4/6/9/16, which turns the sheet to suit the grid, or a custom grid of cols across by rows down, each 1-99, on the sheet as oriented (auto prints portrait); order, border, auto_rotate; cut-stack order arranges single-sided sheets for cutting into piles and stacking left to right, top to bottom, keeping sheet order within each pile; duplex must be off), booklet (booklet_subset both/front/back, binding left/right; a booklet sets two-sided itself, as Acrobat does: both flips on the short edge, front or back prints one-sided), poster (scale %, overlap pt, cut_marks). orientation auto/portrait/landscape; comments_forms document / document-and-markups (default) / document-and-stamps / form-fields-only; paper Letter/Legal/Tabloid, ARCH A/B/C/D/E1/E, ANSI C/D/E, A0/A1/A2/A3/A4/A5/A6, US #10 Envelope, a driver paper name from printer_papers, or dimensions \"<w>x<h>\"; when printer is given and paper is omitted, uses the printer's default paper if available; use layout actual for 100% in the print-ready PDF; printer drivers may still substitute paper or scale. Then path (save) or printer (a name or \"default\") with copies, collate, duplex off/long-edge/short-edge, grayscale, and options (driver options from printer_options, CUPS). color_management app (Acrobat's Color Handling, the app managing colours) prints the pages as images converted into color_profile with rendering_intent and black_point_compensation; turn the driver's own colour management off for that job, or the printer converts them again. Any caller-supplied `media` option is replaced by the paper the document was laid out on."
"Print with Acrobat's Print dialog options, or save the print-ready PDF. pages: a range such as \"1-3, 6, 9-\" (page labels allowed, \"(n)\" for the nth page whatever its label, unless a page is labelled exactly \"(n)\", since labels are looked up first; default all); subset odd/even (by page number, as Acrobat counts them: pages 2, 7-10 with even prints 2, 8 and 10, not every second page of the range); reverse. layout: fit (default), actual, shrink, custom (scale %), multiple (per_sheet 2/4/6/9/16, which turns the sheet to suit the grid, or a custom grid of cols across by rows down, each 1-99, on the sheet as oriented (auto prints portrait); order, border, auto_rotate; cut-stack order arranges single-sided sheets for cutting into piles and stacking left to right, top to bottom, keeping sheet order within each pile; duplex must be off), booklet (booklet_subset both/front/back, binding left/right; a booklet sets two-sided itself, as Acrobat does: both flips on the short edge, front or back prints one-sided), poster (scale %, overlap pt, cut_marks). marks (Acrobat's Marks and Bleeds, with a one-page-a-sheet layout: fit, actual, shrink or custom): a list of all, trim, bleed, registration, color_bars and page_info (document name, page n of N, date), drawn around each page on the printed copy only, in registration colour except the colour bars, at marks_weight points (0.1 to 4, default 0.25); the page is widened for them, so fit shrinks it to make room, and marks the document already has print once; not with as_image, color_management app or area. orientation auto/portrait/landscape; comments_forms document / document-and-markups (default) / document-and-stamps / form-fields-only; paper Letter/Legal/Tabloid, ARCH A/B/C/D/E1/E, ANSI C/D/E, A0/A1/A2/A3/A4/A5/A6, US #10 Envelope, a driver paper name from printer_papers, or dimensions \"<w>x<h>\"; when printer is given and paper is omitted, uses the printer's default paper if available; use layout actual for 100% in the print-ready PDF; printer drivers may still substitute paper or scale. Then path (save) or printer (a name or \"default\") with copies, collate, duplex off/long-edge/short-edge, grayscale, and options (driver options from printer_options, CUPS). color_management app (Acrobat's Color Handling, the app managing colours) prints the pages as images converted into color_profile with rendering_intent and black_point_compensation; turn the driver's own colour management off for that job, or the printer converts them again. Any caller-supplied `media` option is replaced by the paper the document was laid out on."
)
.with(schema(
json!({
@@ -802,6 +802,8 @@ pub fn tools() -> Vec<ToolDef> {
"creep": { "type": "number", "minimum": 0, "maximum": 10, "description": "Booklet creep compensation: points each sheet's pages move toward the fold, times the sheet's place from the outside (default 0)." },
"overlap": { "type": "number", "minimum": 0 },
"cut_marks": { "type": "boolean" },
"marks": { "type": "array", "items": { "type": "string", "enum": ["all", "trim", "bleed", "registration", "color_bars", "page_info"] }, "description": "Printer's marks drawn around each page on the printed copy only (one page a sheet; not with as_image, color_management app or area)." },
"marks_weight": { "type": "number", "minimum": 0.1, "maximum": 4, "description": "With marks: their line weight in points (default 0.25)." },
"orientation": { "type": "string", "enum": ["auto", "portrait", "landscape"] },
"comments_forms": { "type": "string", "enum": ["document", "document-and-markups", "document-and-stamps", "form-fields-only"] },
"paper": { "type": "string", "description": "A paper name (US Letter, A4…) or a size of its own such as 8.5x14in, 210x297mm, 10x15cm or 612x792pt (1 to 200 inches a side). The paper the document is laid out on determines the `media` option sent to the printer; any caller-supplied `media` option in `options` is replaced by this paper." },
+149 -1
View File
@@ -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]
@@ -10564,6 +10579,36 @@ fn xfa_forms_flatten_and_convert_to_static_through_tools() {
assert!(text.to_string().contains("Japan"), "{text}");
}
/// A check box whose change script shows a section that needs a second page: the tools see
/// the new page and the new fields' places, and the form saves and reopens with both pages.
#[test]
fn an_xfa_script_that_adds_a_page_is_seen_and_saved_through_tools() {
let dir = workdir("xfa-script-page");
std::fs::write(dir.join("grow.pdf"), pdfcraft_xfa::fixtures::shell(&pdfcraft_xfa::fixtures::presence_growth_template(false, "", "", "")))
.unwrap();
let mut a = auto(&dir);
let doc = ok(&mut a, "doc_open", json!({ "path": "grow.pdf" }))["doc"].as_u64().unwrap();
let pages_of = |a: &mut Automation, doc: u64| {
let list = ok(a, "doc_list", json!({}));
list["documents"].as_array().unwrap().iter().find(|d| d["doc"] == doc).unwrap()["pages"].as_u64().unwrap()
};
assert_eq!(pages_of(&mut a, doc), 1);
ok(&mut a, "form_fill", json!({ "doc": doc, "values": { "more": true } }));
assert_eq!(pages_of(&mut a, doc), 2);
let fields = ok(&mut a, "form_fields", json!({ "doc": doc }));
let d2 = fields["fields"].as_array().unwrap().iter().find(|f| f["name"] == "d2").unwrap().clone();
assert_eq!(d2["page"], 2, "{d2}");
assert!(d2["rect"].is_array(), "{d2}");
ok(&mut a, "doc_save", json!({ "doc": doc, "path": "saved.pdf" }));
let again = ok(&mut a, "doc_open", json!({ "path": "saved.pdf" }))["doc"].as_u64().unwrap();
assert_eq!(pages_of(&mut a, again), 2);
// The second page keeps its field: on page 2, at the place it had before saving.
let fields = ok(&mut a, "form_fields", json!({ "doc": again }));
let saved_d2 = fields["fields"].as_array().unwrap().iter().find(|f| f["name"] == "d2").unwrap().clone();
assert_eq!(saved_d2["page"], 2, "{saved_d2}");
assert_eq!(saved_d2["rect"], d2["rect"], "{saved_d2}");
}
#[test]
fn xfa_data_files_export_and_import_through_tools() {
let dir = workdir("xfa-data");
@@ -11376,11 +11421,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]
@@ -12885,6 +12961,78 @@ fn printer_marks_through_tools() {
));
}
/// Marks and bleeds when printing: the marks are on the printed sheets, the document gets none.
#[test]
fn printing_with_printer_marks_through_tools() {
let dir = workdir("print-marks");
let mut a = auto(&dir);
let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap();
let before = page_text(&mut a, doc);
let width = ok(&mut a, "doc_info", json!({ "doc": doc }))["pages"][1]["width"].clone();
let r =
ok(&mut a, "doc_print", json!({ "doc": doc, "pages": "2", "layout": "actual", "marks": ["all"], "marks_weight": 0.5, "path": "marked.pdf" }));
assert_eq!(r["sheets"], 1);
let printed = ok(&mut a, "doc_open", json!({ "path": "marked.pdf" }))["doc"].as_u64().unwrap();
let sheet = page_text(&mut a, printed).concat();
assert!(sheet.contains("a.pdf") && sheet.contains("2 of 3"), "the page information line: {sheet}");
ok(&mut a, "doc_close", json!({ "doc": printed }));
ok(&mut a, "doc_print", json!({ "doc": doc, "pages": "2", "marks": ["trim", "registration"], "path": "trim.pdf" }));
let trim = ok(&mut a, "doc_open", json!({ "path": "trim.pdf" }))["doc"].as_u64().unwrap();
assert!(!page_text(&mut a, trim).concat().contains("2 of 3"), "only the marks asked for");
// The document itself is untouched.
assert_eq!(page_text(&mut a, doc), before);
let info = ok(&mut a, "doc_info", json!({ "doc": doc }));
assert_eq!((&info["pages"][1]["width"], &info["document"]["dirty"]), (&width, &json!(false)));
for (wrong, says) in [
(json!({ "marks": [] }), "marks must be a list"),
(json!({ "marks": ["crop"] }), "marks must be a list"),
(json!({ "marks": "all" }), "marks must be a list"),
(json!({ "marks": ["all"], "marks_weight": 10 }), "marks_weight must be from"),
(json!({ "marks_weight": 1 }), "marks_weight needs marks"),
(json!({ "marks": ["all"], "layout": "multiple", "per_sheet": 2 }), "one page a sheet"),
(json!({ "marks": ["all"], "layout": "booklet" }), "one page a sheet"),
(json!({ "marks": ["all"], "as_image": true }), "as they are"),
(json!({ "marks": ["all"], "pages": "1", "area": [0, 0, 50, 50] }), "without printer marks"),
] {
let mut args = wrong.clone();
args["doc"] = json!(doc);
args["path"] = json!("x.pdf");
match a.call("doc_print", &args) {
Err(ToolError::InvalidArgs(m)) => assert!(m.contains(says), "{wrong}: {m}"),
other => panic!("{wrong}: {other:?}"),
}
}
assert!(!dir.join("x.pdf").exists());
let _ = std::fs::remove_dir_all(dir);
}
/// Marks on a protected document: low-resolution-only printing refuses the marks, since it
/// prints as pictures; no printing at all is the permission error, not the marks one.
#[test]
fn printing_marks_on_a_print_restricted_document_through_tools() {
let dir = workdir("print-marks-restricted");
let mut a = auto(&dir);
for (printing, file) in [("low", "low.pdf"), ("none", "none.pdf")] {
let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap();
ok(&mut a, "doc_protect", json!({ "doc": doc, "permissions_password": "boss", "printing": printing }));
ok(&mut a, "doc_save", json!({ "doc": doc, "path": file }));
ok(&mut a, "doc_close", json!({ "doc": doc }));
}
let mut b = auto(&dir);
let low = ok(&mut b, "doc_open", json!({ "path": "low.pdf" }))["doc"].as_u64().unwrap();
match b.call("doc_print", &json!({ "doc": low, "pages": "1", "marks": ["all"], "path": "x.pdf" })) {
Err(ToolError::InvalidArgs(m)) => assert!(m.contains("low-resolution"), "{m}"),
other => panic!("low-resolution only: {other:?}"),
}
let none = ok(&mut b, "doc_open", json!({ "path": "none.pdf" }))["doc"].as_u64().unwrap();
match b.call("doc_print", &json!({ "doc": none, "pages": "1", "marks": ["all"], "path": "x.pdf" })) {
Err(ToolError::Failed(m)) => assert!(m.contains("don't allow printing"), "{m}"),
other => panic!("no printing: {other:?}"),
}
assert!(!dir.join("x.pdf").exists());
let _ = std::fs::remove_dir_all(dir);
}
/// Convert colours through the tools: counts, converts, reports nothing to do.
#[test]
fn convert_colours_through_tools() {
@@ -123,3 +123,30 @@ fn js_event_runs_the_field_its_field_id_names() {
);
let _ = std::fs::remove_dir_all(&dir);
}
/// Printer marks that would widen a 14,400 pt page past the largest page a PDF can have are
/// refused before Will Print runs, so its field change isn't left behind by a print that fails.
#[test]
fn marks_that_cannot_fit_fail_before_will_print() {
let pdf = pdf_of(&[
"<< /Type /Catalog /Pages 2 0 R /AA << /WP 6 0 R >> /AcroForm << /Fields [4 0 R] /DA (/Helv 0 Tf 0 g) /DR << /Font << /Helv 5 0 R >> >> >> >>".into(),
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 14400 300] >>".into(),
"<< /Type /Page /Parent 2 0 R /Annots [4 0 R] >>".into(),
"<< /Type /Annot /Subtype /Widget /FT /Tx /T (log) /V () /Rect [20 250 180 270] /P 3 0 R /F 4 >>".into(),
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".into(),
"<< /S /JavaScript /JS (getField\\('log'\\).value += 'print;';) >>".into(),
]);
let dir = std::env::temp_dir().join(format!("pdfcraft-marks-will-print-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("wide.pdf"), pdf).unwrap();
let mut a = Automation::new().with_root(&dir).unwrap().with_clock(|| 1_700_000_000);
let doc = tool(&mut a, "doc_open", json!({ "path": "wide.pdf" }))["doc"].as_u64().unwrap();
let refused = a.call("doc_print", &json!({ "doc": doc, "marks": ["trim"], "path": "marked.pdf" }));
assert!(refused.is_err(), "{refused:?}");
assert_eq!(log(&mut a, doc).as_str().unwrap_or_default(), "", "Will Print didn't run");
assert!(!dir.join("marked.pdf").exists());
// Without marks the page prints, and Will Print runs.
tool(&mut a, "doc_print", json!({ "doc": doc, "path": "plain.pdf" }));
assert_eq!(log(&mut a, doc), "print;");
let _ = std::fs::remove_dir_all(dir);
}
+52 -1
View File
@@ -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
View File
@@ -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));
}
}
+347
View File
@@ -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
View File
@@ -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();
+6
View File
@@ -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,
+62 -1
View File
@@ -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
}
+23 -7
View File
@@ -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.
+171
View File
@@ -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));
}
}
+2 -1
View File
@@ -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
});
+46 -11
View File
@@ -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);
+44
View File
@@ -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,
}
}
+7 -1
View File
@@ -260,6 +260,8 @@ pub(crate) struct EditCtx {
pub(crate) xfa_unchanged: bool,
/// What the XFA scripts' time limits are multiplied by ([`Session::with_xfa_time_scale`]).
pub(crate) xfa_time_scale: u32,
/// The form's scripts or new data laid it out again: its pages and widgets were replaced.
pub(crate) xfa_relaid: bool,
/// The edit took the XFA out of the form: what went with it, for the document's warnings.
pub(crate) xfa_removed: Vec<String>,
/// Pages in the document, for `xfa.layout.pageCount()`.
@@ -331,6 +333,7 @@ impl EditCtx {
xfa_ran_away: false,
xfa_unchanged: false,
xfa_time_scale: 1,
xfa_relaid: false,
xfa_removed: Vec::new(),
pages: 0,
highlight: false,
@@ -791,6 +794,7 @@ pub(crate) fn run_edit(doc: &mut pdfcraft_cos::Document, edit: &Edit, cx: &mut E
ran_away: false,
highlight,
time_scale: cx.xfa_time_scale,
relaid: false,
};
let ran = if matches!(activity.as_str(), "enter" | "exit") {
xfa::on_focus(doc, &tpl, som, activity, &mut run).map(|changes| changes.is_empty())
@@ -799,10 +803,12 @@ pub(crate) fn run_edit(doc: &mut pdfcraft_cos::Document, edit: &Edit, cx: &mut E
};
cx.xfa_datasets = run.datasets;
cx.xfa_ran_away |= run.ran_away;
cx.xfa_relaid |= run.relaid;
// The next edit of a batch reads the highlight this one's scripts set.
let on = run.highlight;
cx.set_highlight(on);
cx.xfa_unchanged = ran.map_err(EditError::Invalid)?;
// A form laid out again changed, whatever its scripts counted.
cx.xfa_unchanged = ran.map_err(EditError::Invalid)? && !cx.xfa_relaid;
}
Edit::SetFieldImage { name, image } | Edit::SetFieldImageTarget { name, image, .. } => {
let object = match edit {
+9
View File
@@ -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
+1
View File
@@ -225,6 +225,7 @@ impl Session {
ran_away: false,
highlight: context.highlight,
time_scale: context.xfa_time_scale,
relaid: false,
};
let changes = xfa::on_open(&mut work, &tpl, &mut run);
if run.ran_away {
+9
View File
@@ -278,6 +278,7 @@ impl Session {
ran_away: false,
highlight,
time_scale: cx.xfa_time_scale,
relaid: false,
};
// Every changed field's scripts, then the calculations once (after a reset,
// only those).
@@ -285,6 +286,7 @@ impl Session {
.unwrap_or_else(|m| Err(format!("the form's scripts failed unexpectedly ({m})")));
cx.xfa_datasets = run.datasets;
cx.xfa_ran_away |= run.ran_away;
cx.xfa_relaid |= run.relaid;
// The next edit of a batch reads the highlight this one's scripts set.
let on = run.highlight;
cx.set_highlight(on);
@@ -293,6 +295,13 @@ impl Session {
}
}
}
// The form's scripts (a check box showing a section) or its new data (a picture) laid
// it out again, even if a later script then failed: as with text growth below, its
// pages, widgets and fields were replaced, whether or not the page count changed. The
// view and undo/redo rebuild them instead of refreshing only field values.
if cx.xfa_relaid {
scope = Scope::Full;
}
// XFA forms keep their values in the datasets packet too, for Adobe's viewers.
let mut xfa_notes = Vec::new();
if is_xfa && matches!(scope_of(&edit), Scope::Form | Scope::Full | Scope::Content) {
+51
View File
@@ -4,6 +4,9 @@ use super::{
print_layer_states, print_raster, set_default_layer_state, source_kind, writable, write_full,
};
/// Why printer's marks were refused for a print that goes as pictures.
const MARKS_AS_PICTURES: &str = "printer marks print with the pages as they are, not as pictures: leave out as_image and app-managed colour (a document that allows only low-resolution printing always prints as pictures)";
/// Whether a conversion may run LibreOffice for an Office document (seconds, in another
/// process) or must refuse it because the caller is on the frame thread.
#[derive(Clone, Copy, PartialEq, Eq)]
@@ -229,6 +232,36 @@ impl Session {
/// The print-ready PDF for `settings` (sheets laid out for the paper; see `pdfcraft-print`).
pub fn print_pdf(&self, id: DocId, settings: &print::Settings) -> Result<Vec<u8>, EditError> {
self.print_pdf_marked(id, settings, None)
}
/// Whether printer's marks fit around `pages` (0-based): [`pdfcraft_edit::add_printer_marks`]
/// run on a scratch copy, so a page the marks would widen past the largest page a PDF can
/// have is refused before anything (the Will Print actions) changes the document. The copy
/// is dropped; [`Session::print_pdf_marked`] adds the marks again on the print copy.
pub fn check_printer_marks(&self, id: DocId, pages: &[usize], marks: &crate::PrinterMarks) -> Result<(), EditError> {
let doc = self.get(id).ok_or(EditError::NoDocument)?;
let mut cos = match doc.editor.as_ref() {
Some(e) => e.cos.clone(),
None => {
pdfcraft_cos::Document::open_with_password(doc.bytes.clone(), doc.password.as_deref()).map_err(|e| EditError::Write(e.to_string()))?
}
};
let mut pages = pages.to_vec();
pages.sort_unstable();
pages.dedup();
pdfcraft_edit::add_printer_marks(&mut cos, &pages, marks, true)?;
Ok(())
}
/// [`Session::print_pdf`] with printer's marks (Acrobat's Marks and Bleeds) drawn around each
/// printed page on the print copy only: the document itself gets none. A page is widened for
/// them as [`pdfcraft_edit::add_printer_marks`] widens it, and marks the document already
/// carries are replaced, so a page never prints two sets. With form fields only, the fields
/// and the marks print and the page content doesn't. The pages print as they are, so
/// marks can't go with a print as pictures (Print as image, app-managed colour, or a document
/// that allows only low-resolution printing).
pub fn print_pdf_marked(&self, id: DocId, settings: &print::Settings, marks: Option<&crate::PrinterMarks>) -> Result<Vec<u8>, EditError> {
let doc = self.get(id).ok_or(EditError::NoDocument)?;
if !doc.allows_printing() {
return Err(EditError::NotPermitted("printing"));
@@ -243,6 +276,9 @@ impl Session {
// Print as image: the pages used become pictures first, then the picture document is
// imposed in their place (its page k is the k-th distinct source page used).
if let Some(raster) = low_res.as_ref().or(settings.raster.as_ref()) {
if marks.is_some() {
return Err(EditError::Print(MARKS_AS_PICTURES.into()));
}
let mut distinct: Vec<usize> = Vec::new();
for &p in &settings.pages {
if !distinct.contains(&p) {
@@ -287,6 +323,21 @@ impl Session {
if doc.signatures.iter().any(|s| s.verdict_shown) {
let _ = pdfcraft_sign::show_status_layers(&mut cos, &mut doc.signatures.to_vec(), &doc.captions);
}
let marked;
let mut settings = settings;
if let Some(marks) = marks {
// Form fields only prints no page content, so the page content goes before the
// marks are added, and the marks then print as the page content does.
if settings.content == print::Content::FormFieldsOnly {
pdfcraft_print::keep_printed(&mut cos, print::Content::FormFieldsOnly);
marked = print::Settings { content: print::Content::Document, ..settings.clone() };
settings = &marked;
}
let mut pages = settings.pages.clone();
pages.sort_unstable();
pages.dedup();
pdfcraft_edit::add_printer_marks(&mut cos, &pages, marks, true)?;
}
pdfcraft_print::impose(&cos, settings).map_err(|e| EditError::Print(e.to_string()))
}
+185 -2
View File
@@ -5,6 +5,8 @@ use super::edit::{EditCtx, check_permission, run_edit};
use super::*;
use pdfcraft_render::{Layer, LayerOp, OpenError, ReadingColors};
mod print_marks;
/// A minimal `n`-page document; page `i` shows "Page i+1".
pub(crate) fn fixture(n: usize) -> Vec<u8> {
let mut objs: Vec<Vec<u8>> = vec![b"<< /Type /Catalog /Pages 2 0 R >>".to_vec()];
@@ -7500,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/">
@@ -8312,11 +8346,13 @@ fn on_changes_notes_only_the_exits_that_ran() {
let names = vec!["probe".to_string()];
let mut exited = Vec::new();
let mut out = crate::js::JsOutput::default();
let mut stopped = crate::xfa::XfaRun { page_count: 1, out: &mut out, datasets: None, ran_away: true, highlight: false, time_scale: 1 };
let mut stopped =
crate::xfa::XfaRun { page_count: 1, out: &mut out, datasets: None, ran_away: true, highlight: false, time_scale: 1, relaid: false };
crate::xfa::on_changes(&mut cos, &tpl, &names, &mut stopped, &mut exited).unwrap();
assert!(exited.is_empty(), "no exit ran: {exited:?}");
let mut out = crate::js::JsOutput::default();
let mut running = crate::xfa::XfaRun { page_count: 1, out: &mut out, datasets: None, ran_away: false, highlight: false, time_scale: 1 };
let mut running =
crate::xfa::XfaRun { page_count: 1, out: &mut out, datasets: None, ran_away: false, highlight: false, time_scale: 1, relaid: false };
crate::xfa::on_changes(&mut cos, &tpl, &names, &mut running, &mut exited).unwrap();
assert_eq!(exited.len(), 1, "the exit ran: {exited:?}");
}
@@ -9389,6 +9425,153 @@ fn filling_growable_xfa_text_reflows_and_undo_restores_the_layout() {
}
}
/// What the last edit (the top of the undo stack) said it changed.
fn last_scope(s: &Session, id: DocId) -> crate::history::Scope {
s.get(id).unwrap().editor.as_ref().unwrap().undo.last().unwrap().3
}
/// The view's entry for field `name`: its page index and first widget's rectangle.
fn field_place(s: &Session, id: DocId, name: &str) -> (Option<usize>, Option<[f32; 4]>) {
let f = s.get(id).unwrap().info.fields.iter().find(|f| f.name == name).unwrap_or_else(|| panic!("no field {name}")).clone();
(f.page, f.rect)
}
/// Bytes that save and reopen as the document the session shows (the save check of #1698).
fn saves_and_reopens(s: &mut Session, id: DocId, pages: usize) {
let bytes = s.save_bytes(id).unwrap();
s.check_save(id, &bytes).unwrap();
let again = s.open("saved.pdf", None, bytes, None).unwrap();
assert_eq!(s.get(again).unwrap().info.pages.len(), pages);
s.close(again);
}
/// A check box's change script that shows a hidden section lays the form out onto a second
/// page: the view's pages and fields are rebuilt, the file saves and reopens, undo and redo
/// rebuild them too, and hiding the section again takes the page away.
#[test]
fn an_xfa_script_that_shows_a_section_adds_its_page_and_undo_takes_it_away() {
let template = pdfcraft_xfa::fixtures::presence_growth_template(false, "", "", "");
let mut s = Session::new().with_clock(|| 1_700_000_000);
let id = s.open("grow.pdf", None, Arc::new(pdfcraft_xfa::fixtures::shell(&template)), None).unwrap();
let pages = |s: &Session| s.get(id).unwrap().info.pages.len();
let fields = |s: &Session| s.get(id).unwrap().info.fields.len();
assert_eq!(pages(&s), 1);
let before = fields(&s);
assert!(s.get(id).unwrap().info.fields.iter().all(|f| f.name != "d1"), "a hidden section has no widgets");
s.apply(id, Edit::SetFieldValue { name: "more".into(), value: FieldValue::Check(true) }).unwrap();
let out = s.take_js_output(id);
assert_eq!(pages(&s), 2, "{:?}", out.errors);
assert_eq!(last_scope(&s, id), crate::history::Scope::Full);
assert_eq!(fields(&s), s.get(id).unwrap().form.len(), "the field list is the form's");
assert!(fields(&s) > before);
for name in ["d1", "d2"] {
let (page, rect) = field_place(&s, id, name);
assert_eq!(page, Some(1), "{name}");
assert!(rect.is_some(), "{name}");
}
saves_and_reopens(&mut s, id, 2);
// A value typed into the new section lays nothing out: only the values are refreshed.
s.apply(id, Edit::SetFieldValue { name: "d1".into(), value: FieldValue::Text("typed".into()) }).unwrap();
assert_eq!(last_scope(&s, id), crate::history::Scope::Form);
assert_eq!(pages(&s), 2);
s.undo(id).unwrap();
s.undo(id).unwrap();
assert_eq!(pages(&s), 1);
assert_eq!(fields(&s), before);
saves_and_reopens(&mut s, id, 1);
s.redo(id).unwrap();
assert_eq!(pages(&s), 2);
assert_eq!(field_place(&s, id, "d2").0, Some(1));
saves_and_reopens(&mut s, id, 2);
// Hidden again: the form shrinks back to one page.
s.apply(id, Edit::SetFieldValue { name: "more".into(), value: FieldValue::Check(false) }).unwrap();
assert_eq!(pages(&s), 1);
assert_eq!(fields(&s), before);
saves_and_reopens(&mut s, id, 1);
}
/// A relayout that keeps the page count still replaces the pages: a field the shown section
/// pushes onto the second page is placed there in the view.
#[test]
fn an_xfa_script_relayout_that_keeps_the_page_count_moves_fields_in_the_view() {
let after = r#"<field name="late" w="3in" h="0.5in"><ui><textEdit/></ui></field><draw name="tail" w="7.5in" h="2in"><value><text>Tail</text></value></draw>"#;
let template = pdfcraft_xfa::fixtures::presence_growth_template(false, "", after, "");
let mut s = Session::new().with_clock(|| 1_700_000_000);
let id = s.open("moves.pdf", None, Arc::new(pdfcraft_xfa::fixtures::shell(&template)), None).unwrap();
assert_eq!(s.get(id).unwrap().info.pages.len(), 2);
assert_eq!(field_place(&s, id, "late").0, Some(0));
s.apply(id, Edit::SetFieldValue { name: "more".into(), value: FieldValue::Check(true) }).unwrap();
assert_eq!(s.get(id).unwrap().info.pages.len(), 2, "{:?}", s.take_js_output(id).errors);
let (page, rect) = field_place(&s, id, "late");
assert_eq!(page, Some(1));
let widget = s.get(id).unwrap().form.iter().find(|f| f.name == "late").unwrap().widgets[0].rect;
assert_eq!(rect, Some(widget.map(|v| v as f32)), "the view has the new widget's place");
s.undo(id).unwrap();
assert_eq!(field_place(&s, id, "late").0, Some(0));
saves_and_reopens(&mut s, id, 2);
}
/// A reset whose calculations hide the section lays the form out again too.
#[test]
fn an_xfa_reset_whose_calculations_hide_a_section_takes_its_page_away() {
let template = pdfcraft_xfa::fixtures::presence_growth_template(true, "", "", "");
let mut s = Session::new().with_clock(|| 1_700_000_000);
let id = s.open("reset.pdf", None, Arc::new(pdfcraft_xfa::fixtures::shell(&template)), None).unwrap();
assert_eq!(s.get(id).unwrap().info.pages.len(), 1);
s.apply(id, Edit::SetFieldValue { name: "more".into(), value: FieldValue::Check(true) }).unwrap();
assert_eq!(s.get(id).unwrap().info.pages.len(), 2, "{:?}", s.take_js_output(id).errors);
s.apply(id, Edit::ResetForm { names: None }).unwrap();
assert_eq!(s.get(id).unwrap().info.pages.len(), 1, "{:?}", s.take_js_output(id).errors);
assert_eq!(last_scope(&s, id), crate::history::Scope::Full);
saves_and_reopens(&mut s, id, 1);
s.undo(id).unwrap();
assert_eq!(s.get(id).unwrap().info.pages.len(), 2);
}
/// Two relayouts in one event, and a script that fails after them: the form was still laid
/// out again, so the view is rebuilt.
#[test]
fn an_xfa_event_that_lays_out_twice_then_fails_still_rebuilds_the_view() {
let template = pdfcraft_xfa::fixtures::presence_growth_template(false, "", "", r#"xfa.layout.relayout(); throw new Error("late failure");"#);
let mut s = Session::new().with_clock(|| 1_700_000_000);
let id = s.open("twice.pdf", None, Arc::new(pdfcraft_xfa::fixtures::shell(&template)), None).unwrap();
s.apply(id, Edit::SetFieldValue { name: "more".into(), value: FieldValue::Check(true) }).unwrap();
let out = s.take_js_output(id);
assert!(out.errors.iter().any(|e| e.contains("late failure")), "{:?}", out.errors);
assert_eq!(s.get(id).unwrap().info.pages.len(), 2);
assert_eq!(last_scope(&s, id), crate::history::Scope::Full);
saves_and_reopens(&mut s, id, 2);
}
/// A picture chosen for an image field lays the form out again from its data.
#[test]
fn an_xfa_picture_lays_the_form_out_again_and_rebuilds_the_view() {
let after = r#"<field name="photo" w="1in" h="1in"><ui><imageEdit/></ui></field>"#;
let template = pdfcraft_xfa::fixtures::presence_growth_template(false, "", after, "");
let mut s = Session::new().with_clock(|| 1_700_000_000);
let id = s.open("photo.pdf", None, Arc::new(pdfcraft_xfa::fixtures::shell(&template)), None).unwrap();
s.apply(id, Edit::SetFieldImage { name: "photo".into(), image: Arc::new(pdfcraft_xfa::fixtures::TINY_GIF.to_vec()) }).unwrap();
assert_eq!(last_scope(&s, id), crate::history::Scope::Full, "{:?}", s.take_js_output(id).errors);
saves_and_reopens(&mut s, id, 1);
}
/// Text growth, then a script: each lays the form out onto one more page, and it saves.
#[test]
fn xfa_text_growth_then_a_script_relayout_both_add_pages() {
let before = r#"<field name="notes" w="7.5in" minH="0.5in"><ui><textEdit multiLine="1"/></ui></field>"#;
let template = pdfcraft_xfa::fixtures::presence_growth_template(false, before, "", "");
let mut s = Session::new().with_clock(|| 1_700_000_000);
let id = s.open("mixed.pdf", None, Arc::new(pdfcraft_xfa::fixtures::shell(&template)), None).unwrap();
assert_eq!(s.get(id).unwrap().info.pages.len(), 1);
let notes: String = (1..=60).map(|i| format!("line {i}\n")).collect();
s.apply(id, Edit::SetFieldValue { name: "notes".into(), value: FieldValue::Text(notes) }).unwrap();
assert_eq!(s.get(id).unwrap().info.pages.len(), 2);
saves_and_reopens(&mut s, id, 2);
s.apply(id, Edit::SetFieldValue { name: "more".into(), value: FieldValue::Check(true) }).unwrap();
assert_eq!(s.get(id).unwrap().info.pages.len(), 3, "{:?}", s.take_js_output(id).errors);
saves_and_reopens(&mut s, id, 3);
}
#[test]
fn xfa_text_growth_refreshes_widget_geometry_but_fixed_height_fields_keep_their_widgets() {
for fixed in [false, true] {
+87
View File
@@ -0,0 +1,87 @@
//! Printer's marks on the printed copy only (Acrobat's Marks and Bleeds).
use super::*;
fn marks() -> PrinterMarks {
PrinterMarks { label: "proof.pdf".into(), date: "2026-11-12".into(), ..PrinterMarks::default() }
}
fn actual(pages: Vec<usize>) -> print::Settings {
print::Settings { pages, layout: print::Layout::Size(print::SizeMode::Actual), ..Default::default() }
}
/// The pixels on the first sheet that aren't white.
fn inked(bytes: Vec<u8>) -> usize {
let (_, _, rgba) = printed_pixels(bytes);
rgba.as_chunks::<4>().0.iter().filter(|p| p[0] < 200 || p[1] < 200 || p[2] < 200).count()
}
fn sheet_texts(bytes: Vec<u8>) -> Vec<String> {
let mut s = Session::new();
let id = s.open("sheets.pdf", None, Arc::new(bytes), None).unwrap();
page_texts(&s, id)
}
#[test]
fn printer_marks_go_on_the_printed_sheets_and_not_the_document() {
let (s, id) = session_with(3);
let before = s.get(id).unwrap().bytes.clone();
let plain = s.print_pdf(id, &actual(vec![1])).unwrap();
let marked = s.print_pdf_marked(id, &actual(vec![1]), Some(&marks())).unwrap();
assert!(inked(marked.clone()) > inked(plain.clone()) + 200, "trim and bleed marks, targets and colour bars are drawn");
let texts = sheet_texts(marked);
assert!(texts[0].contains("proof.pdf") && texts[0].contains("2 of 3") && texts[0].contains("2026-11-12"), "{texts:?}");
assert!(!sheet_texts(plain)[0].contains("2 of 3"));
let doc = s.get(id).unwrap();
assert!(Arc::ptr_eq(&doc.bytes, &before) && !doc.dirty, "the document itself is untouched");
}
/// Each printed page carries its own place in the document, in the order printed, a page
/// printed twice included.
#[test]
fn each_printed_page_is_marked_with_its_own_number() {
let (s, id) = session_with(4);
let texts = sheet_texts(s.print_pdf_marked(id, &actual(vec![2, 0, 2]), Some(&marks())).unwrap());
assert_eq!(texts.len(), 3, "{texts:?}");
for (text, page) in texts.iter().zip(["3 of 4", "1 of 4", "3 of 4"]) {
assert_eq!(text.matches(" of 4").count(), 1, "{texts:?}");
assert!(text.contains(page), "{page}: {texts:?}");
}
}
#[test]
fn marks_the_document_already_has_are_replaced_on_paper() {
let (mut s, id) = session_with(2);
let old = PrinterMarks { label: "old.pdf".into(), date: "2020-01-01".into(), ..PrinterMarks::default() };
s.apply(id, Edit::AddPrinterMarks { pages: vec![0], settings: old, replace: true }).unwrap();
let texts = sheet_texts(s.print_pdf_marked(id, &actual(vec![0]), Some(&marks())).unwrap());
assert!(texts[0].contains("proof.pdf") && texts[0].contains("2026-11-12"), "the print's marks: {texts:?}");
assert!(!texts[0].contains("old.pdf") && !texts[0].contains("2020-01-01"), "the document's marks are replaced: {texts:?}");
}
#[test]
fn printer_marks_are_refused_for_a_print_as_pictures() {
let (s, id) = session_with(1);
let raster = Some(print::Raster { dpi: 72.0, grayscale: false, colour: None });
let settings = print::Settings { raster, ..actual(vec![0]) };
assert!(matches!(s.print_pdf_marked(id, &settings, Some(&marks())), Err(EditError::Print(m)) if m.contains("as_image")));
assert!(s.print_pdf_marked(id, &settings, None).is_ok());
}
/// Form fields only prints the fields and the marks, without the page content or comments.
#[test]
fn printer_marks_print_with_form_fields_only() {
let mut s = Session::new();
let id = s.open("fields.pdf", None, Arc::new(print_content_pdf()), None).unwrap();
let marks = PrinterMarks { color_bars: false, registration: false, ..marks() };
let settings = print::Settings { paper: (300.0, 600.0), content: print::Content::FormFieldsOnly, ..actual(vec![0]) };
let bytes = s.print_pdf_marked(id, &settings, Some(&marks)).unwrap();
assert!(sheet_texts(bytes.clone())[0].contains("1 of 1"), "the page information line prints");
let (_, _, rgba) = printed_pixels(bytes);
let count = |c: [u8; 3]| rgba.as_chunks::<4>().0.iter().filter(|p| p[..3].iter().zip(c).all(|(&a, b)| a.abs_diff(b) < 40)).count();
assert!(count([0, 255, 0]) > 5000, "the field prints");
assert_eq!((count([0, 0, 255]), count([255, 0, 0]), count([255, 255, 0])), (0, 0, 0), "no page content, stamp or comment");
let plain = s.print_pdf(id, &settings).unwrap();
let (with, without) = (inked(s.print_pdf_marked(id, &settings, Some(&marks)).unwrap()), inked(plain));
assert!(with > without + 100, "trim and bleed marks print: {with} inked pixels, {without} without marks");
}
+5
View File
@@ -135,6 +135,9 @@ pub(crate) struct XfaRun<'a> {
/// start and each script's own): 1, unless the session was given another
/// ([`crate::Session::with_xfa_time_scale`]).
pub time_scale: u32,
/// The form was laid out again: its pages, widgets and fields were replaced, so the edit
/// must rebuild the document's page and field lists, not only refresh their values.
pub relaid: bool,
}
/// The script engine's copies of a form's property trees, by the address of the tree each was
@@ -762,6 +765,8 @@ impl<'a, 'b> Runner<'a, 'b> {
}
self.relayouts += 1;
self.flush()?;
// Set before the layout: one that fails part way may already have replaced fields.
self.run.relaid = true;
self.embedded_changed = false;
let report = pdfcraft_xfa::rerender(self.doc, self.tpl).map_err(|e| e.to_string())?;
self.console(report.warnings);
+2
View File
@@ -243,11 +243,13 @@ pub(crate) fn xfa_after_data_change(doc: &mut pdfcraft_cos::Document, cx: &mut E
ran_away: false,
highlight,
time_scale: cx.xfa_time_scale,
relaid: false,
};
let r = guard(|| xfa::on_data_replaced(doc, &tpl, calculate, &mut run))
.unwrap_or_else(|m| Err(format!("laying the form out again failed unexpectedly ({m})")));
cx.xfa_datasets = run.datasets;
cx.xfa_ran_away |= run.ran_away;
cx.xfa_relaid |= run.relaid;
// The next edit of a batch reads the highlight this one's scripts set.
let on = run.highlight;
cx.set_highlight(on);
+168 -27
View File
@@ -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;
+158 -2
View File
@@ -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
+81 -11
View File
@@ -18,18 +18,31 @@ pub struct Page {
pub dict: Dict,
}
/// The side, in points, at or below which a `/MediaBox` has no area and the page falls back to
/// US Letter (the renderer's `is_nearly_zero`, 1/4096).
/// The side, in points, at or below which a `/MediaBox` or clipped `/CropBox` has no area and
/// falls back (the renderer's `is_nearly_zero`, 1/4096).
const MIN_BOX_SIDE: f64 = 1.0 / 4096.0;
fn rect(doc: &Document, o: Option<&Object>) -> Option<[f64; 4]> {
/// Normalized `[x0, y0, x1, y1]` of a page box when its first four entries form a finite, positive rectangle.
///
/// Origin and size are unscaled; overflowing widths are returned so [`Page::crop`] can clip them
/// to the media box.
fn box_coords(doc: &Document, o: Option<&Object>) -> Option<[f64; 4]> {
let o = doc.resolve(o?);
// Four entries, or not a rectangle: a longer array (one shared by many pages, say) is not
// resolved entry by entry only to be discarded.
let [a, b, c, d] = o.as_array()?.as_slice() else { return None };
let v = [a, b, c, d].map(|x| doc.resolve(x).as_f64());
let [Some(x0), Some(y0), Some(x1), Some(y1)] = v else { return None };
[x0, y0, x1, y1].iter().all(|x| x.is_finite()).then(|| [x0.min(x1), y0.min(y1), x0.max(x1), y0.max(y1)])
let [a, b, c, d, ..] = o.as_array()?.as_slice() else { return None };
let coords = [doc.resolve(a).as_f64()?, doc.resolve(b).as_f64()?, doc.resolve(c).as_f64()?, doc.resolve(d).as_f64()?];
if !coords.iter().all(|x| x.is_finite()) {
return None;
}
let r = [coords[0].min(coords[2]), coords[1].min(coords[3]), coords[0].max(coords[2]), coords[1].max(coords[3])];
let (w, h) = (r[2] - r[0], r[3] - r[1]);
(w > 0.0 && h > 0.0).then_some(r)
}
/// Like [`box_coords`], also rejecting boxes whose span overflows when scaled by [`MAX_USER_UNIT`].
fn rect(doc: &Document, o: Option<&Object>) -> Option<[f64; 4]> {
let r = box_coords(doc, o)?;
let (w, h) = (r[2] - r[0], r[3] - r[1]);
((w * MAX_USER_UNIT).is_finite() && (h * MAX_USER_UNIT).is_finite()).then_some(r)
}
impl Page {
@@ -40,10 +53,10 @@ impl Page {
let media = rect(doc, self.dict.get(b"MediaBox"))
.filter(|m| m[2] - m[0] > MIN_BOX_SIDE && m[3] - m[1] > MIN_BOX_SIDE)
.unwrap_or([0.0, 0.0, 612.0, 792.0]);
match rect(doc, self.dict.get(b"CropBox")) {
match box_coords(doc, self.dict.get(b"CropBox")) {
Some(c) => {
let r = [c[0].max(media[0]), c[1].max(media[1]), c[2].min(media[2]), c[3].min(media[3])];
if r[2] > r[0] && r[3] > r[1] { r } else { media }
if r[2] - r[0] > MIN_BOX_SIDE && r[3] - r[1] > MIN_BOX_SIDE { r } else { media }
}
None => media,
}
@@ -512,4 +525,61 @@ mod tests {
assert_eq!(pages(&d)[0].user_unit(&d), unit, "{pages_attrs} {page_attrs}");
}
}
#[test]
fn degenerate_or_malformed_boxes_fall_back() {
for bad_media in ["[0 0 0 792]", "[10 10 100 10]", "[10 10 10 10]", "[0 0 /Bad 400 500]"] {
let d = doc_with(0, &format!("/MediaBox {bad_media}"), "/CropBox null");
let p = &pages(&d)[0];
assert_eq!(p.crop(&d), [0.0, 0.0, 612.0, 792.0], "{bad_media}");
assert_eq!(p.display_size(&d), (612.0, 792.0), "{bad_media}");
}
// Rejected /CropBox falls back to /MediaBox ([0 0 600 800] from doc_with).
for bad_crop in ["[0 0 0 800]", "[0 0 /Bad 400 500]"] {
let d = doc_with(0, "", &format!("/CropBox {bad_crop}"));
assert_eq!(pages(&d)[0].crop(&d), [0.0, 0.0, 600.0, 800.0], "{bad_crop}");
}
// Reversed coordinates are normalized, and four valid leading coordinates with trailing
// entries match the renderer's crop bounds.
let reversed = doc_with(0, "", "/CropBox [300 400 10 20]");
assert_eq!(pages(&reversed)[0].crop(&reversed), [10.0, 20.0, 300.0, 400.0]);
let trailing = doc_with(0, "", "/CropBox [0 0 300 792 /Extra]");
assert_eq!(pages(&trailing)[0].crop(&trailing), [0.0, 0.0, 300.0, 792.0]);
// An overflowing /CropBox still intersects a normal /MediaBox; the visible region is that
// intersection, not the full media box (hidden-text cleanup uses this crop), unless the
// clipped intersection is a sliver at or below MIN_BOX_SIDE, matching the renderer.
let overflow = doc_with(0, "/MediaBox [0 0 600 800]", "/CropBox [-1e308 0 1e308 792]");
assert_eq!(pages(&overflow)[0].crop(&overflow), [0.0, 0.0, 600.0, 792.0]);
for sliver in ["/CropBox [-1e308 0 1e308 0.0001]", "/CropBox [-1e308 0 0.0001 800]"] {
let d = doc_with(0, "/MediaBox [0 0 600 800]", sliver);
assert_eq!(pages(&d)[0].crop(&d), [0.0, 0.0, 600.0, 800.0], "{sliver}");
}
let mut d = doc_with(0, "", "/CropBox null");
let leaf = ObjRef { num: 3, generation: 0 };
// Indirect box array and indirect coordinate numbers resolve cleanly.
let w_ref = d.add(Object::Int(250));
let h_ref = d.add(Object::Real(350.0));
let box_ref = d.add(Object::Array(vec![Object::Int(0), Object::Int(0), Object::Ref(w_ref), Object::Ref(h_ref)]));
d.update_dict(leaf, |dict| dict.set(b"CropBox".to_vec(), Object::Ref(box_ref))).unwrap();
assert_eq!(pages(&d)[0].crop(&d), [0.0, 0.0, 250.0, 350.0]);
d.update_dict(leaf, |dict| dict.set(b"CropBox".to_vec(), Object::Null)).unwrap();
for extreme in [
vec![Object::Real(-1e308), Object::Real(0.0), Object::Real(1e308), Object::Real(792.0)],
vec![Object::Real(0.0), Object::Real(0.0), Object::Real(1e308), Object::Real(792.0)],
vec![Object::Real(0.0), Object::Real(0.0), Object::Real(1e306), Object::Real(792.0)],
vec![Object::Real(0.0), Object::Real(0.0), Object::Real(f64::NAN), Object::Real(792.0)],
] {
d.update_dict(leaf, |dict| {
dict.set(b"MediaBox".to_vec(), Object::Array(extreme.clone()));
dict.set(b"UserUnit".to_vec(), Object::Real(1000.0));
})
.unwrap();
let p = &pages(&d)[0];
assert_eq!(p.crop(&d), [0.0, 0.0, 612.0, 792.0], "{extreme:?}");
let (w, h) = p.display_size(&d);
assert!(w.is_finite() && h.is_finite() && w > 0.0 && h > 0.0, "{extreme:?}: ({w}, {h})");
}
}
}
+8 -1
View File
@@ -141,7 +141,14 @@ or in a form under an area (a stray `)` or `}` in a `TJ` array, say): the interp
them, so text they hide, which other readers may draw, would be neither found nor removed. Remove
hidden information refuses a page for both too, in whatever content it walks. A Redact annotation with neither a usable `/QuadPoints` array nor a usable
`/Rect` makes it fail with `RedactError::UnreadableMark` before anything changes, instead of
skipping that mark. The count covers the marks on the pages being applied.
skipping that mark. The count covers the marks on the pages being applied. Where the walk or a
cleanup can't read what it must to show something gone (content or forms with bytes the parser
can't read, or past what one page may read or is followed, a form whose `/Matrix` isn't six
numbers, a Type 3 font without the entries its cleanup reads), the operation fails with
`RedactError::PageRefused`, naming the page whose content or forms are the cause, marked or not, or
with `RedactError::Refused` where no one page is (a Type 3 font, or forms shared across the
document). `remove_hidden` may have changed the document by then, as for its other refusals: a
caller passes a copy it can drop.
Tiling-pattern cells are separate streams. Applying a mark removes a pattern resource when no
surviving paint uses it. If a cell remains reachable after rewriting the selected pages and may
+62 -47
View File
@@ -158,7 +158,7 @@ pub(crate) struct Output {
/// rewrite would drop the bytes but keep the strings. A redaction must not trust it.
pub unparsed: bool,
pub tag_changes: Vec<(ObjRef, ObjRef, HashSet<i64>, HashSet<i64>)>,
pub error: Option<CosError>,
pub error: Option<RedactError>,
}
pub(crate) struct Scope<'a> {
@@ -1108,6 +1108,57 @@ fn show(scope: &mut Scope<'_>, gs: &Gs, tm: &mut Matrix, items: &[Object]) -> (V
(out, removed)
}
/// The content of form `s` (named `name`, object `r`) for [`xobject`], or what `xobject` returns
/// for a form it can't read: Apply refuses the page once the page's budget is spent and drops a
/// form that won't decode; the scans count a form past the budget, and the hidden-information
/// scans one that won't decode as well.
fn form_data(doc: &Document, scope: &mut Scope<'_>, s: &Stream, name: &[u8], r: ObjRef, out: &mut Output) -> Result<Vec<u8>, Option<Option<Op>>> {
// Strict, like page content: a Form read only in part counts as undecodable. With its
// `/DecodeParms` given by reference too, as the cleanups after the walk read it: read
// without them, it looks empty and is left as it was, drawing whatever lies under a mark.
let refused = scope.budget.refused();
let entered = scope.budget.enter_form();
let data = if entered {
scope.budget.decode_strict(doc, s)
} else {
Err(CosError::Filter(format!("the page draws more than {MAX_PAGE_FORMS} form XObjects")))
};
match data {
Ok(d) => Ok(d),
// Past the page's budget nothing more is read: apply refuses the page, and
// verification counts the form as content that may remain.
Err(e) if scope.budget.exhausted() => {
if scope.mode == Mode::Apply {
// The budget spent says nothing of this form: it went past what the page
// may read only where it was refused for that; one that doesn't decode
// says why.
let past = !entered || scope.budget.refused() > refused;
out.error = Some(if past { RedactError::past_allowance(e) } else { e.into() });
} else if scope.everywhere() {
scope.layer_blocks += 1;
} else {
out.residue += 1;
}
Err(None)
}
Err(_) if scope.mode == Mode::Apply => {
scope.report.forms_removed += 1;
scope.removed_cut = true;
out.replaced.push(name.to_vec());
out.doomed.push(r);
Err(Some(None))
}
Err(_) => {
// Apply drops an undecodable Form while sanitizing. Count it during Verify
// so a zero-count preflight cannot leave its potentially hidden bytes behind.
if scope.everywhere() {
scope.layer_blocks += 1;
}
Err(None)
}
}
}
/// `Do`: `None` = leave the operator alone; `Some(None)` = drop it; `Some(Some(op))` = replace it.
fn xobject(
doc: &mut Document,
@@ -1177,16 +1228,14 @@ fn xobject(
// the form is walked as it stands.
Err(()) if scope.everywhere() && scope.hidden_text.is_none() => Matrix::IDENTITY,
// Otherwise where the form draws, and so whether it reaches a mark or leaves the
// page, can't be told. Apply refuses the page, and the scans count it, as for a
// form past the page's budget below.
// page, can't be told. Apply refuses the page, and the scans count it, as
// `form_data` does for a form past the page's budget.
Err(()) => {
if scope.mode == Mode::Apply {
out.error = Some(CosError::Syntax {
offset: 0,
detail:
"a form XObject's /Matrix isn't six numbers given directly or through one reference, so where it draws can't be told"
.into(),
});
out.error = Some(RedactError::Refused(
"a form XObject's /Matrix isn't six numbers given directly or through one reference, so where it draws can't be told"
.into(),
));
} else if scope.everywhere() {
scope.layer_blocks += 1;
} else {
@@ -1207,8 +1256,8 @@ fn xobject(
return None;
}
// Too deep: this form cannot be read, so it goes (Apply) or the page is left alone
// (Verify), as a form that will not decode does. The page's decode budget below is what
// keeps a fan-out or a cycle from costing 2^50 walks.
// (Verify), as a form that will not decode does. The page's decode budget, which
// `form_data` reads within, is what keeps a fan-out or a cycle from costing 2^50 walks.
if scope.depth >= MAX_DEPTH {
if scope.mode == Mode::Verify {
// Sanitization removes a Form it cannot enter, so the verification scan
@@ -1225,43 +1274,9 @@ fn xobject(
out.doomed.push(r);
return Some(None);
}
// Strict, like page content: a Form read only in part counts as undecodable. With its
// `/DecodeParms` given by reference too, as the cleanups after the walk read it: read
// without them, it looks empty and is left as it was, drawing whatever lies under a mark.
let data = if scope.budget.enter_form() {
scope.budget.decode_strict(doc, s)
} else {
Err(CosError::Filter(format!("the page draws more than {MAX_PAGE_FORMS} form XObjects")))
};
let data = match data {
let data = match form_data(doc, scope, s, &name, r, out) {
Ok(d) => d,
// Past the page's budget nothing more is read: apply refuses the page, and
// verification counts the form as content that may remain.
Err(e) if scope.budget.exhausted() => {
if scope.mode == Mode::Apply {
out.error = Some(e);
} else if scope.everywhere() {
scope.layer_blocks += 1;
} else {
out.residue += 1;
}
return None;
}
Err(_) if scope.mode == Mode::Apply => {
scope.report.forms_removed += 1;
scope.removed_cut = true;
out.replaced.push(name);
out.doomed.push(r);
return Some(None);
}
Err(_) => {
// Apply drops an undecodable Form while sanitizing. Count it during Verify
// so a zero-count preflight cannot leave its potentially hidden bytes behind.
if scope.everywhere() {
scope.layer_blocks += 1;
}
return None;
}
Err(leave_or_drop) => return leave_or_drop,
};
let own = s.dict.get(b"Resources").and_then(|r| doc.resolve(r).as_dict().cloned());
let res = own.clone().unwrap_or_else(|| resources.clone());
+55 -20
View File
@@ -1,6 +1,6 @@
use super::{
CosError, DecodeBudget, Dict, Document, HashMap, HashSet, MAX_DEPTH, Matrix, Metrics, ObjRef, Object, Op, Pieces, Rc, RedactError, Scope,
is_vertical, num, overlaps, page_streams, res_dict,
DecodeBudget, Dict, Document, HashMap, HashSet, MAX_DEPTH, Matrix, Metrics, ObjRef, Object, Op, Pieces, Rc, RedactError, Scope, is_vertical, num,
overlaps, page_streams, res_dict,
};
/// Drop every `replaced` name of the XObject resources `xo` that the rewritten `content` no
@@ -13,7 +13,7 @@ use super::{
/// fonts' cleanup, an allowance of its own when no Type 3 font is listed), the walk passes
/// 2,000,000 operators, or the parser can't read all of such a form or of `content`.
/// Corrupt data in such a form is read, tolerantly, up to the damage, which may be nothing.
pub(crate) fn prune(doc: &Document, budget: &mut DecodeBudget, xo: &mut Dict, replaced: &[Vec<u8>], content: &[Vec<u8>]) -> Result<(), CosError> {
pub(crate) fn prune(doc: &Document, budget: &mut DecodeBudget, xo: &mut Dict, replaced: &[Vec<u8>], content: &[Vec<u8>]) -> Result<(), RedactError> {
if replaced.is_empty() {
return Ok(());
}
@@ -313,10 +313,14 @@ pub(crate) fn unlink_doomed(doc: &mut Document, doomed: &[ObjRef], retired_prope
continue;
}
let mut contents = Vec::with_capacity(users.len());
// Which page each content is, where the page tree lists it.
let mut numbers = Vec::with_capacity(users.len());
for user in &users {
let page = doc.get(*user).as_dict().cloned().unwrap_or_default();
let at = index.get(user).copied();
// A page whose content cannot be read may still draw the name: fail closed.
contents.push(page_streams(doc, &page, index.get(user).copied().unwrap_or(0))?.1);
contents.push(page_streams(doc, &page, at.unwrap_or(0))?.1);
numbers.push(at.map(|at| at + 1));
}
let mut pruned = false;
// What each page draws through this dictionary, worked out once for all the names.
@@ -329,13 +333,21 @@ pub(crate) fn unlink_doomed(doc: &mut Document, doomed: &[ObjRef], retired_prope
xo.remove(&n);
pruned = true;
}
None => return Err(RedactError::Residue(1)),
// A page sharing these resources draws through them forms that can't all be read.
None => {
let reason = "a form it draws through resources shared with what was removed can't all be read".to_string();
let page = drawn.iter().zip(&numbers).find(|((_, unknown), _)| *unknown).and_then(|(_, page)| *page);
return Err(match page {
Some(page) => RedactError::PageRefused { page, reason },
None => RedactError::Refused(reason),
});
}
}
}
if pruned {
res.set(b"XObject".to_vec(), Object::Dict(xo));
}
pruned |= prune_retired_properties(doc, &mut res, &property_names, &contents)?;
pruned |= prune_retired_properties(doc, &mut res, &property_names, &contents, &numbers)?;
if pruned {
doc.update_dict(node, |d| d.set(b"Resources".to_vec(), Object::Dict(res)))?;
}
@@ -349,14 +361,26 @@ pub(crate) fn unlink_doomed(doc: &mut Document, doomed: &[ObjRef], retired_prope
/// Retire only properties removed from a rewritten scope, preserving names still used by any
/// content sharing this holder. Different pages' streams must never be concatenated together.
fn prune_retired_properties(doc: &Document, res: &mut Dict, names: &[Vec<u8>], contents: &[Vec<Vec<u8>>]) -> Result<bool, CosError> {
/// `pages` are the (1-based) pages whose content `contents` are, in order, named when theirs
/// refuses; a form's content has none, nor a page the page tree doesn't list.
fn prune_retired_properties(
doc: &Document,
res: &mut Dict,
names: &[Vec<u8>],
contents: &[Vec<Vec<u8>>],
pages: &[Option<usize>],
) -> Result<bool, RedactError> {
if names.is_empty() {
return Ok(false);
}
let mut used = HashSet::new();
for content in contents {
for (i, content) in contents.iter().enumerate() {
// Each is one page's content or one form's, with the allowance of a page.
for op in resource_ops(doc, &mut DecodeBudget::page(), res, content)? {
let ops = resource_ops(doc, &mut DecodeBudget::page(), res, content).map_err(|e| match pages.get(i).copied().flatten() {
Some(page) => e.on_page(page),
None => e,
})?;
for op in ops {
if matches!(op.op.as_slice(), b"BDC" | b"DP")
&& let Some(name) = op.last_name()
{
@@ -384,7 +408,7 @@ fn prune_retired_properties(doc: &Document, res: &mut Dict, names: &[Vec<u8>], c
/// Unlink retired properties and `doomed` XObjects from the resources of the forms reachable from
/// the page-tree `holders`, each unless the form's own content (or a form inheriting its
/// resources) still uses the name. Fails closed when that cannot be determined.
fn unlink_from_forms(doc: &mut Document, holders: &[ObjRef], doomed: &HashSet<ObjRef>, retired: &[Object]) -> Result<(), CosError> {
fn unlink_from_forms(doc: &mut Document, holders: &[ObjRef], doomed: &HashSet<ObjRef>, retired: &[Object]) -> Result<(), RedactError> {
if retired.is_empty() && doomed.is_empty() {
return Ok(());
}
@@ -400,7 +424,7 @@ fn unlink_from_forms(doc: &mut Document, holders: &[ObjRef], doomed: &HashSet<Ob
continue;
}
if seen.len() > 1_000_000 {
return Err(CosError::Syntax { offset: 0, detail: "redaction could not fully inspect shared form resources".into() });
return Err(RedactError::Refused("the forms the document's resources draw are more than can be followed".into()));
}
let object = doc.get(reference);
let Object::Stream(form) = &*object else { continue };
@@ -422,7 +446,7 @@ fn unlink_from_forms(doc: &mut Document, holders: &[ObjRef], doomed: &HashSet<Ob
if pruned {
res.set(b"XObject".to_vec(), Object::Dict(xo));
}
pruned |= prune_retired_properties(doc, &mut res, &names, &[vec![data]])?;
pruned |= prune_retired_properties(doc, &mut res, &names, &[vec![data]], &[])?;
if pruned {
doc.update_dict(reference, |d| d.set(b"Resources".to_vec(), Object::Dict(res.clone())))?;
}
@@ -432,7 +456,7 @@ fn unlink_from_forms(doc: &mut Document, holders: &[ObjRef], doomed: &HashSet<Ob
Ok(())
}
fn prune_doomed_xobjects(doc: &Document, content: &[Vec<u8>], xo: &mut Dict, doomed_names: &[Vec<u8>]) -> Result<bool, CosError> {
fn prune_doomed_xobjects(doc: &Document, content: &[Vec<u8>], xo: &mut Dict, doomed_names: &[Vec<u8>]) -> Result<bool, RedactError> {
let mut pruned = false;
if doomed_names.is_empty() {
return Ok(false);
@@ -442,7 +466,9 @@ fn prune_doomed_xobjects(doc: &Document, content: &[Vec<u8>], xo: &mut Dict, doo
match any_draws(&drawn, name) {
Some(true) => {}
Some(false) => pruned |= xo.remove(name).is_some(),
None => return Err(CosError::Syntax { offset: 0, detail: "redaction could not fully inspect shared form resources".into() }),
None => {
return Err(RedactError::Refused("a form that may still draw what was removed draws forms that can't all be read".into()));
}
}
}
Ok(pruned)
@@ -479,14 +505,16 @@ pub(super) fn clip_out(rects: &[[f64; 4]], ctm: &Matrix, around: [f64; 4]) -> Op
/// when that can't all be read: the parser can't read all of `content` or of such a form, the walk
/// passes 2,000,000 operators, or such a form doesn't decode or runs past `budget`. Operators are
/// read one at a time, so the walk stops at one past the limit rather than holding them all.
pub(crate) fn resource_ops(doc: &Document, budget: &mut DecodeBudget, res: &Dict, content: &[Vec<u8>]) -> Result<Vec<Op>, CosError> {
pub(crate) fn resource_ops(doc: &Document, budget: &mut DecodeBudget, res: &Dict, content: &[Vec<u8>]) -> Result<Vec<Op>, RedactError> {
const MAX_OPS: usize = 2_000_000;
let joined = Pieces::join(content);
let mut read = pdfcraft_content::ops(joined.data());
let mut ops: Vec<Op> = read.by_ref().take(MAX_OPS + 1).collect();
// Under the limit the reader ran to the end, so `skipped` counts all of it.
if read.skipped() > 0 || ops.len() > MAX_OPS {
return Err(CosError::Syntax { offset: 0, detail: "redaction could not fully read the content that uses these resources".into() });
return Err(RedactError::Refused(
"content that draws with its resources has bytes that can't be read, or more than 2,000,000 operators".into(),
));
}
let xobjects = res_dict(doc, res, b"XObject");
let mut seen = HashSet::new();
@@ -500,12 +528,19 @@ pub(crate) fn resource_ops(doc: &Document, budget: &mut DecodeBudget, res: &Dict
&& s.dict.name(b"Subtype") == Some(b"Form")
&& s.dict.get(b"Resources").is_none_or(|r| doc.resolve(r).as_dict().is_none())
{
let data = budget.decode(&doc.with_direct_parms(s))?;
// Past what the page may read where the budget refused it; a form that doesn't decode
// says why.
let refused = budget.refused();
let data = budget
.decode(&doc.with_direct_parms(s))
.map_err(|e| if budget.refused() > refused { RedactError::past_allowance(e) } else { e.into() })?;
let mut read = pdfcraft_content::ops(&data);
ops.extend(read.by_ref().take((MAX_OPS + 1).saturating_sub(ops.len())));
// `seen` gains at most one form for each `Do` in `ops`, so this bounds it too.
if ops.len() > MAX_OPS || read.skipped() > 0 {
return Err(CosError::Syntax { offset: 0, detail: "redaction could not fully inspect inherited form resources".into() });
return Err(RedactError::Refused(
"a form without resources of its own has bytes that can't be read, or takes what draws with those resources past 2,000,000 operators".into(),
));
}
}
cursor += 1;
@@ -513,7 +548,7 @@ pub(crate) fn resource_ops(doc: &Document, budget: &mut DecodeBudget, res: &Dict
Ok(ops)
}
pub(crate) fn prune_properties(doc: &Document, budget: &mut DecodeBudget, res: &mut Dict, content: &[Vec<u8>]) -> Result<Vec<Object>, CosError> {
pub(crate) fn prune_properties(doc: &Document, budget: &mut DecodeBudget, res: &mut Dict, content: &[Vec<u8>]) -> Result<Vec<Object>, RedactError> {
let mut properties = res_dict(doc, res, b"Properties");
if properties.is_empty() {
return Ok(Vec::new());
@@ -536,7 +571,7 @@ pub(crate) fn prune_properties(doc: &Document, budget: &mut DecodeBudget, res: &
Ok(retired)
}
pub(super) fn prune_form_resources(doc: &Document, budget: &mut DecodeBudget, res: &mut Dict, content: &[Vec<u8>]) -> Result<(), CosError> {
pub(super) fn prune_form_resources(doc: &Document, budget: &mut DecodeBudget, res: &mut Dict, content: &[Vec<u8>]) -> Result<(), RedactError> {
let ops = resource_ops(doc, budget, res, content)?;
let mut xo = res_dict(doc, res, b"XObject");
let names: Vec<Vec<u8>> = xo.iter().map(|(n, _)| n.to_vec()).collect();
+47 -2
View File
@@ -131,6 +131,17 @@ pub enum RedactError {
"finding and storing again what shares JBIG2 symbol data with something being removed would read more of this file than one run allows, so it can't be shown that the data leaves with it; this was refused"
)]
SharedJbig2Budget,
/// What cleaning a page needs to read whole, or to find, isn't there to read: content with
/// bytes the parser can't read, or past what one page may read or is followed, forms nesting
/// past what is followed, a form whose placement can't be told. What it holds can't be shown
/// gone.
#[error("page {page} can't be redacted safely: {reason}; the operation was refused")]
PageRefused { page: usize, reason: String },
/// [`RedactError::PageRefused`] where no one page is the cause: a Type 3 font's own entries,
/// glyphs or forms, forms and resources shared across the document, or a page the page tree
/// doesn't list.
#[error("the document can't be redacted safely: {0}; the operation was refused")]
Refused(String),
#[error(transparent)]
Edit(#[from] pdfcraft_edit::EditError),
#[error(transparent)]
@@ -139,6 +150,40 @@ pub enum RedactError {
Cos(#[from] pdfcraft_cos::CosError),
}
/// What a `DecodeBudget` said when it refused: a filter's message as it stands, another error as
/// it displays.
fn budget_detail(error: pdfcraft_cos::CosError) -> String {
match error {
pdfcraft_cos::CosError::Filter(detail) => detail,
other => other.to_string(),
}
}
impl RedactError {
/// The refusal of content and forms that go past what one page may read, from what the page's
/// `DecodeBudget` said.
pub(crate) fn past_allowance(error: pdfcraft_cos::CosError) -> Self {
RedactError::Refused(format!("content and forms go past what one page may read ({})", budget_detail(error)))
}
/// The refusal of the glyph programs the document's Type 3 fonts keep, which the cleanup
/// reads under one allowance the size of a page's, when together they go past it.
pub(crate) fn past_glyph_allowance(error: pdfcraft_cos::CosError) -> Self {
RedactError::Refused(format!(
"the glyph programs the document's Type 3 fonts keep go, together, past what one page may read ({})",
budget_detail(error)
))
}
/// This error as met while cleaning page `page` (1-based): a refusal names the page.
pub(crate) fn on_page(self, page: usize) -> Self {
match self {
RedactError::Refused(reason) => RedactError::PageRefused { page, reason },
other => other,
}
}
}
/// [`RedactError::SharedJbig2Globals`]'s text, which says what keeps the data.
fn shared_jbig2_text(stuck: usize) -> String {
let why = match stuck {
@@ -624,7 +669,7 @@ fn apply_within(doc: &mut Document, pages: Option<&[usize]>, images: pdfcraft_co
for &(pi, page_marks) in &groups {
let page = pdfcraft_model::pages(doc).swap_remove(pi);
let rects: Vec<[f64; 4]> = page_marks.iter().flat_map(|m| m.rects.iter().copied()).collect();
redact_page_content(doc, &mut applying, pi, &page, &rects)?;
redact_page_content(doc, &mut applying, pi, &page, &rects).map_err(|e| e.on_page(pi + 1))?;
remove_page_annotations(doc, &mut applying, pi, &page, &rects, page_marks)?;
}
if applying.images.refused() > 0 {
@@ -904,7 +949,7 @@ fn redact_page_content(
// document). The error does not claim the text was under the mark. Full vertical-text
// removal is a future enhancement.
if let Some(error) = out.error {
return Err(error.into());
return Err(error);
}
if out.vertical {
return Err(RedactError::VerticalText(pi + 1));
+4 -4
View File
@@ -658,7 +658,7 @@ fn content_pass(doc: &mut Document, text: bool, layers: bool, write: bool) -> Re
scope.layers_enabled = layers;
let out = process(doc, &mut scope, &data, &resources, Matrix::IDENTITY);
if let Some(error) = out.error {
return Err(error.into());
return Err(error.on_page(pi + 1));
}
// Bytes the parser can't read, or an inline image whose end is a guess: the walk reads past
// them, so what it reads around them may not be what other readers draw (hidden text in a
@@ -714,11 +714,11 @@ fn content_pass(doc: &mut Document, text: bool, layers: bool, write: bool) -> Re
}
// A full save keeps whatever is still referenced: unlink the originals this page no
// longer draws so the removed form or image bytes cannot survive in the saved file.
crate::interp::prune(doc, &mut budget, &mut xo, &out.replaced, &page_content)?;
crate::interp::prune(doc, &mut budget, &mut xo, &out.replaced, &page_content).map_err(|e| e.on_page(pi + 1))?;
res.set(b"XObject".to_vec(), Object::Dict(xo));
}
retired_properties.extend(crate::interp::prune_properties(doc, &mut budget, &mut res, &page_content)?);
crate::type3::prune_type3_from_resources(doc, &mut budget, &mut res, &page_content, Some(&page.dict))?;
retired_properties.extend(crate::interp::prune_properties(doc, &mut budget, &mut res, &page_content).map_err(|e| e.on_page(pi + 1))?);
crate::type3::prune_type3_from_resources(doc, &mut budget, &mut res, &page_content, Some(&page.dict)).map_err(|e| e.on_page(pi + 1))?;
doc.update_dict(page.obj, |d| {
d.set(b"Contents".to_vec(), Object::Array(new_list));
d.set(b"Resources".to_vec(), Object::Dict(res));
+2 -1
View File
@@ -3475,7 +3475,7 @@ fn unreadable_bytes_in_a_stream_left_as_it_was_refuse_the_redaction_of_an_image(
mark(&mut doc, 0, &[[0.0, 200.0, 300.0, 300.0]], "");
let result = apply(&mut doc, None);
assert!(
matches!(&result, Err(RedactError::Cos(pdfcraft_cos::CosError::Syntax { detail, .. })) if detail == "redaction could not fully inspect inherited form resources"),
matches!(&result, Err(RedactError::PageRefused { page: 1, reason }) if reason.starts_with("a form without resources of its own has bytes")),
"{result:?}"
);
}
@@ -6406,6 +6406,7 @@ mod metadata_fail_closed;
mod metadata_matching;
mod operands_from_the_end;
mod property_retirement;
mod refusal_pages;
mod surviving_references;
mod text_state;
mod unparsed;
+38 -3
View File
@@ -65,13 +65,48 @@ fn a_form_whose_matrix_is_not_six_numbers_is_refused() {
mark(&mut doc, 0, &[MARK], "");
let result = apply(&mut doc, None);
assert!(
matches!(&result, Err(RedactError::Cos(pdfcraft_cos::CosError::Syntax { detail, .. })) if detail.contains("/Matrix")),
matches!(&result, Err(RedactError::PageRefused { page: 1, reason }) if reason.contains("/Matrix")),
"{matrix} with 8 0 obj {}: {result:?}",
String::from_utf8_lossy(extra)
);
}
}
/// The refusal names the page whose form can't be placed, and says the operation was refused: here the
/// second, which shares the first's resources and draws the form the first doesn't, for Apply
/// Redactions and for Remove Hidden Information.
#[test]
fn a_refusal_names_the_page_whose_form_can_t_be_placed() {
use crate::sanitize::{Hidden, remove_hidden};
let two_pages = || {
pdf(vec![
b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(),
b"<< /Type /Pages /Kids [3 0 R 9 0 R] /Count 2 >>".to_vec(),
b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Contents 4 0 R /Resources 10 0 R >>".to_vec(),
stream("", b"BT /F1 10 Tf 20 260 Td (PLAIN) Tj ET"),
FONT.replace("95 0 R", "6 0 R").into_bytes(),
widths(),
stream(
"/Type /XObject /Subtype /Form /BBox [0 0 300 100] /Matrix [1 0 0 1 0 (up)] /Resources << /Font << /F1 5 0 R >> >>",
b"BT /F1 10 Tf 20 60 Td (SECRET) Tj ET",
),
b"null".to_vec(),
b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Contents 11 0 R /Resources 10 0 R >>".to_vec(),
b"<< /Font << /F1 5 0 R >> /XObject << /Fm 7 0 R >> >>".to_vec(),
stream("", b"/Fm Do"),
])
};
let said = "page 2 can't be redacted safely: a form XObject's /Matrix isn't six numbers given directly or through one reference, so where it draws can't be told; the operation was refused";
let mut doc = two_pages();
mark(&mut doc, 1, &[MARK], "");
let applied = apply(&mut doc, None);
assert!(matches!(&applied, Err(RedactError::PageRefused { page: 2, .. })), "{applied:?}");
assert_eq!(applied.map(|_| ()).unwrap_err().to_string(), said);
let removed = remove_hidden(&mut two_pages(), &[Hidden::HiddenText]);
assert!(matches!(&removed, Err(RedactError::PageRefused { page: 2, .. })), "{removed:?}");
assert_eq!(removed.map(|_| ()).unwrap_err().to_string(), said);
}
/// A reference to a reference, for the matrix or one of its entries: Poppler doesn't follow it (it
/// reads such a matrix as the identity, such an entry as 0), the app's renderer follows it and
/// reads the move, so where the form draws can't be told, and the page is refused, as for a matrix that isn't six numbers. Read as either,
@@ -88,7 +123,7 @@ fn a_form_whose_matrix_goes_through_a_reference_to_a_reference_is_refused() {
mark(&mut doc, 0, &[mark_at], "");
let result = apply(&mut doc, None);
assert!(
matches!(&result, Err(RedactError::Cos(pdfcraft_cos::CosError::Syntax { detail, .. })) if detail.contains("/Matrix")),
matches!(&result, Err(RedactError::PageRefused { page: 1, reason }) if reason.contains("/Matrix")),
"{matrix}, 8 0 obj 9 0 R, 9 0 obj {}, mark at {mark_at:?}: {result:?}",
String::from_utf8_lossy(target)
);
@@ -106,7 +141,7 @@ fn a_form_whose_matrix_is_not_six_numbers_counts_in_the_scans() {
let counts: std::collections::HashMap<Hidden, usize> = scan(&doc).into_iter().collect();
assert_eq!(counts[&Hidden::HiddenText], 1);
let removed = remove_hidden(&mut doc, &[Hidden::HiddenText]);
assert!(matches!(&removed, Err(RedactError::Cos(pdfcraft_cos::CosError::Syntax { detail, .. })) if detail.contains("/Matrix")), "{removed:?}");
assert!(matches!(&removed, Err(RedactError::PageRefused { page: 1, reason }) if reason.contains("/Matrix")), "{removed:?}");
}
/// Removing hidden layers alone never asks where content lands, so such a form is walked as it
@@ -156,7 +156,15 @@ fn uninspectable_forms_with_candidate_properties_fail_closed() {
add_second_page(&mut doc, b"/Fm Do", Object::Ref(shared));
assert_eq!(under(&mut doc, 0, &[[5.0, 195.0, 60.0, 212.0]]), 6);
let error = redact_first(&mut doc).unwrap_err();
assert!(matches!(error, RedactError::Cos(_)), "own Resources={own}, malformed={malformed}: {error:?}");
// A form that doesn't decode says so; one the parser can't read is a refusal, of the
// second page when it draws the form through the page's resources, and of the document
// when the form is read for its own.
let expected = match (own, malformed) {
(_, false) => matches!(error, RedactError::Cos(pdfcraft_cos::CosError::Filter(_))),
(false, true) => matches!(&error, RedactError::PageRefused { page: 2, reason } if reason.contains("without resources of its own")),
(true, true) => matches!(&error, RedactError::Refused(reason) if reason.contains("draws with its resources")),
};
assert!(expected, "own Resources={own}, malformed={malformed}: {error:?}");
}
}
}
+147
View File
@@ -0,0 +1,147 @@
//! Redaction refusals name the page whose content or forms are their cause
//! (`RedactError::PageRefused`), in Apply Redactions and Remove Hidden Information, and errors
//! that aren't refusals keep their own text.
use super::*;
use crate::sanitize::{Hidden, remove_hidden};
/// Two pages: the first plain, the second showing hidden text (`3 Tr`) and then `content`, with
/// `res` as its resources; objects from 9 on are `extra`.
fn second_page_hidden(content: &[u8], res: &str, extra: Vec<Vec<u8>>) -> Document {
let mut objs = vec![
b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(),
b"<< /Type /Pages /Kids [3 0 R 7 0 R] /Count 2 >>".to_vec(),
b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >>".to_vec(),
stream("", b"BT /F1 10 Tf 20 260 Td (PLAIN) Tj ET"),
FONT.replace("95 0 R", "6 0 R").into_bytes(),
widths(),
format!("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Contents 8 0 R /Resources << {res} >> >>").into_bytes(),
stream("", [b"BT /F1 10 Tf 3 Tr 20 60 Td (HIDDEN) Tj ET ".as_slice(), content].concat()),
];
objs.extend(extra);
pdf(objs)
}
/// Asserts that removing hidden text from `doc` is refused, naming page 2, for a reason that holds
/// `reason`.
fn refuses_page_two(mut doc: Document, reason: &str) {
let removed = remove_hidden(&mut doc, &[Hidden::HiddenText]);
assert!(matches!(&removed, Err(RedactError::PageRefused { page: 2, reason: r }) if r.contains(reason)), "{removed:?}");
}
/// Past 2,000,000 operators, what the second page's resources still draw can't be told: the
/// refusal of the properties' cleanup names that page.
#[test]
fn the_properties_cleanup_names_the_page_it_refuses() {
let many = b"n ".repeat(2_000_001);
refuses_page_two(second_page_hidden(&many, "/Font << /F1 5 0 R >> /Properties << /P0 << >> >>", vec![]), "more than 2,000,000 operators");
}
/// The same for the cleanup of the forms the page replaced, which reads the page first.
#[test]
fn the_replaced_forms_cleanup_names_the_page_it_refuses() {
let many = [b"/Fm Do ".as_slice(), &b"n ".repeat(2_000_001)].concat();
let form = stream(
"/Type /XObject /Subtype /Form /BBox [0 0 300 300] /Resources << /Font << /F1 5 0 R >> >>",
b"BT /F1 10 Tf 3 Tr 20 100 Td (FORMHIDDEN) Tj ET",
);
refuses_page_two(second_page_hidden(&many, "/Font << /F1 5 0 R >> /XObject << /Fm 9 0 R >>", vec![form]), "more than 2,000,000 operators");
}
/// With a Type 3 font listed, the fonts' cleanup reads the soft masks without resources of their
/// own that the page sets, which the walk doesn't enter: one with bytes the parser can't read is
/// refused, naming the page.
#[test]
fn the_type3_cleanup_names_the_page_it_refuses() {
let group = stream("/Type /XObject /Subtype /Form /BBox [0 0 300 300] /Group << /S /Transparency >>", b"BT ( ET");
let font = b"<< /Type /Font /Subtype /Type3 /FontBBox [0 0 1000 1000] /FontMatrix [0.001 0 0 0.001 0 0] /FirstChar 65 /LastChar 65 /Widths [500] /Encoding << /Differences [65 /A] >> /CharProcs << >> >>".to_vec();
let res = "/Font << /F1 5 0 R /T3 10 0 R >> /ExtGState << /GS1 << /SMask << /S /Luminosity /G 9 0 R >> >> >>";
refuses_page_two(second_page_hidden(b"/GS1 gs", res, vec![group, font]), "a soft mask or form without resources of its own has bytes");
}
/// A page whose forms go past what one page may read is refused, named, by Apply Redactions and by
/// Remove Hidden Information: here it draws a form more often than the page may enter forms.
#[test]
fn a_page_past_what_it_may_read_is_named() {
let many = [b"BT /F1 10 Tf 20 260 Td (SECRET) Tj ET ".as_slice(), &b"/Fm Do ".repeat(pdfcraft_cos::MAX_PAGE_FORMS + 1)].concat();
let page = || one_page(&many, "/XObject << /Fm 7 0 R >>", vec![stream("/Type /XObject /Subtype /Form /BBox [0 0 300 300]", b"0 0 m")]);
let past = |error: &RedactError| {
matches!(error, RedactError::PageRefused { page: 1, reason }
if reason == &format!("content and forms go past what one page may read (the page draws more than {} form XObjects)", pdfcraft_cos::MAX_PAGE_FORMS))
};
let mut doc = page();
mark(&mut doc, 0, &[[0.0, 250.0, 300.0, 280.0]], "");
let applied = apply(&mut doc, None).map(|_| ());
assert!(applied.as_ref().is_err_and(past), "{applied:?}");
let removed = remove_hidden(&mut page(), &[Hidden::HiddenText]).map(|_| ());
assert!(removed.as_ref().is_err_and(past), "{removed:?}");
}
/// Pages sharing a resource dictionary with an image a mark removed: the second draws, through
/// the shared resources, a form that doesn't decode, so whether it still draws the image can't be
/// told. The refusal names the second page, and doesn't say anything was found under the mark.
#[test]
fn a_page_sharing_resources_whose_forms_can_t_be_read_is_named() {
let mut doc = pdf(vec![
b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(),
b"<< /Type /Pages /Kids [3 0 R 9 0 R] /Count 2 >>".to_vec(),
b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Contents 4 0 R /Resources 11 0 R >>".to_vec(),
stream("", b"q 50 0 0 50 20 230 cm /Im1 Do Q"),
b"null".to_vec(),
b"null".to_vec(),
stream("/Type /XObject /Subtype /Image /Width 16 /Height 1 /ColorSpace /DeviceGray /BitsPerComponent 8", b"REDIMGONECOVERED"),
stream("/Type /XObject /Subtype /Form /BBox [0 0 300 300] /Filter /UnsupportedForTheTest", b"opaque"),
b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Contents 10 0 R /Resources 11 0 R >>".to_vec(),
stream("", b"/FmBad Do"),
b"<< /XObject << /Im1 7 0 R /FmBad 8 0 R >> >>".to_vec(),
]);
mark(&mut doc, 0, &[[0.0, 200.0, 300.0, 300.0]], "");
let applied = apply(&mut doc, None).map(|_| ());
assert!(matches!(&applied, Err(RedactError::PageRefused { page: 2, reason }) if reason.contains("can't all be read")), "{applied:?}");
}
/// A page whose forms spend exactly what it may enter, nothing refused, and a form that doesn't
/// decode: that form says why, and the page isn't said to go past what it may read. In the walk, as
/// the page's last entry, where with room left the walk would remove it, it still refuses the
/// page, as before, now with its own text; in the cleanup of the page's properties, outside the
/// mark, which the walk doesn't enter, for Apply Redactions; and in the Type 3 cleanup's read of an
/// annotation appearance, for Apply Redactions and Remove Hidden Information.
#[test]
fn a_form_that_doesn_t_decode_at_the_page_s_last_entry_says_why() {
const MAX: usize = pdfcraft_cos::MAX_PAGE_FORMS;
const SECRET: &[u8] = b"BT /F1 10 Tf 20 260 Td (SECRET) Tj ET ";
const BAD: &str = "/Type /XObject /Subtype /Form /BBox [0 0 300 300] /Filter /UnsupportedForTheTest";
let says_why = |result: Result<(), RedactError>| {
assert!(matches!(&result, Err(RedactError::Cos(pdfcraft_cos::CosError::Filter(why))) if why.contains("UnsupportedForTheTest")), "{result:?}");
};
let form = || stream("/Type /XObject /Subtype /Form /BBox [0 0 300 300]", b"0 0 m");
let marked = |mut doc: Document| {
mark(&mut doc, 0, &[[0.0, 250.0, 300.0, 280.0]], "");
apply(&mut doc, None).map(|_| ())
};
// The walk: the form that doesn't decode is the page's last entry.
let content = [SECRET, &b"/Fm Do ".repeat(MAX - 1), b"/Fc Do"].concat();
says_why(marked(one_page(&content, "/XObject << /Fm 7 0 R /Fc 8 0 R >>", vec![form(), stream(BAD, b"opaque")])));
// The properties' cleanup, after the walk entered every form the page may.
let content = [SECRET, &b"/Fm Do ".repeat(MAX), b"/Fbad Do"].concat();
let resources = "/XObject << /Fm 7 0 R /Fbad 8 0 R >> /Properties << /P0 << >> >>";
says_why(marked(one_page(&content, resources, vec![form(), stream(&BAD.replace("300 300", "10 10"), b"opaque")])));
// The Type 3 cleanup's appearances.
let with_type3 = |content: Vec<u8>| {
pdf(vec![
b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(),
b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(),
b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Contents 4 0 R /Resources << /Font << /F1 5 0 R /T3 9 0 R >> /XObject << /Fm 7 0 R >> >> /Annots [10 0 R] >>".to_vec(),
stream("", &content),
FONT.replace("95 0 R", "6 0 R").into_bytes(),
widths(),
form(),
stream(BAD, b"opaque"),
b"<< /Type /Font /Subtype /Type3 /FontBBox [0 0 1000 1000] /FontMatrix [0.001 0 0 0.001 0 0] /FirstChar 65 /LastChar 65 /Widths [500] /Encoding << /Differences [65 /A] >> /CharProcs << >> >>".to_vec(),
b"<< /Type /Annot /Subtype /Square /Rect [0 0 10 10] /AP << /N 8 0 R >> >>".to_vec(),
])
};
says_why(marked(with_type3([SECRET, &b"/Fm Do ".repeat(MAX)].concat())));
let hidden = [b"BT /F1 10 Tf 3 Tr 20 60 Td (HIDDEN) Tj ET ".as_slice(), &b"/Fm Do ".repeat(MAX)].concat();
says_why(remove_hidden(&mut with_type3(hidden), &[Hidden::HiddenText]).map(|_| ()));
}
@@ -245,13 +245,63 @@ fn the_form_a_kept_type3_glyph_draws_is_walked_within_the_allowance_of_a_page()
mark(&mut doc, 0, &[[9.0, 95.0, 14.9, 110.0]], "");
let out = apply(&mut doc, None);
if refused {
assert!(matches!(out, Err(RedactError::Cos(pdfcraft_cos::CosError::Filter(_)))), "forms of {size} bytes each: {out:?}");
// The font's forms are cleaned for the document, not for one page.
assert!(
matches!(&out, Err(RedactError::Refused(reason)) if reason.starts_with("content and forms go past what one page may read")),
"forms of {size} bytes each: {out:?}"
);
} else {
assert_eq!(out.unwrap().glyphs, 1, "forms of {size} bytes each");
}
}
}
/// The kept glyph programs a Type 3 cleanup reads share one page's allowance: two compressed ones,
/// each past half of it, refuse the redaction for the document, as the font's forms do, with a
/// reason that names them. One that doesn't decode keeps its own error, and two small ones are
/// the control.
#[test]
fn kept_type3_glyph_programs_past_the_allowance_of_a_page_refuse_the_document() {
enum Then {
PastTheAllowance,
DoesNotDecode,
Cleaned,
}
for (size, filter, then) in [
(pdfcraft_cos::MAX_PAGE_DECODED / 2 + 1, "/FlateDecode", Then::PastTheAllowance),
(1, "/UnsupportedForTheTest", Then::DoesNotDecode),
(1, "/FlateDecode", Then::Cleaned),
] {
let packed = pdfcraft_filters::encode_flate(&vec![b' '; size]);
let glyph = || stream(&format!("/Filter {filter}"), packed.as_slice());
let mut doc = pdf(vec![
b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(),
b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(),
b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Contents 4 0 R /Resources 5 0 R >>".to_vec(),
stream("", b"BT /T3 10 Tf 10 100 Td (ABC) Tj ET"),
b"<< /Font << /T3 6 0 R >> >>".to_vec(),
b"<< /Type /Font /Subtype /Type3 /FontBBox [0 -200 1000 800] /FontMatrix [0.001 0 0 0.001 0 0] /FirstChar 65 /LastChar 67 /Widths [500 500 500] /Encoding << /Differences [65 /A /B /C] >> /CharProcs << /A 7 0 R /B 8 0 R /C 9 0 R >> /Resources << /XObject << /ImA 10 0 R >> >> >>".to_vec(),
stream("", b"/ImA Do"),
glyph(),
glyph(),
stream("/Type /XObject /Subtype /Image /Width 1 /Height 1 /ColorSpace /DeviceGray /BitsPerComponent 8", b"CONFIDENTIAL_IMAGE_A"),
]);
mark(&mut doc, 0, &[[9.0, 95.0, 14.9, 110.0]], "");
let out = apply(&mut doc, None);
match then {
Then::PastTheAllowance => assert!(
matches!(&out, Err(RedactError::Refused(reason)) if reason.starts_with("the glyph programs the document's Type 3 fonts keep go, together, past what one page may read")),
"glyph programs of {size} bytes each: {out:?}"
),
Then::DoesNotDecode => assert!(
matches!(&out, Err(RedactError::Cos(pdfcraft_cos::CosError::Filter(why))) if why.contains("UnsupportedForTheTest")),
"glyph programs that don't decode: {out:?}"
),
Then::Cleaned => assert_eq!(out.unwrap().glyphs, 1, "glyph programs of {size} bytes each"),
}
}
}
/// When all glyphs of a Type 3 font are redacted, the entire font is removed from Resources (F-011).
#[test]
fn all_redacted_type3_glyphs_cause_font_removal_from_resources() {
@@ -503,9 +553,14 @@ fn an_image_a_type3_glyph_with_parameters_by_reference_draws_is_kept() {
assert!(full_save_holds(&doc, b"PUBLIC_IMG_B"), "glyph B still draws its image");
}
/// Whether `out` is the redaction refused with a syntax error whose detail holds `detail`.
fn refused_for(out: &Result<Report, RedactError>, detail: &str) -> bool {
matches!(out, Err(RedactError::Cos(pdfcraft_cos::CosError::Syntax { detail: d, .. })) if d.contains(detail))
/// Whether `out` is the redaction refused, of `page` (1-based) or, with `None`, of the document, for
/// a reason that holds `reason`.
fn refused_for(out: &Result<Report, RedactError>, page: Option<usize>, reason: &str) -> bool {
match out {
Err(RedactError::PageRefused { page: p, reason: r }) => page == Some(*p) && r.contains(reason),
Err(RedactError::Refused(r)) => page.is_none() && r.contains(reason),
_ => false,
}
}
/// The font's cleanup scans every page and form for the glyphs they show. A string left open in a
@@ -527,7 +582,7 @@ fn unreadable_bytes_in_a_form_the_type3_cleanup_scans_refuse_the_redaction() {
]);
mark(&mut doc, 0, &[[9.0, 95.0, 16.0, 110.0]], "");
let out = apply(&mut doc, None);
assert!(refused_for(&out, "content stream syntax"), "{out:?}");
assert!(refused_for(&out, Some(1), "content that may show a Type 3 font has bytes that can't be read"), "{out:?}");
}
/// The font's cleanup reads the program of each glyph it keeps, for the resources it uses. A
@@ -549,7 +604,32 @@ fn unreadable_bytes_in_a_kept_type3_glyph_program_refuse_the_redaction() {
]);
mark(&mut doc, 0, &[[9.0, 95.0, 16.0, 110.0]], "");
let out = apply(&mut doc, None);
assert!(refused_for(&out, "glyph stream syntax"), "{out:?}");
assert!(refused_for(&out, None, "a Type 3 font's glyph has bytes that can't be read"), "{out:?}");
assert_eq!(
out.map(|_| ()).unwrap_err().to_string(),
"the document can't be redacted safely: a Type 3 font's glyph has bytes that can't be read; the operation was refused"
);
}
/// The font's cleanup scans every page, marked or not: where a page's content can't be read, the
/// refusal names that page, here the second, which no mark is on.
#[test]
fn unreadable_bytes_on_another_page_the_type3_cleanup_scans_refuse_that_page() {
let mut doc = pdf(vec![
b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(),
b"<< /Type /Pages /Kids [3 0 R 9 0 R] /Count 2 >>".to_vec(),
b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Contents 4 0 R /Resources 5 0 R >>".to_vec(),
stream("", b"BT /T3 10 Tf 10 100 Td (A) Tj ET"),
b"<< /Font << /T3 6 0 R >> >>".to_vec(),
TYPE3.as_bytes().to_vec(),
stream("", b"% SECRET_TYPE3_GLYPH_A"),
stream("", b"% PUBLIC_TYPE3_GLYPH_B"),
b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Contents 10 0 R /Resources 5 0 R >>".to_vec(),
stream("", b"BT /T3 10 Tf 10 20 Td ( (B) Tj ET"),
]);
mark(&mut doc, 0, &[[9.0, 95.0, 16.0, 110.0]], "");
let out = apply(&mut doc, None);
assert!(refused_for(&out, Some(2), "content that may show a Type 3 font has bytes that can't be read"), "{out:?}");
}
/// A Form the surviving glyph draws holds `/Resources` as an array that references the removed
@@ -739,7 +819,10 @@ fn a_page_s_appearances_share_one_decoded_byte_allowance() {
]);
mark(&mut doc, 0, &[[9.0, 95.0, 14.9, 110.0]], "");
let refused = apply(&mut doc, None);
assert!(refused.is_err(), "two appearances past the page's decoded-byte allowance together were read in full: {refused:?}");
assert!(
matches!(&refused, Err(RedactError::PageRefused { page: 1, reason }) if reason.starts_with("content and forms go past what one page may read")),
"two appearances past the page's decoded-byte allowance together were read in full: {refused:?}"
);
}
/// The appearances are read within what the page's content left of the page's allowance, not
+55 -57
View File
@@ -3,7 +3,7 @@
use std::collections::{HashMap, HashSet};
use pdfcraft_content::Pieces;
use pdfcraft_cos::{CosError, DecodeBudget, Dict, Document, ObjRef, Object};
use pdfcraft_cos::{DecodeBudget, Dict, Document, ObjRef, Object};
use crate::{RedactError, page_streams};
@@ -24,9 +24,9 @@ pub(crate) enum FontKey {
/// Build the mapping from character code (0..=255) to glyph name in a Type 3 font.
/// Fails closed if the encoding cannot be safely resolved or parsed.
pub(crate) fn type3_code_to_glyph(doc: &Document, font_dict: &Dict) -> Result<[Option<Vec<u8>>; 256], CosError> {
pub(crate) fn type3_code_to_glyph(doc: &Document, font_dict: &Dict) -> Result<[Option<Vec<u8>>; 256], RedactError> {
let Some(enc_obj) = font_dict.get(b"Encoding") else {
return Err(CosError::Syntax { offset: 0, detail: "redaction could not establish safe Type 3 font cleanup: missing Encoding".into() });
return Err(RedactError::Refused("a Type 3 font has no /Encoding".into()));
};
let resolved_enc = doc.resolve(enc_obj);
@@ -61,10 +61,7 @@ pub(crate) fn type3_code_to_glyph(doc: &Document, font_dict: &Dict) -> Result<[O
base_name = Some(name.clone());
}
_ => {
return Err(CosError::Syntax {
offset: 0,
detail: "redaction could not establish safe Type 3 font cleanup: invalid Encoding object".into(),
});
return Err(RedactError::Refused("a Type 3 font's /Encoding is neither a name nor a dictionary".into()));
}
}
@@ -74,13 +71,10 @@ pub(crate) fn type3_code_to_glyph(doc: &Document, font_dict: &Dict) -> Result<[O
Some(b"MacRomanEncoding") => Some(&crate::type3_tables::MAC_ROMAN),
Some(b"MacExpertEncoding") => Some(&crate::type3_tables::MAC_EXPERT),
Some(other) => {
return Err(CosError::Syntax {
offset: 0,
detail: format!(
"redaction could not establish safe Type 3 font cleanup: unsupported BaseEncoding: {}",
String::from_utf8_lossy(other)
),
});
return Err(RedactError::Refused(format!(
"a Type 3 font's base encoding /{} isn't one whose glyph names are known",
String::from_utf8_lossy(other)
)));
}
None => None,
};
@@ -149,13 +143,13 @@ struct GlyphReads {
budget: DecodeBudget,
}
fn collect_used_resources_in_stream(data: &[u8], used: &mut UsedInGlyphs) -> Result<(), CosError> {
fn collect_used_resources_in_stream(data: &[u8], used: &mut UsedInGlyphs) -> Result<(), RedactError> {
// One operator at a time, so a glyph program of millions of them is never held whole. A byte
// that can't be read anywhere in it still refuses, once the loop has read it all.
let mut read = pdfcraft_content::ops(data);
read.by_ref().for_each(|op| record_used(&op, used));
if read.skipped() > 0 {
return Err(CosError::Syntax { offset: 0, detail: "redaction could not fully inspect glyph stream syntax".into() });
return Err(RedactError::Refused("a Type 3 font's glyph has bytes that can't be read".into()));
}
Ok(())
}
@@ -209,7 +203,7 @@ fn record_used(op: &pdfcraft_content::Op, used: &mut UsedInGlyphs) {
/// surviving glyph draws may name, unused, an image only a removed glyph drew; that entry would
/// keep the image in the file. Pruning only unused entries is safe for a shared Form: no drawer
/// of it can use a name its content doesn't. Fails closed when a Form can't be read.
fn prune_font_forms(doc: &mut Document, font_res: &Dict) -> Result<(), CosError> {
fn prune_font_forms(doc: &mut Document, font_res: &Dict) -> Result<(), RedactError> {
let mut pending: Vec<(ObjRef, usize)> = res_dict(doc, font_res, b"XObject").iter().filter_map(|(_, v)| v.as_ref()).map(|r| (r, 0)).collect();
let mut seen = HashSet::new();
while let Some((form_ref, depth)) = pending.pop() {
@@ -217,7 +211,7 @@ fn prune_font_forms(doc: &mut Document, font_res: &Dict) -> Result<(), CosError>
continue;
}
if depth > MAX_DEPTH || seen.len() > MAX_HOLDERS {
return Err(CosError::Syntax { offset: 0, detail: "redaction could not establish safe Type 3 font cleanup: forms nest too deep".into() });
return Err(RedactError::Refused("the forms a Type 3 font's resources draw nest deeper, or are more, than can be followed".into()));
}
let Object::Stream(form) = &*doc.get(form_ref) else { continue };
if form.dict.name(b"Subtype") != Some(b"Form") {
@@ -232,10 +226,7 @@ fn prune_font_forms(doc: &mut Document, font_res: &Dict) -> Result<(), CosError>
Some(r) => match r.as_dict() {
Some(d) => d.clone(),
None => {
return Err(CosError::Syntax {
offset: 0,
detail: "redaction could not establish safe Type 3 font cleanup: a form's /Resources is not a dictionary".into(),
});
return Err(RedactError::Refused("a form a Type 3 font's resources draw has /Resources that isn't a dictionary".into()));
}
},
};
@@ -307,9 +298,11 @@ fn scan_content_stream(
res: &Dict,
initial_font: Option<FontKey>,
depth: usize,
) -> Result<(), CosError> {
) -> Result<(), RedactError> {
if depth > MAX_DEPTH {
return Err(CosError::Syntax { offset: 0, detail: "redaction exceeded max depth inspecting Type 3 font content".into() });
return Err(RedactError::Refused(
"content that may show a Type 3 font nests forms, patterns or soft masks deeper than can be followed".into(),
));
}
let joined = Pieces::join(content);
// One operator at a time, so content of millions of them is never held whole. The scan only
@@ -347,7 +340,7 @@ fn scan_content_stream(
}
}
if read.skipped() > 0 {
return Err(CosError::Syntax { offset: 0, detail: "redaction could not fully inspect content stream syntax".into() });
return Err(RedactError::Refused("content that may show a Type 3 font has bytes that can't be read".into()));
}
Ok(())
}
@@ -405,7 +398,7 @@ fn scan_xobject(
name: &[u8],
current_font: Option<FontKey>,
depth: usize,
) -> Result<(), CosError> {
) -> Result<(), RedactError> {
let xo = res_dict(ctx.doc, res, b"XObject");
let Some(r) = xo.get(name).and_then(Object::as_ref) else { return Ok(()) };
if !matches!(&*ctx.doc.get(r), Object::Stream(s) if s.dict.name(b"Subtype") == Some(b"Form")) {
@@ -417,7 +410,7 @@ fn scan_xobject(
/// Scan the tiling pattern `name` that an `scn` or `SCN` operator selects. Its cell is content of
/// its own and can show glyphs of a font the page lists too. A shading pattern is not a stream and
/// draws no text.
fn scan_pattern(ctx: &mut ScanContext<'_>, res: &Dict, holder_ref: ObjRef, name: &[u8], depth: usize) -> Result<(), CosError> {
fn scan_pattern(ctx: &mut ScanContext<'_>, res: &Dict, holder_ref: ObjRef, name: &[u8], depth: usize) -> Result<(), RedactError> {
let patterns = res_dict(ctx.doc, res, b"Pattern");
let Some(r) = patterns.get(name).and_then(Object::as_ref) else { return Ok(()) };
scan_stream_object(ctx, res, holder_ref, r, None, depth)
@@ -425,7 +418,7 @@ fn scan_pattern(ctx: &mut ScanContext<'_>, res: &Dict, holder_ref: ObjRef, name:
/// Scan the transparency group of the soft mask that the ExtGState `name` sets: what it shows
/// shapes the page, so its glyphs are in use.
fn scan_soft_mask(ctx: &mut ScanContext<'_>, res: &Dict, holder_ref: ObjRef, name: &[u8], depth: usize) -> Result<(), CosError> {
fn scan_soft_mask(ctx: &mut ScanContext<'_>, res: &Dict, holder_ref: ObjRef, name: &[u8], depth: usize) -> Result<(), RedactError> {
let states = res_dict(ctx.doc, res, b"ExtGState");
let Some(state) = states.get(name).and_then(|s| ctx.doc.resolve(s).as_dict().cloned()) else { return Ok(()) };
let Some(mask) = state.get(b"SMask").and_then(|m| ctx.doc.resolve(m).as_dict().cloned()) else { return Ok(()) };
@@ -436,7 +429,7 @@ fn scan_soft_mask(ctx: &mut ScanContext<'_>, res: &Dict, holder_ref: ObjRef, nam
/// Scan the appearance streams of a page's annotations. A comment, stamp or field can show glyphs
/// of a Type 3 font that the page lists too. An appearance without resources of its own draws
/// through the page's.
fn scan_appearances(ctx: &mut ScanContext<'_>, page: &Dict, page_ref: ObjRef, page_res: &Dict) -> Result<(), CosError> {
fn scan_appearances(ctx: &mut ScanContext<'_>, page: &Dict, page_ref: ObjRef, page_res: &Dict) -> Result<(), RedactError> {
for annot in crate::annots_of(ctx.doc, page) {
for r in appearance_streams(ctx.doc, &annot) {
scan_stream_object(ctx, page_res, page_ref, r, None, 0)?;
@@ -488,7 +481,7 @@ fn resourceless_appearances(doc: &Document, page: &Dict) -> Vec<ObjRef> {
/// already. Tiling patterns are not read here: a tiling pattern must have resources of its own,
/// so its cell draws through them, and Apply Redactions refuses one without them
/// (`pattern_guard`).
fn add_soft_mask_ops(doc: &Document, res: &Dict, ops: &mut Vec<pdfcraft_content::Op>, known: usize) -> Result<(), CosError> {
fn add_soft_mask_ops(doc: &Document, res: &Dict, ops: &mut Vec<pdfcraft_content::Op>, known: usize) -> Result<(), RedactError> {
let xobjects = res_dict(doc, res, b"XObject");
let states = res_dict(doc, res, b"ExtGState");
let mut seen = HashSet::new();
@@ -519,7 +512,9 @@ fn add_soft_mask_ops(doc: &Document, res: &Dict, ops: &mut Vec<pdfcraft_content:
}
let parsed = pdfcraft_content::parse(&doc.with_direct_parms(s).decoded()?);
if parsed.skipped > 0 || ops.len().saturating_add(parsed.ops.len()) > 2_000_000 {
return Err(CosError::Syntax { offset: 0, detail: "redaction could not fully inspect soft mask content".into() });
return Err(RedactError::Refused(
"a soft mask or form without resources of its own has bytes that can't be read, or takes what draws with those resources past 2,000,000 operators".into(),
));
}
ops.extend(parsed.ops);
}
@@ -536,7 +531,7 @@ fn scan_stream_object(
r: ObjRef,
current_font: Option<FontKey>,
depth: usize,
) -> Result<(), CosError> {
) -> Result<(), RedactError> {
let obj = ctx.doc.get(r);
let Object::Stream(s) = &*obj else { return Ok(()) };
let own_res = s.dict.get(b"Resources").and_then(|ro| ctx.doc.resolve(ro).as_dict().cloned());
@@ -577,7 +572,7 @@ pub(crate) fn prune_type3_from_resources(
res: &mut Dict,
content: &[Vec<u8>],
page: Option<&Dict>,
) -> Result<(), CosError> {
) -> Result<(), RedactError> {
let mut fonts = res_dict(doc, res, b"Font");
if fonts.is_empty() {
return Ok(());
@@ -605,10 +600,16 @@ pub(crate) fn prune_type3_from_resources(
// only in its turn, so they are never all held at once.
for r in resourceless_appearances(doc, page) {
let Object::Stream(s) = &*doc.get(r) else { continue };
let data = budget.decode(&doc.with_direct_parms(s))?;
// Past what the page may read where the budget refused it, as in `resource_ops`.
let refused = budget.refused();
let data = budget
.decode(&doc.with_direct_parms(s))
.map_err(|e| if budget.refused() > refused { RedactError::past_allowance(e) } else { e.into() })?;
let more = crate::interp::resource_ops(doc, budget, res, std::slice::from_ref(&data))?;
if ops.len().saturating_add(more.len()) > 2_000_000 {
return Err(CosError::Syntax { offset: 0, detail: "redaction could not fully inspect annotation appearances".into() });
return Err(RedactError::Refused(
"the page's annotation appearances take what draws with its resources past 2,000,000 operators".into(),
));
}
ops.extend(more);
}
@@ -736,8 +737,9 @@ pub(crate) fn unlink_type3(doc: &mut Document) -> Result<(), RedactError> {
})
.unwrap_or_default();
scan_content_stream(&mut ctx, &content, p.obj, &page_res, None, 0)?;
scan_appearances(&mut ctx, &p.dict, p.obj, &page_res)?;
scan_content_stream(&mut ctx, &content, p.obj, &page_res, None, 0)
.and_then(|()| scan_appearances(&mut ctx, &p.dict, p.obj, &page_res))
.map_err(|e| e.on_page(pi + 1))?;
}
// Also scan any surviving form that wasn't reached by page streams directly.
@@ -761,7 +763,7 @@ pub(crate) fn unlink_type3(doc: &mut Document) -> Result<(), RedactError> {
/// Every reachable Form XObject with resources of its own, with those resources, found by
/// walking the resources of the holders and of the forms they draw.
fn reachable_form_holders(doc: &Document, holders: &[(ObjRef, Vec<ObjRef>)]) -> Result<Vec<(ObjRef, Dict)>, CosError> {
fn reachable_form_holders(doc: &Document, holders: &[(ObjRef, Vec<ObjRef>)]) -> Result<Vec<(ObjRef, Dict)>, RedactError> {
let mut form_holders: Vec<(ObjRef, Dict)> = Vec::new();
let mut pending_res: Vec<Dict> = holders
.iter()
@@ -775,7 +777,7 @@ fn reachable_form_holders(doc: &Document, holders: &[(ObjRef, Vec<ObjRef>)]) ->
continue;
}
if seen_forms.len() > MAX_HOLDERS {
return Err(CosError::Syntax { offset: 0, detail: "redaction exceeded max depth inspecting form resources".into() });
return Err(RedactError::Refused("the forms the document's resources draw are more than can be followed".into()));
}
let object = doc.get(reference);
let Object::Stream(form) = &*object else { continue };
@@ -794,12 +796,9 @@ fn reachable_form_holders(doc: &Document, holders: &[(ObjRef, Vec<ObjRef>)]) ->
/// Record every Type 3 font named by a resource dictionary's `/Font` and `/ExtGState` entries.
/// A Type 3 font held directly in a resource dictionary can neither be named reliably nor have its
/// glyph programs rewritten, so redaction fails closed rather than leaving its glyphs unchecked.
fn collect_type3_fonts(doc: &Document, res: &Dict, t3_fonts: &mut HashMap<FontKey, Dict>) -> Result<(), CosError> {
let direct = || CosError::Syntax {
offset: 0,
detail: "redaction could not establish safe Type 3 font cleanup: a Type 3 font is not an indirect object".into(),
};
let mut consider = |font_obj: &Object| -> Result<(), CosError> {
fn collect_type3_fonts(doc: &Document, res: &Dict, t3_fonts: &mut HashMap<FontKey, Dict>) -> Result<(), RedactError> {
let direct = || RedactError::Refused("a Type 3 font is written inside a resource dictionary, not as an object of its own".into());
let mut consider = |font_obj: &Object| -> Result<(), RedactError> {
if let Some(dict) = doc.resolve(font_obj).as_dict().cloned()
&& dict.name(b"Subtype") == Some(b"Type3")
{
@@ -831,12 +830,10 @@ fn clean_type3_font(
reads: &mut GlyphReads,
) -> Result<(), RedactError> {
let Some(char_procs_val) = font_dict.get(b"CharProcs") else {
return Err(CosError::Syntax { offset: 0, detail: "redaction could not establish safe Type 3 font cleanup: missing CharProcs".into() }.into());
return Err(RedactError::Refused("a Type 3 font has no /CharProcs".into()));
};
let mut char_procs = doc.resolve(char_procs_val).as_dict().cloned().ok_or_else(|| CosError::Syntax {
offset: 0,
detail: "redaction could not establish safe Type 3 font cleanup: CharProcs is not a dict".into(),
})?;
let mut char_procs =
doc.resolve(char_procs_val).as_dict().cloned().ok_or_else(|| RedactError::Refused("a Type 3 font's /CharProcs isn't a dictionary".into()))?;
let mut procs_changed = false;
let glyph_names: Vec<Vec<u8>> = char_procs.iter().map(|(n, _)| n.to_vec()).collect();
@@ -878,14 +875,15 @@ fn clean_type3_font(
}
let resolved = doc.resolve(proc_val);
let Object::Stream(s) = &*resolved else {
return Err(CosError::Syntax {
offset: 0,
detail: "redaction could not establish safe Type 3 font cleanup: CharProc is not a stream".into(),
}
.into());
return Err(RedactError::Refused("a Type 3 font's glyph isn't a stream".into()));
};
// Past the allowance the cleanup can't be shown complete, and the redaction is refused.
let data = reads.budget.decode(&doc.with_direct_parms(s))?;
// Past the allowance the cleanup can't be shown complete, and the redaction is refused, as
// in `resource_ops`; a glyph that doesn't decode says why.
let refused = reads.budget.refused();
let data = reads
.budget
.decode(&doc.with_direct_parms(s))
.map_err(|e| if reads.budget.refused() > refused { RedactError::past_glyph_allowance(e) } else { e.into() })?;
let mut used = UsedInGlyphs::default();
collect_used_resources_in_stream(&data, &mut used)?;
used_in_glyphs.merge(&used);
+115 -8
View File
@@ -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`].
@@ -200,27 +209,105 @@ pub fn layout(glyphs: Vec<TextGlyph>) -> PageText {
PageText { glyphs, line_of, space_before, truncated: false }
}
/// [`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();
@@ -517,7 +604,27 @@ fn arrange(glyphs: &[TextGlyph]) -> (Vec<usize>, Vec<u32>, Vec<bool>) {
let &[p, c] = pair else { continue };
let Some(&Some(gap)) = sc.cluster_gap.get(w + 1) else { continue };
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.
+214
View File
@@ -1348,6 +1348,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]
@@ -3184,6 +3300,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.
+6 -3
View File
@@ -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();
+38
View File
@@ -66,6 +66,44 @@ pub fn template(rows: usize) -> String {
t
}
/// A check box `more`, `before`, an 8in block, the hidden section `details` (two fields 3in
/// tall) and `after`, on letter pages: shown, the section needs another page. With
/// `calculated`, a hidden field's calculate script shows or hides the section as `more` says
/// (so a reset does too); otherwise the check box's change script does. `exit` is the check
/// box's exit script, if not empty.
pub fn presence_growth_template(calculated: bool, before: &str, after: &str, exit: &str) -> String {
let js = |activity: &str, body: &str| {
format!(r#"<event activity="{activity}"><script contentType="application/x-javascript">{body}</script></event>"#)
};
let (change, sync) = if calculated {
let script = r#"details.presence = (more.rawValue == 1) ? "visible" : "hidden"; "";"#;
let sync = format!(
r#"<field name="sync" w="1in" h="0.2in" presence="hidden"><ui><textEdit/></ui><calculate><script contentType="application/x-javascript">{script}</script></calculate></field>"#
);
(String::new(), sync)
} else {
(js("change", r#"details.presence = (this.rawValue == 1) ? "visible" : "hidden";"#), String::new())
};
let exit = if exit.is_empty() { String::new() } else { js("exit", exit) };
format!(
r#"<xdp:xdp xmlns:xdp="http://ns.adobe.com/xdp/">
<template xmlns="http://www.xfa.org/schema/xfa-template/3.3/"><subform name="form" layout="tb">
<pageSet><pageArea name="master"><occur max="-1"/><contentArea x="0.5in" y="0.5in" w="7.5in" h="10in"/><medium short="8.5in" long="11in"/></pageArea></pageSet>
<subform name="page1" layout="tb">
<field name="more" w="3in" h="0.3in"><ui><checkButton/></ui><items><integer>1</integer><integer>0</integer></items>{change}{exit}</field>
{sync}{before}
<draw name="filler" w="7.5in" h="8in"><value><text>Filler</text></value></draw>
<subform name="details" layout="tb" presence="hidden">
<field name="d1" w="6in" h="3in"><ui><textEdit/></ui></field>
<field name="d2" w="6in" h="3in"><ui><textEdit/></ui></field>
</subform>
{after}
</subform>
</subform></template>
</xdp:xdp>"#
)
}
/// A growable rich-text field followed by a section that starts on a new page.
pub fn growable_text_template(scripted: bool) -> String {
let event = if scripted { r#"<event activity="initialize"><script contentType="application/x-javascript">0;</script></event>"# } else { "" };
+38 -3
View File
@@ -1,7 +1,8 @@
//! The layout engine: places a template's subforms, draws and fields on pages (XFA 3.3 part 2,
//! "Layout"). Supports positioned, top-to-bottom, left-to-right and table/row layouts, page
//! masters with content areas, `breakBefore`/`breakAfter`, and overflow leaders (header rows
//! repeated after a page break). Repeating subforms get their initial instances.
//! masters with content areas, `breakBefore`/`breakAfter` (including a named `pageArea`
//! target), overflow onto a named master, and overflow leaders (header rows repeated after a
//! page break). Repeating subforms get their initial instances.
//!
//! Output is a list of pages of resolution-independent items; `pdf` turns them into PDF.
@@ -30,7 +31,7 @@ mod pages;
pub(crate) use common::date_pattern;
pub use common::formatted_value;
use common::{collect_names, collect_values};
use common::{clamp_opt, collect_names, collect_values};
pub(crate) use items::UNDERLINE_DROP;
pub use items::{Action, BorderShape, Form, Item, Page, Rounded, Turned, Widget, WidgetBorder, WidgetKind};
@@ -129,6 +130,9 @@ struct Frame {
w: f64,
margin: Margin,
border: Option<Border>,
/// Width-less sections adapt to a new content area, using their original constraints.
/// A fixed width keeps its position.
width_limits: Option<(Option<f64>, Option<f64>)>,
part: FlowMark,
parts: Vec<(usize, usize, Rect)>,
/// Something inside didn't fit its content area: an item cut across areas, or one placed past
@@ -141,6 +145,19 @@ struct Frame {
held: bool,
}
impl Frame {
fn fit_width(&mut self, (x, w): (f64, f64)) {
if let Some((min, max)) = self.width_limits {
self.x = x;
self.w = clamp_opt(w, min, max).min(w.max(1.0));
}
}
fn inner_width(&self) -> (f64, f64) {
(self.x + self.margin.left, (self.w - self.margin.horizontal()).max(1.0))
}
}
struct Cursor {
area: usize,
content: usize,
@@ -168,6 +185,12 @@ struct Layouter<'t> {
pages: Vec<Page>,
cur: Option<Cursor>,
names: HashMap<String, usize>,
/// State before the current master was drawn, for replacing an otherwise empty page.
page_fields: usize,
/// Only names touched on this page, including reservations that emitted no widget.
page_names: HashMap<String, Option<usize>>,
/// PDF field names added to [`Self::taken`] on the current page.
page_taken: Vec<String>,
/// Every PDF field name handed out so far.
taken: HashSet<String>,
/// The names the template's fields, groups and groups' members take as written
@@ -200,6 +223,12 @@ struct Layouter<'t> {
/// The flowed subforms being laid out, outermost first: a break between their children
/// closes their parts on one content area and opens new ones on the next.
frames: Vec<Frame>,
/// The `pageArea` index used for an untargeted new page. Explicit break targets stick.
/// An `overflow` target is installed only while its subform is laid out, then the previous
/// selection returns unless a later explicit break replaced it (`preferred_epoch`).
preferred_area: Option<usize>,
/// Bumped when an explicit break selects [`Self::preferred_area`].
preferred_epoch: u64,
/// What scripts set on page-master content, applied to each page's copy by its own SOM path.
overrides: Option<&'t crate::script::Overrides>,
/// The pages' copies of master content that overrides changed, kept for the whole layout so
@@ -242,6 +271,7 @@ fn layout_inner(tpl: &Template, data: Option<&DataNode>, overrides: Option<&crat
Some(ps) if !ps.areas.is_empty() => ps.areas.clone(),
_ => vec![PageArea {
name: None,
id: None,
width: 612.0,
height: 792.0,
content: vec![Rect::new(36.0, 36.0, 540.0, 720.0)],
@@ -263,6 +293,9 @@ fn layout_inner(tpl: &Template, data: Option<&DataNode>, overrides: Option<&crat
pages: Vec::new(),
cur: None,
names: HashMap::new(),
page_fields: 0,
page_names: HashMap::new(),
page_taken: Vec::new(),
taken: HashSet::new(),
template_names,
values,
@@ -279,6 +312,8 @@ fn layout_inner(tpl: &Template, data: Option<&DataNode>, overrides: Option<&crat
field_border: None,
views: Views::ALL,
frames: Vec::new(),
preferred_area: None,
preferred_epoch: 0,
overrides,
master_copies: Vec::new(),
};
+13 -3
View File
@@ -115,9 +115,19 @@ pub(super) fn clamp_opt(v: f64, min: Option<f64>, max: Option<f64>) -> f64 {
v.max(0.0)
}
/// Does `node` flow (may be split across pages) rather than being placed as one block?
pub(super) fn splittable(node: &Node) -> bool {
matches!(node, Node::Subform(s) if matches!(s.layout, Layout::Tb | Layout::Table) && s.common.h.is_none())
/// Does `node` flow through [`Layouter::flow_subform`] (either because it may be split across
/// pages or because it carries a page break or page-area target of its own)?
pub(super) fn flows_as_subform(node: &Node) -> bool {
matches!(
node,
Node::Subform(s)
if (matches!(s.layout, Layout::Tb | Layout::Table) && s.common.h.is_none())
|| s.break_before_page
|| s.break_after_page
|| s.break_before_target.is_some()
|| s.break_after_target.is_some()
|| s.overflow_target.is_some()
)
}
/// Top and bottom of an item a page break must not cut (text, a picture, a field); `None`
+3
View File
@@ -479,14 +479,17 @@ impl Layouter<'_> {
let base = clean_name(base);
// The template's own name, while no other field has it.
if !fallback && self.taken.insert(base.clone()) {
self.page_taken.push(base.clone());
return base;
}
loop {
self.page_names.entry(base.clone()).or_insert_with(|| self.names.get(&base).copied());
let n = self.names.entry(base.clone()).or_insert(0);
*n = n.saturating_add(1);
let candidate = if *n == 1 { base.clone() } else { format!("{base}_{n}") };
let reserved = (fallback || *n > 1) && self.template_names.contains(&candidate);
if !reserved && self.taken.insert(candidate.clone()) {
self.page_taken.push(candidate.clone());
return candidate;
}
}
+61 -14
View File
@@ -1,4 +1,4 @@
use super::common::{WidgetRest, clamp_opt, divide, is_row, moved, solid_extent, split_line, split_widget, splittable, widget_box};
use super::common::{WidgetRest, clamp_opt, divide, flows_as_subform, is_row, moved, solid_extent, split_line, split_widget, widget_box};
use super::items::Item;
use super::{
Ctx, Frame, Layout, Layouter, MAX_DEPTH, MAX_INSTANCES, MAX_MEASURES, Node, Rect, SomIndices, Splitting, Subform, XfaError, data_path,
@@ -323,8 +323,28 @@ impl Layouter<'_> {
}
let Node::Subform(sf) = node else { return Ok(()) };
self.check_measures()?;
if sf.break_before_page && self.page_has_flow() {
self.break_frames(0.0, true)?;
let prev_rect = self.cursor().0;
let before_target = sf.break_before_target.as_deref().and_then(|t| self.find_page_area(t));
if let Some(idx) = before_target {
self.select_break_area(idx);
}
if sf.break_before_page {
if self.page_has_flow() {
self.break_frames_to(0.0, true, before_target)?;
} else if let Some(idx) = before_target
&& self.cur.as_ref().is_some_and(|c| c.area != idx)
{
self.switch_empty_page(idx)?;
}
}
// Overflow steers pages created while this subform (and its descendants) are open.
// Putting the previous selection back afterwards keeps a later sibling's untargeted
// break off this master. A descendant's explicit break bumps `preferred_epoch` and stays.
let overflow_area = sf.overflow_target.as_deref().and_then(|t| self.find_page_area(t));
let preferred_before_overflow = self.preferred_area;
let epoch_at_overflow = self.preferred_epoch;
if let Some(idx) = overflow_area {
self.preferred_area = Some(idx);
}
// Data adds instances of a repeating subform (rows added in another viewer).
let instances = self.laid_out_instances(node, &ctx.som);
@@ -335,7 +355,13 @@ impl Layouter<'_> {
self.check_measures()?;
let ctx = ctx_parent.with_som(&sf.common, sib + i);
let (rect, _, _) = self.cursor();
let (x, w) = avail.unwrap_or((rect.x, rect.w));
// When a break moved to a content area of a different width (such as switching from a
// portrait master to a landscape master), a width from the old content area no longer
// bounds this subform.
let (x, w) = match avail {
Some(av) if rect == prev_rect => av,
_ => self.frames.last().map_or((rect.x, rect.w), Frame::inner_width),
};
let w = clamp_opt(sf.common.w.unwrap_or(w), sf.common.min_w, sf.common.max_w).min(w.max(1.0));
if !matches!(sf.layout, Layout::Tb | Layout::Table) || sf.common.h.is_some() {
// Not splittable: one block.
@@ -347,14 +373,25 @@ impl Layouter<'_> {
// Its border and fill go round what it takes from here, a part on each content area.
let framed = match self.flow_mark() {
Some(part) => {
self.frames.push(Frame { x, w, margin: m, border: sf.common.border.clone(), part, parts: Vec::new(), lost: false, held: false });
self.frames.push(Frame {
x,
w,
margin: m,
border: sf.common.border.clone(),
width_limits: sf.common.w.is_none().then_some((sf.common.min_w, sf.common.max_w)),
part,
parts: Vec::new(),
lost: false,
held: false,
});
true
}
None => false,
};
self.advance(m.top);
let inner_x = x + m.left;
let inner_w = (w - m.horizontal()).max(1.0);
let mut cur_rect = rect;
let mut inner_x = x + m.left;
let mut inner_w = (w - m.horizontal()).max(1.0);
match sf.layout {
Layout::Table => self.flow_table(sf, inner_x, inner_w, &ctx, depth)?,
_ => {
@@ -363,10 +400,15 @@ impl Layouter<'_> {
if !child.common().presence.occupies() {
continue;
}
let (r, _, _) = self.cursor();
if r != cur_rect && sf.common.w.is_none() {
cur_rect = r;
if framed && let Some(f) = self.frames.last() {
(inner_x, inner_w) = f.inner_width();
}
}
let csib = sibs.at(ci);
if let Node::Subform(_) = child
&& splittable(child)
{
if flows_as_subform(child) {
self.flow_subform(child, Some((inner_x, inner_w)), &ctx, depth + 1, csib)?;
continue;
}
@@ -379,8 +421,15 @@ impl Layouter<'_> {
self.finish_frame(frame)?;
}
}
if overflow_area.is_some() && self.preferred_epoch == epoch_at_overflow {
self.preferred_area = preferred_before_overflow;
}
if sf.break_after_page {
self.break_frames(0.0, true)?;
let after_target = sf.break_after_target.as_deref().and_then(|t| self.find_page_area(t));
if let Some(idx) = after_target {
self.select_break_area(idx);
}
self.break_frames_to(0.0, true, after_target)?;
}
Ok(())
}
@@ -430,9 +479,7 @@ impl Layouter<'_> {
}
continue;
}
if splittable(child)
&& let Node::Subform(_) = child
{
if flows_as_subform(child) {
self.flow_subform(child, Some((x, inner_w)), ctx, depth + 1, csib)?;
continue;
}
+99 -4
View File
@@ -3,7 +3,7 @@ use super::EMBED_COPIED;
use super::items::{Item, Page, UNDERLINE_DROP};
use super::{
Block, Border, Common, Ctx, Cursor, FlowMark, Font, Frame, Layouter, MAX_DRAW_CHARS, MAX_ITEMS, MAX_MEASURES, MAX_PAGES, Node, PAGE_COUNT_MARK,
PageRole, Para, Rc, Rect, SomIndices, Views, XfaError, data_path, text,
PageArea, PageRole, Para, Rc, Rect, SomIndices, Views, XfaError, data_path, text,
};
impl Layouter<'_> {
@@ -114,12 +114,79 @@ impl Layouter<'_> {
// ───────────────────────────────────────────────────────────────────────── pages
/// Find the `pageArea` index matching a `target` attribute (by `name` or `#id`, or the final
/// SOM segment), preferring an area whose `occur_max` is not yet exhausted.
pub(super) fn find_page_area(&self, target: &str) -> Option<usize> {
let raw = target.trim().trim_start_matches('#');
let leaf = raw.rsplit('.').next().unwrap_or(raw).split('[').next().unwrap_or(raw).trim().trim_start_matches('#');
if leaf.is_empty() {
return None;
}
let matches = |a: &PageArea| {
a.name.as_deref() == Some(leaf) || a.id.as_deref() == Some(leaf) || a.name.as_deref() == Some(raw) || a.id.as_deref() == Some(raw)
};
(0..self.areas.len()).find(|&i| {
let Some(area) = self.areas.get(i) else { return false };
matches(area) && area.occur_max.is_none_or(|m| self.uses.get(i).is_some_and(|u| *u < m))
})
}
/// Remember an explicit break target for later untargeted pages. A later explicit break
/// replaces it. An `overflow` target may hide it while that subform is open; it returns
/// afterwards unless a later explicit break replaced the overflow.
pub(super) fn select_break_area(&mut self, idx: usize) {
self.preferred_area = Some(idx);
self.preferred_epoch = self.preferred_epoch.saturating_add(1);
}
pub(super) fn new_page(&mut self) -> Result<(), XfaError> {
let idx =
(0..self.areas.len()).find(|&i| self.areas[i].occur_max.is_none_or(|m| self.uses[i] < m)).unwrap_or(self.areas.len().saturating_sub(1));
let idx = self
.preferred_area
.filter(|&i| self.areas.get(i).is_some_and(|a| a.occur_max.is_none_or(|m| self.uses.get(i).is_some_and(|u| *u < m))))
.or_else(|| {
(0..self.areas.len())
.find(|&i| self.areas.get(i).is_some_and(|a| a.occur_max.is_none_or(|m| self.uses.get(i).is_some_and(|u| *u < m))))
})
.unwrap_or(self.areas.len().saturating_sub(1));
self.new_page_of(idx)
}
/// Replace the current page when nothing from the flow has been placed on it yet and a
/// subform's `breakBefore` targets a different `pageArea` `idx`.
pub(super) fn switch_empty_page(&mut self, idx: usize) -> Result<(), XfaError> {
if let Some(c) = &self.cur
&& let Some(u) = self.uses.get_mut(c.area)
{
*u = u.saturating_sub(1);
}
if let Some(old) = self.pages.pop() {
self.items = self.items.saturating_sub(old.items.len());
}
self.fields = self.page_fields;
for name in self.page_taken.drain(..) {
self.taken.remove(&name);
}
for (name, previous) in self.page_names.drain() {
if let Some(count) = previous {
self.names.insert(name, count);
} else {
self.names.remove(&name);
}
}
self.new_page_of(idx)?;
let (rect, y, _) = self.cursor();
let mut room = (rect.bottom() - y).max(0.0);
for i in 0..self.frames.len() {
let Some(mark) = self.flow_mark() else { break };
let Some(f) = self.frames.get_mut(i) else { break };
f.part = mark;
let top = f.margin.top.max(0.0).min(room);
room = (room - top).max(0.0);
self.advance(top);
}
Ok(())
}
/// Once the body has been laid out, give every page area that has been used fewer times than
/// its `occur min` the pages it still needs, in template order, after the body's pages.
pub(super) fn satisfy_page_area_minimums(&mut self) -> Result<(), XfaError> {
@@ -134,6 +201,7 @@ impl Layouter<'_> {
/// Start a page from page area `idx`.
fn new_page_of(&mut self, idx: usize) -> Result<(), XfaError> {
let old_area = self.cursor().0;
if self.pages.len() >= MAX_PAGES {
return Err(XfaError::TooLarge(format!("the form lays out to more than {MAX_PAGES} pages")));
}
@@ -147,6 +215,10 @@ impl Layouter<'_> {
self.pages.push(Page { width: area.width, height: area.height, items: Vec::new(), area: area.name.clone() });
let content = area.content.first().copied().unwrap_or(Rect::new(0.0, 0.0, area.width, area.height));
self.cur = Some(Cursor { area: idx, content: 0, rect: content, y: content.y, placed: false });
self.refresh_frame_widths(old_area);
self.page_fields = self.fields;
self.page_names.clear();
self.page_taken.clear();
// Master page content: positioned draws and fields. The page area's own SOM index counts
// the pages made from it, so a field repeated on each page (a page number, an office-use
// box) has a path of its own per page rather than every page sharing `[0]`.
@@ -182,12 +254,29 @@ impl Layouter<'_> {
&& let Some(next) = area.content.get(c.content + 1).copied()
{
let i = c.content + 1;
let old_area = c.rect;
self.cur = Some(Cursor { area: c.area, content: i, rect: next, y: next.y, placed: false });
self.refresh_frame_widths(old_area);
return Ok(());
}
self.new_page()
}
/// Refresh outer frames before their children, preserving each parent's available width
/// and margins. A fixed-width frame keeps its position. Raw area moves (a split block) keep
/// their existing lost-border bookkeeping.
fn refresh_frame_widths(&mut self, old_area: Rect) {
let area = self.cursor().0;
if area == old_area {
return;
}
let mut available = (area.x, area.w);
for frame in &mut self.frames {
frame.fit_width(available);
available = frame.inner_width();
}
}
/// The current content area, how far down it the flow is, and whether anything has been
/// placed in it; before the first page, an empty letter-size page from its top.
pub(super) fn cursor(&self) -> (Rect, f64, bool) {
@@ -222,6 +311,10 @@ impl Layouter<'_> {
/// otherwise run past its bottom, out of its border. `to_page` moves to a new page instead (a
/// child's own page break), which breaks the subforms around it the same way.
pub(super) fn break_frames(&mut self, need: f64, to_page: bool) -> Result<(), XfaError> {
self.break_frames_to(need, to_page, None)
}
pub(super) fn break_frames_to(&mut self, need: f64, to_page: bool, target_area: Option<usize>) -> Result<(), XfaError> {
let (rect, mut y, _) = self.cursor();
let page = self.pages.len().saturating_sub(1);
let here: Vec<bool> = self.frames.iter().map(|f| self.on_area(&f.part)).collect();
@@ -234,7 +327,9 @@ impl Layouter<'_> {
f.parts.push((page, f.part.items, Rect::new(f.x, f.part.y, f.w, y - f.part.y)));
}
}
if to_page {
if let Some(idx) = target_area {
self.new_page_of(idx)?;
} else if to_page {
self.new_page()?;
} else {
self.next_area()?;
+7
View File
@@ -534,6 +534,12 @@ pub struct Subform {
/// `<breakBefore targetType="pageArea">`: start on a new page.
pub break_before_page: bool,
pub break_after_page: bool,
/// `<breakBefore target="…">` / `<break beforeTarget="…">`: named `pageArea` (or `#id`) to start on.
pub break_before_target: Option<String>,
/// `<breakAfter target="…">` / `<break afterTarget="…">`: named `pageArea` (or `#id`) to switch to after.
pub break_after_target: Option<String>,
/// `<overflow target="…">` / `<break overflowTarget="…">`: named `pageArea` (or `#id`) for overflow pages.
pub overflow_target: Option<String>,
/// Parsed from a `subformSet`: transparent to layout (XFA 3.3 p. 357), so in a flowing
/// container its members are laid out among their parent's other children.
pub set: bool,
@@ -848,6 +854,7 @@ pub struct PageSet {
#[derive(Clone, Debug, Default, PartialEq)]
pub struct PageArea {
pub name: Option<String>,
pub id: Option<String>,
pub width: f64,
pub height: f64,
/// Where flowed content goes, in order.
+30 -2
View File
@@ -942,7 +942,16 @@ fn parse_page_set(n: XmlNode, warnings: &mut Vec<String>, depth: usize) -> PageS
// would exhaust it, and demand a page for every master).
let occur = child(pa, "occur").map(|o| parse_occur(Some(o)));
let (occur_min, occur_max) = occur.map_or((0, None), |o| (o.min, o.max));
areas.push(PageArea { name: pa.attribute("name").map(str::to_string), width, height, content, items, occur_max, occur_min });
areas.push(PageArea {
name: pa.attribute("name").map(str::to_string),
id: pa.attribute("id").map(str::to_string),
width,
height,
content,
items,
occur_max,
occur_min,
});
}
// Nested page sets: take their areas too.
for ps in children(n, "pageSet") {
@@ -973,9 +982,22 @@ fn parse_subform(n: XmlNode, warnings: &mut Vec<String>, depth: usize, set_layou
}
let column_widths: Vec<f64> =
n.attribute("columnWidths").map(|s| s.split_whitespace().filter_map(measure).map(|w| w.max(0.0)).take(256).collect()).unwrap_or_default();
let is_page_target = |t: Option<&str>| t.is_none_or(|v| v == "pageArea" || v == "contentArea");
// A break to a page or content area. With no targetType, the default is `auto`: "layout
// continues using the current layout container" (XFA 3.3 p. 638), so no break.
let break_to_page = |name: &str| children(n, name).any(|b| b.attribute("targetType").is_some_and(|t| t == "pageArea" || t == "contentArea"));
let non_empty = |s: Option<&str>| s.map(str::trim).filter(|v| !v.is_empty()).map(str::to_string);
let break_target = |name: &str, break_attr: &str, target_attr: &str| -> Option<String> {
children(n, name)
.filter(|b| is_page_target(b.attribute("targetType")))
.find_map(|b| non_empty(b.attribute("target")))
.or_else(|| child(n, "break").filter(|b| is_page_target(b.attribute(break_attr))).and_then(|b| non_empty(b.attribute(target_attr))))
};
let break_before_target = break_target("breakBefore", "before", "beforeTarget");
let break_after_target = break_target("breakAfter", "after", "afterTarget");
let overflow_target = child(n, "overflow")
.and_then(|o| non_empty(o.attribute("target")))
.or_else(|| child(n, "break").and_then(|b| non_empty(b.attribute("overflowTarget"))));
Subform {
common,
layout,
@@ -984,8 +1006,14 @@ fn parse_subform(n: XmlNode, warnings: &mut Vec<String>, depth: usize, set_layou
page_set,
occur: parse_occur(child(n, "occur")),
break_before_page: break_to_page("breakBefore")
|| break_before_target.is_some()
|| child(n, "break").is_some_and(|b| b.attribute("before").is_some_and(|v| v == "pageArea" || v == "contentArea")),
break_after_page: break_to_page("breakAfter"),
break_after_page: break_to_page("breakAfter")
|| break_after_target.is_some()
|| child(n, "break").is_some_and(|b| b.attribute("after").is_some_and(|v| v == "pageArea" || v == "contentArea")),
break_before_target,
break_after_target,
overflow_target,
set: false,
column_widths,
overflow_leader: child(n, "overflow").and_then(|o| o.attribute("leader")).map(str::to_string).filter(|s| !s.is_empty()),
+463
View File
@@ -426,6 +426,8 @@ fn the_xdp_template_wins_over_the_config_packets_template_element() {
assert_eq!(tpl.root.common.name.as_deref(), Some("form"));
}
/// The sample form lays out over two pages: captions, draws and page numbers are drawn,
/// hidden draws take no space, and each field gets its widget with its size, kind and SOM path.
#[test]
fn layout_places_captions_fields_and_sizes_containers_to_their_content() {
let form = layout_xml(&template(1)).unwrap();
@@ -484,6 +486,97 @@ fn layout_places_captions_fields_and_sizes_containers_to_their_content() {
);
}
/// The left edges of the lines of a draw `w` points wide holding `text` in Arial 8 pt, with
/// `para` attributes, from the content area's left edge (0.5in).
fn line_starts(text: &str, w: f64, para: &str) -> Vec<f64> {
let xdp = format!(
r##"<xdp:xdp xmlns:xdp="http://ns.adobe.com/xdp/"><template xmlns="http://www.xfa.org/schema/xfa-template/3.3/">
<subform name="form" layout="tb">
<pageSet><pageArea name="front"><contentArea x="0.5in" y="0.5in" w="7.5in" h="10in"/><medium short="8.5in" long="11in"/></pageArea></pageSet>
<draw name="label" w="{w}pt" h="1in"><value><text>{text}</text></value><font typeface="Arial" size="8pt"/><para {para} lineHeight="8pt"/></draw>
</subform>
</template></xdp:xdp>"##
);
let form = layout_xml(&xdp).unwrap();
let mut lines: Vec<(i64, f64)> = Vec::new();
for item in &form.pages[0].items {
let Item::Text(s) = item else { continue };
let key = (s.baseline * 100.0).round() as i64;
match lines.iter_mut().find(|(b, _)| *b == key) {
Some((_, x)) => *x = x.min(s.x),
None => lines.push((key, s.x)),
}
}
lines.sort_by_key(|(b, _)| *b);
lines.into_iter().map(|(_, x)| x - 36.0).collect()
}
/// A negative textIndent hangs the first line: it starts left of the others, never left of the
/// box, and the other lines move in by the hang. A positive indent still moves only the first line.
#[test]
fn a_negative_text_indent_hangs_the_first_line_and_indents_the_rest() {
let text = "11. SERVICE MEMBER BALANCE (TOTAL)";
// No left margin: the first line starts at the box's edge and the others 18pt in.
let starts = line_starts(text, 58.0, r#"textIndent="-18pt""#);
assert!(starts.len() >= 3, "{starts:?}");
assert!(starts[0].abs() < 1e-6, "first line at the edge: {starts:?}");
assert!(starts[1..].iter().all(|x| (x - 18.0).abs() < 1e-6), "the rest hang 18pt in: {starts:?}");
// With a left margin wider than the hang, the first line starts at the margin less the hang.
let starts = line_starts(text, 90.0, r#"marginLeft="30pt" textIndent="-18pt""#);
assert!(starts.len() >= 2, "{starts:?}");
assert!((starts[0] - 12.0).abs() < 1e-6 && starts[1..].iter().all(|x| (x - 30.0).abs() < 1e-6), "{starts:?}");
// A positive indent still moves only the first line in.
let starts = line_starts(text, 58.0, r#"textIndent="10pt""#);
assert!((starts[0] - 10.0).abs() < 1e-6 && starts[1..].iter().all(|x| x.abs() < 1e-6), "{starts:?}");
// Without a negative indent a negative left margin moves every line left, as before.
let starts = line_starts(text, 58.0, r#"marginLeft="-6pt""#);
assert!(starts.iter().all(|x| (x + 6.0).abs() < 1e-6), "{starts:?}");
let starts = line_starts(text, 58.0, r#"marginLeft="-6pt" textIndent="10pt""#);
assert!((starts[0] - 4.0).abs() < 1e-6 && starts[1..].iter().all(|x| (x + 6.0).abs() < 1e-6), "{starts:?}");
}
/// A hang wider than its box is bounded by it: every line still starts and ends inside the box,
/// and lines after the first keep room for the widest glyph when the text wraps.
#[test]
fn a_hang_wider_than_the_box_keeps_every_line_inside_it() {
// A 58pt box hanging its first line by 100pt, right-aligned.
for text in ["AB CD EF", "ABCDEFGHIJ KLMNOPQRST UVWXYZ MMMM WWWW"] {
let xdp = format!(
r##"<xdp:xdp xmlns:xdp="http://ns.adobe.com/xdp/"><template xmlns="http://www.xfa.org/schema/xfa-template/3.3/">
<subform name="form" layout="tb">
<pageSet><pageArea name="front"><contentArea x="0.5in" y="0.5in" w="7.5in" h="10in"/><medium short="8.5in" long="11in"/></pageArea></pageSet>
<draw name="label" w="58pt" h="5in"><value><text>{text}</text></value><font typeface="Arial" size="8pt"/><para hAlign="right" textIndent="-100pt" lineHeight="8pt"/></draw>
</subform>
</template></xdp:xdp>"##
);
let form = layout_xml(&xdp).unwrap();
let mut lines = std::collections::BTreeSet::new();
for item in &form.pages[0].items {
let Item::Text(s) = item else { continue };
lines.insert((s.baseline * 100.0).round() as i64);
let right = s.x + s.face.width(s.text.trim_end());
assert!(s.x >= 36.0 - 1e-6 && right <= 36.0 + 58.0 + 1e-6, "{text}: {:?} runs from {} to {right}", s.text, s.x);
}
if text.len() > 10 {
assert!(lines.len() > 1, "{text}: wraps onto more lines ({})", lines.len());
}
}
}
/// A label without a width that hangs its first line is as wide as that line is laid out: the
/// hang takes back the left margin the first line doesn't use, so right-aligned text starts at
/// the label's x.
#[test]
fn a_label_without_a_width_measures_its_hanging_indent_as_it_is_laid_out() {
let items = positioned(
r#"<draw name="a" x="1in" y="0"><value><text>11. BALANCE</text></value><font typeface="Arial" size="8pt"/><para hAlign="right" marginLeft="18pt" textIndent="-18pt"/></draw>"#,
);
let span = items.iter().find_map(|i| if let Item::Text(s) = i { Some(s) } else { None }).expect("the text");
assert!((span.x - (36.0 + 72.0)).abs() < 0.05, "starts at its x: {}", span.x);
}
/// A long table breaks across pages between whole rows, repeats its header row at the top of
/// each page it continues on, and keeps every row (and field name) once.
#[test]
fn tables_break_across_pages_and_repeat_their_header_row() {
let form = layout_xml(&template(40)).unwrap();
@@ -5599,6 +5692,376 @@ fn clear_password_values_clears_static_xfa_password_fields() {
assert!(!packets.xdp.contains("hunter2"), "{}", packets.xdp);
}
/// #3910: `<breakBefore target="…" targetType="pageArea"/>`, `<breakAfter target="…"/>` and
/// `<break before="pageArea" beforeTarget="…"/>` switch to the named `pageArea` master (including
/// landscape masters after unbounded portrait masters) and give sections on that master its full
/// content-area width.
#[test]
fn named_page_area_breaks_switch_between_portrait_and_landscape_masters() {
let xml = r##"<template xmlns="http://www.xfa.org/schema/xfa-template/3.3/">
<subform name="form1" layout="tb">
<pageSet>
<pageArea name="Page1" id="PA1">
<contentArea x="25mm" y="44.45mm" w="172.5mm" h="232.55mm"/>
<medium stock="a4" short="210mm" long="297mm"/>
</pageArea>
<pageArea name="Page2" id="PA2">
<contentArea x="25mm" y="31.75mm" w="172.5mm" h="245.25mm"/>
<medium stock="a4" short="210mm" long="297mm"/>
</pageArea>
<pageArea name="Page3" id="PA3">
<contentArea x="25mm" y="28.575mm" w="259.5mm" h="161.875mm"/>
<medium stock="a4" short="210mm" long="297mm" orientation="landscape"/>
</pageArea>
</pageSet>
<subform name="intro" layout="tb">
<field name="f1" w="150mm" h="20mm"><ui><textEdit/></ui></field>
</subform>
<subform name="wide_flow" layout="tb">
<breakBefore target="Page3" targetType="pageArea" startNew="1"/>
<field name="f_wide1" w="240mm" h="100mm"><ui><textEdit/></ui></field>
<field name="f_wide2" w="240mm" h="100mm"><ui><textEdit/></ui></field>
</subform>
<subform name="back_portrait" layout="tb">
<breakBefore target="Page2" targetType="pageArea" startNew="1"/>
<field name="f_p2" w="160mm" h="20mm"><ui><textEdit/></ui></field>
</subform>
<subform name="wide_positioned" w="250mm" h="50mm">
<break before="pageArea" beforeTarget="#PA3" after="pageArea" afterTarget="Page1"/>
<field name="f_pos" x="200mm" y="5mm" w="45mm" h="15mm"><ui><textEdit/></ui></field>
</subform>
<subform name="outro" layout="tb">
<field name="f_end" w="120mm" h="20mm"><ui><textEdit/></ui></field>
</subform>
</subform>
</template>"##;
let form = layout_xml(xml).unwrap();
// Pages:
// 0: Page1 (portrait) — intro
// 1: Page3 (landscape) — wide_flow part 1 (f_wide1)
// 2: Page3 (landscape) — wide_flow overflow (f_wide2 stays on Page3)
// 3: Page2 (portrait) — back_portrait
// 4: Page3 (landscape) — wide_positioned (via #PA3)
// 5: Page1 (portrait) — outro (afterTarget="Page1")
assert_eq!(form.pages.len(), 6, "expected 6 pages, got {}", form.pages.len());
let is_landscape = |p: &Page| p.width > p.height && (p.width - 841.89).abs() < 1.0 && (p.height - 595.28).abs() < 1.0;
let is_portrait = |p: &Page| p.height > p.width && (p.width - 595.28).abs() < 1.0 && (p.height - 841.89).abs() < 1.0;
assert!(is_portrait(&form.pages[0]), "page 1 is Page1 portrait: {:?}", (form.pages[0].width, form.pages[0].height));
assert!(is_landscape(&form.pages[1]), "page 2 is Page3 landscape: {:?}", (form.pages[1].width, form.pages[1].height));
assert!(is_landscape(&form.pages[2]), "page 3 overflow stays on Page3 landscape: {:?}", (form.pages[2].width, form.pages[2].height));
assert!(is_portrait(&form.pages[3]), "page 4 switches to Page2 portrait: {:?}", (form.pages[3].width, form.pages[3].height));
assert!(is_landscape(&form.pages[4]), "page 5 positioned subform switches to #PA3 landscape");
assert!(is_portrait(&form.pages[5]), "page 6 afterTarget switches back to Page1 portrait");
// Wide fields on Page3 keep their full 240mm (~680.3pt) width rather than being clamped to
// Page1's 172.5mm (~489pt) portrait content area.
let widget_w = |page: usize, name: &str| -> f64 {
form.pages[page]
.items
.iter()
.find_map(|it| match it {
Item::Widget(w) if w.name == name => Some(w.rect.w),
_ => None,
})
.unwrap_or(0.0)
};
assert!(widget_w(1, "f_wide1") > 670.0, "f_wide1 width on landscape page: {}", widget_w(1, "f_wide1"));
assert!(widget_w(2, "f_wide2") > 670.0, "f_wide2 width on landscape overflow page: {}", widget_w(2, "f_wide2"));
let pos_right = form.pages[4]
.items
.iter()
.find_map(|it| match it {
Item::Widget(w) if w.name == "f_pos" => Some(w.rect.x + w.rect.w),
_ => None,
})
.unwrap_or(0.0);
assert!(pos_right > 600.0, "f_pos at x=200mm on landscape page is not clipped: {pos_right}");
// When the very first subform targets Page3, page 1 itself uses Page3 without an extra blank page,
// `<overflow target="…"/>` directs overflow pages to a named master, and `<breakAfter target="…"/>`
// switches the following page master.
let first_landscape = r##"<template xmlns="http://www.xfa.org/schema/xfa-template/3.3/">
<subform name="form1" layout="tb">
<pageSet>
<pageArea name="Page1" id="PA1"><contentArea x="25mm" y="25mm" w="160mm" h="247mm"/><medium stock="a4" short="210mm" long="297mm"/></pageArea>
<pageArea name="Page3" id="PA3"><contentArea x="25mm" y="25mm" w="247mm" h="160mm"/><medium stock="a4" short="210mm" long="297mm" orientation="landscape"/></pageArea>
</pageSet>
<subform name="first" layout="tb">
<breakBefore target="#pageSet.Page3[0]" targetType="pageArea" startNew="1"/>
<overflow target="pageSet.#PA1"/>
<breakAfter target="Page3" targetType="pageArea"/>
<field name="f1" w="220mm" h="100mm"><ui><textEdit/></ui></field>
<field name="f2" w="150mm" h="100mm"><ui><textEdit/></ui></field>
</subform>
<subform name="after" layout="tb">
<field name="f3" w="220mm" h="20mm"><ui><textEdit/></ui></field>
</subform>
</subform>
</template>"##;
let first_form = layout_xml(first_landscape).unwrap();
assert_eq!(first_form.pages.len(), 3);
assert!(is_landscape(&first_form.pages[0]), "first page switched to Page3 landscape");
assert!(is_portrait(&first_form.pages[1]), "overflow target switched page 2 to PA1 portrait");
assert!(is_landscape(&first_form.pages[2]), "breakAfter target switched page 3 back to Page3 landscape");
}
/// An `overflow` target applies while its subform is laid out (XFA 3.3, "Break on Overflow").
/// It must not stay selected for a later sibling's untargeted break: that break keeps the
/// previous master, which is the first eligible area or an explicit `breakBefore` /
/// `breakAfter` target. A nested overflow ends with its subform, while an ancestor overflow
/// that is still open keeps applying, and a descendant's explicit break still sticks.
#[test]
fn overflow_target_does_not_steer_a_later_untargeted_break() {
fn master(page: &Page) -> &'static str {
match (page.width.round() as i64, page.height.round() as i64) {
(200, 400) => "Body",
(180, 360) => "Overflow",
(150, 300) => "Special",
_ => "other",
}
}
let field = |name: &str, h: &str| format!(r#"<field name="{name}" w="40pt" h="{h}"><ui><textEdit/></ui></field>"#);
let kept = field("kept", "20pt");
let a = field("a", "80pt");
let b = field("b", "80pt");
let after = field("after", "20pt");
let inner = field("inner", "20pt");
let assert_layout = |label: &str, body: &str, masters: &[&str], fields: &[(&str, usize)]| {
let xml = format!(
r#"<template><subform layout="tb"><pageSet>
<pageArea name="Body"><contentArea x="10pt" y="10pt" w="100pt" h="100pt"/><medium short="200pt" long="400pt"/></pageArea>
<pageArea name="Overflow"><contentArea x="12pt" y="10pt" w="100pt" h="100pt"/><medium short="180pt" long="360pt"/></pageArea>
<pageArea name="Special"><contentArea x="14pt" y="10pt" w="100pt" h="100pt"/><medium short="150pt" long="300pt"/></pageArea>
</pageSet>{body}</subform></template>"#
);
let form = layout_xml(&xml).unwrap();
let got: Vec<&str> = form.pages.iter().map(master).collect();
assert_eq!(got, masters, "{label}");
for (name, page) in fields {
let found = form.pages.iter().position(|p| widgets(p).iter().any(|w| w.name == *name));
assert_eq!(found, Some(*page), "{label}: {name}");
}
assert!(form.warnings.is_empty(), "{label}: {:?}", form.warnings);
};
// Nothing overflowed, so the target never applies. The sibling's plain page break stays on Body.
assert_layout(
"unused overflow target",
&format!(
r#"<subform name="ov" layout="tb"><overflow target="Overflow"/>{kept}</subform><subform name="next" layout="tb"><breakBefore targetType="pageArea"/>{after}</subform>"#
),
&["Body", "Body"],
&[("kept", 0), ("after", 1)],
);
// The overflowing fragment uses Overflow. The sibling's untargeted break does not.
assert_layout(
"taken overflow target",
&format!(
r#"<subform name="ov" layout="tb"><overflow target="Overflow"/>{a}{b}</subform><subform name="next" layout="tb"><breakBefore targetType="pageArea"/>{after}</subform>"#
),
&["Body", "Overflow", "Body"],
&[("a", 0), ("b", 1), ("after", 2)],
);
// This subform's own breakBefore is what later untargeted breaks keep.
assert_layout(
"breakBefore survives an unused overflow target",
&format!(
r#"<subform name="ov" layout="tb"><breakBefore target="Special"/><overflow target="Overflow"/>{kept}</subform><subform name="next" layout="tb"><breakBefore targetType="pageArea"/>{after}</subform>"#
),
&["Special", "Special"],
&[("kept", 0), ("after", 1)],
);
assert_layout(
"breakBefore survives a taken overflow target",
&format!(
r#"<subform name="ov" layout="tb"><breakBefore target="Special"/><overflow target="Overflow"/>{a}{b}</subform><subform name="next" layout="tb"><breakBefore targetType="pageArea"/>{after}</subform>"#
),
&["Special", "Overflow", "Special"],
&[("a", 0), ("b", 1), ("after", 2)],
);
// An untargeted breakAfter is not an overflow, so it must not adopt the overflow master.
assert_layout(
"untargeted breakAfter",
&format!(
r#"<subform name="ov" layout="tb"><overflow target="Overflow"/><breakAfter targetType="pageArea"/>{kept}</subform><subform name="next" layout="tb">{after}</subform>"#
),
&["Body", "Body"],
&[("kept", 0), ("after", 1)],
);
// An explicit breakAfter still selects its own master after the overflow target is put back.
assert_layout(
"explicit breakAfter",
&format!(
r#"<subform name="ov" layout="tb"><overflow target="Overflow"/><breakAfter target="Special"/>{kept}</subform><subform name="next" layout="tb">{after}</subform>"#
),
&["Body", "Special"],
&[("kept", 0), ("after", 1)],
);
// A descendant's explicit break sticks, including when it names the same master as the overflow.
assert_layout(
"descendant break names the overflow master",
&format!(
r#"<subform name="chapter" layout="tb"><overflow target="Overflow"/><subform name="section" layout="tb"><breakBefore target="Overflow"/>{inner}</subform></subform><subform name="next" layout="tb"><breakBefore targetType="pageArea"/>{after}</subform>"#
),
&["Overflow", "Overflow"],
&[("inner", 0), ("after", 1)],
);
// The inner overflow ends with that subform. The outer one is still open, so the sibling uses it.
assert_layout(
"nested overflow yields to the ancestor",
&format!(
r#"<subform name="outer" layout="tb"><overflow target="Overflow"/><subform name="inner" layout="tb"><overflow target="Special"/>{kept}</subform><subform name="sib" layout="tb"><breakBefore targetType="pageArea"/>{after}</subform></subform>"#
),
&["Body", "Overflow"],
&[("kept", 0), ("after", 1)],
);
}
/// A discarded page master must not consume field counts or names, even for a widget too
/// small to be emitted. Earlier retained pages still own their counts and reservations.
#[test]
fn replacing_empty_page_restores_master_field_state() {
for prior_page in [false, true] {
let prior = if prior_page {
r#"<subform layout="tb"><breakAfter target="Discard"/><field name="body" w="20pt" h="20pt"><ui><textEdit/></ui></field></subform>"#
} else {
""
};
let xml = format!(
r#"<template><subform layout="tb"><pageSet>
<pageArea name="Discard"><contentArea x="10pt" y="40pt" w="200pt" h="200pt"/>
<field name="shared" w="20pt" h="20pt"><ui><textEdit/></ui></field>
<field name="shared" x="25pt" w="20pt" h="20pt"><ui><textEdit/></ui></field>
<field name="tiny" w="20pt" h="0.5pt"><ui><textEdit/></ui></field>
</pageArea>
<pageArea name="Intermediate"><contentArea x="20pt" y="40pt" w="200pt" h="200pt"/>
<field name="shared" w="20pt" h="20pt"><ui><textEdit/></ui></field>
<field name="tiny" w="20pt" h="0.5pt"><ui><textEdit/></ui></field>
</pageArea>
<pageArea name="Kept"><contentArea x="30pt" y="40pt" w="200pt" h="200pt"/>
<field name="shared" w="20pt" h="20pt"><ui><textEdit/></ui></field>
<field name="tiny" x="25pt" w="20pt" h="20pt"><ui><textEdit/></ui></field>
</pageArea>
</pageSet>{prior}
<subform layout="tb"><breakBefore target="Intermediate"/></subform>
<subform layout="tb"><breakBefore target="Kept"/><field name="last" w="20pt" h="20pt"><ui><textEdit/></ui></field></subform>
</subform></template>"#
);
let form = layout_xml(&xml).unwrap();
assert_eq!(form.pages.len(), if prior_page { 2 } else { 1 });
let actual_fields: usize = form.pages.iter().map(|p| widgets(p).len()).sum();
assert_eq!(form.fields, actual_fields, "discarded master fields must not remain counted");
let kept = widgets(form.pages.last().unwrap());
let names: Vec<&str> = kept.iter().map(|w| w.name.as_str()).collect();
assert_eq!(names, if prior_page { vec!["shared_3", "tiny_2", "last"] } else { vec!["shared", "tiny", "last"] });
assert!(form.warnings.is_empty(), "{:?}", form.warnings);
}
}
/// Updating frame geometry at a break must include ancestors whose final child crosses several
/// differently-sized masters before returning, while fixed widths keep their original geometry.
#[test]
fn flowed_frame_tracks_every_named_master_including_final_child() {
for (limits, widths, x_positions) in [
("", [100.0, 240.0, 140.0], [10.0, 30.0, 50.0]),
(r#"minW="120pt" maxW="200pt""#, [100.0, 200.0, 140.0], [10.0, 30.0, 50.0]),
(r#"w="80pt""#, [80.0; 3], [10.0; 3]),
] {
let xml = format!(
r#"<template><subform layout="tb" {limits}>
<border><edge/><fill><color value="230,230,230"/></fill></border>
<pageSet>
<pageArea name="A"><contentArea x="10pt" y="10pt" w="100pt" h="200pt"/></pageArea>
<pageArea name="B"><contentArea x="30pt" y="10pt" w="240pt" h="200pt"/></pageArea>
<pageArea name="C"><contentArea x="50pt" y="10pt" w="140pt" h="200pt"/></pageArea>
</pageSet>
<field name="first" w="20pt" h="20pt"><ui><textEdit/></ui></field>
<subform layout="tb">
<subform layout="tb"><breakBefore target="B"/><field name="second" w="20pt" h="20pt"><ui><textEdit/></ui></field></subform>
<subform layout="tb"><breakBefore target="C"/><field name="last" w="20pt" h="20pt"><ui><textEdit/></ui></field></subform>
</subform>
</subform></template>"#
);
let form = layout_xml(&xml).unwrap();
assert_eq!(form.pages.len(), 3);
for (i, page) in form.pages.iter().enumerate() {
let fills: Vec<Rect> = page.items.iter().filter_map(|it| if let Item::Fill { rect, .. } = it { Some(*rect) } else { None }).collect();
assert_eq!(fills, vec![Rect::new(x_positions[i], 10.0, widths[i], 20.0)], "page {i}, limits {limits}");
assert!(matches!(page.items.first(), Some(Item::Fill { .. })), "the fill stays below the widgets");
}
assert!(form.warnings.is_empty(), "{:?}", form.warnings);
}
}
/// A final field can move to another content area on the same page without another child
/// observing the changed cursor, and replacing the initial master must refresh open frames too.
#[test]
fn flowed_frame_tracks_content_areas_and_initial_master_replacement() {
for replace_initial in [false, true] {
let unused = if replace_initial { r#"<pageArea name="Unused"><contentArea x="5pt" y="5pt" w="50pt" h="100pt"/></pageArea>"# } else { "" };
let xml = format!(
r#"<template><subform layout="tb"><border><edge/><fill/></border><pageSet>{unused}
<pageArea name="Used">
<contentArea x="10pt" y="10pt" w="100pt" h="100pt"/>
<contentArea x="130pt" y="10pt" w="240pt" h="100pt"/>
<contentArea x="390pt" y="10pt" w="140pt" h="100pt"/>
</pageArea></pageSet>
<subform layout="tb"><breakBefore target="Used"/>
<field name="a" w="20pt" h="80pt"><ui><textEdit/></ui></field>
<field name="b" w="20pt" h="80pt"><ui><textEdit/></ui></field>
<field name="c" w="20pt" h="80pt"><ui><textEdit/></ui></field>
</subform></subform></template>"#
);
let form = layout_xml(&xml).unwrap();
assert_eq!(form.pages.len(), 1);
let fills: Vec<Rect> =
form.pages[0].items.iter().filter_map(|it| if let Item::Fill { rect, .. } = it { Some(*rect) } else { None }).collect();
assert_eq!(fills, vec![Rect::new(10.0, 10.0, 100.0, 80.0), Rect::new(130.0, 10.0, 240.0, 80.0), Rect::new(390.0, 10.0, 140.0, 80.0)]);
assert!(form.warnings.is_empty(), "{:?}", form.warnings);
}
}
/// Restarting an auto-width child must keep the available width and inset supplied by an
/// explicitly sized parent, even when the final child moves to a new content area.
#[test]
fn flowed_frame_keeps_fixed_parent_width_and_margins() {
let xml = r#"<template><subform layout="tb" w="80pt"><margin leftInset="5pt" rightInset="7pt"/>
<pageSet><pageArea>
<contentArea x="10pt" y="10pt" w="100pt" h="100pt"/>
<contentArea x="10pt" y="130pt" w="100pt" h="100pt"/>
</pageArea></pageSet>
<subform layout="tb"><border><edge/><fill/></border>
<field name="a" w="20pt" h="80pt"><ui><textEdit/></ui></field>
<field name="b" w="20pt" h="80pt"><ui><textEdit/></ui></field>
</subform></subform></template>"#;
let form = layout_xml(xml).unwrap();
assert_eq!(form.pages.len(), 1);
let fills: Vec<Rect> = form.pages[0].items.iter().filter_map(|it| if let Item::Fill { rect, .. } = it { Some(*rect) } else { None }).collect();
assert_eq!(fills, vec![Rect::new(15.0, 10.0, 68.0, 80.0), Rect::new(15.0, 130.0, 68.0, 80.0)]);
assert!(form.warnings.is_empty(), "{:?}", form.warnings);
}
/// A positioned block uses raw area moves while it splits. The next flowed sibling still
/// receives the new area's horizontal geometry, even though its enclosing border is lost.
#[test]
fn flowed_sibling_after_split_block_uses_current_area_width() {
let xml = r#"<template><subform layout="tb"><pageSet><pageArea>
<contentArea x="10pt" y="10pt" w="100pt" h="100pt"/>
<contentArea x="130pt" y="10pt" w="240pt" h="100pt"/>
</pageArea></pageSet>
<subform w="80pt" h="160pt">
<field name="a" w="20pt" h="20pt"><ui><textEdit/></ui></field>
<field name="b" y="120pt" w="20pt" h="20pt"><ui><textEdit/></ui></field>
</subform>
<field name="after" w="200pt" h="20pt"><ui><textEdit/></ui></field>
</subform></template>"#;
let form = layout_xml(xml).unwrap();
assert_eq!(form.pages.len(), 1);
let after = widgets(&form.pages[0]).into_iter().find(|w| w.name == "after").unwrap();
assert_eq!((after.rect.x, after.rect.w), (130.0, 200.0));
assert!(form.warnings.is_empty(), "{:?}", form.warnings);
}
/// The data a radio group writes for its selected on state compares every button's state before
/// any `/PCOn`: with states `/0` `/1` and `/PCOn` items `1` `2`, the state `1` is the second
/// button, whose item is `2` (it used to match the first button's `/PCOn` `1` and write `1`).
+47 -9
View File
@@ -252,15 +252,24 @@ pub fn layout(rich: &RichText, rect: Rect, para: &Para, base: &Face, embed: &dyn
size: f64,
first: bool,
}
let avail = (rect.w - para.margin_left - para.margin_right).max(1.0);
// Every paragraph's words first (the hang depends on the widest glyph), in order, so
// embedded fields share one text budget as they did paragraph by paragraph.
let mut embed_left = MAX_EMBEDDED;
let paragraphs: Vec<Vec<Word>> = rich.paragraphs.iter().map(|p| words(&p.runs, base, embed, &mut embed_left)).collect();
// A negative textIndent is a hanging indent: the first line starts left of the others. It
// never starts left of the box, so the others move in to make room, as other viewers lay
// such labels out; never so far that a line after the first has no room for the widest
// glyph, however wide the hang.
let widest = paragraphs.iter().flatten().map(widest_glyph).fold(1.0, f64::max);
let hang = (-para.text_indent).min((rect.w - para.margin_right - widest).max(0.0));
let (margin_left, first_indent) = indents(para, hang);
let avail = (rect.w - margin_left - para.margin_right).max(1.0);
let mut lines: Vec<(Line, Option<HAlign>)> = Vec::new();
let mut total = 0.0;
let mut embed_left = MAX_EMBEDDED;
for (pi, p) in rich.paragraphs.iter().enumerate() {
let ws = words(&p.runs, base, embed, &mut embed_left);
for (pi, (p, ws)) in rich.paragraphs.iter().zip(paragraphs).enumerate() {
let mut line = Line { words: Vec::new(), width: 0.0, size: base.size, first: true };
let mut first_in_para = true;
let indent = |first: bool| if first { para.text_indent.max(0.0) } else { 0.0 };
let indent = |first: bool| if first { first_indent } else { 0.0 };
for w in ws {
// A word fits when what it draws does: the spaces after it would end the line. Spaces
// alone draw nothing, so they always stay on the line (keeping their width, so a word
@@ -323,7 +332,7 @@ pub fn layout(rich: &RichText, rect: Rect, para: &Para, base: &Face, embed: &dyn
let mut spans = Vec::new();
let mut y = start_y + para.space_above;
for ((line, align), lh) in lines.into_iter().zip(heights) {
let indent = if line.first { para.text_indent.max(0.0) } else { 0.0 };
let indent = if line.first { first_indent } else { 0.0 };
// Trailing spaces don't count for alignment: those of the last word with ink, and any
// words of spaces alone after it.
let mut trailing = 0.0;
@@ -335,7 +344,7 @@ pub fn layout(rich: &RichText, rect: Rect, para: &Para, base: &Face, embed: &dyn
}
}
let used = (line.width - trailing).max(0.0);
let mut x = rect.x + para.margin_left + indent;
let mut x = rect.x + margin_left + indent;
x += match align.unwrap_or(para.h_align) {
HAlign::Left | HAlign::Justify => 0.0,
HAlign::Center => ((avail - indent - used) / 2.0).max(0.0),
@@ -368,11 +377,40 @@ pub fn layout(rich: &RichText, rect: Rect, para: &Para, base: &Face, embed: &dyn
/// The width `rich` takes with no line wrapped (its longest paragraph, with the paragraph's
/// margins and first-line indent): how wide a box without an explicit width grows.
pub fn natural_width(rich: &RichText, para: &Para, base: &Face, embed: &dyn Fn(&str, usize) -> String) -> f64 {
let indent = para.text_indent.max(0.0);
// Unwrapped, every line is a paragraph's first line; the hang is as wide as asked, since the
// box will be as wide as this.
let (margin_left, first_indent) = indents(para, -para.text_indent);
let mut embed_left = MAX_EMBEDDED;
let widest =
rich.paragraphs.iter().map(|p| words(&p.runs, base, embed, &mut embed_left).iter().map(|w| w.width).sum::<f64>()).fold(0.0, f64::max);
(para.margin_left + indent + widest + para.margin_right).max(0.0)
(margin_left + first_indent + widest + para.margin_right).max(0.0)
}
/// The width of the widest glyph `w` draws (spaces draw nothing).
fn widest_glyph(w: &Word) -> f64 {
let mut glyph = String::new();
w.text
.chars()
.filter(|c| *c != ' ')
.map(|c| {
glyph.clear();
glyph.push(c);
w.face.width(&glyph)
})
.fold(0.0, f64::max)
}
/// The left margin of a paragraph's lines and where its first line starts from them, for a
/// hanging indent of `hang` (the negative textIndent, as far as the box allows): the first line
/// never starts left of the box, so the other lines move in to make room.
/// Without a negative textIndent the margins are as given (a negative marginLeft still moves
/// every line left) and the first line's indent is the textIndent, at least 0.
fn indents(para: &Para, hang: f64) -> (f64, f64) {
if para.text_indent >= 0.0 || para.text_indent.is_nan() {
return (para.margin_left, para.text_indent.max(0.0));
}
let margin_left = para.margin_left.max(hang);
(margin_left, para.text_indent.max(-margin_left))
}
/// Height `rich` needs at `width` (for boxes without an explicit height).
+4 -1
View File
@@ -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. |
+6 -6
View File
@@ -5453,8 +5453,8 @@ milestone = "M12"
status = "partial"
commands = ["file.open"]
tools = ["doc_open", "doc_info", "form_fields", "form_fill", "js_run", "form_focus"]
evidence = ["crates/xfa/src/tests.rs::a_draw_turns_counter_clockwise_about_its_anchor", "crates/xfa/src/tests.rs::layout_places_captions_fields_and_sizes_containers_to_their_content", "crates/xfa/src/tests.rs::tables_break_across_pages_and_repeat_their_header_row", "crates/xfa/src/tests.rs::rendering_into_the_pdf_replaces_the_placeholder_page_and_adds_fields", "crates/engine/src/tests.rs::dynamic_xfa_forms_are_laid_out_on_open_filled_and_saved_incrementally", "crates/automation/tests/it/automation.rs::dynamic_xfa_forms_open_render_fill_and_save_through_tools", "crates/ui-egui/tests/it/xfa.rs::a_dynamic_xfa_form_is_laid_out_and_filled", "crates/xfa/src/tests.rs::nested_width_less_subforms_lay_out_in_polynomial_time", "crates/js/src/tests.rs::instance_managers_add_remove_and_count", "crates/xfa/src/tests.rs::the_form_tree_carries_values_presence_instances_and_the_events", "crates/engine/src/tests.rs::xfa_scripts_initialize_calculate_validate_toggle_and_add_rows", "crates/engine/src/tests.rs::xfa_date_arithmetic_reads_the_date_as_its_display_picture_shows_it", "crates/automation/tests/it/automation.rs::xfa_scripts_run_for_buttons_and_field_changes_through_tools", "crates/ui-egui/tests/it/xfa.rs::xfa_buttons_run_their_scripts_in_the_app", "crates/engine/src/tests.rs::hostile_xfa_open_scripts_are_merged_capped_kept_from_printing_and_noted", "crates/engine/src/tests.rs::runaway_xfa_calculations_at_open_end_quickly_with_a_report", "crates/ui-egui/tests/it/xfa.rs::a_form_whose_scripts_were_turned_off_at_open_says_so", "crates/ui-egui/tests/it/xfa.rs::scripts_turned_off_by_a_click_bring_a_closed_notice_bar_back", "crates/automation/tests/it/automation.rs::doc_info_says_when_a_runaway_script_turned_the_forms_scripts_off", "crates/xfa/src/tests.rs::the_live_form_of_nested_repeating_subforms_stops_at_its_node_budget", "crates/xfa/src/tests.rs::data_ops_of_one_event_are_one_datasets_rewrite", "crates/xfa/src/tests.rs::choice_lists_signatures_passwords_and_pictures_become_fields_and_images", "crates/xfa/src/tests.rs::choice_values_come_from_the_data_as_saved_values_and_several_for_lists", "crates/xfa/src/tests.rs::pictures_are_sized_from_their_headers_and_hostile_ones_are_refused_unallocated", "crates/engine/src/tests.rs::xfa_choice_lists_signature_and_picture_fields_open_fill_script_and_save", "crates/xfa/src/tests.rs::repeating_subforms_inside_positioned_content_get_their_instances", "crates/engine/src/tests.rs::xfa_rows_in_areas_are_laid_out_read_calculated_and_written_where_adobe_binds_them", "crates/xfa/src/tests.rs::page_area_without_occur_serves_every_body_page", "apps/pdfcraft-cli/tests/it/xfa.rs::info_reports_the_laid_out_pages_and_fields", "apps/pdfcraft-cli/tests/it/xfa.rs::text_reads_the_layout_including_a_page_absent_from_the_placeholder", "apps/pdfcraft-cli/tests/it/xfa.rs::render_matches_the_engine_layout_on_the_second_page", "apps/pdfcraft-cli/tests/it/xfa.rs::a_laid_out_form_keeps_the_original_copy_permissions", "crates/engine/src/tests.rs::filling_growable_xfa_text_reflows_and_undo_restores_the_layout", "crates/engine/src/tests.rs::xfa_text_growth_refreshes_widget_geometry_but_fixed_height_fields_keep_their_widgets", "crates/automation/tests/it/automation.rs::growable_xfa_text_paginates_after_fill_save_and_print", "crates/engine/src/tests.rs::an_xfa_script_that_fails_partway_keeps_what_it_changed_before_the_error", "crates/engine/src/tests.rs::repeated_xfa_print_buttons_run_their_click_script", "crates/automation/tests/it/automation.rs::repeated_xfa_print_buttons_work_through_tools_and_after_reopen", "crates/xfa/src/tests.rs::rich_text_max_length_reaches_the_field_and_layout", "crates/automation/tests/it/automation.rs::xfa_rich_text_max_length_is_reported_and_enforced_through_tools", "crates/xfa/src/tests.rs::bmp_and_tiff_pictures_are_decoded_and_drawn", "crates/engine/src/tests.rs::active_xfa_does_not_run_pdf_container_scripts_but_keeps_requested_alerts", "crates/engine/src/tests.rs::active_xfa_without_template_scripts_does_not_initialize_pdf_fallback_scripts", "crates/engine/src/tests.rs::inactive_xfa_and_ordinary_pdfs_keep_document_helpers_and_alerts", "crates/automation/tests/it/automation.rs::active_xfa_skips_container_fallback_scripts_after_save_and_reopen", "crates/xfa/src/tests.rs::laying_a_form_out_takes_off_the_usage_rights_it_voids", "crates/engine/src/tests.rs::a_dynamic_xfa_form_is_saved_without_the_usage_rights_its_layout_voided", "crates/xfa/src/tests.rs::faces_measure_text_at_their_standard_14_widths", "crates/xfa/src/tests.rs::rich_text_links_keep_their_address", "crates/xfa/src/tests.rs::links_in_rich_text_become_link_annotations_one_per_line", "crates/xfa/src/tests.rs::a_links_pieces_share_one_address", "crates/xfa/src/tests.rs::a_rule_between_two_pieces_of_a_link_keeps_them_apart", "crates/xfa/src/tests.rs::links_to_anything_but_web_and_email_addresses_stay_plain_text", "crates/automation/tests/it/automation.rs::links_in_xfa_rich_text_are_listed_through_tools", "crates/xfa/src/testsLine truncated
notes = "A draw placed by position turns about its anchor (rotate); fields, subforms and draws in a flow don't. Active XFA layout skips PDF-container document-script initialization for the Acrobat console/field context, so fallback-viewer scripts do not run there. Scripts remain in the file/listing; explicit console/field and XFA alerts still run. Ordinary PDF, static XFA and unlaid-out shells keep document scripts; static-conversion undo restores the XFA policy. Changed growable multiline text (no fixed h) reflows from final datasets after edits, with or without scripts; pages/widgets refresh and undo/redo, save/reopen and print retain all text. Oversized text still uses the existing read-only page-text fallback with a warning; fixed-height fields do not reflow. Repeated page-master buttons resolve their own PDF field to the shared XFA click script; the numPages-based print script requests printing from every copy, including after save/reopen (#2572). Rich-text exData/maxLength is carried into AcroForm MaxLen, reported by form_fields and enforced by form_fill (Unicode characters); limits and accepted values survive save/reopen (#2570). laid out from the template on open by the xfa crate (prototypes first: use/usehref references to #id or #som(...) in the same template, as Designer style sheets write them, are merged in by the XFA 3.3 chapter 6 rules, the element's own attributes and children winning, with loops cut and chain length, nesting, look-up and merge work and growth capped, each with a warning; prototypes in other documents are not followed, and SOM references cover names, #class and [n] only; positioned, tb, lr-tb, table/row, page masters (a page area with no occur repeats without limit, one with occur max=1 is used once, one with occur min=1 the body never reached gets a page after the body, as Acrobat Pro does on a synthetic form), breaks, repeated header rows, borders and fills of flowed subforms (a page break between their children gives each page's part a closed border, the margins repeated at the cut, as measured on a synthetic form in another viewer, and a child's own page break breaks them the same way; one holding an item that doesn't fit on its page, cut across pages or placed past the content area's bottom, is drawn without its border, with a layout warning), captions (in their field's font unless they name their own), objects shown only on screen or only in print (relevant -print and +print, inside containers too: fields by their annotation flags, draws in optional content groups whose view and print usage say so; PdfCraft's own printing doesn't yet apply a layer's print usage, so a screen-only or print-only draw prints as it shows on screen, and a hidden object relevant prints isn't laid out), rounded and inverted border corners (XFA 3.3 p. 38 gives the order of edges and corners and says the last one listed is reused for the sides not listed; readers draw an unlisted edge or corner from the one on the same side instead, one serving all four, two alternating, three reusing the second for the bottom-left; edges already followed the readers, and corners now do too), rich text (its http, https and mailto links clickable), JPEG/PNG/GIF/BMP/TIFF images) into real pages and AcroForm fields (text, password, date with AFDate formats (a date one of the edit picture's patterns reads is kept in its first, and in the data as an ISO date; text none of them reads, ISO text included, is kept and shown as typed rather than refused, as another viewer keeps it on a synthetic form; shown through the field's display picture (weekday and month names included) and typed in its edit picture's pattern, as another viewer shows a date on a synthetic form, a two-digit year in that pattern read with XFA's century split of 30 (00 to 29 are 2000 to 2029); the field holds its date in the edit pattern whether it came from the data, the template's default or typing, so it never reads two ways; a field with no picture at all shows yyyy-mm-dd, where that viewer uses its locale's default), check boxes and radio groups (each box placed by its field's margins, caption and paragraph alignment as measured on two synthetic forms in another viewer: with no caption at the right of the content area, beside a reserved caption where the alignment puts it, and a caption without a reserve taking the rest of the field; a check box's own margin larger than the box draws a bigger box there, which isn't copied), drop-downs and list boxes with shown/saved item pairs and multi-select, signature fields (each named by its SOM path, under a generated field for each step above it, so that another viewer, which lays the form out again, finds a signature made here, as seen on a synthetic form, and a box signed here keeps its signature, and that name, when a script lays the form out again; a box whose path, or a part of it, the file already gives another field keeps its own name, and its signature isn't found there yet), image fields showing Line truncated
evidence = ["crates/xfa/src/tests.rs::a_draw_turns_counter_clockwise_about_its_anchor", "crates/xfa/src/tests.rs::layout_places_captions_fields_and_sizes_containers_to_their_content", "crates/xfa/src/tests.rs::tables_break_across_pages_and_repeat_their_header_row", "crates/xfa/src/tests.rs::rendering_into_the_pdf_replaces_the_placeholder_page_and_adds_fields", "crates/engine/src/tests.rs::dynamic_xfa_forms_are_laid_out_on_open_filled_and_saved_incrementally", "crates/automation/tests/it/automation.rs::dynamic_xfa_forms_open_render_fill_and_save_through_tools", "crates/ui-egui/tests/it/xfa.rs::a_dynamic_xfa_form_is_laid_out_and_filled", "crates/xfa/src/tests.rs::nested_width_less_subforms_lay_out_in_polynomial_time", "crates/js/src/tests.rs::instance_managers_add_remove_and_count", "crates/xfa/src/tests.rs::the_form_tree_carries_values_presence_instances_and_the_events", "crates/engine/src/tests.rs::xfa_scripts_initialize_calculate_validate_toggle_and_add_rows", "crates/engine/src/tests.rs::xfa_date_arithmetic_reads_the_date_as_its_display_picture_shows_it", "crates/automation/tests/it/automation.rs::xfa_scripts_run_for_buttons_and_field_changes_through_tools", "crates/ui-egui/tests/it/xfa.rs::xfa_buttons_run_their_scripts_in_the_app", "crates/engine/src/tests.rs::hostile_xfa_open_scripts_are_merged_capped_kept_from_printing_and_noted", "crates/engine/src/tests.rs::runaway_xfa_calculations_at_open_end_quickly_with_a_report", "crates/ui-egui/tests/it/xfa.rs::a_form_whose_scripts_were_turned_off_at_open_says_so", "crates/ui-egui/tests/it/xfa.rs::scripts_turned_off_by_a_click_bring_a_closed_notice_bar_back", "crates/automation/tests/it/automation.rs::doc_info_says_when_a_runaway_script_turned_the_forms_scripts_off", "crates/xfa/src/tests.rs::the_live_form_of_nested_repeating_subforms_stops_at_its_node_budget", "crates/xfa/src/tests.rs::data_ops_of_one_event_are_one_datasets_rewrite", "crates/xfa/src/tests.rs::choice_lists_signatures_passwords_and_pictures_become_fields_and_images", "crates/xfa/src/tests.rs::choice_values_come_from_the_data_as_saved_values_and_several_for_lists", "crates/xfa/src/tests.rs::pictures_are_sized_from_their_headers_and_hostile_ones_are_refused_unallocated", "crates/engine/src/tests.rs::xfa_choice_lists_signature_and_picture_fields_open_fill_script_and_save", "crates/xfa/src/tests.rs::repeating_subforms_inside_positioned_content_get_their_instances", "crates/engine/src/tests.rs::xfa_rows_in_areas_are_laid_out_read_calculated_and_written_where_adobe_binds_them", "crates/xfa/src/tests.rs::page_area_without_occur_serves_every_body_page", "apps/pdfcraft-cli/tests/it/xfa.rs::info_reports_the_laid_out_pages_and_fields", "apps/pdfcraft-cli/tests/it/xfa.rs::text_reads_the_layout_including_a_page_absent_from_the_placeholder", "apps/pdfcraft-cli/tests/it/xfa.rs::render_matches_the_engine_layout_on_the_second_page", "apps/pdfcraft-cli/tests/it/xfa.rs::a_laid_out_form_keeps_the_original_copy_permissions", "crates/engine/src/tests.rs::filling_growable_xfa_text_reflows_and_undo_restores_the_layout", "crates/engine/src/tests.rs::xfa_text_growth_refreshes_widget_geometry_but_fixed_height_fields_keep_their_widgets", "crates/automation/tests/it/automation.rs::growable_xfa_text_paginates_after_fill_save_and_print", "crates/engine/src/tests.rs::an_xfa_script_that_fails_partway_keeps_what_it_changed_before_the_error", "crates/engine/src/tests.rs::repeated_xfa_print_buttons_run_their_click_script", "crates/automation/tests/it/automation.rs::repeated_xfa_print_buttons_work_through_tools_and_after_reopen", "crates/xfa/src/tests.rs::rich_text_max_length_reaches_the_field_and_layout", "crates/automation/tests/it/automation.rs::xfa_rich_text_max_length_is_reported_and_enforced_through_tools", "crates/xfa/src/tests.rs::bmp_and_tiff_pictures_are_decoded_and_drawn", "crates/engine/src/tests.rs::active_xfa_does_not_run_pdf_container_scripts_but_keeps_requested_alerts", "crates/engine/src/tests.rs::active_xfa_without_template_scripts_does_not_initialize_pdf_fallback_scripts", "crates/engine/src/tests.rs::inactive_xfa_and_ordinary_pdfs_keep_document_helpers_and_alerts", "crates/automation/tests/it/automation.rs::active_xfa_skips_container_fallback_scripts_after_save_and_reopen", "crates/xfa/src/tests.rs::laying_a_form_out_takes_off_the_usage_rights_it_voids", "crates/engine/src/tests.rs::a_dynamic_xfa_form_is_saved_without_the_usage_rights_its_layout_voided", "crates/xfa/src/tests.rs::faces_measure_text_at_their_standard_14_widths", "crates/xfa/src/tests.rs::rich_text_links_keep_their_address", "crates/xfa/src/tests.rs::links_in_rich_text_become_link_annotations_one_per_line", "crates/xfa/src/tests.rs::a_links_pieces_share_one_address", "crates/xfa/src/tests.rs::a_rule_between_two_pieces_of_a_link_keeps_them_apart", "crates/xfa/src/tests.rs::links_to_anything_but_web_and_email_addresses_stay_plain_text", "crates/automation/tests/it/automation.rs::links_in_xfa_rich_text_are_listed_through_tools", "crates/xfa/src/testsLine truncated
notes = "A draw placed by position turns about its anchor (rotate); fields, subforms and draws in a flow don't. Active XFA layout skips PDF-container document-script initialization for the Acrobat console/field context, so fallback-viewer scripts do not run there. Scripts remain in the file/listing; explicit console/field and XFA alerts still run. Ordinary PDF, static XFA and unlaid-out shells keep document scripts; static-conversion undo restores the XFA policy. Changed growable multiline text (no fixed h) reflows from final datasets after edits, with or without scripts; pages/widgets refresh and undo/redo, save/reopen and print retain all text. A field change, reset or picture whose scripts or data lay the form out again (a section shown that needs another page, or hidden again) rebuilds the pages and fields the same way, whether or not the page count changed, so the view, undo/redo and save see the new pages. Oversized text still uses the existing read-only page-text fallback with a warning; fixed-height fields do not reflow. Repeated page-master buttons resolve their own PDF field to the shared XFA click script; the numPages-based print script requests printing from every copy, including after save/reopen (#2572). Rich-text exData/maxLength is carried into AcroForm MaxLen, reported by form_fields and enforced by form_fill (Unicode characters); limits and accepted values survive save/reopen (#2570). laid out from the template on open by the xfa crate (prototypes first: use/usehref references to #id or #som(...) in the same template, as Designer style sheets write them, are merged in by the XFA 3.3 chapter 6 rules, the element's own attributes and children winning, with loops cut and chain length, nesting, look-up and merge work and growth capped, each with a warning; prototypes in other documents are not followed, and SOM references cover names, #class and [n] only; positioned, tb, lr-tb, table/row, page masters (a page area with no occur repeats without limit, one with occur max=1 is used once, one with occur min=1 the body never reached gets a page after the body, as Acrobat Pro does on a synthetic form), breaks, repeated header rows, borders and fills of flowed subforms (a page break between their children gives each page's part a closed border, the margins repeated at the cut, as measured on a synthetic form in another viewer, and a child's own page break breaks them the same way; one holding an item that doesn't fit on its page, cut across pages or placed past the content area's bottom, is drawn without its border, with a layout warning), captions (in their field's font unless they name their own), objects shown only on screen or only in print (relevant -print and +print, inside containers too: fields by their annotation flags, draws in optional content groups whose view and print usage say so; PdfCraft's own printing doesn't yet apply a layer's print usage, so a screen-only or print-only draw prints as it shows on screen, and a hidden object relevant prints isn't laid out), rounded and inverted border corners (XFA 3.3 p. 38 gives the order of edges and corners and says the last one listed is reused for the sides not listed; readers draw an unlisted edge or corner from the one on the same side instead, one serving all four, two alternating, three reusing the second for the bottom-left; edges already followed the readers, and corners now do too), rich text (its http, https and mailto links clickable), JPEG/PNG/GIF/BMP/TIFF images) into real pages and AcroForm fields (text, password, date with AFDate formats (a date one of the edit picture's patterns reads is kept in its first, and in the data as an ISO date; text none of them reads, ISO text included, is kept and shown as typed rather than refused, as another viewer keeps it on a synthetic form; shown through the field's display picture (weekday and month names included) and typed in its edit picture's pattern, as another viewer shows a date on a synthetic form, a two-digit year in that pattern read with XFA's century split of 30 (00 to 29 are 2000 to 2029); the field holds its date in the edit pattern whether it came from the data, the template's default or typing, so it never reads two ways; a field with no picture at all shows yyyy-mm-dd, where that viewer uses its locale's default), check boxes and radio groups (each box placed by its field's margins, caption and paragraph alignment as measured on two synthetic forms in another viewer: with no caption at the right of the content area, beside a reserved caption where the alignment puts it, and a caption without a reserve taking the rest of the field; a check box's own margin larger than the box draws a bigger box there, which isn't copied), drop-downs and list boxes with shown/saved item pairs and multi-select, signature fields (each named by its SOM path, under a generated field for each step above it, so that another viewer, which lays the form out again, finds a signature made here, as seen onLine truncated
[[feature]]
id = "form.xfa-formcalc"
@@ -8676,11 +8676,11 @@ title = "Marks and bleeds when printing"
area = "L"
tier = "P2"
milestone = "M11"
status = "planned"
status = "partial"
commands = []
tools = []
evidence = []
notes = ""
tools = ["doc_print"]
evidence = ["crates/engine/src/tests/print_marks.rs::printer_marks_go_on_the_printed_sheets_and_not_the_document", "crates/automation/tests/it/automation.rs::printing_with_printer_marks_through_tools"]
notes = "doc_print marks (all, trim, bleed, registration, color_bars, page_info) and marks_weight: the marks of Add printer marks, drawn around each printed page on the print copy only, so the document is never changed; marks it already has print once. With a one-page-a-sheet layout (fit, actual, shrink, custom); the page is widened for them, so fit shrinks it to make room. Still missing against Acrobat: the Print dialog's Marks and Bleeds panel (headless only), the mark styles, and printing them with Print as image or app-managed colour (refused, as those print pages as pictures)."
[[feature]]
id = "print.trap-presets"
+9 -3
View File
@@ -121,13 +121,19 @@ pub fn ci(_: &[String]) -> anyhow::Result<()> {
("deny", Box::new(|| deny(&[]))),
("parity", Box::new(|| crate::parity::run(&[]))),
];
for (i, (name, f)) in steps.iter().enumerate() {
// Independent steps keep running after a failure, so one run reports every failing step.
let mut failed = Vec::new();
for (name, f) in &steps {
eprintln!("\n=== ci: {name} ===");
if let Err(e) = f() {
println!("\nCI: {} passed, FAILED at `{name}`: {e:#}", i);
bail!("ci failed at `{name}`");
println!("\nCI: `{name}` FAILED: {e:#}");
failed.push(*name);
}
}
if !failed.is_empty() {
println!("\nCI: {} of {} steps passed, FAILED: {}", steps.len() - failed.len(), steps.len(), failed.join(", "));
bail!("ci failed at {}", failed.iter().map(|n| format!("`{n}`")).collect::<Vec<_>>().join(", "));
}
println!("\nCI: all {} steps passed", steps.len());
Ok(())
}
+1 -1
View File
@@ -30,7 +30,7 @@ const COMMANDS: &[(&str, &str, Command)] = &[
("deny", "Dependency licences, bans, sources and advisories (deny.toml; needs cargo-deny)", gates::deny),
(
"ci",
"fmt --check, clippy -D warnings, the CLI without default features, test, i18n-report, layers, wasm, license-check, deny, parity (stops at first failure)",
"fmt --check, clippy -D warnings, the CLI without default features, test, i18n-report, layers, wasm, license-check, deny, parity (runs every step, then reports each failure)",
gates::ci,
),
("test", "Workspace tests: cargo nextest (cargo test when it is missing), then doctests", gates::test),