Merge main into fix/pdfcraft-win10-opengl-native

Move the frame decision into compatibility_frame::frame_for and the saved-choice override into
effective_title_bar_pref, and test the registry build parsing, the Windows 10 OpenGL rule and the
override, so they are covered without Windows or an OpenGL driver.
This commit is contained in:
FredApps
2026-12-02 16:10:33 +01:00
144 changed files with 7604 additions and 615 deletions
+9 -4
View File
@@ -40,12 +40,17 @@ jobs:
# egui/winit/rfd, and the independent oracles (crates/oracle).
packages: >-
libxkbcommon-dev libwayland-dev libx11-dev libxrandr-dev libxi-dev libgl1-mesa-dev
libgtk-3-dev qpdf poppler-utils
libgtk-3-dev qpdf poppler-utils xvfb libxkbcommon-x11-0
# cargo-deny for the deny step of `cargo xtask ci`, which requires it under CI.
tools: cargo-nextest@0.9.150,cargo-deny@0.20.2
# A missing oracle fails the job instead of printing a skip notice that reads as a pass.
linux-env: PDFCRAFT_ORACLES_REQUIRED=1
windows-env: PDFCRAFT_REQUIRE_WINRES=1
# One KEY=VALUE per line. No debug info on Windows: a cold-cache gate built it for every
# dependency and spent the 90-minute cap compiling before the tests started.
windows-env: |
PDFCRAFT_REQUIRE_WINRES=1
CARGO_PROFILE_DEV_DEBUG=0
CARGO_PROFILE_TEST_DEBUG=0
# Windows completed its 54m33s gate, then cache save hit the default 60m job cap
# (run 44364342368). Leave bounded room for setup and post-job cleanup.
# This changes no test watchdog or selection; craft-common-actions#60.
@@ -54,7 +59,7 @@ jobs:
command: |
pwsh -NoProfile -File packaging/windows/test-font-notices.ps1
cargo xtask ci
# Windows checks what differs by platform: the build (with resources) and the tests.
# Windows checks what differs by platform: the build (with resources) and the tests. Clippy
# runs on Linux in `cargo xtask ci`; lints don't differ by platform.
windows-command: |
cargo clippy --workspace --all-targets --locked -- -D warnings
cargo test --workspace --locked
+2
View File
@@ -19,6 +19,8 @@ jobs:
# Tracked at @main so org-wide CI improvements propagate without PR churn.
uses: storytold/craft-common-actions/.github/workflows/sonarcloud.yml@main
with:
coverage-application-binaries: pdfcraft
linux-test-packages: xvfb libxkbcommon-x11-0
# Same craft-fonts commit as ci.yml and release.yml.
fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
secrets: inherit
Generated
+1
View File
@@ -6707,6 +6707,7 @@ dependencies = [
"pdfcraft-ocr",
"pdfcraft-platform",
"pdfcraft-render",
"pdfcraft-testkit",
"pdfcraft-xfa",
"plist",
"proptest",
+1
View File
@@ -76,6 +76,7 @@
PdfCraft is part of [ArtCraft](https://getartcraft.com). Come say hello, get help and follow development:
- **Discord: [discord.gg/artcraft](https://discord.gg/artcraft)**. This is the fastest way to get help and share feedback. The app has a Discord button in its title bar.
- [Collect a Windows startup log](docs/windows-renderer-startup.md#if-the-window-freezes-at-startup) if the app opens a frozen window.
- **Web page:** [getartcraft.com/apps/pdfcraft](https://getartcraft.com/apps/pdfcraft)
- **Source:** [github.com/storytold/pdfcraft](https://github.com/storytold/pdfcraft)
+1
View File
@@ -360,6 +360,7 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md
- **2026-10-26 (M3, view.text-select):** Text selection runs across pages: dragging onto another page (also a quick flick off the page, and the edge and wheel scrolling of #721/#1670) or ⇧-clicking there selects the rest of the first page, the pages between and the last page up to the pointer. Copy has each page's part on a line of its own, reading pages not yet read off the UI thread; highlight, underline, strikethrough and Redact put one mark on each page in one undo step (a tool that finishes first marks once the pages are read; Redact refuses a selection over a page whose text could not be read); Add comment and Replace text stay one-page. A drag from one page's text that is already over the next when it starts no longer begins a Redact or area-highlight box there. Estimates unchanged.
- **2026-10-25 (M5, comment replies):** One reply can be deleted from the Comments panel without its thread. On the selected card each reply has its own "…" menu (Edit, Copy text, Delete); Delete takes that reply with its pop-up and the replies to it, as `comment_delete` already did headlessly, and the comment and its other replies stay. The card stays selected, and the panel's editor stays open, on what they were on though the delete moved it in `/Annots`. Undo and Redo close the editor, since either can move what it was open on. A locked reply can't be deleted. Estimates unchanged.
- **2026-10-25 (M7, #2750):** Single-style Keep source fonts edits retain source glyphs and batch only missing glyphs in fallback fonts. Per-rewrite character eligibility and widths are cached; source and fallback edge spaces stay extractable. Estimates unchanged.
- **2026-10-25 (M4, #2725):** Dismissing the ordinary form-field reminder persists across launches, while security, repair and XFA notices keep their independent controls and defaults. Estimates unchanged.
- **2026-10-25 (M10, #4399):** The printer picker has a wider searchable list, wrapped device names, stable selection while filtering, and Search and Save as PDF kept visible. Synthetic fleet UI regressions cover long lists and a smaller window. Estimates unchanged.
- **2026-10-25 (web, same-document host mode):** A page that loads the PdfCraft web module into its own document (no iframe) can opt into the host bridge with `data-host="page"` on the app's canvas — the exact value `page`; any other value keeps the normal app with downloads, unless a same-origin framed `?host=parent` selects the parent bridge (unframed or cross-origin, `?host=parent` also keeps the normal app). It is the `?host=parent` bridge with the transport swapped: the same five messages travel as non-bubbling `CustomEvent`s on the canvas (`detail` holds the parent messages' fields without `type`; the host answers with a `pdfcraft:open` event), so saves reach the host instead of downloading and dirty and start-up-failure reporting are unchanged. Unit tests cover the opt-in rule; no parity or estimate changes.
- **2026-10-25 (M10):** Vector printing keeps field and comment artwork whose rectangle coordinates are indirect, requiring exactly four finite resolved values.
+20 -16
View File
@@ -1,6 +1,6 @@
use super::options::{
COMBINE_OPTIONS, EXTRACT_OPTIONS, INFO_OPTIONS, RENDER_OPTIONS, SPLIT_OPTIONS, TEXT_OPTIONS, can_be_path_value, flag, needs_value, positional,
validate_options,
COMBINE_OPTIONS, EXTRACT_OPTIONS, INFO_OPTIONS, RENDER_OPTIONS, SPLIT_OPTIONS, TEXT_OPTIONS, can_be_path_value, needs_value, positional,
validate_options, value_of_flag,
};
use super::{Arc, CliError, ImageFormat, PageRenderer, Path, PathBuf, RenderConfig, RenderRequest, RequestKind, Write, inspect, stdout_line};
@@ -26,7 +26,7 @@ pub(crate) fn info(args: &[String]) -> Result<(), CliError> {
validate_options("info", args, INFO_OPTIONS)?;
let path = *positional(args, INFO_OPTIONS).first().ok_or("info: missing file")?;
let bytes = read(path)?;
let password = flag(args, "--password");
let password = value_of_flag("info", args, INFO_OPTIONS, "--password")?;
// The renderer takes only the user password of R2–R4 files; `Session::open` takes either.
let render_password = pdfcraft_engine::render_password_for(bytes.clone(), password);
let mut info = inspect(bytes.clone(), render_password.as_deref()).map_err(|e| e.to_string())?;
@@ -104,7 +104,7 @@ pub(crate) fn text(args: &[String]) -> Result<(), CliError> {
options.next();
}
}
let password = flag(args, "--password");
let password = value_of_flag("text", args, TEXT_OPTIONS, "--password")?;
let mut bytes = read(path)?;
// The renderer takes only the user password of R2–R4 files; `Session::open` takes either.
// Worked out from the file as read: `bytes` may become the session's display copy below.
@@ -306,7 +306,7 @@ fn file_stem(path: &str) -> String {
pub(crate) fn combine(args: &[String]) -> Result<(), CliError> {
validate_options("combine", args, COMBINE_OPTIONS)?;
let out = flag(args, "--out").ok_or("combine: missing --out")?;
let out = value_of_flag("combine", args, COMBINE_OPTIONS, "--out")?.ok_or("combine: missing --out")?;
let inputs = positional(args, COMBINE_OPTIONS);
if inputs.len() < 2 {
return Err("combine: give at least two input files".into());
@@ -319,10 +319,10 @@ pub(crate) fn combine(args: &[String]) -> Result<(), CliError> {
pub(crate) fn extract(args: &[String]) -> Result<(), CliError> {
validate_options("extract", args, EXTRACT_OPTIONS)?;
let path = *positional(args, EXTRACT_OPTIONS).first().ok_or("extract: missing file")?;
let out = flag(args, "--out").ok_or("extract: missing --out")?;
let pages = page_list(flag(args, "--pages").ok_or("extract: missing --pages")?)?;
let out = value_of_flag("extract", args, EXTRACT_OPTIONS, "--out")?.ok_or("extract: missing --out")?;
let pages = page_list(value_of_flag("extract", args, EXTRACT_OPTIONS, "--pages")?.ok_or("extract: missing --pages")?)?;
let mut session = pdfcraft_engine::Session::new();
let id = session.open(path, None, read(path)?, flag(args, "--password")).map_err(|e| e.to_string())?;
let id = session.open(path, None, read(path)?, value_of_flag("extract", args, EXTRACT_OPTIONS, "--password")?).map_err(|e| e.to_string())?;
let bytes = session.extract(id, &pages).map_err(|e| e.to_string())?;
write_pdf(Path::new(out), &bytes)
}
@@ -331,7 +331,7 @@ pub(crate) fn split(args: &[String]) -> Result<(), CliError> {
validate_options("split", args, SPLIT_OPTIONS)?;
use pdfcraft_engine::SplitBy;
let path = *positional(args, SPLIT_OPTIONS).first().ok_or("split: missing file")?;
let by = match (flag(args, "--every"), flag(args, "--before")) {
let by = match (value_of_flag("split", args, SPLIT_OPTIONS, "--every")?, value_of_flag("split", args, SPLIT_OPTIONS, "--before")?) {
(Some(n), None) => {
// A count the splitter cannot hold is refused here, before the file is opened,
// rather than silently clamped to 1 further down.
@@ -345,9 +345,9 @@ pub(crate) fn split(args: &[String]) -> Result<(), CliError> {
(None, Some(list)) => SplitBy::Before(page_list(list)?),
_ => return Err("split: give either --every N or --before PAGES".into()),
};
let dir = PathBuf::from(flag(args, "--out-dir").unwrap_or("."));
let dir = PathBuf::from(value_of_flag("split", args, SPLIT_OPTIONS, "--out-dir")?.unwrap_or("."));
let mut session = pdfcraft_engine::Session::new();
let id = session.open(path, None, read(path)?, flag(args, "--password")).map_err(|e| e.to_string())?;
let id = session.open(path, None, read(path)?, value_of_flag("split", args, SPLIT_OPTIONS, "--password")?).map_err(|e| e.to_string())?;
let stem = file_stem(path);
let parts = session.split(id, &by).map_err(|e| e.to_string())?;
// An output folder that does not exist yet is created (#249); one that can't be is reported
@@ -376,11 +376,15 @@ pub(crate) fn parse_dpi(value: &str) -> Result<f32, String> {
pub(crate) fn render(args: &[String]) -> Result<(), CliError> {
validate_options("render", args, RENDER_OPTIONS)?;
let path = *positional(args, RENDER_OPTIONS).first().ok_or("render: missing file")?;
let page: usize =
flag(args, "--page").unwrap_or("1").parse().ok().filter(|page| *page > 0).ok_or("bad --page: expected a positive page number")?;
let page: usize = value_of_flag("render", args, RENDER_OPTIONS, "--page")?
.unwrap_or("1")
.parse()
.ok()
.filter(|page| *page > 0)
.ok_or("bad --page: expected a positive page number")?;
let page_index = page - 1;
let dpi = parse_dpi(flag(args, "--dpi").unwrap_or("96"))?;
let out = flag(args, "--out").ok_or("render: missing --out (.png, .jpg, .tif or .pam)")?;
let dpi = parse_dpi(value_of_flag("render", args, RENDER_OPTIONS, "--dpi")?.unwrap_or("96"))?;
let out = value_of_flag("render", args, RENDER_OPTIONS, "--out")?.ok_or("render: missing --out (.png, .jpg, .tif or .pam)")?;
// The file is what its name says (#248): a `.png` used to get a netpbm PAM stream.
let format = match Path::new(out).extension().and_then(std::ffi::OsStr::to_str).map(str::to_ascii_lowercase).as_deref() {
Some("png") => Some(ImageFormat::Png),
@@ -393,7 +397,7 @@ pub(crate) fn render(args: &[String]) -> Result<(), CliError> {
// of named-layer signatures (here with no trusted certificates); the CLI must agree with it
// (and with independent viewers), while keeping the file it reads intact.
let bytes = read(path)?;
let password = flag(args, "--password");
let password = value_of_flag("render", args, RENDER_OPTIONS, "--password")?;
// The renderer takes only the user password of R2–R4 files; `Session::open` and the display
// copy take either.
let render_password = pdfcraft_engine::render_password_for(bytes.clone(), password);
+51
View File
@@ -4,6 +4,29 @@ pub(crate) fn flag<'a>(args: &'a [String], name: &str) -> Option<&'a str> {
args.iter().position(|a| a == name).and_then(|i| args.get(i + 1)).map(String::as_str)
}
/// The operand of the last `name` in `args`, read the way `validate_options` and `positional` walk
/// them: a token that is another option's operand is never taken for an option. [`flag`] matches
/// any token, so in `--password --out input.pdf --out out.pdf` (a password of `--out`) it answered
/// `input.pdf` for `--out` and the command wrote over its own source file (#7516). `Err` when
/// `name` is the last token and so has no operand.
pub(crate) fn value_of_flag<'a>(command: &str, args: &'a [String], specs: &[OptionSpec], name: &str) -> Result<Option<&'a str>, CliError> {
let mut i = 0;
let mut result = None;
while let Some(a) = args.get(i) {
if a == name {
let value = args.get(i + 1).map(String::as_str).ok_or_else(|| needs_value(command, name, None))?;
result = Some(value);
i += 2;
continue;
}
match specs.iter().find(|spec| spec.name == a.as_str()) {
Some(spec) if spec.takes_value => i += 2,
_ => i += 1,
}
}
Ok(result)
}
#[derive(Clone, Copy)]
pub(crate) struct OptionSpec {
pub(crate) name: &'static str,
@@ -151,3 +174,31 @@ pub(crate) fn positional<'a>(args: &'a [String], specs: &[OptionSpec]) -> Vec<&'
}
out
}
#[cfg(test)]
mod tests {
use super::*;
fn args(tokens: &[&str]) -> Vec<String> {
tokens.iter().map(|token| (*token).to_string()).collect()
}
/// #7516: a password that reads like an option is still a password, not that option.
#[test]
fn value_of_flag_skips_password_operand() {
let line = args(&["--password", "--out", "input.pdf", "--out", "out.pdf"]);
assert_eq!(value_of_flag("extract", &line, EXTRACT_OPTIONS, "--out").unwrap(), Some("out.pdf"));
assert_eq!(value_of_flag("extract", &line, EXTRACT_OPTIONS, "--password").unwrap(), Some("--out"));
// The old lookup, for contrast: it is why the call sites moved.
assert_eq!(flag(&line, "--out"), Some("input.pdf"));
}
#[test]
fn value_of_flag_reports_absent_and_dangling_options() {
let line = args(&["in.pdf", "--password", "--pages"]);
assert_eq!(value_of_flag("extract", &line, EXTRACT_OPTIONS, "--pages").unwrap(), None);
let dangling = args(&["in.pdf", "--pages"]);
let error = value_of_flag("extract", &dangling, EXTRACT_OPTIONS, "--pages").unwrap_err();
assert_eq!(error.to_string(), "extract: --pages needs a value");
}
}
+1
View File
@@ -12,6 +12,7 @@ mod help;
mod info_repairs;
mod info_standards;
mod mcp_compact;
mod option_operands;
mod options;
mod owner_password;
mod render;
@@ -0,0 +1,167 @@
//! A value-taking option's operand is never read as another option (#7516). A password can be any
//! string, `--out` included, and the commands used to look options up by scanning every token:
//! in `extract --password --out in.pdf --pages 1 --out out.pdf` the password's operand was taken
//! for the real `--out`, its neighbour `in.pdf` for the output, and the source file was replaced.
use std::path::PathBuf;
use std::process::Command;
const BIN: &str = env!("CARGO_BIN_EXE_pdfcraft-cli");
/// A PDF with `n` empty 200×300 pt pages.
fn fixture(n: usize) -> Vec<u8> {
let mut objs: Vec<Vec<u8>> = vec![b"<< /Type /Catalog /Pages 2 0 R >>".to_vec()];
let kids: Vec<String> = (0..n).map(|i| format!("{} 0 R", 3 + i)).collect();
objs.push(format!("<< /Type /Pages /Kids [{}] /Count {n} /MediaBox [0 0 200 300] >>", kids.join(" ")).into_bytes());
for _ in 0..n {
objs.push(b"<< /Type /Page /Parent 2 0 R >>".to_vec());
}
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", i + 1).as_bytes());
out.extend_from_slice(o);
out.extend_from_slice(b"\nendobj\n");
}
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 fresh directory holding `in.pdf` (3 pages), and that file's path as the command line takes it.
fn workdir(test: &str) -> (PathBuf, String) {
let d = std::env::temp_dir().join(format!("pdfcraft-cli-operands-{test}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
std::fs::create_dir_all(&d).unwrap();
let input = d.join("in.pdf");
std::fs::write(&input, fixture(3)).unwrap();
let name = input.to_str().unwrap().to_string();
(d, name)
}
/// The page count and first page size `info` reports for a PDF the CLI wrote.
fn pages_of(path: &std::path::Path) -> (u64, serde_json::Value) {
let run = Command::new(BIN).args(["info", path.to_str().unwrap()]).output().unwrap();
assert!(run.status.success(), "info {}: {}", path.display(), String::from_utf8_lossy(&run.stderr));
let info: serde_json::Value = serde_json::from_slice(&run.stdout).unwrap();
(info["pages"].as_u64().unwrap(), info["first_page_pt"].clone())
}
/// The names in `dir`, sorted, so a test sees a stray staging file or a missing part.
fn listing(dir: &std::path::Path) -> Vec<String> {
let mut names: Vec<String> = std::fs::read_dir(dir).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect();
names.sort();
names
}
// Ordinary command lines through the shared atomic writer (`craft::atomic`): the lookup still
// finds each command's real options, writes what they ask for, and leaves the source alone.
#[test]
fn ordinary_extract_writes_the_chosen_pages_and_keeps_its_source() {
let (dir, input) = workdir("plain-extract");
let out = dir.join("out.pdf");
let run = Command::new(BIN).args(["extract", &input, "--pages", "2-3", "--out", out.to_str().unwrap()]).output().unwrap();
assert!(run.status.success(), "{}", String::from_utf8_lossy(&run.stderr));
assert_eq!(pages_of(&out), (2, serde_json::json!([200.0, 300.0])));
assert_eq!(std::fs::read(&input).unwrap(), fixture(3), "the source file changed");
assert_eq!(listing(&dir), ["in.pdf", "out.pdf"], "only the output was written");
}
#[test]
fn ordinary_split_writes_one_part_per_page_and_keeps_its_source() {
let (dir, input) = workdir("plain-split");
let parts = dir.join("parts");
let run = Command::new(BIN).args(["split", &input, "--every", "1", "--out-dir", parts.to_str().unwrap()]).output().unwrap();
assert!(run.status.success(), "{}", String::from_utf8_lossy(&run.stderr));
assert_eq!(listing(&parts), ["in-p1.pdf", "in-p2.pdf", "in-p3.pdf"]);
for n in 1..=3 {
assert_eq!(pages_of(&parts.join(format!("in-p{n}.pdf"))).0, 1, "part {n}");
}
assert_eq!(std::fs::read(&input).unwrap(), fixture(3), "the source file changed");
assert_eq!(listing(&dir), ["in.pdf", "parts"]);
}
#[test]
fn ordinary_render_writes_the_chosen_page_at_the_chosen_dpi_and_keeps_its_source() {
let (dir, input) = workdir("plain-render");
let png = dir.join("page.png");
let run = Command::new(BIN).args(["render", &input, "--page", "2", "--dpi", "36", "--out", png.to_str().unwrap()]).output().unwrap();
assert!(run.status.success(), "{}", String::from_utf8_lossy(&run.stderr));
let image = craft_image_codecs::decode(&std::fs::read(&png).unwrap()).unwrap();
// 200×300 pt at 36 dpi.
assert_eq!((image.width(), image.height()), (100, 150));
assert_eq!(std::fs::read(&input).unwrap(), fixture(3), "the source file changed");
assert_eq!(listing(&dir), ["in.pdf", "page.png"], "only the image was written");
}
#[test]
fn extract_does_not_write_over_its_source_when_the_password_is_out() {
let (dir, input) = workdir("extract");
let out = dir.join("out.pdf");
let run = Command::new(BIN).args(["extract", "--password", "--out", &input, "--pages", "1", "--out", out.to_str().unwrap()]).output().unwrap();
assert!(run.status.success(), "{}", String::from_utf8_lossy(&run.stderr));
assert_eq!(std::fs::read(&input).unwrap(), fixture(3), "the source file was replaced");
assert!(out.is_file(), "the page went to the real --out");
}
#[test]
fn extract_reads_the_real_pages_when_the_password_is_pages() {
let (dir, input) = workdir("extract-pages");
let out = dir.join("out.pdf");
// `--password --pages` then the file: the old lookup read the file's name as the page list.
let run = Command::new(BIN).args(["extract", "--password", "--pages", &input, "--pages", "2", "--out", out.to_str().unwrap()]).output().unwrap();
assert!(run.status.success(), "{}", String::from_utf8_lossy(&run.stderr));
assert_eq!(pages_of(&out).0, 1, "the real --pages chose one page");
assert_eq!(std::fs::read(&input).unwrap(), fixture(3), "the source file changed");
}
#[test]
fn split_writes_to_the_real_out_dir_when_the_password_is_out_dir() {
let (dir, input) = workdir("split");
let parts = dir.join("parts");
let run =
Command::new(BIN).args(["split", "--password", "--out-dir", &input, "--every", "1", "--out-dir", parts.to_str().unwrap()]).output().unwrap();
assert!(run.status.success(), "{}", String::from_utf8_lossy(&run.stderr));
for n in 1..=3 {
assert!(parts.join(format!("in-p{n}.pdf")).is_file(), "part {n} missing");
}
assert_eq!(std::fs::read(&input).unwrap(), fixture(3));
}
#[test]
fn render_writes_to_the_real_out_when_the_password_is_out() {
let (dir, input) = workdir("render");
let png = dir.join("page.png");
let run = Command::new(BIN).args(["render", "--password", "--out", &input, "--dpi", "36", "--out", png.to_str().unwrap()]).output().unwrap();
assert!(run.status.success(), "{}", String::from_utf8_lossy(&run.stderr));
assert!(std::fs::read(&png).unwrap().starts_with(b"\x89PNG"), "the image went to the real --out");
assert_eq!(std::fs::read(&input).unwrap(), fixture(3), "the source file was replaced");
}
/// An option left without its operand at the end of the line is named, instead of being read as
/// absent: `render in.pdf --out page.png --page` used to render page 1 and exit 0.
#[test]
fn an_option_with_no_operand_is_named() {
let (dir, input) = workdir("dangling");
let png = dir.join("page.png");
for args in [
vec!["render", &input, "--out", png.to_str().unwrap(), "--page"],
vec!["render", &input, "--out", png.to_str().unwrap(), "--dpi"],
vec!["split", &input, "--every", "1", "--password"],
] {
let option = *args.last().unwrap();
let run = Command::new(BIN).current_dir(&dir).args(&args).output().unwrap();
let stderr = String::from_utf8_lossy(&run.stderr);
assert!(!run.status.success(), "{args:?} unexpectedly succeeded");
assert!(stderr.contains(&format!("{option} needs a value")), "{args:?}: {stderr}");
}
assert!(!png.exists(), "nothing was rendered");
assert_eq!(listing(&dir), ["in.pdf"], "a refused command left a file behind");
assert_eq!(std::fs::read(&input).unwrap(), fixture(3), "the source file changed");
}
+61 -3
View File
@@ -2,7 +2,7 @@
//! its real input coordinates (#8845, emilk/egui#2770). A native non-client frame keeps
//! rendering and hit testing in the same coordinate system.
#[cfg(target_os = "windows")]
pub(crate) fn windows_build() -> Option<u32> {
fn registry_build() -> Option<String> {
use winsafe::{HKEY, RegistryValue, co::RRF};
let RegistryValue::Sz(build) =
@@ -10,18 +10,46 @@ pub(crate) fn windows_build() -> Option<u32> {
else {
return None;
};
build.parse().ok()
Some(build)
}
#[cfg(not(target_os = "windows"))]
pub(crate) fn windows_build() -> Option<u32> {
fn registry_build() -> Option<String> {
None
}
/// The Windows build number, or `None` on other systems or when the registry doesn't give one.
pub(crate) fn windows_build() -> Option<u32> {
registry_build().as_deref().and_then(parse_build)
}
/// The build number as the registry stores it: a decimal string, possibly padded with whitespace or NULs.
fn parse_build(value: &str) -> Option<u32> {
value.trim_matches(|c: char| c.is_whitespace() || c == '\0').parse().ok()
}
pub(crate) fn requires_native_frame(build: Option<u32>, renderer: eframe::Renderer) -> bool {
renderer == eframe::Renderer::Glow && build.is_some_and(|build| (10240..22000).contains(&build))
}
/// Who draws the root window's frame for `renderer`, and whether the driver forces the native one.
/// A forced native frame replaces the saved title-bar choice for this run only; the choice itself
/// is not changed.
pub(crate) fn frame_for(
build: Option<u32>,
renderer: eframe::Renderer,
saved: craft::window::policy::TitleBarPref,
backend: craft::window::policy::Backend,
) -> (craft::window::policy::Decision, bool) {
use craft::window::{
Prefix,
policy::{TitleBarPref, decide_for},
};
let requires_native_frame = requires_native_frame(build, renderer);
let pref = if requires_native_frame { TitleBarPref::System } else { saved };
(decide_for(Prefix::new("PDFCRAFT"), backend, pref), requires_native_frame)
}
#[cfg(test)]
mod tests {
use super::*;
@@ -37,4 +65,34 @@ mod tests {
assert!(!requires_native_frame(build, Glow));
}
}
#[test]
fn a_build_number_is_read_from_the_registry_text() {
assert_eq!(parse_build("19045"), Some(19045));
assert_eq!(parse_build(" 22631\0"), Some(22631));
for bad in ["", "abc", "-1", "19045.1"] {
assert_eq!(parse_build(bad), None);
}
}
#[test]
fn a_driver_that_needs_the_native_frame_overrides_the_saved_choice_for_this_run() {
use craft::window::{
Prefix,
policy::{Backend, TitleBarPref, decide_for},
};
let backend = Backend::from_env();
let decide = |pref| decide_for(Prefix::new("PDFCRAFT"), backend, pref);
for saved in [TitleBarPref::Integrated, TitleBarPref::System] {
let (frame, forced) = frame_for(Some(19045), Glow, saved, backend);
assert!(forced);
assert_eq!(frame, decide(TitleBarPref::System));
let (frame, forced) = frame_for(Some(19045), Wgpu, saved, backend);
assert!(!forced);
assert_eq!(frame, decide(saved));
let (frame, forced) = frame_for(Some(26100), Glow, saved, backend);
assert!(!forced);
assert_eq!(frame, decide(saved));
}
}
}
+17 -4
View File
@@ -67,6 +67,19 @@ mod tests {
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--"])
}
/// What [`super::prepare`] returns for `argv`, without installing the profile process-wide.
/// `cargo test` runs every unit test of the binary in one process, and an installed nightly
/// profile would make the stable icon, app id and title tests that run after it see nightly.
#[cfg(any(windows, all(unix, not(target_os = "macos"))))]
fn prepare_without_installing(argv: Vec<OsString>) -> Result<craft_nightly::Launch, ProfileError> {
let spec = profile_root::spec();
let mut launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv, &StartupOptions::new())?;
if let Profile::NightlyV1(root) = &launch.profile {
launch.profile = Profile::NightlyV1(craft_nightly::validate_and_prepare_root(root, &spec)?);
}
Ok(launch)
}
#[test]
fn stable_arguments_and_directory_policy_are_unchanged() {
let spec = profile_root::spec();
@@ -158,14 +171,14 @@ mod tests {
let listener = UnixListener::bind(&sock_path).unwrap();
// Live listener socket already present inside <profile>/single-instance/.
let live_launch = super::prepare(BuildFlavor::NightlyV1, launch_arguments(&profile, &args(&["doc.pdf"]))).unwrap();
let live_launch = prepare_without_installing(launch_arguments(&profile, &args(&["doc.pdf"]))).unwrap();
assert_eq!(live_launch.profile, Profile::NightlyV1(expected_root.clone()));
assert_eq!(live_launch.passthrough_args, args(&["doc.pdf"]));
// Leftover/stale socket remaining after the previous instance exits.
drop(listener);
assert!(std::fs::symlink_metadata(&sock_path).is_ok(), "stale socket remains on disk");
let stale_launch = super::prepare(BuildFlavor::NightlyV1, launch_arguments(&profile, &args(&["after-exit.pdf"]))).unwrap();
let stale_launch = prepare_without_installing(launch_arguments(&profile, &args(&["after-exit.pdf"]))).unwrap();
assert_eq!(stale_launch.profile, Profile::NightlyV1(expected_root));
assert_eq!(stale_launch.passthrough_args, args(&["after-exit.pdf"]));
}
@@ -183,14 +196,14 @@ mod tests {
let listener = uds_windows::UnixListener::bind(&sock_path).unwrap();
// Live AF_UNIX listener socket already present inside <profile>\single-instance\.
let live_launch = super::prepare(BuildFlavor::NightlyV1, launch_arguments(&profile, &args(&["doc.pdf"]))).unwrap();
let live_launch = prepare_without_installing(launch_arguments(&profile, &args(&["doc.pdf"]))).unwrap();
assert_eq!(live_launch.profile, Profile::NightlyV1(expected_root.clone()));
assert_eq!(live_launch.passthrough_args, args(&["doc.pdf"]));
// Leftover/stale socket remaining after the previous instance exits.
drop(listener);
assert!(std::fs::symlink_metadata(&sock_path).is_ok(), "stale socket remains on disk");
let stale_launch = super::prepare(BuildFlavor::NightlyV1, launch_arguments(&profile, &args(&["after-exit.pdf"]))).unwrap();
let stale_launch = prepare_without_installing(launch_arguments(&profile, &args(&["after-exit.pdf"]))).unwrap();
assert_eq!(stale_launch.profile, Profile::NightlyV1(expected_root));
assert_eq!(stale_launch.passthrough_args, args(&["after-exit.pdf"]));
}
+80 -19
View File
@@ -336,6 +336,8 @@ fn main() -> eframe::Result {
// window.
// Absolute for this instance too: links relative to a document resolve against its folder,
// never the working directory.
let startup_time = std::time::Instant::now();
startup_stage(startup_time, "claiming application instance");
let files = single_instance::absolute(&files);
let instance = match single_instance::claim(&files, may_hand_off, combine, launch_profile::current().root()) {
single_instance::Claim::HandedOff => return Ok(()),
@@ -363,6 +365,7 @@ fn main() -> eframe::Result {
// unless `PDFCRAFT_TITLEBAR` overrides them. The store is read here and opened again by the
// app (each window attempt opens its own: the OpenGL retry runs the creator again).
// The interface language is read the same way, for the fonts the runtime installs with.
startup_stage(startup_time, "reading startup preferences");
let (title_bar, saved_lang) = {
let settings = pdfcraft_ui_egui::settings::open();
let saved = settings.get();
@@ -375,16 +378,10 @@ fn main() -> eframe::Result {
let choice = renderer_choice(std::env::var("PDFCRAFT_RENDERER").ok().as_deref());
let first = if choice == RendererChoice::Gl { eframe::Renderer::Glow } else { eframe::Renderer::Wgpu };
let windows_build = compatibility_frame::windows_build();
let frame_for = |renderer| {
let requires_native_frame = compatibility_frame::requires_native_frame(windows_build, renderer);
let pref = if requires_native_frame { craft::window::policy::TitleBarPref::System } else { title_bar };
(
craft::window::policy::decide_for(craft::window::Prefix::new("PDFCRAFT"), craft::window::policy::Backend::from_env(), pref),
requires_native_frame,
)
};
let frame_for = |renderer| compatibility_frame::frame_for(windows_build, renderer, title_bar, craft::window::policy::Backend::from_env());
let (frame, requires_native_frame) = frame_for(first);
let mut launch = Launch {
startup_time,
files,
options,
control,
@@ -402,6 +399,7 @@ fn main() -> eframe::Result {
let apple_events = apple_events::AppleEvents::install();
// Set once the app is created, which is after the renderer has started.
let started = Rc::new(Cell::new(false));
startup_stage(startup_time, if choice == RendererChoice::Gl { "initializing OpenGL" } else { "initializing wgpu" });
let result = eframe::run_native(
app_title(),
native_options(launch.integrated(), first),
@@ -421,6 +419,7 @@ fn main() -> eframe::Result {
// usually still works there, so that's better than quitting.
log::error!("the GPU renderer (wgpu) didn't start: {e}. Starting with OpenGL instead; set PDFCRAFT_RENDERER=gl to skip wgpu.");
(launch.frame, launch.requires_native_frame) = frame_for(eframe::Renderer::Glow);
startup_stage(startup_time, "retrying with OpenGL");
eframe::run_native(
app_title(),
native_options(launch.integrated(), eframe::Renderer::Glow),
@@ -439,6 +438,10 @@ fn main() -> eframe::Result {
final_result
}
fn startup_stage(start: std::time::Instant, stage: &str) {
log::info!(target: "pdfcraft::startup", "+{} ms: {stage}", start.elapsed().as_millis());
}
/// Which renderer to start with, from `PDFCRAFT_RENDERER`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum RendererChoice {
@@ -551,6 +554,7 @@ fn native_options(integrated: bool, renderer: eframe::Renderer) -> eframe::Nativ
/// What the command line asked for, kept so a second run (with OpenGL) can start the same way.
#[derive(Clone)]
struct Launch {
startup_time: std::time::Instant,
files: Vec<String>,
options: Vec<(String, String)>,
/// The control server's port and token, when `--control` asked for one.
@@ -651,9 +655,11 @@ fn app_creator<'a>(
instance: Option<&'a single_instance::Server>,
#[cfg(target_os = "macos")] apple_events: &'a apple_events::AppleEvents,
) -> eframe::AppCreator<'a> {
let Launch { files, options, control, create_images, combine, frame, requires_native_frame, lang, two_paged, nightly_watch } = launch;
let Launch { startup_time, files, options, control, create_images, combine, frame, requires_native_frame, lang, two_paged, nightly_watch } =
launch;
Box::new(move |cc| {
started.set(true);
startup_stage(startup_time, "renderer ready, installing fonts and runtime");
install_runtime(cc, frame, lang)?;
let ctx = cc.egui_ctx.clone();
let wake = craft::host::Wake::new(move || ctx.request_repaint());
@@ -667,6 +673,7 @@ fn app_creator<'a>(
// drains them into the intake.
#[cfg(target_os = "macos")]
let apple_events_poll = apple_events.connect(intake.sender(), &cc.egui_ctx);
startup_stage(startup_time, "initializing application and recovery");
let mut app = PdfCraftApp::with_intake(&cc.egui_ctx, intake);
app.requires_native_frame = requires_native_frame;
#[cfg(target_os = "linux")]
@@ -686,6 +693,7 @@ fn app_creator<'a>(
app.units = pdfcraft_ui_egui::units::Unit::system();
// The system's reopen-windows choice (macOS) starts the preference; a saved choice replaces it.
app.reopen_last_session = reopen::system_default();
startup_stage(startup_time, "applying preferences");
let settings = pdfcraft_ui_egui::settings::open();
app.apply_settings(settings.get());
app.attach_settings(settings);
@@ -732,6 +740,7 @@ fn app_creator<'a>(
if let Some(warning) = &pdfcraft_ui_egui::settings::resolution().warning {
app.notify(warning.clone());
}
startup_stage(startup_time, "restoring session and opening requested documents");
let defer_layout = two_paged && !files.is_empty() && !create_images;
if create_images {
if let Err(e) = app.begin_image_import_paths(&cc.egui_ctx, &files) {
@@ -752,6 +761,8 @@ fn app_creator<'a>(
log::warn!("--{k} {v}: {e}");
}
}
startup_stage(startup_time, "entering UI event loop");
app.startup_time = Some(startup_time);
Ok(Box::new(app))
})
}
@@ -812,21 +823,36 @@ fn configure_gpu(native: &mut eframe::NativeOptions) {
descriptor.required_limits = surface_texture_limits(descriptor.required_limits, &adapter.limits());
descriptor
});
if std::env::var_os("WGPU_POWER_PREF").is_none() {
let power_chosen = std::env::var_os("WGPU_POWER_PREF").is_some();
let explicit_renderer = renderer_choice(std::env::var("PDFCRAFT_RENDERER").ok().as_deref()) == RendererChoice::Wgpu;
if !power_chosen {
setup.power_preference = eframe::wgpu::PowerPreference::LowPower;
let displays = display_gpus();
let compositor = compositor_gpu::compositor_gpu();
if !displays.is_empty() || compositor.is_some() {
// Always on Windows, so that an OpenGL-only GPU is declined (`wgpu_draws_with`) even when
// no display names its GPU, as over Remote Desktop; `pick_adapter` then ranks by kind,
// most frugal first, as wgpu's own low-power choice does.
if !displays.is_empty() || compositor.is_some() || cfg!(target_os = "windows") {
let backend_chosen = explicit_renderer || std::env::var_os("WGPU_BACKEND").is_some();
setup.native_adapter_selector = Some(std::sync::Arc::new(move |adapters, surface| {
let usable: Vec<&eframe::wgpu::Adapter> = adapters.iter().filter(|a| surface.is_none_or(|s| a.is_surface_supported(s))).collect();
let infos: Vec<(u32, u32, eframe::wgpu::DeviceType)> = usable
let infos: Vec<(u32, u32, eframe::wgpu::DeviceType, eframe::wgpu::Backend)> = usable
.iter()
.map(|a| {
let info = a.get_info();
(info.vendor, info.device, info.device_type)
(info.vendor, info.device, info.device_type, info.backend)
})
.collect();
let picked = pick_adapter(&infos, &displays, compositor).and_then(|i| usable.get(i)).map(|a| (*a).clone());
if let Some(a) = &picked
&& !wgpu_draws_with(a.get_info().backend, cfg!(target_os = "windows"), backend_chosen)
{
log::warn!(
"wgpu found no Direct3D 12 adapter for {}, only its OpenGL backend: drawing with eframe's OpenGL renderer instead",
a.get_info().name
);
return Err("wgpu would draw through its OpenGL backend".to_string());
}
match &picked {
// Which GPU draws is the first question when a window stays black (#8, #378, #445).
Some(a) => {
@@ -839,14 +865,36 @@ fn configure_gpu(native: &mut eframe::NativeOptions) {
}));
}
}
if cfg!(target_os = "windows") && std::env::var_os("WGPU_BACKEND").is_none() {
setup.instance_descriptor.backends = eframe::wgpu::Backends::DX12 | eframe::wgpu::Backends::GL;
if let Some(backends) =
automatic_windows_backends(cfg!(target_os = "windows"), std::env::var_os("WGPU_BACKEND").is_some(), power_chosen, explicit_renderer)
{
setup.instance_descriptor.backends = backends;
}
if cfg!(target_os = "windows") {
setup.instance_descriptor.backend_options.dx12.presentation_system = dx12_presentation(eframe::wgpu::Dx12SwapchainKind::from_env());
}
}
/// A power preference delegates adapter ranking to wgpu, bypassing the selector that declines
/// its OpenGL surface on Windows. Auto mode must then try DX12 alone before native OpenGL.
fn automatic_windows_backends(windows: bool, explicit_backend: bool, power_chosen: bool, explicit_renderer: bool) -> Option<eframe::wgpu::Backends> {
use eframe::wgpu::Backends;
if !windows || explicit_backend {
return None;
}
Some(if power_chosen && !explicit_renderer { Backends::DX12 } else { Backends::DX12 | Backends::GL })
}
/// Whether wgpu should draw with the adapter it picked on `backend`. On Windows (`windows`) wgpu
/// reaches its OpenGL backend only for a GPU with no Direct3D 12 driver, such as Intel's Ivy
/// Bridge, and there that backend fails in `Surface::configure` a few seconds after the window
/// opens: too late for the start-up retry with OpenGL, so the app closed (#519, #4134, #5553).
/// eframe's own OpenGL renderer works on the same GPUs, so wgpu declines and that retry takes over.
/// An explicit `PDFCRAFT_RENDERER=wgpu` or `WGPU_BACKEND` selection (`backend_chosen`) is kept.
fn wgpu_draws_with(backend: eframe::wgpu::Backend, windows: bool, backend_chosen: bool) -> bool {
!(windows && backend == eframe::wgpu::Backend::Gl && !backend_chosen)
}
/// How Direct3D 12 presents on Windows: through a DirectComposition visual (issue #2738), unless
/// `WGPU_DX12_PRESENTATION_SYSTEM` asked for something else (`asked`).
fn dx12_presentation(asked: Option<eframe::wgpu::Dx12SwapchainKind>) -> eframe::wgpu::Dx12SwapchainKind {
@@ -974,14 +1022,25 @@ fn linux_display_gpus(drm: &std::path::Path) -> Vec<DisplayGpu> {
/// primary display (a hybrid laptop's panel, #8; the primary display on Windows, #378), or else,
/// with no primary display known (a Linux desktop with a monitor on each GPU, #445), the discrete
/// one. Otherwise the most frugal kind: integrated, discrete, other, virtual, software.
fn pick_adapter(adapters: &[(u32, u32, eframe::wgpu::DeviceType)], displays: &[DisplayGpu], compositor: Option<(u32, u32)>) -> Option<usize> {
use eframe::wgpu::DeviceType;
///
/// On Windows wgpu offers a Direct3D 12 GPU through OpenGL too, and declines OpenGL there
/// (`wgpu_draws_with`), so an OpenGL adapter comes after another adapter of its vendor. wgpu's
/// OpenGL adapter has no device id and guesses its kind (every Intel GPU is integrated), so it is
/// matched by vendor alone, before its kind is compared: an Intel discrete GPU's Direct3D 12
/// adapter beats its own OpenGL one. A GPU with only OpenGL (Intel's Ivy Bridge) still beats the
/// software adapter, Microsoft's.
fn pick_adapter(
adapters: &[(u32, u32, eframe::wgpu::DeviceType, eframe::wgpu::Backend)],
displays: &[DisplayGpu],
compositor: Option<(u32, u32)>,
) -> Option<usize> {
use eframe::wgpu::{Backend, DeviceType};
let display = |pci: (u32, u32)| displays.iter().find(|g| g.pci == pci);
let multi_gpu_desktop = displays.len() > 1 && !displays.iter().any(|g| g.primary);
adapters
.iter()
.enumerate()
.min_by_key(|(_, (vendor, device, kind))| {
.min_by_key(|(_, (vendor, device, kind, backend))| {
let shown = display((*vendor, *device));
let drives_display = shown.is_some();
let drives_primary = shown.is_some_and(|g| g.primary);
@@ -995,7 +1054,9 @@ fn pick_adapter(adapters: &[(u32, u32, eframe::wgpu::DeviceType)], displays: &[D
DeviceType::VirtualGpu => 4,
DeviceType::Cpu => 5,
};
(compositor != Some((*vendor, *device)), !drives_display, !drives_primary, rank)
let gl = *backend == Backend::Gl;
let vendor_has_more = gl && adapters.iter().any(|(v, _, _, b)| v == vendor && *b != Backend::Gl);
(compositor != Some((*vendor, *device)), !drives_display, !drives_primary, vendor_has_more, rank, gl)
})
.map(|(i, _)| i)
}
+78 -5
View File
@@ -19,6 +19,71 @@ pub(crate) fn install_runtime(ctx: &egui::Context) {
craft::ui::shell::embed::install(ctx, spec, &pdfcraft_ui_egui::fonts::ui_fonts(Lang::EN)).expect("the runtime installs on a fresh context");
}
#[test]
fn a_power_preference_without_an_explicit_renderer_retries_native_opengl_on_windows() {
use eframe::wgpu::Backends;
for power in [false, true] {
for renderer in [false, true] {
assert_eq!(super::automatic_windows_backends(false, false, power, renderer), None);
assert_eq!(super::automatic_windows_backends(true, true, power, renderer), None);
let expected = if power && !renderer { Backends::DX12 } else { Backends::DX12 | Backends::GL };
assert_eq!(super::automatic_windows_backends(true, false, power, renderer), Some(expected));
}
}
}
#[test]
fn on_windows_wgpu_leaves_an_opengl_only_gpu_to_eframes_opengl_renderer() {
use eframe::wgpu::Backend;
// Issues #4134 and #5553: an Intel HD 4000 has no Direct3D 12 driver, so wgpu picks its
// OpenGL backend, which fails a few seconds after the window opens.
assert!(!super::wgpu_draws_with(Backend::Gl, true, false), "declined, so the start-up retry uses glow");
// Everything else draws with wgpu as before.
assert!(super::wgpu_draws_with(Backend::Dx12, true, false));
assert!(super::wgpu_draws_with(Backend::Gl, true, true), "WGPU_BACKEND asked for it");
for backend in [Backend::Gl, Backend::Vulkan, Backend::Metal] {
assert!(super::wgpu_draws_with(backend, false, false), "{backend:?} off Windows");
}
}
#[test]
fn pick_adapter_takes_a_gpus_opengl_adapter_last_and_an_opengl_only_gpu_over_software() {
use eframe::wgpu::{Backend, DeviceType};
// wgpu's OpenGL adapter has its vendor's id, no device id, and a kind guessed from its
// strings: every Intel GPU is integrated, and most others are "other" (wgpu-hal's gles
// `make_info`).
let gl = |vendor: u32, kind| (vendor, 0, kind, Backend::Gl);
// A GPU offered through OpenGL and through Direct3D 12 or Vulkan, in either order, with or
// without a known display: never OpenGL, which `wgpu_draws_with` declines on Windows.
const ARC: (u32, u32) = (0x8086, 0x56a0);
for other in [Backend::Dx12, Backend::Vulkan] {
for (gpu, kind, guessed) in [
(INTEL_IGPU, DeviceType::IntegratedGpu, DeviceType::IntegratedGpu),
// An Intel discrete GPU, which wgpu's OpenGL backend calls integrated (CodeRabbit).
(ARC, DeviceType::DiscreteGpu, DeviceType::IntegratedGpu),
(NVIDIA, DeviceType::DiscreteGpu, DeviceType::Other),
] {
let gl_first = [gl(gpu.0, guessed), (gpu.0, gpu.1, kind, other)];
for displays in [&[panel(gpu)][..], &[]] {
assert_eq!(super::pick_adapter(&gl_first, displays, None), Some(1), "{gpu:x?} {other:?} {displays:?}");
assert_eq!(super::pick_adapter(&[gl_first[1], gl_first[0]], displays, None), Some(0), "{gpu:x?} {other:?} {displays:?}");
}
}
}
// Issue #4134: an Intel HD 4000 has only OpenGL, and the Microsoft Basic Render Driver (in
// software) has Direct3D 12. The GPU is still picked, by kind, with or without a known
// display, as over Remote Desktop; declining it then starts glow on that GPU.
const HD_4000: (u32, u32) = (0x8086, 0x0166);
let ivy_bridge = [(0x1414, 0x008c, DeviceType::Cpu, Backend::Dx12), gl(HD_4000.0, DeviceType::IntegratedGpu)];
assert_eq!(super::pick_adapter(&ivy_bridge, &[panel(HD_4000)], None), Some(1));
assert_eq!(super::pick_adapter(&ivy_bridge, &[], None), Some(1));
assert!(!super::wgpu_draws_with(Backend::Gl, true, false));
// Only OpenGL, or only software: that adapter.
assert_eq!(super::pick_adapter(&ivy_bridge[1..], &[], None), Some(0));
assert_eq!(super::pick_adapter(&ivy_bridge[..1], &[], None), Some(0));
assert_eq!(super::pick_adapter(&[], &[], None), None);
}
#[test]
fn opengl_is_the_fallback_unless_a_renderer_was_chosen() {
use super::{RendererChoice, native_options, renderer_choice, retry_with_gl};
@@ -322,9 +387,13 @@ const NVIDIA: (u32, u32) = (0x10de, 0x2684);
const NVIDIA_3090: (u32, u32) = (0x10de, 0x2204);
const AMD_IGPU: (u32, u32) = (0x1002, 0x164e);
fn adapters() -> Vec<(u32, u32, eframe::wgpu::DeviceType)> {
use eframe::wgpu::DeviceType;
vec![(NVIDIA.0, NVIDIA.1, DeviceType::DiscreteGpu), (AMD_IGPU.0, AMD_IGPU.1, DeviceType::IntegratedGpu), (0, 0, DeviceType::Cpu)]
fn adapters() -> Vec<(u32, u32, eframe::wgpu::DeviceType, eframe::wgpu::Backend)> {
use eframe::wgpu::{Backend, DeviceType};
vec![
(NVIDIA.0, NVIDIA.1, DeviceType::DiscreteGpu, Backend::Vulkan),
(AMD_IGPU.0, AMD_IGPU.1, DeviceType::IntegratedGpu, Backend::Vulkan),
(0, 0, DeviceType::Cpu, Backend::Vulkan),
]
}
const INTEL_IGPU: (u32, u32) = (0x8086, 0xa780);
@@ -391,8 +460,12 @@ fn pick_adapter_keeps_the_integrated_gpu_on_hybrid_laptops() {
#[test]
fn pick_adapter_prefers_the_discrete_gpu_on_desktops_with_a_monitor_on_each() {
// Issue #445: one monitor on the Intel iGPU, one on the NVIDIA card, no built-in panel.
use eframe::wgpu::DeviceType;
let desktop = [(INTEL_IGPU.0, INTEL_IGPU.1, DeviceType::IntegratedGpu), (NVIDIA.0, NVIDIA.1, DeviceType::DiscreteGpu), (0, 0, DeviceType::Cpu)];
use eframe::wgpu::{Backend, DeviceType};
let desktop = [
(INTEL_IGPU.0, INTEL_IGPU.1, DeviceType::IntegratedGpu, Backend::Vulkan),
(NVIDIA.0, NVIDIA.1, DeviceType::DiscreteGpu, Backend::Vulkan),
(0, 0, DeviceType::Cpu, Backend::Vulkan),
];
assert_eq!(super::pick_adapter(&desktop, &[monitor(INTEL_IGPU), monitor(NVIDIA)], None), Some(1));
assert_eq!(super::pick_adapter(&desktop, &[monitor(NVIDIA), monitor(INTEL_IGPU)], None), Some(1));
// A GPU driving no display still loses to one that does.
+106
View File
@@ -0,0 +1,106 @@
#![cfg(target_os = "linux")]
//! The logger must reach disk while the real desktop app is running, before it can be closed.
use std::io::{BufRead, BufReader, Read, Write};
use std::net::{TcpListener, TcpStream};
use std::process::{Child, Command, Stdio};
use std::time::{Duration, Instant};
struct Running(Child);
impl Drop for Running {
fn drop(&mut self) {
if self.0.try_wait().ok().flatten().is_none() {
let _ = self.0.kill();
}
let _ = self.0.wait();
}
}
#[test]
fn startup_breadcrumbs_reach_the_portable_log_before_quit() {
use std::os::unix::fs::PermissionsExt;
let xvfb = Command::new("Xvfb").args(["-displayfd", "1", "-screen", "0", "1024x768x24", "-nolisten", "tcp"]).stdout(Stdio::piped()).spawn();
let mut display = match xvfb {
Ok(p) => Running(p),
Err(e) if e.kind() == std::io::ErrorKind::NotFound && std::env::var_os("CI").is_none() => {
eprintln!("Xvfb is needed to exercise desktop startup");
return;
}
Err(e) => panic!("start Xvfb: {e}"),
};
let mut number = String::new();
BufReader::new(display.0.stdout.take().unwrap()).read_line(&mut number).unwrap();
assert!(!number.trim().is_empty(), "Xvfb did not open a display");
let root = std::env::temp_dir().join(format!("pdfcraft-startup-log-{}", std::process::id()));
std::fs::create_dir(&root).unwrap();
std::fs::set_permissions(&root, std::fs::Permissions::from_mode(0o700)).unwrap();
let exe = root.join("pdfcraft");
let bin = env!("CARGO_BIN_EXE_pdfcraft");
if std::fs::hard_link(bin, &exe).is_err() {
std::fs::copy(bin, &exe).unwrap();
}
std::fs::write(root.join("portable.txt"), []).unwrap();
let port = TcpListener::bind(("127.0.0.1", 0)).unwrap().local_addr().unwrap().port();
let mut secret = [0_u8; 32];
std::fs::File::open("/dev/urandom").unwrap().read_exact(&mut secret).unwrap();
let token: String = secret.iter().map(|byte| format!("{byte:02x}")).collect();
let mut app = Running(
Command::new(exe)
.args(["--new-window", "--control", &port.to_string()])
.env("PDFCRAFT_CONTROL_TOKEN", &token)
.env("HOME", &root)
.env("XDG_RUNTIME_DIR", &root)
.env("XDG_CONFIG_HOME", &root)
.env("XDG_DATA_HOME", &root)
.env_remove("WAYLAND_DISPLAY")
.env_remove("PDFCRAFT_CONFIG_DIR")
.env("DISPLAY", format!(":{}", number.trim()))
.env("PDFCRAFT_RENDERER", "gl")
.env("RUST_LOG", "info")
.env("LIBGL_ALWAYS_SOFTWARE", "1")
.spawn()
.unwrap(),
);
let deadline = Instant::now() + Duration::from_secs(60);
let log = root.join("PdfCraftData/logs/pdfcraft.log");
let mut socket = loop {
if log.exists()
&& std::fs::read_to_string(&log).unwrap_or_default().contains("first UI pass finished")
&& let Ok(socket) = TcpStream::connect(("127.0.0.1", port))
{
break socket;
}
assert!(app.0.try_wait().unwrap().is_none(), "PdfCraft exited during startup");
assert!(Instant::now() < deadline, "startup log: {:?}", std::fs::read_to_string(&log));
std::thread::sleep(Duration::from_millis(100));
};
let log = std::fs::read_to_string(log).unwrap();
let mut rest = log.as_str();
for stage in [
"claiming application instance",
"reading startup preferences",
"initializing OpenGL",
"renderer ready, installing fonts and runtime",
"initializing application and recovery",
"applying preferences",
"restoring session and opening requested documents",
"entering UI event loop",
"first UI pass finished",
] {
rest = rest.split_once(stage).unwrap_or_else(|| panic!("missing or misordered stage {stage}: {log}")).1;
}
socket.set_read_timeout(Some(Duration::from_secs(10))).unwrap();
let mut read = BufReader::new(socket.try_clone().unwrap());
for (method, params) in [("auth", serde_json::json!({"token":token})), ("ui.quit", serde_json::json!({}))] {
writeln!(socket, "{}", serde_json::json!({"id":1,"method":method,"params":params})).unwrap();
let mut reply = String::new();
read.read_line(&mut reply).unwrap();
assert_eq!(serde_json::from_str::<serde_json::Value>(&reply).unwrap()["ok"], true);
}
while app.0.try_wait().unwrap().is_none() {
assert!(Instant::now() < deadline, "PdfCraft did not quit");
std::thread::sleep(Duration::from_millis(100));
}
assert!(app.0.wait().unwrap().success());
std::fs::remove_dir_all(root).unwrap();
}
+189 -31
View File
@@ -7,9 +7,12 @@
//! out ("marker" style), counts as the rectangle the stroke paints (#2385). Graphics state tracked
//! here is deliberately small: the CTM stack (`q`/`Q`/`cm`), the colors (`g`/`rg`/`k` and
//! `G`/`RG`/`K`), the line width (`w`) and what ExtGState sets of them (`gs` reading `/ca`,
//! `/CA` and `/LW`). Form XObjects are followed read-only with a depth cap. Anything fancier
//! (other filled paths, slanted or bent strokes, shadings, patterns) is out of scope and
//! documented as such.
//! `/CA` and `/LW`), rectangular and glyph clipping, form bounds, and default-off
//! optional-content groups. Rotated rectangles are conservatively bounded in user space.
//! If only the source of a glyph clip is known, the audit excludes fills of that text object
//! from its own cover findings and retains potential covers on independently drawn text.
//! Form XObjects are followed read-only with a depth and decode budget. Other filled paths,
//! slanted or bent strokes, shadings and patterns remain out of scope.
//!
//! Paint order: a page's content streams are one stream in pieces (ISO 32000-2 §7.8.2), so they
//! are parsed joined and walked once with a single graphics state — state set in an earlier
@@ -18,8 +21,11 @@
//! the joined stream)`; rectangles inside a form XObject carry the `Do` operator's position.
//! Positions compare lexicographically in paint order.
use std::collections::HashSet;
use std::ops::Range;
use pdfcraft_content::{Matrix, Op, Pieces, ops};
use pdfcraft_cos::{DecodeBudget, Dict, Document, Object};
use pdfcraft_cos::{DecodeBudget, Dict, Document, ObjRef, Object};
use crate::AuditError;
@@ -40,6 +46,38 @@ pub struct FilledRect {
/// Paint position: `(content-stream index, operator index in the joined stream)`.
/// Rectangles inside a form XObject carry the `Do` operator's position.
pub pos: (usize, usize),
/// Page operators of the text object whose own glyphs this paint fills.
pub glyph_source: Option<GlyphSource>,
}
#[derive(Clone, Debug, PartialEq)]
pub struct GlyphSource {
pub operators: Range<usize>,
pub painted: bool,
}
#[derive(Clone, Copy)]
enum Clip {
Unbounded,
Rect([f64; 4]),
Empty,
}
impl Clip {
fn visible_rect(self, rect: [f64; 4]) -> Option<[f64; 4]> {
match self {
Self::Unbounded => Some(rect),
Self::Rect(clip) => {
let intersection = [rect[0].max(clip[0]), rect[1].max(clip[1]), rect[2].min(clip[2]), rect[3].min(clip[3])];
(intersection[0] < intersection[2] && intersection[1] < intersection[3]).then_some(intersection)
}
Self::Empty => None,
}
}
fn intersect_rect(&mut self, rect: [f64; 4]) {
*self = self.visible_rect(rect).map_or(Self::Empty, Self::Rect);
}
}
#[derive(Clone)]
@@ -49,6 +87,9 @@ struct Gs {
alpha: f64,
stroke: [f64; 3],
stroke_alpha: f64,
clip: Clip,
text_render_mode: u8,
glyph_source: Option<GlyphSource>,
/// Line width, in the space the path is drawn in.
width: f64,
/// Line cap (`J`, `/LC`): 0 butt, 1 round, 2 projecting square.
@@ -68,9 +109,9 @@ enum Path {
impl Path {
/// The rectangle a fill of this path paints, if the path is one.
fn rect(self) -> Option<[f64; 4]> {
fn rect(&self) -> Option<[f64; 4]> {
match self {
Path::Rect(r) => Some(r),
Path::Rect(r) => Some(*r),
Path::Lines(pts, _) => lines_rect(pts),
Path::Empty | Path::Other => None,
}
@@ -110,13 +151,11 @@ impl Path {
/// The bounding box of a closed polygon that is an axis-aligned rectangle, or `None`. A repeated
/// start point is dropped first; the remaining four corners must alternate horizontal and
/// vertical edges.
fn lines_rect(mut pts: Vec<[f64; 2]>) -> Option<[f64; 4]> {
fn lines_rect(pts: &[[f64; 2]]) -> Option<[f64; 4]> {
// CTM products leave rounding noise, so corners compare with a tolerance (in points).
const EPS: f64 = 1e-6;
let same = |a: f64, b: f64| (a - b).abs() <= EPS;
if pts.len() == 5 && same(pts[0][0], pts[4][0]) && same(pts[0][1], pts[4][1]) {
pts.pop();
}
let pts = if pts.len() == 5 && same(pts[0][0], pts[4][0]) && same(pts[0][1], pts[4][1]) { &pts[..4] } else { pts };
let [a, b, c, d] = <[[f64; 2]; 4]>::try_from(pts).ok()?;
let fits = |first_horizontal: bool| {
[(a, b), (b, c), (c, d), (d, a)]
@@ -139,7 +178,18 @@ fn lines_rect(mut pts: Vec<[f64; 2]>) -> Option<[f64; 4]> {
impl Default for Gs {
fn default() -> Self {
Gs { ctm: Matrix::IDENTITY, fill: [0.0, 0.0, 0.0], alpha: 1.0, stroke: [0.0, 0.0, 0.0], stroke_alpha: 1.0, width: 1.0, cap: 0 }
Gs {
ctm: Matrix::IDENTITY,
fill: [0.0, 0.0, 0.0],
alpha: 1.0,
stroke: [0.0, 0.0, 0.0],
stroke_alpha: 1.0,
clip: Clip::Unbounded,
text_render_mode: 0,
glyph_source: None,
width: 1.0,
cap: 0,
}
}
}
@@ -151,6 +201,8 @@ struct Walker<'a> {
/// Decoded bytes and form entries left for the page, its forms included: spending either
/// fails the audit.
budget: DecodeBudget,
off_layers: HashSet<ObjRef>,
blank_clips: &'a HashSet<usize>,
}
impl<'a> Walker<'a> {
@@ -162,6 +214,24 @@ impl<'a> Walker<'a> {
Ok(())
}
fn push_cover(&mut self, rect: Option<[f64; 4]>, gs: &Gs, stroke: bool, pos: (usize, usize)) {
let (alpha, rgb) = if stroke { (gs.stroke_alpha, gs.stroke) } else { (gs.alpha, gs.fill) };
if alpha >= 1.0
&& let Some(rect) = rect.and_then(|rect| gs.clip.visible_rect(rect))
{
self.out.push(FilledRect { rect, rgb, pos, glyph_source: gs.glyph_source.clone() });
}
}
fn paint_path(&mut self, path: &Path, operator: &[u8], gs: &Gs, pos: (usize, usize)) {
if matches!(operator, b"B" | b"B*" | b"b" | b"b*" | b"S" | b"s") {
self.push_cover(path.stroked_rect(gs), gs, true, pos);
}
if !matches!(operator, b"S" | b"s" | b"n") {
self.push_cover(path.rect(), gs, false, pos);
}
}
/// Walk one stream's operators, read one at a time (a stream of millions of short operators
/// is never held whole), with the given graphics state. `at_do` is the `Do` position to
/// stamp on rectangles found inside a form XObject, or `None` at page level (where each
@@ -176,6 +246,13 @@ impl<'a> Walker<'a> {
at_do: Option<(usize, usize)>,
) -> Result<(), AuditError> {
let mut path = Path::Empty;
let mut multiple_subpaths = false;
let mut clip_next = false;
let mut glyph_clip_pending = false;
let mut glyph_only_text = false;
let mut glyph_source_painted = false;
let mut text_start = 0;
let mut hidden_depth = 0usize;
for (i, op) in ops.enumerate() {
self.bump()?;
let op = &op;
@@ -245,6 +322,7 @@ impl<'a> Walker<'a> {
}
}
b"re" => {
multiple_subpaths |= !matches!(path, Path::Empty);
let rect = op.nums::<4>().and_then(|[x, y, w, h]| {
if [x, y, w, h].iter().all(|v| v.is_finite()) && w != 0.0 && h != 0.0 {
let r = gs.ctm.bbox([x.min(x + w), y.min(y + h), x.max(x + w), y.max(y + h)]);
@@ -256,6 +334,7 @@ impl<'a> Walker<'a> {
path = rect.map_or(Path::Other, Path::Rect);
}
b"m" => {
multiple_subpaths |= !matches!(path, Path::Empty);
path = match (path, user_point(gs, op)) {
(Path::Empty, Some(p)) => Path::Lines(vec![p], false),
_ => Path::Other,
@@ -279,38 +358,67 @@ impl<'a> Walker<'a> {
_ => Path::Other,
};
}
// `b`/`b*` close the path before filling it, which the fill does anyway.
b"f" | b"F" | b"f*" | b"B" | b"B*" | b"b" | b"b*" => {
b"W" | b"W*" => clip_next = true,
b"f" | b"F" | b"f*" | b"B" | b"B*" | b"b" | b"b*" | b"S" | b"s" | b"n" => {
let done = std::mem::replace(&mut path, Path::Empty);
if matches!(op.op.as_slice(), b"B" | b"B*" | b"b" | b"b*")
&& let Some(r) = done.stroked_rect(gs)
&& gs.stroke_alpha >= 1.0
{
self.out.push(FilledRect { rect: r, rgb: gs.stroke, pos });
if hidden_depth == 0 {
self.paint_path(&done, op.op.as_slice(), gs, pos);
}
if let Some(r) = done.rect()
&& gs.alpha >= 1.0
// A clipping operator takes effect after the path-ending paint.
if clip_next
&& !multiple_subpaths
&& let Some(rect) = done.rect()
{
self.out.push(FilledRect { rect: r, rgb: gs.fill, pos });
gs.clip.intersect_rect(rect);
}
clip_next = false;
multiple_subpaths = false;
}
b"c" | b"v" | b"y" => path = Path::Other,
b"BT" => {
glyph_clip_pending = false;
glyph_only_text = true;
glyph_source_painted = false;
text_start = i;
}
b"Tr" => {
if let Some(mode) = op.num(0).filter(|v| (0.0..=7.0).contains(v) && v.fract() == 0.0) {
gs.text_render_mode = mode as u8;
}
}
b"S" | b"s" => {
if let Some(r) = std::mem::replace(&mut path, Path::Empty).stroked_rect(gs)
&& gs.stroke_alpha >= 1.0
{
self.out.push(FilledRect { rect: r, rgb: gs.stroke, pos });
b"Tj" | b"TJ" | b"'" | b"\"" if shows_glyphs(op) => {
let clips = gs.text_render_mode >= 4;
glyph_clip_pending |= clips && (at_do.is_some() || !self.blank_clips.contains(&i));
glyph_only_text &= clips;
glyph_source_painted |= hidden_depth == 0
&& ((matches!(gs.text_render_mode, 4 | 6) && gs.alpha > 0.0)
|| (matches!(gs.text_render_mode, 5 | 6) && gs.stroke_alpha > 0.0));
}
b"ET" => {
if std::mem::take(&mut glyph_clip_pending) {
// Without glyph outlines, retain the rectangular bound as a conservative
// estimate. Paint through the clip can still cover independently drawn text.
gs.glyph_source =
(glyph_only_text && at_do.is_none()).then_some(GlyphSource { operators: text_start..i, painted: glyph_source_painted });
}
}
b"n" => path = Path::Empty,
b"c" | b"v" | b"y" | b"W" | b"W*" => path = Path::Other,
b"BDC" => {
if hidden_depth > 0 || (op.name(0) == Some(b"OC") && self.layer_is_off(resources, op.operands.get(1))) {
hidden_depth += 1;
}
}
b"BMC" if hidden_depth > 0 => hidden_depth += 1,
b"EMC" => hidden_depth = hidden_depth.saturating_sub(1),
b"Do" => {
if let Some(name) = op.name(0) {
if let Some(name) = op.name(0).filter(|_| hidden_depth == 0) {
if depth >= MAX_DEPTH {
return Err(AuditError::TooDeep);
}
self.walk_xobject(name, gs, resources, depth, pos)?;
}
path = Path::Empty;
clip_next = false;
multiple_subpaths = false;
}
_ => {}
}
@@ -318,6 +426,15 @@ impl<'a> Walker<'a> {
Ok(())
}
fn layer_is_off(&self, resources: &Dict, property: Option<&Object>) -> bool {
let Object::Name(name) = property.unwrap_or(&Object::Null) else {
return matches!(property, Some(Object::Ref(id)) if self.off_layers.contains(id));
};
let props = resources.get(b"Properties").map(|value| self.doc.resolve(value));
let layer = props.as_deref().and_then(Object::as_dict).and_then(|dict| dict.get(name));
matches!(layer, Some(Object::Ref(id)) if self.off_layers.contains(id))
}
/// Follow a form XObject read-only, composing its matrix onto the current CTM. State
/// changes inside never leak out; every rectangle found is stamped with the `Do`
/// position `pos`.
@@ -331,6 +448,9 @@ impl<'a> Walker<'a> {
if crate::subtype(self.doc, dict)?.as_deref() != Some(b"Form") {
return Ok(());
}
if matches!(dict.get(b"OC"), Some(Object::Ref(id)) if self.off_layers.contains(id)) {
return Ok(());
}
let matrix = dict
.get(b"Matrix")
.map(|o| self.doc.resolve(o))
@@ -350,6 +470,19 @@ impl<'a> Walker<'a> {
// The XObject matrix maps form space into the user space active at `Do`.
let mut sub_gs = gs.clone();
sub_gs.ctm = matrix.then(&gs.ctm);
let bbox = dict.get(b"BBox").map(|value| self.doc.resolve(value));
if let Some([x0, y0, x1, y1]) =
bbox.as_deref().and_then(Object::as_array).and_then(|operands| <&[Object; 4]>::try_from(operands.as_slice()).ok()).and_then(|values| {
let [x0, y0, x1, y1] = values.each_ref().map(|value| self.doc.resolve(value).as_f64());
Some([x0?, y0?, x1?, y1?]).filter(|values| values.iter().all(|v| v.is_finite()))
})
{
let bounds = [x0.min(x1), y0.min(y1), x0.max(x1), y0.max(y1)];
let bbox = sub_gs.ctm.bbox(bounds);
if bbox.iter().all(|v| v.is_finite()) {
sub_gs.clip.intersect_rect(bbox);
}
}
let mut sub_stack = Vec::new();
self.walk_ops(ops(&data), &mut sub_gs, &mut sub_stack, sub_resources, depth + 1, Some(pos))
}
@@ -392,12 +525,37 @@ fn ext_state(doc: &Document, resources: &Dict, name: &[u8], gs: &mut Gs) {
}
}
/// Empty shows and TJ positioning adjustments contribute no outline to a text clip.
fn shows_glyphs(op: &Op) -> bool {
let nonempty = |value: &Object| matches!(value, Object::String(text) if !text.bytes.is_empty());
match op.operands.last() {
Some(Object::Array(items)) if op.is("TJ") => items.iter().any(nonempty),
Some(value) if !op.is("TJ") => nonempty(value),
_ => false,
}
}
/// Only explicit groups in `/D /OFF` suppress covers. `/BaseState`, `/ON` and
/// optional-content membership dictionaries stay visible to the audit.
fn off_layers(doc: &Document) -> HashSet<ObjRef> {
let Some(root) = doc.trailer().get(b"Root").map(|value| doc.resolve(value)) else { return HashSet::new() };
let props = root.as_dict().and_then(|dict| dict.get(b"OCProperties")).map(|value| doc.resolve(value));
let configuration = props.as_deref().and_then(Object::as_dict).and_then(|dict| dict.get(b"D")).map(|value| doc.resolve(value));
let off = configuration.as_deref().and_then(Object::as_dict).and_then(|dict| dict.get(b"OFF")).map(|value| doc.resolve(value));
off.as_deref()
.and_then(Object::as_array)
.into_iter()
.flatten()
.filter_map(|value| if let Object::Ref(id) = value { Some(*id) } else { None })
.collect()
}
/// Every opaque filled rectangle drawn by a page's content (and its form XObjects), with paint
/// positions. A page's content streams are walked once, joined, with one graphics state, so
/// state set in an earlier stream is still in force in the later ones. Any content stream that
/// cannot be decoded, or content and forms that decode or enter past one page's [`DecodeBudget`]
/// in all, is an audit failure, never an empty result.
pub fn filled_rects(doc: &Document, page: &Dict) -> Result<Vec<FilledRect>, AuditError> {
pub fn filled_rects(doc: &Document, page: &Dict, blank_clips: &HashSet<usize>) -> Result<Vec<FilledRect>, AuditError> {
let resources = page.get(b"Resources").map(|o| doc.resolve(o)).and_then(|o| o.as_dict().cloned()).unwrap_or_default();
let contents: Vec<Object> = match page.get(b"Contents") {
None => Vec::new(),
@@ -414,7 +572,7 @@ pub fn filled_rects(doc: &Document, page: &Dict) -> Result<Vec<FilledRect>, Audi
}
}
let pieces = Pieces::join(&streams);
let mut w = Walker { doc, pieces: &pieces, out: Vec::new(), ops_seen: 0, budget };
let mut w = Walker { doc, pieces: &pieces, out: Vec::new(), ops_seen: 0, budget, off_layers: off_layers(doc), blank_clips };
let mut gs = Gs::default();
let mut stack = Vec::new();
// Read one operator at a time: the joined stream can hold millions of them within the
+11 -4
View File
@@ -234,10 +234,11 @@ fn audit(doc: &Document, limits: Limits) -> Result<Vec<AuditFinding>, AuditError
for (n, page) in pdfcraft_model::pages(doc).iter().enumerate() {
// The glyphs themselves: `/ActualText` is the file's own claim about them, and an empty
// or substitute one must not hide text a cover sits on.
let lines = pdfcraft_edit::glyph_text_lines(doc, page).map_err(|e| AuditError::Text(n, e.to_string()))?;
let mut blank_clips = std::collections::HashSet::new();
let lines = pdfcraft_edit::glyph_text_lines_with_blank_clips(doc, page, &mut blank_clips).map_err(|e| AuditError::Text(n, e.to_string()))?;
budget.start_page(&lines);
// 1. Opaque rectangles (filled, or painted by a thick stroke) over extractable text.
for r in cover::filled_rects(doc, &page.dict)? {
for r in cover::filled_rects(doc, &page.dict, &blank_clips)? {
if let Some(covered) = budget.hidden_text(&lines, copying, std::slice::from_ref(&r.rect), |line| hides(&r, line))? {
let covered_text = budget.report_text(covered, copying)?;
out.push(AuditFinding { page: n, kind: rect_kind(&r), rect: r.rect, covered_text });
@@ -282,10 +283,16 @@ fn rect_kind(rect: &cover::FilledRect) -> FindingKind {
/// Does `rect` hide `line`: painted after the start of the line and over it, and white or a cover
/// ([`is_cover`]). Light covers in between (table shading) are not flagged.
fn hides(rect: &cover::FilledRect, line: &TextLine) -> bool {
match rect_kind(rect) {
let kind = rect_kind(rect);
let hides = match kind {
FindingKind::HiddenUnderWhite => rect.pos > line.first_paint_pos() && covers(&rect.rect, line),
_ => is_cover(rect, line),
}
};
hides
&& !rect
.glyph_source
.as_ref()
.is_some_and(|source| line.drawn_within(&source.operators) && !(source.painted && kind == FindingKind::HiddenUnderWhite))
}
/// Does `cover` hide a substantial part of what `line` draws? Three ways, any is enough:
+201 -3
View File
@@ -1091,7 +1091,7 @@ fn repeated_stream_references_share_one_decode_budget() {
let mut doc = Document::new_empty();
let spaces = doc.add(Stream::flate(Dict::new(), &vec![b' '; 1 << 20]));
let contents: Dict = [(b"Contents".to_vec(), Object::Array(vec![Object::Ref(spaces); 300]))].into_iter().collect();
assert!(crate::cover::filled_rects(&doc, &contents).is_err(), "repeated content streams");
assert!(crate::cover::filled_rects(&doc, &contents, &Default::default()).is_err(), "repeated content streams");
let form_dict: Dict = [(b"Subtype".to_vec(), Object::Name(b"Form".to_vec()))].into_iter().collect();
let form = doc.add(Stream::flate(form_dict, &vec![b' '; 1 << 20]));
@@ -1099,7 +1099,7 @@ fn repeated_stream_references_share_one_decode_budget() {
let xobjects: Dict = [(b"X".to_vec(), Object::Ref(form))].into_iter().collect();
let resources: Dict = [(b"XObject".to_vec(), Object::Dict(xobjects))].into_iter().collect();
let page: Dict = [(b"Contents".to_vec(), Object::Ref(draws)), (b"Resources".to_vec(), Object::Dict(resources))].into_iter().collect();
assert!(crate::cover::filled_rects(&doc, &page).is_err(), "repeated form draws");
assert!(crate::cover::filled_rects(&doc, &page, &Default::default()).is_err(), "repeated form draws");
}
#[test]
@@ -1113,7 +1113,7 @@ fn form_entries_past_the_page_allowance_fail_the_audit() {
let xobjects: Dict = [(b"X".to_vec(), Object::Ref(form))].into_iter().collect();
let resources: Dict = [(b"XObject".to_vec(), Object::Dict(xobjects))].into_iter().collect();
let page: Dict = [(b"Contents".to_vec(), Object::Ref(draws)), (b"Resources".to_vec(), Object::Dict(resources))].into_iter().collect();
assert!(matches!(crate::cover::filled_rects(&doc, &page), Err(crate::AuditError::TooManyForms)));
assert!(matches!(crate::cover::filled_rects(&doc, &page, &Default::default()), Err(crate::AuditError::TooManyForms)));
}
/// Copying a covered line's text walks all of it, padding included, so a long padded line under
@@ -1164,3 +1164,201 @@ fn every_finding_record_counts_against_the_output_bound() {
let short = crate::Limits { covered_text: 3 * one - 1, ..exact };
assert!(matches!(crate::audit(&doc, short), Err(crate::AuditError::TooMuchOutput)));
}
#[test]
fn clipping_path_prunes_clipped_out_box() {
// Negative control (#3118): box is drawn outside the active clip, so it hides nothing.
let content = b"BT /F1 24 Tf 100 700 Td (SECRET DATA 123) Tj ET\nq 0 0 10 10 re W n 0 g 100 688 220 32 re f Q\n";
let findings = audit_redactions(&open(one_page(content, ""))).expect("audit must run");
assert!(findings.is_empty(), "{findings:?}");
// Paired positive control: clipping path contains the box, so the cover is detected.
let content = b"BT /F1 24 Tf 100 700 Td (SECRET DATA 123) Tj ET\nq 90 680 240 50 re W n 0 g 100 688 220 32 re f Q\n";
let findings = audit_redactions(&open(one_page(content, ""))).expect("audit must run");
assert_eq!(findings.len(), 1, "{findings:?}");
assert_eq!(findings[0].kind, FindingKind::CoveredText);
assert!(findings[0].covered_text.contains("SECRET"));
// Disjoint clips leave an empty intersection so nothing visible is painted.
let content = b"BT /F1 24 Tf 100 700 Td (SECRET DATA 123) Tj ET\nq 0 0 10 10 re W n 50 50 10 10 re W n 0 g 100 688 220 32 re f Q\n";
let findings = audit_redactions(&open(one_page(content, ""))).expect("audit must run");
assert!(findings.is_empty(), "disjoint clips leave nothing visible: {findings:?}");
// A clip that is not an axis-aligned rectangle fails closed as unknown and keeps the candidate cover.
let content = b"BT /F1 24 Tf 100 700 Td (SECRET DATA 123) Tj ET\nq 0 0 m 612 0 l 306 792 l h W n 0 g 100 688 220 32 re f Q\n";
let findings = audit_redactions(&open(one_page(content, ""))).expect("audit must run");
assert_eq!(findings.len(), 1, "non-rectangular clip path fails closed: {findings:?}");
assert!(findings[0].covered_text.contains("SECRET"));
}
#[test]
fn form_bbox_clips_contained_drawing() {
// Negative control (#3118): form BBox does not reach the text.
let mut b = Builder::new();
b.add("<< /Type /Catalog /Pages 2 0 R >>");
b.add("<< /Type /Pages /Kids [3 0 R] /Count 1 >>");
b.add("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R /Resources << /Font << /F1 6 0 R >> /XObject << /Fm 5 0 R >> >> >>");
b.add_stream(b"BT /F1 24 Tf 100 700 Td (SECRET DATA 123) Tj ET\n/Fm Do\n");
b.add_stream_with(b"0 g\n100 688 220 32 re f\n", "/Type /XObject /Subtype /Form /BBox [0 0 10 10]");
b.add(FONT);
let findings = audit_redactions(&open(b.build())).expect("audit must run");
assert!(findings.is_empty(), "{findings:?}");
// Paired positive control: form BBox covers the text.
let mut b = Builder::new();
b.add("<< /Type /Catalog /Pages 2 0 R >>");
b.add("<< /Type /Pages /Kids [3 0 R] /Count 1 >>");
b.add("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R /Resources << /Font << /F1 6 0 R >> /XObject << /Fm 5 0 R >> >> >>");
b.add_stream(b"BT /F1 24 Tf 100 700 Td (SECRET DATA 123) Tj ET\n/Fm Do\n");
b.add_stream_with(b"0 g\n100 688 220 32 re f\n", "/Type /XObject /Subtype /Form /BBox [0 0 612 792]");
b.add(FONT);
let findings = audit_redactions(&open(b.build())).expect("audit must run");
assert_eq!(findings.len(), 1, "{findings:?}");
assert!(findings[0].covered_text.contains("SECRET"));
}
#[test]
fn optional_content_hidden_layer_is_not_reported() {
// Negative control (#3118): box is drawn inside a layer that is default OFF.
let mut b = Builder::new();
b.add("<< /Type /Catalog /Pages 2 0 R /OCProperties << /OCGs [6 0 R] /D << /OFF [6 0 R] >> >> >>");
b.add("<< /Type /Pages /Kids [3 0 R] /Count 1 >>");
b.add(
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> /Properties << /L1 6 0 R >> >> >>",
);
b.add_stream(b"BT /F1 24 Tf 100 700 Td (SECRET DATA 123) Tj ET\n/OC /L1 BDC\n0 g\n100 688 220 32 re f\nEMC\n");
b.add(FONT);
b.add("<< /Type /OCG /Name (Hidden) >>");
let findings = audit_redactions(&open(b.build())).expect("audit must run");
assert!(findings.is_empty(), "{findings:?}");
// Paired positive control: box is drawn inside a layer that is visible.
let mut b = Builder::new();
b.add("<< /Type /Catalog /Pages 2 0 R /OCProperties << /OCGs [6 0 R] /D << /Order [6 0 R] >> >> >>");
b.add("<< /Type /Pages /Kids [3 0 R] /Count 1 >>");
b.add(
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> /Properties << /L1 6 0 R >> >> >>",
);
b.add_stream(b"BT /F1 24 Tf 100 700 Td (SECRET DATA 123) Tj ET\n/OC /L1 BDC\n0 g\n100 688 220 32 re f\nEMC\n");
b.add(FONT);
b.add("<< /Type /OCG /Name (Visible) >>");
let findings = audit_redactions(&open(b.build())).expect("audit must run");
assert_eq!(findings.len(), 1, "{findings:?}");
assert!(findings[0].covered_text.contains("SECRET"));
}
#[test]
fn text_clipping_mode_fill_is_not_reported_as_cover() {
// Negative control (#3118): fill through Tr 7 text clip fills the glyphs, not a page cover.
let content = b"q BT /F1 24 Tf 7 Tr 100 700 Td (SECRET DATA 123) Tj ET 0 0 0.5 rg 0 0 612 792 re f Q\n";
let findings = audit_redactions(&open(one_page(content, ""))).expect("audit must run");
assert!(findings.is_empty(), "{findings:?}");
// Paired positive control: after Q restores normal clipping (or with 0 Tr), fill is detected.
let content = b"q BT /F1 24 Tf 7 Tr 100 700 Td (SECRET DATA 123) Tj ET Q 0 g 100 688 220 32 re f\n";
let findings = audit_redactions(&open(one_page(content, ""))).expect("audit must run");
assert_eq!(findings.len(), 1, "{findings:?}");
assert!(findings[0].covered_text.contains("SECRET"));
// 4 Tr clips like 7 Tr: text clipping modes 4..=7 fill glyphs, not a page cover.
let content = b"q BT /F1 24 Tf 4 Tr 100 700 Td (SECRET DATA 123) Tj ET 0 g 0 0 612 792 re f Q\n";
let findings = audit_redactions(&open(one_page(content, ""))).expect("audit must run");
assert!(findings.is_empty(), "Tr 4 text clip fills glyphs: {findings:?}");
// 3 Tr (neither stroke nor fill) does not clip: a black box over invisible, extractable text is still a cover.
let content = b"BT /F1 24 Tf 3 Tr 100 700 Td (SECRET DATA 123) Tj ET\n0 g 100 688 220 32 re f\n";
let findings = audit_redactions(&open(one_page(content, ""))).expect("audit must run");
assert_eq!(findings.len(), 1, "Tr 3 text does not clip: {findings:?}");
assert!(findings[0].covered_text.contains("SECRET"));
}
#[test]
fn white_cover_distinguishes_painted_and_clip_only_glyph_sources() {
let doc = open(one_page(b"BT /F1 24 Tf 100 700 Td (Sample) Tj ET", ""));
let lines = pdfcraft_edit::glyph_text_lines(&doc, &pdfcraft_model::pages(&doc)[0]).expect("text");
let line = &lines[0];
let mut cover = crate::cover::FilledRect {
rect: line.rect,
rgb: [1.0; 3],
pos: (0, 10),
glyph_source: Some(crate::cover::GlyphSource { operators: 0..5, painted: false }),
};
assert!(!crate::hides(&cover, line));
cover.glyph_source.as_mut().unwrap().painted = true;
assert!(crate::hides(&cover, line));
}
#[test]
fn glyph_clipping_keeps_covers_over_independent_text() {
let content = b"BT /F1 24 Tf 100 700 Td (SECRET DATA 123) Tj ET q BT /F1 24 Tf 7 Tr 100 700 Td (MASK) Tj ET 0 g 100 688 220 32 re f Q";
let findings = audit_redactions(&open(one_page(content, ""))).expect("audit must run");
assert!(findings.iter().any(|finding| finding.covered_text.contains("SECRET")), "{findings:?}");
}
#[test]
fn empty_glyph_shows_leave_clipping_unchanged() {
let blank = r#"BT /F1 24 Tf 7 Tr () Tj [() 120 ()] TJ () ' 0 0 () " /F1 0 Tf (TEXT) Tj ET"#;
let fill = "0 g 100 688 220 32 re f";
let content = format!("BT /F1 24 Tf 100 700 Td (SECRET DATA 123) Tj ET {blank} {fill}");
let findings = audit_redactions(&open(one_page(content.as_bytes(), ""))).expect("audit must run");
assert_eq!(findings.len(), 1, "{findings:?}");
assert!(findings[0].covered_text.contains("SECRET"));
let content = format!("BT /F1 24 Tf 7 Tr 100 700 Td (MASK) Tj ET {blank} {fill}");
let findings = audit_redactions(&open(one_page(content.as_bytes(), ""))).expect("audit must run");
assert!(findings.is_empty(), "a blank show must preserve the previous text clip: {findings:?}");
}
#[test]
fn unclosed_oc_in_form_xobject_does_not_leak_to_parent() {
let mut b = Builder::new();
b.add("<< /Type /Catalog /Pages 2 0 R /OCProperties << /OCGs [6 0 R] /D << /OFF [6 0 R] >> >> >>");
b.add("<< /Type /Pages /Kids [3 0 R] /Count 1 >>");
b.add(
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> /XObject << /Fm 7 0 R >> /Properties << /L1 6 0 R >> >> >>",
);
// Page: text, then /Fm Do (which has unclosed /OC /L1 BDC), then genuine cover over text.
b.add_stream(b"BT /F1 24 Tf 100 700 Td (SECRET DATA 123) Tj ET\n/Fm Do\n0 g\n100 688 220 32 re f\n");
b.add(FONT);
b.add("<< /Type /OCG /Name (Hidden) >>");
// Form Fm leaves /OC /L1 unclosed (no EMC)
b.add_stream_with(
b"/OC /L1 BDC\n0 g\n0 0 10 10 re f\n",
"/Type /XObject /Subtype /Form /BBox [0 0 10 10] /Resources << /Properties << /L1 6 0 R >> >>",
);
let findings = audit_redactions(&open(b.build())).expect("audit must run");
assert_eq!(findings.len(), 1, "genuine cover following unclosed form OC must not be suppressed: {findings:?}");
assert!(findings[0].covered_text.contains("SECRET"));
}
#[test]
fn rotated_re_cover_detection() {
// 90-degree axis-aligned rotation: (x_user, y_user) = (800 - y, x)
// with rect [688, 480, 32, 220] mapping to user space [100, 688, 320, 720] over the text.
let content = b"BT /F1 24 Tf 100 700 Td (SECRET DATA 123) Tj ET\nq 0 1 -1 0 800 0 cm 0 g 688 480 32 220 re f Q\n";
let findings = audit_redactions(&open(one_page(content, ""))).expect("audit must run");
assert_eq!(findings.len(), 1, "90-deg rotated axis-aligned rect is detected: {findings:?}");
assert!(findings[0].covered_text.contains("SECRET"));
// 45-degree rotation: keep the conservative bounding-box result.
let content = b"BT /F1 24 Tf 100 700 Td (SECRET DATA 123) Tj ET\nq 0.7071 0.7071 -0.7071 0.7071 200 550 cm 0 g 10 10 160 160 re f Q\n";
let findings = audit_redactions(&open(one_page(content, ""))).expect("audit must run");
assert_eq!(findings.len(), 1, "the rotated cover must still be reported: {findings:?}");
}
#[test]
fn nested_marked_content_inside_hidden_oc_is_not_reported() {
let mut b = Builder::new();
b.add("<< /Type /Catalog /Pages 2 0 R /OCProperties << /OCGs [6 0 R] /D << /OFF [6 0 R] >> >> >>");
b.add("<< /Type /Pages /Kids [3 0 R] /Count 1 >>");
b.add(
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> /Properties << /L1 6 0 R >> >> >>",
);
// Nested marked content (/Span) inside hidden layer (/OC /L1): box remains on hidden layer after inner EMC.
b.add_stream(b"BT /F1 24 Tf 100 700 Td (SECRET DATA 123) Tj ET\n/OC /L1 BDC\n/Span << >> BDC\nEMC\n0 g\n100 688 220 32 re f\nEMC\n");
b.add(FONT);
b.add("<< /Type /OCG /Name (Hidden) >>");
let findings = audit_redactions(&open(b.build())).expect("audit must run");
assert!(findings.is_empty(), "box inside nested marked content on hidden OC layer must not be reported: {findings:?}");
}
+1 -2
View File
@@ -266,10 +266,9 @@ impl Automation {
let path = self.resolve(p, false)?;
files.push((p.to_string(), crate::read_input_bytes(&path).map_err(|e| failed(format!("{p}: {e}")))?));
}
let csv = pdfcraft_engine::merge_data_files(&files).map_err(failed)?;
let (csv, columns) = pdfcraft_engine::merge_data_files_with_columns(&files).map_err(failed)?;
let target = self.resolve(a.str("path")?, true)?;
write_atomic(&target, csv.as_bytes())?;
let columns = csv.lines().next().map_or(0, |h| h.split(',').count());
Ok(json!({ "path": target.to_string_lossy(), "rows": files.len(), "columns": columns }))
}
+27 -3
View File
@@ -4,6 +4,27 @@ use super::paths::{child, read_input, read_input_bytes, unused, write_atomic};
use super::{Arc, Automation, CombineSource, Edit, Path, PathBuf, Value, json};
impl Automation {
/// The sheet image pages go on: `page_size` as a paper name ("A4", "Letter", "ARCH C") or
/// `[width, height]` in points, with the image scaled to fit and centred. Absent, each page
/// is the size of its own image, which is what a phone photo's pixels give.
fn image_page(a: &Args) -> Result<pdfcraft_engine::ImagePage> {
let turn = a.opt_bool("page_turn")?.unwrap_or(true);
let bad = || ToolError::InvalidArgs("page_size must be a paper name or [width, height] in points".into());
let page = match a.get("page_size") {
None | Some(Value::Null) => pdfcraft_engine::ImagePage::Image,
Some(Value::String(s)) => pdfcraft_engine::ImagePage::fixed(super::printing::paper_named(Some(s))?.1, turn),
Some(Value::Array(v)) if v.len() == 2 => {
let side = |i: usize| v.get(i).and_then(Value::as_f64).ok_or_else(bad);
pdfcraft_engine::ImagePage::fixed((side(0)?, side(1)?), turn)
}
Some(_) => return Err(bad()),
};
// A page the creator cannot make is the caller's argument being wrong, not a conversion
// failure, and refusing it here is what keeps mode "separate" from making out_dir first.
page.check().map_err(|e| ToolError::InvalidArgs(e.to_string()))?;
Ok(page)
}
pub(crate) fn doc_create(&mut self, a: &Args) -> Result<Value> {
let (name, bytes) = match a.str("from")? {
"blank" => {
@@ -24,7 +45,7 @@ impl Automation {
} else {
"Images.pdf".into()
};
(name, self.session.create_from_images_with_resolution(&images, resolution).map_err(failed)?)
(name, self.session.create_from_images_with(&images, resolution, Self::image_page(a)?).map_err(failed)?)
}
"text" => {
let (title, text) = match (a.opt_str("text")?, a.opt_str("path")?) {
@@ -201,11 +222,12 @@ impl Automation {
Some(_) => return Err(ToolError::InvalidArgs("pages must list a range (or null) for each path".into())),
};
// Each file is read, converted and copied in turn, so a long list holds one file at a time.
let page = Self::image_page(a)?;
let sources = paths.into_iter().zip(ranges).map(|(p, range)| -> std::result::Result<pdfcraft_engine::CombineSource, ToolError> {
let path = self.resolve(p, false)?;
let bytes = read_input(&path)?;
let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
let (_, pdf) = self.session.convert_to_pdf(&name, &Arc::new(bytes)).map_err(failed)?;
let (_, pdf) = self.session.convert_to_pdf_with(&name, &Arc::new(bytes), page).map_err(failed)?;
let title = path.file_stem().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
Ok((title, pdf, range))
});
@@ -216,6 +238,8 @@ impl Automation {
/// One PDF per file, written into `out_dir`; a file that fails doesn't stop the others.
fn create_separate(&mut self, a: &Args, paths: &[&str]) -> Result<Value> {
let dir = self.resolve(a.str("out_dir").map_err(|_| ToolError::InvalidArgs("mode \"separate\" needs out_dir".into()))?, true)?;
// Checked before the folder is made, so a bad page_size leaves nothing behind.
let page = Self::image_page(a)?;
std::fs::create_dir_all(&dir).map_err(|e| failed(format!("{}: {e}", dir.display())))?;
let mut out = Vec::new();
for &p in paths {
@@ -223,7 +247,7 @@ impl Automation {
let bytes = read_input_bytes(&src).map_err(|e| format!("{}: {e}", src.display()))?;
let name = src.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
let stem = src.file_stem().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| "document".into());
let (kind, pdf) = self.session.convert_to_pdf(&name, &Arc::new(bytes)).map_err(|e| e.to_string())?;
let (kind, pdf) = self.session.convert_to_pdf_with(&name, &Arc::new(bytes), page).map_err(|e| e.to_string())?;
Ok((kind, stem, pdf))
});
out.push(match converted {
+6
View File
@@ -33,6 +33,12 @@ impl Automation {
Some(Value::Object(params)) => params.clone(),
Some(_) => return Err(ToolError::InvalidArgs("params must be an object".into())),
};
// Without it the tool would do something else: add a header and footer, not update one.
if let Some(arg) = tools::command_needs(id)
&& params.get(arg).is_none_or(Value::is_null)
{
return Err(ToolError::InvalidArgs(format!("{id} needs params.{arg} (see {tool})")));
}
let props = def.input_schema.get("properties").and_then(Value::as_object).ok_or_else(|| failed("tool has no parameter schema"))?;
let accepted = props.keys().map(String::as_str).collect::<Vec<_>>().join(", ");
let mut warnings = Vec::new();
+16 -1
View File
@@ -44,6 +44,14 @@ fn view_transform_to_user(info: &pdfcraft_render::PageInfo, m: [f64; 6]) -> Resu
impl Automation {
/// Run the tool `name` with JSON `args` (an object; `null` means no arguments).
pub fn call(&mut self, name: &str, args: &Value) -> Result<Vec<Content>> {
let out = self.call_tool(name, args);
// Whatever the call did, failed or not: the id of a header and footer it removed must not
// pass to one a later call adds with the same settings (#5785).
self.forget_removed_header_footers();
out
}
fn call_tool(&mut self, name: &str, args: &Value) -> Result<Vec<Content>> {
let empty = json!({});
let args = if args.is_null() { &empty } else { args };
if !args.is_object() {
@@ -393,7 +401,13 @@ impl Automation {
let doc = self.doc(&a)?;
let p = &doc.info.pages[page];
let user = p.view_to_user(point[0] as f32, point[1] as f32).map(f64::from);
let images: Vec<_> = doc.page_images(page).iter().enumerate().filter(|(_, im)| im.contains(user)).map(|(i, _)| i + 1).collect();
let images: Vec<_> = doc
.page_images(page)
.iter()
.enumerate()
.filter(|(_, im)| im.contains(user) && doc.image_shows_at(im, user))
.map(|(i, _)| i + 1)
.collect();
json!({"page":page+1,"images":images})
}
"page_images" => {
@@ -722,6 +736,7 @@ impl Automation {
"doc_export_images" | "doc_export_text" | "doc_export_all_images" => self.export(name, &a)?,
"doc_header_footer" | "doc_watermark" | "doc_background" | "doc_printer_marks" | "doc_remove_marks" => self.marks(name, &a)?,
"doc_backdrops" => self.backdrops(&a)?,
"doc_header_footers" => self.header_footers(&a)?,
"doc_unprotect" => {
let mut out = self.apply(&a, Edit::RemoveProtection)?;
out["security"] = security(self.doc(&a)?);
+160 -5
View File
@@ -15,7 +15,107 @@ const BOOKMARK_PAGE: usize = 100;
const MAX_BOOKMARK_PAGE: usize = 1000;
/// The ids `doc_header_footers` gives one document's headers and footers, for
/// `doc_header_footer`'s `update` (#5785).
///
/// A mark is known by its recorded settings (marks with equal ones count as one, and Update finds
/// the one to change by them), so the id names the mark with those settings wherever it moves and
/// however the list around it changes. But equal settings alone don't make the same mark: one
/// removed and then added again with the same settings is a new one. So each mark gets a serial
/// when it is first seen, never given before, which it keeps only while it stays: every tool call
/// ends by forgetting the serials of the marks it removed or changed
/// ([`Automation::forget_removed_header_footers`]). An id taken before then names no mark, and
/// a stale selection is refused rather than applied to another mark.
pub(crate) struct HeaderFooterIds {
/// The working file the serials were last checked against: a call that leaves it as it was
/// removed no mark.
seen: Arc<Vec<u8>>,
/// The serial of each mark the document has, by [`settings_digest`].
serials: std::collections::HashMap<u64, u64>,
}
/// The key ids are hashed with: afresh each run, like doc handles, so an id tells nothing about
/// text a document doesn't allow copying.
fn id_hasher() -> std::hash::DefaultHasher {
use std::hash::BuildHasher;
static KEY: std::sync::OnceLock<std::collections::hash_map::RandomState> = std::sync::OnceLock::new();
KEY.get_or_init(Default::default).build_hasher()
}
/// The `id` of the mark with settings digest `digest` and serial `serial` ([`HeaderFooterIds`]).
fn header_footer_id(digest: u64, serial: u64) -> String {
use std::hash::Hasher;
let mut h = id_hasher();
h.write_u64(digest);
h.write_u64(serial);
format!("{:016x}", h.finish())
}
/// Settings equal as compared, and only those, digest alike.
fn settings_digest(settings: &pdfcraft_engine::HeaderFooter) -> u64 {
use std::hash::{Hash, Hasher};
// Every field, so a new one can't be left out.
let pdfcraft_engine::HeaderFooter { text, font, font_size, color, underline, margins, start_number, shrink } = settings;
let mut h = id_hasher();
text.hash(&mut h);
h.write_u8(match font {
pdfcraft_engine::FontFamily::Helvetica => 0,
pdfcraft_engine::FontFamily::Times => 1,
pdfcraft_engine::FontFamily::Courier => 2,
});
// -0.0 equals 0.0 as a setting, so both hash as 0.0. (Listed settings are finite.)
for v in std::iter::once(font_size).chain(color).chain(margins) {
h.write_u64(if *v == 0.0 { 0 } else { v.to_bits() });
}
underline.hash(&mut h);
start_number.hash(&mut h);
shrink.hash(&mut h);
h.finish()
}
impl Automation {
/// The headers and footers of `id` (as `Document::header_footers` lists them) with their ids,
/// giving a new serial to each one not seen before and forgetting those of the ones gone.
fn header_footers_with_ids(&mut self, id: DocId) -> Result<Vec<(pdfcraft_engine::HeaderFooterMark, String)>> {
let doc = self.session.get(id).ok_or_else(|| failed("no such document"))?;
let marks = doc.header_footers();
let ids = self.header_footer_ids.entry(id).or_insert_with(|| HeaderFooterIds { seen: doc.bytes.clone(), serials: Default::default() });
ids.seen = doc.bytes.clone();
let digests: Vec<u64> = marks.iter().map(|m| settings_digest(&m.settings)).collect();
ids.serials.retain(|d, _| digests.contains(d));
let last = &mut self.last_header_footer;
Ok(marks
.into_iter()
.zip(digests)
.map(|(m, d)| {
let serial = *ids.serials.entry(d).or_insert_with(|| {
*last += 1;
*last
});
(m, header_footer_id(d, serial))
})
.collect())
}
/// After every tool call: forget the ids of the headers and footers the call removed or
/// changed, in each document ids were given for, so none passes to one added later
/// ([`HeaderFooterIds`]). A document whose working file the call left as it was is skipped.
pub(crate) fn forget_removed_header_footers(&mut self) {
let docs: Vec<DocId> = self.header_footer_ids.keys().copied().collect();
for id in docs {
let changed = match self.session.get(id) {
None => {
self.header_footer_ids.remove(&id);
continue;
}
Some(doc) => !Arc::ptr_eq(&doc.bytes, &self.header_footer_ids[&id].seen),
};
if changed {
let _ = self.header_footers_with_ids(id);
}
}
}
// ---- documents ---------------------------------------------------------------------------
/// One page of a document's bookmarks: `offset` (from 0) and `limit` (1 to `MAX_BOOKMARK_PAGE`).
@@ -603,6 +703,33 @@ impl Automation {
Ok(out)
}
/// The headers and footers with recorded settings, each with the `id` `doc_header_footer`'s
/// `update` names it by. Their text is copied out only where the document allows copying, as
/// with `doc_to_copy`.
pub(crate) fn header_footers(&mut self, a: &Args) -> Result<Value> {
let id = self.doc(a)?.id;
let marks = self.header_footers_with_ids(id)?;
let copying = self.doc(a)?.check_copying().is_ok();
let found: Vec<Value> = marks
.iter()
.map(|(m, id)| {
let mut out = json!({ "id": id, "pages": m.pages.iter().map(|p| p + 1).collect::<Vec<_>>() });
if copying {
let boxes = ["header_left", "header_center", "header_right", "footer_left", "footer_center", "footer_right"];
let text: serde_json::Map<String, Value> =
boxes.iter().zip(&m.settings.text).filter(|(_, t)| !t.is_empty()).map(|(k, t)| ((*k).to_string(), json!(t))).collect();
out["text"] = Value::Object(text);
}
out
})
.collect();
let mut out = json!({ "header_footers": found });
if !copying {
out["text_withheld"] = json!("the document does not allow copying its text");
}
Ok(out)
}
/// Pages whose own backdrop hides a background (see `pdfcraft_edit::backdrop`).
pub(crate) fn backdrops(&mut self, a: &Args) -> Result<Value> {
let n = self.doc(a)?.info.pages.len();
@@ -628,9 +755,28 @@ impl Automation {
pub(crate) fn marks(&mut self, tool: &str, a: &Args) -> Result<Value> {
use pdfcraft_engine::{Background, HeaderFooter, MarkKind, Watermark};
let n = self.doc(a)?.info.pages.len();
let pages = match a.opt_ints("pages")? {
Some(_) => self.pages(a, "pages")?,
None => (0..n).collect(),
// The header and footer `update` names, as `doc_header_footers` lists it.
let updating = match a.opt_str("update")? {
Some(_) if tool != "doc_header_footer" => return Err(ToolError::InvalidArgs("update is only for doc_header_footer".into())),
Some(_) if a.opt_bool("replace")?.is_some() => return Err(ToolError::InvalidArgs("give update or replace, not both".into())),
Some(id) => {
// By id, never by place in the list: a selection made before the list changed
// still reaches its own header and footer, or none (#5785).
let doc = self.doc(a)?.id;
let mark = self.header_footers_with_ids(doc)?.into_iter().find(|(_, i)| i == id).map(|(m, _)| m);
Some(mark.ok_or_else(|| {
ToolError::InvalidArgs(format!(
"no header and footer has the id {id:?}: it was changed or removed since doc_header_footers listed it, so list them again"
))
})?)
}
None => None,
};
let updated = updating.is_some();
let pages = match (a.opt_ints("pages")?, &updating) {
(Some(_), _) => self.pages(a, "pages")?,
(None, Some(mark)) => mark.pages.clone(),
(None, None) => (0..n).collect(),
};
let color =
|key: &str, default: [f64; 3]| -> Result<[f64; 3]> { Ok(a.opt_str(key)?.map(comments::parse_color).transpose()?.unwrap_or(default)) };
@@ -661,7 +807,10 @@ impl Automation {
hf.start_number = s.clamp(1, u32::MAX as i64) as u32;
}
hf.shrink = a.opt_bool("shrink")?.unwrap_or(false);
Edit::AddHeaderFooter { pages, settings: hf, replace }
match updating {
Some(mark) => Edit::UpdateHeaderFooter { old: mark.settings, pages, settings: hf },
None => Edit::AddHeaderFooter { pages, settings: hf, replace },
}
}
"doc_watermark" => {
let d = Watermark::default();
@@ -742,7 +891,13 @@ impl Automation {
Edit::RemoveMarks { kind }
}
};
self.apply(a, edit)
let mut out = self.apply(a, edit)?;
// An update gives the header and footer it changed a new id (its settings changed): hand
// back the list as it now is.
if updated {
out["header_footers"] = self.header_footers(a)?["header_footers"].take();
}
Ok(out)
}
pub(crate) fn export(&mut self, tool: &str, a: &Args) -> Result<Value> {
+13
View File
@@ -422,6 +422,19 @@ fn link_target(i: &pdfcraft_render::DocInfo, target: &pdfcraft_render::LinkTarge
},
"new_window": new_window,
}),
pdfcraft_render::LinkTarget::EmbeddedGoTo { source, destination, new_window } => json!({
"action": "GoToE",
"embedded_file": match source {
pdfcraft_render::AttachmentSource::Document { key } => json!({ "name": key }),
pdfcraft_render::AttachmentSource::Annotation { page, index } => json!({ "page": page1(*page), "annotation": index.saturating_add(1) }),
},
"destination": match destination {
pdfcraft_render::RemoteDestination::Default => json!({ "kind": "default" }),
pdfcraft_render::RemoteDestination::Page { page, view } => json!({ "kind": "page", "page": page1(*page), "view": format!("{view:?}") }),
pdfcraft_render::RemoteDestination::Named(name) => json!({ "kind": "named", "name": name }),
},
"new_window": new_window,
}),
pdfcraft_render::LinkTarget::Other(o) => json!({ "other": o }),
}
}
+6
View File
@@ -101,6 +101,10 @@ pub struct Automation {
next_ocr_review: u64,
/// What object_copy copied, for object_paste into any open document.
objects_clipboard: Option<pdfcraft_engine::ObjectClipboard>,
/// The header and footer ids handed out, by document (see `documents::HeaderFooterIds`).
header_footer_ids: HashMap<DocId, documents::HeaderFooterIds>,
/// The last serial a header and footer id was given; none is given twice.
last_header_footer: u64,
}
impl Default for Automation {
@@ -122,6 +126,8 @@ impl Automation {
ocr_reviews: HashMap::new(),
next_ocr_review: 0,
objects_clipboard: None,
header_footer_ids: HashMap::new(),
last_header_footer: 0,
}
}
+47 -4
View File
@@ -4,7 +4,7 @@
use pdfcraft_engine::{
Edit, LinkAction, LinkHighlight, LinkStyle, LinkZoom, read_remote_document, remote_document_path_is_absolute, resolve_remote_document_path,
};
use pdfcraft_render::{DestView, LinkTarget, RemoteDestination};
use pdfcraft_render::{AttachmentSource, DestView, LinkTarget, RemoteDestination};
use serde_json::{Value, json};
use std::path::Path;
@@ -224,10 +224,15 @@ impl Automation {
.iter()
.find(|link| link.page == page && link.index == index)
.ok_or_else(|| failed(format!("page {page_number} has no link {index_number} (see link_list)")))?;
let LinkTarget::RemoteGoTo { file, destination, new_window, .. } = &link.target else {
return Err(bad("the selected link is not a supported local PDF GoToR link"));
let (file, destination, new_window) = match &link.target {
LinkTarget::RemoteGoTo { file, destination, new_window, .. } => (file.clone(), destination.clone(), *new_window),
LinkTarget::EmbeddedGoTo { source: attached, destination, new_window } => {
let (attached, destination, new_window) = (attached.clone(), destination.clone(), *new_window);
return self.open_embedded_link(a, &attached, destination, new_window);
}
_ => return Err(bad("the selected link is not a supported local PDF GoToR or embedded GoToE link")),
};
(source.path.clone(), file.clone(), destination.clone(), *new_window)
(source.path.clone(), file, destination, new_window)
};
let path = resolve_remote_document_path(source_path.as_deref().map(Path::new), &file).map_err(failed)?;
let allow_absolute = a.opt_bool("allow_absolute")?.unwrap_or(false);
@@ -259,6 +264,44 @@ impl Automation {
}))
}
/// `link_open` for an embedded Go-To link (ISO 32000-2 §12.6.4.4): open the PDF attached to
/// the document, from the document's own bytes, as a new document. No file is read, so
/// `--root` has nothing to confine.
fn open_embedded_link(
&mut self,
a: &Args,
attached: &AttachmentSource,
destination: RemoteDestination,
new_window: Option<bool>,
) -> Result<Value> {
let (name, bytes) = {
let doc = self.doc(a)?;
let att = doc
.info
.attachments
.iter()
.find(|x| x.source == *attached)
.ok_or_else(|| failed("the file this GoToE link names is not attached to the document"))?;
let bytes = pdfcraft_render::attachment_data(&doc.bytes, doc.password.as_deref(), att).map_err(failed)?;
(att.name.clone(), bytes)
};
// "Embedded go-to actions work only for files of Type PDF" (§12.6.4.4).
if !pdfcraft_render::looks_like_pdf(&bytes) {
return Err(failed(format!("{name} is not a PDF, so the GoToE link can't open it")));
}
let id = self.session.open(name.clone(), None, std::sync::Arc::new(bytes), a.opt_str("password")?).map_err(failed)?;
let opened = self.session.get(id).ok_or_else(|| failed("the linked document vanished"))?;
let (destination_applied, destination_value, warning) = destination_report(opened, destination);
Ok(json!({
"document": crate::summary(opened),
"embedded_file": name,
"destination_applied": destination_applied,
"destination": destination_value,
"warning": warning,
"new_window_hint": new_window,
}))
}
pub(crate) fn link_add(&mut self, a: &Args) -> Result<Value> {
let page = self.page(a)?;
let rect = self.view_rect(a, page)?.ok_or_else(|| bad("link_add needs rect"))?;
+24
View File
@@ -89,6 +89,30 @@ fn bad(m: impl Into<String>) -> ToolError {
ToolError::InvalidArgs(m.into())
}
/// `doc_print`'s `paper`, by its name or a short form ("Letter", "ARCH D"), as its `PAPERS`
/// index and size; US Letter when none is given.
///
/// `pub(crate)` so Create answers the same names as Print: `doc_create` takes a `page_size` that
/// may be a paper name, and a second copy of this table would drift from this one.
pub(crate) fn paper_named(name: Option<&str>) -> Result<(usize, (f64, f64))> {
let mut papers = PAPERS.iter().enumerate();
let found = match name {
None => papers.next(),
Some(p) => papers.find(|(_, (n, _))| {
n.eq_ignore_ascii_case(p)
|| n.replace("US ", "").eq_ignore_ascii_case(p)
|| n.split(" (").next().is_some_and(|name| name.eq_ignore_ascii_case(p))
}),
};
found.map(|(index, (_, size))| (index, *size)).ok_or_else(|| {
bad(format!(
"unknown paper {:?}; choose one of {}",
name.unwrap_or_default(),
PAPERS.iter().map(|(name, _)| *name).collect::<Vec<_>>().join(", ")
))
})
}
/// Parse explicit custom dimensions like "300x500", "300 x 500", "300x500 pt", "300pt x 500pt", "Custom.300x500".
fn parse_custom_dimensions(s: &str) -> Option<(f64, f64)> {
let s = s.trim().trim_start_matches("Custom.").trim_start_matches("custom.").trim();
+42 -4
View File
@@ -2,6 +2,8 @@
//! document, and manage trusted certificates. Rectangles are points from the top-left of the
//! displayed page.
use std::io::Read;
use pdfcraft_engine::js::SignEvent;
use pdfcraft_engine::sign::{self, Certificate, DigitalId, Modification, Name, PrivateKey};
use pdfcraft_engine::{SignOptions, SignatureInfo, SignatureStatus};
@@ -9,6 +11,9 @@ use serde_json::{Value, json};
use crate::{Args, Automation, Result, ToolError, failed, write_atomic};
/// The name the EU Trusted List file is loaded under (`sign_trust eu_trusted_list`).
const EU_LIST: &str = "EU Trusted List";
fn bad(m: impl Into<String>) -> ToolError {
ToolError::InvalidArgs(m.into())
}
@@ -377,8 +382,10 @@ impl Automation {
}
pub(crate) fn sign_trust(&mut self, a: &Args) -> Result<Value> {
let mut certs: Vec<Certificate> =
if a.opt_bool("clear")?.unwrap_or(false) { Vec::new() } else { self.session.trusted_certificates().to_vec() };
// Every argument is read and checked first, so a bad one changes nothing, and the changes
// are applied together: the open documents are revalidated once, not once per change.
let clear = a.opt_bool("clear")?.unwrap_or(false);
let mut certs: Vec<Certificate> = if clear { Vec::new() } else { self.session.trusted_certificates().to_vec() };
// Which certificates are already in, by their bytes: a set, so a bundle of many distinct
// certificates isn't compared against every one before it.
let mut known: std::collections::HashSet<Vec<u8>> = certs.iter().map(|c| c.raw.clone()).collect();
@@ -391,6 +398,7 @@ impl Automation {
.map(|p| p.as_str().map(str::to_string).ok_or_else(|| bad("paths must be strings")))
.collect::<Result<_>>()?,
};
let certs_changed = clear || !paths.is_empty();
for p in paths {
let path = self.resolve(&p, false)?;
let bytes = crate::read_input(&path)?;
@@ -407,7 +415,37 @@ impl Automation {
}
}
}
self.session.set_trusted_certificates(certs);
Ok(json!({ "trusted": self.session.trusted_certificates().iter().map(cert_json).collect::<Vec<_>>() }))
// The trust list, off until asked for. `None`: not mentioned, left alone.
let eu_list = match a.get("eu_trusted_list") {
None => None,
Some(Value::Bool(false) | Value::Null) => Some(None),
Some(Value::String(p)) => {
let path = self.resolve(p, false)?;
// One byte more than allowed is read, so an oversize file (or one that grows, or a
// device) is refused by `from_bytes` instead of being read whole.
let mut bytes = Vec::new();
std::fs::File::open(&path)
.and_then(|f| f.take(sign::trust::MAX_LIST_BYTES as u64 + 1).read_to_end(&mut bytes))
.map_err(|e| failed(format!("{}: {e}", path.display())))?;
Some(Some(sign::trust::TrustList::from_bytes(EU_LIST, &bytes).map_err(failed)?))
}
Some(_) => return Err(bad("eu_trusted_list must be the path of a trust list file, or false")),
};
if certs_changed || eu_list.is_some() {
self.session.update_trust(|trust| {
if certs_changed {
trust.certs = certs;
}
match eu_list {
Some(Some(list)) => trust.add_list(list),
Some(None) => trust.remove_list(EU_LIST),
None => {}
}
});
}
Ok(json!({
"trusted": self.session.trusted_certificates().iter().map(cert_json).collect::<Vec<_>>(),
"trust_lists": self.session.trust_lists().iter().map(|l| json!({ "name": l.name, "certificates": l.certs.len() })).collect::<Vec<_>>(),
}))
}
}
+46 -10
View File
@@ -363,12 +363,13 @@ pub fn tools() -> Vec<ToolDef> {
"passwords": { "type": "array", "items": { "type": ["string", "null"] } },
"groups": { "type": "array", "items": { "type": ["integer", "null"], "minimum": 0 } },
"field_conflicts": { "type": "string", "enum": ["rename", "merge"] },
"out": save_out,
"open": open,
}),
&["paths"],
)),
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.")
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; page_size puts each image on a sheet of one size instead of a page as large as the image. 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!({
@@ -378,6 +379,8 @@ pub fn tools() -> Vec<ToolDef> {
"out": save_out.clone(),
"open": open.clone(),
"out_dir": { "type": "string", "description": "Folder for mode \"separate\"." },
"page_size": { "type": ["string", "array"], "items": { "type": "number", "minimum": 3, "maximum": 14400 }, "minItems": 2, "maxItems": 2, "description": "For image files: put each image on a sheet of this size instead of a page as large as the image. A paper name (A4, Letter, Legal, Tabloid, A0-A6, ARCH A-E, ANSI C-E) or [width, height] in points, each between 3 and 14400 (the largest a PDF page may be); the image is scaled to fit and centred." },
"page_turn": { "type": "boolean", "description": "With page_size: turn the sheet to match each image's orientation, so a landscape photo gets a landscape page (default true)." },
}),
&["paths"],
)),
@@ -897,7 +900,7 @@ pub fn tools() -> Vec<ToolDef> {
t("link_list", "List links", "Every link: page, 1-based index (for link_edit/link_delete), rect (points from the top-left of the page), and where it goes (url, or to_page with its zoom). A relative url also has resolved_url, the address resolved against the document's base URI (catalog /URI /Base); a link active only in its /QuadPoints has active_areas, one rect per quadrilateral. With text_links: true, also the web and email addresses written as plain page text with no link over them, which the viewer opens on a click: page, rects (one per line), url, and blocked (why it won't open) when the link check refuses it. Only http, https and mailto addresses are found. At most 100 pages are read per call, from text_links_from (default 1); text_links_next_page then gives the page to continue from.")
.ro()
.with(schema(json!({ "doc": doc(), "text_links": { "type": "boolean" }, "text_links_from": { "type": "integer", "minimum": 1 } }), &["doc"])),
t("link_open", "Open a linked PDF", "Follow a local GoToR link in PdfCraft: open the referenced PDF as a new document, respecting --root. page and index use link_list numbering. A named destination is looked up in the target, as the app does; one the target doesn't define is reported with a warning. Absolute file specifications require allow_absolute: true after reviewing the target; relative links need no opt-in.")
t("link_open", "Open a linked PDF", "Follow a local GoToR link in PdfCraft: open the referenced PDF as a new document, respecting --root. page and index use link_list numbering. A named destination is looked up in the target, as the app does; one the target doesn't define is reported with a warning. Absolute file specifications require allow_absolute: true after reviewing the target; relative links need no opt-in. A GoToE link opens the PDF embedded in this document that it names (a child target), from the document itself.")
.with(schema(
json!({ "doc": doc(), "page": { "type": "integer", "minimum": 1 }, "index": { "type": "integer", "minimum": 1 }, "password": { "type": "string", "description": "Optional password for the linked PDF." }, "allow_absolute": { "type": "boolean", "description": "Explicitly allow an absolute local GoToR target (default false). Existing validation and --root confinement still apply." } }),
&["doc", "page", "index"],
@@ -1086,8 +1089,8 @@ pub fn tools() -> Vec<ToolDef> {
}),
&["doc", "id", "out"],
)),
t("sign_trust", "Trust certificates", "Add certificates (.cer/.crt/.pem/.der, a .p7b/.p7c bundle, or the certificates in a .p12 with `password`) to the trusted certificates used to validate signatures, or clear the list (clear: true). Every open document is revalidated. Returns the trusted list.").with(schema(
json!({ "paths": { "type": "array", "items": { "type": "string" } }, "password": { "type": "string" }, "clear": { "type": "boolean" } }),
t("sign_trust", "Trust certificates", "Add certificates (.cer/.crt/.pem/.der, a .p7b/.p7c bundle, or the certificates in a .p12 with `password`) to the trusted certificates used to validate signatures, or clear the list (clear: true). `eu_trusted_list` loads a trust list kept apart from them, off until asked for: the path of a file of CA certificates (DER one after the other, or PEM; the EU Trusted Lists' qualified CAs, say), whose CAs may vouch for signers but never for a time-stamp authority; false removes it. The changes of one call are applied together, or not at all if an argument is bad, and every open document is revalidated once. Returns the trusted list and the loaded trust lists.").with(schema(
json!({ "paths": { "type": "array", "items": { "type": "string" } }, "password": { "type": "string" }, "clear": { "type": "boolean" }, "eu_trusted_list": { "type": ["string", "boolean"] } }),
&[],
)),
t("comment_mark", "Mark a comment with a checkmark", "Mark or unmark a comment with a checkmark (Acrobat: Mark with checkmark), recorded as a private reply. Undoable.").with(schema(
@@ -1246,13 +1249,14 @@ pub fn tools() -> Vec<ToolDef> {
t(
"doc_header_footer",
"Add header and footer",
"Add a header and/or footer to pages. Text boxes: header_left/center/right, footer_left/center/right. Tokens: <<1>> page number, <<n>> page count, <<1 of n>>, <<Page 1 of n>>, <<1/n>>, dates <<m/d/yyyy>> <<yyyy-mm-dd>> <<mmmm d, yyyy>> <<dd.mm.yyyy>> (and more), Bates <<Bates Number#6#1#PREFIX#SUFFIX>>. shrink: true scales the page content down evenly into the room the header and footer leave free, so they don't cover it. font: Helvetica (default), Times or Courier; Thai is drawn from PdfCraft's built-in Thai face beside it (a build without one refuses it). replace: true swaps out existing ones (Update). Undoable.",
"Add a header and/or footer to pages. Text boxes: header_left/center/right, footer_left/center/right. Tokens: <<1>> page number, <<n>> page count, <<1 of n>>, <<Page 1 of n>>, <<1/n>>, dates <<m/d/yyyy>> <<yyyy-mm-dd>> <<mmmm d, yyyy>> <<dd.mm.yyyy>> (and more), Bates <<Bates Number#6#1#PREFIX#SUFFIX>>. shrink: true scales the page content down evenly into the room the header and footer leave free, so they don't cover it. font: Helvetica (default), Times or Courier; Thai is drawn from PdfCraft's built-in Thai face beside it (a build without one refuses it). replace: true swaps out every one on those pages. update: an id from doc_header_footers changes that one alone, on its own pages unless pages is given; settings left out go back to their defaults, and the result lists them again (the changed one under a new id). Undoable.",
)
.cmd("edit.header_footer")
.with(schema(
json!({
"doc": doc(),
"pages": pages("to mark (default: all)"),
"update": { "type": "string", "minLength": 1, "description": "The id doc_header_footers lists for the header and footer to change; refused once that one has been changed or removed. Not with replace." },
"header_left": { "type": "string" }, "header_center": { "type": "string" }, "header_right": { "type": "string" },
"footer_left": { "type": "string" }, "footer_center": { "type": "string" }, "footer_right": { "type": "string" },
"font": { "type": "string", "enum": ["Helvetica", "Times", "Courier"] },
@@ -1310,6 +1314,10 @@ pub fn tools() -> Vec<ToolDef> {
.ro()
.cmd("edit.background")
.with(schema(json!({ "doc": doc(), "pages": pages("to check (default: all)") }), &["doc"])),
// No command: edit.header_footer.update changes the document, and this only lists.
t("doc_header_footers", "List headers and footers", "The headers and footers in the document, each with an `id` for doc_header_footer's `update`, its 1-based `pages` and the `text` of its boxes, tokens unexpanded (left out, with `text_withheld`, when the document does not allow copying). Lists those PdfCraft recorded settings for, in page order; older ones and other tools' are left out. An id names its header and footer wherever it moves and whatever else changes, until that one is changed or removed (or PdfCraft restarts); an update with it after that is refused, even once one with the same settings is added again (that one gets a new id).")
.ro()
.with(schema(json!({ "doc": doc() }), &["doc"])),
t("doc_remove_marks", "Remove header & footer, watermark, background or printer marks", "Remove every header and footer, watermark, background or printer marks PdfCraft (or a compatible tool) added. Undoable.")
.destructive()
.with(schema(json!({ "doc": doc(), "kind": { "type": "string", "enum": ["header_footer", "watermark", "background", "printer_marks"] } }), &["doc", "kind"])),
@@ -1448,10 +1456,10 @@ pub fn tools() -> Vec<ToolDef> {
t("form_merge_data", "Merge data files into spreadsheet", "Collect the field values of form data files (FDF, XFDF) or filled-in PDF forms into one CSV file at path: a column per field name, a row per file. Returns the row and column counts.")
.cmd("form.merge_data")
.with(schema(json!({ "paths": { "type": "array", "items": { "type": "string" }, "minItems": 1 }, "path": { "type": "string" } }), &["paths", "path"])),
t("js_run", "Run JavaScript", "Run Acrobat JavaScript in the document, as the JavaScript console does (or as push button `field`'s Mouse Up script when field is given; on a laid-out XFA form, `field` runs that button's XFA click script instead, JavaScript or FormCalc, which can add and remove rows and show or hide subforms). The form object model is available: this/getField, event, app, util, console, display, color, and the document-level scripts (except the PDF container scripts when XFA layout is active; they remain available through js_document_scripts). Field changes and resetForm are applied as one undoable step; returns the script's and subsequent field scripts' alerts (each with its message, title, icon and buttons, in order; AcroForm replies consume ordered answers; missing replies cancel input or use the alert button set's safe default), console output, requests (print, page, url, submit, attachment), error, and the errors of document-level scripts that failed (the rest still ran), plus warnings from applying the changes.")
t("js_run", "Run JavaScript", "Run Acrobat JavaScript in the document, as the JavaScript console does (or as push button `field`'s Mouse Up script when field is given; on a laid-out XFA form, `field` runs that button's XFA click script instead, JavaScript or FormCalc, which can add and remove rows and show or hide subforms). The form object model is available: this/getField, event, app, util, console, display, color, and the document-level scripts (except the PDF container scripts when XFA layout is active; they remain available through js_document_scripts). Field changes and resetForm are applied as one undoable step; returns the script's and subsequent field scripts' alerts (each with its message, title, icon and buttons, in order; popups, responses and message boxes take the ordered answers (on an XFA button only its message boxes do, xfa.host.messageBox, $host.messageBox and app.alert; its xfa.host.response and app.response return null and take none), each message box returning the button answered (1 OK, 2 Cancel, 3 No, 4 Yes); missing replies cancel input or give the message box's safe default: OK alone 1, Yes/No 3, otherwise 2), console output, requests (print, page, url, submit, attachment), error, and the errors of document-level scripts that failed (the rest still ran), plus warnings from applying the changes.")
.cmd("tools.js_console")
.with(schema(
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)."} }),
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 message box answers (every message box takes one, OK-only ones too; an XFA button's responses take none; \"1\" OK, \"2\" Cancel, \"3\" No, \"4\" Yes); strings are limited to 4096 UTF-8 bytes at runtime; null cancels a popup or response, and selects a message box's default (OK, Cancel or No, by button set)."} }),
&["doc", "script"],
)),
t(
@@ -1667,7 +1675,7 @@ pub fn tools() -> Vec<ToolDef> {
t(
"doc_create",
"Create a PDF",
"Create a new, unsaved document and return it like doc_open: `blank` (pages, width, height in points; default 1 US Letter page), `images` (paths of PNG, JPEG, TIFF (every page), GIF or BMP files, one page each at the image's resolution) or `text` (a .txt path, or `text` directly; set in Helvetica, or in the bundled Inter face when it has Latin, Greek or Cyrillic letters outside Western European (WinAnsi); other characters are refused). Save it with doc_save and a path.",
"Create a new, unsaved document and return it like doc_open: `blank` (pages, width, height in points; default 1 US Letter page), `images` (paths of PNG, JPEG, TIFF (every page), GIF or BMP files, one page each at the image's resolution, or every image on a page of one size with page_size) or `text` (a .txt path, or `text` directly; set in Helvetica, or in the bundled Inter face when it has Latin, Greek or Cyrillic letters outside Western European (WinAnsi); other characters are refused). Save it with doc_save and a path.",
)
.with(schema(
json!({
@@ -1680,6 +1688,9 @@ pub fn tools() -> Vec<ToolDef> {
"width": { "type": "number", "minimum": 3 },
"height": { "type": "number", "minimum": 3 },
"name": { "type": "string", "description": "Name for the new document (default derived from the source)." },
"page_size": { "type": ["string", "array"], "items": { "type": "number", "minimum": 3, "maximum": 14400 }, "minItems": 2, "maxItems": 2, "description": "For image files: put each image on a sheet of this size instead of a page as large as the image. A paper name (A4, Letter, Legal, Tabloid, A0-A6, ARCH A-E, ANSI C-E) or [width, height] in points, each between 3 and 14400 (the largest a PDF page may be); the image is scaled to fit and centred." },
"page_turn": { "type": "boolean", "description": "With page_size: turn the sheet to match each image's orientation, so a landscape photo gets a landscape page (default true)." },
}),
&["from"],
)),
@@ -1713,7 +1724,7 @@ pub fn tools() -> Vec<ToolDef> {
.ro()
.cmd("edit.edit_text")
.with(schema(json!({ "doc": doc(), "page": { "type": "integer", "minimum": 1 } }), &["doc", "page"])),
t("image_hit", "Hit test page artwork", "List image/Form numbers whose placement and all clipping paths contain point [x,y] in top-left-origin points. Bezier curves, even-odd/nonzero fill and holes are respected. Read only.")
t("image_hit", "Hit test page artwork", "List image/Form numbers whose placement and all clipping paths contain point [x,y] in top-left-origin points. Bezier curves, even-odd/nonzero fill and holes are respected; a picture with transparency (soft mask, /Mask, stencil) counts only where it shows. Read only.")
.ro()
.cmd("edit.edit_text")
.with(schema(json!({"doc":doc(),"page":{"type":"integer","minimum":1},"point":{"type":"array","items":{"type":"number"},"minItems":2,"maxItems":2}}), &["doc","page","point"])),
@@ -1859,8 +1870,18 @@ pub(crate) fn find(name: &str) -> Option<&'static ToolDef> {
TOOLS.iter().find(|t| t.name == name)
}
/// Commands a tool runs besides its own [`ToolDef::command`], each with the argument that makes
/// the tool do what the command does: Update header & footer is `doc_header_footer`'s `update`.
const MORE_COMMANDS: &[(&str, &str, &str)] = &[("edit.header_footer.update", "doc_header_footer", "update")];
pub(crate) fn tool_for_command(id: &str) -> Option<&'static str> {
TOOLS.iter().find(|t| t.command == Some(id)).map(|t| t.name)
let more = || MORE_COMMANDS.iter().find(|(command, ..)| *command == id).map(|(_, tool, _)| *tool);
TOOLS.iter().find(|t| t.command == Some(id)).map(|t| t.name).or_else(more)
}
/// The argument command `id` needs, when its tool does something else without it.
pub(crate) fn command_needs(id: &str) -> Option<&'static str> {
MORE_COMMANDS.iter().find(|(command, ..)| *command == id).map(|(.., arg)| *arg)
}
/// Reject unknown and missing arguments (types are checked when each value is read).
@@ -1878,3 +1899,18 @@ pub(crate) fn check_args(def: &ToolDef, args: &Value) -> Result<(), ToolError> {
}
Ok(())
}
#[cfg(test)]
mod tests {
/// Each extra command is a registered one, run by a tool that takes the argument it needs.
#[test]
fn more_commands_name_real_commands_tools_and_arguments() {
for (command, tool, arg) in super::MORE_COMMANDS {
assert!(pdfcraft_engine::commands::command(command).is_some(), "{command} is not registered");
assert!(super::TOOLS.iter().all(|t| t.command != Some(*command)), "{command} already has a tool");
let def = super::find(tool).unwrap_or_else(|| panic!("{tool} is not a tool"));
assert!(def.input_schema["properties"].get(*arg).is_some(), "{tool} takes no {arg}");
assert_eq!(super::tool_for_command(command), Some(*tool));
}
}
}
+453
View File
@@ -3275,6 +3275,11 @@ fn copy_restricted_text_stays_in_the_document() {
}
let restyled = ok(&mut a, "text_edit", json!({ "doc": re, "page": 1, "paragraph": 1, "size": 30 }));
assert!(!restyled.to_string().contains("Page"), "{restyled}");
// A header's text is listed only where copying is allowed: its index and pages still are.
ok(&mut a, "doc_header_footer", json!({ "doc": re, "pages": [1], "header_left": "HEADERTEXT" }));
let listed = ok(&mut a, "doc_header_footers", json!({ "doc": re }));
assert!(!listed.to_string().contains("HEADERTEXT") && listed["text_withheld"].is_string(), "{listed}");
assert_eq!(listed["header_footers"][0]["pages"], json!([1]));
// A path that would carry the page's words OUT of the document — the editable output, or
// the review word list — is refused on a copy-restricted document (no engines needed).
match a.call("ocr_recognize", &json!({ "doc": re, "output_mode": "editable", "out": "copy.pdf" })) {
@@ -3914,6 +3919,127 @@ fn duplicating_and_cropping_through_tools() {
assert!(matches!(a.call("page_set_box", &json!({ "doc": doc, "rect": [0, 0, 10, 10] })), Err(ToolError::InvalidArgs(_))));
}
#[test]
fn header_footer_update_changes_the_one_named() {
let dir = workdir("marks-update");
let mut a = auto(&dir);
let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap();
ok(&mut a, "doc_header_footer", json!({ "doc": doc, "pages": [1], "header_left": "FIRST" }));
ok(&mut a, "doc_header_footer", json!({ "doc": doc, "pages": [2, 3], "header_left": "SECOND" }));
let listed = ok(&mut a, "doc_header_footers", json!({ "doc": doc }));
assert_eq!(listed["header_footers"][0]["pages"], json!([1]));
let second = &listed["header_footers"][1];
assert_eq!((&second["pages"], &second["text"]), (&json!([2, 3]), &json!({ "header_left": "SECOND" })));
assert!(second["id"].as_str().is_some_and(|id| !id.is_empty()), "{second}");
let first = listed["header_footers"][0]["id"].clone();
assert_ne!(first, second["id"]);
// THIRD shares page 1 with FIRST and must stay.
ok(&mut a, "doc_header_footer", json!({ "doc": doc, "pages": [1], "footer_left": "THIRD" }));
let updated = ok(&mut a, "doc_header_footer", json!({ "doc": doc, "update": first, "header_left": "CHANGED" }));
assert_eq!(updated["header_footers"], ok(&mut a, "doc_header_footers", json!({ "doc": doc }))["header_footers"], "the ids as they are now");
let texts = page_text(&mut a, doc);
assert!(texts[0].contains("CHANGED") && !texts[0].contains("FIRST"), "{texts:?}");
assert!(texts[0].contains("THIRD"), "the other one on that page stays: {texts:?}");
assert!(texts[1].contains("SECOND") && !texts[1].contains("CHANGED"), "{texts:?}");
// Given pages, the update goes there instead: it leaves every page the old one was on, and
// the other header and footer on those pages stays.
let changed = header_footer_id(&updated, "CHANGED");
ok(&mut a, "doc_header_footer", json!({ "doc": doc, "update": changed, "pages": [2], "header_left": "MOVED" }));
let texts = page_text(&mut a, doc);
assert!(!texts[0].contains("CHANGED") && !texts[0].contains("MOVED") && texts[0].contains("THIRD"), "{texts:?}");
assert!(texts[1].contains("MOVED") && texts[1].contains("SECOND"), "{texts:?}");
assert!(!texts[2].contains("MOVED") && texts[2].contains("SECOND"), "{texts:?}");
let moved = header_footer_id(&ok(&mut a, "doc_header_footers", json!({ "doc": doc })), "MOVED");
for bad in [
json!({ "doc": doc, "update": "no-such-id", "header_left": "X" }),
json!({ "doc": doc, "update": 1, "header_left": "X" }),
json!({ "doc": doc, "update": moved, "replace": true, "header_left": "X" }),
] {
assert!(matches!(a.call("doc_header_footer", &bad), Err(ToolError::InvalidArgs(_))), "{bad}");
}
// The Update command runs the update, and only with an id: without one, the tool would add
// a header and footer instead.
let listed = ok(&mut a, "doc_header_footers", json!({ "doc": doc }));
let no_id = json!({ "id": "edit.header_footer.update", "params": { "doc": doc, "header_left": "NO ID" } });
assert!(matches!(a.call("command_run", &no_id), Err(ToolError::InvalidArgs(_))));
assert_eq!(ok(&mut a, "doc_header_footers", json!({ "doc": doc })), listed, "nothing changed");
let third = header_footer_id(&listed, "");
let by_command = json!({ "id": "edit.header_footer.update", "params": { "doc": doc, "update": third, "header_left": "VIA COMMAND" } });
ok(&mut a, "command_run", by_command);
let texts = page_text(&mut a, doc);
assert!(texts[0].contains("VIA COMMAND") && !texts[0].contains("THIRD"), "{texts:?}");
assert!(texts[1].contains("MOVED") && texts[1].contains("SECOND"), "the others stay: {texts:?}");
}
/// The `id` a `doc_header_footers` (or update) result lists for the header and footer whose
/// header_left is `text` ("" for one without).
fn header_footer_id(listed: &Value, text: &str) -> Value {
let marks = listed["header_footers"].as_array().unwrap();
let mark = marks.iter().find(|m| m["text"]["header_left"].as_str().unwrap_or("") == text).unwrap_or_else(|| panic!("no {text:?} in {listed}"));
mark["id"].clone()
}
/// A selection names its header and footer, never a place in the list (#5785). After the list
/// changes under it (another one added in front, another moved to other pages), an update with an
/// id taken earlier changes only that one; with the id of one changed since, it is refused and
/// nothing changes. With list indices, both would have reached a different header and footer.
/// Equal settings don't make the same one either: an id taken before its header and footer was
/// removed is refused after one with the same settings is added again.
#[test]
fn header_footer_update_never_reaches_another_one() {
let dir = workdir("marks-update-stale");
let mut a = auto(&dir);
let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap();
ok(&mut a, "doc_header_footer", json!({ "doc": doc, "pages": [2], "header_left": "EARLY" }));
ok(&mut a, "doc_header_footer", json!({ "doc": doc, "pages": [3], "header_left": "LATE" }));
// The selection: both ids, as listed (in page order, EARLY first).
let listed = ok(&mut a, "doc_header_footers", json!({ "doc": doc }));
let (early, late) = (header_footer_id(&listed, "EARLY"), header_footer_id(&listed, "LATE"));
assert_eq!((&listed["header_footers"][0]["id"], &listed["header_footers"][1]["id"]), (&early, &late));
// The list changes: a new one comes first, and LATE moves to page 1 (a new id, and now listed
// ahead of EARLY too).
ok(&mut a, "doc_header_footer", json!({ "doc": doc, "pages": [1], "footer_left": "NEW" }));
ok(&mut a, "doc_header_footer", json!({ "doc": doc, "update": late, "pages": [1], "header_left": "LATE MOVED" }));
let now = ok(&mut a, "doc_header_footers", json!({ "doc": doc }));
assert_eq!(now["header_footers"].as_array().unwrap().len(), 3, "{now}");
assert_eq!(now["header_footers"][2]["id"], early, "EARLY is listed last, and NEW where EARLY was: {now}");
// LATE's id is stale: refused, and no header and footer changes.
let before = page_text(&mut a, doc);
let stale = a.call("doc_header_footer", &json!({ "doc": doc, "update": late, "header_left": "WRONG" }));
assert!(matches!(&stale, Err(ToolError::InvalidArgs(m)) if m.contains("list them again")), "{stale:?}");
assert_eq!(ok(&mut a, "doc_header_footers", json!({ "doc": doc })), now, "nothing changed");
assert_eq!(page_text(&mut a, doc), before);
// EARLY's id still names EARLY alone, though another now sits where it was listed.
ok(&mut a, "doc_header_footer", json!({ "doc": doc, "update": early, "header_left": "EARLY CHANGED" }));
let texts = page_text(&mut a, doc);
assert!(texts[1].contains("EARLY CHANGED"), "{texts:?}");
assert!(texts[0].contains("LATE MOVED") && texts[0].contains("NEW") && !texts[0].contains("EARLY"), "{texts:?}");
assert!(!texts[2].contains("EARLY") && !texts[2].contains("LATE"), "{texts:?}");
// Removed, and then added again with the same settings on another page, without a listing in
// between: that is a new header and footer. The id taken before the removal names none, so it
// is refused and the new one stays as it is.
let gone = header_footer_id(&ok(&mut a, "doc_header_footers", json!({ "doc": doc })), "EARLY CHANGED");
ok(&mut a, "doc_remove_marks", json!({ "doc": doc, "kind": "header_footer" }));
ok(&mut a, "doc_header_footer", json!({ "doc": doc, "pages": [3], "header_left": "EARLY CHANGED" }));
let recreated = ok(&mut a, "doc_header_footers", json!({ "doc": doc }));
assert_eq!(recreated["header_footers"].as_array().unwrap().len(), 1, "{recreated}");
assert_ne!(header_footer_id(&recreated, "EARLY CHANGED"), gone, "a new id: {recreated}");
let before = page_text(&mut a, doc);
assert!(before[2].contains("EARLY CHANGED") && !before[1].contains("EARLY"), "{before:?}");
let stale = a.call("doc_header_footer", &json!({ "doc": doc, "update": gone, "header_left": "WRONG" }));
assert!(matches!(&stale, Err(ToolError::InvalidArgs(m)) if m.contains("list them again")), "{stale:?}");
assert_eq!(ok(&mut a, "doc_header_footers", json!({ "doc": doc })), recreated, "the recreated one is unchanged");
assert_eq!(page_text(&mut a, doc), before);
// Its own id, listed after it was added, reaches it.
let fresh = header_footer_id(&recreated, "EARLY CHANGED");
ok(&mut a, "doc_header_footer", json!({ "doc": doc, "update": fresh, "header_left": "RECREATED CHANGED" }));
assert!(page_text(&mut a, doc)[2].contains("RECREATED CHANGED"));
}
#[test]
fn headers_watermarks_and_backgrounds_through_tools() {
let dir = workdir("marks");
@@ -7727,6 +7853,65 @@ fn a_launch_link_to_a_pdf_opens_it_like_a_remote_link() {
assert_eq!(a.session().docs().len(), before, "nothing was opened or launched");
}
/// An embedded Go-To link (ISO 32000-2 §12.6.4.4) opens the PDF attached to the document, from
/// the document itself: no file of that name is read, inside the root or out of it. One to a
/// file that isn't attached, or isn't a PDF, opens nothing.
#[test]
fn an_embedded_go_to_link_opens_the_attached_pdf() {
let (_base, root) = sandbox("gotoe");
// A file of the attachment's name next to the document, which must not be what opens.
std::fs::write(root.join("inner.pdf"), fixture(1)).unwrap();
let embedded = fixture(3);
let stream = |dict: &str, data: &[u8]| {
let mut s = format!("<< {dict} /Length {} >>\nstream\n", data.len()).into_bytes();
s.extend_from_slice(data);
s.extend_from_slice(b"\nendstream");
s
};
let objs: Vec<Vec<u8>> = vec![
b"<< /Type /Catalog /Pages 2 0 R /Names << /EmbeddedFiles << /Names [(inner.pdf) 5 0 R (notes.txt) 6 0 R] >> >> >>".to_vec(),
b"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 200 300] >>".to_vec(),
b"<< /Type /Page /Parent 2 0 R /Annots [7 0 R 8 0 R 9 0 R] >>".to_vec(),
stream("/Type /EmbeddedFile", &embedded),
b"<< /Type /Filespec /F (inner.pdf) /UF (inner.pdf) /EF << /F 4 0 R >> >>".to_vec(),
b"<< /Type /Filespec /F (notes.txt) /EF << /F 10 0 R >> >>".to_vec(),
b"<< /Type /Annot /Subtype /Link /Rect [0 0 10 10] /A << /S /GoToE /T << /R /C /N (inner.pdf) >> /D [2 /Fit] >> >>".to_vec(),
b"<< /Type /Annot /Subtype /Link /Rect [0 20 10 30] /A << /S /GoToE /T << /R /C /N (missing.pdf) >> /D [0 /Fit] >> >>".to_vec(),
b"<< /Type /Annot /Subtype /Link /Rect [0 40 10 50] /A << /S /GoToE /T << /R /C /N (notes.txt) >> /D [0 /Fit] >> >>".to_vec(),
stream("/Type /EmbeddedFile", b"just some notes"),
];
let mut pdf = b"%PDF-1.7\n".to_vec();
let mut offsets = Vec::new();
for (i, o) in objs.iter().enumerate() {
offsets.push(pdf.len());
pdf.extend_from_slice(format!("{} 0 obj\n", i + 1).as_bytes());
pdf.extend_from_slice(o);
pdf.extend_from_slice(b"\nendobj\n");
}
let xref = pdf.len();
pdf.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes());
for o in offsets {
pdf.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());
}
pdf.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes());
std::fs::write(root.join("outer.pdf"), pdf).unwrap();
let mut a = auto(&root);
let source = ok(&mut a, "doc_open", json!({ "path": "outer.pdf" }))["doc"].as_u64().unwrap();
let info = ok(&mut a, "doc_info", json!({ "doc": source }));
let link = &info["links"][0]["target"];
assert_eq!((link["action"].as_str(), &link["embedded_file"]), (Some("GoToE"), &json!({ "name": "inner.pdf" })), "{info}");
let opened = ok(&mut a, "link_open", json!({ "doc": source, "page": 1, "index": 1 }));
assert_eq!(opened["document"]["pages"], 3, "the attached PDF, not the file beside the document: {opened}");
assert_eq!((opened["embedded_file"].as_str(), opened["destination_applied"].as_bool()), (Some("inner.pdf"), Some(true)));
assert_eq!(opened["destination"], json!({ "kind": "page", "page": 3, "view": { "kind": "fit" } }), "{opened}");
let before = a.session().docs().len();
for (index, why) in [(2, "not attached"), (3, "notes.txt is not a PDF")] {
let e = err(&mut a, "link_open", json!({ "doc": source, "page": 1, "index": index }));
assert!(matches!(&e, ToolError::Failed(m) if m.contains(why)), "{e}");
}
assert_eq!(a.session().docs().len(), before, "nothing else was opened");
}
/// A bookmark's action is reported as a link's target is, and only a go-to names a page here: a
/// remote go-to's `[1 /Fit]` is the other file's page 2, so doc_info and bookmark_list give this
/// file's no page for it.
@@ -8899,6 +9084,59 @@ fn optimizing_discards_an_embedded_search_index_through_tools() {
assert_eq!(piece_info("small.pdf"), ["Illustrator"]);
}
#[test]
fn a_trust_list_is_off_until_loaded_through_sign_trust() {
let dir = workdir("trust_list");
let mut a = auto(&dir);
ok(&mut a, "sign_id_create", json!({ "name": "Ada Lovelace", "country": "GB", "key": "p256", "password": "secret12", "path": "ada.p12" }));
let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap();
ok(&mut a, "sign_document", json!({ "doc": doc, "id": "ada.p12", "password": "secret12", "out": "signed.pdf" }));
let status = |a: &mut Automation| ok(a, "sign_list", json!({ "doc": doc }))["signatures"][0]["status"].as_str().unwrap().to_string();
assert_eq!(status(&mut a), "unknown", "nothing trusted by default");
// Default: no list.
let t = ok(&mut a, "sign_trust", json!({}));
assert_eq!(t["trust_lists"].as_array().map(Vec::len), Some(0));
// A trust list file (the certificate as DER), loaded by path.
let ada = pdfcraft_engine::sign::pkcs12::open(&std::fs::read(dir.join("ada.p12")).unwrap(), "secret12").unwrap();
std::fs::write(dir.join("list.der"), &ada.certificate.raw).unwrap();
let t = ok(&mut a, "sign_trust", json!({ "eu_trusted_list": "list.der" }));
assert_eq!(t["trust_lists"][0]["name"], "EU Trusted List");
assert_eq!(t["trust_lists"][0]["certificates"], 1);
assert_eq!(t["trusted"].as_array().unwrap().len(), 0, "the list is kept apart from the user's certificates");
assert_eq!(status(&mut a), "valid");
// Bad input is refused and leaves the list as it was.
std::fs::write(dir.join("junk.der"), b"not certificates").unwrap();
assert!(matches!(a.call("sign_trust", &json!({ "eu_trusted_list": "junk.der" })), Err(ToolError::Failed(_))));
assert!(matches!(a.call("sign_trust", &json!({ "eu_trusted_list": "missing.der" })), Err(ToolError::Failed(_))));
// A file over the size limit (sparse, so cheap) is refused without being read whole.
let big = std::fs::File::create(dir.join("big.der")).unwrap();
big.set_len(pdfcraft_engine::sign::trust::MAX_LIST_BYTES as u64 + 1).unwrap();
assert!(matches!(a.call("sign_trust", &json!({ "eu_trusted_list": "big.der" })), Err(ToolError::Failed(_))));
assert!(matches!(a.call("sign_trust", &json!({ "eu_trusted_list": 5 })), Err(ToolError::InvalidArgs(_))));
assert!(a.call("sign_trust", &json!({ "eu_trusted_list": "../outside.der" })).is_err(), "paths stay inside the root");
assert_eq!(status(&mut a), "valid");
// Removing it makes the signer unknown again.
assert_eq!(ok(&mut a, "sign_trust", json!({ "eu_trusted_list": false }))["trust_lists"].as_array().map(Vec::len), Some(0));
assert_eq!(status(&mut a), "unknown");
// One call can change everything at once (and revalidates once).
let t = ok(&mut a, "sign_trust", json!({ "paths": ["ada.p12"], "password": "secret12", "eu_trusted_list": "list.der" }));
assert_eq!((t["trusted"].as_array().map(Vec::len), t["trust_lists"].as_array().map(Vec::len)), (Some(1), Some(1)));
// A bad argument changes nothing, not even what came before it in the same call.
ok(&mut a, "sign_trust", json!({ "clear": true, "eu_trusted_list": false }));
for bad in [
json!({ "paths": ["ada.p12"], "password": "secret12", "eu_trusted_list": "junk.der" }),
json!({ "paths": ["ada.p12"], "password": "secret12", "eu_trusted_list": 5 }),
] {
assert!(a.call("sign_trust", &bad).is_err(), "{bad}");
let t = ok(&mut a, "sign_trust", json!({}));
assert_eq!((t["trusted"].as_array().map(Vec::len), t["trust_lists"].as_array().map(Vec::len)), (Some(0), Some(0)), "{bad}");
}
assert_eq!(status(&mut a), "unknown");
}
#[test]
fn optimizing_through_tools() {
let dir = workdir("optimize");
@@ -9869,6 +10107,9 @@ fn javascript_through_tools() {
assert!(page_text(&mut a, doc)[0].contains("EUR 2.500,00"), "{:?}", page_text(&mut a, doc));
let err = a.call("form_fill", &json!({ "doc": doc, "values": { "Qty": "0" } })).unwrap_err();
assert!(err.to_string().contains("Order at least one"), "{err}");
let fields = ok(&mut a, "form_fields", json!({ "doc": doc }));
let qty = fields["fields"].as_array().unwrap().iter().find(|x| x["name"] == "Qty").unwrap();
assert_eq!(qty["value"], "2", "the rejected value is reported, not stored");
let r = ok(
&mut a,
@@ -9953,6 +10194,47 @@ fn merging_form_data_into_a_spreadsheet() {
assert_eq!(std::fs::read_to_string(dir.join("report.csv")).unwrap(), "City\nParis\nOslo\nOslo\n");
}
#[test]
fn merging_form_data_counts_a_quoted_header_as_one_column() {
let dir = workdir("merge-data-quoted-header");
let mut a = auto(&dir);
let xfdf = |name: &str| {
format!(
r#"<?xml version="1.0" encoding="UTF-8"?><xfdf xmlns="http://ns.adobe.com/xfdf/"><fields><field name="{name}"><value>Checked</value></field></fields></xfdf>"#
)
};
// A comma or a quote in a name makes it a quoted CSV cell, still one column.
for (file, name) in [
("comma.xfdf", "Shipping, notes"),
("quote.xfdf", "Say &quot;hi&quot;, ok"),
("plain.xfdf", "Shipping notes"),
("lf.xfdf", "a&#10;b"),
("tab.xfdf", "a&#9;b"),
] {
std::fs::write(dir.join(file), xfdf(name)).unwrap();
let out = format!("{file}.csv");
let r = ok(&mut a, "form_merge_data", json!({ "paths": [file], "path": out }));
assert_eq!((r["rows"].as_u64(), r["columns"].as_u64()), (Some(1), Some(1)), "{file}: {r}");
}
// A field with an empty name is one column, not the empty header of a file without fields.
std::fs::write(dir.join("noname.xfdf"), xfdf("")).unwrap();
let r = ok(&mut a, "form_merge_data", json!({ "paths": ["noname.xfdf"], "path": "noname.csv" }));
assert_eq!((r["rows"].as_u64(), r["columns"].as_u64()), (Some(1), Some(1)), "{r}");
assert_eq!(std::fs::read_to_string(dir.join("noname.csv")).unwrap(), "\nChecked\n");
// Files without fields: no column.
std::fs::write(dir.join("empty.xfdf"), r#"<?xml version="1.0" encoding="UTF-8"?><xfdf xmlns="http://ns.adobe.com/xfdf/"><fields/></xfdf>"#)
.unwrap();
let r = ok(&mut a, "form_merge_data", json!({ "paths": ["empty.xfdf"], "path": "empty.csv" }));
assert_eq!((r["rows"].as_u64(), r["columns"].as_u64()), (Some(1), Some(0)), "{r}");
assert_eq!(std::fs::read_to_string(dir.join("empty.csv")).unwrap(), "\n\n");
// Two files with different names, one of them quoted: three columns in all.
std::fs::write(dir.join("a.xfdf"), xfdf("A, B")).unwrap();
std::fs::write(dir.join("b.xfdf"), xfdf("C")).unwrap();
std::fs::write(dir.join("c.xfdf"), xfdf("D")).unwrap();
let r = ok(&mut a, "form_merge_data", json!({ "paths": ["a.xfdf", "b.xfdf", "c.xfdf"], "path": "three.csv" }));
assert_eq!((r["rows"].as_u64(), r["columns"].as_u64()), (Some(3), Some(3)), "{r}");
}
#[test]
fn field_actions_through_tools() {
let dir = workdir("field-actions");
@@ -11521,6 +11803,42 @@ fn xfa_scripts_run_for_buttons_and_field_changes_through_tools() {
assert_eq!(r["alerts"], json!([{ "message": "Hello 4", "title": null, "icon": "error", "buttons": "ok" }]));
}
/// An XFA button that asks Yes or No branches on the answer `js_run` gives, in JavaScript and
/// FormCalc alike, and without one takes the No branch (#4291).
#[test]
fn js_run_answers_an_xfa_buttons_message_boxes() {
let dir = workdir("xfa-answers");
let tpl = pdfcraft_xfa::fixtures::scripted_template()
.replace(
r#"xfa.host.messageBox("Hello " + qty.rawValue);"#,
r#"qty.rawValue = xfa.host.messageBox("Clear?", "Order form", 2, 2) == 4 ? 0 : 7;"#,
)
.replace(r#"$host.messageBox("FormCalc")"#, r#"if ($host.messageBox("Sure?", "", 2, 1) == 1) then qty = 50 else qty = 9 endif"#);
std::fs::write(dir.join("asking.pdf"), pdfcraft_xfa::fixtures::shell(&tpl)).unwrap();
let mut a = auto(&dir).with_xfa_time_scale(100);
let doc = ok(&mut a, "doc_open", json!({ "path": "asking.pdf" }))["doc"].as_u64().unwrap();
let qty = |a: &mut Automation| {
let f = ok(a, "form_fields", json!({ "doc": doc }));
f["fields"].as_array().unwrap().iter().find(|f| f["name"] == "qty").unwrap()["value"].clone()
};
let r = ok(&mut a, "js_run", json!({ "doc": doc, "script": "", "field": "hello", "answers": ["4"] }));
assert!(r["error"].is_null(), "{r}");
assert_eq!(r["alerts"], json!([{ "message": "Clear?", "title": "Order form", "icon": "question", "buttons": "yes_no" }]));
assert_eq!(qty(&mut a), "0");
ok(&mut a, "js_run", json!({ "doc": doc, "script": "", "field": "hello", "answers": ["3"] }));
assert_eq!(qty(&mut a), "7");
ok(&mut a, "js_run", json!({ "doc": doc, "script": "", "field": "legacy", "answers": ["1"] }));
assert_eq!(qty(&mut a), "50");
// No answer: No, and Cancel.
ok(&mut a, "js_run", json!({ "doc": doc, "script": "", "field": "hello" }));
assert_eq!(qty(&mut a), "7");
ok(&mut a, "js_run", json!({ "doc": doc, "script": "", "field": "legacy", "answers": [null] }));
assert_eq!(qty(&mut a), "9");
// An answer the buttons can't give is the script's error, naming it.
let r = ok(&mut a, "js_run", json!({ "doc": doc, "script": "", "field": "hello", "answers": ["2"] }));
assert!(r["error"].as_str().is_some_and(|e| e.contains("message box 1 (2)")), "{r}");
}
/// Filling an XFA check box or radio group through form_fill clicks it, as the app does: the
/// change scripts, then the click scripts, a radio group's before those of the button now on.
#[test]
@@ -14307,6 +14625,53 @@ fn simple_rule_scan_drawn(content: &[u8]) -> Vec<u8> {
write_full(&doc, &SaveOptions::default()).unwrap()
}
/// `image_hit` counts a picture with transparency only where it shows: through a soft-masked
/// picture's transparent margin, only the picture below is hit.
#[test]
fn image_hit_sees_through_transparent_parts_of_pictures() {
let dir = workdir("alpha-hit");
let stream = |dict: &str, data: &[u8]| {
let mut o = format!("<< {dict} /Length {} >>\nstream\n", data.len()).into_bytes();
o.extend_from_slice(data);
o.extend_from_slice(b"\nendstream");
o
};
let image = "/Type /XObject /Subtype /Image /Width 4 /Height 4 /BitsPerComponent 8";
// The soft mask shows the top-right quarter only.
let mask: Vec<u8> = [[0, 0, 255, 255], [0, 0, 255, 255], [0; 4], [0; 4]].concat();
let objs: Vec<Vec<u8>> = vec![
b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(),
b"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 300 300] >>".to_vec(),
b"<< /Type /Page /Parent 2 0 R /Contents 4 0 R /Resources << /XObject << /Low 5 0 R /Top 6 0 R >> >> >>".to_vec(),
stream("", b"q 100 0 0 100 20 20 cm /Low Do Q q 100 0 0 100 60 60 cm /Top Do Q"),
stream(&format!("{image} /ColorSpace /DeviceRGB"), &[0x80; 48]),
stream(&format!("{image} /ColorSpace /DeviceRGB /SMask 7 0 R"), &[0x40; 48]),
stream(&format!("{image} /ColorSpace /DeviceGray"), &mask),
];
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", i + 1).as_bytes());
out.extend_from_slice(o);
out.extend_from_slice(b"\nendobj\n");
}
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());
std::fs::write(dir.join("overlap.pdf"), out).unwrap();
let mut a = auto(&dir);
let doc = ok(&mut a, "doc_open", json!({"path":"overlap.pdf"}))["doc"].as_u64().unwrap();
let hit = |a: &mut Automation, x: i32, y: i32| ok(a, "image_hit", json!({"doc":doc,"page":1,"point":[x, 300 - y]}))["images"].clone();
assert_eq!(hit(&mut a, 70, 70), json!([1]), "the top picture's transparent margin");
assert_eq!(hit(&mut a, 115, 115), json!([1, 2]), "where the top picture shows");
assert_eq!(hit(&mut a, 150, 70), json!([]), "transparent, over nothing");
assert_eq!(hit(&mut a, 150, 150), json!([2]));
}
/// text_extract says when a page's text is incomplete because its content was cut at the
/// renderer's limits (#623); a page read whole carries no such mark.
#[test]
@@ -15379,3 +15744,91 @@ fn pdf_watermark_uses_visible_source_crop_through_tools() {
assert_eq!(rendered[0], rendered[1], "same displayed source gives identical saved watermark at target rotation {rotation}");
}
}
/// #3273: images became pages as large as their pixels, so a set of photos gave pages of several
/// sizes and none of them paper. `page_size` puts them all on one sheet, scaled to fit.
#[test]
fn image_pages_go_on_a_chosen_paper_size_through_every_create_tool() {
let dir = workdir("image-page-size");
let mut a = auto(&dir);
let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap();
// Two pictures of different shapes, from the fixture's own pages.
ok(&mut a, "doc_export_images", json!({ "doc": doc, "folder": "src", "dpi": 18, "pages": [1, 2] }));
let shots = ["src/a_page_1.png", "src/a_page_2.png"];
let size = |a: &mut Automation, d: u64, page: usize| -> (f64, f64) {
let p = &ok(a, "doc_info", json!({ "doc": d }))["pages"][page];
(p["width"].as_f64().unwrap(), p["height"].as_f64().unwrap())
};
const A4: (f64, f64) = (595.28, 841.89);
let close = |got: (f64, f64), want: (f64, f64)| (got.0 - want.0).abs() < 0.01 && (got.1 - want.1).abs() < 0.01;
// Without it, pages follow the pixels, as they always have.
let plain = ok(&mut a, "doc_create", json!({ "from": "images", "paths": shots }))["doc"].as_u64().unwrap();
assert!(!close(size(&mut a, plain, 0), A4), "the default is unchanged: {:?}", size(&mut a, plain, 0));
// doc_create: a paper name, with the sheet turned to each image by default.
let named = ok(&mut a, "doc_create", json!({ "from": "images", "paths": shots, "page_size": "A4" }))["doc"].as_u64().unwrap();
for page in 0..2 {
let got = size(&mut a, named, page);
assert!(close(got, A4) || close(got, (A4.1, A4.0)), "page {page} is an A4 sheet either way up: {got:?}");
}
// page_turn: false pins the orientation, so every page is portrait A4.
let pinned =
ok(&mut a, "doc_create", json!({ "from": "images", "paths": shots, "page_size": "A4", "page_turn": false }))["doc"].as_u64().unwrap();
for page in 0..2 {
assert!(close(size(&mut a, pinned, page), A4), "page {page}: {:?}", size(&mut a, pinned, page));
}
// An explicit size in points works too, and the names Print accepts are accepted here.
let explicit =
ok(&mut a, "doc_create", json!({ "from": "images", "paths": shots, "page_size": [300, 300], "page_turn": false }))["doc"].as_u64().unwrap();
assert!(close(size(&mut a, explicit, 0), (300.0, 300.0)));
let letter =
ok(&mut a, "doc_create", json!({ "from": "images", "paths": shots, "page_size": "Letter", "page_turn": false }))["doc"].as_u64().unwrap();
assert!(close(size(&mut a, letter, 0), (612.0, 792.0)));
// doc_create_multiple takes it as well.
ok(&mut a, "doc_create_multiple", json!({ "paths": shots, "page_size": "A4", "page_turn": false, "out": "multiple.pdf" }));
let multiple = ok(&mut a, "doc_open", json!({ "path": "multiple.pdf" }))["doc"].as_u64().unwrap();
assert!(close(size(&mut a, multiple, 0), A4) && close(size(&mut a, multiple, 1), A4));
// mode "separate" writes one PDF per image, each on the sheet.
ok(&mut a, "doc_create_multiple", json!({ "paths": shots, "mode": "separate", "out_dir": "out", "page_size": "A4", "page_turn": false }));
let one = ok(&mut a, "doc_open", json!({ "path": "out/a_page_1.pdf" }))["doc"].as_u64().unwrap();
assert!(close(size(&mut a, one, 0), A4));
// A size no page can be is refused the same way: not a paper name, not a pair of points, or
// a pair outside the 3 to 14400 points a PDF page may be (ISO 32000-2 Annex C). Checked for
// every tool that takes one and in both of doc_create_multiple's modes, because "separate"
// makes out_dir before it converts anything and a size reported only by the conversion would
// leave the folder behind.
for bad in [json!("A9"), json!([300]), json!(["a", "b"]), json!(5), json!({}), json!([14401, 792]), json!([612, 2]), json!([-612, 792])] {
for (tool, args) in [
("doc_create", json!({ "from": "images", "paths": shots, "page_size": bad.clone() })),
("doc_create_multiple", json!({ "paths": shots, "page_size": bad.clone(), "out": "refused.pdf" })),
("doc_create_multiple", json!({ "paths": shots, "mode": "separate", "out_dir": "refused", "page_size": bad.clone() })),
] {
assert!(matches!(a.call(tool, &args), Err(ToolError::InvalidArgs(_))), "{tool}: {bad} should be refused");
}
}
assert!(!dir.join("refused.pdf").exists(), "a refused page_size leaves no file behind");
assert!(!dir.join("refused").exists(), "nor a folder");
// page_size lays out images and nothing else. A PDF source is returned as it is and a .txt
// goes through create_from_text, so neither takes the sheet: #3273 asked for photos to stop
// dictating the page, not for every source to be re-sized. Covering it because the engine
// passes `page` only to the image arm of `convert_to_pdf_with`, which is easy to widen by
// accident later (@FredApps named this as the part he read but did not run).
std::fs::write(dir.join("notes.txt"), "Some notes").unwrap();
let mixed = ok(&mut a, "doc_create_multiple", json!({ "paths": ["a.pdf", "notes.txt", shots[0]], "page_size": "A4", "out": "mixed.pdf" }));
assert!(mixed["bytes"].as_u64().unwrap_or(0) > 0, "the mixed run produced a file: {mixed}");
let doc_mixed = ok(&mut a, "doc_open", json!({ "path": "mixed.pdf" }))["doc"].as_u64().unwrap();
let pages = ok(&mut a, "doc_info", json!({ "doc": doc_mixed }))["pages"].as_array().cloned().unwrap_or_default();
let a_pdf = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap();
let kept = size(&mut a, a_pdf, 0);
assert!(!close(kept, A4) && !close(kept, (A4.1, A4.0)), "the fixture is not A4 already, or this test proves nothing: {kept:?}");
assert!(close(size(&mut a, doc_mixed, 0), kept), "the PDF's first page keeps its own size: {:?}", size(&mut a, doc_mixed, 0));
let last = pages.len() - 1;
let image_page = size(&mut a, doc_mixed, last);
assert!(close(image_page, A4) || close(image_page, (A4.1, A4.0)), "the image page did go on the sheet: {image_page:?}");
assert!(pages.len() > 2, "all three sources contributed pages: {}", pages.len());
}
+68 -2
View File
@@ -689,6 +689,65 @@ pub enum ImageResolution {
Dpi(f64),
}
/// How the page an image is placed on is sized.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub enum ImagePage {
/// The page is the image's own size at its resolution, so a page is as large as its photo
/// (a 4000 × 3000 phone picture with no stored resolution gives a 4000 × 3000 pt page).
#[default]
Image,
/// Every page is this size in points, with the image scaled to fit inside it and centred,
/// so a set of photos of different pixel sizes gives one paper size throughout.
Fixed {
width: f64,
height: f64,
/// Turn the sheet to match each image, so a landscape photo gets a landscape page
/// instead of being shrunk into a portrait one.
turn: bool,
},
}
impl ImagePage {
/// A4, Letter and the rest are resolved by the caller: the paper table lives in
/// `pdfcraft-print`, which is this crate's own layer, so names are parsed above both.
pub fn fixed(size: (f64, f64), turn: bool) -> Self {
Self::Fixed { width: size.0, height: size.1, turn }
}
/// Refuse a page this crate cannot make.
///
/// Public so a caller that acts before converting can refuse the size before the side effect:
/// `doc_create_multiple` in mode "separate" makes `out_dir` first, and an out-of-range size
/// reported only by the conversion would leave the folder behind.
pub fn check(self) -> Result<(), CreateError> {
let Self::Fixed { width, height, .. } = self else { return Ok(()) };
if !(width.is_finite() && height.is_finite() && (3.0..=MAX_SIDE).contains(&width) && (3.0..=MAX_SIDE).contains(&height)) {
return Err(CreateError::Invalid(format!("the page must be between 3 and {MAX_SIDE} points on each side")));
}
Ok(())
}
/// The page `(width, height)` for an image of `(w, h)` points, and where to draw it:
/// `(scaled width, scaled height, x, y)`.
fn place(self, w: f64, h: f64) -> ((f64, f64), (f64, f64, f64, f64)) {
let Self::Fixed { width, height, turn } = self else { return ((w, h), (w, h, 0.0, 0.0)) };
// A square image keeps the page as given; only a clear difference turns the sheet.
let (pw, ph) = if turn && (w > h) != (width > height) && w != h { (height, width) } else { (width, height) };
// A scale is a ratio, not a length, so `MAX_SIDE` has no business capping it: it bounds
// a page side, which `ImagePage::check` has already applied. Capping the scale with it
// only shrank a small image on a large sheet (a 4 x 2 image at 1200 dpi covered 3456 pt
// of a 14400 pt page instead of all of it). The fit scale needs no cap of its own: it is
// `min(pw / w, ph / h)`, so the drawn size is the page's by construction.
//
// `w` and `h` are above zero, so the division is defined: a decoded image has at least
// one pixel, and every decoder here falls back to 72 dpi rather than pass on a
// non-positive resolution (`xppu > 0 && yppu > 0` for PNG, `> 1.0` for JPEG).
let k = (pw / w).min(ph / h);
let (dw, dh) = (w * k, h * k);
((pw, ph), (dw, dh, (pw - dw) / 2.0, (ph - dh) / 2.0))
}
}
/// One page per image, each the size of its image at the image's resolution.
pub fn from_images(images: &[(String, Vec<u8>)]) -> Result<Document, CreateError> {
from_images_with_resolution(images, ImageResolution::Embedded)
@@ -696,11 +755,17 @@ pub fn from_images(images: &[(String, Vec<u8>)]) -> Result<Document, CreateError
/// Create image pages with embedded resolution or a fixed dpi (72 gives one point per pixel).
pub fn from_images_with_resolution(images: &[(String, Vec<u8>)], resolution: ImageResolution) -> Result<Document, CreateError> {
from_images_with(images, resolution, ImagePage::Image)
}
/// Create image pages at a resolution, each on a page of its own size or on a fixed sheet.
pub fn from_images_with(images: &[(String, Vec<u8>)], resolution: ImageResolution, page: ImagePage) -> Result<Document, CreateError> {
if let ImageResolution::Dpi(dpi) = resolution
&& (!dpi.is_finite() || !(1.0..=1200.0).contains(&dpi))
{
return Err(CreateError::Invalid("image DPI must be finite and between 1 and 1200".into()));
}
page.check()?;
if images.is_empty() {
return Err(CreateError::Invalid("no images".into()));
}
@@ -717,13 +782,14 @@ pub fn from_images_with_resolution(images: &[(String, Vec<u8>)], resolution: Ima
let k = (MAX_SIDE / w.max(h)).min(1.0);
w *= k;
h *= k;
let ((pw, ph), (dw, dh, x, y)) = page.place(w, h);
let xr = add_image(&mut doc, img, &mut profiles);
let mut xobj = Dict::new();
xobj.set(b"Im0".to_vec(), Object::Ref(xr));
let mut res = Dict::new();
res.set(b"XObject".to_vec(), Object::Dict(xobj));
let content = format!("q {w:.3} 0 0 {h:.3} 0 0 cm /Im0 Do Q\n").into_bytes();
tree.add(&mut doc, w, h, res, Some(content));
let content = format!("q {dw:.3} 0 0 {dh:.3} {x:.3} {y:.3} cm /Im0 Do Q\n").into_bytes();
tree.add(&mut doc, pw, ph, res, Some(content));
}
tree.finish(&mut doc)?;
if let Some((name, _)) = images.first() {
+103
View File
@@ -3157,3 +3157,106 @@ fn shared_pcx_keeps_version_four_rgb_and_palette_pixels() {
assert_eq!(super::pcx("windows.pcx", &palette).unwrap().data, [4, 5, 6]);
assert!(from_images(&[("windows.pcx".into(), rgb)]).is_ok());
}
/// A4 in points, as `pdfcraft-print`'s paper table has it (the tools resolve the name there).
const A4: (f64, f64) = (595.28, 841.89);
#[test]
fn a_fixed_page_scales_the_image_to_fit_and_centres_it() {
// 4 x 2 points at 72 dpi: wider than A4's proportions, so the width is the limit.
let fit = ImagePage::fixed(A4, false);
let ((pw, ph), (dw, dh, x, y)) = fit.place(4.0, 2.0);
assert_eq!((pw, ph), A4, "the sheet keeps the size it was given");
assert!((dw - A4.0).abs() < 1e-9, "the wide side fills the page: {dw}");
assert!((dh - A4.0 / 2.0).abs() < 1e-9, "and the aspect ratio is kept: {dh}");
assert!(x.abs() < 1e-9 && (y - (A4.1 - dh) / 2.0).abs() < 1e-9, "centred: {x}, {y}");
// Nothing is ever cropped or stretched.
assert!(dw <= pw + 1e-9 && dh <= ph + 1e-9);
assert!((dw / dh - 2.0).abs() < 1e-9, "aspect ratio kept");
// A tall image on the same sheet is limited by the height instead.
let (_, (dw, dh, x, y)) = fit.place(2.0, 4.0);
assert!((dh - A4.1).abs() < 1e-9 && (dw - A4.1 / 2.0).abs() < 1e-9, "{dw} x {dh}");
assert!(y.abs() < 1e-9 && (x - (A4.0 - dw) / 2.0).abs() < 1e-9);
// An image smaller than the sheet is enlarged to fit it, not left in a corner.
let (_, (dw, dh, ..)) = fit.place(10.0, 10.0);
assert!((dw - A4.0).abs() < 1e-9 && (dh - A4.0).abs() < 1e-9, "a square fills the narrow side");
}
#[test]
fn turning_the_sheet_follows_the_image_but_leaves_a_square_alone() {
let turn = ImagePage::fixed(A4, true);
// A landscape image turns a portrait sheet; a portrait one leaves it.
assert_eq!(turn.place(4.0, 2.0).0, (A4.1, A4.0), "landscape photo, landscape sheet");
assert_eq!(turn.place(2.0, 4.0).0, A4, "portrait photo, portrait sheet");
// A landscape sheet turns the other way for a portrait image.
let landscape = ImagePage::fixed((A4.1, A4.0), true);
assert_eq!(landscape.place(2.0, 4.0).0, A4);
// A square image is neither, so the sheet is left as asked for.
assert_eq!(turn.place(5.0, 5.0).0, A4, "a square never turns the sheet");
// Without turning, the sheet is whatever it was given.
assert_eq!(ImagePage::fixed(A4, false).place(4.0, 2.0).0, A4);
}
#[test]
fn image_pages_sized_by_the_image_are_unchanged() {
// The default must still put the page exactly on the image, at the origin.
assert_eq!(ImagePage::Image.place(4.0, 2.0), ((4.0, 2.0), (4.0, 2.0, 0.0, 0.0)));
assert_eq!(ImagePage::default(), ImagePage::Image);
let images = [("photo.png".into(), png_bytes(true)), ("scan.jpg".into(), jpeg_bytes())];
let by_image = from_images_with(&images, ImageResolution::Embedded, ImagePage::Image).unwrap();
assert_eq!(reopen(&by_image).bytes(), reopen(&from_images(&images).unwrap()).bytes(), "the same file as before");
}
#[test]
fn a_set_of_differently_shaped_images_lands_on_one_paper_size() {
// #3273: a 4 x 2 and a 3 x 2 image gave pages of two different sizes, neither of them paper.
let images = [("photo.png".into(), png_bytes(true)), ("scan.jpg".into(), jpeg_bytes())];
let doc = reopen(&from_images_with(&images, ImageResolution::Embedded, ImagePage::fixed(A4, false)).unwrap());
let p = pages(&doc);
assert_eq!(p.len(), 2);
for d in &p {
let m = media(d);
assert!((m[2] - A4.0).abs() < 0.001 && (m[3] - A4.1).abs() < 0.001, "every page is A4: {m:?}");
}
// The image is drawn scaled and centred, not at the page's origin.
let c = doc.resolve(p[0].get(b"Contents").unwrap());
let Object::Stream(s) = &*c else { panic!("expected a content stream") };
let text = String::from_utf8_lossy(&s.decoded().unwrap()).into_owned();
assert!(text.contains("595.280 0 0 297.640 0.000 272.125 cm"), "scaled to the width and centred: {text}");
// Turning gives the landscape images landscape sheets instead.
let doc = reopen(&from_images_with(&images, ImageResolution::Embedded, ImagePage::fixed(A4, true)).unwrap());
for d in pages(&doc).iter() {
let m = media(d);
assert!((m[2] - A4.1).abs() < 0.001 && (m[3] - A4.0).abs() < 0.001, "turned for a wide image: {m:?}");
}
}
#[test]
fn an_unusable_page_size_is_refused_and_nothing_is_written() {
let images = [("photo.png".into(), png_bytes(true))];
for size in [(0.0, 100.0), (100.0, 0.0), (2.9, 100.0), (f64::NAN, 100.0), (100.0, f64::INFINITY), (20_000.0, 100.0), (-5.0, 100.0)] {
let page = ImagePage::fixed(size, true);
assert!(matches!(from_images_with(&images, ImageResolution::Embedded, page), Err(CreateError::Invalid(_))), "{size:?}");
}
// The largest page PDF allows is fine.
assert!(from_images_with(&images, ImageResolution::Embedded, ImagePage::fixed((14_400.0, 14_400.0), true)).is_ok());
}
/// A fixed page is filled by the image whatever its resolution: a tiny image at a high dpi is
/// enlarged to the sheet, not left small on it. `MAX_SIDE` bounds a page side, which
/// `ImagePage::check` has already applied, so it must not also cap the fit scale.
#[test]
fn a_tiny_high_dpi_image_still_fills_its_fixed_page() {
let images = [("photo.png".into(), png_bytes(true))];
// 4 x 2 px at 1200 dpi is 0.24 x 0.12 pt: the fit scale is 60000, far past MAX_SIDE.
let page = ImagePage::fixed((MAX_SIDE, MAX_SIDE), false);
let doc = reopen(&from_images_with(&images, ImageResolution::Dpi(1200.0), page).unwrap());
let p = pages(&doc);
let c = doc.resolve(p[0].get(b"Contents").unwrap());
let Object::Stream(s) = &*c else { panic!("expected a content stream") };
let text = String::from_utf8_lossy(&s.decoded().unwrap()).into_owned();
assert!(text.contains("14400.000 0 0 7200.000 0.000 3600.000 cm"), "the image should span the full 14400 pt page: {text}");
}
+276 -21
View File
@@ -1,14 +1,14 @@
use pdfcraft_fonts::shaped_text::{is_thai, thai_refusal, thai_width};
use super::marks::{
Background, Context, HeaderFooter, MarkKind, MarkText, Watermark, add_picture_resource, bates_start, expand, matrix_number, n, picture, rgb,
shrink_matrix,
Background, Context, HeaderFooter, HeaderFooterMark, MarkKind, MarkText, SETTINGS_KEY, Watermark, add_picture_resource, bates_start, expand,
matrix_number, n, picture, read, rgb, shrink_matrix,
};
use super::place::{
END, Isolation, add_page_resources, add_resources, begin, check, check_on_top, contents, free_font_name, isolation, page_fonts, page_list, place,
place_inside_wrapper, stream_tag, undrawable, wrapper_role,
END, Isolation, add_page_resources, add_resources, begin, check, check_on_top, content_list, contents, first_wrapper, free_font_name, isolation,
page_fonts, page_list, place, place_at, place_inside_wrapper, stream_tag, undrawable, wrapper_role,
};
use super::{Document, EditError, Object, added, backdrop, helvetica_width};
use super::{Document, EditError, ObjRef, Object, added, backdrop, helvetica_width};
/// Commit one complete mark operation only after every selected page succeeds. The snapshot
/// shares original bytes, cross-references, caches and unchanged objects; only the overlay table
@@ -25,24 +25,182 @@ fn apply_mark_transaction(doc: &mut Document, apply: impl FnOnce(&mut Document)
/// those pages are removed first (Acrobat's Replace Existing). The whole call is atomic:
/// on error, the document (including earlier selected pages) is unchanged.
pub fn add_header_footer(doc: &mut Document, pages: &[usize], hf: &HeaderFooter, replace: bool, cx: &Context) -> Result<(), EditError> {
apply_mark_transaction(doc, |staged| add_header_footer_in_place(staged, pages, hf, replace, cx))
let replacing = if replace { Replacing::OnThosePages } else { Replacing::Nothing };
apply_mark_transaction(doc, |staged| add_header_footer_in_place(staged, pages, hf, replacing, cx))
}
fn add_header_footer_in_place(doc: &mut Document, pages: &[usize], hf: &HeaderFooter, replace: bool, cx: &Context) -> Result<(), EditError> {
/// Replace one header and footer: `old` (settings from [`header_footers`]) goes from every page
/// it is on and `hf` is added to `pages`. Any other header or footer stays, on those pages too
/// (#5785). On a page `old` was on, `hf` takes its place among the page's marks, so one added
/// after `old` still draws over it; on the others it goes on top. The whole call is atomic.
pub fn update_header_footer(doc: &mut Document, old: &HeaderFooter, pages: &[usize], hf: &HeaderFooter, cx: &Context) -> Result<(), EditError> {
apply_mark_transaction(doc, |staged| add_header_footer_in_place(staged, pages, hf, Replacing::Only(old), cx))
}
/// How many different headers and footers [`header_footers`] lists: enough for any real document,
/// and a limit on the work a file with a different one in every stream can ask for.
const MAX_HEADER_FOOTERS: usize = 256;
/// The settings a content stream records for its header and footer, if it records any.
fn recorded_settings(doc: &Document, stream: &Object) -> Option<HeaderFooter> {
if stream_tag(doc, stream).as_deref() != Some(MarkKind::HeaderFooter.tag()) {
return None;
}
read(doc, stream, |s| HeaderFooter::from_object(doc, s.as_dict()?.get(SETTINGS_KEY)?))
}
/// The most bytes of recorded text one scan of a document converts: the text of hundreds of
/// thousands of real headers, yet a bound on a file that repeats a large one in every stream.
const MAX_SCAN_TEXT: usize = 16 * 1024 * 1024;
/// One scan of a document's headers and footers. A stream, or a settings entry, given by reference
/// is read once however many pages share it, and the text converted in all is bounded
/// ([`MAX_SCAN_TEXT`]): a file repeating its settings can't make listing them slow.
struct Scan {
found: Vec<HeaderFooterMark>,
streams: std::collections::HashMap<ObjRef, Recorded>,
settings: std::collections::HashMap<ObjRef, Recorded>,
budget: usize,
/// Some settings went [`Recorded::Unread`].
unread: bool,
}
/// What a content stream records.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Recorded {
/// No header and footer, or one whose settings can't be read (from before they were recorded,
/// another tool's, or unreadable).
Nothing,
/// Settings past the scan's text budget ([`MAX_SCAN_TEXT`]), not read: they may be any
/// header and footer's, so a listed one may be on more pages than the scan found.
Unread,
/// Settings, listed as `found[k]`, or not listed (`None`) past [`MAX_HEADER_FOOTERS`].
Settings(Option<usize>),
}
impl Scan {
fn of(doc: &Document) -> Self {
let mut scan = Self { found: Vec::new(), streams: Default::default(), settings: Default::default(), budget: MAX_SCAN_TEXT, unread: false };
for (i, page) in page_list(doc).iter().enumerate() {
for o in content_list(doc, page).iter() {
if let Recorded::Settings(Some(k)) = scan.stream(doc, o)
&& let Some(mark) = scan.found.get_mut(k)
&& mark.pages.last() != Some(&i)
{
mark.pages.push(i);
}
}
}
scan
}
fn stream(&mut self, doc: &Document, o: &Object) -> Recorded {
let Object::Ref(r) = o else { return self.read_stream(doc, o) };
if let Some(known) = self.streams.get(r) {
return *known;
}
let recorded = self.read_stream(doc, o);
self.streams.insert(*r, recorded);
recorded
}
fn read_stream(&mut self, doc: &Document, o: &Object) -> Recorded {
if stream_tag(doc, o).as_deref() != Some(MarkKind::HeaderFooter.tag()) {
return Recorded::Nothing;
}
read(doc, o, |s| Some(self.entry(doc, s.as_dict()?.get(SETTINGS_KEY)?))).unwrap_or(Recorded::Nothing)
}
/// A stream's [`SETTINGS_KEY`] entry.
fn entry(&mut self, doc: &Document, value: &Object) -> Recorded {
let Object::Ref(r) = value else { return self.read_settings(doc, value) };
if let Some(known) = self.settings.get(r) {
return *known;
}
let recorded = self.read_settings(doc, value);
self.settings.insert(*r, recorded);
recorded
}
fn read_settings(&mut self, doc: &Document, value: &Object) -> Recorded {
let Some(settings) = HeaderFooter::from_object_within(doc, value, &mut self.budget) else {
// Running out of budget spends all of it.
if self.budget == 0 {
self.unread = true;
return Recorded::Unread;
}
return Recorded::Nothing;
};
if let Some(k) = self.found.iter().position(|m| m.settings == settings) {
return Recorded::Settings(Some(k));
}
if self.found.len() >= MAX_HEADER_FOOTERS {
return Recorded::Settings(None);
}
self.found.push(HeaderFooterMark { pages: Vec::new(), settings });
Recorded::Settings(Some(self.found.len() - 1))
}
}
/// The headers and footers that record their settings, in page order, each with the pages it is
/// on. Marks from before settings were recorded, or from another tool, are not listed. In a file
/// recording more text than one scan reads ([`MAX_SCAN_TEXT`]) a mark may be on more pages than
/// it lists, and [`remove_header_footer`] refuses rather than leave it on the others.
pub fn header_footers(doc: &Document) -> Vec<HeaderFooterMark> {
Scan::of(doc).found
}
/// The header and footer added last to page `page` (0-based): `Some(None)` when it records no
/// settings (from before they were recorded, or another tool), `None` when the page has none.
/// Each mark's own stream goes on top of the page's content, so the last one is the newest; a
/// shrink goes underneath, inside the wrapper, and is never last.
pub fn newest_header_footer(doc: &Document, page: usize) -> Option<Option<HeaderFooter>> {
let page = page_list(doc).into_iter().nth(page)?;
let content = content_list(doc, &page);
let newest = content.iter().rev().find(|o| stream_tag(doc, o).as_deref() == Some(MarkKind::HeaderFooter.tag()))?;
Some(recorded_settings(doc, newest))
}
/// Where in a page's content list `list` the header and footer recorded with `old` draws: the
/// last stream that records `old`, not counting shrinks, which go first inside the wrapper
/// ([`place_inside_wrapper`]) and draw nothing. `None` when it is not on the page.
fn mark_slot(doc: &Document, list: &[Object], old: &HeaderFooter) -> Option<usize> {
let shrinks = first_wrapper(doc, list).map_or(0..0, |open| {
let start = open.saturating_add(1);
let run = list.iter().skip(start).take_while(|o| stream_tag(doc, o).as_deref() == Some(MarkKind::HeaderFooter.tag())).count();
start..start.saturating_add(run)
});
list.iter().enumerate().rev().find(|(i, o)| !shrinks.contains(i) && recorded_settings(doc, o).as_ref() == Some(old)).map(|(i, _)| i)
}
/// Pages (0-based) with a header and footer that records no settings: Update can only replace
/// those page-wide, as it did before settings were recorded.
pub fn unrecorded_header_footer_pages(doc: &Document) -> Vec<usize> {
let tagged = |o: &Object| stream_tag(doc, o).as_deref() == Some(MarkKind::HeaderFooter.tag());
let mut scan = Scan::of(doc);
page_list(doc)
.iter()
.enumerate()
.filter(|(_, page)| content_list(doc, page).iter().any(|o| tagged(o) && scan.stream(doc, o) == Recorded::Nothing))
.map(|(i, _)| i)
.collect()
}
/// Which existing headers and footers an added one takes the place of.
#[derive(Clone, Copy)]
enum Replacing<'a> {
Nothing,
OnThosePages,
Only(&'a HeaderFooter),
}
fn add_header_footer_in_place(doc: &mut Document, pages: &[usize], hf: &HeaderFooter, replacing: Replacing, cx: &Context) -> Result<(), EditError> {
let all = page_list(doc);
check(pages, all.len())?;
if hf.text.iter().all(|t| t.trim().is_empty()) {
return Err(EditError::Invalid("type the header or footer text first".into()));
}
if let Some(why) = hf.text.iter().find_map(|t| thai_refusal(t)) {
return Err(EditError::Invalid(why));
}
if let Some(c) = hf.first_undrawable() {
return Err(undrawable(c));
}
if !(hf.font_size.is_finite() && hf.font_size > 0.0 && hf.font_size <= 200.0 && hf.margins.iter().all(|m| m.is_finite() && *m >= 0.0)) {
return Err(EditError::Invalid("invalid font size or margins".into()));
}
hf.check()?;
// Page numbers count up from start_number, so the last selected page needs the most room.
// Refuse the whole run before drawing anything: headers applied to some pages and then a
// failed page number would leave the document half changed.
@@ -74,9 +232,17 @@ fn add_header_footer_in_place(doc: &mut Document, pages: &[usize], hf: &HeaderFo
for &i in pages {
check_on_top(doc, &all[i])?;
}
if replace {
remove_marks(doc, pages, MarkKind::HeaderFooter)?;
match replacing {
Replacing::Nothing => {}
Replacing::OnThosePages => {
remove_marks(doc, pages, MarkKind::HeaderFooter)?;
}
Replacing::Only(old) => {
// Where the new one goes, `old` stays for now, to mark its place.
remove_recorded(doc, old, pages)?;
}
}
let settings = hf.to_object();
let all = page_list(doc);
let count = all.len();
let number_of = |k: usize| {
@@ -147,11 +313,22 @@ fn add_header_footer_in_place(doc: &mut Document, pages: &[usize], hf: &HeaderFo
}
thai.add_to(doc, &page_list(doc)[i])?;
let page = &page_list(doc)[i];
place(doc, page, MarkKind::HeaderFooter, content, false)?;
let slot = match replacing {
Replacing::Only(old) => mark_slot(doc, &content_list(doc, page), old),
Replacing::Nothing | Replacing::OnThosePages => None,
};
let mark = match slot {
Some(at) => place_at(doc, page, at, MarkKind::HeaderFooter, content)?,
None => place(doc, page, MarkKind::HeaderFooter, content, false)?,
};
doc.update_dict(mark, |d| d.set(SETTINGS_KEY.to_vec(), settings.clone()))?;
if let Some(Some(m)) = shrinks.get(k) {
let cm = format!("{} cm\n", m.map(matrix_number).join(" "));
let page = &page_list(doc)[i];
place_inside_wrapper(doc, page, MarkKind::HeaderFooter.tag(), cm.into_bytes())?;
// The shrink goes with its header: it records the same settings, so Update takes it too.
if let Some(shrink) = place_inside_wrapper(doc, page, MarkKind::HeaderFooter.tag(), cm.into_bytes())? {
doc.update_dict(shrink, |d| d.set(SETTINGS_KEY.to_vec(), settings.clone()))?;
}
}
}
Ok(())
@@ -301,6 +478,78 @@ fn add_background_in_place(doc: &mut Document, pages: &[usize], bg: &Background,
/// turns a backdrop [`add_background`] replaced back on where that is still safe; the pages where
/// it isn't are [`backdrops_left_off`].
pub fn remove_marks(doc: &mut Document, pages: &[usize], kind: MarkKind) -> Result<usize, EditError> {
remove_matching(doc, pages, kind, |_, _| true, |_, _, _| None)
}
/// Remove the header and footer recorded with `old` from every page it is on, and no other
/// header and footer: what [`update_header_footer`] takes away before it adds the new one in its
/// place. Returns how many mark streams went; an error when no header and footer records `old`
/// any more, or when the document records more header and footer text than one scan reads, so
/// not every page it is on can be known.
pub fn remove_header_footer(doc: &mut Document, old: &HeaderFooter) -> Result<usize, EditError> {
remove_recorded(doc, old, &[])
}
/// [`remove_header_footer`], except that on `kept_on` (pages, 0-based) the stream `old` draws
/// with ([`mark_slot`]) stays, for the header and footer replacing it to take its place.
fn remove_recorded(doc: &mut Document, old: &HeaderFooter, kept_on: &[usize]) -> Result<usize, EditError> {
let scan = Scan::of(doc);
if scan.unread {
return Err(EditError::Invalid(
"this document records too much header and footer text to find every page one is on: replace the headers and footers on the pages instead".into(),
));
}
let on = scan.found.into_iter().find(|m| m.settings == *old).map(|m| m.pages);
let on = on.ok_or_else(|| EditError::Invalid("that header and footer is no longer in the document".into()))?;
let kept = |doc: &Document, page: usize, list: &[Object]| if kept_on.contains(&page) { mark_slot(doc, list, old) } else { None };
remove_matching(doc, &on, MarkKind::HeaderFooter, |doc, o| recorded_settings(doc, o).as_ref() == Some(old), kept)
}
/// The pages under the header and footer recorded with `old`, for Update's preview: `old` goes
/// from every page it is on, with everything drawn after it there, which
/// [`over_header_footer`] keeps. Returns how many mark streams of `old` went; an error as
/// [`remove_header_footer`] gives one.
pub fn under_header_footer(doc: &mut Document, old: &HeaderFooter) -> Result<usize, EditError> {
for page in page_list(doc) {
let list = content_list(doc, &page);
if let Some(slot) = mark_slot(doc, &list, old)
&& slot.saturating_add(1) < list.len()
{
let mut list = contents(doc, &page)?;
list.truncate(slot.saturating_add(1));
doc.update_dict(page.obj, |d| d.set(b"Contents".to_vec(), Object::Array(list)))?;
}
}
remove_header_footer(doc, old)
}
/// What Update of the header and footer recorded with `old` leaves drawn over the one replacing
/// it, for its preview: each page keeps only what is drawn after `old` (nothing, where `old` is
/// not, as the new one goes on top there) and no annotations, which [`under_header_footer`]'s
/// pages already show. Returns how many pages have anything left.
pub fn over_header_footer(doc: &mut Document, old: &HeaderFooter) -> Result<usize, EditError> {
let mut left = 0;
for page in page_list(doc) {
let list = content_list(doc, &page);
let over: Vec<Object> = mark_slot(doc, &list, old).map(|slot| list.into_iter().skip(slot.saturating_add(1)).collect()).unwrap_or_default();
left += usize::from(!over.is_empty());
doc.update_dict(page.obj, |d| {
d.set(b"Contents".to_vec(), Object::Array(over));
d.remove(b"Annots");
})?;
}
Ok(left)
}
/// [`remove_marks`], only for the mark streams `matches` accepts, and on each page not the one
/// at the place in its content list `kept` names, if any.
fn remove_matching(
doc: &mut Document,
pages: &[usize],
kind: MarkKind,
matches: impl Fn(&Document, &Object) -> bool,
kept: impl Fn(&Document, usize, &[Object]) -> Option<usize>,
) -> Result<usize, EditError> {
let all = page_list(doc);
check(pages, all.len())?;
let mut removed = 0;
@@ -311,7 +560,13 @@ pub fn remove_marks(doc: &mut Document, pages: &[usize], kind: MarkKind) -> Resu
}
let list = contents(doc, page)?;
let before = list.len();
let mut kept: Vec<Object> = list.into_iter().filter(|o| stream_tag(doc, o).as_deref() != Some(kind.tag())).collect();
let stays = kept(doc, i, &list);
let mut kept: Vec<Object> = list
.into_iter()
.enumerate()
.filter(|(k, o)| Some(*k) == stays || stream_tag(doc, o).as_deref() != Some(kind.tag()) || !matches(doc, o))
.map(|(_, o)| o)
.collect();
removed += before - kept.len();
// Strip only wrapper pairs whose close ends the list (after stripping the pairs after
// it): nothing comes after them to need the state they restore. Pairs come from the
+7 -4
View File
@@ -62,8 +62,8 @@ pub mod paragraph_align;
pub mod text;
pub use text::{
BlockKey, BlockStyle, LineEdit, MAX_FORM_DEPTH, MAX_FORM_VISITS, RangeStyle, ReadingBlocks, RunSources, TextBlock, TextLine, TextSession,
block_overlapping, clear_block, glyph_text_lines, reading_blocks, reading_blocks_checked, replace_block, replace_line, rewrite_block,
text_blocks, text_lines,
block_overlapping, clear_block, glyph_text_lines, glyph_text_lines_with_blank_clips, reading_blocks, reading_blocks_checked, replace_block,
replace_line, rewrite_block, text_blocks, text_lines,
};
pub mod printer_marks;
pub use printer_marks::{PrinterMarks, add_printer_marks};
@@ -83,10 +83,13 @@ mod apply;
mod marks;
mod place;
pub use apply::{add_background, add_header_footer, add_watermark, marks_present, remove_marks};
pub use apply::{
add_background, add_header_footer, add_watermark, header_footers, marks_present, newest_header_footer, over_header_footer, remove_header_footer,
remove_marks, under_header_footer, unrecorded_header_footer_pages, update_header_footer,
};
#[cfg(test)]
use marks::bates_start;
pub use marks::{Background, Context, HeaderFooter, MarkKind, MarkSource, Watermark, expand};
pub use marks::{Background, Context, HeaderFooter, HeaderFooterMark, MarkKind, MarkSource, Watermark, expand, recorded_header_footer};
use marks::{matrix_number, n};
pub(crate) use place::undrawable;
#[cfg(test)]
+156
View File
@@ -160,6 +160,162 @@ impl HeaderFooter {
}
}
/// One header and footer in a document: its settings and the pages (0-based, ascending) it is on.
/// Marks with the same settings count as one.
#[derive(Clone, Debug, PartialEq)]
pub struct HeaderFooterMark {
pub pages: Vec<usize>,
pub settings: HeaderFooter,
}
/// The entry of a header and footer's content streams that keeps its settings, so Update can tell
/// several apart and fill the dialog with the one chosen (#5785). Drawn text alone can't say
/// which tokens made it. Private to PdfCraft (like `/PCMark`); other readers ignore it.
pub(crate) const SETTINGS_KEY: &[u8] = b"PCHeaderFooter";
/// The most bytes one recorded text box may take. A dialog box never needs more, and it bounds
/// what listing the headers and footers of a hostile file decodes.
const MAX_RECORDED_TEXT: usize = 16 * 1024;
/// `f` of `o`, or of what it refers to: a direct value is read in place, never copied, so a large
/// one costs nothing until it has been checked. (`Document::resolve` copies a direct value whole.)
pub(crate) fn read<T>(doc: &Document, o: &Object, f: impl FnOnce(&Object) -> Option<T>) -> Option<T> {
match o {
Object::Ref(_) => f(&doc.resolve(o)),
_ => f(o),
}
}
/// An array of exactly `N` numbers, each resolved: a rewriting tool may make any of them indirect.
fn numbers<const N: usize>(doc: &Document, o: &Object) -> Option<[f64; N]> {
read(doc, o, |array| {
let items = array.as_array().filter(|a| a.len() == N)?;
let values: Vec<f64> = items.iter().map(|v| read(doc, v, Object::as_f64)).collect::<Option<_>>()?;
<[f64; N]>::try_from(values).ok()
})
}
impl HeaderFooter {
/// Why [`add_header_footer`] refuses these settings, if it does. A recorded header and footer
/// is listed only when it passes too, so every one Update offers is one OK can apply.
pub(crate) fn check(&self) -> Result<(), EditError> {
if self.text.iter().all(|t| t.trim().is_empty()) {
return Err(EditError::Invalid("type the header or footer text first".into()));
}
// Measured as recorded: a box the listing would refuse to decode must not be added, or it
// could never be listed and updated, only replaced page-wide.
if self.text.iter().any(|t| pdfcraft_cos::PdfString::text(t).bytes.len() > MAX_RECORDED_TEXT) {
return Err(EditError::Invalid(format!("a header or footer box can hold at most {} KB of text", MAX_RECORDED_TEXT / 1024)));
}
if let Some(c) = self.first_undrawable() {
return Err(super::place::undrawable(c));
}
if !(self.font_size.is_finite() && self.font_size > 0.0 && self.font_size <= 200.0 && self.margins.iter().all(|m| m.is_finite() && *m >= 0.0))
{
return Err(EditError::Invalid("invalid font size or margins".into()));
}
Ok(())
}
/// These settings as the [`SETTINGS_KEY`] entry. The colour is recorded as drawn (see `rgb`),
/// so a header added with an out-of-range colour can still be listed and updated.
pub(crate) fn to_object(&self) -> Object {
let reals = |v: &[f64]| Object::Array(v.iter().copied().map(Object::Real).collect());
let drawn = self.color.map(|c| if c.is_finite() { c.clamp(0.0, 1.0) } else { 0.0 });
let mut d = Dict::new();
d.set(b"Text".to_vec(), Object::Array(self.text.iter().map(|t| Object::String(pdfcraft_cos::PdfString::text(t))).collect()));
d.set(
b"Font".to_vec(),
Object::name(match self.font {
added::Family::Helvetica => "Helvetica",
added::Family::Times => "Times",
added::Family::Courier => "Courier",
}),
);
d.set(b"Size".to_vec(), Object::Real(self.font_size));
d.set(b"Color".to_vec(), reals(&drawn));
d.set(b"Underline".to_vec(), Object::Bool(self.underline));
d.set(b"Margins".to_vec(), reals(&self.margins));
d.set(b"Start".to_vec(), Object::Int(i64::from(self.start_number)));
d.set(b"Shrink".to_vec(), Object::Bool(self.shrink));
Object::Dict(d)
}
/// Settings back from a [`SETTINGS_KEY`] entry. `None` unless every value is one the dialog
/// could have written: a file can say anything here.
pub(crate) fn from_object(doc: &Document, o: &Object) -> Option<Self> {
let mut unlimited = usize::MAX;
Self::from_object_within(doc, o, &mut unlimited)
}
/// [`from_object`](Self::from_object), converting at most `budget` bytes of text, which it
/// takes from: `None` once that is spent, leaving it 0 so a scan can tell settings it could not
/// afford from ones it could not read. Bounds what one scan of a document converts.
pub(crate) fn from_object_within(doc: &Document, o: &Object, budget: &mut usize) -> Option<Self> {
#[cfg(test)]
DECODED.with(|n| n.set(n.get() + 1));
// Every value resolved, as a rewriting tool may make any of them indirect, and read in
// place: nothing is copied before it is checked.
read(doc, o, |o| {
let d = o.as_dict()?;
let flag = |key: &[u8]| {
read(doc, d.get(key)?, |v| match v {
Object::Bool(b) => Some(*b),
_ => None,
})
};
// The count and each size are checked before anything is decoded.
let text: Vec<String> = read(doc, d.get(b"Text")?, |texts| {
let texts = texts.as_array().filter(|a| a.len() == 6)?;
texts
.iter()
.map(|t| {
read(doc, t, |t| {
let s = t.as_string().filter(|s| s.bytes.len() <= MAX_RECORDED_TEXT)?;
let Some(left) = budget.checked_sub(s.bytes.len()) else {
*budget = 0;
return None;
};
*budget = left;
Some(s.to_text())
})
})
.collect()
})?;
let hf = Self {
text: text.try_into().ok()?,
font: read(doc, d.get(b"Font")?, |v| match v.as_name()? {
b"Helvetica" => Some(added::Family::Helvetica),
b"Times" => Some(added::Family::Times),
b"Courier" => Some(added::Family::Courier),
_ => None,
})?,
font_size: read(doc, d.get(b"Size")?, Object::as_f64)?,
color: numbers(doc, d.get(b"Color")?)?,
underline: flag(b"Underline")?,
margins: numbers(doc, d.get(b"Margins")?)?,
start_number: read(doc, d.get(b"Start")?, |v| u32::try_from(v.as_int()?).ok())?,
shrink: flag(b"Shrink")?,
};
let sane = hf.check().is_ok() && hf.color.iter().all(|c| (0.0..=1.0).contains(c));
sane.then_some(hf)
})
}
}
#[cfg(test)]
thread_local! {
/// How many settings entries [`HeaderFooter::from_object_within`] has read on this thread.
pub(crate) static DECODED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// The header and footer settings a [`SETTINGS_KEY`] entry records, if it records ones that
/// [`add_header_footer`](crate::add_header_footer) would accept: what redaction matches a
/// header's streams by, however each stores them.
pub fn recorded_header_footer(doc: &Document, value: &Object) -> Option<HeaderFooter> {
HeaderFooter::from_object(doc, value)
}
/// The `cm` that shrinks a page's original content (user space) into the band `hf` leaves free,
/// for a page shown `size` (display space) with view matrix `view` (display to user space): an
/// even scale, centred across, the content's bottom on the footer's band.
+45 -17
View File
@@ -306,11 +306,25 @@ pub(crate) fn isolation(doc: &Document, list: &[Object]) -> Isolation {
/// Put a mark's content on a page: behind (with the behind-marks at the start) or on top
/// (appended, after wrapping the original content in q/Q).
pub(crate) fn place(doc: &mut Document, page: &pdfcraft_model::Page, kind: MarkKind, content: Vec<u8>, behind: bool) -> Result<(), EditError> {
place_tagged(doc, page, kind.tag(), content, behind)?;
pub(crate) fn place(doc: &mut Document, page: &pdfcraft_model::Page, kind: MarkKind, content: Vec<u8>, behind: bool) -> Result<ObjRef, EditError> {
let mark = place_tagged(doc, page, kind.tag(), content, behind)?;
#[cfg(test)]
fail_after_mark_placement(kind)?;
Ok(())
Ok(mark)
}
/// Put a mark's content on a page in the place of the stream at `at` in its `/Contents`: an
/// earlier mark of the same kind, which drew there in the state the content before it leaves, so
/// the new one needs no wrapper and keeps the old one's place among the page's other marks.
pub(crate) fn place_at(doc: &mut Document, page: &pdfcraft_model::Page, at: usize, kind: MarkKind, content: Vec<u8>) -> Result<ObjRef, EditError> {
let mut list = contents(doc, page)?;
let mark_ref = doc.add(Object::Stream(Stream::flate(tagged(kind.tag()), &content)));
let slot = list.get_mut(at).ok_or_else(|| EditError::Invalid("the mark to replace is no longer on the page".into()))?;
*slot = Object::Ref(mark_ref);
doc.update_dict(page.obj, |d| d.set(b"Contents".to_vec(), Object::Array(list)))?;
#[cfg(test)]
fail_after_mark_placement(kind)?;
Ok(mark_ref)
}
#[cfg(test)]
@@ -461,29 +475,43 @@ fn too_deep_on_top() -> EditError {
/// The refusal [`place_tagged`] gives for a mark on top of `page`, checked before an edit changes
/// anything (removing old marks, adding resources) so a refused edit leaves the document as it was.
pub(crate) fn check_on_top(doc: &Document, page: &pdfcraft_model::Page) -> Result<(), EditError> {
let obj = doc.get(page.obj);
let list = match obj.as_dict().and_then(|d| d.get(b"Contents")) {
None => return Ok(()),
Some(Object::Ref(r)) => doc.get(*r).as_array().cloned().unwrap_or_else(|| vec![Object::Ref(*r)]),
Some(Object::Array(a)) => a.clone(),
Some(other) => vec![other.clone()],
};
match isolation(doc, &list) {
match isolation(doc, &content_list(doc, page)) {
Isolation::TooDeep => Err(too_deep_on_top()),
_ => Ok(()),
}
}
/// The streams of a page's /Contents, read without changing the document.
pub(crate) fn content_list(doc: &Document, page: &pdfcraft_model::Page) -> Vec<Object> {
let obj = doc.get(page.obj);
match obj.as_dict().and_then(|d| d.get(b"Contents")) {
None => Vec::new(),
Some(Object::Ref(r)) => doc.get(*r).as_array().cloned().unwrap_or_else(|| vec![Object::Ref(*r)]),
Some(Object::Array(a)) => a.clone(),
Some(other) => vec![other.clone()],
}
}
/// Put content tagged `tag` first inside the q/Q wrapper, so it applies to the page's original
/// content and nothing else (a header's shrink). A page without a wrapper has no original content
/// on it and is left alone.
pub(crate) fn place_inside_wrapper(doc: &mut Document, page: &pdfcraft_model::Page, tag: &str, content: Vec<u8>) -> Result<(), EditError> {
/// on it and is left alone. Returns the new content stream, if one was placed.
pub(crate) fn place_inside_wrapper(
doc: &mut Document,
page: &pdfcraft_model::Page,
tag: &str,
content: Vec<u8>,
) -> Result<Option<ObjRef>, EditError> {
let mut list = contents(doc, page)?;
let Some(open) = list.iter().position(|o| stream_tag(doc, o).as_deref() == Some("Wrap")) else { return Ok(()) };
let stream = Object::Ref(doc.add(Object::Stream(Stream::flate(tagged(tag), &content))));
list.insert(open + 1, stream);
let Some(open) = first_wrapper(doc, &list) else { return Ok(None) };
let stream = doc.add(Object::Stream(Stream::flate(tagged(tag), &content)));
list.insert(open + 1, Object::Ref(stream));
doc.update_dict(page.obj, |d| d.set(b"Contents".to_vec(), Object::Array(list)))?;
Ok(())
Ok(Some(stream))
}
/// The first `Wrap`-tagged stream in `list`, which [`place_inside_wrapper`] puts content after.
pub(crate) fn first_wrapper(doc: &Document, list: &[Object]) -> Option<usize> {
list.iter().position(|o| stream_tag(doc, o).as_deref() == Some("Wrap"))
}
/// Draw `content` on top of a page (0-based) as permanent page content, with standard Helvetica
+257
View File
@@ -302,6 +302,263 @@ fn replace_and_remove_restore_the_original_content() {
assert_eq!(streams(&reopen(&doc), 0), original, "back to exactly the original content");
}
fn with_text(text: &str) -> HeaderFooter {
let mut hf = HeaderFooter::default();
hf.text[1] = text.into();
hf
}
/// #5785: Update could only reach the newest header and footer, and took every other one on
/// those pages with it.
#[test]
fn update_changes_one_header_and_footer_and_leaves_the_others() {
let mut doc = fixture();
let (header, footer) = (with_text("Héader <<1>>"), with_text("Footer"));
add_header_footer(&mut doc, &[0], &header, false, &cx()).unwrap();
add_header_footer(&mut doc, &[0], &footer, false, &cx()).unwrap();
// Listed after a save too, in the document's own words: tokens unexpanded, accents kept.
let doc = &mut reopen(&doc);
let found = header_footers(doc);
assert_eq!(found.iter().map(|m| (&m.settings, &m.pages[..])).collect::<Vec<_>>(), [(&header, &[0][..]), (&footer, &[0][..])]);
// "Héader 1" is drawn with its é as an escape: what follows it is the old header's drawing.
assert!(streams(doc, 0).iter().any(|x| x.contains("ader 1)")), "{:?}", streams(doc, 0));
update_header_footer(doc, &found[0].settings, &[0], &with_text("New"), &cx()).unwrap();
let s = streams(doc, 0);
assert!(s.iter().any(|x| x.contains("(New)")) && s.iter().any(|x| x.contains("(Footer)")), "{s:?}");
assert!(!s.iter().any(|x| x.contains("ader 1)")), "the old header is gone: {s:?}");
assert_eq!(header_footers(doc).len(), 2);
let gone = update_header_footer(doc, &header, &[0], &with_text("Again"), &cx());
assert!(matches!(gone, Err(EditError::Invalid(_))), "{gone:?}");
assert!(streams(doc, 0).iter().any(|x| x.contains("(New)")), "a refused update changes nothing");
}
/// FredApps on #6352: an updated header and footer stays under the ones added after it, where
/// they overlap, as before the update, and its shrink is never taken for its place.
#[test]
fn update_keeps_the_header_and_footer_in_its_place_among_the_others() {
let mut doc = fixture();
let (header, footer) = (HeaderFooter { shrink: true, ..with_text("Under") }, with_text("Over"));
add_header_footer(&mut doc, &[0], &header, false, &cx()).unwrap();
add_header_footer(&mut doc, &[0, 1], &footer, false, &cx()).unwrap();
let at = |doc: &Document, page: usize, text: &str| streams(doc, page).iter().position(|x| x.contains(text));
update_header_footer(&mut doc, &header, &[0, 1], &with_text("New"), &cx()).unwrap();
let s = streams(&doc, 0);
assert!(at(&doc, 0, "(New)") < at(&doc, 0, "(Over)"), "still under the footer added after it: {s:?}");
assert!(!s.iter().any(|x| x.contains("(Under)") || x.trim_end().ends_with(" cm")), "the old one and its shrink are gone: {s:?}");
assert!(at(&doc, 1, "(New)") > at(&doc, 1, "(Over)"), "on a page it was not on, it goes on top");
}
/// Update's preview draws its draft between the two: the page under the header and footer it
/// replaces, and what is drawn over it.
#[test]
fn update_preview_layers_split_the_page_at_the_header_and_footer() {
let mut doc = fixture();
let (old, later) = (with_text("Old"), with_text("Later"));
add_header_footer(&mut doc, &[0], &old, false, &cx()).unwrap();
add_header_footer(&mut doc, &[0, 1], &later, false, &cx()).unwrap();
let original = streams(&fixture(), 0);
let mut under = doc.clone();
assert!(under_header_footer(&mut under, &old).unwrap() > 0);
let s = streams(&under, 0);
assert!(!s.iter().any(|x| x.contains("(Old)") || x.contains("(Later)")), "{s:?}");
assert!(original.iter().all(|o| s.contains(o)), "the page's own content stays: {s:?}");
assert!(streams(&under, 1).iter().any(|x| x.contains("(Later)")), "a page without it is left as it is");
let mut over = doc.clone();
assert_eq!(over_header_footer(&mut over, &old).unwrap(), 1);
let s = streams(&over, 0);
assert!(s.iter().any(|x| x.contains("(Later)")) && !s.iter().any(|x| x.contains("(Old)")), "{s:?}");
assert!(!original.iter().any(|o| s.contains(o)), "nothing under it: {s:?}");
assert!(streams(&over, 1).is_empty(), "where it is not, the new one goes on top");
assert_eq!(over_header_footer(&mut doc.clone(), &later).unwrap(), 0, "nothing is over the newest");
}
#[test]
fn updating_a_shrinking_header_takes_its_shrink_away_too() {
let mut doc = fixture();
let original = streams(&doc, 0);
let shrunk = HeaderFooter { shrink: true, ..with_text("Small") };
add_header_footer(&mut doc, &[0], &shrunk, false, &cx()).unwrap();
update_header_footer(&mut doc, &shrunk, &[0], &with_text("Plain"), &cx()).unwrap();
let s = streams(&doc, 0);
assert_eq!(s.iter().filter(|x| x.contains("/PCMark")).count(), 1);
assert!(original.iter().all(|o| s.contains(o)), "{s:?}");
assert_eq!(s.len(), original.len() + 3, "the original, one wrapper and the new mark: {s:?}");
}
/// A document with one header "Real" on page 1, and that header's stream.
fn one_recorded_header() -> (Document, pdfcraft_cos::ObjRef) {
let mut doc = fixture();
add_header_footer(&mut doc, &[0], &with_text("Real"), false, &cx()).unwrap();
let page = crate::page_list(&doc).swap_remove(0);
let marks: Vec<_> = crate::contents(&mut doc, &page)
.unwrap()
.iter()
.filter_map(Object::as_ref)
.filter(|r| doc.get(*r).as_dict().is_some_and(|d| d.contains(b"PCHeaderFooter")))
.collect();
assert_eq!(marks.len(), 1);
(doc, marks[0])
}
/// A change made to recorded settings, for [`settings_a_file_makes_up_are_not_listed`].
type Change = Box<dyn FnOnce(&mut Document, &mut Dict)>;
/// The recorded settings of `with_text("Real")`, changed by `change`.
fn real_settings_with(doc: &mut Document, change: impl FnOnce(&mut Document, &mut Dict)) -> Object {
let mut d = with_text("Real").to_object().as_dict().cloned().unwrap();
change(doc, &mut d);
Object::Dict(d)
}
#[test]
fn settings_a_file_makes_up_are_not_listed() {
let texts = |entries: Vec<&[u8]>| Object::Array(entries.into_iter().map(|t| Object::String(pdfcraft_cos::PdfString::literal(t))).collect());
let long = vec![b'x'; 16 * 1024 + 1];
let cases: Vec<(&str, Change)> = vec![
("not text", Box::new(|_, d| d.set(b"Text".to_vec(), Object::Array(vec![Object::Int(1); 6])))),
("five boxes", Box::new(move |_, d| d.set(b"Text".to_vec(), texts(vec![&b"a"[..]; 5])))),
("a million boxes", Box::new(|_, d| d.set(b"Text".to_vec(), Object::Array(vec![Object::Null; 1_000_000])))),
("a box too long", Box::new(move |_, d| d.set(b"Text".to_vec(), texts(vec![&b""[..], &long[..], &b""[..], &b""[..], &b""[..], &b""[..]])))),
("no text", Box::new(move |_, d| d.set(b"Text".to_vec(), texts(vec![&b""[..]; 6])))),
("undrawable", Box::new(|_, d| d.set(b"Text".to_vec(), Object::Array(vec![Object::String(pdfcraft_cos::PdfString::text("中")); 6])))),
("size not a number", Box::new(|_, d| d.set(b"Size".to_vec(), Object::Real(f64::NAN)))),
("size too big", Box::new(|_, d| d.set(b"Size".to_vec(), Object::Real(300.0)))),
("a negative margin", Box::new(|_, d| d.set(b"Margins".to_vec(), Object::Array(vec![Object::Real(-1.0); 4])))),
("three margins", Box::new(|_, d| d.set(b"Margins".to_vec(), Object::Array(vec![Object::Real(1.0); 3])))),
("a colour out of range", Box::new(|_, d| d.set(b"Color".to_vec(), Object::Array(vec![Object::Real(2.0); 3])))),
("an unknown face", Box::new(|_, d| d.set(b"Font".to_vec(), Object::name("Comic")))),
("a negative start", Box::new(|_, d| d.set(b"Start".to_vec(), Object::Int(-1)))),
];
for (what, change) in cases {
let (mut doc, mark) = one_recorded_header();
let hostile = real_settings_with(&mut doc, change);
doc.update_dict(mark, |d| d.set(b"PCHeaderFooter".to_vec(), hostile)).unwrap();
assert!(header_footers(&doc).is_empty(), "{what}");
assert_eq!(marks_present(&doc), [MarkKind::HeaderFooter], "{what}: still a mark: Remove and page-wide Update reach it");
assert_eq!(unrecorded_header_footer_pages(&doc), [0], "{what}");
assert_eq!(newest_header_footer(&doc, 0), Some(None), "{what}");
}
}
/// #6352 review: listing read a header's settings again for every stream that recorded them, so a
/// file repeating one shared entry (or one stream) across its pages could make it slow. A scan now
/// reads each stream and each settings entry given by reference once, and still finds every page.
#[test]
fn settings_shared_by_many_streams_are_read_once_in_a_scan() {
let (mut doc, mark) = one_recorded_header();
let settings = doc.get(mark).as_dict().unwrap().get(b"PCHeaderFooter").cloned().unwrap();
let shared = Object::Ref(doc.add(settings));
doc.update_dict(mark, |d| d.set(b"PCHeaderFooter".to_vec(), shared)).unwrap();
let Object::Stream(copy) = (*doc.get(mark)).clone() else { panic!("a stream") };
// Page 0 draws the header's own stream 500 times; page 1 has 200 streams of its own, each
// recording the same settings by reference.
let mut first = vec![Object::Ref(pdfcraft_cos::ObjRef::new(7, 0))];
first.extend(std::iter::repeat_n(Object::Ref(mark), 500));
let mut second = vec![Object::Ref(pdfcraft_cos::ObjRef::new(7, 0))];
second.extend((0..200).map(|_| Object::Ref(doc.add(Object::Stream(copy.clone())))));
doc.update_dict(pdfcraft_cos::ObjRef::new(3, 0), |d| d.set(b"Contents".to_vec(), Object::Array(first))).unwrap();
doc.update_dict(pdfcraft_cos::ObjRef::new(4, 0), |d| d.set(b"Contents".to_vec(), Object::Array(second))).unwrap();
crate::marks::DECODED.with(|n| n.set(0));
let found = header_footers(&doc);
assert_eq!(crate::marks::DECODED.with(std::cell::Cell::get), 1, "the shared entry is read once");
assert_eq!(found.len(), 1);
assert_eq!((found[0].pages.as_slice(), found[0].settings.text[1].as_str()), (&[0, 1][..], "Real"));
assert!(unrecorded_header_footer_pages(&doc).is_empty());
}
/// #6352 review: past the scan's text budget, settings went unread like a header that records
/// none, so a header and footer listed itself on only the pages before that, and Update removed
/// it from those alone. Update now refuses instead, and the unread ones are not offered as older.
#[test]
fn update_refuses_when_the_scan_cannot_find_every_page_of_a_header() {
let (mut doc, mark) = one_recorded_header();
let pages = crate::page_list(&doc);
let Object::Stream(real) = (*doc.get(mark)).clone() else { panic!("a stream") };
// Page 0: the real header, then 200 others recording 96 KiB of text each, past the budget.
let big = HeaderFooter { text: std::array::from_fn(|_| "x".repeat(16 * 1024)), ..HeaderFooter::default() };
let mut heavy = real.clone();
heavy.dict.set(b"PCHeaderFooter".to_vec(), big.to_object());
let mut first = crate::contents(&mut doc, &pages[0]).unwrap();
first.extend((0..200).map(|_| Object::Ref(doc.add(Object::Stream(heavy.clone())))));
// Page 1: the real header again, in a stream of its own, which the scan no longer reads.
let mut second = crate::contents(&mut doc, &pages[1]).unwrap();
second.push(Object::Ref(doc.add(Object::Stream(real))));
let page_refs: Vec<_> = pages.iter().map(|p| p.obj).collect();
doc.update_dict(page_refs[0], |d| d.set(b"Contents".to_vec(), Object::Array(first.clone()))).unwrap();
doc.update_dict(page_refs[1], |d| d.set(b"Contents".to_vec(), Object::Array(second.clone()))).unwrap();
let real = with_text("Real");
let listed = header_footers(&doc);
assert_eq!(listed.iter().find(|m| m.settings == real).map(|m| m.pages.as_slice()), Some(&[0][..]), "the scan stops short");
assert!(unrecorded_header_footer_pages(&doc).is_empty(), "settings it did not read are not offered as older ones");
assert!(matches!(remove_header_footer(&mut doc, &real), Err(EditError::Invalid(_))));
assert!(matches!(update_header_footer(&mut doc, &real, &[0], &with_text("New"), &cx()), Err(EditError::Invalid(_))));
assert_eq!(crate::contents(&mut doc, &pages[0]).unwrap(), first, "page 0 is as it was");
assert_eq!(crate::contents(&mut doc, &pages[1]).unwrap(), second, "and the header stays on page 1");
}
#[test]
fn settings_a_rewriting_tool_made_indirect_are_still_listed() {
let (mut doc, mark) = one_recorded_header();
let indirect = real_settings_with(&mut doc, |doc, d| {
for key in [&b"Font"[..], b"Size", b"Start", b"Underline", b"Text"] {
let value = d.get(key).cloned().unwrap();
d.set(key.to_vec(), Object::Ref(doc.add(value)));
}
let half = Object::Ref(doc.add(Object::Real(0.5)));
d.set(b"Color".to_vec(), Object::Array(vec![half.clone(), half.clone(), half]));
let margins = Object::Array(vec![Object::Ref(doc.add(Object::Real(36.0))), Object::Real(36.0), Object::Real(72.0), Object::Real(72.0)]);
d.set(b"Margins".to_vec(), Object::Ref(doc.add(margins)));
});
doc.update_dict(mark, |d| d.set(b"PCHeaderFooter".to_vec(), indirect)).unwrap();
let found = header_footers(&doc);
assert_eq!(found.len(), 1);
assert_eq!(found[0].settings, HeaderFooter { color: [0.5; 3], ..with_text("Real") });
assert!(unrecorded_header_footer_pages(&doc).is_empty());
}
#[test]
fn a_header_too_long_to_be_listed_is_not_added() {
// Every header add accepts is one the listing can name, so Update never has to fall back to
// replacing it page-wide.
let mut doc = fixture();
let too_long = with_text(&"x".repeat(16 * 1024 + 1));
assert!(matches!(add_header_footer(&mut doc, &[0], &too_long, false, &cx()), Err(EditError::Invalid(_))));
assert!(marks_present(&doc).is_empty(), "nothing drawn");
let longest = with_text(&"x".repeat(16 * 1024));
add_header_footer(&mut doc, &[0], &longest, false, &cx()).unwrap();
assert_eq!(header_footers(&doc).len(), 1, "the longest box add accepts is listed");
}
#[test]
fn a_header_added_with_an_out_of_range_colour_can_be_updated() {
let mut doc = fixture();
let bright = HeaderFooter { color: [2.0, -1.0, 0.5], ..with_text("Bright") };
add_header_footer(&mut doc, &[0], &bright, false, &cx()).unwrap();
let found = header_footers(&doc);
assert_eq!(found.len(), 1, "listed with the colour it is drawn in");
assert_eq!(found[0].settings.color, [1.0, 0.0, 0.5]);
update_header_footer(&mut doc, &found[0].settings, &[0], &with_text("Calm"), &cx()).unwrap();
assert_eq!(header_footers(&doc).iter().map(|m| m.settings.text[1].as_str()).collect::<Vec<_>>(), ["Calm"]);
}
#[test]
fn the_newest_header_on_a_page_is_the_one_added_last() {
let mut doc = fixture();
assert_eq!(newest_header_footer(&doc, 0), None);
let (first, second) = (HeaderFooter { shrink: true, ..with_text("First") }, HeaderFooter { shrink: true, ..with_text("Second") });
add_header_footer(&mut doc, &[0, 1], &first, false, &cx()).unwrap();
add_header_footer(&mut doc, &[0], &second, false, &cx()).unwrap();
// The second shrink goes in ahead of the first, so content order alone would say First.
assert_eq!(newest_header_footer(&doc, 0), Some(Some(second)));
assert_eq!(newest_header_footer(&doc, 1), Some(Some(first)));
assert_eq!(newest_header_footer(&doc, 9), None);
}
/// The six numbers of the first `… cm` in `content`.
fn first_cm(content: &str) -> [f64; 6] {
let line = content.lines().find(|l| l.ends_with(" cm")).unwrap_or_else(|| panic!("no cm in {content:?}"));
+1 -1
View File
@@ -69,7 +69,7 @@ pub(crate) use lines::{
ContentStream, FormBudget, Read, content_streams, content_streams_within, dict_in_place, drawn_before_damage, dropped_advances,
dropped_side_effects, first_op_after_damage, form_call, joined, reopen_text_object, resource_dict, rewritten_contents, splice,
};
pub use lines::{MAX_FORM_DEPTH, MAX_FORM_VISITS, glyph_text_lines, text_lines};
pub use lines::{MAX_FORM_DEPTH, MAX_FORM_VISITS, glyph_text_lines, glyph_text_lines_with_blank_clips, text_lines};
use lines::{page_dict, word_lines};
pub use rewrite::{LineEdit, replace_line, rewrite_block};
use rewrite::{coincident_ops, rewrite_block_from};
+7
View File
@@ -449,6 +449,8 @@ pub(super) struct Shown {
pub(super) extra_ops: Vec<usize>,
/// Encoded glyphs, not bytes or Unicode characters (a ligature can represent several).
pub(super) glyph_count: usize,
/// A glyph has an outline, or its font could not establish that it is empty.
pub(super) may_draw_outline: bool,
/// Advance in text space, including spacing and TJ adjustments.
pub(super) advance: f64,
pub(super) tracking: f64,
@@ -819,11 +821,15 @@ fn show_text(op: &Op, i: usize, state: &mut TextRunState<'_>) -> Result<(), Edit
// before may have ended in one: a justified line can be split over `TJ` and `Tj`.
let mut gap_space = std::mem::take(&mut carry.gap_space);
let mut glyph_count = 0_usize;
let mut may_draw_outline = false;
for p in &pieces {
match p {
Object::String(s) => {
for (code, len) in m.codes(&s.bytes) {
glyph_count = glyph_count.saturating_add(1);
if (4..=7).contains(&ts.render_mode) && ts.size != 0.0 && ts.scale != 0.0 {
may_draw_outline |= m.past_allowance || m.codespaces_dropped || m.has_outline(code) != Some(false);
}
let shown = m.text_of(code);
let blank = m.is_space(code, len) || shown.as_deref().is_some_and(|t| !t.is_empty() && t.chars().all(char::is_whitespace));
// A space glyph right after a gap that read as a space is that space:
@@ -942,6 +948,7 @@ fn show_text(op: &Op, i: usize, state: &mut TextRunState<'_>) -> Result<(), Edit
op: i,
extra_ops: Vec::new(),
glyph_count,
may_draw_outline,
// Vertical text: the TJ adjustment that undoes the run is n = -1000 y / size; the
// preview divides by size × `Tz`, so `Tz` is put back here.
advance: if vertical.is_some() { y_text * ts.scale } else { x_text },
+32 -4
View File
@@ -19,6 +19,16 @@ impl TextLine {
(self.stream, self.ops.iter().min().copied().unwrap_or(0))
}
/// Whether all the line's drawing operators are inside one text object in the joined
/// page stream. A line can join runs from several text objects.
pub fn drawn_within(&self, operators: &std::ops::Range<usize>) -> bool {
if self.actual_text {
return !self.ops.is_empty() && self.ops.iter().all(|op| operators.contains(op));
}
// Glyph shows are appended in stream order.
self.ops.first().zip(self.ops.last()).is_some_and(|(first, last)| operators.contains(first) && operators.contains(last))
}
/// The runs of text the line joins, in content order: each run's text as its glyphs show it,
/// the boxes of its words (a part of `ink`), and whether joining put a space between it and
/// the run before (`text` has one there; runs closer together join with none, so one word
@@ -431,13 +441,13 @@ fn fill_color(fill: &[Op]) -> [f64; 3] {
/// The lines of text on a page (0-based), in content order.
pub fn text_lines(doc: &Document, page: usize) -> Result<Vec<TextLine>, EditError> {
text_lines_in(doc, &page_dict(doc, page)?, true, false)
text_lines_in(doc, &page_dict(doc, page)?, true, false, None)
}
/// [`text_lines`] with every show of invisible text a line of its own, however alike its
/// neighbours: an OCR layer's words, which an edit can keep or change one by one.
pub(crate) fn word_lines(doc: &Document, page: usize) -> Result<Vec<TextLine>, EditError> {
text_lines_in(doc, &page_dict(doc, page)?, true, true)
text_lines_in(doc, &page_dict(doc, page)?, true, true, None)
}
/// The lines `page`'s glyphs show, in content order, without `/ActualText` replacements: what the
@@ -445,12 +455,27 @@ pub(crate) fn word_lines(doc: &Document, page: usize) -> Result<Vec<TextLine>, E
/// not trust that metadata (the redaction audit). Takes the page itself, so a caller going
/// through every page doesn't walk the page tree again for each.
pub fn glyph_text_lines(doc: &Document, page: &pdfcraft_model::Page) -> Result<Vec<TextLine>, EditError> {
text_lines_in(doc, page, false, false)
text_lines_in(doc, page, false, false, None)
}
/// Extracts the glyph lines and records text-clipping shows whose glyphs have no outlines.
pub fn glyph_text_lines_with_blank_clips(
doc: &Document,
page: &pdfcraft_model::Page,
blank_clips: &mut std::collections::HashSet<usize>,
) -> Result<Vec<TextLine>, EditError> {
text_lines_in(doc, page, false, false, Some(blank_clips))
}
/// [`text_lines`] of `p`; with `actual_text`, `/ActualText` replaces the glyphs it spans, and with
/// `invisible_apart`, no show of invisible text joins the one before it.
fn text_lines_in(doc: &Document, p: &pdfcraft_model::Page, actual_text: bool, invisible_apart: bool) -> Result<Vec<TextLine>, EditError> {
fn text_lines_in(
doc: &Document,
p: &pdfcraft_model::Page,
actual_text: bool,
invisible_apart: bool,
blank_clips: Option<&mut std::collections::HashSet<usize>>,
) -> Result<Vec<TextLine>, EditError> {
let res = p.dict.get(b"Resources").map(|r| doc.resolve(r)).and_then(|r| r.as_dict().cloned()).unwrap_or_default();
let mut cache = HashMap::new();
let mut lines: Vec<TextLine> = Vec::new();
@@ -462,6 +487,9 @@ fn text_lines_in(doc: &Document, p: &pdfcraft_model::Page, actual_text: bool, in
let properties = res.get(b"Properties").and_then(|o| doc.dict(o)).unwrap_or_default();
carry.containers = std::rc::Rc::new(super::containers::Containers::collect(doc, &ops, &res));
let shown = interpret(doc, &ops, &res, &mut cache, &mut carry, None, actual_text.then_some(&properties))?;
if let Some(blank_clips) = blank_clips {
blank_clips.extend(shown.iter().filter(|s| (4..=7).contains(&s.state.render_mode) && !s.may_draw_outline).map(|s| s.op));
}
let mut last: Option<(usize, Pen)> = None; // the stream piece and where its last run ended
for mut s in shown {
// A single RTL glyph's ActualText (e.g. lam-alef) is an inline ligature, not a
+1 -1
View File
@@ -46,7 +46,7 @@ impl Document {
self.page_images(page).iter().rposition(|i| {
i.contains(at)
&& match (i.is_form, i.object) {
(false, Some(_)) => true,
(false, Some(_)) => self.image_shows_at(i, at),
(true, Some(form)) => picture_in_form(&editor.cos, form).is_some(),
_ => false,
}
+6 -1
View File
@@ -34,9 +34,14 @@ pub enum ImageEdit {
/// Forms ▸ Merge data files into spreadsheet: the field values of each file (FDF, XFDF or a
/// filled-in PDF form), as CSV with one row per file.
pub fn merge_data_files(files: &[(String, Vec<u8>)]) -> Result<String, String> {
merge_data_files_with_columns(files).map(|(csv, _)| csv)
}
/// Merge the files to CSV and report the distinct field count.
pub fn merge_data_files_with_columns(files: &[(String, Vec<u8>)]) -> Result<(String, usize), String> {
let rows =
files.iter().map(|(name, bytes)| pdfcraft_xfdf::data_values(bytes).map_err(|e| format!("{name}: {e}"))).collect::<Result<Vec<_>, _>>()?;
Ok(pdfcraft_xfdf::merge_csv(&rows))
Ok(pdfcraft_xfdf::merge_csv_with_columns(&rows))
}
/// One file produced by a split: (1-based first page, last page, PDF bytes).
+21
View File
@@ -65,6 +65,10 @@ pub struct Document {
/// since they last gained focus: their exit on losing focus has run already
/// ([`Session::field_focus`]).
pub(crate) xfa_exited: std::collections::HashSet<String>,
/// An XFA button click run on a worker ([`Session::start_javascript_target`]) had a script
/// run away: the next edit turns the form's scripts off, as it would have had the click been
/// kept (it may have been dropped: the document changed, or the app stopped waiting).
pub(crate) xfa_ran_away: std::sync::Arc<std::sync::atomic::AtomicBool>,
/// A content-only refresh keeps `info` from before the edit; an edit may have added or
/// embedded fonts, so the font list is read again on demand ([`Session::refresh_fonts`]).
pub(crate) fonts_stale: bool,
@@ -76,6 +80,8 @@ pub struct Document {
/// applied redactions left that still hold the removed text. The interface shows it; tools
/// return it.
pub edit_notices: Vec<EditNotice>,
/// Which parts of pictures with transparency show, for picking them ([`Document::image_shows_at`]).
pub(crate) alpha: crate::image_alpha::AlphaCache,
}
/// Something the last successful edit did that the user should hear about, never left silent
@@ -616,6 +622,21 @@ impl Document {
.marks
}
/// The headers and footers Update can tell apart (`pdfcraft_edit::header_footers`).
pub fn header_footers(&self) -> Vec<pdfcraft_edit::HeaderFooterMark> {
self.editor.as_ref().map(|e| pdfcraft_edit::header_footers(&e.cos)).unwrap_or_default()
}
/// The header and footer added last to page `page` (`pdfcraft_edit::newest_header_footer`).
pub fn newest_header_footer(&self, page: usize) -> Option<Option<pdfcraft_edit::HeaderFooter>> {
self.editor.as_ref().and_then(|e| pdfcraft_edit::newest_header_footer(&e.cos, page))
}
/// Pages whose header and footer records no settings (`pdfcraft_edit::unrecorded_header_footer_pages`).
pub fn unrecorded_header_footer_pages(&self) -> Vec<usize> {
self.editor.as_ref().map(|e| pdfcraft_edit::unrecorded_header_footer_pages(&e.cos)).unwrap_or_default()
}
/// Text and images added with Edit a PDF ▸ Add content (still editable).
pub fn added(&self) -> &[pdfcraft_edit::Added] {
&self
+7
View File
@@ -556,6 +556,13 @@ pub enum Edit {
settings: HeaderFooter,
replace: bool,
},
/// Update one header and footer: `old` (settings from `Document::header_footers`) goes from
/// every page it is on and `settings` is added to `pages`. Others stay.
UpdateHeaderFooter {
old: HeaderFooter,
pages: Vec<usize>,
settings: HeaderFooter,
},
/// `file`: a picture from a file (an image, or a page of a PDF) instead of text.
AddWatermark {
pages: Vec<usize>,
+1 -1
View File
@@ -316,7 +316,7 @@ impl Edit {
ImageEdit::Ungroup => "Ungroup artwork",
}),
Edit::AddHeaderFooter { replace: false, .. } => Label::of("Add header & footer"),
Edit::AddHeaderFooter { .. } => Label::of("Update header & footer"),
Edit::AddHeaderFooter { .. } | Edit::UpdateHeaderFooter { .. } => Label::of("Update header & footer"),
Edit::AddWatermark { replace: false, .. } => Label::of("Add watermark"),
Edit::AddWatermark { .. } => Label::of("Update watermark"),
Edit::AddBackground { replace: false, .. } => Label::of("Add background"),
+9
View File
@@ -110,6 +110,7 @@ pub(crate) fn check_permission(edit: &Edit, p: &pdfcraft_cos::Permissions) -> Re
}
Edit::SetInfo { .. }
| Edit::AddHeaderFooter { .. }
| Edit::UpdateHeaderFooter { .. }
| Edit::AddPrinterMarks { .. }
| Edit::AddWatermark { .. }
| Edit::AddBackground { .. }
@@ -260,6 +261,8 @@ pub(crate) struct EditCtx {
pub(crate) xfa_unchanged: bool,
/// What the XFA scripts' time limits are multiplied by ([`Session::with_xfa_time_scale`]).
pub(crate) xfa_time_scale: u32,
/// The answers the edit's XFA event takes ([`Session::xfa_answers`](crate::Session)).
pub(crate) xfa_answers: xfa::XfaAnswers,
/// The form's scripts or new data laid it out again: its pages and widgets were replaced.
pub(crate) xfa_relaid: bool,
/// The edit took the XFA out of the form: what went with it, for the document's warnings.
@@ -333,6 +336,7 @@ impl EditCtx {
xfa_ran_away: false,
xfa_unchanged: false,
xfa_time_scale: 1,
xfa_answers: Default::default(),
xfa_relaid: false,
xfa_removed: Vec::new(),
pages: 0,
@@ -794,6 +798,7 @@ pub(crate) fn run_edit(doc: &mut pdfcraft_cos::Document, edit: &Edit, cx: &mut E
ran_away: false,
highlight,
time_scale: cx.xfa_time_scale,
answers: std::mem::take(&mut cx.xfa_answers),
relaid: false,
};
let ran = if matches!(activity.as_str(), "enter" | "exit") {
@@ -971,6 +976,10 @@ pub(crate) fn run_edit(doc: &mut pdfcraft_cos::Document, edit: &Edit, cx: &mut E
let date = cx.today;
pdfcraft_edit::add_header_footer(doc, pages, settings, *replace, &pdfcraft_edit::Context { date })?;
}
Edit::UpdateHeaderFooter { old, pages, settings } => {
let date = cx.today;
pdfcraft_edit::update_header_footer(doc, old, pages, settings, &pdfcraft_edit::Context { date })?;
}
Edit::AddWatermark { pages, settings, replace, file } => {
let mut s = settings.clone();
if let Some(f) = file {
+9
View File
@@ -78,3 +78,12 @@ impl From<pdfcraft_sign::SignError> for EditError {
EditError::Sign(e.to_string())
}
}
impl EditError {
/// A field's validate action refused the value it was given (ISO 32000-2 Table 199 `/V`).
/// The document is unchanged and the field keeps its value; an interface drops the typing
/// rather than holding the user in the field.
pub fn is_rejected_value(&self) -> bool {
matches!(self, EditError::Form(pdfcraft_forms::FormError::Rejected(_)))
}
}
+1
View File
@@ -103,6 +103,7 @@ pub(crate) fn scope_of(edit: &Edit) -> Scope {
| Edit::PasteContent { .. }
| Edit::PasteObjects { .. }
| Edit::AddHeaderFooter { .. }
| Edit::UpdateHeaderFooter { .. }
| Edit::AddWatermark { .. }
| Edit::AddBackground { .. }
| Edit::RemoveMarks { .. }
+257
View File
@@ -0,0 +1,257 @@
//! Edit text & images: a picture is picked where it shows, not across its whole box. A PNG
//! signature or a cut-out photo with a transparent margin overlaps its neighbours; clicking a
//! neighbour through that margin picked the transparent picture on top.
//!
//! A picture with transparency (a soft mask, a stencil or colour-key `/Mask`, or a stencil image
//! `/ImageMask`) gets an opacity grid of at most [`MAX_GRID`] cells a side, built once from its
//! pixels and kept until the document changes. A cell counts as opaque if any pixel
//! in it is: thin strokes and the edges of a shape stay easy to pick. Pictures without
//! transparency, Form artwork, pictures that show nowhere and pictures that can't be decoded
//! keep their whole box.
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use pdfcraft_cos::{ObjRef, Object};
use crate::Document;
/// The opacity grid's largest side, in cells.
const MAX_GRID: u32 = 256;
/// Grids kept at once (at most 64 KiB each); past this the cache starts over.
const MAX_CACHED: usize = 256;
/// Pictures larger than this many pixels keep their whole box rather than being decoded.
const MAX_DECODE_PIXELS: u64 = 64_000_000;
/// Alpha at or above this (of 255) counts as showing.
const OPAQUE: u8 = 16;
/// Colour components assumed for a colour space that can't be read: as many as a DeviceN space
/// may have in practice, so the decoding bound stays generous.
const MAX_COMPONENTS: u64 = 32;
/// Decoded bytes allowed past what a picture's declared size needs (with a quarter more), for
/// padding writers leave after the samples.
const DECODE_SLACK: u64 = 64 << 10;
/// Which cells of a picture show, row 0 at the top of the picture.
#[derive(Debug)]
pub(crate) struct Opacity {
width: u32,
height: u32,
cells: Vec<bool>,
}
/// Opacity grids by picture object, for the document generation they were built at; `None` for
/// a picture that is opaque everywhere, shows nowhere or couldn't be read (its whole box counts). The
/// generation, not the picture object alone, says when to rebuild: an edit may change the
/// picture's soft mask without touching the picture.
type Grids = (u64, HashMap<ObjRef, Option<Arc<Opacity>>>);
#[derive(Default)]
pub(crate) struct AlphaCache(Mutex<Grids>);
impl Document {
/// Whether `image` shows at user-space `point` (assumed inside its placement): `false` only
/// where a picture with transparency is see-through. Form artwork, pictures without
/// transparency and pictures that can't be read show everywhere in their box.
pub fn image_shows_at(&self, image: &pdfcraft_edit::PageImage, point: [f64; 2]) -> bool {
if image.is_form {
return true;
}
let Some(object) = image.object else { return true };
let Some(grid) = self.opacity(object) else { return true };
let Some((x, y)) = unit_point(image.matrix, point) else { return true };
if !(0.0..=1.0).contains(&x) || !(0.0..=1.0).contains(&y) {
return true;
}
// Image space: row 0 is the top of the unit square (y = 1).
let col = ((x * f64::from(grid.width)) as u32).min(grid.width.saturating_sub(1));
let row = (((1.0 - y) * f64::from(grid.height)) as u32).min(grid.height.saturating_sub(1));
let at = usize::try_from(u64::from(row) * u64::from(grid.width) + u64::from(col)).unwrap_or(usize::MAX);
grid.cells.get(at).copied().unwrap_or(true)
}
/// The opacity grid of picture `object`, built on first use and kept until the document
/// changes.
fn opacity(&self, object: ObjRef) -> Option<Arc<Opacity>> {
let editor = self.editor.as_ref()?;
// A poisoned cache is only a cache: build without it.
if let Ok(cache) = self.alpha.0.lock()
&& cache.0 == self.generation
&& let Some(grid) = cache.1.get(&object)
{
return grid.clone();
}
let grid = build(&editor.cos, object).map(Arc::new);
if let Ok(mut cache) = self.alpha.0.lock() {
if cache.0 != self.generation || cache.1.len() >= MAX_CACHED {
*cache = (self.generation, HashMap::new());
}
cache.1.insert(object, grid.clone());
}
grid
}
}
/// The picture's opacity grid, or `None` when it is opaque everywhere or can't be read.
fn build(cos: &pdfcraft_cos::Document, object: ObjRef) -> Option<Opacity> {
let current = cos.get(object);
let Object::Stream(s) = &*current else { return None };
let stencil = flag(cos, s, b"ImageMask");
let soft = s.dict.get(b"SMask").is_some_and(|v| cos.resolve(v).as_name() != Some(b"None"));
let in_data = s.dict.int(b"SMaskInData").is_some_and(|v| v != 0);
if !(stencil || soft || in_data || s.dict.get(b"Mask").is_some()) {
return None;
}
// The picture and the mask images it brings are decoded in full before anything is scaled
// down to the picture's size, so each must be small enough, in pixels and in decoded bytes,
// before any of it is decoded.
// One decoding allowance for the picture and its masks (`ImageBudget`), however many there are.
let mut budget = pdfcraft_cos::ImageBudget::new(cos);
let components = if stencil { 1 } else { components(cos, s.dict.get(b"ColorSpace")) };
if !within_budget(cos, &mut budget, s, components, stencil) {
return None;
}
for key in [&b"SMask"[..], b"Mask"] {
if let Some(Object::Stream(mask)) = s.dict.get(key).map(|v| cos.resolve(v)).as_deref()
&& !within_budget(cos, &mut budget, mask, 1, key == b"Mask" || flag(cos, mask, b"ImageMask"))
{
return None;
}
}
let (_, bytes) = pdfcraft_create::image_file_within(cos, object, &mut budget).ok()?;
let format = image::guess_format(&bytes).ok()?;
let mut reader = image::ImageReader::with_format(std::io::Cursor::new(bytes.as_slice()), format);
let mut limits = image::Limits::default();
limits.max_alloc = Some(MAX_DECODE_PIXELS.saturating_mul(4));
reader.limits(limits);
let picture = reader.decode().ok()?;
let (w, h) = (picture.width(), picture.height());
if w == 0 || h == 0 {
return None;
}
let shows: Box<dyn Fn(u32, u32) -> bool> = if picture.color().has_alpha() {
let rgba = picture.into_rgba8();
Box::new(move |x, y| rgba.get_pixel_checked(x, y).is_none_or(|p| p.0[3] >= OPAQUE))
} else if stencil {
// The export draws a stencil image's painted samples white, whatever its `/Decode`.
let luma = picture.into_luma8();
Box::new(move |x, y| luma.get_pixel_checked(x, y).is_none_or(|p| p.0[0] >= 128))
} else {
return None;
};
let (gw, gh) = (w.min(MAX_GRID), h.min(MAX_GRID));
let mut cells = vec![false; usize::try_from(u64::from(gw) * u64::from(gh)).ok()?];
for y in 0..h {
let rows = cells_covered(y, h, gh);
for x in 0..w {
if shows(x, y) {
// Every cell the pixel reaches into shows: a point anywhere on a showing pixel
// picks the picture, also where the pixel crosses into the next cell.
for row in rows.clone() {
for col in cells_covered(x, w, gw) {
if let Some(cell) = usize::try_from(row * u64::from(gw) + col).ok().and_then(|i| cells.get_mut(i)) {
*cell = true;
}
}
}
}
}
}
// A picture that shows everywhere, or nowhere (a faint watermark, a transparent
// placeholder), keeps its whole box: one that showed nowhere couldn't be picked at all.
if cells.iter().all(|c| *c) || !cells.iter().any(|c| *c) {
return None;
}
Some(Opacity { width: gw, height: gh, cells })
}
/// The grid cells, along an axis of `pixels` pixels and `cells` cells, that pixel `i` reaches
/// into: from the cell its start is in to the cell its end is in. `cells` is at most `pixels`, so
/// a pixel reaches into at most two.
fn cells_covered(i: u32, pixels: u32, cells: u32) -> std::ops::Range<u64> {
let (i, pixels, cells) = (u64::from(i), u64::from(pixels).max(1), u64::from(cells));
let start = i * cells / pixels;
let end = ((i + 1) * cells).div_ceil(pixels).min(cells);
start..end.max(start)
}
/// Whether the boolean `key` of image stream `s` is `true`.
fn flag(cos: &pdfcraft_cos::Document, s: &pdfcraft_cos::Stream, key: &[u8]) -> bool {
s.dict.get(key).is_some_and(|v| matches!(&*cos.resolve(v), Object::Bool(true)))
}
/// Whether image stream `s`, of `components` colour components (one bit each for a `stencil`),
/// is small enough to decode for its opacity grid: at most [`MAX_DECODE_PIXELS`] pixels and, when
/// its samples are decoded through its filters, no more decoded bytes than its declared size
/// needs, with room for padding a writer left after the samples. Without that bound a 1 × 1
/// picture whose stream inflates to a gigabyte would be decoded in full on the first hover. JPEG,
/// JPEG 2000 and JBIG2 data go to their own decoders instead. The decode is charged to
/// `allowance`, the picture's shared [`ImageBudget`](pdfcraft_cos::ImageBudget).
fn within_budget(
cos: &pdfcraft_cos::Document,
allowance: &mut pdfcraft_cos::ImageBudget,
s: &pdfcraft_cos::Stream,
components: u64,
stencil: bool,
) -> bool {
let size = |key: &[u8]| u64::try_from(s.dict.int(key).unwrap_or(0)).unwrap_or(0);
let (w, h) = (size(b"Width"), size(b"Height"));
if w.saturating_mul(h) > MAX_DECODE_PIXELS {
return false;
}
let codec = match s.dict.get(b"Filter").map(|f| cos.resolve(f)).as_deref() {
Some(Object::Name(n)) => Some(n.clone()),
Some(Object::Array(a)) => a.last().and_then(Object::as_name).map(<[u8]>::to_vec),
_ => None,
};
if matches!(codec.as_deref(), Some(b"DCTDecode" | b"DCT" | b"JPXDecode" | b"JBIG2Decode")) {
return true;
}
let bpc = if stencil { 1 } else { u64::try_from(s.dict.int(b"BitsPerComponent").unwrap_or(8)).unwrap_or(8).clamp(1, 16) };
let row = w.checked_mul(components).and_then(|n| n.checked_mul(bpc)).map(|bits| bits.div_ceil(8));
let budget = row.and_then(|r| r.checked_mul(h)).and_then(|n| n.checked_add(n / 4)).and_then(|n| n.checked_add(DECODE_SLACK));
let Some(budget) = budget.and_then(|n| usize::try_from(n).ok()) else { return false };
allowance.decode(cos, s, budget).is_ok()
}
/// The colour components of an image in colour space `space` (ISO 32000-2 §8.6): one for an
/// indexed or separation space, the `/N` of an ICC-based one, as many as a DeviceN space names.
/// A space that can't be read counts as [`MAX_COMPONENTS`], which keeps the decoding bound
/// generous rather than refusing the picture.
fn components(cos: &pdfcraft_cos::Document, space: Option<&Object>) -> u64 {
let Some(space) = space.map(|s| cos.resolve(s)) else { return MAX_COMPONENTS };
let array = space.as_array();
let family = match (&*space, array.and_then(|a| a.first()).and_then(Object::as_name)) {
(Object::Name(n), _) => n.as_slice(),
(_, Some(n)) => n,
_ => return MAX_COMPONENTS,
};
let operand = || array.and_then(|a| a.get(1)).map(|o| cos.resolve(o));
match family {
b"DeviceGray" | b"G" | b"CalGray" | b"Indexed" | b"I" | b"Separation" => 1,
b"DeviceRGB" | b"RGB" | b"CalRGB" | b"Lab" => 3,
b"DeviceCMYK" | b"CMYK" => 4,
b"ICCBased" => match operand().as_deref() {
Some(Object::Stream(icc)) => {
icc.dict.int(b"N").and_then(|n| u64::try_from(n).ok()).filter(|n| (1..=MAX_COMPONENTS).contains(n)).unwrap_or(MAX_COMPONENTS)
}
_ => MAX_COMPONENTS,
},
b"DeviceN" => match operand().as_deref() {
Some(Object::Array(names)) => u64::try_from(names.len()).unwrap_or(MAX_COMPONENTS).clamp(1, MAX_COMPONENTS),
_ => MAX_COMPONENTS,
},
_ => MAX_COMPONENTS,
}
}
/// `point` in the placement's unit square: the inverse of `matrix` applied to it.
fn unit_point(m: [f64; 6], point: [f64; 2]) -> Option<(f64, f64)> {
let det = m[0] * m[3] - m[1] * m[2];
if !det.is_finite() || det.abs() < 1e-12 {
return None;
}
let (dx, dy) = (point[0] - m[4], point[1] - m[5]);
let x = (m[3] * dx - m[2] * dy) / det;
let y = (m[0] * dy - m[1] * dx) / det;
(x.is_finite() && y.is_finite()).then_some((x, y))
}
+143 -20
View File
@@ -1193,24 +1193,18 @@ impl Session {
let doc = self.get(id).ok_or(EditError::NoDocument)?;
let cos = doc.editor.as_ref().map(|e| e.cos.clone()).ok_or_else(|| EditError::ReadOnly(doc.read_only_reason.clone().unwrap_or_default()))?;
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
&& let Some(som) = crate::xfa::clickable_som(&cos, &tpl, field)
// A button PdfCraft generated from an XFA template runs its XFA click script, its
// message boxes taking `answers` (then their buttons' safe default: nobody is asked).
if event_name.is_none_or(|n| n == "Mouse Up")
&& let Some(som) = xfa_click_som(doc, &cos, target, target_id)
{
self.xfa_answers = Some(crate::xfa::XfaAnswers { given: answers.to_vec(), ..Default::default() });
// The click returns only the output of its own edit; output from opening or from earlier edits stays.
let ((), out) = self.with_own_js_output(id, |s| s.apply(id, Edit::XfaEvent { som, activity: "click".into() }))?;
return Ok(Outcome {
rc: true,
alerts: out.alerts,
console: out.console,
requests: out.requests,
error: out.errors.first().cloned(),
..Default::default()
});
let ran = self.with_own_js_output(id, |s| s.apply(id, Edit::XfaEvent { som, activity: "click".into() }));
// Not taken when the edit stopped before it ran the event: no later edit takes it.
self.xfa_answers = None;
let ((), out) = ran?;
return Ok(xfa_click_outcome(out));
}
let mut runner = JsRunner::new(&cos, &doc.name, self.field_highlight);
runner.doc.zoom = doc.js_zoom;
@@ -1699,6 +1693,32 @@ mod caption_tests {
}
}
/// The SOM path of the XFA click script button `target` runs, when it is a push button PdfCraft
/// generated from a laid-out XFA form's template.
fn xfa_click_som(doc: &crate::Document, cos: &pdfcraft_cos::Document, target: Option<&str>, target_id: Option<u64>) -> Option<String> {
let t = target?;
let tpl = doc.xfa_template.as_ref()?;
let field = doc.form.iter().find(|f| f.name == t && target_id.is_none_or(|id| field_object_id(f.obj) == id))?;
if field.kind != crate::FormFieldKind::PushButton {
return None;
}
crate::xfa::clickable_som(cos, tpl, field)
}
/// What an XFA button click did, as a button script's outcome.
fn xfa_click_outcome(out: JsOutput) -> Outcome {
Outcome { rc: true, alerts: out.alerts, console: out.console, requests: out.requests, error: out.errors.first().cloned(), ..Default::default() }
}
/// Stack for the thread an XFA button click runs on in the app: it lays the form out again, as
/// the app's main thread does for other edits.
#[cfg(not(target_arch = "wasm32"))]
const XFA_CLICK_STACK: usize = 8 << 20;
/// An XFA button click's edit, once its worker has run it ([`Session::start_javascript_target`]).
#[cfg(not(target_arch = "wasm32"))]
type XfaClick = std::sync::Arc<std::sync::Mutex<Option<(crate::session::BegunEdit, Result<(), EditError>)>>>;
/// A failed link action commits nothing: its field changes, requests and layer changes are
/// dropped (the realm put its timers back), its alerts, console lines and error kept (#2081).
fn drop_failed_link_effects(o: &mut Outcome) {
@@ -1822,6 +1842,16 @@ pub struct PendingScript {
/// Whether the script may add or show pages from templates ([`may_change_pages`]).
may_change_pages: bool,
pub receiver: std::sync::mpsc::Receiver<pdfcraft_js::interaction::InteractiveEvent>,
/// An XFA button click: its edit, filled in by its worker before it completes.
xfa: Option<XfaClick>,
}
#[cfg(not(target_arch = "wasm32"))]
impl PendingScript {
/// Whether this is an XFA button's click ([`Session::start_javascript_target`]). It reads
/// no view state (zoom, page) the way an AcroForm script does, and its own limits bound it.
pub fn is_xfa(&self) -> bool {
self.xfa.is_some()
}
}
#[cfg(not(target_arch = "wasm32"))]
impl Session {
@@ -1846,12 +1876,15 @@ impl Session {
}
let doc = self.get(id).ok_or(EditError::NoDocument)?;
let cos = &doc.editor.as_ref().ok_or_else(|| EditError::ReadOnly(doc.read_only_reason.clone().unwrap_or_default()))?.cos;
let fields = pdfcraft_forms::fields(cos);
validate_script_target(target, target_id, &fields)?;
if let Some(som) = xfa_click_som(doc, cos, target, target_id) {
return self.start_xfa_click(id, som);
}
let mut runner = JsRunner::new(cos, &doc.name, self.field_highlight);
runner.doc.zoom = doc.js_zoom;
runner.doc.page = doc.js_page;
runner.doc.layers = crate::live_scripts::js_layers(&doc.info);
let fields = pdfcraft_forms::fields(cos);
validate_script_target(target, target_id, &fields)?;
let states = std::sync::Arc::new(fields.iter().map(|f| crate::live_scripts::live_state(doc, cos, f, &runner.doc)).collect::<Vec<_>>());
let job = pdfcraft_js::session::Job {
script: script.into(),
@@ -1868,7 +1901,65 @@ impl Session {
let receiver =
doc.js_runtime.lock().map_err(|_| EditError::Invalid("script runtime unavailable".into()))?.start(job).map_err(EditError::Invalid)?;
let may_change_pages = may_change_pages(target, &fields);
Ok(PendingScript { id, link: false, generation: doc.generation, runtime: doc.js_runtime.clone(), states, may_change_pages, receiver })
Ok(PendingScript {
id,
link: false,
generation: doc.generation,
runtime: doc.js_runtime.clone(),
states,
may_change_pages,
receiver,
xfa: None,
})
}
/// Start XFA button `som`'s click on a worker, so the app goes on drawing while it runs and
/// can ask its message boxes' questions: each comes through the pending script's receiver
/// as a prompt, and the script waits for the answer with its clock stopped. Once the worker
/// is done, [`Session::finish_javascript`] keeps the click as one undo step, as
/// [`Session::apply`] would, unless the document changed meanwhile.
fn start_xfa_click(&mut self, id: DocId, som: String) -> Result<PendingScript, EditError> {
let (prompts, receiver) = std::sync::mpsc::channel();
self.xfa_answers = Some(crate::xfa::XfaAnswers { prompts: Some(prompts.clone()), ..Default::default() });
let begun = self.begin_edit(id, Edit::XfaEvent { som, activity: "click".into() });
// Not taken when the edit stopped before it began.
self.xfa_answers = None;
let begun = begun?;
let doc = self.get(id).ok_or(EditError::NoDocument)?;
let click: XfaClick = Default::default();
let pending = PendingScript {
id,
link: false,
generation: doc.generation,
runtime: doc.js_runtime.clone(),
states: Default::default(),
// Its edit is kept as an undo step of its own (`finish_javascript`), never applied as a
// script outcome, so it adds no pages from templates.
may_change_pages: false,
receiver,
xfa: Some(click.clone()),
};
let Some(mut begun) = begun else {
// Nothing to run: done at once.
let _ = prompts.send(InteractiveEvent::Complete(Outcome::default()));
return Ok(pending);
};
let ran_away = std::sync::Arc::clone(&doc.xfa_ran_away);
std::thread::Builder::new()
.name("pdfcraft-xfa-click".into())
.stack_size(XFA_CLICK_STACK)
.spawn(move || {
let checked = crate::session::run_checked_edit(&mut begun.next, &begun.edit, &mut begun.cx);
if begun.cx.xfa_ran_away {
ran_away.store(true, std::sync::atomic::Ordering::Relaxed);
}
// A poisoned lock only means a panic elsewhere while it was held: the slot is still ours.
*click.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some((begun, checked));
// The app may have stopped waiting: then nobody takes the click.
let _ = prompts.send(InteractiveEvent::Complete(Outcome::default()));
})
.map_err(|e| EditError::Invalid(format!("the form script could not start: {e}")))?;
Ok(pending)
}
/// Start link `index` on page `page` as [`Session::run_link_javascript`] runs it, without
/// blocking on its prompts; [`Session::finish_javascript`] commits nothing if it failed.
@@ -1879,10 +1970,23 @@ impl Session {
doc.js_runtime.lock().map_err(|_| EditError::Invalid("script runtime unavailable".into()))?.start(job).map_err(EditError::Invalid)?;
// A link's script has the document as its target, as a document script does.
let may_change_pages = may_change_pages(None, &[]);
Ok(PendingScript { id, link: true, generation: doc.generation, runtime: doc.js_runtime.clone(), states, may_change_pages, receiver })
Ok(PendingScript {
id,
link: true,
generation: doc.generation,
runtime: doc.js_runtime.clone(),
states,
may_change_pages,
receiver,
xfa: None,
})
}
/// Discard only the captured runtime, preserving a newer realm created by an intervening edit.
pub fn discard_javascript(&mut self, p: &PendingScript) {
// An XFA click's worker holds no realm: what it did is dropped with the pending script.
if p.xfa.is_some() {
return;
}
if let Some(doc) = self.docs.iter_mut().find(|d| d.id == p.id)
&& std::sync::Arc::ptr_eq(&doc.js_runtime, &p.runtime)
{
@@ -1891,6 +1995,10 @@ impl Session {
}
/// Discard a timed-out invocation and retain the worker slot until its thread exits.
pub fn timeout_javascript(&mut self, p: PendingScript) {
// An XFA click's scripts are bounded on its worker; what it did is dropped.
if p.xfa.is_some() {
return;
}
if self.script_pending_current(&p)
&& let Ok(mut runtime) = p.runtime.lock()
{
@@ -1902,6 +2010,21 @@ impl Session {
/// Apply a current worker result, or discard it and reset the realm when the document changed.
pub fn finish_javascript(&mut self, p: PendingScript, mut out: Outcome) -> Result<Outcome, EditError> {
if let Some(click) = &p.xfa {
if !self.script_pending_current(&p) {
return Err(EditError::Invalid("document changed while the script was running".into()));
}
let ran = click.lock().unwrap_or_else(std::sync::PoisonError::into_inner).take();
let Some((begun, checked)) = ran else { return Ok(Outcome { rc: true, ..Default::default() }) };
let ran_away = begun.cx.xfa_ran_away;
let ((), out) = self.with_own_js_output(p.id, |s| s.finish_edit(p.id, begun, checked).map(|_| ()))?;
// Kept, a click that ran away turned the scripts off itself: not again. A flag another
// click set (one this commit makes stale) stays for the next edit.
if ran_away && let Some(d) = self.get(p.id) {
d.xfa_ran_away.store(false, std::sync::atomic::Ordering::Relaxed);
}
return Ok(xfa_click_outcome(out));
}
if p.link {
drop_failed_link_effects(&mut out);
}
+4 -3
View File
@@ -34,6 +34,7 @@ pub mod field_table;
mod fill_sign;
pub mod find_replace;
mod history;
mod image_alpha;
pub mod js;
mod layers;
pub mod links;
@@ -97,7 +98,7 @@ pub use pdfcraft_organize::view::{InitialView, Layout as InitialLayout, Magnific
pub use pdfcraft_cos::{Algorithm, civil_from_days};
pub use pdfcraft_create::{
CONVERTIBLE, CreateError, IMAGE_EXTENSIONS, ImageResolution, OFFICE_EXTENSIONS, SourceKind, TEXT_EXTENSIONS, decode_text, source_kind,
CONVERTIBLE, CreateError, IMAGE_EXTENSIONS, ImagePage, 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,
@@ -106,7 +107,7 @@ pub use pdfcraft_edit::added::{
pub use pdfcraft_edit::paragraph_align;
pub use pdfcraft_edit::{
Added, AddedImage, AddedText, Align as TextAlign, Background, ColourTarget, ColoursConverted, Content as AddedContent, ConvertColours,
Family as FontFamily, Hairlines, HairlinesFixed, HeaderFooter, Ink as TextInk, MarkKind, PrinterMarks, Watermark,
Family as FontFamily, Hairlines, HairlinesFixed, HeaderFooter, HeaderFooterMark, Ink as TextInk, MarkKind, PrinterMarks, Watermark,
};
pub use pdfcraft_forms::{
BorderStyle, CalculatedField, CalculationIssue, CalculationOrder, CheckStyle, Field as FormField, FieldAction, FieldChange, FieldFont,
@@ -191,7 +192,7 @@ mod doc_state;
pub use pdfcraft_edit::ArrangeOrder;
use clock::{local_utc_offset, parse_ymd};
pub use doc_state::{DocId, ImageEdit, OptimizeReport, RecoverySnapshot, SplitPart, guard, merge_data_files};
pub use doc_state::{DocId, ImageEdit, OptimizeReport, RecoverySnapshot, SplitPart, guard, merge_data_files, merge_data_files_with_columns};
use doc_state::{LOW_RESOLUTION_PRINT_DPI, editor_signatures, render_threads, renderer_password, signatures_of, writable};
/// The configuration of the pool that draws the viewer: the document's own, plus installed CJK
+3
View File
@@ -232,6 +232,7 @@ impl Session {
ran_away: false,
highlight: context.highlight,
time_scale: context.xfa_time_scale,
answers: Default::default(),
relaid: false,
};
let changes = xfa::on_open(&mut work, &tpl, &mut run);
@@ -405,9 +406,11 @@ impl Session {
xfa_template: None,
xfa_scripts_off: false,
xfa_exited: Default::default(),
xfa_ran_away: Default::default(),
fonts_stale: false,
xfa_warnings: Vec::new(),
edit_notices: Vec::new(),
alpha: Default::default(),
}
}
}
+11 -2
View File
@@ -10,7 +10,7 @@ use crate::check_refresh_panic;
use crate::edit::{EditCtx, check_permission, run_edit};
use crate::history::{Keys, MAX_UNDO, Scope, keys_after, scope_of, uses_scripts};
use crate::{
BookmarkPage, BookmarkRow, CombineSource, Combined, DataFormat, DocId, Document, Edit, EditError, Hairlines, HairlinesFixed, Hidden,
BookmarkPage, BookmarkRow, CombineSource, Combined, DataFormat, DocId, Document, Edit, EditError, Hairlines, HairlinesFixed, Hidden, ImagePage,
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, editor_signatures, guard, info_fields, js, local_utc_offset, note_warnings,
@@ -20,6 +20,8 @@ use crate::{
};
mod editing;
#[cfg(not(target_arch = "wasm32"))]
pub(crate) use editing::{BegunEdit, run_checked_edit};
mod files;
mod save;
mod view;
@@ -35,10 +37,14 @@ pub struct Session {
/// injected time AS local time and zeroes the zone, so injecting only it leaves either the
/// local dates or the UTC ones wrong by the zone's offset.
utc_offset: Option<fn() -> i64>,
/// Certificates trusted for signing (Acrobat: Trusted Certificates).
/// What is trusted for signing: the user's certificates (Acrobat: Trusted Certificates) and the
/// trust lists they loaded.
pub(crate) trust: Arc<TrustStore>,
/// The words signature status layers are drawn with, in the interface language.
pub(crate) captions: Arc<StatusCaptions>,
/// How often every open document's signatures were validated again after a trust change.
#[cfg(test)]
pub(crate) revalidations: usize,
/// Preferences ▸ JavaScript ▸ Enable Acrobat JavaScript, inverted (on by default).
pub(crate) js_off: bool,
/// Preferences ▸ Date format, when not the default (see [`dates`]).
@@ -51,4 +57,7 @@ pub struct Session {
/// What the XFA scripts' time limits are multiplied by (`None`: 1); see
/// [`Session::with_xfa_time_scale`].
pub(crate) xfa_time_scale: Option<u32>,
/// The answers the next XFA event takes for its message boxes, set by the caller running it
/// (`js_run`'s answers, an app's button click) and taken by that event's edit.
pub(crate) xfa_answers: Option<crate::xfa::XfaAnswers>,
}
+57 -5
View File
@@ -46,7 +46,7 @@ fn deletes_pages(edit: &Edit) -> bool {
}
/// Keep edits to the working copy until both the operation and its script callbacks succeed.
fn run_checked_edit(next: &mut pdfcraft_cos::Document, edit: &Edit, cx: &mut EditCtx) -> Result<(), EditError> {
pub(crate) fn run_checked_edit(next: &mut pdfcraft_cos::Document, edit: &Edit, cx: &mut EditCtx) -> Result<(), EditError> {
let result = guard(|| run_edit(next, edit, cx))
.unwrap_or_else(|m| Err(EditError::Invalid(format!("{} failed unexpectedly ({m}); the document was not changed", edit.label()))));
let refusal = cx.js.as_mut().and_then(|runner| runner.refused.take());
@@ -122,6 +122,20 @@ fn sync_script_history(doc: &Document, previous: &pdfcraft_cos::Document, restor
}
}
/// An edit between [`Session::begin_edit`] and [`Session::finish_edit`]: the copy of the
/// document it runs on (`next`) and its context. Send, so an XFA button click can run on a
/// worker while the app goes on drawing and asks the click's questions.
pub(crate) struct BegunEdit {
pub(crate) edit: Edit,
pub(crate) next: pdfcraft_cos::Document,
pub(crate) cx: EditCtx,
scope: Scope,
is_xfa: bool,
signed: bool,
/// The document's generation it was made from: a changed document doesn't take it.
generation: u64,
}
impl Session {
/// Apply an edit. On success the previous state is undoable and the view data is refreshed.
pub fn apply(&mut self, id: DocId, edit: Edit) -> Result<(), EditError> {
@@ -138,12 +152,27 @@ impl Session {
/// [`Session::apply`], giving back what an [`Edit::PrepareText`] did (`None` for other edits).
fn apply_reporting(&mut self, id: DocId, edit: Edit) -> Result<Option<pdfcraft_edit::text::forms::Preparation>, EditError> {
let Some(mut begun) = self.begin_edit(id, edit)? else { return Ok(None) };
// `next` is a copy: if the edit fails or crashes, the document is unchanged.
let checked = run_checked_edit(&mut begun.next, &begun.edit, &mut begun.cx);
self.finish_edit(id, begun, checked)
}
/// The first part of [`Session::apply`]: check that `edit` may be made, and make the copy of
/// the document it runs on, with its context. `None`: there is nothing to do.
pub(crate) fn begin_edit(&mut self, id: DocId, edit: Edit) -> Result<Option<BegunEdit>, EditError> {
let now = self.now();
let today = self.today();
let js_off = self.js_off;
let highlight = self.field_highlight;
let xfa_time_scale = self.xfa_time_scale.unwrap_or(1);
let xfa_answers = self.xfa_answers.take().unwrap_or_default();
let doc = self.doc_mut(id)?;
// A script of an XFA click run on a worker ran away: the form's scripts go off, whether
// or not the click was kept.
if doc.xfa_ran_away.swap(false, std::sync::atomic::Ordering::Relaxed) {
take_xfa_output(doc, js::JsOutput::default(), true);
}
// An edit must never read globals from a completed-but-unapplied button invocation.
// Fork its realm before any edit-triggered calculation, even if the edit later fails.
#[cfg(not(target_arch = "wasm32"))]
@@ -153,12 +182,13 @@ impl Session {
doc.edit_notices.clear();
let name = doc.name.clone();
let is_xfa = doc.info.xfa.is_some();
let mut scope = scope_of(&edit);
let scope = scope_of(&edit);
let mut cx = EditCtx::new(now, doc.generation ^ (id.0 << 48));
if !js_off {
cx.xfa = doc.xfa_template.clone();
}
cx.xfa_time_scale = xfa_time_scale;
cx.xfa_answers = xfa_answers;
cx.pages = doc.info.pages.len();
cx.highlight = highlight;
cx.today = today;
@@ -175,7 +205,7 @@ impl Session {
if matches!(&edit, Edit::FlattenFillSign) && !pdfcraft_annot::has_visible_fill_sign(&editor.cos) {
return Ok(None);
}
let mut next = editor.cos.clone();
let next = editor.cos.clone();
if !js_off && uses_scripts(&edit) {
let mut runner = js::JsRunner::new(&next, &name, highlight);
runner.runtime = doc.js_runtime.clone();
@@ -187,8 +217,27 @@ impl Session {
cx.renamed_fields.clear();
cx.redaction_overlays.clear();
cx.redaction_marks.clear();
// `next` is a copy: if the edit fails or crashes, the document is unchanged.
run_checked_edit(&mut next, &edit, &mut cx)?;
Ok(Some(BegunEdit { edit, next, cx, scope, is_xfa, signed, generation: doc.generation }))
}
/// The last part of [`Session::apply`]: keep the edit [`Session::begin_edit`] prepared once
/// it ran (`checked`), as one undo step, unless it failed or the document changed meanwhile
/// (an XFA button click runs on a worker: [`Session::start_javascript_target`]).
pub(crate) fn finish_edit(
&mut self,
id: DocId,
begun: BegunEdit,
checked: Result<(), EditError>,
) -> Result<Option<pdfcraft_edit::text::forms::Preparation>, EditError> {
let BegunEdit { edit, mut next, mut cx, mut scope, is_xfa, signed, generation } = begun;
let doc = self.doc_mut(id)?;
if doc.generation != generation {
discard_edit_callbacks(&cx);
return Err(EditError::Invalid("the document changed while the form's script ran; what it did was not kept".into()));
}
let reason = doc.read_only_reason.clone().unwrap_or_default();
let editor = doc.editor.as_mut().ok_or(EditError::ReadOnly(reason))?;
checked?;
// A field's enter or exit scripts that changed nothing leave no edit behind (no undo step,
// nothing unsaved); what they showed or asked for still goes out. Only an event on its own:
// a batch keeps the other edits it holds.
@@ -278,6 +327,7 @@ impl Session {
ran_away: false,
highlight,
time_scale: cx.xfa_time_scale,
answers: Default::default(),
relaid: false,
};
// Every changed field's scripts, then the calculations once (after a reset,
@@ -623,6 +673,7 @@ impl Session {
matches!(
e,
Edit::AddHeaderFooter { .. }
| Edit::UpdateHeaderFooter { .. }
| Edit::AddWatermark { .. }
| Edit::AddBackground { .. }
| Edit::AddPrinterMarks { .. }
@@ -788,6 +839,7 @@ fn rerun_layout_ready(next: &mut pdfcraft_cos::Document, cx: &mut EditCtx) {
ran_away: false,
highlight,
time_scale: cx.xfa_time_scale,
answers: Default::default(),
relaid: false,
};
let ran = guard(|| xfa::on_layout(next, &tpl, &mut run)).unwrap_or_else(|m| Err(format!("the form's scripts failed unexpectedly ({m})")));
+27 -10
View File
@@ -1,7 +1,7 @@
use super::{
Arc, CombineSource, Combined, DataFormat, DocId, EditError, Hairlines, HairlinesFixed, Hidden, ImageResolution, LOW_RESOLUTION_PRINT_DPI,
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,
Arc, CombineSource, Combined, DataFormat, DocId, EditError, Hairlines, HairlinesFixed, Hidden, ImagePage, ImageResolution,
LOW_RESOLUTION_PRINT_DPI, 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,
};
/// Why printer's marks were refused for a print that goes as pictures.
@@ -33,7 +33,18 @@ impl Session {
/// Create image pages at embedded resolution or a fixed dpi, without resampling.
pub fn create_from_images_with_resolution(&self, images: &[(String, Vec<u8>)], resolution: ImageResolution) -> Result<Arc<Vec<u8>>, EditError> {
self.write_new(&pdfcraft_create::from_images_with_resolution(images, resolution)?)
self.create_from_images_with(images, resolution, ImagePage::Image)
}
/// Create image pages at a resolution, each on its own size or on one fixed sheet (scaled to
/// fit and centred). Pixels are never resampled either way.
pub fn create_from_images_with(
&self,
images: &[(String, Vec<u8>)],
resolution: ImageResolution,
page: ImagePage,
) -> Result<Arc<Vec<u8>>, EditError> {
self.write_new(&pdfcraft_create::from_images_with(images, resolution, page)?)
}
/// A new document from plain text (US Letter, 11 pt Helvetica, or the bundled Inter face for
@@ -57,17 +68,23 @@ impl Session {
/// 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(name, bytes, Office::Convert, ImagePage::Image)
}
/// [`Self::convert_to_pdf`], putting an image source on `page`. A PDF, text or Office source is
/// unaffected: only an image is laid onto a sheet of a chosen size.
pub fn convert_to_pdf_with(&self, name: &str, bytes: &Arc<Vec<u8>>, page: ImagePage) -> Result<(SourceKind, Arc<Vec<u8>>), EditError> {
self.convert(name, bytes, Office::Convert, page)
}
/// [`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)
self.convert(name, bytes, Office::Refuse, ImagePage::Image)
}
fn convert(&self, name: &str, bytes: &Arc<Vec<u8>>, office: Office) -> Result<(SourceKind, Arc<Vec<u8>>), EditError> {
fn convert(&self, name: &str, bytes: &Arc<Vec<u8>>, office: Office, page: ImagePage) -> 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, a .txt file or a Word, Excel or PowerPoint file"
@@ -82,7 +99,7 @@ impl Session {
// 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::Image => self.create_from_images_with(&[(name.to_string(), bytes.to_vec())], ImageResolution::Embedded, page),
SourceKind::Text => self.create_from_text(title, &decode_text(bytes)),
SourceKind::Office => office_to_pdf(name, bytes),
})
@@ -108,7 +125,7 @@ impl Session {
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(name, bytes, office)?;
let (_, pdf) = self.convert(name, bytes, office, ImagePage::Image)?;
return Ok((self.page_count_of(name, &pdf)?, pdf));
}
let src = crate::sources::open_source_into(name, bytes, self.cos(dest)?)?;
@@ -141,7 +158,7 @@ impl Session {
Some(SourceKind::Image | SourceKind::Text | SourceKind::Office) => false,
None => name.to_ascii_lowercase().ends_with(".pdf"),
};
if pdf { Ok(bytes.clone()) } else { self.convert(name, bytes, office).map(|(_, pdf)| pdf) }
if pdf { Ok(bytes.clone()) } else { self.convert(name, bytes, office, ImagePage::Image).map(|(_, pdf)| pdf) }
}
/// Reduce File Size: Acrobat's defaults (colour and grey images above 225 ppi to 150 ppi,
+37 -4
View File
@@ -252,11 +252,44 @@ impl Session {
&self.trust.certs
}
/// Replace the trusted certificates, revalidate every open document's signatures,
/// and rebuild its display copy and renderer to match (working file untouched,
/// generation/dirty unchanged: trust alone is not an edit).
/// Change the trust store, revalidate every open document's signatures, and rebuild its
/// display copy and renderer to match (working file untouched, generation/dirty unchanged:
/// trust alone is not an edit). This happens once, however many changes `change` makes:
/// revalidating runs chain building and signature verification for every signature, against
/// every certificate of every trust list.
pub fn update_trust(&mut self, change: impl FnOnce(&mut TrustStore)) {
let mut trust = (*self.trust).clone();
change(&mut trust);
self.trust = Arc::new(trust);
self.revalidate_signatures();
}
/// Replace the trusted certificates (see [`Session::update_trust`]).
pub fn set_trusted_certificates(&mut self, certs: Vec<pdfcraft_sign::Certificate>) {
self.trust = Arc::new(TrustStore { certs });
self.update_trust(|trust| trust.certs = certs);
}
/// The trust lists the user loaded (e.g. the EU Trusted Lists' qualified CAs), none by default.
/// They are not part of [`Session::trusted_certificates`].
pub fn trust_lists(&self) -> &[pdfcraft_sign::trust::TrustList] {
&self.trust.lists
}
/// Load `list` (replacing a list of the same name) and revalidate every open document.
pub fn add_trust_list(&mut self, list: pdfcraft_sign::trust::TrustList) {
self.update_trust(|trust| trust.add_list(list));
}
/// Remove the trust list called `name` and revalidate every open document.
pub fn remove_trust_list(&mut self, name: &str) {
self.update_trust(|trust| trust.remove_list(name));
}
fn revalidate_signatures(&mut self) {
#[cfg(test)]
{
self.revalidations += 1;
}
for doc in &mut self.docs {
Self::revalidate(doc, self.trust.clone());
}
+603 -7
View File
@@ -4534,6 +4534,51 @@ fn update_previews_on_the_page_without_the_marks_it_replaces() {
assert_eq!((doc.edit_generation(), doc.dirty, doc.can_undo()), (generation, dirty, Some("Add watermark")), "the document is unchanged");
}
/// #5785: Update of one header and footer previews the page without that one alone, so a second
/// header and footer on the same page, which OK keeps, is still drawn in the preview.
#[test]
fn update_of_one_header_previews_the_page_with_the_others() {
let (mut s, id) = session_with(2);
let header = |text: &str, color: [f64; 3]| {
let mut hf = pdfcraft_edit::HeaderFooter { color, font_size: 24.0, ..pdfcraft_edit::HeaderFooter::default() };
hf.text[1] = text.into();
hf
};
let (red, blue) = (header("REDREDRED", [1.0, 0.0, 0.0]), header("BLUEBLUEBLUE", [0.0, 0.0, 1.0]));
s.apply(id, Edit::AddHeaderFooter { pages: vec![0, 1], settings: red.clone(), replace: false }).unwrap();
let mut footer = blue.clone();
footer.text.swap(1, 4);
s.apply(id, Edit::AddHeaderFooter { pages: vec![0], settings: footer.clone(), replace: false }).unwrap();
let doc = s.get(id).unwrap();
let generation = doc.edit_generation();
let count =
|p: &pdfcraft_render::RenderedPage, f: fn(u8, u8, u8) -> bool| p.rgba.as_chunks::<4>().0.iter().filter(|[r, g, b, _]| f(*r, *g, *b)).count();
let reds = |p: &pdfcraft_render::RenderedPage| count(p, |r, g, b| r > 200 && g < 80 && b < 80);
let blues = |p: &pdfcraft_render::RenderedPage| count(p, |r, g, b| b > 200 && r < 80 && g < 80);
let mut without_red = doc.without_header_footer(&red).unwrap().expect("the red header is on the pages");
let page = without_red.render_page(0, 1.0).unwrap();
assert_eq!(reds(&page), 0, "the header Update replaces is gone");
assert_eq!(blues(&page), 0, "the footer added after it is drawn over the new one, so not under it");
assert_eq!(reds(&without_red.render_page(1, 1.0).unwrap()), 0, "from every page it is on");
// The footer OK keeps over the new header, alone.
let mut over_red = doc.over_header_footer(&red).unwrap().expect("the blue footer is over the red header");
let page = over_red.render_page(0, 1.0).unwrap();
let opaque = |p: &pdfcraft_render::RenderedPage| p.rgba.as_chunks::<4>().0.iter().filter(|[.., a]| *a > 0).count();
assert!(blues(&page) > 20 && reds(&page) == 0, "the other header and footer on the page stays, as OK keeps it");
assert!(opaque(&page) < page.rgba.len() / 8, "on a transparent page: the draft under it shows");
assert_eq!(opaque(&over_red.render_page(1, 1.0).unwrap()), 0, "nothing is over it where it is alone");
assert!(doc.over_header_footer(&footer).unwrap().is_none(), "nothing is over the newest");
let page = doc.without_header_footer(&footer).unwrap().expect("the blue footer is on page 1").render_page(0, 1.0).unwrap();
assert!(reds(&page) > 20 && blues(&page) == 0, "and the other way round");
// Every header and footer goes for a page-wide replace, and a header no page records has nothing to prepare.
let page = doc.without_marks(MarkKind::HeaderFooter).unwrap().expect("there are headers").render_page(0, 1.0).unwrap();
assert_eq!((reds(&page), blues(&page)), (0, 0));
assert!(doc.without_header_footer(&header("GONE", [0.0, 1.0, 0.0])).unwrap().is_none());
assert_eq!(s.get(id).unwrap().edit_generation(), generation, "the document is unchanged");
}
#[test]
fn marker_indexes_match_after_open_and_save_when_requested() {
let (mut source, source_id) = session_with(1);
@@ -5799,6 +5844,31 @@ fn reading_colors_set_and_invalidated() {
assert!(!s.set_reading_colors(DocId(u64::MAX), ReadingColors::WHITE_ON_BLACK));
}
#[test]
fn several_trust_changes_revalidate_the_open_documents_once() {
let p12 = std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/../sign/tests/data/ec-p256.p12")).unwrap();
let cert = sign::pkcs12::open(&p12, "test").unwrap().certificate;
let mut s = Session::default();
// Each setter changes one thing and revalidates.
s.set_trusted_certificates(vec![cert.clone()]);
s.set_trusted_certificates(Vec::new());
assert_eq!(s.revalidations, 2);
// One `update_trust` changes any number of things and revalidates once.
let list = sign::trust::TrustList::from_bytes("Test list", &cert.raw).unwrap();
s.update_trust(|trust| {
trust.certs = vec![cert.clone()];
trust.add_list(list.clone());
});
assert_eq!(s.revalidations, 3);
assert_eq!((s.trusted_certificates().len(), s.trust_lists().len()), (1, 1));
// A list loaded again under its name replaces itself; removing it by that name takes it back.
s.add_trust_list(list);
assert_eq!(s.trust_lists().len(), 1);
s.remove_trust_list("Test list");
assert!(s.trust_lists().is_empty());
assert_eq!(s.revalidations, 5);
}
#[test]
fn signing_saving_trusting_and_commenting_afterwards() {
let p12 = std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/../sign/tests/data/ec-p256.p12")).unwrap();
@@ -8347,13 +8417,29 @@ fn on_changes_notes_only_the_exits_that_ran() {
let names = vec!["probe".to_string()];
let mut exited = Vec::new();
let mut out = crate::js::JsOutput::default();
let mut stopped =
crate::xfa::XfaRun { page_count: 1, out: &mut out, datasets: None, ran_away: true, highlight: false, time_scale: 1, relaid: false };
let mut stopped = crate::xfa::XfaRun {
page_count: 1,
out: &mut out,
datasets: None,
ran_away: true,
highlight: false,
time_scale: 1,
answers: Default::default(),
relaid: false,
};
crate::xfa::on_changes(&mut cos, &tpl, &names, &Default::default(), &mut stopped, &mut exited).unwrap();
assert!(exited.is_empty(), "no exit ran: {exited:?}");
let mut out = crate::js::JsOutput::default();
let mut running =
crate::xfa::XfaRun { page_count: 1, out: &mut out, datasets: None, ran_away: false, highlight: false, time_scale: 1, relaid: false };
let mut running = crate::xfa::XfaRun {
page_count: 1,
out: &mut out,
datasets: None,
ran_away: false,
highlight: false,
time_scale: 1,
answers: Default::default(),
relaid: false,
};
crate::xfa::on_changes(&mut cos, &tpl, &names, &Default::default(), &mut running, &mut exited).unwrap();
assert_eq!(exited.len(), 1, "the exit ran: {exited:?}");
}
@@ -10423,6 +10509,284 @@ fn xfa_message_boxes_keep_their_title_icon_and_buttons() {
assert_eq!(o.alerts, vec![titled("Too many", "Limits", MessageIcon::Warning, MessageButtons::OkCancel)]);
}
/// A form whose buttons branch on their message boxes' answers (#4291): `hello` (JavaScript)
/// shows a message, then asks two questions; `legacy` (FormCalc) asks one.
fn asking_form() -> (Session, DocId) {
let tpl = pdfcraft_xfa::fixtures::scripted_template()
.replace(
r#"xfa.host.messageBox("Hello " + qty.rawValue);"#,
r#"xfa.host.messageBox("Starting"); var a = xfa.host.messageBox("Clear?", "T", 2, 2); var b = app.alert("Really?", 2, 1); qty.rawValue = (a == 4 ? 10 : 20) + (b == 1 ? 1 : 2);"#,
)
.replace(r#"$host.messageBox("FormCalc")"#, r#"if ($host.messageBox("Sure?", "", 2, 2) == 4) then qty = 50 else qty = 1 endif"#);
let mut s = Session::new().with_clock(|| 1_700_000_000);
let id = s.open("asking.pdf", None, Arc::new(pdfcraft_xfa::fixtures::shell(&tpl)), None).expect("opens");
(s, id)
}
fn qty(s: &Session, id: DocId) -> Vec<String> {
s.get(id).unwrap().form.iter().find(|f| f.name == "qty").unwrap().value.clone()
}
fn answers(a: &[&str]) -> Vec<Option<String>> {
a.iter().map(|a| Some(a.to_string())).collect()
}
/// An XFA button's message boxes return the answers given, in order, headless (`js_run`'s
/// answers), in JavaScript and FormCalc alike: a form can branch on No and Cancel (#4291).
/// Without answers each question gets its buttons' safe default (No; Cancel), not OK.
#[test]
fn xfa_message_boxes_return_the_answers_given() {
let (mut s, id) = asking_form();
assert_eq!(qty(&s, id), ["2"]);
let o = s.run_javascript_answers(id, "", Some("hello"), &answers(&["1", "4", "1"])).unwrap();
assert_eq!((o.error.as_deref(), o.alerts.len()), (None, 3), "{o:?}");
assert_eq!(qty(&s, id), ["11"]);
let o = s.run_javascript_answers(id, "", Some("hello"), &answers(&["1", "3", "2"])).unwrap();
assert_eq!(o.error, None);
assert_eq!(qty(&s, id), ["22"]);
s.run_javascript(id, "", Some("hello")).unwrap();
assert_eq!(qty(&s, id), ["22"], "no answers: No and Cancel");
s.run_javascript_answers(id, "", Some("legacy"), &answers(&["4"])).unwrap();
assert_eq!(qty(&s, id), ["50"]);
s.run_javascript(id, "", Some("legacy")).unwrap();
assert_eq!(qty(&s, id), ["1"]);
// An answer the buttons can't give fails the script and says which.
let o = s.run_javascript_answers(id, "", Some("hello"), &answers(&["1", "2"])).unwrap();
assert!(o.error.as_deref().is_some_and(|e| e.contains("message box 2 (2)")), "{o:?}");
}
/// Wait for the next event of an XFA click started as the app starts it.
#[cfg(not(target_arch = "wasm32"))]
fn next_event(p: &crate::js::PendingScript) -> crate::js::InteractiveEvent {
p.receiver.recv_timeout(std::time::Duration::from_secs(20)).expect("the click goes on")
}
/// Answer the click's questions in turn with `answers` (each prompt checked against `asked`),
/// then keep the click. Returns the outcome.
#[cfg(not(target_arch = "wasm32"))]
fn answer_click(s: &mut Session, p: crate::js::PendingScript, asked: &[&str], answers: &[Option<&str>]) -> Result<js::Outcome, EditError> {
use crate::js::{InteractiveEvent, Prompt};
for (want, answer) in asked.iter().zip(answers) {
match next_event(&p) {
InteractiveEvent::Prompt(Prompt::Alert(m), reply) => {
assert_eq!(m.text, *want);
reply.send(answer.map(String::from)).expect("the script waits");
}
InteractiveEvent::Prompt(other, _) => panic!("{other:?}"),
InteractiveEvent::Complete(_) => panic!("finished before asking {want}"),
}
}
let InteractiveEvent::Complete(out) = next_event(&p) else { panic!("asked more than {asked:?}") };
s.finish_javascript(p, out)
}
/// An XFA button clicked in the app runs on a worker and asks its message boxes' questions,
/// each script waiting for its answer, in JavaScript and FormCalc alike (#4291), as an AcroForm
/// script's `app.alert` does: nothing changes while it asks, and the click is kept as one undo
/// step once answered.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn an_xfa_click_started_in_the_app_asks_and_waits_for_each_answer() {
use crate::js::{InteractiveEvent, Prompt};
let (mut s, id) = asking_form();
let p = s.start_javascript_target(id, "", Some("hello"), None).unwrap();
let InteractiveEvent::Prompt(Prompt::Alert(m), reply) = next_event(&p) else { panic!("asks") };
assert_eq!((m.text.as_str(), m.buttons), ("Starting", js::MessageButtons::Ok));
// The script waits; the document is as it was.
assert_eq!(qty(&s, id), ["2"]);
assert!(s.get(id).unwrap().can_undo().is_none());
reply.send(Some("1".into())).unwrap();
let o = answer_click(&mut s, p, &["Clear?", "Really?"], &[Some("4"), None]).unwrap();
assert_eq!((o.error, o.alerts.len()), (None, 3));
assert_eq!(qty(&s, id), ["12"], "Yes, then closed (Cancel)");
assert!(s.get(id).unwrap().can_undo().is_some());
let p = s.start_javascript_target(id, "", Some("legacy"), None).unwrap();
answer_click(&mut s, p, &["Sure?"], &[Some("3")]).unwrap();
assert_eq!(qty(&s, id), ["1"]);
}
/// A document changed while its XFA click waits for an answer doesn't take the click.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn an_xfa_click_is_dropped_when_the_document_changes_while_it_asks() {
use crate::js::{InteractiveEvent, Prompt};
let (mut s, id) = asking_form();
let p = s.start_javascript_target(id, "", Some("legacy"), None).unwrap();
let InteractiveEvent::Prompt(Prompt::Alert(_), reply) = next_event(&p) else { panic!("asks") };
s.apply(id, Edit::SetFieldValue { name: "qty".into(), value: FieldValue::Text("7".into()) }).unwrap();
reply.send(Some("4".into())).unwrap();
let InteractiveEvent::Complete(out) = next_event(&p) else { panic!("finishes") };
assert!(!s.script_pending_current(&p));
assert!(s.finish_javascript(p, out).is_err());
assert_eq!(qty(&s, id), ["7"]);
}
/// A click asks at most 32 questions; every later message box gets its buttons' safe default (No
/// for Yes/No) without asking, and the script goes on, as it does when the click's questions are
/// spent across its script sessions (review on #6984).
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn an_xfa_click_asks_at_most_32_questions() {
use crate::js::{InteractiveEvent, Prompt};
let tpl = pdfcraft_xfa::fixtures::scripted_template().replace(
r#"xfa.host.messageBox("Hello " + qty.rawValue);"#,
r#"var yes = 0; var no = 0; for (var i = 0; i &lt; 60; i++) { var a = xfa.host.messageBox("Again?", "", 2, 2); if (a == 4) yes++; else if (a == 3) no++; } qty.rawValue = yes * 10000 + no;"#,
);
let mut s = Session::new().with_clock(|| 1_700_000_000);
let id = s.open("many.pdf", None, Arc::new(pdfcraft_xfa::fixtures::shell(&tpl)), None).expect("opens");
let p = s.start_javascript_target(id, "", Some("hello"), None).unwrap();
let mut asked = 0;
let out = loop {
match next_event(&p) {
InteractiveEvent::Prompt(Prompt::Alert(_), reply) => {
asked += 1;
reply.send(Some("4".into())).unwrap();
}
InteractiveEvent::Prompt(other, _) => panic!("{other:?}"),
InteractiveEvent::Complete(out) => break out,
}
};
assert_eq!(asked, 32);
let o = s.finish_javascript(p, out).unwrap();
assert!(o.error.is_none(), "the script goes on: {o:?}");
// 32 answered Yes; the other 28 got No without being asked.
assert_eq!(qty(&s, id), ["320028"]);
}
/// The 32-question limit holds for the whole click, not for each script session: a script that
/// turns field highlighting on or off starts a new session for the next, and the calculations
/// after it still can't ask more (they get the buttons' safe default).
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn an_xfa_clicks_question_limit_holds_across_its_script_sessions() {
use crate::js::{InteractiveEvent, Prompt};
let asks = "app.runtimeHighlight = !app.runtimeHighlight; for (var i = 0; i &lt; 20; i++) xfa.host.messageBox(\"Again?\", \"\", 0, 1);";
let tpl = pdfcraft_xfa::fixtures::scripted_template()
.replace(r#"xfa.host.messageBox("Hello " + qty.rawValue);"#, asks)
.replace(
"<calculate><script contentType=\"application/x-javascript\">qty.rawValue * price.rawValue</script></calculate>",
&format!("<calculate><script contentType=\"application/x-javascript\">{asks} qty.rawValue * price.rawValue</script></calculate>"),
)
.replace(
r#"var t = 0; var rows = xfa.resolveNodes("table.row[*]"); for (var i = 0; i &lt; rows.length; i++) { t += (rows.item(i).amount.rawValue || 0); } t"#,
&format!("{asks} 0"),
);
let mut s = Session::new().with_clock(|| 1_700_000_000);
let id = s.open("hostile.pdf", None, Arc::new(pdfcraft_xfa::fixtures::shell(&tpl)), None).expect("opens");
let p = s.start_javascript_target(id, "", Some("hello"), None).unwrap();
let mut asked = 0;
loop {
match next_event(&p) {
InteractiveEvent::Prompt(Prompt::Alert(_), reply) => {
asked += 1;
reply.send(Some("1".into())).unwrap();
}
InteractiveEvent::Prompt(other, _) => panic!("{other:?}"),
InteractiveEvent::Complete(_) => break,
}
}
assert_eq!(asked, 32, "the click and two calculations would ask 60 times");
}
/// A click whose script ran away turns the form's scripts off even when the click itself is
/// dropped (here the document changed while it ran), as a kept one does.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn a_dropped_xfa_click_that_ran_away_still_turns_the_scripts_off() {
use crate::js::InteractiveEvent;
let tpl = pdfcraft_xfa::fixtures::scripted_template().replace(
r#"xfa.host.messageBox("Hello " + qty.rawValue);"#,
"xfa.host.messageBox(\"Go\"); function f() { for (var j = 0; j &lt; 99999; j++) {} } for (var k = 0; k &lt; 5000; k++) f();",
);
let mut s = Session::new().with_clock(|| 1_700_000_000);
let id = s.open("runaway.pdf", None, Arc::new(pdfcraft_xfa::fixtures::shell(&tpl)), None).expect("opens");
let p = s.start_javascript_target(id, "", Some("hello"), None).unwrap();
// The script waits on its question until the other edit is in, so it cannot run away first.
let InteractiveEvent::Prompt(_, reply) = next_event(&p) else { panic!("asks first") };
s.apply(id, Edit::SetFieldValue { name: "price".into(), value: FieldValue::Text("6".into()) }).unwrap();
reply.send(Some("1".into())).unwrap();
let InteractiveEvent::Complete(out) = next_event(&p) else { panic!("finishes") };
assert!(s.finish_javascript(p, out).is_err(), "the document changed");
assert!(!s.get(id).unwrap().xfa_scripts_off());
s.apply(id, Edit::SetFieldValue { name: "price".into(), value: FieldValue::Text("7".into()) }).unwrap();
assert!(s.get(id).unwrap().xfa_scripts_off(), "the next edit turns them off");
assert!(s.take_js_output(id).errors.iter().any(|e| e.contains("scripts are off")));
}
/// Another click kept while a dropped one ran away leaves its signal for the next edit.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn a_click_kept_beside_one_that_ran_away_leaves_the_scripts_to_turn_off() {
use crate::js::InteractiveEvent;
let tpl = pdfcraft_xfa::fixtures::scripted_template().replace(
r#"xfa.host.messageBox("Hello " + qty.rawValue);"#,
"xfa.host.messageBox(\"Go\"); function f() { for (var j = 0; j &lt; 99999; j++) {} } for (var k = 0; k &lt; 5000; k++) f();",
);
let mut s = Session::new().with_clock(|| 1_700_000_000);
let id = s.open("runaway.pdf", None, Arc::new(pdfcraft_xfa::fixtures::shell(&tpl)), None).expect("opens");
let runaway = s.start_javascript_target(id, "", Some("hello"), None).unwrap();
// The runaway script waits on its question until the other click has begun.
let InteractiveEvent::Prompt(_, reply) = next_event(&runaway) else { panic!("asks first") };
let kept = s.start_javascript_target(id, "", Some("addRow"), None).unwrap();
reply.send(Some("1".into())).unwrap();
let InteractiveEvent::Complete(ran) = next_event(&runaway) else { panic!("finishes") };
let InteractiveEvent::Complete(out) = next_event(&kept) else { panic!("finishes") };
assert_eq!(s.finish_javascript(kept, out).unwrap().error, None);
assert!(s.finish_javascript(runaway, ran).is_err(), "the document changed");
s.apply(id, Edit::SetFieldValue { name: "price".into(), value: FieldValue::Text("7".into()) }).unwrap();
assert!(s.get(id).unwrap().xfa_scripts_off(), "the next edit turns them off");
}
/// The viewer is asked with a FormCalc message clipped, as the message box kept is.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn a_formcalc_question_is_asked_clipped() {
use crate::js::{InteractiveEvent, Prompt};
let tpl = pdfcraft_xfa::fixtures::scripted_template()
.replace(r#"$host.messageBox("FormCalc")"#, r#"var t = "x" while (Len(t) &lt; 100000) do t = Concat(t, t) endwhile $host.messageBox(t, t)"#);
let mut s = Session::new().with_clock(|| 1_700_000_000);
let id = s.open("long.pdf", None, Arc::new(pdfcraft_xfa::fixtures::shell(&tpl)), None).expect("opens");
let p = s.start_javascript_target(id, "", Some("legacy"), None).unwrap();
let InteractiveEvent::Prompt(Prompt::Alert(m), reply) = next_event(&p) else { panic!("asks") };
assert!(m.text.chars().count() <= 4_097, "{}", m.text.len());
assert!(m.title.as_deref().is_some_and(|t| t.chars().count() <= 4_097));
reply.send(None).unwrap();
let InteractiveEvent::Complete(out) = next_event(&p) else { panic!("finishes") };
assert_eq!(s.finish_javascript(p, out).unwrap().error, None);
}
/// The time a calculation waits for the user isn't the event's: the calculations after it still
/// run, though the wait is longer than their whole budget.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn waiting_for_an_answer_does_not_spend_the_events_time() {
use crate::js::{InteractiveEvent, Prompt};
let tpl = pdfcraft_xfa::fixtures::scripted_template()
.replace(r#"xfa.host.messageBox("Hello " + qty.rawValue);"#, "qty.rawValue = 5;")
.replace(
"<calculate><script contentType=\"application/x-javascript\">qty.rawValue * price.rawValue</script></calculate>",
"<calculate><script contentType=\"application/x-javascript\">if (qty.rawValue == 5) xfa.host.messageBox(\"Recalculate?\", \"\", 2, 2); qty.rawValue * price.rawValue</script></calculate>",
)
.replace(
r#"var t = 0; var rows = xfa.resolveNodes("table.row[*]"); for (var i = 0; i &lt; rows.length; i++) { t += (rows.item(i).amount.rawValue || 0); } t"#,
"qty.rawValue + 100",
);
let mut s = Session::new().with_clock(|| 1_700_000_000);
let id = s.open("slow.pdf", None, Arc::new(pdfcraft_xfa::fixtures::shell(&tpl)), None).expect("opens");
let grand = |s: &Session| s.get(id).unwrap().form.iter().find(|f| f.name == "grand").unwrap().value.clone();
assert_eq!(grand(&s), ["102"]);
let p = s.start_javascript_target(id, "", Some("hello"), None).unwrap();
let InteractiveEvent::Prompt(Prompt::Alert(m), reply) = next_event(&p) else { panic!("asks") };
assert_eq!(m.text, "Recalculate?");
// Longer than the calculations' 3 s budget.
std::thread::sleep(std::time::Duration::from_millis(3_500));
reply.send(Some("4".into())).unwrap();
let InteractiveEvent::Complete(out) = next_event(&p) else { panic!("finishes") };
let o = s.finish_javascript(p, out).unwrap();
assert_eq!(o.error, None, "{o:?}");
assert_eq!(grand(&s), ["105"], "the calculation after the question ran");
}
#[test]
fn runaway_xfa_calculations_at_open_end_quickly_with_a_report() {
// Nested loops in one frame stop at the loop limit; loops in nested calls (that limit is per
@@ -11425,7 +11789,9 @@ fn copy_image_finds_the_image_under_a_point_and_decodes_it_at_full_size() {
let id = s.open("p.pdf", None, pic, None).unwrap();
let d = s.get(id).unwrap();
let r = d.page_images(0)[0].rect;
assert_eq!(d.page_image_at(0, [(r[0] + r[2]) / 2.0, (r[1] + r[3]) / 2.0]), Some(0));
// On its red top-left pixel; its other pixels but the blue one are transparent.
assert_eq!(d.page_image_at(0, [r[0] + (r[2] - r[0]) / 6.0, r[3] - (r[3] - r[1]) / 4.0]), Some(0));
assert_eq!(d.page_image_at(0, [(r[0] + r[2]) / 2.0, (r[1] + r[3]) / 2.0]), None);
assert_eq!(d.page_image_at(0, [r[2] + 10.0, r[3] + 10.0]), None);
assert_eq!(d.page_image_at(7, [0.0, 0.0]), None);
let (w, h, rgba) = d.page_image_rgba(0, 0).unwrap();
@@ -11437,8 +11803,10 @@ fn copy_image_finds_the_image_under_a_point_and_decodes_it_at_full_size() {
let crop_keep = [r[0] + (r[2] - r[0]) * 0.25, r[1] + (r[3] - r[1]) * 0.25, r[0] + (r[2] - r[0]) * 0.75, r[1] + (r[3] - r[1]) * 0.75];
s.apply(id, Edit::EditPageImage { page: 0, index: 0, change: ImageEdit::Crop(crop_keep) }).unwrap();
let d = s.get(id).unwrap();
assert_eq!(d.page_image_at(0, [(r[0] + r[2]) / 2.0, (r[1] + r[3]) / 2.0]), Some(0));
assert_eq!(d.page_image_at(0, [r[0] + 0.1, r[1] + 0.1]), None, "cropped-away corner must not hit-test positive");
// Probe the red pixel: a picture is picked only where it shows, so a transparent pixel would
// not hit-test positive whether or not it was cropped away.
assert_eq!(d.page_image_at(0, [r[0] + (r[2] - r[0]) * 0.29, r[1] + (r[3] - r[1]) * 0.65]), Some(0));
assert_eq!(d.page_image_at(0, [r[0] + 0.1, r[3] - 0.1]), None, "cropped-away corner must not hit-test positive");
}
/// Copy Image: a JPEG drawn through grouped Form artwork (as Word, InDesign and scanners write
@@ -14156,6 +14524,234 @@ fn repeated_backdrop_artwork_survives_background_undo_redo_and_both_save_modes()
black(&s, rewritten);
}
/// A one-page 300 × 300 PDF of `objects` (numbered from 5) drawn by `content`; the page's
/// XObjects are `xobjects`.
fn images_pdf(xobjects: &str, content: &[u8], objects: &[(String, Vec<u8>)]) -> Vec<u8> {
let stream = |dict: &str, data: &[u8]| {
let mut o = format!("<< {dict} /Length {} >>\nstream\n", data.len()).into_bytes();
o.extend_from_slice(data);
o.extend_from_slice(b"\nendstream");
o
};
let mut objs: Vec<Vec<u8>> = vec![
b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(),
b"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 300 300] >>".to_vec(),
format!("<< /Type /Page /Parent 2 0 R /Contents 4 0 R /Resources << /XObject << {xobjects} >> >> >>").into_bytes(),
stream("", content),
];
objs.extend(objects.iter().map(|(dict, data)| stream(dict, data)));
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", i + 1).as_bytes());
out.extend_from_slice(o);
out.extend_from_slice(b"\nendobj\n");
}
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
}
/// #3069 review: a picture that shows nowhere (a soft mask below the opacity threshold
/// everywhere: a faint watermark, a transparent placeholder) keeps its whole box, so it can still
/// be picked to move or delete.
#[test]
fn a_picture_that_shows_nowhere_is_picked_by_its_whole_box() {
let objects = vec![
("/Type /XObject /Subtype /Image /Width 4 /Height 4 /ColorSpace /DeviceRGB /BitsPerComponent 8 /SMask 6 0 R".to_string(), vec![0x80; 48]),
("/Type /XObject /Subtype /Image /Width 4 /Height 4 /ColorSpace /DeviceGray /BitsPerComponent 8".to_string(), vec![8; 16]),
];
let mut s = Session::new();
let id = s.open("faint.pdf", None, Arc::new(images_pdf("/Faint 5 0 R", b"q 100 0 0 100 20 20 cm /Faint Do Q", &objects)), None).unwrap();
let d = s.get(id).unwrap();
assert_eq!(d.page_image_at(0, [70.0, 70.0]), Some(0));
assert!(d.image_shows_at(&d.page_images(0)[0], [30.0, 110.0]));
}
/// Pictures are picked where they show. Overlapping pictures with transparent margins (a PNG
/// signature over a table, cut-out photos side by side) give a click through the margin to the
/// picture below; stencil images and colour-keyed pictures likewise. Pictures that can't be
/// read, or show everywhere, keep their whole box.
#[test]
fn pictures_are_picked_where_they_show() {
let rgb = |n: usize| ("/Type /XObject /Subtype /Image /Width 4 /Height 4 /ColorSpace /DeviceRGB /BitsPerComponent 8".to_string(), vec![0x80; n]);
let with = |(d, data): (String, Vec<u8>), extra: &str| (format!("{d} {extra}"), data);
let gray = |rows: [[u8; 4]; 4]| {
("/Type /XObject /Subtype /Image /Width 4 /Height 4 /ColorSpace /DeviceGray /BitsPerComponent 8".to_string(), rows.concat())
};
let (a, o) = (255, 0);
let objects = vec![
rgb(48), // 5: Low, opaque
with(rgb(48), "/SMask 7 0 R"), // 6: Top
gray([[o, o, a, a], [o, o, a, a], [o, o, o, o], [o, o, o, o]]), // 7: its top-right quarter shows
("/Type /XObject /Subtype /Image /Width 2 /Height 1 /ImageMask true".into(), vec![0x40]), // 8
("/Type /XObject /Subtype /Image /Width 2 /Height 1 /ImageMask true /Decode [1 0]".into(), vec![0x40]), // 9
(
"/Type /XObject /Subtype /Image /Width 2 /Height 1 /ColorSpace /DeviceRGB /BitsPerComponent 8 /Mask [250 255 0 5 0 5]".into(),
vec![255, 0, 0, 0, 0, 255],
), // 10: red keyed out
(
"/Type /XObject /Subtype /Image /Width 4 /Height 4 /ColorSpace /DeviceRGB /BitsPerComponent 8 /Filter /JPXDecode /SMask 7 0 R".into(),
b"not a JPEG 2000 codestream".to_vec(),
), // 11: can't be read
with(rgb(48), "/SMask 13 0 R"), // 12
gray([[a; 4]; 4]), // 13: shows everywhere
];
let content = b"q 100 0 0 100 20 20 cm /Low Do Q q 100 0 0 100 60 60 cm /Top Do Q \
q 40 0 0 40 200 20 cm /St Do Q q 40 0 0 40 250 20 cm /StI Do Q q 40 0 0 40 200 100 cm /Key Do Q \
q 40 0 0 40 200 200 cm /Jpx Do Q q 40 0 0 40 250 200 cm /Full Do Q q -40 0 0 40 140 200 cm /Top Do Q q 0 40 -40 0 300 250 cm /Top Do Q";
let xobjects = "/Low 5 0 R /Top 6 0 R /St 8 0 R /StI 9 0 R /Key 10 0 R /Jpx 11 0 R /Full 12 0 R";
let mut s = Session::new();
let id = s.open("alpha.pdf", None, Arc::new(images_pdf(xobjects, content, &objects)), None).unwrap();
let d = s.get(id).unwrap();
assert_eq!(d.page_images(0).len(), 9, "{:?}", d.page_images(0));
let cases: [([f64; 2], Option<usize>); 14] = [
// Top's transparent lower-left, over Low: Low is picked.
([70.0, 70.0], Some(0)),
([100.0, 100.0], Some(0)),
// Top's showing quarter, over Low and beyond it.
([115.0, 145.0], Some(1)),
([150.0, 150.0], Some(1)),
// Top's transparent lower-right, over nothing.
([150.0, 70.0], None),
// A stencil paints its 0 samples; with /Decode [1 0], its 1 samples.
([210.0, 40.0], Some(2)),
([230.0, 40.0], None),
([260.0, 40.0], None),
([280.0, 40.0], Some(3)),
// The colour-keyed red half doesn't show.
([210.0, 120.0], None),
([230.0, 120.0], Some(4)),
// Unreadable, and showing everywhere: the whole box.
([205.0, 205.0], Some(5)),
([255.0, 205.0], Some(6)),
// Top mirrored: its showing quarter is on the left.
([105.0, 235.0], Some(7)),
];
for (at, want) in cases {
assert_eq!(d.page_image_at(0, at), want, "at {at:?}");
}
assert_eq!(d.page_image_at(0, [135.0, 235.0]), None, "the mirrored placement's transparent right");
// Top turned a quarter: its showing quarter is at the top left.
assert_eq!(d.page_image_at(0, [265.0, 285.0]), Some(8));
assert_eq!(d.page_image_at(0, [295.0, 285.0]), None);
assert_eq!(d.page_image_at(0, [265.0, 255.0]), None);
let images = d.page_images(0);
assert!(!d.image_shows_at(&images[1], [70.0, 70.0]));
assert!(d.image_shows_at(&images[1], [150.0, 150.0]));
// An edit changing only Top's soft mask is seen at once: it now shows everywhere.
let doc = s.doc_mut(id).unwrap();
let editor = doc.editor.as_mut().unwrap();
let full = editor.cos.get(pdfcraft_cos::ObjRef::new(13, 0));
editor.cos.set(pdfcraft_cos::ObjRef::new(7, 0), (*full).clone());
doc.generation += 1;
let d = s.get(id).unwrap();
assert_eq!(d.page_image_at(0, [70.0, 70.0]), Some(1));
assert_eq!(d.page_image_at(0, [150.0, 70.0]), Some(1));
}
/// A picture larger than the opacity grid is picked where it shows, its pixels scaled onto the
/// grid: a 300 × 300 picture showing only its top-left 150 × 150.
#[test]
fn large_pictures_are_picked_where_they_show() {
let mask: Vec<u8> = (0..300).flat_map(|y| (0..300).map(move |x| if x < 150 && y < 150 { 255 } else { 0 })).collect();
let objects = vec![
(
"/Type /XObject /Subtype /Image /Width 300 /Height 300 /ColorSpace /DeviceGray /BitsPerComponent 8 /SMask 6 0 R".to_string(),
vec![0x80; 90_000],
),
("/Type /XObject /Subtype /Image /Width 300 /Height 300 /ColorSpace /DeviceGray /BitsPerComponent 8".to_string(), mask),
];
let mut s = Session::new();
let id = s.open("large.pdf", None, Arc::new(images_pdf("/Big 5 0 R", b"q 100 0 0 100 0 0 cm /Big Do Q", &objects)), None).unwrap();
let d = s.get(id).unwrap();
// Just inside and just outside the showing quarter, along each axis.
assert_eq!(d.page_image_at(0, [45.0, 55.5]), Some(0));
assert_eq!(d.page_image_at(0, [45.0, 44.0]), None);
assert_eq!(d.page_image_at(0, [49.0, 80.0]), Some(0));
assert_eq!(d.page_image_at(0, [56.0, 80.0]), None);
}
/// `data` compressed with Flate, as a stream's bytes.
fn flated(data: &[u8]) -> Vec<u8> {
pdfcraft_cos::Stream::flate(pdfcraft_cos::Dict::default(), data).raw.to_vec()
}
/// #3069 review: a showing pixel that crosses from one grid cell into the next marks both. In a
/// 257-pixel-wide picture on a 256-cell grid, pixel 1 starts in cell 0 and ends in cell 1; a point
/// on its right part, in cell 1, picks the picture.
#[test]
fn a_showing_pixel_marks_every_grid_cell_it_reaches_into() {
let mut mask = vec![0u8; 257];
mask[1] = 255;
let objects = vec![
("/Type /XObject /Subtype /Image /Width 257 /Height 1 /ColorSpace /DeviceGray /BitsPerComponent 8 /SMask 6 0 R".to_string(), vec![0x80; 257]),
("/Type /XObject /Subtype /Image /Width 257 /Height 1 /ColorSpace /DeviceGray /BitsPerComponent 8".to_string(), mask),
];
let mut s = Session::new();
let id = s.open("wide.pdf", None, Arc::new(images_pdf("/Wide 5 0 R", b"q 257 0 0 10 0 0 cm /Wide Do Q", &objects)), None).unwrap();
let d = s.get(id).unwrap();
let image = &d.page_images(0)[0];
for x in [1.2, 1.5, 1.8] {
assert!(d.image_shows_at(image, [x, 5.0]), "pixel 1 shows at x = {x}");
}
assert!(!d.image_shows_at(image, [5.5, 5.0]), "pixel 5 is transparent");
}
/// #3069 review: a soft mask larger than the opacity grid's decoding limit keeps the picture's
/// whole box, however small the picture: the mask would be decoded in full before being scaled
/// to the picture's size.
#[test]
fn a_picture_whose_soft_mask_is_too_large_keeps_its_whole_box() {
// 8000 × 8001 pixels, just past 64 million; its left quarter shows, so once scaled to the
// picture's two pixels the left one shows and the right one doesn't.
let (w, h) = (8000usize, 8001usize);
let row: Vec<u8> = (0..w).map(|x| if x < w / 4 { 255 } else { 0 }).collect();
let mask = flated(&row.repeat(h));
let objects = vec![
("/Type /XObject /Subtype /Image /Width 2 /Height 1 /ColorSpace /DeviceGray /BitsPerComponent 8 /SMask 6 0 R".to_string(), vec![0x80; 2]),
(format!("/Type /XObject /Subtype /Image /Width {w} /Height {h} /ColorSpace /DeviceGray /BitsPerComponent 8 /Filter /FlateDecode"), mask),
];
let mut s = Session::new();
let id = s.open("mask.pdf", None, Arc::new(images_pdf("/Small 5 0 R", b"q 100 0 0 100 0 0 cm /Small Do Q", &objects)), None).unwrap();
let d = s.get(id).unwrap();
assert!(d.image_shows_at(&d.page_images(0)[0], [75.0, 50.0]), "the whole box, without decoding the mask");
}
/// #3069 review: a picture or soft mask whose stream inflates far past what its declared size
/// needs keeps the picture's whole box, rather than being decoded in full on the first hover.
#[test]
fn picture_streams_that_inflate_past_their_size_keep_the_whole_box() {
let flate = "/Filter /FlateDecode";
let image = |extra: &str, data: Vec<u8>| {
(format!("/Type /XObject /Subtype /Image /Width 2 /Height 1 /ColorSpace /DeviceGray /BitsPerComponent 8 {extra}"), data)
};
let huge = || flated(&[255u8, 0].repeat(4 << 20));
let objects = vec![
image(&format!("{flate} /SMask 7 0 R"), huge()), // 5: its samples inflate to 8 MiB
image("/SMask 9 0 R", vec![0x80; 2]), // 6: its mask inflates to 8 MiB
image("", vec![255, 0]), // 7: the left half shows
image(&format!("{flate} /SMask 7 0 R"), flated(&[9, 9])), // 8: as declared
image(flate, huge()), // 9: 6's mask
];
let content = b"q 100 0 0 100 0 0 cm /A Do Q q 100 0 0 100 0 100 cm /B Do Q q 100 0 0 100 0 200 cm /C Do Q";
let mut s = Session::new();
let id = s.open("inflate.pdf", None, Arc::new(images_pdf("/A 5 0 R /B 6 0 R /C 8 0 R", content, &objects)), None).unwrap();
let d = s.get(id).unwrap();
let images = d.page_images(0);
assert_eq!(images.len(), 3);
assert!(d.image_shows_at(&images[0], [75.0, 50.0]), "the picture's samples are too large: its whole box");
assert!(d.image_shows_at(&images[1], [75.0, 150.0]), "its soft mask's samples are too large: its whole box");
assert!(!d.image_shows_at(&images[2], [75.0, 250.0]), "Flate data as large as declared is read");
assert!(d.image_shows_at(&images[2], [25.0, 250.0]));
}
/// A form saved with its pages whose signature box sits deeper than the 32 nested fields looked
/// through counts as signed, as the xfa crate counts it, so it is left as saved rather than laid
/// out again over a signature that may be there; nested less deep, unsigned, it is laid out.
+38 -3
View File
@@ -157,17 +157,52 @@ impl Document {
if !self.marks().contains(&kind) {
return Ok(None);
}
self.unmarked_by(false, |cos| {
let n = pdfcraft_model::pages(cos).len();
pdfcraft_edit::remove_marks(cos, &(0..n).collect::<Vec<_>>(), kind)
})
}
/// The pages under the one header and footer recorded with `old`: without it and without what
/// is drawn after it on its pages, with every other mark under it. Update of that header and
/// footer puts the new one in its place (#5785), so its preview draws the draft on these and
/// [`Self::over_header_footer`] over the draft. `None` when nothing records `old`. Read-only,
/// like [`Self::without_marks`].
pub fn without_header_footer(&self, old: &pdfcraft_edit::HeaderFooter) -> Result<Option<UnmarkedPages>, String> {
if !self.marks().contains(&crate::MarkKind::HeaderFooter) {
return Ok(None);
}
// A header and footer gone since the dialog read it removes nothing here: the thumbnail is the page.
self.unmarked_by(false, |cos| pdfcraft_edit::under_header_footer(cos, old).or(Ok(0)))
}
/// What is drawn after the header and footer recorded with `old` on its pages, alone on
/// transparent pages: what Update keeps over the one replacing it. `None` when nothing is.
/// Read-only, like [`Self::without_marks`].
pub fn over_header_footer(&self, old: &pdfcraft_edit::HeaderFooter) -> Result<Option<UnmarkedPages>, String> {
if !self.marks().contains(&crate::MarkKind::HeaderFooter) {
return Ok(None);
}
self.unmarked_by(true, |cos| pdfcraft_edit::over_header_footer(cos, old))
}
/// A copy of the document with `remove` applied, for the preview, on `transparent` pages:
/// `None` when it removed nothing.
fn unmarked_by(
&self,
transparent: bool,
remove: impl FnOnce(&mut pdfcraft_cos::Document) -> Result<usize, pdfcraft_edit::EditError>,
) -> Result<Option<UnmarkedPages>, String> {
guard(|| {
let editor = self.editor.as_ref().ok_or("the document can't be read")?;
let mut cos = editor.cos.clone();
let n = pdfcraft_model::pages(&cos).len();
if pdfcraft_edit::remove_marks(&mut cos, &(0..n).collect::<Vec<_>>(), kind).map_err(|e| e.to_string())? == 0 {
if remove(&mut cos).map_err(|e| e.to_string())? == 0 {
return Ok(None);
}
let bytes = Arc::new(pdfcraft_cos::write_incremental(&cos, &pdfcraft_cos::SaveOptions::default()).map_err(|e| e.to_string())?);
Ok(Some(UnmarkedPages {
bytes,
config: self.config.clone(),
config: RenderConfig { transparent, ..self.config.clone() },
parsed: None,
#[cfg(test)]
builds: 0,
+53 -4
View File
@@ -67,6 +67,8 @@ struct Clock {
#[cfg(not(target_arch = "wasm32"))]
started: std::time::Instant,
budget_ms: u64,
/// Time the scripts spent waiting for the user: not counted.
waited: std::time::Duration,
}
impl Clock {
@@ -75,17 +77,23 @@ impl Clock {
#[cfg(not(target_arch = "wasm32"))]
started: std::time::Instant::now(),
budget_ms,
waited: std::time::Duration::ZERO,
}
}
/// Leave `waited` out of the time spent: the time the scripts waited for the user isn't theirs.
fn extend(&mut self, waited: std::time::Duration) {
self.waited = self.waited.saturating_add(waited);
}
fn spent(&self) -> bool {
#[cfg(not(target_arch = "wasm32"))]
{
self.started.elapsed() >= std::time::Duration::from_millis(self.budget_ms)
self.started.elapsed().saturating_sub(self.waited) >= std::time::Duration::from_millis(self.budget_ms)
}
#[cfg(target_arch = "wasm32")]
{
let _ = self.budget_ms;
let _ = (self.budget_ms, self.waited);
false
}
}
@@ -135,11 +143,33 @@ pub(crate) struct XfaRun<'a> {
/// start and each script's own): 1, unless the session was given another
/// ([`crate::Session::with_xfa_time_scale`]).
pub time_scale: u32,
/// The answers to the event's message boxes.
pub answers: XfaAnswers,
/// The form was laid out again: its pages, widgets and fields were replaced, so the edit
/// must rebuild the document's page and field lists, not only refresh their values.
pub relaid: bool,
}
/// The answers to one event's message boxes (`xfa.host.messageBox`, `$host.messageBox`,
/// `app.alert`): its click script and the calculations after it take them in order, each
/// script starting after the ones the scripts before it took. Past them, a message box asks the
/// user when `prompts` is set (an app's button click, run on a worker:
/// [`crate::Session::start_javascript_target`]), and otherwise gets its buttons' safe default.
#[derive(Clone, Debug, Default)]
pub(crate) struct XfaAnswers {
/// The answers, in order (`None`: closed without picking a button).
pub given: Vec<Option<String>>,
/// Message boxes the event's scripts have shown so far.
pub used: usize,
/// Where the scripts' questions go, for the viewer to ask.
#[cfg(not(target_arch = "wasm32"))]
pub prompts: Option<std::sync::mpsc::Sender<crate::js::InteractiveEvent>>,
/// Questions the event has asked, across the script sessions it uses
/// ([`XfaSession::with_prompts`]).
#[cfg(not(target_arch = "wasm32"))]
pub asked: Arc<std::sync::atomic::AtomicUsize>,
}
/// The script engine's copies of a form's property trees, by the address of the tree each was
/// made from: made the first time a script of the form needs one, then shared by every later
/// script and event of that form. They are kept in the form's template
@@ -567,7 +597,17 @@ impl<'a, 'b> Runner<'a, 'b> {
fn session(&mut self) -> &mut XfaSession {
let doc_info = XfaDoc { file_name: String::new(), page: 0, page_count: self.run.page_count, highlight: self.run.highlight };
let scale = self.run.time_scale;
self.session.get_or_insert_with(|| XfaSession::new(doc_info).with_time_scale(scale))
#[cfg(not(target_arch = "wasm32"))]
let (prompts, asked) = (self.run.answers.prompts.clone(), Arc::clone(&self.run.answers.asked));
self.session.get_or_insert_with(|| {
let session = XfaSession::new(doc_info).with_time_scale(scale);
#[cfg(not(target_arch = "wasm32"))]
let session = match prompts {
Some(p) => session.with_prompts(p, asked),
None => session,
};
session
})
}
/// Give the object at `som` the value `text` in the data and in the live form (refreshed
@@ -1015,7 +1055,14 @@ impl<'a, 'b> Runner<'a, 'b> {
self.runs += 1;
#[cfg(test)]
self.check_live();
let event = XfaEvent { activity: ev.activity.clone(), target: ev.som.clone(), new_text: new_text.to_string(), prev_text: String::new() };
let used = self.run.answers.used;
let event = XfaEvent {
activity: ev.activity.clone(),
target: ev.som.clone(),
new_text: new_text.to_string(),
prev_text: String::new(),
answers: self.run.answers.given.get(used..).unwrap_or_default().to_vec(),
};
let tpl = self.tpl;
let root = match &self.js_root {
Some(r) => Arc::clone(r),
@@ -1039,6 +1086,8 @@ impl<'a, 'b> Runner<'a, 'b> {
// The thread is left to the runaway script: nothing more is sent to it.
self.session = None;
}
self.clock.extend(o.waited);
self.run.answers.used = used.saturating_add(o.messages);
self.console(o.console.iter().cloned());
for n in &o.notes {
self.error(format!("{} ({}): {n}", ev.som, ev.activity));
+1
View File
@@ -243,6 +243,7 @@ pub(crate) fn xfa_after_data_change(doc: &mut pdfcraft_cos::Document, cx: &mut E
ran_away: false,
highlight,
time_scale: cx.xfa_time_scale,
answers: Default::default(),
relaid: false,
};
let r = guard(|| xfa::on_data_replaced(doc, &tpl, calculate, &mut run))
+6
View File
@@ -74,6 +74,12 @@ pub enum FormError {
/// checked before any of the field's scripts run.
#[error("{0}")]
Format(String),
/// The field's validate action (ISO 32000-2 Table 199 `/V`: it "may check the new value
/// for validity") refused the value: a range it is outside, or a script that set `event.rc`
/// to false. The message is the script's alert, or the range's. Nothing was changed, and
/// the field keeps the value it had.
#[error("{0}")]
Rejected(String),
#[error("{0}")]
Cos(#[from] pdfcraft_cos::CosError),
}
+6 -1
View File
@@ -130,7 +130,12 @@ pub(crate) fn accept(doc: &mut Document, f: &Field, value: &str, scripts: &mut d
refresh_field |= r.changes.iter().any(|change| change.name == f.name && change.object.is_none_or(|id| id == f.obj));
apply_changes(doc, &r.changes, &f.name, Some(f.obj), scripts)?;
if !r.rc {
return Err(FormError::Invalid(r.message.unwrap_or_else(|| format!("{default} [ {} ]", f.name))));
let message = r.message.unwrap_or_else(|| format!("{default} [ {} ]", f.name));
// A keystroke refusal is about the typing; a validate refusal is about the value.
return Err(match event {
FieldEvent::Validate => FormError::Rejected(message),
_ => FormError::Invalid(message),
});
}
v = r.value;
}
+54 -2
View File
@@ -1945,7 +1945,7 @@ fn formats_validation_and_calculations_run_like_acrobat() {
);
assert_eq!(
set_value(&mut doc, "Qty", &FieldValue::Text("120".into())),
Err(FormError::Invalid("Invalid value: must be greater than or equal to 1 and less than or equal to 99.".into()))
Err(FormError::Rejected("Invalid value: must be greater than or equal to 1 and less than or equal to 99.".into()))
);
assert_eq!(field(&fields(&doc), "Qty").value, ["2"]);
// Dates: stored as typed, shown in the format; impossible dates are refused.
@@ -2079,7 +2079,7 @@ fn unsupported_first_validation_call_preserves_custom_script_dispatch() {
let mut scripts = RejectingInterpreter { calls: 0 };
assert_eq!(
set_value_with(&mut doc, "amount", &FieldValue::Text("10".into()), &mut scripts),
Err(FormError::Invalid("custom validation ran".into()))
Err(FormError::Rejected("custom validation ran".into()))
);
assert_eq!(scripts.calls, 1);
assert_eq!(field(&fields(&doc), "amount").value, ["20"]);
@@ -7114,6 +7114,58 @@ fn locked_button_export_edits_leave_the_document_unchanged() {
}
}
/// A validate action (ISO 32000-2 Table 199 `/V`) that refuses a value is a rejection the
/// caller can tell apart: the field keeps its value and the interface drops the typing. A
/// keystroke refusal is not one: it is about the typing, which the user may want to fix.
#[test]
fn a_validate_refusal_is_a_rejection_and_a_keystroke_refusal_is_not() {
use crate::af::Validate;
struct Checks;
impl Scripts for Checks {
fn run(&mut self, event: FieldEvent, script: &str, _: &Field, value: &str, _: &[Field], _: &Document) -> ScriptResult {
let (rc, message) = match (event, script) {
(FieldEvent::Validate, "short") => (value.chars().count() <= 3, Some("At most 3 characters".to_string())),
(FieldEvent::Validate, "never") => (false, None),
(FieldEvent::Keystroke, "digits") => (value.chars().all(|c| c.is_ascii_digit()), Some("Digits only".to_string())),
_ => (true, None),
};
ScriptResult { rc, value: value.to_string(), value_set: false, changes: Vec::new(), message: if rc { None } else { message } }
}
}
let mut doc = one_page();
for (i, name) in ["G_range", "H_short", "code", "never"].into_iter().enumerate() {
let y = 10.0 + 30.0 * i as f64;
add_field(&mut doc, 0, [10.0, y, 100.0, y + 20.0], &NewField::Text { multiline: false }, Some(name)).unwrap();
}
set_props(&mut doc, "G_range", &FieldProps { validate: Some(Validate::Range { min: Some(1.0), max: Some(100.0) }), ..FieldProps::default() })
.unwrap();
set_field_script(&mut doc, "H_short", "validate", Some("short")).unwrap();
set_field_script(&mut doc, "code", "keystroke", Some("digits")).unwrap();
set_field_script(&mut doc, "never", "validate", Some("never")).unwrap();
let set = |doc: &mut Document, name: &str, v: &str| set_value_with(doc, name, &FieldValue::Text(v.into()), &mut Checks);
assert_eq!(
set(&mut doc, "G_range", "150"),
Err(FormError::Rejected("Invalid value: must be greater than or equal to 1 and less than or equal to 100.".into()))
);
assert!(field(&fields(&doc), "G_range").value.is_empty(), "the field keeps its (blank) value");
assert_eq!(set(&mut doc, "G_range", "50"), Ok(()));
assert_eq!(field(&fields(&doc), "G_range").value, ["50"], "a value in range commits");
assert_eq!(
set(&mut doc, "G_range", "0"),
Err(FormError::Rejected("Invalid value: must be greater than or equal to 1 and less than or equal to 100.".into()))
);
assert_eq!(field(&fields(&doc), "G_range").value, ["50"], "and stays when the next one is refused");
assert_eq!(set(&mut doc, "H_short", "abcd"), Err(FormError::Rejected("At most 3 characters".into())), "the script's alert is the message");
assert!(field(&fields(&doc), "H_short").value.is_empty());
assert_eq!(set(&mut doc, "H_short", "abc"), Ok(()));
assert_eq!(set(&mut doc, "never", "x"), Err(FormError::Rejected("The value entered is not valid for the field [ never ]".into())), "no alert");
assert_eq!(set(&mut doc, "code", "x1"), Err(FormError::Invalid("Digits only".into())), "a keystroke refusal is not a rejected value");
assert_eq!(set(&mut doc, "code", "12"), Ok(()));
}
/// A widget reached from `/Fields` as an unnamed kid of a plain field, whose own `/Parent` is an
/// unlisted password field: the quick check must still read that `/Parent` chain.
#[test]
+1 -1
View File
@@ -331,7 +331,7 @@ fn write_value_impl(doc: &mut Document, f: &Field, value: &FieldValue, scripts:
}
// Keystroke (on commit) and Validate, as Acrobat runs them before accepting a value.
let t = &f.actions.keystroke(&f.name, t).map_err(FormError::Format)?;
af::validate(&f.actions.validate, t).map_err(FormError::Invalid)?;
af::validate(&f.actions.validate, t).map_err(FormError::Rejected)?;
let (t, refresh_field) = if resetting { (t.clone(), false) } else { scripting::accept(doc, f, t, scripts)? };
let shadow = t.is_empty() && crate::author::ancestor_sets(doc, f.obj, b"V");
doc.update_dict(f.obj, |d| {
+2
View File
@@ -138,6 +138,7 @@ pub(crate) fn run_formcalc_at(
Err(e) => return XfaOutcome { error: Some(e), ..Default::default() },
};
let mut host = XHost::new(root, reuse, &event.target, doc);
host.answers = event.answers.clone();
#[cfg(target_arch = "wasm32")]
let _ = deadline;
let mut interp = Interp {
@@ -186,6 +187,7 @@ pub(crate) fn run_formcalc_at(
out.notes = host.notes();
out.effects = host.effects;
out.console = host.console;
out.messages = host.messages;
clip_result(&mut out);
out
}
+11 -4
View File
@@ -249,10 +249,17 @@ impl Interp<'_> {
let title = Some(self.arg_str(args, 1)?).filter(|t| !t.is_empty());
let icon = MessageIcon::from_code(Some(self.arg_num(args, 2)?));
let buttons = MessageButtons::from_code(Some(self.arg_num(args, 3)?));
self.h.push(XfaEffect::MessageBox(Message { text, title, icon, buttons }));
// Always OK for now: the viewer can't ask the user and run the script on
// with the answer yet (#4291).
Ok(Val::Num(1.0))
// The button picked: 1 OK, 2 Cancel, 3 No, 4 Yes. Time spent waiting for the
// user isn't the script's: its deadline moves on by it.
#[cfg(not(target_arch = "wasm32"))]
let asked = std::time::Instant::now();
let reply = self.h.message_box(Message { text, title, icon, buttons })?;
#[cfg(not(target_arch = "wasm32"))]
if crate::interaction::has_host() {
let waited = asked.elapsed();
self.deadline = self.deadline.and_then(|d| d.checked_add(waited));
}
Ok(Val::Num(f64::from(reply)))
}
"resetdata" => {
let list = self.arg_str(args, 0)?;
+6 -21
View File
@@ -78,33 +78,18 @@ pub(crate) fn message_box_message(args: &[JsValue], ctx: &mut Context) -> JsResu
}
/// `app.alert(cMsg, nIcon, nType, cTitle)`: records the message with its title, icon and buttons,
/// given in that order or as one object with those keys, and returns 1 (the OK button).
/// given in that order or as one object with those keys, and returns the button picked (1 OK,
/// 2 Cancel, 3 No, 4 Yes). Where nobody can be asked (the web build, a script run outside a
/// document's session), that is the buttons' safe default, as when the dialog is closed.
fn alert(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
let m = alert_message(args, ctx)?;
host(ctx)?.borrow_mut().alert(m.clone());
if !crate::interaction::has_host() {
return Ok(JsValue::from(1));
return Ok(JsValue::from(i32::from(m.buttons.safe_default())));
}
let answer = crate::interaction::ask(crate::interaction::Prompt::Alert(m.clone()))?;
let fallback = match m.buttons {
MessageButtons::Ok => "1",
MessageButtons::YesNo => "3",
_ => "2",
};
let answer = answer.as_deref().unwrap_or(fallback);
let accepted = match m.buttons {
MessageButtons::Ok => ["1"].as_slice(),
MessageButtons::OkCancel => ["1", "2"].as_slice(),
MessageButtons::YesNo => ["3", "4"].as_slice(),
MessageButtons::YesNoCancel => ["2", "3", "4"].as_slice(),
};
if answer == "1" && !accepted.contains(&"1") {
return Ok(JsValue::from(2));
}
if !accepted.contains(&answer) {
return Err(error("invalid alert response"));
}
Ok(JsValue::from(answer.parse::<i32>().unwrap_or(2)))
let reply = m.buttons.reply(answer.as_deref()).ok_or_else(|| error("invalid alert response"))?;
Ok(JsValue::from(i32::from(reply)))
}
/// `app.beep()`: queues a request to beep.
+8 -1
View File
@@ -21,6 +21,8 @@ pub enum InteractiveEvent {
Prompt(Prompt, Sender<Option<String>>),
Complete(Outcome),
}
/// Most prompts one script invocation (an AcroForm script, an XFA event) shows the user.
pub const MAX_PROMPTS: usize = 32;
thread_local! { static HOST:RefCell<Option<(Sender<InteractiveEvent>,usize)>>=const {RefCell::new(None)}; }
/// Tell alert/menu helpers whether this worker has an interactive or deterministic reply channel.
pub(crate) fn has_host() -> bool {
@@ -31,12 +33,17 @@ pub(crate) fn has_host() -> bool {
pub(crate) fn set_host(host: Option<Sender<InteractiveEvent>>) {
HOST.with(|h| *h.borrow_mut() = host.map(|h| (h, 0)));
}
/// Whether the invocation may still ask: it has a prompt channel and has asked fewer than
/// [`MAX_PROMPTS`] questions.
pub(crate) fn can_ask() -> bool {
HOST.with(|h| h.borrow().as_ref().is_some_and(|(_, n)| *n < MAX_PROMPTS))
}
/// Charge one prompt to the invocation's budget: the channel to send it on, if the worker has one.
fn reserve() -> JsResult<Option<Sender<InteractiveEvent>>> {
HOST.with(|h| {
let mut h = h.borrow_mut();
let Some((tx, n)) = h.as_mut() else { return Ok(None) };
if *n >= 32 {
if *n >= MAX_PROMPTS {
return Err(error("too many interactive prompts"));
}
*n += 1;
+35
View File
@@ -266,6 +266,41 @@ impl MessageButtons {
MessageButtons::YesNoCancel => "yes_no_cancel",
}
}
/// What a script receives when nobody picks a button (closing the dialog, no answer given):
/// OK (1) when that is the only button, No (3) for Yes/No, otherwise Cancel (2).
pub fn safe_default(self) -> u8 {
match self {
MessageButtons::Ok => 1,
MessageButtons::YesNo => 3,
MessageButtons::OkCancel | MessageButtons::YesNoCancel => 2,
}
}
/// The number a script receives for `answer`, the button picked as the references number
/// them (1 OK, 2 Cancel, 3 No, 4 Yes): no answer is [`MessageButtons::safe_default`], and OK
/// where these buttons have none is Cancel. `None`: an answer these buttons can't give.
pub fn reply(self, answer: Option<&str>) -> Option<u8> {
let Some(answer) = answer else { return Some(self.safe_default()) };
let n = match answer {
"1" => 1,
"2" => 2,
"3" => 3,
"4" => 4,
_ => return None,
};
let accepted: &[u8] = match self {
MessageButtons::Ok => &[1],
MessageButtons::OkCancel => &[1, 2],
MessageButtons::YesNo => &[3, 4],
MessageButtons::YesNoCancel => &[2, 3, 4],
};
match n {
1 if !accepted.contains(&1) => Some(2),
n if accepted.contains(&n) => Some(n),
_ => None,
}
}
}
/// `code` as one of the numbers 0 to 3 the references define, when it is exactly one.
+122 -6
View File
@@ -504,9 +504,32 @@ fn app_alert_falls_back_on_bad_icon_and_button_numbers() {
assert_eq!(m, Message::plain("Hi"), "{bad}");
}
assert_eq!(alerted("'Hi', '2', '3'"), Message { icon: MessageIcon::Question, buttons: MessageButtons::YesNoCancel, ..Message::plain("Hi") });
// Every call still answers OK (1) until answers are asked for (#4291).
let o = go("event.value = String(app.alert('Delete?', 2, 2));", &Event::field("Mouse Up", "agree", ""));
assert_eq!(o.value, "1");
// Outside a document's session (and on the web build) nobody can be asked: each call gets
// its buttons' safe default, as a closed dialog does (#4291).
for (buttons, want) in [(0, "1"), (1, "2"), (2, "3"), (3, "2")] {
let o = go(&format!("event.value = String(app.alert('Delete?', 2, {buttons}));"), &Event::field("Mouse Up", "agree", ""));
assert_eq!(o.value, want, "{buttons}");
}
}
/// The number a script receives for each answer: the references' button numbers, checked
/// against the buttons shown, with no answer the safe default (#4291).
#[test]
fn message_replies_follow_the_buttons() {
use MessageButtons as B;
let cases = [
(B::Ok, [Some(1), Some(1), None, None, None]),
(B::OkCancel, [Some(2), Some(1), Some(2), None, None]),
(B::YesNo, [Some(3), Some(2), None, Some(3), Some(4)]),
(B::YesNoCancel, [Some(2), Some(2), Some(2), Some(3), Some(4)]),
];
for (buttons, want) in cases {
let got = [None, Some("1"), Some("2"), Some("3"), Some("4")].map(|a| buttons.reply(a));
assert_eq!(got, want, "{buttons:?}");
for bad in ["0", "5", " 4", "04", "yes", ""] {
assert_eq!(buttons.reply(Some(bad)), None, "{buttons:?} {bad}");
}
}
}
/// A title is cut to a message's length like the text, and both are charged to the run's byte
@@ -1242,9 +1265,35 @@ mod xfa_model {
assert_eq!(boxed("xfa.host.messageBox('Hi', null, 2.5, 'x')"), Message::plain("Hi"));
let m = boxed("xfa.host.messageBox('Hi', new Array(100000).join('t'))");
assert!(m.title.as_deref().is_some_and(|t| t.chars().count() <= 4_097));
// Answers are always OK for now (#4291).
let o = go("this.rawValue = xfa.host.messageBox('Delete?', 'T', 2, 2)", "form1[0].page1[0].qty[0]", "click");
assert!(o.effects.iter().any(|e| matches!(e, XfaEffect::SetValue { value, .. } if value == "1")), "{:?}", o.effects);
}
/// Run the JavaScript `script` as the go button's click, with `answers` to its message boxes.
fn answered(script: &str, answers: &[Option<&str>]) -> XfaOutcome {
let ev = XfaEvent {
activity: "click".into(),
target: "form1[0].page1[0].go[0]".into(),
answers: answers.iter().map(|a| a.map(String::from)).collect(),
..Default::default()
};
run_xfa(script, &ev, &XfaDoc::default(), &form(), Limits::default())
}
/// `xfa.host.messageBox` and `app.alert` in an XFA script return the button picked, from the
/// event's answers in order (#4291), so a script can branch on No and Cancel; past the
/// answers, where nobody can be asked, each gets its buttons' safe default.
#[test]
fn message_box_returns_the_answer_given() {
let script = "var r = [xfa.host.messageBox('Clear?', 'T', 2, 2), app.alert('Sure?', 2, 3), xfa.host.messageBox('Saved')]; r.join(',')";
let o = answered(script, &[Some("4"), Some("2"), None]);
assert_eq!((o.result.as_deref(), o.error.as_deref(), o.messages), (Some("4,2,1"), None, 3), "{o:?}");
let o = answered(script, &[Some("3"), Some("4")]);
assert_eq!(o.result.as_deref(), Some("3,4,1"), "{o:?}");
// No answers: the safe defaults (No; Cancel; OK).
let o = answered(script, &[]);
assert_eq!(o.result.as_deref(), Some("3,2,1"), "{o:?}");
// An answer the buttons can't give fails the script, naming it.
let o = answered("xfa.host.messageBox('Clear?', 'T', 2, 2)", &[Some("2")]);
assert!(o.error.as_deref().is_some_and(|e| e.contains("message box 1 (2)") && e.contains("yes_no")), "{o:?}");
}
/// `app.alert` in an XFA form's script reads its own order (`cMsg, nIcon, nType, cTitle`)
@@ -2065,6 +2114,35 @@ $host.gotoURL("https://example.org")"#,
assert!(matches!(o.effects.as_slice(), [XfaEffect::MessageBox(m)] if m.title.as_deref().is_some_and(|t| t.chars().count() <= 4_097)));
}
/// FormCalc's `$host.messageBox` returns the button picked, from the event's answers in
/// order, as the JavaScript one does (#4291).
#[test]
fn formcalc_message_box_returns_the_answer_given() {
let run = |answers: &[Option<&str>]| {
let ev = XfaEvent {
activity: "click".into(),
target: "form1[0].page1[0].go[0]".into(),
answers: answers.iter().map(|a| a.map(String::from)).collect(),
..Default::default()
};
run_formcalc(
"Concat($host.messageBox(\"Clear?\", \"T\", 2, 3), \",\", $host.messageBox(\"Sure?\", \"\", 2, 1))",
&ev,
&XfaDoc::default(),
&form(),
Limits::default(),
)
};
let o = run(&[Some("3"), Some("1")]);
assert_eq!(o.result.as_deref(), Some("3,1"), "{o:?}");
let o = run(&[Some("4")]);
assert_eq!(o.result.as_deref(), Some("4,2"), "{o:?}");
let o = run(&[None, None]);
assert_eq!(o.result.as_deref(), Some("2,2"), "{o:?}");
let o = run(&[Some("9")]);
assert!(o.error.as_deref().is_some_and(|e| e.contains("message box 1 (9)")), "{o:?}");
}
fn run_hostile_formcalc(script: &str) -> XfaOutcome {
let ev = XfaEvent { activity: "calculate".into(), target: "form1[0].page1[0].total[0]".into(), ..Default::default() };
let doc = XfaDoc::default();
@@ -2133,6 +2211,44 @@ mod session {
assert_eq!(o.result.as_deref(), Some("4:hidden"), "{o:?}");
}
/// A session that can ask passes each message box's question on and gives the script the
/// answer, in JavaScript and FormCalc alike (#4291). The user's time isn't the script's: one
/// answered after its time limit has passed still finishes, and says how long it waited.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn a_session_that_can_ask_waits_for_the_answer_with_its_clock_stopped() {
use crate::interaction::{InteractiveEvent, Prompt};
let (tx, rx) = std::sync::mpsc::channel();
let answerer = std::thread::spawn(move || {
let mut asked = Vec::new();
for answer in ["4", "3", "2"] {
let Ok(InteractiveEvent::Prompt(Prompt::Alert(m), reply)) = rx.recv() else { break };
asked.push(m.text);
// Longer than the scripts' time limit below.
std::thread::sleep(std::time::Duration::from_millis(400));
let _ = reply.send(Some(answer.to_string()));
}
asked
});
let mut s = XfaSession::new(XfaDoc::default()).with_prompts(tx, Default::default());
let mut js = script("xfa.host.messageBox('Clear?', 'T', 2, 2) + ',' + app.alert('Sure?', 2, 2)", false, "form1[0].page1[0].go[0]", "click");
js.timeout = std::time::Duration::from_millis(300);
let o = s.run(js);
assert_eq!((o.result.as_deref(), o.error.as_deref(), o.abandoned), (Some("4,3"), None, false), "{o:?}");
assert!(o.waited >= std::time::Duration::from_millis(800), "{:?}", o.waited);
// FormCalc keeps its own deadline, read as it works: it works on after the answer.
let mut fc = script(
"var r = $host.messageBox(\"Save?\", \"\", 2, 3)\nvar i = 0\nwhile (i < 20000) do i = i + 1 endwhile\nr",
true,
"form1[0].page1[0].go[0]",
"click",
);
fc.timeout = std::time::Duration::from_millis(300);
assert_eq!(s.run(fc).result.as_deref(), Some("2"));
drop(s);
assert_eq!(answerer.join().unwrap_or_default(), ["Clear?", "Sure?", "Save?"]);
}
/// JavaScript and FormCalc scripts run in turn in one session, each on the form the caller
/// sends: nothing an earlier script changed or defined leaks into the next, a failing script
/// doesn't end the session, and hundreds of scripts run on its one thread.
+11 -9
View File
@@ -43,23 +43,25 @@ fn set_runtime_highlight(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> Js
Ok(JsValue::undefined())
}
/// `xfa.host.messageBox(message, title, icon, buttons)`: records the message with its title,
/// icon and buttons, its text and title cut to [`MAX_LINE`] characters, and returns 1.
/// Shows message box `m` and returns the button picked ([`XHost::message_box`]).
fn show(ctx: &mut Context, m: crate::Message) -> JsResult<JsValue> {
let reply = host(ctx)?.borrow_mut().message_box(m).map_err(super::error)?;
Ok(JsValue::from(f64::from(reply)))
}
/// `xfa.host.messageBox(message, title, icon, buttons)`: shows the message with its title,
/// icon and buttons, its text and title cut to [`MAX_LINE`] characters, and returns the button
/// picked: 1 OK, 2 Cancel, 3 No, 4 Yes.
fn message_box(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
let m = crate::globals::message_box_message(args, ctx)?;
effect(ctx, XfaEffect::MessageBox(m))?;
// Always OK for now: the viewer can't ask the user and run the script on with the answer
// yet (#4291).
Ok(JsValue::from(1.0))
show(ctx, m)
}
/// `app.alert(cMsg, nIcon, nType, cTitle)` in an XFA form's script: the same message box, its
/// arguments in `app.alert`'s order (or one object with those keys).
fn app_alert(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
let m = crate::globals::alert_message(args, ctx)?;
effect(ctx, XfaEffect::MessageBox(m))?;
// The OK button, as for `messageBox` (#4291).
Ok(JsValue::from(1.0))
show(ctx, m)
}
/// `xfa.host.resetData(names)`: asks to reset the comma-separated fields, or every field when
+34
View File
@@ -110,6 +110,10 @@ pub(crate) struct XHost {
/// Bytes of edges and corners copied when a script reached sides a border doesn't list,
/// against [`super::props::MAX_COPIED`].
pub(super) copied: usize,
/// The answers to the script's message boxes ([`super::XfaEvent::answers`]).
pub(crate) answers: Vec<Option<String>>,
/// Message boxes shown so far ([`super::XfaOutcome::messages`]).
pub(crate) messages: usize,
}
impl XHost {
@@ -153,9 +157,39 @@ impl XHost {
prop_writes: super::props::PropWrites::new(),
dropped_prop_writes: 0,
copied: 0,
answers: Vec::new(),
messages: 0,
}
}
/// Show message box `m` and return the button picked: the next of the event's answers
/// (headless runs); past them, the user's answer when the viewer can ask (an app's button
/// click: the script waits on its thread, as an AcroForm script's `app.alert` does), or
/// else the buttons' safe default. Past [`crate::interaction::MAX_PROMPTS`] questions nobody
/// is asked and the safe default is given, as it is when the click's questions are spent
/// across its script sessions: a form follows the same path either way. `Err`: an answer
/// `m`'s buttons can't give.
pub(crate) fn message_box(&mut self, m: Message) -> Result<u8, String> {
// Clipped before the viewer is asked, as the effect is: the dialog shows no more than is kept.
let m = Message { text: clip(m.text), title: m.title.map(clip), ..m };
let at = self.messages;
self.messages = self.messages.saturating_add(1);
let invalid = |answer: Option<&str>| {
let given: String = answer.unwrap_or("null").chars().take(32).collect();
format!("the answer to the script's message box {} ({given}) is not one of its buttons ({})", at.saturating_add(1), m.buttons.name())
};
let reply = match self.answers.get(at) {
Some(answer) => m.buttons.reply(answer.as_deref()).ok_or_else(|| invalid(answer.as_deref()))?,
None if crate::interaction::can_ask() => {
let answer = crate::interaction::ask(crate::interaction::Prompt::Alert(m.clone())).map_err(|e| e.to_string())?;
m.buttons.reply(answer.as_deref()).ok_or_else(|| invalid(answer.as_deref()))?
}
None => m.buttons.safe_default(),
};
self.push(XfaEffect::MessageBox(m));
Ok(reply)
}
/// Room for `bytes` more bytes of kept text: charged when there is, a drop counted when not.
pub(super) fn room(&mut self, bytes: usize) -> bool {
match self.kept.checked_add(bytes).filter(|k| *k <= MAX_PAYLOAD) {
+12
View File
@@ -64,6 +64,12 @@ pub struct XfaEvent {
pub target: String,
pub new_text: String,
pub prev_text: String,
/// Answers to the script's message boxes, in order: each `xfa.host.messageBox`,
/// `$host.messageBox` or `app.alert` takes the next (`None`: closed without picking a
/// button), checked against its buttons by [`crate::MessageButtons::reply`]. Past the end,
/// a message asks the user when the viewer can ask ([`crate::xfa_session::XfaSession::with_prompts`]),
/// and otherwise gets its buttons' safe default.
pub answers: Vec<Option<String>>,
}
/// About the document.
@@ -141,6 +147,12 @@ pub struct XfaOutcome {
/// The script ran past its time limit and was left running on its own thread (the engine
/// can't interrupt it): the caller should run no more of this form's scripts.
pub abandoned: bool,
/// How many message boxes the script showed: the answers it took from
/// [`XfaEvent::answers`], so the next script of the event starts after them.
pub messages: usize,
/// How long the script waited for the user to answer its message boxes: not counted
/// against its time limit, nor the event's.
pub waited: std::time::Duration,
}
/// Most nodes a snapshot may hold.
+3 -1
View File
@@ -143,7 +143,8 @@ pub(crate) fn run_here(
};
ctx.runtime_limits_mut().set_loop_iteration_limit(limits.loop_iterations);
ctx.runtime_limits_mut().set_recursion_limit(limits.recursion);
let host_state = XHost::new(root, reuse, &event.target, doc);
let mut host_state = XHost::new(root, reuse, &event.target, doc);
host_state.answers = event.answers.clone();
let current = host_state.current;
ctx.insert_data(RefCell::new(host_state));
let mut out = XfaOutcome::default();
@@ -174,6 +175,7 @@ pub(crate) fn run_here(
out.notes = h.notes();
out.effects = h.effects;
out.console = h.console;
out.messages = h.messages;
}
clip_result(&mut out);
out
+62 -2
View File
@@ -75,13 +75,22 @@ mod native {
use std::time::{Duration, Instant};
use super::{Script, run_script};
use crate::interaction::{InteractiveEvent, MAX_PROMPTS, Prompt};
use crate::xfa::{ENGINE_START_LIMIT, XfaDoc, XfaOutcome};
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
/// Longest a script waits for the user to answer one message box, as an AcroForm script's
/// prompt waits; then it gets the buttons' safe default.
const PROMPT_LIMIT: Duration = Duration::from_secs(300);
enum Reply {
/// The thread is up.
Ready,
/// The engine is ready for the script just sent: its time starts now.
Started,
/// The script asks the user (a message box) and waits for the answer.
Prompt(Prompt, Sender<Option<String>>),
Outcome(Box<XfaOutcome>),
}
@@ -99,11 +108,26 @@ mod native {
dead: Option<String>,
/// How long the engine has to be ready for a script ([`ENGINE_START_LIMIT`] by default).
start_limit: Duration,
/// Where the scripts' questions go, when the viewer can ask the user
/// ([`XfaSession::with_prompts`]), and how many the event has asked.
prompts: Option<(Sender<InteractiveEvent>, Arc<AtomicUsize>)>,
}
impl XfaSession {
pub fn new(doc: XfaDoc) -> XfaSession {
XfaSession { doc, worker: None, dead: None, start_limit: ENGINE_START_LIMIT }
XfaSession { doc, worker: None, dead: None, start_limit: ENGINE_START_LIMIT, prompts: None }
}
/// Let the scripts' message boxes ask the user: each question goes to `prompts` with a
/// sender for the answer, and the script waits on its thread (at most [`PROMPT_LIMIT`]
/// for each), its time limit stopped meanwhile. `asked` counts the event's questions,
/// across every session the event uses (a script turning field highlighting on or off
/// starts a new one): past [`MAX_PROMPTS`] nobody is asked and each message box gets its
/// buttons' safe default, so a form can't keep the user answering. Without it a message
/// box takes the event's answers, then its buttons' safe default.
pub fn with_prompts(mut self, prompts: Sender<InteractiveEvent>, asked: Arc<AtomicUsize>) -> XfaSession {
self.prompts = Some((prompts, asked));
self
}
/// Multiply the time the engine has to be ready for a script by `factor` (a script's
@@ -125,7 +149,26 @@ mod native {
let (to, inbox) = channel::<Box<Script>>();
let (reply, from) = channel::<Reply>();
let doc = self.doc.clone();
let asking = self.prompts.is_some();
let spawned = std::thread::Builder::new().name("pdfcraft-xfa-session".into()).stack_size(crate::SCRIPT_STACK).spawn(move || {
// The scripts' questions reach the session (which passes them on and stops
// the clock while the user answers) through the reply channel. The host is
// set once for the thread, so the prompt limit holds for the whole event.
if asking {
let (questions, asked) = channel::<InteractiveEvent>();
let forward = reply.clone();
let forwarder = std::thread::Builder::new().name("pdfcraft-xfa-prompts".into()).spawn(move || {
while let Ok(InteractiveEvent::Prompt(prompt, answer)) = asked.recv() {
if forward.send(Reply::Prompt(prompt, answer)).is_err() {
break;
}
}
});
// Without the forwarder nobody would answer: the scripts don't ask.
if forwarder.is_ok() {
crate::interaction::set_host(Some(questions));
}
}
crate::xfa::warm_up();
// The caller is gone when a send fails: nothing to report then.
let _ = reply.send(Reply::Ready);
@@ -164,6 +207,7 @@ mod native {
}
let timeout = script.timeout;
let start_limit = self.start_limit;
let prompts = self.prompts.clone();
let worker = match self.worker() {
Ok(w) => w,
Err(why) => return failed(why),
@@ -176,18 +220,34 @@ mod native {
// The engine's start, then the script's own time.
let (mut running, mut limit) = (false, start_limit);
let mut deadline = Instant::now().checked_add(limit);
let mut waited = Duration::ZERO;
loop {
let left = deadline.map_or(limit, |d| d.saturating_duration_since(Instant::now()));
match worker.from.recv_timeout(left) {
Ok(Reply::Outcome(o)) => {
Ok(Reply::Outcome(mut o)) => {
// A FormCalc script its own clock stopped reports as abandoned: the
// session ends as it does when the wait runs out first.
if o.abandoned {
self.dead = o.error.clone();
self.worker = None;
}
o.waited = waited;
return *o;
}
Ok(Reply::Prompt(prompt, answer)) => {
// The user's time isn't the script's: its clock stops until the answer.
let asked = Instant::now();
let (give, given) = channel();
let sent = prompts.as_ref().is_some_and(|(p, asked)| {
asked.fetch_add(1, Ordering::Relaxed) < MAX_PROMPTS && p.send(InteractiveEvent::Prompt(prompt, give)).is_ok()
});
let reply = if sent { given.recv_timeout(PROMPT_LIMIT).ok().flatten() } else { None };
// The script's own wait may have ended first: then it took the default.
let _ = answer.send(reply);
let paused = asked.elapsed();
waited = waited.saturating_add(paused);
deadline = deadline.and_then(|d| d.checked_add(paused));
}
Ok(Reply::Started) => {
// A second call changes nothing: the script's time has already begun.
if !running {
+42 -7
View File
@@ -35,6 +35,7 @@ mod pattern_guard;
pub mod patterns;
pub mod sanitize;
mod tags;
#[cfg(test)]
mod tests;
#[cfg(test)]
@@ -920,6 +921,13 @@ struct Applying {
pruned_patterns: Vec<ObjRef>,
}
/// Whether a stream's `/PCHeaderFooter` entry `v` records the same header and footer as one of
/// the entries taken off redacted streams (`raw`, and those of them that decode, `decoded`).
fn same_settings(doc: &Document, raw: &[Object], decoded: &[pdfcraft_edit::HeaderFooter], v: &Object) -> bool {
let value = doc.resolve(v);
raw.iter().any(|r| *doc.resolve(r) == *value) || pdfcraft_edit::recorded_header_footer(doc, v).is_some_and(|hf| decoded.contains(&hf))
}
/// Step 1 for one page: rewrites its content so nothing readable stays under a mark, and cleans the tags it no longer shows.
fn redact_page_content(
doc: &mut Document,
@@ -969,6 +977,8 @@ fn redact_page_content(
retired_properties.extend(out.retired_properties);
let mut new_list = list.clone();
let mut changed = false;
// Header and footer settings taken off a redacted stream (see below).
let mut redacted_settings: Vec<Object> = Vec::new();
for (i, new) in out.streams.into_iter().enumerate() {
let Some(bytes) = new else { continue };
let mut dict = match &*doc.resolve(&list[i]) {
@@ -980,10 +990,32 @@ fn redact_page_content(
// are redacted, keeping it would leave the redacted text in the file. The item stays
// as plain drawn content but is no longer editable.
dict.remove(b"PCAdded");
// A header and footer keeps its text templates in `/PCHeaderFooter` (#5785): the same goes.
// The mark stays as drawn content, which Update can only replace page-wide.
redacted_settings.extend(dict.remove(b"PCHeaderFooter"));
// A new object: the original may be shared with other pages.
new_list[i] = Object::Ref(doc.add(Object::Stream(Stream::flate(dict, &bytes))));
changed = true;
}
// A shrinking header's `cm` stream records the same settings but draws no text, so it is
// never rewritten above: take its copy of the templates away too.
// Matched by what the settings say, not how they are stored: a rewriting tool may make the
// entry indirect on one stream and leave it direct on the other.
// Only the entry goes: the stream's content is still what was read for it above.
let mut settings_only = Vec::new();
if !redacted_settings.is_empty() {
let decoded: Vec<pdfcraft_edit::HeaderFooter> =
redacted_settings.iter().filter_map(|v| pdfcraft_edit::recorded_header_footer(doc, v)).collect();
for (i, o) in new_list.iter_mut().enumerate() {
let mut stream = match &*doc.resolve(o) {
Object::Stream(s) if s.dict.get(b"PCHeaderFooter").is_some_and(|v| same_settings(doc, &redacted_settings, &decoded, v)) => s.clone(),
_ => continue,
};
stream.dict.remove(b"PCHeaderFooter");
*o = Object::Ref(doc.add(Object::Stream(stream)));
settings_only.push(i);
}
}
if changed || !out.xobjects.is_empty() || !out.replaced.is_empty() {
let mut res = resources.clone();
if !out.xobjects.is_empty() || !out.replaced.is_empty() {
@@ -999,14 +1031,17 @@ fn redact_page_content(
.iter()
.zip(&list)
.zip(&data)
.map(|((now, was), read)| match &*doc.resolve(now) {
// Left as it was: what was read above, with its parameters by reference.
_ if now == was => read.clone(),
// Written above by `Stream::flate`, which leaves no `/DecodeParms`.
Object::Stream(s) => s.decoded().unwrap_or_default(),
_ => Vec::new(),
.enumerate()
.map(|(i, ((now, was), read))| match &*doc.resolve(now) {
// Left as it was, or only its header settings taken off (keeping its
// `/Filter` and `/DecodeParms`, perhaps by reference): what was read above.
_ if now == was || settings_only.contains(&i) => Ok(read.clone()),
// Written above by `Stream::flate`. One that won't decode is an error, not
// empty content: `prune` would take that as drawing nothing.
Object::Stream(s) => doc.with_direct_parms(s).decoded(),
_ => Ok(Vec::new()),
})
.collect();
.collect::<Result<_, _>>()?;
interp::prune(doc, &mut budget, &mut xo, &out.replaced, &page_content)?;
res.set(b"XObject".to_vec(), Object::Dict(xo));
}
+91
View File
@@ -245,6 +245,44 @@ fn an_image_drawn_again_in_content_with_parameters_by_reference_stays() {
assert_eq!((image.dict.name(b"Subtype"), image.decoded().ok()), (Some(&b"Image"[..]), Some(vec![255; 4])));
}
/// #6352 review: a stream that only records a redacted header's settings keeps its `/Filter`
/// and `/DecodeParms` when the settings are taken off. Read again without its parameters (given by
/// reference), it seemed to draw nothing, so an image it draws, removed under the mark elsewhere on
/// the page, lost its resource while the stream still drew it.
#[test]
fn an_image_drawn_by_a_stream_keeping_header_settings_stays() {
use pdfcraft_cos::{Dict, ObjRef, Object};
let img = stream("/Type /XObject /Subtype /Image /Width 4 /Height 1 /ColorSpace /DeviceGray /BitsPerComponent 8", [255, 255, 255, 255]);
let mut doc = one_page(b"q 10 0 0 10 10 270 cm /Im1 Do Q", "/XObject << /Im1 7 0 R >>", vec![img]);
let mut hf = pdfcraft_edit::HeaderFooter::default();
hf.text[1] = "SECRET9".into();
pdfcraft_edit::add_header_footer(&mut doc, &[0], &hf, false, &pdfcraft_edit::Context { date: (2026, 10, 1) }).unwrap();
let page = doc.resolve(&Object::Ref(ObjRef::new(3, 0))).as_dict().unwrap().clone();
let mut contents = doc.resolve(page.get(b"Contents").unwrap()).as_array().unwrap().to_vec();
let settings = contents
.iter()
.find_map(|o| match &*doc.resolve(o) {
Object::Stream(s) => s.dict.get(b"PCHeaderFooter").cloned(),
_ => None,
})
.unwrap();
let mut again = predicted(&mut doc, Dict::new(), b"q 10 0 0 10 200 100 cm /Im1 Do Q");
again.dict.set(b"PCHeaderFooter".to_vec(), settings);
contents.push(Object::Ref(doc.add(Object::Stream(again))));
doc.update_dict(ObjRef::new(3, 0), |d| d.set(b"Contents".to_vec(), Object::Array(contents))).unwrap();
// Over the header and the image drawn at the top, not the one drawn again below.
mark(&mut doc, 0, &[[0.0, 240.0, 300.0, 300.0]], "");
let r = apply(&mut doc, None).unwrap();
assert_eq!(r.images_removed, 1, "{r:?}");
let doc = reopen(&doc);
assert!(content(&doc, 0).contains("200 100 cm /Im1 Do"), "{}", content(&doc, 0));
let p = pdfcraft_model::pages(&doc).swap_remove(0);
let res = doc.resolve(p.dict.get(b"Resources").unwrap()).as_dict().cloned().unwrap();
let xo = doc.resolve(res.get(b"XObject").unwrap()).as_dict().cloned().unwrap();
let Some(Object::Stream(image)) = xo.reference(b"Im1").map(|r| (*doc.get(r)).clone()) else { panic!("no /Im1: {xo:?}") };
assert_eq!((image.dict.name(b"Subtype"), image.decoded().ok()), (Some(&b"Image"[..]), Some(vec![255; 4])));
}
/// #2130: a font with no /Widths is drawn with its embedded program's advances. Measured with a
/// guess from its name instead (Courier's 600 units for "Mono"), the end of the line seemed to
/// lie past a mark that covers all of it on screen, and was kept.
@@ -687,6 +725,59 @@ fn added_text_parameters_do_not_keep_redacted_text() {
assert!(!bytes.windows(4).any(|w| w == b"1234"), "redacted text left in the saved file");
}
#[test]
fn a_redacted_header_keeps_no_copy_of_its_text() {
// A header and footer records its templates in /PCHeaderFooter, on its own stream and, when
// it shrinks the page, on the shrink's `cm` stream too (#5785).
let mut doc = one_page(b"BT /F1 10 Tf 10 100 Td (AB) Tj ET", "", vec![]);
let mut hf = pdfcraft_edit::HeaderFooter { shrink: true, ..Default::default() };
hf.text[1] = "SECRET9".into();
pdfcraft_edit::add_header_footer(&mut doc, &[0], &hf, false, &pdfcraft_edit::Context { date: (2026, 10, 1) }).unwrap();
assert!(write_full(&doc, &SaveOptions::default()).unwrap().windows(7).any(|w| w == b"SECRET9"), "the settings are written in the clear");
mark(&mut doc, 0, &[[0.0, 240.0, 300.0, 300.0]], "");
apply(&mut doc, None).unwrap();
let bytes = write_full(&doc, &SaveOptions::default()).unwrap();
assert!(!bytes.windows(7).any(|w| w == b"SECRET9"), "the redacted header's text left in the saved file");
assert!(content(&doc, 0).contains("(AB)"), "the rest of the page stays");
}
#[test]
fn a_redacted_header_keeps_no_copy_of_its_text_however_its_streams_store_it() {
let mut doc = one_page(b"BT /F1 10 Tf 10 100 Td (AB) Tj ET", "", vec![]);
let mut hf = pdfcraft_edit::HeaderFooter { shrink: true, ..Default::default() };
hf.text[1] = "SECRET9".into();
pdfcraft_edit::add_header_footer(&mut doc, &[0], &hf, false, &pdfcraft_edit::Context { date: (2026, 10, 1) }).unwrap();
// As a rewriting tool may: one stream's settings moved to an object of their own, the
// other's left in place, so the two entries are no longer the same value.
let page = doc.resolve(&Object::Ref(ObjRef::new(3, 0))).as_dict().unwrap().clone();
let contents = doc.resolve(page.get(b"Contents").unwrap()).as_array().unwrap().to_vec();
let recorded: Vec<ObjRef> = contents
.iter()
.filter_map(|o| match o {
Object::Ref(r) => Some(*r),
_ => None,
})
.filter(|r| matches!(&*doc.resolve(&Object::Ref(*r)), Object::Stream(s) if s.dict.get(b"PCHeaderFooter").is_some()))
.collect();
assert_eq!(recorded.len(), 2, "the header's stream and its shrink's");
for &moved in &recorded {
let mut doc = doc.clone();
let settings = match &*doc.resolve(&Object::Ref(moved)) {
Object::Stream(s) => s.dict.get(b"PCHeaderFooter").unwrap().clone(),
_ => panic!("a content stream"),
};
let indirect = doc.add(settings);
doc.update_dict(moved, |d| d.set(b"PCHeaderFooter".to_vec(), Object::Ref(indirect))).unwrap();
mark(&mut doc, 0, &[[0.0, 240.0, 300.0, 300.0]], "");
apply(&mut doc, None).unwrap();
let page = doc.resolve(&Object::Ref(ObjRef::new(3, 0))).as_dict().unwrap().clone();
let contents = doc.resolve(page.get(b"Contents").unwrap()).as_array().unwrap().to_vec();
let left = contents.iter().filter(|o| matches!(&*doc.resolve(o), Object::Stream(s) if s.dict.get(b"PCHeaderFooter").is_some())).count();
assert_eq!(left, 0, "a stream of the redacted header still records its settings ({moved:?} indirect)");
assert!(content(&doc, 0).contains("(AB)"), "the rest of the page stays");
}
}
#[test]
fn operators_split_across_content_streams_are_redacted_whole() {
// One content stream in three pieces, split between tokens: a marked-content dictionary
+1 -1
View File
@@ -42,9 +42,9 @@ pub use navigation::named_destination;
use navigation::{OUTLINE_DEPTH, OUTLINE_WINDOW};
#[cfg(test)]
use resources::LABEL_DECODES;
pub use resources::attachment_data;
#[cfg(test)]
use resources::{MAX_LAYER_LABEL_CHARS, MAX_LAYER_ORDER_ROWS, xfa_config_dynamic_render, xfa_packet_text};
pub use resources::{attachment_data, looks_like_pdf};
#[derive(Clone, Debug, Default)]
pub struct DocInfo {
+110 -3
View File
@@ -4,7 +4,7 @@ use super::model::{
state_or_default,
};
use super::navigation::text_string;
use super::{Dictionary, DocInfo, Entry, HashMap, HashSet, Inspector, Object, ObjectId};
use super::{Dictionary, DocInfo, Entry, HashMap, HashSet, Inspector, Object, ObjectId, OnceCell};
/// Negative cache of failed script-stream decompressions during one structure inspection.
/// Callers must supply stream addresses that stay stable for that inspection; these are
@@ -84,6 +84,14 @@ pub(super) const MAX_ANNOTATION_BYTES: usize = 64 << 20;
/// embedded file whose key does not fit is not listed.
pub(super) const MAX_LINK_ATTACHMENT_TEXT_BYTES: usize = 16 << 20;
/// `/NM` bytes, with a slot per entry, that the per-page annotation-name indexes for GoToE targets
/// hash in all. One `/Annots` array or one long name many pages share would otherwise be hashed
/// again for each page; past it a page is scanned for each name instead.
pub(super) const MAX_ANNOTATION_NAME_INDEX_BYTES: usize = 16 << 20;
/// A longer `/NM` is not indexed: it is scanned for. Real names are short identifiers.
const MAX_INDEXED_ANNOTATION_NAME_BYTES: usize = 1024;
/// A colour array as RGB, read as pdfcraft-annot's appearance builder reads it (`appearance::color`
/// and `drawn_color`): one entry is grey, three RGB, four CMYK; among four entries a non-number is
/// 0 but a reference is unreadable, otherwise every entry must be a number. `None` for anything
@@ -525,13 +533,22 @@ impl<'a> Inspector<'a> {
"SetOCGState" => self.layer_state(a),
"GoToR" => self.remote_go_to(a).unwrap_or_else(|| LinkTarget::Other("GoToR".into())),
"Launch" => self.launch_pdf(a).unwrap_or_else(|| LinkTarget::Other("Launch".into())),
"GoToE" => self.embedded_go_to(a, text_budget).unwrap_or_else(|| LinkTarget::Other("GoToE".into())),
other => LinkTarget::Other(spend(other.as_bytes(), text_budget, |b| String::from_utf8_lossy(b).into_owned()).unwrap_or_default()),
})
}
fn remote_go_to(&self, action: &Dictionary) -> Option<LinkTarget> {
let file = self.action_file(action)?;
let destination = match action.get(b"D") {
let destination = self.remote_destination(action)?;
Some(LinkTarget::RemoteGoTo { launch: false, file, destination, new_window: self.new_window(action) })
}
/// The `/D` of a remote or embedded Go-To: a destination in another document, so an
/// explicit one names its page by number (§12.3.2.2). No `/D` is that document's default
/// view; an unusable one is `None`.
fn remote_destination(&self, action: &Dictionary) -> Option<RemoteDestination> {
Some(match action.get(b"D") {
Err(_) => RemoteDestination::Default,
Ok(o) => match self.resolve(o) {
Object::Array(items) => {
@@ -556,8 +573,98 @@ impl<'a> Inspector<'a> {
}
_ => return None,
},
})
}
/// An embedded Go-To action (§12.6.4.4). Only a child of this document is opened: a target
/// dictionary with `/R /C` and no further `/T`, naming the file by its `/N` key in the
/// EmbeddedFiles name tree, or, for a file attachment annotation, by `/P` (a page number, or
/// a named destination giving it) and `/A` (the annotation's index in `/Annots`, or its
/// `/NM`) (Table 205). The parent (`/R /P`), a nested path, or a target under another root
/// document (`/F`) is `None`: not followed.
fn embedded_go_to(&self, action: &Dictionary, text_budget: &mut usize) -> Option<LinkTarget> {
if action.has(b"F") {
return None;
}
let t = self.dict(action.get(b"T").ok()?)?;
if self.name(t, b"R").as_deref() != Some("C") || t.has(b"T") {
return None;
}
let source = match t.get(b"N") {
Ok(n) => {
let Object::String(bytes, _) = self.resolve(n) else { return None };
// Converted as the EmbeddedFiles keys `DocInfo::attachments` lists are.
AttachmentSource::Document { key: spend(bytes, text_budget, text_string)? }
}
Err(_) => {
let page = match self.resolve(t.get(b"P").ok()?) {
Object::Integer(p) => usize::try_from(*p).ok()?,
named @ Object::String(..) => self.dest(named, 0)?.0,
_ => return None,
};
let index = match self.resolve(t.get(b"A").ok()?) {
Object::Integer(i) => usize::try_from(*i).ok()?,
Object::String(nm, _) => self.annotation_named(page, nm)?,
_ => return None,
};
AttachmentSource::Annotation { page, index }
}
};
Some(LinkTarget::RemoteGoTo { launch: false, file, destination, new_window: self.new_window(action) })
Some(LinkTarget::EmbeddedGoTo { source, destination: self.remote_destination(action)?, new_window: self.new_window(action) })
}
/// The position in page `page`'s `/Annots` of the first annotation whose `/NM` is `nm`.
fn annotation_named(&self, page: usize, nm: &[u8]) -> Option<usize> {
let pages = self.annotation_names.get_or_init(|| self.page_ids.iter().map(|_| OnceCell::new()).collect());
let names = pages.get(page)?.get_or_init(|| self.annotation_names_on(page));
match names {
// A name longer than an indexed one is not in the index: scanned for.
Some(names) if nm.len() <= MAX_INDEXED_ANNOTATION_NAME_BYTES => names.get(nm).copied(),
_ => self.annotations_on(page)?.iter().position(|a| self.annotation_name(a) == Some(nm)),
}
}
/// Each `/NM` on page `page` up to [`MAX_INDEXED_ANNOTATION_NAME_BYTES`] long, with the
/// position in its `/Annots` of the first annotation that has it, spent from
/// `annotation_name_budget`. `None` once the budget does not cover the page.
fn annotation_names_on(&self, page: usize) -> super::core::AnnotationNames {
let mut names = HashMap::new();
let Some(annots) = self.annotations_on(page) else { return Some(names) };
let mut budget = self.annotation_name_budget.get();
for (i, a) in annots.iter().enumerate() {
let Some(nm) = self.annotation_name(a).filter(|nm| nm.len() <= MAX_INDEXED_ANNOTATION_NAME_BYTES) else { continue };
// A repeated name keeps its first position and adds no entry, so it costs nothing.
if names.contains_key(nm) {
continue;
}
// Each entry costs its name and its slot, so many short names are bounded too.
let Some(left) = budget.checked_sub(nm.len().saturating_add(std::mem::size_of::<(Vec<u8>, usize)>())) else {
// What the page used so far is spent; nothing of it is kept.
self.annotation_name_budget.set(budget);
return None;
};
budget = left;
names.insert(nm.to_vec(), i);
}
self.annotation_name_budget.set(budget);
Some(names)
}
/// Page `page`'s `/Annots`.
fn annotations_on(&self, page: usize) -> Option<&'a [Object]> {
let page = self.doc.get_dictionary(*self.page_ids.get(page)?).ok()?;
match self.resolve(page.get(b"Annots").ok()?) {
Object::Array(annots) => Some(annots),
_ => None,
}
}
/// An annotation's `/NM` string bytes.
fn annotation_name(&self, a: &'a Object) -> Option<&'a [u8]> {
match self.resolve(self.dict(a)?.get(b"NM").ok()?) {
Object::String(nm, _) => Some(nm),
_ => None,
}
}
/// The non-empty local file an action's `/F` names (a string or a file specification), shared
+14 -1
View File
@@ -1,10 +1,11 @@
use super::annotations::{FieldWalk, MAX_LINK_ATTACHMENT_TEXT_BYTES};
use super::annotations::{FieldWalk, MAX_ANNOTATION_NAME_INDEX_BYTES, MAX_LINK_ATTACHMENT_TEXT_BYTES};
use super::model::{Attachment, AttachmentSource, PageInfo, Portfolio, PortfolioView, Xfa};
use super::navigation::text_string;
use super::{
Arc, AssertUnwindSafe, Dictionary, DocInfo, Document, HashMap, HashSet, LazyStructure, LoadOptions, Object, ObjectId, OnceCell, OpenError,
Structure, catch_unwind,
};
use std::cell::Cell;
/// lopdf decodes object and cross-reference streams while it loads, with no limit unless one is
/// set: a few hundred bytes of nested FlateDecode then inflate to gigabytes. Real object and
@@ -120,6 +121,11 @@ pub(super) fn inspect_structure(info: &mut DocInfo, fill: impl FnOnce(&mut DocIn
}
}
/// The names are copies (borrowing them would make `Inspector` invariant in its lifetime), each
/// short, and all of them within [`MAX_ANNOTATION_NAME_INDEX_BYTES`]. `None` when the page's names
/// did not fit what was left of it: that page is scanned for each name instead.
pub(super) type AnnotationNames = Option<HashMap<Vec<u8>, usize>>;
pub(super) struct Inspector<'a> {
pub(super) doc: &'a dyn Structure,
pub(super) page_ids: Vec<ObjectId>,
@@ -131,6 +137,11 @@ pub(super) struct Inspector<'a> {
/// has no `/P`. Searching every page's `/Annots` for each such field was O(fields ×
/// annotations): a second on a form of 8,000 fields.
pub(super) annotation_pages: OnceCell<HashMap<ObjectId, usize>>,
/// Per page, the position in `/Annots` of the first annotation with each `/NM`, built when a
/// GoToE target names one. Scanning `/Annots` for each link was O(links × annotations).
pub(super) annotation_names: OnceCell<Vec<OnceCell<AnnotationNames>>>,
/// What is left of [`MAX_ANNOTATION_NAME_INDEX_BYTES`] for `annotation_names`.
pub(super) annotation_name_budget: Cell<usize>,
/// What is left of [`MAX_FIELD_TEXT_BYTES`]: names, values and tooltips of form fields and
/// layer names, which many entries can share one string of.
pub(super) field_text: std::cell::Cell<usize>,
@@ -155,6 +166,8 @@ impl<'a> Inspector<'a> {
page_index,
named: HashMap::new(),
annotation_pages: OnceCell::new(),
annotation_names: OnceCell::new(),
annotation_name_budget: Cell::new(MAX_ANNOTATION_NAME_INDEX_BYTES),
field_text: MAX_FIELD_TEXT_BYTES.into(),
field_actions: false.into(),
parent_widgets: OnceCell::new(),
+9
View File
@@ -262,6 +262,15 @@ pub enum LinkTarget {
destination: RemoteDestination,
new_window: Option<bool>,
},
/// An embedded Go-To action (ISO 32000-2 §12.6.4.4, Tables 204–205) to a PDF embedded in
/// this document: the attachment its target dictionary names as a child (`/R /C`), by its
/// `/N` key in the EmbeddedFiles name tree or by its file attachment annotation (`/P`, `/A`),
/// and the destination `/D` in it. The caller opens it from this document's bytes.
EmbeddedGoTo {
source: AttachmentSource,
destination: RemoteDestination,
new_window: Option<bool>,
},
Other(String),
}
+7
View File
@@ -382,6 +382,13 @@ impl<'a> Inspector<'a> {
}
}
/// Whether `bytes` (an attachment's, from [`attachment_data`]) are a PDF file: the `%PDF-`
/// header (ISO 32000-2 §7.5.2) within their first 1024 bytes. Embedded go-to actions open only
/// these (§12.6.4.4).
pub fn looks_like_pdf(bytes: &[u8]) -> bool {
bytes.get(..bytes.len().min(1024)).is_some_and(|head| head.windows(5).any(|w| w == b"%PDF-"))
}
/// Fetch an attachment's bytes (decoded). Capped at 1 GiB to defuse decompression bombs. A
/// document opened without the password its embedded files need (`/AuthEvent /EFOpen`, ISO
/// 32000-2 §7.6.6) holds them encrypted: asking for one is an error, never its encrypted bytes.
+233 -2
View File
@@ -1798,6 +1798,226 @@ fn launch_actions_that_name_a_pdf_open_it_like_a_remote_link() {
);
}
/// Embedded Go-To actions (§12.6.4.4, Tables 204–205) to a child of this document are read
/// with the attachment they name; the parent, a nested path, another root document or a
/// malformed target stays an action that isn't followed.
#[test]
fn links_read_embedded_go_to_actions_to_attached_pdfs() {
let actions = [
"<< /S /GoToE /T << /R /C /N (inner.pdf) >> /D [2 /FitH 100] /NewWindow true >>",
"<< /S /GoToE /T << /R /C /P 0 /A 1 >> >>",
"<< /S /GoToE /T << /R /C /P 0 /A (att-1) >> /D (chapter) >>",
"<< /S /GoToE /T << /R /C /P (here) /A 1 >> /D [0 /Fit] >>",
"<< /S /GoToE /T << /R /P >> /D [0 /Fit] >>",
"<< /S /GoToE /T << /R /P /N (inner.pdf) >> /D [0 /Fit] >>",
"<< /S /GoToE /T << /R /C /N (inner.pdf) /T << /R /C /N (deeper.pdf) >> >> /D [0 /Fit] >>",
"<< /S /GoToE /F (other.pdf) /T << /R /C /N (inner.pdf) >> /D [0 /Fit] >>",
"<< /S /GoToE /T << /R /C /N /inner.pdf >> /D [0 /Fit] >>",
"<< /S /GoToE /T << /R /C /P 0 /A (no-such-name) >> /D [0 /Fit] >>",
"<< /S /GoToE /T << /R /C /P -1 /A 1 >> /D [0 /Fit] >>",
"<< /S /GoToE /T << /R /C /N (inner.pdf) >> /D [/Fit] >>",
"<< /S /GoToE >>",
];
let mut pdf = String::from(
"%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R /Names << /Dests << /Names [(here) [3 0 R /Fit]] >> >> >> endobj\n\
2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 300 400] >> endobj\n",
);
let annots: Vec<String> = (0..=actions.len()).map(|k| format!("{} 0 R", 30 + k)).collect();
pdf.push_str(&format!("3 0 obj << /Type /Page /Parent 2 0 R /Annots [{}] >> endobj\n", annots.join(" ")));
// Index 0 is a link; index 1 the file attachment annotation, named att-1.
pdf.push_str(&format!("30 0 obj << /Type /Annot /Subtype /Link /Rect [0 0 10 10] /A {} >> endobj\n", actions[0]));
pdf.push_str("31 0 obj << /Type /Annot /Subtype /FileAttachment /Rect [0 0 10 10] /NM (att-1) >> endobj\n");
for (k, a) in actions.iter().enumerate().skip(1) {
pdf.push_str(&format!("{} 0 obj << /Type /Annot /Subtype /Link /Rect [0 0 10 10] /A {a} >> endobj\n", 31 + k));
}
pdf.push_str("trailer << /Root 1 0 R >>\n%%EOF");
let info = inspect(Arc::new(pdf.into_bytes()), None).expect("opens");
let targets: Vec<_> = info.links.iter().map(|l| l.target.clone()).collect();
let annotation = AttachmentSource::Annotation { page: 0, index: 1 };
let embedded = |source: &AttachmentSource, destination, new_window| LinkTarget::EmbeddedGoTo { source: source.clone(), destination, new_window };
let other = || LinkTarget::Other("GoToE".into());
assert_eq!(
targets,
[
embedded(
&AttachmentSource::Document { key: "inner.pdf".into() },
RemoteDestination::Page { page: 2, view: DestView::FitH { top: Some(100.0) } },
Some(true)
),
// No /D: the document's default view.
embedded(&annotation, RemoteDestination::Default, None),
// /A by the annotation's /NM; a named destination in the target.
embedded(&annotation, RemoteDestination::Named("chapter".into()), None),
// /P by a named destination of this document.
embedded(&annotation, RemoteDestination::Page { page: 0, view: DestView::Fit }, None),
other(),
other(),
other(),
other(),
other(),
other(),
other(),
other(),
other(),
]
);
}
/// Many GoToE links naming a file attachment annotation by `/NM` read the page's annotations
/// once, not once per link, and a repeated `/NM` is the first annotation that has it.
#[test]
fn embedded_go_to_links_by_annotation_name_read_the_page_once() {
const N: usize = 400;
let att = |k: usize| 10 + k;
let link = |k: usize| 10 + N + k;
let mut pdf =
String::from("%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj\n");
let annots: Vec<String> = (0..N).map(att).chain((0..N).map(link)).map(|o| format!("{o} 0 R")).collect();
pdf += &format!("3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Annots [{}] >> endobj\n", annots.join(" "));
for k in 0..N {
// The last two attachments share a name: the first of them is the one named.
let name = if k == N - 1 { N - 2 } else { k };
pdf += &format!("{} 0 obj << /Type /Annot /Subtype /FileAttachment /Rect [0 0 1 1] /NM (a{name}) >> endobj\n", att(k));
}
for k in 0..N {
pdf +=
&format!("{} 0 obj << /Type /Annot /Subtype /Link /Rect [0 0 1 1] /A << /S /GoToE /T << /R /C /P 0 /A (a{k}) >> >> >> endobj\n", link(k));
}
pdf += "trailer << /Root 1 0 R >>\n%%EOF";
let doc = Document::load_mem(pdf.as_bytes()).expect("loads");
let counting = CountingReads { doc: &doc, reads: std::cell::Cell::new(0) };
let page = PageInfo { width: 200.0, height: 200.0, crop: [0.0, 0.0, 200.0, 200.0], rotation: 0, label: String::new() };
let mut info = DocInfo { pages: vec![page], ..Default::default() };
Inspector::new(&counting).fill(&mut info);
let indexes: Vec<Option<usize>> = info
.links
.iter()
.map(|l| match &l.target {
LinkTarget::EmbeddedGoTo { source: AttachmentSource::Annotation { page: 0, index }, .. } => Some(*index),
_ => None,
})
.collect();
let want: Vec<Option<usize>> = (0..N).map(|k| (k < N - 1).then_some(k)).collect();
assert_eq!(indexes, want);
// A handful of reads per annotation; scanning `/Annots` for each link read about 80,000.
let reads = counting.reads.get();
assert!(reads < 20 * 2 * N, "{reads} object reads");
}
/// The `/NM` indexes for GoToE targets stay within `MAX_ANNOTATION_NAME_INDEX_BYTES` when many
/// pages share one `/Annots` array holding one very long name and many short ones, and every
/// target still resolves: the long name and the pages past the budget are scanned instead.
#[test]
fn embedded_go_to_annotation_name_indexes_share_a_byte_budget() {
use super::annotations::MAX_ANNOTATION_NAME_INDEX_BYTES;
const PAGES: usize = 32;
const SHORT: usize = 1100;
let page = |k: usize| 100 + k;
let short = |j: usize| 1000 + j;
let link = |k: usize, which: usize| 10_000 + 2 * k + which;
let links_page = page(PAGES);
let kids: Vec<String> = (0..=PAGES).map(|k| format!("{} 0 R", page(k))).collect();
let mut pdf = format!(
"%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n2 0 obj << /Type /Pages /Kids [{}] /Count {} >> endobj\n",
kids.join(" "),
PAGES + 1
);
let shared: Vec<String> = std::iter::once(6).chain((0..SHORT).map(short)).map(|o| format!("{o} 0 R")).collect();
pdf += &format!("4 0 obj [{}] endobj\n", shared.join(" "));
// One name of a mebibyte, which every page's index would otherwise hash.
pdf += &format!("7 0 obj ({}) endobj\n", "x".repeat(1 << 20));
pdf += "6 0 obj << /Type /Annot /Subtype /FileAttachment /Rect [0 0 1 1] /NM 7 0 R >> endobj\n";
for j in 0..SHORT {
pdf += &format!("{} 0 obj << /Type /Annot /Subtype /FileAttachment /Rect [0 0 1 1] /NM (n{j:0>999}) >> endobj\n", short(j));
}
for k in 0..PAGES {
pdf += &format!("{} 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Annots 4 0 R >> endobj\n", page(k));
}
let links: Vec<String> = (0..PAGES).flat_map(|k| [link(k, 0), link(k, 1)]).map(|o| format!("{o} 0 R")).collect();
pdf += &format!("{links_page} 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Annots [{}] >> endobj\n", links.join(" "));
let target = |k: usize| (k * 37) % SHORT;
for k in 0..PAGES {
let action = |a: String| format!("<< /S /GoToE /T << /R /C /P {k} /A {a} >> /D [0 /Fit] >>");
pdf += &format!("{} 0 obj << /Type /Annot /Subtype /Link /Rect [0 0 1 1] /A {} >> endobj\n", link(k, 0), action("7 0 R".into()));
pdf += &format!(
"{} 0 obj << /Type /Annot /Subtype /Link /Rect [0 0 1 1] /A {} >> endobj\n",
link(k, 1),
action(format!("(n{:0>999})", target(k)))
);
}
pdf += "trailer << /Root 1 0 R >>\n%%EOF";
let doc = Document::load_mem(pdf.as_bytes()).expect("loads");
let blank = PageInfo { width: 200.0, height: 200.0, crop: [0.0, 0.0, 200.0, 200.0], rotation: 0, label: String::new() };
let mut info = DocInfo { pages: vec![blank; PAGES + 1], ..Default::default() };
let inspector = Inspector::new(&doc);
inspector.fill(&mut info);
let indexes: Vec<(usize, usize)> = info
.links
.iter()
.filter_map(|l| match &l.target {
LinkTarget::EmbeddedGoTo { source: AttachmentSource::Annotation { page, index }, .. } => Some((*page, *index)),
_ => None,
})
.collect();
let want: Vec<(usize, usize)> = (0..PAGES).flat_map(|k| [(k, 0), (k, 1 + target(k))]).collect();
assert_eq!(indexes, want);
let indexed: Vec<usize> = inspector
.annotation_names
.get()
.into_iter()
.flatten()
.filter_map(|page| page.get().cloned().flatten())
.flat_map(|names| names.into_keys())
.map(|name| name.len())
.collect();
let total: usize = indexed.iter().sum();
assert!(total > 0 && total <= MAX_ANNOTATION_NAME_INDEX_BYTES, "{total} name bytes indexed");
// The mebibyte name is scanned for, never copied into an index.
assert!(indexed.iter().all(|&len| len < 1 << 20), "the long name was indexed");
}
/// A `/NM` repeated across a page's `/Annots` is charged to the index budget once: one long name
/// on 17,000 annotations would otherwise spend the whole budget, drop the page's index and send
/// every GoToE target on that page back to scanning `/Annots`.
#[test]
fn embedded_go_to_repeated_annotation_name_is_charged_once() {
use super::annotations::MAX_ANNOTATION_NAME_INDEX_BYTES;
const REPEATS: usize = 17_000;
let long = "r".repeat(1000);
let annots = format!("{} 6 0 R", "5 0 R ".repeat(REPEATS));
let mut pdf =
String::from("%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n2 0 obj << /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 >> endobj\n");
pdf += &format!("3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Annots [{annots}] >> endobj\n");
pdf += "4 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Annots [8 0 R 9 0 R] >> endobj\n";
pdf += &format!("5 0 obj << /Type /Annot /Subtype /FileAttachment /Rect [0 0 1 1] /NM ({long}) >> endobj\n");
pdf += "6 0 obj << /Type /Annot /Subtype /FileAttachment /Rect [0 0 1 1] /NM (last) >> endobj\n";
let link = |o: usize, nm: &str| {
format!("{o} 0 obj << /Type /Annot /Subtype /Link /Rect [0 0 1 1] /A << /S /GoToE /T << /R /C /P 0 /A ({nm}) >> /D [0 /Fit] >> >> endobj\n")
};
pdf += &link(8, &long);
pdf += &link(9, "last");
pdf += "trailer << /Root 1 0 R >>\n%%EOF";
let doc = Document::load_mem(pdf.as_bytes()).expect("loads");
let blank = PageInfo { width: 200.0, height: 200.0, crop: [0.0, 0.0, 200.0, 200.0], rotation: 0, label: String::new() };
let mut info = DocInfo { pages: vec![blank; 2], ..Default::default() };
let inspector = Inspector::new(&doc);
inspector.fill(&mut info);
let indexes: Vec<usize> = info
.links
.iter()
.filter_map(|l| match &l.target {
LinkTarget::EmbeddedGoTo { source: AttachmentSource::Annotation { page: 0, index }, .. } => Some(*index),
_ => None,
})
.collect();
assert_eq!(indexes, [0, REPEATS]);
let page = inspector.annotation_names.get().and_then(|pages| pages.first()).and_then(|page| page.get());
let Some(Some(names)) = page else { panic!("page 0's /NM index was dropped: {page:?}") };
assert_eq!(names.len(), 2);
let spent = MAX_ANNOTATION_NAME_INDEX_BYTES - inspector.annotation_name_budget.get();
assert!(spent < 2 * (1000 + 64), "{spent} budget bytes spent on two names");
}
#[test]
fn links_read_bounded_local_remote_go_to_actions() {
use DestView::{Fit, Xyz};
@@ -2173,8 +2393,8 @@ fn outline_items_carry_their_colour_and_style() {
/// A bookmark's action (`/A`, ISO 32000-2 §12.3.3 Table 151) is read as a link's is. Only a
/// go-to's `/D` is a page of this document: a remote go-to's names a page or destination of the
/// other file (§12.6.4.3), so `[0 /FitH 200]` there is not this file's first page. A web address,
/// another PDF and actions PdfCraft doesn't run are kept for the bookmark to run or report. An
/// action without a type is still read as the go-to its `/D` suggests.
/// another PDF, a PDF attached to this one (GoToE, §12.6.4.4) and actions PdfCraft doesn't run
/// are kept for the bookmark to run or report. An action without a type is still read as the go-to its `/D` suggests.
#[test]
fn bookmark_actions_are_read_as_links_read_them() {
use DestView::*;
@@ -2184,6 +2404,7 @@ fn bookmark_actions_are_read_as_links_read_them() {
("Other file", "/A << /S /GoToR /F (other.pdf) /D [0 /FitH 200] /NewWindow true >>"),
("Other file, named", "/A << /S /GoToR /F (other.pdf) /D (sec) >>"),
("Launch", "/A << /S /Launch /F (other.pdf) >>"),
("Attached", "/A << /S /GoToE /T << /R /C /N (inner.pdf) >> /D [1 /Fit] >>"),
("Menu item", "/A << /S /Named /N /NextPage >>"),
("Script", "/A << /S /JavaScript /JS (app.alert\\(1\\)) >>"),
("No type", "/A << /D [3 0 R /Fit] >>"),
@@ -2214,6 +2435,16 @@ fn bookmark_actions_are_read_as_links_read_them() {
Top,
Some(LinkTarget::RemoteGoTo { launch: true, file: "other.pdf".into(), destination: RemoteDestination::Default, new_window: None })
),
(
"Attached",
None,
Top,
Some(LinkTarget::EmbeddedGoTo {
source: AttachmentSource::Document { key: "inner.pdf".into() },
destination: RemoteDestination::Page { page: 1, view: Fit },
new_window: None
})
),
("Menu item", None, Top, Some(LinkTarget::Other("Named".into()))),
("Script", None, Top, Some(LinkTarget::Other("JavaScript".into()))),
("No type", Some(0), Fit, None),
+2 -1
View File
@@ -22,7 +22,8 @@ pub mod transition;
pub use inspect::{
Annotation, Attachment, AttachmentSource, DestView, DocInfo, Field, FieldKind, FontInfo, Layer, LayerItem, LayerOp, LayerRow, Link, LinkTarget,
MAX_GROUP_DEPTH, OutlineItem, PageInfo, PageTransition, Popup, Portfolio, PortfolioView, RemoteDestination, ReviewStates, TransitionStyle, Xfa,
attachment_data, check_pages, fill_group_text, group_primaries, inspect, link_replies, named_destination, pretty_date, thread_tops,
attachment_data, check_pages, fill_group_text, group_primaries, inspect, link_replies, looks_like_pdf, named_destination, pretty_date,
thread_tops,
};
pub use link_area::{MAX_LINK_QUADS, MAX_URI_BASE_BYTES, link_quads, quad_contains, resolve_uri};
pub use pixels::Pixels;
+9
View File
@@ -114,6 +114,15 @@ needs a prompt to open is listed and asks at signing (issue #179).
- **Weak algorithms still validate, and say so.** SHA-1 and RIPEMD-160 signatures are common in
documents signed years ago, so they validate (new signatures never use SHA-1), but the signature's
details say that the algorithm is weak and shouldn't be relied on.
- **Trust is the user's decision.** Only the user's own list (`TrustStore::certs`) is trusted by
default. A trust list the user loads from a file (`sign_trust eu_trusted_list`, the EU Trusted
Lists' qualified CAs, say) is kept apart from it (`TrustStore::lists`), off until loaded, and
named in the details when it vouches. Nothing of the kind is embedded. A list vouches for
signers, never for a time-stamp authority: trusted time comes from the user's own certificates.
- **Not Adobe's list.** Adobe's AATL is not used: Adobe-authored data outside the closed list in
AGENTS.md §1.1 needs the owner's explicit approval, and the EU Trusted Lists (and, planned, the
operating system's store) cover the same ground. A signer that chains only to an AATL root stays
"unknown" until the user trusts that root.
- **Validation algorithms:** digests SHA-1, SHA-224/256/384/512, SHA-512/224, SHA-512/256,
SHA3-224/256/384/512 and RIPEMD-160. RSA PKCS #1 v1.5 and RSASSA-PSS (the hash, MGF1 hash and
salt length the signature declares), ECDSA on P-256, P-384, P-521, brainpoolP256r1, P384r1 and
+3 -2
View File
@@ -21,6 +21,7 @@ pub mod pkcs12;
pub mod revocation;
pub mod status_layers;
pub mod timestamp;
pub mod trust;
#[cfg(target_os = "windows")]
pub mod windows;
pub mod x509;
@@ -29,8 +30,8 @@ pub use der::Time;
pub use graphic::Graphic;
pub use keys::{DigestAlg, PrivateKey, PublicKey};
pub use pdf::{
Appearance, AppearanceLabels, Detail, DigestCache, Fill, Modification, SignOptions, SignatureInfo, Status, TrustStore, WORDINGS, Words,
has_signatures, in_english, kind, list as signatures, sign, sign_with_timestamp, timestamp_document, validate,
Appearance, AppearanceLabels, Detail, DigestCache, Fill, Modification, SignOptions, SignatureInfo, Status, TrustSource, TrustStore, WORDINGS,
Words, has_signatures, in_english, kind, list as signatures, sign, sign_with_timestamp, timestamp_document, validate,
};
pub use pkcs12::DigitalId;
pub use status_layers::{StatusCaptions, has_status_layers, show_status_layers, status_rgb};
+1 -1
View File
@@ -40,7 +40,7 @@ pub use listing::{DigestCache, list, list_cached};
pub(crate) use listing::{walk_sig_fields, widget_shown};
pub(crate) use signing::fmt;
pub use signing::{Appearance, AppearanceLabels, SignOptions, display_date, has_signatures, sign, sign_with_timestamp, timestamp_document};
pub use types::{Detail, Fill, Modification, Status, TrustStore, WORDINGS, Words, in_english, kind};
pub use types::{Detail, Fill, Modification, Status, TrustSource, TrustStore, WORDINGS, Words, in_english, kind};
pub(crate) use validate::signature_contents;
pub use validate::validate;
#[cfg(test)]
+45 -3
View File
@@ -1,12 +1,52 @@
use super::Certificate;
/// Certificates the user trusts for signing (Acrobat: Trusted Certificates).
/// Certificates trusted for signing (Acrobat: Trusted Certificates). Only `certs`, the user's own
/// list, is trusted by default; a trust list has to be loaded.
#[derive(Clone, Debug, Default)]
pub struct TrustStore {
pub certs: Vec<Certificate>,
/// Lists of CA certificates the user loaded (e.g. the EU Trusted Lists' qualified CAs). They
/// vouch for signers, never for a time-stamp authority: trusted time comes from `certs` alone.
pub lists: Vec<crate::trust::TrustList>,
}
/// Why a certificate in a chain is trusted.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum TrustSource {
/// The user's own list of trusted certificates.
User,
/// The named list the user loaded.
List(String),
}
impl TrustStore {
/// Load `list`, replacing a list of the same name. A list is known by its own name, so
/// [`remove_list`](Self::remove_list) takes back exactly what was loaded.
pub fn add_list(&mut self, list: crate::trust::TrustList) {
self.remove_list(&list.name);
self.lists.push(list);
}
/// Remove the list called `name`, if one is loaded.
pub fn remove_list(&mut self, name: &str) {
self.lists.retain(|l| l.name != name);
}
/// Every certificate that can anchor a signer's chain: the user's, then the loaded lists'.
pub(super) fn anchors(&self) -> impl Iterator<Item = &Certificate> + Clone {
self.certs.iter().chain(self.lists.iter().flat_map(|l| l.certs.iter()))
}
/// What makes `c` trusted to vouch for a signer, if anything. The user's own list wins.
pub fn source_of(&self, c: &Certificate) -> Option<TrustSource> {
if self.trusts(c) {
Some(TrustSource::User)
} else {
self.lists.iter().find(|l| l.certs.iter().any(|t| t.raw == c.raw)).map(|l| TrustSource::List(l.name.clone()))
}
}
/// Whether the user's own list holds `c`. Only that vouches for a time-stamp authority.
pub(super) fn trusts(&self, c: &Certificate) -> bool {
self.certs.iter().any(|t| t.raw == c.raw)
}
@@ -92,8 +132,9 @@ pub enum Fill {
/// A value out of the signature itself — a time, the evidence a revocation came from — written
/// as it stands, the way a certificate's name or date is.
Value(String),
/// Two certificates' own names, for the wording that says one was not used to vouch for the
/// other. They go in the order the wording puts its two holes in, which a language may reverse.
/// Two names, for the wording with two holes: that one certificate was not used to vouch for
/// another, or which trust list vouched through which certificate. They go in the order the
/// wording puts its two holes in, which a language may reverse.
Names(String, String),
}
@@ -199,6 +240,7 @@ pub const WORDINGS: &[&str] = &[
"The certificate of {} was not valid at the time of signing, so it is not used to vouch for {}.",
"The signer's identity is unknown because it has not been included in your list of trusted certificates and none of its parent certificates are trusted certificates.",
"The signer's identity is valid.",
"Its certificate chains to {} in the trust list “{}”.",
"The signature includes an embedded timestamp.",
"Signing time is from the clock on the signer's computer.",
// What the signature's own timestamp token proves, if it carries one.
+9 -5
View File
@@ -1,7 +1,7 @@
use super::changes::classify_changes;
use super::listing::{DigestCache, Field, list, nums, sig_fields, text};
use super::locks::{Locked, locked_fields};
use super::types::{Detail, Fill, Modification, Status, TrustStore, kind};
use super::types::{Detail, Fill, Modification, Status, TrustSource, TrustStore, kind};
use super::{
Certificate, Dict, DigestAlg, Document, HashSet, ObjRef, Object, SignError, SignatureInfo, SignedData, Time, build_chain, build_chain_noted,
};
@@ -337,13 +337,13 @@ fn finish_validation(context: SignatureValidation<'_>, verified: VerifiedSignatu
let SignatureValidation { doc, bytes, trust, info, cache, .. } = context;
let VerifiedSignature { covered, certificate: cert, embedded, cms_time, unverified_time } = verified;
info.signing_time = cms_time.or_else(|| info.date.as_deref().and_then(Time::from_pdf));
let mut pool = embedded.to_vec();
pool.extend(trust.certs.iter().cloned());
// The time the chain is judged at: trusted timestamp, else the signer's claimed time.
let at = info.timestamp_time.or(info.signing_time);
let (chain, refused) = build_chain_noted(&cert, &pool, at);
let (chain, refused) = build_chain_noted(&cert, embedded.iter().chain(trust.anchors()), at);
let chain: Vec<Certificate> = chain.into_iter().cloned().collect();
let trusted = chain.iter().any(|c| trust.trusts(c));
// The first trusted certificate going up the chain, and what makes it trusted.
let anchor = chain.iter().find_map(|c| trust.source_of(c).map(|s| (c.display_name(), s)));
let trusted = anchor.is_some();
info.chain = chain;
info.certificate = Some(cert.clone());
if let Some(why) = refused
@@ -474,6 +474,10 @@ fn finish_validation(context: SignatureValidation<'_>, verified: VerifiedSignatu
}
} else {
info.details.push(Detail::plain("The signer's identity is valid."));
// Which list vouched, when one did: the user's own list is the plain case and says nothing.
if let Some((root, TrustSource::List(list))) = anchor {
info.details.push(Detail::of("Its certificate chains to {} in the trust list “{}”.", Fill::Names(root, list)));
}
if !problems && !revoked {
info.status = Status::Valid;
}
+141
View File
@@ -0,0 +1,141 @@
//! Trust lists: sets of CA certificates the user loads from a file, kept apart from the
//! certificates they trust themselves.
//!
//! Nothing here is trusted unless the user loads it (`TrustStore::lists`): which authorities a PDF
//! reader vouches for is the user's decision, not ours, so no list is embedded in PdfCraft. The
//! first intended source is the EU Trusted Lists' qualified CA services. Chain building
//! ([`crate::x509::build_chain`]) still applies to a list: a certificate in it only vouches for what
//! a chain of CA certificates under it leads to.
//!
//! An entry that is not a CA stays in the list (the national lists file a few OCSP responder and
//! time-stamp certificates under their CA services, so refusing them would refuse the real
//! lists). It can issue nothing in chain building and vouches only for itself, which the signer
//! checks of [`crate::x509::Certificate::signing_problem`] still judge.
//!
//! A list vouches for signers. It never vouches for a time-stamp authority: a CA that is trusted
//! to issue signing certificates is not thereby a source of trusted time, so trusted time still
//! comes only from the user's own certificates.
//!
//! Adobe's AATL is not used in any form: Adobe-authored data outside the closed list in AGENTS.md §1.1
//! needs the owner's explicit approval, and the EU Trusted Lists cover the same ground.
use std::sync::Arc;
use crate::SignError;
use crate::der::Tlv;
use crate::x509::Certificate;
/// Certificates as DER one after the other. A certificate that doesn't parse (a key type PdfCraft
/// doesn't read, say) is skipped. Bytes that aren't a DER element at all, as in a file cut short,
/// are an error, so a damaged list doesn't load as a smaller one without a word.
fn parse_concatenated(mut rest: &[u8]) -> Result<Vec<Certificate>, SignError> {
let mut out = Vec::new();
while !rest.iter().all(u8::is_ascii_whitespace) {
let Ok((t, r)) = Tlv::parse(rest) else {
return Err(SignError::Malformed(format!("the trust list is damaged after {} certificates ({} bytes left)", out.len(), rest.len())));
};
if let Ok(c) = Certificate::parse(t.raw) {
out.push(c);
}
rest = r;
}
Ok(out)
}
/// The most a list file may hold: far above the roughly 1.5 MB of the EU qualified CAs.
pub const MAX_LIST_BYTES: usize = 32 << 20;
/// A named set of trusted CA certificates the user loaded from a file, e.g. "EU Trusted List".
#[derive(Clone, Debug)]
pub struct TrustList {
pub name: String,
pub certs: Arc<Vec<Certificate>>,
}
impl TrustList {
/// A list from a file's bytes: certificates as DER one after the other, or a PEM bundle.
/// Certificates that don't parse are skipped; a file with none, a damaged one, or one over
/// [`MAX_LIST_BYTES`], is an error.
pub fn from_bytes(name: &str, bytes: &[u8]) -> Result<TrustList, SignError> {
if bytes.len() > MAX_LIST_BYTES {
return Err(SignError::Malformed(format!("trust list over {} MiB", MAX_LIST_BYTES >> 20)));
}
let mut certs = if bytes.first() == Some(&0x30) && !crate::x509::is_pem(bytes) {
parse_concatenated(bytes)?
} else {
crate::x509::load_certificates(bytes)?
};
let mut seen = std::collections::HashSet::new();
certs.retain(|c| seen.insert(c.raw.clone()));
if certs.is_empty() {
return Err(SignError::Malformed("no certificates in the trust list".into()));
}
Ok(TrustList { name: name.to_string(), certs: Arc::new(certs) })
}
}
#[cfg(test)]
mod tests {
use super::*;
/// A few self-made certificates to load: the lists are tested without any real CA's data.
fn certificates(n: usize) -> Vec<Vec<u8>> {
(0..n)
.map(|i| {
let key = crate::PrivateKey::generate_p256().unwrap();
let name = crate::x509::Name::build(&format!("List Test {i}"), "", "Trust Tests", "", "US");
let alg = key.preferred_digest();
let sig_alg = key.signature_algorithm(alg);
let tbs = crate::der::seq(&[
&crate::der::uint(&[1 + i as u8]),
&sig_alg,
&name.raw,
&crate::der::seq(&[
&crate::der::Time { year: 2020, month: 1, day: 1, hour: 0, minute: 0, second: 0 }.encode(),
&crate::der::Time { year: 2040, month: 1, day: 1, hour: 0, minute: 0, second: 0 }.encode(),
]),
&name.raw,
&key.public_key().spki(),
]);
let signature = key.sign(alg, &tbs).unwrap();
crate::der::seq(&[&tbs, &sig_alg, &crate::der::bit_string(&signature)])
})
.collect()
}
#[test]
fn a_list_reads_concatenated_der_and_rejects_garbage() {
let certs = certificates(3);
let file = certs.concat();
let list = TrustList::from_bytes("Test list", &file).unwrap();
assert_eq!((list.name.as_str(), list.certs.len()), ("Test list", 3));
// The same as a PEM bundle.
let pem: String = list.certs.iter().map(crate::x509::to_pem).collect();
assert_eq!(TrustList::from_bytes("pem", pem.as_bytes()).unwrap().certs.len(), 3);
assert!(TrustList::from_bytes("none", b"not certificates").is_err());
assert!(TrustList::from_bytes("none", &[]).is_err());
assert!(TrustList::from_bytes("big", &vec![0x30; MAX_LIST_BYTES + 1]).is_err());
// A file cut short is refused, not loaded as the certificates before the cut.
assert!(TrustList::from_bytes("cut", &file[..file.len() - 5]).is_err());
// Whitespace after the last certificate is not damage.
let spaced = [file.as_slice(), b"\n"].concat();
assert_eq!(TrustList::from_bytes("spaced", &spaced).unwrap().certs.len(), 3);
// PEM that follows a note starting with "0" (the first byte DER starts with) is still PEM.
let noted = format!("0 certificates have been revoked in this bundle\n{pem}");
assert_eq!(TrustList::from_bytes("noted", noted.as_bytes()).unwrap().certs.len(), 3);
// A PEM bundle cut short is refused too, wherever the cut falls: in the last block, or
// right after the last complete one.
let blocks: Vec<String> = list.certs.iter().map(crate::x509::to_pem).collect();
let cut_inside = format!("{}{}", blocks[0], &blocks[1][..blocks[1].len() / 2]);
assert!(TrustList::from_bytes("cut pem", cut_inside.as_bytes()).is_err());
let cut_after = format!("{}{}-----BEGIN CERTIFICATE-----\n", blocks[0], blocks[1]);
assert!(TrustList::from_bytes("cut pem", cut_after.as_bytes()).is_err());
// So is a block that begins before the one before it ended.
let head: String = blocks[0].lines().take(2).map(|l| format!("{l}\n")).collect();
let spliced = format!("{head}{}", blocks[1]);
assert!(TrustList::from_bytes("spliced", spliced.as_bytes()).is_err());
// A certificate listed twice, even apart, is one entry.
let repeated = [certs[0].clone(), certs[1].clone(), certs[0].clone()].concat();
assert_eq!(TrustList::from_bytes("dups", &repeated).unwrap().certs.len(), 2);
}
}
+22 -4
View File
@@ -569,7 +569,7 @@ pub fn subject_of(raw: &[u8]) -> Option<Name> {
/// `pathLenConstraint` allows the CA certificates below it, and (when `at` is given) it was valid
/// then. Stops at a self-signed certificate. Certificates embedded in a document are in `pool`
/// too, so an ordinary end-entity certificate must never be accepted as an issuer.
pub fn build_chain<'a>(leaf: &'a Certificate, pool: &'a [Certificate], at: Option<Time>) -> Vec<&'a Certificate> {
pub fn build_chain<'a>(leaf: &'a Certificate, pool: impl IntoIterator<Item = &'a Certificate> + Clone, at: Option<Time>) -> Vec<&'a Certificate> {
build_chain_noted(leaf, pool, at).0
}
@@ -579,7 +579,11 @@ pub fn build_chain<'a>(leaf: &'a Certificate, pool: &'a [Certificate], at: Optio
/// The reason is a whole sentence of ours, listed in [`WORDINGS`](crate::pdf::WORDINGS), with the two
/// certificates' own names put in afterwards, so an interface reading in another language says it in
/// it.
pub fn build_chain_noted<'a>(leaf: &'a Certificate, pool: &'a [Certificate], at: Option<Time>) -> (Vec<&'a Certificate>, Option<Detail>) {
pub fn build_chain_noted<'a>(
leaf: &'a Certificate,
pool: impl IntoIterator<Item = &'a Certificate> + Clone,
at: Option<Time>,
) -> (Vec<&'a Certificate>, Option<Detail>) {
let mut chain = vec![leaf];
let mut refused = None;
while chain.len() < 10 {
@@ -591,7 +595,11 @@ pub fn build_chain_noted<'a>(leaf: &'a Certificate, pool: &'a [Certificate], at:
let below = chain.len() - 1;
let mut found = None;
let mut digest = None;
for c in pool.iter().filter(|c| c.subject.raw == last.issuer.raw && !chain.contains(c) && last.signed_by_cached(&c.public_key, &mut digest)) {
for c in pool
.clone()
.into_iter()
.filter(|c| c.subject.raw == last.issuer.raw && !chain.contains(c) && last.signed_by_cached(&c.public_key, &mut digest))
{
// Each reason is a whole sentence, not a phrase stitched into one: a language puts the
// two names where it needs them.
let why = if !c.may_issue() {
@@ -622,11 +630,17 @@ pub fn build_chain_noted<'a>(leaf: &'a Certificate, pool: &'a [Certificate], at:
(chain, refused)
}
/// Whether `bytes` hold PEM. PEM may start with explanatory text, even text that begins with a
/// "0" (0x30), which is also the first byte of every DER certificate.
pub(crate) fn is_pem(bytes: &[u8]) -> bool {
bytes.windows(10).any(|w| w == b"-----BEGIN")
}
/// Certificates from a file: DER, or PEM with one or more `CERTIFICATE` blocks (`.cer`, `.crt`,
/// `.pem`, Acrobat's `.fdf`-free exports), or a PKCS #7 bundle (`.p7b`, `.p7c`) in DER or as a
/// PEM `PKCS7`/`CMS` block, as Windows, Acrobat and certificate authorities export chains.
pub fn load_certificates(bytes: &[u8]) -> Result<Vec<Certificate>, SignError> {
if bytes.first() == Some(&0x30) {
if bytes.first() == Some(&0x30) && !is_pem(bytes) {
// One DER certificate, else a DER bundle; a file that is neither reports the
// certificate's error, the common case.
return match Certificate::parse(bytes) {
@@ -640,6 +654,10 @@ pub fn load_certificates(bytes: &[u8]) -> Result<Vec<Certificate>, SignError> {
let mut block: Option<(&str, String)> = None;
for line in text.lines().map(str::trim) {
if let Some(label) = line.strip_prefix("-----BEGIN ").and_then(|l| l.strip_suffix("-----")) {
// A block that begins before the open one ended is a file cut short or spliced.
if block.is_some() {
return Err(SignError::Malformed("a PEM block is not closed".into()));
}
block = matches!(label, "CERTIFICATE" | "PKCS7" | "CMS").then(|| (label, String::new()));
} else if let Some(label) = line.strip_prefix("-----END ").and_then(|l| l.strip_suffix("-----")) {
// An END that doesn't close the open block ends nothing.
+114 -1
View File
@@ -189,7 +189,7 @@ fn verdict(leaf: Party, embedded: Vec<Certificate>, anchor: &Certificate) -> (St
let doc = Document::open(Arc::new(fixture())).unwrap();
let opts = SignOptions { page: 0, rect: None, date: "D:20260601120000Z".into(), ..SignOptions::default() };
let signed = pdfcraft_sign::sign(&doc, &id, &opts).unwrap();
let trust = TrustStore { certs: vec![anchor.clone()] };
let trust = TrustStore { certs: vec![anchor.clone()], ..TrustStore::default() };
let s = signatures(&Document::open(Arc::new(signed.clone())).unwrap(), &signed, &trust).into_iter().rfind(|s| s.signed).unwrap();
// The details as they read in English; what an interface says in another language is checked in
// `tests/it/pdf.rs`.
@@ -362,3 +362,116 @@ fn an_issuer_with_an_unprocessed_critical_extension_does_not_vouch() {
let pool = [i.cert.clone(), constrained_root.cert.clone()];
assert_eq!(names(&build_chain(&l.cert, &pool, None)), ["Leaf", "Under Constrained Root", "Name Constrained Root"]);
}
/// Like `verdict`, but with a whole `TrustStore`.
fn verdict_with(leaf: Party, embedded: Vec<Certificate>, trust: &TrustStore) -> (Status, Vec<String>) {
let id = DigitalId { key: leaf.key, certificate: leaf.cert, chain: embedded, friendly_name: None };
let doc = Document::open(Arc::new(fixture())).unwrap();
let opts = SignOptions { page: 0, rect: None, date: "D:20260601120000Z".into(), ..SignOptions::default() };
let signed = pdfcraft_sign::sign(&doc, &id, &opts).unwrap();
let s = signatures(&Document::open(Arc::new(signed.clone())).unwrap(), &signed, trust).into_iter().rfind(|s| s.signed).unwrap();
(s.status, s.details.iter().map(|d| d.message.clone()).collect())
}
#[test]
fn a_trust_list_is_off_by_default_and_named_when_it_vouches() {
use pdfcraft_sign::trust::TrustList;
let r = root();
let i = ca("Issuing CA", &r, None);
let leaf = |cn: &str| end_entity(cn, &i);
let list = TrustList::from_bytes("Test List", &r.cert.raw).unwrap();
// Nothing is trusted unless asked for.
let none = TrustStore::default();
assert!(none.lists.is_empty() && none.certs.is_empty());
let (status, details) = verdict_with(leaf("Signer A"), vec![i.cert.clone()], &none);
assert_eq!(status, Status::Unknown, "{details:?}");
// With the list loaded, the same signature is valid and says which list vouched.
let with_list = TrustStore { lists: vec![list.clone()], ..TrustStore::default() };
let (status, details) = verdict_with(leaf("Signer B"), vec![i.cert.clone()], &with_list);
assert_eq!(status, Status::Valid, "{details:?}");
assert!(details.iter().any(|d| d.contains("Test List")), "{details:?}");
// The user's own list wins over a loaded one that holds the same certificate.
let both = TrustStore { certs: vec![r.cert.clone()], lists: vec![list.clone()] };
assert_eq!(both.source_of(&r.cert), Some(pdfcraft_sign::TrustSource::User));
assert_eq!(with_list.source_of(&r.cert), Some(pdfcraft_sign::TrustSource::List("Test List".into())));
assert_eq!(none.source_of(&r.cert), None);
// A list does not make a subscriber a CA: the forged identity stays unknown.
let subscriber = end_entity("Ordinary Subscriber", &r);
let forged = end_entity("Forged Identity", &subscriber);
let (status, details) = verdict_with(forged, vec![subscriber.cert.clone()], &with_list);
assert_eq!(status, Status::Unknown, "{details:?}");
}
/// A time-stamp authority that answers in-process, with whatever certificate it is given.
struct Stamper {
key: PrivateKey,
cert: Certificate,
time: Time,
}
impl pdfcraft_sign::TimestampAuthority for Stamper {
fn timestamp(&self, request: &[u8]) -> Result<Vec<u8>, pdfcraft_sign::SignError> {
let q = pdfcraft_sign::timestamp::parse_request(request)?;
pdfcraft_sign::timestamp::respond(
pdfcraft_sign::timestamp::TimestampSigner {
key: &self.key,
certificate: &self.cert,
chain: &[],
digest: pdfcraft_sign::DigestAlg::Sha256,
},
pdfcraft_sign::timestamp::TimestampIssuance { query: &q, policy: "1.2.3.4", generation_time: self.time, serial: 7 },
)
}
}
#[test]
fn a_list_vouches_for_a_signer_whose_file_carries_only_its_leaf_and_never_for_a_time_stamp_authority() {
use pdfcraft_sign::trust::TrustList;
// The shape of a CAdES signature under a qualified service (#775): the list holds the issuing
// CA (not a root), the CMS embeds only the leaf, and the time-stamp authority is not the user's.
let r = root();
let i = ca("Issuing CA", &r, None);
let leaf = end_entity("Signer", &i);
// A real time-stamp authority: its certificate is issued for time stamping (RFC 3161 §2.3).
let tsa = issue(
"Some Stamper",
Some(&root()),
FOREVER,
&[basic_constraints(false, None), key_usage(DIGITAL_SIGNATURE), extended_key_usage(&["1.3.6.1.5.5.7.3.8"])],
);
let stamped_at = time(2026);
let stamper = Stamper { key: tsa.key, cert: tsa.cert.clone(), time: stamped_at };
let id = DigitalId { key: leaf.key, certificate: leaf.cert, chain: Vec::new(), friendly_name: None };
let doc = Document::open(Arc::new(fixture())).unwrap();
let opts = SignOptions { page: 0, rect: None, date: "D:20260601120000Z".into(), ..SignOptions::default() };
let signed = pdfcraft_sign::sign_with_timestamp(&doc, &id, &opts, &stamper).unwrap();
let check =
|trust: &TrustStore| signatures(&Document::open(Arc::new(signed.clone())).unwrap(), &signed, trust).into_iter().rfind(|s| s.signed).unwrap();
let said = |s: &pdfcraft_sign::SignatureInfo, what: &str| s.details.iter().any(|d| d.message.contains(what));
// Nothing loaded: unknown.
let s = check(&TrustStore::default());
assert_eq!(s.status, Status::Unknown, "{:?}", s.details);
// The list with the issuing CA completes the chain the file leaves out: valid, and named.
let list = TrustList::from_bytes("Test List", &i.cert.raw).unwrap();
let s = check(&TrustStore { lists: vec![list.clone()], ..TrustStore::default() });
assert_eq!(s.status, Status::Valid, "{:?}", s.details);
assert!(said(&s, "trust list “Test List”"), "{:?}", s.details);
assert!(s.timestamp && s.timestamp_time.is_none(), "{:?}", s.details);
// A list that holds the authority's own certificate does not make its time trusted.
let both = TrustList::from_bytes("Both", &[i.cert.raw.clone(), tsa.cert.raw.clone()].concat()).unwrap();
let s = check(&TrustStore { lists: vec![both], ..TrustStore::default() });
assert_eq!(s.status, Status::Valid, "{:?}", s.details);
assert_eq!(s.timestamp_time, None, "{:?}", s.details);
assert!(said(&s, "unverified timestamp"), "{:?}", s.details);
// The user's own certificate for the authority is their decision, and it does.
let s = check(&TrustStore { certs: vec![tsa.cert.clone()], lists: vec![list] });
assert_eq!((s.status, s.timestamp_time), (Status::Valid, Some(stamped_at)), "{:?}", s.details);
}
+1 -1
View File
@@ -116,7 +116,7 @@ fn byte_range(added: &[u8], alg: pdfcraft_cos::Algorithm) -> [usize; 4] {
#[test]
fn signed_encrypted_documents_cover_their_earlier_revision() {
let id = pkcs12::open(&data("ec-p256.p12"), "test").unwrap();
let trust = TrustStore { certs: vec![id.certificate.clone()] };
let trust = TrustStore { certs: vec![id.certificate.clone()], ..TrustStore::default() };
for alg in ALL_ALGORITHMS {
let base = protected(alg, -1);
let doc = open_pw(&base, None);
+62 -58
View File
@@ -108,7 +108,7 @@ fn signing_then_validating_with_and_without_trust() {
assert!(sigs.iter().any(|s| s.field == "Approval" && !s.signed));
// Trusting the signer (or its root) makes it valid.
let anchor = id.chain.first().cloned().unwrap_or_else(|| id.certificate.clone());
let trusted = signatures(&doc, &signed, &TrustStore { certs: vec![anchor] });
let trusted = signatures(&doc, &signed, &TrustStore { certs: vec![anchor], ..TrustStore::default() });
let s = trusted.iter().find(|s| s.signed).unwrap();
assert_eq!(s.status, Status::Valid, "{file}: {:?}", s.details);
assert_eq!(s.chain.len(), if file == "chain.p12" { 2 } else { 1 });
@@ -273,7 +273,7 @@ fn an_indirect_annots_array_is_judged_by_the_annotations_it_gains() {
let annots_ref = |bytes: &[u8]| open(bytes).get(page).as_dict().and_then(|d| d.get(b"Annots").and_then(Object::as_ref));
let annots = annots_ref(&unsigned).unwrap();
let id = pkcs12::open(&data("rsa-aes.p12"), "test").unwrap();
let trust = TrustStore { certs: vec![id.certificate.clone()] };
let trust = TrustStore { certs: vec![id.certificate.clone()], ..TrustStore::default() };
let first = pdfcraft_sign::sign(&open(&unsigned), &id, &opts()).unwrap();
let second = pdfcraft_sign::sign(&open(&first), &id, &SignOptions { rect: Some([20.0, 160.0, 220.0, 210.0]), ..opts() }).unwrap();
assert_eq!(annots_ref(&second), Some(annots), "the signer kept the page's array indirect");
@@ -330,7 +330,7 @@ fn an_indirect_annots_array_is_judged_by_the_annotations_it_gains() {
#[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 trust = TrustStore { certs: vec![id.certificate.clone()], ..TrustStore::default() };
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();
@@ -445,7 +445,7 @@ fn change_text(doc: &mut Document) {
#[test]
fn later_changes_are_classified_under_the_signature_permissions() {
let id = pkcs12::open(&data("rsa-aes.p12"), "test").unwrap();
let trust = TrustStore { certs: vec![id.certificate.clone()] };
let trust = TrustStore { certs: vec![id.certificate.clone()], ..TrustStore::default() };
let check = |bytes: &[u8]| signatures(&open(bytes), bytes, &trust).into_iter().find(|s| s.signed).unwrap();
// Approval signature: comments are permitted, rewriting page content is not.
let signed = pdfcraft_sign::sign(&open(&fixture()), &id, &opts()).unwrap();
@@ -485,7 +485,7 @@ fn later_changes_are_classified_under_the_signature_permissions() {
/// Certify `fixture` with "no changes allowed" (DocMDP P=1).
fn certified_p1() -> (DigitalId, TrustStore, Vec<u8>) {
let id = pkcs12::open(&data("rsa-aes.p12"), "test").unwrap();
let trust = TrustStore { certs: vec![id.certificate.clone()] };
let trust = TrustStore { certs: vec![id.certificate.clone()], ..TrustStore::default() };
let signed = pdfcraft_sign::sign(&open(&fixture()), &id, &SignOptions { certify: Some(1), ..opts() }).unwrap();
(id, trust, signed)
}
@@ -565,7 +565,7 @@ fn certification_of(perms: &str) -> pdfcraft_sign::SignatureInfo {
b"<< /Type /Sig /Filter /Adobe.PPKLite /SubFilter /adbe.pkcs7.detached /Reference [<< /Type /SigRef /TransformMethod /DocMDP /TransformParams << /Type /TransformParams /P 1 /V /1.2 >> >>] >>",
b"<< /Type /Sig /Filter /Adobe.PPKLite /SubFilter /adbe.pkcs7.detached >>",
]);
signatures(&open(&bytes), &bytes, &TrustStore { certs: Vec::new() }).into_iter().find(|s| s.field == "Approval").unwrap()
signatures(&open(&bytes), &bytes, &TrustStore::default()).into_iter().find(|s| s.field == "Approval").unwrap()
}
/// Only the signature the catalog's `/Perms /DocMDP` names certifies the document: a DocMDP
@@ -900,14 +900,14 @@ fn signing_with_a_timestamp_embeds_a_verified_rfc3161_token() {
let signed = pdfcraft_sign::sign_with_timestamp(&open(&fixture()), &id, &opts(), &tsa).unwrap();
assert!(signed.starts_with(&fixture()), "still an incremental update");
let anchor = id.chain.first().cloned().unwrap_or_else(|| id.certificate.clone());
let trust = TrustStore { certs: vec![anchor.clone(), tsa.id.certificate.clone()] };
let trust = TrustStore { certs: vec![anchor.clone(), tsa.id.certificate.clone()], ..TrustStore::default() };
let s = signatures(&open(&signed), &signed, &trust).into_iter().find(|s| s.signed).unwrap();
assert_eq!(s.status, Status::Valid, "{:?}", s.details);
assert!(s.timestamp, "{:?}", s.details);
assert_eq!(s.timestamp_time, Some(tsa.time), "the token's generation time, verified over the signature value");
assert!(s.details.iter().any(|d| d.message.contains("trusted time")), "{:?}", s.details);
// A trusted signer with an untrusted TSA: still valid, but the token's time is unverified.
let s = signatures(&open(&signed), &signed, &TrustStore { certs: vec![anchor] }).into_iter().find(|s| s.signed).unwrap();
let s = signatures(&open(&signed), &signed, &TrustStore { certs: vec![anchor], ..TrustStore::default() }).into_iter().find(|s| s.signed).unwrap();
assert_eq!(s.status, Status::Valid, "{:?}", s.details);
assert!(s.timestamp);
assert_eq!(s.timestamp_time, None);
@@ -935,7 +935,7 @@ fn a_document_timestamp_covers_the_file_and_validates() {
let tsa = TestTsa { id: tsa_id(), time: Time { year: 2026, month: 10, day: 6, hour: 12, minute: 0, second: 0 } };
let stamped = pdfcraft_sign::timestamp_document(&open(&fixture()), &tsa, "D:20261006120000Z").unwrap();
assert!(stamped.starts_with(&fixture()), "an incremental update");
let trust_tsa = TrustStore { certs: vec![tsa.id.certificate.clone()] };
let trust_tsa = TrustStore { certs: vec![tsa.id.certificate.clone()], ..TrustStore::default() };
let s = signatures(&open(&stamped), &stamped, &trust_tsa).into_iter().find(|s| s.doc_timestamp).unwrap();
assert!(s.doc_timestamp && s.timestamp);
assert_eq!(s.sub_filter.as_deref(), Some("ETSI.RFC3161"));
@@ -953,7 +953,7 @@ fn a_document_timestamp_covers_the_file_and_validates() {
let id = pkcs12::open(&data("ec-p256.p12"), "test").unwrap();
let signed = pdfcraft_sign::sign(&open(&fixture()), &id, &opts()).unwrap();
let both = pdfcraft_sign::timestamp_document(&open(&signed), &tsa, "D:20261006130000Z").unwrap();
let all = signatures(&open(&both), &both, &TrustStore { certs: vec![tsa.id.certificate.clone()] });
let all = signatures(&open(&both), &both, &TrustStore { certs: vec![tsa.id.certificate.clone()], ..TrustStore::default() });
let field = all.iter().find(|s| s.signed && !s.doc_timestamp).unwrap();
let allowed = match &field.modification {
Modification::Allowed(k) => k,
@@ -976,7 +976,7 @@ fn cached_discovery_still_validates_current_timestamp_bytes_ranges_and_trust() {
let bytes = pdfcraft_sign::timestamp_document(&source, &tsa, "D:20261006120000Z").unwrap();
let doc = open(&bytes);
let cache = pdfcraft_sign::DigestCache::default();
let trusted = TrustStore { certs: vec![tsa.id.certificate.clone()] };
let trusted = TrustStore { certs: vec![tsa.id.certificate.clone()], ..TrustStore::default() };
let check = |doc: &Document, bytes: &[u8], trust: &TrustStore| {
let listed = pdfcraft_sign::pdf::list_cached(doc, bytes, trust, &cache);
assert_eq!(listed.len(), 1);
@@ -1008,7 +1008,7 @@ fn cached_discovery_still_validates_current_timestamp_bytes_ranges_and_trust() {
#[test]
fn ltv_writers_may_declare_the_esic_extension_but_not_change_a_signed_one() {
let id = pkcs12::open(&data("rsa-aes.p12"), "test").unwrap();
let trust = TrustStore { certs: vec![id.certificate.clone()] };
let trust = TrustStore { certs: vec![id.certificate.clone()], ..TrustStore::default() };
let check = |bytes: &[u8]| signatures(&open(bytes), bytes, &trust).into_iter().find(|s| s.signed).unwrap();
let ext = |base: &[u8], level: i64| {
let mut esic = pdfcraft_cos::Dict::new();
@@ -1082,7 +1082,7 @@ fn sign_then_ltv_then_timestamp_makes_a_b_lta_file() {
let signed = pdfcraft_sign::sign(&open(&fixture()), &id, &opts()).unwrap();
let ltv = dss::embed(&open(&signed), &Evidence { certs: vec![id.certificate.raw.clone()], ocsps: Vec::new(), crls: Vec::new() }).unwrap();
let lta = pdfcraft_sign::timestamp_document(&open(&ltv), &tsa, "D:20261006120000Z").unwrap();
let all = signatures(&open(&lta), &lta, &TrustStore { certs: vec![tsa.id.certificate.clone()] });
let all = signatures(&open(&lta), &lta, &TrustStore { certs: vec![tsa.id.certificate.clone()], ..TrustStore::default() });
assert_eq!(all.iter().filter(|s| s.signed).count(), 2);
let field = all.iter().find(|s| s.signed && !s.doc_timestamp).unwrap();
assert_eq!(field.status, Status::Unknown);
@@ -1106,7 +1106,7 @@ fn what_was_removed_before_signing_is_not_signed() {
let id = pkcs12::open(&data("ec-p256.p12"), "test").unwrap();
let tsa = TestTsa { id: tsa_id(), time: Time { year: 2026, month: 10, day: 6, hour: 12, minute: 0, second: 0 } };
let anchor = id.chain.first().cloned().unwrap_or_else(|| id.certificate.clone());
let trust = TrustStore { certs: vec![anchor, tsa.id.certificate.clone()] };
let trust = TrustStore { certs: vec![anchor, tsa.id.certificate.clone()], ..TrustStore::default() };
let text = |s: &str| Object::String(PdfString::literal(s.as_bytes().to_vec()));
let dict = |entries: &[(&str, Object)]| {
let mut d = Dict::new();
@@ -1201,7 +1201,7 @@ fn validates_a_signature_made_by_openssl() {
assert!(s.signing_time.is_some_and(|t| t.year == 2026), "from the CMS signing-time attribute");
assert!(!s.visible);
let rsa = pdfcraft_sign::Certificate::parse(&pkcs12::open(&data("rsa-aes.p12"), "test").unwrap().certificate.raw).unwrap();
let s = signatures(&doc, &bytes, &TrustStore { certs: vec![rsa] }).into_iter().next().unwrap();
let s = signatures(&doc, &bytes, &TrustStore { certs: vec![rsa], ..TrustStore::default() }).into_iter().next().unwrap();
assert_eq!(s.status, Status::Valid, "{:?}", s.details);
// A later comment is allowed for this approval signature.
let edited = edit_after(&bytes, add_comment);
@@ -1270,7 +1270,7 @@ fn signing_with_keychain_identities() {
for id in &ids {
assert!(id.key.is_external());
let signed = pdfcraft_sign::sign(&open(&fixture()), id, &opts()).unwrap();
let trusted = signatures(&open(&signed), &signed, &TrustStore { certs: vec![id.certificate.clone()] });
let trusted = signatures(&open(&signed), &signed, &TrustStore { certs: vec![id.certificate.clone()], ..TrustStore::default() });
let s = trusted.iter().find(|s| s.signed).unwrap();
assert_eq!(s.status, Status::Valid, "{:?}", s.details);
}
@@ -1420,7 +1420,7 @@ fn xfa_page_swap(doc: &mut Document) {
#[test]
fn a_later_field_with_the_same_name_does_not_inherit_the_signature() {
let id = pkcs12::open(&data("rsa-aes.p12"), "test").unwrap();
let trust = TrustStore { certs: vec![id.certificate.clone()] };
let trust = TrustStore { certs: vec![id.certificate.clone()], ..TrustStore::default() };
let signed = pdfcraft_sign::sign(&open(&fixture()), &id, &SignOptions { field: Some("Approval".into()), ..opts() }).unwrap();
let edited = edit_after(&signed, |doc| {
let root = doc.root().unwrap();
@@ -1463,7 +1463,7 @@ fn a_later_field_with_the_same_name_does_not_inherit_the_signature() {
#[test]
fn toggling_needs_rendering_is_a_structure_change() {
let id = pkcs12::open(&data("rsa-aes.p12"), "test").unwrap();
let trust = TrustStore { certs: vec![id.certificate.clone()] };
let trust = TrustStore { certs: vec![id.certificate.clone()], ..TrustStore::default() };
let check = |bytes: &[u8]| signatures(&open(bytes), bytes, &trust).into_iter().find(|s| s.signed).unwrap();
let certified = pdfcraft_sign::sign(&open(&fixture()), &id, &SignOptions { certify: Some(1), ..opts() }).unwrap();
assert_eq!(check(&certified).status, Status::Valid);
@@ -1479,7 +1479,7 @@ fn toggling_needs_rendering_is_a_structure_change() {
#[test]
fn declaring_a_form_xfa_does_not_excuse_replacing_the_pages() {
let id = pkcs12::open(&data("rsa-aes.p12"), "test").unwrap();
let trust = TrustStore { certs: vec![id.certificate.clone()] };
let trust = TrustStore { certs: vec![id.certificate.clone()], ..TrustStore::default() };
let check = |bytes: &[u8]| signatures(&open(bytes), bytes, &trust).into_iter().find(|s| s.signed).unwrap();
for certify in [None, Some(2), Some(3)] {
let signed = pdfcraft_sign::sign(&open(&fixture()), &id, &SignOptions { certify, ..opts() }).unwrap();
@@ -1515,7 +1515,7 @@ fn rewrite_stream(num: u32, body: &'static [u8]) -> impl FnOnce(&mut Document) {
#[test]
fn rewriting_a_certified_forms_xfa_data_is_a_form_fill() {
let id = pkcs12::open(&data("rsa-aes.p12"), "test").unwrap();
let trust = TrustStore { certs: vec![id.certificate.clone()] };
let trust = TrustStore { certs: vec![id.certificate.clone()], ..TrustStore::default() };
let check = |bytes: &[u8]| signatures(&open(bytes), bytes, &trust).into_iter().find(|s| s.signed).unwrap();
let certified = pdfcraft_sign::sign(&open(&xfa_fixture()), &id, &SignOptions { certify: Some(2), ..opts() }).unwrap();
assert_eq!(check(&certified).status, Status::Valid);
@@ -1580,7 +1580,8 @@ fn validates_signatures_written_with_ber_indefinite_lengths() {
ber.resize((b - a) / 2, 0);
signed[a..b].copy_from_slice(hex(&ber).as_bytes());
let anchor = id.certificate.clone();
let s = signatures(&open(&signed), &signed, &TrustStore { certs: vec![anchor] }).into_iter().find(|s| s.signed).unwrap();
let s =
signatures(&open(&signed), &signed, &TrustStore { certs: vec![anchor], ..TrustStore::default() }).into_iter().find(|s| s.signed).unwrap();
assert_eq!(s.status, Status::Valid, "{file}: {:?}", s.details);
assert!(s.details.iter().any(|d| d.message.contains("BER")), "the tolerance is reported: {:?}", s.details);
// Tampering is still caught: the digest check is not relaxed.
@@ -1637,7 +1638,7 @@ const MESSAGE_DIGEST: &str = "1.2.840.113549.1.9.4";
#[test]
fn signed_attributes_must_bind_the_document() {
let id = pkcs12::open(&data("rsa-aes.p12"), "test").unwrap();
let trust = TrustStore { certs: vec![id.certificate.clone()] };
let trust = TrustStore { certs: vec![id.certificate.clone()], ..TrustStore::default() };
let signed = pdfcraft_sign::sign(&open(&fixture()), &id, &opts()).unwrap();
let (a, b) = contents_span(&signed);
let digest = pdfcraft_sign::DigestAlg::Sha256.digest(&[&signed[..a - 1], &signed[b + 1..]]);
@@ -1792,7 +1793,7 @@ const LEVELS: [Option<u8>; 4] = [None, Some(1), Some(2), Some(3)];
/// reasons, while the untouched file stays valid.
fn assert_refused_at_every_level(base: &[u8], kind: &str, attack: impl Fn(&mut Document)) {
let id = pkcs12::open(&data("rsa-aes.p12"), "test").unwrap();
let trust = TrustStore { certs: vec![id.certificate.clone()] };
let trust = TrustStore { certs: vec![id.certificate.clone()], ..TrustStore::default() };
let check = |bytes: &[u8]| signatures(&open(bytes), bytes, &trust).into_iter().find(|s| s.signed).unwrap();
for certify in LEVELS {
let signed = pdfcraft_sign::sign(&open(base), &id, &SignOptions { certify, ..opts() }).unwrap();
@@ -2008,7 +2009,7 @@ fn the_forms_signed_fields_are_not_dropped_after_signing() {
id: pkcs12::open(&data("rsa-aes.p12"), "test").unwrap(),
time: Time { year: 2026, month: 10, day: 6, hour: 12, minute: 0, second: 0 },
};
let trust = TrustStore { certs: vec![id.certificate.clone()] };
let trust = TrustStore { certs: vec![id.certificate.clone()], ..TrustStore::default() };
let signed = pdfcraft_sign::sign(&open(&fixture_with_indirect_acroform()), &id, &opts()).unwrap();
let stamped = pdfcraft_sign::timestamp_document(&open(&signed), &tsa, "D:20261006120000Z").unwrap();
let mut failures = Vec::new();
@@ -2098,7 +2099,7 @@ fn the_catalogs_own_xmp_stream_may_still_be_rewritten_after_signing() {
// document's XMP, and rewriting it is allowed at every level.
let base = fixture_with_stream_7("/Metadata 7 0 R", false, "/Type /Metadata /Subtype /XML", b"<x:xmpmeta/>");
let id = pkcs12::open(&data("rsa-aes.p12"), "test").unwrap();
let trust = TrustStore { certs: vec![id.certificate.clone()] };
let trust = TrustStore { certs: vec![id.certificate.clone()], ..TrustStore::default() };
for certify in LEVELS {
let signed = pdfcraft_sign::sign(&open(&base), &id, &SignOptions { certify, ..opts() }).unwrap();
let edited = edit_after(&signed, |doc| {
@@ -2129,7 +2130,7 @@ fn fixture_with_dss() -> (Vec<u8>, u32, u32) {
#[test]
fn a_signed_store_may_grow_but_not_lose_or_swap_entries() {
let id = pkcs12::open(&data("rsa-aes.p12"), "test").unwrap();
let trust = TrustStore { certs: vec![id.certificate.clone()] };
let trust = TrustStore { certs: vec![id.certificate.clone()], ..TrustStore::default() };
let check = |bytes: &[u8]| signatures(&open(bytes), bytes, &trust).into_iter().find(|s| s.signed).unwrap();
let (base, certs, vri) = fixture_with_dss();
for certify in LEVELS {
@@ -2164,7 +2165,7 @@ fn a_signed_store_may_grow_but_not_lose_or_swap_entries() {
#[test]
fn a_form_xobject_relabelled_metadata_is_not_a_metadata_change() {
let id = pkcs12::open(&data("rsa-aes.p12"), "test").unwrap();
let trust = TrustStore { certs: vec![id.certificate.clone()] };
let trust = TrustStore { certs: vec![id.certificate.clone()], ..TrustStore::default() };
let signed = pdfcraft_sign::sign(&open(&fixture_with_xobject()), &id, &opts()).unwrap();
let relabel = |doc: &mut Document| {
let mut d = pdfcraft_cos::Dict::new();
@@ -2212,7 +2213,7 @@ fn a_form_xobject_relabelled_as_file_plumbing_is_still_judged() {
// drawn Form XObject rewritten after signing and labelled /ObjStm or /XRef still shows its
// new content (the renderer ignores /Type), so it must not be skipped.
let id = pkcs12::open(&data("rsa-aes.p12"), "test").unwrap();
let trust = TrustStore { certs: vec![id.certificate.clone()] };
let trust = TrustStore { certs: vec![id.certificate.clone()], ..TrustStore::default() };
for certify in LEVELS {
let signed = pdfcraft_sign::sign(&open(&fixture_with_xobject()), &id, &SignOptions { certify, ..opts() }).unwrap();
for label in ["ObjStm", "XRef"] {
@@ -2290,7 +2291,7 @@ fn a_signed_page_relabelled_or_stripped_of_type_is_still_page_content() {
// Positive control: an ordinary /Info /ModDate bump on the signed revision's own information
// dictionary stays a permitted metadata change.
let id = pkcs12::open(&data("rsa-aes.p12"), "test").unwrap();
let trust = TrustStore { certs: vec![id.certificate.clone()] };
let trust = TrustStore { certs: vec![id.certificate.clone()], ..TrustStore::default() };
for certify in LEVELS {
let signed = pdfcraft_sign::sign(&open(&fixture_with_info()), &id, &SignOptions { certify, ..opts() }).unwrap();
let bumped = edit_after(&signed, |doc| {
@@ -2331,7 +2332,7 @@ fn a_revoked_certificate_stays_invalid_when_it_was_also_expired_at_signing() {
let crl = self_crl(&id, t(2039), t(2041), t(2039));
let ltv = dss::embed(&open(&signed), &Evidence { certs: Vec::new(), ocsps: Vec::new(), crls: vec![crl] }).unwrap();
let anchor = id.chain.first().cloned().unwrap_or_else(|| id.certificate.clone());
for trust in [TrustStore::default(), TrustStore { certs: vec![anchor] }] {
for trust in [TrustStore::default(), TrustStore { certs: vec![anchor], ..TrustStore::default() }] {
let s = signatures(&open(&ltv), &ltv, &trust).into_iter().find(|s| s.signed && !s.doc_timestamp).unwrap();
assert!(s.details.iter().any(|d| d.message.contains("not valid at the time of signing")), "{:?}", s.details);
assert_eq!(s.status, Status::Invalid, "{:?}", s.details);
@@ -2346,7 +2347,7 @@ fn a_revocation_behind_many_dss_entries_is_not_reported_valid() {
let t = |year| Time { year, month: 1, day: 1, hour: 0, minute: 0, second: 0 };
let crl = self_crl(&id, t(2026), t(2027), Time { year: 2026, month: 6, day: 1, hour: 8, minute: 0, second: 0 });
let anchor = id.chain.first().cloned().unwrap_or_else(|| id.certificate.clone());
let trust = TrustStore { certs: vec![anchor] };
let trust = TrustStore { certs: vec![anchor], ..TrustStore::default() };
// `/CRLs`: the revoking CRL after `benign` other entries; `repeated` lists one stream for all of them.
let status = |benign: usize, repeated: bool| {
let ltv = edit_after(&signed, |doc| {
@@ -2379,14 +2380,17 @@ fn an_untrusted_timestamp_does_not_set_the_validation_time() {
let late = SignOptions { date: "D:20400101120000Z".into(), ..opts() };
let signed = pdfcraft_sign::sign_with_timestamp(&open(&fixture()), &id, &late, &tsa).unwrap();
let anchor = id.chain.first().cloned().unwrap_or_else(|| id.certificate.clone());
let s = signatures(&open(&signed), &signed, &TrustStore { certs: vec![anchor.clone()] }).into_iter().find(|s| s.signed).unwrap();
let s = signatures(&open(&signed), &signed, &TrustStore { certs: vec![anchor.clone()], ..TrustStore::default() })
.into_iter()
.find(|s| s.signed)
.unwrap();
assert_ne!(s.status, Status::Valid, "{:?}", s.details);
assert_eq!(s.timestamp_time, None, "an untrusted token's time is not a trusted time");
assert!(s.details.iter().any(|d| d.message.contains("not valid at the time of signing")), "{:?}", s.details);
assert!(!s.details.iter().any(|d| d.message.contains("trusted time")), "{:?}", s.details);
assert!(s.details.iter().any(|d| d.message.contains("unverified timestamp")), "{:?}", s.details);
// Trusting the TSA makes its time authoritative: the certificate was valid then.
let trust = TrustStore { certs: vec![anchor, tsa.id.certificate.clone()] };
let trust = TrustStore { certs: vec![anchor, tsa.id.certificate.clone()], ..TrustStore::default() };
let s = signatures(&open(&signed), &signed, &trust).into_iter().find(|s| s.signed).unwrap();
assert_eq!(s.timestamp_time, Some(tsa.time));
assert_eq!(s.status, Status::Valid, "{:?}", s.details);
@@ -2513,7 +2517,7 @@ fn signing_with_windows_store_identities() {
assert!(now.status.success());
options.date = format!("D:{}Z", String::from_utf8(now.stdout).unwrap().trim());
let signed = pdfcraft_sign::sign(&open(&fixture()), &id, &options).unwrap();
let validated = signatures(&open(&signed), &signed, &TrustStore { certs: vec![id.certificate.clone()] });
let validated = signatures(&open(&signed), &signed, &TrustStore { certs: vec![id.certificate.clone()], ..TrustStore::default() });
let signature = validated.iter().find(|s| s.signed).unwrap();
assert_eq!(signature.status, Status::Valid, "{:?}", signature.details);
assert_eq!(signature.modification, Modification::None);
@@ -2583,7 +2587,7 @@ fn a_windows_store_identity_signs_with_its_issuers() {
assert!(now.status.success());
options.date = format!("D:{}Z", String::from_utf8(now.stdout).unwrap().trim());
let signed = pdfcraft_sign::sign(&open(&fixture()), &id, &options).unwrap();
let validated = signatures(&open(&signed), &signed, &TrustStore { certs: vec![anchor] });
let validated = signatures(&open(&signed), &signed, &TrustStore { certs: vec![anchor], ..TrustStore::default() });
let signature = validated.iter().find(|s| s.signed).unwrap();
assert_eq!(signature.status, Status::Valid, "{:?}", signature.details);
assert_eq!(signature.signer.as_deref(), Some(signer.as_str()));
@@ -2632,7 +2636,7 @@ fn fixture_timestamped_in_a_field(tsa: &TestTsa) -> Vec<u8> {
fn a_document_timestamp_held_by_a_signature_field_is_checked_as_a_timestamp() {
let tsa = TestTsa { id: tsa_id(), time: Time { year: 2026, month: 10, day: 6, hour: 12, minute: 0, second: 0 } };
let stamped = fixture_timestamped_in_a_field(&tsa);
let trust = TrustStore { certs: vec![tsa.id.certificate.clone()] };
let trust = TrustStore { certs: vec![tsa.id.certificate.clone()], ..TrustStore::default() };
let all = signatures(&open(&stamped), &stamped, &trust);
let stamps: Vec<_> = all.iter().filter(|s| s.signed).collect();
assert_eq!(stamps.len(), 1, "listed once, not as field and as standalone: {:?}", all.iter().map(|s| &s.field).collect::<Vec<_>>());
@@ -2665,7 +2669,7 @@ fn a_field_timestamp_from_a_trusted_tsa_outside_its_validity_is_not_valid() {
time: Time { year: 2020, month: 1, day: 1, hour: 0, minute: 0, second: 0 },
};
let stamped = fixture_timestamped_in_a_field(&tsa);
let trust = TrustStore { certs: vec![tsa.id.certificate.clone()] };
let trust = TrustStore { certs: vec![tsa.id.certificate.clone()], ..TrustStore::default() };
let s = signatures(&open(&stamped), &stamped, &trust).into_iter().find(|s| s.signed).unwrap();
assert!(s.doc_timestamp);
assert_eq!(s.status, Status::Unknown, "{:?}", s.details);
@@ -2717,7 +2721,7 @@ fn validates_the_legacy_adbe_x509_rsa_sha1_format() {
let weak = "This signature uses SHA-1, a weak hash algorithm: collisions in it have been demonstrated. It still validates because many documents signed years ago use it, but it should not be relied on.";
assert_eq!(s.details.iter().filter(|d| d.message == weak).count(), 1, "{:?}", s.details);
assert!(s.details.iter().any(|d| d.message.contains("legacy adbe.x509.rsa_sha1 format")), "{:?}", s.details);
let trusted = TrustStore { certs: vec![id.certificate.clone()] };
let trusted = TrustStore { certs: vec![id.certificate.clone()], ..TrustStore::default() };
let s = signatures(&open(&pdf), &pdf, &trusted).into_iter().find(|s| s.signed).unwrap();
assert_eq!(s.status, Status::Valid, "{:?}", s.details);
// One changed byte inside the signed range.
@@ -2757,7 +2761,7 @@ fn protected_with(alg: pdfcraft_cos::Algorithm, user: &str, permissions: i32) ->
fn a_user_password_document_keeps_its_earlier_signature_valid_when_counter_signed() {
let id = pkcs12::open(&data("ec-p256.p12"), "test").unwrap();
let id2 = pkcs12::open(&data("rsa-aes.p12"), "test").unwrap();
let trust = TrustStore { certs: vec![id.certificate.clone(), id2.certificate.clone()] };
let trust = TrustStore { certs: vec![id.certificate.clone(), id2.certificate.clone()], ..TrustStore::default() };
for alg in ALL_ALGORITHMS {
let base = protected_with(alg, "secret", -1);
assert!(Document::open_with_password(Arc::new(base.clone()), None).is_err(), "{alg:?}: the file asks for its password");
@@ -2796,7 +2800,7 @@ const ALL_ALGORITHMS: [pdfcraft_cos::Algorithm; 4] =
fn encrypted_documents_are_signed_with_an_unencrypted_contents() {
let id = pkcs12::open(&data("ec-p256.p12"), "test").unwrap();
let id2 = pkcs12::open(&data("rsa-aes.p12"), "test").unwrap();
let trust = TrustStore { certs: vec![id.certificate.clone(), id2.certificate.clone()] };
let trust = TrustStore { certs: vec![id.certificate.clone(), id2.certificate.clone()], ..TrustStore::default() };
for alg in ALL_ALGORITHMS {
let base = protected(alg, -1);
let doc = open_pw(&base, None);
@@ -2843,7 +2847,7 @@ fn encrypted_documents_are_signed_with_an_unencrypted_contents() {
#[test]
fn an_encrypted_documents_signature_graphic_is_encrypted_with_it() {
let id = pkcs12::open(&data("ec-p256.p12"), "test").unwrap();
let trust = TrustStore { certs: vec![id.certificate.clone()] };
let trust = TrustStore { certs: vec![id.certificate.clone()], ..TrustStore::default() };
for alg in ALL_ALGORITHMS {
let base = protected(alg, -1);
let signed = pdfcraft_sign::sign(&open_pw(&base, None), &id, &SignOptions { graphic: Some(picture(true)), ..opts() }).unwrap();
@@ -2865,7 +2869,7 @@ fn an_encrypted_documents_signature_graphic_is_encrypted_with_it() {
#[test]
fn encrypted_documents_are_signed_only_as_their_permissions_allow() {
let id = pkcs12::open(&data("ec-p256.p12"), "test").unwrap();
let trust = TrustStore { certs: vec![id.certificate.clone()] };
let trust = TrustStore { certs: vec![id.certificate.clone()], ..TrustStore::default() };
let base = protected(pdfcraft_cos::Algorithm::Aes256, FILL_AND_SIGN_ONLY);
let user = open_pw(&base, None);
let refused = |r: Result<Vec<u8>, SignError>, what: &str| match r {
@@ -2910,7 +2914,7 @@ fn encrypted_documents_take_a_document_timestamp() {
let base = protected(pdfcraft_cos::Algorithm::Aes128, FILL_AND_SIGN_ONLY);
let stamped = pdfcraft_sign::timestamp_document(&open_pw(&base, None), &tsa, "D:20261006120000Z").unwrap();
assert!(stamped.starts_with(&base));
let s = signatures(&open_pw(&stamped, None), &stamped, &TrustStore { certs: vec![tsa.id.certificate.clone()] })
let s = signatures(&open_pw(&stamped, None), &stamped, &TrustStore { certs: vec![tsa.id.certificate.clone()], ..TrustStore::default() })
.into_iter()
.find(|s| s.doc_timestamp)
.unwrap();
@@ -3020,7 +3024,7 @@ fn visible_appearance_draws_central_european_characters_with_embedded_font() {
assert!(fonts.contains(b"PCFull0"), "appearance should reference the embedded font: {fonts:?}");
// Verify signature validation still passes.
let doc = open(&signed);
let trust = TrustStore { certs: vec![luka_id.certificate.clone()] };
let trust = TrustStore { certs: vec![luka_id.certificate.clone()], ..TrustStore::default() };
let s = signatures(&doc, &signed, &trust).into_iter().find(|s| s.signed).unwrap();
assert_eq!(s.status, Status::Valid);
assert_eq!(s.reason.as_deref(), Some("Podpisano s potrdilom"));
@@ -3177,7 +3181,7 @@ fn xref_entry(offset: usize) -> String {
#[test]
fn a_cross_reference_entry_the_reader_sets_aside_does_not_hide_new_page_content() {
let id = pkcs12::open(&data("rsa-aes.p12"), "test").unwrap();
let trust = TrustStore { certs: vec![id.certificate.clone()] };
let trust = TrustStore { certs: vec![id.certificate.clone()], ..TrustStore::default() };
for certify in LEVELS {
let signed = pdfcraft_sign::sign(&open(&fixture()), &id, &SignOptions { certify, ..opts() }).unwrap();
// Where the signed revision keeps the page's content stream.
@@ -3209,7 +3213,7 @@ fn a_cross_reference_entry_the_reader_sets_aside_does_not_hide_new_page_content(
#[test]
fn a_cross_reference_entry_that_misses_its_object_is_not_an_unchanged_object() {
let id = pkcs12::open(&data("rsa-aes.p12"), "test").unwrap();
let trust = TrustStore { certs: vec![id.certificate.clone()] };
let trust = TrustStore { certs: vec![id.certificate.clone()], ..TrustStore::default() };
let signed = pdfcraft_sign::sign(&open(&fixture()), &id, &opts()).unwrap();
// A copy of the signed content, named by an entry two bytes into its `4 0 obj` header.
let edited = append_content_revision(&signed, "Contract text", |new| format!("4 1\n{}", xref_entry(new + 2)));
@@ -3256,7 +3260,7 @@ fn append_revision(signed: &[u8], bodies: &[&str], trailer_extra: &str, xref: im
#[test]
fn an_unlisted_object_body_or_an_entry_that_points_at_no_object_is_not_permitted() {
let id = pkcs12::open(&data("rsa-aes.p12"), "test").unwrap();
let trust = TrustStore { certs: vec![id.certificate.clone()] };
let trust = TrustStore { certs: vec![id.certificate.clone()], ..TrustStore::default() };
let text = "BT /F1 14 Tf 20 250 Td (Forged text) Tj ET";
let forged = format!("4 0 obj\n<< /Length {} >>\nstream\n{text}\nendstream\nendobj\n", text.len());
let unused = "60 0 obj\n(unused)\nendobj\n";
@@ -3371,7 +3375,7 @@ fn append_signature_with_unlisted_xref_stream(signed: &[u8], xref_num: u32, anno
#[test]
fn a_cross_reference_stream_without_a_row_for_itself_is_no_unlisted_body() {
let id = pkcs12::open(&data("rsa-aes.p12"), "test").unwrap();
let trust = TrustStore { certs: vec![id.certificate.clone()] };
let trust = TrustStore { certs: vec![id.certificate.clone()], ..TrustStore::default() };
for certify in [Some(2), None] {
let signed = pdfcraft_sign::sign(&open(&fixture()), &id, &SignOptions { certify, ..opts() }).unwrap();
let check = |bytes: &[u8]| signatures(&open(bytes), bytes, &trust).into_iter().find(|s| s.field == "Signature1").unwrap();
@@ -3506,7 +3510,7 @@ fn rewritten_page_resources_are_page_content_whatever_keys_they_carry() {
// content draws, so it is not page content (it is still an unclassified change, refused as
// "other", as before).
let id = pkcs12::open(&data("rsa-aes.p12"), "test").unwrap();
let trust = TrustStore { certs: vec![id.certificate.clone()] };
let trust = TrustStore { certs: vec![id.certificate.clone()], ..TrustStore::default() };
let signed = pdfcraft_sign::sign(&open(&fixture_with_indirect_resources()), &id, &SignOptions { certify: Some(3), ..opts() }).unwrap();
let grown = edit_after(&signed, |doc| {
let f = courier(doc);
@@ -3534,7 +3538,7 @@ fn switching_the_trailer_to_another_signed_catalog_is_not_permitted() {
],
);
let id = pkcs12::open(&data("ec-p256.p12"), "test").unwrap();
let trust = TrustStore { certs: vec![id.certificate.clone()] };
let trust = TrustStore { certs: vec![id.certificate.clone()], ..TrustStore::default() };
let signed = pdfcraft_sign::sign(&open(&base), &id, &SignOptions { field: Some("Approval".into()), rect: None, ..opts() }).unwrap();
let s = signatures(&open(&signed), &signed, &trust).into_iter().find(|s| s.signed).unwrap();
assert_eq!(s.status, Status::Valid, "{:?}", s.details);
@@ -3551,13 +3555,13 @@ fn switching_the_trailer_to_another_signed_catalog_is_not_permitted() {
fn a_timestamp_from_a_certificate_not_issued_for_time_stamping_is_not_trusted_time() {
let tsa = TestTsa { id: tsa_id_with(&["1.3.6.1.5.5.7.3.4"]), time: Time { year: 2026, month: 10, day: 6, hour: 12, minute: 0, second: 0 } };
let stamped = pdfcraft_sign::timestamp_document(&open(&fixture()), &tsa, "D:20261006120000Z").unwrap();
let trust = TrustStore { certs: vec![tsa.id.certificate.clone()] };
let trust = TrustStore { certs: vec![tsa.id.certificate.clone()], ..TrustStore::default() };
let s = signatures(&open(&stamped), &stamped, &trust).into_iter().find(|s| s.doc_timestamp).unwrap();
assert_eq!(s.status, Status::Unknown, "{:?}", s.details);
assert!(s.details.iter().any(|d| d.message.contains("not issued for time stamping")), "{:?}", s.details);
let id = pkcs12::open(&data("ec-p256.p12"), "test").unwrap();
let signed = pdfcraft_sign::sign_with_timestamp(&open(&fixture()), &id, &opts(), &tsa).unwrap();
let trust = TrustStore { certs: vec![id.certificate.clone(), tsa.id.certificate.clone()] };
let trust = TrustStore { certs: vec![id.certificate.clone(), tsa.id.certificate.clone()], ..TrustStore::default() };
let s = signatures(&open(&signed), &signed, &trust).into_iter().find(|s| s.signed).unwrap();
assert!(s.timestamp);
assert_eq!(s.timestamp_time, None, "{:?}", s.details);
@@ -3570,7 +3574,7 @@ fn a_timestamp_from_a_certificate_not_issued_for_time_stamping_is_not_trusted_ti
#[test]
fn freeing_a_signed_object_or_rewriting_the_signed_widget_is_a_page_content_change() {
let id = pkcs12::open(&data("rsa-aes.p12"), "test").unwrap();
let trust = TrustStore { certs: vec![id.certificate.clone()] };
let trust = TrustStore { certs: vec![id.certificate.clone()], ..TrustStore::default() };
let check = |bytes: &[u8]| signatures(&open(bytes), bytes, &trust).into_iter().find(|s| s.signed).unwrap();
let signed = pdfcraft_sign::sign(&open(&fixture()), &id, &opts()).unwrap();
let freed = check(&edit_after(&signed, |doc| doc.free(pdfcraft_cos::ObjRef { num: 5, generation: 0 })));
@@ -3595,7 +3599,7 @@ fn freeing_a_signed_object_or_rewriting_the_signed_widget_is_a_page_content_chan
#[test]
fn signing_a_field_with_a_null_value_after_another_signature_keeps_the_first_valid() {
let id = pkcs12::open(&data("rsa-aes.p12"), "test").unwrap();
let trust = TrustStore { certs: vec![id.certificate.clone()] };
let trust = TrustStore { certs: vec![id.certificate.clone()], ..TrustStore::default() };
let first = pdfcraft_sign::sign(&open(&fixture()), &id, &opts()).unwrap();
let second = pdfcraft_sign::sign(&open(&first), &id, &SignOptions { field: Some("Approval".into()), ..opts() }).unwrap();
let all = signatures(&open(&second), &second, &trust);
@@ -3681,7 +3685,7 @@ fn signed_catalog_and_page_tree_keep_their_role_when_relabelled_or_dropped() {
#[test]
fn signed_signature_objects_and_byte_ranges_are_read_from_the_signed_revision() {
let id = pkcs12::open(&data("ec-p256.p12"), "test").unwrap();
let trust = TrustStore { certs: vec![id.certificate.clone()] };
let trust = TrustStore { certs: vec![id.certificate.clone()], ..TrustStore::default() };
let signed = pdfcraft_sign::sign(&open(&fixture()), &id, &SignOptions { certify: Some(1), ..opts() }).unwrap();
let sig_ref = open(&signed)
.object_numbers()
@@ -3738,7 +3742,7 @@ fn signed_signature_objects_and_byte_ranges_are_read_from_the_signed_revision()
fn certify_level_one_forbids_adding_signature_fields_or_counter_signing() {
let id = pkcs12::open(&data("ec-p256.p12"), "test").unwrap();
let tsa = TestTsa { id: tsa_id(), time: Time { year: 2026, month: 10, day: 6, hour: 12, minute: 0, second: 0 } };
let trust = TrustStore { certs: vec![id.certificate.clone(), tsa.id.certificate.clone()] };
let trust = TrustStore { certs: vec![id.certificate.clone(), tsa.id.certificate.clone()], ..TrustStore::default() };
let certified_p1 = pdfcraft_sign::sign(&open(&fixture()), &id, &SignOptions { certify: Some(1), ..opts() }).unwrap();
let counter_p1 = pdfcraft_sign::sign(&open(&certified_p1), &id, &SignOptions { field: Some("Approval".into()), ..opts() }).unwrap();
let first_p1 = signatures(&open(&counter_p1), &counter_p1, &trust).into_iter().find(|s| s.field == "Signature1").unwrap();
@@ -3779,7 +3783,7 @@ fn certify_level_one_forbids_adding_signature_fields_or_counter_signing() {
#[test]
fn fields_sharing_a_signature_value_are_listed_with_one_verdict() {
let id = pkcs12::open(&data("rsa-aes.p12"), "test").unwrap();
let trust = TrustStore { certs: vec![id.certificate.clone()] };
let trust = TrustStore { certs: vec![id.certificate.clone()], ..TrustStore::default() };
let signed = pdfcraft_sign::sign(&open(&fixture()), &id, &SignOptions { field: Some("Approval".into()), ..opts() }).unwrap();
let v = open(&signed).get(pdfcraft_cos::ObjRef { num: 6, generation: 0 }).as_dict().and_then(|d| d.get(b"V").cloned()).unwrap();
let shared = edit_after(&signed, |doc| {
@@ -3811,7 +3815,7 @@ fn the_catalogs_perms_do_not_change_under_no_changes() {
// /Perms names the certification signature (DocMDP). Under P=1 nothing may change, so a later
// revision that drops it, or points it elsewhere, breaks the certification.
let id = pkcs12::open(&data("rsa-aes.p12"), "test").unwrap();
let trust = TrustStore { certs: vec![id.certificate.clone()] };
let trust = TrustStore { certs: vec![id.certificate.clone()], ..TrustStore::default() };
let certified = pdfcraft_sign::sign(&open(&fixture()), &id, &SignOptions { certify: Some(1), ..opts() }).unwrap();
let elsewhere = dict_of(vec![("DocMDP", oref(5))]);
for (how, perms) in [("dropped", None), ("pointed elsewhere", Some(Object::Dict(elsewhere)))] {
@@ -78,7 +78,7 @@ fn opts(certify: u8) -> SignOptions {
/// The certification signature of `bytes`, which must be refused.
fn assert_refused(bytes: &[u8]) {
let id = pkcs12::open(&data("rsa-aes.p12"), "test").unwrap();
let trust = TrustStore { certs: vec![id.certificate.clone()] };
let trust = TrustStore { certs: vec![id.certificate.clone()], ..TrustStore::default() };
let s = signatures(&open(bytes), bytes, &trust).into_iter().find(|s| s.signed).unwrap();
assert!(matches!(s.modification, Modification::Disallowed(_)) && s.status != Status::Valid, "main returns {:?}, {:?}", s.status, s.modification);
}
+1 -1
View File
@@ -69,7 +69,7 @@ fn edit_after(signed: &[u8], f: impl FnOnce(&mut Document)) -> Vec<u8> {
/// The certification signature of `bytes`: its status and modification verdict.
fn verdict(bytes: &[u8]) -> (Status, Modification) {
let id = pkcs12::open(&data("rsa-aes.p12"), "test").unwrap();
let trust = TrustStore { certs: vec![id.certificate.clone()] };
let trust = TrustStore { certs: vec![id.certificate.clone()], ..TrustStore::default() };
let s = signatures(&open(bytes), bytes, &trust).into_iter().find(|s| s.signed && s.certify.is_some()).unwrap();
(s.status, s.modification)
}
+3
View File
@@ -92,6 +92,9 @@ js-sys = "0.3"
web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "Url", "HtmlIFrameElement", "HtmlImageElement", "HtmlCollection", "Node", "EventTarget", "Navigator", "RequestCache", "RequestInit", "Response", "Worker", "WorkerOptions", "WorkerType", "MessageEvent"] }
[dev-dependencies]
# Exercise preference round-trips in the persisted config.toml format.
toml = "1"
pdfcraft-testkit = { workspace = true }
# The fixture and suite runner the component trials drive the app's components with.
craft = { workspace = true, features = ["ui-testing", "zip"] }
pdfcraft-xfa = { workspace = true }
+26 -2
View File
@@ -295,9 +295,11 @@ impl PdfCraftApp {
rename_returned: rename_ui::Returned::default(),
active: None,
last_frame_active: None,
typing_refused: false,
mode: Mode::AllTools,
default_mode: Mode::AllTools,
view_defaults: Default::default(),
show_form_field_reminder: true,
highlight_fields: true,
units: Default::default(),
blank_paper: crate::paper::Paper::system(),
@@ -333,6 +335,7 @@ impl PdfCraftApp {
ui_scale: None,
title_bar_choice: Default::default(),
requires_native_frame: false,
applied_title_bar: None,
flatten_fill_sign_on_save: false,
ask_to_lock_signatures: true,
placed_signatures: Default::default(),
@@ -371,6 +374,7 @@ impl PdfCraftApp {
reload_changed_files: true,
update_check_at_start: true,
at_exit: None,
startup_time: None,
show_secured_notice: true,
text_links: true,
always_default_view: false,
@@ -381,6 +385,8 @@ impl PdfCraftApp {
#[cfg(not(target_arch = "wasm32"))]
pending_opens: Vec::new(),
#[cfg(not(target_arch = "wasm32"))]
opening_notice: None,
#[cfg(not(target_arch = "wasm32"))]
password_retry: None,
#[cfg(not(target_arch = "wasm32"))]
next_open_token: 0,
@@ -557,8 +563,21 @@ impl PdfCraftApp {
static SIZES: std::sync::OnceLock<Arc<craft::theme::AppSizes>> = std::sync::OnceLock::new();
let sizes = SIZES.get_or_init(|| {
let mut sizes = craft::theme::AppSizes::default();
sizes.all.insert("typography.display.size".into(), craft::theme::SizeValue::Number(24.0));
sizes.all.insert("typography.display.line_height".into(), craft::theme::SizeValue::Number(29.0));
// PdfCraft's shapes and sizes from before the framework port (v0.22.0's `theme.rs`), over the
// framework's Comfortable set: buttons with 6-point corners rather than pills, windows with 10-point
// corners, 13-point button labels, 11-point small text and 8 points between neighbouring controls.
// They go in the Comfortable section only, so Compact keeps the framework's own tighter set.
for (path, value) in [
("typography.display.size", 24.0),
("typography.display.line_height", 29.0),
("radius.button", 6.0),
("radius.window", 10.0),
("typography.label.size", 13.0),
("typography.caption.size", 11.0),
("space.gap.item", 8.0),
] {
sizes.comfortable.insert(path.into(), craft::theme::SizeValue::Number(value));
}
Arc::new(sizes)
});
let lang = i18n::Lang::from_pref(&self.language);
@@ -749,6 +768,11 @@ impl eframe::App for PdfCraftApp {
let ctx = ui.ctx().clone();
self.guarded_frame(&ctx, |app| app.ui_unguarded(ui));
self.end_ui();
if !self.frame_panicked
&& let Some(start) = self.startup_time.take()
{
log::info!(target: "pdfcraft::startup", "+{} ms: first UI pass finished", start.elapsed().as_millis());
}
}
}
+7
View File
@@ -90,6 +90,13 @@ impl PdfCraftApp {
("default-mode", _) => {
self.default_mode = Mode::parse(value).ok_or("default-mode must be all, read, edit, convert or sign")?;
}
("form-reminder", _) => {
self.show_form_field_reminder = match value {
"on" | "true" => true,
"off" | "false" => false,
_ => return Err("form-reminder must be on or off".to_string()),
};
}
("date-format", _) => {
self.session.set_date_format(value)?;
self.sync_open_date_format();
+19
View File
@@ -1,6 +1,8 @@
use super::{DocId, DocView, LeftPanel, Mode, PasswordPrompt, PdfCraftApp, RecentFile, RightPanel, UnlockPrompt, canvas, i18n};
#[cfg(not(target_arch = "wasm32"))]
use super::{OpenOutcome, OpenRequest, PendingOpen, open_worker};
#[cfg(not(target_arch = "wasm32"))]
use crate::OpeningNotice;
use craft::docpath::names::safe_file_name;
#[cfg(not(target_arch = "wasm32"))]
use craft::host::queue::Priority;
@@ -169,9 +171,25 @@ impl PdfCraftApp {
reopen: false,
target_group: request.target_group,
});
self.refresh_opening_notice();
token
}
#[cfg(not(target_arch = "wasm32"))]
/// Updates the notice for the first pending native document, including its current language.
fn refresh_opening_notice(&mut self) {
let Some(pending) = self.pending_opens.first() else {
self.opening_notice = None;
return;
};
let lang = i18n::current();
if self.opening_notice.as_ref().is_some_and(|notice| notice.token == pending.token && notice.lang == lang) {
return;
}
self.opening_notice =
Some(OpeningNotice { token: pending.token, lang, label: i18n::fmt(tl!("Opening {name}…"), &[("name", &pending.name)]) });
}
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn poll_pending_opens(&mut self, ctx: &egui::Context) {
// The queue delivers in the order jobs finish; each result goes to its entry, so the list
@@ -226,6 +244,7 @@ impl PdfCraftApp {
// earlier waiting replies, without consuming a blocked receiver's result.
waiting.append(&mut self.pending_opens);
self.pending_opens = waiting;
self.refresh_opening_notice();
self.settle_launch_layout();
}
+11 -1
View File
@@ -9,10 +9,20 @@ impl PdfCraftApp {
/// command states and host. eframe calls the hook once per frame, before the first pass, so
/// a second pass of the same frame runs on what this call set and fires nothing twice.
pub(super) fn prepare_raw_input(&mut self, ctx: &egui::Context, _raw: &mut egui::RawInput) {
self.set_title_bar_choice(ctx, self.title_bar_choice);
// Preferences and the control channel only change `title_bar_choice`; the window follows on the
// next frame. Asking the policy again when nothing changed would re-read the platform each frame.
if self.applied_title_bar != Some(self.title_bar_choice) {
self.applied_title_bar = Some(self.title_bar_choice);
self.set_title_bar_choice(ctx, self.title_bar_choice);
}
self.control_before_input(ctx);
let typing_refused = std::mem::take(&mut self.typing_refused);
embed::before_input(ctx, |output| {
for fired in &output.fired {
// A key pressed with typing the field refused (⌘S right after Enter) goes with the refusal.
if typing_refused && fired.source == craft::ui::runtime::commands::FireSource::Key {
continue;
}
self.run_fired(ctx, fired);
}
for declined in &output.declined {

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