mirror of
https://github.com/storytold/pdfcraft.git
synced 2026-12-04 19:42:12 -05:00
Merge upstream/main into feat/alpha-hit-testing
This commit is contained in:
Generated
+1
@@ -4706,6 +4706,7 @@ dependencies = [
|
||||
"skrifa 0.44.0",
|
||||
"thiserror 2.0.21",
|
||||
"unicode-bidi",
|
||||
"url",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
@@ -527,6 +527,8 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md
|
||||
- **2026-10-15 (M3, #1248):** A fresh install follows the desktop's appearance: the theme preference defaults to System (dark on a dark desktop, Light where the desktop says nothing); saved settings and `--theme` still win. Dark page rendering is Reading colours, and the page reading themes are #1732.
|
||||
- **2026-10-15 (M3, #1767):** Restore last view settings when reopening documents, as Acrobat's preference does: a file opened again shows the page, zoom and page display it was last shown with (remembered for the last 100 files when a tab closes or settings are saved), over the file's own initial view; on by default, Preferences ▸ Documents and view turns it off.
|
||||
- **2026-10-14 (M2, #623):** A page whose content was cut at the renderer's limits no longer looks complete: a notice names it (and how many), `ui.state` lists the affected pages under `active.cut_pages`, and `text_extract` marks its text `truncated`, since the cut part's text can't be found or copied. The renderer already reported the cut; nothing showed it.
|
||||
- **2026-10-14 (M5, comment pop-ups; reworked 2026-11-01):** A double-click on a comment opens its pop-up window on the page: a title bar with the comment's kind, author and date; its text and its replies' typed in place, the replies as panels each inside the one it answers, a Reply button under each; the window keeps its `/Rect` size on screen as the page zooms, scrolls its thread, drags by its title bar, resizes by its corner and closes with ×, each an undo step saved in the file's `/Popup` so other viewers agree. A faint wedge in the comment's colour joins the comment to its open window on roll-over or selection. `comment_popup` does the same headlessly and `comment_list` reports the pop-up.
|
||||
- **2026-10-15 (M6, #1741):** Custom stamps can be dynamic: Create Custom Stamp adds an optional line under the picture, a template with {name}, {date} and {time} filled in when the stamp is placed (the built-in dynamic stamps' format), kept in the stamp library; `stamp_custom` takes the same `line`.
|
||||
- **2026-10-13 (M3, native-opening candidate):** Chosen tools survive preparation, conversion and password retries; startup intake waits for pending preparation. Regression tests cover completion, cancellation and document identity. Estimates unchanged.
|
||||
- **2026-10-13 (community, M3, #531 touchpad momentum):** On Wayland a two-finger swipe keeps gliding after the fingers lift and slows to a stop, measured from the gesture's last 0.1 s and decaying with a 0.35 s time constant through the #759 1:1 path. Any wheel input, click, key, zoom or edge ends it (fingers resting on the touchpad don't yet: the vendored winit binds no Wayland hold gestures); single-page paging, macOS (which sends its own momentum), the web, and Animation effects Off never glide. Unit tests for the physics and two headless view tests. Estimates unchanged.
|
||||
- **2026-10-13 (M3, native-open admission):** Later prepared replies stay queued while a modal or native picker owns the foreground. Picker completion, cancellation and abandonment wake retained opens. Regressions cover recipient ownership, exactly-once admission, source/history preservation and one-shot repaint requests. Estimates unchanged.
|
||||
|
||||
@@ -440,6 +440,12 @@ pub(crate) fn render(args: &[String]) -> Result<(), CliError> {
|
||||
let _ =
|
||||
writeln!(std::io::stderr().lock(), "warning: page {page}: a colour that could not be computed was painted in a fallback colour");
|
||||
}
|
||||
pdfcraft_render::RenderWarning::MalformedIndexedImage => {
|
||||
let _ = writeln!(
|
||||
std::io::stderr().lock(),
|
||||
"warning: page {page}: an image with a malformed Indexed colour table may be drawn wrongly or not at all"
|
||||
);
|
||||
}
|
||||
pdfcraft_render::RenderWarning::Type3WidthsMissing => {
|
||||
let _ = writeln!(
|
||||
std::io::stderr().lock(),
|
||||
|
||||
+177
-101
@@ -1,9 +1,12 @@
|
||||
//! Create a valid, reviewable structure tree for PDFs whose painted content is text only.
|
||||
//! Create a valid, reviewable structure tree for untagged PDFs.
|
||||
//!
|
||||
//! The writer refuses mixed content and existing tags. Each text object becomes a paragraph,
|
||||
//! which can then be retagged with the existing tag-property tool after human review.
|
||||
//! Each text object becomes a paragraph, which can then be retagged with the existing
|
||||
//! tag-property tool after human review. Painted paths, shadings and images outside text objects
|
||||
//! are wrapped in `/Artifact BMC … EMC` so the resulting page passes the tagged-content check.
|
||||
|
||||
use pdfcraft_content::{Op, parse, serialize_ops};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use pdfcraft_content::{Op, Pieces, serialize_ops};
|
||||
use pdfcraft_cos::{DecodeBudget, Dict, Document, ObjRef, Object, Stream};
|
||||
|
||||
const MAX_PAGES: usize = 1_000;
|
||||
@@ -41,25 +44,27 @@ struct Plan {
|
||||
page: ObjRef,
|
||||
ops: Vec<Op>,
|
||||
spans: Vec<(usize, usize)>,
|
||||
artifacts: HashMap<usize, usize>,
|
||||
}
|
||||
|
||||
fn unsupported(page: usize, reason: impl Into<String>) -> AutoTagError {
|
||||
AutoTagError::Unsupported { page: page + 1, reason: reason.into() }
|
||||
}
|
||||
|
||||
fn content_bytes(doc: &Document, page: &pdfcraft_model::Page, index: usize) -> Result<Vec<u8>, AutoTagError> {
|
||||
let Some(contents) = page.dict.get(b"Contents") else { return Ok(Vec::new()) };
|
||||
fn content_pieces(doc: &Document, page: &pdfcraft_model::Page, index: usize) -> Result<Pieces, AutoTagError> {
|
||||
let Some(contents) = page.dict.get(b"Contents") else { return Ok(Pieces::join::<&[u8]>(&[])) };
|
||||
let resolved = doc.resolve(contents);
|
||||
let pieces: Vec<Object> = match &*resolved {
|
||||
let items: Vec<Object> = match &*resolved {
|
||||
Object::Array(items) => items.clone(),
|
||||
Object::Stream(_) => vec![contents.clone()],
|
||||
_ => return Err(unsupported(index, "contents are not a stream or array of streams")),
|
||||
};
|
||||
let mut all = Vec::new();
|
||||
for item in pieces {
|
||||
let mut pieces = Vec::with_capacity(items.len());
|
||||
let mut total = 0usize;
|
||||
for item in items {
|
||||
let value = doc.resolve(&item);
|
||||
let Object::Stream(stream) = &*value else { return Err(unsupported(index, "contents include a non-stream object")) };
|
||||
let remaining = MAX_PAGE_BYTES.saturating_sub(all.len().saturating_add(1));
|
||||
let remaining = MAX_PAGE_BYTES.saturating_sub(total.saturating_add(1));
|
||||
if remaining == 0 {
|
||||
return Err(unsupported(index, "decoding the content takes more than 16 MiB"));
|
||||
}
|
||||
@@ -79,10 +84,18 @@ fn content_bytes(doc: &Document, page: &pdfcraft_model::Page, index: usize) -> R
|
||||
unsupported(index, format!("content cannot be decoded strictly: {why}"))
|
||||
}
|
||||
})?;
|
||||
all.extend_from_slice(&decoded);
|
||||
all.push(b' ');
|
||||
total = total.saturating_add(decoded.len()).saturating_add(1);
|
||||
pieces.push(decoded);
|
||||
}
|
||||
Ok(all)
|
||||
Ok(Pieces::join(&pieces))
|
||||
}
|
||||
|
||||
fn page_xobjects(doc: &Document, page: &Dict) -> Dict {
|
||||
page.get(b"Resources")
|
||||
.map(|r| doc.resolve(r))
|
||||
.and_then(|r| r.as_dict().and_then(|r| r.get(b"XObject").map(|x| doc.resolve(x))))
|
||||
.and_then(|x| x.as_dict().cloned())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn harmless_outside(op: &[u8]) -> bool {
|
||||
@@ -110,9 +123,35 @@ fn harmless_outside(op: &[u8]) -> bool {
|
||||
| b"sc"
|
||||
| b"SCN"
|
||||
| b"scn"
|
||||
| b"m"
|
||||
| b"l"
|
||||
| b"c"
|
||||
| b"v"
|
||||
| b"y"
|
||||
| b"h"
|
||||
| b"re"
|
||||
| b"W"
|
||||
| b"W*"
|
||||
| b"n"
|
||||
)
|
||||
}
|
||||
|
||||
fn painted_outside(doc: &Document, xobjects: &Dict, op: &Op) -> bool {
|
||||
match op.op.as_slice() {
|
||||
b"f" | b"F" | b"f*" | b"B" | b"B*" | b"b" | b"b*" | b"S" | b"s" | b"sh" | b"BI" => true,
|
||||
b"Do" => op
|
||||
.name(0)
|
||||
.and_then(|n| xobjects.get(n))
|
||||
.map(|o| doc.resolve(o))
|
||||
.and_then(|o| match &*o {
|
||||
Object::Stream(s) => s.dict.name(b"Subtype").map(<[u8]>::to_vec),
|
||||
_ => None,
|
||||
})
|
||||
.is_some_and(|st| st == b"Image"),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn harmless_inside(op: &[u8]) -> bool {
|
||||
matches!(
|
||||
op,
|
||||
@@ -142,17 +181,38 @@ fn harmless_inside(op: &[u8]) -> bool {
|
||||
)
|
||||
}
|
||||
|
||||
/// The `(BT, ET)` operator index pairs of each text object that shows text, or why the page cannot be tagged.
|
||||
fn text_spans(ops: &[Op], index: usize) -> Result<Vec<(usize, usize)>, AutoTagError> {
|
||||
let mut start = None;
|
||||
let mut has_text = false;
|
||||
let mut spans = Vec::new();
|
||||
for (at, op) in ops.iter().enumerate() {
|
||||
/// `totals` is the decoded bytes and operators of the pages planned so far, bounded by
|
||||
/// `MAX_TOTAL_BYTES` and `MAX_TOTAL_OPERATORS`.
|
||||
fn plan_page(doc: &Document, page: &pdfcraft_model::Page, index: usize, totals: &mut (usize, usize)) -> Result<Plan, AutoTagError> {
|
||||
if page.dict.contains(b"StructParents") {
|
||||
return Err(unsupported(index, "page already has a structure parent key"));
|
||||
}
|
||||
if page.dict.get(b"Annots").is_some_and(|a| match &*doc.resolve(a) {
|
||||
Object::Array(items) => !items.is_empty(),
|
||||
_ => true,
|
||||
}) {
|
||||
return Err(unsupported(index, "annotations need separate structure tags"));
|
||||
}
|
||||
let pieces = content_pieces(doc, page, index)?;
|
||||
totals.0 = totals.0.saturating_add(pieces.data().len());
|
||||
let parsed = pieces.parse();
|
||||
if parsed.skipped > 0 || parsed.ambiguous_images > 0 || parsed.ops.len() > MAX_OPERATORS {
|
||||
return Err(unsupported(index, "content has malformed or too many operators"));
|
||||
}
|
||||
totals.1 = totals.1.saturating_add(parsed.ops.len());
|
||||
if totals.0 > MAX_TOTAL_BYTES || totals.1 > MAX_TOTAL_OPERATORS {
|
||||
return Err(unsupported(index, "the document has too much content to auto-tag in one edit"));
|
||||
}
|
||||
let xobjects = page_xobjects(doc, &page.dict);
|
||||
let (mut start, mut has_text, mut spans, mut artifacts) = (None, false, Vec::new(), HashMap::new());
|
||||
// Marked-content boundaries must enclose the whole path, not just its paint operator.
|
||||
let mut path = None;
|
||||
for (at, op) in parsed.ops.iter().enumerate() {
|
||||
if path.is_some() && matches!(op.op.as_slice(), b"BT" | b"Do" | b"BI" | b"sh") {
|
||||
return Err(unsupported(index, "painted content interrupts an unfinished path"));
|
||||
}
|
||||
match op.op.as_slice() {
|
||||
b"BT" if start.is_none() => {
|
||||
start = Some(at);
|
||||
has_text = false;
|
||||
}
|
||||
b"BT" if start.is_none() => (start, has_text) = (Some(at), false),
|
||||
b"ET" => {
|
||||
let Some(first) = start.take() else { return Err(unsupported(index, "unmatched ET operator")) };
|
||||
if has_text {
|
||||
@@ -164,14 +224,31 @@ fn text_spans(ops: &[Op], index: usize) -> Result<Vec<(usize, usize)>, AutoTagEr
|
||||
}
|
||||
b"Tj" | b"TJ" | b"'" | b"\"" if start.is_some() => has_text = true,
|
||||
name if start.is_some() && harmless_inside(name) => {}
|
||||
name if start.is_none() && harmless_outside(name) => {}
|
||||
name if start.is_none() && harmless_outside(name) => match name {
|
||||
b"m" | b"re" => {
|
||||
path.get_or_insert(at);
|
||||
}
|
||||
b"n" => path = None,
|
||||
_ => {}
|
||||
},
|
||||
_ if start.is_none() && painted_outside(doc, &xobjects, op) => {
|
||||
let first = if matches!(op.op.as_slice(), b"f" | b"F" | b"f*" | b"B" | b"B*" | b"b" | b"b*" | b"S" | b"s") {
|
||||
path.take().unwrap_or(at)
|
||||
} else {
|
||||
at
|
||||
};
|
||||
artifacts.insert(first, at);
|
||||
}
|
||||
_ => return Err(unsupported(index, format!("unsupported or painted operator {}", String::from_utf8_lossy(&op.op)))),
|
||||
}
|
||||
}
|
||||
if start.is_some() {
|
||||
return Err(unsupported(index, "unterminated BT text object"));
|
||||
}
|
||||
Ok(spans)
|
||||
if path.is_some() {
|
||||
return Err(unsupported(index, "unterminated path object"));
|
||||
}
|
||||
Ok(Plan { page: page.obj, ops: parsed.ops, spans, artifacts })
|
||||
}
|
||||
|
||||
fn plan(doc: &Document) -> Result<Vec<Plan>, AutoTagError> {
|
||||
@@ -190,30 +267,11 @@ fn plan(doc: &Document) -> Result<Vec<Plan>, AutoTagError> {
|
||||
}
|
||||
let mut out = Vec::with_capacity(pages.len());
|
||||
let mut total = 0usize;
|
||||
let (mut total_bytes, mut total_ops) = (0usize, 0usize);
|
||||
let mut totals = (0usize, 0usize);
|
||||
for (index, page) in pages.iter().enumerate() {
|
||||
if page.dict.contains(b"StructParents") {
|
||||
return Err(unsupported(index, "page already has a structure parent key"));
|
||||
}
|
||||
if page.dict.get(b"Annots").is_some_and(|a| match &*doc.resolve(a) {
|
||||
Object::Array(items) => !items.is_empty(),
|
||||
_ => true,
|
||||
}) {
|
||||
return Err(unsupported(index, "annotations need separate structure tags"));
|
||||
}
|
||||
let bytes = content_bytes(doc, page, index)?;
|
||||
total_bytes = total_bytes.saturating_add(bytes.len());
|
||||
let parsed = parse(&bytes);
|
||||
if parsed.skipped > 0 || parsed.ops.len() > MAX_OPERATORS {
|
||||
return Err(unsupported(index, "content has malformed or too many operators"));
|
||||
}
|
||||
total_ops = total_ops.saturating_add(parsed.ops.len());
|
||||
if total_bytes > MAX_TOTAL_BYTES || total_ops > MAX_TOTAL_OPERATORS {
|
||||
return Err(unsupported(index, "the document has too much content to auto-tag in one edit"));
|
||||
}
|
||||
let spans = text_spans(&parsed.ops, index)?;
|
||||
total = total.saturating_add(spans.len());
|
||||
out.push(Plan { page: page.obj, ops: parsed.ops, spans });
|
||||
let planned = plan_page(doc, page, index, &mut totals)?;
|
||||
total = total.saturating_add(planned.spans.len());
|
||||
out.push(planned);
|
||||
}
|
||||
if total == 0 {
|
||||
return Err(AutoTagError::NoText);
|
||||
@@ -221,62 +279,36 @@ fn plan(doc: &Document) -> Result<Vec<Plan>, AutoTagError> {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Tag every text object in an untagged, text-only PDF as a paragraph. The full structure tree,
|
||||
/// parent tree and marked-content IDs are written together. Mixed content is refused before any
|
||||
/// mutation. On success the caller can use tag-property edits to assign reviewed heading roles.
|
||||
pub fn autotag_text(doc: &mut Document) -> Result<AutoTagResult, AutoTagError> {
|
||||
let plans = plan(doc)?;
|
||||
let mut next = doc.clone();
|
||||
let catalog = next.root().ok_or(AutoTagError::NoCatalog)?;
|
||||
let root = next.add(Object::Null);
|
||||
let document = next.add(Object::Null);
|
||||
let mut children = Vec::new();
|
||||
let mut numbers = Vec::new();
|
||||
let mut tagged_pages = 0usize;
|
||||
let mut paragraphs = 0usize;
|
||||
for page in plans {
|
||||
if page.spans.is_empty() {
|
||||
continue;
|
||||
fn mark_ops(ops: Vec<Op>, starts: &HashMap<usize, usize>, ends: &HashSet<usize>, artifacts: &HashMap<usize, usize>) -> Result<Vec<Op>, AutoTagError> {
|
||||
let artifact_ends: HashSet<usize> = artifacts.values().copied().collect();
|
||||
let extra = starts.len().saturating_add(artifacts.len()).saturating_mul(2);
|
||||
let mut marked = Vec::with_capacity(ops.len().saturating_add(extra));
|
||||
for (at, op) in ops.into_iter().enumerate() {
|
||||
let is_artifact = artifacts.contains_key(&at);
|
||||
if let Some(mcid) = starts.get(&at) {
|
||||
let mut properties = Dict::new();
|
||||
properties.set(b"MCID".to_vec(), Object::Int(i64::try_from(*mcid).map_err(|_| AutoTagError::TooManyPages)?));
|
||||
marked.push(Op::new("BDC", vec![Object::name("P"), Object::Dict(properties)]));
|
||||
} else if is_artifact {
|
||||
marked.push(Op::new("BMC", vec![Object::name("Artifact")]));
|
||||
}
|
||||
let key = i64::try_from(tagged_pages).map_err(|_| AutoTagError::TooManyPages)?;
|
||||
let mut parents = Vec::with_capacity(page.spans.len());
|
||||
let mut starts = std::collections::HashMap::new();
|
||||
let mut ends = std::collections::HashSet::new();
|
||||
for (mcid, (first, last)) in page.spans.iter().enumerate() {
|
||||
let mut element = Dict::new();
|
||||
element.set(b"Type".to_vec(), Object::name("StructElem"));
|
||||
element.set(b"S".to_vec(), Object::name("P"));
|
||||
element.set(b"P".to_vec(), Object::Ref(document));
|
||||
element.set(b"Pg".to_vec(), Object::Ref(page.page));
|
||||
element.set(b"K".to_vec(), Object::Int(i64::try_from(mcid).map_err(|_| AutoTagError::TooManyPages)?));
|
||||
let reference = next.add(element);
|
||||
parents.push(Object::Ref(reference));
|
||||
children.push(Object::Ref(reference));
|
||||
starts.insert(*first, mcid);
|
||||
ends.insert(*last);
|
||||
paragraphs = paragraphs.saturating_add(1);
|
||||
marked.push(op);
|
||||
if ends.contains(&at) || artifact_ends.contains(&at) {
|
||||
marked.push(Op::new("EMC", Vec::new()));
|
||||
}
|
||||
let mut marked = Vec::with_capacity(page.ops.len().saturating_add(page.spans.len().saturating_mul(2)));
|
||||
for (at, op) in page.ops.into_iter().enumerate() {
|
||||
if let Some(mcid) = starts.get(&at) {
|
||||
let mut properties = Dict::new();
|
||||
properties.set(b"MCID".to_vec(), Object::Int(i64::try_from(*mcid).map_err(|_| AutoTagError::TooManyPages)?));
|
||||
marked.push(Op::new("BDC", vec![Object::name("P"), Object::Dict(properties)]));
|
||||
}
|
||||
marked.push(op);
|
||||
if ends.contains(&at) {
|
||||
marked.push(Op::new("EMC", Vec::new()));
|
||||
}
|
||||
}
|
||||
let stream = next.add(Stream::flate(Dict::new(), &serialize_ops(&marked)));
|
||||
next.update_dict(page.page, |d| {
|
||||
d.set(b"Contents".to_vec(), Object::Ref(stream));
|
||||
d.set(b"StructParents".to_vec(), Object::Int(key));
|
||||
})?;
|
||||
numbers.push(Object::Int(key));
|
||||
numbers.push(Object::Array(parents));
|
||||
tagged_pages += 1;
|
||||
}
|
||||
Ok(marked)
|
||||
}
|
||||
|
||||
fn write_structure(
|
||||
next: &mut Document,
|
||||
catalog: ObjRef,
|
||||
root: ObjRef,
|
||||
document: ObjRef,
|
||||
children: Vec<Object>,
|
||||
numbers: Vec<Object>,
|
||||
tagged_pages: usize,
|
||||
) -> Result<(), AutoTagError> {
|
||||
let mut tree = Dict::new();
|
||||
tree.set(b"Nums".to_vec(), Object::Array(numbers));
|
||||
let parent_tree = next.add(tree);
|
||||
@@ -299,6 +331,50 @@ pub fn autotag_text(doc: &mut Document) -> Result<AutoTagResult, AutoTagError> {
|
||||
d.set(b"StructTreeRoot".to_vec(), Object::Ref(root));
|
||||
d.set(b"MarkInfo".to_vec(), Object::Dict(mark_info));
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Tag every text object in an untagged PDF as a paragraph and mark painted paths, shadings and
|
||||
/// images outside text objects as artifacts. The full structure tree, parent tree and
|
||||
/// marked-content IDs are written together. Unsupported operators are refused before any
|
||||
/// mutation. On success the caller can use tag-property edits to assign reviewed heading roles.
|
||||
pub fn autotag_text(doc: &mut Document) -> Result<AutoTagResult, AutoTagError> {
|
||||
let plans = plan(doc)?;
|
||||
let mut next = doc.clone();
|
||||
let catalog = next.root().ok_or(AutoTagError::NoCatalog)?;
|
||||
let (root, document) = (next.add(Object::Null), next.add(Object::Null));
|
||||
let (mut children, mut numbers, mut tagged_pages, mut paragraphs) = (Vec::new(), Vec::new(), 0usize, 0usize);
|
||||
for page in plans {
|
||||
if page.spans.is_empty() && page.artifacts.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let (mut starts, mut ends) = (HashMap::new(), HashSet::new());
|
||||
if !page.spans.is_empty() {
|
||||
let key = i64::try_from(tagged_pages).map_err(|_| AutoTagError::TooManyPages)?;
|
||||
let mut parents = Vec::with_capacity(page.spans.len());
|
||||
for (mcid, (first, last)) in page.spans.iter().enumerate() {
|
||||
let mut element = Dict::new();
|
||||
element.set(b"Type".to_vec(), Object::name("StructElem"));
|
||||
element.set(b"S".to_vec(), Object::name("P"));
|
||||
element.set(b"P".to_vec(), Object::Ref(document));
|
||||
element.set(b"Pg".to_vec(), Object::Ref(page.page));
|
||||
element.set(b"K".to_vec(), Object::Int(i64::try_from(mcid).map_err(|_| AutoTagError::TooManyPages)?));
|
||||
let reference = next.add(element);
|
||||
parents.push(Object::Ref(reference));
|
||||
children.push(Object::Ref(reference));
|
||||
starts.insert(*first, mcid);
|
||||
ends.insert(*last);
|
||||
paragraphs = paragraphs.saturating_add(1);
|
||||
}
|
||||
next.update_dict(page.page, |d| d.set(b"StructParents".to_vec(), Object::Int(key)))?;
|
||||
numbers.extend([Object::Int(key), Object::Array(parents)]);
|
||||
tagged_pages += 1;
|
||||
}
|
||||
let marked = mark_ops(page.ops, &starts, &ends, &page.artifacts)?;
|
||||
let stream = next.add(Stream::flate(Dict::new(), &serialize_ops(&marked)));
|
||||
next.update_dict(page.page, |d| d.set(b"Contents".to_vec(), Object::Ref(stream)))?;
|
||||
}
|
||||
write_structure(&mut next, catalog, root, document, children, numbers, tagged_pages)?;
|
||||
*doc = next;
|
||||
Ok(AutoTagResult { pages: tagged_pages, paragraphs })
|
||||
}
|
||||
|
||||
+105
-2
@@ -142,17 +142,120 @@ fn autotag_text_says_why_it_cannot_read_a_page() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn autotag_text_refuses_paint_and_does_not_modify_the_document() {
|
||||
fn autotag_text_marks_vector_graphics_and_images_as_artifacts() {
|
||||
let mut doc = pdf(
|
||||
&[
|
||||
"<< /Type /Catalog /Pages 2 0 R >>".into(),
|
||||
"<< /Type /Pages /Kids [3 0 R 7 0 R] /Count 2 >>".into(),
|
||||
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> /XObject << /Im1 6 0 R >> >> >>".into(),
|
||||
stream("0 0 200 200 m 200 0 l 200 200 l 0 200 l h f 10 10 50 50 re B BT /F1 12 Tf 20 100 Td (Hello) Tj ET q 20 0 0 20 80 80 cm /Im1 Do Q"),
|
||||
FONT.into(),
|
||||
"<< /Type /XObject /Subtype /Image /Width 1 /Height 1 /ColorSpace /DeviceGray /BitsPerComponent 8 /Length 1 >>\nstream\n\u{0}\nendstream".into(),
|
||||
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Contents 8 0 R >>".into(),
|
||||
stream("0 0 100 100 re S"),
|
||||
],
|
||||
"",
|
||||
);
|
||||
let result = autotag_text(&mut doc).unwrap();
|
||||
assert_eq!(result, AutoTagResult { pages: 1, paragraphs: 1 });
|
||||
let report = check(&doc, &Options { rules: [Rule::TaggedPdf, Rule::TaggedContent].into(), pages: None });
|
||||
assert_eq!(status(&report, Rule::TaggedPdf), Status::Passed);
|
||||
assert_eq!(status(&report, Rule::TaggedContent), Status::Passed);
|
||||
let bytes = pdfcraft_cos::write_incremental(&doc, &pdfcraft_cos::SaveOptions::default()).unwrap();
|
||||
let reopened = Document::open(Arc::new(bytes)).unwrap();
|
||||
let reopened_report = check(&reopened, &Options { rules: [Rule::TaggedPdf, Rule::TaggedContent].into(), pages: None });
|
||||
assert_eq!(status(&reopened_report, Rule::TaggedPdf), Status::Passed);
|
||||
assert_eq!(status(&reopened_report, Rule::TaggedContent), Status::Passed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn autotag_artifacts_wrap_complete_paths_and_leave_unpainted_clips_outside() {
|
||||
let content = "0 0 m 10 0 l 10 10 l h f 0 0 20 20 re W B 0 0 50 50 re W* n /Shade sh BT /F1 12 Tf (Text) Tj ET 3 3 5 5 re S";
|
||||
let mut doc = pdf(
|
||||
&[
|
||||
"<< /Type /Catalog /Pages 2 0 R >>".into(),
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".into(),
|
||||
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >>".into(),
|
||||
stream("BT /F1 12 Tf 20 100 Td (Hello) Tj ET 0 0 50 50 re f"),
|
||||
stream(content),
|
||||
FONT.into(),
|
||||
],
|
||||
"",
|
||||
);
|
||||
autotag_text(&mut doc).unwrap();
|
||||
let bytes = pdfcraft_cos::write_incremental(&doc, &pdfcraft_cos::SaveOptions::default()).unwrap();
|
||||
let doc = Document::open(Arc::new(bytes)).unwrap();
|
||||
let page = pdfcraft_model::pages(&doc).remove(0);
|
||||
let content = doc.resolve(page.dict.get(b"Contents").unwrap());
|
||||
let Object::Stream(content) = &*content else { panic!("page stream") };
|
||||
let ops = pdfcraft_content::parse(&content.decoded_strict().unwrap()).ops;
|
||||
let names: Vec<&[u8]> = ops.iter().map(|op| op.op.as_slice()).collect();
|
||||
assert_eq!(
|
||||
names,
|
||||
vec![
|
||||
b"BMC".as_slice(),
|
||||
b"m",
|
||||
b"l",
|
||||
b"l",
|
||||
b"h",
|
||||
b"f",
|
||||
b"EMC",
|
||||
b"BMC",
|
||||
b"re",
|
||||
b"W",
|
||||
b"B",
|
||||
b"EMC",
|
||||
b"re",
|
||||
b"W*",
|
||||
b"n",
|
||||
b"BMC",
|
||||
b"sh",
|
||||
b"EMC",
|
||||
b"BDC",
|
||||
b"BT",
|
||||
b"Tf",
|
||||
b"Tj",
|
||||
b"ET",
|
||||
b"EMC",
|
||||
b"BMC",
|
||||
b"re",
|
||||
b"S",
|
||||
b"EMC",
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn autotag_rejects_text_interleaved_with_an_unfinished_path_atomically() {
|
||||
for tail in ["10 10 l S", "n"] {
|
||||
let mut doc = pdf(
|
||||
&[
|
||||
"<< /Type /Catalog /Pages 2 0 R >>".into(),
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".into(),
|
||||
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >>".into(),
|
||||
stream(&format!("0 0 m BT /F1 12 Tf (Text) Tj ET {tail}")),
|
||||
FONT.into(),
|
||||
],
|
||||
"",
|
||||
);
|
||||
let before = pdfcraft_cos::write_incremental(&doc, &pdfcraft_cos::SaveOptions::default()).unwrap();
|
||||
assert!(matches!(autotag_text(&mut doc), Err(AutoTagError::Unsupported { .. })));
|
||||
assert_eq!(pdfcraft_cos::write_incremental(&doc, &pdfcraft_cos::SaveOptions::default()).unwrap(), before);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn autotag_text_refuses_form_xobjects_and_does_not_modify_the_document() {
|
||||
let mut doc = pdf(
|
||||
&[
|
||||
"<< /Type /Catalog /Pages 2 0 R >>".into(),
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".into(),
|
||||
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> /XObject << /Fm1 6 0 R >> >> >>".into(),
|
||||
stream("BT /F1 12 Tf 20 100 Td (Hello) Tj ET /Fm1 Do"),
|
||||
FONT.into(),
|
||||
"<< /Type /XObject /Subtype /Form /BBox [0 0 50 50] /Length 12 >>\nstream\n0 0 10 10 re f\nendstream".into(),
|
||||
],
|
||||
"",
|
||||
);
|
||||
assert!(matches!(autotag_text(&mut doc), Err(AutoTagError::Unsupported { .. })));
|
||||
assert!(!doc.get(doc.root().unwrap()).as_dict().unwrap().contains(b"StructTreeRoot"));
|
||||
assert_eq!(autotag_text(&mut pdf(&good(), "")), Err(AutoTagError::AlreadyTagged));
|
||||
|
||||
@@ -27,7 +27,9 @@ Comments (annotations), ISO 32000-2 §12.5. Layer L3, depends on `pdfcraft-cos`,
|
||||
comment another program drew with a font that has those characters, whose appearance is kept
|
||||
rather than redrawn with `?` (new text for it is taken).
|
||||
- **Edits:** reply (`/IRT`), set review status (a `/State` reply, as Acrobat's "Set status"
|
||||
does), change text, move, resize, restyle, delete (with pop-up and replies).
|
||||
does), change text, move, resize, restyle, delete (with pop-up and replies), and open, close
|
||||
or move the pop-up window (`set_popup`: `/Popup` `/Open` and `/Rect`, created beside a comment
|
||||
that has none; a note's own `/Open` follows). `summaries` report each comment's pop-up.
|
||||
|
||||
## API sketch
|
||||
|
||||
|
||||
+115
-31
@@ -8,19 +8,25 @@
|
||||
//! itself; for the other values, callers that hold the document follow references first
|
||||
//! (`draw::with_direct_values`).
|
||||
//!
|
||||
//! The note icons are PdfCraft's own drawings (AGENTS.md §1). Text boxes use the standard
|
||||
//! Helvetica font with WinAnsi encoding, and draw Thai from the craft-fonts Thai face as Type 3
|
||||
//! glyphs (`pdfcraft_fonts::shaped_text`, the writer Add text uses); line breaking uses
|
||||
//! [`text_width`], the standard-14 metrics and the Thai face's shaped advances.
|
||||
//! The note icons are PdfCraft's own drawings (AGENTS.md §1). Text boxes use a standard text
|
||||
//! font with WinAnsi encoding: Helvetica, or the face their `/DA` or `/DS` asks for
|
||||
//! ([`crate::text_style`]), and draw Thai from the craft-fonts Thai face as Type 3 glyphs
|
||||
//! (`pdfcraft_fonts::shaped_text`, the writer Add text uses); lines break at that face's
|
||||
//! standard-14 widths and the Thai face's shaped advances (no other font program is bundled).
|
||||
|
||||
use pdfcraft_cos::{Dict, Object, PdfString, Stream};
|
||||
use pdfcraft_fonts::shaped_text;
|
||||
use pdfcraft_fonts::{first_undrawable, helvetica_width, literal, win_ansi, wrap_with};
|
||||
use pdfcraft_fonts::{first_undrawable, literal, win_ansi, wrap_with};
|
||||
|
||||
/// The width of `text` at `size` as appearances draw it: Helvetica, with Thai shaped in the Thai
|
||||
/// face that text boxes draw it with.
|
||||
pub fn text_width(text: &str, size: f64) -> f64 {
|
||||
shaped_text::thai_width(text, size, helvetica_width)
|
||||
text_width_in(pdfcraft_fonts::Std14::Helvetica, text, size)
|
||||
}
|
||||
|
||||
/// [`text_width`] in the standard `face` a text box draws its other text in.
|
||||
pub fn text_width_in(face: pdfcraft_fonts::Std14, text: &str, size: f64) -> f64 {
|
||||
shaped_text::thai_width(text, size, |s, size| face.text_width(s, size))
|
||||
}
|
||||
|
||||
/// `text` wrapped `width` wide as [`text_width`] measures it; a Thai mark stays on its letter.
|
||||
@@ -410,13 +416,17 @@ pub fn da_border(d: &Dict) -> Option<Rgb> {
|
||||
col
|
||||
}
|
||||
|
||||
/// `/DA` of a text box: (text colour, font size). Defaults to black 12 pt.
|
||||
/// `/DA` of a text box: (text colour, font size). Defaults to black 12 pt: a `Tf` without a
|
||||
/// usable size (missing, zero, negative or not a number) keeps 12 pt, and sizes past 400 pt are
|
||||
/// capped. A text box has no automatic size, so a zero size, which means auto-size in a form
|
||||
/// field's `/DA` (ISO 32000-2 §12.7.4.3), is the default here. An operand that isn't a finite
|
||||
/// number (`NaN`, `inf`, which Rust's parser would otherwise accept) is ignored with its operator.
|
||||
pub fn parse_da(d: &Dict) -> (Rgb, f64) {
|
||||
let da = d.get(b"DA").and_then(|o| o.as_string()).map(|s| String::from_utf8_lossy(&s.bytes).into_owned()).unwrap_or_default();
|
||||
let toks: Vec<&str> = da.split_whitespace().collect();
|
||||
let mut col = [0.0; 3];
|
||||
let mut size = 12.0;
|
||||
let num = |i: usize| toks.get(i).and_then(|t| t.parse::<f64>().ok());
|
||||
let num = |i: usize| toks.get(i).and_then(|t| t.parse::<f64>().ok()).filter(|v| v.is_finite());
|
||||
for (i, t) in toks.iter().enumerate() {
|
||||
match *t {
|
||||
"rg" if i >= 3 => {
|
||||
@@ -544,7 +554,9 @@ pub fn undrawable_text(d: &Dict) -> Option<(&'static str, char)> {
|
||||
b"FreeText" => return Some(("the comment's text", shaped_text::first_undrawable(&text(b"Contents")?)?)),
|
||||
b"Line" if !d.contains(b"PCMeasureValue") => ("the line's caption", line_caption(d)?),
|
||||
b"Line" | b"PolyLine" | b"Polygon" => ("the measurement label", text(b"PCMeasureValue")?),
|
||||
b"Stamp" if matches!(d.get(b"PCStamp"), Some(Object::Bool(true))) => ("the stamp's \"By\" line", text(b"PCByLine")?),
|
||||
b"Stamp" if matches!(d.get(b"PCStamp"), Some(Object::Bool(true))) || d.contains(b"PCPicture") => {
|
||||
("the stamp's \"By\" line", text(b"PCByLine")?)
|
||||
}
|
||||
// Drawn in Helvetica when the redaction is applied: refused when it is marked.
|
||||
b"Redact" => ("the redaction's overlay text", text(b"OverlayText")?),
|
||||
_ => return None,
|
||||
@@ -554,18 +566,19 @@ pub fn undrawable_text(d: &Dict) -> Option<(&'static str, char)> {
|
||||
|
||||
/// `/Font` resources naming `/Helv`: standard Helvetica with WinAnsiEncoding.
|
||||
pub(crate) fn helvetica_resource() -> Object {
|
||||
Object::Dict(helvetica_fonts())
|
||||
Object::Dict(font_resources(pdfcraft_fonts::Std14::Helvetica))
|
||||
}
|
||||
|
||||
/// [`helvetica_resource`]'s dictionary.
|
||||
fn helvetica_fonts() -> Dict {
|
||||
/// `/Font` resources naming one standard face with WinAnsiEncoding, under the resource name
|
||||
/// [`crate::text_style::resource_name`] gives it (`/Helv` for Helvetica).
|
||||
fn font_resources(face: pdfcraft_fonts::Std14) -> Dict {
|
||||
let mut font = Dict::new();
|
||||
font.set(b"Type".to_vec(), Object::name("Font"));
|
||||
font.set(b"Subtype".to_vec(), Object::name("Type1"));
|
||||
font.set(b"BaseFont".to_vec(), Object::name("Helvetica"));
|
||||
font.set(b"BaseFont".to_vec(), Object::name(face.base_font()));
|
||||
font.set(b"Encoding".to_vec(), Object::name("WinAnsiEncoding"));
|
||||
let mut fonts = Dict::new();
|
||||
fonts.set(b"Helv".to_vec(), Object::Dict(font));
|
||||
fonts.set(crate::text_style::resource_name(face).as_bytes().to_vec(), Object::Dict(font));
|
||||
fonts
|
||||
}
|
||||
|
||||
@@ -661,7 +674,8 @@ pub(crate) fn build_on_page(doc: &Document, d: &Dict, page: Option<[f64; 4]>) ->
|
||||
b"Text" => return draw_icon(&context, "Note", [1.0, 0.82, 0.0], drawing),
|
||||
b"FileAttachment" => return draw_icon(&context, "PushPin", [0.0, 0.47, 0.84], drawing),
|
||||
b"Stamp" => return draw_stamp(&context, drawing),
|
||||
b"FreeText" => return draw_free_text(&context, drawing),
|
||||
// The face a text box's `/DA` font names in the form's `/DR`, when it names one.
|
||||
b"FreeText" => return draw_free_text(&context, drawing, crate::text_style::dr_face(doc, d)),
|
||||
_ => {}
|
||||
}
|
||||
let mut drawing = drawing;
|
||||
@@ -971,11 +985,31 @@ fn draw_markup(context: &AppearanceContext<'_>, drawing: &mut AppearanceDrawing)
|
||||
}
|
||||
|
||||
fn draw_redaction(context: &AppearanceContext<'_>, drawing: &mut AppearanceDrawing) -> Option<()> {
|
||||
let d = context.dict;
|
||||
let stroke = context.stroke;
|
||||
let c = &mut drawing.content;
|
||||
// While marked: the outline of each area (the fill comes when applied).
|
||||
let q = quads(context)?;
|
||||
let col = stroke.unwrap_or([0.89, 0.13, 0.13]);
|
||||
// ISO 32000-2 gives a mark no outline colour (§12.5.6.23, Table 195). An array `/OC` of
|
||||
// three numbers is the one some writers give it, and is drawn (the observation is in
|
||||
// `parity/acrobat-features.toml`); `/OC` as ISO 32000-2 defines it (Table 166) is an
|
||||
// optional-content dictionary, which this leaves alone.
|
||||
let outline = nums(d, b"OC").and_then(|c| match c.as_slice() {
|
||||
[r, g, b] if c.iter().all(|x| x.is_finite()) => Some([r.clamp(0.0, 1.0), g.clamp(0.0, 1.0), b.clamp(0.0, 1.0)]),
|
||||
_ => None,
|
||||
});
|
||||
// Quadrilaterals are outlined in the `/OC` colour, else in `/C` as they always were.
|
||||
let (q, col) = match d.get(b"QuadPoints") {
|
||||
Some(_) => (quads(context)?, outline.or(stroke)),
|
||||
// Without `/QuadPoints`, `/Rect` is the area (Table 195): outlined just inside its
|
||||
// edges when the mark names an outline colour, else not drawn while marked.
|
||||
None => {
|
||||
let outline = outline?;
|
||||
let rect = context.rect;
|
||||
let [x0, y0, x1, y1] = [rect[0] + 0.5, rect[1] + 0.5, rect[2] - 0.5, rect[3] - 0.5];
|
||||
(vec![[x0, y1, x1, y1, x0, y0, x1, y0]], Some(outline))
|
||||
}
|
||||
};
|
||||
let col = col.unwrap_or([0.89, 0.13, 0.13]);
|
||||
c.push_str(&format!("{}1 w\n", rg_stroke(col)));
|
||||
for quad in q.iter() {
|
||||
c.push_str(&format!(
|
||||
@@ -1230,7 +1264,8 @@ fn draw_stamp(context: &AppearanceContext<'_>, mut drawing: AppearanceDrawing) -
|
||||
return Some(form(rect, c.as_bytes(), res));
|
||||
}
|
||||
// A custom stamp: its picture (an image, or a form mapped to /PCPictureSize) fills
|
||||
// the rectangle. An image signature added to a turned page (`/PCPictureRotate`) gets
|
||||
// the rectangle. An image signature or a stamp with a line added to a turned page
|
||||
// (`/PCPictureRotate`) gets
|
||||
// the standard counter-rotation as its form `/Matrix`: viewers fit the turned
|
||||
// bounding box to `/Rect` (ISO 32000-2 §12.5.5), so it reads upright as displayed.
|
||||
if let Some(pic) = d.get(b"PCPicture").and_then(Object::as_ref) {
|
||||
@@ -1239,14 +1274,61 @@ fn draw_stamp(context: &AppearanceContext<'_>, mut drawing: AppearanceDrawing) -
|
||||
[w, h] if *w > 0.0 && *h > 0.0 => Some((*w, *h)),
|
||||
_ => None,
|
||||
});
|
||||
let place = picture_place(rect, image, size)?;
|
||||
// A text line (#1741) takes the bottom of the rectangle, and the picture keeps its
|
||||
// shape, centred above it. Without one the picture fills the rectangle.
|
||||
let line = d.get(b"PCByLine").and_then(Object::as_string).map(PdfString::to_text).filter(|l| !l.trim().is_empty());
|
||||
let turn = picture_turn(d);
|
||||
// A lined stamp on a quarter-turned page is laid out in its displayed box (the
|
||||
// rectangle with its sides swapped) and turned into `/Rect` by the `/Matrix` below.
|
||||
// Laid out in user space, the viewer's fit of the turned box to `/Rect` would scale
|
||||
// the two displayed axes differently and squash the picture and its line.
|
||||
let bbox = if line.is_some() && matches!(turn, 90 | 270) { [0.0, 0.0, rect[3] - rect[1], rect[2] - rect[0]] } else { rect };
|
||||
let [x0, y0, x1, y1] = bbox;
|
||||
let band = if line.is_some() { (y1 - y0) * crate::CUSTOM_LINE_BAND } else { 0.0 };
|
||||
let (w, h) = (x1 - x0, y1 - y0 - band);
|
||||
let place = match (&line, size) {
|
||||
(Some(_), Some((sw, sh))) => {
|
||||
let k = (w / sw).min(h / sh).max(0.0);
|
||||
let (pw, ph) = (sw * k, sh * k);
|
||||
let (px, py) = (x0 + (w - pw) / 2.0, y0 + band + (h - ph) / 2.0);
|
||||
if image {
|
||||
format!("{} 0 0 {} {} {} cm", n(pw), n(ph), n(px), n(py))
|
||||
} else {
|
||||
format!("{} 0 0 {} {} {} cm", n(k), n(k), n(px), n(py))
|
||||
}
|
||||
}
|
||||
// Without a line the band is empty and this is the rectangle itself.
|
||||
_ => picture_place([x0, y0 + band, x1, y1], image, size)?,
|
||||
};
|
||||
c.push_str(&format!("q {place} /Pic Do Q\n"));
|
||||
// Bytes from here: the line is WinAnsi, not UTF-8.
|
||||
let mut content = std::mem::take(c).into_bytes();
|
||||
if let Some(l) = &line {
|
||||
// Centred in the band, at its usual size unless the stamp was made narrower.
|
||||
let mut size = band * crate::CUSTOM_LINE_TEXT;
|
||||
let tw = text_width(l, size);
|
||||
if tw > w - 4.0 && tw > 0.0 {
|
||||
size *= ((w - 4.0) / tw).max(0.0);
|
||||
}
|
||||
let tw = text_width(l, size);
|
||||
let ty = y0 + (band - size * 0.72) / 2.0;
|
||||
content.extend(format!("BT\n0.2 0.2 0.2 rg\n/Helv {} Tf\n1 0 0 1 {} {} Tm ", n(size), n(x0 + (w - tw) / 2.0), n(ty)).bytes());
|
||||
content.extend(literal(&win_ansi(l)));
|
||||
content.extend_from_slice(b" Tj\nET\n");
|
||||
let mut f = Dict::new();
|
||||
f.set(b"Type".to_vec(), Object::name("Font"));
|
||||
f.set(b"Subtype".to_vec(), Object::name("Type1"));
|
||||
f.set(b"BaseFont".to_vec(), Object::name("Helvetica"));
|
||||
f.set(b"Encoding".to_vec(), Object::name("WinAnsiEncoding"));
|
||||
let mut fonts = Dict::new();
|
||||
fonts.set(b"Helv".to_vec(), Object::Dict(f));
|
||||
res.set(b"Font".to_vec(), Object::Dict(fonts));
|
||||
}
|
||||
let mut xo = Dict::new();
|
||||
xo.set(b"Pic".to_vec(), Object::Ref(pic));
|
||||
res.set(b"XObject".to_vec(), Object::Dict(xo));
|
||||
let mut stream = form(rect, c.as_bytes(), res);
|
||||
let turn = picture_turn(d);
|
||||
if image && turn != 0 {
|
||||
let mut stream = form(bbox, &content, res);
|
||||
if (image || line.is_some()) && turn != 0 {
|
||||
// The page's view matrix without its offset: display axes in user space.
|
||||
let m = pdfcraft_model::view_matrix_for(turn, [0.0; 4]);
|
||||
let matrix = [m[0], m[1], m[2], m[3], 0.0, 0.0];
|
||||
@@ -1359,7 +1441,7 @@ fn shaped_border(
|
||||
Some(rect)
|
||||
}
|
||||
|
||||
fn draw_free_text(context: &AppearanceContext<'_>, mut drawing: AppearanceDrawing) -> Option<Stream> {
|
||||
fn draw_free_text(context: &AppearanceContext<'_>, mut drawing: AppearanceDrawing, dr_face: Option<pdfcraft_fonts::Std14>) -> Option<Stream> {
|
||||
let d = context.dict;
|
||||
let parts = context.parts;
|
||||
let rect = context.rect;
|
||||
@@ -1367,11 +1449,12 @@ fn draw_free_text(context: &AppearanceContext<'_>, mut drawing: AppearanceDrawin
|
||||
let mut c = std::mem::take(&mut drawing.content);
|
||||
let mut res = std::mem::take(&mut drawing.resources);
|
||||
let _tail = std::mem::take(&mut drawing.tail);
|
||||
let (text_color, size) = parse_da(d);
|
||||
let crate::text_style::TextStyle { face, size, color: text_color } = crate::text_style::text_style(d, dr_face);
|
||||
// The box's border and a callout's leader line: their own colour, else the text's.
|
||||
let line_color = da_border(d).unwrap_or(text_color);
|
||||
let bg = stroke;
|
||||
let bw = if d.contains(b"BS") || d.contains(b"Border") { border_width(d) } else { 0.0 };
|
||||
// Without `/BS` or `/Border`, the `/Border` default [0 0 1]: a 1-pt border (Table 166).
|
||||
let bw = border_width(d);
|
||||
// A callout: the leader line (arrowhead at its first point), and the text box inside
|
||||
// `/Rect` by `/RD`.
|
||||
// Text added to a turned page is drawn upright in its displayed box, which the form
|
||||
@@ -1469,37 +1552,38 @@ fn draw_free_text(context: &AppearanceContext<'_>, mut drawing: AppearanceDrawin
|
||||
c.push_str("/GS1 gs\n");
|
||||
}
|
||||
c.push_str(&format!(
|
||||
"{} {} {} {} re W n\nBT\n/Helv {} Tf\n{}",
|
||||
"{} {} {} {} re W n\nBT\n/{} {} Tf\n{}",
|
||||
n(rect[0]),
|
||||
n(rect[1]),
|
||||
n(rect[2] - rect[0]),
|
||||
n(rect[3] - rect[1]),
|
||||
crate::text_style::resource_name(face),
|
||||
n(size),
|
||||
rg(text_color)
|
||||
));
|
||||
let mut out = c.into_bytes();
|
||||
let lines = wrap(&text, size, width);
|
||||
let lines = pdfcraft_fonts::wrap_with(&text, size, width, |s, size| text_width_in(face, s, size));
|
||||
let mut y = rect[3] - pad - size * reach(&lines)[0];
|
||||
if round {
|
||||
y -= ((rect[3] - rect[1] - 2.0 * pad - text_lines_height(&lines, size)) / 2.0).max(0.0);
|
||||
}
|
||||
// Thai is shaped and drawn from the Thai face (Type 3 fonts in the form's resources, whose
|
||||
// streams `apply_appearance` stores in the document); the rest, and Thai it can't draw (as
|
||||
// `?`, which `undrawable_text` reports), in Helvetica.
|
||||
let mut fonts = helvetica_fonts();
|
||||
// `?`, which `undrawable_text` reports), in the box's standard face.
|
||||
let mut fonts = font_resources(face);
|
||||
let (pieces, shaped) = shaped_text::appearance_lines(&lines, &mut fonts);
|
||||
let mut current = None;
|
||||
for pieces in &pieces {
|
||||
if y < rect[1] - size {
|
||||
break;
|
||||
}
|
||||
let lw = shaped_text::pieces_width(pieces, size, 0.0, helvetica_width);
|
||||
let lw = shaped_text::pieces_width(pieces, size, 0.0, |s, size| face.text_width(s, size));
|
||||
let x = match q {
|
||||
1 => rect[0] + pad + (width - lw) / 2.0,
|
||||
2 => rect[2] - pad - lw,
|
||||
_ => rect[0] + pad,
|
||||
};
|
||||
shaped.show_line(&mut out, pieces, x, y, size, "Helv", win_ansi, |s| helvetica_width(s, size), &mut current);
|
||||
shaped.show_line(&mut out, pieces, x, y, size, crate::text_style::resource_name(face), win_ansi, |s| face.text_width(s, size), &mut current);
|
||||
y -= size * 1.2;
|
||||
}
|
||||
out.extend_from_slice(b"ET\n");
|
||||
|
||||
+127
-10
@@ -204,14 +204,110 @@ fn subject(shape: &Shape) -> &'static str {
|
||||
pub fn callout_attach(rect: [f64; 4], knee: [f64; 2]) -> [f64; 2] {
|
||||
let [x0, y0, x1, y1] = normalize(rect);
|
||||
let (cx, cy) = ((x0 + x1) / 2.0, (y0 + y1) / 2.0);
|
||||
if knee[0] < x0 {
|
||||
[x0, cy]
|
||||
} else if knee[0] > x1 {
|
||||
[x1, cy]
|
||||
} else if knee[1] > y1 {
|
||||
[cx, y1]
|
||||
match callout_side(rect, knee) {
|
||||
Side::Left => [x0, cy],
|
||||
Side::Right => [x1, cy],
|
||||
Side::Top => [cx, y1],
|
||||
Side::Bottom => [cx, y0],
|
||||
}
|
||||
}
|
||||
|
||||
/// A side of a callout's text box.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Side {
|
||||
Left,
|
||||
Right,
|
||||
Top,
|
||||
Bottom,
|
||||
}
|
||||
|
||||
impl Side {
|
||||
/// Whether a knee line on this side is horizontal (it meets the left or right side). Acrobat
|
||||
/// lets a knee line be resized along its own direction only (Acrobat DC Help, 11/28/2019,
|
||||
/// p. 357).
|
||||
pub fn horizontal(self) -> bool {
|
||||
matches!(self, Side::Left | Side::Right)
|
||||
}
|
||||
}
|
||||
|
||||
/// The side of the text box `rect` that faces `knee`: the one [`callout_attach`] attaches to.
|
||||
///
|
||||
/// Every position has one side (review on #4094):
|
||||
/// - left or right of the box (`x < x0`, `x > x1`): that side, whatever `y` is, so a knee off a
|
||||
/// corner diagonally, or on the line of the top or bottom edge past the box, is beside it;
|
||||
/// - otherwise above or below it (`y > y1`, `y < y0`): that side, so a knee on the line of the
|
||||
/// left or right edge past the box is above or below it;
|
||||
/// - on the box's outline, or within `CALLOUT_SLACK` (0.01 pt) inside it, since the page hands
|
||||
/// positions back as `f32` values: the side whose edge it lies on, the left or right edge
|
||||
/// first, so a corner takes the left or right side as a knee beside the box does. The line
|
||||
/// stays out of the box (it was sent across the box to the bottom side);
|
||||
/// - inside the box, or with a coordinate that isn't a number: the bottom side.
|
||||
pub fn callout_side(rect: [f64; 4], knee: [f64; 2]) -> Side {
|
||||
let [x0, y0, x1, y1] = normalize(rect);
|
||||
let [x, y] = knee;
|
||||
// Before any comparison: one with NaN is false, so the other coordinate alone would decide.
|
||||
if x.is_nan() || y.is_nan() {
|
||||
return Side::Bottom;
|
||||
}
|
||||
if x < x0 {
|
||||
Side::Left
|
||||
} else if x > x1 {
|
||||
Side::Right
|
||||
} else if y > y1 {
|
||||
Side::Top
|
||||
} else if y < y0 {
|
||||
Side::Bottom
|
||||
} else if x - x0 < CALLOUT_SLACK {
|
||||
Side::Left
|
||||
} else if x1 - x < CALLOUT_SLACK {
|
||||
Side::Right
|
||||
} else if y1 - y < CALLOUT_SLACK {
|
||||
Side::Top
|
||||
} else {
|
||||
[cx, y0]
|
||||
Side::Bottom
|
||||
}
|
||||
}
|
||||
|
||||
/// A callout's knee line when Acrobat lays it out: 12 pt, out from the middle of the side. Seen in
|
||||
/// Acrobat Pro DC, a 2021 Continuous release: a new callout's knee line, and one laid out again
|
||||
/// after its knee was dragged into the box or the side it meets was moved, are all 12 pt, and the
|
||||
/// knee can't come nearer the box than that.
|
||||
pub const CALLOUT_KNEE_LINE: f64 = 12.0;
|
||||
|
||||
/// Where a knee goes on `side` of the text box `rect`: [`CALLOUT_KNEE_LINE`] out from the middle
|
||||
/// of that side, so the knee line is level (left, right) or upright (top, bottom).
|
||||
pub fn callout_knee_on(rect: [f64; 4], side: Side) -> [f64; 2] {
|
||||
let [x0, y0, x1, y1] = normalize(rect);
|
||||
let (cx, cy) = ((x0 + x1) / 2.0, (y0 + y1) / 2.0);
|
||||
match side {
|
||||
Side::Left => [x0 - CALLOUT_KNEE_LINE, cy],
|
||||
Side::Right => [x1 + CALLOUT_KNEE_LINE, cy],
|
||||
Side::Top => [cx, y1 + CALLOUT_KNEE_LINE],
|
||||
Side::Bottom => [cx, y0 - CALLOUT_KNEE_LINE],
|
||||
}
|
||||
}
|
||||
|
||||
/// A new callout's knee: on the side of its text box `rect` that faces the arrow `point`
|
||||
/// ([`callout_knee_on`]).
|
||||
pub fn callout_knee(rect: [f64; 4], point: [f64; 2]) -> [f64; 2] {
|
||||
callout_knee_on(rect, callout_side(rect, point))
|
||||
}
|
||||
|
||||
/// How far apart, in points, two positions of a callout's box or line may be and still count as the
|
||||
/// same. The page hands a box back as `f32` values, which moves a coordinate such as 323.05 by a few
|
||||
/// hundred-thousandths of a point (review on #4094).
|
||||
pub(crate) const CALLOUT_SLACK: f64 = 0.01;
|
||||
|
||||
/// Whether `end` lies on `side` of the text box `rect`: the leader line can stay where it meets it.
|
||||
pub(crate) fn on_side(rect: [f64; 4], side: Side, end: [f64; 2]) -> bool {
|
||||
let [x0, y0, x1, y1] = normalize(rect);
|
||||
let near = |a: f64, b: f64| (a - b).abs() < CALLOUT_SLACK;
|
||||
let within = |v: f64, lo: f64, hi: f64| v > lo - CALLOUT_SLACK && v < hi + CALLOUT_SLACK;
|
||||
match side {
|
||||
Side::Left => near(end[0], x0) && within(end[1], y0, y1),
|
||||
Side::Right => near(end[0], x1) && within(end[1], y0, y1),
|
||||
Side::Top => near(end[1], y1) && within(end[0], x0, x1),
|
||||
Side::Bottom => near(end[1], y0) && within(end[0], x0, x1),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -296,15 +392,20 @@ pub fn add_annotation(doc: &mut Document, new: &NewAnnotation, meta: &Meta) -> R
|
||||
let list = contours.iter().filter(|c| c.len() > 2).map(|c| num_array(&c.iter().flat_map(|p| [p[0], p[1]]).collect::<Vec<_>>())).collect();
|
||||
d.set(b"PCOutline".to_vec(), Object::Array(list));
|
||||
}
|
||||
Shape::CustomStamp { name, picture, image, size, .. } => {
|
||||
Shape::CustomStamp { name, picture, image, size, line, .. } => {
|
||||
let clean: String = name.chars().filter(char::is_ascii_alphanumeric).collect();
|
||||
d.set(b"Name".to_vec(), Object::name(&format!("PCCustom{clean}")));
|
||||
d.set(b"PCPicture".to_vec(), Object::Ref(*picture));
|
||||
d.set(b"PCPictureImage".to_vec(), Object::Bool(*image));
|
||||
d.set(b"PCPictureSize".to_vec(), num_array(&[size.0, size.1]));
|
||||
let lined = line.as_deref().map(str::trim).filter(|l| !l.is_empty());
|
||||
if let Some(l) = lined {
|
||||
d.set(b"PCByLine".to_vec(), PdfString::text(l));
|
||||
}
|
||||
// An image signature's rectangle is in user space; on a turned page its appearance is
|
||||
// turned back (see `appearance::build`), so it reads upright as displayed.
|
||||
if *image && matches!(clean.as_str(), "Signature" | "Initials") {
|
||||
// turned back (see `appearance::build`), so it reads upright as displayed. A stamp
|
||||
// with a line is laid out in the displayed box, so it needs the turn too.
|
||||
if lined.is_some() || (*image && matches!(clean.as_str(), "Signature" | "Initials")) {
|
||||
let turn = pdfcraft_model::pages(doc).get(new.page).map_or(0, |p| p.rotation(doc));
|
||||
if turn != 0 {
|
||||
d.set(b"PCPictureRotate".to_vec(), Object::Int(turn));
|
||||
@@ -500,6 +601,22 @@ fn add_popup(doc: &mut Document, parent: ObjRef, rect: Option<[f64; 4]>, annots:
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The share of a custom stamp's height its text line takes (the rest is the picture).
|
||||
pub const CUSTOM_LINE_BAND: f64 = 0.22;
|
||||
|
||||
/// A custom stamp line's text height as a share of its band.
|
||||
pub const CUSTOM_LINE_TEXT: f64 = 0.62;
|
||||
|
||||
/// The natural size of a custom stamp whose picture is `picture` points (#1741): with `line`,
|
||||
/// the band under the picture is added, and the stamp is as wide as the line at its usual size
|
||||
/// when that is wider than the picture.
|
||||
pub fn custom_stamp_size(picture: (f64, f64), line: Option<&str>) -> (f64, f64) {
|
||||
let Some(line) = line else { return picture };
|
||||
let h = picture.1 / (1.0 - CUSTOM_LINE_BAND);
|
||||
let text = appearance::text_width(line, h * CUSTOM_LINE_BAND * CUSTOM_LINE_TEXT) + 8.0;
|
||||
(picture.0.max(text), h)
|
||||
}
|
||||
|
||||
/// Counterrotate a newly placed picture stamp's appearance into displayed-page axes.
|
||||
/// The picture may be an image or a PDF page. The normal appearance's transformed bounding
|
||||
/// box is fitted to `/Rect` by PDF viewers.
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
use super::create::finite;
|
||||
use super::draw::set_appearance;
|
||||
use super::lookup::{annot_dict, annot_ref, annotation_flags, annots, drawn_upright, is_fill_sign, page_ref, page_refs};
|
||||
use super::modify::{fillable, touch, unlocked};
|
||||
use super::modify::{callout_line, callout_text_box, fillable, touch, unlocked};
|
||||
use super::text_style;
|
||||
use super::types::{BorderShape, FLAG_LOCKED, LineEnding, Meta, NoteIcon, Rgb};
|
||||
use super::{AnnotError, Dict, Document, ObjRef, Object, PdfString, appearance};
|
||||
|
||||
@@ -23,7 +24,8 @@ pub struct Summary {
|
||||
pub in_reply_to: Option<String>,
|
||||
/// The page and `/Annots` position `/IRT` points at, by reference (`/NM` need not be unique).
|
||||
pub parent: Option<(usize, usize)>,
|
||||
/// `/RT /Group`: grouped with the `/IRT` annotation (Replace Text's caret), not a reply to it.
|
||||
/// `/RT /Group`: with an `/IRT` reference, a subordinate of the group whose primary that is
|
||||
/// ([`is_group_subordinate`]), not a reply to it.
|
||||
pub grouped: bool,
|
||||
pub rect: [f32; 4],
|
||||
pub color: Option<[f32; 3]>,
|
||||
@@ -35,9 +37,66 @@ pub struct Summary {
|
||||
pub fill_sign: bool,
|
||||
/// The NoRotate flag (`/F` bit 5), as `pdfcraft_render::Annotation::no_rotate`.
|
||||
pub no_rotate: bool,
|
||||
/// A line's two ends (`/L`), or the corners of connected lines, a polygon or a cloud
|
||||
/// (`/Vertices`), in user space; empty for other comments.
|
||||
/// A line's two ends (`/L`), the corners of connected lines, a polygon or a cloud
|
||||
/// (`/Vertices`), or a callout's arrow point and knee (`/CL` without its end, which follows
|
||||
/// the text box), in user space; empty for other comments.
|
||||
pub points: Vec<[f32; 2]>,
|
||||
/// A callout's text box (`/Rect` inset by `/RD`), in user space; `None` for other comments.
|
||||
pub text_box: Option<[f32; 4]>,
|
||||
/// The comment's pop-up window (`/Popup`), when it has one.
|
||||
pub popup: Option<PopupInfo>,
|
||||
}
|
||||
|
||||
impl Summary {
|
||||
/// A subordinate of a group (`/RT /Group` with an `/IRT` to a listed comment, ISO 32000-2
|
||||
/// §12.5.6.2): part of its primary's comment, not a reply. As
|
||||
/// `pdfcraft_render::Annotation::is_group_member`, which also drops a looping `/IRT`.
|
||||
pub fn is_group_member(&self) -> bool {
|
||||
self.grouped && self.parent.is_some()
|
||||
}
|
||||
}
|
||||
|
||||
/// A comment's pop-up window (ISO 32000-2 §12.5.6.14): where it sits on the page and whether it
|
||||
/// is shown open.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct PopupInfo {
|
||||
/// `/Rect` of the `/Popup` annotation, in user space.
|
||||
pub rect: [f32; 4],
|
||||
/// `/Open` of the `/Popup` annotation.
|
||||
pub open: bool,
|
||||
}
|
||||
|
||||
/// The pop-up the comment `annot` (the object `own`, when it is one of its own) names in
|
||||
/// `/Popup`, when it is the comment's: a pop-up annotation whose `/Parent`, if it has one, is a
|
||||
/// reference to the comment. A `/Popup` naming another annotation, or a pop-up of another
|
||||
/// comment, isn't. ISO 32000-2:2020 §12.5.6.14, Table 186: `/Parent` is "(Optional; shall be
|
||||
/// an indirect reference)".
|
||||
pub(crate) fn own_popup(doc: &Document, own: Option<ObjRef>, annot: &Dict) -> Option<ObjRef> {
|
||||
let pr = annot.reference(b"Popup")?;
|
||||
let is_own = doc.get(pr).as_dict().is_some_and(|pd| {
|
||||
pd.name(b"Subtype") == Some(b"Popup")
|
||||
&& pd
|
||||
.get(b"Parent")
|
||||
.is_none_or(|parent| parent.as_ref().is_some_and(|parent| own.is_some_and(|own| final_ref(doc, parent) == final_ref(doc, own))))
|
||||
});
|
||||
is_own.then_some(pr)
|
||||
}
|
||||
|
||||
/// The comment's own pop-up (see [`own_popup`]), as [`PopupInfo`]: `None` when it has none or it
|
||||
/// is unreadable.
|
||||
pub(crate) fn popup_info(doc: &Document, own: Option<ObjRef>, annot: &Dict) -> Option<PopupInfo> {
|
||||
// Another annotation's rectangle and open state aren't this comment's (review on #2137).
|
||||
let r = own_popup(doc, own, annot)?;
|
||||
let p = doc.get(r);
|
||||
let p = p.as_dict()?;
|
||||
let rect: Vec<f32> = doc.resolve(p.get(b"Rect")?).as_array()?.iter().filter_map(|v| doc.resolve(v).as_f64().map(|x| x as f32)).collect();
|
||||
// Four numbers that are finite as `f32` (a huge one becomes infinite), corners in any order.
|
||||
let [x0, y0, x1, y1] = rect[..] else { return None };
|
||||
if !rect.iter().all(|v| v.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
let open = p.get(b"Open").map(|o| doc.resolve(o)).is_some_and(|o| matches!(&*o, Object::Bool(true)));
|
||||
Some(PopupInfo { rect: [x0.min(x1), y0.min(y1), x0.max(x1), y0.max(y1)], open })
|
||||
}
|
||||
|
||||
pub(crate) fn text_value(doc: &Document, d: &Dict, key: &[u8]) -> Option<String> {
|
||||
@@ -74,6 +133,15 @@ fn final_ref(doc: &Document, mut r: ObjRef) -> ObjRef {
|
||||
r
|
||||
}
|
||||
|
||||
/// Whether an annotation is a subordinate of a group rather than a reply: `/RT /Group` with an
|
||||
/// `/IRT` reference (ISO 32000-2 §12.5.6.2, Table 172). The group's primary is the `/IRT`
|
||||
/// annotation, and the subordinate's own text, author, colour, dates and pop-up are ignored.
|
||||
/// `/RT` is `R` by default, and a value other than `Group` reads as `R` too. Keep in step with
|
||||
/// `pdfcraft_render::inspect`.
|
||||
pub fn is_group_subordinate(d: &Dict) -> bool {
|
||||
d.name(b"RT") == Some(b"Group") && d.reference(b"IRT").is_some()
|
||||
}
|
||||
|
||||
/// Every comment (see [`is_comment_subtype`]), ordered by page and then top edge.
|
||||
pub fn summaries(doc: &Document) -> Vec<Summary> {
|
||||
let mut out = Vec::new();
|
||||
@@ -130,15 +198,29 @@ pub fn summaries(doc: &Document) -> Vec<Summary> {
|
||||
pdfcraft_geom::quad_points::usable_quads(entries).into_iter().map(|q| q.map(|v| v as f32)).collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
// Keep in step with `pdfcraft_render::inspect`.
|
||||
// Keep in step with `pdfcraft_render::inspect`: a callout gives its points only with a
|
||||
// readable text box, without which they can't be changed either.
|
||||
let callout = (subtype == "FreeText").then(|| callout_line(doc, d).zip(callout_text_box(doc, d))).flatten();
|
||||
let points = match subtype.as_str() {
|
||||
"Line" => Some(nums(b"L")).filter(|l| l.len() == 4).map(|l| l.as_chunks::<2>().0.to_vec()).unwrap_or_default(),
|
||||
"PolyLine" | "Polygon" => nums(b"Vertices").as_chunks::<2>().0.to_vec(),
|
||||
"FreeText" => callout
|
||||
.as_ref()
|
||||
.and_then(|(line, _)| line.split_last())
|
||||
.map(|(_, lead)| lead.iter().map(|p| [p[0] as f32, p[1] as f32]).collect())
|
||||
.unwrap_or_default(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
let text_box = callout.map(|(_, t)| t.map(|v| v as f32));
|
||||
let irt = d.get(b"IRT").map(|o| o.as_ref().map_or_else(|| doc.resolve(o), |r| doc.get(final_ref(doc, r))));
|
||||
let in_reply_to = irt.and_then(|o| o.as_dict().cloned()).and_then(|p| text_value(doc, &p, b"NM"));
|
||||
let parent = d.get(b"IRT").and_then(Object::as_ref).and_then(|r| slots.get(&final_ref(doc, r)).copied());
|
||||
// A group is one page's, as Acrobat reads it: a subordinate whose primary is on
|
||||
// another page is a comment of its own (keep in step with
|
||||
// `pdfcraft_render::link_replies`).
|
||||
let grouped = d.name(b"RT") == Some(b"Group");
|
||||
let cross_page = grouped && parent.is_some_and(|(p, _)| p != page);
|
||||
let (parent, in_reply_to) = if cross_page { (None, None) } else { (parent, in_reply_to) };
|
||||
out.push(Summary {
|
||||
page,
|
||||
index,
|
||||
@@ -151,7 +233,7 @@ pub fn summaries(doc: &Document) -> Vec<Summary> {
|
||||
name: text_value(doc, d, b"NM"),
|
||||
in_reply_to,
|
||||
parent,
|
||||
grouped: d.name(b"RT") == Some(b"Group"),
|
||||
grouped,
|
||||
rect,
|
||||
color,
|
||||
// A reply that gives only `/StateModel` has the model's default state (ISO 32000-2
|
||||
@@ -167,6 +249,8 @@ pub fn summaries(doc: &Document) -> Vec<Summary> {
|
||||
fill_sign: is_fill_sign(doc, d),
|
||||
no_rotate: drawn_upright(doc, d),
|
||||
points,
|
||||
text_box,
|
||||
popup: popup_info(doc, entry.as_ref().map(|r| final_ref(doc, r)), d),
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -256,10 +340,15 @@ pub fn props(doc: &Document, page: usize, index: usize) -> Option<Props> {
|
||||
let direct = crate::draw::with_direct_values(doc, raw);
|
||||
let d = direct.as_ref();
|
||||
let subtype = String::from_utf8_lossy(d.name(b"Subtype")?).into_owned();
|
||||
let color = if subtype == "FreeText" { Some(appearance::parse_da(d).0) } else { drawn_color(d, b"C") };
|
||||
// A text box reports the colour and size it is drawn in (`/DA`, or `/DS` where it sets one).
|
||||
let style = (subtype == "FreeText").then(|| text_style::text_style(d, None));
|
||||
let color = match &style {
|
||||
Some(s) => Some(s.color),
|
||||
None => drawn_color(d, b"C"),
|
||||
};
|
||||
let width = matches!(subtype.as_str(), "Square" | "Circle" | "Line" | "Ink" | "Polygon" | "PolyLine" | "FreeText").then(|| {
|
||||
if subtype == "FreeText" {
|
||||
if !d.contains(b"BS") && !d.contains(b"Border") { 0.0 } else { appearance::border_width(d) }
|
||||
appearance::border_width(d)
|
||||
} else {
|
||||
d.get(b"BS").and_then(|b| b.as_dict()).and_then(|b| b.get(b"W")).and_then(|w| w.as_f64()).unwrap_or(1.0)
|
||||
}
|
||||
@@ -276,7 +365,7 @@ pub fn props(doc: &Document, page: usize, index: usize) -> Option<Props> {
|
||||
locked: annotation_flags(doc, d) & FLAG_LOCKED != 0,
|
||||
fillable: fillable(&subtype),
|
||||
fill: fill_of(d),
|
||||
font_size: (subtype == "FreeText").then(|| appearance::parse_da(d).1),
|
||||
font_size: style.map(|s| s.size),
|
||||
border_color: (subtype == "FreeText").then(|| appearance::da_border(d)).flatten(),
|
||||
border_shape: (subtype == "FreeText" && !d.contains(b"CL")).then(|| BorderShape::of(d)),
|
||||
fill_opacity: fillable(&subtype).then(|| appearance::part_opacity(d).fill),
|
||||
|
||||
@@ -29,9 +29,12 @@ mod types;
|
||||
|
||||
#[cfg(test)]
|
||||
use create::num_array;
|
||||
pub use create::{add_annotation, callout_attach, orient_image_stamp};
|
||||
pub use create::{
|
||||
CALLOUT_KNEE_LINE, CUSTOM_LINE_BAND, CUSTOM_LINE_TEXT, Side, add_annotation, callout_attach, callout_knee, callout_knee_on, callout_side,
|
||||
custom_stamp_size, orient_image_stamp,
|
||||
};
|
||||
pub use draw::{AppearanceCache, set_appearance, with_missing_appearances, with_missing_appearances_cached};
|
||||
pub use info::{Props, Summary, is_comment_subtype, props, set_info, summaries};
|
||||
pub use info::{PopupInfo, Props, Summary, is_comment_subtype, is_group_subordinate, props, set_info, summaries};
|
||||
#[cfg(test)]
|
||||
use lookup::{ANNOTS_ENTRIES_COPIED, PageWalk, annot_dict, annot_ref};
|
||||
use lookup::{annots, page_ref};
|
||||
@@ -41,9 +44,9 @@ pub use lookup::{
|
||||
pub use model3d::{Model3d, Model3dKind, model_3d, model_3d_annotations};
|
||||
pub(crate) use modify::n;
|
||||
pub use modify::{
|
||||
add_reply, add_text_replacement, deletable, delete_annotation, erase_ink, fillable, goes_with, lift_annotation, move_annotation,
|
||||
set_border_color, set_border_shape, set_contents, set_fill, set_font_size, set_locked, set_marked, set_part_opacity, set_points, set_rect,
|
||||
set_review_state, set_style, with_replies_and_popups,
|
||||
add_reply, add_text_replacement, deletable, delete_annotation, erase_ink, fillable, goes_with, lift_annotation, move_annotation, release_members,
|
||||
set_border_color, set_border_shape, set_contents, set_fill, set_font_size, set_locked, set_marked, set_part_opacity, set_points, set_popup,
|
||||
set_rect, set_review_state, set_style, with_replies_and_popups,
|
||||
};
|
||||
pub use threed::{Activation as Activation3d, MAX_MODEL_BYTES, ModelFormat, NewModel3d, PosterPicture, add_3d_model, check_model};
|
||||
pub use types::{
|
||||
@@ -53,6 +56,7 @@ pub use types::{
|
||||
|
||||
pub mod appearance;
|
||||
pub mod links;
|
||||
pub mod text_style;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
+344
-61
@@ -1,15 +1,17 @@
|
||||
use super::create::{
|
||||
add_annotation, base_dict, bounds, callout_attach, ending_draws, ending_pair, finite, grow, ink_bounds, normalize, num_array, polygon_rect,
|
||||
rect_for, rgb,
|
||||
CALLOUT_SLACK, add_annotation, base_dict, bounds, callout_attach, callout_knee, callout_side, ending_draws, ending_pair, finite, grow,
|
||||
ink_bounds, normalize, num_array, on_side, polygon_rect, rect_for, rgb,
|
||||
};
|
||||
use super::draw::{draw_appearance, redraw_or_restore, set_appearance};
|
||||
use super::info::{line_endings_of, text_value};
|
||||
use super::lookup::{annot_dict, annot_ref, annotation_flags, annots, page_ref, set_annots};
|
||||
use super::info::{is_comment_subtype, is_group_subordinate, line_endings_of, own_popup, popup_info, text_value};
|
||||
use super::lookup::{annot_dict, annot_ref, annotation_flags, annots, is_fill_sign, page_ref, set_annots};
|
||||
use super::text_style::{self, TextStyle};
|
||||
use super::types::{
|
||||
BorderShape, FLAG_HIDDEN, FLAG_LOCKED, FLAG_NO_ROTATE, FLAG_NO_ZOOM, FLAG_PRINT, LineEnding, Markup, Meta, NewAnnotation, ReviewState, Rgb,
|
||||
Shape, Style, StyleChange, TextReplacement,
|
||||
};
|
||||
use super::{AnnotError, Dict, Document, HashMap, HashSet, ObjRef, Object, PdfString, appearance};
|
||||
use pdfcraft_fonts::Std14;
|
||||
|
||||
/// A comment another program drew, whose text the standard fonts can't draw. Redrawing it would
|
||||
/// replace those characters with `?`, so the edit is refused before the dictionary changes.
|
||||
@@ -44,11 +46,36 @@ pub(crate) fn n(v: f64) -> String {
|
||||
|
||||
// ── edits ───────────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
/// A text box's rich text (§12.7.4.3): `/DS` (default style) and `/RC` (XHTML) written from its
|
||||
/// plain `/Contents`, `/DA` and `/Q`, so viewers that edit rich text show the same thing.
|
||||
/// [`rich_text_in`] for a text box whose `/DA` was just written (in Helvetica, as PdfCraft writes it).
|
||||
pub(crate) fn rich_text(d: &mut Dict) {
|
||||
let (color, size) = appearance::parse_da(d);
|
||||
rich_text_in(d, TextStyle { face: Std14::Helvetica, size, color });
|
||||
}
|
||||
|
||||
/// Give a text box the text `style`: `/DA` keeps the font resource it names (`/Helv` when it names
|
||||
/// none) and the border colour it gives (`RG`, [`appearance::da_border`]) with the new colour and
|
||||
/// size, and `/DS` and `/RC` carry the face, so the text keeps the face it is drawn in (ISO
|
||||
/// 32000-2 Table 177).
|
||||
fn restyle_text(d: &mut Dict, style: TextStyle) {
|
||||
let border = appearance::da_border(d);
|
||||
restyle_text_bordered(d, style, border);
|
||||
}
|
||||
|
||||
/// [`restyle_text`] with the border colour `border` (`None`: the text's).
|
||||
fn restyle_text_bordered(d: &mut Dict, style: TextStyle, border: Option<crate::Rgb>) {
|
||||
let font = text_style::da_font_name(d).unwrap_or_else(|| "Helv".into());
|
||||
let [r, g, b] = style.color.map(|x| x.clamp(0.0, 1.0));
|
||||
let stroke = border.map(|c| c.map(|x| x.clamp(0.0, 1.0))).map(|[r, g, b]| format!("{} {} {} RG ", n(r), n(g), n(b))).unwrap_or_default();
|
||||
d.set(b"DA".to_vec(), PdfString::literal(format!("{} {} {} rg {stroke}/{font} {} Tf", n(r), n(g), n(b), n(style.size)).into_bytes()));
|
||||
rich_text_in(d, TextStyle { color: [r, g, b], ..style });
|
||||
}
|
||||
|
||||
/// A text box's rich text (§12.7.4.3): `/DS` (default style) and `/RC` (XHTML) written from its
|
||||
/// plain `/Contents`, its text `style` and `/Q`, so viewers that edit rich text show the same thing.
|
||||
fn rich_text_in(d: &mut Dict, style: TextStyle) {
|
||||
let text = d.get(b"Contents").and_then(|c| c.as_string()).map(PdfString::to_text).unwrap_or_default();
|
||||
let (col, size) = appearance::parse_da(d);
|
||||
let TextStyle { face, size, color: col } = style;
|
||||
let (family, weight, slant) = text_style::css(face);
|
||||
let hex = format!(
|
||||
"#{:02X}{:02X}{:02X}",
|
||||
(col[0].clamp(0.0, 1.0) * 255.0).round() as u8,
|
||||
@@ -63,13 +90,15 @@ pub(crate) fn rich_text(d: &mut Dict) {
|
||||
let esc = |s: &str| s.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """);
|
||||
let body: String = text.split('\n').map(|line| format!("<p dir=\"ltr\">{}</p>", esc(line.trim_end_matches('\r')))).collect();
|
||||
let style = format!(
|
||||
"font-size:{}pt;text-align:{align};color:{hex};font-weight:normal;font-style:normal;font-family:Helvetica;font-stretch:normal",
|
||||
"font-size:{}pt;text-align:{align};color:{hex};font-weight:{weight};font-style:{slant};font-family:{family};font-stretch:normal",
|
||||
n(size)
|
||||
);
|
||||
let rc = format!(
|
||||
"<?xml version=\"1.0\"?><body xmlns=\"http://www.w3.org/1999/xhtml\" xmlns:xfa=\"http://www.xfa.org/schema/xfa-data/1.0/\" xfa:spec=\"2.0.2\" style=\"{style}\">{body}</body>"
|
||||
);
|
||||
d.set(b"DS".to_vec(), PdfString::text(&format!("font: Helvetica {}pt; text-align:{align}; color:{hex}", n(size))));
|
||||
// "font: Helvetica 12pt" for PdfCraft's own boxes; other faces add their slant and weight.
|
||||
let keywords = format!("{}{}", if slant == "normal" { "" } else { "italic " }, if weight == "normal" { "" } else { "bold " });
|
||||
d.set(b"DS".to_vec(), PdfString::text(&format!("font: {keywords}{family} {}pt; text-align:{align}; color:{hex}", n(size))));
|
||||
d.set(b"RC".to_vec(), PdfString::text(&rc));
|
||||
}
|
||||
|
||||
@@ -80,9 +109,14 @@ pub(crate) fn touch(d: &mut Dict, meta: &Meta) {
|
||||
}
|
||||
|
||||
/// Delete a comment together with its pop-up and its replies (and theirs), as Acrobat does.
|
||||
/// Refused while it, or a reply that would go with it, is locked.
|
||||
/// Refused while it, or a reply that would go with it, is locked. A member of a group (`/RT
|
||||
/// /Group`), its primary included, goes alone, as Acrobat deletes the member clicked and keeps the
|
||||
/// rest of its group, although ISO 32000-2 §12.5.6.2 lists deletion among the operations that act
|
||||
/// on the entire group; a subordinate left without its primary is a comment of its own and
|
||||
/// loses its `/IRT` ([`release_members`]). Replace Text's strikeout and caret are one comment and
|
||||
/// go together from either ([`own_deletion`]).
|
||||
pub fn delete_annotation(doc: &mut Document, page: usize, index: usize) -> Result<(), AnnotError> {
|
||||
deletable(doc, page, index)?;
|
||||
let index = deleted_index(doc, page, index)?;
|
||||
lift_annotation(doc, page, index)
|
||||
}
|
||||
|
||||
@@ -90,23 +124,44 @@ pub fn delete_annotation(doc: &mut Document, page: usize, index: usize) -> Resul
|
||||
/// changing anything: what a Delete command asks before it is offered. It is refused while the
|
||||
/// annotation is locked, or a reply that would go with it is.
|
||||
pub fn deletable(doc: &Document, page: usize, index: usize) -> Result<(), AnnotError> {
|
||||
deleted_index(doc, page, index).map(|_| ())
|
||||
}
|
||||
|
||||
/// [`deletable`], returning the index [`delete_annotation`] deletes from: the caret for Replace
|
||||
/// Text's strikeout, else `index`.
|
||||
fn deleted_index(doc: &Document, page: usize, index: usize) -> Result<usize, AnnotError> {
|
||||
let list = annots(doc, page_ref(doc, page)?);
|
||||
let target = list.get(index).ok_or(AnnotError::NoSuchAnnotation { page, index })?;
|
||||
let mut target = list.get(index).ok_or(AnnotError::NoSuchAnnotation { page, index })?;
|
||||
let mut index = index;
|
||||
if let Some(r) = target.as_ref() {
|
||||
unlocked(doc, r)?;
|
||||
}
|
||||
// Replace Text is one comment: its strikeout goes with its caret, the group's primary, and
|
||||
// the caret with it, as Acrobat deletes the pair from either.
|
||||
let caret = doc
|
||||
.resolve(target)
|
||||
.as_dict()
|
||||
.filter(|d| is_group_subordinate(d) && !own_deletion(doc, d))
|
||||
.and_then(|d| d.reference(b"IRT"))
|
||||
.and_then(|irt| list.iter().enumerate().find(|(_, e)| e.as_ref() == Some(irt)));
|
||||
if let Some((i, e)) = caret {
|
||||
(target, index) = (e, i);
|
||||
}
|
||||
let doomed = with_replies_and_popups(doc, &list, seed(doc, target));
|
||||
// A locked reply can't be deleted on its own, so it doesn't go with the comment or reply it
|
||||
// answers either. Pop-ups follow their comment.
|
||||
for (_, e) in list.iter().enumerate().filter(|(i, e)| *i != index && goes_with(e, &doomed)) {
|
||||
// answers either (ISO 32000-2 §12.5.3, Table 167: Locked); nor does the other half of Replace
|
||||
// Text. Pop-ups follow their comment.
|
||||
for (i, e) in list.iter().enumerate().filter(|(i, e)| (*i != index || caret.is_some()) && goes_with(doc, e, &doomed)) {
|
||||
let obj = doc.resolve(e);
|
||||
if let Some(d) = obj.as_dict().filter(|d| d.name(b"Subtype") != Some(b"Popup".as_slice()))
|
||||
&& annotation_flags(doc, d) & FLAG_LOCKED != 0
|
||||
{
|
||||
return Err(AnnotError::Invalid("a reply to it is locked".into()));
|
||||
let grouped = is_group_subordinate(d) || caret.is_some_and(|(c, _)| c == i);
|
||||
let what = if grouped { "a comment in its group is locked" } else { "a reply to it is locked" };
|
||||
return Err(AnnotError::Invalid(what.into()));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
Ok(index)
|
||||
}
|
||||
|
||||
/// Take the annotation at `(page, index)` out of its page with its pop-up and replies, as
|
||||
@@ -117,10 +172,42 @@ pub fn lift_annotation(doc: &mut Document, page: usize, index: usize) -> Result<
|
||||
let list = annots(doc, p);
|
||||
let target = list.get(index).ok_or(AnnotError::NoSuchAnnotation { page, index })?;
|
||||
let doomed = with_replies_and_popups(doc, &list, seed(doc, target));
|
||||
let kept: Vec<Object> = list.iter().enumerate().filter(|(i, e)| *i != index && !goes_with(e, &doomed)).map(|(_, e)| e.clone()).collect();
|
||||
let kept: Vec<Object> = list.iter().enumerate().filter(|(i, e)| *i != index && !goes_with(doc, e, &doomed)).map(|(_, e)| e.clone()).collect();
|
||||
let kept = release_members(doc, kept, &doomed)?;
|
||||
Ok(set_annots(doc, p, kept)?)
|
||||
}
|
||||
|
||||
/// The `/Annots` entries `kept` after deleting `going`, with every group subordinate that stays
|
||||
/// ([`own_deletion`]) but whose `/IRT` names an annotation going made a comment of its own: its
|
||||
/// `/IRT` is removed and its `/RT /Group` kept, as Acrobat does when a group's primary is deleted.
|
||||
/// A deleted primary then stays reachable from nothing, so a full save leaves its text out. An
|
||||
/// inline entry is rewritten in the list; a referenced one is updated in place. Each entry is
|
||||
/// read once, following no chain.
|
||||
pub fn release_members(doc: &mut Document, kept: Vec<Object>, going: &HashSet<ObjRef>) -> Result<Vec<Object>, pdfcraft_cos::CosError> {
|
||||
let orphaned = |d: &Dict| is_group_subordinate(d) && d.reference(b"IRT").is_some_and(|r| going.contains(&r));
|
||||
let mut out = Vec::with_capacity(kept.len());
|
||||
for e in kept {
|
||||
match e.as_ref() {
|
||||
Some(r) => {
|
||||
if doc.get(r).as_dict().is_some_and(orphaned) {
|
||||
doc.update_dict(r, |d| {
|
||||
d.remove(b"IRT");
|
||||
})?;
|
||||
}
|
||||
out.push(e);
|
||||
}
|
||||
None => match e {
|
||||
Object::Dict(mut d) if orphaned(&d) => {
|
||||
d.remove(b"IRT");
|
||||
out.push(Object::Dict(d));
|
||||
}
|
||||
other => out.push(other),
|
||||
},
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// What deleting the `/Annots` entry `target` starts from: its reference, or for an inline
|
||||
/// comment (which has none to collect) the pop-up it names, which still goes. The strikeout of a
|
||||
/// Replace Text proposal also takes the caret it is grouped under, so the two go together
|
||||
@@ -144,16 +231,35 @@ fn replaced_by(doc: &Document, strike: &Object) -> Option<ObjRef> {
|
||||
/// one of them, or it is written inline (a file can, though the standard asks for references) and
|
||||
/// replies to (`/IRT`) or pops up for (`/Parent`) one of them. An inline entry has no reference
|
||||
/// for the walk to collect, so it is matched here.
|
||||
pub fn goes_with(entry: &Object, going: &HashSet<ObjRef>) -> bool {
|
||||
pub fn goes_with(doc: &Document, entry: &Object, going: &HashSet<ObjRef>) -> bool {
|
||||
match entry.as_ref() {
|
||||
Some(r) => going.contains(&r),
|
||||
None => entry.as_dict().is_some_and(|d| [d.reference(b"IRT"), d.reference(b"Parent")].into_iter().flatten().any(|r| going.contains(&r))),
|
||||
None => entry.as_dict().is_some_and(|d| hangs_off(doc, d).into_iter().flatten().any(|r| going.contains(&r))),
|
||||
}
|
||||
}
|
||||
|
||||
/// What the annotation `d` goes with when it is deleted: what it replies to (`/IRT`) and what it
|
||||
/// pops up for (`/Parent`). A group subordinate (`/RT /Group`) is deleted on its own
|
||||
/// ([`own_deletion`]), so its `/IRT` doesn't count.
|
||||
fn hangs_off(doc: &Document, d: &Dict) -> [Option<ObjRef>; 2] {
|
||||
[d.reference(b"IRT").filter(|_| !own_deletion(doc, d)), d.reference(b"Parent")]
|
||||
}
|
||||
|
||||
/// Whether the annotation `d` stays when its group's primary is deleted: a group subordinate
|
||||
/// (`/RT /Group`) does, as Acrobat deletes only the member clicked, unless it is half of Replace
|
||||
/// Text, which Acrobat deletes as one comment: the strikeout (`/IT /StrikeOutTextEdit`) under its
|
||||
/// caret, or a caret under such a strikeout, as earlier PdfCraft builds wrote the pair.
|
||||
fn own_deletion(doc: &Document, d: &Dict) -> bool {
|
||||
let edit = |d: &Dict| d.name(b"IT") == Some(b"StrikeOutTextEdit".as_slice());
|
||||
let under_edit =
|
||||
|| d.name(b"Subtype") == Some(b"Caret".as_slice()) && d.reference(b"IRT").is_some_and(|r| doc.get(r).as_dict().is_some_and(edit));
|
||||
is_group_subordinate(d) && !edit(d) && !under_edit()
|
||||
}
|
||||
|
||||
/// `doomed` and what goes with it, as Acrobat deletes a comment: the entries of `list` (one or
|
||||
/// more pages' `/Annots`) that reply to (`/IRT`) or pop up for (`/Parent`) anything going, their
|
||||
/// own replies, and the pop-ups going annotations name (`/Popup`). An inline reply has no
|
||||
/// own replies, and the pop-ups going annotations name (`/Popup`). A group subordinate stays
|
||||
/// ([`own_deletion`]). An inline reply has no
|
||||
/// reference to collect, but the pop-up it names is. Each annotation is visited once, so a long or
|
||||
/// cyclic chain costs no more than its length. Filter a list with [`goes_with`], which also
|
||||
/// matches inline entries.
|
||||
@@ -165,7 +271,7 @@ pub fn with_replies_and_popups(doc: &Document, list: &[Object], doomed: impl Int
|
||||
// What goes with the annotation this entry hangs off: the entry, or for an inline one the
|
||||
// pop-up it names.
|
||||
let Some(goes) = e.as_ref().or_else(|| d.reference(b"Popup")) else { continue };
|
||||
for on in [d.reference(b"IRT"), d.reference(b"Parent")].into_iter().flatten() {
|
||||
for on in hangs_off(doc, d).into_iter().flatten() {
|
||||
hanging.entry(on).or_default().push(goes);
|
||||
}
|
||||
}
|
||||
@@ -186,15 +292,17 @@ pub fn with_replies_and_popups(doc: &Document, list: &[Object], doomed: impl Int
|
||||
/// around its text stays snug around the new text, centred where it was.
|
||||
pub fn set_contents(doc: &mut Document, page: usize, index: usize, text: &str, meta: &Meta) -> Result<(), AnnotError> {
|
||||
let (_, r) = annot_ref(doc, page, index)?;
|
||||
let d = annot_dict(doc, r);
|
||||
let free_text = d.name(b"Subtype") == Some(b"FreeText");
|
||||
let before = annot_dict(doc, r);
|
||||
let free_text = before.name(b"Subtype") == Some(b"FreeText");
|
||||
refuse_undrawable_thai(free_text, text)?;
|
||||
let snug = free_text && is_snug(&d);
|
||||
let snug = free_text && is_snug(&before);
|
||||
// The text keeps the look it is drawn with (`/DA`, or `/DS` where it sets one).
|
||||
let style = text_style::text_style(&before, text_style::dr_face(doc, &before));
|
||||
doc.update_dict(r, |d| {
|
||||
d.set(b"Contents".to_vec(), PdfString::text(text));
|
||||
// The rich-text version follows the new plain text (text boxes), or would contradict it.
|
||||
if free_text {
|
||||
rich_text(d);
|
||||
rich_text_in(d, style);
|
||||
} else {
|
||||
d.remove(b"RC");
|
||||
}
|
||||
@@ -227,7 +335,9 @@ pub fn set_contents(doc: &mut Document, page: usize, index: usize, text: &str, m
|
||||
fn fitted_box(doc: &Document, r: ObjRef, text: &str) -> Option<[f64; 4]> {
|
||||
let d = annot_dict(doc, r);
|
||||
let nums = |key: &[u8]| -> Option<Vec<f64>> { d.get(key)?.as_array()?.iter().map(|o| o.as_f64()).collect() };
|
||||
let (_, size) = appearance::parse_da(&d);
|
||||
// Measured in the face and size the text is drawn in (`/DA`, or `/DS` where it sets one).
|
||||
let TextStyle { face, size, .. } = text_style::text_style(&d, text_style::dr_face(doc, &d));
|
||||
let measure = |s: &str, size: f64| appearance::text_width_in(face, s, size);
|
||||
let pad = 2.0 + border_width_of(&d);
|
||||
let rect = nums(b"Rect").filter(|v| v.len() == 4 && v.iter().all(|x| x.is_finite()))?;
|
||||
let rect = [rect[0], rect[1], rect[2], rect[3]];
|
||||
@@ -245,10 +355,10 @@ fn fitted_box(doc: &Document, r: ObjRef, text: &str) -> Option<[f64; 4]> {
|
||||
w
|
||||
} else {
|
||||
// No usable old width: fall back to the creation-time width (at most 300 pt).
|
||||
let longest = text.lines().map(|l| appearance::text_width(l, size)).fold(0.0, f64::max);
|
||||
let longest = text.lines().map(|l| measure(l, size)).fold(0.0, f64::max);
|
||||
(longest + 2.0 * pad + 4.0).clamp(40.0, 300.0)
|
||||
};
|
||||
let height = appearance::text_lines_height(&appearance::wrap(text, size, (w - 2.0 * pad).max(1.0)), size);
|
||||
let height = appearance::text_lines_height(&pdfcraft_fonts::wrap_with(text, size, (w - 2.0 * pad).max(1.0), measure), size);
|
||||
Some([x0, top - height - 2.0 * pad - 2.0, x0 + w, top])
|
||||
}
|
||||
|
||||
@@ -328,6 +438,83 @@ pub(crate) fn unlocked(doc: &Document, r: ObjRef) -> Result<(), AnnotError> {
|
||||
if flags(doc, r) & FLAG_LOCKED != 0 { Err(AnnotError::Invalid("the comment is locked".into())) } else { Ok(()) }
|
||||
}
|
||||
|
||||
/// Open, close or move a comment's pop-up window (Acrobat: double-click a comment to open it,
|
||||
/// drag its title bar to move it). `rect` is the pop-up's new `/Rect` in user space; `open` its
|
||||
/// `/Open`. A comment without a `/Popup` gets one, placed to the right of the comment as new
|
||||
/// notes get theirs. A text box, a Fill & Sign mark or a reply has no pop-up of its own (a reply
|
||||
/// shows in its parent's). The lock does not apply: the window's place and state are not the
|
||||
/// comment. The modification date is left alone: nothing of the comment changed.
|
||||
pub fn set_popup(doc: &mut Document, page: usize, index: usize, rect: Option<[f64; 4]>, open: Option<bool>, meta: &Meta) -> Result<(), AnnotError> {
|
||||
let (p, r) = annot_ref(doc, page, index)?;
|
||||
let d = annot_dict(doc, r);
|
||||
let subtype = String::from_utf8_lossy(d.name(b"Subtype").unwrap_or_default()).into_owned();
|
||||
if !is_comment_subtype(&subtype) || subtype == "FreeText" || is_fill_sign(doc, &d) || d.contains(b"IRT") {
|
||||
return Err(AnnotError::Invalid(format!("{subtype} comments have no pop-up of their own")));
|
||||
}
|
||||
let rect = match rect {
|
||||
Some(rect) => {
|
||||
let rect = normalize(rect);
|
||||
if !finite(&rect) || rect[2] - rect[0] < 1.0 || rect[3] - rect[1] < 1.0 {
|
||||
return Err(AnnotError::Invalid("invalid pop-up rectangle".into()));
|
||||
}
|
||||
Some(rect)
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let _ = meta;
|
||||
// Where a new pop-up goes: to the right of the comment, as new notes' do.
|
||||
let own: Vec<f64> = d
|
||||
.get(b"Rect")
|
||||
.map(|o| doc.resolve(o))
|
||||
.and_then(|o| o.as_array().cloned())
|
||||
.unwrap_or_default()
|
||||
.iter()
|
||||
.filter_map(|v| doc.resolve(v).as_f64())
|
||||
.collect();
|
||||
let beside = match own[..] {
|
||||
[_, _, x1, y1] if finite(&own) => [x1 + 10.0, y1 - 120.0, x1 + 210.0, y1],
|
||||
_ => [0.0, 0.0, 200.0, 120.0],
|
||||
};
|
||||
// Only a pop-up that is this comment's: `/Popup` naming another annotation (or a pop-up
|
||||
// whose `/Parent` is another comment) would move or open that one, so it gets its own.
|
||||
match own_popup(doc, Some(r), &d) {
|
||||
Some(pr) => {
|
||||
// One without a `/Rect` of four numbers reads as no pop-up (`summaries`), so it gets
|
||||
// the new pop-up's place: opening it then shows it.
|
||||
let rect = rect.or_else(|| popup_info(doc, Some(r), &d).is_none().then_some(beside));
|
||||
doc.update_dict(pr, |p| {
|
||||
if let Some(rect) = rect {
|
||||
p.set(b"Rect".to_vec(), num_array(&rect));
|
||||
}
|
||||
if let Some(open) = open {
|
||||
p.set(b"Open".to_vec(), Object::Bool(open));
|
||||
}
|
||||
})?
|
||||
}
|
||||
None => {
|
||||
let mut pd = Dict::new();
|
||||
pd.set(b"Type".to_vec(), Object::name("Annot"));
|
||||
pd.set(b"Subtype".to_vec(), Object::name("Popup"));
|
||||
pd.set(b"Rect".to_vec(), num_array(&rect.unwrap_or(beside)));
|
||||
pd.set(b"Parent".to_vec(), Object::Ref(r));
|
||||
pd.set(b"Open".to_vec(), Object::Bool(open.unwrap_or(false)));
|
||||
pd.set(b"F".to_vec(), Object::Int(FLAG_PRINT | FLAG_NO_ZOOM | FLAG_NO_ROTATE));
|
||||
let pref = doc.add(Object::Dict(pd));
|
||||
doc.update_dict(r, |d| d.set(b"Popup".to_vec(), Object::Ref(pref)))?;
|
||||
let mut list = annots(doc, p);
|
||||
list.push(Object::Ref(pref));
|
||||
set_annots(doc, p, list)?;
|
||||
}
|
||||
}
|
||||
// A note's own `/Open` says the same thing to viewers that read it there (§12.5.6.4).
|
||||
if let Some(open) = open
|
||||
&& (subtype == "Text" || d.contains(b"Open"))
|
||||
{
|
||||
doc.update_dict(r, |d| d.set(b"Open".to_vec(), Object::Bool(open)))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Lock or unlock a comment (the Locked flag). A locked comment can't be moved, resized,
|
||||
/// restyled or deleted; its text and replies stay editable, as in Acrobat.
|
||||
pub fn set_locked(doc: &mut Document, page: usize, index: usize, locked: bool) -> Result<(), AnnotError> {
|
||||
@@ -612,10 +799,12 @@ pub fn set_border_shape(doc: &mut Document, page: usize, index: usize, shape: Bo
|
||||
/// At most this many points reshape a comment (a drawn polygon has a handful).
|
||||
const MAX_POINTS: usize = 100_000;
|
||||
|
||||
/// Reshape a line, connected lines, a polygon or a cloud: its points in user space (a line's two
|
||||
/// ends, the others' corners), as dragging the comment's handles sets them. `/Rect` follows the
|
||||
/// points with room for the line's width and endings, as when the comment was drawn, and the
|
||||
/// appearance is redrawn. A measurement keeps the points it measured.
|
||||
/// Reshape a line, connected lines, a polygon, a cloud or a callout: its points in user space (a
|
||||
/// line's two ends, the others' corners; a callout's arrow point and, if it has one, its knee), as
|
||||
/// dragging the comment's handles sets them. `/Rect` follows the points with room for the line's
|
||||
/// width and endings, as when the comment was drawn, and the appearance is redrawn. A callout's
|
||||
/// text box stays where it is and its leader line re-attaches. A measurement keeps the points it
|
||||
/// measured.
|
||||
pub fn set_points(doc: &mut Document, page: usize, index: usize, points: &[[f64; 2]], meta: &Meta) -> Result<(), AnnotError> {
|
||||
let (_, r) = annot_ref(doc, page, index)?;
|
||||
unlocked(doc, r)?;
|
||||
@@ -626,6 +815,15 @@ pub fn set_points(doc: &mut Document, page: usize, index: usize, points: &[[f64;
|
||||
if points.len() > MAX_POINTS {
|
||||
return Err(AnnotError::Invalid(format!("at most {MAX_POINTS} points")));
|
||||
}
|
||||
if d.name(b"Subtype") == Some(b"FreeText") && callout_line(doc, &d).is_some() {
|
||||
// A callout's points: its arrow point, then optionally its knee (a four-number `/CL`
|
||||
// gains one; ISO 32000-2 Table 177 allows both forms). The arrow point alone keeps a knee.
|
||||
if !matches!(points.len(), 1 | 2) || !finite(&points.concat()) {
|
||||
return Err(AnnotError::Invalid("a callout has an arrow point and, optionally, a knee".into()));
|
||||
}
|
||||
let text_box = callout_text_box(doc, &d).ok_or_else(|| AnnotError::Invalid("the callout's text box (/RD) can't be read".into()))?;
|
||||
return place_text_box(doc, r, text_box, Some(points), meta, false);
|
||||
}
|
||||
// The width the appearance draws with (`/BS`, else `/Border`), so the room is the drawn stroke's.
|
||||
let style = Style { width: appearance::border_width(&d), ..Style::default() };
|
||||
let ends = line_endings_of(&d).unwrap_or_default();
|
||||
@@ -700,6 +898,43 @@ fn resize_ink(doc: &mut Document, r: ObjRef, rect: [f64; 4], meta: &Meta) -> Res
|
||||
/// leader line re-attaches and `/Rect` grows to hold it, and the appearance is redrawn
|
||||
/// (`new_text`: for changed contents, see [`set_appearance`] and `draw_appearance`).
|
||||
fn apply_text_box(doc: &mut Document, r: ObjRef, rect: [f64; 4], meta: &Meta, new_text: bool) -> Result<(), AnnotError> {
|
||||
place_text_box(doc, r, rect, None, meta, new_text)
|
||||
}
|
||||
|
||||
/// A callout's leader line (`/CL`, ISO 32000-2 Table 177): four numbers (start, end) or six
|
||||
/// (start, knee, end), as points in user space. `None` when the annotation has no usable `/CL`.
|
||||
pub(crate) fn callout_line(doc: &Document, d: &Dict) -> Option<Vec<[f64; 2]>> {
|
||||
// All or nothing: a non-number would shift every later number into the wrong point.
|
||||
let l: Vec<f64> = doc.resolve(d.get(b"CL")?).as_array()?.iter().map(|x| doc.resolve(x).as_f64()).collect::<Option<_>>()?;
|
||||
(matches!(l.len(), 4 | 6) && finite(&l)).then(|| l.as_chunks::<2>().0.to_vec())
|
||||
}
|
||||
|
||||
/// A callout's text box: `/Rect` inset by `/RD` (ISO 32000-2 Table 177). `None` without both.
|
||||
pub(crate) fn callout_text_box(doc: &Document, d: &Dict) -> Option<[f64; 4]> {
|
||||
let nums = |key: &[u8]| -> Option<Vec<f64>> { doc.resolve(d.get(key)?).as_array()?.iter().map(|o| doc.resolve(o).as_f64()).collect() };
|
||||
let r = nums(b"Rect").filter(|v| v.len() == 4 && finite(v))?;
|
||||
let rd = nums(b"RD").filter(|v| v.len() == 4 && finite(v) && v.iter().all(|x| *x >= 0.0))?;
|
||||
let r = normalize([r[0], r[1], r[2], r[3]]);
|
||||
let tb = [r[0] + rd[0], r[1] + rd[1], r[2] - rd[2], r[3] - rd[3]];
|
||||
(tb[2] - tb[0] >= 1.0 && tb[3] - tb[1] >= 1.0).then_some(tb)
|
||||
}
|
||||
|
||||
/// As [`apply_text_box`]. For a callout, `lead` (its arrow point and optional knee, dragged by
|
||||
/// their handles) replaces the leader line's own points. The arrow point never moves with the box
|
||||
/// ("The text box moves around a stationary anchor point—the arrow on the end-point line",
|
||||
/// Acrobat DC Help, 11/28/2019, p. 357), and the line follows the box as Acrobat Pro DC (a 2021
|
||||
/// Continuous release) was seen to:
|
||||
/// - the box moved without changing size: the knee and the end move with it (also seen in
|
||||
/// Acrobat Pro 2026.002.22031);
|
||||
/// - the box resized with the side the line meets left where it was (the end still on it): the
|
||||
/// line doesn't change;
|
||||
/// - otherwise (that side moved): the line meets the middle of that side, the knee
|
||||
/// [`CALLOUT_KNEE_LINE`] out from it ([`callout_knee_on`]). Acrobat also moves the box next to
|
||||
/// the arrow point then; PdfCraft leaves the box where it was put.
|
||||
///
|
||||
/// With `lead`, the end stays where it is while it is on the side facing the knee (dragging the
|
||||
/// knee or the arrow point leaves it in Acrobat), and otherwise meets the middle of that side.
|
||||
fn place_text_box(doc: &mut Document, r: ObjRef, rect: [f64; 4], lead: Option<&[[f64; 2]]>, meta: &Meta, new_text: bool) -> Result<(), AnnotError> {
|
||||
let rect = normalize(rect);
|
||||
if !finite(&rect) || rect[2] - rect[0] < 1.0 || rect[3] - rect[1] < 1.0 {
|
||||
return Err(AnnotError::Invalid("invalid rectangle (too small)".into()));
|
||||
@@ -708,17 +943,62 @@ fn apply_text_box(doc: &mut Document, r: ObjRef, rect: [f64; 4], meta: &Meta, ne
|
||||
if !new_text {
|
||||
refuse_foreign_text(doc, &d)?;
|
||||
}
|
||||
// A callout's rectangle is its text box: the leader line re-attaches and `/Rect` grows to hold it.
|
||||
let callout = d.get(b"CL").and_then(|o| o.as_array()).map(|a| a.iter().filter_map(|x| x.as_f64()).collect::<Vec<f64>>()).filter(|l| l.len() == 6);
|
||||
let (outer, cl) = match callout {
|
||||
Some(mut l) => {
|
||||
let attach = callout_attach(rect, [l[2], l[3]]);
|
||||
(l[4], l[5]) = (attach[0], attach[1]);
|
||||
let pad = border_width_of(&d) / 2.0 + appearance::arrow_size(border_width_of(&d)) + 1.0;
|
||||
let lead = grow(bounds([[l[0], l[1]], [l[2], l[3]]].into_iter()).unwrap_or_default(), pad);
|
||||
([rect[0].min(lead[0]), rect[1].min(lead[1]), rect[2].max(lead[2]), rect[3].max(lead[3])], Some(l))
|
||||
// A callout's rectangle is its text box: `/Rect` grows to hold the leader line. A four-number
|
||||
// `/CL` (no knee) stays four numbers unless `lead` adds a knee.
|
||||
let old_line = callout_line(doc, &d);
|
||||
let old_box = callout_text_box(doc, &d);
|
||||
let old_end = old_line.as_deref().and_then(<[[f64; 2]]>::last).copied();
|
||||
// An arrow point alone moves the arrow: a knee the line has stays where it is.
|
||||
let kept: [[f64; 2]; 2];
|
||||
let lead = match (lead, old_line.as_deref()) {
|
||||
(Some([point]), Some([_, knee, _])) => {
|
||||
kept = [*point, *knee];
|
||||
Some(&kept[..])
|
||||
}
|
||||
None => (rect, None),
|
||||
_ => lead,
|
||||
};
|
||||
let line: Option<Vec<[f64; 2]>> = match (lead, old_line.as_deref()) {
|
||||
(Some(lead @ [.., toward]), _) => {
|
||||
let side = callout_side(rect, *toward);
|
||||
let end = old_end.filter(|e| on_side(rect, side, *e)).unwrap_or_else(|| callout_attach(rect, *toward));
|
||||
Some(lead.iter().copied().chain([end]).collect())
|
||||
}
|
||||
(Some(_), _) => None,
|
||||
(None, Some(old @ [start, .., end])) => {
|
||||
let (start, end) = (*start, *end);
|
||||
let knee = old.get(1).filter(|_| old.len() == 3).copied();
|
||||
let toward = knee.unwrap_or(start);
|
||||
Some(match old_box {
|
||||
// Moved, not resized: the knee and the end come along.
|
||||
Some(b)
|
||||
if ((rect[2] - rect[0]) - (b[2] - b[0])).abs() < CALLOUT_SLACK && ((rect[3] - rect[1]) - (b[3] - b[1])).abs() < CALLOUT_SLACK =>
|
||||
{
|
||||
let (dx, dy) = (rect[0] - b[0], rect[1] - b[1]);
|
||||
let shift = |p: [f64; 2]| [p[0] + dx, p[1] + dy];
|
||||
[start].into_iter().chain(knee.map(shift)).chain([shift(end)]).collect()
|
||||
}
|
||||
// Resized, the side the line meets still under its end: nothing changes.
|
||||
Some(b) if on_side(rect, callout_side(b, toward), end) => old.to_vec(),
|
||||
// That side moved: laid out again as a new callout is, from the side facing the
|
||||
// arrow point (the box may now be on the knee's other side).
|
||||
Some(_) => {
|
||||
let new_knee = callout_knee(rect, start);
|
||||
let end = callout_attach(rect, new_knee);
|
||||
[start].into_iter().chain(knee.map(|_| new_knee)).chain([end]).collect()
|
||||
}
|
||||
None => [start].into_iter().chain(knee).chain([callout_attach(rect, toward)]).collect(),
|
||||
})
|
||||
}
|
||||
(None, _) => None,
|
||||
};
|
||||
let (outer, cl) = match line.as_deref() {
|
||||
Some(line @ [lead @ .., _]) => {
|
||||
// The end is on the box, so only the arrow point and the knee need room around them.
|
||||
let pad = border_width_of(&d) / 2.0 + appearance::arrow_size(border_width_of(&d)) + 1.0;
|
||||
let lead_box = grow(bounds(lead.iter().copied()).unwrap_or_default(), pad);
|
||||
([rect[0].min(lead_box[0]), rect[1].min(lead_box[1]), rect[2].max(lead_box[2]), rect[3].max(lead_box[3])], Some(line.concat()))
|
||||
}
|
||||
_ => (rect, None),
|
||||
};
|
||||
let (shape, width) = (BorderShape::of(&d), border_width_of(&d));
|
||||
let free_text = d.name(b"Subtype") == Some(b"FreeText");
|
||||
@@ -749,8 +1029,9 @@ fn apply_text_box(doc: &mut Document, r: ObjRef, rect: [f64; 4], meta: &Meta, ne
|
||||
}
|
||||
}
|
||||
|
||||
/// The border width as the appearance draws it: `/BS /W`, else the third number of `/Border`
|
||||
/// (another app's), else 1.
|
||||
/// The width a comment's border is drawn with ([`appearance::border_width`]: `/BS /W`, else
|
||||
/// `/Border`'s third number, 1 when neither gives a usable one), so what is sized around it
|
||||
/// leaves room for what is drawn.
|
||||
fn border_width_of(d: &Dict) -> f64 {
|
||||
appearance::border_width(d)
|
||||
}
|
||||
@@ -857,6 +1138,8 @@ fn style_one(doc: &mut Document, r: ObjRef, change: StyleChange, meta: &Meta) ->
|
||||
}
|
||||
refuse_foreign_text(doc, &d)?;
|
||||
let free_text = subtype == "FreeText";
|
||||
// The face and size the text is drawn in, which the new colour keeps.
|
||||
let drawn = text_style::text_style(&d, text_style::dr_face(doc, &d));
|
||||
// Typewriter text has no box of its own: a border goes around its text, so the box grows
|
||||
// (or shrinks) by the change on every side and the text keeps its place and its lines.
|
||||
// So does a text box inside an oval or a circle, which goes around it again.
|
||||
@@ -878,9 +1161,7 @@ fn style_one(doc: &mut Document, r: ObjRef, change: StyleChange, meta: &Meta) ->
|
||||
}
|
||||
if let Some(c) = color {
|
||||
if free_text {
|
||||
let (_, size) = appearance::parse_da(d);
|
||||
d.set(b"DA".to_vec(), free_text_da(c, appearance::da_border(d), size));
|
||||
rich_text(d);
|
||||
restyle_text(d, TextStyle { color: c, ..drawn });
|
||||
} else {
|
||||
d.set(b"C".to_vec(), rgb(c));
|
||||
}
|
||||
@@ -939,11 +1220,11 @@ pub fn set_border_color(doc: &mut Document, page: usize, index: usize, color: Op
|
||||
return Err(AnnotError::Invalid("invalid colour".into()));
|
||||
}
|
||||
refuse_foreign_text(doc, &d)?;
|
||||
// The face, size and colour the text is drawn in, which the border colour keeps.
|
||||
let drawn = text_style::text_style(&d, text_style::dr_face(doc, &d));
|
||||
let before = d;
|
||||
doc.update_dict(r, |d| {
|
||||
let (text, size) = appearance::parse_da(d);
|
||||
d.set(b"DA".to_vec(), free_text_da(text, color, size));
|
||||
rich_text(d);
|
||||
restyle_text_bordered(d, drawn, color);
|
||||
touch(d, meta);
|
||||
})?;
|
||||
redraw_or_restore(doc, r, before)
|
||||
@@ -964,11 +1245,11 @@ pub fn set_font_size(doc: &mut Document, page: usize, index: usize, size: f64, m
|
||||
}
|
||||
refuse_foreign_text(doc, &d)?;
|
||||
let snug = is_snug(&d);
|
||||
// The face and colour the text is drawn in, which the new size keeps.
|
||||
let drawn = text_style::text_style(&d, text_style::dr_face(doc, &d));
|
||||
let before = d;
|
||||
doc.update_dict(r, |d| {
|
||||
let (col, _) = appearance::parse_da(d);
|
||||
d.set(b"DA".to_vec(), free_text_da(col, appearance::da_border(d), size));
|
||||
rich_text(d);
|
||||
restyle_text(d, TextStyle { size, ..drawn });
|
||||
touch(d, meta);
|
||||
})?;
|
||||
let text = text_value(doc, &annot_dict(doc, r), b"Contents").unwrap_or_default();
|
||||
@@ -1120,16 +1401,17 @@ fn pair_points(d: &Dict, key: &[u8]) -> Option<Vec<[f64; 2]>> {
|
||||
}
|
||||
|
||||
/// Replace Text (Acrobat's proposal): strike out `quads` and add a caret at the end of the
|
||||
/// struck text holding `replacement`, the two grouped so they move, list and delete as one.
|
||||
/// Returns the strikeout's index.
|
||||
/// struck text holding `replacement`, grouped (ISO 32000-2 §12.5.6.2) so they list, select and
|
||||
/// delete as one. Returns the caret's index, the group's comment.
|
||||
///
|
||||
/// The caret is the group's primary (`/IT /Replace`) and the strikeout its subordinate (`/IRT` to
|
||||
/// the caret, `/RT /Group`, `/IT /StrikeOutTextEdit`): a group's text is read from its primary,
|
||||
/// and the subordinates' `Contents` are ignored (ISO 32000-2 §12.5.6.2), so the replacement has
|
||||
/// to be on the primary.
|
||||
/// The caret is the group's primary: it holds `replacement` in `/Contents` and has `/IT
|
||||
/// /Replace`. The strikeout is its subordinate (`/IRT` to the caret, `/RT /Group`, `/IT
|
||||
/// /StrikeOutTextEdit`) with no `/Contents`, since a reader ignores a subordinate's text.
|
||||
/// Groups written before this the other way round (the strikeout primary, the text only on
|
||||
/// the caret) still list their text: see `pdfcraft_render::fill_group_text`.
|
||||
///
|
||||
/// The two annotations need their own `/NM`: XFDF names a reply by the `/NM` of what it replies
|
||||
/// to, so one id for both writes `inreplyto` equal to the caret's own `name`, and a reader that
|
||||
/// to, so one id for both writes `inreplyto` equal to the strikeout's own `name`, and a reader that
|
||||
/// resolves names (Acrobat, and our own importer) loses the pair. `caret_meta` is a second id
|
||||
/// from the caller, so the edit stays deterministic.
|
||||
pub fn add_text_replacement(doc: &mut Document, replacement: TextReplacement<'_>) -> Result<usize, AnnotError> {
|
||||
@@ -1168,8 +1450,9 @@ pub fn add_text_replacement(doc: &mut Document, replacement: TextReplacement<'_>
|
||||
d.set(b"IT".to_vec(), Object::name("StrikeOutTextEdit"));
|
||||
d.set(b"IRT".to_vec(), Object::Ref(cr));
|
||||
d.set(b"RT".to_vec(), Object::name("Group"));
|
||||
d.remove(b"Contents");
|
||||
})?;
|
||||
Ok(s)
|
||||
Ok(c)
|
||||
}
|
||||
|
||||
/// The Eraser (Draw tools): remove the parts of drawing `(page, index)` within `radius` points
|
||||
|
||||
+1217
-24
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,480 @@
|
||||
//! The face, size and colour a text box's text is drawn in when PdfCraft draws its appearance:
|
||||
//! `/DA` (ISO 32000-2 Table 177; the font named there is looked up in the interactive form's
|
||||
//! `/DR` font resources, §12.7.4.3) and `/DS`, the default style string (Table 177), which is
|
||||
//! read for its CSS `font`, `font-family`, `font-size`, `font-weight`, `font-style` and `color`.
|
||||
//!
|
||||
//! Only the twelve standard text faces are drawn (Helvetica, Times and Courier, each regular,
|
||||
//! bold, italic and bold italic, in WinAnsiEncoding): a font that isn't one of them is drawn in
|
||||
//! Helvetica, as before. Symbol and ZapfDingbats are not text faces for this purpose.
|
||||
|
||||
use pdfcraft_cos::{Dict, Document, Object};
|
||||
use pdfcraft_fonts::{Std14, Std14Match as Match};
|
||||
|
||||
use crate::Rgb;
|
||||
use crate::appearance::parse_da;
|
||||
|
||||
/// `/DS` past this many bytes is read only this far (a style string is a line or two).
|
||||
const MAX_DS: usize = 4096;
|
||||
|
||||
/// Font sizes a text box is drawn at, as for `/DA`.
|
||||
const MAX_SIZE: f64 = 400.0;
|
||||
|
||||
/// How a text box's text is drawn.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct TextStyle {
|
||||
pub face: Std14,
|
||||
pub size: f64,
|
||||
pub color: Rgb,
|
||||
}
|
||||
|
||||
/// The style of `d`'s text: `/DA`, with what `/DS` sets taking its place. `dr_face` is the face
|
||||
/// the `/DA` font resource names in the form's `/DR` ([`dr_face`]); `None` when it isn't there,
|
||||
/// and the common resource names (`/Helv`, `/Cour`, `/TiRo`, …) are read instead.
|
||||
pub fn text_style(d: &Dict, dr_face: Option<Std14>) -> TextStyle {
|
||||
let (da_color, da_size) = parse_da(d);
|
||||
let da_face = dr_face.or_else(|| da_font_name(d).as_deref().and_then(resource_face)).unwrap_or(Std14::Helvetica);
|
||||
let mut style = TextStyle { face: da_face, size: da_size, color: da_color };
|
||||
let Some(ds) = d.get(b"DS").and_then(Object::as_string).map(|s| s.to_text()) else { return style };
|
||||
let ds = parse_ds(&ds);
|
||||
if let Some(size) = ds.size {
|
||||
style.size = size;
|
||||
}
|
||||
// `/DS` colours are 8-bit (`#RRGGBB`): one that rounds to the same as `/DA`'s keeps `/DA`'s.
|
||||
if let Some(color) = ds.color
|
||||
&& bytes(color) != bytes(da_color)
|
||||
{
|
||||
style.color = color;
|
||||
}
|
||||
let base = ds.face.unwrap_or(style.face);
|
||||
style.face = styled(base, ds.bold.unwrap_or(is_bold(base)), ds.italic.unwrap_or(is_italic(base)));
|
||||
style
|
||||
}
|
||||
|
||||
/// The face the `/DA` font of `d` names in the document's `/AcroForm /DR /Font` (§12.7.4.3):
|
||||
/// `Some` when that resource is there — the standard text face its `/BaseFont` names, or
|
||||
/// Helvetica for any other font — and `None` when it isn't.
|
||||
pub fn dr_face(doc: &Document, d: &Dict) -> Option<Std14> {
|
||||
let name = da_font_name(d)?;
|
||||
let root = doc.trailer().get(b"Root").map(|r| doc.resolve(r))?;
|
||||
let form = root.as_dict()?.get(b"AcroForm").map(|f| doc.resolve(f))?;
|
||||
let dr = form.as_dict()?.get(b"DR").map(|r| doc.resolve(r))?;
|
||||
let fonts = dr.as_dict()?.get(b"Font").map(|f| doc.resolve(f))?;
|
||||
let font = fonts.as_dict()?.get(name.as_bytes()).map(|f| doc.resolve(f))?;
|
||||
let font = font.as_dict()?;
|
||||
let base = font.name(b"BaseFont").map(String::from_utf8_lossy);
|
||||
Some(base.as_deref().and_then(base_font_face).unwrap_or(Std14::Helvetica))
|
||||
}
|
||||
|
||||
/// The font resource name of the last `Tf` in `/DA` (without the slash). `Tf` takes a name and
|
||||
/// a size; a name given without its size (`/TiRo Tf`) is still read, and the size then falls back
|
||||
/// as [`parse_da`] says.
|
||||
pub fn da_font_name(d: &Dict) -> Option<String> {
|
||||
let da = d.get(b"DA").and_then(Object::as_string)?;
|
||||
let da = String::from_utf8_lossy(&da.bytes);
|
||||
let toks: Vec<&str> = da.split_whitespace().collect();
|
||||
let tf = toks.iter().rposition(|t| *t == "Tf")?;
|
||||
let name = match toks.get(..tf)? {
|
||||
[.., name, size] if !size.starts_with('/') => name,
|
||||
[.., name] => name,
|
||||
[] => return None,
|
||||
};
|
||||
let name = name.strip_prefix('/')?;
|
||||
(!name.is_empty()).then(|| name.to_string())
|
||||
}
|
||||
|
||||
/// The face a font resource name stands for: the names PDF writers commonly give the standard
|
||||
/// fonts in `/DR` (`Helv`, `HeBo`, `Cour`, `TiRo`, …), or a standard face's own name.
|
||||
pub fn resource_face(name: &str) -> Option<Std14> {
|
||||
Some(match name {
|
||||
"Helv" => Std14::Helvetica,
|
||||
"HeBo" => Std14::HelveticaBold,
|
||||
"HeOb" | "HeIt" => Std14::HelveticaOblique,
|
||||
"HeBO" | "HeBI" => Std14::HelveticaBoldOblique,
|
||||
"Cour" => Std14::Courier,
|
||||
"CoBo" => Std14::CourierBold,
|
||||
"CoOb" | "CoIt" => Std14::CourierOblique,
|
||||
"CoBO" | "CoBI" => Std14::CourierBoldOblique,
|
||||
"TiRo" => Std14::TimesRoman,
|
||||
"TiBo" => Std14::TimesBold,
|
||||
"TiIt" => Std14::TimesItalic,
|
||||
"TiBI" => Std14::TimesBoldItalic,
|
||||
_ => return base_font_face(name),
|
||||
})
|
||||
}
|
||||
|
||||
/// The standard text face a `/BaseFont` (or family) name asks for: the spec's names and their
|
||||
/// usual aliases (Arial, Times New Roman, Courier New), not a guess from a family hint.
|
||||
fn base_font_face(name: &str) -> Option<Std14> {
|
||||
match Std14::recognise(name)? {
|
||||
(Std14::Symbol | Std14::ZapfDingbats, _) | (_, Match::FamilyHint) => None,
|
||||
(face, Match::Alias) => Some(face),
|
||||
}
|
||||
}
|
||||
|
||||
/// `CSS` family names: the generic ones, else a standard face's name or alias.
|
||||
fn family_face(name: &str) -> Option<Std14> {
|
||||
let name = name.trim().trim_matches(|c| c == '"' || c == '\'').trim();
|
||||
match name.to_ascii_lowercase().as_str() {
|
||||
"serif" => Some(Std14::TimesRoman),
|
||||
"monospace" => Some(Std14::Courier),
|
||||
"sans-serif" => Some(Std14::Helvetica),
|
||||
_ => base_font_face(name),
|
||||
}
|
||||
}
|
||||
|
||||
fn is_bold(f: Std14) -> bool {
|
||||
matches!(
|
||||
f,
|
||||
Std14::HelveticaBold
|
||||
| Std14::HelveticaBoldOblique
|
||||
| Std14::TimesBold
|
||||
| Std14::TimesBoldItalic
|
||||
| Std14::CourierBold
|
||||
| Std14::CourierBoldOblique
|
||||
)
|
||||
}
|
||||
|
||||
fn is_italic(f: Std14) -> bool {
|
||||
matches!(
|
||||
f,
|
||||
Std14::HelveticaOblique
|
||||
| Std14::HelveticaBoldOblique
|
||||
| Std14::TimesItalic
|
||||
| Std14::TimesBoldItalic
|
||||
| Std14::CourierOblique
|
||||
| Std14::CourierBoldOblique
|
||||
)
|
||||
}
|
||||
|
||||
/// `base`'s family in the given weight and slant.
|
||||
fn styled(base: Std14, bold: bool, italic: bool) -> Std14 {
|
||||
use Std14::*;
|
||||
match (base, bold, italic) {
|
||||
(TimesRoman | TimesBold | TimesItalic | TimesBoldItalic, false, false) => TimesRoman,
|
||||
(TimesRoman | TimesBold | TimesItalic | TimesBoldItalic, true, false) => TimesBold,
|
||||
(TimesRoman | TimesBold | TimesItalic | TimesBoldItalic, false, true) => TimesItalic,
|
||||
(TimesRoman | TimesBold | TimesItalic | TimesBoldItalic, true, true) => TimesBoldItalic,
|
||||
(Courier | CourierBold | CourierOblique | CourierBoldOblique, false, false) => Courier,
|
||||
(Courier | CourierBold | CourierOblique | CourierBoldOblique, true, false) => CourierBold,
|
||||
(Courier | CourierBold | CourierOblique | CourierBoldOblique, false, true) => CourierOblique,
|
||||
(Courier | CourierBold | CourierOblique | CourierBoldOblique, true, true) => CourierBoldOblique,
|
||||
(_, false, false) => Helvetica,
|
||||
(_, true, false) => HelveticaBold,
|
||||
(_, false, true) => HelveticaOblique,
|
||||
(_, true, true) => HelveticaBoldOblique,
|
||||
}
|
||||
}
|
||||
|
||||
/// The resource name an appearance stream gives `face` (the usual `/DR` names).
|
||||
pub fn resource_name(face: Std14) -> &'static str {
|
||||
match face {
|
||||
Std14::HelveticaBold => "HeBo",
|
||||
Std14::HelveticaOblique => "HeOb",
|
||||
Std14::HelveticaBoldOblique => "HeBO",
|
||||
Std14::TimesRoman => "TiRo",
|
||||
Std14::TimesBold => "TiBo",
|
||||
Std14::TimesItalic => "TiIt",
|
||||
Std14::TimesBoldItalic => "TiBI",
|
||||
Std14::Courier => "Cour",
|
||||
Std14::CourierBold => "CoBo",
|
||||
Std14::CourierOblique => "CoOb",
|
||||
Std14::CourierBoldOblique => "CoBO",
|
||||
_ => "Helv",
|
||||
}
|
||||
}
|
||||
|
||||
/// `face`'s `CSS` family, weight and style, for writing `/DS` and `/RC`.
|
||||
pub fn css(face: Std14) -> (&'static str, &'static str, &'static str) {
|
||||
let family = match styled(face, false, false) {
|
||||
Std14::TimesRoman => "Times",
|
||||
Std14::Courier => "Courier",
|
||||
_ => "Helvetica",
|
||||
};
|
||||
(family, if is_bold(face) { "bold" } else { "normal" }, if is_italic(face) { "italic" } else { "normal" })
|
||||
}
|
||||
|
||||
fn bytes(c: Rgb) -> [u8; 3] {
|
||||
// Clamped to 0..=1 first, so the product is 0..=255 and the cast exact.
|
||||
c.map(|x| (x.clamp(0.0, 1.0) * 255.0).round() as u8)
|
||||
}
|
||||
|
||||
/// What a `/DS` string sets.
|
||||
#[derive(Debug, Default, PartialEq)]
|
||||
struct Ds {
|
||||
face: Option<Std14>,
|
||||
bold: Option<bool>,
|
||||
italic: Option<bool>,
|
||||
size: Option<f64>,
|
||||
color: Option<Rgb>,
|
||||
}
|
||||
|
||||
/// Read a default style string: `;`-separated `CSS` declarations. Unknown or malformed ones are
|
||||
/// skipped; later ones win.
|
||||
fn parse_ds(ds: &str) -> Ds {
|
||||
let end = ds.char_indices().map(|(i, _)| i).find(|i| *i >= MAX_DS).unwrap_or(ds.len());
|
||||
let ds = ds.get(..end).unwrap_or_default();
|
||||
let mut out = Ds::default();
|
||||
for decl in ds.split(';') {
|
||||
let Some((prop, value)) = decl.split_once(':') else { continue };
|
||||
let value = value.trim();
|
||||
match prop.trim().to_ascii_lowercase().as_str() {
|
||||
"font" => font_shorthand(value, &mut out),
|
||||
"font-family" => {
|
||||
if let Some(face) = value.split(',').find_map(family_face) {
|
||||
out.face = Some(face);
|
||||
}
|
||||
}
|
||||
"font-size" => {
|
||||
if let Some(size) = font_size(value, true) {
|
||||
out.size = Some(size);
|
||||
}
|
||||
}
|
||||
"font-weight" => {
|
||||
if let Some(bold) = weight(value) {
|
||||
out.bold = Some(bold);
|
||||
}
|
||||
}
|
||||
"font-style" => {
|
||||
if let Some(italic) = slant(value) {
|
||||
out.italic = Some(italic);
|
||||
}
|
||||
}
|
||||
"color" => {
|
||||
if let Some(c) = css_color(value) {
|
||||
out.color = Some(c);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `font: [style] [weight] size[/line-height] family[, family…]`, read leniently: the size is
|
||||
/// the token with a unit, keywords set weight and slant, and the rest is the family list (some
|
||||
/// writers put the family first).
|
||||
fn font_shorthand(value: &str, out: &mut Ds) {
|
||||
let mut family = Vec::new();
|
||||
for tok in value.split_whitespace() {
|
||||
if let Some(size) = font_size(tok, false) {
|
||||
out.size = Some(size);
|
||||
} else if let Some(bold) = weight(tok).filter(|_| !tok.eq_ignore_ascii_case("normal")) {
|
||||
out.bold = Some(bold);
|
||||
} else if let Some(italic) = slant(tok).filter(|_| !tok.eq_ignore_ascii_case("normal")) {
|
||||
out.italic = Some(italic);
|
||||
} else if !matches!(tok.to_ascii_lowercase().as_str(), "normal" | "small-caps") {
|
||||
family.push(tok);
|
||||
}
|
||||
}
|
||||
if let Some(face) = family.join(" ").split(',').find_map(family_face) {
|
||||
out.face = Some(face);
|
||||
}
|
||||
}
|
||||
|
||||
/// A size in points: `14pt` (with a line height, `14pt/16pt`), or a bare number where
|
||||
/// `unitless` allows it. Positive and finite only; capped as `/DA` sizes are.
|
||||
fn font_size(tok: &str, unitless: bool) -> Option<f64> {
|
||||
let tok = tok.split('/').next()?.trim();
|
||||
let num = match tok.strip_suffix("pt").or_else(|| tok.strip_suffix("PT")) {
|
||||
Some(n) => n,
|
||||
None if unitless => tok,
|
||||
None => return None,
|
||||
};
|
||||
num.parse::<f64>().ok().filter(|s| s.is_finite() && *s > 0.0).map(|s| s.min(MAX_SIZE))
|
||||
}
|
||||
|
||||
fn weight(v: &str) -> Option<bool> {
|
||||
match v.to_ascii_lowercase().as_str() {
|
||||
"bold" | "bolder" | "600" | "700" | "800" | "900" => Some(true),
|
||||
"normal" | "lighter" | "100" | "200" | "300" | "400" | "500" => Some(false),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn slant(v: &str) -> Option<bool> {
|
||||
match v.to_ascii_lowercase().as_str() {
|
||||
"italic" | "oblique" => Some(true),
|
||||
"normal" => Some(false),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// `#RRGGBB`, `#RGB` or `rgb(r, g, b)` (0–255 or percentages).
|
||||
fn css_color(v: &str) -> Option<Rgb> {
|
||||
let v = v.trim();
|
||||
if let Some(hex) = v.strip_prefix('#') {
|
||||
let digit = |c: char| c.to_digit(16).map(f64::from);
|
||||
let ds: Vec<f64> = hex.chars().map(digit).collect::<Option<_>>()?;
|
||||
return match ds.as_slice() {
|
||||
[r, g, b] => Some([r * 17.0 / 255.0, g * 17.0 / 255.0, b * 17.0 / 255.0]),
|
||||
[r1, r0, g1, g0, b1, b0] => Some([(r1 * 16.0 + r0) / 255.0, (g1 * 16.0 + g0) / 255.0, (b1 * 16.0 + b0) / 255.0]),
|
||||
_ => None,
|
||||
};
|
||||
}
|
||||
let lower = v.to_ascii_lowercase();
|
||||
let inner = lower.strip_prefix("rgb(")?.strip_suffix(')')?;
|
||||
let parts: Vec<f64> = inner
|
||||
.split(',')
|
||||
.map(|p| {
|
||||
let p = p.trim();
|
||||
let x = match p.strip_suffix('%') {
|
||||
Some(pc) => pc.trim().parse::<f64>().ok()? / 100.0,
|
||||
None => p.parse::<f64>().ok()? / 255.0,
|
||||
};
|
||||
x.is_finite().then(|| x.clamp(0.0, 1.0))
|
||||
})
|
||||
.collect::<Option<_>>()?;
|
||||
match parts.as_slice() {
|
||||
[r, g, b] => Some([*r, *g, *b]),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use pdfcraft_cos::PdfString;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn dict(da: &str, ds: Option<&str>) -> Dict {
|
||||
let mut d = Dict::new();
|
||||
d.set(b"DA".to_vec(), PdfString::literal(da.as_bytes().to_vec()));
|
||||
if let Some(ds) = ds {
|
||||
d.set(b"DS".to_vec(), PdfString::text(ds));
|
||||
}
|
||||
d
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn da_resource_names_pick_the_standard_faces() {
|
||||
assert_eq!(text_style(&dict("0 g /Cour 12 Tf", None), None).face, Std14::Courier);
|
||||
assert_eq!(text_style(&dict("1 0 0 rg /TiRo 16 Tf", None), None).face, Std14::TimesRoman);
|
||||
assert_eq!(text_style(&dict("/HeBo 9 Tf 0 g", None), None).face, Std14::HelveticaBold);
|
||||
assert_eq!(text_style(&dict("/Courier-Bold 9 Tf", None), None).face, Std14::CourierBold);
|
||||
// Unknown, symbolic and family-hint-only names keep Helvetica.
|
||||
for da in ["/F1 12 Tf", "/ZaDb 12 Tf", "/Symbol 12 Tf", "/MySerif 12 Tf", "12 Tf", "", "/ Tf"] {
|
||||
assert_eq!(text_style(&dict(da, None), None).face, Std14::Helvetica, "{da:?}");
|
||||
}
|
||||
// A `/DR` lookup outranks the name.
|
||||
assert_eq!(text_style(&dict("/Cour 12 Tf", None), Some(Std14::TimesRoman)).face, Std14::TimesRoman);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ds_font_size_and_colour_win_over_da() {
|
||||
let s = text_style(&dict("0 g /Helv 12 Tf", Some("font: Times 14pt; color: #008000")), None);
|
||||
assert_eq!((s.face, s.size), (Std14::TimesRoman, 14.0));
|
||||
assert!((s.color[1] - 128.0 / 255.0).abs() < 1e-9 && s.color[0] == 0.0 && s.color[2] == 0.0, "{:?}", s.color);
|
||||
let s = text_style(
|
||||
&dict(
|
||||
"1 0 0 rg /Cour 9 Tf",
|
||||
Some("font-family: 'Helvetica', sans-serif; font-size: 20; font-weight: bold; font-style: italic; color: rgb(0, 0, 255)"),
|
||||
),
|
||||
None,
|
||||
);
|
||||
assert_eq!((s.face, s.size, s.color), (Std14::HelveticaBoldOblique, 20.0, [0.0, 0.0, 1.0]));
|
||||
// CSS order, a line height, a #RGB colour and a generic family.
|
||||
let s = text_style(&dict("0 g /Helv 12 Tf", Some("font: italic bold 10pt/12pt serif; color:#f00")), None);
|
||||
assert_eq!((s.face, s.size, s.color), (Std14::TimesBoldItalic, 10.0, [1.0, 0.0, 0.0]));
|
||||
// Bold from the style keeps the DA family.
|
||||
assert_eq!(text_style(&dict("/Cour 12 Tf", Some("font-weight:700")), None).face, Std14::CourierBold);
|
||||
}
|
||||
|
||||
/// PdfCraft writes `/DS` from `/DA` (8-bit colour): `/DA`'s exact colour, size and face stay.
|
||||
#[test]
|
||||
fn pdfcraft_written_ds_matches_da() {
|
||||
let s = text_style(&dict("0.1 0.2 0.3 rg /Helv 12.5 Tf", Some("font: Helvetica 12.5pt; text-align:left; color:#1A334D")), None);
|
||||
assert_eq!(s, TextStyle { face: Std14::Helvetica, size: 12.5, color: [0.1, 0.2, 0.3] });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_ds_falls_back_to_da() {
|
||||
let da = TextStyle { face: Std14::Courier, size: 9.0, color: [1.0, 0.0, 0.0] };
|
||||
let huge = format!("color: #00ff00;{}", "x".repeat(1 << 20));
|
||||
let past_cap = format!("{}; font-size: 30pt", " ".repeat(MAX_DS));
|
||||
for ds in [
|
||||
"font-size: NaN",
|
||||
"font-size: inf",
|
||||
"font-size: -3pt",
|
||||
"font-size: 0",
|
||||
"font: NaNpt Zzz",
|
||||
"font: 1e999pt",
|
||||
"color: #12",
|
||||
"color: #zzzzzz",
|
||||
"color: rgb(1, 2)",
|
||||
"color: rgb(NaN, 0, 0)",
|
||||
"color: #ff0000é",
|
||||
":::;;;",
|
||||
"font-family: Wingdings, 'Comic Sans'",
|
||||
"é: ü; ;",
|
||||
past_cap.as_str(),
|
||||
] {
|
||||
assert_eq!(text_style(&dict("1 0 0 rg /Cour 9 Tf", Some(ds)), None), da, "{ds:?}");
|
||||
}
|
||||
// Read up to the cap: what comes first still counts, and nothing past it is scanned.
|
||||
assert_eq!(text_style(&dict("1 0 0 rg /Cour 9 Tf", Some(&huge)), None).color, [0.0, 1.0, 0.0]);
|
||||
// Sizes are capped as /DA's are.
|
||||
assert_eq!(text_style(&dict("/Helv 9 Tf", Some("font-size: 1e300pt")), None).size, MAX_SIZE);
|
||||
}
|
||||
|
||||
/// `/DA` strings as files give them: a `Tf` without a size, a zero size (auto-size in a form
|
||||
/// field, which a text box doesn't have), and hostile operands. None panics, each keeps what it
|
||||
/// can read, and nothing that isn't a finite number reaches the style.
|
||||
#[test]
|
||||
fn hostile_da_strings_keep_what_they_can() {
|
||||
let style = |da: &str| text_style(&dict(da, None), None);
|
||||
let black12 = |face| TextStyle { face, size: 12.0, color: [0.0; 3] };
|
||||
for (da, want) in [
|
||||
// A missing size keeps the named face at the default size.
|
||||
("/TiRo Tf", black12(Std14::TimesRoman)),
|
||||
("0 g /Cour Tf", black12(Std14::Courier)),
|
||||
// Zero, negative, NaN, infinite or not a number: the default size.
|
||||
("/Cour 0 Tf", black12(Std14::Courier)),
|
||||
("/Cour -0 Tf", black12(Std14::Courier)),
|
||||
("/Cour -12 Tf", black12(Std14::Courier)),
|
||||
("/Cour NaN Tf", black12(Std14::Courier)),
|
||||
("/Cour inf Tf", black12(Std14::Courier)),
|
||||
("/Cour -inf Tf", black12(Std14::Courier)),
|
||||
("/Cour 1e999 Tf", black12(Std14::Courier)),
|
||||
("/Cour twelve Tf", black12(Std14::Courier)),
|
||||
// No Tf at all, or one with nothing before it.
|
||||
("1 0 0 rg", TextStyle { color: [1.0, 0.0, 0.0], ..black12(Std14::Helvetica) }),
|
||||
("Tf", black12(Std14::Helvetica)),
|
||||
("Tf Tf Tf", black12(Std14::Helvetica)),
|
||||
("", black12(Std14::Helvetica)),
|
||||
// Colour operands that aren't finite numbers leave the colour black.
|
||||
("NaN NaN NaN rg /Helv 9 Tf", TextStyle { size: 9.0, ..black12(Std14::Helvetica) }),
|
||||
("NaN g /Helv 9 Tf", TextStyle { size: 9.0, ..black12(Std14::Helvetica) }),
|
||||
("inf 0 0 rg /Helv 9 Tf", TextStyle { size: 9.0, ..black12(Std14::Helvetica) }),
|
||||
("rg g /Helv 9 Tf", TextStyle { size: 9.0, ..black12(Std14::Helvetica) }),
|
||||
// Out-of-range colour components are clamped.
|
||||
("2 -1 0.5 rg /Helv 9 Tf", TextStyle { size: 9.0, color: [1.0, 0.0, 0.5], ..black12(Std14::Helvetica) }),
|
||||
// Huge sizes are capped.
|
||||
("/Helv 1e300 Tf", TextStyle { size: MAX_SIZE, ..black12(Std14::Helvetica) }),
|
||||
("/Helv 100000 Tf", TextStyle { size: MAX_SIZE, ..black12(Std14::Helvetica) }),
|
||||
// Garbage around a valid Tf: the last Tf is read.
|
||||
("\u{0} ] [ << /Helv 9 Tf >> /Cour 14 Tf )", TextStyle { size: 14.0, ..black12(Std14::Courier) }),
|
||||
] {
|
||||
assert_eq!(style(da), want, "{da:?}");
|
||||
let s = style(da);
|
||||
assert!(s.size.is_finite() && s.size > 0.0 && s.color.iter().all(|c| (0.0..=1.0).contains(c)), "{da:?}: {s:?}");
|
||||
}
|
||||
// A font name that is no standard face and that no `/DR` lists keeps Helvetica.
|
||||
assert_eq!(style("0 g /F9 11 Tf"), TextStyle { size: 11.0, ..black12(Std14::Helvetica) });
|
||||
// Binary bytes that aren't UTF-8 don't panic.
|
||||
let mut d = Dict::new();
|
||||
d.set(b"DA".to_vec(), PdfString::literal(vec![0xFF, 0xFE, b' ', b'/', 0xC3, b' ', b'9', b' ', b'T', b'f']));
|
||||
assert_eq!(text_style(&d, None).size, 9.0);
|
||||
assert_eq!(da_font_name(&dict("/TiRo Tf", None)).as_deref(), Some("TiRo"));
|
||||
assert_eq!(da_font_name(&dict("12 Tf", None)), None);
|
||||
assert_eq!(da_font_name(&dict("0 g Tf", None)), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn css_round_trips_through_the_parser() {
|
||||
for face in [Std14::Helvetica, Std14::TimesBold, Std14::CourierOblique, Std14::HelveticaBoldOblique, Std14::TimesBoldItalic] {
|
||||
let (family, weight, style) = css(face);
|
||||
let ds = format!("font-family:{family};font-weight:{weight};font-style:{style}");
|
||||
assert_eq!(text_style(&dict("/Helv 9 Tf", Some(&ds)), None).face, face);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -417,13 +417,17 @@ pub enum Shape {
|
||||
contours: Vec<Vec<[f64; 2]>>,
|
||||
},
|
||||
/// A custom stamp: a picture already in the document (an image XObject, or a form XObject
|
||||
/// whose `/Matrix` maps it to `size` points) filling `rect`, named `name`.
|
||||
/// whose `/Matrix` maps it to `size` points) filling `rect`, named `name`. With `line`, a
|
||||
/// line of text under the picture (#1741): a dynamic stamp's name, date and time, filled in
|
||||
/// when it was placed; the picture then fills the rectangle above it
|
||||
/// ([`CUSTOM_LINE_BAND`](crate::CUSTOM_LINE_BAND)).
|
||||
CustomStamp {
|
||||
rect: [f64; 4],
|
||||
name: String,
|
||||
picture: ObjRef,
|
||||
image: bool,
|
||||
size: (f64, f64),
|
||||
line: Option<String>,
|
||||
},
|
||||
/// A redaction mark (§12.5.6.23) over quadrilaterals (text) or one rectangle as a quad
|
||||
/// (areas, pages). `overlay` is the text shown on the box once applied, drawn with `look`.
|
||||
|
||||
@@ -179,7 +179,21 @@ impl Automation {
|
||||
let doc = self.doc(a)?;
|
||||
let only = a.opt_int("page")?.map(|p| (p.max(1) - 1) as usize);
|
||||
let all = self.comments(a)?;
|
||||
// A group (`/RT /Group`, ISO 32000-2 §12.5.6.2) lists as its primary, with the primary's
|
||||
// attributes: the subordinates are neither comments nor replies, only its `group`.
|
||||
let mut members: HashMap<(usize, usize), Vec<&Annotation>> = HashMap::new();
|
||||
for (m, p) in all.iter().zip(pdfcraft_render::group_primaries(&all)) {
|
||||
if let Some(p) = p.and_then(|p| all.get(p)) {
|
||||
members.entry((p.page, p.index)).or_default().push(m);
|
||||
}
|
||||
}
|
||||
let view = |c: &Annotation| -> Value {
|
||||
let group: Vec<Value> = members
|
||||
.get(&(c.page, c.index))
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(|m| json!({ "id": m.name, "page": m.page + 1, "index": m.index + 1, "type": m.subtype }))
|
||||
.collect();
|
||||
let mut v = json!({
|
||||
"id": c.name,
|
||||
"page": c.page + 1,
|
||||
@@ -191,6 +205,9 @@ impl Automation {
|
||||
"modified": c.modified,
|
||||
"rect": crate::view_rect(&doc.info, c.page, c.shown_rect(doc.info.pages.get(c.page).map_or(0, |p| p.rotation))),
|
||||
"color": c.color.map(hex),
|
||||
"group": group,
|
||||
// Unchanged on a page the viewer could not read, as `rect` is.
|
||||
"popup": c.popup.map(|w| json!({ "rect": crate::view_rect(&doc.info, c.page, w.rect), "open": w.open })),
|
||||
});
|
||||
// A text box's or typed text's oval or circle (a rectangle is not reported).
|
||||
if c.subtype == "FreeText"
|
||||
@@ -211,8 +228,8 @@ impl Automation {
|
||||
v["text_opacity"] = json!(t);
|
||||
}
|
||||
}
|
||||
// A line's ends, or the corners of connected lines, a polygon or a cloud, as
|
||||
// comment_edit's `points` takes them.
|
||||
// A line's ends, the corners of connected lines, a polygon or a cloud, or a callout's
|
||||
// arrow point and knee, as comment_edit's `points` takes them.
|
||||
// Unchanged on a page the viewer could not read, as `rect` is.
|
||||
if !c.points.is_empty() {
|
||||
let round = |v: f32| (v * 100.0).round() / 100.0;
|
||||
@@ -220,15 +237,20 @@ impl Automation {
|
||||
v["points"] =
|
||||
json!(c.points.iter().map(|q| page.map_or([q[0], q[1]], |p| p.user_to_view(q[0], q[1])).map(round)).collect::<Vec<_>>());
|
||||
}
|
||||
// A callout's text box, as comment_edit's `rect` takes it (`rect` also holds the line).
|
||||
if let Some(tb) = c.text_box {
|
||||
v["text_box"] = json!(crate::view_rect(&doc.info, c.page, tb));
|
||||
}
|
||||
v
|
||||
};
|
||||
// Every reply under the comment its thread starts from, at any depth, in document order:
|
||||
// a reply to a reply keeps its `/IRT` on the direct parent, so following one level would
|
||||
// drop it. Parents are found by reference, as `/NM` need not be unique. Status and
|
||||
// checkmark replies are read through `review` instead.
|
||||
// checkmark replies are read through `review` instead. A group subordinate is in no
|
||||
// thread, and a reply to one is the group's, its primary's.
|
||||
let tops = pdfcraft_render::thread_tops(&all);
|
||||
let mut threads: HashMap<(usize, usize), Vec<&Annotation>> = HashMap::new();
|
||||
for r in all.iter().filter(|r| r.state.is_none()) {
|
||||
for r in all.iter().filter(|r| r.state.is_none() && !r.is_group_member()) {
|
||||
let Some(&top) = tops.get(&(r.page, r.index)) else { continue };
|
||||
threads.entry(top).or_default().push(r);
|
||||
}
|
||||
@@ -408,18 +430,8 @@ impl Automation {
|
||||
let point = to_user(&info, t[0], t[1]);
|
||||
let knee = match a.nums::<2>("knee")? {
|
||||
Some(k) => to_user(&info, k[0], k[1]),
|
||||
// Halfway between the point and the box, level with the box's middle.
|
||||
None => {
|
||||
let mid = (rect[1] + rect[3]) / 2.0;
|
||||
let side = if point[0] < rect[0] {
|
||||
rect[0]
|
||||
} else if point[0] > rect[2] {
|
||||
rect[2]
|
||||
} else {
|
||||
(rect[0] + rect[2]) / 2.0
|
||||
};
|
||||
[(point[0] + side) / 2.0, mid]
|
||||
}
|
||||
// Acrobat's: 12 pt out from the middle of the side facing the point.
|
||||
None => pdfcraft_engine::callout_knee(rect, point),
|
||||
};
|
||||
Shape::Callout {
|
||||
rect,
|
||||
@@ -700,6 +712,17 @@ impl Automation {
|
||||
self.apply(a, Edit::MarkAnnotation { page, index, marked, author })
|
||||
}
|
||||
|
||||
pub(crate) fn comment_popup(&mut self, a: &Args) -> Result<Value> {
|
||||
let (page, index) = self.comment_target(a)?;
|
||||
let info = self.doc(a)?.info.pages[page].clone();
|
||||
let open = a.opt_bool("open")?;
|
||||
let rect = a.nums::<4>("rect")?.map(|r| rect_to_user(&info, r));
|
||||
if open.is_none() && rect.is_none() {
|
||||
return Err(ToolError::InvalidArgs("nothing to change: pass open and/or rect".into()));
|
||||
}
|
||||
self.apply(a, Edit::SetAnnotationPopup { page, index, rect, open })
|
||||
}
|
||||
|
||||
pub(crate) fn comment_lock(&mut self, a: &Args) -> Result<Value> {
|
||||
let (page, index) = self.comment_target(a)?;
|
||||
let locked = a.opt_bool("locked")?.unwrap_or(true);
|
||||
@@ -873,6 +896,7 @@ impl Automation {
|
||||
let bytes = crate::read_input(&path)?;
|
||||
let file = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
let name = a.opt_str("name")?.map(str::to_owned).unwrap_or_else(|| file.rsplit_once('.').map_or(file.clone(), |(s, _)| s.to_owned()));
|
||||
let author = a.opt_str("author")?.unwrap_or(DEFAULT_AUTHOR).to_string();
|
||||
let edit = Edit::AddCustomStamp {
|
||||
page,
|
||||
rect,
|
||||
@@ -882,7 +906,16 @@ impl Automation {
|
||||
bytes: std::sync::Arc::new(bytes),
|
||||
page: a.opt_int("file_page")?.unwrap_or(1).max(1) as usize - 1,
|
||||
},
|
||||
author: a.opt_str("author")?.unwrap_or(DEFAULT_AUTHOR).to_string(),
|
||||
line: None,
|
||||
author: author.clone(),
|
||||
};
|
||||
// A dynamic line (#1741): `{name}`, `{date}` and `{time}` filled in now.
|
||||
let edit = match (edit, a.opt_str("line")?) {
|
||||
(Edit::AddCustomStamp { page, rect, name, file, author, .. }, Some(t)) if !t.trim().is_empty() => {
|
||||
let line = Some(self.session().stamp_line(t, &author));
|
||||
Edit::AddCustomStamp { page, rect, name, file, author, line }
|
||||
}
|
||||
(edit, _) => edit,
|
||||
};
|
||||
self.apply(a, edit)
|
||||
}
|
||||
|
||||
@@ -879,6 +879,7 @@ impl Automation {
|
||||
"sign_trust" => self.sign_trust(&a)?,
|
||||
"comment_mark" => self.comment_mark(&a)?,
|
||||
"comment_lock" => self.comment_lock(&a)?,
|
||||
"comment_popup" => self.comment_popup(&a)?,
|
||||
"comments_hide" => self.comments_hide(&a)?,
|
||||
"layer_set" => self.layer_set(&a)?,
|
||||
"view_reading_colors" => self.view_reading_colors(&a)?,
|
||||
|
||||
@@ -310,8 +310,35 @@ impl Automation {
|
||||
json!((0..f.widgets.len()).filter(|&i| f.widget_on(i)).map(|i| i.saturating_add(1)).collect::<Vec<_>>()),
|
||||
);
|
||||
}
|
||||
// A check box whose kids have different on states (ISO 32000-2 §12.7.5.2.3):
|
||||
// which one is ticked, and the names form_fill takes to tick each. One option
|
||||
// per distinct on state: kids sharing a state tick together (EXAMPLE 2), so
|
||||
// their `/Opt` exports are not separate choices. Exports name the options
|
||||
// unless two states share one (Table 230 allows it) or an export would tick
|
||||
// another state (form_fill reads a name as an on state first); then the
|
||||
// states do.
|
||||
FormFieldKind::CheckBox => {
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let states: Vec<&str> = f.widgets.iter().filter_map(|w| w.on_state.as_deref()).filter(|s| seen.insert(*s)).collect();
|
||||
if states.len() > 1 {
|
||||
let mut exports = std::collections::HashSet::new();
|
||||
let by_export = states.iter().all(|s| {
|
||||
let e = f.export_for_state(s);
|
||||
exports.insert(e) && f.state_for(e) == Some(*s)
|
||||
});
|
||||
let name = |s: &str| if by_export { f.export_for_state(s).to_owned() } else { s.to_owned() };
|
||||
// The ticked kid is the one whose `/AS` is its on state: §12.7.5.2.3
|
||||
// makes `/AS` decide where it and `/V` differ.
|
||||
let on = (0..f.widgets.len()).find(|&i| f.widget_on(i)).and_then(|i| f.widgets.get(i)?.on_state.as_deref());
|
||||
o.insert("options".into(), json!(states.iter().map(|s| name(s)).collect::<Vec<_>>()));
|
||||
o.insert("checked".into(), json!(on.map(name)));
|
||||
}
|
||||
}
|
||||
FormFieldKind::Combo | FormFieldKind::List => {
|
||||
o.insert("options".into(), f.options.iter().map(|(e, d)| json!({ "value": e, "label": d })).collect());
|
||||
// The selected options as 1-based positions in `options`: two options can share
|
||||
// an export value, and `value` alone does not tell them apart.
|
||||
o.insert("selected".into(), json!(f.selected.iter().map(|i| i.saturating_add(1)).collect::<Vec<_>>()));
|
||||
o.insert("multi_select".into(), json!(f.has(field_flags::MULTI_SELECT)));
|
||||
o.insert("editable".into(), json!(f.has(field_flags::EDIT)));
|
||||
}
|
||||
|
||||
@@ -334,6 +334,12 @@ pub(crate) fn info(d: &Document) -> Value {
|
||||
"target": link_target(i, &l.target),
|
||||
})).collect::<Vec<_>>(),
|
||||
"layers": i.layers.iter().map(|l| json!({ "name": l.name, "visible": l.visible, "initial": l.initial })).collect::<Vec<_>>(),
|
||||
// The Layers panel's rows, the default configuration's /Order (ISO 32000-2 Table 99): a
|
||||
// layer by its 1-based position in `layers`, or a label; `depth` 0 at the top.
|
||||
"layer_order": i.layer_order.iter().map(|r| match &r.item {
|
||||
pdfcraft_render::LayerItem::Layer(n) => json!({ "depth": r.depth, "layer": n.saturating_add(1), "name": i.layers.get(*n).map(|l| l.name.as_str()) }),
|
||||
pdfcraft_render::LayerItem::Label(s) => json!({ "depth": r.depth, "label": s }),
|
||||
}).collect::<Vec<_>>(),
|
||||
// Full-screen presentation settings a page carries (ISO 32000-2 §12.4.4): only pages with
|
||||
// a `/Trans` or `/Dur` appear; `style` is null for a display time alone.
|
||||
"transitions": i.transitions.iter().map(|t| json!({
|
||||
|
||||
@@ -77,7 +77,8 @@ impl Automation {
|
||||
|
||||
pub(crate) fn link_list(&self, a: &Args) -> Result<Value> {
|
||||
let doc = self.doc(a)?;
|
||||
let targets: std::collections::HashMap<(usize, usize), &LinkTarget> = doc.info.links.iter().map(|t| ((t.page, t.index), &t.target)).collect();
|
||||
let viewed: std::collections::HashMap<(usize, usize), &pdfcraft_render::Link> =
|
||||
doc.info.links.iter().map(|t| ((t.page, t.index), t)).collect();
|
||||
let items: Vec<Value> = doc
|
||||
.links()
|
||||
.iter()
|
||||
@@ -85,14 +86,49 @@ impl Automation {
|
||||
// The link's page may be one the viewer could not read (#2660): rect unchanged then.
|
||||
let rect = crate::view_rect(&doc.info, l.page, l.rect.map(|x| x as f32));
|
||||
let mut v = json!({ "page": l.page + 1, "index": l.index + 1, "rect": rect, "visible": l.style.visible });
|
||||
let link = viewed.get(&(l.page, l.index));
|
||||
// Where the link is active when that isn't its whole rect: its /QuadPoints
|
||||
// (ISO 32000-2 Table 176), as the bounding box of each quadrilateral.
|
||||
if let Some(link) = link.filter(|k| !k.quads.is_empty()) {
|
||||
let areas: Vec<Value> = link
|
||||
.quads
|
||||
.iter()
|
||||
.map(|q| {
|
||||
let (xs, ys) = ([q[0], q[2], q[4], q[6]], [q[1], q[3], q[5], q[7]]);
|
||||
let fold = |v: [f32; 4], f: fn(f32, f32) -> f32, start: f32| v.into_iter().fold(start, f);
|
||||
let box_ = [
|
||||
fold(xs, f32::min, f32::MAX),
|
||||
fold(ys, f32::min, f32::MAX),
|
||||
fold(xs, f32::max, f32::MIN),
|
||||
fold(ys, f32::max, f32::MIN),
|
||||
];
|
||||
json!(crate::view_rect(&doc.info, l.page, box_))
|
||||
})
|
||||
.collect();
|
||||
v["active_areas"] = json!(areas);
|
||||
}
|
||||
// Where an in-document link goes, as the viewer resolves it: named destinations
|
||||
// included, with the position on the page.
|
||||
let target = targets.get(&(l.page, l.index)).and_then(|t| match t {
|
||||
let target = link.and_then(|t| match &t.target {
|
||||
LinkTarget::Page(page, view) => Some((*page, view)),
|
||||
_ => None,
|
||||
});
|
||||
match (&l.action, target) {
|
||||
(LinkAction::Uri(u), _) => v["url"] = json!(u),
|
||||
(LinkAction::Uri(u), _) => {
|
||||
v["url"] = json!(u);
|
||||
// A relative address, resolved against the catalog's /URI /Base
|
||||
// (ISO 32000-2 Table 211): what the viewer offers to open. That is the
|
||||
// address inspection kept, which stays raw once its text budget is spent;
|
||||
// resolve afresh only for a link inspection did not list.
|
||||
let opened = match link.map(|t| &t.target) {
|
||||
Some(LinkTarget::Uri(kept)) => Some(kept.clone()),
|
||||
Some(_) => None,
|
||||
None => pdfcraft_render::resolve_uri(doc.info.uri_base.as_deref(), u),
|
||||
};
|
||||
if let Some(opened) = opened.filter(|o| o != u) {
|
||||
v["resolved_url"] = json!(opened);
|
||||
}
|
||||
}
|
||||
(action, Some((page, view))) => {
|
||||
v["to_page"] = json!(page + 1);
|
||||
if let Some(d) = doc.info.pages.get(page).and_then(|p| crate::destination(view, p)) {
|
||||
|
||||
@@ -414,6 +414,7 @@ fn render_warning_text(warning: pdfcraft_render::RenderWarning) -> &'static str
|
||||
match warning {
|
||||
RenderWarning::ContentTruncated => "content past the page's safety budget was skipped",
|
||||
RenderWarning::ColourFallback => "a colour that could not be computed was painted in a fallback colour",
|
||||
RenderWarning::MalformedIndexedImage => "an image with a malformed Indexed colour table may be drawn wrongly or not at all",
|
||||
RenderWarning::Type3WidthsMissing => "a Type 3 font has no /Widths; its glyphs were spaced by the widths their glyph procedures give",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
use pdfcraft_engine::{
|
||||
Edit, HIDDEN, Hidden, NewAnnotation, REDACT_MAX_WORDS, REDACT_VALIDATORS, REDACTION_CODE_SETS, RedactPattern, RedactRegex, RedactValidator,
|
||||
RedactionCodeSet, Shape, Style, find_pattern, rect_quad, redact_word_list,
|
||||
RedactionCodeSet, Shape, Style, find_pattern, rect_quad, redact_word_list, redacted_file_name,
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
@@ -200,6 +200,8 @@ impl Automation {
|
||||
let after = self.doc(a)?.redaction_marks();
|
||||
out["applied"] = json!(before - after);
|
||||
out["marks_pending"] = json!(after);
|
||||
// The name to save the redacted copy under, as Save does in the app.
|
||||
out["save_as"] = json!(redacted_file_name(&self.doc(a)?.name));
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
|
||||
@@ -175,7 +175,7 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
.cmd("file.open")
|
||||
.with(schema(json!({ "path": { "type": "string" }, "password": { "type": "string", "description": "User or owner password for encrypted files." } }), &["path"])),
|
||||
t("doc_list", "List open documents", "List the open documents with their ids, page counts and unsaved state.").ro().with(schema(json!({}), &[])),
|
||||
t("doc_info", "Inspect a document", "Metadata, page sizes and labels, bookmarks, annotations, form fields, links, layers, page transitions and display times, the destination it opens at, attachments, fonts, security, repair notes and the objects that could not be read.")
|
||||
t("doc_info", "Inspect a document", "Metadata, page sizes and labels, bookmarks, annotations, form fields, links, layers and the Layers panel's tree (layer_order), page transitions and display times, the destination it opens at, attachments, fonts, security, repair notes and the objects that could not be read.")
|
||||
.ro()
|
||||
.cmd("file.properties")
|
||||
.with(schema(json!({ "doc": doc() }), &["doc"])),
|
||||
@@ -508,13 +508,13 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
}),
|
||||
&["doc", "from", "to"],
|
||||
)),
|
||||
t("form_fields", "List form fields", "Every interactive form field: name, type (text, checkbox, radio, combo, list, button, signature), value, options, page, rect (top-left-origin points) and rotation (0, 90, 180 or 270 degrees counterclockwise), read-only and required flags. A calculated field includes calculate: {op, fields} or {notation} as form_set_props takes them, or {script} for a custom Calculate script (set with form_set_script). Push buttons include caption (first widget's normal label) and captions [{widget, caption}] for all widgets (1-based). Radio groups include on_widgets, the 1-based numbers of the buttons that are on (buttons sharing an option tell apart only there).")
|
||||
t("form_fields", "List form fields", "Every interactive form field: name, type (text, checkbox, radio, combo, list, button, signature), value, options, page, rect (top-left-origin points) and rotation (0, 90, 180 or 270 degrees counterclockwise), read-only and required flags. A calculated field includes calculate: {op, fields} or {notation} as form_set_props takes them, or {script} for a custom Calculate script (set with form_set_script). Push buttons include caption (first widget's normal label) and captions [{widget, caption}] for all widgets (1-based). Radio groups include on_widgets, the 1-based numbers of the buttons that are on (buttons sharing an option tell apart only there). A check box whose widgets have different on states also lists them as options, and which one is checked (null when none). Combo and list boxes include selected: the 1-based positions in options of the selected ones, which tells apart options that share an export value.")
|
||||
.ro()
|
||||
.with(schema(json!({ "doc": doc() }), &["doc"])),
|
||||
t(
|
||||
"form_fill",
|
||||
"Fill in form fields",
|
||||
"Set several fields at once (one undo step). values maps field names (from form_fields) to: a string for text fields, combo boxes and radio groups (an option), true/false for check boxes, an array of strings for multi-select lists; {\"widget\": n} turns on button n (1-based) of a check box or radio group and never turns it off (to clear, use null for a radio group that allows it, false for a check box); of radio buttons sharing an option only that one is on unless the group has RadiosInUnison. Appearances are regenerated so every viewer shows the values. Thai the field's font can't hold is drawn from PdfCraft's built-in Thai face (a build without one refuses it). Any other value whose characters the field's font can't draw (Chinese in a Helvetica field) is still saved; `warnings` in the result names the field and character: PdfCraft draws `?` there and asks other viewers to redraw the field from its value.",
|
||||
"Set several fields at once (one undo step). values maps field names (from form_fields) to: a string for text fields, combo boxes and radio groups (an option), true/false for check boxes (or one of a check box's options, to check that widget and clear the others), an array of strings for multi-select lists; {\"widget\": n} turns on button n (1-based) of a check box or radio group and never turns it off (to clear, use null for a radio group that allows it, false for a check box); of radio buttons sharing an option only that one is on unless the group has RadiosInUnison. Appearances are regenerated so every viewer shows the values. Thai the field's font can't hold is drawn from PdfCraft's built-in Thai face (a build without one refuses it). Any other value whose characters the field's font can't draw (Chinese in a Helvetica field) is still saved; `warnings` in the result names the field and character: PdfCraft draws `?` there and asks other viewers to redraw the field from its value.",
|
||||
)
|
||||
.with(schema(json!({ "doc": doc(), "values": { "type": "object", "description": "Field name → value." } }), &["doc", "values"])),
|
||||
t("form_reset", "Clear form", "Reset fields to their default values: all of them, or only those listed. Undoable.")
|
||||
@@ -563,7 +563,7 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
}),
|
||||
&["doc", "page", "rect", "rows"],
|
||||
)),
|
||||
t("stamp_custom", "Add a custom stamp", "Stamp a picture: a PDF page (file_page, default 1, kept as vector content in a form XObject) or an image file. Either centred at at [x, y] (points from the top-left of the displayed page) at its natural size, at most 200 pt, or fitted inside rect [x0, y0, x1, y1] (the same coordinates; each side 1–14400 pt), scaled to keep its shape and centred in the box. Like at, rect is not clipped to the page. Pass at or rect, not both. name labels it (default: the file name). Undoable.")
|
||||
t("stamp_custom", "Add a custom stamp", "Stamp a picture: a PDF page (file_page, default 1, kept as vector content in a form XObject) or an image file. Either centred at at [x, y] (points from the top-left of the displayed page) at its natural size, at most 200 pt, or fitted inside rect [x0, y0, x1, y1] (the same coordinates; each side 1–14400 pt), scaled to keep its shape and centred in the box. Like at, rect is not clipped to the page. Pass at or rect, not both. name labels it (default: the file name). line adds a text line under the picture with {name} (the author), {date} and {time} filled in now, as a dynamic stamp. Undoable.")
|
||||
.cmd("comment.stamp")
|
||||
.with(schema(
|
||||
json!({
|
||||
@@ -575,6 +575,7 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
"file_page": { "type": "integer", "minimum": 1 },
|
||||
"name": { "type": "string" },
|
||||
"author": { "type": "string" },
|
||||
"line": { "type": "string", "maxLength": 200 },
|
||||
}),
|
||||
&["doc", "page", "path"],
|
||||
)),
|
||||
@@ -678,7 +679,7 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
t(
|
||||
"redact_apply",
|
||||
"Apply redactions",
|
||||
"Apply the redaction marks (all, or those on pages): text, images, vectors, comments and form fields under them are removed for good and boxes are drawn in their place. A verification pass fails the operation if anything readable remains. Undoable until saved; the saved file no longer contains the content.",
|
||||
"Apply the redaction marks (all, or those on pages): text, images, vectors, comments and form fields under them are removed for good and boxes are drawn in their place. A verification pass fails the operation if anything readable remains. Undoable until saved; the saved file no longer contains the content. The result's save_as is the document's name with _Redacted before the extension (contract.pdf gives contract_Redacted.pdf; a name that already ends in _Redacted is unchanged); pass it to doc_save as path to save under that name.",
|
||||
)
|
||||
.destructive()
|
||||
.with(schema(json!({ "doc": doc(), "pages": pages("whose marks to apply (default: all)") }), &["doc"])),
|
||||
@@ -824,7 +825,7 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
t("content_delete", "Delete added content", "Delete an added item (page, index from content_list). Undoable.")
|
||||
.destructive()
|
||||
.with(schema(json!({ "doc": doc(), "page": { "type": "integer", "minimum": 1 }, "index": { "type": "integer", "minimum": 1 } }), &["doc", "page", "index"])),
|
||||
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). 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.")
|
||||
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. Named destinations are reported but not applied. Absolute file specifications require allow_absolute: true after reviewing the target; relative links need no opt-in.")
|
||||
@@ -880,7 +881,7 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
.ro().cmd("measure.snap").with(schema(json!({"doc":doc(),"page":{"type":"integer","minimum":1},"at":point(),"tolerance":{"type":"number","minimum":0,"maximum":10000},"endpoints":{"type":"boolean"},"midpoints":{"type":"boolean"},"intersections":{"type":"boolean"},"paths":{"type":"boolean"}}), &["doc","page","at"])),
|
||||
t("measure_export", "Export measurements as CSV", "Atomically write saved measurement values, labels, authors and scale ratios as spreadsheet-safe CSV. Returns how many unsupported measurements were left out.")
|
||||
.cmd("measure.export").with(schema(json!({"doc":doc(),"out":path_arg()}), &["doc","out"])),
|
||||
t("comment_list", "List comments", "Every comment (annotation other than links, form widgets and pop-ups) with its page, index, id, type, author, text, date, rectangle, colour, review status, checkmark and replies (each with its own status and checkmark).")
|
||||
t("comment_list", "List comments", "Every comment (annotation other than links, form widgets and pop-ups) with its page, index, id, type, author, text, date, rectangle, colour, review status, checkmark and replies (each with its own status and checkmark); the points that shape a line, polygon or callout, and a callout's text box. Annotations grouped with a comment (/RT /Group) are listed once, as that comment with its attributes, and named in its `group`. comment_delete deletes just the member named, as Acrobat does (Replace Text's strikeout and caret go together).")
|
||||
.ro()
|
||||
.with(schema(json!({ "doc": doc(), "page": { "type": "integer", "minimum": 1, "description": "Only this page." } }), &["doc"])),
|
||||
t(
|
||||
@@ -1051,7 +1052,7 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
json!({ "doc": doc(), "sort": { "type": "string", "enum": ["page", "author", "date", "type"] }, "out": save_out, "open": open }),
|
||||
&["doc"],
|
||||
)),
|
||||
t("comment_edit", "Edit a comment", "Change a comment's text, colour, opacity (the whole comment's, or its fill's and text's own), line width, font size (text box/typewriter/callout), fill (rectangle/oval/polygon/text box/callout; \"none\" removes it), border colour (`border_color`, text box/typewriter/callout; \"text\" gives it the text's colour again), rectangle (rectangle/oval/text box/stamp), position (`move` [dx, dy] in points) or shape (`points`: a line's two ends, or the corners of connected lines, a polygon or a cloud). Stamps keep their original appearance when resized. One undo step.").with(schema(
|
||||
t("comment_edit", "Edit a comment", "Change a comment's text, colour, opacity (the whole comment's, or its fill's and text's own), line width, font size (text box/typewriter/callout), fill (rectangle/oval/polygon/text box/callout; \"none\" removes it), border colour (`border_color`, text box/typewriter/callout; \"text\" gives it the text's colour again), rectangle (rectangle/oval/text box/stamp, or a callout's text box: its arrow point stays and its leader line re-attaches), position (`move` [dx, dy] in points) or shape (`points`: a line's two ends, the corners of connected lines, a polygon or a cloud, or a callout's arrow point and knee, as comment_list gives them). Stamps keep their original appearance when resized. One undo step.").with(schema(
|
||||
comment_ref(json!({
|
||||
"contents": { "type": "string" },
|
||||
"color": color(),
|
||||
@@ -1065,13 +1066,18 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
"font_size": { "type": "number", "minimum": 1, "maximum": 400, "description": "Font size in points of a text box, typewriter text or callout; the box grows to hold the text." },
|
||||
"rect": { "type": "array", "items": { "type": "number" }, "minItems": 4, "maxItems": 4 },
|
||||
"move": point(),
|
||||
"points": { "type": "array", "items": point(), "minItems": 2, "description": "A line's two ends, or every corner of connected lines, a polygon or a cloud, in page coordinates." },
|
||||
"points": { "type": "array", "items": point(), "minItems": 1, "description": "A line's two ends, every corner of connected lines, a polygon or a cloud, or a callout's arrow point and (optionally) knee, in page coordinates. A callout given its arrow point alone keeps the knee it has." },
|
||||
})),
|
||||
&["doc"],
|
||||
)),
|
||||
t("comment_image_preview", "Preview image signature layers", "Return a PNG of the page without the selected image signature/initials (layer=background, default), or its embedded image with alpha (layer=image). Includes the displayed rectangle, document rotation, image_rotation (how far clockwise the image is shown turned) and annotation opacity. Cache these layers for live placement/resizing; commit once with comment_edit. Does not change the document or undo history.")
|
||||
.ro().with(schema(comment_ref(json!({ "layer": { "type": "string", "enum": ["background", "image"], "default": "background" }, "dpi": { "type": "number", "minimum": 1, "maximum": 600, "default": 96 } })), &["doc"])),
|
||||
t("comment_delete", "Delete a comment", "Delete a comment with its pop-up and replies, or one reply (its id, or page and index, from comment_list) with its pop-up and the replies to it; the comment and its other replies stay. Undoable.").destructive().with(schema(comment_ref(json!({})), &["doc"])),
|
||||
t("comment_popup", "Open, close or move a comment's pop-up", "Open or close a comment's pop-up window (open), or move it (rect, in page view coordinates as comment_list reports). A comment without a pop-up gets one beside it. Text boxes, Fill & Sign marks and replies have none of their own. Undoable.")
|
||||
.with(schema(comment_ref(json!({
|
||||
"open": { "type": "boolean" },
|
||||
"rect": { "type": "array", "items": { "type": "number" }, "minItems": 4, "maxItems": 4 },
|
||||
})), &["doc"])),
|
||||
t(
|
||||
"comments_copy",
|
||||
"Copy comments",
|
||||
|
||||
@@ -2263,6 +2263,93 @@ fn text_links_leave_out_addresses_on_hidden_layers() {
|
||||
assert_eq!(created["created"], json!(["https://example.com/shown", "https://example.com/layered"]), "{created}");
|
||||
}
|
||||
|
||||
/// Table 211), and a link with `/QuadPoints` is active only there (§12.5.6.5, Table 176): both as
|
||||
/// link_list and doc_info report them.
|
||||
#[test]
|
||||
fn links_resolve_relative_addresses_and_report_their_quad_points() {
|
||||
let dir = workdir("link-base-quads");
|
||||
let objs: Vec<&str> = vec![
|
||||
"<< /Type /Catalog /Pages 2 0 R /URI << /Base (https://example.com/base/) >> >>",
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 612 792] >>",
|
||||
"<< /Type /Page /Parent 2 0 R /Annots [4 0 R 5 0 R 6 0 R] >>",
|
||||
"<< /Type /Annot /Subtype /Link /Rect [72 700 300 716] /Border [0 0 0] /A << /S /URI /URI (page.html) >> >>",
|
||||
"<< /Type /Annot /Subtype /Link /Rect [72 670 300 686] /QuadPoints [72 670 120 670 120 686 72 686] /Border [0 0 0] /A << /S /URI /URI (https://example.org/q) >> >>",
|
||||
"<< /Type /Annot /Subtype /Link /Rect [72 640 300 656] /Border [0 0 0] /A << /S /URI /URI (javascript:alert\\(1\\)) >> >>",
|
||||
];
|
||||
let mut pdf = b"%PDF-1.7\n".to_vec();
|
||||
let mut offsets = Vec::new();
|
||||
for (i, o) in objs.iter().enumerate() {
|
||||
offsets.push(pdf.len());
|
||||
pdf.extend_from_slice(format!("{} 0 obj\n{o}\nendobj\n", i + 1).as_bytes());
|
||||
}
|
||||
let xref = pdf.len();
|
||||
pdf.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes());
|
||||
for o in offsets {
|
||||
pdf.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());
|
||||
}
|
||||
pdf.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes());
|
||||
std::fs::write(dir.join("links.pdf"), pdf).unwrap();
|
||||
let mut a = auto(&dir);
|
||||
let doc = ok(&mut a, "doc_open", json!({ "path": "links.pdf" }))["doc"].as_u64().unwrap();
|
||||
let links = ok(&mut a, "link_list", json!({ "doc": doc }));
|
||||
let [relative, quads, script] = [&links["links"][0], &links["links"][1], &links["links"][2]];
|
||||
assert_eq!(
|
||||
(relative["url"].clone(), relative["resolved_url"].clone()),
|
||||
(json!("page.html"), json!("https://example.com/base/page.html")),
|
||||
"{links}"
|
||||
);
|
||||
assert_eq!(relative.get("active_areas"), None, "{links}");
|
||||
// 792 − 686 = 106 points from the top: only the first word, not the whole rect.
|
||||
assert_eq!(quads["active_areas"], json!([[72.0, 106.0, 120.0, 122.0]]), "{links}");
|
||||
assert_eq!(quads.get("resolved_url"), None, "an absolute address is not resolved");
|
||||
// A base never turns a script into a web address.
|
||||
assert_eq!((script["url"].clone(), script.get("resolved_url")), (json!("javascript:alert(1)"), None), "{links}");
|
||||
let info = ok(&mut a, "doc_info", json!({ "doc": doc }));
|
||||
assert_eq!(info["links"][0]["target"]["uri"], "https://example.com/base/page.html", "{info}");
|
||||
}
|
||||
|
||||
/// Once inspection's text budget is spent, a relative address stays raw, and the viewer opens it
|
||||
/// as written: `link_list` reports that address, not a second resolution against `/URI /Base`.
|
||||
#[test]
|
||||
fn link_list_reports_the_address_the_viewer_opens_past_the_text_budget() {
|
||||
let dir = workdir("link-base-budget");
|
||||
// Each link spends what the base adds to its address; well past 16 MiB of it in all.
|
||||
let base = format!("https://example.com/{}/", "b".repeat(8000));
|
||||
let count = (16 << 20) / base.len() + 20;
|
||||
let annots = "<< /Type /Annot /Subtype /Link /Rect [0 0 10 10] /Border [0 0 0] /A 4 0 R >> ".repeat(count);
|
||||
let catalog = format!("<< /Type /Catalog /Pages 2 0 R /URI << /Base ({base}) >> >>");
|
||||
let page = format!("<< /Type /Page /Parent 2 0 R /Annots [{annots}] >>");
|
||||
let objs = [catalog.as_str(), "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 612 792] >>", page.as_str(), "<< /S /URI /URI (p.html) >>"];
|
||||
let mut pdf = b"%PDF-1.7\n".to_vec();
|
||||
let mut offsets = Vec::new();
|
||||
for (i, o) in objs.iter().enumerate() {
|
||||
offsets.push(pdf.len());
|
||||
pdf.extend_from_slice(format!("{} 0 obj\n{o}\nendobj\n", i + 1).as_bytes());
|
||||
}
|
||||
let xref = pdf.len();
|
||||
pdf.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes());
|
||||
for o in offsets {
|
||||
pdf.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());
|
||||
}
|
||||
pdf.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes());
|
||||
std::fs::write(dir.join("links.pdf"), pdf).unwrap();
|
||||
let mut a = auto(&dir);
|
||||
let doc = ok(&mut a, "doc_open", json!({ "path": "links.pdf" }))["doc"].as_u64().unwrap();
|
||||
let listed = ok(&mut a, "link_list", json!({ "doc": doc }));
|
||||
let links = listed["links"].as_array().unwrap();
|
||||
assert_eq!(links.len(), count);
|
||||
let info = ok(&mut a, "doc_info", json!({ "doc": doc }));
|
||||
let opened = info["links"].as_array().unwrap();
|
||||
assert_eq!(opened.len(), count);
|
||||
let resolved = format!("{base}p.html");
|
||||
assert_eq!(links[0]["resolved_url"], json!(resolved), "the first links resolve");
|
||||
assert_eq!(opened[0]["target"]["uri"], json!(resolved));
|
||||
// Past the budget the viewer keeps (and opens) the raw address; the listing says so.
|
||||
let last = count - 1;
|
||||
assert_eq!(opened[last]["target"]["uri"], json!("p.html"));
|
||||
assert_eq!((links[last]["url"].clone(), links[last].get("resolved_url")), (json!("p.html"), None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bookmarks_from_structure_through_tools() {
|
||||
let dir = workdir("bookmarks-structure");
|
||||
@@ -2757,6 +2844,193 @@ trailer << /Root 1 0 R >>
|
||||
assert_eq!((&reply["marked"], &reply["status"]), (&json!(true), &json!("Accepted")), "{reply}");
|
||||
}
|
||||
|
||||
// Contributor-original PDF: a Square, a Circle grouped with it (`/RT /Group`) that keeps its own
|
||||
// author, text, colour, dates and subject, an ordinary reply, a reply to the Circle, a review
|
||||
// status reply and a reply with a `/RT` name that is neither `R` nor `Group`.
|
||||
const GROUP_FIXTURE: &[u8] = b"%PDF-1.7
|
||||
1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj
|
||||
2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj
|
||||
3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 300 200] /Annots [5 0 R 6 0 R 7 0 R 8 0 R 9 0 R 10 0 R] >> endobj
|
||||
5 0 obj << /Type /Annot /Subtype /Square /Rect [20 20 100 80] /NM (sq-primary) /T (Alice) /Contents (Primary) /C [1 0 0] >> endobj
|
||||
6 0 obj << /Type /Annot /Subtype /Circle /Rect [180 120 260 180] /NM (circ-sub) /T (Bob) /Contents (Subordinate) /C [0 0 1] /IRT 5 0 R /RT /Group /M (D:20260101000000) /CreationDate (D:20260101000000) /Subj (Oval) >> endobj
|
||||
7 0 obj << /Type /Annot /Subtype /Text /Rect [120 20 140 40] /NM (reply) /T (Carol) /Contents (Reply) /IRT 5 0 R >> endobj
|
||||
8 0 obj << /Type /Annot /Subtype /Text /Rect [120 50 140 70] /NM (sub-reply) /T (Dan) /Contents (Reply to the subordinate) /IRT 6 0 R >> endobj
|
||||
9 0 obj << /Type /Annot /Subtype /Text /Rect [120 80 140 100] /NM (status) /T (Eve) /IRT 5 0 R /StateModel /Review /State /Accepted >> endobj
|
||||
10 0 obj << /Type /Annot /Subtype /Text /Rect [150 20 170 40] /NM (odd) /T (Fay) /Contents (Odd reply type) /IRT 5 0 R /RT /Bogus >> endobj
|
||||
trailer << /Root 1 0 R >>
|
||||
%%EOF";
|
||||
|
||||
/// ISO 32000-2 §12.5.6.2: an annotation with `/RT /Group` is a subordinate of the group whose
|
||||
/// primary its `/IRT` names. It lists as one comment, with the primary's attributes; the
|
||||
/// subordinate's own are ignored, and a reply to it joins the primary's thread.
|
||||
#[test]
|
||||
fn a_group_lists_as_its_primary() {
|
||||
let dir = workdir("rt-group");
|
||||
std::fs::write(dir.join("group.pdf"), GROUP_FIXTURE).unwrap();
|
||||
let mut a = auto(&dir);
|
||||
let doc = ok(&mut a, "doc_open", json!({ "path": "group.pdf" }))["doc"].as_u64().unwrap();
|
||||
let check = |list: &Value, when: &str| {
|
||||
assert_eq!(list["count"], 1, "{when}: one comment, the group's primary: {list}");
|
||||
let c = &list["comments"][0];
|
||||
assert_eq!((c["id"].as_str(), c["author"].as_str(), c["contents"].as_str()), (Some("sq-primary"), Some("Alice"), Some("Primary")), "{when}");
|
||||
assert_eq!(c["color"], "#FF0000", "{when}: the primary's colour");
|
||||
let group: Vec<&str> = c["group"].as_array().unwrap().iter().filter_map(|m| m["id"].as_str()).collect();
|
||||
assert_eq!(group, ["circ-sub"], "{when}: the subordinate is a member of the group");
|
||||
assert_eq!(c["group"][0]["type"], "Circle", "{when}");
|
||||
let mut replies: Vec<&str> = c["replies"].as_array().unwrap().iter().filter_map(|r| r["id"].as_str()).collect();
|
||||
replies.sort_unstable();
|
||||
assert_eq!(replies, ["odd", "reply", "sub-reply"], "{when}: an unknown /RT reads as a reply, a reply to the subordinate joins the thread");
|
||||
assert_eq!(c["status"], "Accepted", "{when}: a status reply is still a reply");
|
||||
let text = list.to_string();
|
||||
for leak in ["Bob", "Subordinate", "#0000FF"] {
|
||||
assert!(!text.contains(leak), "{when}: the subordinate's own {leak:?} is ignored: {list}");
|
||||
}
|
||||
};
|
||||
// As opened (the inspector), and after an edit (the engine's own list).
|
||||
check(&ok(&mut a, "comment_list", json!({ "doc": doc })), "opened");
|
||||
ok(&mut a, "comment_add", json!({ "doc": doc, "page": 1, "type": "note", "at": [280, 20], "contents": "Other" }));
|
||||
let after = ok(&mut a, "comment_list", json!({ "doc": doc }));
|
||||
let primary = after["comments"].as_array().unwrap().iter().find(|c| c["id"] == "sq-primary").cloned().unwrap();
|
||||
check(&json!({ "count": 1, "comments": [primary] }), "edited");
|
||||
assert_eq!(after["count"], 2, "{after}");
|
||||
|
||||
// Deleting a member deletes just it, as Acrobat does: the subordinate, or the primary, which
|
||||
// leaves the subordinate a comment of its own. One undo step each.
|
||||
ok(&mut a, "comment_delete", json!({ "doc": doc, "id": "circ-sub" }));
|
||||
let left = ok(&mut a, "comment_list", json!({ "doc": doc }));
|
||||
assert_eq!(left["count"], 2, "the primary and the new note are left: {left}");
|
||||
assert!(left.to_string().contains("sq-primary") && !left.to_string().contains("circ-sub"), "{left}");
|
||||
ok(&mut a, "edit_undo", json!({ "doc": doc }));
|
||||
ok(&mut a, "comment_delete", json!({ "doc": doc, "id": "sq-primary" }));
|
||||
let left = ok(&mut a, "comment_list", json!({ "doc": doc }));
|
||||
let ids: Vec<&str> = left["comments"].as_array().unwrap().iter().filter_map(|c| c["id"].as_str()).collect();
|
||||
assert!(ids.contains(&"circ-sub") && !ids.contains(&"sq-primary") && ids.len() == 2, "the new note and the Circle, on its own: {left}");
|
||||
ok(&mut a, "edit_undo", json!({ "doc": doc }));
|
||||
let back = ok(&mut a, "comment_list", json!({ "doc": doc }));
|
||||
let primary = back["comments"].as_array().unwrap().iter().find(|c| c["id"] == "sq-primary").cloned().unwrap();
|
||||
check(&json!({ "count": 1, "comments": [primary] }), "undone");
|
||||
}
|
||||
|
||||
// Contributor-original PDF: group subordinates whose `/IRT` chains loop (each other, and one
|
||||
// itself), and a chain of two subordinates that leads to a primary.
|
||||
const GROUP_LOOP_FIXTURE: &[u8] = b"%PDF-1.7
|
||||
1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj
|
||||
2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj
|
||||
3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 300 200] /Annots [5 0 R 6 0 R 7 0 R 8 0 R 9 0 R 10 0 R] >> endobj
|
||||
5 0 obj << /Type /Annot /Subtype /Circle /Rect [10 10 30 30] /NM (a) /Contents (Loop A) /IRT 6 0 R /RT /Group >> endobj
|
||||
6 0 obj << /Type /Annot /Subtype /Circle /Rect [40 10 60 30] /NM (b) /Contents (Loop B) /IRT 5 0 R /RT /Group >> endobj
|
||||
7 0 obj << /Type /Annot /Subtype /Circle /Rect [70 10 90 30] /NM (self) /Contents (Itself) /IRT 7 0 R /RT /Group >> endobj
|
||||
8 0 obj << /Type /Annot /Subtype /Square /Rect [10 100 60 150] /NM (top) /Contents (Top) >> endobj
|
||||
9 0 obj << /Type /Annot /Subtype /Circle /Rect [70 100 90 120] /NM (mid) /Contents (Middle) /IRT 8 0 R /RT /Group >> endobj
|
||||
10 0 obj << /Type /Annot /Subtype /Circle /Rect [100 100 120 120] /NM (low) /Contents (Lowest) /IRT 9 0 R /RT /Group >> endobj
|
||||
trailer << /Root 1 0 R >>
|
||||
%%EOF";
|
||||
|
||||
/// Looping `/IRT` chains between group subordinates neither hang nor panic, and list as comments
|
||||
/// of their own, as looping replies do; a subordinate of a subordinate joins the group of the
|
||||
/// primary the chain leads to.
|
||||
#[test]
|
||||
fn looping_groups_end_and_chained_groups_reach_their_primary() {
|
||||
let dir = workdir("rt-group-loop");
|
||||
std::fs::write(dir.join("loop.pdf"), GROUP_LOOP_FIXTURE).unwrap();
|
||||
let mut a = auto(&dir);
|
||||
let doc = ok(&mut a, "doc_open", json!({ "path": "loop.pdf" }))["doc"].as_u64().unwrap();
|
||||
let list = ok(&mut a, "comment_list", json!({ "doc": doc }));
|
||||
let comments = list["comments"].as_array().unwrap();
|
||||
let mut ids: Vec<&str> = comments.iter().filter_map(|c| c["id"].as_str()).collect();
|
||||
ids.sort_unstable();
|
||||
assert_eq!(ids, ["a", "b", "self", "top"], "{list}");
|
||||
let top = comments.iter().find(|c| c["id"] == "top").unwrap();
|
||||
let group: Vec<&str> = top["group"].as_array().unwrap().iter().filter_map(|m| m["id"].as_str()).collect();
|
||||
assert_eq!(group, ["mid", "low"], "{list}");
|
||||
assert_eq!(top["replies"], json!([]), "{list}");
|
||||
// Deleting a looping member ends too and takes just it, as any group member goes alone; so
|
||||
// does the lowest subordinate of the chain.
|
||||
ok(&mut a, "comment_delete", json!({ "doc": doc, "id": "a" }));
|
||||
ok(&mut a, "comment_delete", json!({ "doc": doc, "id": "self" }));
|
||||
ok(&mut a, "comment_delete", json!({ "doc": doc, "id": "low" }));
|
||||
let list = ok(&mut a, "comment_list", json!({ "doc": doc }));
|
||||
let mut ids: Vec<&str> = list["comments"].as_array().unwrap().iter().filter_map(|c| c["id"].as_str()).collect();
|
||||
ids.sort_unstable();
|
||||
assert_eq!(ids, ["b", "top"], "{list}");
|
||||
let top = list["comments"].as_array().unwrap().iter().find(|c| c["id"] == "top").cloned().unwrap_or_default();
|
||||
let group: Vec<&str> = top["group"].as_array().into_iter().flatten().filter_map(|m| m["id"].as_str()).collect();
|
||||
assert_eq!(group, ["mid"], "{list}");
|
||||
}
|
||||
|
||||
// Contributor-original PDF: a Replace Text group as earlier PdfCraft builds wrote it, the
|
||||
// strikeout (primary) with empty `/Contents` and the replacement only on the caret (subordinate).
|
||||
const OLD_REPLACE_FIXTURE: &[u8] = b"%PDF-1.7
|
||||
1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj
|
||||
2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj
|
||||
3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 300 200] /Annots [5 0 R 6 0 R] >> endobj
|
||||
5 0 obj << /Type /Annot /Subtype /StrikeOut /Rect [20 100 120 120] /QuadPoints [20 120 120 120 20 100 120 100] /NM (strike) /T (Ada) /Contents () /IT /StrikeOutTextEdit >> endobj
|
||||
6 0 obj << /Type /Annot /Subtype /Caret /Rect [115 95 125 105] /NM (caret) /T (Ada) /Contents (red) /IRT 5 0 R /RT /Group /Subj (Replace Text) >> endobj
|
||||
trailer << /Root 1 0 R >>
|
||||
%%EOF";
|
||||
|
||||
// Contributor-original PDF: a Replace Text group with the caret as the primary (holding the
|
||||
// text, `/IT /Replace`) and the strikeout as its subordinate, each with its own author, colour
|
||||
// and dates.
|
||||
const REPLACE_FIXTURE: &[u8] = b"%PDF-1.7
|
||||
1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj
|
||||
2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj
|
||||
3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 300 200] /Annots [5 0 R 6 0 R] >> endobj
|
||||
5 0 obj << /Type /Annot /Subtype /Caret /Rect [115 95 125 105] /NM (caret) /T (Ada) /C [0 0 1] /Contents (busy) /IT /Replace /Subj (Replace Text) /M (D:20260101000000) >> endobj
|
||||
6 0 obj << /Type /Annot /Subtype /StrikeOut /Rect [20 100 120 120] /QuadPoints [20 120 120 120 20 100 120 100] /NM (strike) /T (Grace) /C [1 0 0] /IRT 5 0 R /RT /Group /IT /StrikeOutTextEdit /Subj (Cross-Out) /M (D:20260101000000) >> endobj
|
||||
trailer << /Root 1 0 R >>
|
||||
%%EOF";
|
||||
|
||||
/// A Replace Text comment lists once, with its replacement text: one made now (the caret is the
|
||||
/// primary and holds it), one with that orientation from another writer, and one saved by an
|
||||
/// earlier PdfCraft (the strikeout primary with no text, the caret holding it), which is read
|
||||
/// leniently and not rewritten.
|
||||
#[test]
|
||||
fn replace_text_lists_its_replacement() {
|
||||
let dir = workdir("rt-group-replace");
|
||||
std::fs::write(dir.join("old.pdf"), OLD_REPLACE_FIXTURE).unwrap();
|
||||
std::fs::write(dir.join("other.pdf"), REPLACE_FIXTURE).unwrap();
|
||||
let mut a = auto(&dir);
|
||||
let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap();
|
||||
ok(&mut a, "comment_add", json!({ "doc": doc, "page": 1, "type": "replace", "find": "Page 1", "contents": "red" }));
|
||||
let list = ok(&mut a, "comment_list", json!({ "doc": doc }));
|
||||
assert_eq!(list["count"], 1, "{list}");
|
||||
let c = &list["comments"][0];
|
||||
assert_eq!(
|
||||
(c["type"].as_str(), c["contents"].as_str(), c["group"][0]["type"].as_str()),
|
||||
(Some("Caret"), Some("red"), Some("StrikeOut")),
|
||||
"{list}"
|
||||
);
|
||||
ok(&mut a, "doc_save", json!({ "doc": doc, "path": "new.pdf" }));
|
||||
let mut b = auto(&dir);
|
||||
for (path, text, primary) in [("new.pdf", "red", "Caret"), ("other.pdf", "busy", "Caret"), ("old.pdf", "red", "StrikeOut")] {
|
||||
let doc = ok(&mut b, "doc_open", json!({ "path": path }))["doc"].as_u64().unwrap();
|
||||
let list = ok(&mut b, "comment_list", json!({ "doc": doc }));
|
||||
let c = &list["comments"][0];
|
||||
assert_eq!(
|
||||
(list["count"].as_u64(), c["type"].as_str(), c["contents"].as_str()),
|
||||
(Some(1), Some(primary), Some(text)),
|
||||
"{path} as opened: {list}"
|
||||
);
|
||||
assert!(!list.to_string().contains("Grace"), "{path}: the subordinate's author is ignored: {list}");
|
||||
// And from the engine's own list, after an edit.
|
||||
ok(&mut b, "comment_add", json!({ "doc": doc, "page": 1, "type": "note", "at": [280, 20], "contents": "Other" }));
|
||||
let list = ok(&mut b, "comment_list", json!({ "doc": doc }));
|
||||
assert_eq!(list["count"], 2, "{path}: {list}");
|
||||
let c = list["comments"].as_array().unwrap().iter().find(|c| c["type"] == primary).cloned().unwrap();
|
||||
assert_eq!(c["contents"], text, "{path} after an edit: {list}");
|
||||
// Replace Text is one comment: deleting either half deletes both, as Acrobat does, in
|
||||
// either orientation.
|
||||
for id in [c["id"].clone(), c["group"][0]["id"].clone()] {
|
||||
ok(&mut b, "comment_delete", json!({ "doc": doc, "id": id }));
|
||||
let left = ok(&mut b, "comment_list", json!({ "doc": doc }));
|
||||
assert_eq!(left["count"], 1, "{path}: deleting {id} leaves only the note: {left}");
|
||||
assert!(!left.to_string().contains("StrikeOut") && !left.to_string().contains("Caret"), "{path}: {left}");
|
||||
ok(&mut b, "edit_undo", json!({ "doc": doc }));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn protecting_through_tools() {
|
||||
let dir = workdir("protect");
|
||||
@@ -3091,6 +3365,113 @@ fn form_fill_picks_one_of_radio_buttons_sharing_an_on_state() {
|
||||
assert!(matches!(a.call("form_fill", &json!({ "doc": doc, "values": { "pick": bad } })), Err(ToolError::InvalidArgs(_))), "{bad}");
|
||||
}
|
||||
}
|
||||
|
||||
/// `form_fill` ticks one kid of a check box whose kids have different on states by naming it
|
||||
/// (ISO 32000-2 §12.7.5.2.3, Table 230), and `form_fields` lists the names and the ticked one.
|
||||
#[test]
|
||||
fn form_fill_ticks_one_kid_of_a_check_box_by_its_on_state() {
|
||||
let objs = [
|
||||
"<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>",
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 400 300] >>",
|
||||
"<< /Type /Page /Parent 2 0 R /Annots [6 0 R 7 0 R] >>",
|
||||
"<< /Fields [5 0 R] /DA (/Helv 0 Tf 0 g) >>",
|
||||
"<< /FT /Btn /T (pair) /V /Off /Kids [6 0 R 7 0 R] >>",
|
||||
"<< /Type /Annot /Subtype /Widget /Parent 5 0 R /AS /Off /Rect [10 250 26 266] /P 3 0 R /AP << /N << /A 8 0 R /Off 8 0 R >> >> >>",
|
||||
"<< /Type /Annot /Subtype /Widget /Parent 5 0 R /AS /Off /Rect [40 250 56 266] /P 3 0 R /AP << /N << /B 8 0 R /Off 8 0 R >> >> >>",
|
||||
"<< /Length 0 >>\nstream\n\nendstream",
|
||||
];
|
||||
let dir = workdir("check-box-kids");
|
||||
std::fs::write(dir.join("form.pdf"), pdf_of(&objs)).unwrap();
|
||||
let mut a = auto(&dir);
|
||||
let doc = ok(&mut a, "doc_open", json!({ "path": "form.pdf" }))["doc"].as_u64().unwrap();
|
||||
let before = ok(&mut a, "form_fields", json!({ "doc": doc }));
|
||||
assert_eq!((&before["fields"][0]["options"], &before["fields"][0]["checked"]), (&json!(["A", "B"]), &Value::Null), "{before}");
|
||||
ok(&mut a, "form_fill", json!({ "doc": doc, "values": { "pair": "A" } }));
|
||||
ok(&mut a, "form_fill", json!({ "doc": doc, "values": { "pair": "B" } }));
|
||||
let after = ok(&mut a, "form_fields", json!({ "doc": doc }));
|
||||
assert_eq!((&after["fields"][0]["value"], &after["fields"][0]["checked"]), (&json!(true), &json!("B")), "{after}");
|
||||
ok(&mut a, "form_fill", json!({ "doc": doc, "values": { "pair": false } }));
|
||||
assert_eq!(ok(&mut a, "form_fields", json!({ "doc": doc }))["fields"][0]["checked"], Value::Null);
|
||||
}
|
||||
|
||||
/// The options `form_fields` reports fill back through `form_fill` to the kid they name, also
|
||||
/// where one kid's `/Opt` export is the other kid's on state: B exports `(A)`, and filling `A`
|
||||
/// still ticks the kid whose on state is A (ISO 32000-2 §12.7.5.2.3, Table 230).
|
||||
#[test]
|
||||
fn form_fill_round_trips_the_reported_options_of_a_check_box_with_a_crossed_export() {
|
||||
let objs = [
|
||||
"<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>",
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 400 300] >>",
|
||||
"<< /Type /Page /Parent 2 0 R /Annots [6 0 R 7 0 R] >>",
|
||||
"<< /Fields [5 0 R] /DA (/Helv 0 Tf 0 g) >>",
|
||||
"<< /FT /Btn /T (pair) /V /Off /Opt [(x) (A)] /Kids [6 0 R 7 0 R] >>",
|
||||
"<< /Type /Annot /Subtype /Widget /Parent 5 0 R /AS /Off /Rect [10 250 26 266] /P 3 0 R /AP << /N << /A 8 0 R /Off 8 0 R >> >> >>",
|
||||
"<< /Type /Annot /Subtype /Widget /Parent 5 0 R /AS /Off /Rect [40 250 56 266] /P 3 0 R /AP << /N << /B 8 0 R /Off 8 0 R >> >> >>",
|
||||
"<< /Length 0 >>
|
||||
stream
|
||||
|
||||
endstream",
|
||||
];
|
||||
let dir = workdir("check-box-crossed-export-fill");
|
||||
std::fs::write(dir.join("form.pdf"), pdf_of(&objs)).unwrap();
|
||||
let mut a = auto(&dir);
|
||||
let doc = ok(&mut a, "doc_open", json!({ "path": "form.pdf" }))["doc"].as_u64().unwrap();
|
||||
let before = ok(&mut a, "form_fields", json!({ "doc": doc }));
|
||||
let options = before["fields"][0]["options"].clone();
|
||||
assert_eq!(options, json!(["A", "B"]), "{before}");
|
||||
for option in ["A", "B"] {
|
||||
ok(&mut a, "form_fill", json!({ "doc": doc, "values": { "pair": option } }));
|
||||
let after = ok(&mut a, "form_fields", json!({ "doc": doc }));
|
||||
assert_eq!(after["fields"][0]["checked"], json!(option), "filling {option}: {after}");
|
||||
}
|
||||
}
|
||||
|
||||
/// `form_fields` on a check box's kids: one option per distinct on state, named by its `/Opt`
|
||||
/// export unless two states share one, and `checked` follows the kid whose `/AS` is on, which
|
||||
/// ISO 32000-2 §12.7.5.2.3 makes decide where `/AS` and `/V` differ.
|
||||
#[test]
|
||||
fn form_fields_lists_a_check_box_by_on_state_and_reports_the_kid_that_is_on() {
|
||||
// Each kid is (on state, /AS).
|
||||
let listed = |name: &str, field: &str, (sa, asa): (&str, &str), (sb, asb): (&str, &str)| {
|
||||
let kid = |on: &str, state: &str, x: u32| {
|
||||
format!(
|
||||
"<< /Type /Annot /Subtype /Widget /Parent 5 0 R /AS /{state} /Rect [{x} 250 {} 266] /P 3 0 R /AP << /N << /{on} 8 0 R /Off 8 0 R >> >> >>",
|
||||
x + 16
|
||||
)
|
||||
};
|
||||
let (wa, wb) = (kid(sa, asa, 10), kid(sb, asb, 40));
|
||||
let objs = [
|
||||
"<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>",
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 400 300] >>",
|
||||
"<< /Type /Page /Parent 2 0 R /Annots [6 0 R 7 0 R] >>",
|
||||
"<< /Fields [5 0 R] /DA (/Helv 0 Tf 0 g) >>",
|
||||
field,
|
||||
&wa,
|
||||
&wb,
|
||||
"<< /Length 0 >>\nstream\n\nendstream",
|
||||
];
|
||||
let dir = workdir(name);
|
||||
std::fs::write(dir.join("form.pdf"), pdf_of(&objs)).unwrap();
|
||||
let mut a = auto(&dir);
|
||||
let doc = ok(&mut a, "doc_open", json!({ "path": "form.pdf" }))["doc"].as_u64().unwrap();
|
||||
let r = ok(&mut a, "form_fields", json!({ "doc": doc }));
|
||||
(r["fields"][0]["options"].clone(), r["fields"][0]["checked"].clone())
|
||||
};
|
||||
// Kids sharing the on state Yes tick together, whatever their exports: not two options.
|
||||
let shared =
|
||||
listed("check-box-shared-state", "<< /FT /Btn /T (pair) /V /Off /Opt [(x) (y)] /Kids [6 0 R 7 0 R] >>", ("Yes", "Off"), ("Yes", "Off"));
|
||||
assert_eq!(shared, (Value::Null, Value::Null));
|
||||
// /V names B, but A's /AS is on: A is the one ticked.
|
||||
let differ = listed("check-box-as-wins", "<< /FT /Btn /T (pair) /V /B /Kids [6 0 R 7 0 R] >>", ("A", "A"), ("B", "Off"));
|
||||
assert_eq!(differ, (json!(["A", "B"]), json!("A")));
|
||||
// Two on states with one export: the states name the options.
|
||||
let same = listed("check-box-same-export", "<< /FT /Btn /T (pair) /V /B /Opt [(x) (x)] /Kids [6 0 R 7 0 R] >>", ("A", "Off"), ("B", "B"));
|
||||
assert_eq!(same, (json!(["A", "B"]), json!("B")));
|
||||
// B's export is A's on state, so naming it would tick A: the states name the options.
|
||||
let crossed = listed("check-box-crossed-export", "<< /FT /Btn /T (pair) /V /B /Opt [(x) (A)] /Kids [6 0 R 7 0 R] >>", ("A", "Off"), ("B", "B"));
|
||||
assert_eq!(crossed, (json!(["A", "B"]), json!("B")));
|
||||
}
|
||||
|
||||
/// A form whose fields are only page widgets (the `/Fields` list is empty) still lists, fills and
|
||||
/// resets through the tools, and the leniency shows up as a repair note.
|
||||
#[test]
|
||||
@@ -5162,6 +5543,28 @@ fn redacting_through_tools() {
|
||||
assert!(matches!(a.call("redact_mark", &json!({ "doc": doc })), Err(ToolError::InvalidArgs(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn applying_redactions_proposes_the_name_with_redacted() {
|
||||
let dir = workdir("redact-save-as");
|
||||
std::fs::write(dir.join("memo.txt"), "Call 555-123-4567 today").unwrap();
|
||||
let mut a = auto(&dir);
|
||||
let made = ok(&mut a, "doc_create", json!({ "from": "text", "path": "memo.txt" }))["doc"].as_u64().unwrap();
|
||||
ok(&mut a, "doc_save", json!({ "doc": made, "path": "contract.pdf" }));
|
||||
let original = std::fs::read(dir.join("contract.pdf")).unwrap();
|
||||
let doc = ok(&mut a, "doc_open", json!({ "path": "contract.pdf" }))["doc"].as_u64().unwrap();
|
||||
ok(&mut a, "redact_mark", json!({ "doc": doc, "pattern": "phone" }));
|
||||
let r = ok(&mut a, "redact_apply", json!({ "doc": doc }));
|
||||
assert_eq!(r["save_as"], "contract_Redacted.pdf");
|
||||
ok(&mut a, "doc_save", json!({ "doc": doc, "path": r["save_as"] }));
|
||||
assert_eq!(std::fs::read(dir.join("contract.pdf")).unwrap(), original, "the opened file is left as it was");
|
||||
let bytes = std::fs::read(dir.join("contract_Redacted.pdf")).unwrap();
|
||||
assert!(!bytes.windows(4).any(|w| w == b"4567"), "the copy has no trace of the number");
|
||||
// Redacting the redacted copy again proposes the same name, with one suffix.
|
||||
let copy = ok(&mut a, "doc_open", json!({ "path": "contract_Redacted.pdf" }))["doc"].as_u64().unwrap();
|
||||
ok(&mut a, "redact_mark", json!({ "doc": copy, "find": "today" }));
|
||||
assert_eq!(ok(&mut a, "redact_apply", json!({ "doc": copy }))["save_as"], "contract_Redacted.pdf");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn redacting_with_a_caller_regex_through_tools() {
|
||||
let dir = workdir("redact-regex");
|
||||
@@ -7274,17 +7677,26 @@ fn drawing_comments_through_tools() {
|
||||
ok(&mut a, "comment_add", json!({ "doc": doc, "page": 2, "type": "replace", "find": "page 2", "contents": "second page", "color": "green" }));
|
||||
let list = ok(&mut a, "comment_list", json!({ "doc": doc, "page": 2 }));
|
||||
let caret = list["comments"].as_array().unwrap().iter().find(|c| c["type"] == "Caret").unwrap().clone();
|
||||
assert_eq!(caret["contents"], "second page", "the replacement is on the caret");
|
||||
assert_eq!(caret["replies"][0]["type"], "StrikeOut", "the strikeout is grouped under the caret");
|
||||
// One comment, the caret (the group's primary, ISO 32000-2 §12.5.6.2), holding the new text;
|
||||
// the strikeout is in its group, not a reply or a comment of its own.
|
||||
assert_eq!(caret["contents"], "second page", "{list}");
|
||||
assert_eq!(caret["replies"], json!([]), "{list}");
|
||||
assert_eq!(caret["group"][0]["type"], "StrikeOut", "{list}");
|
||||
assert!(!list["comments"].as_array().unwrap().iter().any(|c| c["type"] == "StrikeOut"), "{list}");
|
||||
// Review on #5689 (CodeRabbit): the requested colour is the group's, so the primary has it.
|
||||
assert_eq!(caret["replies"][0]["color"], caret["color"], "one colour for the pair: {caret}");
|
||||
assert_eq!(caret["color"], json!("#2E9E5C"), "the requested green, not the caret's default blue: {caret}");
|
||||
// Restyling the caret restyles the proposal, its strikeout too, as one undo step.
|
||||
// The list gives a group the primary's colour alone, so the strikeout's own (`/C`, what it is
|
||||
// drawn in) is read from an XFDF export.
|
||||
let pair = |a: &mut Automation| {
|
||||
let list = ok(a, "comment_list", json!({ "doc": doc, "page": 2 }));
|
||||
let c = list["comments"].as_array().unwrap().iter().find(|c| c["type"] == "Caret").unwrap().clone();
|
||||
(c["color"].clone(), c["replies"][0]["color"].clone())
|
||||
ok(a, "doc_export_data", json!({ "doc": doc, "path": "pair.xfdf", "what": "comments" }));
|
||||
let xfdf = std::fs::read_to_string(dir.join("pair.xfdf")).unwrap();
|
||||
let strike = xfdf.split("<strikeout").nth(1).and_then(|e| e.split('>').next()).unwrap_or_default().to_owned();
|
||||
let color = strike.split("color=\"").nth(1).and_then(|v| v.split('"').next()).map(|v| json!(v)).unwrap_or(Value::Null);
|
||||
(c["color"].clone(), color)
|
||||
};
|
||||
assert_eq!(pair(&mut a), (json!("#2E9E5C"), json!("#2E9E5C")), "the requested green on both, not the caret's default blue: {caret}");
|
||||
// Restyling the caret restyles the proposal, its strikeout too, as one undo step.
|
||||
ok(&mut a, "comment_edit", json!({ "doc": doc, "page": 2, "index": caret["index"], "color": "purple" }));
|
||||
assert_eq!(pair(&mut a), (json!("#8A3FD1"), json!("#8A3FD1")), "the strikeout follows its caret");
|
||||
ok(&mut a, "edit_undo", json!({ "doc": doc }));
|
||||
@@ -9946,6 +10358,38 @@ fn doc_info_describes_set_layer_links() {
|
||||
})
|
||||
);
|
||||
assert_eq!(info["layers"], json!([{ "name": "Red", "visible": true, "initial": true }, { "name": "Green", "visible": false, "initial": false }]));
|
||||
// No /Order: the Layers panel presents none (ISO 32000-2 Table 99), though both are layers.
|
||||
assert_eq!(info["layer_order"], json!([]));
|
||||
}
|
||||
|
||||
/// `doc_info`'s `layer_order` follows the default configuration's /Order (ISO 32000-2 Table 99):
|
||||
/// a group by its 1-based position in `layers` and its name, a nested array one level deeper,
|
||||
/// a label that starts one, and a group /Order does not list left out.
|
||||
#[test]
|
||||
fn doc_info_lists_the_layer_order_tree() {
|
||||
let dir = workdir("layer-order");
|
||||
let pdf = pdf_of(&[
|
||||
"<< /Type /Catalog /Pages 2 0 R /OCProperties << /OCGs [4 0 R 5 0 R 6 0 R 7 0 R] /D << /Order [6 0 R [(Inks) 4 0 R [5 0 R]]] >> >> >>",
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
|
||||
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] >>",
|
||||
"<< /Type /OCG /Name (Red) >>",
|
||||
"<< /Type /OCG /Name (Green) >>",
|
||||
"<< /Type /OCG /Name (Blue) >>",
|
||||
"<< /Type /OCG /Name (Unlisted) >>",
|
||||
]);
|
||||
std::fs::write(dir.join("order.pdf"), pdf).unwrap();
|
||||
let mut a = auto(&dir);
|
||||
let doc = ok(&mut a, "doc_open", json!({ "path": "order.pdf" }))["doc"].as_u64().unwrap();
|
||||
let info = ok(&mut a, "doc_info", json!({ "doc": doc }));
|
||||
assert_eq!(
|
||||
info["layer_order"],
|
||||
json!([
|
||||
{ "depth": 0, "layer": 3, "name": "Blue" },
|
||||
{ "depth": 0, "label": "Inks" },
|
||||
{ "depth": 1, "layer": 1, "name": "Red" },
|
||||
{ "depth": 2, "layer": 2, "name": "Green" },
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
mod close_argument_tests {
|
||||
@@ -11353,6 +11797,49 @@ fn text_box_and_callout_fill_and_border_through_tools() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A custom stamp can carry a dynamic line (#1741): `{name}`, `{date}` and `{time}` are filled in
|
||||
/// when it is placed and drawn under the picture, which keeps its shape; the stamp widens to fit
|
||||
/// the line; a line too long is cut.
|
||||
#[test]
|
||||
fn a_custom_stamp_line_is_filled_in_when_placed() {
|
||||
let dir = workdir("stamp_line");
|
||||
let mut a = auto(&dir);
|
||||
let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap();
|
||||
ok(&mut a, "stamp_custom", json!({ "doc": doc, "page": 2, "path": "b.pdf", "file_page": 2, "at": [100, 150], "name": "Plain" }));
|
||||
ok(
|
||||
&mut a,
|
||||
"stamp_custom",
|
||||
json!({ "doc": doc, "page": 1, "path": "b.pdf", "file_page": 2, "at": [100, 150], "name": "Logo", "author": "Ada", "line": "Received {date} {time} by {name}" }),
|
||||
);
|
||||
// The clock is 2023-11-14 22:13:20, taken as local time.
|
||||
let text = page_text(&mut a, doc)[0].clone();
|
||||
assert!(text.contains("Received Nov 14, 2023 10:13 pm by Ada"), "{text}");
|
||||
let list = ok(&mut a, "comment_list", json!({ "doc": doc }));
|
||||
let rect = |page: u64| {
|
||||
let c = list["comments"].as_array().unwrap().iter().find(|c| c["page"] == page).unwrap();
|
||||
let r: Vec<f64> = c["rect"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect();
|
||||
(r[2] - r[0], r[3] - r[1])
|
||||
};
|
||||
let ((pw, ph), (lw, lh)) = (rect(2), rect(1));
|
||||
// The stamp stays within the natural 200 pt. Its line, at its usual size, is wider than the
|
||||
// picture, so the stamp is wider than the picture's shape with the band added.
|
||||
assert!(lw / lh > pw / ph * (1.0 - 0.22) + 0.01, "widened for the line: {pw}x{ph} vs {lw}x{lh}");
|
||||
// A template within the schema's 200 characters whose filled-in line runs past the limit
|
||||
// (33 times of 8 characters) is cut to exactly 200, not refused.
|
||||
let long = "{time}".repeat(33);
|
||||
assert!(long.chars().count() <= 200);
|
||||
ok(&mut a, "stamp_custom", json!({ "doc": doc, "page": 3, "path": "b.pdf", "file_page": 2, "at": [100, 150], "line": long }));
|
||||
ok(&mut a, "doc_save", json!({ "doc": doc, "path": "stamped.pdf" }));
|
||||
let saved = pdfcraft_cos::Document::open(std::sync::Arc::new(std::fs::read(dir.join("stamped.pdf")).unwrap())).unwrap();
|
||||
let lines: Vec<String> = saved
|
||||
.scan_objects()
|
||||
.filter_map(|(_, o)| o.as_dict()?.get(b"PCByLine")?.as_string().map(pdfcraft_cos::PdfString::to_text))
|
||||
.filter(|l| l.starts_with("10:13 pm"))
|
||||
.collect();
|
||||
assert_eq!(lines.len(), 1, "{lines:?}");
|
||||
assert_eq!(lines[0].chars().count(), 200, "{:?}", lines[0]);
|
||||
}
|
||||
|
||||
/// Three paragraphs: Alpha (two rows), Bravo (one row) and Charlie (two rows), at the leading
|
||||
/// of #2516. Alpha's last baseline is 35.6 pt above Bravo's; moving Alpha down 21.2 pt leaves
|
||||
/// 14.4 pt, Alpha's own leading, so the next read groups the two as one paragraph.
|
||||
@@ -12237,6 +12724,118 @@ fn text_extract_says_when_a_pages_content_was_cut() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
// Contributor-original PDF: a Square on page 1 and, on page 2, a Circle with `/IRT` to it and
|
||||
// `/RT /Group`.
|
||||
const SPREAD_GROUP_FIXTURE: &[u8] = b"%PDF-1.7
|
||||
1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj
|
||||
2 0 obj << /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 >> endobj
|
||||
3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 300 200] /Annots [5 0 R] >> endobj
|
||||
4 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 300 200] /Annots [6 0 R] >> endobj
|
||||
5 0 obj << /Type /Annot /Subtype /Square /Rect [20 20 100 80] /NM (sq-primary) /T (Alice) /Contents (Primary) /C [1 0 0] >> endobj
|
||||
6 0 obj << /Type /Annot /Subtype /Circle /Rect [180 120 260 180] /NM (circ-other-page) /T (Bob) /Contents (Member on page 2) /C [0 0 1] /IRT 5 0 R /RT /Group >> endobj
|
||||
trailer << /Root 1 0 R >>
|
||||
%%EOF";
|
||||
|
||||
/// A group is one page's, as Acrobat reads it: a subordinate whose primary is on another page
|
||||
/// lists as a comment of its own, with its own author and text, not as part of the group or a
|
||||
/// reply, and deleting the primary leaves it. ISO 32000-2 §12.5.6.2 doesn't limit a group to a
|
||||
/// page; Acrobat (desktop and iPad) and PDF-XChange all delete the primary without such a
|
||||
/// subordinate, and Acrobat desktop lists it on its own.
|
||||
#[test]
|
||||
fn a_group_member_on_another_page_is_a_comment_of_its_own() {
|
||||
let dir = workdir("rt-group-spread");
|
||||
std::fs::write(dir.join("group.pdf"), SPREAD_GROUP_FIXTURE).unwrap();
|
||||
let mut a = auto(&dir);
|
||||
let doc = ok(&mut a, "doc_open", json!({ "path": "group.pdf" }))["doc"].as_u64().unwrap();
|
||||
let check = |list: &Value, when: &str| {
|
||||
assert_eq!(list["count"], 2, "{when}: the Square and the Circle, each a comment: {list}");
|
||||
let circle = list["comments"].as_array().unwrap().iter().find(|c| c["id"] == "circ-other-page").cloned().unwrap();
|
||||
assert_eq!((circle["author"].as_str(), circle["contents"].as_str()), (Some("Bob"), Some("Member on page 2")), "{when}");
|
||||
let square = list["comments"].as_array().unwrap().iter().find(|c| c["id"] == "sq-primary").cloned().unwrap();
|
||||
assert!(square["group"].as_array().unwrap().is_empty() && square["replies"].as_array().unwrap().is_empty(), "{when}: {square}");
|
||||
};
|
||||
check(&ok(&mut a, "comment_list", json!({ "doc": doc })), "opened");
|
||||
ok(&mut a, "comment_add", json!({ "doc": doc, "page": 1, "type": "note", "at": [280, 20], "contents": "Other" }));
|
||||
let after = ok(&mut a, "comment_list", json!({ "doc": doc }));
|
||||
let kept: Vec<Value> = after["comments"].as_array().unwrap().iter().filter(|c| c["contents"] != "Other").cloned().collect();
|
||||
check(&json!({ "count": kept.len(), "comments": kept }), "edited");
|
||||
ok(&mut a, "comment_delete", json!({ "doc": doc, "id": "sq-primary" }));
|
||||
let left = ok(&mut a, "comment_list", json!({ "doc": doc }));
|
||||
assert!(left.to_string().contains("circ-other-page"), "deleting the primary leaves the Circle on page 2: {left}");
|
||||
}
|
||||
|
||||
/// #1152 headless: comment_list gives a callout's arrow point, knee and text box; comment_edit's
|
||||
/// `points` moves the arrow point and knee, and `rect` resizes the text box with the arrow left
|
||||
/// where it is.
|
||||
#[test]
|
||||
fn a_callouts_parts_are_listed_and_changed_through_the_tools() {
|
||||
let dir = workdir("callout-parts");
|
||||
let mut a = auto(&dir);
|
||||
let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap();
|
||||
ok(
|
||||
&mut a,
|
||||
"comment_add",
|
||||
json!({ "doc": doc, "page": 1, "type": "callout", "rect": [110, 200, 190, 240], "to": [40, 160], "knee": [80, 220], "contents": "Look" }),
|
||||
);
|
||||
let first = |a: &mut Automation| ok(a, "comment_list", json!({ "doc": doc }))["comments"][0].clone();
|
||||
let near = |v: &Value, want: &[f64]| v.as_array().unwrap().iter().zip(want).all(|(x, w)| (x.as_f64().unwrap() - w).abs() < 0.6);
|
||||
let c = first(&mut a);
|
||||
assert!(near(&c["points"][0], &[40.0, 160.0]) && near(&c["points"][1], &[80.0, 220.0]), "{c}");
|
||||
assert!(near(&c["text_box"], &[110.0, 200.0, 190.0, 240.0]), "{c}");
|
||||
let (page, index) = (c["page"].clone(), c["index"].clone());
|
||||
ok(&mut a, "comment_edit", json!({ "doc": doc, "page": page, "index": index, "points": [[30, 150], [80, 220]] }));
|
||||
let c = first(&mut a);
|
||||
assert!(near(&c["points"][0], &[30.0, 150.0]) && near(&c["text_box"], &[110.0, 200.0, 190.0, 240.0]), "{c}");
|
||||
ok(&mut a, "comment_edit", json!({ "doc": doc, "page": page, "index": index, "rect": [110, 200, 230, 260] }));
|
||||
let c = first(&mut a);
|
||||
assert!(near(&c["text_box"], &[110.0, 200.0, 230.0, 260.0]) && near(&c["points"][0], &[30.0, 150.0]), "{c}");
|
||||
// Three points, or none, aren't a callout's.
|
||||
assert!(matches!(
|
||||
a.call("comment_edit", &json!({ "doc": doc, "page": page, "index": index, "points": [[1, 1], [2, 2], [3, 3]] })),
|
||||
Err(ToolError::Failed(_) | ToolError::InvalidArgs(_))
|
||||
));
|
||||
ok(&mut a, "doc_save", json!({ "doc": doc, "path": "callout.pdf" }));
|
||||
let saved = ok(&mut a, "doc_open", json!({ "path": "callout.pdf" }))["doc"].as_u64().unwrap();
|
||||
let c = ok(&mut a, "comment_list", json!({ "doc": saved }))["comments"][0].clone();
|
||||
assert!(near(&c["points"][0], &[30.0, 150.0]) && near(&c["text_box"], &[110.0, 200.0, 230.0, 260.0]), "after reopening: {c}");
|
||||
// Without a knee, comment_add puts it where Acrobat does: 12 pt out from the middle of the side
|
||||
// facing the point.
|
||||
ok(
|
||||
&mut a,
|
||||
"comment_add",
|
||||
json!({ "doc": saved, "page": 1, "type": "callout", "rect": [300, 200, 380, 240], "to": [250, 160], "contents": "Auto" }),
|
||||
);
|
||||
let list = ok(&mut a, "comment_list", json!({ "doc": saved }))["comments"].clone();
|
||||
let auto = list.as_array().unwrap().iter().find(|c| c["contents"] == "Auto").unwrap();
|
||||
assert!(near(&auto["points"][1], &[288.0, 220.0]), "{auto}");
|
||||
}
|
||||
|
||||
/// comment_popup opens, closes and moves a comment's pop-up, comment_list reports it, and each
|
||||
/// change is one undo step with its own label.
|
||||
#[test]
|
||||
fn comment_popups_are_opened_moved_and_listed() {
|
||||
let dir = workdir("popup");
|
||||
let mut a = auto(&dir);
|
||||
let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap();
|
||||
ok(&mut a, "comment_add", json!({ "doc": doc, "page": 1, "type": "note", "at": [30.0, 40.0], "contents": "Look here" }));
|
||||
let listed = ok(&mut a, "comment_list", json!({ "doc": doc }));
|
||||
let note = &listed["comments"][0];
|
||||
assert_eq!(note["popup"]["open"], json!(false), "{listed}");
|
||||
let id = note["id"].as_str().unwrap().to_string();
|
||||
let opened = ok(&mut a, "comment_popup", json!({ "doc": doc, "id": id, "open": true }));
|
||||
assert_eq!(opened["undo"], json!("Open comment pop-up"), "{opened}");
|
||||
let listed = ok(&mut a, "comment_list", json!({ "doc": doc }));
|
||||
assert_eq!(listed["comments"][0]["popup"]["open"], json!(true));
|
||||
let moved = ok(&mut a, "comment_popup", json!({ "doc": doc, "id": id, "rect": [60.0, 60.0, 180.0, 140.0] }));
|
||||
assert_eq!(moved["undo"], json!("Move comment pop-up"));
|
||||
let listed = ok(&mut a, "comment_list", json!({ "doc": doc }));
|
||||
assert_eq!(listed["comments"][0]["popup"]["rect"], json!([60.0, 60.0, 180.0, 140.0]), "{listed}");
|
||||
let closed = ok(&mut a, "comment_popup", json!({ "doc": doc, "id": id, "open": false }));
|
||||
assert_eq!(closed["undo"], json!("Close comment pop-up"));
|
||||
assert!(matches!(err(&mut a, "comment_popup", json!({ "doc": doc, "id": id })), ToolError::InvalidArgs(_)));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// #3005: a table and a small signature drawn inside one transparency-group Form XObject (how
|
||||
/// HTML-to-PDF converters write a block with a translucent picture). Edit a PDF sees one piece
|
||||
/// of artwork and no text; `image_edit ungroup` draws it in place with the same pixels, its
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
//! `text_find` on a ligature glyph named in the encoding and on a word divided by a hyphen at a
|
||||
//! line end.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use pdfcraft_automation::{Automation, Content};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// A fresh directory for one test.
|
||||
fn tmp(name: &str) -> PathBuf {
|
||||
let d = std::env::temp_dir().join(format!("pdfcraft-find-text-{}-{name}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
d
|
||||
}
|
||||
|
||||
fn ok(a: &mut Automation, tool: &str, args: Value) -> Value {
|
||||
match a.call(tool, &args) {
|
||||
Ok(mut c) => match c.remove(0) {
|
||||
Content::Json(v) => v,
|
||||
other => panic!("{tool}: expected JSON, got {other:?}"),
|
||||
},
|
||||
Err(e) => panic!("{tool} {args}: {e}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// One page: `of<fi>ce` in a Helvetica whose code 128 is named `/fi`, and `exam-` at the end of
|
||||
/// one line with `ple` starting the next.
|
||||
fn find_pdf() -> Vec<u8> {
|
||||
let body = "BT /F2 14 Tf 90 700 Td (of\\200ce) Tj ET\nBT /F1 14 Tf 90 650 Td (exam-) Tj 0 -16 Td (ple) Tj ET\n";
|
||||
let objs = [
|
||||
"<< /Type /Catalog /Pages 2 0 R >>".to_string(),
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_string(),
|
||||
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R /Resources << /Font << /F1 5 0 R /F2 6 0 R >> >> >>".to_string(),
|
||||
format!("<< /Length {} >>\nstream\n{body}\nendstream", body.len()),
|
||||
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".to_string(),
|
||||
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding << /Type /Encoding /BaseEncoding /WinAnsiEncoding /Differences [128 /fi] >> >>"
|
||||
.to_string(),
|
||||
];
|
||||
let mut out = b"%PDF-1.7\n".to_vec();
|
||||
let mut offsets = Vec::new();
|
||||
for (i, o) in objs.iter().enumerate() {
|
||||
offsets.push(out.len());
|
||||
out.extend_from_slice(format!("{} 0 obj\n{o}\nendobj\n", i + 1).as_bytes());
|
||||
}
|
||||
let xref = out.len();
|
||||
out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes());
|
||||
for 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
|
||||
}
|
||||
|
||||
/// "office" finds the ligature, and "example" both halves of the divided word, highlighted line by
|
||||
/// line; the hyphenated form is still found as written.
|
||||
#[test]
|
||||
fn text_find_matches_ligatures_and_words_divided_at_a_line_end() {
|
||||
let dir = tmp("forms");
|
||||
std::fs::write(dir.join("find.pdf"), find_pdf()).unwrap();
|
||||
let mut a = Automation::new().with_root(&dir).unwrap();
|
||||
let doc = ok(&mut a, "doc_open", json!({ "path": "find.pdf" }))["doc"].as_u64().unwrap();
|
||||
let find = |a: &mut Automation, q: &str| ok(a, "text_find", json!({ "doc": doc, "query": q }));
|
||||
|
||||
let office = find(&mut a, "office");
|
||||
assert_eq!(office["count"], 1, "{office}");
|
||||
let rects = office["matches"][0]["rects"].as_array().unwrap();
|
||||
assert_eq!(rects.len(), 1);
|
||||
assert!((rects[0][0].as_f64().unwrap() - 90.0).abs() < 0.5, "from the left edge of the o: {rects:?}");
|
||||
|
||||
let example = find(&mut a, "example");
|
||||
assert_eq!(example["count"], 1, "{example}");
|
||||
assert_eq!(example["matches"][0]["text"], "exam-\nple");
|
||||
let rects = example["matches"][0]["rects"].as_array().unwrap();
|
||||
assert_eq!(rects.len(), 2, "one highlight on each line: {rects:?}");
|
||||
let top = |k: usize| rects[k][1].as_f64().unwrap();
|
||||
assert!(top(1) > top(0) + 10.0, "the second on the next line down: {rects:?}");
|
||||
|
||||
for q in ["exam-ple", "Exam- ple", "exam-"] {
|
||||
assert_eq!(find(&mut a, q)["count"], 1, "{q}");
|
||||
}
|
||||
assert_eq!(find(&mut a, "examples")["count"], 0);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
//! Which options a list box has selected, through the tool table (ISO 32000-2 Table 234, `/I`).
|
||||
|
||||
use pdfcraft_automation::{Automation, Content};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
fn tool(a: &mut Automation, name: &str, args: Value) -> Value {
|
||||
match a.call(name, &args).unwrap().remove(0) {
|
||||
Content::Json(value) => value,
|
||||
other => panic!("expected JSON: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// A PDF of the given objects (numbered from 1).
|
||||
fn pdf_of(objs: &[&str]) -> Vec<u8> {
|
||||
let mut out = b"%PDF-1.7\n".to_vec();
|
||||
let mut offsets = Vec::new();
|
||||
for (i, o) in objs.iter().enumerate() {
|
||||
offsets.push(out.len());
|
||||
out.extend_from_slice(format!("{} 0 obj\n{o}\nendobj\n", i + 1).as_bytes());
|
||||
}
|
||||
let xref = out.len();
|
||||
out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes());
|
||||
for o in offsets {
|
||||
out.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());
|
||||
}
|
||||
out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes());
|
||||
out
|
||||
}
|
||||
|
||||
fn open(test: &str) -> (Automation, u64, std::path::PathBuf) {
|
||||
let dir = std::env::temp_dir().join(format!("pdfcraft-list-selection-{test}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let bytes = pdf_of(&[
|
||||
"<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [4 0 R 6 0 R] /NeedAppearances true /DA (/Helv 10 Tf 0 g) /DR << /Font << /Helv 5 0 R >> >> >> >>",
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 400 400] >>",
|
||||
"<< /Type /Page /Parent 2 0 R /Annots [4 0 R 6 0 R] >>",
|
||||
"<< /Type /Annot /Subtype /Widget /FT /Ch /T (D_dup) /Opt [[(1) (One-A)] [(1) (One-B)] [(2) (Two)]] /V (1) /I [1] /Rect [50 250 200 320] /P 3 0 R /F 4 >>",
|
||||
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>",
|
||||
"<< /Type /Annot /Subtype /Widget /FT /Ch /T (H_twovals) /Opt [[(TW) (Taiwan)] [(JP) (Japan)] [(US) (United States)]] /V [(TW) (JP)] /Rect [50 150 200 220] /P 3 0 R /F 4 >>",
|
||||
]);
|
||||
std::fs::write(dir.join("choice.pdf"), bytes).unwrap();
|
||||
let mut a = Automation::new().with_root(&dir).unwrap();
|
||||
let id = tool(&mut a, "doc_open", json!({ "path": "choice.pdf" }))["doc"].as_u64().unwrap();
|
||||
(a, id, dir)
|
||||
}
|
||||
|
||||
fn field(a: &mut Automation, doc: u64, name: &str) -> Value {
|
||||
let all = tool(a, "form_fields", json!({ "doc": doc }));
|
||||
all["fields"].as_array().unwrap().iter().find(|f| f["name"] == name).unwrap().clone()
|
||||
}
|
||||
|
||||
/// Two options share the export value `1`: `selected` says which one `/I` picks, and filling the
|
||||
/// field with an option's label picks that option.
|
||||
#[test]
|
||||
fn form_fields_reports_which_of_two_options_with_one_export_value_is_selected() {
|
||||
let (mut a, doc, dir) = open("dup");
|
||||
let d = field(&mut a, doc, "D_dup");
|
||||
assert_eq!(d["value"], "1");
|
||||
assert_eq!(d["selected"], json!([2]), "One-B, the second option: {d}");
|
||||
tool(&mut a, "form_fill", json!({ "doc": doc, "values": { "D_dup": "One-A" } }));
|
||||
let d = field(&mut a, doc, "D_dup");
|
||||
assert_eq!((d["value"].clone(), d["selected"].clone()), (json!("1"), json!([1])), "{d}");
|
||||
tool(&mut a, "form_fill", json!({ "doc": doc, "values": { "D_dup": "One-B" } }));
|
||||
let d = field(&mut a, doc, "D_dup");
|
||||
assert_eq!(d["selected"], json!([2]));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A list box without MultiSelect given `/V [(TW) (JP)]` reports Taiwan alone (ISO 32000-2
|
||||
/// Table 233: "at most one item shall be selected"), and filling it writes one value.
|
||||
#[test]
|
||||
fn form_fields_reports_one_value_for_a_single_select_list_given_two() {
|
||||
let (mut a, doc, dir) = open("twovals");
|
||||
let h = field(&mut a, doc, "H_twovals");
|
||||
assert_eq!((h["value"].clone(), h["selected"].clone()), (json!("TW"), json!([1])), "{h}");
|
||||
tool(&mut a, "form_fill", json!({ "doc": doc, "values": { "H_twovals": "United States" } }));
|
||||
let h = field(&mut a, doc, "H_twovals");
|
||||
assert_eq!((h["value"].clone(), h["selected"].clone()), (json!("US"), json!([3])), "{h}");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
@@ -9,8 +9,10 @@ mod batch;
|
||||
mod batch_failures;
|
||||
mod batch_secrets;
|
||||
mod button_caption;
|
||||
mod find_text;
|
||||
mod form_bulk;
|
||||
mod hostile_args;
|
||||
mod list_selection;
|
||||
mod model_3d;
|
||||
mod model_render;
|
||||
mod optimize_content_boundaries;
|
||||
|
||||
@@ -96,6 +96,33 @@ fn a_clean_page_renders_to_the_png_alone() {
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
/// An image whose Indexed lookup table is too short (ISO 32000-2 §8.6.6.3) is drawn recovered, and
|
||||
/// `page_render` says so in the words `pdfcraft-cli render` prints.
|
||||
#[test]
|
||||
fn page_render_reports_a_recovered_malformed_indexed_image() {
|
||||
let dir = std::env::temp_dir().join(format!("pdfcraft-render-warnings-indexed-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let content = "q 200 0 0 200 0 0 cm /Im Do Q";
|
||||
// hival 7 over DeviceRGB needs 24 bytes; the table holds 6.
|
||||
let pdf = format!(
|
||||
"%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n\
|
||||
2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj\n\
|
||||
3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Resources << /XObject << /Im 5 0 R >> >> /Contents 4 0 R >> endobj\n\
|
||||
4 0 obj << /Length {} >> stream\n{content}\nendstream endobj\n\
|
||||
5 0 obj << /Type /XObject /Subtype /Image /Width 2 /Height 1 /BitsPerComponent 8 /ColorSpace [/Indexed /DeviceRGB 7 <FF0000 00FF00>] /Filter /ASCIIHexDecode /Length 5 >> stream\n0001>\nendstream endobj\n\
|
||||
trailer << /Root 1 0 R >>\n%%EOF",
|
||||
content.len()
|
||||
);
|
||||
std::fs::write(dir.join("indexed.pdf"), pdf).unwrap();
|
||||
let mut a = Automation::new().with_root(&dir).unwrap();
|
||||
let doc = open(&mut a, "indexed.pdf");
|
||||
let out = a.call("page_render", &json!({ "doc": doc, "page": 1, "dpi": 72 })).unwrap();
|
||||
let Some(Content::Json(report)) = out.get(1) else { panic!("expected the warnings as JSON: {out:?}") };
|
||||
assert_eq!(report["warnings"], json!(["an image with a malformed Indexed colour table may be drawn wrongly or not at all"]));
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
/// Over MCP the warnings are a text block after the image and the call's `structuredContent`.
|
||||
#[cfg(feature = "mcp")]
|
||||
#[test]
|
||||
|
||||
+145
-5
@@ -6844,6 +6844,142 @@ fn reading_follows_forms_however_their_resources_are_stored() {
|
||||
}
|
||||
}
|
||||
|
||||
/// #3503: a form XObject's `/BBox` clips its content, so text drawn outside it is not shown and
|
||||
/// should not be read either -- matching the renderer, which already honours the clip.
|
||||
#[test]
|
||||
fn form_bbox_clips_text_from_reading() {
|
||||
let page = stream("", "/Fm Do");
|
||||
let fm = stream(
|
||||
"/Type /XObject /Subtype /Form /BBox [0 0 50 50] /Resources << /Font << /F1 6 0 R >> >>",
|
||||
"BT /F1 12 Tf 5 5 Td (INSIDE) Tj ET BT /F1 12 Tf 100 100 Td (OUTSIDE) Tj ET",
|
||||
);
|
||||
let doc = build(&[
|
||||
"<< /Type /Catalog /Pages 2 0 R >>",
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
|
||||
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Resources << /XObject << /Fm 5 0 R >> >> /Contents 4 0 R >>",
|
||||
&page,
|
||||
&fm,
|
||||
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",
|
||||
]);
|
||||
let texts: Vec<String> = text::reading_blocks(&doc, 0).unwrap().into_iter().map(|b| b.text).collect();
|
||||
assert_eq!(texts, ["INSIDE"]);
|
||||
}
|
||||
|
||||
/// #3503: a page's own `re`/`W`/`n` clip (not a form's `/BBox`) hides text outside it the same
|
||||
/// way, and `Q` lifts it again -- the clip is scoped to its `q`/`Q` like the rest of the graphics
|
||||
/// state, not a one-way switch.
|
||||
#[test]
|
||||
fn page_re_w_n_clip_hides_text_from_reading_until_q() {
|
||||
let page = stream(
|
||||
"",
|
||||
"q 0 0 50 50 re W n BT /F1 12 Tf 5 5 Td (INSIDE) Tj ET BT /F1 12 Tf 100 100 Td (HIDDEN) Tj ET Q BT /F1 12 Tf 100 100 Td (AFTER) Tj ET",
|
||||
);
|
||||
let doc = build(&[
|
||||
"<< /Type /Catalog /Pages 2 0 R >>",
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
|
||||
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Resources << /Font << /F1 5 0 R >> >> /Contents 4 0 R >>",
|
||||
&page,
|
||||
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",
|
||||
]);
|
||||
let texts: Vec<String> = text::reading_blocks(&doc, 0).unwrap().into_iter().map(|b| b.text).collect();
|
||||
assert_eq!(texts, ["INSIDE", "AFTER"]);
|
||||
}
|
||||
|
||||
/// The text `reading_blocks` reads on a 400 × 400 pt page drawing `content` with Helvetica as
|
||||
/// `/F1`, and forms `/Fa` and `/Fb` (objects 6 and 7) with the given dictionary entries and content.
|
||||
fn read_clipped(content: &str, forms: [(&str, &str); 2]) -> Vec<String> {
|
||||
let font = "/Font << /F1 5 0 R >>";
|
||||
let resources = format!("<< {font} /XObject << /Fa 6 0 R /Fb 7 0 R >> >>");
|
||||
let form = |(dict, body): (&str, &str)| stream(&format!("/Type /XObject /Subtype /Form {dict} /Resources {resources}"), body);
|
||||
let doc = build(&[
|
||||
"<< /Type /Catalog /Pages 2 0 R >>",
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
|
||||
&format!("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 400 400] /Resources {resources} /Contents 4 0 R >>"),
|
||||
&stream("", content),
|
||||
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",
|
||||
&form(forms[0]),
|
||||
&form(forms[1]),
|
||||
]);
|
||||
text::reading_blocks(&doc, 0).unwrap().into_iter().map(|b| b.text).collect()
|
||||
}
|
||||
|
||||
/// #5075 review: a `/BBox` with anything but four numbers is no bound. Reading the numbers it
|
||||
/// happens to hold (`[0 /Bad 0 50 50]` as `[0 0 50 50]`) invented a clip and hid real text.
|
||||
#[test]
|
||||
fn a_malformed_form_bbox_clips_nothing() {
|
||||
let body = "BT /F1 12 Tf 5 5 Td (INSIDE) Tj ET BT /F1 12 Tf 100 100 Td (OUTSIDE) Tj ET";
|
||||
for bbox in ["[0 /Bad 0 50 50]", "[0 0 50]", "[0 0 50 50 60]", "[0 (x) 50 50]"] {
|
||||
let texts = read_clipped("/Fa Do", [(&format!("/BBox {bbox}"), body), ("", "")]);
|
||||
assert_eq!(texts, ["INSIDE", "OUTSIDE"], "/BBox {bbox}");
|
||||
}
|
||||
}
|
||||
|
||||
/// #5075 review: a clipping path of several rectangles clips to all of them, not to the last one
|
||||
/// drawn (text seen through the first rectangle was hidden), and not to the box around them
|
||||
/// either (text in the gap between them was read, though nothing of it shows).
|
||||
#[test]
|
||||
fn a_clip_of_several_rectangles_keeps_text_in_each() {
|
||||
let content = "q 0 0 50 50 re 100 100 50 50 re W n BT /F1 12 Tf 5 5 Td (FIRST) Tj ET BT /F1 12 Tf 105 105 Td (SECOND) Tj ET \
|
||||
BT /F1 12 Tf 60 60 Td (GAP) Tj ET BT /F1 12 Tf 300 300 Td (OUTSIDE) Tj ET Q";
|
||||
assert_eq!(read_clipped(content, [("", ""), ("", "")]), ["FIRST", "SECOND"]);
|
||||
}
|
||||
|
||||
/// #5075 review: a form's `/BBox` clips however thin it is and wherever its matrix puts it. A box
|
||||
/// one point by 1e-10 was taken for no box (its area fell under a fixed threshold), and one moved
|
||||
/// 1e12 points away lost its area to rounding; either way the text outside it was read.
|
||||
#[test]
|
||||
fn a_thin_or_far_off_form_bbox_still_clips() {
|
||||
let after = "BT /F1 12 Tf 5 300 Td (AFTER) Tj ET";
|
||||
let body = "BT /F1 12 Tf 5 5 Td (INSIDE) Tj ET BT /F1 12 Tf 300 300 Td (OUTSIDE) Tj ET";
|
||||
let sorted = |mut v: Vec<String>| {
|
||||
v.sort();
|
||||
v
|
||||
};
|
||||
let thin = read_clipped(&format!("/Fa Do {after}"), [("/BBox [0 0 1 1e-10]", body), ("", "")]);
|
||||
assert_eq!(thin, ["AFTER"], "a thin /BBox");
|
||||
let far = read_clipped(&format!("/Fa Do {after}"), [("/Matrix [1 0 0 1 1e12 1e12] /BBox [0 0 100 100]", body), ("", "")]);
|
||||
assert_eq!(sorted(far), ["AFTER", "INSIDE"], "a /BBox 1e12 points away");
|
||||
}
|
||||
|
||||
/// #5075 review: a clip of no area has no inside, so nothing drawn under it shows (ISO 32000-2
|
||||
/// §8.5.4). It was taken for no clip at all, and everything under it was read.
|
||||
#[test]
|
||||
fn a_clip_of_no_area_shows_nothing() {
|
||||
let content = "q 0 0 100 0 re W n BT /F1 12 Tf 5 5 Td (HIDDEN) Tj ET Q BT /F1 12 Tf 5 300 Td (AFTER) Tj ET";
|
||||
assert_eq!(read_clipped(content, [("", ""), ("", "")]), ["AFTER"]);
|
||||
}
|
||||
|
||||
/// #5075 review: what shows is the intersection of every clip in force. A long run that crosses a
|
||||
/// page clip and, apart from it, a form's `/BBox` overlaps each of them but shows in neither, as it
|
||||
/// does not when one form's `/BBox` lies apart from the one of the form it is drawn in.
|
||||
#[test]
|
||||
fn disjoint_clips_show_nothing_between_them() {
|
||||
let run = "BT /F1 12 Tf 5 10 Td (AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA) Tj ET";
|
||||
let after = "BT /F1 12 Tf 5 300 Td (AFTER) Tj ET";
|
||||
// A page clip and a form's `/BBox` side by side.
|
||||
let page_clip = format!("q 0 0 50 50 re W n /Fa Do Q {after}");
|
||||
assert_eq!(read_clipped(&page_clip, [("/BBox [100 0 150 50]", run), ("", "")]), ["AFTER"]);
|
||||
// A form's `/BBox` and the `/BBox` of the form inside it, side by side.
|
||||
let nested = format!("/Fa Do {after}");
|
||||
assert_eq!(read_clipped(&nested, [("/BBox [0 0 50 50]", "/Fb Do"), ("/BBox [100 0 150 50]", run)]), ["AFTER"]);
|
||||
}
|
||||
|
||||
/// #5075 review: a clip turned with its matrix keeps its turned shape. Its upright bounding box
|
||||
/// takes in corners it does not cover, and text there was read although it is clipped away.
|
||||
#[test]
|
||||
fn a_turned_clip_hides_text_in_the_corners_of_its_bounding_box() {
|
||||
// A 100 pt square turned 45° about (200, 0): a diamond with its lower corner at (200, 0).
|
||||
// Undone straight after the clip, so the text is drawn upright on the page.
|
||||
let (turn, undo) =
|
||||
("0.70710678 0.70710678 -0.70710678 0.70710678 200 0 cm", "0.70710678 -0.70710678 0.70710678 0.70710678 -141.421356 141.421356 cm");
|
||||
let texts = "BT /F1 6 Tf 132 3 Td (CORNER) Tj ET BT /F1 6 Tf 195 65 Td (CENTRE) Tj ET";
|
||||
let page_clip = format!("q {turn} 0 0 100 100 re W n {undo} {texts} Q");
|
||||
assert_eq!(read_clipped(&page_clip, [("", ""), ("", "")]), ["CENTRE"], "a turned page clip");
|
||||
// The same diamond as a form's `/BBox`, under its `/Matrix`.
|
||||
let matrix = "/Matrix [0.70710678 0.70710678 -0.70710678 0.70710678 200 0] /BBox [0 0 100 100]";
|
||||
assert_eq!(read_clipped("/Fa Do", [(matrix, &format!("{undo} {texts}")), ("", "")]), ["CENTRE"], "a turned form /BBox");
|
||||
}
|
||||
|
||||
/// A chain of forms, each drawing the next twenty times, twelve deep: within the depth cap but
|
||||
/// 20^11 visits without a budget. Reading stops at the page's visit budget instead of hanging.
|
||||
#[test]
|
||||
@@ -6958,24 +7094,28 @@ fn forms_that_fan_out_a_hundred_ways_stop_quickly_and_say_so() {
|
||||
|
||||
/// Forms that draw themselves or each other, have no resources, a malformed matrix, or are
|
||||
/// missing are read once (or skipped) without panicking or looping.
|
||||
///
|
||||
/// `/BBox [0 0 20 420]` is wide enough to hold every form's own text below (#3503 clips a form's
|
||||
/// content to its `/BBox`; this test is about the loop and resource handling, not clipping).
|
||||
#[test]
|
||||
fn hostile_form_xobjects_are_read_once() {
|
||||
let page = stream("", "/Loop Do /A Do /NoRes Do /Bad Do /Missing Do /F1 Do");
|
||||
let font = "/Font << /F1 5 0 R >>";
|
||||
let lp = stream(
|
||||
&format!("/Subtype /Form /BBox [0 0 9 9] /Resources << {font} /XObject << /Loop 6 0 R >> >>"),
|
||||
&format!("/Subtype /Form /BBox [0 0 20 420] /Resources << {font} /XObject << /Loop 6 0 R >> >>"),
|
||||
"/Loop Do BT /F1 10 Tf 10 10 Td (once) Tj ET",
|
||||
);
|
||||
let a = stream(
|
||||
&format!("/Subtype /Form /BBox [0 0 9 9] /Resources << {font} /XObject << /B 8 0 R >> >>"),
|
||||
&format!("/Subtype /Form /BBox [0 0 20 420] /Resources << {font} /XObject << /B 8 0 R >> >>"),
|
||||
"/B Do BT /F1 10 Tf 10 100 Td (from a) Tj ET",
|
||||
);
|
||||
let b = stream(
|
||||
&format!("/Subtype /Form /BBox [0 0 9 9] /Resources << {font} /XObject << /A 7 0 R >> >>"),
|
||||
&format!("/Subtype /Form /BBox [0 0 20 420] /Resources << {font} /XObject << /A 7 0 R >> >>"),
|
||||
"/A Do BT /F1 10 Tf 10 200 Td (from b) Tj ET",
|
||||
);
|
||||
let nores = stream("/Subtype /Form /BBox [0 0 9 9]", "BT /F1 10 Tf 10 300 Td (inherited) Tj ET");
|
||||
let bad = stream(&format!("/Subtype /Form /BBox [0 0 9 9] /Matrix [1 0 0] /Resources << {font} >>"), "BT /F1 10 Tf 10 400 Td (bad matrix) Tj ET");
|
||||
let nores = stream("/Subtype /Form /BBox [0 0 20 420]", "BT /F1 10 Tf 10 300 Td (inherited) Tj ET");
|
||||
let bad =
|
||||
stream(&format!("/Subtype /Form /BBox [0 0 20 420] /Matrix [1 0 0] /Resources << {font} >>"), "BT /F1 10 Tf 10 400 Td (bad matrix) Tj ET");
|
||||
let doc = build(&[
|
||||
"<< /Type /Catalog /Pages 2 0 R >>",
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
|
||||
|
||||
@@ -155,6 +155,66 @@ impl TextLine {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The clip regions reading uses (#3503): intersected regions keep only what both cover,
|
||||
/// regions apart leave nothing, turned ones keep their shape, and touching is not showing.
|
||||
#[test]
|
||||
fn clip_regions_intersect_and_show_what_they_cover() {
|
||||
use interp::{intersect, region, shows};
|
||||
let square = |x: f64, y: f64| region(&Matrix::IDENTITY, [x, y, x + 10.0, y + 10.0]).unwrap();
|
||||
let area = |p: &[[f64; 2]]| p.iter().zip(p.iter().cycle().skip(1)).map(|(a, b)| a[0] * b[1] - b[0] * a[1]).sum::<f64>().abs() / 2.0;
|
||||
// Squares overlapping by half each way share a quarter.
|
||||
let both = intersect(&square(0.0, 0.0), &square(5.0, 5.0));
|
||||
assert!((area(&both) - 25.0).abs() < 1e-9, "{both:?}");
|
||||
assert!(shows([6.0, 6.0, 7.0, 7.0], &both) && !shows([1.0, 1.0, 2.0, 2.0], &both));
|
||||
// Squares apart share nothing, so nothing shows, not even a box across both.
|
||||
let none = intersect(&square(0.0, 0.0), &square(20.0, 0.0));
|
||||
assert!(!shows([-100.0, -100.0, 100.0, 100.0], &none), "{none:?}");
|
||||
// Squares that meet only along an edge share no area either: a box across that edge
|
||||
// does not show (#5075 review).
|
||||
let edge = intersect(&square(0.0, 0.0), &square(10.0, 0.0));
|
||||
assert!(!shows([8.0, 2.0, 12.0, 4.0], &edge), "{edge:?}");
|
||||
// Nothing intersected with anything is nothing, whichever side it is on.
|
||||
assert!(!shows([1.0, 1.0, 2.0, 2.0], &intersect(&square(0.0, 0.0), &Vec::new())));
|
||||
assert!(!shows([1.0, 1.0, 2.0, 2.0], &intersect(&Vec::new(), &square(0.0, 0.0))));
|
||||
// A box touching an edge shares no area; one a hair inside does.
|
||||
assert!(!shows([10.0, 0.0, 12.0, 5.0], &square(0.0, 0.0)));
|
||||
assert!(shows([9.99, 0.0, 12.0, 5.0], &square(0.0, 0.0)));
|
||||
// A square turned 45° keeps its diamond shape: a box in the corner of its bounding box is
|
||||
// outside it, the centre is inside.
|
||||
let c = std::f64::consts::FRAC_1_SQRT_2;
|
||||
let diamond = region(&Matrix([c, c, -c, c, 0.0, 0.0]), [0.0, 0.0, 10.0, 10.0]).unwrap();
|
||||
assert!(!shows([-7.0, 0.0, -6.5, 0.5], &diamond) && shows([-0.5, 6.5, 0.5, 7.5], &diamond));
|
||||
// A corner repeated (an edge of no length) does not hide what the region covers.
|
||||
let doubled = vec![[0.0, 0.0], [10.0, 0.0], [10.0, 0.0], [10.0, 10.0], [0.0, 10.0]];
|
||||
assert!(shows([4.0, 4.0, 6.0, 6.0], &doubled));
|
||||
// A rectangle of no area is a region that covers nothing; a corner that isn't finite
|
||||
// gives no region to clip with at all.
|
||||
let flat = region(&Matrix::IDENTITY, [0.0, 0.0, 10.0, 0.0]).unwrap();
|
||||
assert!(!shows([-100.0, -100.0, 100.0, 100.0], &flat), "{flat:?}");
|
||||
assert!(region(&Matrix::IDENTITY, [0.0, 0.0, f64::INFINITY, 10.0]).is_none());
|
||||
// However thin, a rectangle with area keeps it, and so does one far from the origin.
|
||||
let thin = region(&Matrix::IDENTITY, [0.0, 0.0, 1.0, 1e-10]).unwrap();
|
||||
assert!(shows([0.25, 0.0, 0.75, 1.0], &thin) && !shows([0.25, 1.0, 0.75, 2.0], &thin));
|
||||
let far = region(&Matrix([1.0, 0.0, 0.0, 1.0, 1e12, 1e12]), [0.0, 0.0, 100.0, 100.0]).unwrap();
|
||||
assert!(shows([1e12 + 10.0, 1e12 + 10.0, 1e12 + 20.0, 1e12 + 20.0], &far) && !shows([1e12 + 200.0, 1e12, 1e12 + 300.0, 1e12 + 10.0], &far));
|
||||
}
|
||||
|
||||
/// A stream that sets clip after clip, each turned a little more, keeps its region bounded:
|
||||
/// past the corner cap a region becomes its bounding box, which still holds all it held.
|
||||
#[test]
|
||||
fn clip_after_clip_keeps_the_region_bounded() {
|
||||
use interp::{intersect, region, shows};
|
||||
let mut clip = region(&Matrix::IDENTITY, [-100.0, -100.0, 100.0, 100.0]).unwrap();
|
||||
for i in 1..=10_000 {
|
||||
let (s, c) = (f64::from(i) * 0.001).sin_cos();
|
||||
let turned = region(&Matrix([c, s, -s, c, 0.0, 0.0]), [-60.0, -60.0, 60.0, 60.0]).unwrap();
|
||||
clip = intersect(&clip, &turned);
|
||||
assert!(clip.len() <= 32 && clip.iter().flatten().all(|v| v.is_finite()), "clip {i}: {} corners", clip.len());
|
||||
}
|
||||
// Every square is centred on the origin, so the middle still shows.
|
||||
assert!(shows([-1.0, -1.0, 1.0, 1.0], &clip));
|
||||
}
|
||||
|
||||
fn block(text: &str, rect: [f64; 4]) -> TextBlock {
|
||||
TextBlock {
|
||||
text: text.into(),
|
||||
|
||||
@@ -218,9 +218,139 @@ pub(crate) fn union(a: [f64; 4], b: [f64; 4]) -> [f64; 4] {
|
||||
[a[0].min(b[0]), a[1].min(b[1]), a[2].max(b[2]), a[3].max(b[3])]
|
||||
}
|
||||
|
||||
/// A convex part of the page, in page space: the corners of a convex polygon, in order. With fewer
|
||||
/// than three corners it covers nothing.
|
||||
pub(super) type Region = Vec<[f64; 2]>;
|
||||
|
||||
/// A clip, as the union of the convex regions it leaves visible: one for each rectangle of its
|
||||
/// path. With no parts it leaves nothing visible.
|
||||
pub(super) type Clip = Vec<Region>;
|
||||
|
||||
/// The most corners a clip region keeps. Each intersection with a four-cornered clip can add
|
||||
/// corners, so past this a region becomes its bounding box: still all it held, and a stream that
|
||||
/// sets clip after clip stays bounded.
|
||||
const MAX_REGION_CORNERS: usize = 32;
|
||||
|
||||
/// The most parts a clip keeps. Clips intersect part by part, so past this its parts become one,
|
||||
/// the box around them: still all they held, and the work stays bounded.
|
||||
const MAX_CLIP_PARTS: usize = 16;
|
||||
|
||||
/// `r` (`[x0, y0, x1, y1]`, either way round) under `m`, keeping its shape when `m` turns or
|
||||
/// skews it. A rectangle of no area is a region that covers nothing, however thin a rectangle
|
||||
/// with area is; `None` when a corner, or its measure, is not finite.
|
||||
pub(super) fn region(m: &Matrix, r: [f64; 4]) -> Option<Region> {
|
||||
let corners: Region = [(r[0], r[1]), (r[2], r[1]), (r[2], r[3]), (r[0], r[3])]
|
||||
.into_iter()
|
||||
.map(|(x, y)| {
|
||||
let (x, y) = m.apply(x, y);
|
||||
[x, y]
|
||||
})
|
||||
.collect();
|
||||
let finite = corners.iter().flatten().all(|v| v.is_finite()) && twice_area(&corners).is_finite() && perimeter(&corners).is_finite();
|
||||
finite.then(|| if encloses_area(&corners) { corners } else { Vec::new() })
|
||||
}
|
||||
|
||||
/// The polygon's signed area, doubled: positive when its corners run anticlockwise (y up).
|
||||
/// Measured from its first corner, so that far from the origin it keeps its precision.
|
||||
fn twice_area(p: &[[f64; 2]]) -> f64 {
|
||||
let Some(o) = p.first() else { return 0.0 };
|
||||
p.iter().zip(p.iter().cycle().skip(1)).map(|(a, b)| (a[0] - o[0]) * (b[1] - o[1]) - (b[0] - o[0]) * (a[1] - o[1])).sum()
|
||||
}
|
||||
|
||||
fn perimeter(p: &[[f64; 2]]) -> f64 {
|
||||
p.iter().zip(p.iter().cycle().skip(1)).map(|(a, b)| (b[0] - a[0]).hypot(b[1] - a[1])).sum()
|
||||
}
|
||||
|
||||
/// Whether the polygon encloses any area: its area against the square of its perimeter, so the
|
||||
/// answer is the same at any scale and a thin box still has one.
|
||||
fn encloses_area(p: &[[f64; 2]]) -> bool {
|
||||
let around = perimeter(p);
|
||||
p.len() >= 3 && twice_area(p).abs() > 1e-12 * around * around
|
||||
}
|
||||
|
||||
/// The four corners of the box around `points`.
|
||||
fn bounding<'a>(points: impl Iterator<Item = &'a [f64; 2]>) -> Region {
|
||||
let b = points.fold([f64::MAX, f64::MAX, f64::MIN, f64::MIN], |b, p| [b[0].min(p[0]), b[1].min(p[1]), b[2].max(p[0]), b[3].max(p[1])]);
|
||||
vec![[b[0], b[1]], [b[2], b[1]], [b[2], b[3]], [b[0], b[3]]]
|
||||
}
|
||||
|
||||
/// The part of `a` inside `b`, both convex (Sutherland-Hodgman: `a` cut by each edge of `b`). Clips
|
||||
/// in force intersect, so text shows only where all of them let it through. Regions that share no
|
||||
/// area (apart, or meeting only along an edge) leave an empty one, as does an empty `a` or `b`.
|
||||
pub(super) fn intersect(a: &Region, b: &Region) -> Region {
|
||||
if a.len() < 3 || b.len() < 3 {
|
||||
return Vec::new();
|
||||
}
|
||||
let turn = twice_area(b).signum();
|
||||
let mut out = a.clone();
|
||||
for (p, q) in b.iter().zip(b.iter().cycle().skip(1)) {
|
||||
// Positive on the side of the edge `p` → `q` that `b` lies on.
|
||||
let inside = |v: &[f64; 2]| turn * ((q[0] - p[0]) * (v[1] - p[1]) - (q[1] - p[1]) * (v[0] - p[0]));
|
||||
let cut = std::mem::take(&mut out);
|
||||
for (s, e) in cut.iter().zip(cut.iter().cycle().skip(1)) {
|
||||
let (ds, de) = (inside(s), inside(e));
|
||||
if ds >= 0.0 {
|
||||
out.push(*s);
|
||||
}
|
||||
// The edge crosses the line: `ds - de` is not zero, as one is negative and one is not.
|
||||
if (ds >= 0.0) != (de >= 0.0) {
|
||||
let t = ds / (ds - de);
|
||||
out.push([s[0] + t * (e[0] - s[0]), s[1] + t * (e[1] - s[1])]);
|
||||
}
|
||||
}
|
||||
}
|
||||
if !encloses_area(&out) {
|
||||
return Vec::new();
|
||||
}
|
||||
if out.len() > MAX_REGION_CORNERS {
|
||||
out = bounding(out.iter());
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The clip that leaves visible only what both `a` and `b` do: each part of one intersected with
|
||||
/// each part of the other.
|
||||
pub(super) fn clip_within(a: &Clip, b: &Clip) -> Clip {
|
||||
let mut out: Clip = a.iter().flat_map(|p| b.iter().map(move |q| intersect(p, q))).filter(|r| !r.is_empty()).collect();
|
||||
if out.len() > MAX_CLIP_PARTS {
|
||||
out = vec![bounding(out.iter().flatten())];
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether the box `r` shows through `clip`: through any of its parts.
|
||||
pub(super) fn clip_shows(r: [f64; 4], clip: &Clip) -> bool {
|
||||
clip.iter().any(|part| shows(r, part))
|
||||
}
|
||||
|
||||
/// Whether the box `r` (`[x0, y0, x1, y1]`) and `region` share some area, by the separating axis
|
||||
/// test: two convex shapes are apart exactly when their shadows on some axis, one of the box's or
|
||||
/// a normal of one of the region's edges, do not overlap. Touching is not sharing.
|
||||
pub(super) fn shows(r: [f64; 4], region: &Region) -> bool {
|
||||
if region.len() < 3 {
|
||||
return false;
|
||||
}
|
||||
let corners = [[r[0], r[1]], [r[2], r[1]], [r[2], r[3]], [r[0], r[3]]];
|
||||
let apart = |axis: [f64; 2]| {
|
||||
let shadow = |points: &[[f64; 2]]| {
|
||||
points.iter().map(|p| p[0] * axis[0] + p[1] * axis[1]).fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), v| (lo.min(v), hi.max(v)))
|
||||
};
|
||||
let ((a0, a1), (b0, b1)) = (shadow(&corners), shadow(region));
|
||||
a1 <= b0 || b1 <= a0
|
||||
};
|
||||
// An edge of no length (two corners in one place) has no normal to test.
|
||||
let normals = region.iter().zip(region.iter().cycle().skip(1)).map(|(p, q)| [p[1] - q[1], q[0] - p[0]]).filter(|n| n[0] != 0.0 || n[1] != 0.0);
|
||||
!([[1.0, 0.0], [0.0, 1.0]].into_iter().chain(normals).any(apart))
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(super) struct Ts {
|
||||
pub(super) ctm: Matrix,
|
||||
/// The clip in force, if any, as what it leaves visible: the intersection of every
|
||||
/// rectangular content-stream clip (`re` `W`/`W*` `n`, ISO 32000-2 §8.5.4) and every enclosing
|
||||
/// form's `/BBox` ([`super::lines`]), each in the shape its matrix gives it. `q`/`Q` save and
|
||||
/// restore it along with the rest of `Ts`.
|
||||
pub(super) clip: Option<Clip>,
|
||||
/// The operators that set the current fill colour (`g`, `rg`, `k`, or `cs` + `sc`/`scn`).
|
||||
pub(super) fill: Vec<Op>,
|
||||
pub(super) font: Option<(Vec<u8>, Rc<Metrics>)>,
|
||||
@@ -506,6 +636,7 @@ impl Carry {
|
||||
pub(super) fn new() -> Self {
|
||||
let ts = Ts {
|
||||
ctm: Matrix::IDENTITY,
|
||||
clip: None,
|
||||
fill: Vec::new(),
|
||||
font: None,
|
||||
face: None,
|
||||
@@ -860,11 +991,57 @@ pub(super) fn interpret(
|
||||
// with no properties dict (a file saved before this was tracked, or by another writer) reads
|
||||
// as 1, the single space a rejoin always used before #2529.
|
||||
let mut soft_gap = 1usize;
|
||||
// A pending path of `x y w h re`s, and whether a `W`/`W*` has marked it as the path that `n`
|
||||
// turns into the new clip (ISO 32000-2 §8.5.4) -- the common "set a rectangular clip" idiom.
|
||||
// The path is `Some(None)` once one of its rectangles can't be read, and then clips nothing.
|
||||
// Each rectangle is a part of the clip; a path of more than `MAX_CLIP_PARTS` keeps the box
|
||||
// around them, which still holds them all. Any other operator between `re` and `n` ends the
|
||||
// idiom: the clip is not read then.
|
||||
let mut pending_clip: Option<Option<Vec<[f64; 4]>>> = None;
|
||||
let mut clip_pending = false;
|
||||
for (i, op) in ops.iter().enumerate() {
|
||||
// A gap's space carries only into a `Tj` or `TJ` right after it.
|
||||
if !matches!(op.op.as_slice(), b"Tj" | b"TJ") {
|
||||
carry.gap_space = false;
|
||||
}
|
||||
match op.op.as_slice() {
|
||||
b"re" => {
|
||||
let rect = op.nums::<4>().map(|[x, y, w, h]| [x.min(x + w), y.min(y + h), x.max(x + w), y.max(y + h)]);
|
||||
pending_clip = Some(match (pending_clip.take(), rect) {
|
||||
(None, Some(rect)) => Some(vec![rect]),
|
||||
(Some(Some(mut path)), Some(rect)) => {
|
||||
if path.len() >= MAX_CLIP_PARTS {
|
||||
path = vec![path.iter().fold(rect, |all, r| union(all, *r))];
|
||||
} else {
|
||||
path.push(rect);
|
||||
}
|
||||
Some(path)
|
||||
}
|
||||
_ => None,
|
||||
});
|
||||
}
|
||||
b"W" | b"W*" => clip_pending = pending_clip.is_some(),
|
||||
b"n" => {
|
||||
if clip_pending && let Some(Some(path)) = pending_clip.take() {
|
||||
// A rectangle past what a matrix can hold leaves the clip unread. One of no
|
||||
// area is a part that shows nothing, so a clip of no area hides everything.
|
||||
let parts: Option<Clip> = path.iter().map(|r| region(&ts.ctm, *r)).collect();
|
||||
if let Some(parts) = parts {
|
||||
let new: Clip = parts.into_iter().filter(|part| !part.is_empty()).collect();
|
||||
ts.clip = Some(match &ts.clip {
|
||||
Some(old) => clip_within(old, &new),
|
||||
None => new,
|
||||
});
|
||||
}
|
||||
}
|
||||
pending_clip = None;
|
||||
clip_pending = false;
|
||||
}
|
||||
_ => {
|
||||
pending_clip = None;
|
||||
clip_pending = false;
|
||||
}
|
||||
}
|
||||
match op.op.as_slice() {
|
||||
// No depth cap: every `EMC` pops, so a capped push would pair it with the enclosing
|
||||
// sequence (#3573). Both stacks stay bounded by the number of operators.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use super::fallback::{same_font, same_paint};
|
||||
use super::interp::{Carry, Origin, Pen, Shown, TextState, Ts, direction, interpret, to_frame, union};
|
||||
use super::interp::{Carry, Clip, Origin, Pen, Shown, TextState, Ts, clip_shows, clip_within, direction, interpret, region, to_frame, union};
|
||||
use super::{DecodeBudget, Dict, Document, EditError, HashMap, Matrix, Object, Op, Pieces, Stream, TextLine, parse, serialize_ops};
|
||||
|
||||
impl TextLine {
|
||||
@@ -565,8 +565,9 @@ impl FormBudget {
|
||||
}
|
||||
}
|
||||
|
||||
/// A form XObject a page draws: its object, content, resources and its matrix composed with the
|
||||
/// CTM at the `Do`.
|
||||
/// A form XObject a page draws: its object, content, resources, its matrix composed with the
|
||||
/// CTM at the `Do`, and the clip its `/BBox` makes (page space, under that same matrix, so a
|
||||
/// turned form keeps its turned box; a box of no area hides everything) if it has a valid one.
|
||||
pub(crate) struct FormCall {
|
||||
pub(crate) obj: Option<pdfcraft_cos::ObjRef>,
|
||||
pub(crate) data: Vec<u8>,
|
||||
@@ -575,6 +576,7 @@ pub(crate) struct FormCall {
|
||||
form: Arc<Object>,
|
||||
own: Option<Arc<Object>>,
|
||||
pub(crate) ctm: Matrix,
|
||||
bbox: Option<Clip>,
|
||||
}
|
||||
|
||||
impl FormCall {
|
||||
@@ -644,6 +646,12 @@ pub(crate) fn form_call(
|
||||
<[f64; 6]>::try_from(v).ok().filter(|v| v.iter().all(|x| x.is_finite()))
|
||||
});
|
||||
let own = s.dict.get(b"Resources").filter(|r| matches!(r, Object::Ref(_))).map(|r| doc.resolve(r));
|
||||
// Four finite numbers, or no bound at all: a member that isn't one makes the box unknown, and
|
||||
// reading the numbers around it would invent a clip.
|
||||
let bbox = s.dict.get(b"BBox").map(|b| doc.resolve(b)).and_then(|b| {
|
||||
let values: Vec<f64> = b.as_array()?.iter().map(|x| doc.resolve(x).as_f64().filter(|v| v.is_finite())).collect::<Option<_>>()?;
|
||||
<[f64; 4]>::try_from(values).ok()
|
||||
});
|
||||
let data = match budget.decode.decode(s) {
|
||||
Ok(data) => data,
|
||||
Err(_) if budget.decode.remaining() == 0 => {
|
||||
@@ -653,7 +661,8 @@ pub(crate) fn form_call(
|
||||
Err(_) => Vec::new(),
|
||||
};
|
||||
budget.visits = budget.visits.saturating_add(1);
|
||||
Some(FormCall { obj, data, form, own, ctm: m.map_or(ctm, |m| Matrix(m).then(&ctm)) })
|
||||
let ctm = m.map_or(ctm, |m| Matrix(m).then(&ctm));
|
||||
Some(FormCall { obj, data, form, own, ctm, bbox: bbox.and_then(|b| region(&ctm, b)).map(|r| if r.is_empty() { Vec::new() } else { vec![r] }) })
|
||||
}
|
||||
|
||||
/// The lines a page shows as it reads, including text drawn by form XObjects (which
|
||||
@@ -684,6 +693,12 @@ pub(super) fn reading_lines(doc: &Document, page: usize) -> Result<(Vec<TextLine
|
||||
// Text after a form starts a new line.
|
||||
last = None;
|
||||
}
|
||||
// A run that the clips in force (forms' `/BBox`es and content-stream `re`/`W`/`n`
|
||||
// clips, intersected) hide is not drawn, so it is not read either (#3503).
|
||||
if s.state.clip.as_ref().is_some_and(|clip| !clip_shows(s.rect, clip)) {
|
||||
last = None;
|
||||
continue;
|
||||
}
|
||||
let si = stream(s.op);
|
||||
// Text from another stream starts a new line, as when each stream was read alone.
|
||||
if last_stream.replace(si).is_some_and(|prev| prev != si) {
|
||||
@@ -701,8 +716,14 @@ pub(super) fn reading_lines(doc: &Document, page: usize) -> Result<(Vec<TextLine
|
||||
let Some(form) = form_call(w.doc, resources, name, ts.ctm, &w.path, &mut w.budget) else { return Ok(()) };
|
||||
let ops = parse(&form.data).ops;
|
||||
// The form starts with the graphics state at its `Do`, its own matrix applied.
|
||||
// Its content is clipped to its `/BBox` within whatever clips the page had in force at the
|
||||
// `Do`. It starts with a stack of its own, so no `Q` of its own can lift that clip.
|
||||
let clip = match (&ts.clip, &form.bbox) {
|
||||
(Some(outer), Some(own)) => Some(clip_within(outer, own)),
|
||||
(outer, own) => outer.clone().or_else(|| own.clone()),
|
||||
};
|
||||
let mut carry = Carry {
|
||||
ts: Ts { ctm: form.ctm, ..ts },
|
||||
ts: Ts { ctm: form.ctm, clip, ..ts },
|
||||
stack: Vec::new(),
|
||||
marked: Vec::new(),
|
||||
layers: Vec::new(),
|
||||
|
||||
@@ -24,9 +24,12 @@ pub(crate) fn comment_list(doc: &pdfcraft_cos::Document) -> Vec<pdfcraft_render:
|
||||
fill_sign: s.fill_sign,
|
||||
no_rotate: s.no_rotate,
|
||||
points: s.points,
|
||||
text_box: s.text_box,
|
||||
popup: s.popup.map(|p| pdfcraft_render::Popup { rect: p.rect, open: p.open }),
|
||||
})
|
||||
.collect();
|
||||
pdfcraft_render::link_replies(&mut list);
|
||||
pdfcraft_render::fill_group_text(&mut list);
|
||||
list
|
||||
}
|
||||
|
||||
@@ -79,9 +82,10 @@ pub fn comment_type_name(subtype: &str) -> &str {
|
||||
}
|
||||
}
|
||||
|
||||
/// [`comment_type_name`], telling callouts, clouds and typewriter text apart by `/IT`.
|
||||
/// [`comment_type_name`], telling replaced text, callouts, clouds and typewriter text apart by `/IT`.
|
||||
pub fn comment_kind(a: &pdfcraft_render::Annotation) -> &str {
|
||||
match a.intent.as_deref() {
|
||||
Some("StrikeOutTextEdit" | "Replace") => "Replace Text",
|
||||
Some("FreehandHighlight") if a.subtype == "Ink" => "Freehand Highlight",
|
||||
Some("FreeTextCallout") => "Callout",
|
||||
Some("PolygonCloud") => "Cloud",
|
||||
@@ -106,19 +110,26 @@ pub fn comment_summary(name: &str, all: &[pdfcraft_render::Annotation], sort: Su
|
||||
}
|
||||
// Write a comment's replies, indenting each level. A reply to a reply keeps its `/IRT` on the
|
||||
// direct parent, so following one level would leave the deeper replies out of the summary.
|
||||
fn write_replies(out: &mut String, children: &Children<'_>, parent: &pdfcraft_render::Annotation, depth: usize) {
|
||||
// A group subordinate (`/RT /Group`, ISO 32000-2 §12.5.6.2) is part of the comment, not a
|
||||
// reply: it is not written, and replies to it are written at its level, as the comment's.
|
||||
// `depth` bounds the walk; `level` is the indent.
|
||||
fn write_replies(out: &mut String, children: &Children<'_>, parent: &pdfcraft_render::Annotation, depth: usize, level: usize) {
|
||||
use std::fmt::Write;
|
||||
if depth > 64 {
|
||||
return;
|
||||
}
|
||||
for r in children.get(&(parent.page, parent.index)).into_iter().flatten() {
|
||||
let indent = " ".repeat(depth + 1);
|
||||
if r.is_group_member() {
|
||||
write_replies(out, children, r, depth + 1, level);
|
||||
continue;
|
||||
}
|
||||
let indent = " ".repeat(level + 1);
|
||||
let _ =
|
||||
writeln!(out, "{indent}Author: {} Subject: Reply Date: {}", r.author.as_deref().unwrap_or(""), r.modified.as_deref().unwrap_or(""));
|
||||
for line in r.contents.as_deref().unwrap_or("").lines() {
|
||||
let _ = writeln!(out, "{indent}{line}");
|
||||
}
|
||||
write_replies(out, children, r, depth + 1);
|
||||
write_replies(out, children, r, depth + 1, level + 1);
|
||||
}
|
||||
}
|
||||
let mut numbered: Vec<(usize, &pdfcraft_render::Annotation)> = Vec::new();
|
||||
@@ -157,7 +168,7 @@ pub fn comment_summary(name: &str, all: &[pdfcraft_render::Annotation], sort: Su
|
||||
if let Some(c) = a.contents.as_deref().filter(|c| !c.is_empty()) {
|
||||
let _ = writeln!(out, "{c}");
|
||||
}
|
||||
write_replies(&mut out, &children, a, 0);
|
||||
write_replies(&mut out, &children, a, 0, 0);
|
||||
out.push('\n');
|
||||
}
|
||||
out
|
||||
|
||||
@@ -160,12 +160,14 @@ pub enum Edit {
|
||||
/// `rect` is a point: the stamp is centred there at its natural size (at most 200 pt).
|
||||
/// Any other `rect` is a box: the picture is scaled to fit inside it, keeping its shape,
|
||||
/// and centred in it (#4077).
|
||||
/// `line` is a text line under the picture, already filled in ([`Session::stamp_line`](crate::Session::stamp_line)).
|
||||
AddCustomStamp {
|
||||
page: usize,
|
||||
rect: [f64; 4],
|
||||
name: String,
|
||||
file: MarkFile,
|
||||
author: String,
|
||||
line: Option<String>,
|
||||
},
|
||||
/// Rich Media ▸ Add 3D: a U3D or PRC `model` as a 3D annotation in `rect` on `page`, named
|
||||
/// `name` (its alternate description). Its poster is the picture in `poster` (a PDF page or an
|
||||
@@ -243,6 +245,14 @@ pub enum Edit {
|
||||
index: usize,
|
||||
points: Vec<[f64; 2]>,
|
||||
},
|
||||
/// Open, close or move a comment's pop-up window (`rect` in user space; a comment without a
|
||||
/// pop-up gets one).
|
||||
SetAnnotationPopup {
|
||||
page: usize,
|
||||
index: usize,
|
||||
rect: Option<[f64; 4]>,
|
||||
open: Option<bool>,
|
||||
},
|
||||
/// Resize a rectangle, oval or text box.
|
||||
ResizeAnnotation {
|
||||
page: usize,
|
||||
|
||||
@@ -87,6 +87,9 @@ pub const EDIT_LABELS: &[&str] = &[
|
||||
"Unlock comment",
|
||||
"Move comment",
|
||||
"Reshape comment",
|
||||
"Open comment pop-up",
|
||||
"Close comment pop-up",
|
||||
"Move comment pop-up",
|
||||
"Resize comment",
|
||||
"Change comment properties",
|
||||
"Fill in {name}",
|
||||
@@ -232,6 +235,9 @@ impl Edit {
|
||||
Edit::LockAnnotation { .. } => Label::of("Unlock comment"),
|
||||
Edit::MoveAnnotation { .. } => Label::of("Move comment"),
|
||||
Edit::ReshapeAnnotation { .. } => Label::of("Reshape comment"),
|
||||
Edit::SetAnnotationPopup { rect: Some(_), .. } => Label::of("Move comment pop-up"),
|
||||
Edit::SetAnnotationPopup { open: Some(true), .. } => Label::of("Open comment pop-up"),
|
||||
Edit::SetAnnotationPopup { .. } => Label::of("Close comment pop-up"),
|
||||
Edit::ResizeAnnotation { .. } => Label::of("Resize comment"),
|
||||
Edit::StyleAnnotation { .. }
|
||||
| Edit::FillAnnotation { .. }
|
||||
|
||||
@@ -62,6 +62,7 @@ pub(crate) fn check_permission(edit: &Edit, p: &pdfcraft_cos::Permissions) -> Re
|
||||
| Edit::LockAnnotation { .. }
|
||||
| Edit::MoveAnnotation { .. }
|
||||
| Edit::ReshapeAnnotation { .. }
|
||||
| Edit::SetAnnotationPopup { .. }
|
||||
| Edit::ResizeAnnotation { .. }
|
||||
| Edit::StyleAnnotation { .. }
|
||||
| Edit::FillAnnotation { .. }
|
||||
@@ -559,9 +560,12 @@ pub(crate) fn run_edit(doc: &mut pdfcraft_cos::Document, edit: &Edit, cx: &mut E
|
||||
}
|
||||
note_skipped(doc, &report);
|
||||
}
|
||||
Edit::AddCustomStamp { page, rect, name, file, author } => {
|
||||
Edit::AddCustomStamp { page, rect, name, file, author, line } => {
|
||||
let src = mark_source(doc, file)?;
|
||||
let (sw, sh) = (src.size.0.max(1.0), src.size.1.max(1.0));
|
||||
let line = line.as_deref().map(str::trim).filter(|l| !l.is_empty()).map(|l| l.chars().take(crate::MAX_STAMP_LINE).collect::<String>());
|
||||
let picture = (src.size.0.max(1.0), src.size.1.max(1.0));
|
||||
// A text line adds its band under the picture, and widens the stamp to fit (#1741).
|
||||
let (sw, sh) = pdfcraft_annot::custom_stamp_size(picture, line.as_deref());
|
||||
let natural = rect[2] == rect[0] && rect[3] == rect[1];
|
||||
let rotation = pdfcraft_organize::page_rotation(doc, *page)?;
|
||||
// The picture as displayed: a quarter turn swaps its sides in user space.
|
||||
@@ -573,7 +577,7 @@ pub(crate) fn run_edit(doc: &mut pdfcraft_cos::Document, edit: &Edit, cx: &mut E
|
||||
} else {
|
||||
fit_picture(*rect, dw, dh)
|
||||
};
|
||||
let shape = Shape::CustomStamp { rect, name: name.clone(), picture: src.xobject, image: src.image, size: (sw, sh) };
|
||||
let shape = Shape::CustomStamp { rect, name: name.clone(), picture: src.xobject, image: src.image, size: picture, line };
|
||||
let style = pdfcraft_annot::Style::default_for(&shape);
|
||||
let new = NewAnnotation { page: *page, shape, style, contents: name.clone(), author: author.clone() };
|
||||
let index = pdfcraft_annot::add_annotation(doc, &new, &cx.meta())?;
|
||||
@@ -611,7 +615,7 @@ pub(crate) fn run_edit(doc: &mut pdfcraft_cos::Document, edit: &Edit, cx: &mut E
|
||||
}
|
||||
Edit::DeleteAttachment { key } => pdfcraft_organize::delete_attachment(doc, key)?,
|
||||
Edit::ReplaceText { page, quads, text, author, strike, caret } => {
|
||||
// One `/NM` each: the strikeout is grouped under the caret, and XFDF names that link by
|
||||
// One `/NM` each: the strikeout is grouped with the caret, and XFDF names that link by
|
||||
// the caret's `/NM` (#2666).
|
||||
let (strike_meta, caret_meta) = (cx.meta(), cx.meta());
|
||||
pdfcraft_annot::add_text_replacement(
|
||||
@@ -634,6 +638,7 @@ pub(crate) fn run_edit(doc: &mut pdfcraft_cos::Document, edit: &Edit, cx: &mut E
|
||||
Edit::LockAnnotation { page, index, locked } => pdfcraft_annot::set_locked(doc, *page, *index, *locked)?,
|
||||
Edit::MoveAnnotation { page, index, dx, dy } => pdfcraft_annot::move_annotation(doc, *page, *index, *dx, *dy, &cx.meta())?,
|
||||
Edit::ReshapeAnnotation { page, index, points } => pdfcraft_annot::set_points(doc, *page, *index, points, &cx.meta())?,
|
||||
Edit::SetAnnotationPopup { page, index, rect, open } => pdfcraft_annot::set_popup(doc, *page, *index, *rect, *open, &cx.meta())?,
|
||||
Edit::ResizeAnnotation { page, index, rect } => pdfcraft_annot::set_rect(doc, *page, *index, *rect, &cx.meta())?,
|
||||
Edit::StyleAnnotation { page, index, color, opacity, width, endings } => {
|
||||
pdfcraft_annot::set_style(
|
||||
|
||||
@@ -66,6 +66,7 @@ pub(crate) fn scope_of(edit: &Edit) -> Scope {
|
||||
| Edit::EraseInk { .. }
|
||||
| Edit::MoveAnnotation { .. }
|
||||
| Edit::ReshapeAnnotation { .. }
|
||||
| Edit::SetAnnotationPopup { .. }
|
||||
| Edit::ResizeAnnotation { .. }
|
||||
| Edit::StyleAnnotation { .. }
|
||||
| Edit::FillAnnotation { .. }
|
||||
|
||||
@@ -121,8 +121,9 @@ pub use pdfcraft_fonts::{MAX_SIGNATURE_CHARS, ScriptOutline, script_missing, scr
|
||||
pub use pdfcraft_annot::appearance as annot_text;
|
||||
pub use pdfcraft_annot::links::{Highlight as LinkHighlight, LinkAction, LinkItem, LinkStyle, LinkZoom};
|
||||
pub use pdfcraft_annot::{
|
||||
Activation3d, AppearanceCache, AttachIcon, BorderShape, FillMark, LineEnding, Markup, NOTE_SIZE, NewAnnotation, NoteIcon, OverlayFont,
|
||||
OverlayLook, Props as CommentProps, ReviewState, Rgb, Shape, StampGroup, StampKind, Style, rect_quad,
|
||||
Activation3d, AppearanceCache, AttachIcon, BorderShape, CALLOUT_KNEE_LINE, FillMark, LineEnding, Markup, NOTE_SIZE, NewAnnotation, NoteIcon,
|
||||
OverlayFont, OverlayLook, Props as CommentProps, ReviewState, Rgb, Shape, Side as CalloutSide, StampGroup, StampKind, Style, callout_attach,
|
||||
callout_knee, callout_side, rect_quad,
|
||||
};
|
||||
pub use pdfcraft_annot::{MAX_MODEL_BYTES as MAX_3D_MODEL_BYTES, ModelFormat as Model3dFormat};
|
||||
pub use pdfcraft_forms::detect;
|
||||
@@ -133,6 +134,7 @@ pub use pdfcraft_redact::codes::{CODE_SETS as REDACTION_CODE_SETS, CodeSet as Re
|
||||
pub use pdfcraft_redact::patterns::{
|
||||
MAX_WORDS as REDACT_MAX_WORDS, PATTERNS as REDACT_PATTERNS, Pattern as RedactPattern, find as find_pattern, word_list as redact_word_list,
|
||||
};
|
||||
pub use pdfcraft_redact::redacted_file_name;
|
||||
pub use pdfcraft_redact::sanitize::{HIDDEN, Hidden};
|
||||
pub use pdfcraft_redact::user_regex::{UserRegex as RedactRegex, VALIDATORS as REDACT_VALIDATORS, Validator as RedactValidator};
|
||||
pub use pdfcraft_sign as sign;
|
||||
@@ -189,5 +191,8 @@ fn display_config(config: &pdfcraft_render::RenderConfig) -> pdfcraft_render::Re
|
||||
config.clone().on_screen()
|
||||
}
|
||||
|
||||
/// How long a custom stamp's text line may be, in characters (#1741).
|
||||
pub const MAX_STAMP_LINE: usize = 200;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
@@ -22,6 +22,9 @@ pub fn rasterize(doc: &Document, pages: &[usize], raster: &Raster, content: Cont
|
||||
let mut config = src.config.clone();
|
||||
// The copy below holds only what prints, so the viewer's own comment hiding plays no part.
|
||||
config.hide_comments = false;
|
||||
// Printing is not the View event: a layer the auto state turns off on screen keeps its
|
||||
// configured state on paper, as in a print that goes out as vectors.
|
||||
config.for_print = true;
|
||||
let (printed, layers) = guard(|| -> Result<(Vec<u8>, Option<Vec<pdfcraft_render::Layer>>), String> {
|
||||
let mut cos = pdfcraft_cos::Document::open_with_password(src.bytes.clone(), config.password.as_deref()).map_err(|e| e.to_string())?;
|
||||
pdfcraft_print::keep_printed(&mut cos, content);
|
||||
|
||||
@@ -211,7 +211,13 @@ impl Session {
|
||||
Err(_) => return Vec::new(),
|
||||
},
|
||||
};
|
||||
(0..doc.info.pages.len()).map(|i| pages.contains(&i) && pdfcraft_print::text_reads_up(&cos, i)).collect()
|
||||
// The page tree is read once, and each page is looked up, not searched for, in `pages`.
|
||||
let mut out = vec![false; doc.info.pages.len()];
|
||||
let wanted: Vec<usize> = pages.iter().copied().filter(|&p| p < out.len()).collect::<std::collections::BTreeSet<_>>().into_iter().collect();
|
||||
for (p, up) in wanted.iter().zip(pdfcraft_print::texts_read_up(&cos, &wanted)) {
|
||||
out[*p] = up;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Combine whole files, in order, into new PDF bytes (one bookmark per file).
|
||||
|
||||
@@ -62,20 +62,54 @@ impl Session {
|
||||
return None;
|
||||
}
|
||||
|
||||
/// Today's date in local time: (year, month, day). With an injected clock (tests) the clock
|
||||
/// is taken as local time.
|
||||
/// A dynamic stamp's second line: "By Ada at 2:14 pm, Oct 02, 2026" (local time).
|
||||
pub fn stamp_by_line(&self, author: &str) -> String {
|
||||
let (date, time) = self.stamp_date_time();
|
||||
let who = if author.trim().is_empty() { String::new() } else { format!("By {} ", author.trim()) };
|
||||
format!("{who}at {time}, {date}")
|
||||
}
|
||||
|
||||
/// A custom stamp's text line (#1741): `template` with `{name}` (the author), `{date}`
|
||||
/// ("Oct 02, 2026") and `{time}` ("2:14 pm") filled in now, in local time, as the dynamic
|
||||
/// stamps' "By" line has them. Cut to [`MAX_STAMP_LINE`](crate::MAX_STAMP_LINE) characters.
|
||||
pub fn stamp_line(&self, template: &str, author: &str) -> String {
|
||||
let (date, time) = self.stamp_date_time();
|
||||
// One pass over the template, so a placeholder the author's name happens to contain
|
||||
// (`Ada {date}`) stays as written rather than being filled in too.
|
||||
let mut filled = String::new();
|
||||
let mut rest = template.trim();
|
||||
while let Some(c) = rest.chars().next() {
|
||||
if let Some(after) = rest.strip_prefix("{name}") {
|
||||
filled.push_str(author.trim());
|
||||
rest = after;
|
||||
} else if let Some(after) = rest.strip_prefix("{date}") {
|
||||
filled.push_str(&date);
|
||||
rest = after;
|
||||
} else if let Some(after) = rest.strip_prefix("{time}") {
|
||||
filled.push_str(&time);
|
||||
rest = after;
|
||||
} else {
|
||||
filled.push(c);
|
||||
rest = rest.get(c.len_utf8()..).unwrap_or_default();
|
||||
}
|
||||
}
|
||||
filled.chars().take(crate::MAX_STAMP_LINE).collect()
|
||||
}
|
||||
|
||||
/// Now, as the stamps write it: ("Oct 02, 2026", "2:14 pm"), local time.
|
||||
fn stamp_date_time(&self) -> (String, String) {
|
||||
let offset = self.local_offset();
|
||||
let d = self.now().map(|t| pdfcraft_cos::pdf_date(t + offset)).unwrap_or_default();
|
||||
let num = |a: usize, b: usize| d.get(a..b).and_then(|s| s.parse::<u32>().ok()).unwrap_or(0);
|
||||
let (y, mo, day, hh, mm) = (num(2, 6), num(6, 8), num(8, 10), num(10, 12), num(12, 14));
|
||||
const MONTHS: [&str; 12] = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
|
||||
let h12 = if hh % 12 == 0 { 12 } else { hh % 12 };
|
||||
let who = if author.trim().is_empty() { String::new() } else { format!("By {} ", author.trim()) };
|
||||
format!("{who}at {h12}:{mm:02} {}, {} {day:02}, {y}", if hh < 12 { "am" } else { "pm" }, MONTHS[(mo.clamp(1, 12) - 1) as usize])
|
||||
let month = MONTHS.get(mo.clamp(1, 12) as usize - 1).copied().unwrap_or("Jan");
|
||||
(format!("{month} {day:02}, {y}"), format!("{h12}:{mm:02} {}", if hh < 12 { "am" } else { "pm" }))
|
||||
}
|
||||
|
||||
/// Today's date in local time: (year, month, day). With an injected clock (tests) the clock
|
||||
/// is taken as local time.
|
||||
pub fn today(&self) -> (i64, u32, u32) {
|
||||
let offset = self.local_offset();
|
||||
self.now().map(|t| pdfcraft_cos::pdf_date(t + offset)).as_deref().and_then(parse_ymd).unwrap_or((1970, 1, 1))
|
||||
|
||||
@@ -241,6 +241,7 @@ impl SignatureImage {
|
||||
name: if initials { "Initials" } else { "Signature" }.into(),
|
||||
file: MarkFile { name: "signature.png".into(), bytes: self.bytes.clone(), page: 0 },
|
||||
author: author.into(),
|
||||
line: None,
|
||||
}],
|
||||
})
|
||||
}
|
||||
|
||||
+209
-1
@@ -106,6 +106,7 @@ fn custom_image_stamp_keeps_displayed_orientation_on_rotated_pages() {
|
||||
name: "Original quadrants".into(),
|
||||
file: MarkFile { name: "quadrants.png".into(), bytes: bytes.clone(), page: 0 },
|
||||
author: "Test".into(),
|
||||
line: None,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
@@ -441,6 +442,7 @@ fn explicit_image_stamps_keep_displayed_orientation_on_rotated_pages() {
|
||||
name: "Original quadrants".into(),
|
||||
file: MarkFile { name: "quadrants.png".into(), bytes: bytes.clone(), page: 0 },
|
||||
author: "Test".into(),
|
||||
line: None,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
@@ -493,6 +495,7 @@ fn pdf_page_stamps_keep_displayed_orientation_on_rotated_pages() {
|
||||
name: "Half red".into(),
|
||||
file: MarkFile { name: "half.pdf".into(), bytes: bytes.clone(), page: 0 },
|
||||
author: "Test".into(),
|
||||
line: None,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
@@ -522,6 +525,7 @@ fn pdf_page_stamps_fit_inside_an_explicit_box() {
|
||||
name: "Diagram".into(),
|
||||
file: MarkFile { name: "diagram.pdf".into(), bytes: bytes.clone(), page: 0 },
|
||||
author: "Test".into(),
|
||||
line: None,
|
||||
};
|
||||
session.apply(id, stamp([56.0, 400.0, 539.0, 700.0])).unwrap();
|
||||
assert_eq!(session.get(id).unwrap().info.annotations[0].rect, [56.0, 429.25, 539.0, 670.75]);
|
||||
@@ -5164,6 +5168,85 @@ fn comment_summary_includes_replies_to_replies() {
|
||||
assert!(text.contains(" NESTED_REPLY"), "the nested reply is indented under its parent: {text}");
|
||||
}
|
||||
|
||||
/// ISO 32000-2 §12.5.6.2: a group subordinate (`/RT /Group`) is part of its primary's comment,
|
||||
/// not a reply: the summary leaves it out and writes the replies to it as the comment's.
|
||||
#[test]
|
||||
fn comment_summary_leaves_group_members_out_and_keeps_their_replies() {
|
||||
let (mut s, id) = session_with(1);
|
||||
s.apply(id, rect_comment(0, [40.0, 40.0, 90.0, 90.0])).unwrap();
|
||||
s.apply(id, Edit::ReplyToAnnotation { page: 0, index: 0, text: "MEMBER_TEXT".into(), author: "Bob".into() }).unwrap();
|
||||
s.apply(id, Edit::ReplyToAnnotation { page: 0, index: 1, text: "REPLY_TO_MEMBER".into(), author: "Carol".into() }).unwrap();
|
||||
let mut all = s.get(id).unwrap().info.annotations.clone();
|
||||
all.iter_mut().find(|a| a.contents.as_deref() == Some("MEMBER_TEXT")).unwrap().grouped = true;
|
||||
let text = comment_summary("doc.pdf", &all, SummarySort::Page);
|
||||
assert!(!text.contains("MEMBER_TEXT") && !text.contains("Bob"), "{text}");
|
||||
assert!(text.lines().any(|l| l == " REPLY_TO_MEMBER"), "the reply is the comment's, one level in: {text}");
|
||||
}
|
||||
|
||||
/// The summary follows `/IRT` down from a comment at most 64 steps, group subordinates included:
|
||||
/// a reply under a longer chain of subordinates is left out, one under a short chain is written,
|
||||
/// and a subordinate listed at its own primary's position (a loop, from a malformed listing)
|
||||
/// ends the walk.
|
||||
#[test]
|
||||
fn comment_summary_follows_a_group_chain_a_bounded_number_of_steps() {
|
||||
let (mut s, id) = session_with(1);
|
||||
s.apply(id, rect_comment(0, [40.0, 40.0, 90.0, 90.0])).unwrap();
|
||||
let top = s.get(id).unwrap().info.annotations.iter().find(|a| a.is_comment()).unwrap().clone();
|
||||
let at = |a: &pdfcraft_render::Annotation| (a.page, a.index);
|
||||
let under = |index: usize, parent: (usize, usize), grouped: bool, text: &str| pdfcraft_render::Annotation {
|
||||
index,
|
||||
parent: Some(parent),
|
||||
grouped,
|
||||
contents: Some(text.into()),
|
||||
..top.clone()
|
||||
};
|
||||
for (members, written) in [(10, true), (100, false)] {
|
||||
let mut all = vec![top.clone()];
|
||||
let mut up = at(&top);
|
||||
for k in 0..members {
|
||||
let m = under(1000 + k, up, true, "MEMBER");
|
||||
up = at(&m);
|
||||
all.push(m);
|
||||
}
|
||||
all.push(under(5000, up, false, "DEEP_REPLY"));
|
||||
let text = comment_summary("doc.pdf", &all, SummarySort::Page);
|
||||
assert_eq!(text.contains("DEEP_REPLY"), written, "{members}: {text}");
|
||||
assert!(!text.contains("MEMBER"), "{members}: {text}");
|
||||
}
|
||||
let looped = vec![top.clone(), under(top.index, at(&top), true, "LOOP")];
|
||||
let text = comment_summary("doc.pdf", &looped, SummarySort::Page);
|
||||
assert!(!text.contains("LOOP"), "{text}");
|
||||
}
|
||||
|
||||
/// Deleting a group's primary removes the subordinate's `/IRT` in the same edit, as Acrobat does:
|
||||
/// the subordinate lists as a comment of its own and keeps `/RT /Group`. One undo puts the group
|
||||
/// back, `/IRT` included.
|
||||
#[test]
|
||||
fn deleting_a_group_primary_releases_its_member_in_one_undo_step() {
|
||||
let bytes = pdf_with_annots(&[
|
||||
b"<< /Type /Annot /Subtype /Square /Rect [10 10 50 50] /NM (primary) /Contents (PRIMARY_TEXT) >>",
|
||||
b"<< /Type /Annot /Subtype /Circle /Rect [60 60 90 90] /NM (member) /IRT 4 0 R /RT /Group >>",
|
||||
]);
|
||||
let mut s = Session::new().with_clock(|| 1_700_000_000);
|
||||
let id = s.open("group.pdf", None, Arc::new(bytes), None).unwrap();
|
||||
let names = |s: &Session| -> Vec<(Option<String>, bool, bool)> {
|
||||
s.get(id).unwrap().info.annotations.iter().map(|a| (a.name.clone(), a.is_comment(), a.is_group_member())).collect()
|
||||
};
|
||||
// Listed by top edge: the Circle is the higher one.
|
||||
let grouped = vec![(Some("member".into()), false, true), (Some("primary".into()), true, false)];
|
||||
assert_eq!(names(&s), grouped);
|
||||
s.apply(id, Edit::DeleteAnnotation { page: 0, index: 0 }).unwrap();
|
||||
assert_eq!(names(&s), [(Some("member".into()), true, false)], "a comment of its own");
|
||||
let member = |s: &Session| {
|
||||
let cos = &s.get(id).unwrap().editor.as_ref().unwrap().cos;
|
||||
cos.get(pdfcraft_cos::ObjRef::new(5, 0)).as_dict().cloned().unwrap()
|
||||
};
|
||||
assert!(member(&s).get(b"IRT").is_none() && member(&s).name(b"RT") == Some(b"Group".as_slice()), "{:?}", member(&s));
|
||||
s.undo(id).unwrap();
|
||||
assert_eq!(names(&s), grouped, "one undo puts the group back");
|
||||
assert!(member(&s).reference(b"IRT").is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reading_colors_set_and_invalidated() {
|
||||
let (mut s, id) = session_with(1);
|
||||
@@ -8575,6 +8658,44 @@ fn a_line_without_an_appearance_is_drawn_at_its_leader_length() {
|
||||
assert_eq!(px(100, 200), vec![255, 255, 255, 255], "nothing along /L");
|
||||
}
|
||||
|
||||
/// A text box without `/AP`, `/BS` or `/Border` is drawn with the `/Border` default, a 1-pt
|
||||
/// border in its text colour (ISO 32000-2 Table 166), and a redaction mark without `/AP` or
|
||||
/// `/QuadPoints` is outlined around `/Rect` (Table 195), here in its array `/OC` colour.
|
||||
#[test]
|
||||
fn text_boxes_and_redaction_marks_without_appearances_show_their_outlines() {
|
||||
let objs: Vec<&[u8]> = vec![
|
||||
b"<< /Type /Catalog /Pages 2 0 R >>",
|
||||
b"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 200 300] >>",
|
||||
b"<< /Type /Page /Parent 2 0 R /Annots [4 0 R 5 0 R] >>",
|
||||
b"<< /Type /Annot /Subtype /FreeText /Rect [20 200 180 260] /Contents (Box) /DA (1 0 0 rg /Helv 10 Tf) >>",
|
||||
b"<< /Type /Annot /Subtype /Redact /Rect [20 20 180 120] /IC [0 0 0] /OC [0 0 1] >>",
|
||||
];
|
||||
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 mut s = Session::new().with_clock(|| 1_700_000_000);
|
||||
let id = s.open("outlines.pdf", None, Arc::new(bytes), None).expect("opens");
|
||||
let p = shown(&s, id, 0);
|
||||
let px = |x: u32, y: u32| p.rgba[((y * p.width + x) * 4) as usize..][..3].to_vec();
|
||||
// y down: the text box spans rows 40..100, the redaction mark rows 180..280; both left edges
|
||||
// are column 20.
|
||||
assert_eq!(px(20, 70), [255, 0, 0], "the text box's left border, in its /DA colour");
|
||||
assert_eq!(px(100, 99), [255, 0, 0], "the text box's bottom border");
|
||||
assert_eq!(px(20, 230), [0, 0, 255], "the redaction mark's outline, in its /OC colour");
|
||||
assert_eq!(px(100, 230), [255, 255, 255], "no fill before the redaction is applied");
|
||||
}
|
||||
|
||||
/// A stamp's `/Rect` and the colour family expected inside it.
|
||||
type StampRect = ([f64; 4], char);
|
||||
|
||||
@@ -10043,7 +10164,8 @@ fn a_phone_photo_used_as_a_custom_stamp_is_embedded_upright() {
|
||||
// A click places the stamp at its natural size: 30 x 20 pt as stored, 20 x 30 pt upright.
|
||||
// Named "Signature" so `signature_image` finds its picture.
|
||||
let file = MarkFile { name: "photo.jpg".into(), bytes: Arc::new(phone_jpeg()), page: 0 };
|
||||
let stamp = Edit::AddCustomStamp { page: 0, rect: [100.0, 100.0, 100.0, 100.0], name: "Signature".into(), file, author: "Ada".into() };
|
||||
let stamp =
|
||||
Edit::AddCustomStamp { page: 0, rect: [100.0, 100.0, 100.0, 100.0], name: "Signature".into(), file, author: "Ada".into(), line: None };
|
||||
session.apply(id, stamp).unwrap();
|
||||
let cos = &session.get(id).unwrap().editor.as_ref().unwrap().cos;
|
||||
let picture = pdfcraft_annot::signature_image(cos, 0, 0).unwrap().unwrap();
|
||||
@@ -11936,6 +12058,92 @@ fn picture_streams_that_inflate_past_their_size_keep_the_whole_box() {
|
||||
assert!(d.image_shows_at(&images[2], [25.0, 250.0]));
|
||||
}
|
||||
|
||||
/// A custom stamp's line template (#1741) fills in the author, date and time as the dynamic
|
||||
/// stamps write them, and the "By" line itself is unchanged.
|
||||
#[test]
|
||||
fn stamp_lines_fill_in_the_name_date_and_time() {
|
||||
let s = Session::new().with_clock(|| 1_700_000_000);
|
||||
assert_eq!(s.stamp_line("Received {date} {time} by {name}", " Ada "), "Received Nov 14, 2023 10:13 pm by Ada");
|
||||
// Review on #2345 (gabglus): placeholders inside the author's name are kept as written.
|
||||
assert_eq!(s.stamp_line("By {name} — {date} {time}", "Ada {date} {time}"), "By Ada {date} {time} — Nov 14, 2023 10:13 pm");
|
||||
assert_eq!(s.stamp_line("{name}{name}", "{name}"), "{name}{name}");
|
||||
assert_eq!(s.stamp_by_line("Ada"), "By Ada at 10:13 pm, Nov 14, 2023");
|
||||
assert_eq!(s.stamp_by_line(""), "at 10:13 pm, Nov 14, 2023");
|
||||
assert_eq!(s.stamp_line(&"{date}".repeat(100), "Ada").chars().count(), MAX_STAMP_LINE);
|
||||
}
|
||||
|
||||
/// A custom stamp's line keeps Western European letters (#1741): the appearance holds them as
|
||||
/// WinAnsi bytes. A lossy UTF-8 round trip once turned them into replacement characters.
|
||||
#[test]
|
||||
fn a_custom_stamp_line_keeps_accented_letters() {
|
||||
let image = image::RgbaImage::from_pixel(80, 40, image::Rgba([20, 120, 220, 255]));
|
||||
let mut png = std::io::Cursor::new(Vec::new());
|
||||
image.write_to(&mut png, image::ImageFormat::Png).unwrap();
|
||||
let (mut session, id) = session_with(1);
|
||||
let edit = Edit::AddCustomStamp {
|
||||
page: 0,
|
||||
rect: [100.0, 100.0, 100.0, 100.0],
|
||||
name: "Logo".into(),
|
||||
file: MarkFile { name: "logo.png".into(), bytes: Arc::new(png.into_inner()), page: 0 },
|
||||
author: "Zoë".into(),
|
||||
line: Some(session.stamp_line("Reçu à Zürich par {name}", "Zoë")),
|
||||
};
|
||||
session.apply(id, edit).unwrap();
|
||||
let saved = session.save_bytes(id).unwrap();
|
||||
let doc = pdfcraft_cos::Document::open(saved).unwrap();
|
||||
const WANT: &[u8] = b"(Re\xe7u \xe0 Z\xfcrich par Zo\xeb)";
|
||||
let found = doc.scan_objects().any(|(_, o)| match o.as_ref() {
|
||||
pdfcraft_cos::Object::Stream(st) => st.decoded().is_ok_and(|b| b.windows(WANT.len()).any(|w| w == WANT)),
|
||||
_ => false,
|
||||
});
|
||||
assert!(found, "the line's letters are WinAnsi bytes in the appearance");
|
||||
}
|
||||
|
||||
/// A custom stamp with a line keeps its picture's shape over the line on a turned page: it is
|
||||
/// laid out in the displayed box, then turned into `/Rect`. Laid out in user space, a quarter
|
||||
/// turn squashed the picture into a narrow strip and stretched the band.
|
||||
#[test]
|
||||
fn a_lined_custom_stamp_keeps_its_layout_on_turned_pages() {
|
||||
let colours = [[240, 20, 20, 255], [20, 180, 20, 255], [20, 20, 240, 255], [230, 180, 20, 255]];
|
||||
let image = image::RgbaImage::from_fn(80, 40, |x, y| image::Rgba(colours[usize::from(y >= 20) * 2 + usize::from(x >= 40)]));
|
||||
let mut png = std::io::Cursor::new(Vec::new());
|
||||
image.write_to(&mut png, image::ImageFormat::Png).unwrap();
|
||||
let bytes = Arc::new(png.into_inner());
|
||||
// A short line: the stamp is the picture's 80 pt wide, 40 / 0.78 pt tall with its band.
|
||||
let (w, h) = pdfcraft_annot::custom_stamp_size((80.0, 40.0), Some("OK"));
|
||||
assert_eq!(w, 80.0);
|
||||
let top = 100.0 - h / 2.0;
|
||||
for degrees in [0, 90, 180, 270] {
|
||||
let (mut session, id) = session_with(1);
|
||||
session.apply(id, Edit::RotatePages { pages: vec![0], degrees }).unwrap();
|
||||
let at = session.get(id).unwrap().info.pages[0].view_to_user(100.0, 100.0).map(f64::from);
|
||||
let edit = Edit::AddCustomStamp {
|
||||
page: 0,
|
||||
rect: [at[0], at[1], at[0], at[1]],
|
||||
name: "Quadrants".into(),
|
||||
file: MarkFile { name: "quadrants.png".into(), bytes: bytes.clone(), page: 0 },
|
||||
author: "Test".into(),
|
||||
line: Some("OK".into()),
|
||||
};
|
||||
session.apply(id, edit).unwrap();
|
||||
let doc = session.get(id).unwrap();
|
||||
let mut renderer = pdfcraft_render::PageRenderer::new(doc.bytes.clone(), doc.config.clone());
|
||||
let rendered = renderer.render(pdfcraft_render::RenderRequest { page: 0, scale: 1.0, ..Default::default() });
|
||||
assert!(rendered.error.is_none(), "{:?}", rendered.error);
|
||||
let pixel = |x: f64, y: f64| {
|
||||
let offset = ((y as u32 * rendered.width + x as u32) * 4) as usize;
|
||||
rendered.rgba[offset..offset + 4].to_vec()
|
||||
};
|
||||
// The picture fills the top 80 x 40 pt of the displayed box, its quadrants in place.
|
||||
let points = [(70.0, top + 5.0), (130.0, top + 5.0), (70.0, top + 35.0), (130.0, top + 35.0)];
|
||||
for ((x, y), colour) in points.into_iter().zip(colours) {
|
||||
assert_eq!(pixel(x, y), colour, "page rotation {degrees}; displayed point ({x}, {y})");
|
||||
}
|
||||
// The band under it holds no picture.
|
||||
assert_eq!(pixel(64.0, top + h - 3.0), [255, 255, 255, 255], "page rotation {degrees}: the band");
|
||||
}
|
||||
}
|
||||
|
||||
fn contains(haystack: &[u8], needle: &[u8]) -> bool {
|
||||
haystack.windows(needle.len()).any(|w| w == needle)
|
||||
}
|
||||
|
||||
@@ -1051,6 +1051,8 @@ mod tests {
|
||||
flags: 0,
|
||||
max_len: None,
|
||||
options: Vec::new(),
|
||||
selected: Vec::new(),
|
||||
single_value_is_array: false,
|
||||
da: String::new(),
|
||||
quadding: 0,
|
||||
tooltip: None,
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
//! A check box the file leaves to the viewer draws its `/MK /CA` caption `4` in ZapfDingbats
|
||||
//! (ISO 32000-2 Table 192 and §12.7.5.2.3), and the standard font's bundled stand-in draws that
|
||||
//! check mark (a20, Annex D.6) at its standard advance (§9.6.2.2): centred in the box, at the
|
||||
//! `/DA` size, neither squeezed nor spilling past its advance.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use pdfcraft_cos::{Document, SaveOptions, write_incremental};
|
||||
use pdfcraft_fonts::Std14;
|
||||
use pdfcraft_render::{PageRenderer, RenderConfig, RenderRequest};
|
||||
|
||||
/// The `/DA` size of the check, in points (and pixels, at scale 1).
|
||||
const SIZE: f64 = 60.0;
|
||||
|
||||
fn pdf(objects: &[&str]) -> Vec<u8> {
|
||||
let mut bytes = b"%PDF-1.7\n".to_vec();
|
||||
let mut offsets = Vec::new();
|
||||
for (i, object) in objects.iter().enumerate() {
|
||||
offsets.push(bytes.len());
|
||||
bytes.extend_from_slice(format!("{} 0 obj\n{object}\nendobj\n", i + 1).as_bytes());
|
||||
}
|
||||
let xref = bytes.len();
|
||||
bytes.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objects.len() + 1).as_bytes());
|
||||
for offset in offsets {
|
||||
bytes.extend_from_slice(format!("{offset:010} 00000 n \n").as_bytes());
|
||||
}
|
||||
bytes.extend_from_slice(format!("trailer << /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objects.len() + 1).as_bytes());
|
||||
bytes
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_check_box_caption_check_is_drawn_at_its_standard_advance() {
|
||||
// A 100 pt box at (50, 50) on a 200 pt page, with no border, no background and no /AP.
|
||||
let bytes = pdf(&[
|
||||
"<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>",
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
|
||||
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Annots [5 0 R] >>",
|
||||
"<< /Fields [5 0 R] /NeedAppearances true >>",
|
||||
"<< /Type /Annot /Subtype /Widget /FT /Btn /T (c) /V /Yes /AS /Yes /DA (/ZaDb 60 Tf 0 g) /MK << /CA (4) >> /Rect [50 50 150 150] /F 4 /P 3 0 R >>",
|
||||
]);
|
||||
let doc = Document::open(Arc::new(bytes)).expect("the fixture opens");
|
||||
let shown = pdfcraft_forms::with_field_appearances(&doc).expect("the check box gets an appearance");
|
||||
let bytes = write_incremental(&shown, &SaveOptions::default()).expect("the display copy saves");
|
||||
let mut renderer = PageRenderer::new(Arc::new(bytes), RenderConfig::default());
|
||||
let page = renderer.render(RenderRequest { page: 0, scale: 1.0, ..Default::default() });
|
||||
assert!(page.error.is_none(), "{:?}", page.error);
|
||||
|
||||
// The bounding box of the dark pixels, in pixels from the top left.
|
||||
let (mut x0, mut y0, mut x1, mut y1) = (u32::MAX, u32::MAX, 0, 0);
|
||||
for y in 0..page.height {
|
||||
for x in 0..page.width {
|
||||
let at = usize::try_from((y * page.width + x) * 4).unwrap_or(usize::MAX);
|
||||
if page.rgba.get(at).is_some_and(|r| *r < 128) {
|
||||
(x0, y0, x1, y1) = (x0.min(x), y0.min(y), x1.max(x), y1.max(y));
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(x0 <= x1, "the check is drawn");
|
||||
let (x0, y0, x1, y1) = (f64::from(x0), f64::from(y0), f64::from(x1 + 1), f64::from(y1 + 1));
|
||||
|
||||
// The check's advance, centred across the box: 846 units at 60 pt is 50.76 pt.
|
||||
let advance = Std14::ZapfDingbats.advance(b'4', SIZE);
|
||||
assert_eq!(Std14::ZapfDingbats.width(b'4'), 846.0, "a20's standard width");
|
||||
let left = 50.0 + (100.0 - advance) / 2.0;
|
||||
assert!(x0 >= left - 1.0 && x1 <= left + advance + 1.0, "the check stays within its advance {left}..{}: {x0}..{x1}", left + advance);
|
||||
assert!(x1 - x0 >= 0.8 * advance, "the check is not squeezed: {} px of {advance}", x1 - x0);
|
||||
assert!(((x0 + x1) / 2.0 - 100.0).abs() <= 3.0, "the check is centred across the box: {x0}..{x1}");
|
||||
// Inside the box vertically, and about as tall as the font size makes it.
|
||||
assert!(y0 >= 50.0 && y1 <= 150.0, "the check stays inside the box: {y0}..{y1}");
|
||||
assert!((0.5 * SIZE..=0.85 * SIZE).contains(&(y1 - y0)), "the check is {} px tall at {SIZE} pt", y1 - y0);
|
||||
}
|
||||
@@ -4,6 +4,7 @@ mod support {
|
||||
pub mod font_fixture;
|
||||
}
|
||||
|
||||
mod dingbat_check_box;
|
||||
mod document_fonts;
|
||||
mod form_rotation;
|
||||
mod marked_content_isolation;
|
||||
|
||||
@@ -34,7 +34,7 @@ pub use script::{
|
||||
pub use shaping::{
|
||||
ShapedCluster, ShapedScript, arabic_glyph, arabic_has, face_glyph, hebrew_has, shape_arabic, shape_hebrew, shape_thai, shaped_glyph, thai_has,
|
||||
};
|
||||
pub use std14::Std14;
|
||||
pub use std14::{Match as Std14Match, Std14};
|
||||
|
||||
/// Advance of `s` in Helvetica at `size` points, using the exact standard-14 metrics.
|
||||
///
|
||||
|
||||
@@ -1423,6 +1423,115 @@ pub fn glyph_unicode(name: &str) -> Option<char> {
|
||||
chars.next().filter(|_| chars.len() == 0)
|
||||
}
|
||||
|
||||
/// What each code of an embedded TrueType font that isn't flagged non-symbolic and names no base
|
||||
/// encoding shows, by the `post` table name of the glyph its `cmap` selects (the way the renderer
|
||||
/// selects it: the code, then at 0xF000, 0xF100 and 0xF200). Such a font's codes need not be
|
||||
/// Standard or WinAnsi: FrameMaker files distilled with Distiller 3 number them in the Macintosh
|
||||
/// glyph order, 29 below ASCII, so `Solid` read as `6ROLG` and typing set the wrong glyphs (#3962).
|
||||
/// Codes without a glyph, and fonts whose `post` table names no glyphs, are left out (the latter
|
||||
/// to [`symbolic_mac_roman_texts`]). A code whose glyph has no name with a Unicode value reads
|
||||
/// as WinAnsi, as the renderer reads it (vendored hayro-interpret patch (79)), so the editor and
|
||||
/// extraction agree: `€` for code 0x80, which Standard leaves without a character.
|
||||
fn symbolic_glyph_texts(doc: &Document, font: &Dict) -> Vec<(u32, String)> {
|
||||
use skrifa::GlyphId;
|
||||
use skrifa::raw::{FontData, FontRead as _, TableProvider as _, tables::cmap::PlatformId, tables::post::Post, types::Tag};
|
||||
let Some(descriptor) = dict(doc, font.get(b"FontDescriptor")) else { return Vec::new() };
|
||||
// Flag bit 6, Nonsymbolic (ISO 32000-2 Table 121).
|
||||
if descriptor_flags(doc, &descriptor) & 32 != 0 {
|
||||
return Vec::new();
|
||||
}
|
||||
let Some(object) = descriptor.get(b"FontFile2") else { return Vec::new() };
|
||||
let object = doc.resolve(object);
|
||||
let Object::Stream(stream) = object.as_ref() else { return Vec::new() };
|
||||
let Ok(bytes) = doc.with_direct_parms(stream).decoded_within(MAX_SFNT) else { return Vec::new() };
|
||||
let Ok(face) = skrifa::FontRef::from_index(&bytes, 0) else { return Vec::new() };
|
||||
let Ok(cmap) = face.cmap() else { return Vec::new() };
|
||||
// A `post` version written with its 16-bit halves swapped (`00 00 00 02` for 2.0, as ScanSoft
|
||||
// PDF Create! writes it) is read as the version it means, as the renderer reads it (#2946,
|
||||
// vendored hayro-interpret patch (49)); otherwise its names would be lost here alone.
|
||||
let repaired = face.table_data(Tag::new(b"post")).and_then(|data| match data.as_bytes() {
|
||||
[0, 0, 0, n @ 1..=3, rest @ ..] => Some([&[0, *n, 0, 0], rest].concat()),
|
||||
_ => None,
|
||||
});
|
||||
let post = match &repaired {
|
||||
Some(bytes) => Post::read(FontData::new(bytes)),
|
||||
None => face.post(),
|
||||
};
|
||||
let Ok(post) = post else { return Vec::new() };
|
||||
// A font that names no glyphs (no `post` table of version 1.0, or one of version 2.0 with an
|
||||
// empty name index) is left to `symbolic_mac_roman_texts` and the encoding's reading.
|
||||
let names_glyphs = match post.version() {
|
||||
skrifa::raw::types::Version16Dot16::VERSION_1_0 => true,
|
||||
skrifa::raw::types::Version16Dot16::VERSION_2_0 => post.glyph_name_index().is_some_and(|index| !index.is_empty()),
|
||||
_ => false,
|
||||
};
|
||||
if !names_glyphs {
|
||||
return Vec::new();
|
||||
}
|
||||
let custom = post_custom_names(&post);
|
||||
(0..=255u32)
|
||||
.filter_map(|code| {
|
||||
// The records in order, as the renderer's `map_code` reads a symbolic font: a Windows
|
||||
// symbol or Unicode cmap with the code and the code at 0xF000, 0xF100 and 0xF200, a
|
||||
// Macintosh or Unicode-platform one with the code alone; the first glyph found wins.
|
||||
let glyph = cmap.encoding_records().iter().find_map(|record| {
|
||||
let offsets: &[u32] = match (record.platform_id(), record.encoding_id()) {
|
||||
(PlatformId::Windows, 0 | 1) => &[0, 0xF000, 0xF100, 0xF200],
|
||||
(PlatformId::Macintosh | PlatformId::Unicode, 0) => &[0],
|
||||
_ => return None,
|
||||
};
|
||||
let subtable = record.subtable(cmap.offset_data()).ok()?;
|
||||
offsets.iter().find_map(|o| subtable.map_codepoint(code + o).filter(|g| *g != GlyphId::NOTDEF))
|
||||
})?;
|
||||
let glyph = u16::try_from(glyph.to_u32()).ok()?;
|
||||
let winansi = || {
|
||||
let u = crate::encodings::WIN_ANSI.get(usize::try_from(code).ok()?).copied().filter(|u| *u != 0)?;
|
||||
char::from_u32(u).map(String::from)
|
||||
};
|
||||
let text = post_name(&post, &custom, glyph).filter(|n| uppercase_hex_forms(n)).and_then(glyph_text);
|
||||
Some((code, text.or_else(winansi)?))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Whether the `uni` and `u` components of a glyph name spell their hex digits in uppercase, as
|
||||
/// the glyph list specification's forms do (ISO 32000-2 §9.10.2): `uni1eae` names nothing, so
|
||||
/// its glyph's code reads as WinAnsi, as the renderer reads it (vendored hayro-interpret patch
|
||||
/// (79)). A component that is a list name (`a`, `ecircumflex`) is read as such whatever its case.
|
||||
fn uppercase_hex_forms(name: &str) -> bool {
|
||||
let stem = name.split('.').next().unwrap_or_default();
|
||||
stem.split('_').all(|part| {
|
||||
// Outside the list, a component `glyph_text` reads is `u` or `uni` and hex digits, so a
|
||||
// lowercase `a` to `f` in it is a lowercase digit.
|
||||
crate::encodings::NAMES.binary_search_by(|(n, _)| (*n).cmp(part)).is_ok() || !part.bytes().any(|b| matches!(b, b'a'..=b'f'))
|
||||
})
|
||||
}
|
||||
|
||||
/// The names a version 2.0 `post` table spells out, in order, read once. `Post::glyph_name` walks
|
||||
/// this data from its start for each glyph it is asked about, which over a font program of up to
|
||||
/// 16 MiB, asked about 256 codes, is work an untrusted file can make large. Reading stops at the
|
||||
/// first name that can't be read, as each lookup would.
|
||||
fn post_custom_names<'a>(post: &skrifa::raw::tables::post::Post<'a>) -> Vec<&'a str> {
|
||||
post.string_data().map(|names| names.iter().map_while(|name| name.ok().map(|n| n.as_str())).collect()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// `glyph`'s name in `post`, as `Post::glyph_name` gives it, with the table's own names from
|
||||
/// [`post_custom_names`].
|
||||
fn post_name<'a>(post: &skrifa::raw::tables::post::Post<'a>, custom: &[&'a str], glyph: u16) -> Option<&'a str> {
|
||||
use skrifa::raw::{tables::post::DEFAULT_GLYPH_NAMES, types::Version16Dot16};
|
||||
match post.version() {
|
||||
Version16Dot16::VERSION_1_0 => DEFAULT_GLYPH_NAMES.get(usize::from(glyph)).copied(),
|
||||
Version16Dot16::VERSION_2_0 => {
|
||||
let index = usize::from(post.glyph_name_index()?.get(usize::from(glyph))?.get());
|
||||
match index.checked_sub(DEFAULT_GLYPH_NAMES.len()) {
|
||||
None => DEFAULT_GLYPH_NAMES.get(index).copied(),
|
||||
Some(i) => custom.get(i).copied(),
|
||||
}
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Code → Unicode for a font: its ToUnicode CMap (for a composite font, also the name
|
||||
/// `/Identity-H` or `/Identity-V`, read as code = Unicode), else (simple fonts) its encoding.
|
||||
fn unicode_map(doc: &Document, font: &Dict, composite: bool) -> Unicode {
|
||||
@@ -1465,7 +1574,12 @@ fn unicode_map(doc: &Document, font: &Dict, composite: bool) -> Unicode {
|
||||
out.encoding.insert(code as u32, c.to_string());
|
||||
}
|
||||
}
|
||||
// A font named as Symbol or ZapfDingbats keeps reporting nothing: its names may be as
|
||||
// un-Latin as its codes (WordPerfect's WPTypographicSymbols calls its apostrophe `equal`).
|
||||
// A font whose `post` table names its glyphs reads by those names; one that names none
|
||||
// and keeps the Macintosh order reads as Mac OS Roman, over the WinAnsi fallback.
|
||||
if base_name.is_none() && !symbolic_builtin {
|
||||
out.encoding.extend(symbolic_glyph_texts(doc, font));
|
||||
out.encoding.extend(symbolic_mac_roman_texts(doc, font));
|
||||
}
|
||||
if let Some(Object::Dict(d)) = enc.as_deref()
|
||||
|
||||
@@ -214,6 +214,194 @@ fn mac_subset_cmap_uses_pdf_unicode_without_changing_source_program() {
|
||||
assert!(append_editor_cmap(&mut broken, &std::collections::BTreeMap::from([(65, 1)])).is_none());
|
||||
}
|
||||
|
||||
/// The names read once give what `Post::glyph_name` gives, for every glyph of a font with its
|
||||
/// own names (Inter's version 2.0 table), and none past the last glyph.
|
||||
#[test]
|
||||
fn post_names_read_once_match_the_table() {
|
||||
use skrifa::raw::TableProvider as _;
|
||||
let face = skrifa::FontRef::new(include_bytes!("../../../../assets/fonts/Inter-Regular.ttf")).unwrap();
|
||||
let post = face.post().unwrap();
|
||||
let custom = post_custom_names(&post);
|
||||
assert!(custom.len() > 100, "Inter names glyphs of its own: {}", custom.len());
|
||||
let glyphs = face.maxp().unwrap().num_glyphs();
|
||||
for g in 0..glyphs {
|
||||
assert_eq!(post_name(&post, &custom, g), post.glyph_name(skrifa::raw::types::GlyphId16::new(g)), "glyph {g}");
|
||||
}
|
||||
assert_eq!(post_name(&post, &custom, glyphs), None);
|
||||
}
|
||||
|
||||
/// #3962: a symbolic TrueType subset with no `/Encoding` whose codes are glyph positions in
|
||||
/// the Macintosh order, 29 below ASCII, mapped by a Mac (1,0) cmap. Its text is what the
|
||||
/// `post` table names the glyphs its codes select, and typing encodes back to those codes.
|
||||
/// A (3,0) symbol cmap at 0xF000 + code is read too: code 0x20, `.notdef` in the Mac table,
|
||||
/// shows `k` there, code 0xC0 `é`, and code 0xC1 the variant `a.1`, whose suffix is dropped.
|
||||
/// Records are read in order, each with its offsets, as the renderer reads them: 0xC2 is the
|
||||
/// symbol cmap's `x`, not a later (3,1) cmap's `z`.
|
||||
#[test]
|
||||
fn a_symbolic_truetype_font_without_an_encoding_reads_its_glyph_names() {
|
||||
use skrifa::{MetadataProvider as _, raw::TableProvider as _};
|
||||
const TEXT: &str = "Solid state";
|
||||
let original = include_bytes!("../../../../assets/fonts/Inter-Regular.ttf");
|
||||
let face = skrifa::FontRef::new(original).unwrap();
|
||||
let charmap = face.charmap();
|
||||
let post = face.post().unwrap();
|
||||
let variant = (1..face.maxp().unwrap().num_glyphs())
|
||||
.find(|&g| post.glyph_name(skrifa::raw::types::GlyphId16::new(g)) == Some("a.1"))
|
||||
.expect("Inter has a.1");
|
||||
// A glyph whose name has no Unicode value: its code reads as WinAnsi, as the renderer reads it.
|
||||
let unnamed = (1..face.maxp().unwrap().num_glyphs())
|
||||
.find(|&g| post.glyph_name(skrifa::raw::types::GlyphId16::new(g)).is_some_and(|n| !n.starts_with('.') && glyph_text(n).is_none()))
|
||||
.expect("Inter has a glyph whose name has no text");
|
||||
// A format 6 Mac cmap over codes 3..=0x57: each letter at its code minus 29.
|
||||
let (first, last) = (3u16, 0x57u16);
|
||||
let mut glyphs = vec![0u16; usize::from(last - first + 1)];
|
||||
for c in TEXT.chars() {
|
||||
glyphs[usize::from(c as u16 - 29 - first)] = u16::try_from(charmap.map(c).unwrap().to_u32()).unwrap();
|
||||
}
|
||||
let mac_len = 10 + 2 * glyphs.len() as u16;
|
||||
let gid = |c: char| u16::try_from(charmap.map(c).unwrap().to_u32()).unwrap();
|
||||
let mut mac = vec![0, 6];
|
||||
mac.extend_from_slice(&mac_len.to_be_bytes());
|
||||
mac.extend_from_slice(&[0, 0]);
|
||||
mac.extend_from_slice(&first.to_be_bytes());
|
||||
mac.extend_from_slice(&(glyphs.len() as u16).to_be_bytes());
|
||||
glyphs.iter().for_each(|g| mac.extend_from_slice(&g.to_be_bytes()));
|
||||
// A format 4 subtable: one segment per code, then the closing 0xFFFF segment.
|
||||
let format4 = |map: &[(u16, u16)]| {
|
||||
let segments: Vec<(u16, u16)> = map.iter().copied().chain([(0xFFFF, 0)]).collect();
|
||||
let n = segments.len() as u16;
|
||||
let words: Vec<u16> = [4, 16 + 8 * n, 0, 2 * n, 2, 0, 2 * n - 2]
|
||||
.into_iter()
|
||||
.chain(segments.iter().map(|s| s.0))
|
||||
.chain([0])
|
||||
.chain(segments.iter().map(|s| s.0))
|
||||
.chain(segments.iter().map(|&(code, glyph)| if code == 0xFFFF { 1 } else { glyph.wrapping_sub(code) }))
|
||||
.chain(segments.iter().map(|_| 0))
|
||||
.collect();
|
||||
words.iter().flat_map(|w| w.to_be_bytes()).collect::<Vec<u8>>()
|
||||
};
|
||||
// A glyph whose name the table spells `uni1eae`, lowercase, below: the glyph list
|
||||
// specification's hex digits are uppercase (ISO 32000-2 §9.10.2), so it names nothing.
|
||||
let lowercase = (1..face.maxp().unwrap().num_glyphs())
|
||||
.find(|&g| post.glyph_name(skrifa::raw::types::GlyphId16::new(g)) == Some("uni1EAE"))
|
||||
.expect("Inter has uni1EAE");
|
||||
// Symbol (3,0): 0xF020 → k, 0xF0C0 → é, 0xF0C1 → a.1, 0xF0C2 → x, 0xF0C4 → the unnamed glyph,
|
||||
// 0xF0C5 → the one spelt in lowercase.
|
||||
let symbol = format4(&[
|
||||
(0xF020, gid('k')),
|
||||
(0xF0C0, gid('é')),
|
||||
(0xF0C1, variant),
|
||||
(0xF0C2, gid('x')),
|
||||
(0xF0C3, gid('w')),
|
||||
(0xF0C4, unnamed),
|
||||
(0xF0C5, lowercase),
|
||||
]);
|
||||
// Unicode (3,1), after it: 0xC2 → z. The renderer reads the (3,0) record, offsets and
|
||||
// all, before this one, so code 0xC2 is `x`.
|
||||
let unicode = format4(&[(0xC2, gid('z'))]);
|
||||
// A Unicode-platform (0,3) record, first, which the renderer doesn't read: 0xC3 → q there,
|
||||
// so code 0xC3 is the symbol cmap's `w`.
|
||||
let platform0 = format4(&[(0xC3, gid('q'))]);
|
||||
// Four records, in platform order as the cmap table requires.
|
||||
let at = |n: usize| (36 + n) as u32;
|
||||
let mut cmap = vec![0, 0, 0, 4];
|
||||
for (platform, encoding, offset) in [
|
||||
(0u16, 3u16, at(0)),
|
||||
(1, 0, at(platform0.len())),
|
||||
(3, 0, at(platform0.len() + mac.len())),
|
||||
(3, 1, at(platform0.len() + mac.len() + symbol.len())),
|
||||
] {
|
||||
cmap.extend_from_slice(&platform.to_be_bytes());
|
||||
cmap.extend_from_slice(&encoding.to_be_bytes());
|
||||
cmap.extend_from_slice(&offset.to_be_bytes());
|
||||
}
|
||||
cmap.extend(platform0);
|
||||
cmap.extend(mac);
|
||||
cmap.extend(symbol);
|
||||
cmap.extend(unicode);
|
||||
let mut subset = original.to_vec();
|
||||
let count = u16::from_be_bytes(subset[4..6].try_into().unwrap()) as usize;
|
||||
let entry = (0..count).map(|i| 12 + i * 16).find(|i| &subset[*i..*i + 4] == b"cmap").unwrap();
|
||||
let offset = subset.len() as u32;
|
||||
subset[entry + 8..entry + 12].copy_from_slice(&offset.to_be_bytes());
|
||||
subset[entry + 12..entry + 16].copy_from_slice(&(cmap.len() as u32).to_be_bytes());
|
||||
subset.extend_from_slice(&cmap);
|
||||
// The `post` table's own spelling of that name, a Pascal string, lowercased in place.
|
||||
let spelt = b"\x07uni1EAE";
|
||||
assert_eq!(subset.windows(spelt.len()).filter(|w| w == spelt).count(), 1);
|
||||
let spot = subset.windows(spelt.len()).position(|w| w == spelt).unwrap();
|
||||
subset[spot..spot + spelt.len()].copy_from_slice(b"\x07uni1eae");
|
||||
let codes: Vec<u8> = TEXT.bytes().map(|b| b - 29).collect();
|
||||
let metrics = |flags: i64, encoding: Option<Object>| {
|
||||
let mut doc = Document::new_empty();
|
||||
let program = doc.add(Object::Stream(Stream::flate(Dict::new(), &subset)));
|
||||
let mut descriptor = Dict::new();
|
||||
descriptor.set(b"Flags".to_vec(), Object::Int(flags));
|
||||
descriptor.set(b"FontFile2".to_vec(), Object::Ref(program));
|
||||
let mut entries = vec![("Subtype", Object::name("TrueType")), ("FontDescriptor", Object::Dict(descriptor))];
|
||||
if let Some(encoding) = encoding {
|
||||
entries.push(("Encoding", encoding));
|
||||
}
|
||||
let f = font(&mut doc, entries);
|
||||
Metrics::from_dict(&doc, &f)
|
||||
};
|
||||
let symbolic = metrics(4, None);
|
||||
assert_eq!(symbolic.decode(&codes), TEXT);
|
||||
// The same font with its `post` version halves swapped (`00 00 00 02`) reads the same,
|
||||
// as the renderer reads it (#2946).
|
||||
let post = (0..count).map(|i| 12 + i * 16).find(|i| &subset[*i..*i + 4] == b"post").unwrap();
|
||||
let at = u32::from_be_bytes(subset[post + 8..post + 12].try_into().unwrap()) as usize;
|
||||
assert_eq!(subset[at..at + 4], [0, 2, 0, 0], "Inter's post is version 2.0");
|
||||
let mut swapped = subset.clone();
|
||||
swapped[at..at + 4].copy_from_slice(&[0, 0, 0, 2]);
|
||||
let mut doc = Document::new_empty();
|
||||
let program = doc.add(Object::Stream(Stream::flate(Dict::new(), &swapped)));
|
||||
let mut descriptor = Dict::new();
|
||||
descriptor.set(b"Flags".to_vec(), Object::Int(4));
|
||||
descriptor.set(b"FontFile2".to_vec(), Object::Ref(program));
|
||||
let f = font(&mut doc, vec![("Subtype", Object::name("TrueType")), ("FontDescriptor", Object::Dict(descriptor))]);
|
||||
assert_eq!(Metrics::from_dict(&doc, &f).decode(&codes), TEXT, "a swapped post version");
|
||||
assert_eq!(symbolic.decode(&[0x20, 0xC0, 0xC1, 0xC2, 0xC3]), "kéaxw");
|
||||
assert_eq!(symbolic.decode(&[0xC4]), "Ä", "a glyph name with no text reads as WinAnsi, not Standard's `tilde`");
|
||||
assert_eq!(symbolic.decode(&[0xC5]), "Å", "`uni1eae` names nothing, so the code reads as WinAnsi, not U+1EAE");
|
||||
assert_eq!(symbolic.encode("Solid").as_deref(), Some(&codes[..5]), "typing sets the same glyphs");
|
||||
// A named encoding, or the Nonsymbolic flag, says what the codes are: they read through it.
|
||||
assert_eq!(metrics(4, Some(Object::name("WinAnsiEncoding"))).decode(&codes), "6ROLGVWDWH");
|
||||
// `/Differences` still names its codes: 0x36 shows `A` there, not the glyph's `S`.
|
||||
let mut differences = Dict::new();
|
||||
differences.set(b"Differences".to_vec(), Object::Array(vec![Object::Int(0x36), Object::name("A")]));
|
||||
assert_eq!(metrics(4, Some(Object::Dict(differences))).decode(&codes), "Aolid state");
|
||||
assert_eq!(metrics(32, None).decode(&codes), "6ROLGVWDWH");
|
||||
// A font named as a symbol font reports nothing, as before: its glyph names can't be
|
||||
// trusted to be Latin either.
|
||||
let mut doc = Document::new_empty();
|
||||
let program = doc.add(Object::Stream(Stream::flate(Dict::new(), &subset)));
|
||||
let mut descriptor = Dict::new();
|
||||
descriptor.set(b"Flags".to_vec(), Object::Int(4));
|
||||
descriptor.set(b"FontFile2".to_vec(), Object::Ref(program));
|
||||
let f = font(
|
||||
&mut doc,
|
||||
vec![
|
||||
("Subtype", Object::name("TrueType")),
|
||||
("BaseFont", Object::name("KNMDCP+WPTypographicSymbols")),
|
||||
("FontDescriptor", Object::Dict(descriptor)),
|
||||
],
|
||||
);
|
||||
assert_eq!(Metrics::from_dict(&doc, &f).decode(&codes), "");
|
||||
}
|
||||
|
||||
/// The glyph list specification's `uni` and `u` forms spell their hex digits in uppercase
|
||||
/// (ISO 32000-2 §9.10.2); list names keep their own case.
|
||||
#[test]
|
||||
fn glyph_names_with_lowercase_hex_digits_name_nothing() {
|
||||
for name in ["uni1EAE", "u1F600", "a", "ecircumflex", "f_i", "a.ss01", "uni0041_uni0042"] {
|
||||
assert!(uppercase_hex_forms(name), "{name}");
|
||||
}
|
||||
for name in ["uni1eae", "u1f600", "uni20ac.alt", "f_uni20ac", "uni0041_uni00e9"] {
|
||||
assert!(!uppercase_hex_forms(name), "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
fn metrics_with_flags(flags: Option<Object>) -> Metrics {
|
||||
let mut doc = Document::new_empty();
|
||||
let mut descriptor = Dict::new();
|
||||
|
||||
@@ -858,11 +858,15 @@ fn field_appearance_fit(doc: &Document, f: &Field, w: &Widget, values: &[String]
|
||||
size = rows.size;
|
||||
let line = rows.row;
|
||||
let mut y = height - rows.inset;
|
||||
for (export, display) in f.options.iter().skip(rows.top) {
|
||||
// The field's own selection (its `/I`) when these are its values; values it doesn't
|
||||
// hold yet select by export value alone.
|
||||
let picked = if values == f.value.as_slice() { f.selected.clone() } else { crate::selected_options(&f.options, values, None) };
|
||||
for (i, (_, display)) in f.options.iter().enumerate().skip(rows.top) {
|
||||
if y - line < 0.0 {
|
||||
break;
|
||||
}
|
||||
if values.contains(export) {
|
||||
// Both sources list positions in ascending order.
|
||||
if picked.binary_search(&i).is_ok() {
|
||||
c.push_str(&format!("0.6 0.75 0.86 rg\n{} {} {} {} re f\n", n(bw), n(y - line), n(width - 2.0 * bw), n(line)));
|
||||
}
|
||||
show(pad, y - line + size * 0.25, display);
|
||||
|
||||
+88
-7
@@ -42,10 +42,11 @@ mod values;
|
||||
|
||||
pub use appearances::{FieldAppearanceCache, declares_pdfa, need_appearances, undrawn_fields, with_field_appearances, with_field_appearances_cached};
|
||||
pub(crate) use read::page_refs;
|
||||
pub use read::selected_options;
|
||||
pub use read::{Fields, acroform, adopted_page_fields, fields, fields_with_adopted};
|
||||
#[cfg(test)]
|
||||
use read::{MAX_SCRIPT_BYTES, PageWalk, enumerate, form_reads};
|
||||
use read::{script, script_budget};
|
||||
use read::{first_by_export, script, script_budget};
|
||||
pub use tab_order::{TabOrder, move_in_tab_order, set_tab_order, tab_orders};
|
||||
#[cfg(test)]
|
||||
use values::has_password_flag;
|
||||
@@ -159,6 +160,14 @@ pub struct Field {
|
||||
pub max_len: Option<usize>,
|
||||
/// Choice options: (export value, display text).
|
||||
pub options: Vec<(String, String)>,
|
||||
/// Combo and list boxes: the selected options, as ascending positions in `options` (see
|
||||
/// [`selected_options`]). Two options can share an export value, so `value` alone can't say
|
||||
/// which of them is selected. Empty for other kinds.
|
||||
pub selected: Vec<usize>,
|
||||
/// A list box without MultiSelect whose `/V` is an array (a value of one option is a string,
|
||||
/// ISO 32000-2 Table 233): `value` holds its first entry only, and picking that option again
|
||||
/// writes the value as one string rather than leaving the array.
|
||||
pub single_value_is_array: bool,
|
||||
/// Default appearance string (`/DA`, inherited from the form if absent).
|
||||
pub da: String,
|
||||
/// Quadding: 0 left, 1 centred, 2 right.
|
||||
@@ -252,18 +261,75 @@ impl Field {
|
||||
&& self.widgets.iter().position(|x| sharing(x) && x.state.is_none()) == Some(i)
|
||||
}
|
||||
|
||||
/// The value that gives this check box the stored value `value` (`/V`, `/DV`, imported or
|
||||
/// script data): the on state it names (or whose `/Opt` export it is), so that of kids with
|
||||
/// different on states the right one turns on (ISO 32000-2 §12.7.5.2.3, Table 230); checked
|
||||
/// for any other value but Off, unchecked for none.
|
||||
pub fn check_box_value(&self, value: Option<&str>) -> FieldValue {
|
||||
match value.filter(|v| !v.is_empty() && *v != "Off") {
|
||||
Some(v) => self.state_for(v).map_or(FieldValue::Check(true), |s| FieldValue::Text(s.to_owned())),
|
||||
None => FieldValue::Check(false),
|
||||
}
|
||||
}
|
||||
|
||||
/// Combo and list boxes: this field's option positions `picked` as positions in `other`'s
|
||||
/// options, in the same order. Same-name twins are one field (ISO 32000-2 §12.7.3.1) but can
|
||||
/// list their options in different orders, and a value given by position is read in the first
|
||||
/// twin's options. `None` when an option picked has no match in `other`.
|
||||
pub fn positions_in(&self, other: &Field, picked: &[usize]) -> Option<Vec<usize>> {
|
||||
option_positions_in(picked, &self.options, &other.options)
|
||||
}
|
||||
|
||||
/// Combo and list boxes: the selected options in the order the value names them (`/V` keeps
|
||||
/// the order they were picked in), so the last is the latest pick.
|
||||
pub fn picked_in_order(&self) -> Vec<usize> {
|
||||
let mut out: Vec<usize> = Vec::with_capacity(self.selected.len());
|
||||
let mut taken: std::collections::HashSet<usize> = std::collections::HashSet::with_capacity(self.selected.len());
|
||||
let mut unpicked = self.selected_by_export();
|
||||
for v in &self.value {
|
||||
if let Some(i) = unpicked.get_mut(v.as_str()).and_then(std::collections::VecDeque::pop_front) {
|
||||
taken.insert(i);
|
||||
out.push(i);
|
||||
}
|
||||
}
|
||||
// Positions `/I` holds beyond what the value names (none while the two agree).
|
||||
out.extend(self.selected.iter().copied().filter(|i| !taken.contains(i)));
|
||||
out
|
||||
}
|
||||
|
||||
/// The value as one string: text, the state name, or the selected display texts.
|
||||
pub fn display_value(&self) -> String {
|
||||
match self.kind {
|
||||
FieldKind::Combo | FieldKind::List => self
|
||||
.value
|
||||
.iter()
|
||||
.map(|v| self.options.iter().find(|(e, _)| e == v).map_or(v.clone(), |(_, d)| d.clone()))
|
||||
.collect::<Vec<_>>()
|
||||
.join(", "),
|
||||
FieldKind::Combo | FieldKind::List => {
|
||||
// Each value as the selected option it names (options can share an export
|
||||
// value), in the value's order; past those, the first option exporting it.
|
||||
let mut unpicked = self.selected_by_export();
|
||||
let first = first_by_export(&self.options);
|
||||
self.value
|
||||
.iter()
|
||||
.map(|v| {
|
||||
let i =
|
||||
unpicked.get_mut(v.as_str()).and_then(std::collections::VecDeque::pop_front).or_else(|| first.get(v.as_str()).copied());
|
||||
i.and_then(|i| self.options.get(i)).map_or(v.clone(), |(_, d)| d.clone())
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ")
|
||||
}
|
||||
_ => self.value.join(", "),
|
||||
}
|
||||
}
|
||||
|
||||
/// The selected positions grouped by the export value of their option, each group
|
||||
/// ascending, so a value takes the next selected option exporting it in one lookup.
|
||||
fn selected_by_export(&self) -> std::collections::HashMap<&str, std::collections::VecDeque<usize>> {
|
||||
let mut out: std::collections::HashMap<&str, std::collections::VecDeque<usize>> = std::collections::HashMap::new();
|
||||
for &i in &self.selected {
|
||||
if let Some((e, _)) = self.options.get(i) {
|
||||
out.entry(e.as_str()).or_default().push_back(i);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// A value to put in a field.
|
||||
@@ -281,6 +347,10 @@ pub enum FieldValue {
|
||||
Widget(usize),
|
||||
/// Combo box or list box: export values (several only for multi-select lists).
|
||||
Choice(Vec<String>),
|
||||
/// Combo box or list box: options by their zero-based position in `/Opt` (as `/I` numbers
|
||||
/// them), which tells apart options that share an export value. Several only for
|
||||
/// multi-select lists; `/V` takes them in this order.
|
||||
ChoiceIndices(Vec<usize>),
|
||||
}
|
||||
|
||||
// ── reading ─────────────────────────────────────────────────────────────────────────────────
|
||||
@@ -334,3 +404,14 @@ fn name_obj(text: &str) -> Object {
|
||||
fn invalid<T>(m: impl Into<String>) -> Result<T, FormError> {
|
||||
Err(FormError::Invalid(m.into()))
|
||||
}
|
||||
|
||||
/// The positions in `target` of the options at positions `picked` in `source`, in the same order:
|
||||
/// each goes to `target`'s first not yet taken option with the same export value and text, so two
|
||||
/// options sharing both stay apart. `None` when one has no such option in `target`.
|
||||
pub(crate) fn option_positions_in(picked: &[usize], source: &[(String, String)], target: &[(String, String)]) -> Option<Vec<usize>> {
|
||||
let mut free: std::collections::HashMap<(&str, &str), std::collections::VecDeque<usize>> = std::collections::HashMap::new();
|
||||
for (i, (e, d)) in target.iter().enumerate() {
|
||||
free.entry((e.as_str(), d.as_str())).or_default().push_back(i);
|
||||
}
|
||||
picked.iter().map(|&p| source.get(p).and_then(|(e, d)| free.get_mut(&(e.as_str(), d.as_str()))).and_then(|q| q.pop_front())).collect()
|
||||
}
|
||||
|
||||
@@ -243,6 +243,69 @@ fn values_of(doc: &Document, o: Option<&Object>, budget: &mut DecodeBudget) -> V
|
||||
}
|
||||
}
|
||||
|
||||
/// A choice field's `/I` (ISO 32000-2 Table 234) as option positions, when it is usable: an array
|
||||
/// of integers "sorted in ascending order", each naming one of `count` options. `None` when it is
|
||||
/// absent or anything in it is not (a non-integer, a position out of range, out of order or
|
||||
/// repeated), so the field falls back to `/V`.
|
||||
pub(crate) fn listed_indices(doc: &Document, d: &Dict, count: usize) -> Option<Vec<usize>> {
|
||||
let listed = doc.resolve(d.get(b"I")?);
|
||||
let entries = listed.as_array()?;
|
||||
// Strictly ascending positions below `count` number at most `count`.
|
||||
if entries.len() > count {
|
||||
return None;
|
||||
}
|
||||
let mut out: Vec<usize> = Vec::with_capacity(entries.len());
|
||||
for e in entries {
|
||||
let i = usize::try_from(doc.resolve(e).as_int()?).ok().filter(|&i| i < count)?;
|
||||
if out.last().is_some_and(|&last| last >= i) {
|
||||
return None;
|
||||
}
|
||||
out.push(i);
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// The options a choice field shows selected, as ascending positions in `options`, given its
|
||||
/// values (`/V`) and its usable `/I` ([`listed_indices`]).
|
||||
///
|
||||
/// `/I` decides when it names the same export values as `/V`: it "shall be used when two or more
|
||||
/// elements in the Opt array have different names but the same export value", and "if the items
|
||||
/// identified by this entry differ from those in the V entry …, the V entry shall be used" (ISO
|
||||
/// 32000-2 Table 234). Otherwise each value selects the first option with that export value, as
|
||||
/// the writer numbers `/I` when it is given only an export value, so a pick keeps showing the same
|
||||
/// option when `/I` is lost. A value no option exports selects nothing.
|
||||
pub fn selected_options(options: &[(String, String)], values: &[String], listed: Option<&[usize]>) -> Vec<usize> {
|
||||
if let Some(listed) = listed {
|
||||
// The same items, each as many times: `/V [(1) (1)]` names two items, which an `/I [1]`
|
||||
// naming one doesn't, so `/V` decides then.
|
||||
let mut named: Vec<&str> = values.iter().map(String::as_str).collect();
|
||||
named.sort_unstable();
|
||||
let exports: Option<Vec<&str>> = listed.iter().map(|&i| options.get(i).map(|(e, _)| e.as_str())).collect();
|
||||
if let Some(mut exports) = exports {
|
||||
exports.sort_unstable();
|
||||
if exports == named {
|
||||
return listed.to_vec();
|
||||
}
|
||||
}
|
||||
}
|
||||
let first = first_by_export(options);
|
||||
let mut out: Vec<usize> = values.iter().filter_map(|v| first.get(v.as_str()).copied()).collect();
|
||||
out.sort_unstable();
|
||||
out.dedup();
|
||||
out
|
||||
}
|
||||
|
||||
/// Each export value in `options` with the position of the first option exporting it, so
|
||||
/// matching values against options takes one pass over each rather than one over the options per
|
||||
/// value (a file can hold many of both).
|
||||
pub(crate) fn first_by_export(options: &[(String, String)]) -> std::collections::HashMap<&str, usize> {
|
||||
let mut first: std::collections::HashMap<&str, usize> = std::collections::HashMap::with_capacity(options.len());
|
||||
for (i, (e, _)) in options.iter().enumerate() {
|
||||
first.entry(e.as_str()).or_insert(i);
|
||||
}
|
||||
first
|
||||
}
|
||||
|
||||
fn nums(doc: &Document, o: Option<&Object>) -> Option<Vec<f64>> {
|
||||
let o = doc.resolve(o?);
|
||||
o.as_array()?.iter().map(|x| doc.resolve(x).as_f64()).collect()
|
||||
@@ -676,16 +739,36 @@ fn walk(
|
||||
Object::Array(pair) if pair.len() >= 2 => Some((text_of(&doc.resolve(&pair[0]))?, text_of(&doc.resolve(&pair[1]))?)),
|
||||
other => text_of(other).map(|t| (t.clone(), t)),
|
||||
})
|
||||
.collect();
|
||||
.collect::<Vec<(String, String)>>();
|
||||
let mut value = values_of(doc, inh.v.as_ref(), &mut seen.values);
|
||||
// A list box without MultiSelect selects one option: "if clear, at most one item shall be
|
||||
// selected" (ISO 32000-2 Table 233). Given an array /V or /DV anyway, it holds the first
|
||||
// value only, and shows and resets to it; the file keeps its entries until the field is filled.
|
||||
let mut default = values_of(doc, inh.dv.as_ref(), &mut seen.values);
|
||||
let single = kind == FieldKind::List && ff & flags::MULTI_SELECT == 0;
|
||||
let single_value_is_array = single && inh.v.as_ref().is_some_and(|v| doc.resolve(v).as_array().is_some());
|
||||
if single {
|
||||
value.truncate(1);
|
||||
default.truncate(1);
|
||||
}
|
||||
let mut selected = match kind {
|
||||
FieldKind::Combo | FieldKind::List => selected_options(&options, &value, listed_indices(doc, d, options.len()).as_deref()),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
if single {
|
||||
selected.truncate(1);
|
||||
}
|
||||
out.push(Field {
|
||||
name: inh.name.clone(),
|
||||
obj: r,
|
||||
kind,
|
||||
value: values_of(doc, inh.v.as_ref(), &mut seen.values),
|
||||
default: values_of(doc, inh.dv.as_ref(), &mut seen.values),
|
||||
value,
|
||||
default,
|
||||
flags: ff,
|
||||
max_len: inh.max_len,
|
||||
options,
|
||||
selected,
|
||||
single_value_is_array,
|
||||
da: inh.da.clone().unwrap_or_else(|| "/Helv 0 Tf 0 g".into()),
|
||||
quadding: inh.q.unwrap_or(0),
|
||||
tooltip: d.get(b"TU").and_then(|o| text_of(&doc.resolve(o))),
|
||||
|
||||
@@ -140,7 +140,7 @@ pub(crate) fn apply_changes(doc: &mut Document, changes: &[FieldChange], except:
|
||||
{
|
||||
let value = match f.kind {
|
||||
FieldKind::Text => FieldValue::Text(v.first().cloned().unwrap_or_default()),
|
||||
FieldKind::CheckBox => FieldValue::Check(!v.is_empty()),
|
||||
FieldKind::CheckBox => f.check_box_value(v.first().map(String::as_str)),
|
||||
FieldKind::Radio => FieldValue::Radio(v.first().cloned()),
|
||||
FieldKind::Combo | FieldKind::List => FieldValue::Choice(v.clone()),
|
||||
_ => continue,
|
||||
|
||||
@@ -6547,6 +6547,338 @@ fn a_read_only_button_is_not_turned_on_by_number() {
|
||||
assert_eq!(on_widgets(&doc, "r").0, [false, false, true]);
|
||||
}
|
||||
|
||||
/// Two check box fields of two kids each: `pair` with the on states `A` and `B` (and `/DV /B`),
|
||||
/// `same` with `Yes` twice.
|
||||
fn check_box_kids() -> Document {
|
||||
let kid = |parent: usize, x: u32, state: &str| {
|
||||
format!(
|
||||
"<< /Type /Annot /Subtype /Widget /Parent {parent} 0 R /AS /Off /Rect [{x} 700 {} 715] /P 3 0 R /AP << /N << /{state} 10 0 R /Off 11 0 R >> >> >>",
|
||||
x + 15
|
||||
)
|
||||
};
|
||||
let objs: Vec<String> = vec![
|
||||
"<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(), // 1
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(), // 2
|
||||
"<< /Type /Page /Parent 2 0 R /Annots [6 0 R 7 0 R 8 0 R 9 0 R] >>".into(), // 3
|
||||
"<< /Fields [5 0 R 12 0 R] /DA (/Helv 0 Tf 0 g) >>".into(), // 4
|
||||
"<< /FT /Btn /T (pair) /V /Off /DV /B /Kids [6 0 R 7 0 R] >>".into(), // 5
|
||||
kid(5, 100, "A"), // 6
|
||||
kid(5, 200, "B"), // 7
|
||||
kid(12, 100, "Yes"), // 8
|
||||
kid(12, 200, "Yes"), // 9
|
||||
"<< /Length 0 >>\nstream\n\nendstream".into(), // 10
|
||||
"<< /Length 0 >>\nstream\n\nendstream".into(), // 11
|
||||
"<< /FT /Btn /T (same) /V /Off /Kids [8 0 R 9 0 R] >>".into(), // 12
|
||||
];
|
||||
document(&objs)
|
||||
}
|
||||
|
||||
/// ISO 32000-2 §12.7.5.2.3: a check box field's `/V` is the on state of its kid that is on, and
|
||||
/// its kids can have different on states (Table 230). Naming `B` ticks `B` and clears `A`;
|
||||
/// "checked" keeps the kid that is on; a reset goes back to `/DV /B`. Kids sharing `Yes` tick
|
||||
/// together (EXAMPLE 2).
|
||||
#[test]
|
||||
fn check_box_kids_with_different_on_states_tick_one_at_a_time() {
|
||||
let mut doc = check_box_kids();
|
||||
set_value(&mut doc, "pair", &FieldValue::Text("A".into())).unwrap();
|
||||
assert_eq!(on_widgets(&doc, "pair"), (vec![true, false], vec!["A".to_string()]));
|
||||
set_value(&mut doc, "pair", &FieldValue::Text("B".into())).unwrap();
|
||||
let mut doc = reopen(&doc);
|
||||
assert_eq!(on_widgets(&doc, "pair"), (vec![false, true], vec!["B".to_string()]), "B, after a save");
|
||||
set_value(&mut doc, "pair", &FieldValue::Check(true)).unwrap();
|
||||
assert_eq!(on_widgets(&doc, "pair").0, [false, true], "checked keeps the kid that is on");
|
||||
set_value(&mut doc, "pair", &FieldValue::Check(false)).unwrap();
|
||||
assert_eq!(on_widgets(&doc, "pair"), (vec![false, false], vec![]));
|
||||
set_value(&mut doc, "pair", &FieldValue::Check(true)).unwrap();
|
||||
assert_eq!(on_widgets(&doc, "pair").0, [true, false], "from off, checked takes the first kid");
|
||||
reset(&mut doc, None).unwrap();
|
||||
assert_eq!(on_widgets(&doc, "pair"), (vec![false, true], vec!["B".to_string()]), "reset goes back to /DV /B");
|
||||
// Kids sharing an on state tick and untick together.
|
||||
set_value(&mut doc, "same", &FieldValue::Text("Yes".into())).unwrap();
|
||||
assert_eq!(on_widgets(&doc, "same"), (vec![true, true], vec!["Yes".to_string()]));
|
||||
set_value(&mut doc, "same", &FieldValue::Check(false)).unwrap();
|
||||
assert_eq!(on_widgets(&doc, "same").0, [false, false]);
|
||||
assert!(matches!(set_value(&mut doc, "pair", &FieldValue::Text("C".into())), Err(FormError::Invalid(_))));
|
||||
// A script that sets the value to B ticks B.
|
||||
let to_b = FieldChange { name: "pair".into(), value: Some(vec!["B".into()]), ..FieldChange::default() };
|
||||
set_value(&mut doc, "pair", &FieldValue::Text("A".into())).unwrap();
|
||||
apply_script_changes(&mut doc, &[to_b], &mut NoScripts).unwrap();
|
||||
assert_eq!(on_widgets(&doc, "pair"), (vec![false, true], vec!["B".to_string()]), "a script's B");
|
||||
}
|
||||
|
||||
/// A one-page form with list box `dup` (single select unless `ff` says otherwise) whose first two
|
||||
/// options share the export value `1`, plus `extra` entries (`/V`, `/I`) on the field.
|
||||
fn duplicate_exports(ff: u32, extra: &str) -> Document {
|
||||
let objs: Vec<String> = vec![
|
||||
"<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(),
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(),
|
||||
"<< /Type /Page /Parent 2 0 R /Annots [6 0 R] >>".into(),
|
||||
"<< /Fields [6 0 R] /NeedAppearances true /DA (/Helv 10 Tf 0 g) /DR << /Font << /Helv 5 0 R >> >> >>".into(),
|
||||
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".into(),
|
||||
format!(
|
||||
"<< /Type /Annot /Subtype /Widget /FT /Ch /T (dup) /Ff {ff} /Opt [[(1) (One-A)] [(1) (One-B)] [(2) (Two)]] {extra} /Rect [50 700 200 746] /P 3 0 R >>"
|
||||
),
|
||||
];
|
||||
document(&objs)
|
||||
}
|
||||
|
||||
/// The bottom edges of the highlighted rows in a list box appearance, top row first.
|
||||
fn highlighted_rows(appearance: &str) -> Vec<String> {
|
||||
let lines: Vec<&str> = appearance.lines().collect();
|
||||
lines.windows(2).filter(|w| w[0] == "0.6 0.75 0.86 rg").map(|w| w[1].split(' ').nth(1).unwrap_or_default().to_string()).collect()
|
||||
}
|
||||
|
||||
/// The rows the display copy (`/NeedAppearances`) highlights in `dup`.
|
||||
fn shown_rows(doc: &Document) -> Vec<String> {
|
||||
let copy = with_field_appearances(doc).expect("the form leaves its appearances to the viewer");
|
||||
highlighted_rows(&ap(©, &field(&fields(©), "dup").widgets[0]))
|
||||
}
|
||||
|
||||
/// ISO 32000-2 Table 234: `/I` "shall be used when two or more elements in the Opt array have
|
||||
/// different names but the same export value". `/V (1)` with `/I [1]` selects One-B alone, not
|
||||
/// every option exporting `1`.
|
||||
#[test]
|
||||
fn a_list_box_with_duplicate_export_values_selects_the_option_i_names() {
|
||||
let doc = duplicate_exports(0, "/V (1) /I [1]");
|
||||
let dup = field(&fields(&doc), "dup").clone();
|
||||
assert_eq!(dup.selected, [1]);
|
||||
assert_eq!(dup.display_value(), "One-B");
|
||||
let one_b = shown_rows(&doc);
|
||||
assert_eq!(one_b.len(), 1, "one highlighted row");
|
||||
// The same field with /I [0] highlights the row above it.
|
||||
let one_a = shown_rows(&duplicate_exports(0, "/V (1) /I [0]"));
|
||||
assert_eq!(one_a.len(), 1);
|
||||
assert_ne!(one_a, one_b, "One-A and One-B are different rows");
|
||||
let row = |s: &[String]| s.first().and_then(|y| y.parse::<f64>().ok()).unwrap();
|
||||
assert!(row(&one_b) < row(&one_a), "One-B is drawn below One-A");
|
||||
}
|
||||
|
||||
/// Without a usable `/I`, `/V` decides (Table 234: "If the items identified by this entry differ
|
||||
/// from those in the V entry …, the V entry shall be used"), and an export value two options
|
||||
/// share selects the first of them. A malformed `/I` never panics.
|
||||
#[test]
|
||||
fn an_unusable_i_falls_back_to_the_first_option_with_the_value() {
|
||||
for (extra, multi, want) in [
|
||||
("/V (1)", 0, vec![0]), // no /I: the first option exporting 1
|
||||
("/V (1) /I [5]", 0, vec![0]), // out of range
|
||||
("/V (1) /I [-1]", 0, vec![0]), // negative
|
||||
("/V (1) /I [(1)]", 0, vec![0]), // not an integer
|
||||
("/V (1) /I [1.5]", 0, vec![0]), // not a whole number
|
||||
("/V (1) /I 1", 0, vec![0]), // not an array
|
||||
("/V (1) /I [2]", 0, vec![0]), // names Two, which /V doesn't
|
||||
("/V (1) /I []", 0, vec![0]), // names nothing
|
||||
("/V [(1) (2)] /I [2 1]", 1 << 21, vec![0, 2]), // not ascending
|
||||
("/V [(1) (2)] /I [1 1 2]", 1 << 21, vec![0, 2]), // repeated
|
||||
("/V [(1) (2)] /I [1 2]", 1 << 21, vec![1, 2]), // usable: One-B and Two
|
||||
("/V [(1) (1)] /I [0 1]", 1 << 21, vec![0, 1]), // usable: both options exporting 1
|
||||
("/V [(1) (1)] /I [1]", 1 << 21, vec![0]), // names one item where /V names two
|
||||
("/V [] /I [1]", 0, vec![]), // an empty value selects nothing
|
||||
("/V (9)", 0, vec![]), // no option exports 9
|
||||
] {
|
||||
let doc = duplicate_exports(multi, extra);
|
||||
assert_eq!(field(&fields(&doc), "dup").selected, want, "{extra}");
|
||||
assert_eq!(shown_rows(&doc).len(), want.len(), "{extra}");
|
||||
}
|
||||
// Pure: positions past the options or unlike the values are ignored.
|
||||
let options = [("1".to_string(), "One-A".to_string()), ("1".to_string(), "One-B".to_string())];
|
||||
assert_eq!(selected_options(&options, &["1".into()], Some(&[1])), [1]);
|
||||
assert_eq!(selected_options(&options, &["1".into()], Some(&[7])), [0]);
|
||||
assert_eq!(selected_options(&options, &[], Some(&[])), Vec::<usize>::new());
|
||||
}
|
||||
|
||||
/// Picking an option by position writes its export value to `/V` and its position to `/I`, so a
|
||||
/// pick of One-A or One-B survives a save and reopen; picking by display text does the same.
|
||||
#[test]
|
||||
fn picking_one_of_two_options_with_the_same_export_value_round_trips() {
|
||||
for (value, want) in [
|
||||
(FieldValue::ChoiceIndices(vec![0]), 0),
|
||||
(FieldValue::ChoiceIndices(vec![1]), 1),
|
||||
(FieldValue::Text("One-B".into()), 1),
|
||||
(FieldValue::Text("One-A".into()), 0),
|
||||
(FieldValue::Choice(vec!["1".into()]), 0),
|
||||
] {
|
||||
let mut doc = duplicate_exports(0, "/V (1) /I [1]");
|
||||
set_value(&mut doc, "dup", &value).unwrap();
|
||||
let doc = reopen(&doc);
|
||||
let dup = field(&fields(&doc), "dup").clone();
|
||||
let d = doc.get(dup.obj).as_dict().cloned().unwrap();
|
||||
assert_eq!(d.get(b"V").and_then(|v| v.as_string()).map(|s| s.to_text()).as_deref(), Some("1"), "{value:?}: /V is one string");
|
||||
let i: Vec<i64> = d.get(b"I").and_then(|i| i.as_array()).unwrap().iter().filter_map(Object::as_int).collect();
|
||||
assert_eq!(i, [want as i64], "{value:?}");
|
||||
assert_eq!(dup.selected, [want], "{value:?}");
|
||||
assert_eq!(highlighted_rows(&ap(&doc, &dup.widgets[0])).len(), 1, "{value:?}: its saved look highlights one row");
|
||||
}
|
||||
// The saved look highlights the row picked, not the first with its value.
|
||||
let saved = |pick: usize| {
|
||||
let mut doc = duplicate_exports(0, "");
|
||||
set_value(&mut doc, "dup", &FieldValue::ChoiceIndices(vec![pick])).unwrap();
|
||||
highlighted_rows(&ap(&doc, &field(&fields(&doc), "dup").widgets[0]))
|
||||
};
|
||||
assert_ne!(saved(0), saved(1));
|
||||
// Positions are checked: out of range, or several in a single-select list.
|
||||
let mut doc = duplicate_exports(0, "");
|
||||
assert!(matches!(set_value(&mut doc, "dup", &FieldValue::ChoiceIndices(vec![3])), Err(FormError::Invalid(_))));
|
||||
assert!(matches!(set_value(&mut doc, "dup", &FieldValue::ChoiceIndices(vec![usize::MAX])), Err(FormError::Invalid(_))));
|
||||
assert!(matches!(set_value(&mut doc, "dup", &FieldValue::ChoiceIndices(vec![0, 1])), Err(FormError::Invalid(_))));
|
||||
// A multi-select list takes both options that share the value, in ascending /I.
|
||||
let mut doc = duplicate_exports(1 << 21, "");
|
||||
set_value(&mut doc, "dup", &FieldValue::ChoiceIndices(vec![1, 0])).unwrap();
|
||||
let doc = reopen(&doc);
|
||||
let dup = field(&fields(&doc), "dup").clone();
|
||||
assert_eq!(dup.value, ["1", "1"]);
|
||||
assert_eq!(dup.selected, [0, 1]);
|
||||
assert_eq!(dup.picked_in_order(), [0, 1]);
|
||||
// A check box can't take positions.
|
||||
let mut doc = fixture();
|
||||
assert!(matches!(set_value(&mut doc, "agree", &FieldValue::ChoiceIndices(vec![0])), Err(FormError::Invalid(_))));
|
||||
}
|
||||
|
||||
/// A file can hold a list box with very many options and values. Matching values to options
|
||||
/// takes one lookup per value, not a scan of the options (or of the selection) for each, so
|
||||
/// reading and showing such a field stays fast. Two options share each export value, and every
|
||||
/// result still names the first option exporting a value, or the next one selected.
|
||||
#[test]
|
||||
fn many_options_and_values_match_in_linear_time() {
|
||||
const N: usize = 100_000;
|
||||
let options: Vec<(String, String)> = (0..2 * N).map(|i| (format!("e{}", i / 2), format!("d{i}"))).collect();
|
||||
let values: Vec<String> = (0..N).rev().map(|k| format!("e{k}")).collect();
|
||||
let started = std::time::Instant::now();
|
||||
let selected = selected_options(&options, &values, None);
|
||||
assert_eq!(selected, (0..N).map(|k| 2 * k).collect::<Vec<_>>(), "the first option exporting each value");
|
||||
let took = started.elapsed();
|
||||
assert!(took < std::time::Duration::from_secs(2), "selected_options took {took:?}");
|
||||
|
||||
let mut list = field(&fields(&fixture()), "toppings").clone();
|
||||
list.options = options;
|
||||
list.value = values;
|
||||
list.selected = (0..2 * N).collect();
|
||||
let started = std::time::Instant::now();
|
||||
let order = list.picked_in_order();
|
||||
let shown = list.display_value();
|
||||
let took = started.elapsed();
|
||||
assert!(took < std::time::Duration::from_secs(2), "picked_in_order and display_value took {took:?}");
|
||||
// The values name e{N-1} first: its first option, then down to e0; the second option of
|
||||
// each value is selected without a value naming it, so it follows in ascending order.
|
||||
assert_eq!(order.first(), Some(&(2 * (N - 1))));
|
||||
assert_eq!(order.get(N - 1), Some(&0));
|
||||
assert_eq!(order.get(N..), Some(&(0..N).map(|k| 2 * k + 1).collect::<Vec<_>>()[..]));
|
||||
assert!(shown.starts_with(&format!("d{}, d{}", 2 * (N - 1), 2 * (N - 2))), "{}", shown.get(..40).unwrap_or(&shown));
|
||||
}
|
||||
|
||||
/// A one-page form with list box `pair` (single select unless `ff` says otherwise) of three
|
||||
/// countries, plus `extra` entries (`/V`, `/DV`, `/I`) on the field.
|
||||
fn countries(ff: u32, extra: &str) -> Document {
|
||||
let objs: Vec<String> = vec![
|
||||
"<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(),
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(),
|
||||
"<< /Type /Page /Parent 2 0 R /Annots [6 0 R] >>".into(),
|
||||
"<< /Fields [6 0 R] /NeedAppearances true /DA (/Helv 10 Tf 0 g) /DR << /Font << /Helv 5 0 R >> >> >>".into(),
|
||||
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".into(),
|
||||
format!(
|
||||
"<< /Type /Annot /Subtype /Widget /FT /Ch /T (pair) /Ff {ff} /Opt [[(TW) (Taiwan)] [(JP) (Japan)] [(US) (United States)]] {extra} /Rect [50 700 200 746] /P 3 0 R >>"
|
||||
),
|
||||
];
|
||||
document(&objs)
|
||||
}
|
||||
|
||||
/// ISO 32000-2 Table 233, MultiSelect: "if clear, at most one item shall be selected". A list box
|
||||
/// without it given `/V [(TW) (JP)]` holds and shows Taiwan alone, and opening it changes nothing
|
||||
/// in the file.
|
||||
#[test]
|
||||
fn a_single_select_list_given_several_values_shows_the_first() {
|
||||
for (extra, multi, value, want) in [
|
||||
("/V [(TW) (JP)]", 0, vec!["TW"], vec![0]),
|
||||
("/V [(JP) (TW)]", 0, vec!["JP"], vec![1]),
|
||||
("/V [(TW) (JP)] /I [0 1]", 0, vec!["TW"], vec![0]), // /I names more than the one value
|
||||
("/V [(XX) (JP)]", 0, vec!["XX"], vec![]), // the first value is no option
|
||||
("/V []", 0, vec![], vec![]),
|
||||
("/V [(TW) (JP)]", 1 << 21, vec!["TW", "JP"], vec![0, 1]), // multi-select keeps both
|
||||
] {
|
||||
let doc = countries(multi, extra);
|
||||
let pair = field(&fields(&doc), "pair").clone();
|
||||
assert_eq!(pair.value, value, "{extra}");
|
||||
assert_eq!(pair.selected, want, "{extra}");
|
||||
let copy = with_field_appearances(&doc).expect("left to the viewer");
|
||||
assert_eq!(highlighted_rows(&ap(©, &field(&fields(©), "pair").widgets[0])).len(), want.len(), "{extra}");
|
||||
// Reading and drawing the display copy leaves the field's own /V as it was.
|
||||
let v = doc.get(pair.obj).as_dict().and_then(|d| d.get(b"V").cloned()).unwrap();
|
||||
assert!(matches!(v, Object::Array(_)), "{extra}: {v:?}");
|
||||
}
|
||||
// Two options selected by /I alone in a single-select list: the first.
|
||||
let doc = duplicate_exports(0, "/V (1) /I [0 1]");
|
||||
assert_eq!(field(&fields(&doc), "dup").selected, [0]);
|
||||
}
|
||||
|
||||
/// Picking a row in such a list writes one string to `/V` and that option's position to `/I`,
|
||||
/// and Clear form goes back to the first value of an array `/DV` instead of refusing it.
|
||||
#[test]
|
||||
fn picking_in_a_single_select_list_given_several_values_writes_one() {
|
||||
for (pick, export, index) in [(FieldValue::ChoiceIndices(vec![2]), "US", 2), (FieldValue::Choice(vec!["JP".into()]), "JP", 1)] {
|
||||
let mut doc = countries(0, "/V [(TW) (JP)] /I [0 1]");
|
||||
set_value(&mut doc, "pair", &pick).unwrap();
|
||||
let doc = reopen(&doc);
|
||||
let pair = field(&fields(&doc), "pair").clone();
|
||||
let d = doc.get(pair.obj).as_dict().cloned().unwrap();
|
||||
assert_eq!(d.get(b"V").and_then(|v| v.as_string()).map(|s| s.to_text()).as_deref(), Some(export), "{pick:?}: /V is one string");
|
||||
let i: Vec<i64> = d.get(b"I").and_then(|i| i.as_array()).unwrap().iter().filter_map(Object::as_int).collect();
|
||||
assert_eq!(i, [index], "{pick:?}");
|
||||
assert_eq!((pair.value, pair.selected), (vec![export.to_string()], vec![index as usize]));
|
||||
}
|
||||
let mut doc = countries(0, "/V (US) /DV [(JP) (TW)]");
|
||||
assert_eq!(reset(&mut doc, None).unwrap(), 1);
|
||||
let pair = field(&fields(&doc), "pair").clone();
|
||||
assert_eq!((pair.value, pair.selected), (vec!["JP".to_string()], vec![1]));
|
||||
}
|
||||
|
||||
/// A position picked twice is written once in both `/V` and `/I`, so they still match item for
|
||||
/// item and the option picked (the second of two sharing an export value) comes back on reopen.
|
||||
#[test]
|
||||
fn a_position_picked_twice_is_written_once_in_v_and_i() {
|
||||
let mut doc = duplicate_exports(1 << 21, "");
|
||||
set_value(&mut doc, "dup", &FieldValue::ChoiceIndices(vec![1, 1])).unwrap();
|
||||
let dup = field(&fields(&doc), "dup").clone();
|
||||
let d = doc.get(dup.obj).as_dict().cloned().unwrap();
|
||||
let v: Vec<String> = match d.get(b"V") {
|
||||
Some(Object::Array(a)) => a.iter().filter_map(|o| o.as_string().map(|s| s.to_text())).collect(),
|
||||
Some(o) => o.as_string().map(|s| vec![s.to_text()]).unwrap_or_default(),
|
||||
None => Vec::new(),
|
||||
};
|
||||
let i: Vec<i64> = d.get(b"I").and_then(|i| i.as_array()).map(|a| a.iter().filter_map(Object::as_int).collect()).unwrap_or_default();
|
||||
assert_eq!((v, i), (vec!["1".to_string()], vec![1]), "one entry each");
|
||||
assert_eq!(dup.selected, [1], "One-B, not One-A");
|
||||
}
|
||||
|
||||
/// A same-name twin listing the options sharing an export value in another order is given the
|
||||
/// option picked, not the one at the same position: `/I` is mapped to the twin's own options.
|
||||
#[test]
|
||||
fn a_twin_with_options_in_another_order_gets_the_option_picked() {
|
||||
let objs: Vec<String> = vec![
|
||||
"<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(),
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(),
|
||||
"<< /Type /Page /Parent 2 0 R /Annots [6 0 R 7 0 R] >>".into(),
|
||||
"<< /Fields [6 0 R 7 0 R] /NeedAppearances true /DA (/Helv 10 Tf 0 g) /DR << /Font << /Helv 5 0 R >> >> >>".into(),
|
||||
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".into(),
|
||||
"<< /Type /Annot /Subtype /Widget /FT /Ch /T (dup) /Ff 0 /Opt [[(1) (One-A)] [(1) (One-B)] [(2) (Two)]] /Rect [50 700 200 746] /P 3 0 R >>"
|
||||
.into(),
|
||||
"<< /Type /Annot /Subtype /Widget /FT /Ch /T (dup) /Ff 0 /Opt [[(1) (One-B)] [(1) (One-A)] [(2) (Two)]] /Rect [50 600 200 646] /P 3 0 R >>"
|
||||
.into(),
|
||||
];
|
||||
let mut doc = document(&objs);
|
||||
set_value(&mut doc, "dup", &FieldValue::ChoiceIndices(vec![1])).unwrap();
|
||||
let all = fields(&doc);
|
||||
let twin = all.iter().find(|f| f.obj == pdfcraft_cos::ObjRef::new(7, 0)).unwrap();
|
||||
let i: Vec<i64> = doc
|
||||
.get(twin.obj)
|
||||
.as_dict()
|
||||
.and_then(|d| d.get(b"I").and_then(|i| i.as_array().cloned()))
|
||||
.unwrap_or_default()
|
||||
.iter()
|
||||
.filter_map(Object::as_int)
|
||||
.collect();
|
||||
assert_eq!(i, [0], "One-B is first in the twin's options");
|
||||
assert_eq!(twin.selected, [0]);
|
||||
}
|
||||
|
||||
/// A `/MK /BC` or `/BG` written `[1 0 0 null]` is CMYK with the null as 0, as annotation `/C`
|
||||
/// colours are read (PDFBOX-2699), not RGB from the three numbers left; three numbers stay RGB.
|
||||
#[test]
|
||||
|
||||
+132
-46
@@ -1,5 +1,5 @@
|
||||
use super::appearances::{declares_pdfa, need_appearances};
|
||||
use super::read::{acroform, field_flags, fields, listing_fields_named, page_refs};
|
||||
use super::read::{acroform, field_flags, fields, listed_indices, listing_fields_named, page_refs, selected_options};
|
||||
use super::{
|
||||
Dict, Document, Field, FieldEvent, FieldKind, FieldValue, FormError, NoScripts, ObjRef, Object, PdfString, Scripts, Widget, af, appearance,
|
||||
author, calc_order, flags, invalid, name_obj, scripting,
|
||||
@@ -117,7 +117,7 @@ fn fill(doc: &mut Document, all: &[Field], named: &[usize], name: &str, value: &
|
||||
if !twins.is_empty() {
|
||||
let taken = fields(doc).into_iter().find(|x| x.obj == f.obj).map(|x| x.value).unwrap_or_default();
|
||||
for t in twins {
|
||||
share_value(doc, f.obj, t, &taken, scripts)?;
|
||||
share_value(doc, (f.obj, &f.options), t, &taken, scripts)?;
|
||||
}
|
||||
}
|
||||
// A field whose `/Kids` lists radio fields that don't name it as their `/Parent` has their
|
||||
@@ -133,9 +133,15 @@ fn fill(doc: &mut Document, all: &[Field], named: &[usize], name: &str, value: &
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Give `twin` the value `source` holds: its `/V` (and a choice's `/I`), drawn in the twin's own
|
||||
/// widgets.
|
||||
fn share_value(doc: &mut Document, source: ObjRef, twin: &Field, value: &[String], scripts: &mut dyn Scripts) -> Result<(), FormError> {
|
||||
/// Give `twin` the value `source` (a field and its options) holds: its `/V`, and a choice's `/I`
|
||||
/// mapped to the twin's own options, drawn in the twin's own widgets.
|
||||
fn share_value(
|
||||
doc: &mut Document,
|
||||
(source, source_options): (ObjRef, &[(String, String)]),
|
||||
twin: &Field,
|
||||
value: &[String],
|
||||
scripts: &mut dyn Scripts,
|
||||
) -> Result<(), FormError> {
|
||||
match twin.kind {
|
||||
FieldKind::CheckBox => {
|
||||
let state = twin.widgets.iter().find_map(|w| w.on_state.clone()).unwrap_or_else(|| "Yes".into());
|
||||
@@ -153,18 +159,37 @@ fn share_value(doc: &mut Document, source: ObjRef, twin: &Field, value: &[String
|
||||
}
|
||||
FieldKind::Text | FieldKind::Combo | FieldKind::List => {
|
||||
let src = doc.get(source).as_dict().cloned().unwrap_or_default();
|
||||
// `/I` holds positions in the source's options: each goes to the twin's first unused option
|
||||
// with the same export value and text, its options perhaps in another order. One with no
|
||||
// match leaves the twin no `/I` (its `/V` picks), never part of one.
|
||||
let positions = match twin.kind {
|
||||
FieldKind::Combo | FieldKind::List => {
|
||||
listed_indices(doc, &src, source_options.len()).and_then(|picked| twin_positions(&picked, source_options, &twin.options))
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
doc.update_dict(twin.obj, |d| {
|
||||
for key in [&b"V"[..], b"I"] {
|
||||
match src.get(key) {
|
||||
Some(v) => d.set(key.to_vec(), v.clone()),
|
||||
None => {
|
||||
d.remove(key);
|
||||
}
|
||||
match src.get(b"V") {
|
||||
Some(v) => d.set(b"V".to_vec(), v.clone()),
|
||||
None => {
|
||||
d.remove(b"V");
|
||||
}
|
||||
}
|
||||
match &positions {
|
||||
Some(p) => d.set(b"I".to_vec(), Object::Array(p.iter().map(|&i| Object::Int(i64::try_from(i).unwrap_or(i64::MAX))).collect())),
|
||||
None => {
|
||||
d.remove(b"I");
|
||||
}
|
||||
}
|
||||
d.remove(b"RV");
|
||||
})?;
|
||||
redraw(doc, twin, value, scripts)
|
||||
// Drawn with the options that `/I` selects, not only the export values.
|
||||
let mut shown = twin.clone();
|
||||
shown.value = value.to_vec();
|
||||
if matches!(twin.kind, FieldKind::Combo | FieldKind::List) {
|
||||
shown.selected = selected_options(&twin.options, value, positions.as_deref());
|
||||
}
|
||||
redraw(doc, &shown, value, scripts)
|
||||
}
|
||||
FieldKind::PushButton | FieldKind::Signature => Ok(()),
|
||||
}
|
||||
@@ -303,24 +328,33 @@ pub(crate) fn write_value(doc: &mut Document, f: &Field, value: &FieldValue, scr
|
||||
set_states(doc, f, Some(&state), Some(*i))
|
||||
}
|
||||
(FieldKind::CheckBox, v) => {
|
||||
let state = f.widgets.iter().find_map(|w| w.on_state.clone()).unwrap_or_else(|| "Yes".into());
|
||||
let on = match v {
|
||||
FieldValue::Check(on) => *on,
|
||||
// The on-state name or a yes/no word also work (agents, FDF-style data).
|
||||
// The kids of one check box field can have different on states, and the field's
|
||||
// value is the on state of the kid that is on (ISO 32000-2 §12.7.5.2.3, Table 230).
|
||||
// "Checked" keeps the state that is on, else takes the first kid's.
|
||||
let first = f.widgets.iter().find_map(|w| w.on_state.clone()).unwrap_or_else(|| "Yes".into());
|
||||
let checked = || (0..f.widgets.len()).find(|&i| f.widget_on(i)).and_then(|i| f.widgets.get(i)?.on_state.clone()).unwrap_or(first.clone());
|
||||
let state = match v {
|
||||
FieldValue::Check(on) => on.then(checked),
|
||||
// An on-state name (or `/Opt` export value) turns on the kids that have it; a
|
||||
// yes/no word also works (agents, FDF-style data).
|
||||
FieldValue::Text(t) | FieldValue::Radio(Some(t)) => {
|
||||
let t = t.trim();
|
||||
if t == state || f.state_for(t).is_some() || ["yes", "true", "on", "1", "x", "checked"].contains(&t.to_lowercase().as_str()) {
|
||||
true
|
||||
if let Some(s) = f.state_for(t) {
|
||||
Some(s.to_owned())
|
||||
} else if t == first || ["yes", "true", "on", "1", "x", "checked"].contains(&t.to_lowercase().as_str()) {
|
||||
Some(checked())
|
||||
} else if t.is_empty() || ["no", "false", "off", "0", "unchecked"].contains(&t.to_lowercase().as_str()) {
|
||||
false
|
||||
None
|
||||
} else {
|
||||
return invalid(format!("{:?} is a check box: use true or false", f.name));
|
||||
}
|
||||
}
|
||||
FieldValue::Radio(None) => false,
|
||||
FieldValue::Choice(_) | FieldValue::Widget(_) => return invalid(format!("{:?} is a check box: use true or false", f.name)),
|
||||
FieldValue::Radio(None) => None,
|
||||
FieldValue::Choice(_) | FieldValue::ChoiceIndices(_) | FieldValue::Widget(_) => {
|
||||
return invalid(format!("{:?} is a check box: use true or false", f.name));
|
||||
}
|
||||
};
|
||||
set_states(doc, f, on.then_some(state.as_str()), None)
|
||||
set_states(doc, f, state.as_deref(), None)
|
||||
}
|
||||
(FieldKind::Radio, v) => {
|
||||
let choice = match v {
|
||||
@@ -343,37 +377,67 @@ pub(crate) fn write_value(doc: &mut Document, f: &Field, value: &FieldValue, scr
|
||||
}
|
||||
set_states(doc, f, choice.as_deref(), None)
|
||||
}
|
||||
(FieldKind::Combo | FieldKind::List, FieldValue::Choice(_) | FieldValue::Text(_)) => {
|
||||
let vals: Vec<String> = match value {
|
||||
FieldValue::Choice(v) => v.clone(),
|
||||
FieldValue::Text(t) if t.is_empty() => Vec::new(),
|
||||
FieldValue::Text(t) => vec![t.clone()],
|
||||
other => return invalid(format!("{:?} can't take {other:?}", f.name)),
|
||||
(FieldKind::Combo | FieldKind::List, FieldValue::Choice(_) | FieldValue::Text(_) | FieldValue::ChoiceIndices(_)) => {
|
||||
let count = match value {
|
||||
FieldValue::Choice(v) => v.len(),
|
||||
FieldValue::ChoiceIndices(v) => v.len(),
|
||||
_ => 1,
|
||||
};
|
||||
if vals.len() > 1 && !(f.kind == FieldKind::List && f.has(flags::MULTI_SELECT)) {
|
||||
if count > 1 && !(f.kind == FieldKind::List && f.has(flags::MULTI_SELECT)) {
|
||||
return invalid(format!("{:?} takes a single value", f.name));
|
||||
}
|
||||
// Accept export values or display texts; free text only in editable combo boxes.
|
||||
// Each value as its export value and, when it is one of the options, that option's
|
||||
// position: two options can share an export value, and the position (`/I`) says
|
||||
// which one is picked (ISO 32000-2 Table 234).
|
||||
let mut exports = Vec::new();
|
||||
for v in &vals {
|
||||
match option_named(f, v).and_then(|i| f.options.get(i)) {
|
||||
Some((e, _)) => exports.push(e.clone()),
|
||||
None if f.kind == FieldKind::Combo && f.has(flags::EDIT) => exports.push(v.clone()),
|
||||
None if f.options.is_empty() => exports.push(v.clone()),
|
||||
None => {
|
||||
let opts: Vec<&str> = f.options.iter().map(|(_, d)| d.as_str()).collect();
|
||||
return invalid(format!("{:?} has no option {v:?} (options: {})", f.name, opts.join(", ")));
|
||||
let mut picked: Vec<usize> = Vec::new();
|
||||
// Each option once in both `/V` and `/I`: a reader that finds them differ (a repeat in one)
|
||||
// goes by the export values alone and may pick another option sharing one.
|
||||
let mut seen = vec![false; f.options.len()];
|
||||
match value {
|
||||
FieldValue::ChoiceIndices(positions) => {
|
||||
for &i in positions {
|
||||
let Some((e, _)) = f.options.get(i) else {
|
||||
return invalid(format!("{:?} has no option {} (it has {})", f.name, i.saturating_add(1), f.options.len()));
|
||||
};
|
||||
if first_pick(&mut seen, i) {
|
||||
exports.push(e.clone());
|
||||
picked.push(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
let vals: Vec<String> = match value {
|
||||
FieldValue::Choice(v) => v.clone(),
|
||||
FieldValue::Text(t) if t.is_empty() => Vec::new(),
|
||||
FieldValue::Text(t) => vec![t.clone()],
|
||||
other => return invalid(format!("{:?} can't take {other:?}", f.name)),
|
||||
};
|
||||
// Accept export values or display texts; free text only in editable combo boxes.
|
||||
for v in &vals {
|
||||
match option_named(f, v) {
|
||||
Some(i) => {
|
||||
if first_pick(&mut seen, i) {
|
||||
exports.push(f.options.get(i).map(|(e, _)| e.clone()).unwrap_or_else(|| v.clone()));
|
||||
picked.push(i);
|
||||
}
|
||||
}
|
||||
None if f.kind == FieldKind::Combo && f.has(flags::EDIT) => exports.push(v.clone()),
|
||||
None if f.options.is_empty() => exports.push(v.clone()),
|
||||
None => {
|
||||
let opts: Vec<&str> = f.options.iter().map(|(_, d)| d.as_str()).collect();
|
||||
return invalid(format!("{:?} has no option {v:?} (options: {})", f.name, opts.join(", ")));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut indices: Vec<Object> =
|
||||
exports.iter().filter_map(|e| f.options.iter().position(|(x, _)| x == e)).map(|i| Object::Int(i as i64)).collect();
|
||||
// /I lists option indices in ascending order; /V keeps the caller's value order.
|
||||
// Every entry above is an integer, so this sorts by its numeric option index.
|
||||
indices.sort_unstable_by_key(Object::as_int);
|
||||
// /I lists option indices in ascending order, each once; /V keeps the caller's order.
|
||||
picked.sort_unstable();
|
||||
picked.dedup();
|
||||
let indices: Vec<Object> = picked.iter().map(|&i| Object::Int(i64::try_from(i).unwrap_or(i64::MAX))).collect();
|
||||
// A list box scrolls (`/TI`) so the picked options are among the rows it draws, as
|
||||
// in other viewers: a pick below the last visible row would otherwise not show (#1524).
|
||||
let picked: Vec<usize> = indices.iter().filter_map(|i| i.as_int()).filter_map(|i| usize::try_from(i).ok()).collect();
|
||||
let top = list_scroll(f, &picked, f.options.len());
|
||||
// An empty value of its own keeps a parent field's /V from showing through.
|
||||
let shadow = exports.is_empty() && crate::author::ancestor_sets(doc, f.obj, b"V");
|
||||
@@ -398,7 +462,10 @@ pub(crate) fn write_value(doc: &mut Document, f: &Field, value: &FieldValue, scr
|
||||
}
|
||||
})?;
|
||||
scroll_widgets(doc, f, &picked, f.options.len())?;
|
||||
redraw(doc, f, &exports, scripts)
|
||||
let mut shown = f.clone();
|
||||
shown.value = exports.clone();
|
||||
shown.selected = picked;
|
||||
redraw(doc, &shown, &exports, scripts)
|
||||
}
|
||||
(FieldKind::PushButton, _) => invalid(format!("{:?} is a button; it has no value", f.name)),
|
||||
(FieldKind::Signature, _) => invalid(format!("{:?} is a signature field; sign it with Fill & Sign or a digital ID", f.name)),
|
||||
@@ -774,7 +841,7 @@ pub fn reset(doc: &mut Document, names: Option<&[String]>) -> Result<usize, Form
|
||||
}
|
||||
let v = match f.kind {
|
||||
FieldKind::Text => FieldValue::Text(f.default.first().cloned().unwrap_or_default()),
|
||||
FieldKind::CheckBox => FieldValue::Check(!f.default.is_empty()),
|
||||
FieldKind::CheckBox => f.check_box_value(f.default.first().map(String::as_str)),
|
||||
FieldKind::Radio => FieldValue::Radio(f.default.first().cloned()),
|
||||
FieldKind::Combo | FieldKind::List => FieldValue::Choice(f.default.clone()),
|
||||
FieldKind::PushButton | FieldKind::Signature => continue,
|
||||
@@ -788,3 +855,22 @@ pub fn reset(doc: &mut Document, names: Option<&[String]>) -> Result<usize, Form
|
||||
recalculate(doc)?;
|
||||
Ok(changed)
|
||||
}
|
||||
|
||||
/// Marks option `i` picked; false when it already was, or there is no such option.
|
||||
fn first_pick(seen: &mut [bool], i: usize) -> bool {
|
||||
match seen.get_mut(i) {
|
||||
Some(taken) if !*taken => {
|
||||
*taken = true;
|
||||
true
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The twin's positions for the source's picked positions `picked`, as
|
||||
/// [`crate::option_positions_in`] maps them, in ascending order, as `/I` lists them.
|
||||
fn twin_positions(picked: &[usize], source: &[(String, String)], twin: &[(String, String)]) -> Option<Vec<usize>> {
|
||||
let mut out = crate::option_positions_in(picked, source, twin)?;
|
||||
out.sort_unstable();
|
||||
Some(out)
|
||||
}
|
||||
|
||||
@@ -538,7 +538,7 @@ mod tests {
|
||||
|
||||
/// An `OWNER RIGHTS` entry replaces what an owner may do implicitly. Granting only *write
|
||||
/// owner* that way, the access list can't be replaced although the owner can still be set: the
|
||||
/// file isn't taken as restricted.
|
||||
/// file isn't taken as restricted. Run elevated, it can be replaced, and then must be restricted.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn a_file_whose_access_list_cant_be_replaced_is_not_restricted() {
|
||||
@@ -566,10 +566,24 @@ mod tests {
|
||||
// Nothing but the two entries: no Administrators entry for the elevated runner to use.
|
||||
let sddl = sddl_of(&file).unwrap();
|
||||
assert_eq!(section(&sddl, "D:"), Some(format!("(A;;524288;;;S-1-3-4)(A;;1179785;;;{me})").as_str()), "{sddl}");
|
||||
assert!(restrict_to_owner(&file, &user()).is_err(), "the access list could not be replaced");
|
||||
// An elevated administrator (the windows-latest runner) may replace the list anyway; then the
|
||||
// file must really be the user's alone, since the result is checked before it is trusted.
|
||||
if restrict_to_owner(&file, &user()).is_ok() {
|
||||
let after = sddl_of(&file).unwrap();
|
||||
assert!(elevated(), "the access list could not be replaced: {after}");
|
||||
assert_eq!(foreign_access(&after, &me), None, "{after}");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// Whether the tests run elevated: `whoami /groups` lists the high (or system) mandatory label.
|
||||
#[cfg(windows)]
|
||||
fn elevated() -> bool {
|
||||
let out = system_tool(WHOAMI).args(["/groups", "/fo", "csv", "/nh"]).output().unwrap();
|
||||
let text = String::from_utf8_lossy(&out.stdout);
|
||||
text.contains("\"S-1-16-12288\"") || text.contains("\"S-1-16-16384\"")
|
||||
}
|
||||
|
||||
/// When the tools fail, the functions say so: nothing is taken as restricted or as checked.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
|
||||
@@ -42,4 +42,4 @@ pub use settings::{
|
||||
};
|
||||
#[cfg(test)]
|
||||
use sheets::text_direction;
|
||||
pub use sheets::{LABEL_MARGIN, MARGIN, Placement, Sheet, layout, matching_paper, text_reads_up};
|
||||
pub use sheets::{LABEL_MARGIN, MARGIN, Placement, Sheet, layout, matching_paper, text_reads_up, texts_read_up};
|
||||
|
||||
@@ -7,7 +7,17 @@ use super::{DecodeBudget, Dict, Document, Matrix, Object};
|
||||
/// sideways on a letter or A4 sheet), counting each text-showing operator once; form XObjects
|
||||
/// are followed a few levels deep.
|
||||
pub fn text_reads_up(doc: &Document, index: usize) -> bool {
|
||||
let Some(page) = pdfcraft_model::pages(doc).into_iter().nth(index) else { return false };
|
||||
texts_read_up(doc, &[index]).first().copied().unwrap_or(false)
|
||||
}
|
||||
|
||||
/// [`text_reads_up`] for each of `indices`, reading the page tree once: once per page, the
|
||||
/// whole tree would be walked for every page asked about.
|
||||
pub fn texts_read_up(doc: &Document, indices: &[usize]) -> Vec<bool> {
|
||||
let pages = pdfcraft_model::pages(doc);
|
||||
indices.iter().map(|&i| pages.get(i).is_some_and(|page| page_reads_up(doc, page))).collect()
|
||||
}
|
||||
|
||||
fn page_reads_up(doc: &Document, page: &pdfcraft_model::Page) -> bool {
|
||||
let to_display = Matrix(page.view_matrix(doc)).invert().unwrap_or_default();
|
||||
let res = page.dict.get(b"Resources").and_then(|r| doc.resolve(r).as_dict().cloned()).unwrap_or_default();
|
||||
let mut score = 0i64;
|
||||
|
||||
@@ -1345,3 +1345,17 @@ fn a_page_form_without_annotations_shares_the_pages_indirect_resources() {
|
||||
let Object::Stream(s) = &*doc.get(form) else { panic!("form stream") };
|
||||
assert_eq!(s.dict.get(b"Resources"), Some(&Object::Ref(res)));
|
||||
}
|
||||
|
||||
/// Many pages asked about at once are answered from one walk of the page tree, each as
|
||||
/// [`text_reads_up`] answers it alone; a page past the end is `false`.
|
||||
#[test]
|
||||
fn texts_read_up_answers_many_pages_from_one_walk() {
|
||||
let doc = fixture(3_000);
|
||||
let all: Vec<usize> = (0..3_001).collect();
|
||||
let started = std::time::Instant::now();
|
||||
let up = texts_read_up(&doc, &all);
|
||||
assert!(started.elapsed() < std::time::Duration::from_secs(20), "{:?}", started.elapsed());
|
||||
assert_eq!(up.len(), all.len());
|
||||
assert!(up.iter().all(|u| !u), "upright text, and no page 3000");
|
||||
assert_eq!(up[1], text_reads_up(&doc, 1));
|
||||
}
|
||||
|
||||
@@ -1000,12 +1000,28 @@ pub fn clear_marks(doc: &mut Document, pages: Option<&[usize]>) -> Result<usize,
|
||||
let doomed = pdfcraft_annot::with_replies_and_popups(doc, &listed, targets.iter().copied());
|
||||
for p in pdfcraft_model::pages(doc) {
|
||||
let annots = annots_of(doc, &p.dict);
|
||||
let kept: Vec<Object> = annots.iter().filter(|a| !pdfcraft_annot::goes_with(a, &doomed)).cloned().collect();
|
||||
let kept: Vec<Object> = annots.iter().filter(|a| !pdfcraft_annot::goes_with(doc, a, &doomed)).cloned().collect();
|
||||
// A group subordinate of a mark stays, as when a comment's group primary is deleted, and
|
||||
// loses its `/IRT`: through it the mark would stay in the file.
|
||||
let kept = pdfcraft_annot::release_members(doc, kept, &doomed)?;
|
||||
// As deleting a comment does: a page whose marks were all it had loses `/Annots` again,
|
||||
// and an indirect array stays the one object the page points to.
|
||||
if kept.len() != annots.len() {
|
||||
// and an indirect array stays the one object the page points to. A page whose inline
|
||||
// member lost its `/IRT` is written too.
|
||||
if kept != annots {
|
||||
pdfcraft_annot::set_annots(doc, p.obj, kept)?;
|
||||
}
|
||||
}
|
||||
Ok(targets.len())
|
||||
}
|
||||
|
||||
/// The name to save a document under after [`apply`]: `_Redacted` before the extension, as
|
||||
/// Acrobat appends it ("contract.pdf" gives "contract_Redacted.pdf"). The `.pdf` extension is
|
||||
/// matched in any letter case. A name that already ends in `_Redacted` keeps it once.
|
||||
pub fn redacted_file_name(name: &str) -> String {
|
||||
let cut = name.len().saturating_sub(4);
|
||||
let stem = match (name.get(..cut), name.get(cut..)) {
|
||||
(Some(stem), Some(ext)) if ext.eq_ignore_ascii_case(".pdf") => stem,
|
||||
_ => name,
|
||||
};
|
||||
if stem.ends_with("_Redacted") { format!("{stem}.pdf") } else { format!("{stem}_Redacted.pdf") }
|
||||
}
|
||||
|
||||
@@ -2319,6 +2319,45 @@ fn clearing_marks_leaves_the_annotation_list_as_it_was() {
|
||||
assert_eq!((doc.get(page), doc.get(list)), before, "the page points at its array, which lists the link alone");
|
||||
}
|
||||
|
||||
/// A group subordinate (`/RT /Group`) of a mark stays when the marks are cleared, as one stays
|
||||
/// when its primary comment is deleted, and loses its `/IRT`: nothing then refers to the mark,
|
||||
/// so a full save leaves the mark's text out.
|
||||
#[test]
|
||||
fn clearing_marks_releases_a_group_member_of_a_mark() {
|
||||
let mut doc = one_page(b"BT /F1 10 Tf 10 100 Td (AB) Tj ET", "", vec![]);
|
||||
mark(&mut doc, 0, &[[0.0, 0.0, 50.0, 50.0]], "");
|
||||
let m = marks(&doc)[0].obj;
|
||||
doc.update_dict(m, |d| d.set(b"Contents".to_vec(), pdfcraft_cos::PdfString::text("MARK_SECRET_TEXT"))).unwrap();
|
||||
let mut member = Dict::new();
|
||||
member.set(b"Type".to_vec(), Object::name("Annot"));
|
||||
member.set(b"Subtype".to_vec(), Object::name("Square"));
|
||||
member.set(b"Rect".to_vec(), Object::Array([60, 60, 90, 90].map(Object::Int).to_vec()));
|
||||
member.set(b"IRT".to_vec(), Object::Ref(m));
|
||||
member.set(b"RT".to_vec(), Object::name("Group"));
|
||||
let member = doc.add(Object::Dict(member));
|
||||
let page = pdfcraft_model::pages(&doc)[0].obj;
|
||||
let mut listed = annots_of(&doc, doc.get(page).as_dict().unwrap());
|
||||
listed.push(Object::Ref(member));
|
||||
doc.update_dict(page, |d| d.set(b"Annots".to_vec(), Object::Array(listed))).unwrap();
|
||||
assert_eq!(clear_marks(&mut doc, None), Ok(1));
|
||||
assert_eq!(annots_of(&doc, doc.get(page).as_dict().unwrap()), [Object::Ref(member)], "the member stays");
|
||||
let d = doc.get(member).as_dict().cloned().unwrap();
|
||||
assert!(d.get(b"IRT").is_none() && d.name(b"RT") == Some(b"Group".as_slice()), "{d:?}");
|
||||
let full = write_full(&doc, &SaveOptions { object_streams: false, ..SaveOptions::default() }).unwrap();
|
||||
assert!(!full.windows(16).any(|w| w == b"MARK_SECRET_TEXT"), "the cleared mark is not in a full save");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn redacted_copies_are_named_with_redacted_before_the_extension() {
|
||||
assert_eq!(redacted_file_name("contract.pdf"), "contract_Redacted.pdf");
|
||||
assert_eq!(redacted_file_name("SCAN.PDF"), "SCAN_Redacted.pdf");
|
||||
assert_eq!(redacted_file_name("Report.Pdf"), "Report_Redacted.pdf");
|
||||
// A document without the extension (opened from bytes) gets it.
|
||||
assert_eq!(redacted_file_name("Untitled"), "Untitled_Redacted.pdf");
|
||||
// Redacting a redacted copy again does not add a second suffix.
|
||||
assert_eq!(redacted_file_name("contract_Redacted.pdf"), "contract_Redacted.pdf");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unreadable_content_fails_closed() {
|
||||
let mut doc = one_page(b"", "", vec![]);
|
||||
|
||||
@@ -25,6 +25,9 @@ log = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
# Reads rendered pixel words as bytes; already in the tree through hayro.
|
||||
bytemuck = { version = "1" }
|
||||
# Resolves relative URI actions against the catalog's /URI /Base, by the rules the browser uses;
|
||||
# already in the tree (pdfcraft-engine checks document links with it).
|
||||
url = "2.5"
|
||||
# Tells combining marks (bidi class NSM: general categories Mn and Me) in extracted text; the
|
||||
# version pdfcraft-fonts already uses.
|
||||
unicode-bidi = "0.3"
|
||||
|
||||
@@ -36,14 +36,17 @@ pub use core::{check_pages, inspect, pretty_date};
|
||||
#[cfg(test)]
|
||||
use core::{inspect_structure, spend};
|
||||
pub use model::{
|
||||
Annotation, Attachment, AttachmentSource, DestView, Field, FieldKind, FontInfo, Layer, LayerOp, Link, LinkTarget, OutlineItem, PageInfo,
|
||||
PageTransition, RemoteDestination, ReviewStates, TransitionStyle, Xfa, link_replies, thread_tops,
|
||||
Annotation, Attachment, AttachmentSource, DestView, Field, FieldKind, FontInfo, Layer, LayerItem, LayerOp, LayerRow, Link, LinkTarget,
|
||||
MAX_GROUP_DEPTH, OutlineItem, PageInfo, PageTransition, Popup, RemoteDestination, ReviewStates, TransitionStyle, Xfa, fill_group_text,
|
||||
group_primaries, link_replies, thread_tops,
|
||||
};
|
||||
#[cfg(test)]
|
||||
use navigation::{OUTLINE_DEPTH, OUTLINE_WINDOW};
|
||||
#[cfg(test)]
|
||||
use resources::LABEL_DECODES;
|
||||
pub use resources::attachment_data;
|
||||
#[cfg(test)]
|
||||
use resources::{xfa_config_dynamic_render, xfa_packet_text};
|
||||
use resources::{MAX_LAYER_LABEL_CHARS, MAX_LAYER_ORDER_ROWS, xfa_config_dynamic_render, xfa_packet_text};
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct DocInfo {
|
||||
@@ -70,10 +73,17 @@ pub struct DocInfo {
|
||||
pub annotations: Vec<Annotation>,
|
||||
pub fields: Vec<Field>,
|
||||
pub links: Vec<Link>,
|
||||
/// The catalog's `/URI /Base` (ISO 32000-2 Table 211), the base for relative URI actions, when
|
||||
/// it is a string of at most [`crate::MAX_URI_BASE_BYTES`].
|
||||
pub uri_base: Option<String>,
|
||||
pub layers: Vec<Layer>,
|
||||
/// Radio-button layer groups (`/OCProperties /D /RBGroups`): turning one layer of a group on
|
||||
/// turns the others off.
|
||||
pub layer_groups: Vec<Vec<(u32, u16)>>,
|
||||
/// The Layers panel's rows: the default configuration's `/Order` (ISO 32000-2 Table 99), a
|
||||
/// tree of layers (indices into `layers`) and labels. A layer it doesn't list isn't presented,
|
||||
/// though it still draws in its state; no `/Order` presents none.
|
||||
pub layer_order: Vec<LayerRow>,
|
||||
pub fonts: Vec<FontInfo>,
|
||||
pub attachments: Vec<Attachment>,
|
||||
/// Pages with a presentation transition (`/Trans`) or display time (`/Dur`), in page order.
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use super::core::{limited_pdf_string, pretty_date, spend};
|
||||
use super::model::{
|
||||
Annotation, AttachmentSource, DestView, Field, FieldKind, LayerOp, Link, LinkTarget, RemoteDestination, link_replies, state_or_default,
|
||||
Annotation, AttachmentSource, DestView, Field, FieldKind, LayerOp, Link, LinkTarget, Popup, RemoteDestination, fill_group_text, link_replies,
|
||||
state_or_default,
|
||||
};
|
||||
use super::navigation::text_string;
|
||||
use super::{Dictionary, DocInfo, Entry, HashMap, HashSet, Inspector, Object, ObjectId};
|
||||
@@ -17,11 +18,13 @@ const MAX_REMOTE_DESTINATION_NAME_BYTES: usize = 1024;
|
||||
/// are not listed: real comments stay far below, many small ones sharing one long string do not.
|
||||
pub(super) const MAX_ANNOTATION_BYTES: usize = 64 << 20;
|
||||
|
||||
/// Web-address text the bookmark and link listings, and name, description and embedded-file key
|
||||
/// text the attachment listing, keep together. Many bookmarks, links or attachments can share one
|
||||
/// long string, which each would otherwise copy. Past it, a bookmark or link to a web address lists
|
||||
/// as a URI action without its address, an attachment under its generic name without a
|
||||
/// description, and an embedded file whose key does not fit is not listed.
|
||||
/// Web-address text and `/QuadPoints` geometry the bookmark and link listings, and name,
|
||||
/// description and embedded-file key text the attachment listing, keep together. Many bookmarks,
|
||||
/// links or attachments can share one long string or array, which each would otherwise copy. Past
|
||||
/// it, a bookmark or link to a web address lists as a URI action without its address (or a link
|
||||
/// keeps a relative address unresolved against the document's base), a link is active over its
|
||||
/// whole `/Rect`, an attachment is listed under its generic name without a description, and an
|
||||
/// embedded file whose key does not fit is not listed.
|
||||
pub(super) const MAX_LINK_ATTACHMENT_TEXT_BYTES: usize = 16 << 20;
|
||||
|
||||
/// A colour array as RGB, read as pdfcraft-annot's appearance builder reads it (`appearance::color`
|
||||
@@ -87,6 +90,9 @@ impl<'a> Inspector<'a> {
|
||||
|
||||
/// `text_budget` is what is left of [`MAX_LINK_ATTACHMENT_TEXT_BYTES`].
|
||||
pub(super) fn annotations(&self, info: &mut DocInfo, text_budget: &mut usize) {
|
||||
// Indirect `/QuadPoints` arrays whose quadrilaterals did not fit what was left of the budget:
|
||||
// the budget only shrinks, so they are not read again (review on #4474).
|
||||
let mut unfit_quads: HashSet<ObjectId> = HashSet::new();
|
||||
let mut pages: Vec<(ObjectId, usize)> = self.page_index.iter().map(|(&id, &page)| (id, page)).collect();
|
||||
pages.sort_unstable_by_key(|&(_, page)| page);
|
||||
// An annotation, or a whole `/Annots` array, that several entries or pages list is on the
|
||||
@@ -138,7 +144,7 @@ impl<'a> Inspector<'a> {
|
||||
info.attachments.push(self.attachment(fs, AttachmentSource::Annotation { page, index }, text_budget, fallback));
|
||||
}
|
||||
if subtype == "Link" {
|
||||
if let Some(link) = self.link(page, index, d, text_budget) {
|
||||
if let Some(link) = self.link(page, index, d, info.uri_base.as_deref(), text_budget, &mut unfit_quads) {
|
||||
if matches!(&link.target, LinkTarget::Other(s) if s == "JavaScript") {
|
||||
info.has_javascript = true;
|
||||
}
|
||||
@@ -202,6 +208,35 @@ impl<'a> Inspector<'a> {
|
||||
}
|
||||
_ => Vec::new(),
|
||||
};
|
||||
// A callout: its arrow point and knee, and its text box (keep in step with
|
||||
// `pdfcraft_annot::summaries`).
|
||||
let (points, text_box) = match self.callout(d, rect) {
|
||||
Some((lead, text_box)) if subtype == "FreeText" => (lead, Some(text_box)),
|
||||
_ => (points, None),
|
||||
};
|
||||
// Only the comment's own pop-up: a pop-up annotation whose /Parent, if any, is a
|
||||
// reference to this comment (keep in step with `pdfcraft_annot::summaries`).
|
||||
let own = self.resolved_id(a);
|
||||
let is_own = |p: &&Dictionary| {
|
||||
self.name(p, b"Subtype").as_deref() == Some("Popup")
|
||||
&& p.get(b"Parent")
|
||||
.map_or(true, |parent| parent.as_reference().is_ok() && self.resolved_id(parent).is_some_and(|id| Some(id) == own))
|
||||
};
|
||||
// A pop-up without a `/Rect` of four numbers finite as `f32` is none, as
|
||||
// `pdfcraft_annot::summaries` reads it: both lists of the comments agree. Its corners
|
||||
// may come in any order.
|
||||
let popup = d.get(b"Popup").ok().and_then(|o| self.dict(o)).filter(is_own).and_then(|p| {
|
||||
let rect = self.resolve(p.get(b"Rect").ok()?).as_array().ok()?;
|
||||
let nums: Vec<f32> = rect.iter().filter_map(|v| self.resolve(v).as_float().ok()).collect();
|
||||
let [x0, y0, x1, y1] = nums[..] else { return None };
|
||||
if !nums.iter().all(|v| v.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
Some(Popup {
|
||||
rect: [x0.min(x1), y0.min(y1), x0.max(x1), y0.max(y1)],
|
||||
open: p.get(b"Open").ok().and_then(|o| self.resolve(o).as_bool().ok()).unwrap_or(false),
|
||||
})
|
||||
});
|
||||
let annotation = Annotation {
|
||||
page,
|
||||
subtype,
|
||||
@@ -224,6 +259,8 @@ impl<'a> Inspector<'a> {
|
||||
fill_sign,
|
||||
no_rotate: d.get(b"F").is_ok_and(|f| draw_flags(self.resolve(f)) & 16 != 0),
|
||||
points,
|
||||
text_box,
|
||||
popup,
|
||||
};
|
||||
kept = kept.saturating_add(retained(&annotation));
|
||||
if kept > MAX_ANNOTATION_BYTES {
|
||||
@@ -234,20 +271,89 @@ impl<'a> Inspector<'a> {
|
||||
}
|
||||
info.annotations.sort_by(|a, b| a.page.cmp(&b.page).then(b.rect[3].total_cmp(&a.rect[3])));
|
||||
link_replies(&mut info.annotations);
|
||||
fill_group_text(&mut info.annotations);
|
||||
}
|
||||
|
||||
/// A callout's arrow point and knee (`/CL`, four or six numbers, without the end that meets
|
||||
/// the text box) and its text box (`/Rect`, here `rect`, inset by `/RD`); ISO 32000-2
|
||||
/// Table 177. `None` when either is missing or unusable.
|
||||
fn callout(&self, d: &Dictionary, rect: [f32; 4]) -> Option<(Vec<[f32; 2]>, [f32; 4])> {
|
||||
let nums = |key: &[u8]| -> Option<Vec<f32>> {
|
||||
match self.resolve(d.get(key).ok()?) {
|
||||
Object::Array(v) => v.iter().map(|o| self.resolve(o).as_float().ok()).collect(),
|
||||
_ => None,
|
||||
}
|
||||
};
|
||||
let cl = nums(b"CL").filter(|l| matches!(l.len(), 4 | 6) && l.iter().all(|x| x.is_finite()))?;
|
||||
let rd = nums(b"RD").filter(|v| v.len() == 4 && v.iter().all(|x| x.is_finite() && *x >= 0.0))?;
|
||||
let tb = [rect[0] + rd[0], rect[1] + rd[1], rect[2] - rd[2], rect[3] - rd[3]];
|
||||
if tb[2] - tb[0] < 1.0 || tb[3] - tb[1] < 1.0 {
|
||||
return None;
|
||||
}
|
||||
let (_, lead) = cl.as_chunks::<2>().0.split_last()?;
|
||||
Some((lead.to_vec(), tb))
|
||||
}
|
||||
|
||||
/// The link annotation `d`, at position `index` of page `page`'s `/Annots`: where its `/Dest`
|
||||
/// goes, else what its action `/A` does ([`Self::action_target`]). `None` when it has no
|
||||
/// rectangle, or a destination or action that leads nowhere.
|
||||
fn link(&self, page: usize, index: usize, d: &Dictionary, text_budget: &mut usize) -> Option<Link> {
|
||||
/// rectangle, or a destination or action that leads nowhere. `base` is the catalog's
|
||||
/// `/URI /Base`, which a relative URI action is resolved against. `unfit_quads` holds the
|
||||
/// indirect `/QuadPoints` arrays already found too large for the budget.
|
||||
fn link(
|
||||
&self,
|
||||
page: usize,
|
||||
index: usize,
|
||||
d: &Dictionary,
|
||||
base: Option<&str>,
|
||||
text_budget: &mut usize,
|
||||
unfit_quads: &mut HashSet<ObjectId>,
|
||||
) -> Option<Link> {
|
||||
let rect = rect4(self.resolve(d.get(b"Rect").ok()?));
|
||||
let target = if let Ok(dest) = d.get(b"Dest") {
|
||||
let (page, view) = self.dest(dest, 0)?;
|
||||
LinkTarget::Page(page, view)
|
||||
} else {
|
||||
self.action_target(d.get(b"A").ok().and_then(|a| self.dict(a))?, text_budget)?
|
||||
match self.action_target(d.get(b"A").ok().and_then(|a| self.dict(a))?, text_budget)? {
|
||||
LinkTarget::Uri(uri) => match crate::resolve_uri(base, &uri) {
|
||||
// The raw address is spent already. What the base adds is spent too, or the
|
||||
// link keeps the raw address.
|
||||
Some(resolved) if resolved.len().saturating_sub(uri.len()) <= *text_budget => {
|
||||
*text_budget = text_budget.saturating_sub(resolved.len().saturating_sub(uri.len()));
|
||||
LinkTarget::Uri(resolved)
|
||||
}
|
||||
_ => LinkTarget::Uri(uri),
|
||||
},
|
||||
other => other,
|
||||
}
|
||||
};
|
||||
Some(Link { page, index, rect, target })
|
||||
// Not read at all once no quadrilateral would fit what is left of the budget, or when this
|
||||
// shared array already did not fit: many links can share one long array, and reading it
|
||||
// again for each would cost its length every time (review on #4474).
|
||||
let shared = d.get(b"QuadPoints").ok().and_then(|o| o.as_reference().ok());
|
||||
let readable = *text_budget >= std::mem::size_of::<[f32; 8]>() && shared.is_none_or(|id| !unfit_quads.contains(&id));
|
||||
let quads = match d.get(b"QuadPoints").map(|o| self.resolve(o)) {
|
||||
// Read no further than one value past the cap: a longer array isn't used.
|
||||
Ok(Object::Array(q)) if readable && q.len() <= crate::MAX_LINK_QUADS.saturating_mul(8) => {
|
||||
#[cfg(test)]
|
||||
QUAD_ARRAYS_READ.with(|n| n.set(n.get() + 1));
|
||||
let values: Vec<Option<f32>> = q.iter().map(|o| self.resolve(o).as_float().ok()).collect();
|
||||
let quads = crate::link_quads(&values, rect);
|
||||
// Many links can share one long array, which each would otherwise copy. Past the
|
||||
// budget a link is active over its whole `/Rect`.
|
||||
let bytes = std::mem::size_of_val(quads.as_slice());
|
||||
if bytes <= *text_budget {
|
||||
*text_budget = text_budget.saturating_sub(bytes);
|
||||
quads
|
||||
} else {
|
||||
if let Some(id) = shared {
|
||||
unfit_quads.insert(id);
|
||||
}
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
_ => Vec::new(),
|
||||
};
|
||||
Some(Link { page, index, rect, quads, target })
|
||||
}
|
||||
|
||||
/// What an action does when a link or a bookmark runs it. Only a go-to's `/D` is a place in
|
||||
@@ -643,3 +749,9 @@ fn rect4(o: &Object) -> [f32; 4] {
|
||||
_ => [0.0; 4],
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// `/QuadPoints` arrays whose values were read.
|
||||
pub(super) static QUAD_ARRAYS_READ: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
@@ -222,6 +222,10 @@ impl<'a> Inspector<'a> {
|
||||
Ok(notes) => info.warnings.extend(notes.into_iter().map(|note| format!("Page labels: {note}."))),
|
||||
Err(reason) => info.warnings.push(format!("Page labels were skipped: {reason}; using physical page numbers.")),
|
||||
}
|
||||
info.uri_base = catalog.get(b"URI").ok().and_then(|o| self.dict(o)).and_then(|d| match d.get(b"Base").map(|o| self.resolve(o)) {
|
||||
Ok(Object::String(bytes, _)) if bytes.len() <= crate::MAX_URI_BASE_BYTES => std::str::from_utf8(bytes).ok().map(str::to_owned),
|
||||
_ => None,
|
||||
});
|
||||
let mut text_budget = MAX_LINK_ATTACHMENT_TEXT_BYTES;
|
||||
if let Some(first) = catalog.get(b"Outlines").ok().and_then(|o| self.dict(o)).and_then(|d| d.get(b"First").ok()) {
|
||||
(info.outline, info.outline_more) = self.outline_window(first, &mut text_budget);
|
||||
@@ -267,6 +271,7 @@ impl<'a> Inspector<'a> {
|
||||
}
|
||||
self.layers(catalog, &mut info.layers);
|
||||
info.layer_groups = self.layer_groups(catalog);
|
||||
info.layer_order = self.layer_order(catalog, &info.layers);
|
||||
self.fonts(&mut info.fonts);
|
||||
if let Some(names) = catalog.get(b"Names").ok().and_then(|o| self.dict(o)) {
|
||||
if let Some(ef) = names.get(b"EmbeddedFiles").ok().and_then(|o| self.dict(o)) {
|
||||
|
||||
@@ -196,13 +196,39 @@ pub struct Link {
|
||||
/// Zero-based position in the page's raw `/Annots` array.
|
||||
pub index: usize,
|
||||
pub rect: [f32; 4],
|
||||
/// Where the link is active when that isn't the whole of `rect`: its `/QuadPoints`, 8 numbers
|
||||
/// each in user space (ISO 32000-2 Table 176). Empty when the link is active over `rect`
|
||||
/// ([`crate::link_quads`]).
|
||||
pub quads: Vec<[f32; 8]>,
|
||||
pub target: LinkTarget,
|
||||
}
|
||||
|
||||
impl Link {
|
||||
/// Whether the user-space point `(x, y)` activates the link: inside one of its quadrilaterals,
|
||||
/// or inside its rectangle when it has none.
|
||||
pub fn contains(&self, x: f32, y: f32) -> bool {
|
||||
let [x0, y0, x1, y1] = self.rect;
|
||||
if self.quads.is_empty() {
|
||||
return x >= x0 && x <= x1 && y >= y0 && y <= y1;
|
||||
}
|
||||
// Every kept quadrilateral lies within `/Rect` give or take the slack `link_quads`
|
||||
// accepts, so a point outside that is in none of them: skip the scan (up to
|
||||
// `MAX_LINK_QUADS` per link, run per link on every pointer move).
|
||||
let s = crate::link_area::RECT_SLACK;
|
||||
if !(x >= x0 - s && x <= x1 + s && y >= y0 - s && y <= y1 + s) {
|
||||
return false;
|
||||
}
|
||||
self.quads.iter().any(|q| crate::quad_contains(q, x, y))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum LinkTarget {
|
||||
/// A destination in this document: the 0-based page and where on it the view goes.
|
||||
Page(usize, DestView),
|
||||
/// A URI action's address, resolved against the catalog's `/URI /Base` when it is a relative
|
||||
/// reference ([`crate::resolve_uri`]); not yet checked, as the opener must
|
||||
/// (`pdfcraft_engine::links::document_url`).
|
||||
Uri(String),
|
||||
/// A set-layer-visibility action (`SetOCGState`, ISO 32000-2 §12.6.4.13): each change in
|
||||
/// order, naming the layer by its optional content group. With `preserve_rb`, a layer turned
|
||||
@@ -320,8 +346,9 @@ pub struct Annotation {
|
||||
/// names the first comment on every page `fitz-A0`. `None` when `/IRT` leads to no listed
|
||||
/// comment ([`link_replies`]).
|
||||
pub parent: Option<(usize, usize)>,
|
||||
/// `/RT /Group`: grouped with the annotation `/IRT` points at (Replace Text's caret with its
|
||||
/// strikeout) rather than a reply to it.
|
||||
/// `/RT /Group` (ISO 32000-2 §12.5.6.2, Table 172): with a `parent`, a subordinate of the
|
||||
/// group whose primary `/IRT` points at, not a reply ([`Self::is_group_member`]). Its own
|
||||
/// text, author, colour and dates are ignored; see [`group_primaries`].
|
||||
pub grouped: bool,
|
||||
/// Rect in PDF user space: [x0, y0, x1, y1].
|
||||
pub rect: [f32; 4],
|
||||
@@ -343,9 +370,83 @@ pub struct Annotation {
|
||||
/// appearance stays upright, turned about the upper-left corner of `rect`
|
||||
/// ([`Self::shown_rect`]).
|
||||
pub no_rotate: bool,
|
||||
/// The points that shape a line (its two ends, `/L`) or connected lines, a polygon or a
|
||||
/// cloud (their corners, `/Vertices`), in user space; empty for other comments.
|
||||
/// The points that shape a line (its two ends, `/L`), connected lines, a polygon or a cloud
|
||||
/// (their corners, `/Vertices`), or a callout (its arrow point and knee: `/CL` without its
|
||||
/// end, which follows the text box), in user space; empty for other comments.
|
||||
pub points: Vec<[f32; 2]>,
|
||||
/// A callout's text box (`/Rect` inset by `/RD`), in user space; `None` for other comments.
|
||||
pub text_box: Option<[f32; 4]>,
|
||||
/// The comment's pop-up window (`/Popup`): where it sits and whether it is open.
|
||||
pub popup: Option<Popup>,
|
||||
}
|
||||
|
||||
/// How far [`group_primaries`] follows `/IRT` from a group subordinate to its primary.
|
||||
pub const MAX_GROUP_DEPTH: usize = 64;
|
||||
|
||||
/// For each annotation of `all`, the position in `all` of the primary of the group it is a
|
||||
/// subordinate of ([`Annotation::is_group_member`], ISO 32000-2 §12.5.6.2), or `None` when it is
|
||||
/// not one. The group's attributes, its comment and its replies are the primary's. A subordinate
|
||||
/// of a subordinate leads to the first non-subordinate up the `/IRT` chain. Expects links
|
||||
/// [`link_replies`] settled: a subordinate whose chain loops or names nothing listed has lost its
|
||||
/// `parent` there and is a comment of its own, as such a reply is. One still on a subordinate
|
||||
/// after [`MAX_GROUP_DEPTH`] steps has no primary (`None`) and is listed under no comment.
|
||||
pub fn group_primaries(all: &[Annotation]) -> Vec<Option<usize>> {
|
||||
let mut at: HashMap<(usize, usize), usize> = HashMap::new();
|
||||
for (i, a) in all.iter().enumerate() {
|
||||
at.entry((a.page, a.index)).or_insert(i);
|
||||
}
|
||||
let primary = |start: usize| -> Option<usize> {
|
||||
let mut i = start;
|
||||
for _ in 0..MAX_GROUP_DEPTH {
|
||||
let a = all.get(i)?;
|
||||
if !a.is_group_member() {
|
||||
return Some(i);
|
||||
}
|
||||
i = *at.get(&a.parent?)?;
|
||||
}
|
||||
None
|
||||
};
|
||||
all.iter().enumerate().map(|(i, a)| if a.is_group_member() { primary(i) } else { None }).collect()
|
||||
}
|
||||
|
||||
/// Give a group's StrikeOut primary with no text of its own (`/Contents` missing or empty) the
|
||||
/// text of its first Caret subordinate that has some. A reader ignores a subordinate's
|
||||
/// `/Contents` (ISO 32000-2 §12.5.6.2), but Replace Text groups written by earlier PdfCraft builds
|
||||
/// made the strikeout the primary, with no text, and kept the replacement only on the caret:
|
||||
/// without this they would list as a comment with no text. A primary's own text always wins, no
|
||||
/// other subordinate lends its text, and no other kind of primary borrows one. Only the listing
|
||||
/// changes, not the file.
|
||||
pub fn fill_group_text(all: &mut [Annotation]) {
|
||||
if !all.iter().any(Annotation::is_group_member) {
|
||||
return;
|
||||
}
|
||||
let primaries = group_primaries(all);
|
||||
let lacks_text = |p: usize| all.get(p).is_some_and(|a| a.subtype == "StrikeOut" && a.contents.as_deref().is_none_or(str::is_empty));
|
||||
// Keyed by the primary's position: the first caret with text per primary wins (an empty one
|
||||
// lends nothing), and each primary is written once, so the order of the map does not matter.
|
||||
let mut texts: HashMap<usize, String> = HashMap::new();
|
||||
for (a, p) in all.iter().zip(&primaries) {
|
||||
if let (Some(p), Some(text), "Caret") = (*p, a.contents.as_ref(), a.subtype.as_str())
|
||||
&& !text.is_empty()
|
||||
&& lacks_text(p)
|
||||
{
|
||||
texts.entry(p).or_insert_with(|| text.clone());
|
||||
}
|
||||
}
|
||||
for (p, text) in texts {
|
||||
if let Some(primary) = all.get_mut(p) {
|
||||
primary.contents = Some(text);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A comment's pop-up window (ISO 32000-2 §12.5.6.14).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Popup {
|
||||
/// `/Rect` of the `/Popup` annotation, in user space.
|
||||
pub rect: [f32; 4],
|
||||
/// `/Open`: shown open.
|
||||
pub open: bool,
|
||||
}
|
||||
|
||||
impl Annotation {
|
||||
@@ -366,6 +467,13 @@ impl Annotation {
|
||||
!self.is_reply() && self.state.is_none()
|
||||
}
|
||||
|
||||
/// A subordinate of a group (`/RT /Group` with an `/IRT` that leads to a listed comment, ISO
|
||||
/// 32000-2 §12.5.6.2): part of its primary's comment ([`group_primaries`]), neither a comment
|
||||
/// of its own nor one of its replies. Expects links [`link_replies`] settled.
|
||||
pub fn is_group_member(&self) -> bool {
|
||||
self.grouped && self.is_reply()
|
||||
}
|
||||
|
||||
/// Whether this annotation's `/IRT` points at `other`.
|
||||
pub fn replies_to(&self, other: &Annotation) -> bool {
|
||||
self.parent == Some((other.page, other.index))
|
||||
@@ -470,6 +578,18 @@ pub fn link_replies(annotations: &mut [Annotation]) {
|
||||
a.parent = None;
|
||||
}
|
||||
}
|
||||
// A group is one page's (Acrobat reads it so): a subordinate whose primary is on another page
|
||||
// is a comment of its own, with its own author and text, rather than part of that group or a
|
||||
// reply to it. ISO 32000-2 §12.5.6.2 doesn't limit a group to a page, but Acrobat (desktop and
|
||||
// iPad) and PDF-XChange all delete the primary without such a subordinate, and Acrobat desktop
|
||||
// lists it on its own. Keep in step with
|
||||
// `pdfcraft_annot::summaries`.
|
||||
for a in annotations.iter_mut() {
|
||||
if a.grouped && a.parent.is_some_and(|(page, _)| page != a.page) {
|
||||
a.parent = None;
|
||||
a.in_reply_to = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The comment each reply's thread starts from, by the reply's page and `/Annots` position: a
|
||||
@@ -521,6 +641,9 @@ impl<'a> ReviewStates<'a> {
|
||||
// costs one walk, not one per reply.
|
||||
let mut reaches: HashMap<(usize, usize), Option<(usize, usize)>> = HashMap::new();
|
||||
let mut by_target: HashMap<(usize, usize), Vec<&Annotation>> = HashMap::new();
|
||||
// A state set on a group subordinate is the group's, its primary's (ISO 32000-2 §12.5.6.2).
|
||||
let primary_of: HashMap<(usize, usize), (usize, usize)> =
|
||||
all.iter().zip(group_primaries(all)).filter_map(|(a, p)| all.get(p?).map(|p| ((a.page, a.index), (p.page, p.index)))).collect();
|
||||
for r in all.iter().filter(|a| a.state.is_some()) {
|
||||
let (mut path, mut seen, mut up) = (vec![(r.page, r.index)], HashSet::from([(r.page, r.index)]), r.parent);
|
||||
let target = loop {
|
||||
@@ -541,7 +664,7 @@ impl<'a> ReviewStates<'a> {
|
||||
for key in path {
|
||||
reaches.insert(key, target);
|
||||
}
|
||||
if let Some(t) = target {
|
||||
if let Some(t) = target.map(|t| primary_of.get(&t).copied().unwrap_or(t)) {
|
||||
by_target.entry(t).or_default().push(r);
|
||||
}
|
||||
}
|
||||
@@ -652,6 +775,23 @@ pub struct Layer {
|
||||
pub initial: bool,
|
||||
}
|
||||
|
||||
/// One row of the Layers panel ([`DocInfo::layer_order`]).
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct LayerRow {
|
||||
/// Nesting level, 0 at the top: a nested array's entries are one deeper than the layer or
|
||||
/// label before them.
|
||||
pub depth: usize,
|
||||
pub item: LayerItem,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum LayerItem {
|
||||
/// A layer, by its index in [`DocInfo::layers`].
|
||||
Layer(usize),
|
||||
/// A text label heading a nested array: not a layer, so it can't be selected or toggled.
|
||||
Label(String),
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Attachment {
|
||||
pub name: String,
|
||||
@@ -723,6 +863,8 @@ mod review_state_tests {
|
||||
fill_sign: false,
|
||||
no_rotate: false,
|
||||
points: Vec::new(),
|
||||
text_box: None,
|
||||
popup: None,
|
||||
})
|
||||
.collect();
|
||||
link_replies(&mut all);
|
||||
@@ -791,6 +933,24 @@ mod review_state_tests {
|
||||
assert!(states.history(by_name(&all, "s1")).is_empty(), "a state reply has no states of its own");
|
||||
}
|
||||
|
||||
/// §12.5.6.2: a group is one comment, its primary's, so a status set on a subordinate is the
|
||||
/// group's; one set on an ordinary reply stays the reply's.
|
||||
#[test]
|
||||
fn a_status_on_a_group_subordinate_is_the_groups() {
|
||||
let mut all = listed(&[
|
||||
("p", None, "Alice", None),
|
||||
("sub", Some("p"), "Bob", None),
|
||||
("s", Some("sub"), "Dan", Some("Accepted")),
|
||||
("r", Some("p"), "Carol", None),
|
||||
("rs", Some("r"), "Eve", Some("Rejected")),
|
||||
]);
|
||||
all[1].grouped = true;
|
||||
let states = ReviewStates::new(&all);
|
||||
assert_eq!(states.statuses(by_name(&all, "p")), [("Dan", "Accepted")]);
|
||||
assert!(states.history(by_name(&all, "sub")).is_empty());
|
||||
assert_eq!(states.statuses(by_name(&all, "r")), [("Eve", "Rejected")]);
|
||||
}
|
||||
|
||||
/// States follow object references, not `/NM`: two comments with the same `/NM` (some writers
|
||||
/// name the first comment on every page alike) each keep their own statuses.
|
||||
#[test]
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
#[cfg(test)]
|
||||
use super::core::inspect;
|
||||
use super::core::{Inspector, load_options};
|
||||
use super::model::{Attachment, AttachmentSource, FontInfo, Layer, PageTransition, TransitionStyle};
|
||||
use super::navigation::NameTreeSeen;
|
||||
use super::{AssertUnwindSafe, Dictionary, DocInfo, Document, HashSet, Object, ObjectId, catch_unwind};
|
||||
use super::model::{Attachment, AttachmentSource, FontInfo, Layer, LayerItem, LayerRow, PageTransition, TransitionStyle};
|
||||
use super::navigation::{NameTreeSeen, text_string};
|
||||
use super::{AssertUnwindSafe, Dictionary, DocInfo, Document, HashMap, HashSet, Object, ObjectId, catch_unwind};
|
||||
|
||||
/// Decoded bytes read from an XFA form's configuration packet (or a whole-XDP `/XFA` stream) to
|
||||
/// find `dynamicRender`. Designer's packets are a few kilobytes; a whole XDP can hold the template.
|
||||
@@ -12,6 +12,25 @@ const MAX_XFA_CONFIG_BYTES: usize = 16 << 20;
|
||||
/// At most this many layers are read from all of `/RBGroups` together.
|
||||
const MAX_LAYER_GROUP_ENTRIES: usize = 4096;
|
||||
|
||||
/// The configuration's auto state (`/AS`): at most this many usage application dictionaries,
|
||||
/// `/OCGs` entries across them, and `/Category` names in each are read. The renderer's
|
||||
/// (vendored hayro-interpret patch (103)) have the same values.
|
||||
const MAX_AUTO_STATE_APPLICATIONS: usize = 256;
|
||||
const MAX_AUTO_STATE_GROUPS: usize = 4096;
|
||||
const MAX_AUTO_STATE_CATEGORIES: usize = 16;
|
||||
|
||||
/// The Layers panel's rows from `/Order`: at most this many rows, nested at most this deep, and
|
||||
/// a label keeps at most this many characters.
|
||||
pub(super) const MAX_LAYER_ORDER_ROWS: usize = 4096;
|
||||
const MAX_LAYER_ORDER_DEPTH: usize = 32;
|
||||
pub(super) const MAX_LAYER_LABEL_CHARS: usize = 256;
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// Layer labels decoded by [`Inspector::layer_order`] on this thread.
|
||||
pub(super) static LABEL_DECODES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
impl<'a> Inspector<'a> {
|
||||
// ── object helpers ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -100,11 +119,14 @@ impl<'a> Inspector<'a> {
|
||||
.and_then(|o| self.resolve(o).as_array().ok())
|
||||
.map(|a| a.iter().filter_map(|x| x.as_reference().ok()).collect())
|
||||
.unwrap_or_default();
|
||||
let auto = config.map(|c| self.view_auto_state(c)).unwrap_or_default();
|
||||
let Ok(Object::Array(ocgs)) = props.get(b"OCGs").map(|o| self.resolve(o)) else { return };
|
||||
for g in ocgs {
|
||||
let Some(d) = self.dict(g) else { continue };
|
||||
let id = g.as_reference().ok();
|
||||
// The View auto state, when it manages the group, then the configuration.
|
||||
let visible = match id {
|
||||
Some(id) if let Some(&state) = auto.get(&id) => state,
|
||||
Some(id) if off.contains(&id) => false,
|
||||
Some(id) if on.contains(&id) => true,
|
||||
_ => !base_off,
|
||||
@@ -114,6 +136,129 @@ impl<'a> Inspector<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The state the configuration's auto state (`/AS`) gives each group it manages for the View
|
||||
/// event (ISO 32000-2 §8.11.4.4, Table 101), which overrides `/BaseState`, `/ON` and `/OFF`
|
||||
/// as the document opens. Keep in step with the renderer's (vendored hayro-interpret patch
|
||||
/// (103), `apply_view_auto_state`): each usage application with `/Event /View` and `/View` in
|
||||
/// its `/Category` recommends the `/ViewState` of each group in its `/OCGs` whose `/Usage`
|
||||
/// gives one; a group is on only if all its recommendations are. Groups with none are absent.
|
||||
/// Other categories (`/Zoom`, `/User`, `/Language`) give no recommendation here.
|
||||
fn view_auto_state(&self, config: &Dictionary) -> HashMap<ObjectId, bool> {
|
||||
let mut out: HashMap<ObjectId, bool> = HashMap::new();
|
||||
let Some(applications) = config.get(b"AS").ok().and_then(|o| self.resolve(o).as_array().ok()) else { return out };
|
||||
let mut groups_left = MAX_AUTO_STATE_GROUPS;
|
||||
for application in applications.iter().take(MAX_AUTO_STATE_APPLICATIONS) {
|
||||
let Some(application) = self.dict(application) else { continue };
|
||||
if self.name(application, b"Event").as_deref() != Some("View") {
|
||||
continue;
|
||||
}
|
||||
let views = application.get(b"Category").ok().and_then(|o| self.resolve(o).as_array().ok()).is_some_and(|categories| {
|
||||
categories.iter().take(MAX_AUTO_STATE_CATEGORIES).any(|c| matches!(c, Object::Name(n) if n.as_slice() == b"View"))
|
||||
});
|
||||
if !views {
|
||||
continue;
|
||||
}
|
||||
let Some(groups) = application.get(b"OCGs").ok().and_then(|o| self.resolve(o).as_array().ok()) else { continue };
|
||||
for g in groups {
|
||||
if groups_left == 0 {
|
||||
return out;
|
||||
}
|
||||
groups_left -= 1;
|
||||
let Ok(id) = g.as_reference() else { continue };
|
||||
let state = self
|
||||
.dict(g)
|
||||
.and_then(|d| d.get(b"Usage").ok())
|
||||
.and_then(|o| self.dict(o))
|
||||
.and_then(|u| u.get(b"View").ok())
|
||||
.and_then(|o| self.dict(o))
|
||||
.and_then(|v| self.name(v, b"ViewState"));
|
||||
let on = match state.as_deref() {
|
||||
Some("ON") => true,
|
||||
Some("OFF") => false,
|
||||
_ => continue,
|
||||
};
|
||||
let entry = out.entry(id).or_insert(true);
|
||||
*entry &= on;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The Layers panel's rows: the default configuration's `/Order` (ISO 32000-2 Table 99). Its
|
||||
/// entries are groups, shown by name, and nested arrays, shown as a tree one level deeper;
|
||||
/// a nested array may start with a text string, a label that is not a group. Groups not
|
||||
/// listed aren't presented, and `/Order` defaults to the empty array in the default
|
||||
/// configuration, so a document without one presents no layers. An entry that is neither a
|
||||
/// group in `/OCGs` nor an array is skipped. Bounded by `MAX_LAYER_ORDER_*`, an indirect
|
||||
/// array is read once, so a cycle ends, and an indirect label is decoded once, however many
|
||||
/// arrays it heads.
|
||||
pub(super) fn layer_order(&self, catalog: &Dictionary, layers: &[Layer]) -> Vec<LayerRow> {
|
||||
let mut out = Vec::new();
|
||||
let Some(config) = catalog.get(b"OCProperties").ok().and_then(|o| self.dict(o)).and_then(|p| p.get(b"D").ok()).and_then(|o| self.dict(o))
|
||||
else {
|
||||
return out;
|
||||
};
|
||||
let Some(order) = config.get(b"Order").ok() else { return out };
|
||||
let index: HashMap<ObjectId, usize> = layers.iter().enumerate().map(|(i, l)| ((l.id.0, l.id.1), i)).collect();
|
||||
let mut seen = HashSet::new();
|
||||
if let Object::Reference(id) = order {
|
||||
seen.insert(*id);
|
||||
}
|
||||
if let Ok(items) = self.resolve(order).as_array() {
|
||||
self.layer_order_rows(items, 0, &index, &mut seen, &mut HashMap::new(), &mut out);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `labels` holds each indirect label already decoded: one string object can head any
|
||||
/// number of direct arrays, and each decode costs its full length before the cut.
|
||||
fn layer_order_rows(
|
||||
&self,
|
||||
items: &'a [Object],
|
||||
depth: usize,
|
||||
index: &HashMap<ObjectId, usize>,
|
||||
seen: &mut HashSet<ObjectId>,
|
||||
labels: &mut HashMap<ObjectId, String>,
|
||||
out: &mut Vec<LayerRow>,
|
||||
) {
|
||||
if depth > MAX_LAYER_ORDER_DEPTH {
|
||||
return;
|
||||
}
|
||||
for item in items {
|
||||
if out.len() >= MAX_LAYER_ORDER_ROWS {
|
||||
return;
|
||||
}
|
||||
if let Object::Reference(id) = item {
|
||||
if let Some(&layer) = index.get(id) {
|
||||
out.push(LayerRow { depth, item: LayerItem::Layer(layer) });
|
||||
continue;
|
||||
}
|
||||
// An indirect nested array, read once.
|
||||
if !seen.insert(*id) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
let Ok(nested) = self.resolve(item).as_array() else { continue };
|
||||
let rest = match nested.split_first() {
|
||||
Some((first, rest)) if let Object::String(bytes, _) = self.resolve(first) => {
|
||||
let decode = || {
|
||||
#[cfg(test)]
|
||||
LABEL_DECODES.with(|n| n.set(n.get().saturating_add(1)));
|
||||
text_string(bytes).chars().take(MAX_LAYER_LABEL_CHARS).collect::<String>()
|
||||
};
|
||||
let label = match first {
|
||||
Object::Reference(id) => labels.entry(*id).or_insert_with(decode).clone(),
|
||||
_ => decode(),
|
||||
};
|
||||
out.push(LayerRow { depth, item: LayerItem::Label(label) });
|
||||
rest
|
||||
}
|
||||
_ => nested.as_slice(),
|
||||
};
|
||||
self.layer_order_rows(rest, depth.saturating_add(1), index, seen, labels, out);
|
||||
}
|
||||
}
|
||||
|
||||
/// The default configuration's radio-button groups (`/RBGroups`) of two or more layers.
|
||||
pub(super) fn layer_groups(&self, catalog: &Dictionary) -> Vec<Vec<ObjectId>> {
|
||||
let groups = catalog
|
||||
|
||||
@@ -304,6 +304,8 @@ fn no_rotate_comments_are_shown_upright_from_their_corner_and_back() {
|
||||
fill_sign: false,
|
||||
no_rotate: true,
|
||||
points: Vec::new(),
|
||||
text_box: None,
|
||||
popup: None,
|
||||
};
|
||||
let rect = note.rect.map(f64::from);
|
||||
for rotation in [0u16, 90, 180, 270, 45] {
|
||||
@@ -769,6 +771,103 @@ trailer << /Root 1 0 R >>
|
||||
assert_eq!(layers, [("Red", true), ("Green", false), ("Blue", false)]);
|
||||
}
|
||||
|
||||
/// ISO 32000-2 Table 99 `/Order`: the Layers panel presents the groups it lists, as a tree,
|
||||
/// with nested arrays one level deeper and a leading text string as a label. Groups it
|
||||
/// doesn't list are not presented (they stay in `layers` and keep their state), and without
|
||||
/// `/Order` none are. Malformed entries are skipped; cycles and depth are bounded.
|
||||
#[test]
|
||||
fn the_layers_panel_presents_the_order_tree() {
|
||||
let rows = |order: &str, extra: &str| {
|
||||
let pdf = format!(
|
||||
"%PDF-1.7
|
||||
1 0 obj << /Type /Catalog /Pages 2 0 R /OCProperties << /OCGs [5 0 R 6 0 R 7 0 R 8 0 R] /D << /OFF [8 0 R] {order} >> >> >> endobj
|
||||
2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj
|
||||
3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] >> endobj
|
||||
5 0 obj << /Type /OCG /Name (A) >> endobj
|
||||
6 0 obj << /Type /OCG /Name (B) >> endobj
|
||||
7 0 obj << /Type /OCG /Name (C) >> endobj
|
||||
8 0 obj << /Type /OCG /Name (D) >> endobj
|
||||
9 0 obj << /Type /OCG /Name (Unlisted) >> endobj
|
||||
{extra}
|
||||
trailer << /Root 1 0 R >>
|
||||
%%EOF"
|
||||
);
|
||||
let info = inspect(Arc::new(pdf.into_bytes()), None).expect("opens");
|
||||
assert_eq!(info.layers.len(), 4, "every group in /OCGs keeps its state: {order}");
|
||||
info.layer_order
|
||||
.iter()
|
||||
.map(|r| match &r.item {
|
||||
LayerItem::Layer(i) => format!("{}{}", " ".repeat(r.depth), info.layers.get(*i).map_or("?", |l| l.name.as_str())),
|
||||
LayerItem::Label(s) => format!("{}[{s}]", " ".repeat(r.depth)),
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
// A layer with sublayers, and a group not listed (D) that isn't presented.
|
||||
assert_eq!(rows("/Order [5 0 R 6 0 R [7 0 R]]", ""), ["A", "B", " C"]);
|
||||
// A labelled collection heads its own level, with a nested array under B.
|
||||
assert_eq!(rows("/Order [5 0 R [(Set) 6 0 R [7 0 R]] 8 0 R]", ""), ["A", "[Set]", " B", " C", "D"]);
|
||||
// Without /Order, or with an empty one, nothing is presented.
|
||||
assert!(rows("", "").is_empty());
|
||||
assert!(rows("/Order []", "").is_empty());
|
||||
// An indirect /Order and nested array; a group outside /OCGs, a missing object and junk
|
||||
// are skipped.
|
||||
assert_eq!(rows("/Order 10 0 R", "10 0 obj [5 0 R 11 0 R 9 0 R 12 0 R 1 (x) /N] endobj\n11 0 obj [6 0 R] endobj"), ["A", " B"]);
|
||||
// Cycles: an array holding itself, and an /Order holding itself.
|
||||
assert_eq!(rows("/Order 10 0 R", "10 0 obj [5 0 R 10 0 R 11 0 R] endobj\n11 0 obj [6 0 R 11 0 R 10 0 R] endobj"), ["A", " B"]);
|
||||
// Nesting past the limit is cut off; a long label is cut short.
|
||||
let deep = format!("/Order [5 0 R {}6 0 R{}]", "[".repeat(40), "]".repeat(40));
|
||||
assert_eq!(rows(&deep, ""), ["A"]);
|
||||
let long = format!("/Order [[({}) 5 0 R]]", "x".repeat(1000));
|
||||
let got = rows(&long, "");
|
||||
assert_eq!(got.first().map(|s| s.len()), Some(MAX_LAYER_LABEL_CHARS + 2));
|
||||
// Many rows stop at the cap.
|
||||
let many = format!("/Order [{}]", "5 0 R ".repeat(MAX_LAYER_ORDER_ROWS + 10));
|
||||
assert_eq!(rows(&many, "").len(), MAX_LAYER_ORDER_ROWS);
|
||||
// One long indirect label heading many direct arrays is decoded once, and cut short in
|
||||
// every row.
|
||||
let shared = format!("/Order [{}]", "[13 0 R 5 0 R] ".repeat(100));
|
||||
let label = format!("13 0 obj ({}) endobj", "y".repeat(10_000));
|
||||
let before = LABEL_DECODES.with(std::cell::Cell::get);
|
||||
let got = rows(&shared, &label);
|
||||
assert_eq!(LABEL_DECODES.with(std::cell::Cell::get) - before, 1);
|
||||
assert_eq!(got.len(), 200);
|
||||
assert!(got.iter().step_by(2).all(|s| s.len() == MAX_LAYER_LABEL_CHARS + 2), "{:?}", got.first());
|
||||
}
|
||||
|
||||
/// ISO 32000-2 §8.11.4.4: the View auto state (`/AS`) decides the initial state of the groups
|
||||
/// it manages, over `/ON` and `/OFF`; the others keep the configuration's. Malformed entries
|
||||
/// are ignored.
|
||||
#[test]
|
||||
fn initial_layer_visibility_applies_the_view_auto_state() {
|
||||
let initial = |config: &str| {
|
||||
let pdf = format!(
|
||||
"%PDF-1.7
|
||||
1 0 obj << /Type /Catalog /Pages 2 0 R /OCProperties << /OCGs [5 0 R 6 0 R 7 0 R] /D {config} >> >> endobj
|
||||
2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj
|
||||
3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] >> endobj
|
||||
5 0 obj << /Type /OCG /Name (ViewOff) /Usage << /View << /ViewState /OFF >> >> >> endobj
|
||||
6 0 obj << /Type /OCG /Name (ViewOn) /Usage 8 0 R >> endobj
|
||||
7 0 obj << /Type /OCG /Name (Plain) >> endobj
|
||||
8 0 obj << /View << /ViewState /ON >> >> endobj
|
||||
9 0 obj 9 0 R endobj
|
||||
trailer << /Root 1 0 R >>
|
||||
%%EOF"
|
||||
);
|
||||
let info = inspect(Arc::new(pdf.into_bytes()), None).expect("opens");
|
||||
// Opened, so each is shown as it starts.
|
||||
info.layers.iter().inspect(|l| assert_eq!(l.initial, l.visible, "{}", l.name)).map(|l| l.initial).collect::<Vec<_>>()
|
||||
};
|
||||
let managed = "/AS [<< /Event /View /Category [/View] /OCGs [5 0 R 6 0 R 7 0 R] >>]";
|
||||
assert_eq!(initial(&format!("<< /OFF [6 0 R 7 0 R] {managed} >>")), [false, true, false]);
|
||||
assert_eq!(initial("<< /OFF [6 0 R 7 0 R] >>"), [true, false, false], "without /AS");
|
||||
assert_eq!(initial("<< /OFF [6 0 R] /AS [<< /Event /Print /Category [/View] /OCGs [5 0 R 6 0 R] >>] >>"), [true, false, true], "Print event");
|
||||
assert_eq!(initial("<< /AS [<< /Event /View /Category [/Zoom] /OCGs [5 0 R] >>] >>"), [true, true, true], "Zoom only");
|
||||
for bad in ["/AS 9 0 R", "/AS [9 0 R 1 null]", "/AS [<< /Event /View /OCGs [5 0 R] >>]", "/AS [<< /Event /View /Category [/View] /OCGs 9 0 R >>]"]
|
||||
{
|
||||
assert_eq!(initial(&format!("<< {bad} >>")), [true, true, true], "{bad}");
|
||||
}
|
||||
}
|
||||
|
||||
const ORPHAN_FIELDS: &[u8] = b"%PDF-1.7
|
||||
1 0 obj << /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >> endobj
|
||||
2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj
|
||||
@@ -1044,6 +1143,152 @@ fn a_named_attachment_leaves_its_contents_unspent() {
|
||||
assert!(matches!(&info.links[0].target, LinkTarget::Uri(u) if *u == uri));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn link_hit_test_rejects_points_outside_the_rect_before_scanning_quads() {
|
||||
// A quadrilateral reaching past `/Rect` (hand-built: `link_quads` keeps none beyond the
|
||||
// slack) shows whether the bounds gate runs before the quadrilateral scan.
|
||||
let link = Link {
|
||||
page: 0,
|
||||
index: 0,
|
||||
rect: [0.0, 0.0, 10.0, 10.0],
|
||||
quads: vec![[0.0, 0.0, 50.0, 0.0, 50.0, 10.0, 0.0, 10.0]],
|
||||
target: LinkTarget::Other("URI".into()),
|
||||
};
|
||||
assert!(link.contains(5.0, 5.0), "inside the rect and the quadrilateral");
|
||||
assert!(link.contains(10.005, 5.0), "within the slack `link_quads` accepts");
|
||||
assert!(!link.contains(30.0, 5.0), "outside the rect: no quadrilateral is scanned");
|
||||
assert!(!link.contains(f32::NAN, 5.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_link_whose_quads_have_no_area_is_active_over_its_rect() {
|
||||
let rect = [10.0, 10.0, 200.0, 30.0];
|
||||
let link = |values: &[f32]| Link {
|
||||
page: 0,
|
||||
index: 0,
|
||||
rect,
|
||||
quads: crate::link_quads(&values.iter().map(|v| Some(*v)).collect::<Vec<_>>(), rect),
|
||||
target: LinkTarget::Other("URI".into()),
|
||||
};
|
||||
let flat = [10.0, 20.0, 60.0, 20.0, 60.0, 20.0, 10.0, 20.0];
|
||||
assert!(link(&flat).contains(100.0, 25.0), "no usable quad: the whole /Rect");
|
||||
let good = [10.0, 10.0, 60.0, 10.0, 60.0, 30.0, 10.0, 30.0];
|
||||
let mixed: Vec<f32> = flat.iter().chain(good.iter()).copied().collect();
|
||||
assert!(link(&mixed).contains(30.0, 25.0), "inside the usable quad");
|
||||
assert!(!link(&mixed).contains(100.0, 25.0), "the usable quad still gates the /Rect");
|
||||
}
|
||||
|
||||
fn links_of(catalog_extra: &str, annots: &str) -> DocInfo {
|
||||
let pdf = format!(
|
||||
"%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R {catalog_extra} >> endobj\n\
|
||||
2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj\n\
|
||||
3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Annots [{annots}] >> endobj\n\
|
||||
trailer << /Root 1 0 R >>\n%%EOF"
|
||||
);
|
||||
let doc = Document::load_mem(pdf.as_bytes()).expect("loads");
|
||||
let page = PageInfo { width: 300.0, height: 300.0, crop: [0.0, 0.0, 300.0, 300.0], rotation: 0, label: String::new() };
|
||||
let mut info = DocInfo { pages: vec![page], ..Default::default() };
|
||||
Inspector::new(&doc).fill(&mut info);
|
||||
info
|
||||
}
|
||||
|
||||
fn uris(info: &DocInfo) -> Vec<String> {
|
||||
info.links.iter().map(|l| if let LinkTarget::Uri(u) = &l.target { u.clone() } else { format!("{:?}", l.target) }).collect()
|
||||
}
|
||||
|
||||
/// ISO 32000-2 §12.6.4.8, Table 211: a relative URI action is resolved against the catalog's
|
||||
/// `/URI /Base`; absolute addresses, and a base that isn't a web address, change nothing.
|
||||
#[test]
|
||||
fn relative_uri_actions_resolve_against_the_catalog_base() {
|
||||
let annots = "<< /Subtype /Link /Rect [0 0 10 10] /A << /S /URI /URI (page.html) >> >> \
|
||||
<< /Subtype /Link /Rect [0 0 10 10] /A << /S /URI /URI (javascript:alert(1)) >> >> \
|
||||
<< /Subtype /Link /Rect [0 0 10 10] /A << /S /URI /URI (https://example.org/abs) >> >>";
|
||||
let info = links_of("/URI << /Base (https://example.com/base/) >>", annots);
|
||||
assert_eq!(info.uri_base.as_deref(), Some("https://example.com/base/"));
|
||||
assert_eq!(uris(&info), ["https://example.com/base/page.html", "javascript:alert(1)", "https://example.org/abs"]);
|
||||
// An indirect URI dictionary is followed too.
|
||||
let pdf_indirect = links_of("/URI 4 0 R >> endobj\n4 0 obj << /Base (https://example.com/b/) >> endobj\n5 0 obj <<", annots);
|
||||
assert_eq!(uris(&pdf_indirect).first().map(String::as_str), Some("https://example.com/b/page.html"));
|
||||
// Without a base, or with one that isn't a web address, the address stays as written.
|
||||
assert_eq!(uris(&links_of("", annots)).first().map(String::as_str), Some("page.html"));
|
||||
for base in ["/URI << /Base (file:///C:/docs/) >>", "/URI << /Base /NotAString >>", "/URI 7", "/URI << /Base (javascript:x//) >>"] {
|
||||
assert_eq!(uris(&links_of(base, annots)).first().map(String::as_str), Some("page.html"), "{base}");
|
||||
}
|
||||
}
|
||||
|
||||
/// ISO 32000-2 §12.5.6.5, Table 176: a link is active in its `/QuadPoints`, or over its
|
||||
/// `/Rect` when they are missing, malformed or reach outside it.
|
||||
#[test]
|
||||
fn links_are_active_in_their_quad_points() {
|
||||
let link = |quads: &str| format!("<< /Subtype /Link /Rect [10 10 200 30] {quads} /A << /S /URI /URI (https://example.org/) >> >>");
|
||||
let info = links_of("", &link("/QuadPoints [10 10 60 10 60 30 10 30]"));
|
||||
let l = &info.links[0];
|
||||
assert_eq!(l.quads, vec![[10.0, 10.0, 60.0, 10.0, 60.0, 30.0, 10.0, 30.0]]);
|
||||
assert!(l.contains(30.0, 20.0), "the first word");
|
||||
assert!(!l.contains(150.0, 20.0), "inside /Rect but outside the quad");
|
||||
for fallback in [
|
||||
"",
|
||||
"/QuadPoints [10 10 60 10 60 30 10]",
|
||||
"/QuadPoints [10 10 60 10 60 30 10 (x)]",
|
||||
"/QuadPoints [10 10 260 10 260 30 10 30]",
|
||||
"/QuadPoints 5",
|
||||
] {
|
||||
let info = links_of("", &link(fallback));
|
||||
let l = &info.links[0];
|
||||
assert!(l.quads.is_empty(), "{fallback}");
|
||||
assert!(l.contains(150.0, 20.0) && !l.contains(250.0, 20.0), "{fallback}: active over /Rect");
|
||||
}
|
||||
let many = "10 10 60 10 60 30 10 30 ".repeat(crate::MAX_LINK_QUADS + 1);
|
||||
assert!(links_of("", &link(&format!("/QuadPoints [{many}]"))).links[0].quads.is_empty(), "too many quads");
|
||||
}
|
||||
|
||||
/// Links sharing one long `/QuadPoints` array, or a relative address resolved against a long
|
||||
/// `/URI /Base`, keep their copies only within `MAX_LINK_ATTACHMENT_TEXT_BYTES`, and every
|
||||
/// link is still listed.
|
||||
#[test]
|
||||
fn links_sharing_quad_points_or_a_long_base_keep_them_within_a_budget() {
|
||||
let page = PageInfo { width: 200.0, height: 200.0, crop: [0.0, 0.0, 200.0, 200.0], rotation: 0, label: String::new() };
|
||||
let fill = |catalog_extra: &str, links: &str, object5: &str| {
|
||||
let pdf = format!(
|
||||
"%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R {catalog_extra} >> endobj\n\
|
||||
2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj\n\
|
||||
3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Annots [{links}] >> endobj\n\
|
||||
5 0 obj {object5} endobj\n\
|
||||
trailer << /Root 1 0 R >>\n%%EOF"
|
||||
);
|
||||
let doc = Document::load_mem(pdf.as_bytes()).expect("loads");
|
||||
let mut info = DocInfo { pages: vec![page.clone()], ..Default::default() };
|
||||
Inspector::new(&doc).fill(&mut info);
|
||||
info
|
||||
};
|
||||
|
||||
let count = MAX_LINK_ATTACHMENT_TEXT_BYTES / (crate::MAX_LINK_QUADS * std::mem::size_of::<[f32; 8]>()) + 20;
|
||||
let quads = format!("[{}]", "10 10 60 10 60 30 10 30 ".repeat(crate::MAX_LINK_QUADS));
|
||||
let links = "<< /Subtype /Link /Rect [0 0 100 100] /QuadPoints 5 0 R /A << /S /URI /URI (https://example.org/) >> >> ".repeat(count);
|
||||
super::annotations::QUAD_ARRAYS_READ.with(|n| n.set(0));
|
||||
let info = fill("", &links, &quads);
|
||||
assert_eq!(info.links.len(), count);
|
||||
let kept: usize = info.links.iter().map(|l| std::mem::size_of_val(l.quads.as_slice())).sum();
|
||||
assert!(kept > 0 && kept <= MAX_LINK_ATTACHMENT_TEXT_BYTES, "{kept} quad bytes kept");
|
||||
assert!(info.links.iter().any(|l| l.quads.is_empty()), "past the budget a link is active over its /Rect");
|
||||
// Review on #4474: the shared array is read once for each link it fits, and once more to find
|
||||
// that it no longer does; not again for every link after that.
|
||||
let fitted = info.links.iter().filter(|l| !l.quads.is_empty()).count();
|
||||
let read = super::annotations::QUAD_ARRAYS_READ.with(std::cell::Cell::get);
|
||||
assert_eq!(read, fitted + 1, "{read} reads for {fitted} links within the budget, of {count}");
|
||||
|
||||
let base = format!("https://example.com/{}/", "b".repeat(crate::MAX_URI_BASE_BYTES - 32));
|
||||
let count = MAX_LINK_ATTACHMENT_TEXT_BYTES / base.len() + 20;
|
||||
let links = "<< /Subtype /Link /Rect [0 0 1 1] /A 5 0 R >> ".repeat(count);
|
||||
let info = fill(&format!("/URI << /Base ({base}) >>"), &links, "<< /S /URI /URI (p.html) >>");
|
||||
assert_eq!(info.links.len(), count);
|
||||
let addresses = uris(&info);
|
||||
let kept: usize = addresses.iter().map(String::len).sum();
|
||||
assert!(kept <= MAX_LINK_ATTACHMENT_TEXT_BYTES, "{kept} address bytes kept");
|
||||
assert_eq!(addresses.first(), Some(&format!("{base}p.html")));
|
||||
assert!(addresses.iter().any(|u| u == "p.html"), "past the budget a link keeps its raw address");
|
||||
}
|
||||
|
||||
/// Embedded files whose name-tree keys share one long string keep it, as key and as name, only
|
||||
/// within `MAX_LINK_ATTACHMENT_TEXT_BYTES`.
|
||||
#[test]
|
||||
@@ -1999,6 +2244,39 @@ fn carriage_returns_in_comment_text_become_line_breaks() {
|
||||
assert_eq!(info.annotations[0].contents.as_deref(), Some("one\n\ntwo\nthree"));
|
||||
}
|
||||
|
||||
/// A comment's pop-up (`/Popup`) is read with its place and state; one without reads none.
|
||||
#[test]
|
||||
fn a_comments_pop_up_is_read_with_its_place_and_state() {
|
||||
let bytes = b"%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\n3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 200 300] /Annots [4 0 R 5 0 R 6 0 R] >> endobj\n4 0 obj << /Type /Annot /Subtype /Text /Rect [20 260 40 280] /Contents (Hi) /Popup 5 0 R /Open true >> endobj\n5 0 obj << /Type /Annot /Subtype /Popup /Rect [190 160 50 280] /Parent 4 0 R /Open true >> endobj\n6 0 obj << /Type /Annot /Subtype /Square /Rect [10 10 60 60] >> endobj\ntrailer << /Root 1 0 R >>\n%%EOF\n";
|
||||
let info = inspect(Arc::new(bytes.to_vec()), None).expect("opens");
|
||||
let note = info.annotations.iter().find(|a| a.subtype == "Text").expect("the note");
|
||||
assert_eq!(note.popup, Some(Popup { rect: [50.0, 160.0, 190.0, 280.0], open: true }), "normalised, and open");
|
||||
let square = info.annotations.iter().find(|a| a.subtype == "Square").expect("the square");
|
||||
assert_eq!(square.popup, None);
|
||||
assert!(info.annotations.iter().all(|a| a.subtype != "Popup"), "the pop-up is not a comment of its own");
|
||||
|
||||
// #2137 review: a /Popup naming another annotation, a pop-up of another comment, or one
|
||||
// whose /Parent isn't a reference isn't this comment's pop-up; one without /Parent is.
|
||||
for (target, extra, own) in [
|
||||
("6 0 R", "", false),
|
||||
("7 0 R", "7 0 obj << /Type /Annot /Subtype /Popup /Rect [0 0 50 50] /Parent 6 0 R >> endobj\n", false),
|
||||
("7 0 R", "7 0 obj << /Type /Annot /Subtype /Popup /Rect [0 0 50 50] /Parent << >> >> endobj\n", false),
|
||||
("7 0 R", "7 0 obj << /Type /Annot /Subtype /Popup /Rect [0 0 50 50] >> endobj\n", true),
|
||||
] {
|
||||
let text = String::from_utf8_lossy(bytes).replace("/Popup 5 0 R", &format!("/Popup {target}")).replace("trailer", &format!("{extra}trailer"));
|
||||
let info = inspect(Arc::new(text.into_bytes()), None).expect("opens");
|
||||
let note = info.annotations.iter().find(|a| a.subtype == "Text").expect("the note");
|
||||
assert_eq!(note.popup.is_some(), own, "/Popup {target} {extra}");
|
||||
}
|
||||
|
||||
// #2137 review: /Annots may list the note through an object that is only a reference to
|
||||
// it; its pop-up's /Parent names the note itself, and is still its own.
|
||||
let text = String::from_utf8_lossy(bytes).replace("/Annots [4 0 R", "/Annots [8 0 R").replace("trailer", "8 0 obj 4 0 R endobj\ntrailer");
|
||||
let info = inspect(Arc::new(text.into_bytes()), None).expect("opens");
|
||||
let note = info.annotations.iter().find(|a| a.subtype == "Text").expect("the note");
|
||||
assert_eq!(note.popup, Some(Popup { rect: [50.0, 160.0, 190.0, 280.0], open: true }), "listed through 8 0 R");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dates_are_prettified() {
|
||||
assert_eq!(pretty_date("D:20260930104512-04'00'"), "2026-09-30 10:45");
|
||||
@@ -2020,6 +2298,186 @@ trailer << /Root 1 0 R >>
|
||||
assert!((p.height - 5493.54).abs() < 0.1, "height expected ~5493.54, got {}", p.height);
|
||||
}
|
||||
|
||||
mod group_tests {
|
||||
use crate::inspect::{Annotation, MAX_GROUP_DEPTH, group_primaries, link_replies};
|
||||
|
||||
/// The annotation at `/Annots` position `index` of page 0, whose `/IRT` points at position
|
||||
/// `parent`, with `/RT /Group` when `grouped`.
|
||||
fn annot(index: usize, parent: Option<usize>, grouped: bool) -> Annotation {
|
||||
Annotation {
|
||||
page: 0,
|
||||
subtype: "Circle".into(),
|
||||
author: None,
|
||||
contents: None,
|
||||
modified: None,
|
||||
name: Some(index.to_string()),
|
||||
in_reply_to: parent.map(|p| p.to_string()),
|
||||
parent: parent.map(|p| (0, p)),
|
||||
grouped,
|
||||
rect: [0.0; 4],
|
||||
color: None,
|
||||
index,
|
||||
state: None,
|
||||
quads: Vec::new(),
|
||||
locked: false,
|
||||
intent: None,
|
||||
fill_sign: false,
|
||||
no_rotate: false,
|
||||
points: Vec::new(),
|
||||
text_box: None,
|
||||
popup: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// `all` with its reply links settled, as both comment readers list it.
|
||||
fn listed(mut all: Vec<Annotation>) -> Vec<Annotation> {
|
||||
link_replies(&mut all);
|
||||
all
|
||||
}
|
||||
|
||||
/// ISO 32000-2 §12.5.6.2: a subordinate's primary is the annotation its `/IRT` points at,
|
||||
/// past any other subordinate; a reply is no subordinate. A loop, or an `/IRT` to nothing
|
||||
/// listed, leaves a comment of its own (as `link_replies` leaves such a reply), and an
|
||||
/// over-long chain ends.
|
||||
#[test]
|
||||
fn group_primaries_follow_irt_to_the_first_non_subordinate() {
|
||||
let all = listed(vec![
|
||||
annot(0, None, false), // top
|
||||
annot(1, Some(0), true), // mid
|
||||
annot(2, Some(1), true), // low
|
||||
annot(3, Some(0), false), // a reply
|
||||
annot(4, Some(5), true), // a loop
|
||||
annot(5, Some(4), true), // of two
|
||||
annot(6, Some(6), true), // itself
|
||||
annot(7, Some(99), true), // nothing listed
|
||||
annot(8, Some(3), true), // grouped with the reply
|
||||
]);
|
||||
assert_eq!(group_primaries(&all), [None, Some(0), Some(0), None, None, None, None, None, Some(3)]);
|
||||
assert!(all.iter().skip(4).take(4).all(Annotation::is_comment), "{all:?}");
|
||||
// A chain longer than the cap has no primary; one within it does, whether the reply links
|
||||
// are settled first or not.
|
||||
for (len, found) in [(MAX_GROUP_DEPTH - 1, true), (MAX_GROUP_DEPTH + 1, false)] {
|
||||
let mut chain = vec![annot(0, None, false)];
|
||||
chain.extend((1..=len).map(|i| annot(i, Some(i - 1), true)));
|
||||
assert_eq!(group_primaries(&chain).last().copied().flatten().is_some(), found, "{len}");
|
||||
assert_eq!(group_primaries(&listed(chain)).last().copied().flatten().is_some(), found, "{len}, listed");
|
||||
}
|
||||
}
|
||||
|
||||
/// `group_primaries` is public and may be handed links `link_replies` has not settled: a loop
|
||||
/// of subordinates (each other's `/IRT`, or its own) still ends, within `MAX_GROUP_DEPTH`
|
||||
/// steps, with no primary.
|
||||
#[test]
|
||||
fn group_primaries_end_on_an_unsettled_loop() {
|
||||
let all = vec![annot(0, Some(1), true), annot(1, Some(0), true), annot(2, Some(2), true), annot(3, None, false)];
|
||||
assert_eq!(group_primaries(&all), [None, None, None, None]);
|
||||
}
|
||||
|
||||
fn with(mut a: Annotation, subtype: &str, t: Option<&str>) -> Annotation {
|
||||
a.subtype = subtype.into();
|
||||
a.contents = t.map(Into::into);
|
||||
a
|
||||
}
|
||||
|
||||
/// A StrikeOut primary with no text lists its first Caret subordinate's (earlier Replace
|
||||
/// Text groups kept the replacement on the caret only); a primary's own text always wins, a
|
||||
/// subordinate of another type lends nothing, and a primary of another type borrows nothing
|
||||
/// (ISO 32000-2 §12.5.6.2: the group's text is the primary's).
|
||||
#[test]
|
||||
fn a_primary_without_text_lists_its_carets() {
|
||||
let mut all = listed(vec![
|
||||
with(annot(0, None, false), "StrikeOut", None),
|
||||
with(annot(1, Some(0), true), "Caret", Some("red")),
|
||||
with(annot(2, Some(0), true), "Caret", Some("second")),
|
||||
with(annot(3, None, false), "Caret", Some("kept")),
|
||||
with(annot(4, Some(3), true), "Caret", Some("ignored")),
|
||||
with(annot(5, Some(0), false), "Text", Some("a reply")),
|
||||
with(annot(6, None, false), "StrikeOut", None),
|
||||
with(annot(7, Some(6), true), "Circle", Some("not lent")),
|
||||
with(annot(8, None, false), "Square", None),
|
||||
with(annot(9, Some(8), true), "Caret", Some("not borrowed")),
|
||||
]);
|
||||
super::fill_group_text(&mut all);
|
||||
let shown: Vec<Option<&str>> = all.iter().map(|a| a.contents.as_deref()).collect();
|
||||
assert_eq!(
|
||||
shown,
|
||||
[
|
||||
Some("red"),
|
||||
Some("red"),
|
||||
Some("second"),
|
||||
Some("kept"),
|
||||
Some("ignored"),
|
||||
Some("a reply"),
|
||||
None,
|
||||
Some("not lent"),
|
||||
None,
|
||||
Some("not borrowed"),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
/// Review on #4358: an empty caret ahead of one with text lends nothing, so the primary lists
|
||||
/// the replacement rather than nothing.
|
||||
#[test]
|
||||
fn an_empty_caret_does_not_hide_the_next_carets_text() {
|
||||
let mut all = listed(vec![
|
||||
with(annot(0, None, false), "StrikeOut", None),
|
||||
with(annot(1, Some(0), true), "Caret", Some("")),
|
||||
with(annot(2, Some(0), true), "Caret", Some("new words")),
|
||||
]);
|
||||
super::fill_group_text(&mut all);
|
||||
assert_eq!(all[0].contents.as_deref(), Some("new words"));
|
||||
}
|
||||
|
||||
/// Many groups each get their own caret's text (one map lookup per caret, not a scan of the
|
||||
/// groups seen so far).
|
||||
#[test]
|
||||
fn many_groups_each_list_their_own_caret() {
|
||||
const N: usize = 20_000;
|
||||
let mut all = Vec::with_capacity(2 * N);
|
||||
for i in 0..N {
|
||||
all.push(with(annot(i, None, false), "StrikeOut", None));
|
||||
}
|
||||
// Carets in reverse order, so a primary's caret is far from it in the list.
|
||||
for (k, i) in (0..N).rev().enumerate() {
|
||||
all.push(with(annot(N + k, Some(i), true), "Caret", Some(&format!("t{i}"))));
|
||||
}
|
||||
let mut all = listed(all);
|
||||
super::fill_group_text(&mut all);
|
||||
for (i, a) in all.iter().take(N).enumerate() {
|
||||
assert_eq!(a.contents.as_deref(), Some(format!("t{i}").as_str()), "{i}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// #2137 review: a pop-up without a `/Rect` of four numbers reads as no pop-up, as
|
||||
/// `pdfcraft_annot::summaries` reads it, so the two lists of comments agree.
|
||||
#[test]
|
||||
fn a_pop_up_without_a_four_number_rect_is_none() {
|
||||
let bytes = "%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\n3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 200 300] /Annots [4 0 R 5 0 R] >> endobj\n4 0 obj << /Type /Annot /Subtype /Text /Rect [20 260 40 280] /Contents (Hi) /Popup 5 0 R >> endobj\n5 0 obj << /Type /Annot /Subtype /Popup RECT /Parent 4 0 R /Open true >> endobj\ntrailer << /Root 1 0 R >>\n%%EOF\n";
|
||||
for (rect, read) in [("", false), ("/Rect [0 0 50]", false), ("/Rect (box)", false), ("/Rect [0 0 50 /x]", false), ("/Rect [0 0 50 60]", true)] {
|
||||
let info = inspect(Arc::new(bytes.replace("RECT", rect).into_bytes()), None).expect("opens");
|
||||
let note = info.annotations.iter().find(|a| a.subtype == "Text").expect("the note");
|
||||
assert_eq!(note.popup.is_some(), read, "{rect:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// #2137 review: a pop-up `/Rect` with its corners reversed reads with them in order (ISO
|
||||
/// 32000-2 §7.9.5), and one with a number too large for `f32` reads as no pop-up, as
|
||||
/// `pdfcraft_annot::summaries` reads both.
|
||||
#[test]
|
||||
fn a_pop_up_rect_with_reversed_corners_is_put_in_order_and_a_huge_one_is_none() {
|
||||
let bytes = "%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\n3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 200 300] /Annots [4 0 R 5 0 R] >> endobj\n4 0 obj << /Type /Annot /Subtype /Text /Rect [20 260 40 280] /Contents (Hi) /Popup 5 0 R >> endobj\n5 0 obj << /Type /Annot /Subtype /Popup /Rect RECT /Parent 4 0 R /Open true >> endobj\ntrailer << /Root 1 0 R >>\n%%EOF\n";
|
||||
let popup = |rect: &str| {
|
||||
let info = inspect(Arc::new(bytes.replace("RECT", rect).into_bytes()), None).expect("opens");
|
||||
info.annotations.iter().find(|a| a.subtype == "Text").expect("the note").popup.map(|p| p.rect)
|
||||
};
|
||||
assert_eq!(popup("[150 200 50 100]"), Some([50.0, 100.0, 150.0, 200.0]), "reversed");
|
||||
let huge = format!("1{}", "0".repeat(40));
|
||||
assert_eq!(popup(&format!("[0 0 {huge} 100]")), None, "a number past f32");
|
||||
assert_eq!(popup(&format!("[0 0 {huge}.0 100]")), None, "a real past f32");
|
||||
}
|
||||
|
||||
/// Inspection keeps every object it reads, converted, for as long as it runs, and nothing it
|
||||
/// reports comes from `/PieceInfo`. InDesign writes kilobytes of that private data into every
|
||||
/// page, and a 1,412-page book held over a gigabyte of it (#5873). It is left out of what
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
mod inspect;
|
||||
mod link_area;
|
||||
mod pixels;
|
||||
mod raster;
|
||||
mod reading;
|
||||
@@ -18,10 +19,11 @@ pub mod text;
|
||||
pub mod transition;
|
||||
|
||||
pub use inspect::{
|
||||
Annotation, Attachment, AttachmentSource, DestView, DocInfo, Field, FieldKind, FontInfo, Layer, LayerOp, Link, LinkTarget, OutlineItem, PageInfo,
|
||||
PageTransition, RemoteDestination, ReviewStates, TransitionStyle, Xfa, attachment_data, check_pages, inspect, link_replies, pretty_date,
|
||||
thread_tops,
|
||||
Annotation, Attachment, AttachmentSource, DestView, DocInfo, Field, FieldKind, FontInfo, Layer, LayerItem, LayerOp, LayerRow, Link, LinkTarget,
|
||||
MAX_GROUP_DEPTH, OutlineItem, PageInfo, PageTransition, Popup, RemoteDestination, ReviewStates, TransitionStyle, Xfa, attachment_data,
|
||||
check_pages, fill_group_text, group_primaries, inspect, link_replies, 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;
|
||||
pub use raster::{
|
||||
MAX_PIXELS, MAX_SIDE, PRINT_TAG, PageRenderer, RenderConfig, RenderPool, RenderRequest, RenderStats, RenderWarning, RenderedPage, RequestKind,
|
||||
|
||||
@@ -0,0 +1,310 @@
|
||||
//! Where a link annotation is active, and where its URI action goes.
|
||||
//!
|
||||
//! - ISO 32000-2 §12.5.6.5, Table 176: a link's `/QuadPoints` are "the region in which the link
|
||||
//! should be activated"; when they are absent, not understood, or any coordinate lies outside
|
||||
//! `/Rect`, the activation region is `/Rect`.
|
||||
//! - ISO 32000-2 §12.6.4.8, Table 211: the catalog's `/URI /Base` is "the base URI that shall be
|
||||
//! used in resolving relative URI references" in URI actions.
|
||||
|
||||
/// The most quadrilaterals a link's `/QuadPoints` may give before they are not used (the link is
|
||||
/// then active over its `/Rect`, as for an array that isn't understood).
|
||||
pub const MAX_LINK_QUADS: usize = 1024;
|
||||
|
||||
/// The longest `/URI /Base` that is used. A longer base would only produce an address the link
|
||||
/// check refuses as too long, so it is ignored.
|
||||
pub const MAX_URI_BASE_BYTES: usize = 8192;
|
||||
|
||||
/// How far (in points) a quadrilateral's corner may lie outside `/Rect` and still count as inside:
|
||||
/// rounding in the writer, not a different region.
|
||||
pub(crate) const RECT_SLACK: f32 = 0.01;
|
||||
|
||||
/// A link's quadrilaterals from its `/QuadPoints` values (`None` for an entry that isn't a
|
||||
/// number), or an empty list when the link is active over its whole `/Rect`: no values, a count
|
||||
/// that isn't a multiple of 8, more than [`MAX_LINK_QUADS`], a value that isn't a finite number,
|
||||
/// a corner outside `rect` (normalized, `[x0, y0, x1, y1]`), or no quadrilateral that encloses
|
||||
/// an area.
|
||||
///
|
||||
/// A quadrilateral no thicker than [`RECT_SLACK`] (its corners on one line, give or take
|
||||
/// rounding) is left out: it adds nothing to the region the others make, and kept alone it would
|
||||
/// leave the link active nowhere. When every quadrilateral is like that, the array is not one
|
||||
/// that can be used and the link is active over `/Rect`.
|
||||
pub fn link_quads(values: &[Option<f32>], rect: [f32; 4]) -> Vec<[f32; 8]> {
|
||||
if values.is_empty() || !values.len().is_multiple_of(8) || values.len() / 8 > MAX_LINK_QUADS {
|
||||
return Vec::new();
|
||||
}
|
||||
let mut numbers = Vec::with_capacity(values.len());
|
||||
for v in values {
|
||||
match v {
|
||||
Some(n) if n.is_finite() => numbers.push(*n),
|
||||
_ => return Vec::new(),
|
||||
}
|
||||
}
|
||||
let [x0, y0, x1, y1] = rect;
|
||||
let inside = numbers
|
||||
.as_chunks::<2>()
|
||||
.0
|
||||
.iter()
|
||||
.all(|[x, y]| *x >= x0 - RECT_SLACK && *x <= x1 + RECT_SLACK && *y >= y0 - RECT_SLACK && *y <= y1 + RECT_SLACK);
|
||||
if !inside {
|
||||
return Vec::new();
|
||||
}
|
||||
numbers.as_chunks::<8>().0.iter().filter(|q| encloses_area(q)).copied().collect()
|
||||
}
|
||||
|
||||
/// Whether the quadrilateral `q` (`x1 y1 … x4 y4`, finite) is thicker than [`RECT_SLACK`]: one of
|
||||
/// the four triangles its corners make (whose union [`quad_contains`] tests) is more than that
|
||||
/// high over its longest side. Worked in `f64`, where products of finite `f32` values neither
|
||||
/// overflow nor become NaN.
|
||||
fn encloses_area(q: &[f32; 8]) -> bool {
|
||||
let p = [[q[0], q[1]], [q[2], q[3]], [q[4], q[5]], [q[6], q[7]]].map(|[x, y]| [f64::from(x), f64::from(y)]);
|
||||
let len = |u: [f64; 2], v: [f64; 2]| (v[0] - u[0]).hypot(v[1] - u[1]);
|
||||
[[0, 1, 2], [0, 1, 3], [0, 2, 3], [1, 2, 3]].iter().any(|&[a, b, c]| match (p.get(a), p.get(b), p.get(c)) {
|
||||
(Some(&a), Some(&b), Some(&c)) => {
|
||||
// Twice the triangle's area is its longest side times its height over that side.
|
||||
let twice_area = ((b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])).abs();
|
||||
let longest = len(a, b).max(len(b, c)).max(len(c, a));
|
||||
twice_area > f64::from(RECT_SLACK) * longest
|
||||
}
|
||||
_ => false,
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether the point `(x, y)` lies in the quadrilateral `q` (`x1 y1 … x4 y4`), edges included.
|
||||
/// Writers disagree on the corners' order (the specification says counterclockwise, text-markup
|
||||
/// writers often go top-left, top-right, bottom-left, bottom-right), so the quadrilateral is taken
|
||||
/// as the area its four corners enclose: the union of the four triangles they make.
|
||||
pub fn quad_contains(q: &[f32; 8], x: f32, y: f32) -> bool {
|
||||
if !(x.is_finite() && y.is_finite()) {
|
||||
return false;
|
||||
}
|
||||
let p = [[q[0], q[1]], [q[2], q[3]], [q[4], q[5]], [q[6], q[7]]];
|
||||
[[0, 1, 2], [0, 1, 3], [0, 2, 3], [1, 2, 3]].iter().any(|&[a, b, c]| match (p.get(a), p.get(b), p.get(c)) {
|
||||
(Some(a), Some(b), Some(c)) => triangle_contains(*a, *b, *c, [x, y]),
|
||||
_ => false,
|
||||
})
|
||||
}
|
||||
|
||||
/// Worked in `f64`, like [`encloses_area`]: in `f32` the cross products of far-apart finite
|
||||
/// corners overflow to infinity and their differences to NaN, which no sign test rejects.
|
||||
fn triangle_contains(a: [f32; 2], b: [f32; 2], c: [f32; 2], p: [f32; 2]) -> bool {
|
||||
let [a, b, c, p] = [a, b, c, p].map(|[x, y]| [f64::from(x), f64::from(y)]);
|
||||
let cross = |o: [f64; 2], u: [f64; 2], v: [f64; 2]| (u[0] - o[0]) * (v[1] - o[1]) - (u[1] - o[1]) * (v[0] - o[0]);
|
||||
// A triangle with no area holds no point (it would otherwise hold its whole line).
|
||||
if cross(a, b, c) == 0.0 {
|
||||
return false;
|
||||
}
|
||||
let (d1, d2, d3) = (cross(a, b, p), cross(b, c, p), cross(c, a, p));
|
||||
let negative = d1 < 0.0 || d2 < 0.0 || d3 < 0.0;
|
||||
let positive = d1 > 0.0 || d2 > 0.0 || d3 > 0.0;
|
||||
!(negative && positive)
|
||||
}
|
||||
|
||||
/// Whether `s` begins with an RFC 3986 scheme (`ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) ":"`),
|
||||
/// so it is an absolute URI rather than a relative reference.
|
||||
fn has_scheme(s: &str) -> bool {
|
||||
s.split_once(':').is_some_and(|(scheme, _)| {
|
||||
scheme.chars().next().is_some_and(|c| c.is_ascii_alphabetic())
|
||||
&& scheme.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'))
|
||||
})
|
||||
}
|
||||
|
||||
/// The address a URI action goes to when the document's catalog gives `base` (`/URI /Base`):
|
||||
/// a relative reference (`page.html`, `../a/`, `?q=1`, `//host/x`) resolved against it by
|
||||
/// RFC 3986 §5 (the WHATWG URL rules, which the browser applies too). `None` when the address is
|
||||
/// used as written: it already has a scheme (`https:`, `mailto:`, `javascript:`…), there is no
|
||||
/// usable base, or the result wouldn't be a web address.
|
||||
///
|
||||
/// Only a web (`http`, `https`) base is used, and the result must keep the base's scheme, so a
|
||||
/// base never turns a relative link into a `file:`, `javascript:` or other address. An address
|
||||
/// with control characters or whitespace other than a plain space is left as written, since the
|
||||
/// URL rules would drop them and read what is left (`java\nscript:`) differently. Either way the
|
||||
/// address still goes through the same check and confirmation as any other link.
|
||||
pub fn resolve_uri(base: Option<&str>, raw: &str) -> Option<String> {
|
||||
let reference = raw.trim();
|
||||
let base = base?.trim();
|
||||
if reference.is_empty() || base.len() > MAX_URI_BASE_BYTES || has_scheme(reference) {
|
||||
return None;
|
||||
}
|
||||
let hidden = |s: &str| s.chars().any(|c| c.is_control() || (c.is_whitespace() && c != ' '));
|
||||
// The base must name its host as written (`https://host/…`): the URL rules would also accept
|
||||
// `https:///host/` or `https:host/`, which no link check reads as a web address.
|
||||
let names_host = base.split_once("://").is_some_and(|(_, rest)| !rest.starts_with(['/', '\\']));
|
||||
if hidden(reference) || hidden(base) || !names_host {
|
||||
return None;
|
||||
}
|
||||
let base = url::Url::parse(base).ok()?;
|
||||
if !matches!(base.scheme(), "http" | "https") || base.host().is_none() {
|
||||
return None;
|
||||
}
|
||||
let resolved = base.join(reference).ok()?;
|
||||
(resolved.scheme() == base.scheme() && resolved.host().is_some()).then(|| resolved.to_string())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const BASE: &str = "https://example.com/base/";
|
||||
|
||||
#[test]
|
||||
fn relative_references_resolve_against_the_base() {
|
||||
let r = |raw: &str| resolve_uri(Some(BASE), raw);
|
||||
assert_eq!(r("page.html").as_deref(), Some("https://example.com/base/page.html"));
|
||||
assert_eq!(r(" page.html ").as_deref(), Some("https://example.com/base/page.html"), "trimmed like any link");
|
||||
assert_eq!(r("../up.html").as_deref(), Some("https://example.com/up.html"));
|
||||
assert_eq!(r("/root.html").as_deref(), Some("https://example.com/root.html"));
|
||||
assert_eq!(r("?q=1").as_deref(), Some("https://example.com/base/?q=1"));
|
||||
assert_eq!(r("#part").as_deref(), Some("https://example.com/base/#part"));
|
||||
assert_eq!(r("a/b:c").as_deref(), Some("https://example.com/base/a/b:c"), "a colon after a slash is no scheme");
|
||||
// A network-path reference names its own host; the confirmation shows that host.
|
||||
assert_eq!(r("//other.example/x").as_deref(), Some("https://other.example/x"));
|
||||
assert_eq!(resolve_uri(Some("http://example.com/dir/file.pdf"), "next.pdf").as_deref(), Some("http://example.com/dir/next.pdf"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn absolute_addresses_and_missing_bases_are_used_as_written() {
|
||||
for raw in ["https://example.org/x", "HTTP://example.org", "mailto:a@example.org", "javascript:alert(1)", "file:///etc/passwd", "C:\\x.pdf"] {
|
||||
assert_eq!(resolve_uri(Some(BASE), raw), None, "{raw}");
|
||||
}
|
||||
assert_eq!(resolve_uri(None, "page.html"), None);
|
||||
assert_eq!(resolve_uri(Some(BASE), ""), None);
|
||||
assert_eq!(resolve_uri(Some(BASE), " "), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_base_that_is_not_a_web_address_is_not_used() {
|
||||
for base in [
|
||||
"file:///C:/docs/",
|
||||
"javascript:alert(1)//",
|
||||
"data:text/html,x/",
|
||||
"mailto:a@example.org",
|
||||
"smb://server/share/",
|
||||
"relative/base/",
|
||||
"",
|
||||
"https://",
|
||||
"https:///nohost/",
|
||||
"https:nohost/",
|
||||
"https:\\\\nohost/",
|
||||
"https://exa\nmple.com/",
|
||||
] {
|
||||
assert_eq!(resolve_uri(Some(base), "page.html"), None, "{base:?}");
|
||||
}
|
||||
let long = format!("https://example.com/{}/", "a".repeat(MAX_URI_BASE_BYTES));
|
||||
assert_eq!(resolve_uri(Some(&long), "page.html"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hidden_characters_never_make_a_scheme() {
|
||||
// The URL rules drop tabs and newlines, which would read these as `javascript:`.
|
||||
for raw in ["java\nscript:alert(1)", "java\tscript:alert(1)", "\u{0}javascript:alert(1)", "page\u{2028}.html"] {
|
||||
assert_eq!(resolve_uri(Some(BASE), raw), None, "{raw:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quads_inside_the_rect_are_used() {
|
||||
let rect = [10.0, 10.0, 200.0, 30.0];
|
||||
let q = [10.0, 10.0, 60.0, 10.0, 60.0, 30.0, 10.0, 30.0].map(Some);
|
||||
assert_eq!(link_quads(&q, rect), vec![[10.0, 10.0, 60.0, 10.0, 60.0, 30.0, 10.0, 30.0]]);
|
||||
let two: Vec<Option<f32>> = q.iter().chain(q.iter()).copied().collect();
|
||||
assert_eq!(link_quads(&two, rect).len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quads_that_are_not_understood_fall_back_to_the_rect() {
|
||||
let rect = [10.0, 10.0, 200.0, 30.0];
|
||||
let good = [10.0, 10.0, 60.0, 10.0, 60.0, 30.0, 10.0, 30.0];
|
||||
assert!(link_quads(&[], rect).is_empty());
|
||||
assert!(link_quads(&good[..7].iter().copied().map(Some).collect::<Vec<_>>(), rect).is_empty(), "not a multiple of 8");
|
||||
let mut odd: Vec<Option<f32>> = good.map(Some).to_vec();
|
||||
odd.push(Some(1.0));
|
||||
assert!(link_quads(&odd, rect).is_empty());
|
||||
let mut not_number = good.map(Some);
|
||||
not_number[3] = None;
|
||||
assert!(link_quads(¬_number, rect).is_empty());
|
||||
let mut nan = good.map(Some);
|
||||
nan[0] = Some(f32::NAN);
|
||||
assert!(link_quads(&nan, rect).is_empty());
|
||||
// A /Rect too large for f32 would hold an infinite corner.
|
||||
let mut infinite = good.map(Some);
|
||||
infinite[2] = Some(f32::INFINITY);
|
||||
assert!(link_quads(&infinite, [f32::NEG_INFINITY, f32::NEG_INFINITY, f32::INFINITY, f32::INFINITY]).is_empty());
|
||||
let mut outside = good.map(Some);
|
||||
outside[2] = Some(250.0);
|
||||
assert!(link_quads(&outside, rect).is_empty(), "a corner outside /Rect");
|
||||
let mut below = good.map(Some);
|
||||
below[1] = Some(9.0);
|
||||
assert!(link_quads(&below, rect).is_empty(), "a corner below /Rect");
|
||||
let too_many: Vec<Option<f32>> = std::iter::repeat_n(good.map(Some), MAX_LINK_QUADS + 1).flatten().collect();
|
||||
assert!(link_quads(&too_many, rect).is_empty());
|
||||
let most: Vec<Option<f32>> = std::iter::repeat_n(good.map(Some), MAX_LINK_QUADS).flatten().collect();
|
||||
assert_eq!(link_quads(&most, rect).len(), MAX_LINK_QUADS);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quads_with_no_area_are_left_out() {
|
||||
let rect = [10.0, 10.0, 200.0, 30.0];
|
||||
let good = [10.0, 10.0, 60.0, 10.0, 60.0, 30.0, 10.0, 30.0];
|
||||
// Corners on one line, all at one point, and a sliver thinner than the slack.
|
||||
let line = [10.0, 20.0, 60.0, 20.0, 60.0, 20.0, 10.0, 20.0];
|
||||
let point = [30.0, 20.0, 30.0, 20.0, 30.0, 20.0, 30.0, 20.0];
|
||||
let sliver = [10.0, 20.0, 60.0, 20.0, 60.0, 20.005, 10.0, 20.005];
|
||||
for flat in [line, point, sliver] {
|
||||
assert!(link_quads(&flat.map(Some), rect).is_empty(), "{flat:?} alone: active over /Rect");
|
||||
let mixed: Vec<Option<f32>> = flat.iter().chain(good.iter()).map(|v| Some(*v)).collect();
|
||||
assert_eq!(link_quads(&mixed, rect), vec![good], "{flat:?} beside a usable quad");
|
||||
}
|
||||
// Thicker than the slack is a region, however thin.
|
||||
let thin = [10.0, 20.0, 60.0, 20.0, 60.0, 20.05, 10.0, 20.05];
|
||||
assert_eq!(link_quads(&thin.map(Some), rect), vec![thin]);
|
||||
// A triangle (two corners shared) still encloses an area.
|
||||
let triangle = [10.0, 10.0, 60.0, 10.0, 60.0, 30.0, 60.0, 30.0];
|
||||
assert_eq!(link_quads(&triangle.map(Some), rect), vec![triangle]);
|
||||
// The largest finite values neither overflow nor turn to NaN.
|
||||
let all = [f32::MIN, f32::MIN, f32::MAX, f32::MAX];
|
||||
let huge = [f32::MIN, f32::MIN, f32::MAX, f32::MIN, f32::MAX, f32::MAX, f32::MIN, f32::MAX];
|
||||
assert_eq!(link_quads(&huge.map(Some), all), vec![huge]);
|
||||
let huge_line = [f32::MIN, f32::MIN, f32::MAX, f32::MAX, f32::MAX, f32::MAX, f32::MIN, f32::MIN];
|
||||
assert!(link_quads(&huge_line.map(Some), all).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_quad_holds_its_area_in_any_corner_order() {
|
||||
// Counterclockwise from the bottom left, as the specification writes them.
|
||||
let ccw = [10.0, 10.0, 60.0, 10.0, 60.0, 30.0, 10.0, 30.0];
|
||||
// Top-left, top-right, bottom-left, bottom-right, as text-markup writers often do.
|
||||
let z = [10.0, 30.0, 60.0, 30.0, 10.0, 10.0, 60.0, 10.0];
|
||||
for q in [ccw, z] {
|
||||
assert!(quad_contains(&q, 30.0, 20.0));
|
||||
assert!(quad_contains(&q, 10.0, 10.0), "corners count");
|
||||
assert!(quad_contains(&q, 60.0, 20.0), "edges count");
|
||||
assert!(!quad_contains(&q, 100.0, 20.0), "right of the quad");
|
||||
assert!(!quad_contains(&q, 30.0, 31.0), "above the quad");
|
||||
assert!(!quad_contains(&q, 9.0, 20.0), "left of the quad");
|
||||
assert!(!quad_contains(&q, 30.0, 9.0), "below the quad");
|
||||
}
|
||||
// A tilted quad: the corner of its bounding box is outside it.
|
||||
let diamond = [50.0, 0.0, 100.0, 50.0, 50.0, 100.0, 0.0, 50.0];
|
||||
assert!(quad_contains(&diamond, 50.0, 50.0));
|
||||
assert!(!quad_contains(&diamond, 5.0, 5.0));
|
||||
// A quad with no area holds nothing.
|
||||
let flat = [0.0, 0.0, 10.0, 0.0, 20.0, 0.0, 30.0, 0.0];
|
||||
assert!(!quad_contains(&flat, 5.0, 0.0));
|
||||
assert!(!quad_contains(&ccw, f32::NAN, 20.0), "a point that isn't a number is nowhere");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_quad_with_extreme_corners_holds_only_its_area() {
|
||||
// In f32 the cross products overflow (inf, and inf - inf = NaN), which passed every sign
|
||||
// test and put (1.5e20, 1.5e20), outside the triangle, inside it.
|
||||
let q = [0.0, 0.0, 2e20, 0.0, 0.0, 2e20, 0.0, 0.0];
|
||||
assert_eq!(link_quads(&q.map(Some), [0.0, 0.0, 3e20, 3e20]), vec![q], "kept by the area check");
|
||||
assert!(!quad_contains(&q, 1.5e20, 1.5e20), "beyond the long edge");
|
||||
assert!(!quad_contains(&q, 3e20, 1.0), "right of the triangle");
|
||||
assert!(quad_contains(&q, 0.5e20, 0.5e20));
|
||||
assert!(quad_contains(&q, 1.0, 1.0));
|
||||
let max = [0.0, 0.0, f32::MAX, 0.0, 0.0, f32::MAX, 0.0, 0.0];
|
||||
assert!(!quad_contains(&max, f32::MAX, f32::MAX));
|
||||
assert!(quad_contains(&max, 1.0, 1.0));
|
||||
}
|
||||
}
|
||||
@@ -83,6 +83,9 @@ pub struct RenderConfig {
|
||||
/// viewer and preview rasters: exports, printing and OCR render without it, so nothing drawn with an
|
||||
/// installed font is saved or printed (AGENTS.md §1.2, §1.4).
|
||||
pub system_fonts: bool,
|
||||
/// The render is output for printing (print as image): the configuration's auto state for
|
||||
/// the View event (ISO 32000-2 §8.11.4.4) is not applied, since printing is not viewing.
|
||||
pub for_print: bool,
|
||||
/// Steps of JBIG2 decoding a render may take across the page's images, instead of the usual
|
||||
/// `hayro_syntax::MAX_PAGE_JBIG2_WORK`. Those past it aren't drawn, like an image that can't
|
||||
/// be decoded.
|
||||
@@ -113,6 +116,7 @@ impl RenderConfig {
|
||||
let system_fonts = self.system_fonts;
|
||||
InterpreterSettings {
|
||||
ocg_overrides: self.layers.clone(),
|
||||
view_auto_state: !self.for_print,
|
||||
hide_comments: self.hide_comments,
|
||||
font_resolver: Arc::new(move |query| {
|
||||
japanese_fallback(query).or_else(|| system_fonts.then(|| system_fallback(query)).flatten()).or_else(|| standard(query))
|
||||
@@ -270,6 +274,13 @@ pub enum RenderWarning {
|
||||
/// A colour could not be computed (a colour space that cannot be read, or a Separation or
|
||||
/// DeviceN tint transform that cannot be evaluated) and was painted in a fallback colour.
|
||||
ColourFallback,
|
||||
/// An image's `/Indexed` colour space is malformed (ISO 32000-2 §8.6.6.3), so the image may be
|
||||
/// drawn wrongly or not at all. It is drawn recovered when it can be: indices past a lookup
|
||||
/// table shorter than m × (hival + 1) bytes in black, a `hival` past 255 taken as 255, a real
|
||||
/// one truncated, or (a `hival` below zero or not a number) the image in DeviceGray. With no
|
||||
/// lookup table at all (missing, not a string or a stream, or a stream that does not decode)
|
||||
/// it is not drawn. Reported once per page however many images it affects.
|
||||
MalformedIndexedImage,
|
||||
/// A Type 3 font without the `/Widths` it requires (ISO 32000-2 Table 110) was used; its
|
||||
/// glyphs were spaced by the widths their glyph procedures give.
|
||||
Type3WidthsMissing,
|
||||
@@ -454,6 +465,8 @@ fn render_page<'a>(
|
||||
// Previews render at low detail (tiny images are skipped); finals always draw all.
|
||||
let mut preview_settings = settings.clone();
|
||||
preview_settings.preview = req.preview;
|
||||
// A print preview shows what prints, and printing is not the View event.
|
||||
preview_settings.view_auto_state &= req.tag & PRINT_TAG == 0;
|
||||
render_into(page, cache, &preview_settings, &rs, pixels.bytes_mut());
|
||||
Ok((w.into(), h.into(), pixels, None))
|
||||
}));
|
||||
@@ -477,10 +490,12 @@ fn warning_settings(settings: &InterpreterSettings, warnings: Arc<Mutex<Vec<Rend
|
||||
InterpreterSettings {
|
||||
warning_sink: Arc::new(move |warning| {
|
||||
// Nested forms, Type 3 glyphs and patterns are interpreted again and each reports the
|
||||
// exhausted budget, or the colours that fell back: once per page is enough.
|
||||
// exhausted budget, or the colours that fell back, and several images can share one
|
||||
// malformed colour space: each warning is recorded once per page.
|
||||
let warning = match warning {
|
||||
InterpreterWarning::ContentTruncated => RenderWarning::ContentTruncated,
|
||||
InterpreterWarning::ColorFallback => RenderWarning::ColourFallback,
|
||||
InterpreterWarning::MalformedIndexedImage => RenderWarning::MalformedIndexedImage,
|
||||
InterpreterWarning::Type3WidthsMissing => RenderWarning::Type3WidthsMissing,
|
||||
InterpreterWarning::UnsupportedFont | InterpreterWarning::ImageDecodeFailure => return,
|
||||
};
|
||||
|
||||
@@ -2091,6 +2091,125 @@ fn rounded_pixel_budget_invalid_requests_never_reach_allocator() {
|
||||
}
|
||||
}
|
||||
|
||||
/// #3962: FrameMaker files distilled with Distiller 3 embed TrueType subsets that are symbolic,
|
||||
/// with no `/Encoding` and no `/ToUnicode`, whose codes are glyph positions in the Macintosh
|
||||
/// order, 29 below ASCII; the font's own `cmap` maps them to the right glyphs. Read as WinAnsi
|
||||
/// the text came out shifted (`Solid` as `6ROLG`), in the editor and in Word export alike. The
|
||||
/// `post` table names the glyph each code selects, which gives the text (vendored
|
||||
/// hayro-interpret patch 79). A font with an `/Encoding` still reads its codes through it.
|
||||
#[test]
|
||||
fn a_symbolic_truetype_font_without_an_encoding_reads_its_glyph_names() {
|
||||
use skrifa::MetadataProvider;
|
||||
use skrifa::raw::TableProvider;
|
||||
const TEXT: &str = "Solid state";
|
||||
// Four more codes: 0x3D selects `W.cv07`, a variant whose suffix is dropped (`W`); 0x3E a
|
||||
// glyph named `uniXXXX`, that code point; 0x3F `EMquad`, a name with no text, so the code
|
||||
// reads as WinAnsi (`?`); 0x40 the ligature `less_equal.liga`, two characters (`<=`).
|
||||
const SUFFIXED: u16 = 0x3D;
|
||||
const UNI: u16 = 0x3E;
|
||||
const UNNAMED: u16 = 0x3F;
|
||||
const LIGATURE: u16 = 0x40;
|
||||
// 0x41 selects a glyph whose name is spelt `uni01cd`, lowercase: the glyph list
|
||||
// specification's hex digits are uppercase (ISO 32000-2 §9.10.2), so the name stands for no
|
||||
// text and the code reads as WinAnsi (`A`), not as U+01CD.
|
||||
const LOWERCASE: u16 = 0x41;
|
||||
let font = include_bytes!("../../../../assets/fonts/JetBrainsMono-Regular.ttf");
|
||||
let face = skrifa::FontRef::new(font).expect("the test font parses");
|
||||
let charmap = face.charmap();
|
||||
let post = face.post().expect("the test font has a post table");
|
||||
let glyphs = face.maxp().expect("the test font has a maxp table").num_glyphs();
|
||||
let named = |name: &str| {
|
||||
(1..glyphs).find(|&g| post.glyph_name(skrifa::raw::types::GlyphId16::new(g)) == Some(name)).expect("the test font has the glyph")
|
||||
};
|
||||
let (uni, uni_char) = (1..glyphs)
|
||||
.find_map(|g| {
|
||||
let name = post.glyph_name(skrifa::raw::types::GlyphId16::new(g))?;
|
||||
let c = char::from_u32(u32::from_str_radix(name.strip_prefix("uni")?, 16).ok()?)?;
|
||||
(!c.is_control()).then_some((g, c))
|
||||
})
|
||||
.expect("the test font names a glyph uniXXXX");
|
||||
// Codes 29 below ASCII, mapped by a (3,0) symbol cmap at 0xF000 + code.
|
||||
let mut map: Vec<(u16, u16)> =
|
||||
TEXT.chars().map(|c| (0xF000 + c as u16 - 29, charmap.map(c).expect("the test font has the letter").to_u32() as u16)).collect();
|
||||
map.push((0xF000 + SUFFIXED, named("W.cv07")));
|
||||
map.push((0xF000 + UNI, uni));
|
||||
map.push((0xF000 + UNNAMED, named("EMquad")));
|
||||
map.push((0xF000 + LIGATURE, named("less_equal.liga")));
|
||||
let lowercase = named("uni01CD");
|
||||
assert_ne!(lowercase, uni, "the lowercased name is not the `uniXXXX` glyph read above");
|
||||
map.push((0xF000 + LOWERCASE, lowercase));
|
||||
map.sort_unstable();
|
||||
map.dedup();
|
||||
// A format 4 subtable: one segment per code, then the closing 0xFFFF segment.
|
||||
let segments: Vec<(u16, u16)> = map.iter().copied().chain([(0xFFFF, 0)]).collect();
|
||||
let n = segments.len() as u16;
|
||||
let mut sub = Vec::new();
|
||||
let words = |v: &mut Vec<u8>, w: &[u16]| w.iter().for_each(|w| v.extend_from_slice(&w.to_be_bytes()));
|
||||
words(&mut sub, &[4, 16 + 8 * n, 0, 2 * n, 2, 0, 2 * n - 2]);
|
||||
words(&mut sub, &segments.iter().map(|s| s.0).collect::<Vec<_>>());
|
||||
words(&mut sub, &[0]);
|
||||
words(&mut sub, &segments.iter().map(|s| s.0).collect::<Vec<_>>());
|
||||
words(&mut sub, &segments.iter().map(|&(code, gid)| if code == 0xFFFF { 1 } else { gid.wrapping_sub(code) }).collect::<Vec<_>>());
|
||||
words(&mut sub, &vec![0; segments.len()]);
|
||||
let mut cmap = Vec::new();
|
||||
words(&mut cmap, &[0, 1, 3, 0]);
|
||||
cmap.extend_from_slice(&12u32.to_be_bytes());
|
||||
cmap.extend(sub);
|
||||
// The new cmap goes at the end; the table directory's `cmap` entry points at it.
|
||||
let mut program = font.to_vec();
|
||||
while !program.len().is_multiple_of(4) {
|
||||
program.push(0);
|
||||
}
|
||||
let at = program.len();
|
||||
program.extend(&cmap);
|
||||
let tables = usize::from(u16::from_be_bytes([font[4], font[5]]));
|
||||
let entry = (0..tables).map(|i| 12 + 16 * i).find(|&e| &font[e..e + 4] == b"cmap").expect("the test font has a cmap");
|
||||
program[entry + 8..entry + 12].copy_from_slice(&(at as u32).to_be_bytes());
|
||||
program[entry + 12..entry + 16].copy_from_slice(&(cmap.len() as u32).to_be_bytes());
|
||||
// The `post` table's own spelling of the name, a Pascal string, lowercased in place.
|
||||
let spelt = b"\x07uni01CD";
|
||||
let spot = program.windows(spelt.len()).position(|w| w == spelt).expect("the post table spells the name");
|
||||
assert_eq!(program.windows(spelt.len()).filter(|w| w == spelt).count(), 1);
|
||||
program[spot..spot + spelt.len()].copy_from_slice(b"\x07uni01cd");
|
||||
|
||||
let text_of = |encoding: &str| -> String {
|
||||
let codes: String = TEXT.chars().map(|c| format!("{:02X}", c as u8 - 29)).collect::<String>()
|
||||
+ &format!("{SUFFIXED:02X}{UNI:02X}{UNNAMED:02X}{LIGATURE:02X}{LOWERCASE:02X}");
|
||||
let content = format!("BT /F1 14 Tf 10 40 Td <{codes}> Tj ET");
|
||||
let objects: Vec<Vec<u8>> = vec![
|
||||
b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(),
|
||||
b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(),
|
||||
b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 80] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >>".to_vec(),
|
||||
format!("<< /Length {} >>\nstream\n{content}\nendstream", content.len()).into_bytes(),
|
||||
format!("<< /Type /Font /Subtype /TrueType /BaseFont /ABCDEF+JetBrainsMono-Regular /FirstChar 0 /LastChar 255 /Widths [{}] /FontDescriptor 6 0 R {encoding}>>", vec!["600"; 256].join(" ")).into_bytes(),
|
||||
b"<< /Type /FontDescriptor /FontName /ABCDEF+JetBrainsMono-Regular /Flags 4 /FontBBox [-500 -300 1200 1000] /ItalicAngle 0 /Ascent 1020 /Descent -300 /CapHeight 730 /StemV 80 /FontFile2 7 0 R >>".to_vec(),
|
||||
[format!("<< /Length {} >>\nstream\n", program.len()).into_bytes(), program.clone(), b"\nendstream".to_vec()].concat(),
|
||||
];
|
||||
let mut pdf = b"%PDF-1.3\n".to_vec();
|
||||
let mut offsets = Vec::new();
|
||||
for (i, object) in objects.iter().enumerate() {
|
||||
offsets.push(pdf.len());
|
||||
pdf.extend(format!("{} 0 obj\n", i + 1).into_bytes());
|
||||
pdf.extend(object);
|
||||
pdf.extend(b"\nendobj\n");
|
||||
}
|
||||
let xref = pdf.len();
|
||||
pdf.extend(format!("xref\n0 {}\n0000000000 65535 f \n", objects.len() + 1).into_bytes());
|
||||
for offset in offsets {
|
||||
pdf.extend(format!("{offset:010} 00000 n \n").into_bytes());
|
||||
}
|
||||
pdf.extend(format!("trailer << /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objects.len() + 1).into_bytes());
|
||||
let mut r = PageRenderer::new(Arc::new(pdf), RenderConfig::default());
|
||||
let page = r.filtered_text(0, crate::text::TextFilter::default()).expect("the page has text");
|
||||
page.glyphs.iter().map(|g| g.text.as_str()).collect()
|
||||
};
|
||||
assert_eq!(text_of(""), format!("Solid stateW{uni_char}?<=A"));
|
||||
// An encoding says what the codes are, so they read through it.
|
||||
assert_eq!(text_of("/Encoding /WinAnsiEncoding "), "6ROLGVWDWH=>?@A");
|
||||
// `/Differences` still names its code: 0x36 reads `A`, not the glyph's `S`.
|
||||
assert_eq!(text_of("/Encoding << /Differences [54 /A] >> "), format!("Aolid stateW{uni_char}?<=A"));
|
||||
}
|
||||
|
||||
/// Issue #102: an A4 page (595.28×841.89 pt) rendered 595×841 at 72 dpi, dropping the last
|
||||
/// partial row and column. Like pdftoppm it is now 596×842, the edge pixels partly covered.
|
||||
#[test]
|
||||
@@ -2769,6 +2888,126 @@ trailer << /Root 1 0 R >>
|
||||
assert_eq!(px(off), vec![255, 255, 255, 255], "toggled-off layer must not draw");
|
||||
}
|
||||
|
||||
/// A page whose red square is in group 5 0 R (`ocg` its dictionary), under the default
|
||||
/// configuration `config`; `extra` adds objects from number 8.
|
||||
fn auto_state_pdf(ocg: &str, config: &str, extra: &str) -> Vec<u8> {
|
||||
format!(
|
||||
"%PDF-1.7
|
||||
1 0 obj << /Type /Catalog /Pages 2 0 R /OCProperties << /OCGs [5 0 R] /D {config} >> >> endobj
|
||||
2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj
|
||||
3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] /Contents 4 0 R /Resources << /Properties << /L1 5 0 R >> >> >> endobj
|
||||
4 0 obj << /Length 44 >> stream
|
||||
/OC /L1 BDC 1 0 0 rg 0 0 100 100 re f EMC
|
||||
endstream endobj
|
||||
5 0 obj {ocg} endobj
|
||||
{extra}
|
||||
trailer << /Root 1 0 R >>
|
||||
%%EOF"
|
||||
)
|
||||
.into_bytes()
|
||||
}
|
||||
|
||||
/// Whether the red square in group 5 0 R draws.
|
||||
fn auto_state_red(pdf: Vec<u8>, config: RenderConfig) -> bool {
|
||||
let mut r = PageRenderer::new(Arc::new(pdf), config);
|
||||
let p = r.render(RenderRequest { page: 0, kind: RequestKind::Pixels, tile: None, scale: 0.5, tag: 0, ..Default::default() });
|
||||
p.rgba.get(..4) == Some(&[255, 0, 0, 255][..])
|
||||
}
|
||||
|
||||
const VIEW_OFF: &str = "<< /Type /OCG /Name (A) /Usage << /View << /ViewState /OFF >> >> >>";
|
||||
const VIEW_ON: &str = "<< /Type /OCG /Name (A) /Usage << /View << /ViewState /ON >> >> >>";
|
||||
const AS_VIEW: &str = "/AS [<< /Event /View /Category [/View] /OCGs [5 0 R] >>]";
|
||||
|
||||
/// ISO 32000-2 §8.11.4.4: the configuration's auto state (`/AS`) sets a group's state for
|
||||
/// the View event from its usage, over `/BaseState`, `/ON` and `/OFF`. It was ignored, so a
|
||||
/// group whose `/ViewState` is OFF still drew on screen.
|
||||
#[test]
|
||||
fn the_view_auto_state_sets_a_groups_state_on_screen() {
|
||||
let shown = |ocg: &str, config: &str| auto_state_red(auto_state_pdf(ocg, config, ""), RenderConfig::default());
|
||||
assert!(!shown(VIEW_OFF, &format!("<< {AS_VIEW} >>")), "ViewState OFF, managed: hidden");
|
||||
assert!(shown(VIEW_OFF, "<< >>"), "no /AS: the usage alone changes nothing");
|
||||
assert!(shown(VIEW_OFF, "<< /AS [<< /Event /View /Category [/View] /OCGs [] >>] >>"), "not listed in /OCGs");
|
||||
assert!(shown(VIEW_ON, &format!("<< /OFF [5 0 R] {AS_VIEW} >>")), "ViewState ON wins over /OFF");
|
||||
assert!(shown(VIEW_ON, &format!("<< /BaseState /OFF {AS_VIEW} >>")), "and over /BaseState /OFF");
|
||||
assert!(!shown(VIEW_ON, "<< /OFF [5 0 R] >>"), "without /AS, /OFF decides");
|
||||
// The View event only, and the View category only.
|
||||
assert!(shown(VIEW_OFF, "<< /AS [<< /Event /Print /Category [/View] /OCGs [5 0 R] >>] >>"), "Print event: not on screen");
|
||||
assert!(shown(VIEW_OFF, "<< /AS [<< /Event /Export /Category [/View] /OCGs [5 0 R] >>] >>"), "Export event: not on screen");
|
||||
assert!(shown(VIEW_OFF, "<< /AS [<< /Event /View /Category [/Print] /OCGs [5 0 R] >>] >>"), "a category without a View entry");
|
||||
// A category it cannot evaluate gives no recommendation; the View one still applies.
|
||||
assert!(!shown(VIEW_OFF, "<< /AS [<< /Event /View /Category [/Zoom /View] /OCGs [5 0 R] >>] >>"), "Zoom alongside View");
|
||||
let zoomed = "<< /Type /OCG /Name (A) /Usage << /Zoom << /min 4 >> >> >>";
|
||||
assert!(shown(zoomed, "<< /AS [<< /Event /View /Category [/Zoom] /OCGs [5 0 R] >>] >>"), "Zoom alone: unchanged");
|
||||
// Indirect applications, arrays and usage dictionaries are followed.
|
||||
let indirect = "<< /Type /OCG /Name (A) /Usage 10 0 R >>";
|
||||
let extra = "8 0 obj [9 0 R] endobj\n9 0 obj << /Event /View /Category [/View] /OCGs 11 0 R >> endobj\n10 0 obj << /View << /ViewState /OFF >> >> endobj\n11 0 obj [5 0 R] endobj";
|
||||
assert!(!auto_state_red(auto_state_pdf(indirect, "<< /AS 8 0 R >>", extra), RenderConfig::default()), "indirect");
|
||||
}
|
||||
|
||||
/// The Layers panel's toggles still decide over the auto state, and a render for printing
|
||||
/// does not apply it (printing is not the View event).
|
||||
#[test]
|
||||
fn layer_toggles_and_print_renders_are_not_the_view_auto_state() {
|
||||
let pdf = auto_state_pdf(VIEW_OFF, &format!("<< {AS_VIEW} >>"), "");
|
||||
let on = RenderConfig { layers: Arc::new(vec![(5, 0, true)]), ..Default::default() };
|
||||
assert!(auto_state_red(pdf.clone(), on), "toggled on in the Layers panel");
|
||||
assert!(auto_state_red(pdf.clone(), RenderConfig { for_print: true, ..Default::default() }), "printed: its configured state");
|
||||
assert!(!auto_state_red(pdf, RenderConfig::default()), "on screen: hidden");
|
||||
}
|
||||
|
||||
/// A print preview ([`PRINT_TAG`], with or without the canvas's scale and grayscale bits)
|
||||
/// shows what prints, so the View auto state is not applied to it either.
|
||||
#[test]
|
||||
fn print_previews_are_not_the_view_auto_state() {
|
||||
let pdf = Arc::new(auto_state_pdf(VIEW_OFF, &format!("<< {AS_VIEW} >>"), ""));
|
||||
let mut r = PageRenderer::new(pdf, RenderConfig::default());
|
||||
for tag in [PRINT_TAG, PRINT_TAG | 1 << 59 | 7] {
|
||||
let p = r.render(RenderRequest { page: 0, kind: RequestKind::Pixels, tile: None, scale: 0.5, tag, ..Default::default() });
|
||||
assert_eq!(p.rgba.get(..4), Some(&[255, 0, 0, 255][..]), "tag {tag:#x}: printed state");
|
||||
}
|
||||
let p = r.render(RenderRequest { page: 0, kind: RequestKind::Pixels, tile: None, scale: 0.5, tag: 7, ..Default::default() });
|
||||
assert_ne!(p.rgba.get(..4), Some(&[255, 0, 0, 255][..]), "on screen: hidden");
|
||||
}
|
||||
|
||||
/// Malformed auto state is ignored without a panic, and the walk is bounded.
|
||||
#[test]
|
||||
fn malformed_view_auto_state_is_ignored() {
|
||||
let shown = |config: &str, extra: &str| auto_state_red(auto_state_pdf(VIEW_OFF, config, extra), RenderConfig::default());
|
||||
for config in [
|
||||
"<< /AS 5 >>",
|
||||
"<< /AS << /Event /View /Category [/View] /OCGs [5 0 R] >> >>",
|
||||
"<< /AS [1 null /x (s) [5 0 R]] >>",
|
||||
"<< /AS [<< /Event /View /Category [/View] >>] >>",
|
||||
"<< /AS [<< /Event /View /OCGs [5 0 R] >>] >>",
|
||||
"<< /AS [<< /Category [/View] /OCGs [5 0 R] >>] >>",
|
||||
"<< /AS [<< /Event (View) /Category [/View] /OCGs [5 0 R] >>] >>",
|
||||
"<< /AS [<< /Event /View /Category /View /OCGs [5 0 R] >>] >>",
|
||||
"<< /AS [<< /Event /View /Category [/View] /OCGs 5 0 R >>] >>",
|
||||
"<< /AS [<< /Event /View /Category [/View] /OCGs [(5) 5 /OCG] >>] >>",
|
||||
] {
|
||||
assert!(shown(config, ""), "{config}: ignored");
|
||||
}
|
||||
let bad_state = |s: &str| {
|
||||
let ocg = format!("<< /Type /OCG /Name (A) /Usage << /View << /ViewState {s} >> >> >>");
|
||||
auto_state_red(auto_state_pdf(&ocg, &format!("<< {AS_VIEW} >>"), ""), RenderConfig::default())
|
||||
};
|
||||
for s in ["/Off", "(OFF)", "0", "null", "[/OFF]"] {
|
||||
assert!(bad_state(s), "ViewState {s}: no recommendation");
|
||||
}
|
||||
// Cyclic references: an /AS, an application and a usage that refer to themselves.
|
||||
assert!(shown("<< /AS 8 0 R >>", "8 0 obj 8 0 R endobj"), "self-referencing /AS");
|
||||
assert!(shown("<< /AS [8 0 R] >>", "8 0 obj 8 0 R endobj"), "self-referencing application");
|
||||
let cyclic = "<< /Type /OCG /Name (A) /Usage 8 0 R >>";
|
||||
assert!(auto_state_red(auto_state_pdf(cyclic, &format!("<< {AS_VIEW} >>"), "8 0 obj 8 0 R endobj"), RenderConfig::default()));
|
||||
// Huge arrays: the group listed after 4096 other entries is past the cap.
|
||||
let many = format!("<< /AS [<< /Event /View /Category [/View] /OCGs [{}5 0 R] >>] >>", "9 0 R ".repeat(4096));
|
||||
assert!(shown(&many, "9 0 obj << /Type /OCG /Name (B) >> endobj"), "past the cap: unchanged");
|
||||
let within = format!("<< /AS [<< /Event /View /Category [/View] /OCGs [{}5 0 R] >>] >>", "9 0 R ".repeat(4095));
|
||||
assert!(!shown(&within, "9 0 obj << /Type /OCG /Name (B) >> endobj"), "within the cap: applied");
|
||||
let apps = format!("<< /AS [{}<< /Event /View /Category [/View] /OCGs [5 0 R] >>] >>", "<< /Event /Print >> ".repeat(256));
|
||||
assert!(shown(&apps, ""), "past the application cap: unchanged");
|
||||
}
|
||||
|
||||
/// #2986: an optional content membership dictionary with a visibility expression (`/VE`,
|
||||
/// ISO 32000-2 §8.11.2.2) shows its content only when the expression is true, and the
|
||||
/// expression takes precedence over `/OCGs` and `/P`. It was ignored, so content under it
|
||||
@@ -9163,6 +9402,10 @@ fn an_averaged_down_soft_mask_follows_its_samples_and_its_drawn_size() {
|
||||
// ICC profiles whose stream dictionaries are the same (vendored hayro-interpret patch 48).
|
||||
mod icc_profile_cache;
|
||||
|
||||
// An Indexed resource named by many inline images reads its lookup once (vendored
|
||||
// hayro-interpret patch 80).
|
||||
mod indexed_lookup_cache;
|
||||
|
||||
// A Type 3 glyph shown again decodes its procedure once (vendored hayro-interpret patch 87).
|
||||
mod type3_proc_cache;
|
||||
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
//! An `/Indexed` colour space named by a resource is built once, and its lookup table read
|
||||
//! once, however many inline images name it (vendored hayro-interpret patch 80). An earlier
|
||||
//! version of the patch checked the table again before every inline image, decoding a lookup
|
||||
//! stream once per image outside the colour-space cache.
|
||||
|
||||
use super::image_cache_pdf;
|
||||
|
||||
/// A page that draws `count` 2 × 1 inline images in the resource colour space `/P`, an Indexed
|
||||
/// space over DeviceRGB with `hival` whose lookup is stream object 5 holding `table`.
|
||||
fn page(count: usize, hival: u8, table: &[u8]) -> Vec<u8> {
|
||||
let image = "q 20 0 0 20 0 0 cm BI /W 2 /H 1 /BPC 8 /CS /P /F /AHx ID 0001> EI Q";
|
||||
let content = vec![image; count].join("\n");
|
||||
let resources = format!("<< /ColorSpace << /P [/Indexed /DeviceRGB {hival} 5 0 R] >> >>");
|
||||
let dict = format!("<< /Length {} >>", table.len());
|
||||
image_cache_pdf(&content, &resources, &[(&dict, table)])
|
||||
}
|
||||
|
||||
fn lookup_reads(pdf: Vec<u8>) -> [usize; 2] {
|
||||
use hayro::hayro_interpret::font::Glyph;
|
||||
use hayro::hayro_interpret::hayro_syntax::Pdf;
|
||||
use hayro::hayro_interpret::{
|
||||
BlendMode, ClipPath, Context, Device, GlyphDrawMode, Image, InterpreterCache, InterpreterSettings, Paint, PathDrawMode, SoftMask,
|
||||
TransformExt, interpret_page,
|
||||
};
|
||||
use kurbo::{Affine, BezPath, Rect};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Draws nothing: only the colour spaces the page reads matter here.
|
||||
struct Nothing;
|
||||
impl<'a> Device<'a> for Nothing {
|
||||
fn set_soft_mask(&mut self, _: Option<SoftMask<'a>>) {}
|
||||
fn set_blend_mode(&mut self, _: BlendMode) {}
|
||||
fn draw_path(&mut self, _: &BezPath, _: Affine, _: &Paint<'a>, _: &PathDrawMode) {}
|
||||
fn push_clip_path(&mut self, _: &ClipPath) {}
|
||||
fn push_transparency_group(&mut self, _: f32, _: Option<SoftMask<'a>>, _: BlendMode) {}
|
||||
fn draw_glyph(&mut self, _: &Glyph<'a>, _: Affine, _: Affine, _: &Paint<'a>, _: &GlyphDrawMode) {}
|
||||
fn draw_image(&mut self, _: Image<'a, '_>, _: Affine) {}
|
||||
fn pop_clip_path(&mut self) {}
|
||||
fn pop_transparency_group(&mut self) {}
|
||||
}
|
||||
|
||||
let pdf = Pdf::new(Arc::new(pdf)).expect("parses");
|
||||
let page = &pdf.pages()[0];
|
||||
let cache = InterpreterCache::new();
|
||||
[(); 2].map(|()| {
|
||||
let initial = page.initial_transform(true).to_kurbo();
|
||||
let mut ctx = Context::new(initial, Rect::new(0.0, 0.0, 130.0, 70.0), &cache, page.xref(), InterpreterSettings::default());
|
||||
interpret_page(page, &mut ctx, &mut Nothing);
|
||||
cache.indexed_lookup_reads()
|
||||
})
|
||||
}
|
||||
|
||||
/// Twenty inline images naming one resource read its lookup stream once, in the first render
|
||||
/// and none in a second render through the same cache: for a full table, and for a short one
|
||||
/// that is padded (whose images an earlier version of the patch checked, and skipped, one by
|
||||
/// one).
|
||||
#[test]
|
||||
fn inline_images_naming_one_indexed_resource_read_its_lookup_once() {
|
||||
let full = page(20, 1, b"\xFF\x00\x00\x00\xFF\x00");
|
||||
assert_eq!(lookup_reads(full), [1, 1], "a full table: read once, then cached");
|
||||
let short = page(20, 7, b"\xFF\x00\x00\x00\xFF\x00");
|
||||
assert_eq!(lookup_reads(short), [1, 1], "a short table: read once, then cached");
|
||||
}
|
||||
|
||||
/// Two Indexed resources whose arrays differ (`/P` names object 5, `/Q` object 6) are two
|
||||
/// spaces: each is built, and its table read, once, and neither stands in for the other.
|
||||
#[test]
|
||||
fn two_indexed_resources_are_cached_apart() {
|
||||
let image = |name: &str| format!("q 20 0 0 20 0 0 cm BI /W 2 /H 1 /BPC 8 /CS /{name} /F /AHx ID 0001> EI Q");
|
||||
let content = [image("P"), image("Q"), image("P"), image("Q")].join("\n");
|
||||
let resources = "<< /ColorSpace << /P [/Indexed /DeviceRGB 1 5 0 R] /Q [/Indexed /DeviceRGB 1 6 0 R] >> >>";
|
||||
let (red_green, blue_white): (&[u8], &[u8]) = (b"\xFF\x00\x00\x00\xFF\x00", b"\x00\x00\xFF\xFF\xFF\xFF");
|
||||
let pdf = image_cache_pdf(&content, resources, &[("<< /Length 6 >>", red_green), ("<< /Length 6 >>", blue_white)]);
|
||||
assert_eq!(lookup_reads(pdf), [2, 2], "each table read once");
|
||||
}
|
||||
@@ -137,7 +137,8 @@ impl PageText {
|
||||
/// Case-insensitive search. Returns glyph ranges of every match (words may span line breaks,
|
||||
/// which count as a single space, or as nothing where the line runs on between two Chinese or
|
||||
/// Japanese characters or ends in a soft hyphen: there a query with a space across the break
|
||||
/// doesn't match, and one without does).
|
||||
/// doesn't match, and one without does; a ligature matches its letters, and a word divided by a
|
||||
/// hyphen at a line end matches whole as well as with the hyphen).
|
||||
pub fn find(&self, needle: &str) -> Vec<std::ops::Range<usize>> {
|
||||
self.find_opts(needle, false, false)
|
||||
}
|
||||
|
||||
@@ -1,33 +1,133 @@
|
||||
//! Literal search in normalized page text, retaining the original glyph owners.
|
||||
//!
|
||||
//! Words and lines are separated by one space, except where a line of Chinese or Japanese runs on
|
||||
//! to the next: a break between two such characters is no word break, so it reads as nothing and
|
||||
//! "検知機構" is found when the line ends after "検知".
|
||||
//! The page text is read as characters, each owned by the glyph it came from. Words and lines are
|
||||
//! separated by one space, except where a line of Chinese or Japanese runs on to the next: a break
|
||||
//! between two such characters is no word break, so it reads as nothing and "検知機構" is found
|
||||
//! when the line ends after "検知". A Latin compatibility ligature (U+FB00–U+FB06) reads as its
|
||||
//! letters in the page and in the query, so "office" finds "o\u{FB03}ce". A word divided by a
|
||||
//! hyphen at the end of a line is also found whole: where a line ends in a hyphen between two
|
||||
//! letters, the text is searched a second time without the hyphen and the line break ("example"
|
||||
//! finds "exam-" + "ple") and a third time with the hyphen but without the break ("exam-ple"). A
|
||||
//! hit in any reading counts; where hits from different readings overlap, the one that starts
|
||||
//! first is kept (the longer on a tie). A soft hyphen needs no second reading: it draws nothing,
|
||||
//! and a line that ends in one always runs on.
|
||||
use super::device::ligature_letters;
|
||||
use super::{PageText, fold_case};
|
||||
use std::ops::Range;
|
||||
|
||||
/// How a line ending in a hyphen between two letters is read.
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum Hyphen {
|
||||
/// As written: the hyphen, then a line break (a space).
|
||||
Written,
|
||||
/// One word: neither the hyphen nor the break.
|
||||
Joined,
|
||||
/// A hyphenated compound: the hyphen, but no break.
|
||||
Kept,
|
||||
}
|
||||
|
||||
/// A visible hyphen that can divide a word at a line end: HYPHEN-MINUS and HYPHEN. A SOFT HYPHEN
|
||||
/// (ISO 32000-2 §14.8.2.3) is invisible instead: find skips it, and a line that ends in one runs on.
|
||||
fn is_hyphen(c: char) -> bool {
|
||||
matches!(c, '-' | '\u{2010}')
|
||||
}
|
||||
|
||||
/// Whether a line break separates glyph `i` from the glyph before it.
|
||||
fn breaks_before(page: &PageText, i: usize) -> bool {
|
||||
i.checked_sub(1).and_then(|previous| page.line_of.get(previous)).zip(page.line_of.get(i)).is_some_and(|(a, b)| a != b)
|
||||
}
|
||||
|
||||
pub(super) fn find(page: &PageText, query: &str, sensitive: bool, whole_words: bool, limit: usize) -> Vec<Range<usize>> {
|
||||
if limit == 0 {
|
||||
return Vec::new();
|
||||
}
|
||||
let fold = |s: &str| if sensitive { s.to_owned() } else { fold_case(s) };
|
||||
let fold = |s: &str| if sensitive { ligature_letters(s.to_owned()) } else { fold_case(&ligature_letters(s.to_owned())) };
|
||||
let query: String = fold(query).chars().filter(|&c| !is_invisible(c)).collect();
|
||||
let needle: Vec<char> = query.split_whitespace().collect::<Vec<_>>().join(" ").chars().collect();
|
||||
if needle.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let texts: Vec<String> = page.glyphs.iter().map(|g| fold(&g.text)).collect();
|
||||
let divided: Vec<bool> = (0..texts.len()).map(|i| divides(page, &texts, i)).collect();
|
||||
let readings: &[Hyphen] = if divided.contains(&true) { &[Hyphen::Written, Hyphen::Joined, Hyphen::Kept] } else { &[Hyphen::Written] };
|
||||
// KMP reuses a matched prefix instead of comparing a long query again at every position.
|
||||
// The table is bounded by the page's already materialized character count.
|
||||
let mut prefix = vec![0; needle.len()];
|
||||
let mut matched = 0;
|
||||
for (i, &c) in needle.iter().enumerate().skip(1) {
|
||||
matched = advance(&needle, &prefix, matched, c);
|
||||
if let Some(slot) = prefix.get_mut(i) {
|
||||
*slot = matched;
|
||||
}
|
||||
}
|
||||
let mut hits: Vec<(Range<usize>, usize)> = Vec::new();
|
||||
for (r, &reading) in readings.iter().enumerate() {
|
||||
let (chars, zero_width_space) = characters(page, &texts, ÷d, reading);
|
||||
let found = search(&chars, &zero_width_space, &needle, &prefix, whole_words, limit);
|
||||
hits.extend(found.into_iter().map(|hit| (hit, r)));
|
||||
}
|
||||
if readings.len() == 1 {
|
||||
return hits.into_iter().map(|(hit, _)| hit).collect();
|
||||
}
|
||||
// Each reading's hits are in order and apart in its characters, though two can share a glyph
|
||||
// ("f" twice in an "ffi" glyph); they are all kept. Across readings, the earliest start wins
|
||||
// (the longer on a tie): a hit is left out where it overlaps one kept from another reading.
|
||||
// The sort is stable, so the earlier reading wins an exact tie.
|
||||
hits.sort_by(|a, b| a.0.start.cmp(&b.0.start).then(b.0.end.cmp(&a.0.end)));
|
||||
// The furthest end of the hits kept from each reading. Hits come in order of start, so one
|
||||
// overlaps an earlier kept hit exactly when it starts before that hit's end.
|
||||
let mut ends = [0usize; 3];
|
||||
let mut kept: Vec<Range<usize>> = Vec::new();
|
||||
for (hit, r) in hits {
|
||||
if ends.iter().enumerate().all(|(other, &end)| other == r || hit.start >= end) {
|
||||
if let Some(end) = ends.get_mut(r) {
|
||||
*end = (*end).max(hit.end);
|
||||
}
|
||||
kept.push(hit);
|
||||
if kept.len() == limit {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
kept
|
||||
}
|
||||
|
||||
/// Whether glyph `i` ends its line with a hyphen that follows a letter of its word, and the next
|
||||
/// line starts with a letter. `texts` are the glyphs' folded texts; the invisible characters find
|
||||
/// skips are passed over on both sides.
|
||||
fn divides(page: &PageText, texts: &[String], i: usize) -> bool {
|
||||
let Some(text) = texts.get(i) else { return false };
|
||||
let mut back = text.chars().rev().filter(|&c| !is_invisible(c));
|
||||
if !back.next().is_some_and(is_hyphen) {
|
||||
return false;
|
||||
}
|
||||
let before = match back.next() {
|
||||
Some(c) => Some(c),
|
||||
// A hyphen glyph of its own: the letter is the end of the glyph before, on its line with no word gap.
|
||||
None if !page.space_before.get(i).copied().unwrap_or(false) && !breaks_before(page, i) => {
|
||||
i.checked_sub(1).and_then(|p| texts.get(p)).and_then(|t| t.chars().rev().find(|&c| !is_invisible(c)))
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let Some(next) = i.checked_add(1) else { return false };
|
||||
before.is_some_and(char::is_alphabetic)
|
||||
&& breaks_before(page, next)
|
||||
&& texts.get(next).and_then(|t| t.chars().find(|&c| !is_invisible(c))).is_some_and(char::is_alphabetic)
|
||||
}
|
||||
|
||||
/// The page's characters in one `reading`, each with the glyph it came from, and whether a
|
||||
/// skipped ZERO WIDTH SPACE came right before each one: it draws nothing, but it is a word
|
||||
/// boundary (UAX #29 breaks on both sides of it), which Thai and Khmer write between words with
|
||||
/// no visible gap, so whole-word search still sees two words there.
|
||||
fn characters(page: &PageText, texts: &[String], divided: &[bool], reading: Hyphen) -> (Vec<(char, usize)>, Vec<bool>) {
|
||||
let mut chars: Vec<(char, usize)> = Vec::new();
|
||||
// Whether a skipped ZERO WIDTH SPACE came right before each character: it draws nothing, but
|
||||
// it is a word boundary (UAX #29 breaks on both sides of it), which Thai and Khmer write between words
|
||||
// with no visible gap, so whole-word search still sees two words there.
|
||||
let mut zero_width_space: Vec<bool> = Vec::new();
|
||||
let mut pending_zero_width_space = false;
|
||||
// The last character pushed other than a variation selector, kept as characters are pushed so
|
||||
// a long run of selectors costs no rescan.
|
||||
let mut last_base: Option<char> = None;
|
||||
for (i, glyph) in page.glyphs.iter().enumerate() {
|
||||
let text = fold(&glyph.text);
|
||||
let line_break = i.checked_sub(1).and_then(|previous| page.line_of.get(previous)).zip(page.line_of.get(i)).is_some_and(|(a, b)| a != b);
|
||||
for (i, text) in texts.iter().enumerate() {
|
||||
let line_break = breaks_before(page, i);
|
||||
// A soft hyphen marks where a word may be divided at a line end (ISO 32000-2 §14.8.2.3), so
|
||||
// a line that ends in one runs on to the next with no word break between them.
|
||||
// Other invisible characters after the soft hyphen don't hide it.
|
||||
@@ -36,18 +136,29 @@ pub(super) fn find(page: &PageText, query: &str, sensitive: bool, whole_words: b
|
||||
// sides of the break are the visible ones: invisible characters are skipped below, and a
|
||||
// variation selector after the last one only picks its glyph.
|
||||
let joined = line_break && last_base.is_some_and(unspaced) && first_visible(page, i).is_some_and(unspaced) && wraps(page, i);
|
||||
let gap = page.space_before.get(i).copied().unwrap_or(false) || (line_break && !(joined || soft_break));
|
||||
// And, in the readings that join it, a line that ends in a visible hyphen between letters.
|
||||
let after_divide = reading != Hyphen::Written && i.checked_sub(1).and_then(|p| divided.get(p)).copied().unwrap_or(false);
|
||||
let gap = page.space_before.get(i).copied().unwrap_or(false) || (line_break && !(joined || soft_break || after_divide));
|
||||
if i > 0 && gap && chars.last().is_some_and(|c| c.0 != ' ') {
|
||||
chars.push((' ', i));
|
||||
last_base = Some(' ');
|
||||
zero_width_space.push(false);
|
||||
pending_zero_width_space = false;
|
||||
}
|
||||
for c in text.chars() {
|
||||
// The divided glyph's hyphen is its last visible character, left out of the joined reading.
|
||||
let dropped = if reading == Hyphen::Joined && divided.get(i).copied().unwrap_or(false) {
|
||||
text.char_indices().rev().find(|&(_, c)| !is_invisible(c)).map(|(at, _)| at)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
for (at, c) in text.char_indices() {
|
||||
if is_invisible(c) {
|
||||
pending_zero_width_space |= c == '\u{200B}';
|
||||
continue;
|
||||
}
|
||||
if Some(at) == dropped {
|
||||
continue;
|
||||
}
|
||||
let c = if c.is_whitespace() { ' ' } else { c };
|
||||
if c != ' ' || chars.last().is_none_or(|last| last.0 != ' ') {
|
||||
chars.push((c, i));
|
||||
@@ -59,35 +170,38 @@ pub(super) fn find(page: &PageText, query: &str, sensitive: bool, whole_words: b
|
||||
}
|
||||
}
|
||||
}
|
||||
(chars, zero_width_space)
|
||||
}
|
||||
|
||||
/// Non-overlapping hits of `needle` (with its KMP `prefix` table) in `chars`, as glyph ranges.
|
||||
/// `zero_width_space` says which characters come right after a skipped zero width space.
|
||||
fn search(
|
||||
chars: &[(char, usize)],
|
||||
zero_width_space: &[bool],
|
||||
needle: &[char],
|
||||
prefix: &[usize],
|
||||
whole_words: bool,
|
||||
limit: usize,
|
||||
) -> Vec<Range<usize>> {
|
||||
if needle.len() > chars.len() {
|
||||
return Vec::new();
|
||||
}
|
||||
// KMP reuses a matched prefix instead of comparing a long query again at every position.
|
||||
// The table is bounded by the page's already materialized character count.
|
||||
let mut prefix = vec![0; needle.len()];
|
||||
let mut matched = 0;
|
||||
for (i, &c) in needle.iter().enumerate().skip(1) {
|
||||
matched = advance(&needle, &prefix, matched, c);
|
||||
if let Some(slot) = prefix.get_mut(i) {
|
||||
*slot = matched;
|
||||
}
|
||||
}
|
||||
matched = 0;
|
||||
// A neighbour bounds a word only in a script that puts spaces between words. Han, kana, Thai
|
||||
// and the like run their words together, so a character of theirs next to the match is no
|
||||
// reason to reject it: Acrobat finds 台北 inside 台北市 with Whole words only on. Digits still
|
||||
// bound, in any script: ๑ is not a whole word inside the number ๑๒.
|
||||
let word = |i: Option<usize>| i.and_then(|i| chars.get(i)).is_some_and(|c| c.0.is_alphanumeric() && (c.0.is_numeric() || !unspaced_script(c.0)));
|
||||
// A skipped zero width space before the first character or after the last is a boundary.
|
||||
let after_break = |i: usize| zero_width_space.get(i).copied().unwrap_or(false);
|
||||
let mut hits = Vec::new();
|
||||
for (i, &(c, owner)) in chars.iter().enumerate() {
|
||||
matched = advance(&needle, &prefix, matched, c);
|
||||
matched = advance(needle, prefix, matched, c);
|
||||
if matched != needle.len() {
|
||||
continue;
|
||||
}
|
||||
let end = i.saturating_add(1);
|
||||
let start = end.saturating_sub(needle.len());
|
||||
// A skipped zero width space before the first character or after the last is a boundary.
|
||||
let after_break = |i: usize| zero_width_space.get(i).copied().unwrap_or(false);
|
||||
let bounded = !whole_words || ((after_break(start) || !word(start.checked_sub(1))) && (after_break(end) || !word(Some(end))));
|
||||
if bounded {
|
||||
if let Some((_, first)) = chars.get(start)
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
//! A standard 14 font named without `/Widths` draws each glyph within the advance its standard
|
||||
//! metrics give (ISO 32000-2 §9.6.2.2), including the Euro at WinAnsiEncoding code 128 (Annex D,
|
||||
//! Table D.2): the bundled stand-ins draw their € up to 722 units wide, and it overlapped the
|
||||
//! glyph after it in Helvetica and Times.
|
||||
|
||||
use pdfcraft_fonts::Std14;
|
||||
use pdfcraft_render::{PageRenderer, RenderConfig, RenderRequest};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// 100 pt at scale 1 is 100 pixels to the em, so a width of 556 units is 55.6 pixels.
|
||||
pub(crate) const SIZE: f64 = 100.0;
|
||||
const EURO: u8 = 0x80;
|
||||
|
||||
fn pdf(objects: &[String]) -> Vec<u8> {
|
||||
let mut bytes = b"%PDF-1.7\n".to_vec();
|
||||
let mut offsets = Vec::new();
|
||||
for (i, object) in objects.iter().enumerate() {
|
||||
offsets.push(bytes.len());
|
||||
bytes.extend_from_slice(format!("{} 0 obj\n{object}\nendobj\n", i + 1).as_bytes());
|
||||
}
|
||||
let xref = bytes.len();
|
||||
bytes.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objects.len() + 1).as_bytes());
|
||||
for offset in offsets {
|
||||
bytes.extend_from_slice(format!("{offset:010} 00000 n \n").as_bytes());
|
||||
}
|
||||
bytes.extend_from_slice(format!("trailer << /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objects.len() + 1).as_bytes());
|
||||
bytes
|
||||
}
|
||||
|
||||
/// The runs of columns holding dark pixels, as (first, last) column, of `text` (a PDF literal
|
||||
/// string body) shown at 100 pt in the standard font `name` with WinAnsiEncoding and no
|
||||
/// `/Widths`, starting 20 pt from the left edge.
|
||||
fn ink_runs(name: &str, text: &str) -> Vec<(u32, u32)> {
|
||||
ink_runs_in(name, Some("WinAnsiEncoding"), text)
|
||||
}
|
||||
|
||||
/// [`ink_runs`] in `encoding`, or with no `/Encoding` at all (the font's built-in one).
|
||||
pub(crate) fn ink_runs_in(name: &str, encoding: Option<&str>, text: &str) -> Vec<(u32, u32)> {
|
||||
let body = format!("BT /F1 {SIZE} Tf 20 40 Td ({text}) Tj ET");
|
||||
let bytes = pdf(&[
|
||||
"<< /Type /Catalog /Pages 2 0 R >>".into(),
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".into(),
|
||||
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 160] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >>".into(),
|
||||
format!("<< /Length {} >>\nstream\n{body}\nendstream", body.len()),
|
||||
format!("<< /Type /Font /Subtype /Type1 /BaseFont /{name}{} >>", encoding.map(|e| format!(" /Encoding /{e}")).unwrap_or_default()),
|
||||
]);
|
||||
let mut renderer = PageRenderer::new(Arc::new(bytes), RenderConfig::default());
|
||||
let image = renderer.render(RenderRequest { page: 0, scale: 1.0, ..Default::default() });
|
||||
assert!(image.error.is_none(), "{:?}", image.error);
|
||||
let dark = |x: u32| {
|
||||
(0..image.height).any(|y| {
|
||||
let at = usize::try_from((y * image.width + x) * 4).unwrap_or(usize::MAX);
|
||||
image.rgba.get(at).is_some_and(|r| *r < 128)
|
||||
})
|
||||
};
|
||||
let mut runs: Vec<(u32, u32)> = Vec::new();
|
||||
for x in 0..image.width {
|
||||
if dark(x) {
|
||||
match runs.last_mut() {
|
||||
Some(run) if run.1 + 1 == x => run.1 = x,
|
||||
_ => runs.push((x, x)),
|
||||
}
|
||||
}
|
||||
}
|
||||
runs
|
||||
}
|
||||
|
||||
/// `a€b`: the € keeps clear of both neighbours, its ink is no wider than its advance, and each
|
||||
/// glyph sits where the advances the writer measures with (`Std14`) put it: 556 units for the
|
||||
/// Helvetica family, 500 for Times and 600 for Courier.
|
||||
#[test]
|
||||
fn the_euro_fits_its_standard_advance() {
|
||||
for (name, font, euro) in [
|
||||
("Helvetica", Std14::Helvetica, 556),
|
||||
("Helvetica-Bold", Std14::HelveticaBold, 556),
|
||||
("Times-Roman", Std14::TimesRoman, 500),
|
||||
("Times-Bold", Std14::TimesBold, 500),
|
||||
("Courier", Std14::Courier, 600),
|
||||
("Courier-Bold", Std14::CourierBold, 600),
|
||||
] {
|
||||
assert_eq!(font.width(EURO), f64::from(euro), "{name}: the writer's Euro width");
|
||||
let advance = font.advance(EURO, SIZE);
|
||||
let a = font.advance(b'a', SIZE);
|
||||
|
||||
let runs = ink_runs(name, "a\\200b");
|
||||
let [_, (euro_start, euro_end), (b_start, _)] = runs[..] else { panic!("{name}: a, € and b apart: {runs:?}") };
|
||||
let [(alone_euro, _)] = ink_runs(name, "\\200")[..] else { panic!("{name}: one €") };
|
||||
let [(alone_b, _)] = ink_runs(name, "b")[..] else { panic!("{name}: one b") };
|
||||
|
||||
assert!(f64::from(euro_end - euro_start + 1) <= advance + 1.0, "{name}: the € is no wider than {euro} units: {runs:?}");
|
||||
assert!((f64::from(euro_start) - f64::from(alone_euro) - a).abs() <= 1.0, "{name}: the € starts one `a` on: {runs:?}");
|
||||
assert!((f64::from(b_start) - f64::from(alone_b) - a - advance).abs() <= 1.0, "{name}: the b starts {euro} units after the €: {runs:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// `€€`: two Euros side by side stay two glyphs, the second one advance on.
|
||||
#[test]
|
||||
fn two_euros_stay_apart() {
|
||||
for (name, font) in [("Helvetica", Std14::Helvetica), ("Times-Roman", Std14::TimesRoman), ("Times-Bold", Std14::TimesBold)] {
|
||||
let runs = ink_runs(name, "\\200\\200");
|
||||
let [(first, _), (second, _)] = runs[..] else { panic!("{name}: two separate Euros: {runs:?}") };
|
||||
assert!((f64::from(second - first) - font.advance(EURO, SIZE)).abs() <= 1.0, "{name}: {runs:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The slanted faces: a lone € is no wider than its advance either. (Their neighbours can share
|
||||
/// a column with it through the slant alone, so the gaps of `a€b` aren't a measure there.)
|
||||
#[test]
|
||||
fn a_slanted_euro_fits_its_standard_advance() {
|
||||
for (name, font) in [
|
||||
("Helvetica-Oblique", Std14::HelveticaOblique),
|
||||
("Helvetica-BoldOblique", Std14::HelveticaBoldOblique),
|
||||
("Times-BoldItalic", Std14::TimesBoldItalic),
|
||||
] {
|
||||
let runs = ink_runs(name, r"\200");
|
||||
let [(start, end)] = runs[..] else { panic!("{name}: one €: {runs:?}") };
|
||||
assert!(f64::from(end - start + 1) <= font.advance(EURO, SIZE) + 1.0, "{name}: {runs:?}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,458 @@
|
||||
//! An `/Indexed` image whose colour space breaks ISO 32000-2 §8.6.6.3 (a lookup table shorter
|
||||
//! than m × (hival + 1) bytes, or a `hival` past 255 or with a fraction) is drawn as most
|
||||
//! readers draw it, and the render reports `RenderWarning::MalformedIndexedImage`:
|
||||
//! - a short table keeps the entries it holds in full, and an index past them is drawn black,
|
||||
//! whatever the base space;
|
||||
//! - a `hival` past 255 is taken as 255;
|
||||
//! - a real `hival` is truncated toward zero.
|
||||
//!
|
||||
//! An image whose lookup is missing, `null`, neither a string nor a stream, or a stream that
|
||||
//! does not decode is not drawn, and is reported. A `hival` that is negative or not a number
|
||||
//! keeps the upstream handling (the image falls back to DeviceGray), and is reported too.
|
||||
//! Upstream fell back to DeviceGray for every one of these, painting the indices as near-black
|
||||
//! grey levels, even those whose entries were present.
|
||||
//!
|
||||
//! The images are 8 × 1, samples 0 to 7, each column 25 px wide on a 200 × 200 page (the layout
|
||||
//! of the seven cases A to G a reviewer compared across readers on #4393).
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use pdfcraft_render::{PageRenderer, RenderConfig, RenderRequest, RenderWarning, RenderedPage, RequestKind};
|
||||
|
||||
/// The eight entries the tests' tables hold, in order.
|
||||
const TABLE: &str = "FF0000 00FF00 0000FF FFFF00 FF00FF 00FFFF 808080 000000";
|
||||
const COLOURS: [[u8; 3]; 8] = [[255, 0, 0], [0, 255, 0], [0, 0, 255], [255, 255, 0], [255, 0, 255], [0, 255, 255], [128, 128, 128], [0, 0, 0]];
|
||||
const BLACK: [u8; 3] = [0, 0, 0];
|
||||
const WHITE: [u8; 3] = [255, 255, 255];
|
||||
const DRAW_IMAGE: &str = "q 200 0 0 200 0 0 cm /Im Do Q";
|
||||
const MALFORMED: [RenderWarning; 1] = [RenderWarning::MalformedIndexedImage];
|
||||
|
||||
/// The first `n` hex entries of `TABLE`.
|
||||
fn entries(n: usize) -> String {
|
||||
TABLE.split(' ').take(n).collect::<Vec<_>>().join(" ")
|
||||
}
|
||||
|
||||
/// A 200 × 200 page whose `/Im` image is eight samples wide (indices 0 to 7) and covers the
|
||||
/// page, with `/P` naming `colour_space` as a resource. `extra` objects are numbered from 6.
|
||||
fn pdf(colour_space: &str, content: &str, extra: &[&[u8]]) -> Vec<u8> {
|
||||
pdf_with_resource("P", colour_space, content, extra)
|
||||
}
|
||||
|
||||
/// As `pdf`, with the colour space resource named `resource` rather than `/P`.
|
||||
fn pdf_with_resource(resource: &str, colour_space: &str, content: &str, extra: &[&[u8]]) -> Vec<u8> {
|
||||
pdf_with_resources(resource, colour_space, "", content, extra)
|
||||
}
|
||||
|
||||
/// As `pdf_with_resource`, with `more` entries in the page's resource dictionary.
|
||||
fn pdf_with_resources(resource: &str, colour_space: &str, more: &str, content: &str, extra: &[&[u8]]) -> Vec<u8> {
|
||||
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 >>".to_vec(),
|
||||
format!(
|
||||
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Contents 4 0 R \
|
||||
/Resources << /XObject << /Im 5 0 R >> /ColorSpace << /{resource} {colour_space} >> {more} >> >>"
|
||||
)
|
||||
.into_bytes(),
|
||||
format!("<< /Length {} >>\nstream\n{content}\nendstream", content.len()).into_bytes(),
|
||||
format!(
|
||||
"<< /Type /XObject /Subtype /Image /Width 8 /Height 1 /BitsPerComponent 8 \
|
||||
/ColorSpace {colour_space} /Filter /ASCIIHexDecode /Length 17 >>\nstream\n0001020304050607>\nendstream"
|
||||
)
|
||||
.into_bytes(),
|
||||
];
|
||||
objs.extend(extra.iter().map(|o| o.to_vec()));
|
||||
let mut out = b"%PDF-1.7\n".to_vec();
|
||||
let mut offsets = Vec::new();
|
||||
for (i, body) in objs.iter().enumerate() {
|
||||
offsets.push(out.len());
|
||||
out.extend_from_slice(format!("{} 0 obj\n", i + 1).as_bytes());
|
||||
out.extend_from_slice(body);
|
||||
out.extend_from_slice(b"\nendobj\n");
|
||||
}
|
||||
let xref = out.len();
|
||||
let size = objs.len() + 1;
|
||||
out.extend_from_slice(format!("xref\n0 {size}\n0000000000 65535 f \n").as_bytes());
|
||||
for off in offsets {
|
||||
out.extend_from_slice(format!("{off:010} 00000 n \n").as_bytes());
|
||||
}
|
||||
out.extend_from_slice(format!("trailer\n<< /Size {size} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n").as_bytes());
|
||||
out
|
||||
}
|
||||
|
||||
fn render(bytes: Vec<u8>) -> RenderedPage {
|
||||
let page = PageRenderer::new(Arc::new(bytes), RenderConfig::default()).render(RenderRequest {
|
||||
page: 0,
|
||||
kind: RequestKind::Pixels,
|
||||
tile: None,
|
||||
scale: 1.0,
|
||||
tag: 0,
|
||||
preview: false,
|
||||
});
|
||||
assert!(page.error.is_none(), "{:?}", page.error);
|
||||
assert_eq!((page.width, page.height), (200, 200));
|
||||
page
|
||||
}
|
||||
|
||||
/// The centre pixel of each of the eight columns (indices 0 to 7), RGB.
|
||||
fn columns(page: &RenderedPage) -> [[u8; 3]; 8] {
|
||||
std::array::from_fn(|i| {
|
||||
let at = (100 * page.width as usize + 12 + 25 * i) * 4;
|
||||
let px = page.rgba.get(at..at + 3).expect("pixel inside the page");
|
||||
[px[0], px[1], px[2]]
|
||||
})
|
||||
}
|
||||
|
||||
/// The first `n` of `COLOURS`, then black: a table of `n` entries.
|
||||
fn padded(n: usize) -> [[u8; 3]; 8] {
|
||||
std::array::from_fn(|i| if i < n { COLOURS[i] } else { BLACK })
|
||||
}
|
||||
|
||||
/// Index `i` drawn as the grey level `i` / 255: the DeviceGray fallback.
|
||||
fn grey_fallback() -> [[u8; 3]; 8] {
|
||||
std::array::from_fn(|i| [i as u8; 3])
|
||||
}
|
||||
|
||||
#[track_caller]
|
||||
fn assert_page(colour_space: &str, extra: &[&[u8]], want: [[u8; 3]; 8], warned: bool) {
|
||||
let page = render(pdf(colour_space, DRAW_IMAGE, extra));
|
||||
assert_eq!(columns(&page), want, "{colour_space}: the columns");
|
||||
let want_warnings: &[RenderWarning] = if warned { &MALFORMED } else { &[] };
|
||||
assert_eq!(page.warnings, want_warnings, "{colour_space}: the warnings");
|
||||
}
|
||||
|
||||
/// Case A: a full table draws its eight colours, with no warning.
|
||||
#[test]
|
||||
fn a_full_table_draws_its_colours() {
|
||||
assert_page(&format!("[/Indexed /DeviceRGB 7 <{TABLE}>]"), &[], COLOURS, false);
|
||||
assert_page(&format!("[/Indexed /DeviceRGB 7.0 <{TABLE}>]"), &[], COLOURS, false);
|
||||
}
|
||||
|
||||
/// Cases B and F: a short table keeps the entries it holds, and an index past them is black.
|
||||
#[test]
|
||||
fn a_short_table_draws_its_entries_and_black_past_them() {
|
||||
// B: hival 7 needs 24 bytes; 6 are given. Indices 0 and 1 used to draw black.
|
||||
assert_page(&format!("[/Indexed /DeviceRGB 7 <{}>]", entries(2)), &[], padded(2), true);
|
||||
// F: one entry short.
|
||||
assert_page(&format!("[/Indexed /DeviceRGB 7 <{}>]", entries(7)), &[], padded(7), true);
|
||||
// One byte short: entry 1 is incomplete, so it is not held; indices past hival take it.
|
||||
let mut want = [BLACK; 8];
|
||||
want[0] = COLOURS[0];
|
||||
assert_page("[/Indexed /DeviceRGB 1 <FF0000 00FF>]", &[], want, true);
|
||||
}
|
||||
|
||||
/// The base space for each of the short-table tests below, with its two-entry table, and the
|
||||
/// stream objects it needs (numbered from 6).
|
||||
fn short_table_in(base: &str, table: &str) -> String {
|
||||
format!("[/Indexed {base} 7 <{table}>]")
|
||||
}
|
||||
|
||||
/// A short table over `base`: the two entries it holds draw as they do with a full table (the
|
||||
/// rest of which is white, never drawn black by a reader), and every index past them is black.
|
||||
/// Zero bytes would be white in DeviceCMYK, Separation and DeviceN, and blue in Lab.
|
||||
#[track_caller]
|
||||
fn assert_black_past_the_table(base: &str, two: &str, white: &str, extra: &[&[u8]]) {
|
||||
let full = render(pdf(&short_table_in(base, &format!("{two} {}", white.repeat(6))), DRAW_IMAGE, extra));
|
||||
assert!(full.warnings.is_empty(), "{base}: {:?}", full.warnings);
|
||||
let full = columns(&full);
|
||||
assert!(full[..2].iter().all(|c| *c != BLACK && *c != WHITE), "{base}: the two entries have colour: {full:?}");
|
||||
let page = render(pdf(&short_table_in(base, two), DRAW_IMAGE, extra));
|
||||
assert_eq!(page.warnings, MALFORMED, "{base}");
|
||||
let mut want = [BLACK; 8];
|
||||
want[..2].copy_from_slice(&full[..2]);
|
||||
assert_eq!(columns(&page), want, "{base}: entries 2 to 7 are black");
|
||||
}
|
||||
|
||||
/// DeviceGray: zero is black here, so a zero-padded table drew the same (a guard).
|
||||
#[test]
|
||||
fn indices_past_a_short_table_are_black_over_device_gray() {
|
||||
assert_black_past_the_table("/DeviceGray", "40 80", "FF ", &[]);
|
||||
}
|
||||
|
||||
/// DeviceCMYK: a zero entry would be white (no ink).
|
||||
#[test]
|
||||
fn indices_past_a_short_table_are_black_over_device_cmyk() {
|
||||
assert_black_past_the_table("/DeviceCMYK", "FF000000 00FF0000", "00000000 ", &[]);
|
||||
}
|
||||
|
||||
/// Lab: a zero entry would be L* 0 with a* and b* at the bottom of their ranges, blue.
|
||||
#[test]
|
||||
fn indices_past_a_short_table_are_black_over_lab() {
|
||||
assert_black_past_the_table("[/Lab << /WhitePoint [0.9505 1 1.089] /Range [-128 127 -128 127] >>]", "80FF80 8080FF", "FF8080 ", &[]);
|
||||
}
|
||||
|
||||
/// Separation (a spot orange: tint 1 is orange in DeviceCMYK): a zero entry would be tint 0,
|
||||
/// white.
|
||||
#[test]
|
||||
fn indices_past_a_short_table_are_black_over_separation() {
|
||||
assert_black_past_the_table(
|
||||
"[/Separation /Orange /DeviceCMYK << /FunctionType 2 /Domain [0 1] /C0 [0 0 0 0] /C1 [0 0.5 1 0] /N 1 >>]",
|
||||
"FF 80",
|
||||
"00 ",
|
||||
&[],
|
||||
);
|
||||
}
|
||||
|
||||
/// DeviceN (cyan and magenta, mapped onto DeviceCMYK by a Type 4 function): a zero entry would
|
||||
/// be white.
|
||||
#[test]
|
||||
fn indices_past_a_short_table_are_black_over_device_n() {
|
||||
let tint: &[u8] = b"<< /FunctionType 4 /Domain [0 1 0 1] /Range [0 1 0 1 0 1 0 1] /Length 9 >>\nstream\n{ 0 0 }\nendstream";
|
||||
assert_black_past_the_table("[/DeviceN [/Cyan /Magenta] /DeviceCMYK 6 0 R]", "FF00 00FF", "0000 ", &[tint]);
|
||||
}
|
||||
|
||||
/// ICCBased with four components and no usable profile, drawn in its /Alternate DeviceCMYK: a
|
||||
/// zero entry would be white.
|
||||
#[test]
|
||||
fn indices_past_a_short_table_are_black_over_icc_based_with_four_components() {
|
||||
let profile: &[u8] = b"<< /N 4 /Alternate /DeviceCMYK /Length 4 >>\nstream\nJUNK\nendstream";
|
||||
assert_black_past_the_table("[/ICCBased 6 0 R]", "FF000000 00FF0000", "00000000 ", &[profile]);
|
||||
}
|
||||
|
||||
/// Case C: an index past `hival` takes the nearest entry (ISO 32000-2 §8.6.6.3: "shall be
|
||||
/// adjusted to the nearest value within that range"); a table longer than needed is fine.
|
||||
#[test]
|
||||
fn an_index_past_hival_takes_the_last_entry() {
|
||||
let mut want = COLOURS;
|
||||
want[4..].fill(COLOURS[3]);
|
||||
assert_page(&format!("[/Indexed /DeviceRGB 3 <{TABLE}>]"), &[], want, false);
|
||||
}
|
||||
|
||||
/// Case D: a `hival` past 255 is taken as 255, and the table padded to 256 entries.
|
||||
#[test]
|
||||
fn a_hival_past_255_is_clamped() {
|
||||
assert_page(&format!("[/Indexed /DeviceRGB 300 <{TABLE}>]"), &[], COLOURS, true);
|
||||
// With a table long enough for 301 entries, the clamp alone is reported.
|
||||
let long = format!("<{TABLE}{}>", "00".repeat(3 * 293));
|
||||
assert_page(&format!("[/Indexed /DeviceRGB 300 {long}]"), &[], COLOURS, true);
|
||||
// 256, one past.
|
||||
assert_page(&format!("[/Indexed /DeviceRGB 256 <{TABLE}{}>]", "00".repeat(3 * 249)), &[], COLOURS, true);
|
||||
// 255, the largest, with a full table draws without a warning.
|
||||
assert_page(&format!("[/Indexed /DeviceRGB 255 <{TABLE}{}>]", "00".repeat(3 * 248)), &[], COLOURS, false);
|
||||
}
|
||||
|
||||
/// Case E: a real `hival` is truncated toward zero, as hayro read it before patch (80).
|
||||
#[test]
|
||||
fn a_real_hival_is_truncated() {
|
||||
assert_page(&format!("[/Indexed /DeviceRGB 7.5 <{TABLE}>]"), &[], COLOURS, true);
|
||||
// 6.9 is 6, not 7: index 7 takes entry 6.
|
||||
let mut want = COLOURS;
|
||||
want[7] = COLOURS[6];
|
||||
assert_page(&format!("[/Indexed /DeviceRGB 6.9 <{TABLE}>]"), &[], want, true);
|
||||
// -0.5 is 0 (toward zero; a real above -1 truncates to 0): every index takes entry 0.
|
||||
assert_page(&format!("[/Indexed /DeviceRGB -0.5 <{TABLE}>]"), &[], [COLOURS[0]; 8], true);
|
||||
// 255.5 is 255; 255.0 written as a real is the integer 255.
|
||||
let full = format!("<{TABLE}{}>", "00".repeat(3 * 248));
|
||||
assert_page(&format!("[/Indexed /DeviceRGB 255.5 {full}]"), &[], COLOURS, true);
|
||||
assert_page(&format!("[/Indexed /DeviceRGB 255.0 {full}]"), &[], COLOURS, false);
|
||||
}
|
||||
|
||||
/// Case G: inline images, named through the resources or given in place, are recovered too, and
|
||||
/// skipped when the space has no table.
|
||||
#[test]
|
||||
fn inline_images_with_a_short_table_are_recovered_too() {
|
||||
let inline = |cs: &str| format!("q 200 0 0 200 0 0 cm BI /W 8 /H 1 /BPC 8 /CS {cs} /F /AHx ID 0001020304050607> EI Q");
|
||||
let short = format!("[/Indexed /DeviceRGB 7 <{}>]", entries(2));
|
||||
// Named through the page's resources.
|
||||
let page = render(pdf_with_resource("CS0", &short, &inline("/CS0"), &[]));
|
||||
assert_eq!(columns(&page), padded(2));
|
||||
assert_eq!(page.warnings, MALFORMED);
|
||||
// Given in place, with the inline abbreviations.
|
||||
let page = render(pdf("/DeviceRGB", &inline(&format!("[/I /RGB 7 <{}>]", entries(2))), &[]));
|
||||
assert_eq!(columns(&page), padded(2));
|
||||
assert_eq!(page.warnings, MALFORMED);
|
||||
// A `hival` with no reading falls back and is reported, named or in place.
|
||||
let page = render(pdf(&format!("[/Indexed /DeviceRGB -1 <{TABLE}>]"), &inline("/P"), &[]));
|
||||
assert_eq!((columns(&page), page.warnings), (grey_fallback(), MALFORMED.to_vec()));
|
||||
let page = render(pdf("/DeviceRGB", &inline(&format!("[/I /RGB -1 <{TABLE}>]")), &[]));
|
||||
assert_eq!((columns(&page), page.warnings), (grey_fallback(), MALFORMED.to_vec()));
|
||||
// No table: not drawn, named or in place.
|
||||
let page = render(pdf("[/Indexed /DeviceRGB 7 null]", &inline("/P"), &[]));
|
||||
assert_eq!((columns(&page), page.warnings), ([WHITE; 8], MALFORMED.to_vec()));
|
||||
let page = render(pdf("/DeviceRGB", &inline("[/I /RGB 7]"), &[]));
|
||||
assert_eq!((columns(&page), page.warnings), ([WHITE; 8], MALFORMED.to_vec()));
|
||||
// A well-formed one draws without a warning.
|
||||
let page = render(pdf(&format!("[/Indexed /DeviceRGB 7 <{TABLE}>]"), &inline("/P"), &[]));
|
||||
assert_eq!(columns(&page), COLOURS);
|
||||
assert!(page.warnings.is_empty(), "{:?}", page.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_inline_device_space_name_ignores_a_resource_of_the_same_name() {
|
||||
// ISO 32000-2 §8.6.8 (the CS operator): the device colour space names never refer to
|
||||
// resources in the ColorSpace subdictionary, so a malformed Indexed resource that shares the
|
||||
// name (here the inline abbreviation `/RGB`, and `/DeviceRGB`) is not used.
|
||||
let data: String = TABLE.split(' ').collect();
|
||||
for (resource, cs) in [("RGB", "/RGB"), ("DeviceRGB", "/DeviceRGB")] {
|
||||
let content = format!("q 200 0 0 200 0 0 cm BI /W 8 /H 1 /BPC 8 /CS {cs} /F /AHx ID {data}> EI Q");
|
||||
let page = render(pdf_with_resource(resource, "[/Indexed /DeviceRGB 7 <FF0000 00FF00>]", &content, &[]));
|
||||
assert_eq!(columns(&page), COLOURS, "{cs}: the device space draws");
|
||||
assert!(page.warnings.is_empty(), "{cs}: {:?}", page.warnings);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_page_with_several_malformed_images_reports_the_warning_once() {
|
||||
let content = format!("{DRAW_IMAGE} {DRAW_IMAGE} 0 0 1 rg 0 0 10 10 re f");
|
||||
let page = render(pdf(&format!("[/Indexed /DeviceRGB 7 <{}>]", entries(2)), &content, &[]));
|
||||
assert_eq!(page.warnings, MALFORMED);
|
||||
assert_eq!(columns(&page), padded(2));
|
||||
let at = (195 * page.width as usize + 5) * 4;
|
||||
assert_eq!(page.rgba.get(at..at + 3), Some(&[0u8, 0, 255][..]), "content after the images still draws");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_lookup_string_given_by_reference_is_read() {
|
||||
// A lookup is a byte string or a stream (ISO 32000-2 §8.6.6.3), and either may be indirect.
|
||||
// A string by reference used to be missed: trying it as a stream consumed the reference.
|
||||
let full = format!("<{TABLE}>");
|
||||
assert_page("[/Indexed /DeviceRGB 7 6 0 R]", &[full.as_bytes()], COLOURS, false);
|
||||
let short = format!("<{}>", entries(2));
|
||||
assert_page("[/Indexed /DeviceRGB 7 6 0 R]", &[short.as_bytes()], padded(2), true);
|
||||
// Something that is neither a string nor a stream is no table: the image is not drawn.
|
||||
assert_page("[/Indexed /DeviceRGB 7 6 0 R]", &[b"42"], [WHITE; 8], true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_table_size_holds_at_the_bounds_of_hival_and_the_base() {
|
||||
// Four components (DeviceCMYK): hival 1 needs 8 bytes. With 7, entry 1 is incomplete, so it
|
||||
// is not held: index 1, and the indices past hival that take it, are black.
|
||||
let full = render(pdf("[/Indexed /DeviceCMYK 1 <FF000000 00FF0000>]", DRAW_IMAGE, &[]));
|
||||
assert!(full.warnings.is_empty(), "{:?}", full.warnings);
|
||||
assert_ne!(columns(&full)[0], WHITE, "the image is drawn");
|
||||
let short = render(pdf("[/Indexed /DeviceCMYK 1 <FF000000 00FF00>]", DRAW_IMAGE, &[]));
|
||||
assert_eq!(short.warnings, MALFORMED);
|
||||
let mut want = [BLACK; 8];
|
||||
want[0] = columns(&full)[0];
|
||||
assert_eq!(columns(&short), want);
|
||||
// One component (DeviceGray): hival 0 needs one byte; an empty table holds no entry.
|
||||
assert_page("[/Indexed /DeviceGray 0 <80>]", &[], [[128; 3]; 8], false);
|
||||
assert_page("[/Indexed /DeviceGray 0 <>]", &[], [BLACK; 8], true);
|
||||
// hival 255 over DeviceRGB needs 768 bytes: 767 is one short.
|
||||
assert_page(&format!("[/Indexed /DeviceRGB 255 <{TABLE}{}>]", "00".repeat(3 * 248 - 1)), &[], COLOURS, true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hival_that_would_overflow_a_size_is_clamped_without_panicking() {
|
||||
// Values whose (hival + 1) × components would overflow a 32-bit or 64-bit size, or that do
|
||||
// not fit an integer at all, are taken as 255.
|
||||
for hival in ["4294967295", "4294967296", "18446744073709551615", "99999999999999999999999"] {
|
||||
assert_page(&format!("[/Indexed /DeviceRGB {hival} <{}>]", entries(2)), &[], padded(2), true);
|
||||
}
|
||||
}
|
||||
|
||||
/// A `hival` that is negative or not a number has no reading to recover: the image keeps the
|
||||
/// upstream handling (it falls back to DeviceGray), and the warning is still reported.
|
||||
#[test]
|
||||
fn a_negative_or_non_numeric_hival_falls_back_with_a_warning() {
|
||||
for hival in ["-1", "-1.5", "-2147483649", "/One", "null"] {
|
||||
assert_page(&format!("[/Indexed /DeviceRGB {hival} <{TABLE}>]"), &[], grey_fallback(), true);
|
||||
}
|
||||
}
|
||||
|
||||
/// An empty string is a table that holds no entry: every index is black.
|
||||
#[test]
|
||||
fn an_empty_table_draws_black() {
|
||||
for lookup in ["<>", "()"] {
|
||||
assert_page(&format!("[/Indexed /DeviceRGB 1 {lookup}]"), &[], padded(0), true);
|
||||
}
|
||||
}
|
||||
|
||||
/// A lookup that is missing, `null` or a number is no table at all: the image is not drawn (the
|
||||
/// page stays white), and the warning is reported.
|
||||
#[test]
|
||||
fn a_missing_lookup_skips_the_image() {
|
||||
for lookup in ["", "null", "42"] {
|
||||
assert_page(&format!("[/Indexed /DeviceRGB 7 {lookup}]"), &[], [WHITE; 8], true);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_lookup_stream_is_measured_after_decoding() {
|
||||
let short: &[u8] = b"<< /Length 14 /Filter /ASCIIHexDecode >>\nstream\nFF0000 00FF00>\nendstream";
|
||||
assert_page("[/Indexed /DeviceRGB 7 6 0 R]", &[short], padded(2), true);
|
||||
let mut want = [COLOURS[1]; 8];
|
||||
want[0] = COLOURS[0];
|
||||
assert_page("[/Indexed /DeviceRGB 1 6 0 R]", &[short], want, false);
|
||||
// An empty stream decodes to an empty table, which holds no entry.
|
||||
let empty: &[u8] = b"<< /Length 0 >>\nstream\n\nendstream";
|
||||
assert_page("[/Indexed /DeviceRGB 1 6 0 R]", &[empty], padded(0), true);
|
||||
}
|
||||
|
||||
/// A stream that does not decode is no table: the image is not drawn, and is reported.
|
||||
#[test]
|
||||
fn a_lookup_stream_that_cannot_be_decoded_skips_the_image() {
|
||||
for broken in [
|
||||
&b"<< /Length 12 /Filter /FlateDecode >>\nstream\nnot deflated\nendstream"[..],
|
||||
b"<< /Length 6 /Filter /FlateDecode >>\nstream\nnot-zl\nendstream",
|
||||
] {
|
||||
assert_page("[/Indexed /DeviceRGB 7 6 0 R]", &[broken], [WHITE; 8], true);
|
||||
}
|
||||
}
|
||||
|
||||
/// An Indexed space whose base cannot be read keeps the upstream handling (DeviceGray), whatever
|
||||
/// its `hival`; only a `hival` with no reading is reported.
|
||||
#[test]
|
||||
fn an_unreadable_base_keeps_its_fallback() {
|
||||
for (hival, warned) in [("1", false), ("300", false), ("-1", true)] {
|
||||
assert_page(&format!("[/Indexed /NoSuchSpace {hival} <{TABLE}>]"), &[], grey_fallback(), warned);
|
||||
}
|
||||
}
|
||||
|
||||
/// A fill or stroke colour set in such a space (`cs`, `sc`, `CS`, `SC`) draws through the same
|
||||
/// recovered table, and the recovery is reported as `ColourFallback`, as the upstream DeviceGray
|
||||
/// fallback was.
|
||||
#[test]
|
||||
fn a_fill_or_stroke_colour_in_a_short_table_is_recovered_and_reported() {
|
||||
let fill = |index: u8| format!("/P cs {index} sc 0 0 200 200 re f");
|
||||
let short = format!("[/Indexed /DeviceRGB 7 <{}>]", entries(2));
|
||||
let page = render(pdf(&short, &fill(1), &[]));
|
||||
assert_eq!(columns(&page)[0], COLOURS[1], "entry 1 is green");
|
||||
assert_eq!(page.warnings, vec![RenderWarning::ColourFallback]);
|
||||
let page = render(pdf(&short, &fill(5), &[]));
|
||||
assert_eq!(columns(&page)[0], BLACK, "entry 5 is past the table");
|
||||
// Over DeviceCMYK too, where a zero entry would be white.
|
||||
let cmyk = "[/Indexed /DeviceCMYK 7 <FF000000 00FF0000>]";
|
||||
let page = render(pdf(cmyk, &fill(5), &[]));
|
||||
assert_eq!(columns(&page)[0], BLACK, "DeviceCMYK entry 5 is past the table");
|
||||
// A stroke colour (`CS`, `SC`) the same way.
|
||||
let page = render(pdf(&short, "/P CS 1 SC 20 w 0 100 m 200 100 l S", &[]));
|
||||
assert_eq!(columns(&page)[0], COLOURS[1], "the stroke is green");
|
||||
assert_eq!(page.warnings, vec![RenderWarning::ColourFallback]);
|
||||
let page = render(pdf(&format!("[/Indexed /DeviceRGB 7 <{TABLE}>]"), &fill(1), &[]));
|
||||
assert_eq!(columns(&page)[0], COLOURS[1]);
|
||||
assert!(page.warnings.is_empty(), "{:?}", page.warnings);
|
||||
}
|
||||
|
||||
/// A fill colour in an Indexed space with no lookup table keeps the upstream fallback: DeviceGray,
|
||||
/// reported as `ColourFallback` (tint 1 is white, over a red fill).
|
||||
#[test]
|
||||
fn a_fill_colour_in_a_space_with_no_table_keeps_the_fallback() {
|
||||
for lookup in ["", "null"] {
|
||||
let content = "1 0 0 rg 0 0 200 200 re f /P cs 1 sc 0 0 200 200 re f";
|
||||
let page = render(pdf(&format!("[/Indexed /DeviceRGB 7 {lookup}]"), content, &[]));
|
||||
assert_eq!(columns(&page)[0], WHITE, "{lookup:?}: DeviceGray 1");
|
||||
assert_eq!(page.warnings, vec![RenderWarning::ColourFallback], "{lookup:?}");
|
||||
// A stroke colour the same way.
|
||||
let content = "1 0 0 rg 0 0 200 200 re f /P CS 1 SC 20 w 0 100 m 200 100 l S";
|
||||
let page = render(pdf(&format!("[/Indexed /DeviceRGB 7 {lookup}]"), content, &[]));
|
||||
assert_eq!(columns(&page)[0], WHITE, "{lookup:?}: a DeviceGray 1 stroke");
|
||||
assert_eq!(page.warnings, vec![RenderWarning::ColourFallback], "{lookup:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Only images and the colour operators handle a space with no table: anything else reads it as
|
||||
/// upstream did, as a space that cannot be read. A shading in one is not drawn.
|
||||
#[test]
|
||||
fn a_shading_in_a_space_with_no_table_is_not_drawn() {
|
||||
let shading = |cs: &str| {
|
||||
format!(
|
||||
"/Shading << /Sh << /ShadingType 2 /ColorSpace {cs} /Coords [0 0 200 0] \
|
||||
/Function << /FunctionType 2 /Domain [0 1] /C0 [0] /C1 [1] /N 1 >> /Extend [true true] >> >>"
|
||||
)
|
||||
};
|
||||
let page = render(pdf_with_resources("P", "/DeviceRGB", &shading("[/Indexed /DeviceRGB 1 null]"), "/Sh sh", &[]));
|
||||
assert_eq!(columns(&page), [WHITE; 8]);
|
||||
// The same shading with a table draws.
|
||||
let page = render(pdf_with_resources("P", "/DeviceRGB", &shading("[/Indexed /DeviceRGB 1 <FF0000 00FF00>]"), "/Sh sh", &[]));
|
||||
assert_ne!(columns(&page), [WHITE; 8]);
|
||||
}
|
||||
@@ -2,7 +2,9 @@
|
||||
|
||||
mod cid_cff_unusable_font_dict;
|
||||
mod cid_fallback_query;
|
||||
mod euro_width;
|
||||
mod fill_stroke_knockout;
|
||||
mod indexed_lookup;
|
||||
mod inline_image_ei;
|
||||
mod jbig2_invariants;
|
||||
mod knockout_backdrop;
|
||||
@@ -15,9 +17,12 @@ mod search;
|
||||
mod separation_all;
|
||||
mod stray_q_in_a_form;
|
||||
mod stroke_degenerate_cubic;
|
||||
mod stroke_geometry;
|
||||
mod stroke_zero_end_tangent;
|
||||
mod substitute_widths;
|
||||
mod symbol_dingbats_width;
|
||||
mod symbol_mt_builtin_encoding;
|
||||
mod tiling_cell_placement;
|
||||
mod type3_text_clip;
|
||||
mod widgets_above_annotations;
|
||||
mod zero_area_fill_clip;
|
||||
|
||||
@@ -88,68 +88,172 @@ const UNSPACED_BLOCK_SAMPLES: &[(char, bool, &str)] = &[
|
||||
('\u{323AF}', true, "CJK Unified Ideographs Extension H (31350..323AF), last"),
|
||||
];
|
||||
|
||||
// The original straightforward search is an independent oracle for valid page metadata.
|
||||
// The original straightforward search is an independent oracle for valid page metadata, extended
|
||||
// with ligature letters and the three readings of a line-end hyphen between letters: as written,
|
||||
// joined (no hyphen, no break) and kept (hyphen, no break).
|
||||
fn reference(page: &PageText, query: &str, sensitive: bool, whole: bool, limit: usize) -> Vec<Range<usize>> {
|
||||
let fold = |s: &str| if sensitive { s.to_owned() } else { fold_case(s) };
|
||||
let letters = |s: &str| {
|
||||
s.replace('\u{FB00}', "ff")
|
||||
.replace('\u{FB01}', "fi")
|
||||
.replace('\u{FB02}', "fl")
|
||||
.replace('\u{FB03}', "ffi")
|
||||
.replace('\u{FB04}', "ffl")
|
||||
.replace(['\u{FB05}', '\u{FB06}'], "st")
|
||||
};
|
||||
let fold = |s: &str| if sensitive { letters(s) } else { fold_case(&letters(s)) };
|
||||
// Soft hyphens and zero width characters draw nothing and are skipped on both sides.
|
||||
let visible =
|
||||
|s: String| s.chars().filter(|c| !matches!(c, '\u{AD}' | '\u{200B}' | '\u{200C}' | '\u{200D}' | '\u{2060}' | '\u{FEFF}')).collect::<String>();
|
||||
let invisible = |c: char| matches!(c, '\u{AD}' | '\u{200B}' | '\u{200C}' | '\u{200D}' | '\u{2060}' | '\u{FEFF}');
|
||||
let visible = |s: String| s.chars().filter(|&c| !invisible(c)).collect::<String>();
|
||||
let needle: Vec<char> = visible(fold(query)).split_whitespace().collect::<Vec<_>>().join(" ").chars().collect();
|
||||
if needle.is_empty() || limit == 0 {
|
||||
return Vec::new();
|
||||
}
|
||||
// Each character, its glyph, and whether a skipped zero width space came right before it.
|
||||
let mut chars: Vec<(char, usize, bool)> = Vec::new();
|
||||
let mut after_zwsp = false;
|
||||
for (i, glyph) in page.glyphs.iter().enumerate() {
|
||||
// A line that ends in a soft hyphen, past any empty or other invisible glyphs and
|
||||
// characters after it on that line, runs on to the next.
|
||||
let ends_in_soft_hyphen = |end: usize| {
|
||||
(0..=end)
|
||||
.rev()
|
||||
.take_while(|&k| page.line_of[k] == page.line_of[end])
|
||||
.flat_map(|k| page.glyphs[k].text.chars().rev())
|
||||
.find(|&c| c == '\u{AD}' || !visible(c.to_string()).is_empty())
|
||||
== Some('\u{AD}')
|
||||
};
|
||||
let line_break = i > 0 && page.line_of[i] != page.line_of[i - 1] && !ends_in_soft_hyphen(i - 1);
|
||||
if i > 0 && (page.space_before[i] || line_break) && chars.last().is_some_and(|&(c, ..)| c != ' ') {
|
||||
chars.push((' ', i, false));
|
||||
after_zwsp = false;
|
||||
}
|
||||
for c in fold(&glyph.text).chars() {
|
||||
after_zwsp |= c == '\u{200B}';
|
||||
if visible(c.to_string()).is_empty() {
|
||||
continue;
|
||||
}
|
||||
let c = if c.is_whitespace() { ' ' } else { c };
|
||||
if c != ' ' || chars.last().is_none_or(|&(last, ..)| last != ' ') {
|
||||
chars.push((c, i, after_zwsp && c != ' '));
|
||||
let texts: Vec<String> = page.glyphs.iter().map(|g| fold(&g.text)).collect();
|
||||
let n = texts.len();
|
||||
let new_line = |i: usize| i > 0 && page.line_of[i] != page.line_of[i - 1];
|
||||
// A line that ends in a soft hyphen, past any empty or other invisible glyphs and characters
|
||||
// after it on that line, runs on to the next.
|
||||
let ends_in_soft_hyphen = |end: usize| {
|
||||
(0..=end)
|
||||
.rev()
|
||||
.take_while(|&k| page.line_of[k] == page.line_of[end])
|
||||
.flat_map(|k| page.glyphs[k].text.chars().rev())
|
||||
.find(|&c| c == '\u{AD}' || !invisible(c))
|
||||
== Some('\u{AD}')
|
||||
};
|
||||
// A visible hyphen between letters at a line end.
|
||||
let hyphen = |c: char| matches!(c, '-' | '\u{2010}');
|
||||
let divided: Vec<bool> = (0..n)
|
||||
.map(|i| {
|
||||
let chars: Vec<char> = visible(texts[i].clone()).chars().collect();
|
||||
let Some(&last) = chars.last() else { return false };
|
||||
let before = if chars.len() >= 2 {
|
||||
Some(chars[chars.len() - 2])
|
||||
} else if i > 0 && !page.space_before[i] && !new_line(i) {
|
||||
visible(texts[i - 1].clone()).chars().last()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
hyphen(last)
|
||||
&& before.is_some_and(char::is_alphabetic)
|
||||
&& i + 1 < n
|
||||
&& new_line(i + 1)
|
||||
&& visible(texts[i + 1].clone()).chars().next().is_some_and(char::is_alphabetic)
|
||||
})
|
||||
.collect();
|
||||
let mut all = Vec::new();
|
||||
let readings = if divided.contains(&true) { 3 } else { 1 };
|
||||
for reading in 0..readings {
|
||||
// Each character, its glyph, and whether a skipped zero width space came right before it.
|
||||
let mut chars: Vec<(char, usize, bool)> = Vec::new();
|
||||
let mut after_zwsp = false;
|
||||
for i in 0..n {
|
||||
let joined = reading > 0 && i > 0 && divided[i - 1];
|
||||
let line_break = new_line(i) && !ends_in_soft_hyphen(i - 1) && !joined;
|
||||
if i > 0 && (page.space_before[i] || line_break) && chars.last().is_some_and(|&(c, ..)| c != ' ') {
|
||||
chars.push((' ', i, false));
|
||||
after_zwsp = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
// A neighbour bounds a word only in a script written with spaces between words, or when it
|
||||
// is a digit.
|
||||
let word = |i: Option<usize>| i.and_then(|i| chars.get(i)).is_some_and(|&(c, ..)| c.is_alphanumeric() && (c.is_numeric() || !unspaced(c)));
|
||||
// A word ends at a skipped zero width space as it does at a space.
|
||||
let edge = |i: usize| chars.get(i).is_some_and(|&(.., zwsp)| zwsp);
|
||||
let mut hits = Vec::new();
|
||||
let mut start = 0;
|
||||
while start + needle.len() <= chars.len() {
|
||||
let end = start + needle.len();
|
||||
let bounded = (edge(start) || !word(start.checked_sub(1))) && (edge(end) || !word(Some(end)));
|
||||
if (!whole || bounded) && chars[start..end].iter().map(|&(c, ..)| c).eq(needle.iter().copied()) {
|
||||
hits.push(chars[start].1..chars[end - 1].1 + 1);
|
||||
if hits.len() == limit {
|
||||
break;
|
||||
let mut glyph: Vec<char> = texts[i].chars().collect();
|
||||
if reading == 1 && divided[i] {
|
||||
// The hyphen: the last visible character.
|
||||
if let Some(at) = glyph.iter().rposition(|&c| !invisible(c)) {
|
||||
glyph.remove(at);
|
||||
}
|
||||
}
|
||||
start = end;
|
||||
} else {
|
||||
start += 1;
|
||||
for c in glyph {
|
||||
after_zwsp |= c == '\u{200B}';
|
||||
if invisible(c) {
|
||||
continue;
|
||||
}
|
||||
let c = if c.is_whitespace() { ' ' } else { c };
|
||||
if c != ' ' || chars.last().is_none_or(|&(last, ..)| last != ' ') {
|
||||
chars.push((c, i, after_zwsp && c != ' '));
|
||||
after_zwsp = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
// A neighbour bounds a word only in a script written with spaces between words, or when it
|
||||
// is a digit.
|
||||
let word = |i: Option<usize>| i.and_then(|i| chars.get(i)).is_some_and(|&(c, ..)| c.is_alphanumeric() && (c.is_numeric() || !unspaced(c)));
|
||||
// A word ends at a skipped zero width space as it does at a space.
|
||||
let edge = |i: usize| chars.get(i).is_some_and(|&(.., zwsp)| zwsp);
|
||||
let mut hits = Vec::new();
|
||||
let mut start = 0;
|
||||
while start + needle.len() <= chars.len() {
|
||||
let end = start + needle.len();
|
||||
let bounded = (edge(start) || !word(start.checked_sub(1))) && (edge(end) || !word(Some(end)));
|
||||
if (!whole || bounded) && chars[start..end].iter().map(|&(c, ..)| c).eq(needle.iter().copied()) {
|
||||
hits.push(chars[start].1..chars[end - 1].1 + 1);
|
||||
if hits.len() == limit {
|
||||
break;
|
||||
}
|
||||
start = end;
|
||||
} else {
|
||||
start += 1;
|
||||
}
|
||||
}
|
||||
all.push(hits);
|
||||
}
|
||||
if readings == 1 {
|
||||
return all.remove(0);
|
||||
}
|
||||
// A hit is left out where it overlaps one kept from another reading; one reading's hits are
|
||||
// all kept, though two can share a glyph.
|
||||
let mut hits: Vec<(Range<usize>, usize)> = all.into_iter().enumerate().flat_map(|(r, hits)| hits.into_iter().map(move |h| (h, r))).collect();
|
||||
hits.sort_by_key(|(h, _)| (h.start, std::cmp::Reverse(h.end)));
|
||||
let mut out: Vec<(Range<usize>, usize)> = Vec::new();
|
||||
for (h, r) in hits {
|
||||
let overlaps = out.iter().any(|(k, kr)| *kr != r && h.start < k.end && k.start < h.end);
|
||||
if !overlaps && out.len() < limit {
|
||||
out.push((h, r));
|
||||
}
|
||||
}
|
||||
hits
|
||||
out.into_iter().map(|(h, _)| h).collect()
|
||||
}
|
||||
|
||||
/// One glyph per entry of `text`, each on the line given in `lines`.
|
||||
fn lined(text: &[&str], lines: &[u32]) -> PageText {
|
||||
let mut p = page(text);
|
||||
p.line_of = lines.to_vec();
|
||||
p
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_ligature_matches_its_letters() {
|
||||
let text = page(&["o", "\u{FB03}", "c", "e", " ", "o", "f", "\u{FB01}", "c", "e"]);
|
||||
assert_eq!(text.find("office"), vec![0..4, 5..10]);
|
||||
assert_eq!(text.find("OFFICE"), vec![0..4, 5..10]);
|
||||
assert_eq!(text.find_opts("office", true, true), vec![0..4, 5..10], "case-sensitive and whole words too");
|
||||
assert_eq!(text.find("o\u{FB03}ce"), vec![0..4, 5..10], "a ligature in the query reads as its letters too");
|
||||
assert_eq!(text.find("fi"), vec![1..2, 7..8], "a match inside a ligature takes its glyph");
|
||||
assert!(text.find("o\u{FB13}").is_empty(), "no other compatibility folding");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_word_divided_by_a_line_end_hyphen_matches_whole_and_as_written() {
|
||||
// "exam-" ends line 0, "ple" starts line 1; the hyphen is its own glyph.
|
||||
let text = lined(&["e", "x", "a", "m", "-", "p", "l", "e"], &[0, 0, 0, 0, 0, 1, 1, 1]);
|
||||
assert_eq!(text.find("example"), vec![0..8], "both parts, and the hyphen between them");
|
||||
assert_eq!(text.find_opts("example", false, true), vec![0..8], "a whole word");
|
||||
assert_eq!(text.find("exam-ple"), vec![0..8], "a query with the hyphen");
|
||||
assert_eq!(text.find("exam- ple"), vec![0..8], "and with the line break as a space");
|
||||
assert_eq!(text.find("exam"), vec![0..4]);
|
||||
// The hyphen in the glyph of the last letter, a soft hyphen and U+2010.
|
||||
for hyphen in ["m-", "m\u{AD}", "m\u{2010}"] {
|
||||
let text = lined(&["e", "x", "a", hyphen, "p", "l", "e"], &[0, 0, 0, 0, 1, 1, 1]);
|
||||
assert_eq!(text.find("example"), vec![0..7], "{hyphen:?}");
|
||||
}
|
||||
// Not divided: a hyphen inside a line, a dash after a word gap, a hyphen between digits.
|
||||
assert!(page(&["e", "x", "a", "m", "-", "p", "l", "e"]).find("example").is_empty(), "inside a line");
|
||||
let mut spaced = lined(&["e", "x", "a", "m", "-", "p", "l", "e"], &[0, 0, 0, 0, 0, 1, 1, 1]);
|
||||
spaced.space_before[4] = true;
|
||||
assert!(spaced.find("example").is_empty(), "a dash after a word gap");
|
||||
assert!(spaced.find("exam ple").is_empty(), "a dash after a word gap is never dropped");
|
||||
assert!(lined(&["1", "0", "-", "2", "0"], &[0, 0, 0, 1, 1]).find("1020").is_empty(), "between digits");
|
||||
assert!(lined(&["a", "-", "2", "0"], &[0, 0, 1, 1]).find("a20").is_empty(), "before a number");
|
||||
assert!(lined(&["1", "0", "-", "a", "b"], &[0, 0, 0, 1, 1]).find("10ab").is_empty(), "after a number");
|
||||
assert!(lined(&["a", "-"], &[0, 0]).find("a-").len() == 1, "at the end of the page");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -171,6 +275,10 @@ fn whole_word_rejection_keeps_overlapping_candidates() {
|
||||
// Accepted matches still do not overlap, even within one multi-character glyph.
|
||||
assert_eq!(page(&["aaaaa"]).find("aaa"), vec![0..1]);
|
||||
assert_eq!(page(&["aaaaa"]).find("aa"), vec![0..1, 0..1]);
|
||||
// So does a page with a word divided at a line end, which is searched in three readings.
|
||||
let divided = lined(&["\u{FB03}", " ", "exam", "-", "ple"], &[0, 0, 0, 0, 1]);
|
||||
assert_eq!(divided.find("f"), vec![0..1, 0..1]);
|
||||
assert_eq!(divided.find("example"), vec![2..5]);
|
||||
}
|
||||
|
||||
/// A letter from a block in `UNSPACED_BLOCK_SAMPLES` next to a whole-word match leaves it standing
|
||||
@@ -191,6 +299,8 @@ fn whole_words_follow_the_unicode_blocks_of_unspaced_scripts() {
|
||||
#[test]
|
||||
fn search_matches_reference_for_unicode_gaps_limits_and_word_boundaries() {
|
||||
let alphabet = ["a", "b", " ", "-", "İ", "ı", "ς", "Σ", "\t", "\n", "ffi", "", "界", "ก", "한", "e\u{301}", "العربية", "\u{AD}", "a\u{200B}"];
|
||||
// Ligatures, digits and HYPHEN exercise the readings of a line-end hyphen.
|
||||
let alphabet: Vec<&str> = alphabet.into_iter().chain(["\u{FB01}", "1", "\u{2010}"]).collect();
|
||||
let mut seed = 1234567u64;
|
||||
let mut next = || {
|
||||
seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1);
|
||||
|
||||
@@ -0,0 +1,295 @@
|
||||
//! Stroke geometry the renderer gets from the graphics state: degenerate subpaths and their line
|
||||
//! caps (ISO 32000-2 §8.5.3.2), dash arrays that are all zero or otherwise invalid (§8.4.3.6) and
|
||||
//! line widths below zero (§8.4.3.2). Vendored hayro-interpret patch 61.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use hayro::hayro_interpret::font::Glyph;
|
||||
use hayro::hayro_interpret::hayro_syntax::Pdf;
|
||||
use hayro::hayro_interpret::{
|
||||
BlendMode, ClipPath, Context, Device, GlyphDrawMode, Image, InterpreterCache, InterpreterSettings, Paint, PathDrawMode, SoftMask, StrokeProps,
|
||||
TransformExt, interpret_page,
|
||||
};
|
||||
use kurbo::{Affine, BezPath, Rect};
|
||||
use pdfcraft_render::{PageRenderer, RenderConfig, RenderRequest, RenderedPage, RequestKind};
|
||||
|
||||
const WHITE: [u8; 4] = [255, 255, 255, 255];
|
||||
const BLUE: [u8; 4] = [0, 0, 255, 255];
|
||||
|
||||
/// Renders `content` on a 40 × 40 pt page at 1 px per pt, with `gs1` as the ExtGState `/GS1`.
|
||||
fn render(content: &str, gs1: &str) -> RenderedPage {
|
||||
let pdf = format!(
|
||||
"%PDF-1.7
|
||||
1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj
|
||||
2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj
|
||||
3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 40 40] /Contents 4 0 R /Resources << /ExtGState << /GS1 {gs1} >> >> >> endobj
|
||||
4 0 obj << /Length {} >> stream
|
||||
{content}
|
||||
endstream endobj
|
||||
trailer << /Root 1 0 R >>
|
||||
%%EOF",
|
||||
content.len()
|
||||
);
|
||||
let mut r = PageRenderer::new(Arc::new(pdf.into_bytes()), RenderConfig::default());
|
||||
let page = r.render(RenderRequest { page: 0, kind: RequestKind::Pixels, tile: None, scale: 1.0, tag: 0, ..Default::default() });
|
||||
assert!(page.error.is_none(), "{:?}", page.error);
|
||||
assert_eq!((page.width, page.height), (40, 40));
|
||||
page
|
||||
}
|
||||
|
||||
/// The pixel at device (x, y), y down.
|
||||
fn px(page: &RenderedPage, x: usize, y: usize) -> [u8; 4] {
|
||||
let i = (y * 40 + x) * 4;
|
||||
let mut out = [0; 4];
|
||||
out.copy_from_slice(&page.rgba[i..i + 4]);
|
||||
out
|
||||
}
|
||||
|
||||
/// How many pixels are not white.
|
||||
fn inked(page: &RenderedPage) -> usize {
|
||||
page.rgba.as_chunks::<4>().0.iter().filter(|p| **p != WHITE).count()
|
||||
}
|
||||
|
||||
/// §8.5.3.2: a degenerate subpath (a single-point closed path, or points that all coincide) is
|
||||
/// painted as a filled circle of the line width when the caps are round, and not at all with butt
|
||||
/// or projecting square caps. User-space point (20, 20) is device pixel (20, 20); a 10 pt round
|
||||
/// dot covers (20 ± 4, 20) and (20, 20 ± 4) but not the square's corner (24, 24).
|
||||
#[test]
|
||||
fn degenerate_subpaths_draw_a_round_dot_or_nothing() {
|
||||
let round = [
|
||||
("m l to the same point", "0 0 1 RG 10 w 1 J 20 20 m 20 20 l S"),
|
||||
("m h, a single-point closed path", "0 0 1 RG 10 w 1 J 20 20 m h S"),
|
||||
("m h by s", "0 0 1 RG 10 w 1 J 20 20 m s"),
|
||||
("m c with every point the same", "0 0 1 RG 10 w 1 J 20 20 m 20 20 20 20 20 20 c S"),
|
||||
("m l l h at one point", "0 0 1 RG 10 w 1 J 20 20 m 20 20 l 20 20 l h S"),
|
||||
("a 0 × 0 re", "0 0 1 RG 10 w 1 J 20 20 0 0 re S"),
|
||||
];
|
||||
for (what, content) in round {
|
||||
let page = render(content, "<< >>");
|
||||
for (x, y) in [(20, 20), (16, 20), (23, 20), (20, 16), (20, 23)] {
|
||||
assert_eq!(px(&page, x, y), BLUE, "{what}, round caps: ({x}, {y}) is inside the dot");
|
||||
}
|
||||
assert_eq!(px(&page, 24, 24), WHITE, "{what}, round caps: the dot is round, not square");
|
||||
assert_eq!(px(&page, 27, 20), WHITE, "{what}, round caps: the dot is the line width across");
|
||||
}
|
||||
for cap in ["0 J", "2 J"] {
|
||||
for (what, content) in round {
|
||||
let content = content.replace("1 J", cap);
|
||||
assert_eq!(inked(&render(&content, "<< >>")), 0, "{what} with {cap}: nothing is painted");
|
||||
}
|
||||
}
|
||||
// A single-point open subpath (a trailing m) paints nothing whatever the cap.
|
||||
assert_eq!(inked(&render("0 0 1 RG 10 w 1 J 20 20 m S", "<< >>")), 0, "a lone m");
|
||||
}
|
||||
|
||||
/// Only the degenerate subpaths of a path change: the line drawn with them keeps its caps, and a
|
||||
/// line whose ends differ by a hair is not degenerate.
|
||||
#[test]
|
||||
fn degenerate_subpaths_leave_the_rest_of_the_path_alone() {
|
||||
// Projecting square caps: the line from x 10 to 30 at y 10 reaches x 7 and x 33; the
|
||||
// degenerate subpath at (20, 30) is dropped.
|
||||
let page = render("0 0 1 RG 6 w 2 J 10 30 m 30 30 l 20 10 m h S", "<< >>");
|
||||
for x in [8, 20, 32] {
|
||||
assert_eq!(px(&page, x, 10), BLUE, "({x}, 10) on the line with its square caps");
|
||||
}
|
||||
assert_eq!(px(&page, 20, 30), WHITE, "the degenerate subpath is dropped");
|
||||
// Round caps: the degenerate subpath becomes a dot beside the line.
|
||||
let page = render("0 0 1 RG 6 w 1 J 10 30 m 30 30 l 20 10 m h S", "<< >>");
|
||||
assert_eq!(px(&page, 20, 10), BLUE, "the line");
|
||||
assert_eq!(px(&page, 20, 30), BLUE, "the dot");
|
||||
// A trailing open single-point subpath (`m` with nothing after it) paints nothing, and leaves
|
||||
// the line before it as it is, with either cap.
|
||||
let page = render("0 0 1 RG 6 w 2 J 10 30 m 30 30 l 20 10 m S", "<< >>");
|
||||
for x in [8, 20, 32] {
|
||||
assert_eq!(px(&page, x, 10), BLUE, "({x}, 10) on the line before a trailing m");
|
||||
}
|
||||
assert_eq!(px(&page, 20, 30), WHITE, "a trailing m with square caps paints nothing");
|
||||
let page = render("0 0 1 RG 6 w 1 J 10 30 m 30 30 l 20 10 m S", "<< >>");
|
||||
assert_eq!(px(&page, 20, 10), BLUE, "the line before a trailing m");
|
||||
assert_eq!(px(&page, 20, 30), WHITE, "a trailing m with round caps paints no dot");
|
||||
// `b` (close, fill and stroke) of a single point strokes the dot too.
|
||||
let page = render("0 0 1 RG 1 0 0 rg 6 w 1 J 20 20 m b", "<< >>");
|
||||
assert_eq!(px(&page, 20, 20), BLUE, "b of one point strokes a round dot");
|
||||
// A curve back to its start through other control points is a loop, not a point.
|
||||
let page = render("0 0 1 RG 2 w 2 J 20 10 m 35 35 5 35 20 10 c S", "<< >>");
|
||||
assert!(inked(&page) > 20, "a curve that returns to its start is stroked");
|
||||
// A hairline dot is still drawn, about a device pixel across.
|
||||
let page = render("0 0 1 RG 0 w 1 J 20 20 m h S", "<< >>");
|
||||
assert!((1..=9).contains(&inked(&page)), "a 0 w round dot: {} pixels", inked(&page));
|
||||
// Not degenerate: the ends differ, so the square caps are drawn along the hairline segment.
|
||||
let page = render("0 0 1 RG 10 w 2 J 20 20 m 20.01 20 l S", "<< >>");
|
||||
assert_eq!(px(&page, 20, 20), BLUE, "a segment a hundredth of a point long is stroked with its caps");
|
||||
}
|
||||
|
||||
/// `h` "terminates the current subpath. Appending another segment to the current path shall begin
|
||||
/// a new subpath, even if the new segment begins at the endpoint reached by the h operation"
|
||||
/// (ISO 32000-2 §8.5.2.1, Table 58). So a segment after `h` back to the point `h` reached is a
|
||||
/// degenerate subpath of its own: a round dot with round caps, nothing with the others. The closed
|
||||
/// line from x 10 to x 30 turns back on itself at x 10, where the miter join falls back to a bevel
|
||||
/// and paints nothing left of x 10; a 6 pt dot at (10, 20) reaches x 7.
|
||||
#[test]
|
||||
fn a_segment_after_h_begins_a_new_subpath() {
|
||||
let page = render("0 0 1 RG 6 w 1 J 10 20 m 30 20 l h S", "<< >>");
|
||||
assert_eq!(px(&page, 20, 20), BLUE, "the closed line");
|
||||
assert_eq!(px(&page, 8, 20), WHITE, "a closed line has no cap at its start");
|
||||
for (what, after) in [("l", "10 20 l"), ("c", "10 20 10 20 10 20 c"), ("v", "10 20 10 20 v"), ("y", "10 20 10 20 y")] {
|
||||
let page = render(&format!("0 0 1 RG 6 w 1 J 10 20 m 30 20 l h {after} S"), "<< >>");
|
||||
assert_eq!(px(&page, 20, 20), BLUE, "{what} after h: the closed line");
|
||||
assert_eq!(px(&page, 8, 20), BLUE, "{what} after h, round caps: a dot at the point h reached");
|
||||
for cap in ["0 J", "2 J"] {
|
||||
let page = render(&format!("0 0 1 RG 6 w {cap} 10 20 m 30 20 l h {after} S"), "<< >>");
|
||||
assert_eq!(px(&page, 20, 20), BLUE, "{what} after h with {cap}: the closed line");
|
||||
assert_eq!(px(&page, 8, 20), WHITE, "{what} after h with {cap}: no dot");
|
||||
}
|
||||
}
|
||||
// A segment after h that goes somewhere is an open subpath with caps of its own: with square
|
||||
// caps the line from (10, 20) down to (10, 35) reaches y 38 (device row 2).
|
||||
let page = render("0 0 1 RG 6 w 2 J 10 20 m 30 20 l h 10 35 l S", "<< >>");
|
||||
assert_eq!(px(&page, 10, 3), BLUE, "the new subpath's projecting cap");
|
||||
}
|
||||
|
||||
/// §8.4.3.6 asks for dash numbers that are nonnegative and not all zero, but not how to recover
|
||||
/// from others. They draw a solid line, as an empty dash array does; before, `[0 0]` was cut into
|
||||
/// hundredth-of-a-point dashes and came out a faint, half-covered line.
|
||||
#[test]
|
||||
fn all_zero_dash_arrays_draw_a_solid_line() {
|
||||
for (what, content, gs1) in [
|
||||
("[0 0]", "0 0 1 RG 4 w [0 0] 0 d 10 20 m 30 20 l S", "<< >>"),
|
||||
("[0]", "0 0 1 RG 4 w [0] 0 d 10 20 m 30 20 l S", "<< >>"),
|
||||
("[0 0 0] with a phase", "0 0 1 RG 4 w [0 0 0] 3 d 10 20 m 30 20 l S", "<< >>"),
|
||||
("[0 0] from an ExtGState", "0 0 1 RG 4 w /GS1 gs 10 20 m 30 20 l S", "<< /D [[0 0] 0] >>"),
|
||||
("[0 -1], negative", "0 0 1 RG 4 w [0 -1] 0 d 10 20 m 30 20 l S", "<< >>"),
|
||||
("[3 -1] from an ExtGState", "0 0 1 RG 4 w /GS1 gs 10 20 m 30 20 l S", "<< /D [[3 -1] 0] >>"),
|
||||
] {
|
||||
let page = render(content, gs1);
|
||||
for x in 11..30 {
|
||||
assert_eq!(px(&page, x, 20), BLUE, "{what}: ({x}, 20) is solid and opaque");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Patterns that are valid keep their dashes: `[0 12]` with round caps is a row of dots, `[4 4]`
|
||||
/// leaves gaps, an odd `[4]` repeats as `[4 4]`.
|
||||
#[test]
|
||||
fn valid_dash_patterns_still_dash() {
|
||||
let page = render("0 0 1 RG 4 w 1 J [0 12] 0 d 4 20 m 36 20 l S", "<< >>");
|
||||
for x in [4, 16, 28] {
|
||||
assert_eq!(px(&page, x, 20), BLUE, "[0 12] round caps: a dot at x {x}");
|
||||
}
|
||||
for x in [10, 22, 34] {
|
||||
assert_eq!(px(&page, x, 20), WHITE, "[0 12] round caps: a gap at x {x}");
|
||||
}
|
||||
for (what, content) in [("[4 4]", "0 0 1 RG 4 w [4 4] 0 d 0 20 m 40 20 l S"), ("[4]", "0 0 1 RG 4 w [4] 0 d 0 20 m 40 20 l S")] {
|
||||
let page = render(content, "<< >>");
|
||||
assert_eq!(px(&page, 2, 20), BLUE, "{what}: the first dash");
|
||||
assert_eq!(px(&page, 6, 20), WHITE, "{what}: the first gap");
|
||||
assert_eq!(px(&page, 10, 20), BLUE, "{what}: the second dash");
|
||||
}
|
||||
}
|
||||
|
||||
/// The stroke properties and paints every `draw_path` of `content` reaches a device with.
|
||||
fn strokes(content: &str, gs1: &str) -> Vec<(StrokeProps, Paint<'static>)> {
|
||||
#[derive(Default)]
|
||||
struct Strokes(Vec<(StrokeProps, Paint<'static>)>);
|
||||
impl<'a> Device<'a> for Strokes {
|
||||
fn set_soft_mask(&mut self, _: Option<SoftMask<'a>>) {}
|
||||
fn set_blend_mode(&mut self, _: BlendMode) {}
|
||||
fn draw_path(&mut self, _: &BezPath, _: Affine, paint: &Paint<'a>, mode: &PathDrawMode) {
|
||||
if let (PathDrawMode::Stroke(props), Paint::Color(colour)) = (mode, paint) {
|
||||
self.0.push((props.clone(), Paint::Color(colour.clone())));
|
||||
}
|
||||
}
|
||||
fn push_clip_path(&mut self, _: &ClipPath) {}
|
||||
fn push_transparency_group(&mut self, _: f32, _: Option<SoftMask<'a>>, _: BlendMode) {}
|
||||
fn draw_glyph(&mut self, _: &Glyph<'a>, _: Affine, _: Affine, _: &Paint<'a>, _: &GlyphDrawMode) {}
|
||||
fn draw_image(&mut self, _: Image<'a, '_>, _: Affine) {}
|
||||
fn pop_clip_path(&mut self) {}
|
||||
fn pop_transparency_group(&mut self) {}
|
||||
}
|
||||
let pdf = format!(
|
||||
"%PDF-1.7
|
||||
1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj
|
||||
2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj
|
||||
3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 40 40] /Contents 4 0 R /Resources << /ExtGState << /GS1 {gs1} >> >> >> endobj
|
||||
4 0 obj << /Length {} >> stream
|
||||
{content}
|
||||
endstream endobj
|
||||
trailer << /Root 1 0 R >>
|
||||
%%EOF",
|
||||
content.len()
|
||||
);
|
||||
let parsed = Pdf::new(Arc::new(pdf.into_bytes())).expect("parses");
|
||||
let page = &parsed.pages()[0];
|
||||
let cache = InterpreterCache::new();
|
||||
let mut ctx =
|
||||
Context::new(page.initial_transform(true).to_kurbo(), Rect::new(0.0, 0.0, 40.0, 40.0), &cache, page.xref(), InterpreterSettings::default());
|
||||
let mut device = Strokes::default();
|
||||
interpret_page(page, &mut ctx, &mut device);
|
||||
device.0
|
||||
}
|
||||
|
||||
/// §8.4.3.2: a line width of 0 is the thinnest line the device can draw. A negative or
|
||||
/// non-finite one is invalid and kept as 0, so no device sees a width below zero; the stroke
|
||||
/// keeps the current stroke colour.
|
||||
#[test]
|
||||
fn negative_line_widths_reach_a_device_as_zero() {
|
||||
for (what, content, gs1, width) in [
|
||||
("-6 w", "0 0 1 RG -6 w 10 20 m 30 20 l S", "<< >>", 0.0),
|
||||
("/LW -6", "0 0 1 RG /GS1 gs 10 20 m 30 20 l S", "<< /LW -6 >>", 0.0),
|
||||
("/LW 1e40, beyond f32", "0 0 1 RG /GS1 gs 10 20 m 30 20 l S", "<< /LW 10000000000000000000000000000000000000000 >>", 0.0),
|
||||
("2.5 w", "0 0 1 RG 2.5 w 10 20 m 30 20 l S", "<< >>", 2.5),
|
||||
("0 w", "0 0 1 RG 0 w 10 20 m 30 20 l S", "<< >>", 0.0),
|
||||
] {
|
||||
let seen = strokes(content, gs1);
|
||||
assert_eq!(seen.len(), 1, "{what}: one stroke");
|
||||
let (props, paint) = &seen[0];
|
||||
assert_eq!(props.line_width, width, "{what}: line width");
|
||||
let Paint::Color(colour) = paint else { unreachable!() };
|
||||
assert_eq!(colour.to_rgba().to_rgba8(), [0, 0, 255, 255], "{what}: the stroke colour");
|
||||
}
|
||||
}
|
||||
|
||||
/// The dash array a device is given: `[]` (solid) for one that is all zero or has a negative or
|
||||
/// non-finite entry, from `d` or from `/D`; a valid one keeps its entries, a zero entry turned
|
||||
/// into a hundredth of a point, as before.
|
||||
#[test]
|
||||
fn invalid_dash_arrays_reach_a_device_as_solid() {
|
||||
let line = "10 20 m 30 20 l S";
|
||||
for (what, setup, gs1, dashes) in [
|
||||
("[0 0]", "[0 0] 0 d", "<< >>", &[][..]),
|
||||
("[0]", "[0] 0 d", "<< >>", &[]),
|
||||
("[0 0 0] with a phase", "[0 0 0] 4 d", "<< >>", &[]),
|
||||
("/D [[0 0] 0]", "/GS1 gs", "<< /D [[0 0] 0] >>", &[]),
|
||||
("[3 -1]", "[3 -1] 0 d", "<< >>", &[]),
|
||||
("/D [[0 -1] 0]", "/GS1 gs", "<< /D [[0 -1] 0] >>", &[]),
|
||||
("[3 1e40], beyond f32", "[3 10000000000000000000000000000000000000000] 0 d", "<< >>", &[]),
|
||||
("[]", "[] 0 d", "<< >>", &[]),
|
||||
("[0 12]", "[0 12] 0 d", "<< >>", &[0.01, 12.0]),
|
||||
("/D [[0 12] 0]", "/GS1 gs", "<< /D [[0 12] 0] >>", &[0.01, 12.0]),
|
||||
("[20 10]", "[20 10] 5 d", "<< >>", &[20.0, 10.0]),
|
||||
("[10]", "[10] 0 d", "<< >>", &[10.0]),
|
||||
] {
|
||||
let seen = strokes(&format!("{setup} {line}"), gs1);
|
||||
assert_eq!(seen.len(), 1, "{what}: one stroke");
|
||||
assert_eq!(seen[0].0.dash_array.as_slice(), dashes, "{what}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The renderer already drew a negative width as its thinnest line (it widens anything under a
|
||||
/// device pixel); that stays so, in the stroke colour.
|
||||
#[test]
|
||||
fn negative_line_widths_draw_the_thinnest_line_in_the_stroke_colour() {
|
||||
for (what, content, gs1, reference) in [
|
||||
("-6 w", "0 0 1 RG -6 w 10 20 m 30 20 l S", "<< >>", "0 0 1 RG 0 w 10 20 m 30 20 l S"),
|
||||
("/LW -6", "0 0 1 RG /GS1 gs 10 20 m 30 20 l S", "<< /LW -6 >>", "0 0 1 RG 0 w 10 20 m 30 20 l S"),
|
||||
("-6 w with round caps", "0 0 1 RG 1 J -6 w 10 20 m 30 20 l S", "<< >>", "0 0 1 RG 1 J 0 w 10 20 m 30 20 l S"),
|
||||
] {
|
||||
let hairline = render(reference, "<< >>");
|
||||
let page = render(content, gs1);
|
||||
assert!(page.rgba[..] == hairline.rgba[..], "{what}: drawn as 0 w");
|
||||
let ink: Vec<[u8; 4]> = page.rgba.as_chunks::<4>().0.iter().filter(|p| **p != WHITE).copied().collect();
|
||||
assert!(!ink.is_empty(), "{what}: the line is drawn");
|
||||
assert!(ink.iter().all(|p| p[2] == 255 && p[0] == p[1]), "{what}: every inked pixel is a tint of the blue stroke colour: {ink:?}");
|
||||
assert!(ink.len() <= 2 * 22, "{what}: about one pixel thick, {} pixels inked", ink.len());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
//! Symbol and ZapfDingbats named without `/Widths` or `/Encoding` draw each glyph within the
|
||||
//! advance their standard metrics give (ISO 32000-2 §9.6.2.2, Annex D.5 and D.6), through their
|
||||
//! bundled stand-ins as the text fonts do: the next glyph starts one standard advance on, and the
|
||||
//! glyph's ink stays inside that advance. ZapfDingbats `4` (a20, the check mark) is what a check
|
||||
//! box's `/MK /CA` caption draws.
|
||||
|
||||
use crate::euro_width::{SIZE, ink_runs_in};
|
||||
use pdfcraft_fonts::Std14;
|
||||
|
||||
/// The page's left margin, where the text starts, in pixels.
|
||||
const ORIGIN: f64 = 20.0;
|
||||
|
||||
/// `codes` as a PDF literal string body, every byte octal-escaped.
|
||||
fn literal(codes: &[u8]) -> String {
|
||||
codes.iter().map(|c| format!("\\{c:03o}")).collect()
|
||||
}
|
||||
|
||||
/// For each `(code, glyph)` of `font` (`name`): drawn alone, the glyph's ink lies within its
|
||||
/// standard advance (one pixel of rounding either side, as for the Euro), and drawn before
|
||||
/// `follower`, the follower's ink starts one standard advance later than when drawn alone.
|
||||
fn fits(name: &str, font: Std14, follower: u8, glyphs: &[(u8, &str)]) {
|
||||
let [(follower_alone, _), ..] = ink_runs_in(name, None, &literal(&[follower]))[..] else { panic!("{name}: the follower draws") };
|
||||
for &(code, glyph) in glyphs {
|
||||
let advance = font.advance(code, SIZE);
|
||||
assert!(advance > 0.0, "{name} {glyph}: a standard width");
|
||||
let alone = ink_runs_in(name, None, &literal(&[code]));
|
||||
let (Some(&(start, _)), Some(&(_, end))) = (alone.first(), alone.last()) else { panic!("{name} {glyph}: no ink") };
|
||||
assert!(f64::from(start) >= ORIGIN - 1.0, "{name} {glyph}: ink starts at its origin or after: {alone:?}");
|
||||
assert!(f64::from(end) + 1.0 <= ORIGIN + advance + 1.0, "{name} {glyph}: ink ends within {advance} px: {alone:?}");
|
||||
// The glyph is fitted, not squeezed: its ink fills most of the advance, as each of these does.
|
||||
assert!(f64::from(end - start + 1) >= 0.7 * advance, "{name} {glyph}: ink spans most of {advance} px: {alone:?}");
|
||||
|
||||
let pair = ink_runs_in(name, None, &literal(&[code, follower]));
|
||||
let Some(&(next, _)) = pair.last() else { panic!("{name} {glyph}: no ink") };
|
||||
assert!(pair.len() > alone.len(), "{name} {glyph}: the follower stands apart: {pair:?}");
|
||||
assert!(
|
||||
(f64::from(next) - f64::from(follower_alone) - advance).abs() <= 1.0,
|
||||
"{name} {glyph}: the follower starts {advance} px on: {pair:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Symbol's Greek letters and signs by their built-in codes (Annex D.5).
|
||||
#[test]
|
||||
fn symbol_glyphs_keep_their_standard_advances() {
|
||||
let glyphs = [
|
||||
(0x61, "alpha"),
|
||||
(0x62, "beta"),
|
||||
(0x70, "pi"),
|
||||
(0x53, "Sigma"),
|
||||
(0x57, "Omega"),
|
||||
(0x44, "Delta"),
|
||||
(0xA5, "infinity"),
|
||||
(0xB7, "bullet"),
|
||||
(0x2B, "plus"),
|
||||
];
|
||||
fits("Symbol", Std14::Symbol, 0x53, &glyphs);
|
||||
}
|
||||
|
||||
/// ZapfDingbats' check marks, crosses, dot, square, diamond and star by their built-in codes
|
||||
/// (Annex D.6), the check box caption `4` among them.
|
||||
#[test]
|
||||
fn zapf_dingbats_glyphs_keep_their_standard_advances() {
|
||||
let glyphs = [
|
||||
(0x34, "a20 check"),
|
||||
(0x33, "a19 light check"),
|
||||
(0x37, "a23 ballot x"),
|
||||
(0x38, "a24 heavy ballot x"),
|
||||
(0x6C, "a71 dot"),
|
||||
(0x6E, "a73 square"),
|
||||
(0x75, "a77 diamond"),
|
||||
(0x48, "a28 star"),
|
||||
];
|
||||
fits("ZapfDingbats", Std14::ZapfDingbats, 0x6E, &glyphs);
|
||||
}
|
||||
@@ -0,0 +1,301 @@
|
||||
//! Zero-area fills and clips mark the pixels they touch (ISO 32000-2 §10.7.4: "A zero-width or
|
||||
//! zero-height rectangle paints a line 1 pixel wide", and "the clipping region consists of the
|
||||
//! set of pixels that would be included by a fill operation").
|
||||
//!
|
||||
//! Which row (or column) a line on a pixel boundary marks is not left open. §10.7.4, "Scan
|
||||
//! conversion rules", in device space:
|
||||
//!
|
||||
//! > Pixel boundaries always fall on integer coordinates in device space. A pixel is a square
|
||||
//! > region identified by the location of its corner with minimum horizontal and vertical
|
||||
//! > coordinates. The region is half-open, meaning that it includes its lower but not its upper
|
||||
//! > boundaries. More precisely, for any point whose real-number coordinates are (x, y), let
|
||||
//! > i = floor(x) and j = floor(y). The pixel that contains this point is the one identified as
|
||||
//! > (i, j).
|
||||
//!
|
||||
//! > Like pixels, shapes to be painted by filling (8.5.3.3, "Filling") and stroking (8.5.3.2,
|
||||
//! > "Stroking") operations are also treated as half-open regions that include the boundaries
|
||||
//! > along their "floor" sides, but not along their "ceiling" sides.
|
||||
//!
|
||||
//! > A shape shall be scan-converted by painting any pixel whose half-open square region
|
||||
//! > intersects the shape, no matter how small the intersection is.
|
||||
//!
|
||||
//! So a line at device y = 150 lies in pixel row floor(150) = 150 and not in row 149, whose
|
||||
//! region stops short of 150; a line from device x = 10 to x = 110 marks columns 10 to 109, as
|
||||
//! its ceiling end at 110 is not part of it. Off a boundary, a line at y = 149.5 marks row
|
||||
//! floor(149.5) = 149. The rule is stated in device space, whose y axis here points down the
|
||||
//! page, so row 150 is the one just below the line as the page is seen.
|
||||
//!
|
||||
//! Every page is 200 × 200 pt rendered at scale 1, so user `(x, y)` lands on device
|
||||
//! `(x, 200 - y)`: a line at user `y = 50` lies on the boundary between device rows 149 and
|
||||
//! 150, and by the half-open rule marks row 150.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use pdfcraft_render::{PageRenderer, RenderConfig, RenderRequest, RequestKind};
|
||||
|
||||
const SIZE: u32 = 200;
|
||||
|
||||
fn build_pdf(content: &str) -> Vec<u8> {
|
||||
let objs = [
|
||||
"<< /Type /Catalog /Pages 2 0 R >>".to_owned(),
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_owned(),
|
||||
format!("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 {SIZE} {SIZE}] /Contents 4 0 R >>"),
|
||||
format!("<< /Length {} >>\nstream\n{content}\nendstream", content.len()),
|
||||
];
|
||||
let mut out = b"%PDF-1.7\n".to_vec();
|
||||
let mut offs = Vec::with_capacity(objs.len());
|
||||
for (i, body) in objs.iter().enumerate() {
|
||||
offs.push(out.len());
|
||||
out.extend_from_slice(format!("{} 0 obj\n{body}\nendobj\n", i + 1).as_bytes());
|
||||
}
|
||||
let xref = out.len();
|
||||
let size = objs.len() + 1;
|
||||
out.extend_from_slice(format!("xref\n0 {size}\n0000000000 65535 f \n").as_bytes());
|
||||
for off in offs {
|
||||
out.extend_from_slice(format!("{off:010} 00000 n \n").as_bytes());
|
||||
}
|
||||
out.extend_from_slice(format!("trailer\n<< /Size {size} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n").as_bytes());
|
||||
out
|
||||
}
|
||||
|
||||
/// The page drawn by `content`, as RGBA rows of `SIZE` pixels.
|
||||
fn render(content: &str) -> Vec<u8> {
|
||||
let pdf = Arc::new(build_pdf(content));
|
||||
let mut renderer = PageRenderer::new(pdf, RenderConfig::default());
|
||||
let page = renderer.render(RenderRequest { page: 0, kind: RequestKind::Pixels, tile: None, scale: 1.0, tag: 0, preview: false });
|
||||
assert!(page.error.is_none(), "render error: {:?}", page.error);
|
||||
assert_eq!((page.width, page.height), (SIZE, SIZE));
|
||||
page.rgba.to_vec()
|
||||
}
|
||||
|
||||
fn px(rgba: &[u8], x: u32, y: u32) -> [u8; 3] {
|
||||
let i = ((y * SIZE + x) * 4) as usize;
|
||||
[rgba[i], rgba[i + 1], rgba[i + 2]]
|
||||
}
|
||||
|
||||
fn is_red(p: [u8; 3]) -> bool {
|
||||
p[0] > 240 && p[1] < 15 && p[2] < 15
|
||||
}
|
||||
|
||||
fn is_white(p: [u8; 3]) -> bool {
|
||||
p.iter().all(|&c| c > 250)
|
||||
}
|
||||
|
||||
/// The red pixels of the page, as `(x, y)`.
|
||||
fn red_pixels(rgba: &[u8]) -> Vec<(u32, u32)> {
|
||||
let mut red = Vec::new();
|
||||
for y in 0..SIZE {
|
||||
for x in 0..SIZE {
|
||||
if is_red(px(rgba, x, y)) {
|
||||
red.push((x, y));
|
||||
}
|
||||
}
|
||||
}
|
||||
red
|
||||
}
|
||||
|
||||
/// The pixels that are neither white nor full red: partly covered ones.
|
||||
fn tinted_pixels(rgba: &[u8]) -> usize {
|
||||
let mut n = 0;
|
||||
for y in 0..SIZE {
|
||||
for x in 0..SIZE {
|
||||
let p = px(rgba, x, y);
|
||||
if !is_red(p) && !is_white(p) {
|
||||
n += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
n
|
||||
}
|
||||
|
||||
/// Asserts the page is exactly a full-red run of device pixels `x0..x1` × `y0..y1` on white.
|
||||
fn assert_only_red_run(rgba: &[u8], (x0, x1): (u32, u32), (y0, y1): (u32, u32), what: &str) {
|
||||
let mut expected = Vec::new();
|
||||
for y in y0..y1 {
|
||||
for x in x0..x1 {
|
||||
expected.push((x, y));
|
||||
}
|
||||
}
|
||||
assert_eq!(red_pixels(rgba), expected, "{what}: the red pixels");
|
||||
assert_eq!(tinted_pixels(rgba), 0, "{what}: partly covered pixels");
|
||||
}
|
||||
|
||||
const FLOOD: &str = "1 0 0 rg 0 0 200 200 re f";
|
||||
/// A fill that covers the whole page under any of the CTMs below.
|
||||
const BIG_FLOOD: &str = "1 0 0 rg -400 -400 800 800 re f";
|
||||
|
||||
#[test]
|
||||
fn zero_height_clip_shows_the_fill_as_one_device_row() {
|
||||
// User y = 50 is device y = 150, a pixel boundary: row 150 and nothing else.
|
||||
let rgba = render(&format!("q 10 50 100 0 re W n {FLOOD} Q"));
|
||||
assert_only_red_run(&rgba, (10, 110), (150, 151), "clip on a pixel boundary");
|
||||
// Off the boundary (device y = 149.5) the line marks the row it runs through.
|
||||
let rgba = render(&format!("q 10 50.5 100 0 re W n {FLOOD} Q"));
|
||||
assert_only_red_run(&rgba, (10, 110), (149, 150), "clip inside a row");
|
||||
// Inside a translated CTM, as the line is usually drawn.
|
||||
let rgba = render(&format!("q 1 0 0 1 20 30 cm 10 10 100 0 re W n {FLOOD} Q"));
|
||||
assert_only_red_run(&rgba, (30, 130), (160, 161), "clip under a translation");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zero_width_clip_shows_the_fill_as_one_device_column() {
|
||||
let rgba = render(&format!("q 50 10 0 100 re W n {FLOOD} Q"));
|
||||
assert_only_red_run(&rgba, (50, 51), (90, 190), "zero-width clip");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zero_height_and_zero_width_fills_paint_one_pixel_lines() {
|
||||
let rgba = render("1 0 0 rg 10 50 100 0 re f");
|
||||
assert_only_red_run(&rgba, (10, 110), (150, 151), "zero-height fill");
|
||||
let rgba = render("1 0 0 rg 50 10 0 100 re f");
|
||||
assert_only_red_run(&rgba, (50, 51), (90, 190), "zero-width fill");
|
||||
// The same line drawn as a fill and seen through a clip marks the same pixels.
|
||||
let fill = render("1 0 0 rg 10 50.5 100 0 re f");
|
||||
let clip = render(&format!("q 10 50.5 100 0 re W n {FLOOD} Q"));
|
||||
assert_eq!(red_pixels(&fill), red_pixels(&clip));
|
||||
}
|
||||
|
||||
/// Each of the four cases (zero-height and zero-width, fill and clip) on a pixel boundary and
|
||||
/// off one, by the half-open rule quoted above: a line on a boundary marks the row or column on
|
||||
/// its floor side, one off it marks the row or column it runs through, and its ends mark every
|
||||
/// pixel they reach into but not one they only meet at the ceiling side.
|
||||
#[test]
|
||||
fn zero_height_and_zero_width_fills_and_clips_on_and_off_a_pixel_boundary() {
|
||||
let cases = [
|
||||
// (the line, its device columns, its device rows, what)
|
||||
("10 50 100 0 re", (10, 110), (150, 151), "zero-height on a boundary"),
|
||||
("10 50.5 100 0 re", (10, 110), (149, 150), "zero-height off a boundary"),
|
||||
("10.5 50.5 99 0 re", (10, 110), (149, 150), "zero-height, ends inside pixels"),
|
||||
("50 10 0 100 re", (50, 51), (90, 190), "zero-width on a boundary"),
|
||||
("50.5 10 0 100 re", (50, 51), (90, 190), "zero-width off a boundary"),
|
||||
("50.5 10.5 0 99 re", (50, 51), (90, 190), "zero-width, ends inside pixels"),
|
||||
];
|
||||
for (line, columns, rows, what) in cases {
|
||||
let fill = render(&format!("1 0 0 rg {line} f"));
|
||||
assert_only_red_run(&fill, columns, rows, &format!("{what}: fill"));
|
||||
let clip = render(&format!("q {line} W n {FLOOD} Q"));
|
||||
assert_only_red_run(&clip, columns, rows, &format!("{what}: clip"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_quarter_turn_maps_a_zero_height_clip_to_one_device_column() {
|
||||
// `0 1 -1 0 100 20 cm` turns user x into device -y: the line runs up column 100.
|
||||
let rgba = render(&format!("q 0 1 -1 0 100 20 cm 10 0 100 0 re W n {BIG_FLOOD} Q"));
|
||||
assert_only_red_run(&rgba, (100, 101), (70, 170), "quarter-turned clip");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rotated_zero_height_clip_and_fill_show_a_one_pixel_band() {
|
||||
// 45 degrees: the line runs diagonally, so it shows as a band about one pixel wide.
|
||||
let clip = render(&format!("q 0.70710678 0.70710678 -0.70710678 0.70710678 50 50 cm 0 0 100 0 re W n {BIG_FLOOD} Q"));
|
||||
let fill = render("q 0.70710678 0.70710678 -0.70710678 0.70710678 50 50 cm 1 0 0 rg 0 0 100 0 re f Q");
|
||||
for (rgba, what) in [(&clip, "clip"), (&fill, "fill")] {
|
||||
// Along the diagonal from device (50, 150) to (120.7, 79.3), the pixel the line crosses
|
||||
// corner to corner in each column is mostly red, and the pixels well off it are white.
|
||||
for step in 5..65 {
|
||||
let (x, y) = (50 + step, 149 - step);
|
||||
let p = px(rgba, x, y);
|
||||
assert!(p[0] > 240 && p[1] < 160, "{what}: pixel ({x}, {y}) on the line is {p:?}");
|
||||
assert!(is_white(px(rgba, x + 3, y)), "{what}: pixel off the line");
|
||||
assert!(is_white(px(rgba, x - 3, y)), "{what}: pixel off the line");
|
||||
}
|
||||
// The band is one pixel wide: its ink adds up to its length, 100 pixels.
|
||||
let ink: f64 = rgba.as_chunks::<4>().0.iter().map(|p| 1.0 - f64::from(p[1]) / 255.0).sum();
|
||||
assert!((90.0..=110.0).contains(&ink), "{what}: ink {ink}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_thin_rectangle_with_area_keeps_its_partial_coverage() {
|
||||
// 0.3 pt high is not degenerate: it covers 30 % of device row 149 and is antialiased as
|
||||
// before, not widened to a whole pixel.
|
||||
let rgba = render("1 0 0 rg 10 50.2 100 0.3 re f");
|
||||
assert!(red_pixels(&rgba).is_empty(), "a 0.3 pt rectangle is not painted solid");
|
||||
for x in 10..110 {
|
||||
let p = px(&rgba, x, 149);
|
||||
assert!(p[0] > 240, "row 149 at {x}: {p:?}");
|
||||
assert!((150..=210).contains(&p[1]), "row 149 at {x} is 30 % covered: {p:?}");
|
||||
assert!(is_white(px(&rgba, x, 148)) && is_white(px(&rgba, x, 150)));
|
||||
}
|
||||
// The same rectangle as a clip keeps the same partial coverage.
|
||||
let clip = render(&format!("q 10 50.2 100 0.3 re W n {FLOOD} Q"));
|
||||
assert_eq!(clip, rgba);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_zero_area_clip_with_nothing_painted_on_it_stays_blank() {
|
||||
// The fill misses the line the clip keeps.
|
||||
let rgba = render("q 10 50 100 0 re W n 1 0 0 rg 0 100 200 100 re f Q");
|
||||
assert!(rgba.as_chunks::<4>().0.iter().all(|p| is_white([p[0], p[1], p[2]])), "page not blank");
|
||||
// Nothing painted at all.
|
||||
let rgba = render("q 10 50 100 0 re W n Q");
|
||||
assert!(rgba.as_chunks::<4>().0.iter().all(|p| is_white([p[0], p[1], p[2]])), "page not blank");
|
||||
// A clip that is a point keeps nothing, as before.
|
||||
let rgba = render(&format!("q 10 50 0 0 re W n {FLOOD} Q"));
|
||||
assert!(red_pixels(&rgba).is_empty() && tinted_pixels(&rgba) == 0, "a point clip shows the fill");
|
||||
// So does a point a little off zero both ways.
|
||||
let rgba = render(&format!("q 10 50 0.001 0.001 re W n {FLOOD} Q"));
|
||||
assert!(red_pixels(&rgba).is_empty() && tinted_pixels(&rgba) == 0, "a tiny clip shows the fill");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_clip_is_restored_after_q() {
|
||||
let rgba = render(&format!("q 10 50 100 0 re W n Q {FLOOD}"));
|
||||
assert_eq!(red_pixels(&rgba).len(), (SIZE * SIZE) as usize);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_thin_rectangle_scaled_up_to_whole_pixels_keeps_its_area() {
|
||||
// 1/1024 pt high is under the rasteriser's "nearly zero" threshold, but the rectangle has
|
||||
// area: scaled 4096 times vertically it covers device y 164..168, four whole rows, and is
|
||||
// painted as the rectangle it is, not as a line across its bounding box.
|
||||
let fill = render("q 1 0 0 4096 0 0 cm 1 0 0 rg 10 0.0078125 100 0.0009765625 re f Q");
|
||||
assert_only_red_run(&fill, (10, 110), (164, 168), "scaled-up thin fill");
|
||||
let clip = render(&format!("q 1 0 0 4096 0 0 cm 10 0.0078125 100 0.0009765625 re W n {FLOOD} Q"));
|
||||
assert_only_red_run(&clip, (10, 110), (164, 168), "scaled-up thin clip");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_slanted_zero_height_line_crossing_a_row_marks_each_row_only_where_it_runs() {
|
||||
// A slight skew lifts the line from device y 149.52 at x = 10 to 148.74 at x = 110: under a
|
||||
// pixel high in all, but crossing the boundary between rows 148 and 149 near x = 75. Each
|
||||
// row is marked where the line runs through it, not along the whole length.
|
||||
let skew = "1 0.008 0 1 0 0 cm";
|
||||
let fill = render(&format!("q {skew} 1 0 0 rg 10 50.4 100 0 re f Q"));
|
||||
let clip = render(&format!("q {skew} 10 50.4 100 0 re W n {FLOOD} Q"));
|
||||
for (rgba, what) in [(&fill, "fill"), (&clip, "clip")] {
|
||||
for x in [12, 15, 20] {
|
||||
assert!(px(rgba, x, 149)[1] < 128, "{what}: ({x}, 149) on the line is {:?}", px(rgba, x, 149));
|
||||
assert!(px(rgba, x, 148)[1] > 128, "{what}: ({x}, 148) off the line is {:?}", px(rgba, x, 148));
|
||||
}
|
||||
for x in [100, 105, 108] {
|
||||
assert!(px(rgba, x, 148)[1] < 128, "{what}: ({x}, 148) on the line is {:?}", px(rgba, x, 148));
|
||||
assert!(px(rgba, x, 149)[1] > 128, "{what}: ({x}, 149) off the line is {:?}", px(rgba, x, 149));
|
||||
}
|
||||
// One pixel wide: its ink adds up to its length, about 100 pixels, not two rows' worth.
|
||||
let ink: f64 = rgba.as_chunks::<4>().0.iter().map(|p| 1.0 - f64::from(p[1]) / 255.0).sum();
|
||||
assert!((90.0..=110.0).contains(&ink), "{what}: ink {ink}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disconnected_subpaths_on_one_line_leave_the_gap_between_them_unpainted() {
|
||||
// Two zero-height subpaths on user y = 50 (device row 150), x 10..30 and 60..90: the fill
|
||||
// and the clip mark the pixels each subpath touches, not the gap between them.
|
||||
let mut expected = Vec::new();
|
||||
for x in (10..30).chain(60..90) {
|
||||
expected.push((x, 150));
|
||||
}
|
||||
let fill = render("1 0 0 rg 10 50 m 30 50 l 60 50 m 90 50 l f");
|
||||
let clip = render(&format!("q 10 50 m 30 50 l 60 50 m 90 50 l W n {FLOOD} Q"));
|
||||
for (rgba, what) in [(&fill, "fill"), (&clip, "clip")] {
|
||||
assert_eq!(red_pixels(rgba), expected, "{what}: the red pixels");
|
||||
assert_eq!(tinted_pixels(rgba), 0, "{what}: partly covered pixels");
|
||||
}
|
||||
// Overlapping subpaths drawn in opposite directions still paint their union under either rule.
|
||||
let fill = render("1 0 0 rg 10 50 m 60 50 l 90 50 m 40 50 l f*");
|
||||
assert_only_red_run(&fill, (10, 90), (150, 151), "overlapping subpaths");
|
||||
let clip = render(&format!("q 10 50 m 60 50 l 90 50 m 40 50 l W* n {FLOOD} Q"));
|
||||
assert_only_red_run(&clip, (10, 90), (150, 151), "overlapping subpaths: clip");
|
||||
}
|
||||
@@ -42,6 +42,7 @@ mod xform;
|
||||
mod zoom;
|
||||
pub(super) mod zoom_snap;
|
||||
|
||||
pub(crate) use area::SignTab;
|
||||
pub(crate) use area::signature_badges;
|
||||
use area::{drawing_edge_pointer, glide_interrupted, page_scroll, presentation_click, run_button, set_layers, zoom_anchor};
|
||||
#[cfg(test)]
|
||||
@@ -714,6 +715,24 @@ pub struct DocView {
|
||||
/// Redact tool: the box being drawn, and a mark to add (page, quads) for the app to style.
|
||||
pub redact_drag: crate::redact_ui::AreaDrag,
|
||||
pub pending_redaction: Option<(usize, Vec<[f64; 8]>)>,
|
||||
/// How many Apply redactions steps are in effect in this view. While it is above 0, Save
|
||||
/// proposes the name with `_Redacted` ([`pdfcraft_engine::redacted_file_name`]), and while it is
|
||||
/// above `redactions_downloaded`, Save asks where.
|
||||
/// Undo of an Apply redactions step takes one off and Redo adds it back. Reload and a desktop
|
||||
/// save set it to 0, and Revert sets it to `redactions_downloaded`; after a desktop save the document has the name it was saved
|
||||
/// under. A web download keeps it, so later downloads carry the `_Redacted` name.
|
||||
pub redactions_applied: usize,
|
||||
/// How many Apply redactions steps saved into the document's file are undone in this view.
|
||||
/// While it is above 0, Save asks where, so the restored content is not written over the
|
||||
/// redacted file. Redo takes one off. Revert, Reload and a desktop save set it to 0.
|
||||
pub redactions_undone_after_save: usize,
|
||||
/// Set when Apply redactions runs while saved Apply redactions steps are undone: Redo can no
|
||||
/// longer bring those steps back, so Save asks where until a desktop save or Revert clears it.
|
||||
pub saved_redactions_cut_off: bool,
|
||||
/// `redactions_applied` at the last web download, which Revert restores. While
|
||||
/// `redactions_applied` is below it, a delivered step is undone and Save asks where. A desktop
|
||||
/// save leaves it at 0.
|
||||
pub redactions_downloaded: usize,
|
||||
/// A crop rectangle being dragged (Crop tool).
|
||||
pub crop_drag: crate::crop::CropDrag,
|
||||
/// Enhance ▸ Camera image: the quadrilateral being placed.
|
||||
@@ -1129,6 +1148,10 @@ impl DocView {
|
||||
links: Default::default(),
|
||||
redact_drag: None,
|
||||
pending_redaction: None,
|
||||
redactions_applied: 0,
|
||||
redactions_undone_after_save: 0,
|
||||
saved_redactions_cut_off: false,
|
||||
redactions_downloaded: 0,
|
||||
crop_drag: None,
|
||||
camera: None,
|
||||
camera_done: None,
|
||||
@@ -1298,6 +1321,8 @@ struct PageEnv<'a> {
|
||||
comments_hidden: bool,
|
||||
content_h: f32,
|
||||
content_w: f32,
|
||||
/// The custom stamp's line, filled in now (#1741).
|
||||
custom_line: &'a Option<String>,
|
||||
custom_stamp: &'a Option<crate::stamps_ui::CustomStamp>,
|
||||
date_text: &'a Result<String, String>,
|
||||
doc: &'a pdfcraft_engine::Document,
|
||||
@@ -1716,6 +1741,7 @@ fn draw_page(ui: &mut egui::Ui, view: &mut DocView, frame: &mut PageFrame<'_>, i
|
||||
area_tool: false,
|
||||
hover: None,
|
||||
released_over: false,
|
||||
sign_tabs: Vec::new(),
|
||||
}
|
||||
} else {
|
||||
page_tool_input(ui, view, frame, &slot)
|
||||
@@ -2716,7 +2742,8 @@ fn scroll_direction(dir: i8, dy: f32, resized: bool) -> i8 {
|
||||
/// The hover tip, find bar, size hint and the in-place editors drawn over the pages. Whether the
|
||||
/// text editor was finished.
|
||||
fn frame_overlays(ui: &mut egui::Ui, view: &mut DocView, env: &PageEnv<'_>, primary_down: bool, hover_text: Option<(Pos2, String)>) -> bool {
|
||||
let PageEnv { added, author, avail, can_modify, doc, form, info, prefs, t, today, tool, units, unobstructed, .. } = *env;
|
||||
let PageEnv { added, allowed, author, avail, can_modify, comments_hidden, doc, form, info, prefs, t, today, tool, units, unobstructed, .. } =
|
||||
*env;
|
||||
if let Some((pos, text)) = hover_text {
|
||||
// Click-through, as a tooltip is: the pages lose the pointer under anything that isn't.
|
||||
let tip = egui::Area::new(egui::Id::unique("canvas-hover")).order(egui::Order::Tooltip).interactable(false);
|
||||
@@ -2735,6 +2762,14 @@ fn frame_overlays(ui: &mut egui::Ui, view: &mut DocView, env: &PageEnv<'_>, prim
|
||||
if let Some(e) = comments::composer(ui.ctx(), view, info, prefs) {
|
||||
view.pending_edit = Some(e);
|
||||
}
|
||||
if let Some(e) = comments::popups(ui.ctx(), view, info, prefs, comments_hidden, allowed) {
|
||||
// A click on the composer's Post also takes the focus from a pop-up's box, saving what
|
||||
// was typed there: both edits land in this frame, so both are kept, in one batch.
|
||||
view.pending_edit = Some(match view.pending_edit.take() {
|
||||
Some(first) => Edit::Batch { label: "Edit comment".into(), edits: vec![first, e] },
|
||||
None => e,
|
||||
});
|
||||
}
|
||||
if let Some(e) = crate::edit_text_ui::overlay(ui.ctx(), view, info) {
|
||||
view.pending_edit = Some(e);
|
||||
}
|
||||
@@ -3025,7 +3060,8 @@ fn fits_height(r: Rect, view_height: f32, pixels_per_point: f32) -> bool {
|
||||
}
|
||||
|
||||
/// Draws the document tab at `index`: its notice bars, then its pages (or the Organize grid) in a
|
||||
/// scroll area with this frame's zoom, scrolling, tool input, overlays and render requests.
|
||||
/// scroll area with this frame's zoom, scrolling, tool input, overlays (form fields, comments,
|
||||
/// signature badges and sign tabs) and render requests.
|
||||
pub fn document_area(app: &mut PdfCraftApp, index: usize, ui: &mut egui::Ui) {
|
||||
let t = Tokens::get(ui.ctx());
|
||||
let can_paste_key = egui::Id::unique("can-paste-image");
|
||||
@@ -3188,6 +3224,7 @@ pub fn document_area(app: &mut PdfCraftApp, index: usize, ui: &mut egui::Ui) {
|
||||
QuickTool::CustomStamp(i) => app.custom_stamps.get(i).cloned(),
|
||||
_ => None,
|
||||
};
|
||||
let custom_line = custom_stamp.as_ref().and_then(|cs| cs.line.as_deref()).map(|t| app.session.stamp_line(t, &author));
|
||||
let mut open_props: Option<(usize, usize)> = None;
|
||||
let mut recolour: Option<pdfcraft_engine::Rgb> = None;
|
||||
// The table being set up in its window, shown on its own document's page.
|
||||
@@ -3230,6 +3267,7 @@ pub fn document_area(app: &mut PdfCraftApp, index: usize, ui: &mut egui::Ui) {
|
||||
comments_hidden,
|
||||
content_h,
|
||||
content_w,
|
||||
custom_line: &custom_line,
|
||||
custom_stamp: &custom_stamp,
|
||||
date_text: &date_text,
|
||||
doc,
|
||||
@@ -3607,7 +3645,7 @@ fn apply_frame_requests(app: &mut PdfCraftApp, index: usize, ui: &mut egui::Ui,
|
||||
Some(crate::comments::Composer { page, at, kind: crate::comments::ComposerKind::Note, text: String::new(), focus: true });
|
||||
}
|
||||
Some(PageMenuAction::FlattenComments) => {
|
||||
app.views[index].comments.selected = None;
|
||||
app.views[index].comments.select(None);
|
||||
app.views[index].pending_edit = Some(pdfcraft_engine::Edit::Flatten { comments: true, fields: false });
|
||||
}
|
||||
Some(PageMenuAction::AddBookmark) => {
|
||||
@@ -3699,5 +3737,7 @@ enum FieldMenu {
|
||||
Duplicate(String),
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod sign_tab_tests;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::{LayerOp, PdfCraftApp, Pos2, Rect};
|
||||
use super::{Color32, HashSet, LayerOp, PdfCraftApp, Pos2, Rect, Tokens, Vec2, icons, pos2, theme, vec2};
|
||||
|
||||
/// A validation badge drawn over a signature widget: the widget rectangle (user space), the verdict it shows, and its hover text.
|
||||
pub(crate) struct SignatureBadge {
|
||||
@@ -27,6 +27,121 @@ pub(crate) fn signature_badges(signatures: &[pdfcraft_engine::SignatureInfo], pa
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The empty signature fields on one page that get a sign tab, as their names and widget
|
||||
/// rectangles (user space). Each is unsigned and visible, on this page, with a rectangle that
|
||||
/// passes the same screen-space guard as [`signature_badges`]. A click must also be able to sign
|
||||
/// it, as in `forms_ui::page_input`: the document allows filling (`can_fill`), and the form field
|
||||
/// of that name is a signature field that isn't read-only, with a shown widget at that place
|
||||
/// that isn't read-only on its own.
|
||||
pub(crate) fn sign_tabs<'a>(
|
||||
signatures: &'a [pdfcraft_engine::SignatureInfo],
|
||||
form: &[pdfcraft_engine::FormField],
|
||||
page: usize,
|
||||
can_fill: bool,
|
||||
) -> Vec<(&'a str, [f64; 4])> {
|
||||
let mut empty = signatures
|
||||
.iter()
|
||||
.filter(|s| can_fill && !s.signed && s.visible && s.page == Some(page))
|
||||
.filter_map(|s| s.rect.filter(|r| r.iter().all(|v| v.is_finite() && v.abs() < f32::MAX as f64)).map(|r| (s.field.as_str(), r)))
|
||||
.peekable();
|
||||
if empty.peek().is_none() {
|
||||
return Vec::new();
|
||||
}
|
||||
// The widgets a click signs, by field name and exact rectangle, from one pass over the form:
|
||||
// a file with thousands of fields costs no more per frame than the field hit test does.
|
||||
let signable: HashSet<(&str, [u64; 4])> = form
|
||||
.iter()
|
||||
.filter(|f| f.kind == pdfcraft_engine::FormFieldKind::Signature && !f.read_only())
|
||||
.flat_map(|f| {
|
||||
f.widgets.iter().filter(|w| w.page == Some(page) && !w.hidden && !w.read_only).map(move |w| (f.name.as_str(), w.rect.map(f64::to_bits)))
|
||||
})
|
||||
.collect();
|
||||
empty.filter(|(name, r)| signable.contains(&(*name, r.map(f64::to_bits)))).collect()
|
||||
}
|
||||
|
||||
/// The largest sign tab's height, in points. Every other size is a share of the tab's height,
|
||||
/// taken from this one: a 3 pt inset, a 12 pt icon, 5 pt padding, an 11 pt label and 4 pt corners.
|
||||
pub(super) const SIGN_TAB_MAX: f32 = 18.0;
|
||||
/// The smallest sign tab's height, in points: a field too small for this chip gets no tab.
|
||||
const SIGN_TAB_MIN: f32 = 10.0;
|
||||
/// The share of its field's height on screen that a sign tab takes, between the two sizes.
|
||||
const SIGN_TAB_SHARE: f32 = 0.4;
|
||||
/// The smallest sign tab that carries the label; below it the tab is the icon alone.
|
||||
const SIGN_TAB_LABEL_MIN: f32 = 14.0;
|
||||
/// The label's font size on the largest sign tab; it shrinks with the tab.
|
||||
const SIGN_TAB_FONT: f32 = 11.0;
|
||||
|
||||
/// Where one sign tab is drawn on screen: its chip, the icon's square and, when the label fits,
|
||||
/// the point where the label starts (its left edge, on the chip's center line), with the
|
||||
/// label's font size and the chip's corner radius at this tab's size.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub(crate) struct SignTab {
|
||||
pub rect: Rect,
|
||||
pub icon: Rect,
|
||||
pub label: Option<Pos2>,
|
||||
pub font: f32,
|
||||
pub radius: f32,
|
||||
}
|
||||
|
||||
/// Lays out a sign tab inside the top-left corner of `field` (the widget on screen), for a label
|
||||
/// `label_width` points wide at [`SIGN_TAB_FONT`], its size on the largest tab. The tab is
|
||||
/// [`SIGN_TAB_SHARE`] of the field's height, from [`SIGN_TAB_MIN`] to [`SIGN_TAB_MAX`], and its
|
||||
/// inset, icon, padding, label and corners scale with it. It carries the label from
|
||||
/// [`SIGN_TAB_LABEL_MIN`] up when the whole tab fits in half the field's width, and is a square
|
||||
/// icon chip otherwise. It is left out when even that chip doesn't fit, or the field isn't finite.
|
||||
pub(crate) fn sign_tab_layout(field: Rect, label_width: f32) -> Option<SignTab> {
|
||||
if !field.is_finite() {
|
||||
return None;
|
||||
}
|
||||
// Finite, so the clamp has a number to work on (and its bounds are constants in order).
|
||||
let h = (field.height() * SIGN_TAB_SHARE).clamp(SIGN_TAB_MIN, SIGN_TAB_MAX);
|
||||
let scale = h / SIGN_TAB_MAX;
|
||||
let (inset, icon_side, pad) = (3.0 * scale, 12.0 * scale, 5.0 * scale);
|
||||
if field.height() < h + 2.0 * inset || h > field.width() / 2.0 {
|
||||
return None;
|
||||
}
|
||||
let full = pad + icon_side + pad + label_width * scale + pad;
|
||||
let with_label = h >= SIGN_TAB_LABEL_MIN && label_width.is_finite() && label_width > 0.0 && full <= field.width() / 2.0;
|
||||
let width = if with_label { full } else { h };
|
||||
let rect = Rect::from_min_size(field.min + Vec2::splat(inset), vec2(width, h));
|
||||
let icon_x = if with_label { rect.left() + pad } else { rect.center().x - icon_side / 2.0 };
|
||||
let icon = Rect::from_min_size(pos2(icon_x, rect.center().y - icon_side / 2.0), Vec2::splat(icon_side));
|
||||
let label = with_label.then(|| pos2(icon.right() + pad, rect.center().y));
|
||||
Some(SignTab { rect, icon, label, font: SIGN_TAB_FONT * scale, radius: 4.0 * scale })
|
||||
}
|
||||
|
||||
/// The sign tab's label, "Sign", laid out at `size` points.
|
||||
fn sign_tab_label(ui: &egui::Ui, size: f32) -> std::sync::Arc<egui::Galley> {
|
||||
ui.fonts_mut(|f| f.layout_no_wrap(tl!("Sign").to_string(), theme::semibold(size), Color32::WHITE))
|
||||
}
|
||||
|
||||
/// The sign tab of an empty signature field whose widget is at `field` on screen, on the page at
|
||||
/// `page`, laid out for its label measured at its largest size: where it is painted and where a
|
||||
/// click on it signs.
|
||||
pub(super) fn sign_tab_at(ui: &egui::Ui, field: Rect, page: Rect) -> Option<SignTab> {
|
||||
sign_tab_on_page(field, page, sign_tab_label(ui, SIGN_TAB_FONT).size().x)
|
||||
}
|
||||
|
||||
/// [`sign_tab_layout`] in the part of `field` that is on `page`: form fields take clicks on the
|
||||
/// page only, so a widget that straddles the page's edge gets its tab where a click reaches it,
|
||||
/// or none when that part has no room for one.
|
||||
pub(crate) fn sign_tab_on_page(field: Rect, page: Rect, label_width: f32) -> Option<SignTab> {
|
||||
sign_tab_layout(field.intersect(page), label_width)
|
||||
}
|
||||
|
||||
/// Paints a sign tab laid out by [`sign_tab_at`]: an accent chip with the signature icon and
|
||||
/// "Sign" in white, as the app's primary buttons are. The label is drawn at the tab's size; text
|
||||
/// scales with its size, and the padding takes up any rounding. Screen-only chrome, like the
|
||||
/// validation badges.
|
||||
pub(super) fn paint_sign_tab(ui: &egui::Ui, painter: &egui::Painter, tab: &SignTab, t: &Tokens) {
|
||||
painter.rect_filled(tab.rect, egui::epaint::CornerRadiusF32::same(tab.radius), t.accent);
|
||||
icons::paint(ui, tab.icon, "signature", tab.icon.width(), Color32::WHITE);
|
||||
if let Some(at) = tab.label {
|
||||
let galley = sign_tab_label(ui, tab.font);
|
||||
painter.galley(at - vec2(0.0, galley.size().y / 2.0), galley, Color32::WHITE);
|
||||
}
|
||||
}
|
||||
|
||||
// Keep the viewer's scroll identity tied to the document instead of its parent UI. Without
|
||||
// `fades` (Show Page Edge Shadows off) the viewport-edge gradients are off for this area only.
|
||||
pub(super) fn page_scroll<R>(
|
||||
|
||||
@@ -363,6 +363,9 @@ fn zoom_shortcuts(view: &mut DocView, pressed: &impl Fn(egui::KeyboardShortcut)
|
||||
}
|
||||
}
|
||||
|
||||
/// The document view's keyboard shortcuts: find, rotation, zoom (or the page grid's size),
|
||||
/// history, Escape, and the paging and scrolling keys. An open form field keeps the paging
|
||||
/// and scrolling keys for itself.
|
||||
pub fn shortcuts(view: &mut DocView, ctx: &egui::Context, speed: crate::scroll_speed::ScrollSpeed) {
|
||||
use egui::{Key, KeyboardShortcut, Modifiers};
|
||||
if ctx.input_mut(|i| i.consume_shortcut(&KeyboardShortcut::new(Modifiers::COMMAND, Key::F))) {
|
||||
@@ -407,8 +410,13 @@ pub fn shortcuts(view: &mut DocView, ctx: &egui::Context, speed: crate::scroll_s
|
||||
view.view_history(true);
|
||||
}
|
||||
let key = |k| (arrows || !matches!(k, Key::ArrowLeft | Key::ArrowRight | Key::ArrowUp | Key::ArrowDown)) && ctx.input(|i| i.key_pressed(k));
|
||||
// An open form field (a drop-down's or a list box's items) takes the arrows, Page Up / Page
|
||||
// Down, Home, End and Escape. A focused check box or radio button uses none of them, so the
|
||||
// page keys still work there.
|
||||
let field_open = view.forms.focus.is_some() && form_box.is_none();
|
||||
// An open menu takes Escape first and closes; the selection stays for the next one (#3535).
|
||||
if key(Key::Escape) && !egui::Popup::is_any_open(ctx) {
|
||||
// So does an open field, whose list closes.
|
||||
if key(Key::Escape) && !egui::Popup::is_any_open(ctx) && !field_open {
|
||||
if view.camera.is_some() || view.camera_done.is_some() {
|
||||
view.pending_action = Some(ViewAction::CancelCamera);
|
||||
} else if view.selection.is_some() || view.all_text {
|
||||
@@ -418,6 +426,10 @@ pub fn shortcuts(view: &mut DocView, ctx: &egui::Context, speed: crate::scroll_s
|
||||
view.find = None;
|
||||
}
|
||||
}
|
||||
// The open field's keys leave the page under it where it is.
|
||||
if field_open {
|
||||
return;
|
||||
}
|
||||
// Home and End, and the keys listed with them for Go to first / last page: Shift+Ctrl
|
||||
// (Shift+⌘ on macOS) with ↑ / ↓ or Page Up / Page Down (#6434).
|
||||
let shift_cmd = |k| KeyboardShortcut::new(Modifiers::COMMAND | Modifiers::SHIFT, k);
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
use egui::{Color32, CornerRadius, Pos2, Rect, Stroke};
|
||||
use pdfcraft_render::{DocInfo, LinkTarget, PageText};
|
||||
|
||||
use super::area::{SignTab, paint_sign_tab, sign_tab_at, sign_tabs};
|
||||
use super::{
|
||||
DocView, MARK_ICON_SHARE, PageEnv, PageFrame, PageSlot, PageXform, Selection, Span, cached_edit_images, click_unit, mark_anchor,
|
||||
signature_badges, verdict_mark_rect,
|
||||
@@ -30,6 +31,8 @@ pub(super) struct PageInput {
|
||||
/// The press's click came up over what the press began on: a link's or a field's click counts
|
||||
/// only then, as a button's does.
|
||||
pub(super) released_over: bool,
|
||||
/// The sign tabs on empty fields a click would sign, painted over the page.
|
||||
pub(super) sign_tabs: Vec<SignTab>,
|
||||
}
|
||||
|
||||
/// Common geometry and pointer state for a tool acting on one page.
|
||||
@@ -83,6 +86,10 @@ pub(super) fn page_tool_input(ui: &mut egui::Ui, view: &mut DocView, frame: &mut
|
||||
};
|
||||
// While a table is being set up, nothing else is drawn or moved.
|
||||
let prepare_allowed = can_modify && table_preview.is_none() && frame.out.open_table.is_none();
|
||||
// An empty field a click would sign carries a small tab saying so, shown only while
|
||||
// a click on the field signs it (the Select tool, not while preparing a form). The tab
|
||||
// is drawn over every field, so a click on it signs its field (`forms_ui::hit`).
|
||||
let tabs = page_sign_tabs(ui, doc, form, info, slot, can_fill, tool == QuickTool::Select && !preparing);
|
||||
let hits = PageHits {
|
||||
page: i,
|
||||
xf: &xf,
|
||||
@@ -103,6 +110,7 @@ pub(super) fn page_tool_input(ui: &mut egui::Ui, view: &mut DocView, frame: &mut
|
||||
doc,
|
||||
clip: ui.clip_rect(),
|
||||
text_links,
|
||||
tabs: &tabs,
|
||||
};
|
||||
if let Some(o) = ptr.pressed() {
|
||||
// A press with Shift or ⌘ in Edit text is the objects', whatever lies under it
|
||||
@@ -255,7 +263,39 @@ pub(super) fn page_tool_input(ui: &mut egui::Ui, view: &mut DocView, frame: &mut
|
||||
let on_comment = comments::page_input(ui, resp, &pcx, press, taken, view);
|
||||
let consumed = taken || on_comment;
|
||||
let hover = pointer.and_then(|p| claim_under(&hits, view, p, frame.env.unobstructed));
|
||||
PageInput { press, text_drag: !view.router.keeps_drag(), consumed, area_tool, hover, released_over }
|
||||
PageInput {
|
||||
press,
|
||||
text_drag: !view.router.keeps_drag(),
|
||||
consumed,
|
||||
area_tool,
|
||||
hover,
|
||||
released_over,
|
||||
sign_tabs: tabs.into_iter().map(|(_, tab)| tab).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The sign tabs on the slot's page, on empty fields a click would sign, each with the field it
|
||||
/// signs; none unless `shown`.
|
||||
fn page_sign_tabs<'a>(
|
||||
ui: &egui::Ui,
|
||||
doc: &'a pdfcraft_engine::Document,
|
||||
form: &[pdfcraft_engine::FormField],
|
||||
info: &DocInfo,
|
||||
slot: &PageSlot,
|
||||
can_fill: bool,
|
||||
shown: bool,
|
||||
) -> Vec<(&'a str, SignTab)> {
|
||||
let PageSlot { i, xf, .. } = slot;
|
||||
let i = *i;
|
||||
if !shown {
|
||||
return Vec::new();
|
||||
}
|
||||
sign_tabs(&doc.signatures, form, i, can_fill)
|
||||
.into_iter()
|
||||
.filter_map(|(name, [x0, y0, x1, y1])| {
|
||||
sign_tab_at(ui, xf.user_rect(info, i, [x0 as f32, y0 as f32, x1 as f32, y1 as f32]), xf.rect).map(|tab| (name, tab))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// What lies under the pointer at `p`, after the tools act: its top, what a press there would take,
|
||||
@@ -301,6 +341,7 @@ fn tool_input(
|
||||
by_line,
|
||||
can_crop,
|
||||
can_modify,
|
||||
custom_line,
|
||||
custom_stamp,
|
||||
date_text,
|
||||
doc,
|
||||
@@ -329,7 +370,7 @@ fn tool_input(
|
||||
}
|
||||
if let Some(cs) = custom_stamp.as_ref()
|
||||
&& allowed
|
||||
&& crate::stamps_ui::place_custom(cx, cs, author, free, view)
|
||||
&& crate::stamps_ui::place_custom(cx, cs, custom_line, author, free, view)
|
||||
{
|
||||
frame.out.stamp_placed = true;
|
||||
}
|
||||
@@ -406,7 +447,7 @@ fn right_click(hits: &PageHits<'_>, under: &[crate::page_router::Hit], view: &mu
|
||||
Some(Owner::Comment { index, .. }) => Some(index),
|
||||
_ => None,
|
||||
};
|
||||
comments::context(hits.pcx, comment, view);
|
||||
comments::context(hits.pcx, p, comment, view);
|
||||
}
|
||||
if let Some(Owner::PrepareField { field, widget }) = context {
|
||||
crate::prepare::context(hits.form, field, widget, view);
|
||||
@@ -460,6 +501,9 @@ struct PageHits<'a> {
|
||||
clip: Rect,
|
||||
/// Addresses written as plain page text open like links (#4207).
|
||||
text_links: bool,
|
||||
/// The sign tabs on empty signature fields, with the field each one signs: drawn over every
|
||||
/// field, so the pointer on one is on its own field.
|
||||
tabs: &'a [(&'a str, SignTab)],
|
||||
}
|
||||
|
||||
impl PageHits<'_> {
|
||||
@@ -543,6 +587,7 @@ impl PageHits<'_> {
|
||||
doc,
|
||||
clip,
|
||||
text_links,
|
||||
tabs,
|
||||
} = *self;
|
||||
// A press with Shift or ⌘ is the objects' (`object_ui::modified_hit`), off crop mode's page.
|
||||
if let Some(objects) = objects {
|
||||
@@ -565,7 +610,7 @@ impl PageHits<'_> {
|
||||
let fields = if preparing {
|
||||
crate::prepare::hit(xf, info, page, form, field_tool, prepare_allowed, &view.prepare, p)
|
||||
} else if tool == QuickTool::Select {
|
||||
crate::forms_ui::hit(xf, info, page, form, can_fill, p)
|
||||
crate::forms_ui::hit(xf, info, page, form, tabs, can_fill, p)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
@@ -848,6 +893,7 @@ pub(super) fn page_overlays(ui: &mut egui::Ui, view: &mut DocView, frame: &mut P
|
||||
prefs,
|
||||
preparing,
|
||||
redact_mark,
|
||||
t,
|
||||
table_preview,
|
||||
tool,
|
||||
unobstructed,
|
||||
@@ -973,6 +1019,11 @@ pub(super) fn page_overlays(ui: &mut egui::Ui, view: &mut DocView, frame: &mut P
|
||||
view.flash = None;
|
||||
}
|
||||
}
|
||||
// The sign tabs (above). Like the validation badges, they never enter the file,
|
||||
// exports or printing.
|
||||
for tab in &input.sign_tabs {
|
||||
paint_sign_tab(ui, painter, tab, t);
|
||||
}
|
||||
// Validation badges are viewer chrome over the widget. A recognised named-layer appearance may
|
||||
// show the verdict in the display copy too; saves retain its original streams. Badges never
|
||||
// enter document streams, exports or either print path. Their tips show where the comments'
|
||||
|
||||
@@ -164,7 +164,7 @@ fn edges_are_primary_finite_in_order_and_capped() {
|
||||
}
|
||||
|
||||
/// The page modules: the per-page chain in `canvas::document_area` and what it calls.
|
||||
const PAGE_MODULES: [&str; 37] = [
|
||||
const PAGE_MODULES: [&str; 38] = [
|
||||
"canvas.rs",
|
||||
"canvas/page_input.rs",
|
||||
"canvas/area.rs",
|
||||
@@ -182,6 +182,7 @@ const PAGE_MODULES: [&str; 37] = [
|
||||
"tools/comments/input.rs",
|
||||
"tools/comments/menu.rs",
|
||||
"tools/comments/paint.rs",
|
||||
"tools/comments/popups.rs",
|
||||
"tools/comments/state.rs",
|
||||
"tools/forms_ui.rs",
|
||||
"tools/prepare.rs",
|
||||
@@ -241,14 +242,17 @@ const RAW_READS: [&str; 21] = [
|
||||
|
||||
/// Functions in the page modules that are not page input and read egui's pointer state
|
||||
/// themselves: (file, function, why).
|
||||
const NOT_PAGE_INPUT: [(&str, &str, &str); 10] = [
|
||||
const NOT_PAGE_INPUT: [(&str, &str, &str); 13] = [
|
||||
("canvas/area.rs", "zoom_anchor", "a pinch zooms the whole view, and is read before the pages' widget exists"),
|
||||
("canvas/area.rs", "drawing_edge_pointer", "scrolls the view at its edges, read before the pages' widget exists"),
|
||||
("canvas/area.rs", "glide_interrupted", "a press anywhere stops the touchpad's glide"),
|
||||
("canvas/area.rs", "presentation_click", "full screen's click to turn the page, read before the pages' widget exists"),
|
||||
("canvas/bars.rs", "page_size_hint", "the page size hint sits in the view's corner, not on a page"),
|
||||
("canvas/organize.rs", "organize_grid", "Organize Pages shows thumbnails, not pages"),
|
||||
("tools/comments/popups.rs", "popups", "the comment pop-up windows are Areas of their own over the page"),
|
||||
("tools/forms_ui.rs", "overlay", "the field editor is an Area of its own over the page"),
|
||||
("tools/forms_ui.rs", "choice_list", "a drop-down's open list is an Area of its own over the page"),
|
||||
("tools/forms_ui.rs", "scroll_bar", "the scroll bar of a drop-down's open list, in its Area over the page"),
|
||||
("tools/content_ui.rs", "editor", "the added-text editor is an Area of its own over the page"),
|
||||
("tools/edit_text_ui.rs", "overlay", "the paragraph editor is an Area of its own over the page"),
|
||||
("tools/fill_sign/scan.rs", "scan_tab", "the signature dialog's Scan tab"),
|
||||
@@ -292,10 +296,15 @@ const NOT_PAGE_DRAGS: [(&str, &str, &str); 3] = [
|
||||
const CURSOR_WRITES: [&str; 4] = ["set_cursor_icon(", ".cursor_icon = ", "on_hover_cursor(", "on_hover_and_drag_cursor("];
|
||||
|
||||
/// Functions in the page modules that set a cursor other than the pages': (file, function, why).
|
||||
const NOT_PAGE_CURSOR: [(&str, &str, &str); 3] = [
|
||||
const NOT_PAGE_CURSOR: [(&str, &str, &str); 4] = [
|
||||
("tools/fill_sign/scan.rs", "scan_tab", "the signature dialog's Scan tab"),
|
||||
("tools/edit_text_ui.rs", "overlay", "the paragraph editor is an Area of its own over the page, drawn after the pages' cursor is set"),
|
||||
("tools/calc_order_ui.rs", "panel", "the Calculation order panel, whose rows are dragged to reorder them"),
|
||||
(
|
||||
"tools/comments/popups.rs",
|
||||
"popups",
|
||||
"the comment pop-up windows are Areas of their own over the page; their title bars are dragged to move them",
|
||||
),
|
||||
];
|
||||
|
||||
/// Whether `line` uses `name`, and not a longer name that ends in it (a field, after its `.`, is
|
||||
@@ -587,9 +596,14 @@ const PAGE_HITS_ASKERS: [(&str, &str, &str); 5] = [
|
||||
const COMMENT_POINT_TESTS: [&str; 2] = [".comment_at(", "PageCx::comment_at("];
|
||||
|
||||
/// The functions that ask which comment lies under a point: (file, function, why).
|
||||
const COMMENT_POINT_TESTERS: [(&str, &str, &str); 3] = [
|
||||
const COMMENT_POINT_TESTERS: [(&str, &str, &str); 4] = [
|
||||
("tools/comments/input.rs", "hit", "the comments' hit test"),
|
||||
("tools/comments/input.rs", "context_hit", "the comments' hit test for a right-click"),
|
||||
(
|
||||
"tools/comments/state.rs",
|
||||
"click_target",
|
||||
"the comments' hit tests' lookup: a group subordinate (`/RT /Group`, ISO 32000-2 §12.5.6.2) stands for its primary",
|
||||
),
|
||||
("tools/comments/state.rs", "picked", "which group subordinate a click selected its primary through, when the click is acted on"),
|
||||
("tools/comments/paint.rs", "paint_page", "a redaction mark shows its fill under the pointer with every tool, as comments' tips show"),
|
||||
];
|
||||
|
||||
|
||||
@@ -76,9 +76,14 @@ impl DocView {
|
||||
/// Screen position of the centre of glyph `glyph` on `page`, if that page is on screen and its
|
||||
/// text layer is loaded (used by UI tests and automation to aim pointer input).
|
||||
pub fn glyph_screen_pos(&self, page: usize, glyph: usize) -> Option<Pos2> {
|
||||
self.glyph_screen_rect(page, glyph).map(|r| r.center())
|
||||
}
|
||||
|
||||
/// The screen rectangle of glyph `glyph` on `page`, when the page is on screen.
|
||||
pub fn glyph_screen_rect(&self, page: usize, glyph: usize) -> Option<Rect> {
|
||||
let (_, xf) = self.screen_xforms.iter().find(|(p, _)| *p == page)?;
|
||||
let g = self.texts.get(&page)?.glyphs.get(glyph)?;
|
||||
Some(xf.view_rect(g.rect).center())
|
||||
Some(xf.view_rect(g.rect))
|
||||
}
|
||||
|
||||
/// Selected text, if any (⌘C).
|
||||
@@ -172,6 +177,9 @@ enum SelectionAction {
|
||||
Copy,
|
||||
}
|
||||
|
||||
/// The selection bar's width before it has been laid out once (English labels).
|
||||
const SELECTION_BAR_GUESS: f32 = 520.0;
|
||||
|
||||
/// Actions on an existing text selection, next to the selected words.
|
||||
pub(super) fn selection_actions(
|
||||
ui: &mut egui::Ui,
|
||||
@@ -203,32 +211,33 @@ pub(super) fn selection_actions(
|
||||
if !viewport.intersects(rect) {
|
||||
return false;
|
||||
}
|
||||
let x = rect.left().clamp(viewport.left() + 8.0, (viewport.right() - 520.0).max(viewport.left() + 8.0));
|
||||
let id = egui::Id::unique(("text-selection-actions", view.view_key()));
|
||||
// The bar stays inside the pages' area, by the width it had last frame (its labels make it
|
||||
// wider in some languages), so it never covers a side panel; a first guess before it has one.
|
||||
let width = egui::AreaState::load(ui.ctx(), id).and_then(|a| a.size).map_or(SELECTION_BAR_GUESS, |s| s.x);
|
||||
let x = rect.left().clamp(viewport.left() + 8.0, (viewport.right() - width - 8.0).max(viewport.left() + 8.0));
|
||||
let y = if rect.bottom() + 48.0 < viewport.bottom() { rect.bottom() + 6.0 } else { (rect.top() - 44.0).max(viewport.top() + 6.0) };
|
||||
let mut chosen = None;
|
||||
egui::Area::new(egui::Id::unique(("text-selection-actions", view.view_key()))).order(egui::Order::Foreground).fixed_pos(pos2(x, y)).show(
|
||||
ui.ctx(),
|
||||
|ui| {
|
||||
egui::Frame::popup(ui.style()).show(ui, |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
for (label, action) in [
|
||||
(tl!("Add comment"), SelectionAction::Note),
|
||||
(tl!("Highlight"), SelectionAction::Markup(comments::CommentTool::Highlight)),
|
||||
(tl!("Underline"), SelectionAction::Markup(comments::CommentTool::Underline)),
|
||||
(tl!("Strikethrough"), SelectionAction::Markup(comments::CommentTool::StrikeOut)),
|
||||
(tl!("Replace text"), SelectionAction::Replace),
|
||||
] {
|
||||
if ui.add_enabled(can_comment, egui::Button::new(label)).clicked() {
|
||||
chosen = Some(action);
|
||||
}
|
||||
egui::Area::new(id).order(egui::Order::Foreground).fixed_pos(pos2(x, y)).show(ui.ctx(), |ui| {
|
||||
egui::Frame::popup(ui.style()).show(ui, |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
for (label, action) in [
|
||||
(tl!("Add comment"), SelectionAction::Note),
|
||||
(tl!("Highlight"), SelectionAction::Markup(comments::CommentTool::Highlight)),
|
||||
(tl!("Underline"), SelectionAction::Markup(comments::CommentTool::Underline)),
|
||||
(tl!("Strikethrough"), SelectionAction::Markup(comments::CommentTool::StrikeOut)),
|
||||
(tl!("Replace text"), SelectionAction::Replace),
|
||||
] {
|
||||
if ui.add_enabled(can_comment, egui::Button::new(label)).clicked() {
|
||||
chosen = Some(action);
|
||||
}
|
||||
if ui.add_enabled(can_copy, egui::Button::new(tl!("Copy"))).clicked() {
|
||||
chosen = Some(SelectionAction::Copy);
|
||||
}
|
||||
});
|
||||
}
|
||||
if ui.add_enabled(can_copy, egui::Button::new(tl!("Copy"))).clicked() {
|
||||
chosen = Some(SelectionAction::Copy);
|
||||
}
|
||||
});
|
||||
},
|
||||
);
|
||||
});
|
||||
});
|
||||
let Some(action) = chosen else { return false };
|
||||
if let SelectionAction::Copy = action {
|
||||
// Copying closes the bar but keeps the words selected, for ⌘C or a second action.
|
||||
|
||||
@@ -0,0 +1,377 @@
|
||||
//! Unit tests for the sign tabs on empty signature fields (`area.rs`).
|
||||
|
||||
use super::area::{SIGN_TAB_MAX, sign_tab_layout, sign_tab_on_page, sign_tabs};
|
||||
use super::*;
|
||||
use pdfcraft_engine::{FormField, FormFieldKind, FormWidget, SignatureInfo};
|
||||
|
||||
/// The widget rectangle the unit tests use (user space).
|
||||
const RECT: [f64; 4] = [20.0, 110.0, 140.0, 180.0];
|
||||
|
||||
/// An unsigned, visible signature listing for field `name` with its widget on `page` at
|
||||
/// `rect`. Each test changes the one thing it is about.
|
||||
fn listing(name: &str, page: usize, rect: [f64; 4]) -> SignatureInfo {
|
||||
SignatureInfo {
|
||||
field: name.into(),
|
||||
signed: false,
|
||||
page: Some(page),
|
||||
rect: Some(rect),
|
||||
visible: true,
|
||||
signer: None,
|
||||
certificate: None,
|
||||
chain: Vec::new(),
|
||||
date: None,
|
||||
signing_time: None,
|
||||
reason: None,
|
||||
location: None,
|
||||
contact: None,
|
||||
sub_filter: None,
|
||||
doc_timestamp: false,
|
||||
certify: None,
|
||||
revision: 1,
|
||||
signed_len: 0,
|
||||
digest: None,
|
||||
algorithm: None,
|
||||
timestamp: false,
|
||||
timestamp_time: None,
|
||||
status: pdfcraft_engine::SignatureStatus::Unknown,
|
||||
modification: pdfcraft_engine::sign::Modification::None,
|
||||
details: Vec::new(),
|
||||
verdict_shown: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The signature form field `name` with one shown widget on `page` at `rect`.
|
||||
fn field(name: &str, page: usize, rect: [f64; 4]) -> FormField {
|
||||
FormField {
|
||||
name: name.into(),
|
||||
obj: pdfcraft_cos::ObjRef::new(4, 0),
|
||||
kind: FormFieldKind::Signature,
|
||||
value: Vec::new(),
|
||||
default: Vec::new(),
|
||||
flags: 0,
|
||||
max_len: None,
|
||||
options: Vec::new(),
|
||||
selected: Vec::new(),
|
||||
single_value_is_array: false,
|
||||
da: String::new(),
|
||||
quadding: 0,
|
||||
tooltip: None,
|
||||
widgets: vec![FormWidget {
|
||||
obj: pdfcraft_cos::ObjRef::new(4, 0),
|
||||
page: Some(page),
|
||||
rect,
|
||||
on_state: None,
|
||||
state: None,
|
||||
tab: 0,
|
||||
locked: false,
|
||||
hidden: false,
|
||||
read_only: false,
|
||||
rotation: 0,
|
||||
caption: None,
|
||||
list: None,
|
||||
round: false,
|
||||
}],
|
||||
actions: Default::default(),
|
||||
button: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The cases (by name) whose single listing and form still got a tab on page 0.
|
||||
fn tabbed<'a>(cases: &[(&'a str, SignatureInfo, Vec<FormField>, bool)]) -> Vec<&'a str> {
|
||||
cases.iter().filter(|(_, s, form, can_fill)| !sign_tabs(std::slice::from_ref(s), form, 0, *can_fill).is_empty()).map(|c| c.0).collect()
|
||||
}
|
||||
|
||||
/// An empty, visible signature field that a click signs gets one tab, at its widget, on its
|
||||
/// own page only.
|
||||
#[test]
|
||||
fn sign_tabs_mark_an_empty_field_that_a_click_signs() {
|
||||
let approver = [listing("Approver", 0, RECT)];
|
||||
assert_eq!(sign_tabs(&approver, &[field("Approver", 0, RECT)], 0, true), vec![("Approver", RECT)]);
|
||||
let later = [listing("Witness", 1, RECT)];
|
||||
assert_eq!(sign_tabs(&later, &[field("Witness", 1, RECT)], 1, true), vec![("Witness", RECT)]);
|
||||
assert!(sign_tabs(&later, &[field("Witness", 1, RECT)], 0, true).is_empty(), "not on the page before");
|
||||
}
|
||||
|
||||
/// Signed, invisible, other-page and unplaced fields get no tab. Each case is checked on its
|
||||
/// own, so a failure names every case that wrongly got one.
|
||||
#[test]
|
||||
fn sign_tabs_skip_signed_invisible_other_page_and_unplaced_fields() {
|
||||
let form = || vec![field("Approver", 0, RECT)];
|
||||
let cases = [
|
||||
("signed", SignatureInfo { signed: true, ..listing("Approver", 0, RECT) }, form(), true),
|
||||
("invisible", SignatureInfo { visible: false, ..listing("Approver", 0, RECT) }, form(), true),
|
||||
("on another page", listing("Approver", 1, RECT), vec![field("Approver", 1, RECT)], true),
|
||||
("on no page", SignatureInfo { page: None, ..listing("Approver", 0, RECT) }, form(), true),
|
||||
("without a rectangle", SignatureInfo { rect: None, ..listing("Approver", 0, RECT) }, form(), true),
|
||||
];
|
||||
assert_eq!(tabbed(&cases), Vec::<&str>::new());
|
||||
}
|
||||
|
||||
/// NaN, infinite and gigantic rectangles never reach the painter, even when the form's
|
||||
/// widget carries the same numbers.
|
||||
#[test]
|
||||
fn sign_tabs_skip_rectangles_that_cannot_reach_the_screen() {
|
||||
let hostile = |name: &'static str, rect: [f64; 4]| (name, listing("Approver", 0, rect), vec![field("Approver", 0, rect)], true);
|
||||
let cases = [
|
||||
hostile("NaN", [f64::NAN, 110.0, 140.0, 180.0]),
|
||||
hostile("infinite", [20.0, f64::INFINITY, 140.0, 180.0]),
|
||||
hostile("minus infinite", [20.0, 110.0, f64::NEG_INFINITY, 180.0]),
|
||||
hostile("huge", [20.0, 110.0, 1e300, 180.0]),
|
||||
];
|
||||
assert_eq!(tabbed(&cases), Vec::<&str>::new());
|
||||
}
|
||||
|
||||
/// Fields a click would not sign get no tab: a read-only field, a document that refuses
|
||||
/// filling, a listing with no form field of its name, a field of another kind of that name,
|
||||
/// and a widget that is hidden, read-only on its own or elsewhere.
|
||||
#[test]
|
||||
fn sign_tabs_skip_fields_that_a_click_cannot_sign() {
|
||||
let empty = || listing("Approver", 0, RECT);
|
||||
let with = |change: fn(&mut FormField)| {
|
||||
let mut f = field("Approver", 0, RECT);
|
||||
change(&mut f);
|
||||
vec![f]
|
||||
};
|
||||
let cases = [
|
||||
("read-only", empty(), with(|f| f.flags = pdfcraft_engine::field_flags::READ_ONLY), true),
|
||||
("filling refused", empty(), with(|_| {}), false),
|
||||
("no form field", empty(), Vec::new(), true),
|
||||
("another kind", empty(), with(|f| f.kind = FormFieldKind::Text), true),
|
||||
("hidden widget", empty(), with(|f| f.widgets.iter_mut().for_each(|w| w.hidden = true)), true),
|
||||
("read-only widget", empty(), with(|f| f.widgets.iter_mut().for_each(|w| w.read_only = true)), true),
|
||||
("widget elsewhere", empty(), with(|f| f.widgets.iter_mut().for_each(|w| w.rect = [160.0, 110.0, 280.0, 180.0])), true),
|
||||
];
|
||||
assert_eq!(tabbed(&cases), Vec::<&str>::new());
|
||||
}
|
||||
|
||||
/// Whether two layout sizes match, to a hundredth of a point.
|
||||
fn near(a: f32, b: f32) -> bool {
|
||||
(a - b).abs() < 0.01
|
||||
}
|
||||
|
||||
/// What a field `width` by `height` points on screen shows, for a label 30 pt wide on the
|
||||
/// largest tab: "label" (the full tab), "icon" (the square chip) or "none".
|
||||
fn shows(width: f32, height: f32) -> &'static str {
|
||||
match sign_tab_layout(Rect::from_min_size(Pos2::ZERO, vec2(width, height)), 30.0) {
|
||||
Some(tab) if tab.label.is_some() => "label",
|
||||
Some(_) => "icon",
|
||||
None => "none",
|
||||
}
|
||||
}
|
||||
|
||||
/// The tab is 0.4 of the field's height on screen, at most 18 pt: a tall, wide field gets the
|
||||
/// 18 pt tab with its label 3 pt inside the corner, and a 29 pt field (a 22 pt box at fit
|
||||
/// width) an 11.6 pt icon chip, too small for the label, with the inset and icon scaled to it.
|
||||
#[test]
|
||||
fn sign_tab_layout_scales_the_chip_with_the_field_height() {
|
||||
let large = Rect::from_min_size(pos2(100.0, 200.0), vec2(400.0, 60.0));
|
||||
let tab = sign_tab_layout(large, 30.0).expect("fits");
|
||||
assert!(near(tab.rect.height(), 18.0) && tab.rect.min == large.min + vec2(3.0, 3.0), "{tab:?}");
|
||||
assert!(near(tab.icon.width(), 12.0) && tab.rect.contains_rect(tab.icon), "{tab:?}");
|
||||
let at = tab.label.expect("the label fits");
|
||||
assert!(at.x >= tab.icon.right() && at.x + 30.0 <= tab.rect.right() && at.y == tab.rect.center().y, "{tab:?}");
|
||||
|
||||
let short = Rect::from_min_size(pos2(100.0, 200.0), vec2(400.0, 29.0));
|
||||
let tab = sign_tab_layout(short, 30.0).expect("fits");
|
||||
assert!(near(tab.rect.height(), 11.6) && near(tab.rect.width(), 11.6) && tab.label.is_none(), "{tab:?}");
|
||||
let inset = tab.rect.min - short.min;
|
||||
assert!(near(inset.x, 11.6 / 6.0) && near(inset.y, 11.6 / 6.0) && short.contains_rect(tab.rect), "{tab:?}");
|
||||
assert!(near(tab.icon.width(), 11.6 * 2.0 / 3.0) && tab.rect.contains_rect(tab.icon), "{tab:?}");
|
||||
}
|
||||
|
||||
/// A 19 pt field (a 14 pt box at fit width) still gets the smallest chip, 10 pt with the icon
|
||||
/// alone. A 12 pt field is too short for even that, and a rectangle that isn't finite gets
|
||||
/// nothing. A label that can't be measured is left out instead of drawn at a NaN position.
|
||||
#[test]
|
||||
fn sign_tab_layout_keeps_a_small_icon_on_short_fields_and_none_below() {
|
||||
let field = Rect::from_min_size(pos2(100.0, 200.0), vec2(400.0, 19.0));
|
||||
let tab = sign_tab_layout(field, 30.0).expect("the smallest chip fits");
|
||||
assert!(near(tab.rect.height(), 10.0) && near(tab.rect.width(), 10.0) && tab.label.is_none(), "{tab:?}");
|
||||
assert!(field.contains_rect(tab.rect) && tab.rect.contains_rect(tab.icon), "{tab:?}");
|
||||
let cases = [
|
||||
("12 pt tall", Rect::from_min_size(Pos2::ZERO, vec2(400.0, 12.0))),
|
||||
("infinite", Rect::from_min_max(Pos2::ZERO, pos2(f32::INFINITY, 40.0))),
|
||||
("NaN", Rect::from_min_max(pos2(f32::NAN, 0.0), pos2(400.0, 40.0))),
|
||||
];
|
||||
let laid_out: Vec<&str> = cases.iter().filter(|(_, r)| sign_tab_layout(*r, 30.0).is_some()).map(|c| c.0).collect();
|
||||
assert_eq!(laid_out, Vec::<&str>::new());
|
||||
let roomy = Rect::from_min_size(Pos2::ZERO, vec2(400.0, 60.0));
|
||||
assert_eq!(sign_tab_layout(roomy, f32::NAN).map(|t| t.label), Some(None));
|
||||
}
|
||||
|
||||
/// The label's font and the chip's corners shrink with the tab: 11 pt and 4 pt on the largest
|
||||
/// tab, 8.8 pt and 3.2 pt on the 14.4 pt tab of a 36 pt field.
|
||||
#[test]
|
||||
fn sign_tab_layout_scales_the_label_font_and_corners_with_the_chip() {
|
||||
let large = sign_tab_layout(Rect::from_min_size(Pos2::ZERO, vec2(400.0, 60.0)), 30.0).expect("fits");
|
||||
assert!(near(large.font, 11.0) && near(large.radius, 4.0), "{large:?}");
|
||||
let small = sign_tab_layout(Rect::from_min_size(Pos2::ZERO, vec2(400.0, 36.0)), 30.0).expect("fits");
|
||||
assert!(near(small.font, 8.8) && near(small.radius, 3.2) && small.label.is_some(), "{small:?}");
|
||||
}
|
||||
|
||||
/// As a 36 pt field (a 14.4 pt tab, its label 24 pt wide at that size) narrows, the tab keeps
|
||||
/// its label while the whole tab fits in half the width (91.2 pt), then shows the icon alone
|
||||
/// while the chip does (28.8 pt), then nothing.
|
||||
#[test]
|
||||
fn sign_tab_layout_drops_the_label_then_the_tab_as_the_field_narrows() {
|
||||
let widths = [400.0, 92.0, 90.0, 29.0, 28.0];
|
||||
assert_eq!(widths.map(|w| shows(w, 36.0)), ["label", "label", "icon", "icon", "none"]);
|
||||
let tab = sign_tab_layout(Rect::from_min_size(Pos2::ZERO, vec2(92.0, 36.0)), 30.0).expect("fits");
|
||||
assert!(near(tab.rect.height(), 14.4) && tab.rect.width() <= 46.0, "{tab:?}");
|
||||
}
|
||||
|
||||
/// A field that straddles the page's edge gets its tab in the part on the page, where clicks
|
||||
/// reach it, or none when that part has no room for one.
|
||||
#[test]
|
||||
fn a_sign_tab_stays_on_the_page() {
|
||||
let page = Rect::from_min_size(pos2(100.0, 50.0), vec2(600.0, 800.0));
|
||||
let straddling = Rect::from_min_size(pos2(60.0, 20.0), vec2(300.0, 90.0));
|
||||
let tab = sign_tab_on_page(straddling, page, 30.0).expect("the part on the page has room");
|
||||
assert!(page.contains_rect(tab.rect), "{tab:?} on {page:?}");
|
||||
assert_eq!(tab.rect.height(), SIGN_TAB_MAX, "sized to the 60 px on the page");
|
||||
let sliver = Rect::from_min_size(pos2(60.0, 20.0), vec2(300.0, 36.0));
|
||||
assert_eq!(sign_tab_on_page(sliver, page, 30.0), None, "6 px on the page");
|
||||
let off = Rect::from_min_size(pos2(60.0, 900.0), vec2(300.0, 90.0));
|
||||
assert_eq!(sign_tab_on_page(off, page, 30.0), None, "wholly off the page");
|
||||
}
|
||||
|
||||
/// Where two sign tabs overlap, a click takes the one painted last, which is on top.
|
||||
#[test]
|
||||
fn the_sign_tab_painted_last_takes_the_click() {
|
||||
let tab = |x: f32| sign_tab_layout(Rect::from_min_size(pos2(x, 0.0), vec2(300.0, 60.0)), 30.0).expect("fits");
|
||||
let tabs = [("Approver", tab(0.0)), ("Witness", tab(10.0))];
|
||||
let both = tabs[1].1.rect.left_center() + vec2(2.0, 0.0);
|
||||
assert!(tabs[0].1.rect.contains(both), "the tabs overlap there");
|
||||
assert_eq!(crate::forms_ui::tab_under(&tabs, both), Some("Witness"));
|
||||
assert_eq!(crate::forms_ui::tab_under(&tabs, tabs[0].1.rect.left_center() + vec2(2.0, 0.0)), Some("Approver"));
|
||||
assert_eq!(crate::forms_ui::tab_under(&tabs, pos2(-5.0, -5.0)), None);
|
||||
}
|
||||
|
||||
/// One page with three signature fields: Approver is empty, Witness is signed (a signature
|
||||
/// dictionary as its value is enough to list it as signed) and Locked is empty but read-only.
|
||||
const SIGN_FIELDS: &[u8] = b"%PDF-1.7
|
||||
1 0 obj << /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [4 0 R 5 0 R 6 0 R] >> >> endobj
|
||||
2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj
|
||||
3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 300 200] /Annots [4 0 R 5 0 R 6 0 R] >> endobj
|
||||
4 0 obj << /Type /Annot /Subtype /Widget /FT /Sig /T (Approver) /Rect [20 110 140 180] /P 3 0 R /F 4 >> endobj
|
||||
5 0 obj << /Type /Annot /Subtype /Widget /FT /Sig /T (Witness) /V << /Type /Sig >> /Rect [160 110 280 180] /P 3 0 R /F 4 >> endobj
|
||||
6 0 obj << /Type /Annot /Subtype /Widget /FT /Sig /T (Locked) /Ff 1 /Rect [20 20 140 90] /P 3 0 R /F 4 >> endobj
|
||||
trailer << /Root 1 0 R >>
|
||||
%%EOF";
|
||||
|
||||
/// Every shape painted in the last frame, with nested lists flattened.
|
||||
fn painted(h: &egui_kittest::Harness<'static, PdfCraftApp>) -> Vec<egui::Shape> {
|
||||
let mut stack: Vec<egui::Shape> = h.output().shapes.iter().map(|c| c.shape.clone()).collect();
|
||||
let mut out = Vec::new();
|
||||
while let Some(shape) = stack.pop() {
|
||||
match shape {
|
||||
egui::Shape::Vec(inner) => stack.extend(inner),
|
||||
shape => out.push(shape),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Where the named field's first widget is on screen.
|
||||
fn field_on_screen(h: &egui_kittest::Harness<'static, PdfCraftApp>, name: &str) -> Rect {
|
||||
let app = h.state();
|
||||
let view = &app.views[0];
|
||||
let doc = app.session.get(view.id).expect("open");
|
||||
let f = doc.form.iter().find(|f| f.name == name).expect("field");
|
||||
crate::forms_ui::field_screen_rect(view, &doc.info, f, 0).expect("on screen")
|
||||
}
|
||||
|
||||
/// One page where the text field Name, first in the form's order, covers the top-left corner
|
||||
/// of the empty signature field Approver, where its sign tab is drawn.
|
||||
const SIGN_UNDER_TEXT: &[u8] = b"%PDF-1.7
|
||||
1 0 obj << /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [4 0 R 5 0 R] >> >> endobj
|
||||
2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj
|
||||
3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 300 200] /Annots [4 0 R 5 0 R] >> endobj
|
||||
4 0 obj << /Type /Annot /Subtype /Widget /FT /Tx /T (Name) /Rect [10 120 130 190] /P 3 0 R /F 4 >> endobj
|
||||
5 0 obj << /Type /Annot /Subtype /Widget /FT /Sig /T (Approver) /Rect [20 110 140 180] /P 3 0 R /F 4 >> endobj
|
||||
trailer << /Root 1 0 R >>
|
||||
%%EOF";
|
||||
|
||||
/// The real shell with `bytes` open, the side panes closed, after the first frames.
|
||||
fn shell(bytes: &'static [u8]) -> egui_kittest::Harness<'static, PdfCraftApp> {
|
||||
let mut h = egui_kittest::Harness::builder().with_size(vec2(1400.0, 900.0)).build_eframe(move |_cc| {
|
||||
let mut app = PdfCraftApp::new();
|
||||
app.set_option("language", "en").unwrap();
|
||||
app.open_bytes("sign-fields.pdf", None, bytes.to_vec()).unwrap();
|
||||
app.set_option("left", "closed").unwrap();
|
||||
app.set_option("panel", "none").unwrap();
|
||||
app
|
||||
});
|
||||
h.run_steps(6);
|
||||
h
|
||||
}
|
||||
|
||||
/// The accent chips painted in the last frame: the sign tabs.
|
||||
fn chips(h: &egui_kittest::Harness<'static, PdfCraftApp>) -> Vec<Rect> {
|
||||
let accent = Tokens::get(&h.ctx).accent;
|
||||
painted(h)
|
||||
.iter()
|
||||
.filter_map(|s| match s {
|
||||
egui::Shape::Rect(r) if r.fill == accent => Some(r.rect),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Clicks at `at` and lets the shell answer.
|
||||
fn click_at(h: &mut egui_kittest::Harness<'static, PdfCraftApp>, at: Pos2) {
|
||||
h.drag_at(at);
|
||||
h.run_steps(1);
|
||||
h.drop_at(at);
|
||||
h.run_steps(3);
|
||||
}
|
||||
|
||||
/// In the real shell, an empty signature field shows its accent tab with "Sign" in its
|
||||
/// top-left corner, and the signed and read-only fields show none. The tab is part of the
|
||||
/// field: hovering it shows the pointing hand, and clicking it starts signing that field.
|
||||
#[test]
|
||||
fn empty_signature_fields_show_a_sign_tab_that_signs_them() {
|
||||
let mut h = shell(SIGN_FIELDS);
|
||||
let (shapes, chips) = (painted(&h), chips(&h));
|
||||
let (approver, witness, locked) = (field_on_screen(&h, "Approver"), field_on_screen(&h, "Witness"), field_on_screen(&h, "Locked"));
|
||||
let tab = chips.iter().copied().find(|c| approver.contains_rect(*c)).unwrap_or_else(|| panic!("no tab in {approver:?}: {chips:?}"));
|
||||
assert!(tab.min.x - approver.min.x < 8.0 && tab.min.y - approver.min.y < 8.0, "in the top-left corner: {tab:?} in {approver:?}");
|
||||
let label = shapes.iter().any(|s| matches!(s, egui::Shape::Text(t) if t.galley.text() == "Sign" && tab.contains(t.pos)));
|
||||
assert!(label, "the tab says Sign");
|
||||
assert!(!chips.iter().any(|c| witness.intersects(*c)), "a signed field has no tab: {chips:?}");
|
||||
assert!(!chips.iter().any(|c| locked.intersects(*c)), "a read-only field has no tab: {chips:?}");
|
||||
|
||||
h.hover_at(tab.center());
|
||||
h.run_steps(1);
|
||||
assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::PointingHand);
|
||||
click_at(&mut h, tab.center());
|
||||
assert_eq!(h.state().dialog, Some(crate::Dialog::Sign));
|
||||
assert_eq!(h.state().sign_draft.as_ref().and_then(|d| d.field.clone()).as_deref(), Some("Approver"));
|
||||
}
|
||||
|
||||
/// A sign tab is drawn over every field, so a click on it signs its field even where a field
|
||||
/// earlier in the form's order overlaps it, which would otherwise take the click. Beside the
|
||||
/// tab, the overlapping field still takes clicks as before.
|
||||
#[test]
|
||||
fn a_sign_tab_signs_its_field_where_an_earlier_field_overlaps_it() {
|
||||
let mut h = shell(SIGN_UNDER_TEXT);
|
||||
let (name, approver) = (field_on_screen(&h, "Name"), field_on_screen(&h, "Approver"));
|
||||
let tab = chips(&h).into_iter().find(|c| approver.contains_rect(*c)).expect("Approver has a tab");
|
||||
assert!(name.contains_rect(tab), "the text field covers the tab: {tab:?} in {name:?}");
|
||||
|
||||
h.hover_at(tab.center());
|
||||
h.run_steps(1);
|
||||
assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::PointingHand);
|
||||
click_at(&mut h, tab.center());
|
||||
assert_eq!(h.state().dialog, Some(crate::Dialog::Sign));
|
||||
assert_eq!(h.state().sign_draft.as_ref().and_then(|d| d.field.clone()).as_deref(), Some("Approver"));
|
||||
assert!(h.state().views[0].forms.focus.is_none(), "the text field didn't open");
|
||||
|
||||
let beside = pos2(tab.right() + 6.0, tab.center().y);
|
||||
assert!(name.contains(beside) && approver.contains(beside), "beside the tab, both fields are under the pointer");
|
||||
h.state_mut().dialog = None;
|
||||
h.state_mut().sign_draft = None;
|
||||
h.run_steps(1);
|
||||
click_at(&mut h, beside);
|
||||
assert_eq!(h.state().views[0].forms.focus.as_ref().map(|f| f.name.as_str()), Some("Name"), "the earlier field takes the click");
|
||||
}
|
||||
@@ -20,6 +20,11 @@ impl DocView {
|
||||
pub fn page_xform(&self, page: usize) -> Option<PageXform> {
|
||||
self.screen_xforms.iter().find(|(p, _)| *p == page).map(|(_, xf)| *xf)
|
||||
}
|
||||
|
||||
/// Where the pages are on screen this frame, with their transforms.
|
||||
pub(crate) fn page_xforms(&self) -> Vec<(usize, PageXform)> {
|
||||
self.screen_xforms.iter().map(|(p, xf)| (*p, *xf)).collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// `r` moved so its corner lies on a whole physical pixel, so that a raster drawn from there
|
||||
@@ -128,6 +133,19 @@ impl PageXform {
|
||||
Rect::from_two_pos(self.norm_to_screen(a.0, a.1), self.norm_to_screen(b.0, b.1))
|
||||
}
|
||||
|
||||
/// Whether the screen point `p` activates link `l` on `page`: inside one of its
|
||||
/// `/QuadPoints` quadrilaterals, or its rectangle when it has none (ISO 32000-2 Table 176).
|
||||
pub fn link_contains(&self, info: &DocInfo, page: usize, l: &pdfcraft_render::Link, p: Pos2) -> bool {
|
||||
if l.quads.is_empty() {
|
||||
return self.user_rect(info, page, l.rect).contains(p);
|
||||
}
|
||||
// The inverse of `user_rect`: screen → the displayed page's fraction → user space.
|
||||
let Some(pg) = info.pages.get(page) else { return false };
|
||||
let (u, v) = self.screen_to_norm(p);
|
||||
let [x, y] = pg.view_to_user(u * pg.width, v * pg.height);
|
||||
l.contains(x, y)
|
||||
}
|
||||
|
||||
pub fn user_rect_f64(&self, info: &DocInfo, page: usize, r: [f64; 4]) -> Rect {
|
||||
self.user_rect(info, page, r.map(|v| v as f32))
|
||||
}
|
||||
|
||||
@@ -1885,6 +1885,15 @@ fn finish_redactions_and_fields(app: &mut PdfCraftApp, req: &mut Pending) {
|
||||
Some(Dialog::RedactApply) => {
|
||||
let marks = app.active_ids().and_then(|(_, id)| app.session.get(id)).map_or(0, |d| d.redaction_marks());
|
||||
if app.apply_edit(Edit::ApplyRedactions { pages: None }) {
|
||||
if let Some(view) = app.active.and_then(|i| app.views.get_mut(i)) {
|
||||
let delivered_undone = view.redactions_applied < view.redactions_downloaded;
|
||||
view.redactions_applied = view.redactions_applied.saturating_add(1);
|
||||
// A new step clears the redo history, so the undone saved steps can't come back.
|
||||
if view.redactions_undone_after_save > 0 || delivered_undone {
|
||||
view.redactions_undone_after_save = 0;
|
||||
view.saved_redactions_cut_off = true;
|
||||
}
|
||||
}
|
||||
if let Some((_, id)) = app.active_ids() {
|
||||
app.renew_recovery(id);
|
||||
}
|
||||
|
||||
@@ -119,7 +119,7 @@ impl PdfCraftApp {
|
||||
self.notify_fmt("New {tool} comments will look like this one", &[("tool", &kind)]);
|
||||
return;
|
||||
}
|
||||
let Some(tool) = crate::comments::tool_for_default(a, p.endings.as_deref()) else { return };
|
||||
let Some(tool) = crate::comments::tool_for_default(&doc.info.annotations, a, p.endings.as_deref()) else { return };
|
||||
let mut style = self.comment_prefs.style(tool);
|
||||
if let Some(c) = p.color {
|
||||
style.color = c;
|
||||
@@ -323,9 +323,10 @@ pub(crate) fn body(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens) -> (boo
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let has_default = app.comment_props.as_ref().is_some_and(|d| {
|
||||
let doc = app.active_ids().and_then(|(_, id)| app.session.get(id));
|
||||
doc.and_then(|doc| doc.info.annotations.iter().find(|a| a.page == d.page && a.index == d.index && !a.is_reply()))
|
||||
.is_some_and(|a| crate::comments::tool_for_default(a, d.edited.endings.as_deref()).is_some() || crate::comments::typed_text(a))
|
||||
let Some(doc) = app.active_ids().and_then(|(_, id)| app.session.get(id)) else { return false };
|
||||
doc.info.annotations.iter().find(|a| a.page == d.page && a.index == d.index && !a.is_reply()).is_some_and(|a| {
|
||||
crate::comments::tool_for_default(&doc.info.annotations, a, d.edited.endings.as_deref()).is_some() || crate::comments::typed_text(a)
|
||||
})
|
||||
});
|
||||
let Some(d) = app.comment_props.as_mut() else { return (false, true) };
|
||||
let kind = tl!(crate::comments_panel::subtype_label(&d.edited.subtype)).to_string();
|
||||
|
||||
@@ -20,7 +20,7 @@ pub use save::{SaveTarget, write_atomically};
|
||||
#[cfg(test)]
|
||||
pub(crate) use save::{is_mail_temp_copy, save_dialog_folder};
|
||||
#[cfg(test)]
|
||||
use save::{write_atomically_syncing, write_atomically_with};
|
||||
use save::{unredacted_file_name, write_atomically_syncing, write_atomically_with};
|
||||
|
||||
/// Text typed into a new text box that isn't added to the page yet.
|
||||
fn new_text_typed(v: &crate::DocView) -> bool {
|
||||
@@ -168,6 +168,15 @@ impl PdfCraftApp {
|
||||
}
|
||||
_ => Vec::new(),
|
||||
};
|
||||
// The comments the pop-ups hold unsaved text or a drag for, to see afterwards whether
|
||||
// their places still name them (pages may move, come or go).
|
||||
let popups_before: Vec<pdfcraft_render::Annotation> = match (self.views.get(i), self.session.get(id)) {
|
||||
(Some(v), Some(d)) => {
|
||||
let keys = v.comments.popup_keys();
|
||||
d.info.annotations.iter().filter(|a| keys.contains(&(a.page, a.index))).cloned().collect()
|
||||
}
|
||||
_ => Vec::new(),
|
||||
};
|
||||
match self.session.apply(id, edit.clone()) {
|
||||
Ok(()) => {
|
||||
let Some(doc) = self.session.get(id) else { return true };
|
||||
@@ -210,8 +219,7 @@ impl PdfCraftApp {
|
||||
view.forms.unbaked.extend(unbaked);
|
||||
}
|
||||
} else if let Some(page) = one_page {
|
||||
// Comment and content edits change one page: keep every other raster.
|
||||
view.page_changed(page);
|
||||
one_page_changed(view, &edit, page);
|
||||
} else if let Some((changed_pages, unbaked)) = form_edit {
|
||||
view.forms.unbaked.extend(unbaked);
|
||||
for page in changed_pages {
|
||||
@@ -223,6 +231,10 @@ impl PdfCraftApp {
|
||||
if matches!(edit, Edit::AddAnnotation(_)) {
|
||||
view.comments.comment_added();
|
||||
}
|
||||
// A deletion moves the pop-ups' state with its comments (`annotation_deleted`).
|
||||
if !matches!(edit, Edit::DeleteAnnotation { .. }) {
|
||||
view.comments.popups_after_edit(&popups_before, &info.annotations);
|
||||
}
|
||||
// Keep the pages the user acted on selected, where they now are.
|
||||
select_after_edit(view, &edit, info, &annots_before, self.quick_tool);
|
||||
if let (Some((target, ambiguous_before)), Edit::EditPageImage { page, .. }) = (target_arrange_image, &edit) {
|
||||
@@ -380,6 +392,17 @@ impl PdfCraftApp {
|
||||
view.comments.selected = None;
|
||||
view.comments.history_stepped();
|
||||
}
|
||||
if label == (Edit::ApplyRedactions { pages: None }).label() {
|
||||
let view = &mut self.views[i];
|
||||
let (applied, undone) = (view.redactions_applied, view.redactions_undone_after_save);
|
||||
// Undo past the last save counts as undone; Redo first takes those back.
|
||||
match (undo, applied, undone) {
|
||||
(true, 0, _) => view.redactions_undone_after_save = undone.saturating_add(1),
|
||||
(true, _, _) => view.redactions_applied = applied.saturating_sub(1),
|
||||
(false, _, 0) => view.redactions_applied = applied.saturating_add(1),
|
||||
(false, _, _) => view.redactions_undone_after_save = undone.saturating_sub(1),
|
||||
}
|
||||
}
|
||||
let label = crate::i18n::edit_label(&label);
|
||||
if undo {
|
||||
self.notify_fmt("Undid {label}", &[("label", &label)]);
|
||||
@@ -785,7 +808,7 @@ impl PdfCraftApp {
|
||||
.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.comments.selected = newest.map(|index| (page, index));
|
||||
view.comments.select(newest.map(|index| (page, index)));
|
||||
view.comments.reveal = true;
|
||||
self.quick_tool = crate::QuickTool::Select;
|
||||
}
|
||||
@@ -1008,6 +1031,15 @@ fn content_page(edit: &Edit) -> Option<usize> {
|
||||
}
|
||||
}
|
||||
|
||||
/// A comment or content edit changes one page, `page`: keep every other raster. Opening, closing
|
||||
/// or moving a pop-up changes none: the window is drawn over the page, and a /Popup annotation
|
||||
/// paints nothing in the raster (ISO 32000-2 §12.5.6.14).
|
||||
fn one_page_changed(view: &mut crate::DocView, edit: &Edit, page: usize) {
|
||||
if !matches!(edit, Edit::SetAnnotationPopup { .. }) {
|
||||
view.page_changed(page);
|
||||
}
|
||||
}
|
||||
|
||||
fn comment_page(edit: &Edit) -> Option<usize> {
|
||||
match edit {
|
||||
Edit::AddAnnotation(a) => Some(a.page),
|
||||
@@ -1017,6 +1049,7 @@ fn comment_page(edit: &Edit) -> Option<usize> {
|
||||
| Edit::SetAnnotationStatus { page, .. }
|
||||
| Edit::MoveAnnotation { page, .. }
|
||||
| Edit::ReshapeAnnotation { page, .. }
|
||||
| Edit::SetAnnotationPopup { page, .. }
|
||||
| Edit::ResizeAnnotation { page, .. }
|
||||
| Edit::StyleAnnotation { page, .. }
|
||||
| Edit::FillAnnotation { page, .. }
|
||||
@@ -1201,9 +1234,11 @@ mod revert_draft_tests {
|
||||
use crate::forms_ui::Focus;
|
||||
use pdfcraft_engine::FieldValue;
|
||||
|
||||
/// An open editor on the first widget of the field "name", holding `text` as typed.
|
||||
fn focus(text: &str) -> Focus {
|
||||
Focus {
|
||||
name: "name".into(),
|
||||
obj: None,
|
||||
widget: 0,
|
||||
text: text.into(),
|
||||
picked: Vec::new(),
|
||||
@@ -1213,6 +1248,7 @@ mod revert_draft_tests {
|
||||
calendar: None,
|
||||
calendar_rect: None,
|
||||
calendar_text: None,
|
||||
list: Default::default(),
|
||||
had_focus: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -94,6 +94,11 @@ impl PdfCraftApp {
|
||||
view.forms.committed = None;
|
||||
view.forms.unbaked.clear();
|
||||
view.pending_edit = None;
|
||||
// The redactions applied since the last save are discarded too. Those in the
|
||||
// last web download stay, so later downloads keep the `_Redacted` name.
|
||||
view.redactions_applied = view.redactions_downloaded;
|
||||
view.redactions_undone_after_save = 0;
|
||||
view.saved_redactions_cut_off = false;
|
||||
}
|
||||
self.notify_tr("Reverted to the last saved version");
|
||||
}
|
||||
|
||||
@@ -50,6 +50,21 @@ impl PdfCraftApp {
|
||||
let Some(id) = self.views.get(index).map(|v| v.id) else { return false };
|
||||
let Some(doc) = self.session.get(id) else { return false };
|
||||
let (name, path) = (doc.name.clone(), doc.path.clone());
|
||||
// After Apply redactions, Save asks where and proposes the name with `_Redacted`.
|
||||
// In the web build a delivered step stays counted, so only the steps applied since the
|
||||
// last delivery make Save ask where.
|
||||
let redacted = self.views.get(index).is_some_and(|v| v.redactions_applied > 0);
|
||||
let not_delivered = self.views.get(index).is_some_and(|v| v.redactions_applied > v.redactions_downloaded);
|
||||
let name = if redacted { pdfcraft_engine::redacted_file_name(&name) } else { name };
|
||||
// Undo past a saved Apply redactions brings back content that the file on disk has
|
||||
// redacted: ask where instead of writing it over that file. In the web build a delivered
|
||||
// step stays counted in `redactions_applied`, so fewer steps than were delivered means one
|
||||
// was undone.
|
||||
let unredacted = self.views.get(index).is_some_and(restores_saved_redactions);
|
||||
// The restored content is not a redacted copy: propose the name without `_Redacted`, so
|
||||
// the dialog's default is not the redacted file.
|
||||
let name = if unredacted && !redacted { unredacted_file_name(&name) } else { name };
|
||||
let target = if not_delivered || unredacted { SaveTarget::As } else { target };
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
let doc_path = path.clone();
|
||||
@@ -66,6 +81,14 @@ impl PdfCraftApp {
|
||||
let dialog = in_document_folder(dialog, doc_path.as_deref());
|
||||
// The bytes are taken once the user has chosen, so edits made meanwhile are saved too.
|
||||
self.ask_one(crate::pickers::Ask::Save(dialog), None, move |app, dest| {
|
||||
// An Apply redactions or an Undo of one while the dialog was open makes the
|
||||
// name it proposed wrong: ask again with the name for the current content.
|
||||
let asked = (redacted, unredacted);
|
||||
let changed = |v: &crate::DocView| v.id == id && (v.redactions_applied > 0, restores_saved_redactions(v)) != asked;
|
||||
if let Some(index) = app.views.iter().position(changed) {
|
||||
app.save_then(index, SaveTarget::As, after);
|
||||
return;
|
||||
}
|
||||
app.save_doc_to_then(id, &dest.to_string_lossy(), target, Box::new(after));
|
||||
});
|
||||
return false;
|
||||
@@ -100,6 +123,9 @@ impl PdfCraftApp {
|
||||
&& let Some(view) = self.views.get_mut(index)
|
||||
{
|
||||
view.document_changed(&doc.info);
|
||||
// `redactions_applied` stays set: the document keeps its name here, so
|
||||
// later downloads are named after the redacted copy too.
|
||||
view.redactions_downloaded = view.redactions_applied;
|
||||
}
|
||||
// The host reports where the file went (and any failure) itself.
|
||||
if !to_host {
|
||||
@@ -206,6 +232,9 @@ impl PdfCraftApp {
|
||||
// Saving over a version that changed on disk keeps this one: nothing to ask.
|
||||
for view in self.views.iter_mut().filter(|v| v.id == id) {
|
||||
view.disk_changed = false;
|
||||
view.redactions_applied = 0;
|
||||
view.redactions_undone_after_save = 0;
|
||||
view.saved_redactions_cut_off = false;
|
||||
}
|
||||
self.notify_fmt("Saved {name}", &[("name", &short_name(dest))]);
|
||||
#[cfg(target_os = "macos")]
|
||||
@@ -244,6 +273,27 @@ pub(crate) fn is_mail_temp_copy(path: &str) -> bool {
|
||||
|| p.contains("/library/containers/com.apple.mail/data/library/mail downloads/")
|
||||
}
|
||||
|
||||
/// Whether `view` holds content that a saved or delivered Apply redactions removed: a saved step
|
||||
/// is undone, cannot be redone, or (in the web build) fewer steps are in effect than were
|
||||
/// delivered.
|
||||
fn restores_saved_redactions(view: &crate::DocView) -> bool {
|
||||
view.redactions_undone_after_save > 0 || view.saved_redactions_cut_off || view.redactions_applied < view.redactions_downloaded
|
||||
}
|
||||
|
||||
/// `name` without the `_Redacted` that [`pdfcraft_engine::redacted_file_name`] adds before the
|
||||
/// extension ("contract_Redacted.pdf" gives "contract.pdf"). Any other name is returned as it is.
|
||||
pub(crate) fn unredacted_file_name(name: &str) -> String {
|
||||
let cut = name.len().saturating_sub(4);
|
||||
let (stem, ext) = match (name.get(..cut), name.get(cut..)) {
|
||||
(Some(stem), Some(ext)) if ext.eq_ignore_ascii_case(".pdf") => (stem, ext),
|
||||
_ => (name, ""),
|
||||
};
|
||||
match stem.strip_suffix("_Redacted") {
|
||||
Some(base) if !base.is_empty() => format!("{base}{ext}"),
|
||||
_ => name.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The folder a Save As style dialog should open in for a document stored at `path`: the
|
||||
/// document's own folder, as Acrobat and Foxit do, instead of whichever folder the system picks.
|
||||
/// `None` (keep the system's choice) for a new document, a path with no parent, or an email
|
||||
|
||||
@@ -1,4 +1,15 @@
|
||||
use super::{SaveTarget, is_mail_temp_copy, save_dialog_folder, write_atomically, write_atomically_syncing, write_atomically_with};
|
||||
use super::{
|
||||
SaveTarget, is_mail_temp_copy, save_dialog_folder, unredacted_file_name, write_atomically, write_atomically_syncing, write_atomically_with,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn restored_content_is_not_proposed_under_the_redacted_name() {
|
||||
assert_eq!(unredacted_file_name("contract_Redacted.pdf"), "contract.pdf");
|
||||
assert_eq!(unredacted_file_name("SCAN_Redacted.PDF"), "SCAN.PDF");
|
||||
assert_eq!(unredacted_file_name("Untitled_Redacted"), "Untitled");
|
||||
assert_eq!(unredacted_file_name("contract.pdf"), "contract.pdf");
|
||||
assert_eq!(unredacted_file_name("_Redacted.pdf"), "_Redacted.pdf");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_dialogs_open_in_the_documents_folder() {
|
||||
|
||||
@@ -40,6 +40,8 @@ pub fn subtype_label(s: &str) -> &str {
|
||||
/// The comment type as the panel names it, telling callouts, clouds and replaced text apart by `/IT`.
|
||||
pub fn kind_label(a: &Annotation) -> &str {
|
||||
match a.intent.as_deref() {
|
||||
// Replace Text: the caret (`/IT /Replace`) is the group's primary; earlier builds made
|
||||
// the strikeout primary.
|
||||
Some("StrikeOutTextEdit" | "Replace") => "Replace text",
|
||||
Some("FreeTextCallout") => "Callout",
|
||||
Some("PolygonCloud") => "Cloud",
|
||||
@@ -89,10 +91,10 @@ pub fn count(info: &DocInfo) -> usize {
|
||||
info.annotations.iter().filter(|a| a.is_comment()).count()
|
||||
}
|
||||
|
||||
/// The replies under the header's count, at any depth: not status changes, checkmarks or a
|
||||
/// Replace Text caret (grouped with its strikeout, not a reply to it).
|
||||
/// The replies under the header's count, at any depth: not status changes, checkmarks or group
|
||||
/// subordinates (`/RT /Group`, such as Replace Text's strikeout: part of the comment, not a reply).
|
||||
pub fn reply_count(info: &DocInfo) -> usize {
|
||||
info.annotations.iter().filter(|a| a.is_reply() && a.state.is_none() && !a.grouped).count()
|
||||
info.annotations.iter().filter(|a| a.is_reply() && a.state.is_none() && !a.is_group_member()).count()
|
||||
}
|
||||
|
||||
fn matches(a: &Annotation, q: &str) -> bool {
|
||||
@@ -176,10 +178,14 @@ pub(crate) fn show(
|
||||
// annotation its `/IRT` chain refers to past earlier state replies (ISO 32000-2 §12.5.6.3),
|
||||
// so one set on a reply, at any depth, is that reply's and not the comment's, and the card's
|
||||
// badges and checkmark leave it out (comment_list reports it on the reply). Page badges count
|
||||
// roots before filtering.
|
||||
// roots before filtering. A group (`/RT /Group`, ISO 32000-2 §12.5.6.2) is one comment, its
|
||||
// primary's: a subordinate is no reply, and a reply to one (a status too) is the group's.
|
||||
let tops = pdfcraft_render::thread_tops(&info.annotations);
|
||||
let states = ReviewStates::new(&info.annotations);
|
||||
for a in &info.annotations {
|
||||
if a.is_group_member() {
|
||||
continue;
|
||||
}
|
||||
if let Some(parent) = a.parent {
|
||||
if a.state.is_none() {
|
||||
replies.entry(tops.get(&(a.page, a.index)).copied().unwrap_or(parent)).or_default().push(a);
|
||||
|
||||
@@ -49,7 +49,9 @@ pub fn right_panel(app: &mut PdfCraftApp, ui: &mut egui::Ui) {
|
||||
RightPanel::Bookmarks => ("Bookmarks", None),
|
||||
RightPanel::Pages => ("Pages", Some(info.pages.len())),
|
||||
RightPanel::Fields => ("Fields", Some(info.fields.len())),
|
||||
RightPanel::Layers => ("Layers", Some(info.layers.len())),
|
||||
RightPanel::Layers => {
|
||||
("Layers", Some(info.layer_order.iter().filter(|r| matches!(r.item, pdfcraft_render::LayerItem::Layer(_))).count()))
|
||||
}
|
||||
RightPanel::Attachments => ("Attachments", Some(info.attachments.len())),
|
||||
RightPanel::Signatures => ("Signatures", Some(doc.signatures.iter().filter(|s| s.signed).count())),
|
||||
RightPanel::Accessibility => ("Accessibility Checker", None),
|
||||
@@ -234,8 +236,31 @@ pub fn right_panel(app: &mut PdfCraftApp, ui: &mut egui::Ui) {
|
||||
RightPanel::Layers => {
|
||||
if info.layers.is_empty() {
|
||||
empty(ui, &t, "layers", "This document has no layers.");
|
||||
} else if info.layer_order.is_empty() {
|
||||
// ISO 32000-2 Table 99: only the groups /Order lists are presented.
|
||||
empty(ui, &t, "layers", "This document lists no layers to show.");
|
||||
}
|
||||
for (li, l) in info.layers.iter().enumerate() {
|
||||
// The default configuration's /Order, as a tree: a level is indented
|
||||
// 16 points, up to eight levels; a label is a heading, not a layer.
|
||||
for row in &info.layer_order {
|
||||
let indent = 16.0 * row.depth.min(8) as f32;
|
||||
let li = match &row.item {
|
||||
pdfcraft_render::LayerItem::Layer(li) => *li,
|
||||
pdfcraft_render::LayerItem::Label(label) => {
|
||||
let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 28.0), Sense::hover());
|
||||
resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, label));
|
||||
crate::widgets::paint_left(
|
||||
ui,
|
||||
rect.left_center() + vec2(8.0 + indent, 0.0),
|
||||
label,
|
||||
theme::medium(12.0),
|
||||
t.text_faint,
|
||||
(rect.width() - 12.0 - indent).max(0.0),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let Some(l) = info.layers.get(li) else { continue };
|
||||
let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 32.0), Sense::click());
|
||||
resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::CheckBox, true, l.visible, &l.name));
|
||||
let press = theme::Press::track(ui, &resp);
|
||||
@@ -243,7 +268,7 @@ pub fn right_panel(app: &mut PdfCraftApp, ui: &mut egui::Ui) {
|
||||
let body = rect.translate(press.offset());
|
||||
icons::paint(
|
||||
ui,
|
||||
Rect::from_min_size(body.min + vec2(4.0, 7.0), vec2(18.0, 18.0)),
|
||||
Rect::from_min_size(body.min + vec2(4.0 + indent, 7.0), vec2(18.0, 18.0)),
|
||||
if l.visible { "eye" } else { "eye-off" },
|
||||
16.0,
|
||||
t.icon,
|
||||
@@ -251,11 +276,11 @@ pub fn right_panel(app: &mut PdfCraftApp, ui: &mut egui::Ui) {
|
||||
let fg = if l.visible { t.text } else { t.text_faint };
|
||||
crate::widgets::paint_left(
|
||||
ui,
|
||||
body.left_center() + vec2(32.0, 0.0),
|
||||
body.left_center() + vec2(32.0 + indent, 0.0),
|
||||
&l.name,
|
||||
theme::regular(13.0),
|
||||
fg,
|
||||
(rect.width() - 40.0).max(0.0),
|
||||
(rect.width() - 40.0 - indent).max(0.0),
|
||||
);
|
||||
if theme::hand(resp).on_hover_text(if l.visible { tl!("Hide layer") } else { tl!("Show layer") }).clicked() {
|
||||
toggle_layer = Some((li, !l.visible));
|
||||
|
||||
@@ -26,6 +26,7 @@ mod geometry;
|
||||
mod input;
|
||||
mod menu;
|
||||
mod paint;
|
||||
mod popups;
|
||||
mod state;
|
||||
|
||||
pub(crate) use composer::{composer, submit_key};
|
||||
@@ -45,6 +46,7 @@ use menu::{RECENT_CUSTOM, same_colour};
|
||||
pub(crate) use paint::paint_page;
|
||||
#[cfg(test)]
|
||||
use paint::{changing_points, drawn_shape, edited_in_view};
|
||||
pub(crate) use popups::popups;
|
||||
#[cfg(test)]
|
||||
use state::after_delete;
|
||||
use state::login_name;
|
||||
@@ -443,14 +445,23 @@ pub(crate) fn made_by(a: &Annotation, tool: CommentTool) -> bool {
|
||||
/// The tool whose defaults "Make Current Properties Default" should update.
|
||||
///
|
||||
/// Arrows are stored as Line annotations. An arrow ending belongs to the Arrow tool, so its
|
||||
/// defaults stay separate from a plain line.
|
||||
pub(crate) fn tool_for_default(a: &Annotation, endings: Option<&[LineEnding]>) -> Option<CommentTool> {
|
||||
/// defaults stay separate from a plain line. A Replace Text group is selected by its caret (the
|
||||
/// group's primary, ISO 32000-2 §12.5.6.2), so a caret whose group holds a Replace Text strikeout
|
||||
/// (`/IT /StrikeOutTextEdit`) belongs to the Replace Text tool; `all` is the document's listing.
|
||||
pub(crate) fn tool_for_default(all: &[Annotation], a: &Annotation, endings: Option<&[LineEnding]>) -> Option<CommentTool> {
|
||||
match tool_for(a) {
|
||||
Some(CommentTool::Line) if endings.is_some_and(|ends| ends.iter().copied().any(arrow_ending)) => Some(CommentTool::Arrow),
|
||||
Some(CommentTool::Caret) if replaces_text(all, a) => Some(CommentTool::ReplaceText),
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the caret `a` is the primary of a Replace Text group: a grouped strikeout with
|
||||
/// `/IT /StrikeOutTextEdit` is one of its subordinates.
|
||||
fn replaces_text(all: &[Annotation], a: &Annotation) -> bool {
|
||||
all.iter().any(|s| s.is_group_member() && s.subtype == "StrikeOut" && s.intent.as_deref() == Some("StrikeOutTextEdit") && s.replies_to(a))
|
||||
}
|
||||
|
||||
fn arrow_ending(ending: LineEnding) -> bool {
|
||||
matches!(ending, LineEnding::OpenArrow | LineEnding::ClosedArrow | LineEnding::ROpenArrow | LineEnding::RClosedArrow)
|
||||
}
|
||||
|
||||
@@ -137,14 +137,7 @@ pub(crate) fn composer(ctx: &egui::Context, view: &mut DocView, info: &DocInfo,
|
||||
// A callout's leader and box stay in user-space axes (its appearance isn't turned).
|
||||
let font_size = prefs.font_size(CommentTool::Callout).unwrap_or(10.0);
|
||||
let rect = text_box_rect(c.at, &text, font_size, 0);
|
||||
let side = if point[0] < rect[0] {
|
||||
rect[0]
|
||||
} else if point[0] > rect[2] {
|
||||
rect[2]
|
||||
} else {
|
||||
(rect[0] + rect[2]) / 2.0
|
||||
};
|
||||
let knee = [(point[0] + side) / 2.0, (rect[1] + rect[3]) / 2.0];
|
||||
let knee = pdfcraft_engine::callout_knee(rect, point);
|
||||
Some(new_comment(&cx, CommentTool::Callout, Shape::Callout { rect, knee, point, font_size, ending: LineEnding::OpenArrow }, text))
|
||||
}
|
||||
ComposerKind::Replace => {
|
||||
|
||||
@@ -12,21 +12,72 @@ pub(super) fn on_text(a: &Annotation) -> bool {
|
||||
is_markup(&a.subtype) || a.subtype == "Caret" && a.intent.as_deref() == Some("Replace")
|
||||
}
|
||||
|
||||
/// Rectangles, ovals, text boxes, stamps and drawings (drawn signatures among them). A callout's
|
||||
/// `/Rect` also holds its leader line, so it only moves.
|
||||
/// Rectangles, ovals, text boxes, stamps and drawings (drawn signatures among them). A callout
|
||||
/// resizes its text box ([`frame`]); one whose box can't be read (no `/RD`) only moves, since its
|
||||
/// `/Rect` also holds its leader line.
|
||||
pub(super) fn resizable(a: &Annotation) -> bool {
|
||||
matches!(a.subtype.as_str(), "Square" | "Circle" | "FreeText" | "Stamp" | "Ink") && a.intent.as_deref() != Some("FreeTextCallout")
|
||||
matches!(a.subtype.as_str(), "Square" | "Circle" | "FreeText" | "Stamp" | "Ink")
|
||||
&& (a.intent.as_deref() != Some("FreeTextCallout") || a.text_box.is_some())
|
||||
}
|
||||
|
||||
/// Lines, connected lines, polygons and clouds: their ends and corners have handles of their own
|
||||
/// (measurements keep the points they measured, and a locked comment its shape).
|
||||
/// Lines, connected lines, polygons, clouds and callouts: their ends, corners, or a callout's
|
||||
/// arrow point and knee have handles of their own (measurements keep the points they measured,
|
||||
/// and a locked comment its shape).
|
||||
pub(super) fn reshapable(a: &Annotation) -> bool {
|
||||
matches!(a.subtype.as_str(), "Line" | "PolyLine" | "Polygon")
|
||||
(matches!(a.subtype.as_str(), "Line" | "PolyLine" | "Polygon") || is_callout(a))
|
||||
&& !a.points.is_empty()
|
||||
&& !a.locked
|
||||
&& !a.intent.as_deref().is_some_and(|i| i.ends_with("Dimension"))
|
||||
}
|
||||
|
||||
/// A callout whose text box and leader line PdfCraft can read.
|
||||
pub(super) fn is_callout(a: &Annotation) -> bool {
|
||||
a.subtype == "FreeText" && a.text_box.is_some()
|
||||
}
|
||||
|
||||
/// The rectangle a comment's selection frame and resize handles go around, in user space: a
|
||||
/// callout's text box, otherwise where the comment is drawn (`/Rect`, or a sticky note kept
|
||||
/// upright on a page turned `rotation` degrees).
|
||||
pub(super) fn frame(a: &Annotation, rotation: u16) -> [f32; 4] {
|
||||
a.text_box.unwrap_or_else(|| a.shown_rect(rotation))
|
||||
}
|
||||
|
||||
/// A callout's points while one is dragged to `to`. Its knee moves along its knee line only
|
||||
/// (Acrobat: "The knee line can be resized in one direction only; horizontal knee lines can be
|
||||
/// resized horizontally only; vertical knee lines can be resized vertically only", Acrobat DC Help,
|
||||
/// 11/28/2019, p. 357), and no nearer the box than [`pdfcraft_engine::CALLOUT_KNEE_LINE`]
|
||||
/// (Acrobat Pro DC, a 2021 Continuous release, lays a knee dragged into the box out again at that
|
||||
/// distance). Its arrow point moves freely, with Shift held to 45° from the knee.
|
||||
pub(super) fn callout_reshaped(points: &[[f64; 2]], text_box: [f32; 4], i: usize, to: [f64; 2], shift: bool) -> Vec<[f64; 2]> {
|
||||
let tb = text_box.map(f64::from);
|
||||
let gap = pdfcraft_engine::CALLOUT_KNEE_LINE;
|
||||
match (i, points.get(1)) {
|
||||
(1, Some(knee)) => {
|
||||
let to = match pdfcraft_engine::callout_side(tb, *knee) {
|
||||
pdfcraft_engine::CalloutSide::Left => [to[0].min(tb[0] - gap), knee[1]],
|
||||
pdfcraft_engine::CalloutSide::Right => [to[0].max(tb[2] + gap), knee[1]],
|
||||
pdfcraft_engine::CalloutSide::Top => [knee[0], to[1].max(tb[3] + gap)],
|
||||
pdfcraft_engine::CalloutSide::Bottom => [knee[0], to[1].min(tb[1] - gap)],
|
||||
};
|
||||
let mut out = points.to_vec();
|
||||
if let Some(k) = out.get_mut(1) {
|
||||
*k = to;
|
||||
}
|
||||
out
|
||||
}
|
||||
_ => reshaped(points, i, to, shift),
|
||||
}
|
||||
}
|
||||
|
||||
/// A selected comment's points moved as handle `i` is dragged to `to` ([`reshaped`], or
|
||||
/// [`callout_reshaped`] for a callout).
|
||||
pub(super) fn reshape_for(a: &Annotation, points: &[[f64; 2]], i: usize, to: [f64; 2], shift: bool) -> Vec<[f64; 2]> {
|
||||
match a.text_box.filter(|_| is_callout(a)) {
|
||||
Some(tb) => callout_reshaped(points, tb, i, to, shift),
|
||||
None => reshaped(points, i, to, shift),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `tool` reaches a line's end and corner handles: the Select and Fill & Sign tools.
|
||||
/// The drawing tools draw from where they are pressed, so a new line starts at the end of the
|
||||
/// one just drawn rather than dragging it.
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user