mirror of
https://github.com/storytold/pdfcraft.git
synced 2026-11-10 13:01:29 +00:00
Merge pull request #6711 from storytold/merge/render-patches2
Land renderer patches, layer auto state, auto-tag artifacts, export clips and print page lookup (#3969, #4393, #4396, #4410, #4433, #4459, #4159, #5075, #5973)
This commit is contained in:
52 files changed
+3909
-212
No files matched your search
@@ -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));
|
||||
|
||||
@@ -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!({
|
||||
|
||||
@@ -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",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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"])),
|
||||
|
||||
@@ -9946,6 +9946,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 {
|
||||
|
||||
@@ -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(),
|
||||
|
||||
@@ -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).
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
@@ -36,14 +36,16 @@ 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,
|
||||
OutlineItem, PageInfo, PageTransition, RemoteDestination, ReviewStates, TransitionStyle, Xfa, 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 {
|
||||
@@ -74,6 +76,10 @@ pub struct DocInfo {
|
||||
/// 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.
|
||||
|
||||
@@ -267,6 +267,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)) {
|
||||
|
||||
@@ -652,6 +652,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,
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -769,6 +769,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
|
||||
|
||||
@@ -18,9 +18,9 @@ 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,
|
||||
OutlineItem, PageInfo, PageTransition, RemoteDestination, ReviewStates, TransitionStyle, Xfa, attachment_data, check_pages, inspect,
|
||||
link_replies, pretty_date, thread_tops,
|
||||
};
|
||||
pub use pixels::Pixels;
|
||||
pub use raster::{
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
@@ -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;
|
||||
@@ -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");
|
||||
}
|
||||
@@ -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));
|
||||
|
||||
@@ -9,9 +9,14 @@ use pdfcraft_ui_egui::PdfCraftApp;
|
||||
/// One page with layers Red (on) and Green (off), a radio-button group, each drawing a band;
|
||||
/// a "show-red" push button turns Red on and a link toggles Green.
|
||||
fn fixture() -> Vec<u8> {
|
||||
fixture_with("")
|
||||
}
|
||||
|
||||
/// [`fixture`] with `order` added to the default configuration.
|
||||
fn fixture_with(order: &str) -> Vec<u8> {
|
||||
let content = "/OC /R BDC 1 0 0 rg 20 300 260 40 re f EMC /OC /G BDC 0 1 0 rg 20 240 260 40 re f EMC";
|
||||
let objs = [
|
||||
"<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [7 0 R] >> /OCProperties << /OCGs [5 0 R 6 0 R] /D << /OFF [6 0 R] /RBGroups [[5 0 R 6 0 R]] >> >> >>".to_string(),
|
||||
format!("<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [7 0 R] >> /OCProperties << /OCGs [5 0 R 6 0 R] /D << /OFF [6 0 R] /RBGroups [[5 0 R 6 0 R]] {order} >> >> >>"),
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".into(),
|
||||
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 400] /Contents 4 0 R /Resources << /Properties << /R 5 0 R /G 6 0 R >> >> /Annots [7 0 R 8 0 R] >>".into(),
|
||||
format!("<< /Length {} >>\nstream\n{content}\nendstream", content.len()),
|
||||
@@ -36,10 +41,14 @@ fn fixture() -> Vec<u8> {
|
||||
}
|
||||
|
||||
fn harness(setup: impl FnOnce(&mut PdfCraftApp) + 'static) -> Harness<'static, PdfCraftApp> {
|
||||
harness_with(fixture(), setup)
|
||||
}
|
||||
|
||||
fn harness_with(pdf: Vec<u8>, setup: impl FnOnce(&mut PdfCraftApp) + 'static) -> Harness<'static, PdfCraftApp> {
|
||||
let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(move |_cc| {
|
||||
let mut app = PdfCraftApp::new();
|
||||
app.set_option("language", "en").unwrap();
|
||||
app.open_bytes("layers.pdf", None, fixture()).unwrap();
|
||||
app.open_bytes("layers.pdf", None, pdf).unwrap();
|
||||
app.set_option("zoom", "150").unwrap();
|
||||
setup(&mut app);
|
||||
app
|
||||
@@ -124,3 +133,28 @@ fn layer_options_reset_to_initial_visibility() {
|
||||
assert!(!doc.dirty, "showing and hiding layers doesn't change the document");
|
||||
assert_eq!(doc.can_undo(), None, "nor is it an edit to undo");
|
||||
}
|
||||
|
||||
/// ISO 32000-2 Table 99 `/Order`: the Layers panel shows the tree it gives, a leading text
|
||||
/// string as a label, and not the groups it leaves out, which still draw in their state. Without
|
||||
/// `/Order` it presents none.
|
||||
#[test]
|
||||
fn the_layers_panel_shows_the_order_tree() {
|
||||
let mut h = harness_with(fixture_with("/Order [[(Colours) 5 0 R]]"), |app| app.set_option("panel", "layers").unwrap());
|
||||
h.run_steps(2);
|
||||
let label = h.get_by_label("Colours").rect();
|
||||
let red = h.get_by_label("Red").rect();
|
||||
assert!(red.min.y > label.max.y - 1.0, "Red is listed under its label");
|
||||
assert!(h.query_by_label("Green").is_none(), "Green isn't in /Order, so it isn't presented");
|
||||
assert_eq!(shown(&h), layers(true, false), "but it is still a layer, in its state");
|
||||
// Clicking the label changes nothing; clicking Red hides it.
|
||||
h.get_by_label("Colours").click();
|
||||
h.run_steps(2);
|
||||
assert_eq!(shown(&h), layers(true, false));
|
||||
h.get_by_label("Red").click();
|
||||
h.run_steps(3);
|
||||
assert_eq!(shown(&h), layers(false, false));
|
||||
|
||||
let h = harness(|app| app.set_option("panel", "layers").unwrap());
|
||||
assert!(h.query_by_label("Red").is_none() && h.query_by_label("Green").is_none(), "no /Order: none presented");
|
||||
h.get_by_label("This document lists no layers to show.");
|
||||
}
|
||||
@@ -1346,8 +1346,8 @@ milestone = "M3"
|
||||
status = "shipped"
|
||||
commands = []
|
||||
tools = ["doc_info", "layer_set"]
|
||||
evidence = ["crates/render/src/raster/tests.rs::layer_override_hides_content", "crates/engine/src/tests.rs::layer_choices_survive_edits", "crates/automation/tests/it/automation.rs::layers_and_hidden_comments_change_what_page_render_draws"]
|
||||
notes = "layer_set shows or hides a layer by name (every group with that name, as CAD exporters repeat names) or by position, and page_render draws with the document's layer visibility. Still missing: Reset to initial visibility (view.layers-reset), layer properties, and /OC on annotations (#2176)."
|
||||
evidence = ["crates/render/src/raster/tests.rs::layer_override_hides_content", "crates/engine/src/tests.rs::layer_choices_survive_edits", "crates/automation/tests/it/automation.rs::layers_and_hidden_comments_change_what_page_render_draws", "crates/render/src/raster/tests.rs::the_view_auto_state_sets_a_groups_state_on_screen", "crates/render/src/raster/tests.rs::layer_toggles_and_print_renders_are_not_the_view_auto_state", "crates/render/src/raster/tests.rs::malformed_view_auto_state_is_ignored", "crates/render/src/inspect/tests.rs::the_layers_panel_presents_the_order_tree", "crates/ui-egui/tests/it/layer_actions.rs::the_layers_panel_shows_the_order_tree"]
|
||||
notes = "layer_set shows or hides a layer by name (every group with that name, as CAD exporters repeat names) or by position, and page_render draws with the document's layer visibility. Still missing: Reset to initial visibility (view.layers-reset), layer properties, and /OC on annotations (#2176). The default configuration's auto state for the View event (/AS, ISO 32000-2 8.11.4.4) sets the groups it manages from their /Usage /View /ViewState as the document opens, on screen and in the panel, and toggles still override it; renders for printing and print previews don't apply it; printing takes the Print event's auto state instead (print.print-ready-pdf). Not yet: the /Zoom, /User and /Language categories. The panel presents the default configuration's /Order (ISO 32000-2 Table 99) as a tree: a nested array one level deeper, a leading text string as a label that can't be toggled. Groups /Order leaves out aren't listed but still draw in their state, and a document without /Order lists none, the default Table 99 gives; doc_info reports the rows as layer_order. Not yet: /ListMode /VisiblePages."
|
||||
|
||||
[[feature]]
|
||||
id = "view.layers-reset"
|
||||
@@ -1358,7 +1358,7 @@ milestone = "M12"
|
||||
status = "partial"
|
||||
commands = []
|
||||
tools = ["doc_info"]
|
||||
evidence = ["crates/engine/src/tests.rs::reset_layers_returns_to_the_files_visibility", "crates/render/src/inspect/tests.rs::initial_layer_visibility_is_the_default_configuration"]
|
||||
evidence = ["crates/engine/src/tests.rs::reset_layers_returns_to_the_files_visibility", "crates/render/src/inspect/tests.rs::initial_layer_visibility_is_the_default_configuration", "crates/render/src/inspect/tests.rs::initial_layer_visibility_applies_the_view_auto_state"]
|
||||
notes = "Layers panel ▸ Layer options ▸ Reset to Initial Visibility shows each layer as the default configuration (/OCProperties /D) has it; doc_info reports it as `initial`. Not yet: listing the layers of all pages or the current page only."
|
||||
|
||||
[[feature]]
|
||||
|
||||
Vendored
+1
-1
@@ -39,7 +39,7 @@ Other resource categories retain their existing parent-chain lookup.
|
||||
|
||||
| Crate | Version | Licence | Patches | Test |
|
||||
|---|---|---|---|---|
|
||||
| hayro-interpret | 0.7.0 | Apache-2.0 OR MIT | (1) select `/AP /N` appearance states via `/AS` (checkboxes, radios, stateful icons) and honour the NoView flag; (2) Type3 Unicode fallback to `/Encoding` glyph names, then printable ASCII; (3) `Type3Glyph::advance_width`; (4) `InterpreterSettings::ocg_overrides` for viewer layer toggles; (5) soft masks whose group lacks `/CS` were dropped (Chrome gradient text); (6) paint nesting cap `MAX_PAINT_NESTING` for tiling patterns and Type 3 glyphs (self-referencing content overflowed the stack); (7) CID width ranges in `/W` and `/W2` clamped to `MAX_CID` (a `0 4294967295 w` range hung); (8) `InterpreterSettings::hide_comments` skips markup annotations but keeps widgets and links (View ▸ Hide all comments); (9) `image_size_ok`: images and masks over 2^28 pixels are not decoded (a fuzzed `/W 4294967295` stencil mask allocated 4 GiB); (10) `MAX_NESTED_PAINTS`: nested paints (forms, Type 3 glyphs and tiling patterns inside one another) share a per-page budget of 50,000 (a glyph showing eight glyphs of its own font, sixteen deep, hung); (11) depends on skrifa 0.47 instead of 0.42 (upstream read-fonts fixed a Type 1 tokenizer that recursed through runs of numbers: a fuzzed font hung or overflowed the stack), with the one API change (`Charset::glyph_id` returns `Option`); (12) annotation appearances whose `/BBox` or `/Matrix` collapses to a line or a point are skipped (mapping them onto `/Rect` divided by zero and handed the device infinite or NaN matrices); (13) a Highlight annotation without a usable normal appearance is drawn from its `/QuadPoints`, `/C` and `/CA` with Multiply blending, as pdfcraft-annot draws highlights (it was not drawn at all); (14) simple-font `/Widths` (`read_widths`): entries only for codes 0–255 (one entry per code below `/FirstChar` was allocated: `4294967295` asked for 34 GB), an entry that isn't a number leaves its code missing instead of ending the array, and a `/LastChar` below `/FirstChar` gives no widths instead of discarding the font for a standard one; (15) the appearance box is mapped onto `/Rect` corner to corner: the translation now accounts for the scale (an appearance whose box didn't start at the origin and differed in size from `/Rect` was drawn shifted); (16) a clip set by `W`/`W*` takes effect after whichever path-painting operator ends the path (`S`, `f`, `B`, … as well as `n`; ISO 32000-2 §8.5.4): it was applied only on `n`, so `re W* S` clipped nothing and the clip stayed pending for a later, unrelated `n`; (17) `InterpreterSettings::cancelled`: once set, interpretation stops before the next content operator (a render pool sets it for every worker when dropped, after an edit or on closing, and for one worker when the watchdog gives up on its render, so renders whose answers nobody can receive stop instead of running to the end); (18) `MAX_PAGE_CONTENT`: the content a page holds at once (its contents, and the forms, tiling patterns and Type 3 glyph procedures being painted) stays within 512 MiB (`decode_content`; once it runs out, `InterpreterWarning::ContentTruncated` is reported (once per page by pdfcraft-render) so a truncated page is not a clean render; each level gives its bytes back when it finishes): forms nest fifty deep and each level kept its content while the next ran, so a form painting itself around a stream inflating to 256 MiB would have held over 12 GB; and Type 0 sampled functions take at most `MAX_SAMPLE_ENTRIES` (2^21) table points and `MAX_SAMPLE_VALUES` (2^23) samples, read no further than `/Size` asks (256 MiB of 1-bit samples asked for over 8 GB); (19) mesh shadings (types 4–7) are sampled only inside the area being drawn (`ShadingPattern::encode_within`, which the vendored hayro renderer calls with that area plus a pixel), within 8 visits per pixel of it plus 4 per triangle (`TriangleSampler`), and patches are triangulated one at a time: points far off the page were sampled over their whole bounding box, up to 65536 × 65536 entries (a fuzzed 147-byte patch stream; a synthetic page passed 6 GB in six seconds), ten thousand overlapping triangles ran for minutes, and every patch became 722 triangles before any limit; meshes hold at most `MAX_MESH_PATCHES` (2^16) patches and `MAX_MESH_TRIANGLES` (2^20) triangles, a lattice needs two to 2^19 vertices per row (`/VerticesPerRow 0` pushed empty rows for ever; one huge row read the whole stream), and a page samples at most `MAX_PAGE_MESH_TRIANGLES` (2^25) mesh triangles in all (a mesh painted a thousand times was triangulated a thousand times); each cut logs a warning; (20) PDF function construction is limited to 64 levels and 10,000 total nodes with cycle detection; calculator parsing and evaluation share procedure depth/work budgets, integer division/bitshift/rotation/index are panic-free, and fixed-size stack errors propagate; (21) a Type 0 font drawn with a substitute that isn't CID-keyed (it isn't embedded, or its program doesn't load) draws `.nLine truncated
|
||||
| hayro-interpret | 0.7.0 | Apache-2.0 OR MIT | (1) select `/AP /N` appearance states via `/AS` (checkboxes, radios, stateful icons) and honour the NoView flag; (2) Type3 Unicode fallback to `/Encoding` glyph names, then printable ASCII; (3) `Type3Glyph::advance_width`; (4) `InterpreterSettings::ocg_overrides` for viewer layer toggles; (5) soft masks whose group lacks `/CS` were dropped (Chrome gradient text); (6) paint nesting cap `MAX_PAINT_NESTING` for tiling patterns and Type 3 glyphs (self-referencing content overflowed the stack); (7) CID width ranges in `/W` and `/W2` clamped to `MAX_CID` (a `0 4294967295 w` range hung); (8) `InterpreterSettings::hide_comments` skips markup annotations but keeps widgets and links (View ▸ Hide all comments); (9) `image_size_ok`: images and masks over 2^28 pixels are not decoded (a fuzzed `/W 4294967295` stencil mask allocated 4 GiB); (10) `MAX_NESTED_PAINTS`: nested paints (forms, Type 3 glyphs and tiling patterns inside one another) share a per-page budget of 50,000 (a glyph showing eight glyphs of its own font, sixteen deep, hung); (11) depends on skrifa 0.47 instead of 0.42 (upstream read-fonts fixed a Type 1 tokenizer that recursed through runs of numbers: a fuzzed font hung or overflowed the stack), with the one API change (`Charset::glyph_id` returns `Option`); (12) annotation appearances whose `/BBox` or `/Matrix` collapses to a line or a point are skipped (mapping them onto `/Rect` divided by zero and handed the device infinite or NaN matrices); (13) a Highlight annotation without a usable normal appearance is drawn from its `/QuadPoints`, `/C` and `/CA` with Multiply blending, as pdfcraft-annot draws highlights (it was not drawn at all); (14) simple-font `/Widths` (`read_widths`): entries only for codes 0–255 (one entry per code below `/FirstChar` was allocated: `4294967295` asked for 34 GB), an entry that isn't a number leaves its code missing instead of ending the array, and a `/LastChar` below `/FirstChar` gives no widths instead of discarding the font for a standard one; (15) the appearance box is mapped onto `/Rect` corner to corner: the translation now accounts for the scale (an appearance whose box didn't start at the origin and differed in size from `/Rect` was drawn shifted); (16) a clip set by `W`/`W*` takes effect after whichever path-painting operator ends the path (`S`, `f`, `B`, … as well as `n`; ISO 32000-2 §8.5.4): it was applied only on `n`, so `re W* S` clipped nothing and the clip stayed pending for a later, unrelated `n`; (17) `InterpreterSettings::cancelled`: once set, interpretation stops before the next content operator (a render pool sets it for every worker when dropped, after an edit or on closing, and for one worker when the watchdog gives up on its render, so renders whose answers nobody can receive stop instead of running to the end); (18) `MAX_PAGE_CONTENT`: the content a page holds at once (its contents, and the forms, tiling patterns and Type 3 glyph procedures being painted) stays within 512 MiB (`decode_content`; once it runs out, `InterpreterWarning::ContentTruncated` is reported (once per page by pdfcraft-render) so a truncated page is not a clean render; each level gives its bytes back when it finishes): forms nest fifty deep and each level kept its content while the next ran, so a form painting itself around a stream inflating to 256 MiB would have held over 12 GB; and Type 0 sampled functions take at most `MAX_SAMPLE_ENTRIES` (2^21) table points and `MAX_SAMPLE_VALUES` (2^23) samples, read no further than `/Size` asks (256 MiB of 1-bit samples asked for over 8 GB); (19) mesh shadings (types 4–7) are sampled only inside the area being drawn (`ShadingPattern::encode_within`, which the vendored hayro renderer calls with that area plus a pixel), within 8 visits per pixel of it plus 4 per triangle (`TriangleSampler`), and patches are triangulated one at a time: points far off the page were sampled over their whole bounding box, up to 65536 × 65536 entries (a fuzzed 147-byte patch stream; a synthetic page passed 6 GB in six seconds), ten thousand overlapping triangles ran for minutes, and every patch became 722 triangles before any limit; meshes hold at most `MAX_MESH_PATCHES` (2^16) patches and `MAX_MESH_TRIANGLES` (2^20) triangles, a lattice needs two to 2^19 vertices per row (`/VerticesPerRow 0` pushed empty rows for ever; one huge row read the whole stream), and a page samples at most `MAX_PAGE_MESH_TRIANGLES` (2^25) mesh triangles in all (a mesh painted a thousand times was triangulated a thousand times); each cut logs a warning; (20) PDF function construction is limited to 64 levels and 10,000 total nodes with cycle detection; calculator parsing and evaluation share procedure depth/work budgets, integer division/bitshift/rotation/index are panic-free, and fixed-size stack errors propagate; (21) a Type 0 font drawn with a substitute that isn't CID-keyed (it isn't embedded, or its program doesn't load) draws `.nLine truncated
|
||||
| hayro | 0.7.1 | Apache-2.0 OR MIT | (1) `RenderSettings::{x_offset, y_offset}` to render one tile of a large page; (2) images over `MAX_IMAGE_PIXELS` (2^28) are skipped (a fuzzed `/W 4294967295` hung in resampling); (3) `tiling_cell_scale` keeps a tiling pattern's cell pixmap within 3000 px a side whatever its `/XStep`/`/YStep` (a fuzzed step far beyond `/BBox` allocated 2 GB); (4) stroke widths clamped to 4 × (canvas width + height) device pixels (a fuzzed `/LW 9223372036854775807` allocated 10 GB in stroke expansion); (5) `usable_dash_pattern`: a stroke whose dash pattern could cut it into more than `MAX_DASHES_PER_STROKE` (250,000) pieces, counting kurbo's restart of the pattern at every subpath and `ClosePath`, is drawn solid (a fuzzed `/D [[11] 0]` on a line from x = 92234775807 allocated over 5 GB, `[0.000001] 0 d` on a 20 pt line over 10 GB); (6) a dash pattern with a negative or non-finite entry, or a period that isn't positive, is drawn solid (`[-1 -1] 0 d` looped for ever in kurbo); (7) `render_size` and `render_into`: render into a buffer the caller allocates (PdfCraft renders into pixel-aligned memory that the GUI takes over as texture data); `render` is `render_into` on a new pixmap; (8) checked image source/target/RGBA, alpha-premultiplication scratch and intermediate sizes before resampling, finite transforms and exact source/mask buffers; sources wider than u16 may shrink before backend limits, with a 2^20 source-axis cap and conservative 128 MiB filter-planning estimate; an over-limit or failed resize keeps the original image resolution and geometry when the source fits the backend, otherwise skips it, with a logged warning; staging, resampling output/scratch, RGBA conversion and padding buffers use fallible reserves; (9) `may_paint_canvas`: a fill or stroke whose control-point box, grown by how far its paint reaches past the path (half the stroke width times the larger of the miter limit and √2) plus 0.5 user units and 2 pixels, misses the canvas is not drawn, so a tile no longer strokes and fills every path of its page (item 5 of #623); `set_skip_offscreen_paths` turns this off for the regression test; (10) `/Interpolate` governs the pre-resize too (#624): a minified image that does not request interpolation is pre-resized with nearest-neighbour (since (21), only inside Type 3 glyphs), planned without the Catmull-Rom filter limits (`image_resampling_size` takes the flag); a Type 3 glyph image is sampled bicubically only when interpolated; a minified image with a matching soft mask is nearest-sampled straight into premultiplied RGBA; (11) `may_paint_rect`: an image whose stream-size box, mapped to the device, misses the canvas is skipped before decoding (decoded data can only shrink against that box), so a tile of an image-heavy page no longer decodes, resamples and rasterizes every image on it; (12) preview renders (`InterpreterSettings::preview`: backdrops, thumbnails, grid cells, signature-drag backgrounds) skip images under `PREVIEW_MIN_IMAGE_AREA` device pixels, while final renders always draw them; (13) reading colours (#897): `RenderSettings::color_replacement` takes a `ColorReplacement` (text colour, background, `only_black`, `line_art`) that remaps solid text and line-art paint while rendering, glyph outlines counting as text and stencil-mask ink as line art; images, image alpha masks, soft masks and pattern cells keep their colours; `render_pdf` gains a `color_replacement: Option<ColorReplacement>` argument (pass `None` for true colours); the upstream-only `[dev-dependencies.log]` entry is removed from `Cargo.toml` (log is a normal dependency since the logging patch), so `cargo test -p hayro` runs this crate's unit tests; (14) a shrunk image that is interpolated (or, since (21), area-averaged) and whose axes lie along the device's (upright, mirrored or a quarter turn, as on a page under `/Rotate`) is snapped to whole device pixels: shrunk once to its rounded device rectangle (halves round up, so a tile snaps an edge where the whole page does) and drawn 1:1 from the rounded corner, instead of a ceil-sized raster resampled again at a fractional scale and offset (`snap_minified_image`; scans looked soft next to Acrobat, and until #5530 a turned one still did, up to 200 grey levels off the same page drawn upright). An image counts as axis-aligned when the terms the snap drops move its far edges by at most a hundredth of a device pixel (`SNAP_SKEW`), not by a tolerance on the coefficients, which let a slight skew of a very wide image through; and the snapped 1:1 transform is used only when the shrink produced the snapped size, so a failed resize keeps the full transform instead of drawing the source raster at its source size; (15) a soft mask of another size than its image is filtered when shrunk, whatever its `/Interpolate` (#1649): such a mask carries the shape on its own (Word saves text as a tiny black image with a glyph-bitmap mask), and nearest-neighbour dropped every stroLine truncated
|
||||
| hayro-jbig2 | 0.3.0 | Apache-2.0 OR MIT | (1) at most 2^28 pixels per bitmap and page bitmap, and 2^25 cells per halftone grid and grayscale image (each side could be 65535: 4.3 billion pixels decoded one by one, and a 4-byte value per cell); (2) at most 2^26 symbol pixels per symbol dictionary (a fuzzed dictionary decoded for minutes); (3) a symbol dictionary's height classes are capped at one per new symbol and its export runs at `2 × symbols + 1`, each plus `EXTRA_EMPTY_STEPS` (1024): an empty height class or a zero-length export run doesn't advance, and past the end of its data the arithmetic decoder can decode them for ever (one changed byte hung the renderer); (4) a segment header's long-form referred-to segment count is capped at `u16::MAX` and a larger count is refused before its retention or referred-to bytes are read: the 29-bit count went straight to `Vec::with_capacity`, a reservation of about 2 GiB whose failure aborts the process (from storytold/craft-libs#176); (5) what a page's segments hold for later ones (intermediate regions, pattern and symbol dictionaries with their headers and retained contexts, and Huffman tables) is at most 64 MiB, two square bitmaps of 16,384 a side (`MAX_RETAINED_WORDS`), and a dictionary's new and exported symbols are counted against it as they are made: each was bounded on its own, but a few dozen bytes an intermediate region held 33 MB each, and 8 MiB symbols exported again and again killed the process, so a few kilobytes could exhaust memory; (6) a segment may refer to at most 2^20 symbols, checked before any are collected: references may repeat, and 65,535 of them to one dictionary, in a 78 KB stream, asked for 17 GB; (7) a pattern dictionary keeps at most 16 MiB of shifted copies, which only speed up drawing, and none that wouldn't fit what the page has left (`MAX_SHIFTED_WORDS`); (8) a custom Huffman table has at most 2^16 lines, and a stream with its globals at most 2^20 segments and 2^22 references, checked as they are read: both grew before anything counted them, and PDFs of a kilobyte or so reached 5 GB and more behind nested Flate; (9) a page past the bounds of (1) is refused when the stream is opened: a caller sizes its output from the header before the page bitmap is made, and an Indexed image in a 743-byte PDF asked for 137 GB, which aborts; (10) a stream may ask for at most 2^30 units of decoding work, four of the largest pages, about 6 s to 17 s (`MAX_WORK`): decoding a bitmap costs a pixel each and 4 a row, copying one a word each and 1 a row, and each integer an item reads costs 38, what one takes at worst, so one with no pixels pays too, before it is decoded: each bitmap was bounded, but nothing bounded how many there were, and a 795-byte PDF took 265 s; (11) `Image::decode_within` spends from what a run of images may still do, starting with its page's pixels, and `charge_reading` charges reading a stream and its globals before anything is parsed, so an operation over a document can bound what `MAX_WORK` bounds for one image, and images that fail or decode nothing add up too: a file of thousands of images made to reach that limit took as many times as long; (12) adding to a location, a reference offset, a symbol's corner or a Huffman range line near the end of an `i32`, and negating a decoded integer of 2^31, overflowed: a panic wherever overflow is checked. The refinement context, a text region's corners, the integer decoder and the Huffman table wrap, as a release build did, and `Bitmap::combine` saturates, which comes to the same, as a location that overflows is past the end of any page. What is drawn doesn't change; (13) a bitmap filled with a default pixel of 1 (a page, or an intermediate text or halftone region) had 1s past its width in the last word of each row, and a refinement, which reads its reference a word at a time, read them as pixels where the standard has 0 (6.3.5.2): refining such a reference not a multiple of 32 wide decoded to other pixels than were coded, release builds too. `Bitmap::clear_padding` clears those bits when a bitmap is filled with 1s, as cutting symbols and patterns from a collective bitmap already did. Ghostscript reads the test's page and text streams as they decode now; (14) a region's location is unsigned (5.4.4), so one past `i32::MAX` is off the page, where the decoder took it for a signed one: a region there was drawn back onto the page from the left or the top (at 0xFFFFFFFC, four pixels left of it), and a refinement there, of the page or of a region at the same place (7.4.7.5), was refused as an overflow, and the page with it. `Bitmap::combine_region` keeps such a location past the page. A refinement of another region refines it where it is, as Table 35 has it (GRREFERENCEDX and GRREFERENCEDY 0), whatever the two locations say; a refinement of the page, see (16); (15) a refinement whose reference is offset right of it (GRREFERENCEDX above 0, which a refined text instance has from a wider bitmap, TaLine truncated
|
||||
| lopdf | 0.45.0 | MIT | (1) PNG predictor rows longer than the data are refused before their buffers are allocated (a fuzzed `/Columns 4294967295` allocated two 4 GiB rows), and empty frames return without row buffers; (2) predictor row widths use saturating arithmetic or reject overflow; (3) sub-byte TIFF Predictor 2 scratch is bounded by the samples present in the input instead of the declared `/Colors`, aligned with [lopdf#589](https://github.com/J-F-Liu/lopdf/pull/589); (4) the object lookup keeps its cycle history through compressed objects, requires an ordinary in-file container, and caps the chain of indirect lookups at 16 (a chain of new objects, each a `/Length` compressed in a container whose own `/Length` names the next, or a stream whose `/Length` names the next stream, overflowed the stack: a dev build's 2 MiB thread within 800 hops); (5) object-stream members are parsed within their own extent (up to the next distinct offset), an entry whose offset repeats an earlier entry's is skipped (so a repeated object number can resolve to its earlier entry), and offsets are processed in index order; (6) `find_latest_trailer`: a rebuild takes a `/Type /XRef` stream dictionary as the trailer when the file has no `trailer` keyword (the latest in the file wins, as a later `trailer` would), so a concatenated or truncated file keeps its /Info and /ID instead of failing to load; a candidate whose /Root is the catalog beats one whose /Root is another dictionary, and an in-file /Root must match its generation (#2365) | (1) `inspect::tests::png_predictor_rows_longer_than_the_data_are_refused_before_allocating`, `inspect::tests::empty_png_predictor_frames_do_not_allocate_rows`; (2) `inspect::tests::tiff_subbyte_predictor_row_width_overflow_is_refused`; (3) `inspect::tests::tiff_subbyte_predictor_scratch_is_bounded_by_available_samples`, `inspect::tests::tiff_subbyte_predictors_keep_components_rows_and_padding`; (4) `inspect::tests::compressed_object_self_container_does_not_recurse`, `inspect::tests::compressed_object_mutual_containers_do_not_recurse`, `inspect::tests::object_stream_length_cycle_does_not_recurse`, `inspect::tests::compressed_object_container_chain_does_not_recurse`, `inspect::tests::compressed_length_chain_does_not_recurse`, `inspect::tests::plain_stream_length_chain_does_not_recurse`, `inspect::tests::compressed_objects_and_indirect_stream_length_still_load`, `inspect::tests::compressed_length_in_a_container_with_an_indirect_length_still_loads`; (5) `inspect::tests::object_stream_member_extents_bound_owned_strings`, `inspect::tests::object_stream_member_extents_preserve_index_order_and_whitespace`; (6) `inspect::tests::rebuilt_file_keeps_the_info_of_its_cross_reference_stream`, `inspect::tests::rebuilt_file_prefers_a_trailer_whose_root_is_the_catalog` |
|
||||
|
||||
Vendored
+21
-3
@@ -10,9 +10,10 @@ use std::sync::{Arc, Mutex};
|
||||
|
||||
type CacheMap = HashMap<u128, Option<Box<dyn Any + Send + Sync>>>;
|
||||
/// The objects read from a document, by key. PdfCraft patch (48): the second field counts the
|
||||
/// ICC profiles read through it ([`Cache::icc_profile_reads`]).
|
||||
/// ICC profiles read through it ([`Cache::icc_profile_reads`]). PdfCraft patch (80): the third
|
||||
/// counts the `/Indexed` lookup tables read ([`Cache::indexed_lookup_reads`]).
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct Cache(Arc<Mutex<CacheMap>>, Arc<AtomicUsize>);
|
||||
pub(crate) struct Cache(Arc<Mutex<CacheMap>>, Arc<AtomicUsize>, Arc<AtomicUsize>);
|
||||
impl Default for Cache {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
@@ -21,7 +22,11 @@ impl Default for Cache {
|
||||
|
||||
impl Cache {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self(Arc::new(Mutex::new(HashMap::new())), Arc::default())
|
||||
Self(
|
||||
Arc::new(Mutex::new(HashMap::new())),
|
||||
Arc::default(),
|
||||
Arc::default(),
|
||||
)
|
||||
}
|
||||
|
||||
/// PdfCraft patch (48): count one ICC profile read, the colour space of an `/ICCBased`
|
||||
@@ -35,6 +40,17 @@ impl Cache {
|
||||
self.1.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// PdfCraft patch (80): count one `/Indexed` lookup table read (a stream decoded or a
|
||||
/// string copied).
|
||||
pub(crate) fn count_indexed_lookup_read(&self) {
|
||||
self.2.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// PdfCraft patch (80): how many `/Indexed` lookup tables were read through this cache.
|
||||
pub(crate) fn indexed_lookup_reads(&self) -> usize {
|
||||
self.2.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
pub(crate) fn get_or_insert_with<T: Clone + Send + Sync + 'static>(
|
||||
&self,
|
||||
id: u128,
|
||||
@@ -142,6 +158,7 @@ fn warning_bit(warning: InterpreterWarning) -> u8 {
|
||||
InterpreterWarning::ContentTruncated => 4,
|
||||
InterpreterWarning::ColorFallback => 8,
|
||||
InterpreterWarning::Type3WidthsMissing => 16,
|
||||
InterpreterWarning::MalformedIndexedImage => 32,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -153,6 +170,7 @@ fn warnings_in(bits: u8) -> impl Iterator<Item = InterpreterWarning> {
|
||||
InterpreterWarning::ContentTruncated,
|
||||
InterpreterWarning::ColorFallback,
|
||||
InterpreterWarning::Type3WidthsMissing,
|
||||
InterpreterWarning::MalformedIndexedImage,
|
||||
]
|
||||
.into_iter()
|
||||
.filter(move |warning| bits & warning_bit(*warning) != 0)
|
||||
|
||||
Vendored
+160
-30
@@ -258,7 +258,7 @@ impl ColorSpaceType {
|
||||
return Some(Self::Lab(Lab::new(&lab_dict)?));
|
||||
}
|
||||
INDEXED | I => {
|
||||
return Some(Self::Indexed(Indexed::new(&color_array, cache, depth)?));
|
||||
return Some(Self::Indexed(Indexed::new(&color_array, cache, depth, false)?));
|
||||
}
|
||||
SEPARATION => {
|
||||
return Some(Self::Separation(Separation::new(&color_array, cache, depth)?));
|
||||
@@ -312,6 +312,22 @@ impl ColorSpace {
|
||||
Some(Self(Arc::new(ColorSpaceType::new(object, cache, depth)?)))
|
||||
}
|
||||
|
||||
/// PdfCraft patch (80): as `new`, except that an `/Indexed` space with no lookup table is
|
||||
/// built (marked tableless) rather than unreadable, for the image and colour operators to
|
||||
/// handle it (see `Indexed::new`). Every other space is read as by `new`.
|
||||
pub(crate) fn new_allowing_tableless(object: Object<'_>, cache: &Cache) -> Option<Self> {
|
||||
if let Object::Array(array) = &object
|
||||
&& array
|
||||
.flex_iter()
|
||||
.next::<Name<'_>>()
|
||||
.is_some_and(|family| matches!(family.deref(), INDEXED | I))
|
||||
{
|
||||
return Indexed::new(array, cache, 0, true)
|
||||
.map(|indexed| Self(Arc::new(ColorSpaceType::Indexed(indexed))));
|
||||
}
|
||||
Self::new(object, cache)
|
||||
}
|
||||
|
||||
/// Create a new color space from the name.
|
||||
pub(crate) fn new_from_name(name: &Name<'_>) -> Option<Self> {
|
||||
ColorSpaceType::new_from_name(name).map(|c| Self(Arc::new(c)))
|
||||
@@ -354,6 +370,18 @@ impl ColorSpace {
|
||||
matches!(self.0.as_ref(), ColorSpaceType::Indexed(_))
|
||||
}
|
||||
|
||||
/// PdfCraft patch (80): whether this is an indexed colour space that broke ISO 32000-2
|
||||
/// §8.6.6.3 and was recovered (see `Indexed::new`).
|
||||
pub(crate) fn is_recovered_indexed(&self) -> bool {
|
||||
matches!(self.0.as_ref(), ColorSpaceType::Indexed(i) if i.recovered && !i.tableless)
|
||||
}
|
||||
|
||||
/// PdfCraft patch (80): whether this is an indexed colour space with no lookup table (see
|
||||
/// `Indexed::new`), which only `ColorSpace::new_allowing_tableless` builds.
|
||||
pub(crate) fn is_tableless_indexed(&self) -> bool {
|
||||
matches!(self.0.as_ref(), ColorSpaceType::Indexed(i) if i.tableless)
|
||||
}
|
||||
|
||||
/// Get the default decode array for the color space.
|
||||
pub(crate) fn default_decode_arr(&self, n: f32) -> SmallVec<[(f32, f32); 4]> {
|
||||
match self.0.as_ref() {
|
||||
@@ -1003,55 +1031,144 @@ impl ToRgb for Lab {
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub(crate) struct Indexed {
|
||||
/// `hival + 1` entries of the base's component count each; entries from `present` on are
|
||||
/// zeros and are drawn black (see `convert_f32`).
|
||||
values: Vec<Vec<f32>>,
|
||||
hival: u8,
|
||||
base: Box<ColorSpace>,
|
||||
/// PdfCraft patch (80): how many entries the lookup table holds in full (at most
|
||||
/// `hival + 1`). An index at or past it is drawn black.
|
||||
present: usize,
|
||||
/// PdfCraft patch (80): the space broke ISO 32000-2 §8.6.6.3 and was recovered (see
|
||||
/// `Indexed::new`).
|
||||
recovered: bool,
|
||||
/// PdfCraft patch (80): the space has no lookup table at all (see `Indexed::new`).
|
||||
tableless: bool,
|
||||
}
|
||||
|
||||
impl Indexed {
|
||||
fn new(array: &Array<'_>, cache: &Cache, depth: u32) -> Option<Self> {
|
||||
/// PdfCraft patch (80): ISO 32000-2 §8.6.6.3 says `hival` "shall be an integer" no greater
|
||||
/// than 255 and the lookup table "shall be m × (hival + 1) bytes long", but not how a reader
|
||||
/// recovers when a file breaks this. Most readers draw such a space, and so does this:
|
||||
/// - a real `hival` is truncated toward zero (upstream read it so too);
|
||||
/// - a `hival` past 255 is taken as 255;
|
||||
/// - a lookup table shorter than m × (hival + 1) bytes keeps the entries it holds in full,
|
||||
/// and an index past them is drawn black, after conversion, whatever the base space (zero
|
||||
/// bytes would be white in DeviceCMYK, Separation and DeviceN, and blue in Lab).
|
||||
///
|
||||
/// Any of these sets `recovered`, which the drawing paths report. A `hival` below zero (once
|
||||
/// truncated), or not a number, has no reading: the space cannot be read, as upstream, and
|
||||
/// `has_unusable_hival` lets the image path report it.
|
||||
///
|
||||
/// A lookup that is missing, or neither a string nor a stream that decodes, is no table at
|
||||
/// all. Upstream could not read such a space either. With `allow_tableless` it is built,
|
||||
/// marked `tableless`, so that the image path can skip the image with a warning and the
|
||||
/// colour operators can fall back as upstream; without it, it is `None` as upstream.
|
||||
fn new(array: &Array<'_>, cache: &Cache, depth: u32, allow_tableless: bool) -> Option<Self> {
|
||||
let mut iter = array.flex_iter();
|
||||
// Skip name
|
||||
let _ = iter.next::<Name<'_>>()?;
|
||||
let base_color_space = ColorSpace::within(iter.next::<Object<'_>>()?, cache, depth + 1)?;
|
||||
let hival = iter.next::<u32>()?.min(u8::MAX as u32) as u8;
|
||||
let (hival, hival_recovered) = indexed_hival(iter.next::<object::Number>()?)?;
|
||||
|
||||
let values = {
|
||||
// PdfCraft patch (71): read once, as whichever it is. A failed read as a stream leaves
|
||||
// a direct string in place but uses up a reference, so a table in an indirect string
|
||||
// was lost, and the space with it.
|
||||
let data = match iter.next::<Object<'_>>()? {
|
||||
Object::Stream(s) => s.decoded().ok()?,
|
||||
Object::String(s) => Cow::Owned(s.to_vec()),
|
||||
_ => return None,
|
||||
};
|
||||
// At most 255 components (a `u8`), and at most 256 entries.
|
||||
let num_components = usize::from(base_color_space.num_components());
|
||||
let entries = usize::from(hival) + 1;
|
||||
|
||||
let num_components = base_color_space.num_components();
|
||||
|
||||
let mut byte_iter = data.iter().copied();
|
||||
|
||||
let mut vals = vec![];
|
||||
for _ in 0..=hival {
|
||||
let mut temp = vec![];
|
||||
|
||||
for _ in 0..num_components {
|
||||
temp.push(byte_iter.next()? as f32 / 255.0);
|
||||
}
|
||||
|
||||
vals.push(temp);
|
||||
}
|
||||
|
||||
vals
|
||||
};
|
||||
// PdfCraft patch (80): read once and then by type, so a string lookup given by an
|
||||
// indirect reference is found (a failed stream read had already consumed the
|
||||
// reference).
|
||||
let data = iter
|
||||
.next::<Object<'_>>()
|
||||
.and_then(|o| indexed_lookup(o, cache));
|
||||
let tableless = data.is_none();
|
||||
if tableless && !allow_tableless {
|
||||
return None;
|
||||
}
|
||||
let data: &[u8] = data.as_deref().unwrap_or_default();
|
||||
let present = data
|
||||
.len()
|
||||
.checked_div(num_components)
|
||||
.unwrap_or(0)
|
||||
.min(entries);
|
||||
let mut bytes = data.iter().copied();
|
||||
let values: Vec<Vec<f32>> = (0..entries)
|
||||
.map(|entry| {
|
||||
(0..num_components)
|
||||
.map(|_| {
|
||||
if entry < present {
|
||||
f32::from(bytes.next().unwrap_or(0)) / 255.0
|
||||
} else {
|
||||
0.0
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.collect();
|
||||
|
||||
Some(Self {
|
||||
values,
|
||||
hival,
|
||||
base: Box::new(base_color_space),
|
||||
present,
|
||||
recovered: hival_recovered || present < entries,
|
||||
tableless,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// PdfCraft patch (80): an Indexed space's `hival` (ISO 32000-2 §8.6.6.3) as drawn, and whether
|
||||
/// it had to be recovered: a real is truncated toward zero and a value past 255 is taken as 255.
|
||||
/// `None` for a value below zero once truncated, or one that is not finite.
|
||||
fn indexed_hival(number: object::Number) -> Option<(u8, bool)> {
|
||||
let value = number.as_f64();
|
||||
let whole = value.trunc();
|
||||
// NaN fails this test too.
|
||||
if !(whole >= 0.0 && whole.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
let clamped = whole.min(f64::from(u8::MAX));
|
||||
// `clamped` is a whole number in 0..=255, so the cast is exact.
|
||||
Some((clamped as u8, clamped != value))
|
||||
}
|
||||
|
||||
/// PdfCraft patch (80): whether `object` is an `/Indexed` colour space array whose `hival` has no
|
||||
/// reading (below zero, or not a number), which `Indexed::new` cannot recover. Reads the array's
|
||||
/// first and third entries only; the lookup table is not touched.
|
||||
pub(crate) fn has_unusable_hival(object: &Object<'_>) -> bool {
|
||||
let Object::Array(array) = object else {
|
||||
return false;
|
||||
};
|
||||
let mut iter = array.flex_iter();
|
||||
if !iter
|
||||
.next::<Name<'_>>()
|
||||
.is_some_and(|family| matches!(family.deref(), INDEXED | I))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let _base = iter.next::<Object<'_>>();
|
||||
iter.next::<object::Number>()
|
||||
.and_then(indexed_hival)
|
||||
.is_none()
|
||||
}
|
||||
|
||||
/// PdfCraft patch (80): an Indexed space's lookup table, a byte string or a stream (ISO 32000-2
|
||||
/// §8.6.6.3), with a stream's filters applied. `None` for any other object or a stream that
|
||||
/// cannot be decoded. A stream that decodes to nothing although it holds data counts as one that
|
||||
/// cannot be decoded: the Flate decoder recovers what it can from a broken stream, and here
|
||||
/// recovered nothing. Each call is counted on `cache` (`Cache::indexed_lookup_reads`).
|
||||
fn indexed_lookup<'a>(lookup: Object<'a>, cache: &Cache) -> Option<Cow<'a, [u8]>> {
|
||||
cache.count_indexed_lookup_read();
|
||||
match lookup {
|
||||
Object::Stream(s) => s
|
||||
.decoded()
|
||||
.ok()
|
||||
.filter(|d| !d.is_empty() || s.raw_data().is_empty()),
|
||||
Object::String(s) => Some(Cow::Owned(s.to_vec())),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
impl ToRgb for Indexed {
|
||||
fn convert_f32(&self, input: &[f32], output: &mut [u8], _: bool) -> Option<()> {
|
||||
let mut indexed = vec![0.0; input.len() * self.base.num_components() as usize];
|
||||
@@ -1065,7 +1182,20 @@ impl ToRgb for Indexed {
|
||||
output.copy_from_slice(&self.values[idx]);
|
||||
}
|
||||
|
||||
self.base.convert_f32(&indexed, output, true)
|
||||
self.base.convert_f32(&indexed, output, true)?;
|
||||
|
||||
// PdfCraft patch (80): an index past the entries the table holds is drawn black, in
|
||||
// whatever space the base is (see `Indexed::new`).
|
||||
if self.present <= usize::from(self.hival) {
|
||||
for (input, rgb) in input.iter().copied().zip(output.chunks_exact_mut(3)) {
|
||||
let idx = (input.clamp(0.0, self.hival as f32) + 0.5) as usize;
|
||||
if idx >= self.present {
|
||||
rgb.fill(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Some(())
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+14
-2
@@ -220,6 +220,13 @@ impl<'a> InterpreterCache<'a> {
|
||||
pub fn icc_profile_reads(&self) -> usize {
|
||||
self.object_cache.icc_profile_reads()
|
||||
}
|
||||
|
||||
/// PdfCraft patch (80): how many `/Indexed` lookup tables were read through this cache, for
|
||||
/// diagnostics and tests. A colour space named by a resource is built, and its table read,
|
||||
/// once however many images or colours use it.
|
||||
pub fn indexed_lookup_reads(&self) -> usize {
|
||||
self.object_cache.indexed_lookup_reads()
|
||||
}
|
||||
}
|
||||
|
||||
/// A per-page interpretation context that borrows shared data from an [`InterpreterCache`].
|
||||
@@ -308,7 +315,7 @@ impl<'a> Context<'a> {
|
||||
let mut ocg_state = {
|
||||
let root_ref = xref.root_id();
|
||||
xref.get::<Dict<'_>>(root_ref)
|
||||
.map(|catalog| OcgState::from_catalog(&catalog))
|
||||
.map(|catalog| OcgState::from_catalog(&catalog, xref, settings.view_auto_state))
|
||||
.unwrap_or_default()
|
||||
};
|
||||
// PdfCraft patch: apply viewer layer toggles.
|
||||
@@ -565,6 +572,8 @@ impl<'a> Context<'a> {
|
||||
self.get_mut().ctm *= transform;
|
||||
}
|
||||
|
||||
/// PdfCraft patch (80): an `/Indexed` resource with no lookup table is built, marked
|
||||
/// tableless, for the image and colour operators to handle (see `Indexed::new`).
|
||||
pub(crate) fn get_color_space(
|
||||
&mut self,
|
||||
resources: &Resources<'_>,
|
||||
@@ -574,7 +583,10 @@ impl<'a> Context<'a> {
|
||||
self.interpreter_cache
|
||||
.object_cache
|
||||
.get_or_insert_with(cs_object.cache_key(), || {
|
||||
ColorSpace::new(cs_object.clone(), &self.interpreter_cache.object_cache)
|
||||
ColorSpace::new_allowing_tableless(
|
||||
cs_object.clone(),
|
||||
&self.interpreter_cache.object_cache,
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
+30
@@ -28,3 +28,33 @@ pub(crate) fn convert_line_join(lc: LineJoin) -> kurbo::Join {
|
||||
_ => kurbo::Join::Miter,
|
||||
}
|
||||
}
|
||||
|
||||
/// PdfCraft patch (61): the line width to keep for a `w` operand or an ExtGState `/LW`. ISO
|
||||
/// 32000-2 §8.4.3.2 makes 0 "the thinnest line that can be rendered at device resolution" but
|
||||
/// says nothing of a negative width; it is drawn as 0, as is one that isn't finite, so no device
|
||||
/// sees a width below zero.
|
||||
pub(crate) fn convert_line_width(width: f32) -> f32 {
|
||||
if width.is_finite() && width > 0.0 {
|
||||
width
|
||||
} else {
|
||||
0.0
|
||||
}
|
||||
}
|
||||
|
||||
/// PdfCraft patch (61): the dash array to keep for a `d` operator or an ExtGState `/D`. ISO
|
||||
/// 32000-2 §8.4.3.6 requires numbers that "shall be nonnegative and not all zero". A pattern that
|
||||
/// breaks that (all zero, a negative or a non-finite entry) is kept as `[]`, a solid line, rather
|
||||
/// than cut into dashes the zero-entry workaround below would make a hundredth of a point long.
|
||||
pub(crate) fn convert_dash_array(
|
||||
dashes: impl Iterator<Item = f32>,
|
||||
) -> smallvec::SmallVec<[f32; 4]> {
|
||||
let dashes: smallvec::SmallVec<[f32; 4]> = dashes.collect();
|
||||
if dashes.iter().any(|d| !d.is_finite() || *d < 0.0) || dashes.iter().all(|d| *d == 0.0) {
|
||||
return smallvec::SmallVec::new();
|
||||
}
|
||||
// kurbo apparently cannot properly deal with dashes that are exactly 0.
|
||||
dashes
|
||||
.into_iter()
|
||||
.map(|d| if d == 0.0 { 0.01 } else { d })
|
||||
.collect()
|
||||
}
|
||||
+13
@@ -5,6 +5,7 @@ use skrifa::instance::{LocationRef, Size};
|
||||
use skrifa::metrics::GlyphMetrics;
|
||||
use skrifa::outline::{DrawSettings, Engine, HintingInstance, HintingOptions, Target};
|
||||
use skrifa::raw::TableProvider;
|
||||
use skrifa::raw::model::pen::NullPen;
|
||||
use skrifa::raw::ps::cff::{CffFontRef, Subfont, charset::Charset, v1::Cff};
|
||||
use skrifa::raw::ps::string::Sid;
|
||||
use skrifa::raw::ps::type1::Type1Font;
|
||||
@@ -126,6 +127,18 @@ impl CffFontBlob {
|
||||
path.take()
|
||||
}
|
||||
|
||||
/// PdfCraft patch (see vendor/README.md hayro-interpret (77)): the glyph's own advance from
|
||||
/// its charstring, in thousandths of an em like [`Self::outline_glyph`], or `None` when the
|
||||
/// charstring can't be read or gives no usable width.
|
||||
pub(crate) fn advance_width(&self, glyph: GlyphId) -> Option<f32> {
|
||||
let subfont = self.subfont(glyph)?;
|
||||
self.font()
|
||||
.draw(subfont, glyph, &[], Some(UNITS_PER_EM), &mut NullPen)
|
||||
.ok()
|
||||
.flatten()
|
||||
.filter(|width| width.is_finite() && *width > 0.0)
|
||||
}
|
||||
|
||||
pub(crate) fn glyph_names(&self) -> Vec<(GlyphId, String)> {
|
||||
let Some(charset) = self.charset() else {
|
||||
return Vec::new();
|
||||
|
||||
+3
-1
@@ -361,7 +361,9 @@ impl StandardFontBlob {
|
||||
|
||||
pub(crate) fn advance_width(&self, glyph: GlyphId) -> Option<f32> {
|
||||
match self {
|
||||
Self::Cff(_) => None,
|
||||
// PdfCraft patch (77): the stand-in's own advance, so a glyph drawn wider than the
|
||||
// standard metrics (the € of the bundled stand-ins) is fitted to them.
|
||||
Self::Cff(blob) => blob.advance_width(glyph),
|
||||
Self::Otf(blob, _) => blob.glyph_metrics().advance_width(glyph),
|
||||
}
|
||||
}
|
||||
|
||||
+130
-5
@@ -191,11 +191,23 @@ impl TrueTypeFont {
|
||||
}
|
||||
|
||||
match &self.kind {
|
||||
// PdfCraft patch (#3169): a name outside the glyph list reads by the glyph list
|
||||
// specification's full mapping (`f_i`, `hyphen.case`).
|
||||
Kind::Embedded(e) => e.code_to_unicode_name(code as u8).and_then(|name| {
|
||||
glyph_name_to_unicode(name).map(BfString::Char).or_else(|| glyph_name_to_text(name))
|
||||
}),
|
||||
Kind::Embedded(e) => {
|
||||
// PdfCraft patch (79): see `EmbeddedKind::symbolic_text`.
|
||||
if let Some(text) = e.symbolic_text(code as u8) {
|
||||
let mut chars = text.chars();
|
||||
return Some(match (chars.next(), chars.next()) {
|
||||
(Some(c), None) => BfString::Char(c),
|
||||
_ => BfString::String(text.to_string()),
|
||||
});
|
||||
}
|
||||
// PdfCraft patch (#3169): a name outside the glyph list reads by the glyph list
|
||||
// specification's full mapping (`f_i`, `hyphen.case`).
|
||||
e.code_to_unicode_name(code as u8).and_then(|name| {
|
||||
glyph_name_to_unicode(name)
|
||||
.map(BfString::Char)
|
||||
.or_else(|| glyph_name_to_text(name))
|
||||
})
|
||||
}
|
||||
Kind::Standard(s) => s.char_code_to_unicode(code as u8).map(BfString::Char),
|
||||
}
|
||||
|
||||
@@ -221,6 +233,9 @@ struct EmbeddedKind {
|
||||
cached_mappings: RefCell<HashMap<u8, GlyphId>>,
|
||||
/// PostScript name from the PDF.
|
||||
postscript_name: Option<String>,
|
||||
/// PdfCraft patch (79): the text each glyph's `post` table name stands for, for the names
|
||||
/// that stand for any (`glyph_name_text`).
|
||||
text_names: HashMap<GlyphId, String>,
|
||||
/// PdfCraft patch (101): whether the font may take the Mac OS Roman reading at all, worked out
|
||||
/// once when it is loaded (`EmbeddedKind::mac_roman_name`).
|
||||
mac_roman_eligible: bool,
|
||||
@@ -240,6 +255,10 @@ impl EmbeddedKind {
|
||||
.and_then(|d| OpenTypeFontBlob::new(Arc::new(d.to_vec()), 0))?;
|
||||
|
||||
let glyph_names = base_font.glyph_names();
|
||||
let text_names = glyph_names
|
||||
.iter()
|
||||
.filter_map(|(name, glyph)| Some((*glyph, glyph_name_text(name)?)))
|
||||
.collect();
|
||||
|
||||
let cff_font_blob = base_font
|
||||
.font_ref()
|
||||
@@ -283,6 +302,7 @@ impl EmbeddedKind {
|
||||
encoding,
|
||||
cached_mappings: RefCell::new(HashMap::new()),
|
||||
postscript_name,
|
||||
text_names,
|
||||
mac_roman_eligible: !names_base_encoding && !symbolic_builtin,
|
||||
})
|
||||
}
|
||||
@@ -325,6 +345,29 @@ impl EmbeddedKind {
|
||||
.or_else(|| win_ansi::get(code))
|
||||
}
|
||||
|
||||
/// PdfCraft patch (79): a symbolic font without an encoding selects its glyphs through its
|
||||
/// own `cmap`, so its codes need not mean anything in WinAnsi. FrameMaker files distilled
|
||||
/// with Distiller 3 number them in the Macintosh glyph order, 29 below ASCII, and read as
|
||||
/// WinAnsi `Solid` came out as `6ROLG` (#3962). The name the `post` table gives the glyph the
|
||||
/// code selects says what it is, as MuPDF reads it, and as pdfcraft-fonts reads it for the
|
||||
/// editor. `None` when the font is non-symbolic, has an encoding or a `/Differences` entry
|
||||
/// for the code, selects no glyph for it, or names it with no text: the code is then read as
|
||||
/// before.
|
||||
fn symbolic_text(&self, code: u8) -> Option<&str> {
|
||||
if self.is_non_symbolic()
|
||||
|| !matches!(self.encoding, Encoding::BuiltIn)
|
||||
|| self.differences.contains_key(&code)
|
||||
|| self.cff_blob.is_some()
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let glyph = self.map_code(code);
|
||||
if glyph == GlyphId::NOTDEF {
|
||||
return None;
|
||||
}
|
||||
self.text_names.get(&glyph).map(String::as_str)
|
||||
}
|
||||
|
||||
fn outline_glyph(&self, glyph: GlyphId) -> BezPath {
|
||||
self.base_font.outline_glyph(glyph)
|
||||
}
|
||||
@@ -510,6 +553,38 @@ pub(crate) enum Width {
|
||||
Missing,
|
||||
}
|
||||
|
||||
/// PdfCraft patch (79): the text a glyph name stands for, by the rules of the Adobe Glyph List
|
||||
/// specification (ISO 32000-2 §9.10.2): drop any suffix from the first `.` (`a.ss01` is `a`),
|
||||
/// then each `_`-separated component is a list name, `uni` and groups of exactly four
|
||||
/// uppercase hex digits, or `u` and four to six. A value in the surrogate range or past
|
||||
/// U+10FFFF is no character. `None` when any component is none of these (`uni20ac`, `uni65`,
|
||||
/// `u65`). Each component gives at least one character, so the text is never empty.
|
||||
fn glyph_name_text(name: &str) -> Option<String> {
|
||||
// An empty stem (`.notdef`) is no list name and no number, so it gives `None` below.
|
||||
let stem = name.split('.').next()?;
|
||||
// `from_str_radix` alone would also take a sign (`uni+041`) and lowercase digits, which the
|
||||
// specification's forms don't have.
|
||||
let hex = |h: &str| !h.is_empty() && h.bytes().all(|b| matches!(b, b'0'..=b'9' | b'A'..=b'F'));
|
||||
let mut out = String::new();
|
||||
for part in stem.split('_') {
|
||||
if let Some(text) = glyph_names::get(part) {
|
||||
out.push_str(text);
|
||||
} else if let Some(digits) = part.strip_prefix("uni").filter(|h| hex(h)) {
|
||||
// A group short of four digits isn't there to take, so `uni041` gives `None`.
|
||||
for i in (0..digits.len()).step_by(4) {
|
||||
let unit = digits.get(i..i.saturating_add(4))?;
|
||||
out.push(char::from_u32(u32::from_str_radix(unit, 16).ok()?)?);
|
||||
}
|
||||
} else {
|
||||
let digits = part
|
||||
.strip_prefix('u')
|
||||
.filter(|h| (4..=6).contains(&h.len()) && hex(h))?;
|
||||
out.push(char::from_u32(u32::from_str_radix(digits, 16).ok()?)?);
|
||||
}
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
pub(crate) fn read_widths(dict: &Dict<'_>, descriptor: &Dict<'_>) -> Option<(Vec<Width>, f32)> {
|
||||
let mut widths = Vec::new();
|
||||
|
||||
@@ -601,3 +676,53 @@ pub(crate) fn read_encoding(dict: &Dict<'_>) -> (Encoding, HashMap<u8, String>)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::glyph_name_text;
|
||||
|
||||
/// PdfCraft patch (79): glyph names read by the glyph list specification's rules.
|
||||
#[test]
|
||||
fn glyph_names_read_by_the_adobe_glyph_list_rules() {
|
||||
for (name, expected) in [
|
||||
("a", "a"),
|
||||
("a.ss01", "a"),
|
||||
("less_equal.liga", "<="),
|
||||
("uni0041", "A"),
|
||||
("uni00410042", "AB"),
|
||||
("u0041", "A"),
|
||||
("u1F600", "\u{1F600}"),
|
||||
] {
|
||||
assert_eq!(glyph_name_text(name).as_deref(), Some(expected), "{name}");
|
||||
}
|
||||
for name in [
|
||||
"",
|
||||
".notdef",
|
||||
".alt",
|
||||
"EMquad",
|
||||
"uni041",
|
||||
"uni00410",
|
||||
"uni004G",
|
||||
"uni+041",
|
||||
"u+041",
|
||||
"uniD800",
|
||||
"u041",
|
||||
"u0000041",
|
||||
"u004G",
|
||||
"a_EMquad",
|
||||
// PdfCraft patch (79): the glyph list specification's hex digits are uppercase only.
|
||||
"uni20ac",
|
||||
"uni004100e9",
|
||||
"u1f600",
|
||||
"u20ac",
|
||||
"a_uni20ac",
|
||||
"uni65",
|
||||
"u65",
|
||||
"uni+065",
|
||||
"uDFFF",
|
||||
"u110000",
|
||||
] {
|
||||
assert_eq!(glyph_name_text(name), None, "{name}");
|
||||
}
|
||||
}
|
||||
}
|
||||
+62
-13
@@ -1,11 +1,12 @@
|
||||
use crate::{BlendMode, FillRule};
|
||||
use crate::color::{ColorSpace, DefaultColorSpaces, DeviceFamily};
|
||||
use crate::context::Context;
|
||||
use crate::convert::{convert_line_cap, convert_line_join};
|
||||
use crate::convert::{convert_dash_array, convert_line_cap, convert_line_join, convert_line_width};
|
||||
use crate::device::Device;
|
||||
use crate::font::{Font, FontData, FontQuery, StandardFont};
|
||||
use crate::interpret::path::{
|
||||
apply_pending_clip, close_path, fill_path, fill_path_impl, fill_stroke_path, stroke_path,
|
||||
apply_pending_clip, begin_subpath_after_close, close_path, fill_path, fill_path_impl,
|
||||
fill_stroke_path, stroke_path,
|
||||
};
|
||||
use crate::interpret::state::{TextStateFont, handle_gs};
|
||||
use crate::interpret::text::TextRenderingMode;
|
||||
@@ -111,6 +112,11 @@ pub struct InterpreterSettings {
|
||||
/// PdfCraft patch: viewer overrides for optional content groups (object number, generation,
|
||||
/// visible), applied on top of the document's default configuration (Layers panel toggles).
|
||||
pub ocg_overrides: Arc<Vec<(i32, i32, bool)>>,
|
||||
/// PdfCraft patch (103): apply the default configuration's auto state for the View event
|
||||
/// (`/AS` usage applications with `/Event /View`, ISO 32000-2 §8.11.4.4) before
|
||||
/// `ocg_overrides`. On by default: that is the state for viewing. Off for output made for
|
||||
/// printing, which the View event is not.
|
||||
pub view_auto_state: bool,
|
||||
/// PdfCraft patch: once this is `true`, interpretation stops before the next content
|
||||
/// operator. What was drawn is then incomplete, so only set it when the output will be
|
||||
/// thrown away (a viewer's render whose result nobody can receive any more).
|
||||
@@ -144,6 +150,7 @@ impl Default for InterpreterSettings {
|
||||
render_annotations: true,
|
||||
hide_comments: false,
|
||||
ocg_overrides: Arc::new(Vec::new()),
|
||||
view_auto_state: true,
|
||||
cancelled: None,
|
||||
preview: false,
|
||||
jbig2_work: hayro_syntax::MAX_PAGE_JBIG2_WORK,
|
||||
@@ -166,6 +173,11 @@ pub enum InterpreterWarning {
|
||||
/// read, or a Separation or DeviceN tint transform that cannot be evaluated) and was painted
|
||||
/// in a fallback colour. Reported at most once per content stream.
|
||||
ColorFallback,
|
||||
/// PdfCraft patch (80): an image's `/Indexed` colour space is malformed (ISO 32000-2
|
||||
/// §8.6.6.3). The image was drawn recovered (indices past a short lookup table in black, a
|
||||
/// `hival` past 255 taken as 255, a real one truncated), or, with a `hival` below zero or not a
|
||||
/// number, in DeviceGray; with no lookup table at all it was not drawn.
|
||||
MalformedIndexedImage,
|
||||
/// PdfCraft patch (90): a Type 3 font without `/Widths` (or `/FirstChar`/`/LastChar`),
|
||||
/// which ISO 32000-2 Table 110 requires, was selected; its glyphs advance by the widths
|
||||
/// their glyph procedures set with `d0`/`d1`. Reported each time such a font is selected.
|
||||
@@ -531,7 +543,9 @@ fn interpret_window<'a>(
|
||||
context.get_mut().graphics_state.stroke_pattern = None;
|
||||
}
|
||||
TypedInstruction::LineWidth(w) => {
|
||||
context.get_mut().graphics_state.stroke_props.line_width = w.0.as_f32();
|
||||
// PdfCraft patch (61): see `convert_line_width`.
|
||||
context.get_mut().graphics_state.stroke_props.line_width =
|
||||
convert_line_width(w.0.as_f32());
|
||||
}
|
||||
TypedInstruction::LineCap(c) => {
|
||||
context.get_mut().graphics_state.stroke_props.line_cap = convert_line_cap(c);
|
||||
@@ -610,19 +624,20 @@ fn interpret_window<'a>(
|
||||
}
|
||||
TypedInstruction::LineTo(m) => {
|
||||
if !context.path().elements().is_empty() {
|
||||
let last_point = *context.last_point();
|
||||
let mut p = Point::new(m.0.as_f64(), m.1.as_f64());
|
||||
begin_subpath_after_close(context);
|
||||
// PdfCraft patch (61): a segment to the point it starts from is kept as it
|
||||
// is. Upstream nudged its end a ten-thousandth of a point to the right so
|
||||
// round caps drew a dot, which also gave butt and square caps a direction
|
||||
// to draw in; `stroke_path_impl` now handles degenerate subpaths.
|
||||
let p = Point::new(m.0.as_f64(), m.1.as_f64());
|
||||
*(context.last_point_mut()) = p;
|
||||
if last_point == p {
|
||||
// Add a small delta so that zero width lines can still have a round stroke.
|
||||
p.x += 0.0001;
|
||||
}
|
||||
|
||||
context.path_mut().line_to(p);
|
||||
}
|
||||
}
|
||||
TypedInstruction::CubicTo(c) => {
|
||||
if !context.path().elements().is_empty() {
|
||||
begin_subpath_after_close(context);
|
||||
let p1 = Point::new(c.0.as_f64(), c.1.as_f64());
|
||||
let p2 = Point::new(c.2.as_f64(), c.3.as_f64());
|
||||
let p3 = Point::new(c.4.as_f64(), c.5.as_f64());
|
||||
@@ -634,6 +649,7 @@ fn interpret_window<'a>(
|
||||
}
|
||||
TypedInstruction::CubicStartTo(c) => {
|
||||
if !context.path().elements().is_empty() {
|
||||
begin_subpath_after_close(context);
|
||||
let p1 = *context.last_point();
|
||||
let p2 = Point::new(c.0.as_f64(), c.1.as_f64());
|
||||
let p3 = Point::new(c.2.as_f64(), c.3.as_f64());
|
||||
@@ -645,6 +661,7 @@ fn interpret_window<'a>(
|
||||
}
|
||||
TypedInstruction::CubicEndTo(c) => {
|
||||
if !context.path().elements().is_empty() {
|
||||
begin_subpath_after_close(context);
|
||||
let p2 = Point::new(c.0.as_f64(), c.1.as_f64());
|
||||
let p3 = Point::new(c.2.as_f64(), c.3.as_f64());
|
||||
|
||||
@@ -695,11 +712,19 @@ fn interpret_window<'a>(
|
||||
// PdfCraft patch (38): see `named_color_space`.
|
||||
// PdfCraft patch (55): a space that cannot be read is drawn in DeviceGray, as
|
||||
// before, and the fallback is reported.
|
||||
// PdfCraft patch (80): an Indexed space with no lookup table counts as one that
|
||||
// cannot be read, as upstream.
|
||||
let cs = named_color_space(c.0, resources, &defaults, context)
|
||||
.filter(|cs| !cs.is_tableless_indexed())
|
||||
.unwrap_or_else(|| {
|
||||
crate::color::note_color_fallback();
|
||||
ColorSpace::device_gray()
|
||||
});
|
||||
// PdfCraft patch (80): so is an Indexed space drawn recovered (indices past a
|
||||
// short table drawn black, a `hival` clamped or truncated; see `Indexed::new`).
|
||||
if cs.is_recovered_indexed() {
|
||||
crate::color::note_color_fallback();
|
||||
}
|
||||
|
||||
if !cs.is_pattern() {
|
||||
context.get_mut().graphics_state.stroke_pattern = None;
|
||||
@@ -711,11 +736,19 @@ fn interpret_window<'a>(
|
||||
// PdfCraft patch (38): see `named_color_space`.
|
||||
// PdfCraft patch (55): a space that cannot be read is drawn in DeviceGray, as
|
||||
// before, and the fallback is reported.
|
||||
// PdfCraft patch (80): an Indexed space with no lookup table counts as one that
|
||||
// cannot be read, as upstream.
|
||||
let cs = named_color_space(c.0, resources, &defaults, context)
|
||||
.filter(|cs| !cs.is_tableless_indexed())
|
||||
.unwrap_or_else(|| {
|
||||
crate::color::note_color_fallback();
|
||||
ColorSpace::device_gray()
|
||||
});
|
||||
// PdfCraft patch (80): so is an Indexed space drawn recovered (indices past a
|
||||
// short table drawn black, a `hival` clamped or truncated; see `Indexed::new`).
|
||||
if cs.is_recovered_indexed() {
|
||||
crate::color::note_color_fallback();
|
||||
}
|
||||
|
||||
if !cs.is_pattern() {
|
||||
context.get_mut().graphics_state.non_stroke_pattern = None;
|
||||
@@ -725,11 +758,9 @@ fn interpret_window<'a>(
|
||||
}
|
||||
TypedInstruction::DashPattern(p) => {
|
||||
context.get_mut().graphics_state.stroke_props.dash_offset = p.1.as_f32();
|
||||
// kurbo apparently cannot properly deal with offsets that are exactly 0.
|
||||
// PdfCraft patch (61): see `convert_dash_array`.
|
||||
context.get_mut().graphics_state.stroke_props.dash_array =
|
||||
p.0.iter::<f32>()
|
||||
.map(|n| if n == 0.0 { 0.01 } else { n })
|
||||
.collect();
|
||||
convert_dash_array(p.0.iter::<f32>());
|
||||
}
|
||||
TypedInstruction::RenderingIntent(_) => {
|
||||
// Ignore for now.
|
||||
@@ -971,6 +1002,24 @@ fn interpret_window<'a>(
|
||||
let warning_sink = context.settings.warning_sink.clone();
|
||||
let transfer_function = context.get().graphics_state.transfer_function.clone();
|
||||
let cache = context.interpreter_cache.object_cache.clone();
|
||||
// PdfCraft patch (80): an inline image naming a resource colour space that is an
|
||||
// Indexed space whose `hival` has no reading is reported, as `ImageXObject::new`
|
||||
// reports one given in place; the image falls back as upstream. Only the array's
|
||||
// name and `hival` are read here, never its lookup table: a recovered space is
|
||||
// reported by `ImageXObject::new` from the space it builds through the resource
|
||||
// cache. A device space name (or its inline abbreviation) never refers to a
|
||||
// resource (ISO 32000-2 §8.6.8), and `ImageXObject::new` takes it first, so a
|
||||
// resource of that name is not consulted.
|
||||
let inline_dict = i.0.dict();
|
||||
if inline_dict
|
||||
.get::<hayro_syntax::object::Name<'_>>(hayro_syntax::object::dict::keys::CS)
|
||||
.or_else(|| inline_dict.get::<hayro_syntax::object::Name<'_>>(hayro_syntax::object::dict::keys::COLORSPACE))
|
||||
.filter(|name| ColorSpace::new_from_name(name).is_none())
|
||||
.and_then(|name| resources.get_color_space(&name))
|
||||
.is_some_and(|cs| crate::color::has_unusable_hival(&cs))
|
||||
{
|
||||
warning_sink(InterpreterWarning::MalformedIndexedImage);
|
||||
}
|
||||
// PdfCraft patch: inline images are not cached (see `DecodedImageKey`).
|
||||
// PdfCraft patch (38): an inline image in a device space, named directly or by a
|
||||
// resource, draws in its default.
|
||||
|
||||
+239
-9
@@ -3,8 +3,9 @@ use crate::context::{Context, path_as_rect};
|
||||
use crate::device::Device;
|
||||
use crate::util::{BezPathExt, Float32Ext};
|
||||
use crate::{BlendMode, FillRule, Paint, PathDrawMode, StrokeProps};
|
||||
use kurbo::{BezPath, Cap, Join, PathEl};
|
||||
use kurbo::{Affine, BezPath, Cap, Join, PathEl, Point, Rect, Vec2};
|
||||
use smallvec::smallvec;
|
||||
use std::borrow::Cow;
|
||||
|
||||
pub(crate) fn fill_path<'a>(
|
||||
context: &mut Context<'a>,
|
||||
@@ -92,22 +93,160 @@ pub(crate) fn apply_pending_clip<'a>(context: &mut Context<'a>, device: &mut imp
|
||||
if let Some(rule) = context.clip_mut().take()
|
||||
&& !context.path().elements().is_empty()
|
||||
{
|
||||
let clip_path = context.get().ctm * context.path().clone();
|
||||
context.push_clip_path(clip_path, rule, device);
|
||||
let ctm = context.get().ctm;
|
||||
// PdfCraft patch (65): a clip that encloses no area keeps the pixels a fill of it marks
|
||||
// (see `degenerate_fill_area`), as ISO 32000-2 §10.7.4 says of clipping: "the clipping
|
||||
// region consists of the set of pixels that would be included by a fill operation".
|
||||
match degenerate_fill_area(context.path(), ctm) {
|
||||
Some(area) => context.push_clip_path(area, FillRule::NonZero, device),
|
||||
None => {
|
||||
let clip_path = ctm * context.path().clone();
|
||||
context.push_clip_path(clip_path, rule, device);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// PdfCraft patch (65): the device-space area a fill marks for a path whose bounding box (user
|
||||
/// space) has exactly no width or exactly no height, but not both, under `ctm`: one area per
|
||||
/// subpath (see `degenerate_line_area`), kept as separate subpaths of one path, so a gap between
|
||||
/// two subpaths on the same line stays unpainted (ISO 32000-2 §10.7.4 marks only the pixels the
|
||||
/// shape touches). Every area winds the same way, so the non-zero rule paints their union. `None`
|
||||
/// for a path with area, a path that is a point, or one none of whose subpaths is a line: those
|
||||
/// paint as before.
|
||||
pub(crate) fn degenerate_fill_area(path: &BezPath, ctm: Affine) -> Option<BezPath> {
|
||||
let bbox = path.fast_bounding_box();
|
||||
if (bbox.width() == 0.0) == (bbox.height() == 0.0) {
|
||||
return None;
|
||||
}
|
||||
let mut area = BezPath::new();
|
||||
let mut add = |subpath: &BezPath| {
|
||||
if subpath.elements().is_empty() {
|
||||
return;
|
||||
}
|
||||
let Some(mut corners) = degenerate_line_area(subpath.fast_bounding_box(), ctm) else {
|
||||
return;
|
||||
};
|
||||
// Shoelace: wind every area the same way, so overlapping ones add up under non-zero.
|
||||
let twice_area: f64 = (0..4)
|
||||
.map(|i| {
|
||||
let (p, q) = (corners[i], corners[(i + 1) % 4]);
|
||||
p.x * q.y - q.x * p.y
|
||||
})
|
||||
.sum();
|
||||
if twice_area < 0.0 {
|
||||
corners.reverse();
|
||||
}
|
||||
area.move_to(corners[0]);
|
||||
for corner in &corners[1..] {
|
||||
area.line_to(*corner);
|
||||
}
|
||||
area.close_path();
|
||||
};
|
||||
let mut subpath = BezPath::new();
|
||||
for el in path.elements() {
|
||||
if matches!(el, PathEl::MoveTo(_)) {
|
||||
add(&subpath);
|
||||
subpath.truncate(0);
|
||||
}
|
||||
subpath.push(*el);
|
||||
}
|
||||
add(&subpath);
|
||||
(!area.elements().is_empty()).then_some(area)
|
||||
}
|
||||
|
||||
/// PdfCraft patch (65): the corners of the device-space area a fill marks for one subpath whose
|
||||
/// bounding box `bbox` (user space) has exactly no width or exactly no height, but not both,
|
||||
/// under `ctm`. ISO 32000-2 §10.7.4 paints "any pixel whose half-open square region intersects
|
||||
/// the shape, no matter how small the intersection is", and its example says "A zero-width or
|
||||
/// zero-height rectangle paints a line 1 pixel wide". Such a path encloses no area, so the
|
||||
/// rasteriser marks nothing: the fill used to fall back to a thinnest-line stroke along the box
|
||||
/// (half-covering two rows when the line fell on a pixel boundary), and a clip of it hid
|
||||
/// everything painted after it. A box with area, however thin, is not one of these: scaled up it
|
||||
/// can cover many pixels.
|
||||
///
|
||||
/// When the line stays within one device row or column (counting a line less than 1/256 of a
|
||||
/// pixel across as lying exactly along the axis, at its middle), the area is the run of whole
|
||||
/// pixels it touches, by the half-open rule: from the floor of its low end to the ceiling of its
|
||||
/// high end, at least one pixel. Otherwise (a rotated or skewed `ctm` that carries it across
|
||||
/// rows and columns) it is a band one device pixel wide centred on the line, like the thinnest
|
||||
/// line of §8.4.3.2, so each row or column is marked only where the line runs through it. `None`
|
||||
/// for a box with area, a point (both sides zero), a non-finite box, or a `ctm` that collapses
|
||||
/// the line to a point.
|
||||
fn degenerate_line_area(bbox: Rect, ctm: Affine) -> Option<[Point; 4]> {
|
||||
let flat_x = bbox.width() == 0.0;
|
||||
let flat_y = bbox.height() == 0.0;
|
||||
if flat_x == flat_y {
|
||||
return None;
|
||||
}
|
||||
let a = ctm * Point::new(bbox.x0, bbox.y0);
|
||||
let b = ctm * Point::new(bbox.x1, bbox.y1);
|
||||
if ![a.x, a.y, b.x, b.y].iter().all(|v| v.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
let along = b - a;
|
||||
let length = along.hypot();
|
||||
if !length.is_finite() || length <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
let device = Rect::from_points(a, b);
|
||||
let (x0, x1) = touched_pixels(device.x0, device.x1);
|
||||
let (y0, y1) = touched_pixels(device.y0, device.y1);
|
||||
if x1 - x0 <= 1.0 || y1 - y0 <= 1.0 {
|
||||
return Some([Point::new(x0, y0), Point::new(x1, y0), Point::new(x1, y1), Point::new(x0, y1)]);
|
||||
}
|
||||
let half = Vec2::new(-along.y, along.x) * (0.5 / length);
|
||||
Some([a + half, b + half, b - half, a - half])
|
||||
}
|
||||
|
||||
/// PdfCraft patch (65): the device pixel boundaries `(first, end)` of the pixels a span `lo..=hi`
|
||||
/// (`lo <= hi`, finite) touches along one axis by the half-open rule, at least one pixel. A span
|
||||
/// under 1/256 of a pixel is taken at its middle, so a line along a device axis that a CTM's
|
||||
/// rounding tilts slightly still marks one row or column.
|
||||
fn touched_pixels(lo: f64, hi: f64) -> (f64, f64) {
|
||||
let (lo, hi) = if ((hi - lo) as f32).is_nearly_zero() {
|
||||
let mid = lo + (hi - lo) / 2.0;
|
||||
(mid, mid)
|
||||
} else {
|
||||
(lo, hi)
|
||||
};
|
||||
let first = lo.floor();
|
||||
(first, hi.ceil().max(first + 1.0))
|
||||
}
|
||||
|
||||
pub(crate) fn close_path(context: &mut Context<'_>) {
|
||||
// This is necessary to prevent artifacts (see for example issue 157),
|
||||
// but it does cause some weird lines (maybe conflation artifacts) in
|
||||
// pdftc_900k_0907.
|
||||
if context.path().elements().last() != Some(&PathEl::ClosePath) && !context.path().is_empty() {
|
||||
//
|
||||
// PdfCraft patch (61): a path that is a single `m` is closed too. kurbo's `is_empty` counts
|
||||
// only segments, so upstream dropped the `h` of `x y m h`, and the single-point closed
|
||||
// subpath a round cap paints as a dot (ISO 32000-2 §8.5.3.2) became a trailing `m`, which
|
||||
// paints nothing.
|
||||
if context.path().elements().last() != Some(&PathEl::ClosePath)
|
||||
&& !context.path().elements().is_empty()
|
||||
{
|
||||
context.path_mut().close_path();
|
||||
|
||||
*(context.last_point_mut()) = *context.sub_path_start();
|
||||
}
|
||||
}
|
||||
|
||||
/// PdfCraft patch (61): call before appending a segment. ISO 32000-2 §8.5.2.1 (Table 58) says `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." kurbo
|
||||
/// takes a segment after a `ClosePath` on from the closed subpath's start without a `MoveTo`, so
|
||||
/// `resolve_degenerate_subpaths` saw the closed subpath and a degenerate one after it (`h` then an
|
||||
/// `l` to the same point) as one subpath and drew no round dot. A `MoveTo` to the point `h`
|
||||
/// reached starts the new subpath.
|
||||
pub(crate) fn begin_subpath_after_close(context: &mut Context<'_>) {
|
||||
if context.path().elements().last() == Some(&PathEl::ClosePath) {
|
||||
let p = *context.last_point();
|
||||
*(context.sub_path_start_mut()) = p;
|
||||
context.path_mut().move_to(p);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn fill_path_impl<'a>(
|
||||
context: &mut Context<'a>,
|
||||
device: &mut impl Device<'a>,
|
||||
@@ -128,10 +267,22 @@ pub(crate) fn fill_path_impl<'a>(
|
||||
// pdf.js issue 4260: Replace zero-sized paths with a small stroke instead.
|
||||
let bbox = path.fast_bounding_box();
|
||||
|
||||
match (
|
||||
(bbox.width() as f32).is_nearly_zero(),
|
||||
(bbox.height() as f32).is_nearly_zero(),
|
||||
) {
|
||||
// PdfCraft patch (65): see `degenerate_fill_area`. Painted with the non-zero rule: the
|
||||
// area is one simple shape, whatever rule the path was filled with.
|
||||
if let Some(area) = degenerate_fill_area(path, base_transform) {
|
||||
let draw_mode = PathDrawMode::Fill(FillRule::NonZero);
|
||||
if let Some(rect) = path_as_rect(&area) {
|
||||
device.draw_rect(&rect, Affine::IDENTITY, &paint, &draw_mode);
|
||||
} else {
|
||||
device.draw_path(&area, Affine::IDENTITY, &paint, &draw_mode);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// PdfCraft patch (65): only a box with exactly no width or height (by now a point) is
|
||||
// stroked. A box with area, however thin, is filled as the shape it is: a "nearly zero"
|
||||
// side scaled up by the CTM can cover many device pixels.
|
||||
match (bbox.width() == 0.0, bbox.height() == 0.0) {
|
||||
(false, false) => {
|
||||
let draw_mode = PathDrawMode::Fill(fill_rule);
|
||||
if let Some(rect) = path_as_rect(path) {
|
||||
@@ -185,7 +336,16 @@ pub(crate) fn stroke_path_impl<'a>(
|
||||
device.set_blend_mode(context.get().graphics_state.blend_mode);
|
||||
let paint = get_paint(context, true);
|
||||
|
||||
let path = path.unwrap_or(context.path());
|
||||
// PdfCraft patch (61): see `resolve_degenerate_subpaths`.
|
||||
let path = resolve_degenerate_subpaths(
|
||||
path.unwrap_or(context.path()),
|
||||
stroke_props.line_cap,
|
||||
stroke_props.line_width,
|
||||
);
|
||||
let path = path.as_ref();
|
||||
if path.elements().is_empty() {
|
||||
return;
|
||||
}
|
||||
let draw_mode = PathDrawMode::Stroke(stroke_props);
|
||||
|
||||
if let Some(rect) = path_as_rect(path) {
|
||||
@@ -195,6 +355,76 @@ pub(crate) fn stroke_path_impl<'a>(
|
||||
}
|
||||
}
|
||||
|
||||
/// PdfCraft patch (61): `path` as `S` strokes it, by ISO 32000-2 §8.5.3.2: "If a subpath is
|
||||
/// degenerate (consists of a single-point closed path or of two or more points at the same
|
||||
/// coordinates), the S operator shall paint it only if round line caps have been specified,
|
||||
/// producing a filled circle centred at the single point." With butt or projecting square caps
|
||||
/// it "shall produce no output". So with round caps a degenerate subpath becomes a segment
|
||||
/// centred on its point, a thousandth of the line width long (kurbo draws no cap on a segment of
|
||||
/// length zero), and is left out for the other caps. The other subpaths, and zero-length dashes
|
||||
/// of them, are not touched. Borrowed when nothing changes.
|
||||
pub(crate) fn resolve_degenerate_subpaths(
|
||||
path: &BezPath,
|
||||
cap: Cap,
|
||||
line_width: f32,
|
||||
) -> Cow<'_, BezPath> {
|
||||
let elements = path.elements();
|
||||
if !subpaths(elements).any(|sub| degenerate_point(sub).is_some()) {
|
||||
return Cow::Borrowed(path);
|
||||
}
|
||||
let mut out = BezPath::new();
|
||||
for sub in subpaths(elements) {
|
||||
match degenerate_point(sub) {
|
||||
Some(p) if cap == Cap::Round => {
|
||||
// A hairline (width 0) is widened by the device, so it keeps a length kurbo still
|
||||
// caps; an enormous width keeps the segment within half a unit.
|
||||
let half = (f64::from(line_width) * 5e-4).max(5e-5).min(0.5);
|
||||
out.move_to((p.x - half, p.y));
|
||||
out.line_to((p.x + half, p.y));
|
||||
}
|
||||
Some(_) => {}
|
||||
None => sub.iter().for_each(|el| out.push(*el)),
|
||||
}
|
||||
}
|
||||
Cow::Owned(out)
|
||||
}
|
||||
|
||||
/// The subpaths of `elements`: each starts at a `MoveTo`, except perhaps the first.
|
||||
fn subpaths(elements: &[PathEl]) -> impl Iterator<Item = &[PathEl]> {
|
||||
let mut rest = elements;
|
||||
std::iter::from_fn(move || {
|
||||
if rest.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let end = rest
|
||||
.iter()
|
||||
.skip(1)
|
||||
.position(|el| matches!(el, PathEl::MoveTo(_)))
|
||||
.map_or(rest.len(), |i| i.saturating_add(1));
|
||||
let (sub, tail) = rest.split_at_checked(end).unwrap_or((rest, &[]));
|
||||
rest = tail;
|
||||
Some(sub)
|
||||
})
|
||||
}
|
||||
|
||||
/// The point a degenerate subpath stays at: one that starts with a `MoveTo` and has at least one
|
||||
/// segment or a `ClosePath`, every point of which (control points too) is the start point. A lone
|
||||
/// `MoveTo` (a trailing `m`) is not one: it paints nothing whatever the caps.
|
||||
fn degenerate_point(sub: &[PathEl]) -> Option<Point> {
|
||||
let (PathEl::MoveTo(start), rest) = sub.split_first()? else {
|
||||
return None;
|
||||
};
|
||||
let at = |p: &Point| p == start;
|
||||
let degenerate = !rest.is_empty()
|
||||
&& rest.iter().all(|el| match el {
|
||||
PathEl::MoveTo(p) | PathEl::LineTo(p) => at(p),
|
||||
PathEl::QuadTo(a, b) => at(a) && at(b),
|
||||
PathEl::CurveTo(a, b, c) => at(a) && at(b) && at(c),
|
||||
PathEl::ClosePath => true,
|
||||
});
|
||||
degenerate.then_some(*start)
|
||||
}
|
||||
|
||||
pub(crate) fn get_paint<'a>(context: &Context<'a>, is_stroke: bool) -> Paint<'a> {
|
||||
let data = if is_stroke {
|
||||
context.get().stroke_data()
|
||||
|
||||
+9
-7
@@ -1,7 +1,7 @@
|
||||
use crate::StrokeProps;
|
||||
use crate::color::{AlphaColor, ColorComponents, ColorSpace};
|
||||
use crate::context::Context;
|
||||
use crate::convert::{convert_line_cap, convert_line_join};
|
||||
use crate::convert::{convert_dash_array, convert_line_cap, convert_line_join, convert_line_width};
|
||||
use crate::font::{Font, UNITS_PER_EM};
|
||||
use crate::function::Function;
|
||||
use crate::interpret::text::TextRenderingMode;
|
||||
@@ -319,7 +319,11 @@ pub(crate) fn handle_gs_single<'a>(
|
||||
) -> Option<()> {
|
||||
// TODO Can we use constants here somehow?
|
||||
match key.as_str() {
|
||||
"LW" => context.get_mut().graphics_state.stroke_props.line_width = dict.get::<f32>(key)?,
|
||||
// PdfCraft patch (61): see `convert_line_width`.
|
||||
"LW" => {
|
||||
context.get_mut().graphics_state.stroke_props.line_width =
|
||||
convert_line_width(dict.get::<f32>(key)?);
|
||||
}
|
||||
"LC" => {
|
||||
context.get_mut().graphics_state.stroke_props.line_cap =
|
||||
convert_line_cap(LineCap(dict.get::<Number>(key)?));
|
||||
@@ -402,11 +406,9 @@ pub(crate) fn handle_gs_single<'a>(
|
||||
let dash_phase = iter.next()?.into_number()?.as_f32();
|
||||
|
||||
context.get_mut().graphics_state.stroke_props.dash_offset = dash_phase;
|
||||
context.get_mut().graphics_state.stroke_props.dash_array = dash_array
|
||||
.iter::<f32>()
|
||||
// kurbo apparently cannot properly deal with offsets that are exactly 0.
|
||||
.map(|n| if n == 0.0 { 0.01 } else { n })
|
||||
.collect();
|
||||
// PdfCraft patch (61): see `convert_dash_array`.
|
||||
context.get_mut().graphics_state.stroke_props.dash_array =
|
||||
convert_dash_array(dash_array.iter::<f32>());
|
||||
}
|
||||
"Type" => {}
|
||||
_ => {}
|
||||
|
||||
Vendored
+94
-3
@@ -1,6 +1,9 @@
|
||||
use hayro_syntax::object::dict::keys::{BASE_STATE, D, OCGS, OCMD, OCPROPERTIES, OFF, ON, P, TYPE, VE};
|
||||
use hayro_syntax::object::dict::keys::{
|
||||
AS, BASE_STATE, D, OCGS, OCMD, OCPROPERTIES, OFF, ON, P, TYPE, USAGE, VE, VIEW, VIEW_STATE,
|
||||
};
|
||||
use hayro_syntax::object::{Array, Dict, MaybeRef, Name, Object, ObjectIdentifier};
|
||||
use std::collections::HashSet;
|
||||
use hayro_syntax::xref::XRef;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
pub(crate) struct OcgState {
|
||||
inactive_ocgs: HashSet<ObjectIdentifier>,
|
||||
@@ -30,7 +33,10 @@ impl OcgState {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn from_catalog(catalog: &Dict<'_>) -> Self {
|
||||
/// The groups' states as the document opens: the default configuration (`/BaseState`, then
|
||||
/// `/ON` and `/OFF`), then, when `view_auto_state` is set (PdfCraft patch (103)), the auto
|
||||
/// state its `/AS` array gives for the View event ([`apply_view_auto_state`]).
|
||||
pub(crate) fn from_catalog(catalog: &Dict<'_>, xref: &XRef, view_auto_state: bool) -> Self {
|
||||
let Some(oc_properties) = catalog.get::<Dict<'_>>(OCPROPERTIES) else {
|
||||
return Self::dummy();
|
||||
};
|
||||
@@ -83,6 +89,10 @@ impl OcgState {
|
||||
read_ocg_array(ON, true);
|
||||
read_ocg_array(OFF, false);
|
||||
|
||||
if view_auto_state {
|
||||
apply_view_auto_state(&config, xref, &mut inactive);
|
||||
}
|
||||
|
||||
Self {
|
||||
inactive_ocgs: inactive,
|
||||
known_ocgs: known,
|
||||
@@ -213,6 +223,87 @@ impl Default for OcgState {
|
||||
}
|
||||
}
|
||||
|
||||
/// PdfCraft patch (103): at most this many usage application dictionaries of an `/AS` array are
|
||||
/// read; the rest are ignored.
|
||||
const MAX_AUTO_STATE_APPLICATIONS: usize = 256;
|
||||
/// PdfCraft patch (103): at most this many `/OCGs` entries are read across all of them.
|
||||
const MAX_AUTO_STATE_GROUPS: usize = 4096;
|
||||
/// PdfCraft patch (103): at most this many `/Category` names are read per application.
|
||||
const MAX_AUTO_STATE_CATEGORIES: usize = 16;
|
||||
|
||||
/// PdfCraft patch (103): apply the configuration's auto state for the View event (ISO 32000-2
|
||||
/// §8.11.4.4, Tables 99 and 101). For each usage application dictionary in `/AS` whose `/Event`
|
||||
/// is `/View`, each group in its `/OCGs` gets a recommended state from each category in its
|
||||
/// `/Category` that the group's `/Usage` gives one for. A group is ON only if every
|
||||
/// recommendation it receives, across all such dictionaries, is ON, and OFF otherwise; a group
|
||||
/// that receives none keeps its configured state.
|
||||
///
|
||||
/// Only the `/View` category (`/ViewState`) is evaluated. `/Zoom`, `/User` and `/Language` need
|
||||
/// the magnification, user and locale, which the interpreter doesn't know, so they give no
|
||||
/// recommendation. Malformed entries (not a dictionary, no `/Category`, a `/ViewState` other
|
||||
/// than ON or OFF) are skipped, and the walk is bounded by the caps above.
|
||||
fn apply_view_auto_state(config: &Dict<'_>, xref: &XRef, inactive: &mut HashSet<ObjectIdentifier>) {
|
||||
let Some(applications) = config.get::<Array<'_>>(AS) else {
|
||||
return;
|
||||
};
|
||||
let mut recommended: HashMap<ObjectIdentifier, bool> = HashMap::new();
|
||||
let mut groups_left = MAX_AUTO_STATE_GROUPS;
|
||||
for application in applications.raw_iter().take(MAX_AUTO_STATE_APPLICATIONS) {
|
||||
let application = match application {
|
||||
MaybeRef::Ref(r) => xref.get::<Dict<'_>>(r.into()),
|
||||
MaybeRef::NotRef(Object::Dict(d)) => Some(d),
|
||||
MaybeRef::NotRef(_) => None,
|
||||
};
|
||||
let Some(application) = application else {
|
||||
continue;
|
||||
};
|
||||
if application.get::<Name<'_>>(b"Event").as_deref() != Some(VIEW) {
|
||||
continue;
|
||||
}
|
||||
let views = application.get::<Array<'_>>(b"Category").is_some_and(|categories| {
|
||||
categories
|
||||
.raw_iter()
|
||||
.take(MAX_AUTO_STATE_CATEGORIES)
|
||||
.any(|c| matches!(c, MaybeRef::NotRef(Object::Name(n)) if n.as_ref() == VIEW))
|
||||
});
|
||||
if !views {
|
||||
continue;
|
||||
}
|
||||
let Some(groups) = application.get::<Array<'_>>(OCGS) else {
|
||||
continue;
|
||||
};
|
||||
for group in groups.raw_iter() {
|
||||
if groups_left == 0 {
|
||||
break;
|
||||
}
|
||||
groups_left -= 1;
|
||||
let Some(r) = group.as_obj_ref() else {
|
||||
continue;
|
||||
};
|
||||
let id: ObjectIdentifier = r.into();
|
||||
let state = xref
|
||||
.get::<Dict<'_>>(id)
|
||||
.and_then(|g| g.get::<Dict<'_>>(USAGE))
|
||||
.and_then(|u| u.get::<Dict<'_>>(VIEW))
|
||||
.and_then(|v| v.get::<Name<'_>>(VIEW_STATE));
|
||||
let on = match state.as_deref() {
|
||||
Some(ON) => true,
|
||||
Some(OFF) => false,
|
||||
_ => continue,
|
||||
};
|
||||
let entry = recommended.entry(id).or_insert(true);
|
||||
*entry &= on;
|
||||
}
|
||||
}
|
||||
for (id, on) in recommended {
|
||||
if on {
|
||||
inactive.remove(&id);
|
||||
} else {
|
||||
inactive.insert(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// PdfCraft patch (40): how deep visibility expressions may nest; deeper ones are malformed.
|
||||
const MAX_VISIBILITY_EXPRESSION_DEPTH: usize = 32;
|
||||
|
||||
|
||||
+29
-1
@@ -526,6 +526,7 @@ impl<'a> ImageXObject<'a> {
|
||||
is_mask |= is_stencil_mask;
|
||||
|
||||
let mut default_space = None;
|
||||
let mut malformed_indexed = false;
|
||||
let image_cs = if is_mask {
|
||||
// Masks are always single-channel.
|
||||
Some(ColorSpace::device_gray())
|
||||
@@ -543,9 +544,14 @@ impl<'a> ImageXObject<'a> {
|
||||
default_space = Some(key);
|
||||
Some(space)
|
||||
} else {
|
||||
// PdfCraft patch (80): an Indexed space given in place whose `hival` has no
|
||||
// reading cannot be built and falls back below, as upstream; it is reported.
|
||||
malformed_indexed = cs_obj
|
||||
.as_ref()
|
||||
.is_some_and(crate::color::has_unusable_hival);
|
||||
cs_obj
|
||||
.clone()
|
||||
.and_then(|c| ColorSpace::new(c, cache))
|
||||
.and_then(|c| ColorSpace::new_allowing_tableless(c, cache))
|
||||
// Inline images can also refer to color spaces by name.
|
||||
.or_else(|| {
|
||||
cs_obj
|
||||
@@ -554,6 +560,24 @@ impl<'a> ImageXObject<'a> {
|
||||
})
|
||||
}
|
||||
};
|
||||
// PdfCraft patch (80): an Indexed space that ISO 32000-2 §8.6.6.3 rules out (a short
|
||||
// lookup table, a `hival` past 255 or with a fraction) is drawn recovered (see
|
||||
// `Indexed::new`), and reported. The check asks the space that was built, so it reads
|
||||
// no lookup table of its own (an inline image naming a resource builds it once, through
|
||||
// the resource cache).
|
||||
malformed_indexed |= image_cs
|
||||
.as_ref()
|
||||
.is_some_and(ColorSpace::is_recovered_indexed);
|
||||
// PdfCraft patch (80): an Indexed space with no lookup table at all (missing, or not a
|
||||
// string or a stream that decodes) leaves nothing to draw: the image is skipped, and
|
||||
// reported. Upstream drew it in DeviceGray.
|
||||
if image_cs
|
||||
.as_ref()
|
||||
.is_some_and(ColorSpace::is_tableless_indexed)
|
||||
{
|
||||
warning_sink(InterpreterWarning::MalformedIndexedImage);
|
||||
return None;
|
||||
}
|
||||
|
||||
let interpolate = dict
|
||||
.get::<bool>(I)
|
||||
@@ -567,6 +591,10 @@ impl<'a> ImageXObject<'a> {
|
||||
return None;
|
||||
}
|
||||
|
||||
if malformed_indexed {
|
||||
warning_sink(InterpreterWarning::MalformedIndexedImage);
|
||||
}
|
||||
|
||||
Some(Self {
|
||||
width,
|
||||
cache: cache.clone(),
|
||||
|
||||
Reference in new issue
Block a user