Merge remote-tracking branch 'origin/main' into fix/sec-cmap-codespaces

# Conflicts:
#	crates/fonts/src/pdf/tests.rs
This commit is contained in:
Dylan M. Taylor
2026-11-11 20:05:08 +00:00
106 changed files with 6260 additions and 654 deletions
+4
View File
@@ -29,6 +29,10 @@ jobs:
permissions:
contents: read
steps:
- name: Harden runner
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
+4
View File
@@ -24,6 +24,10 @@ jobs:
name: fuzz (mutation, 15 min)
runs-on: ubuntu-latest
steps:
- name: Harden runner
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
+4
View File
@@ -27,6 +27,10 @@ jobs:
name: Windows installation policy (no app build)
runs-on: windows-latest
steps:
- name: Harden runner
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
Generated
+72 -70
View File
@@ -238,7 +238,7 @@ dependencies = [
"objc2-foundation 0.3.2",
"parking_lot",
"percent-encoding",
"windows-sys 0.61.2",
"windows-sys 0.52.0",
"wl-clipboard-rs",
"x11rb",
]
@@ -321,7 +321,7 @@ dependencies = [
"futures-lite",
"parking",
"polling",
"rustix 1.1.5",
"rustix 1.1.6",
"slab",
"windows-sys 0.61.2",
]
@@ -352,7 +352,7 @@ dependencies = [
"cfg-if",
"event-listener",
"futures-lite",
"rustix 1.1.5",
"rustix 1.1.6",
]
[[package]]
@@ -378,7 +378,7 @@ dependencies = [
"cfg-if",
"futures-core",
"futures-io",
"rustix 1.1.5",
"rustix 1.1.6",
"signal-hook-registry",
"slab",
"windows-sys 0.61.2",
@@ -878,7 +878,7 @@ checksum = "4dbf9978365bac10f54d1d4b04f7ce4427e51f71d61f2fe15e3fed5166474df7"
dependencies = [
"bitflags 2.13.2",
"polling",
"rustix 1.1.5",
"rustix 1.1.6",
"slab",
"tracing",
]
@@ -902,7 +902,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "138efcf0940a02ebf0cc8d1eff41a1682a46b431630f4c52450d6265876021fa"
dependencies = [
"calloop 0.14.4",
"rustix 1.1.5",
"rustix 1.1.6",
"wayland-backend",
"wayland-client",
]
@@ -1289,7 +1289,7 @@ dependencies = [
[[package]]
name = "craft-update"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b"
dependencies = [
"chrono",
"dunce",
@@ -1299,6 +1299,7 @@ dependencies = [
"image",
"log",
"plist",
"rustix 1.1.6",
"semver",
"serde",
"serde_json",
@@ -2050,7 +2051,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
dependencies = [
"libc",
"windows-sys 0.61.2",
"windows-sys 0.52.0",
]
[[package]]
@@ -2427,7 +2428,7 @@ version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8"
dependencies = [
"rustix 1.1.5",
"rustix 1.1.6",
"windows-link",
]
@@ -4172,7 +4173,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967"
dependencies = [
"libc",
"windows-sys 0.61.2",
"windows-sys 0.52.0",
]
[[package]]
@@ -4263,7 +4264,7 @@ dependencies = [
[[package]]
name = "pdfcraft"
version = "0.18.1"
version = "0.21.0"
dependencies = [
"chrono",
"craft-update",
@@ -4288,7 +4289,7 @@ dependencies = [
[[package]]
name = "pdfcraft-a11y"
version = "0.18.1"
version = "0.21.0"
dependencies = [
"pdfcraft-content",
"pdfcraft-cos",
@@ -4299,7 +4300,7 @@ dependencies = [
[[package]]
name = "pdfcraft-annot"
version = "0.18.1"
version = "0.21.0"
dependencies = [
"hayro-syntax",
"pdfcraft-cos",
@@ -4311,7 +4312,7 @@ dependencies = [
[[package]]
name = "pdfcraft-audit"
version = "0.18.1"
version = "0.21.0"
dependencies = [
"pdfcraft-content",
"pdfcraft-cos",
@@ -4322,7 +4323,7 @@ dependencies = [
[[package]]
name = "pdfcraft-automation"
version = "0.18.1"
version = "0.21.0"
dependencies = [
"base64 0.23.1",
"flate2",
@@ -4338,7 +4339,7 @@ dependencies = [
"pdfcraft-render",
"pdfcraft-xfa",
"png 0.18.1",
"rustix 1.1.5",
"rustix 1.1.6",
"serde_json",
"sha2 0.11.1",
"tempfile",
@@ -4346,7 +4347,7 @@ dependencies = [
[[package]]
name = "pdfcraft-cli"
version = "0.18.1"
version = "0.21.0"
dependencies = [
"base64 0.23.1",
"pdfcraft-audit",
@@ -4357,18 +4358,18 @@ dependencies = [
"pdfcraft-preflight",
"pdfcraft-render",
"png 0.18.1",
"rustix 1.1.5",
"rustix 1.1.6",
"serde_json",
"winresource",
]
[[package]]
name = "pdfcraft-compare"
version = "0.18.1"
version = "0.21.0"
[[package]]
name = "pdfcraft-content"
version = "0.18.1"
version = "0.21.0"
dependencies = [
"hayro-syntax",
"pdfcraft-cos",
@@ -4376,7 +4377,7 @@ dependencies = [
[[package]]
name = "pdfcraft-cos"
version = "0.18.1"
version = "0.21.0"
dependencies = [
"chrono",
"hayro-syntax",
@@ -4393,7 +4394,7 @@ dependencies = [
[[package]]
name = "pdfcraft-create"
version = "0.18.1"
version = "0.21.0"
dependencies = [
"encoding_rs",
"hayro-ccitt",
@@ -4405,6 +4406,7 @@ dependencies = [
"pdfcraft-model",
"pdfcraft-xfa",
"png 0.18.1",
"rustix 1.1.6",
"thiserror 2.0.21",
"tiff",
"zune-jpeg",
@@ -4412,7 +4414,7 @@ dependencies = [
[[package]]
name = "pdfcraft-crypt"
version = "0.18.1"
version = "0.21.0"
dependencies = [
"aes",
"md-5",
@@ -4425,7 +4427,7 @@ dependencies = [
[[package]]
name = "pdfcraft-edit"
version = "0.18.1"
version = "0.21.0"
dependencies = [
"hayro-syntax",
"icu_segmenter",
@@ -4444,7 +4446,7 @@ dependencies = [
[[package]]
name = "pdfcraft-engine"
version = "0.18.1"
version = "0.21.0"
dependencies = [
"chrono",
"craft-docpath",
@@ -4488,14 +4490,14 @@ dependencies = [
[[package]]
name = "pdfcraft-export"
version = "0.18.1"
version = "0.21.0"
dependencies = [
"flate2",
]
[[package]]
name = "pdfcraft-filters"
version = "0.18.1"
version = "0.21.0"
dependencies = [
"fax",
"flate2",
@@ -4508,7 +4510,7 @@ dependencies = [
[[package]]
name = "pdfcraft-fonts"
version = "0.18.1"
version = "0.21.0"
dependencies = [
"harfrust",
"pdfcraft-cos",
@@ -4518,7 +4520,7 @@ dependencies = [
[[package]]
name = "pdfcraft-forms"
version = "0.18.1"
version = "0.21.0"
dependencies = [
"hayro-syntax",
"pdfcraft-content",
@@ -4531,11 +4533,11 @@ dependencies = [
[[package]]
name = "pdfcraft-geom"
version = "0.18.1"
version = "0.21.0"
[[package]]
name = "pdfcraft-js"
version = "0.18.1"
version = "0.21.0"
dependencies = [
"boa_engine",
"chrono",
@@ -4543,7 +4545,7 @@ dependencies = [
[[package]]
name = "pdfcraft-measure"
version = "0.18.1"
version = "0.21.0"
dependencies = [
"pdfcraft-annot",
"pdfcraft-content",
@@ -4556,14 +4558,14 @@ dependencies = [
[[package]]
name = "pdfcraft-model"
version = "0.18.1"
version = "0.21.0"
dependencies = [
"pdfcraft-cos",
]
[[package]]
name = "pdfcraft-ocr"
version = "0.18.1"
version = "0.21.0"
dependencies = [
"ocrs",
"pdfcraft-fonts",
@@ -4578,7 +4580,7 @@ dependencies = [
[[package]]
name = "pdfcraft-ocr-worker"
version = "0.18.1"
version = "0.21.0"
dependencies = [
"js-sys",
"pdfcraft-ocr",
@@ -4588,7 +4590,7 @@ dependencies = [
[[package]]
name = "pdfcraft-optimize"
version = "0.18.1"
version = "0.21.0"
dependencies = [
"image",
"pdfcraft-annot",
@@ -4605,11 +4607,11 @@ dependencies = [
[[package]]
name = "pdfcraft-oracle"
version = "0.18.1"
version = "0.21.0"
[[package]]
name = "pdfcraft-organize"
version = "0.18.1"
version = "0.21.0"
dependencies = [
"hayro-syntax",
"pdfcraft-content",
@@ -4620,18 +4622,18 @@ dependencies = [
[[package]]
name = "pdfcraft-platform"
version = "0.18.1"
version = "0.21.0"
dependencies = [
"async-channel",
"futures-lite",
"log",
"rustix 1.1.5",
"rustix 1.1.6",
"zbus",
]
[[package]]
name = "pdfcraft-prc"
version = "0.18.1"
version = "0.21.0"
dependencies = [
"flate2",
"proptest",
@@ -4640,7 +4642,7 @@ dependencies = [
[[package]]
name = "pdfcraft-prc-render"
version = "0.18.1"
version = "0.21.0"
dependencies = [
"flate2",
"pdfcraft-prc",
@@ -4649,7 +4651,7 @@ dependencies = [
[[package]]
name = "pdfcraft-preflight"
version = "0.18.1"
version = "0.21.0"
dependencies = [
"flate2",
"pdfcraft-content",
@@ -4660,7 +4662,7 @@ dependencies = [
[[package]]
name = "pdfcraft-print"
version = "0.18.1"
version = "0.21.0"
dependencies = [
"craft-print",
"log",
@@ -4675,7 +4677,7 @@ dependencies = [
[[package]]
name = "pdfcraft-redact"
version = "0.18.1"
version = "0.21.0"
dependencies = [
"aho-corasick",
"pdfcraft-annot",
@@ -4699,7 +4701,7 @@ dependencies = [
[[package]]
name = "pdfcraft-render"
version = "0.18.1"
version = "0.21.0"
dependencies = [
"bytemuck",
"flate2",
@@ -4723,7 +4725,7 @@ dependencies = [
[[package]]
name = "pdfcraft-sign"
version = "0.18.1"
version = "0.21.0"
dependencies = [
"aes",
"aws-lc-rs",
@@ -4762,11 +4764,11 @@ dependencies = [
[[package]]
name = "pdfcraft-testkit"
version = "0.18.1"
version = "0.21.0"
[[package]]
name = "pdfcraft-ui-egui"
version = "0.18.1"
version = "0.21.0"
dependencies = [
"arboard",
"base64 0.23.1",
@@ -4807,7 +4809,7 @@ dependencies = [
"pollster 1.0.1",
"proptest",
"rfd",
"rustix 1.1.5",
"rustix 1.1.6",
"serde",
"serde_json",
"skrifa 0.44.0",
@@ -4825,7 +4827,7 @@ dependencies = [
[[package]]
name = "pdfcraft-web"
version = "0.18.1"
version = "0.21.0"
dependencies = [
"craft-web-api",
"craft-web-host",
@@ -4840,7 +4842,7 @@ dependencies = [
[[package]]
name = "pdfcraft-xfa"
version = "0.18.1"
version = "0.21.0"
dependencies = [
"base64 0.23.1",
"image",
@@ -4854,7 +4856,7 @@ dependencies = [
[[package]]
name = "pdfcraft-xfdf"
version = "0.18.1"
version = "0.21.0"
dependencies = [
"base64 0.23.1",
"pdfcraft-annot",
@@ -5143,7 +5145,7 @@ dependencies = [
"concurrent-queue",
"hermit-abi",
"pin-project-lite",
"rustix 1.1.5",
"rustix 1.1.6",
"windows-sys 0.61.2",
]
@@ -5401,7 +5403,7 @@ dependencies = [
"once_cell",
"socket2",
"tracing",
"windows-sys 0.61.2",
"windows-sys 0.52.0",
]
[[package]]
@@ -5953,15 +5955,15 @@ dependencies = [
[[package]]
name = "rustix"
version = "1.1.5"
version = "1.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d"
checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa"
dependencies = [
"bitflags 2.13.2",
"errno",
"libc",
"linux-raw-sys 0.12.1",
"windows-sys 0.61.2",
"windows-sys 0.52.0",
]
[[package]]
@@ -6031,7 +6033,7 @@ dependencies = [
"security-framework",
"security-framework-sys",
"webpki-root-certs",
"windows-sys 0.61.2",
"windows-sys 0.52.0",
]
[[package]]
@@ -6655,7 +6657,7 @@ dependencies = [
"libc",
"log",
"memmap2",
"rustix 1.1.5",
"rustix 1.1.6",
"thiserror 2.0.21",
"wayland-backend",
"wayland-client",
@@ -6920,8 +6922,8 @@ dependencies = [
"fastrand",
"getrandom 0.4.3",
"once_cell",
"rustix 1.1.5",
"windows-sys 0.61.2",
"rustix 1.1.6",
"windows-sys 0.52.0",
]
[[package]]
@@ -7673,7 +7675,7 @@ checksum = "38a91b4eaddff87b1cd1074985e3713da4af2c49742d1b356b2c01670a67a078"
dependencies = [
"cc",
"downcast-rs",
"rustix 1.1.5",
"rustix 1.1.6",
"scoped-tls",
"smallvec",
"wayland-sys",
@@ -7686,7 +7688,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3c36a0f861ad76d0901f2800b46321410d9f73f2ea88aac0650d86c32688073"
dependencies = [
"bitflags 2.13.2",
"rustix 1.1.5",
"rustix 1.1.6",
"wayland-backend",
"wayland-scanner",
]
@@ -7708,7 +7710,7 @@ version = "0.31.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4a52d18780be9b1314328a3de5f930b73d2200112e3849ca6cb11822793fb34d"
dependencies = [
"rustix 1.1.5",
"rustix 1.1.6",
"wayland-client",
"xcursor",
]
@@ -8046,7 +8048,7 @@ version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
dependencies = [
"windows-sys 0.61.2",
"windows-sys 0.52.0",
]
[[package]]
@@ -8404,7 +8406,7 @@ dependencies = [
"libc",
"log",
"os_pipe",
"rustix 1.1.5",
"rustix 1.1.6",
"thiserror 2.0.21",
"tree_magic_mini",
"wayland-backend",
@@ -8462,7 +8464,7 @@ dependencies = [
"libc",
"libloading",
"once_cell",
"rustix 1.1.5",
"rustix 1.1.6",
"x11rb-protocol",
]
@@ -8504,7 +8506,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156"
dependencies = [
"libc",
"rustix 1.1.5",
"rustix 1.1.6",
]
[[package]]
@@ -8611,7 +8613,7 @@ dependencies = [
"hex",
"libc",
"ordered-stream",
"rustix 1.1.5",
"rustix 1.1.6",
"serde",
"serde_repr",
"tracing",
+37 -37
View File
@@ -5,7 +5,7 @@ exclude = ["vendor"]
default-members = ["crates/*", "apps/pdfcraft", "apps/pdfcraft-cli", "xtask"]
[workspace.package]
version = "0.18.1"
version = "0.21.0"
edition = "2024"
license = "MIT OR Apache-2.0"
rust-version = "1.95"
@@ -30,43 +30,43 @@ craft-print = { git = "https://github.com/storytold/craft-libs", version = "0.1.
# Whether a path stored in a document may be opened (GoToR link targets).
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "787a7a0f972fd1d7a7618fdbeca3a5267a0407ff" }
# craft-update: app-specific pretend versions apply to startup and manual checks.
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "1b34eba41e62138fc2438d2734523b302840b45d", features = ["egui"] }
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["egui"] }
# internal
pdfcraft-geom = { path = "crates/geom", version = "0.18.1" }
pdfcraft-filters = { path = "crates/filters", version = "0.18.1" }
pdfcraft-cos = { path = "crates/cos", version = "0.18.1" }
pdfcraft-crypt = { path = "crates/crypt", version = "0.18.1" }
pdfcraft-organize = { path = "crates/organize", version = "0.18.1" }
pdfcraft-measure = { path = "crates/measure", version = "0.18.1" }
pdfcraft-annot = { path = "crates/annot", version = "0.18.1" }
pdfcraft-audit = { path = "crates/audit", version = "0.18.1" }
pdfcraft-fonts = { path = "crates/fonts", version = "0.18.1" }
pdfcraft-model = { path = "crates/model", version = "0.18.1" }
pdfcraft-content = { path = "crates/content", version = "0.18.1" }
pdfcraft-redact = { path = "crates/redact", version = "0.18.1" }
pdfcraft-print = { path = "crates/print", version = "0.18.1" }
pdfcraft-xfdf = { path = "crates/xfdf", version = "0.18.1" }
pdfcraft-sign = { path = "crates/sign", version = "0.18.1" }
pdfcraft-optimize = { path = "crates/optimize", version = "0.18.1" }
pdfcraft-a11y = { path = "crates/a11y", version = "0.18.1" }
pdfcraft-oracle = { path = "crates/oracle", version = "0.18.1" }
pdfcraft-testkit = { path = "crates/testkit", version = "0.18.1" }
pdfcraft-ocr = { path = "crates/ocr", version = "0.18.1" }
pdfcraft-js = { path = "crates/js", version = "0.18.1" }
pdfcraft-compare = { path = "crates/compare", version = "0.18.1" }
pdfcraft-preflight = { path = "crates/preflight", version = "0.18.1" }
pdfcraft-export = { path = "crates/export", version = "0.18.1" }
pdfcraft-edit = { path = "crates/edit", version = "0.18.1" }
pdfcraft-create = { path = "crates/create", version = "0.18.1" }
pdfcraft-forms = { path = "crates/forms", version = "0.18.1" }
pdfcraft-xfa = { path = "crates/xfa", version = "0.18.1" }
pdfcraft-render = { path = "crates/render", version = "0.18.1" }
pdfcraft-engine = { path = "crates/engine", version = "0.18.1" }
pdfcraft-platform = { path = "crates/platform", version = "0.18.1" }
pdfcraft-ui-egui = { path = "crates/ui-egui", version = "0.18.1" }
pdfcraft-automation = { path = "crates/automation", version = "0.18.1", default-features = false }
pdfcraft-prc = { path = "crates/prc", version = "0.18.1" }
pdfcraft-prc-render = { path = "crates/prc-render", version = "0.18.1" }
pdfcraft-geom = { path = "crates/geom", version = "0.21.0" }
pdfcraft-filters = { path = "crates/filters", version = "0.21.0" }
pdfcraft-cos = { path = "crates/cos", version = "0.21.0" }
pdfcraft-crypt = { path = "crates/crypt", version = "0.21.0" }
pdfcraft-organize = { path = "crates/organize", version = "0.21.0" }
pdfcraft-measure = { path = "crates/measure", version = "0.21.0" }
pdfcraft-annot = { path = "crates/annot", version = "0.21.0" }
pdfcraft-audit = { path = "crates/audit", version = "0.21.0" }
pdfcraft-fonts = { path = "crates/fonts", version = "0.21.0" }
pdfcraft-model = { path = "crates/model", version = "0.21.0" }
pdfcraft-content = { path = "crates/content", version = "0.21.0" }
pdfcraft-redact = { path = "crates/redact", version = "0.21.0" }
pdfcraft-print = { path = "crates/print", version = "0.21.0" }
pdfcraft-xfdf = { path = "crates/xfdf", version = "0.21.0" }
pdfcraft-sign = { path = "crates/sign", version = "0.21.0" }
pdfcraft-optimize = { path = "crates/optimize", version = "0.21.0" }
pdfcraft-a11y = { path = "crates/a11y", version = "0.21.0" }
pdfcraft-oracle = { path = "crates/oracle", version = "0.21.0" }
pdfcraft-testkit = { path = "crates/testkit", version = "0.21.0" }
pdfcraft-ocr = { path = "crates/ocr", version = "0.21.0" }
pdfcraft-js = { path = "crates/js", version = "0.21.0" }
pdfcraft-compare = { path = "crates/compare", version = "0.21.0" }
pdfcraft-preflight = { path = "crates/preflight", version = "0.21.0" }
pdfcraft-export = { path = "crates/export", version = "0.21.0" }
pdfcraft-edit = { path = "crates/edit", version = "0.21.0" }
pdfcraft-create = { path = "crates/create", version = "0.21.0" }
pdfcraft-forms = { path = "crates/forms", version = "0.21.0" }
pdfcraft-xfa = { path = "crates/xfa", version = "0.21.0" }
pdfcraft-render = { path = "crates/render", version = "0.21.0" }
pdfcraft-engine = { path = "crates/engine", version = "0.21.0" }
pdfcraft-platform = { path = "crates/platform", version = "0.21.0" }
pdfcraft-ui-egui = { path = "crates/ui-egui", version = "0.21.0" }
pdfcraft-automation = { path = "crates/automation", version = "0.21.0", default-features = false }
pdfcraft-prc = { path = "crates/prc", version = "0.21.0" }
pdfcraft-prc-render = { path = "crates/prc-render", version = "0.21.0" }
# pdf
hayro = "0.7.1"
+2
View File
@@ -87,6 +87,7 @@
> **Last reviewed:** 2026-10-18 · **Last updated:** 2026-10-18 · **Change:** minor (M8, #1350: named replacement descriptions retired during Sanitize and across shared resources; estimates unchanged)
> **Last reviewed:** 2026-10-17 · **Last updated:** 2026-10-17 · **Change:** minor (M4 #2997: Ctrl-drag (Option on macOS) in the Organize grid copies the pages into the drop gap; `page_duplicate` takes `at`; estimates unchanged) · **Target:** Adobe Acrobat Pro (Acrobat DC, continuous track 26.002.21931, macOS)
> **Last reviewed:** 2026-10-15 · **Last updated:** 2026-10-15 · **Change:** minor (M6: AcroForm XML text; estimates unchanged)
> **Last reviewed:** 2026-10-17 · **Last updated:** 2026-10-17 · **Change:** minor (M10, gap 8: Office documents open through an installed LibreOffice; estimates unchanged) · **Target:** Adobe Acrobat Pro (Acrobat DC, continuous track 26.002.21931, macOS)
> **Last reviewed:** 2026-10-15 · **Last updated:** 2026-10-15 · **Change:** minor (M2/gap 12: the Annex D.2 alias codes read as the ink they draw in both tables; the text oracle scores reading order; estimates unchanged) · **Target:** Adobe Acrobat Pro (Acrobat DC, continuous track 26.002.21931, macOS)
> **Last reviewed:** 2026-10-15 · **Last updated:** 2026-10-15 · **Change:** minor (M14/#2383 GPU-limit candidate; estimates unchanged) · **Target:** Adobe Acrobat Pro (Acrobat DC, continuous track 26.002.21931, macOS)
> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-13 · **Change:** minor (M4: indirect page rotations; M13: CLI check visits each directory once through aliases and cycles; estimates unchanged) · **Target:** Adobe Acrobat Pro (Acrobat DC, continuous track 26.002.21931, macOS)
@@ -494,6 +495,7 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md
- **2026-10-16 (M14, localization):** Czech goes from menus-and-dialogs to the whole surface: 2,674 entries after adding the ~220 keys the other catalogs had -- the sentences the engine words (signature details, accessibility findings and report, PDF/A problems, pages to print, history labels), the date picker's weekday heads, the certificate viewer's fields and shared buttons. "Tag" is *tag* throughout (the Tags panel said *značky*, which is also a redaction mark), and "{n} tags" no longer reads "1 značek". Two new catalog tests. Estimates unchanged.
- **2026-10-16 (M5, #2583, #1869):** A sticky note on a page with `/Rotate` is drawn upright, with its top-left where it was placed. Notes are saved with the NoRotate flag, and the renderer now honours it: the appearance is turned against the page's rotation about the upper-left corner of `/Rect`, which stays put (ISO 32000-2 §12.5.3; vendored hayro-interpret patch 37). Attachment icons follow the same rule. Selection, hover, the edit composer, the Comments panel's flash and the `comment_list` and `doc_info` rectangles use the drawn box, and `comment_add` anchors an icon's displayed top-left at `at`. Estimates unchanged.
- **2026-10-16 (M11, #1201):** Optimize decodes a JPEG with its colour transform: an Adobe APP14 marker's flag, else the filter's `/ColorTransform` (ISO 32000-2 §7.4.8). An RGB JPEG stored untransformed (`/ColorTransform 0`, no marker) used to be converted from YCbCr anyway and came out in other colours, recompressed or merged from strips; it now keeps them. A JPEG whose marker and `/ColorTransform` disagree, or whose components are named R, G and B without `/ColorTransform 0`, is left as it is, since readers differ on it. Estimates unchanged.
- **2026-10-17 (M10, gap 8):** File ▸ Open opens Word, Excel, PowerPoint, OpenDocument and RTF files as new, unsaved PDFs, converted on the open worker by an installed LibreOffice (headless, a private temporary folder and fresh profile with macros off, stopped after 120 s); without LibreOffice the user is told it is needed. The Open dialog lists PDF (the default), Images, Office documents, Text and All files. Insert, Combine and Create ▸ Multiple files refuse Office documents for now, since they convert on the frame thread. `create.from-office` planned → partial. On 2026-10-26 the profile also stopped Writer and Calc from updating linked content (Impress has no such setting), and tests that skip without LibreOffice convert generated DOCX, XLSX, PPTX and RTF files through `doc_create_multiple` and `doc_combine` and check their text. Estimates unchanged.
- **2026-10-15 (M2, gap 12):** `cargo xtask text-oracle` scores reading order as well as word F1: the longest common subsequence of the two word sequences over the longer one. F1 is a bag of words and cannot see order at all -- measuring #2431, a change that moves text and nothing else, it called 26 of the 29 files whose output changed identical, where the order score separated 18 improvements from 6 regressions. Reports, does not gate; a disagreement with Poppler, not a verdict. Estimates unchanged.
- **2026-10-15 (M2, #2305 follow-up):** WinAnsiEncoding 0xA0 and 0xAD and MacRomanEncoding 0xCA extract as the ordinary space and hyphen Annex D.2 names them, in the vendored hayro tables (patch 30) as well as `crates/fonts`, so search, copy and redaction see characters that were hidden behind U+00A0 and U+00AD. Across the pdf.js corpus the soft hyphens we extract fall 117 to 13 and the non-breaking spaces 30 to 26; the rest come from `/ToUnicode`. An explicit `/Differences` name keeps its glyph list value, as pdftotext does. Estimates unchanged.
- **2026-10-15 (M14, gap 16, #1683):** Split view. View ▸ Split (⌘\\ / Ctrl+\\) and a tab's Split right / Split down show two panes, each with its own tab strip, scroll and zoom; a tab dropped on the right half of the page area splits right, and the divider drags. One document in both panes is one document with one Undo; closing one of its views keeps it open. The pane last clicked is the one menus, keys and panels act on. Nothing about the panes is kept across restarts. `view.split-window` planned → shipped. Multiple windows stay planned. Estimates unchanged.
+47 -22
View File
@@ -857,19 +857,38 @@ pub fn set_points(doc: &mut Document, page: usize, index: usize, points: &[[f64;
/// Scale a drawing's strokes into `rect`. The margin between the strokes and the old `/Rect` (half
/// the line width and a little more) stays the same on each side, so the line isn't clipped.
/// Most stroke points a stored drawing may have for resizing or erasing it. Counted as each
/// stroke is resolved, so one stroke array referenced again and again can't expand past it.
const MAX_STORED_INK_POINTS: usize = 1_000_000;
/// Most points the eraser densifies a drawing into before testing them against its path.
const MAX_ERASE_SAMPLES: usize = 4_000_000;
/// The strokes of an ink annotation's `/InkList`, at most [`MAX_STORED_INK_POINTS`] points.
fn ink_strokes(doc: &Document, d: &Dict) -> Result<Vec<Vec<[f64; 2]>>, AnnotError> {
let too_many = || AnnotError::Invalid(format!("the drawing has more than {MAX_STORED_INK_POINTS} points"));
let list = d.get(b"InkList").map(|l| doc.resolve(l));
let mut points = 0usize;
let mut strokes = Vec::new();
for s in list.as_deref().and_then(Object::as_array).map(Vec::as_slice).unwrap_or_default() {
let stroke = doc.resolve(s);
let Some(a) = stroke.as_array() else {
strokes.push(Vec::new());
continue;
};
// Charged before the coordinates are read: a shared array costs each time it is listed.
points = points.saturating_add(a.len() / 2);
if points > MAX_STORED_INK_POINTS {
return Err(too_many());
}
let v: Vec<f64> = a.iter().filter_map(|x| doc.resolve(x).as_f64()).collect();
strokes.push(v.as_chunks::<2>().0.iter().map(|p| [p[0], p[1]]).collect());
}
Ok(strokes)
}
fn resize_ink(doc: &mut Document, r: ObjRef, rect: [f64; 4], meta: &Meta) -> Result<(), AnnotError> {
let d = annot_dict(doc, r);
let strokes: Vec<Vec<[f64; 2]>> = d
.get(b"InkList")
.map(|l| doc.resolve(l))
.and_then(|l| l.as_array().cloned())
.unwrap_or_default()
.iter()
.map(|s| {
let v: Vec<f64> = doc.resolve(s).as_array().map(|a| a.iter().filter_map(|x| doc.resolve(x).as_f64()).collect()).unwrap_or_default();
v.as_chunks::<2>().0.iter().map(|p| [p[0], p[1]]).collect()
})
.collect();
let strokes = ink_strokes(doc, &d)?;
let Some(inner) = bounds(strokes.iter().flatten().copied()) else {
return Err(AnnotError::Invalid("the drawing has no strokes".into()));
};
@@ -1475,17 +1494,7 @@ pub fn erase_ink(doc: &mut Document, page: usize, index: usize, path: &[[f64; 2]
if path.is_empty() || !path.iter().all(|p| finite(p)) || !radius.is_finite() || radius <= 0.0 {
return Err(AnnotError::Invalid("invalid eraser path".into()));
}
let strokes: Vec<Vec<[f64; 2]>> = d
.get(b"InkList")
.map(|l| doc.resolve(l))
.and_then(|l| l.as_array().cloned())
.unwrap_or_default()
.iter()
.map(|s| {
let v: Vec<f64> = doc.resolve(s).as_array().map(|a| a.iter().filter_map(|x| doc.resolve(x).as_f64()).collect()).unwrap_or_default();
v.as_chunks::<2>().0.iter().map(|p| [p[0], p[1]]).collect()
})
.collect();
let strokes = ink_strokes(doc, &d)?;
// Distance from a point to the eraser's path (segments, or a single point).
let near = |p: [f64; 2]| -> bool {
if path.len() == 1 {
@@ -1501,17 +1510,27 @@ pub fn erase_ink(doc: &mut Document, page: usize, index: usize, path: &[[f64; 2]
};
let mut kept: Vec<Vec<[f64; 2]>> = Vec::new();
let mut erased = false;
let mut samples = 0usize;
for s in &strokes {
// Densify so long segments are cut where the eraser crosses them.
let mut pts: Vec<[f64; 2]> = Vec::new();
for w in s.windows(2) {
let n = ((w[1][0] - w[0][0]).hypot(w[1][1] - w[0][1]) / (radius / 2.0)).ceil().clamp(1.0, 2000.0) as usize;
samples = samples.saturating_add(n);
if samples > MAX_ERASE_SAMPLES {
return Err(AnnotError::Invalid("the drawing is too large to erase at this eraser size".into()));
}
for k in 0..n {
let t = k as f64 / n as f64;
pts.push([w[0][0] + (w[1][0] - w[0][0]) * t, w[0][1] + (w[1][1] - w[0][1]) * t]);
}
}
if let Some(last) = s.last() {
// The final point is a sample too.
samples = samples.saturating_add(1);
if samples > MAX_ERASE_SAMPLES {
return Err(AnnotError::Invalid("the drawing is too large to erase at this eraser size".into()));
}
pts.push(*last);
}
let mut run: Vec<[f64; 2]> = Vec::new();
@@ -1537,6 +1556,12 @@ pub fn erase_ink(doc: &mut Document, page: usize, index: usize, path: &[[f64; 2]
delete_annotation(doc, page, index)?;
return Ok(true);
}
// The retained runs are stored as the new `/InkList`: past the cap, writing them would leave a
// drawing that later `resize_ink` and `erase_ink` refuse to read.
let points: usize = kept.iter().map(Vec::len).sum();
if points > MAX_STORED_INK_POINTS {
return Err(AnnotError::Invalid(format!("erasing would leave a drawing with more than {MAX_STORED_INK_POINTS} points")));
}
let width = d.get(b"BS").and_then(|b| b.as_dict()).and_then(|b| b.get(b"W")).and_then(|w| w.as_f64()).unwrap_or(1.0);
let rect = grow(bounds(kept.iter().flatten().copied()).unwrap_or_default(), width / 2.0 + 1.0);
doc.update_dict(r, |d| {
+67
View File
@@ -4797,6 +4797,73 @@ fn freehand_highlight_is_compatible_ink_with_marker_blending() {
}
}
/// A drawing whose /InkList lists one stroke array over and over is refused once its points
/// pass the cap, counted as each stroke is resolved, before they are collected or scaled.
#[test]
fn ink_points_are_counted_as_strokes_resolve() {
let numbers: String = (0..2000).map(|k| format!(" {}", k % 100)).collect();
let refs = " 5 0 R".repeat(501);
let doc_with = |refs: &str| {
doc_of(&[
"<< /Type /Catalog /Pages 2 0 R >>".into(),
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 612 792] >>".into(),
"<< /Type /Page /Parent 2 0 R /Annots [4 0 R] >>".into(),
format!("<< /Type /Annot /Subtype /Ink /Rect [0 0 100 100] /InkList [{refs}] >>"),
format!("[{numbers}]"),
])
};
// 501 × 1,000 points is under the cap: the points are read (this bare drawing then has no
// appearance it can be redrawn with, which is another matter).
let mut doc = doc_with(&refs);
let under = set_rect(&mut doc, 0, 0, [0.0, 0.0, 50.0, 50.0], &meta(""));
assert!(!matches!(&under, Err(AnnotError::Invalid(m)) if m.contains("points")), "{under:?}");
// 1,001 × 1,000 points is over it.
let mut doc = doc_with(&" 5 0 R".repeat(1001));
match set_rect(&mut doc, 0, 0, [0.0, 0.0, 50.0, 50.0], &meta("")) {
Err(AnnotError::Invalid(m)) => assert!(m.contains("more than 1000000 points"), "{m}"),
other => panic!("refused: {other:?}"),
}
match erase_ink(&mut doc, 0, 0, &[[1.0, 1.0]], 1.0, &meta("")) {
Err(AnnotError::Invalid(m)) => assert!(m.contains("more than 1000000 points"), "{m}"),
other => panic!("refused: {other:?}"),
}
}
/// The eraser's densified samples have a total: a tiny eraser over long strokes is refused
/// instead of interpolating millions of points.
#[test]
fn the_eraser_densifies_within_a_total() {
let zigzag: String = (0..2100).map(|k| format!(" {} {}", if k % 2 == 0 { 0 } else { 5000 }, k)).collect();
let mut doc = doc_of(&[
"<< /Type /Catalog /Pages 2 0 R >>".into(),
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 612 792] >>".into(),
"<< /Type /Page /Parent 2 0 R /Annots [4 0 R] >>".into(),
format!("<< /Type /Annot /Subtype /Ink /Rect [0 0 5000 2100] /InkList [[{zigzag}]] >>"),
]);
match erase_ink(&mut doc, 0, 0, &[[1.0, 1.0]], 0.01, &meta("")) {
Err(AnnotError::Invalid(m)) => assert!(m.contains("too large to erase"), "{m}"),
other => panic!("refused: {other:?}"),
}
}
/// Each stroke's final point is a sample too: 500,000 strokes of two points at 8 samples a segment
/// are 4,000,000 densified samples and as many final points again, past the total.
#[test]
fn the_eraser_counts_each_strokes_final_point() {
let refs = " 5 0 R".repeat(500_000);
let mut doc = doc_of(&[
"<< /Type /Catalog /Pages 2 0 R >>".into(),
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 612 792] >>".into(),
"<< /Type /Page /Parent 2 0 R /Annots [4 0 R] >>".into(),
format!("<< /Type /Annot /Subtype /Ink /Rect [0 0 100 100] /InkList [{refs}] >>"),
"[0 0 8 0]".into(),
]);
match erase_ink(&mut doc, 0, 0, &[[1.0, 1.0]], 2.0, &meta("")) {
Err(AnnotError::Invalid(m)) => assert!(m.contains("too large to erase"), "{m}"),
other => panic!("refused: {other:?}"),
}
}
/// A 3D annotation is PDF 1.6 and a PRC model 1.7 (ISO 32000-2 §13.6): an older document's
/// catalog says so, and a newer one is left as it is.
#[test]
+57 -8
View File
@@ -21,12 +21,35 @@ fn request_json(r: &pdfcraft_engine::js::Request) -> Value {
}
}
/// The optional `field_id` argument: a field's identity from form_fields, selecting one of
/// fields sharing a name.
fn field_id(a: &Args) -> Result<Option<u64>> {
a.0.get("field_id")
.map(|v| {
v.as_u64()
.filter(|id| *id < 1 << 48)
.ok_or_else(|| ToolError::InvalidArgs("field_id must be an integer between 0 and 281474976710655".into()))
})
.transpose()
}
/// A message a script showed, as `js_run` reports it: its text, title (null when it gave none),
/// icon and buttons.
pub(crate) fn alert_json(m: &pdfcraft_engine::js::Message) -> Value {
json!({ "message": m.text, "title": m.title, "icon": m.icon.name(), "buttons": m.buttons.name() })
}
/// What scripts that ran unasked (a document's Will Save or Will Print actions) showed, said
/// or asked for, as tools report it.
pub(crate) fn js_output_json(out: &pdfcraft_engine::js::JsOutput) -> Value {
json!({
"alerts": out.alerts.iter().map(alert_json).collect::<Vec<_>>(),
"console": out.console,
"requests": out.requests.iter().map(request_json).collect::<Vec<_>>(),
"errors": out.errors,
})
}
impl Automation {
/// `js_run`: run `script` in the document, or as button `field`'s script, and report its
/// messages, console lines, requests, error, the failing document scripts' errors and result.
@@ -44,14 +67,7 @@ impl Automation {
.collect::<Result<Vec<_>>>()?,
_ => return Err(ToolError::InvalidArgs("answers must be an array of at most 32 strings or null".into())),
};
let identity =
a.0.get("field_id")
.map(|v| {
v.as_u64()
.filter(|id| *id < 1 << 48)
.ok_or_else(|| ToolError::InvalidArgs("field_id must be an integer between 0 and 281474976710655".into()))
})
.transpose()?;
let identity = field_id(a)?;
let (script, field) = (a.str("script")?, a.opt_str("field")?);
let (mut o, edit) =
self.session.with_own_js_output(id, |s| s.run_javascript_answers_target(id, script, field, identity, &answers)).map_err(failed)?;
@@ -122,6 +138,39 @@ impl Automation {
)
}
/// `js_event`: run the JavaScript widget `widget` (1-based) of field `field` has for `event`
/// (a trigger id: mouse_enter, mouse_exit, mouse_down, mouse_up, on_focus, on_blur); returns
/// whether the form changed and what the script showed or asked for.
pub(crate) fn js_event(&mut self, a: &Args) -> Result<Value> {
let event = a.str("event")?;
let trigger = pdfcraft_engine::FieldTrigger::from_id(event).ok_or_else(|| {
ToolError::InvalidArgs(format!("event must be mouse_enter, mouse_exit, mouse_down, mouse_up, on_focus or on_blur, not {event:?}"))
})?;
let name = a.str("field")?;
let identity = field_id(a)?;
let doc = self.doc(a)?;
let field =
doc.form.iter().find(|f| f.name == name && identity.is_none_or(|i| pdfcraft_engine::js::field_object_id(f.obj) == i)).ok_or_else(
|| match identity {
Some(i) => failed(format!("there is no field named {name:?} with field_id {i} (see form_fields)")),
None => failed(format!("there is no field named {name:?} (see form_fields)")),
},
)?;
let widgets = field.widgets.len();
let widget = a.opt_int("widget")?.unwrap_or(1);
let widget = usize::try_from(widget).ok().and_then(|w| w.checked_sub(1)).filter(|w| *w < widgets).ok_or_else(|| match widgets {
0 => ToolError::InvalidArgs(format!("{name:?} has no widget")),
n => ToolError::InvalidArgs(format!("widget must be 1 to {n} for {name:?}")),
})?;
let (id, object) = (doc.id, pdfcraft_engine::js::field_object_id(field.obj));
// Only this event's output: what opening or an earlier tool left waiting stays.
let (changed, out) =
self.session.with_own_js_output(id, |s| s.field_trigger_target(id, name, Some(object), widget, trigger)).map_err(failed)?;
let mut result = js_output_json(&out);
result["changed"] = json!(changed);
Ok(result)
}
/// `form_merge_data`: merge the form data files at `paths` into one CSV at `path`, a row per
/// file; returns the path and the row and column counts.
pub(crate) fn form_merge_data(&mut self, a: &Args) -> Result<Value> {
+1
View File
@@ -835,6 +835,7 @@ impl Automation {
"accessibility_autotag_form_fields" => self.accessibility_autotag_form_fields(&a)?,
"ocr_recognize" => self.ocr_recognize(&a)?,
"js_run" => self.js_run(&a)?,
"js_event" => self.js_event(&a)?,
"js_document_scripts" => self.js_document_scripts(&a)?,
"js_set_document_script" => self.js_set_document_script(&a)?,
"js_enabled" => self.js_enabled(&a)?,
+9 -1
View File
@@ -168,11 +168,19 @@ impl Automation {
if flatten_fill_sign {
self.apply(a, Edit::FlattenFillSign)?;
}
// The document's Will Save actions run first: what they change is saved (#269).
let scripts = self.session.run_document_actions(id, pdfcraft_engine::js::DocumentScriptEvent::WillSave);
let bytes = if full { self.session.save_full_bytes(id) } else { self.session.save_bytes(id) }.map_err(failed)?;
// A save that adds or removes encryption, or must not keep the old revision (Sanitize,
// redaction), is rewritten in full even when an incremental save was asked for.
let incremental = !full && bytes.starts_with(&self.doc(a)?.saved_bytes());
self.publish_save(id, &target, bytes, incremental, write)
let mut out = self.publish_save(id, &target, bytes, incremental, write)?;
if !scripts.is_empty()
&& let Some(o) = out.as_object_mut()
{
o.insert("will_save".into(), crate::a11y::form_tools::js_output_json(&scripts));
}
Ok(out)
}
/// Validate the prepared bytes before publishing them or marking the document saved.
+28 -7
View File
@@ -361,29 +361,50 @@ impl Automation {
let settings = print::Settings { pages, paper, orientation, layout, content, raster, crops: Vec::new(), area };
let laid_out = print::layout(&sizes, &settings).map_err(|e| bad(e.to_string()))?;
let sheets = laid_out.len();
// Where it goes is checked before the Will Print actions run, so a call that can't print
// doesn't change the document.
let destination = match (a.opt_str("path")?, printer) {
(Some(p), None) => Destination::File(self.resolve(p, true)?),
(None, Some(printer)) => {
let actual_printer = resolved_printer.as_deref().unwrap_or(printer);
Destination::Printer(spool_job(a, actual_printer, self.doc(a)?.name.clone(), duplex, media.as_deref(), settings.raster, &laid_out)?)
}
_ => return Err(bad("pass either path (save the print-ready PDF) or printer (a name from printers, or \"default\")")),
};
// The document's Will Print actions run first: what they change is printed (#269).
let scripts = if self.doc(a)?.allows_printing() {
self.session.run_document_actions(id, pdfcraft_engine::js::DocumentScriptEvent::WillPrint)
} else {
Default::default()
};
let bytes = self.session.print_pdf(id, &settings).map_err(failed)?;
let mut out = json!({ "sheets": sheets, "pages": settings.pages.len(), "bytes": bytes.len() });
match (a.opt_str("path")?, printer) {
(Some(p), None) => {
let path = self.resolve(p, true)?;
if !scripts.is_empty() {
out["will_print"] = crate::a11y::form_tools::js_output_json(&scripts);
}
match destination {
Destination::File(path) => {
write_atomic(&path, &bytes)?;
out["path"] = json!(path.to_string_lossy());
}
(None, Some(printer)) => {
let actual_printer = resolved_printer.as_deref().unwrap_or(printer);
let mut job = spool_job(a, actual_printer, self.doc(a)?.name.clone(), duplex, media.as_deref(), settings.raster, &laid_out)?;
Destination::Printer(mut job) => {
// A GDI (v3) driver gets transparent sheets flattened (#6155, #5838, #5940); XPS
// (v4) drivers print them as they are.
let flatten = job.printer.as_deref().is_some_and(spool::gdi_driver);
let bytes = pdfcraft_engine::spooler::spooler_copy(bytes, &mut job, flatten);
out["job"] = json!(spool::submit(&bytes, &job).map_err(|e| failed(e.to_string()))?);
}
_ => return Err(bad("pass either path (save the print-ready PDF) or printer (a name from printers, or \"default\")")),
}
Ok(out)
}
}
/// Where `doc_print` sends the sheets: a print-ready PDF file, or a printer's queue.
enum Destination {
File(std::path::PathBuf),
Printer(spool::Job),
}
/// "WxH" with a unit (in, mm, cm or pt) as a portrait paper size in points; each side 1 to 200
/// inches (PDF's own page limit).
fn paper_size(spec: &str) -> Option<(f64, f64)> {
+20 -5
View File
@@ -347,7 +347,7 @@ pub fn tools() -> Vec<ToolDef> {
json!({ "doc": doc(), "pages": pages("to extract"), "out": save_out.clone(), "open": open.clone(), "separate": { "type": "boolean" }, "out_dir": { "type": "string" }, "delete": { "type": "boolean" } }),
&["doc", "pages"],
)),
t("doc_combine", "Combine files", "Combine files, in order, into one PDF (bookmarks are kept under one entry per file). Images (PNG, JPEG, TIFF, GIF, BMP, JPEG 2000) and .txt files are made into PDFs first. pages optionally chooses each file's pages, in step with paths: a range such as \"1-3, 6\" or null for all pages. passwords, also in step with paths, opens encrypted files (the open password, or the permissions password where a file's security doesn't allow copying pages; null for none). The result is not encrypted. Passwords are never echoed back. groups, also in step with paths, splits a file around others: entries with the same number (they must name the same path) are one file, copied once, so it keeps one bookmark at its first page, its links and its form fields; null for a file of its own. A group uses its first entry's password. When two files' forms name the same field, field_conflicts says what happens: \"rename\" (the default) keeps the fields separate by renaming the later one (Text1 becomes Text1-1) and the result lists renamed_fields as [[old, new], …] — scripts that refer to the old name are not rewritten; \"merge\" makes them one field, as before.")
t("doc_combine", "Combine files", "Combine files, in order, into one PDF (bookmarks are kept under one entry per file). Images (PNG, JPEG, TIFF, GIF, BMP, JPEG 2000), .txt files and Office documents (Word, Excel, PowerPoint, OpenDocument, RTF; through an installed LibreOffice) are made into PDFs first. pages optionally chooses each file's pages, in step with paths: a range such as \"1-3, 6\" or null for all pages. passwords, also in step with paths, opens encrypted files (the open password, or the permissions password where a file's security doesn't allow copying pages; null for none). The result is not encrypted. Passwords are never echoed back. groups, also in step with paths, splits a file around others: entries with the same number (they must name the same path) are one file, copied once, so it keeps one bookmark at its first page, its links and its form fields; null for a file of its own. A group uses its first entry's password. When two files' forms name the same field, field_conflicts says what happens: \"rename\" (the default) keeps the fields separate by renaming the later one (Text1 becomes Text1-1) and the result lists renamed_fields as [[old, new], …] — scripts that refer to the old name are not rewritten; \"merge\" makes them one field, as before.")
.cmd("page.combine")
.with(schema(
json!({
@@ -361,7 +361,7 @@ pub fn tools() -> Vec<ToolDef> {
}),
&["paths"],
)),
t("doc_create_multiple", "Create PDF from multiple files", "Convert several files (PDFs, PNG/JPEG/JPEG 2000/TIFF/GIF/BMP images, .txt files) to PDF in one run. mode \"combine\" (default) joins them, in order, into one PDF with a bookmark per file; pages optionally chooses each file's pages, in step with paths (a range such as \"1-3, 6\" or null). mode \"separate\" writes one PDF per file into out_dir (files that are already PDFs are skipped; existing files are never overwritten) and reports each file's result.")
t("doc_create_multiple", "Create PDF from multiple files", "Convert several files (PDFs, PNG/JPEG/JPEG 2000/TIFF/GIF/BMP images, .txt files, Office documents through an installed LibreOffice) to PDF in one run. mode \"combine\" (default) joins them, in order, into one PDF with a bookmark per file; pages optionally chooses each file's pages, in step with paths (a range such as \"1-3, 6\" or null). mode \"separate\" writes one PDF per file into out_dir (files that are already PDFs are skipped; existing files are never overwritten) and reports each file's result.")
.cmd("create.multiple")
.with(schema(
json!({
@@ -543,7 +543,7 @@ pub fn tools() -> Vec<ToolDef> {
t(
"form_focus",
"Move the focus into or out of a field",
"A field gains (event enter) or loses (event exit) focus, as when someone clicks or tabs into or out of it, and the dynamic XFA form's enter or exit scripts for it run (other forms have none, and nothing happens). widget picks the radio button or copy of the field (1-based, default 1; see form_fields). What the scripts change is one undoable edit, and none when they change nothing. Changing a field's value (form_fill) runs its exit scripts already, so the next exit of that field doesn't run them again. Returns changed, and the scripts' alerts, console output, requests and errors.",
"A field gains (event enter) or loses (event exit) focus, as when someone clicks or tabs into or out of it, and the dynamic XFA form's enter or exit scripts for it run; on another form, the widget's own On Focus or On Blur JavaScript runs, if it has one (see also js_event). widget picks the radio button or copy of the field (1-based, default 1; see form_fields). What the scripts change is one undoable edit, and none when they change nothing. Changing a field's value (form_fill) runs its exit scripts already, so the next exit of that field doesn't run them again. Returns changed, and the scripts' alerts, console output, requests and errors.",
)
.with(schema(
json!({
@@ -726,7 +726,7 @@ pub fn tools() -> Vec<ToolDef> {
t(
"doc_hidden_info",
"Find hidden information",
"What Remove Hidden Information would remove, by category (metadata, attachments, comments, form-fields, hidden-text, hidden-layers, bookmarks, links-actions-scripts, private-data) with counts.",
"What Remove Hidden Information would remove, by category (metadata, attachments, comments, form-fields, hidden-text, hidden-layers, bookmarks, links-actions-scripts, private-data) with counts. A page that can't be read in full (its content streams don't decode, or they or a form they draw hold bytes the parser can't read or an inline image whose end is a guess) counts as one item of hidden-text and of hidden-layers: removing either category then fails on that page. With form-fields removed too, a field's appearance becomes page content and is read the same way, though it isn't counted here.",
)
.ro()
.with(schema(json!({ "doc": doc() }), &["doc"])),
@@ -1421,6 +1421,21 @@ pub fn tools() -> Vec<ToolDef> {
json!({ "doc": doc(), "script": { "type": "string" }, "field": { "type": "string", "description": "Run as this button's Mouse Up event." }, "field_id": {"type":"integer","minimum":0,"maximum":281474976710655u64,"description":"Optional exact field identity from form_fields; requires matching field name and is scoped to this document."}, "answers": {"type":"array","maxItems":32,"items":{"type":["string","null"],"maxLength":4096},"description":"Ordered popup, response and alert answers; strings are limited to 4096 UTF-8 bytes at runtime; null cancels a popup or response, and selects an alert default (OK, Cancel or No, by button set)."} }),
&["doc", "script"],
)),
t(
"js_event",
"Run a field's pointer or focus script",
"Run the JavaScript action widget `widget` of AcroForm field `field` has for `event`, as when the pointer enters (mouse_enter), leaves (mouse_exit), presses (mouse_down) or releases (mouse_up) it, or it gains (on_focus) or loses (on_blur) the focus, in the document's script realm (variables document scripts and earlier scripts left are kept), with event.name Mouse Enter, Mouse Exit, Mouse Down, Mouse Up, Focus or Blur. Nothing runs when the widget has no JavaScript for that event, JavaScript is off, or the form is a laid-out XFA form (use form_focus and js_run there). What it changes is one undoable edit. Pointer-over and focus scripts run unasked in a viewer, so their requests to print, open Save As or show a panel are dropped (noted on the console); mouse_down and mouse_up keep them. Returns changed, and the script's alerts, console output, requests and errors.",
)
.with(schema(
json!({
"doc": doc(),
"field": { "type": "string", "description": "Field name (from form_fields)." },
"event": { "type": "string", "enum": ["mouse_enter", "mouse_exit", "mouse_down", "mouse_up", "on_focus", "on_blur"] },
"field_id": {"type":"integer","minimum":0,"maximum":281474976710655u64,"description":"Optional exact field identity from form_fields: of fields sharing the name, the one to run."},
"widget": { "type": "integer", "minimum": 1, "description": "Widget of the field (1-based, default 1): a radio button of the group, or a copy of the field." },
}),
&["doc", "field", "event"],
)),
t("js_document_scripts", "Document JavaScripts", "List the document-level JavaScripts (name and source), which define functions field scripts use.")
.ro()
.cmd("tools.document_js")
@@ -1745,7 +1760,7 @@ pub fn tools() -> Vec<ToolDef> {
.with(schema(json!({ "doc": doc() }), &["doc"])),
t("doc_open_revision", "Open a revision", "Open saved revision `revision` (1 = the oldest) of a document as a new, unsaved document, to see the file as it was then.")
.with(schema(json!({ "doc": doc(), "revision": { "type": "integer", "minimum": 1 } }), &["doc", "revision"])),
t("doc_optimize", "Optimize PDF", "Write an optimized copy to `path` (Acrobat's PDF Optimizer). preset: standard (default; Reduce File Size's choices) or mobile (images to 96 ppi above 144, JPEG high quality); the options below change it. compatibility: retain (default; keeps the document's version, or 1.5 when object streams are written), 1.4, 1.5, 1.6, 1.7 or 2.0. merge_fragments (default true) first puts a page picture drawn as many stacked image strips (as some PDF printers write it) back together into one image, so it can be resampled (merged_images, fragments_merged). color / gray: { downsample, ppi, above_ppi, compression: jpeg|zip|retain, quality 1–100 } (defaults: downsample to 150 ppi above 225, JPEG 60). mono: { downsample, ppi, above_ppi, compression: ccitt_g4|jbig2|retain } for black-and-white images and image masks (default: averaged down to 300 ppi above 450 ppi, counted in images_resampled; stored losslessly as CCITT Group 4 or JBIG2 (or 1-bit Flate, once resampled or packed from more bits) when that is smaller, up to 16 JBIG2 images sharing one symbol dictionary (/JBIG2Globals) where that is smaller still (image masks and DeviceGray images named directly, of at most 64 Mi pixels, which redaction can store again without it), Group 3 fax images, JBIG2 images, black-and-white RGB and indexed images using only palette entries 0 and 1 among them, counted in images_recompressed; retain resamples only, a CCITT image staying CCITT, a JBIG2 image JBIG2 and any other becoming Flate). Images past what one run may decode stay as they are, counted in images_refused; streams it only stores with Flate past that stay LZW, uncounted. Images are measured where pages draw them and replaced only when smaller. discard_*: thumbnails (default true), alternate_images (true), tags, search_index (removes the catalog's /PieceInfo entries whose application name contains \"index\" in any letter case; search_indexes), print_settings (entries removed: print_settings), form_actions (submit, import and reset actions removed: form_actions; the fields and links stay, and the actions chained after one still run); flate_unencoded (true); object_streams (default true; always off for 1.4); lzw_to_flate (true) decodes LZW streams and stores them with Flate instead, leaving any it cannot decode unchanged (lzw_streams counts the streams converted); remove_invalid_links and remove_unreferenced_dests (true); discard_external_refs takes GoToR, GoToE, Launch and ImportData actions, and Thread actions with /F, out of links and bookmarks, removes a link left with nothing to do, and keeps links within the document and web links (external_links, external_bookmarks); images and forms the pages list but never draw are always dropped (unused_xobjects). discard: Remove Hidden Information categories (metadata, attachments, comments, form-fields, hidden-text, hidden-layers, bookmarks, links-actions-scripts, private-data). Signed documents are refused. target_bytes (optional): if the copy is larger, retry with up to 5 progressively stronger image settings (downsample to at most 110, 96, 72, 54, 36 ppi, applied to colour and grey images; images set to JPEG also get JPEG quality at most 45, 35, 28, 20, 12, while zip and retain images keep their encoding and only get the lower ppi) and stop at the first copy that fits; reports target_reached, attempts and target_settings, and writes the smallest copy with target_reached false when none fits. Without it nothing changes. The open document is unchanged.")
t("doc_optimize", "Optimize PDF", "Write an optimized copy to `path` (Acrobat's PDF Optimizer). preset: standard (default; Reduce File Size's choices) or mobile (images to 96 ppi above 144, JPEG high quality); the options below change it. compatibility: retain (default; keeps the document's version, or 1.5 when object streams are written), 1.4, 1.5, 1.6, 1.7 or 2.0. merge_fragments (default true) first puts a page picture drawn as many stacked image strips (as some PDF printers write it) back together into one image, so it can be resampled (merged_images, fragments_merged). color / gray: { downsample, ppi, above_ppi, compression: jpeg|zip|retain, quality 1–100 } (defaults: downsample to 150 ppi above 225, JPEG 60). mono: { downsample, ppi, above_ppi, compression: ccitt_g4|jbig2|retain } for black-and-white images and image masks (default: averaged down to 300 ppi above 450 ppi, counted in images_resampled; stored losslessly as CCITT Group 4 or JBIG2 (or 1-bit Flate, once resampled or packed from more bits) when that is smaller, up to 16 JBIG2 images sharing one symbol dictionary (/JBIG2Globals) where that is smaller still (image masks and DeviceGray images named directly, of at most 64 Mi pixels, which redaction can store again without it), Group 3 fax images, JBIG2 images, black-and-white RGB and indexed images using only palette entries 0 and 1 among them, counted in images_recompressed; a picture's stencil /Mask and one-bit /SMask are stored again the same way, at their size, not resampled and sharing no dictionary, counted as images; retain resamples only, a CCITT image staying CCITT, a JBIG2 image JBIG2 and any other becoming Flate). Images past what one run may decode stay as they are, counted in images_refused; streams it only stores with Flate past that stay LZW, uncounted. Images are measured where pages draw them and replaced only when smaller. discard_*: thumbnails (default true), alternate_images (true), tags, search_index (removes the catalog's /PieceInfo entries whose application name contains \"index\" in any letter case; search_indexes), print_settings (entries removed: print_settings), form_actions (submit, import and reset actions removed: form_actions; the fields and links stay, and the actions chained after one still run); flate_unencoded (true); object_streams (default true; always off for 1.4); lzw_to_flate (true) decodes LZW streams and stores them with Flate instead, leaving any it cannot decode unchanged (lzw_streams counts the streams converted); remove_invalid_links and remove_unreferenced_dests (true); discard_external_refs takes GoToR, GoToE, Launch and ImportData actions, and Thread actions with /F, out of links and bookmarks, removes a link left with nothing to do, and keeps links within the document and web links (external_links, external_bookmarks); images and forms the pages list but never draw are always dropped (unused_xobjects). discard: Remove Hidden Information categories (metadata, attachments, comments, form-fields, hidden-text, hidden-layers, bookmarks, links-actions-scripts, private-data). Signed documents are refused. target_bytes (optional): if the copy is larger, retry with up to 5 progressively stronger image settings (downsample to at most 110, 96, 72, 54, 36 ppi, applied to colour and grey images; images set to JPEG also get JPEG quality at most 45, 35, 28, 20, 12, while zip and retain images keep their encoding and only get the lower ppi) and stop at the first copy that fits; reports target_reached, attempts and target_settings, and writes the smallest copy with target_reached false when none fits. Without it nothing changes. The open document is unchanged.")
.cmd("optimize.advanced")
.with(schema(
json!({
+61 -6
View File
@@ -1226,7 +1226,7 @@ fn combine_takes_images_and_text_files() {
std::fs::write(dir.join("scan.png"), png).unwrap();
std::fs::write(dir.join("notes.txt"), "Some notes").unwrap();
std::fs::write(dir.join("broken.png"), b"\x89PNG\r\n\x1a\nbroken").unwrap();
std::fs::write(dir.join("report.docx"), b"PK\x03\x04").unwrap();
std::fs::write(dir.join("archive.zip"), b"PK\x03\x04").unwrap();
let mut a = auto(&dir);
let combined = ok(&mut a, "doc_combine", json!({ "paths": ["a.pdf", "scan.png", "notes.txt"], "pages": [null, null, "1"], "open": true }));
let doc = combined["document"]["doc"].as_u64().unwrap();
@@ -1236,7 +1236,7 @@ fn combine_takes_images_and_text_files() {
let titles: Vec<&str> = marks.as_array().unwrap().iter().map(|b| b["title"].as_str().unwrap()).collect();
assert_eq!(titles, ["a", "scan", "notes"]);
// A file that can't be made into a PDF stops the combine, and says which.
for bad in ["broken.png", "report.docx"] {
for bad in ["broken.png", "archive.zip"] {
let refused = a.call("doc_combine", &json!({ "paths": ["a.pdf", bad] }));
assert!(matches!(&refused, Err(ToolError::Failed(e)) if e.contains(bad)), "{bad}: {refused:?}");
}
@@ -5452,7 +5452,7 @@ fn creating_from_multiple_files_through_tools() {
}
std::fs::write(dir.join("scan.png"), png).unwrap();
std::fs::write(dir.join("notes.txt"), "hello").unwrap();
std::fs::write(dir.join("report.docx"), b"PK\x03\x04").unwrap();
std::fs::write(dir.join("archive.zip"), b"PK\x03\x04").unwrap();
let mut a = auto(&dir);
// Combine: every file converted, in the order given, with a bookmark per file.
@@ -5472,8 +5472,8 @@ fn creating_from_multiple_files_through_tools() {
assert_eq!(titles, ["notes", "a", "scan"]);
assert!(dir.join("all.pdf").is_file());
// A file that can't be converted fails the whole combine, naming it.
let err = a.call("doc_create_multiple", &json!({ "paths": ["a.pdf", "report.docx"] })).unwrap_err();
assert!(matches!(&err, ToolError::Failed(m) if m.contains("report.docx") && m.contains("can't be converted")), "{err}");
let err = a.call("doc_create_multiple", &json!({ "paths": ["a.pdf", "archive.zip"] })).unwrap_err();
assert!(matches!(&err, ToolError::Failed(m) if m.contains("archive.zip") && m.contains("can't be converted")), "{err}");
assert!(matches!(a.call("doc_create_multiple", &json!({ "paths": [] })), Err(ToolError::InvalidArgs(_))));
assert!(matches!(a.call("doc_create_multiple", &json!({ "paths": ["a.pdf"], "mode": "zip" })), Err(ToolError::InvalidArgs(_))));
assert!(matches!(a.call("doc_create_multiple", &json!({ "paths": ["a.pdf"], "mode": "separate" })), Err(ToolError::InvalidArgs(_))));
@@ -5482,7 +5482,7 @@ fn creating_from_multiple_files_through_tools() {
// existing file is never overwritten.
std::fs::create_dir_all(dir.join("out")).unwrap();
std::fs::write(dir.join("out/notes.pdf"), b"mine").unwrap();
let args = json!({ "paths": ["notes.txt", "report.docx", "a.pdf", "scan.png", "missing.txt"], "mode": "separate", "out_dir": "out" });
let args = json!({ "paths": ["notes.txt", "archive.zip", "a.pdf", "scan.png", "missing.txt"], "mode": "separate", "out_dir": "out" });
let made = ok(&mut a, "doc_create_multiple", args);
let files = made["files"].as_array().unwrap();
assert!(files[0]["output"].as_str().unwrap().ends_with("notes (2).pdf"), "{files:?}");
@@ -8986,6 +8986,61 @@ fn doc_optimize_stores_black_and_white_images_as_ccitt_group_4() {
}
}
/// A mixed-raster page: a flat colour layer drawn through a one-bit soft mask, [`scanned_page`]'s
/// scan, which the page no longer draws by name. `doc_optimize` stores the mask as Group 4, at its
/// size, still the picture's soft mask, and counts it as an image; with `mono: retain` it stays.
#[test]
fn doc_optimize_stores_a_pictures_one_bit_soft_mask_as_ccitt_group_4() {
use pdfcraft_cos::{Dict, Document, ObjRef, Object, SaveOptions, Stream, write_full};
let dir = workdir("optimize-mono-mask");
let mut doc = Document::open(std::sync::Arc::new(scanned_page())).unwrap();
let find = |doc: &Document, kind: &[u8], key: &[u8]| {
doc.object_numbers().into_iter().map(|num| ObjRef { num, generation: doc.generation(num) }).find(|r| match &*doc.get(*r) {
Object::Stream(s) => s.dict.name(key) == Some(kind),
Object::Dict(d) => d.name(key) == Some(kind),
_ => false,
})
};
let scan = find(&doc, b"Image", b"Subtype").unwrap();
let page = find(&doc, b"Page", b"Type").unwrap();
let mut d = Dict::new();
d.set(b"Type".to_vec(), Object::name("XObject"));
d.set(b"Subtype".to_vec(), Object::name("Image"));
d.set(b"Width".to_vec(), Object::Int(250));
d.set(b"Height".to_vec(), Object::Int(100));
d.set(b"BitsPerComponent".to_vec(), Object::Int(8));
d.set(b"ColorSpace".to_vec(), Object::name("DeviceRGB"));
d.set(b"SMask".to_vec(), Object::Ref(scan));
let picture = doc.add(Object::Stream(Stream::flate(d, &[0, 102, 204].repeat(250 * 100))));
doc.update_dict(page, |p| {
let mut x = Dict::new();
x.set(b"Scan".to_vec(), Object::Ref(picture));
let mut res = Dict::new();
res.set(b"XObject".to_vec(), Object::Dict(x));
p.set(b"Resources".to_vec(), Object::Dict(res));
})
.unwrap();
std::fs::write(dir.join("masked.pdf"), write_full(&doc, &SaveOptions::default()).unwrap()).unwrap();
let mut a = auto(&dir);
let doc = ok(&mut a, "doc_open", json!({ "path": "masked.pdf" }))["doc"].as_u64().unwrap();
let kept = ok(&mut a, "doc_optimize", json!({ "doc": doc, "path": "kept.pdf", "mono": { "compression": "retain" } }));
assert_eq!(kept["images_recompressed"].as_u64(), Some(0), "{kept}");
let r = ok(&mut a, "doc_optimize", json!({ "doc": doc, "path": "small.pdf" }));
assert_eq!((r["images"].as_u64(), r["images_recompressed"].as_u64()), (Some(2), Some(1)), "the picture and its mask: {r}");
// In the copy written, the picture's soft mask is Group 4, at its size.
let small = Document::open(std::sync::Arc::new(std::fs::read(dir.join("small.pdf")).unwrap())).unwrap();
let picture = small
.object_numbers()
.into_iter()
.map(|num| small.get(ObjRef { num, generation: small.generation(num) }))
.find(|o| matches!(&**o, Object::Stream(s) if s.dict.contains(b"SMask")))
.unwrap();
let Object::Stream(picture) = &*picture else { unreachable!() };
let Object::Stream(mask) = &*small.get(picture.dict.reference(b"SMask").unwrap()) else { panic!("the soft mask is a stream") };
assert_eq!(mask.dict.name(b"Filter"), Some(&b"CCITTFaxDecode"[..]));
assert_eq!((mask.dict.int(b"Width"), mask.dict.int(b"Height")), (Some(1000), Some(400)));
}
/// A scan drawn at 600 ppi is averaged down to 300 ppi by default. `mono: { downsample: false }`
/// keeps its size, `ppi` and `above_ppi` choose others, and values of the wrong type are refused.
#[test]
@@ -0,0 +1,125 @@
//! A form's document actions and pointer/focus scripts through the tool table (#269, ported
//! from #344): the open action runs on doc_open, Will Save on doc_save, Will Print on
//! doc_print, and js_event runs a widget's pointer and focus scripts, all in one realm.
use pdfcraft_automation::{Automation, Content};
use serde_json::{Value, json};
fn tool(a: &mut Automation, name: &str, args: Value) -> Value {
match a.call(name, &args).unwrap().remove(0) {
Content::Json(value) => value,
other => panic!("expected JSON: {other:?}"),
}
}
fn pdf_of(objs: &[String]) -> Vec<u8> {
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 o in offsets {
out.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());
}
out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes());
out
}
/// `log` records what ran; `hot` has Mouse Enter and On Blur scripts. The open action counts
/// in a variable the Will Save and Will Print actions and `hot`'s scripts read.
fn form() -> Vec<u8> {
pdf_of(&[
"<< /Type /Catalog /Pages 2 0 R /OpenAction 6 0 R /AA << /WS 7 0 R /WP 8 0 R >> /AcroForm << /Fields [4 0 R 9 0 R] /DA (/Helv 0 Tf 0 g) /DR << /Font << /Helv 5 0 R >> >> >> >>".into(),
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 200 300] >>".into(),
"<< /Type /Page /Parent 2 0 R /Annots [4 0 R 9 0 R] >>".into(),
"<< /Type /Annot /Subtype /Widget /FT /Tx /T (log) /V () /Rect [20 250 180 270] /P 3 0 R /F 4 >>".into(),
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".into(),
"<< /S /JavaScript /JS (var n = 1; getField\\('log'\\).value = 'open' + n;) >>".into(),
"<< /S /JavaScript /JS (n++; getField\\('log'\\).value += ' save' + n; console.println\\('saving'\\);) >>".into(),
"<< /S /JavaScript /JS (n++; getField\\('log'\\).value += ' print' + n;) >>".into(),
"<< /Type /Annot /Subtype /Widget /FT /Tx /T (hot) /V () /Rect [20 200 180 220] /P 3 0 R /F 4 /AA << /E << /S /JavaScript /JS (n++; getField\\('log'\\).value += ' ' + event.name + n;) >> /Bl << /S /JavaScript /JS (this.print\\(\\); getField\\('log'\\).value += ' ' + event.name;) >> >> >>".into(),
])
}
fn log(a: &mut Automation, doc: u64) -> Value {
let f = tool(a, "form_fields", json!({ "doc": doc }));
f["fields"].as_array().unwrap().iter().find(|f| f["name"] == "log").map(|f| f["value"].clone()).unwrap()
}
#[test]
fn open_will_save_will_print_and_field_events_share_the_document_realm() {
let dir = std::env::temp_dir().join(format!("pdfcraft-document-actions-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("form.pdf"), form()).unwrap();
let mut a = Automation::new().with_root(&dir).unwrap().with_clock(|| 1_700_000_000);
let doc = tool(&mut a, "doc_open", json!({ "path": "form.pdf" }))["doc"].as_u64().unwrap();
assert_eq!(log(&mut a, doc), "open1");
let entered = tool(&mut a, "js_event", json!({ "doc": doc, "field": "hot", "event": "mouse_enter" }));
assert_eq!(entered["changed"], true, "{entered}");
assert_eq!(log(&mut a, doc), "open1 Mouse Enter2");
// Losing the focus happens unasked: its print request is dropped and noted.
let blurred = tool(&mut a, "js_event", json!({ "doc": doc, "field": "hot", "event": "on_blur" }));
assert_eq!(blurred["requests"], json!([]), "{blurred}");
assert_eq!(log(&mut a, doc), "open1 Mouse Enter2 Blur");
let none = tool(&mut a, "js_event", json!({ "doc": doc, "field": "log", "event": "mouse_down" }));
assert_eq!(none["changed"], false, "no script: {none}");
assert!(a.call("js_event", &json!({ "doc": doc, "field": "hot", "event": "keystroke" })).is_err());
assert!(a.call("js_event", &json!({ "doc": doc, "field": "hot", "event": "mouse_up", "widget": 2 })).is_err());
// Saved in place (incrementally): object numbers stay, so the realm is kept. A full
// rewrite starts a fresh realm for the next event.
let saved = tool(&mut a, "doc_save", json!({ "doc": doc }));
assert_eq!(saved["incremental"], true, "{saved}");
std::fs::copy(dir.join("form.pdf"), dir.join("saved.pdf")).unwrap();
assert_eq!(saved["will_save"]["console"], json!(["saving"]), "{saved}");
assert_eq!(log(&mut a, doc), "open1 Mouse Enter2 Blur save3");
let printed = tool(&mut a, "doc_print", json!({ "doc": doc, "path": "printed.pdf" }));
assert!(printed.get("will_print").is_none(), "nothing to report: {printed}");
assert_eq!(log(&mut a, doc), "open1 Mouse Enter2 Blur save3 print4");
// A print with nowhere to go fails before Will Print runs.
assert!(a.call("doc_print", &json!({ "doc": doc })).is_err());
assert_eq!(log(&mut a, doc), "open1 Mouse Enter2 Blur save3 print4");
// What Will Save changed is in the saved file.
tool(&mut a, "js_enabled", json!({ "enabled": false }));
let reopened = tool(&mut a, "doc_open", json!({ "path": "saved.pdf" }))["doc"].as_u64().unwrap();
assert_eq!(log(&mut a, reopened), "open1 Mouse Enter2 Blur save3");
}
/// Of two fields sharing a name, `field_id` (from form_fields) picks the one js_event runs; by
/// name alone it is the first.
#[test]
fn js_event_runs_the_field_its_field_id_names() {
let enter = |text: &str| format!("/AA << /E << /S /JavaScript /JS (getField\\('log'\\).value += '{text}';) >> >>");
let pdf = pdf_of(&[
"<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [4 0 R 6 0 R 7 0 R] /DA (/Helv 0 Tf 0 g) /DR << /Font << /Helv 5 0 R >> >> >> >>".into(),
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 200 300] >>".into(),
"<< /Type /Page /Parent 2 0 R /Annots [4 0 R 6 0 R 7 0 R] >>".into(),
"<< /Type /Annot /Subtype /Widget /FT /Tx /T (log) /V () /Rect [20 250 180 270] /P 3 0 R /F 4 >>".into(),
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".into(),
format!("<< /Type /Annot /Subtype /Widget /FT /Tx /T (dup) /V () /Rect [20 200 180 220] /P 3 0 R /F 4 {} >>", enter("first;")),
format!("<< /Type /Annot /Subtype /Widget /FT /Tx /T (dup) /V () /Rect [20 150 180 170] /P 3 0 R /F 4 {} >>", enter("second;")),
]);
let dir = std::env::temp_dir().join(format!("pdfcraft-js-event-dup-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("dup.pdf"), pdf).unwrap();
let mut a = Automation::new().with_root(&dir).unwrap();
let doc = tool(&mut a, "doc_open", json!({ "path": "dup.pdf" }))["doc"].as_u64().unwrap();
let fields = tool(&mut a, "form_fields", json!({ "doc": doc }));
let ids: Vec<u64> = fields["fields"].as_array().unwrap().iter().filter(|f| f["name"] == "dup").map(|f| f["field_id"].as_u64().unwrap()).collect();
assert_eq!(ids.len(), 2, "{fields}");
tool(&mut a, "js_event", json!({ "doc": doc, "field": "dup", "field_id": ids[1], "event": "mouse_enter" }));
assert_eq!(log(&mut a, doc), "second;");
tool(&mut a, "js_event", json!({ "doc": doc, "field": "dup", "event": "mouse_enter" }));
assert_eq!(log(&mut a, doc), "second;first;");
assert!(
a.call("js_event", &json!({ "doc": doc, "field": "log", "field_id": ids[1], "event": "mouse_enter" })).is_err(),
"the id is another field's"
);
let _ = std::fs::remove_dir_all(&dir);
}
+2
View File
@@ -9,12 +9,14 @@ mod batch;
mod batch_failures;
mod batch_secrets;
mod button_caption;
mod document_actions;
mod find_text;
mod form_bulk;
mod hostile_args;
mod list_selection;
mod model_3d;
mod model_render;
mod office;
mod optimize_content_boundaries;
mod portfolio_info;
mod redact_after_stray_q_form;
+277
View File
@@ -0,0 +1,277 @@
//! Office documents converted by a real LibreOffice through the tools that take them
//! (`doc_create_multiple`, `doc_combine`), with the converted text checked. Every test here
//! skips when LibreOffice isn't installed, which is the case on CI; run them on a machine that
//! has it. The Word, Excel and PowerPoint files are written here, as the smallest packages
//! LibreOffice reads, so no binary fixtures are committed.
use std::path::Path;
use pdfcraft_automation::{Automation, Content, ToolError};
use serde_json::{Value, json};
fn auto(dir: &Path) -> Automation {
Automation::new().with_root(dir).unwrap().with_clock(|| 1_700_000_000)
}
fn ok(a: &mut Automation, tool: &str, args: Value) -> Value {
match a.call(tool, &args) {
Ok(mut c) => match c.remove(0) {
Content::Json(v) => v,
other => panic!("{tool}: expected JSON, got {other:?}"),
},
Err(e) => panic!("{tool} {args}: {e}"),
}
}
/// Each page's text, with runs of whitespace made single spaces.
fn page_text(a: &mut Automation, doc: u64) -> Vec<String> {
ok(a, "text_extract", json!({ "doc": doc }))["pages"]
.as_array()
.unwrap()
.iter()
.map(|p| p["text"].as_str().unwrap().split_whitespace().collect::<Vec<_>>().join(" "))
.collect()
}
/// A ZIP of `entries`, stored without compression (Office packages may be).
fn zip(entries: &[(&str, &str)]) -> Vec<u8> {
fn crc32(data: &[u8]) -> u32 {
let mut crc = !0u32;
for &b in data {
crc ^= u32::from(b);
for _ in 0..8 {
crc = if crc & 1 == 1 { (crc >> 1) ^ 0xEDB8_8320 } else { crc >> 1 };
}
}
!crc
}
let (mut out, mut central) = (Vec::new(), Vec::new());
for (name, data) in entries {
let (crc, size, offset) = (crc32(data.as_bytes()), data.len() as u32, out.len() as u32);
// version 2.0, no flags, stored, 1980-01-01 00:00
let common = [&20u16.to_le_bytes()[..], &0u16.to_le_bytes(), &0u16.to_le_bytes(), &0u16.to_le_bytes(), &0x21u16.to_le_bytes()].concat();
let sizes = [crc.to_le_bytes(), size.to_le_bytes(), size.to_le_bytes()].concat();
out.extend_from_slice(&0x0403_4b50u32.to_le_bytes());
out.extend_from_slice(&common);
out.extend_from_slice(&sizes);
out.extend_from_slice(&(name.len() as u16).to_le_bytes());
out.extend_from_slice(&0u16.to_le_bytes());
out.extend_from_slice(name.as_bytes());
out.extend_from_slice(data.as_bytes());
central.extend_from_slice(&0x0201_4b50u32.to_le_bytes());
central.extend_from_slice(&20u16.to_le_bytes());
central.extend_from_slice(&common);
central.extend_from_slice(&sizes);
central.extend_from_slice(&(name.len() as u16).to_le_bytes());
// extra, comment, disk, internal and external attributes
central.extend_from_slice(&[0u8; 12]);
central.extend_from_slice(&offset.to_le_bytes());
central.extend_from_slice(name.as_bytes());
}
let (at, count) = (out.len() as u32, entries.len() as u16);
out.extend_from_slice(&central);
out.extend_from_slice(&0x0605_4b50u32.to_le_bytes());
out.extend_from_slice(&[0u8; 4]);
out.extend_from_slice(&count.to_le_bytes());
out.extend_from_slice(&count.to_le_bytes());
out.extend_from_slice(&(central.len() as u32).to_le_bytes());
out.extend_from_slice(&at.to_le_bytes());
out.extend_from_slice(&0u16.to_le_bytes());
out
}
const XML: &str = r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>"#;
const PACKAGE_RELS: &str = "http://schemas.openxmlformats.org/package/2006/relationships";
const DOC_RELS: &str = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
/// `[Content_Types].xml` with one override per (part, type).
fn content_types(parts: &[(&str, &str)]) -> String {
let overrides: String = parts.iter().map(|(part, kind)| format!(r#"<Override PartName="/{part}" ContentType="{kind}"/>"#)).collect();
format!(
r#"{XML}<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/>{overrides}</Types>"#
)
}
/// A relationships part with one relationship per (id, type under officeDocument, target).
fn rels(list: &[(&str, &str, &str)]) -> String {
let items: String =
list.iter().map(|(id, kind, target)| format!(r#"<Relationship Id="{id}" Type="{DOC_RELS}/{kind}" Target="{target}"/>"#)).collect();
format!(r#"{XML}<Relationships xmlns="{PACKAGE_RELS}">{items}</Relationships>"#)
}
/// A Word document of one paragraph.
fn docx(text: &str) -> Vec<u8> {
let document = format!(
r#"{XML}<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body><w:p><w:r><w:t>{text}</w:t></w:r></w:p></w:body></w:document>"#
);
zip(&[
(
"[Content_Types].xml",
&content_types(&[("word/document.xml", "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml")]),
),
("_rels/.rels", &rels(&[("rId1", "officeDocument", "word/document.xml")])),
("word/document.xml", &document),
])
}
/// An Excel workbook whose one sheet holds `text` in A1 and a formula, `=6*7`, in A2.
fn xlsx(text: &str) -> Vec<u8> {
let workbook = format!(
r#"{XML}<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="{DOC_RELS}"><sheets><sheet name="Sheet1" sheetId="1" r:id="rId1"/></sheets></workbook>"#
);
let sheet = format!(
r#"{XML}<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><sheetData><row r="1"><c r="A1" t="inlineStr"><is><t>{text}</t></is></c></row><row r="2"><c r="A2"><f>6*7</f></c></row></sheetData></worksheet>"#
);
zip(&[
(
"[Content_Types].xml",
&content_types(&[
("xl/workbook.xml", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"),
("xl/worksheets/sheet1.xml", "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"),
]),
),
("_rels/.rels", &rels(&[("rId1", "officeDocument", "xl/workbook.xml")])),
("xl/workbook.xml", &workbook),
("xl/_rels/workbook.xml.rels", &rels(&[("rId1", "worksheet", "worksheets/sheet1.xml")])),
("xl/worksheets/sheet1.xml", &sheet),
])
}
/// A PowerPoint presentation of one slide with one text box.
fn pptx(text: &str) -> Vec<u8> {
const P: &str =
r#"xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main""#;
let presentation = format!(
r#"{XML}<p:presentation {P} xmlns:r="{DOC_RELS}"><p:sldMasterIdLst><p:sldMasterId id="2147483648" r:id="rId1"/></p:sldMasterIdLst><p:sldIdLst><p:sldId id="256" r:id="rId2"/></p:sldIdLst><p:sldSz cx="9144000" cy="6858000"/><p:notesSz cx="6858000" cy="9144000"/></p:presentation>"#
);
let tree = r#"<p:cSld><p:spTree><p:nvGrpSpPr><p:cNvPr id="1" name=""/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr><p:grpSpPr/>"#;
let master = format!(
r#"{XML}<p:sldMaster {P} xmlns:r="{DOC_RELS}">{tree}</p:spTree></p:cSld><p:clrMap bg1="lt1" tx1="dk1" bg2="lt2" tx2="dk2" accent1="accent1" accent2="accent2" accent3="accent3" accent4="accent4" accent5="accent5" accent6="accent6" hlink="hlink" folHlink="folHlink"/><p:sldLayoutIdLst><p:sldLayoutId id="2147483649" r:id="rId1"/></p:sldLayoutIdLst></p:sldMaster>"#
);
let layout = format!(r#"{XML}<p:sldLayout {P}>{tree}</p:spTree></p:cSld></p:sldLayout>"#);
let slide = format!(
r#"{XML}<p:sld {P}>{tree}<p:sp><p:nvSpPr><p:cNvPr id="2" name="Text"/><p:cNvSpPr txBox="1"/><p:nvPr/></p:nvSpPr><p:spPr><a:xfrm><a:off x="914400" y="914400"/><a:ext cx="6000000" cy="1000000"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom></p:spPr><p:txBody><a:bodyPr/><a:p><a:r><a:rPr lang="en-US" sz="2800"/><a:t>{text}</a:t></a:r></a:p></p:txBody></p:sp></p:spTree></p:cSld></p:sld>"#
);
let theme = format!(
r#"{XML}<a:theme xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" name="Plain"><a:themeElements><a:clrScheme name="Plain"><a:dk1><a:srgbClr val="000000"/></a:dk1><a:lt1><a:srgbClr val="FFFFFF"/></a:lt1><a:dk2><a:srgbClr val="000000"/></a:dk2><a:lt2><a:srgbClr val="FFFFFF"/></a:lt2><a:accent1><a:srgbClr val="4472C4"/></a:accent1><a:accent2><a:srgbClr val="ED7D31"/></a:accent2><a:accent3><a:srgbClr val="A5A5A5"/></a:accent3><a:accent4><a:srgbClr val="FFC000"/></a:accent4><a:accent5><a:srgbClr val="5B9BD5"/></a:accent5><a:accent6><a:srgbClr val="70AD47"/></a:accent6><a:hlink><a:srgbClr val="0563C1"/></a:hlink><a:folHlink><a:srgbClr val="954F72"/></a:folHlink></a:clrScheme><a:fontScheme name="Plain"><a:majorFont><a:latin typeface="Arial"/><a:ea typeface=""/><a:cs typeface=""/></a:majorFont><a:minorFont><a:latin typeface="Arial"/><a:ea typeface=""/><a:cs typeface=""/></a:minorFont></a:fontScheme><a:fmtScheme name="Plain"><a:fillStyleLst><a:solidFill><a:schemeClr val="phClr"/></a:solidFill><a:solidFill><a:schemeClr val="phClr"/></a:solidFill><a:solidFill><a:schemeClr val="phClr"/></a:solidFill></a:fillStyleLst><a:lnStyleLst><a:ln><a:solidFill><a:schemeClr val="phClr"/></a:solidFill></a:ln><a:ln><a:solidFill><a:schemeClr val="phClr"/></a:solidFill></a:ln><a:ln><a:solidFill><a:schemeClr val="phClr"/></a:solidFill></a:ln></a:lnStyleLst><a:effectStyleLst><a:effectStyle><a:effectLst/></a:effectStyle><a:effectStyle><a:effectLst/></a:effectStyle><a:effectStyle><a:effectLst/></a:effectStyle></a:effectStyleLst><a:bgFillStyleLst><a:solidFill><a:schemeClr val="phClr"/></a:solidFill><a:solidFill><a:schemeClr val="phClr"/></a:solidFill><a:solidFill><a:schemeClr val="phClr"/></a:solidFill></a:bgFillStyleLst></a:fmtScheme></a:themeElements></a:theme>"#
);
const PML: &str = "application/vnd.openxmlformats-officedocument.presentationml";
let types = content_types(&[
("ppt/presentation.xml", &format!("{PML}.presentation.main+xml")),
("ppt/slideMasters/slideMaster1.xml", &format!("{PML}.slideMaster+xml")),
("ppt/slideLayouts/slideLayout1.xml", &format!("{PML}.slideLayout+xml")),
("ppt/slides/slide1.xml", &format!("{PML}.slide+xml")),
("ppt/theme/theme1.xml", "application/vnd.openxmlformats-officedocument.theme+xml"),
]);
zip(&[
("[Content_Types].xml", &types),
("_rels/.rels", &rels(&[("rId1", "officeDocument", "ppt/presentation.xml")])),
("ppt/presentation.xml", &presentation),
(
"ppt/_rels/presentation.xml.rels",
&rels(&[
("rId1", "slideMaster", "slideMasters/slideMaster1.xml"),
("rId2", "slide", "slides/slide1.xml"),
("rId3", "theme", "theme/theme1.xml"),
]),
),
("ppt/slideMasters/slideMaster1.xml", &master),
(
"ppt/slideMasters/_rels/slideMaster1.xml.rels",
&rels(&[("rId1", "slideLayout", "../slideLayouts/slideLayout1.xml"), ("rId2", "theme", "../theme/theme1.xml")]),
),
("ppt/slideLayouts/slideLayout1.xml", &layout),
("ppt/slideLayouts/_rels/slideLayout1.xml.rels", &rels(&[("rId1", "slideMaster", "../slideMasters/slideMaster1.xml")])),
("ppt/slides/slide1.xml", &slide),
("ppt/slides/_rels/slide1.xml.rels", &rels(&[("rId1", "slideLayout", "../slideLayouts/slideLayout1.xml")])),
("ppt/theme/theme1.xml", &theme),
])
}
/// An RTF document of one paragraph.
fn rtf(text: &str) -> Vec<u8> {
format!("{{\\rtf1\\ansi{{\\fonttbl\\f0\\fswiss Helvetica;}}\\f0\\pard {text}\\par}}").into_bytes()
}
/// A folder with one Word, Excel, PowerPoint and RTF file, each carrying its own word, and the
/// tools rooted there; `None` when LibreOffice isn't installed.
fn office_files() -> Option<(tempfile::TempDir, Automation)> {
let dir = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join("letter.docx"), docx("Quokka letter")).unwrap();
std::fs::write(dir.path().join("budget.xlsx"), xlsx("Narwhal budget")).unwrap();
std::fs::write(dir.path().join("deck.pptx"), pptx("Axolotl deck")).unwrap();
std::fs::write(dir.path().join("notes.rtf"), rtf("Pangolin notes")).unwrap();
let mut a = auto(dir.path());
match a.call("doc_create_multiple", &json!({ "paths": ["notes.rtf"] })) {
Err(ToolError::Failed(e)) if e.contains("needs LibreOffice") => {
eprintln!("skipped: LibreOffice isn't installed");
None
}
_ => Some((dir, a)),
}
}
/// Each Office format converts to a PDF of its own that holds the document's text (and, for
/// the spreadsheet, the formula's value).
#[test]
fn office_documents_convert_separately_with_their_text() {
let Some((dir, mut a)) = office_files() else { return };
let paths = ["letter.docx", "budget.xlsx", "deck.pptx", "notes.rtf"];
let made = ok(&mut a, "doc_create_multiple", json!({ "paths": paths, "mode": "separate", "out_dir": "out" }));
let files = made["files"].as_array().unwrap();
assert_eq!(files.len(), 4, "{made}");
let expected = [
("letter.pdf", &["Quokka letter"][..]),
("budget.pdf", &["Narwhal budget", "42"]),
("deck.pdf", &["Axolotl deck"]),
("notes.pdf", &["Pangolin notes"]),
];
for (file, (name, words)) in files.iter().zip(expected) {
let output = file["output"].as_str().unwrap_or_else(|| panic!("{file}"));
// The tool reports the folder in its canonical form (`\\?\C:\…` on Windows).
assert_eq!(Path::new(output).file_name(), Some(std::ffi::OsStr::new(name)), "{output}");
assert!(dir.path().join("out").join(name).is_file(), "{name}");
let doc = ok(&mut a, "doc_open", json!({ "path": output }))["doc"].as_u64().unwrap();
let text = page_text(&mut a, doc).join("\n");
for word in words {
assert!(text.contains(word), "{output}: {word:?} not in {text:?}");
}
}
}
/// Office documents combine, in the order given, with a PDF made here, one bookmark each.
#[test]
fn office_documents_combine_in_order_with_a_bookmark_each() {
let Some((dir, mut a)) = office_files() else { return };
let made = ok(
&mut a,
"doc_create_multiple",
json!({ "paths": ["deck.pptx", "letter.docx", "budget.xlsx", "notes.rtf"], "out": "all.pdf", "open": true }),
);
let doc = made["document"]["doc"].as_u64().unwrap();
let pages = page_text(&mut a, doc);
assert_eq!(pages.len(), 4, "{pages:?}");
for (page, word) in pages.iter().zip(["Axolotl deck", "Quokka letter", "Narwhal budget", "Pangolin notes"]) {
assert!(page.contains(word), "{word:?} not in {page:?}");
}
let titles: Vec<String> = ok(&mut a, "bookmark_list", json!({ "doc": doc }))["bookmarks"]
.as_array()
.unwrap()
.iter()
.map(|b| b["title"].as_str().unwrap().to_string())
.collect();
assert_eq!(titles, ["deck", "letter", "budget", "notes"]);
assert!(dir.path().join("all.pdf").is_file());
// doc_combine takes them beside a PDF, with a page range for one of them.
std::fs::write(dir.path().join("cover.txt"), "Cover page").unwrap();
ok(&mut a, "doc_create_multiple", json!({ "paths": ["cover.txt"], "out": "cover.pdf" }));
assert!(dir.path().join("cover.pdf").is_file());
let combined = ok(&mut a, "doc_combine", json!({ "paths": ["cover.pdf", "notes.rtf", "letter.docx"], "pages": [null, "1", null], "open": true }));
let doc = combined["document"]["doc"].as_u64().unwrap();
let pages = page_text(&mut a, doc);
assert_eq!(pages.len(), 3, "{pages:?}");
for (page, word) in pages.iter().zip(["Cover page", "Pangolin notes", "Quokka letter"]) {
assert!(page.contains(word), "{word:?} not in {page:?}");
}
}
+17
View File
@@ -58,6 +58,23 @@ impl Op {
pub fn last_name(&self) -> Option<&[u8]> {
self.operands.last().and_then(Object::as_name)
}
/// Operand `k` counted from the end (0 is the last), as the renderer reads an operator's
/// operands: `(x) /OC /MC0 BDC` marks with `/OC /MC0`, and `(x) /F1 10 Tf` selects `/F1`.
pub fn back(&self, k: usize) -> Option<&Object> {
let i = self.operands.len().checked_sub(k)?.checked_sub(1)?;
self.operands.get(i)
}
/// [`Op::back`] as a name.
pub fn name_back(&self, k: usize) -> Option<&[u8]> {
self.back(k).and_then(Object::as_name)
}
/// [`Op::back`] as a number.
pub fn num_back(&self, k: usize) -> Option<f64> {
self.back(k).and_then(Object::as_f64)
}
}
/// A parsed stream.
+11
View File
@@ -10,6 +10,17 @@ thread_local! {
pub(crate) static PIECE_VISITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
#[test]
fn operands_are_counted_from_the_end() {
let op = parse(b"(x) /OC /MC0 BDC").ops.remove(0);
assert_eq!((op.name_back(1), op.name_back(0)), (Some(&b"OC"[..]), Some(&b"MC0"[..])));
assert_eq!(op.back(2).and_then(Object::as_string).map(|s| s.bytes.clone()), Some(b"x".to_vec()));
assert_eq!((op.back(3), op.back(usize::MAX)), (None, None));
let op = parse(b"/F1 10 Tf").ops.remove(0);
assert_eq!((op.name_back(1), op.num_back(0), op.num_back(1)), (Some(&b"F1"[..]), Some(10.0), None));
assert_eq!(Op::new("Q", vec![]).back(0), None);
}
#[test]
fn splicing_visits_each_piece_a_few_times() {
let n = 5_000;
+5
View File
@@ -24,6 +24,11 @@ thiserror = { workspace = true }
# Already in the graph through lopdf; used only to read plain-text files (decode_text).
encoding_rs = "0.8"
[target.'cfg(unix)'.dependencies]
# Already in the graph (pdfcraft-platform, ui-egui); stops a timed-out LibreOffice's whole process
# group, soffice.bin included, without unsafe code.
rustix = { version = "1", features = ["process"] }
[dev-dependencies]
# An independent CCITT decoder, to check Create PDF's Group 4 images.
hayro-ccitt.workspace = true
+24
View File
@@ -28,6 +28,30 @@ Layer L4. Create a PDF (Acrobat's Create a PDF tool), execution plan M10.2:
Every function returns a `pdfcraft_cos::Document`; the caller writes it.
Office documents (`office.rs`) are the exception: PdfCraft doesn't read Word, Excel, PowerPoint,
OpenDocument or RTF itself. `is_office(name, bytes)` recognises them (an `OFFICE_EXTENSIONS`
name and an OLE, ZIP or RTF signature; `source_kind` reports `SourceKind::Office`), and
`office_to_pdf(name, bytes)` returns PDF bytes made by an installed LibreOffice, run headless as
a separate process: a private temporary folder (owner-only on Unix; the document is always
`document.<ext>` there, never its own name), a fresh profile with macros disabled, untrusted
links blocked and Writer and Calc set never to update linked content (sections, files, external
data) on load, no console window on Windows, and a stop after `TIMEOUT` (120 s) or as soon as the
output grows past 512 MB (the whole process tree is stopped, not only `soffice`). LibreOffice is
found through `PDFCRAFT_SOFFICE`, the `PATH`, then the usual install folders (`libreoffice()`).
A snap-installed LibreOffice is not among those folders: its private `/tmp` cannot see the work
folder. Where `/snap/bin` is on the `PATH` it can still be found there, so point
`PDFCRAFT_SOFFICE` at a non-snap install if conversions fail. It takes seconds, so callers keep it
off the frame thread. On the web it returns an error.
Impress has no setting for linked content, and the profile settings are LibreOffice's own:
PdfCraft doesn't sandbox the process's network access. Converting test documents whose linked
sections, pictures and external cell references point at a local listener made no connection,
with or without the Writer and Calc settings (LibreOffice 26.8.1, Windows, 2026-10-26), so the settings are a
second line of defence rather than a measured fix.
`IMAGE_EXTENSIONS`, `TEXT_EXTENSIONS` and `OFFICE_EXTENSIONS` are what the app's file pickers
offer, so detection and pickers agree.
Image export and Save Image As apply each lossless image's Decode pair before converting its color components.
JBIG2 images and masks are decoded through `pdfcraft_cos::ImageBudget` (`pdfcraft_filters::decode_jbig2_within`), behind
other filters too, with the `/JBIG2Globals` of their own `/DecodeParms` entry, as `JBIG2Decode` gives them: black as 0. An image
+23 -4
View File
@@ -1,4 +1,4 @@
//! pdfcraft-create — create PDFs from nothing, images or text (L4). See the README.
//! pdfcraft-create — create PDFs from nothing, images, text or (through LibreOffice) Office documents (L4). See the README.
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
@@ -8,6 +8,10 @@ mod extract;
mod text_font;
mod upright_image;
pub use extract::{ExtractedImage, ImageExport, extract_images, image_file, image_file_within};
mod office;
#[cfg(not(target_arch = "wasm32"))]
pub use office::libreoffice;
pub use office::{OFFICE_EXTENSIONS, is_office, office_to_pdf};
use pdfcraft_fonts::wrap_with;
use text_font::TextFont;
@@ -17,6 +21,9 @@ pub enum CreateError {
Image(String, String),
#[error("{0}")]
Invalid(String),
/// An Office document LibreOffice couldn't convert, or LibreOffice isn't installed.
#[error("{0}")]
Office(String),
}
/// US Letter in points.
@@ -757,9 +764,18 @@ pub enum SourceKind {
Pdf,
Image,
Text,
/// A Word, Excel, PowerPoint or OpenDocument file, converted through LibreOffice.
Office,
}
/// File extensions Create converts to PDF (images and plain text).
/// File extensions of the images Create converts to PDF.
pub const IMAGE_EXTENSIONS: [&str; 11] = ["png", "jpg", "jpeg", "tif", "tiff", "gif", "bmp", "jp2", "j2k", "jpx", "pcx"];
/// File extensions of the plain-text files Create converts to PDF.
pub const TEXT_EXTENSIONS: [&str; 2] = ["txt", "text"];
/// File extensions Create converts to PDF itself: [`IMAGE_EXTENSIONS`] and [`TEXT_EXTENSIONS`]
/// (Office documents go through LibreOffice, [`OFFICE_EXTENSIONS`]).
pub const CONVERTIBLE: [&str; 13] = ["png", "jpg", "jpeg", "tif", "tiff", "gif", "bmp", "jp2", "j2k", "jpx", "pcx", "txt", "text"];
/// A PCX file: its manufacturer byte, a version (1 was never used), run-length coding and 1 or 8
@@ -792,8 +808,8 @@ fn is_image(bytes: &[u8]) -> bool {
&& bytes.get(14..18).and_then(|h| <[u8; 4]>::try_from(h).ok()).is_some_and(|h| matches!(u32::from_le_bytes(h), 12 | 40 | 52 | 56 | 108 | 124)))
}
/// Whether `bytes` named `name` is a PDF, an image Create can embed, or plain text (a `.txt` or
/// `.text` file). `None` for anything else.
/// Whether `bytes` named `name` is a PDF, an image Create can embed, plain text (a `.txt` or
/// `.text` file) or an Office document ([`is_office`]). `None` for anything else.
pub fn source_kind(name: &str, bytes: &[u8]) -> Option<SourceKind> {
let head = bytes.get(..bytes.len().min(1024)).unwrap_or_default();
if head.windows(5).any(|w| w == b"%PDF-") {
@@ -802,6 +818,9 @@ pub fn source_kind(name: &str, bytes: &[u8]) -> Option<SourceKind> {
if is_image(bytes) {
return Some(SourceKind::Image);
}
if is_office(name, bytes) {
return Some(SourceKind::Office);
}
let lower = name.to_ascii_lowercase();
(lower.ends_with(".txt") || lower.ends_with(".text")).then_some(SourceKind::Text)
}
+599
View File
@@ -0,0 +1,599 @@
//! Office documents (Word, Excel, PowerPoint, OpenDocument, RTF) to PDF through an installed
//! LibreOffice, run as a separate process: the "LibreOffice sidecar" of
//! `docs/file-format-parity.md`. PdfCraft never parses these formats itself.
//!
//! Detection ([`is_office`]) is pure and works everywhere. Conversion ([`office_to_pdf`]) runs
//! only on desktop builds: each run gets its own temporary folder and a fresh LibreOffice
//! profile with macros and untrusted links turned off, and is stopped after [`TIMEOUT`].
use crate::CreateError;
/// File extensions of the Office documents converted through LibreOffice.
pub const OFFICE_EXTENSIONS: &[&str] = &[
// Word and Writer
"doc", "docx", "docm", "dot", "dotx", "dotm", "odt", "ott", "rtf", //
// Excel and Calc
"xls", "xlsx", "xlsm", "xlt", "xltx", "xltm", "ods", "ots", //
// PowerPoint and Impress
"ppt", "pptx", "pptm", "pot", "potx", "potm", "pps", "ppsx", "ppsm", "odp", "otp",
];
/// The OLE compound-file signature of Office 97–2003 files (`.doc`, `.xls`, `.ppt`).
const OLE: &[u8] = &[0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1];
/// The longest a conversion may run before LibreOffice is stopped. A fresh profile costs a
/// few seconds on its own; large spreadsheets take longer.
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
pub const TIMEOUT: std::time::Duration = std::time::Duration::from_secs(120);
/// The largest PDF read back from LibreOffice.
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
const MAX_PDF: u64 = 512 * 1024 * 1024;
/// `name`'s extension as it appears in [`OFFICE_EXTENSIONS`], if it is one.
fn office_extension(name: &str) -> Option<&'static str> {
let (_, ext) = name.rsplit_once('.')?;
OFFICE_EXTENSIONS.iter().copied().find(|e| ext.eq_ignore_ascii_case(e))
}
/// Whether `bytes` named `name` is an Office document: an Office extension, and the bytes start
/// like one (an OLE compound file, a ZIP package as OOXML and OpenDocument are, or RTF).
pub fn is_office(name: &str, bytes: &[u8]) -> bool {
office_extension(name).is_some() && (bytes.starts_with(OLE) || bytes.starts_with(b"PK\x03\x04") || bytes.starts_with(b"{\\rtf"))
}
/// Convert the Office document `bytes` named `name` to PDF bytes with LibreOffice.
#[cfg(target_arch = "wasm32")]
pub fn office_to_pdf(name: &str, _bytes: &[u8]) -> Result<Vec<u8>, CreateError> {
Err(CreateError::Office(format!("{name}: Office documents open only in the desktop app, which converts them with LibreOffice")))
}
/// Convert the Office document `bytes` named `name` to PDF bytes with LibreOffice.
#[cfg(not(target_arch = "wasm32"))]
pub fn office_to_pdf(name: &str, bytes: &[u8]) -> Result<Vec<u8>, CreateError> {
let program = native::libreoffice().ok_or_else(|| {
CreateError::Office(format!(
"{name}: opening Word, Excel and PowerPoint files needs LibreOffice, which isn't installed (get it free from libreoffice.org)"
))
})?;
native::convert_with(&program, name, bytes, TIMEOUT)
}
/// Where LibreOffice is installed, if it is: `PDFCRAFT_SOFFICE`, then the `PATH`, then the
/// usual install folders.
#[cfg(not(target_arch = "wasm32"))]
pub fn libreoffice() -> Option<std::path::PathBuf> {
native::libreoffice()
}
#[cfg(not(target_arch = "wasm32"))]
mod native {
use super::{CreateError, MAX_PDF, office_extension};
use std::ffi::OsString;
use std::path::{Path, PathBuf};
use std::process::{Child, Command, ExitStatus, Stdio};
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Duration, Instant};
/// The program names LibreOffice installs on the `PATH`.
#[cfg(windows)]
const PATH_NAMES: &[&str] = &["soffice.exe"];
#[cfg(not(windows))]
const PATH_NAMES: &[&str] = &["soffice", "libreoffice"];
pub(super) fn libreoffice() -> Option<PathBuf> {
let defaults = default_locations(&|key| std::env::var_os(key));
candidates(std::env::var_os("PDFCRAFT_SOFFICE"), std::env::var_os("PATH"), defaults).into_iter().find(|p| p.is_file())
}
/// Where to look, in order: the override, each `PATH` folder, then `defaults`.
pub(super) fn candidates(override_path: Option<OsString>, path: Option<OsString>, defaults: Vec<PathBuf>) -> Vec<PathBuf> {
let mut out: Vec<PathBuf> = override_path.filter(|p| !p.is_empty()).map(PathBuf::from).into_iter().collect();
if let Some(path) = path {
for dir in std::env::split_paths(&path) {
out.extend(PATH_NAMES.iter().map(|name| dir.join(name)));
}
}
out.extend(defaults);
out
}
/// The usual install locations, given a way to read environment variables.
#[cfg(windows)]
pub(super) fn default_locations(env: &dyn Fn(&str) -> Option<OsString>) -> Vec<PathBuf> {
["ProgramFiles", "ProgramW6432", "ProgramFiles(x86)"]
.iter()
.filter_map(|key| env(key))
.map(|dir| PathBuf::from(dir).join("LibreOffice").join("program").join("soffice.exe"))
.collect()
}
/// The usual install locations, given a way to read environment variables.
#[cfg(target_os = "macos")]
pub(super) fn default_locations(env: &dyn Fn(&str) -> Option<OsString>) -> Vec<PathBuf> {
let app = Path::new("LibreOffice.app/Contents/MacOS/soffice");
let mut out = vec![Path::new("/Applications").join(app)];
out.extend(env("HOME").map(|home| PathBuf::from(home).join("Applications").join(app)));
out
}
/// The usual install locations, given a way to read environment variables.
#[cfg(not(any(windows, target_os = "macos")))]
pub(super) fn default_locations(_env: &dyn Fn(&str) -> Option<OsString>) -> Vec<PathBuf> {
[
"/usr/bin/soffice",
"/usr/bin/libreoffice",
"/usr/local/bin/soffice",
"/usr/local/bin/libreoffice",
"/usr/lib/libreoffice/program/soffice",
"/opt/libreoffice/program/soffice",
]
.iter()
.map(PathBuf::from)
.collect()
}
/// The fresh profile's settings: no macros at all, no links to untrusted locations, and
/// linked content in Writer and Calc documents (sections, files, external data) never
/// updated on load, so a document can't make LibreOffice fetch from the network or a share.
/// The two `Link` settings number "Never" differently (Writer.xcs: 0 Always, 1 On request,
/// 2 Never; Calc.xcs: 0 Always, 1 Never, 2 On request). Impress has no such setting.
pub(super) const PROFILE_SETTINGS: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
<oor:items xmlns:oor="http://openoffice.org/2001/registry" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<item oor:path="/org.openoffice.Office.Common/Security/Scripting"><prop oor:name="DisableMacrosExecution" oor:op="fuse"><value>true</value></prop></item>
<item oor:path="/org.openoffice.Office.Common/Security/Scripting"><prop oor:name="MacroSecurityLevel" oor:op="fuse"><value>3</value></prop></item>
<item oor:path="/org.openoffice.Office.Common/Security/Scripting"><prop oor:name="BlockUntrustedRefererLinks" oor:op="fuse"><value>true</value></prop></item>
<item oor:path="/org.openoffice.Office.Writer/Content/Update"><prop oor:name="Link" oor:op="fuse"><value>2</value></prop></item>
<item oor:path="/org.openoffice.Office.Calc/Content/Update"><prop oor:name="Link" oor:op="fuse"><value>1</value></prop></item>
</oor:items>
"#;
/// A private temporary folder, removed (with everything in it) when dropped.
pub(super) struct WorkDir(pub(super) PathBuf);
impl WorkDir {
pub(super) fn new() -> std::io::Result<Self> {
static NEXT: AtomicU64 = AtomicU64::new(0);
let n = NEXT.fetch_add(1, Ordering::Relaxed);
let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.subsec_nanos());
let dir = std::env::temp_dir().join(format!("pdfcraft-office-{}-{n}-{nanos}", std::process::id()));
// Not recursive: a folder that already exists is not ours. Owner-only on Unix, where the
// temporary folder is shared: the document and its PDF are not for other users.
#[cfg_attr(not(unix), allow(unused_mut))]
let mut builder = std::fs::DirBuilder::new();
#[cfg(unix)]
{
use std::os::unix::fs::DirBuilderExt;
builder.mode(0o700);
}
builder.create(&dir)?;
Ok(Self(dir))
}
}
impl Drop for WorkDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
/// `path` as a `file://` URL, which `-env:UserInstallation` takes.
pub(super) fn file_url(path: &Path) -> String {
let path = path.to_string_lossy().replace('\\', "/");
let mut url = String::from("file://");
// A Windows path (`C:/…`) needs the third slash a Unix path already starts with.
if !path.starts_with('/') {
url.push('/');
}
for b in path.bytes() {
if b.is_ascii_alphanumeric() || b"-._~/:".contains(&b) {
url.push(char::from(b));
} else {
url.push_str(&format!("%{b:02X}"));
}
}
url
}
pub(super) enum Run {
Exited(ExitStatus),
TimedOut,
/// The watched folder grew past its limit while the command ran.
TooLarge,
}
/// The bytes in the files directly inside `dir` (LibreOffice writes its one output there).
/// Anything unreadable counts as nothing, and the sum saturates. Each size is read from the
/// file itself: on Windows a directory listing keeps the old size while a process still
/// has the file open for writing.
pub(super) fn folder_size(dir: &Path) -> u64 {
let Ok(entries) = std::fs::read_dir(dir) else { return 0 };
entries
.flatten()
.filter_map(|entry| std::fs::symlink_metadata(entry.path()).ok())
.filter(|meta| meta.is_file())
.fold(0u64, |sum, meta| sum.saturating_add(meta.len()))
}
/// Run `command` to completion, killing it and every process it started once `timeout`
/// passes, or once the files in `watch`'s folder add up to more than its limit (so a
/// document that converts to an enormous PDF can't fill the disk before it is checked).
/// `soffice` hands the conversion to its own child, `soffice.bin`, which would
/// otherwise outlive the kill, holding the profile folder and its memory.
pub(super) fn run_limited(mut command: Command, timeout: Duration, watch: Option<(&Path, u64)>) -> std::io::Result<Run> {
#[cfg(unix)]
{
use std::os::unix::process::CommandExt;
// Its own process group, so the whole group can be stopped together.
command.process_group(0);
}
let mut child = command.spawn()?;
let start = Instant::now();
loop {
match child.try_wait() {
Ok(Some(status)) => return Ok(Run::Exited(status)),
Ok(None) => {}
Err(error) => {
kill_tree(&mut child);
return Err(error);
}
}
if watch.is_some_and(|(dir, limit)| folder_size(dir) > limit) {
kill_tree(&mut child);
return Ok(Run::TooLarge);
}
if start.elapsed() >= timeout {
kill_tree(&mut child);
return Ok(Run::TimedOut);
}
std::thread::sleep(Duration::from_millis(50));
}
}
/// Kill `child` and every process it started, then reap it.
fn kill_tree(child: &mut Child) {
#[cfg(unix)]
{
use rustix::process::{Pid, Signal, kill_process_group};
// The group `process_group(0)` made has the child's id.
if let Some(group) = i32::try_from(child.id()).ok().and_then(Pid::from_raw) {
let _ = kill_process_group(group, Signal::KILL);
}
}
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
// `/T` walks the tree from the child's id, so it runs while the child is still alive.
// Windows' own copy, not whatever `taskkill` the PATH finds first.
let taskkill = std::env::var_os("SystemRoot")
.map_or_else(|| PathBuf::from("taskkill.exe"), |root| PathBuf::from(root).join("System32").join("taskkill.exe"));
let _ = Command::new(taskkill)
.args(["/T", "/F", "/PID", &child.id().to_string()])
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
// CREATE_NO_WINDOW, as for LibreOffice itself.
.creation_flags(0x0800_0000)
.status();
}
// The child itself, if the tree kill couldn't reach it.
let _ = child.kill();
let _ = child.wait();
}
/// Convert with the LibreOffice at `program`, giving up after `timeout`.
pub(super) fn convert_with(program: &Path, name: &str, bytes: &[u8], timeout: Duration) -> Result<Vec<u8>, CreateError> {
convert_capped(program, name, bytes, timeout, MAX_PDF)
}
/// [`convert_with`] with the converted PDF's size limit given: the output folder is watched
/// while LibreOffice runs, and the finished file is checked again.
pub(super) fn convert_capped(program: &Path, name: &str, bytes: &[u8], timeout: Duration, max_pdf: u64) -> Result<Vec<u8>, CreateError> {
let too_large = || format!("the converted PDF is larger than {} MB", max_pdf / (1024 * 1024));
let failed = |why: String| CreateError::Office(format!("{name}: {why}"));
let ext = office_extension(name).ok_or_else(|| failed("this isn't a Word, Excel or PowerPoint file".into()))?;
let work = WorkDir::new().map_err(|e| failed(format!("couldn't make a temporary folder: {e}")))?;
// A fixed input name: the document's own name never reaches LibreOffice's command line.
let input = work.0.join(format!("document.{ext}"));
let profile = work.0.join("profile");
let out = work.0.join("out");
let prepared = std::fs::write(&input, bytes)
.and_then(|()| std::fs::create_dir_all(profile.join("user")))
.and_then(|()| std::fs::write(profile.join("user").join("registrymodifications.xcu"), PROFILE_SETTINGS))
.and_then(|()| std::fs::create_dir(&out));
prepared.map_err(|e| failed(format!("couldn't prepare the conversion: {e}")))?;
let mut command = Command::new(program);
command
.arg(format!("-env:UserInstallation={}", file_url(&profile)))
.args(["--headless", "--invisible", "--nologo", "--norestore", "--nodefault", "--nolockcheck", "--convert-to", "pdf", "--outdir"])
.arg(&out)
.arg(&input)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null());
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
// CREATE_NO_WINDOW: no console window flashes up during the conversion.
command.creation_flags(0x0800_0000);
}
let status = match run_limited(command, timeout, Some((&out, max_pdf))) {
Ok(Run::Exited(status)) => status,
Ok(Run::TooLarge) => return Err(failed(format!("{}; LibreOffice was stopped", too_large()))),
Ok(Run::TimedOut) => return Err(failed(format!("LibreOffice took longer than {} seconds and was stopped", timeout.as_secs()))),
Err(e) => return Err(failed(format!("couldn't start LibreOffice ({}): {e}", program.display()))),
};
let pdf = out.join("document.pdf");
let size = match std::fs::metadata(&pdf) {
Ok(meta) => meta.len(),
Err(_) if !status.success() => return Err(failed(format!("LibreOffice couldn't convert it ({status})"))),
Err(_) => return Err(failed("LibreOffice didn't produce a PDF; the file may be damaged or password-protected".into())),
};
if size > max_pdf {
return Err(failed(too_large()));
}
let bytes = std::fs::read(&pdf).map_err(|e| failed(format!("couldn't read the converted PDF: {e}")))?;
if !bytes.starts_with(b"%PDF-") {
return Err(failed("LibreOffice's output isn't a PDF".into()));
}
Ok(bytes)
}
}
#[cfg(test)]
mod tests {
use super::*;
const DOCX_HEAD: &[u8] = b"PK\x03\x04\x14\x00\x06\x00";
#[test]
fn office_files_are_recognised_by_extension_and_signature() {
assert!(is_office("Report.docx", DOCX_HEAD));
assert!(is_office("SHEET.XLSX", DOCX_HEAD));
assert!(is_office("deck.odp", DOCX_HEAD));
assert!(is_office("old.doc", OLE));
assert!(is_office("old.ppt", &[OLE, b"rest"].concat()));
assert!(is_office("letter.rtf", b"{\\rtf1\\ansi"));
// Word saves RTF under .doc too.
assert!(is_office("letter.doc", b"{\\rtf1\\ansi"));
}
#[test]
fn other_files_are_not_office_documents() {
// The right signature with another extension, or an Office name with other bytes.
assert!(!is_office("archive.zip", DOCX_HEAD));
assert!(!is_office("Report.docx", b"%PDF-1.7"));
assert!(!is_office("Report.docx", b"plain text"));
assert!(!is_office("Report.docx", b""));
assert!(!is_office("docx", DOCX_HEAD));
assert!(!is_office("", DOCX_HEAD));
// A multi-byte name never splits a character.
assert!(!is_office("résumé.dócx", DOCX_HEAD));
assert!(is_office("résumé.docx", DOCX_HEAD));
}
#[cfg(not(target_arch = "wasm32"))]
mod native {
use super::super::native::*;
use super::DOCX_HEAD;
use std::ffi::OsString;
use std::path::{Path, PathBuf};
use std::time::Duration;
#[test]
fn file_urls_escape_spaces_and_keep_drive_letters() {
assert_eq!(file_url(Path::new("/tmp/a b/profile")), "file:///tmp/a%20b/profile");
assert_eq!(file_url(Path::new(r"C:\Users\Jo Ann\profile")), "file:///C:/Users/Jo%20Ann/profile");
assert_eq!(file_url(Path::new("/tmp/é")), "file:///tmp/%C3%A9");
}
#[test]
fn the_override_comes_first_then_the_path_then_the_defaults() {
let path = std::env::join_paths([Path::new("first"), Path::new("second")]).unwrap();
let found = candidates(Some(OsString::from("custom/soffice")), Some(path), vec![PathBuf::from("default/soffice")]);
assert_eq!(found.first(), Some(&PathBuf::from("custom/soffice")));
assert!(found.get(1).is_some_and(|p| p.starts_with("first")));
assert_eq!(found.last(), Some(&PathBuf::from("default/soffice")));
// An empty override is no override.
assert_eq!(candidates(Some(OsString::new()), None, Vec::new()), Vec::<PathBuf>::new());
}
#[test]
fn default_locations_read_only_the_given_environment() {
let found = default_locations(&|_| None);
assert!(found.iter().all(|p| p.is_absolute()), "{found:?}");
}
/// Each setting the fresh profile makes, as (path, property, value).
fn profile_settings() -> Vec<(&'static str, &'static str, &'static str)> {
let between = |s: &'static str, start: &str, end: &str| s.split_once(start).and_then(|(_, rest)| rest.split_once(end)).map(|(v, _)| v);
PROFILE_SETTINGS
.split("<item ")
.skip(1)
.filter_map(|item| {
Some((between(item, "oor:path=\"", "\"")?, between(item, "oor:name=\"", "\"")?, between(item, "<value>", "</value>")?))
})
.collect()
}
#[test]
fn the_profile_turns_off_macros_and_never_updates_links() {
let settings = profile_settings();
let scripting = "/org.openoffice.Office.Common/Security/Scripting";
assert!(settings.contains(&(scripting, "DisableMacrosExecution", "true")), "{settings:?}");
assert!(settings.contains(&(scripting, "MacroSecurityLevel", "3")), "{settings:?}");
assert!(settings.contains(&(scripting, "BlockUntrustedRefererLinks", "true")), "{settings:?}");
// "Never" is 2 for Writer but 1 for Calc (Writer.xcs and Calc.xcs); Writer's 1 is
// its default, "On request".
assert!(settings.contains(&("/org.openoffice.Office.Writer/Content/Update", "Link", "2")), "{settings:?}");
assert!(settings.contains(&("/org.openoffice.Office.Calc/Content/Update", "Link", "1")), "{settings:?}");
assert_eq!(settings.len(), 5, "{settings:?}");
}
#[test]
fn a_missing_converter_is_an_error_not_a_crash() {
let missing = std::env::temp_dir().join("pdfcraft-no-such-soffice").join("soffice");
let error = convert_with(&missing, "Report.docx", DOCX_HEAD, Duration::from_secs(5)).unwrap_err();
assert!(error.to_string().contains("couldn't start LibreOffice"), "{error}");
}
#[test]
fn a_converter_that_makes_no_pdf_is_reported() {
// This test binary stands in for LibreOffice: it rejects the arguments and exits
// without writing anything.
let program = std::env::current_exe().unwrap();
let error = convert_with(&program, "Report.docx", DOCX_HEAD, Duration::from_secs(60)).unwrap_err();
assert!(error.to_string().contains("LibreOffice"), "{error}");
}
#[test]
fn a_converter_that_hangs_is_stopped() {
let mut command = std::process::Command::new(std::env::current_exe().unwrap());
command.args(["--ignored", "--exact", "office::tests::native::sleeps_for_a_minute", "--nocapture"]);
command.stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null());
let started = std::time::Instant::now();
assert!(matches!(run_limited(command, Duration::from_millis(500), None), Ok(Run::TimedOut)));
assert!(started.elapsed() < Duration::from_secs(30));
}
/// The stand-in for a LibreOffice that never finishes (run only by the test above).
#[test]
#[ignore]
fn sleeps_for_a_minute() {
std::thread::sleep(Duration::from_secs(60));
}
/// Where the stand-ins below write their heartbeat.
const HEARTBEAT: &str = "PDFCRAFT_TEST_OFFICE_HEARTBEAT";
/// This test binary run as one of its own ignored tests, with the heartbeat file set.
fn stand_in(test: &str, heartbeat: &Path) -> std::process::Command {
let mut command = std::process::Command::new(std::env::current_exe().unwrap());
command.args(["--ignored", "--exact", test, "--nocapture"]).env(HEARTBEAT, heartbeat);
command.stdin(std::process::Stdio::null()).stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null());
command
}
/// `soffice` starts `soffice.bin` as its own child: a timeout must stop both, or the
/// child keeps running, holding the profile folder.
#[test]
fn a_timeout_stops_the_processes_the_converter_started() {
let work = WorkDir::new().unwrap();
let heartbeat = work.0.join("heartbeat");
let parent = stand_in("office::tests::native::starts_a_child_that_keeps_beating", &heartbeat);
assert!(matches!(run_limited(parent, Duration::from_secs(5), None), Ok(Run::TimedOut)));
let beats = || std::fs::metadata(&heartbeat).map_or(0, |m| m.len());
// A killed process may take a moment to go.
std::thread::sleep(Duration::from_millis(300));
let after_kill = beats();
assert!(after_kill > 0, "the grandchild started and was beating before the timeout");
std::thread::sleep(Duration::from_secs(1));
assert_eq!(beats(), after_kill, "the grandchild was stopped with its parent");
}
/// The stand-in for `soffice`: starts [`beats_until_stopped`] and waits (run only by the
/// test above).
#[test]
#[ignore]
fn starts_a_child_that_keeps_beating() {
let Some(heartbeat) = std::env::var_os(HEARTBEAT) else { return };
let mut child = stand_in("office::tests::native::beats_until_stopped", Path::new(&heartbeat)).spawn().unwrap();
std::thread::sleep(Duration::from_secs(60));
let _ = child.kill();
let _ = child.wait();
}
/// The stand-in for `soffice.bin`: appends to the heartbeat file every 50 ms for a minute.
#[test]
#[ignore]
fn beats_until_stopped() {
use std::io::Write;
let Some(heartbeat) = std::env::var_os(HEARTBEAT) else { return };
let mut file = std::fs::OpenOptions::new().create(true).append(true).open(heartbeat).unwrap();
for _ in 0..1200 {
file.write_all(b".").unwrap();
std::thread::sleep(Duration::from_millis(50));
}
}
/// Where the stand-in below writes.
const FILL_DIR: &str = "PDFCRAFT_TEST_OFFICE_FILL_DIR";
/// A converter that writes without end is stopped as soon as its output passes the
/// limit, not after it has run out its time.
#[test]
fn a_converter_whose_output_grows_past_the_limit_is_stopped() {
let work = WorkDir::new().unwrap();
let mut command = std::process::Command::new(std::env::current_exe().unwrap());
command.args(["--ignored", "--exact", "office::tests::native::writes_without_end", "--nocapture"]).env(FILL_DIR, &work.0);
command.stdin(std::process::Stdio::null()).stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null());
let limit = 256 * 1024;
let started = std::time::Instant::now();
let run = run_limited(command, Duration::from_secs(60), Some((&work.0, limit)));
assert!(matches!(run, Ok(Run::TooLarge)), "stopped for size, not for time");
assert!(started.elapsed() < Duration::from_secs(30), "stopped long before the timeout");
// A killed process may take a moment to go; after that nothing is written.
std::thread::sleep(Duration::from_millis(300));
let after_kill = folder_size(&work.0);
assert!(after_kill > limit, "the stand-in had written past the limit");
std::thread::sleep(Duration::from_secs(1));
assert_eq!(folder_size(&work.0), after_kill, "the converter was stopped");
}
/// The stand-in for a LibreOffice that fills the disk: 64 KiB every 10 ms for a minute
/// (run only by the test above).
#[test]
#[ignore]
fn writes_without_end() {
use std::io::Write;
let Some(dir) = std::env::var_os(FILL_DIR) else { return };
let mut file = std::fs::File::create(Path::new(&dir).join("document.pdf")).unwrap();
let chunk = vec![0u8; 64 * 1024];
for _ in 0..6000 {
file.write_all(&chunk).unwrap();
std::thread::sleep(Duration::from_millis(10));
}
}
#[test]
fn a_folder_that_cannot_be_read_counts_as_empty() {
assert_eq!(folder_size(&std::env::temp_dir().join("pdfcraft-no-such-folder")), 0);
}
/// The temporary folder holds a confidential document and its PDF: on Unix only the owner
/// may enter it.
#[cfg(unix)]
#[test]
fn the_temporary_folder_is_private_to_its_owner() {
use std::os::unix::fs::PermissionsExt;
let work = WorkDir::new().unwrap();
let mode = std::fs::metadata(&work.0).unwrap().permissions().mode();
assert_eq!(mode & 0o777, 0o700, "{mode:o}");
}
#[test]
fn temporary_folders_are_removed_with_their_contents() {
let work = WorkDir::new().unwrap();
let other = WorkDir::new().unwrap();
assert_ne!(work.0, other.0);
let dir = work.0.clone();
std::fs::create_dir_all(dir.join("profile").join("user")).unwrap();
std::fs::write(dir.join("document.docx"), DOCX_HEAD).unwrap();
drop(work);
assert!(!dir.exists());
}
/// A real conversion, when LibreOffice is installed (skipped otherwise).
#[test]
fn libreoffice_converts_a_document_when_installed() {
let Some(program) = super::super::libreoffice() else {
eprintln!("skipped: LibreOffice isn't installed");
return;
};
let rtf = b"{\\rtf1\\ansi{\\fonttbl\\f0\\fswiss Helvetica;}\\f0\\pard Hello from PdfCraft.\\par}";
let pdf = convert_with(&program, "hello.rtf", rtf, super::super::TIMEOUT).unwrap();
assert!(pdf.starts_with(b"%PDF-"));
}
}
}
+17 -1
View File
@@ -559,7 +559,7 @@ fn source_kind_tells_pdfs_images_and_text_apart() {
// Text that merely starts like a BMP stays text; a truncated BMP header is not an image.
assert_eq!(source_kind("b.txt", b"BMW drivers"), Some(SourceKind::Text));
assert_eq!(source_kind("b.bmp", b"BM"), None);
assert_eq!(source_kind("a.docx", b"PK\x03\x04"), None);
assert_eq!(source_kind("a.docx", b"PK\x03\x04"), Some(SourceKind::Office), "Office documents convert through LibreOffice");
assert_eq!(source_kind("", b""), None);
// Only the GIF versions Create decodes count as images, so detection never promises a
// conversion that then fails.
@@ -2952,3 +2952,19 @@ fn stripping_extended_xmp_leaves_the_rest_of_the_jpeg() {
// 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());
}
#[test]
fn convertible_is_the_image_and_text_extensions() {
let both: Vec<&str> = IMAGE_EXTENSIONS.iter().chain(TEXT_EXTENSIONS.iter()).copied().collect();
assert_eq!(both, CONVERTIBLE.to_vec());
assert!(OFFICE_EXTENSIONS.iter().all(|e| !CONVERTIBLE.contains(e) && *e != "pdf"));
}
#[test]
fn office_documents_are_their_own_kind() {
assert_eq!(source_kind("Report.docx", b"PK\x03\x04\x14\x00"), Some(SourceKind::Office));
assert_eq!(source_kind("Budget.xls", &[0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1]), Some(SourceKind::Office));
// A PDF saved with a Word name is still a PDF; a ZIP that isn't named like Office is nothing.
assert_eq!(source_kind("Report.docx", b"%PDF-1.7\n"), Some(SourceKind::Pdf));
assert_eq!(source_kind("photos.zip", b"PK\x03\x04\x14\x00"), None);
}
+32
View File
@@ -14850,6 +14850,38 @@ fn a_thai_edit_that_spends_its_allowance_to_the_byte_goes_through() {
assert!(error.contains("THSarabunPSK") && error.contains("MiB of font data"), "{error}");
}
/// Only a read the allowance refuses leaves a font of the face unread for want of it. With the
/// allowance spent to the byte as above, another font of the face, whose ToUnicode is an empty
/// stream behind a filter nothing decodes (unread with any allowance), still has its program read,
/// which the allowance refuses: the edit is refused, rather than going through without that font.
#[test]
fn a_font_of_the_face_unread_on_its_own_once_the_allowance_is_spent_still_refuses_the_edit() {
let mut program = legacy_thai_program();
program.resize((16 << 20) - 192, 0);
let mut unicode = LEGACY_THAI_UNICODE.to_vec();
unicode.resize(256, b' ');
let mut doc = text_page("BT /F1 16 Tf 50 650 Td <00d6> Tj ET");
let font = legacy_thai_font(&mut doc, "ABCDEF+THSarabunPSK", &program, &unicode);
doc.set(pdfcraft_cos::ObjRef::new(5, 0), Object::Dict(font));
// Not a subset, so its metrics read no program, only the ToUnicode.
let mut other = legacy_thai_font(&mut doc, "THSarabunPSK", &legacy_thai_program(), LEGACY_THAI_UNICODE);
let mut dict = Dict::new();
dict.set(b"Filter".to_vec(), Object::name("NoSuchFilter"));
other.set(b"ToUnicode".to_vec(), Object::Ref(doc.add(Object::Stream(Stream::from_raw(dict, Vec::new())))));
let other = doc.add(Object::Dict(other));
doc.update_dict(pdfcraft_cos::ObjRef::new(3, 0), |page| {
let Some(Object::Dict(mut resources)) = page.get(b"Resources").cloned() else { panic!("fixture") };
let Some(Object::Dict(mut fonts)) = resources.get(b"Font").cloned() else { panic!("fixture") };
fonts.set(b"F2".to_vec(), Object::Ref(other));
resources.set(b"Font".to_vec(), Object::Dict(fonts));
page.set(b"Resources".to_vec(), Object::Dict(resources));
})
.unwrap();
let style = BlockStyle { width: Some(400.0), ..Default::default() };
let error = text::rewrite_block(&mut doc, 0, 0, Some("กขค"), &style).unwrap_err().to_string();
assert!(error.contains("THSarabunPSK") && error.contains("MiB of font data"), "{error}");
}
/// A THSarabunPSK-named subset that has OpenType Thai mark positioning is a modern face: it is
/// shaped with its own layout like any source font, not by the legacy shaper (which would ask
/// for Windows PUA alternates such a face doesn't need).
+2 -2
View File
@@ -2,7 +2,7 @@ use super::blocks::{BlockStyle, TextBlock};
use super::fallback::MAX_TYPE3_GLYPHS;
use super::lines::{page_dict, text_lines};
use super::rewrite::rewrite_block_from;
use super::{DecodeBudget, Dict, Document, EditError, Metrics, Object, TextLine, TextSession};
use super::{DecodeBudget, Dict, Document, EditError, Object, TextLine, TextSession};
/// An embedded source font or an approved bundled document-font choice.
/// Source bytes stay in memory and are never installed or copied into another document.
@@ -45,7 +45,7 @@ pub fn text_editor_fonts(doc: &Document, page: usize) -> Result<Vec<TextEditorFo
budget -= bytes.len();
result.push(TextEditorFont {
resource: String::from_utf8_lossy(name).into_owned(),
face: Metrics::from_dict(doc, &font).base_font.rsplit('+').next().unwrap_or_default().to_owned(),
face: pdfcraft_fonts::pdf::base_font_name(doc, &font).rsplit('+').next().unwrap_or_default().to_owned(),
bytes,
choice_only: false,
});
+379
View File
@@ -0,0 +1,379 @@
//! Catalog JavaScript actions (#269, ported from #344): the `/OpenAction` runs once on opening
//! and again on Revert, `/AA /WS` before a save and `/AA /WP` before printing, all in the
//! document's retained realm.
use std::sync::Arc;
use crate::js::DocumentScriptEvent;
use crate::{DocId, Session};
/// A PDF of `objs`, numbered from 1, with a cross-reference table.
fn pdf_of(objs: &[String]) -> Vec<u8> {
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 o in offsets {
out.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());
}
out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes());
out
}
/// A one-field form (`log`, a text field) whose catalog carries `catalog` (PDF syntax, e.g.
/// `/OpenAction 6 0 R`), with `extra` objects numbered from 6.
fn form(catalog: &str, extra: &[&str]) -> Vec<u8> {
let mut objs = vec![
format!("<< /Type /Catalog /Pages 2 0 R {catalog} /AcroForm << /Fields [4 0 R] /DA (/Helv 0 Tf 0 g) /DR << /Font << /Helv 5 0 R >> >> >> >>"),
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 200 300] >>".into(),
"<< /Type /Page /Parent 2 0 R /Annots [4 0 R] >>".into(),
"<< /Type /Annot /Subtype /Widget /FT /Tx /T (log) /V () /Rect [20 250 180 270] /P 3 0 R /F 4 >>".into(),
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".into(),
];
objs.extend(extra.iter().map(|s| s.to_string()));
pdf_of(&objs)
}
fn log(s: &Session, id: DocId) -> String {
s.get(id).unwrap().form.iter().find(|f| f.name == "log").unwrap().value.join(",")
}
/// The open action runs once on opening, after the document scripts and in their realm, and
/// sees `event.name` "Open"; its field change is applied.
#[test]
fn the_open_action_runs_once_on_opening_in_the_document_realm() {
let bytes = form(
"/OpenAction 6 0 R /Names << /JavaScript << /Names [(init) 7 0 R] >> >>",
&[
"<< /S /JavaScript /JS (opened++; getField\\('log'\\).value = event.type + '/' + event.name + '/' + opened;) >>",
"<< /S /JavaScript /JS (var opened = 0;) >>",
],
);
let mut s = Session::new();
let id = s.open("open.pdf", None, Arc::new(bytes), None).unwrap();
assert_eq!(log(&s, id), "Doc/Open/1");
assert!(s.take_js_output(id).errors.is_empty());
// The realm is kept: a later script sees the count the open action left.
assert_eq!(s.run_javascript(id, "opened;", None).unwrap().result.as_deref(), Some("1"));
}
/// An open action chain runs in order through `/Next` (a dictionary or an array), skipping
/// actions of other types, and a cycle in it runs each action once.
#[test]
fn an_open_action_chain_runs_in_order_and_a_cycle_runs_each_action_once() {
let bytes = form(
"/OpenAction 6 0 R",
&[
"<< /S /JavaScript /JS (var seen = ['a'];) /Next [7 0 R 8 0 R] >>",
"<< /S /GoTo /D [3 0 R /Fit] /Next 9 0 R >>",
"<< /S /JavaScript /JS (seen.push\\('c'\\); getField\\('log'\\).value = seen.join\\(''\\);) /Next 6 0 R >>",
"<< /S /JavaScript /JS (seen.push\\('b'\\);) /Next 7 0 R >>",
],
);
let mut s = Session::new();
let id = s.open("chain.pdf", None, Arc::new(bytes), None).unwrap();
assert_eq!(log(&s, id), "abc");
}
/// What an open action asks for that needs a click (a URL, printing) is dropped; a page
/// change it asks for is kept.
#[test]
fn an_open_action_may_not_open_a_url_or_print() {
let bytes = form("/OpenAction << /S /JavaScript /JS (app.launchURL\\('https://example.com'\\); this.print\\(\\); this.pageNum = 0;) >>", &[]);
let mut s = Session::new();
let id = s.open("asks.pdf", None, Arc::new(bytes), None).unwrap();
let out = s.take_js_output(id);
assert_eq!(out.requests, [crate::js::Request::GoToPage(0)], "{out:?}");
}
/// With JavaScript off the open action doesn't run.
#[test]
fn the_open_action_does_not_run_with_javascript_off() {
let bytes = form("/OpenAction << /S /JavaScript /JS (getField\\('log'\\).value = 'ran';) >>", &[]);
let mut s = Session::new();
s.set_javascript(false);
let id = s.open("off.pdf", None, Arc::new(bytes), None).unwrap();
assert_eq!(log(&s, id), "");
assert!(s.run_document_actions(id, DocumentScriptEvent::CatalogOpen).is_empty());
}
/// Revert reopens the saved file in a fresh realm, so the open action runs again from scratch.
#[test]
fn revert_runs_the_open_action_again_in_a_fresh_realm() {
let bytes = form(
"/OpenAction << /S /JavaScript /JS (if \\(typeof runs == 'undefined'\\) var runs = 0; runs++; getField\\('log'\\).value = 'run ' + runs;) >>",
&[],
);
let mut s = Session::new();
let id = s.open("revert.pdf", None, Arc::new(bytes), None).unwrap();
assert_eq!(log(&s, id), "run 1");
s.run_javascript(id, "getField('log').value = 'typed';", None).unwrap();
s.revert(id).unwrap();
assert_eq!(log(&s, id), "run 1", "a fresh realm counts from zero again");
}
/// Will Save runs in the document realm before the bytes are written, and what it changes is in
/// the saved file; a failing Will Save is reported and the save still has bytes to write.
#[test]
fn will_save_changes_what_is_saved_and_a_failing_one_does_not_stop_the_save() {
let bytes = form(
"/Names << /JavaScript << /Names [(init) 6 0 R] >> >> /AA << /WS << /S /JavaScript /JS (saves++; getField\\('log'\\).value = event.name + ' ' + saves;) >> >>",
&["<< /S /JavaScript /JS (var saves = 0;) >>"],
);
let mut s = Session::new();
let id = s.open("save.pdf", None, Arc::new(bytes), None).unwrap();
let out = s.run_document_actions(id, DocumentScriptEvent::WillSave);
assert!(out.errors.is_empty(), "{out:?}");
assert_eq!(log(&s, id), "WillSave 1");
let saved = s.save_bytes(id).unwrap();
let mut reopened = Session::new();
reopened.set_javascript(false);
let again = reopened.open("saved.pdf", None, saved, None).unwrap();
assert_eq!(log(&reopened, again), "WillSave 1");
let failing = form("/AA << /WS << /S /JavaScript /JS (throw new Error\\('no'\\);) >> >>", &[]);
let id = s.open("fail.pdf", None, Arc::new(failing), None).unwrap();
let out = s.run_document_actions(id, DocumentScriptEvent::WillSave);
assert!(out.errors.iter().any(|e| e.contains("no")), "{out:?}");
assert!(s.save_bytes(id).is_ok());
}
/// Will Print runs before printing, in the same realm, and sees `event.name` "WillPrint".
#[test]
fn will_print_runs_in_the_document_realm() {
let bytes = form("/AA << /WP << /S /JavaScript /JS (getField\\('log'\\).value = event.name;) >> >>", &[]);
let mut s = Session::new();
let id = s.open("print.pdf", None, Arc::new(bytes), None).unwrap();
assert!(s.run_document_actions(id, DocumentScriptEvent::WillSave).is_empty(), "no Will Save action: nothing runs");
assert_eq!(log(&s, id), "");
s.run_document_actions(id, DocumentScriptEvent::WillPrint);
assert_eq!(log(&s, id), "WillPrint");
}
/// A form with a text field `log` and a text field `hot` whose widget has JavaScript for every
/// pointer and focus trigger, each appending `event.name` to `log`.
fn triggers_form() -> Vec<u8> {
let add =
|| "<< /S /JavaScript /JS (var l = getField\\('log'\\); l.value = l.value + event.name + ':' + event.target.name + ';';) >>".to_string();
let objs = vec![
"<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [4 0 R 6 0 R] /DA (/Helv 0 Tf 0 g) /DR << /Font << /Helv 5 0 R >> >> >> >>".to_string(),
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 200 300] >>".into(),
"<< /Type /Page /Parent 2 0 R /Annots [4 0 R 6 0 R] >>".into(),
"<< /Type /Annot /Subtype /Widget /FT /Tx /T (log) /V () /Rect [20 250 180 270] /P 3 0 R /F 4 >>".into(),
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".into(),
format!(
"<< /Type /Annot /Subtype /Widget /FT /Tx /T (hot) /V () /Rect [20 200 180 220] /P 3 0 R /F 4 /AA << /E {} /X {} /D {} /U {} /Fo {} /Bl {} >> >>",
add(),
add(),
"<< /S /JavaScript /JS (getField\\('log'\\).value += 'D;'; this.print\\(\\);) >>",
add(),
add(),
"<< /S /JavaScript /JS (getField\\('log'\\).value += 'Bl;'; this.print\\(\\);) >>",
),
];
pdf_of(&objs)
}
/// Pointer and focus triggers run the widget's JavaScript with the event names Acrobat uses,
/// each as one undoable edit; a field without such a script runs nothing.
#[test]
fn pointer_and_focus_triggers_run_the_widget_scripts() {
use crate::js::FieldFocus;
use pdfcraft_forms::Trigger;
let mut s = Session::new();
let id = s.open("hot.pdf", None, Arc::new(triggers_form()), None).unwrap();
assert!(s.field_trigger(id, "hot", 0, Trigger::MouseEnter).unwrap());
assert!(s.field_focus(id, "hot", 0, FieldFocus::Enter).unwrap());
assert!(s.field_trigger(id, "hot", 0, Trigger::MouseUp).unwrap());
assert!(s.field_trigger(id, "hot", 0, Trigger::MouseExit).unwrap());
assert_eq!(log(&s, id), "Mouse Enter:hot;Focus:hot;Mouse Up:hot;Mouse Exit:hot;");
assert_eq!(s.get(id).unwrap().can_undo(), Some("Run JavaScript"));
assert!(!s.field_trigger(id, "log", 0, Trigger::MouseEnter).unwrap(), "no script: nothing runs");
assert!(!s.field_trigger(id, "hot", 5, Trigger::MouseEnter).unwrap(), "no such widget: nothing runs");
assert!(s.field_trigger(id, "missing", 0, Trigger::MouseEnter).is_err());
s.set_javascript(false);
assert!(!s.field_trigger(id, "hot", 0, Trigger::MouseEnter).unwrap(), "JavaScript off");
}
/// A click's Mouse Down may ask to print; losing the focus, which happens unasked, may not.
#[test]
fn only_a_click_trigger_may_print() {
use crate::js::{FieldFocus, Request};
use pdfcraft_forms::Trigger;
let mut s = Session::new();
let id = s.open("hot.pdf", None, Arc::new(triggers_form()), None).unwrap();
s.field_trigger(id, "hot", 0, Trigger::MouseDown).unwrap();
assert_eq!(s.take_js_output(id).requests, [Request::Print]);
s.field_focus(id, "hot", 0, FieldFocus::Exit).unwrap();
let out = s.take_js_output(id);
assert!(out.requests.is_empty(), "{out:?}");
assert_eq!(log(&s, id), "D;Bl;");
}
/// `setItems` and `setAction` are written to the document: the combo box gets its new items
/// (pairs where text and export value differ), the installed scripts run on their triggers, and
/// both survive a save (#269, from #344).
#[test]
fn set_items_and_set_action_are_written_to_the_document() {
use pdfcraft_forms::Trigger;
let objs = vec![
"<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [4 0 R 6 0 R] /DA (/Helv 0 Tf 0 g) /DR << /Font << /Helv 5 0 R >> >> >> >>".to_string(),
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 200 300] >>".into(),
"<< /Type /Page /Parent 2 0 R /Annots [4 0 R 6 0 R] >>".into(),
"<< /Type /Annot /Subtype /Widget /FT /Tx /T (log) /V () /Rect [20 250 180 270] /P 3 0 R /F 4 >>".into(),
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".into(),
"<< /Type /Annot /Subtype /Widget /FT /Ch /Ff 131072 /T (size) /Opt [(Small) (Large)] /V (Large) /Rect [20 200 180 220] /P 3 0 R /F 4 >>"
.into(),
];
let mut s = Session::new();
let id = s.open("items.pdf", None, Arc::new(pdf_of(&objs)), None).unwrap();
let out = s
.run_javascript(
id,
"var f = getField('size'); f.setItems([['Medium', 'm'], 'Large']); \
f.setAction('MouseEnter', \"getField('log').value = 'entered ' + event.target.value;\");",
None,
)
.unwrap();
assert_eq!(out.error, None, "{out:?}");
let size = s.get(id).unwrap().form.iter().find(|f| f.name == "size").unwrap().clone();
assert_eq!(size.options, [("m".to_string(), "Medium".to_string()), ("Large".into(), "Large".into())]);
assert_eq!(size.value, ["Large"], "the value is still an item: it stays");
assert!(s.field_trigger(id, "size", 0, Trigger::MouseEnter).unwrap());
assert_eq!(log(&s, id), "entered Large");
s.undo(id).unwrap();
s.undo(id).unwrap();
assert_eq!(s.get(id).unwrap().form.iter().find(|f| f.name == "size").unwrap().options[0].1, "Small", "undone");
s.redo(id).unwrap();
let saved = s.save_bytes(id).unwrap();
let mut again = Session::new();
let reopened = again.open("saved.pdf", None, saved, None).unwrap();
let size = again.get(reopened).unwrap().form.iter().find(|f| f.name == "size").unwrap().clone();
assert_eq!(size.options[0], ("m".to_string(), "Medium".to_string()));
assert!(again.field_trigger(reopened, "size", 0, Trigger::MouseEnter).unwrap(), "the installed script is in the file");
}
/// A check box's Mouse Up, run after the click stored the new value, reads that value and can
/// show or hide another field by it (#247).
#[test]
fn a_check_box_mouse_up_reads_the_value_its_click_stored() {
use crate::{Edit, FieldValue};
use pdfcraft_forms::Trigger;
let objs = vec![
"<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [4 0 R 6 0 R 7 0 R] /DA (/Helv 0 Tf 0 g) /DR << /Font << /Helv 5 0 R >> >> >> >>".to_string(),
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 200 300] >>".into(),
"<< /Type /Page /Parent 2 0 R /Annots [4 0 R 6 0 R 7 0 R] >>".into(),
"<< /Type /Annot /Subtype /Widget /FT /Tx /T (log) /V () /Rect [20 250 180 270] /P 3 0 R /F 4 >>".into(),
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".into(),
"<< /Type /Annot /Subtype /Widget /FT /Btn /T (strike) /V /Off /AS /Off /Rect [20 150 50 180] /P 3 0 R /F 4 /MK << /CA (4) >> /AP << /N << /Yes 8 0 R /Off 8 0 R >> >> /A << /S /JavaScript /JS (getField\\('note'\\).display = event.target.value == 'Off' ? display.hidden : display.visible; getField\\('log'\\).value += 'up:' + event.target.value + ';';) >> >>".into(),
"<< /Type /Annot /Subtype /Widget /FT /Tx /T (note) /V (struck) /Rect [60 150 180 180] /P 3 0 R /F 6 >>".into(),
"<< /Type /XObject /Subtype /Form /BBox [0 0 30 30] /Length 0 >>\nstream\n\nendstream".into(),
];
let mut s = Session::new();
let id = s.open("strike.pdf", None, Arc::new(pdf_of(&objs)), None).unwrap();
s.apply(id, Edit::SetFieldValue { name: "strike".into(), value: FieldValue::Text("Yes".into()) }).unwrap();
let ran = s.field_trigger(id, "strike", 0, Trigger::MouseUp);
let out = s.take_js_output(id);
assert!(ran.unwrap(), "{out:?}");
assert_eq!(log(&s, id), "up:Yes;");
let note = |s: &Session| s.get(id).unwrap().form.iter().find(|f| f.name == "note").unwrap().widgets[0].hidden;
assert!(!note(&s), "shown by the script");
s.apply(id, Edit::SetFieldValue { name: "strike".into(), value: FieldValue::Check(false) }).unwrap();
assert!(s.field_trigger(id, "strike", 0, Trigger::MouseUp).unwrap());
assert_eq!(log(&s, id), "up:Yes;up:Off;");
assert!(note(&s), "hidden again");
}
/// A widget action's `/Next` chain runs too, each JavaScript action in order (depth first), past
/// an action of another type at its head.
#[test]
fn a_widget_actions_next_chain_runs_each_script_in_order() {
use pdfcraft_forms::Trigger;
let js = |text: &str, next: &str| format!("<< /S /JavaScript /JS (getField\\('log'\\).value += '{text}';) {next} >>");
let chain = format!("<< /S /URI /URI (https://example.com/) /Next [{} {}] >>", js("a;", &format!("/Next {}", js("b;", ""))), js("c;", ""));
let objs = vec![
"<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [4 0 R 6 0 R] /DA (/Helv 0 Tf 0 g) /DR << /Font << /Helv 5 0 R >> >> >> >>".to_string(),
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 200 300] >>".into(),
"<< /Type /Page /Parent 2 0 R /Annots [4 0 R 6 0 R] >>".into(),
"<< /Type /Annot /Subtype /Widget /FT /Tx /T (log) /V () /Rect [20 250 180 270] /P 3 0 R /F 4 >>".into(),
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".into(),
format!("<< /Type /Annot /Subtype /Widget /FT /Tx /T (hot) /V () /Rect [20 200 180 220] /P 3 0 R /F 4 /AA << /E {chain} >> >>"),
];
let mut s = Session::new();
let id = s.open("chain.pdf", None, Arc::new(pdf_of(&objs)), None).unwrap();
assert!(s.field_trigger(id, "hot", 0, Trigger::MouseEnter).unwrap());
assert_eq!(log(&s, id), "a;b;c;");
}
/// `setAction` on a field that shares its name with another installs the script on that field,
/// the one the script's object stands for, not the first of the name.
#[test]
fn set_action_installs_on_the_field_the_object_stands_for() {
let objs = vec![
"<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [4 0 R 6 0 R] /DA (/Helv 0 Tf 0 g) /DR << /Font << /Helv 5 0 R >> >> >> >>".to_string(),
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 200 300] >>".into(),
"<< /Type /Page /Parent 2 0 R /Annots [4 0 R 6 0 R] >>".into(),
"<< /Type /Annot /Subtype /Widget /FT /Tx /T (dup) /V () /Rect [20 250 180 270] /P 3 0 R /F 4 >>".into(),
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".into(),
"<< /Type /Annot /Subtype /Widget /FT /Tx /T (dup) /V () /Rect [20 200 180 220] /P 3 0 R /F 4 >>".into(),
];
let mut s = Session::new();
let id = s.open("dup.pdf", None, Arc::new(pdf_of(&objs)), None).unwrap();
let second = crate::js::field_object_id(pdfcraft_cos::ObjRef::new(6, 0));
let out =
s.run_javascript_answers_target(id, "event.target.setAction('Format', \"event.value = 'x';\");", Some("dup"), Some(second), &[]).unwrap();
assert_eq!(out.error, None, "{out:?}");
let cos = s.get(id).unwrap().editor.as_ref().unwrap().cos.clone();
let formats: Vec<(u32, bool)> = pdfcraft_forms::fields(&cos).iter().map(|f| (f.obj.num, f.actions.scripts.format.is_some())).collect();
assert_eq!(formats, [(4, false), (6, true)]);
}
/// Of two fields sharing a name, the one the pointer is on runs its own widget script.
#[test]
fn a_trigger_on_a_field_sharing_a_name_runs_that_fields_script() {
use pdfcraft_forms::Trigger;
let enter = |text: &str| format!("/AA << /E << /S /JavaScript /JS (getField\\('log'\\).value += '{text}';) >> >>");
let objs = vec![
"<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [4 0 R 6 0 R 7 0 R] /DA (/Helv 0 Tf 0 g) /DR << /Font << /Helv 5 0 R >> >> >> >>"
.to_string(),
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 200 300] >>".into(),
"<< /Type /Page /Parent 2 0 R /Annots [4 0 R 6 0 R 7 0 R] >>".into(),
"<< /Type /Annot /Subtype /Widget /FT /Tx /T (log) /V () /Rect [20 250 180 270] /P 3 0 R /F 4 >>".into(),
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".into(),
format!("<< /Type /Annot /Subtype /Widget /FT /Tx /T (dup) /V () /Rect [20 200 180 220] /P 3 0 R /F 4 {} >>", enter("first;")),
format!("<< /Type /Annot /Subtype /Widget /FT /Tx /T (dup) /V () /Rect [20 150 180 170] /P 3 0 R /F 4 {} >>", enter("second;")),
];
let mut s = Session::new();
let id = s.open("dup.pdf", None, Arc::new(pdf_of(&objs)), None).unwrap();
let second = crate::js::field_object_id(pdfcraft_cos::ObjRef::new(7, 0));
assert!(s.field_trigger_target(id, "dup", Some(second), 0, Trigger::MouseEnter).unwrap());
assert_eq!(log(&s, id), "second;");
assert!(s.field_trigger(id, "dup", 0, Trigger::MouseEnter).unwrap(), "by name alone, the first");
assert_eq!(log(&s, id), "second;first;");
}
/// Focus too: of two fields sharing a name, the one that gained focus runs its On Focus script.
#[test]
fn focus_on_a_field_sharing_a_name_runs_that_fields_script() {
use crate::js::FieldFocus;
let focus = |text: &str| format!("/AA << /Fo << /S /JavaScript /JS (getField\\('log'\\).value += '{text}';) >> >>");
let objs = vec![
"<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [4 0 R 6 0 R 7 0 R] /DA (/Helv 0 Tf 0 g) /DR << /Font << /Helv 5 0 R >> >> >> >>"
.to_string(),
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 200 300] >>".into(),
"<< /Type /Page /Parent 2 0 R /Annots [4 0 R 6 0 R 7 0 R] >>".into(),
"<< /Type /Annot /Subtype /Widget /FT /Tx /T (log) /V () /Rect [20 250 180 270] /P 3 0 R /F 4 >>".into(),
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".into(),
format!("<< /Type /Annot /Subtype /Widget /FT /Tx /T (dup) /V () /Rect [20 200 180 220] /P 3 0 R /F 4 {} >>", focus("first;")),
format!("<< /Type /Annot /Subtype /Widget /FT /Tx /T (dup) /V () /Rect [20 150 180 170] /P 3 0 R /F 4 {} >>", focus("second;")),
];
let mut s = Session::new();
let id = s.open("dup.pdf", None, Arc::new(pdf_of(&objs)), None).unwrap();
let second = crate::js::field_object_id(pdfcraft_cos::ObjRef::new(7, 0));
assert!(s.field_focus_target(id, "dup", Some(second), 0, FieldFocus::Enter).unwrap());
assert_eq!(log(&s, id), "second;");
}
+185 -7
View File
@@ -408,6 +408,8 @@ fn changes(
text_color: a.text_color.as_deref().filter(|_| a.text_color != b.text_color).map(<[_]>::to_vec),
fill_color: a.fill_color.as_deref().filter(|_| a.fill_color != b.fill_color).map(<[_]>::to_vec),
caption: (a.caption != b.caption || (a.caption_written && b.caption_mixed)).then(|| a.caption.clone()).flatten(),
options: (a.options != b.options).then(|| a.options.clone()),
actions: a.actions.clone(),
};
(c.value.is_some()
|| c.read_only.is_some()
@@ -422,7 +424,9 @@ fn changes(
|| c.line_width.is_some()
|| c.border_style.is_some()
|| c.user_name.is_some()
|| c.icon.is_some())
|| c.icon.is_some()
|| c.options.is_some()
|| !c.actions.is_empty())
.then_some(c)
})
.collect()
@@ -827,6 +831,23 @@ impl DocumentScriptEvent {
Self::WillPrint => "WillPrint",
}
}
/// Where the catalog keeps this event's actions.
fn trigger(self) -> pdfcraft_forms::DocumentTrigger {
match self {
Self::CatalogOpen => pdfcraft_forms::DocumentTrigger::Open,
Self::WillSave => pdfcraft_forms::DocumentTrigger::WillSave,
Self::WillPrint => pdfcraft_forms::DocumentTrigger::WillPrint,
}
}
}
/// Keep only what a script that ran unasked (on opening, before saving or printing) may ask
/// the viewer for: highlighting, zoom, focus and the page shown. Opening a URL, a file, mail or
/// a dialog needs a click.
fn unasked_requests(requests: &mut Vec<Request>) {
requests
.retain(|r| matches!(r, Request::Highlight(_) | Request::Zoom(_) | Request::Focus(_) | Request::FocusField { .. } | Request::GoToPage(_)));
}
impl Session {
@@ -878,13 +899,33 @@ impl Session {
/// change runs it) isn't run a second time. Returns whether the document changed; what the
/// scripts showed or asked for is in [`Session::take_js_output`].
pub fn field_focus(&mut self, id: DocId, name: &str, widget: usize, focus: FieldFocus) -> Result<bool, EditError> {
self.field_focus_target(id, name, None, widget, focus)
}
/// [`Session::field_focus`] for the field object `target` ([`field_object_id`]) when given:
/// of fields sharing `name`, the one that gained or lost focus runs its own script.
pub fn field_focus_target(&mut self, id: DocId, name: &str, target: Option<u64>, widget: usize, focus: FieldFocus) -> Result<bool, EditError> {
if self.js_off {
return Ok(false);
}
let doc = self.doc_mut(id)?;
let Some(tpl) = doc.xfa_template.clone().filter(|t| pdfcraft_xfa::has_focus_scripts(t)) else { return Ok(false) };
let Some(tpl) = doc.xfa_template.clone().filter(|t| pdfcraft_xfa::has_focus_scripts(t)) else {
// An AcroForm widget's own On Focus / On Blur JavaScript (#269).
let trigger = match focus {
FieldFocus::Enter => pdfcraft_forms::Trigger::OnFocus,
FieldFocus::Exit => pdfcraft_forms::Trigger::OnBlur,
};
return self.field_trigger_target(id, name, target, widget, trigger);
};
let Some(cos) = doc.editor.as_ref().map(|e| &e.cos) else { return Ok(false) };
let Some(som) = doc.form.iter().find(|f| f.name == name).and_then(|f| crate::xfa::widget_som(cos, f, widget)) else { return Ok(false) };
let Some(som) = doc
.form
.iter()
.find(|f| f.name == name && target.is_none_or(|t| field_object_id(f.obj) == t))
.and_then(|f| crate::xfa::widget_som(cos, f, widget))
else {
return Ok(false);
};
let activity = match focus {
FieldFocus::Enter => "enter",
FieldFocus::Exit => "exit",
@@ -902,6 +943,85 @@ impl Session {
Ok(self.get(id).is_some_and(|d| d.generation != before))
}
/// Widget `widget` (0-based) of AcroForm field `name` in document `id` saw `trigger`: the
/// pointer entered, left, pressed or released it, or it gained or lost the focus. Run that
/// widget's JavaScript action for the trigger, if it has one, in the document's realm, with
/// `event.type` "Field" and `event.name` "Mouse Enter", "Mouse Exit", "Mouse Down", "Mouse
/// Up", "Focus" or "Blur" (#269, ported from #344), then those of the actions chained after
/// it (`/Next`). What each action changes is one undoable edit.
/// Returns whether the document changed; what the script showed or asked for is in
/// [`Session::take_js_output`]. Pointer and focus scripts run unasked, so they may not
/// print, open Save As or show a panel; Mouse Down and Mouse Up come from a click and may.
/// Nothing runs on an XFA form (its own events run instead), with JavaScript off, or for a
/// widget with no JavaScript for the trigger.
pub fn field_trigger(&mut self, id: DocId, name: &str, widget: usize, trigger: pdfcraft_forms::Trigger) -> Result<bool, EditError> {
self.field_trigger_target(id, name, None, widget, trigger)
}
/// [`Session::field_trigger`] for the field object `target` ([`field_object_id`]) when given:
/// of fields sharing `name`, the one the pointer is on runs its own script.
pub fn field_trigger_target(
&mut self,
id: DocId,
name: &str,
target: Option<u64>,
widget: usize,
trigger: pdfcraft_forms::Trigger,
) -> Result<bool, EditError> {
use pdfcraft_forms::Trigger;
if self.js_off {
return Ok(false);
}
let doc = self.get(id).ok_or(EditError::NoDocument)?;
if doc.info.xfa.is_some() {
return Ok(false);
}
let Some(cos) = doc.editor.as_ref().map(|e| &e.cos) else { return Ok(false) };
let field = doc
.form
.iter()
.find(|f| f.name == name && target.is_none_or(|t| field_object_id(f.obj) == t))
.ok_or_else(|| EditError::Invalid(format!("there is no field named {name:?}")))?;
let Some(w) = field.widgets.get(widget) else { return Ok(false) };
let scripts = pdfcraft_forms::widget_scripts(cos, w.obj, trigger);
if scripts.is_empty() {
return Ok(false);
}
let target_id = Some(field_object_id(field.obj));
let event = match trigger {
Trigger::OnFocus => "Focus",
Trigger::OnBlur => "Blur",
other => other.label(),
};
let before = doc.generation;
let mut out = JsOutput::default();
// Each action of a /Next chain runs on its own, as Acrobat runs them: one that fails
// doesn't stop the next.
for script in scripts {
let o = match self.run_javascript_job(id, &script, (Some(name), target_id), &[], Some(event), false) {
Ok(o) => o,
Err(e) => {
out.errors.push(e.to_string());
continue;
}
};
if matches!(trigger, Trigger::MouseUp | Trigger::MouseDown) {
out.append(JsOutput {
alerts: o.alerts,
console: o.console,
requests: o.requests,
errors: o.error.into_iter().chain(o.doc_errors.iter().cloned()).collect(),
doc_errors: o.doc_errors,
});
} else {
out.absorb(&o);
}
}
let doc = self.doc_mut(id)?;
doc.js_output.append(out);
Ok(doc.generation != before)
}
/// Run signature field `field`'s XFA signing scripts for `event` in document `id`: `preSign`
/// before it is signed, `postSign` after, as one undoable step, as a form's signing events run
/// (DA 31's dates the signature and locks the date). `Ok(false)`, with nothing changed, when
@@ -970,9 +1090,66 @@ impl Session {
self.run_javascript_job(id, "", (None, None), &[], None, true)
}
/// Opening document `id`: its document-level scripts run once, then the catalog
/// `/OpenAction`'s JavaScript, in the document's retained realm (#269). Not on an XFA form
/// (its own opening scripts run instead) or with JavaScript off. What they showed or asked
/// for waits in [`Session::take_js_output`].
pub(crate) fn run_open_scripts(&mut self, id: DocId) {
if self.js_off {
return;
}
let Some(doc) = self.get(id).filter(|d| d.info.xfa.is_none()) else { return };
let has_document_scripts = !doc.document_scripts().is_empty();
let opens =
doc.editor.as_ref().map(|e| pdfcraft_forms::document_action_scripts(&e.cos, pdfcraft_forms::DocumentTrigger::Open)).unwrap_or_default();
if !has_document_scripts && opens.is_empty() {
return;
}
let mut out = JsOutput::default();
if has_document_scripts && opens.is_empty() {
match self.run_opening_javascript(id) {
Ok(o) => out.absorb(&o),
Err(e) => out.errors.push(e.to_string()),
}
}
// The first open action initializes the realm with the document scripts too.
out.append(self.run_actions(id, DocumentScriptEvent::CatalogOpen, &opens));
unasked_requests(&mut out.requests);
if let Some(doc) = self.docs.iter_mut().find(|d| d.id == id) {
doc.js_output.append(out);
}
}
/// Run the catalog's JavaScript actions for document event `event` (`/AA /WS` before a save,
/// `/AA /WP` before printing, `/OpenAction` on opening) in document `id`'s retained realm.
/// Each action's field changes are one undoable edit. A failing action is reported in the
/// output and the next one still runs; it never stops the save or print, which must not
/// lose the user's work. Requests are limited to what an unasked script may make. With
/// JavaScript off, on an XFA form, or with no such action, nothing runs.
pub fn run_document_actions(&mut self, id: DocId, event: DocumentScriptEvent) -> JsOutput {
if self.js_off {
return JsOutput::default();
}
let Some(doc) = self.get(id).filter(|d| d.info.xfa.is_none()) else { return JsOutput::default() };
let scripts = doc.editor.as_ref().map(|e| pdfcraft_forms::document_action_scripts(&e.cos, event.trigger())).unwrap_or_default();
self.run_actions(id, event, &scripts)
}
fn run_actions(&mut self, id: DocId, event: DocumentScriptEvent, scripts: &[String]) -> JsOutput {
let mut out = JsOutput::default();
for script in scripts {
match self.run_javascript_job(id, script, (None, None), &[], Some(event.name()), event == DocumentScriptEvent::CatalogOpen) {
Ok(o) => out.absorb(&o),
Err(e) => out.errors.push(format!("{} script: {e}", event.name())),
}
}
unasked_requests(&mut out.requests);
out
}
/// Run an explicitly dispatched PDF document action in the document's retained runtime.
pub fn run_document_script_event(&mut self, id: DocId, event: DocumentScriptEvent, script: &str) -> Result<Outcome, EditError> {
self.run_javascript_job(id, script, (None, None), &[], Some(event), false)
self.run_javascript_job(id, script, (None, None), &[], Some(event.name()), false)
}
/// Route generated XFA clicks to the XFA engine, or run a synchronous AcroForm job and apply its outcome.
@@ -982,7 +1159,7 @@ impl Session {
script: &str,
(target, target_id): (Option<&str>, Option<u64>),
answers: &[Option<String>],
document_event: Option<DocumentScriptEvent>,
event_name: Option<&'static str>,
opening: bool,
) -> Result<Outcome, EditError> {
if self.js_off {
@@ -993,6 +1170,7 @@ impl Session {
validate_script_target(target, target_id, &doc.form)?;
// A button PdfCraft generated from an XFA template runs its XFA click script.
if let Some(t) = target
&& event_name.is_none_or(|n| n == "Mouse Up")
&& let Some(tpl) = doc.xfa_template.clone()
&& let Some(field) = doc.form.iter().find(|f| f.name == t && target_id.is_none_or(|id| field_object_id(f.obj) == id))
&& field.kind == crate::FormFieldKind::PushButton
@@ -1015,8 +1193,8 @@ impl Session {
let fields = pdfcraft_forms::fields(&cos);
let states = std::sync::Arc::new(fields.iter().map(|f| field_state(&cos, f, &runner.doc)).collect::<Vec<_>>());
let event = match target {
Some(t) => pdfcraft_js::Event { will_commit: false, target_id, ..pdfcraft_js::Event::field("Mouse Up", t, "") },
None => pdfcraft_js::Event::doc(document_event.map_or("Console", DocumentScriptEvent::name)),
Some(t) => pdfcraft_js::Event { will_commit: false, target_id, ..pdfcraft_js::Event::field(event_name.unwrap_or("Mouse Up"), t, "") },
None => pdfcraft_js::Event::doc(event_name.unwrap_or("Console")),
};
let calculations = calculation_scripts(&cos, &fields);
let runtime = doc.js_runtime.clone();
+6 -2
View File
@@ -92,7 +92,9 @@ pub use pdfcraft_organize::check_custom_key;
pub use pdfcraft_organize::view::{InitialView, Layout as InitialLayout, Magnification, Navigation};
pub use pdfcraft_cos::{Algorithm, civil_from_days};
pub use pdfcraft_create::{CONVERTIBLE, CreateError, ImageResolution, SourceKind, decode_text, source_kind};
pub use pdfcraft_create::{
CONVERTIBLE, CreateError, IMAGE_EXTENSIONS, ImageResolution, OFFICE_EXTENSIONS, SourceKind, TEXT_EXTENSIONS, 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,
text_width as added_text_width,
@@ -166,7 +168,7 @@ use pictures::{embed_image, fit_picture, mark_source, model_poster};
use protection::unrestricted;
pub use protection::{Changes, Printing, Protection, SecuritySummary};
pub use session::Session;
pub use sources::{CombineSource, Combined, combine_source_check, source_page_count};
pub use sources::{CombineSource, Combined, combine_source_check, office_to_pdf, source_page_count};
use sources::{open_source, open_source_with};
#[cfg(test)]
use test_hooks::{
@@ -198,5 +200,7 @@ fn display_config(config: &pdfcraft_render::RenderConfig) -> pdfcraft_render::Re
/// How long a custom stamp's text line may be, in characters (#1741).
pub const MAX_STAMP_LINE: usize = 200;
#[cfg(test)]
mod document_actions_tests;
#[cfg(test)]
mod tests;
+1 -29
View File
@@ -101,35 +101,7 @@ impl Session {
Self::draw_captions(&mut document, self.captions.clone());
}
self.docs.push(document);
if !self.js_off && self.get(id).is_some_and(|d| d.info.xfa.is_none() && !d.document_scripts().is_empty()) {
match self.run_opening_javascript(id) {
Ok(mut out) => {
out.requests.retain(|r| {
matches!(
r,
js::Request::Highlight(_)
| js::Request::Zoom(_)
| js::Request::Focus(_)
| js::Request::FocusField { .. }
| js::Request::GoToPage(_)
)
});
if let Some(doc) = self.docs.iter_mut().find(|d| d.id == id) {
doc.js_output.requests.extend(out.requests);
doc.js_output.alerts.extend(out.alerts);
doc.js_output.console.extend(out.console);
doc.js_output.errors.extend(out.error);
doc.js_output.doc_errors.extend(out.doc_errors.iter().cloned());
doc.js_output.errors.extend(out.doc_errors);
}
}
Err(e) => {
if let Some(doc) = self.docs.iter_mut().find(|d| d.id == id) {
doc.js_output.errors.push(e.to_string());
}
}
}
}
self.run_open_scripts(id);
id
}
+1 -1
View File
@@ -13,7 +13,7 @@ use crate::{
BookmarkPage, BookmarkRow, CombineSource, Combined, DataFormat, DocId, Document, Edit, EditError, Hairlines, HairlinesFixed, Hidden,
ImageResolution, 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,
comment_summary, decode_text, display_bytes, display_config, guard, info_fields, js, local_utc_offset, note_warnings, office_to_pdf, open_source,
open_source_with, optimize, outline_rows, 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,
+65 -14
View File
@@ -1,9 +1,17 @@
use super::{
Arc, CombineSource, Combined, DataFormat, DocId, EditError, Hairlines, HairlinesFixed, Hidden, ImageResolution, LOW_RESOLUTION_PRINT_DPI,
OptimizeReport, SaveOptions, Session, SourceKind, SplitPart, decode_text, guard, open_source, open_source_with, optimize, print,
OptimizeReport, SaveOptions, Session, SourceKind, SplitPart, decode_text, guard, office_to_pdf, open_source, open_source_with, optimize, print,
print_layer_states, print_raster, set_default_layer_state, source_kind, writable, write_full,
};
/// Whether a conversion may run LibreOffice for an Office document (seconds, in another
/// process) or must refuse it because the caller is on the frame thread.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Office {
Convert,
Refuse,
}
impl Session {
/// The page count of another PDF (Replace Pages, Insert Pages dialogs).
pub fn page_count_of(&self, name: &str, bytes: &Arc<Vec<u8>>) -> Result<usize, EditError> {
@@ -41,30 +49,63 @@ impl Session {
self.write_new(&doc)
}
/// Convert a file Create understands (an image or plain text) to PDF bytes; a PDF is checked
/// (it must open and allow copying pages) and returned as it is.
/// Convert a file Create understands (an image, plain text or an Office document) to PDF
/// bytes; a PDF is checked (it must open and allow copying pages) and returned as it is.
/// An Office document runs LibreOffice ([`office_to_pdf`]), which takes seconds: keep it off
/// the frame thread ([`Self::convert_to_pdf_inline`] there).
pub fn convert_to_pdf(&self, name: &str, bytes: &Arc<Vec<u8>>) -> Result<(SourceKind, Arc<Vec<u8>>), EditError> {
self.convert(name, bytes, Office::Convert)
}
/// [`Self::convert_to_pdf`] for a caller on the frame thread, which must not wait seconds for
/// LibreOffice: an Office document is refused, pointing to File ▸ Open, which converts it in
/// the background.
pub fn convert_to_pdf_inline(&self, name: &str, bytes: &Arc<Vec<u8>>) -> Result<(SourceKind, Arc<Vec<u8>>), EditError> {
self.convert(name, bytes, Office::Refuse)
}
fn convert(&self, name: &str, bytes: &Arc<Vec<u8>>, office: Office) -> Result<(SourceKind, Arc<Vec<u8>>), EditError> {
let Some(kind) = source_kind(name, bytes) else {
return Err(EditError::Source(format!("{name}: this file type can't be converted; use a PDF, an image or a .txt file")));
return Err(EditError::Source(format!(
"{name}: this file type can't be converted; use a PDF, an image, a .txt file or a Word, Excel or PowerPoint file"
)));
};
if kind == SourceKind::Office && office == Office::Refuse {
return Err(EditError::Source(format!(
"{name}: Word, Excel and PowerPoint files can't be added here yet; open it with File ▸ Open, which converts it to a PDF"
)));
}
let title = name.rsplit_once('.').map_or(name, |(s, _)| s);
// Image decoders read untrusted bytes: a panic in one must not take the app down.
let created = guard(|| match kind {
SourceKind::Pdf => open_source(name, bytes).map(|_| bytes.clone()),
SourceKind::Image => self.create_from_images(&[(name.to_string(), bytes.to_vec())]),
SourceKind::Text => self.create_from_text(title, &decode_text(bytes)),
SourceKind::Office => office_to_pdf(name, bytes),
})
.map_err(|_| EditError::Source(format!("{name}: the file could not be read")))?;
Ok((kind, created?))
}
/// A file for Insert Pages into `dest`, as PDF bytes and its page count: an image or text
/// file is converted, and a PDF is checked as the insert itself checks it, so a file under
/// `dest`'s own protection that withholds only page extraction is accepted, as pasted pages
/// are (#5081).
/// A file for Insert Pages into `dest`, as PDF bytes and its page count: an image, text or
/// Office file is converted, and a PDF is checked as the insert itself checks it, so a file
/// under `dest`'s own protection that withholds only page extraction is accepted, as pasted
/// pages are (#5081). An Office document runs LibreOffice: keep it off the frame thread
/// ([`Self::insert_source_inline`] there).
pub fn insert_source(&self, dest: DocId, name: &str, bytes: &Arc<Vec<u8>>) -> Result<(usize, Arc<Vec<u8>>), EditError> {
self.insert_source_with(dest, name, bytes, Office::Convert)
}
/// [`Self::insert_source`] on the frame thread: Office documents are refused, as
/// [`Self::convert_to_pdf_inline`] refuses them. PDFs are still checked as the insert itself
/// checks them (#5081).
pub fn insert_source_inline(&self, dest: DocId, name: &str, bytes: &Arc<Vec<u8>>) -> Result<(usize, Arc<Vec<u8>>), EditError> {
self.insert_source_with(dest, name, bytes, Office::Refuse)
}
fn insert_source_with(&self, dest: DocId, name: &str, bytes: &Arc<Vec<u8>>, office: Office) -> Result<(usize, Arc<Vec<u8>>), EditError> {
if !matches!(source_kind(name, bytes), Some(SourceKind::Pdf)) {
let (_, pdf) = self.convert_to_pdf(name, bytes)?;
let (_, pdf) = self.convert(name, bytes, office)?;
return Ok((self.page_count_of(name, &pdf)?, pdf));
}
let src = crate::sources::open_source_into(name, bytes, self.cos(dest)?)?;
@@ -78,16 +119,26 @@ impl Session {
Ok(pdfcraft_organize::page_count(&crate::sources::open_source_into(name, bytes, self.cos(dest)?)?)?)
}
/// A file for Combine as PDF bytes: an image or text file is converted; a PDF is returned as
/// it is, unchecked (Combine reads it itself, with its password), as is a file named .pdf
/// without a `%PDF-` header, which the reader may still open.
/// A file for Combine as PDF bytes: an image, text or Office file is converted; a PDF is
/// returned as it is, unchecked (Combine reads it itself, with its password), as is a file
/// named .pdf without a `%PDF-` header, which the reader may still open.
pub fn as_pdf(&self, name: &str, bytes: &Arc<Vec<u8>>) -> Result<Arc<Vec<u8>>, EditError> {
self.as_pdf_with(name, bytes, Office::Convert)
}
/// [`Self::as_pdf`] on the frame thread: Office documents are refused, as
/// [`Self::convert_to_pdf_inline`] refuses them.
pub fn as_pdf_inline(&self, name: &str, bytes: &Arc<Vec<u8>>) -> Result<Arc<Vec<u8>>, EditError> {
self.as_pdf_with(name, bytes, Office::Refuse)
}
fn as_pdf_with(&self, name: &str, bytes: &Arc<Vec<u8>>, office: Office) -> Result<Arc<Vec<u8>>, EditError> {
let pdf = match source_kind(name, bytes) {
Some(SourceKind::Pdf) => true,
Some(SourceKind::Image | SourceKind::Text) => false,
Some(SourceKind::Image | SourceKind::Text | SourceKind::Office) => false,
None => name.to_ascii_lowercase().ends_with(".pdf"),
};
if pdf { Ok(bytes.clone()) } else { self.convert_to_pdf(name, bytes).map(|(_, pdf)| pdf) }
if pdf { Ok(bytes.clone()) } else { self.convert(name, bytes, office).map(|(_, pdf)| pdf) }
}
/// Reduce File Size: Acrobat's defaults (colour and grey images above 225 ppi to 150 ppi,
+6 -2
View File
@@ -132,7 +132,7 @@ impl Session {
}
/// File ▸ Revert: back to the last saved version (or the file as opened). Undo history is
/// cleared, as in Acrobat.
/// cleared, as in Acrobat, and the document's opening scripts run again.
pub fn revert(&mut self, id: DocId) -> Result<(), EditError> {
self.invalidate_javascript(id);
let doc = self.doc_mut(id)?;
@@ -156,7 +156,11 @@ impl Session {
// The changes whose exits ran are gone with the rest: skip no exit.
doc.xfa_exited.clear();
doc.generation += 1;
Self::refresh(doc).inspect_err(|_| Self::show_released(doc))
Self::refresh(doc).inspect_err(|_| Self::show_released(doc))?;
// Reverting reopens the saved file, in a fresh realm: its opening scripts run again,
// as they do on opening it (#269).
self.run_open_scripts(id);
Ok(())
}
/// The document's file changed on disk (a LaTeX or Typst build rewrote it, #431): open
+10
View File
@@ -15,6 +15,16 @@ pub struct Combined {
pub renamed_fields: Vec<(String, String)>,
}
/// Convert the Office document `bytes` named `name` (Word, Excel, PowerPoint, OpenDocument,
/// RTF) to PDF with an installed LibreOffice, and check the result opens. It runs a separate
/// process for seconds, so callers keep it off the frame thread. Desktop only: on the web it
/// returns an error.
pub fn office_to_pdf(name: &str, bytes: &Arc<Vec<u8>>) -> Result<Arc<Vec<u8>>, EditError> {
let pdf = Arc::new(pdfcraft_create::office_to_pdf(name, bytes)?);
open_source(name, &pdf)?;
Ok(pdf)
}
/// Parse another PDF to copy pages from.
pub(crate) fn open_source(name: &str, bytes: &Arc<Vec<u8>>) -> Result<pdfcraft_cos::Document, EditError> {
open_source_with(name, bytes, None)
+54 -4
View File
@@ -1575,8 +1575,13 @@ fn a_page_with_a_form_field_shown_twice_keeps_one_field() {
#[test]
fn files_that_cannot_be_converted_are_refused_clearly() {
let s = Session::new();
let err = s.convert_to_pdf("report.docx", &Arc::new(b"PK\x03\x04".to_vec())).unwrap_err();
assert_eq!(err, EditError::Source("report.docx: this file type can't be converted; use a PDF, an image or a .txt file".into()));
let err = s.convert_to_pdf("archive.zip", &Arc::new(b"PK\x03\x04".to_vec())).unwrap_err();
assert_eq!(
err,
EditError::Source(
"archive.zip: this file type can't be converted; use a PDF, an image, a .txt file or a Word, Excel or PowerPoint file".into()
)
);
assert!(matches!(s.convert_to_pdf("empty", &Arc::new(Vec::new())), Err(EditError::Source(_))));
// Damaged inputs of a known type fail with an error, not a panic.
assert!(s.convert_to_pdf("bad.png", &Arc::new(b"\x89PNG\r\n\x1a\nnope".to_vec())).is_err());
@@ -1597,8 +1602,8 @@ fn files_for_combine_are_made_into_pdfs_and_pdfs_pass_through() {
assert!(Arc::ptr_eq(&s.as_pdf("old.PDF", &headless).unwrap(), &headless));
assert!(s.as_pdf("scan.jpg", &Arc::new(jpeg_bytes())).unwrap().starts_with(b"%PDF-"));
assert!(s.as_pdf("notes.txt", &Arc::new(b"hello".to_vec())).unwrap().starts_with(b"%PDF-"));
let err = s.as_pdf("report.docx", &Arc::new(b"PK\x03\x04".to_vec())).unwrap_err();
assert!(matches!(err, EditError::Source(m) if m.starts_with("report.docx: this file type can't be converted")));
let err = s.as_pdf("archive.zip", &Arc::new(b"PK\x03\x04".to_vec())).unwrap_err();
assert!(matches!(err, EditError::Source(m) if m.starts_with("archive.zip: this file type can't be converted")));
}
fn protected(user: &str, owner: &str, permissions: i32) -> Arc<Vec<u8>> {
@@ -15359,3 +15364,48 @@ fn calculate_now_simple_calculation_reads_formatted_values_and_groups_as_the_nat
assert!(out.console.iter().any(|line| line == "3244.75"), "calculateNow agrees with the native path: {out:?}");
assert_eq!(total(&s), ["3244.75"]);
}
/// A Word document converts through LibreOffice when it is installed; without it, the error
/// says what is missing rather than calling the file a broken PDF.
#[test]
fn office_documents_convert_through_libreoffice_or_explain_why_not() {
let mut s = Session::new();
let text = s.create_from_text("t", "Quarterly report").unwrap();
let id = s.open("t.pdf", None, text, None).unwrap();
let docx = Arc::new(s.get(id).unwrap().export_office(compare::OfficeFormat::Docx));
assert_eq!(source_kind("Report.docx", &docx), Some(SourceKind::Office));
match s.convert_to_pdf("Report.docx", &docx) {
Ok((kind, pdf)) => {
assert_eq!(kind, SourceKind::Office);
let converted = s.open_new("Report.pdf", pdf).unwrap();
assert!(page_texts(&s, converted).concat().contains("Quarterly report"));
}
// Only "not installed" is an acceptable failure: a conversion that fails, times out or
// makes no PDF must fail this test.
Err(e) => assert!(e.to_string().contains("LibreOffice, which isn't installed"), "{e}"),
}
// Combine treats it as a file to convert, not as a PDF to pass through.
assert!(
s.as_pdf("Report.docx", &docx).map_or_else(|e| e.to_string().contains("LibreOffice, which isn't installed"), |pdf| pdf.starts_with(b"%PDF-"))
);
}
/// The frame thread never waits for LibreOffice: Insert, Combine and Create Multiple refuse an
/// Office document and point to File ▸ Open, while images and text still convert there.
#[test]
fn inline_conversions_refuse_office_documents_without_running_libreoffice() {
let s = Session::new();
let docx = Arc::new(b"PK\x03\x04\x14\x00".to_vec());
for err in
[s.convert_to_pdf_inline("Report.docx", &docx).map(|_| ()).unwrap_err(), s.as_pdf_inline("Report.docx", &docx).map(|_| ()).unwrap_err()]
{
assert_eq!(
err,
EditError::Source(
"Report.docx: Word, Excel and PowerPoint files can't be added here yet; open it with File ▸ Open, which converts it to a PDF".into()
)
);
}
assert_eq!(s.convert_to_pdf_inline("notes.txt", &Arc::new(b"hello".to_vec())).unwrap().0, SourceKind::Text);
assert!(s.as_pdf_inline("scan.jpg", &Arc::new(jpeg_bytes())).unwrap().starts_with(b"%PDF-"));
}
+46 -24
View File
@@ -70,8 +70,15 @@ pub struct Metrics {
/// A stream these metrics come from (a CMap, the program, `/CIDToGIDMap`, a Type 3 glyph
/// description) was left unread because the decode allowance [`Metrics::from_dict_within`]
/// was given was spent: what it would have decided (code lengths, CIDs, widths, meanings, a
/// Type 3 font's height) is a guess.
/// Type 3 font's height) is a guess. It is set exactly when the allowance counted a refusal
/// during the read ([`DecodeBudget::refused`]), which callers that share it may refuse on; a
/// read that fails without one, such as an empty stream behind a filter nothing decodes,
/// doesn't set it, with or without anything left.
pub past_allowance: bool,
/// A codespace range of the embedded CMap was dropped (not one to four bytes, or past the range
/// limit): how the font's codes split into characters is then a guess, and a caller that must
/// know which text a string holds (redaction) refuses to rely on it.
pub codespaces_dropped: bool,
}
fn nums(doc: &Document, o: Option<&Object>) -> Vec<f64> {
@@ -420,12 +427,16 @@ impl<'a> Reads<'a> {
/// stage past `max` is unread. When what is left is more than what the stages before that one
/// made and `max`, it is charged those two and isn't refused; otherwise, with more left than
/// the stages' total (behind one filter, `max`), it is charged that total and isn't refused;
/// with no more left than that total, it spends all of it and counts as refused.
/// with no more left than that total, it spends all of it and counts as refused. Only what
/// the allowance counts as refused ([`DecodeBudget::refused`]) is noted: a read that fails
/// without one, such as an empty stream behind a filter nothing decodes, fails the same with
/// more left, and callers that refuse on that count must agree with [`Metrics::past_allowance`].
fn decode(&mut self, stream: &Stream, max: usize) -> Option<Vec<u8>> {
let refused = self.budget.refused();
match self.budget.decode_stages_within(self.doc, stream, max) {
Ok(data) => Some(data),
Err(_) => {
self.refused |= self.budget.remaining() == 0;
self.refused |= self.budget.refused() > refused;
None
}
}
@@ -491,10 +502,14 @@ fn type3_glyph_box(doc: &Document, font: &Dict, reads: &mut Reads<'_>) -> Option
break;
}
let before = reads.budget.remaining();
let refused = reads.budget.refused();
let read = reads.budget.decode_with_damage(doc, s, MAX_TYPE3_GLYPH_BYTES.min(left)).map(|(data, _)| data);
left = left.saturating_sub(before.saturating_sub(reads.budget.remaining()));
let Ok(data) = read else {
if reads.budget.remaining() == 0 {
// As in `Reads::decode`, only a refusal the allowance counts: a description that fails
// without one (an empty one nothing decodes, once the allowance is spent) leaves the
// rest to be read, or refused above.
if reads.budget.refused() > refused {
// The rest go unread too, for want of the reading's allowance.
reads.refused = true;
complete = false;
@@ -810,25 +825,39 @@ fn number(t: &Tok) -> Option<u32> {
}
}
/// The font's `/BaseFont` (a Type 3 font's descriptor `/FontName` when it has none), read without
/// building its metrics, so it decodes no CMap.
pub fn base_font_name(doc: &Document, font: &Dict) -> String {
font.name(b"BaseFont")
.map(|name| String::from_utf8_lossy(name).into_owned())
.or_else(|| {
(font.name(b"Subtype") == Some(b"Type3"))
.then(|| dict(doc, font.get(b"FontDescriptor")))
.flatten()
.and_then(|d| d.name(b"FontName").map(|name| String::from_utf8_lossy(name).into_owned()))
})
.unwrap_or_default()
}
/// Codespace ranges and CID mappings from an embedded CMap stream, at most
/// [`MAX_CMAP_RANGES`] of each (every glyph searches them).
#[allow(clippy::type_complexity)]
fn parse_cmap(data: &[u8]) -> (Vec<(usize, Vec<u8>, Vec<u8>)>, Vec<(u32, u32, u32)>) {
fn parse_cmap(data: &[u8]) -> (Vec<(usize, Vec<u8>, Vec<u8>)>, Vec<(u32, u32, u32)>, bool) {
let (mut spaces, mut cids) = (Vec::new(), Vec::new());
let mut dropped = false;
let mut seen = HashSet::new();
let mut toks = Lexer::new(data);
while let Some(t) = toks.next() {
match t {
Tok::Word(b"begincodespacerange") => {
while let Some([lo, hi]) = entry(&mut toks, b"endcodespacerange") {
if let (Tok::Hex(Some(lo)), Tok::Hex(Some(hi))) = (lo, hi)
&& lo.len() == hi.len()
if let (Tok::Hex(Some(lo)), Tok::Hex(Some(hi))) = (lo, hi) {
// A code is at most four bytes; a repeated range can never match first, so it only costs every glyph a comparison.
&& (1..=4).contains(&lo.len())
&& spaces.len() < MAX_CMAP_RANGES
&& seen.insert((lo.clone(), hi.clone()))
{
spaces.push((lo.len(), lo, hi));
if lo.len() != hi.len() || !(1..=4).contains(&lo.len()) || spaces.len() >= MAX_CMAP_RANGES {
dropped = true;
} else if seen.insert((lo.clone(), hi.clone())) {
spaces.push((lo.len(), lo, hi));
}
}
}
}
@@ -854,7 +883,7 @@ fn parse_cmap(data: &[u8]) -> (Vec<(usize, Vec<u8>, Vec<u8>)>, Vec<(u32, u32, u3
}
}
spaces.sort_by_key(|s| s.0);
(spaces, cids)
(spaces, cids, dropped)
}
impl Metrics {
@@ -884,6 +913,7 @@ impl Metrics {
explicit_reverse: (32..127u8).map(|c| (char::from(c), u32::from(c))).collect(),
outlined_cids: Vec::new(),
past_allowance: false,
codespaces_dropped: false,
}
}
@@ -902,16 +932,7 @@ impl Metrics {
pub fn from_dict_within(doc: &Document, font: &Dict, budget: &mut DecodeBudget) -> Self {
let mut reads = Reads::new(doc, budget);
let mut m = Self::read_metrics(doc, font, &mut reads);
let base = font
.name(b"BaseFont")
.map(|name| String::from_utf8_lossy(name).into_owned())
.or_else(|| {
(font.name(b"Subtype") == Some(b"Type3"))
.then(|| dict(doc, font.get(b"FontDescriptor")))
.flatten()
.and_then(|d| d.name(b"FontName").map(|name| String::from_utf8_lossy(name).into_owned()))
})
.unwrap_or_default();
let base = base_font_name(doc, font);
m.subset = base.len() > 7 && base.as_bytes()[6] == b'+' && base[..6].bytes().all(|b| b.is_ascii_uppercase());
let (bold, italic) = style_from_name(&base);
m.bold |= bold;
@@ -965,7 +986,8 @@ impl Metrics {
&& let Object::Stream(s) = &*e
&& let Some(data) = reads.decode(s, MAX_CMAP_BYTES)
{
let (spaces, cids) = parse_cmap(&data);
let (spaces, cids, dropped) = parse_cmap(&data);
m.codespaces_dropped = dropped;
if !spaces.is_empty() {
m.codes = Codes::Ranges(spaces);
}
+100 -6
View File
@@ -309,17 +309,27 @@ fn a_fonts_streams_are_paid_for_from_its_allowance() {
}
/// With nothing left, an empty stream still reads, as the allowance reads one, and is no reason to
/// call the font read past it; a stream with data is left unread, and is.
/// call the font read past it; a stream with data is left unread, and is. An empty stream behind a
/// filter nothing decodes is unread with any allowance, so it isn't either: the font is read past
/// its allowance exactly when the allowance counts a refusal, which is what callers refuse on.
#[test]
fn an_empty_stream_reads_with_nothing_left() {
let past = |data: &[u8]| {
let past = |filter: Option<&str>, data: &[u8]| {
let mut doc = Document::new_empty();
let unicode = Object::Ref(doc.add(Object::Stream(Stream::from_raw(Dict::new(), data.to_vec()))));
let mut dict = Dict::new();
if let Some(filter) = filter {
dict.set(b"Filter".to_vec(), Object::name(filter));
}
let unicode = Object::Ref(doc.add(Object::Stream(Stream::from_raw(dict, data.to_vec()))));
let f = font(&mut doc, vec![("Subtype", Object::name("TrueType")), ("ToUnicode", unicode)]);
Metrics::from_dict_within(&doc, &f, &mut DecodeBudget::new(0, 0)).past_allowance
let mut budget = DecodeBudget::new(0, 0);
let past = Metrics::from_dict_within(&doc, &f, &mut budget).past_allowance;
assert_eq!(past, budget.refused() > 0, "{filter:?}");
past
};
assert!(!past(b""));
assert!(past(b"1 beginbfchar <41> <0058> endbfchar"));
assert!(!past(None, b""));
assert!(!past(Some("NoSuchFilter"), b""));
assert!(past(None, b"1 beginbfchar <41> <0058> endbfchar"));
}
/// A stream behind one filter past its own limit, with more left than its limit, is left unread as
@@ -424,6 +434,45 @@ fn each_stage_of_a_metrics_stream_is_held_to_its_limit() {
assert_eq!(read(MAX_CID_TO_GID / 4), (false, false));
}
/// The editor's program list reads a legacy Thai font's metrics after its program. With the program
/// spending the allowance to the byte, a ToUnicode that is an empty stream behind a filter nothing
/// decodes, unread with any allowance, doesn't put the metrics past the allowance: the program is
/// listed. A ToUnicode with data is refused by the allowance, and the program isn't.
#[test]
fn an_editors_program_is_listed_past_a_stream_unread_on_its_own() {
let bytes = include_bytes!("../../../../assets/fonts/Inter-Regular.ttf");
let listed = |filter: Option<&str>, data: &[u8]| {
let mut doc = Document::new_empty();
let mut dict = Dict::new();
if let Some(filter) = filter {
dict.set(b"Filter".to_vec(), Object::name(filter));
}
let unicode = Object::Ref(doc.add(Object::Stream(Stream::from_raw(dict, data.to_vec()))));
let program = Object::Ref(doc.add(Object::Stream(Stream::from_raw(Dict::new(), bytes.to_vec()))));
let mut descriptor = Dict::new();
descriptor.set(b"FontFile2".to_vec(), program);
let f = font(
&mut doc,
vec![
("Subtype", Object::name("TrueType")),
("BaseFont", Object::name("THSarabunPSK")),
("FirstChar", Object::Int(65)),
("LastChar", Object::Int(65)),
("Widths", Object::Array(vec![Object::Int(500)])),
("Encoding", Object::name("WinAnsiEncoding")),
("FontDescriptor", Object::Dict(descriptor)),
("ToUnicode", unicode),
],
);
let mut budget = DecodeBudget::new(bytes.len(), 0);
let listed = embedded_sfnt_within(&doc, &f, &mut budget).is_some();
assert_eq!(budget.remaining(), 0, "the program spends the allowance to the byte");
(listed, budget.refused())
};
assert_eq!(listed(Some("NoSuchFilter"), b""), (true, 0));
assert_eq!(listed(None, b"1 beginbfchar <41> <0058> endbfchar"), (false, 1));
}
/// The editor's program is held to its limit as the metrics reads' streams are: a 12 MiB program
/// whose Flate data is about 8 MiB reads behind ASCIIHex and Flate as behind Flate alone, though
/// the two stages make about 20 MiB together. A program of the limit reads behind either, and one a
@@ -969,6 +1018,41 @@ fn type3_glyph_boxes_are_paid_for_from_the_allowance() {
assert!(m.past_allowance, "a byte short, the second description is left unread");
}
/// A glyph description that fails on its own once the allowance is spent to the byte, an empty one
/// behind a filter nothing decodes, fails the same with more left: it doesn't make the metrics read
/// past the allowance, and the descriptions after it are read, or refused by the allowance.
#[test]
fn a_type3_description_unread_on_its_own_is_not_past_the_allowance() {
let mut doc = Document::new_empty();
let procs = ["1 0 0 -20 1 300 d1", "", "1 0 0 0 1 400 d1"];
let mut f = type3(&mut doc, [1.0, 0.0, 0.0, 1.0, 0.0, 0.0], [0, 0, 0, 0], &procs);
let mut dict = Dict::new();
dict.set(b"Filter".to_vec(), Object::name("NoSuchFilter"));
let unread = Object::Ref(doc.add(Object::Stream(Stream::from_raw(dict, Vec::new()))));
let Some(Object::Dict(mut charprocs)) = f.get(b"CharProcs").cloned() else { panic!("CharProcs") };
charprocs.set(b"g1".to_vec(), unread);
f.set(b"CharProcs".to_vec(), Object::Dict(charprocs));
with_differences(&mut f, &["g0", "g1", "g2"].map(String::from));
let first = procs[0].len();
let whole = Metrics::from_dict_within(&doc, &f, &mut DecodeBudget::new(usize::MAX, 0));
assert!(!whole.past_allowance);
assert_eq!((whole.ascent, whole.descent), (400.0, -20.0));
// The first description spends it to the byte; the third, which has data, is refused.
let mut budget = DecodeBudget::new(first, 0);
let m = Metrics::from_dict_within(&doc, &f, &mut budget);
assert_eq!(budget.refused(), 1);
assert!(m.past_allowance);
// Without the third, nothing is refused, and the metrics aren't past the allowance.
let Some(Object::Dict(mut charprocs)) = f.get(b"CharProcs").cloned() else { panic!("CharProcs") };
charprocs.remove(b"g2");
f.set(b"CharProcs".to_vec(), Object::Dict(charprocs));
let mut budget = DecodeBudget::new(first, 0);
let m = Metrics::from_dict_within(&doc, &f, &mut budget);
assert_eq!((budget.refused(), budget.remaining()), (0, 0));
assert!(!m.past_allowance);
assert_eq!((m.ascent, m.descent), (300.0, -20.0));
}
/// 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]
@@ -1749,6 +1833,16 @@ fn codespaces_are_deduplicated_and_at_most_four_bytes() {
assert_eq!(spaces.len(), 1);
}
#[test]
fn base_font_name_matches_the_metrics_name() {
let doc = Document::new_empty();
let mut f = Dict::new();
f.set(b"BaseFont".to_vec(), Object::name("ABCDEF+Body"));
assert_eq!(base_font_name(&doc, &f), "ABCDEF+Body");
assert_eq!(base_font_name(&doc, &f), Metrics::from_dict(&doc, &f).base_font);
assert_eq!(base_font_name(&doc, &Dict::new()), "");
}
#[test]
fn refused_subset_reads_do_not_encode_unverified_glyphs() {
let mut doc = Document::new_empty();
+15
View File
@@ -128,6 +128,21 @@ fn read(doc: &Document, o: &Object, pages: &[pdfcraft_cos::ObjRef], scripts: &mu
})
}
/// The JavaScript widget annotation `widget` runs for `trigger` (ISO 32000-2 Table 197: `/A`
/// or `/AA /U` for Mouse Up, the other `/AA` entries for the rest): that action's, when it is a
/// JavaScript action, then those of the actions chained after it with `/Next`, in the order
/// they run (bounded as [`crate::document_action_scripts`] is). Reads only the widget's own
/// dictionary, so a pointer moving over a large form costs nothing per field.
pub fn widget_scripts(doc: &Document, widget: pdfcraft_cos::ObjRef, trigger: Trigger) -> Vec<String> {
let w = doc.get(widget);
let Some(wd) = w.as_dict() else { return Vec::new() };
let action = match trigger.key() {
None => wd.get(b"A").cloned().or_else(|| wd.get(b"AA").map(|a| doc.resolve(a)).and_then(|a| a.as_dict()?.get(b"U").cloned())),
Some(k) => wd.get(b"AA").map(|a| doc.resolve(a)).and_then(|a| a.as_dict()?.get(k).cloned()),
};
crate::scripting::chained_scripts(doc, action)
}
/// The actions of field `name` (its first widget), by trigger, in the tab's order.
pub fn field_actions(doc: &Document, name: &str) -> Result<Vec<(Trigger, FieldAction)>, FormError> {
let all = fields(doc);
+17 -1
View File
@@ -262,10 +262,26 @@ pub fn delete_widget(doc: &mut Document, name: &str, widget: usize) -> Result<()
fn delete_found_field(doc: &mut Document, f: Field) -> Result<(), FormError> {
let widgets: std::collections::HashSet<ObjRef> = f.widgets.iter().map(|w| w.obj).collect();
drop_from_pages(doc, &widgets)?;
let mut parent = doc.get(f.obj).as_dict().and_then(|d| d.reference(b"Parent"));
detach(doc, f.obj)?;
// Out of the calculation order too: a `/CO` entry would keep the field, its value and its
// widgets reachable for a full save.
drop_from_calculation_order(doc, |r| r == f.obj || widgets.contains(&r))
drop_from_calculation_order(doc, |r| r == f.obj || widgets.contains(&r))?;
// An ancestor left with no kids would become a field of its own, and keep the `/V` and `/DV`
// the deleted field inherited from it: it goes too, up the chain.
let mut gone = std::collections::HashSet::new();
while let Some(p) = parent.filter(|p| gone.len() < 64 && !gone.contains(p)) {
let Some(d) = doc.get(p).as_dict().cloned() else { break };
let empty = d.get(b"Kids").map(|o| doc.resolve(o)).and_then(|o| o.as_array().map(Vec::is_empty)) == Some(true);
if !empty {
break;
}
parent = d.reference(b"Parent");
gone.insert(p);
drop_from_pages(doc, &std::iter::once(p).collect())?;
detach(doc, p)?;
}
drop_from_calculation_order(doc, |r| gone.contains(&r))
}
/// Take the annotations `widgets` off every page's `/Annots`, held directly or by reference.
+3 -3
View File
@@ -24,15 +24,15 @@ mod calc_order;
pub mod detect;
mod scripting;
pub mod table;
pub use actions::{FieldAction, Trigger, field_action_chains, field_actions, set_field_actions};
pub use actions::{FieldAction, Trigger, field_action_chains, field_actions, set_field_actions, widget_scripts};
pub use author::{
BorderStyle, CheckStyle, FieldFont, FieldProps, Look, LookPatch, MIN_FIELD_SIDE, NewField, add_field, check_style, delete_field,
delete_field_object, delete_widget, duplicate_field, look, redraw_field, redraw_fields, set_button_icon, set_button_icon_target, set_props,
};
pub use calc_order::{CalculatedField, CalculationIssue, CalculationOrder, calculation_order, set_calculation_order};
pub use scripting::{
FieldChange, FieldEvent, NoScripts, ScriptResult, Scripts, apply_script_changes, document_scripts, document_scripts_named, set_document_script,
set_field_script,
DocumentTrigger, FieldChange, FieldEvent, NoScripts, ScriptResult, Scripts, apply_script_changes, document_action_scripts, document_scripts,
document_scripts_named, set_document_script, set_field_script,
};
mod appearances;
+164 -1
View File
@@ -57,6 +57,11 @@ pub struct FieldChange {
pub border_style: Option<String>,
pub user_name: Option<String>,
pub icon: Option<Option<u64>>,
/// A combo box's or list box's new items (export value, text), from `setItems`.
pub options: Option<Vec<(String, String)>>,
/// JavaScript actions the script installed with `setAction`, by trigger name (`MouseUp`,
/// `OnFocus`, `Keystroke`, …), each replacing what the field ran for that trigger.
pub actions: Vec<(String, String)>,
}
/// What a script did.
@@ -171,6 +176,73 @@ fn protect_other_mk_owners(doc: &mut Document, field: &Field, owners: &std::coll
Ok(())
}
/// Most items a script may give a choice field ([`FieldChange::options`]).
const MAX_SCRIPT_OPTIONS: usize = 10_000;
/// Write a combo box's or list box's items (export value, text) as its `/Opt`: a plain text
/// where the two are the same, a pair where they differ (ISO 32000-2 Table 231). The selected
/// indices (`/I`) no longer apply and go; the value is written after, and the field redrawn.
fn write_options(doc: &mut Document, f: &Field, options: &[(String, String)]) -> Result<(), FormError> {
if !matches!(f.kind, FieldKind::Combo | FieldKind::List) {
return Err(FormError::Invalid(format!("{} is not a combo box or list box: it has no items to set", f.name)));
}
if options.len() > MAX_SCRIPT_OPTIONS {
return Err(FormError::Invalid(format!("a script may give a field at most {MAX_SCRIPT_OPTIONS} items")));
}
let opt = options
.iter()
.map(|(export, text)| {
if export == text {
Object::String(PdfString::text(text))
} else {
Object::Array(vec![Object::String(PdfString::text(export)), Object::String(PdfString::text(text))])
}
})
.collect();
doc.update_dict(f.obj, |d| {
d.set(b"Opt".to_vec(), Object::Array(opt));
d.remove(b"I");
})?;
crate::author::redraw_field_object(doc, &f.name, f.obj)
}
/// Install `script` as field `f`'s JavaScript for `trigger` (a `setAction` trigger name),
/// replacing the action it had there: the field's `/AA` for Keystroke, Validate, Calculate and
/// Format, each widget's `/A` (Mouse Up) or `/AA` for the rest.
fn set_action(doc: &mut Document, f: &Field, trigger: &str, script: &str) -> Result<(), FormError> {
let event = match trigger {
"Keystroke" => Some("keystroke"),
"Validate" => Some("validate"),
"Calculate" => Some("calculate"),
"Format" => Some("format"),
"MouseUp" => Some("mouse_up"),
_ => None,
};
if let Some(event) = event {
// The field the script's object stands for, even when another shares its name.
return set_script_of(doc, f, event, Some(script));
}
let key: &[u8] = match trigger {
"MouseDown" => b"D",
"MouseEnter" => b"E",
"MouseExit" => b"X",
"OnFocus" => b"Fo",
"OnBlur" => b"Bl",
other => return Err(FormError::Invalid(format!("unknown action trigger {other:?}"))),
};
let mut action = pdfcraft_cos::Dict::new();
action.set(b"S".to_vec(), Object::name("JavaScript"));
action.set(b"JS".to_vec(), PdfString::text(script));
let action = doc.add(Object::Dict(action));
for w in &f.widgets {
let mut aa =
doc.get(w.obj).as_dict().and_then(|d| d.get(b"AA").map(|a| doc.resolve(a))).and_then(|a| a.as_dict().cloned()).unwrap_or_default();
aa.set(key.to_vec(), Object::Ref(action));
doc.update_dict(w.obj, |d| d.set(b"AA".to_vec(), Object::Dict(aa)))?;
}
Ok(())
}
/// [`formatted`] with dates in English names, for widgets whose fonts can't draw the date
/// language's; `None` when the field has no Format script or the English run didn't happen.
pub(crate) fn formatted_in_english(doc: &Document, f: &Field, value: &str, scripts: &mut dyn Scripts) -> Option<String> {
@@ -211,6 +283,19 @@ pub(crate) fn apply_changes(
for c in changes {
let Some(f) = all.iter().find(|f| f.name == c.name && c.object.is_none_or(|obj| f.obj == obj)) else { continue };
// New items go first, so a value among them is written against them.
let reread;
let f = match &c.options {
Some(options) => {
write_options(doc, f, options)?;
reread = fields(doc).into_iter().find(|x| x.obj == f.obj).unwrap_or_else(|| f.clone());
&reread
}
None => f,
};
for (trigger, script) in &c.actions {
set_action(doc, f, trigger, script)?;
}
if let Some(v) = &c.value
&& !except_object.map_or(c.name == except, |obj| f.obj == obj)
&& *v != f.value
@@ -454,6 +539,79 @@ pub fn document_scripts_named(doc: &Document) -> Vec<(String, String)> {
out
}
/// A document-level action trigger whose JavaScript the viewer runs (ISO 32000-2 §12.6.3,
/// Table 199): the catalog's `/OpenAction`, or its `/AA` entries.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DocumentTrigger {
/// The catalog `/OpenAction`, once the document has opened.
Open,
/// `/AA /WS`, before the document is saved.
WillSave,
/// `/AA /WP`, before the document is printed.
WillPrint,
}
/// Most actions read for one document trigger, along its `/Next` chain. A chain can be cyclic
/// or arbitrarily long; the rest are ignored.
const MAX_CHAINED_ACTIONS: usize = 256;
/// The JavaScript of the catalog actions for `trigger`, in the order a viewer runs them: the
/// action, then its `/Next` actions depth first (§12.6.2). Actions of other types (a `/GoTo`
/// open action, say) are skipped; their `/Next` chains are still followed. Bounded: each object
/// is read once and at most [`MAX_CHAINED_ACTIONS`] actions are visited.
pub fn document_action_scripts(doc: &Document, trigger: DocumentTrigger) -> Vec<String> {
let Some(root) = doc.root() else { return Vec::new() };
let cat = doc.get(root);
let Some(cat) = cat.as_dict() else { return Vec::new() };
let first = match trigger {
DocumentTrigger::Open => cat.get(b"OpenAction").cloned(),
DocumentTrigger::WillSave | DocumentTrigger::WillPrint => {
let key: &[u8] = if trigger == DocumentTrigger::WillSave { b"WS" } else { b"WP" };
cat.get(b"AA").map(|a| doc.resolve(a)).and_then(|a| a.as_dict().and_then(|d| d.get(key)).cloned())
}
};
chained_scripts(doc, first)
}
/// The JavaScript of action `first` and of the actions chained after it, in the order they run:
/// the action, then its `/Next` actions depth first (ISO 32000-2 §12.6.2). Actions of other
/// types are skipped; their `/Next` chains are still followed. Bounded: each object is read
/// once and at most [`MAX_CHAINED_ACTIONS`] actions are visited.
pub(crate) fn chained_scripts(doc: &Document, first: Option<Object>) -> Vec<String> {
let mut budget = crate::script_budget();
let mut seen: HashSet<u32> = HashSet::new();
let mut pending: Vec<Object> = first.into_iter().collect();
let mut visited = 0usize;
let mut out = Vec::new();
while let Some(raw) = pending.pop() {
visited += 1;
if visited > MAX_CHAINED_ACTIONS {
break;
}
if let Some(r) = raw.as_ref()
&& !seen.insert(r.num)
{
continue;
}
let action = doc.resolve(&raw);
if let Some(list) = action.as_array() {
// Pushed in reverse so they run in the order listed.
pending.extend(list.iter().take(MAX_CHAINED_ACTIONS).rev().cloned());
continue;
}
let Some(d) = action.as_dict() else { continue };
if d.name(b"S") == Some(b"JavaScript".as_slice())
&& let Some(js) = crate::script(doc, &raw, &mut budget)
{
out.push(js);
}
if let Some(next) = d.get(b"Next") {
pending.push(next.clone());
}
}
out
}
/// Call `f` on the array `o` is, or refers to, read in place: resolving a direct array would
/// copy it.
fn in_array(doc: &Document, o: &Object, f: impl FnOnce(&[Object])) {
@@ -511,7 +669,12 @@ pub fn set_document_script(doc: &mut Document, name: &str, js: Option<&str>) ->
/// (its widgets' `/A`). Calculated fields join the calculation order (`/CO`).
pub fn set_field_script(doc: &mut Document, name: &str, event: &str, js: Option<&str>) -> Result<(), FormError> {
let all = fields(doc);
let f = all.iter().find(|f| f.name == name).ok_or_else(|| FormError::NoSuchField(name.into()))?.clone();
let f = all.iter().find(|f| f.name == name).ok_or_else(|| FormError::NoSuchField(name.into()))?;
set_script_of(doc, f, event, js)
}
/// [`set_field_script`] for the field `f` itself, which may share its name with another.
fn set_script_of(doc: &mut Document, f: &Field, event: &str, js: Option<&str>) -> Result<(), FormError> {
let action = |doc: &mut Document, js: &str| {
let mut a = pdfcraft_cos::Dict::new();
a.set(b"S".to_vec(), Object::name("JavaScript"));
+94
View File
@@ -1664,6 +1664,38 @@ fn properties_rename_and_delete() {
assert_eq!(annots.as_array().unwrap().len(), 13 - 3, "the deleted widgets left the page");
}
/// A deleted field's ancestor left with no kids stays in `/Fields` as a field of its own, with the
/// `/V` the deleted field inherited from it: it leaves too. An ancestor a sibling still has stays.
#[test]
fn deleting_the_last_kid_removes_the_emptied_ancestors_and_their_values() {
let form = |kids: &str, annots: &str| {
document(&[
"<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(),
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(),
format!("<< /Type /Page /Parent 2 0 R /Annots [{annots}] >>"),
"<< /Fields [5 0 R] >>".into(),
"<< /FT /Tx /T (outer) /V (SECRET) /DV (SECRET) /Kids [6 0 R] >>".into(),
format!("<< /T (inner) /Parent 5 0 R /Kids [{kids}] >>"),
"<< /Type /Annot /Subtype /Widget /T (a) /Parent 6 0 R /Rect [50 700 250 720] /P 3 0 R >>".into(),
"<< /Type /Annot /Subtype /Widget /T (b) /Parent 6 0 R /Rect [50 650 250 670] /P 3 0 R >>".into(),
])
};
let top = |doc: &Document| {
let af = doc.get(doc.root().unwrap()).as_dict().unwrap().get(b"AcroForm").map(|o| doc.resolve(o)).unwrap().as_dict().unwrap().clone();
doc.resolve(af.get(b"Fields").unwrap()).as_array().unwrap().len()
};
let mut doc = form("7 0 R", "7 0 R");
delete_field(&mut doc, "outer.inner.a").unwrap();
assert_eq!(top(&doc), 0, "the emptied ancestors left /Fields");
let saved = pdfcraft_cos::write_full(&doc, &SaveOptions::default()).unwrap();
assert!(!saved.windows(6).any(|w| w == b"SECRET"), "the inherited value is gone from a full save");
let mut doc = form("7 0 R 8 0 R", "7 0 R 8 0 R");
delete_field(&mut doc, "outer.inner.a").unwrap();
assert_eq!(top(&doc), 1, "an ancestor with a surviving kid stays");
assert!(fields(&doc).iter().any(|f| f.name == "outer.inner.b"));
}
/// A parent `MASTER` with kids `a` and `b` (each a field merged with its widget) and `e` (a field
/// with two widget kids), and the top-level fields `c` and `d`.
fn dotted_form() -> Document {
@@ -6770,6 +6802,48 @@ fn locked_button_export_edits_leave_the_document_unchanged() {
}
}
/// A radio button that is read-only on its own (its own `/Ff`) can't be picked, and a selected one
/// can't be switched away from, though the group as a whole is writable.
#[test]
fn a_read_only_radio_button_is_neither_picked_nor_left() {
let lock = |doc: &mut Document, num: u32| doc.update_dict(pdfcraft_cos::ObjRef::new(num, 0), |d| d.set(b"Ff".to_vec(), Object::Int(1))).unwrap();
let mut doc = radio_group_form();
lock(&mut doc, 7); // Medium
assert!(matches!(set_value(&mut doc, "size", &FieldValue::Radio(Some("M".into()))), Err(FormError::ReadOnly(_))));
set_value(&mut doc, "size", &FieldValue::Radio(Some("L".into()))).expect("an unlocked button is picked");
// Small (selected) locked: the group stays on it.
let mut doc = radio_group_form();
lock(&mut doc, 6);
assert!(matches!(set_value(&mut doc, "size", &FieldValue::Radio(Some("L".into()))), Err(FormError::ReadOnly(_))));
assert_eq!(field(&fields(&doc), "size").value, ["S"]);
}
/// The group's `/V` names its selection even when the button's `/AS` says nothing: a read-only
/// button that `/V` selects is not switched away from either.
#[test]
fn a_read_only_radio_button_selected_by_the_group_value_is_not_left() {
let mut doc = radio_group_form();
doc.update_dict(pdfcraft_cos::ObjRef::new(6, 0), |d| {
d.set(b"Ff".to_vec(), Object::Int(1));
d.set(b"AS".to_vec(), Object::name("Off"));
})
.unwrap();
assert!(matches!(set_value(&mut doc, "size", &FieldValue::Radio(Some("L".into()))), Err(FormError::ReadOnly(_))));
assert_eq!(field(&fields(&doc), "size").value, ["S"]);
}
/// Clearing the form skips a group held by a read-only button and still clears the rest.
#[test]
fn clearing_the_form_goes_on_past_a_group_held_by_a_read_only_button() {
let mut doc = radio_group_form();
doc.update_dict(pdfcraft_cos::ObjRef::new(6, 0), |d| d.set(b"Ff".to_vec(), Object::Int(1))).unwrap();
doc.update_dict(pdfcraft_cos::ObjRef::new(9, 0), |d| d.set(b"DV".to_vec(), pdfcraft_cos::PdfString::text("Bob"))).unwrap();
assert_eq!(reset(&mut doc, None).unwrap(), 1);
let all = fields(&doc);
assert_eq!(field(&all, "size").value, ["S"]);
assert_eq!(field(&all, "name").value, ["Bob"]);
}
#[test]
/// Cosmetic field updates skip calculations, while a value write still triggers the chain.
fn script_cosmetic_mutations_do_not_run_the_calculation_chain() {
@@ -6905,6 +6979,26 @@ fn radio_buttons_without_as_sharing_the_value_show_one_on() {
assert_eq!(on_widgets(&doc, "r").0, [false, true, false]);
}
/// Two buttons share the on state `Yes`; the first is on by its `/AS` and the second is read-only
/// and off. `/V` is `Yes` for both, but only the first is selected: picking another option switches
/// the first off, which is allowed, and the read-only one never changes.
#[test]
fn a_read_only_button_sharing_the_on_state_of_the_selected_one_does_not_block() {
let mut doc = radio_without_as(49152, "/Ff 1 /AS /Off");
doc.update_dict(pdfcraft_cos::ObjRef::new(6, 0), |d| d.set(b"AS".to_vec(), Object::name("Yes"))).unwrap();
set_value(&mut doc, "r", &FieldValue::Radio(Some("No".into()))).expect("the writable selected button may be switched off");
assert_eq!(on_widgets(&doc, "r").0, [false, false, true]);
}
/// Selecting another button through `FieldValue::Widget` can't switch a read-only selected one off.
#[test]
fn a_read_only_selected_radio_button_is_not_left_by_picking_a_widget() {
let mut doc = radio_group_form();
doc.update_dict(pdfcraft_cos::ObjRef::new(6, 0), |d| d.set(b"Ff".to_vec(), Object::Int(1))).unwrap();
assert!(matches!(set_value(&mut doc, "size", &FieldValue::Widget(2)), Err(FormError::ReadOnly(_))));
assert_eq!(field(&fields(&doc), "size").value, ["S"]);
}
/// Table 227, ReadOnly: a processor "shall not allow a user to change the value". A button whose own
/// dictionary sets it can't be turned on by number.
#[test]
+55 -10
View File
@@ -356,6 +356,9 @@ fn write_value_impl(doc: &mut Document, f: &Field, value: &FieldValue, scripts:
let Some(state) = f.widgets.get(*i).and_then(|w| w.on_state.clone()) else {
return invalid(format!("{:?} has no button {} with an on state", f.name, i.saturating_add(1)));
};
if f.kind == FieldKind::Radio && radio_change_blocked(f, Some(&state), Some(*i)) {
return Err(FormError::ReadOnly(f.name.clone()));
}
set_states(doc, f, Some(&state), Some(*i))
}
(FieldKind::CheckBox, v) => {
@@ -406,6 +409,9 @@ fn write_value_impl(doc: &mut Document, f: &Field, value: &FieldValue, scripts:
if choice.is_none() && f.has(flags::NO_TOGGLE_TO_OFF) && !f.value.is_empty() {
return invalid(format!("{:?} must keep one option selected", f.name));
}
if radio_change_blocked(f, choice.as_deref(), None) {
return Err(FormError::ReadOnly(f.name.clone()));
}
set_states(doc, f, choice.as_deref(), None)
}
(FieldKind::Combo | FieldKind::List, FieldValue::Choice(_) | FieldValue::Text(_) | FieldValue::ChoiceIndices(_)) => {
@@ -541,17 +547,49 @@ pub(crate) fn scroll_widgets(doc: &mut Document, f: &Field, picked: &[usize], co
Ok(())
}
/// The one widget of an exclusive radio group that turns on when `on` is chosen (`pick` when it has
/// that state, else the one already on, else the first); `None` when `on` is `None` or the group
/// turns every widget with that state on together.
fn chosen_widget(f: &Field, on: Option<&str>, pick: Option<usize>) -> Option<usize> {
let exclusive = f.kind == FieldKind::Radio && !f.has(flags::RADIOS_IN_UNISON);
on.filter(|_| exclusive).and_then(|c| {
let has = |i: &usize| f.widgets.get(*i).is_some_and(|w| w.on_state.as_deref() == Some(c));
let n = f.widgets.len();
pick.filter(has).or_else(|| (0..n).filter(has).find(|&i| f.widget_on(i))).or_else(|| (0..n).find(has))
})
}
/// Whether setting a radio group to `on` (through widget `pick`, when the caller chose a widget)
/// would turn a read-only button on or off: such a button can't be picked, and a selected one can't
/// be switched off by picking another. Judged per widget, by the state `set_states` would give it,
/// so buttons sharing an on-state name are told apart by their `/AS`; the group's `/V` stands for
/// the selection only when no button's `/AS` says which is on.
fn radio_change_blocked(f: &Field, on: Option<&str>, pick: Option<usize>) -> bool {
let chosen = chosen_widget(f, on, pick);
let before = |i: usize, w: &Widget| {
let Some(s) = w.on_state.as_deref() else { return false };
if f.widget_on(i) {
return true;
}
// No button sharing this on state is on by its `/AS` and the group's `/V` names it: the
// first of them holds the selection, whatever its own `/AS` says (an `Off` among them).
let sharing = |x: &Widget| x.on_state.as_deref() == Some(s);
f.value.first().map(String::as_str) == Some(s)
&& !f.widgets.iter().any(|x| sharing(x) && x.state.as_deref() == Some(s))
&& f.widgets.iter().position(sharing) == Some(i)
};
f.widgets.iter().enumerate().any(|(i, w)| {
let after = on.is_some() && w.on_state.as_deref() == on && chosen.is_none_or(|k| k == i);
w.read_only && before(i, w) != after
})
}
/// Check boxes and radio buttons: `/V` on the field, `/AS` on each widget. The widgets whose on
/// state is `on` turn on together in a check box (ISO 32000-2 §12.7.5.2.3, EXAMPLE 2) and in a
/// radio group with RadiosInUnison. Without it, at most one radio button is on (Table 229,
/// §12.7.5.2.3): widget `pick` when it has that state, else the one already on, else the first.
fn set_states(doc: &mut Document, f: &Field, on: Option<&str>, pick: Option<usize>) -> Result<(), FormError> {
let exclusive = f.kind == FieldKind::Radio && !f.has(flags::RADIOS_IN_UNISON);
let chosen = on.filter(|_| exclusive).and_then(|c| {
let has = |i: &usize| f.widgets.get(*i).is_some_and(|w| w.on_state.as_deref() == Some(c));
let n = f.widgets.len();
pick.filter(has).or_else(|| (0..n).filter(has).find(|&i| f.widget_on(i))).or_else(|| (0..n).find(has))
});
let chosen = chosen_widget(f, on, pick);
// `/V` names the on state, the same for every widget that has it: which of them is on is
// their `/AS` alone (§12.7.5.2.4).
let v = on.unwrap_or("Off");
@@ -919,10 +957,17 @@ pub fn reset_with_formatting(
// A reset is not blocked by NoToggleToOff: go through the writer directly.
let mut tmp = f.clone();
tmp.flags &= !flags::NO_TOGGLE_TO_OFF;
write_value_impl(doc, &tmp, &v, scripts, true)?;
changed += 1;
if matches!(f.kind, FieldKind::Text | FieldKind::Combo | FieldKind::List) {
redraw_fields.insert(f.obj);
match write_value_impl(doc, &tmp, &v, scripts, true) {
Ok(()) => {
changed += 1;
if matches!(f.kind, FieldKind::Text | FieldKind::Combo | FieldKind::List) {
redraw_fields.insert(f.obj);
}
}
// a read-only button of the group holds the value: this field is left as it is, and the
// rest of the form is still cleared
Err(FormError::ReadOnly(_)) => {}
Err(e) => return Err(e),
}
}
let calculation_runner: &mut dyn Scripts = if calculate_with_scripts { scripts } else { &mut NoScripts };
+74
View File
@@ -279,7 +279,71 @@ fn field_object_new(ctx: &mut Context, name: &str, id: Option<u64>, token: u64)
Ok(JsValue::undefined())
}
/// `setAction(cTrigger, cScript)`: install `cScript` as the field's JavaScript for
/// `cTrigger`, replacing what it ran before; saved with the document (#269).
fn set_action(_: &JsValue, args: &[JsValue], name: &FieldKey, c: &mut Context) -> JsResult<JsValue> {
let trigger = text(&arg(args, 0), c)?;
if !SET_ACTION_TRIGGERS.contains(&trigger.as_str()) {
return Err(error(format!("setAction: unknown trigger {trigger:?}; use one of {}", SET_ACTION_TRIGGERS.join(", "))));
}
let script = text(&arg(args, 1), c)?;
if let Some(why) = crate::run::refuse(&script) {
return Err(error(format!("setAction: {why}")));
}
write(c, name, |f| {
f.actions.retain(|(t, _)| *t != trigger);
f.actions.push((trigger, script));
})?;
Ok(JsValue::undefined())
}
/// `setItems(oArray)`: replace a combo box's or list box's items. Each item is its text, or
/// a `[text, exportValue]` pair. The value stays when an item still has it, and otherwise
/// becomes the first item's (#269).
fn set_items(_: &JsValue, args: &[JsValue], name: &FieldKey, c: &mut Context) -> JsResult<JsValue> {
let f = read(c, name)?;
if !matches!(f.kind, FieldType::ComboBox | FieldType::ListBox) {
return Err(error(format!("setItems: {} is not a combo box or list box", f.name)));
}
let list = arg(args, 0).as_object().filter(JsObject::is_array).ok_or_else(|| error("setItems needs an array of items"))?;
let list = JsArray::from_object(list)?;
let len = list.length(c)?;
if len > MAX_ITEMS as u64 {
return Err(error(format!("setItems: at most {MAX_ITEMS} items")));
}
let mut items = Vec::new();
let mut bytes = 0usize;
for i in 0..len {
let item = list.get(i, c)?;
let (label, export) = match item.as_object().filter(JsObject::is_array) {
Some(pair) => {
let pair = JsArray::from_object(pair.clone())?;
let label = text(&pair.get(0, c)?, c)?;
let export = pair.get(1, c)?;
let export = if export.is_undefined() { label.clone() } else { text(&export, c)? };
(label, export)
}
None => {
let label = text(&item, c)?;
(label.clone(), label)
}
};
bytes = bytes.saturating_add(label.len()).saturating_add(export.len());
if bytes > MAX_ITEM_BYTES {
return Err(error("setItems: the items are too long"));
}
items.push((export, label));
}
write(c, name, |f| {
let kept: Vec<String> = f.value.iter().filter(|v| items.iter().any(|(export, _)| export == *v)).cloned().collect();
f.value = if kept.is_empty() { items.first().map(|(export, _)| vec![export.clone()]).unwrap_or_default() } else { kept };
f.options = items;
})?;
Ok(JsValue::undefined())
}
let rw = Attribute::CONFIGURABLE | Attribute::ENUMERABLE;
let set_action = NativeFunction::from_copy_closure_with_captures(set_action, n.clone());
let set_items = NativeFunction::from_copy_closure_with_captures(set_items, n.clone());
let get_item_at = NativeFunction::from_copy_closure_with_captures(get_item_at, n.clone());
let is_box_checked = NativeFunction::from_copy_closure_with_captures(is_box_checked, n.clone());
let check_this_box = NativeFunction::from_copy_closure_with_captures(check_this_box, n.clone());
@@ -314,6 +378,8 @@ fn field_object_new(ctx: &mut Context, name: &str, id: Option<u64>, token: u64)
.function(is_box_checked, js_string!("isBoxChecked"), 1)
.function(check_this_box, js_string!("checkThisBox"), 2)
.function(set_focus, js_string!("setFocus"), 0)
.function(set_action, js_string!("setAction"), 2)
.function(set_items, js_string!("setItems"), 1)
.function(button_get_icon, js_string!("buttonGetIcon"), 1)
.function(button_set_icon, js_string!("buttonSetIcon"), 2)
.function(button_get_caption, js_string!("buttonGetCaption"), 1)
@@ -321,6 +387,14 @@ fn field_object_new(ctx: &mut Context, name: &str, id: Option<u64>, token: u64)
.build()
}
/// The triggers `field.setAction` takes (Acrobat JavaScript reference, Field.setAction).
const SET_ACTION_TRIGGERS: [&str; 10] =
["MouseUp", "MouseDown", "MouseEnter", "MouseExit", "OnFocus", "OnBlur", "Keystroke", "Validate", "Calculate", "Format"];
/// Most items one `setItems` call takes, and most bytes of their texts and export values: a
/// script must not grow a field without bound.
const MAX_ITEMS: usize = 10_000;
const MAX_ITEM_BYTES: usize = 1 << 20;
// ── the document (global object) ────────────────────────────────────────────────────────────
pub(crate) fn get_field(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
+1
View File
@@ -591,6 +591,7 @@ pub(crate) fn install(ctx: &mut Context) -> JsResult<()> {
ctx.register_global_property(js_string!("display"), display, rw)?;
let color = color_object(ctx);
ctx.register_global_property(js_string!("color"), color, rw)?;
crate::source::install(ctx)?;
Ok(())
}
+1
View File
@@ -44,6 +44,7 @@ mod host;
mod model;
mod nesting;
mod run;
mod source;
#[cfg(test)]
pub(crate) use format::PRINTD_SCANNED;
+6
View File
@@ -74,6 +74,11 @@ pub struct FieldState {
pub caption_mixed: bool,
pub icon_mixed: bool,
pub icon_written: bool,
/// JavaScript actions a script installed with `setAction` during this run, by trigger
/// (`MouseUp`, `MouseDown`, `MouseEnter`, `MouseExit`, `OnFocus`, `OnBlur`, `Keystroke`,
/// `Validate`, `Calculate`, `Format`), the last one for each trigger. Empty in a snapshot:
/// the host reads the document's own actions from the PDF.
pub actions: Vec<(String, String)>,
}
impl FieldState {
@@ -108,6 +113,7 @@ impl FieldState {
caption_mixed: false,
icon_mixed: false,
icon_written: false,
actions: Vec::new(),
}
}
+145
View File
@@ -0,0 +1,145 @@
//! `toSource()` on objects and arrays, which older forms use to keep state in a field or a
//! global as text (#269, ported from #344). It writes a JavaScript literal of the value; scripts
//! here can't `eval` it back, since strings never compile. Plain data only: strings, numbers,
//! booleans, null, undefined, arrays and objects of them. Functions and cycles are refused, and
//! so is a value past the depth, size or length bounds, rather than writing something that
//! reads as another value.
use super::host::{error, function, s, text};
use super::{Context, JsArray, JsObject, JsResult, JsValue, NativeFunction, js_string};
use boa_engine::property::{PropertyDescriptor, PropertyKey};
/// Deepest nesting written.
const MAX_DEPTH: usize = 64;
/// Most values (each array item, property and the value itself) written.
const MAX_VALUES: usize = 10_000;
/// Longest source written, in bytes.
const MAX_BYTES: usize = 1 << 20;
/// Install `toSource` on `Object.prototype` (arrays inherit it), not enumerable, as in the
/// engines that had it.
pub(crate) fn install(ctx: &mut Context) -> JsResult<()> {
let to_source = function(ctx, NativeFunction::from_fn_ptr(to_source));
let prototype = ctx.intrinsics().constructors().object().prototype();
prototype
.insert_property(js_string!("toSource"), PropertyDescriptor::builder().value(to_source).writable(true).configurable(true).enumerable(false));
Ok(())
}
fn to_source(this: &JsValue, _: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
let mut writer = Writer { values: MAX_VALUES, bytes: MAX_BYTES, open: Vec::new() };
let out = writer.value(this, ctx)?;
Ok(s(&out))
}
/// What is left of the bounds, and the objects being written (to refuse a cycle).
struct Writer {
values: usize,
bytes: usize,
open: Vec<JsObject>,
}
impl Writer {
fn value(&mut self, v: &JsValue, ctx: &mut Context) -> JsResult<String> {
self.values = self.values.checked_sub(1).ok_or_else(|| error("toSource: the value has too many parts"))?;
let out = if v.is_callable() {
return Err(error("toSource: functions can't be written"));
} else if let Some(o) = v.as_object() {
self.object(&o, ctx)?
} else if let Some(text) = v.as_string() {
quote(&text.to_std_string_escaped())
} else if v.is_null() {
"null".into()
} else if v.is_undefined() {
"undefined".into()
} else {
text(v, ctx)?
};
self.charge(out.len())?;
Ok(out)
}
fn object(&mut self, o: &JsObject, ctx: &mut Context) -> JsResult<String> {
if self.open.iter().any(|open| open == o) {
return Err(error("toSource: the value refers to itself"));
}
if self.open.len() >= MAX_DEPTH {
return Err(error("toSource: the value is nested too deeply"));
}
if !o.is_array() && !plain(o, ctx) {
return Err(error("toSource: only plain objects, arrays, strings, numbers, booleans, null and undefined can be written"));
}
self.open.push(o.clone());
let out = if o.is_array() { self.array(o, ctx) } else { self.fields(o, ctx) };
self.open.pop();
out
}
fn array(&mut self, o: &JsObject, ctx: &mut Context) -> JsResult<String> {
let array = JsArray::from_object(o.clone())?;
let len = array.length(ctx)?;
if len > self.values as u64 {
return Err(error("toSource: the array is too long"));
}
let mut items = Vec::new();
for i in 0..len {
items.push(self.value(&array.get(i, ctx)?, ctx)?);
}
Ok(format!("[{}]", items.join(", ")))
}
fn fields(&mut self, o: &JsObject, ctx: &mut Context) -> JsResult<String> {
let mut items = Vec::new();
for key in o.own_property_keys(ctx)? {
let label = match &key {
PropertyKey::Symbol(_) => continue,
PropertyKey::String(k) => k.to_std_string_escaped(),
PropertyKey::Index(i) => i.get().to_string(),
};
// `"__proto__": v` in a literal sets the prototype rather than an own property.
if label == "__proto__" {
return Err(error("toSource: a property named __proto__ can't be written"));
}
self.charge(label.len())?;
let value = self.value(&o.get(key, ctx)?, ctx)?;
items.push(format!("{}:{value}", quote(&label)));
}
Ok(format!("({{{}}})", items.join(", ")))
}
/// Count `n` bytes against the length bound. Every part counts, including the parts of what
/// is joined later, so a value repeated many times can't build a long result first.
fn charge(&mut self, n: usize) -> JsResult<()> {
self.bytes = self.bytes.checked_sub(n).ok_or_else(|| error("toSource: the result would be too long"))?;
Ok(())
}
}
/// Whether `o` is a plain object: an ordinary one whose prototype is `Object.prototype` (or
/// none), so its own properties are all there is to it. A Date, a RegExp, a boxed value, a
/// proxy or a class instance holds more than a literal of its properties would give back.
fn plain(o: &JsObject, ctx: &Context) -> bool {
let object_prototype = ctx.intrinsics().constructors().object().prototype();
o.is_ordinary() && o.prototype().is_none_or(|p| p == object_prototype)
}
/// `text` as a double-quoted JavaScript string literal.
fn quote(text: &str) -> String {
let mut out = String::with_capacity(text.len() + 2);
out.push('"');
for c in text.chars() {
match c {
'\\' => out.push_str("\\\\"),
'"' => out.push_str("\\\""),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\t' => out.push_str("\\t"),
'\u{2028}' => out.push_str("\\u2028"),
'\u{2029}' => out.push_str("\\u2029"),
c if c.is_control() => out.push_str(&format!("\\u{:04x}", c as u32)),
c => out.push(c),
}
}
out.push('"');
out
}
+73
View File
@@ -2702,3 +2702,76 @@ fn af_simple_calculate_bounds_selector_work_before_expansion() {
run("AFSimple_Calculate('SUM',new Array(4096).fill('n'));", &Event::doc("Console"), &Default::default(), &fields, &[], Default::default());
assert!(out.error.as_deref().is_some_and(|e| e.contains("calculation field lookup exceeds")));
}
/// `toSource` writes plain state as a JavaScript literal of the same value (#269, from #344).
/// Scripts here can't `eval` it back (strings never compile), so the exact text is checked.
#[test]
fn to_source_writes_plain_state_as_a_literal() {
let event = Event::doc("Console");
let out = go(
"var v = {tab: 2, name: 'a \"q\"\\n', on: true, none: null, list: ['qty', null, undefined, 1.5, [3]]}; \
[v.toSource(), [1, 'x'].toSource(), ({}).toSource()].join('|');",
&event,
);
assert_eq!(out.error, None, "{out:?}");
assert_eq!(
out.result.as_deref(),
Some(r#"({"tab":2, "name":"a \"q\"\n", "on":true, "none":null, "list":["qty", null, undefined, 1.5, [3]]})|[1, "x"]|({})"#)
);
assert!(go("Object.keys({}).indexOf('toSource') < 0 && !({}).propertyIsEnumerable('toSource');", &event).result.as_deref() == Some("true"));
}
/// `toSource` refuses what it can't write faithfully or within its bounds, with an error the
/// script can catch.
#[test]
fn to_source_refuses_cycles_functions_and_oversized_state() {
let event = Event::doc("Console");
for (script, expected) in [
("var v = {}; v.v = v; v.toSource();", "refers to itself"),
("({f: function () {}}).toSource();", "functions"),
("var v = []; v.length = 1000000; v.toSource();", "too long"),
("var v = []; for (var i = 0; i < 100; i++) v = [v]; v.toSource();", "nested too deeply"),
("var s = new Array(4097).join('x'); var v = []; for (var i = 0; i < 300; i++) v.push(s); v.toSource();", "too long"),
("({when: new Date(0)}).toSource();", "only plain objects"),
("[/x/].toSource();", "only plain objects"),
("function C() { this.a = 1; } new C().toSource();", "only plain objects"),
("var v = JSON.parse('{\"__proto__\": 1}'); v.toSource();", "__proto__"),
] {
let out = go(script, &event);
assert!(out.error.as_deref().is_some_and(|e| e.contains(expected)), "{script}: {out:?}");
}
let out = go("try { var v = {}; v.v = v; v.toSource(); 'no'; } catch (e) { 'caught'; }", &event);
assert_eq!(out.result.as_deref(), Some("caught"));
}
/// `setItems` replaces a choice field's items (text, or [text, export] pairs), keeping the value
/// when an item still has it; `setAction` records the script for its trigger, the last one
/// winning. Both refuse what they can't do.
#[test]
fn set_items_and_set_action_change_the_field() {
let event = Event::doc("Console");
let out = go(
"var f = getField('size'); f.setItems([['Medium', 'm'], 'Huge', ['Tiny']]); \
f.setAction('OnFocus', 'console.println(1)'); f.setAction('OnFocus', 'console.println(2)'); f.setAction('Keystroke', 'event.rc = true;'); \
[f.numItems, f.getItemAt(1, true), f.getItemAt(2, false), f.value].join('|');",
&event,
);
assert_eq!(out.error, None, "{out:?}");
assert_eq!(out.result.as_deref(), Some("3|Huge|Tiny|m"));
let size = out.changed.iter().find(|f| f.name == "size").unwrap();
assert_eq!(size.options, [("m".into(), "Medium".into()), ("Huge".into(), "Huge".into()), ("Tiny".into(), "Tiny".into())]);
assert_eq!(size.actions, [("OnFocus".into(), "console.println(2)".into()), ("Keystroke".into(), "event.rc = true;".into())]);
let out = go("var f = getField('size'); f.setItems(['a', 'b']); f.value;", &event);
assert_eq!(out.result.as_deref(), Some("a"), "the old value is gone: the first item's");
for (script, expected) in [
("getField('price').setItems(['a']);", "not a combo box or list box"),
("getField('size').setItems('a');", "needs an array"),
("var a = []; a.length = 20000; getField('size').setItems(a);", "at most"),
("getField('size').setAction('Explode', 'x');", "unknown trigger"),
] {
let out = go(script, &event);
assert!(out.error.as_deref().is_some_and(|e| e.contains(expected)), "{script}: {out:?}");
}
}
+22 -8
View File
@@ -32,10 +32,15 @@ let report = optimize_with_progress(&mut doc, &settings, &mut |stage| keep_going
damaged partway, which may draw an image larger past the damage), no image is resampled. Colour and grayscale images above a
threshold are resampled with a bicubic (Catmull-Rom) filter to a target resolution and
stored as JPEG (Acrobat's quality steps) or ZIP; soft masks are resampled with their image. A
stencil `/Mask` has its own resolution, so the picture changes under it and it stays as it is.
An image is replaced only if the result is smaller. Images over 80 million pixels are left
alone by the image steps, here and below, whatever their settings (memory); Clean Up may still
Flate an unfiltered or LZW one. Left alone by these colour and grey
stencil `/Mask` has its own resolution, so the picture changes under it and it keeps its size and
its bits (stored again as a picture's mask, below).
An image is replaced only if the result is smaller. Images over 80 million pixels are left alone
by the image steps, here and below, whatever their settings (memory), except that the monochrome
step below takes an image already of one bit a pixel, a mask included, while its rows hold no more
bytes than 80 million pixels of eight bits (each row starts on a new byte: a byte for each 8
samples and one for any left over): up to 640 million pixels when it is wide, and a strip one
sample wide no taller than one of eight bits. Clean Up may still Flate an unfiltered or LZW one.
Left alone by these colour and grey
settings: CMYK and other colour spaces, image masks, colour-key masks, decode arrays, more than 8 bits, JPEG 2000,
JBIG2 and CCITT (black-and-white images, CCITT and JBIG2 among them, are below). A JPEG is read with
its colour transform (an Adobe marker's, else `/ColorTransform`, ISO 32000-2 §7.4.8), so one
@@ -108,10 +113,19 @@ let report = optimize_with_progress(&mut doc, &settings, &mut |stage| keep_going
- Apart from the downsampling it is lossless: the samples keep their meaning, so the colour
space, decode array and `/Mask` stay, but for packed RGB, which becomes grey with one decode
pair. Group 4 wins on scans, whose ragged edges defeat Flate; on clean computer-drawn 1-bit
art Flate can be smaller. Not yet: inline images, an image's own `/SMask` or `/Mask`
image (only images drawn on a page are visited), Group 4 for rows wider than 32,767
samples, and JBIG2 past 65,535 samples on a side, where the decoder stops (its 2^28 in all
is past the 80 million pixels above).
art Flate can be smaller.
- **A picture's masks:** after the pictures, each picture's stencil `/Mask` and one-bit
`/SMask` (a picture's own images, which the pages don't draw by name), once however many
pictures name it, is stored again as the compression asks when that is smaller, at its size:
its bits stay as they are, so it masks as it did. A stencil the pages also draw by name is one
of the images above; a soft mask they draw is still stored as a mask. It isn't resampled, as its resolution isn't measured (the walk measures the
picture's), and it shares no JBIG2 dictionary, as only images named directly do. A soft mask of
more bits stays as it is, to be resampled with its picture, which wants it at eight. The report
counts masks as images.
- Not yet: inline images, a picture's mask resampled, or packed to one bit from more, Group 4
for rows wider than 32,767 samples, and JBIG2 past 65,535 samples on a side or 2^28 in all,
where the decoder stops: with JBIG2 chosen, a one-bit image larger than that stays unless
it is averaged.
- Lossless JBIG2 uses bounded generic-region encoding or exact-copy symbol dictionaries when
smaller, a dictionary shared by up to 16 images when that is smaller still. No lossy symbol substitution is used. Export, redaction and this step read JBIG2
+21 -10
View File
@@ -9,7 +9,7 @@
use std::collections::{HashMap, HashSet};
use pdfcraft_cos::{Dict, Document, MAX_DECODED, Object, XrefEntry};
use pdfcraft_cos::{Dict, Document, MAX_DECODED, ObjRef, Object, XrefEntry};
/// The categories, in Acrobat's order.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
@@ -91,6 +91,9 @@ const MAX_FORM_DEPTH: usize = 64;
struct Audit<'a> {
doc: &'a Document,
owner: HashMap<u32, SpaceCategory>,
/// Resource dictionaries (by reference) already walked: one shared by many pages, forms or
/// appearances is walked once, as claiming is the same each time.
walked: HashSet<ObjRef>,
}
impl Audit<'_> {
@@ -124,6 +127,18 @@ impl Audit<'_> {
o.map(|x| self.doc.resolve(x)).and_then(|x| x.as_dict().cloned()).unwrap_or_default()
}
/// The resource dictionary `holder` points at (if it does), by kind: [`Self::resources`],
/// once per dictionary given by reference.
fn resources_of(&mut self, holder: Option<&Object>, depth: usize) {
if let Some(Object::Ref(r)) = holder
&& !self.walked.insert(*r)
{
return;
}
let res = self.resolve_dict(holder);
self.resources(&res, depth);
}
/// A resource dictionary, by kind; `depth` counts the form XObjects it is nested in.
fn resources(&mut self, res: &Dict, depth: usize) {
let xobjects = self.resolve_dict(res.get(b"XObject"));
@@ -135,8 +150,7 @@ impl Audit<'_> {
// A form: its own resources first, by kind, then the rest of it. Owning it
// first stops a form that draws itself.
self.owner.insert(r.num, SpaceCategory::XObjectForms);
let inner = self.resolve_dict(s.dict.get(b"Resources"));
self.resources(&inner, depth + 1);
self.resources_of(s.dict.get(b"Resources"), depth + 1);
self.claim(&Object::Dict(s.dict.clone()), SpaceCategory::XObjectForms);
}
_ => self.claim(x, SpaceCategory::XObjectForms),
@@ -172,8 +186,7 @@ impl Audit<'_> {
_ => Vec::new(),
};
for dict in streams {
let res = self.resolve_dict(dict.get(b"Resources"));
self.resources(&res, 1);
self.resources_of(dict.get(b"Resources"), 1);
}
}
}
@@ -216,19 +229,17 @@ fn object_stream(doc: &Document, num: u32) -> Option<u32> {
/// Audit the space a document uses; `file_len` is the size of the file on disk (the rest is
/// overhead).
pub fn audit_space(doc: &Document, file_len: u64) -> Vec<SpaceUse> {
let mut a = Audit { doc, owner: HashMap::new() };
let mut a = Audit { doc, owner: HashMap::new(), walked: HashSet::new() };
let cat = doc.root().and_then(|r| doc.get(r).as_dict().cloned()).unwrap_or_default();
let pages = pdfcraft_model::pages(doc);
// Order matters: the most specific owners first. Resources by kind before anything that
// uses them: a content stream's dictionary may point at what it draws (PdfCraft's /PCAdded
// records an added image), and form fields and comments draw with fonts and images too.
for p in &pages {
let res = a.resolve_dict(p.dict.get(b"Resources"));
a.resources(&res, 0);
a.resources_of(p.dict.get(b"Resources"), 0);
}
let form = a.resolve_dict(cat.get(b"AcroForm"));
let form_resources = a.resolve_dict(form.get(b"DR"));
a.resources(&form_resources, 0);
a.resources_of(form.get(b"DR"), 0);
for p in &pages {
for x in annotations(doc, &p.dict) {
a.appearance_resources(&x);
+78 -20
View File
@@ -30,17 +30,21 @@ pub const MIN_FRAGMENTS: usize = 4;
/// Most pixels a merged image may have (memory).
const MAX_PIXELS: u64 = 80_000_000;
/// Fragment groups a page's search for runs may read per content operator, and at least. A run
/// that is not one picture is searched again from each of its groups, so without a limit images
/// drawn over one another take time quadratic in their number; past it, the rest of the page is
/// left as it is.
const SCAN_PER_OP: usize = 16;
/// Content operators a page's search for runs may read per content operator of the page, and at
/// least. A run that is not one picture is searched again from each of its groups, so without a
/// limit images drawn over one another take time quadratic in their number; past it, the rest of
/// the page is left as it is. Every operator of a group counts (its `cm` operators are composed
/// each time), not just the group; a group of four operators costs four, so the allowance is 16
/// groups per operator, as before, and groups with many `cm` operators pay for them.
const SCAN_PER_OP: usize = 64;
const MIN_SCAN: usize = 1 << 16;
#[cfg(test)]
thread_local! {
/// Fragment groups read, for the test that keeps a page's search linear in its content.
static GROUP_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
/// Operators group reads walked, for the test that keeps the search linear in operators.
static OP_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// One fragment: its image, its box in the coordinates the run is drawn in, and its size.
@@ -53,21 +57,44 @@ struct Fragment {
/// The ops `q`, one or more `cm`, `Do`, `Q` starting at `i`: the index after them, the matrix
/// and the name drawn.
fn group_at(ops: &[Op], i: usize) -> Option<(usize, Matrix, Vec<u8>)> {
fn group_at(ops: &[Op], i: usize, reads: &std::cell::Cell<usize>) -> Option<(usize, Matrix, Vec<u8>)> {
#[cfg(test)]
GROUP_READS.with(|c| c.set(c.get().saturating_add(1)));
if !ops.get(i)?.is("q") {
let mut looked = 0usize;
let found = group_scan(ops, i, &mut looked);
// Every operator looked at is charged to the page's search allowance, whether or not the
// group turns out to be one.
reads.set(reads.get().saturating_add(looked));
#[cfg(test)]
OP_READS.with(|c| c.set(c.get().saturating_add(looked)));
found
}
/// [`group_at`]'s search, counting in `looked` each operator it examines.
fn group_scan(ops: &[Op], i: usize, looked: &mut usize) -> Option<(usize, Matrix, Vec<u8>)> {
let q = ops.get(i)?;
*looked += 1;
if !q.is("q") {
return None;
}
let mut j = i + 1;
let mut m = Matrix([1.0, 0.0, 0.0, 1.0, 0.0, 0.0]);
while let Some(op) = ops.get(j).filter(|o| o.is("cm")) {
*looked += 1;
m = Matrix::from_operands(&op.operands)?.then(&m);
j += 1;
}
let draw = ops.get(j).filter(|o| o.is("Do"))?;
let draw = ops.get(j)?;
*looked += 1;
if !draw.is("Do") {
return None;
}
let name = draw.name(0)?.to_vec();
ops.get(j + 1).filter(|o| o.is("Q"))?;
let end = ops.get(j + 1)?;
*looked += 1;
if !end.is("Q") {
return None;
}
(j > i + 1).then_some((j + 2, m, name))
}
@@ -152,7 +179,7 @@ fn stacked(run: &mut [Fragment]) -> Option<Vec<std::ops::Range<usize>>> {
/// The fragment groups from `i` on (at most `limit`) while they form a picture drawn row by row
/// or strip by strip in one direction, up to a gap or a jump.
fn drawn_in_sequence(ops: &[Op], i: usize, limit: usize, xobjects: &Dict, doc: &Document) -> Vec<Fragment> {
fn drawn_in_sequence(ops: &[Op], i: usize, limit: usize, xobjects: &Dict, doc: &Document, reads: &std::cell::Cell<usize>) -> Vec<Fragment> {
let mut run: Vec<Fragment> = Vec::new();
let mut row_x = [0.0f64, 0.0];
let mut cur_x = [0.0f64, 0.0];
@@ -163,7 +190,7 @@ fn drawn_in_sequence(ops: &[Op], i: usize, limit: usize, xobjects: &Dict, doc: &
let mut complete = 0usize;
let mut j = i;
while run.len() < limit {
let Some((next, m, name)) = group_at(ops, j) else { break };
let Some((next, m, name)) = group_at(ops, j, reads) else { break };
let Some((image, width, height, ..)) = fragment_image(doc, xobjects, &name) else { break };
let [a, _, _, d, e, f] = m.0;
let f2 = Fragment { image, rect: [e, f, e + a, f + d], width, height };
@@ -240,10 +267,10 @@ fn drawn_in_sequence(ops: &[Op], i: usize, limit: usize, xobjects: &Dict, doc: &
}
/// The op index after the first `count` fragment groups from `i`.
fn run_end(ops: &[Op], i: usize, count: usize) -> usize {
fn run_end(ops: &[Op], i: usize, count: usize, reads: &std::cell::Cell<usize>) -> usize {
let mut j = i;
for _ in 0..count {
match group_at(ops, j) {
match group_at(ops, j, reads) {
Some((next, ..)) => j = next,
None => break,
}
@@ -386,9 +413,9 @@ fn merge_page(
let mut out: Vec<Op> = Vec::with_capacity(ops.len());
let (mut i, mut merged, mut k) = (0, 0, 0);
let budget = ops.len().saturating_mul(SCAN_PER_OP).max(MIN_SCAN);
let mut scanned = 0usize;
let reads = std::cell::Cell::new(0usize);
while i < ops.len() {
if scanned > budget {
if reads.get() > budget {
out.extend(ops.get(i..).unwrap_or_default().iter().cloned());
break;
}
@@ -396,7 +423,7 @@ fn merge_page(
let mut run = Vec::new();
let mut kind: Option<(Object, usize)> = None;
let mut j = i;
while let Some((next, m, name)) = group_at(&ops, j) {
while let Some((next, m, name)) = group_at(&ops, j, &reads) {
let Some((image, width, height, cs, n)) = fragment_image(doc, &xobjects, &name) else { break };
let [a, b, c, d, e, f] = m.0;
if b.abs() > 1e-9 || c.abs() > 1e-9 || !(a > 0.0 && d > 0.0) {
@@ -410,13 +437,11 @@ fn merge_page(
run.push(Fragment { image, rect: [e, f, e + a, f + d], width, height });
j = next;
}
scanned = scanned.saturating_add(run.len()).saturating_add(1);
// Not one picture as a whole: a prefix drawn row by row or strip by strip may be.
let mut rows = if run.len() >= MIN_FRAGMENTS { stacked(&mut run) } else { None };
if run.len() >= MIN_FRAGMENTS && rows.is_none() {
run = drawn_in_sequence(&ops, i, run.len(), &xobjects, doc);
j = run_end(&ops, i, run.len());
scanned = scanned.saturating_add(run.len().saturating_mul(2)).saturating_add(2);
run = drawn_in_sequence(&ops, i, run.len(), &xobjects, doc, &reads);
j = run_end(&ops, i, run.len(), &reads);
rows = stacked(&mut run);
}
let Some(((cs, n), rows)) = kind.zip(rows).filter(|_| run.len() >= MIN_FRAGMENTS) else {
@@ -773,4 +798,37 @@ mod tests {
assert_eq!((merged, report.merged_images), (0, 0));
}
}
/// The same with many `cm` operators in each group: the search reads a bounded number of operators
/// for each one of the page, however the matrices are spread over the groups.
#[test]
fn groups_with_many_matrices_are_charged_for_each_operator() {
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 groups = 400;
let content = doc.add(Object::Stream(Stream::flate(
Dict::new(),
format!("q 10 0 0 10 0 0 cm {}/Im Do Q\n", "1 0 0 1 0 0 cm ".repeat(49)).repeat(groups).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));
OP_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));
let reads = OP_READS.with(|c| c.get());
assert!(reads <= 80 * 53 * groups, "{reads} operator reads");
}
}
+343 -37
View File
@@ -13,6 +13,15 @@ use crate::{Compression, ImageSettings, MonoCompression, MonoSettings, OptimizeE
/// Images with more pixels than this are left alone (memory).
pub(crate) const MAX_PIXELS: u64 = 80_000_000;
/// The bytes an image of one bit a pixel holds as stored: each row starts on a new byte, a byte for
/// each 8 samples and one for any left over. The monochrome step takes such an image while these
/// are no more than [`MAX_PIXELS`], as many as that many pixels of eight bits hold: a wide one up
/// to 640 million pixels (an A0 page at 600 ppi is about 560 million), where at eight bits a pixel
/// it would be left alone, and a strip one sample wide no taller than one of eight bits.
fn one_bit_bytes(w: u64, h: u64) -> u64 {
w.div_ceil(8).saturating_mul(h)
}
/// The resources of a page, inherited from the page tree if the page has none.
pub(crate) fn page_resources(doc: &Document, page: ObjRef) -> Option<Dict> {
held_page_resources(doc, page).map(|(resources, _)| resources)
@@ -829,6 +838,21 @@ fn one_component(doc: &Document, cs: &Object) -> bool {
}
}
/// What the filters before a fax image's decoder may produce, its code: at most about a byte a
/// pixel and each row's end, as redaction allows, but no more than `MAX_PIXELS` bytes for its
/// pixels (and four a row), so a large page's code can't cost a byte a pixel.
fn fax_code_allowance(w: usize, h: usize) -> Option<usize> {
w.checked_mul(h)?.min(usize::try_from(MAX_PIXELS).ok()?).checked_add(h.checked_mul(4)?)?.checked_add(4096)
}
/// Whether `d` is an image of one bit a pixel as stored: an image mask, or one bit in one colour
/// component.
fn one_bit_as_stored(doc: &Document, d: &Dict) -> bool {
let bits = d.int(b"BitsPerComponent");
let mask = matches!(d.get(b"ImageMask"), Some(Object::Bool(true)));
(mask && bits.is_none_or(|b| b == 1)) || (bits == Some(1) && d.get(b"ColorSpace").is_some_and(|cs| one_component(doc, cs)))
}
/// A pixel's samples as a 1 or a 0, or `None` for a colour that is neither.
type Pixel = fn(&[u8]) -> Option<bool>;
@@ -854,19 +878,23 @@ fn one_bit(doc: &Document, s: &Stream, pack: bool, defaults: bool, budget: &mut
let d = &s.dict;
// Through u32 first, as everywhere here, so the product can't overflow.
let (w, h) = (u32::try_from(d.int(b"Width")?).ok()?, u32::try_from(d.int(b"Height")?).ok()?);
if w == 0 || h == 0 || u64::from(w) * u64::from(h) > MAX_PIXELS {
// An image already of one bit a pixel is taken while its rows hold no more than `MAX_PIXELS`
// bytes (`one_bit_bytes`), one packed from more bits (2, 4 or 8) up to `MAX_PIXELS` pixels, as
// before: its samples are decoded as stored first, eight-bit RGB at three bytes a pixel.
let as_stored = one_bit_as_stored(doc, d);
let held = if as_stored { one_bit_bytes(u64::from(w), u64::from(h)) } else { u64::from(w) * u64::from(h) };
if w == 0 || h == 0 || held > MAX_PIXELS {
return None;
}
let (wu, hu) = (usize::try_from(w).ok()?, usize::try_from(h).ok()?);
let stride = wu.div_ceil(8);
let bits = d.int(b"BitsPerComponent");
let mask = matches!(d.get(b"ImageMask"), Some(Object::Bool(true)));
if (mask && bits.is_none_or(|b| b == 1)) || (bits == Some(1) && d.get(b"ColorSpace").is_some_and(|cs| one_component(doc, cs))) {
// No further than its rows can need: a fax image's code (the filters before its decoder
// produce it) takes at most about a byte a pixel and each row's end, as redaction allows.
if as_stored {
// No further than its rows can need.
let len = stride.checked_mul(hu)?;
let max = match s.filters().last() {
Some((pdfcraft_filters::Filter::CcittFax, _)) => wu.checked_mul(hu)?.checked_add(hu.checked_mul(4)?)?.checked_add(4096)?,
Some((pdfcraft_filters::Filter::CcittFax, _)) => fax_code_allowance(wu, hu)?,
// A JBIG2 page, which has to be the image's size, is `len` bytes as rows of a bit.
_ => allowance(len, h)?,
};
@@ -937,6 +965,7 @@ fn one_bit(doc: &Document, s: &Stream, pack: bool, defaults: bool, budget: &mut
_ => return None,
};
let row_len = wu.checked_mul(n)?.checked_mul(bpc)?.div_ceil(8);
count_decoded(u64::from(w) * u64::from(h));
// Through its parameters given by reference too: without a PNG predictor's tag bytes taken
// off, rows of 0 and 255 (or palette entries 0 and 1) would still pass below, each shifted.
let samples = budget.decode_filters(doc, s, allowance(row_len.checked_mul(hu)?, h)?).ok()?;
@@ -1364,9 +1393,9 @@ 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, r.generation));
let total = refs.len();
let mut jbig2 = false;
let mut group: Vec<Held> = Vec::new();
// Then the pictures' masks of one bit a sample, each once ([`decide_mask`]).
let mask_refs = picture_masks(doc, &refs);
let total = refs.len() + mask_refs.len();
// By number: a repaired object answers to two generations.
let mut smask_uses: HashMap<u32, usize> = HashMap::new();
for (r, _) in &refs {
@@ -1374,23 +1403,96 @@ pub(crate) fn run(
*smask_uses.entry(m.num).or_default() += 1;
}
}
let holds = settings.mono.compression == MonoCompression::Jbig2;
let threads = threads_for_items(doc, &refs, settings);
let mut out = Out { doc, report, budget, jbig2: false, group: Vec::new() };
let pictures = Items { items: &refs, threads, first: 0, total };
work_through(
&mut out,
&pictures,
&|doc, rest| batch_len(doc, rest, &smask_uses, holds),
&|doc, r, ppi, budget| decide(doc, r, ppi, defaults.contains(&r.num), settings, budget),
progress,
)?;
share(out.doc, &mut out.group, out.report);
let threads = threads_for_items(out.doc, &mask_refs, settings);
let masks = Items { items: &mask_refs, threads, first: refs.len(), total };
// Each mask is an object of its own (by number), which only its own decision changes.
work_through(
&mut out,
&masks,
&|_, rest| rest.len().min(PICTURES_AT_ONCE),
&|doc, r, _, budget| decide_mask(doc, r, settings, budget),
progress,
)?;
if !progress(Stage::Images { done: total, total }) {
return Err(OptimizeError::Cancelled);
}
if out.jbig2 {
at_least_pdf_1_4(out.doc)?;
}
Ok(())
}
/// What the image pass changes and counts as it goes: the document, the report, the run's
/// allowance, whether it stored an image as JBIG2, and the JBIG2 images held to share a dictionary
/// ([`share`]).
struct Out<'a> {
doc: &'a mut Document,
report: &'a mut Report,
budget: &'a mut ImageBudget,
jbig2: bool,
group: Vec<Held>,
}
/// Images the pass works through, each with its effective resolution, on up to `threads` threads;
/// for progress, the first of them is number `first` of the pass's `total`.
struct Items<'a> {
items: &'a [(ObjRef, f64)],
threads: usize,
first: usize,
total: usize,
}
/// How many of `items` to work on at once: one below [`MIN_FOR_THREADS`], else as many as the
/// workers, and as [`PICTURE_MEMORY`] holds of the largest.
fn threads_for_items(doc: &Document, items: &[(ObjRef, f64)], settings: &Settings) -> usize {
// 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)
};
if items.len() < MIN_FOR_THREADS {
return 1;
}
let largest = items.iter().filter_map(|(r, _)| picture_pixels(doc, *r)).max().unwrap_or(0);
threads_for(crate::pool::workers(settings.workers), largest)
}
/// How [`work_through`] works out what's to become of an image, at its effective resolution, within
/// an allowance; threads share it.
type Decide<'a> = dyn Fn(&Document, ObjRef, f64, &mut ImageBudget) -> Decision + Sync + 'a;
/// How many of the images left, from the first, [`work_through`] may work out beside each other.
type Batch<'a> = dyn Fn(&Document, &[(ObjRef, f64)]) -> usize + 'a;
/// Works out what's to become of each of `items` by `decide`, and does it, in their order: a batch
/// of them beside each other where `batch` says they can be, one at a time otherwise.
fn work_through(
out: &mut Out<'_>,
items: &Items<'_>,
batch: &Batch<'_>,
decide: &Decide<'_>,
progress: &mut dyn FnMut(Stage) -> bool,
) -> Result<(), OptimizeError> {
let (threads, total) = (items.threads, items.total);
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 };
while let Some(rest) = items.items.get(done..).filter(|rest| !rest.is_empty()) {
let at = items.first.saturating_add(done);
let run = if threads > 1 { batch(out.doc, rest) } else { 0 };
let Some(batch) = rest.get(..run).filter(|batch| batch.len() > 1) else {
if !progress(Stage::Images { done, total }) {
if !progress(Stage::Images { done: at, total }) {
return Err(OptimizeError::Cancelled);
}
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 decision = decide(out.doc, *r, *ppi, out.budget);
apply(out.doc, decision, out.report, &mut out.jbig2, &mut out.group);
}
done += 1;
continue;
@@ -1399,10 +1501,10 @@ pub(crate) fn run(
// 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 allowed = out.budget.work_left();
let used = AtomicU64::new(0);
let tried = {
let (doc, defaults) = (&*doc, &defaults);
let doc = &*out.doc;
crate::pool::map(
batch,
threads,
@@ -1411,36 +1513,74 @@ pub(crate) fn run(
return None;
}
let mut own = ImageBudget::with_work(allowed);
let decision = decide(doc, *r, *ppi, defaults.contains(&r.num), settings, &mut own);
let decision = decide(doc, *r, *ppi, &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 }),
&mut |finished| progress(Stage::Images { done: at.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);
Some((decision, cost)) if cost <= out.budget.work_left() => {
out.budget.charge(cost);
decision
}
_ => decide(doc, *r, *ppi, defaults.contains(&r.num), settings, budget),
_ => decide(out.doc, *r, *ppi, out.budget),
};
apply(doc, decision, report, &mut jbig2, &mut group);
apply(out.doc, decision, out.report, &mut out.jbig2, &mut out.group);
}
done += batch.len();
}
share(doc, &mut group, report);
if !progress(Stage::Images { done: total, total }) {
return Err(OptimizeError::Cancelled);
}
if jbig2 {
at_least_pdf_1_4(doc)?;
}
Ok(())
}
/// The masks of `pictures` the pass stores again after them, each once (by number): their soft
/// masks and their stencil masks, unless one is drawn as a picture of its own, and so is one of
/// them. A colour-key `/Mask` is an array, not an image. Their resolution isn't measured.
fn picture_masks(doc: &Document, pictures: &[(ObjRef, f64)]) -> Vec<(ObjRef, f64)> {
let drawn: HashSet<u32> = pictures.iter().map(|(r, _)| r.num).collect();
let mut seen = HashSet::new();
let mut masks = Vec::new();
for (r, _) in pictures {
let object = doc.get(*r);
let Object::Stream(s) = &*object else { continue };
for key in [&b"SMask"[..], b"Mask"] {
if let Some(m) = s.dict.reference(key)
&& !drawn.contains(&m.num)
&& seen.insert(m.num)
{
masks.push((m, f64::NAN));
}
}
}
masks.sort_by_key(|(r, _)| (r.num, r.generation));
masks
}
/// Work out what's to become of mask `r` of a picture, changing nothing yet: stored again as the
/// monochrome settings ask ([`mono`]), at its size, when it has one bit a sample (a stencil mask,
/// or a soft mask of one bit) and that is smaller. The bits stay as they are, so it masks as it did.
/// It isn't resampled: its resolution isn't measured, and its edges are the picture's. A soft mask
/// of more bits is left to be resampled with its picture ([`process`]), which wants it at eight. It
/// shares no JBIG2 dictionary: those are for images named directly, which redaction can store again.
fn decide_mask(doc: &Document, r: ObjRef, settings: &Settings, budget: &mut ImageBudget) -> Decision {
let obj = doc.get(r);
let Object::Stream(s) = &*obj else { return Decision::NotAnImage };
let stencil = matches!(s.dict.get(b"ImageMask"), Some(Object::Bool(true)));
if !stencil && s.dict.int(b"BitsPerComponent") != Some(1) {
return Decision::NotAnImage;
}
let refused = budget.refused();
// Its resolution unmeasured, it isn't resampled. As where a default colour space is in force:
// at one bit a sample that changes nothing, and nothing is packed.
match mono(doc, s, f64::NAN, true, &settings.mono, budget) {
Some((new, _, _)) => Decision::Replace { image: r, before: s.raw.len(), new, resampled: false, smask: None, bits: None },
None => Decision::Stays { refused: budget.refused() > refused },
}
}
/// A picture's soft mask, if it names one.
fn smask_of(doc: &Document, r: ObjRef) -> Option<ObjRef> {
match &*doc.get(r) {
@@ -1494,12 +1634,21 @@ 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.
/// A picture's pixels, if it is small enough to be decoded at all. One of one bit a pixel as
/// stored is taken while the bytes its rows hold ([`one_bit_bytes`]) are no more than
/// `MAX_PIXELS`, and counts as those and one more a row: decoding allows each row's end a few
/// bytes besides its samples ([`allowance`], [`fax_code_allowance`]), which for an image a few
/// samples wide is as much again as its samples.
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)
if one_bit_as_stored(doc, &s.dict) {
let bytes = one_bit_bytes(w, h);
return (bytes <= MAX_PIXELS).then(|| bytes.saturating_add(h));
}
let pixels = w.checked_mul(h)?;
(pixels <= MAX_PIXELS).then_some(pixels)
}
/// How many pictures of `largest` pixels to work on at once: `workers`, or as many as
@@ -1511,7 +1660,7 @@ fn threads_for(workers: usize, largest: u64) -> usize {
/// What's to become of one picture.
enum Decision {
/// Not an image stream after all.
/// Not an image stream after all, or a picture's mask the pass doesn't store again.
NotAnImage,
/// An image that stays as it is, `refused` if the allowance couldn't pay for it.
Stays { refused: bool },
@@ -1750,6 +1899,83 @@ mod dimension_tests {
assert_eq!(threads_for(8, 0), 8);
}
/// A one-bit image counts as the bytes its rows hold and one more a row when planning how many
/// pictures run at once, while those it holds are up to `MAX_PIXELS`: about an eighth of its
/// pixels when wide, two bytes a row when a few samples wide. One of eight bits counts whole,
/// up to `MAX_PIXELS`.
#[test]
fn a_one_bit_picture_counts_as_the_bytes_of_its_rows() {
let mut doc = Document::new_empty();
let mut add = |w: i64, h: i64, bits: i64| {
let mut dict = Dict::new();
dict.set(b"Width".to_vec(), Object::Int(w));
dict.set(b"Height".to_vec(), Object::Int(h));
dict.set(b"BitsPerComponent".to_vec(), Object::Int(bits));
dict.set(b"ColorSpace".to_vec(), Object::name("DeviceGray"));
doc.add(Object::Stream(Stream::from_raw(dict, Vec::new())))
};
let (one_bit, past_one_bit, eight_bit) = (add(20_000, 32_000, 1), add(20_000, 32_001, 1), add(10_000, 8_001, 8));
let (strip, past_strip, narrow) = (add(1, 80_000_000, 1), add(1, 80_000_001, 1), add(8, 10_000_000, 1));
assert_eq!(picture_pixels(&doc, one_bit), Some(80_000_000 + 32_000));
assert_eq!(picture_pixels(&doc, past_one_bit), None);
assert_eq!(picture_pixels(&doc, strip), Some(160_000_000), "a byte a row, and one more");
assert_eq!(picture_pixels(&doc, past_strip), None);
assert_eq!(picture_pixels(&doc, narrow), Some(20_000_000));
assert_eq!(threads_for(8, 20_000_000), 6);
assert_eq!(threads_for(8, 160_000_000), 1);
assert_eq!(picture_pixels(&doc, eight_bit), None);
assert_eq!(threads_for(8, 80_000_000), 1);
}
/// A fax image's code may take about a byte a pixel and its rows' ends, but no more than
/// `MAX_PIXELS` bytes for its pixels however large the page, and four a row.
#[test]
fn a_fax_images_code_is_allowed_80_million_bytes_and_four_a_row() {
assert_eq!(fax_code_allowance(1_000, 1_000), Some(1_000_000 + 4_000 + 4_096));
assert_eq!(fax_code_allowance(20_000, 32_000), Some(80_000_000 + 128_000 + 4_096));
assert_eq!(fax_code_allowance(1, 80_000_000), Some(80_000_000 + 320_000_000 + 4_096));
}
/// The monochrome step decodes an image already of one bit a pixel while its rows hold no more
/// than `MAX_PIXELS` bytes, and one it would pack from eight bits up to `MAX_PIXELS` pixels.
/// Past those, nothing is decoded.
#[test]
fn one_bit_images_are_decoded_up_to_their_own_limit() {
let image = |w: i64, h: i64, bits: i64| {
let mut dict = Dict::new();
dict.set(b"Width".to_vec(), Object::Int(w));
dict.set(b"Height".to_vec(), Object::Int(h));
dict.set(b"BitsPerComponent".to_vec(), Object::Int(bits));
dict.set(b"ColorSpace".to_vec(), Object::name("DeviceGray"));
Stream::from_raw(dict, Vec::new())
};
let decoded = |s: &Stream| {
DECODED_PIXELS.with(|c| c.set(0));
one_bit(&Document::new_empty(), s, true, false, &mut ImageBudget::with_work(u64::MAX));
DECODED_PIXELS.with(|c| c.get())
};
assert_eq!(decoded(&image(20_000, 32_000, 1)), 640_000_000, "one bit, at the limit");
assert_eq!(decoded(&image(20_000, 32_001, 1)), 0, "one bit, past it");
assert_eq!(decoded(&image(1, 80_000_000, 1)), 80_000_000, "one bit a sample wide, a byte a row, at the limit");
assert_eq!(decoded(&image(1, 80_000_001, 1)), 0, "one bit a sample wide, past it");
assert_eq!(decoded(&image(10_000, 8_000, 8)), 80_000_000, "eight bits, at theirs");
assert_eq!(decoded(&image(10_000, 8_001, 8)), 0, "eight bits, past theirs");
}
/// A zero-wide image isn't decoded: its rows hold no bytes, but its filters would be allowed
/// three a row.
#[test]
fn a_zero_wide_image_is_not_decoded() {
let mut dict = Dict::new();
dict.set(b"Width".to_vec(), Object::Int(0));
dict.set(b"Height".to_vec(), Object::Int(1_000_000));
dict.set(b"ImageMask".to_vec(), Object::Bool(true));
let s = Stream::flate(dict, &vec![0u8; 1 << 20]);
let mut budget = ImageBudget::with_work(1 << 40);
assert!(one_bit(&Document::new_empty(), &s, true, false, &mut budget).is_none());
assert_eq!(budget.work_left(), 1 << 40);
}
/// 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]
@@ -1994,6 +2220,86 @@ mod dimension_tests {
}
}
/// A picture's mask past the run's allowance stays as it is, counted as refused, as an image
/// is; one the allowance paid for and that stays (its noise is no smaller as Group 4) isn't. The
/// progress counts the masks with the pictures.
#[test]
fn a_mask_past_the_runs_allowance_stays_and_is_counted() {
let mut seed = 0x2545_F491_4F6C_DD1Du64;
let noise: Vec<u8> = (0..32 * 256)
.map(|_| {
seed ^= seed << 13;
seed ^= seed >> 7;
seed ^= seed << 17;
seed as u8
})
.collect();
let page_of = |pictures: usize, masked: bool| {
let mut doc = Document::new_empty();
let mut xobjects = Dict::new();
let mut drawn = String::from("q 10 0 0 10 0 0 cm ");
let mut masks = Vec::new();
for i in 0..pictures {
let mut dict = Dict::new();
dict.set(b"Subtype".to_vec(), Object::name("Image"));
dict.set(b"Width".to_vec(), Object::Int(16));
dict.set(b"Height".to_vec(), Object::Int(16));
dict.set(b"BitsPerComponent".to_vec(), Object::Int(8));
dict.set(b"ColorSpace".to_vec(), Object::name("DeviceCMYK"));
if masked {
let mut mask = Dict::new();
mask.set(b"Subtype".to_vec(), Object::name("Image"));
mask.set(b"ImageMask".to_vec(), Object::Bool(true));
mask.set(b"Width".to_vec(), Object::Int(256));
mask.set(b"Height".to_vec(), Object::Int(256));
let mask = doc.add(Object::Stream(Stream::flate(mask, &noise)));
dict.set(b"Mask".to_vec(), Object::Ref(mask));
masks.push(mask);
}
let picture = doc.add(Object::Stream(Stream::flate(dict, &[0; 16 * 16 * 4])));
xobjects.set(format!("I{i}").into_bytes(), Object::Ref(picture));
drawn.push_str(&format!("/I{i} Do "));
}
drawn.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(), drawn.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, page, masks)
};
let keep = crate::ImageSettings { downsample: false, compression: crate::Compression::Retain, ..crate::ImageSettings::REDUCE };
let settings = Settings { color: keep, gray: keep, ..Settings::default() };
let cost = |pictures: usize, masked: bool| {
let (mut doc, page, _) = page_of(pictures, masked);
let mut budget = ImageBudget::with_work(u64::MAX);
let mut report = Report::default();
run(&mut doc, &[page], &settings, &mut report, &mut |_| true, &mut budget).unwrap();
assert_eq!(report.images_refused, 0);
u64::MAX - budget.work_left()
};
let mask = cost(1, true) - cost(1, false);
assert!(mask > 0);
let (mut doc, page, masks) = page_of(3, true);
let before: Vec<_> = masks.iter().map(|m| doc.get(*m)).collect();
let mut budget = ImageBudget::with_work(cost(3, false) + 2 * mask);
let mut report = Report::default();
let mut last = None;
let mut progress = |stage: Stage| {
if let Stage::Images { done, total } = stage {
last = Some((done, total));
}
true
};
run(&mut doc, &[page], &settings, &mut report, &mut progress, &mut budget).unwrap();
assert_eq!((report.images, report.images_refused), (6, 1), "{report:?}");
assert_eq!(last, Some((6, 6)), "three pictures and their three masks");
assert!(masks.iter().zip(&before).all(|(m, b)| doc.get(*m) == *b), "every mask stays as it was");
}
/// An image the allowance ran out on between being packed and being resampled is rewritten,
/// as the packed one, so it isn't one that stayed as it was.
#[test]
+6 -3
View File
@@ -15,7 +15,8 @@
//! that use only palette entries 0 and 1, packed to one bit) above a threshold are averaged down to a
//! target resolution when grey, image masks or indexed, halftones and dithers aside (see the README), and
//! are stored as CCITT Group 4 or lossless JBIG2, or 1-bit
//! Flate once resampled or packed, when that is smaller.
//! Flate once resampled or packed, when that is smaller. So are pictures' stencil and one-bit soft
//! masks, at their size.
//! - **Discard objects:** page thumbnails, alternate images, document tags (structure tree),
//! print settings, form submission, import and reset actions.
//! - **Clean up:** drop images and forms that pages list but never draw (such as a deleted
@@ -159,7 +160,8 @@ pub enum MonoCompression {
/// How black-and-white images (1-bit, CCITT fax among them; and eight-bit grey and RGB of only black
/// and white, and indexed images that use only palette entries 0 and 1, packed to one bit), and
/// image masks, are resampled and stored.
/// image masks, are resampled and stored. Pictures' stencil and one-bit soft masks are stored the
/// same way, at their size.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct MonoSettings {
/// Average images whose effective resolution is above `above_ppi` down to `target_ppi`.
@@ -206,7 +208,7 @@ pub struct Settings {
pub merge_fragments: bool,
pub color: ImageSettings,
pub gray: ImageSettings,
/// Black-and-white images, and image masks.
/// Black-and-white images, image masks, and pictures' one-bit masks.
pub mono: MonoSettings,
pub discard_thumbnails: bool,
pub discard_alternate_images: bool,
@@ -314,6 +316,7 @@ pub struct Report {
/// Images merged from fragments, and how many fragments went into them.
pub merged_images: usize,
pub fragments_merged: usize,
/// Images the image step read: those the pages draw, and their pictures' one-bit masks.
pub images: usize,
pub images_resampled: usize,
pub images_recompressed: usize,
+6 -2
View File
@@ -52,8 +52,12 @@ fn tree_entries(doc: &Document, node: &Object) -> Vec<(Vec<u8>, Object)> {
}
}
}
if let Some(kids) = d.get(b"Kids").map(|x| doc.resolve(x)).and_then(|x| x.as_array().cloned()) {
queue.extend(kids.into_iter().map(|k| (k, depth + 1)));
// A kids array shared by reference is read once, and only kids not yet seen are queued:
// nodes sharing one array can't multiply the queue.
if let Some(kids) =
d.get(b"Kids").filter(|k| !matches!(k, Object::Ref(r) if !seen.insert(*r))).map(|x| doc.resolve(x)).and_then(|x| x.as_array().cloned())
{
queue.extend(kids.into_iter().filter(|k| !matches!(k, Object::Ref(r) if seen.contains(r))).map(|k| (k, depth + 1)));
}
}
out
+249 -14
View File
@@ -423,8 +423,10 @@ fn black_and_white_images_become_ccitt_group_4() {
/// Which 1-bit images qualify for Group 4: those of one colour component, an ICC profile of one
/// component and a DeviceN of one colourant among them, but not one of three components or two
/// colourants (more than a bit a pixel); image masks of one bit, as `/BitsPerComponent 1` says or
/// by default, but not one that says 8; and images of up to 80 million pixels, not one row more.
/// The byte totals count exactly the images stored again.
/// by default, but not one that says 8; and images past 80 million pixels too, where an image of
/// eight bits would be left alone (`one_bit_images_are_decoded_up_to_their_own_limit` checks the
/// bytes of rows a one-bit image may hold without decoding so much). The byte totals count exactly
/// the images stored again.
#[test]
fn group_4_takes_images_of_one_bit_a_pixel_up_to_the_pixel_limit() {
let mut doc = Document::new_empty();
@@ -457,7 +459,7 @@ fn group_4_takes_images_of_one_bit_a_pixel_up_to_the_pixel_limit() {
let mask = |bits: i64| [("ImageMask", Object::Bool(true)), ("BitsPerComponent", bits.into())];
let mask_1 = mono_image(&mut doc, w, h, &text, None, &mask(1));
let mask_8 = mono_image(&mut doc, w, h, &bilevel(8 * w, h, false), None, &mask(8));
// 10,000 × 8,000 is the limit itself.
// 10,000 × 8,000 is the limit of an image of eight bits; one of one bit goes past it.
let grey = one_bit(Object::name("DeviceGray"));
let at_limit = mono_image(&mut doc, 10_000, 8_000, &bilevel(10_000, 8_000, false), None, &grey);
let past_limit = mono_image(&mut doc, 10_000, 8_001, &bilevel(10_000, 8_001, false), None, &grey);
@@ -474,8 +476,8 @@ fn group_4_takes_images_of_one_bit_a_pixel_up_to_the_pixel_limit() {
})
.collect();
page(&mut doc, &names.iter().map(String::as_str).zip(all).collect::<Vec<_>>(), &content);
let converted = [icc_1, spot, mask_1, at_limit];
let left = [icc_3, two_spots, mask_8, past_limit];
let converted = [icc_1, spot, mask_1, at_limit, past_limit];
let left = [icc_3, two_spots, mask_8];
let before = |doc: &Document, refs: &[ObjRef]| refs.iter().map(|r| stream(doc, *r).raw).collect::<Vec<_>>();
let (old, untouched) = (before(&doc, &converted), before(&doc, &left));
let r = optimize(&mut doc, &Settings::default()).unwrap();
@@ -4925,15 +4927,22 @@ fn indexed_thin_rules_survive_averaging_for_both_palette_orders_and_decodes() {
}
}
/// An image past what the JBIG2 decoder takes on a side stays as it is: JBIG2 can state the size,
/// but PdfCraft's decoder refuses such a stream, so stored as JBIG2 it drew nothing here. At 65,535
/// on a side, the same bars do become JBIG2, so the fixture does reach that choice, and the coding
/// stored (symbols, here) reads back through that decoder.
/// An image past what the JBIG2 decoder takes on a side, or past 2^28 pixels in all, stays as it
/// is: JBIG2 can state the size, but PdfCraft's decoder refuses such a stream, so stored as JBIG2 it
/// drew nothing here. At 65,535 on a side, and at 2^28 in all (past 80 million, which the
/// monochrome step takes of a one-bit image), the same bars do become JBIG2, so the fixture does
/// reach that choice, and the coding stored reads back through that decoder. Averaged, an image past
/// 2^28 becomes small enough and is stored as JBIG2 too.
#[test]
fn an_image_too_large_for_the_jbig2_decoder_stays_as_it_is() {
for (w, h, stored) in
[(65_535u32, 16u32, &b"JBIG2Decode"[..]), (16, 65_535, b"JBIG2Decode"), (65_536, 16, b"FlateDecode"), (16, 65_536, b"FlateDecode")]
{
for (w, h, stored) in [
(65_535u32, 16u32, &b"JBIG2Decode"[..]),
(16, 65_535, b"JBIG2Decode"),
(65_536, 16, b"FlateDecode"),
(16, 65_536, b"FlateDecode"),
(16_384, 16_384, b"JBIG2Decode"),
(16_384, 16_385, b"FlateDecode"),
] {
let mut doc = Document::new_empty();
let image = mono_image(&mut doc, w, h, &bars(w, h), None, &[("BitsPerComponent", 1.into()), ("ColorSpace", Object::name("DeviceGray"))]);
page(&mut doc, &[("Im", image)], &format!("q {w} 0 0 {h} 0 0 cm /Im Do Q"));
@@ -4958,6 +4967,15 @@ fn an_image_too_large_for_the_jbig2_decoder_stays_as_it_is() {
assert!(decoded_image(&doc, &s).unwrap() == bits, "{w} × {h} reads back");
}
}
let (w, h) = (16_384u32, 16_385u32);
let mut doc = Document::new_empty();
let image = mono_image(&mut doc, w, h, &bars(w, h), None, &[("BitsPerComponent", 1.into()), ("ColorSpace", Object::name("DeviceGray"))]);
let (pw, ph) = (f64::from(w) * 72.0 / 600.0, f64::from(h) * 72.0 / 600.0);
page(&mut doc, &[("Im", image)], &format!("q {pw} 0 0 {ph} 0 0 cm /Im Do Q"));
let settings = Settings { mono: MonoSettings { compression: MonoCompression::Jbig2, ..MonoSettings::REDUCE }, ..Settings::default() };
let r = optimize(&mut doc, &settings).unwrap();
assert_eq!(r.images_resampled, 1, "{r:?}");
assert_eq!(stream(&doc, image).dict.name(b"Filter"), Some(&b"JBIG2Decode"[..]), "averaged, it is stored as JBIG2");
}
/// The colour and grey steps leave an image over 80 million pixels as it is, whatever their settings
@@ -5363,7 +5381,8 @@ fn stencil(doc: &mut Document, w: u32, h: u32) -> ObjRef {
}
/// A picture with a stencil mask is made smaller like any other: the mask has a resolution of its
/// own, so it stays exactly as it was and the hole it cuts stays where it was.
/// own, so it keeps its size and its bits (stored again as Group 4, as a picture's mask is) and the
/// hole it cuts stays where it was.
#[test]
fn a_picture_with_a_stencil_mask_is_downsampled_under_its_mask() {
let mut doc = Document::new_empty();
@@ -5381,7 +5400,9 @@ fn a_picture_with_a_stencil_mask_is_downsampled_under_its_mask() {
let after = stream(&doc, img);
assert_eq!(after.dict.int(b"Width"), Some(300), "150 ppi");
assert_eq!(after.dict.reference(b"Mask"), Some(mask), "the mask stays on it");
assert_eq!(stream(&doc, mask), mask_before, "and doesn't change");
let mask_after = stream(&doc, mask);
assert_eq!((mask_after.dict.int(b"Width"), mask_after.dict.int(b"Height")), (Some(1200), Some(1200)), "the mask isn't resampled");
assert_eq!(decoded_image(&doc, &mask_after).unwrap(), decoded_image(&doc, &mask_before).unwrap(), "and keeps its bits");
let rendered = render(&doc);
assert_eq!(rendered.len(), before.len());
let changed = before.iter().zip(&rendered).filter(|(a, b)| a.abs_diff(**b) > 96).count();
@@ -5396,6 +5417,156 @@ fn a_picture_with_a_stencil_mask_is_downsampled_under_its_mask() {
}
}
/// A picture's masks of one bit a sample, which the page doesn't draw by name, are stored again as
/// the monochrome settings ask, losslessly: a stencil `/Mask` (with a decode array that inverts it)
/// and a one-bit `/SMask` become Group 4, keep their size and bits, and stay the pictures' masks;
/// the page looks the same to the pixel. A mask two pictures share is stored once, and a stencil
/// the page also draws by name is stored as that image. An eight-bit soft mask of only black and
/// white stays as it is, to be resampled with its picture. With `mono: Retain` nothing changes.
/// One-bit images past 80 million pixels are stored again, as images of eight bits that large are
/// not: their rows hold a byte for each 8 samples. A picture's stencil mask and one-bit soft mask
/// too.
#[test]
fn one_bit_images_past_80_million_pixels_are_stored_as_group_4() {
let mut doc = Document::new_empty();
let (w, h) = (9_000, 8_900);
let text = bilevel(w, h, false);
let one_bit = mono_image(&mut doc, w, h, &text, None, &[("BitsPerComponent", 1.into()), ("ColorSpace", Object::name("DeviceGray"))]);
let stencil = mono_image(&mut doc, w, h, &text, None, &[("ImageMask", Object::Bool(true))]);
let soft = mono_image(&mut doc, w, h, &text, None, &[("BitsPerComponent", 1.into()), ("ColorSpace", Object::name("DeviceGray"))]);
let masked = |doc: &mut Document, key: &str, mask: ObjRef| {
let picture = image(doc, 200, 80, 3, false, None);
let mut s = stream(doc, picture);
s.dict.set(key.as_bytes().to_vec(), Object::Ref(mask));
doc.set(picture, Object::Stream(s));
picture
};
let (picture, shaded) = (masked(&mut doc, "Mask", stencil), masked(&mut doc, "SMask", soft));
page(
&mut doc,
&[("I", one_bit), ("P", picture), ("S", shaded)],
"q 300 0 0 300 20 400 cm /I Do Q q 300 0 0 120 20 100 cm /P Do Q q 300 0 0 120 20 250 cm /S Do Q",
);
let keep = ImageSettings { downsample: false, compression: Compression::Retain, ..ImageSettings::REDUCE };
let mono = MonoSettings { downsample: false, ..MonoSettings::REDUCE };
let before = [one_bit, stencil, soft].map(|r| stream(&doc, r));
let r = optimize(&mut doc, &Settings { color: keep, gray: keep, mono, ..Settings::default() }).unwrap();
assert_eq!(r.images_recompressed, 3, "{r:?}");
for (r, old) in [one_bit, stencil, soft].into_iter().zip(&before) {
let new = stream(&doc, r);
assert_eq!(new.dict.name(b"Filter"), Some(&b"CCITTFaxDecode"[..]), "{r:?}");
assert!(new.raw.len() < old.raw.len(), "{r:?}: {} against {}", new.raw.len(), old.raw.len());
assert_eq!(decoded_image(&doc, &new).unwrap(), text, "{r:?} keeps its bits");
}
}
/// With the default settings (Reduce File Size), a one-bit image past 80 million pixels drawn at
/// 600 ppi is averaged to 300 ppi, as a smaller one is: vertical stripes four samples wide.
#[test]
fn a_one_bit_image_past_80_million_pixels_is_averaged_with_the_default_settings() {
let (w, h) = (9_000u32, 8_900u32);
let mut doc = Document::new_empty();
let stripes = vec![0x0F; (w as usize).div_ceil(8) * h as usize];
let one_bit = mono_image(&mut doc, w, h, &stripes, None, &[("BitsPerComponent", 1.into()), ("ColorSpace", Object::name("DeviceGray"))]);
let (pw, ph) = (f64::from(w) * 72.0 / 600.0, f64::from(h) * 72.0 / 600.0);
page(&mut doc, &[("I", one_bit)], &format!("q {pw} 0 0 {ph} 0 0 cm /I Do Q"));
let r = optimize(&mut doc, &Settings::default()).unwrap();
assert_eq!(r.images_resampled, 1, "{r:?}");
let s = stream(&doc, one_bit);
assert_eq!((s.dict.int(b"Width"), s.dict.int(b"Height")), (Some(4_500), Some(4_450)));
}
#[test]
fn a_pictures_one_bit_masks_are_stored_again() {
let mut doc = Document::new_empty();
let (w, h) = (1200, 480);
let text = bilevel(w, h, false);
let decode = Object::Array(vec![1.into(), 0.into()]);
let stencil_mask = mono_image(&mut doc, w, h, &text, None, &[("ImageMask", Object::Bool(true)), ("Decode", decode.clone())]);
let one_bit = mono_image(&mut doc, w, h, &text, None, &[("BitsPerComponent", 1.into()), ("ColorSpace", Object::name("DeviceGray"))]);
let wide: Vec<u8> = text.iter().flat_map(|b| (0..8).rev().map(move |i| if b >> i & 1 == 1 { 255 } else { 0 })).collect();
let eight_bit = mono_image(&mut doc, w, h, &wide, None, &[("BitsPerComponent", 8.into()), ("ColorSpace", Object::name("DeviceGray"))]);
let drawn = mono_image(&mut doc, w, h, &text, None, &[("ImageMask", Object::Bool(true))]);
let masked = |doc: &mut Document, key: &str, mask: ObjRef| {
let picture = image(doc, 200, 80, 3, false, None);
let mut s = stream(doc, picture);
s.dict.set(key.as_bytes().to_vec(), Object::Ref(mask));
doc.set(picture, Object::Stream(s));
picture
};
let a = masked(&mut doc, "Mask", stencil_mask);
let b = masked(&mut doc, "Mask", stencil_mask);
let c = masked(&mut doc, "SMask", one_bit);
let d = masked(&mut doc, "SMask", eight_bit);
let e = masked(&mut doc, "Mask", drawn);
page(
&mut doc,
&[("A", a), ("B", b), ("C", c), ("D", d), ("E", e), ("M", drawn)],
"q 300 0 0 120 20 660 cm /A Do Q q 300 0 0 120 320 660 cm /B Do Q q 300 0 0 120 20 520 cm /C Do Q \
q 300 0 0 120 320 520 cm /D Do Q q 300 0 0 120 20 380 cm /E Do Q q 0 0.4 0.8 rg 300 0 0 120 320 380 cm /M Do Q",
);
// Pictures in colour and grey are left as they are, so only the masks can change.
let keep = ImageSettings { downsample: false, compression: Compression::Retain, ..ImageSettings::REDUCE };
let settings = Settings { color: keep, gray: keep, ..Settings::default() };
let before = render(&doc);
let masks = [stencil_mask, one_bit, eight_bit, drawn].map(|r| stream(&doc, r));
let mut kept = doc.clone();
let r = optimize(&mut kept, &Settings { mono: RETAIN, ..settings.clone() }).unwrap();
assert_eq!(r.images_recompressed, 0, "Retain keeps every mask as it is");
assert_eq!([stencil_mask, one_bit, eight_bit, drawn].map(|r| stream(&kept, r)), masks);
let r = optimize(&mut doc, &settings).unwrap();
assert_eq!(r.images_recompressed, 3, "the shared stencil once, the soft mask, the stencil drawn by name once: {r:?}");
for (mask, old) in [(stencil_mask, &masks[0]), (one_bit, &masks[1]), (drawn, &masks[3])] {
let new = stream(&doc, mask);
assert_eq!(new.dict.name(b"Filter"), Some(&b"CCITTFaxDecode"[..]), "{mask:?}");
assert_eq!((new.dict.int(b"Width"), new.dict.int(b"Height")), (Some(w as i64), Some(h as i64)));
assert_eq!(decoded_image(&doc, &new).unwrap(), decoded_image(&doc, old).unwrap(), "{mask:?} keeps its bits");
}
assert_eq!(stream(&doc, stencil_mask).dict.get(b"Decode"), Some(&decode), "the decode array stays");
assert_eq!(stream(&doc, eight_bit), masks[2], "an eight-bit soft mask stays");
for (picture, key, mask) in
[(a, "Mask", stencil_mask), (b, "Mask", stencil_mask), (c, "SMask", one_bit), (d, "SMask", eight_bit), (e, "Mask", drawn)]
{
assert_eq!(stream(&doc, picture).dict.reference(key.as_bytes()), Some(mask), "{picture:?} keeps its mask");
}
assert!(render(&doc) == before, "the page looks the same");
}
/// Stored as JBIG2, a picture's mask is coded on its own: it shares no symbol dictionary with the
/// images the page draws by name, which do share one.
#[test]
fn a_pictures_mask_stored_as_jbig2_shares_no_dictionary() {
let mut doc = Document::new_empty();
let (w, h) = (1200, 480);
let text = bilevel(w, h, false);
let mask = mono_image(&mut doc, w, h, &text, None, &[("ImageMask", Object::Bool(true))]);
let picture = image(&mut doc, 200, 80, 3, false, None);
let mut s = stream(&doc, picture);
s.dict.set(b"Mask".to_vec(), Object::Ref(mask));
doc.set(picture, Object::Stream(s));
let named: Vec<ObjRef> = (0..3)
.map(|_| mono_image(&mut doc, w, h, &text, None, &[("BitsPerComponent", 1.into()), ("ColorSpace", Object::name("DeviceGray"))]))
.collect();
page(
&mut doc,
&[("P", picture), ("G0", named[0]), ("G1", named[1]), ("G2", named[2])],
"q 300 0 0 120 20 660 cm /P Do Q q 300 0 0 120 320 660 cm /G0 Do Q q 300 0 0 120 20 520 cm /G1 Do Q q 300 0 0 120 320 520 cm /G2 Do Q",
);
let keep = ImageSettings { downsample: false, compression: Compression::Retain, ..ImageSettings::REDUCE };
let jbig2 = MonoSettings { compression: MonoCompression::Jbig2, ..MonoSettings::REDUCE };
let before = render(&doc);
let old = stream(&doc, mask);
optimize(&mut doc, &Settings { color: keep, gray: keep, mono: jbig2, ..Settings::default() }).unwrap();
let new = stream(&doc, mask);
assert_eq!(new.dict.name(b"Filter"), Some(&b"JBIG2Decode"[..]));
assert!(!new.dict.contains(b"DecodeParms"), "no /JBIG2Globals");
assert_eq!(decoded_image(&doc, &new).unwrap(), decoded_image(&doc, &old).unwrap());
assert!(named.iter().any(|r| stream(&doc, *r).dict.get(b"DecodeParms").is_some()), "the images drawn by name share one");
assert!(render(&doc) == before, "the page looks the same");
}
/// A colour-key mask names sample values: resampling or JPEG would make holes where there were none
/// and fill those there were, so the picture stays as it is, however the array is written. A mask
/// that can't be read as a stencil is no reason to change the picture either.
@@ -5442,6 +5613,70 @@ fn a_picture_whose_mask_is_not_a_stencil_is_left_alone() {
}
}
/// A resource dictionary shared by reference between thousands of pages is walked once by the
/// space audit, not once per page.
#[test]
fn space_audit_walks_a_shared_resource_dictionary_once() {
let mut doc = Document::new_empty();
let img = image(&mut doc, 4, 4, 3, false, None);
let mut x = Dict::new();
for i in 0..5_000 {
x.set(format!("Im{i}").into_bytes(), Object::Ref(img));
}
let mut res = Dict::new();
res.set(b"XObject".to_vec(), Object::Dict(x));
let shared = doc.add(Object::Dict(res));
let pages = doc.root().and_then(|r| doc.get(r).as_dict().and_then(|d| d.reference(b"Pages"))).unwrap();
let mut kids = Vec::new();
for _ in 0..2_000 {
let mut p = Dict::new();
p.set(b"Type".to_vec(), Object::name("Page"));
p.set(b"Parent".to_vec(), Object::Ref(pages));
p.set(b"MediaBox".to_vec(), Object::Array(vec![0.into(), 0.into(), 612.into(), 792.into()]));
p.set(b"Resources".to_vec(), Object::Ref(shared));
kids.push(Object::Ref(doc.add(Object::Dict(p))));
}
doc.update_dict(pages, |d| {
d.set(b"Count".to_vec(), Object::Int(kids.len() as i64));
d.set(b"Kids".to_vec(), Object::Array(kids));
})
.unwrap();
let started = std::time::Instant::now();
let audit = audit_space(&doc, 1 << 20);
assert!(started.elapsed() < std::time::Duration::from_secs(5), "{:?}", started.elapsed());
assert!(audit.iter().any(|u| u.category == SpaceCategory::Images && u.bytes > 0), "{audit:?}");
}
/// A name tree whose nodes all share one kids array (by reference) is read once per node, not
/// once per node per kid: the queue can't grow to the nodes times the kids.
#[test]
fn a_name_tree_sharing_one_kids_array_is_walked_once() {
let mut doc = Document::new_empty();
let p = page(&mut doc, &[], "BT ET");
let s = |t: &str| Object::String(pdfcraft_cos::PdfString::literal(t.as_bytes().to_vec()));
let fit = Object::Array(vec![Object::Ref(p), Object::name("Fit")]);
let kids = doc.add(Object::Array(Vec::new()));
let mut nodes = Vec::new();
for i in 0..3_000 {
let mut node = Dict::new();
node.set(b"Kids".to_vec(), Object::Ref(kids));
node.set(b"Names".to_vec(), Object::Array(vec![s(&format!("d{i}")), fit.clone()]));
nodes.push(Object::Ref(doc.add(Object::Dict(node))));
}
doc.set(kids, Object::Array(nodes));
let mut tree = Dict::new();
tree.set(b"Kids".to_vec(), Object::Ref(kids));
let tree = doc.add(Object::Dict(tree));
let mut names = Dict::new();
names.set(b"Dests".to_vec(), Object::Ref(tree));
let root = doc.root().unwrap();
doc.update_dict(root, |c| c.set(b"Names".to_vec(), Object::Dict(names))).unwrap();
let started = std::time::Instant::now();
let report = optimize(&mut doc, &Settings::default()).unwrap();
assert!(started.elapsed() < std::time::Duration::from_secs(10), "{:?}", started.elapsed());
assert_eq!(report.unreferenced_dests, 3_000, "every node's destination was found, once");
}
/// 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() {
+145 -45
View File
@@ -203,6 +203,7 @@ pub const WORDINGS: &[&str] = &[
"A graphics state has the rendering intent {}, which isn't a standard one",
"A graphics state has a rendering intent that isn't a name",
"The form asks viewers to make appearances (NeedAppearances)",
"Some content could not be read for device colour",
// Pages, actions, annotations and fields.
"Page {} has additional actions",
"A {} action isn't allowed",
@@ -229,7 +230,8 @@ pub struct Declared {
/// `pdfaid:part` and `pdfaid:conformance`, e.g. (2, "B").
pub pdfa: Option<(u8, String)>,
pub pdfua: Option<u8>,
/// Output intents' condition identifiers.
/// Output intents' condition identifiers: every intent the document lists (each object
/// once), each identifier cut to [`MAX_IDENTIFIER_BYTES`].
pub output_intents: Vec<String>,
}
@@ -276,10 +278,27 @@ pub fn declared(doc: &Document) -> Declared {
d.pdfua = xmp::identifier(&x, xmp::PDFUA_ID, "part").and_then(|p| p.parse().ok());
}
let cat = catalog(doc);
if let Some(list) = cat.get(b"OutputIntents").map(|o| doc.resolve(o)).and_then(|o| o.as_array().cloned()) {
for oi in list {
if let Some(od) = doc.resolve(&oi).as_dict() {
let id = od.get(b"OutputConditionIdentifier").and_then(|v| doc.resolve(v).as_string().map(|s| s.to_text())).unwrap_or_default();
let list = cat.get(b"OutputIntents").map(|o| doc.resolve(o));
if let Some(list) = list.as_deref().and_then(Object::as_array) {
// One intent object listed again is one declaration: its identifier is not copied once
// per listing. Every distinct one is kept (verification reads them all too), and only
// the start of an identifier longer than any real one.
let mut seen = std::collections::HashSet::new();
for oi in list.iter().filter(|oi| oi.as_ref().is_none_or(|r| seen.insert(r))) {
if let Some(od) = doc.resolve(oi).as_dict() {
let id = od
.get(b"OutputConditionIdentifier")
.and_then(|v| {
doc.resolve(v).as_string().map(|s| {
if s.bytes.len() <= MAX_IDENTIFIER_BYTES {
s.to_text()
} else {
// An even cut keeps UTF-16 text whole code units.
pdfcraft_cos::PdfString { bytes: s.bytes[..MAX_IDENTIFIER_BYTES & !1].to_vec(), hex: s.hex }.to_text()
}
})
})
.unwrap_or_default();
d.output_intents.push(id);
}
}
@@ -287,6 +306,14 @@ pub fn declared(doc: &Document) -> Declared {
d
}
/// The most bytes of an output condition identifier [`declared`] keeps (a real one is a few
/// dozen).
const MAX_IDENTIFIER_BYTES: usize = 1024;
/// Decoded bytes one verification reads looking for device colour, all content streams
/// together. Past it, content is not inspected, and the report says so.
const MAX_COLOUR_DECODED: usize = 1 << 30;
/// Every indirect object, with its reference.
fn objects(doc: &Document) -> Vec<(ObjRef, std::sync::Arc<Object>)> {
doc.object_numbers()
@@ -361,6 +388,9 @@ struct DeviceColour {
/// space, which PDF/A accepts whatever the output intent (ISO 19005-2 6.2.4.3).
default_rgb: bool,
default_cmyk: bool,
/// Content that could not be read (undecodable, or past [`MAX_COLOUR_DECODED`]) may use
/// device colour that was not seen.
incomplete: bool,
}
impl DeviceColour {
@@ -388,27 +418,35 @@ const MAX_DIRECT_DEPTH: u8 = 8;
/// The glyph procedures of every Type 3 font in `d`: `d` itself, or a font held directly inside
/// it (a font can sit inline in a resource dictionary).
fn type3_procs(doc: &Document, d: &Dict, depth: u8, out: &mut std::collections::HashSet<ObjRef>) {
fn type3_procs(doc: &Document, d: &Dict, depth: u8, read: &mut std::collections::HashSet<ObjRef>, out: &mut std::collections::HashSet<ObjRef>) {
if d.name(b"Subtype") == Some(b"Type3")
&& let Some(procs) = d.get(b"CharProcs").map(|c| doc.resolve(c))
&& let Some(procs) = procs.as_dict()
&& let Some(c) = d.get(b"CharProcs")
// One glyph dictionary shared by many fonts is read once: its entries are the same.
&& c.as_ref().is_none_or(|r| read.insert(r))
&& let Some(procs) = doc.resolve(c).as_dict()
{
out.extend(procs.iter().filter_map(|(_, p)| p.as_ref()));
}
for (_, v) in d.iter() {
type3_procs_within(doc, v, depth.saturating_add(1), out);
type3_procs_within(doc, v, depth.saturating_add(1), read, out);
}
}
fn type3_procs_within(doc: &Document, o: &Object, depth: u8, out: &mut std::collections::HashSet<ObjRef>) {
fn type3_procs_within(
doc: &Document,
o: &Object,
depth: u8,
read: &mut std::collections::HashSet<ObjRef>,
out: &mut std::collections::HashSet<ObjRef>,
) {
if depth > MAX_DIRECT_DEPTH {
return;
}
match o {
Object::Dict(d) => type3_procs(doc, d, depth, out),
Object::Dict(d) => type3_procs(doc, d, depth, read, out),
Object::Array(a) => {
for v in a {
type3_procs_within(doc, v, depth.saturating_add(1), out);
type3_procs_within(doc, v, depth.saturating_add(1), read, out);
}
}
_ => {}
@@ -430,9 +468,10 @@ fn referenced_content(doc: &Document, objs: &[(ObjRef, std::sync::Arc<Object>)])
};
out.extend(contents.iter().filter_map(Object::as_ref));
}
let mut read = std::collections::HashSet::new();
for (_, o) in objs {
if let Some(d) = dict_of(o) {
type3_procs(doc, d, 0, &mut out);
type3_procs(doc, d, 0, &mut read, &mut out);
}
}
out
@@ -560,6 +599,7 @@ fn mark_cs_object(doc: &Document, cs: &Object, used: &mut DeviceColour, depth: u
fn uses_device_colour(doc: &Document, objs: &[(ObjRef, std::sync::Arc<Object>)]) -> DeviceColour {
let mut used = DeviceColour::default();
let referenced = referenced_content(doc, objs);
let mut budget = pdfcraft_cos::DecodeBudget::new(MAX_COLOUR_DECODED, usize::MAX);
for (r, o) in objs {
let Some(d) = dict_of(o) else { continue };
// A resource dictionary's /ColorSpace, whether it is this object or the page's inline
@@ -586,9 +626,14 @@ fn uses_device_colour(doc: &Document, objs: &[(ObjRef, std::sync::Arc<Object>)])
if !(used.gray && used.rgb && used.cmyk)
&& let Object::Stream(s) = &**o
&& (referenced.contains(r) || is_content(&s.dict))
&& let Ok(data) = s.decoded()
{
let _ = content_colour(&data, &mut used);
match budget.decode(s) {
Ok(data) => {
let _ = content_colour(&data, &mut used);
}
// Not read: it may draw in a device space nothing above saw.
Err(_) => used.incomplete = true,
}
}
}
used
@@ -830,6 +875,9 @@ fn check_output_intent(
issue: &mut impl FnMut(&'static str, &'static str, Option<String>, Option<usize>, bool),
) {
let used = uses_device_colour(doc, objs);
if used.incomplete {
issue("6.2.3", "Some content could not be read for device colour", None, None, false);
}
match pdfa_intent_profile(doc) {
None if used.any() => {
issue("6.2.3", "Device colour is used, but there is no PDF/A output intent", None, None, !used.cmyk);
@@ -1215,22 +1263,56 @@ const MAX_ACTION_CHAIN: usize = 1024;
fn chain_forbidden(doc: &Document, a: &Dict) -> Option<String> {
let mut read = 0;
let mut seen = std::collections::HashSet::new();
// Actions written in an indirect `/Next` array, copied out of it.
let mut held: Vec<Dict> = Vec::new();
// Objects `/Next` refers to (an action, or an array of them), each read once and borrowed:
// one array shared by many chains is not copied per chain.
let mut held: Vec<std::sync::Arc<Object>> = Vec::new();
if let Some(s) = walk_chain(doc, a, &mut read, &mut seen, &mut held) {
return Some(s);
}
while let Some(d) = held.pop() {
if let Some(s) = walk_chain(doc, &d, &mut read, &mut seen, &mut held) {
return Some(s);
while let Some(o) = held.pop() {
let dicts: Vec<&Dict> = match &*o {
Object::Dict(d) => vec![d],
Object::Array(list) => {
// An array read is work too, with its entries: a chain of arrays alone must
// still reach the limit.
read = read.saturating_add(1 + list.len().min(MAX_ACTION_CHAIN));
if read > MAX_ACTION_CHAIN {
return Some("too deeply chained".into());
}
// More than the chain limit can't be read anyway.
hold_referenced(doc, list, &mut seen, &mut held);
list.iter().filter_map(Object::as_dict).take(MAX_ACTION_CHAIN).collect()
}
_ => continue,
};
for d in dicts {
if let Some(s) = walk_chain(doc, d, &mut read, &mut seen, &mut held) {
return Some(s);
}
}
}
None
}
/// [`chain_forbidden`] for the actions reachable from `a` through direct `/Next` entries. The
/// actions of each indirect `/Next` array (each read once) go to `held`.
fn walk_chain(doc: &Document, a: &Dict, read: &mut usize, seen: &mut std::collections::HashSet<ObjRef>, held: &mut Vec<Dict>) -> Option<String> {
/// Queue the objects the references in a `/Next` array name, each once.
fn hold_referenced(doc: &Document, list: &[Object], seen: &mut std::collections::HashSet<ObjRef>, held: &mut Vec<std::sync::Arc<Object>>) {
for r in list.iter().filter_map(Object::as_ref).take(MAX_ACTION_CHAIN) {
if seen.insert(r) {
// Resolved through any alias: a reference to a reference names its object's value.
held.push(doc.resolve(&Object::Ref(r)));
}
}
}
/// [`chain_forbidden`] for the actions reachable from `a` through direct `/Next` entries. What
/// an indirect `/Next`, or a reference inside a `/Next` array, names goes to `held`.
fn walk_chain(
doc: &Document,
a: &Dict,
read: &mut usize,
seen: &mut std::collections::HashSet<ObjRef>,
held: &mut Vec<std::sync::Arc<Object>>,
) -> Option<String> {
let mut stack = vec![a];
while let Some(d) = stack.pop() {
*read += 1;
@@ -1242,13 +1324,16 @@ fn walk_chain(doc: &Document, a: &Dict, read: &mut usize, seen: &mut std::collec
}
match d.get(b"Next") {
Some(Object::Dict(next)) => stack.push(next),
Some(Object::Array(list)) => stack.extend(list.iter().filter_map(Object::as_dict)),
Some(Object::Ref(r)) if seen.insert(*r) => {
if let Object::Array(list) = &*doc.get(*r) {
// More than the chain limit can't be read anyway.
held.extend(list.iter().filter_map(Object::as_dict).take(MAX_ACTION_CHAIN).cloned());
Some(Object::Array(list)) => {
*read = read.saturating_add(list.len().min(MAX_ACTION_CHAIN));
// A wide array is refused before any of it is queued.
if *read > MAX_ACTION_CHAIN {
return Some("too deeply chained".into());
}
hold_referenced(doc, list, seen, held);
stack.extend(list.iter().filter_map(Object::as_dict));
}
Some(Object::Ref(r)) if seen.insert(*r) => held.push(doc.resolve(&Object::Ref(*r))),
_ => {}
}
}
@@ -1291,6 +1376,26 @@ fn strip_actions(doc: &Document, d: &mut Dict) -> bool {
changed
}
/// Take the annotations `gone` off every page that lists them, each page's list rewritten once, and
/// replace their indirect objects with `Null`.
fn remove_from_pages(doc: &mut Document, gone: &std::collections::HashSet<ObjRef>) -> Result<(), pdfcraft_cos::CosError> {
if gone.is_empty() {
return Ok(());
}
for p in pdfcraft_model::pages(doc) {
let annots = p.dict.get(b"Annots").map(|a| doc.resolve(a)).and_then(|a| a.as_array().cloned()).unwrap_or_default();
let listed = |a: &Object| a.as_ref().is_some_and(|r| gone.contains(&r));
if annots.iter().any(listed) {
let kept: Vec<Object> = annots.into_iter().filter(|a| !listed(a)).collect();
doc.update_dict(p.obj, |pd| pd.set(b"Annots".to_vec(), Object::Array(kept)))?;
}
}
for r in gone {
doc.set(*r, Object::Null);
}
Ok(())
}
/// Collects every indirect annotation reference listed in any page's `/Annots` array.
fn page_annot_refs(doc: &Document) -> std::collections::HashSet<ObjRef> {
let mut refs = std::collections::HashSet::new();
@@ -1304,19 +1409,6 @@ fn page_annot_refs(doc: &Document) -> std::collections::HashSet<ObjRef> {
refs
}
/// Removes annotation `r` from every page's `/Annots` list and replaces its indirect object with `Null`.
fn remove_annot_from_pages(doc: &mut Document, r: ObjRef) -> Result<(), pdfcraft_cos::CosError> {
for p in pdfcraft_model::pages(doc) {
let annots = p.dict.get(b"Annots").map(|a| doc.resolve(a)).and_then(|a| a.as_array().cloned()).unwrap_or_default();
if annots.iter().any(|a| a.as_ref() == Some(r)) {
let kept: Vec<Object> = annots.into_iter().filter(|a| a.as_ref() != Some(r)).collect();
doc.update_dict(p.obj, |pd| pd.set(b"Annots".to_vec(), Object::Array(kept)))?;
}
}
doc.set(r, Object::Null);
Ok(())
}
fn fix_annot_or_field(doc: &Document, nd: &mut Dict, is_annot: bool, sub: Option<&[u8]>, actions: &mut usize, flags: &mut usize) -> bool {
let mut changed = strip_actions(doc, nd);
*actions += changed as usize;
@@ -1413,8 +1505,10 @@ pub fn convert(doc: &mut Document, level: Level) -> Result<Report, pdfcraft_cos:
fixed.push("Cleared NeedAppearances".into());
}
// An sRGB output intent describes RGB and gray content only: a document with CMYK content
// needs a CMYK output condition, which only the user can choose (#667).
if !has_pdfa_intent(doc) && !uses_device_colour(doc, &objects(doc)).cmyk {
// needs a CMYK output condition, which only the user can choose (#667). Content that could
// not all be read may hold CMYK too, so it gets none either.
let colour = uses_device_colour(doc, &objects(doc));
if !has_pdfa_intent(doc) && !colour.cmyk && !colour.incomplete {
let mut icc = Dict::new();
icc.set(b"N".to_vec(), Object::Int(3));
let profile = doc.add(Object::Stream(Stream::flate(icc, &icc::srgb())));
@@ -1448,13 +1542,18 @@ pub fn convert(doc: &mut Document, level: Level) -> Result<Report, pdfcraft_cos:
actions += changed as usize;
convert_direct_page_annots(doc, &p, &mut actions, &mut flags, &mut removed)?;
}
let mut forbidden_annots = std::collections::HashSet::new();
for (r, o) in objects(doc) {
let Some(d) = dict_of(&o).cloned() else { continue };
let ty = d.name(b"Type").map(<[u8]>::to_vec);
let sub = d.name(b"Subtype").map(<[u8]>::to_vec);
let is_annot = matches!(&*o, Object::Dict(_)) && is_annotation(doc, &d, ty.as_deref(), sub.as_deref(), page_annots.contains(&r));
let is_annot = matches!(&*o, Object::Dict(_))
// A widget is an annotation whether or not it says `/Type /Annot` (the form reader
// finds it by its field), so its actions go the same way.
&& (is_annotation(doc, &d, ty.as_deref(), sub.as_deref(), page_annots.contains(&r)) || sub.as_deref() == Some(b"Widget"));
if is_annot && sub.as_deref().is_some_and(|s| FORBIDDEN_ANNOTS.contains(&s)) {
remove_annot_from_pages(doc, r)?;
// Taken off its page below, all of them in one pass over the pages.
forbidden_annots.insert(r);
removed += 1;
continue;
}
@@ -1489,6 +1588,7 @@ pub fn convert(doc: &mut Document, level: Level) -> Result<Report, pdfcraft_cos:
files += 1;
}
}
remove_from_pages(doc, &forbidden_annots)?;
// Forbidden actions left as objects of their own, or chained to by one, and those written
// directly in an /A elsewhere (an outline item's, say).
for (r, o) in objects(doc) {
+124
View File
@@ -452,6 +452,20 @@ fn forbidden_actions_chained_behind_allowed_ones_are_found_and_removed() {
build(&["<< /Type /Catalog /Pages 2 0 R >>", pages, page, &link(&format!("<< /S /GoTo /D [3 0 R /Fit] /Next {js} >>"))], ""),
// `/Next` refers to an array that holds the action directly.
build(&["<< /Type /Catalog /Pages 2 0 R >>", pages, page, &link("<< /S /GoTo /D [3 0 R /Fit] /Next 5 0 R >>"), &format!("[{js}]")], ""),
// `/Next` refers to the action itself, which carries `/P` and `/K` as a structure
// element would: those keys must not exempt it.
build(
&[
"<< /Type /Catalog /Pages 2 0 R >>",
pages,
page,
&link("<< /S /GoTo /D [3 0 R /Fit] /Next 5 0 R >>"),
"<< /S /JavaScript /JS (app.alert(1)) /P 3 0 R /K 0 >>",
],
"",
),
// A `/Next` array refers to the action.
build(&["<< /Type /Catalog /Pages 2 0 R >>", pages, page, &link("<< /S /GoTo /D [3 0 R /Fit] /Next [5 0 R] >>"), js], ""),
];
for (i, mut doc) in cases.into_iter().enumerate() {
let found = messages(&verify(&doc, Level::A2b)).contains(&"A JavaScript action isn't allowed");
@@ -495,6 +509,116 @@ fn an_output_intent_profile_header_is_read_within_a_size_cap() {
}
}
/// A widget the form reader finds by its field is an annotation whether or not it writes
/// `/Type /Annot`: conversion takes its additional actions off all the same.
#[test]
fn a_widget_without_a_type_loses_its_additional_actions() {
let pages = "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 200 200] >>";
let page = "<< /Type /Page /Parent 2 0 R /Annots [4 0 R] >>";
let widget = "<< /Subtype /Widget /Rect [0 0 10 10] /F 4 /T (f) /AA << /K << /S /JavaScript /JS (1) >> >> >>";
let mut doc = build(&["<< /Type /Catalog /Pages 2 0 R >>", pages, page, widget], "");
convert(&mut doc, Level::A2b).unwrap();
let w = doc.get(pdfcraft_cos::ObjRef::new(4, 0));
assert!(w.as_dict().is_some_and(|d| d.get(b"AA").is_none()), "{w:?}");
}
/// Forbidden annotations on one page are taken off it in one pass, all of them.
#[test]
fn forbidden_annotations_leave_their_page_together() {
let n = 300;
let annots: Vec<String> = (0..n).map(|i| format!("{} 0 R", i + 4)).collect();
let page = format!("<< /Type /Page /Parent 2 0 R /Annots [{} 2 0 R] >>", annots.join(" "));
let mut objs =
vec!["<< /Type /Catalog /Pages 2 0 R >>".to_string(), "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 200 200] >>".into(), page];
objs.extend((0..n).map(|_| "<< /Type /Annot /Subtype /Sound /Rect [0 0 0 0] /P 3 0 R >>".to_string()));
let refs: Vec<&str> = objs.iter().map(String::as_str).collect();
let mut doc = build(&refs, "");
let r = convert(&mut doc, Level::A2b).unwrap();
assert!(r.fixed.iter().any(|f| f.starts_with(&format!("{n}: removed multimedia"))), "{:?}", r.fixed);
let left = pdfcraft_model::pages(&doc)[0].dict.get(b"Annots").and_then(|a| doc.resolve(a).as_array().map(Vec::len));
assert_eq!(left, Some(1));
}
/// Content that can't be read may draw in DeviceCMYK: convert then adds no sRGB output intent.
#[test]
fn convert_adds_no_srgb_intent_when_colour_could_not_all_be_read() {
let mut doc = build(
&[
"<< /Type /Catalog /Pages 2 0 R >>",
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 200 200] >>",
"<< /Type /Page /Parent 2 0 R /Contents 4 0 R /Resources << >> >>",
// A /Filter that isn't a name can't be decoded: the content isn't read.
"<< /Length 9 /Filter 5 >>\nstream\nnot flate\nendstream",
],
"",
);
convert(&mut doc, Level::A2b).unwrap();
assert!(declared(&doc).output_intents.is_empty());
}
/// A `/Next` chain of arrays alone (each array naming the next) still reaches the chain limit,
/// so the walk's work is bounded however the arrays are linked.
#[test]
fn an_array_only_next_chain_is_too_deeply_chained() {
let mut doc = Document::new_empty();
let mut next = Object::Array(Vec::new());
for _ in 0..2 * MAX_ACTION_CHAIN {
next = Object::Array(vec![Object::Ref(doc.add(next))]);
}
let mut action = Dict::new();
action.set(b"S".to_vec(), Object::name("URI"));
action.set(b"Next".to_vec(), Object::Ref(doc.add(next)));
assert_eq!(chain_forbidden(&doc, &action).as_deref(), Some("too deeply chained"));
// A short chain of arrays is read through.
let mut short = Object::Array(Vec::new());
for _ in 0..10 {
short = Object::Array(vec![Object::Ref(doc.add(short))]);
}
action.set(b"Next".to_vec(), Object::Ref(doc.add(short)));
assert_eq!(chain_forbidden(&doc, &action), None);
}
/// A direct `/Next` array wider than the chain limit is refused as soon as it is charged, and a
/// `/Next` that reaches its array through a reference alias is read through it.
#[test]
fn a_wide_direct_next_array_is_refused_and_an_alias_is_followed() {
let uri = || {
let mut d = Dict::new();
d.set(b"S".to_vec(), Object::name("URI"));
d
};
let mut action = uri();
action.set(b"Next".to_vec(), Object::Array((0..=MAX_ACTION_CHAIN).map(|_| Object::Dict(uri())).collect()));
let doc = Document::new_empty();
assert_eq!(chain_forbidden(&doc, &action).as_deref(), Some("too deeply chained"));
// `/Next` -> 1 0 R -> 2 0 R -> [ << /S /JavaScript >> ]
let mut doc = Document::new_empty();
let mut js = Dict::new();
js.set(b"S".to_vec(), Object::name("JavaScript"));
let list = doc.add(Object::Array(vec![Object::Dict(js)]));
let alias = doc.add(Object::Ref(list));
let mut action = uri();
action.set(b"Next".to_vec(), Object::Ref(alias));
assert_eq!(chain_forbidden(&doc, &action).as_deref(), Some("JavaScript"));
}
/// Every distinct output intent is declared, past eight; an identifier longer than any real one
/// keeps its start.
#[test]
fn every_output_intent_is_declared_with_its_identifier_cut_to_the_bound() {
let long = "x".repeat(4 * MAX_IDENTIFIER_BYTES);
let intents: Vec<String> = (0..9)
.map(|i| {
format!("<< /Type /OutputIntent /S /GTS_PDFA1 /OutputConditionIdentifier ({}) >>", if i == 8 { long.clone() } else { format!("c{i}") })
})
.collect();
let catalog = format!("<< /Type /Catalog /Pages 2 0 R /OutputIntents [{}] >>", intents.join(" "));
let doc = build(&[catalog.as_str(), "<< /Type /Pages /Kids [] /Count 0 >>"], "");
let d = declared(&doc);
assert_eq!(d.output_intents.len(), 9);
assert_eq!(d.output_intents[8].len(), MAX_IDENTIFIER_BYTES);
}
#[test]
fn typeless_annotations_indexed_cmyk_and_indirect_filter_elements_are_handled() {
// Annotations in /Annots that omit optional /Type /Annot and /P (while keeping required /Subtype
+4 -1
View File
@@ -130,7 +130,10 @@ Text is placed with the font and size set by `Tf` or by an ExtGState's `/Font` t
form XObject starts from the text state of the content that draws it. Content that can't be
decoded makes the operation fail rather than leave it unredacted, and so does an inline image the
renderer's tokenizer reads no image for (`RedactError::Unreadable`): where the page's operators
resume after it would be a guess. A Redact annotation with neither a usable `/QuadPoints` array nor a usable
resume after it would be a guess. So do bytes the content parser can't read, in the page's content
or in a form under an area (a stray `)` or `}` in a `TJ` array, say): the interpreter reads past
them, so text they hide, which other readers may draw, would be neither found nor removed. Remove
hidden information refuses a page for both too, in whatever content it walks. A Redact annotation with neither a usable `/QuadPoints` array nor a usable
`/Rect` makes it fail with `RedactError::UnreadableMark` before anything changes, instead of
skipping that mark. The count covers the marks on the pages being applied.
+68 -11
View File
@@ -139,10 +139,18 @@ pub(crate) struct Output {
/// Apply mode met vertical-writing text (which it cannot remove) while a redaction region was
/// in force: the operation must fail closed rather than leave that text under the mark.
pub vertical: bool,
/// Apply mode met text in a font whose CMap dropped codespace ranges while a redaction region
/// was in force: which text its strings hold is a guess, so the operation must fail closed.
pub dropped_codes: bool,
/// The content holds an inline image the renderer reads no image for
/// ([`pdfcraft_content::Parsed::ambiguous_images`]): what this scope placed after it may not
/// be what the page shows, so a redaction must not trust it.
pub ambiguous: bool,
/// The content holds bytes the parser can't read ([`pdfcraft_content::Parsed::skipped`]), in
/// this scope or a nested form: the walk reads past them, so text they hide (a stray `)` in a
/// `TJ` array, say), which other readers may still draw, is neither found nor removed, and a
/// rewrite would drop the bytes but keep the strings. A redaction must not trust it.
pub unparsed: bool,
pub tag_changes: Vec<(ObjRef, ObjRef, HashSet<i64>, HashSet<i64>)>,
pub error: Option<CosError>,
}
@@ -407,6 +415,7 @@ fn process_from(doc: &mut Document, scope: &mut Scope<'_>, streams: &[Vec<u8>],
let joined = Pieces::join(streams);
let mut parsed = joined.parse();
walk.out.ambiguous = parsed.ambiguous_images > 0;
walk.out.unparsed = parsed.skipped > 0;
// A rewritten piece loses its comments, so keep where they began and ended: a comment that
// ran on into the next piece still hides that piece's first line.
let comment_edges = joined.comment_edges(&parsed);
@@ -571,7 +580,12 @@ impl Walk {
Some(op)
}
b"cs" | b"CS" => {
if op.name(0) != Some(b"Pattern") {
// A Pattern space is told by the name `/Pattern` alone: one named through the
// resources' `/ColorSpace` clears the pattern, which the app's renderer keeps and
// Poppler doesn't (`cs` resets the colour, ISO 32000-2 §8.6.8). Looking the name up
// at each `cs` wants a cache for the page: a `/ColorSpace` too large for the
// document to keep is parsed again at each read.
if op.last_name() != Some(b"Pattern") {
if o == b"cs" {
self.gs.fill_pattern = None;
} else {
@@ -598,8 +612,12 @@ impl Walk {
let o = op.op.as_slice();
let pts: Vec<(f64, f64)> = match o {
b"re" => op.nums::<4>().map(|[x, y, w, h]| vec![(x, y), (x + w, y), (x, y + h), (x + w, y + h)]).unwrap_or_default(),
b"h" | b"W" | b"W*" => Vec::new(),
_ => op.operands.iter().filter_map(Object::as_f64).collect::<Vec<_>>().as_chunks::<2>().0.iter().map(|p| (p[0], p[1])).collect(),
// Each takes its points from the end, as the renderer reads them: a surplus before
// them is ignored, not read as a point.
b"m" | b"l" => op.nums::<2>().map(|[x, y]| vec![(x, y)]).unwrap_or_default(),
b"c" => op.nums::<6>().map(|[x1, y1, x2, y2, x3, y3]| vec![(x1, y1), (x2, y2), (x3, y3)]).unwrap_or_default(),
b"v" | b"y" => op.nums::<4>().map(|[x1, y1, x2, y2]| vec![(x1, y1), (x2, y2)]).unwrap_or_default(),
_ => Vec::new(),
};
for (x, y) in pts {
let (u, v) = self.gs.ctm.apply(x, y);
@@ -633,9 +651,12 @@ impl Walk {
piece.changed = true;
scope.report.paths_removed += 1;
if scope.covered(b) && clips {
// Keep the clipping, drop the painting.
piece.ops.extend(body);
piece.ops.push(Op::new("n", vec![]));
// Everything this clip lets through is under a mark, so an empty clip hides the same
// content. The original outline is confidential and must not stay in the stream.
for o in ["re", "W", "n"] {
let operands = if o == "re" { vec![num(0.0); 4] } else { vec![] };
piece.ops.push(Op::new(o, operands));
}
}
// Partial vector redaction must not retain underlying drawing commands
// behind clipping (F-008). Refuse partial clip retention and remove the path.
@@ -656,10 +677,10 @@ impl Walk {
}
b"Tf" => self.select_font(doc, scope, op),
_ => {
if let Some((font, vertical, size)) = op.name(0).and_then(|n| extgstate_font(doc, scope, &self.ext_gstates, n, &self.fallback)) {
if let Some((font, vertical, size)) = op.last_name().and_then(|n| extgstate_font(doc, scope, &self.ext_gstates, n, &self.fallback)) {
(self.gs.font, self.gs.vertical, self.gs.size) = (font, vertical, size);
// As for `Tf`: a Type 3 font without /Resources paints through this scope's.
self.gs.type3_inherits = op.name(0).is_some_and(|n| extgstate_type3_inherits(doc, &self.ext_gstates, n));
self.gs.type3_inherits = op.last_name().is_some_and(|n| extgstate_type3_inherits(doc, &self.ext_gstates, n));
}
}
}
@@ -764,6 +785,14 @@ impl Walk {
{
self.out.vertical = true;
}
if self.gs.font.codespaces_dropped
&& scope.mode == Mode::Apply
&& scope.hidden_text.is_none()
&& !scope.rects.is_empty()
&& items.iter().any(|o| matches!(o, Object::String(s) if !s.bytes.is_empty()))
{
self.out.dropped_codes = true;
}
let (new_items, removed) = show(scope, &self.gs, &mut self.tm, &items);
if removed == 0 {
return Some(op);
@@ -864,7 +893,8 @@ fn clean_replacements(
if !op.is("BDC") || !affected.contains(&op.span.start) {
continue;
}
let property = match op.operands.get(1) {
// The property list is the last operand, as the renderer reads it.
let property = match op.back(0) {
Some(Object::Name(name)) => properties.get(name).map(|p| doc.resolve(p)),
Some(p) => Some(doc.resolve(p)),
None => None,
@@ -874,7 +904,7 @@ fn clean_replacements(
for key in [&b"ActualText"[..], b"Alt", b"E", b"T"] {
stripped |= dict.remove(key).is_some();
}
if stripped && let Some(property) = op.operands.get_mut(1) {
if stripped && let Some(property) = op.operands.last_mut() {
*property = Object::Dict(dict);
*changed = true;
report.replacement_text += 1;
@@ -1071,7 +1101,32 @@ fn xobject(
}
}
Some(b"Form") => {
let m = s.dict.get(b"Matrix").and_then(|m| Matrix::from_operands(doc.resolve(m).as_array()?)).unwrap_or_default();
// Read as the proof reads it, entries by reference included: read as the identity, a
// form moved onto a mark would be tested against the wrong place and never walked.
let m = match crate::verify::matrix_of(doc, &s.dict) {
Ok(m) => m,
// Not six numbers given directly or through one reference. Removing hidden layers alone never asks where content lands, so
// the form is walked as it stands.
Err(()) if scope.everywhere() && scope.hidden_text.is_none() => Matrix::IDENTITY,
// Otherwise where the form draws, and so whether it reaches a mark or leaves the
// page, can't be told. Apply refuses the page, and the scans count it, as for a
// form past the page's budget below.
Err(()) => {
if scope.mode == Mode::Apply {
out.error = Some(CosError::Syntax {
offset: 0,
detail:
"a form XObject's /Matrix isn't six numbers given directly or through one reference, so where it draws can't be told"
.into(),
});
} else if scope.everywhere() {
scope.layer_blocks += 1;
} else {
out.residue += 1;
}
return None;
}
};
let fctm = m.then(&gs.ctm);
let bbox = s.dict.get(b"BBox").and_then(|b| {
let v: Vec<f64> = doc.resolve(b).as_array()?.iter().filter_map(Object::as_f64).collect();
@@ -1149,7 +1204,9 @@ fn xobject(
scope.fonts = saved_fonts;
out.residue += inner.residue;
out.vertical |= inner.vertical;
out.dropped_codes |= inner.dropped_codes;
out.ambiguous |= inner.ambiguous;
out.unparsed |= inner.unparsed;
out.doomed.extend_from_slice(&inner.doomed);
out.retired_properties.extend(inner.retired_properties);
// A Type 3 glyph without resources shown inside the form may paint with the page's
+4 -2
View File
@@ -225,8 +225,10 @@ pub(super) fn strip_hidden_layers(doc: &Document, scope: &mut Scope<'_>, ops: Ve
match op.op.as_slice() {
b"BDC" | b"BMC" => {
let this = op.is("BDC")
&& op.name(0) == Some(b"OC")
&& match op.operands.get(1) {
// The tag and the property list are the last two operands, as the renderer
// reads them: `(x) /OC /MC0 BDC` is a layer's block too.
&& op.name_back(1) == Some(b"OC")
&& match op.back(0) {
Some(Object::Name(n)) => props.get(n).is_some_and(|o| scope.layer_hidden(doc, o)),
Some(o) => scope.layer_hidden(doc, o),
None => false,
+7 -5
View File
@@ -9,8 +9,9 @@ use super::{
/// by a form without /Resources of its own, which draws through `xo` too. Such forms are read
/// within `budget`, what is left of the page's allowance ([`resource_ops`]). Fails, as the cleanup
/// of the fonts and properties these forms draw with does, when that can't be told: such a form
/// doesn't decode (an image codec or a /Filter it can't run, say) or runs past `budget`, the walk
/// passes 2,000,000 operators, or the parser can't read all of such a form or of `content`.
/// doesn't decode (an image codec or a /Filter it can't run, say) or runs past `budget` (for the
/// fonts' cleanup, an allowance of its own when no Type 3 font is listed), the walk passes
/// 2,000,000 operators, or the parser can't read all of such a form or of `content`.
/// Corrupt data in such a form is read, tolerantly, up to the damage, which may be nothing.
pub(crate) fn prune(doc: &Document, budget: &mut DecodeBudget, xo: &mut Dict, replaced: &[Vec<u8>], content: &[Vec<u8>]) -> Result<(), CosError> {
if replaced.is_empty() {
@@ -357,7 +358,7 @@ fn prune_retired_properties(doc: &Document, res: &mut Dict, names: &[Vec<u8>], c
// Each is one page's content or one form's, with the allowance of a page.
for op in resource_ops(doc, &mut DecodeBudget::page(), res, content)? {
if matches!(op.op.as_slice(), b"BDC" | b"DP")
&& let Some(name) = op.name(1)
&& let Some(name) = op.last_name()
{
used.insert(name.to_vec());
}
@@ -473,7 +474,8 @@ pub(super) fn clip_out(rects: &[[f64; 4]], ctm: &Matrix, around: [f64; 4]) -> Op
/// The operators of `content`, and of every form without /Resources of its own that it draws
/// through `res`, nested ones too: what draws with these resources. Each such form is read once,
/// with its `/DecodeParms` given by reference, its decoded bytes charged to `budget`, so the
/// cleanups of one page that walk the same forms spend one allowance between them. An error
/// cleanups of one page that walk the same forms spend one allowance between them (all but the
/// fonts' cleanup when no Type 3 font is listed, which has one of its own). An error
/// when that can't all be read: the parser can't read all of `content` or of such a form, the walk
/// passes 2,000,000 operators, or such a form doesn't decode or runs past `budget`. Operators are
/// read one at a time, so the walk stops at one past the limit rather than holding them all.
@@ -520,7 +522,7 @@ pub(crate) fn prune_properties(doc: &Document, budget: &mut DecodeBudget, res: &
let ops = resource_ops(doc, budget, res, content)?;
let names: Vec<Vec<u8>> = properties.iter().map(|(n, _)| n.to_vec()).collect();
for name in names {
if !ops.iter().any(|op| matches!(op.op.as_slice(), b"BDC" | b"DP") && op.name(1) == Some(&name))
if !ops.iter().any(|op| matches!(op.op.as_slice(), b"BDC" | b"DP") && op.last_name() == Some(&name))
&& let Some(value) = properties.remove(&name)
{
retired.push(value);
+185 -55
View File
@@ -75,6 +75,10 @@ pub enum RedactError {
"page {0} has vertical-writing text while a redaction mark is pending, and PdfCraft cannot tell whether that text lies under the mark yet, so nothing was changed"
)]
VerticalText(usize),
#[error(
"page {0} shows text in a font whose CMap has codespace ranges PdfCraft could not read, so it cannot tell which text a string holds while a redaction mark is pending; nothing was changed"
)]
DroppedCodespace(usize),
#[error(
"redaction appearance has invalid geometry or exceeds the 8 MiB budget; reduce the marked area, turn off repeated text or apply fewer pages at once (nothing was redacted)"
)]
@@ -247,6 +251,19 @@ pub(crate) fn annots_of(doc: &Document, page: &Dict) -> Vec<Object> {
page.get(b"Annots").map(|a| doc.resolve(a)).and_then(|a| a.as_array().cloned()).unwrap_or_default()
}
/// An annotation's `/Subtype`, resolved: it may be an indirect reference (ISO 32000-2 §7.3.10),
/// and the audit reads it that way, so a mark it reports must not be one [`apply`] passes over.
pub(crate) fn subtype(doc: &Document, d: &Dict) -> Option<Vec<u8>> {
d.get(b"Subtype").and_then(|s| doc.resolve(s).as_name().map(<[u8]>::to_vec))
}
/// The pop-up `d` names (`/Popup`), when it is one: it goes with `d`. Anything else it might name
/// (a mark on another page, say) is left alone.
fn named_popup(doc: &Document, d: &Dict) -> Option<ObjRef> {
let r = d.reference(b"Popup")?;
doc.get(r).as_dict().is_some_and(|p| subtype(doc, p).as_deref() == Some(b"Popup")).then_some(r)
}
/// Every annotation the pages list. Compared before and after a removal, what is no longer listed
/// leaves the structure tree too ([`tags::drop_object_refs`]).
pub(crate) fn listed_annotations(doc: &Document) -> HashSet<ObjRef> {
@@ -267,14 +284,14 @@ pub(crate) fn marks_checked(doc: &Document) -> (Vec<Mark>, Vec<usize>) {
let Some(r) = a.as_ref() else {
// A mark written in place has no object to find, apply or remove: refuse it
// rather than apply the others as if it were not there.
if doc.resolve(&a).as_dict().is_some_and(|d| d.name(b"Subtype") == Some(b"Redact")) {
if doc.resolve(&a).as_dict().is_some_and(|d| subtype(doc, d).as_deref() == Some(b"Redact")) {
unreadable.push(pi);
}
continue;
};
let obj = doc.get(r);
let Some(d) = obj.as_dict() else { continue };
if d.name(b"Subtype") != Some(b"Redact") {
if subtype(doc, d).as_deref() != Some(b"Redact") {
continue;
}
let mut rects: Vec<[f64; 4]> = quad_points(doc, d)
@@ -580,18 +597,41 @@ fn apply_within(doc: &mut Document, pages: Option<&[usize]>, images: pdfcraft_co
let annots = annots_of(doc, &p.dict);
let mut kept = Vec::with_capacity(annots.len());
for a in &annots {
let Some(r) = a.as_ref() else {
kept.push(a.clone());
continue;
};
let obj = doc.get(r);
// An entry written in place is read as one listed by reference: its `/IRT` or
// `/Parent` keeps a removed comment reachable all the same, and it has its own text.
let obj = doc.resolve(a);
let Some(d) = obj.as_dict() else {
kept.push(a.clone());
continue;
};
let is_reply =
d.get(b"IRT").and_then(Object::as_ref).is_some_and(|x| removed_everywhere.contains(&x)) && d.name(b"Subtype") != Some(b"Widget");
let is_popup = d.get(b"Parent").and_then(Object::as_ref).is_some_and(|x| removed_everywhere.contains(&x));
let is_reply = d.reference(b"IRT").is_some_and(|x| removed_everywhere.contains(&x)) && subtype(doc, d).as_deref() != Some(b"Widget");
let is_popup = d.reference(b"Parent").is_some_and(|x| removed_everywhere.contains(&x));
let Some(r) = a.as_ref() else {
if is_reply || is_popup {
grew = true;
if is_reply {
report.annotations += 1;
}
// Its appearance can be shared with an annotation that stays elsewhere.
if !appearance_scan_limit {
match appearance_refs(doc, d) {
Some(references) => removed_appearances.extend(references),
None => appearance_scan_limit = true,
}
if removed_appearances.len() > 16_384 {
appearance_scan_limit = true;
removed_appearances.clear();
}
}
// It has no reference to remove elsewhere; the pop-up it names has.
if let Some(p) = named_popup(doc, d) {
removed_everywhere.insert(p);
}
} else {
kept.push(a.clone());
}
continue;
};
if removed_everywhere.contains(&r) || is_reply || is_popup {
// A reply or pop-up removed here can share its appearance with an annotation
// that stays on an unselected page, like one removed under a mark: the
@@ -638,6 +678,30 @@ fn apply_within(doc: &mut Document, pages: Option<&[usize]>, images: pdfcraft_co
report.fields += 1;
}
}
// A widget written in place on another page names its deleted field through `/Parent`, which
// would keep the field and its value in the file: it goes with the field.
if !doomed_fields.is_empty() {
for p in pdfcraft_model::pages(doc) {
let annots = annots_of(doc, &p.dict);
let kept: Vec<Object> = annots
.iter()
.filter(|a| {
a.as_ref().is_some() || !matches!(&**a, Object::Dict(d) if d.reference(b"Parent").is_some_and(|f| doomed_fields.contains(&f)))
})
.cloned()
.collect();
if kept.len() != annots.len() {
report.annotations += annots.len() - kept.len();
doc.update_dict(p.obj, |d| {
if kept.is_empty() {
d.remove(b"Annots");
} else {
d.set(b"Annots".to_vec(), Object::Array(kept));
}
})?;
}
}
}
// 3a. A tagged PDF's structure tree still points at the removed comments and widgets
// (`/OBJR`, #2874): drop those references, or a full rewrite keeps them reachable, the
@@ -789,10 +853,15 @@ fn redact_page_content(
if out.vertical {
return Err(RedactError::VerticalText(pi + 1));
}
if out.dropped_codes {
return Err(RedactError::DroppedCodespace(pi + 1));
}
// An inline image the renderer reads no image for (no `EI` it accepts, or parameters it
// can't read): where the page's operators resume after it is a guess, so neither removal
// nor the verify pass can be trusted on this page.
if out.ambiguous {
// nor the verify pass can be trusted on this page. Likewise bytes the parser can't read in
// what the walk read, the page's content or a form under a mark: text they hide is neither
// found nor removed, and other readers may draw it.
if out.ambiguous || out.unparsed {
return Err(RedactError::Unreadable(pi + 1));
}
doomed_xobjects.extend_from_slice(&out.doomed);
@@ -883,30 +952,66 @@ fn remove_page_annotations(
page_marks: &[&Mark],
) -> Result<(), RedactError> {
let Applying { report, doomed_fields, widget_owner, removed_everywhere, removed_appearances, appearance_scan_limit, .. } = applying;
// 2. Annotations: the marks, and whatever lies under them (with their pop-ups).
// 2. Annotations: the marks, and whatever lies under them (with their pop-ups). An entry
// written in place (a dictionary in `/Annots`, not a reference) is judged like any other: its
// `/Contents` and `/IRT` stay in the file for as long as the page lists it.
let annots = annots_of(doc, &doc.get(page.obj).as_dict().cloned().unwrap_or_default());
/// What decides an entry's fate, read once.
struct Entry {
r: Option<ObjRef>,
widget: bool,
irt: Option<ObjRef>,
parent: Option<ObjRef>,
popup: Option<ObjRef>,
}
let entries: Vec<Option<Entry>> = annots
.iter()
.map(|a| {
let obj = doc.resolve(a);
let d = obj.as_dict()?;
Some(Entry {
r: a.as_ref(),
widget: subtype(doc, d).as_deref() == Some(b"Widget"),
irt: d.reference(b"IRT"),
parent: d.reference(b"Parent"),
popup: named_popup(doc, d),
})
})
.collect();
let mut removed: Vec<ObjRef> = Vec::new();
for a in &annots {
let Some(r) = a.as_ref() else { continue };
let obj = doc.get(r);
// Entries written in place that go, by position in `/Annots`.
let mut inline_gone = vec![false; annots.len()];
for (i, a) in annots.iter().enumerate() {
let obj = doc.resolve(a);
let Some(d) = obj.as_dict() else { continue };
let subtype = d.name(b"Subtype").unwrap_or(b"");
if subtype == b"Redact" {
if page_marks.iter().any(|m| m.obj == r) {
let r = a.as_ref();
let kind = subtype(doc, d).unwrap_or_default();
if kind == b"Redact" {
// A mark written in place was refused before anything changed.
if let Some(r) = r
&& page_marks.iter().any(|m| m.obj == r)
{
removed.push(r);
}
continue;
}
if subtype == b"Popup" {
if kind == b"Popup" {
continue;
}
if rect_of(doc, d.get(b"Rect")).is_some_and(|b| rects.iter().any(|x| pdfcraft_content::overlaps(*x, b, 0.0))) {
removed.push(r);
if subtype == b"Widget" {
if let Some((_, field)) = widget_owner.iter().find(|(w, _)| *w == r)
&& !doomed_fields.contains(field)
match r {
Some(r) => removed.push(r),
None => inline_gone[i] = true,
}
if kind == b"Widget" {
// A widget written in place has no reference of its own; its `/Parent` is the field,
// even one no referenced widget belongs to (it then has no entry in `widget_owner`).
// Step 3 deletes only what the form lists as a field, so any `/Parent` is safe here.
let owner = r.and_then(|r| widget_owner.iter().find(|(w, _)| *w == r).map(|(_, f)| *f)).or_else(|| d.reference(b"Parent"));
if let Some(field) = owner
&& !doomed_fields.contains(&field)
{
doomed_fields.push(*field);
doomed_fields.push(field);
}
} else {
report.annotations += 1;
@@ -917,29 +1022,25 @@ fn remove_page_annotations(
// those: a reply placed elsewhere would keep its parent — the comment and the QuadPoints
// of the redacted words — in the file through its `/IRT` (#2659). Each pass removes at
// least one more annotation of this page or stops, so it ends.
let replies: Vec<(ObjRef, ObjRef)> = annots
.iter()
.filter_map(Object::as_ref)
.filter_map(|r| {
let obj = doc.get(r);
let d = obj.as_dict()?;
(d.name(b"Subtype") != Some(b"Widget")).then_some(())?;
Some((r, d.get(b"IRT").and_then(Object::as_ref)?))
})
.collect();
loop {
let before = removed.len();
for (r, parent) in &replies {
if !removed.contains(r) && removed.contains(parent) {
removed.push(*r);
report.annotations += 1;
let mut grew = false;
for (i, e) in entries.iter().enumerate() {
let Some(e) = e else { continue };
let gone = e.r.map_or(inline_gone[i], |r| removed.contains(&r));
if gone || e.widget || !e.irt.is_some_and(|p| removed.contains(&p)) {
continue;
}
match e.r {
Some(r) => removed.push(r),
None => inline_gone[i] = true,
}
report.annotations += 1;
grew = true;
}
if removed.len() == before {
if !grew {
break;
}
}
removed_everywhere.extend(removed.iter().copied());
// A removed annotation's appearance streams can be shared with a kept one on another page,
// which would keep a pruned pattern's cell reachable: remember them for the pattern guard.
for reference in &removed {
@@ -959,24 +1060,53 @@ fn remove_page_annotations(
}
}
}
// Pop-ups dropped with their parent below count too: a reply on another page may answer one.
for a in &annots {
let Some(r) = a.as_ref() else { continue };
if doc.get(r).as_dict().and_then(|d| d.get(b"Parent")).and_then(Object::as_ref).is_some_and(|p| removed.contains(&p)) {
removed_everywhere.insert(r);
// An entry written in place that goes keeps no reference, but its appearances count as well.
for (i, a) in annots.iter().enumerate() {
if *appearance_scan_limit {
break;
}
if let (true, Some(annotation)) = (inline_gone[i], doc.resolve(a).as_dict()) {
match appearance_refs(doc, annotation) {
Some(references) => removed_appearances.extend(references),
None => *appearance_scan_limit = true,
}
if removed_appearances.len() > 16_384 {
*appearance_scan_limit = true;
removed_appearances.clear();
}
}
}
// Pop-ups go with their annotation: those that name it (`/Parent`), and those it names
// (`/Popup`), the only link an annotation written in place can have to its pop-up.
let mut going: HashSet<ObjRef> = removed.iter().copied().collect();
for (i, e) in entries.iter().enumerate() {
let Some(e) = e else { continue };
let gone = e.r.map_or(inline_gone[i], |r| removed.contains(&r));
if gone {
going.extend(e.popup);
}
}
for (i, e) in entries.iter().enumerate() {
let Some(e) = e else { continue };
if e.parent.is_some_and(|p| removed.contains(&p)) {
match e.r {
Some(r) => {
going.insert(r);
}
None => inline_gone[i] = true,
}
}
}
// Pop-ups dropped with their parent count too: a reply on another page may answer one.
removed_everywhere.extend(going.iter().copied());
let kept: Vec<Object> = annots
.into_iter()
.filter(|a| {
let Some(r) = a.as_ref() else { return true };
if removed.contains(&r) {
return false;
}
// Pop-ups of removed annotations go too.
let obj = doc.get(r);
!obj.as_dict().and_then(|d| d.get(b"Parent")).and_then(Object::as_ref).is_some_and(|p| removed.contains(&p))
.enumerate()
.filter(|(i, a)| match a.as_ref() {
Some(r) => !going.contains(&r),
None => !inline_gone[*i],
})
.map(|(_, a)| a)
.collect();
doc.update_dict(page.obj, |d| {
if kept.is_empty() {
+11
View File
@@ -659,6 +659,17 @@ fn content_pass(doc: &mut Document, text: bool, layers: bool, write: bool) -> Re
if let Some(error) = out.error {
return Err(error.into());
}
// Bytes the parser can't read, or an inline image whose end is a guess: the walk reads past
// them, so what it reads around them may not be what other readers draw (hidden text in a
// broken `TJ` is neither found nor removed). As for content that doesn't decode, count the
// page so the removal runs and refuses it.
if out.unparsed || out.ambiguous {
if write {
return Err(RedactError::Unreadable(pi + 1));
}
total += 1;
continue;
}
let blocks = scope.layer_blocks;
let glyphs = scope.report.glyphs;
let retained_for_page = std::mem::take(&mut scope.retained_off_layers);
+23 -9
View File
@@ -35,6 +35,14 @@ impl Marked {
/// left are taken as changed (their descriptions go) rather than compared.
const MAX_COMPARED: usize = 1 << 28;
/// `f` of `o`, or of the object it refers to, without copying a direct one.
fn with_held<R>(doc: &Document, o: &Object, f: impl FnOnce(&Object) -> R) -> R {
match o {
Object::Ref(_) => f(&doc.resolve(o)),
o => f(o),
}
}
fn by_mcid(doc: &Document, resources: &Dict, data: &[u8]) -> Marked {
let mut out = Marked::default();
// Open sequences: the MCID with where its content starts in `ops` and the drawing operators
@@ -49,14 +57,22 @@ fn by_mcid(doc: &Document, resources: &Dict, data: &[u8]) -> Marked {
e.1 |= drawn > drawn_before;
}
};
// The named property lists, read once, and each name's MCID, read once: a stream can name one
// at every `BDC` of thousands, and reading an object again can parse it again, all of it (the
// document keeps an object larger than its cache only until it reads another). A direct one
// is read where it is.
let held = resources.get(b"Properties").filter(|p| matches!(p, Object::Ref(_))).map(|p| doc.resolve(p));
let named = held.as_deref().or_else(|| resources.get(b"Properties")).and_then(Object::as_dict);
let mut mcids: HashMap<Vec<u8>, Option<i64>> = HashMap::new();
for op in pdfcraft_content::parse(data).ops {
match op.op.as_slice() {
b"BDC" => {
let id = match op.operands.get(1) {
Some(Object::Name(n)) => resources.get(b"Properties").and_then(|p| {
let props = doc.resolve(p);
let prop = doc.resolve(props.as_dict()?.get(n)?);
prop.as_dict()?.int(b"MCID")
// The property list is the last operand, as the renderer reads it.
let id = match op.back(0) {
Some(Object::Name(n)) => *mcids.entry(n.to_vec()).or_insert_with(|| {
let prop = named?.get(n)?;
// A named property list may give its MCID by reference.
with_held(doc, prop, |prop| prop.as_dict()?.get(b"MCID").and_then(|id| with_held(doc, id, Object::as_int)))
}),
Some(p) => doc.resolve(p).as_dict().and_then(|d| d.int(b"MCID")),
_ => None,
@@ -86,9 +102,7 @@ fn by_mcid(doc: &Document, resources: &Dict, data: &[u8]) -> Marked {
}
let draws = match op.op.as_slice() {
b"Tj" | b"'" | b"\"" => op.operands.last().and_then(Object::as_string).is_some_and(|s| !s.bytes.is_empty()),
b"TJ" => {
op.operands.first().and_then(Object::as_array).is_some_and(|a| a.iter().any(|x| x.as_string().is_some_and(|s| !s.bytes.is_empty())))
}
b"TJ" => op.back(0).and_then(Object::as_array).is_some_and(|a| a.iter().any(|x| x.as_string().is_some_and(|s| !s.bytes.is_empty()))),
b"f" | b"F" | b"f*" | b"B" | b"B*" | b"b" | b"b*" | b"S" | b"s" | b"sh" | b"Do" | b"BI" => true,
_ => false,
};
@@ -139,7 +153,7 @@ fn mcid_of(doc: &Document, o: &Object, page: Option<ObjRef>, target: ObjRef, str
Object::Dict(m) if m.name(b"Type") == Some(b"MCR") => {
let pg = m.get(b"Pg").and_then(Object::as_ref).or(page);
let stm = m.get(b"Stm").and_then(Object::as_ref);
(pg == Some(target) && stm == stream.map(|s| s.0)).then(|| m.int(b"MCID")).flatten()
(pg == Some(target) && stm == stream.map(|s| s.0)).then(|| m.get(b"MCID").and_then(|id| doc.resolve(id).as_int())).flatten()
}
_ => None,
}
+262 -31
View File
@@ -1057,6 +1057,20 @@ fn partially_covered_vector_paths_do_not_leak_drawing_commands() {
assert!(c.contains("300 300 m\n350 350 l\nS"), "unaffected vector path must be kept: {c}");
}
#[test]
fn a_covered_clip_and_paint_path_leaves_an_empty_clip_not_its_outline() {
// The outline of a fully covered path that clips and paints is confidential geometry: only
// an empty clip may stay, and what follows is hidden as the covered clip would have hidden it.
let src = b"q 100 100 m 150 180 l 200 100 l h W f 300 300 50 50 re f Q";
let mut doc = one_page(src, "", vec![]);
mark(&mut doc, 0, &[[90.0, 90.0, 210.0, 190.0]], "");
let r = apply(&mut doc, None).unwrap();
assert_eq!(r.paths_removed, 1);
let c = content(&doc, 0);
assert!(!c.contains("150 180 l") && !c.contains("100 100 m"), "outline must not stay: {c}");
assert!(c.contains("0 0 0 0 re\nW\nn"), "an empty clip stays: {c}");
}
/// A chain of nested forms deeper than the pass can walk was removed from the page, taking
/// whatever else it drew with it even when nothing in it was marked. The limit now reaches as
/// deep as the renderer and Edit text read (50), so anything a reader can see can be walked;
@@ -3297,31 +3311,42 @@ fn image_and_a_tail(catalog: &str, image: &str, image_dict: &str, tail: &[u8]) -
])
}
/// The refusal of the check of what content still draws through its resources (`resource_ops`).
fn unread_content_refusal<T: std::fmt::Debug>(result: &Result<T, RedactError>) -> bool {
matches!(result, Err(RedactError::Cos(pdfcraft_cos::CosError::Syntax { detail, .. }))
if detail == "redaction could not fully read the content that uses these resources")
}
/// What the page draws can't be told when a content stream the redaction leaves as it was holds
/// bytes the parser can't read: the redaction of an image is refused, as it was already on a page
/// with fonts or properties to clean up.
/// What the page draws can't be told when content the redaction leaves as it was holds bytes the
/// parser can't read: the redaction of an image is refused. In a content stream of the page, the
/// walk reads past them and refuses the page itself (`Unreadable`). In a form without resources of
/// its own that lies away from the mark, which the walk doesn't enter, the check of what the page
/// still draws through its resources refuses it.
#[test]
fn unreadable_bytes_in_a_stream_left_as_it_was_refuse_the_redaction_of_an_image() {
for (tail, refused) in [(&b"q Q )"[..], true), (b"q Q", false)] {
let mut doc = image_and_a_tail("", "Im1", "", tail);
mark(&mut doc, 0, &[[0.0, 200.0, 300.0, 300.0]], "");
let result = apply(&mut doc, None);
if refused {
assert!(unread_content_refusal(&result), "{result:?}");
} else {
assert_eq!(result.map(|r| r.images_removed).ok(), Some(1));
}
let result = apply(&mut doc, None).map(|r| r.images_removed);
assert_eq!(result, if refused { Err(RedactError::Unreadable(1)) } else { Ok(1) });
}
let mut doc = image_and_a_tail("", "Im1", "", b"/Fm Do");
let bbox = Object::Array(vec![0.into(), 0.into(), 300.into(), 100.into()]);
let form = Dict::from_iter([(b"Type".to_vec(), Object::name("XObject")), (b"Subtype".to_vec(), Object::name("Form")), (b"BBox".to_vec(), bbox)]);
let form = doc.add(Object::Stream(Stream::from_raw(form, b"q Q )".to_vec())));
doc.update_dict(ObjRef::new(3, 0), |d| {
if let Some(Object::Dict(res)) = d.get_mut(b"Resources")
&& let Some(Object::Dict(xo)) = res.get_mut(b"XObject")
{
xo.set(b"Fm".to_vec(), Object::Ref(form));
}
})
.unwrap();
mark(&mut doc, 0, &[[0.0, 200.0, 300.0, 300.0]], "");
let result = apply(&mut doc, None);
assert!(
matches!(&result, Err(RedactError::Cos(pdfcraft_cos::CosError::Syntax { detail, .. })) if detail == "redaction could not fully inspect inherited form resources"),
"{result:?}"
);
}
/// Remove Hidden Information makes the same check: removing an off layer's image is refused on a
/// page whose drawing can't be told.
/// Remove Hidden Information refuses the same page: removing an off layer's image is refused on a
/// page whose drawing can't be told. Its walk reads every content stream, and refuses the page
/// itself.
#[test]
fn unreadable_bytes_in_a_stream_left_as_it_was_refuse_removing_a_hidden_image() {
use crate::sanitize::{Hidden, remove_hidden};
@@ -3329,7 +3354,7 @@ fn unreadable_bytes_in_a_stream_left_as_it_was_refuse_removing_a_hidden_image()
let mut doc = image_and_a_tail("/OCProperties << /OCGs [7 0 R] /D << /OFF [7 0 R] >> >>", "ImOC", "/OC 7 0 R", tail);
let result = remove_hidden(&mut doc, &[Hidden::HiddenLayers]);
if refused {
assert!(unread_content_refusal(&result), "{result:?}");
assert_eq!(result, Err(RedactError::Unreadable(1)));
} else {
assert!(result.unwrap().iter().any(|(h, n)| *h == Hidden::HiddenLayers && *n > 0));
}
@@ -3571,14 +3596,43 @@ fn what_content_draws_through_its_resources_is_read_within_its_allowance() {
}
}
/// An unused Type 3 font, listed as /T3 beside /F1 in the `/Font` of `holder`'s resources (a page's
/// or a form's), so that the font cleanup, which prunes only Type 3 fonts, charges its read of what
/// they draw to the page's allowance (without one it has an allowance of its own).
fn list_type3(doc: &mut Document, holder: ObjRef) {
let font = Object::Dict(Dict::from_iter([
(b"Type".to_vec(), Object::name("Font")),
(b"Subtype".to_vec(), Object::name("Type3")),
(b"FontBBox".to_vec(), Object::Array(vec![0.into(), 0.into(), 1000.into(), 1000.into()])),
(b"FontMatrix".to_vec(), Object::Array(vec![Object::Real(0.001), 0.into(), 0.into(), Object::Real(0.001), 0.into(), 0.into()])),
(b"CharProcs".to_vec(), Object::Dict(Dict::new())),
]));
let font = Object::Ref(doc.add(font));
let list = |d: &mut Dict| {
let Some(Object::Dict(res)) = d.get_mut(b"Resources") else { panic!("{holder:?} has resources") };
let Some(Object::Dict(fonts)) = res.get_mut(b"Font") else { panic!("{holder:?} lists fonts") };
fonts.set(b"T3".to_vec(), font);
};
match &*doc.get(holder) {
Object::Stream(s) => {
let mut s = s.clone();
list(&mut s.dict);
doc.set(holder, Object::Stream(s));
}
_ => doc.update_dict(holder, list).unwrap(),
}
}
/// The cleanups after the content walk spend what the walk left of the page's allowance, one
/// allowance between them. A form without resources of its own that crosses the mark is read by
/// the walk, then again by the check of what the page still draws and by the font cleanup: at
/// 100 MiB, three reads are more than the page's 256 MiB, and the redaction is refused; at
/// 50 MiB it goes on.
/// the walk, then again by the check of what the page still draws and by the font cleanup, which
/// charges the page's allowance when the page lists a Type 3 font: at 100 MiB, three reads are more
/// than the page's 256 MiB, and the redaction is refused; at 50 MiB it goes on. With no Type 3 font
/// the font cleanup's read has an allowance of its own, so the page's pays for two reads of
/// 100 MiB, and the redaction goes on.
#[test]
fn the_cleanups_after_the_content_walk_spend_what_it_left_of_the_pages_allowance() {
for (mib, refused) in [(100, true), (50, false)] {
for (mib, type3, refused) in [(100, true, true), (50, true, false), (100, false, false)] {
let blank = pdfcraft_filters::encode_flate(&vec![b' '; mib << 20]);
let mut doc = one_page(
b"q 50 0 0 50 20 230 cm /Im1 Do Q /FmBare Do",
@@ -3588,19 +3642,70 @@ fn the_cleanups_after_the_content_walk_spend_what_it_left_of_the_pages_allowance
stream("/Type /XObject /Subtype /Image /Width 1 /Height 1 /ColorSpace /DeviceGray /BitsPerComponent 8", b"o"),
],
);
if type3 {
list_type3(&mut doc, ObjRef::new(3, 0));
}
mark(&mut doc, 0, &[[0.0, 200.0, 300.0, 300.0]], "");
assert_eq!(apply(&mut doc, None).is_err(), refused, "{mib} MiB");
assert_eq!(apply(&mut doc, None).is_err(), refused, "{mib} MiB, Type 3: {type3}");
}
}
/// Text under the mark in a content stream that holds bytes the parser can't read, inside a `TJ`
/// array, is read past by the walk and would stay. The font cleanup's read of what the content
/// draws refuses such bytes in the streams and forms the walk leaves as they were, and makes that
/// read with any font listed, a Type 3 font or not (with none, on an allowance of its own). Here
/// the walk rewrites the text in the page's first stream and leaves the broken `TJ` as it was:
/// Apply Redactions refuses the page, whether that `TJ` is in the page's second stream or in a
/// form without resources of its own, and so does Remove Hidden Information. The cleanups run only
/// when the walk rewrites some of the page, and read what it rewrote as rewritten, so such bytes in
/// a stream it rewrites still go by, and so do those on a page it rewrites nothing of, unless the
/// document still lists a Type 3 font (`unlink_type3` then reads every page).
#[test]
fn text_beside_bytes_the_parser_cannot_read_refuses_the_redaction() {
use crate::sanitize::{Hidden, remove_hidden};
let page_of = |second: &[u8]| {
pdf(vec![
b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(),
b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(),
b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Contents [4 0 R 5 0 R] /Resources << /Font << /F1 6 0 R >> >> >>".to_vec(),
stream("", b"BT /F1 10 Tf 20 230 Td (SECRET) Tj ET"),
stream("", second),
FONT.replace("95 0 R", "7 0 R").into_bytes(),
widths(),
])
};
for tail in [
&b"BT /F1 10 Tf 20 260 Td [(TAIL) ) (SECRET)] TJ ET"[..],
b"BT /F1 10 Tf 20 260 Td [(TAIL) } (SECRET)] TJ ET",
b"BT /F1 10 Tf 20 260 Td [(TAILSECRET) )] TJ ET",
b"BT /F1 10 Tf 20 260 Td [) (TAILSECRET)] TJ ET",
] {
let mut doc = page_of(tail);
mark(&mut doc, 0, &[[0.0, 200.0, 300.0, 300.0]], "");
assert!(apply(&mut doc, None).is_err(), "{}", String::from_utf8_lossy(tail));
}
let mut doc = one_page(
b"BT /F1 10 Tf 20 230 Td (SECRET) Tj ET /FmBare Do",
"/XObject << /FmBare 7 0 R >>",
vec![stream("/Type /XObject /Subtype /Form /BBox [0 0 300 300]", b"BT /F1 10 Tf 20 260 Td [(TAIL) ) (SECRET)] TJ ET")],
);
mark(&mut doc, 0, &[[0.0, 200.0, 300.0, 300.0]], "");
assert!(apply(&mut doc, None).is_err(), "a form's text");
let mut doc = page_of(b"BT /F1 10 Tf 3 Tr 20 260 Td [(TAIL) ) (HIDDEN)] TJ ET");
doc.set(ObjRef::new(4, 0), Object::Stream(Stream::from_raw(Dict::new(), b"BT /F1 10 Tf 3 Tr 20 230 Td (HIDDEN) Tj ET".to_vec())));
assert!(remove_hidden(&mut doc, &[Hidden::HiddenText]).is_err(), "hidden text");
}
/// The cleanups of a form the redaction rewrites spend the page's allowance too. The rewritten
/// form has resources of its own, so the page's cleanups don't follow it, and draws through them a
/// form without any that crosses the mark: the walk reads that form, then the check of what the
/// rewritten form still draws and its font cleanup read it again. At 100 MiB, three reads are more
/// than the page's 256 MiB, and the redaction is refused; at 50 MiB it goes on.
/// rewritten form still draws and its font cleanup (when it lists a Type 3 font) read it again. At
/// 100 MiB, three reads are more than the page's 256 MiB, and the redaction is refused; at 50 MiB
/// it goes on. With no Type 3 font the font cleanup's read has an allowance of its own, so the
/// page's pays for two reads of 100 MiB, and the redaction goes on.
#[test]
fn the_cleanups_of_a_rewritten_form_spend_the_pages_allowance() {
for (mib, refused) in [(100, true), (50, false)] {
for (mib, type3, refused) in [(100, true, true), (50, true, false), (100, false, false)] {
let blank = pdfcraft_filters::encode_flate(&vec![b' '; mib << 20]);
let mut doc = one_page(
b"/FmText Do",
@@ -3613,20 +3718,25 @@ fn the_cleanups_of_a_rewritten_form_spend_the_pages_allowance() {
stream("/Type /XObject /Subtype /Form /BBox [0 0 300 300] /Filter /FlateDecode", &blank),
],
);
if type3 {
list_type3(&mut doc, ObjRef::new(7, 0));
}
mark(&mut doc, 0, &[[0.0, 200.0, 300.0, 300.0]], "");
assert_eq!(apply(&mut doc, None).is_err(), refused, "{mib} MiB");
assert_eq!(apply(&mut doc, None).is_err(), refused, "{mib} MiB, Type 3: {type3}");
}
}
/// Removing hidden text spends what its content walk left of the page's allowance too. The page
/// draws a form holding hidden text, which is rewritten, and a form without resources of its own:
/// the walk reads the second, then the check of what the page still draws and the font cleanup
/// read it again. At 100 MiB, three reads are more than the page's 256 MiB, and the removal is
/// refused; at 50 MiB it goes on.
/// (when the page lists a Type 3 font) read it again. At 100 MiB, three reads are more than the
/// page's 256 MiB, and the removal is refused; at 50 MiB it goes on. With no Type 3 font the font
/// cleanup's read has an allowance of its own, so the page's pays for two reads of 100 MiB, and the
/// removal goes on.
#[test]
fn removing_hidden_text_spends_what_the_content_walk_left_of_the_pages_allowance() {
use crate::sanitize::{Hidden, remove_hidden};
for (mib, refused) in [(100, true), (50, false)] {
for (mib, type3, refused) in [(100, true, true), (50, true, false), (100, false, false)] {
let blank = pdfcraft_filters::encode_flate(&vec![b' '; mib << 20]);
let mut doc = one_page(
b"/FmHidden Do /FmBare Do",
@@ -3636,7 +3746,10 @@ fn removing_hidden_text_spends_what_the_content_walk_left_of_the_pages_allowance
stream("/Type /XObject /Subtype /Form /BBox [0 0 300 300] /Filter /FlateDecode", &blank),
],
);
assert_eq!(remove_hidden(&mut doc, &[Hidden::HiddenText]).is_err(), refused, "{mib} MiB");
if type3 {
list_type3(&mut doc, ObjRef::new(3, 0));
}
assert_eq!(remove_hidden(&mut doc, &[Hidden::HiddenText]).is_err(), refused, "{mib} MiB, Type 3: {type3}");
}
}
@@ -6143,15 +6256,18 @@ fn unused_descriptions_in_shared_or_inherited_resources_are_retired() {
mod descriptions;
mod elsewhere;
mod form_matrix;
mod hidden_scope;
mod identification;
mod inline_images;
mod limits;
mod metadata_fail_closed;
mod metadata_matching;
mod operands_from_the_end;
mod property_retirement;
mod surviving_references;
mod text_state;
mod unparsed;
/// `[(FIRSTARR)] [(LASTARR)] TJ` is malformed (a surplus array operand), but the operator still
/// draws only the one immediately before it (LASTARR, 7 glyphs, 35 pt wide from x = 10) -- not
@@ -6589,6 +6705,78 @@ fn a_type3_text_layer_is_redacted_like_any_other() {
assert_eq!(under(&mut doc, 0, &[[98.0, 96.0, 112.0, 110.0]]), 0, "nothing is left under the mark");
}
#[test]
fn a_mark_whose_subtype_is_an_indirect_name_is_applied() {
// `/Subtype` may be an indirect reference (ISO 32000-2 §7.3.10); the audit reads it that way.
// Passing over the mark would leave the text under it while the others report success.
let objs: Vec<Vec<u8>> = vec![
b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(),
b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(),
b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> /Annots [7 0 R] >>".to_vec(),
stream("", b"BT /F1 10 Tf 20 20 Td (SECRET) Tj ET"),
FONT.replace("95 0 R", "6 0 R").into_bytes(),
widths(),
b"<< /Type /Annot /Subtype 8 0 R /Rect [10 10 90 40] >>".to_vec(),
b"/Redact".to_vec(),
];
let mut doc = pdf(objs);
assert_eq!(marks(&doc).len(), 1, "the mark is found");
let r = apply(&mut doc, None).unwrap();
assert_eq!(r.marks, 1);
assert!(r.glyphs >= 6, "the text under the mark went: {r:?}");
assert!(marks(&doc).is_empty(), "the mark itself went");
}
#[test]
fn a_mark_written_in_place_with_an_indirect_subtype_is_refused() {
let objs: Vec<Vec<u8>> = vec![
b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(),
b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(),
b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Contents 4 0 R /Annots [<< /Type /Annot /Subtype 5 0 R /Rect [10 10 70 40] >>] >>"
.to_vec(),
stream("", b"BT ET"),
b"/Redact".to_vec(),
];
let mut doc = pdf(objs);
mark(&mut doc, 0, &[[100.0, 100.0, 120.0, 120.0]], "");
assert!(matches!(apply(&mut doc, None), Err(RedactError::UnreadableMark(1))));
}
#[test]
fn annotations_written_in_place_go_when_covered_or_hanging_off_a_removed_one() {
// `/Annots` may hold dictionaries rather than references. One under the mark, a reply to a
// removed highlight on the same page and on another, and a reply to that inline comment's
// pop-up must all go; an inline comment elsewhere stays.
let objs: Vec<Vec<u8>> = vec![
b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(),
b"<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 >>".to_vec(),
b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Contents 5 0 R /Annots [6 0 R \
<< /Type /Annot /Subtype /Text /Rect [30 15 40 25] /Contents (INLINE-UNDER) /Popup 7 0 R >> \
<< /Type /Annot /Subtype /Text /Rect [250 250 270 270] /IRT 6 0 R /Contents (INLINE-REPLY) >> \
<< /Type /Annot /Subtype /Text /Rect [250 100 270 120] /Contents (INLINE-KEPT) >> 7 0 R] >>"
.to_vec(),
b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Contents 5 0 R /Annots [\
<< /Type /Annot /Subtype /Text /Rect [250 250 270 270] /IRT 6 0 R /Contents (OTHER-PAGE-INLINE-REPLY) >> \
<< /Type /Annot /Subtype /Text /Rect [200 200 220 220] /IRT 7 0 R /Contents (POPUP-INLINE-REPLY) >>] >>"
.to_vec(),
stream("", b"BT ET"),
b"<< /Type /Annot /Subtype /Highlight /Rect [20 20 60 30] /QuadPoints [20 30 60 30 20 20 60 20] /Contents (HIGHLIGHT-NOTE) >>".to_vec(),
b"<< /Type /Annot /Subtype /Popup /Rect [200 150 290 190] /Contents (INLINE-POPUP) >>".to_vec(),
];
let mut doc = pdf(objs);
mark(&mut doc, 0, &[[10.0, 10.0, 70.0, 40.0]], "");
let r = apply(&mut doc, None).unwrap();
assert_eq!(r.annotations, 5, "the highlight, the inline comment and the three replies: {r:?}");
let pages = pdfcraft_model::pages(&doc);
assert_eq!(annots_of(&doc, &pages[0].dict).len(), 1, "only the inline comment elsewhere stays");
assert!(annots_of(&doc, &pages[1].dict).is_empty(), "the replies leave page 2");
let bytes = write_full(&doc, &SaveOptions { object_streams: false, ..SaveOptions::default() }).unwrap();
for gone in [&b"HIGHLIGHT-NOTE"[..], b"INLINE-UNDER", b"INLINE-REPLY", b"OTHER-PAGE-INLINE-REPLY", b"POPUP-INLINE-REPLY", b"INLINE-POPUP"] {
assert!(!bytes.windows(gone.len()).any(|w| w == gone), "{} survived the save", String::from_utf8_lossy(gone));
}
assert!(bytes.windows(11).any(|w| w == b"INLINE-KEPT"));
}
#[test]
fn a_rewritten_form_xobject_drops_the_source_text_of_added_content() {
// A form drawing invisible text whose dictionary repeats it in /PCAdded.
@@ -6615,6 +6803,49 @@ fn a_redacted_form_xobject_drops_the_source_text_of_added_content() {
assert!(!bytes.windows(4).any(|w| w == b"1234"), "redacted text left in the saved file");
}
#[test]
fn an_inline_widget_takes_its_field_even_with_no_referenced_widget() {
// The field's only widget is written in place in `/Annots`, so no referenced widget names it:
// the field (and its value) must still go with the widget under the mark.
let objs: Vec<Vec<u8>> = vec![
b"<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [6 0 R] >> >>".to_vec(),
b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(),
b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Contents 4 0 R /Annots [<< /Type /Annot /Subtype /Widget /Rect [20 20 60 30] /Parent 6 0 R >>] >>"
.to_vec(),
stream("", b"BT ET"),
b"<< >>".to_vec(),
b"<< /FT /Tx /T (name) /V (FIELD-SECRET) >>".to_vec(),
];
let mut doc = pdf(objs);
mark(&mut doc, 0, &[[10.0, 10.0, 70.0, 40.0]], "");
let r = apply(&mut doc, None).unwrap();
assert_eq!(r.fields, 1, "{r:?}");
let bytes = write_full(&doc, &SaveOptions { object_streams: false, ..SaveOptions::default() }).unwrap();
assert!(!bytes.windows(12).any(|w| w == b"FIELD-SECRET"), "the field value survived the save");
}
#[test]
fn an_inline_widget_of_the_field_on_another_page_goes_with_it() {
// Two pages: the widget under the mark, and a sibling widget in place on the second page with the
// same `/Parent`. Deleting the field must not leave the sibling naming it.
let objs: Vec<Vec<u8>> = vec![
b"<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [7 0 R] >> >>".to_vec(),
b"<< /Type /Pages /Kids [3 0 R 5 0 R] /Count 2 >>".to_vec(),
b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Contents 4 0 R /Annots [<< /Type /Annot /Subtype /Widget /Rect [20 20 60 30] /Parent 7 0 R >>] >>"
.to_vec(),
stream("", b"BT ET"),
b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Contents 4 0 R /Annots [<< /Type /Annot /Subtype /Widget /Rect [200 200 260 230] /Parent 7 0 R >>] >>"
.to_vec(),
b"<< >>".to_vec(),
b"<< /FT /Tx /T (name) /V (SIBLING-SECRET) >>".to_vec(),
];
let mut doc = pdf(objs);
mark(&mut doc, 0, &[[10.0, 10.0, 70.0, 40.0]], "");
apply(&mut doc, None).unwrap();
let bytes = write_full(&doc, &SaveOptions { object_streams: false, ..SaveOptions::default() }).unwrap();
assert!(!bytes.windows(14).any(|w| w == b"SIBLING-SECRET"), "the field value survived through the sibling widget");
}
/// Private data takes an image's prepress data too: its OPI link to the original file and its
/// alternate images, which can be the unedited original.
#[test]
+131
View File
@@ -0,0 +1,131 @@
//! A form's `/Matrix` places what it draws. The redaction walk reads it as the proof does, the
//! array and each entry direct or by reference: read as the identity, a form moved onto a mark
//! was tested against the wrong place, never walked, and its text stayed.
use super::*;
/// One page drawing a form with resources of its own, whose content shows SECRET at (20, 60) in a
/// `/BBox` of [0 0 300 100], with `matrix` in its dictionary; object 8 is `extra`.
fn moved_form(matrix: &str, extra: &[u8]) -> Document {
one_page(
b"/Fm Do",
"/XObject << /Fm 7 0 R >>",
vec![
stream(
&format!("/Type /XObject /Subtype /Form /BBox [0 0 300 100] {matrix} /Resources << /Font << /F1 5 0 R >> >>"),
b"BT /F1 10 Tf 20 60 Td (SECRET) Tj ET",
),
extra.to_vec(),
],
)
}
/// Over the top third of the 300 × 300 page, where a move of 200 puts the text.
const MARK: [f64; 4] = [0.0, 200.0, 300.0, 300.0];
#[test]
fn a_form_moved_onto_a_mark_is_redacted_however_its_matrix_is_given() {
for (matrix, extra) in [
("/Matrix [1 0 0 1 0 200]", &b"null"[..]),
("/Matrix 8 0 R", b"[1 0 0 1 0 200]"),
("/Matrix [1 0 0 1 0 8 0 R]", b"200"),
("/Matrix [8 0 R 0 0 1 0 200]", b"1"),
] {
let mut doc = moved_form(matrix, extra);
mark(&mut doc, 0, &[MARK], "");
assert_eq!(apply(&mut doc, None).map(|r| r.glyphs), Ok(6), "{matrix} with 8 0 obj {}", String::from_utf8_lossy(extra));
}
}
/// A `/Matrix` of null, given directly or by a reference to null, is no `/Matrix` (ISO 32000-2
/// §7.3.9): the identity, under which the text lies below the mark and stays.
#[test]
fn a_form_whose_matrix_is_null_draws_where_it_stands() {
for (matrix, extra) in [("/Matrix null", &b"null"[..]), ("/Matrix 8 0 R", b"null")] {
let mut doc = moved_form(matrix, extra);
mark(&mut doc, 0, &[MARK], "");
assert_eq!(apply(&mut doc, None).map(|r| r.glyphs), Ok(0), "{matrix}");
let mut doc = moved_form(matrix, extra);
mark(&mut doc, 0, &[[0.0, 0.0, 300.0, 100.0]], "");
assert_eq!(apply(&mut doc, None).map(|r| r.glyphs), Ok(6), "{matrix}, marked where it stands");
}
}
/// A `/Matrix` that isn't six numbers: where the form draws can't be told, so neither can whether
/// it reaches the mark, and the page is refused.
#[test]
fn a_form_whose_matrix_is_not_six_numbers_is_refused() {
for (matrix, extra) in [
("/Matrix [1 0 0 1 0 (up)]", &b"null"[..]),
("/Matrix [1 0 0 1 0]", b"null"),
("/Matrix [1 0 0 1 0 8 0 R]", b"(up)"),
("/Matrix 8 0 R", b"(up)"),
] {
let mut doc = moved_form(matrix, extra);
mark(&mut doc, 0, &[MARK], "");
let result = apply(&mut doc, None);
assert!(
matches!(&result, Err(RedactError::Cos(pdfcraft_cos::CosError::Syntax { detail, .. })) if detail.contains("/Matrix")),
"{matrix} with 8 0 obj {}: {result:?}",
String::from_utf8_lossy(extra)
);
}
}
/// A reference to a reference, for the matrix or one of its entries: Poppler doesn't follow it (it
/// reads such a matrix as the identity, such an entry as 0), the app's renderer follows it and
/// reads the move, so where the form draws can't be told, and the page is refused, as for a matrix that isn't six numbers. Read as either,
/// a mark where the other reader shows the text would leave it in the file.
#[test]
fn a_form_whose_matrix_goes_through_a_reference_to_a_reference_is_refused() {
for (matrix, target) in [("/Matrix [1 0 0 1 0 8 0 R]", &b"200"[..]), ("/Matrix 8 0 R", b"[1 0 0 1 0 200]")] {
for mark_at in [MARK, [0.0, 0.0, 300.0, 100.0]] {
let form = stream(
&format!("/Type /XObject /Subtype /Form /BBox [0 0 300 100] {matrix} /Resources << /Font << /F1 5 0 R >> >>"),
b"BT /F1 10 Tf 20 60 Td (SECRET) Tj ET",
);
let mut doc = one_page(b"/Fm Do", "/XObject << /Fm 7 0 R >>", vec![form, b"9 0 R".to_vec(), target.to_vec()]);
mark(&mut doc, 0, &[mark_at], "");
let result = apply(&mut doc, None);
assert!(
matches!(&result, Err(RedactError::Cos(pdfcraft_cos::CosError::Syntax { detail, .. })) if detail.contains("/Matrix")),
"{matrix}, 8 0 obj 9 0 R, 9 0 obj {}, mark at {mark_at:?}: {result:?}",
String::from_utf8_lossy(target)
);
}
}
}
/// The scans count such a form as content that may remain: the verify pass under a mark, and
/// Remove Hidden Information's scan, whose removal then refuses the page.
#[test]
fn a_form_whose_matrix_is_not_six_numbers_counts_in_the_scans() {
use crate::sanitize::{Hidden, remove_hidden, scan};
let mut doc = moved_form("/Matrix [1 0 0 1 0 (up)]", b"null");
assert_eq!(under(&mut doc, 0, &[MARK]), 1);
let counts: std::collections::HashMap<Hidden, usize> = scan(&doc).into_iter().collect();
assert_eq!(counts[&Hidden::HiddenText], 1);
let removed = remove_hidden(&mut doc, &[Hidden::HiddenText]);
assert!(matches!(&removed, Err(RedactError::Cos(pdfcraft_cos::CosError::Syntax { detail, .. })) if detail.contains("/Matrix")), "{removed:?}");
}
/// Removing hidden layers alone never asks where content lands, so such a form is walked as it
/// stands: nothing is counted or refused over it in a document without layers.
#[test]
fn a_form_whose_matrix_is_not_six_numbers_leaves_removing_hidden_layers_alone() {
use crate::sanitize::{Hidden, remove_hidden, scan};
let mut doc = moved_form("/Matrix [1 0 0 1 0 (up)]", b"null");
let counts: std::collections::HashMap<Hidden, usize> = scan(&doc).into_iter().collect();
assert_eq!(counts[&Hidden::HiddenLayers], 0);
assert_eq!(remove_hidden(&mut doc, &[Hidden::HiddenLayers]), Err(RedactError::NothingToApply));
}
/// Remove Hidden Information reads it the same way: text a matrix entry by reference moves off the
/// page is hidden text, and goes.
#[test]
fn text_a_matrix_entry_by_reference_moves_off_the_page_is_hidden_text() {
use crate::sanitize::{Hidden, remove_hidden};
let mut doc = moved_form("/Matrix [1 0 0 1 0 8 0 R]", b"1000");
let removed = remove_hidden(&mut doc, &[Hidden::HiddenText]);
assert!(removed.as_ref().is_ok_and(|r| r.iter().any(|(h, n)| *h == Hidden::HiddenText && *n > 0)), "{removed:?}");
}
@@ -0,0 +1,340 @@
//! An operator takes its operands from the end, as the renderer reads them, and a surplus before
//! them is ignored: `(x) /OC /MC0 BDC` marks a layer's block, `(x) /GS1 gs` selects `/GS1`. Read
//! from the front, the surplus stood in for the operands, and what they named went unseen.
use super::*;
/// Hidden-layer text in a block whose tag and property list follow a string: Remove Hidden
/// Information found nothing to remove, and the text stayed.
#[test]
fn a_hidden_layers_block_after_a_surplus_operand_is_removed() {
use crate::sanitize::{Hidden, remove_hidden};
let mut doc = one_page(
b"(x) /OC /MC0 BDC BT /F1 10 Tf 20 260 Td (LAYERSECRET) Tj ET EMC BT /F1 10 Tf 20 20 Td (PUBLIC) Tj ET",
"/Properties << /MC0 7 0 R >>",
vec![b"<< /Type /OCG /Name (Hidden) >>".to_vec()],
);
doc.update_dict(ObjRef::new(1, 0), |d| {
d.set(
b"OCProperties".to_vec(),
Object::Dict(Dict::from_iter([
(b"OCGs".to_vec(), Object::Array(vec![Object::Ref(ObjRef::new(7, 0))])),
(b"D".to_vec(), Object::Dict(Dict::from_iter([(b"OFF".to_vec(), Object::Array(vec![Object::Ref(ObjRef::new(7, 0))]))]))),
])),
);
})
.unwrap();
let removed = remove_hidden(&mut doc, &[Hidden::HiddenLayers]);
assert!(removed.as_ref().is_ok_and(|r| r.iter().any(|(h, n)| *h == Hidden::HiddenLayers && *n > 0)), "{removed:?}");
let c = content(&doc, 0);
assert!(!c.contains("LAYERSECRET") && c.contains("PUBLIC"), "{c}");
}
/// Paint under a mark named by `/ActualText` in a block after a surplus operand: the name, which
/// would still read the word, kept it.
#[test]
fn actual_text_after_a_surplus_operand_goes_with_the_paint_it_names() {
let mut doc = one_page(b"(x) /Span <</ActualText (SECRET)>> BDC 100 100 m 160 100 l 160 120 l 100 120 l h f EMC", "", vec![]);
mark(&mut doc, 0, &[[90.0, 95.0, 130.0, 125.0]], "");
let r = apply(&mut doc, None).unwrap();
assert_eq!(r.paths_removed, 1);
let c = content(&doc, 0);
assert!(!c.contains("SECRET"), "{c}");
}
/// A tagged paragraph whose `MCID` follows a surplus operand: its structure element kept the
/// removed text in `/ActualText` and `/Alt`.
#[test]
fn a_tag_after_a_surplus_operand_loses_what_redaction_removed() {
let content = b"(x) /P <</MCID 0>> BDC BT /F1 10 Tf 10 200 Td (SECRET) Tj ET EMC";
let mut doc = pdf(vec![
b"<< /Type /Catalog /Pages 2 0 R /StructTreeRoot 7 0 R /MarkInfo << /Marked true >> >>".to_vec(),
b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(),
b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Contents 4 0 R /StructParents 0 /Resources << /Font << /F1 5 0 R >> >> >>".to_vec(),
stream("", content),
FONT.replace("95 0 R", "6 0 R").into_bytes(),
widths(),
b"<< /Type /StructTreeRoot /K 8 0 R >>".to_vec(),
b"<< /S /Document /P 7 0 R /K [9 0 R] >>".to_vec(),
b"<< /S /P /P 8 0 R /Pg 3 0 R /ActualText (SECRET) /Alt (the secret) /K 0 >>".to_vec(),
]);
mark(&mut doc, 0, &[[5.0, 195.0, 60.0, 212.0]], "");
assert_eq!(apply(&mut doc, None).unwrap().tags, 1);
let secret = doc.get(ObjRef::new(9, 0)).as_dict().cloned().unwrap();
assert!(secret.get(b"ActualText").is_none() && secret.get(b"Alt").is_none(), "{secret:?}");
}
/// A property list still drawn with, named after a surplus operand, stays in the page's resources
/// when the redaction cleans them; read from the front, it was taken for unused and retired.
#[test]
fn a_property_list_named_after_a_surplus_operand_is_kept() {
let mut doc = one_page(
b"BT /F1 10 Tf 20 260 Td (SECRET) Tj ET (x) /Span /Pr1 BDC BT /F1 10 Tf 20 20 Td (KEPT) Tj ET EMC",
"/Properties << /Pr1 << /Lang (en-GB) >> >>",
vec![],
);
mark(&mut doc, 0, &[[0.0, 200.0, 300.0, 300.0]], "");
assert_eq!(apply(&mut doc, None).unwrap().glyphs, 6);
let page = pdfcraft_model::pages(&doc).swap_remove(0);
let res = page.dict.get(b"Resources").map(|r| doc.resolve(r)).and_then(|r| r.as_dict().cloned()).unwrap_or_default();
let props = res.get(b"Properties").map(|p| doc.resolve(p)).and_then(|p| p.as_dict().cloned()).unwrap_or_default();
assert!(props.contains(b"Pr1"), "{res:?}");
}
/// A font set only by an ExtGState selected after a surplus operand: read from the front, no font
/// was set, every glyph stood at the start of the line with no size, and a mark over the end of
/// the word removed nothing.
#[test]
fn a_font_from_an_extgstate_selected_after_a_surplus_operand_places_the_text() {
let mut doc = one_page(b"BT (x) /GS1 gs 20 260 Td (SECRET) Tj ET", "/ExtGState << /GS1 << /Font [5 0 R 10] >> >>", vec![]);
// Over the last two glyphs, E and T at x = 40 to 50.
mark(&mut doc, 0, &[[42.0, 255.0, 55.0, 275.0]], "");
assert_eq!(apply(&mut doc, None).unwrap().glyphs, 2);
}
/// `/Pattern cs` after a surplus operand, once the pattern's paint under the mark went: it selects
/// the Pattern space and keeps the pattern, so the fill after it still counts as painting with it
/// and the pattern stays. Read from the front, the surplus cleared the pattern, which was pruned.
/// A grey space clears it.
#[test]
fn a_pattern_space_selected_after_a_surplus_operand_keeps_the_pattern() {
for (space, pruned) in [("(x) /Pattern", 0), ("/Pattern", 0), ("(x) /DeviceGray", 1)] {
let mut doc = one_page(
format!("/Pattern cs /P0 scn 10 260 20 20 re f {space} cs 200 20 50 50 re f").as_bytes(),
"/Pattern << /P0 7 0 R >>",
vec![stream("/PatternType 1 /PaintType 1 /TilingType 1 /BBox [0 0 10 10] /XStep 10 /YStep 10 /Resources << >>", b"0 0 5 5 re f")],
);
mark(&mut doc, 0, &[[0.0, 250.0, 40.0, 290.0]], "");
let r = apply(&mut doc, None).unwrap();
assert_eq!((r.paths_removed, r.patterns_removed), (1, pruned), "{space}");
}
}
/// A Type 3 font selected after a surplus operand, outside the mark, whose glyph selects an
/// ExtGState, a colour space, a property list and a font after one too: the cleanups after the
/// walk took the font for undrawn and those for unused. All stay, with the glyph.
#[test]
fn a_type3_font_and_its_glyphs_resources_named_after_a_surplus_operand_are_kept() {
let mut doc = pdf(vec![
b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(),
b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(),
b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Contents 4 0 R /Resources << /Font << /F1 5 0 R /T3 7 0 R >> >> >>".to_vec(),
stream("", b"BT /F1 10 Tf 20 260 Td (SECRET) Tj ET BT (x) /T3 12 Tf 20 20 Td (a) Tj ET"),
FONT.replace("95 0 R", "6 0 R").into_bytes(),
widths(),
b"<< /Type /Font /Subtype /Type3 /FontBBox [0 0 10 10] /FontMatrix [0.1 0 0 0.1 0 0] /CharProcs << /a 8 0 R >> \
/Encoding << /Differences [97 /a] >> /FirstChar 97 /LastChar 97 /Widths [10] /Resources << /ExtGState << /GS0 << /CA 0.5 >> >> \
/ColorSpace << /CS0 /DeviceGray >> /Properties << /P0 << >> >> /Font << /F0 5 0 R >> >> >>"
.to_vec(),
stream("", b"10 0 d0 (x) /GS0 gs (x) /CS0 cs (x) /Span /P0 BDC 0 0 10 10 re f EMC BT (x) /F0 1 Tf ET"),
]);
mark(&mut doc, 0, &[[0.0, 200.0, 300.0, 300.0]], "");
assert_eq!(apply(&mut doc, None).unwrap().glyphs, 6);
let page = pdfcraft_model::pages(&doc).swap_remove(0);
let res = page.dict.get(b"Resources").map(|r| doc.resolve(r)).and_then(|r| r.as_dict().cloned()).unwrap_or_default();
let fonts = res.get(b"Font").map(|f| doc.resolve(f)).and_then(|f| f.as_dict().cloned()).unwrap_or_default();
let font = fonts.get(b"T3").map(|f| doc.resolve(f)).and_then(|f| f.as_dict().cloned());
let font = font.unwrap_or_else(|| panic!("the drawn Type 3 font stays: {fonts:?}"));
let procs = font.get(b"CharProcs").map(|p| doc.resolve(p)).and_then(|p| p.as_dict().cloned()).unwrap_or_default();
assert!(procs.contains(b"a"), "its glyph stays: {font:?}");
let font_res = font.get(b"Resources").map(|r| doc.resolve(r)).and_then(|r| r.as_dict().cloned()).unwrap_or_default();
let states = font_res.get(b"ExtGState").map(|s| doc.resolve(s)).and_then(|s| s.as_dict().cloned()).unwrap_or_default();
assert!(states.contains(b"GS0"), "the ExtGState its glyph selects stays: {font_res:?}");
for (kind, name) in [(&b"ColorSpace"[..], &b"CS0"[..]), (b"Properties", b"P0"), (b"Font", b"F0")] {
let held = font_res.get(kind).map(|d| doc.resolve(d)).and_then(|d| d.as_dict().cloned()).unwrap_or_default();
assert!(held.contains(name), "the {} its glyph uses stays: {font_res:?}", String::from_utf8_lossy(name));
}
}
/// A tagged paragraph whose `TJ` after a surplus operand still draws once the mark has removed the
/// word beside it: read from the front, that `TJ` drew nothing, the paragraph was taken for empty,
/// and its structure element lost the content the page still shows.
#[test]
fn a_tagged_tj_after_a_surplus_operand_still_draws() {
let content = b"/P <</MCID 0>> BDC BT /F1 10 Tf 10 200 Td (SECRET) Tj 10 -100 Td (x) [(KEPT)] TJ ET EMC";
let mut doc = pdf(vec![
b"<< /Type /Catalog /Pages 2 0 R /StructTreeRoot 7 0 R /MarkInfo << /Marked true >> >>".to_vec(),
b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(),
b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Contents 4 0 R /StructParents 0 /Resources << /Font << /F1 5 0 R >> >> >>".to_vec(),
stream("", content),
FONT.replace("95 0 R", "6 0 R").into_bytes(),
widths(),
b"<< /Type /StructTreeRoot /K 8 0 R >>".to_vec(),
b"<< /S /Document /P 7 0 R /K [9 0 R] >>".to_vec(),
b"<< /S /P /P 8 0 R /Pg 3 0 R /K 0 >>".to_vec(),
]);
mark(&mut doc, 0, &[[5.0, 195.0, 60.0, 212.0]], "");
assert_eq!(apply(&mut doc, None).unwrap().glyphs, 6);
let paragraph = doc.get(ObjRef::new(9, 0)).as_dict().cloned().unwrap();
assert_eq!(paragraph.get(b"K").and_then(Object::as_int), Some(0), "it still tags what the page shows: {paragraph:?}");
}
/// A path's points follow a surplus number: read from the front, each point was shifted by one,
/// so a square under the mark was placed beside it and kept, and one beside the mark was placed
/// under it and removed.
#[test]
fn a_paths_points_after_a_surplus_number_are_where_the_renderer_draws_them() {
let under = b"0 0 1 rg 9 100 100 m 9 140 100 l 9 140 140 l 9 100 140 l h f 9 100 100 m 9 140 140 l S".as_slice();
let mut doc = one_page(under, "", vec![]);
mark(&mut doc, 0, &[[90.0, 90.0, 150.0, 150.0]], "");
assert_eq!(apply(&mut doc, None).unwrap().paths_removed, 2, "both paths under the mark go");
let beside =
b"0 0 1 rg 0 200 200 m 250 200 l 250 250 l 200 250 l h f 0 200 200 m 210 210 220 220 230 230 c 240 240 250 250 v 200 250 200 260 y h f"
.as_slice();
let mut doc = one_page(beside, "", vec![]);
mark(&mut doc, 0, &[[0.0, 0.0, 20.0, 20.0]], "");
assert_eq!(apply(&mut doc, None).unwrap().paths_removed, 0, "the paths beside the mark stay");
// Curves whose points, after a surplus, reach under the mark.
for curve in [&b"200 200 m 9 10 10 12 12 15 15 c f"[..], b"200 200 m 9 10 10 15 15 v f", b"200 200 m 9 10 10 15 15 y f"] {
let mut doc = one_page(curve, "", vec![]);
mark(&mut doc, 0, &[[0.0, 0.0, 20.0, 20.0]], "");
assert_eq!(apply(&mut doc, None).unwrap().paths_removed, 1, "{}", String::from_utf8_lossy(curve));
}
// A line, and curves, from a point beside the mark whose points, after a surplus, stay beside
// it: read from the front, the surplus was a point under it.
for curve in [
&b"100 100 500 m 510 510 l S"[..],
b"500 500 m 100 100 510 l S",
b"100 500 m 100 100 500 110 500 120 500 c f",
b"100 500 m 100 110 500 120 500 v f",
b"100 500 m 100 110 500 120 500 y f",
] {
let mut doc = one_page(curve, "", vec![]);
mark(&mut doc, 0, &[[90.0, 90.0, 150.0, 150.0]], "");
assert_eq!(apply(&mut doc, None).unwrap().paths_removed, 0, "{}", String::from_utf8_lossy(curve));
}
}
/// An `MCID` given by reference: in a named property list, and in a structure element's `/MCR`.
/// Read directly, it was missed, and the element kept the removed text.
#[test]
fn an_mcid_given_by_reference_loses_what_redaction_removed() {
for (content, properties, kid) in [
(b"/P /MC0 BDC BT /F1 10 Tf 10 200 Td (SECRET) Tj ET EMC".as_slice(), "/Properties << /MC0 << /MCID 10 0 R >> >>", "0"),
(b"/P <</MCID 0>> BDC BT /F1 10 Tf 10 200 Td (SECRET) Tj ET EMC", "", "<< /Type /MCR /Pg 3 0 R /MCID 10 0 R >>"),
] {
let mut doc = pdf(vec![
b"<< /Type /Catalog /Pages 2 0 R /StructTreeRoot 7 0 R /MarkInfo << /Marked true >> >>".to_vec(),
b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(),
format!("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Contents 4 0 R /StructParents 0 /Resources << /Font << /F1 5 0 R >> {properties} >> >>").into_bytes(),
stream("", content),
FONT.replace("95 0 R", "6 0 R").into_bytes(),
widths(),
b"<< /Type /StructTreeRoot /K 8 0 R >>".to_vec(),
b"<< /S /Document /P 7 0 R /K [9 0 R] >>".to_vec(),
format!("<< /S /P /P 8 0 R /Pg 3 0 R /ActualText (SECRET) /Alt (the SECRET) /K {kid} >>").into_bytes(),
b"0".to_vec(),
]);
mark(&mut doc, 0, &[[5.0, 195.0, 60.0, 212.0]], "");
assert_eq!(apply(&mut doc, None).unwrap().tags, 1, "{properties}{kid}");
let secret = doc.get(ObjRef::new(9, 0)).as_dict().cloned().unwrap();
assert!(secret.get(b"ActualText").is_none() && secret.get(b"Alt").is_none(), "{secret:?}");
}
// An `/MCR` naming the same MCID in a form's stream (`/Stm`) is other content: it stays.
let mut doc = pdf(vec![
b"<< /Type /Catalog /Pages 2 0 R /StructTreeRoot 7 0 R /MarkInfo << /Marked true >> >>".to_vec(),
b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(),
b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Contents 4 0 R /StructParents 0 /Resources << /Font << /F1 5 0 R >> >> >>".to_vec(),
stream("", b"/P <</MCID 0>> BDC BT /F1 10 Tf 10 200 Td (SECRET) Tj ET EMC"),
FONT.replace("95 0 R", "6 0 R").into_bytes(),
widths(),
b"<< /Type /StructTreeRoot /K 8 0 R >>".to_vec(),
b"<< /S /Document /P 7 0 R /K [9 0 R] >>".to_vec(),
b"<< /S /P /P 8 0 R /Pg 3 0 R /ActualText (FORMTEXT) /K << /Type /MCR /Pg 3 0 R /Stm 11 0 R /MCID 10 0 R >> >>".to_vec(),
b"0".to_vec(),
stream("/Type /XObject /Subtype /Form /BBox [0 0 300 300]", b"/P <</MCID 0>> BDC EMC"),
]);
mark(&mut doc, 0, &[[5.0, 195.0, 60.0, 212.0]], "");
apply(&mut doc, None).unwrap();
let other = doc.get(ObjRef::new(9, 0)).as_dict().cloned().unwrap();
assert!(other.get(b"ActualText").is_some(), "{other:?}");
}
/// The resources of page `page`, resolved.
fn resources_of(doc: &Document, page: usize) -> Dict {
let page = pdfcraft_model::pages(doc).swap_remove(page);
page.dict.get(b"Resources").map(|r| doc.resolve(r)).and_then(|r| r.as_dict().cloned()).unwrap_or_default()
}
/// `dict`'s dictionary `key`, resolved.
fn dict_in(doc: &Document, dict: &Dict, key: &[u8]) -> Dict {
dict.get(key).map(|d| doc.resolve(d)).and_then(|d| d.as_dict().cloned()).unwrap_or_default()
}
/// A property list a second page sharing the resources names after a surplus operand, once the
/// first page's block that named it was redacted: read from the front, the second page's name went
/// unseen and the list was retired from under it.
#[test]
fn a_property_list_another_page_names_after_a_surplus_operand_is_kept() {
use pdfcraft_cos::Stream;
let mut doc = one_page(
b"/Span /P0 BDC BT /F1 10 Tf 10 200 Td (SECRET) Tj ET EMC",
"/Properties << /P0 7 0 R >>",
vec![b"<< /ActualText (SECRET) >>".to_vec()],
);
let shared = doc.add(Object::Dict(resources_of(&doc, 0)));
doc.update_dict(ObjRef::new(3, 0), |d| d.set(b"Resources".to_vec(), Object::Ref(shared))).unwrap();
let mut second = doc.get(ObjRef::new(3, 0)).as_dict().cloned().unwrap();
let contents = doc.add(Object::Stream(Stream::from_raw(Dict::new(), b"(x) /Span /P0 BDC BT /F1 10 Tf 10 100 Td (Other) Tj ET EMC".to_vec())));
second.set(b"Contents".to_vec(), Object::Ref(contents));
let second = doc.add(Object::Dict(second));
doc.update_dict(ObjRef::new(2, 0), |d| {
d.set(b"Kids".to_vec(), Object::Array(vec![Object::Ref(ObjRef::new(3, 0)), Object::Ref(second)]));
d.set(b"Count".to_vec(), Object::Int(2));
})
.unwrap();
mark(&mut doc, 0, &[[5.0, 195.0, 60.0, 212.0]], "");
apply(&mut doc, Some(&[0])).unwrap();
let properties = dict_in(&doc, &resources_of(&doc, 1), b"Properties");
assert!(properties.contains(b"P0"), "the second page's property list stays: {properties:?}");
}
/// A Type 3 font set only by an ExtGState's `/Font`, selected after a surplus operand: read from the
/// front, the cleanups took it for undrawn, dropped it from the page and unlinked its glyph.
#[test]
fn a_type3_font_an_extgstate_selects_after_a_surplus_operand_is_kept() {
let mut doc = pdf(vec![
b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(),
b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(),
b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Contents 4 0 R /Resources << /Font << /F1 5 0 R /T3 7 0 R >> /ExtGState << /GS1 << /Font [7 0 R 12] >> >> >> >>".to_vec(),
stream("", b"BT /F1 10 Tf 20 260 Td (SECRET) Tj ET BT (x) /GS1 gs 20 20 Td (a) Tj ET"),
FONT.replace("95 0 R", "6 0 R").into_bytes(),
widths(),
b"<< /Type /Font /Subtype /Type3 /FontBBox [0 0 10 10] /FontMatrix [0.1 0 0 0.1 0 0] /CharProcs << /a 8 0 R /b 9 0 R >> \
/Encoding << /Differences [97 /a /b] >> /FirstChar 97 /LastChar 98 /Widths [10 10] >>"
.to_vec(),
stream("", b"10 0 d0 0 0 10 10 re f"),
stream("", b"10 0 d0 0 0 5 5 re f"),
]);
mark(&mut doc, 0, &[[0.0, 200.0, 300.0, 300.0]], "");
assert_eq!(apply(&mut doc, None).unwrap().glyphs, 6);
let fonts = dict_in(&doc, &resources_of(&doc, 0), b"Font");
assert!(fonts.contains(b"T3"), "the page still lists the font: {fonts:?}");
let font = doc.get(ObjRef::new(7, 0)).as_dict().cloned().unwrap_or_default();
let procs = dict_in(&doc, &font, b"CharProcs");
assert!(procs.contains(b"a"), "the glyph the page draws stays: {procs:?}");
}
/// A Type 3 font without resources of its own, set by an ExtGState selected after a surplus operand:
/// its glyph paints through the page's resources, so it may paint with the page's pattern, which
/// stays once the page's own fill with it was redacted (the text itself fills with grey). Read from the front, the font was taken
/// for one with resources, and the pattern was pruned.
#[test]
fn a_type3_font_without_resources_an_extgstate_selects_after_a_surplus_operand_keeps_the_pattern() {
let mut doc = pdf(vec![
b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(),
b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(),
b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> /Pattern << /P0 9 0 R >> /ExtGState << /GS1 << /Font [7 0 R 12] >> >> >> >>".to_vec(),
stream("", b"/Pattern cs /P0 scn 10 260 20 20 re f 0 g BT (x) /GS1 gs 150 20 Td (a) Tj ET"),
FONT.replace("95 0 R", "6 0 R").into_bytes(),
widths(),
b"<< /Type /Font /Subtype /Type3 /FontBBox [0 0 10 10] /FontMatrix [0.1 0 0 0.1 0 0] /CharProcs << /a 8 0 R >> \
/Encoding << /Differences [97 /a] >> /FirstChar 97 /LastChar 97 /Widths [10] >>"
.to_vec(),
stream("", b"10 0 d0 /Pattern cs /P0 scn 0 0 10 10 re f"),
stream("/PatternType 1 /PaintType 1 /TilingType 1 /BBox [0 0 10 10] /XStep 10 /YStep 10 /Resources << >>", b"0 0 5 5 re f"),
]);
mark(&mut doc, 0, &[[0.0, 250.0, 40.0, 290.0]], "");
let r = apply(&mut doc, None).unwrap();
assert_eq!((r.paths_removed, r.patterns_removed), (1, 0));
}
@@ -390,6 +390,35 @@ fn type3_font_used_in_a_form_xobject_has_its_redacted_glyph_removed() {
assert!(!full_save_holds(&doc, b"SECRET_FORM_GLYPH_PAYLOAD"), "redacted glyph program survived");
}
/// Type 3 cleanup decoded a glyph program again for every font listing it: 2 000 fonts sharing
/// one large program read it 2 000 times. It is read once now, and the cleanup still keeps the
/// glyph every font shows.
#[test]
fn a_glyph_program_many_type3_fonts_share_is_read_once() {
const FONTS: usize = 2_000;
let names: String = (0..FONTS).map(|i| format!("/T{i} {} 0 R ", 6 + i)).collect();
let shows: String = (0..FONTS).map(|i| format!("/T{i} 10 Tf (A) Tj ")).collect();
let mut objs = vec![
b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(),
b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(),
format!("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Contents 4 0 R /Resources << /Font << {names}>> >> >>").into_bytes(),
stream("", format!("BT 10 100 Td {shows}ET").as_bytes()),
stream("", [b"SHARED_GLYPH ".as_slice(), &b"0 0 m 1 1 l S ".repeat(50_000)].concat()),
];
objs.extend((0..FONTS).map(|_| {
b"<< /Type /Font /Subtype /Type3 /FontBBox [0 0 1000 1000] /FontMatrix [0.001 0 0 0.001 0 0] /FirstChar 65 /LastChar 65 /Widths [0] /Encoding << /Differences [65 /A] >> /CharProcs << /A 5 0 R >> >>".to_vec()
}));
let mut doc = pdf(objs);
// The glyphs are drawn at x 10 with no width, so a mark away from them leaves them all.
mark(&mut doc, 0, &[[200.0, 200.0, 250.0, 250.0]], "");
let started = std::time::Instant::now();
apply(&mut doc, None).unwrap();
assert!(started.elapsed() < std::time::Duration::from_secs(60), "{:?}", started.elapsed());
let font = doc.get(ObjRef::new(6, 0));
let procs = doc.resolve(font.as_dict().unwrap().get(b"CharProcs").unwrap());
assert!(procs.as_dict().unwrap().contains(b"A"), "the glyph every font shows was unlinked");
}
/// A Type 3 font with glyphs A (its program object 7) and B (object 8), at object 6.
const TYPE3: &str = "<< /Type /Font /Subtype /Type3 /FontBBox [0 -200 1000 800] /FontMatrix [0.001 0 0 0.001 0 0] /FirstChar 65 /LastChar 66 /Widths [500 500] /Encoding << /Differences [65 /A /B] >> /CharProcs << /A 7 0 R /B 8 0 R >> >>";
@@ -783,6 +812,37 @@ fn a_type3_font_only_a_soft_mask_without_resources_selects_stays_on_the_page() {
assert!(saved_first_page_lists_font(&doc, b"T4"), "the page no longer lists the font the soft mask selects");
}
/// The same soft mask, its ExtGState selected after a surplus operand (`(x) /GS1 gs`), which the
/// renderer ignores: read from the front, the cleanups never read the group, and dropped the font
/// it selects and its glyph.
#[test]
fn a_type3_font_only_a_soft_mask_selected_after_a_surplus_operand_selects_stays_on_the_page() {
let mut doc = pdf(vec![
b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(),
b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(),
b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Contents 4 0 R /Resources 5 0 R >>".to_vec(),
stream("", b"BT /T3 10 Tf 10 100 Td (AC) Tj ET (x) /GS1 gs 150 150 100 100 re f"),
b"<< /Font << /T3 6 0 R /T4 7 0 R >> /ExtGState << /GS1 << /Type /ExtGState /SMask << /Type /Mask /S /Luminosity /G 8 0 R >> >> >> >>"
.to_vec(),
type3_abc(9),
type3_abc(12),
stream(
"/Type /XObject /Subtype /Form /BBox [0 0 300 300] /Group << /S /Transparency /CS /DeviceGray >>",
b"1 g BT /T4 40 Tf 160 180 Td (B) Tj ET",
),
stream("", b"% REDACTED_GLYPH_A"),
stream("", b"% UNUSED_GLYPH_B"),
stream("", b"% PAGE_GLYPH_C"),
stream("", b"% UNUSED_T4_GLYPH_A"),
stream("", b"% MASK_GLYPH_B"),
stream("", b"% UNUSED_T4_GLYPH_C"),
]);
mark(&mut doc, 0, &[[9.0, 95.0, 14.9, 110.0]], "");
assert_eq!(apply(&mut doc, None).unwrap().glyphs, 1);
assert!(full_save_holds(&doc, b"MASK_GLYPH_B"), "the glyph the soft mask shows was unlinked");
assert!(saved_first_page_lists_font(&doc, b"T4"), "the page no longer lists the font the soft mask selects");
}
/// The same group, its content behind a predictor whose `/DecodeParms` are given by reference:
/// the page's cleanup reads it through them, and keeps the font it selects.
#[test]
+170
View File
@@ -0,0 +1,170 @@
//! Bytes the content parser can't read are read past by the redaction walk, so text they hide (a
//! stray `)` or `}` in a `TJ` array) is neither found nor removed, while other readers still draw
//! it. A page whose walk meets such bytes is refused, by Apply Redactions and by Remove Hidden
//! Information.
use super::*;
use crate::sanitize::{Hidden, remove_hidden, sanitize, scan};
/// `TJ` arrays each holding a byte the parser can't read beside the text.
const BROKEN: [&[u8]; 4] = [b"[(TAIL) ) (SECRET)] TJ", b"[(TAIL) } (SECRET)] TJ", b"[(TAILSECRET) )] TJ", b"[) (TAILSECRET)] TJ"];
/// Over the top third of the 300 × 300 page.
const MARK: [f64; 4] = [0.0, 200.0, 300.0, 300.0];
/// `tj` shown in /F1 at (20, 260), under [`MARK`].
fn shown(tj: &[u8]) -> Vec<u8> {
[b"BT /F1 10 Tf 20 260 Td ".as_slice(), tj, b" ET"].concat()
}
/// The only text under the mark sits in such a `TJ`: the walk finds nothing there and rewrites
/// nothing, so it went on, and the text stayed in the file.
#[test]
fn text_under_a_mark_beside_bytes_the_parser_cannot_read_is_refused() {
for tj in BROKEN {
let mut doc = one_page(&shown(tj), "", vec![]);
mark(&mut doc, 0, &[MARK], "");
assert_eq!(apply(&mut doc, None), Err(RedactError::Unreadable(1)), "{}", String::from_utf8_lossy(tj));
}
// With other text on the page, outside the mark.
let mut doc = one_page(&[b"BT /F1 10 Tf 20 20 Td (PUBLIC) Tj ET ".as_slice(), &shown(BROKEN[0])].concat(), "", vec![]);
mark(&mut doc, 0, &[MARK], "");
assert_eq!(apply(&mut doc, None), Err(RedactError::Unreadable(1)), "beside other text");
}
/// In a stream the walk rewrites, it removed the text it could read and wrote the broken `TJ` out
/// as `(TAIL) (SECRET) TJ`: the stray byte and the brackets went, the strings stayed.
#[test]
fn bytes_the_parser_cannot_read_in_a_stream_the_walk_rewrites_are_refused() {
for tj in BROKEN {
let mut doc = one_page(&[b"BT /F1 10 Tf 20 230 Td (SECRET) Tj ET ".as_slice(), &shown(tj)].concat(), "", vec![]);
mark(&mut doc, 0, &[MARK], "");
assert_eq!(apply(&mut doc, None), Err(RedactError::Unreadable(1)), "{}", String::from_utf8_lossy(tj));
}
}
/// A form under the mark with resources of its own, which the walk enters but doesn't rewrite:
/// no later read of the page follows it.
#[test]
fn bytes_the_parser_cannot_read_in_a_form_under_a_mark_are_refused() {
let form = stream("/Type /XObject /Subtype /Form /BBox [0 0 300 300] /Resources << /Font << /F1 5 0 R >> >>", shown(BROKEN[0]));
let mut doc = one_page(b"/Fm Do", "/XObject << /Fm 7 0 R >>", vec![form]);
mark(&mut doc, 0, &[MARK], "");
assert_eq!(apply(&mut doc, None), Err(RedactError::Unreadable(1)));
}
/// A form the mark doesn't reach isn't walked: bytes in it can't hide anything under the mark, and
/// the walk doesn't refuse the page over them. This one has resources of its own, so the check after
/// the walk doesn't read it either (it would refuse one without), and the page is redacted.
#[test]
fn bytes_the_parser_cannot_read_in_a_form_away_from_the_marks_are_left() {
let form = stream(
"/Type /XObject /Subtype /Form /BBox [0 0 300 100] /Resources << /Font << /F1 5 0 R >> >>",
[b"BT /F1 10 Tf 20 20 Td ".as_slice(), BROKEN[0], b" ET"].concat(),
);
let mut doc = one_page(b"BT /F1 10 Tf 20 230 Td (SECRET) Tj ET /Fm Do", "/XObject << /Fm 7 0 R >>", vec![form]);
mark(&mut doc, 0, &[MARK], "");
assert_eq!(apply(&mut doc, None).unwrap().glyphs, 6);
assert!(!content(&doc, 0).contains("(SECRET)"));
}
/// The page sets its font only through an ExtGState `/Font` and lists no `/Font` resources, so the
/// cleanups after the walk, which look at the listed fonts, read nothing.
#[test]
fn bytes_the_parser_cannot_read_on_a_page_without_font_resources_are_refused() {
let mut doc = pdf(vec![
b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(),
b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(),
b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Contents [4 0 R 5 0 R] /Resources << /ExtGState << /GS1 << /Font [6 0 R 10] >> >> >> >>"
.to_vec(),
stream("", b"BT /GS1 gs 20 230 Td (SECRET) Tj ET"),
stream("", b"BT /GS1 gs 20 260 Td [(TAIL) ) (SECRET)] TJ ET"),
FONT.replace("95 0 R", "7 0 R").into_bytes(),
widths(),
]);
mark(&mut doc, 0, &[MARK], "");
assert_eq!(apply(&mut doc, None), Err(RedactError::Unreadable(1)));
}
/// Hidden text inside a broken `TJ` is never counted: alone, Remove Hidden Information found
/// nothing to remove and Sanitize Document went on; beside other hidden text, the removal went on
/// and left it. The scan now counts the page, and removing hidden text refuses it.
#[test]
fn hidden_text_beside_bytes_the_parser_cannot_read_is_refused() {
let alone = b"BT /F1 10 Tf 3 Tr 20 260 Td [(TAIL) ) (HIDDEN)] TJ ET".as_slice();
let beside = [b"BT /F1 10 Tf 3 Tr 20 230 Td (HIDDEN) Tj ET ".as_slice(), alone].concat();
for content in [alone, &beside] {
let label = String::from_utf8_lossy(content);
let doc = one_page(content, "", vec![]);
let counts: std::collections::HashMap<Hidden, usize> = scan(&doc).into_iter().collect();
assert!(counts[&Hidden::HiddenText] > 0, "{label}");
let mut doc = one_page(content, "", vec![]);
assert_eq!(remove_hidden(&mut doc, &[Hidden::HiddenText]), Err(RedactError::Unreadable(1)), "{label}");
let mut doc = one_page(content, "", vec![]);
assert_eq!(sanitize(&mut doc), Err(RedactError::Unreadable(1)), "{label}");
}
// In a form with resources of its own, which the walk enters on every page.
let form = stream("/Type /XObject /Subtype /Form /BBox [0 0 300 300] /Resources << /Font << /F1 5 0 R >> >>", alone);
let mut doc = one_page(b"/Fm Do", "/XObject << /Fm 7 0 R >>", vec![form]);
assert_eq!(remove_hidden(&mut doc, &[Hidden::HiddenText]), Err(RedactError::Unreadable(1)), "in a form");
}
/// Removing hidden layers alone refuses such bytes too, even in a document without
/// `/OCProperties`: a membership dictionary (`/AllOff` of a layer that is on) still hides what it
/// marks, for the walk as for the app's renderer. With nothing in front of `/OC`, the marked text
/// is removed. Here a string beside a stray `}` is left in front of it, which keeps the block from
/// the walk (it reads a `BDC`'s first operands; a string alone does so too, a matter of its own),
/// and the stray byte has the page refused rather than the text kept.
#[test]
fn bytes_the_parser_cannot_read_refuse_removing_hidden_layers_alone() {
let marked = |before: &[u8]| {
let content = [before, b" /OC /MC0 BDC BT /F1 10 Tf 20 260 Td (LAYERSECRET) Tj ET EMC BT /F1 10 Tf 20 20 Td (PUBLIC) Tj ET"].concat();
one_page(
&content,
"/Properties << /MC0 8 0 R >>",
vec![b"<< /Type /OCG /Name (Layer) >>".to_vec(), b"<< /Type /OCMD /OCGs [7 0 R] /P /AllOff >>".to_vec()],
)
};
let mut doc = marked(b"");
let removed = remove_hidden(&mut doc, &[Hidden::HiddenLayers]);
assert!(removed.as_ref().is_ok_and(|r| r.iter().any(|(h, n)| *h == Hidden::HiddenLayers && *n > 0)), "{removed:?}");
assert!(!content(&doc, 0).contains("LAYERSECRET"));
let mut doc = marked(b"(x) }");
assert_eq!(remove_hidden(&mut doc, &[Hidden::HiddenLayers]), Err(RedactError::Unreadable(1)));
}
/// With form fields removed too, a field's appearance is flattened into page content and read the
/// same way, though the scan, which runs before flattening, doesn't count it: hidden text in a
/// broken `TJ` there refuses removing hidden text, and Sanitize Document, which went on and left it.
/// Removing form fields alone doesn't read the content, and goes on.
#[test]
fn hidden_text_beside_bytes_the_parser_cannot_read_in_a_field_appearance_is_refused() {
let fresh = || {
pdf(vec![
b"<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [6 0 R] >> >>".to_vec(),
b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(),
b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> /Annots [6 0 R] >>"
.to_vec(),
stream("", b"BT /F1 10 Tf 10 230 Td (Name:) Tj ET"),
FONT.replace("95 0 R", "8 0 R").into_bytes(),
b"<< /Type /Annot /Subtype /Widget /FT /Tx /T (name) /P 3 0 R /Rect [50 225 200 240] /AP << /N 7 0 R >> >>".to_vec(),
stream(
"/Type /XObject /Subtype /Form /BBox [0 0 150 15] /Resources << /Font << /F1 5 0 R >> >>",
b"BT /F1 10 Tf 3 Tr 2 3 Td [(TAIL) ) (HIDDEN)] TJ ET",
),
widths(),
])
};
assert!(remove_hidden(&mut fresh(), &[Hidden::FormFields]).is_ok());
assert_eq!(remove_hidden(&mut fresh(), &[Hidden::FormFields, Hidden::HiddenText]), Err(RedactError::Unreadable(1)));
assert_eq!(sanitize(&mut fresh()), Err(RedactError::Unreadable(1)));
}
/// An inline image whose end the parser guesses, as Apply Redactions already refuses it: what
/// follows it may not be what the page draws, so Remove Hidden Information refuses it too.
#[test]
fn hidden_text_beside_an_inline_image_the_renderer_cannot_end_is_refused() {
let page = b"BT /F1 10 Tf 3 Tr 10 100 Td (HIDDEN) Tj ET BI /W 1 /H 1 /CS /G /BPC 8 /F /AHx ID 7F".as_slice();
let mut doc = one_page(page, "", vec![]);
assert_eq!(remove_hidden(&mut doc, &[Hidden::HiddenText]), Err(RedactError::Unreadable(1)));
}
+113
View File
@@ -897,6 +897,119 @@ fn glyphs_are_placed_with_the_text_matrix_and_the_form_matrix() {
assert!(proof.entries[0].detail.contains("glyph(s) still show"));
}
/// The proof reads an operator's operands from the end, as the renderer does: a surplus before
/// them doesn't hide the text a `Tf`, `TJ` or `Do` after it draws, or the image a `Do` draws.
#[test]
fn the_proof_reads_operands_from_the_end() {
let blank = marked_content(b"BT /F1 10 Tf 10 200 Td (Public) Tj ET", Spec::default());
let snap = Snapshot::capture(&blank, None).unwrap();
let form = stream(
"/Type /XObject /Subtype /Form /BBox [0 0 300 300] /Resources << /Font << /F1 5 0 R >> >>",
b"BT /F1 10 Tf 10 100 Td (SECRETVALUE) Tj ET",
);
let image = stream("/Type /XObject /Subtype /Image /Width 1 /Height 1 /ColorSpace /DeviceGray /BitsPerComponent 8", b"o");
let image_form =
stream("/Type /XObject /Subtype /Form /BBox [0 0 300 300] /Resources << /XObject << /Im1 8 0 R >> >>", b"q 50 0 0 12 10 98 cm (x) /Im1 Do Q");
for (content, spec) in [
(&b"BT (x) /F1 10 Tf 10 100 Td (SECRETVALUE) Tj ET"[..], Spec::default()),
// The size: text starting outside the region reaches into it only at its size.
(b"BT (x) /F1 10 Tf -60 100 Td (AAAAAAAAAAAAAAAAAAAAAAAAAAAA) Tj ET", Spec::default()),
(b"BT /F1 10 Tf 10 100 Td (x) [(SECRETVALUE)] TJ ET", Spec::default()),
(b"(x) /Fm1 Do", Spec { resources: "/XObject << /Fm1 7 0 R >>", extra: vec![form.clone()], ..Spec::default() }),
// An image under the mark, and one in a form under it.
(b"q 50 0 0 12 10 98 cm (x) /Im1 Do Q", Spec { resources: "/XObject << /Im1 7 0 R >>", extra: vec![image.clone()], ..Spec::default() }),
(b"(x) /Fm1 Do", Spec { resources: "/XObject << /Fm1 7 0 R >>", extra: vec![image_form.clone(), image.clone()], ..Spec::default() }),
] {
let mut doc = marked_content(content, spec);
doc.require_full_save();
let proof = snap.prove(&doc, None, &ProofOptions::default());
assert_eq!(proof.entries[0].status, Status::Failed, "{}: {}", String::from_utf8_lossy(content), proof.to_text());
}
}
/// The proof reads the text state's operands from the end too. In each case the text starts outside
/// the region and only the operand after the surplus brings a glyph into it: char spacing, word
/// spacing, horizontal scaling, leading with `T*`, rise, and the spacing `"` sets.
#[test]
fn the_proof_reads_the_text_states_operands_from_the_end() {
let blank = marked_content(b"BT /F1 10 Tf 10 200 Td (Public) Tj ET", Spec::default());
let snap = Snapshot::capture(&blank, None).unwrap();
for content in [
&b"BT /F1 10 Tf -60 100 Td (x) 70 Tc (AB) Tj ET"[..],
b"BT /F1 10 Tf -60 100 Td (x) 70 Tw (A B) Tj ET",
b"BT /F1 10 Tf -60 100 Td (x) 1500 Tz (AB) Tj ET",
b"BT /F1 10 Tf 10 200 Td (x) 100 TL T* (A) Tj ET",
b"BT /F1 10 Tf 10 200 Td (x) -100 Ts (A) Tj ET",
b"BT /F1 10 Tf -60 100 Td (x) 0 70 (AB) \" ET",
] {
let mut doc = marked_content(content, Spec::default());
doc.require_full_save();
let proof = snap.prove(&doc, None, &ProofOptions::default());
assert_eq!(proof.entries[0].status, Status::Failed, "{}: {}", String::from_utf8_lossy(content), proof.to_text());
}
}
/// The proof reads a path's points from the end too: a square under the region, its points after
/// a surplus number, still paints there.
#[test]
fn the_proof_reads_a_paths_points_from_the_end() {
let blank = marked_content(b"BT /F1 10 Tf 10 200 Td (Public) Tj ET", Spec::default());
let snap = Snapshot::capture(&blank, None).unwrap();
for content in [
&b"0 0 1 rg 9 20 98 m 9 60 98 l 9 60 108 l 9 20 108 l h f"[..],
b"0 0 1 rg 9 20 98 40 10 re f",
// Curves from a point outside the region whose own points reach into it.
b"0 0 1 rg 9 200 200 m 9 20 98 40 100 60 108 c h f",
b"0 0 1 rg 9 200 200 m 9 20 98 60 108 v h f",
b"0 0 1 rg 9 200 200 m 9 20 98 60 108 y h f",
// A segment after a surplus, from a point outside the region.
b"0 0 1 rg 200 200 m 200 20 100 l h f",
b"0 0 1 rg 200 200 m 200 20 100 30 100 40 100 c h f",
b"0 0 1 rg 200 200 m 200 20 100 40 100 v h f",
b"0 0 1 rg 200 200 m 200 20 100 40 100 y h f",
] {
let mut doc = marked_content(content, Spec::default());
doc.require_full_save();
let proof = snap.prove(&doc, None, &ProofOptions::default());
assert_eq!(proof.entries[0].status, Status::Failed, "{}: {}", String::from_utf8_lossy(content), proof.to_text());
}
}
/// Which font a `Tf` selects, and which strings a `TJ` shows, are read from the end too: text an
/// undecodable font shows after a surplus operand, away from the mark, leaves the region
/// unverifiable. Read from the front, no font was set, or no string was shown, and it passed.
#[test]
fn the_proof_reads_the_font_and_the_strings_from_the_end() {
for content in [&b"BT (x) /F2 10 Tf 10 200 Td <00410042> Tj ET"[..], b"BT /F2 10 Tf 10 200 Td (x) [<00410042>] TJ ET"] {
let mut doc = open(build_with(content, opaque_spec()));
mark(&mut doc, &[[150.0, 20.0, 200.0, 40.0]]);
let (_, proof) = run(&mut doc);
assert_eq!(proof.entries[0].status, Status::Unverifiable, "{}: {}", String::from_utf8_lossy(content), proof.to_text());
}
}
/// An image a Type 3 glyph (one without resources of its own, drawing through the page's) draws
/// after a surplus operand can't be placed, as one it draws without one can't: the region is
/// unverifiable.
#[test]
fn an_image_a_type3_glyph_draws_after_a_surplus_operand_is_found() {
let spec = Spec {
resources: "/Font << /F1 5 0 R /T3 7 0 R >> /XObject << /Im0 9 0 R >>",
extra: vec![
b"<< /Type /Font /Subtype /Type3 /FontBBox [0 0 10 10] /FontMatrix [0.1 0 0 0.1 0 0] /CharProcs << /a 8 0 R >> \
/Encoding << /Differences [97 /a] >> /FirstChar 97 /LastChar 97 /Widths [10] >>"
.to_vec(),
stream("", b"10 0 d0 (x) /Im0 Do"),
stream("/Type /XObject /Subtype /Image /Width 1 /Height 1 /ColorSpace /DeviceGray /BitsPerComponent 8", b"o"),
],
..Spec::default()
};
let mut doc = open(build_with(b"BT /F1 10 Tf 10 100 Td (SECRETVALUE) Tj ET BT /T3 12 Tf 150 20 Td (a) Tj ET", spec));
mark(&mut doc, &[REGION]);
let (_, proof) = run(&mut doc);
assert_eq!(proof.entries[0].status, Status::Unverifiable, "{}", proof.to_text());
}
#[test]
fn an_ambiguous_needle_is_still_swept_outside_page_content() {
// The word also stays on the page legitimately (so page text, the raw file and decoded
+72 -27
View File
@@ -3,7 +3,7 @@
use std::collections::{HashMap, HashSet};
use pdfcraft_content::Pieces;
use pdfcraft_cos::{CosError, Dict, Document, ObjRef, Object};
use pdfcraft_cos::{CosError, DecodeBudget, Dict, Document, ObjRef, Object};
use crate::{RedactError, page_streams};
@@ -130,6 +130,25 @@ struct UsedInGlyphs {
properties: HashSet<Vec<u8>>,
}
impl UsedInGlyphs {
fn merge(&mut self, other: &UsedInGlyphs) {
self.xobjects.extend(other.xobjects.iter().cloned());
self.colorspaces.extend(other.colorspaces.iter().cloned());
self.patterns.extend(other.patterns.iter().cloned());
self.shadings.extend(other.shadings.iter().cloned());
self.extgstates.extend(other.extgstates.iter().cloned());
self.fonts.extend(other.fonts.iter().cloned());
self.properties.extend(other.properties.iter().cloned());
}
}
/// What one Type 3 cleanup reads of glyph programs: the resource names each indirect program
/// uses, read once however many fonts share it, and one decoding allowance for all of them.
struct GlyphReads {
used: HashMap<ObjRef, UsedInGlyphs>,
budget: DecodeBudget,
}
fn collect_used_resources_in_stream(data: &[u8], used: &mut UsedInGlyphs) -> Result<(), CosError> {
// One operator at a time, so a glyph program of millions of them is never held whole. A byte
// that can't be read anywhere in it still refuses, once the loop has read it all.
@@ -151,7 +170,7 @@ fn record_used(op: &pdfcraft_content::Op, used: &mut UsedInGlyphs) {
}
}
b"cs" | b"CS" => {
if let Some(n) = op.name(0) {
if let Some(n) = op.last_name() {
used.colorspaces.insert(n.to_vec());
}
}
@@ -166,17 +185,17 @@ fn record_used(op: &pdfcraft_content::Op, used: &mut UsedInGlyphs) {
}
}
b"gs" => {
if let Some(n) = op.name(0) {
if let Some(n) = op.last_name() {
used.extgstates.insert(n.to_vec());
}
}
b"Tf" => {
if let Some(n) = op.name(0) {
if let Some(n) = op.name_back(1) {
used.fonts.insert(n.to_vec());
}
}
b"BDC" | b"DP" => {
if let Some(n) = op.name(1) {
if let Some(n) = op.last_name() {
used.properties.insert(n.to_vec());
}
}
@@ -315,7 +334,7 @@ fn scan_content_stream(
}
b"gs" => {
apply_text_op(ctx, res, &op, &mut current_font);
if let Some(name) = op.name(0) {
if let Some(name) = op.last_name() {
scan_soft_mask(ctx, res, holder_ref, name, depth)?;
}
}
@@ -338,12 +357,12 @@ fn scan_content_stream(
fn apply_text_op(ctx: &mut ScanContext<'_>, res: &Dict, op: &pdfcraft_content::Op, current_font: &mut Option<FontKey>) {
match op.op.as_slice() {
b"Tf" => {
if let Some(name) = op.name(0) {
if let Some(name) = op.name_back(1) {
*current_font = resolve_font_in_res(ctx.doc, res, name).map(|(k, _)| k);
}
}
b"gs" => {
if let Some(name) = op.name(0)
if let Some(name) = op.last_name()
&& let Some((k, _)) = resolve_extgstate_font(ctx.doc, res, name)
{
*current_font = Some(k);
@@ -477,7 +496,7 @@ fn add_soft_mask_ops(doc: &Document, res: &Dict, ops: &mut Vec<pdfcraft_content:
while let Some(op) = ops.get(cursor) {
let selected = match op.op.as_slice() {
b"gs" => op
.name(0)
.last_name()
.and_then(|n| states.get(n))
.and_then(|s| doc.resolve(s).as_dict().and_then(|s| s.get(b"SMask").cloned()))
.and_then(|m| doc.resolve(&m).as_dict().and_then(|m| m.get(b"G").and_then(Object::as_ref))),
@@ -539,10 +558,19 @@ fn gs_font_object(doc: &Document, state_obj: &Object) -> Option<Object> {
font_entry.into_iter().next()
}
/// Whether font `f` (a reference, or a font dictionary) is a Type 3 font, the only kind the font
/// cleanup prunes: its `/Subtype` is read directly, as the cleanup's other readers read it, so one
/// given by reference isn't recognised by any of them. Which allowance the cleanup's read is charged
/// to, and what it prunes, both go by this.
fn is_type3(doc: &Document, f: &Object) -> bool {
doc.resolve(f).as_dict().is_some_and(|d| d.name(b"Subtype") == Some(b"Type3"))
}
/// Prune Type 3 fonts from a rewritten page or form's `/Resources` dictionary if the rewritten
/// content no longer draws any text using that font name. `page` is the page's dictionary when
/// `res` are a page's resources. What it reads is charged to `budget`, what is left of the page's
/// allowance.
/// allowance, when the resources list a Type 3 font, and otherwise to an allowance of a page of its
/// own (below).
pub(crate) fn prune_type3_from_resources(
doc: &Document,
budget: &mut pdfcraft_cos::DecodeBudget,
@@ -556,12 +584,20 @@ pub(crate) fn prune_type3_from_resources(
}
// The operators of forms that draw through these resources count too: dropping a font a child
// form still shows would leave its text without one.
let mut ops = crate::interp::resource_ops(doc, budget, res, content)?;
// form still shows would leave its text without one. Without a Type 3 font nothing is pruned,
// but the read is still made: it refuses bytes the parser can't read in what the content draws,
// and on a page with nothing replaced and no properties listed no other check does, unless the
// document still lists a Type 3 font (`unlink_type3` then reads every page). The walk reads
// past them, so text they hide would stay under the mark. The read is then charged to an
// allowance of a page of its own, not to what the walk left of the page's, since it decides
// nothing about the fonts.
let type3 = fonts.iter().any(|(_, f)| is_type3(doc, f));
let mut own = pdfcraft_cos::DecodeBudget::page();
let mut ops = crate::interp::resource_ops(doc, if type3 { &mut *budget } else { &mut own }, res, content)?;
// So do those of a page's annotation appearances, and of soft mask groups, without resources of
// their own. They are read only when there is a Type 3 font to keep, so other files are not
// refused over them.
if fonts.iter().any(|(_, f)| doc.resolve(f).as_dict().is_some_and(|d| d.name(b"Subtype") == Some(b"Type3"))) {
if type3 {
if let Some(page) = page {
// One total for all of them, as for the content: each appearance under the cap could
// still add up to far more than it. Their decoded bytes, and their forms', are charged to
@@ -584,11 +620,11 @@ pub(crate) fn prune_type3_from_resources(
let mut drawn_font_names = HashSet::new();
for op in &ops {
if op.is("Tf") {
if let Some(name) = op.name(0) {
if let Some(name) = op.name_back(1) {
drawn_font_names.insert(name.to_vec());
}
} else if op.is("gs")
&& let Some(name) = op.name(0)
&& let Some(name) = op.last_name()
{
let extg = res_dict(doc, res, b"ExtGState");
if let Some(font_obj) = extg.get(name).and_then(|state_obj| gs_font_object(doc, state_obj)) {
@@ -605,15 +641,12 @@ pub(crate) fn prune_type3_from_resources(
let mut changed = false;
let font_names: Vec<Vec<u8>> = fonts.iter().map(|(n, _)| n.to_vec()).collect();
for name in font_names {
if let Some(font_obj) = fonts.get(&name) {
let resolved = doc.resolve(font_obj);
if let Some(d) = resolved.as_dict()
&& d.name(b"Subtype") == Some(b"Type3")
&& !drawn_font_names.contains(&name)
{
fonts.remove(&name);
changed = true;
}
if let Some(font_obj) = fonts.get(&name)
&& is_type3(doc, font_obj)
&& !drawn_font_names.contains(&name)
{
fonts.remove(&name);
changed = true;
}
}
@@ -717,9 +750,10 @@ pub(crate) fn unlink_type3(doc: &mut Document) -> Result<(), RedactError> {
}
// For each Type 3 font: unlink unused glyphs from CharProcs and prune exclusive resources.
let mut reads = GlyphReads { used: HashMap::new(), budget: DecodeBudget::page() };
for (font_key, font_dict) in &type3_fonts {
let surviving = used_glyphs.get(font_key).cloned().unwrap_or_default();
clean_type3_font(doc, &holders, &form_holders, font_key, font_dict, &surviving)?;
clean_type3_font(doc, &holders, &form_holders, font_key, font_dict, &surviving, &mut reads)?;
}
Ok(())
@@ -794,6 +828,7 @@ fn clean_type3_font(
font_key: &FontKey,
font_dict: &Dict,
surviving: &HashSet<Vec<u8>>,
reads: &mut GlyphReads,
) -> Result<(), RedactError> {
let Some(char_procs_val) = font_dict.get(b"CharProcs") else {
return Err(CosError::Syntax { offset: 0, detail: "redaction could not establish safe Type 3 font cleanup: missing CharProcs".into() }.into());
@@ -837,6 +872,10 @@ fn clean_type3_font(
let mut used_in_glyphs = UsedInGlyphs::default();
for (_, proc_val) in char_procs.iter() {
if let Some(used) = proc_val.as_ref().and_then(|r| reads.used.get(&r)) {
used_in_glyphs.merge(used);
continue;
}
let resolved = doc.resolve(proc_val);
let Object::Stream(s) = &*resolved else {
return Err(CosError::Syntax {
@@ -845,8 +884,14 @@ fn clean_type3_font(
}
.into());
};
let data = doc.with_direct_parms(s).decoded()?;
collect_used_resources_in_stream(&data, &mut used_in_glyphs)?;
// Past the allowance the cleanup can't be shown complete, and the redaction is refused.
let data = reads.budget.decode(&doc.with_direct_parms(s))?;
let mut used = UsedInGlyphs::default();
collect_used_resources_in_stream(&data, &mut used)?;
used_in_glyphs.merge(&used);
if let Some(r) = proc_val.as_ref() {
reads.used.insert(r, used);
}
}
if prune_type3_font_resources(doc, &mut f_res, &used_in_glyphs) {
+42 -20
View File
@@ -16,7 +16,7 @@ pub(super) fn carries_glyphs(op: &pdfcraft_content::Op) -> bool {
let nonempty = |o: &Object| o.as_string().is_some_and(|s| !s.bytes.is_empty());
match op.op.as_slice() {
b"Tj" | b"'" | b"\"" => op.operands.last().is_some_and(nonempty),
b"TJ" => op.operands.first().and_then(Object::as_array).is_some_and(|a| a.iter().any(nonempty)),
b"TJ" => op.back(0).and_then(Object::as_array).is_some_and(|a| a.iter().any(nonempty)),
_ => false,
}
}
@@ -396,17 +396,38 @@ pub(super) fn push_squashed(into: &mut String, s: &str) {
into.extend(s.chars().filter(|c| !c.is_whitespace() && *c != '\u{feff}'));
}
/// A form's or pattern's `/Matrix`: absent is the identity, present but malformed is an error
/// (guessing the identity would put its content in the wrong place).
pub(super) fn matrix_of(doc: &Document, dict: &Dict) -> Result<Matrix, ()> {
match dict.get(b"Matrix") {
None => Ok(Matrix::IDENTITY),
Some(m) => {
let m = doc.resolve(m);
let items: Vec<Object> = m.as_array().ok_or(())?.iter().map(|x| (*doc.resolve(x)).clone()).collect();
Matrix::from_operands(&items).filter(|m| m.0.iter().all(|v| v.is_finite())).ok_or(())
/// A form's or an annotation appearance's `/Matrix`, the array and each entry direct or by reference: absent or null
/// is the identity, present but malformed is an error (guessing the identity would put its content in the
/// wrong place). A reference to a reference is malformed here: readers disagree on following it
/// (Poppler doesn't, the app's renderer does), so where the content draws can't be told. The
/// redaction walk reads a form's with it too.
pub(crate) fn matrix_of(doc: &Document, dict: &Dict) -> Result<Matrix, ()> {
let Some(m) = dict.get(b"Matrix") else { return Ok(Matrix::IDENTITY) };
// Each reference is followed one hop. The array is read in place when written directly, and
// its length checked before any entry is read: the walk reads it at every `Do`, and an array of
// any length would be copied each time.
let held;
let m = match m {
Object::Ref(r) => {
held = doc.get(*r);
&*held
}
direct => direct,
};
// A null value is no entry (ISO 32000-2 §7.3.9), whether given directly or by reference.
if matches!(m, Object::Null) {
return Ok(Matrix::IDENTITY);
}
let items = m.as_array().filter(|a| a.len() == 6).ok_or(())?;
let mut values = [0.0; 6];
for (value, item) in values.iter_mut().zip(items) {
let n = match item {
Object::Ref(r) => doc.get(*r).as_f64(),
direct => direct.as_f64(),
};
*value = n.filter(|n| n.is_finite()).ok_or(())?;
}
Ok(Matrix(values))
}
/// A form's `/BBox` as `[x0 y0 x1 y1]`: absent is `None`, present but malformed is an error.
@@ -552,7 +573,7 @@ impl Extractor<'_> {
let o = op.op.as_slice();
// Strings and TJ adjustments, in order.
let items: Vec<&Object> = match o {
b"TJ" => op.operands.first().and_then(Object::as_array).map(|a| a.iter().collect()).unwrap_or_default(),
b"TJ" => op.back(0).and_then(Object::as_array).map(|a| a.iter().collect()).unwrap_or_default(),
_ => op.operands.last().into_iter().collect(),
};
let mut any_text = false;
@@ -637,14 +658,15 @@ impl Extractor<'_> {
tm = Matrix::IDENTITY;
tlm = Matrix::IDENTITY;
}
b"Tc" => gs.tc = op.num(0).unwrap_or(0.0),
b"Tw" => gs.tw = op.num(0).unwrap_or(0.0),
b"Tz" => gs.th = op.num(0).unwrap_or(100.0) / 100.0,
b"TL" => gs.tl = op.num(0).unwrap_or(0.0),
b"Ts" => gs.rise = op.num(0).unwrap_or(0.0),
// Operands are read from the end, as the renderer reads them.
b"Tc" => gs.tc = op.num_back(0).unwrap_or(0.0),
b"Tw" => gs.tw = op.num_back(0).unwrap_or(0.0),
b"Tz" => gs.th = op.num_back(0).unwrap_or(100.0) / 100.0,
b"TL" => gs.tl = op.num_back(0).unwrap_or(0.0),
b"Ts" => gs.rise = op.num_back(0).unwrap_or(0.0),
b"Tf" => {
gs.font = op.name(0).map(<[u8]>::to_vec).unwrap_or_default();
gs.size = op.num(1).unwrap_or(0.0);
gs.font = op.name_back(1).map(<[u8]>::to_vec).unwrap_or_default();
gs.size = op.num_back(0).unwrap_or(0.0);
}
b"Td" | b"TD" => {
if let Some([x, y]) = op.nums::<2>() {
@@ -671,7 +693,7 @@ impl Extractor<'_> {
tm = tlm;
}
if o == b"\""
&& let (Some(aw), Some(ac)) = (op.num(0), op.num(1))
&& let (Some(aw), Some(ac)) = (op.num_back(2), op.num_back(1))
{
(gs.tw, gs.tc) = (aw, ac);
}
@@ -686,7 +708,7 @@ impl Extractor<'_> {
self.show_text(font, &op, &gs, &mut tm, placed);
}
b"Do" => {
let Some(name) = op.name(0) else { continue };
let Some(name) = op.last_name() else { continue };
let Some(entry) = xobjects.get(name) else { continue };
if let Object::Stream(s) = &*doc.resolve(entry)
&& s.dict.name(b"Subtype") == Some(b"Form")
+14 -7
View File
@@ -188,7 +188,7 @@ impl Geo<'_> {
}
}
b"Do" => {
let Some(entry) = op.name(0).and_then(|n| xobjects.get(n)) else { continue };
let Some(entry) = op.last_name().and_then(|n| xobjects.get(n)) else { continue };
let obj = self.doc.resolve(entry);
let Object::Stream(s) = &*obj else { continue };
match s.dict.name(b"Subtype") {
@@ -344,7 +344,7 @@ impl Geo<'_> {
match op.op.as_slice() {
b"BI" => return Ok(true),
b"Do" => {
let Some(entry) = op.name(0).and_then(|n| xobjects.get(n)) else { continue };
let Some(entry) = op.last_name().and_then(|n| xobjects.get(n)) else { continue };
let Object::Stream(x) = &*self.doc.resolve(entry) else { continue };
match x.dict.name(b"Subtype") {
Some(b"Image") => return Ok(true),
@@ -372,21 +372,28 @@ impl Geo<'_> {
/// carries) by one construction operator.
fn extend_path(op: &pdfcraft_content::Op, ctm: &Matrix, sub: &mut Vec<Vec<(f64, f64)>>, clip: &mut Option<bool>) {
let o = op.op.as_slice();
let nums: Vec<f64> = op.operands.iter().filter_map(Object::as_f64).collect();
let at = |x: f64, y: f64| ctm.apply(x, y);
// Each takes its numbers from the end, as the renderer reads them: a surplus before them is
// ignored, not read as a point.
let points: Option<Vec<(f64, f64)>> = match o {
b"l" => op.nums::<2>().map(|[x, y]| vec![at(x, y)]),
b"c" => op.nums::<6>().map(|[x1, y1, x2, y2, x3, y3]| vec![at(x1, y1), at(x2, y2), at(x3, y3)]),
b"v" | b"y" => op.nums::<4>().map(|[x1, y1, x2, y2]| vec![at(x1, y1), at(x2, y2)]),
_ => None,
};
match o {
b"m" => {
if let [x, y] = nums[..] {
if let Some([x, y]) = op.nums::<2>() {
sub.push(vec![at(x, y)]);
}
}
b"l" | b"c" | b"v" | b"y" => {
if let Some(cur) = sub.last_mut() {
cur.extend(nums.as_chunks::<2>().0.iter().map(|p| at(p[0], p[1])));
if let (Some(cur), Some(points)) = (sub.last_mut(), points) {
cur.extend(points);
}
}
b"re" => {
if let [x, y, w, h] = nums[..] {
if let Some([x, y, w, h]) = op.nums::<4>() {
sub.push(vec![at(x, y), at(x + w, y), at(x + w, y + h), at(x, y + h)]);
}
}
+1
View File
@@ -70,6 +70,7 @@ mod snapshot;
mod sweep;
mod util;
pub(crate) use extract::matrix_of;
pub use snapshot::Snapshot;
/// What the proof established for one region.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+59
View File
@@ -0,0 +1,59 @@
//! Work regression for a form's `/Matrix`, which the redaction walk reads at every `Do` of the
//! form: an array of any length costs no more than one of seven entries, written directly or by
//! reference. A test binary of its own, so that none of the crate's other tests shares its process.
//! The test compares two timings of its own, the least of three runs each, not a fixed time.
use std::sync::Arc;
use std::time::{Duration, Instant};
use pdfcraft_annot::{Meta, NewAnnotation, Shape, Style, add_annotation, rect_quad};
use pdfcraft_cos::Document;
use pdfcraft_redact::apply;
use pdfcraft_testkit::{Pdf, stream_obj};
/// One page drawing a form `draws` times under a mark, the form's `/Matrix` an array of `entries`
/// zeros, written in its dictionary or, `by_reference`, as object 6.
fn document(draws: usize, entries: usize, by_reference: bool) -> Document {
let zeros = format!("[{}]", vec!["0"; entries].join(" "));
let matrix = if by_reference { "6 0 R".to_string() } else { zeros.clone() };
let objs = vec![
b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(),
b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(),
b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Contents 4 0 R /Resources << /XObject << /Fm 5 0 R >> >> >>".to_vec(),
stream_obj("", "/Fm Do ".repeat(draws).as_bytes()),
stream_obj(&format!("/Type /XObject /Subtype /Form /BBox [0 0 300 300] /Matrix {matrix}"), b"0 0 10 10 re f"),
zeros.into_bytes(),
];
let mut doc = Document::open(Arc::new(Pdf::new().objs(objs).build())).unwrap();
let shape = Shape::Redact { quads: vec![rect_quad([0.0, 0.0, 300.0, 300.0])], overlay: String::new(), look: Default::default() };
let style = Style::default_for(&shape);
add_annotation(&mut doc, &NewAnnotation { page: 0, shape, style, contents: String::new(), author: "Synthetic test".into() }, &Meta::default())
.unwrap();
doc
}
/// How long redacting `document(draws, entries, by_reference)` takes, the least of three runs. A
/// matrix that isn't six numbers is refused.
fn redaction(draws: usize, entries: usize, by_reference: bool) -> Duration {
(0..3)
.map(|_| {
let mut doc = document(draws, entries, by_reference);
let start = Instant::now();
let refused = apply(&mut doc, None).is_err();
let took = start.elapsed();
assert!(refused, "a /Matrix of {entries} entries is refused");
took
})
.min()
.unwrap_or_default()
}
/// Written when the walk resolved and copied every entry before checking there were six: 4,000
/// draws of a form whose `/Matrix` is 4,000 entries long read sixteen million entries.
#[test]
fn a_long_form_matrix_costs_no_more_than_a_short_one() {
for by_reference in [false, true] {
let (short, long) = (redaction(4_000, 7, by_reference), redaction(4_000, 4_000, by_reference));
assert!(long < short * 3 + Duration::from_millis(50), "by reference: {by_reference}: long {long:?}, short {short:?}");
}
}
+98
View File
@@ -0,0 +1,98 @@
//! Work regressions for what a redaction looks up at operators a stream can hold thousands of: the
//! tags cleanup's named property lists at each `BDC` are not read whole each time. A test binary of
//! its own, so that none of the crate's other tests shares its process, and its tests run one at a
//! time. Each test compares two timings of its own, the least of three runs each, with many
//! entries or operators and with one, not a fixed time. The bound leaves room for slower machines:
//! each regression took seconds against milliseconds.
use std::sync::{Arc, Mutex, PoisonError};
use std::time::{Duration, Instant};
use pdfcraft_annot::{Meta, NewAnnotation, Shape, Style, add_annotation, rect_quad};
use pdfcraft_cos::Document;
use pdfcraft_redact::apply;
use pdfcraft_testkit::{Pdf, stream_obj};
/// One page with `resources` and `extra` objects (from object 5 on), drawing a word under a mark
/// (so the redaction rewrites the page) and then `ops`.
fn page(resources: &str, ops: &[u8], extra: Vec<Vec<u8>>) -> Document {
let content = [b"BT /F1 10 Tf 20 260 Td (SECRET) Tj ET ".as_slice(), ops].concat();
let mut objs = vec![
b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(),
b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(),
format!(
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Contents 4 0 R /Resources << /Font << /F1 << /Type /Font /Subtype /Type1 /BaseFont /Helvetica >> >> {resources} >> >>"
)
.into_bytes(),
stream_obj("", content),
];
objs.extend(extra);
let mut doc = Document::open(Arc::new(Pdf::new().objs(objs).build())).unwrap();
let shape = Shape::Redact { quads: vec![rect_quad([0.0, 200.0, 300.0, 300.0])], overlay: String::new(), look: Default::default() };
let style = Style::default_for(&shape);
add_annotation(&mut doc, &NewAnnotation { page: 0, shape, style, contents: String::new(), author: "Synthetic test".into() }, &Meta::default())
.unwrap();
doc
}
/// One page whose `/Properties` holds `entries` entries, drawing `ops`.
fn properties(entries: usize, ops: &[u8]) -> Document {
let lists: String = (0..entries).map(|i| format!("/M{i} << /Lang (en) >> ")).collect();
page(&format!("/Properties << {lists}>>"), ops, Vec::new())
}
/// One page whose property list `/M0` is object 5, which gives its `MCID` as object 6 and holds
/// 400,000 more entries: larger than the document keeps, so that reading it again parses it again,
/// all of it, once another object has been read since. The page draws `ops`.
fn oversized(ops: &[u8]) -> Document {
let more: String = (0..400_000).map(|i| format!("/J{i} /DeviceGray ")).collect();
page("/Properties << /M0 5 0 R >>", ops, vec![format!("<< /MCID 6 0 R {more}>>").into_bytes(), b"0".to_vec()])
}
/// The tests' lock: they run one at a time, so that none is timed while another works.
static SERIAL: Mutex<()> = Mutex::new(());
fn one_at_a_time() -> std::sync::MutexGuard<'static, ()> {
SERIAL.lock().unwrap_or_else(PoisonError::into_inner)
}
/// How long redacting a document `make` builds takes, the least of three runs.
fn redaction(make: impl Fn() -> Document) -> Duration {
(0..3)
.map(|_| {
let mut doc = make();
let start = Instant::now();
let report = apply(&mut doc, None).unwrap();
let took = start.elapsed();
assert_eq!(report.glyphs, 6, "the word under the mark goes");
took
})
.min()
.unwrap_or_default()
}
/// Whether `many` took about as long as `one`.
fn about_as_long(many: Duration, one: Duration) -> bool {
many < one * 10 + Duration::from_secs(1)
}
/// Written when the tags cleanup resolved the page's `/Properties` at every named `BDC`: 20,000 of
/// them with 5,000 entries took 28 s against 0.07 s with one entry (optimized). Each `BDC` here
/// names another entry, so that it is the lists, not each name's answer, that are read once.
#[test]
fn named_property_lists_are_read_once_for_a_page() {
let _serial = one_at_a_time();
let ops: Vec<u8> = (0..5_000).map(|i| format!("/P /M{i} BDC EMC ")).collect::<String>().into_bytes();
let (one, many) = (redaction(|| properties(1, &ops)), redaction(|| properties(5_000, &ops)));
assert!(about_as_long(many, one), "5,000 entries {many:?}, one {one:?}");
}
/// Written when the tags cleanup read a named property list's `MCID` by reference at each `BDC`: a
/// list larger than the document keeps was parsed again at each, 50 of them taking 12.3 s against
/// 0.44 s with the `MCID` given directly (optimized).
#[test]
fn an_oversized_property_list_is_read_once_for_a_stream() {
let _serial = one_at_a_time();
let (one, many) = (redaction(|| oversized(b"/P /M0 BDC EMC ")), redaction(|| oversized(&b"/P /M0 BDC EMC ".repeat(100))));
assert!(about_as_long(many, one), "100 operators {many:?}, one {one:?}");
}
+15
View File
@@ -325,6 +325,21 @@ fn an_indirect_annots_array_is_judged_by_the_annotations_it_gains() {
assert_eq!((s.status, s.modification), (Status::Invalid, Modification::Disallowed(vec![kind::OTHER])));
}
/// A signature widget taken off the page's inline /Annots array is covered by no permission (the
/// indirect-array case is the test above), and stays a change whatever level the signature has.
#[test]
fn removing_a_widget_from_an_inline_annots_array_is_not_a_comment_change() {
let id = pkcs12::open(&data("rsa-aes.p12"), "test").unwrap();
let trust = TrustStore { certs: vec![id.certificate.clone()] };
let page = pdfcraft_cos::ObjRef { num: 3, generation: 0 };
let signed = pdfcraft_sign::sign(&open(&fixture()), &id, &opts()).unwrap();
let inline = open(&signed).get(page).as_dict().and_then(|d| d.get(b"Annots").cloned()).unwrap();
assert!(matches!(inline, Object::Array(ref a) if !a.is_empty()), "the page keeps its widgets inline");
let stripped = edit_after(&signed, |doc| doc.update_dict(page, |p| p.set(b"Annots".to_vec(), Object::Array(vec![]))).unwrap());
let s = signatures(&open(&stripped), &stripped, &trust).into_iter().find(|s| s.signed).unwrap();
assert_eq!((s.status, s.modification), (Status::Invalid, Modification::Disallowed(vec![kind::OTHER])));
}
/// Issue #1328: a signature field whose /V is null, directly or through a reference, is unsigned:
/// it is listed as unsigned and can be signed by name.
#[test]
+26 -18
View File
@@ -257,6 +257,14 @@ impl PdfCraftApp {
Some(Err(error)) => self.notify_fmt("Couldn't open {name}: {e}", &[("name", &pending.name), ("e", &error)]),
None => {}
},
open_worker::ResultKind::Converted(created) => match self.open_converted_pdf(&pending.name, created) {
Ok(()) => {
if let Some(command) = pending.then {
self.execute(command);
}
}
Err(error) => self.notify_fmt("Couldn't open {name}: {e}", &[("name", &pending.name), ("e", &error)]),
},
open_worker::ResultKind::Prepared { bytes, result } => match *result {
Ok(prepared) => match self.finish_open(&pending.name, pending.path.clone(), bytes.len(), prepared, pending.activate) {
Ok(id) => {
@@ -1009,24 +1017,29 @@ impl PdfCraftApp {
self.open_path_request(path, None, Some((layout, continuous)));
}
/// The File ▸ Open picker: PDFs, and images and text that become PDFs.
#[cfg(not(target_arch = "wasm32"))]
/// The File ▸ Open picker's file types, in order; the first, PDF, is the default. Images, text
/// and (on the desktop, through LibreOffice) Office documents open as new, unsaved PDFs.
/// No "All files" in the browser or on macOS, whose panel merges every type into one list
/// rather than offering a choice.
pub(crate) fn open_filters() -> Vec<(String, Vec<&'static str>)> {
let mut filters = vec![("PDF".to_string(), vec!["pdf"]), (tl!("Images").to_string(), pdfcraft_engine::IMAGE_EXTENSIONS.to_vec())];
#[cfg(not(target_arch = "wasm32"))]
filters.push((tl!("Office documents").to_string(), pdfcraft_engine::OFFICE_EXTENSIONS.to_vec()));
filters.push((tl!("Text").to_string(), pdfcraft_engine::TEXT_EXTENSIONS.to_vec()));
#[cfg(not(any(target_arch = "wasm32", target_os = "macos")))]
filters.push((tl!("All files").to_string(), vec!["*"]));
filters
}
/// The File ▸ Open picker ([`Self::open_filters`]), each type matched in any letter case.
pub(super) fn open_picker() -> rfd::AsyncFileDialog {
rfd::AsyncFileDialog::new()
.add_filter_any_case("PDF", &["pdf"])
.add_filter_any_case(tl!("Images and text (converted to PDF)"), &create_ui::CONVERTIBLE)
Self::open_filters().into_iter().fold(rfd::AsyncFileDialog::new(), |dialog, (name, extensions)| dialog.add_filter_any_case(name, &extensions))
}
pub fn open_dialog(&mut self) {
self.startup_superseded = true;
#[cfg(not(target_arch = "wasm32"))]
self.pick(
pickers::PickFor::Open,
rfd::AsyncFileDialog::new()
.add_filter_any_case("PDF", &["pdf"])
.add_filter_any_case(tl!("Images and text (converted to PDF)"), &create_ui::CONVERTIBLE),
true,
);
self.pick(pickers::PickFor::Open, Self::open_picker(), true);
// Browsers pick files asynchronously; the bytes arrive through `inbox`.
#[cfg(target_arch = "wasm32")]
{
@@ -1035,12 +1048,7 @@ impl PdfCraftApp {
let read = super::input::WebRead::start(&self.web_reads);
wasm_bindgen_futures::spawn_local(async move {
let _read = read;
if let Some(h) = rfd::AsyncFileDialog::new()
.add_filter_any_case("PDF", &["pdf"])
.add_filter_any_case(tl!("Images and text"), &create_ui::CONVERTIBLE)
.pick_file()
.await
{
if let Some(h) = Self::open_picker().pick_file().await {
let bytes = h.read().await;
if let Ok(mut q) = inbox.lock() {
q.push((h.file_name(), bytes));
+5
View File
@@ -1448,6 +1448,8 @@ struct PageFrame<'a> {
current_height: f32,
pressed_page: Option<usize>,
calc_hover: Option<crate::calc_order_ui::Focus>,
/// The form field widget under the pointer on any page, for its Mouse Enter and Exit scripts.
field_hover: Option<crate::forms_ui::WidgetRef>,
/// A page took this frame's right-click.
right_clicked: bool,
}
@@ -1930,6 +1932,7 @@ fn draw_pages(
current_height: f32::INFINITY,
pressed_page: None,
calc_hover: None,
field_hover: None,
right_clicked: false,
};
for &i in visible_pages {
@@ -1944,10 +1947,12 @@ fn draw_pages(
current_height,
pressed_page,
calc_hover,
field_hover,
out: page_out,
right_clicked,
..
} = frame;
crate::forms_ui::hover_moved(view, field_hover);
// A right-click no page took deselects the comment, so the page's menu opens, not the comment's,
// and with Edit text the picture (one on a page went to that page, `page_input`).
if resp.secondary_clicked() && !right_clicked {
+3
View File
@@ -966,6 +966,9 @@ pub(super) fn page_overlays(ui: &mut egui::Ui, view: &mut DocView, frame: &mut P
} else {
crate::forms_ui::paint_page(painter, &xf, i, info, form, view, input.hover.as_ref());
crate::forms_ui::tooltip(resp, form, input.hover.as_ref());
if let Some(hovered) = crate::forms_ui::hovered(form, input.hover.as_ref()) {
frame.field_hover = Some(hovered);
}
}
// Form-field highlight (Acrobat's "Highlight existing fields"); required fields get a
+89 -3
View File
@@ -524,10 +524,22 @@ impl PdfCraftApp {
// click that brought this pane forward took the focus). It goes in first, as it came first.
let (other_applied, stay) = self.apply_other_pane_edit(i);
let modal = self.modal_open();
let generation = |app: &Self| app.views.get(i).and_then(|v| app.session.get(v.id)).map(|d| d.edit_generation());
let before = generation(self);
let queued = self.views.get(i).is_some_and(|v| v.pending_edit.is_some());
let applied = self.apply_queued_edit(i) && other_applied;
// A click's Mouse Up waits on the edit it queued (a check box's toggle, a list's pick):
// when that was refused, the click did nothing and its Mouse Up doesn't run either.
if queued
&& generation(self) == before
&& let Some(view) = self.views.get_mut(i)
{
view.forms.triggers.retain(|(_, t)| *t != pdfcraft_engine::FieldTrigger::MouseUp);
}
// After the queued edit: a value typed into the field the focus left has been taken (and
// its change has run the field's exit) before the focus scripts run.
self.run_focus_scripts(i);
self.run_field_triggers(i);
if !applied {
// Nor may a shortcut pressed with it (⌘S right after Enter) run behind the refusal.
self.deferred_commands.clear();
@@ -818,7 +830,8 @@ impl PdfCraftApp {
/// ([`crate::forms_ui::refresh_draft`]), so leaving the field doesn't write the old value back.
fn run_focus_scripts(&mut self, i: usize) {
let Some(view) = self.views.get_mut(i) else { return };
let now = view.forms.focus.as_ref().map(|f| (f.name.clone(), f.widget));
// The field's object too: moving between fields sharing a name is a move (#344 review).
let now = view.forms.focus.as_ref().map(|f| (f.name.clone(), f.obj, f.widget));
if view.forms.focused == now {
return;
}
@@ -826,13 +839,13 @@ impl PdfCraftApp {
let id = view.id;
let edited = view.forms.focus.clone();
use pdfcraft_engine::js::FieldFocus;
for ((name, widget), focus) in [left.map(|l| (l, FieldFocus::Exit)), now.map(|n| (n, FieldFocus::Enter))].into_iter().flatten() {
for ((name, obj, widget), focus) in [left.map(|l| (l, FieldFocus::Exit)), now.map(|n| (n, FieldFocus::Enter))].into_iter().flatten() {
// The edited field's value before this script, to tell its untouched draft from typing:
// the exit of the field left may have changed it already, and the draft with it.
let before: Option<(String, Vec<String>)> = edited.as_ref().and_then(|e| {
crate::forms_ui::focused_field(e, &self.session.get(id)?.form).map(|f| (crate::forms_ui::draft_text(f), f.value.clone()))
});
match self.session.field_focus(id, &name, widget, focus) {
match self.session.field_focus_target(id, &name, obj.map(pdfcraft_engine::js::field_object_id), widget, focus) {
Ok(changed) => {
if changed
&& let Some(info) = self.session.get(id).map(|d| d.info.clone())
@@ -854,6 +867,42 @@ impl PdfCraftApp {
}
}
/// The pointer triggers tab `i` queued (Mouse Enter, Exit, Down, and a check box's Mouse Up
/// after its toggle), each running its widget's JavaScript in the document's realm (#269).
fn run_field_triggers(&mut self, i: usize) {
let Some(view) = self.views.get_mut(i) else { return };
let triggers = std::mem::take(&mut view.forms.triggers);
let id = view.id;
for ((name, object, widget), trigger) in triggers {
// The field being edited as it was, so a script changing it shows in its editor
// while a draft the user already typed into is kept (as `run_focus_scripts` does).
let before: Option<(String, Vec<String>)> = self.views.get(i).and_then(|v| v.forms.focus.as_ref()).and_then(|e| {
crate::forms_ui::focused_field(e, &self.session.get(id)?.form).map(|f| (crate::forms_ui::draft_text(f), f.value.clone()))
});
match self.session.field_trigger_target(id, &name, Some(object), widget, trigger) {
Ok(changed) => {
if changed
&& let Some(info) = self.session.get(id).map(|d| d.info.clone())
&& let Some(view) = self.views.get_mut(i)
{
view.document_changed(&info);
if let Some(before) = &before
&& let Some(draft) = view.forms.focus.as_mut()
&& let Some(f) = self.session.get(id).and_then(|d| crate::forms_ui::focused_field(draft, &d.form))
{
crate::forms_ui::refresh_draft(draft, (&before.0, &before.1), (crate::forms_ui::draft_text(f), &f.value));
}
}
let out = self.session.take_js_output(id);
if !out.is_empty() {
self.handle_js(id, out);
}
}
Err(e) => self.notify_error(e),
}
}
}
/// Apply the edit queued on tab `i` (the active one). Returns false only when it was a
/// field's typing and the field refused it (#166): the editor reopens with the text, and the
/// user has been told why, so the typing isn't lost and the caller can stop.
@@ -1578,6 +1627,43 @@ mod revert_draft_tests {
assert_eq!(hint(&app), "", "hint's enter ran before the document is read");
assert_eq!(app.views[0].forms.focus.as_ref().map(|f| f.text.as_str()), Some(""), "and its editor shows it");
}
/// A pointer trigger whose script changes the field being edited shows the change in its
/// editor, unless the user already typed there: then the typed draft is kept.
#[test]
fn a_pointer_trigger_changing_the_edited_field_refreshes_an_untouched_draft() {
let objs = [
"<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [4 0 R 6 0 R] /DA (/Helv 0 Tf 0 g) /DR << /Font << /Helv 5 0 R >> >> >> >>".to_string(),
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 200 300] >>".into(),
"<< /Type /Page /Parent 2 0 R /Annots [4 0 R 6 0 R] >>".into(),
"<< /Type /Annot /Subtype /Widget /FT /Tx /T (name) /V (old) /Rect [20 250 180 270] /P 3 0 R /F 4 >>".into(),
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".into(),
"<< /Type /Annot /Subtype /Widget /FT /Tx /T (hot) /V () /Rect [20 200 180 220] /P 3 0 R /F 4 /AA << /E << /S /JavaScript /JS (getField\\('name'\\).value = 'new';) >> >> >>".into(),
];
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{o}\nendobj\n", i + 1).as_bytes());
}
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());
for (typed, shown) in [(false, "new"), (true, "typed")] {
let mut app = PdfCraftApp::new();
app.open_bytes("hot.pdf", None, pdf.clone()).unwrap();
let hot = app.session.get(app.views[0].id).unwrap().form.iter().find(|f| f.name == "hot").unwrap().obj;
let text = if typed { "typed" } else { "old" };
app.views[0].forms.focus = Some(Focus { text: text.into(), picked: vec!["old".into()], ..focus("") });
let hot = ("hot".to_string(), pdfcraft_engine::js::field_object_id(hot), 0);
app.views[0].forms.triggers.push((hot, pdfcraft_engine::FieldTrigger::MouseEnter));
app.run_field_triggers(0);
assert_eq!(app.views[0].forms.focus.as_ref().map(|f| f.text.as_str()), Some(shown), "typed: {typed}");
}
}
#[test]
fn successful_revert_clears_focused_or_queued_drafts_only_on_its_document() {
for queued in [false, true] {
+2
View File
@@ -128,6 +128,7 @@ impl PdfCraftApp {
if !self.flatten_fill_sign_for_save(id) {
return false;
}
self.run_document_actions(id, pdfcraft_engine::js::DocumentScriptEvent::WillSave);
let bytes = match self.session.save_bytes(id) {
Ok(b) => b,
Err(e) => {
@@ -293,6 +294,7 @@ impl PdfCraftApp {
self.notify_tr("The document was closed before it could be saved.");
return false;
};
self.run_document_actions(id, pdfcraft_engine::js::DocumentScriptEvent::WillSave);
let bytes = if full { self.session.save_full_bytes(id) } else { self.session.save_bytes(id) };
let bytes = match bytes.and_then(|b| self.session.check_save(id, &b).map(|()| b)) {
Ok(b) => b,
+11 -3
View File
@@ -20,7 +20,12 @@ pub(crate) enum Input {
pub(crate) enum ResultKind {
Conversion(Arc<Vec<u8>>),
Prepared { bytes: Arc<Vec<u8>>, result: Box<Result<PreparedDocument, OpenError>> },
/// An Office document LibreOffice converted here, off the frame thread, or why it couldn't.
Converted(Result<Arc<Vec<u8>>, String>),
Prepared {
bytes: Arc<Vec<u8>>,
result: Box<Result<PreparedDocument, OpenError>>,
},
ReadFailed(String),
RemoteFailed(String),
RecoveryFailed(String),
@@ -213,8 +218,11 @@ fn prepare(job: Job) -> ResultKind {
},
Input::Bytes(bytes) => bytes.clone(),
};
if matches!(pdfcraft_engine::source_kind(&job.name, &bytes), Some(SourceKind::Image | SourceKind::Text)) {
return ResultKind::Conversion(bytes);
match pdfcraft_engine::source_kind(&job.name, &bytes) {
Some(SourceKind::Image | SourceKind::Text) => return ResultKind::Conversion(bytes),
// LibreOffice takes seconds: it runs here, and the frame thread only opens the result.
Some(SourceKind::Office) => return ResultKind::Converted(pdfcraft_engine::office_to_pdf(&job.name, &bytes).map_err(|e| e.to_string())),
Some(SourceKind::Pdf) | None => {}
}
let result = job.context.prepare_open(job.name, job.path, bytes.clone(), job.password.as_deref().map(String::as_str));
ResultKind::Prepared { bytes, result: Box::new(result) }
@@ -130,10 +130,15 @@ impl HeldToolOpen {
self.started.recv_timeout(Duration::from_secs(5)).expect("the native open reached its preparation barrier");
}
#[allow(clippy::expect_used)]
fn complete(&self, harness: &mut Harness<'static, PdfCraftApp>) {
self.complete_within(harness, Duration::from_secs(5));
}
/// [`Self::complete`] for a preparation that may take up to `timeout`.
#[allow(clippy::expect_used)]
fn complete_within(&self, harness: &mut Harness<'static, PdfCraftApp>, timeout: Duration) {
self.release.send(()).expect("release the native preparation");
self.finished.recv_timeout(Duration::from_secs(5)).expect("the native open returned its result");
self.finished.recv_timeout(timeout).expect("the native open returned its result");
harness.run_steps(2);
}
}
@@ -997,3 +1002,55 @@ fn a_password_prompt_keeps_a_place_in_the_open_queue_for_its_retry() {
assert!(app.password_prompt.is_none(), "the retry is queued: {:?}", app.password_prompt.as_ref().and_then(|p| p.error.clone()));
assert!(app.password_retry.is_some());
}
/// A Word document built from the synthetic fixture (PdfCraft's own Word export).
#[allow(clippy::expect_used)]
fn synthetic_docx() -> Vec<u8> {
let mut session = pdfcraft_engine::Session::new();
let id = session.open("source.pdf", None, Arc::new(fixture(1)), None).expect("open the fixture");
session.get(id).expect("the fixture").export_office(pdfcraft_engine::compare::OfficeFormat::Docx)
}
/// File ▸ Open of a Word document: LibreOffice runs on the open worker, never on the frame
/// thread, and the result opens as a new, unsaved PDF. Without LibreOffice the user is
/// told it is needed, rather than that the file is a broken PDF.
#[test]
#[allow(clippy::expect_used)]
fn file_open_converts_an_office_document_on_the_worker() {
let mut harness = tool_open_harness();
let held = HeldToolOpen::install(&mut harness);
let file = tool_open_file("office", "docx", &synthetic_docx());
harness.state_mut().pick_override = Some(vec![file.0.to_string_lossy().into_owned()]);
harness.state_mut().run_command("file.open");
harness.run_steps(2);
held.wait_started();
assert!(harness.state().views.is_empty(), "nothing opens before the conversion finishes");
// An installed LibreOffice takes seconds; it is stopped after 120 s.
held.complete_within(&mut harness, Duration::from_secs(150));
let app = harness.state();
assert!(app.pending_opens.is_empty());
if let Some(view) = app.views.first() {
let doc = app.session.get(view.id).expect("the converted document");
// Named after the Word file: `<stem>.docx` opens as `<stem>.pdf`.
assert_eq!(doc.name, format!("pdfcraft-open-tool-{}-office.pdf", std::process::id()));
assert!(doc.path.is_none(), "the converted PDF is new and unsaved, not the .docx on disk");
} else {
let message = app.toast.as_ref().map(|(message, _)| message.clone()).unwrap_or_default();
assert!(message.contains("LibreOffice, which isn't installed"), "the failure names the missing dependency: {message}");
}
}
#[test]
fn the_open_picker_defaults_to_pdf_and_offers_images_office_text_and_all_files() {
let filters = PdfCraftApp::open_filters();
let names: Vec<&str> = filters.iter().map(|(name, _)| name.as_str()).collect();
#[cfg(not(target_os = "macos"))]
assert_eq!(names, ["PDF", "Images", "Office documents", "Text", "All files"]);
#[cfg(target_os = "macos")]
assert_eq!(names, ["PDF", "Images", "Office documents", "Text"]);
let extensions = |name: &str| filters.iter().find(|(n, _)| n == name).map(|(_, e)| e.clone()).unwrap_or_default();
assert_eq!(extensions("PDF"), ["pdf"]);
assert_eq!(extensions("Images"), pdfcraft_engine::IMAGE_EXTENSIONS);
assert!(["doc", "docx", "xls", "xlsx", "ppt", "pptx", "odt", "rtf"].iter().all(|e| extensions("Office documents").contains(e)));
assert_eq!(extensions("Text"), pdfcraft_engine::TEXT_EXTENSIONS);
}
+53 -1
View File
@@ -101,11 +101,18 @@ pub struct FormView {
/// The field and widget that had focus when it was last looked at: when the focus moves, the
/// one it left runs its XFA exit scripts and the one it reached its enter scripts
/// (`PdfCraftApp::run_focus_scripts`).
pub(crate) focused: Option<(String, usize)>,
pub(crate) focused: Option<(String, Option<ObjRef>, usize)>,
/// The list box row clicked last, without Shift: (its field name, the row). A Shift-click picks
/// the rows from it to the one clicked; the field's value can't say which row came last when
/// rows share an export value, and `/I` lists them in ascending order.
pub(crate) list_anchor: Option<(String, usize)>,
/// The field and widget under the pointer when it was last looked at: when it changes, the
/// one left runs its Mouse Exit JavaScript and the one reached its Mouse Enter (#269).
pub(crate) hovered: Option<WidgetRef>,
/// Pointer triggers waiting to run their widget's JavaScript, in order (field name, widget,
/// trigger): `PdfCraftApp::run_field_triggers` runs them after the frame's edit, so a check
/// box's Mouse Up sees the value its click just stored (#247).
pub(crate) triggers: Vec<(WidgetRef, pdfcraft_engine::FieldTrigger)>,
}
/// A form message for the app to show, with document data kept separate so the visible
@@ -458,6 +465,38 @@ pub(crate) fn hit(xf: &PageXform, info: &DocInfo, page: usize, form: &[FormField
Some(Hit::new(Owner::Field { field, widget }, Layer::Field, icon))
}
/// A widget a pointer trigger is for: its field's name and object (so a field sharing another's
/// name runs its own script), and the widget's index in the field.
pub(crate) type WidgetRef = (String, u64, usize);
/// `f`'s widget `widget` as a trigger names it.
fn widget_ref(f: &FormField, widget: usize) -> WidgetRef {
(f.name.clone(), pdfcraft_engine::js::field_object_id(f.obj), widget)
}
/// The field and widget under the pointer on a page, when a press there would take it.
pub(crate) fn hovered(form: &[FormField], hover: Option<&Hit>) -> Option<WidgetRef> {
match hover.map(|h| h.owner) {
Some(Owner::Field { field, widget }) => form.get(field).map(|f| widget_ref(f, widget)),
_ => None,
}
}
/// Queue Mouse Exit for the widget the pointer left and Mouse Enter for the one it reached, when
/// they differ from the last frame's (`now`: the widget under the pointer on any page).
pub(crate) fn hover_moved(view: &mut DocView, now: Option<WidgetRef>) {
if view.forms.hovered == now {
return;
}
let left = std::mem::replace(&mut view.forms.hovered, now.clone());
if let Some(w) = left {
view.forms.triggers.push((w, pdfcraft_engine::FieldTrigger::MouseExit));
}
if let Some(w) = now {
view.forms.triggers.push((w, pdfcraft_engine::FieldTrigger::MouseEnter));
}
}
/// The tooltip (`/TU`) of the field under the pointer, as Acrobat shows it on hover (#3854): only
/// where the field is what a press would take (`hover`, the top hit there). ISO 32000-2 Table 226
/// makes it the name the user interface identifies the field by.
@@ -484,6 +523,10 @@ pub(crate) fn page_input(
let PagePress::Mine(Owner::Field { field, widget: wi }) = press else { return false };
let Some((f, w)) = form.get(field).and_then(|f| f.widgets.get(wi).map(|w| (f, w))) else { return false };
let usable = usable(f, w, allowed);
// The press runs the widget's Mouse Down JavaScript, as in Acrobat (#269).
if usable && ptr.pressed().is_some() {
view.forms.triggers.push((widget_ref(f, wi), pdfcraft_engine::FieldTrigger::MouseDown));
}
// A text field opens on the press rather than the click, so a drag that starts on it
// selects its text (#2213).
if f.kind == FormFieldKind::Text
@@ -544,6 +587,10 @@ pub(crate) fn page_input(
commit(view, form);
view.forms.focus = Some(open_focus(f, wi));
}
// A combo box's click runs its Mouse Up JavaScript (#269).
if f.kind == FormFieldKind::Combo {
view.forms.triggers.push((widget_ref(f, wi), pdfcraft_engine::FieldTrigger::MouseUp));
}
}
FormFieldKind::List => {
let Some(p) = ptr.within(xf.rect) else { return true };
@@ -589,6 +636,8 @@ pub(crate) fn page_input(
view.pending_edit = Some(list_pick_edit(form, f, picked));
}
}
// A list box's click runs its Mouse Up JavaScript after the pick is stored (#269).
view.forms.triggers.push((widget_ref(f, wi), pdfcraft_engine::FieldTrigger::MouseUp));
}
}
true
@@ -1376,6 +1425,9 @@ pub(crate) fn overlay(
view.forms.toggle = true;
} else if toggle {
edit = toggle_edit(f, focus.widget);
// The click's Mouse Up JavaScript runs once the toggle is stored, so it reads the
// new value (#247).
view.forms.triggers.push((widget_ref(f, focus.widget), pdfcraft_engine::FieldTrigger::MouseUp));
} else if space {
// Space toggles a check box and selects a radio button, as in browsers: it never
// turns the selected button off.
@@ -39,9 +39,15 @@ fn combinable(ext: &str) -> bool {
}
/// Whether Combine takes a file by what it is: a PDF (by its header or its name) or an image or
/// text file it converts, as `Session::as_pdf` tells them apart.
/// text file it converts, as `Session::as_pdf_inline` tells them apart. Not an Office document:
/// converting one runs LibreOffice for seconds, which Combine can't do on the frame thread, so
/// it is left out and named rather than listed as a file that can't be read.
pub(super) fn takes(name: &str, bytes: &[u8]) -> bool {
pdfcraft_engine::source_kind(name, bytes).is_some() || name.to_ascii_lowercase().ends_with(".pdf")
match pdfcraft_engine::source_kind(name, bytes) {
Some(pdfcraft_engine::SourceKind::Office) => false,
Some(_) => true,
None => name.to_ascii_lowercase().ends_with(".pdf"),
}
}
/// A file's bookmark in the combined PDF: its name without ".pdf", or without the extension of
@@ -279,7 +279,7 @@ impl PdfCraftApp {
notes: Vec::new(),
};
let source = bytes.clone();
let (bytes, assessed) = match self.session.as_pdf(&name, &bytes) {
let (bytes, assessed) = match self.session.as_pdf_inline(&name, &bytes) {
Ok(pdf) => {
let assessed = assess(&pdf, None);
(pdf, assessed)
@@ -43,7 +43,7 @@ impl PdfCraftApp {
continue;
}
};
let (kind, pdf) = match self.session.convert_to_pdf(&name, &Arc::new(bytes)) {
let (kind, pdf) = match self.session.convert_to_pdf_inline(&name, &Arc::new(bytes)) {
Ok(converted) => converted,
Err(error) => {
refused.push(format!("{name} ({error})"));
@@ -111,7 +111,7 @@ impl PdfCraftApp {
let sources = std::iter::from_fn(|| {
loop {
match files.next()? {
Ok((name, bytes)) => match session.convert_to_pdf(&name, &Arc::new(bytes)) {
Ok((name, bytes)) => match session.convert_to_pdf_inline(&name, &Arc::new(bytes)) {
Ok((_, pdf)) => {
converted += 1;
return Some(Ok((stem(&name).to_string(), pdf, None)));
+12 -7
View File
@@ -43,9 +43,6 @@ pub(crate) fn image_import_body(ui: &mut egui::Ui, app: &mut PdfCraftApp) -> (bo
(go, cancel)
}
/// File types Open accepts besides PDF (converted on open).
pub use pdfcraft_engine::CONVERTIBLE;
/// What Create ▸ Clipboard found on the clipboard.
#[derive(Clone, Debug, PartialEq)]
pub enum Clip {
@@ -105,15 +102,23 @@ fn stem(name: &str) -> &str {
}
impl PdfCraftApp {
/// Convert a non-PDF file (image, text) into a new tab. Returns `None` when `bytes` is not
/// something Create understands (the caller then tries to open it as a PDF).
/// Convert a non-PDF file (image, text, Office document) into a new tab. Returns `None` when
/// `bytes` is not something Create understands (the caller then tries to open it as a PDF).
/// An Office document blocks while LibreOffice runs: File ▸ Open converts it on the open
/// worker instead ([`Self::open_converted_pdf`]), leaving this for startup and inline opens.
pub(crate) fn open_converted(&mut self, name: &str, bytes: &[u8]) -> Option<Result<(), String>> {
use pdfcraft_engine::SourceKind;
if !matches!(pdfcraft_engine::source_kind(name, bytes), Some(SourceKind::Image | SourceKind::Text)) {
if !matches!(pdfcraft_engine::source_kind(name, bytes), Some(SourceKind::Image | SourceKind::Text | SourceKind::Office)) {
return None;
}
let created = self.session.convert_to_pdf(name, &Arc::new(bytes.to_vec())).map(|(_, pdf)| pdf);
Some(self.open_created_bytes(&format!("{}.pdf", stem(name)), created.map_err(|e| e.to_string())))
Some(self.open_converted_pdf(name, created.map_err(|e| e.to_string())))
}
/// Open `created`, the PDF converted from the file `name`, as a new, unsaved tab named after
/// it (`Report.docx` → `Report.pdf`).
pub(crate) fn open_converted_pdf(&mut self, name: &str, created: Result<Arc<Vec<u8>>, String>) -> Result<(), String> {
self.open_created_bytes(&format!("{}.pdf", stem(name)), created)
}
fn open_created_bytes(&mut self, name: &str, created: Result<Arc<Vec<u8>>, String>) -> Result<(), String> {
+1 -1
View File
@@ -666,7 +666,7 @@ impl PdfCraftApp {
continue;
}
};
match self.session.insert_source(id, &name, &Arc::new(bytes)) {
match self.session.insert_source_inline(id, &name, &Arc::new(bytes)) {
Ok((pages, bytes)) => {
if self.apply_edit(Edit::InsertPagesFrom {
name,
+17
View File
@@ -200,6 +200,23 @@ impl PdfCraftApp {
true
}
/// Run document `id`'s catalog JavaScript for `event` (Will Save before a save, Will Print
/// before printing) and show what it said. What it changed is part of what is saved or
/// printed. A failing script is reported and the save or print still goes ahead.
pub(crate) fn run_document_actions(&mut self, id: DocId, event: pdfcraft_engine::js::DocumentScriptEvent) {
let before = self.session.get(id).map(|d| d.edit_generation());
let out = self.session.run_document_actions(id, event);
if self.session.get(id).map(|d| d.edit_generation()) != before
&& let Some(i) = self.views.iter().position(|v| v.id == id)
&& let Some(info) = self.session.get(id).map(|d| d.info.clone())
{
self.views[i].document_changed(&info);
}
if !out.is_empty() {
self.handle_js(id, out);
}
}
/// Run a push button's JavaScript (its Mouse Up action).
pub fn run_button_script(&mut self, id: DocId, field: &str, script: &str) {
self.run_button_script_target(id, field, None, script);
+10
View File
@@ -633,6 +633,16 @@ impl PdfCraftApp {
return false;
}
let Some((_, id)) = self.active_ids() else { return false };
// A form's Will Print script runs first: what it changes is printed.
if self.session.get(id).is_some_and(|d| d.allows_printing()) {
let before = self.session.get(id).map(|d| d.edit_generation());
self.run_document_actions(id, pdfcraft_engine::js::DocumentScriptEvent::WillPrint);
// What it showed may lie outside the printed areas Label printing found: find them again.
if self.session.get(id).map(|d| d.edit_generation()) != before && self.print_draft.handling == Handling::Label {
self.print_draft.crop_pages = None;
self.read_label_crops(id);
}
}
let Some(doc) = self.session.get(id) else { return false };
let labels: Vec<String> = doc.info.pages.iter().map(|p| p.label.clone()).collect();
let settings = match self.print_draft.settings(doc.info.pages.len(), &labels) {
+4 -4
View File
@@ -1839,10 +1839,10 @@ fn images_and_text_files_join_the_combine_list_as_pdfs() {
#[test]
fn files_that_cannot_be_read_are_listed_and_left_out_once_the_user_agrees() {
let mut h = combine_of(&[("one.pdf", 2)]);
let bad = vec![("broken.jpg".to_string(), b"\xff\xd8\xff\xe0 not a JPEG".to_vec()), ("report.docx".to_string(), b"PK\x03\x04".to_vec())];
let bad = vec![("broken.jpg".to_string(), b"\xff\xd8\xff\xe0 not a JPEG".to_vec()), ("archive.zip".to_string(), b"PK\x03\x04".to_vec())];
h.state_mut().use_files(pdfcraft_ui_egui::FilePurpose::Combine, bad);
h.run_steps(3);
assert_eq!(combine_names(&h), ["one.pdf", "broken.jpg", "report.docx"]);
assert_eq!(combine_names(&h), ["one.pdf", "broken.jpg", "archive.zip"]);
for f in &h.state().combine_draft[1..] {
let why = f.problem.as_deref().expect("why it can't be combined");
assert!(why.starts_with("Can't be read: ") && !why.contains(&f.name), "{why}");
@@ -1859,7 +1859,7 @@ fn files_that_cannot_be_read_are_listed_and_left_out_once_the_user_agrees() {
h.run_steps(3);
h.get_by_label("Leave out files that can't be read?");
h.get_by_label("• broken.jpg");
h.get_by_label("• report.docx");
h.get_by_label("• archive.zip");
h.get_by_label("Cancel").click();
h.run_steps(3);
assert!(h.query_by_label("Leave out files that can't be read?").is_none());
@@ -2136,7 +2136,7 @@ fn plus_between_pages_inserts_picked_files_there_in_order() {
assert_eq!(texts_of(h.state(), 0), ["a note", "Page 1", "a note", "Page 2", "Page 3", "a note"]);
// A file that can't be converted changes nothing.
let before = texts_of(h.state(), 0);
h.state_mut().use_files(pdfcraft_ui_egui::FilePurpose::InsertPages, vec![("report.docx".into(), b"PK\x03\x04".to_vec())]);
h.state_mut().use_files(pdfcraft_ui_egui::FilePurpose::InsertPages, vec![("archive.zip".into(), b"PK\x03\x04".to_vec())]);
h.run_steps(2);
assert_eq!(texts_of(h.state(), 0), before);
}
+104
View File
@@ -0,0 +1,104 @@
//! A form field widget's pointer scripts in the app (#269, ported from #344): the pointer
//! moving onto and off a widget runs its Mouse Enter and Mouse Exit JavaScript, and a click on a
//! check box runs its Mouse Up JavaScript after the click stored the new value (#247).
use egui_kittest::Harness;
use pdfcraft_ui_egui::PdfCraftApp;
/// `log` records what ran; `hot` (a text field) logs the pointer entering and leaving it;
/// `strike` (a check box) shows or hides `note` from its Mouse Up script by its own new value.
fn form() -> Vec<u8> {
let objs = [
"<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [4 0 R 5 0 R 6 0 R 8 0 R] /DA (/Helv 0 Tf 0 g) /DR << /Font << /Helv 7 0 R >> >> >> >>",
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 300 400] >>",
"<< /Type /Page /Parent 2 0 R /Annots [4 0 R 5 0 R 6 0 R 8 0 R] >>",
"<< /Type /Annot /Subtype /Widget /FT /Tx /T (log) /V () /Rect [20 350 280 370] /P 3 0 R /F 4 >>",
"<< /Type /Annot /Subtype /Widget /FT /Tx /T (hot) /V () /Rect [20 250 280 290] /P 3 0 R /F 4 /AA << /E << /S /JavaScript /JS (getField\\('log'\\).value += 'in;';) >> /X << /S /JavaScript /JS (getField\\('log'\\).value += 'out;';) >> >> >>",
"<< /Type /Annot /Subtype /Widget /FT /Btn /T (strike) /V /Off /AS /Off /Rect [20 300 50 330] /P 3 0 R /F 4 /MK << /CA (4) >> /AP << /N << /Yes 9 0 R /Off 9 0 R >> >> /A << /S /JavaScript /JS (getField\\('note'\\).display = event.target.value == 'Off' ? display.hidden : display.visible; getField\\('log'\\).value += 'up:' + event.target.value + ';';) >> >>",
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>",
"<< /Type /Annot /Subtype /Widget /FT /Tx /T (note) /V (struck) /Rect [60 300 280 330] /P 3 0 R /F 6 >>",
"<< /Type /XObject /Subtype /Form /BBox [0 0 30 30] /Length 0 >>\nstream\n\nendstream",
];
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 o in offsets {
out.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());
}
out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes());
out
}
fn harness() -> Harness<'static, PdfCraftApp> {
let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(|_cc| {
let mut app = PdfCraftApp::new();
app.set_option("language", "en").unwrap();
app.set_option("left", "closed").unwrap();
app.open_bytes("triggers.pdf", None, form()).unwrap();
app
});
crate::support::settle(&mut h);
h
}
fn field<'a>(app: &'a PdfCraftApp, name: &str) -> &'a pdfcraft_engine::FormField {
let id = app.active_ids().unwrap().1;
app.session.get(id).unwrap().form.iter().find(|f| f.name == name).unwrap()
}
fn centre(h: &Harness<'static, PdfCraftApp>, name: &str) -> egui::Pos2 {
let app = h.state();
let (index, id) = app.active_ids().unwrap();
let doc = app.session.get(id).unwrap();
pdfcraft_ui_egui::forms_ui::field_screen_rect(&app.views[index], &doc.info, field(app, name), 0).unwrap().center()
}
fn log(h: &Harness<'static, PdfCraftApp>) -> String {
field(h.state(), "log").value.join(",")
}
#[test]
fn the_pointer_entering_and_leaving_a_widget_runs_its_scripts() {
let mut h = harness();
let hot = centre(&h, "hot");
let away = hot + egui::vec2(0.0, 200.0);
h.hover_at(away);
h.run_steps(2);
h.hover_at(hot);
crate::support::wait_until(&mut h, "Mouse Enter ran", |app| field(app, "log").value.join(",") == "in;");
// Moving within the widget runs nothing more.
h.hover_at(hot + egui::vec2(10.0, 0.0));
h.run_steps(3);
assert_eq!(log(&h), "in;");
h.hover_at(away);
crate::support::wait_until(&mut h, "Mouse Exit ran", |app| field(app, "log").value.join(",") == "in;out;");
}
/// The check box's Mouse Up reads the value its click stored: checking it shows the note,
/// unchecking hides it again (#247).
#[test]
fn a_check_box_mouse_up_script_sees_the_value_its_click_stored() {
let mut h = harness();
let strike = centre(&h, "strike");
let click = |h: &mut Harness<'static, PdfCraftApp>| {
h.hover_at(strike);
h.run_steps(1);
h.drag_at(strike);
h.run_steps(1);
h.drop_at(strike);
h.run_steps(1);
};
click(&mut h);
crate::support::wait_until(&mut h, "checked and its Mouse Up ran", |app| field(app, "log").value.join(",") == "up:Yes;");
assert_eq!(field(h.state(), "strike").value, ["Yes"]);
assert!(!field(h.state(), "note").widgets[0].hidden, "shown by the script");
h.run_steps(6);
click(&mut h);
crate::support::wait_until(&mut h, "unchecked and its Mouse Up ran", |app| field(app, "log").value.join(",") == "up:Yes;up:Off;");
assert!(field(h.state(), "note").widgets[0].hidden, "hidden again");
}
+1
View File
@@ -43,6 +43,7 @@ mod download_mime;
mod editing;
mod editor_taps;
mod export;
mod field_triggers;
mod fill_sign;
mod find_replace;
mod folders;
+13 -3
View File
@@ -148,13 +148,21 @@ pub enum DataOp {
impl DataNode {
/// The node at `path`, made (with empty siblings before it) where missing; `None` past
/// the index cap.
fn ensure(&mut self, path: &[(String, usize)]) -> Option<&mut DataNode> {
fn ensure(&mut self, path: &[(String, usize)], budget: &mut usize) -> Option<&mut DataNode> {
let mut node = self;
for (name, idx) in path {
if *idx >= MAX_INDEX {
return None;
}
let have = node.children.iter().filter(|c| &c.name == name).count();
// Every skipped sibling owns a copy of the name: bounded as `Build::at` bounds a write.
// The budget is the whole path's, not each level's: a deep path that is affordable at
// every level taken alone would otherwise allocate its way past the bound.
let need = (*idx + 1).saturating_sub(have).saturating_mul(name.len());
if need > *budget {
return None;
}
*budget -= need;
for _ in have..=*idx {
node.children.push(DataNode { name: name.clone(), ..Default::default() });
}
@@ -166,9 +174,11 @@ impl DataNode {
/// Apply `op` to this tree (the root is the `xfa:data` element), as [`write_data_ops`]
/// will to the packet, so scripts that run before it is written see the change.
pub fn apply(&mut self, op: &DataOp) {
// One budget for the op's whole path, as `Build::at` bounds a write.
let mut budget = build::MAX_NEW_NAME_BYTES;
match op {
DataOp::Value { path, text } => {
if let Some(n) = self.ensure(path) {
if let Some(n) = self.ensure(path, &mut budget) {
// A multi-select list's picks, one `value` each (see `value_at`), told apart
// as the packet writer does: `value` leaves only, or a group holding none.
let picks = if n.children.is_empty() { n.group } else { n.children.iter().all(|c| c.name == "value" && c.children.is_empty()) };
@@ -189,7 +199,7 @@ impl DataNode {
if let Some(&last) = count.checked_sub(1).as_ref() {
let mut path = parent.clone();
path.push((name.clone(), last.min(MAX_INDEX.saturating_sub(1))));
let _ = self.ensure(&path);
let _ = self.ensure(&path, &mut budget);
}
}
DataOp::Remove(path) => {
+1 -1
View File
@@ -38,7 +38,7 @@ pub(super) const MAX_INDEX: usize = 10_000;
/// Most bytes of names the nodes one write creates hold together: every sibling an index
/// skips over gets its own copy of the name.
const MAX_NEW_NAME_BYTES: usize = 4 << 20;
pub(super) const MAX_NEW_NAME_BYTES: usize = 4 << 20;
/// What one write may still create: nodes and bytes of their names.
pub(super) struct NewNodes {
+23 -1
View File
@@ -82,6 +82,11 @@ pub fn remove_data_instance(doc: &mut Document, path: &DataPath) -> Result<Datas
/// pass, which asks for the instances again).
const MAX_ENSURED: usize = 200_000;
/// Most bytes of path those queued instances hold together: each one owns a copy of its parent
/// path (segment buffers included, twice while duplicates are dropped) and its name, so a long
/// ancestor would otherwise be multiplied by the instance count. Ordinary paths are tens of bytes.
const MAX_ENSURED_BYTES: usize = 128 << 20;
// Instance nodes write_data_ops has queued on this thread, for tests that bound its work.
#[cfg(test)]
thread_local! {
@@ -99,7 +104,7 @@ pub fn write_data_ops(doc: &mut Document, ops: &[DataOp], reuse: Option<ObjRef>)
let mut run: Vec<Want> = Vec::new();
// Instances queued in this run, by parent and name: asking for more only queues the rest.
let mut queued: HashMap<(&DataPath, &str), usize> = HashMap::new();
let (mut ensured, mut capped) = (0usize, false);
let (mut ensured, mut ensured_bytes, mut capped, mut capped_bytes) = (0usize, 0usize, false, false);
let flush = |run: &mut Vec<Want>, steps: &mut Vec<Vec<Want>>, removes: &mut Vec<Option<DataPath>>| {
if !run.is_empty() {
let mut seen = std::collections::HashSet::new();
@@ -117,12 +122,24 @@ pub fn write_data_ops(doc: &mut Document, ops: &[DataOp], reuse: Option<ObjRef>)
}
DataOp::Instances { parent, name, count } => {
let done = queued.entry((parent, name.as_str())).or_insert(0);
// The path (its segments' buffers and their text) is held by the queued step, which a
// clone then `push` can leave with up to twice the room, and cloned again into
// `flush`'s dedup set, beside the label and the step itself.
let segment = std::mem::size_of::<(String, usize)>();
let path_bytes =
parent.iter().fold(segment.saturating_add(name.len()), |n, (p, _)| n.saturating_add(segment).saturating_add(p.len()));
let per_instance = path_bytes.saturating_mul(3).saturating_add(name.len()).saturating_add(16 + std::mem::size_of::<Want>());
while *done < (*count).min(MAX_INDEX) {
if ensured >= MAX_ENSURED {
capped = true;
break;
}
if ensured_bytes.saturating_add(per_instance) > MAX_ENSURED_BYTES {
capped_bytes = true;
break;
}
ensured += 1;
ensured_bytes += per_instance;
#[cfg(test)]
ENSURED.with(|n| n.set(n.get() + 1));
let k = *done;
@@ -154,6 +171,11 @@ pub fn write_data_ops(doc: &mut Document, ops: &[DataOp], reuse: Option<ObjRef>)
if capped {
written.warnings.push(format!("XFA data instances not written past {MAX_ENSURED}: the rows were added and removed too often"));
}
if capped_bytes {
written
.warnings
.push(format!("XFA data instances not written past {MAX_ENSURED_BYTES} bytes of names: the rows were added and removed too often"));
}
Ok(written)
}
+25
View File
@@ -7114,6 +7114,31 @@ fn a_container_is_as_wide_as_a_turned_draw_stands() {
}
}
/// Every sibling a SOM index skips owns a copy of the element name: the in-memory builder refuses
/// a path whose copies would pass the name-byte bound the writer holds itself to, and creates
/// nothing for it.
#[test]
fn the_in_memory_data_builder_bounds_copied_name_bytes() {
let mut root = DataNode::default();
// 1 KiB x 9,999 skipped siblings is about 10 MB, over the 4 MiB bound.
let long = "n".repeat(1 << 10);
root.apply(&DataOp::Value { path: vec![(long.clone(), 9_999)], text: "x".into() });
assert!(root.children.is_empty());
// Within the bound, the same shape still builds (and keeps indexes).
root.apply(&DataOp::Value { path: vec![(long, 100)], text: "x".into() });
assert_eq!(root.children.len(), 101);
}
/// Each queued instance owns a copy of its parent path: a long ancestor stops the queue at the
/// byte allowance, reported as capped, instead of being multiplied by the instance count.
#[test]
fn queued_instances_are_bounded_by_the_path_bytes_they_copy() {
let mut doc = Document::new_empty();
let parent: DataPath = vec![("a".repeat(16 << 20), 0), ("b".repeat(16 << 20), 0)];
let written = crate::data::write_data_ops(&mut doc, &[DataOp::Instances { parent, name: "row".into(), count: 100 }], None).unwrap();
assert!(written.warnings.iter().any(|w| w.contains("not written past")), "{:?}", written.warnings);
}
/// A page break splits an empty multi-line field that grows with its text (XFA 3.3 pp. 291–292:
/// text splits between lines, and a field's `keep intact` is `none`): it starts where it is, its
/// widget runs to the bottom of the content area, and the rest of its box, closed on every side,

Some files were not shown because too many files have changed in this diff Show More