Merge remote-tracking branch 'origin/main' into HEAD

This commit is contained in:
FredApps
2026-12-02 08:53:31 +01:00
52 changed files with 2144 additions and 146 deletions
+8 -3
View File
@@ -45,7 +45,12 @@ jobs:
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
+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 {
+7 -1
View File
@@ -401,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" => {
+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 }),
}
}
+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();
+10 -4
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"],
@@ -1672,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!({
@@ -1685,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"],
)),
@@ -1718,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"])),
+197
View File
@@ -7853,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.
@@ -10048,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,
@@ -14563,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]
@@ -15635,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}");
}
+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,
}
+2
View File
@@ -80,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
+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(_)))
}
}
+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))
}
+2 -1
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,
+1
View File
@@ -410,6 +410,7 @@ impl Session {
fonts_stale: false,
xfa_warnings: Vec::new(),
edit_notices: Vec::new(),
alpha: Default::default(),
}
}
}
+1 -1
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,
+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,
+235 -3
View File
@@ -11789,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();
@@ -11801,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
@@ -14520,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.
+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| {
+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;
+3
View File
@@ -295,6 +295,7 @@ 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(),
@@ -383,6 +384,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,
+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();
}
+5
View File
@@ -16,8 +16,13 @@ impl PdfCraftApp {
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 {
+40
View File
@@ -67,6 +67,46 @@ impl PdfCraftApp {
self.pending_remote_link = None;
}
/// Follow a link's embedded Go-To action (ISO 32000-2 §12.6.4.4): open the PDF attached to
/// document `doc` at `source` in a new tab, as the Attachments panel's Open does (from the
/// document's own bytes: no file is read or written), then go to `destination` in it. A
/// file that isn't attached there, or isn't a PDF, opens nothing.
pub(crate) fn open_embedded_link(
&mut self,
ctx: &egui::Context,
doc: DocId,
source: pdfcraft_render::AttachmentSource,
destination: pdfcraft_render::RemoteDestination,
) {
let Some(d) = self.session.get(doc) else { return };
let Some(att) = d.info.attachments.iter().find(|a| a.source == source).cloned() else {
self.notify_fmt("This PDF uses the unsupported {s} action.", &[("s", "GoToE")]);
return;
};
let bytes = match pdfcraft_render::attachment_data(&d.bytes, d.password.as_deref(), &att) {
Ok(bytes) => bytes,
Err(e) => {
self.notify_fmt("Couldn't read {name}: {e}", &[("name", &att.name), ("e", &e.to_string())]);
return;
}
};
// "Embedded go-to actions work only for files of Type PDF" (§12.6.4.4). Checked here, as
// the Attachments panel's Open would turn a picture or text file into a new PDF.
if !pdfcraft_render::looks_like_pdf(&bytes) {
self.notify_fmt("{name} isn't a PDF, so the link can't open it.", &[("name", &att.name)]);
return;
}
if let Err(e) = self.open_bytes(ctx, &craft::docpath::names::safe_file_name(&att.name, "attachment"), None, bytes) {
self.notify_fmt("Couldn't open {name}: {e}", &[("name", &att.name), ("e", &e.to_string())]);
return;
}
// An encrypted attachment waits for its password; the destination waits with it.
match self.password_prompt.as_mut() {
Some(prompt) => prompt.after_open = Some(destination),
None => self.apply_remote_destination(destination),
}
}
pub(super) fn apply_remote_destination(&mut self, destination: pdfcraft_render::RemoteDestination) {
if let Some(index) = self.views.len().checked_sub(1) {
self.apply_destination_at(index, destination);
+30 -15
View File
@@ -814,13 +814,10 @@ fn close_requested_tab(ctx: &egui::Context, app: &mut PdfCraftApp, index: usize)
true
}
/// Follows the link, or the bookmark's action, that was clicked. A link to another file comes
/// back, to be opened once the document is no longer borrowed.
pub(crate) fn follow_link(
app: &mut PdfCraftApp,
index: usize,
target: Option<LinkTarget>,
) -> Option<(pdfcraft_engine::DocId, String, pdfcraft_render::RemoteDestination)> {
/// Follows the link, or the bookmark's action, that was clicked. A link to another file, or to a
/// PDF attached to this one, comes back, to be opened once the document is no longer borrowed
/// ([`open_link`]).
pub(crate) fn follow_link(app: &mut PdfCraftApp, index: usize, target: Option<LinkTarget>) -> Option<LinkOpen> {
let view_id = app.views[index].id;
match target? {
LinkTarget::Page(p, dest) => {
@@ -831,7 +828,8 @@ pub(crate) fn follow_link(
}
LinkTarget::Uri(u) => app.request_document_url(&u, crate::LinkOrigin::Link),
LinkTarget::SetLayers { changes, preserve_rb } => set_layers(app, index, &changes, preserve_rb),
LinkTarget::RemoteGoTo { file, destination, .. } => return Some((view_id, file, destination)),
LinkTarget::RemoteGoTo { file, destination, .. } => return Some(LinkOpen::Remote(view_id, file, destination)),
LinkTarget::EmbeddedGoTo { source, destination, .. } => return Some(LinkOpen::Embedded(view_id, source, destination)),
// Run by `PdfCraftApp::run_link_script`, which needs the link's page and index.
LinkTarget::JavaScript(_) => {}
LinkTarget::Other(s) => app.notify_fmt("This PDF uses the unsupported {s} action.", &[("s", &s)]),
@@ -991,8 +989,9 @@ fn page_parts_of(ui: &mut egui::Ui, body: &PageBody<'_>, session: &mut PageSessi
}
if cx.editing_content {
if cx.tool == QuickTool::EditText && cx.can_modify {
let pointer = ui.input(|i| i.pointer.latest_pos());
for placed in body.pages {
parts.extend(crate::edit_text_ui::picture_parts(session, cx.doc, placed.page, placed, geo));
parts.extend(crate::edit_text_ui::picture_parts(session, cx.doc, placed.page, placed, geo, pointer));
}
}
// A picture being cropped holds every press on its page: its paragraphs and added text take none there.
@@ -2049,7 +2048,7 @@ pub fn document_area_at(app: &mut PdfCraftApp, index: usize, rect: Rect, ui: &mu
if let Some((page, area)) = body_out.snapshot {
app.finish_marquee(ui.ctx(), index, (page, area));
}
let remote_open = follow_link(app, index, clicked_link);
let link_open = follow_link(app, index, clicked_link);
if let Some((page, link)) = javascript_link {
app.run_link_script(ui.ctx(), doc_id, page, link);
}
@@ -2064,7 +2063,7 @@ pub fn document_area_at(app: &mut PdfCraftApp, index: usize, rect: Rect, ui: &mu
form_notice,
copy_selected: body_out.copy_selected,
recolour,
remote_open,
link_open,
open_table: prepare.table,
open_boxes: body_out.open_boxes,
open_signature: body_out.open_signature,
@@ -2086,7 +2085,7 @@ struct FrameRequests {
copy_selected: bool,
/// A colour picked for every selected comment (Colour in the page's menu).
recolour: Option<pdfcraft_engine::Rgb>,
remote_open: Option<(pdfcraft_engine::DocId, String, pdfcraft_render::RemoteDestination)>,
link_open: Option<LinkOpen>,
/// A table drawn with the prepare tool: its page and user-space rectangle.
open_table: Option<(usize, [f64; 4])>,
/// The Crop tool's double-click: open Set Page Boxes on the current page.
@@ -2109,7 +2108,7 @@ fn apply_frame_requests(app: &mut PdfCraftApp, ctx: &egui::Context, index: usize
form_notice,
copy_selected,
recolour,
remote_open,
link_open,
open_table,
open_boxes,
open_signature,
@@ -2330,11 +2329,27 @@ fn apply_frame_requests(app: &mut PdfCraftApp, ctx: &egui::Context, index: usize
if let Some(notice) = app.views[index].session.comments.notice.take() {
app.notify_tr(notice);
}
if let Some((source, file, destination)) = remote_open {
app.open_remote_link(source, file, destination);
if let Some(open) = link_open {
open_link(app, ctx, open);
}
}
/// Open the document a followed link or bookmark leads to ([`follow_link`]).
pub(crate) fn open_link(app: &mut PdfCraftApp, ctx: &egui::Context, open: LinkOpen) {
match open {
LinkOpen::Remote(source, file, destination) => app.open_remote_link(source, file, destination),
LinkOpen::Embedded(doc, source, destination) => app.open_embedded_link(ctx, doc, source, destination),
}
}
/// A clicked link or bookmark that opens another document once the frame no longer borrows this one.
pub(crate) enum LinkOpen {
/// A GoToR or Launch link: the document it is in, the file, and where in it to go.
Remote(pdfcraft_engine::DocId, String, pdfcraft_render::RemoteDestination),
/// A GoToE link: the document it is in, its attachment, and where in it to go.
Embedded(pdfcraft_engine::DocId, pdfcraft_render::AttachmentSource, pdfcraft_render::RemoteDestination),
}
pub(crate) mod page_box_drag;
#[cfg(test)]
mod sign_tab_tests;
+75 -52
View File
@@ -166,7 +166,12 @@ fn form_edit_pages(
impl PdfCraftApp {
/// Apply an edit to the active document. Returns `true` on success; failures are shown.
pub fn apply_edit(&mut self, ctx: &egui::Context, edit: Edit) -> bool {
let Some((i, id)) = self.active_ids() else { return false };
self.try_apply_edit(ctx, edit).is_ok()
}
/// [`Self::apply_edit`], returning why it failed (already shown to the user).
fn try_apply_edit(&mut self, ctx: &egui::Context, edit: Edit) -> Result<(), pdfcraft_engine::EditError> {
let Some((i, id)) = self.active_ids() else { return Err(pdfcraft_engine::EditError::NoDocument) };
// Taken whatever happens to this edit, so it never carries over to another.
let across_pages = std::mem::take(&mut self.views[i].session.marks_across_pages).filter(|_| annotated_pages(&edit).is_some());
let label = edit.label();
@@ -214,7 +219,7 @@ impl PdfCraftApp {
};
match self.session.apply(id, edit.clone()) {
Ok(()) => {
let Some(doc) = self.session.get(id) else { return true };
let Some(doc) = self.session.get(id) else { return Ok(()) };
let info = &doc.info;
let view = &mut self.views[i];
view.session.applied_editor = None;
@@ -297,7 +302,7 @@ impl PdfCraftApp {
}
let out = self.session.take_js_output(id);
self.handle_js(ctx, id, out);
true
Ok(())
}
Err(e) => {
if let Some(view) = self.views.get_mut(i) {
@@ -320,7 +325,7 @@ impl PdfCraftApp {
let text = crate::i18n::fmt(tl!("{label} failed: {e}"), &[("label", &crate::i18n::edit_label(&label)), ("e", &message)]);
self.last_edit_refusal = Some(text.clone());
self.notify(text);
false
Err(e)
}
}
}
@@ -501,7 +506,7 @@ impl PdfCraftApp {
}
/// Apply any edit a view queued this frame (organize toolbar, keys).
/// Returns false when a field refused the typing queued for it (its editor is open again).
/// Returns false when a field refused the typing queued for it (see [`Self::apply_queued_edit`]).
pub(crate) fn process_pending_edits(&mut self, ctx: &egui::Context) -> bool {
let Some(i) = self.active else { return true };
// Split view: the other pane's tab can hold an edit too (its field committed when the
@@ -527,7 +532,13 @@ impl PdfCraftApp {
if let Some((at, files)) = self.views.get_mut(i).and_then(|v| v.dropped_files.take()) {
self.insert_dropped(ctx, files, at);
}
match self.views.get_mut(i).and_then(|v| v.pending_action.take()) {
if !applied {
// Nor may a shortcut pressed with it (⌘S right after Enter) run behind the refusal
// (`prepare_raw_input` drops it), nor a toolbar action queued in the same frame
// (Organize ▸ Save pages).
self.typing_refused = true;
}
match self.views.get_mut(i).and_then(|v| v.pending_action.take()).filter(|_| applied) {
Some(crate::canvas::ViewAction::InsertFromFile) => self.insert_from_file_dialog(),
Some(crate::canvas::ViewAction::InsertFromFileAt(at)) => self.insert_from_file_at(Some(at)),
Some(crate::canvas::ViewAction::ReplacePages) => self.replace_pages_dialog(),
@@ -824,9 +835,10 @@ impl PdfCraftApp {
/// change too. Run before anything reads the document: Save, Print, Export, Optimize, Sign,
/// Extract, Split, Copy pages and button scripts.
///
/// Returns false when the field rejects the value (a validation script or format; the user
/// is told why). The editor stays open with the text, and the caller must stop: nothing is
/// saved, printed or exported without it.
/// Returns false when the field refuses the value (the user is told why), and the caller
/// must stop: nothing is saved, printed or exported behind the refusal. A value the field's
/// format refuses stays in the open editor, to be fixed; one its validate action rejects is
/// dropped and the field keeps its value (see [`Self::apply_queued_edit`]).
pub(crate) fn commit_form_typing(&mut self, ctx: &egui::Context) -> bool {
let Some((i, id)) = self.active_ids() else { return true };
if !self.apply_queued_edit(ctx, i) {
@@ -844,10 +856,18 @@ impl PdfCraftApp {
if let Some(view) = self.views.get_mut(i) {
view.session.forms.focus = None;
}
if self.apply_edit(ctx, edit) {
// The editor closed: the field's exit runs now, unless its change just ran it.
self.run_focus_scripts(ctx, i);
return true;
match self.try_apply_edit(ctx, edit) {
Ok(()) => {
// The editor closed: the field's exit runs now, unless its change just ran it.
self.run_focus_scripts(ctx, i);
return true;
}
// The editor stays closed: the field shows the value it kept, and the focus left it.
Err(e) if e.is_rejected_value() => {
self.run_focus_scripts(ctx, i);
return false;
}
Err(_) => {}
}
// The refused draft goes back as it is: its editor shows again while `forms.focus` holds it.
if let Some(view) = self.views.get_mut(i) {
@@ -939,8 +959,11 @@ impl PdfCraftApp {
}
/// Apply the edit queued on tab `i` (the active one). Returns false only when it was a
/// field's typing and the field refused it (#166): the editor reopens with the text, and the
/// user has been told why, so the typing isn't lost and the caller can stop.
/// field's typing and the field refused it, after telling the user why, so the caller can
/// stop. Typing the field's format refuses reopens in its editor (#166), so it isn't lost.
/// A value the field's validate action rejects (ISO 32000-2 Table 199 `/V`) is dropped
/// instead, as other readers do: the field keeps the value it had, and the editor Tab or a
/// click opened on the next field stays open, so the user can go on filling the form.
fn apply_queued_edit(&mut self, ctx: &egui::Context, i: usize) -> bool {
let Some(edit) = self.views.get_mut(i).and_then(|v| v.session.pending_edit.take()) else { return true };
let signature_page = self.views.get_mut(i).and_then(|v| v.session.fill_signature.take());
@@ -950,50 +973,50 @@ impl PdfCraftApp {
(Edit::SetFieldValue { name, .. }, Some(draft)) => *name == draft.name,
_ => false,
};
if self.apply_edit(ctx, edit) {
if signature_page.is_some()
&& let Some(id) = doc_id
{
self.placed_signatures.insert(id);
// A new signature shows the Lock now notice again, even if the last was dismissed.
if let Some(view) = self.views.get_mut(i) {
view.lock_offer_dismissed = false;
}
if let Err(e) = self.try_apply_edit(ctx, edit) {
if !typed {
return true;
}
// Tab can wrap to the same field (including another widget of that field).
// Its new editor was opened before this edit ran, so it still holds the old
// value. Refresh from the accepted form before Save can commit that stale draft.
if typed
&& let Some(view) = self.views.get_mut(i)
&& let Some(focus) = view.session.forms.focus.as_mut()
&& committed.as_ref().is_some_and(|draft| draft.name == focus.name)
&& let Some(field) = self.session.get(view.id).and_then(|doc| doc.form.iter().find(|field| field.name == focus.name))
if !e.is_rejected_value()
&& let (Some(draft), Some(view)) = (committed, self.views.get_mut(i))
{
focus.text = crate::forms_ui::draft_text(field);
focus.picked = field.value.clone();
view.session.forms.focus = Some(draft);
}
if let Some(page) = signature_page
&& let Some(view) = self.views.get_mut(i)
{
// Signature imports are a labeled batch; select their appended stamp just
// as AddAnnotation selects a typed or drawn signature.
let newest = self
.session
.get(view.id)
.and_then(|d| d.info.annotations.iter().filter(|a| a.page == page && !a.is_reply()).map(|a| a.index).max());
view.session.comments.select(newest.map(|index| (page, index)));
view.session.comments.reveal = true;
self.quick_tool = crate::QuickTool::Select;
return false;
}
if signature_page.is_some()
&& let Some(id) = doc_id
{
self.placed_signatures.insert(id);
// A new signature shows the Lock now notice again, even if the last was dismissed.
if let Some(view) = self.views.get_mut(i) {
view.lock_offer_dismissed = false;
}
return true;
}
if !typed {
return true;
// Tab can wrap to the same field (including another widget of that field).
// Its new editor was opened before this edit ran, so it still holds the old
// value. Refresh from the accepted form before Save can commit that stale draft.
if typed
&& let Some(view) = self.views.get_mut(i)
&& let Some(focus) = view.session.forms.focus.as_mut()
&& committed.as_ref().is_some_and(|draft| draft.name == focus.name)
&& let Some(field) = self.session.get(view.id).and_then(|doc| doc.form.iter().find(|field| field.name == focus.name))
{
focus.text = crate::forms_ui::draft_text(field);
focus.picked = field.value.clone();
}
if let (Some(draft), Some(view)) = (committed, self.views.get_mut(i)) {
view.session.forms.focus = Some(draft);
if let Some(page) = signature_page
&& let Some(view) = self.views.get_mut(i)
{
// Signature imports are a labeled batch; select their appended stamp just
// as AddAnnotation selects a typed or drawn signature.
let newest =
self.session.get(view.id).and_then(|d| d.info.annotations.iter().filter(|a| a.page == page && !a.is_reply()).map(|a| a.index).max());
view.session.comments.select(newest.map(|index| (page, index)));
view.session.comments.reveal = true;
self.quick_tool = crate::QuickTool::Select;
}
false
true
}
/// [`Self::commit_form_typing`] for document `id`, which may not be the active tab (a save
+59
View File
@@ -267,3 +267,62 @@ fn recolouring_print_ink_text_in_its_box_drops_the_ink_without_an_empty_step() {
let finished = finish(&mut app);
assert!(finished.is_none(), "an empty Undo step: {finished:?}");
}
/// One page with a text field `qty` (value 4) whose validate action (ISO 32000-2 Table 199
/// `/V`) rejects anything over 100.
fn validated_form() -> Vec<u8> {
let objs = [
"<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [4 0 R] /DA (/Helv 0 Tf 0 g) /DR << /Font << /Helv 5 0 R >> >> >> >>",
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 300 400] >>",
"<< /Type /Page /Parent 2 0 R /Annots [4 0 R] >>",
"<< /Type /Annot /Subtype /Widget /FT /Tx /T (qty) /V (4) /Rect [20 350 280 372] /P 3 0 R /F 4 /AA << /V << /S /JavaScript /JS (if (event.value > 100) { app.alert('At most 100'); event.rc = false; }) >> >> >>",
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>",
];
let mut out = b"%PDF-1.7\n".to_vec();
let mut offsets = Vec::new();
for (i, o) in objs.iter().enumerate() {
offsets.push(out.len());
out.extend_from_slice(format!("{} 0 obj\n{o}\nendobj\n", i + 1).as_bytes());
}
let xref = out.len();
out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes());
for o in offsets {
out.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());
}
out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes());
out
}
/// #4498: a toolbar Save (Organize ▸ Save pages) queued in the frame whose typed value the
/// validate action rejects does not run behind the refusal, just as a ⌘S pressed with it does not.
#[test]
fn a_save_action_queued_with_a_rejected_value_does_not_run() {
let (mut h, files, jobs) = shown_with_picks();
let ctx = egui::Context::default();
let app = h.state_mut();
app.open_bytes(&ctx, "order.pdf", None, validated_form()).unwrap();
app.active = Some(0);
let view = &mut app.views[0];
view.session.forms.committed = Some(crate::forms_ui::Focus {
name: "qty".into(),
obj: None,
widget: 0,
text: "4500".into(),
picked: Vec::new(),
selection: Default::default(),
list_open: false,
calendar_open: false,
});
view.session.pending_edit =
Some(pdfcraft_engine::Edit::SetFieldValue { name: "qty".into(), value: pdfcraft_engine::FieldValue::Text("4500".into()) });
view.pending_action = Some(crate::canvas::ViewAction::Save);
assert!(!app.process_pending_edits(&ctx), "the validate action rejects 4500");
assert!(app.views[0].pending_action.is_none(), "the queued Save is not left to run later");
for _ in 0..4 {
jobs.run_all();
h.run_steps(1);
}
assert!(files.requests().is_empty(), "the queued Save does not run behind the refusal: {:?}", files.requests());
let doc = h.state().session.get(h.state().views[0].id).unwrap();
assert_eq!(doc.form.iter().find(|f| f.name == "qty").map(|f| f.value.clone()), Some(vec!["4".to_string()]), "qty keeps its value");
}
+12
View File
@@ -216,6 +216,13 @@ struct PendingDestination {
name: String,
}
#[cfg(not(target_arch = "wasm32"))]
struct OpeningNotice {
token: u64,
lang: i18n::Lang,
label: String,
}
pub struct PdfCraftApp {
/// The app's services: jobs, files, settings sections, commands. Every queue is built from it.
pub(crate) host: std::sync::Arc<craft::host::Host>,
@@ -270,6 +277,9 @@ pub struct PdfCraftApp {
/// The active document during the previous frame, so a deferred keyboard Save from that frame
/// never saves a different document that became active before the next frame's `before_input`.
pub(crate) last_frame_active: Option<DocId>,
/// A field refused the typing committed this frame: the shortcuts pressed in the same frame
/// (⌘S right after Enter), which fire at the start of the next, don't run behind the refusal.
pub(crate) typing_refused: bool,
pub mode: Mode,
/// Workspace used for newly opened PDFs; independent of PDF Initial View metadata.
pub default_mode: Mode,
@@ -481,6 +491,8 @@ pub struct PdfCraftApp {
#[cfg(not(target_arch = "wasm32"))]
pending_destinations: Vec<PendingDestination>,
#[cfg(not(target_arch = "wasm32"))]
opening_notice: Option<OpeningNotice>,
#[cfg(not(target_arch = "wasm32"))]
next_open_token: u64,
/// Explicit CLI layout waits for flagged launch opens, never targeting restored tabs.
#[cfg(not(target_arch = "wasm32"))]
+33
View File
@@ -5,6 +5,14 @@
//! removed when the job ends ([`end_progress`]); both only queue a [`ProgressRequest`] that [`show`] applies with the
//! pass's `Context`, so none is lost before the first pass or from a headless caller. Nothing is mirrored every pass.
#[cfg(not(target_arch = "wasm32"))]
use craft::theme::variant::Tone;
#[cfg(not(target_arch = "wasm32"))]
use craft::ui::contract::{Politeness, Props as _, Show as _};
#[cfg(not(target_arch = "wasm32"))]
use craft::ui::display::Spinner;
#[cfg(not(target_arch = "wasm32"))]
use craft::ui::notices::{Notice, NoticeLayout};
use craft::ui::notices::{NoticeEnd, PostedNotice};
use craft::ui::runtime::toast::ToastId;
#[cfg(test)]
@@ -157,6 +165,31 @@ pub fn show(app: &mut PdfCraftApp, ui: &mut egui::Ui) {
// PLAN: assumed script_notice_ended(&mut self, &egui::Context, &NoticeEnd) (pdf-forms-w16)
app.script_notice_ended(&ctx, &end);
}
#[cfg(not(target_arch = "wasm32"))]
show_opening(app, ui);
}
/// Shows the pending native document, above the toast stack.
#[cfg(not(target_arch = "wasm32"))]
fn show_opening(app: &PdfCraftApp, ui: &mut egui::Ui) {
let Some(notice) = &app.opening_notice else { return };
let ctx = ui.ctx().clone();
let screen = ctx.content_rect();
let window = craft::ui::runtime::env::WindowKey::main();
let toast_count = craft::ui::runtime::toast::cards(&ctx, &window).len();
let lift = (28.0 + toast_count as f32 * 120.0).min((screen.height() - 72.0).max(28.0));
let _ = egui::Area::new(egui::Id::unique("opening-notice"))
.order(egui::Order::Tooltip)
.pivot(egui::Align2::CENTER_BOTTOM)
.fixed_pos(screen.center_bottom() - egui::vec2(0.0, lift))
.show(&ctx, |ui| {
Notice::new(Tone::Neutral, notice.label.clone())
.layout(NoticeLayout::Toast)
.announce(Politeness::Polite)
.content(Spinner::new().label(notice.label.clone()), |_| {})
.show(ui);
});
}
/// The notice an end is about.
@@ -453,6 +453,7 @@ mod tests {
use super::*;
/// Builds a minimal annotation for comments-panel tests.
fn mock_annotation(subtype: &str, intent: Option<&str>) -> Annotation {
Annotation {
page: 0,
@@ -479,6 +480,7 @@ mod tests {
}
}
/// Checks that a freehand highlight annotation uses its localized kind label.
#[test]
fn freehand_highlight_kind_label() {
let freehand = mock_annotation("Ink", Some("FreehandHighlight"));
+2 -2
View File
@@ -135,8 +135,8 @@ pub fn panel_body(app: &mut PdfCraftApp, ui: &mut egui::Ui, cx: &mut BodyCx<'_>,
None => app.views[index].go_to_page(p),
},
Some(Nav::Action(target)) => {
if let Some((source, file, destination)) = crate::canvas::follow_link(app, index, Some(target)) {
app.open_remote_link(source, file, destination);
if let Some(open) = crate::canvas::follow_link(app, index, Some(target)) {
crate::canvas::open_link(app, &ctx, open);
}
}
Some(Nav::Flash(p, r)) => {
@@ -223,6 +223,19 @@ fn open_prepare_keeps_control_and_existing_tabs_live_until_atomic_commit() {
let reply = rig.request("ui.open", json!({ "path": file.path() }));
assert_eq!(reply["pending"], true);
assert_eq!(rig.jobs.waiting(), 1);
let opening_label = format!("Opening {}…", file.name());
assert_eq!(rig.h.state().opening_notice.as_ref().map(|notice| notice.label.as_str()), Some(opening_label.as_str()));
rig.h.run_steps(1);
assert!(rig.notice_says(&opening_label));
if crate::i18n::needs_catalogs() {
let language = std::mem::replace(&mut rig.h.state_mut().language, "ja".into());
rig.h.run_steps(1);
let japanese_label = format!("{} を開いています…", file.name());
assert_eq!(rig.h.state().opening_notice.as_ref().map(|notice| notice.label.as_str()), Some(japanese_label.as_str()));
rig.h.state_mut().language = language;
rig.h.run_steps(1);
}
assert_eq!(rig.h.state().opening_notice.as_ref().map(|notice| notice.label.as_str()), Some(opening_label.as_str()));
let state = rig.request("ui.state", json!({}));
assert_eq!(state["documents"].as_array().map(Vec::len), Some(1));
@@ -238,6 +251,8 @@ fn open_prepare_keeps_control_and_existing_tabs_live_until_atomic_commit() {
assert_eq!(app.views.len(), 2, "one prepared document commits exactly once");
assert_eq!(app.session.get(app.views[1].id).expect("new tab").info.pages.len(), 2);
assert_eq!(app.active, Some(1));
assert!(app.opening_notice.is_none(), "the opening notice clears after commit");
assert!(!rig.notice_says(&opening_label), "the opening notice is no longer visible");
}
/// Picking a file for a tool must carry the tool through native preparation; another file
+14 -4
View File
@@ -610,14 +610,18 @@ fn picture_change(
}
/// The parts of the pictures of `page`, in paint order so the topmost wins a press: a picture's
/// visible shape, and for the selected one its whole frame, a hole in it included. None while
/// the picture is cropped, whose crop overlay holds the page.
/// visible shape where it shows, and for the selected one its whole frame, a hole in it included.
/// None while the picture is cropped, whose crop overlay holds the page.
///
/// A picture with transparency is picked only where it shows: with the pointer at `pointer` over
/// one of its see-through parts, it has no part this pass, so the press goes to what lies below.
pub(crate) fn picture_parts(
session: &PageSession,
doc: &pdfcraft_engine::Document,
page: usize,
placed: &PlacedPage,
geo: PageGeometry<'_>,
pointer: Option<Pos2>,
) -> Vec<PagePart> {
let Some(xf) = session.page_xform(page, geo) else { return Vec::new() };
let selection = session.image_selection.as_ref().filter(|s| s.page == page);
@@ -628,7 +632,7 @@ pub(crate) fn picture_parts(
doc.page_images(page)
.iter()
.enumerate()
.map(|(index, image)| {
.filter_map(|(index, image)| {
let quad = picture_quad(&xf, &doc.info, page, image);
let visible = image.visible_rect.map(|r| xf.user_rect(&doc.info, page, r.map(|v| v as f32)).intersect(placed.rect));
let (shape, icon) = if selected == Some(index) {
@@ -636,7 +640,13 @@ pub(crate) fn picture_parts(
} else {
(visible.map_or_else(|| HitShape::Polygon(quad.to_vec()), HitShape::Rect), CursorIcon::PointingHand)
};
PagePart::new(Owner::Picture { index }, page, shape, PageLayer::Picture).cursor(icon)
// Through a picture's transparent parts, the one below is picked (the selected one keeps its frame).
let see_through = selected != Some(index)
&& pointer.is_some_and(|at| {
let (x, y) = screen_to_user(&xf, &doc.info, page, at);
shape.hit(at) && !doc.image_shows_at(image, [x, y])
});
(!see_through).then(|| PagePart::new(Owner::Picture { index }, page, shape, PageLayer::Picture).cursor(icon))
})
.collect()
}
+3 -2
View File
@@ -65,8 +65,9 @@ pub struct Focus {
#[derive(Clone, Debug, Default)]
pub struct FormView {
pub focus: Option<Focus>,
/// The draft whose edit is queued (`DocView::pending_edit`): if the field refuses the value,
/// the editor reopens with it rather than losing the typing.
/// The draft whose edit is queued (`DocView::pending_edit`): if the field's format refuses
/// the value, the editor reopens with it rather than losing the typing. A value the field's
/// validate action rejects is dropped, and the field keeps its value.
pub(crate) committed: Option<Focus>,
/// The editor handed the keys on (Tab, Shift+Tab): the field the session moved to takes the key focus in the
/// next pass, from its page part, as Tab onto the part would give it.
+6
View File
@@ -147,6 +147,12 @@ pub(crate) fn target_label(info: &DocInfo, target: &LinkTarget) -> String {
LinkTarget::Uri(u) => u.clone(),
LinkTarget::SetLayers { .. } => tl!("Set layer visibility").to_string(),
LinkTarget::RemoteGoTo { file, .. } => file.clone(),
// The attachment's name, as the Attachments panel lists it.
LinkTarget::EmbeddedGoTo { source, .. } => info
.attachments
.iter()
.find(|a| a.source == *source)
.map_or_else(|| crate::i18n::fmt(tl!("{s} action"), &[("s", "GoToE")]), |a| a.name.clone()),
LinkTarget::JavaScript(_) => crate::i18n::fmt(tl!("{s} action"), &[("s", "JavaScript")]),
LinkTarget::Other(s) => crate::i18n::fmt(tl!("{s} action"), &[("s", s)]),
}
+77
View File
@@ -11647,6 +11647,83 @@ fn affine_review_cropped_rotation_preview_matches_saved_corners() {
}
}
/// Edit text & images: a click through the transparent margin of a picture selects the picture
/// below it, and a click where it shows selects it. Once selected, a picture keeps its whole frame.
#[test]
fn a_click_through_a_pictures_transparent_margin_selects_the_picture_below() {
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 top picture's soft mask shows its 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 bytes = b"%PDF-1.7\n".to_vec();
let mut offsets = Vec::new();
for (i, o) in objs.iter().enumerate() {
offsets.push(bytes.len());
bytes.extend_from_slice(format!("{} 0 obj\n", i + 1).as_bytes());
bytes.extend_from_slice(o);
bytes.extend_from_slice(b"\nendobj\n");
}
let xref = bytes.len();
bytes.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes());
for o in offsets {
bytes.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());
}
bytes.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes());
let harness = || {
let bytes = bytes.clone();
let mut h = Harness::builder().with_size(egui::vec2(900.0, 800.0)).build_eframe(move |cc| {
crate::support::install_runtime(&cc.egui_ctx);
let mut app = crate::control::new_app();
app.set_option(&egui::Context::default(), "language", "en").unwrap();
app.open_bytes(&egui::Context::default(), "overlap.pdf", None, bytes).unwrap();
app
});
h.run_steps(4);
assert!(h.execute("edit.edit_text"));
h.state_mut().views[0].view.fit = pdfcraft_ui_egui::canvas::Fit::Page;
h.run_steps(4);
h
};
let click = |h: &mut Harness<'static, PdfCraftApp>, x: f32, y: f32| {
let id = h.state().views[0].id;
let info = h.state().session.get(id).unwrap().info.pages[0].clone();
let page = h.state().views[0].page_screen_rect(0).unwrap();
let v = info.user_to_view(x, y);
let p = page.min + egui::vec2(v[0], v[1]) * (page.width() / info.width);
h.hover_at(p);
h.run_steps(1);
h.drag_at(p);
h.run_steps(1);
h.drop_at(p);
h.run_steps(3);
h.state().views[0].session.image_selection.as_ref().map(|s| s.index)
};
// With nothing selected: where the top picture shows, it is picked; through its transparent
// three quarters, the picture below is.
for ((x, y), want) in [((70.0, 70.0), 0), ((150.0, 150.0), 1), ((100.0, 100.0), 0), ((115.0, 145.0), 1)] {
let mut h = harness();
assert_eq!(click(&mut h, x, y), Some(want), "click at {x}, {y}");
}
// The selected picture's frame is its own, its transparent parts included.
let mut h = harness();
assert_eq!(click(&mut h, 150.0, 150.0), Some(1));
assert_eq!(click(&mut h, 100.0, 100.0), Some(1), "the selected picture keeps its frame");
}
/// The Escape that closes a dialog opened from a menu while a paragraph is being typed is the
/// dialog's: the typing stays, in the open paragraph or applied to the page. It was thrown away.
#[test]
+153
View File
@@ -0,0 +1,153 @@
//! A link's embedded Go-To action (GoToE, ISO 32000-2 §12.6.4.4) opens the PDF attached to the
//! document in a new tab, as the Attachments panel's Open does, and goes to its destination.
use egui_kittest::Harness;
use pdfcraft_ui_egui::PdfCraftApp;
/// A PDF of `objs` (object 1 the catalog), with a cross-reference table.
fn write_pdf(objs: &[Vec<u8>]) -> Vec<u8> {
let mut out = b"%PDF-1.7\n".to_vec();
let mut offs = Vec::new();
for (i, o) in objs.iter().enumerate() {
offs.push(out.len());
out.extend_from_slice(format!("{} 0 obj\n", i + 1).as_bytes());
out.extend_from_slice(o);
out.extend_from_slice(b"\nendobj\n");
}
let x = out.len();
out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes());
for o in offs {
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{x}\n%%EOF\n", objs.len() + 1).as_bytes());
out
}
fn stream(dict: &str, data: &[u8]) -> Vec<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
}
/// A three-page PDF to embed.
fn inner() -> Vec<u8> {
write_pdf(&[
b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(),
b"<< /Type /Pages /Kids [3 0 R 4 0 R 5 0 R] /Count 3 /MediaBox [0 0 200 300] >>".to_vec(),
b"<< /Type /Page /Parent 2 0 R >>".to_vec(),
b"<< /Type /Page /Parent 2 0 R >>".to_vec(),
b"<< /Type /Page /Parent 2 0 R >>".to_vec(),
])
}
/// Link rows, by the y (PDF user space, 300 × 400 page) of their middle.
const TO_PAGE_3: f32 = 375.0;
const PARENT: f32 = 325.0;
const MISSING: f32 = 275.0;
const NOT_A_PDF: f32 = 225.0;
const BY_ANNOTATION: f32 = 175.0;
/// One page with `inner.pdf` and `notes.txt` in the EmbeddedFiles name tree, a file attachment
/// annotation (index 0, `/NM (att-1)`) holding `inner.pdf` too, and a GoToE link per case.
fn fixture() -> Vec<u8> {
let links = [
(TO_PAGE_3, "<< /S /GoToE /T << /R /C /N (inner.pdf) >> /D [2 /Fit] /NewWindow true >>"),
(PARENT, "<< /S /GoToE /T << /R /P >> /D [0 /Fit] >>"),
(MISSING, "<< /S /GoToE /T << /R /C /N (missing.pdf) >> /D [0 /Fit] >>"),
(NOT_A_PDF, "<< /S /GoToE /T << /R /C /N (notes.txt) >> /D [0 /Fit] >>"),
(BY_ANNOTATION, "<< /S /GoToE /T << /R /C /P 0 /A (att-1) >> /D [1 /Fit] >>"),
];
let first_link = 9;
let annots: Vec<String> = std::iter::once("8 0 R".to_string()).chain((0..links.len()).map(|k| format!("{} 0 R", first_link + k))).collect();
let mut objs = vec![
b"<< /Type /Catalog /Pages 2 0 R /Names << /EmbeddedFiles << /Names [(inner.pdf) 6 0 R (notes.txt) 7 0 R] >> >> >>".to_vec(),
b"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 300 400] >>".to_vec(),
format!("<< /Type /Page /Parent 2 0 R /Annots [{}] >>", annots.join(" ")).into_bytes(),
stream("/Type /EmbeddedFile /Subtype /application#2Fpdf", &inner()),
stream("/Type /EmbeddedFile /Subtype /text#2Fplain", b"just some notes"),
b"<< /Type /Filespec /F (inner.pdf) /UF (inner.pdf) /EF << /F 4 0 R >> >>".to_vec(),
b"<< /Type /Filespec /F (notes.txt) /UF (notes.txt) /EF << /F 5 0 R >> >>".to_vec(),
b"<< /Type /Annot /Subtype /FileAttachment /Rect [270 10 290 30] /NM (att-1) /FS << /Type /Filespec /F (inner.pdf) /UF (inner.pdf) /EF << /F 4 0 R >> >> >>".to_vec(),
];
objs.extend(
links
.iter()
.map(|(y, a)| format!("<< /Type /Annot /Subtype /Link /Rect [20 {} 280 {}] /Border [0 0 0] /A {a} >>", y - 10.0, y + 10.0).into_bytes()),
);
write_pdf(&objs)
}
fn harness() -> Harness<'static, PdfCraftApp> {
let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(|cc| {
crate::support::install_runtime(&cc.egui_ctx);
let mut app = crate::control::new_app();
app.set_option(&egui::Context::default(), "language", "en").unwrap();
app.open_bytes(&egui::Context::default(), "outer.pdf", None, fixture()).unwrap();
app.set_option(&egui::Context::default(), "left", "closed").unwrap();
app.set_option(&egui::Context::default(), "panel", "none").unwrap();
app.set_option(&egui::Context::default(), "zoom", "100").unwrap();
app
});
h.run_steps(8);
h
}
/// Click the link at height `y` on page 1 of the first tab.
fn click(h: &mut Harness<'static, PdfCraftApp>, y: f32) {
let r = h.state().views[0].page_screen_rect(0).expect("page 1 on screen");
let k = r.width() / 300.0;
let p = r.min + egui::vec2(150.0 * k, (400.0 - y) * k);
h.hover_at(p);
h.run_steps(1);
h.drag_at(p);
h.run_steps(1);
h.drop_at(p);
h.run_steps(4);
}
fn toast(h: &Harness<'static, PdfCraftApp>) -> Option<String> {
crate::support::shown_notice(h)
}
fn tab_name(h: &Harness<'static, PdfCraftApp>, i: usize) -> Option<String> {
let s = h.state();
s.views.get(i).and_then(|v| s.session.get(v.id)).map(|d| d.name.clone())
}
/// `/R /C /N`: the file in the EmbeddedFiles name tree opens in a new tab at `/D`.
#[test]
fn an_embedded_go_to_link_opens_the_attached_pdf_at_its_destination() {
let mut h = harness();
click(&mut h, TO_PAGE_3);
assert_eq!(h.state().views.len(), 2, "{:?}", toast(&h));
assert_eq!(h.state().active, Some(1));
assert_eq!(tab_name(&h, 1).as_deref(), Some("inner.pdf"));
assert_eq!(h.state().session.get(h.state().views[1].id).unwrap().info.pages.len(), 3);
assert_eq!(h.state().views[1].current(), 2, "the destination's page");
assert_eq!(h.state().session.get(h.state().views[1].id).unwrap().path, None, "opened from the document, not from a file");
}
/// `/R /C /P /A`: the file of a file attachment annotation, found by its `/NM`.
#[test]
fn an_embedded_go_to_link_opens_a_file_attachment_annotations_pdf() {
let mut h = harness();
click(&mut h, BY_ANNOTATION);
assert_eq!(h.state().views.len(), 2, "{:?}", toast(&h));
assert_eq!(h.state().views[1].current(), 1);
}
/// The parent, a file that isn't attached, and a file that isn't a PDF open nothing and say so.
#[test]
fn embedded_go_to_links_that_cannot_be_followed_open_nothing() {
for (y, says) in [
(PARENT, "This PDF uses the unsupported GoToE action."),
(MISSING, "This PDF uses the unsupported GoToE action."),
(NOT_A_PDF, "notes.txt isn't a PDF, so the link can't open it."),
] {
let mut h = harness();
click(&mut h, y);
assert_eq!(h.state().views.len(), 1, "nothing opened for the link at {y}");
assert_eq!(toast(&h).as_deref(), Some(says));
}
}
+93 -14
View File
@@ -1188,8 +1188,10 @@ fn pressing_another_text_field_validates_the_refused_value_once() {
h.drop_at(p);
h.run_steps(3);
assert_eq!(card_count(&h), 1, "the release did not validate it again");
let focus = h.state().views[0].session.forms.focus.clone().expect("the refused field stays open");
assert_eq!((focus.name.as_str(), focus.text.as_str()), ("qty", "4500"));
// The rejected value is dropped: qty keeps its value and the pressed field keeps the focus.
assert_eq!(value(&h, "qty"), ["4"]);
let focus = h.state().views[0].session.forms.focus.clone().expect("the pressed field is open");
assert_eq!((focus.name.as_str(), focus.text.as_str()), ("note", ""));
}
/// `validated_form` plus a plain text field, `note`, under `qty`.
@@ -1204,6 +1206,79 @@ fn validated_form_with_note() -> Vec<u8> {
])
}
/// Three blank text fields in tab order: `G_range` validates with the range function (1 to
/// 100), `H_short` with a script that alerts and sets `event.rc` false past 3 characters, and
/// `note` takes anything.
fn range_and_script_validated_form() -> Vec<u8> {
pdf_from_objects(&[
"<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [4 0 R 5 0 R 6 0 R] /DA (/Helv 0 Tf 0 g) /DR << /Font << /Helv 7 0 R >> >> >> >>",
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 300 400] >>",
"<< /Type /Page /Parent 2 0 R /Annots [4 0 R 5 0 R 6 0 R] >>",
"<< /Type /Annot /Subtype /Widget /FT /Tx /T (G_range) /Rect [20 350 280 372] /P 3 0 R /F 4 /AA << /V << /S /JavaScript /JS (AFRange_Validate\\(true, 1, true, 100\\);) >> >> >>",
"<< /Type /Annot /Subtype /Widget /FT /Tx /T (H_short) /Rect [20 300 280 322] /P 3 0 R /F 4 /AA << /V << /S /JavaScript /JS (if \\(event.value.length > 3\\) { app.alert\\(\"At most 3 characters\"\\); event.rc = false; }) >> >> >>",
"<< /Type /Annot /Subtype /Widget /FT /Tx /T (note) /Rect [20 250 280 272] /P 3 0 R /F 4 >>",
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>",
])
}
/// A value a field's validate action rejects (ISO 32000-2 Table 199 `/V`) is dropped, as other
/// readers do: the message shows, the field keeps its value, nothing is added to undo, and Tab
/// goes on to the next field instead of holding the user in the rejected one.
#[test]
fn a_value_the_validate_action_rejects_reverts_and_tab_moves_on() {
let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(|cc| {
crate::support::install_runtime(&cc.egui_ctx);
let mut app = crate::control::new_app();
app.set_option(&egui::Context::default(), "language", "en").unwrap();
app.open_bytes(&egui::Context::default(), "rows.pdf", None, range_and_script_validated_form()).unwrap();
app.set_option(&egui::Context::default(), "left", "closed").unwrap();
app.set_option(&egui::Context::default(), "zoom", "150").unwrap();
app
});
h.run_steps(6);
let toast = |h: &Harness<'static, PdfCraftApp>| crate::support::shown_notice(h).unwrap_or_default();
let unchanged = |h: &Harness<'static, PdfCraftApp>| {
let doc = h.state().session.get(h.state().views[0].id).unwrap();
!doc.dirty && doc.can_undo().is_none()
};
let type_and_tab = |h: &mut Harness<'static, PdfCraftApp>, text: &str| {
h.event(egui::Event::Text(text.into()));
h.run_steps(2);
h.key_press(egui::Key::Tab);
h.run_steps(3);
};
click_field(&mut h, "G_range", 0);
type_and_tab(&mut h, "150");
assert!(toast(&h).contains("Invalid value"), "the range's message shows: {:?}", toast(&h));
assert!(value(&h, "G_range").is_empty(), "G keeps its blank value");
assert_eq!(focused(&h).map(|(n, _)| n).as_deref(), Some("H_short"), "Tab moved on");
assert_eq!(h.state().views[0].session.forms.focus.as_ref().map(|f| f.text.as_str()), Some(""));
assert!(unchanged(&h), "a rejected value is no change and no undo step");
type_and_tab(&mut h, "abcd");
assert!(toast(&h).contains("At most 3 characters"), "the script's alert shows: {:?}", toast(&h));
assert!(value(&h, "H_short").is_empty());
assert_eq!(focused(&h).map(|(n, _)| n).as_deref(), Some("note"));
assert!(unchanged(&h));
// The next field fills in as usual, and so does a value in range.
type_and_tab(&mut h, "x");
assert_eq!(value(&h, "note"), ["x"]);
click_field(&mut h, "G_range", 0);
type_and_tab(&mut h, "50");
assert_eq!(value(&h, "G_range"), ["50"]);
// Undo steps through the two accepted values only.
h.undo();
h.run_steps(2);
assert!(value(&h, "G_range").is_empty());
assert_eq!(value(&h, "note"), ["x"]);
h.undo();
h.run_steps(2);
assert!(value(&h, "note").is_empty());
assert!(h.state().session.get(h.state().views[0].id).unwrap().can_undo().is_none(), "and nothing else is left to undo");
}
fn pdf_from_objects(objs: &[&str]) -> Vec<u8> {
let mut out = b"%PDF-1.7\n".to_vec();
let mut offsets = Vec::new();
@@ -1296,7 +1371,7 @@ fn buttons_over_text_show_the_pointing_hand_not_the_i_beam() {
}
#[test]
fn a_rejected_value_keeps_the_typing_and_stops_the_save() {
fn a_rejected_value_is_dropped_and_stops_the_save() {
let dir = scratch("rejected");
let out = dir.join("saved.pdf");
let (mut h, files) = scripted_harness("order.pdf", validated_form(), "150", &out);
@@ -1305,15 +1380,18 @@ fn a_rejected_value_keeps_the_typing_and_stops_the_save() {
h.run_steps(2);
h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::S);
h.run_steps(4);
assert!(files.file(&out).is_none(), "nothing is saved without the typed value");
assert!(files.file(&out).is_none(), "the save stops at the refusal, so the user sees it first");
let shown = crate::support::shown_notice(&h);
assert!(shown.as_deref().is_some_and(|t| t.contains("At most 100")), "the script's message is shown: {shown:?}");
assert_eq!(value(&h, "qty"), ["4"], "the field keeps its valid value");
let focus = h.state().views[0].session.forms.focus.clone().expect("the editor stays open");
assert_eq!(focus.text, "4500", "with the text (typed after the 4), so the user can fix it");
// And closing asks rather than dropping it.
assert!(h.state().views[0].session.forms.focus.is_none(), "the rejected 4500 is dropped, not held in an editor");
let doc = h.state().session.get(h.state().views[0].id).unwrap();
assert!(!doc.dirty && doc.can_undo().is_none(), "a rejected value is no change and no undo step");
// Closing has nothing to ask about.
let ctx_h = h.ctx.clone();
h.state_mut().request_close_tab(&ctx_h, 0);
h.run_steps(2);
assert!(asks_to_save(&h));
assert!(!asks_to_save(&h));
let _ = std::fs::remove_dir_all(&dir);
}
@@ -1356,11 +1434,11 @@ fn refused_value_stops_save(commit_key: egui::Key, case: &str) {
h.run_steps(3);
assert_eq!(value(&h, "qty"), ["4"]);
assert!(files.file(&out).is_none(), "nothing is saved right after the field refused its value");
// The refused text is back in the field, so a later ⌘S stops again instead of saving 4.
assert_eq!(h.state().views[0].session.forms.focus.as_ref().map(|f| f.text.as_str()), Some("4500"));
h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::S);
h.run_steps(4);
assert!(files.file(&out).is_none());
// The rejected text is dropped: Enter closes the editor, and Tab wraps to the only field,
// which shows the value it kept.
let expected = if commit_key == egui::Key::Tab { Some("4") } else { None };
assert_eq!(h.state().views[0].session.forms.focus.as_ref().map(|f| f.text.as_str()), expected);
assert!(!h.state().session.get(h.state().views[0].id).unwrap().dirty);
let _ = std::fs::remove_dir_all(&dir);
}
@@ -1445,7 +1523,8 @@ mod revert_tests {
h.run_steps(2);
h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::S);
h.run_steps(4);
assert_eq!(h.state().views[0].session.forms.focus.as_ref().unwrap().text, "99");
assert!(h.state().views[0].session.forms.focus.is_none(), "the rejected 99 is dropped");
assert_eq!(value(&h, "name"), ["Saved original"]);
assert_eq!(files.file(&path), Some(saved.clone()), "rejection leaves the saved file untouched");
assert!(h.execute("file.revert"));
h.run_steps(2);
+1
View File
@@ -42,6 +42,7 @@ mod document_links;
mod edit;
mod editing;
mod editor_taps;
mod embedded_links;
mod export;
mod field_triggers;
mod fill_sign;
+1
View File
@@ -35,6 +35,7 @@ fn type_into(h: &mut Harness<'static, PdfCraftApp>, label: &str, text: &str) {
h.run_steps(2);
}
/// Sets the password pair through the Protect dialog's Advanced Options.
fn open_password_pair(h: &mut Harness<'static, PdfCraftApp>, password: &str) {
type_into(h, "Type Password", password);
type_into(h, "Re-type Password", password);
+8 -1
View File
@@ -43,7 +43,14 @@ with the selected image, also when the picture sits inside a clip it shares with
(a report drawing each picture as `q re W n cm Do Q` within a table's clip): the picture's own
clip scales with it, and shared clips stay fixed without moving neighbouring text or artwork.
`image_hit` applies the same path and hole checks headlessly. `page_images` retains `rect` as
A picture with transparency (a soft mask, a stencil or colour-key `/Mask`, or a stencil
image) is picked only where it shows: a click through the transparent margin of a PNG
signature or a cut-out photo goes to what is below it. Opacity is read on a grid of at most
256 cells a side, a cell counting as showing if any of its pixels does (alpha ≥ 16 of 255).
Form artwork, pictures without transparency, and pictures that can't be decoded (JPEG 2000,
JBIG2, CCITT) keep their whole box.
`image_hit` applies the same path, hole and transparency checks headlessly. `page_images` retains `rect` as
the full placement rectangle used by `image_edit` and adds `visible_rect` for selection (null
when fully clipped). `object_list` reports visible artwork bounds while keeping the original
source indexes. A selection frame does not create, remove or enlarge the PDF's clipping path.
+11 -11
View File
@@ -1213,8 +1213,8 @@ milestone = "M3"
status = "shipped"
commands = []
tools = ["link_open"]
evidence = ["crates/ui-egui/tests/it/view.rs::clicking_a_link_goes_to_its_destination", "crates/ui-egui/tests/it/view.rs::link_destinations_scroll_to_their_position", "crates/ui-egui/tests/it/view.rs::a_link_without_a_position_keeps_the_place_on_the_next_page", "crates/render/src/inspect/tests.rs::bookmarks_and_links_keep_their_destination_view", "crates/render/src/inspect/tests.rs::links_read_bounded_local_remote_go_to_actions", "crates/automation/tests/it/automation.rs::local_gotor_link_open_applies_destinations_and_honors_root", "crates/ui-egui/tests/it/document_links.rs::a_local_gotor_link_opens_in_a_tab_and_applies_its_destination", "crates/ui-egui/tests/it/document_links.rs::a_gotor_link_to_a_named_destination_opens_at_its_page", "crates/render/src/inspect/navigation.rs::a_named_destination_is_looked_up_by_its_name", "crates/ui-egui/tests/it/document_links.rs::an_absolute_gotor_waits_for_consent_and_keeps_its_destination_across_tabs", "crates/ui-egui/tests/it/document_links.rs::cancelling_an_absolute_gotor_by_button_or_escape_changes_nothing", "crates/automation/tests/it/automation.rs::absolute_gotor_consent_does_not_bypass_validation_or_passwords", "crates/render/src/inspect/tests.rs::launch_actions_that_name_a_pdf_open_it_like_a_remote_link", "crates/automation/tests/it/automation.rs::a_launch_link_to_a_pdf_opens_it_like_a_remote_link", "crates/render/src/inspect/tests.rs::relative_uri_actions_resolve_against_the_catalog_base", "crates/render/src/inspect/tests.rs::links_are_active_in_their_quad_points", "crates/automation/tests/it/automation.rs::links_resolve_relative_addresses_and_report_their_quad_points"]
notes = "A relative URI action resolves against the catalog's /URI /Base (ISO 32000-2 Table 211) when that base is an http(s) address, then goes through the usual check and confirmation; without a base, a relative address is still refused (resolving against the document's own location is not done). A link with valid /QuadPoints is active only inside them, otherwise over /Rect (Table 176); link_list reports resolved_url and active_areas. IsMap is not supported. GoTo and URI links plus local-PDF GoToR links: source-relative or local absolute /F paths, /UF preferred in file-spec dictionaries, explicit numeric page/view destinations, and internal tabs. Absolute local GoToR targets require desktop Allow/Cancel confirmation or an explicit allow_absolute opt-in in link_open; relative links open normally. link_open honors --root. A named remote destination opens at its page and view, in the app and in link_open, looked up in the target's /Names /Dests tree or catalog /Dests (§12.3.2.4); a name the target doesn't define opens it at the default view with a warning; /NewWindow is a tab hint. A Launch action whose /F names a .pdf file (and has no /Win launch parameters) opens that PDF the same way, backslash separators read as / (#4168); URL/network file systems, GoToE, other Launch actions and other actions are not executed. Same-document destinations retain their supported /XYZ, /Fit, /FitH, /FitV and /FitR views; /FitB* is read as whole-page fit. A null /XYZ left or top keeps the reader's place, as ISO 32000-2 §12.3.2.2 says and Acrobat Reader was observed to do (synthetic fixture): the user-space point at the window's top-left stays there on the target page at the same zoom, along each axis the page overflows; CAD exports (WSCAD) write every cross-reference this way. Null /FitH top and /FitV left still go to the page edge."
evidence = ["crates/ui-egui/tests/it/view.rs::clicking_a_link_goes_to_its_destination", "crates/ui-egui/tests/it/view.rs::link_destinations_scroll_to_their_position", "crates/ui-egui/tests/it/view.rs::a_link_without_a_position_keeps_the_place_on_the_next_page", "crates/render/src/inspect/tests.rs::bookmarks_and_links_keep_their_destination_view", "crates/render/src/inspect/tests.rs::links_read_bounded_local_remote_go_to_actions", "crates/automation/tests/it/automation.rs::local_gotor_link_open_applies_destinations_and_honors_root", "crates/ui-egui/tests/it/document_links.rs::a_local_gotor_link_opens_in_a_tab_and_applies_its_destination", "crates/ui-egui/tests/it/document_links.rs::a_gotor_link_to_a_named_destination_opens_at_its_page", "crates/render/src/inspect/navigation.rs::a_named_destination_is_looked_up_by_its_name", "crates/ui-egui/tests/it/document_links.rs::an_absolute_gotor_waits_for_consent_and_keeps_its_destination_across_tabs", "crates/ui-egui/tests/it/document_links.rs::cancelling_an_absolute_gotor_by_button_or_escape_changes_nothing", "crates/automation/tests/it/automation.rs::absolute_gotor_consent_does_not_bypass_validation_or_passwords", "crates/render/src/inspect/tests.rs::launch_actions_that_name_a_pdf_open_it_like_a_remote_link", "crates/automation/tests/it/automation.rs::a_launch_link_to_a_pdf_opens_it_like_a_remote_link", "crates/render/src/inspect/tests.rs::links_read_embedded_go_to_actions_to_attached_pdfs", "crates/ui-egui/tests/it/embedded_links.rs::an_embedded_go_to_link_opens_the_attached_pdf_at_its_destination", "crates/ui-egui/tests/it/embedded_links.rs::an_embedded_go_to_link_opens_a_file_attachment_annotations_pdf", "crates/ui-egui/tests/it/embedded_links.rs::embedded_go_to_links_that_cannot_be_followed_open_nothing", "crates/automation/tests/it/automation.rs::an_embedded_go_to_link_opens_the_attached_pdf", "crates/render/src/inspect/tests.rs::relative_uri_actions_resolve_against_the_catalog_base", "crates/render/src/inspect/tests.rs::links_are_active_in_their_quad_points", "crates/automation/tests/it/automation.rs::links_resolve_relative_addresses_and_report_their_quad_points"]
notes = "A relative URI action resolves against the catalog's /URI /Base (ISO 32000-2 Table 211) when that base is an http(s) address, then goes through the usual check and confirmation; without a base, a relative address is still refused (resolving against the document's own location is not done). A link with valid /QuadPoints is active only inside them, otherwise over /Rect (Table 176); link_list reports resolved_url and active_areas. IsMap is not supported. GoTo and URI links plus local-PDF GoToR links: source-relative or local absolute /F paths, /UF preferred in file-spec dictionaries, explicit numeric page/view destinations, and internal tabs. Absolute local GoToR targets require desktop Allow/Cancel confirmation or an explicit allow_absolute opt-in in link_open; relative links open normally. link_open honors --root. A named remote destination opens at its page and view, in the app and in link_open, looked up in the target's /Names /Dests tree or catalog /Dests (§12.3.2.4); a name the target doesn't define opens it at the default view with a warning; /NewWindow is a tab hint. A Launch action whose /F names a .pdf file (and has no /Win launch parameters) opens that PDF the same way, backslash separators read as / (#4168); a GoToE link (ISO 32000-2 §12.6.4.4) to a PDF embedded in the document (a child target, /R /C, by its EmbeddedFiles /N key or its file attachment annotation /P and /A, index or /NM) opens it in a new tab from the document's own bytes, as the Attachments panel does, at its page or named destination; link_open does the same headlessly. GoToE to the parent (/R /P), through nested target dictionaries, under another root document (/F), to a file that isn't attached or to a non-PDF attachment is not followed, with a notice. URL/network file systems, other Launch actions and other actions are not executed. Same-document destinations retain their supported /XYZ, /Fit, /FitH, /FitV and /FitR views; /FitB* is read as whole-page fit. A null /XYZ left or top keeps the reader's place, as ISO 32000-2 §12.3.2.2 says and Acrobat Reader was observed to do (synthetic fixture): the user-space point at the window's top-left stays there on the target page at the same zoom, along each axis the page overflows; CAD exports (WSCAD) write every cross-reference this way. Null /FitH top and /FitV left still go to the page edge."
[[feature]]
id = "view.annotation-hover"
@@ -2184,8 +2184,8 @@ milestone = "M7"
status = "shipped"
commands = ["edit.edit_text"]
tools = ["image_edit", "image_hit"]
evidence = ["crates/edit/src/tests.rs::private_image_crop_with_intervening_state_resizes_across_streams", "crates/automation/tests/it/automation.rs::private_crops_with_nested_state_resize_save_reopen_through_tools", "crates/edit/src/tests.rs::form_artwork_edits_only_the_selected_placement", "crates/ui-egui/tests/it/editing.rs::editing_existing_form_artwork_on_the_page", "crates/automation/tests/it/automation.rs::editing_form_artwork_through_tools", "crates/edit/src/tests.rs::page_images_move_turn_replace_and_delete", "crates/ui-egui/tests/it/editing.rs::editing_existing_images_on_the_page", "crates/automation/tests/it/automation.rs::editing_page_images_through_tools", "crates/edit/src/tests.rs::curved_image_clips_have_analytic_bounds_and_holes_do_not_capture_points", "crates/edit/src/tests.rs::cropped_image_resizing_moves_private_clips_and_keeps_shared_ones", "crates/ui-egui/tests/it/editing.rs::cropped_image_corner_resize_keeps_opposite_corner_and_scales_crop", "crates/edit/src/tests.rs::image_selection_bounds_respect_clips_and_restore_graphics_state", "crates/ui-egui/tests/it/editing.rs::cropped_images_do_not_intercept_text_and_stay_inside_each_page", "crates/automation/tests/it/automation.rs::clipped_image_bounds_and_text_edit_save_reopen_through_tools", "crates/edit/src/tests.rs::resizing_an_image_under_a_shared_clip_moves_its_own_clip", "crates/automation/tests/it/automation.rs::transforming_page_images_through_tools"]
notes = "existing raster images and grouped Form artwork: select, drag to move, 8-point handles to resize (corners keep proportions, edges scale along axis, Shift inverts aspect lock); Delete removes one placement. Headless: image_edit action move (a new box) or transform (any finite, non-flat 6-number matrix in top-left-origin points, applied after the placement: the edit a resize of a turned image makes). Forms include their nested content as a group; individual internal elements and inline images are not supported. See docs/editing-images.md; added images too Since #1116: raster images and grouped Forms move/resize/turn as placements; selected grips own the gesture and opposite anchor, with no PDF writes during movement. Curved path frames use analytic Bezier extrema and hit testing evaluates actual nonzero/even-odd fill rules, excluding holes; intersections can retain a loose frame. Selection and resize use the visible (clipped) frame; exclusive image clips move with their pixels across nested states, intervening operators and content streams, also inside a clip the picture shares with other content (its own clip scales, the shared one stays); shared clips stay fixed. Inline images and Form internals remain unsupported; see docs/editing-images.md"
evidence = ["crates/edit/src/tests.rs::private_image_crop_with_intervening_state_resizes_across_streams", "crates/automation/tests/it/automation.rs::private_crops_with_nested_state_resize_save_reopen_through_tools", "crates/edit/src/tests.rs::form_artwork_edits_only_the_selected_placement", "crates/ui-egui/tests/it/editing.rs::editing_existing_form_artwork_on_the_page", "crates/automation/tests/it/automation.rs::editing_form_artwork_through_tools", "crates/edit/src/tests.rs::page_images_move_turn_replace_and_delete", "crates/ui-egui/tests/it/editing.rs::editing_existing_images_on_the_page", "crates/automation/tests/it/automation.rs::editing_page_images_through_tools", "crates/edit/src/tests.rs::curved_image_clips_have_analytic_bounds_and_holes_do_not_capture_points", "crates/edit/src/tests.rs::cropped_image_resizing_moves_private_clips_and_keeps_shared_ones", "crates/ui-egui/tests/it/editing.rs::cropped_image_corner_resize_keeps_opposite_corner_and_scales_crop", "crates/edit/src/tests.rs::image_selection_bounds_respect_clips_and_restore_graphics_state", "crates/ui-egui/tests/it/editing.rs::cropped_images_do_not_intercept_text_and_stay_inside_each_page", "crates/automation/tests/it/automation.rs::clipped_image_bounds_and_text_edit_save_reopen_through_tools", "crates/edit/src/tests.rs::resizing_an_image_under_a_shared_clip_moves_its_own_clip", "crates/automation/tests/it/automation.rs::transforming_page_images_through_tools", "crates/engine/src/tests.rs::pictures_are_picked_where_they_show", "crates/engine/src/tests.rs::large_pictures_are_picked_where_they_show", "crates/automation/tests/it/automation.rs::image_hit_sees_through_transparent_parts_of_pictures", "crates/ui-egui/tests/it/editing.rs::a_click_through_a_pictures_transparent_margin_selects_the_picture_below"]
notes = "existing raster images and grouped Form artwork: select, drag to move, 8-point handles to resize (corners keep proportions, edges scale along axis, Shift inverts aspect lock); Delete removes one placement. Headless: image_edit action move (a new box) or transform (any finite, non-flat 6-number matrix in top-left-origin points, applied after the placement: the edit a resize of a turned image makes). Forms include their nested content as a group; individual internal elements and inline images are not supported. See docs/editing-images.md; added images too Since #1116: raster images and grouped Forms move/resize/turn as placements; selected grips own the gesture and opposite anchor, with no PDF writes during movement. Curved path frames use analytic Bezier extrema and hit testing evaluates actual nonzero/even-odd fill rules, excluding holes; intersections can retain a loose frame. Selection and resize use the visible (clipped) frame; exclusive image clips move with their pixels across nested states, intervening operators and content streams, also inside a clip the picture shares with other content (its own clip scales, the shared one stays); shared clips stay fixed. Pictures with transparency (soft mask, /Mask, stencil) are picked only where they show, on an opacity grid of at most 256 cells a side; JPEG 2000/JBIG2/CCITT pictures and Form artwork keep their whole box. Inline images and Form internals remain unsupported; see docs/editing-images.md"
[[feature]]
id = "edit.image-extract"
@@ -4776,8 +4776,8 @@ milestone = "M6"
status = "shipped"
commands = ["form.field.properties"]
tools = ["form_set_props", "form_fill"]
evidence = ["crates/forms/src/af/tests.rs::validation_and_calculation", "crates/forms/src/tests.rs::formats_validation_and_calculations_run_like_acrobat", "crates/forms/src/tests.rs::unsupported_first_validation_call_preserves_custom_script_dispatch", "crates/automation/tests/it/automation.rs::form_formats_and_calculations_through_tools"]
notes = "AFRange_Validate with Acrobat's messages; unsupported arguments in the first genuine call preserve the complete custom script for the supplied interpreter, rather than selecting a later literal call (save/reopen and validation dispatch covered)."
evidence = ["crates/forms/src/af/tests.rs::validation_and_calculation", "crates/forms/src/tests.rs::formats_validation_and_calculations_run_like_acrobat", "crates/forms/src/tests.rs::unsupported_first_validation_call_preserves_custom_script_dispatch", "crates/automation/tests/it/automation.rs::form_formats_and_calculations_through_tools", "crates/forms/src/tests.rs::a_validate_refusal_is_a_rejection_and_a_keystroke_refusal_is_not", "crates/ui-egui/tests/it/forms.rs::a_value_the_validate_action_rejects_reverts_and_tab_moves_on"]
notes = "AFRange_Validate with Acrobat's messages; unsupported arguments in the first genuine call preserve the complete custom script for the supplied interpreter, rather than selecting a later literal call (save/reopen and validation dispatch covered). A value it (or a custom validate script setting event.rc false) rejects is not stored: the app shows the message, the field keeps its previous value and Tab or a click moves on, with no undo step; form_fill reports it as an error. Messages still show as a notice, not a modal dialog."
[[feature]]
id = "form.af-simple-calculate"
@@ -4812,8 +4812,8 @@ milestone = "M6"
status = "shipped"
commands = ["form.prepare"]
tools = ["form_set_script"]
evidence = ["crates/engine/src/tests.rs::form_javascript_validates_calculates_and_formats", "crates/automation/tests/it/automation.rs::javascript_through_tools", "crates/engine/src/tests.rs::a_calculate_script_setting_its_own_field_object_keeps_the_value", "crates/engine/src/tests.rs::a_calculate_script_assigning_event_value_wins_and_a_combo_keeps_its_selection", "crates/forms/src/tests.rs::a_calculated_combo_stores_the_export_value_of_the_option_it_names", "crates/forms/src/tests.rs::an_export_value_wins_over_an_earlier_options_display_text", "crates/ui-egui/tests/it/prepare.rs::the_calculate_tab_shows_a_custom_calculation_script", "crates/ui-egui/tests/it/prepare.rs::an_edited_custom_script_is_written_and_no_calculation_removes_it", "crates/ui-egui/tests/it/prepare.rs::an_edit_past_256_kib_is_refused_and_the_next_edit_is_taken", "crates/ui-egui/tests/it/prepare.rs::a_script_past_256_kib_shows_its_start_and_is_kept", "crates/forms/src/tests.rs::a_custom_calculation_script_is_written_as_given_and_a_blank_one_removes_it"]
notes = "Custom keystroke (commit), validate, calculate and format scripts run in Acrobat's event order; AF calls still run natively. Field Properties ▸ Calculate ▸ Custom calculation script shows a field's calculate script and edits it (of one past 256 KiB the start is shown, read-only, and the script is kept); the Format and Validate tabs don't offer their custom scripts yet, so those are set with form_set_script. A calculate script may set its own field through the field object (getField(\"Total\").value = …) instead of event.value; that value is kept, text included, unless the script also assigns event.value (even the value it already had). A combo box a calculation moves to another option, named by export value (first) or display text, stores the export value in /V and selects it in /I."
evidence = ["crates/engine/src/tests.rs::form_javascript_validates_calculates_and_formats", "crates/automation/tests/it/automation.rs::javascript_through_tools", "crates/engine/src/tests.rs::a_calculate_script_setting_its_own_field_object_keeps_the_value", "crates/engine/src/tests.rs::a_calculate_script_assigning_event_value_wins_and_a_combo_keeps_its_selection", "crates/forms/src/tests.rs::a_calculated_combo_stores_the_export_value_of_the_option_it_names", "crates/forms/src/tests.rs::an_export_value_wins_over_an_earlier_options_display_text", "crates/ui-egui/tests/it/prepare.rs::the_calculate_tab_shows_a_custom_calculation_script", "crates/ui-egui/tests/it/prepare.rs::an_edited_custom_script_is_written_and_no_calculation_removes_it", "crates/ui-egui/tests/it/prepare.rs::an_edit_past_256_kib_is_refused_and_the_next_edit_is_taken", "crates/ui-egui/tests/it/prepare.rs::a_script_past_256_kib_shows_its_start_and_is_kept", "crates/forms/src/tests.rs::a_custom_calculation_script_is_written_as_given_and_a_blank_one_removes_it", "crates/ui-egui/tests/it/forms.rs::a_value_the_validate_action_rejects_reverts_and_tab_moves_on"]
notes = "Custom keystroke (commit), validate, calculate and format scripts run in Acrobat's event order; AF calls still run natively. Field Properties ▸ Calculate ▸ Custom calculation script shows a field's calculate script and edits it (of one past 256 KiB the start is shown, read-only, and the script is kept); the Format and Validate tabs don't offer their custom scripts yet, so those are set with form_set_script. A calculate script may set its own field through the field object (getField(\"Total\").value = …) instead of event.value; that value is kept, text included, unless the script also assigns event.value (even the value it already had). A combo box a calculation moves to another option, named by export value (first) or display text, stores the export value in /V and selects it in /I. A validate script that sets event.rc false rejects the value: it is not stored, its alert is the message shown, and the field keeps its previous value."
[[feature]]
id = "form.calculation-order"
@@ -7040,9 +7040,9 @@ tier = "P0"
milestone = "M10"
status = "shipped"
commands = ["create.images"]
tools = ["doc_create"]
evidence = ["crates/create/src/tests.rs::black_and_white_images_are_stored_at_one_bit", "crates/create/src/tests.rs::jpeg_2000_images_are_embedded_as_is", "crates/create/src/tests.rs::images_export_as_jpeg_unchanged_and_others_as_png", "crates/create/src/tests.rs::embedded_icc_profiles_tag_the_image_colour_space"]
notes = "PNG, JPEG, TIFF (multi-page), GIF (first frame), BMP, and JPEG 2000 (JP2 or codestream, embedded as JPXDecode with its capture resolution). JPEG and PNG ICC profiles are kept as /ICCBased; TIFF profiles are not read yet. A picture of only pure black and white (a 1-bit PNG or TIFF, eight-bit grey, a two-colour palette, RGB without a profile) is stored at one bit per pixel, as CCITT Group 4 or Flate, whichever is smaller"
tools = ["doc_create", "doc_create_multiple"]
evidence = ["crates/create/src/tests.rs::black_and_white_images_are_stored_at_one_bit", "crates/create/src/tests.rs::jpeg_2000_images_are_embedded_as_is", "crates/create/src/tests.rs::images_export_as_jpeg_unchanged_and_others_as_png", "crates/create/src/tests.rs::embedded_icc_profiles_tag_the_image_colour_space", "crates/create/src/tests.rs::a_set_of_differently_shaped_images_lands_on_one_paper_size", "crates/automation/tests/it/automation.rs::image_pages_go_on_a_chosen_paper_size_through_every_create_tool"]
notes = "PNG, JPEG, TIFF (multi-page), GIF (first frame), BMP, and JPEG 2000 (JP2 or codestream, embedded as JPXDecode with its capture resolution). JPEG and PNG ICC profiles are kept as /ICCBased; TIFF profiles are not read yet. A picture of only pure black and white (a 1-bit PNG or TIFF, eight-bit grey, a two-colour palette, RGB without a profile) is stored at one bit per pixel, as CCITT Group 4 or Flate, whichever is smaller. Pages follow the image at its resolution, or sit on a chosen sheet (page_size: a paper name or points, scaled to fit, centred, turned to the image unless page_turn is false) in doc_create and doc_create_multiple; doc_combine does not take it yet, and there is no dialog for it"
[[feature]]
id = "create.from-multipage-tiff"