mirror of
https://github.com/storytold/pdfcraft.git
synced 2026-11-16 04:56:40 +00:00
Merge remote-tracking branch 'upstream/main' into feat/pdf-portfolio
# Conflicts: # crates/render/src/inspect/core.rs
This commit is contained in:
Generated
+15
@@ -4592,6 +4592,7 @@ dependencies = [
|
||||
"pdfcraft-render",
|
||||
"proptest",
|
||||
"thiserror 2.0.21",
|
||||
"thread-priority",
|
||||
"zune-jpeg",
|
||||
]
|
||||
|
||||
@@ -6955,6 +6956,20 @@ dependencies = [
|
||||
"syn 3.0.6",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "thread-priority"
|
||||
version = "3.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8d2e834949be5111506bb252643498af1514f600d9e1dceedaa42afae155b67f"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"cfg-if",
|
||||
"libc",
|
||||
"log",
|
||||
"rustversion",
|
||||
"windows",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tiff"
|
||||
version = "0.11.3"
|
||||
|
||||
+18
-16
@@ -198,27 +198,28 @@ What's strong and missing in each: [target-app-parity.md](docs/target-app-parity
|
||||
|
||||
## Languages
|
||||
|
||||
Twelve key languages (historical % snapshot vs 2,143 keys, except Vietnamese, Brazilian
|
||||
Portuguese and Spanish vs the current union). Detail and script notes: [localization-parity.md](docs/localization-parity.md).
|
||||
Twelve key languages: the share of the 2,897 strings in the i18n report's denominator (the interface's strings plus every catalog key), from
|
||||
`cargo xtask i18n-report` on 2026-11-03. Detail and script notes: [localization-parity.md](docs/localization-parity.md).
|
||||
|
||||
| Language | Code | Strings | Status |
|
||||
|---|---|---|---|
|
||||
| English | `en` | 100% | full |
|
||||
| Simplified Chinese | `zh-hans` | 97.4% | partial (native LXGW WenKai Lite; no Hans face in the web build, #826) |
|
||||
| Spanish | `es` | 100% of current union | partial (dialogs / tooltips; no help) |
|
||||
| Hindi | `hi` | 0% | none |
|
||||
| Arabic | `ar` | 100% | partial (logical catalog, explicit RTL labels, mirrored stock chrome; native/browser/IME workflows unqualified) |
|
||||
| French | `fr` | 99.3% | partial |
|
||||
| Portuguese (Brazil) | `pt-br` | 100% of current union | partial |
|
||||
| Indonesian | `id` | 0% | none |
|
||||
| Japanese | `ja` | 99.1% | partial |
|
||||
| German | `de` | 99.3% | partial |
|
||||
| Korean | `ko` | 0% | none |
|
||||
| Vietnamese | `vi` | 100% of current union | partial (dialogs / tooltips; no help) |
|
||||
| Simplified Chinese | `zh-hans` | 88.4% | partial (native LXGW WenKai Lite; no Hans face in the web build, #826) |
|
||||
| Spanish | `es` | 98.4% | partial (dialogs / tooltips; no help) |
|
||||
| Hindi | `hi` | 97.5% | partial (Devanagari rendering unqualified) |
|
||||
| Arabic | `ar` | 97.9% | partial (logical catalog, explicit RTL labels, mirrored stock chrome; native/browser/IME workflows unqualified) |
|
||||
| French | `fr` | 98.4% | partial |
|
||||
| Portuguese (Brazil) | `pt-br` | 98.4% | partial |
|
||||
| Indonesian | `id` | 97.5% | partial |
|
||||
| Japanese | `ja` | 89.6% | partial |
|
||||
| German | `de` | 89.7% | partial |
|
||||
| Korean | `ko` | 97.5% | partial (no Hangul UI face) |
|
||||
| Vietnamese | `vi` | 98.4% | partial (dialogs / tooltips; no help) |
|
||||
|
||||
Also shipped: Traditional Chinese, Russian, Bulgarian, Telugu, Hungarian, Ukrainian, Italian,
|
||||
Kazakh, Polish, Slovenian, Greek, Turkish, Lithuanian, Romanian and Czech: **15 more catalogs**
|
||||
(24 interface languages including English).
|
||||
Kazakh, Polish, Slovenian, Greek, Turkish, Lithuanian, Finnish, Albanian, Catalan, Romanian,
|
||||
Norwegian Bokmål, Persian, Central Kurdish, Thai, Lao and Czech: **23 more catalogs**
|
||||
(35 interface languages including English).
|
||||
|
||||
## Upcoming
|
||||
|
||||
@@ -252,10 +253,11 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md
|
||||
- **2026-11-03 (community, M7, Thai word breaking):** Thai rows end between words, found with ICU4X's dictionary line segmenter (`icu_segmenter` 2.3, compiled dictionary data, no LSTM model; Unicode-3.0), instead of only at spaces when rewrapping and at any cluster in Add text. A row never starts with a following vowel, tone or other mark, Mai Yamok or Paiyannoi, nor ends with a leading vowel; a word wider than the row still breaks between clusters, and the spaces where an Add text row ends are dropped as in Latin text. Rewrapping existing text works out the breaks once per run of non-space characters. Rewriting a paragraph into Thai still needs a source font with the Thai glyphs (there is no Thai fallback face for it yet). The compiled dictionaries (Thai, Lao, Khmer, Burmese) add about 1.8 MB to a stripped release binary. Estimates unchanged.
|
||||
- **2026-11-03 (M7, #5835):** In image crop mode, a right-click on the image, its crop box or its handles keeps the crop and opens no menu, so the menu no longer switches as the pointer moves. A right-click elsewhere clears the selection and opens the page menu. UI tests cover all four page rotations, overlapping images, a 45° image, and a check that the Done/Cancel/Remove Crop pills at a page edge still keep the crop.
|
||||
|
||||
- **2026-11-02 (M12, #1297):** `model_add` embeds a U3D or PRC file, recognised by its header, as a 3D annotation with a chosen activation and a poster (an image or PDF page fitted in the box, or a labelled frame); an older file's catalog `/Version` is raised to what the model needs. Views, a rendered poster and a UI command are later steps. Estimates unchanged.
|
||||
- **2026-11-03 (M14 docs, #5805):** `docs/localization-parity.md` and the Languages table here count every catalog with `cargo xtask i18n-report`: the share of the 2,897 strings in its denominator, on `14ae839a`. The catalog-union measure it replaces had grown to 2,895 keys and left four catalogs at "100%" that were 44 keys short. Hindi, Indonesian and Korean are listed with their catalogs (97.5% each) instead of 0, and Thai, Lao and Central Kurdish join the table. The ≈ 68% localization score is not re-scored.
|
||||
|
||||
- **2026-11-02 (M10, #5743):** macOS print jobs name their title and owner (`com.apple.print.JobInfo.PMJobName`, `PMJobOwner`), as the system print dialog does, because a Kyocera filter crashes on a job without them. Checked by a test and through `doc_print` against a stand-in `lp`; not yet on a physical printer.
|
||||
|
||||
- **2026-11-02 (M3, #5708):** Pages shorter than the window sit in its middle, one page or row at a time and when scrolling continuously with every page in view.
|
||||
- **2026-11-02 (M14, #5737, #5460):** Preferences can turn off the update check at start. It stays on by default, and Help ▸ Check for updates still asks.
|
||||
|
||||
- **2026-11-01 (M7, #5657):** Header/footer, watermark and background additions and replacements stage the complete call before committing. Synthetic later-page failures preserve exact incremental bytes, object count, dirty state and allocation cursor; success controls retain other marks and shared/inherited resources. Estimates unchanged.
|
||||
|
||||
@@ -8,6 +8,9 @@ pub(crate) fn read(path: &str) -> Result<Arc<Vec<u8>>, String> {
|
||||
std::fs::read(path).map(Arc::new).map_err(|e| format!("{path}: {e}"))
|
||||
}
|
||||
|
||||
/// `info FILE`: a JSON summary of the document as the app opens it (pages, fields, metadata, the
|
||||
/// standards it declares, and the notes about damage repaired while opening it), with none of
|
||||
/// its scripts run.
|
||||
pub(crate) fn info(args: &[String]) -> Result<(), CliError> {
|
||||
validate_options("info", args, INFO_OPTIONS)?;
|
||||
let path = *positional(args, INFO_OPTIONS).first().ok_or("info: missing file")?;
|
||||
@@ -18,24 +21,33 @@ pub(crate) fn info(args: &[String]) -> Result<(), CliError> {
|
||||
let mut info = inspect(bytes.clone(), render_password.as_deref()).map_err(|e| e.to_string())?;
|
||||
let pdf_pages = info.pages.len();
|
||||
let acroform_fields = info.fields.len();
|
||||
// The document as the app opens it: the notes about damage repaired while opening, which the
|
||||
// app shows in Document Properties, and for a dynamic XFA form the laid-out pages and fields.
|
||||
// Inspection runs none of the document's scripts: an XFA form's initialize and calculate
|
||||
// scripts, which the app runs on opening, are left alone, as with JavaScript turned off.
|
||||
let mut session = pdfcraft_engine::Session::new();
|
||||
session.set_javascript(false);
|
||||
let opened = session.open("info.pdf", None, bytes.clone(), password).ok().and_then(|id| session.get(id));
|
||||
// Dynamic XFA forms: say what laying the template out gives (what the app shows).
|
||||
let xfa_layout = (info.xfa == Some(pdfcraft_render::Xfa::Dynamic))
|
||||
.then(|| {
|
||||
let mut s = pdfcraft_engine::Session::new();
|
||||
let id = s.open("info.pdf", None, bytes.clone(), password).ok()?;
|
||||
let d = s.get(id)?;
|
||||
d.xfa.as_ref().map(|x| {
|
||||
info = d.info.clone();
|
||||
// The in-memory layout is an appended revision, not the file being inspected.
|
||||
info.file_size = bytes.len();
|
||||
serde_json::json!({ "pages": x.pages, "fields": x.fields, "warnings": x.warnings })
|
||||
})
|
||||
let xfa_layout = opened.filter(|_| info.xfa == Some(pdfcraft_render::Xfa::Dynamic)).and_then(|d| {
|
||||
d.xfa.as_ref().map(|x| {
|
||||
info = d.info.clone();
|
||||
// The in-memory layout is an appended revision, not the file being inspected.
|
||||
info.file_size = bytes.len();
|
||||
serde_json::json!({ "pages": x.pages, "fields": x.fields, "warnings": x.warnings })
|
||||
})
|
||||
.flatten();
|
||||
// What the document declares as a standard, read the way the Standards panel reads it, so
|
||||
// `info` and the app agree. A file that declares nothing leaves these null and empty.
|
||||
let declared =
|
||||
pdfcraft_cos::Document::open_with_password(bytes.clone(), password).map(|doc| pdfcraft_preflight::declared(&doc)).unwrap_or_default();
|
||||
});
|
||||
// What the document declares as a standard, as the Standards panel reads it, and the notes
|
||||
// Document Properties shows, which include what the app repaired after reading the objects (a
|
||||
// page tree rebuilt from the pages found by scanning), both from the session's own reading. A
|
||||
// file the app cannot open is read once more for what the object reader declares and repaired.
|
||||
// A file that declares nothing leaves the standards null and empty.
|
||||
let (declared, repairs) = match opened {
|
||||
Some(d) => (d.standards(), d.repair_log()),
|
||||
None => pdfcraft_cos::Document::open_with_password(bytes.clone(), password)
|
||||
.map(|cos| (pdfcraft_preflight::declared(&cos), cos.repair_log().to_vec()))
|
||||
.unwrap_or_default(),
|
||||
};
|
||||
let json = serde_json::json!({
|
||||
"file": path,
|
||||
"pdf_version": info.pdf_version,
|
||||
@@ -56,6 +68,7 @@ pub(crate) fn info(args: &[String]) -> Result<(), CliError> {
|
||||
"custom_properties": info.custom.len(),
|
||||
"page_labels": info.pages.iter().take(8).map(|p| p.label.clone()).collect::<Vec<_>>(),
|
||||
"warnings": info.warnings,
|
||||
"repairs": repairs,
|
||||
});
|
||||
stdout_line(format_args!("{}", serde_json::to_string_pretty(&json).unwrap_or_default()))?;
|
||||
Ok(())
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
//! `info` lists the notes about damage repaired while opening, as the app shows them in Document
|
||||
//! Properties and as `doc_info` reports them in `repairs`: a rebuilt cross-reference index, and a
|
||||
//! page tree rebuilt from the pages found by scanning (a note the app adds after reading).
|
||||
|
||||
use std::process::Command;
|
||||
|
||||
const BIN: &str = env!("CARGO_BIN_EXE_pdfcraft-cli");
|
||||
|
||||
/// A PDF with `pages` pages, each drawing a rectangle (a page found by scanning has content), and
|
||||
/// `catalog` as object 1; `startxref` points at its cross-reference table, or at `bad_startxref`.
|
||||
fn fixture(catalog: &str, pages: usize, bad_startxref: Option<usize>) -> Vec<u8> {
|
||||
let content = "0 0 0 rg 10 10 40 20 re f";
|
||||
let kids: String = (0..pages).map(|i| format!("{} 0 R ", 4 + i)).collect();
|
||||
let mut objs = vec![
|
||||
catalog.to_string(),
|
||||
format!("<< /Type /Pages /Kids [{kids}] /Count {pages} >>"),
|
||||
format!("<< /Length {} >>\nstream\n{content}\nendstream", content.len()),
|
||||
];
|
||||
objs.extend((0..pages).map(|_| "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 120 60] /Contents 3 0 R >>".to_string()));
|
||||
let mut out = b"%PDF-1.7\n".to_vec();
|
||||
let mut offsets = Vec::new();
|
||||
for (i, o) in objs.iter().enumerate() {
|
||||
offsets.push(out.len());
|
||||
out.extend_from_slice(format!("{} 0 obj\n{o}\nendobj\n", i + 1).as_bytes());
|
||||
}
|
||||
let xref = out.len();
|
||||
out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes());
|
||||
for off in &offsets {
|
||||
out.extend_from_slice(format!("{off:010} 00000 n \n").as_bytes());
|
||||
}
|
||||
let start = bad_startxref.unwrap_or(xref);
|
||||
out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{start}\n%%EOF\n", objs.len() + 1).as_bytes());
|
||||
out
|
||||
}
|
||||
|
||||
const CATALOG: &str = "<< /Type /Catalog /Pages 2 0 R >>";
|
||||
|
||||
fn info_of(bytes: &[u8], name: &str) -> serde_json::Value {
|
||||
let dir = std::env::temp_dir().join(format!("pdfcraft-info-repairs-{}-{name}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("f.pdf");
|
||||
std::fs::write(&path, bytes).unwrap();
|
||||
let out = Command::new(BIN).args(["info", path.to_str().unwrap()]).output().unwrap();
|
||||
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
|
||||
let json = serde_json::from_slice(&out.stdout).expect("info prints JSON");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
json
|
||||
}
|
||||
|
||||
fn repairs(json: &serde_json::Value) -> Vec<String> {
|
||||
json["repairs"].as_array().unwrap_or_else(|| panic!("no repairs array: {json}")).iter().map(|l| l.as_str().unwrap().to_string()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn info_lists_a_rebuilt_cross_reference_index() {
|
||||
// `startxref` points into the middle of an object, so the index is rebuilt from the headers.
|
||||
let json = info_of(&fixture(CATALOG, 1, Some(20)), "xref");
|
||||
assert_eq!(json["pages"], serde_json::json!(1), "{json}");
|
||||
let lines = repairs(&json);
|
||||
assert!(lines.iter().any(|l| l.contains("rebuilt cross-reference index")), "{lines:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn info_lists_a_page_tree_the_app_rebuilt_by_scanning() {
|
||||
// The catalog names a page tree object the file does not have (#1656).
|
||||
let json = info_of(&fixture("<< /Type /Catalog /Pages 9 0 R >>", 2, None), "pagetree");
|
||||
let lines = repairs(&json);
|
||||
assert!(lines.iter().any(|l| l.contains("page tree is missing")), "{lines:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn info_lists_no_repairs_for_a_sound_file() {
|
||||
let json = info_of(&fixture(CATALOG, 1, None), "sound");
|
||||
assert_eq!(json["repairs"], serde_json::json!([]), "{json}");
|
||||
}
|
||||
@@ -8,6 +8,7 @@ mod check;
|
||||
mod edit;
|
||||
mod extract;
|
||||
mod help;
|
||||
mod info_repairs;
|
||||
mod info_standards;
|
||||
mod mcp_compact;
|
||||
mod options;
|
||||
|
||||
@@ -7,6 +7,11 @@ use std::sync::Arc;
|
||||
const BIN: &str = env!("CARGO_BIN_EXE_pdfcraft-cli");
|
||||
|
||||
fn fixture(test: &str) -> PathBuf {
|
||||
fixture_with(test, "")
|
||||
}
|
||||
|
||||
/// The two-page form, with `event` inside its `name` field.
|
||||
fn fixture_with(test: &str, event: &str) -> PathBuf {
|
||||
let xdp = 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">
|
||||
@@ -15,11 +20,12 @@ fn fixture(test: &str) -> PathBuf {
|
||||
<medium short="200pt" long="300pt"/>
|
||||
</pageArea></pageSet>
|
||||
<draw w="160pt" h="20pt"><value><text>First XFA page</text></value></draw>
|
||||
<field name="name" w="160pt" h="20pt"><ui><textEdit/></ui><value><text>Ada</text></value></field>
|
||||
<field name="name" w="160pt" h="20pt"><ui><textEdit/></ui><value><text>Ada</text></value>{event}</field>
|
||||
<subform name="last" layout="tb"><breakBefore targetType="pageArea"/>
|
||||
<draw w="160pt" h="20pt"><value><text>Second XFA page</text></value></draw>
|
||||
</subform>
|
||||
</subform></template></xdp:xdp>"#;
|
||||
</subform></template></xdp:xdp>"#
|
||||
.replace("{event}", event);
|
||||
let objects = [
|
||||
"<< /Type /Catalog /Pages 2 0 R /NeedsRendering true /AcroForm << /XFA 5 0 R /Fields [] >> >>".to_string(),
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".into(),
|
||||
@@ -67,6 +73,21 @@ fn info_reports_the_laid_out_pages_and_fields() {
|
||||
assert_eq!(std::fs::read(path).unwrap(), original, "inspection must not write the layout to the input");
|
||||
}
|
||||
|
||||
/// `info` inspects an untrusted file: a form's initialize script, which the app runs on opening
|
||||
/// and which here would change the field's value, does not run.
|
||||
#[test]
|
||||
fn info_runs_none_of_the_forms_scripts() {
|
||||
let script = r#"<event activity="initialize"><script contentType="application/x-javascript">this.rawValue = "Changed";</script></event>"#;
|
||||
let path = fixture_with("info-script", script);
|
||||
let output = Command::new(BIN).arg("info").arg(&path).output().unwrap();
|
||||
success(&output);
|
||||
let info: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
|
||||
assert_eq!(info["xfa_layout"]["pages"], 2, "the form is still laid out: {info}");
|
||||
let warnings = info["warnings"].as_array().unwrap();
|
||||
assert!(!warnings.iter().any(|w| w.as_str().is_some_and(|w| w.contains("scripts changed it on opening"))), "{warnings:?}");
|
||||
assert_eq!(info["repairs"], serde_json::json!([]), "{info}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_reads_the_layout_including_a_page_absent_from_the_placeholder() {
|
||||
let path = fixture("text");
|
||||
@@ -134,3 +155,21 @@ fn a_laid_out_form_keeps_the_original_copy_permissions() {
|
||||
assert_eq!(info["file_size"], original.len());
|
||||
assert_eq!(std::fs::read(path).unwrap(), original);
|
||||
}
|
||||
|
||||
/// A damaged dynamic XFA form: `info` lists the cross-reference index rebuilt while opening it,
|
||||
/// as Document Properties does after the form is laid out as one more revision.
|
||||
#[test]
|
||||
fn info_lists_the_repairs_of_a_laid_out_form() {
|
||||
let path = fixture("info-damaged");
|
||||
let bytes = std::fs::read(&path).unwrap();
|
||||
let at = bytes.windows(10).rposition(|w| w == b"startxref\n").unwrap() + 10;
|
||||
let mut damaged = bytes[..at].to_vec();
|
||||
damaged.extend_from_slice(b"20\n%%EOF\n");
|
||||
std::fs::write(&path, &damaged).unwrap();
|
||||
let output = Command::new(BIN).arg("info").arg(&path).output().unwrap();
|
||||
success(&output);
|
||||
let info: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
|
||||
assert_eq!(info["xfa_layout"]["pages"], 2, "the form is still laid out: {info}");
|
||||
let repairs = info["repairs"].as_array().unwrap();
|
||||
assert!(repairs.iter().any(|l| l.as_str().is_some_and(|l| l.contains("rebuilt cross-reference index"))), "{repairs:?}");
|
||||
}
|
||||
|
||||
@@ -102,25 +102,12 @@ pub fn timestamp(t: SystemTime) -> String {
|
||||
format!("{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}.{:03}Z", rem / 3600, rem % 3600 / 60, rem % 60, since.subsec_millis())
|
||||
}
|
||||
|
||||
/// Days since 1970-01-01 → proleptic Gregorian (year, month, day).
|
||||
///
|
||||
/// `timestamp` clamps a pre-1970 clock to the epoch, so `days` is an unsigned count that can run
|
||||
/// past `NaiveDate`'s ±262143-year range. The Gregorian calendar repeats every 400 years
|
||||
/// (146_097 days), so chrono converts the day within one cycle and whole cycles go back into the
|
||||
/// year (an `i128`, then saturated into `i64`), keeping chrono as the only calendar logic and
|
||||
/// reproducing the old `civil_from_days` result exactly without hand-rolled day math. 1970-01-01
|
||||
/// is `num_days_from_ce` 719_163.
|
||||
/// Days since 1970-01-01 → proleptic Gregorian (year, month, day): `pdfcraft_engine::civil_from_days`,
|
||||
/// which keeps the date past chrono's range by whole 400-year cycles. `days` is a `u64` second
|
||||
/// count over 86_400, at most about 2.1e14, so it always fits an `i64`.
|
||||
fn civil_from_days(days: u64) -> (i64, u32, u32) {
|
||||
use chrono::Datelike;
|
||||
let (cycles, rest) = (days / 146_097, days % 146_097);
|
||||
// `rest + 719_163` is 719_163..865_259, always a valid CE day.
|
||||
match i32::try_from(rest + 719_163).ok().and_then(chrono::NaiveDate::from_num_days_from_ce_opt) {
|
||||
Some(d) => {
|
||||
let y = i128::from(d.year()) + i128::from(cycles) * 400;
|
||||
(i64::try_from(y).unwrap_or(i64::MAX), d.month(), d.day())
|
||||
}
|
||||
None => (1970, 1, 1), // unreachable
|
||||
}
|
||||
// The fallback is unreachable: `days` is at most `u64::MAX / 86_400`, far below `i64::MAX`.
|
||||
pdfcraft_engine::civil_from_days(i64::try_from(days).unwrap_or(i64::MAX))
|
||||
}
|
||||
|
||||
fn numbered(dir: &Path, n: usize) -> PathBuf {
|
||||
|
||||
@@ -37,9 +37,16 @@ struct Walker<'a> {
|
||||
visits: usize,
|
||||
/// Per page: the text each MCID shows (read once per page).
|
||||
texts: HashMap<usize, HashMap<i64, String>>,
|
||||
/// What is left of [`MAX_TITLE_SOURCE_BYTES`].
|
||||
title_left: usize,
|
||||
out: Vec<Heading>,
|
||||
}
|
||||
|
||||
/// Bytes of `/ActualText`, `/Alt` and `/T` strings the headings of one document decode in all.
|
||||
/// Titles are cut to [`MAX_TITLE`] characters, but many headings can name one large string, and
|
||||
/// each would otherwise be decoded in full first.
|
||||
const MAX_TITLE_SOURCE_BYTES: usize = 32 << 20;
|
||||
|
||||
/// The headings, in document order. Headings without text or a page are left out.
|
||||
pub fn headings(doc: &Document) -> Vec<Heading> {
|
||||
let Some(root) = tree_root(doc) else { return Vec::new() };
|
||||
@@ -52,6 +59,7 @@ pub fn headings(doc: &Document) -> Vec<Heading> {
|
||||
seen: HashSet::new(),
|
||||
visits: 0,
|
||||
texts: HashMap::new(),
|
||||
title_left: MAX_TITLE_SOURCE_BYTES,
|
||||
out: Vec::new(),
|
||||
};
|
||||
if let Some(k) = root.get(b"K") {
|
||||
@@ -131,17 +139,34 @@ impl Walker<'_> {
|
||||
self.marks(kids, pg, depth + 1, &mut marks);
|
||||
}
|
||||
let Some(page) = pg.or_else(|| marks.iter().find_map(|m| m.0)).and_then(|p| self.page_index.get(&p).copied()) else { return };
|
||||
let doc = self.doc;
|
||||
let attr = |key: &[u8]| d.get(key).map(|o| doc.resolve(o)).and_then(|o| o.as_string().map(|s| s.to_text())).filter(|t| !t.trim().is_empty());
|
||||
let title = match attr(b"ActualText") {
|
||||
let title = match self.attr(d, b"ActualText") {
|
||||
Some(t) => Some(t),
|
||||
None => self.marked_text(&marks, page).or_else(|| attr(b"Alt")).or_else(|| attr(b"T")),
|
||||
None => match self.marked_text(&marks, page) {
|
||||
Some(t) => Some(t),
|
||||
None => self.attr(d, b"Alt").or_else(|| self.attr(d, b"T")),
|
||||
},
|
||||
};
|
||||
let Some(title) = title else { return };
|
||||
let title: String = title.split_whitespace().collect::<Vec<_>>().join(" ").chars().take(MAX_TITLE).collect();
|
||||
self.out.push(Heading { obj, level, title, page });
|
||||
}
|
||||
|
||||
/// The non-blank text of the string `key` holds, charged against the title allowance by the
|
||||
/// longer of its raw and decoded size (a string that does not fit is not decoded).
|
||||
fn attr(&mut self, d: &Dict, key: &[u8]) -> Option<String> {
|
||||
let o = self.doc.resolve(d.get(key)?);
|
||||
let s = o.as_string()?;
|
||||
// A text string decodes to at most three bytes per raw byte, so one whose worst case does
|
||||
// not fit the remaining allowance is never decoded: the raw check alone let a string at
|
||||
// the raw limit decode to three times it before the allowance was reduced.
|
||||
if s.bytes.len().saturating_mul(3) > self.title_left {
|
||||
return None;
|
||||
}
|
||||
let text = s.to_text();
|
||||
self.title_left = self.title_left.saturating_sub(text.len().max(s.bytes.len()));
|
||||
Some(text).filter(|t| !t.trim().is_empty())
|
||||
}
|
||||
|
||||
/// The text the marked content shows (`page`: where marks without a page of their own are).
|
||||
fn marked_text(&mut self, marks: &[(Option<ObjRef>, i64)], page: usize) -> Option<String> {
|
||||
let mut parts = Vec::new();
|
||||
|
||||
@@ -1559,6 +1559,24 @@ fn q_inside_a_text_object_restores_the_text_matrices() {
|
||||
assert_eq!(titles, ["Chapter One", "Chapter Two"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn headings_naming_one_large_string_stop_decoding_it_at_the_allowance() {
|
||||
let count = 100;
|
||||
let kids = (0..count).map(|i| format!("{} 0 R", 8 + i)).collect::<Vec<_>>().join(" ");
|
||||
let mut objects = vec![
|
||||
"<< /Type /Catalog /Pages 2 0 R /MarkInfo << /Marked true >> /StructTreeRoot 5 0 R >>".to_string(),
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_string(),
|
||||
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Contents 4 0 R >>".to_string(),
|
||||
stream("BT ET"),
|
||||
"<< /Type /StructTreeRoot /K 6 0 R >>".to_string(),
|
||||
format!("<< /S /Document /P 5 0 R /K [{kids}] >>"),
|
||||
format!("({})", "a".repeat(512 << 10)),
|
||||
];
|
||||
objects.extend((0..count).map(|_| "<< /S /H1 /P 6 0 R /Pg 3 0 R /ActualText 7 0 R >>".to_string()));
|
||||
let found = headings(&pdf(&objects, ""));
|
||||
assert!(!found.is_empty() && found.len() < count, "{}", found.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_untagged_document_has_no_headings() {
|
||||
let mut objs = headings_doc();
|
||||
|
||||
+10
-6
@@ -6,7 +6,9 @@ Comments (annotations), ISO 32000-2 §12.5. Layer L3, depends on `pdfcraft-cos`,
|
||||
|
||||
- **Builders** for the comment types Acrobat's commenting tools create: sticky note (`Text` +
|
||||
`Popup`), highlight, underline, strikethrough, squiggly, rectangle (`Square`), oval (`Circle`),
|
||||
line and arrow (`Line` with `/LE`), freehand drawing (`Ink`) and text box (`FreeText`).
|
||||
line and arrow (`Line` with `/LE`), freehand drawing (`Ink`), text box and callout
|
||||
(`FreeText`), polygon (including cloudy borders), polyline, caret, rubber and custom stamp,
|
||||
and file attachment.
|
||||
- **Appearance streams** (`appearance::build`) generated from the annotation dictionary, so new
|
||||
and restyled comments look the same in every viewer. Highlights multiply (`/BM /Multiply`).
|
||||
A line's leader lines (`/LL`, `/LLE`, `/LLO`) and caption (`/Cap`, `/CP`, `/CO`) are drawn as
|
||||
@@ -47,8 +49,8 @@ deterministic; the engine supplies them.
|
||||
|
||||
- Unknown keys are kept. Inline annotation dictionaries are promoted to indirect objects only
|
||||
when an edit needs a reference to them.
|
||||
- `set_style` refuses (and changes nothing) when it cannot redraw the comment, e.g. stamps,
|
||||
cloudy borders or callouts, instead of leaving a stale appearance.
|
||||
- `set_style` refuses when it cannot redraw the comment, e.g. a stamp
|
||||
whose appearance cannot be regenerated, instead of leaving a stale appearance.
|
||||
- Replies get the parent's `/Rect` and an empty appearance: they appear in comment lists but
|
||||
never paint a second icon.
|
||||
- Resizing a stamp changes its `/Rect` and preserves its original appearance and resources;
|
||||
@@ -63,7 +65,9 @@ deterministic; the engine supplies them.
|
||||
(vendored hayro-interpret patch 37), and `Summary::no_rotate` tells the UI where the icon is
|
||||
drawn.
|
||||
|
||||
## Not yet
|
||||
## Rich text and remaining limits
|
||||
|
||||
Callouts, polygons and polylines, clouds, carets (insert/replace text), stamps, file
|
||||
attachments, rich text (`/RC`, `/DS`), and the shared named-appearance cache Acrobat writes.
|
||||
Text-box text and colour edits regenerate `/RC` (XHTML) and `/DS` from the plain
|
||||
`/Contents`, `/DA` and `/Q`, so rich-text editors show the same text and style. These edits
|
||||
replace imported rich-text formatting. The shared named-appearance cache Acrobat writes
|
||||
is not implemented.
|
||||
|
||||
@@ -205,11 +205,24 @@ fn quads(context: &AppearanceContext<'_>) -> Option<Vec<[f64; 8]>> {
|
||||
(!q.is_empty()).then_some(q)
|
||||
}
|
||||
|
||||
/// `/C`-style colour arrays: none (transparent), gray, RGB or CMYK.
|
||||
fn color(d: &Dict, key: &[u8]) -> Option<Option<Rgb>> {
|
||||
/// `/C`-style colour arrays (ISO 32000-2 Table 166): none (transparent), gray, RGB or CMYK.
|
||||
/// The entries should all be numbers; a four-entry array with a non-number in it, such as
|
||||
/// `[1 0 0 null]`, is still read as CMYK with that entry 0, as PDFium, MuPDF and Poppler read it.
|
||||
/// A reference is not such an entry: it stands for a value this builder can't see (§7.3.10), so
|
||||
/// the colour is unreadable, as the other colour and number readers here treat one.
|
||||
pub(crate) fn color(d: &Dict, key: &[u8]) -> Option<Option<Rgb>> {
|
||||
let c = match d.get(key) {
|
||||
None => return Some(None),
|
||||
Some(o) => o.as_array()?.iter().map(|o| o.as_f64()).collect::<Option<Vec<f64>>>()?,
|
||||
Some(o) => match o.as_array()? {
|
||||
a if a.len() == 4 => a
|
||||
.iter()
|
||||
.map(|o| match o {
|
||||
Object::Ref(_) => None,
|
||||
o => Some(o.as_f64().unwrap_or(0.0)),
|
||||
})
|
||||
.collect::<Option<Vec<f64>>>()?,
|
||||
a => a.iter().map(|o| o.as_f64()).collect::<Option<Vec<f64>>>()?,
|
||||
},
|
||||
};
|
||||
Some(match c.as_slice() {
|
||||
[] => None,
|
||||
|
||||
+29
-11
@@ -105,7 +105,10 @@ pub fn summaries(doc: &Document) -> Vec<Summary> {
|
||||
let r = nums(b"Rect");
|
||||
let rect = if r.len() == 4 { [r[0].min(r[2]), r[1].min(r[3]), r[0].max(r[2]), r[1].max(r[3])] } else { [0.0; 4] };
|
||||
let c = nums(b"C");
|
||||
let mut color = (c.len() == 3).then(|| [c[0], c[1], c[2]]);
|
||||
let rgb = (c.len() == 3).then(|| [c[0], c[1], c[2]]);
|
||||
// Other comments report the stroke colour as it is drawn (grey, CMYK, a null entry
|
||||
// read as 0), like `props`; three numbers, some given by reference, are still read.
|
||||
let mut color = if subtype == "FreeText" { rgb } else { summary_color(doc, d).or(rgb) };
|
||||
if subtype == "FreeText"
|
||||
&& let Some(da) = text_value(doc, d, b"DA")
|
||||
{
|
||||
@@ -244,8 +247,7 @@ pub fn props(doc: &Document, page: usize, index: usize) -> Option<Props> {
|
||||
let obj = doc.resolve(&entry);
|
||||
let d = obj.as_dict()?;
|
||||
let subtype = String::from_utf8_lossy(d.name(b"Subtype")?).into_owned();
|
||||
let c: Vec<f64> = d.get(b"C").and_then(|o| o.as_array().map(|a| a.iter().filter_map(|x| x.as_f64()).collect())).unwrap_or_default();
|
||||
let color = if subtype == "FreeText" { Some(appearance::parse_da(d).0) } else { (c.len() == 3).then(|| [c[0], c[1], c[2]]) };
|
||||
let color = if subtype == "FreeText" { Some(appearance::parse_da(d).0) } else { drawn_color(d, b"C") };
|
||||
let width = matches!(subtype.as_str(), "Square" | "Circle" | "Line" | "Ink" | "Polygon" | "PolyLine" | "FreeText").then(|| {
|
||||
if subtype == "FreeText" {
|
||||
if !d.contains(b"BS") && !d.contains(b"Border") { 0.0 } else { appearance::border_width(d) }
|
||||
@@ -275,16 +277,32 @@ pub fn props(doc: &Document, page: usize, index: usize) -> Option<Props> {
|
||||
})
|
||||
}
|
||||
|
||||
/// A shape’s `/IC` or FreeText `/C` as RGB. Grey and CMYK fills are converted.
|
||||
/// A shape’s `/IC` or FreeText `/C` as RGB, read as it is drawn. Grey and CMYK fills are converted.
|
||||
fn fill_of(d: &Dict) -> Option<Rgb> {
|
||||
let key: &[u8] = if d.name(b"Subtype") == Some(b"FreeText") { b"C" } else { b"IC" };
|
||||
let c: Vec<f64> = d.get(key)?.as_array()?.iter().filter_map(|x| x.as_f64()).collect();
|
||||
let rgb = match c.as_slice() {
|
||||
[g] => [*g; 3],
|
||||
[r, g, b] => [*r, *g, *b],
|
||||
[c, m, y, k] => [(1.0 - c) * (1.0 - k), (1.0 - m) * (1.0 - k), (1.0 - y) * (1.0 - k)],
|
||||
_ => return None,
|
||||
};
|
||||
drawn_color(d, key)
|
||||
}
|
||||
|
||||
/// `/C` as [`drawn_color`] reads it, the array itself followed when it is given by reference.
|
||||
/// Only an array of at most four entries is copied out of the reference.
|
||||
fn summary_color(doc: &Document, d: &Dict) -> Option<[f32; 3]> {
|
||||
let rgb = match d.get(b"C") {
|
||||
Some(o @ Object::Ref(_)) => {
|
||||
let held = doc.resolve(o);
|
||||
let entries = held.as_array().filter(|a| a.len() <= 4)?;
|
||||
let mut direct = Dict::new();
|
||||
direct.set(b"C".to_vec(), Object::Array(entries.clone()));
|
||||
drawn_color(&direct, b"C")
|
||||
}
|
||||
_ => drawn_color(d, b"C"),
|
||||
}?;
|
||||
Some(rgb.map(|x| x as f32))
|
||||
}
|
||||
|
||||
/// The colour array at `key` as RGB, read as the appearance builder draws it: grey and CMYK are
|
||||
/// converted, and a four-entry array with a non-number in it is CMYK with that entry 0.
|
||||
fn drawn_color(d: &Dict, key: &[u8]) -> Option<Rgb> {
|
||||
let rgb = appearance::color(d, key).flatten()?;
|
||||
finite(&rgb).then(|| rgb.map(|x| x.clamp(0.0, 1.0)))
|
||||
}
|
||||
|
||||
|
||||
+84
-11
@@ -94,7 +94,7 @@ pub fn deletable(doc: &Document, page: usize, index: usize) -> Result<(), AnnotE
|
||||
if let Some(r) = target.as_ref() {
|
||||
unlocked(doc, r)?;
|
||||
}
|
||||
let doomed = with_replies_and_popups(doc, &list, seed(target));
|
||||
let doomed = with_replies_and_popups(doc, &list, seed(doc, target));
|
||||
// A locked reply can't be deleted on its own, so it doesn't go with the comment or reply it
|
||||
// answers either. Pop-ups follow their comment.
|
||||
for (_, e) in list.iter().enumerate().filter(|(i, e)| *i != index && goes_with(e, &doomed)) {
|
||||
@@ -115,15 +115,28 @@ pub fn lift_annotation(doc: &mut Document, page: usize, index: usize) -> Result<
|
||||
let p = page_ref(doc, page)?;
|
||||
let list = annots(doc, p);
|
||||
let target = list.get(index).ok_or(AnnotError::NoSuchAnnotation { page, index })?;
|
||||
let doomed = with_replies_and_popups(doc, &list, seed(target));
|
||||
let doomed = with_replies_and_popups(doc, &list, seed(doc, target));
|
||||
let kept: Vec<Object> = list.iter().enumerate().filter(|(i, e)| *i != index && !goes_with(e, &doomed)).map(|(_, e)| e.clone()).collect();
|
||||
Ok(set_annots(doc, p, kept)?)
|
||||
}
|
||||
|
||||
/// What deleting the `/Annots` entry `target` starts from: its reference, or for an inline
|
||||
/// comment (which has none to collect) the pop-up it names, which still goes.
|
||||
fn seed(target: &Object) -> Option<ObjRef> {
|
||||
target.as_ref().or_else(|| target.as_dict().and_then(|d| d.reference(b"Popup")))
|
||||
/// comment (which has none to collect) the pop-up it names, which still goes. The strikeout of a
|
||||
/// Replace Text proposal also takes the caret it is grouped under, so the two go together
|
||||
/// whichever is deleted.
|
||||
fn seed(doc: &Document, target: &Object) -> Vec<ObjRef> {
|
||||
let own = target.as_ref().or_else(|| target.as_dict().and_then(|d| d.reference(b"Popup")));
|
||||
own.into_iter().chain(replaced_by(doc, target)).collect()
|
||||
}
|
||||
|
||||
/// The caret a Replace Text strikeout is grouped under (`/IT /StrikeOutTextEdit`, `/RT /Group`,
|
||||
/// `/IRT` to a caret): the proposal's primary, which holds the replacement.
|
||||
fn replaced_by(doc: &Document, strike: &Object) -> Option<ObjRef> {
|
||||
let obj = doc.resolve(strike);
|
||||
let d = obj.as_dict()?;
|
||||
let edit = d.name(b"Subtype") == Some(b"StrikeOut") && d.name(b"IT") == Some(b"StrikeOutTextEdit") && d.name(b"RT") == Some(b"Group");
|
||||
let caret = d.reference(b"IRT").filter(|_| edit)?;
|
||||
(annot_dict(doc, caret).name(b"Subtype") == Some(b"Caret")).then_some(caret)
|
||||
}
|
||||
|
||||
/// Whether the `/Annots` entry `entry` goes with `going` (from [`with_replies_and_popups`]): it is
|
||||
@@ -713,9 +726,61 @@ fn ink_rect_for_width(d: &Dict, old_w: f64, w: f64) -> Option<[f64; 4]> {
|
||||
|
||||
/// Change a comment's colour, opacity (of the whole comment), line width and/or line endings, and
|
||||
/// redraw it.
|
||||
///
|
||||
/// A Replace Text proposal is one look: colour and opacity are the group's (`/C` is read from
|
||||
/// the primary, ISO 32000-2 §12.5.6.2), so restyling either the caret or its strikeout restyles
|
||||
/// and redraws the other too, in the same edit. The strikeout takes no line width (a text markup
|
||||
/// annotation has no border) and neither part has line endings. All or nothing: if one member
|
||||
/// can't be restyled, none is.
|
||||
pub fn set_style(doc: &mut Document, page: usize, index: usize, change: StyleChange, meta: &Meta) -> Result<(), AnnotError> {
|
||||
let StyleChange { color, opacity, width, endings } = change;
|
||||
let (_, r) = annot_ref(doc, page, index)?;
|
||||
let others = replace_text_partners(doc, page, r)?;
|
||||
// Check every partner before changing anything.
|
||||
for &o in &others {
|
||||
unlocked(doc, o)?;
|
||||
}
|
||||
let before: Vec<(ObjRef, Dict)> = others.iter().map(|&o| (o, annot_dict(doc, o))).collect();
|
||||
let mut done: Vec<(ObjRef, Dict)> = vec![(r, annot_dict(doc, r))];
|
||||
style_one(doc, r, change.clone(), meta)?;
|
||||
for (o, d) in before {
|
||||
let caret = d.name(b"Subtype") == Some(b"Caret");
|
||||
let part = StyleChange { color: change.color, opacity: change.opacity, width: change.width.filter(|_| caret), endings: None };
|
||||
let unchanged = part.color.is_none() && part.opacity.is_none() && part.width.is_none();
|
||||
if unchanged {
|
||||
continue;
|
||||
}
|
||||
if let Err(e) = style_one(doc, o, part, meta) {
|
||||
// Put the members already restyled back, the target included.
|
||||
for (o, d) in done.into_iter().rev() {
|
||||
doc.set(o, Object::Dict(d));
|
||||
}
|
||||
return Err(e);
|
||||
}
|
||||
done.push((o, d));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The other members of the Replace Text proposal `r` belongs to, on `page`: for its caret, the
|
||||
/// strikeouts grouped under it; for a strikeout, its caret and any other strikeout under it.
|
||||
/// Empty for anything else.
|
||||
fn replace_text_partners(doc: &Document, page: usize, r: ObjRef) -> Result<Vec<ObjRef>, AnnotError> {
|
||||
let own = Object::Ref(r);
|
||||
let caret = match replaced_by(doc, &own) {
|
||||
Some(c) => c,
|
||||
None if annot_dict(doc, r).name(b"Subtype") == Some(b"Caret") => r,
|
||||
None => return Ok(Vec::new()),
|
||||
};
|
||||
let list = annots(doc, page_ref(doc, page)?);
|
||||
let strikes = list.iter().filter(|e| replaced_by(doc, e) == Some(caret)).filter_map(Object::as_ref);
|
||||
// `/Annots` may list one annotation twice: restyle each once.
|
||||
let mut seen: HashSet<ObjRef> = HashSet::from([r]);
|
||||
Ok(std::iter::once(caret).chain(strikes).filter(|&o| seen.insert(o)).collect())
|
||||
}
|
||||
|
||||
/// [`set_style`] on one annotation.
|
||||
fn style_one(doc: &mut Document, r: ObjRef, change: StyleChange, meta: &Meta) -> Result<(), AnnotError> {
|
||||
let StyleChange { color, opacity, width, endings } = change;
|
||||
unlocked(doc, r)?;
|
||||
let d = annot_dict(doc, r);
|
||||
let subtype = String::from_utf8_lossy(d.name(b"Subtype").unwrap_or_default()).into_owned();
|
||||
@@ -994,8 +1059,13 @@ fn pair_points(d: &Dict, key: &[u8]) -> Option<Vec<[f64; 2]>> {
|
||||
}
|
||||
|
||||
/// Replace Text (Acrobat's proposal): strike out `quads` and add a caret at the end of the
|
||||
/// struck text holding `replacement`, grouped with the strikeout (`/IRT` + `/RT /Group`) so they
|
||||
/// move, list and delete as one. Returns the strikeout's index.
|
||||
/// struck text holding `replacement`, the two grouped so they move, list and delete as one.
|
||||
/// Returns the strikeout's index.
|
||||
///
|
||||
/// The caret is the group's primary (`/IT /Replace`) and the strikeout its subordinate (`/IRT` to
|
||||
/// the caret, `/RT /Group`, `/IT /StrikeOutTextEdit`): a group's text is read from its primary,
|
||||
/// and the subordinates' `Contents` are ignored (ISO 32000-2 §12.5.6.2), so the replacement has
|
||||
/// to be on the primary.
|
||||
///
|
||||
/// The two annotations need their own `/NM`: XFDF names a reply by the `/NM` of what it replies
|
||||
/// to, so one id for both writes `inreplyto` equal to the caret's own `name`, and a reader that
|
||||
@@ -1016,7 +1086,6 @@ pub fn add_text_replacement(doc: &mut Document, replacement: TextReplacement<'_>
|
||||
meta,
|
||||
)?;
|
||||
let (_, sr) = annot_ref(doc, page, s)?;
|
||||
doc.update_dict(sr, |d| d.set(b"IT".to_vec(), Object::name("StrikeOutTextEdit")))?;
|
||||
// The caret sits on the baseline at the end of the last line, its point at the text.
|
||||
let xs = [last[0], last[2], last[4], last[6]];
|
||||
let ys = [last[1], last[3], last[5], last[7]];
|
||||
@@ -1031,10 +1100,14 @@ pub fn add_text_replacement(doc: &mut Document, replacement: TextReplacement<'_>
|
||||
)?;
|
||||
let (_, cr) = annot_ref(doc, page, c)?;
|
||||
doc.update_dict(cr, |d| {
|
||||
d.set(b"IRT".to_vec(), Object::Ref(sr));
|
||||
d.set(b"RT".to_vec(), Object::name("Group"));
|
||||
d.set(b"IT".to_vec(), Object::name("Replace"));
|
||||
d.set(b"Subj".to_vec(), PdfString::text("Replace Text"));
|
||||
})?;
|
||||
doc.update_dict(sr, |d| {
|
||||
d.set(b"IT".to_vec(), Object::name("StrikeOutTextEdit"));
|
||||
d.set(b"IRT".to_vec(), Object::Ref(cr));
|
||||
d.set(b"RT".to_vec(), Object::name("Group"));
|
||||
})?;
|
||||
Ok(s)
|
||||
}
|
||||
|
||||
|
||||
+135
-7
@@ -1264,22 +1264,36 @@ fn replace_text_groups_a_strikeout_and_a_caret() {
|
||||
let strike = &a[i];
|
||||
assert_eq!((strike.name(b"Subtype"), strike.name(b"IT")), (Some(&b"StrikeOut"[..]), Some(&b"StrikeOutTextEdit"[..])));
|
||||
let caret = a.iter().find(|d| d.name(b"Subtype") == Some(b"Caret")).unwrap();
|
||||
assert_eq!((text(caret, b"Contents").as_str(), caret.name(b"RT")), ("new words", Some(&b"Group"[..])));
|
||||
assert!(caret.reference(b"IRT").is_some());
|
||||
// The caret is the group's primary: a group's text is read from its primary and the
|
||||
// subordinates' Contents are ignored (ISO 32000-2 §12.5.6.2), so the replacement is on it.
|
||||
assert_eq!((text(caret, b"Contents").as_str(), caret.name(b"IT")), ("new words", Some(&b"Replace"[..])));
|
||||
assert!(caret.get(b"IRT").is_none() && caret.get(b"RT").is_none(), "a primary has no /IRT: {caret:?}");
|
||||
assert_eq!(strike.name(b"RT"), Some(&b"Group"[..]));
|
||||
assert!(text(strike, b"Contents").is_empty());
|
||||
// #2666: the pair needs its own `/NM` each. XFDF names a reply by the `/NM` of what it
|
||||
// replies to, so sharing one id writes `inreplyto` equal to the caret's own `name` and the
|
||||
// pair does not survive an export and import.
|
||||
assert_eq!(text(caret, b"NM").as_str(), "r-caret");
|
||||
assert_eq!(text(strike, b"NM").as_str(), "r");
|
||||
assert_ne!(text(caret, b"NM"), text(strike, b"NM"), "the caret must not carry the strikeout's name");
|
||||
let irt = caret.reference(b"IRT").unwrap();
|
||||
assert_eq!(text(doc.get(irt).as_dict().unwrap(), b"NM").as_str(), "r", "the caret replies to the strikeout");
|
||||
let irt = strike.reference(b"IRT").unwrap();
|
||||
assert_eq!(text(doc.get(irt).as_dict().unwrap(), b"NM").as_str(), "r-caret", "the strikeout is grouped under the caret");
|
||||
let r = rect(caret);
|
||||
assert!(r[0] < 200.0 && r[2] > 200.0 && r[1] < 706.0, "at the end of the line, below its baseline: {r:?}");
|
||||
// Deleting the strikeout takes the caret with it (the group).
|
||||
// Deleting either one takes the other with it (the proposal is one comment).
|
||||
let marks = |doc: &Document| list(doc, 0).iter().filter(|d| matches!(d.name(b"Subtype"), Some(b"Caret" | b"StrikeOut"))).count();
|
||||
let mut by_strike = doc.clone();
|
||||
delete_annotation(&mut by_strike, 0, i).unwrap();
|
||||
assert_eq!(marks(&by_strike), 0, "deleting the strikeout deletes the caret");
|
||||
let mut doc = doc;
|
||||
delete_annotation(&mut doc, 0, i).unwrap();
|
||||
assert!(!list(&doc, 0).iter().any(|d| d.name(b"Subtype") == Some(b"Caret")));
|
||||
let c = list(&doc, 0).iter().position(|d| d.name(b"Subtype") == Some(b"Caret")).unwrap();
|
||||
// A locked caret keeps the strikeout too: the pair can't be broken by deleting the other.
|
||||
let mut locked = doc.clone();
|
||||
set_locked(&mut locked, 0, c, true).unwrap();
|
||||
assert!(deletable(&locked, 0, i).is_err() && delete_annotation(&mut locked, 0, i).is_err(), "a locked caret refuses its strikeout's deletion");
|
||||
assert_eq!(marks(&locked), 2);
|
||||
delete_annotation(&mut doc, 0, c).unwrap();
|
||||
assert_eq!(marks(&doc), 0, "deleting the caret deletes the strikeout");
|
||||
assert!(
|
||||
add_text_replacement(
|
||||
&mut doc,
|
||||
@@ -1298,6 +1312,55 @@ fn replace_text_groups_a_strikeout_and_a_caret() {
|
||||
);
|
||||
}
|
||||
|
||||
/// Review on #5689 (CodeRabbit): clicking a Replace Text strikeout selects its caret, the
|
||||
/// group's primary, so a restyle from Comment Properties lands on the caret. Colour and opacity
|
||||
/// are the proposal's, so the strikeout is restyled and redrawn in the same edit, whichever
|
||||
/// member is restyled; it takes no border width. A locked member refuses the whole change.
|
||||
#[test]
|
||||
fn restyling_a_replace_text_pair_restyles_both_members() {
|
||||
let mut doc = fixture();
|
||||
let quads = [[100.0, 720.0, 200.0, 720.0, 100.0, 706.0, 200.0, 706.0]];
|
||||
let red = Style { color: [0.89, 0.13, 0.13], opacity: 1.0, width: 1.0, fill: None, ..Style::default() };
|
||||
let tr = TextReplacement {
|
||||
page: 0,
|
||||
quads: &quads,
|
||||
replacement: "new words",
|
||||
author: "Ada",
|
||||
strike: &red,
|
||||
caret: &red,
|
||||
strike_meta: &meta("r"),
|
||||
caret_meta: &meta("r-caret"),
|
||||
};
|
||||
let s = add_text_replacement(&mut doc, tr).unwrap();
|
||||
let c = list(&doc, 0).iter().position(|d| d.name(b"Subtype") == Some(b"Caret")).unwrap();
|
||||
let color = |doc: &Document, i: usize| {
|
||||
list(doc, 0)[i].get(b"C").and_then(|o| o.as_array().cloned()).unwrap().iter().filter_map(Object::as_f64).collect::<Vec<_>>()
|
||||
};
|
||||
let green = [0.0, 0.5, 0.0];
|
||||
|
||||
// Restyled through the caret (what a click on either part selects).
|
||||
let mut by_caret = doc.clone();
|
||||
set_style(&mut by_caret, 0, c, StyleChange::new(Some(green), Some(0.5), Some(3.0), None), &meta("")).unwrap();
|
||||
let by_caret = reopen(&by_caret);
|
||||
assert_eq!(color(&by_caret, c), green.to_vec());
|
||||
assert_eq!(color(&by_caret, s), green.to_vec(), "the strikeout takes the proposal's colour");
|
||||
let strike = &list(&by_caret, 0)[s];
|
||||
assert_eq!(strike.get(b"CA").and_then(Object::as_f64), Some(0.5), "and its opacity");
|
||||
assert!(strike.get(b"BS").is_none(), "a strikeout has no border to widen: {strike:?}");
|
||||
assert!(ap_content(&by_caret, strike).contains("0 0.5 0 RG"), "its appearance is redrawn: {}", ap_content(&by_caret, strike));
|
||||
|
||||
// Restyled through the strikeout: the caret follows.
|
||||
let mut by_strike = doc.clone();
|
||||
set_style(&mut by_strike, 0, s, StyleChange::new(Some(green), None, None, None), &meta("")).unwrap();
|
||||
assert_eq!(color(&by_strike, c), green.to_vec(), "the caret takes the proposal's colour");
|
||||
|
||||
// A locked strikeout refuses the change, and nothing moves.
|
||||
let mut locked = doc.clone();
|
||||
set_locked(&mut locked, 0, s, true).unwrap();
|
||||
assert!(set_style(&mut locked, 0, c, StyleChange::new(Some(green), None, None, None), &meta("")).is_err());
|
||||
assert_eq!(color(&locked, c), red.color.to_vec(), "the caret keeps its colour");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn files_attach_as_comments() {
|
||||
let mut doc = fixture();
|
||||
@@ -2786,6 +2849,71 @@ fn indirect_typewriter_names_keep_outer_whitespace_in_summaries() {
|
||||
check(&reopen(&doc));
|
||||
}
|
||||
|
||||
/// PDFBOX-2699: a `/C` written `[1 0 0 null]` (Table 166 asks for numbers) is still a four-entry
|
||||
/// colour, CMYK with the null as 0 as PDFium, MuPDF and Poppler read it, so a shape without an
|
||||
/// appearance is drawn instead of dropped. `/IC` is read the same way, and three numbers stay RGB.
|
||||
/// The properties and the comment list report the colours as drawn.
|
||||
#[test]
|
||||
fn a_four_entry_colour_with_a_null_is_cmyk_with_zero() {
|
||||
let doc = document_of(&[
|
||||
b"<< /Type /Catalog /Pages 2 0 R >>",
|
||||
b"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 100 40] >>",
|
||||
b"<< /Type /Page /Parent 2 0 R /Annots [4 0 R 5 0 R] >>",
|
||||
b"<< /Type /Annot /Subtype /Square /Rect [5 5 45 35] /C [1 0 0 null] /IC [0 0 1 null] >>",
|
||||
b"<< /Type /Annot /Subtype /Square /Rect [55 5 95 35] /C [1 0 0] >>",
|
||||
]);
|
||||
let display = with_missing_appearances(&doc).expect("both squares get a fallback appearance");
|
||||
let squares = list(&display, 0);
|
||||
let cmyk = ap_content(&display, &squares[0]);
|
||||
assert!(cmyk.contains("0 1 1 RG") && cmyk.contains("1 1 0 rg"), "CMYK (1,0,0,0) stroke and (0,0,1,0) fill: {cmyk}");
|
||||
let rgb = ap_content(&display, &squares[1]);
|
||||
assert!(rgb.contains("1 0 0 RG"), "three numbers stay RGB: {rgb}");
|
||||
// The properties read the stroke and the fill as they are drawn.
|
||||
let p = props(&doc, 0, 0).expect("the square has properties");
|
||||
assert_eq!((p.color, p.fill), (Some([0.0, 1.0, 1.0]), Some([1.0, 1.0, 0.0])));
|
||||
assert_eq!(props(&doc, 0, 1).and_then(|p| p.color), Some([1.0, 0.0, 0.0]));
|
||||
// The comment list reports the same colours.
|
||||
let colors: Vec<Option<[f32; 3]>> = summaries(&doc).iter().map(|s| s.color).collect();
|
||||
assert_eq!(colors, [Some([0.0, 1.0, 1.0]), Some([1.0, 0.0, 0.0])]);
|
||||
}
|
||||
|
||||
/// A `/C` given by reference is followed for the comment list, as three numbers were, and read
|
||||
/// like a direct one: `[0 0 1 null]` is CMYK yellow, and a referenced grey level is grey.
|
||||
#[test]
|
||||
fn a_referenced_colour_is_listed_like_a_direct_one() {
|
||||
let doc = document_of(&[
|
||||
b"<< /Type /Catalog /Pages 2 0 R >>",
|
||||
b"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 100 40] >>",
|
||||
b"<< /Type /Page /Parent 2 0 R /Annots [4 0 R 5 0 R] >>",
|
||||
b"<< /Type /Annot /Subtype /Square /Rect [5 5 45 35] /C 6 0 R >>",
|
||||
b"<< /Type /Annot /Subtype /Circle /Rect [55 5 95 35] /C 7 0 R >>",
|
||||
b"[0 0 1 null]",
|
||||
b"[0.5]",
|
||||
]);
|
||||
let colors: Vec<Option<[f32; 3]>> = summaries(&doc).iter().map(|s| s.color).collect();
|
||||
assert_eq!(colors, [Some([1.0, 1.0, 0.0]), Some([0.5, 0.5, 0.5])]);
|
||||
}
|
||||
|
||||
/// A reference among the four entries is not a non-number read as 0: `/C [1 0 0 6 0 R]` with
|
||||
/// object 6 the number 1 is CMYK black (§7.3.10), so drawing it cyan would be wrong. The builder
|
||||
/// doesn't follow it and draws no appearance, as for any colour it can't read.
|
||||
#[test]
|
||||
fn a_four_entry_colour_with_a_reference_is_not_read_as_zero() {
|
||||
let doc = document_of(&[
|
||||
b"<< /Type /Catalog /Pages 2 0 R >>",
|
||||
b"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 100 40] >>",
|
||||
b"<< /Type /Page /Parent 2 0 R /Annots [4 0 R 5 0 R] >>",
|
||||
b"<< /Type /Annot /Subtype /Square /Rect [5 5 45 35] /C [1 0 0 6 0 R] >>",
|
||||
b"<< /Type /Annot /Subtype /Square /Rect [55 5 95 35] /C [1 0 0] >>",
|
||||
b"1",
|
||||
]);
|
||||
let display = with_missing_appearances(&doc).expect("the RGB square gets a fallback appearance");
|
||||
let squares = list(&display, 0);
|
||||
assert!(!squares[0].contains(b"AP"), "no cyan stand-in for CMYK black");
|
||||
assert_eq!(props(&doc, 0, 0).and_then(|p| p.color), None);
|
||||
assert_eq!(summaries(&doc)[0].color, None, "nor in the comment list");
|
||||
}
|
||||
|
||||
/// The `y` of every `1 0 0 1 x y Tm` in `content`: where each piece of text sits.
|
||||
fn baselines(content: &str) -> Vec<f64> {
|
||||
content.split(" Tm").filter_map(|s| s.rsplit(' ').next()?.parse().ok()).collect()
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
Layer L4 (may use `edit`): verification tooling, the faux-redaction audit.
|
||||
|
||||
```rust
|
||||
let findings: Vec<Finding> = audit_redactions(&doc)?; // page, kind, rect, covered_text
|
||||
let findings: Vec<AuditFinding> = audit_redactions(&doc)?; // page, kind, rect, covered_text
|
||||
```
|
||||
|
||||
It reports two kinds of finding:
|
||||
|
||||
@@ -288,7 +288,14 @@ Example: `form_set_props doc=1 field=agree export_value=Accepted widget=1`.
|
||||
reference) to a PNG, without the viewer. `model` picks the page's Nth 3D model (default 1);
|
||||
`width` and `height` are 1 to 4096 (default 512); `direction` is the view direction from the eye
|
||||
(default `[-1, 1, -1]`, with Z up unless the view looks along Z); `perspective` defaults to true.
|
||||
The model is framed to fill the image and shaded by a headlight on white. U3D models are refused
|
||||
The model is framed to fill the image and shaded by a headlight on white. `orbit`, instead of
|
||||
`direction`, frames it as a viewer's orbit control would: `{view, up, front, turn, zoom,
|
||||
zoom_at, pan}`, all optional. `view` is `iso` (default), `front`, `right`, `top` or `back`
|
||||
about the `up` axis (default `+z`) and the `front` axis (perpendicular to `up`); `turn` is
|
||||
`[yaw, pitch]` in degrees, pitch down; `zoom` is a positive factor, the result held within 0.05 to 50, at `zoom_at` `[right, up]`
|
||||
in picture heights from the centre, where the point under it stays still; `pan` `[right, up]`
|
||||
moves the target, in model radii, so the model moves the other way. Every view frames the model
|
||||
at the same size, whatever its direction. U3D models are refused
|
||||
with an error, and the annotation's own views, lighting and render modes are not applied yet.
|
||||
|
||||
## Viewer navigation history
|
||||
|
||||
+239
-25
@@ -8,6 +8,8 @@ use super::json::Args;
|
||||
use super::paths::read_input;
|
||||
use super::{Arc, Automation, Path, PathBuf};
|
||||
|
||||
const MAX_BATES_BYTES: u64 = 512 * 1024 * 1024;
|
||||
|
||||
struct FilePlan {
|
||||
input: String,
|
||||
source: PathBuf,
|
||||
@@ -26,19 +28,23 @@ impl Automation {
|
||||
}
|
||||
let start = match args.0.get("start_number") {
|
||||
None | Some(Value::Null) => 1,
|
||||
Some(value) => value
|
||||
.as_u64()
|
||||
.filter(|n| *n >= 1)
|
||||
.ok_or_else(|| ToolError::InvalidArgs("start_number must be a whole number of at least 1".into()))?,
|
||||
Some(value) => {
|
||||
value.as_u64().filter(|n| *n >= 1).ok_or_else(|| ToolError::InvalidArgs("start_number must be an integer of at least 1".into()))?
|
||||
}
|
||||
};
|
||||
let digits = args.opt_int("digits")?.unwrap_or(6);
|
||||
let digits =
|
||||
u8::try_from(digits).ok().filter(|d| (1..=12).contains(d)).ok_or_else(|| ToolError::InvalidArgs("digits must be from 1 to 12".into()))?;
|
||||
let prefix = args.opt_str("prefix")?.unwrap_or("");
|
||||
let suffix = args.opt_str("suffix")?.unwrap_or("");
|
||||
// `#` separates the token's fields and `>>` ends it: either would cut the token short.
|
||||
if prefix.len() > 128 || suffix.len() > 128 || [prefix, suffix].iter().any(|s| s.contains('#') || s.contains(">>")) {
|
||||
return Err(ToolError::InvalidArgs("prefix and suffix must be at most 128 bytes and cannot contain # or >>".into()));
|
||||
if prefix.chars().count() > 128
|
||||
|| suffix.chars().count() > 128
|
||||
|| prefix.contains('#')
|
||||
|| suffix.contains('#')
|
||||
|| prefix.contains(">>")
|
||||
|| suffix.contains(">>")
|
||||
{
|
||||
return Err(ToolError::InvalidArgs("prefix and suffix must be at most 128 characters and cannot contain # or >>".into()));
|
||||
}
|
||||
let dry_run = args.opt_bool("dry_run")?.unwrap_or(false);
|
||||
|
||||
@@ -70,16 +76,7 @@ impl Automation {
|
||||
targets.push((output.to_string(), target));
|
||||
passwords.push(entry.get("password").and_then(Value::as_str).map(str::to_owned));
|
||||
}
|
||||
let input_paths: std::collections::HashSet<_> = sources.iter().map(|(_, path)| path.clone()).collect();
|
||||
let mut output_paths = std::collections::HashSet::new();
|
||||
for (name, path) in &targets {
|
||||
if input_paths.contains(path) {
|
||||
return Err(failed(format!("output {name} names an input file; choose a separate output path")));
|
||||
}
|
||||
if !output_paths.insert(path.clone()) {
|
||||
return Err(failed(format!("two files use the same output path: {name}")));
|
||||
}
|
||||
}
|
||||
check_unique_outputs(&targets, dry_run)?;
|
||||
|
||||
let mut plans = Vec::with_capacity(files.len());
|
||||
let mut next = start;
|
||||
@@ -88,13 +85,13 @@ impl Automation {
|
||||
let size = std::fs::metadata(input_path).map_err(failed)?.len();
|
||||
input_bytes = input_bytes
|
||||
.checked_add(size)
|
||||
.filter(|total| *total <= 512 * 1024 * 1024)
|
||||
.filter(|total| *total <= MAX_BATES_BYTES)
|
||||
.ok_or_else(|| failed("combined Bates input exceeds the 512 MiB safety limit"))?;
|
||||
let bytes = read_input(input_path)?;
|
||||
input_bytes = input_bytes
|
||||
.saturating_sub(size)
|
||||
.checked_add(u64::try_from(bytes.len()).unwrap_or(u64::MAX))
|
||||
.filter(|total| *total <= 512 * 1024 * 1024)
|
||||
.filter(|total| *total <= MAX_BATES_BYTES)
|
||||
.ok_or_else(|| failed("combined Bates input exceeds the 512 MiB safety limit"))?;
|
||||
let display_name = input_path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
let password = passwords.get(index).and_then(Option::as_deref);
|
||||
@@ -106,7 +103,8 @@ impl Automation {
|
||||
return Err(failed(format!("{input_name} has no pages to number")));
|
||||
}
|
||||
let count = u64::try_from(pages).map_err(|_| failed(format!("page count is too large for {input_name}")))?;
|
||||
let last = next.checked_add(count.saturating_sub(1)).ok_or_else(|| failed(format!("Bates number range overflows for {input_name}")))?;
|
||||
let last_offset = count.checked_sub(1).ok_or_else(|| failed(format!("{input_name} has no pages to number")))?;
|
||||
let last = next.checked_add(last_offset).ok_or_else(|| failed(format!("Bates number range overflows for {input_name}")))?;
|
||||
plans.push(FilePlan {
|
||||
input: input_name.clone(),
|
||||
source: input_path.clone(),
|
||||
@@ -116,7 +114,7 @@ impl Automation {
|
||||
first: next,
|
||||
last,
|
||||
});
|
||||
if index + 1 < sources.len() {
|
||||
if index + 1 < files.len() {
|
||||
next = last.checked_add(1).ok_or_else(|| failed(format!("Bates sequence overflows after {input_name}")))?;
|
||||
}
|
||||
}
|
||||
@@ -163,12 +161,14 @@ impl Automation {
|
||||
let result = applied.and_then(|()| self.session.save_full_bytes(id));
|
||||
match result {
|
||||
Ok(bytes) => {
|
||||
let total = output_bytes.saturating_add(u64::try_from(bytes.len()).unwrap_or(u64::MAX));
|
||||
if total > 512 * 1024 * 1024 {
|
||||
results.push(json!({"input":plan.input,"output":plan.output,"status":"error","pages":plan.pages,"first":plan.first,"last":plan.last,"error":"combined Bates output exceeds the 512 MiB safety limit"}));
|
||||
} else {
|
||||
let candidate = output_bytes
|
||||
.checked_add(u64::try_from(bytes.len()).unwrap_or(u64::MAX))
|
||||
.filter(|total| *total <= MAX_BATES_BYTES);
|
||||
if let Some(total) = candidate {
|
||||
output_bytes = total;
|
||||
staged.push((plan.output.clone(), bytes));
|
||||
} else {
|
||||
results.push(json!({"input":plan.input,"output":plan.output,"status":"error","pages":plan.pages,"first":plan.first,"last":plan.last,"error":"combined Bates output exceeds the 512 MiB safety limit"}));
|
||||
}
|
||||
}
|
||||
Err(error) => results.push(json!({"input":plan.input,"output":plan.output,"status":"error","pages":plan.pages,"first":plan.first,"last":plan.last,"error":error.to_string()})),
|
||||
@@ -198,6 +198,123 @@ impl Automation {
|
||||
}
|
||||
}
|
||||
|
||||
fn check_unique_outputs(targets: &[(String, PathBuf)], dry_run: bool) -> Result<()> {
|
||||
if targets.len() < 2 {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// Probe exact basenames in a directory under each canonical parent, so the filesystem applies its own name rules.
|
||||
let mut groups: std::collections::HashMap<PathBuf, (PathBuf, Vec<(String, std::ffi::OsString)>)> = std::collections::HashMap::new();
|
||||
for (name, target) in targets {
|
||||
let parent = target.parent().ok_or_else(|| failed(format!("output has no parent directory: {name}")))?;
|
||||
let identity = parent.canonicalize().map_err(failed)?;
|
||||
let probe_name = output_probe_name(target).map_err(failed)?;
|
||||
groups.entry(identity.clone()).or_insert_with(|| (identity, Vec::new())).1.push((name.clone(), probe_name));
|
||||
}
|
||||
|
||||
if dry_run {
|
||||
// Dry runs cannot probe the volume: Windows uses a conservative case-insensitive comparison,
|
||||
// while Unix preserves case, so unusual case-sensitive Windows or case-insensitive Unix volumes can differ.
|
||||
for (_, (_, names)) in groups {
|
||||
for (index, (name, candidate)) in names.iter().enumerate() {
|
||||
if names.iter().take(index).any(|(_, prior)| same_output_name(prior, candidate)) {
|
||||
return Err(failed(format!("two files use the same output path: {name}")));
|
||||
}
|
||||
}
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
for (_, (parent, names)) in groups {
|
||||
match tempfile::tempdir_in(&parent) {
|
||||
Ok(probes) => {
|
||||
for (name, probe_name) in names {
|
||||
let probe = probes.path().join(probe_name);
|
||||
match std::fs::OpenOptions::new().write(true).create_new(true).open(&probe) {
|
||||
Ok(file) => drop(file),
|
||||
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {
|
||||
return Err(failed(format!("two files use the same output path: {name}")));
|
||||
}
|
||||
Err(error) => return Err(failed(format!("could not validate output path {name}: {error}"))),
|
||||
}
|
||||
}
|
||||
}
|
||||
#[cfg(windows)]
|
||||
Err(error) if error.kind() == std::io::ErrorKind::PermissionDenied => probe_files_for_resolved_outputs(&parent, names)?,
|
||||
Err(error) => return Err(failed(error)),
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn probe_files_for_resolved_outputs(parent: &Path, names: Vec<(String, std::ffi::OsString)>) -> Result<()> {
|
||||
use std::os::windows::fs::OpenOptionsExt;
|
||||
|
||||
const FILE_FLAG_DELETE_ON_CLOSE: u32 = 0x0400_0000;
|
||||
let mut probes = Vec::with_capacity(names.len());
|
||||
for (name, probe_name) in names {
|
||||
let probe = parent.join(probe_name);
|
||||
let mut options = std::fs::OpenOptions::new();
|
||||
options.write(true).create_new(true).share_mode(0).custom_flags(FILE_FLAG_DELETE_ON_CLOSE);
|
||||
match options.open(&probe) {
|
||||
Ok(file) => probes.push(file),
|
||||
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {
|
||||
return Err(failed(format!("two files use the same output path: {name}")));
|
||||
}
|
||||
Err(error) => return Err(failed(format!("could not validate output path {name}: {error}"))),
|
||||
}
|
||||
}
|
||||
drop(probes);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn same_output_name(left: &std::ffi::OsStr, right: &std::ffi::OsStr) -> bool {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::ffi::OsStrExt;
|
||||
fn key(name: &std::ffi::OsStr) -> Vec<u32> {
|
||||
std::char::decode_utf16(name.encode_wide())
|
||||
.map(|decoded| match decoded {
|
||||
Ok(character) => {
|
||||
let mut uppercase = character.to_uppercase();
|
||||
match (uppercase.next(), uppercase.next()) {
|
||||
(Some(single), None) => single as u32,
|
||||
_ => character as u32,
|
||||
}
|
||||
}
|
||||
Err(error) => 0x11_0000 + u32::from(error.unpaired_surrogate()),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
return key(left) == key(right);
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
left == right
|
||||
}
|
||||
}
|
||||
|
||||
fn output_probe_name(path: &Path) -> std::io::Result<std::ffi::OsString> {
|
||||
let name = path.file_name().ok_or_else(|| std::io::Error::new(std::io::ErrorKind::InvalidInput, "output has no file name"))?;
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::ffi::{OsStrExt, OsStringExt};
|
||||
let is_verbatim = path.components().any(|component| matches!(component, std::path::Component::Prefix(prefix) if matches!(prefix.kind(), std::path::Prefix::Verbatim(_) | std::path::Prefix::VerbatimUNC(_, _) | std::path::Prefix::VerbatimDisk(_))));
|
||||
let mut wide: Vec<u16> = name.encode_wide().collect();
|
||||
if !is_verbatim {
|
||||
while wide.last().is_some_and(|unit| *unit == u16::from(b'.') || *unit == u16::from(b' ')) {
|
||||
wide.pop();
|
||||
}
|
||||
}
|
||||
return Ok(std::ffi::OsString::from_wide(&wide));
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
Ok(name.to_os_string())
|
||||
}
|
||||
}
|
||||
|
||||
/// Publish a PDF atomically while refusing a target created by another process after preflight.
|
||||
pub(super) fn publish_new(path: &Path, bytes: &[u8]) -> Result<()> {
|
||||
let parent = path.parent().ok_or_else(|| failed("output has no parent directory"))?;
|
||||
@@ -212,3 +329,100 @@ pub(super) fn publish_new(path: &Path, bytes: &[u8]) -> Result<()> {
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::check_unique_outputs;
|
||||
|
||||
#[test]
|
||||
fn dry_run_path_check_creates_no_probe_files() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("same.pdf");
|
||||
let targets = vec![("first.pdf".into(), path.clone()), ("second.pdf".into(), path)];
|
||||
assert!(check_unique_outputs(&targets, true).is_err());
|
||||
assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 0);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn dry_run_detects_output_parent_aliases_without_writing() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let alias = dir.path().join("alias");
|
||||
std::os::unix::fs::symlink(dir.path(), &alias).unwrap();
|
||||
let first = dir.path().join("same.pdf");
|
||||
let second = alias.join("same.pdf");
|
||||
let targets = vec![("first.pdf".into(), first), ("second.pdf".into(), second)];
|
||||
assert!(check_unique_outputs(&targets, true).is_err());
|
||||
assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn long_output_names_fit_in_probe_directory() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let first = dir.path().join(format!("{}.pdf", "a".repeat(220)));
|
||||
let second = dir.path().join(format!("{}.pdf", "b".repeat(220)));
|
||||
let targets = vec![("first.pdf".into(), first), ("second.pdf".into(), second)];
|
||||
assert!(check_unique_outputs(&targets, false).is_ok());
|
||||
assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 0);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn output_probe_paths_preserve_non_utf8_names() {
|
||||
use std::os::unix::ffi::OsStringExt;
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let first = dir.path().join(std::ffi::OsString::from_vec(vec![b'o', 0xff]));
|
||||
let second = dir.path().join(std::ffi::OsString::from_vec(vec![b'o', 0xfe]));
|
||||
let targets = vec![("first.pdf".into(), first), ("second.pdf".into(), second)];
|
||||
assert!(check_unique_outputs(&targets, false).is_ok());
|
||||
assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 0);
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn windows_probe_names_trim_only_non_verbatim_paths() {
|
||||
use std::ffi::OsString;
|
||||
use std::path::Path;
|
||||
|
||||
let normal = Path::new(r"C:\root\report.pdf. ");
|
||||
assert_eq!(super::output_probe_name(normal).unwrap(), OsString::from("report.pdf"));
|
||||
|
||||
let verbatim = Path::new(r"\\?\C:\root\report.pdf. ");
|
||||
assert_eq!(super::output_probe_name(verbatim).unwrap(), OsString::from("report.pdf. "));
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn dry_run_detects_case_only_output_collisions_without_writing() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let first = dir.path().join("Case.pdf");
|
||||
let second = dir.path().join("CASE.pdf");
|
||||
let targets = vec![("first.pdf".into(), first), ("second.pdf".into(), second)];
|
||||
assert!(check_unique_outputs(&targets, true).is_err());
|
||||
assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 0);
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn permission_denied_child_directory_uses_delete_on_close_file_probes() {
|
||||
use std::process::Command;
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let identity = Command::new("whoami.exe").args(["/user", "/fo", "csv", "/nh"]).output().unwrap();
|
||||
assert!(identity.status.success());
|
||||
let identity = String::from_utf8(identity.stdout).unwrap();
|
||||
let sid = identity.split('"').nth(3).unwrap();
|
||||
let acl = Command::new("icacls.exe").arg(dir.path()).arg("/deny").arg(format!("*{sid}:(AD)")).status().unwrap();
|
||||
assert!(acl.success());
|
||||
|
||||
assert!(matches!(tempfile::tempdir_in(dir.path()), Err(error) if error.kind() == std::io::ErrorKind::PermissionDenied));
|
||||
let direct_probe = dir.path().join("direct-probe");
|
||||
let file = std::fs::OpenOptions::new().write(true).create_new(true).open(&direct_probe).unwrap();
|
||||
drop(file);
|
||||
std::fs::remove_file(&direct_probe).unwrap();
|
||||
|
||||
let targets = vec![("first.pdf".into(), dir.path().join("first.pdf")), ("second.pdf".into(), dir.path().join("second.pdf"))];
|
||||
assert!(check_unique_outputs(&targets, false).is_ok());
|
||||
assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 0);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -490,8 +490,12 @@ impl Automation {
|
||||
if contents.trim().is_empty() {
|
||||
return Err(ToolError::InvalidArgs("replace needs `contents`: the replacement text".into()));
|
||||
}
|
||||
// `/C` is a group attribute, taken from the primary (ISO 32000-2 §12.5.6.2), so the
|
||||
// caret carries the colour too. Only the colour: opacity and the rest are the
|
||||
// caret's own.
|
||||
let mut caret = Style::default_for(&Shape::Caret { rect: [0.0; 4] });
|
||||
caret.color = style.color;
|
||||
let strike = style;
|
||||
let caret = Style::default_for(&Shape::Caret { rect: [0.0; 4] });
|
||||
let mut out = self.apply(a, Edit::ReplaceText { page, quads, text: contents, author, strike, caret })?;
|
||||
out["comment"] = json!({ "page": page + 1, "type": "replace" });
|
||||
return Ok(out);
|
||||
|
||||
@@ -5,10 +5,13 @@
|
||||
//! holds the two folders. Every path a tool reads is checked with [`Access::Read`] and every path
|
||||
//! it writes with [`Access::Write`], in `Automation::resolve`, which all of them go through:
|
||||
//!
|
||||
//! - The path is made absolute against the working directory, as the file system reads it. Its
|
||||
//! links are followed: for a file that doesn't exist yet, the links of its nearest existing
|
||||
//! folder, the rest of the path being plain names (`..` below a missing folder is refused, and so
|
||||
//! is a link that leads nowhere).
|
||||
//! - The path is made absolute against the working directory, then followed the way the file
|
||||
//! system reads it, one name at a time from the top, its links followed. A name is looked up
|
||||
//! only while the folder it is in is the root, inside it, or one of the root's own parent
|
||||
//! folders: a path that leaves those is refused before anything beyond is touched (looking up
|
||||
//! `/net/<host>` mounts it), and every such refusal reads the same, so it can't tell what exists
|
||||
//! out there. Inside the root, a name that doesn't exist yet ends the walk and the rest is taken
|
||||
//! as plain names (`..` below a missing folder is refused, and so is a link that leads nowhere).
|
||||
//! - A path on another network share or in a device namespace (`\\host\share`, `\\.\pipe\x`)
|
||||
//! than the root's is refused by name, before anything is resolved: resolving it would contact
|
||||
//! the host.
|
||||
@@ -20,7 +23,6 @@
|
||||
//! folders in between (swapping in a link) can still win that race. The roots keep an agent to the
|
||||
//! files it was given; they don't guard against other programs on the computer.
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -100,11 +102,10 @@ impl AutomationRoots {
|
||||
Access::Write => Err(format!("automation filesystem access is not granted: write authority is absent: {shown}")),
|
||||
};
|
||||
};
|
||||
let absolute = absolute(shown, target)?;
|
||||
// Another network share or a device is refused by name, as `--root` refuses it: even
|
||||
// resolving the path would contact the host (#4003).
|
||||
if !foreign_share(&absolute, folder) && inside(&resolve(shown, &absolute)?, folder) {
|
||||
return Ok(());
|
||||
match follow(shown, &absolute(shown, target)?, folder) {
|
||||
Toward::Inside => return Ok(()),
|
||||
Toward::Refused(why) => return Err(why),
|
||||
Toward::Outside => {}
|
||||
}
|
||||
let root = root_shown.display();
|
||||
match access {
|
||||
@@ -141,42 +142,66 @@ fn absolute(shown: &str, path: &Path) -> Result<PathBuf, String> {
|
||||
std::path::absolute(path).map_err(|e| format!("automation path rejected: cannot resolve {shown}: {e}"))
|
||||
}
|
||||
|
||||
/// `absolute` with its links followed; for a path that doesn't exist (yet), its nearest existing
|
||||
/// folder's links followed and the rest appended.
|
||||
fn resolve(shown: &str, absolute: &Path) -> Result<PathBuf, String> {
|
||||
// The names below the nearest existing folder, last first.
|
||||
let mut missing: Vec<OsString> = vec![];
|
||||
let mut at = absolute;
|
||||
loop {
|
||||
match std::fs::canonicalize(at) {
|
||||
Ok(mut found) => {
|
||||
found.extend(missing.iter().rev());
|
||||
return Ok(found);
|
||||
/// Where a followed path ends up.
|
||||
pub(crate) enum Toward {
|
||||
/// Inside the root, with its links followed (a missing tail taken as names).
|
||||
Inside,
|
||||
/// Anywhere else. Said the same way whatever is out there.
|
||||
Outside,
|
||||
/// Inside the root, but it can't be followed, and why.
|
||||
Refused(String),
|
||||
}
|
||||
|
||||
/// Follow the absolute `path` the way the file system reads it, one name at a time from the top,
|
||||
/// looking a name up only while the folder it is in is `root`, inside it, or one of `root`'s own
|
||||
/// parent folders (all with their links followed already, so `..` means what it means to the file
|
||||
/// system).
|
||||
pub(crate) fn follow(shown: &str, path: &Path, root: &Path) -> Toward {
|
||||
// Another network share or a device is refused by name, as `--root` refuses it: even looking
|
||||
// it up would contact the host (#4003).
|
||||
if foreign_share(path, root) {
|
||||
return Toward::Outside;
|
||||
}
|
||||
let near = |at: &Path| inside(at, root) || inside(root, at);
|
||||
let mut parts = path.components().peekable();
|
||||
let top: PathBuf = std::iter::from_fn(|| parts.next_if(|c| matches!(c, Component::Prefix(_) | Component::RootDir))).collect();
|
||||
let mut at = match std::fs::canonicalize(&top) {
|
||||
Ok(at) if near(&at) => at,
|
||||
_ => return Toward::Outside,
|
||||
};
|
||||
while let Some(part) = parts.next() {
|
||||
let name = match part {
|
||||
Component::Normal(name) => name,
|
||||
Component::CurDir => continue,
|
||||
Component::ParentDir => {
|
||||
at.pop();
|
||||
continue;
|
||||
}
|
||||
Err(e) => match std::fs::symlink_metadata(at) {
|
||||
Ok(m) if m.file_type().is_symlink() => return Err(format!("automation path rejected: a link that leads nowhere: {shown}")),
|
||||
// There, yet its real path can't be had (no permission): nothing to compare.
|
||||
Ok(_) => return Err(format!("automation path rejected: cannot resolve {shown}: {e}")),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
|
||||
Err(e) => return Err(format!("automation path rejected: cannot resolve {shown}: {e}")),
|
||||
},
|
||||
}
|
||||
let parent = at.parent();
|
||||
match (at.components().next_back(), parent) {
|
||||
(Some(Component::Normal(name)), Some(parent)) => {
|
||||
missing.push(name.to_os_string());
|
||||
at = parent;
|
||||
}
|
||||
(Some(Component::ParentDir), _) => {
|
||||
return Err(format!("automation path rejected: parent traversal below a folder that doesn't exist: {shown}"));
|
||||
}
|
||||
// Down to the root (or drive) and it doesn't exist either.
|
||||
_ => {
|
||||
let e = std::io::Error::from(std::io::ErrorKind::NotFound);
|
||||
return Err(format!("automation path rejected: cannot resolve {shown}: {e}"));
|
||||
Component::Prefix(_) | Component::RootDir => return Toward::Outside,
|
||||
};
|
||||
let next = at.join(name);
|
||||
match std::fs::canonicalize(&next) {
|
||||
Ok(found) if near(&found) => at = found,
|
||||
Ok(_) => return Toward::Outside,
|
||||
// Not even there yet: only inside the root does it matter why.
|
||||
Err(_) if !inside(&at, root) => return Toward::Outside,
|
||||
Err(e) => {
|
||||
return match std::fs::symlink_metadata(&next) {
|
||||
Ok(m) if m.file_type().is_symlink() => Toward::Refused(format!("automation path rejected: a link that leads nowhere: {shown}")),
|
||||
// There, yet its real path can't be had (no permission): nothing to compare.
|
||||
Ok(_) => Toward::Refused(format!("automation path rejected: cannot resolve {shown}: {e}")),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
|
||||
if parts.any(|part| !matches!(part, Component::Normal(_) | Component::CurDir)) {
|
||||
return Toward::Refused(format!("automation path rejected: parent traversal below a folder that doesn't exist: {shown}"));
|
||||
}
|
||||
Toward::Inside
|
||||
}
|
||||
Err(e) => Toward::Refused(format!("automation path rejected: cannot resolve {shown}: {e}")),
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
if inside(&at, root) { Toward::Inside } else { Toward::Outside }
|
||||
}
|
||||
|
||||
/// Is `path` (resolved) `root` or inside it, component by component (without regard to case on
|
||||
@@ -306,6 +331,62 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// Outside the root, the refusal comes before anything out there is looked up, so it can't
|
||||
/// tell whether a folder out there exists.
|
||||
#[test]
|
||||
fn paths_out_of_the_root_are_refused_alike_without_looking() {
|
||||
let (base, roots) = folders("follow");
|
||||
let sep = std::path::MAIN_SEPARATOR;
|
||||
let root = s(base.join("in"));
|
||||
let refusal = |p: &str| roots.check(p, Access::Read).unwrap_err().replace(p, "<path>");
|
||||
// Through a folder outside that exists, and through one that doesn't.
|
||||
let there = format!("{root}{sep}..{sep}outside{sep}..{sep}x.pdf");
|
||||
let missing = format!("{root}{sep}..{sep}nowhere{sep}..{sep}x.pdf");
|
||||
assert_eq!(refusal(&there), refusal(&missing));
|
||||
assert!(refusal(&missing).starts_with("automation path rejected: outside the read root"), "{}", refusal(&missing));
|
||||
// Out through a missing folder and back in. (Windows folds `..` by name when it makes a path
|
||||
// absolute, as it does when it opens one: that path is `in\a.pdf` there.)
|
||||
#[cfg(not(windows))]
|
||||
assert!(refusal(&format!("{root}/../nowhere/../in/a.pdf")).contains("outside the read root"));
|
||||
// A `\\?\` path is taken as written, `..` and all, so there the walk itself refuses it.
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let verbatim = |rest: &str| format!(r"\\?\{root}\{rest}");
|
||||
assert_eq!(refusal(&verbatim(r"..\outside\..\x.pdf")), refusal(&verbatim(r"..\nowhere\..\x.pdf")));
|
||||
assert!(
|
||||
refusal(&verbatim(r"..\nowhere\x.pdf")).starts_with("automation path rejected: outside the read root"),
|
||||
"{}",
|
||||
refusal(&verbatim(r"..\nowhere\x.pdf"))
|
||||
);
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// The root can be named as it was given or as it resolves (`/var/…` and `/private/var/…` on
|
||||
/// macOS, where the temporary folder is reached through a link).
|
||||
#[test]
|
||||
fn a_root_may_be_named_as_given_or_as_resolved() {
|
||||
let (base, roots) = folders("given");
|
||||
let resolved = std::fs::canonicalize(base.join("in")).unwrap();
|
||||
assert_eq!(roots.check(&s(base.join("in/a.pdf")), Access::Read), Ok(()));
|
||||
assert_eq!(roots.check(&s(resolved.join("a.pdf")), Access::Read), Ok(()));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// A link beside the root, in one of its parent folders, is followed: to the root it leads in,
|
||||
/// anywhere else it leads out.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn links_beside_the_root_are_followed() {
|
||||
let (base, roots) = folders("beside");
|
||||
std::os::unix::fs::symlink(base.join("in"), base.join("to-in")).unwrap();
|
||||
std::os::unix::fs::symlink(base.join("outside"), base.join("to-outside")).unwrap();
|
||||
assert_eq!(roots.check(&s(base.join("to-in/a.pdf")), Access::Read), Ok(()));
|
||||
assert_eq!(roots.check(&s(base.join("to-in/sub/new.pdf")), Access::Read), Ok(()));
|
||||
assert!(roots.check(&s(base.join("to-outside/secret.pdf")), Access::Read).unwrap_err().contains("outside the read root"));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relative_paths_resolve_against_the_working_directory() {
|
||||
let (base, roots) = folders("relative");
|
||||
@@ -393,7 +474,8 @@ mod tests {
|
||||
fn tools_do_not_touch_the_file_system_without_resolving_the_path() {
|
||||
// Helpers that are only called with a resolved path. `doc_batch` (batch.rs) resolves its
|
||||
// inputs and out_dir, walks only inside them (skipping links) and resolves every
|
||||
// discovered file again before `process` reads it or `publish` writes it.
|
||||
// discovered file again before `process` reads it or `publish` writes it. `doc_bates_multi`
|
||||
// resolves its paths before checking output collisions and using the probe helpers.
|
||||
const RESOLVED_BY_CALLER: &[&str] = &[
|
||||
"write_atomic",
|
||||
"write_atomic_with",
|
||||
@@ -405,6 +487,8 @@ mod tests {
|
||||
"linked",
|
||||
"walk",
|
||||
"publish",
|
||||
"check_unique_outputs",
|
||||
"probe_files_for_resolved_outputs",
|
||||
];
|
||||
let mut dirs = vec![Path::new(env!("CARGO_MANIFEST_DIR")).join("src")];
|
||||
let mut files = vec![];
|
||||
|
||||
@@ -48,7 +48,6 @@ use serde_json::{Value, json};
|
||||
pub use pdfcraft_render::Pixels;
|
||||
pub use tools::{ToolDef, tools};
|
||||
|
||||
use file_access::foreign_share;
|
||||
use text_cache::TextCache;
|
||||
|
||||
mod assemble;
|
||||
|
||||
@@ -2,7 +2,9 @@
|
||||
|
||||
use pdfcraft_engine::model3d::Model3dKind;
|
||||
use pdfcraft_prc::PrcFile;
|
||||
use pdfcraft_prc_render::{Camera, RenderOptions, assemble, render};
|
||||
use pdfcraft_prc_render::nav::{Axis, NamedView, Orbit, Upright, reach};
|
||||
use pdfcraft_prc_render::{Bounds, Camera, RenderOptions, WorldMesh, assemble, render};
|
||||
use serde_json::Value;
|
||||
|
||||
use super::Automation;
|
||||
use super::dispatch::Content;
|
||||
@@ -22,7 +24,6 @@ impl Automation {
|
||||
let page = self.page(a)?;
|
||||
let width = side(a, "width")?;
|
||||
let height = side(a, "height")?;
|
||||
let direction = direction(a)?;
|
||||
let perspective = a.opt_bool("perspective")?.unwrap_or(true);
|
||||
let doc = self.doc(a)?;
|
||||
let found = doc.model_3d_annotations(page).map_err(failed)?;
|
||||
@@ -42,7 +43,14 @@ impl Automation {
|
||||
let prc = PrcFile::parse(&model.data).map_err(|e| failed(format!("the 3D model could not be read: {e}")))?;
|
||||
let meshes = assemble(&prc).map_err(failed)?;
|
||||
let aspect = f64::from(width) / f64::from(height);
|
||||
let camera = Camera::fit_meshes(&meshes, direction, up_for(direction), perspective, aspect).map_err(failed)?;
|
||||
let camera = match a.get("orbit") {
|
||||
Some(_) if a.get("direction").is_some() => return Err(Args::wrong("orbit", "left out when direction is given")),
|
||||
Some(moves) => orbit_camera(moves, &meshes, perspective, aspect)?,
|
||||
None => {
|
||||
let direction = direction(a)?;
|
||||
Camera::fit_meshes(&meshes, direction, up_for(direction), perspective, aspect).map_err(failed)?
|
||||
}
|
||||
};
|
||||
let image = render(&meshes, &camera, &RenderOptions { width, height, ..RenderOptions::default() }).map_err(failed)?;
|
||||
let data = encode_png(image.width, image.height, &premultiplied(image.rgba))?;
|
||||
Ok(vec![Content::Png { data, width: image.width, height: image.height }])
|
||||
@@ -71,6 +79,65 @@ fn direction(a: &Args) -> Result<[f64; 3]> {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The keys `orbit` takes.
|
||||
const ORBIT_KEYS: [&str; 7] = ["view", "up", "front", "turn", "zoom", "zoom_at", "pan"];
|
||||
|
||||
/// The camera `orbit` names: a named view about an up axis, then a turn, a zoom and a pan, as a
|
||||
/// viewer's orbit control would apply them.
|
||||
fn orbit_camera(moves: &Value, meshes: &[WorldMesh], perspective: bool, aspect: f64) -> Result<Camera> {
|
||||
let wrong = |what: &str| Args::wrong("orbit", what);
|
||||
let moves = moves.as_object().ok_or_else(|| wrong("an object"))?;
|
||||
if let Some(key) = moves.keys().find(|k| !ORBIT_KEYS.contains(&k.as_str())) {
|
||||
return Err(wrong(&format!("an object without {key}; its keys are {}", ORBIT_KEYS.join(", "))));
|
||||
}
|
||||
let token = |key: &str| moves.get(key).map(|v| v.as_str().ok_or_else(|| wrong(&format!("{key} as a string"))));
|
||||
let axis = |key: &str| token(key).map(|t| Axis::from_token(t?).ok_or_else(|| wrong(&format!("{key} as one of +x, +y, +z, -x, -y, -z"))));
|
||||
let mut upright = Upright::default();
|
||||
if let Some(up) = axis("up") {
|
||||
upright = upright.with_up(up?);
|
||||
}
|
||||
if let Some(front) = axis("front") {
|
||||
let front = front?;
|
||||
if !upright.up().perpendicular(front) {
|
||||
return Err(wrong("front perpendicular to up"));
|
||||
}
|
||||
upright = upright.with_front(front);
|
||||
}
|
||||
let view = match token("view") {
|
||||
None => NamedView::Isometric,
|
||||
Some(t) => NamedView::from_token(t?).ok_or_else(|| wrong("view as one of iso, front, right, top, back"))?,
|
||||
};
|
||||
let mut orbit = Orbit::named(view, perspective, upright);
|
||||
let bounds = Bounds::of(meshes).ok_or_else(|| failed("the model has no vertex"))?;
|
||||
let reach = reach(meshes, &bounds);
|
||||
if let Some(v) = moves.get("turn") {
|
||||
let [yaw, pitch] = pair(v).ok_or_else(|| wrong("turn as [yaw, pitch] in degrees"))?;
|
||||
orbit.turn(yaw.to_radians(), pitch.to_radians());
|
||||
}
|
||||
if let Some(v) = moves.get("zoom") {
|
||||
let factor = v.as_f64().filter(|f| f.is_finite() && *f > 0.0).ok_or_else(|| wrong("zoom as a positive number"))?;
|
||||
let at = match moves.get("zoom_at") {
|
||||
None => [0.0, 0.0],
|
||||
Some(v) => pair(v).ok_or_else(|| wrong("zoom_at as [right, up] in picture heights"))?,
|
||||
};
|
||||
orbit.zoom_at(&bounds, reach, aspect, factor, at);
|
||||
} else if moves.contains_key("zoom_at") {
|
||||
return Err(wrong("an object with zoom when it has zoom_at"));
|
||||
}
|
||||
if let Some(v) = moves.get("pan") {
|
||||
orbit.pan_by(pair(v).ok_or_else(|| wrong("pan as [right, up] in model radii"))?);
|
||||
}
|
||||
orbit.camera(&bounds, reach, aspect).map_err(failed)
|
||||
}
|
||||
|
||||
/// Two finite numbers.
|
||||
fn pair(v: &Value) -> Option<[f64; 2]> {
|
||||
match v.as_array()?.as_slice() {
|
||||
[a, b] => Some([a.as_f64().filter(|f| f.is_finite())?, b.as_f64().filter(|f| f.is_finite())?]),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Z is up, as CAD models are drawn, unless the view looks along it.
|
||||
fn up_for([x, y, z]: [f64; 3]) -> [f64; 3] {
|
||||
if x.hypot(y) <= z.abs() * 1e-6 { [0.0, 1.0, 0.0] } else { [0.0, 0.0, 1.0] }
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use super::error::{Result, failed};
|
||||
use super::{Automation, Path, PathBuf, StagingName, file_access, foreign_share, staging_suffixes};
|
||||
use super::{Automation, Path, PathBuf, StagingName, file_access, staging_suffixes};
|
||||
|
||||
impl Automation {
|
||||
// ---- paths -------------------------------------------------------------------------------
|
||||
@@ -39,7 +39,13 @@ impl Automation {
|
||||
let Some(root) = &self.root else { return Ok(p.to_path_buf()) };
|
||||
let outside = || failed(format!("{path} is outside the allowed directory {}", root.display()));
|
||||
let joined = lexical(&root.join(p)).ok_or_else(outside)?;
|
||||
if foreign_share(&joined, root) {
|
||||
// Followed one name at a time first: nothing outside the root or its own parent folders is
|
||||
// looked up, not even to see whether it exists. What can't be followed inside the root is
|
||||
// said below. Made absolute the way Windows reads it first: it drops a folder name's
|
||||
// trailing dot (`in.` is `in`), but `follow` looks names up below `\\?\` folders, where it
|
||||
// doesn't.
|
||||
let as_read = std::path::absolute(&joined).map_err(|_| outside())?;
|
||||
if matches!(file_access::follow(path, &as_read, root), file_access::Toward::Outside) {
|
||||
return Err(outside());
|
||||
}
|
||||
let mut existing = joined.as_path();
|
||||
|
||||
@@ -134,6 +134,18 @@ impl Automation {
|
||||
"shrink" => Layout::Size(SizeMode::Shrink),
|
||||
"custom" => Layout::Size(SizeMode::Custom(a.opt_num("scale")?.ok_or_else(|| bad("custom needs scale (percent)"))?)),
|
||||
"multiple" => {
|
||||
// Custom pages per sheet: `cols` across by `rows` down, both or neither.
|
||||
let grid = match (a.opt_int("cols")?, a.opt_int("rows")?) {
|
||||
(None, None) => None,
|
||||
(Some(cols), Some(rows)) => {
|
||||
if a.opt_int("per_sheet")?.is_some() {
|
||||
return Err(bad("give per_sheet, or cols and rows, not both"));
|
||||
}
|
||||
let grid = usize::try_from(cols).ok().zip(usize::try_from(rows).ok()).and_then(|(cols, rows)| Layout::grid(cols, rows));
|
||||
Some(grid.ok_or_else(|| bad(format!("cols and rows must each be 1 to {}", print::MAX_GRID)))?)
|
||||
}
|
||||
_ => return Err(bad("a custom grid needs both cols and rows")),
|
||||
};
|
||||
let per = a.opt_int("per_sheet")?.unwrap_or(2).clamp(1, 256) as usize;
|
||||
let order = match a.opt_str("order")?.unwrap_or("horizontal") {
|
||||
"horizontal" => PageOrder::Horizontal,
|
||||
@@ -143,14 +155,15 @@ impl Automation {
|
||||
"cut-stack" => PageOrder::CutStack,
|
||||
o => return Err(bad(format!("unknown order {o:?}"))),
|
||||
};
|
||||
match Layout::multiple(per) {
|
||||
Layout::Multiple { cols, rows, per_sheet, .. } => Layout::Multiple {
|
||||
match grid.unwrap_or_else(|| Layout::multiple(per)) {
|
||||
Layout::Multiple { cols, rows, per_sheet, custom, .. } => Layout::Multiple {
|
||||
cols,
|
||||
rows,
|
||||
per_sheet,
|
||||
order,
|
||||
border: a.opt_bool("border")?.unwrap_or(false),
|
||||
auto_rotate: a.opt_bool("auto_rotate")?.unwrap_or(true),
|
||||
custom,
|
||||
},
|
||||
l => l,
|
||||
}
|
||||
@@ -172,6 +185,9 @@ impl Automation {
|
||||
l => return Err(bad(format!("unknown layout {l:?}"))),
|
||||
};
|
||||
let duplex = job_duplex(a.opt_str("duplex")?.unwrap_or("off"), &layout)?;
|
||||
if (a.opt_int("cols")?.is_some() || a.opt_int("rows")?.is_some()) && !matches!(layout, Layout::Multiple { .. }) {
|
||||
return Err(bad("cols and rows need layout multiple"));
|
||||
}
|
||||
if a.opt_str("order")? == Some("cut-stack") && !matches!(layout, Layout::Multiple { .. }) {
|
||||
return Err(bad("cut-stack order needs layout multiple"));
|
||||
}
|
||||
|
||||
@@ -219,6 +219,7 @@ fn names_from_documents_become_one_plain_file_name() {
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn other_shares_and_device_paths_are_refused_by_name() {
|
||||
use crate::file_access::foreign_share;
|
||||
let local = Path::new(r"\\?\C:\work\root");
|
||||
for p in [
|
||||
r"\\host\share\x.pdf",
|
||||
@@ -242,6 +243,28 @@ fn other_shares_and_device_paths_are_refused_by_name() {
|
||||
assert!(foreign_share(Path::new(r"\\attacker\docs\x.pdf"), shared));
|
||||
}
|
||||
|
||||
/// Windows drops a trailing dot from a folder name when it opens a path (`root.` is `root`), so
|
||||
/// with a root, a path that names the root or a folder above it that way still reaches the file
|
||||
/// inside. A dotted name outside stays outside.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn a_trailing_dot_on_the_root_or_above_it_names_the_folder_windows_opens() {
|
||||
let base = std::env::temp_dir().join(format!("pdfcraft-automation-dot-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
std::fs::create_dir_all(base.join("root")).unwrap();
|
||||
std::fs::create_dir_all(base.join("outside")).unwrap();
|
||||
std::fs::write(base.join("root").join("a.pdf"), b"x").unwrap();
|
||||
std::fs::write(base.join("outside").join("b.pdf"), b"x").unwrap();
|
||||
let a = Automation::new().with_root(base.join("root")).unwrap();
|
||||
let shown = base.to_string_lossy().into_owned();
|
||||
for p in [format!(r"{shown}\root.\a.pdf"), format!(r"{shown}.\root\a.pdf")] {
|
||||
let resolved = a.resolve(&p, false);
|
||||
assert!(resolved.is_ok(), "{p}: {resolved:?}");
|
||||
}
|
||||
assert!(a.resolve(&format!(r"{shown}\outside.\b.pdf"), false).is_err());
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
}
|
||||
|
||||
/// A fresh, empty folder for one staging test.
|
||||
fn staging_dir(test: &str) -> PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("pdfcraft-staging-{}-{test}", std::process::id()));
|
||||
|
||||
@@ -140,8 +140,8 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
.with(schema(json!({
|
||||
"files": {"type":"array","minItems":1,"maxItems":1000,"description":"PDFs in Bates sequence order.","items":{"type":"object","properties":{"input":{"type":"string","minLength":1,"description":"Input PDF path."},"output":{"type":"string","minLength":1,"description":"New output PDF path; must not exist."},"password":{"type":"string","description":"Open or permissions password, if needed."}},"required":["input","output"],"additionalProperties":false}},
|
||||
"start_number": {"type":"integer","minimum":1,"description":"First number in the sequence (default 1)."}, "digits": {"type":"integer","minimum":1,"maximum":12,"description":"Zero-padded number width (default 6)."},
|
||||
"prefix": {"type":"string","maxLength":128,"description":"Text before the number: at most 128 UTF-8 bytes, without # or >>."}, "suffix": {"type":"string","maxLength":128,"description":"Text after the number: at most 128 UTF-8 bytes, without # or >>."},
|
||||
"dry_run": {"type":"boolean","description":"Return each file's inclusive number interval without writing (default false)."}
|
||||
"prefix": {"type":"string","maxLength":128,"description":"Bates prefix, up to 128 characters; cannot contain # or >>."}, "suffix": {"type":"string","maxLength":128,"description":"Bates suffix, up to 128 characters; cannot contain # or >>."},
|
||||
"dry_run": {"type":"boolean","description":"Return each file's inclusive number interval without writing (default false). Output collisions are checked conservatively: Windows compares case-insensitively, while Unix preserves case, so case-sensitive Windows and case-insensitive Unix volumes can differ from normal runs."}
|
||||
}), &["files"])),
|
||||
t("doc_batch", "Process files and folders", "Run convert, ocr and/or optimize over files and folders, one file at a time. recursive defaults to false. Preserve paths relative to each selected folder inside out_dir; duplicate inputs run once. Skip unsupported files, links and the output subtree. Existing outputs receive numbered names and are never replaced. Continue after per-file errors unless stop_on_error is true. Return completed/failed/skipped counts and per-file results. Discovery is bounded to 10000 entries and 64 folder levels. Convert must be first; each step can appear once. OCR uses installed models. Optimize uses Reduce File Size settings, optionally overriding target ppi (threshold 1.5 times ppi; black-and-white images go to the larger of ppi and 300) and JPEG quality; a larger candidate keeps the original bytes. Sources and open documents are unchanged.")
|
||||
.with(schema(json!({
|
||||
@@ -195,12 +195,21 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
"hide_text_block": { "type": "integer", "minimum": 1, "description": "Render an inline editor background without this paragraph (number from text_paragraphs, resolved as text_edit does: refused once an edit merged that paragraph into a neighbour). Does not modify the document." },
|
||||
"hide_added_text": { "type": "integer", "minimum": 1, "description": "Render a retyping background without this added text item (added index from object_list). Mutually exclusive with hide_text_block. Does not modify the document." }
|
||||
}), &["doc", "page"])),
|
||||
t("model_render", "Render a 3D model", "Draw a page's 3D model (a 3D annotation's PRC stream) to a PNG, framed to fill the image, with headlight shading on a white background. model is its 1-based position among the page's 3D models (default 1). direction is the view direction [x, y, z] from the eye towards the model (default [-1, 1, -1]); Z is up unless the view looks along Z. perspective defaults to true. U3D models can't be drawn yet and give an error. Does not modify the document.")
|
||||
t("model_render", "Render a 3D model", "Draw a page's 3D model (a 3D annotation's PRC stream) to a PNG, framed to fill the image, with headlight shading on a white background. model is its 1-based position among the page's 3D models (default 1). direction is the view direction [x, y, z] from the eye towards the model (default [-1, 1, -1]); Z is up unless the view looks along Z. orbit, in place of direction, frames the model as a viewer's orbit control does (the same size from every side) and applies, in order: view (iso, front, right, top or back; default iso) about up (+x, +y, +z, -x, -y or -z; default +z) with the Front view looking along front (an axis perpendicular to up; default +y, or -z when y is up), then turn [yaw, pitch] in degrees (pitch looks down and stops just short of the up axis), then zoom (a factor, the result held within 0.05 to 50) about the picture point zoom_at [right, up] in picture heights from the centre (default the centre), then pan [right, up] in model radii (it moves the target, so the model moves the other way). perspective defaults to true. U3D models can't be drawn yet and give an error. Does not modify the document.")
|
||||
.ro()
|
||||
.with(schema(json!({ "doc": doc(), "page": { "type": "integer", "minimum": 1 }, "model": { "type": "integer", "minimum": 1 },
|
||||
"width": { "type": "integer", "minimum": 1, "maximum": 4096 }, "height": { "type": "integer", "minimum": 1, "maximum": 4096 },
|
||||
"direction": { "type": "array", "items": { "type": "number" }, "minItems": 3, "maxItems": 3 },
|
||||
"perspective": { "type": "boolean" }
|
||||
"direction": { "type": "array", "items": { "type": "number" }, "minItems": 3, "maxItems": 3, "description": "The view direction from the eye towards the model (default [-1, 1, -1]). Mutually exclusive with orbit." },
|
||||
"perspective": { "type": "boolean" },
|
||||
"orbit": { "type": "object", "description": "A viewer's orbit moves, applied in the order of these keys; all optional. Mutually exclusive with direction.", "properties": {
|
||||
"view": { "type": "string", "enum": ["iso", "front", "right", "top", "back"], "description": "The view to start from (default iso)." },
|
||||
"up": { "type": "string", "enum": ["+x", "+y", "+z", "-x", "-y", "-z"], "description": "The model axis that appears upward (default +z)." },
|
||||
"front": { "type": "string", "enum": ["+x", "+y", "+z", "-x", "-y", "-z"], "description": "The axis the Front view looks along, perpendicular to up (default +y, or -z when y is up)." },
|
||||
"turn": { "type": "array", "items": { "type": "number" }, "minItems": 2, "maxItems": 2, "description": "[yaw, pitch] in degrees, pitch looking down (default [0, 0])." },
|
||||
"zoom": { "type": "number", "exclusiveMinimum": 0, "description": "A factor on the fitted view (default 1); the result is held within 0.05 to 50." },
|
||||
"zoom_at": { "type": "array", "items": { "type": "number" }, "minItems": 2, "maxItems": 2, "description": "The picture point the zoom keeps still, [right, up] in picture heights from the centre (default [0, 0]). Requires zoom." },
|
||||
"pan": { "type": "array", "items": { "type": "number" }, "minItems": 2, "maxItems": 2, "description": "Moves the target [right, up] in model radii, so the model moves the other way (default [0, 0]); each held within 1000." }
|
||||
}, "additionalProperties": false }
|
||||
}), &["doc", "page"])),
|
||||
t("object_list", "List editable objects", "List existing paragraphs, Image/Form artwork and added content once, with source kind/index references, displayed rectangles and document generation. Indexes change when content changes; use generation in object_move to reject stale references.")
|
||||
.ro().with(schema(json!({"doc":doc(),"page":{"type":"integer","minimum":1}}), &["doc","page"])),
|
||||
@@ -698,7 +707,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; 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, 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, or US #10 Envelope (short names or full preset labels); 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).",
|
||||
"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; 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, or US #10 Envelope (short names or full preset labels); 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).",
|
||||
)
|
||||
.with(schema(
|
||||
json!({
|
||||
@@ -709,6 +718,8 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
"layout": { "type": "string", "enum": ["fit", "actual", "shrink", "custom", "multiple", "booklet", "poster"] },
|
||||
"scale": { "type": "number", "exclusiveMinimum": 0 },
|
||||
"per_sheet": { "type": "integer", "minimum": 1, "maximum": 256 },
|
||||
"cols": { "type": "integer", "minimum": 1, "maximum": 99, "description": "Custom pages per sheet: columns across the sheet; give rows too, and no per_sheet." },
|
||||
"rows": { "type": "integer", "minimum": 1, "maximum": 99, "description": "Custom pages per sheet: rows down the sheet; give cols too, and no per_sheet." },
|
||||
"order": { "type": "string", "enum": ["horizontal", "horizontal-reversed", "vertical", "vertical-reversed", "cut-stack"] },
|
||||
"border": { "type": "boolean" },
|
||||
"auto_rotate": { "type": "boolean" },
|
||||
|
||||
@@ -2969,6 +2969,15 @@ fn bates_numbers_continue_across_files_and_report_preflight_and_permission_failu
|
||||
{"input":"a.pdf","output":"a-numbered.pdf"}
|
||||
]);
|
||||
let mut a = auto(&dir);
|
||||
for invalid_start in [json!(0), json!(-1), json!(1.5), json!("17")] {
|
||||
let error = err(&mut a, "doc_bates_multi", json!({"files":files,"start_number":invalid_start}));
|
||||
assert!(matches!(error, ToolError::InvalidArgs(_)));
|
||||
}
|
||||
let unicode = ok(&mut a, "doc_bates_multi", json!({"files":files,"prefix":"é".repeat(65),"dry_run":true}));
|
||||
assert_eq!(unicode["files"].as_array().unwrap().len(), 2);
|
||||
assert!(matches!(err(&mut a, "doc_bates_multi", json!({"files":files,"prefix":"CASE>>"})), ToolError::InvalidArgs(_)));
|
||||
assert!(matches!(err(&mut a, "doc_bates_multi", json!({"files":files,"suffix":"A>>B"})), ToolError::InvalidArgs(_)));
|
||||
|
||||
let allocation = ok(&mut a, "doc_bates_multi", json!({"files":files,"start_number":50,"dry_run":true}));
|
||||
assert_eq!(allocation["files"][0]["first"], 50);
|
||||
assert_eq!(allocation["files"][0]["last"], 51);
|
||||
@@ -2987,15 +2996,24 @@ fn bates_numbers_continue_across_files_and_report_preflight_and_permission_failu
|
||||
let overflow = err(&mut a, "doc_bates_multi", json!({"files":[{"input":"b.pdf","output":"overflow.pdf"}],"start_number":u64::MAX}));
|
||||
assert!(overflow.to_string().contains("overflows"));
|
||||
assert!(!dir.join("overflow.pdf").exists());
|
||||
// A range may end at u64::MAX itself.
|
||||
let at_max = ok(&mut a, "doc_bates_multi", json!({"files":[{"input":"b.pdf","output":"max.pdf"}],"start_number":u64::MAX - 1,"dry_run":true}));
|
||||
assert_eq!(at_max["files"][0]["last"], u64::MAX);
|
||||
for bad in
|
||||
[json!({"start_number":-3}), json!({"start_number":2.5}), json!({"start_number":"7"}), json!({"prefix":"CASE>>"}), json!({"suffix":"A>>B"})]
|
||||
std::fs::write(dir.join("one.pdf"), fixture(1)).unwrap();
|
||||
let max_number =
|
||||
ok(&mut a, "doc_bates_multi", json!({"files":[{"input":"one.pdf","output":"one-numbered.pdf"}],"start_number":u64::MAX,"dry_run":true}));
|
||||
assert_eq!(max_number["files"][0]["first"], u64::MAX);
|
||||
assert_eq!(max_number["files"][0]["last"], u64::MAX);
|
||||
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let mut args = json!({"files":[{"input":"b.pdf","output":"bad.pdf"}],"dry_run":true});
|
||||
args.as_object_mut().unwrap().extend(bad.as_object().unwrap().clone());
|
||||
assert!(a.call("doc_bates_multi", &args).is_err(), "{bad}");
|
||||
let collision = err(
|
||||
&mut a,
|
||||
"doc_bates_multi",
|
||||
json!({"files":[
|
||||
{"input":"b.pdf","output":"Case.pdf"},
|
||||
{"input":"a.pdf","output":"CASE.pdf"}
|
||||
]}),
|
||||
);
|
||||
assert!(collision.to_string().contains("same output path"));
|
||||
assert!(!dir.join("Case.pdf").exists());
|
||||
}
|
||||
|
||||
use pdfcraft_engine::{Changes, Edit, Protection, Session};
|
||||
@@ -6783,11 +6801,26 @@ fn drawing_comments_through_tools() {
|
||||
a.call("comment_add", &json!({ "doc": doc, "page": 1, "type": "polygon", "points": [[1, 1]] })),
|
||||
Err(ToolError::Failed(_) | ToolError::InvalidArgs(_))
|
||||
));
|
||||
// Replace Text: a strikeout over the found text and a grouped caret.
|
||||
ok(&mut a, "comment_add", json!({ "doc": doc, "page": 2, "type": "replace", "find": "page 2", "contents": "second page" }));
|
||||
// Replace Text: a strikeout over the found text, grouped under a caret holding the
|
||||
// replacement (the group's primary, ISO 32000-2 §12.5.6.2).
|
||||
ok(&mut a, "comment_add", json!({ "doc": doc, "page": 2, "type": "replace", "find": "page 2", "contents": "second page", "color": "green" }));
|
||||
let list = ok(&mut a, "comment_list", json!({ "doc": doc, "page": 2 }));
|
||||
let strike = list["comments"].as_array().unwrap().iter().find(|c| c["type"] == "StrikeOut").unwrap().clone();
|
||||
assert_eq!(strike["replies"][0]["contents"], "second page", "the caret threads under the strikeout");
|
||||
let caret = list["comments"].as_array().unwrap().iter().find(|c| c["type"] == "Caret").unwrap().clone();
|
||||
assert_eq!(caret["contents"], "second page", "the replacement is on the caret");
|
||||
assert_eq!(caret["replies"][0]["type"], "StrikeOut", "the strikeout is grouped under the caret");
|
||||
// Review on #5689 (CodeRabbit): the requested colour is the group's, so the primary has it.
|
||||
assert_eq!(caret["replies"][0]["color"], caret["color"], "one colour for the pair: {caret}");
|
||||
assert_eq!(caret["color"], json!("#2E9E5C"), "the requested green, not the caret's default blue: {caret}");
|
||||
// Restyling the caret restyles the proposal, its strikeout too, as one undo step.
|
||||
let pair = |a: &mut Automation| {
|
||||
let list = ok(a, "comment_list", json!({ "doc": doc, "page": 2 }));
|
||||
let c = list["comments"].as_array().unwrap().iter().find(|c| c["type"] == "Caret").unwrap().clone();
|
||||
(c["color"].clone(), c["replies"][0]["color"].clone())
|
||||
};
|
||||
ok(&mut a, "comment_edit", json!({ "doc": doc, "page": 2, "index": caret["index"], "color": "purple" }));
|
||||
assert_eq!(pair(&mut a), (json!("#8A3FD1"), json!("#8A3FD1")), "the strikeout follows its caret");
|
||||
ok(&mut a, "edit_undo", json!({ "doc": doc }));
|
||||
assert_eq!(pair(&mut a), (json!("#2E9E5C"), json!("#2E9E5C")), "one undo puts both back");
|
||||
assert!(matches!(a.call("comment_add", &json!({ "doc": doc, "page": 2, "type": "replace", "find": "page 2" })), Err(ToolError::InvalidArgs(_))));
|
||||
// A file attached as a comment.
|
||||
std::fs::write(dir.join("notes.txt"), b"remember").unwrap();
|
||||
@@ -8882,6 +8915,49 @@ fn cut_stack_printing_through_tools() {
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_pages_per_sheet_prints_the_grid_as_given() {
|
||||
// Two narrow pages side by side on portrait A4: 2 columns by 1 row (#6551).
|
||||
let dir = workdir("custom-grid");
|
||||
std::fs::write(dir.join("narrow.pdf"), fixture(4)).unwrap();
|
||||
let mut a = auto(&dir);
|
||||
let doc = ok(&mut a, "doc_open", json!({"path": "narrow.pdf"}))["doc"].as_u64().unwrap();
|
||||
for orientation in ["auto", "portrait"] {
|
||||
let r = ok(
|
||||
&mut a,
|
||||
"doc_print",
|
||||
json!({"doc": doc, "layout": "multiple", "cols": 2, "rows": 1, "paper": "A4", "orientation": orientation, "path": "grid.pdf"}),
|
||||
);
|
||||
assert_eq!(r["sheets"], 2, "{orientation}");
|
||||
let printed = ok(&mut a, "doc_open", json!({"path": "grid.pdf"}))["doc"].as_u64().unwrap();
|
||||
let info = ok(&mut a, "doc_info", json!({"doc": printed}));
|
||||
let sheet = &info["pages"][0];
|
||||
assert!(sheet["width"].as_f64().unwrap() < sheet["height"].as_f64().unwrap(), "portrait sheet with {orientation}: {sheet}");
|
||||
// Side by side: the second page level with the first, to its right.
|
||||
let rows = ok(&mut a, "text_extract", json!({"doc": printed, "rect": [0, 0, 600, 850]}));
|
||||
let rows: Vec<&str> = rows["pages"].as_array().unwrap().iter().map(|p| p["text"].as_str().unwrap().trim()).collect();
|
||||
assert_eq!(rows, ["Page 1 Page 2", "Page 3 Page 4"], "{orientation}");
|
||||
ok(&mut a, "doc_close", json!({"doc": printed}));
|
||||
}
|
||||
for bad in [
|
||||
json!({"cols": 2}),
|
||||
json!({"rows": 1}),
|
||||
json!({"cols": 0, "rows": 1}),
|
||||
json!({"cols": 2, "rows": 100}),
|
||||
json!({"cols": -1, "rows": 2}),
|
||||
json!({"cols": 2, "rows": 1, "per_sheet": 2}),
|
||||
json!({"cols": 2, "rows": 1, "layout": "fit"}),
|
||||
] {
|
||||
let mut args = json!({"doc": doc, "layout": "multiple", "path": "refused.pdf"});
|
||||
for (k, v) in bad.as_object().unwrap() {
|
||||
args[k] = v.clone();
|
||||
}
|
||||
assert!(matches!(a.call("doc_print", &args), Err(ToolError::InvalidArgs(_))), "{bad}");
|
||||
}
|
||||
assert!(!dir.join("refused.pdf").exists());
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn measurements_calibrate_draw_save_reopen_and_export() {
|
||||
let dir = workdir("measurements");
|
||||
@@ -12089,6 +12165,49 @@ fn comments_copy_and_paste_between_documents_through_tools() {
|
||||
assert_eq!(ok(&mut a, "comment_list", json!({ "doc": src }))["comments"].as_array().unwrap().len(), 2, "the source is untouched");
|
||||
}
|
||||
|
||||
/// A bitmap Type 3 font drawn with a flipped font matrix under a flipped text matrix (as TeX's
|
||||
/// bitmap fonts are): `text_lines` boxes a line by its glyphs' `d1` boxes (ISO 32000-2 §9.6.4),
|
||||
/// as high as the ink, not a 0.09-point sliver.
|
||||
#[test]
|
||||
fn text_lines_box_a_flipped_type3_line_by_its_glyphs() {
|
||||
let content = "BT /F1 1 Tf 0.15 0 0 -0.15 10 20 Tm (ab) Tj ET";
|
||||
let glyph_a = "46 0 3 -1 42 57 d1 3 -1 39 58 re f";
|
||||
let glyph_b = "42 0 2 -18 40 38 d1 2 -18 38 56 re f";
|
||||
let objs: Vec<String> = vec![
|
||||
"<< /Type /Catalog /Pages 2 0 R >>".into(),
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".into(),
|
||||
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 50] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >>".into(),
|
||||
format!("<< /Length {} >>\nstream\n{content}\nendstream", content.len()),
|
||||
"<< /Type /Font /Subtype /Type3 /FontMatrix [1 0 0 -1 0 0] /FontBBox [-4 -18 51 57] /FirstChar 97 /LastChar 98 \
|
||||
/Widths [46 42] /Encoding << /Differences [97 /a /b] >> /CharProcs << /a 6 0 R /b 7 0 R >> >>"
|
||||
.into(),
|
||||
format!("<< /Length {} >>\nstream\n{glyph_a}\nendstream", glyph_a.len()),
|
||||
format!("<< /Length {} >>\nstream\n{glyph_b}\nendstream", glyph_b.len()),
|
||||
];
|
||||
let mut bytes = b"%PDF-1.7\n".to_vec();
|
||||
let mut offsets = Vec::new();
|
||||
for (i, o) in objs.iter().enumerate() {
|
||||
offsets.push(bytes.len());
|
||||
bytes.extend_from_slice(format!("{} 0 obj\n{o}\nendobj\n", i + 1).as_bytes());
|
||||
}
|
||||
let xref = bytes.len();
|
||||
bytes.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes());
|
||||
for o in offsets {
|
||||
bytes.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());
|
||||
}
|
||||
bytes.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes());
|
||||
let dir = workdir("type3-text-lines");
|
||||
std::fs::write(dir.join("type3.pdf"), bytes).unwrap();
|
||||
let mut a = auto(&dir);
|
||||
let doc = ok(&mut a, "doc_open", json!({ "path": "type3.pdf" }))["doc"].as_u64().unwrap();
|
||||
let lines = ok(&mut a, "text_lines", json!({ "doc": doc, "page": 1 }));
|
||||
// Glyph space y -18..57, turned over twice: 57 × 0.15 above the baseline at y 20 (8.55) and
|
||||
// 18 × 0.15 below it (2.7). Top-left origin on a 50-point page: 21.45 down to 32.7.
|
||||
assert_eq!(lines["count"], 1, "{lines}");
|
||||
assert_eq!(lines["lines"][0]["text"], "ab");
|
||||
assert_eq!(lines["lines"][0]["rect"], json!([10.0, 21.45, 23.2, 32.7]), "{lines}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_bundled_thai_font_choice_layout_edit_undo_and_reopen() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -110,3 +110,171 @@ fn a_model_outside_the_root_is_never_opened_to_be_drawn() {
|
||||
let doc = open(&mut a, "prc.pdf");
|
||||
assert!(a.call("model_render", &json!({ "doc": doc, "page": 1 })).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_orbit_frames_the_model_from_a_named_view_and_its_moves() {
|
||||
let (_dir, mut a) = setup("orbit");
|
||||
let doc = open(&mut a, "prc.pdf");
|
||||
let draw = |a: &mut Automation, orbit: Value| orbit_picture(a, doc, false, &orbit);
|
||||
// The triangle lies in z = 0: the Top view looks down on its face, the Front view along its edge.
|
||||
let top = draw(&mut a, json!({ "view": "top" }));
|
||||
assert_eq!(rgb(&top, 32, 24), [190, 192, 200], "the top view sees the face head on");
|
||||
let front = draw(&mut a, json!({ "view": "front" }));
|
||||
assert!((0..48).all(|y| rgb(&front, 32, y) == [255, 255, 255]), "the front view sees only its edge");
|
||||
let tipped = draw(&mut a, json!({ "view": "front", "turn": [0, 30] }));
|
||||
assert_ne!(rgb(&tipped, 32, 24), [255, 255, 255], "tipped down from the front, the face is in the middle");
|
||||
// With y up the Front view looks along -z, onto the face.
|
||||
let y_up = draw(&mut a, json!({ "view": "front", "up": "+y" }));
|
||||
assert_eq!(rgb(&y_up, 32, 24), [190, 192, 200]);
|
||||
// Turning the front view down by 90° stops just short of the top view and sees the face.
|
||||
let turned = draw(&mut a, json!({ "view": "front", "turn": [0, 90] }));
|
||||
assert_ne!(rgb(&turned, 32, 24), [255, 255, 255]);
|
||||
// A pan moves the target right, so the model moves left; three radii take it out of the picture.
|
||||
let (left, right) = extent(&top, 24);
|
||||
let (moved_left, moved_right) = extent(&draw(&mut a, json!({ "view": "top", "pan": [0.5, 0] })), 24);
|
||||
assert!(moved_left < left && moved_right < right, "{left}..{right} moved to {moved_left}..{moved_right}");
|
||||
let panned = draw(&mut a, json!({ "view": "top", "pan": [3, 0] }));
|
||||
assert!((0..64).all(|x| rgb(&panned, x, 24) == [255, 255, 255]), "the model has left the picture");
|
||||
// Zooming in about the centre keeps the face under it and leaves no background at the corner.
|
||||
let zoomed = draw(&mut a, json!({ "view": "top", "zoom": 8 }));
|
||||
assert_eq!(rgb(&zoomed, 32, 24), [190, 192, 200]);
|
||||
assert_ne!(rgb(&zoomed, 0, 0), [255, 255, 255], "zoomed in, the face fills the corner too");
|
||||
}
|
||||
|
||||
/// The first and last columns on row `y` that are not background.
|
||||
fn extent(data: &[u8], y: usize) -> (usize, usize) {
|
||||
let drawn: Vec<usize> = (0..64).filter(|&x| rgb(data, x, y) != [255, 255, 255]).collect();
|
||||
(*drawn.first().expect("the model is on the row"), *drawn.last().expect("the model is on the row"))
|
||||
}
|
||||
|
||||
/// The first and last rows on column `x` that are not background.
|
||||
fn rows(data: &[u8], x: usize) -> (usize, usize) {
|
||||
let drawn: Vec<usize> = (0..48).filter(|&y| rgb(data, x, y) != [255, 255, 255]).collect();
|
||||
(*drawn.first().expect("the model is on the column"), *drawn.last().expect("the model is on the column"))
|
||||
}
|
||||
|
||||
/// A 64 by 48 picture of the model through `orbit`.
|
||||
fn orbit_picture(a: &mut Automation, doc: u64, perspective: bool, orbit: &Value) -> Vec<u8> {
|
||||
let out =
|
||||
a.call("model_render", &json!({ "doc": doc, "page": 1, "width": 64, "height": 48, "perspective": perspective, "orbit": orbit })).unwrap();
|
||||
let Content::Png { data, .. } = &out[0] else { panic!("expected a PNG") };
|
||||
data.clone()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_orbit_frames_the_isometric_view_in_perspective() {
|
||||
let (_dir, mut a) = setup("orbit-default");
|
||||
let doc = open(&mut a, "prc.pdf");
|
||||
let default = orbit_picture(&mut a, doc, false, &json!({}));
|
||||
assert_ne!(rgb(&default, 32, 24), [255, 255, 255], "the model is centred");
|
||||
let (left, right) = extent(&default, 24);
|
||||
let (high, low) = rows(&default, 32);
|
||||
assert!(left > 0 && right < 63 && high > 0 && low < 47, "inside the picture: {left}..{right}, {high}..{low}");
|
||||
assert!(right - left > 16, "and fills it: {left}..{right}");
|
||||
assert_eq!(default, orbit_picture(&mut a, doc, false, &json!({ "view": "iso", "up": "+z", "front": "+y" })), "the defaults");
|
||||
let unset = a.call("model_render", &json!({ "doc": doc, "page": 1, "width": 64, "height": 48, "orbit": {} })).unwrap();
|
||||
let Content::Png { data: unset, .. } = &unset[0] else { panic!("expected a PNG") };
|
||||
assert_eq!(*unset, orbit_picture(&mut a, doc, true, &json!({})), "perspective is the default");
|
||||
assert_ne!(*unset, default, "and shows");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zoom_at_keeps_the_point_under_it_still() {
|
||||
let (_dir, mut a) = setup("orbit-zoom-at");
|
||||
let doc = open(&mut a, "prc.pdf");
|
||||
let (left, right) = extent(&orbit_picture(&mut a, doc, false, &json!({ "view": "top", "zoom": 2 })), 24);
|
||||
// A point 0.2 picture heights off centre stays there, so what was at the centre moves
|
||||
// 0.2 x (2 - 1) x 48 = 9.6 pixels the other way.
|
||||
for (at, sign) in [(0.2, -1.0), (-0.2, 1.0)] {
|
||||
let (l, r) = extent(&orbit_picture(&mut a, doc, false, &json!({ "view": "top", "zoom": 2, "zoom_at": [at, 0] })), 24);
|
||||
for (was, now) in [(left, l), (right, r)] {
|
||||
let moved = now as f64 - was as f64;
|
||||
assert!((moved - sign * 9.6).abs() <= 1.5, "at {at}: {was} moved to {now}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_zoom_is_held_within_its_range() {
|
||||
let (_dir, mut a) = setup("orbit-zoom-range");
|
||||
let doc = open(&mut a, "prc.pdf");
|
||||
let far = orbit_picture(&mut a, doc, false, &json!({ "view": "top", "zoom": 0.05 }));
|
||||
assert_eq!(far, orbit_picture(&mut a, doc, false, &json!({ "view": "top", "zoom": 0.001 })), "the far end");
|
||||
assert_ne!(far, orbit_picture(&mut a, doc, false, &json!({ "view": "top", "zoom": 0.2 })));
|
||||
// Panned to just inside the near edge, so a nearer view would move the edge in the picture.
|
||||
let close = |z: f64| json!({ "view": "top", "zoom": z, "pan": [0, -0.7] });
|
||||
let near = orbit_picture(&mut a, doc, false, &close(50.0));
|
||||
assert_eq!(near, orbit_picture(&mut a, doc, false, &close(1000.0)), "the near end");
|
||||
assert_ne!(near, orbit_picture(&mut a, doc, false, &close(25.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_orbit_draws_in_perspective_at_the_same_scale() {
|
||||
let (_dir, mut a) = setup("orbit-perspective");
|
||||
let doc = open(&mut a, "prc.pdf");
|
||||
let tipped = json!({ "view": "front", "turn": [0, 30] });
|
||||
let deep = orbit_picture(&mut a, doc, true, &tipped);
|
||||
assert_ne!(rgb(&deep, 32, 24), [255, 255, 255]);
|
||||
assert_ne!(deep, orbit_picture(&mut a, doc, false, &tipped), "foreshortened");
|
||||
let top = json!({ "view": "top" });
|
||||
let (left, right) = extent(&orbit_picture(&mut a, doc, true, &top), 24);
|
||||
let (flat_left, flat_right) = extent(&orbit_picture(&mut a, doc, false, &top), 24);
|
||||
assert!(left.abs_diff(flat_left) <= 2 && right.abs_diff(flat_right) <= 2, "{left}..{right} against {flat_left}..{flat_right}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_orbit_front_yaw_and_upward_pan_each_move_the_picture() {
|
||||
let (_dir, mut a) = setup("orbit-moves");
|
||||
let doc = open(&mut a, "prc.pdf");
|
||||
let mut draw = |orbit: Value| orbit_picture(&mut a, doc, false, &orbit);
|
||||
// Yawing the Front view by 90 degrees is the Right view, which looks along -x; +x is its opposite.
|
||||
let right_view = draw(json!({ "view": "right", "turn": [0, 30] }));
|
||||
assert_eq!(right_view, draw(json!({ "view": "front", "turn": [90, 30] })), "yaw");
|
||||
assert_eq!(right_view, draw(json!({ "view": "front", "front": "-x", "turn": [0, 30] })), "front -x");
|
||||
assert_ne!(right_view, draw(json!({ "view": "front", "turn": [0, 30] })));
|
||||
assert_eq!(draw(json!({ "view": "right", "turn": [180, 30] })), draw(json!({ "view": "front", "front": "+x", "turn": [0, 30] })), "front +x");
|
||||
// From above, the triangle's apex is up the picture; a quarter yaw lays it along the row,
|
||||
// twice as wide there.
|
||||
let top = draw(json!({ "view": "top" }));
|
||||
let (left, right) = extent(&top, 24);
|
||||
let (yaw_left, yaw_right) = extent(&draw(json!({ "view": "top", "turn": [90, 0] })), 24);
|
||||
assert!(yaw_right - yaw_left > (right - left) * 3 / 2, "{left}..{right} yawed to {yaw_left}..{yaw_right}");
|
||||
// A pan up moves the target up, so the model moves down.
|
||||
let (high, low) = rows(&top, 32);
|
||||
let (moved_high, moved_low) = rows(&draw(json!({ "view": "top", "pan": [0, 0.25] })), 32);
|
||||
assert!(moved_high > high && moved_low >= low, "{high}..{low} moved to {moved_high}..{moved_low}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wrong_orbit_is_a_clear_error() {
|
||||
let (_dir, mut a) = setup("orbit-bad");
|
||||
let doc = open(&mut a, "prc.pdf");
|
||||
for (bad, reason) in [
|
||||
(json!({ "orbit": { "view": "side" } }), "view as one of"),
|
||||
(json!({ "orbit": { "view": 1 } }), "view as a string"),
|
||||
(json!({ "orbit": { "up": "z" } }), "up as one of"),
|
||||
(json!({ "orbit": { "up": 1 } }), "up as a string"),
|
||||
(json!({ "orbit": { "front": "y" } }), "front as one of"),
|
||||
(json!({ "orbit": { "up": "+z", "front": "-z" } }), "front perpendicular to up"),
|
||||
(json!({ "orbit": { "turn": [1] } }), "turn as [yaw, pitch]"),
|
||||
(json!({ "orbit": { "turn": [1, 2, 3] } }), "turn as [yaw, pitch]"),
|
||||
(json!({ "orbit": { "turn": 1 } }), "turn as [yaw, pitch]"),
|
||||
(json!({ "orbit": { "zoom": 0 } }), "zoom as a positive number"),
|
||||
(json!({ "orbit": { "zoom": -2 } }), "zoom as a positive number"),
|
||||
(json!({ "orbit": { "zoom": "a" } }), "zoom as a positive number"),
|
||||
(json!({ "orbit": { "zoom_at": [0.1, 0] } }), "with zoom when it has zoom_at"),
|
||||
(json!({ "orbit": { "zoom": 2, "zoom_at": [1] } }), "zoom_at as [right, up]"),
|
||||
(json!({ "orbit": { "zoom": 2, "zoom_at": [1, 2, 3] } }), "zoom_at as [right, up]"),
|
||||
(json!({ "orbit": { "pan": [1, "a"] } }), "pan as [right, up]"),
|
||||
(json!({ "orbit": { "pan": [1] } }), "pan as [right, up]"),
|
||||
(json!({ "orbit": { "pan": [1, 2, 3] } }), "pan as [right, up]"),
|
||||
(json!({ "orbit": { "spin": 1 } }), "without spin"),
|
||||
(json!({ "orbit": 1 }), "an object"),
|
||||
(json!({ "orbit": {}, "direction": [0, 0, -1] }), "left out when direction is given"),
|
||||
] {
|
||||
let mut args = json!({ "doc": doc, "page": 1, "width": 16, "height": 16 });
|
||||
args.as_object_mut().unwrap().extend(bad.as_object().unwrap().clone());
|
||||
let err = a.call("model_render", &args).unwrap_err().to_string();
|
||||
assert!(err.contains("orbit must be") && err.contains(reason), "{bad}: {err}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,8 +20,8 @@ let doc = Document::open(bytes)?; // Arc<Vec<u8>>
|
||||
let doc = Document::open_with_password(bytes, Some("owner"))?; // encrypted files
|
||||
|
||||
let root = doc.root(); // Option<ObjRef> — the catalog
|
||||
let obj = doc.get(ObjRef { num: 12, gen: 0 }); // load (and cache): Arc<Object>
|
||||
let real = doc.resolve(&obj); // follow one indirect reference
|
||||
let obj = doc.get(ObjRef::new(12, 0)); // load (and cache): Arc<Object>
|
||||
let real = doc.resolve(&obj); // follow a bounded reference chain
|
||||
let d = doc.dict(&obj); // Option<Dict>, resolving first
|
||||
let data = stream.decoded()?; // filters applied on demand
|
||||
let data = doc.with_direct_parms(&stream).decoded()?; // /DecodeParms given by reference too
|
||||
|
||||
@@ -209,6 +209,11 @@ impl ImageBudget {
|
||||
self.refused
|
||||
}
|
||||
|
||||
/// Charges `work` steps paid for out of another allowance, by a thread working on its own.
|
||||
pub fn charge(&mut self, work: u64) {
|
||||
self.work = self.work.saturating_sub(work);
|
||||
}
|
||||
|
||||
/// The steps of decoding still allowed.
|
||||
pub fn work_left(&self) -> u64 {
|
||||
self.work
|
||||
|
||||
@@ -25,12 +25,12 @@ mod writer;
|
||||
pub use budget::{DecodeBudget, ImageBudget, MAX_PAGE_DECODED, MAX_PAGE_FORMS, MAX_REDACTED_IMAGE_PIXELS};
|
||||
pub use bytes::Bytes;
|
||||
pub use document::{Document, ReadState, Revision, SourceIdentity, XrefEntry};
|
||||
pub use object::{Dict, MAX_DECODED, MAX_JBIG2_GLOBALS, Name, ObjRef, Object, PdfString, Stream};
|
||||
pub use object::{Dict, MAX_DECODED, MAX_JBIG2_GLOBALS, Name, ObjRef, Object, PdfString, Stream, TextChars};
|
||||
pub use parser::{Lexer, is_whitespace, parse_indirect};
|
||||
pub use pdfcraft_crypt::{
|
||||
Algorithm, Auth, Method as CryptMethod, NewEncryption, Permissions, SecurityHandler, effective_password, pdfdoc_byte, pdfdoc_char,
|
||||
};
|
||||
pub use writer::{SaveOptions, pdf_date, reachable_objects, serialize, write_full, write_incremental};
|
||||
pub use writer::{SaveOptions, civil_from_days, pdf_date, reachable_objects, serialize, write_full, write_incremental};
|
||||
|
||||
#[derive(Debug, thiserror::Error, Clone, PartialEq)]
|
||||
pub enum CosError {
|
||||
|
||||
+105
-7
@@ -57,19 +57,90 @@ impl PdfString {
|
||||
/// non-ASCII bytes (written by some producers) is read as UTF-8 rather than as
|
||||
/// PDFDocEncoding mojibake, and stray leading U+FEFF (doubled BOMs) are removed.
|
||||
pub fn to_text(&self) -> String {
|
||||
let s = match self.bytes.as_slice() {
|
||||
self.text_chars().collect()
|
||||
}
|
||||
|
||||
/// The characters [`PdfString::to_text`] decodes, one at a time, without building a string.
|
||||
pub fn text_chars(&self) -> TextChars<'_> {
|
||||
let decode = match self.bytes.as_slice() {
|
||||
[0xFE, 0xFF, rest @ ..] => {
|
||||
let units: Vec<u16> = rest.as_chunks::<2>().0.iter().map(|c| u16::from_be_bytes(*c)).collect();
|
||||
String::from_utf16_lossy(&units)
|
||||
let units: fn(&[u8; 2]) -> u16 = |c| u16::from_be_bytes(*c);
|
||||
Decode::Utf16(char::decode_utf16(rest.as_chunks::<2>().0.iter().map(units)))
|
||||
}
|
||||
[0xEF, 0xBB, 0xBF, rest @ ..] => String::from_utf8_lossy(rest).into_owned(),
|
||||
[0xEF, 0xBB, 0xBF, rest @ ..] => Decode::Utf8Lossy { chunks: rest.utf8_chunks(), valid: "".chars(), replace: false },
|
||||
b => match std::str::from_utf8(b) {
|
||||
// Pure ASCII is identical either way; only non-ASCII UTF-8 needs the switch.
|
||||
Ok(utf8) if !b.is_ascii() => utf8.to_owned(),
|
||||
_ => b.iter().map(|&c| pdfcraft_crypt::pdfdoc_char(c)).collect(),
|
||||
Ok(utf8) if !b.is_ascii() => Decode::Utf8(utf8.chars()),
|
||||
_ => Decode::PdfDoc(b.iter()),
|
||||
},
|
||||
};
|
||||
if s.starts_with('\u{FEFF}') { s.trim_start_matches('\u{FEFF}').to_owned() } else { s }
|
||||
TextChars { decode, leading: true }
|
||||
}
|
||||
|
||||
/// Whether the string decodes to `s` ([`PdfString::to_text`]), compared without allocating.
|
||||
pub fn text_eq(&self, s: &str) -> bool {
|
||||
self.text_chars().eq(s.chars())
|
||||
}
|
||||
}
|
||||
|
||||
/// The characters of a text string: [`PdfString::text_chars`].
|
||||
pub struct TextChars<'a> {
|
||||
decode: Decode<'a>,
|
||||
/// Still at the start, where stray U+FEFF (doubled BOMs) are dropped.
|
||||
leading: bool,
|
||||
}
|
||||
|
||||
/// The UTF-16BE code units after a BOM (an odd last byte is left out).
|
||||
type Utf16Units<'a> = std::iter::Map<std::slice::Iter<'a, [u8; 2]>, fn(&[u8; 2]) -> u16>;
|
||||
|
||||
enum Decode<'a> {
|
||||
Utf16(std::char::DecodeUtf16<Utf16Units<'a>>),
|
||||
/// After a UTF-8 BOM: each invalid sequence is one U+FFFD, as `String::from_utf8_lossy` has it.
|
||||
Utf8Lossy {
|
||||
chunks: std::str::Utf8Chunks<'a>,
|
||||
valid: std::str::Chars<'a>,
|
||||
replace: bool,
|
||||
},
|
||||
Utf8(std::str::Chars<'a>),
|
||||
PdfDoc(std::slice::Iter<'a, u8>),
|
||||
}
|
||||
|
||||
impl Iterator for Decode<'_> {
|
||||
type Item = char;
|
||||
|
||||
fn next(&mut self) -> Option<char> {
|
||||
match self {
|
||||
Decode::Utf16(units) => units.next().map(|u| u.unwrap_or(char::REPLACEMENT_CHARACTER)),
|
||||
Decode::Utf8Lossy { chunks, valid, replace } => loop {
|
||||
if let Some(c) = valid.next() {
|
||||
return Some(c);
|
||||
}
|
||||
if *replace {
|
||||
*replace = false;
|
||||
return Some(char::REPLACEMENT_CHARACTER);
|
||||
}
|
||||
let chunk = chunks.next()?;
|
||||
*valid = chunk.valid().chars();
|
||||
*replace = !chunk.invalid().is_empty();
|
||||
},
|
||||
Decode::Utf8(chars) => chars.next(),
|
||||
Decode::PdfDoc(bytes) => bytes.next().map(|&c| pdfcraft_crypt::pdfdoc_char(c)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Iterator for TextChars<'_> {
|
||||
type Item = char;
|
||||
|
||||
fn next(&mut self) -> Option<char> {
|
||||
loop {
|
||||
let c = self.decode.next()?;
|
||||
if self.leading && c == '\u{FEFF}' {
|
||||
continue;
|
||||
}
|
||||
self.leading = false;
|
||||
return Some(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -594,6 +665,33 @@ mod tests {
|
||||
assert_eq!(PdfString::literal(Vec::new()).to_text(), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_eq_compares_what_to_text_decodes() {
|
||||
let utf16 = |s: &str| [0xFE, 0xFF].into_iter().chain(s.encode_utf16().flat_map(u16::to_be_bytes)).collect::<Vec<u8>>();
|
||||
// Each invalid UTF-8 sequence is one U+FFFD, as String::from_utf8_lossy has it.
|
||||
let lossy = [0xEF, 0xBB, 0xBF, 0xC3, 0x28, b'x', 0xF0, 0x9F, 0x92, 0xFF];
|
||||
assert_eq!(PdfString::literal(lossy.to_vec()).to_text(), String::from_utf8_lossy(&lossy[3..]));
|
||||
let cases: Vec<Vec<u8>> = vec![
|
||||
Vec::new(),
|
||||
b"Plain".to_vec(),
|
||||
vec![b'C', b'a', b'f', 0xE9, 0x18],
|
||||
"目录".as_bytes().to_vec(),
|
||||
utf16("第一章"),
|
||||
vec![0xFE, 0xFF, 0xD8, 0x00, 0x00, b'A'],
|
||||
vec![0xFE, 0xFF, 0xFE, 0xFF, 0x00, b'A', 0xFE, 0xFF],
|
||||
lossy.to_vec(),
|
||||
];
|
||||
for bytes in cases {
|
||||
let s = PdfString::literal(bytes);
|
||||
let text = s.to_text();
|
||||
assert!(s.text_eq(&text), "{text:?}");
|
||||
assert!(!s.text_eq(&format!("{text}x")), "{text:?}");
|
||||
assert!(text.is_empty() || !s.text_eq(&text[..text.len() - text.chars().last().map_or(0, char::len_utf8)]), "{text:?}");
|
||||
}
|
||||
// A U+FEFF after the first character is text and stays.
|
||||
assert!(PdfString::literal(utf16("A\u{FEFF}")).text_eq("A\u{FEFF}"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pdfdoc_encoding_high_range() {
|
||||
assert_eq!(PdfString::literal(vec![0x84, 0x92, 0xA0, b'A']).to_text(), "—™€A");
|
||||
|
||||
@@ -919,14 +919,14 @@ pub fn pdf_date(unix_secs: i64) -> String {
|
||||
format!("D:{y:04}{m:02}{d:02}{:02}{:02}{:02}Z", secs / 3600, secs / 60 % 60, secs % 60)
|
||||
}
|
||||
|
||||
/// Days since 1970-01-01 → proleptic Gregorian (year, month, day).
|
||||
/// Days since 1970-01-01 → proleptic Gregorian (year, month, day). Total for any `i64` count:
|
||||
/// dates past `NaiveDate`'s ±262143-year range keep their proleptic Gregorian year instead of
|
||||
/// falling back to the epoch.
|
||||
///
|
||||
/// A `from_timestamp` epoch fallback would change dates past `NaiveDate`'s ±262143-year range,
|
||||
/// which the old hand-rolled converter formatted directly. The Gregorian calendar repeats every
|
||||
/// 400 years (146_097 days), so chrono converts the day within one cycle and whole cycles go back
|
||||
/// into the year (an `i128` so the extremes can't overflow), keeping chrono as the only calendar
|
||||
/// logic and reproducing the old result exactly. 1970-01-01 is `num_days_from_ce` 719_163.
|
||||
fn civil_from_days(days: i64) -> (i64, u32, u32) {
|
||||
/// The Gregorian calendar repeats every 400 years (146_097 days), so chrono converts the day
|
||||
/// within one cycle and whole cycles go back into the year (an `i128` so the extremes can't
|
||||
/// overflow), keeping chrono as the only calendar logic. 1970-01-01 is `num_days_from_ce` 719_163.
|
||||
pub fn civil_from_days(days: i64) -> (i64, u32, u32) {
|
||||
use chrono::Datelike;
|
||||
let (cycles, rest) = (days.div_euclid(146_097), days.rem_euclid(146_097));
|
||||
// `rest + 719_163` is 719_163..865_259, always a valid CE day.
|
||||
@@ -1110,6 +1110,12 @@ mod tests {
|
||||
// its sign, exactly as before).
|
||||
assert_eq!(pdf_date(10_000_000_000_000), "D:3188570520174640Z");
|
||||
assert_eq!(pdf_date(-10_000_000_000_000), "D:-3149180813061320Z");
|
||||
assert_eq!(crate::civil_from_days(0), (1970, 1, 1));
|
||||
assert_eq!(crate::civil_from_days(-1), (1969, 12, 31));
|
||||
assert_eq!(crate::civil_from_days(11_016), (2000, 2, 29));
|
||||
assert_eq!(crate::civil_from_days(19_782), (2024, 2, 29));
|
||||
assert_eq!(crate::civil_from_days(i64::MAX), (25_252_734_927_768_524, 7, 27));
|
||||
assert_eq!(crate::civil_from_days(i64::MIN), (-25_252_734_927_764_585, 6, 7));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -302,9 +302,14 @@ thread_local! {
|
||||
}
|
||||
|
||||
/// The size a JPEG's header gives, which is what decoding it goes by, whatever its dictionary
|
||||
/// says: an image of one pixel can hold a header of 500 megapixels.
|
||||
/// says: an image of one pixel can hold a header of 500 megapixels. `None`, as for a JPEG that
|
||||
/// can't be read, when its metadata would take the decoder quadratic time
|
||||
/// ([`decodable_metadata`](crate::upright_image::decodable_metadata)).
|
||||
fn jpeg_size(data: &[u8]) -> Option<(usize, usize)> {
|
||||
use zune_jpeg::zune_core::{bytestream::ZCursor, options::DecoderOptions};
|
||||
if !crate::upright_image::decodable_metadata(data) {
|
||||
return None;
|
||||
}
|
||||
let options = DecoderOptions::default().set_strict_mode(false).set_max_width(usize::from(u16::MAX)).set_max_height(usize::from(u16::MAX));
|
||||
let mut dec = zune_jpeg::JpegDecoder::new_with_options(ZCursor::new(data), options);
|
||||
dec.decode_headers().ok()?;
|
||||
@@ -329,6 +334,15 @@ fn jpeg_samples(data: &[u8], space: &Space, w: usize, h: usize) -> Option<(Vec<u
|
||||
Space::Cmyk => return cmyk_jpeg_samples(data, w, h).map(|px| (px, Space::Cmyk)),
|
||||
_ => {}
|
||||
}
|
||||
// Past the decoder's metadata bound, drop the Extended XMP chunks rather than the mask:
|
||||
// decoded as it stands, an over-chunked JPEG is written as is, without its /SMask.
|
||||
let stripped;
|
||||
let data = if crate::upright_image::decodable_metadata(data) {
|
||||
data
|
||||
} else {
|
||||
stripped = crate::upright_image::without_extended_xmp(data);
|
||||
&stripped[..]
|
||||
};
|
||||
let img = jpeg_of_size(data, w, h)?;
|
||||
Some(match space {
|
||||
Space::Gray => (img.into_luma8().into_raw(), Space::Gray),
|
||||
@@ -340,6 +354,15 @@ fn jpeg_samples(data: &[u8], space: &Space, w: usize, h: usize) -> Option<(Vec<u
|
||||
/// a decoder converting to RGB inverts them, with YCCK converted to CMYK.
|
||||
fn cmyk_jpeg_samples(data: &[u8], w: usize, h: usize) -> Option<Vec<u8>> {
|
||||
use zune_jpeg::zune_core::{bytestream::ZCursor, colorspace::ColorSpace, options::DecoderOptions};
|
||||
// Past the decoder's metadata bound, decode the image without its Extended XMP chunks
|
||||
// rather than not at all: written out as stored, a CMYK JPEG shows inverted colours.
|
||||
let stripped;
|
||||
let data = if crate::upright_image::decodable_metadata(data) {
|
||||
data
|
||||
} else {
|
||||
stripped = crate::upright_image::without_extended_xmp(data);
|
||||
&stripped[..]
|
||||
};
|
||||
let options = DecoderOptions::default().set_strict_mode(false).set_max_width(usize::from(u16::MAX)).set_max_height(usize::from(u16::MAX));
|
||||
let mut dec = zune_jpeg::JpegDecoder::new_with_options(ZCursor::new(data), options);
|
||||
dec.decode_headers().ok()?;
|
||||
|
||||
@@ -941,6 +941,43 @@ fn damaged_masks_and_sizes_never_panic() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_jpeg_with_thousands_of_extended_xmp_chunks_keeps_its_mask() {
|
||||
// Export decodes a JPEG with a soft mask, or a JPEG soft mask, to make a PNG with alpha. A JPEG
|
||||
// whose Extended XMP chunks would take the decoder quadratic time is decoded without them,
|
||||
// which is linear in what is left, so the mask survives; a JPEG mask past the same bound is
|
||||
// still left out, without reaching the decoder.
|
||||
let flood = crate::upright_image::tests::with_extended_xmp_chunks(&real_jpeg(), 5_000);
|
||||
let mut doc = from_images(&[("flat.png".into(), png_bytes(false))]).unwrap();
|
||||
with_image(&mut doc, |doc| {
|
||||
let mask = doc.add(Object::Stream(Stream::from_raw(image_dict(4, 2, "DeviceGray", 8), vec![0; 8])));
|
||||
let mut d = image_dict(4, 2, "DeviceGray", 8);
|
||||
d.set(b"Filter".to_vec(), Object::name("DCTDecode"));
|
||||
d.set(b"SMask".to_vec(), Object::Ref(mask));
|
||||
Stream::from_raw(d, flood.clone())
|
||||
});
|
||||
crate::extract::JPEGS_DECODED.with(|n| n.set(0));
|
||||
let out = extract_images(&doc, &[0], 0);
|
||||
assert_eq!(out.images[0].extension, "png");
|
||||
assert_eq!(crate::extract::JPEGS_DECODED.with(std::cell::Cell::get), 1);
|
||||
// The chunks themselves are gone, so the decoder never saw them.
|
||||
assert!(!out.images[0].data.windows(5).any(|w| w == b"http:"));
|
||||
|
||||
crate::extract::JPEGS_DECODED.with(|n| n.set(0));
|
||||
|
||||
let mut doc = from_images(&[("flat.png".into(), png_bytes(false))]).unwrap();
|
||||
with_image(&mut doc, |doc| {
|
||||
let mut md = image_dict(4, 2, "DeviceGray", 8);
|
||||
md.set(b"Filter".to_vec(), Object::name("DCTDecode"));
|
||||
let mask = doc.add(Object::Stream(Stream::from_raw(md, flood.clone())));
|
||||
let mut d = image_dict(4, 2, "DeviceRGB", 8);
|
||||
d.set(b"SMask".to_vec(), Object::Ref(mask));
|
||||
Stream::from_raw(d, vec![10; 24])
|
||||
});
|
||||
assert_eq!(alphas(&exported_rgba(&doc).1), [255; 8]);
|
||||
assert_eq!(crate::extract::JPEGS_DECODED.with(std::cell::Cell::get), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn indexed_image_export_clamps_samples_to_hival() {
|
||||
for palette in [vec![255, 0, 0, 0, 0, 255], vec![255, 0, 0, 0, 0, 255, 0, 255, 0, 255, 255, 255]] {
|
||||
@@ -2788,3 +2825,30 @@ fn proportions_up_to_the_limit_scale_as_they_did() {
|
||||
let mask = noise(20, 10);
|
||||
assert_eq!(crate::extract::scaled(&mask, 20, 10), mask);
|
||||
}
|
||||
|
||||
/// A CMYK JPEG past the decoder's Extended XMP bound is still decoded (its chunks left out) and
|
||||
/// exported with the colours the page shows, not written as stored, which inverts them.
|
||||
#[test]
|
||||
fn a_cmyk_jpeg_flooded_with_extended_xmp_is_exported_in_its_colours() {
|
||||
let jpeg = crate::upright_image::tests::with_extended_xmp_chunks(&flat_four_component_jpeg([255, 0, 0, 0], 0), 5_000);
|
||||
let mut doc = from_images(&[("flat.png".into(), png_bytes(false))]).unwrap();
|
||||
with_image(&mut doc, |doc| {
|
||||
let mut d = image_dict(8, 8, "DeviceCMYK", 8);
|
||||
d.set(b"Filter".to_vec(), Object::name("DCTDecode"));
|
||||
let m = doc.add(Object::Stream(Stream::from_raw(image_dict(8, 8, "DeviceGray", 8), vec![255; 64])));
|
||||
d.set(b"SMask".to_vec(), Object::Ref(m));
|
||||
Stream::from_raw(d, jpeg.clone())
|
||||
});
|
||||
let (_, rgba) = exported_rgba(&doc);
|
||||
assert!(rgba.as_chunks::<4>().0.iter().all(|p| p[0] <= 6 && p[1] >= 249 && p[2] >= 249), "{:?}", &rgba[..4]);
|
||||
}
|
||||
|
||||
/// Stripping leaves everything but the Extended XMP chunks, byte for byte.
|
||||
#[test]
|
||||
fn stripping_extended_xmp_leaves_the_rest_of_the_jpeg() {
|
||||
let plain = flat_four_component_jpeg([255, 0, 0, 0], 0);
|
||||
let flooded = crate::upright_image::tests::with_extended_xmp_chunks(&plain, 3);
|
||||
assert_ne!(flooded, plain);
|
||||
// The helper puts a stray byte before the chunks, which the decoder skips: it stays.
|
||||
assert_eq!(crate::upright_image::without_extended_xmp(&flooded), [&plain[..2], b"\0".as_slice(), &plain[2..]].concat());
|
||||
}
|
||||
|
||||
@@ -30,7 +30,7 @@ pub(crate) fn upright(bytes: &[u8]) -> Cow<'_, [u8]> {
|
||||
}
|
||||
|
||||
fn turned(bytes: &[u8]) -> Option<Vec<u8>> {
|
||||
if !bytes.starts_with(&[0xFF, 0xD8]) || extended_xmp_chunks(bytes) > MAX_EXTENDED_XMP_CHUNKS {
|
||||
if !bytes.starts_with(&[0xFF, 0xD8]) || !decodable_metadata(bytes) {
|
||||
return None;
|
||||
}
|
||||
#[cfg(test)]
|
||||
@@ -65,10 +65,41 @@ fn turned(bytes: &[u8]) -> Option<Vec<u8>> {
|
||||
/// decoder re-sorts and rescans every chunk so far after each marker, quadratic in their number.
|
||||
const MAX_EXTENDED_XMP_CHUNKS: usize = 1024;
|
||||
|
||||
/// Whether JPEG `bytes` may be handed to a decoder (`image`'s or `zune-jpeg`'s, which `image` uses),
|
||||
/// headers included: not when it carries more than [`MAX_EXTENDED_XMP_CHUNKS`]. Every path that
|
||||
/// decodes a JPEG from a file checks this first: image import here, and image export.
|
||||
pub(crate) fn decodable_metadata(bytes: &[u8]) -> bool {
|
||||
extended_xmp_chunks(bytes) <= MAX_EXTENDED_XMP_CHUNKS
|
||||
}
|
||||
|
||||
/// How many Extended XMP chunks (APP1 segments) come before the image data.
|
||||
fn extended_xmp_chunks(bytes: &[u8]) -> usize {
|
||||
let mut chunks = 0usize;
|
||||
each_extended_xmp(bytes, |_| chunks += 1);
|
||||
chunks
|
||||
}
|
||||
|
||||
/// JPEG `bytes` without their Extended XMP chunks, which nothing here reads: what is left decodes
|
||||
/// in time linear in its size however many chunks the file carried.
|
||||
pub(crate) fn without_extended_xmp(bytes: &[u8]) -> Vec<u8> {
|
||||
// Only the bytes that are kept: a CMYK JPEG can be mostly Extended XMP, and reserving the
|
||||
// whole file for the little that remains aborts the export under a tight address-space limit.
|
||||
let mut removed = 0usize;
|
||||
each_extended_xmp(bytes, |r| removed = removed.saturating_add(r.len()));
|
||||
let mut out = Vec::with_capacity(bytes.len().saturating_sub(removed));
|
||||
let mut at = 0;
|
||||
each_extended_xmp(bytes, |r| {
|
||||
out.extend_from_slice(bytes.get(at..r.start).unwrap_or_default());
|
||||
at = r.end;
|
||||
});
|
||||
out.extend_from_slice(bytes.get(at..).unwrap_or_default());
|
||||
out
|
||||
}
|
||||
|
||||
/// Calls `f` with the byte range of each Extended XMP chunk (APP1 segment) before the image data.
|
||||
fn each_extended_xmp(bytes: &[u8], mut f: impl FnMut(std::ops::Range<usize>)) {
|
||||
const PREFIX: &[u8] = b"http://ns.adobe.com/xmp/extension/\0";
|
||||
let (mut i, mut chunks) = (2usize, 0usize);
|
||||
let mut i = 2usize;
|
||||
while let Some(&byte) = bytes.get(i) {
|
||||
// Stray bytes between segments, which the decoder skips too.
|
||||
if byte != 0xFF {
|
||||
@@ -86,14 +117,16 @@ fn extended_xmp_chunks(bytes: &[u8]) -> usize {
|
||||
_ => {
|
||||
let Some(&[hi, lo]) = bytes.get(i.saturating_add(2)..i.saturating_add(4)) else { break };
|
||||
let len = usize::from(u16::from_be_bytes([hi, lo]));
|
||||
if marker == 0xE1 && bytes.get(i.saturating_add(4)..).is_some_and(|seg| seg.starts_with(PREFIX)) {
|
||||
chunks += 1;
|
||||
let end = i.saturating_add(2).saturating_add(len.max(2));
|
||||
// The prefix must start the APP1 segment's own payload: a zero-length header
|
||||
// followed by prefix bytes is not a chunk.
|
||||
if marker == 0xE1 && bytes.get(i.saturating_add(4)..end.min(bytes.len())).is_some_and(|seg| seg.starts_with(PREFIX)) {
|
||||
f(i..end.min(bytes.len()));
|
||||
}
|
||||
i = i.saturating_add(2).saturating_add(len.max(2));
|
||||
i = end;
|
||||
}
|
||||
}
|
||||
}
|
||||
chunks
|
||||
}
|
||||
|
||||
/// The resolution in a JFIF header, if the file has one in inches or centimetres.
|
||||
@@ -120,7 +153,7 @@ fn jfif_density(bytes: &[u8]) -> Option<PixelDensity> {
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
pub(crate) mod tests {
|
||||
use super::*;
|
||||
use crate::tests::phone_jpeg;
|
||||
|
||||
@@ -138,22 +171,24 @@ mod tests {
|
||||
assert!(matches!(upright(b"\xff\xd8 not a jpeg"), Cow::Borrowed(_)));
|
||||
}
|
||||
|
||||
/// `jpeg` with `n` empty chunks of one never-complete Extended XMP packet after its SOI.
|
||||
pub(crate) fn with_extended_xmp_chunks(jpeg: &[u8], n: usize) -> Vec<u8> {
|
||||
let mut seg = b"http://ns.adobe.com/xmp/extension/\0".to_vec();
|
||||
seg.extend_from_slice(&[b'0'; 32]); // the packet's GUID
|
||||
seg.extend_from_slice(&1000u32.to_be_bytes()); // its full length
|
||||
seg.extend_from_slice(&0u32.to_be_bytes()); // this chunk's offset
|
||||
let mut chunk = vec![0xFF, 0xE1];
|
||||
chunk.extend_from_slice(&u16::try_from(seg.len() + 2).unwrap().to_be_bytes());
|
||||
chunk.extend_from_slice(&seg);
|
||||
[&jpeg[..2], b"\0".as_slice(), &chunk.repeat(n), &jpeg[2..]].concat()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_jpeg_with_thousands_of_extended_xmp_chunks_is_not_decoded() {
|
||||
// Empty chunks of one never-complete extended packet: the decoder re-sorts and rescans every
|
||||
// chunk so far after each marker, quadratic in their number.
|
||||
let chunk = |n: usize| {
|
||||
let mut seg = b"http://ns.adobe.com/xmp/extension/\0".to_vec();
|
||||
seg.extend_from_slice(&[b'0'; 32]); // the packet's GUID
|
||||
seg.extend_from_slice(&1000u32.to_be_bytes()); // its full length
|
||||
seg.extend_from_slice(&0u32.to_be_bytes()); // this chunk's offset
|
||||
let mut out = vec![0xFF, 0xE1];
|
||||
out.extend_from_slice(&u16::try_from(seg.len() + 2).unwrap().to_be_bytes());
|
||||
out.extend_from_slice(&seg);
|
||||
out.repeat(n)
|
||||
};
|
||||
let photo = phone_jpeg(6, 144);
|
||||
let with = |n: usize| [&photo[..2], b"\0".as_slice(), &chunk(n), &photo[2..]].concat();
|
||||
let with = |n: usize| with_extended_xmp_chunks(&photo, n);
|
||||
DECODES.with(|c| c.set(0));
|
||||
assert!(matches!(upright(&with(4)), Cow::Owned(_)), "a few chunks are an ordinary photo");
|
||||
assert!(matches!(upright(&with(5_000)), Cow::Borrowed(_)));
|
||||
|
||||
+16
-3
@@ -302,20 +302,33 @@ impl SecurityHandler {
|
||||
}
|
||||
}
|
||||
|
||||
/// Algorithm 1 (§7.6.3.3): the key for one object. AES-256 uses the file key directly.
|
||||
/// Algorithm 1 (§7.6.3.2): the key for one object. AES-256 uses the file key directly
|
||||
/// (Algorithm 1.A, §7.6.3.3).
|
||||
///
|
||||
/// For an RC4 crypt filter under `/V 4`, a file key shorter than 16 bytes is first extended
|
||||
/// to 16 bytes with zeros. The standard doesn't say so (Algorithm 1 takes the n-byte key as
|
||||
/// it is), but that is how Acrobat writes and reads such files: a `/V 4` RC4 crypt filter
|
||||
/// with a 40- or 48-bit key (pdf.js issue 19484). The renderer's `hayro-syntax` reads them
|
||||
/// the same way, so a page it shows is one this crate can read and save. AES-128 keys are
|
||||
/// left as they are: `AESV2` takes a 128-bit key (Table 25), and Acrobat's extension is only
|
||||
/// seen with RC4. Every key PdfCraft writes under `/V 4` is 16 bytes already.
|
||||
fn object_key(&self, method: Method, num: u32, generation: u16) -> Vec<u8> {
|
||||
if method == Method::Aes256 {
|
||||
return self.key.clone();
|
||||
}
|
||||
let mut key = self.key.clone();
|
||||
if method == Method::Rc4 && self.dict.v == 4 && key.len() < 16 {
|
||||
key.resize(16, 0);
|
||||
}
|
||||
let mut h = Md5::new();
|
||||
h.update(&self.key);
|
||||
h.update(&key);
|
||||
h.update(&num.to_le_bytes()[..3]);
|
||||
h.update(generation.to_le_bytes());
|
||||
if method == Method::Aes128 {
|
||||
h.update(b"sAlT");
|
||||
}
|
||||
let digest = h.finalize();
|
||||
digest[..(self.key.len() + 5).min(16)].to_vec()
|
||||
digest[..(key.len() + 5).min(16)].to_vec()
|
||||
}
|
||||
|
||||
fn apply(&self, method: Method, num: u32, generation: u16, data: &[u8], encrypt: bool) -> Vec<u8> {
|
||||
|
||||
@@ -280,6 +280,69 @@ proptest::proptest! {
|
||||
}
|
||||
}
|
||||
|
||||
/// A `/V 4` RC4 crypt filter with a 40- or 48-bit key, as Acrobat writes it (pdf.js issue 19484):
|
||||
/// the file key is extended to 16 bytes with zeros before Algorithm 1, so each object's key is
|
||||
/// all 16 bytes of MD5(key, zeros, object, generation). Everything else keeps Algorithm 1 as the
|
||||
/// standard has it, n + 5 bytes (at most 16) of MD5(key, object, generation[, "sAlT"]): a `/V 2`
|
||||
/// file with the same short key, a full 128-bit `/V 4` RC4 key, and AESV2, short (88 bits) or
|
||||
/// full. Each object key is computed here by hand; data written with it must decrypt.
|
||||
#[test]
|
||||
fn a_v4_rc4_key_shorter_than_16_bytes_is_extended_with_zeros() {
|
||||
let text = b"Page tree in an object stream".to_vec();
|
||||
let cases =
|
||||
[(4, 40, Method::Rc4), (4, 48, Method::Rc4), (2, 40, Method::Rc4), (4, 128, Method::Rc4), (4, 88, Method::Aes128), (4, 128, Method::Aes128)];
|
||||
for (v, bits, method) in cases {
|
||||
let mut d = EncryptDict {
|
||||
filter: b"Standard".to_vec(),
|
||||
v,
|
||||
r: if v == 4 { 4 } else { 3 },
|
||||
length_bits: bits,
|
||||
o: vec![7; 32],
|
||||
p: -3392,
|
||||
encrypt_metadata: v != 4,
|
||||
..Default::default()
|
||||
};
|
||||
if v == 4 {
|
||||
d.crypt_filters = vec![(b"StdCF".to_vec(), method)];
|
||||
d.stm_f = b"StdCF".to_vec();
|
||||
d.str_f = b"StdCF".to_vec();
|
||||
}
|
||||
let key = file_key_r4(&d, ID, b"");
|
||||
assert_eq!(key.len(), (bits / 8) as usize);
|
||||
d.u = u_value_r4(&d, ID, &key);
|
||||
let h = SecurityHandler::open(d, ID, None).unwrap();
|
||||
let (num, generation) = (13u32, 0u16);
|
||||
let extended = v == 4 && method == Method::Rc4 && key.len() < 16;
|
||||
let mut md5 = Md5::new();
|
||||
md5.update(&key);
|
||||
if extended {
|
||||
md5.update(vec![0u8; 16 - key.len()]);
|
||||
}
|
||||
md5.update(&num.to_le_bytes()[..3]);
|
||||
md5.update(generation.to_le_bytes());
|
||||
if method == Method::Aes128 {
|
||||
md5.update(b"sAlT");
|
||||
}
|
||||
let digest = md5.finalize();
|
||||
let n = if extended { 16 } else { key.len() };
|
||||
let object_key = digest[..(n + 5).min(16)].to_vec();
|
||||
let case = format!("V{v}, {bits}-bit key, {method:?}");
|
||||
let written = if method == Method::Rc4 {
|
||||
rc4(&object_key, &text)
|
||||
} else {
|
||||
let iv = [3u8; 16];
|
||||
[iv.to_vec(), aes_cbc_encrypt(&object_key, &iv, &text, true)].concat()
|
||||
};
|
||||
assert_eq!(h.decrypt_string(num, generation, &written), text, "{case}");
|
||||
assert_eq!(h.decrypt_stream(num, generation, &written, StreamKind::Normal), text, "{case}");
|
||||
let saved = h.encrypt_stream(num, generation, &text, StreamKind::Normal);
|
||||
if method == Method::Rc4 {
|
||||
assert_eq!(saved, written, "saved as it was read: {case}");
|
||||
}
|
||||
assert_eq!(h.decrypt_stream(num, generation, &saved, StreamKind::Normal), text, "{case}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn owner_authentication_recovers_the_user_password() {
|
||||
for alg in [Algorithm::Rc4_40, Algorithm::Rc4_128, Algorithm::Aes128] {
|
||||
|
||||
@@ -54,16 +54,21 @@ pub(super) fn wrapped(t: &AddedText) -> Vec<(String, bool, usize)> {
|
||||
let measure = |s: &str| if rtl_script || thai { shaped_width(t, s, rtl) } else { latin_width(t, s) };
|
||||
let space = measure(" ");
|
||||
let (mut line, mut line_w) = (String::new(), 0.0);
|
||||
// Widths add up (the standard-14 widths have no kerning), so each word is measured once
|
||||
// and appended in place: a line that never fills (negative character spacing) stays
|
||||
// linear instead of being copied and measured again for every word.
|
||||
for word in para.split(' ') {
|
||||
let candidate = if line.is_empty() { word.to_string() } else { format!("{line} {word}") };
|
||||
let candidate_w =
|
||||
if rtl_script || thai { if line.is_empty() { measure(word) } else { line_w + space + measure(word) } } else { measure(&candidate) };
|
||||
let word_w = measure(word);
|
||||
let candidate_w = if line.is_empty() { word_w } else { line_w + space + word_w };
|
||||
if !line.is_empty() && candidate_w > width {
|
||||
out.push((std::mem::take(&mut line), rtl, index));
|
||||
line = word.to_string();
|
||||
line_w = measure(word);
|
||||
line.push_str(word);
|
||||
line_w = word_w;
|
||||
} else {
|
||||
line = candidate;
|
||||
if !line.is_empty() {
|
||||
line.push(' ');
|
||||
}
|
||||
line.push_str(word);
|
||||
line_w = candidate_w;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -328,8 +328,15 @@ pub fn isolate_content(doc: &mut Document, page: usize, index: usize) -> Result<
|
||||
/// names them so), so they go when the item is replaced or deleted.
|
||||
fn own_fonts(doc: &Document, obj: ObjRef) -> Vec<Vec<u8>> {
|
||||
let Object::Stream(s) = &*doc.get(obj) else { return Vec::new() };
|
||||
let Ok(data) = s.decoded() else { return Vec::new() };
|
||||
data.split(u8::is_ascii_whitespace).filter_map(|w| w.strip_prefix(b"/")).filter(|w| w.starts_with(b"PCAr")).map(<[u8]>::to_vec).collect()
|
||||
// The stream is one this writer put there, so its decode is bounded by the stream itself: the
|
||||
// page limit alone would refuse an item larger than a page's content, and its fonts would stay
|
||||
// on the page's /Font, which `write` and `delete_content` are supposed to take them off.
|
||||
let limit = pdfcraft_cos::MAX_PAGE_DECODED.max(s.raw.len().saturating_mul(16));
|
||||
let Ok(data) = s.decoded_within(limit) else { return Vec::new() };
|
||||
// Each name once: a stream that repeats a name is not copied out once per use.
|
||||
let names: std::collections::BTreeSet<&[u8]> =
|
||||
data.split(u8::is_ascii_whitespace).filter_map(|w| w.strip_prefix(b"/")).filter(|w| w.starts_with(b"PCAr")).collect();
|
||||
names.into_iter().map(<[u8]>::to_vec).collect()
|
||||
}
|
||||
|
||||
fn drop_fonts(doc: &Document, res: &mut Dict, names: &[Vec<u8>]) {
|
||||
|
||||
@@ -183,6 +183,19 @@ fn flatten_which(doc: &mut Document, pages: &[usize], which: Which) -> Result<us
|
||||
Ok(drawn)
|
||||
}
|
||||
|
||||
/// `page` with what its own dictionary holds now, after an edit: re-reading this one page,
|
||||
/// where walking the whole page tree again for every flattened page would be quadratic.
|
||||
/// Inherited attributes stay as they were collected, under the page's own entries.
|
||||
fn refreshed(doc: &Document, page: &pdfcraft_model::Page) -> pdfcraft_model::Page {
|
||||
let mut dict = page.dict.clone();
|
||||
if let Some(own) = doc.get(page.obj).as_dict() {
|
||||
for (k, v) in own.iter() {
|
||||
dict.set(k.clone(), v.clone());
|
||||
}
|
||||
}
|
||||
pdfcraft_model::Page { obj: page.obj, dict }
|
||||
}
|
||||
|
||||
fn flatten_in(doc: &mut Document, pages: &[usize], which: Which) -> Result<usize, EditError> {
|
||||
let all = page_list(doc);
|
||||
check(pages, all.len())?;
|
||||
@@ -322,10 +335,10 @@ fn flatten_in(doc: &mut Document, pages: &[usize], which: Which) -> Result<usize
|
||||
}
|
||||
res.set(b"XObject".to_vec(), Object::Dict(xo));
|
||||
doc.update_dict(page.obj, |d| d.set(b"Resources".to_vec(), Object::Dict(res)))?;
|
||||
let page = page_list(doc)[i].clone();
|
||||
let page = refreshed(doc, &page);
|
||||
place_tagged(doc, &page, "Flattened", content.into_bytes(), false)?;
|
||||
}
|
||||
let page_now = page_list(doc)[i].clone();
|
||||
let page_now = refreshed(doc, &page);
|
||||
match page_now.dict.get(b"Annots").and_then(|a| a.as_ref()).filter(|r| doc.get(*r).as_array().is_some()) {
|
||||
Some(r) => doc.set(r, Object::Array(kept)),
|
||||
None => doc.update_dict(page.obj, |d| {
|
||||
|
||||
@@ -1521,6 +1521,45 @@ fn text_page(content: &str) -> Document {
|
||||
Document::open(Arc::new(out)).unwrap()
|
||||
}
|
||||
|
||||
/// ISO 32000-2 §9.6.4: an Edit-text line set in a Type 3 bitmap font is as high as the boxes its
|
||||
/// glyphs declare with `d1`, whatever its `/FontBBox` says and whichever way its font matrix
|
||||
/// turns glyph space, so two lines 8 points apart are two lines with 7-point boxes, not slivers.
|
||||
#[test]
|
||||
fn edit_lines_in_a_type3_font_are_as_high_as_their_glyphs() {
|
||||
// Glyph `a` is drawn 60 units wide, from 20 below the baseline to 50 above it, at 0.1 Tf:
|
||||
// 7 points high, 2 below the baseline.
|
||||
for (matrix, flip) in [("1 0 0 1 0 0", 1), ("1 0 0 -1 0 0", -1)] {
|
||||
for bbox in ["[0 0 0 0]", "[0 0 1 1]"] {
|
||||
let mut doc = text_page(&format!("BT /T3 0.1 Tf 1 0 0 {flip} 72 700 Tm (aa) Tj 1 0 0 {flip} 72 692 Tm (aa) Tj ET"));
|
||||
let glyph = doc.add(Object::Stream(Stream::from_raw(Dict::new(), b"60 0 0 -20 60 50 d1 0 -20 60 70 re f".to_vec())));
|
||||
let font = doc.add(
|
||||
pdfcraft_cos::parse_indirect(
|
||||
format!(
|
||||
"1 0 obj << /Type /Font /Subtype /Type3 /FontMatrix [{matrix}] /FontBBox {bbox} /FirstChar 97 /LastChar 97 /Widths [60] /Encoding << /Differences [97 /a] >> /CharProcs << /a {} 0 R >> >> endobj",
|
||||
glyph.num
|
||||
)
|
||||
.as_bytes(),
|
||||
0,
|
||||
&|_| None,
|
||||
)
|
||||
.unwrap()
|
||||
.1,
|
||||
);
|
||||
let p = pdfcraft_model::pages(&doc)[0].obj;
|
||||
doc.update_dict(p, |d| {
|
||||
d.set(
|
||||
b"Resources".to_vec(),
|
||||
Object::Dict(Dict::from_iter([(b"Font".to_vec(), Object::Dict(Dict::from_iter([(b"T3".to_vec(), Object::Ref(font))])))])),
|
||||
)
|
||||
})
|
||||
.unwrap();
|
||||
let lines = text::text_lines(&doc, 0).unwrap();
|
||||
let rects: Vec<_> = lines.iter().map(|l| (l.text.as_str(), l.rect.map(|v| (v * 100.0).round() / 100.0))).collect();
|
||||
assert_eq!(rects, [("aa", [72.0, 698.0, 84.0, 705.0]), ("aa", [72.0, 690.0, 84.0, 697.0])], "{matrix} {bbox}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tracked_text_keeps_words_in_paragraphs_and_objects() {
|
||||
let expected = "TRACKED SAMPLE TEXT";
|
||||
@@ -9748,6 +9787,20 @@ fn added_text_is_wrapped_once_per_write() {
|
||||
assert!(calls <= 4, "the text was wrapped {calls} times for 40 lines");
|
||||
}
|
||||
|
||||
/// Negative character spacing keeps a line from ever filling its box. Wrapping then holds every
|
||||
/// word on one line, appended and measured once each rather than copied and measured again for
|
||||
/// each word (which took minutes for this text); the widths still decide the breaks.
|
||||
#[test]
|
||||
fn added_text_that_never_fills_its_line_wraps_in_linear_time() {
|
||||
let words = vec!["word"; 200_000].join(" ");
|
||||
let packed = AddedText { rect: [0.0, 0.0, 100.0, 100.0], text: words.clone(), char_spacing: -10.0, ..AddedText::default() };
|
||||
let start = std::time::Instant::now();
|
||||
assert_eq!(added::lines(&packed), [words]);
|
||||
assert!(start.elapsed() < std::time::Duration::from_secs(10), "{:?}", start.elapsed());
|
||||
let plain = AddedText { rect: [0.0, 0.0, 60.0, 100.0], text: "one two three four".into(), size: 10.0, ..AddedText::default() };
|
||||
assert_eq!(added::lines(&plain), ["one two", "three four"]);
|
||||
}
|
||||
|
||||
/// Character spacing on added text (#4245) is the PDF's `Tc`, kept in `/PCAdded` so the item
|
||||
/// reopens with it; an item written without it reads 0.
|
||||
#[test]
|
||||
@@ -10854,6 +10907,116 @@ fn a_run_of_spaces_in_a_subset_without_a_space_glyph_keeps_its_width() {
|
||||
assert_eq!(content.matches("[-330] TJ").count(), 5, "{content}");
|
||||
}
|
||||
|
||||
/// #6131: a subset that writes width 0 for its unused space (pdfTeX does) has no space glyph. A word added to
|
||||
/// the line takes a positioning gap for its spaces, not code 32 at width 0, which would run the words together.
|
||||
#[test]
|
||||
fn a_space_in_a_subset_that_gives_it_no_width_is_a_gap_not_code_32() {
|
||||
for subtype in ["TrueType", "Type1"] {
|
||||
// Codes 32..=98: the space and everything else 0 wide, but a and b (97, 98).
|
||||
let widths: Vec<String> = (32..=98).map(|c| if c == 97 || c == 98 { "500" } else { "0" }.to_string()).collect();
|
||||
let font = format!(
|
||||
"<< /Type /Font /Subtype /{subtype} /BaseFont /ABCDEF+Sample /FirstChar 32 /LastChar 98 /Widths [{}] /Encoding /WinAnsiEncoding >>",
|
||||
widths.join(" ")
|
||||
);
|
||||
let content = "BT /F1 12 Tf 72 700 Td (ab) Tj ET";
|
||||
let objs = [
|
||||
"<< /Type /Catalog /Pages 2 0 R >>".to_string(),
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_string(),
|
||||
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 600 800] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >>".to_string(),
|
||||
format!(
|
||||
"<< /Length {} >>
|
||||
stream
|
||||
{content}
|
||||
endstream",
|
||||
content.len()
|
||||
),
|
||||
font,
|
||||
];
|
||||
let mut out = b"%PDF-1.7
|
||||
"
|
||||
.to_vec();
|
||||
let mut offs = Vec::new();
|
||||
for (i, o) in objs.iter().enumerate() {
|
||||
offs.push(out.len());
|
||||
out.extend_from_slice(
|
||||
format!(
|
||||
"{} 0 obj
|
||||
{o}
|
||||
endobj
|
||||
",
|
||||
i + 1
|
||||
)
|
||||
.as_bytes(),
|
||||
);
|
||||
}
|
||||
let x = out.len();
|
||||
out.extend_from_slice(
|
||||
format!(
|
||||
"xref
|
||||
0 {}
|
||||
0000000000 65535 f
|
||||
",
|
||||
objs.len() + 1
|
||||
)
|
||||
.as_bytes(),
|
||||
);
|
||||
for o in offs {
|
||||
out.extend_from_slice(
|
||||
format!(
|
||||
"{o:010} 00000 n
|
||||
"
|
||||
)
|
||||
.as_bytes(),
|
||||
);
|
||||
}
|
||||
out.extend_from_slice(
|
||||
format!(
|
||||
"trailer
|
||||
<< /Size {} /Root 1 0 R >>
|
||||
startxref
|
||||
{x}
|
||||
%%EOF
|
||||
",
|
||||
objs.len() + 1
|
||||
)
|
||||
.as_bytes(),
|
||||
);
|
||||
let mut doc = Document::open(Arc::new(out)).unwrap();
|
||||
assert_eq!(text::replace_block(&mut doc, 0, 0, "ab ba").unwrap().substituted, None, "{subtype}");
|
||||
// Every byte the text-showing operators draw (strings inside `TJ` arrays too) and every
|
||||
// `TJ` adjustment, read from the saved content rather than matched as text.
|
||||
let ops = pdfcraft_content::parse(&page_content_bytes(&reopen(&doc), 0)).ops;
|
||||
let mut shown: Vec<u8> = Vec::new();
|
||||
let mut adjustments: Vec<f64> = Vec::new();
|
||||
// How many bytes had been drawn when each adjustment came: the gap must sit between the words.
|
||||
let mut positions: Vec<usize> = Vec::new();
|
||||
for op in ops.iter().filter(|o| matches!(o.op.as_slice(), b"Tj" | b"TJ" | b"'" | b"\"")) {
|
||||
for operand in &op.operands {
|
||||
match operand {
|
||||
Object::String(s) => shown.extend_from_slice(&s.bytes),
|
||||
Object::Array(items) => {
|
||||
for item in items {
|
||||
match item {
|
||||
Object::String(s) => shown.extend_from_slice(&s.bytes),
|
||||
number => {
|
||||
if let Some(adjustment) = number.as_f64() {
|
||||
adjustments.push(adjustment);
|
||||
positions.push(shown.len());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
assert_eq!(shown, b"abba", "{subtype}: the words are drawn and no code 32 at width 0 between them");
|
||||
assert!(matches!(adjustments.as_slice(), [gap] if *gap < 0.0), "{subtype}: one adjustment moves the second word right: {adjustments:?}");
|
||||
assert_eq!(positions, [2], "{subtype}: the gap is between the words, after \"ab\"");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn image_exclusive_scope_resets_path_on_scope_exit() {
|
||||
// An earlier scope has a path operation closed by Q (with 'h' closepath).
|
||||
@@ -13757,3 +13920,84 @@ fn editing_legacy_thai_keeps_the_embedded_face_weight_size_spacing_and_paint_aft
|
||||
assert_eq!(page_font_programs(&doc), fonts, "no replacement font program may be added");
|
||||
}
|
||||
}
|
||||
|
||||
/// The Unicode row breaks are invisible moves, not glyphs. A draft carrying them (text pasted
|
||||
/// from a browser or Word) breaks the row on both rewrite paths, rather than being refused
|
||||
/// because no fallback face has an outline for U+2028 (#6272). The paragraph is one wide row, so
|
||||
/// a break that was dropped would leave the words on one row instead of two. A one-line edit has
|
||||
/// no next row, so there each break is written as a space.
|
||||
#[test]
|
||||
fn unicode_row_breaks_break_the_row_instead_of_needing_a_glyph() {
|
||||
let red = text::RangeStyle {
|
||||
range: 0..3,
|
||||
family: None,
|
||||
resource: None,
|
||||
size: None,
|
||||
color: Some([1.0, 0.0, 0.0]),
|
||||
underline: None,
|
||||
char_spacing: None,
|
||||
scale: None,
|
||||
};
|
||||
for separator in ['\u{2028}', '\u{2029}', '\u{0085}', '\u{000B}', '\u{000C}', '\u{001C}', '\u{001D}', '\u{001E}'] {
|
||||
let draft = format!("one{separator}two");
|
||||
for style in [
|
||||
text::BlockStyle::default(),
|
||||
text::BlockStyle { ranges: vec![red.clone()], ..Default::default() },
|
||||
text::BlockStyle { ranges: vec![text::RangeStyle { range: 0..draft.len(), ..red.clone() }], ..Default::default() },
|
||||
text::BlockStyle { bold: Some(true), ..Default::default() },
|
||||
] {
|
||||
let mut doc = text_page("BT /F1 12 Tf 72 700 Td (Hello world) Tj ET");
|
||||
text::rewrite_block(&mut doc, 0, 0, Some(&draft), &style).unwrap_or_else(|e| panic!("U+{:04X}: {e}", u32::from(separator)));
|
||||
let doc = reopen(&doc);
|
||||
let lines: Vec<String> = text::text_lines(&doc, 0).unwrap().into_iter().map(|l| l.text).collect();
|
||||
assert_eq!(lines, ["one", "two"], "U+{:04X}", u32::from(separator));
|
||||
}
|
||||
let mut doc = text_page("BT /F1 12 Tf 72 700 Td (Hello world) Tj ET");
|
||||
text::replace_line(&mut doc, 0, 0, &draft).unwrap_or_else(|e| panic!("U+{:04X}: {e}", u32::from(separator)));
|
||||
let doc = reopen(&doc);
|
||||
let lines: Vec<String> = text::text_lines(&doc, 0).unwrap().into_iter().map(|l| l.text).collect();
|
||||
assert_eq!(lines, ["one two"], "a one-line edit keeps U+{:04X} on its line", u32::from(separator));
|
||||
}
|
||||
}
|
||||
|
||||
/// Thai text on the styled path has its own coverage checks and row splits. A Unicode row break
|
||||
/// in a Thai draft breaks the row there too, whether the paragraph keeps its legacy subset, takes
|
||||
/// the bundled Thai face by choice or is completed by the matching one, instead of being refused
|
||||
/// for a glyph no face has (#6272).
|
||||
#[test]
|
||||
fn thai_paragraphs_break_the_row_on_unicode_row_breaks() {
|
||||
let rows = |doc: &Document| -> Vec<String> { text::text_lines(&reopen(doc), 0).unwrap().into_iter().map(|l| l.text).collect() };
|
||||
let thai_face = pdfcraft_fonts::document_thai_font().is_some();
|
||||
if !thai_face {
|
||||
eprintln!("thai_paragraphs_break_the_row_on_unicode_row_breaks: built without craft-fonts, so only the legacy subset is checked");
|
||||
}
|
||||
for separator in ['\u{2028}', '\u{001C}'] {
|
||||
let draft = format!("กข{separator}ค");
|
||||
let mut doc = text_page("BT /F1 16 Tf 50 650 Td <00d6> Tj ET");
|
||||
let font = legacy_thai_font(&mut doc, "ABCDEF+THSarabunPSK", &legacy_thai_program(), LEGACY_THAI_UNICODE);
|
||||
doc.set(pdfcraft_cos::ObjRef::new(5, 0), Object::Dict(font));
|
||||
let style = BlockStyle { width: Some(400.0), ..Default::default() };
|
||||
text::rewrite_block(&mut doc, 0, 0, Some(&draft), &style).unwrap_or_else(|e| panic!("legacy U+{:04X}: {e}", u32::from(separator)));
|
||||
assert_eq!(rows(&doc), ["กข", "ค"], "legacy U+{:04X}", u32::from(separator));
|
||||
if !thai_face {
|
||||
continue;
|
||||
}
|
||||
let mut doc = text_page("BT /F1 12 Tf 72 700 Td (Hello world) Tj ET");
|
||||
let chosen = BlockStyle { resource: Some("builtin:thai".into()), ..Default::default() };
|
||||
text::rewrite_block(&mut doc, 0, 0, Some(&draft), &chosen).unwrap_or_else(|e| panic!("chosen U+{:04X}: {e}", u32::from(separator)));
|
||||
assert_eq!(rows(&doc), ["กข", "ค"], "chosen U+{:04X}", u32::from(separator));
|
||||
let mut doc = text_page("BT /F1 16 Tf 50 700 Td (A) Tj ET");
|
||||
let cmap = doc.add(Object::Stream(Stream::flate(
|
||||
Dict::new(),
|
||||
b"1 begincodespacerange <00> <FF> endcodespacerange 1 beginbfchar <41> <0E19> endbfchar",
|
||||
)));
|
||||
doc.update_dict(pdfcraft_cos::ObjRef::new(5, 0), |f| {
|
||||
f.set(b"BaseFont".to_vec(), Object::name("ABCDEF+NotoSansThai-Regular"));
|
||||
f.set(b"ToUnicode".to_vec(), Object::Ref(cmap));
|
||||
})
|
||||
.unwrap();
|
||||
text::rewrite_block(&mut doc, 0, 0, Some(&draft), &BlockStyle::default())
|
||||
.unwrap_or_else(|e| panic!("matching U+{:04X}: {e}", u32::from(separator)));
|
||||
assert_eq!(rows(&doc), ["กข", "ค"], "matching U+{:04X}", u32::from(separator));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -36,13 +36,13 @@ mod interp;
|
||||
mod lines;
|
||||
mod rewrite;
|
||||
|
||||
use blocks::paragraph_separator;
|
||||
#[cfg(test)]
|
||||
use blocks::wrap;
|
||||
pub use blocks::{
|
||||
BlockKey, BlockStyle, RangeStyle, ReadingBlocks, TextBlock, block_overlapping, clear_block, reading_blocks, reading_blocks_checked,
|
||||
replace_block, text_blocks,
|
||||
};
|
||||
use blocks::{paragraph_separator, row_break};
|
||||
pub use editor::{TextEditLayout, TextEditorFont, register_text_font, text_edit_layout, text_editor_fonts};
|
||||
use editor::{builtin_thai_choice, layout_draft};
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -344,6 +344,15 @@ pub(crate) fn paragraph_separator(c: char) -> bool {
|
||||
c.is_whitespace() && c != '\u{3000}'
|
||||
}
|
||||
|
||||
/// Characters that end a row rather than draw a glyph: the Unicode mandatory breaks (UAX #14
|
||||
/// class BK: vertical tab, form feed, U+2028 LINE SEPARATOR, U+2029 PARAGRAPH SEPARATOR), the
|
||||
/// next line (U+0085), the information separators (bidi class B) and CR/LF. Text pasted from a
|
||||
/// browser or Word carries these, so a rewrite moves to the next row instead of asking a font
|
||||
/// for an outline no face has (#6272).
|
||||
pub(crate) fn row_break(c: char) -> bool {
|
||||
matches!(c, '\n' | '\r' | '\u{000B}' | '\u{000C}' | '\u{0085}' | '\u{001C}'..='\u{001E}' | '\u{2028}' | '\u{2029}')
|
||||
}
|
||||
|
||||
/// Greedy word wrapping to `width` with `advance` giving a string's width. Each `\n` starts a
|
||||
/// new line. A row may also end inside a word of Chinese or Japanese text ([`crate::linebreak`]);
|
||||
/// those pieces join without a space. Every white-space character is written as one space, so
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::blocks::{BlockStyle, TextBlock, paragraph_separator, wrap};
|
||||
use super::blocks::{BlockStyle, TextBlock, paragraph_separator, row_break, wrap};
|
||||
use super::fallback::{
|
||||
Encoder, MAX_TYPE3_GLYPHS, Type3Fallback, drop_unused_fallback_fonts, needs_type3, no_japanese_font, source_encodes, source_family,
|
||||
source_program_completes, source_show, source_space, source_width, type3_encode, type3_font,
|
||||
@@ -42,7 +42,7 @@ fn refuse_clipping_text(lines: &[TextLine], dropped: &std::collections::HashSet<
|
||||
|
||||
/// [`replace_line`] with the most unique characters one generated font may hold (tests lower it).
|
||||
pub(crate) fn replace_line_with_limit(doc: &mut Document, page: usize, line: usize, text: &str, max_glyphs: usize) -> Result<LineEdit, EditError> {
|
||||
let text = text.replace(['\n', '\r'], " ");
|
||||
let text = text.replace(row_break, " ");
|
||||
let lines = text_lines(doc, page)?;
|
||||
let target = lines.get(line).cloned().ok_or_else(|| EditError::Invalid(format!("page {} has no line {}", page + 1, line + 1)))?;
|
||||
target.ensure_editable()?;
|
||||
@@ -240,7 +240,7 @@ fn choose_rewrite_path(
|
||||
}
|
||||
let visual_indic = members.iter().any(|line| line.visual_order);
|
||||
let has_special_text = text.is_some_and(|draft| {
|
||||
draft.contains(['\n', '\r'])
|
||||
draft.contains(row_break)
|
||||
|| pdfcraft_fonts::source_shaping::required(draft)
|
||||
|| !pdfcraft_fonts::embedding::matching_faces(&block.base_font).is_empty()
|
||||
});
|
||||
@@ -259,14 +259,14 @@ fn choose_rewrite_path(
|
||||
}
|
||||
|
||||
/// The paragraph's text for writing back: explicit line breaks stay (#1443), and so does each typed
|
||||
/// U+0020 space: a run of them is not folded into one (#4199, #3797). `\r\n` and a lone `\r` are
|
||||
/// breaks too; other white space is written as one space.
|
||||
/// U+0020 space: a run of them is not folded into one (#4199, #3797). Every [`row_break`] is a break
|
||||
/// too; other white space is written as one space.
|
||||
fn paragraph_text(text: &str) -> String {
|
||||
text.replace("\r\n", "\n")
|
||||
.chars()
|
||||
.map(|c| match c {
|
||||
'\r' => '\n',
|
||||
c if c != '\n' && paragraph_separator(c) => ' ',
|
||||
c if row_break(c) => '\n',
|
||||
c if paragraph_separator(c) => ' ',
|
||||
c => c,
|
||||
})
|
||||
.collect()
|
||||
|
||||
@@ -3,9 +3,9 @@
|
||||
use super::{
|
||||
BlockStyle, CraftFont, Dict, Document, EditError, HashMap, LineEdit, MAX_TYPE3_GLYPHS, Matrix, Metrics, Object, Op, PdfString, Pieces,
|
||||
RangeStyle, TextBlock, TextLine, Type3Glyph, builtin_thai_choice, coincident_ops, content_streams, fallback_face, japanese_glyph_from,
|
||||
needs_type3, no_fallback_font, no_glyph_for, page_dict, paragraph_separator, reveal_ops, rewritten_contents, same_base_font, same_font,
|
||||
source_encodes, source_family, source_program, source_show, source_space, source_width, splice, strip_subset_tag, type3_faces, type3_glyph,
|
||||
union, write_type3_glyphs,
|
||||
needs_type3, no_fallback_font, no_glyph_for, page_dict, paragraph_separator, reveal_ops, rewritten_contents, row_break, same_base_font,
|
||||
same_font, source_encodes, source_family, source_program, source_show, source_space, source_width, splice, strip_subset_tag, type3_faces,
|
||||
type3_glyph, union, write_type3_glyphs,
|
||||
};
|
||||
|
||||
#[path = "text_regions/grouping.rs"]
|
||||
|
||||
@@ -366,10 +366,13 @@ fn group_layout(lines: &[TextLine], mixed: bool) -> Vec<TextBlock> {
|
||||
if !block.rows.is_empty() {
|
||||
block.editor_text.push('\n');
|
||||
}
|
||||
// The run placed before this one in the row, tracked rather than searched for: rows
|
||||
// don't share runs, so it is the last one this loop pushed.
|
||||
let mut prev_in_row: Option<&TextLine> = None;
|
||||
for &index in row {
|
||||
let Some(line) = lines.get(index) else { continue };
|
||||
// Some producers position separate words without encoding a space.
|
||||
if let Some(prev) = block.lines.last().filter(|i| row.contains(i)).and_then(|i| lines.get(*i))
|
||||
if let Some(prev) = prev_in_row
|
||||
&& !row_text.ends_with(char::is_whitespace)
|
||||
&& !line.text.starts_with(char::is_whitespace)
|
||||
&& line.frame_rect()[0] - prev.frame_rect()[2] > line.size * 0.12
|
||||
@@ -383,6 +386,7 @@ fn group_layout(lines: &[TextLine], mixed: bool) -> Vec<TextBlock> {
|
||||
row_text.push_str(&line.text);
|
||||
block.invisible &= line.origin.state.render_mode == 3;
|
||||
block.lines.push(index);
|
||||
prev_in_row = Some(line);
|
||||
}
|
||||
if !block.text.is_empty() {
|
||||
if block.text.ends_with('-') {
|
||||
|
||||
@@ -3,7 +3,7 @@ use super::grouping::{across, is_centred, row_rect};
|
||||
use super::{
|
||||
BlockStyle, CraftFont, Dict, Document, EditError, HashMap, LineEdit, MAX_TYPE3_GLYPHS, Matrix, Metrics, Object, Op, PdfString, Pieces,
|
||||
RangeStyle, TextBlock, TextLine, Type3Glyph, builtin_thai_choice, coincident_ops, content_streams, fallback_face, japanese_glyph_from,
|
||||
needs_type3, no_fallback_font, no_glyph_for, page_dict, reveal_ops, rewritten_contents, source_encodes, source_family, source_program,
|
||||
needs_type3, no_fallback_font, no_glyph_for, page_dict, reveal_ops, rewritten_contents, row_break, source_encodes, source_family, source_program,
|
||||
source_show, source_space, source_width, splice, type3_faces, type3_glyph, write_type3_glyphs,
|
||||
};
|
||||
|
||||
@@ -181,8 +181,8 @@ impl CharacterPreparation<'_> {
|
||||
"the bundled Thai font ({thai_choice}) is not in this build, which has no craft-fonts Thai face; load a complete Thai font or choose one the page lists"
|
||||
))
|
||||
})?;
|
||||
if !pdfcraft_fonts::embedding::covers(face.bytes, span) {
|
||||
let missing = span.chars().find(|c| !pdfcraft_fonts::embedding::covers(face.bytes, c.encode_utf8(&mut [0; 4])));
|
||||
if !covers_rows(face.bytes, span) {
|
||||
let missing = span.chars().find(|&c| !row_break(c) && !pdfcraft_fonts::embedding::covers(face.bytes, c.encode_utf8(&mut [0; 4])));
|
||||
return Err(EditError::Invalid(match missing {
|
||||
Some(c) => format!("{} has no glyph for {c} (U+{:04X}); choose a font that covers the text", face.family, u32::from(c)),
|
||||
None => format!("{} cannot show every character in this selection; choose a font that covers the text", face.family),
|
||||
@@ -251,12 +251,13 @@ impl CharacterPreparation<'_> {
|
||||
};
|
||||
let start = range.start;
|
||||
for (offset, ch) in draft.get(range).unwrap_or_default().char_indices() {
|
||||
if ch == '\n' {
|
||||
chars.push((ch, index, source.font.clone()));
|
||||
continue;
|
||||
}
|
||||
if ch == '\r' {
|
||||
let crlf = start.checked_add(offset).and_then(|at| draft.get(at.saturating_add(1)..)).is_some_and(|rest| rest.starts_with('\n'));
|
||||
// A row break moves to the next row instead of asking a font for a glyph. The CR
|
||||
// of a CRLF stays a `\r` the rows skip, so the pair is one break; every other break
|
||||
// is written as `\n`. Either way it keeps its place among the draft's characters,
|
||||
// which rows are counted in.
|
||||
if row_break(ch) {
|
||||
let crlf = ch == '\r'
|
||||
&& start.checked_add(offset).and_then(|at| draft.get(at.saturating_add(1)..)).is_some_and(|rest| rest.starts_with('\n'));
|
||||
chars.push((if crlf { '\r' } else { '\n' }, index, source.font.clone()));
|
||||
continue;
|
||||
}
|
||||
@@ -923,7 +924,7 @@ fn legacy_thai_font(
|
||||
if !has_thai_source_face(cache, &family) {
|
||||
return Ok(None);
|
||||
}
|
||||
let rows = || span.split(['\n', '\r']).filter(|row| !row.is_empty());
|
||||
let rows = || span.split(row_break).filter(|row| !row.is_empty());
|
||||
for row in rows() {
|
||||
if let Err(error) = shape_existing_thai(cache, &source.font, row) {
|
||||
// Not in the face's existing codes. A complete program of the face that shapes every
|
||||
@@ -1097,7 +1098,7 @@ fn matching_thai_outline(doc: &Document, fonts: &Dict, source: &TextLine, span:
|
||||
}
|
||||
if !span.chars().any(|c| matches!(u32::from(c), 0x0e00..=0x0e7f))
|
||||
|| !pdfcraft_fonts::embedding::matching_faces(&source.base_font).iter().any(|f| std::ptr::eq(*f, face))
|
||||
|| !pdfcraft_fonts::embedding::covers(face.bytes, span)
|
||||
|| !covers_rows(face.bytes, span)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
@@ -1112,16 +1113,22 @@ fn matching_thai_outline(doc: &Document, fonts: &Dict, source: &TextLine, span:
|
||||
&& pdfcraft_fonts::pdf::embedded_sfnt(doc, &font).is_some_and(|bytes| {
|
||||
pdfcraft_fonts::embedding::validate(&bytes).is_ok()
|
||||
&& pdfcraft_fonts::source_shaping::has_thai_layout(&bytes)
|
||||
&& pdfcraft_fonts::embedding::covers(&bytes, span)
|
||||
&& span.split(['\n', '\r']).all(|row| pdfcraft_fonts::source_shaping::shape(&bytes, row).is_ok())
|
||||
&& covers_rows(&bytes, span)
|
||||
&& span.split(row_break).all(|row| pdfcraft_fonts::source_shaping::shape(&bytes, row).is_ok())
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether a complete program draws every row of `span`. [`row_break`] characters move to the next
|
||||
/// row and are never drawn, so they need no glyph (#6272); `embedding::covers` exempts only CR and LF.
|
||||
fn covers_rows(bytes: &[u8], span: &str) -> bool {
|
||||
span.split(row_break).all(|row| pdfcraft_fonts::embedding::covers(bytes, row))
|
||||
}
|
||||
|
||||
/// Use the same Thai script selection and mark/cluster positioning as Add Text, including
|
||||
/// rows beginning with Latin or digits (guessing from their first character would select Latin).
|
||||
fn shape_thai_row(text: &str) -> Result<pdfcraft_fonts::source_shaping::ShapedRun, EditError> {
|
||||
if text.len() > 262_144 || text.contains(['\n', '\r']) {
|
||||
if text.len() > 262_144 || text.contains(row_break) {
|
||||
return Err(EditError::Invalid("shape one bounded text row at a time".into()));
|
||||
}
|
||||
let clusters =
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//! file in its original format. A picture drawn through grouped
|
||||
//! Form artwork (as Word, InDesign and many scanners write them) is found inside the group.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use pdfcraft_cos::{Dict, Document as Cos, ObjRef, Object};
|
||||
|
||||
@@ -13,6 +13,31 @@ const MAX_COPY_PIXELS: u64 = 64_000_000;
|
||||
/// How deep Form artwork is searched for its picture.
|
||||
const MAX_FORM_DEPTH: usize = 12;
|
||||
|
||||
/// A picture on a page, with its index in [`Document::page_images`].
|
||||
pub type PagePicture = (usize, pdfcraft_edit::PageImage);
|
||||
|
||||
/// The topmost of `pictures` under user-space point `at` (`[x, y]`). `pictures` is bottom first,
|
||||
/// as [`Document::page_pictures_job`] lists them, so the last one that holds `at` wins.
|
||||
pub fn picture_at(pictures: &[PagePicture], at: [f64; 2]) -> Option<&PagePicture> {
|
||||
pictures.iter().rev().find(|(_, image)| image.contains(at))
|
||||
}
|
||||
|
||||
/// The pictures on `page`, bottom first: raster images, and Form artwork that holds one.
|
||||
fn pictures(cos: &Cos, page: usize) -> Vec<PagePicture> {
|
||||
let images = pdfcraft_edit::page_images(cos, page).unwrap_or_default();
|
||||
// Artwork drawn many times is searched once.
|
||||
let mut holds_one: HashMap<ObjRef, bool> = HashMap::new();
|
||||
images
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.filter(|(_, i)| match (i.is_form, i.object) {
|
||||
(false, Some(_)) => true,
|
||||
(true, Some(form)) => *holds_one.entry(form).or_insert_with(|| picture_in_form(cos, form).is_some()),
|
||||
_ => false,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
impl Document {
|
||||
/// The topmost picture on `page` under user-space point `at`, as its index in
|
||||
/// [`Document::page_images`]: a raster image, or Form artwork that holds one.
|
||||
@@ -28,6 +53,18 @@ impl Document {
|
||||
})
|
||||
}
|
||||
|
||||
/// Work that lists the pictures on `page`, bottom first, for another thread: it reads every
|
||||
/// drawing operator on the page, seconds on a dense one, so it must not run on the window
|
||||
/// thread. Look a point up with [`picture_at`].
|
||||
///
|
||||
/// `None` when the document can't be read. The work reads the document as it is now: later
|
||||
/// edits aren't seen (key its answer by [`Document::edit_generation`]). It returns no pictures
|
||||
/// for a page that doesn't exist or can't be read.
|
||||
pub fn page_pictures_job(&self, page: usize) -> Option<impl FnOnce() -> Vec<PagePicture> + Send + 'static> {
|
||||
let cos = self.editor.as_ref()?.cos.clone();
|
||||
Some(move || crate::guard(|| pictures(&cos, page)).unwrap_or_default())
|
||||
}
|
||||
|
||||
/// Copy Image in Original Format: picture `index` on `page` as a file (extension, bytes):
|
||||
/// a JPEG as stored in the PDF, otherwise a lossless PNG.
|
||||
pub fn page_image_copy_file(&self, page: usize, index: usize) -> Result<(&'static str, Vec<u8>), String> {
|
||||
|
||||
@@ -32,7 +32,8 @@ pub struct Document {
|
||||
pub dirty: bool,
|
||||
/// Bumped on every change to the working file (edit, undo, redo, save); autosave compares it.
|
||||
pub(crate) generation: u64,
|
||||
/// The generation last handed out by `autosave_snapshots`.
|
||||
/// The generation last handed out by `autosave_snapshots`, or another one when storing that
|
||||
/// snapshot failed (`autosave_failed`), so it is due again.
|
||||
pub(crate) snapshot_generation: u64,
|
||||
/// Why the document cannot be edited (e.g. encryption), if so.
|
||||
pub read_only_reason: Option<String>,
|
||||
@@ -727,6 +728,14 @@ pub(crate) fn write_display_copy(
|
||||
}
|
||||
}
|
||||
|
||||
/// `doc` as the reader shows it: comments without an appearance stream drawn
|
||||
/// (`pdfcraft_annot::with_missing_appearances`) and form fields drawn from their values where the
|
||||
/// file leaves that to the viewer. `None` when `doc` needs neither. The vector print draws from
|
||||
/// this copy too, so what prints is what the page shows (#371, #3475 draw them for display only).
|
||||
pub(crate) fn as_displayed(doc: &pdfcraft_cos::Document) -> Option<pdfcraft_cos::Document> {
|
||||
with_field_appearances(pdfcraft_annot::with_missing_appearances(doc), doc)
|
||||
}
|
||||
|
||||
/// Carry the marks across a revalidation that leaves the display copy alone, when it may: only
|
||||
/// when every verdict is the one the copy was drawn with. Returns whether it did; otherwise the
|
||||
/// copy has to be drawn again.
|
||||
@@ -778,7 +787,7 @@ pub fn display_bytes_for(bytes: Arc<Vec<u8>>, password: Option<&str>) -> Arc<Vec
|
||||
let cos = pdfcraft_cos::Document::open_with_password(bytes.clone(), password).ok()?;
|
||||
let mut signatures = signatures_of(&cos, &bytes, &TrustStore::default(), &pdfcraft_sign::DigestCache::default());
|
||||
let layered = pdfcraft_sign::has_status_layers(&cos, &signatures);
|
||||
let (mut display, added) = match with_field_appearances(pdfcraft_annot::with_missing_appearances(&cos), &cos) {
|
||||
let (mut display, added) = match as_displayed(&cos) {
|
||||
Some(display) => (display, true),
|
||||
None if layered => (cos, false),
|
||||
None => return None,
|
||||
|
||||
@@ -561,8 +561,8 @@ pub(crate) fn run_edit(doc: &mut pdfcraft_cos::Document, edit: &Edit, cx: &mut E
|
||||
}
|
||||
Edit::DeleteAttachment { key } => pdfcraft_organize::delete_attachment(doc, key)?,
|
||||
Edit::ReplaceText { page, quads, text, author, strike, caret } => {
|
||||
// One `/NM` each: the caret replies to the strikeout, and XFDF names that reply by
|
||||
// the strikeout's `/NM` (#2666).
|
||||
// One `/NM` each: the strikeout is grouped under the caret, and XFDF names that link by
|
||||
// the caret's `/NM` (#2666).
|
||||
let (strike_meta, caret_meta) = (cx.meta(), cx.meta());
|
||||
pdfcraft_annot::add_text_replacement(
|
||||
doc,
|
||||
|
||||
@@ -95,7 +95,11 @@ pub(crate) fn scope_of(edit: &Edit) -> Scope {
|
||||
| Edit::AddHeaderFooter { .. }
|
||||
| Edit::AddWatermark { .. }
|
||||
| Edit::AddBackground { .. }
|
||||
| Edit::RemoveMarks { .. } => Scope::Content,
|
||||
| Edit::RemoveMarks { .. }
|
||||
// Recognized text is an invisible text layer stamped on its page, with its font in the
|
||||
// page's resources (#6310): a full re-inspection made applying one word cost seconds on
|
||||
// a large file.
|
||||
| Edit::AddOcrText { .. } => Scope::Content,
|
||||
Edit::Batch { edits, .. } => {
|
||||
let mut scopes = edits.iter().map(scope_of);
|
||||
let first = scopes.next().unwrap_or(Scope::Full);
|
||||
|
||||
+113
-14
@@ -26,29 +26,70 @@ pub struct JsOutput {
|
||||
pub doc_errors: Vec<String>,
|
||||
}
|
||||
|
||||
/// Console lines one output keeps, from every script an edit runs together (a form's
|
||||
/// calculations, say): each run's own cap ([`pdfcraft_js::xfa::MAX_CONSOLE`]) would otherwise
|
||||
/// be multiplied by the number of fields a document declares.
|
||||
pub const MAX_CONSOLE_LINES: usize = 10_000;
|
||||
/// Bytes of console text one output keeps, for the same reason.
|
||||
pub const MAX_CONSOLE_BYTES: usize = 1 << 20;
|
||||
/// Alerts one output keeps.
|
||||
pub const MAX_ALERTS: usize = 1_000;
|
||||
|
||||
impl JsOutput {
|
||||
/// Whether scripts produced nothing: no alerts, console lines, requests or errors.
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.alerts.is_empty() && self.console.is_empty() && self.requests.is_empty() && self.errors.is_empty()
|
||||
}
|
||||
|
||||
/// Adds `lines` to the console within [`MAX_CONSOLE_LINES`] and [`MAX_CONSOLE_BYTES`]; what
|
||||
/// is past them is left out, which one closing line says.
|
||||
fn say(&mut self, lines: impl IntoIterator<Item = String>) {
|
||||
let note = format!("more console lines were left out: the scripts printed more than {MAX_CONSOLE_LINES} lines or {MAX_CONSOLE_BYTES} bytes");
|
||||
// Once the notice is written the console is closed: nothing may follow it, and a later
|
||||
// rejection must not add a second copy.
|
||||
if self.console.last() == Some(¬e) {
|
||||
return;
|
||||
}
|
||||
let mut bytes: usize = self.console.iter().map(String::len).sum();
|
||||
let mut dropped = false;
|
||||
for l in lines {
|
||||
if self.console.len() >= MAX_CONSOLE_LINES || bytes.saturating_add(l.len()) > MAX_CONSOLE_BYTES {
|
||||
dropped = true;
|
||||
break;
|
||||
}
|
||||
bytes += l.len();
|
||||
self.console.push(l);
|
||||
}
|
||||
if dropped && !self.console.iter().any(|l| l == ¬e) {
|
||||
self.console.push(note);
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds `alerts` within [`MAX_ALERTS`].
|
||||
fn alert(&mut self, alerts: impl IntoIterator<Item = Message>) {
|
||||
let room = MAX_ALERTS.saturating_sub(self.alerts.len());
|
||||
self.alerts.extend(alerts.into_iter().take(room));
|
||||
}
|
||||
|
||||
/// Adds what a field's own script produced: its alerts, console lines, errors and requests,
|
||||
/// except a request to show a side panel or open Save As, which is noted on the console
|
||||
/// and dropped.
|
||||
fn absorb(&mut self, o: &Outcome) {
|
||||
self.alerts.extend(o.alerts.iter().cloned());
|
||||
self.console.extend(o.console.iter().cloned());
|
||||
self.alert(o.alerts.iter().cloned());
|
||||
self.say(o.console.iter().cloned());
|
||||
// A field's own scripts (keystroke, format, validate, calculate) run unasked: only a
|
||||
// button's may show or hide a side panel, or open Save As.
|
||||
// The warnings go through `say` like any other console line, so they count against the
|
||||
// line and byte caps instead of growing the console past them.
|
||||
let mut notes = Vec::new();
|
||||
for r in &o.requests {
|
||||
match r {
|
||||
Request::ShowPanel(_) => self.console.push("A field script asked to show a side panel; only a button may show a side panel".into()),
|
||||
Request::SaveAs => {
|
||||
self.console.push("A field script asked to save the document as a new file; only a button may open Save As".into())
|
||||
}
|
||||
Request::ShowPanel(_) => notes.push("A field script asked to show a side panel; only a button may show a side panel".to_string()),
|
||||
Request::SaveAs => notes.push("A field script asked to save the document as a new file; only a button may open Save As".to_string()),
|
||||
r => self.requests.push(r.clone()),
|
||||
}
|
||||
}
|
||||
self.say(notes);
|
||||
self.errors.extend(o.error.iter().cloned());
|
||||
// The document scripts run before every field script, so a failing one would repeat
|
||||
// once per calculation; it is reported once.
|
||||
@@ -61,8 +102,8 @@ impl JsOutput {
|
||||
}
|
||||
|
||||
pub(crate) fn append(&mut self, other: JsOutput) {
|
||||
self.alerts.extend(other.alerts);
|
||||
self.console.extend(other.console);
|
||||
self.alert(other.alerts);
|
||||
self.say(other.console);
|
||||
self.requests.extend(other.requests);
|
||||
// As in `absorb`: a document script's error, already reported, is not repeated; a field
|
||||
// script's errors are each their own, even one worded like a document script's.
|
||||
@@ -118,6 +159,7 @@ fn field_state_with_display(f: &Field, display: i32) -> pdfcraft_js::FieldState
|
||||
s.readonly = f.read_only();
|
||||
s.required = f.has(pdfcraft_forms::flags::REQUIRED);
|
||||
s.display = display;
|
||||
s.rect = f.widgets.first().map(|w| w.rect);
|
||||
s.char_limit = f.max_len;
|
||||
s.options = match f.kind {
|
||||
FieldKind::CheckBox | FieldKind::Radio => f.widgets.iter().filter_map(|w| w.on_state.clone()).map(|o| (o.clone(), o)).collect(),
|
||||
@@ -147,8 +189,9 @@ fn changes(before: &[pdfcraft_js::FieldState], after: &[pdfcraft_js::FieldState]
|
||||
read_only: (a.readonly != b.readonly).then_some(a.readonly),
|
||||
required: (a.required != b.required).then_some(a.required),
|
||||
display: (a.display != b.display).then_some(a.display),
|
||||
rect: (a.rect != b.rect).then_some(a.rect).flatten(),
|
||||
};
|
||||
(c.value.is_some() || c.read_only.is_some() || c.required.is_some() || c.display.is_some()).then_some(c)
|
||||
(c.value.is_some() || c.read_only.is_some() || c.required.is_some() || c.display.is_some() || c.rect.is_some()).then_some(c)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -203,6 +246,7 @@ impl Scripts for JsRunner {
|
||||
self.run_logged(event, script, target, value, fields, true).unwrap_or_else(|| ScriptResult {
|
||||
rc: true,
|
||||
value: value.to_string(),
|
||||
value_set: false,
|
||||
changes: Vec::new(),
|
||||
message: None,
|
||||
})
|
||||
@@ -239,6 +283,7 @@ impl JsRunner {
|
||||
Some(ScriptResult {
|
||||
rc: o.rc,
|
||||
value: o.value.clone(),
|
||||
value_set: o.value_set,
|
||||
changes: changes(&states, &o.changed),
|
||||
message: (!o.rc).then(|| o.alerts.last().map(|m| m.text.clone())).flatten(),
|
||||
})
|
||||
@@ -330,11 +375,9 @@ impl Session {
|
||||
if !changes.is_empty() {
|
||||
edits.push(Edit::ApplyScriptChanges { changes });
|
||||
}
|
||||
for names in resets {
|
||||
let all: Vec<String> = fields.iter().map(|f| f.name.clone()).collect();
|
||||
let names = (!names.is_empty())
|
||||
.then(|| all.iter().filter(|n| names.iter().any(|x| *n == x || n.starts_with(&format!("{x}.")))).cloned().collect());
|
||||
edits.push(Edit::ResetForm { names });
|
||||
if !resets.is_empty() {
|
||||
let all: Vec<&str> = fields.iter().map(|f| f.name.as_str()).collect();
|
||||
edits.push(Edit::ResetForm { names: reset_targets(&all, &resets) });
|
||||
}
|
||||
if !edits.is_empty() {
|
||||
self.apply(id, Edit::Batch { label: "Run JavaScript".into(), edits })?;
|
||||
@@ -343,6 +386,21 @@ impl Session {
|
||||
}
|
||||
}
|
||||
|
||||
/// The fields every `resetForm` call of one script asked for, as one reset: a reset is to the
|
||||
/// defaults, so resetting the union once does what each call in turn would, and recalculates
|
||||
/// once. `None` is the whole form (a call with no names). A field is named by a selector that
|
||||
/// is its name or the name of a field above it, looked up in a set of the selectors, so the
|
||||
/// work is the fields times their depth, not the fields times the selectors, which a script
|
||||
/// controls.
|
||||
fn reset_targets(fields: &[&str], requests: &[Vec<String>]) -> Option<Vec<String>> {
|
||||
if requests.iter().any(Vec::is_empty) {
|
||||
return None;
|
||||
}
|
||||
let wanted: std::collections::HashSet<&str> = requests.iter().flatten().map(String::as_str).collect();
|
||||
let matched = |name: &str| name.match_indices('.').map(|(i, _)| &name[..i]).chain(std::iter::once(name)).any(|p| wanted.contains(p));
|
||||
Some(fields.iter().filter(|n| matched(n)).map(|n| n.to_string()).collect())
|
||||
}
|
||||
|
||||
/// A page's words for form-field detection, in user space (underscore runs split from the
|
||||
/// text around them).
|
||||
fn detection_words(text: &pdfcraft_render::PageText, info: &pdfcraft_render::PageInfo) -> Vec<pdfcraft_forms::detect::Word> {
|
||||
@@ -492,6 +550,47 @@ impl Session {
|
||||
mod review_tests {
|
||||
use super::*;
|
||||
|
||||
/// Many `resetForm` calls with many selectors over a big form: one reset of the union, found
|
||||
/// by looking each field's name and parents up, not by comparing every field with every
|
||||
/// selector.
|
||||
#[test]
|
||||
fn reset_requests_are_coalesced_and_matched_through_an_index() {
|
||||
let fields: Vec<String> = (0..20_000).map(|i| format!("group{}.row{i}.cell", i % 100)).collect();
|
||||
let names: Vec<&str> = fields.iter().map(String::as_str).collect();
|
||||
let requests: Vec<Vec<String>> = (0..1_000).map(|k| (0..20).map(|j| format!("nothing{}", k * 20 + j)).collect()).collect();
|
||||
let started = std::time::Instant::now();
|
||||
assert_eq!(reset_targets(&names, &requests), Some(Vec::new()), "no selector names a field");
|
||||
let mut requests = requests;
|
||||
requests.push(vec!["group7".into(), "group7.row7.cell".into(), "group8.row8".into()]);
|
||||
let hit = reset_targets(&names, &requests).unwrap();
|
||||
assert_eq!(hit.len(), 200 + 1, "group7 has 200 fields, one more by its exact name");
|
||||
assert!(hit.iter().all(|n| n.starts_with("group7.") || n == "group8.row8.cell"));
|
||||
assert!(started.elapsed() < std::time::Duration::from_secs(5), "{:?}", started.elapsed());
|
||||
requests.push(Vec::new());
|
||||
assert_eq!(reset_targets(&names, &requests), None, "a call without names resets the whole form");
|
||||
}
|
||||
|
||||
/// A form of many calculated fields, each printing its own cap of console lines, keeps a
|
||||
/// bounded console: past the budget, lines are left out and one closing line says so.
|
||||
#[test]
|
||||
fn console_output_of_one_edit_is_bounded() {
|
||||
let mut out = JsOutput::default();
|
||||
let line = "x".repeat(4_096);
|
||||
let run = Outcome { console: vec![line; 1_000], alerts: vec![Message::plain("hi"); 100], ..Default::default() };
|
||||
for _ in 0..1_000 {
|
||||
out.absorb(&run);
|
||||
}
|
||||
let bytes: usize = out.console.iter().map(String::len).sum();
|
||||
assert!(bytes <= MAX_CONSOLE_BYTES + 256, "{bytes} bytes kept");
|
||||
assert!(out.console.len() <= MAX_CONSOLE_LINES + 1, "{} lines kept", out.console.len());
|
||||
assert!(out.console.last().unwrap().starts_with("more console lines were left out"));
|
||||
assert_eq!(out.console.iter().filter(|l| l.starts_with("more console lines")).count(), 1, "said once");
|
||||
assert_eq!(out.alerts.len(), MAX_ALERTS);
|
||||
let mut merged = JsOutput::default();
|
||||
merged.append(out);
|
||||
assert!(merged.console.len() <= MAX_CONSOLE_LINES + 1);
|
||||
}
|
||||
|
||||
/// A long run of underscores (a form's blank) is read in one pass: each glyph is compared with
|
||||
/// the word so far without reading the word again.
|
||||
#[test]
|
||||
|
||||
+112
-3
@@ -6,10 +6,102 @@ use pdfcraft_render::{Layer, LayerOp, RenderPool};
|
||||
|
||||
use crate::{Document, display_config, render_threads};
|
||||
|
||||
/// Most usage application dictionaries (`/AS` entries) that [`print_layer_states`] reads, and
|
||||
/// most category names and groups it reads in all of them together (entries can share one
|
||||
/// array, so the count is over every entry, not each).
|
||||
const MAX_AUTO_STATES: usize = 1024;
|
||||
const MAX_AUTO_ITEMS: usize = 65_536;
|
||||
|
||||
/// The usage dictionary entry and its state key that a `/Category` name of a usage application
|
||||
/// dictionary reads when printing (ISO 32000-2 Table 101): Print, View and Export each name a
|
||||
/// state of the group's own. Zoom, User and Language depend on the magnification, the user and
|
||||
/// the system language, which printing doesn't fix, so they give no recommendation here.
|
||||
fn print_category(name: &[u8]) -> Option<(&'static [u8], &'static [u8])> {
|
||||
match name {
|
||||
b"Print" => Some((b"Print", b"PrintState")),
|
||||
b"View" => Some((b"View", b"ViewState")),
|
||||
b"Export" => Some((b"Export", b"ExportState")),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The layers as they print: `layers` as shown, then the default configuration's auto state for
|
||||
/// the Print event (ISO 32000-2 §8.11.4.4, Table 101). Each usage application dictionary
|
||||
/// (`/AS` entry) whose `/Event` is `/Print` recommends, for each group in its `/OCGs` and each of
|
||||
/// its categories ([`print_category`]), the state the group's usage dictionary gives (for the
|
||||
/// Print category, `/Usage /Print /PrintState`). A group with recommendations is on only if all
|
||||
/// of them, in all the entries naming it, are ON; other groups keep their state. `/Category` is
|
||||
/// an array; a single name is read as one. `None` when no `/AS` entry is for printing.
|
||||
pub(crate) fn print_layer_states(cos: &pdfcraft_cos::Document, layers: &[Layer]) -> Option<Vec<Layer>> {
|
||||
use pdfcraft_cos::Object;
|
||||
let root = cos.trailer().get(b"Root").map(|r| cos.resolve(r))?;
|
||||
let properties = root.as_dict()?.get(b"OCProperties").map(|p| cos.resolve(p))?;
|
||||
let config = properties.as_dict()?.get(b"D").map(|d| cos.resolve(d))?;
|
||||
let auto = config.as_dict()?.get(b"AS").map(|a| cos.resolve(a))?;
|
||||
let mut printing = false;
|
||||
let mut recommended: std::collections::HashMap<(u32, u16), bool> = std::collections::HashMap::new();
|
||||
let mut items_left = MAX_AUTO_ITEMS;
|
||||
for entry in auto.as_array()?.iter().take(MAX_AUTO_STATES) {
|
||||
let entry = cos.resolve(entry);
|
||||
let Some(entry) = entry.as_dict() else { continue };
|
||||
if entry.get(b"Event").map(|e| cos.resolve(e)).as_deref().and_then(Object::as_name) != Some(b"Print") {
|
||||
continue;
|
||||
}
|
||||
printing = true;
|
||||
let categories = entry.get(b"Category").map(|c| cos.resolve(c));
|
||||
let mut read: Vec<(&[u8], &[u8])> = Vec::new();
|
||||
let mut consider = |name: Option<&[u8]>| {
|
||||
if let Some(category) = name.and_then(print_category).filter(|c| !read.contains(c)) {
|
||||
read.push(category);
|
||||
}
|
||||
};
|
||||
match categories.as_deref() {
|
||||
Some(Object::Array(names)) => {
|
||||
let count = names.len().min(items_left);
|
||||
items_left -= count;
|
||||
names.iter().take(count).for_each(|n| consider(cos.resolve(n).as_name()));
|
||||
}
|
||||
Some(Object::Name(n)) => consider(Some(n.as_slice())),
|
||||
_ => {}
|
||||
}
|
||||
if read.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let Some(groups) = entry.get(b"OCGs").map(|g| cos.resolve(g)) else { continue };
|
||||
for group in groups.as_array().into_iter().flatten() {
|
||||
let Some(left) = items_left.checked_sub(1) else { break };
|
||||
items_left = left;
|
||||
let Some(id) = group.as_ref() else { continue };
|
||||
let ocg = cos.resolve(group);
|
||||
let usage = ocg.as_dict().and_then(|g| g.get(b"Usage").map(|u| cos.resolve(u)));
|
||||
for (entry_key, state_key) in &read {
|
||||
// No state given (a Print category without `/PrintState`): no recommendation, so
|
||||
// the group is left as it is.
|
||||
let state = usage
|
||||
.as_deref()
|
||||
.and_then(|u| u.as_dict().and_then(|u| u.get(entry_key).map(|e| cos.resolve(e))))
|
||||
.and_then(|e| e.as_dict().and_then(|e| e.get(state_key).map(|s| cos.resolve(s))))
|
||||
.and_then(|s| match s.as_name() {
|
||||
Some(b"ON") => Some(true),
|
||||
Some(b"OFF") => Some(false),
|
||||
_ => None,
|
||||
});
|
||||
if let Some(on) = state {
|
||||
let all_on = recommended.entry((id.num, id.generation)).or_insert(true);
|
||||
*all_on = *all_on && on;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
printing.then(|| layers.iter().map(|l| Layer { visible: recommended.get(&l.id).copied().unwrap_or(l.visible), ..l.clone() }).collect())
|
||||
}
|
||||
|
||||
/// Write `layers`' visibility into the default optional-content configuration of `cos` (a copy
|
||||
/// made for printing): `/BaseState /ON`, `/ON` the visible layers, `/OFF` the hidden ones. Its
|
||||
/// other entries (`/Order`, `/RBGroups`, `/AS`…) are kept. A document without `/OCProperties`
|
||||
/// is left alone.
|
||||
/// made for printing): `/BaseState /ON`, `/ON` the visible layers, `/OFF` the hidden ones. The
|
||||
/// states written are final, so what would set them again goes: the auto state (`/AS`), and the
|
||||
/// layers' own `/Usage`, which some readers apply when they draw (a `/ViewState /ON` turns a layer
|
||||
/// that prints off back on). The configuration's other entries (`/Order`, `/RBGroups`…) are kept.
|
||||
/// A document without `/OCProperties` is left alone.
|
||||
pub(crate) fn set_default_layer_state(cos: &mut pdfcraft_cos::Document, layers: &[Layer]) {
|
||||
use pdfcraft_cos::{Dict, ObjRef, Object};
|
||||
let Some(root_ref) = cos.trailer().get(b"Root").and_then(Object::as_ref) else { return };
|
||||
@@ -22,18 +114,35 @@ pub(crate) fn set_default_layer_state(cos: &mut pdfcraft_cos::Document, layers:
|
||||
config.set(b"BaseState".to_vec(), Object::name("ON"));
|
||||
config.set(b"ON".to_vec(), refs(true));
|
||||
config.set(b"OFF".to_vec(), refs(false));
|
||||
config.remove(b"AS");
|
||||
properties.set(b"D".to_vec(), Object::Dict(config));
|
||||
root.set(b"OCProperties".to_vec(), Object::Dict(properties));
|
||||
cos.set(root_ref, Object::Dict(root));
|
||||
for layer in layers {
|
||||
let id = ObjRef::new(layer.id.0, layer.id.1);
|
||||
let Some(mut group) = cos.get(id).as_dict().cloned() else { continue };
|
||||
if group.remove(b"Usage").is_some() {
|
||||
cos.set(id, Object::Dict(group));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Render `doc` with the layer visibility in its `info.layers`.
|
||||
pub(crate) fn use_layer_choices(doc: &mut Document) {
|
||||
let overrides: Vec<(i32, i32, bool)> = doc.info.layers.iter().map(|l| (l.id.0 as i32, l.id.1 as i32, l.visible)).collect();
|
||||
doc.config.layers = Arc::new(overrides);
|
||||
doc.config.print_layers = print_preview_layers(doc.editor.as_ref().map(|e| &e.cos), &doc.info.layers);
|
||||
doc.renderer = RenderPool::new(doc.display.clone(), render_threads(), display_config(&doc.config));
|
||||
}
|
||||
|
||||
/// The layer overrides a print preview draws with (`RenderConfig::print_layers`): the layers as
|
||||
/// they print ([`print_layer_states`]), so the preview shows the page as it prints. `None` when
|
||||
/// the document has no auto state for printing (or no structure to read it from).
|
||||
pub(crate) fn print_preview_layers(cos: Option<&pdfcraft_cos::Document>, layers: &[Layer]) -> Option<Arc<Vec<(i32, i32, bool)>>> {
|
||||
let printed = print_layer_states(cos?, layers)?;
|
||||
Some(Arc::new(printed.iter().map(|l| (l.id.0 as i32, l.id.1 as i32, l.visible)).collect()))
|
||||
}
|
||||
|
||||
/// Apply a set-layer-visibility action to `layers`, one change at a time, so a toggle flips the
|
||||
/// state the changes before it left. Returns whether any layer ended up changed.
|
||||
pub(crate) fn apply_layer_state(layers: &mut [Layer], groups: &[Vec<(u32, u16)>], changes: &[(LayerOp, (u32, u16))], preserve_rb: bool) -> bool {
|
||||
|
||||
@@ -24,6 +24,7 @@ pub mod commands;
|
||||
mod comments;
|
||||
pub mod compare;
|
||||
mod copy_image;
|
||||
pub use copy_image::{PagePicture, picture_at};
|
||||
pub mod dates;
|
||||
mod document;
|
||||
mod edit;
|
||||
@@ -86,7 +87,7 @@ pub use pdfcraft_organize::Standard;
|
||||
pub use pdfcraft_organize::check_custom_key;
|
||||
pub use pdfcraft_organize::view::{InitialView, Layout as InitialLayout, Magnification, Navigation};
|
||||
|
||||
pub use pdfcraft_cos::Algorithm;
|
||||
pub use pdfcraft_cos::{Algorithm, civil_from_days};
|
||||
pub use pdfcraft_create::{CONVERTIBLE, CreateError, ImageResolution, SourceKind, decode_text, source_kind};
|
||||
pub use pdfcraft_edit::added::{
|
||||
CHAR_SPACING_LIMIT as ADDED_CHAR_SPACING_LIMIT, paste_place as added_paste_place, paste_rect as added_paste_rect, text_rect as added_text_rect,
|
||||
@@ -149,7 +150,7 @@ pub use edit::{BATCH_LABELS, EDIT_LABELS, Edit};
|
||||
pub use error::{EditError, SourceProblem};
|
||||
pub use fill_sign::{displayed_offset, text_box_at, typed_signature_graphic, typed_signature_shape};
|
||||
pub use history::Label;
|
||||
use layers::{apply_layer_state, set_default_layer_state, use_layer_choices};
|
||||
use layers::{apply_layer_state, print_layer_states, print_preview_layers, set_default_layer_state, use_layer_choices};
|
||||
pub use open::{OpenContext, PreparedDocument};
|
||||
pub use page_filter::{PageOrientation, PageParity, filter_pages};
|
||||
pub use pictures::{MarkFile, image_dimensions};
|
||||
@@ -160,7 +161,10 @@ pub use session::Session;
|
||||
pub use sources::{CombineSource, Combined, combine_source_check, source_page_count};
|
||||
use sources::{open_source, open_source_with};
|
||||
#[cfg(test)]
|
||||
use test_hooks::{check_refresh_panic, panic_on_refresh, record_link_scan, record_marker_scan, reset_secondary_scan_counts, secondary_scan_counts};
|
||||
use test_hooks::{
|
||||
check_refresh_panic, panic_on_refresh, record_full_refresh, record_link_scan, record_marker_scan, reset_secondary_scan_counts,
|
||||
secondary_scan_counts, take_full_refreshes,
|
||||
};
|
||||
use xfa_form::{
|
||||
XFA_REMOVED_PREFIX, XFA_SCRIPTS_OFF, decode_data_file, image_content_type, is_xfa_data_file, note_warnings, strip_xfa, sync_xfa_state,
|
||||
undrawn_field_warnings, xfa_after_data_change, xfa_layout, xfa_redraw, xfa_sync_datasets, xfa_values_from_datasets,
|
||||
|
||||
@@ -971,10 +971,23 @@ impl Session {
|
||||
pub fn ocr_job(&self, id: DocId, pages: &[usize], settings: OcrSettings) -> Option<OcrJob> {
|
||||
let doc = self.get(id)?;
|
||||
let all = doc.info.pages.len();
|
||||
let pages: Vec<usize> = if pages.is_empty() { (0..all).collect() } else { pages.iter().copied().filter(|p| *p < all).collect() };
|
||||
let mut seen = vec![false; all];
|
||||
let pages: Vec<usize> = if pages.is_empty() {
|
||||
seen.fill(true);
|
||||
(0..all).collect()
|
||||
} else {
|
||||
let mut deduped = Vec::new();
|
||||
for &p in pages {
|
||||
if seen.get(p) == Some(&false) {
|
||||
seen[p] = true;
|
||||
deduped.push(p);
|
||||
}
|
||||
}
|
||||
deduped
|
||||
};
|
||||
let native = (0..all)
|
||||
.map(|p| {
|
||||
if !pages.contains(&p) {
|
||||
if seen.get(p) != Some(&true) {
|
||||
return None;
|
||||
}
|
||||
doc.page_images(p)
|
||||
@@ -2234,6 +2247,59 @@ mod tests {
|
||||
assert_eq!(page, 0);
|
||||
}
|
||||
|
||||
/// A scan selected explicitly is rendered at its native scale, like the same page in an
|
||||
/// all-pages job: selecting pages must not lose the native-resolution lookup and render
|
||||
/// the scan above its own resolution at a higher chosen dpi.
|
||||
#[test]
|
||||
fn selected_scan_page_uses_native_scale_like_all_pages() {
|
||||
let mut s = Session::new();
|
||||
let page = export::encode_png(2480, 3508, &vec![255; (2480 * 3508 * 4) as usize]).unwrap();
|
||||
let bytes = s.create_from_images(&[("a4.png".into(), page)]).unwrap();
|
||||
let id = s.open("scan.pdf", None, bytes, None).unwrap();
|
||||
let settings = OcrSettings { dpi: 300.0, ..Default::default() };
|
||||
let all = s.ocr_job(id, &[], settings.clone()).unwrap();
|
||||
let selected = s.ocr_job(id, &[0], settings).unwrap();
|
||||
assert_eq!(selected.pages, vec![0]);
|
||||
let wanted = 300.0 / 72.0;
|
||||
assert!(all.render_scale(0) < wanted, "native resolution limits the all-pages job: {}", all.render_scale(0));
|
||||
assert!(
|
||||
(selected.render_scale(0) - all.render_scale(0)).abs() < 1e-4,
|
||||
"selected page {} vs all-pages {}",
|
||||
selected.render_scale(0),
|
||||
all.render_scale(0)
|
||||
);
|
||||
}
|
||||
|
||||
/// A job requested with the same page twice carries each page once: a duplicate would
|
||||
/// otherwise be recognized twice.
|
||||
#[test]
|
||||
fn ocr_job_deduplicates_requested_pages() {
|
||||
let mut s = Session::new();
|
||||
let id = s.open("t.pdf", None, Arc::new(fixture(3)), None).unwrap();
|
||||
let job = s.ocr_job(id, &[2, 0, 2, 1, 0, 2], OcrSettings::default()).unwrap();
|
||||
assert_eq!(job.pages, vec![2, 0, 1], "each requested page appears once, in request order");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ocr_job_bounds_page_vector_reservation_by_page_count() {
|
||||
let mut s = Session::new();
|
||||
let id = s.open("t.pdf", None, Arc::new(fixture(3)), None).unwrap();
|
||||
let requested = vec![999usize; 1024];
|
||||
let job = s.ocr_job(id, &requested, OcrSettings::default()).unwrap();
|
||||
assert!(job.pages.is_empty());
|
||||
assert!(job.pages.capacity() <= 3, "reservation {} exceeds the 3 pages that can survive deduplication", job.pages.capacity());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ocr_job_does_not_reserve_capacity_for_invalid_pages() {
|
||||
let mut s = Session::new();
|
||||
let id = s.open("t.pdf", None, Arc::new(fixture(1024)), None).unwrap();
|
||||
let requested = vec![4096usize; 1024];
|
||||
let job = s.ocr_job(id, &requested, OcrSettings::default()).unwrap();
|
||||
assert!(job.pages.is_empty());
|
||||
assert_eq!(job.pages.capacity(), 0, "no valid pages were found, so no capacity should be reserved");
|
||||
}
|
||||
|
||||
/// #1848: an A4 scan at 300 dpi whose page box is its pixel size (2480 x 3508 pt, one pixel
|
||||
/// per point) gets a smaller bitmap for each lower "Downsample to" choice, and a low-resolution
|
||||
/// letter page is still never shrunk below one pixel per point.
|
||||
|
||||
@@ -8,7 +8,8 @@ use pdfcraft_render::{DocInfo, OpenError, RenderConfig, RenderPool, inspect};
|
||||
use crate::history::{Editor, Keys, TextBlocksCache};
|
||||
use crate::{
|
||||
AppearanceCache, DocId, Document, Session, StatusCaptions, TrustStore, XFA_SCRIPTS_OFF, XfaLayout, display_bytes, display_config, guard,
|
||||
info_fields, js, note_warnings, recovered_render_password, render_threads, same_pages, signatures_of, xfa, xfa_layout, xfa_values_from_datasets,
|
||||
info_fields, js, note_warnings, print_preview_layers, recovered_render_password, render_threads, same_pages, signatures_of, xfa, xfa_layout,
|
||||
xfa_values_from_datasets,
|
||||
};
|
||||
|
||||
/// Immutable session state needed while a document is prepared away from its owning thread.
|
||||
@@ -125,11 +126,17 @@ impl Session {
|
||||
// pages and fields so the rest of the engine works on it. The original bytes stay: the
|
||||
// laid-out form is one appended revision.
|
||||
let opts = SaveOptions { mod_date: context.now.map(pdfcraft_cos::pdf_date), ..SaveOptions::default() };
|
||||
// Write `work` as one more revision and reopen it: what the document then is.
|
||||
// Write `work` as one more revision and reopen it: what the document then is. The notes
|
||||
// about damage repaired while reading the file stay with it (Document Properties), once.
|
||||
let rebase = |work: &pdfcraft_cos::Document| -> Result<(Arc<Vec<u8>>, DocInfo, pdfcraft_cos::Document), String> {
|
||||
let new_bytes = write_incremental(work, &opts).map(Arc::new).map_err(|e| e.to_string())?;
|
||||
let new_info = inspect(new_bytes.clone(), render_password.as_deref()).map_err(|e| e.to_string())?;
|
||||
let new_cos = pdfcraft_cos::Document::open_with_password(new_bytes.clone(), password).map_err(|e| e.to_string())?;
|
||||
let mut new_cos = pdfcraft_cos::Document::open_with_password(new_bytes.clone(), password).map_err(|e| e.to_string())?;
|
||||
for line in work.repair_log() {
|
||||
if !new_cos.repair_log().contains(line) {
|
||||
new_cos.note_repair(line.clone());
|
||||
}
|
||||
}
|
||||
Ok((new_bytes, new_info, new_cos))
|
||||
};
|
||||
let (bytes, info, cos, xfa) = match (info.xfa, cos) {
|
||||
@@ -254,9 +261,6 @@ impl Session {
|
||||
};
|
||||
match rebuilt {
|
||||
Some((b, i, mut c)) => {
|
||||
for line in cos.repair_log() {
|
||||
c.note_repair(line.clone());
|
||||
}
|
||||
c.note_repair(format!("the page tree is missing; its {} pages were found by scanning the file", i.pages.len()));
|
||||
(b, i, Ok(Ok(c)))
|
||||
}
|
||||
@@ -283,7 +287,7 @@ impl Session {
|
||||
/// The last step of opening: build the document record and register it.
|
||||
fn build_document(context: &OpenContext, data: DocumentOpenData<'_>) -> Document {
|
||||
let DocumentOpenData { name, path, bytes, mut info, structure: cos, render_password, password, xfa } = data;
|
||||
let config = RenderConfig { password: render_password.as_deref().map(Arc::from), ..Default::default() };
|
||||
let mut config = RenderConfig { password: render_password.as_deref().map(Arc::from), ..Default::default() };
|
||||
let (mut editor, read_only_reason) = match cos {
|
||||
Ok(Ok(cos)) => {
|
||||
let keys = Keys { render: render_password.clone(), reopen: password.map(str::to_owned) };
|
||||
@@ -318,6 +322,8 @@ impl Session {
|
||||
}
|
||||
}
|
||||
}
|
||||
// The print preview draws the layers as they print.
|
||||
config.print_layers = print_preview_layers(editor.as_ref().map(|e| &e.cos), &info.layers);
|
||||
let display = display_bytes(editor.as_mut(), &bytes, &mut signatures, &context.captions);
|
||||
let renderer = RenderPool::new(display.clone(), render_threads(), display_config(&config));
|
||||
let (form, adopted) = editor
|
||||
|
||||
@@ -12,11 +12,12 @@ use pdfcraft_cos::{SaveOptions, write_full};
|
||||
use crate::{DocId, EditError, Hidden, OptimizeReport, Session, guard, optimize};
|
||||
|
||||
/// Where an optimization is.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum OptimizeStage {
|
||||
/// Removing the user data chosen under Discard User Data.
|
||||
#[default]
|
||||
/// Removing the user data chosen under Discard User Data, if any was.
|
||||
Discarding,
|
||||
/// Reading what the pages draw: `done` of `total` read.
|
||||
Reading { done: usize, total: usize },
|
||||
/// Merging the fragments of a page picture into one image.
|
||||
Fragments,
|
||||
/// About to process image `done` (0-based) of `total`.
|
||||
@@ -29,14 +30,21 @@ pub enum OptimizeStage {
|
||||
Writing,
|
||||
}
|
||||
|
||||
impl Default for OptimizeStage {
|
||||
fn default() -> Self {
|
||||
OptimizeStage::Reading { done: 0, total: 0 }
|
||||
}
|
||||
}
|
||||
|
||||
impl OptimizeStage {
|
||||
/// How far along the whole run is, from 0 to 1. Images take most of the time; the rest are
|
||||
/// small fixed steps.
|
||||
/// How far along the whole run is, from 0 to 1, weighed by where the time goes: reading pages
|
||||
/// and pictures. The rest are small fixed steps.
|
||||
pub fn fraction(self) -> f32 {
|
||||
let part = |done: usize, total: usize| if total == 0 { 1.0 } else { done.min(total) as f32 / total as f32 };
|
||||
match self {
|
||||
OptimizeStage::Discarding => 0.0,
|
||||
OptimizeStage::Fragments => 0.03,
|
||||
OptimizeStage::Images { done, total } => 0.05 + 0.75 * if total == 0 { 1.0 } else { done.min(total) as f32 / total as f32 },
|
||||
OptimizeStage::Discarding | OptimizeStage::Fragments => 0.0,
|
||||
OptimizeStage::Reading { done, total } => 0.25 * if total == 0 { 0.0 } else { part(done, total) },
|
||||
OptimizeStage::Images { done, total } => 0.25 + 0.55 * part(done, total),
|
||||
OptimizeStage::CleaningUp => 0.8,
|
||||
OptimizeStage::Merging => 0.85,
|
||||
OptimizeStage::Writing => 0.9,
|
||||
@@ -91,10 +99,10 @@ impl OptimizeJob {
|
||||
pdfcraft_forms::clear_password_values(&mut cos).map_err(|e| EditError::Write(e.to_string()))?;
|
||||
pdfcraft_xfa::clear_password_values(&mut cos).map_err(|e| EditError::Write(e.to_string()))?;
|
||||
let mut step = |stage| if progress(stage) { Ok(()) } else { Err(EditError::Cancelled) };
|
||||
step(OptimizeStage::Discarding)?;
|
||||
let discarded = if discard.is_empty() {
|
||||
Vec::new()
|
||||
} else {
|
||||
step(OptimizeStage::Discarding)?;
|
||||
// Every ticked category, as `remove_hidden` decides between them: with form fields
|
||||
// ticked, discarding hidden text also takes the hidden text the flattened appearances
|
||||
// bring onto the page, which no scan before flattening counts. It refuses when its scan
|
||||
@@ -112,6 +120,7 @@ impl OptimizeJob {
|
||||
};
|
||||
let report = optimize::optimize_with_progress(&mut cos, &settings, &mut |s| {
|
||||
step(match s {
|
||||
optimize::Stage::Reading { done, total } => OptimizeStage::Reading { done, total },
|
||||
optimize::Stage::Fragments => OptimizeStage::Fragments,
|
||||
optimize::Stage::Images { done, total } => OptimizeStage::Images { done, total },
|
||||
optimize::Stage::CleanUp => OptimizeStage::CleaningUp,
|
||||
|
||||
@@ -11,7 +11,7 @@ use pdfcraft_print::{Content, Raster};
|
||||
use pdfcraft_render::{PRINT_TAG, PageRenderer, RenderRequest};
|
||||
|
||||
use crate::export::encode_png;
|
||||
use crate::{Document, guard};
|
||||
use crate::{Document, guard, print_layer_states};
|
||||
|
||||
/// `doc`'s pages `pages` (0-based, each once, in the order given) as an image-only PDF, one
|
||||
/// page per entry, the size of the source page as displayed, drawing what `content` prints.
|
||||
@@ -22,11 +22,16 @@ pub fn rasterize(doc: &Document, pages: &[usize], raster: &Raster, content: Cont
|
||||
let mut config = src.config.clone();
|
||||
// The copy below holds only what prints, so the viewer's own comment hiding plays no part.
|
||||
config.hide_comments = false;
|
||||
let printed = guard(|| -> Result<Vec<u8>, String> {
|
||||
let (printed, layers) = guard(|| -> Result<(Vec<u8>, Option<Vec<pdfcraft_render::Layer>>), String> {
|
||||
let mut cos = pdfcraft_cos::Document::open_with_password(src.bytes.clone(), config.password.as_deref()).map_err(|e| e.to_string())?;
|
||||
pdfcraft_print::keep_printed(&mut cos, content);
|
||||
write_incremental(&cos, &SaveOptions::default()).map_err(|e| e.to_string())
|
||||
// The layers as the vector print sets them: as shown, then the Print event's auto state.
|
||||
let layers = print_layer_states(&cos, &doc.info.layers);
|
||||
Ok((write_incremental(&cos, &SaveOptions::default()).map_err(|e| e.to_string())?, layers))
|
||||
})??;
|
||||
if let Some(layers) = layers {
|
||||
config.layers = std::sync::Arc::new(layers.iter().map(|l| (l.id.0 as i32, l.id.1 as i32, l.visible)).collect());
|
||||
}
|
||||
let mut renderer = PageRenderer::new(std::sync::Arc::new(printed), config);
|
||||
let mut images: Vec<(String, Vec<u8>)> = Vec::with_capacity(pages.len());
|
||||
let mut used: Option<f64> = None;
|
||||
|
||||
@@ -14,8 +14,8 @@ use crate::{
|
||||
LOW_RESOLUTION_PRINT_DPI, Label, ObjectKind, OptimizeReport, RecoverySnapshot, SignOptions, SourceKind, SplitPart, StatusCaptions, SummarySort,
|
||||
TrustStore, XFA_REMOVED_PREFIX, XFA_SCRIPTS_OFF, apply_layer_state, carry_verdict_marks, comment_list, comment_summary, decode_text,
|
||||
display_bytes, display_config, guard, info_fields, js, local_utc_offset, note_warnings, open_source, open_source_with, optimize, outline_rows,
|
||||
parse_ymd, print, print_raster, render_threads, scan_colours, set_default_layer_state, shown_under_redactions, signatures_of, source_kind,
|
||||
sync_xfa_state, undrawn_notices, use_layer_choices, writable, xfa, xfa_sync_datasets,
|
||||
parse_ymd, print, print_layer_states, print_raster, render_threads, scan_colours, set_default_layer_state, shown_under_redactions, signatures_of,
|
||||
source_kind, sync_xfa_state, undrawn_notices, use_layer_choices, writable, xfa, xfa_sync_datasets,
|
||||
};
|
||||
|
||||
mod editing;
|
||||
|
||||
@@ -6,7 +6,7 @@ use super::{
|
||||
inspect, js, keys_after, note_warnings, render_threads, run_edit, scan_colours, scope_of, shown_under_redactions, signatures_of, sync_xfa_state,
|
||||
undrawn_notices, uses_scripts, write_incremental, xfa, xfa_sync_datasets,
|
||||
};
|
||||
use crate::{EditNotice, MarkKind};
|
||||
use crate::{EditNotice, MarkKind, print_preview_layers};
|
||||
|
||||
/// Whether the edit, or any edit inside a batch, deletes pages.
|
||||
fn deletes_pages(edit: &Edit) -> bool {
|
||||
@@ -515,6 +515,8 @@ impl Session {
|
||||
}
|
||||
|
||||
fn refresh_with_indexes(doc: &mut Document, invalidate_markers: bool, invalidate_links: bool) -> Result<(), EditError> {
|
||||
#[cfg(test)]
|
||||
crate::record_full_refresh();
|
||||
// A full refresh may follow structural or annotation changes: cached appearances
|
||||
// may be stale, so they are rebuilt below.
|
||||
if let Some(editor) = doc.editor.as_mut() {
|
||||
@@ -545,6 +547,7 @@ impl Session {
|
||||
}
|
||||
}
|
||||
doc.info = info;
|
||||
doc.config.print_layers = print_preview_layers(Some(&editor.cos), &doc.info.layers);
|
||||
doc.fonts_stale = false;
|
||||
let mut form = pdfcraft_forms::fields(&editor.cos);
|
||||
xfa::mark_script_buttons(&editor.cos, &mut form);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::{
|
||||
Arc, CombineSource, Combined, DataFormat, DocId, EditError, Hidden, ImageResolution, LOW_RESOLUTION_PRINT_DPI, OptimizeReport, SaveOptions,
|
||||
Session, SourceKind, SplitPart, decode_text, guard, open_source, open_source_with, optimize, print, print_raster, set_default_layer_state,
|
||||
source_kind, writable, write_full,
|
||||
Session, SourceKind, SplitPart, decode_text, guard, open_source, open_source_with, optimize, print, print_layer_states, print_raster,
|
||||
set_default_layer_state, source_kind, writable, write_full,
|
||||
};
|
||||
|
||||
impl Session {
|
||||
@@ -164,10 +164,21 @@ impl Session {
|
||||
pdfcraft_cos::Document::open_with_password(doc.bytes.clone(), doc.password.as_deref()).map_err(|e| EditError::Write(e.to_string()))?
|
||||
}
|
||||
};
|
||||
// Comments and fields without an appearance print as the page shows them (and as Print
|
||||
// as Image already printed them): the vector print drew only appearance streams, so a
|
||||
// text box without one was on screen but not on paper. ISO 32000-2 §12.5.3: an
|
||||
// annotation with the Print flag is printed.
|
||||
if let Some(displayed) = guard(|| crate::document::as_displayed(&cos)).ok().flatten() {
|
||||
cos = displayed;
|
||||
}
|
||||
// #3046: the layers print as they are shown. Once the Layers panel (or a set-layer
|
||||
// action) has changed one, the print copy's default configuration says which are on, so a
|
||||
// hidden layer stays off on paper too; untouched, the document's own configuration prints.
|
||||
if !doc.config.layers.is_empty() {
|
||||
// On top of either, the configuration's auto state for the Print event sets the layers it
|
||||
// names (`print_layer_states`), as printing does in a viewer (ISO 32000-2 §8.11.4.4).
|
||||
if let Some(printed) = print_layer_states(&cos, &doc.info.layers) {
|
||||
set_default_layer_state(&mut cos, &printed);
|
||||
} else if !doc.config.layers.is_empty() {
|
||||
set_default_layer_state(&mut cos, &doc.info.layers);
|
||||
}
|
||||
// Signature states as the screen shows them, so not when its display copy could not be
|
||||
|
||||
@@ -217,6 +217,15 @@ impl Session {
|
||||
out
|
||||
}
|
||||
|
||||
/// The snapshot [`Self::autosave_snapshots`] handed out for `id` could not be stored: the
|
||||
/// document is due again, so the next autosave tries it again.
|
||||
pub fn autosave_failed(&mut self, id: DocId) {
|
||||
if let Some(d) = self.docs.iter_mut().find(|d| d.id == id) {
|
||||
// Any generation but the current one leaves it due.
|
||||
d.snapshot_generation = d.generation.wrapping_sub(1);
|
||||
}
|
||||
}
|
||||
|
||||
/// Mark a document opened from a recovery file: it has unsaved changes and belongs at
|
||||
/// `path` (where Save writes), as when the session ended.
|
||||
pub fn mark_recovered(&mut self, id: DocId, path: Option<String>) {
|
||||
|
||||
@@ -120,17 +120,7 @@ impl Session {
|
||||
let rects: Vec<[f64; 4]> = text
|
||||
.line_rects(glyphs)
|
||||
.into_iter()
|
||||
.map(|v| {
|
||||
let q = doc.info.pages[page].view_rect_to_quad(v);
|
||||
let xs = [q[0], q[2], q[4], q[6]];
|
||||
let ys = [q[1], q[3], q[5], q[7]];
|
||||
[
|
||||
xs.iter().copied().fold(f64::MAX, f64::min),
|
||||
ys.iter().copied().fold(f64::MAX, f64::min),
|
||||
xs.iter().copied().fold(f64::MIN, f64::max),
|
||||
ys.iter().copied().fold(f64::MIN, f64::max),
|
||||
]
|
||||
})
|
||||
.filter_map(|v| line_user_rect(&doc.info.pages[page], v))
|
||||
.filter(|r| {
|
||||
!doc.links().iter().any(|l| l.page == page && l.rect[0] < r[2] && r[0] < l.rect[2] && l.rect[1] < r[3] && r[1] < l.rect[3])
|
||||
})
|
||||
@@ -313,3 +303,112 @@ impl Session {
|
||||
&self.docs
|
||||
}
|
||||
}
|
||||
|
||||
/// Convert a view-space text line rectangle into a normalized, finite PDF user-space rectangle.
|
||||
fn line_user_rect(page: &pdfcraft_render::PageInfo, v: [f32; 4]) -> Option<[f64; 4]> {
|
||||
if !v.iter().all(|x| x.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
let r = page.view_rect_to_user(v).map(f64::from);
|
||||
r.iter().all(|x| x.is_finite()).then_some(r)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::line_user_rect;
|
||||
use crate::{Edit, Session};
|
||||
use pdfcraft_render::PageInfo;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Build a sample `PageInfo` with a non-origin crop box `[10.0, 20.0, 210.0, 320.0]` (`200 × 300`).
|
||||
fn sample_page(rotation: u16) -> PageInfo {
|
||||
let (width, height) = if rotation % 180 == 90 { (300.0, 200.0) } else { (200.0, 300.0) };
|
||||
PageInfo { width, height, label: String::new(), crop: [10.0, 20.0, 210.0, 320.0], rotation }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn line_user_rect_rejects_non_finite_coordinates() {
|
||||
let page = sample_page(0);
|
||||
assert_eq!(line_user_rect(&page, [f32::NAN; 4]), None);
|
||||
assert_eq!(line_user_rect(&page, [f32::NAN, 10.0, 50.0, 20.0]), None);
|
||||
assert_eq!(line_user_rect(&page, [10.0, 20.0, f32::INFINITY, 30.0]), None);
|
||||
assert_eq!(line_user_rect(&page, [10.0, f32::NEG_INFINITY, 50.0, 30.0]), None);
|
||||
|
||||
for bad_crop_box in [[f32::NAN, 0.0, 200.0, 300.0], [0.0, f32::INFINITY, 200.0, 300.0], [0.0, 0.0, f32::NEG_INFINITY, 300.0]] {
|
||||
let mut bad_crop = sample_page(0);
|
||||
bad_crop.crop = bad_crop_box;
|
||||
assert_eq!(line_user_rect(&bad_crop, [10.0, 20.0, 50.0, 40.0]), None);
|
||||
}
|
||||
|
||||
// Finite inputs whose crop span overflows f32 during view-to-user mapping must also be rejected.
|
||||
let overflow_page = PageInfo { width: 1.0, height: 1.0, label: String::new(), crop: [-f32::MAX, 0.0, f32::MAX, 300.0], rotation: 0 };
|
||||
assert_eq!(line_user_rect(&overflow_page, [1.0, 10.0, 2.0, 20.0]), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn line_user_rect_matches_view_rect_to_user_across_rotations() {
|
||||
let v = [12.0, 24.0, 96.0, 48.0];
|
||||
let cases = [
|
||||
(0, [22.0, 272.0, 106.0, 296.0]),
|
||||
(90, [34.0, 32.0, 58.0, 116.0]),
|
||||
(180, [114.0, 44.0, 198.0, 68.0]),
|
||||
(270, [162.0, 224.0, 186.0, 308.0]),
|
||||
];
|
||||
for (rotation, expected) in cases {
|
||||
let page = sample_page(rotation);
|
||||
let got = line_user_rect(&page, v).expect("finite view rect maps to user space");
|
||||
for (g, e) in got.into_iter().zip(expected) {
|
||||
assert!((g - e).abs() < 1e-4, "rotation {rotation}: got {got:?}, expected {expected:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn find_urls_returns_finite_user_rects_on_rotated_page() {
|
||||
let mut objs: Vec<Vec<u8>> = vec![
|
||||
b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(),
|
||||
b"<< /Type /Pages /Kids [4 0 R] /Count 1 /MediaBox [0 0 200 300] >>".to_vec(),
|
||||
b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>".to_vec(),
|
||||
b"<< /Type /Page /Parent 2 0 R /Contents 5 0 R /Resources << /Font << /F1 3 0 R >> >> >>".to_vec(),
|
||||
];
|
||||
let body = "BT /F1 12 Tf 20 150 Td (Visit https://example.com today) Tj ET";
|
||||
objs.push(format!("<< /Length {} >>\nstream\n{body}\nendstream", body.len()).into_bytes());
|
||||
let mut pdf = b"%PDF-1.7\n".to_vec();
|
||||
let mut offsets = Vec::new();
|
||||
for (i, o) in objs.iter().enumerate() {
|
||||
offsets.push(pdf.len());
|
||||
pdf.extend_from_slice(format!("{} 0 obj\n", i + 1).as_bytes());
|
||||
pdf.extend_from_slice(o);
|
||||
pdf.extend_from_slice(b"\nendobj\n");
|
||||
}
|
||||
let xref = pdf.len();
|
||||
pdf.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes());
|
||||
for o in offsets {
|
||||
pdf.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());
|
||||
}
|
||||
pdf.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes());
|
||||
|
||||
let mut session = Session::new();
|
||||
let id = session.open("urls.pdf", None, Arc::new(pdf), None).expect("opens");
|
||||
let expected_rect = [46.004, 147.6, 153.38, 159.6];
|
||||
let base_urls = session.find_urls(id);
|
||||
assert_eq!(base_urls.len(), 1);
|
||||
let base_rect = base_urls[0].1[0];
|
||||
for (got, exp) in base_rect.into_iter().zip(expected_rect) {
|
||||
assert!((got - exp).abs() < 1e-2, "0 deg: got {base_rect:?}, expected {expected_rect:?}");
|
||||
}
|
||||
|
||||
for step in [90, 180, 270] {
|
||||
session.apply(id, Edit::RotatePages { pages: vec![0], degrees: 90 }).expect("rotates");
|
||||
let urls = session.find_urls(id);
|
||||
assert_eq!(urls.len(), 1);
|
||||
assert_eq!(urls[0].0, 0);
|
||||
assert_eq!(urls[0].2, "https://example.com");
|
||||
assert_eq!(urls[0].1.len(), 1);
|
||||
let r = urls[0].1[0];
|
||||
for (got, exp) in r.into_iter().zip(expected_rect) {
|
||||
assert!((got - exp).abs() < 1e-2, "rotation {step} deg: got {r:?}, expected {expected_rect:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -40,3 +40,17 @@ pub(crate) fn record_link_scan() {
|
||||
counts.set((markers, links + 1));
|
||||
});
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static FULL_REFRESHES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// A whole-document refresh (re-inspection) ran on this thread.
|
||||
pub(crate) fn record_full_refresh() {
|
||||
FULL_REFRESHES.with(|n| n.set(n.get() + 1));
|
||||
}
|
||||
|
||||
/// How many whole-document refreshes ran on this thread since the last call, and starts over.
|
||||
pub(crate) fn take_full_refreshes() -> usize {
|
||||
FULL_REFRESHES.with(|n| n.replace(0))
|
||||
}
|
||||
|
||||
+501
-1
@@ -1779,6 +1779,45 @@ fn low_resolution_printing_prints_only_the_chosen_content() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A comment and a field the file leaves without an appearance print as the page shows them:
|
||||
/// a text box (`/FreeText` with only `/Contents` and `/DA`) and a check box set on with
|
||||
/// `/NeedAppearances`. The vector print drew only appearance streams, so both were on screen and
|
||||
/// in Print as Image but not on paper (pdf.js `bug1865341`, `freetext_print_no_appearance`).
|
||||
/// ISO 32000-2 §12.5.3: an annotation with the Print flag is printed.
|
||||
#[test]
|
||||
fn comments_and_fields_without_an_appearance_print_as_shown() {
|
||||
let content = "";
|
||||
let pdf = format!(
|
||||
"%PDF-1.7
|
||||
1 0 obj << /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [6 0 R] /NeedAppearances true /DA (/Helv 0 Tf 0 g) >> >> endobj
|
||||
2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj
|
||||
3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Contents 4 0 R /Annots [5 0 R 6 0 R] >> endobj
|
||||
4 0 obj << /Length {} >> stream
|
||||
{content}
|
||||
endstream endobj
|
||||
5 0 obj << /Type /Annot /Subtype /FreeText /F 4 /P 3 0 R /Rect [10 120 190 190] /DA (/Helv 40 Tf 0 g) /Contents (WWWW) >> endobj
|
||||
6 0 obj << /Type /Annot /Subtype /Widget /FT /Btn /T (Box) /V /Yes /AS /Yes /F 4 /P 3 0 R /Rect [10 10 110 110] /MK << /CA (8) >> >> endobj
|
||||
trailer << /Root 1 0 R >>
|
||||
%%EOF",
|
||||
content.len(),
|
||||
);
|
||||
let mut s = Session::new();
|
||||
let id = s.open("bare.pdf", None, Arc::new(pdf.into_bytes()), None).unwrap();
|
||||
let settings =
|
||||
print::Settings { pages: vec![0], paper: (200.0, 200.0), layout: print::Layout::Size(print::SizeMode::Actual), ..Default::default() };
|
||||
let (w, h, rgba) = printed_pixels(s.print_pdf(id, &settings).unwrap());
|
||||
assert_eq!((w, h), (200, 200));
|
||||
// Dark pixels in the text box (top half) and in the check box (bottom half).
|
||||
let dark = |y0: usize, y1: usize| {
|
||||
(y0..y1)
|
||||
.flat_map(|y| (0..w as usize).map(move |x| (x, y)))
|
||||
.filter(|&(x, y)| rgba.get((y * w as usize + x) * 4).is_some_and(|&r| r < 128))
|
||||
.count()
|
||||
};
|
||||
assert!(dark(10, 80) > 50, "the text box prints");
|
||||
assert!(dark(90, 190) > 50, "the check box prints");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_permissions_password_unlocks_an_open_document() {
|
||||
// Only a permissions password (#995, #1077): opens without asking. Changes are allowed,
|
||||
@@ -3120,6 +3159,66 @@ fn setting_the_calculation_order_recalculates_and_undoes() {
|
||||
assert!(matches!(s.apply(id, Edit::SetCalculationOrder { names: vec!["qty".into()] }), Err(EditError::Form(_))));
|
||||
}
|
||||
|
||||
/// A Calculate script that sets its own field through the field object, not `event.value`,
|
||||
/// gives the field that value, text included; when it sets `event.value` as well, that wins.
|
||||
#[test]
|
||||
fn a_calculate_script_setting_its_own_field_object_keeps_the_value() {
|
||||
let (mut s, id) = session_with(1);
|
||||
for (i, name) in ["origin", "copy", "both"].into_iter().enumerate() {
|
||||
let y = 250.0 - 40.0 * i as f64;
|
||||
let kind = NewField::Text { multiline: false };
|
||||
s.apply(id, Edit::AddField { page: 0, rect: [20.0, y, 180.0, y + 22.0], kind, name: Some(name.into()) }).unwrap();
|
||||
}
|
||||
let script = |name: &str, js: &str| Edit::SetFieldScript { name: name.into(), event: "calculate".into(), script: Some(js.into()) };
|
||||
s.apply(id, script("copy", "var o = this.getField(\"origin\");\nthis.getField(\"copy\").value = o.value;")).unwrap();
|
||||
s.apply(id, script("both", "this.getField(\"both\").value = \"field\";\nevent.value = this.getField(\"origin\").value + \"!\";")).unwrap();
|
||||
s.apply(id, Edit::SetFieldValue { name: "origin".into(), value: FieldValue::Text("abc".into()) }).unwrap();
|
||||
let value = |s: &Session, n: &str| s.get(id).unwrap().form.iter().find(|f| f.name == n).and_then(|f| f.value.first().cloned());
|
||||
assert_eq!(value(&s, "copy").as_deref(), Some("abc"));
|
||||
assert_eq!(value(&s, "both").as_deref(), Some("abc!"), "event.value decides when the script sets both");
|
||||
s.apply(id, Edit::SetFieldValue { name: "origin".into(), value: FieldValue::Text("12".into()) }).unwrap();
|
||||
assert_eq!(value(&s, "copy").as_deref(), Some("12"));
|
||||
}
|
||||
|
||||
/// A Calculate script that assigns `event.value` the value its field already holds keeps it, even
|
||||
/// after writing another value through its field object; and a combo box a script moves to
|
||||
/// another option selects that option in `/I` too.
|
||||
#[test]
|
||||
fn a_calculate_script_assigning_event_value_wins_and_a_combo_keeps_its_selection() {
|
||||
let (mut s, id) = session_with(1);
|
||||
s.apply(
|
||||
id,
|
||||
Edit::AddField { page: 0, rect: [20.0, 250.0, 180.0, 272.0], kind: NewField::Text { multiline: false }, name: Some("origin".into()) },
|
||||
)
|
||||
.unwrap();
|
||||
s.apply(id, Edit::AddField { page: 0, rect: [20.0, 210.0, 180.0, 232.0], kind: NewField::Text { multiline: false }, name: Some("kept".into()) })
|
||||
.unwrap();
|
||||
let kind = NewField::Combo { options: vec!["Small".into(), "Large".into()], editable: false };
|
||||
s.apply(id, Edit::AddField { page: 0, rect: [20.0, 170.0, 180.0, 192.0], kind, name: Some("size".into()) }).unwrap();
|
||||
s.apply(id, Edit::SetFieldValue { name: "size".into(), value: FieldValue::Choice(vec!["Small".into()]) }).unwrap();
|
||||
let script = |name: &str, js: &str| Edit::SetFieldScript { name: name.into(), event: "calculate".into(), script: Some(js.into()) };
|
||||
s.apply(
|
||||
id,
|
||||
script(
|
||||
"kept",
|
||||
"var v = event.value;
|
||||
this.getField(\"kept\").value = \"field\";
|
||||
event.value = v;",
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
s.apply(id, script("size", "event.value = this.getField(\"origin\").value > 5 ? \"Large\" : \"Small\";")).unwrap();
|
||||
s.apply(id, Edit::SetFieldValue { name: "origin".into(), value: FieldValue::Text("9".into()) }).unwrap();
|
||||
assert!(s.take_js_output(id).errors.is_empty(), "both scripts ran to the end");
|
||||
let doc = s.get(id).unwrap();
|
||||
let value = |n: &str| doc.form.iter().find(|f| f.name == n).and_then(|f| f.value.first().cloned());
|
||||
assert_eq!(value("kept").as_deref(), None, "event.value, set to the field's own value, decides");
|
||||
assert_eq!(value("size").as_deref(), Some("Large"));
|
||||
let size = doc.form.iter().find(|f| f.name == "size").map(|f| f.obj).unwrap();
|
||||
let selected = doc.editor.as_ref().unwrap().cos.get(size).as_dict().and_then(|d| d.get(b"I")).cloned();
|
||||
assert_eq!(selected, Some(pdfcraft_cos::Object::Array(vec![pdfcraft_cos::Object::Int(1)])));
|
||||
}
|
||||
|
||||
/// One 612×300 page with the content stream `body`. Object 4 is Helvetica; `resources` is what
|
||||
/// the page's /Resources holds.
|
||||
fn one_line_page(resources: &str, body: &str) -> Vec<u8> {
|
||||
@@ -3441,6 +3540,185 @@ fn printing_keeps_hidden_layers_hidden() {
|
||||
assert!(red > 100, "shown again, Layer A prints again: {red} red");
|
||||
}
|
||||
|
||||
/// A PDF of `objs`, numbered from 1, the first being the catalog.
|
||||
fn pdf_of_objects(objs: &[Vec<u8>]) -> Vec<u8> {
|
||||
let mut pdf = b"%PDF-1.7\n".to_vec();
|
||||
let mut offsets = Vec::new();
|
||||
for (i, o) in objs.iter().enumerate() {
|
||||
offsets.push(pdf.len());
|
||||
pdf.extend_from_slice(format!("{} 0 obj\n", i + 1).as_bytes());
|
||||
pdf.extend_from_slice(o);
|
||||
pdf.extend_from_slice(b"\nendobj\n");
|
||||
}
|
||||
let xref = pdf.len();
|
||||
pdf.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes());
|
||||
for o in offsets {
|
||||
pdf.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());
|
||||
}
|
||||
pdf.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes());
|
||||
pdf
|
||||
}
|
||||
|
||||
/// ISO 32000-2 §8.11.4.4: the default configuration's auto state for the Print event sets the
|
||||
/// layers it names when the document prints. Red is on screen but `/PrintState /OFF`, green is off
|
||||
/// on screen but `/PrintState /ON`: on paper, vector or as an image, green prints and red doesn't.
|
||||
/// Two blue squares are on screen and `/PrintState /OFF` too, but no Print recommendation reaches
|
||||
/// them (one is named only in the View entry, the other in a Print entry without the Print
|
||||
/// category), so they print as shown.
|
||||
#[test]
|
||||
fn printing_applies_the_print_auto_state() {
|
||||
let content = b"/OC /A BDC 1 0 0 rg 10 10 80 80 re f EMC /OC /B BDC 0 1 0 rg 110 10 80 80 re f EMC \
|
||||
/OC /C BDC 0 0 1 rg 210 10 40 40 re f EMC /OC /D BDC 0 0 1 rg 210 55 40 40 re f EMC";
|
||||
let screen_only = b"/Usage << /View << /ViewState /ON >> /Print << /PrintState /OFF >> >> >>";
|
||||
let objs: Vec<Vec<u8>> = vec![
|
||||
b"<< /Type /Catalog /Pages 2 0 R /OCProperties << /OCGs [5 0 R 6 0 R 7 0 R 8 0 R] /D << /OFF [6 0 R] \
|
||||
/AS [<< /Event /Print /OCGs [5 0 R 6 0 R] /Category [/Print] >> << /Event /View /OCGs [5 0 R 6 0 R 7 0 R] /Category [/View] >> \
|
||||
<< /Event /Print /OCGs [8 0 R] /Category [/Language] >>] >> >> >>"
|
||||
.to_vec(),
|
||||
b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(),
|
||||
b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 100] /Contents 4 0 R \
|
||||
/Resources << /Properties << /A 5 0 R /B 6 0 R /C 7 0 R /D 8 0 R >> >> >>"
|
||||
.to_vec(),
|
||||
[format!("<< /Length {} >>\nstream\n", content.len()).as_bytes(), content, b"\nendstream"].concat(),
|
||||
[b"<< /Type /OCG /Name (View only) ".as_slice(), screen_only].concat(),
|
||||
b"<< /Type /OCG /Name (Print only) /Usage << /View << /ViewState /OFF >> /Print << /PrintState /ON >> >> >>".to_vec(),
|
||||
[b"<< /Type /OCG /Name (View entry) ".as_slice(), screen_only].concat(),
|
||||
[b"<< /Type /OCG /Name (Other category) ".as_slice(), screen_only].concat(),
|
||||
];
|
||||
let pdf = pdf_of_objects(&objs);
|
||||
|
||||
let colours = |page: &pdfcraft_render::RenderedPage| {
|
||||
let px = page.rgba.as_chunks::<4>().0;
|
||||
let red = px.iter().filter(|p| p[0] > 200 && p[1] < 60 && p[2] < 60).count();
|
||||
let green = px.iter().filter(|p| p[1] > 200 && p[0] < 60 && p[2] < 60).count();
|
||||
let blue = px.iter().filter(|p| p[2] > 200 && p[0] < 60 && p[1] < 60).count();
|
||||
(red, green, blue)
|
||||
};
|
||||
let mut s = Session::new();
|
||||
let id = s.open("auto-state.pdf", None, Arc::new(pdf), None).unwrap();
|
||||
let (red, green, shown_blue) = colours(&render_page(&s, id));
|
||||
assert!(red > 100 && green == 0, "on screen, red shows and green doesn't: {red} red, {green} green");
|
||||
// The print dialog's preview shows the page as it prints, the view as it shows; so after a
|
||||
// Layers panel change too.
|
||||
let preview = |s: &Session, tag: u64| {
|
||||
let doc = s.get(id).unwrap();
|
||||
let mut renderer = pdfcraft_render::PageRenderer::new(doc.display.clone(), display_config(&doc.config));
|
||||
colours(&renderer.render(pdfcraft_render::RenderRequest { page: 0, scale: 2.0, tag, ..Default::default() }))
|
||||
};
|
||||
let view_entry = s.get(id).unwrap().info.layers.iter().position(|l| l.name == "View entry").unwrap();
|
||||
let mut printed_blue = Vec::new();
|
||||
for _ in 0..2 {
|
||||
let (red, green, blue) = preview(&s, pdfcraft_render::PRINT_TAG);
|
||||
assert!(red == 0 && green > 100, "the preview shows the print: {red} red, {green} green");
|
||||
printed_blue.push(blue);
|
||||
let (red, green, _) = preview(&s, 0);
|
||||
assert!(red > 100 && green == 0, "the view is unchanged: {red} red, {green} green");
|
||||
// Hidden after the first round, shown again after the second.
|
||||
assert!(s.set_layer_visible(id, view_entry, printed_blue.len() == 2));
|
||||
}
|
||||
// Hidden in the panel, View entry (no Print recommendation) leaves the preview too.
|
||||
assert!(printed_blue[1] * 4 < printed_blue[0] * 3, "the preview follows the panel: {printed_blue:?} blue");
|
||||
for raster in [None, Some(print::Raster { dpi: 72.0, grayscale: false })] {
|
||||
let bytes = Arc::new(s.print_pdf(id, &print::Settings { pages: vec![0], raster, ..Default::default() }).unwrap());
|
||||
let mut out = Session::new();
|
||||
let printed = out.open("print.pdf", None, bytes.clone(), None).unwrap();
|
||||
let (red, green, blue) = colours(&render_page(&out, printed));
|
||||
assert_eq!(red, 0, "the view-only layer doesn't print (as image: {})", raster.is_some());
|
||||
assert!(green > 100, "the print-only layer prints (as image: {}): {green} green", raster.is_some());
|
||||
// Both blue squares print: the one shown on screen alone is half of them.
|
||||
assert!(
|
||||
blue * 4 > shown_blue * 3,
|
||||
"the layers no Print recommendation reaches print as shown (as image: {}): {blue} of {shown_blue} blue",
|
||||
raster.is_some()
|
||||
);
|
||||
// The vector copy's states are final: nothing a reader applies when drawing is left to
|
||||
// turn them back (the auto state, or a layer's `/Usage /View /ViewState`).
|
||||
let layers = &out.get(printed).unwrap().info.layers;
|
||||
if raster.is_none() {
|
||||
let cos = pdfcraft_cos::Document::open(bytes).unwrap();
|
||||
assert_eq!(layers.len(), 4);
|
||||
for layer in layers {
|
||||
let group = cos.get(pdfcraft_cos::ObjRef::new(layer.id.0, layer.id.1));
|
||||
assert!(group.as_dict().is_some_and(|g| !g.contains(b"Usage")), "{} keeps its /Usage", layer.name);
|
||||
}
|
||||
let root = cos.trailer().get(b"Root").map(|r| cos.resolve(r)).unwrap();
|
||||
let properties = root.as_dict().and_then(|r| r.get(b"OCProperties")).map(|p| cos.resolve(p)).unwrap();
|
||||
let config = properties.as_dict().and_then(|p| p.get(b"D")).map(|d| cos.resolve(d)).unwrap();
|
||||
assert!(config.as_dict().is_some_and(|d| !d.contains(b"AS")), "the print copy keeps /AS");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The print auto state of `layers` (object numbers from 5) in a document whose default
|
||||
/// configuration has `auto` as its `/AS` and `groups` as the layers' dictionaries.
|
||||
fn print_states_of(auto: &str, groups: &[&str]) -> Vec<bool> {
|
||||
let ocgs: String = (0..groups.len()).map(|i| format!("{} 0 R ", i + 5)).collect();
|
||||
let mut objs: Vec<Vec<u8>> = vec![
|
||||
format!("<< /Type /Catalog /Pages 2 0 R /OCProperties << /OCGs [{ocgs}] /D << /AS {auto} >> >> >>").into_bytes(),
|
||||
b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(),
|
||||
b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] /Contents 4 0 R >>".to_vec(),
|
||||
b"<< /Length 0 >>\nstream\n\nendstream".to_vec(),
|
||||
];
|
||||
objs.extend(groups.iter().map(|g| g.as_bytes().to_vec()));
|
||||
let cos = pdfcraft_cos::Document::open(Arc::new(pdf_of_objects(&objs))).unwrap();
|
||||
let layers: Vec<Layer> = (0..groups.len()).map(|i| Layer { id: (i as u32 + 5, 0), name: format!("{i}"), visible: true, initial: true }).collect();
|
||||
crate::print_layer_states(&cos, &layers).expect("there are Print entries").iter().map(|l| l.visible).collect()
|
||||
}
|
||||
|
||||
/// ISO 32000-2 §8.11.4.4: a group prints only if every category of every Print entry naming it
|
||||
/// recommends ON. A Print category (`/PrintState /ON`) and a View category of another Print entry
|
||||
/// (`/ViewState /OFF`) disagree, so the group stays off; with both ON it prints. A `/Category`
|
||||
/// written as a single name (Table 101 asks for an array) is read as one.
|
||||
#[test]
|
||||
fn a_layer_prints_only_if_every_recommendation_is_on() {
|
||||
let auto = "[<< /Event /Print /OCGs [5 0 R 6 0 R] /Category [/Print] >> << /Event /Print /OCGs [5 0 R 6 0 R] /Category [/View] >> \
|
||||
<< /Event /Print /OCGs [7 0 R] /Category /Print >>]";
|
||||
let states = print_states_of(
|
||||
auto,
|
||||
&[
|
||||
"<< /Type /OCG /Name (Disagree) /Usage << /View << /ViewState /OFF >> /Print << /PrintState /ON >> >> >>",
|
||||
"<< /Type /OCG /Name (Agree) /Usage << /View << /ViewState /ON >> /Print << /PrintState /ON >> >> >>",
|
||||
"<< /Type /OCG /Name (Single name) /Usage << /Print << /PrintState /OFF >> >> >>",
|
||||
],
|
||||
);
|
||||
assert_eq!(states, [false, true, false]);
|
||||
}
|
||||
|
||||
/// At most 1,024 `/AS` entries are read: an entry past them that would turn the layer off is not
|
||||
/// reached, while the same entry within them is.
|
||||
#[test]
|
||||
fn the_print_auto_state_reads_a_bounded_number_of_entries() {
|
||||
let layer = "<< /Type /OCG /Name (Layer) /Usage << /Print << /PrintState /OFF >> >> >>";
|
||||
let other = "<< /Type /OCG /Name (Other) >>";
|
||||
let auto = |before: usize| {
|
||||
let filler = "<< /Event /Print /OCGs [6 0 R] /Category [/Print] >> ".repeat(before);
|
||||
format!("[{filler} << /Event /Print /OCGs [5 0 R] /Category [/Print] >>]")
|
||||
};
|
||||
assert_eq!(print_states_of(&auto(1023), &[layer, other]), [false, true], "the 1,024th entry is read");
|
||||
assert_eq!(print_states_of(&auto(1024), &[layer, other]), [true, true], "the 1,025th entry is not");
|
||||
}
|
||||
|
||||
/// Reading the print auto state is bounded over all `/AS` entries together: 1,024 Print entries
|
||||
/// sharing one `/Category` array of 70,000 names, `/Print` last, read 65,536 names in all, find no
|
||||
/// Print category and recommend nothing, instead of reading the array 1,024 times.
|
||||
#[test]
|
||||
fn the_print_auto_state_reads_a_bounded_number_of_categories() {
|
||||
let names = format!("[{} /Print]", "/View ".repeat(70_000));
|
||||
let entries = "<< /Event /Print /OCGs [5 0 R] /Category 6 0 R >> ".repeat(1024);
|
||||
let objs: Vec<Vec<u8>> = vec![
|
||||
format!("<< /Type /Catalog /Pages 2 0 R /OCProperties << /OCGs [5 0 R] /D << /AS [{entries}] >> >> >>").into_bytes(),
|
||||
b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(),
|
||||
b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] /Contents 4 0 R >>".to_vec(),
|
||||
b"<< /Length 0 >>\nstream\n\nendstream".to_vec(),
|
||||
b"<< /Type /OCG /Name (Layer) /Usage << /Print << /PrintState /OFF >> >> >>".to_vec(),
|
||||
names.into_bytes(),
|
||||
];
|
||||
let cos = pdfcraft_cos::Document::open(Arc::new(pdf_of_objects(&objs))).unwrap();
|
||||
let layer = Layer { id: (5, 0), name: "Layer".into(), visible: true, initial: true };
|
||||
let printed = crate::print_layer_states(&cos, std::slice::from_ref(&layer)).expect("there are Print entries");
|
||||
assert!(printed.iter().all(|l| l.visible), "past the bound nothing is read, so the layer prints as shown");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn printing_lays_out_sheets_that_render() {
|
||||
let (s, id) = session_with(5);
|
||||
@@ -3904,7 +4182,9 @@ fn an_optimize_job_reports_its_stages_and_can_be_cancelled() {
|
||||
})
|
||||
.unwrap();
|
||||
assert!(bytes.starts_with(b"%PDF-"));
|
||||
assert_eq!(stages.first(), Some(&OptimizeStage::Discarding));
|
||||
assert_eq!(stages.first(), Some(&OptimizeStage::Reading { done: 0, total: 2 }), "it says what it does first");
|
||||
assert!(!stages.contains(&OptimizeStage::Discarding), "nothing was chosen to discard: {stages:?}");
|
||||
assert!(stages.iter().any(|st| matches!(st, OptimizeStage::Images { .. })), "{stages:?}");
|
||||
assert_eq!(&stages[stages.len() - 3..], [OptimizeStage::CleaningUp, OptimizeStage::Merging, OptimizeStage::Writing]);
|
||||
let fractions: Vec<f32> = stages.iter().map(|st| st.fraction()).collect();
|
||||
assert!(fractions.windows(2).all(|w| w[0] <= w[1]), "the bar never goes back: {fractions:?}");
|
||||
@@ -3915,6 +4195,20 @@ fn an_optimize_job_reports_its_stages_and_can_be_cancelled() {
|
||||
"no images: no division by zero"
|
||||
);
|
||||
|
||||
// What the bar shows before anything is reported says nothing of user data either.
|
||||
assert_eq!(OptimizeStage::default(), OptimizeStage::Reading { done: 0, total: 0 });
|
||||
assert_eq!(OptimizeStage::default().fraction(), 0.0);
|
||||
assert!(OptimizeStage::Reading { done: 2, total: 4 }.fraction() > 0.0, "reading pages moves the bar");
|
||||
|
||||
// Discarding says so when something is. This document has no metadata, which only stops it after
|
||||
// the stage is reported.
|
||||
let mut with_discard = Vec::new();
|
||||
let _ = s.optimize_job(id, &settings, &[crate::Hidden::Metadata]).unwrap().run(|st| {
|
||||
with_discard.push(st);
|
||||
true
|
||||
});
|
||||
assert_eq!(with_discard.first(), Some(&OptimizeStage::Discarding));
|
||||
|
||||
// Cancelled at the merge: nothing is written, the open document is untouched.
|
||||
let before = s.get(id).unwrap().bytes.clone();
|
||||
let r = s.optimize_job(id, &settings, &[]).unwrap().run(|st| st != OptimizeStage::Merging);
|
||||
@@ -6080,6 +6374,20 @@ fn form_javascript_validates_calculates_and_formats() {
|
||||
assert!(s.run_javascript(id, "1", None).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn javascript_field_rect_moves_first_widget_and_undoes() {
|
||||
let mut s = Session::new();
|
||||
let id = s.open("rect.pdf", None, Arc::new(scripted_form()), None).unwrap();
|
||||
let initial = s.get(id).unwrap().form.iter().find(|f| f.name == "price").unwrap().widgets[0].rect;
|
||||
s.run_javascript(id, "getField('price').rect = [30, 40, 130, 60];", Some("go")).unwrap();
|
||||
assert_eq!(s.get(id).unwrap().form.iter().find(|f| f.name == "price").unwrap().widgets[0].rect, [30.0, 40.0, 130.0, 60.0]);
|
||||
assert_eq!(s.get(id).unwrap().can_undo(), Some("Run JavaScript"));
|
||||
s.undo(id).unwrap();
|
||||
assert_eq!(s.get(id).unwrap().form.iter().find(|f| f.name == "price").unwrap().widgets[0].rect, initial);
|
||||
s.redo(id).unwrap();
|
||||
assert_eq!(s.get(id).unwrap().form.iter().find(|f| f.name == "price").unwrap().widgets[0].rect, [30.0, 40.0, 130.0, 60.0]);
|
||||
}
|
||||
|
||||
/// XFA forms check `xfa_installed` and `xfa_version` in a document script that runs before
|
||||
/// each of their scripts, and alert when either is missing.
|
||||
#[test]
|
||||
@@ -8857,6 +9165,45 @@ fn content_refresh_lists_match_the_storages_an_edit_touches() {
|
||||
assert_eq!(Session::content_refresh_lists(None), (true, true), "undo/redo re-read both");
|
||||
}
|
||||
|
||||
/// Recognized text is an invisible text layer on its page, so applying it refreshes like any
|
||||
/// other content edit, not by re-inspecting the whole document (#6310): on a 567-page file with
|
||||
/// 60,102 font resources one word took 2.4 s, the full refresh nearly all of it. The page tree,
|
||||
/// comments, fields, links and marks stay as they were; the words are on their page, the font
|
||||
/// list picks up the OCR font on `refresh_fonts`, undo and redo take the words out and back
|
||||
/// without a full refresh either, and a save keeps them.
|
||||
#[test]
|
||||
fn ocr_words_refresh_only_the_page_content_they_add() {
|
||||
use crate::ocr::{OcrPage, PlacedWord};
|
||||
let (mut s, id) = session_with(3);
|
||||
let words_on = |s: &Session, page: usize| s.get(id).unwrap().text_lines(page).iter().map(|l| l.text.trim().to_string()).collect::<Vec<_>>();
|
||||
let before = s.get(id).unwrap();
|
||||
let view = format!("{:?}", (&before.info.pages, &before.info.annotations, &before.info.fields, &before.links, before.marks()));
|
||||
let others = (words_on(&s, 0), words_on(&s, 2));
|
||||
assert!(!words_on(&s, 1).iter().any(|w| w.contains("HELLO")));
|
||||
take_full_refreshes();
|
||||
let word = PlacedWord { text: "HELLO".into(), origin: [40.0, 40.0], across: [60.0, 0.0], up: [0.0, 20.0] };
|
||||
assert_eq!(s.apply_ocr(id, &[OcrPage { page: 1, words: vec![word], already_on_page: 0, skipped: None }]).unwrap(), 1);
|
||||
assert_eq!(take_full_refreshes(), 0, "applying OCR words doesn't re-inspect the document");
|
||||
let after = s.get(id).unwrap();
|
||||
assert_eq!(format!("{:?}", (&after.info.pages, &after.info.annotations, &after.info.fields, &after.links, after.marks())), view);
|
||||
assert!(words_on(&s, 1).iter().any(|w| w == "HELLO"), "{:?}", words_on(&s, 1));
|
||||
assert_eq!((words_on(&s, 0), words_on(&s, 2)), others, "the other pages are untouched");
|
||||
s.refresh_fonts(id);
|
||||
let d = s.get(id).unwrap();
|
||||
let full = pdfcraft_render::inspect(d.bytes.clone(), None).unwrap();
|
||||
assert_eq!(format!("{:?}", d.info.fonts), format!("{:?}", full.fonts), "the font list is what a full inspection reads");
|
||||
assert_eq!(d.info.file_size, full.file_size);
|
||||
s.undo(id).unwrap();
|
||||
assert!(!words_on(&s, 1).iter().any(|w| w.contains("HELLO")), "undo takes the words out");
|
||||
s.redo(id).unwrap();
|
||||
assert!(words_on(&s, 1).iter().any(|w| w == "HELLO"), "redo puts them back");
|
||||
assert_eq!(take_full_refreshes(), 0, "undo and redo refresh the content alone too");
|
||||
let saved = s.save_bytes(id).unwrap();
|
||||
let mut reopened = Session::new();
|
||||
let rid = reopened.open("saved.pdf", None, saved, None).unwrap();
|
||||
assert!(reopened.get(rid).unwrap().text_lines(1).iter().any(|l| l.text.trim() == "HELLO"), "the save keeps the words");
|
||||
}
|
||||
|
||||
/// A content edit can add a font (Add text in Times); the narrow refresh leaves the font list
|
||||
/// as it was, and `refresh_fonts` reads it again before Properties ▸ Fonts or `doc_info` show it.
|
||||
#[test]
|
||||
@@ -10147,6 +10494,159 @@ fn a_date_its_validate_script_refuses_is_not_tried_again() {
|
||||
assert!(value(&s, "name").is_empty(), "nothing the refused run changed is kept: {:?}", value(&s, "name"));
|
||||
}
|
||||
|
||||
/// Floating fields (XFA 3.3 p. 1222): text that embeds a hidden field shows the value its
|
||||
/// initialize script gives it, the value a button's script gives it later and the value a
|
||||
/// calculation gives one, as it does the sheet number and count; the fields sit in an unnamed
|
||||
/// subform, as forms place them (#6160).
|
||||
#[test]
|
||||
fn text_shows_the_values_scripts_give_its_floating_fields() {
|
||||
let xdp = r##"<?xml version="1.0" encoding="UTF-8"?>
|
||||
<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>
|
||||
<subform w="7in" h="9in">
|
||||
<field name="Viewer" id="floatViewer" presence="hidden" access="readOnly" w="1in" h="0.3in"><ui><textEdit/></ui>
|
||||
<event activity="initialize"><script contentType="application/x-javascript">this.rawValue = "Opened";</script></event><bind match="none"/></field>
|
||||
<field name="Sheet" id="floatSheet" presence="hidden" w="1in" h="0.3in"><ui><textEdit/></ui>
|
||||
<event activity="ready" ref="$layout"><script contentType="application/x-javascript">this.rawValue = xfa.layout.sheet(this)+1</script></event><bind match="none"/></field>
|
||||
<field name="Sheets" id="floatSheets" presence="hidden" w="1in" h="0.3in"><ui><textEdit/></ui>
|
||||
<event activity="ready" ref="$layout"><script contentType="application/x-javascript">this.rawValue = xfa.layout.sheetCount()</script></event><bind match="none"/></field>
|
||||
<field name="Shout" id="floatShout" presence="hidden" w="1in" h="0.3in"><ui><textEdit/></ui>
|
||||
<calculate><script contentType="application/x-javascript">Viewer.rawValue + "!"</script></calculate><bind match="none"/></field>
|
||||
<field name="set" y="1in" w="2in" h="0.3in"><ui><button/></ui>
|
||||
<event activity="click"><script contentType="application/x-javascript">Viewer.rawValue = "Clicked";</script></event></field>
|
||||
<draw name="line" y="2in" w="6in" h="1in"><value><exData contentType="text/html"><body xmlns="http://www.w3.org/1999/xhtml" xmlns:xfa="http://www.xfa.org/schema/xfa-data/1.0/"><p>Viewer: <span xfa:embedType="uri" xfa:embedMode="raw" xfa:embed="#floatViewer"/><br/>Sheet <span xfa:embed="#floatSheet"/> of <span xfa:embed="#floatSheets"/><br/>Calculated: <span xfa:embed="#floatShout"/></p></body></exData></value></draw>
|
||||
</subform>
|
||||
</subform>
|
||||
</template>
|
||||
</xdp:xdp>
|
||||
"##;
|
||||
let mut s = Session::new();
|
||||
let id = s.open("float.pdf", None, Arc::new(pdfcraft_xfa::fixtures::shell(xdp)), None).expect("opens");
|
||||
let text = page_texts(&s, id).join(
|
||||
"
|
||||
",
|
||||
);
|
||||
assert!(text.contains("Viewer: Opened"), "{text}");
|
||||
assert!(text.contains("Sheet 1 of 1"), "{text}");
|
||||
assert!(text.contains("Calculated: Opened!"), "{text}");
|
||||
let o = s.run_javascript(id, "", Some("set")).expect("clicks");
|
||||
assert_eq!(o.error, None, "{o:?}");
|
||||
let text = page_texts(&s, id).join(
|
||||
"
|
||||
",
|
||||
);
|
||||
assert!(text.contains("Viewer: Clicked"), "{text}");
|
||||
assert!(text.contains("Calculated: Clicked!"), "{text}");
|
||||
}
|
||||
|
||||
/// Text that embeds a field follows its data whoever writes it (XFA 3.3 pp. 221–222): a
|
||||
/// script writing another field bound to the same data, a script writing a page area's field,
|
||||
/// a typed value in a plain one-line field, a pick in a drop-down list, and a reset (of a
|
||||
/// drop-down list, and of a page area's field that has no widget).
|
||||
#[test]
|
||||
fn floating_fields_follow_their_data_whoever_writes_it() {
|
||||
let xdp = r##"<?xml version="1.0" encoding="UTF-8"?>
|
||||
<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="1in" w="7.5in" h="9in"/><medium short="8.5in" long="11in"/>
|
||||
<field name="Stamp" id="floatStamp" presence="hidden" w="1in" h="0.3in"><ui><textEdit/></ui></field>
|
||||
<draw x="0.5in" y="0.2in" w="5in" h="0.4in"><value><exData contentType="text/html"><body xmlns="http://www.w3.org/1999/xhtml" xmlns:xfa="http://www.xfa.org/schema/xfa-data/1.0/"><p>Stamp: <span xfa:embed="#floatStamp"/></p></body></exData></value></draw>
|
||||
</pageArea></pageSet>
|
||||
<subform w="7in" h="8in">
|
||||
<field name="Note" id="floatNote" presence="hidden" w="1in" h="0.3in"><ui><textEdit/></ui></field>
|
||||
<area name="box" y="0.5in"><field name="Note" w="2in" h="0.3in"><ui><textEdit/></ui></field></area>
|
||||
<field name="Edit" id="floatEdit" y="1in" w="2in" h="0.3in"><ui><textEdit/></ui><value><text>start</text></value></field>
|
||||
<field name="Pick" id="floatPick" y="4.5in" w="2in" h="0.3in"><ui><choiceList/></ui><items><text>A</text><text>B</text></items><value><text>A</text></value></field>
|
||||
<field name="pickB" y="5in" w="2in" h="0.3in"><ui><button/></ui>
|
||||
<event activity="click"><script contentType="application/x-javascript">Pick.rawValue = "B";</script></event></field>
|
||||
<field name="clearPick" y="5.5in" w="2in" h="0.3in"><ui><button/></ui>
|
||||
<event activity="click"><script contentType="application/x-javascript">xfa.host.resetData("Pick");</script></event></field>
|
||||
<field name="share" y="1.5in" w="2in" h="0.3in"><ui><button/></ui>
|
||||
<event activity="click"><script contentType="application/x-javascript">box.Note.rawValue = "Shared";</script></event></field>
|
||||
<field name="stamp" y="2in" w="2in" h="0.3in"><ui><button/></ui>
|
||||
<event activity="click"><script contentType="application/x-javascript">front.Stamp.rawValue = "Paid";</script></event></field>
|
||||
<field name="clear" y="2.5in" w="2in" h="0.3in"><ui><button/></ui>
|
||||
<event activity="click"><script contentType="application/x-javascript">xfa.host.resetData();</script></event></field>
|
||||
<draw y="3in" w="6in" h="1in"><value><exData contentType="text/html"><body xmlns="http://www.w3.org/1999/xhtml" xmlns:xfa="http://www.xfa.org/schema/xfa-data/1.0/"><p>Note: <span xfa:embed="#floatNote"/><br/>Edit: <span xfa:embed="#floatEdit"/><br/>Pick: <span xfa:embed="#floatPick"/></p></body></exData></value></draw>
|
||||
</subform>
|
||||
</subform>
|
||||
</template>
|
||||
</xdp:xdp>
|
||||
"##;
|
||||
let mut s = Session::new();
|
||||
let id = s.open("follow.pdf", None, Arc::new(pdfcraft_xfa::fixtures::shell(xdp)), None).expect("opens");
|
||||
let text = |s: &Session| {
|
||||
page_texts(s, id).join(
|
||||
"
|
||||
",
|
||||
)
|
||||
};
|
||||
let click = |s: &mut Session, button: &str| {
|
||||
let o = s.run_javascript(id, "", Some(button)).expect("clicks");
|
||||
assert_eq!(o.error, None, "{button}: {o:?}");
|
||||
};
|
||||
assert!(text(&s).contains("Edit: start"), "{}", text(&s));
|
||||
click(&mut s, "share");
|
||||
assert!(text(&s).contains("Note: Shared"), "the field bound to the same data: {}", text(&s));
|
||||
click(&mut s, "stamp");
|
||||
assert!(text(&s).contains("Stamp: Paid"), "a page area's field: {}", text(&s));
|
||||
let edit = s.get(id).unwrap().form.iter().find(|f| f.name.ends_with("Edit")).map(|f| f.name.clone()).expect("the Edit field");
|
||||
s.apply(id, Edit::SetFieldValue { name: edit, value: FieldValue::Text("typed".into()) }).unwrap();
|
||||
assert!(text(&s).contains("Edit: typed"), "a typed value in a one-line field: {}", text(&s));
|
||||
click(&mut s, "pickB");
|
||||
assert!(text(&s).contains("Pick: B"), "{}", text(&s));
|
||||
click(&mut s, "clearPick");
|
||||
assert!(text(&s).contains("Pick: A"), "a reset drop-down list: {}", text(&s));
|
||||
let pick = s.get(id).unwrap().form.iter().find(|f| f.name.ends_with("Pick")).map(|f| f.name.clone()).expect("the Pick field");
|
||||
s.apply(id, Edit::SetFieldValue { name: pick, value: FieldValue::Choice(vec!["B".into()]) }).unwrap();
|
||||
assert!(text(&s).contains("Pick: B"), "a picked value: {}", text(&s));
|
||||
click(&mut s, "pickB");
|
||||
click(&mut s, "clear");
|
||||
let after = text(&s);
|
||||
assert!(after.contains("Edit: start") && !after.contains("Shared"), "reset: {after}");
|
||||
assert!(after.contains("Pick: A"), "a reset drop-down list: {after}");
|
||||
assert!(after.contains("Stamp:") && !after.contains("Paid"), "a reset page-area field with no widget: {after}");
|
||||
}
|
||||
|
||||
/// A reset gives a hidden floating field its default in every row of a repeating subform, not
|
||||
/// only the first, and each row's text shows it.
|
||||
#[test]
|
||||
fn a_reset_clears_a_floating_field_in_every_row() {
|
||||
let xdp = r##"<?xml version="1.0" encoding="UTF-8"?>
|
||||
<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>
|
||||
<subform name="row" layout="tb"><occur min="1" max="-1"/>
|
||||
<field name="amount" id="floatAmount" presence="hidden" w="1in" h="0.3in"><ui><textEdit/></ui><value><text>none</text></value></field>
|
||||
<draw w="5in" h="0.4in"><value><exData contentType="text/html"><body xmlns="http://www.w3.org/1999/xhtml" xmlns:xfa="http://www.xfa.org/schema/xfa-data/1.0/"><p>Amount: <span xfa:embed="#floatAmount"/></p></body></exData></value></draw>
|
||||
</subform>
|
||||
<field name="clear" w="2in" h="0.3in"><ui><button/></ui>
|
||||
<event activity="click"><script contentType="application/x-javascript">xfa.host.resetData();</script></event></field>
|
||||
</subform>
|
||||
</template>
|
||||
<xfa:datasets xmlns:xfa="http://www.xfa.org/schema/xfa-data/1.0/"><xfa:data><form><row><amount>10</amount></row><row><amount>20</amount></row></form></xfa:data></xfa:datasets>
|
||||
</xdp:xdp>
|
||||
"##;
|
||||
let mut s = Session::new();
|
||||
let id = s.open("rows.pdf", None, Arc::new(pdfcraft_xfa::fixtures::shell(xdp)), None).expect("opens");
|
||||
let text = page_texts(&s, id).join(
|
||||
"
|
||||
",
|
||||
);
|
||||
assert!(text.contains("Amount: 10") && text.contains("Amount: 20"), "{text}");
|
||||
let o = s.run_javascript(id, "", Some("clear")).expect("clicks");
|
||||
assert_eq!(o.error, None, "{o:?}");
|
||||
let text = page_texts(&s, id).join(
|
||||
"
|
||||
",
|
||||
);
|
||||
assert_eq!(text.matches("Amount: none").count(), 2, "both rows reset: {text}");
|
||||
}
|
||||
|
||||
/// An XFA button's click script may show the attachments panel; a text field's exit script
|
||||
/// asking the same is noted on the console and ignored.
|
||||
#[test]
|
||||
|
||||
+194
-10
@@ -275,6 +275,9 @@ struct Runner<'a, 'b> {
|
||||
/// rebuilt when the structure changed).
|
||||
session: Option<XfaSession>,
|
||||
changes: Changes,
|
||||
/// A field embedded in rich text (a floating field) took a new value since the form was
|
||||
/// last laid out: the text that shows it is laid out again when the event ends.
|
||||
embedded_changed: bool,
|
||||
}
|
||||
|
||||
impl<'a, 'b> Runner<'a, 'b> {
|
||||
@@ -304,6 +307,7 @@ impl<'a, 'b> Runner<'a, 'b> {
|
||||
cached: None,
|
||||
session: None,
|
||||
changes: Changes::default(),
|
||||
embedded_changed: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -422,6 +426,9 @@ impl<'a, 'b> Runner<'a, 'b> {
|
||||
fn set_value(&mut self, som: &str, value: &str) -> bool {
|
||||
use pdfcraft_forms::FieldKind as K;
|
||||
let path = pdfcraft_xfa::data_path(self.tpl, som);
|
||||
// A floating field shows the value of its data node in the text that embeds it (XFA 3.3
|
||||
// pp. 221–222): a page area's, or one another field shares, as well.
|
||||
let embedded = pdfcraft_xfa::path_is_embedded(self.tpl, &path);
|
||||
let names = self.widgets_at(&path);
|
||||
// The data text: the widget at `som` says how its kind writes the value; without one,
|
||||
// the first widget bound to the node, else the value itself.
|
||||
@@ -471,6 +478,7 @@ impl<'a, 'b> Runner<'a, 'b> {
|
||||
}
|
||||
if changed {
|
||||
self.changes.values += 1;
|
||||
self.embedded_changed |= embedded;
|
||||
}
|
||||
changed
|
||||
}
|
||||
@@ -521,6 +529,7 @@ impl<'a, 'b> Runner<'a, 'b> {
|
||||
}
|
||||
self.relayouts += 1;
|
||||
self.flush()?;
|
||||
self.embedded_changed = false;
|
||||
let report = pdfcraft_xfa::rerender(self.doc, self.tpl).map_err(|e| e.to_string())?;
|
||||
self.console(report.warnings);
|
||||
crate::xfa_redraw(self.doc)?;
|
||||
@@ -541,13 +550,14 @@ impl<'a, 'b> Runner<'a, 'b> {
|
||||
} else {
|
||||
Some(by_som.iter().filter(|(som, _)| names.iter().any(|n| som_matches(som, n))).map(|(_, f)| f.clone()).collect())
|
||||
};
|
||||
if listed.as_ref().is_some_and(Vec::is_empty) {
|
||||
return Ok(());
|
||||
// Names no widget answers to may still name a floating field (below).
|
||||
let widgets = !listed.as_ref().is_some_and(Vec::is_empty);
|
||||
if widgets {
|
||||
pdfcraft_forms::reset(self.doc, listed.as_deref()).map_err(|e| e.to_string())?;
|
||||
}
|
||||
pdfcraft_forms::reset(self.doc, listed.as_deref()).map_err(|e| e.to_string())?;
|
||||
self.fields = None;
|
||||
let infos = self.fields().clone();
|
||||
for (som, name) in &by_som {
|
||||
for (som, name) in by_som.iter().filter(|_| widgets) {
|
||||
if listed.as_ref().is_some_and(|l| !l.contains(name)) {
|
||||
continue;
|
||||
}
|
||||
@@ -558,10 +568,28 @@ impl<'a, 'b> Runner<'a, 'b> {
|
||||
let path = pdfcraft_xfa::data_path(self.tpl, som);
|
||||
let text = data_text(info);
|
||||
if self.data.as_ref().and_then(|d| d.text_at(&path)).unwrap_or("") != text {
|
||||
self.embedded_changed |= pdfcraft_xfa::path_is_embedded(self.tpl, &path);
|
||||
self.data_op(pdfcraft_xfa::DataOp::Value { path, text });
|
||||
self.changes.values += 1;
|
||||
}
|
||||
}
|
||||
// A floating field without a widget (a hidden one, as forms place them) goes back to
|
||||
// its default too, and the text that embeds it shows that.
|
||||
for (som, default) in pdfcraft_xfa::embedded_fields(self.tpl) {
|
||||
if by_som.contains_key(&som) || (!names.is_empty() && !names.iter().any(|n| som_matches(&som, n))) {
|
||||
continue;
|
||||
}
|
||||
// Every row that holds it, not only the first.
|
||||
let names: Vec<String> = pdfcraft_xfa::data_path(self.tpl, &som).into_iter().map(|(name, _)| name).collect();
|
||||
let paths = self.data.as_ref().map(|d| d.paths_named(&names, pdfcraft_xfa::MAX_FORM_NODES)).unwrap_or_default();
|
||||
for path in paths {
|
||||
if self.data.as_ref().and_then(|d| d.text_at(&path)).unwrap_or("") != default {
|
||||
self.embedded_changed = true;
|
||||
self.data_op(pdfcraft_xfa::DataOp::Value { path, text: default.clone() });
|
||||
self.changes.values += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
self.invalidate();
|
||||
Ok(())
|
||||
}
|
||||
@@ -719,7 +747,7 @@ impl<'a, 'b> Runner<'a, 'b> {
|
||||
fn finish(mut self) -> Result<Changes, String> {
|
||||
#[cfg(test)]
|
||||
self.check_live();
|
||||
if self.relayouts_skipped {
|
||||
if self.relayouts_skipped || self.embedded_changed {
|
||||
self.relayouts = 0;
|
||||
self.relayouts_skipped = false;
|
||||
self.relayout()?;
|
||||
@@ -779,7 +807,9 @@ fn collect_fields(n: &FormNode, out: &mut Vec<(String, String, String, String)>,
|
||||
}
|
||||
}
|
||||
|
||||
/// Reflow a laid-out XFA form when an edited multiline field can grow. The datasets must
|
||||
/// Reflow a laid-out XFA form when an edited multiline field can grow, or an edited text field,
|
||||
/// choice list or check box is embedded in rich text (a floating field, whose value that text
|
||||
/// shows). The datasets must
|
||||
/// already hold the final values, including calculation results. Fixed-height fields keep
|
||||
/// their existing geometry; forms without scripts parse their template only when needed.
|
||||
/// `Some` means pages/widgets were rebuilt and the caller must fully refresh its snapshot.
|
||||
@@ -794,12 +824,14 @@ pub(crate) fn relayout_changed_text(
|
||||
let current = &*doc;
|
||||
let mut changed = before
|
||||
.iter()
|
||||
.filter(|f| f.kind == pdfcraft_forms::FieldKind::Text && f.has(pdfcraft_forms::flags::MULTILINE))
|
||||
.filter(|f| {
|
||||
use pdfcraft_forms::FieldKind as K;
|
||||
matches!(f.kind, K::Text | K::Combo | K::List | K::CheckBox)
|
||||
})
|
||||
.filter_map(|f| {
|
||||
let object = current.get(f.obj);
|
||||
let dict = object.as_dict()?;
|
||||
let value = dict.get(b"V").and_then(|v| current.resolve(v).as_string().map(|s| s.to_text())).unwrap_or_default();
|
||||
if f.value.first().map_or("", String::as_str) == value {
|
||||
if value_unchanged(current, f, dict.get(b"V")) {
|
||||
return None;
|
||||
}
|
||||
dict.get(pdfcraft_xfa::SOM_KEY).and_then(|s| current.resolve(s).as_string().map(|s| s.to_text()))
|
||||
@@ -812,7 +844,7 @@ pub(crate) fn relayout_changed_text(
|
||||
Some(tpl) => std::borrow::Cow::Borrowed(tpl),
|
||||
None => std::borrow::Cow::Owned(pdfcraft_xfa::template_of(current).map_err(|e| e.to_string())?),
|
||||
};
|
||||
let reflow = changed.any(|som| pdfcraft_xfa::field_grows_with_text(&template, &som));
|
||||
let reflow = changed.any(|som| pdfcraft_xfa::field_grows_with_text(&template, &som) || pdfcraft_xfa::field_is_embedded(&template, &som));
|
||||
drop(changed);
|
||||
if !reflow {
|
||||
return Ok(None);
|
||||
@@ -822,6 +854,60 @@ pub(crate) fn relayout_changed_text(
|
||||
Ok(Some(report.warnings))
|
||||
}
|
||||
|
||||
/// Whether field `f` still holds the value it had (`f.value`), its `/V` being `v`: a list box's
|
||||
/// picks are an array, a check box's state a name (Off for none, as the field's value has
|
||||
/// none), and of a text field only the first value counts. Compared in place, so an edit costs
|
||||
/// no copy of every field's value.
|
||||
fn value_unchanged(doc: &pdfcraft_cos::Document, f: &pdfcraft_forms::Field, v: Option<&pdfcraft_cos::Object>) -> bool {
|
||||
use pdfcraft_cos::Object as O;
|
||||
let text = f.kind == pdfcraft_forms::FieldKind::Text;
|
||||
let first = f.value.first().map_or("", String::as_str);
|
||||
// The value is the one string `is` accepts.
|
||||
let one = |is: &dyn Fn(&str) -> bool| if text { is(first) } else { matches!(f.value.as_slice(), [old] if is(old)) };
|
||||
let none = if text { first.is_empty() } else { f.value.is_empty() };
|
||||
let held;
|
||||
let v = match v {
|
||||
Some(r @ O::Ref(_)) => {
|
||||
held = doc.resolve(r);
|
||||
Some(&*held)
|
||||
}
|
||||
v => v,
|
||||
};
|
||||
match v {
|
||||
Some(O::Array(items)) => {
|
||||
let mut old = f.value.iter();
|
||||
for item in items {
|
||||
let held_item;
|
||||
let item = match item {
|
||||
O::Ref(_) => {
|
||||
held_item = doc.resolve(item);
|
||||
&*held_item
|
||||
}
|
||||
i => i,
|
||||
};
|
||||
let Some(s) = item.as_string() else { continue };
|
||||
if text {
|
||||
return s.text_eq(first);
|
||||
}
|
||||
if !old.next().is_some_and(|o| s.text_eq(o)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if text { none } else { old.next().is_none() }
|
||||
}
|
||||
Some(O::Name(n)) if n.as_slice() == b"Off" => none,
|
||||
Some(O::Name(n)) => {
|
||||
let n = String::from_utf8_lossy(n);
|
||||
one(&|old| old == n)
|
||||
}
|
||||
Some(v) => match v.as_string() {
|
||||
Some(s) => one(&|old| s.text_eq(old)),
|
||||
None => none,
|
||||
},
|
||||
None => none,
|
||||
}
|
||||
}
|
||||
|
||||
/// On open: initialize scripts, then calculations. Returns what they changed.
|
||||
pub(crate) fn on_open(doc: &mut pdfcraft_cos::Document, tpl: &Template, run: &mut XfaRun) -> Result<Changes, String> {
|
||||
let mut r = Runner::new(doc, tpl, run, OPEN_BUDGET_MS);
|
||||
@@ -954,4 +1040,102 @@ mod tests {
|
||||
Some((2, "form[0].table[0]".into(), "row".into(), 2))
|
||||
);
|
||||
}
|
||||
|
||||
fn field(obj: pdfcraft_cos::ObjRef, kind: pdfcraft_forms::FieldKind, value: &[&str]) -> pdfcraft_forms::Field {
|
||||
pdfcraft_forms::Field {
|
||||
name: "f".into(),
|
||||
obj,
|
||||
kind,
|
||||
value: value.iter().map(|v| (*v).to_owned()).collect(),
|
||||
default: Vec::new(),
|
||||
flags: 0,
|
||||
max_len: None,
|
||||
options: Vec::new(),
|
||||
da: String::new(),
|
||||
quadding: 0,
|
||||
tooltip: None,
|
||||
widgets: Vec::new(),
|
||||
actions: pdfcraft_forms::af::Actions::default(),
|
||||
button: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// A field dictionary whose `/V` is `v`, with a SOM path.
|
||||
fn field_dict(doc: &mut pdfcraft_cos::Document, v: Option<pdfcraft_cos::Object>) -> pdfcraft_cos::ObjRef {
|
||||
let mut d = pdfcraft_cos::Dict::new();
|
||||
if let Some(v) = v {
|
||||
d.set(b"V".to_vec(), v);
|
||||
}
|
||||
d.set(pdfcraft_xfa::SOM_KEY.to_vec(), pdfcraft_cos::Object::String(pdfcraft_cos::PdfString::text("form[0].f[0]")));
|
||||
doc.add(d)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn changed_values_are_found_in_place() {
|
||||
use pdfcraft_cos::{Object as O, PdfString};
|
||||
use pdfcraft_forms::FieldKind as K;
|
||||
let s = |t: &str| O::String(PdfString::text(t));
|
||||
let mut doc = pdfcraft_cos::Document::new_empty();
|
||||
let same = |doc: &mut pdfcraft_cos::Document, kind, old: &[&str], v: Option<O>| {
|
||||
let r = field_dict(doc, v);
|
||||
let dict = doc.get(r);
|
||||
value_unchanged(doc, &field(r, kind, old), dict.as_dict().and_then(|d| d.get(b"V")))
|
||||
};
|
||||
// Text: the first value only, an absent or non-text value being empty.
|
||||
assert!(same(&mut doc, K::Text, &["Café"], Some(s("Café"))));
|
||||
assert!(!same(&mut doc, K::Text, &["Café"], Some(s("Cafe"))));
|
||||
assert!(same(&mut doc, K::Text, &[], None));
|
||||
assert!(same(&mut doc, K::Text, &[], Some(s(""))));
|
||||
assert!(!same(&mut doc, K::Text, &["a"], None));
|
||||
assert!(same(&mut doc, K::Text, &["a", "b"], Some(O::Array(vec![s("a"), s("c")]))));
|
||||
// A value given by reference is followed.
|
||||
let inner = doc.add(s("日本"));
|
||||
assert!(same(&mut doc, K::Text, &["日本"], Some(O::Ref(inner))));
|
||||
assert!(!same(&mut doc, K::Combo, &["日"], Some(O::Ref(inner))));
|
||||
// Combo box: one value.
|
||||
assert!(same(&mut doc, K::Combo, &["Two"], Some(s("Two"))));
|
||||
assert!(!same(&mut doc, K::Combo, &["Two"], Some(s("Three"))));
|
||||
assert!(!same(&mut doc, K::Combo, &[], Some(s("Two"))));
|
||||
assert!(!same(&mut doc, K::Combo, &["Two"], None));
|
||||
// List box: every pick, in order, by count; non-strings in the array are skipped.
|
||||
let picks = |v: &[&str]| O::Array(v.iter().map(|t| s(t)).collect());
|
||||
assert!(same(&mut doc, K::List, &["a", "b"], Some(picks(&["a", "b"]))));
|
||||
assert!(!same(&mut doc, K::List, &["a", "b"], Some(picks(&["b", "a"]))));
|
||||
assert!(!same(&mut doc, K::List, &["a", "b"], Some(picks(&["a"]))));
|
||||
assert!(!same(&mut doc, K::List, &["a"], Some(picks(&["a", "b"]))));
|
||||
assert!(!same(&mut doc, K::List, &["a", "b"], Some(picks(&["a", "c"]))));
|
||||
assert!(same(&mut doc, K::List, &[], Some(picks(&[]))));
|
||||
let item = doc.add(s("b"));
|
||||
assert!(same(&mut doc, K::List, &["a", "b"], Some(O::Array(vec![s("a"), O::Int(3), O::Ref(item)]))));
|
||||
// Check box: a state name, Off for none.
|
||||
assert!(same(&mut doc, K::CheckBox, &["Yes"], Some(O::name("Yes"))));
|
||||
assert!(!same(&mut doc, K::CheckBox, &["Yes"], Some(O::name("Off"))));
|
||||
assert!(same(&mut doc, K::CheckBox, &[], Some(O::name("Off"))));
|
||||
assert!(!same(&mut doc, K::CheckBox, &[], Some(O::name("Yes"))));
|
||||
assert!(!same(&mut doc, K::CheckBox, &["Yes"], Some(O::name("On"))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unchanged_values_return_before_the_template_is_read() {
|
||||
use pdfcraft_cos::{Object as O, PdfString};
|
||||
use pdfcraft_forms::FieldKind as K;
|
||||
// Laid out, but with no XFA packets: reading the template fails.
|
||||
let mut doc = pdfcraft_cos::Document::new_empty();
|
||||
let mut acro = pdfcraft_cos::Dict::new();
|
||||
acro.set(pdfcraft_xfa::LAYOUT_KEY.to_vec(), pdfcraft_cos::Dict::new());
|
||||
let acro = doc.add(acro);
|
||||
let root = doc.root().unwrap_or_else(|| panic!("no catalog"));
|
||||
let mut catalog = doc.get(root).as_dict().cloned().unwrap_or_default();
|
||||
catalog.set(b"AcroForm".to_vec(), O::Ref(acro));
|
||||
doc.set(root, catalog);
|
||||
assert!(pdfcraft_xfa::existing_layout(&doc).is_some());
|
||||
let text = field_dict(&mut doc, Some(O::String(PdfString::text("same"))));
|
||||
let list = field_dict(&mut doc, Some(O::Array(vec![O::String(PdfString::text("a")), O::String(PdfString::text("b"))])));
|
||||
let check = field_dict(&mut doc, Some(O::name("Yes")));
|
||||
let before = [field(text, K::Text, &["same"]), field(list, K::List, &["a", "b"]), field(check, K::CheckBox, &["Yes"])];
|
||||
assert_eq!(relayout_changed_text(&mut doc, None, &before), Ok(None));
|
||||
// A changed pick reaches the template, which this document doesn't have.
|
||||
let before = [field(text, K::Text, &["same"]), field(list, K::List, &["b", "a"]), field(check, K::CheckBox, &["Yes"])];
|
||||
assert!(relayout_changed_text(&mut doc, None, &before).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -60,20 +60,23 @@ pub(crate) fn emphasis(text: &str, bold: bool, italic: bool, open: bool, close:
|
||||
pub(crate) fn paragraph(runs: &[(&str, bool, bool)]) -> String {
|
||||
let mut merged: Vec<(String, bool, bool)> = Vec::new();
|
||||
for &(text, bold, italic) in runs {
|
||||
let text = md_text(text);
|
||||
if text.is_empty() {
|
||||
continue;
|
||||
}
|
||||
match merged.last_mut() {
|
||||
Some(last) if last.1 == bold && last.2 == italic => last.0.push_str(text),
|
||||
_ => merged.push((text.to_string(), bold, italic)),
|
||||
Some(last) if last.1 == bold && last.2 == italic => last.0.push_str(&text),
|
||||
_ => merged.push((text, bold, italic)),
|
||||
}
|
||||
}
|
||||
let texts: Vec<String> = merged.iter().map(|(text, ..)| md_text(text)).collect();
|
||||
let mut out = String::new();
|
||||
for (k, ((_, bold, italic), text)) in merged.iter().zip(&texts).enumerate() {
|
||||
for (k, (text, bold, italic)) in merged.iter().enumerate() {
|
||||
let core = text.trim();
|
||||
let open = marks(core.chars().next(), out.chars().last());
|
||||
// Markers of a styled neighbour right next to these would join them into one run.
|
||||
let close = match (merged.get(k.saturating_add(1)), texts.get(k.saturating_add(1))) {
|
||||
(Some((_, b, i)), Some(next)) if (*b || *i) && !next.starts_with(char::is_whitespace) => false,
|
||||
(_, next) => marks(core.chars().last(), next.and_then(|n| n.chars().next())),
|
||||
let close = match merged.get(k.saturating_add(1)) {
|
||||
Some((next, b, i)) if (*b || *i) && !next.starts_with(char::is_whitespace) => false,
|
||||
next => marks(core.chars().last(), next.and_then(|(n, ..)| n.chars().next())),
|
||||
};
|
||||
out.push_str(&emphasis(text, *bold, *italic, open, close));
|
||||
}
|
||||
@@ -149,3 +152,27 @@ pub fn markdown(pages: &[Page]) -> String {
|
||||
s.push('\n');
|
||||
s
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::paragraph;
|
||||
|
||||
#[test]
|
||||
fn empty_or_control_run_does_not_split_styled_runs() {
|
||||
assert_eq!(paragraph(&[("hello", true, false), ("", false, false), ("world", true, false)]), "**helloworld**");
|
||||
assert_eq!(paragraph(&[("hello", true, false), ("\u{1}", false, false), ("world", true, false)]), "**helloworld**");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_styled_run_does_not_affect_neighbor_emphasis() {
|
||||
assert_eq!(paragraph(&[("x", true, false), ("", false, true)]), "**x**");
|
||||
assert_eq!(paragraph(&[("foo", false, false), (".", true, false), ("", true, true), ("bar", false, false)]), "foo<strong>.</strong>bar");
|
||||
// Empty/control runs between differently styled runs still look ahead to the next non-empty run.
|
||||
assert_eq!(paragraph(&[("bold", true, false), ("", false, false), ("italic", false, true)]), "<strong>bold</strong>*italic*");
|
||||
assert_eq!(paragraph(&[("bold", true, false), ("\u{1}", false, false), (" italic", false, true)]), "**bold** *italic*");
|
||||
// Leading empty/control runs do not affect the opening delimiter.
|
||||
assert_eq!(paragraph(&[("", false, true), ("\u{1}", true, false), ("lead", true, false)]), "**lead**");
|
||||
// All-empty/control paragraphs produce empty output.
|
||||
assert_eq!(paragraph(&[("", true, false), ("\u{1}", false, true), ("\u{7f}", false, false)]), "");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -110,6 +110,125 @@ mod tests {
|
||||
data
|
||||
}
|
||||
|
||||
/// The JBIG2 file header's ID string (ISO 14492 D.4.1).
|
||||
const FILE_HEADER_ID: [u8; 8] = [0x97, 0x4A, 0x42, 0x32, 0x0D, 0x0A, 0x1A, 0x0A];
|
||||
|
||||
/// `embedded`, segments as [`encode_jbig2_generic`] writes them (11-byte headers: no references,
|
||||
/// a one-byte page association), behind a file header with `flags` and the page count `pages`,
|
||||
/// in the organization `flags` declares (D.4.2, bit 0): 1 sequential, each segment's header
|
||||
/// before its data (D.1); 0 random access, every header first, the last an end of file segment
|
||||
/// numbered 2, which tells where they end, then every segment's data in the same order (D.2).
|
||||
fn with_file_header(embedded: &[u8], flags: u8, pages: Option<u32>) -> Vec<u8> {
|
||||
let mut data = FILE_HEADER_ID.to_vec();
|
||||
data.push(flags);
|
||||
data.extend(pages.map(u32::to_be_bytes).into_iter().flatten());
|
||||
if flags & 0x01 != 0 {
|
||||
data.extend_from_slice(embedded);
|
||||
return data;
|
||||
}
|
||||
let (mut headers, mut bodies, mut rest) = (Vec::new(), Vec::new(), embedded);
|
||||
while !rest.is_empty() {
|
||||
let (header, after) = rest.split_at(11);
|
||||
assert_eq!(header[5], 0, "no references");
|
||||
let (body, after) = after.split_at(u32::from_be_bytes(header[7..11].try_into().unwrap()) as usize);
|
||||
headers.extend_from_slice(header);
|
||||
bodies.extend_from_slice(body);
|
||||
rest = after;
|
||||
}
|
||||
headers.extend_from_slice(&[0, 0, 0, 2, 51, 0, 1, 0, 0, 0, 0]);
|
||||
data.extend(headers);
|
||||
data.extend(bodies);
|
||||
data
|
||||
}
|
||||
|
||||
/// A stream that starts with a JBIG2 file header (ISO 14492 D.4), which some producers write
|
||||
/// into `JBIG2Decode` data although ISO 32000-1 7.4.7 has the embedded organization there,
|
||||
/// decodes past it as Acrobat and PDFBox draw it (hayro-jbig2 patch 17), in either organization
|
||||
/// the header declares, with the page count and without it. "Bit 0: File organisation type. If
|
||||
/// this bit is 0, the file uses the random-access organisation. If this bit is 1, the file uses
|
||||
/// the sequential organisation." (D.4.2) A header with its reserved flag bits set is an error,
|
||||
/// not a panic.
|
||||
#[test]
|
||||
fn a_stream_with_a_jbig2_file_header_decodes_past_it() {
|
||||
let (w, h) = (203u32, 41u32);
|
||||
let bits = noise(w, h);
|
||||
let max = bits.len();
|
||||
let embedded = encode_jbig2_generic(&bits, w, h).unwrap();
|
||||
let decode = |flags: u8, pages: Option<u32>| decode_jbig2(&with_file_header(&embedded, flags, pages), None, w, h, max);
|
||||
// Sequential organization (bit 0 is 1), one page.
|
||||
assert_eq!(decode(0x01, Some(1)).unwrap(), bits, "sequential, page count given");
|
||||
// Sequential, number of pages unknown (bit 1 is 1): no count follows (D.4.3).
|
||||
assert_eq!(decode(0x03, None).unwrap(), bits, "sequential, page count unknown");
|
||||
// Random-access organization (bit 0 is 0): the segment headers, then their data.
|
||||
assert_ne!(with_file_header(&embedded, 0x00, Some(1))[13..], embedded[..], "laid out otherwise");
|
||||
assert_eq!(decode(0x00, Some(1)).unwrap(), bits, "random access, page count given");
|
||||
assert_eq!(decode(0x02, None).unwrap(), bits, "random access, page count unknown");
|
||||
assert!(decode(0x11, Some(1)).is_err(), "reserved bits");
|
||||
}
|
||||
|
||||
/// A file header cut short, or the segments after it, is an error and not a panic: the ID string
|
||||
/// alone or in part, a header whose flags promise a page count with fewer than its four bytes,
|
||||
/// a header with no segments after it, and segments cut anywhere in either organization. No
|
||||
/// prefix of a whole stream decodes to its samples.
|
||||
#[test]
|
||||
fn a_truncated_jbig2_file_header_is_an_error() {
|
||||
let (w, h) = (24u32, 8u32);
|
||||
let bits = noise(w, h);
|
||||
let max = bits.len();
|
||||
let embedded = encode_jbig2_generic(&bits, w, h).unwrap();
|
||||
let decode = |data: &[u8]| decode_jbig2(data, None, w, h, max);
|
||||
assert!(decode(&FILE_HEADER_ID[..5]).is_err(), "part of the ID string");
|
||||
assert!(decode(&FILE_HEADER_ID).is_err(), "the ID string, no flags");
|
||||
for count in 0..4 {
|
||||
let mut data = FILE_HEADER_ID.to_vec();
|
||||
data.push(0x01);
|
||||
data.extend_from_slice(&1u32.to_be_bytes()[..count]);
|
||||
assert!(decode(&data).is_err(), "{count} bytes of the page count");
|
||||
}
|
||||
for (flags, pages) in [(0x01, Some(1)), (0x03, None), (0x00, Some(1)), (0x02, None)] {
|
||||
let whole = with_file_header(&embedded, flags, pages);
|
||||
let header = 9 + if pages.is_some() { 4 } else { 0 };
|
||||
assert!(decode(&whole[..header]).is_err(), "flags {flags:#04x}: the header alone");
|
||||
assert!(decode(&whole[..whole.len() - 1]).is_err(), "flags {flags:#04x}: the last byte cut");
|
||||
for end in 0..whole.len() {
|
||||
assert_ne!(decode(&whole[..end]).ok(), Some(bits.clone()), "flags {flags:#04x}: {end} bytes");
|
||||
}
|
||||
assert_eq!(decode(&whole).unwrap(), bits, "flags {flags:#04x}: whole");
|
||||
}
|
||||
}
|
||||
|
||||
/// The segments after a file header count toward hayro-jbig2's cap on the segments of a stream
|
||||
/// together with its `/JBIG2Globals`, in either organization (patches 8 and 17): globals of
|
||||
/// extension segments, which decode to nothing, fill the cap to the image's segments, and one
|
||||
/// more is refused.
|
||||
#[test]
|
||||
fn segments_after_a_jbig2_file_header_count_with_the_globals() {
|
||||
/// hayro-jbig2's `MAX_SEGMENTS`, the most segments of a stream with its globals.
|
||||
const MAX_SEGMENTS: u32 = 1 << 20;
|
||||
let (w, h) = (24u32, 8u32);
|
||||
let bits = noise(w, h);
|
||||
let max = bits.len();
|
||||
let embedded = encode_jbig2_generic(&bits, w, h).unwrap();
|
||||
// Numbered past the image's segments (0 to 2), of no page, with no data.
|
||||
let globals = |count: u32| -> Vec<u8> {
|
||||
(16..16 + count)
|
||||
.flat_map(|number| {
|
||||
let mut segment = number.to_be_bytes().to_vec();
|
||||
segment.extend_from_slice(&[62, 0, 0, 0, 0, 0, 0]);
|
||||
segment
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
// The image's page information and region, and in random access its end of file segment.
|
||||
for (flags, organization, image) in [(0x01, "sequential", 2), (0x00, "random access", 3)] {
|
||||
let data = with_file_header(&embedded, flags, Some(1));
|
||||
let (at_cap, past_cap) = (globals(MAX_SEGMENTS - image), globals(MAX_SEGMENTS - image + 1));
|
||||
assert_eq!(decode_jbig2(&data, Some(&at_cap), w, h, max).unwrap(), bits, "{organization}: at the cap");
|
||||
let refused = decode_jbig2(&data, Some(&past_cap), w, h, max).unwrap_err();
|
||||
assert!(refused.to_string().contains("too many segments"), "{organization}: {refused}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Either coding decodes to its samples, black as 0, the bits that pad each row 0: a generic
|
||||
/// region of noise, and symbols for letters repeated across the page. With no rows asked for,
|
||||
/// nothing is decoded.
|
||||
|
||||
+123
-10
@@ -356,6 +356,94 @@ const MAX_CMAP_RANGES: usize = 1 << 16;
|
||||
/// Largest decoded Encoding or ToUnicode CMap stream read; real CMaps stay well under it, and a larger
|
||||
/// one is not decoded at all.
|
||||
const MAX_CMAP_BYTES: usize = 16 << 20;
|
||||
/// Most Type 3 glyph descriptions read for their `d1` box. A simple font shows at most 256 codes.
|
||||
const MAX_TYPE3_GLYPHS: usize = 256;
|
||||
/// Largest decoded Type 3 glyph description read for its `d1` box; a larger one is skipped.
|
||||
const MAX_TYPE3_GLYPH_BYTES: usize = 64 << 10;
|
||||
/// Decoded bytes all of one font's glyph descriptions may take together.
|
||||
const MAX_TYPE3_FONT_BYTES: usize = 4 << 20;
|
||||
/// Farthest a Type 3 glyph box reaches from the baseline, in text space per unit of font size. A
|
||||
/// bitmap font drawn in page units at `0.01 Tf` is a few thousand; past this a box is garbage, and
|
||||
/// clamping it keeps the run boxes built from it finite.
|
||||
const MAX_TYPE3_EXTENT: f64 = 1e6;
|
||||
|
||||
/// The union of the boxes a Type 3 font's glyph descriptions declare with `d1` (ISO 32000-2
|
||||
/// §9.6.4, Table 111), in glyph space, and whether every description chosen was read; `None` when
|
||||
/// no glyph declares one (`d0` glyphs don't). The descriptions the encoding's `/Differences`
|
||||
/// names are chosen, since it "shall specify the complete character encoding" (Table 110); only a
|
||||
/// font without one has its first descriptions chosen. Reads at most [`MAX_TYPE3_GLYPHS`]
|
||||
/// descriptions within [`MAX_TYPE3_FONT_BYTES`].
|
||||
fn type3_glyph_box(doc: &Document, font: &Dict) -> Option<([f64; 4], bool)> {
|
||||
let procs = dict(doc, font.get(b"CharProcs"))?;
|
||||
let mut names: Vec<&[u8]> = Vec::new();
|
||||
// Whether every glyph that can be drawn is read; if not, the union may be short of them.
|
||||
let mut complete = true;
|
||||
let encoding = dict(doc, font.get(b"Encoding"));
|
||||
// A base encoding reaches glyphs `/Differences` doesn't name, which Type 3 doesn't provide for (its
|
||||
// `/Differences` "shall specify the complete character encoding", Table 110): those boxes go unread.
|
||||
if encoding.as_ref().is_some_and(|e| e.contains(b"BaseEncoding")) {
|
||||
complete = false;
|
||||
}
|
||||
let diffs = encoding.as_ref().and_then(|e| e.get(b"Differences")).map(|d| doc.resolve(d));
|
||||
for name in diffs.as_deref().and_then(Object::as_array).into_iter().flatten().filter_map(Object::as_name) {
|
||||
if procs.get(name).is_none() || names.contains(&name) {
|
||||
continue;
|
||||
}
|
||||
if names.len() >= MAX_TYPE3_GLYPHS {
|
||||
complete = false;
|
||||
break;
|
||||
}
|
||||
names.push(name);
|
||||
}
|
||||
let chosen: Vec<&Object> = if names.is_empty() {
|
||||
complete = procs.len() <= MAX_TYPE3_GLYPHS;
|
||||
procs.iter().take(MAX_TYPE3_GLYPHS).map(|(_, proc)| proc).collect()
|
||||
} else {
|
||||
names.iter().filter_map(|n| procs.get(n)).collect()
|
||||
};
|
||||
let mut budget = DecodeBudget::new(MAX_TYPE3_FONT_BYTES, 0);
|
||||
let mut union: Option<[f64; 4]> = None;
|
||||
for proc in chosen {
|
||||
let Object::Stream(s) = &*doc.resolve(proc) else { continue };
|
||||
let Ok(data) = budget.decode_within(&doc.with_direct_parms(s), MAX_TYPE3_GLYPH_BYTES) else {
|
||||
if budget.remaining() == 0 {
|
||||
// The rest go unread too.
|
||||
complete = false;
|
||||
break;
|
||||
}
|
||||
continue;
|
||||
};
|
||||
if let Some([llx, lly, urx, ury]) = d1_box(&data) {
|
||||
let r = [llx.min(urx), lly.min(ury), llx.max(urx), lly.max(ury)];
|
||||
union = Some(union.map_or(r, |u| [u[0].min(r[0]), u[1].min(r[1]), u[2].max(r[2]), u[3].max(r[3])]));
|
||||
}
|
||||
}
|
||||
union.map(|u| (u, complete))
|
||||
}
|
||||
|
||||
/// The glyph box `llx lly urx ury` of a glyph description that begins with `wx wy llx lly urx ury
|
||||
/// d1`; `None` for `d0` or anything else first.
|
||||
fn d1_box(data: &[u8]) -> Option<[f64; 4]> {
|
||||
let mut lexer = pdfcraft_cos::Lexer::new(data, 0);
|
||||
let mut operands = [0.0; 6];
|
||||
for slot in &mut operands {
|
||||
lexer.skip_ws();
|
||||
*slot = std::str::from_utf8(lexer.token()).ok()?.parse::<f64>().ok().filter(|v| v.is_finite())?;
|
||||
}
|
||||
lexer.skip_ws();
|
||||
(lexer.token() == b"d1").then(|| [operands[2], operands[3], operands[4], operands[5]])
|
||||
}
|
||||
|
||||
/// The lowest and highest text-space y of the glyph-space box `r` under a font matrix whose
|
||||
/// y column is `b`, `d`, `f` (§9.2.4): a flipped matrix (`d < 0`) turns the box over. `None`
|
||||
/// when the box has no height in text space or the numbers overflow; clamped to
|
||||
/// [`MAX_TYPE3_EXTENT`].
|
||||
fn text_y_extent(r: [f64; 4], b: f64, d: f64, f: f64) -> Option<(f64, f64)> {
|
||||
let ys = [(r[0], r[1]), (r[2], r[1]), (r[0], r[3]), (r[2], r[3])].map(|(x, y)| b * x + d * y + f);
|
||||
let lo = ys.iter().copied().fold(f64::INFINITY, f64::min);
|
||||
let hi = ys.iter().copied().fold(f64::NEG_INFINITY, f64::max);
|
||||
(lo.is_finite() && hi.is_finite() && hi > lo).then_some((lo.max(-MAX_TYPE3_EXTENT), hi.min(MAX_TYPE3_EXTENT)))
|
||||
}
|
||||
|
||||
/// Code → Unicode of a font. Explicit mappings and sequential ranges are kept as declared, so a range
|
||||
/// costs one record however many codes it covers; where two overlap, the one declared later wins.
|
||||
@@ -754,6 +842,8 @@ impl Metrics {
|
||||
m.std14 = None;
|
||||
let subtype = font.name(b"Subtype").unwrap_or(b"Type1").to_vec();
|
||||
let descriptor;
|
||||
// A Type 3 font measured from its glyph descriptions' `d1` boxes or its `/FontBBox` (see below).
|
||||
let mut type3_measured = false;
|
||||
if subtype == b"Type0" {
|
||||
m.composite = true;
|
||||
m.default = 1000.0;
|
||||
@@ -814,13 +904,28 @@ impl Metrics {
|
||||
descriptor = dict(doc, font.get(b"FontDescriptor"));
|
||||
m.default = descriptor.as_ref().and_then(|d| d.get(b"MissingWidth")).and_then(|w| doc.resolve(w).as_f64()).unwrap_or(0.0);
|
||||
if subtype == b"Type3" {
|
||||
let fm = nums(doc, font.get(b"FontMatrix"));
|
||||
if fm.len() == 6 {
|
||||
m.scale = fm[0];
|
||||
let bbox = nums(doc, font.get(b"FontBBox"));
|
||||
if bbox.len() == 4 && fm[3] != 0.0 {
|
||||
m.ascent = (bbox[3] * fm[3]).max(0.5);
|
||||
m.descent = (bbox[1] * fm[3]).min(-0.1);
|
||||
if let [a, b, _, d, _, f] = nums(doc, font.get(b"FontMatrix"))[..] {
|
||||
m.scale = a;
|
||||
// The glyphs' own boxes first: a bitmap font's `/FontBBox` is often all zero
|
||||
// or one unit high, while each `d1` declares the box its glyph fills.
|
||||
// Each `d1` box "shall be correct" (Table 111), so their union is used as
|
||||
// declared, only widened to reach the baseline: a font of small glyphs gets a
|
||||
// small box. A `/FontBBox` is often one unit high, so it keeps the 0.5 / 0.1 em
|
||||
// minimum.
|
||||
// A union cut short by a limit may miss glyphs that are drawn, so a nonzero
|
||||
// `/FontBBox` comes first then; all zero, the partial union is still better
|
||||
// than no box. A box with no height in text space gives way to the next.
|
||||
let glyphs = type3_glyph_box(doc, font);
|
||||
// All zero: no assumption about glyph sizes (Table 110).
|
||||
let bbox = <[f64; 4]>::try_from(nums(doc, font.get(b"FontBBox"))).ok().filter(|r| r.iter().any(|&v| v != 0.0));
|
||||
let union = |complete: bool| glyphs.filter(|g| g.1 == complete).map(|(r, _)| (r, 0.0, 0.0));
|
||||
let candidates = [union(true), bbox.map(|r| (r, 0.5, -0.1)), union(false)];
|
||||
if let Some(((lo, hi), min_ascent, max_descent)) =
|
||||
candidates.into_iter().flatten().find_map(|(r, up, down)| text_y_extent(r, b, d, f).map(|e| (e, up, down)))
|
||||
{
|
||||
m.ascent = hi.max(min_ascent);
|
||||
m.descent = lo.min(max_descent);
|
||||
type3_measured = true;
|
||||
}
|
||||
}
|
||||
} else if m.widths.is_empty() {
|
||||
@@ -840,11 +945,15 @@ impl Metrics {
|
||||
let ascent = d.get(b"Ascent").and_then(|v| doc.resolve(v).as_f64());
|
||||
let descent = d.get(b"Descent").and_then(|v| doc.resolve(v).as_f64());
|
||||
// Fonts often claim 0; never shrink the glyph box below a sensible minimum.
|
||||
if ascent.is_some() || subtype != b"Type3" {
|
||||
// A Type 3 font measured from its glyphs' `d1` boxes or its `/FontBBox` keeps those:
|
||||
// they are in glyph space and go through its font matrix, while a descriptor's
|
||||
// /Ascent and /Descent are optional for Type 3 (Table 120) and read here as 1000-unit
|
||||
// values, whatever the matrix.
|
||||
if (ascent.is_some() && !type3_measured) || subtype != b"Type3" {
|
||||
let a = ascent.unwrap_or(0.0) / 1000.0;
|
||||
m.ascent = if a > 0.3 { a.min(1.5) } else { 0.9 };
|
||||
}
|
||||
if descent.is_some() || subtype != b"Type3" {
|
||||
if (descent.is_some() && !type3_measured) || subtype != b"Type3" {
|
||||
let de = descent.unwrap_or(0.0) / 1000.0;
|
||||
m.descent = if de < -0.05 { de.max(-0.6) } else { -0.25 };
|
||||
}
|
||||
@@ -951,7 +1060,11 @@ impl Metrics {
|
||||
|| (self.outlined_cids.is_empty() && self.explicit_default);
|
||||
}
|
||||
match code.checked_sub(self.first).and_then(|i| self.widths.get(i as usize)) {
|
||||
Some(w) => *w > 0.0 || code == 32,
|
||||
// A full font keeps its space whatever `/Widths` says; a subset that gives its space no width has no
|
||||
// space glyph (pdfTeX writes 0 for the codes it never uses), and a typed space drawn as code 32 would
|
||||
// glue the words together (#6131): the edit sets it as a positioning gap instead. Only when code 32
|
||||
// is a space: another glyph a subset puts there keeps its code.
|
||||
Some(w) => *w > 0.0 || (code == 32 && !(self.subset && self.text_of(code).is_some_and(|t| t.chars().all(char::is_whitespace)))),
|
||||
None => self.widths.is_empty() && !self.subset,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -265,6 +265,228 @@ fn type3_descriptor_names_the_font_without_changing_its_metrics() {
|
||||
assert_eq!(Metrics::from_dict(&doc, &f).base_font, "ExplicitName", "an explicit BaseFont takes precedence");
|
||||
}
|
||||
|
||||
/// A Type 3 font with `matrix`, `bbox` and one glyph description per entry of `procs`.
|
||||
fn type3(doc: &mut Document, matrix: [f64; 6], bbox: [i64; 4], procs: &[&str]) -> Dict {
|
||||
let mut charprocs = Dict::new();
|
||||
for (i, proc) in procs.iter().enumerate() {
|
||||
let glyph = doc.add(Object::Stream(Stream::flate(Dict::new(), proc.as_bytes())));
|
||||
charprocs.set(format!("g{i}").into_bytes(), Object::Ref(glyph));
|
||||
}
|
||||
font(
|
||||
doc,
|
||||
vec![
|
||||
("Subtype", Object::name("Type3")),
|
||||
("FontMatrix", Object::Array(matrix.iter().map(|&v| Object::Real(v)).collect())),
|
||||
("FontBBox", Object::Array(bbox.iter().map(|&v| Object::Int(v)).collect())),
|
||||
("CharProcs", Object::Dict(charprocs)),
|
||||
],
|
||||
)
|
||||
}
|
||||
|
||||
/// ISO 32000-2 §9.6.4: a bitmap font whose `/FontBBox` is all zero (no assumption about glyph
|
||||
/// sizes) is as high as the boxes its glyphs declare with `d1`, not a fixed 0.6 of the size.
|
||||
#[test]
|
||||
fn a_type3_font_is_as_high_as_its_d1_glyph_boxes() {
|
||||
let mut doc = Document::new_empty();
|
||||
let unit = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0];
|
||||
let f = type3(&mut doc, unit, [0, 0, 0, 0], &["100 0 0 0 100 100 d1\nq 100 0 0 100 0 0 cm BI /W 1 /H 1 /IM true ID \x00 EI Q"]);
|
||||
let m = Metrics::from_dict(&doc, &f);
|
||||
assert_eq!((m.ascent, m.descent), (100.0, 0.0));
|
||||
// Shown at `0.12 Tf`, the glyph is 12 points high.
|
||||
assert!((m.ascent * 0.12 - 12.0).abs() < 1e-9);
|
||||
|
||||
// The union of every glyph's box, leading comments and white space allowed; `d0` glyphs
|
||||
// declare none, and a non-numeric operand isn't a box.
|
||||
let f = type3(&mut doc, unit, [0, 0, 0, 0], &["% c\n 50 0 0 -20 40 60 d1", "60 0 d0", "60 0 0 -30 40 x d1", "60 0 0 0 40 80 d1"]);
|
||||
let m = Metrics::from_dict(&doc, &f);
|
||||
assert_eq!((m.ascent, m.descent), (80.0, -20.0));
|
||||
|
||||
// A wrong but non-zero `/FontBBox` (one unit high) gives way to the glyphs.
|
||||
let f = type3(&mut doc, unit, [0, 0, 1, 1], &["100 0 0 -10 100 90 d1"]);
|
||||
let m = Metrics::from_dict(&doc, &f);
|
||||
assert_eq!((m.ascent, m.descent), (90.0, -10.0));
|
||||
|
||||
// No `d1` anywhere: the `/FontBBox` still decides, scaled by the matrix.
|
||||
let f = type3(&mut doc, [0.001, 0.0, 0.0, 0.001, 0.0, 0.0], [0, -300, 1000, 900], &["600 0 d0"]);
|
||||
let m = Metrics::from_dict(&doc, &f);
|
||||
assert!((m.ascent - 0.9).abs() < 1e-12 && (m.descent + 0.3).abs() < 1e-12, "{} {}", m.ascent, m.descent);
|
||||
}
|
||||
|
||||
/// Small glyphs keep their small box: there is no 0.5 em / 0.1 em minimum for `d1` boxes, which
|
||||
/// made a 58-point line of 0.15 em glyphs 35 points high. The shape of a scanned-text bitmap
|
||||
/// font: matrix 0.0042, `/FontBBox` all zero, `d1` boxes from -8 to 33 units.
|
||||
#[test]
|
||||
fn small_type3_glyphs_keep_their_d1_height() {
|
||||
let mut doc = Document::new_empty();
|
||||
let small = [0.0042, 0.0, 0.0, 0.0042, 0.0, 0.0];
|
||||
let f = type3(&mut doc, small, [0, 0, 0, 0], &["13 0 2 19 9 33 d1", "26 0 2 -8 24 28 d1", "13 0 0 0 1 1 d1"]);
|
||||
let m = Metrics::from_dict(&doc, &f);
|
||||
assert!((m.ascent - 33.0 * 0.0042).abs() < 1e-12 && (m.descent + 8.0 * 0.0042).abs() < 1e-12, "{} {}", m.ascent, m.descent);
|
||||
// Glyphs that all sit above the baseline still reach down to it.
|
||||
let f = type3(&mut doc, small, [0, 0, 0, 0], &["13 0 2 19 9 33 d1"]);
|
||||
let m = Metrics::from_dict(&doc, &f);
|
||||
assert!((m.ascent - 33.0 * 0.0042).abs() < 1e-12 && m.descent == 0.0, "{} {}", m.ascent, m.descent);
|
||||
}
|
||||
|
||||
/// A font matrix that turns glyph space over (`[1 0 0 -1 0 0]`, drawn under a flipped text
|
||||
/// matrix) puts the top of the glyph box at text-space y -top: the box is as high as before,
|
||||
/// upside down, not clamped to a sliver.
|
||||
#[test]
|
||||
fn a_flipped_type3_font_matrix_keeps_the_glyph_height() {
|
||||
let mut doc = Document::new_empty();
|
||||
let flipped = [1.0, 0.0, 0.0, -1.0, 0.0, 0.0];
|
||||
let f = type3(&mut doc, flipped, [-4, -18, 51, 57], &["37 0 2 -1 34 38 d1", "42 0 2 -18 40 38 d1", "46 0 3 -1 42 57 d1"]);
|
||||
let m = Metrics::from_dict(&doc, &f);
|
||||
assert_eq!((m.ascent, m.descent), (18.0, -57.0));
|
||||
let f = type3(&mut doc, flipped, [-4, -18, 51, 57], &[]);
|
||||
let m = Metrics::from_dict(&doc, &f);
|
||||
assert_eq!((m.ascent, m.descent), (18.0, -57.0), "the /FontBBox, turned over the same way");
|
||||
}
|
||||
|
||||
/// Glyph descriptions are untrusted: unreadable ones, a box of infinities, a degenerate matrix
|
||||
/// and a font with more glyphs than are read all leave finite metrics.
|
||||
#[test]
|
||||
fn type3_glyph_boxes_are_read_within_bounds() {
|
||||
let mut doc = Document::new_empty();
|
||||
let unit = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0];
|
||||
for procs in [&["inf 0 0 -inf 1 inf d1"][..], &["d1"], &["1 2 3 d1"], &[""], &["1 0 0 0 1 0 d1"], &["1e308 0 -1e308 -1e308 1e308 1e308 d1"]] {
|
||||
let f = type3(&mut doc, unit, [0, 0, 0, 0], procs);
|
||||
let m = Metrics::from_dict(&doc, &f);
|
||||
assert!(m.ascent > 0.0 && m.descent < 0.0, "{procs:?}");
|
||||
assert!(m.ascent <= MAX_TYPE3_EXTENT && m.descent >= -MAX_TYPE3_EXTENT, "{procs:?}");
|
||||
}
|
||||
// A matrix with no y scale gives the box no height: the fallback metrics stand.
|
||||
let f = type3(&mut doc, [1.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0, 0, 0, 0], &["1 0 0 0 1 100 d1"]);
|
||||
let m = Metrics::from_dict(&doc, &f);
|
||||
assert_eq!((m.ascent, m.descent), (Metrics::fallback().ascent, Metrics::fallback().descent));
|
||||
// Glyphs past the first MAX_TYPE3_GLYPHS are not read.
|
||||
let mut procs = vec!["1 0 0 0 1 10 d1"; MAX_TYPE3_GLYPHS];
|
||||
procs.push("1 0 0 0 1 1000 d1");
|
||||
let f = type3(&mut doc, unit, [0, 0, 0, 0], &procs);
|
||||
assert_eq!(Metrics::from_dict(&doc, &f).ascent, 10.0);
|
||||
}
|
||||
|
||||
/// `/Differences` with the glyph names `names` from code 0, set on the Type 3 font `f`.
|
||||
fn with_differences(f: &mut Dict, names: &[String]) {
|
||||
let mut items = vec![Object::Int(0)];
|
||||
items.extend(names.iter().map(|n| Object::name(n)));
|
||||
let mut enc = Dict::new();
|
||||
enc.set(b"Differences".to_vec(), Object::Array(items));
|
||||
f.set(b"Encoding".to_vec(), Object::Dict(enc));
|
||||
}
|
||||
|
||||
/// The glyph descriptions the encoding reaches are the ones read, since its `/Differences`
|
||||
/// "shall specify the complete character encoding" (ISO 32000-2 Table 110): a drawn glyph past
|
||||
/// the first [`MAX_TYPE3_GLYPHS`] descriptions still counts.
|
||||
#[test]
|
||||
fn type3_glyph_boxes_are_read_for_the_glyphs_the_encoding_reaches() {
|
||||
let mut doc = Document::new_empty();
|
||||
let mut procs = vec!["1 0 0 0 1 10 d1"; MAX_TYPE3_GLYPHS + 44];
|
||||
procs.push("1 0 0 0 1 1000 d1");
|
||||
let mut f = type3(&mut doc, [1.0, 0.0, 0.0, 1.0, 0.0, 0.0], [0, 0, 0, 0], &procs);
|
||||
with_differences(&mut f, &[format!("g{}", MAX_TYPE3_GLYPHS + 44), "g0".into()]);
|
||||
assert_eq!(Metrics::from_dict(&doc, &f).ascent, 1000.0);
|
||||
}
|
||||
|
||||
/// Byte limits on glyph descriptions: one larger than [`MAX_TYPE3_GLYPH_BYTES`] is skipped, its
|
||||
/// `d1` box unread, and the rest are read; once the font's [`MAX_TYPE3_FONT_BYTES`] run out,
|
||||
/// the boxes read so far may miss glyphs that are drawn, so a nonzero `/FontBBox` stands.
|
||||
#[test]
|
||||
fn type3_glyph_byte_limits_leave_honest_metrics() {
|
||||
let mut doc = Document::new_empty();
|
||||
let unit = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0];
|
||||
let pad = |head: &str, len: usize| format!("{head}{}", " ".repeat(len.saturating_sub(head.len())));
|
||||
let oversized = pad("1 0 0 0 1 1000 d1", MAX_TYPE3_GLYPH_BYTES + 100);
|
||||
let procs = [oversized.as_str(), "1 0 0 0 1 3 d1"];
|
||||
let mut f = type3(&mut doc, unit, [0, -2, 10, 5], &procs);
|
||||
with_differences(&mut f, &["g0".into(), "g1".into()]);
|
||||
let m = Metrics::from_dict(&doc, &f);
|
||||
assert_eq!((m.ascent, m.descent), (3.0, 0.0), "the oversized glyph is skipped, the other read");
|
||||
|
||||
let filler = pad("0 0 m", MAX_TYPE3_GLYPH_BYTES - 1000);
|
||||
let fillers = MAX_TYPE3_FONT_BYTES / (MAX_TYPE3_GLYPH_BYTES - 1000) + 1;
|
||||
let mut procs = vec!["1 0 0 0 1 1 d1"];
|
||||
procs.extend(std::iter::repeat_n(filler.as_str(), fillers));
|
||||
procs.push("1 0 0 0 1 1000 d1");
|
||||
let mut f = type3(&mut doc, unit, [0, -2, 10, 5], &procs);
|
||||
let names: Vec<String> = (0..procs.len()).map(|i| format!("g{i}")).collect();
|
||||
with_differences(&mut f, &names);
|
||||
let m = Metrics::from_dict(&doc, &f);
|
||||
assert_eq!((m.ascent, m.descent), (5.0, -2.0), "the /FontBBox, not the first glyph's box alone");
|
||||
}
|
||||
|
||||
/// A Type 3 font measured from its glyphs' `d1` boxes keeps them over a descriptor's `/Ascent`
|
||||
/// and `/Descent`, which are optional for Type 3 (ISO 32000-2 Table 120).
|
||||
#[test]
|
||||
fn type3_d1_glyph_boxes_win_over_descriptor_metrics() {
|
||||
let mut doc = Document::new_empty();
|
||||
let small = [0.0042, 0.0, 0.0, 0.0042, 0.0, 0.0];
|
||||
let mut f = type3(&mut doc, small, [0, 0, 0, 0], &["13 0 2 -8 9 33 d1"]);
|
||||
let mut descriptor = Dict::new();
|
||||
descriptor.set(b"Type".to_vec(), Object::name("FontDescriptor"));
|
||||
descriptor.set(b"Ascent".to_vec(), Object::Int(891));
|
||||
descriptor.set(b"Descent".to_vec(), Object::Int(-216));
|
||||
let reference = doc.add(Object::Dict(descriptor));
|
||||
f.set(b"FontDescriptor".to_vec(), Object::Ref(reference));
|
||||
let m = Metrics::from_dict(&doc, &f);
|
||||
assert!((m.ascent - 33.0 * 0.0042).abs() < 1e-12 && (m.descent + 8.0 * 0.0042).abs() < 1e-12, "{} {}", m.ascent, m.descent);
|
||||
}
|
||||
|
||||
/// A `/Differences` naming more distinct glyphs than [`MAX_TYPE3_GLYPHS`] leaves some unread, so
|
||||
/// a nonzero `/FontBBox` stands over the boxes of those read.
|
||||
#[test]
|
||||
fn type3_glyphs_past_the_limit_leave_the_font_bbox_standing() {
|
||||
let mut doc = Document::new_empty();
|
||||
let mut procs = vec!["1 0 0 0 1 10 d1"; MAX_TYPE3_GLYPHS];
|
||||
procs.push("1 0 0 0 1 1000 d1");
|
||||
let mut f = type3(&mut doc, [1.0, 0.0, 0.0, 1.0, 0.0, 0.0], [0, -2, 10, 50], &procs);
|
||||
let names: Vec<String> = (0..procs.len()).map(|i| format!("g{i}")).collect();
|
||||
with_differences(&mut f, &names);
|
||||
let m = Metrics::from_dict(&doc, &f);
|
||||
assert_eq!((m.ascent, m.descent), (50.0, -2.0));
|
||||
}
|
||||
|
||||
/// `d1` boxes with no height in text space (all flat) give way to a usable `/FontBBox`.
|
||||
#[test]
|
||||
fn flat_type3_glyph_boxes_give_way_to_the_font_bbox() {
|
||||
let mut doc = Document::new_empty();
|
||||
let f = type3(&mut doc, [1.0, 0.0, 0.0, 1.0, 0.0, 0.0], [0, -2, 10, 50], &["1 0 0 5 1 5 d1"]);
|
||||
let m = Metrics::from_dict(&doc, &f);
|
||||
assert_eq!((m.ascent, m.descent), (50.0, -2.0));
|
||||
}
|
||||
|
||||
/// A Type 3 font measured from its `/FontBBox` keeps that box through its font matrix over a
|
||||
/// descriptor's `/Ascent` and `/Descent`, which would be read as 1000-unit values.
|
||||
#[test]
|
||||
fn a_type3_font_bbox_wins_over_descriptor_metrics() {
|
||||
let mut doc = Document::new_empty();
|
||||
let small = [0.0042, 0.0, 0.0, 0.0042, 0.0, 0.0];
|
||||
let mut f = type3(&mut doc, small, [0, -50, 100, 200], &[]);
|
||||
let mut descriptor = Dict::new();
|
||||
descriptor.set(b"Type".to_vec(), Object::name("FontDescriptor"));
|
||||
descriptor.set(b"Ascent".to_vec(), Object::Int(891));
|
||||
descriptor.set(b"Descent".to_vec(), Object::Int(-216));
|
||||
let reference = doc.add(Object::Dict(descriptor));
|
||||
f.set(b"FontDescriptor".to_vec(), Object::Ref(reference));
|
||||
let m = Metrics::from_dict(&doc, &f);
|
||||
// 200 and -50 units at 0.0042, kept at the 0.5 / -0.1 em floor.
|
||||
assert!((m.ascent - 0.84).abs() < 1e-9 && (m.descent + 0.21).abs() < 1e-9, "{} {}", m.ascent, m.descent);
|
||||
}
|
||||
|
||||
/// An `/Encoding` with a `/BaseEncoding` reaches glyphs its `/Differences` doesn't name, whose
|
||||
/// boxes go unread, so a nonzero `/FontBBox` stands over the boxes of those named.
|
||||
#[test]
|
||||
fn a_type3_base_encoding_leaves_the_font_bbox_standing() {
|
||||
let mut doc = Document::new_empty();
|
||||
let mut f = type3(&mut doc, [1.0, 0.0, 0.0, 1.0, 0.0, 0.0], [0, -2, 10, 50], &["1 0 0 0 1 10 d1", "1 0 0 0 1 1000 d1"]);
|
||||
let mut enc = Dict::new();
|
||||
enc.set(b"BaseEncoding".to_vec(), Object::name("WinAnsiEncoding"));
|
||||
enc.set(b"Differences".to_vec(), Object::Array(vec![Object::Int(0), Object::name("g0")]));
|
||||
f.set(b"Encoding".to_vec(), Object::Dict(enc));
|
||||
let m = Metrics::from_dict(&doc, &f);
|
||||
assert_eq!((m.ascent, m.descent), (50.0, -2.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn simple_fonts_decode_and_encode_through_their_encoding() {
|
||||
let mut doc = Document::new_empty();
|
||||
@@ -334,6 +556,76 @@ fn subset_fonts_only_encode_the_glyphs_they_have() {
|
||||
assert_eq!(m.encode("abc"), None);
|
||||
}
|
||||
|
||||
/// #6131: pdfTeX writes `/FirstChar` below 32 and `/Widths` of 0 for the codes it never uses, the space
|
||||
/// among them: the subset has no space glyph, and the words are apart by `TJ` gaps. Writing a typed space as
|
||||
/// code 32 would glue the words together at width 0, so the font can't encode one and the edit sets the
|
||||
/// space as a gap instead (as for a subset whose widths stop short of 32).
|
||||
#[test]
|
||||
fn a_subset_that_gives_the_space_no_width_cannot_encode_one() {
|
||||
// pdfTeX writes Type 1 fonts; the same rule holds for a TrueType subset.
|
||||
for subtype in ["TrueType", "Type1"] {
|
||||
a_zero_width_space_in_a_subset_of(subtype);
|
||||
}
|
||||
}
|
||||
|
||||
fn a_zero_width_space_in_a_subset_of(subtype: &str) {
|
||||
let metrics = |base: &str, space: i64| {
|
||||
let mut doc = Document::new_empty();
|
||||
// Codes 32..=98: the space, then a and b (97, 98) with a width, everything else 0.
|
||||
let widths: Vec<Object> = (32..=98)
|
||||
.map(|code| {
|
||||
Object::Int(match code {
|
||||
32 => space,
|
||||
97 | 98 => 500,
|
||||
_ => 0,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let f = font(
|
||||
&mut doc,
|
||||
vec![
|
||||
("Subtype", Object::name(subtype)),
|
||||
("BaseFont", Object::name(base)),
|
||||
("FirstChar", Object::Int(32)),
|
||||
("Widths", Object::Array(widths)),
|
||||
("Encoding", Object::name("WinAnsiEncoding")),
|
||||
],
|
||||
);
|
||||
Metrics::from_dict(&doc, &f)
|
||||
};
|
||||
let subset = metrics("ABCDEF+Sample", 0);
|
||||
assert!(subset.subset);
|
||||
assert_eq!(subset.encode("ab").as_deref(), Some(&b"ab"[..]));
|
||||
assert_eq!(subset.encode("a b"), None, "no space glyph: a gap sets it");
|
||||
assert_eq!(subset.encode(" "), None);
|
||||
assert_eq!(metrics("ABCDEF+Sample", 250).encode("a b").as_deref(), Some(&b"a b"[..]), "a subset that does draw the space");
|
||||
assert_eq!(metrics("Sample", 0).encode("a b").as_deref(), Some(&b"a b"[..]), "a full font keeps its space whatever the width says");
|
||||
}
|
||||
|
||||
/// Only a *space* at code 32 is given up for a width of 0: a subset that puts another glyph there (a symbol
|
||||
/// font, say) keeps encoding it.
|
||||
#[test]
|
||||
fn a_subset_keeps_a_zero_width_glyph_that_is_not_a_space_at_code_32() {
|
||||
let mut doc = Document::new_empty();
|
||||
let widths: Vec<Object> = (32..=98).map(|code| Object::Int(if code == 97 { 500 } else { 0 })).collect();
|
||||
let mut enc = Dict::new();
|
||||
enc.set(b"Differences".to_vec(), Object::Array(vec![Object::Int(32), Object::name("Z")]));
|
||||
let f = font(
|
||||
&mut doc,
|
||||
vec![
|
||||
("Subtype", Object::name("TrueType")),
|
||||
("BaseFont", Object::name("ABCDEF+Sample")),
|
||||
("FirstChar", Object::Int(32)),
|
||||
("Widths", Object::Array(widths)),
|
||||
("Encoding", Object::Dict(enc)),
|
||||
],
|
||||
);
|
||||
let m = Metrics::from_dict(&doc, &f);
|
||||
assert!(m.subset);
|
||||
assert_eq!(m.text_of(32).as_deref(), Some("Z"));
|
||||
assert_eq!(m.encode("Z").as_deref(), Some(&[32][..]), "code 32 is a glyph here, not a space");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cmap_streams_decode_within_a_size_cap() {
|
||||
// A valid CMap padded past the cap (a small Flate stream of whitespace) is not decoded whole.
|
||||
|
||||
@@ -531,6 +531,10 @@ pub fn calculate(c: &Calculate, values: &dyn Fn(&str) -> Vec<String>) -> Option<
|
||||
let num = |s: &String| make_number(s).unwrap_or(0.0);
|
||||
match c {
|
||||
Calculate::None => None,
|
||||
// A product of no values is 0, as an empty sum, average, minimum or maximum is, not the
|
||||
// empty product 1: a blank quantity × price row reads 0, and a total over the rows
|
||||
// doesn't count it as 1. (The form's `values` leaves out a field that has no value.)
|
||||
Calculate::Simple { op: CalcOp::Product, fields } if fields.iter().all(|f| values(f).is_empty()) => Some("0".into()),
|
||||
Calculate::Simple { op, fields } => {
|
||||
let xs: Vec<f64> = fields.iter().flat_map(|f| values(f)).map(|v| num(&v)).collect();
|
||||
let v = match op {
|
||||
|
||||
@@ -360,6 +360,35 @@ fn dates_times_and_masks() {
|
||||
assert!(keystroke(&Format::Mask("AA-9999".into()), "Code", "a11234").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_calculation_over_fields_without_values_is_0_for_every_operation() {
|
||||
// A blank row: neither field has a value, so the form's lookup returns none.
|
||||
let vals = |name: &str| -> Vec<String> { if name == "a" { vec!["2".into()] } else { vec![] } };
|
||||
let simple = |op, f: &[&str]| calculate(&Calculate::Simple { op, fields: f.iter().map(|s| s.to_string()).collect() }, &vals);
|
||||
for op in CalcOp::ALL {
|
||||
assert_eq!(simple(op, &["qty", "price"]), Some("0".into()), "{op:?} of empty fields");
|
||||
assert_eq!(simple(op, &[]), Some("0".into()), "{op:?} of no fields");
|
||||
}
|
||||
assert_eq!(simple(CalcOp::Product, &["a", "qty"]), Some("2".into()), "a field with no value is left out");
|
||||
}
|
||||
|
||||
/// A drop-down's blank option is often a single space, the value it starts with. That is a value
|
||||
/// worth 0, so a row whose quantity is still blank reads 0 × price = 0. Read as "no value", it
|
||||
/// would be left out and the row would read the price alone.
|
||||
#[test]
|
||||
fn a_blank_option_of_a_single_space_is_a_value_worth_0() {
|
||||
let vals = |name: &str| -> Vec<String> {
|
||||
match name {
|
||||
"qty" => vec![" ".into()],
|
||||
"price" => vec!["605".into()],
|
||||
_ => vec![],
|
||||
}
|
||||
};
|
||||
let simple = |op, f: &[&str]| calculate(&Calculate::Simple { op, fields: f.iter().map(|s| s.to_string()).collect() }, &vals);
|
||||
assert_eq!(simple(CalcOp::Product, &["qty", "price"]), Some("0".into()));
|
||||
assert_eq!(simple(CalcOp::Product, &["qty", "none"]), Some("0".into()), "a blank quantity on a row without a price");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validation_and_calculation() {
|
||||
let r = Validate::Range { min: Some(0.0), max: Some(100.0) };
|
||||
|
||||
@@ -399,9 +399,17 @@ fn helvetica() -> Object {
|
||||
Object::Dict(f)
|
||||
}
|
||||
|
||||
/// An `/MK /BC` or `/BG` colour (ISO 32000-2 Table 192) as a fill operator. A four-entry array
|
||||
/// with a non-number in it, such as `[1 0 0 null]`, is CMYK with that entry 0, as annotation `/C`
|
||||
/// colours are read.
|
||||
fn color_array(doc: &Document, mk: Option<&Dict>, key: &[u8]) -> Option<String> {
|
||||
let a = doc.resolve(mk?.get(key)?);
|
||||
let v: Vec<f64> = a.as_array()?.iter().filter_map(|x| doc.resolve(x).as_f64()).collect();
|
||||
let a = a.as_array()?;
|
||||
let v: Vec<f64> = if a.len() == 4 {
|
||||
a.iter().map(|x| doc.resolve(x).as_f64().unwrap_or(0.0)).collect()
|
||||
} else {
|
||||
a.iter().filter_map(|x| doc.resolve(x).as_f64()).collect()
|
||||
};
|
||||
match v.as_slice() {
|
||||
[g] => Some(format!("{} g", n(*g))),
|
||||
[r, g, b] => Some(format!("{} {} {} rg", n(*r), n(*g), n(*b))),
|
||||
|
||||
+64
-13
@@ -106,12 +106,19 @@ fn qualified_name(doc: &Document, r: ObjRef) -> Option<String> {
|
||||
if let Some(t) = d.get(b"T").and_then(|o| text_of(&doc.resolve(o))) {
|
||||
parts.push(t);
|
||||
}
|
||||
cur = d.get(b"Parent").and_then(|p| p.as_ref());
|
||||
cur = parent_of(doc, d);
|
||||
}
|
||||
parts.reverse();
|
||||
(!parts.is_empty()).then(|| parts.join("."))
|
||||
}
|
||||
|
||||
/// The field `d` names as its `/Parent`, when that is a dictionary. A reference to an object the
|
||||
/// file doesn't hold reads as `null`, and a `null` entry is the same as an absent one (ISO
|
||||
/// 32000-2 §7.3.9): the field is then a root, as if it named no parent.
|
||||
fn parent_of(doc: &Document, d: &Dict) -> Option<ObjRef> {
|
||||
d.reference(b"Parent").filter(|p| doc.get(*p).as_dict().is_some())
|
||||
}
|
||||
|
||||
/// JavaScript streams one reading of the form (its fields, or its document scripts) may decode
|
||||
/// in all, however many actions name the same stream.
|
||||
pub(crate) const MAX_SCRIPT_BYTES: usize = 64 << 20;
|
||||
@@ -331,13 +338,19 @@ pub(crate) fn enumerate(doc: &Document) -> (Vec<Field>, usize) {
|
||||
let af = acroform(doc);
|
||||
let mut page_of = std::collections::HashMap::new();
|
||||
let mut annot_index = std::collections::HashMap::new();
|
||||
let mut by_parent: std::collections::HashMap<ObjRef, Vec<ObjRef>> = std::collections::HashMap::new();
|
||||
let pages = page_refs(doc);
|
||||
for (i, p) in pages.iter().enumerate() {
|
||||
if let Some(a) = doc.get(*p).as_dict().and_then(|d| d.get(b"Annots").cloned()) {
|
||||
for (k, e) in doc.resolve(&a).as_array().into_iter().flatten().enumerate() {
|
||||
if let Some(r) = e.as_ref() {
|
||||
page_of.entry(r).or_insert(i);
|
||||
annot_index.entry(r).or_insert(k);
|
||||
if let Some(r) = e.as_ref()
|
||||
&& let std::collections::hash_map::Entry::Vacant(slot) = page_of.entry(r)
|
||||
{
|
||||
slot.insert(i);
|
||||
annot_index.insert(r, k);
|
||||
if let Some(parent) = widget_parent(doc, r) {
|
||||
by_parent.entry(parent).or_default().push(r);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -351,18 +364,24 @@ pub(crate) fn enumerate(doc: &Document) -> (Vec<Field>, usize) {
|
||||
None => Inherited::default(),
|
||||
};
|
||||
let mut out = Vec::new();
|
||||
let listed_roots: Vec<ObjRef> = af
|
||||
.as_ref()
|
||||
.and_then(|af| af.get(b"Fields").map(|o| doc.resolve(o)).and_then(|o| o.as_array().cloned()))
|
||||
.unwrap_or_default()
|
||||
.iter()
|
||||
.filter_map(Object::as_ref)
|
||||
.collect();
|
||||
let mut seen = Seen {
|
||||
fields: std::collections::HashSet::new(),
|
||||
widgets: std::collections::HashSet::new(),
|
||||
roots: listed_roots.iter().copied().collect(),
|
||||
path: Vec::new(),
|
||||
by_parent,
|
||||
scripts: script_budget(),
|
||||
values: DecodeBudget::new(MAX_VALUE_BYTES, 0),
|
||||
};
|
||||
if let Some(af) = &af {
|
||||
for f in af.get(b"Fields").map(|o| doc.resolve(o)).and_then(|o| o.as_array().cloned()).unwrap_or_default() {
|
||||
if let Some(r) = f.as_ref() {
|
||||
walk(doc, r, &base, &page_of, &mut seen, &mut out, 0);
|
||||
}
|
||||
}
|
||||
for r in listed_roots {
|
||||
walk(doc, r, &base, &page_of, &mut seen, &mut out, 0);
|
||||
}
|
||||
let listed = out.len();
|
||||
adopt_page_fields(doc, &pages, &base, &page_of, &mut seen, &mut out);
|
||||
@@ -413,7 +432,7 @@ fn unlisted_root(doc: &Document, r: ObjRef, seen: &std::collections::HashSet<Obj
|
||||
let mut top = r;
|
||||
let mut visited = std::collections::HashSet::from([r]);
|
||||
loop {
|
||||
let parent = doc.get(top).as_dict().and_then(|d| d.reference(b"Parent"));
|
||||
let parent = doc.get(top).as_dict().and_then(|d| parent_of(doc, d));
|
||||
let Some(p) = parent else {
|
||||
return if seen.contains(&top) { None } else { Some(top) };
|
||||
};
|
||||
@@ -433,10 +452,36 @@ struct Seen {
|
||||
fields: std::collections::HashSet<ObjRef>,
|
||||
/// A widget belongs to the first field that lists it, however often it is listed.
|
||||
widgets: std::collections::HashSet<ObjRef>,
|
||||
/// The fields `/Fields` lists: root fields, with no ancestors (ISO 32000-2 §12.7.3, Table 224).
|
||||
roots: std::collections::HashSet<ObjRef>,
|
||||
/// The fields being walked, outermost first, whose `/Kids` are being read.
|
||||
path: Vec<ObjRef>,
|
||||
/// The page widgets (no `/T`) that name each field as their `/Parent`, in page-annotation order.
|
||||
by_parent: std::collections::HashMap<ObjRef, Vec<ObjRef>>,
|
||||
scripts: DecodeBudget,
|
||||
values: DecodeBudget,
|
||||
}
|
||||
|
||||
/// The field a page widget `r` names as its `/Parent`, when `r` is a widget and not a field of its
|
||||
/// own (no `/T`).
|
||||
fn widget_parent(doc: &Document, r: ObjRef) -> Option<ObjRef> {
|
||||
let obj = doc.get(r);
|
||||
let d = obj.as_dict()?;
|
||||
if d.name(b"Subtype") != Some(b"Widget") || d.contains(b"T") {
|
||||
return None;
|
||||
}
|
||||
d.reference(b"Parent")
|
||||
}
|
||||
|
||||
/// Whether `k`, listed in the `/Kids` of field `r`, is not a child of `r` after all: `r` itself or
|
||||
/// a field `r` descends from (a loop), or a root field (one `/Fields` lists) that doesn't name `r`
|
||||
/// as its `/Parent`. Root fields have no ancestors (ISO 32000-2 §12.7.3, Table 224), and a
|
||||
/// child names its parent (§12.7.4.1, Table 226): only the `/Kids` entry says otherwise, so the
|
||||
/// field is read as the root it is, and `r` keeps its other kids.
|
||||
fn not_a_child(doc: &Document, seen: &Seen, r: ObjRef, k: ObjRef) -> bool {
|
||||
k == r || seen.path.contains(&k) || (seen.roots.contains(&k) && doc.get(k).as_dict().and_then(|d| d.reference(b"Parent")) != Some(r))
|
||||
}
|
||||
|
||||
/// Read the field at `r` and the fields under it into `out`, with what they inherit from
|
||||
/// `parent`: kids with a name are fields of their own, kids without are this field's widgets.
|
||||
fn walk(
|
||||
@@ -483,11 +528,14 @@ fn walk(
|
||||
let kids: Vec<ObjRef> =
|
||||
d.get(b"Kids").map(|k| doc.resolve(k)).and_then(|k| k.as_array().cloned()).unwrap_or_default().iter().filter_map(|k| k.as_ref()).collect();
|
||||
// Kids with /T are fields; kids without are this field's widgets.
|
||||
let field_kids: Vec<ObjRef> = kids.iter().copied().filter(|k| doc.get(*k).as_dict().is_some_and(|kd| kd.contains(b"T"))).collect();
|
||||
let (field_kids, kids): (Vec<ObjRef>, Vec<ObjRef>) = kids.into_iter().partition(|k| doc.get(*k).as_dict().is_some_and(|kd| kd.contains(b"T")));
|
||||
let field_kids: Vec<ObjRef> = field_kids.into_iter().filter(|k| !not_a_child(doc, seen, r, *k)).collect();
|
||||
if !field_kids.is_empty() {
|
||||
seen.path.push(r);
|
||||
for k in field_kids {
|
||||
walk(doc, k, &inh, page_of, seen, out, depth + 1);
|
||||
}
|
||||
seen.path.pop();
|
||||
return;
|
||||
}
|
||||
// A field of no kind this reads is skipped before it claims widgets or scripts, which a later
|
||||
@@ -503,7 +551,10 @@ fn walk(
|
||||
Some(b"Sig") => FieldKind::Signature,
|
||||
_ => return,
|
||||
};
|
||||
let widget_refs: Vec<ObjRef> = if d.contains(b"Rect") { vec![r] } else { kids };
|
||||
// A child names its parent (ISO 32000-2 §12.7.4.1, Table 226): a page widget naming this field
|
||||
// is one of its widgets even when its `/Kids` leave it out, as MuPDF and PDFium read it.
|
||||
let widget_refs: Vec<ObjRef> =
|
||||
if d.contains(b"Rect") { vec![r] } else { kids.into_iter().chain(seen.by_parent.get(&r).into_iter().flatten().copied()).collect() };
|
||||
let widget_refs: Vec<ObjRef> = widget_refs.into_iter().filter(|w| seen.widgets.insert(*w)).collect();
|
||||
let actions = actions_of(doc, d, &widget_refs, &mut seen.scripts);
|
||||
let button = (inh.ft.as_deref() == Some(b"Btn") && inh.ff.unwrap_or(0) & flags::PUSH_BUTTON != 0)
|
||||
|
||||
@@ -42,6 +42,8 @@ pub struct FieldChange {
|
||||
pub required: Option<bool>,
|
||||
/// `display.visible` 0, `hidden` 1, `noPrint` 2, `noView` 3.
|
||||
pub display: Option<i32>,
|
||||
/// Move/resize the first widget, in PDF user space.
|
||||
pub rect: Option<[f64; 4]>,
|
||||
}
|
||||
|
||||
/// What a script did.
|
||||
@@ -51,6 +53,8 @@ pub struct ScriptResult {
|
||||
pub rc: bool,
|
||||
/// `event.value` afterwards.
|
||||
pub value: String,
|
||||
/// Whether the script assigned `event.value`, even the value it already had.
|
||||
pub value_set: bool,
|
||||
pub changes: Vec<FieldChange>,
|
||||
/// Why it rejected the value (its alert), for the error shown.
|
||||
pub message: Option<String>,
|
||||
@@ -82,7 +86,7 @@ pub struct NoScripts;
|
||||
|
||||
impl Scripts for NoScripts {
|
||||
fn run(&mut self, _: FieldEvent, _: &str, _: &Field, value: &str, _: &[Field]) -> ScriptResult {
|
||||
ScriptResult { rc: true, value: value.to_string(), changes: Vec::new(), message: None }
|
||||
ScriptResult { rc: true, value: value.to_string(), value_set: false, changes: Vec::new(), message: None }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -173,6 +177,9 @@ pub(crate) fn apply_changes(doc: &mut Document, changes: &[FieldChange], except:
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(rect) = c.rect {
|
||||
crate::set_props(doc, &c.name, &crate::FieldProps { rect: Some((0, rect)), ..Default::default() })?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
+255
-3
@@ -305,6 +305,85 @@ fn field_flags_reject_values_outside_the_unsigned_32_bit_domain() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A `/Kids` entry that loops back (the field itself, or a field it descends from), or names a root
|
||||
/// field that doesn't name this one as its `/Parent`, is not a child (ISO 32000-2 §12.7.3,
|
||||
/// Table 224; §12.7.4.1, Table 226). The field keeps its other kids: here its radio buttons.
|
||||
#[test]
|
||||
fn kids_that_loop_back_or_are_roots_are_not_children() {
|
||||
let objs: Vec<String> = vec![
|
||||
"<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(), // 1
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(), // 2
|
||||
"<< /Type /Page /Parent 2 0 R /Annots [6 0 R 9 0 R 12 0 R 15 0 R] >>".into(), // 3
|
||||
"<< /Fields [5 0 R 7 0 R 8 0 R 10 0 R] /DA (/Helv 0 Tf 0 g) >>".into(), // 4
|
||||
"<< /FT /Btn /Ff 49152 /T (size) /V /Off /Kids [5 0 R 6 0 R] >>".into(), // 5 lists itself
|
||||
"<< /Type /Annot /Subtype /Widget /Parent 5 0 R /Rect [50 700 65 715] /P 3 0 R /AP << /N << /S 11 0 R /Off 11 0 R >> >> >>".into(), // 6
|
||||
"<< /FT /Btn /Ff 49152 /T (left) /V /Off /Kids [8 0 R 9 0 R] >>".into(), // 7 lists the root 8
|
||||
"<< /FT /Btn /Ff 49152 /T (right) /V /Off /Kids [7 0 R 12 0 R] >>".into(), // 8 lists the root 7
|
||||
"<< /Type /Annot /Subtype /Widget /Parent 7 0 R /Rect [50 650 65 665] /P 3 0 R /AP << /N << /A 11 0 R /Off 11 0 R >> >> >>".into(), // 9
|
||||
"<< /T (group) /Kids [13 0 R] >>".into(), // 10
|
||||
"<< /Length 0 >>
|
||||
stream
|
||||
|
||||
endstream"
|
||||
.into(), // 11
|
||||
"<< /Type /Annot /Subtype /Widget /Parent 8 0 R /Rect [50 600 65 615] /P 3 0 R /AP << /N << /B 11 0 R /Off 11 0 R >> >> >>".into(), // 12
|
||||
"<< /FT /Tx /T (inner) /Parent 10 0 R /Kids [14 0 R] >>".into(), // 13
|
||||
"<< /FT /Tx /T (deep) /Parent 13 0 R /Kids [13 0 R 15 0 R] >>".into(), // 14 lists its parent
|
||||
"<< /Type /Annot /Subtype /Widget /Parent 14 0 R /Rect [50 550 250 570] /P 3 0 R >>".into(), // 15
|
||||
];
|
||||
let doc = document(&objs);
|
||||
let all = fields(&doc);
|
||||
let listed: Vec<(&str, FieldKind, Vec<ObjRef>)> =
|
||||
all.iter().map(|f| (f.name.as_str(), f.kind, f.widgets.iter().map(|w| w.obj).collect())).collect();
|
||||
let r = |num| ObjRef::new(num, 0);
|
||||
assert_eq!(
|
||||
listed,
|
||||
[
|
||||
("size", FieldKind::Radio, vec![r(6)]),
|
||||
("left", FieldKind::Radio, vec![r(9)]),
|
||||
("right", FieldKind::Radio, vec![r(12)]),
|
||||
("group.inner.deep", FieldKind::Text, vec![r(15)]),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
/// A page widget whose `/Parent` names a field is one of that field's widgets even when the
|
||||
/// field's `/Kids` leave it out: a child names its parent (ISO 32000-2 §12.7.4.1, Table 226). Here
|
||||
/// `radio` lists itself and one of its two widgets, and `pair` and `other` list each other (roots,
|
||||
/// so not children) and none of their widgets. Each field gets every widget naming it, once.
|
||||
#[test]
|
||||
fn widgets_naming_a_field_that_does_not_list_them_join_it() {
|
||||
let w = |parent: u32, state: &str, y: u32| {
|
||||
format!(
|
||||
"<< /Type /Annot /Subtype /Widget /Parent {parent} 0 R /Rect [50 {y} 65 {}] /P 3 0 R /AP << /N << /{state} 10 0 R /Off 10 0 R >> >> >>",
|
||||
y + 15
|
||||
)
|
||||
};
|
||||
let objs: Vec<String> = vec![
|
||||
"<< /Type /Catalog /Pages 2 0 R /AcroForm 6 0 R >>".into(), // 1
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(), // 2
|
||||
"<< /Type /Page /Parent 2 0 R /Annots [4 0 R 7 0 R 11 0 R 12 0 R 13 0 R] >>".into(), // 3
|
||||
w(5, "A", 700), // 4: not in 5's /Kids
|
||||
"<< /FT /Btn /Ff 49152 /T (radio) /V /Off /Kids [5 0 R 7 0 R] >>".into(), // 5
|
||||
"<< /Fields [5 0 R 8 0 R 9 0 R] /DA (/Helv 0 Tf 0 g) >>".into(), // 6
|
||||
w(5, "B", 650), // 7: in 5's /Kids
|
||||
"<< /FT /Btn /Ff 49152 /T (pair) /V /Off /Kids [9 0 R 11 0 R] >>".into(), // 8 lists the root 9
|
||||
"<< /FT /Btn /Ff 49152 /T (other) /V /Off /Kids [8 0 R] >>".into(), // 9 lists the root 8
|
||||
"<< /Length 0 >>\nstream\n\nendstream".into(), // 10
|
||||
w(8, "C", 600), // 11: in 8's /Kids
|
||||
w(8, "D", 550), // 12: not in 8's /Kids
|
||||
w(9, "E", 500), // 13: not in 9's /Kids
|
||||
];
|
||||
let doc = document(&objs);
|
||||
let (all, adopted) = enumerate(&doc);
|
||||
let listed: Vec<(&str, Vec<ObjRef>)> = all.iter().map(|f| (f.name.as_str(), f.widgets.iter().map(|w| w.obj).collect())).collect();
|
||||
let r = |num| ObjRef::new(num, 0);
|
||||
assert_eq!(listed, [("radio", vec![r(7), r(4)]), ("pair", vec![r(11), r(12)]), ("other", vec![r(13)])]);
|
||||
assert_eq!(adopted, 0, "no widget is read as a field of its own");
|
||||
let states: Vec<_> = field(&all, "radio").widgets.iter().filter_map(|w| w.on_state.as_deref()).collect();
|
||||
assert_eq!(states, ["B", "A"]);
|
||||
}
|
||||
|
||||
/// Some writers leave every field out of `/Fields` and put the widgets only in the page
|
||||
/// annotations: the tree walk alone finds nothing, and Acrobat and the browsers fill them anyway.
|
||||
/// The pages' widgets are adopted as fields, after the listed tree fields.
|
||||
@@ -353,6 +432,37 @@ fn fields_listed_only_on_the_pages_are_adopted() {
|
||||
assert_eq!(adopted_page_fields(&doc), 4);
|
||||
}
|
||||
|
||||
/// A widget whose `/Parent` names an object the file doesn't hold, or one that isn't a dictionary,
|
||||
/// has no parent: the reference reads as `null`, the same as an absent entry (ISO
|
||||
/// 32000-2 §7.3.9). It is adopted as a field of its own, under its own name, and can be filled.
|
||||
#[test]
|
||||
fn a_widget_whose_parent_is_missing_is_a_field_of_its_own() {
|
||||
let objs: Vec<String> = vec![
|
||||
"<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(), // 1
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(), // 2
|
||||
"<< /Type /Page /Parent 2 0 R /Annots [5 0 R 7 0 R 8 0 R] >>".into(), // 3
|
||||
"<< /Fields [] /DA (/Helv 0 Tf 0 g) /DR << /Font << /Helv 6 0 R >> >> >>".into(), // 4
|
||||
"<< /Type /Annot /Subtype /Widget /FT /Tx /T (city) /V (Oslo) /Parent 40 0 R /Rect [50 700 250 720] /P 3 0 R >>".into(), // 5 parent not in the file
|
||||
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".into(), // 6
|
||||
"<< /Type /Annot /Subtype /Widget /FT /Tx /T (zip) /Parent 9 0 R /Rect [50 660 250 680] /P 3 0 R >>".into(), // 7 parent is no dictionary
|
||||
"<< /Type /Annot /Subtype /Widget /Parent 40 0 R /Rect [400 700 415 715] /P 3 0 R >>".into(), // 8 no /FT or /T: not a field
|
||||
"[1 2 3]".into(), // 9
|
||||
];
|
||||
let mut doc = document(&objs);
|
||||
assert_combined_matches_legacy(&doc, 2);
|
||||
let all = fields(&doc);
|
||||
let names: Vec<&str> = all.iter().map(|f| f.name.as_str()).collect();
|
||||
assert_eq!(names, ["city", "zip"]);
|
||||
let city = field(&all, "city");
|
||||
assert_eq!(
|
||||
(city.kind, city.value.as_slice(), city.widgets.len(), city.widgets[0].page),
|
||||
(FieldKind::Text, &["Oslo".to_string()][..], 1, Some(0))
|
||||
);
|
||||
set_value(&mut doc, "zip", &FieldValue::Text("0150".into())).unwrap();
|
||||
let doc = reopen(&doc);
|
||||
assert_eq!(field(&fields(&doc), "zip").value, ["0150"]);
|
||||
}
|
||||
|
||||
/// pdf-lib and other writers give radio groups and check boxes an `/Opt` array and name the on
|
||||
/// states by position (`/0`, `/1`): the export values select them, as in Acrobat.
|
||||
#[test]
|
||||
@@ -1574,7 +1684,7 @@ fn a_script_that_spells_the_markers_in_a_string_runs_as_a_script() {
|
||||
struct Ran;
|
||||
impl Scripts for Ran {
|
||||
fn run(&mut self, _event: FieldEvent, _script: &str, _target: &Field, _value: &str, _fields: &[Field]) -> ScriptResult {
|
||||
ScriptResult { rc: true, value: "ran".into(), changes: Vec::new(), message: None }
|
||||
ScriptResult { rc: true, value: "ran".into(), value_set: true, changes: Vec::new(), message: None }
|
||||
}
|
||||
}
|
||||
let mut doc = one_page();
|
||||
@@ -1833,6 +1943,59 @@ fn missing_fields_and_built_names_are_flagged() {
|
||||
assert_eq!(order.fields[3].reads, ["qty"], "the names it does know are still read");
|
||||
}
|
||||
|
||||
/// An order form's rows, as a public one lays them out: an editable drop-down quantity whose blank
|
||||
/// option, and starting value, is a single space, a prefilled price, the row's product and a total
|
||||
/// over the rows. A blank quantity is 0, so its row is 0; a quantity cleared to nothing on a row
|
||||
/// without a price leaves the product nothing to multiply, and it is 0 too, not 1.
|
||||
#[test]
|
||||
fn an_order_form_with_blank_drop_down_quantities_totals_only_the_chosen_rows() {
|
||||
let tx = |name: &str, y: u32, rest: &str| {
|
||||
format!("<< /Type /Annot /Subtype /Widget /FT /Tx /T ({name}) /Rect [250 {y} 350 {}] /P 3 0 R {rest} >>", y + 20)
|
||||
};
|
||||
let qty = |name: &str, y: u32| {
|
||||
format!(
|
||||
"<< /Type /Annot /Subtype /Widget /FT /Ch /Ff 393216 /T ({name}) /Opt [( ) (1) (2) (3)] /V ( ) /Rect [50 {y} 150 {}] /P 3 0 R >>",
|
||||
y + 20
|
||||
)
|
||||
};
|
||||
let prd = |row: u32| {
|
||||
format!("/AA << /C << /S /JavaScript /JS (AFSimple_Calculate\\(\"PRD\", new Array \\(\"QTY {row}\", \"price {row}\"\\)\\);) >> >>")
|
||||
};
|
||||
let objs: Vec<String> = vec![
|
||||
"<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(),
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(),
|
||||
"<< /Type /Page /Parent 2 0 R /Annots [5 0 R 6 0 R 7 0 R 8 0 R 9 0 R 10 0 R 11 0 R 12 0 R 13 0 R 14 0 R] >>".into(),
|
||||
"<< /Fields [5 0 R 6 0 R 7 0 R 8 0 R 9 0 R 10 0 R 11 0 R 12 0 R 13 0 R 14 0 R] /DA (/Helv 0 Tf 0 g) >>".into(),
|
||||
qty("QTY 0", 700),
|
||||
tx("price 0", 700, "/V (605)"),
|
||||
tx("Total 0", 700, &format!("/V (0) {}", prd(0))),
|
||||
qty("QTY 1", 660),
|
||||
tx("price 1", 660, "/V (780)"),
|
||||
tx("Total 1", 660, &format!("/V (0) {}", prd(1))),
|
||||
qty("QTY 2", 620),
|
||||
tx("price 2", 620, ""),
|
||||
tx("Total 2", 620, &format!("/V (0) {}", prd(2))),
|
||||
tx(
|
||||
"Total",
|
||||
580,
|
||||
r#"/V (0) /AA << /C << /S /JavaScript /JS (AFSimple_Calculate\("SUM", new Array \("Total 0", "Total 1", "Total 2"\)\);) >> >>"#,
|
||||
),
|
||||
];
|
||||
let mut doc = document(&objs);
|
||||
let totals = |doc: &Document| {
|
||||
let all = fields(doc);
|
||||
["Total 0", "Total 1", "Total 2", "Total"].map(|n| field(&all, n).value.first().cloned().unwrap_or_default())
|
||||
};
|
||||
recalculate(&mut doc).unwrap();
|
||||
assert_eq!(totals(&doc), ["0", "0", "0", "0"], "every quantity blank: a single space is worth 0");
|
||||
set_value(&mut doc, "QTY 0", &FieldValue::Text("2".into())).unwrap();
|
||||
assert_eq!(totals(&doc), ["1210", "0", "0", "1210"], "only the chosen row");
|
||||
set_value(&mut doc, "QTY 2", &FieldValue::Text(String::new())).unwrap();
|
||||
assert_eq!(totals(&doc), ["1210", "0", "0", "1210"], "a quantity cleared on a row without a price");
|
||||
let doc = reopen(&doc);
|
||||
assert_eq!(totals(&doc), ["1210", "0", "0", "1210"], "kept across a save");
|
||||
}
|
||||
|
||||
/// `/CO` as other tools leave it: a calculated field missing, a field without a calculation, an
|
||||
/// entry repeated, a reference to nothing and a number. The order reads around them, and setting
|
||||
/// the order writes `/CO` afresh.
|
||||
@@ -2988,20 +3151,22 @@ fn recalc_chain_where_script_changes_checkbox() {
|
||||
ScriptResult {
|
||||
rc: true,
|
||||
value: "calc1".into(),
|
||||
value_set: true,
|
||||
changes: vec![FieldChange {
|
||||
name: "agree".into(),
|
||||
value: Some(vec!["Yes".into()]),
|
||||
read_only: None,
|
||||
required: None,
|
||||
display: None,
|
||||
rect: None,
|
||||
}],
|
||||
message: None,
|
||||
}
|
||||
} else if script == "read_box" {
|
||||
let box_val = fields.iter().find(|f| f.name == "agree").and_then(|f| f.value.first()).cloned().unwrap_or_default();
|
||||
ScriptResult { rc: true, value: format!("box_was_{box_val}"), changes: Vec::new(), message: None }
|
||||
ScriptResult { rc: true, value: format!("box_was_{box_val}"), value_set: true, changes: Vec::new(), message: None }
|
||||
} else {
|
||||
ScriptResult { rc: true, value: String::new(), changes: Vec::new(), message: None }
|
||||
ScriptResult { rc: true, value: String::new(), value_set: false, changes: Vec::new(), message: None }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3022,6 +3187,61 @@ fn recalc_chain_where_script_changes_checkbox() {
|
||||
assert_eq!(field(&all, "result").value, ["box_was_Yes"], "second recalc saw the normalized checkbox value");
|
||||
}
|
||||
|
||||
/// A calculation returning a combo option's display text stores the option's export value in /V
|
||||
/// and selects it in /I, as choosing it does.
|
||||
#[test]
|
||||
fn a_calculated_combo_stores_the_export_value_of_the_option_it_names() {
|
||||
struct Pick;
|
||||
impl Scripts for Pick {
|
||||
fn run(&mut self, _event: FieldEvent, script: &str, _target: &Field, _value: &str, _fields: &[Field]) -> ScriptResult {
|
||||
ScriptResult { rc: true, value: script.into(), value_set: true, changes: Vec::new(), message: None }
|
||||
}
|
||||
}
|
||||
let mut doc = one_page();
|
||||
let kind = NewField::Combo { options: vec!["ca".into(), "fr".into()], editable: false };
|
||||
add_field(&mut doc, 0, [10.0, 10.0, 100.0, 30.0], &kind, Some("country")).unwrap();
|
||||
let obj = field(&fields(&doc), "country").obj;
|
||||
let pair = |e: &str, d: &str| Object::Array(vec![Object::String(PdfString::text(e)), Object::String(PdfString::text(d))]);
|
||||
doc.update_dict(obj, |d| d.set(b"Opt".to_vec(), Object::Array(vec![pair("ca", "Canada"), pair("fr", "France")]))).unwrap();
|
||||
set_field_script(&mut doc, "country", "calculate", Some("France")).unwrap();
|
||||
assert_eq!(recalculate_with(&mut doc, &mut Pick).unwrap(), 1);
|
||||
let dict = doc.get(obj).as_dict().cloned().unwrap();
|
||||
assert_eq!(dict.get(b"V").cloned(), Some(Object::String(PdfString::text("fr"))));
|
||||
assert_eq!(dict.get(b"I").cloned(), Some(Object::Array(vec![Object::Int(1)])));
|
||||
assert_eq!(field(&fields(&doc), "country").value, ["fr"]);
|
||||
assert_eq!(recalculate_with(&mut doc, &mut Pick).unwrap(), 0, "the display text names the value it already has");
|
||||
}
|
||||
|
||||
/// An export value names its own option even when an earlier option shows that text, whether a
|
||||
/// calculation or the user sets it.
|
||||
#[test]
|
||||
fn an_export_value_wins_over_an_earlier_options_display_text() {
|
||||
struct Pick;
|
||||
impl Scripts for Pick {
|
||||
fn run(&mut self, _event: FieldEvent, script: &str, _target: &Field, _value: &str, _fields: &[Field]) -> ScriptResult {
|
||||
ScriptResult { rc: true, value: script.into(), value_set: true, changes: Vec::new(), message: None }
|
||||
}
|
||||
}
|
||||
let mut doc = one_page();
|
||||
let pair = |e: &str, d: &str| Object::Array(vec![Object::String(PdfString::text(e)), Object::String(PdfString::text(d))]);
|
||||
let mut objs = Vec::new();
|
||||
for (name, y) in [("calculated", 10.0), ("chosen", 40.0)] {
|
||||
let kind = NewField::Combo { options: vec!["ca".into(), "fr".into()], editable: false };
|
||||
add_field(&mut doc, 0, [10.0, y, 100.0, y + 20.0], &kind, Some(name)).unwrap();
|
||||
let obj = field(&fields(&doc), name).obj;
|
||||
doc.update_dict(obj, |d| d.set(b"Opt".to_vec(), Object::Array(vec![pair("ca", "fr"), pair("fr", "France")]))).unwrap();
|
||||
objs.push(obj);
|
||||
}
|
||||
set_field_script(&mut doc, "calculated", "calculate", Some("fr")).unwrap();
|
||||
recalculate_with(&mut doc, &mut Pick).unwrap();
|
||||
set_value(&mut doc, "chosen", &FieldValue::Choice(vec!["fr".into()])).unwrap();
|
||||
for obj in objs {
|
||||
let dict = doc.get(obj).as_dict().cloned().unwrap();
|
||||
assert_eq!(dict.get(b"V").cloned(), Some(Object::String(PdfString::text("fr"))));
|
||||
assert_eq!(dict.get(b"I").cloned(), Some(Object::Array(vec![Object::Int(1)])));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn partial_appearance_keeps_custom_default_appearance_and_font_resources() {
|
||||
let mut doc = fixture();
|
||||
@@ -5706,3 +5926,35 @@ fn locked_button_export_edits_leave_the_document_unchanged() {
|
||||
assert_eq!(write_incremental(&doc, &SaveOptions::default()).unwrap(), before);
|
||||
}
|
||||
}
|
||||
|
||||
/// A `/MK /BC` or `/BG` written `[1 0 0 null]` is CMYK with the null as 0, as annotation `/C`
|
||||
/// colours are read (PDFBOX-2699), not RGB from the three numbers left; three numbers stay RGB.
|
||||
#[test]
|
||||
fn a_four_entry_mk_colour_with_a_null_is_cmyk_with_zero() {
|
||||
let widget = |name: &str, mk: &str| {
|
||||
format!("<< /Type /Annot /Subtype /Widget /FT /Btn /T ({name}) /Rect [50 700 70 720] /P 3 0 R /MK << {mk} >> /BS << /W 1 /S /S >> >>")
|
||||
};
|
||||
let objs: Vec<String> = vec![
|
||||
"<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(),
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(),
|
||||
"<< /Type /Page /Parent 2 0 R /Annots [5 0 R 6 0 R] >>".into(),
|
||||
"<< /Fields [5 0 R 6 0 R] >>".into(),
|
||||
widget("cmyk", "/BG [0 0 1 null] /BC [1 0 0 null]"),
|
||||
widget("rgb", "/BG [0 0 1] /BC [1 0 0]"),
|
||||
];
|
||||
let mut doc = document(&objs);
|
||||
let off = |doc: &mut Document, name: &str| {
|
||||
redraw_field(doc, name).unwrap();
|
||||
let all = fields(doc);
|
||||
let w = field(&all, name).widgets[0].obj;
|
||||
let wd = doc.get(w).as_dict().cloned().unwrap();
|
||||
let n = doc.resolve(wd.get(b"AP").unwrap().as_dict().unwrap().get(b"N").unwrap());
|
||||
let r = n.as_dict().unwrap().reference(b"Off").expect("an Off appearance");
|
||||
let Object::Stream(s) = &*doc.get(r) else { panic!("Off is a stream") };
|
||||
String::from_utf8_lossy(&s.decoded().unwrap()).into_owned()
|
||||
};
|
||||
let cmyk = off(&mut doc, "cmyk");
|
||||
assert!(cmyk.contains("0 0 1 0 k") && cmyk.contains("1 0 0 0 K"), "CMYK background and border: {cmyk}");
|
||||
let rgb = off(&mut doc, "rgb");
|
||||
assert!(rgb.contains("0 0 1 rg") && rgb.contains("1 0 0 RG"), "three numbers stay RGB: {rgb}");
|
||||
}
|
||||
|
||||
@@ -163,6 +163,11 @@ pub fn recalculate_with(doc: &mut Document, scripts: &mut dyn Scripts) -> Result
|
||||
let current = f.value.first().cloned().unwrap_or_default();
|
||||
let v = if let Some(js) = &f.actions.scripts.calculate {
|
||||
let r = scripts.run(FieldEvent::Calculate, js, &f, ¤t, &all);
|
||||
// A script may set its own field through the field object (`getField("Total").value
|
||||
// = …`) rather than through `event.value`. `apply_changes` leaves the event's own
|
||||
// field to the event, so that value is the result unless the script also assigned
|
||||
// `event.value`, even the value it already had.
|
||||
let own = r.changes.iter().find(|c| c.name == f.name).and_then(|c| c.value.as_ref()).map(|v| v.first().cloned().unwrap_or_default());
|
||||
scripting::apply_changes(doc, &r.changes, &f.name)?;
|
||||
if !r.changes.is_empty() {
|
||||
all = fields(doc);
|
||||
@@ -170,13 +175,37 @@ pub fn recalculate_with(doc: &mut Document, scripts: &mut dyn Scripts) -> Result
|
||||
if !r.rc {
|
||||
continue;
|
||||
}
|
||||
r.value
|
||||
match own {
|
||||
Some(v) if !r.value_set => v,
|
||||
_ => r.value,
|
||||
}
|
||||
} else {
|
||||
let Some(v) = af::calculate(&f.actions.calculate, &lookup) else { continue };
|
||||
v
|
||||
};
|
||||
// A combo box result naming an option, by export value or display text, is stored as that
|
||||
// option's export value (the first element of an /Opt pair, ISO 32000-2 Table 234), as
|
||||
// `write_value` stores a choice, so /V, /I and exported form data agree.
|
||||
let combo = f.kind == FieldKind::Combo;
|
||||
let matched = if combo { option_named(&f, &v) } else { None };
|
||||
let v = match matched.and_then(|i| f.options.get(i)) {
|
||||
Some((export, _)) => export.clone(),
|
||||
None => v,
|
||||
};
|
||||
if current != v && matches!(f.kind, FieldKind::Text | FieldKind::Combo) {
|
||||
doc.update_dict(f.obj, |d| d.set(b"V".to_vec(), PdfString::text(&v)))?;
|
||||
// A combo box's /I (its option indices, ISO 32000-2 Table 234) follows the value, as
|
||||
// `write_value` keeps it, so the selection kept never disagrees with the value.
|
||||
let picked = matched.and_then(|i| i64::try_from(i).ok());
|
||||
doc.update_dict(f.obj, |d| {
|
||||
d.set(b"V".to_vec(), PdfString::text(&v));
|
||||
match picked {
|
||||
Some(i) if combo => d.set(b"I".to_vec(), Object::Array(vec![Object::Int(i)])),
|
||||
_ if combo => {
|
||||
d.remove(b"I");
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
})?;
|
||||
redraw(doc, &f, std::slice::from_ref(&v), scripts)?;
|
||||
if let Some(target) = all.iter_mut().find(|x| x.obj == obj) {
|
||||
target.value = vec![v];
|
||||
@@ -187,6 +216,12 @@ pub fn recalculate_with(doc: &mut Document, scripts: &mut dyn Scripts) -> Result
|
||||
Ok(changed)
|
||||
}
|
||||
|
||||
/// The index of the choice option `v` names: the option whose export value it is, else the first
|
||||
/// whose display text it is, so a display text never shadows a later option's export value.
|
||||
fn option_named(f: &Field, v: &str) -> Option<usize> {
|
||||
f.options.iter().position(|(e, _)| e == v).or_else(|| f.options.iter().position(|(_, d)| d == v))
|
||||
}
|
||||
|
||||
/// The fields whose calculation differs between two readings of a form, matched by field object
|
||||
/// and named as in `after`: the formulas an edit rewrote, such as a rename's.
|
||||
pub fn calculations_changed(before: &[Field], after: &[Field]) -> Vec<String> {
|
||||
@@ -280,7 +315,7 @@ pub(crate) fn write_value(doc: &mut Document, f: &Field, value: &FieldValue, scr
|
||||
// Accept export values or display texts; free text only in editable combo boxes.
|
||||
let mut exports = Vec::new();
|
||||
for v in &vals {
|
||||
match f.options.iter().find(|(e, d)| e == v || d == v) {
|
||||
match option_named(f, v).and_then(|i| f.options.get(i)) {
|
||||
Some((e, _)) => exports.push(e.clone()),
|
||||
None if f.kind == FieldKind::Combo && f.has(flags::EDIT) => exports.push(v.clone()),
|
||||
None if f.options.is_empty() => exports.push(v.clone()),
|
||||
|
||||
@@ -94,6 +94,36 @@ pub(crate) fn field_object(ctx: &mut Context, name: &str) -> JsObject {
|
||||
}
|
||||
function(ctx, NativeFunction::from_copy_closure_with_captures(set, n.clone()))
|
||||
};
|
||||
let rect_get = getter!(ctx, n, |f, c| match f.rect {
|
||||
Some(rect) => JsArray::from_iter(rect.into_iter().map(JsValue::from).collect::<Vec<_>>(), c).into(),
|
||||
None => JsValue::null(),
|
||||
});
|
||||
let rect_set = {
|
||||
fn set(_: &JsValue, args: &[JsValue], name: &JsString, c: &mut Context) -> JsResult<JsValue> {
|
||||
let value = arg(args, 0);
|
||||
let object = value.as_object().filter(|o| o.is_array()).ok_or_else(|| error("rect must be an array of four finite numbers"))?;
|
||||
let array = JsArray::from_object(object.clone())?;
|
||||
if array.length(c)? != 4 {
|
||||
return Err(error("rect must be an array of four finite numbers"));
|
||||
}
|
||||
let mut rect = [0.0; 4];
|
||||
for (i, coordinate) in rect.iter_mut().enumerate() {
|
||||
*coordinate = array.get(i as u64, c)?.to_number(c)?;
|
||||
}
|
||||
if !rect.iter().all(|coordinate| coordinate.is_finite()) {
|
||||
return Err(error("rect coordinates must be finite"));
|
||||
}
|
||||
let width = (rect[2] - rect[0]).abs();
|
||||
let height = (rect[3] - rect[1]).abs();
|
||||
if !width.is_finite() || !height.is_finite() || width < 4.0 || height < 4.0 {
|
||||
return Err(error("rect must be at least 4 points wide and high"));
|
||||
}
|
||||
let rect = [rect[0].min(rect[2]), rect[1].min(rect[3]), rect[0].max(rect[2]), rect[1].max(rect[3])];
|
||||
write(c, name, |f| f.rect = Some(rect))?;
|
||||
Ok(JsValue::undefined())
|
||||
}
|
||||
function(ctx, NativeFunction::from_copy_closure_with_captures(set, n.clone()))
|
||||
};
|
||||
|
||||
fn get_item_at(_: &JsValue, args: &[JsValue], name: &JsString, c: &mut Context) -> JsResult<JsValue> {
|
||||
let f = read(c, name)?;
|
||||
@@ -150,6 +180,7 @@ pub(crate) fn field_object(ctx: &mut Context, name: &str) -> JsObject {
|
||||
.accessor(js_string!("currentValueIndices"), Some(indices), None, rw)
|
||||
.accessor(js_string!("textColor"), Some(text_color_get), Some(text_color_set), rw)
|
||||
.accessor(js_string!("fillColor"), Some(fill_color_get), Some(fill_color_set), rw)
|
||||
.accessor(js_string!("rect"), Some(rect_get), Some(rect_set), rw)
|
||||
.function(get_item_at, js_string!("getItemAt"), 2)
|
||||
.function(is_box_checked, js_string!("isBoxChecked"), 1)
|
||||
.function(check_this_box, js_string!("checkThisBox"), 2)
|
||||
|
||||
@@ -245,4 +245,42 @@ mod tests {
|
||||
assert_eq!(num_text(-1e20), "-100000000000000000000");
|
||||
assert_eq!(num_text(f64::MAX).len(), 309);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decode_xml_and_html_entities() {
|
||||
let eval = |script: &str| {
|
||||
let root = XfaNode::default();
|
||||
let out = run_formcalc(script, &XfaEvent::default(), &XfaDoc::default(), &root, Limits::default());
|
||||
assert!(out.error.is_none(), "{:?}", out.error);
|
||||
out.result.unwrap_or_default()
|
||||
};
|
||||
|
||||
// `'` in both xml and html
|
||||
assert_eq!(eval(r#"Decode("It's <ok> & "fine"", "xml")"#), "It's <ok> & \"fine\"");
|
||||
assert_eq!(eval(r#"Decode("It's", "html")"#), "It's");
|
||||
|
||||
// Decimal and hex numeric character references (case-insensitive #x/#X and hex digits, leading zeros)
|
||||
assert_eq!(eval(r#"Decode("ABCDe€😀", "xml")"#), "ABCDe€😀");
|
||||
assert_eq!(eval(r#"Decode("ABCé", "html")"#), "ABCé");
|
||||
|
||||
// Invalid / surrogate / out-of-range / zero / malformed numeric references stay literal without panicking
|
||||
assert_eq!(
|
||||
eval(r#"Decode("� � � � � &#; &#x; A G; &;", "xml")"#),
|
||||
"� � � � � &#; &#x; A G; &;"
|
||||
);
|
||||
|
||||
// Single-pass decoding: `&lt;` and `&lt;` must decode to `<`, never `<`
|
||||
assert_eq!(eval(r#"Decode("&lt; &#65; &lt; &apos;", "xml")"#), "< A < '");
|
||||
assert_eq!(eval(r#"Decode("&nbsp; &eacute;", "html")"#), " é");
|
||||
|
||||
// HTML named entities decode in "html" mode but remain literal in "xml" mode
|
||||
assert_eq!(eval(r#"Decode("café ©€—αΩ♥", "html")"#), "café\u{00A0}©€—αΩ♥");
|
||||
assert_eq!(eval(r#"Decode("café ©€", "xml")"#), "café ©€");
|
||||
// Case sensitivity of HTML named entities (`É` vs `é`, `″` vs `′`, `‡` vs `†`)
|
||||
assert_eq!(eval(r#"Decode("Éé″′‡†&bogus;", "html")"#), "Éé″′‡†&bogus;");
|
||||
// Non-ASCII characters after `&` or `&#` and long runs of `&` without `;`
|
||||
assert_eq!(eval(r#"Decode("&é; &#é; &#xé; &é", "html")"#), "&é; &#é; &#xé; &é");
|
||||
let amps = "&".repeat(5_000);
|
||||
assert_eq!(eval(&format!(r#"Decode("{amps}'", "xml")"#)), format!("{amps}'"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ use super::ast::Expr;
|
||||
use super::dates::{MAX_DAYS, civil_from_days, days_from_civil, format_date, parse_date};
|
||||
use super::parser::parse;
|
||||
use super::value::{Val, fixed, is_numeric_text, parse_num};
|
||||
use super::words::word_num;
|
||||
use super::words::{decode_entities, word_num};
|
||||
use super::{Interp, MAX_STRING, R, STRING_TOO_LONG, XfaKind, is_limit};
|
||||
|
||||
impl Interp<'_> {
|
||||
@@ -200,7 +200,8 @@ impl Interp<'_> {
|
||||
let kind = if args.len() > 1 { self.arg_str(args, 1)?.to_ascii_lowercase() } else { "url".into() };
|
||||
Val::Str(match (lower.as_str(), kind.as_str()) {
|
||||
("encode", "html" | "xml") => s.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """),
|
||||
("decode", "html" | "xml") => s.replace("<", "<").replace(">", ">").replace(""", "\"").replace("&", "&"),
|
||||
("decode", "xml") => decode_entities(&s, false),
|
||||
("decode", "html") => decode_entities(&s, true),
|
||||
("encode", _) => s
|
||||
.bytes()
|
||||
.map(|b| if b.is_ascii_alphanumeric() || b"-_.~".contains(&b) { (b as char).to_string() } else { format!("%{b:02X}") })
|
||||
|
||||
@@ -292,15 +292,23 @@ impl Interp<'_> {
|
||||
}
|
||||
_ => Ok(Val::Null),
|
||||
},
|
||||
Val::Layout => match m.as_str() {
|
||||
"page" | "abspage" => Ok(Val::Num(self.h.doc.page as f64 + if m == "page" { 1.0 } else { 0.0 })),
|
||||
"pagecount" | "abspagecount" => Ok(Val::Num(self.h.doc.page_count as f64)),
|
||||
"relayout" | "relayoutpagearea" => {
|
||||
self.h.push(XfaEffect::Relayout);
|
||||
Ok(Val::Null)
|
||||
Val::Layout => {
|
||||
// No layout method reads its arguments, but each is evaluated once, for what it
|
||||
// does (a message box in an argument still shows), as the other objects' are.
|
||||
for i in 0..args.len() {
|
||||
self.arg(args, i)?;
|
||||
}
|
||||
_ => Ok(Val::Num(0.0)),
|
||||
},
|
||||
match m.as_str() {
|
||||
// On screen every page is a sheet of its own (see the JavaScript `sheet`).
|
||||
"page" | "abspage" | "sheet" => Ok(Val::Num(self.h.doc.page as f64 + if m == "page" { 1.0 } else { 0.0 })),
|
||||
"pagecount" | "abspagecount" | "sheetcount" => Ok(Val::Num(self.h.doc.page_count as f64)),
|
||||
"relayout" | "relayoutpagearea" => {
|
||||
self.h.push(XfaEffect::Relayout);
|
||||
Ok(Val::Null)
|
||||
}
|
||||
_ => Ok(Val::Num(0.0)),
|
||||
}
|
||||
}
|
||||
Val::Xfa => match m.as_str() {
|
||||
"resolvenode" | "resolvenodes" => {
|
||||
let s = self.arg_str(args, 0)?;
|
||||
|
||||
+123
-44
@@ -49,52 +49,12 @@ pub(super) fn lex(src: &str) -> Result<Vec<Token>, String> {
|
||||
}
|
||||
}
|
||||
'"' => {
|
||||
let mut s = String::new();
|
||||
i += 1;
|
||||
loop {
|
||||
match chars.get(i) {
|
||||
None => return Err(format!("line {line}: unterminated string")),
|
||||
Some('"') if chars.get(i + 1) == Some(&'"') => {
|
||||
s.push('"');
|
||||
i += 2;
|
||||
}
|
||||
Some('"') => {
|
||||
i += 1;
|
||||
break;
|
||||
}
|
||||
Some(&ch) => {
|
||||
if ch == '\n' {
|
||||
line += 1;
|
||||
}
|
||||
s.push(ch);
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
if s.len() > MAX_STRING {
|
||||
return Err(format!("line {line}: a string is too long"));
|
||||
}
|
||||
}
|
||||
out.push(Token { tok: Tok::Str(s), line });
|
||||
let tok_line = line;
|
||||
let s = lex_string(&chars, &mut i, &mut line)?;
|
||||
out.push(Token { tok: Tok::Str(s), line: tok_line });
|
||||
}
|
||||
c if c.is_ascii_digit() || (c == '.' && chars.get(i + 1).is_some_and(char::is_ascii_digit)) => {
|
||||
let start = i;
|
||||
while i < chars.len() && (chars[i].is_ascii_digit() || (chars[i] == '.' && chars.get(i + 1) != Some(&'.'))) {
|
||||
i += 1;
|
||||
}
|
||||
if i < chars.len() && (chars[i] == 'e' || chars[i] == 'E') {
|
||||
let mut j = i + 1;
|
||||
if j < chars.len() && (chars[j] == '+' || chars[j] == '-') {
|
||||
j += 1;
|
||||
}
|
||||
if j < chars.len() && chars[j].is_ascii_digit() {
|
||||
i = j;
|
||||
while i < chars.len() && chars[i].is_ascii_digit() {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
let text: String = chars[start..i].iter().collect();
|
||||
let n: f64 = text.parse().map_err(|_| format!("line {line}: bad number {text}"))?;
|
||||
let n = lex_number(&chars, &mut i, line)?;
|
||||
out.push(Token { tok: Tok::Num(n), line });
|
||||
}
|
||||
'!' => {
|
||||
@@ -127,3 +87,122 @@ pub(super) fn lex(src: &str) -> Result<Vec<Token>, String> {
|
||||
out.push(Token { tok: Tok::Eof, line });
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn hex_u32(digits: &[char]) -> Option<u32> {
|
||||
let mut v = 0u32;
|
||||
for &c in digits {
|
||||
v = (v << 4) | c.to_digit(16)?;
|
||||
}
|
||||
Some(v)
|
||||
}
|
||||
|
||||
/// FormCalc string escape (`\uXXXX` or `\UXXXXXXXX`, XFA 3.3 part 8 p. 1054); any other `\` stays literal.
|
||||
fn unicode_escape(chars: &[char], at: usize) -> Option<(char, usize)> {
|
||||
if chars.get(at) != Some(&'\\') {
|
||||
return None;
|
||||
}
|
||||
match chars.get(at + 1)? {
|
||||
'u' => {
|
||||
let hi = hex_u32(chars.get(at + 2..at + 6)?)?;
|
||||
if (0xD800..=0xDBFF).contains(&hi)
|
||||
&& chars.get(at + 6..at + 8) == Some(&['\\', 'u'])
|
||||
&& let Some(lo) = chars.get(at + 8..at + 12).and_then(hex_u32).filter(|lo| (0xDC00..=0xDFFF).contains(lo))
|
||||
{
|
||||
let scalar = 0x1_0000 + ((hi - 0xD800) << 10) + (lo - 0xDC00);
|
||||
return Some((char::from_u32(scalar)?, 12));
|
||||
}
|
||||
Some((char::from_u32(hi)?, 6))
|
||||
}
|
||||
'U' => {
|
||||
let code = hex_u32(chars.get(at + 2..at + 10)?)?;
|
||||
Some((char::from_u32(code)?, 10))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn lex_string(chars: &[char], i: &mut usize, line: &mut usize) -> Result<String, String> {
|
||||
let mut s = String::new();
|
||||
*i += 1;
|
||||
loop {
|
||||
match chars.get(*i) {
|
||||
None => return Err(format!("line {line}: unterminated string")),
|
||||
Some('"') if chars.get(*i + 1) == Some(&'"') => {
|
||||
s.push('"');
|
||||
*i += 2;
|
||||
}
|
||||
Some('"') => {
|
||||
*i += 1;
|
||||
return Ok(s);
|
||||
}
|
||||
Some(&ch) => {
|
||||
if let Some((decoded, step)) = unicode_escape(chars, *i) {
|
||||
s.push(decoded);
|
||||
*i += step;
|
||||
} else {
|
||||
if ch == '\n' {
|
||||
*line += 1;
|
||||
}
|
||||
s.push(ch);
|
||||
*i += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
if s.len() > MAX_STRING {
|
||||
return Err(format!("line {line}: a string is too long"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `c` may start a FormCalc identifier.
|
||||
fn is_ident_start(c: char) -> bool {
|
||||
c.is_alphabetic() || c == '_' || c == '$'
|
||||
}
|
||||
|
||||
/// End index of a numeric exponent starting at `at` (`e`/`E`, optional sign, digits), or `None`
|
||||
/// if no valid exponent starts there or if identifier characters immediately follow the digits.
|
||||
fn exponent_end(chars: &[char], at: usize) -> Option<usize> {
|
||||
if !matches!(chars.get(at), Some('e' | 'E')) {
|
||||
return None;
|
||||
}
|
||||
let mut j = at + 1;
|
||||
if matches!(chars.get(j), Some('+' | '-')) {
|
||||
j += 1;
|
||||
}
|
||||
if !chars.get(j).is_some_and(char::is_ascii_digit) {
|
||||
return None;
|
||||
}
|
||||
while chars.get(j).is_some_and(char::is_ascii_digit) {
|
||||
j += 1;
|
||||
}
|
||||
if chars.get(j).is_some_and(|&c| c.is_alphanumeric() || c == '_' || c == '$') {
|
||||
return None;
|
||||
}
|
||||
Some(j)
|
||||
}
|
||||
|
||||
/// Scan a FormCalc number literal starting at `*i`, stopping before `.member` or `..` while
|
||||
/// rejecting malformed multi-dot literals such as `1.2.3`.
|
||||
fn lex_number(chars: &[char], i: &mut usize, line: usize) -> Result<f64, String> {
|
||||
let start = *i;
|
||||
let mut seen_dot = false;
|
||||
while *i < chars.len() {
|
||||
let next = chars.get(*i + 1).copied();
|
||||
let next_is_member = next.is_some_and(is_ident_start) && exponent_end(chars, *i + 1).is_none();
|
||||
if chars[*i].is_ascii_digit() {
|
||||
*i += 1;
|
||||
} else if chars[*i] == '.' && !seen_dot && next != Some('.') && !next_is_member {
|
||||
seen_dot = true;
|
||||
*i += 1;
|
||||
} else if chars[*i] == '.' && seen_dot && next.is_some_and(|c| c.is_ascii_digit()) {
|
||||
return Err(format!("line {line}: bad number"));
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if let Some(end) = exponent_end(chars, *i) {
|
||||
*i = end;
|
||||
}
|
||||
let text: String = chars[start..*i].iter().collect();
|
||||
text.parse().map_err(|_| format!("line {line}: bad number {text}"))
|
||||
}
|
||||
|
||||
@@ -341,10 +341,7 @@ impl Parser {
|
||||
Ok(Expr::Neg(Box::new(self.unary()?)))
|
||||
} else if self.eat_op("+") {
|
||||
self.unary()
|
||||
} else if self.eat_kw("not") || matches!(self.peek(), Tok::Ident(w) if w == "!") {
|
||||
if matches!(self.peek(), Tok::Ident(w) if w == "!") {
|
||||
self.at += 1;
|
||||
}
|
||||
} else if self.eat_kw("not") || self.eat_kw("!") {
|
||||
Ok(Expr::Not(Box::new(self.unary()?)))
|
||||
} else {
|
||||
self.postfix()
|
||||
@@ -449,3 +446,31 @@ pub(super) fn parse(src: &str) -> Result<Vec<Stmt>, String> {
|
||||
t => Err(format!("line {}: unexpected {}", p.line(), describe(t))),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn unary_not_does_not_swallow_following_bang() {
|
||||
assert_eq!(parse("not !1"), Ok(vec![Stmt::Expr(Expr::Not(Box::new(Expr::Not(Box::new(Expr::Num(1.0))))))]));
|
||||
assert_eq!(parse("not !flag"), Ok(vec![Stmt::Expr(Expr::Not(Box::new(Expr::Not(Box::new(Expr::Ident("flag".into()))))))]));
|
||||
assert_eq!(parse("!!1"), Ok(vec![Stmt::Expr(Expr::Not(Box::new(Expr::Not(Box::new(Expr::Num(1.0))))))]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn string_literals_decode_xfa_unicode_escapes_and_keep_other_backslashes() {
|
||||
assert_eq!(parse(r#""\u0041\u20ac\U00000042\U0001F600""#), Ok(vec![Stmt::Expr(Expr::Str("A\u{20ac}B\u{1F600}".into()))]));
|
||||
assert_eq!(parse(r#""\uD83D\uDE00""#), Ok(vec![Stmt::Expr(Expr::Str("\u{1F600}".into()))]));
|
||||
assert_eq!(parse(r#""C:\temp\new\u12""#), Ok(vec![Stmt::Expr(Expr::Str(r"C:\temp\new\u12".into()))]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn number_literals_stop_before_second_dot_for_member_access() {
|
||||
assert_eq!(parse("1.5.rawValue"), Ok(vec![Stmt::Expr(Expr::Member(Box::new(Expr::Num(1.5)), "rawValue".into()))]));
|
||||
assert_eq!(parse("1.rawValue"), Ok(vec![Stmt::Expr(Expr::Member(Box::new(Expr::Num(1.0)), "rawValue".into()))]));
|
||||
assert_eq!(parse("1.e2foo"), Ok(vec![Stmt::Expr(Expr::Member(Box::new(Expr::Num(1.0)), "e2foo".into()))]));
|
||||
assert_eq!(parse("1.e2"), Ok(vec![Stmt::Expr(Expr::Num(100.0))]));
|
||||
assert!(parse("1.2.3").is_err(), "a second decimal point followed by digits is a bad number");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -73,3 +73,140 @@ pub(super) fn word_num(n: f64, cents: bool) -> String {
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Decode XML (`html == false`) or HTML (`html == true`) character and entity references in a
|
||||
/// single pass so `&lt;` becomes `<` rather than `<`, and invalid or unrecognized
|
||||
/// references remain literal without panicking.
|
||||
///
|
||||
/// When `html` is `false`, only the five predefined XML entities (`<`, `>`, `&`,
|
||||
/// `"`, `'`) and numeric character references (`&#...;`, `&#x...;`, `&#X...;`) are
|
||||
/// decoded. When `html` is `true`, W3C HTML 4 / XHTML 1.0 named entities are decoded as well.
|
||||
pub(super) fn decode_entities(s: &str, html: bool) -> String {
|
||||
let mut out = String::with_capacity(s.len());
|
||||
let mut rest = s;
|
||||
while let Some(at) = rest.find('&') {
|
||||
out.push_str(rest.get(..at).unwrap_or_default());
|
||||
rest = rest.get(at..).unwrap_or_default();
|
||||
match entity_at(rest, html) {
|
||||
Some((c, len)) => {
|
||||
out.push(c);
|
||||
rest = rest.get(len..).unwrap_or_default();
|
||||
}
|
||||
None => {
|
||||
out.push('&');
|
||||
rest = rest.get(1..).unwrap_or_default();
|
||||
}
|
||||
}
|
||||
}
|
||||
out.push_str(rest);
|
||||
out
|
||||
}
|
||||
|
||||
/// Parse a character reference starting at the leading `&` of `s`, returning the decoded `char`
|
||||
/// and the byte length of the reference (including `&` and `;`).
|
||||
fn entity_at(s: &str, html: bool) -> Option<(char, usize)> {
|
||||
if let Some(body) = s.strip_prefix("&#") {
|
||||
let (radix, digits, prefix_len) = match body.strip_prefix(['x', 'X']) {
|
||||
Some(hex) => (16u32, hex, 3usize),
|
||||
None => (10u32, body, 2usize),
|
||||
};
|
||||
let mut value = 0u32;
|
||||
let mut any_digit = false;
|
||||
for (i, c) in digits.char_indices() {
|
||||
match c.to_digit(radix) {
|
||||
Some(d) => {
|
||||
any_digit = true;
|
||||
value = value.checked_mul(radix)?.checked_add(d)?;
|
||||
if value > 0x10_FFFF {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
None if c == ';' && any_digit && value != 0 => {
|
||||
return Some((char::from_u32(value)?, prefix_len + i + 1));
|
||||
}
|
||||
None => return None,
|
||||
}
|
||||
}
|
||||
return None;
|
||||
}
|
||||
let body = s.strip_prefix('&')?;
|
||||
let semi = body.bytes().take(9).position(|b| b == b';')?;
|
||||
let name = body.get(..semi).filter(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_alphanumeric()))?;
|
||||
let ch = match name {
|
||||
"lt" => '<',
|
||||
"gt" => '>',
|
||||
"amp" => '&',
|
||||
"quot" => '"',
|
||||
"apos" => '\'',
|
||||
_ if html => html_named_entity(name)?,
|
||||
_ => return None,
|
||||
};
|
||||
Some((ch, 1 + semi + 1))
|
||||
}
|
||||
|
||||
/// Look up a W3C HTML 4 / XHTML 1.0 named entity (excluding the five XML entities).
|
||||
fn html_named_entity(name: &str) -> Option<char> {
|
||||
if let Some(idx) = LATIN1_ENTITIES.iter().position(|&n| n == name) {
|
||||
return char::from_u32(0xA0 + idx as u32);
|
||||
}
|
||||
HTML_ENTITIES.iter().find(|&&(n, _)| n == name).map(|&(_, c)| c)
|
||||
}
|
||||
|
||||
/// ISO-8859-1 named entities in code-point order `U+00A0..=U+00FF`. Entries must remain ordered
|
||||
/// by successive code points starting at `0xA0` and must not be reordered alphabetically, since
|
||||
/// [`html_named_entity`] maps each entry's index to `0xA0 + idx as u32`.
|
||||
#[rustfmt::skip]
|
||||
const LATIN1_ENTITIES: [&str; 96] = [
|
||||
"nbsp", "iexcl", "cent", "pound", "curren", "yen", "brvbar", "sect", "uml", "copy", "ordf", "laquo", "not", "shy", "reg", "macr",
|
||||
"deg", "plusmn", "sup2", "sup3", "acute", "micro", "para", "middot", "cedil", "sup1", "ordm", "raquo", "frac14", "frac12", "frac34", "iquest",
|
||||
"Agrave", "Aacute", "Acirc", "Atilde", "Auml", "Aring", "AElig", "Ccedil", "Egrave", "Eacute", "Ecirc", "Euml", "Igrave", "Iacute", "Icirc", "Iuml",
|
||||
"ETH", "Ntilde", "Ograve", "Oacute", "Ocirc", "Otilde", "Ouml", "times", "Oslash", "Ugrave", "Uacute", "Ucirc", "Uuml", "Yacute", "THORN", "szlig",
|
||||
"agrave", "aacute", "acirc", "atilde", "auml", "aring", "aelig", "ccedil", "egrave", "eacute", "ecirc", "euml", "igrave", "iacute", "icirc", "iuml",
|
||||
"eth", "ntilde", "ograve", "oacute", "ocirc", "otilde", "ouml", "divide", "oslash", "ugrave", "uacute", "ucirc", "uuml", "yacute", "thorn", "yuml",
|
||||
];
|
||||
|
||||
#[rustfmt::skip]
|
||||
const HTML_ENTITIES: &[(&str, char)] = &[
|
||||
("OElig", '\u{0152}'), ("oelig", '\u{0153}'), ("Scaron", '\u{0160}'), ("scaron", '\u{0161}'), ("Yuml", '\u{0178}'), ("fnof", '\u{0192}'), ("circ", '\u{02C6}'), ("tilde", '\u{02DC}'),
|
||||
("Alpha", '\u{0391}'), ("Beta", '\u{0392}'), ("Gamma", '\u{0393}'), ("Delta", '\u{0394}'), ("Epsilon", '\u{0395}'), ("Zeta", '\u{0396}'), ("Eta", '\u{0397}'), ("Theta", '\u{0398}'),
|
||||
("Iota", '\u{0399}'), ("Kappa", '\u{039A}'), ("Lambda", '\u{039B}'), ("Mu", '\u{039C}'), ("Nu", '\u{039D}'), ("Xi", '\u{039E}'), ("Omicron", '\u{039F}'), ("Pi", '\u{03A0}'),
|
||||
("Rho", '\u{03A1}'), ("Sigma", '\u{03A3}'), ("Tau", '\u{03A4}'), ("Upsilon", '\u{03A5}'), ("Phi", '\u{03A6}'), ("Chi", '\u{03A7}'), ("Psi", '\u{03A8}'), ("Omega", '\u{03A9}'),
|
||||
("alpha", '\u{03B1}'), ("beta", '\u{03B2}'), ("gamma", '\u{03B3}'), ("delta", '\u{03B4}'), ("epsilon", '\u{03B5}'), ("zeta", '\u{03B6}'), ("eta", '\u{03B7}'), ("theta", '\u{03B8}'),
|
||||
("iota", '\u{03B9}'), ("kappa", '\u{03BA}'), ("lambda", '\u{03BB}'), ("mu", '\u{03BC}'), ("nu", '\u{03BD}'), ("xi", '\u{03BE}'), ("omicron", '\u{03BF}'), ("pi", '\u{03C0}'),
|
||||
("rho", '\u{03C1}'), ("sigmaf", '\u{03C2}'), ("sigma", '\u{03C3}'), ("tau", '\u{03C4}'), ("upsilon", '\u{03C5}'), ("phi", '\u{03C6}'), ("chi", '\u{03C7}'), ("psi", '\u{03C8}'),
|
||||
("omega", '\u{03C9}'), ("thetasym", '\u{03D1}'), ("upsih", '\u{03D2}'), ("piv", '\u{03D6}'), ("ensp", '\u{2002}'), ("emsp", '\u{2003}'), ("thinsp", '\u{2009}'), ("zwnj", '\u{200C}'),
|
||||
("zwj", '\u{200D}'), ("lrm", '\u{200E}'), ("rlm", '\u{200F}'), ("ndash", '\u{2013}'), ("mdash", '\u{2014}'), ("lsquo", '\u{2018}'), ("rsquo", '\u{2019}'), ("sbquo", '\u{201A}'),
|
||||
("ldquo", '\u{201C}'), ("rdquo", '\u{201D}'), ("bdquo", '\u{201E}'), ("dagger", '\u{2020}'), ("Dagger", '\u{2021}'), ("bull", '\u{2022}'), ("hellip", '\u{2026}'), ("permil", '\u{2030}'),
|
||||
("prime", '\u{2032}'), ("Prime", '\u{2033}'), ("lsaquo", '\u{2039}'), ("rsaquo", '\u{203A}'), ("oline", '\u{203E}'), ("frasl", '\u{2044}'), ("euro", '\u{20AC}'), ("image", '\u{2111}'),
|
||||
("weierp", '\u{2118}'), ("real", '\u{211C}'), ("trade", '\u{2122}'), ("alefsym", '\u{2135}'), ("larr", '\u{2190}'), ("uarr", '\u{2191}'), ("rarr", '\u{2192}'), ("darr", '\u{2193}'),
|
||||
("harr", '\u{2194}'), ("crarr", '\u{21B5}'), ("lArr", '\u{21D0}'), ("uArr", '\u{21D1}'), ("rArr", '\u{21D2}'), ("dArr", '\u{21D3}'), ("hArr", '\u{21D4}'), ("forall", '\u{2200}'),
|
||||
("part", '\u{2202}'), ("exist", '\u{2203}'), ("empty", '\u{2205}'), ("nabla", '\u{2207}'), ("isin", '\u{2208}'), ("notin", '\u{2209}'), ("ni", '\u{220B}'), ("prod", '\u{220F}'),
|
||||
("sum", '\u{2211}'), ("minus", '\u{2212}'), ("lowast", '\u{2217}'), ("radic", '\u{221A}'), ("prop", '\u{221D}'), ("infin", '\u{221E}'), ("ang", '\u{2220}'), ("and", '\u{2227}'),
|
||||
("or", '\u{2228}'), ("cap", '\u{2229}'), ("cup", '\u{222A}'), ("int", '\u{222B}'), ("there4", '\u{2234}'), ("sim", '\u{223C}'), ("cong", '\u{2245}'), ("asymp", '\u{2248}'),
|
||||
("ne", '\u{2260}'), ("equiv", '\u{2261}'), ("le", '\u{2264}'), ("ge", '\u{2265}'), ("sub", '\u{2282}'), ("sup", '\u{2283}'), ("nsub", '\u{2284}'), ("sube", '\u{2286}'),
|
||||
("supe", '\u{2287}'), ("oplus", '\u{2295}'), ("otimes", '\u{2297}'), ("perp", '\u{22A5}'), ("sdot", '\u{22C5}'), ("lceil", '\u{2308}'), ("rceil", '\u{2309}'), ("lfloor", '\u{230A}'),
|
||||
("rfloor", '\u{230B}'), ("lang", '\u{2329}'), ("rang", '\u{232A}'), ("loz", '\u{25CA}'), ("spades", '\u{2660}'), ("clubs", '\u{2663}'), ("hearts", '\u{2665}'), ("diams", '\u{2666}'),
|
||||
];
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{HTML_ENTITIES, LATIN1_ENTITIES, decode_entities};
|
||||
|
||||
#[test]
|
||||
fn every_listed_html_entity_decodes_including_eight_byte_boundary() {
|
||||
for (i, &name) in LATIN1_ENTITIES.iter().enumerate() {
|
||||
let expected = char::from_u32(0xA0 + i as u32).unwrap().to_string();
|
||||
let input = format!("&{name};");
|
||||
assert_eq!(decode_entities(&input, true), expected, "entity {name}");
|
||||
assert_eq!(decode_entities(&input, false), input, "xml mode leaves {name} literal");
|
||||
}
|
||||
for &(name, ch) in HTML_ENTITIES {
|
||||
assert!(name.len() <= 8, "entity name {name} exceeds 8-byte parser limit");
|
||||
let input = format!("&{name};");
|
||||
assert_eq!(decode_entities(&input, true), ch.to_string(), "entity {name}");
|
||||
assert_eq!(decode_entities(&input, false), input, "xml mode leaves {name} literal");
|
||||
}
|
||||
assert_eq!(decode_entities("ϑ", true), "\u{03D1}");
|
||||
assert_eq!(decode_entities("&thetasymx;", true), "&thetasymx;");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -276,12 +276,29 @@ pub(crate) fn platform() -> &'static str {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn event_object(ctx: &mut Context, e: &Event) -> JsObject {
|
||||
/// The `event` object for `e`, and the store behind its `value`: `value` holds what the script
|
||||
/// reads and writes, and `set` turns true once the script assigns `event.value`, even the value it
|
||||
/// already had. The store is out of the script's reach.
|
||||
pub(crate) fn event_object(ctx: &mut Context, e: &Event) -> JsResult<(JsObject, JsObject)> {
|
||||
fn get(_: &JsValue, _: &[JsValue], store: &JsObject, c: &mut Context) -> JsResult<JsValue> {
|
||||
store.get(js_string!("value"), c)
|
||||
}
|
||||
fn set(_: &JsValue, args: &[JsValue], store: &JsObject, c: &mut Context) -> JsResult<JsValue> {
|
||||
store.set(js_string!("value"), arg(args, 0), false, c)?;
|
||||
store.set(js_string!("set"), true, false, c)?;
|
||||
Ok(JsValue::undefined())
|
||||
}
|
||||
let store = ObjectInitializer::new(ctx)
|
||||
.property(js_string!("value"), s(&e.value), Attribute::all())
|
||||
.property(js_string!("set"), false, Attribute::all())
|
||||
.build();
|
||||
let value_get = function(ctx, NativeFunction::from_copy_closure_with_captures(get, store.clone()));
|
||||
let value_set = function(ctx, NativeFunction::from_copy_closure_with_captures(set, store.clone()));
|
||||
let target = e.target.as_ref().map_or(JsValue::null(), |t| field_object(ctx, t).into());
|
||||
ObjectInitializer::new(ctx)
|
||||
let event = ObjectInitializer::new(ctx)
|
||||
.property(js_string!("name"), s(&e.name), Attribute::all())
|
||||
.property(js_string!("type"), s(&e.kind), Attribute::all())
|
||||
.property(js_string!("value"), s(&e.value), Attribute::all())
|
||||
.accessor(js_string!("value"), Some(value_get), Some(value_set), Attribute::CONFIGURABLE | Attribute::ENUMERABLE)
|
||||
.property(js_string!("change"), s(&e.change), Attribute::all())
|
||||
.property(js_string!("changeEx"), s(&e.change), Attribute::all())
|
||||
.property(js_string!("willCommit"), e.will_commit, Attribute::all())
|
||||
@@ -293,5 +310,6 @@ pub(crate) fn event_object(ctx: &mut Context, e: &Event) -> JsObject {
|
||||
.property(js_string!("commitKey"), 0, Attribute::all())
|
||||
.property(js_string!("modifier"), false, Attribute::all())
|
||||
.property(js_string!("shift"), false, Attribute::all())
|
||||
.build()
|
||||
.build();
|
||||
Ok((event, store))
|
||||
}
|
||||
|
||||
@@ -52,6 +52,8 @@ pub struct FieldState {
|
||||
/// `textColor` / `fillColor` as Acrobat colour arrays (`["RGB", r, g, b]` etc.), when set.
|
||||
pub text_color: Option<Vec<String>>,
|
||||
pub fill_color: Option<Vec<String>>,
|
||||
/// Rectangle of the first widget, in PDF user space.
|
||||
pub rect: Option<[f64; 4]>,
|
||||
}
|
||||
|
||||
impl FieldState {
|
||||
@@ -68,6 +70,7 @@ impl FieldState {
|
||||
char_limit: None,
|
||||
text_color: None,
|
||||
fill_color: None,
|
||||
rect: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -275,6 +278,8 @@ pub struct Outcome {
|
||||
pub rc: bool,
|
||||
/// `event.value` after the script.
|
||||
pub value: String,
|
||||
/// Whether the script assigned `event.value`, even the value it already had.
|
||||
pub value_set: bool,
|
||||
pub change: String,
|
||||
/// Fields whose value or properties the script changed, as they are now.
|
||||
pub changed: Vec<FieldState>,
|
||||
|
||||
@@ -217,7 +217,7 @@ fn run_here(
|
||||
let mut doc_errors: Vec<(usize, String)> = skipped.iter().map(|(i, why)| (*i, doc_error(*i, why))).collect();
|
||||
let result = (|| -> JsResult<()> {
|
||||
install(&mut ctx)?;
|
||||
let ev = event_object(&mut ctx, event);
|
||||
let (ev, value_store) = event_object(&mut ctx, event)?;
|
||||
ctx.register_global_property(js_string!("event"), ev.clone(), Attribute::all())?;
|
||||
// One document script that throws (calling a method PdfCraft lacks, say) must not keep
|
||||
// every field script in the form from running: what it defined before the error, and
|
||||
@@ -235,6 +235,7 @@ fn run_here(
|
||||
out.rc = rc.to_boolean();
|
||||
let v = ev.get(js_string!("value"), &mut ctx)?;
|
||||
out.value = text(&v, &mut ctx)?;
|
||||
out.value_set = value_store.get(js_string!("set"), &mut ctx)?.to_boolean();
|
||||
let c = ev.get(js_string!("change"), &mut ctx)?;
|
||||
out.change = text(&c, &mut ctx)?;
|
||||
Ok(())
|
||||
|
||||
@@ -31,6 +31,21 @@ fn calculate_scripts_read_fields_and_set_the_value() {
|
||||
assert!(o.rc);
|
||||
}
|
||||
|
||||
/// `event.value` reads and writes as a plain value, numbers included, and the outcome says whether
|
||||
/// the script assigned it, even to the value it already had.
|
||||
#[test]
|
||||
fn the_outcome_says_whether_the_script_assigned_event_value() {
|
||||
let ev = Event::field("Calculate", "total", "7");
|
||||
let o = go("event.value = event.value;", &ev);
|
||||
assert_eq!((o.value.as_str(), o.value_set), ("7", true));
|
||||
let o = go("event.value = 2; event.value += 3; typeof event.value;", &ev);
|
||||
assert_eq!((o.value.as_str(), o.value_set, o.result.as_deref()), ("5", true, Some("number")));
|
||||
let o = go("var v = event.value; this.getField('price').value = 3;", &ev);
|
||||
assert_eq!((o.value.as_str(), o.value_set), ("7", false));
|
||||
let o = go("Object.keys(event).indexOf('value') >= 0;", &ev);
|
||||
assert_eq!(o.result.as_deref(), Some("true"), "value stays an enumerable property of event");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numbers_with_leading_zeros_stay_text() {
|
||||
let o = go("event.value = typeof getField('zip').value + ':' + typeof getField('qty').value;", &Event::field("Calculate", "total", ""));
|
||||
@@ -73,6 +88,22 @@ fn scripts_change_other_fields_and_their_properties() {
|
||||
assert_eq!(o.changed.iter().find(|f| f.name == "size").unwrap().value, ["l"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn widget_rect_reads_and_writes_a_four_number_array() {
|
||||
let o = go(
|
||||
"var t = getField('total'); t.rect = [10, 20, 110, 50]; event.value = getField('total').rect.join(',');",
|
||||
&Event::field("Mouse Up", "agree", ""),
|
||||
);
|
||||
assert_eq!(o.error, None);
|
||||
assert_eq!(o.value, "10,20,110,50");
|
||||
assert_eq!(o.changed.iter().find(|f| f.name == "total").and_then(|f| f.rect), Some([10.0, 20.0, 110.0, 50.0]));
|
||||
let o = go("getField('total').rect = [110, 50, 10, 20];", &Event::field("Mouse Up", "agree", ""));
|
||||
assert_eq!(o.changed.iter().find(|f| f.name == "total").and_then(|f| f.rect), Some([10.0, 20.0, 110.0, 50.0]));
|
||||
let o = go("getField('total').rect = [0, 0, Infinity, 10];", &Event::field("Mouse Up", "agree", ""));
|
||||
assert!(o.error.is_some());
|
||||
assert!(o.changed.iter().all(|f| f.name != "total"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn choice_and_check_box_object_model() {
|
||||
let o = go(
|
||||
@@ -792,6 +823,19 @@ mod xfa_model {
|
||||
assert_eq!(o.result.as_deref(), Some("7"));
|
||||
}
|
||||
|
||||
/// On screen every page is a sheet of its own: `xfa.layout.sheet` counts it from 0, as
|
||||
/// `absPage` does (forms show `sheet(this) + 1`), and `sheetCount` is the page count.
|
||||
#[test]
|
||||
fn the_sheet_is_the_page_on_screen() {
|
||||
let o = go(
|
||||
"[xfa.layout.sheet(this) + 1, xfa.layout.sheetCount(), xfa.layout.absPage(this)].join(',')",
|
||||
"form1[0].page1[0].total[0]",
|
||||
"calculate",
|
||||
);
|
||||
assert_eq!(o.error, None, "{o:?}");
|
||||
assert_eq!(o.result.as_deref(), Some("2,3,1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn field_names_never_shadow_javascript_builtins() {
|
||||
let mut f = form();
|
||||
@@ -1011,6 +1055,23 @@ mod formcalc {
|
||||
run_formcalc(script, &ev, &doc, &form(), Limits::default())
|
||||
}
|
||||
|
||||
/// `xfa.layout.sheet` and `sheetCount` give what the JavaScript ones give.
|
||||
#[test]
|
||||
fn the_sheet_is_the_page_on_screen() {
|
||||
assert_eq!(calc("xfa.layout.sheet($) + 1"), "2");
|
||||
assert_eq!(calc("xfa.layout.sheetCount()"), "3");
|
||||
}
|
||||
|
||||
/// A layout method's arguments are evaluated, once each, for what they do: a message box
|
||||
/// in one still shows.
|
||||
#[test]
|
||||
fn layout_method_arguments_are_evaluated_once() {
|
||||
let o = go("xfa.layout.sheet($host.messageBox(\"Hi\"), $host.messageBox(\"Yo\")) + 1", "form1[0].page1[0].total[0]", "calculate");
|
||||
assert_eq!(o.error, None, "{o:?}");
|
||||
assert_eq!(o.result.as_deref(), Some("2"));
|
||||
assert_eq!(o.effects.iter().filter(|e| matches!(e, XfaEffect::MessageBox(_))).count(), 2, "each argument once: {:?}", o.effects);
|
||||
}
|
||||
|
||||
/// The value of a script run as a calculate on `total`.
|
||||
fn calc(script: &str) -> String {
|
||||
let o = go(script, "form1[0].page1[0].total[0]", "calculate");
|
||||
|
||||
@@ -174,6 +174,11 @@ pub(super) fn install(ctx: &mut Context, event: &XfaEvent, doc: &XfaDoc, current
|
||||
.function(NativeFunction::from_fn_ptr(layout_page0), js_string!("absPage"), 1)
|
||||
.function(NativeFunction::from_fn_ptr(layout_page_count), js_string!("pageCount"), 0)
|
||||
.function(NativeFunction::from_fn_ptr(layout_page_count), js_string!("absPageCount"), 0)
|
||||
// On screen every page is a sheet of its own: the sheet is the page, counted from 0
|
||||
// as absPage counts (a form shows `sheet(this) + 1` as the sheet number), and the
|
||||
// sheet count is the page count.
|
||||
.function(NativeFunction::from_fn_ptr(layout_page0), js_string!("sheet"), 1)
|
||||
.function(NativeFunction::from_fn_ptr(layout_page_count), js_string!("sheetCount"), 0)
|
||||
.function(NativeFunction::from_fn_ptr(relayout), js_string!("relayout"), 0)
|
||||
.function(NativeFunction::from_fn_ptr(relayout), js_string!("relayoutPageArea"), 0)
|
||||
.function(NativeFunction::from_fn_ptr(zero), js_string!("h"), 2)
|
||||
|
||||
@@ -452,6 +452,13 @@ pub struct Listing {
|
||||
pub truncated: bool,
|
||||
}
|
||||
const MAX_ANNOTATIONS: usize = 100_000;
|
||||
/// Vertex pairs one listing compares for self-intersection in all: an area's boundary check
|
||||
/// is quadratic in its vertices, and many areas (or many annotations sharing one indirect vertex
|
||||
/// array) must not multiply that into a stall.
|
||||
const MAX_LISTED_WORK: usize = 50_000_000;
|
||||
/// Scales already read by one listing, by the indirect `/Measure` object: one scale shared by
|
||||
/// many annotations is read (and its ratio decoded) once, failures included.
|
||||
type Scales = std::collections::HashMap<ObjRef, std::result::Result<Scale, String>>;
|
||||
/// Points and text one listing keeps, as counted by [`retained`]: about a thousand
|
||||
/// measurements of [`MAX_POINTS`] points each.
|
||||
const MAX_LISTED_BYTES: usize = 32 << 20;
|
||||
@@ -462,8 +469,18 @@ fn retained(m: &Measurement) -> usize {
|
||||
.into_iter()
|
||||
.fold(m.points.len().saturating_mul(std::mem::size_of::<Point>()), usize::saturating_add)
|
||||
}
|
||||
fn read_measurement(doc: &Document, d: &Dict, kind: Kind, page: usize, index: usize) -> Result<Measurement> {
|
||||
let scale = Scale::read(doc, d.get(b"Measure").ok_or_else(|| invalid("measurement has no scale"))?)?;
|
||||
/// The scale a measurement annotation reads with, through the listing's cache: a scale given by
|
||||
/// reference is read once, and its error kept, however many annotations name it.
|
||||
fn scale_of(doc: &Document, d: &Dict, scales: &mut Scales) -> Result<Scale> {
|
||||
let measure = d.get(b"Measure").ok_or_else(|| invalid("measurement has no scale"))?;
|
||||
match measure.as_ref() {
|
||||
Some(r) => scales.entry(r).or_insert_with(|| Scale::read(doc, measure).map_err(|e| e.to_string())).clone().map_err(|e| invalid(&e)),
|
||||
None => Scale::read(doc, measure),
|
||||
}
|
||||
}
|
||||
|
||||
fn read_measurement(doc: &Document, d: &Dict, kind: Kind, page: usize, index: usize, scales: &mut Scales) -> Result<Measurement> {
|
||||
let scale = scale_of(doc, d, scales)?;
|
||||
let key = if kind == Kind::Distance { &b"L"[..] } else { b"Vertices" };
|
||||
let o = doc.resolve(d.get(key).ok_or_else(|| invalid("measurement has no vertices"))?);
|
||||
let a = o.as_array().ok_or_else(|| invalid("invalid measurement vertices"))?;
|
||||
@@ -482,7 +499,9 @@ pub fn list(doc: &Document) -> Listing {
|
||||
let mut out = Listing::default();
|
||||
let mut count = 0usize;
|
||||
let mut kept = 0usize;
|
||||
let mut work = 0usize;
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let mut scales = Scales::new();
|
||||
for (page, p) in pdfcraft_model::pages(doc).iter().enumerate() {
|
||||
let Some(o) = p.dict.get(b"Annots") else { continue };
|
||||
let o = doc.resolve(o);
|
||||
@@ -507,7 +526,29 @@ pub fn list(doc: &Document) -> Listing {
|
||||
Some(b"PolygonDimension") => Kind::Area,
|
||||
_ => continue,
|
||||
};
|
||||
match read_measurement(doc, d, kind, page, index) {
|
||||
// An area's boundary check compares every pair of edges: charge it before reading the
|
||||
// vertices, so a listing stops at its work bound rather than at a stall. Other kinds
|
||||
// read their vertices once.
|
||||
let vertices = d.get(if kind == Kind::Distance { b"L".as_slice() } else { b"Vertices" }).map(|v| doc.resolve(v));
|
||||
let n = vertices.as_deref().and_then(Object::as_array).map_or(0, |a| a.len() / 2).min(MAX_POINTS);
|
||||
// An area's boundary check compares every pair of edges: charge it before reading the
|
||||
// vertices, so a listing stops at its work bound rather than at a stall. The scale is
|
||||
// resolved first, as `read_measurement` reads it: one that is rejected reads nothing at
|
||||
// all, so it must not spend the work that later, valid measurements need.
|
||||
if kind == Kind::Area {
|
||||
if let Err(e) = scale_of(doc, d, &mut scales) {
|
||||
out.unsupported.push(Unsupported { page, index, reason: e.to_string() });
|
||||
continue;
|
||||
}
|
||||
work = work.saturating_add(n.saturating_mul(n));
|
||||
} else {
|
||||
work = work.saturating_add(n.max(1));
|
||||
}
|
||||
if work > MAX_LISTED_WORK {
|
||||
out.truncated = true;
|
||||
return out;
|
||||
}
|
||||
match read_measurement(doc, d, kind, page, index, &mut scales) {
|
||||
Ok(m) => {
|
||||
kept = kept.saturating_add(retained(&m));
|
||||
if kept > MAX_LISTED_BYTES {
|
||||
|
||||
+23
-16
@@ -1,7 +1,7 @@
|
||||
//! Bounded path extraction and snapping in PDF user space, including nested Form XObjects.
|
||||
use crate::{Point, Result, check_points, distance, invalid};
|
||||
use pdfcraft_content::{Matrix, parse};
|
||||
use pdfcraft_cos::{Dict, Document, ObjRef, Object};
|
||||
use pdfcraft_content::{Matrix, ops};
|
||||
use pdfcraft_cos::{DecodeBudget, Dict, Document, ObjRef, Object};
|
||||
use serde::Serialize;
|
||||
use std::collections::HashSet;
|
||||
|
||||
@@ -199,7 +199,9 @@ struct Walker<'a> {
|
||||
doc: &'a Document,
|
||||
geometry: Geometry,
|
||||
seen: HashSet<ObjRef>,
|
||||
bytes: usize,
|
||||
/// Decoded bytes left for the page: every filter stage's output counts, so a stream that
|
||||
/// expands and then shrinks pays for the expansion each time it is drawn.
|
||||
budget: DecodeBudget,
|
||||
streams: usize,
|
||||
}
|
||||
impl Walker<'_> {
|
||||
@@ -215,46 +217,44 @@ impl Walker<'_> {
|
||||
for part in arr {
|
||||
let s = self.doc.resolve(part);
|
||||
if let Object::Stream(s) = s.as_ref() {
|
||||
let remaining = MAX_BYTES.saturating_sub(self.bytes).saturating_sub(joined.len());
|
||||
let remaining = self.budget.remaining();
|
||||
if remaining == 0 {
|
||||
self.geometry.truncated = true;
|
||||
break;
|
||||
}
|
||||
// An undecodable part is skipped; the parts before it still snap.
|
||||
match s.decoded_within(remaining) {
|
||||
match self.budget.decode_within(s, remaining) {
|
||||
Ok(data) => {
|
||||
joined.extend(data);
|
||||
// A space, as the renderer joins pieces: a trailing comment runs on.
|
||||
joined.push(b' ');
|
||||
}
|
||||
Err(_) => self.decode_failed(remaining),
|
||||
Err(_) => self.decode_failed(),
|
||||
}
|
||||
}
|
||||
}
|
||||
return self.ops(&joined, resources, initial, depth);
|
||||
}
|
||||
let Object::Stream(stream) = o.as_ref() else { return Ok(()) };
|
||||
let remaining = MAX_BYTES.saturating_sub(self.bytes);
|
||||
let remaining = self.budget.remaining();
|
||||
if remaining == 0 {
|
||||
self.geometry.truncated = true;
|
||||
return Ok(());
|
||||
}
|
||||
match stream.decoded_within(remaining) {
|
||||
match self.budget.decode_within(stream, remaining) {
|
||||
Ok(data) => self.ops(&data, resources, initial, depth),
|
||||
Err(_) => {
|
||||
self.decode_failed(remaining);
|
||||
self.decode_failed();
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
/// A tolerant decode fails on an unsupported filter or once it has produced `remaining` bytes,
|
||||
/// so a failure uses up the byte budget: repeating a failing stream cannot repeat that work.
|
||||
fn decode_failed(&mut self, remaining: usize) {
|
||||
/// A failed decode has paid the budget for what it decoded before failing (all of it, past
|
||||
/// the bound): repeating a failing stream cannot repeat that work for free.
|
||||
fn decode_failed(&mut self) {
|
||||
self.geometry.unreadable = self.geometry.unreadable.saturating_add(1);
|
||||
self.bytes = self.bytes.saturating_add(remaining);
|
||||
}
|
||||
fn ops(&mut self, data: &[u8], resources: &Dict, initial: Matrix, depth: usize) -> Result<()> {
|
||||
self.bytes = self.bytes.saturating_add(data.len());
|
||||
self.streams = self.streams.saturating_add(1);
|
||||
let mut matrix = initial;
|
||||
let mut stack = Vec::new();
|
||||
@@ -268,7 +268,8 @@ impl Walker<'_> {
|
||||
let (x, y) = m.apply(x, y);
|
||||
[x, y]
|
||||
};
|
||||
for op in parse(data).ops {
|
||||
// One operator at a time: a stream of millions of short operators is never held whole.
|
||||
for op in ops(data) {
|
||||
if self.geometry.segments.len().saturating_add(path.segments.len()) >= MAX_SEGMENTS
|
||||
|| self.geometry.targets().saturating_add(path.targets()) >= MAX_TARGETS
|
||||
{
|
||||
@@ -425,6 +426,11 @@ impl Walker<'_> {
|
||||
self.seen.insert(r);
|
||||
}
|
||||
self.walk(o, res, m, depth + 1)?;
|
||||
// A form that hit a bound ends this walk too: more `Do`s would
|
||||
// only repeat the work of copying its resources.
|
||||
if self.geometry.truncated {
|
||||
break;
|
||||
}
|
||||
if let Some(r) = r {
|
||||
self.seen.remove(&r);
|
||||
}
|
||||
@@ -449,7 +455,8 @@ pub fn geometry(doc: &Document, page_index: usize) -> Result<Geometry> {
|
||||
let resources = p.dict.get(b"Resources").map(|o| doc.resolve(o));
|
||||
let empty = Dict::new();
|
||||
let resources = resources.as_ref().and_then(|o| o.as_dict()).unwrap_or(&empty);
|
||||
let mut walker = Walker { doc, geometry: Geometry::default(), seen: HashSet::new(), bytes: 0, streams: 0 };
|
||||
let mut walker =
|
||||
Walker { doc, geometry: Geometry::default(), seen: HashSet::new(), budget: DecodeBudget::new(MAX_BYTES, usize::MAX), streams: 0 };
|
||||
// Extraction is lenient: limits and unreadable streams are reported in the geometry.
|
||||
if let Some(contents) = p.dict.get(b"Contents") {
|
||||
walker.walk(contents, resources, Matrix::IDENTITY, 0)?;
|
||||
|
||||
@@ -471,3 +471,77 @@ fn a_stream_over_the_byte_budget_uses_it_up_once() {
|
||||
assert!(g.truncated);
|
||||
assert_eq!(g.segments.len(), 1, "the parts before it still snap");
|
||||
}
|
||||
|
||||
/// A content stream drawn again and again pays for every filter stage's output each time, not
|
||||
/// only for what the last stage leaves: `/ASCIIHexDecode /RunLengthDecode` turns 4 MiB of hex
|
||||
/// into 2 MiB and then 1 MiB, and eight draws of it are 24 MiB of decoding against a 16 MiB bound.
|
||||
#[test]
|
||||
fn repeated_content_pays_for_every_filter_stage() {
|
||||
let hex = "0058".repeat(1 << 20);
|
||||
let pdf = Pdf::new()
|
||||
.obj("<< /Type /Catalog /Pages 2 0 R >>")
|
||||
.obj("<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 612 792] >>")
|
||||
.obj("<< /Type /Page /Parent 2 0 R /Contents [4 0 R 4 0 R 4 0 R 4 0 R 4 0 R 4 0 R 4 0 R 4 0 R] >>")
|
||||
.stream("/Filter [/ASCIIHexDecode /RunLengthDecode]", &hex);
|
||||
let d = Document::open(Arc::new(pdf.build())).unwrap();
|
||||
let g = snap::geometry(&d, 0).unwrap();
|
||||
assert!(g.truncated, "eight draws decode past the page's bound");
|
||||
}
|
||||
|
||||
/// One scale shared by many measurements is read once, and the self-intersection check of many
|
||||
/// areas is charged against one work bound rather than run in full for each.
|
||||
#[test]
|
||||
fn listing_reads_a_shared_scale_once_and_bounds_boundary_checks() {
|
||||
let measure = "<< /Type /Measure /Subtype /RL /R (1 pt = 1 pt) /X [<< /Type /NumberFormat /U (pt) /C 1 /D 100 >>] /D [<< /Type /NumberFormat /U (pt) /C 1 /D 100 >>] /A [<< /Type /NumberFormat /U (pt) /C 1 /D 100 >>] >>";
|
||||
// A convex 2,048-gon: every one of its edges is checked against every other.
|
||||
let n = MAX_POINTS;
|
||||
let verts: Vec<String> = (0..n)
|
||||
.map(|i| {
|
||||
let a = i as f64 / n as f64 * std::f64::consts::TAU;
|
||||
format!("{:.3} {:.3}", 300.0 + 100.0 * a.cos(), 400.0 + 100.0 * a.sin())
|
||||
})
|
||||
.collect();
|
||||
let verts = verts.join(" ");
|
||||
let areas = 40;
|
||||
let annots: Vec<String> = (0..areas).map(|i| format!("{} 0 R", 6 + i)).collect();
|
||||
let mut pdf = Pdf::new()
|
||||
.obj("<< /Type /Catalog /Pages 2 0 R >>")
|
||||
.obj("<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 612 792] >>")
|
||||
.obj(format!("<< /Type /Page /Parent 2 0 R /Contents 4 0 R /Annots [{}] >>", annots.join(" ")))
|
||||
.stream("", "")
|
||||
.obj(measure);
|
||||
for _ in 0..areas {
|
||||
pdf = pdf.obj(format!("<< /Type /Annot /Subtype /Polygon /IT /PolygonDimension /Rect [0 0 612 792] /Vertices [{verts}] /Measure 5 0 R >>"));
|
||||
}
|
||||
let d = Document::open(Arc::new(pdf.build())).unwrap();
|
||||
let l = list(&d);
|
||||
// 40 areas of 2,048 vertices are 168 million pairs: the listing stops at its bound, with the
|
||||
// areas before it listed.
|
||||
assert!(l.truncated, "{} listed", l.measurements.len());
|
||||
assert!((5..areas).contains(&l.measurements.len()), "{} listed", l.measurements.len());
|
||||
assert!(l.unsupported.is_empty(), "{:?}", l.unsupported);
|
||||
}
|
||||
|
||||
/// Perimeters and distances read their vertices once: only areas pay for the pairwise boundary
|
||||
/// check, so many maximal perimeters list in full.
|
||||
#[test]
|
||||
fn perimeters_are_charged_linear_work() {
|
||||
let measure = "<< /Type /Measure /Subtype /RL /R (1 pt = 1 pt) /X [<< /Type /NumberFormat /U (pt) /C 1 /D 100 >>] /D [<< /Type /NumberFormat /U (pt) /C 1 /D 100 >>] /A [<< /Type /NumberFormat /U (pt) /C 1 /D 100 >>] >>";
|
||||
let verts: Vec<String> = (0..MAX_POINTS).map(|i| format!("{} {}", 10 + i % 500, 10 + i / 500 * 3 + (i % 2))).collect();
|
||||
let verts = verts.join(" ");
|
||||
let lines = 40;
|
||||
let annots: Vec<String> = (0..lines).map(|i| format!("{} 0 R", 6 + i)).collect();
|
||||
let mut pdf = Pdf::new()
|
||||
.obj("<< /Type /Catalog /Pages 2 0 R >>")
|
||||
.obj("<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 612 792] >>")
|
||||
.obj(format!("<< /Type /Page /Parent 2 0 R /Contents 4 0 R /Annots [{}] >>", annots.join(" ")))
|
||||
.stream("", "")
|
||||
.obj(measure);
|
||||
for _ in 0..lines {
|
||||
pdf = pdf.obj(format!("<< /Type /Annot /Subtype /PolyLine /IT /PolyLineDimension /Rect [0 0 612 792] /Vertices [{verts}] /Measure 5 0 R >>"));
|
||||
}
|
||||
let d = Document::open(Arc::new(pdf.build())).unwrap();
|
||||
let l = list(&d);
|
||||
assert!(!l.truncated, "{} listed", l.measurements.len());
|
||||
assert_eq!(l.measurements.len() + l.unsupported.len(), lines, "{:?}", l.unsupported.first());
|
||||
}
|
||||
|
||||
@@ -22,6 +22,10 @@ image = { version = "0.25", default-features = false, features = ["jpeg"] }
|
||||
# The same JPEG decoder, used directly to read samples untransformed (/ColorTransform 0).
|
||||
zune-jpeg = "0.5"
|
||||
|
||||
# Lets other programs go first while a copy is being made.
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
thread-priority = "3.1"
|
||||
|
||||
[dev-dependencies]
|
||||
pdfcraft-render = { workspace = true }
|
||||
proptest.workspace = true
|
||||
|
||||
@@ -121,6 +121,12 @@ let report = optimize_with_progress(&mut doc, &settings, &mut |stage| keep_going
|
||||
1,000 scanned pages' worth, plus more for each byte of the file, enough to decode a stream
|
||||
about 8 times at Flate's best. Images past it stay as they are, and `Report::images_refused`
|
||||
counts those the image step read. Streams it only stores with Flate (below) aren't counted.
|
||||
- **Threads**: pictures are worked out on up to half the machine's processors (at most 8, one on
|
||||
the web), and as many as 1 GiB holds of the largest picture. Those threads go at low priority
|
||||
where the system allows it, so other programs go first; pictures done on the calling thread keep
|
||||
its priority. The document only changes in order on one thread, and what a picture costs is paid
|
||||
in that order, so the file written, and the pictures the run's decoding allowance refuses, are
|
||||
the same with any number.
|
||||
- **Discard objects:** thumbnails, alternate images, document tags, print settings.
|
||||
- **Clean up:** Flate for streams with no filter; for streams with an outer ASCII85 or ASCIIHex
|
||||
layer, that layer is removed when the result is smaller (the inner filters keep their encoded
|
||||
|
||||
@@ -243,14 +243,22 @@ fn merge_page(
|
||||
images: &mut ImageBudget,
|
||||
) -> Result<usize, OptimizeError> {
|
||||
let Some(contents) = doc.get(page).as_dict().and_then(|d| d.get(b"Contents").cloned()) else { return Ok(0) };
|
||||
let resources = page_resources(doc, page).unwrap_or_default();
|
||||
let mut xobjects = resources.get(b"XObject").map(|x| doc.resolve(x)).and_then(|x| x.as_dict().cloned()).unwrap_or_default();
|
||||
// Reading a heavy page takes seconds, so not one that has no picture that could be a fragment.
|
||||
if !xobjects.iter().any(|(name, _)| fragment_image(doc, &xobjects, name).is_some()) {
|
||||
return Ok(0);
|
||||
}
|
||||
// A page whose content isn't all known is left alone: rewriting it would drop the rest.
|
||||
let Some(data) = content_bytes(doc, &contents, &mut DecodeBudget::page()) else { return Ok(0) };
|
||||
// Nor one that doesn't draw enough things for a run, each fragment being a `Do`.
|
||||
if data.windows(2).filter(|w| *w == b"Do").count() < MIN_FRAGMENTS {
|
||||
return Ok(0);
|
||||
}
|
||||
let parsed = parse(&data);
|
||||
if parsed.skipped > 0 {
|
||||
return Ok(0);
|
||||
}
|
||||
let resources = page_resources(doc, page).unwrap_or_default();
|
||||
let mut xobjects = resources.get(b"XObject").map(|x| doc.resolve(x)).and_then(|x| x.as_dict().cloned()).unwrap_or_default();
|
||||
let ops = parsed.ops;
|
||||
let mut out: Vec<Op> = Vec::with_capacity(ops.len());
|
||||
let (mut i, mut merged, mut k) = (0, 0, 0);
|
||||
@@ -339,6 +347,9 @@ pub(crate) fn run(
|
||||
budget: &mut ImageBudget,
|
||||
) -> Result<(), OptimizeError> {
|
||||
for p in pages {
|
||||
if !progress(Stage::Reading { done: 0, total: pages.len() }) {
|
||||
return Err(OptimizeError::Cancelled);
|
||||
}
|
||||
report.fragments_merged += merge_page(doc, *p, report, progress, budget)?;
|
||||
}
|
||||
Ok(())
|
||||
@@ -405,6 +416,35 @@ mod tests {
|
||||
assert_eq!(budget.refused(), 1);
|
||||
}
|
||||
|
||||
/// A page drawing too few things for a run isn't parsed for one, even with a picture that could
|
||||
/// be a fragment.
|
||||
#[test]
|
||||
fn too_few_draws_for_a_run_read_no_groups() {
|
||||
let mut doc = Document::new_empty();
|
||||
let mut image = Dict::new();
|
||||
for (k, v) in
|
||||
[("Subtype", Object::name("Image")), ("Width", Object::Int(1)), ("Height", Object::Int(1)), ("BitsPerComponent", Object::Int(8))]
|
||||
{
|
||||
image.set(k.as_bytes().to_vec(), v);
|
||||
}
|
||||
image.set(b"ColorSpace".to_vec(), Object::name("DeviceGray"));
|
||||
let image = doc.add(Object::Stream(Stream::from_raw(image, vec![0])));
|
||||
let drawn = "q 10 0 0 10 0 0 cm /Im Do Q\n".repeat(MIN_FRAGMENTS - 1);
|
||||
let content = doc.add(Object::Stream(Stream::flate(Dict::new(), drawn.as_bytes())));
|
||||
let mut xobjects = Dict::new();
|
||||
xobjects.set(b"Im".to_vec(), Object::Ref(image));
|
||||
let mut resources = Dict::new();
|
||||
resources.set(b"XObject".to_vec(), Object::Dict(xobjects));
|
||||
let mut page = Dict::new();
|
||||
page.set(b"Contents".to_vec(), Object::Ref(content));
|
||||
page.set(b"Resources".to_vec(), Object::Dict(resources));
|
||||
let page = doc.add(Object::Dict(page));
|
||||
GROUP_READS.with(|c| c.set(0));
|
||||
let merged = merge_page(&mut doc, page, &mut Report::default(), &mut |_| true, &mut ImageBudget::with_work(u64::MAX));
|
||||
assert_eq!(merged.ok(), Some(0));
|
||||
assert_eq!(GROUP_READS.with(|c| c.get()), 0);
|
||||
}
|
||||
|
||||
/// Many images drawn on top of each other are not one picture; looking for runs among them reads
|
||||
/// a bounded number of groups per operator, not the rest of the page from every group.
|
||||
#[test]
|
||||
|
||||
+323
-83
@@ -4,6 +4,8 @@ use std::collections::{HashMap, HashSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
use pdfcraft_content::{Matrix, Pieces};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
use pdfcraft_cos::{DecodeBudget, Dict, Document, ImageBudget, ObjRef, Object, Stream};
|
||||
|
||||
use crate::{Compression, ImageSettings, MonoCompression, MonoSettings, OptimizeError, Report, Settings, Stage};
|
||||
@@ -250,13 +252,20 @@ fn remaps_device_spaces(doc: &Document, resources: &Dict) -> bool {
|
||||
/// decode within its budget or is damaged partway, every image is given `INFINITY` (never
|
||||
/// resampled), since its largest use may be among those missed.
|
||||
pub fn effective_resolutions(doc: &Document, pages: &[ObjRef]) -> HashMap<ObjRef, f64> {
|
||||
walk_pages(doc, pages).0
|
||||
let Ok((ppi, ..)) = walk_pages(doc, pages, &mut |_| true) else { return HashMap::new() };
|
||||
ppi
|
||||
}
|
||||
|
||||
/// What a walk of the pages found: each image's resolution, the images under remapped device
|
||||
/// spaces, and the references followed.
|
||||
type PagesWalked = (HashMap<ObjRef, f64>, HashSet<u32>, Read);
|
||||
|
||||
/// [`effective_resolutions`], the images drawn or listed where `/DefaultGray` or `/DefaultRGB` is
|
||||
/// in force, by object number (all of them when a use may have been missed), and the references
|
||||
/// followed to reach them.
|
||||
fn walk_pages(doc: &Document, pages: &[ObjRef]) -> (HashMap<ObjRef, f64>, HashSet<u32>, Read) {
|
||||
///
|
||||
/// `tick` hears how many pages are done, and stops the walk by returning false.
|
||||
fn walk_pages(doc: &Document, pages: &[ObjRef], tick: &mut dyn FnMut(usize) -> bool) -> Result<PagesWalked, OptimizeError> {
|
||||
let mut walk = Walk {
|
||||
doc,
|
||||
path: Vec::new(),
|
||||
@@ -269,7 +278,10 @@ fn walk_pages(doc: &Document, pages: &[ObjRef]) -> (HashMap<ObjRef, f64>, HashSe
|
||||
defaults: HashSet::new(),
|
||||
read: Read::default(),
|
||||
};
|
||||
for p in pages {
|
||||
for (done, p) in pages.iter().enumerate() {
|
||||
if !tick(done) {
|
||||
return Err(OptimizeError::Cancelled);
|
||||
}
|
||||
let Some(dict) = doc.get(*p).as_dict().cloned() else { continue };
|
||||
let page = pdfcraft_model::Page { obj: *p, dict };
|
||||
walk.resources_above(*p);
|
||||
@@ -288,7 +300,7 @@ fn walk_pages(doc: &Document, pages: &[ObjRef]) -> (HashMap<ObjRef, f64>, HashSe
|
||||
walk.out.values_mut().for_each(|v| *v = f64::INFINITY);
|
||||
walk.defaults.extend(walk.out.keys().map(|r| r.num));
|
||||
}
|
||||
(walk.out, walk.defaults, walk.read)
|
||||
Ok((walk.out, walk.defaults, walk.read))
|
||||
}
|
||||
|
||||
/// Whether image `r` is one [`one_bit`] may make grey: eight-bit `DeviceRGB`, not in an image codec.
|
||||
@@ -1330,7 +1342,7 @@ pub(crate) fn run(
|
||||
progress: &mut dyn FnMut(Stage) -> bool,
|
||||
budget: &mut ImageBudget,
|
||||
) -> Result<(), OptimizeError> {
|
||||
let (ppi, mut defaults, read) = walk_pages(doc, pages);
|
||||
let (ppi, mut defaults, read) = walk_pages(doc, pages, &mut |done| progress(Stage::Reading { done, total: pages.len() }))?;
|
||||
// Black-and-white RGB becomes grey, which default colour spaces would draw otherwise, and an
|
||||
// indexed image's palette says which of its samples a resampled one keeps, which they may
|
||||
// change: one used where the walk didn't look may be drawn so.
|
||||
@@ -1347,93 +1359,73 @@ pub(crate) fn run(
|
||||
})
|
||||
.collect();
|
||||
let mut refs: Vec<(ObjRef, f64)> = ppi.into_iter().filter(|(r, _)| !masks.contains(r)).collect();
|
||||
refs.sort_by_key(|(r, _)| r.num);
|
||||
refs.sort_by_key(|(r, _)| (r.num, r.generation));
|
||||
let total = refs.len();
|
||||
let mut jbig2 = false;
|
||||
let mut group: Vec<Held> = Vec::new();
|
||||
// Holds a JBIG2 image for `share`, which codes the group once it is full.
|
||||
let mut hold = |doc: &mut Document, image: ObjRef, size: (Option<i64>, Option<i64>), bits: Option<Vec<u8>>, report: &mut Report| {
|
||||
let side = |v: Option<i64>| v.and_then(|v| u32::try_from(v).ok());
|
||||
let (Some(bits), Some(width), Some(height)) = (bits, side(size.0), side(size.1)) else { return };
|
||||
hold_in(&mut group, Held { image, bits, width, height }, SHARED_BYTES, |group| share(doc, group, report));
|
||||
// By number: a repaired object answers to two generations.
|
||||
let mut smask_uses: HashMap<u32, usize> = HashMap::new();
|
||||
for (r, _) in &refs {
|
||||
if let Some(m) = smask_of(doc, *r) {
|
||||
*smask_uses.entry(m.num).or_default() += 1;
|
||||
}
|
||||
}
|
||||
// Too few to be worth the threads, which keeps a small file's progress in step too.
|
||||
let threads = if total < MIN_FOR_THREADS {
|
||||
1
|
||||
} else {
|
||||
let largest = refs.iter().filter_map(|(r, _)| picture_pixels(doc, *r)).max().unwrap_or(0);
|
||||
threads_for(crate::pool::workers(settings.workers), largest)
|
||||
};
|
||||
for (done, (r, ppi)) in refs.into_iter().enumerate() {
|
||||
if !progress(Stage::Images { done, total }) {
|
||||
return Err(OptimizeError::Cancelled);
|
||||
}
|
||||
let obj = doc.get(r);
|
||||
let Object::Stream(s) = &*obj else { continue };
|
||||
report.images += 1;
|
||||
let refused = budget.refused();
|
||||
// Packed from more bits a sample, it is lossless at one bit, but the grey or colour
|
||||
// settings can make it smaller still (below).
|
||||
let packed_from_more = s.dict.int(b"BitsPerComponent").is_some_and(|b| b > 1);
|
||||
let (packed, mono) = match mono(doc, s, ppi, defaults.contains(&r.num), &settings.mono, budget) {
|
||||
Some(m) if packed_from_more => (Some(m), None),
|
||||
m => (None, m),
|
||||
};
|
||||
if let Some((new, resampled, bits)) = mono {
|
||||
report.image_bytes_before += s.raw.len();
|
||||
report.image_bytes_after += new.raw.len();
|
||||
if resampled {
|
||||
report.images_resampled += 1;
|
||||
} else {
|
||||
report.images_recompressed += 1;
|
||||
let mut done = 0;
|
||||
while let Some(rest) = refs.get(done..).filter(|rest| !rest.is_empty()) {
|
||||
let run = if threads > 1 { batch_len(doc, rest, &smask_uses, settings.mono.compression == MonoCompression::Jbig2) } else { 0 };
|
||||
let Some(batch) = rest.get(..run).filter(|batch| batch.len() > 1) else {
|
||||
if !progress(Stage::Images { done, total }) {
|
||||
return Err(OptimizeError::Cancelled);
|
||||
}
|
||||
jbig2 |= new.dict.name(b"Filter") == Some(b"JBIG2Decode");
|
||||
let size = (new.dict.int(b"Width"), new.dict.int(b"Height"));
|
||||
let bits = bits.filter(|_| shares(&new.dict));
|
||||
doc.set(r, Object::Stream(new));
|
||||
hold(doc, r, size, bits, report);
|
||||
continue;
|
||||
}
|
||||
let n = s.dict.get(b"ColorSpace").and_then(|cs| components(doc, cs));
|
||||
let processed = n.and_then(|n| process(doc, s, ppi, if n == 1 { &settings.gray } else { &settings.color }, n, budget));
|
||||
// A dithered scan, say, downsampled and JPEG-compressed: the smaller wins, counting a soft
|
||||
// mask resampled with it.
|
||||
let smask_len = |smask: Option<&(ObjRef, Stream)>| match smask {
|
||||
Some((_, m)) => Some(m.raw.len()),
|
||||
None => s.dict.reference(b"SMask").map(|m| match &*doc.get(m) {
|
||||
Object::Stream(m) => m.raw.len(),
|
||||
_ => 0,
|
||||
}),
|
||||
};
|
||||
let total = |new: &Stream, smask: Option<&(ObjRef, Stream)>| Some(crate::stored_len(new)?.saturating_add(smask_len(smask).unwrap_or(0)));
|
||||
let packed_wins = packed.as_ref().is_some_and(|(p, _, _)| {
|
||||
processed.as_ref().is_none_or(|(new, smask)| total(p, None).zip(total(new, smask.as_ref())).is_some_and(|(a, b)| a <= b))
|
||||
});
|
||||
if let Some((new, resampled, bits)) = packed.filter(|_| packed_wins) {
|
||||
jbig2 |= new.dict.name(b"Filter") == Some(b"JBIG2Decode");
|
||||
report.image_bytes_before += s.raw.len();
|
||||
report.image_bytes_after += new.raw.len();
|
||||
if resampled {
|
||||
report.images_resampled += 1;
|
||||
} else {
|
||||
report.images_recompressed += 1;
|
||||
if let Some((r, ppi)) = rest.first() {
|
||||
let decision = decide(doc, *r, *ppi, defaults.contains(&r.num), settings, budget);
|
||||
apply(doc, decision, report, &mut jbig2, &mut group);
|
||||
}
|
||||
let size = (new.dict.int(b"Width"), new.dict.int(b"Height"));
|
||||
let bits = bits.filter(|_| shares(&new.dict));
|
||||
doc.set(r, Object::Stream(new));
|
||||
hold(doc, r, size, bits, report);
|
||||
continue;
|
||||
}
|
||||
let Some((new, smask)) = processed else {
|
||||
// Read to be packed and again to be resampled, it is still one image, and it stayed.
|
||||
report.images_refused += usize::from(budget.refused() > refused);
|
||||
done += 1;
|
||||
continue;
|
||||
};
|
||||
let resized = new.dict.int(b"Width") != s.dict.int(b"Width") || new.dict.int(b"Height") != s.dict.int(b"Height");
|
||||
report.image_bytes_before += s.raw.len();
|
||||
report.image_bytes_after += new.raw.len();
|
||||
if resized {
|
||||
report.images_resampled += 1;
|
||||
} else {
|
||||
report.images_recompressed += 1;
|
||||
}
|
||||
doc.set(r, Object::Stream(new));
|
||||
if let Some((mr, m)) = smask {
|
||||
doc.set(mr, Object::Stream(m));
|
||||
// Each thread works within what's left now, and pays for what it used in the document's
|
||||
// order below: a picture the order can't pay for is done again as if there were no threads,
|
||||
// so the same pictures are refused with any number of them. Once more than what's left has
|
||||
// been used, no more are started.
|
||||
let allowed = budget.work_left();
|
||||
let used = AtomicU64::new(0);
|
||||
let tried = {
|
||||
let (doc, defaults) = (&*doc, &defaults);
|
||||
crate::pool::map(
|
||||
batch,
|
||||
threads,
|
||||
|(r, ppi)| {
|
||||
if used.load(Ordering::Relaxed) >= allowed {
|
||||
return None;
|
||||
}
|
||||
let mut own = ImageBudget::with_work(allowed);
|
||||
let decision = decide(doc, *r, *ppi, defaults.contains(&r.num), settings, &mut own);
|
||||
let cost = allowed.saturating_sub(own.work_left());
|
||||
used.fetch_add(cost, Ordering::Relaxed);
|
||||
(own.refused() == 0).then_some((decision, cost))
|
||||
},
|
||||
&mut |finished| progress(Stage::Images { done: done.saturating_add(finished), total }),
|
||||
)?
|
||||
};
|
||||
for ((r, ppi), tried) in batch.iter().zip(tried) {
|
||||
let decision = match tried.flatten() {
|
||||
Some((decision, cost)) if cost <= budget.work_left() => {
|
||||
budget.charge(cost);
|
||||
decision
|
||||
}
|
||||
_ => decide(doc, *r, *ppi, defaults.contains(&r.num), settings, budget),
|
||||
};
|
||||
apply(doc, decision, report, &mut jbig2, &mut group);
|
||||
}
|
||||
done += batch.len();
|
||||
}
|
||||
share(doc, &mut group, report);
|
||||
if !progress(Stage::Images { done: total, total }) {
|
||||
@@ -1445,6 +1437,166 @@ pub(crate) fn run(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A picture's soft mask, if it names one.
|
||||
fn smask_of(doc: &Document, r: ObjRef) -> Option<ObjRef> {
|
||||
match &*doc.get(r) {
|
||||
Object::Stream(s) => s.dict.reference(b"SMask"),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// How many of `rest`, from the first, can be worked out beside each other.
|
||||
fn batch_len(doc: &Document, rest: &[(ObjRef, f64)], smask_uses: &HashMap<u32, usize>, holds_samples: bool) -> usize {
|
||||
// One object under two generations: the second must see what the first left. Under one of them
|
||||
// it can be a picture, and under the other another's soft mask.
|
||||
let mut numbers = HashSet::new();
|
||||
let mut samples = 0usize;
|
||||
rest.iter()
|
||||
.take(PICTURES_AT_ONCE)
|
||||
.take_while(|(r, _)| {
|
||||
// Results wait for the end of the batch, samples kept to share a dictionary with them.
|
||||
samples = samples.saturating_add(if holds_samples { held_samples(doc, *r) } else { 0 });
|
||||
// A soft mask two pictures share is changed by the first of them, and the second must
|
||||
// see that, so they don't run beside others.
|
||||
samples <= SHARED_BYTES
|
||||
&& !smask_uses.contains_key(&r.num)
|
||||
&& numbers.insert(r.num)
|
||||
&& smask_of(doc, *r).is_none_or(|m| smask_uses.get(&m.num) == Some(&1))
|
||||
})
|
||||
.count()
|
||||
}
|
||||
|
||||
/// The most bytes of 1-bit samples picture `r` could keep to share a dictionary: whole bytes a row.
|
||||
fn held_samples(doc: &Document, r: ObjRef) -> usize {
|
||||
let object = doc.get(r);
|
||||
let Object::Stream(s) = &*object else { return 0 };
|
||||
let side = |key: &[u8]| s.dict.int(key).and_then(|v| u64::try_from(v).ok());
|
||||
let Some((w, h)) = side(b"Width").zip(side(b"Height")) else { return 0 };
|
||||
if w.saturating_mul(h) > SHARED_PIXELS {
|
||||
return 0;
|
||||
}
|
||||
usize::try_from(w.div_ceil(8).saturating_mul(h)).unwrap_or(usize::MAX)
|
||||
}
|
||||
|
||||
/// Below this many pictures, one thread does them.
|
||||
const MIN_FOR_THREADS: usize = 16;
|
||||
|
||||
/// How many pictures run beside each other before what they used is paid for.
|
||||
const PICTURES_AT_ONCE: usize = 32;
|
||||
|
||||
/// What the pictures being worked out may hold in memory together.
|
||||
const PICTURE_MEMORY: u64 = 1 << 30;
|
||||
|
||||
/// What a picture holds while it is worked out, for each pixel: decoded, and resampled or encoded.
|
||||
const PICTURE_BYTES_PER_PIXEL: u64 = 8;
|
||||
|
||||
/// A picture's pixels, if it is small enough to be decoded at all.
|
||||
fn picture_pixels(doc: &Document, r: ObjRef) -> Option<u64> {
|
||||
let object = doc.get(r);
|
||||
let Object::Stream(s) = &*object else { return None };
|
||||
let (w, h) = (u64::try_from(s.dict.int(b"Width")?).ok()?, u64::try_from(s.dict.int(b"Height")?).ok()?);
|
||||
w.checked_mul(h).filter(|pixels| *pixels <= MAX_PIXELS)
|
||||
}
|
||||
|
||||
/// How many pictures of `largest` pixels to work on at once: `workers`, or as many as
|
||||
/// [`PICTURE_MEMORY`] holds, and at least one.
|
||||
fn threads_for(workers: usize, largest: u64) -> usize {
|
||||
let fit = PICTURE_MEMORY / largest.saturating_mul(PICTURE_BYTES_PER_PIXEL).max(1);
|
||||
workers.min(usize::try_from(fit).unwrap_or(usize::MAX)).max(1)
|
||||
}
|
||||
|
||||
/// What's to become of one picture.
|
||||
enum Decision {
|
||||
/// Not an image stream after all.
|
||||
NotAnImage,
|
||||
/// An image that stays as it is, `refused` if the allowance couldn't pay for it.
|
||||
Stays { refused: bool },
|
||||
Replace {
|
||||
image: ObjRef,
|
||||
before: usize,
|
||||
new: Stream,
|
||||
resampled: bool,
|
||||
smask: Option<(ObjRef, Stream)>,
|
||||
/// Its 1-bit samples, if it may share a JBIG2 dictionary ([`share`]).
|
||||
bits: Option<Vec<u8>>,
|
||||
},
|
||||
}
|
||||
|
||||
/// Do what was decided for one picture, and count it.
|
||||
fn apply(doc: &mut Document, decision: Decision, report: &mut Report, jbig2: &mut bool, group: &mut Vec<Held>) {
|
||||
let (image, before, new, resampled, smask, bits) = match decision {
|
||||
Decision::NotAnImage => return,
|
||||
Decision::Stays { refused } => {
|
||||
report.images += 1;
|
||||
report.images_refused += usize::from(refused);
|
||||
return;
|
||||
}
|
||||
Decision::Replace { image, before, new, resampled, smask, bits } => (image, before, new, resampled, smask, bits),
|
||||
};
|
||||
report.images += 1;
|
||||
*jbig2 |= new.dict.name(b"Filter") == Some(b"JBIG2Decode");
|
||||
report.image_bytes_before += before;
|
||||
report.image_bytes_after += new.raw.len();
|
||||
if resampled {
|
||||
report.images_resampled += 1;
|
||||
} else {
|
||||
report.images_recompressed += 1;
|
||||
}
|
||||
let side = |key: &[u8]| new.dict.int(key).and_then(|v| u32::try_from(v).ok());
|
||||
let held = bits.zip(side(b"Width")).zip(side(b"Height"));
|
||||
doc.set(image, Object::Stream(new));
|
||||
if let Some((mr, m)) = smask {
|
||||
doc.set(mr, Object::Stream(m));
|
||||
}
|
||||
// A JBIG2 image waits for `share`, which codes the group once it is full.
|
||||
if let Some(((bits, width), height)) = held {
|
||||
hold_in(group, Held { image, bits, width, height }, SHARED_BYTES, |group| share(doc, group, report));
|
||||
}
|
||||
}
|
||||
|
||||
/// Work out what's to become of picture `r`, changing nothing yet.
|
||||
fn decide(doc: &Document, r: ObjRef, ppi: f64, defaults: bool, settings: &Settings, budget: &mut ImageBudget) -> Decision {
|
||||
let obj = doc.get(r);
|
||||
let Object::Stream(s) = &*obj else { return Decision::NotAnImage };
|
||||
let refused = budget.refused();
|
||||
// Packed from more bits a sample, it is lossless at one bit, but the grey or colour
|
||||
// settings can make it smaller still (below).
|
||||
let packed_from_more = s.dict.int(b"BitsPerComponent").is_some_and(|b| b > 1);
|
||||
let (packed, mono) = match mono(doc, s, ppi, defaults, &settings.mono, budget) {
|
||||
Some(m) if packed_from_more => (Some(m), None),
|
||||
m => (None, m),
|
||||
};
|
||||
if let Some((new, resampled, bits)) = mono {
|
||||
let bits = bits.filter(|_| shares(&new.dict));
|
||||
return Decision::Replace { image: r, before: s.raw.len(), new, resampled, smask: None, bits };
|
||||
}
|
||||
let n = s.dict.get(b"ColorSpace").and_then(|cs| components(doc, cs));
|
||||
let processed = n.and_then(|n| process(doc, s, ppi, if n == 1 { &settings.gray } else { &settings.color }, n, budget));
|
||||
// A dithered scan, say, downsampled and JPEG-compressed: the smaller wins, counting a soft
|
||||
// mask resampled with it.
|
||||
let smask_len = |smask: Option<&(ObjRef, Stream)>| match smask {
|
||||
Some((_, m)) => Some(m.raw.len()),
|
||||
None => s.dict.reference(b"SMask").map(|m| match &*doc.get(m) {
|
||||
Object::Stream(m) => m.raw.len(),
|
||||
_ => 0,
|
||||
}),
|
||||
};
|
||||
let total = |new: &Stream, smask: Option<&(ObjRef, Stream)>| Some(crate::stored_len(new)?.saturating_add(smask_len(smask).unwrap_or(0)));
|
||||
let packed_wins = packed.as_ref().is_some_and(|(p, _, _)| {
|
||||
processed.as_ref().is_none_or(|(new, smask)| total(p, None).zip(total(new, smask.as_ref())).is_some_and(|(a, b)| a <= b))
|
||||
});
|
||||
if let Some((new, resampled, bits)) = packed.filter(|_| packed_wins) {
|
||||
let bits = bits.filter(|_| shares(&new.dict));
|
||||
return Decision::Replace { image: r, before: s.raw.len(), new, resampled, smask: None, bits };
|
||||
}
|
||||
let Some((new, smask)) = processed else {
|
||||
// Read to be packed and again to be resampled, it is still one image, and it stayed.
|
||||
return Decision::Stays { refused: budget.refused() > refused };
|
||||
};
|
||||
let resampled = new.dict.int(b"Width") != s.dict.int(b"Width") || new.dict.int(b"Height") != s.dict.int(b"Height");
|
||||
Decision::Replace { image: r, before: s.raw.len(), new, resampled, smask, bits: None }
|
||||
}
|
||||
|
||||
/// JBIG2Decode is PDF 1.4: a document whose header says less, and whose catalog doesn't say 1.4
|
||||
/// or more already (directly or by reference), gets `/Version /1.4` in its catalog (ISO 32000-2
|
||||
/// §7.7.2). A full save with object streams writes a 1.5 header anyway.
|
||||
@@ -1492,6 +1644,37 @@ mod dimension_tests {
|
||||
assert_eq!((count, group.len()), (SHARED_IMAGES, 0), "coded on the 16th");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_batch_holds_no_more_samples_than_a_group_may() {
|
||||
let mut doc = Document::new_empty();
|
||||
let mut add = |width: i64, height: i64| {
|
||||
let mut d = Dict::new();
|
||||
d.set(b"Width".to_vec(), Object::Int(width));
|
||||
d.set(b"Height".to_vec(), Object::Int(height));
|
||||
(doc.add(Object::Stream(Stream::from_raw(d, Vec::new()))), 72.0)
|
||||
};
|
||||
// Eight megabytes of samples each, and one byte a pixel when one pixel wide.
|
||||
let large: Vec<_> = (0..12).map(|_| add(8192, 8192)).collect();
|
||||
let thin: Vec<_> = (0..8).map(|_| add(1, 32 << 20)).collect();
|
||||
let small: Vec<_> = (0..40).map(|_| add(100, 100)).collect();
|
||||
// Past what may share a dictionary, so never held.
|
||||
let huge: Vec<_> = (0..12).map(|_| add(16384, 16384)).collect();
|
||||
let none = HashMap::new();
|
||||
assert_eq!(batch_len(&doc, &large, &none, true), 8);
|
||||
assert_eq!(batch_len(&doc, &thin, &none, true), 2);
|
||||
assert_eq!(batch_len(&doc, &small, &none, true), PICTURES_AT_ONCE);
|
||||
assert_eq!(batch_len(&doc, &huge, &none, true), huge.len());
|
||||
assert_eq!(batch_len(&doc, &large, &none, false), large.len(), "nothing is held but for JBIG2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn threads_are_limited_by_the_memory_of_the_largest_picture() {
|
||||
assert_eq!(threads_for(8, 1_000_000), 8);
|
||||
assert_eq!(threads_for(8, 40_000_000), 3);
|
||||
assert_eq!(threads_for(8, MAX_PIXELS), 1);
|
||||
assert_eq!(threads_for(8, 0), 8);
|
||||
}
|
||||
|
||||
/// Only what redaction can store again without the dictionary shares one: an image mask, or
|
||||
/// DeviceGray named directly, of at most 2^26 pixels.
|
||||
#[test]
|
||||
@@ -1609,6 +1792,63 @@ mod dimension_tests {
|
||||
assert_eq!(changed, 2, "the third is as it was");
|
||||
}
|
||||
|
||||
/// An allowance that runs out refuses the same pictures with any number of threads as it does
|
||||
/// one after another.
|
||||
#[test]
|
||||
fn the_allowance_refuses_the_same_pictures_with_any_number_of_threads() {
|
||||
let picture = |shade: u32| {
|
||||
let mut dict = Dict::new();
|
||||
dict.set(b"Type".to_vec(), Object::name("XObject"));
|
||||
dict.set(b"Subtype".to_vec(), Object::name("Image"));
|
||||
dict.set(b"Width".to_vec(), Object::Int(400));
|
||||
dict.set(b"Height".to_vec(), Object::Int(400));
|
||||
dict.set(b"BitsPerComponent".to_vec(), Object::Int(8));
|
||||
dict.set(b"ColorSpace".to_vec(), Object::name("DeviceGray"));
|
||||
let samples: Vec<u8> = (0..400u32 * 400).map(|i| (i.wrapping_mul(shade + 3) % 251) as u8).collect();
|
||||
Stream::flate(dict, &samples)
|
||||
};
|
||||
let build = || {
|
||||
let mut doc = Document::new_empty();
|
||||
// A few of different sizes, so what's left when the allowance ends depends on the order.
|
||||
let refs: Vec<ObjRef> = (0..40u32).map(|i| doc.add(Object::Stream(picture(i)))).collect();
|
||||
let mut xobjects = Dict::new();
|
||||
let mut content = String::from("q 72 0 0 72 0 0 cm ");
|
||||
for (i, r) in refs.iter().enumerate() {
|
||||
xobjects.set(format!("I{i}").into_bytes(), Object::Ref(*r));
|
||||
content.push_str(&format!("/I{i} Do "));
|
||||
}
|
||||
content.push('Q');
|
||||
let mut resources = Dict::new();
|
||||
resources.set(b"XObject".to_vec(), Object::Dict(xobjects));
|
||||
let content = doc.add(Object::Stream(Stream::flate(Dict::new(), content.as_bytes())));
|
||||
let mut page = Dict::new();
|
||||
page.set(b"Type".to_vec(), Object::name("Page"));
|
||||
page.set(b"Resources".to_vec(), Object::Dict(resources));
|
||||
page.set(b"Contents".to_vec(), Object::Ref(content));
|
||||
let page = doc.add(Object::Dict(page));
|
||||
(doc, refs, page)
|
||||
};
|
||||
let run_with = |work: u64, workers: usize| {
|
||||
let (mut doc, refs, page) = build();
|
||||
let settings = Settings { workers: Some(workers), ..Settings::default() };
|
||||
let (mut report, mut budget) = (Report::default(), ImageBudget::with_work(work));
|
||||
run(&mut doc, &[page], &settings, &mut report, &mut |_| true, &mut budget).unwrap();
|
||||
let raws: Vec<Vec<u8>> = refs.iter().map(|r| if let Object::Stream(s) = &*doc.get(*r) { s.raw.to_vec() } else { Vec::new() }).collect();
|
||||
(format!("{report:?}"), budget.work_left(), raws)
|
||||
};
|
||||
let all = u64::MAX - run_with(u64::MAX, 1).1;
|
||||
// Past one batch of what threads run together, and part of the way through a picture.
|
||||
let work = all / 40 * 37 + all / 80;
|
||||
let one = run_with(work, 1);
|
||||
assert!(one.0.contains("images_refused: 3"), "{}", one.0);
|
||||
for workers in [2, 4, 8] {
|
||||
let many = run_with(work, workers);
|
||||
assert_eq!(many.0, one.0, "{workers} threads count the same");
|
||||
assert_eq!(many.1, one.1, "{workers} threads leave the same allowance");
|
||||
assert!(many.2 == one.2, "{workers} threads store the same pictures");
|
||||
}
|
||||
}
|
||||
|
||||
/// Images that aren't JBIG2 share the run's allowance too, both on the way to being resampled
|
||||
/// and on the way to being packed to a bit a sample: a file of filter bombs would hold a run
|
||||
/// as long as one of JBIG2, and those past it stay as they are.
|
||||
|
||||
@@ -32,6 +32,7 @@ mod audit;
|
||||
pub mod fragments;
|
||||
mod images;
|
||||
mod links;
|
||||
mod pool;
|
||||
mod samples;
|
||||
mod unused;
|
||||
|
||||
@@ -41,6 +42,7 @@ use pdfcraft_cos::{Dict, Document, ImageBudget, MAX_PAGE_DECODED, ObjRef, Object
|
||||
use pdfcraft_filters::{Filter, Params};
|
||||
|
||||
pub use images::effective_resolutions;
|
||||
pub use pool::give_way_to_other_programs;
|
||||
pub use samples::{NotDecoded, Samples, decode_samples, encode_samples};
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
@@ -106,6 +108,8 @@ impl Compatibility {
|
||||
/// Where an optimization is, reported to [`optimize_with_progress`]'s callback.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Stage {
|
||||
/// Reading what pages draw: `done` of `total` read, none yet while looking for fragments.
|
||||
Reading { done: usize, total: usize },
|
||||
/// About to process image `done` (0-based) of `total`; `done == total` once all are done.
|
||||
Images { done: usize, total: usize },
|
||||
/// Merging the fragments of a page picture into one image (only when a page has some).
|
||||
@@ -181,6 +185,8 @@ impl ImageSettings {
|
||||
pub struct Settings {
|
||||
/// Target PDF version (`Retain` by default).
|
||||
pub compatibility: Compatibility,
|
||||
/// Threads for pictures: `None` picks from the machine. The result is the same with any number.
|
||||
pub workers: Option<usize>,
|
||||
/// Put page pictures drawn as many stacked fragments back together first ([`fragments`]).
|
||||
pub merge_fragments: bool,
|
||||
pub color: ImageSettings,
|
||||
@@ -217,6 +223,7 @@ impl Default for Settings {
|
||||
/// Acrobat's Reduce File Size choices.
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
workers: None,
|
||||
compatibility: Compatibility::Retain,
|
||||
merge_fragments: true,
|
||||
color: ImageSettings::REDUCE,
|
||||
|
||||
@@ -0,0 +1,262 @@
|
||||
//! Work over many pages or images on several threads, the results in order, so that what is
|
||||
//! written is the same however many threads did it.
|
||||
|
||||
use std::panic::{AssertUnwindSafe, catch_unwind};
|
||||
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
||||
use std::sync::mpsc::{RecvTimeoutError, channel};
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::OptimizeError;
|
||||
|
||||
/// Threads beyond this add more memory than speed: each holds a page or an image being worked on.
|
||||
const MAX_WORKERS: usize = 8;
|
||||
/// How long Cancel can wait while every thread is busy with something long.
|
||||
const CANCEL_CHECK: Duration = Duration::from_millis(100);
|
||||
|
||||
/// Let other programs go first on this thread: the wait for a copy matters less than whatever else
|
||||
/// is open. A system that refuses leaves it as it was.
|
||||
pub fn give_way_to_other_programs() {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let _ = thread_priority::set_current_thread_priority(thread_priority::ThreadPriority::Min);
|
||||
}
|
||||
|
||||
/// How many threads to use: `asked`, or half the machine's processors up to [`MAX_WORKERS`], so a
|
||||
/// bigger machine goes faster and every machine keeps room for other programs. One on the web, which
|
||||
/// has no threads here.
|
||||
pub(crate) fn workers(asked: Option<usize>) -> usize {
|
||||
if cfg!(target_arch = "wasm32") {
|
||||
return 1;
|
||||
}
|
||||
asked.unwrap_or_else(|| std::thread::available_parallelism().map_or(1, |n| (n.get() / 2).clamp(1, MAX_WORKERS))).max(1)
|
||||
}
|
||||
|
||||
/// `work` on each of `items`, results in the order of `items`. `tick` hears how many are done, and
|
||||
/// stops the run by returning false. With more than one worker an item whose work panics gets
|
||||
/// `None`, and the caller decides what becomes of it; with one, the panic goes on up as it does for
|
||||
/// any other work.
|
||||
pub(crate) fn map<T: Sync, R: Send>(
|
||||
items: &[T],
|
||||
workers: usize,
|
||||
work: impl Fn(&T) -> R + Sync,
|
||||
tick: &mut dyn FnMut(usize) -> bool,
|
||||
) -> Result<Vec<Option<R>>, OptimizeError> {
|
||||
let mut out: Vec<Option<R>> = Vec::with_capacity(items.len());
|
||||
if workers <= 1 || items.len() <= 1 {
|
||||
for (done, item) in items.iter().enumerate() {
|
||||
if !tick(done) {
|
||||
return Err(OptimizeError::Cancelled);
|
||||
}
|
||||
out.push(Some(work(item)));
|
||||
}
|
||||
return Ok(out);
|
||||
}
|
||||
out.resize_with(items.len(), || None);
|
||||
let (next, stop) = (AtomicUsize::new(0), AtomicBool::new(false));
|
||||
let mut stopped = false;
|
||||
std::thread::scope(|scope| {
|
||||
let (results, finished) = channel();
|
||||
for _ in 0..workers.min(items.len()) {
|
||||
let results = results.clone();
|
||||
let (next, stop, work) = (&next, &stop, &work);
|
||||
// A thread that can't start only leaves more for the others, or for below.
|
||||
let _ = std::thread::Builder::new().name("pdfcraft-optimize-worker".into()).spawn_scoped(scope, move || {
|
||||
give_way_to_other_programs();
|
||||
while !stop.load(Ordering::Relaxed) {
|
||||
let i = next.fetch_add(1, Ordering::Relaxed);
|
||||
let Some(item) = items.get(i) else { break };
|
||||
let result = catch_unwind(AssertUnwindSafe(|| work(item))).ok();
|
||||
if results.send((i, result)).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
drop(results);
|
||||
let mut done = 0;
|
||||
loop {
|
||||
if !stopped && !tick(done) {
|
||||
stopped = true;
|
||||
stop.store(true, Ordering::Relaxed);
|
||||
}
|
||||
match finished.recv_timeout(CANCEL_CHECK) {
|
||||
Ok((i, result)) => {
|
||||
if let Some(slot) = out.get_mut(i) {
|
||||
*slot = result;
|
||||
}
|
||||
done += 1;
|
||||
}
|
||||
Err(RecvTimeoutError::Timeout) => {}
|
||||
Err(RecvTimeoutError::Disconnected) => break,
|
||||
}
|
||||
}
|
||||
});
|
||||
if stopped {
|
||||
return Err(OptimizeError::Cancelled);
|
||||
}
|
||||
// No thread could start, or the last of them stopped early: the rest are done here.
|
||||
let claimed = next.load(Ordering::Relaxed).min(items.len());
|
||||
for (done, (item, slot)) in items.iter().zip(out.iter_mut()).enumerate().skip(claimed) {
|
||||
if !tick(done) {
|
||||
return Err(OptimizeError::Cancelled);
|
||||
}
|
||||
*slot = Some(work(item));
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::Mutex;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn results_keep_their_order_whatever_finishes_first() {
|
||||
let items: Vec<u64> = (0..200).collect();
|
||||
let out = map(
|
||||
&items,
|
||||
4,
|
||||
|i| {
|
||||
// The early ones finish last.
|
||||
std::thread::sleep(Duration::from_micros(200u64.saturating_sub(*i)));
|
||||
i * 2
|
||||
},
|
||||
&mut |_| true,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(out, items.iter().map(|i| Some(i * 2)).collect::<Vec<_>>());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_worker_does_them_in_order_on_this_thread() {
|
||||
let here = std::thread::current().id();
|
||||
let order = Mutex::new(Vec::new());
|
||||
let mut ticks = Vec::new();
|
||||
map(
|
||||
&[1, 2, 3],
|
||||
1,
|
||||
|i| {
|
||||
assert_eq!(std::thread::current().id(), here);
|
||||
order.lock().unwrap().push(*i);
|
||||
},
|
||||
&mut |done| {
|
||||
ticks.push(done);
|
||||
true
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(*order.lock().unwrap(), [1, 2, 3]);
|
||||
assert_eq!(ticks, [0, 1, 2]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn several_workers_share_the_work() {
|
||||
let threads = Mutex::new(std::collections::HashSet::new());
|
||||
map(
|
||||
&[0; 64],
|
||||
4,
|
||||
|_| {
|
||||
threads.lock().unwrap().insert(std::thread::current().id());
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
},
|
||||
&mut |_| true,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(threads.lock().unwrap().len() > 1, "it really ran on more than one");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stopping_stops_and_says_so() {
|
||||
let ran = AtomicUsize::new(0);
|
||||
let r = map(
|
||||
&[0; 500],
|
||||
4,
|
||||
|_| {
|
||||
ran.fetch_add(1, Ordering::Relaxed);
|
||||
std::thread::sleep(Duration::from_millis(1));
|
||||
},
|
||||
&mut |done| done < 8,
|
||||
);
|
||||
assert!(matches!(r, Err(OptimizeError::Cancelled)));
|
||||
assert!(ran.load(Ordering::Relaxed) < 500, "the rest never started");
|
||||
}
|
||||
|
||||
/// Cancel is heard while every thread is busy with something long, not only between items.
|
||||
#[test]
|
||||
fn a_stop_gets_through_while_every_thread_is_busy() {
|
||||
let mut asked_while_busy = 0;
|
||||
map(&[0; 2], 2, |_| std::thread::sleep(Duration::from_millis(600)), &mut |done| {
|
||||
if done == 0 {
|
||||
asked_while_busy += 1;
|
||||
}
|
||||
true
|
||||
})
|
||||
.unwrap();
|
||||
assert!(asked_while_busy >= 3, "asked {asked_while_busy} times before anything finished");
|
||||
|
||||
let started = std::time::Instant::now();
|
||||
let mut asked = 0;
|
||||
let r = map(&[0; 4], 2, |_| std::thread::sleep(Duration::from_millis(400)), &mut |_| {
|
||||
asked += 1;
|
||||
asked < 3
|
||||
});
|
||||
assert!(matches!(r, Err(OptimizeError::Cancelled)));
|
||||
assert!(started.elapsed() < Duration::from_millis(1500), "the items not started never ran");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_item_that_panics_is_left_alone_and_the_rest_are_done() {
|
||||
let items: Vec<u32> = (0..32).collect();
|
||||
let out = map(
|
||||
&items,
|
||||
4,
|
||||
|i| {
|
||||
assert_ne!(*i, 7, "this one panics");
|
||||
*i
|
||||
},
|
||||
&mut |_| true,
|
||||
)
|
||||
.unwrap();
|
||||
for (i, got) in out.iter().enumerate() {
|
||||
assert_eq!(*got, (i != 7).then_some(i as u32), "item {i}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The workers give way, and the thread that asked keeps its own priority.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn workers_give_way_to_other_programs() {
|
||||
use thread_priority::get_current_thread_priority;
|
||||
let here = get_current_thread_priority().unwrap();
|
||||
let theirs = Mutex::new(Vec::new());
|
||||
map(
|
||||
&[0; 8],
|
||||
2,
|
||||
|_| {
|
||||
theirs.lock().unwrap().push(get_current_thread_priority().unwrap());
|
||||
std::thread::sleep(Duration::from_millis(2));
|
||||
},
|
||||
&mut |_| true,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(get_current_thread_priority().unwrap(), here);
|
||||
let theirs = theirs.into_inner().unwrap();
|
||||
assert_eq!(theirs.len(), 8);
|
||||
assert!(theirs.iter().all(|p| *p != here), "{theirs:?} against {here:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_to_do_is_fine() {
|
||||
let none: [u8; 0] = [];
|
||||
assert!(map(&none, 4, |_| 1, &mut |_| true).unwrap().is_empty());
|
||||
assert_eq!(map(&[5], 4, |i| *i, &mut |_| true).unwrap(), [Some(5)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_web_and_small_machines_get_a_sensible_count() {
|
||||
assert_eq!(workers(Some(3)), if cfg!(target_arch = "wasm32") { 1 } else { 3 });
|
||||
assert_eq!(workers(Some(0)), 1, "never none");
|
||||
let picked = workers(None);
|
||||
assert!((1..=MAX_WORKERS).contains(&picked), "{picked}");
|
||||
}
|
||||
}
|
||||
@@ -395,9 +395,9 @@ fn a_jpeg_header_that_takes_more_than_a_few_steps_to_read_is_left_as_it_is() {
|
||||
#[test]
|
||||
fn cancelling_works_from_the_first_call_with_a_jpeg_drawn_many_times() {
|
||||
// One JPEG with 8 MB of stray bytes after SOI, drawn 64 times at the same place (the case
|
||||
// reported on #3012). Fragment merging reads its header for each group it tries, before the
|
||||
// first progress call. The header scan stops at the first stray byte, so that call is the
|
||||
// first image, and cancelling there stops Optimize.
|
||||
// reported on #3012). Fragment merging reads its header for each group it tries. The header
|
||||
// scan stops at the first stray byte, so the first image comes soon, and cancelling there stops
|
||||
// Optimize. Cancelling while pages are read stops it sooner still.
|
||||
let (w, h) = (128, 8);
|
||||
let jpeg = after_soi(&rgb_jpeg(&photo(w, h), w, h), &vec![0; 8_000_000]);
|
||||
let mut doc = Document::new_empty();
|
||||
@@ -411,8 +411,16 @@ fn cancelling_works_from_the_first_call_with_a_jpeg_drawn_many_times() {
|
||||
let mut stages = Vec::new();
|
||||
let result = optimize_with_progress(&mut doc, &Settings::default(), &mut |stage| {
|
||||
stages.push(stage);
|
||||
!matches!(stage, Stage::Images { .. })
|
||||
});
|
||||
assert!(matches!(result, Err(OptimizeError::Cancelled)), "{result:?}");
|
||||
assert_eq!(stages.last(), Some(&Stage::Images { done: 0, total: 1 }));
|
||||
assert_eq!(stages.first(), Some(&Stage::Reading { done: 0, total: 1 }), "it can be stopped from the first call");
|
||||
let mut stages = 0;
|
||||
let result = optimize_with_progress(&mut doc, &Settings::default(), &mut |_| {
|
||||
stages += 1;
|
||||
false
|
||||
});
|
||||
assert!(matches!(result, Err(OptimizeError::Cancelled)), "{result:?}");
|
||||
assert_eq!(stages, [Stage::Images { done: 0, total: 1 }]);
|
||||
assert_eq!(stages, 1);
|
||||
}
|
||||
|
||||
@@ -2647,7 +2647,9 @@ fn progress_is_reported_per_image_and_a_refusal_cancels() {
|
||||
};
|
||||
let mut seen = Vec::new();
|
||||
let report = optimize_with_progress(&mut build(), &Settings::default(), &mut |s| {
|
||||
seen.push(s);
|
||||
if !matches!(s, Stage::Reading { .. }) {
|
||||
seen.push(s);
|
||||
}
|
||||
true
|
||||
})
|
||||
.unwrap();
|
||||
@@ -2665,7 +2667,10 @@ fn progress_is_reported_per_image_and_a_refusal_cancels() {
|
||||
|
||||
// Stopping after the first image.
|
||||
let mut calls = 0;
|
||||
let r = optimize_with_progress(&mut build(), &Settings::default(), &mut |_| {
|
||||
let r = optimize_with_progress(&mut build(), &Settings::default(), &mut |s| {
|
||||
if matches!(s, Stage::Reading { .. }) {
|
||||
return true;
|
||||
}
|
||||
calls += 1;
|
||||
calls < 2
|
||||
});
|
||||
@@ -4289,3 +4294,135 @@ fn a_picture_whose_mask_is_not_a_stencil_is_left_alone() {
|
||||
assert_eq!(stream(&doc, img), before, "{what}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Pictures run on several threads: what comes out doesn't depend on how many.
|
||||
#[test]
|
||||
fn the_same_file_comes_out_with_any_number_of_threads() {
|
||||
let build = || {
|
||||
let mut doc = Document::new_empty();
|
||||
let shared_mask = image(&mut doc, 1200, 1200, 1, false, None);
|
||||
// Under a soft mask they share, at different sizes on the page: the second must start from
|
||||
// the mask the first left. Each needs the mask at a different size.
|
||||
let first = image(&mut doc, 1200, 1200, 3, true, Some(shared_mask));
|
||||
let second = image(&mut doc, 1000, 1000, 3, true, Some(shared_mask));
|
||||
page(&mut doc, &[("Im0", first)], "q 144 0 0 144 100 100 cm /Im0 Do Q");
|
||||
page(&mut doc, &[("Im0", second)], "q 180 0 0 180 100 100 cm /Im0 Do Q");
|
||||
// Enough others for the threads.
|
||||
for page_no in 0..22u32 {
|
||||
let img = image(&mut doc, 500 + page_no, 500, 3, true, None);
|
||||
page(&mut doc, &[("Im0", img)], "q 72 0 0 72 100 100 cm /Im0 Do Q");
|
||||
}
|
||||
doc
|
||||
};
|
||||
let run = |workers| {
|
||||
let mut doc = build();
|
||||
let report = optimize(&mut doc, &Settings { workers: Some(workers), ..Settings::default() }).unwrap();
|
||||
assert_eq!(report.images, 24, "{report:?}");
|
||||
assert!(report.images_resampled + report.images_recompressed > 16, "{report:?}");
|
||||
(write_full(&doc, &SaveOptions::default()).unwrap(), format!("{report:?}"))
|
||||
};
|
||||
let (one, one_report) = run(1);
|
||||
for workers in [2, 4, 7] {
|
||||
let (many, many_report) = run(workers);
|
||||
assert_eq!(many_report, one_report, "{workers} threads count the same");
|
||||
assert!(many == one, "{workers} threads write the same bytes");
|
||||
}
|
||||
}
|
||||
|
||||
/// A table that disagrees with an object's header leaves it reachable under two generations, as
|
||||
/// one object: each use decides from what the one before it left, with any number of threads.
|
||||
#[test]
|
||||
fn one_object_under_two_generations_comes_out_the_same_with_any_number_of_threads() {
|
||||
let picture = |size: usize, extra: &str| {
|
||||
let samples: Vec<u8> = (0..size * size).map(|i| ((i % size) * 255 / size) as u8 ^ ((i / size) as u8 & 7)).collect();
|
||||
let dict = format!(
|
||||
"<< /Type /XObject /Subtype /Image /Width {size} /Height {size} /BitsPerComponent 8 /ColorSpace /DeviceGray{extra} /Length {} >>\nstream\n",
|
||||
samples.len()
|
||||
);
|
||||
[dict.as_bytes(), &samples, b"\nendstream"].concat()
|
||||
};
|
||||
let build = || {
|
||||
// 1 the catalog, 2 the pages, 3 the mask, 4 and 5 under it, 6 the picture, 7 a picture that is
|
||||
// also 8's mask, then the others.
|
||||
let mut objects = vec![b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(), Vec::new()];
|
||||
objects.push(picture(1200, ""));
|
||||
objects.push(picture(1200, " /SMask 3 0 R"));
|
||||
objects.push(picture(1000, " /SMask 3 1 R"));
|
||||
objects.push(picture(1200, ""));
|
||||
objects.push(picture(1200, ""));
|
||||
objects.push(picture(1000, " /SMask 7 1 R"));
|
||||
// Small under one generation, large under the other: they want different sizes.
|
||||
let mut draws = vec![
|
||||
("4 0 R".to_string(), 144),
|
||||
("5 0 R".to_string(), 180),
|
||||
("6 0 R".to_string(), 72),
|
||||
("6 1 R".to_string(), 576),
|
||||
("7 0 R".to_string(), 72),
|
||||
("8 0 R".to_string(), 180),
|
||||
];
|
||||
for i in 0..22 {
|
||||
objects.push(picture(500 + i, ""));
|
||||
draws.push((format!("{} 0 R", objects.len()), 72));
|
||||
}
|
||||
let mut kids = String::new();
|
||||
for (drawn, size) in &draws {
|
||||
let content = format!("q {size} 0 0 {size} 10 10 cm /Im0 Do Q");
|
||||
objects.push(format!("<< /Length {} >>\nstream\n{content}\nendstream", content.len()).into_bytes());
|
||||
let contents = objects.len();
|
||||
objects.push(
|
||||
format!(
|
||||
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents {contents} 0 R /Resources << /XObject << /Im0 {drawn} >> >> >>"
|
||||
)
|
||||
.into_bytes(),
|
||||
);
|
||||
kids.push_str(&format!("{} 0 R ", objects.len()));
|
||||
}
|
||||
objects[1] = format!("<< /Type /Pages /Kids [{kids}] /Count {} >>", draws.len()).into_bytes();
|
||||
let mut bytes = b"%PDF-1.7\n".to_vec();
|
||||
let mut table = format!("xref\n0 {}\n0000000000 65535 f \n", objects.len() + 1);
|
||||
for (i, object) in objects.iter().enumerate() {
|
||||
let num = i + 1;
|
||||
// Headers say generation 0, and the table says 1 of these three.
|
||||
let generation = u8::from(num == 3 || num == 6 || num == 7);
|
||||
table.push_str(&format!("{:010} {generation:05} n \n", bytes.len()));
|
||||
bytes.extend(format!("{num} 0 obj\n").as_bytes());
|
||||
bytes.extend(object);
|
||||
bytes.extend(b"\nendobj\n");
|
||||
}
|
||||
let start = bytes.len();
|
||||
bytes.extend(table.as_bytes());
|
||||
bytes.extend(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{start}\n%%EOF\n", objects.len() + 1).as_bytes());
|
||||
let doc = Document::open(Arc::new(bytes)).unwrap();
|
||||
for (num, generation) in [(3, 0), (3, 1), (6, 0), (6, 1), (7, 0), (7, 1)] {
|
||||
assert!(matches!(&*doc.get(ObjRef { num, generation }), Object::Stream(_)), "{num} {generation} finds the object");
|
||||
}
|
||||
doc
|
||||
};
|
||||
let run = |workers| {
|
||||
let mut doc = build();
|
||||
let report = optimize(&mut doc, &Settings { workers: Some(workers), ..Settings::default() }).unwrap();
|
||||
(write_full(&doc, &SaveOptions::default()).unwrap(), format!("{report:?}"))
|
||||
};
|
||||
let (one, one_report) = run(1);
|
||||
for workers in [2, 4, 7] {
|
||||
let (many, many_report) = run(workers);
|
||||
assert_eq!(many_report, one_report, "{workers} threads count the same");
|
||||
assert!(many == one, "{workers} threads write the same bytes");
|
||||
}
|
||||
}
|
||||
|
||||
/// Pages too small for a run aren't read, and that must not cost the smallest run there can be.
|
||||
#[test]
|
||||
fn the_fewest_strips_that_make_a_picture_are_merged() {
|
||||
use pdfcraft_optimize::fragments::MIN_FRAGMENTS;
|
||||
let keep = Settings {
|
||||
gray: ImageSettings { downsample: false, target_ppi: 150.0, above_ppi: 225.0, compression: Compression::Retain },
|
||||
..Settings::default()
|
||||
};
|
||||
let (mut doc, _) = printed_page(MIN_FRAGMENTS as _, |_| false, |_, s| s);
|
||||
let r = optimize(&mut doc, &keep).unwrap();
|
||||
assert_eq!((r.merged_images, r.fragments_merged), (1, MIN_FRAGMENTS), "{r:?}");
|
||||
let (mut doc, _) = printed_page((MIN_FRAGMENTS - 1) as _, |_| false, |_, s| s);
|
||||
let r = optimize(&mut doc, &keep).unwrap();
|
||||
assert_eq!((r.merged_images, r.fragments_merged), (0, 0), "{r:?}");
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user