diff --git a/Cargo.lock b/Cargo.lock index b8e1b6cba9..9072b1042e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2591,8 +2591,6 @@ dependencies = [ [[package]] name = "hayro-postscript" version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "885c5ef0654933139a9b9546fc2c69e18d37f38aa2520f079092b1be18f1fcaa" [[package]] name = "hayro-syntax" diff --git a/Cargo.toml b/Cargo.toml index 2714debb62..e7acfd31f9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -115,6 +115,7 @@ hayro-interpret = { path = "vendor/hayro-interpret" } hayro = { path = "vendor/hayro" } hayro-syntax = { path = "vendor/hayro-syntax" } hayro-cmap = { path = "vendor/hayro-cmap" } +hayro-postscript = { path = "vendor/hayro-postscript" } hayro-jbig2 = { path = "vendor/hayro-jbig2" } lopdf = { path = "vendor/lopdf" } winit = { path = "vendor/winit" } diff --git a/contributors/people.toml b/contributors/people.toml index 4f2b22775c..dd75a07314 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -176,3 +176,7 @@ real_name = "Nick Nyssen" [people.agent-reed] sync_github_name = true + +[people.dotCooCoo] +real_name = "Robert Lee" +sync_github_name = true diff --git a/crates/a11y/src/alt.rs b/crates/a11y/src/alt.rs index 87cfce5acb..720b8a6a1e 100644 --- a/crates/a11y/src/alt.rs +++ b/crates/a11y/src/alt.rs @@ -211,6 +211,25 @@ fn close(marks: &mut Vec, matching: &mut usize, out: &mut HashMap Option<[f64; 4]> { + let r = op.name(0).and_then(|n| xobjects.get(n)).and_then(Object::as_ref)?; + Some(match &*doc.get(r) { + Object::Stream(s) if s.dict.name(b"Subtype") == Some(b"Form") => { + let bb: Vec = + s.dict.get(b"BBox").and_then(|b| b.as_array().map(|a| a.iter().filter_map(Object::as_f64).collect())).unwrap_or_default(); + let m = Matrix::from_operands(s.dict.get(b"Matrix").and_then(|m| m.as_array()).map(Vec::as_slice).unwrap_or(&[])) + .unwrap_or(Matrix([1.0, 0.0, 0.0, 1.0, 0.0, 0.0])); + match bb[..] { + [a, b, c, d] => m.then(top).bbox([a, b, c, d]), + _ => return None, + } + } + _ => top.bbox([0.0, 0.0, 1.0, 1.0]), + }) +} + /// Where each of the marked content `ids` is drawn on a page (images, forms and paths), in one pass /// over the page. What a sequence draws counts for every sequence of `ids` around it too. pub(crate) fn content_bboxes(doc: &Document, page: &Dict, ids: &HashSet) -> HashMap { @@ -274,20 +293,7 @@ pub(crate) fn content_bboxes(doc: &Document, page: &Dict, ids: &HashSet) -> path.clear(); } b"Do" if inside => { - let Some(r) = op.name(0).and_then(|n| xobjects.get(n)).and_then(Object::as_ref) else { continue }; - let unit = match &*doc.get(r) { - Object::Stream(s) if s.dict.name(b"Subtype") == Some(b"Form") => { - let bb: Vec = - s.dict.get(b"BBox").and_then(|b| b.as_array().map(|a| a.iter().filter_map(Object::as_f64).collect())).unwrap_or_default(); - let m = Matrix::from_operands(s.dict.get(b"Matrix").and_then(|m| m.as_array()).map(Vec::as_slice).unwrap_or(&[])) - .unwrap_or(Matrix([1.0, 0.0, 0.0, 1.0, 0.0, 0.0])); - match bb[..] { - [a, b, c, d] => m.then(&top).bbox([a, b, c, d]), - _ => continue, - } - } - _ => top.bbox([0.0, 0.0, 1.0, 1.0]), - }; + let Some(unit) = xobject_bbox(doc, &xobjects, &op, &top) else { continue }; draw(&mut marks, unit); } b"BI" if inside => draw(&mut marks, top.bbox([0.0, 0.0, 1.0, 1.0])), diff --git a/crates/a11y/src/autotag.rs b/crates/a11y/src/autotag.rs index 4462025cf5..9b65f6972b 100644 --- a/crates/a11y/src/autotag.rs +++ b/crates/a11y/src/autotag.rs @@ -132,6 +132,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, AutoTagError> { + let mut start = None; + let mut has_text = false; + let mut spans = Vec::new(); + for (at, op) in ops.iter().enumerate() { + match op.op.as_slice() { + b"BT" if start.is_none() => { + start = Some(at); + has_text = false; + } + b"ET" => { + let Some(first) = start.take() else { return Err(unsupported(index, "unmatched ET operator")) }; + if has_text { + spans.push((first, at)); + if spans.len() > MAX_TEXT_OBJECTS { + return Err(unsupported(index, "too many text objects (maximum 4096)")); + } + } + } + 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) => {} + _ => 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) +} + fn plan(doc: &Document) -> Result, AutoTagError> { let root = doc.root().ok_or(AutoTagError::NoCatalog)?; let catalog = doc.get(root); @@ -163,33 +195,7 @@ fn plan(doc: &Document) -> Result, AutoTagError> { if parsed.skipped > 0 || parsed.ops.len() > MAX_OPERATORS { return Err(unsupported(index, "content has malformed or too many operators")); } - let mut start = None; - let mut has_text = false; - let mut spans = Vec::new(); - for (at, op) in parsed.ops.iter().enumerate() { - match op.op.as_slice() { - b"BT" if start.is_none() => { - start = Some(at); - has_text = false; - } - b"ET" => { - let Some(first) = start.take() else { return Err(unsupported(index, "unmatched ET operator")) }; - if has_text { - spans.push((first, at)); - if spans.len() > MAX_TEXT_OBJECTS { - return Err(unsupported(index, "too many text objects (maximum 4096)")); - } - } - } - 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) => {} - _ => 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")); - } + let spans = text_spans(&parsed.ops, index)?; total = total.saturating_add(spans.len()); out.push(Plan { page: page.obj, ops: parsed.ops, spans }); } diff --git a/crates/annot/README.md b/crates/annot/README.md index 55df6d1a75..8108201835 100644 --- a/crates/annot/README.md +++ b/crates/annot/README.md @@ -9,10 +9,12 @@ Comments (annotations), ISO 32000-2 §12.5. Layer L3, depends on `pdfcraft-cos`, line and arrow (`Line` with `/LE`), freehand drawing (`Ink`) and text box (`FreeText`). - **Appearance streams** (`appearance::build`) generated from the annotation dictionary, so new and restyled comments look the same in every viewer. Highlights multiply (`/BM /Multiply`). + A line's leader lines (`/LL`, `/LLE`, `/LLO`) and caption (`/Cap`, `/CP`, `/CO`) are drawn as + ISO 32000-2 Table 178 places them, the caption in black Helvetica 10. Note icons are PdfCraft's own drawings. Text boxes use standard Helvetica (WinAnsi), with line breaking by approximate Helvetica proportions (no font program is bundled). Text it can't - draw (in a text box, callout, Fill & Sign text, measurement label or dynamic stamp's by-line; - `appearance::undrawable_text`) is kept as typed and drawn as `?`, and the comment is marked with + draw (in a text box, callout, Fill & Sign text, line caption, measurement label or dynamic + stamp's by-line; `appearance::undrawable_text`) is kept as typed and drawn as `?`, and the comment is marked with the first such character (`pdfcraft_fonts::UNDRAWN_MARK`) so the engine reports the edit and flattening refuses to make it permanent. Two refusals (`AnnotError::Undrawable`): a redaction mark's overlay text, which becomes page content when applied; and a restyle or resize of a diff --git a/crates/annot/src/appearance.rs b/crates/annot/src/appearance.rs index 436c49b35f..530438db6d 100644 --- a/crates/annot/src/appearance.rs +++ b/crates/annot/src/appearance.rs @@ -302,13 +302,14 @@ fn text_turn(d: &Dict) -> i64 { /// The first text [`build`] would draw in the standard fonts (Helvetica, WinAnsiEncoding) that /// they can't, which would come out as `?`: what it is (for the message) and the character. The -/// text of a text box, callout or Fill & Sign text, a measurement's label, a dynamic stamp's -/// "By …" line, and a redaction mark's overlay text (drawn when it is applied). `None` when all of +/// text of a text box, callout or Fill & Sign text, a line's caption, a measurement's label, a +/// dynamic stamp's "By …" line, and a redaction mark's overlay text (drawn when it is applied). `None` when all of /// it can be drawn. pub fn undrawable_text(d: &Dict) -> Option<(&'static str, char)> { let text = |key: &[u8]| d.get(key).and_then(Object::as_string).map(PdfString::to_text); let (what, text) = match d.name(b"Subtype")? { b"FreeText" => ("the comment's text", text(b"Contents")?), + b"Line" if !d.contains(b"PCMeasureValue") => ("the line's caption", line_caption(d)?), b"Line" | b"PolyLine" | b"Polygon" => ("the measurement label", text(b"PCMeasureValue")?), b"Stamp" if matches!(d.get(b"PCStamp"), Some(Object::Bool(true))) => ("the stamp's \"By\" line", text(b"PCByLine")?), // Drawn in Helvetica when the redaction is applied: refused when it is marked. @@ -389,6 +390,8 @@ pub fn build(d: &Dict) -> Option { let w = border_width(d); let mut res = Dict::new(); let mut c = String::new(); + // Content after `c` that isn't UTF-8 (WinAnsi text). + let mut tail: Vec = Vec::new(); let markup = matches!(subtype.as_slice(), b"Highlight" | b"Underline" | b"StrikeOut" | b"Squiggly"); if let Some(gs) = ext_gstate(opacity, subtype == b"Highlight") { res.set(b"ExtGState".to_vec(), Object::Dict(gs)); @@ -513,13 +516,29 @@ pub fn build(d: &Dict) -> Option { return None; } let fill = interior_color(d, Some(col)).unwrap_or(col); + let layout = line_layout(d, [(l[0], l[1]), (l[2], l[3])], w); + let [p, q] = layout.line; c.push_str(&format!("{}{}{} w 1 J 1 j\n{}", rg_stroke(col), rg(fill), n(w), dash(d))); - c.push_str(&format!("{} {} m {} {} l S\n[] 0 d\n", n(l[0]), n(l[1]), n(l[2]), n(l[3]))); - for (end, (tip, from)) in ends.iter().zip([((l[0], l[1]), (l[2], l[3])), ((l[2], l[3]), (l[0], l[1]))]) { + for [s, e] in layout.leaders.iter().chain(&layout.strokes).chain(&layout.tick) { + c.push_str(&format!("{} {} m {} {} l S\n", n(s.0), n(s.1), n(e.0), n(e.1))); + } + c.push_str("[] 0 d\n"); + for (end, (tip, from)) in ends.iter().zip([(p, q), (q, p)]) { if !line_end(&mut c, end, tip, from, w) { return None; } } + if let Some((text, m)) = layout.caption { + // The caption is black, in the standard font the measurement label uses. + tail.extend( + format!("q 0 g BT /Helv {} Tf {} {} {} {} {} {} Tm ", n(CAPTION_SIZE), n(m[0]), n(m[1]), n(m[2]), n(m[3]), n(m[4]), n(m[5])) + .bytes(), + ); + // WinAnsi bytes go into the stream as-is, not through UTF-8. + tail.extend(literal(&win_ansi(&text))); + tail.extend_from_slice(b" Tj ET Q\n"); + res.set(b"Font".to_vec(), helvetica_resource()); + } } b"Polygon" | b"PolyLine" => { let v = nums(d, b"Vertices").filter(|v| v.len() >= 4 && v.len() % 2 == 0 && v.iter().all(|x| x.is_finite()))?; @@ -866,6 +885,7 @@ pub fn build(d: &Dict) -> Option { // PdfCraft measurement captions are kept separate from the comment's free-form text. // A restyle regenerates the path and its value together. let mut out = c.into_bytes(); + out.extend(tail); if let Some(value) = d.get(b"PCMeasureValue").and_then(Object::as_string) { let value = value.to_text(); if value.chars().count() <= 256 && matches!(subtype.as_slice(), b"Line" | b"PolyLine" | b"Polygon") { @@ -969,6 +989,190 @@ pub(crate) fn display_stamp(d: &Dict) -> Option { Some(form(rect, c.as_bytes(), res)) } +/// Size of a line's caption, as of a measurement's label. +const CAPTION_SIZE: f64 = 10.0; + +/// Characters of a line's caption drawn at most, as for a measurement's label. +const MAX_CAPTION_CHARS: usize = 256; + +/// Leader lengths and caption offsets (Table 178) are held within this many points (200 inches, +/// the largest page side ISO 32000-2 Annex C allows), so an absurd value can't overflow. +const MAX_LINE_EXTENT: f64 = 14_400.0; + +/// A Table 178 length or offset: finite and within [`MAX_LINE_EXTENT`], 0 when absent or not one. +fn line_length(v: Option) -> f64 { + v.filter(|v| v.is_finite()).map_or(0.0, |v| v.clamp(-MAX_LINE_EXTENT, MAX_LINE_EXTENT)) +} + +/// The caption a Line with `/Cap true` shows (ISO 32000-2 Table 178): its `/Contents`, else the +/// plain text of its `/RC`, on one line and cut to [`MAX_CAPTION_CHARS`]. `None` without a +/// caption, and for PdfCraft's own measurements, whose label (`/PCMeasureValue`) is the caption. +fn line_caption(d: &Dict) -> Option { + if !matches!(d.get(b"Cap"), Some(Object::Bool(true))) || d.contains(b"PCMeasureValue") { + return None; + } + let text = |key: &[u8]| d.get(key).and_then(Object::as_string).map(PdfString::to_text); + let raw = text(b"Contents").filter(|t| !t.trim().is_empty()).or_else(|| text(b"RC").map(|rc| rich_plain(&rc)))?; + let words: Vec<&str> = raw.split_whitespace().collect(); + let caption: String = words.join(" ").chars().filter(|c| !c.is_control()).take(MAX_CAPTION_CHARS).collect(); + (!caption.is_empty()).then_some(caption) +} + +/// The text of rich text (§12.7.4.3, XHTML): its markup dropped, the five XML entities and +/// numeric character references read, block ends read as spaces. +fn rich_plain(rc: &str) -> String { + let mut out = String::new(); + let mut tag: Option = None; + // Rich text past this is not caption material; it bounds the work. + for ch in rc.chars().take(MAX_CAPTION_CHARS * 64) { + match (&mut tag, ch) { + (None, '<') => tag = Some(String::new()), + (Some(name), '>') => { + let name = + name.trim_start_matches('/').split(|c: char| c.is_whitespace() || c == '/').next().unwrap_or_default().to_ascii_lowercase(); + if matches!(name.as_str(), "p" | "br" | "div" | "li") { + out.push(' '); + } + tag = None; + } + (Some(name), c) => { + if name.len() < 16 { + name.push(c); + } + } + (None, c) => out.push(c), + } + } + let mut text = String::new(); + let mut rest = out.as_str(); + while let Some(at) = rest.find('&') { + text.push_str(rest.get(..at).unwrap_or_default()); + let after = rest.get(at + 1..).unwrap_or_default(); + let entity = after.find(';').filter(|&end| end <= 10).and_then(|end| Some((after.get(..end)?, end))); + let decoded = entity.and_then(|(name, end)| { + let c = match name { + "amp" => '&', + "lt" => '<', + "gt" => '>', + "quot" => '"', + "apos" => '\'', + _ => { + let num = name.strip_prefix('#')?; + let code = match num.strip_prefix(['x', 'X']) { + Some(hex) => u32::from_str_radix(hex, 16).ok()?, + None => num.parse().ok()?, + }; + char::from_u32(code)? + } + }; + Some((c, end)) + }); + match decoded { + Some((c, end)) => { + text.push(c); + rest = after.get(end + 1..).unwrap_or_default(); + } + None => { + text.push('&'); + rest = after; + } + } + } + text.push_str(rest); + text +} + +/// Where a Line annotation's parts go (ISO 32000-2 §12.5.6.7, Table 178). +#[derive(Debug, Default)] +struct LineLayout { + /// The line itself, start to end: `/L`, or `/L` moved out by its leader lines. + line: [(f64, f64); 2], + /// Strokes along the line: the whole line, or the two pieces either side of an inline caption. + strokes: Vec<[(f64, f64); 2]>, + /// The leader lines, from `/L` (past the `/LLO` gap) to the line and on by `/LLE`. + leaders: Vec<[(f64, f64); 2]>, + /// A short stroke from the line to a caption `/CO` moved off it. + tick: Option<[(f64, f64); 2]>, + /// The caption and its text matrix. + caption: Option<(String, [f64; 6])>, +} + +/// Lay out a Line annotation from `/L` = `[a b]`, line width `w`, and its leader and caption +/// entries. +/// +/// Leader lines: a positive `/LL` puts the line on the left of travel from `a` to `b` (above `/L` +/// for a line drawn left to right), so the leader lines, followed from the line to `/L`, turn +/// clockwise from the direction of travel; a negative one puts it on the right. The line sits +/// `|LL| + LLO` from `/L`. `/LLE` and `/LLO` are non-negative: a negative one counts as 0. +/// +/// Caption (`/Cap true`): centred on the line's midpoint and turned with it so it reads left to +/// right (bottom to top for a vertical line). `/CP /Inline` (the default) centres it on the line, +/// which is broken around it; `/Top` sets it on top of the unbroken line. `/CO [h v]` moves it `h` +/// along the line and `v` across it (positive: up in reading direction); a caption moved off an +/// inline line gets a tick from the line to it. +/// +/// A zero-length or overflowing `/L` has no direction: it gets neither leader lines nor caption. +/// Every point is finite; if anything derived from the entries is not, they are left out. +fn line_layout(d: &Dict, [a, b]: [(f64, f64); 2], w: f64) -> LineLayout { + let plain = LineLayout { line: [a, b], strokes: vec![[a, b]], ..LineLayout::default() }; + let (dx, dy) = (b.0 - a.0, b.1 - a.1); + let len = dx.hypot(dy); + if !len.is_finite() || len <= 0.0 { + return plain; + } + let (ux, uy) = (dx / len, dy / len); + let mut out = LineLayout { line: [a, b], ..LineLayout::default() }; + let ll = line_length(d.get(b"LL").and_then(Object::as_f64)); + if ll != 0.0 { + // The unit normal from `/L` towards the line: left of travel for a positive /LL. + let s = ll.signum(); + let (nx, ny) = (-uy * s, ux * s); + let llo = line_length(d.get(b"LLO").and_then(Object::as_f64)).max(0.0); + let lle = line_length(d.get(b"LLE").and_then(Object::as_f64)).max(0.0); + let at = |p: (f64, f64), k: f64| (p.0 + nx * k, p.1 + ny * k); + let off = ll.abs() + llo; + out.line = [at(a, off), at(b, off)]; + out.leaders = vec![[at(a, llo), at(a, off + lle)], [at(b, llo), at(b, off + lle)]]; + } + let [p, _] = out.line; + let along = |t: f64| (p.0 + ux * t, p.1 + uy * t); + let mut gap = None; + if let Some(text) = line_caption(d) { + let size = CAPTION_SIZE; + let width = text_width(&text, size); + // Reading direction, and "up" across it. + let (tx, ty) = if ux < 0.0 || (ux == 0.0 && uy < 0.0) { (-ux, -uy) } else { (ux, uy) }; + let (vx, vy) = (-ty, tx); + let co = nums(d, b"CO").filter(|c| c.len() == 2).unwrap_or_default(); + let h = line_length(co.first().copied()); + let v = line_length(co.get(1).copied()); + let top = d.name(b"CP") == Some(b"Top"); + // The caption's centre, as a distance along the line from `p`. + let centre = len / 2.0 + h * (tx * ux + ty * uy); + let mid = along(centre); + // Baseline across the line: on top of it, or with the text centred on it. + let base = if top { w.max(0.0) / 2.0 + 2.0 + v } else { v - size * 0.35 }; + let origin = (mid.0 - tx * width / 2.0 + vx * base, mid.1 - ty * width / 2.0 + vy * base); + out.caption = Some((text, [tx, ty, -ty, tx, origin.0, origin.1])); + if !top && v.abs() < size / 2.0 { + let half = width / 2.0 + 2.0; + gap = Some(((centre - half).clamp(0.0, len), (centre + half).clamp(0.0, len))); + } else if !top { + let reach = v - v.signum() * size * 0.4; + out.tick = Some([mid, (mid.0 + vx * reach, mid.1 + vy * reach)]); + } + } + out.strokes = match gap { + Some((g0, g1)) => [(0.0, g0), (g1, len)].into_iter().filter(|(s, e)| e > s).map(|(s, e)| [along(s), along(e)]).collect(), + None => vec![out.line], + }; + let finite = |q: &(f64, f64)| q.0.is_finite() && q.1.is_finite(); + let all_finite = + out.line.iter().chain(out.strokes.iter().flatten()).chain(out.leaders.iter().flatten()).chain(out.tick.iter().flatten()).all(finite) + && out.caption.as_ref().is_none_or(|(_, m)| m.iter().all(|x| x.is_finite())); + if all_finite { out } else { plain } +} + /// A rubber stamp: a rounded frame (a pointed tag for sign-here stamps) with the label in bold /// capitals, and the dynamic stamps' "By … at …" line. fn stamp(label: &str, sign_here: bool, rect: [f64; 4], col: Rgb, by: Option<&str>, opacity: f64, mut res: Dict) -> Stream { diff --git a/crates/annot/src/tests.rs b/crates/annot/src/tests.rs index c3602d8b57..4f0e0fb1fc 100644 --- a/crates/annot/src/tests.rs +++ b/crates/annot/src/tests.rs @@ -1867,3 +1867,230 @@ fn a_caret_with_a_paragraph_symbol_draws_the_pilcrow() { let d = doc.get(ObjRef::new(1, 0)).as_dict().cloned().unwrap(); assert!(appearance::build(&d).is_some()); } + +// ── Line annotations: leader lines and captions (ISO 32000-2 §12.5.6.7, Table 178) ────────── + +/// A red Line from `l` with a 1 pt border, a generous `/Rect`, and `extra` entries. +fn table_178_line(l: [f64; 4], extra: &[(&str, Object)]) -> Dict { + let mut d = Dict::new(); + d.set(b"Subtype".to_vec(), Object::name("Line")); + d.set(b"Rect".to_vec(), Object::Array([0.0, 0.0, 600.0, 800.0].map(Object::Real).to_vec())); + d.set(b"C".to_vec(), Object::Array([1.0, 0.0, 0.0].map(Object::Real).to_vec())); + d.set(b"L".to_vec(), Object::Array(l.map(Object::Real).to_vec())); + for (k, v) in extra { + d.set(k.as_bytes().to_vec(), v.clone()); + } + d +} + +/// The built appearance's content. +fn line_drawing(d: &Dict) -> String { + let s = crate::appearance::build(d).expect("the line is drawn"); + String::from_utf8_lossy(&s.decoded().unwrap()).into_owned() +} + +/// Every straight two-point stroke (`x0 y0 m x1 y1 l S`) in a drawing. +fn segments(content: &str) -> Vec<[f64; 4]> { + content + .lines() + .filter_map(|line| { + let t: Vec<&str> = line.split_whitespace().collect(); + if t.len() != 7 || t[2] != "m" || t[5] != "l" || t[6] != "S" { + return None; + } + let v: Vec = [t[0], t[1], t[3], t[4]].iter().map(|x| x.parse().unwrap()).collect(); + Some([v[0], v[1], v[2], v[3]]) + }) + .collect() +} + +/// The caption's text matrix (`a b c d e f Tm`), if any. +fn caption_matrix(content: &str) -> Option<[f64; 6]> { + let at = content.find(" Tm")?; + let before: Vec = content[..at].split_whitespace().rev().take(6).map(|x| x.parse().unwrap()).collect(); + Some([before[5], before[4], before[3], before[2], before[1], before[0]]) +} + +fn has(segs: &[[f64; 4]], want: [f64; 4]) -> bool { + segs.iter().any(|s| s.iter().zip(want).all(|(a, b)| (a - b).abs() < 0.01)) +} + +#[test] +fn a_positive_leader_length_puts_the_line_above_a_left_to_right_line_and_a_negative_one_below() { + let up = segments(&line_drawing(&table_178_line([72.0, 620.0, 272.0, 620.0], &[("LL", Object::Real(20.0))]))); + assert!(has(&up, [72.0, 640.0, 272.0, 640.0]), "the line is 20 above /L: {up:?}"); + assert!(has(&up, [72.0, 620.0, 72.0, 640.0]) && has(&up, [272.0, 620.0, 272.0, 640.0]), "leader lines from /L up to it: {up:?}"); + assert!(!has(&up, [72.0, 620.0, 272.0, 620.0]), "nothing along /L itself: {up:?}"); + + let down = segments(&line_drawing(&table_178_line([72.0, 540.0, 272.0, 540.0], &[("LL", Object::Real(-20.0)), ("LLE", Object::Real(10.0))]))); + assert!(has(&down, [72.0, 520.0, 272.0, 520.0]), "the line is 20 below /L: {down:?}"); + assert!(has(&down, [72.0, 540.0, 72.0, 510.0]) && has(&down, [272.0, 540.0, 272.0, 510.0]), "leaders run 10 past it: {down:?}"); +} + +#[test] +fn a_leader_offset_leaves_a_gap_and_the_endings_sit_on_the_line_itself() { + let d = table_178_line( + [72.0, 460.0, 272.0, 460.0], + &[("LL", Object::Real(20.0)), ("LLO", Object::Real(10.0)), ("LE", Object::Array(vec![Object::name("OpenArrow"), Object::name("OpenArrow")]))], + ); + let content = line_drawing(&d); + let segs = segments(&content); + assert!(has(&segs, [72.0, 490.0, 272.0, 490.0]), "the line sits |LL| + LLO above /L: {segs:?}"); + assert!(has(&segs, [72.0, 470.0, 72.0, 490.0]) && has(&segs, [272.0, 470.0, 272.0, 490.0]), "leaders start LLO from /L: {segs:?}"); + // The open arrows' tips (`tip l`) are at the ends of the line, not of /L. + assert!(content.contains(" 72 490 l ") && content.contains(" 272 490 l "), "arrows at the moved line: {content}"); + assert!(!content.contains(" 72 460 l "), "no arrow on /L: {content}"); +} + +#[test] +fn an_inline_caption_breaks_the_line_around_its_text() { + let d = + table_178_line([72.0, 380.0, 272.0, 380.0], &[("Cap", Object::Bool(true)), ("Contents", Object::String(PdfString::text("Inline 50 mm")))]); + let content = line_drawing(&d); + assert!(content.contains("(Inline 50 mm) Tj"), "the caption is drawn: {content}"); + assert!(content.contains("/Helv 10 Tf"), "in Helvetica 10: {content}"); + let m = caption_matrix(&content).expect("text matrix"); + let width = crate::appearance::text_width("Inline 50 mm", 10.0); + assert!((m[4] - (172.0 - width / 2.0)).abs() < 0.01 && m[5] < 380.0 && m[5] > 380.0 - 10.0, "centred on the line: {m:?}"); + let segs = segments(&content); + assert_eq!(segs.len(), 2, "two pieces: {segs:?}"); + assert!(segs.iter().all(|s| s[2] <= 172.0 - width / 2.0 || s[0] >= 172.0 + width / 2.0), "no stroke under the text: {segs:?}"); + assert!(has(&segs, [72.0, 380.0, 172.0 - width / 2.0 - 2.0, 380.0]), "the left piece starts at the line's start: {segs:?}"); +} + +#[test] +fn a_top_caption_sits_above_the_unbroken_line() { + let d = table_178_line( + [72.0, 300.0, 272.0, 300.0], + &[("Cap", Object::Bool(true)), ("CP", Object::name("Top")), ("Contents", Object::String(PdfString::text("Top 50 mm")))], + ); + let content = line_drawing(&d); + let m = caption_matrix(&content).expect("text matrix"); + assert!(m[5] > 300.0 && m[5] < 305.0, "baseline just above the line: {m:?}"); + assert_eq!(segments(&content), vec![[72.0, 300.0, 272.0, 300.0]], "the line is whole"); +} + +#[test] +fn a_caption_offset_moves_it_along_and_off_the_line_with_a_tick() { + let co = |h: f64, v: f64| Object::Array(vec![Object::Real(h), Object::Real(v)]); + let text = ("Contents", Object::String(PdfString::text("Offset 15"))); + let base = caption_matrix(&line_drawing(&table_178_line([330.0, 700.0, 530.0, 700.0], &[("Cap", Object::Bool(true)), text.clone()]))).unwrap(); + let content = line_drawing(&table_178_line([330.0, 700.0, 530.0, 700.0], &[("Cap", Object::Bool(true)), ("CO", co(0.0, 15.0)), text.clone()])); + let up = caption_matrix(&content).unwrap(); + assert!((up[5] - base[5] - 15.0).abs() < 0.01 && (up[4] - base[4]).abs() < 0.01, "15 up: {base:?} → {up:?}"); + let segs = segments(&content); + assert!(has(&segs, [330.0, 700.0, 530.0, 700.0]), "a caption off the line leaves it whole: {segs:?}"); + assert!(segs.iter().any(|s| s[0] == 430.0 && s[2] == 430.0 && s[1] == 700.0 && s[3] > 705.0), "a tick from the midpoint up: {segs:?}"); + let along = + caption_matrix(&line_drawing(&table_178_line([330.0, 700.0, 530.0, 700.0], &[("Cap", Object::Bool(true)), ("CO", co(-30.0, 0.0)), text]))) + .unwrap(); + assert!((along[4] - base[4] + 30.0).abs() < 0.01 && (along[5] - base[5]).abs() < 0.01, "30 left: {base:?} → {along:?}"); +} + +#[test] +fn without_cap_true_no_caption_is_drawn() { + for cap in [None, Some(Object::Bool(false)), Some(Object::Int(1))] { + let mut extra = vec![("Contents", Object::String(PdfString::text("Hidden caption")))]; + if let Some(c) = cap.clone() { + extra.push(("Cap", c)); + } + let d = table_178_line([330.0, 620.0, 530.0, 620.0], &extra); + let content = line_drawing(&d); + assert!(!content.contains("Tj"), "{cap:?}: {content}"); + assert_eq!(segments(&content), vec![[330.0, 620.0, 530.0, 620.0]]); + assert!(crate::appearance::undrawable_text(&d).is_none()); + } +} + +#[test] +fn a_diagonal_lines_leaders_are_perpendicular_and_its_caption_turns_with_it() { + let d = table_178_line( + [330.0, 460.0, 530.0, 560.0], + &[ + ("LL", Object::Real(20.0)), + ("LLE", Object::Real(10.0)), + ("Cap", Object::Bool(true)), + ("Contents", Object::String(PdfString::text("Diagonal"))), + ], + ); + let content = line_drawing(&d); + let segs = segments(&content); + let (ux, uy) = (200.0 / 100f64.hypot(200.0), 100.0 / 100f64.hypot(200.0)); + let leaders: Vec<&[f64; 4]> = segs.iter().filter(|s| (s[2] - s[0]) * ux + (s[3] - s[1]) * uy < 1e-2).collect(); + assert_eq!(leaders.len(), 2, "two leader lines across the line: {segs:?}"); + for l in leaders { + let (dx, dy) = (l[2] - l[0], l[3] - l[1]); + assert!((dx.hypot(dy) - 30.0).abs() < 0.01, "|LL| + LLE long: {l:?}"); + assert!(dx < 0.0 && dy > 0.0, "up and to the left (left of travel): {l:?}"); + } + let m = caption_matrix(&content).expect("caption"); + assert!((m[0] - ux).abs() < 1e-3 && (m[1] - uy).abs() < 1e-3, "the text runs along the line: {m:?}"); + // Drawn right to left, it still reads left to right. + let back = caption_matrix(&line_drawing(&table_178_line( + [530.0, 560.0, 330.0, 460.0], + &[("Cap", Object::Bool(true)), ("Contents", Object::String(PdfString::text("x")))], + ))) + .unwrap(); + assert!(back[0] > 0.0, "{back:?}"); +} + +#[test] +fn a_caption_from_rich_text_and_one_the_font_cant_draw() { + let rc = "

Dim & 50 mm <x>

"; + let d = table_178_line([0.0, 0.0, 100.0, 0.0], &[("Cap", Object::Bool(true)), ("RC", Object::String(PdfString::text(rc)))]); + let s = crate::appearance::build(&d).unwrap().decoded().unwrap(); + assert!(s.windows(17).any(|w| w == b"(Dim & 50 mm )"), "{}", String::from_utf8_lossy(&s)); + let cjk = table_178_line([0.0, 0.0, 100.0, 0.0], &[("Cap", Object::Bool(true)), ("Contents", Object::String(PdfString::text("長さ")))]); + assert_eq!(crate::appearance::undrawable_text(&cjk), Some(("the line's caption", '長'))); + // A PdfCraft measurement's label is its caption: the comment text isn't drawn a second time. + let mut measured = cjk.clone(); + measured.set(b"PCMeasureValue".to_vec(), Object::String(PdfString::text("5 mm"))); + assert_eq!(crate::appearance::undrawable_text(&measured), None); + let content = line_drawing(&measured); + assert_eq!(content.matches(" Tj").count(), 1, "{content}"); +} + +#[test] +fn degenerate_and_absurd_leader_and_caption_values_do_not_panic() { + let cap = ("Cap", Object::Bool(true)); + let text = ("Contents", Object::String(PdfString::text(&"w".repeat(10_000)))); + // A zero-length line has no direction: no leader lines, no caption, no NaN. + let point = + line_drawing(&table_178_line([50.0, 50.0, 50.0, 50.0], &[("LL", Object::Real(20.0)), ("LLE", Object::Real(5.0)), cap.clone(), text.clone()])); + assert!(!point.contains("NaN") && !point.contains("inf") && !point.contains("Tj"), "{point}"); + assert_eq!(segments(&point).len(), 1); + for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, 1e300, -1e300, f64::MAX] { + let d = table_178_line( + [0.0, 0.0, 100.0, 0.0], + &[ + ("LL", Object::Real(bad)), + ("LLE", Object::Real(bad)), + ("LLO", Object::Real(bad)), + ("CO", Object::Array(vec![Object::Real(bad), Object::Real(bad)])), + cap.clone(), + text.clone(), + ], + ); + let content = line_drawing(&d); + assert!(!content.contains("NaN") && !content.contains("inf"), "{bad}: {content}"); + for s in segments(&content) { + assert!(s.iter().all(|x| x.abs() <= 50_000.0), "{bad}: {s:?}"); + } + } + // Negative LLE and LLO count as 0. + let neg = segments(&line_drawing(&table_178_line( + [0.0, 0.0, 100.0, 0.0], + &[("LL", Object::Real(10.0)), ("LLE", Object::Real(-5.0)), ("LLO", Object::Real(-5.0))], + ))); + assert!(has(&neg, [0.0, 0.0, 0.0, 10.0]) && has(&neg, [0.0, 10.0, 100.0, 10.0]), "{neg:?}"); + // Huge endpoints whose midpoint would overflow fall back to the plain line. + let huge = line_drawing(&table_178_line([f64::MAX, f64::MAX, f64::MAX / 2.0, f64::MAX], &[("LL", Object::Real(20.0)), cap, text])); + assert!(!huge.contains("NaN") && !huge.contains("inf"), "{huge}"); + // The caption is cut to 256 characters. + let long = line_drawing(&table_178_line( + [0.0, 0.0, 100.0, 0.0], + &[("Cap", Object::Bool(true)), ("Contents", Object::String(PdfString::text(&"w".repeat(10_000))))], + )); + assert!(long.contains(&format!("({}) Tj", "w".repeat(256))), "cut to 256"); + assert!(!long.contains(&"w".repeat(257))); +} diff --git a/crates/automation/README.md b/crates/automation/README.md index 7eb8ca1191..cdaaa13e64 100644 --- a/crates/automation/README.md +++ b/crates/automation/README.md @@ -33,7 +33,7 @@ its undo/redo history. - For proportional image signature resizing, use the embedded image layer's width/height ratio rather than a previously stretched annotation rectangle. The GUI preserves this ratio at corners with the opposite corner anchored; edge midpoint handles change only their own axis. `comment_edit` accepts the resulting rectangle. - `doc_close` refuses to drop unsaved changes unless `discard_changes: true`. `doc_save` writes atomically, incrementally in place, and in full for a new path. Atomic output writes call `sync_all` on the staging file before replacing the destination. A write or sync error leaves the destination intact, removes staging and leaves the document dirty for retry. A filesystem that does not support syncing returns an error; there is no unsynced fallback. This flushes file contents, but does not guarantee persistence of the parent-directory rename across power loss. - With a root set, every read and write path must resolve inside it (symlinks and `..` included). Relative paths resolve inside the root, and `..` is resolved by name before the check. Every path outside the root gets the same refusal (` is outside the allowed directory `), whether or not it exists, so a confined agent can't probe the rest of the disk; on Windows another network share or device path (`\\host\share`, `\\?\UNC\…`, `\\.\…`) is refused without being contacted. "Not found" and other filesystem errors are reported only for paths inside the root. Tools that write several files into a folder name them after the document or input file, with separators, colons and control characters replaced by `_`, so a name can't lead them out of the folder. The root itself must be a folder. -- `Automation::with_automation_roots` holds a read folder and a write folder (`pdfcraft-cli mcp --automation-read-root DIR --automation-write-root DIR`, see [docs/mcp.md](../../docs/mcp.md)). Reads must lie inside the read root and writes inside the write root, links followed. A root left out grants none of its access. Refusals read `automation path rejected: outside the read root : `. It applies on top of `with_root`. +- `Automation::with_automation_roots` holds a read folder and a write folder (`pdfcraft-cli mcp --automation-read-root DIR --automation-write-root DIR`, see [docs/mcp.md](../../docs/mcp.md)). Reads must lie inside the read root and writes inside the write root, links followed. A root left out grants none of its access. Refusals read `automation path rejected: outside the read root : `. As with a root set, on Windows a path on another network share or device path is refused with that refusal without being contacted (#4003). It applies on top of `with_root`. ## Text search and cache limits diff --git a/crates/automation/src/file_access.rs b/crates/automation/src/file_access.rs index 4820743e22..1556e3c90b 100644 --- a/crates/automation/src/file_access.rs +++ b/crates/automation/src/file_access.rs @@ -9,6 +9,9 @@ //! links are followed: for a file that doesn't exist yet, the links of its nearest existing //! folder, the rest of the path being plain names (`..` below a missing folder is refused, and so //! is a link that leads nowhere). +//! - A path on another network share or in a device namespace (`\\host\share`, `\\.\pipe\x`) +//! than the root's is refused by name, before anything is resolved: resolving it would contact +//! the host. //! - The result must lie inside the root, compared by whole components (`/work2` isn't inside //! `/work`), without regard to case on Windows. //! - Read and write access are separate: a root given alone grants only its own kind of access. @@ -97,7 +100,10 @@ impl AutomationRoots { Access::Write => Err(format!("automation filesystem access is not granted: write authority is absent: {shown}")), }; }; - if inside(&resolve(shown, target)?, folder) { + let absolute = absolute(shown, target)?; + // Another network share or a device is refused by name, as `--root` refuses it: even + // resolving the path would contact the host (#4003). + if !foreign_share(&absolute, folder) && inside(&resolve(shown, &absolute)?, folder) { return Ok(()); } let root = root_shown.display(); @@ -123,9 +129,8 @@ fn plain(path: PathBuf) -> PathBuf { } } -/// `path` made absolute with its links followed; for a path that doesn't exist (yet), its nearest -/// existing folder's links followed and the rest appended. -fn resolve(shown: &str, path: &Path) -> Result { +/// `path` made absolute against the working directory, by name: nothing on disk is read. +fn absolute(shown: &str, path: &Path) -> Result { if path.as_os_str().is_empty() { return Err("automation path rejected: path is empty".into()); } @@ -133,10 +138,15 @@ fn resolve(shown: &str, path: &Path) -> Result { if cfg!(windows) && path.components().any(|c| matches!(c, Component::Normal(n) if is_device_name(&n.to_string_lossy()))) { return Err(format!("automation path rejected: reserved device names are not allowed: {shown}")); } - let absolute = std::path::absolute(path).map_err(|e| format!("automation path rejected: cannot resolve {shown}: {e}"))?; + std::path::absolute(path).map_err(|e| format!("automation path rejected: cannot resolve {shown}: {e}")) +} + +/// `absolute` with its links followed; for a path that doesn't exist (yet), its nearest existing +/// folder's links followed and the rest appended. +fn resolve(shown: &str, absolute: &Path) -> Result { // The names below the nearest existing folder, last first. let mut missing: Vec = vec![]; - let mut at = absolute.as_path(); + let mut at = absolute; loop { match std::fs::canonicalize(at) { Ok(mut found) => { @@ -189,6 +199,24 @@ fn same_component(a: Component, b: Component) -> bool { } } +/// Whether `path` names another network share or device namespace than `root` (Windows +/// `\\host\share`, `\\?\UNC\…`, `\\.\…`, `\\?\…`). Those are refused by name: even checking +/// that one exists would contact the host. Drive letters are left to the normal check. +pub(crate) fn foreign_share(path: &Path, root: &Path) -> bool { + use std::path::Prefix; + fn share(p: &Path) -> Option { + let Some(Component::Prefix(prefix)) = p.components().next() else { return None }; + let (kind, a, b) = match prefix.kind() { + Prefix::Disk(_) | Prefix::VerbatimDisk(_) => return None, + Prefix::UNC(host, share) | Prefix::VerbatimUNC(host, share) => ("unc", host, share), + Prefix::DeviceNS(name) => ("device", name, std::ffi::OsStr::new("")), + Prefix::Verbatim(name) => ("verbatim", name, std::ffi::OsStr::new("")), + }; + Some(format!("{kind}\\{}\\{}", a.to_string_lossy(), b.to_string_lossy()).to_lowercase()) + } + share(path).is_some_and(|s| share(root).as_ref() != Some(&s)) +} + /// A Windows device name (`CON`, `NUL`, `COM1`… also with an extension), which names no file. fn is_device_name(component: &str) -> bool { let stem = component.split('.').next().unwrap_or(component).trim_end_matches(' ').to_ascii_uppercase(); @@ -233,6 +261,27 @@ mod tests { let _ = std::fs::remove_dir_all(base); } + /// #4003: another share or a device namespace is refused by name, with the same words as any + /// other path outside the root, before anything is resolved (which would contact the host). + #[cfg(windows)] + #[test] + fn other_shares_and_devices_are_refused_before_they_are_resolved() { + let (base, roots) = folders("shares"); + for p in [ + r"\\.\pipe\pdfcraft-4003.pdf", + r"\\?\GLOBALROOT\Device\Null", + r"\\pdfcraft-no-such-host.invalid\share\a.pdf", + "//pdfcraft-no-such-host.invalid/share/a.pdf", + r"\\?\UNC\pdfcraft-no-such-host.invalid\share\a.pdf", + ] { + let e = roots.check(p, Access::Read).unwrap_err(); + assert!(e.starts_with("automation path rejected: outside the read root"), "{p}: {e}"); + let e = roots.check(p, Access::Write).unwrap_err(); + assert!(e.starts_with("automation path rejected: outside the write root"), "{p}: {e}"); + } + let _ = std::fs::remove_dir_all(base); + } + #[test] fn a_sibling_with_the_same_prefix_is_outside() { let (base, roots) = folders("prefix"); diff --git a/crates/automation/src/lib.rs b/crates/automation/src/lib.rs index 9a217ab3f0..b9f906f189 100644 --- a/crates/automation/src/lib.rs +++ b/crates/automation/src/lib.rs @@ -106,6 +106,7 @@ const MAX_BOOKMARK_POSITION: f64 = 1_000_000.0; const FIND_FIRST_BATCH: usize = 8; const FIND_MAX_BATCH: usize = 128; +use file_access::foreign_share; use text_cache::TextCache; type PageTexts = Vec<(usize, std::result::Result, String>)>; @@ -2396,24 +2397,6 @@ fn lexical(path: &Path) -> Option { Some(parts.iter().collect()) } -/// Whether `path` names another network share or device namespace than `root` (Windows -/// `\\host\share`, `\\?\UNC\…`, `\\.\…`, `\\?\…`). Those are refused by name: even checking -/// that one exists would contact the host. Drive letters are left to the normal check. -fn foreign_share(path: &Path, root: &Path) -> bool { - use std::path::{Component, Prefix}; - fn share(p: &Path) -> Option { - let Some(Component::Prefix(prefix)) = p.components().next() else { return None }; - let (kind, a, b) = match prefix.kind() { - Prefix::Disk(_) | Prefix::VerbatimDisk(_) => return None, - Prefix::UNC(host, share) | Prefix::VerbatimUNC(host, share) => ("unc", host, share), - Prefix::DeviceNS(name) => ("device", name, std::ffi::OsStr::new("")), - Prefix::Verbatim(name) => ("verbatim", name, std::ffi::OsStr::new("")), - }; - Some(format!("{kind}\\{}\\{}", a.to_string_lossy(), b.to_string_lossy()).to_lowercase()) - } - share(path).is_some_and(|s| share(root).as_ref() != Some(&s)) -} - // ---- JSON helpers ---------------------------------------------------------------------------- fn parse_style_ranges(value: Option<&Value>) -> Result> { @@ -2676,6 +2659,9 @@ fn info(d: &Document) -> Value { "creator": i.creator, "producer": i.producer, "tagged": i.tagged, "has_javascript": i.has_javascript, + // Where the document opens (/OpenAction, named destinations resolved): 1-based page and + // destination, null without one. + "open_destination": i.open_dest.as_ref().map(|(p, view)| json!({ "page": page1(*p), "destination": i.pages.get(*p).and_then(|pg| destination(view, pg)) })), // XFA forms: "static" (the PDF's own fields work; the XFA data is ignored) or "dynamic" // (laid out from the template by PdfCraft, see xfa_layout; placeholder pages when that failed). "xfa": i.xfa.map(|x| match x { pdfcraft_render::Xfa::Static => "static", pdfcraft_render::Xfa::Dynamic => "dynamic" }), diff --git a/crates/automation/src/tools.rs b/crates/automation/src/tools.rs index 4ceedafd57..ccc2ee85cc 100644 --- a/crates/automation/src/tools.rs +++ b/crates/automation/src/tools.rs @@ -139,7 +139,7 @@ pub fn tools() -> Vec { .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, attachments, fonts, security and repair notes.") + 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 and repair notes.") .ro() .cmd("file.properties") .with(schema(json!({ "doc": doc() }), &["doc"])), diff --git a/crates/automation/tests/it/automation.rs b/crates/automation/tests/it/automation.rs index c2eb4b71c1..cf124f169a 100644 --- a/crates/automation/tests/it/automation.rs +++ b/crates/automation/tests/it/automation.rs @@ -213,6 +213,49 @@ fn doc_info_lists_page_transitions_and_display_times() { ); } +/// `doc_info` says where the document opens: the `/OpenAction` destination, a named one +/// resolved (ISO 32000-2 §12.3.2.4), as a 1-based page and a destination in view coordinates. +#[test] +fn doc_info_reports_the_open_destination() { + let dir = workdir("open-destination"); + let write = |name: &str, catalog: &str| { + let objects: Vec = vec![ + format!("<< /Type /Catalog /Pages 2 0 R {catalog} >>"), + "<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 /MediaBox [0 0 612 792] >>".into(), + "<< /Type /Page /Parent 2 0 R >>".into(), + "<< /Type /Page /Parent 2 0 R >>".into(), + ]; + 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 o in offsets { + bytes.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes()); + } + bytes.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objects.len() + 1).as_bytes()); + std::fs::write(dir.join(name), bytes).unwrap(); + }; + write("named.pdf", "/OpenAction << /S /GoTo /D /there >> /Dests << /there [4 0 R /XYZ 100 500 2] >>"); + write("script.pdf", "/OpenAction << /S /JavaScript /JS (1) >>"); + let mut a = auto(&dir); + let doc = ok(&mut a, "doc_open", json!({ "path": "named.pdf" }))["doc"].as_u64().unwrap(); + let open = ok(&mut a, "doc_info", json!({ "doc": doc }))["open_destination"].clone(); + assert_eq!(open["page"], 2, "{open}"); + // y 500 is 292 points below the top of the 792-point page. + assert_eq!( + (open["destination"]["fit"].as_str(), open["destination"]["left"].as_f64(), open["destination"]["top"].as_f64()), + (Some("XYZ"), Some(100.0), Some(292.0)), + "{open}" + ); + assert_eq!(open["destination"]["zoom"].as_f64(), Some(2.0)); + let doc = ok(&mut a, "doc_open", json!({ "path": "script.pdf" }))["doc"].as_u64().unwrap(); + assert!(ok(&mut a, "doc_info", json!({ "doc": doc }))["open_destination"].is_null()); +} + /// Page transitions through the tools: set on chosen pages, written to the file as `/Trans` and /// `/Dur`, removed again, bad values refused, and one undo step. (Read through `pdfcraft_cos`, /// so this does not lean on `doc_info` listing them.) diff --git a/crates/automation/tests/it/automation_roots.rs b/crates/automation/tests/it/automation_roots.rs index 3e2d024cdb..a96870ca02 100644 --- a/crates/automation/tests/it/automation_roots.rs +++ b/crates/automation/tests/it/automation_roots.rs @@ -352,6 +352,19 @@ fn links_out_of_a_root_are_refused() { assert_eq!(names(&base.join("outside")), ["pic.png", "secret.pdf"]); } +/// #4003: without `--root`, another network share or a device is refused by name through the +/// tools too, with the same words as any other path outside a root. +#[cfg(windows)] +#[test] +fn other_shares_and_devices_are_refused_by_name() { + let (mut server, base) = confined("shares", true, true); + ok(&mut server, "doc_open", json!({"path": s(&base.join("in/a.pdf"))})); + for p in [r"\\.\pipe\pdfcraft-4003.pdf", r"\\pdfcraft-no-such-host.invalid\share\a.pdf", "//pdfcraft-no-such-host.invalid/share/a.pdf"] { + refused(&mut server, "doc_open", json!({"path": p}), "outside the read root"); + refused(&mut server, "doc_save", json!({"doc": 1, "path": p}), "outside the write root"); + } +} + #[test] fn without_roots_nothing_is_confined() { let base = folders("none"); diff --git a/crates/engine/src/camera_edges.rs b/crates/engine/src/camera_edges.rs index fd8dbd5f28..cee5c8f694 100644 --- a/crates/engine/src/camera_edges.rs +++ b/crates/engine/src/camera_edges.rs @@ -311,6 +311,35 @@ fn refine(q: [Point; 4], edges: &[Option], w: usize, h: usize) -> Option<[ order_quad(refined) } +/// A candidate quad's score (its area times the square of its sides' mean support), or `None` when it +/// strays off the image, is too small, or has a side without enough edge support. +fn quad_score(q: &[Point; 4], edges: &[Option], w: usize, h: usize) -> Option { + let (fw, fh) = (w as f64, h as f64); + let (mx, my) = (MARGIN * fw, MARGIN * fh); + if q.iter().any(|p| p[0] < -mx || p[1] < -my || p[0] > fw + mx || p[1] > fh + my) { + return None; + } + let area = (0..4) + .map(|k| { + let (p, n) = (q[k], q[(k + 1) % 4]); + p[0] * n[1] - n[0] * p[1] + }) + .sum::() + .abs() + / 2.0; + if area < MIN_AREA * fw * fh { + return None; + } + let sides: Vec = (0..4).map(|k| support(q[k], q[(k + 1) % 4], edges, w, h)).collect(); + if sides.iter().any(|&s| s < MIN_SUPPORT) { + return None; + } + // Large, and with every side on its edge: a slightly larger quad with a side + // off the sheet loses to the sheet itself. + let mean = sides.iter().sum::() / 4.0; + Some(area * mean * mean) +} + /// The convex quadrilateral of two near-horizontal and two near-vertical lines whose four sides /// all lie on edges, scored by its area times the square of its sides' mean support. fn best_quad(lines: &[Line], edges: &[Option], w: usize, h: usize) -> Option<[Point; 4]> { @@ -318,8 +347,6 @@ fn best_quad(lines: &[Line], edges: &[Option], w: usize, h: usize) -> Opti let flat = |l: &&Line| (l.theta.to_degrees() - 90.0).abs() <= 45.0; let horizontal: Vec<&Line> = lines.iter().filter(flat).collect(); let vertical: Vec<&Line> = lines.iter().filter(|l| !flat(l)).collect(); - let (fw, fh) = (w as f64, h as f64); - let (mx, my) = (MARGIN * fw, MARGIN * fh); let mut best: Option<(f64, [Point; 4])> = None; for (i, &h1) in horizontal.iter().enumerate() { for &h2 in horizontal.iter().skip(i + 1) { @@ -328,28 +355,7 @@ fn best_quad(lines: &[Line], edges: &[Option], w: usize, h: usize) -> Opti let corners = [intersect(*h1, *v1), intersect(*h1, *v2), intersect(*h2, *v2), intersect(*h2, *v1)]; let [Some(a), Some(b), Some(c), Some(d)] = corners else { continue }; let Some(q) = order_quad([a, b, c, d]) else { continue }; - if q.iter().any(|p| p[0] < -mx || p[1] < -my || p[0] > fw + mx || p[1] > fh + my) { - continue; - } - let area = (0..4) - .map(|k| { - let (p, n) = (q[k], q[(k + 1) % 4]); - p[0] * n[1] - n[0] * p[1] - }) - .sum::() - .abs() - / 2.0; - if area < MIN_AREA * fw * fh { - continue; - } - let sides: Vec = (0..4).map(|k| support(q[k], q[(k + 1) % 4], edges, w, h)).collect(); - if sides.iter().any(|&s| s < MIN_SUPPORT) { - continue; - } - // Large, and with every side on its edge: a slightly larger quad with a side - // off the sheet loses to the sheet itself. - let mean = sides.iter().sum::() / 4.0; - let score = area * mean * mean; + let Some(score) = quad_score(&q, edges, w, h) else { continue }; if best.is_none_or(|(b, _)| score > b) { best = Some((score, q)); } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 8cd90bf750..c764d6e311 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -51,6 +51,7 @@ pub use pdfcraft_organize::{BoxSpec, FieldConflicts, PageBox, SplitBy, Transitio /// One file produced by a split: (1-based first page, last page, PDF bytes). pub use pdfcraft_organize::LabelStyle; pub use pdfcraft_organize::Standard; +pub use pdfcraft_organize::check_custom_key; pub use pdfcraft_organize::view::{InitialView, Layout as InitialLayout, Magnification, Navigation}; pub use pdfcraft_cos::Algorithm; @@ -951,6 +952,11 @@ impl Document { self.editor.as_ref().and_then(|e| pdfcraft_organize::info(&e.cos, key)) } + /// Whether the document information has an entry `key`, of any type, listed or not. + pub fn has_info(&self, key: &str) -> bool { + self.editor.as_ref().is_some_and(|e| pdfcraft_organize::has_info(&e.cos, key)) + } + /// The custom document properties as they are now (name, text), Document Properties ▸ Custom. pub fn custom_info(&self) -> Vec<(String, String)> { self.editor.as_ref().map(|e| pdfcraft_organize::custom_info(&e.cos)).unwrap_or_default() diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 5f3e836f34..a7d984ee87 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -6466,6 +6466,42 @@ fn comments_without_appearances_are_drawn_but_not_saved() { } } +/// ISO 32000-2 Table 178: with `/LL`, `/L` gives the ends of the leader lines, and the line itself +/// is drawn `/LL` from it (above, for a positive `/LL` on a line drawn left to right). The page +/// view shows the line there, with its leaders down to `/L`, and nothing along `/L` itself. +#[test] +fn a_line_without_an_appearance_is_drawn_at_its_leader_length() { + let objs: Vec<&[u8]> = vec![ + b"<< /Type /Catalog /Pages 2 0 R >>", + b"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 200 300] >>", + b"<< /Type /Page /Parent 2 0 R /Annots [4 0 R] >>", + b"<< /Type /Annot /Subtype /Line /Rect [0 0 200 300] /L [40 100 160 100] /LL 30 /C [1 0 0] /BS << /W 4 >> >>", + ]; + let mut bytes = b"%PDF-1.7\n".to_vec(); + let mut offsets = Vec::new(); + for (i, o) in objs.iter().enumerate() { + offsets.push(bytes.len()); + bytes.extend_from_slice(format!("{} 0 obj\n", i + 1).as_bytes()); + bytes.extend_from_slice(o); + bytes.extend_from_slice(b"\nendobj\n"); + } + let xref = bytes.len(); + bytes.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes()); + for o in offsets { + bytes.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes()); + } + bytes.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes()); + let mut s = Session::new().with_clock(|| 1_700_000_000); + let id = s.open("line.pdf", None, Arc::new(bytes), None).expect("opens"); + let p = shown(&s, id, 0); + let px = |x: u32, y: u32| p.rgba[((y * p.width + x) * 4) as usize..][..4].to_vec(); + // y down: /L is row 200, the line itself row 170. + assert_eq!(px(100, 170), vec![255, 0, 0, 255], "the line, 30 above /L"); + assert_eq!(px(40, 185), vec![255, 0, 0, 255], "the leader line at the start"); + assert_eq!(px(160, 185), vec![255, 0, 0, 255], "the leader line at the end"); + assert_eq!(px(100, 200), vec![255, 255, 255, 255], "nothing along /L"); +} + /// A stamp's `/Rect` and the colour family expected inside it. type StampRect = ([f64; 4], char); diff --git a/crates/engine/src/word_count.rs b/crates/engine/src/word_count.rs index bd31c27e4c..feeb0a066f 100644 --- a/crates/engine/src/word_count.rs +++ b/crates/engine/src/word_count.rs @@ -110,6 +110,16 @@ fn standard_role(doc: &pdfcraft_cos::Document, map: &Dict, role: &[u8]) -> Vec bool { + let resources = page.get(b"Resources").map(|o| doc.resolve(o)); + let objects = resources.as_ref().and_then(|o| o.as_dict()).and_then(|d| d.get(b"XObject")).map(|o| doc.resolve(o)); + objects + .as_ref() + .and_then(|o| o.as_dict()) + .is_some_and(|d| d.iter().any(|(_, value)| matches!(&*doc.resolve(value), Object::Stream(s) if s.dict.name(b"Subtype") == Some(b"Form")))) +} + type Exclusions = HashMap>; /// Resolve page-local MCIDs through the structure hierarchy, including inherited roles and @@ -179,11 +189,7 @@ fn exclusions(source: &ExportSource, options: Options) -> Result<(Exclusions, bo if !out.contains_key(&index) { continue; } - let resources = page.dict.get(b"Resources").map(|o| doc.resolve(o)); - let objects = resources.as_ref().and_then(|o| o.as_dict()).and_then(|d| d.get(b"XObject")).map(|o| doc.resolve(o)); - let has_form = objects.as_ref().and_then(|o| o.as_dict()).is_some_and(|d| { - d.iter().any(|(_, value)| matches!(&*doc.resolve(value), Object::Stream(s) if s.dict.name(b"Subtype") == Some(b"Form"))) - }); + let has_form = page_has_form_xobject(&doc, &page.dict); if has_form { out.remove(&index); unclassified = true; diff --git a/crates/forms/src/appearance.rs b/crates/forms/src/appearance.rs index 3172fd7d6c..da25c211c0 100644 --- a/crates/forms/src/appearance.rs +++ b/crates/forms/src/appearance.rs @@ -133,8 +133,11 @@ impl TextBox { // As the appearance draws it: the first baseline is 0.85 em below the padded top and // a line is drawn while its descent (0.207 em) stays inside the border, so the // padding below the last line is not needed: `inner_h` plus 2 pt. - let above = wrap_with(&shown, size, self.inner_w, width_of).len().saturating_sub(1) as f64; - above * size * 1.15 + 1.057 * size <= self.inner_h + 2.0 + 0.01 + // Long words break by character, so a line is wider than the box only when it is a + // single character wider than the box, which the appearance still cuts at the sides. + let lines = wrap_with(&shown, size, self.inner_w, width_of); + let above = lines.len().saturating_sub(1) as f64; + above * size * 1.15 + 1.057 * size <= self.inner_h + 2.0 + 0.01 && lines.iter().all(|l| width_of(l, size) <= self.inner_w + 0.01) } else { // A line break in a single-line value is drawn as a space. let line: String = shown.chars().map(|c| if matches!(c, '\n' | '\r') { ' ' } else { c }).collect(); diff --git a/crates/forms/src/tests.rs b/crates/forms/src/tests.rs index 9af1bc5732..54bc137abd 100644 --- a/crates/forms/src/tests.rs +++ b/crates/forms/src/tests.rs @@ -471,6 +471,32 @@ fn a_short_multiline_field_takes_the_one_line_it_draws() { assert!(!tb("boxed").fits("one line")); } +/// A multi-line field narrower than one glyph: wrapping can't break inside a character, so the +/// appearance cuts that character at the sides (`Overflow::Wide`), and `fits` must say so too. +#[test] +fn a_multiline_field_rejects_a_glyph_wider_than_the_field() { + // 12 x 40 pt with no border: 8 pt inside the 2 pt padding. At 12 pt Helvetica a W is 11.3 pt + // wide and an i 2.7 pt. + let objs: Vec = vec![ + "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(), + "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(), + "<< /Type /Page /Parent 2 0 R /Annots [6 0 R] >>".into(), + "<< /Fields [6 0 R] /DA (/Helv 12 Tf 0 g) /DR << /Font << /Helv 5 0 R >> >> >>".into(), + "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".into(), + format!( + "<< /Type /Annot /Subtype /Widget /FT /Tx /T (thin) /V (W) /DA (/Helv 12 Tf 0 g) /Ff {} /Rect [50 660 62 700] /P 3 0 R >>", + flags::MULTILINE + ), + ]; + let doc = document(&objs); + let all = fields(&doc); + let f = field(&all, "thin"); + let tb = appearance::text_box(&doc, f, &f.widgets[0]); + assert!(tb.fits("i") && tb.fits("i\ni")); + assert!(matches!(appearance::value_overflow(&doc, f, &f.widgets[0]), Some(appearance::Overflow::Wide { .. }))); + assert!(!tb.fits("W") && !tb.fits("iW")); +} + /// An edit to a field that doesn't scroll keeps as much of what it inserted as fits, wherever the /// caret was, and always keeps a deletion. #[test] diff --git a/crates/optimize/src/links.rs b/crates/optimize/src/links.rs index 082d56e7df..cbd64eb928 100644 --- a/crates/optimize/src/links.rs +++ b/crates/optimize/src/links.rs @@ -152,11 +152,12 @@ fn referenced_names(doc: &Document) -> HashSet> { Object::Dict(d) => { // Resolve first: /Dest and a GoTo's /D may be an indirect reference to the name // string, and an unresolved ref has no name, so the destination it uses would - // look unreferenced and be removed. + // look unreferenced and be removed. A GoToR or GoToE /D names a destination in + // another document, so it does not count as a use of this one's. if let Some(n) = d.get(b"Dest").and_then(|x| dest_name(doc.resolve(x).as_ref())) { out.insert(n); } - if matches!(d.name(b"S"), Some(b"GoTo" | b"GoToR" | b"GoToE")) + if d.name(b"S") == Some(b"GoTo") && let Some(n) = d.get(b"D").and_then(|x| dest_name(doc.resolve(x).as_ref())) { out.insert(n); diff --git a/crates/optimize/tests/optimize.rs b/crates/optimize/tests/optimize.rs index 8802ef3515..3e69e27cb9 100644 --- a/crates/optimize/tests/optimize.rs +++ b/crates/optimize/tests/optimize.rs @@ -1273,6 +1273,50 @@ fn indirectly_referenced_destination_is_kept() { assert!(!left.contains(&b"unused".to_vec())); } +#[test] +fn a_destination_named_only_by_a_remote_or_embedded_go_to_is_removed() { + // The /D of a GoToR or GoToE action names a destination in another document. A local + // destination of the same name that nothing else uses is unreferenced. + let mut doc = Document::new_empty(); + let p = page(&mut doc, &[], "BT ET"); + let s = |t: &str| Object::String(pdfcraft_cos::PdfString::literal(t.as_bytes().to_vec())); + let link = |doc: &mut Document, action: Dict| { + let mut link = Dict::new(); + link.set(b"Type".to_vec(), Object::name("Annot")); + link.set(b"Subtype".to_vec(), Object::name("Link")); + link.set(b"Rect".to_vec(), Object::Array(vec![0.into(), 0.into(), 10.into(), 10.into()])); + link.set(b"A".to_vec(), Object::Dict(action)); + Object::Ref(doc.add(Object::Dict(link))) + }; + let mut go_to = Dict::new(); + go_to.set(b"S".to_vec(), Object::name("GoTo")); + go_to.set(b"D".to_vec(), s("local")); + let mut remote = Dict::new(); + remote.set(b"S".to_vec(), Object::name("GoToR")); + remote.set(b"F".to_vec(), s("other.pdf")); + remote.set(b"D".to_vec(), s("remote")); + let mut target = Dict::new(); + target.set(b"R".to_vec(), Object::name("C")); + target.set(b"N".to_vec(), s("attached.pdf")); + let mut embedded = Dict::new(); + embedded.set(b"S".to_vec(), Object::name("GoToE")); + embedded.set(b"T".to_vec(), Object::Dict(target)); + embedded.set(b"D".to_vec(), s("embedded")); + let links = vec![link(&mut doc, go_to), link(&mut doc, remote), link(&mut doc, embedded)]; + doc.update_dict(p, |d| d.set(b"Annots".to_vec(), Object::Array(links))).unwrap(); + let fit = Object::Array(vec![Object::Ref(p), Object::name("Fit")]); + let mut tree = Dict::new(); + tree.set(b"Names".to_vec(), Object::Array(vec![s("embedded"), fit.clone(), s("local"), fit.clone(), s("remote"), fit])); + let tree = doc.add(Object::Dict(tree)); + let mut names = Dict::new(); + names.set(b"Dests".to_vec(), Object::Ref(tree)); + let root = doc.root().unwrap(); + doc.update_dict(root, |c| c.set(b"Names".to_vec(), Object::Dict(names))).unwrap(); + let report = optimize(&mut doc, &Settings::default()).unwrap(); + assert_eq!(report.unreferenced_dests, 2); + assert_eq!(named_dest_keys(&doc), vec![b"local".to_vec()]); +} + /// The keys in the catalog's /Names /Dests name tree (one level, as the optimizer writes it). fn named_dest_keys(doc: &Document) -> Vec> { let cat = doc.get(doc.root().unwrap()).as_dict().cloned().unwrap(); diff --git a/crates/organize/src/lib.rs b/crates/organize/src/lib.rs index 9f8cc5c457..e24056a9c3 100644 --- a/crates/organize/src/lib.rs +++ b/crates/organize/src/lib.rs @@ -672,6 +672,11 @@ pub fn info(doc: &Document, key: &str) -> Option { in_info.filter(|v| !v.trim_matches('\0').trim().is_empty()).or_else(|| xmp::info_value(doc, key)) } +/// Whether the document information has an entry `key`, of any type. +pub fn has_info(doc: &Document, key: &str) -> bool { + doc.trailer().get(b"Info").map(|o| doc.resolve(o)).is_some_and(|info| info.as_dict().is_some_and(|d| d.get(key.as_bytes()).is_some())) +} + /// Set (or clear, with an empty value) a document-information entry. /// /// Documents with XMP metadata also carry Title, Author, Subject, Keywords, Creator and Producer @@ -699,12 +704,18 @@ fn set_info_entry(doc: &mut Document, key: &[u8], entry: Option) -> Resu })?; } _ => { - let Some(v) = entry else { return Ok(()) }; let mut d = match doc.trailer().get(b"Info") { Some(Object::Dict(d)) => d.clone(), _ => Dict::new(), }; - d.set(key.to_vec(), v); + match entry { + Some(v) => d.set(key.to_vec(), v), + None => { + if d.remove(key).is_none() { + return Ok(()); + } + } + } let r = doc.add(d); doc.trailer_mut().set(b"Info".to_vec(), Object::Ref(r)); } diff --git a/crates/organize/src/outline.rs b/crates/organize/src/outline.rs index 4bcfe93ae3..cc1bbb0884 100644 --- a/crates/organize/src/outline.rs +++ b/crates/organize/src/outline.rs @@ -553,10 +553,7 @@ pub fn add_bookmark_at( let at = index.min(kids.len()); kids.insert(at, item); relink(doc, parent, &kids)?; - // Show the new bookmark: open its parent (the root is always open). - if !parent_path.is_empty() && doc.get(parent).as_dict().and_then(|d| d.int(b"Count")).is_none_or(|c| c <= 0) { - put(doc, parent, b"Count", Some(Object::Int(1)))?; - } + show_children(doc, parent, parent_path)?; recount(doc)?; let mut path = parent_path.to_vec(); path.push(at); @@ -699,11 +696,23 @@ pub fn move_bookmark(doc: &mut Document, from: &[usize], to_parent: &[usize], in let at = index.min(kids.len()); kids.insert(at, r); relink(doc, parent, &kids)?; + if parent != old_parent { + show_children(doc, parent, &to_parent)?; + } recount(doc)?; to_parent.push(at); Ok(to_parent) } +/// Open `parent` so a bookmark just added or moved into it shows (the root is always open). +/// Only the sign of `/Count` matters here: [`recount`] sets its value. +fn show_children(doc: &mut Document, parent: ObjRef, parent_path: &[usize]) -> Result<()> { + if !parent_path.is_empty() && doc.get(parent).as_dict().and_then(|d| d.int(b"Count")).is_none_or(|c| c <= 0) { + put(doc, parent, b"Count", Some(Object::Int(1)))?; + } + Ok(()) +} + /// Expand or collapse a bookmark that has children. pub fn set_bookmark_open(doc: &mut Document, path: &[usize], open: bool) -> Result<()> { let (r, _) = resolve_path(doc, path)?; diff --git a/crates/organize/src/tests.rs b/crates/organize/src/tests.rs index 02cee53d49..1ba8861cbe 100644 --- a/crates/organize/src/tests.rs +++ b/crates/organize/src/tests.rs @@ -528,6 +528,29 @@ fn custom_document_properties_are_listed_set_removed_and_their_names_checked() { assert!(custom_info(&doc).is_empty()); } +/// An `/Info` dictionary written directly in the trailer: a cleared entry is removed, and the +/// other entries are kept. +#[test] +fn document_info_entries_are_cleared_from_an_info_dictionary_in_the_trailer() { + let b = build( + &[ + "<< /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 >>".into(), + body("X"), + ], + "/Root 1 0 R /Info << /Title (Report) /Project (Apollo) /Revision (7) >>", + ); + let mut doc = open(b); + set_info(&mut doc, "Missing", "").unwrap(); + assert!(matches!(doc.trailer().get(b"Info"), Some(Object::Dict(_))), "clearing an absent entry changes nothing"); + set_info(&mut doc, "Project", "").unwrap(); + set_info(&mut doc, "Title", "").unwrap(); + let doc = save_and_reopen(&doc); + assert_eq!(custom_info(&doc), [("Revision".to_string(), "7".to_string())]); + assert_eq!(info(&doc, "Title"), None); +} + /// Padding is not part of a custom value, in any mix of NULs and whitespace, a value that is only /// padding is not listed, and such entries don't count towards the 256 listed: a real property /// after 300 blank ones is still there. @@ -1725,6 +1748,18 @@ fn bookmarks_add_rename_move_delete() { assert_eq!(crate::move_bookmark(&mut d, &[0], &[2], 9).unwrap(), vec![1, 1]); assert_eq!(titles(&crate::bookmarks(&d)), ["Intro", "Results[Table,Figure 1]"]); assert_eq!(crate::move_bookmark(&mut d, &[1], &[1, 0], 0), Err(crate::OutlineError::IntoItself)); + // Into a bookmark with no children yet (Indent): it opens, so the moved one shows. + assert_eq!(crate::move_bookmark(&mut d, &[1, 1], &[0], 0).unwrap(), vec![0, 0]); + let intro = crate::bookmarks(&d)[0].obj; + assert_eq!(count_of(&d, intro), Some(1)); + // Reordering inside a closed parent leaves it closed. + crate::add_bookmark(&mut d, &[0], 1, "Second", 0).unwrap(); + crate::set_bookmark_open(&mut d, &[0], false).unwrap(); + crate::move_bookmark(&mut d, &[0, 1], &[0], 0).unwrap(); + assert_eq!(count_of(&d, intro), Some(-2)); + crate::delete_bookmark(&mut d, &[0, 0]).unwrap(); + crate::move_bookmark(&mut d, &[0, 0], &[1], 9).unwrap(); + assert_eq!(titles(&crate::bookmarks(&d)), ["Intro", "Results[Table,Figure 1]"]); crate::delete_bookmark(&mut d, &[1, 0]).unwrap(); assert_eq!(titles(&crate::bookmarks(&d)), ["Intro", "Results[Figure 1]"]); @@ -2392,6 +2427,46 @@ fn initial_view_round_trips_and_keeps_scripts() { assert!(crate::set_initial_view(&mut doc, &crate::InitialView { page: 9, ..Default::default() }).is_err()); } +#[test] +fn an_unchanged_opening_destination_keeps_its_position_and_name() { + use crate::view::{Magnification, Navigation}; + let page2 = Object::Ref(pdfcraft_cos::ObjRef::new(5, 0)); + let xyz = Object::Array(vec![page2.clone(), Object::name("XYZ"), Object::Int(100), Object::Int(500), Object::Int(2)]); + let mut named = pdfcraft_cos::Dict::new(); + named.set(b"S".to_vec(), Object::name("GoTo")); + named.set(b"D".to_vec(), Object::name("there")); + let mut dests = pdfcraft_cos::Dict::new(); + dests.set(b"there".to_vec(), Object::Array(vec![page2, Object::name("Fit")])); + let mut prefs = pdfcraft_cos::Dict::new(); + prefs.set(b"NonFullScreenPageMode".to_vec(), Object::name("UseOutlines")); + for action in [xyz, Object::Dict(named)] { + let mut doc = open(fixture()); + let root = doc.root().unwrap(); + doc.update_dict(root, |c| { + c.set(b"OpenAction".to_vec(), action.clone()); + c.set(b"Dests".to_vec(), Object::Dict(dests.clone())); + c.set(b"PageMode".to_vec(), Object::name("FullScreen")); + c.set(b"ViewerPreferences".to_vec(), Object::Dict(prefs.clone())); + }) + .unwrap(); + // Another option changes: the opening action is written back as it was, and so is the + // full-screen panel, which the dialog doesn't edit. + let v = crate::initial_view(&doc); + assert_eq!(v.non_full_screen, Navigation::Bookmarks); + crate::set_initial_view(&mut doc, &crate::InitialView { hide_toolbar: true, ..v.clone() }).unwrap(); + let catalog = doc.get(root).as_dict().cloned().unwrap(); + assert_eq!(catalog.get(b"OpenAction"), Some(&action)); + let doc = save_and_reopen(&doc); + assert_eq!(crate::initial_view(&doc), crate::InitialView { hide_toolbar: true, ..v.clone() }); + // A changed magnification writes a destination of its own. + let mut doc = doc; + crate::set_initial_view(&mut doc, &crate::InitialView { magnification: Magnification::FitPage, ..v }).unwrap(); + let catalog = doc.get(root).as_dict().cloned().unwrap(); + assert_ne!(catalog.get(b"OpenAction"), Some(&action)); + assert_eq!(crate::initial_view(&doc).magnification, Magnification::FitPage); + } +} + // ── Split / Extract keep only the resources the part draws (#204) ────────────────────────────── /// A content stream with no text operators (an image draw). diff --git a/crates/organize/src/view.rs b/crates/organize/src/view.rs index 0f115d3051..b51df1aa55 100644 --- a/crates/organize/src/view.rs +++ b/crates/organize/src/view.rs @@ -63,6 +63,10 @@ pub struct InitialView { pub language: Option, /// Right-edge binding (`/Direction /R2L`). pub right_to_left: bool, + /// The navigation panel on leaving full screen (`/ViewerPreferences /NonFullScreenPageMode`, + /// ISO 32000-2 Table 147), read only when `full_screen` is set. It is read, not written: + /// [`set_initial_view`] leaves the entry as it is. + pub non_full_screen: Navigation, } fn catalog(doc: &Document) -> Result<(pdfcraft_cos::ObjRef, Dict), OrganizeError> { @@ -104,6 +108,15 @@ pub fn initial_view(doc: &Document) -> InitialView { v.hide_toolbar = flag(b"HideToolbar"); v.hide_window_ui = flag(b"HideWindowUI"); v.right_to_left = name(&vp, b"Direction").as_deref() == Some(b"R2L"); + // Table 147: meaningful only with `/PageMode /FullScreen`, and only these four values. + if v.full_screen { + v.non_full_screen = match name(&vp, b"NonFullScreenPageMode").as_deref() { + Some(b"UseOutlines") => Navigation::Bookmarks, + Some(b"UseThumbs") => Navigation::Pages, + Some(b"UseOC") => Navigation::Layers, + _ => Navigation::PageOnly, + }; + } } // The opening destination: an explicit array, or a GoTo action's. let dest = c.get(b"OpenAction").map(|o| doc.resolve(o)).and_then(|o| match &*o { @@ -149,8 +162,13 @@ pub fn displays_doc_title(doc: &Document) -> bool { } /// Write the initial view. An opening action that isn't a plain destination (a script, say) is -/// kept unless the page or magnification asks for a destination. +/// kept unless the page or magnification asks for a destination, and an opening action whose page +/// and magnification `v` leaves as [`initial_view`] reads them is kept as it is. pub fn set_initial_view(doc: &mut Document, v: &InitialView) -> Result<(), OrganizeError> { + let same_destination = { + let now = initial_view(doc); + now.page == v.page && now.magnification == v.magnification + }; let (root, c) = catalog(doc)?; let pages = crate::walk(doc)?; if v.page >= pages.len() { @@ -238,6 +256,9 @@ pub fn set_initial_view(doc: &mut Document, v: &InitialView) -> Result<(), Organ } } match (&dest, open_action_is_dest) { + // The opening page and magnification are as read: the action stays as written, with + // its position or named destination (§12.3.2.4) that the view model doesn't hold. + _ if same_destination => {} (Some(d), _) => c.set(b"OpenAction".to_vec(), Object::Array(d.clone())), (None, true) => { c.remove(b"OpenAction"); @@ -294,4 +315,40 @@ mod tests { assert_eq!(flags(initial_view(&doc)), [false; 6]); } } + + /// A catalog with `/PageMode page_mode` and `/ViewerPreferences << /NonFullScreenPageMode mode >>`. + fn with_modes(page_mode: &str, mode: Object) -> Document { + let mut doc = Document::new_empty(); + let mode = doc.add(mode); + let mut preferences = Dict::new(); + preferences.set(b"NonFullScreenPageMode".to_vec(), Object::Ref(mode)); + let root = doc.root().unwrap(); + doc.update_dict(root, |c| { + c.set(b"PageMode".to_vec(), Object::name(page_mode)); + c.set(b"ViewerPreferences".to_vec(), Object::Dict(preferences)); + }) + .unwrap(); + doc + } + + #[test] + fn non_full_screen_page_mode_is_read_with_full_screen_only() { + for (mode, want) in [ + ("UseOutlines", Navigation::Bookmarks), + ("UseThumbs", Navigation::Pages), + ("UseOC", Navigation::Layers), + ("UseNone", Navigation::PageOnly), + // Not a value Table 147 lists. + ("UseAttachments", Navigation::PageOnly), + ("FullScreen", Navigation::PageOnly), + ] { + let v = initial_view(&with_modes("FullScreen", Object::name(mode))); + assert!(v.full_screen); + assert_eq!(v.non_full_screen, want, "{mode}"); + // Ignored unless the document opens in full screen. + let v = initial_view(&with_modes("UseThumbs", Object::name(mode))); + assert_eq!((v.navigation, v.non_full_screen), (Navigation::Pages, Navigation::PageOnly), "{mode}"); + } + assert_eq!(initial_view(&with_modes("FullScreen", Object::Int(1))).non_full_screen, Navigation::PageOnly); + } } diff --git a/crates/redact/src/interp.rs b/crates/redact/src/interp.rs index 3380fece14..ffd59a26f6 100644 --- a/crates/redact/src/interp.rs +++ b/crates/redact/src/interp.rs @@ -455,8 +455,8 @@ fn content_draws(doc: &Document, content: &[Vec], xo: &Dict, name: &[u8], de if depth >= MAX_DEPTH { return None; } - let Ok(_data) = s.decoded() else { return None }; - match content_draws(doc, content, xo, name, depth + 1, seen) { + let Ok(data) = s.decoded() else { return None }; + match content_draws(doc, std::slice::from_ref(&data), xo, name, depth + 1, seen) { Some(false) => {} other => return other, } diff --git a/crates/redact/src/tests/surviving_references.rs b/crates/redact/src/tests/surviving_references.rs index d3aa98af67..a297ded2a4 100644 --- a/crates/redact/src/tests/surviving_references.rs +++ b/crates/redact/src/tests/surviving_references.rs @@ -66,3 +66,42 @@ fn an_image_a_surviving_form_draws_is_kept() { assert_eq!(apply(&mut doc, None).unwrap().images_removed, 1); assert!(full_save_holds(&doc, b"IMAGESECRET"), "the image the form still draws outside the mark"); } + +/// The surviving form draws the image through a nested form without /Resources of its own, +/// which draws through the outer form's: the image is kept. +#[test] +fn an_image_a_surviving_forms_nested_form_draws_is_kept() { + let mut doc = pdf(vec![ + b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(), + b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(), + b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Contents 4 0 R /Resources 5 0 R >>".to_vec(), + stream("", b"q 100 0 0 100 0 0 cm /Im Do Q /Fm Do"), + b"<< /XObject << /Im 6 0 R /Fm 7 0 R /Inner 8 0 R >> >>".to_vec(), + stream("/Type /XObject /Subtype /Image /Width 11 /Height 1 /ColorSpace /DeviceGray /BitsPerComponent 8", b"IMAGESECRET"), + stream("/Type /XObject /Subtype /Form /BBox [0 0 300 300] /Resources 5 0 R", b"/Inner Do"), + stream("/Type /XObject /Subtype /Form /BBox [0 0 300 300]", b"q 50 0 0 50 200 200 cm /Im Do Q"), + ]); + mark(&mut doc, 0, &[[0.0, 0.0, 120.0, 120.0]], ""); + assert_eq!(apply(&mut doc, None).unwrap().images_removed, 1); + assert!(full_save_holds(&doc, b"IMAGESECRET"), "the image the nested form still draws outside the mark"); +} + +/// Two pages share one resource dictionary, and the second draws the image only through a form +/// without /Resources: redacting the image on the first page keeps it for the second. +#[test] +fn an_image_another_page_draws_through_a_form_without_resources_is_kept() { + let mut doc = pdf(vec![ + b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(), + b"<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 >>".to_vec(), + b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Contents 5 0 R /Resources 7 0 R >>".to_vec(), + b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Contents 6 0 R /Resources 7 0 R >>".to_vec(), + stream("", b"q 100 0 0 100 0 0 cm /Im Do Q"), + stream("", b"/Inner Do"), + b"<< /XObject << /Im 8 0 R /Inner 9 0 R >> >>".to_vec(), + stream("/Type /XObject /Subtype /Image /Width 11 /Height 1 /ColorSpace /DeviceGray /BitsPerComponent 8", b"IMAGESECRET"), + stream("/Type /XObject /Subtype /Form /BBox [0 0 300 300]", b"q 50 0 0 50 200 200 cm /Im Do Q"), + ]); + mark(&mut doc, 0, &[[0.0, 0.0, 120.0, 120.0]], ""); + assert_eq!(apply(&mut doc, None).unwrap().images_removed, 1); + assert!(full_save_holds(&doc, b"IMAGESECRET"), "the second page still draws the image through its form"); +} diff --git a/crates/render/src/inspect.rs b/crates/render/src/inspect.rs index 26969396a1..827e678567 100644 --- a/crates/render/src/inspect.rs +++ b/crates/render/src/inspect.rs @@ -110,6 +110,10 @@ pub struct DocInfo { pub attachments: Vec, /// Pages with a presentation transition (`/Trans`) or display time (`/Dur`), in page order. pub transitions: Vec, + /// Where the document opens (`/OpenAction`): the (0-based page, view) of its destination, + /// named destinations resolved. `None` without one, for an action that goes nowhere in this + /// document (a script, say), or for one that doesn't resolve to a page of it. + pub open_dest: Option<(usize, DestView)>, pub warnings: Vec, } @@ -401,6 +405,9 @@ pub struct OutlineItem { /// Where on `page` the bookmark goes ([`DestView::Top`] for a bookmark without a page). pub view: DestView, pub children: Vec, + /// Whether the bookmark starts open: only a positive `/Count` says so (ISO 32000-2 §12.3.3, + /// Table 151). A negative one is closed, and so is a missing one, which a bookmark with + /// children should not have. pub open: bool, /// The title's colour (`/C`, DeviceRGB, ISO 32000-2 §12.3.3 Table 151), or `None` for the /// default black or a value that isn't three numbers. @@ -825,6 +832,25 @@ impl<'a> Inspector<'a> { { info.has_javascript = true; } + info.open_dest = catalog.get(b"OpenAction").ok().and_then(|o| self.open_dest(o)); + } + + /// The destination `/OpenAction` opens at (ISO 32000-2 §7.7.2 Table 29): an explicit + /// destination array, a `/GoTo` action's `/D`, or (leniently, since Table 29 asks for an array + /// or an action) a destination name or string; a name or string is looked up as a named + /// destination (§12.3.2.4). Any other action (a script, a remote go-to) has none here, and + /// neither has a page number past the end of the document. + fn open_dest(&self, action: &Object) -> Option<(usize, DestView)> { + let dest = match self.resolve(action) { + Object::Dictionary(d) => { + if d.get(b"S").ok().and_then(|o| self.resolve(o).as_name().ok()) != Some(&b"GoTo"[..]) { + return None; + } + d.get(b"D").ok()? + } + other => other, + }; + self.dest(dest, 0).filter(|(page, _)| *page < self.page_ids.len()) } // ── object helpers ────────────────────────────────────────────────────────────────────── @@ -4114,3 +4140,112 @@ mod open_action_javascript_tests { assert!(!info.has_javascript, "a /GoTo /OpenAction is not JavaScript"); } } + +#[cfg(test)] +mod open_dest_tests { + use std::sync::Arc; + + use super::{DestView, inspect}; + + /// Three 612×792 pages (objects 3, 4, 5); `catalog` is added to the catalog dictionary and + /// `extra` become objects 6, 7, …. + fn pdf(catalog: &str, extra: &[String]) -> Vec { + let mut objs = + vec![format!("<< /Type /Catalog /Pages 2 0 R {catalog} >>"), "<< /Type /Pages /Kids [3 0 R 4 0 R 5 0 R] /Count 3 >>".to_string()]; + for _ in 0..3 { + objs.push("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>".to_string()); + } + objs.extend(extra.iter().cloned()); + let mut out = b"%PDF-1.7\n".to_vec(); + let mut offsets = Vec::new(); + for (i, o) in objs.iter().enumerate() { + offsets.push(out.len()); + out.extend_from_slice(format!("{} 0 obj\n{o}\nendobj\n", i + 1).as_bytes()); + } + let xref = out.len(); + out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes()); + for o in offsets { + out.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes()); + } + out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes()); + out + } + + fn open_dest(catalog: &str, extra: &[String]) -> Option<(usize, DestView)> { + inspect(Arc::new(pdf(catalog, extra)), None).expect("inspects").open_dest + } + + const XYZ: DestView = DestView::Xyz { left: Some(100.0), top: Some(500.0), zoom: Some(2.0) }; + + #[test] + fn an_explicit_destination_opens_at_its_page_and_position() { + assert_eq!(open_dest("/OpenAction [5 0 R /XYZ 100 500 2]", &[]), Some((2, XYZ))); + assert_eq!(open_dest("/OpenAction [4 0 R /FitH 400]", &[]), Some((1, DestView::FitH { top: Some(400.0) }))); + // Indirect, and a zoom of 0 keeps the zoom (Table 149). + assert_eq!( + open_dest("/OpenAction 6 0 R", &["[4 0 R /XYZ 0 792 0]".into()]), + Some((1, DestView::Xyz { left: Some(0.0), top: Some(792.0), zoom: None })) + ); + } + + #[test] + fn a_go_to_action_opens_at_its_destination_explicit_or_named() { + assert_eq!(open_dest("/OpenAction << /S /GoTo /D [5 0 R /XYZ 100 500 2] >>", &[]), Some((2, XYZ))); + // A name, through the PDF 1.1 catalog /Dests dictionary (§12.3.2.4). + assert_eq!(open_dest("/OpenAction << /S /GoTo /D /there >> /Dests << /there [5 0 R /XYZ 100 500 2] >>", &[]), Some((2, XYZ))); + // A byte string, through the /Names /Dests name tree, whose value is a dictionary with /D. + assert_eq!( + open_dest( + "/OpenAction << /S /GoTo /D (there) >> /Names << /Dests 6 0 R >>", + &["<< /Kids [7 0 R] >>".into(), "<< /Names [(here) [3 0 R /Fit] (there) << /D [5 0 R /XYZ 100 500 2] >>] >>".into()] + ), + Some((2, XYZ)) + ); + } + + #[test] + fn an_open_action_given_as_a_name_or_string_is_looked_up() { + assert_eq!(open_dest("/OpenAction /there /Dests << /there [4 0 R /Fit] >>", &[]), Some((1, DestView::Fit))); + assert_eq!( + open_dest("/OpenAction (there) /Names << /Dests << /Names [(there) [5 0 R /FitV 30]] >> >>", &[]), + Some((2, DestView::FitV { left: Some(30.0) })) + ); + } + + #[test] + fn an_open_action_that_goes_nowhere_here_has_no_destination() { + for catalog in [ + "", + "/OpenAction << /S /JavaScript /JS (app.alert(1)) >>", + // A remote go-to's /D is a page of another file. + "/OpenAction << /S /GoToR /F (other.pdf) /D [1 /Fit] >>", + "/OpenAction << /D [4 0 R /Fit] >>", + // An unknown name, and no name dictionaries at all. + "/OpenAction << /S /GoTo /D /missing >> /Dests << /there [4 0 R /Fit] >>", + "/OpenAction /missing", + // A page number past the end, and a page reference that is no page. + "/OpenAction [7 /Fit]", + "/OpenAction [2 0 R /Fit]", + "/OpenAction 42", + ] { + assert_eq!(open_dest(catalog, &[]), None, "{catalog}"); + } + } + + #[test] + fn cyclic_and_deep_named_destinations_end() { + // Names that refer to each other. + assert_eq!(open_dest("/OpenAction /a /Dests << /a /b /b /a >>", &[]), None); + assert_eq!(open_dest("/OpenAction /a /Dests << /a << /D /a >> >>", &[]), None); + // A name tree whose node is its own kid. + assert_eq!(open_dest("/OpenAction (x) /Names << /Dests 6 0 R >>", &["<< /Kids [6 0 R] >>".into()]), None); + // A name tree deeper than the depth bound: the leaf past it isn't read. + let depth = 40; + let mut nodes: Vec = (0..depth).map(|i| format!("<< /Kids [{} 0 R] >>", 7 + i)).collect(); + nodes.push("<< /Names [(x) [4 0 R /Fit]] >>".into()); + assert_eq!(open_dest("/OpenAction (x) /Names << /Dests 6 0 R >>", &nodes), None); + // A shallow one is read. + let shallow = ["<< /Kids [7 0 R] >>".to_string(), "<< /Kids [8 0 R] >>".into(), "<< /Names [(x) [4 0 R /Fit]] >>".into()]; + assert_eq!(open_dest("/OpenAction (x) /Names << /Dests 6 0 R >>", &shallow), Some((1, DestView::Fit))); + } +} diff --git a/crates/render/tests/it/main.rs b/crates/render/tests/it/main.rs index 3c556b6096..bc17f18067 100644 --- a/crates/render/tests/it/main.rs +++ b/crates/render/tests/it/main.rs @@ -6,3 +6,4 @@ mod jbig2_invariants; mod named_form_properties; mod search; mod substitute_widths; +mod tiling_cell_placement; diff --git a/crates/render/tests/it/tiling_cell_placement.rs b/crates/render/tests/it/tiling_cell_placement.rs new file mode 100644 index 0000000000..3a57f15085 --- /dev/null +++ b/crates/render/tests/it/tiling_cell_placement.rs @@ -0,0 +1,191 @@ +//! Tiling pattern cells sit at whole multiples of `/XStep` and `/YStep` in pattern space +//! (ISO 32000-2 8.7.3.1, Table 74), at any rendering scale, however far they are from the +//! pattern's origin. +//! +//! Each page is filled (or stroked) with a pattern whose 20 × 20 cell holds one 6 × 6 blue square +//! at (7, 7). At 110 dpi a step is 30.56 device pixels; every probe finds the blue square in a +//! disc around where the pattern matrix puts it and checks that its centroid is within one +//! device pixel of that place. + +use std::sync::Arc; + +use pdfcraft_render::{PageRenderer, RenderConfig, RenderRequest, RequestKind}; + +/// The rendering scale for 110 dpi: a step of 20 points is 30.56 pixels, not a whole number. +const SCALE: f64 = 110.0 / 72.0; +/// The page is `SIDE` × `SIDE` points. +const SIDE: f64 = 400.0; + +/// One page `SIDE` points square whose content `content` paints with `/P1`: the 20-point cell +/// with its blue square, `/XStep` and `/YStep` 20, under pattern matrix `matrix`. +fn page_pdf(content: &str, matrix: [f64; 6]) -> Vec { + let cell = "0 0 1 rg 7 7 6 6 re f"; + let m = matrix.map(|v| format!("{v}")).join(" "); + 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 {SIDE} {SIDE}] /Contents 4 0 R /Resources << /Pattern << /P1 5 0 R >> >> >> endobj +4 0 obj << /Length {} >> stream +{content} +endstream endobj +5 0 obj << /Type /Pattern /PatternType 1 /PaintType 1 /TilingType 1 /BBox [0 0 20 20] /XStep 20 /YStep 20 /Matrix [{m}] /Length {} >> stream +{cell} +endstream endobj +trailer << /Root 1 0 R >> +%%EOF", + content.len(), + cell.len() + ) + .into_bytes() +} + +struct Page { + rgba: Vec, + width: usize, + height: usize, +} + +fn render(content: &str, matrix: [f64; 6]) -> Page { + let mut r = PageRenderer::new(Arc::new(page_pdf(content, matrix)), RenderConfig::default()); + let page = r.render(RenderRequest { page: 0, kind: RequestKind::Pixels, tile: None, scale: SCALE as f32, tag: 0, ..Default::default() }); + assert!(page.error.is_none(), "{:?}", page.error); + Page { rgba: page.rgba.to_vec(), width: page.width as usize, height: page.height as usize } +} + +/// The device position of pattern-space point `(x, y)`: the pattern matrix to page space, then +/// page space to device pixels (y down). +fn device(matrix: [f64; 6], x: f64, y: f64) -> (f64, f64) { + let [a, b, c, d, e, f] = matrix; + let (px, py) = (a * x + c * y + e, b * x + d * y + f); + (px * SCALE, (SIDE - py) * SCALE) +} + +/// The centroid of blue (weighted by how far each pixel is from white) in the disc of `radius` +/// pixels around `(cx, cy)`, and the total weight. `None` when the disc leaves the page. +fn blue_centroid(page: &Page, cx: f64, cy: f64, radius: f64) -> Option<((f64, f64), f64)> { + let (x0, x1) = ((cx - radius).floor(), (cx + radius).ceil()); + let (y0, y1) = ((cy - radius).floor(), (cy + radius).ceil()); + if x0 < 0.0 || y0 < 0.0 || x1 >= page.width as f64 || y1 >= page.height as f64 { + return None; + } + let (mut sum, mut sx, mut sy) = (0.0, 0.0, 0.0); + for j in (y0 as usize)..=(y1 as usize) { + for i in (x0 as usize)..=(x1 as usize) { + let (px, py) = (i as f64 + 0.5, j as f64 + 0.5); + if (px - cx).powi(2) + (py - cy).powi(2) > radius * radius { + continue; + } + let red = *page.rgba.get((j * page.width + i) * 4)?; + let w = f64::from(255 - red) / 255.0; + sum += w; + sx += w * px; + sy += w * py; + } + } + (sum > 0.0).then(|| ((sx / sum, sy / sum), sum)) +} + +/// Checks every cell `(k, m)` whose blue square's centre falls in the page rectangle `area` +/// (points: x0, y0, x1, y1): its square is found where the matrix puts it, within one pixel. +/// Returns how many cells were checked. +fn assert_cells_in_place(page: &Page, matrix: [f64; 6], area: [f64; 4], what: &str) -> usize { + let [a, b, c, d, _, _] = matrix; + // The square is 6 × 6 at (7, 7); its centre is (10, 10) in the cell. A disc of 6 cell + // units around it holds the whole square (half-diagonal 4.24) and no neighbour (7 away). + let units = (a * a + b * b).sqrt().min((c * c + d * d).sqrt()); + let radius = 6.0 * units * SCALE; + let area_px = 36.0 * units * units * SCALE * SCALE; + let mut checked = 0; + for k in -60..60 { + for m in -60..60 { + let (cx_cell, cy_cell) = (20.0 * f64::from(k) + 10.0, 20.0 * f64::from(m) + 10.0); + let [ea, eb, ec, ed, ee, ef] = matrix; + let (px, py) = (ea * cx_cell + ec * cy_cell + ee, eb * cx_cell + ed * cy_cell + ef); + if px < area[0] || px > area[2] || py < area[1] || py > area[3] { + continue; + } + let (cx, cy) = device(matrix, cx_cell, cy_cell); + let Some(((gx, gy), weight)) = blue_centroid(page, cx, cy, radius) else { continue }; + assert!(weight > 0.8 * area_px, "{what}: cell ({k}, {m}) at ({cx:.1}, {cy:.1}) only partly there: {weight:.1} of {area_px:.1}"); + assert!( + (gx - cx).abs() <= 1.0 && (gy - cy).abs() <= 1.0, + "{what}: cell ({k}, {m}) should be centred at ({cx:.2}, {cy:.2}) px, found at ({gx:.2}, {gy:.2})" + ); + checked += 1; + } + } + checked +} + +const IDENTITY: [f64; 6] = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]; + +/// A fill far from the pattern's origin: the cells 300 to 400 points away (15 to 19 steps) are +/// where 15 to 19 steps put them, not 0.44 pixel further for every step. +#[test] +fn far_cells_of_a_fill_sit_at_whole_steps() { + let page = render("/Pattern cs /P1 scn 0 0 400 400 re f", IDENTITY); + let near = assert_cells_in_place(&page, IDENTITY, [0.0, 0.0, 100.0, 100.0], "near the origin"); + let far = assert_cells_in_place(&page, IDENTITY, [290.0, 290.0, 400.0, 400.0], "far from the origin"); + assert!(near >= 16 && far >= 16, "{near} near, {far} far"); +} + +/// The same under a pattern matrix that scales by 1.49 and turns by 30 degrees: a step is +/// 45.5 pixels along each turned axis. +#[test] +fn far_cells_sit_at_whole_steps_under_a_turned_scaled_matrix() { + let (scale, turn) = (1.49_f64, 30_f64.to_radians()); + let matrix = [scale * turn.cos(), scale * turn.sin(), -scale * turn.sin(), scale * turn.cos(), 3.0, 5.0]; + let page = render("/Pattern cs /P1 scn 0 0 400 400 re f", matrix); + let far = assert_cells_in_place(&page, matrix, [250.0, 250.0, 390.0, 390.0], "turned and scaled"); + assert!(far >= 6, "{far} cells checked"); +} + +/// A stroke painted with the pattern: the cells under a wide border far from the origin are +/// in place on every side of it. +#[test] +fn far_cells_of_a_stroke_sit_at_whole_steps() { + let page = render("/Pattern CS /P1 SCN 40 w 200 200 180 180 re S", IDENTITY); + let mut checked = 0; + // The border is 40 points wide around the square from (200, 200) to (380, 380). + for band in [[180.0, 180.0, 400.0, 220.0], [180.0, 360.0, 400.0, 400.0], [180.0, 180.0, 220.0, 400.0], [360.0, 180.0, 400.0, 400.0]] { + checked += assert_cells_in_place(&page, IDENTITY, band, "stroke"); + } + assert!(checked >= 20, "{checked} cells checked"); + // Inside the border nothing is painted. + let (cx, cy) = device(IDENTITY, 290.0, 290.0); + let at = ((cy as usize) * page.width + cx as usize) * 4; + assert_eq!(page.rgba.get(at..at + 3), Some(&[255, 255, 255][..]), "inside the stroked square"); +} + +/// The cell pixmap's side and the scale its cell is drawn at: one step is exactly the side, the +/// side stays within 1 and the cap whatever the step, and nothing odd reaches the cast. +#[test] +fn a_cell_pixmap_spans_exactly_one_step() { + // 110 dpi, a step of 20: 30.56 pixels, drawn at 31 / 20. + assert_eq!(hayro::tiling_cell_pixels(110.0 / 72.0, 20.0, 3000.0), (31, 31.0 / 20.0)); + assert_eq!(hayro::tiling_cell_pixels(110.0 / 72.0, -20.0, 3000.0), (31, 31.0 / 20.0), "a negative step"); + for (scale, step) in [(1.0_f32, 7.3_f32), (2.37, 0.9), (0.013, 1234.5), (3.0, 999.9), (1.0, 2.0e9)] { + let (side, drawn) = hayro::tiling_cell_pixels(scale, step, 3000.0); + assert!((1..=3000).contains(&side), "{scale} {step}: {side}"); + let span = drawn * f64::from(step); + assert!((span - f64::from(side)).abs() < 1e-9 * f64::from(side), "{scale} {step}: a step spans {span}, not {side}"); + if f64::from(scale) * f64::from(step) <= 3000.0 { + assert!((span - f64::from(scale) * f64::from(step)).abs() <= 0.5 + 1e-9, "{scale} {step}: drawn {drawn}"); + } + } + // A step under half a pixel still gets one pixel (a 0 × N pixmap can't be sampled). + assert_eq!(hayro::tiling_cell_pixels(0.03, 10.0, 3000.0), (1, 0.1)); + // Steps and scales that aren't finite and positive: the side is bounded, the scale kept. + assert_eq!(hayro::tiling_cell_pixels(2.0, f32::INFINITY, 3000.0), (3000, 2.0)); + assert_eq!(hayro::tiling_cell_pixels(2.0, 0.0, 3000.0), (1, 2.0)); + let (side, drawn) = hayro::tiling_cell_pixels(f32::NAN, 20.0, 3000.0); + assert!(side == 1 && drawn.is_nan()); + // A cap past u16::MAX is lowered to it, and the scale follows the side the pixmap gets. + let (side, drawn) = hayro::tiling_cell_pixels(2.0, 1.0e6, 1.0e9); + assert_eq!(side, u16::MAX, "the cap is at most u16::MAX"); + assert!((drawn * 1.0e6 - f64::from(u16::MAX)).abs() < 1e-6, "a step spans the side: {drawn}"); + // A cap that is not a whole number, or not a number, is a whole number of pixels. + assert_eq!(hayro::tiling_cell_pixels(1.0, 100.0, 30.7), (30, 0.3)); + assert_eq!(hayro::tiling_cell_pixels(1.0, 100.0, f32::NAN), (1, 0.01)); +} diff --git a/crates/ui-egui/src/calc_order_ui.rs b/crates/ui-egui/src/calc_order_ui.rs index a9a726d241..894fe17929 100644 --- a/crates/ui-egui/src/calc_order_ui.rs +++ b/crates/ui-egui/src/calc_order_ui.rs @@ -752,7 +752,7 @@ pub(crate) fn paint_page( let pointer = ui.input(|i| i.pointer.hover_pos()); let hovered = pointer.and_then(|p| on_page.iter().rev().find(|(_, r)| r.contains(p))).map(|(n, _)| (*n).to_owned()); let at: HashMap<&str, Rect> = on_page.iter().copied().collect(); - let zoom = (xf.rect.width() / xf.pw.max(1.0)).clamp(0.5, 3.0); + let zoom = xf.zoom().clamp(0.5, 3.0); let focus = if view.hide_links { None } else { view.focus(selected) }; // The focus's links, and the fields at either end of them (with the focus itself). let shown: Vec<&Link> = focus.as_deref().map(|f| listed.links.iter().filter(|l| l.from == f || l.to == f).collect()).unwrap_or_default(); diff --git a/crates/ui-egui/src/commands.rs b/crates/ui-egui/src/commands.rs index 909c976284..78f50b49d6 100644 --- a/crates/ui-egui/src/commands.rs +++ b/crates/ui-egui/src/commands.rs @@ -391,6 +391,7 @@ impl PdfCraftApp { }; self.marks_draft.replace = id.ends_with(".update"); self.marks_draft.opened(kind); + self.marks_draft.preview = None; self.dialog = Some(Dialog::Marks(kind)); } "edit.bates" => { @@ -401,6 +402,7 @@ impl PdfCraftApp { self.marks_draft.hf.text[5] = "<>".into(); } self.marks_draft.focused_box = 5; + self.marks_draft.preview = None; self.dialog = Some(Dialog::Marks(pdfcraft_engine::MarkKind::HeaderFooter)); } "edit.header_footer.remove" | "edit.watermark.remove" | "edit.background.remove" => { diff --git a/crates/ui-egui/src/content_ui.rs b/crates/ui-egui/src/content_ui.rs index d966b04a58..2ac624d3fc 100644 --- a/crates/ui-egui/src/content_ui.rs +++ b/crates/ui-egui/src/content_ui.rs @@ -510,7 +510,7 @@ pub(crate) fn after_refresh(view: &mut DocView, added: &[Added]) { pub(crate) fn editor(ctx: &egui::Context, view: &mut DocView, info: &DocInfo, added: &[Added]) -> (Option, bool) { let Some(page) = view.content.draft.as_ref().map(|d| d.page) else { return (None, false) }; let Some(xf) = view.page_xform(page) else { return (None, false) }; - let zoom = xf.rect.width() / xf.pw.max(1.0); + let zoom = xf.zoom(); let Some(draft) = view.content.draft.as_mut() else { return (None, false) }; let font = crate::edit_text_ui::editor_font(&draft.style, (draft.style.size as f32 * zoom).clamp(1.0, 300.0)); let text = AddedText { text: draft.text.clone(), ..draft.style.clone() }; diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 1099030ea7..086dd2346c 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -36,6 +36,7 @@ fn dialogs(app: &mut PdfCraftApp, ctx: &egui::Context) { let Some(dialog) = app.dialog else { app.props_draft = None; app.view_draft = None; + app.custom_draft = None; return; }; // Properties ▸ Fonts shows the fonts as they are now, after any content edits. @@ -49,6 +50,7 @@ fn dialogs(app: &mut PdfCraftApp, ctx: &egui::Context) { { app.props_draft = Some((id, INFO_KEYS.map(|k| doc.info_value(k).unwrap_or_default()))); app.view_draft = Some((id, doc.initial_view())); + app.custom_draft = Some((id, crate::CustomDraft { props: doc.custom_info(), ..Default::default() })); } let mut apply = false; let mut split_now: Option = None; @@ -114,6 +116,7 @@ fn dialogs(app: &mut PdfCraftApp, ctx: &egui::Context) { (PropsTab::InitialView, tl!("Initial View")), (PropsTab::Security, tl!("Security")), (PropsTab::Fonts, tl!("Fonts")), + (PropsTab::Custom, tl!("Custom")), (PropsTab::Advanced, tl!("Advanced")), ] { if widgets::mode_tab(ui, label, tab == tb).clicked() { @@ -345,6 +348,89 @@ fn dialogs(app: &mut PdfCraftApp, ctx: &egui::Context) { row(ui, &f.name, detail); } } + PropsTab::Custom => { + // Add takes a new name, Update changes the value of the listed property the + // Name field names, Delete removes it; OK writes the changes as one step. + let editable = doc.allows_modification(); + let Some((_, d)) = app.custom_draft.as_mut() else { return }; + let l = ui.label(egui::RichText::new(tl!("Name:")).color(t.text_muted)); + ui.add_enabled( + editable, + widgets::line(&mut d.name).desired_width(420.0).background_color(t.field).id_salt("custom-name"), + ) + .labelled_by(l.id); + ui.end_row(); + let l = ui.label(egui::RichText::new(tl!("Value:")).color(t.text_muted)); + ui.add_enabled( + editable, + widgets::line(&mut d.value).desired_width(420.0).background_color(t.field).id_salt("custom-value"), + ) + .labelled_by(l.id); + ui.end_row(); + // Untrimmed: a file's `/Project#20` is not `/Project`, and a typed space is refused. + let name = d.name.clone(); + let value = d.value.trim().to_owned(); + let listed = d.props.iter().position(|(k, _)| *k == name); + // An entry the list leaves out (not text, only padding, or past its 256) keeps its value. + let file_props = doc.custom_info(); + let unlisted = doc.has_info(&name) && !file_props.iter().any(|(k, _)| *k == name); + let refused = pdfcraft_engine::check_custom_key(&name).err().filter(|_| !name.is_empty()).map(|e| e.to_string()); + ui.label(""); + // A file can hold a custom name that `check_custom_key` refuses, such as one + // with a space: the tab lists it, and Add, Update and Delete stay off for it. + let why = |b: egui::Response| match &refused { + Some(why) => b.on_disabled_hover_text(crate::i18n::words(why)), + None => b, + }; + // A name that isn't UTF-8 is listed with U+FFFD and can't be written back as it is. + let editable = editable && refused.is_none() && !name.contains(char::REPLACEMENT_CHARACTER); + // `custom_info` lists at most 256 properties, and a new name goes after the file's + // entries, so Add is off once the draft or the file's own list holds 256. + let room = d.props.len() < 256 && file_props.len() < 256; + ui.horizontal(|ui| { + let add = editable && room && listed.is_none() && !unlisted && !name.is_empty() && !value.is_empty(); + if why(ui.add_enabled(add, egui::Button::new(tl!("Add")))).clicked() { + d.props.push((name.clone(), value.clone())); + d.name.clear(); + d.value.clear(); + } + let update = editable && !value.is_empty() && listed.and_then(|n| d.props.get(n)).is_some_and(|(_, v)| *v != value); + if why(ui.add_enabled(update, egui::Button::new(tl!("Update")))).clicked() + && let Some(p) = listed.and_then(|n| d.props.get_mut(n)) + { + p.1 = value.clone(); + } + if why(ui.add_enabled(editable && listed.is_some(), egui::Button::new(tl!("Delete")))).clicked() + && let Some(n) = listed.filter(|n| *n < d.props.len()) + { + d.props.remove(n); + d.name.clear(); + d.value.clear(); + } + }); + ui.end_row(); + if d.props.is_empty() { + ui.label(""); + ui.label(egui::RichText::new(tl!("None")).color(t.text_faint)); + ui.end_row(); + } + // A click on a property fills the fields with it; values are document data. + let mut picked = None; + for (k, v) in &d.props { + if ui.selectable_label(*k == name, k.as_str()).clicked() { + picked = Some((k.clone(), v.clone())); + } + ui.scope(|ui| { + ui.set_max_width(420.0); + ui.add(egui::Label::new(v.as_str()).wrap()); + }); + ui.end_row(); + } + if let Some((k, v)) = picked { + d.name = k; + d.value = v; + } + } PropsTab::Advanced => { row(ui, "PDF version", i.pdf_version.clone()); row(ui, "Location", crate::bidi::visual(doc.path.as_deref().unwrap_or_default()).into_owned()); @@ -1443,6 +1529,7 @@ fn dialogs(app: &mut PdfCraftApp, ctx: &egui::Context) { app.dialog = None; app.props_draft = None; app.view_draft = None; + app.custom_draft = None; app.bulk_field_props = None; } else { app.dialog = Some(next); @@ -1494,6 +1581,18 @@ fn draft_changes(app: &PdfCraftApp) -> Option> { { edits.push(Edit::SetInitialView(Box::new(v.clone()))); } + // Custom: deleted properties are cleared, then added and changed ones are set. + if let Some((cid, d)) = &app.custom_draft + && cid == id + { + let before = doc.custom_info(); + for (k, _) in before.iter().filter(|(k, _)| !d.props.iter().any(|(n, _)| n == k)) { + edits.push(Edit::SetInfo { key: k.clone(), value: String::new() }); + } + for (k, v) in d.props.iter().filter(|(k, v)| !before.iter().any(|(n, w)| n == k && w == v)) { + edits.push(Edit::SetInfo { key: k.clone(), value: v.clone() }); + } + } Some(edits) } diff --git a/crates/ui-egui/src/field_table_ui.rs b/crates/ui-egui/src/field_table_ui.rs index 9314dc927d..d9b5255bfd 100644 --- a/crates/ui-egui/src/field_table_ui.rs +++ b/crates/ui-egui/src/field_table_ui.rs @@ -342,11 +342,37 @@ fn column_bar(ui: &mut egui::Ui, d: &mut FieldTableDraft, t: &theme::Tokens) { }) .collect() }; + let n = d.table.columns.len(); + let ends = edges(&d.shares()); + let active = column_dividers(ui, d, bar, &ends); + + let painter = ui.painter_at(bar); + // Input may have resized a pair; paint the shares after handling it. + let shares = d.shares(); + let mut left = bar.left(); + for (c, (&right, share)) in edges(&shares).iter().zip(&shares).enumerate() { + // The last column ends at the bar's edge, whatever rounding says. + let right = if c + 1 == n { bar.right() } else { right.min(bar.right()) }; + let column = Rect::from_min_max(pos2(left, bar.top()), pos2(right, bar.bottom())); + painter.rect_filled(column, CornerRadius::ZERO, SELECT_BLUE.gamma_multiply(if c % 2 == 0 { 0.11 } else { 0.055 })); + if column.width() > 32.0 { + painter.text(column.center(), egui::Align2::CENTER_CENTER, format!("{:.0}%", share * 100.0), theme::medium(11.0), t.text); + } + left = right; + } + painter.rect_stroke(bar, CornerRadius::same(3), Stroke::new(1.0, t.border), egui::StrokeKind::Inside); + for (i, &x) in edges(&shares).iter().enumerate().take(n.saturating_sub(1)) { + let stroke = if active == Some(i) { Stroke::new(3.0, SELECT_BLUE) } else { Stroke::new(1.5, t.border) }; + painter.line_segment([pos2(x, bar.top() + 1.0), pos2(x, bar.bottom() - 1.0)], stroke); + } +} + +/// Handle input at the pre-interaction edges and return the hovered, dragged or focused divider. +fn column_dividers(ui: &mut egui::Ui, d: &mut FieldTableDraft, bar: Rect, ends: &[f32]) -> Option { let n = d.table.columns.len(); // Wide enough to grab, never reaching past the middle of a column. let reach = (bar.width() / n.max(1) as f32 / 2.0).clamp(2.0, 8.0); let mut active = None; - let ends = edges(&d.shares()); for (i, &x) in ends.iter().enumerate().take(n.saturating_sub(1)) { let hit = Rect::from_min_max(pos2(x - reach, bar.top()), pos2(x + reach, bar.bottom())); let resp = ui.interact(hit, ui.id().with(("field table divider", i)), Sense::click_and_drag()); @@ -374,24 +400,7 @@ fn column_bar(ui: &mut egui::Ui, d: &mut FieldTableDraft, t: &theme::Tokens) { } } - let painter = ui.painter_at(bar); - let shares = d.shares(); - let mut left = bar.left(); - for (c, (&right, share)) in edges(&shares).iter().zip(&shares).enumerate() { - // The last column ends at the bar's edge, whatever rounding says. - let right = if c + 1 == n { bar.right() } else { right.min(bar.right()) }; - let column = Rect::from_min_max(pos2(left, bar.top()), pos2(right, bar.bottom())); - painter.rect_filled(column, CornerRadius::ZERO, SELECT_BLUE.gamma_multiply(if c % 2 == 0 { 0.11 } else { 0.055 })); - if column.width() > 32.0 { - painter.text(column.center(), egui::Align2::CENTER_CENTER, format!("{:.0}%", share * 100.0), theme::medium(11.0), t.text); - } - left = right; - } - painter.rect_stroke(bar, CornerRadius::same(3), Stroke::new(1.0, t.border), egui::StrokeKind::Inside); - for (i, &x) in edges(&shares).iter().enumerate().take(n.saturating_sub(1)) { - let stroke = if active == Some(i) { Stroke::new(3.0, SELECT_BLUE) } else { Stroke::new(1.5, t.border) }; - painter.line_segment([pos2(x, bar.top() + 1.0), pos2(x, bar.bottom() - 1.0)], stroke); - } + active } /// The table being set up, on its page: each cell with its name, or the table's outline in red @@ -401,7 +410,7 @@ pub(crate) fn paint_preview(painter: &egui::Painter, xf: &PageXform, page: usize if preview.page != page { return; } - let zoom = (xf.rect.width() / xf.pw.max(1.0)).clamp(0.5, 3.0); + let zoom = xf.zoom().clamp(0.5, 3.0); let font = theme::regular((9.0 * zoom).clamp(7.0, 13.0)); let on_screen = |r: [f64; 4]| xf.view_rect([r[0] as f32, r[1] as f32, r[2] as f32, r[3] as f32]); let outline = on_screen(preview.laid.table.rect); @@ -448,6 +457,62 @@ mod tests { d } + fn bar_frame(ctx: &egui::Context, d: &mut FieldTableDraft, key: Option, focus: Option) -> egui::FullOutput { + let events = key + .into_iter() + .flat_map(|key| { + [true, false].map(|pressed| egui::Event::Key { key, physical_key: None, pressed, repeat: false, modifiers: egui::Modifiers::NONE }) + }) + .collect(); + ctx.run_ui( + egui::RawInput { screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(400.0, 160.0))), events, ..Default::default() }, + |ui| { + let other = ui.button("Other control"); + if let Some(i) = focus { + ui.memory_mut(|memory| memory.request_focus(ui.id().with(("field table divider", i)))); + } else { + other.request_focus(); + } + column_bar(ui, d, &theme::Tokens::get(ctx)); + }, + ) + } + + #[test] + fn arrow_keys_resize_only_the_focused_pair_and_paint_its_new_widths() { + for columns in [3, 30] { + let ctx = egui::Context::default(); + ctx.set_fonts(theme::font_definitions()); + let mut d = draft(columns); + let before: Vec = d.table.columns.iter().map(|c| c.width).collect(); + let total: f64 = before.iter().sum(); + bar_frame(&ctx, &mut d, None, Some(0)).drop_without_applying_deltas(); + let output = bar_frame(&ctx, &mut d, Some(egui::Key::ArrowRight), Some(0)); + assert!((d.table.columns[0].width - before[0] - total * 0.01).abs() < 1e-9); + assert!((d.table.columns[1].width - before[1] + total * 0.01).abs() < 1e-9); + assert_eq!(d.table.columns.iter().skip(2).map(|c| c.width).collect::>(), before[2..]); + let painted: Vec = output + .shapes + .iter() + .filter_map(|shape| match &shape.shape { + egui::Shape::Rect(r) if r.fill == SELECT_BLUE.gamma_multiply(0.11) || r.fill == SELECT_BLUE.gamma_multiply(0.055) => Some(r.rect), + _ => None, + }) + .collect(); + assert_eq!(painted.len(), columns); + let width: f32 = painted.iter().map(Rect::width).sum(); + assert!((f64::from(painted[0].width() / width) - d.shares()[0]).abs() < 1e-6, "paint the changed shares in the same frame"); + output.drop_without_applying_deltas(); + bar_frame(&ctx, &mut d, Some(egui::Key::ArrowLeft), Some(0)).drop_without_applying_deltas(); + assert!(d.table.columns.iter().zip(&before).all(|(c, w)| (c.width - w).abs() < 1e-9), "left reverses right on the focused divider"); + bar_frame(&ctx, &mut d, Some(egui::Key::ArrowRight), None).drop_without_applying_deltas(); + assert!( + d.table.columns.iter().zip(&before).all(|(c, w)| (c.width - w).abs() < 1e-9), + "arrows on another control leave the columns alone" + ); + } + } + /// Thirty even columns leave each pair less than twice the least share a divider keeps: the /// two bounds crossed, and `f64::clamp` panicked on the first drag. #[test] diff --git a/crates/ui-egui/src/fill_sign.rs b/crates/ui-egui/src/fill_sign.rs index 64c8ee0d40..1684c80bea 100644 --- a/crates/ui-egui/src/fill_sign.rs +++ b/crates/ui-egui/src/fill_sign.rs @@ -712,7 +712,7 @@ pub(crate) fn type_box(ctx: &egui::Context, view: &mut DocView, info: &DocInfo, let xf = view.page_xform(tb.page)?; let v = info.pages.get(tb.page)?.user_to_view(tb.at[0] as f32, tb.at[1] as f32); let pos = xf.norm_to_screen(v[0] / xf.pw, v[1] / xf.ph); - let zoom = xf.rect.width() / xf.pw.max(1.0); + let zoom = xf.zoom(); let mut commit = false; let mut cancel = false; // Shown at once, like the paragraph editor: a fade-in shows the page's copy through it. diff --git a/crates/ui-egui/src/forms_ui.rs b/crates/ui-egui/src/forms_ui.rs index 5c3b91a393..760c0b6cb6 100644 --- a/crates/ui-egui/src/forms_ui.rs +++ b/crates/ui-egui/src/forms_ui.rs @@ -577,7 +577,7 @@ pub(crate) fn overlay( return None; }; let rect = widget_rect(&xf, info, page, w.rect); - let zoom = xf.rect.width() / xf.pw.max(1.0); + let zoom = xf.zoom(); let t = Tokens::get(ctx); let mut edit = None; let mut close = false; diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 09312b8444..b6f1e0ea0c 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -374,9 +374,19 @@ pub enum PropsTab { InitialView, Security, Fonts, + Custom, Advanced, } +/// Document Properties ▸ Custom being edited: the properties as they will be after OK, in order, +/// and the Name and Value fields. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct CustomDraft { + pub props: Vec<(String, String)>, + pub name: String, + pub value: String, +} + /// Duplicate Field: the field and the pages (all, or a range, 1-based). #[derive(Clone, Debug, PartialEq)] pub struct DuplicateDraft { @@ -782,6 +792,8 @@ pub struct PdfCraftApp { pub props_draft: Option<(DocId, [String; 4])>, /// Document Properties ▸ Initial View (and reading options) being edited. pub view_draft: Option<(DocId, pdfcraft_engine::InitialView)>, + /// Document Properties ▸ Custom being edited. + pub custom_draft: Option<(DocId, CustomDraft)>, /// Files picked asynchronously for combine / insert (web). pub requests: files::Requests, /// Native file pickers in flight (they never block the frame; see `pickers`). @@ -1161,6 +1173,7 @@ impl PdfCraftApp { save_override: None, props_draft: None, view_draft: None, + custom_draft: None, requests: Default::default(), #[cfg(not(target_arch = "wasm32"))] pickers: Default::default(), @@ -1284,14 +1297,19 @@ impl PdfCraftApp { } /// Open a document the way it asks to be opened: navigation panel, layout, magnification, - /// page (Document Properties ▸ Initial View). With Always use my default zoom and page - /// layout on, the layout and magnification stay at the defaults the view opened with. + /// page and the place on it (Document Properties ▸ Initial View, `/OpenAction`). With Always + /// use my default zoom and page layout on, the layout and magnification stay at the defaults + /// the view opened with, and the view goes to the opening page's top. fn apply_initial_view(&mut self, index: usize, v: &pdfcraft_engine::InitialView) { use pdfcraft_engine::{InitialLayout as L, Magnification as M, Navigation as N}; let pages = self.session.get(self.views[index].id).map_or(0, |d| d.info.pages.len()); // A right panel the user closed stays closed, whatever the document asks for (#2884). + // A document that asks for full screen gets the panel it names for outside it + // (`/NonFullScreenPageMode`, Table 147), there when the prompt is declined or full + // screen is left. + let navigation = if v.full_screen { v.non_full_screen } else { v.navigation }; if self.active == Some(index) && !self.right_panel_closed { - match v.navigation { + match navigation { N::PageOnly => {} N::Bookmarks => self.right = Some(RightPanel::Bookmarks), N::Pages => self.right = Some(RightPanel::Pages), @@ -1325,8 +1343,19 @@ impl PdfCraftApp { M::FitHeight => view.fit = canvas::Fit::Height, } } - if v.page > 0 && v.page < pages { - view.go_to_page(v.page); + // The opening destination (`/OpenAction`, named destinations resolved): its page, and + // where on it and how large, as a bookmark or link to it would (ISO 32000-2 Table 149). + // With the default view kept, only the page. + let info = self.session.get(view.id).map(|d| &d.info); + match info.and_then(|i| i.open_dest.filter(|(page, _)| *page < pages).map(|d| (i, d))) { + Some((info, (page, dest))) if !self.always_default_view => view.go_to_dest(page, dest, info), + Some((_, (page, _))) => { + if page > 0 { + view.go_to_page(page); + } + } + None if v.page > 0 && v.page < pages => view.go_to_page(v.page), + None => {} } } @@ -1526,16 +1555,18 @@ impl PdfCraftApp { // Read mode opens with the panes closed; the rail still opens them (#932). A right panel // the user closed stays closed (#1590). let opening_mode = self.mode_override.unwrap_or(self.default_mode); + let initial = doc.initial_view(); if activate && self.right.is_none() && !self.right_panel_closed && opening_mode != Mode::Read { self.right = if !doc.info.annotations.is_empty() { Some(RightPanel::Comments) - } else if !doc.info.outline.is_empty() { + // A full-screen document names its panel for outside full screen, and with + // `/NonFullScreenPageMode /UseNone` (the default) no outline is visible (Table 147). + } else if !doc.info.outline.is_empty() && !initial.full_screen { Some(RightPanel::Bookmarks) } else { None }; } - let initial = doc.initial_view(); let view = DocView::new(id, &doc.info, self.view_defaults); self.views.push(view); if activate { @@ -2867,6 +2898,7 @@ impl PdfCraftApp { "properties" => Some(Dialog::Properties(PropsTab::Description)), "security" => Some(Dialog::Properties(PropsTab::Security)), "fonts" => Some(Dialog::Properties(PropsTab::Fonts)), + "custom" => Some(Dialog::Properties(PropsTab::Custom)), "advanced" => Some(Dialog::Properties(PropsTab::Advanced)), "shortcuts" => Some(Dialog::Shortcuts), "split" => Some(Dialog::Split), diff --git a/crates/ui-egui/src/marks_ui.rs b/crates/ui-egui/src/marks_ui.rs index b5f2d5bf24..b4c930e624 100644 --- a/crates/ui-egui/src/marks_ui.rs +++ b/crates/ui-egui/src/marks_ui.rs @@ -7,7 +7,7 @@ use egui::{Align, Color32, CornerRadius, Layout, Rect, Stroke, pos2, vec2}; use pdfcraft_engine::{Backdrop, Background, DocId, Edit, FontFamily, HeaderFooter, MarkKind, Watermark}; use crate::theme::{self, Tokens}; -use crate::{PdfCraftApp, widgets}; +use crate::{PdfCraftApp, icons, widgets}; /// How far a watermark may be moved from the page centre, in points. const MAX_OFFSET: f64 = 20_000.0; @@ -199,6 +199,9 @@ pub struct MarksDraft { pub file_page: usize, /// Background: pages that paint their own backdrop. pub backdrops: BackdropCheck, + /// The page (0-based) the preview was stepped to; `None` previews the current page. Reset + /// each time the dialog opens. + pub preview: Option, } impl Default for MarksDraft { @@ -217,6 +220,7 @@ impl Default for MarksDraft { file: None, file_page: 1, backdrops: BackdropCheck::default(), + preview: None, } } } @@ -282,6 +286,24 @@ fn preview_page(range: &PageRange, current: usize, count: usize) -> usize { if pages.contains(¤t) { current } else { pages.first().copied().unwrap_or(current) } } +/// [`preview_page`] for the page stepped to (`stepped`), or the current page if none. A page +/// stepped to that the range leaves out is replaced by the page shown, so widening the range again +/// keeps that page rather than jumping back. +fn shown_preview(range: &PageRange, stepped: &mut Option, current: usize, count: usize) -> usize { + let shown = preview_page(range, stepped.unwrap_or(current), count); + if stepped.is_some() { + *stepped = Some(shown); + } + shown +} + +/// The page the preview steps to from `shown`: the range's next page after it (`forward`) or the +/// last one before it, or `None` at either end. +fn step_preview(range: &PageRange, shown: usize, count: usize, forward: bool) -> Option { + let pages = range.pages(count); + if forward { pages.into_iter().find(|&p| p > shown) } else { pages.into_iter().rev().find(|&p| p < shown) } +} + /// The dialog for `kind`; returns (apply, cancel). pub(crate) fn body(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens, kind: MarkKind) -> (bool, bool) { let Some((i, id)) = app.active_ids() else { return (false, true) }; @@ -456,10 +478,10 @@ pub(crate) fn body(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens, kind: M ui.label(egui::RichText::new(tl!("Page Range Options")).font(theme::semibold(12.5))); d.range.ui(ui, count); ui.add_space(8.0); - // The preview: the current page, or the first one the range selects if it leaves that out, - // drawn from its thumbnail at its displayed size (after /Rotate), the frame the engine lays - // the marks out in. - let target = preview_page(&d.range, current, count); + // The preview: the current page (or the page stepped to), or the first one the range selects + // if it leaves that out, drawn from its thumbnail at its displayed size (after /Rotate), the + // frame the engine lays the marks out in. + let target = shown_preview(&d.range, &mut d.preview, current, count); let page = doc.info.pages.get(target).map(|p| (p.width as f64, p.height as f64)).unwrap_or((612.0, 792.0)); let picture = app.views.get_mut(i).and_then(|view| { view.need_thumbnail(target, true); @@ -538,14 +560,24 @@ pub(crate) fn body(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens, kind: M MarkKind::Background => {} }); ui.vertical(|ui| { - ui.label( - egui::RichText::new(crate::i18n::fmt( - tl!("Preview: page {p} of {n}"), - &[("p", &(target + 1).to_string()), ("n", &count.to_string())], - )) - .small() - .color(t.text_faint), - ); + ui.horizontal(|ui| { + // Steps through the pages the range selects. + let (back, next) = (step_preview(&d.range, target, count, false), step_preview(&d.range, target, count, true)); + if ui.add_enabled_ui(back.is_some(), |ui| icons::button(ui, "chevron-left", 22.0, false, tl!("Previous page"))).inner.clicked() { + d.preview = back.or(d.preview); + } + ui.label( + egui::RichText::new(crate::i18n::fmt( + tl!("Preview: page {p} of {n}"), + &[("p", &(target + 1).to_string()), ("n", &count.to_string())], + )) + .small() + .color(t.text_faint), + ); + if ui.add_enabled_ui(next.is_some(), |ui| icons::button(ui, "chevron-right", 22.0, false, tl!("Next page"))).inner.clicked() { + d.preview = next.or(d.preview); + } + }); let n = d.range.pages(count).len(); let applies = if n == 1 { tl!("Applies to 1 page").to_string() } else { crate::i18n::fmt(tl!("Applies to {n} pages"), &[("n", &n.to_string())]) }; @@ -751,6 +783,40 @@ mod tests { assert_eq!(preview_page(&all, 0, 0), 0, "no pages at all"); } + #[test] + fn the_preview_steps_through_the_pages_the_range_selects() { + let odd = PageRange { all: true, subset: Subset::Odd, ..PageRange::default() }; + // Pages 1, 3 and 5 (0-based 0, 2, 4) of 5. + assert_eq!(step_preview(&odd, 0, 5, true), Some(2)); + assert_eq!(step_preview(&odd, 2, 5, true), Some(4)); + assert_eq!(step_preview(&odd, 4, 5, true), None, "the last page has no next"); + assert_eq!(step_preview(&odd, 4, 5, false), Some(2)); + assert_eq!(step_preview(&odd, 0, 5, false), None, "the first page has no previous"); + // From a page the range leaves out, to the nearest one it selects on that side. + assert_eq!(step_preview(&odd, 1, 5, true), Some(2)); + assert_eq!(step_preview(&odd, 1, 5, false), Some(0)); + assert_eq!(step_preview(&odd, 0, 0, true), None, "no pages at all"); + // A page stepped to is previewed while the range selects it, and the range's first page + // once a new range leaves it out. + assert_eq!(preview_page(&odd, 2, 5), 2); + let later = PageRange { all: false, from: 4, to: 5, subset: Subset::All }; + assert_eq!(preview_page(&later, 2, 5), 3); + // Narrowing the range past the page stepped to keeps the page shown instead, also once + // the range is widened again. + let mut stepped = Some(4); + let first_two = PageRange { all: false, from: 1, to: 2, subset: Subset::All }; + assert_eq!(shown_preview(&first_two, &mut stepped, 1, 5), 0); + assert_eq!(stepped, Some(0)); + assert_eq!(shown_preview(&PageRange::default(), &mut stepped, 1, 5), 0); + // A page stepped to inside the range stays; with none stepped to, the current page shows. + let mut stepped = Some(2); + assert_eq!(shown_preview(&odd, &mut stepped, 0, 5), 2); + assert_eq!(stepped, Some(2)); + let mut stepped = None; + assert_eq!(shown_preview(&odd, &mut stepped, 4, 5), 4); + assert_eq!(stepped, None); + } + #[test] fn a_background_tints_the_page_it_is_behind() { assert_eq!(behind([1.0, 0.0, 0.0], 1.0), Color32::from_rgb(255, 0, 0)); diff --git a/crates/ui-egui/src/measure_ui.rs b/crates/ui-egui/src/measure_ui.rs index 658457499a..7c675c694a 100644 --- a/crates/ui-egui/src/measure_ui.rs +++ b/crates/ui-egui/src/measure_ui.rs @@ -208,7 +208,7 @@ pub(crate) fn page_input( if state.paths.as_ref().is_none_or(|(p, g, _)| *p != page || *g != doc.edit_generation()) { state.paths = Some((page, doc.edit_generation(), doc.measurement_paths(page))); } - let pixels_per_unit = (xf.rect.width() / xf.pw).max(1e-6); + let pixels_per_unit = xf.zoom().max(1e-6); if let Some((_, _, Err(e))) = &state.paths { state.error = Some(e.clone()); } diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 44f132ac93..a7820c2d02 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -1139,7 +1139,10 @@ fn outline_item(ui: &mut egui::Ui, t: &Tokens, info: &DocInfo, item: &OutlineIte if let Some(levels) = cx.expand { ui.data_mut(|d| d.insert_temp(id, depth < levels)); } - let mut open = cx.searching || ui.data(|d| d.get_temp::(id)).unwrap_or(item.open || depth == 0); + // A bookmark opens as the file says at every level: a positive /Count is open, a negative + // one (or none) closed (ISO 32000-2 §12.3.3, Table 151). The reader's own toggles and a + // search override it. + let mut open = cx.searching || ui.data(|d| d.get_temp::(id)).unwrap_or(item.open); let x_text = indent + 20.0; if let Some((rpath, text)) = cx.rename.as_mut() && rpath.as_slice() == path diff --git a/crates/ui-egui/src/prepare.rs b/crates/ui-egui/src/prepare.rs index f3913401a5..5833c38384 100644 --- a/crates/ui-egui/src/prepare.rs +++ b/crates/ui-egui/src/prepare.rs @@ -543,7 +543,7 @@ pub(crate) fn paint_page(ui: &egui::Ui, painter: &egui::Painter, xf: &PageXform, let prep = &view.prepare; let pointer = ui.input(|i| i.pointer.hover_pos()); let grab = prep.grab.filter(|(gp, ..)| *gp == page); - let zoom = (xf.rect.width() / xf.pw.max(1.0)).clamp(0.5, 3.0); + let zoom = xf.zoom().clamp(0.5, 3.0); for f in form { for (wi, w) in f.widgets.iter().enumerate().filter(|(_, w)| w.page == Some(page)) { let mut r = screen_rect(xf, info, page, w.rect); diff --git a/crates/ui-egui/tests/it/bookmarks.rs b/crates/ui-egui/tests/it/bookmarks.rs index 1cf78958f6..be8c5151bb 100644 --- a/crates/ui-egui/tests/it/bookmarks.rs +++ b/crates/ui-egui/tests/it/bookmarks.rs @@ -77,6 +77,7 @@ fn new_rename_reorder_indent_delete_and_undo() { menu(&mut h, "Results", "Indent"); assert_eq!(outline(&h), [("Intro".into(), Some(0), 0), ("Results".into(), Some(2), 1)]); + h.get_by_label("Results"); // its new parent opened, so it still shows menu(&mut h, "Results", "Outdent"); menu(&mut h, "Results", "Move up"); assert_eq!(outline(&h)[0].0, "Results"); @@ -310,3 +311,60 @@ fn style_and_colour_from_the_bookmark_menu() { h.run_steps(3); assert!(look(&h).0, "undoable"); } + +/// Top-level bookmarks open as the file says, like every other level: a positive /Count shows +/// the children, a negative one hides them until the reader opens it (ISO 32000-2 §12.3.3, +/// Table 151). They used to open regardless. +#[test] +fn a_closed_top_level_bookmark_opens_closed() { + const OUTLINED: &[u8] = b"%PDF-1.7 +1 0 obj << /Type /Catalog /Pages 2 0 R /Outlines 10 0 R >> endobj +2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 300 400] >> endobj +3 0 obj << /Type /Page /Parent 2 0 R >> endobj +10 0 obj << /Type /Outlines /First 11 0 R /Last 13 0 R /Count 5 >> endobj +11 0 obj << /Title (Closed parent) /Parent 10 0 R /Next 12 0 R /First 21 0 R /Last 22 0 R /Count -2 /Dest [3 0 R /Fit] >> endobj +12 0 obj << /Title (Open parent) /Parent 10 0 R /Prev 11 0 R /Next 13 0 R /First 23 0 R /Last 24 0 R /Count 2 /Dest [3 0 R /Fit] >> endobj +13 0 obj << /Title (Uncounted parent) /Parent 10 0 R /Prev 12 0 R /First 25 0 R /Last 25 0 R /Dest [3 0 R /Fit] >> endobj +21 0 obj << /Title (Closed child A) /Parent 11 0 R /Next 22 0 R /Dest [3 0 R /Fit] >> endobj +22 0 obj << /Title (Closed child B) /Parent 11 0 R /Prev 21 0 R /Dest [3 0 R /Fit] >> endobj +23 0 obj << /Title (Open child A) /Parent 12 0 R /Next 24 0 R /Dest [3 0 R /Fit] >> endobj +24 0 obj << /Title (Open child B) /Parent 12 0 R /Prev 23 0 R /Dest [3 0 R /Fit] >> endobj +25 0 obj << /Title (Uncounted child) /Parent 13 0 R /Dest [3 0 R /Fit] >> endobj +trailer << /Root 1 0 R >> +%%EOF"; + let mut h = harness(); + h.state_mut().open_bytes("outlined.pdf", None, OUTLINED.to_vec()).unwrap(); + h.run_steps(4); + let shown = |h: &Harness<'static, PdfCraftApp>, t: &str| h.query_by_label(t).is_some(); + assert!(shown(&h, "Closed parent") && shown(&h, "Open parent") && shown(&h, "Uncounted parent")); + assert!(!shown(&h, "Closed child A") && !shown(&h, "Closed child B"), "a negative /Count opens closed"); + assert!(shown(&h, "Open child A") && shown(&h, "Open child B"), "a positive /Count opens open"); + assert!(!shown(&h, "Uncounted child"), "only a positive /Count opens a bookmark"); + + // The disclosure triangle at the row's left still opens and closes it. + let toggle = |h: &mut Harness<'static, PdfCraftApp>, title: &str| { + let row = h.get_by_label(title).rect(); + let at = egui::pos2(row.left() + 8.0, row.top() + 14.0); + h.hover_at(at); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + h.run_steps(3); + }; + toggle(&mut h, "Closed parent"); + assert!(shown(&h, "Closed child A") && shown(&h, "Closed child B"), "opened by the reader"); + toggle(&mut h, "Closed parent"); + assert!(!shown(&h, "Closed child A"), "closed again"); + toggle(&mut h, "Open parent"); + assert!(!shown(&h, "Open child A"), "an open bookmark closes"); + + // A search still shows the matches inside a closed bookmark, and clearing it restores it. + h.get_by_label("Search").click(); + h.run_steps(1); + h.get_by_label("Search").type_text("child B"); + h.run_steps(3); + assert!(shown(&h, "Closed child B") && shown(&h, "Open child B")); + h.get_by_label("Clear").click(); + h.run_steps(3); + assert!(!shown(&h, "Closed child B") && !shown(&h, "Open child B"), "search leaves the open state alone"); +} diff --git a/crates/ui-egui/tests/it/editing.rs b/crates/ui-egui/tests/it/editing.rs index 75afd2a017..a6523184a9 100644 --- a/crates/ui-egui/tests/it/editing.rs +++ b/crates/ui-egui/tests/it/editing.rs @@ -1153,6 +1153,216 @@ fn cancelling_properties_discards_the_draft() { assert!(h.state().props_draft.is_none()); } +fn custom_properties(h: &Harness<'static, PdfCraftApp>) -> Vec<(String, String)> { + let app = h.state(); + app.session.get(app.views[0].id).unwrap().custom_info() +} + +fn type_into(h: &mut Harness<'static, PdfCraftApp>, label: &str, text: &str) { + let field = h.get_by_role_and_label(Role::TextInput, label); + field.focus(); + field.type_text(text); + h.run_steps(2); +} + +fn clear(h: &mut Harness<'static, PdfCraftApp>, label: &str) { + h.get_by_role_and_label(Role::TextInput, label).focus(); + h.run_steps(1); + h.key_press_modifiers(Modifiers::COMMAND, Key::A); + h.key_press(Key::Backspace); + h.run_steps(2); +} + +#[test] +fn custom_properties_are_added_in_the_custom_tab_as_one_undoable_step() { + let mut h = harness(1, |app| app.set_option("dialog", "custom").unwrap()); + h.get_by_label("None"); + type_into(&mut h, "Name:", "Project"); + type_into(&mut h, "Value:", "Apollo"); + h.get_by_role_and_label(Role::Button, "Add").click(); + h.run_steps(3); + assert!(custom_properties(&h).is_empty(), "nothing is written before OK"); + h.get_by_label("Project"); + type_into(&mut h, "Name:", "Revision"); + type_into(&mut h, "Value:", "4"); + h.get_by_role_and_label(Role::Button, "Add").click(); + h.run_steps(3); + h.get_by_label("OK").click(); + h.run_steps(3); + assert_eq!(custom_properties(&h), [("Project".to_string(), "Apollo".to_string()), ("Revision".to_string(), "4".to_string())]); + let app = h.state(); + assert_eq!(app.session.get(app.views[0].id).unwrap().can_undo(), Some("Change document properties")); + assert!(app.dialog.is_none() && app.custom_draft.is_none()); + + h.key_press_modifiers(Modifiers::COMMAND, Key::Z); + h.run_steps(3); + assert!(custom_properties(&h).is_empty()); +} + +#[test] +fn custom_properties_are_changed_and_deleted_in_the_custom_tab() { + let mut h = harness(1, |app| { + for (key, value) in [("Project", "Apollo"), ("Revision", "4")] { + assert!(app.apply_edit(pdfcraft_engine::Edit::SetInfo { key: key.into(), value: value.into() })); + } + app.set_option("dialog", "custom").unwrap(); + }); + h.get_by_label("Revision").click(); + h.run_steps(3); + h.get_by_role_and_label(Role::Button, "Delete").click(); + h.run_steps(3); + h.get_by_label("Project").click(); + h.run_steps(3); + assert!(h.get_by_role_and_label(Role::Button, "Update").accesskit_node().is_disabled(), "the value is unchanged"); + clear(&mut h, "Value:"); + type_into(&mut h, "Value:", "Apollo 2"); + h.get_by_role_and_label(Role::Button, "Update").click(); + h.run_steps(3); + h.get_by_label("OK").click(); + h.run_steps(3); + assert_eq!(custom_properties(&h), [("Project".to_string(), "Apollo 2".to_string())]); + let app = h.state(); + let doc = app.session.get(app.views[0].id).unwrap(); + assert_eq!(doc.info_value("Revision"), None); + assert_eq!(doc.can_undo(), Some("Change document properties")); +} + +#[test] +fn the_custom_tab_refuses_names_a_custom_property_cannot_have() { + let mut h = harness(1, |app| { + assert!(app.apply_edit(pdfcraft_engine::Edit::SetInfo { key: "Project".into(), value: "Apollo".into() })); + app.set_option("dialog", "custom").unwrap(); + }); + type_into(&mut h, "Value:", "x"); + let add_disabled = |h: &Harness<'static, PdfCraftApp>| h.get_by_role_and_label(Role::Button, "Add").accesskit_node().is_disabled(); + assert!(add_disabled(&h), "no name"); + // A standard name, a name with a space, a delimiter, and a name already listed. + for name in ["Title", "Client name", "R&D/2", "Project"] { + type_into(&mut h, "Name:", name); + assert!(add_disabled(&h), "{name} is refused"); + clear(&mut h, "Name:"); + } + type_into(&mut h, "Name:", "Client"); + assert!(!add_disabled(&h)); + assert!(h.get_by_role_and_label(Role::Button, "Delete").accesskit_node().is_disabled(), "Client is not listed"); +} + +#[test] +fn a_custom_property_whose_name_the_tools_refuse_is_listed_and_left_alone() { + // `/Client#20name` and `/Project#20` are valid PDF names with a space in them, which a new custom + // property can't have; `/Project#20` is not `/Project`. `/Dept#E9` is not UTF-8 and is listed as + // "Dept\u{FFFD}". `/Revision` is a number, so it isn't listed. + let pdf = String::from_utf8(fixture(1)).unwrap().replace( + "/Root 1 0 R >>\nstartxref", + "/Root 1 0 R /Info << /Client#20name (Acme) /Project#20 (Padded) /Dept#E9 (Sales) /Project (Apollo) /Revision 4 >> >>\nstartxref", + ); + 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("doc.pdf", None, pdf.into_bytes()).expect("fixture opens"); + app.set_option("dialog", "custom").unwrap(); + app + }); + h.run_steps(4); + for name in ["Client name", "Project ", "Dept\u{FFFD}"] { + h.get_by_label(name).click(); + h.run_steps(3); + for button in ["Update", "Delete"] { + assert!(h.get_by_role_and_label(Role::Button, button).accesskit_node().is_disabled(), "{button} is off for {name:?}"); + } + } + clear(&mut h, "Name:"); + type_into(&mut h, "Name:", "Revision"); + assert!(h.get_by_role_and_label(Role::Button, "Add").accesskit_node().is_disabled(), "Add would overwrite the number"); + assert_eq!(h.state().custom_draft.as_ref().map(|(_, d)| d.value.as_str()), Some("Sales")); + h.get_by_label("Project").click(); + h.run_steps(3); + clear(&mut h, "Value:"); + type_into(&mut h, "Value:", "Gemini"); + h.get_by_role_and_label(Role::Button, "Update").click(); + h.run_steps(3); + h.get_by_label("OK").click(); + h.run_steps(3); + assert_eq!( + custom_properties(&h), + [ + ("Client name".to_string(), "Acme".to_string()), + ("Project ".to_string(), "Padded".to_string()), + ("Dept\u{FFFD}".to_string(), "Sales".to_string()), + ("Project".to_string(), "Gemini".to_string()) + ] + ); + let app = h.state(); + let doc = app.session.get(app.views[0].id).unwrap(); + assert!(doc.has_info("Revision") && doc.info_value("Revision").is_none(), "the number is kept"); + assert!(app.dialog.is_none()); +} + +#[test] +fn a_custom_property_is_deleted_from_an_info_dictionary_in_the_trailer() { + let pdf = String::from_utf8(fixture(1)) + .unwrap() + .replace("/Root 1 0 R >>\nstartxref", "/Root 1 0 R /Info << /Project (Apollo) /Revision (4) >> >>\nstartxref"); + 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("doc.pdf", None, pdf.into_bytes()).expect("fixture opens"); + app.set_option("dialog", "custom").unwrap(); + app + }); + h.run_steps(4); + h.get_by_label("Project").click(); + h.run_steps(3); + h.get_by_role_and_label(Role::Button, "Delete").click(); + h.run_steps(3); + h.get_by_label("OK").click(); + h.run_steps(3); + assert_eq!(custom_properties(&h), [("Revision".to_string(), "4".to_string())]); + let app = h.state(); + assert_eq!(app.session.get(app.views[0].id).unwrap().can_undo(), Some("Change document properties")); +} + +#[test] +fn add_stops_at_the_256_custom_properties_the_tab_lists() { + let with_props = |count: usize| { + let entries: String = (0..count).map(|n| format!("/P{n:03} (v) ")).collect(); + let pdf = + String::from_utf8(fixture(1)).unwrap().replace("/Root 1 0 R >>\nstartxref", &format!("/Root 1 0 R /Info << {entries}>> >>\nstartxref")); + 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("doc.pdf", None, pdf.into_bytes()).expect("fixture opens"); + app.set_option("dialog", "custom").unwrap(); + app + }); + h.run_steps(4); + h + }; + let add_disabled = |h: &Harness<'static, PdfCraftApp>| h.get_by_role_and_label(Role::Button, "Add").accesskit_node().is_disabled(); + + // 255 in the file: one more fits, a second does not. + let mut h = with_props(255); + type_into(&mut h, "Name:", "Client"); + type_into(&mut h, "Value:", "Acme"); + assert!(!add_disabled(&h)); + h.get_by_role_and_label(Role::Button, "Add").click(); + h.run_steps(3); + type_into(&mut h, "Name:", "Other"); + type_into(&mut h, "Value:", "x"); + assert!(add_disabled(&h), "the draft holds 256"); + assert_eq!(h.state().custom_draft.as_ref().map(|(_, d)| d.props.len()), Some(256)); + + // 257 in the file: after a Delete a new name would still be past the 256 listed. + let mut h = with_props(257); + h.get_by_label("P000").click(); + h.run_steps(3); + h.get_by_role_and_label(Role::Button, "Delete").click(); + h.run_steps(3); + type_into(&mut h, "Name:", "Client"); + type_into(&mut h, "Value:", "Acme"); + assert!(add_disabled(&h), "the file lists 256"); +} + #[test] fn edit_menu_names_the_step_to_undo() { let mut h = harness(2, |app| { diff --git a/crates/ui-egui/tests/it/fill_sign.rs b/crates/ui-egui/tests/it/fill_sign.rs index 88051a9e58..566a14f186 100644 --- a/crates/ui-egui/tests/it/fill_sign.rs +++ b/crates/ui-egui/tests/it/fill_sign.rs @@ -237,6 +237,51 @@ fn fill_text_size_resizes_the_selected_text() { assert!(after > before * 2.0, "36 pt text has a taller box than 10 pt text: {before} -> {after}"); } +/// The font sizes of the texts `text` drawn in the last frame. +fn drawn_sizes(h: &Harness<'static, PdfCraftApp>, text: &str) -> Vec { + fn walk(shape: &egui::Shape, text: &str, out: &mut Vec) { + match shape { + egui::Shape::Vec(shapes) => shapes.iter().for_each(|s| walk(s, text, out)), + egui::Shape::Text(t) if t.galley.text() == text => { + out.extend(t.galley.job.sections.first().map(|s| s.format.font_id.size)); + } + _ => {} + } + } + let mut out = Vec::new(); + for clipped in &h.output().shapes { + walk(&clipped.shape, text, &mut out); + } + out +} + +/// The type box draws its text at the page's zoom whichever way the view is turned. With the +/// view turned a quarter, the page's width runs down the screen: reading the zoom off the screen +/// rectangle's width instead made the typed text a height-over-width too large (here 4/3). +#[test] +fn the_type_box_text_matches_the_page_zoom_in_a_turned_view() { + for rotate in ["0", "90"] { + let mut h = harness(); + h.state_mut().set_option("rotate", rotate).unwrap(); + h.run_steps(3); + h.state_mut().execute("sign.fill.text"); + click(&mut h, 50.0, 250.0); + h.event(egui::Event::Text("Ada".into())); + h.run_steps(2); + let s = h.state(); + let page = &s.session.get(s.views[0].id).unwrap().info.pages[0]; + let rect = s.views[0].page_screen_rect(0).expect("on screen"); + // Screen pixels per page point: the page's width lies across, or down when turned. + let zoom = if rotate == "90" { rect.height() } else { rect.width() } / page.width; + let size = s.views[0].fill_text.as_ref().expect("an open type box").size as f32; + let drawn = drawn_sizes(&h, "Ada"); + assert!(!drawn.is_empty(), "{rotate}°: the typed text is drawn"); + for d in drawn { + assert!((d - size * zoom).abs() < 0.5, "{rotate}°: drawn at {d}, the page shows it at {}", size * zoom); + } + } +} + #[test] fn the_type_box_grows_as_text_is_typed() { let mut h = harness(); diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 3a534850f0..0e543a7888 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -50,6 +50,7 @@ mod links; mod marks; mod object_selection; mod ocr; +mod open_action; mod organize_drag; mod pageboxes; mod panel_snapshots; diff --git a/crates/ui-egui/tests/it/marks.rs b/crates/ui-egui/tests/it/marks.rs index 626513f303..2c8b39d558 100644 --- a/crates/ui-egui/tests/it/marks.rs +++ b/crates/ui-egui/tests/it/marks.rs @@ -372,6 +372,35 @@ fn the_preview_shows_the_page_the_range_selects_under_the_marks() { assert_eq!(tint, egui::Color32::from_rgb(red, green, blue), "the default background colour, opaque"); } +/// The preview's page stepper, beside its "page N of M" label: the dialog's own button, not the +/// page navigation's of the same name. +fn preview_step(h: &mut Harness<'static, PdfCraftApp>, label: &str, now: &str) { + let row = h.get_by_label(now).rect().center().y; + h.query_all_by_label(label).find(|n| (n.rect().center().y - row).abs() < 15.0).unwrap_or_else(|| panic!("{label} beside {now:?}")).click(); + h.run_steps(2); +} + +#[test] +fn the_preview_steps_through_the_pages_and_starts_at_the_current_one() { + let mut h = harness(); + h.state_mut().views[0].go_to_page(1); + h.run_steps(2); + assert!(h.state_mut().execute("edit.watermark")); + h.run_steps(2); + h.get_by_label("Preview: page 2 of 3"); + preview_step(&mut h, "Next page", "Preview: page 2 of 3"); + h.get_by_label("Preview: page 3 of 3"); + preview_step(&mut h, "Previous page", "Preview: page 3 of 3"); + preview_step(&mut h, "Previous page", "Preview: page 2 of 3"); + h.get_by_label("Preview: page 1 of 3"); + // Opened again, the preview is back at the current page. + h.get_by_label("Cancel").click(); + h.run_steps(2); + assert!(h.state_mut().execute("edit.watermark")); + h.run_steps(2); + h.get_by_label("Preview: page 2 of 3"); +} + /// Pages from 1 to 1 stays one page: the dialog used to turn "to" back into the last page on /// every frame while both were 1, so only page 1 could not be chosen alone. The field starts on /// the last page. diff --git a/crates/ui-egui/tests/it/open_action.rs b/crates/ui-egui/tests/it/open_action.rs new file mode 100644 index 0000000000..a6593af707 --- /dev/null +++ b/crates/ui-egui/tests/it/open_action.rs @@ -0,0 +1,191 @@ +//! A document opens where its `/OpenAction` says (ISO 32000-2 §12.3.2.2 Table 149, §12.3.2.4): +//! the page, and the place on it, of an explicit destination, a go-to action's or a named one; +//! and a full-screen document's `/NonFullScreenPageMode` panel (Table 147). + +use egui::{Key, Modifiers}; +use egui_kittest::Harness; +use pdfcraft_render::DestView; +use pdfcraft_ui_egui::canvas::Fit; +use pdfcraft_ui_egui::{PdfCraftApp, RightPanel}; + +/// Six Letter (612×792) pages, objects 3 to 8; `catalog` is added to the catalog dictionary. +/// Object 9 is an outline (one bookmark, object 10) that `/Outlines 9 0 R` can use. +fn fixture(catalog: &str) -> Vec { + let n = 6; + let kids: Vec = (0..n).map(|i| format!("{} 0 R", 3 + i)).collect(); + let mut objs = vec![format!("<< /Type /Catalog /Pages 2 0 R {catalog} >>"), format!("<< /Type /Pages /Kids [{}] /Count {n} >>", kids.join(" "))]; + for _ in 0..n { + objs.push("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>".to_string()); + } + objs.push("<< /Type /Outlines /First 10 0 R /Last 10 0 R /Count 1 >>".to_string()); + objs.push("<< /Title (Chapter) /Parent 9 0 R /Dest [6 0 R /Fit] >>".to_string()); + let mut out = b"%PDF-1.7\n".to_vec(); + let mut offsets = Vec::new(); + for (i, o) in objs.iter().enumerate() { + offsets.push(out.len()); + out.extend_from_slice(format!("{} 0 obj\n{o}\nendobj\n", i + 1).as_bytes()); + } + let xref = out.len(); + out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes()); + for o in offsets { + out.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes()); + } + out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes()); + out +} + +fn harness(catalog: &str) -> Harness<'static, PdfCraftApp> { + let bytes = fixture(catalog); + 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.set_option("left", "closed").unwrap(); + app.open_bytes("open.pdf", None, bytes).expect("opens"); + app + }); + h.run_steps(4); + settle(&mut h); + h +} + +/// Run frames until rendering has finished and the layout holds still. +fn settle(h: &mut Harness<'static, PdfCraftApp>) { + for _ in 0..200 { + h.run_steps(2); + if !h.state().render_pending() { + break; + } + std::thread::sleep(std::time::Duration::from_millis(5)); + } +} + +/// The page at the top of the window and the user-space height there: where a bookmark made now +/// (⌘B) goes. +fn window_top(h: &mut Harness<'static, PdfCraftApp>) -> (usize, f32) { + h.key_press_modifiers(Modifiers::COMMAND, Key::B); + h.run_steps(3); + let id = h.state().views[0].id; + let outline = &h.state().session.get(id).unwrap().info.outline; + let made = outline.iter().find(|b| b.title == "Untitled").expect("the new bookmark"); + match made.view { + DestView::Xyz { top: Some(top), .. } => (made.page.expect("a page"), top), + other => panic!("expected /XYZ with a top, got {other:?}"), + } +} + +/// The left edge of `page` on screen and its scale (screen points per user-space point). +fn page_left(h: &Harness<'static, PdfCraftApp>, page: usize) -> (f32, f32) { + let rects = h.state().views[0].visible_page_rects(); + let (_, r) = rects.iter().find(|(p, _)| *p == page).expect("the page is shown"); + (r.left(), r.width() / 612.0) +} + +fn near(got: f32, want: f32, what: &str) { + assert!((got - want).abs() < 2.0, "{what}: {got} vs {want}"); +} + +#[test] +fn an_xyz_open_action_puts_its_point_at_the_window_top_left() { + let mut h = harness("/OpenAction [5 0 R /XYZ 100 500 2]"); + assert_eq!(h.state().views[0].current, 2); + assert_eq!((h.state().views[0].fit, h.state().views[0].zoom), (Fit::None, 2.0)); + // `left`: the page sits 100 user points further left than one opened at left 0. + let (left, scale) = page_left(&h, 2); + let (left0, _) = page_left(&harness("/OpenAction [5 0 R /XYZ 0 500 2]"), 2); + near(left0 - left, 100.0 * scale, "the page moved left by `left`"); + let (page, top) = window_top(&mut h); + assert_eq!(page, 2); + near(top, 500.0, "y 500 is at the window's top edge"); +} + +#[test] +fn a_fith_open_action_puts_its_top_at_the_window_top() { + let mut h = harness("/OpenAction [4 0 R /FitH 400]"); + assert_eq!(h.state().views[0].current, 1); + assert_eq!(h.state().views[0].fit, Fit::Width); + let (page, top) = window_top(&mut h); + assert_eq!(page, 1); + near(top, 400.0, "y 400 is at the window's top edge"); +} + +#[test] +fn a_named_open_destination_opens_its_page() { + for catalog in [ + // PDF 1.1: a name, through the catalog's /Dests. + "/OpenAction << /S /GoTo /D /there >> /Dests << /there [7 0 R /XYZ 0 792 0] >>", + // A string, through the /Names /Dests name tree. + "/OpenAction << /S /GoTo /D (there) >> /Names << /Dests << /Names [(there) [7 0 R /XYZ 0 792 0]] >> >>", + // The destination given as a name, without an action. + "/OpenAction /there /Dests << /there [7 0 R /XYZ 0 792 0] >>", + ] { + let mut h = harness(catalog); + assert_eq!(h.state().views[0].current, 4, "{catalog}"); + // A zoom of 0 keeps the default zoom. + assert_eq!(h.state().views[0].fit, Fit::Width, "{catalog}"); + let (page, top) = window_top(&mut h); + assert_eq!(page, 4, "{catalog}"); + near(top, 792.0, "the page's top is at the window's top edge"); + } + // A name nothing defines opens on the first page. + let h = harness("/OpenAction << /S /GoTo /D /missing >> /Dests << /there [7 0 R /Fit] >>"); + assert_eq!(h.state().views[0].current, 0); +} + +#[test] +fn always_my_default_view_keeps_the_zoom_and_goes_to_the_page_top() { + let bytes = fixture("/OpenAction [5 0 R /XYZ 100 500 2]"); + 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.set_option("left", "closed").unwrap(); + app.always_default_view = true; + app.open_bytes("open.pdf", None, bytes).expect("opens"); + app + }); + h.run_steps(4); + settle(&mut h); + assert_eq!(h.state().views[0].current, 2); + assert_eq!(h.state().views[0].fit, Fit::Width); + let (page, top) = window_top(&mut h); + assert_eq!(page, 2); + near(top, 792.0, "the page's top"); +} + +#[test] +fn a_full_screen_document_shows_its_non_full_screen_panel_outside_full_screen() { + for (mode, want) in [("UseThumbs", Some(RightPanel::Pages)), ("UseOC", Some(RightPanel::Layers)), ("UseNone", None)] { + let mut h = harness(&format!("/PageMode /FullScreen /ViewerPreferences << /NonFullScreenPageMode /{mode} >>")); + assert!(h.state().pending_full_screen.is_some(), "{mode}: full screen is asked for"); + assert_eq!(h.state().right, want, "{mode}: the panel behind the prompt"); + // Declining it leaves that panel. + let ctx = h.ctx.clone(); + h.state_mut().resolve_full_screen_prompt(&ctx, false); + h.run_steps(2); + assert_eq!((h.state().full_screen, h.state().right), (false, want), "{mode}: declined"); + // Entering and leaving full screen comes back to it. + h.state_mut().apply_full_screen(true); + h.run_steps(2); + h.state_mut().apply_full_screen(false); + h.run_steps(2); + assert_eq!(h.state().right, want, "{mode}: after full screen"); + } + // Without /PageMode /FullScreen the entry means nothing. + let h = harness("/ViewerPreferences << /NonFullScreenPageMode /UseThumbs >>"); + assert_eq!(h.state().right, None); +} + +#[test] +fn a_full_screen_document_with_an_outline_shows_it_only_when_it_asks_to() { + // UseNone (and its absence, the default) shows no outline outside full screen; UseOutlines does. + for (prefs, want) in [ + ("", None), + ("/ViewerPreferences << /NonFullScreenPageMode /UseNone >>", None), + ("/ViewerPreferences << /NonFullScreenPageMode /UseOutlines >>", Some(RightPanel::Bookmarks)), + ] { + let h = harness(&format!("/Outlines 9 0 R /PageMode /FullScreen {prefs}")); + assert_eq!(h.state().right, want, "{prefs}"); + } + // Not in full screen, a document with an outline still opens on it. + let h = harness("/Outlines 9 0 R"); + assert_eq!(h.state().right, Some(RightPanel::Bookmarks)); +} diff --git a/crates/xfa/src/layout.rs b/crates/xfa/src/layout.rs index 3657bdbe2e..670d43791a 100644 --- a/crates/xfa/src/layout.rs +++ b/crates/xfa/src/layout.rs @@ -14,7 +14,10 @@ use base64::Engine; use crate::XfaError; use crate::data::{DataNode, data_date_letters, data_path, data_to_iso, date_letters, is_on, iso_to_pattern}; -use crate::model::*; +use crate::model::{ + Access, Area, Border, Common, Draw, ExclGroup, Field, Font, HAlign, Layout, Margin, Node, Occur, PageArea, PageRole, Para, Placement, Presence, + Rect, Script, SomIndices, Stroke, Subform, Template, Ui, VAlign, Value, +}; use crate::text::{self, Block, Face, Span}; /// Most pages a form may lay out to. @@ -1325,6 +1328,10 @@ impl Layouter<'_> { if cap.value.is_empty() && cap.reserve.is_none() { return None; } + // A check box has no text for an inline caption to run with: it is not shown. + if f.ui == Ui::CheckButton && cap.placement == Placement::Inline { + return None; + } let placement = if cap.placement == Placement::Inline { Placement::Left } else { cap.placement }; let font = ctx.font.apply(&cap.font); let para = ctx.para.apply(&cap.para); @@ -1365,13 +1372,18 @@ impl Layouter<'_> { }; match self.caption_reserve(f, inner_w, ctx) { Some((Placement::Top | Placement::Bottom, r)) => ui + r, - Some((_, r)) => { + Some((placement, r)) => { + // A check box's caption without a reserve is drawn in all the box leaves. + let w = match auto_check_reserve(f, placement, inner_w, None) { + Some(auto) => auto, + None => inner_w - r, + }; let cap = f.caption.as_ref().map(|c| { let rich = match &c.value { Value::Rich(r) => r.clone(), other => text::plain(&other.plain().unwrap_or_default()), }; - text::measure_height(&rich, (inner_w - r).max(1.0), &ctx.para.apply(&c.para), &Face::of(&ctx.font.apply(&c.font)), &|id, max| { + text::measure_height(&rich, w.max(1.0), &ctx.para.apply(&c.para), &Face::of(&ctx.font.apply(&c.font)), &|id, max| { self.embed(id, max) }) }); @@ -1838,6 +1850,7 @@ impl Layouter<'_> { let inner = rect.inset(&f.common.margin); let (mut ui, mut cap_rect) = (inner, None); if let Some((placement, reserve)) = self.caption_reserve(f, inner.w, ctx) { + let reserve = auto_check_reserve(f, placement, inner.w, Some(inner.h)).unwrap_or(reserve); let r = reserve.max(0.0); match placement { Placement::Top => { @@ -1975,12 +1988,21 @@ impl Layouter<'_> { let (kind, rect, border, value, tooltip) = match f.ui { Ui::CheckButton => { let s = f.check_size.unwrap_or(10.0).min(ui.w.max(1.0)).min(ui.h.max(1.0)); - let y = match fctx.para.v_align { - VAlign::Top => ui.y + f.ui_margin.top, - VAlign::Middle => ui.y + (ui.h - s) / 2.0, - VAlign::Bottom => ui.bottom() - s - f.ui_margin.bottom, + // Without a caption the box sits at the right of the content area, as if a + // caption on its left took the rest, so the paragraph's alignment has no room to + // act on; beside a caption that alignment places it. The box's own margin doesn't + // move it. + let x = match (cap_rect, fctx.para.h_align) { + (None, _) | (Some(_), HAlign::Right) => ui.right() - s, + (Some(_), HAlign::Center) => ui.x + (ui.w - s) / 2.0, + (Some(_), HAlign::Left | HAlign::Justify) => ui.x, }; - let r = Rect::new(ui.x + f.ui_margin.left, y, s, s); + let y = match fctx.para.v_align { + VAlign::Top => ui.y, + VAlign::Middle => ui.y + (ui.h - s) / 2.0, + VAlign::Bottom => ui.bottom() - s, + }; + let r = Rect::new(x, y, s, s); let on = f.items.first().cloned().filter(|s| !s.trim().is_empty()).unwrap_or_else(|| "1".into()); let (kind, tip, checked) = match radio { Some((group, on_value, tip, chosen)) => ( @@ -2069,6 +2091,22 @@ impl Layouter<'_> { } } +/// The room a caption without a reserve takes beside a check box: all the box leaves of a +/// content area `w` wide (and `h` tall, when known), the box at the size it can be drawn there. +/// `None` for any other field, or a caption with a reserve of its own. +fn auto_check_reserve(f: &Field, placement: Placement, w: f64, h: Option) -> Option { + if f.ui != Ui::CheckButton || f.caption.as_ref().is_none_or(|c| c.reserve.is_some()) { + return None; + } + let s = f.check_size.unwrap_or(10.0).min(w.max(1.0)).min(h.map_or(f64::INFINITY, |h| h.max(1.0))); + let rest = match (placement, h) { + (Placement::Top | Placement::Bottom, Some(h)) => h - s, + (Placement::Top | Placement::Bottom, None) => return None, + _ => w - s, + }; + Some(rest.max(0.0)) +} + /// The widget's own border from the `` border element. Without one, a check box gets a /// solid box, as Designer draws it, and any other field has no box of its own. fn widget_border(b: Option<&Border>, check: bool) -> WidgetBorder { diff --git a/crates/xfa/src/parse.rs b/crates/xfa/src/parse.rs index e312d5310f..838d1730ea 100644 --- a/crates/xfa/src/parse.rs +++ b/crates/xfa/src/parse.rs @@ -5,7 +5,11 @@ use base64::Engine; use roxmltree::Node as XmlNode; use crate::XfaError; -use crate::model::*; +use crate::model::{ + Access, Anchor, Area, Border, Caption, ChoiceList, Color, Common, Corner, Draw, Edge, ExclGroup, Field, FontSpec, HAlign, Layout, Margin, Node, + Occur, PageArea, PageRole, PageSet, ParaSpec, Paragraph, Placement, Presence, Rect, RichText, Run, Script, Stroke, Subform, Template, Ui, VAlign, + Value, +}; /// Deepest element nesting followed (templates are shallow; hostile ones are not). const MAX_DEPTH: usize = 64; @@ -424,7 +428,9 @@ fn parse_caption(n: Option, warnings: &mut Vec) -> Option Placement::Inline, _ => Placement::Left, }, - reserve: attr_measure(n, "reserve").filter(|r| *r >= 0.0), + // A reserve of zero or less sizes the caption to its content, as none does (XFA 3.3, + // the caption's reserve). + reserve: attr_measure(n, "reserve").filter(|r| *r > 0.0), presence: Presence::parse(n.attribute("presence")), value: parse_value(child(n, "value"), warnings), font: parse_font(child(n, "font")), diff --git a/crates/xfa/src/script.rs b/crates/xfa/src/script.rs index c8d506495e..d330c2a647 100644 --- a/crates/xfa/src/script.rs +++ b/crates/xfa/src/script.rs @@ -7,7 +7,7 @@ use std::collections::{BTreeMap, HashMap}; use pdfcraft_cos::{Dict, Document, Object, PdfString}; use crate::data::{DataNode, data_path, parse_datasets}; -use crate::model::*; +use crate::model::{Access, Field, Node, Presence, Script, SomIndices, Template}; use crate::{Report, XfaError}; /// Private key on the AcroForm: presence scripts set, by SOM path. diff --git a/crates/xfa/src/tests.rs b/crates/xfa/src/tests.rs index 46c2435314..3175882f89 100644 --- a/crates/xfa/src/tests.rs +++ b/crates/xfa/src/tests.rs @@ -2757,6 +2757,258 @@ fn a_text_field_without_a_border_of_its_own_has_no_box() { assert_eq!(shapes, [BorderShape::None, BorderShape::Full, BorderShape::Full]); } +/// One measured check box: its name, width, box size, check box children, field children, and +/// where its box was drawn (x and y in inches from the field's top left). +type CheckCase<'a> = (&'a str, &'a str, Option<&'a str>, String, String, f64, f64); + +/// A check box field for the placement tests: `extra` holds its margin, paragraph and caption, +/// `ui` the check box's own children, and `size` its box size (none for the default 10pt). +fn placed_check(name: &str, x: f64, y: f64, w: &str, size: Option<&str>, ui: &str, extra: &str) -> String { + let size = size.map(|s| format!(r#" size="{s}""#)).unwrap_or_default(); + format!( + r#"{ui}{extra}10"# + ) +} + +/// Where a check box is drawn inside its field, measured in inches from the field's top left in +/// another viewer on synthetic probes: with no caption the box sits at the right of the content +/// area whatever the paragraph's alignment, beside a reserved caption the alignment places it, +/// a caption without a reserve takes all the box leaves, and the box's own margin doesn't move it. +#[test] +fn a_check_box_sits_where_its_margins_caption_and_alignment_put_it() { + let m = |a: &str| format!(""); + let p = |a: &str| format!(""); + let cap = |a: &str, text: &str| format!(r#"{text}"#); + // (name, width, box size, check box children, field children, box x and y in inches) + let cases: Vec = vec![ + ("none", "1.2in", Some("0.25in"), String::new(), String::new(), 0.95, 0.0), + ("left_margin", "1.2in", Some("0.25in"), String::new(), m(r#"leftInset="0.3in""#), 0.95, 0.0), + ("right_margin", "1.2in", Some("0.25in"), String::new(), m(r#"rightInset="0.3in""#), 0.65, 0.0), + ("both_margins", "1.2in", Some("0.25in"), String::new(), m(r#"leftInset="0.1in" rightInset="0.4in""#), 0.55, 0.0), + ("h_left", "1.2in", Some("0.25in"), String::new(), p(r#"hAlign="left""#), 0.95, 0.0), + ("h_center", "1.2in", Some("0.25in"), String::new(), p(r#"hAlign="center""#), 0.95, 0.0), + ("h_right", "1.2in", Some("0.25in"), String::new(), p(r#"hAlign="right""#), 0.95, 0.0), + ("h_justify", "1.2in", Some("0.25in"), String::new(), p(r#"hAlign="justify""#), 0.95, 0.0), + ("center_right_margin", "1.2in", Some("0.25in"), String::new(), m(r#"rightInset="0.3in""#) + &p(r#"hAlign="center""#), 0.65, 0.0), + ("left_left_margin", "1.2in", Some("0.25in"), String::new(), m(r#"leftInset="0.3in""#) + &p(r#"hAlign="left""#), 0.95, 0.0), + ("v_top_margin", "1.2in", Some("0.25in"), String::new(), m(r#"topInset="0.15in""#) + &p(r#"vAlign="top""#), 0.95, 0.15), + ("v_middle_margin", "1.2in", Some("0.25in"), String::new(), m(r#"topInset="0.2in""#) + &p(r#"vAlign="middle""#), 0.95, 0.275), + ("v_bottom_margin", "1.2in", Some("0.25in"), String::new(), m(r#"bottomInset="0.15in""#) + &p(r#"vAlign="bottom""#), 0.95, 0.2), + ("v_bottom", "1.2in", Some("0.25in"), String::new(), p(r#"vAlign="bottom""#), 0.95, 0.35), + ("cap_left_reserve", "1.5in", Some("0.25in"), String::new(), cap(r#"placement="left" reserve="0.5in""#, "Cap"), 0.5, 0.0), + ("cap_right_reserve", "1.5in", Some("0.25in"), String::new(), cap(r#"placement="right" reserve="0.5in""#, "Cap"), 0.0, 0.0), + ( + "cap_left_reserve_center", + "1.5in", + Some("0.25in"), + String::new(), + cap(r#"placement="left" reserve="0.5in""#, "Cap") + &p(r#"hAlign="center""#), + 0.875, + 0.0, + ), + ( + "cap_left_reserve_right", + "1.5in", + Some("0.25in"), + String::new(), + cap(r#"placement="left" reserve="0.5in""#, "Cap") + &p(r#"hAlign="right""#), + 1.25, + 0.0, + ), + ( + "cap_left_reserve_middle", + "1.5in", + Some("0.25in"), + String::new(), + cap(r#"placement="left" reserve="0.5in""#, "Cap") + &p(r#"vAlign="middle""#), + 0.5, + 0.175, + ), + ( + "cap_right_reserve_center", + "1.5in", + Some("0.25in"), + String::new(), + cap(r#"placement="right" reserve="0.5in""#, "Cap") + &p(r#"hAlign="center""#), + 0.375, + 0.0, + ), + ("cap_top_reserve", "1.5in", Some("0.25in"), String::new(), cap(r#"placement="top" reserve="0.25in""#, "Cap"), 0.0, 0.25), + ("cap_bottom_reserve", "1.5in", Some("0.25in"), String::new(), cap(r#"placement="bottom" reserve="0.25in""#, "Cap"), 0.0, 0.0), + ( + "cap_hidden_reserve", + "1.5in", + Some("0.25in"), + String::new(), + cap(r#"placement="left" reserve="0.5in" presence="hidden""#, "Cap"), + 1.25, + 0.0, + ), + ("cap_empty_reserve", "1.5in", Some("0.25in"), String::new(), r#""#.to_string(), 0.5, 0.0), + ("cap_left_auto", "1.5in", Some("0.25in"), String::new(), cap(r#"placement="left""#, "Cap"), 1.25, 0.0), + ("cap_left_auto_center", "1.5in", Some("0.25in"), String::new(), cap(r#"placement="left""#, "Cap") + &p(r#"hAlign="center""#), 1.25, 0.0), + ("cap_right_auto", "1.5in", Some("0.25in"), String::new(), cap(r#"placement="right""#, "Cap"), 0.0, 0.0), + ("cap_right_auto_middle", "1.5in", Some("0.25in"), String::new(), cap(r#"placement="right""#, "Cap") + &p(r#"vAlign="middle""#), 0.0, 0.175), + ("cap_top_auto", "1.5in", Some("0.25in"), String::new(), cap(r#"placement="top""#, "Cap"), 0.0, 0.35), + ("cap_top_auto_center", "1.5in", Some("0.25in"), String::new(), cap(r#"placement="top""#, "Cap") + &p(r#"hAlign="center""#), 0.625, 0.35), + ("cap_bottom_auto", "1.5in", Some("0.25in"), String::new(), cap(r#"placement="bottom""#, "Cap"), 0.0, 0.0), + ("cap_inline", "1.5in", Some("0.25in"), String::new(), cap(r#"placement="inline""#, "Cap"), 1.25, 0.0), + ("cap_hidden_auto", "1.5in", Some("0.25in"), String::new(), cap(r#"placement="left" presence="hidden""#, "Cap"), 1.25, 0.0), + ("box_margin_left", "1.5in", Some("0.25in"), m(r#"leftInset="0.1in""#), String::new(), 1.25, 0.0), + ( + "box_margin_all", + "1.5in", + Some("0.25in"), + m(r#"leftInset="0.1in" rightInset="0.1in" topInset="0.1in" bottomInset="0.1in""#), + String::new(), + 1.25, + 0.0, + ), + ("default_size", "1.2in", None, String::new(), String::new(), 1.2 - 10.0 / 72.0, 0.0), + ("default_size_center", "1.2in", None, String::new(), p(r#"hAlign="center""#), 1.2 - 10.0 / 72.0, 0.0), + ]; + let fields: String = cases + .iter() + .enumerate() + .map(|(i, (name, w, size, ui, extra, _, _))| placed_check(name, (i % 4) as f64 * 1.8, (i / 4) as f64 * 0.8, w, *size, ui, extra)) + .collect(); + // The form in the measured case the probes started from (DD Form 2946's checklist boxes). + let cell = r#"10"#; + let body = format!(r#"{fields}{cell}"#); + let form = layout_xml(&one_area_form(r#"layout="tb""#, &body)).unwrap(); + let laid = widgets(&form.pages[0]); + let at = |name: &str| laid.iter().find(|w| w.name == name).map(|w| w.rect).unwrap_or_else(|| panic!("no widget {name}")); + // The content area starts half an inch in. + for (i, (name, _, size, _, _, x, y)) in cases.iter().enumerate() { + let r = at(name); + let (fx, fy) = (36.0 + (i % 4) as f64 * 1.8 * 72.0, 36.0 + (i / 4) as f64 * 0.8 * 72.0); + let s = if size.is_some() { 18.0 } else { 10.0 }; + assert!((r.x - fx - x * 72.0).abs() < 0.01, "{name}: box x {} in, expected {x}", (r.x - fx) / 72.0); + assert!((r.y - fy - y * 72.0).abs() < 0.01, "{name}: box y {} in, expected {y}", (r.y - fy) / 72.0); + assert!((r.w - s).abs() < 0.01 && (r.h - s).abs() < 0.01, "{name}: box size {}x{}", r.w, r.h); + } + // Its box sits 4.2mm in, against its 3.556mm right margin, and in the middle of its height. + let r = at("cell"); + let mm = 72.0 / 25.4; + assert!((r.x - 36.0 - (12.7 - 3.556 - 4.9389) * mm).abs() < 0.01, "cell box x {}", r.x - 36.0); + assert!((r.y - 36.0 - 8.0 * 72.0 - (0.6 * 72.0 - 4.9389 * mm) / 2.0).abs() < 0.01, "cell box y {}", r.y - 36.0 - 8.0 * 72.0); +} + +/// Radio buttons in an exclusion group sit as check boxes do: at the right without a caption, +/// moved in by a right margin, and placed by the alignment or the caption beside a caption. +#[test] +fn a_radio_button_sits_where_a_check_box_would() { + let radio = |name: &str, x: f64, extra: &str| { + format!( + r#"{extra}{name}"# + ) + }; + let cap = |a: &str| format!(r#"Cap"#); + // (name, field children, box x and y in inches from the field's top left) + let cases = [ + ("plain", String::new(), 1.25, 0.0), + ("right_margin", r#""#.to_string(), 0.95, 0.0), + ("centered", r#""#.to_string(), 1.25, 0.0), + ("cap_right_center", cap(r#"placement="right" reserve="0.5in""#) + r#""#, 0.375, 0.0), + ("cap_left_auto", cap(r#"placement="left""#), 1.25, 0.0), + ("cap_top_auto", cap(r#"placement="top""#), 0.0, 0.35), + ]; + let fields: String = cases.iter().enumerate().map(|(i, (name, extra, _, _))| radio(name, i as f64 * 1.6, extra)).collect(); + let body = format!( + r#"{fields}"# + ); + let form = layout_xml(&one_area_form(r#"layout="tb""#, &body)).unwrap(); + let laid = widgets(&form.pages[0]); + for (i, (name, _, x, y)) in cases.iter().enumerate() { + let w = laid.iter().find(|w| w.name == *name).unwrap_or_else(|| panic!("no radio button {name}")); + assert!(matches!(w.kind, WidgetKind::Radio { .. }), "{name} is a radio button"); + let fx = 36.0 + i as f64 * 1.6 * 72.0; + assert!((w.rect.x - fx - x * 72.0).abs() < 0.01, "{name}: box x {} in, expected {x}", (w.rect.x - fx) / 72.0); + assert!((w.rect.y - 36.0 - y * 72.0).abs() < 0.01, "{name}: box y {} in, expected {y}", (w.rect.y - 36.0) / 72.0); + } +} + +/// A caption without a reserve leaves room for the box at the size it is drawn, a box larger than +/// its field shrinking to fit; and a field without a height is as tall as that caption drawn in +/// all the box leaves, not at some narrower width. +#[test] +fn a_check_box_caption_without_a_reserve_is_measured_as_it_is_drawn() { + let cap = + r#"Caption text running on one line"#; + let tall = r#""# + .to_string() + + cap + + "10"; + let form = layout_xml(&one_area_form(r#"layout="tb""#, &format!(r#"{tall}"#))) + .unwrap(); + let r = widgets(&form.pages[0]).iter().find(|w| w.name == "tall").map(|w| w.rect).unwrap(); + assert!((r.w - 18.0).abs() < 0.01, "the box shrinks to the field's height: {}", r.w); + assert!((r.x - 36.0 - 1.25 * 72.0).abs() < 0.01, "and still sits at the right: {} in", (r.x - 36.0) / 72.0); + + let grows = r#""#.to_string() + + cap + + r#"10"#; + let form = layout_xml(&one_area_form(r#"layout="tb""#, &format!(r#"{grows}"#))).unwrap(); + let next = widgets(&form.pages[0]).iter().find(|w| w.name == "next").map(|w| w.rect).unwrap(); + assert!((next.y - 36.0 - 18.0).abs() < 0.01, "a one-line caption beside the box keeps the field the box's height: {}", next.y - 36.0); +} + +/// A caption without a reserve beside a check box takes all the room the box leaves, and starts +/// right after it; an inline caption has no text to run with and is not drawn. +#[test] +fn a_check_box_caption_without_a_reserve_takes_the_rest_of_the_field() { + let cap = |place: &str, text: &str| { + format!(r#"{text}"#) + }; + let body = format!( + r#"{}{}{}{}"#, + placed_check("after", 0.0, 0.0, "1.5in", Some("0.25in"), "", &cap("right", "Right")), + placed_check("before", 2.0, 0.0, "1.5in", Some("0.25in"), "", &cap("left", "Left")), + placed_check("below", 4.0, 0.0, "1.5in", Some("0.25in"), "", &cap("bottom", "Below")), + placed_check("inline", 0.0, 1.0, "1.5in", Some("0.25in"), "", &cap("inline", "Inline")), + ); + let form = layout_xml(&one_area_form(r#"layout="tb""#, &body)).unwrap(); + let span = |t: &str| { + form.pages[0].items.iter().find_map(|i| match i { + Item::Text(s) if s.text == t => Some(s.clone()), + _ => None, + }) + }; + let right = span("Right").expect("the right caption is drawn"); + assert!((right.x - 36.0 - 18.0).abs() < 0.01, "a right caption starts after the box: {}", right.x - 36.0); + let left = span("Left").expect("the left caption is drawn"); + assert!((left.x - 36.0 - 2.0 * 72.0).abs() < 0.01, "a left caption starts at the field's left: {}", left.x - 36.0); + let below = span("Below").expect("the bottom caption is drawn"); + assert!(below.baseline - 36.0 > 18.0, "a bottom caption is below the box: {}", below.baseline - 36.0); + assert!(span("Inline").is_none(), "an inline caption beside a check box is not drawn"); +} + +/// A caption reserve of zero sizes the caption to its content, as no reserve does: beside a check +/// box it takes the rest of the field, and before a text field it is as wide as its text. +#[test] +fn a_zero_caption_reserve_sizes_the_caption_as_none_does() { + let cap = |reserve: &str| { + format!(r#"Right"#) + }; + let text = |name: &str, y: &str, reserve: &str| { + format!( + r#"Name"# + ) + }; + let body = format!( + r#"{}{}{}"#, + placed_check("zero", 0.0, 0.0, "1.5in", Some("0.25in"), "", &cap(r#" reserve="0""#)), + text("withZero", "1in", r#" reserve="0in""#), + text("without", "2in", ""), + ); + let form = layout_xml(&one_area_form(r#"layout="tb""#, &body)).unwrap(); + let right = form.pages[0].items.iter().find_map(|i| if let Item::Text(s) = i { (s.text == "Right").then_some(s.x) } else { None }); + assert!(right.is_some_and(|x| (x - 36.0 - 18.0).abs() < 0.01), "the caption starts after the box: {right:?}"); + let x_of = |name: &str| widgets(&form.pages[0]).iter().find(|w| w.name == name).map(|w| w.rect.x).unwrap(); + assert!(x_of("withZero") > 36.0 + 1.0, "the caption takes its text's width: {}", x_of("withZero")); + assert!((x_of("withZero") - x_of("without")).abs() < 0.01, "as without a reserve: {} {}", x_of("withZero"), x_of("without")); +} + #[test] fn a_signed_signature_box_shows_the_signature_the_file_holds() { let mut doc = Document::open(Arc::new(crate::fixtures::signed_shell())).unwrap(); diff --git a/crates/xfdf/src/lib.rs b/crates/xfdf/src/lib.rs index a6da88f4db..6131c9c96b 100644 --- a/crates/xfdf/src/lib.rs +++ b/crates/xfdf/src/lib.rs @@ -271,8 +271,10 @@ fn text_of(doc: &Document, d: &Dict, k: &[u8]) -> Option { }) } +/// The numbers of a list; empty when any entry is non-finite (`nan`, `inf`), so the list is unusable as a whole. fn csv(list: &str) -> Vec { - list.split([',', ';', ' ']).filter(|t| !t.is_empty()).filter_map(|t| t.trim().parse().ok()).collect() + let v: Vec = list.split([',', ';', ' ']).filter(|t| !t.is_empty()).filter_map(|t| t.trim().parse().ok()).collect(); + if v.iter().all(|x| x.is_finite()) { v } else { Vec::new() } } fn arr(v: &[f64]) -> Object { diff --git a/crates/xfdf/src/tests.rs b/crates/xfdf/src/tests.rs index 80e7d8049d..17c48c281b 100644 --- a/crates/xfdf/src/tests.rs +++ b/crates/xfdf/src/tests.rs @@ -1874,3 +1874,62 @@ fn a_comment_locked_by_an_indirect_flag_is_not_replaced_by_an_import() { assert!(annots.contains(&Object::Ref(note)), "the locked comment was replaced"); assert_eq!(doc.get(note), before, "the locked comment was changed"); } + +#[test] +fn import_skips_annotations_with_non_finite_coordinates() { + for rect in ["nan,10,100,100", "0,inf,100,100", "0,10,infinity,100", "0,10,100,-inf"] { + let mut doc = blank(); + let xfdf = format!( + r#""# + ); + let r = import(&mut doc, xfdf.as_bytes()).unwrap(); + assert_eq!(r.comments, 1, "rect {rect}: {r:?}"); + let names = annots_of(&doc); + assert_eq!(names.len(), 1, "rect {rect}: {names:?}"); + assert_eq!(names[0].get(b"NM"), Some(&PdfString::literal(b"good".to_vec()).into()), "rect {rect}"); + } +} + +#[test] +fn import_drops_non_finite_numbers_from_every_coordinate_list() { + let xfdf = r#" + + 1,2;inf,4;5,6 + 1,2;3,-inf + + + "#; + let mut doc = blank(); + let r = import(&mut doc, xfdf.as_bytes()).unwrap(); + assert_eq!(r.comments, 5, "{r:?}"); + fn finite(doc: &Document, o: &Object) -> bool { + match &*doc.resolve(o) { + Object::Real(x) => x.is_finite(), + Object::Array(a) => a.iter().all(|e| finite(doc, e)), + _ => true, + } + } + let annots = annots_of(&doc); + assert_eq!(annots.len(), 5); + for d in &annots { + for (k, v) in d.iter() { + if k.as_slice() != b"P" { + assert!(finite(&doc, v), "{d:?}"); + } + } + assert!(d.get(b"L").is_none() && d.get(b"CL").is_none() && d.get(b"Vertices").is_none(), "{d:?}"); + } +} + +fn annots_of(doc: &Document) -> Vec { + let page = &pdfcraft_model::pages(doc)[0]; + page.dict + .get(b"Annots") + .map(|a| doc.resolve(a)) + .and_then(|a| a.as_array().cloned()) + .unwrap_or_default() + .iter() + .map(|a| doc.resolve(a).as_dict().cloned().unwrap()) + .filter(|d| d.get(b"Subtype") != Some(&Object::name("Widget"))) + .collect() +} diff --git a/docs/mcp.md b/docs/mcp.md index 77a3c9484d..8aa30ec6e8 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -90,8 +90,10 @@ config works across the suite) keep the agent to the folders you give it: nearest existing folder's links are followed and the rest must be plain names, so `..` below a folder that doesn't exist is refused, as is a link that leads nowhere (writing through it would create its target). The result is compared with the root by whole folder names: `/work2/x` is not - inside `/work`. On Windows case is ignored, UNC paths are resolved like drive-letter ones, and - device names (`CON`, `NUL`, `COM1`...) are refused. + inside `/work`. On Windows case is ignored, device names (`CON`, `NUL`, `COM1`...) are refused, + and a path on another network share or in a device namespace than the root's (`\\host\share`, + `\\?\UNC\...`, `\\.\...`) is refused by name, before it is resolved, so the host is never + contacted. A root on a share accepts the paths on that share. - A refused path is an ordinary tool error the agent can read and correct, for example `automation path rejected: outside the write root /work/project/out: /etc/x.pdf` or `automation filesystem access is not granted: write authority is absent: /work/project/out/x.pdf`. diff --git a/docs/pdf-spec-parity.md b/docs/pdf-spec-parity.md index 4ce13f195a..8cfe4be471 100644 --- a/docs/pdf-spec-parity.md +++ b/docs/pdf-spec-parity.md @@ -1,6 +1,6 @@ # PDF specification and standards parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-14 · **Change:** minor (§12.4.4: page transitions and display times read) · **Target:** Adobe Acrobat Pro (Acrobat DC, continuous track 26.002.21931, macOS) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-24 · **Change:** minor (§14.3: custom properties edited in Document Properties) · **Target:** Adobe Acrobat Pro (Acrobat DC, continuous track 26.002.21931, macOS) How much of ISO 32000-2 (PDF 2.0) and the PDF subset standards PdfCraft implements, set against what Acrobat Pro implements. This is PdfCraft's equivalent of a "geometry" or "codec" checklist: @@ -44,7 +44,7 @@ are borrowed; PDF 2.0 additions and most subset standards are missing. **150–2 | §12.9 | Measurement and geospatial | full | 2D measuring with viewports and calibration; no geospatial | `comment.geospatial` planned | | §12.10 | Document requirements | yes | none | | | §13 | Multimedia: sound, movies, screen, rich media, 3D (U3D, PRC) | yes | preserved untouched; not played or shown | `misc.rich-media-*`, `misc.3d-view` planned (P3) | -| §14.3 | Metadata: info dictionary, XMP | full, XMP editor | info dictionary edited, with its XMP counterparts (title, author, subject, keywords, creator tool, producer) kept in step; XMP written for PDF/A; no XMP editor or custom properties | `organize.xmp-editor` planned | +| §14.3 | Metadata: info dictionary, XMP | full, XMP editor | info dictionary edited, with its XMP counterparts (title, author, subject, keywords, creator tool, producer) kept in step; XMP written for PDF/A; custom properties listed, added, changed and deleted (Document Properties ▸ Custom, `doc_info`, `doc_set_info`); no XMP editor | `organize.custom-properties` partial, `organize.xmp-editor` planned | | §14.6–14.8 | Marked content, logical structure, tagged PDF | full, with editing tools | read (checker, bookmarks from structure, redaction of tags); no tag editing or autotag | gap 11 | | §14.9 | Accessibility support: alt text, ActualText, language | full | alt text figure by figure, language, title | `a11y.alt-text-workflow` | | §14.10 | Web capture | yes | none | | diff --git a/packaging/linux/package.sh b/packaging/linux/package.sh index b7813920e7..df292455e8 100755 --- a/packaging/linux/package.sh +++ b/packaging/linux/package.sh @@ -121,7 +121,7 @@ fi # ---- .deb / .rpm -------------------------------------------------------------------------------- if has deb || has rpm; then - command -v nfpm >/dev/null || { echo "error: nfpm not found (https://nfpm.goreleaser.com/install/)" >&2; exit 1; } + command -v nfpm >/dev/null || { echo "error: nfpm not found (https://nfpm.goreleaser.com/docs/install/)" >&2; exit 1; } export VERSION export RELEASE="1${PDFCRAFT_BUILD_LABEL:+.$PDFCRAFT_BUILD_LABEL}" export NFPM_ARCH="$DEB_ARCH" diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml index da57e884ce..10f560b4b3 100644 --- a/parity/acrobat-features.toml +++ b/parity/acrobat-features.toml @@ -746,8 +746,8 @@ milestone = "M2" status = "partial" commands = [] tools = [] -evidence = ["crates/render/src/raster.rs::self_referencing_tiling_pattern_terminates"] -notes = "via hayro bootstrap" +evidence = ["crates/render/src/raster.rs::self_referencing_tiling_pattern_terminates", "crates/render/tests/it/tiling_cell_placement.rs::far_cells_of_a_fill_sit_at_whole_steps", "crates/render/tests/it/tiling_cell_placement.rs::far_cells_sit_at_whole_steps_under_a_turned_scaled_matrix", "crates/render/tests/it/tiling_cell_placement.rs::far_cells_of_a_stroke_sit_at_whole_steps"] +notes = "via hayro bootstrap. Tiling pattern cells sit at whole multiples of /XStep and /YStep at any zoom, filled or stroked, under any pattern matrix. Missing: a cell is cut at its step, so content reaching past the step into the next cell is lost; a cell pixmap is capped at 3000 pixels a side, so very large steps draw at reduced resolution" [[feature]] id = "view.render-transparency" @@ -3363,8 +3363,8 @@ milestone = "M4" status = "shipped" commands = ["file.properties"] tools = [] -evidence = ["crates/ui-egui/tests/it/bookmarks.rs::expanding_and_collapsing_all_bookmarks"] -notes = "Bookmarks panel options: expand all, expand top-level, collapse all" +evidence = ["crates/ui-egui/tests/it/bookmarks.rs::expanding_and_collapsing_all_bookmarks", "crates/ui-egui/tests/it/bookmarks.rs::a_closed_top_level_bookmark_opens_closed", "crates/organize/src/tests.rs::bookmarks_add_rename_move_delete"] +notes = "Bookmarks panel options: expand all, expand top-level, collapse all. Each bookmark, top level included, opens as its /Count says (positive open; negative or missing closed, ISO 32000-2 Table 151); the triangle toggles it for the session and a search shows matches inside closed ones. Adding or moving a bookmark into another opens that one. Missing: the open/closed state the reader sets is not written back to /Count on save" [[feature]] id = "organize.bookmarks-from-structure" @@ -3507,8 +3507,8 @@ milestone = "M4" status = "shipped" commands = ["file.properties"] tools = ["doc_initial_view"] -evidence = ["crates/organize/src/view.rs::initial_view_resolves_indirect_boolean_preferences", "crates/ui-egui/tests/it/ui.rs::a_document_asking_for_full_screen_is_asked_about_first", "crates/organize/src/tests.rs::initial_view_round_trips_and_keeps_scripts", "crates/ui-egui/tests/it/viewer.rs::initial_view_is_edited_and_honoured_on_open", "crates/automation/tests/it/automation.rs::initial_view_through_tools"] -notes = "navigation panel, layout, magnification, page, window and interface options; honoured on open; script open actions kept. Open in Full Screen mode (/PageMode /FullScreen) asks first (Full Screen / Not now), as Acrobat does, instead of taking the screen. Window and interface options also read indirect boolean ViewerPreferences values. Missing: Acrobat's Full Screen preference to turn that alert off and its \"remember my choice for this document\" (misc.prefs-full-screen)" +evidence = ["crates/organize/src/view.rs::initial_view_resolves_indirect_boolean_preferences", "crates/ui-egui/tests/it/ui.rs::a_document_asking_for_full_screen_is_asked_about_first", "crates/organize/src/tests.rs::initial_view_round_trips_and_keeps_scripts", "crates/ui-egui/tests/it/viewer.rs::initial_view_is_edited_and_honoured_on_open", "crates/automation/tests/it/automation.rs::initial_view_through_tools", "crates/render/src/inspect.rs::a_go_to_action_opens_at_its_destination_explicit_or_named", "crates/ui-egui/tests/it/open_action.rs::an_xyz_open_action_puts_its_point_at_the_window_top_left", "crates/ui-egui/tests/it/open_action.rs::a_fith_open_action_puts_its_top_at_the_window_top", "crates/ui-egui/tests/it/open_action.rs::a_named_open_destination_opens_its_page", "crates/ui-egui/tests/it/open_action.rs::a_full_screen_document_shows_its_non_full_screen_panel_outside_full_screen", "crates/organize/src/tests.rs::an_unchanged_opening_destination_keeps_its_position_and_name", "crates/automation/tests/it/automation.rs::doc_info_reports_the_open_destination"] +notes = "navigation panel, layout, magnification, page, window and interface options; honoured on open; script open actions kept. Open in Full Screen mode (/PageMode /FullScreen) asks first (Full Screen / Not now), as Acrobat does, instead of taking the screen. Window and interface options also read indirect boolean ViewerPreferences values. Missing: Acrobat's Full Screen preference to turn that alert off and its \"remember my choice for this document\" (misc.prefs-full-screen). On open the /OpenAction destination places the view as ISO 32000-2 Table 149 says (the /XYZ point at the window's top-left, /FitH and /FitV top or left at the edge), and a named destination (name or string, /Names /Dests tree or catalog /Dests, §12.3.2.4) resolves; Always use my default zoom keeps only the page. A full-screen document shows its /NonFullScreenPageMode panel outside full screen (Table 147). doc_info reports the opening destination. Document Properties keeps an opening action whose page and magnification are left alone, but still edits only those two, and shows page 1 for a named destination" [[feature]] id = "organize.custom-properties" @@ -3517,10 +3517,10 @@ area = "D" tier = "P2" milestone = "M4" status = "partial" -commands = [] +commands = ["file.properties"] tools = ["doc_info", "doc_set_info"] -evidence = ["crates/organize/src/tests.rs::custom_document_properties_are_listed_set_removed_and_their_names_checked", "crates/render/src/inspect.rs::custom_document_properties_are_listed_apart_from_the_standard_ones", "crates/automation/tests/it/automation.rs::custom_document_properties_are_set_listed_and_cleared_through_the_tools"] -notes = "Through the tools: doc_set_info sets or clears an /Info entry under any name the spec does not use (names checked as Acrobat does: no standard name, no empty name, no spaces or delimiters, at most 127 bytes), and doc_info lists them under custom, apart from the standard entries. Not yet: the Custom tab in Document Properties, and mirroring them into XMP (pdfx:) as Acrobat does" +evidence = ["crates/organize/src/tests.rs::custom_document_properties_are_listed_set_removed_and_their_names_checked", "crates/render/src/inspect.rs::custom_document_properties_are_listed_apart_from_the_standard_ones", "crates/automation/tests/it/automation.rs::custom_document_properties_are_set_listed_and_cleared_through_the_tools", "crates/ui-egui/tests/it/editing.rs::custom_properties_are_added_in_the_custom_tab_as_one_undoable_step", "crates/ui-egui/tests/it/editing.rs::custom_properties_are_changed_and_deleted_in_the_custom_tab", "crates/ui-egui/tests/it/editing.rs::the_custom_tab_refuses_names_a_custom_property_cannot_have", "crates/ui-egui/tests/it/editing.rs::a_custom_property_whose_name_the_tools_refuse_is_listed_and_left_alone", "crates/ui-egui/tests/it/editing.rs::a_custom_property_is_deleted_from_an_info_dictionary_in_the_trailer", "crates/ui-egui/tests/it/editing.rs::add_stops_at_the_256_custom_properties_the_tab_lists", "crates/organize/src/tests.rs::document_info_entries_are_cleared_from_an_info_dictionary_in_the_trailer"] +notes = "Document Properties ▸ Custom lists them, with Name and Value fields and Add, Update (the value of the listed property the Name field names) and Delete; OK writes the changes as one undo step with the other tabs' changes. A property already in the file under a name the tools refuse (a space, a delimiter) or a name that is not UTF-8 is listed and cannot be changed or deleted there, and Add is off for a name the file already uses for an entry that is not listed (not text, only padding, or past the 256 listed), and once the tab or the file lists 256 properties. Through the tools: doc_set_info sets or clears an /Info entry under any name the spec does not use (names checked as Acrobat does: no standard name, no empty name, no spaces or delimiters, at most 127 bytes), and doc_info lists them under custom, apart from the standard entries. Not yet: mirroring them into XMP (pdfx:) as Acrobat does" [[feature]] id = "organize.xmp-editor" @@ -3751,8 +3751,8 @@ milestone = "M5" status = "shipped" commands = ["comment.line"] tools = ["comment_add"] -evidence = ["crates/annot/src/tests.rs::every_tool_creates_a_drawable_comment"] -notes = "" +evidence = ["crates/annot/src/tests.rs::every_tool_creates_a_drawable_comment", "crates/annot/src/tests.rs::a_positive_leader_length_puts_the_line_above_a_left_to_right_line_and_a_negative_one_below", "crates/annot/src/tests.rs::an_inline_caption_breaks_the_line_around_its_text"] +notes = "A line without an appearance is drawn with its leader lines (/LL, /LLE, /LLO: the line sits |LL| + LLO from /L, on the left of travel for a positive /LL) and its caption (/Cap, /CP Inline or Top, /CO), endings at the line itself (ISO 32000-2 Table 178). Not yet: the tool can't add leader lines or a caption, the caption is always black Helvetica 10 (no /DS or rich-text styling), and drawing past /Rect is clipped (/Rect isn't grown)." [[feature]] id = "comment.arrow" @@ -5284,8 +5284,8 @@ milestone = "M12" status = "partial" commands = ["file.open"] tools = ["doc_open", "doc_info", "form_fields", "form_fill", "js_run"] -evidence = ["crates/xfa/src/tests.rs::layout_places_captions_fields_and_sizes_containers_to_their_content", "crates/xfa/src/tests.rs::tables_break_across_pages_and_repeat_their_header_row", "crates/xfa/src/tests.rs::rendering_into_the_pdf_replaces_the_placeholder_page_and_adds_fields", "crates/engine/src/tests.rs::dynamic_xfa_forms_are_laid_out_on_open_filled_and_saved_incrementally", "crates/automation/tests/it/automation.rs::dynamic_xfa_forms_open_render_fill_and_save_through_tools", "crates/ui-egui/tests/it/xfa.rs::a_dynamic_xfa_form_is_laid_out_and_filled", "crates/xfa/src/tests.rs::nested_width_less_subforms_lay_out_in_polynomial_time", "crates/js/src/tests.rs::instance_managers_add_remove_and_count", "crates/xfa/src/tests.rs::the_form_tree_carries_values_presence_instances_and_the_events", "crates/engine/src/tests.rs::xfa_scripts_initialize_calculate_validate_toggle_and_add_rows", "crates/engine/src/tests.rs::xfa_date_arithmetic_reads_the_date_as_its_display_picture_shows_it", "crates/automation/tests/it/automation.rs::xfa_scripts_run_for_buttons_and_field_changes_through_tools", "crates/ui-egui/tests/it/xfa.rs::xfa_buttons_run_their_scripts_in_the_app", "crates/engine/src/tests.rs::hostile_xfa_open_scripts_are_merged_capped_kept_from_printing_and_noted", "crates/engine/src/tests.rs::runaway_xfa_calculations_at_open_end_quickly_with_a_report", "crates/ui-egui/tests/it/xfa.rs::a_form_whose_scripts_were_turned_off_at_open_says_so", "crates/ui-egui/tests/it/xfa.rs::scripts_turned_off_by_a_click_bring_a_closed_notice_bar_back", "crates/automation/tests/it/automation.rs::doc_info_says_when_a_runaway_script_turned_the_forms_scripts_off", "crates/xfa/src/tests.rs::the_live_form_of_nested_repeating_subforms_stops_at_its_node_budget", "crates/xfa/src/tests.rs::data_ops_of_one_event_are_one_datasets_rewrite", "crates/xfa/src/tests.rs::choice_lists_signatures_passwords_and_pictures_become_fields_and_images", "crates/xfa/src/tests.rs::choice_values_come_from_the_data_as_saved_values_and_several_for_lists", "crates/xfa/src/tests.rs::pictures_are_sized_from_their_headers_and_hostile_ones_are_refused_unallocated", "crates/engine/src/tests.rs::xfa_choice_lists_signature_and_picture_fields_open_fill_script_and_save", "crates/xfa/src/tests.rs::repeating_subforms_inside_positioned_content_get_their_instances", "crates/engine/src/tests.rs::xfa_rows_in_areas_are_laid_out_read_calculated_and_written_where_adobe_binds_them", "crates/xfa/src/tests.rs::page_area_without_occur_serves_every_body_page", "apps/pdfcraft-cli/tests/it/xfa.rs::info_reports_the_laid_out_pages_and_fields", "apps/pdfcraft-cli/tests/it/xfa.rs::text_reads_the_layout_including_a_page_absent_from_the_placeholder", "apps/pdfcraft-cli/tests/it/xfa.rs::render_matches_the_engine_layout_on_the_second_page", "apps/pdfcraft-cli/tests/it/xfa.rs::a_laid_out_form_keeps_the_original_copy_permissions", "crates/engine/src/tests.rs::filling_growable_xfa_text_reflows_and_undo_restores_the_layout", "crates/engine/src/tests.rs::xfa_text_growth_refreshes_widget_geometry_but_fixed_height_fields_keep_their_widgets", "crates/automation/tests/it/automation.rs::growable_xfa_text_paginates_after_fill_save_and_print", "crates/engine/src/tests.rs::an_xfa_script_that_fails_partway_keeps_what_it_changed_before_the_error", "crates/engine/src/tests.rs::repeated_xfa_print_buttons_run_their_click_script", "crates/automation/tests/it/automation.rs::repeated_xfa_print_buttons_work_through_tools_and_after_reopen", "crates/xfa/src/tests.rs::rich_text_max_length_reaches_the_field_and_layout", "crates/automation/tests/it/automation.rs::xfa_rich_text_max_length_is_reported_and_enforced_through_tools", "crates/xfa/src/tests.rs::bmp_and_tiff_pictures_are_decoded_and_drawn", "crates/engine/src/tests.rs::active_xfa_does_not_run_pdf_container_scripts_but_keeps_requested_alerts", "crates/engine/src/tests.rs::active_xfa_without_template_scripts_does_not_initialize_pdf_fallback_scripts", "crates/engine/src/tests.rs::inactive_xfa_and_ordinary_pdfs_keep_document_helpers_and_alerts", "crates/automation/tests/it/automation.rs::active_xfa_skips_container_fallback_scripts_after_save_and_reopen", "crates/xfa/src/tests.rs::laying_a_form_out_takes_off_the_usage_rights_it_voids", "crates/engine/src/tests.rs::a_dynamic_xfa_form_is_saved_without_the_usage_rights_its_layout_voided", "crates/xfa/src/tests.rs::faces_measure_text_at_their_standard_14_widths", "crates/xfa/src/tests.rs::rich_text_links_keep_their_address", "crates/xfa/src/tests.rs::links_in_rich_text_become_link_annotations_one_per_line", "crates/xfa/src/tests.rs::a_links_pieces_share_one_address", "crates/xfa/src/tests.rs::a_rule_between_two_pieces_of_a_link_keeps_them_apart", "crates/xfa/src/tests.rs::links_to_anything_but_web_and_email_addresses_stay_plain_text", "crates/automation/tests/it/automation.rs::links_in_xfa_rich_text_are_listed_through_tools", "crates/xfa/src/tests.rs::rounded_corners_make_a_border_one_rounded_shape", "crates/xfa/src/tests.rs::a_rounded_box_cut_by_a_page_break_keeps_its_corners_on_each_page", "crates/xfa/src/tests.rs::rounded_boxes_are_written_as_curved_paths", "crates/xfa/src/tests.rs::a_flowed_subform_is_drawn_with_its_border_under_its_content"] -notes = "Active XFA layout skips PDF-container document-script initialization for the Acrobat console/field context, so fallback-viewer scripts do not run there. Scripts remain in the file/listing; explicit console/field and XFA alerts still run. Ordinary PDF, static XFA and unlaid-out shells keep document scripts; static-conversion undo restores the XFA policy. Changed growable multiline text (no fixed h) reflows from final datasets after edits, with or without scripts; pages/widgets refresh and undo/redo, save/reopen and print retain all text. Oversized text still uses the existing read-only page-text fallback with a warning; fixed-height fields do not reflow. Repeated page-master buttons resolve their own PDF field to the shared XFA click script; the numPages-based print script requests printing from every copy, including after save/reopen (#2572). Rich-text exData/maxLength is carried into AcroForm MaxLen, reported by form_fields and enforced by form_fill (Unicode characters); limits and accepted values survive save/reopen (#2570). laid out from the template on open by the xfa crate (positioned, tb, lr-tb, table/row, page masters (a page area with no occur repeats without limit, one with occur max=1 is used once, one with occur min=1 the body never reached gets a page after the body, as Acrobat Pro does on a synthetic form), breaks, repeated header rows, borders and fills of flowed subforms (a page break between their children gives each page's part a closed border, the margins repeated at the cut, as measured on a synthetic form in another viewer, and a child's own page break breaks them the same way; one holding an item that doesn't fit on its page, cut across pages or placed past the content area's bottom, is drawn without its border, with a layout warning), captions, rounded and inverted border corners, rich text (its http, https and mailto links clickable), JPEG/PNG/GIF/BMP/TIFF images) into real pages and AcroForm fields (text, password, date with AFDate formats, check boxes, radio groups, drop-downs and list boxes with shown/saved item pairs and multi-select, signature fields, image fields showing their picture (pictures decoded once per document, at most 20 million pixels, and reused across re-layouts), buttons with reset/print/save/URL), filled from the datasets packet (including rows another viewer added), saved as an incremental revision with the values merged into the datasets so Adobe's viewers show them; usage rights the form carried (/Perms /UR3) are taken off with a note, as the layout voids them and a form with void usage rights opens with every field locked; doc_info reports xfa_layout. CLI info reports the laid-out page/field counts and dimensions while retaining the input file size and raw counts as pdf_pages/acroform_fields; text and render use those pages too, preserving copy permissions and leaving the source file unchanged (#1645). XFA JavaScript and FormCalc (form.xfa-formcalc) run in the js crate's XFA object model (xfa.form, SOM resolution, rawValue, formattedValue in a date display picture's pattern (number and text display pictures still give the raw value), presence, access, instance managers, xfa.host, xfa.layout, xfa.event): initialize and calculate on open, exit, validate and calculate after a field changes, click for buttons (through js_run and the app), with rows added and removed, subforms shown and hidden, and the form laid out again, all as one undo step and kept in the file. All the scripts of one event run on one thread, each in a fresh context on the form as the engine holds it then (nothing shared between scripts; the live form kept up to date in place for values, rebuilt only when the structure changed), so hundreds of calculations run within the open budget. Hostile scripts are bounded per event (merged and capped effects, messages and console lines, lower loop limits and a time budget on open and calculate, one datasets rewrite per event, print/save/links/focus from clicks only, a runaway script abandoned and the form's scripts turned off, which the app says in a toast and on the notice bar, with a button to the JavaScript console, and doc_info reports as xfa_scripts_off) and what open-time scripts changed is noted. A script that fails partway keeps what it changed before the error, as JavaScript does (forms often trip over an object an earlier version had after their first lines did the work). Missing: a page area's relevant=\"-print\" (on a synthetic form Acrobat still prints the page but leaves it blank; PdfCraft prints its content, #2574); a page break before the first section (Acrobat opens an empty body page first when the first section has breakBefore targetType=pageArea, with or without startNew, as seen on synthetic forms; PdfCraft skips a break on an empty page and lays out one page fewer, #2574); loops inside nested calls are only stopped by abandoning their thread, and script memory is not capped; the change event per keystroke; xfa.template, connections and data descriptions; a hidden instance of a repeating subform hides them all; barcodes are drawn as their text, not bars; keep rules; text is measured at the exact standard-14 widths of the face it is drawn in (bold, italic and Times included), not in the template's own typefaces, and Acrobat fidelity is eyeballed on real forms, not measured (#60)" +evidence = ["crates/xfa/src/tests.rs::layout_places_captions_fields_and_sizes_containers_to_their_content", "crates/xfa/src/tests.rs::tables_break_across_pages_and_repeat_their_header_row", "crates/xfa/src/tests.rs::rendering_into_the_pdf_replaces_the_placeholder_page_and_adds_fields", "crates/engine/src/tests.rs::dynamic_xfa_forms_are_laid_out_on_open_filled_and_saved_incrementally", "crates/automation/tests/it/automation.rs::dynamic_xfa_forms_open_render_fill_and_save_through_tools", "crates/ui-egui/tests/it/xfa.rs::a_dynamic_xfa_form_is_laid_out_and_filled", "crates/xfa/src/tests.rs::nested_width_less_subforms_lay_out_in_polynomial_time", "crates/js/src/tests.rs::instance_managers_add_remove_and_count", "crates/xfa/src/tests.rs::the_form_tree_carries_values_presence_instances_and_the_events", "crates/engine/src/tests.rs::xfa_scripts_initialize_calculate_validate_toggle_and_add_rows", "crates/engine/src/tests.rs::xfa_date_arithmetic_reads_the_date_as_its_display_picture_shows_it", "crates/automation/tests/it/automation.rs::xfa_scripts_run_for_buttons_and_field_changes_through_tools", "crates/ui-egui/tests/it/xfa.rs::xfa_buttons_run_their_scripts_in_the_app", "crates/engine/src/tests.rs::hostile_xfa_open_scripts_are_merged_capped_kept_from_printing_and_noted", "crates/engine/src/tests.rs::runaway_xfa_calculations_at_open_end_quickly_with_a_report", "crates/ui-egui/tests/it/xfa.rs::a_form_whose_scripts_were_turned_off_at_open_says_so", "crates/ui-egui/tests/it/xfa.rs::scripts_turned_off_by_a_click_bring_a_closed_notice_bar_back", "crates/automation/tests/it/automation.rs::doc_info_says_when_a_runaway_script_turned_the_forms_scripts_off", "crates/xfa/src/tests.rs::the_live_form_of_nested_repeating_subforms_stops_at_its_node_budget", "crates/xfa/src/tests.rs::data_ops_of_one_event_are_one_datasets_rewrite", "crates/xfa/src/tests.rs::choice_lists_signatures_passwords_and_pictures_become_fields_and_images", "crates/xfa/src/tests.rs::choice_values_come_from_the_data_as_saved_values_and_several_for_lists", "crates/xfa/src/tests.rs::pictures_are_sized_from_their_headers_and_hostile_ones_are_refused_unallocated", "crates/engine/src/tests.rs::xfa_choice_lists_signature_and_picture_fields_open_fill_script_and_save", "crates/xfa/src/tests.rs::repeating_subforms_inside_positioned_content_get_their_instances", "crates/engine/src/tests.rs::xfa_rows_in_areas_are_laid_out_read_calculated_and_written_where_adobe_binds_them", "crates/xfa/src/tests.rs::page_area_without_occur_serves_every_body_page", "apps/pdfcraft-cli/tests/it/xfa.rs::info_reports_the_laid_out_pages_and_fields", "apps/pdfcraft-cli/tests/it/xfa.rs::text_reads_the_layout_including_a_page_absent_from_the_placeholder", "apps/pdfcraft-cli/tests/it/xfa.rs::render_matches_the_engine_layout_on_the_second_page", "apps/pdfcraft-cli/tests/it/xfa.rs::a_laid_out_form_keeps_the_original_copy_permissions", "crates/engine/src/tests.rs::filling_growable_xfa_text_reflows_and_undo_restores_the_layout", "crates/engine/src/tests.rs::xfa_text_growth_refreshes_widget_geometry_but_fixed_height_fields_keep_their_widgets", "crates/automation/tests/it/automation.rs::growable_xfa_text_paginates_after_fill_save_and_print", "crates/engine/src/tests.rs::an_xfa_script_that_fails_partway_keeps_what_it_changed_before_the_error", "crates/engine/src/tests.rs::repeated_xfa_print_buttons_run_their_click_script", "crates/automation/tests/it/automation.rs::repeated_xfa_print_buttons_work_through_tools_and_after_reopen", "crates/xfa/src/tests.rs::rich_text_max_length_reaches_the_field_and_layout", "crates/automation/tests/it/automation.rs::xfa_rich_text_max_length_is_reported_and_enforced_through_tools", "crates/xfa/src/tests.rs::bmp_and_tiff_pictures_are_decoded_and_drawn", "crates/engine/src/tests.rs::active_xfa_does_not_run_pdf_container_scripts_but_keeps_requested_alerts", "crates/engine/src/tests.rs::active_xfa_without_template_scripts_does_not_initialize_pdf_fallback_scripts", "crates/engine/src/tests.rs::inactive_xfa_and_ordinary_pdfs_keep_document_helpers_and_alerts", "crates/automation/tests/it/automation.rs::active_xfa_skips_container_fallback_scripts_after_save_and_reopen", "crates/xfa/src/tests.rs::laying_a_form_out_takes_off_the_usage_rights_it_voids", "crates/engine/src/tests.rs::a_dynamic_xfa_form_is_saved_without_the_usage_rights_its_layout_voided", "crates/xfa/src/tests.rs::faces_measure_text_at_their_standard_14_widths", "crates/xfa/src/tests.rs::rich_text_links_keep_their_address", "crates/xfa/src/tests.rs::links_in_rich_text_become_link_annotations_one_per_line", "crates/xfa/src/tests.rs::a_links_pieces_share_one_address", "crates/xfa/src/tests.rs::a_rule_between_two_pieces_of_a_link_keeps_them_apart", "crates/xfa/src/tests.rs::links_to_anything_but_web_and_email_addresses_stay_plain_text", "crates/automation/tests/it/automation.rs::links_in_xfa_rich_text_are_listed_through_tools", "crates/xfa/src/tests.rs::rounded_corners_make_a_border_one_rounded_shape", "crates/xfa/src/tests.rs::a_rounded_box_cut_by_a_page_break_keeps_its_corners_on_each_page", "crates/xfa/src/tests.rs::rounded_boxes_are_written_as_curved_paths", "crates/xfa/src/tests.rs::a_flowed_subform_is_drawn_with_its_border_under_its_content", "crates/xfa/src/tests.rs::a_check_box_sits_where_its_margins_caption_and_alignment_put_it", "crates/xfa/src/tests.rs::a_check_box_caption_without_a_reserve_takes_the_rest_of_the_field", "crates/xfa/src/tests.rs::a_radio_button_sits_where_a_check_box_would", "crates/xfa/src/tests.rs::a_check_box_caption_without_a_reserve_is_measured_as_it_is_drawn"] +notes = "Active XFA layout skips PDF-container document-script initialization for the Acrobat console/field context, so fallback-viewer scripts do not run there. Scripts remain in the file/listing; explicit console/field and XFA alerts still run. Ordinary PDF, static XFA and unlaid-out shells keep document scripts; static-conversion undo restores the XFA policy. Changed growable multiline text (no fixed h) reflows from final datasets after edits, with or without scripts; pages/widgets refresh and undo/redo, save/reopen and print retain all text. Oversized text still uses the existing read-only page-text fallback with a warning; fixed-height fields do not reflow. Repeated page-master buttons resolve their own PDF field to the shared XFA click script; the numPages-based print script requests printing from every copy, including after save/reopen (#2572). Rich-text exData/maxLength is carried into AcroForm MaxLen, reported by form_fields and enforced by form_fill (Unicode characters); limits and accepted values survive save/reopen (#2570). laid out from the template on open by the xfa crate (positioned, tb, lr-tb, table/row, page masters (a page area with no occur repeats without limit, one with occur max=1 is used once, one with occur min=1 the body never reached gets a page after the body, as Acrobat Pro does on a synthetic form), breaks, repeated header rows, borders and fills of flowed subforms (a page break between their children gives each page's part a closed border, the margins repeated at the cut, as measured on a synthetic form in another viewer, and a child's own page break breaks them the same way; one holding an item that doesn't fit on its page, cut across pages or placed past the content area's bottom, is drawn without its border, with a layout warning), captions, rounded and inverted border corners, rich text (its http, https and mailto links clickable), JPEG/PNG/GIF/BMP/TIFF images) into real pages and AcroForm fields (text, password, date with AFDate formats, check boxes and radio groups (each box placed by its field's margins, caption and paragraph alignment as measured on two synthetic forms in another viewer: with no caption at the right of the content area, beside a reserved caption where the alignment puts it, and a caption without a reserve taking the rest of the field; a check box's own margin larger than the box draws a bigger box there, which isn't copied), drop-downs and list boxes with shown/saved item pairs and multi-select, signature fields, image fields showing their picture (pictures decoded once per document, at most 20 million pixels, and reused across re-layouts), buttons with reset/print/save/URL), filled from the datasets packet (including rows another viewer added), saved as an incremental revision with the values merged into the datasets so Adobe's viewers show them; usage rights the form carried (/Perms /UR3) are taken off with a note, as the layout voids them and a form with void usage rights opens with every field locked; doc_info reports xfa_layout. CLI info reports the laid-out page/field counts and dimensions while retaining the input file size and raw counts as pdf_pages/acroform_fields; text and render use those pages too, preserving copy permissions and leaving the source file unchanged (#1645). XFA JavaScript and FormCalc (form.xfa-formcalc) run in the js crate's XFA object model (xfa.form, SOM resolution, rawValue, formattedValue in a date display picture's pattern (number and text display pictures still give the raw value), presence, access, instance managers, xfa.host, xfa.layout, xfa.event): initialize and calculate on open, exit, validate and calculate after a field changes, click for buttons (through js_run and the app), with rows added and removed, subforms shown and hidden, and the form laid out again, all as one undo step and kept in the file. All the scripts of one event run on one thread, each in a fresh context on the form as the engine holds it then (nothing shared between scripts; the live form kept up to date in place for values, rebuilt only when the structure changed), so hundreds of calculations run within the open budget. Hostile scripts are bounded per event (merged and capped effects, messages and console lines, lower loop limits and a time budget on open and calculate, one datasets rewrite per event, print/save/links/focus from clicks only, a runaway script abandoned and the form's scripts turned off, which the app says in a toast and on the notice bar, with a button to the JavaScript console, and doc_info reports as xfa_scripts_off) and what open-time scripts changed is noted. A script that fails partway keeps what it changed before the error, as JavaScript does (forms often trip over an object an earlier version had after their first lines did the work). Missing: a page area's relevant=\"-print\" (on a synthetic form Acrobat still prints the page but leaves it blank; PdfCraft prints its content, #2574); a page break before the first section (Acrobat opens an empty body page first when the first section has breakBefore targetType=pageArea, with or without startNew, as seen on synthetic forms; PdfCraft skips a break on an empty page and lays out one page fewer, #2574); loops inside nested calls are only stopped by abandoning their thread, and script memory is not capped; the change event per keystroke; xfa.template, connections and data descriptions; a hidden instance of a repeating subform hides them all; barcodes are drawn as their text, not bars; keep rules; text is measured at the exact standard-14 widths of the face it is drawn in (bold, italic and Times included), not in the template's own typefaces, and Acrobat fidelity is eyeballed on real forms, not measured (#60)" [[feature]] id = "form.xfa-formcalc" diff --git a/vendor/README.md b/vendor/README.md index 77bb7773df..a80f132321 100644 --- a/vendor/README.md +++ b/vendor/README.md @@ -18,7 +18,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 `.notdef` for a CID of an Adobe character collection (Japan1, GB1, CNS1, Korea1) that it can't find by Unicode: hayro took the CID for a glyph index of the substitute, which numbers its glyphs its own way, so the character was drawn as an unrelated one (𠮷 as "Q" in BIZ UDPGothic); (22) a Type 0 font drawn with a substitute finds a character given with a variation selector (`/ToUnicode`, or Adobe-Japan1-UCS2, which maps the JIS X 0208 forms of the kanji JIS X 0213:2004 redrew that way: CID 1247 is 噂 U+E0100) through the substitute's variation sequences, else as the character alone: such a CID found no glyph and was drawn as an unrelated one; (23) backport of hayro 0.8's `gradient` module: `EncodedShadingPattern::as_svg_gradient` turns an axial or radial shading into stops of an sRGB gradient (within 0.01 per channel, a stop at every stitching-function bound via `Function::stitching_bounds`) when a native gradient draws it exactly (extended past the box drawn in; a radial one with no background colour); (24) `DecodedImageCache`: decoded image pixels shared across renders through the interpreter cache within a 64 MiB budget (an image-heavy page decoded its thousands of images again per tile and per scale), keyed by every decode input (`DecodedImageKey`: the stream's place and dictionary bytes, its object, mask/stencil/raster output, interpolation, decode target size, preview or final); images under a transfer function and inline images are not cached, an image over the budget is never kept, and a poisoned lock decodes uncached; (25) `Device::actual_text` hands the device a marked content sequence's `/ActualText` (inline or named in `/Properties`), so text extraction keeps the Thai, Indic and Arabic clusters Chrome marks this way (their shaped tone marks and vowels have no Unicode of their own); (26) non-embedded simple fonts drawn with a standard-font stand-in build the Latin Extended-A letters the stand-in lacks (`/Gbreve`, `/Idotaccent`, `/Scedilla`, `/aogonek`, `/ccaron`…) from the base letter and accent it has (`StandardKind::composite_glyph`, `ACCENTED_LETTERS`): PDFium's Foxit stand-ins hold only the Standard/WinAnsi/Mac Roman glyphs, so iText letters with Times New Roman unembedded showed blanks for Ğ, İ, Ş, ğ and ş; the comma-below letters (`/scommaaccent`, `/Tcommaaccent`, `/kcommaaccent`…, found by character, so `/uni0136` and the glyph list's `/Kcedilla` too) are the letter and the font's comma, smaller and under the baseline, since the stand-ins have no `commaaccent` (Romanian ș drew nothing and ț a cedilla in forms laid out from XFA; ģ, whose comma is turned and above, is not built); (27) an embedded TrueType font without a base encoding reads its codes as WinAnsi for text extraction (`EmbeddedKind::code_to_unicode_name`), matching pdftotext's output, instead of Standard: OCR text layers of scans write WinAnsi codes with no `/Encoding`, and Standard has no ü, ö or ß and reads é as Ø (glyph selection unchanged); (28) an image whose pixels hold at most 16 bits of samples (an 8-bit Separation or DeviceN image, a 1-, 2- or 4-bit gray or indexed one) is converted once per possible pixel value through a lookup table instead of once per pixel (`rgb_via_lookup`): a spot-colour tint transform is often a PostScript calculator program, run for every pixel, so a fillable character sheet's 3304 × 4105 DeviceN background took four seconds and 430 MB to draw a page; each entry is converted on its own (`convert_each`), so a tint transform giving the wrong number of components for a value the image never uses cannot shift the colours of the values it does; (29) `Device::begin_annotations`/`end_annotations` bracket the page's annotations, so a device can tell comment paints from document paints (reading colours recolour the document, never a comment, #1548); (30) the Annex D.2 alias codes read as the ink they draw: WinAnsiEncoding 0xA0 and 0xAD, and MacRomanEncoding 0xCA, carry the glyph names `space` and `hyphen` -- the names those tables also give 0x20 and 0x2D -- not `nbspace` and `sfthyphen`, whose glyph list values U+00A0 and U+00AD are invisible formatting characters. Extraction hid drawn ink behind them, so search and redaction matched neither (`XiaoBiaoSong.pdf` in the pdf.js corpus drew 104 soft hyphens; across the 989 files the soft hyphens we extract fall from 117 to 13 and the non-breaking spaces from 30 to 26, what remains coming from `/ToUnicode` maps, which say so explicitly). The base table only, in the text direction only: a `/Differences` name keeps its glyph list value and glyph lookup is untouched, both as pdftotext does; (31) a Type 0 sampled function keeps its samples in one flat array indexed by strides (`Type0::entry`) instead of a hash map keyed by each grid point: the map was built again, one hashed insert per sample, every time a shading using the function was painted (a 2,097,152-sample ramp painted 30 times took 38 s; `bug1721218` in the pdf.js corpus spent most of a 1.5 s page on it); the interpolation is unchanged, so results are bit for bit the same, a sample missing from a short stream still gives no value, and the maximum sample value is computed without overflowing at 32 bits per sample; (32) the decoded-image cache (24) keys a decode by the size the image is drawn at only when a JPX stream decodes it or its soft mask or mask (`decode_reads_target`): JPX is the only filter that decodes a reduced resolution for a size, so a JPEG or Flate scan was decoded again at every zoom step and kept once per zoom level; one decode now serves every size; `InterpreterCache::decoded_image_decodes` counts the cache's decodes; (33) Coons and tensor-product patches copy their vertices' colours less: each point of a patch's 20 × 20 triangle grid is interpolated once (`generate_patch_triangles`; each cell interpolated its four corners itself, 1,444 interpolations a patch for 400 points), a cell's second triangle takes the vertices its first copied, and the mesh sampler moves a patch's triangles into device space instead of copying each vertex (`TriangleSampler::sample_owned`); the same values, 10–16% faster on mesh-gradient pages; (34) `color::tint_transform_runs`: how many colours the calling thread has run through a Separation or DeviceN tint transform (counted once per batch in `convert_f32`), so a test counts patch (28)'s once-per-sample-value runs instead of timing them (its 10 s deadline failed on a busy FreeBSD VM in CI); (35) `EncodedShadingPattern::extent`: where a mesh shading (types 4–7) can paint at all, the pixels its triangles touched when it was encoded (`None` for the types that paint everywhere, and when the shading has a `/Background`), so the renderer samples a texture there alone and skips a mesh with nothing on the canvas; (36) a mesh shading's pixel whose corner no triangle holds strictly (on an edge two triangles share, or on the mesh's side) takes the triangle that covers its centre, edges included (`Triangle::covers`): testing only the corner left a white seam along every shared edge, and the colour is still taken at the corner; (38) the `/DefaultGray`, `/DefaultRGB` and `/DefaultCMYK` colour spaces of a resource dictionary (ISO 32000-2 §8.6.5.6) replace the device space content selects: with `g`/`G`, `rg`/`RG`, `k`/`K` and `cs`/`CS` (by name, or through a `/ColorSpace` resource that is a device space), and as the `/ColorSpace` of an image XObject, an inline image or a shading painted by `sh` or as a shading pattern (`DefaultColorSpaces`, looked up once per content window in the resources and those they inherit, so a form XObject without a default of its own draws in its page's, as Poppler and MuPDF draw it); a default that is a Lab, Indexed, Pattern or device space, has another number of components or is no colour space is ignored and device colour is drawn as before; device spaces inside other spaces (an Indexed base, a Separation or DeviceN alternate, a Pattern's underlying space), shading dictionaries, masks and transparency group spaces are unchanged, and the decoded-image cache (24) keys a decode by the default it was drawn in. hayro drew device colour as it was, so pages that calibrate it this way (common in PDF/A) came out in the wrong colours; (39) knockout groups (#2971): `Device::set_knockout` right after a `/K true` group is pushed; `Device::knockout_image` for an unmasked image before its group is pushed, when `Device::in_knockout_group`: the device clears its placement rectangle only if it will draw the image (on the canvas, not a preview's tiny image, and it decodes), decoded at its draw size so the draw reuses that decode; and, when `Device::knockout_erase_wanted`, a nested group's content drawn once between `begin_knockout_erase` and `end_knockout_erase` before the group itself, which then always gets a layer of its own; (40) an optional content membership dictionary's visibility expression (`/VE`: `/And`, `/Or`, `/Not`, nested up to 32 deep) decides its visibility ahead of `/OCGs` and `/P` (ISO 32000-2 §8.11.2.2); it was ignored, so content under it stayed visible with its layers hidden; a malformed expression, including one naming an object the document doesn't list in `/OCProperties /OCGs`, falls back to `/OCGs` and `/P` (#2986); (41) a transparency group that is neither isolated nor knockout, entered at full opacity with no soft mask and Normal blending, is drawn straight onto the page instead of into a layer of its own (§11.4.7: its elements composite with the backdrop; the layer made a `/BM /Multiply` highlight appearance an opaque block, #1968); (42) text in a Type 3 font is drawn filled whatever the text rendering mode, except mode 3 (invisible): only that mode has any effect on Type 3 fonts (ISO 32000-1 §9.3.6). Stroking ran the glyph procedure a second time, so `2 Tr` made bitmap fonts look bold, `1 Tr` painted an uncoloured glyph in the stroking colour, and `7 Tr` hid it; (43) Lab colour spaces honour their own `/WhitePoint`: L\*a\*b\* goes to XYZ relative to that white, is Bradford-adapted to D65 and converted to sRGB (ISO 32000-2 §8.6.5.4) instead of through `LAB.icc` as if every white were D50 (a D65 blue came out 45 levels too red; the profile is removed); components normalised to [0, 1] (`manual_scale`, an `/Indexed` palette over Lab) map onto L\* 0..100 and the a\*/b\* `/Range`; (44) a Type 0 font whose `/ToUnicode` is the name `/Identity-H` or `/Identity-V` (not a CMap stream; WSCAD writes it) reads each code as its Unicode value, as Acrobat shows it (`Type0Font::identity_to_unicode`); the identity CMap the name resolved to maps codes to CIDs only, so such pages had no text to select or find; (46) an image XObject's group applies the fill opacity, so the fill alpha is reset to 1 before a stencil mask takes the fill colour as its paint, and a pattern paint drops the opacity it captured at `scn` (`Pattern::without_opacity`) (it was applied twice: a mask at `ca 0.5` was drawn at a quarter, #2975); (47) `path_as_rect`: a five-element path is a rectangle only when its four points are distinct, each step from one to the next runs along a single axis, and the last returns to the first. The length test admits one MoveTo and four LineTo as well as one MoveTo, three LineTo and a ClosePath, and asking only that every corner of the bounding box was visited says nothing about the order or the steps between, so a five-point polyline whose ends reached the corners was painted as that box -- a fourth side the path does not have -- and a clip of that shape was discarded; the coordinates are compared exactly, since the matrix is applied after this check and a `cm` of 10,000 turns `is_nearly_equal`'s 256th of a unit into tens of device units (#3327); (48) an `/ICCBased` colour space is cached by what its profile is read from (`IccProfileKey`): the stream object it names, looked up without reading the stream, and then the stream's dictionary and its own bytes (decrypted, not decoded), so a byte-for-byte copy of a profile in another object is read once, and a profile stream written directly in its array, which reports the object holding the array as every other stream written there does, is told apart by its bytes. hayro keyed it by the stream dictionary's bytes alone, so two different profiles with the same `/N` and `/Length` shared whichever was read first, and colours in the second were drawn through the first. `InterpreterCache::icc_profile_reads` counts the profiles read; (49) `OpenTypeFontBlob::new` also accepts a `post` table version 1.0, 2.0 or 3.0 written with its 16-bit halves swapped (`00 00 00 03`), as ScanSoft PDF Create! embeds every font; such fonts were refused and their text drawn with a substitute (Hebrew came out garbled or missing, #2946); `glyph_names` reads such a table from a copy with the version written correctly, so a 2.0 table's names serve `/Differences`. Any other unknown version is still refused (pdf.js 9462); (50) `CffFontBlob::glyph_index_by_name` looks a glyph name up in a name to glyph map built on first use (shared between clones) instead of searching the whole charset, with a string lookup per glyph, for every character code of a font; the first glyph with a name still wins; (51) at most 4096 graphics states saved at once, holding at most 64 MiB together (each `q` copies the whole state, dash array and clip list included, so short operators multiplied one large state); a `q` past either limit is counted but not copied, and its `Q` still removes the clips added since (from storytold/craft-libs#239); (52) a `/W2` run whose first CID is past `MAX_CID` stops there, as in `/W` (7), checked before the run's metrics are read: a first CID of 4294967295 inserted one entry and then overflowed, discarding the whole `/W2` table (from storytold/craft-libs#254); (55) a Separation or DeviceN tint transform that cannot be read keeps its colour space, and one that cannot be read or evaluated paints the alternate space's initial colour, as evaluation failures already did; that fallback, and a `cs`/`CS` colour space that cannot be read (drawn in DeviceGray as before), are now reported once per content stream as `InterpreterWarning::ColorFallback` (`RenderWarning::ColourFallback` in `pdfcraft-render`) instead of silently (#4260); (56) an annotation whose Invisible flag (bit 1) is set and whose `/Subtype` is none of the standard types of ISO 32000-2 Table 171 (`is_standard_annotation_type`; no `/Subtype` counts as unknown) is not drawn (Table 167), and a `/Popup` annotation's appearance is never painted on the page (§12.5.6.14: a popup has no appearance stream of its own; the viewer shows it as a window for its parent annotation). Both were drawn from their `/AP`; (57) a simple font drawn with a standard-font stand-in because the document names a font it doesn't embed (`StandardKind` with `fallback`) narrows a glyph to a narrower `/Widths` advance but no longer widens it to a wider one: the advance already places the next glyph (ISO 32000-2 §9.2.4; /Widths in Table 109), and widening drew a non-embedded `Arial,Bold` with 600-unit widths as a heavy fixed-pitch face whose `i` and `l` were solid blocks twice their width; an exact standard-14 font still matches its standard metrics both ways; (58) the fallback request for a Type 0 font that is not embedded (`FallbackFontQuery::with_descriptor`) takes its serif, italic and small-cap flags, `/FontWeight`, `/FontFamily` and `/FontStretch` from the descendant CIDFont's font descriptor (ISO 32000-2 §9.7.4.1, §9.7.6.1; §9.8): it read them from the Type 0 dictionary, which has none, so every such request asked for a regular sans-serif face and no resolver could tell a Song or Mincho font from a Hei or Gothic one, or see `/FontWeight 700`; (59) the NoRotate flag (`/F` bit 5) is honoured: the appearance, fitted to `/Rect`, is turned against the page's `/Rotate` about the rectangle's upper-left corner, which stays where it is, so it reads upright as the page is displayed (ISO 32000-2 §12.5.3). Sticky notes, which are saved NoRotate, were drawn turned with the page (#2583). Form fields and links stay in `/Rect`, where PdfCraft takes their click targets from it | (1) `raster::tests::widget_appearance_states`; (2, 3) `xtask text-oracle` on corpus/pdfjs issue918; (4) `raster::tests::layer_override_hides_content`; (5) `raster::tests::soft_mask_without_group_colour_space_is_applied`; (6) `raster::tests::self_referencing_tiling_pattern_terminates`, `raster::tests::self_referencing_type3_glyph_terminates`; (7) `raster::tests::huge_cid_width_ranges_terminate`; (8) `raster::tests::hiding_comments_keeps_fields`; (9) `raster::tests::absurd_mask_and_fax_sizes_are_refused_before_decoding`; (10) `raster::tests::type3_glyphs_that_fan_out_into_themselves_finish`; (11) `raster::tests::type1_font_programs_with_long_runs_of_numbers_load_quickly`; (12) `raster::tests::degenerate_annotation_appearances_are_skipped`; (13) `raster::tests::highlights_without_an_appearance_are_drawn`; (14) `raster::tests::malformed_simple_font_widths_keep_later_widths_and_the_font`, `raster::tests::huge_simple_font_first_char_terminates`; (15) `raster::tests::annotation_appearance_box_maps_onto_rect`; (16) `raster::tests::clipping_path_applies_after_any_painting_operator`; (17) `raster::tests::dropping_the_pool_cancels_its_renders`, `raster::tests::the_watchdog_stops_the_render_it_gives_up_on`; (18) `raster::tests::page_contents_and_nested_forms_share_one_budget`, `raster::tests::content_painted_again_and_again_keeps_drawing`, `raster::tests::sampled_functions_with_billions_of_samples_are_refused`; (19) `raster::tests::mesh_shadings_far_off_the_page_render`, `raster::tests::many_overlapping_mesh_triangles_finish`, `raster::tests::mesh_shadings_with_many_patches_or_no_rows_finish`; (20) `raster::tests::function_limits_calculator_arithmetic_and_depth`, `raster::tests::function_limits_public_construction_work_and_depth`, `raster::tests::function_limits_stitching_cycles_are_refused_and_shared_children_work`, `raster::tests::function_limits_invalid_calculator_keeps_the_page_renderable`; (21) `raster::tests::cids_a_substitute_lacks_are_not_drawn_as_other_glyphs`; (22) `raster::tests::variation_sequences_draw_their_kanji_in_a_substitute`; (23) `raster::tests::axial_and_radial_shadings_draw_as_native_gradients`; (24) `raster::tests::tiles_match_full_render`, `raster::tests::skipping_paths_off_the_canvas_changes_no_pixel` (both decode through the cache), `raster::tests::decoded_images_with_identical_dictionaries_keep_their_own_pixels`, `raster::tests::decoded_images_under_a_transfer_function_are_not_shared`; (25) `text::tests::actual_text_replaces_the_glyphs_it_marks_in_every_writing_direction`, `text::tests::actual_text_follows_the_pdf_rules_for_marked_content`; (26) `raster::tests::accented_letters_the_standard_stand_ins_lack_are_built_from_their_parts`, `raster::tests::comma_below_letters_in_standard_fonts_draw_a_comma_under_the_letter`; (27) `text::tests::truetype_without_an_encoding_reads_its_codes_as_win_ansi`; (28) `raster::tests::spot_colour_images_run_their_tint_transform_once_per_sample_value`, `raster::tests::images_converted_through_a_table_keep_every_samples_colour`, `raster::tests::a_malformed_tint_for_an_unused_sample_keeps_the_used_colours`; (29) `raster::tests::reading_colors_keep_highlight_annotations_readable`; (30) `text::tests::the_annex_d2_alias_codes_read_as_an_ordinary_hyphen_and_space`; (31) `raster::tests::shadings_with_large_sampled_functions_paint_quickly`, `raster::tests::sampled_functions_interpolate_their_grid_as_before`; (32) `raster::tests::decoded_images_serve_every_size_they_are_drawn_at`; (33) `raster::tests::patch_meshes_keep_their_corner_colours`; (34) `raster::tests::spot_colour_images_run_their_tint_transform_once_per_sample_value`; (35) `mesh_extent_tests::{a_mesh_paints_its_triangles_alone, a_mesh_keeps_the_graphics_state_alpha, a_mesh_off_the_canvas_paints_nothing}` (`cargo test -p hayro`); (36) `raster::tests::mesh_triangles_sharing_an_edge_leave_no_seam`; (38) `raster::tests::default_colour_spaces::device_rgb_operators_draw_in_default_rgb`, `raster::tests::default_colour_spaces::device_cmyk_operators_draw_in_default_cmyk`, `raster::tests::default_colour_spaces::device_gray_operators_draw_in_default_gray`, `raster::tests::default_colour_spaces::device_images_draw_in_the_default_colour_spaces`, `raster::tests::default_colour_spaces::device_shadings_draw_in_the_default_colour_spaces`, `raster::tests::default_colour_spaces::an_image_drawn_with_and_without_a_default_keeps_both_colours`, `raster::tests::default_colour_spaces::forms_inherit_the_default_colour_spaces_they_do_not_override`, `raster::tests::default_colour_spaces::unusable_defaults_leave_device_colour_alone`; (39) `raster::tests::knockout_groups_replace_what_their_elements_cover`; (40) `raster::tests::visibility_expressions_decide_what_a_membership_dictionary_shows`; (41) `raster::tests::a_multiply_highlight_inside_a_transparency_group_keeps_the_text`; (42) `raster::tests::text_rendering_modes_other_than_invisible_draw_type3_glyphs_as_filled`; (43) `raster::tests::lab_honours_the_space_white_point`, `raster::tests::indexed_palettes_over_lab_keep_their_colours` |; (44) `text::tests::identity_to_unicode_names_give_text`; (46) `raster::tests::stencil_masks_are_drawn_at_the_fill_opacity_once`; (47) `raster::tests::a_five_point_polyline_is_not_painted_as_its_bounding_box`, `raster::tests::a_path_that_visits_every_corner_out_of_order_is_not_a_rectangle`, `raster::tests::a_rectangle_is_still_painted_as_a_rectangle`; (48) `raster::tests::icc_profile_cache::icc_profiles_with_identical_dictionaries_draw_their_own_colours`, `raster::tests::icc_profile_cache::icc_profiles_used_again_are_read_once`; (49) `raster::tests::a_font_whose_post_version_has_swapped_halves_is_still_used`; (50) `font::blob::tests::glyph_names_resolve_to_the_first_glyph_with_that_name`; (51) `context::saved_state_tests::repeated_saves_stay_bounded_and_balanced`; (52) `font::cid::tests::w2_run_past_the_largest_cid_keeps_the_rest_of_the_table` (hayro-interpret); (55) `raster::tests::devicen_inks::a_tint_transform_that_cannot_be_evaluated_draws_the_rest_of_the_page_and_warns`, `raster::tests::devicen_inks::a_tint_transform_that_cannot_be_read_falls_back_and_warns`; (56) `raster::tests::invisible_unknown_annotations_and_popups_paint_nothing`; (57) `substitute_widths::a_substitute_keeps_its_glyph_shapes_at_wider_advances`, `substitute_widths::a_substitute_still_narrows_glyphs_to_narrower_advances` (pdfcraft-render `tests/it`); (58) `cid_fallback_query::a_cid_font_fallback_request_carries_its_descendants_style`, `cid_fallback_query::a_cid_font_without_a_descriptor_asks_for_the_default_style` (pdfcraft-render integration tests); (59) `raster::tests::no_rotate_notes_stay_upright_at_their_corner_on_rotated_pages` (hayro-interpret) | -| 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, 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` 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, interpolated, axis-aligned image is snapped to whole device pixels: shrunk once to its rounded device rectangle and drawn 1:1 at 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); (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 stroke thinner than the shrink factor; (16) under a soft mask or a blend mode, axial and radial shadings are sampled instead of drawn as native gradients (#2128): vello_cpu 0.0.8 copies an opaque gradient over fully covered tiles without the mask or blend mode, so PowerPoint's faded gradient fills came out solid; (17) the renderer keeps annotation paints out of the reading-colours mapping between `begin_annotations` and `end_annotations` (#1548); (18) the page renders as one transparency group; under reading colours its background is painted inside it as the initial backdrop, so a Multiply highlight blends with the dark background instead of staying an opaque block, and otherwise the background stays outside, so a blend mode over an empty part of the page keeps its colour instead of blending with the white paper (#2970); (19) `set_paint` samples a mesh shading's texture over its triangles alone (`EncodedShadingPattern::extent`, padded rather than repeated) and skips a mesh with none on the canvas: a BricsCAD plan's 310 one-triangle `sh` each covered the whole tile, 2 s per 1024 px tile at any zoom (the watchdog gave the page up on a busy machine), now about 70 ms; (20) a tiling pattern whose step is too large for a cell pixmap, where what is painted (a fill, or a stroke with its width) can only show the first cell (PowerPoint's `/XStep 2147480100` for a picture fill drawn once), has its `/BBox` drawn at full scale with a transparent border and padded instead of tiled (`shows_one_cell`; a cell whose scale isn't finite and positive, from a `/BBox` too thin to divide by, keeps the old path: `usable_cell_scale`); shrinking the cell to fit the 3000 px limit of (3) left the picture under a pixel, so network diagrams lost their pictures (#3349); (22) knockout groups: while one is innermost, fills, strokes, glyph outlines and shadings are drawn with `Compose::Copy` (weighted by coverage), so each element replaces what earlier elements of the group drew instead of compositing over it; an image or nested group, drawn into a layer of its own, first has what is under its shape cleared (`knockout_image` for an unmasked image's rectangle, only when `draw_image` will draw it, decoded at the size it is drawn; a knockout erase pass that draws a nested group's content with every paint clearing instead of painting, a shading fill's clear clipped to the shading's `/BBox` as its paint is) and then composites over it (#2971); (23) backport of hayro 0.8: shadings that `as_svg_gradient` can represent are painted as a `vello_cpu` linear or two-point radial gradient instead of a texture sampled pixel by pixel through the shading function (InDesign fades are luminosity soft masks of one full-page axial `sh`: 40 on a report page took 15 s at 144 dpi, now under 1 s); without upstream's half-pixel shift, which suits vello_cpu 0.3 but moves 0.0.8's gradients off pixel centres | (1) `raster::tests::tiles_match_full_render`; (2) `raster::tests::absurd_image_dimensions_are_skipped`; (3) `raster::tests::tiling_cells_stay_small_whatever_the_step`; (4) `raster::tests::absurd_predictor_columns_and_line_widths_render`; (5) `raster::tests::dash_patterns_that_cut_a_stroke_into_billions_of_pieces_render`; (6) `raster::tests::invalid_dash_patterns_terminate_and_are_drawn_solid`; (7) `raster::tests::pixels_are_a_plain_renders_bytes_in_a_buffer_a_gui_can_take_over`; (8) `raster::tests::image_resampling_rejects_anisotropic_target_growth`, `raster::tests::image_resampling_bounds_intermediate_before_planning`, `raster::tests::image_resampling_rejects_invalid_sources_and_scales`, `raster::tests::image_resampling_keeps_valid_sizes_and_exact_limits`, `raster::tests::resampling_fallback_preserves_original_geometry_and_pixels`, `raster::tests::image_resampling_wide_sources_shrink_before_backend_side_limits`, `raster::tests::image_resampling_wide_transparent_sources_still_shrink`, `raster::tests::image_resampling_padded_backend_dimensions_stay_checked`, `raster::tests::image_resampling_mismatched_alpha_mask_keeps_pixels_and_placement`; (9) `raster::tests::skipping_paths_off_the_canvas_changes_no_pixel`; (10) `raster::tests::non_interpolated_images_are_not_smoothed_when_minified`, `raster::tests::non_interpolated_gray_images_are_not_smoothed_when_minified`, `raster::tests::non_integer_minification_samples_the_same_columns`, `raster::tests::non_integer_minification_samples_colour_and_mask_from_the_same_columns`, `raster::tests::non_interpolated_alpha_images_keep_their_colours_and_mask_when_minified`, `raster::tests::non_interpolated_type3_glyph_images_are_not_smoothed_when_minified`, `raster::tests::image_resampling_nearest_accepts_wide_sources_the_filter_refuses`, `raster::tests::wide_non_interpolated_sources_draw_after_shrinking`; (11) `raster::tests::skipping_paths_off_the_canvas_changes_no_pixel`; (12) `raster::tests::preview_renders_skip_tiny_images_but_finals_draw_everything`; (13) `color_replacement_tests::{black_maps_to_text_colour, white_maps_to_background, midgrey_interpolates, alpha_copied_verbatim, only_black_threshold, line_art_false_skips_paths_but_not_text}`, `color_replacement_render_tests::{color_replacement_maps_text_and_line_art, color_replacement_maps_stencil_mask_ink}`; (14) `raster::tests::interpolated_minified_image_edges_snap_to_whole_pixels` (`cargo test -p hayro`); (15) `raster::tests::shrunk_soft_mask_larger_than_its_image_keeps_thin_strokes`; (16) `raster::tests::soft_mask_applies_to_a_shading_pattern_fill`; (17), (18) `raster::tests::reading_colors_keep_highlight_annotations_readable`; (19) `mesh_extent_tests::{a_mesh_paints_its_triangles_alone, a_mesh_keeps_the_graphics_state_alpha, a_mesh_off_the_canvas_paints_nothing}` (`cargo test -p hayro`); (20) `raster::tests::a_tiling_pattern_drawn_once_shows_its_cell`, `raster::tests::a_large_step_still_tiles_where_the_next_cell_shows`, `raster::tests::a_tiling_cell_too_thin_to_scale_keeps_the_old_path` |; (22) `raster::tests::knockout_groups_replace_what_their_elements_cover`; (23) `raster::tests::axial_and_radial_shadings_draw_as_native_gradients` | +| 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, 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` 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, interpolated, axis-aligned image is snapped to whole device pixels: shrunk once to its rounded device rectangle and drawn 1:1 at 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); (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 stroke thinner than the shrink factor; (16) under a soft mask or a blend mode, axial and radial shadings are sampled instead of drawn as native gradients (#2128): vello_cpu 0.0.8 copies an opaque gradient over fully covered tiles without the mask or blend mode, so PowerPoint's faded gradient fills came out solid; (17) the renderer keeps annotation paints out of the reading-colours mapping between `begin_annotations` and `end_annotations` (#1548); (18) the page renders as one transparency group; under reading colours its background is painted inside it as the initial backdrop, so a Multiply highlight blends with the dark background instead of staying an opaque block, and otherwise the background stays outside, so a blend mode over an empty part of the page keeps its colour instead of blending with the white paper (#2970); (19) `set_paint` samples a mesh shading's texture over its triangles alone (`EncodedShadingPattern::extent`, padded rather than repeated) and skips a mesh with none on the canvas: a BricsCAD plan's 310 one-triangle `sh` each covered the whole tile, 2 s per 1024 px tile at any zoom (the watchdog gave the page up on a busy machine), now about 70 ms; (20) a tiling pattern whose step is too large for a cell pixmap, where what is painted (a fill, or a stroke with its width) can only show the first cell (PowerPoint's `/XStep 2147480100` for a picture fill drawn once), has its `/BBox` drawn at full scale with a transparent border and padded instead of tiled (`shows_one_cell`; a cell whose scale isn't finite and positive, from a `/BBox` too thin to divide by, keeps the old path: `usable_cell_scale`); shrinking the cell to fit the 3000 px limit of (3) left the picture under a pixel, so network diagrams lost their pictures (#3349); (22) knockout groups: while one is innermost, fills, strokes, glyph outlines and shadings are drawn with `Compose::Copy` (weighted by coverage), so each element replaces what earlier elements of the group drew instead of compositing over it; an image or nested group, drawn into a layer of its own, first has what is under its shape cleared (`knockout_image` for an unmasked image's rectangle, only when `draw_image` will draw it, decoded at the size it is drawn; a knockout erase pass that draws a nested group's content with every paint clearing instead of painting, a shading fill's clear clipped to the shading's `/BBox` as its paint is) and then composites over it (#2971); (23) backport of hayro 0.8: shadings that `as_svg_gradient` can represent are painted as a `vello_cpu` linear or two-point radial gradient instead of a texture sampled pixel by pixel through the shading function (InDesign fades are luminosity soft masks of one full-page axial `sh`: 40 on a report page took 15 s at 144 dpi, now under 1 s); without upstream's half-pixel shift, which suits vello_cpu 0.3 but moves 0.0.8's gradients off pixel centres; (25) a tiling cell is drawn at the scale that makes one `/XStep` (`/YStep`) exactly the cell pixmap's whole number of pixels (`tiling_cell_pixels`, at least 1 and at most the cap), so the repeated pixmap puts cells at whole multiples of the step at any device scale; drawing at the unrounded scale repeated the cell up to half a pixel off at every step, and the error grew with distance from the pattern's origin (ISO 32000-2 8.7.3.1) | (1) `raster::tests::tiles_match_full_render`; (2) `raster::tests::absurd_image_dimensions_are_skipped`; (3) `raster::tests::tiling_cells_stay_small_whatever_the_step`; (4) `raster::tests::absurd_predictor_columns_and_line_widths_render`; (5) `raster::tests::dash_patterns_that_cut_a_stroke_into_billions_of_pieces_render`; (6) `raster::tests::invalid_dash_patterns_terminate_and_are_drawn_solid`; (7) `raster::tests::pixels_are_a_plain_renders_bytes_in_a_buffer_a_gui_can_take_over`; (8) `raster::tests::image_resampling_rejects_anisotropic_target_growth`, `raster::tests::image_resampling_bounds_intermediate_before_planning`, `raster::tests::image_resampling_rejects_invalid_sources_and_scales`, `raster::tests::image_resampling_keeps_valid_sizes_and_exact_limits`, `raster::tests::resampling_fallback_preserves_original_geometry_and_pixels`, `raster::tests::image_resampling_wide_sources_shrink_before_backend_side_limits`, `raster::tests::image_resampling_wide_transparent_sources_still_shrink`, `raster::tests::image_resampling_padded_backend_dimensions_stay_checked`, `raster::tests::image_resampling_mismatched_alpha_mask_keeps_pixels_and_placement`; (9) `raster::tests::skipping_paths_off_the_canvas_changes_no_pixel`; (10) `raster::tests::non_interpolated_images_are_not_smoothed_when_minified`, `raster::tests::non_interpolated_gray_images_are_not_smoothed_when_minified`, `raster::tests::non_integer_minification_samples_the_same_columns`, `raster::tests::non_integer_minification_samples_colour_and_mask_from_the_same_columns`, `raster::tests::non_interpolated_alpha_images_keep_their_colours_and_mask_when_minified`, `raster::tests::non_interpolated_type3_glyph_images_are_not_smoothed_when_minified`, `raster::tests::image_resampling_nearest_accepts_wide_sources_the_filter_refuses`, `raster::tests::wide_non_interpolated_sources_draw_after_shrinking`; (11) `raster::tests::skipping_paths_off_the_canvas_changes_no_pixel`; (12) `raster::tests::preview_renders_skip_tiny_images_but_finals_draw_everything`; (13) `color_replacement_tests::{black_maps_to_text_colour, white_maps_to_background, midgrey_interpolates, alpha_copied_verbatim, only_black_threshold, line_art_false_skips_paths_but_not_text}`, `color_replacement_render_tests::{color_replacement_maps_text_and_line_art, color_replacement_maps_stencil_mask_ink}`; (14) `raster::tests::interpolated_minified_image_edges_snap_to_whole_pixels` (`cargo test -p hayro`); (15) `raster::tests::shrunk_soft_mask_larger_than_its_image_keeps_thin_strokes`; (16) `raster::tests::soft_mask_applies_to_a_shading_pattern_fill`; (17), (18) `raster::tests::reading_colors_keep_highlight_annotations_readable`; (19) `mesh_extent_tests::{a_mesh_paints_its_triangles_alone, a_mesh_keeps_the_graphics_state_alpha, a_mesh_off_the_canvas_paints_nothing}` (`cargo test -p hayro`); (20) `raster::tests::a_tiling_pattern_drawn_once_shows_its_cell`, `raster::tests::a_large_step_still_tiles_where_the_next_cell_shows`, `raster::tests::a_tiling_cell_too_thin_to_scale_keeps_the_old_path`; (22) `raster::tests::knockout_groups_replace_what_their_elements_cover`; (23) `raster::tests::axial_and_radial_shadings_draw_as_native_gradients`; (25) `tiling_cell_placement::{far_cells_of_a_fill_sit_at_whole_steps, far_cells_sit_at_whole_steps_under_a_turned_scaled_matrix, far_cells_of_a_stroke_sit_at_whole_steps, a_cell_pixmap_spans_exactly_one_step}` (`cargo test -p pdfcraft-render --test it`) | | hayro-jbig2 | 0.3.0 | Apache-2.0 OR MIT | (1) at most 2^28 pixels per bitmap, page bitmap, halftone grid and grayscale image (each side could be 65535: 4.3 billion pixels decoded one by one); (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) | (1) `raster::tests::jbig2_regions_of_billions_of_pixels_are_refused`; (2) the nightly `cargo xtask fuzz` finding, which now finishes in about a second; (3) `raster::tests::jbig2_symbol_dictionaries_that_never_advance_terminate`; (4) `segment::tests::test_referred_to_count_is_capped` (`cargo test --manifest-path vendor/hayro-jbig2/Cargo.toml`) | | 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` | | hayro-syntax | 0.7.2 | Apache-2.0 OR MIT | (1) Page-tree cycle guard in `resolve_pages` (visited set + depth cap): a `/Kids` loop among compressed objects overflowed the stack and aborted the process; (2) `ccitt_size_ok`: CCITT images wider than 2^20 columns or over 2^28 pixels are not decoded (a fuzzed `/Columns 4294967295` allocated 4 GiB); (3) Flate/LZW predictor row widths are saturating `usize`, a zero width is refused and a row longer than the data is not allocated (a fuzzed `/Columns 9223372036854775807` wrapped to a 2^61-byte allocation and aborted); (4) the inline-image end-of-data check (`EI`) doesn't nest inside its own look-ahead and examines at most 256 candidates and steps (50 images with "EI" in their data ran for over ten minutes); an EI followed by a delimiter (EI%..., EI[...) ends the image like one followed by white space; only a regular character after EI skips the candidate; (5) a stream whose `/Length` is wrong is recovered only when `stream` is the next token — scanning ahead to a later object's `stream` made an indirect appearance-state dictionary (Quartz checkboxes: `/AP /N` → `<< /Yes … /Off … >>`) render as a non-form, so the widget was skipped; (6) JPX rescaling uses an exact integer sample range for 1–32-bit components (32 shifted past u32, and floating-point maxima at 25–31 bits wrapped to zero), and refuses zero-sized rows; (7) `decode_limit`: Flate (through flate2 and the fallback inflater), LZW, RunLength and ASCII85 never write past `MAX_DECODED_STREAM` (256 MiB), or, for the last filter of an image of known size, past twice its pixel bytes (a predictor tag byte per byte), at most 1 GiB; `Stream::decoded_within` for budgeted callers; a page's `/Contents` array shares one `MAX_DECODED_STREAM` (a 2 MB page whose content stream or 8 × 8 image inflated to 2 GB took the renderer past 3 GB in under a second; naming the stream twenty times in `/Contents`, 5 GB); (8) high-precision numbers (jsPDF MediaBox coordinates with over 19 digits) parse without overflowing the u64 mantissa: fractional digits past it are dropped, integer digits past it scale the value (a real, kept finite); (9) large dictionary indexes are built on first use and shared across repeated reads within each PDF (#307); the validated-byte cache is bounded, reader contexts remain separate, repairs and inline/content dictionaries bypass sharing, and small dictionaries stay eager; (10) decoded object-stream slots publish once under contention, cold loading rejects recursive dependencies, and xref repair serializes without holding recursive read guards; this permits one parser per native render pool with private worker caches; (11) `sync.rs`: a poisoned lock is recovered instead of unwrapped (a worker panic no longer cascades into every reader of the same PDF), and xref repair takes a blocking write lock instead of asserting a non-blocking one; (12) `SegmentList` (`util.rs`) returns `None` for an out-of-range index instead of panicking; (13) a page's `/UserUnit` scales `render_dimensions` and `initial_transform`, so the page and everything on it are sized in points, as Acrobat shows them; it is read as Acrobat reads it (the page's own entry, not inherited; a number from 1 up, at most 75,000; anything else counts as 1), and a page without it keeps exactly the transform it had; (14) revision 2–4 passwords are tried as given and then in PDFDocEncoding (`legacy_passwords` in `crypto/mod.rs`, which resolves the upstream `TODO: Convert to PDFDocEncoding`): passwords arrive as UTF-8 text, so a password with characters outside ASCII (`Çok güzel`, `ılık€`) written in PDFDocEncoding, as ISO 32000-2 §7.6.4.3.2 asks and qpdf and Acrobat write it, was always wrong; (15) page content is read a piece at a time (`page::ContentReader`, `Page::content_reader`): plain streams and Flate streams without a predictor are decoded as they are read, with a budget of 64 times their compressed size and never less than `MAX_DECODED_STREAM` (a stream that expands past it is cut and reported); other streams are decoded whole, as before, and share `MAX_DECODED_STREAM`. The content tokenizer reads a window at a time (`UntypedIter::new_window`, `TypedIter::needs_more`, `TypedIter::committed`): an instruction that runs past the window is not decided until more data follows, which `Reader` records by flagging reads and `at_end` past the end of the data, including through the clones the parser makes. The Flate decoder keeps its own 32 KiB history, so it pauses at any output size. `ContentReader::new` reuses raw/decrypted stream bytes for budget accounting and piece creation, and `decoded_raw_within` applies the existing Whole-stream filters and limits to those bytes without decrypting twice; (16) revision 5–6 (AES-256) passwords are tried in their SASLprep form (RFC 4013, then UTF-8, at most 127 bytes, as ISO 32000-2 §7.6.4.3.3 Algorithm 2.A asks and pdfcraft-crypt writes them) and then, if that differs, as given (`aes256_passwords` in `crypto/mod.rs`, which resolves the upstream `TODO: Do the above.`; `stringprep`, already in the tree through pdfcraft-crypt, is an optional dependency enabled by `std`, and without `std` passwords are used as given): the renderer used the password as typed, so one that SASLprep changes (a decomposed `café`, a no-break space, the fullwidth `ab` a Japanese IME types in full-width mode) was wrong, although pdfcraft-cos accepted it: protecting a document with such an open password was rolled back ("the password is incorrect"), and a file with such a password did not open with it.; (17) CCITT `/Rows 0` means the height is not predetermined (ISO 32000-2 Table 11), not zero rows: scanned Group 4 pages written that way rendered blank; (18) The streaming Flate decoder (`lzw_flate::flate::fallback`) copies a back-reference in runs of up to its distance (`extend_from_within`), not byte by byte. The copy reads only bytes already in the output, and a copy whose source does not exist still writes nothing, so the bytes are those a byte-by-byte copy writes. Inflating the A1 sample's content stream (278.6 MB) takes about 14% less time (0.66 s to 0.56 s); the output is identical; (19) CCITT `/Rows` below the image's `/Height` decodes to the height: a plotter driver wrote `/Rows` equal to `/Columns`, so only the first rows were decoded and the rest drawn black (#3308) (20) `stream` followed by spaces or tabs and then the line break (`stream \r\n`, as Microsoft Reporting Services writes it) starts the data after the line break; the content stream was taken to start at the space and the page rendered blank.; (21) a JP2 colour specification naming an enumerated colour space the decoder refuses (CIEJab in a veraPDF fixture, YCbCr, PhotoYCC, YPbPr, bilevel…) no longer fails the image: it is decoded again from a copy whose `colr` names the space the decoder assumes without one, greyscale, sRGB or CMYK by component count, as MuPDF and Poppler draw it (`without_refused_enumerated_colour`; the page drew blank, #3306); (22) an object stream's index of `objnum offset` pairs is parsed once per stream and kept beside its decoded data (`ObjectStreamIndexes`, `XRef::with_object_stream_indexes`), and an offset past `usize` is malformed instead of wrapping: `XRef::get_with` parsed the whole index again for every object it fetched from the stream, so reading all of a stream of N objects took N² steps (a Firefox page whose 65,542 objects share one stream took 37 s to draw and 40 s to extract its text); (23) the inline-image end-of-data look-ahead no longer rejects a candidate `EI` because a byte above 0x7F lies between it and the next one: when the candidate is the end, those bytes are the content stream that follows the image, and its strings carry such bytes (WinAnsi `(Grüße) Tj`, the two-byte codes of any Type 0 font), so the operator check that follows decides alone, bounded as in (4) (a scanned page whose OCR text held an accented word and a later capital "EI" — EINGANG, BEI, KLEIN — drew and extracted nothing after the image: 40 of 275 pages across five real documents); (24) `xref::prev_offset`: a trailer `/Prev` written as a reference `N G R` is read as the offset that object holds when the section's own entries place it (iText's `indirectPrev.pdf`; each section's entries are read before its `Prev` is followed), and otherwise as offset N (tiff2pdf; JHOVE's PDF-HUL-157 files, #2366), as `pdfcraft-cos` and other readers take it, so the earlier sections' pages are seen instead of one; (25) direct arrays and dictionaries share a reader-local nesting cap of 128, counted while skipping and while parsing a dictionary (its lenient repair reads, rather than skips, an object found where a key belongs, so `<< << …` recursed through that read); deeper objects return `None` instead of overflowing the stack (including unused trailer values, trailer entries, content operands and marked-content properties); a chain of 65 direct stitching functions now stops at this cap, before the 64-function guard; (26) an xref stream subsection must be backed by its decoded data: all-zero `/W` widths (an entry reads no bytes) and a declared count longer than the data are refused before any entry is inserted, where a tiny stream with a large `/Size` or `/Index` count inserted that many entries (from storytold/craft-libs#239); a subsection running past object number `i32::MAX` is refused instead of overflowing or turning negative; (27) an xref stream's type field is read big-endian at its full `/W[0]` width, where only its first byte was read and wider fields shifted every later entry, and `/W[0]` over 8 bytes is refused like `/W[1]` (from storytold/craft-libs#241); (28) a content instruction keeps up to 256 operands (`MAX_OPERANDS`) instead of 10, and past that drops the oldest instead of ending the content stream: the eleventh operand of a twelve-ink DeviceN `scn` (ISO 32000-2 §8.6.6.5 allows any number of components) blanked the rest of the page (#4260) | (1) `cos/tests/writer.rs::page_tree_loops_in_object_streams_do_not_crash_readers`; (2) `raster::tests::absurd_mask_and_fax_sizes_are_refused_before_decoding`; (3) `raster::tests::absurd_predictor_columns_and_line_widths_render`; (4) `raster::tests::inline_images_with_ei_in_their_data_parse_in_linear_time`, `content::tests::inline_image_ei_may_be_followed_by_a_delimiter`; (5) `raster::tests::indirect_appearance_state_dict_is_not_another_stream`; (6) `raster::tests::jpx_stream_bit_depth_boundaries_do_not_panic`, `raster::tests::jpx_32_bit_image_does_not_prevent_other_page_content_from_rendering`, `raster::tests::jpx_gray_rgb_and_alpha_keep_eight_bit_samples`, `raster::tests::jpx_streams_reject_out_of_range_bit_depths`; (7) `raster::tests::decompression_bombs_stop_at_the_stream_limit`, `raster::tests::page_contents_and_nested_forms_share_one_budget`; (8) `inspect::tests::jspdf_high_precision_mediabox_does_not_overflow_dimensions`, `object::number::tests::high_precision_float_does_not_overflow_mantissa` (hayro-syntax); (9) `object::dict::lazy_index_tests`, `raster::tests::large_resource_indexes_preserve_pixels_and_text`; (10) `data::tests`, `xref::tests::concurrent_cold_object_stream_reads_all_succeed`, `raster::tests::shared_parser_is_lazy_and_initializes_once_under_contention`; (11) `data::tests::panicking_initializer_wakes_waiters_and_prevents_retries`, `xref::tests::concurrent_cold_object_stream_reads_all_succeed`; (12) `util::tests::segment_list_rejects_out_of_range_indices`; (13) `raster::tests::user_unit_scales_the_page_and_everything_on_it`; (14) `crypto::pdfcraft_password_tests`, `pdfcraft-engine` `tests::legacy_passwords_with_turkish_characters_open`; (15) `content::tests::windows_keep_every_instruction_at_every_split`, `content::tests::windows_keep_every_instruction_in_pieces_of_any_size`, `content::tests::windows_match_the_slice_on_random_content`, `content::tests::windows_drop_blanks_and_keep_a_comment_that_may_go_on`, `page::content_reader_tests::content_past_the_cap_is_read_to_the_end`, `page::content_reader_tests::a_stream_that_expands_past_the_budget_is_cut_there`, `page::content_reader_tests::a_small_expansion_under_the_cap_is_not_cut`, `raster::tests::page_content_past_the_old_cap_renders`, `raster::tests::content_reader_returns_the_same_bytes_in_any_pieces`, `raster::tests::content_bombs_stop_at_the_budget_and_say_so`, `page::content_reader_tests::plain_and_whole_pieces_keep_their_bytes`, `page::content_reader_tests::repeated_content_reference_counts_compressed_bytes_once`, `page::content_reader_tests::whole_cap_still_counts_later_unique_streams`; (16) `crypto::pdfcraft_password_tests::aes256_passwords_are_tried_in_their_saslprep_form_then_as_given`, `crypto::pdfcraft_password_tests::aes256_passwords_open_as_typed_and_in_their_saslprep_form`, `pdfcraft-engine` `tests::aes256_open_passwords_that_saslprep_changes_protect_and_reopen_as_typed`, `tests::aes256_files_whose_passwords_saslprep_changes_open_as_typed`; (17) `raster::tests::group4_fax_with_rows_zero_decodes_to_the_image_height`; (18) `filter::lzw_flate::tests::back_reference_longer_than_its_distance_repeats_its_source`, `back_reference_cut_by_the_limit_resumes_in_the_next_call` and `back_reference_reads_bytes_written_by_an_earlier_call`; each fails when the copy returns the wrong remaining count; (19) `raster::tests::group4_fax_with_rows_below_its_height_decodes_to_the_image_height`; (20) `raster::tests::space_before_the_line_break_after_stream_still_renders`; (21) `raster::tests::a_jp2_image_in_a_refused_enumerated_colour_space_is_drawn`, `filter::jpx::tests::refused_enumerated_colour_spaces_become_the_component_counts_default`, `filter::jpx::tests::what_the_decoder_handles_or_cant_be_read_is_left_alone` (`cargo test --manifest-path vendor/hayro-syntax/Cargo.toml`); (22) `raster::tests::objects_in_one_large_object_stream_are_read_in_linear_time`; (23) `text::tests::text_after_an_inline_image_survives_a_non_ascii_byte_before_a_later_ei`, `content::tests::an_inline_image_ends_at_its_own_ei_when_later_text_holds_a_non_ascii_byte` (hayro-syntax); (24) `xref::tests::prev_as_reference_reaches_the_earlier_section`, `xref::tests::prev_as_reference_to_an_object_holding_the_offset_reads_that_offset`, `pdfcraft-cos` `document::tests::a_prev_written_as_a_reference_still_reaches_the_earlier_sections`, `document::tests::a_prev_reference_to_an_object_holding_the_offset_reads_that_offset`; (25) `raster::tests::deeply_nested_direct_objects_do_not_overflow_the_stack`, `raster::tests::dictionaries_nested_without_keys_in_content_do_not_overflow_the_stack`, `raster::tests::dictionaries_nested_without_keys_in_the_trailer_do_not_overflow_the_stack`, `raster::tests::dictionaries_nested_without_keys_as_marked_content_properties_do_not_overflow_the_stack`, `raster::tests::dictionaries_nested_without_keys_are_read_up_to_the_nesting_cap`, `raster::tests::nesting_at_the_cap_fits_a_512_kib_stack` (native only), `raster::tests::function_limits_depth_guard_refuses_a_chain_of_references`; (26) `xref::tests::xref_stream_entries_need_backing_bytes`; (27) `xref::tests::xref_stream_type_field_uses_the_full_w0_width`, `xref::tests::xref_stream_loader_rejects_oversized_w0` (`cargo test --manifest-path vendor/hayro-syntax/Cargo.toml`); (28) `content::ops::tests::scn_with_twelve_components_keeps_them_all`, `content::ops::tests::operands_past_the_cap_keep_the_latest_in_order` (hayro-syntax), `raster::tests::devicen_inks::a_twelve_ink_devicen_colour_paints`, `raster::tests::devicen_inks::a_four_ink_devicen_colour_paints`, `raster::tests::devicen_inks::an_operator_with_hundreds_of_operands_does_not_end_the_content` | @@ -26,6 +26,7 @@ Other resource categories retain their existing parent-chain lookup. | egui-wgpu | 0.36.2 | MIT OR Apache-2.0 | (1) `winit::surface_fit`: a window's surface is configured within the device's `max_texture_dimension_2d`, both sides shrunk by one factor that egui then draws at (`pixels_per_point × render_scale`), so the whole window is drawn into the surface (on DX12 it is stretched over the window and lines up with the pointer; wgpu's GL backend copies it unscaled into a corner); the longer side becomes exactly the limit; the depth and MSAA textures follow, and a recreated surface starts again from the window's own size. egui-wgpu configured the window's size as is, and `Surface::configure` panics beyond the limit: a window restored at another monitor's scale (opening an Outlook attachment on a mixed-DPI laptop asked an 8192-pixel device for 8600 × 3423, #577) or stretched across monitors closed PdfCraft, before its window appeared when it happened at start-up ([emilk/egui#8361](https://github.com/emilk/egui/issues/8361)). The published crate leaves out egui's licence files; `LICENSE-APACHE` and `LICENSE-MIT` are from the 0.36.2 tag; (2) `winit::catch_errors`: a new window's surface is configured inside wgpu error scopes (validation, out of memory, internal), and a failure is returned as `WgpuError::ConfigureSurface` (for the root window at start-up eframe returns it as `Error::Wgpu`, which PdfCraft retries with OpenGL); nothing is kept for the window. wgpu's default handler panicked instead, and eframe configures the root surface before the app is created, so a driver that can't configure one closed PdfCraft at launch (a 2015 Intel GPU through wgpu's GL backend timed out waiting for the GPU to go idle, `GpuWaitTimeout`, #519). Unchanged, so still a panic: an error in a later reconfigure (resize, a lost surface), a device lost during the first configure (wgpu reports it only to a callback), and a window shown at zero size (first configured on resize) | (1) `pdfcraft` `tests::a_window_larger_than_the_gpu_limit_gets_a_surface_within_it`, `tests::surface_fit_never_empties_or_overflows_a_surface`, and `tests::egui_wgpu_carries_the_surface_size_fit`, which keeps the patch in the build and in the paths that size a surface; (2) `pdfcraft` `tests::a_gpu_error_while_a_window_is_set_up_is_returned_not_a_panic` (a real device: an error inside `catch_errors` is returned, not a panic) and `tests::egui_wgpu_returns_a_surface_it_cannot_configure_as_an_error`, which keeps it around `add_surface`'s configure | | vello_common | 0.0.8 | Apache-2.0 OR MIT | (1) `clip::intersect` (the clip step every clipped path passes through) starts its row walk at the first row both paths have strips in, not the earlier of the two first rows. The walk visited every row from the top of the clip for each path (on the A1 sample's full-page canvas, about half its strip rows per stroke), and rows where one path has no strips produce no output, so the strips are unchanged (vello_common 0.1 starts at the later row too). Its cost grew with the page, and a full-page render of the A1 sample was about 30% faster; the output is byte-identical | (1) `clip::tests::intersect_walks_only_rows_both_paths_have_strips` counts the rows the walk visits (`cargo test --manifest-path vendor/vello_common/Cargo.toml`) and fails without the patch; the render crate's pixel tests run through the patched crate | | hayro-cmap | 0.1.0 | Apache-2.0 OR MIT | (1) malformed parts of a CMap (bad bfchar/bfrange entries, unresolvable `usecmap`, unparseable tail) are skipped instead of discarding the whole map, so search and redaction find text the edit layer can read (#3177); (2) a binary CMap's `usecmap` counts against the 16-level nesting limit as a text one does, where it passed its own depth and a self-referencing binary CMap recursed until the stack overflowed (from storytold/craft-libs#254) | (1) `hayro-cmap::tests::bad_bfchar_entry_is_skipped`, `unresolvable_usecmap_is_skipped`; (2) `tests::self_referencing_binary_usecmap_stops_at_the_nesting_limit` | +| hayro-postscript | 0.1.0 | Apache-2.0 OR MIT | (1) the token scanner's `object::read` skips `<<` and `>>` in a loop; it called itself once per delimiter, so a CMap stream holding a long run of `<` or `>` overflowed the stack and aborted the process (from storytold/craft-libs#263) | (1) `hayro-postscript::object::tests::long_open_dict_run_does_not_overflow`, `long_close_dict_run_does_not_overflow`, `dict_delimiters_are_skipped`, `nested_dict_delimiters_are_skipped` | Renderer startup errors: `egui-wgpu::RenderState::create` also wraps `Renderer::new` in `winit::catch_errors` when the winit feature is enabled. A rejected shader or render pipeline diff --git a/vendor/hayro-postscript/Cargo.lock b/vendor/hayro-postscript/Cargo.lock new file mode 100644 index 0000000000..b95d341526 --- /dev/null +++ b/vendor/hayro-postscript/Cargo.lock @@ -0,0 +1,7 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "hayro-postscript" +version = "0.1.0" diff --git a/vendor/hayro-postscript/Cargo.toml b/vendor/hayro-postscript/Cargo.toml new file mode 100644 index 0000000000..b1d53c3f3f --- /dev/null +++ b/vendor/hayro-postscript/Cargo.toml @@ -0,0 +1,70 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +edition = "2024" +name = "hayro-postscript" +version = "0.1.0" +authors = ["Laurenz Stampfl "] +build = false +autolib = false +autobins = false +autoexamples = false +autotests = false +autobenches = false +description = "A lightweight PostScript scanner." +readme = "README.md" +license = "Apache-2.0 OR MIT" +repository = "https://github.com/LaurenzV/hayro" +resolver = "2" + +[lib] +name = "hayro_postscript" +path = "src/lib.rs" + +[[example]] +name = "tokenize" +path = "examples/tokenize.rs" + +[lints.clippy] +collection_is_never_read = "warn" +dbg_macro = "warn" +debug_assert_with_mut_call = "warn" +default_trait_access = "warn" +doc_markdown = "warn" +fn_to_numeric_cast_any = "warn" +infinite_loop = "warn" +large_stack_arrays = "warn" +mismatching_type_param_order = "warn" +negative_feature_names = "warn" +redundant_feature_names = "warn" +same_functions_in_if_condition = "warn" +semicolon_if_nothing_returned = "warn" +todo = "warn" +too_many_arguments = "allow" +unseparated_literal_suffix = "warn" +use_self = "warn" +wildcard_dependencies = "warn" + +[lints.rust] +elided_lifetimes_in_paths = "warn" +keyword_idents_2024 = "forbid" +missing_docs = "warn" +non_ascii_idents = "forbid" +non_local_definitions = "forbid" +trivial_numeric_casts = "warn" +unnameable_types = "warn" +unreachable_pub = "warn" +unsafe_op_in_unsafe_fn = "forbid" +unused_import_braces = "warn" +unused_lifetimes = "warn" +unused_macro_rules = "warn" +unused_qualifications = "warn" diff --git a/vendor/hayro-postscript/Cargo.toml.orig b/vendor/hayro-postscript/Cargo.toml.orig new file mode 100644 index 0000000000..6ba1eed22f --- /dev/null +++ b/vendor/hayro-postscript/Cargo.toml.orig @@ -0,0 +1,11 @@ +[package] +name = "hayro-postscript" +version = "0.1.0" +description = "A lightweight PostScript scanner." +authors = { workspace = true } +edition = { workspace = true } +repository = { workspace = true } +license = { workspace = true } + +[lints] +workspace = true diff --git a/vendor/hayro-postscript/LICENSE-APACHE b/vendor/hayro-postscript/LICENSE-APACHE new file mode 100644 index 0000000000..4947287f7b --- /dev/null +++ b/vendor/hayro-postscript/LICENSE-APACHE @@ -0,0 +1,177 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS \ No newline at end of file diff --git a/vendor/hayro-postscript/LICENSE-MIT b/vendor/hayro-postscript/LICENSE-MIT new file mode 100644 index 0000000000..ae3742de4e --- /dev/null +++ b/vendor/hayro-postscript/LICENSE-MIT @@ -0,0 +1,7 @@ +Copyright (c) The Hayro Authors + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/vendor/hayro-postscript/README.md b/vendor/hayro-postscript/README.md new file mode 100644 index 0000000000..3c2282716b --- /dev/null +++ b/vendor/hayro-postscript/README.md @@ -0,0 +1,30 @@ +# hayro-postscript + +[![Crates.io](https://img.shields.io/crates/v/hayro-postscript.svg)](https://crates.io/crates/hayro-postscript) +[![Documentation](https://docs.rs/hayro-postscript/badge.svg)](https://docs.rs/hayro-postscript) + + + +A lightweight PostScript scanner. + +This crate provides a scanner for tokenizing PostScript programs into typed objects. +It currently only implements a very small subset of the PostScript language, +with the main goal of being enough to parse CMAP files, but the scope _might_ +be expanded upon in the future. + +The supported types include integers and real numbers, name objects, strings and arrays. +Unsupported is anything else, including dictionaries, procedures, etc. An error +will be returned in case any of these is encountered. + +### Safety +This crate forbids unsafe code via a crate-level attribute. + + + +## License +Licensed under either of + +- Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or ) +- MIT license ([LICENSE-MIT](LICENSE-MIT) or ) + +at your option. diff --git a/vendor/hayro-postscript/examples/tokenize.rs b/vendor/hayro-postscript/examples/tokenize.rs new file mode 100644 index 0000000000..c8cd84d038 --- /dev/null +++ b/vendor/hayro-postscript/examples/tokenize.rs @@ -0,0 +1,74 @@ +//! A small example that shows how to tokenize a PostScript program. + +#![allow(missing_docs)] + +use hayro_postscript::{Number, Object, Scanner}; +use std::env; +use std::fs; +use std::process; + +fn main() { + let path = match env::args().nth(1) { + Some(p) => p, + None => { + eprintln!("Usage: tokenize "); + process::exit(1); + } + }; + + let data = match fs::read(&path) { + Ok(d) => d, + Err(e) => { + eprintln!("Error reading {path}: {e}"); + process::exit(1); + } + }; + + let mut scanner = Scanner::new(&data); + + while !scanner.at_end() { + match scanner.parse_object() { + Ok(object) => { + print_object(&object); + println!(); + } + Err(e) => eprintln!("Error: {e}"), + } + } +} + +fn print_object(object: &Object<'_>) { + match object { + Object::Number(Number::Integer(n)) => print!("Integer({n})"), + Object::Number(Number::Real(n)) => print!("Real({n})"), + Object::Name(name) => { + let kind = if name.is_literal() { + "literal" + } else { + "executable" + }; + let text = name.as_str().unwrap_or(""); + print!("Name({text}, {kind})"); + } + Object::String(s) => { + let decoded = s.decode().unwrap_or_else(|_| Vec::new()); + print!("String({})", String::from_utf8_lossy(&decoded)); + } + Object::Array(arr) => { + print!("["); + let mut inner = arr.objects(); + let mut first = true; + while !inner.at_end() { + if !first { + print!(" "); + } + first = false; + match inner.parse_object() { + Ok(obj) => print_object(&obj), + Err(e) => print!("Error({e})"), + } + } + print!("]"); + } + } +} diff --git a/vendor/hayro-postscript/src/array.rs b/vendor/hayro-postscript/src/array.rs new file mode 100644 index 0000000000..b96b3601a5 --- /dev/null +++ b/vendor/hayro-postscript/src/array.rs @@ -0,0 +1,127 @@ +use crate::error::{Error, Result}; +use crate::object; +use crate::reader::Reader; +use crate::string; + +/// A PostScript array object. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Array<'a> { + data: &'a [u8], +} + +impl<'a> Array<'a> { + pub(crate) fn new(data: &'a [u8]) -> Self { + Self { data } + } + + /// Return a [`Scanner`](crate::Scanner) that iterates over the objects inside + /// this array. + pub fn objects(&self) -> crate::Scanner<'a> { + crate::Scanner::new(self.data) + } +} + +pub(crate) fn parse<'a>(r: &mut Reader<'a>) -> Result<&'a [u8]> { + r.forward_tag(b"[").ok_or(Error::SyntaxError)?; + + let start = r.offset(); + skip_array(r)?; + let end = r.offset() - 1; + + r.range(start..end).ok_or(Error::SyntaxError) +} + +fn skip_array(r: &mut Reader<'_>) -> Result<()> { + let mut depth = 1_u32; + + while depth > 0 { + match r.peek_byte().ok_or(Error::SyntaxError)? { + b'[' => { + r.forward(); + depth += 1; + } + b']' => { + r.forward(); + depth -= 1; + } + b'(' => { + let _ = string::parse_literal(r).ok_or(Error::SyntaxError)?; + } + b'<' => { + if r.peek_bytes(2) == Some(b"<~") { + let _ = string::parse_ascii85(r).ok_or(Error::SyntaxError)?; + } else if r.peek_bytes(2) == Some(b"<<") { + r.forward(); + r.forward(); + } else { + let _ = string::parse_hex(r).ok_or(Error::SyntaxError)?; + } + } + b'%' => object::skip_whitespace_and_comments(r), + _ => { + r.forward(); + } + } + } + + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn parse_array(input: &[u8]) -> Result<&[u8]> { + let mut r = Reader::new(input); + parse(&mut r) + } + + #[test] + fn empty() { + assert_eq!(parse_array(b"[]").unwrap(), b""); + } + + #[test] + fn simple() { + assert_eq!(parse_array(b"[1 2 3]").unwrap(), b"1 2 3"); + } + + #[test] + fn nested() { + assert_eq!(parse_array(b"[1 [2 3] 4]").unwrap(), b"1 [2 3] 4"); + } + + #[test] + fn with_string() { + // The ']' inside the string should not close the array. + assert_eq!(parse_array(b"[1 (str]) 2]").unwrap(), b"1 (str]) 2"); + } + + #[test] + fn with_hex_string() { + assert_eq!(parse_array(b"[<48> /name]").unwrap(), b"<48> /name"); + } + + #[test] + fn with_ascii85_string() { + assert_eq!(parse_array(b"[<~87cURDZ~> 1]").unwrap(), b"<~87cURDZ~> 1"); + } + + #[test] + fn with_comment() { + assert_eq!( + parse_array(b"[1 % comment with ]\n2]").unwrap(), + b"1 % comment with ]\n2" + ); + } + + #[test] + fn unterminated() { + assert_eq!(parse_array(b"[1 2"), Err(Error::SyntaxError)); + } + + #[test] + fn not_an_array() { + assert_eq!(parse_array(b"1 2]"), Err(Error::SyntaxError)); + } +} diff --git a/vendor/hayro-postscript/src/error.rs b/vendor/hayro-postscript/src/error.rs new file mode 100644 index 0000000000..3a2627a1a6 --- /dev/null +++ b/vendor/hayro-postscript/src/error.rs @@ -0,0 +1,30 @@ +//! Error types for the PostScript scanner. + +use core::fmt; + +/// A specialized [`Result`] type for PostScript scanner operations. +pub type Result = core::result::Result; + +/// An error encountered while scanning a PostScript token stream. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Error { + /// A syntax error in the input. + SyntaxError, + /// A numeric value exceeded implementation limits. + LimitCheck, + /// An unsupported PostScript type was encountered (like dictionaries or + /// procedures, which will be added in the future). + UnsupportedType, +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::SyntaxError => f.write_str("syntaxerror"), + Self::LimitCheck => f.write_str("limitcheck"), + Self::UnsupportedType => f.write_str("unsupported type"), + } + } +} + +impl core::error::Error for Error {} diff --git a/vendor/hayro-postscript/src/lib.rs b/vendor/hayro-postscript/src/lib.rs new file mode 100644 index 0000000000..e16d55562d --- /dev/null +++ b/vendor/hayro-postscript/src/lib.rs @@ -0,0 +1,179 @@ +/*! +A lightweight PostScript scanner. + +This crate provides a scanner for tokenizing PostScript programs into typed objects. +It currently only implements a very small subset of the PostScript language, +with the main goal of being enough to parse CMAP files, but the scope _might_ +be expanded upon in the future. + +The supported types include integers and real numbers, name objects, strings and arrays. +Unsupported is anything else, including dictionaries, procedures, etc. An error +will be returned in case any of these is encountered. + +## Safety +This crate forbids unsafe code via a crate-level attribute. +*/ + +#![no_std] +#![forbid(unsafe_code)] +#![allow(missing_docs)] + +extern crate alloc; + +mod array; +mod error; +mod name; +mod number; +mod object; +mod reader; +mod string; + +pub use array::Array; +pub use error::{Error, Result}; +pub use name::Name; +pub use number::Number; +pub use object::Object; +pub use string::String; + +use reader::Reader; + +/// A PostScript scanner that parses [`Object`]s from a byte stream. +pub struct Scanner<'a> { + reader: Reader<'a>, +} + +impl<'a> Scanner<'a> { + /// Create a new scanner over the given bytes of a PostScript program. + pub fn new(data: &'a [u8]) -> Self { + Self { + reader: Reader::new(data), + } + } + + /// Returns `true` if there are no more objects to parse. + pub fn at_end(&mut self) -> bool { + object::at_end(&mut self.reader) + } + + /// Parse the next object. + pub fn parse_object(&mut self) -> Result> { + object::read(&mut self.reader) + } + + /// Parse the next object as a [`Number`]. + pub fn parse_number(&mut self) -> Result { + match self.parse_object()? { + Object::Number(n) => Ok(n), + _ => Err(Error::SyntaxError), + } + } + + /// Parse the next object as a [`Name`]. + pub fn parse_name(&mut self) -> Result> { + match self.parse_object()? { + Object::Name(n) => Ok(n), + _ => Err(Error::SyntaxError), + } + } + + /// Parse the next object as a [`String`]. + pub fn parse_string(&mut self) -> Result> { + match self.parse_object()? { + Object::String(s) => Ok(s), + _ => Err(Error::SyntaxError), + } + } + + /// Parse the next object as an [`Array`]. + pub fn parse_array(&mut self) -> Result> { + match self.parse_object()? { + Object::Array(a) => Ok(a), + _ => Err(Error::SyntaxError), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn cmap_snippet() { + let input = br#"/CIDInit /ProcSet findresource begin +12 dict begin +begincmap +/CMapName /Test-H def +1 begincodespacerange +<00> +endcodespacerange +2 beginbfchar +<03> <0041> +<04> <0042> +endbfchar +endcmap"#; + + let mut s = Scanner::new(input); + + assert_eq!(s.parse_name().unwrap(), Name::new(b"CIDInit", true)); + assert_eq!(s.parse_name().unwrap(), Name::new(b"ProcSet", true)); + assert_eq!(s.parse_name().unwrap(), Name::new(b"findresource", false)); + assert_eq!(s.parse_name().unwrap(), Name::new(b"begin", false)); + assert_eq!(s.parse_number().unwrap(), Number::Integer(12)); + assert_eq!(s.parse_name().unwrap(), Name::new(b"dict", false)); + assert_eq!(s.parse_name().unwrap(), Name::new(b"begin", false)); + assert_eq!(s.parse_name().unwrap(), Name::new(b"begincmap", false)); + assert_eq!(s.parse_name().unwrap(), Name::new(b"CMapName", true)); + assert_eq!(s.parse_name().unwrap(), Name::new(b"Test-H", true)); + assert_eq!(s.parse_name().unwrap(), Name::new(b"def", false)); + assert_eq!(s.parse_number().unwrap(), Number::Integer(1)); + assert_eq!( + s.parse_name().unwrap(), + Name::new(b"begincodespacerange", false) + ); + assert_eq!(s.parse_string().unwrap(), String::from_hex(b"00")); + assert_eq!(s.parse_string().unwrap(), String::from_hex(b"FF")); + assert_eq!( + s.parse_name().unwrap(), + Name::new(b"endcodespacerange", false) + ); + assert_eq!(s.parse_number().unwrap(), Number::Integer(2)); + assert_eq!(s.parse_name().unwrap(), Name::new(b"beginbfchar", false)); + assert_eq!(s.parse_string().unwrap(), String::from_hex(b"03")); + assert_eq!(s.parse_string().unwrap(), String::from_hex(b"0041")); + assert_eq!(s.parse_string().unwrap(), String::from_hex(b"04")); + assert_eq!(s.parse_string().unwrap(), String::from_hex(b"0042")); + assert_eq!(s.parse_name().unwrap(), Name::new(b"endbfchar", false)); + assert_eq!(s.parse_name().unwrap(), Name::new(b"endcmap", false)); + assert!(s.at_end()); + } + + #[test] + fn array_round_trip() { + let input = b"[123 /abc (xyz)]"; + let mut scanner = Scanner::new(input); + let arr = scanner.parse_array().unwrap(); + assert!(scanner.at_end()); + + let mut inner = arr.objects(); + assert_eq!(inner.parse_number().unwrap(), Number::Integer(123)); + assert_eq!(inner.parse_name().unwrap(), Name::new(b"abc", true)); + assert_eq!(inner.parse_string().unwrap(), String::from_literal(b"xyz")); + assert!(inner.at_end()); + } + + #[test] + fn comments_skipped() { + let input = b"% comment\n42 % another\n/Name"; + let mut scanner = Scanner::new(input); + + assert_eq!(scanner.parse_number().unwrap(), Number::Integer(42)); + assert_eq!(scanner.parse_name().unwrap(), Name::new(b"Name", true)); + assert!(scanner.at_end()); + } + + #[test] + fn wrong_type_is_error() { + let mut scanner = Scanner::new(b"42 "); + assert!(scanner.parse_name().is_err()); + } +} diff --git a/vendor/hayro-postscript/src/name.rs b/vendor/hayro-postscript/src/name.rs new file mode 100644 index 0000000000..ab78e7ba67 --- /dev/null +++ b/vendor/hayro-postscript/src/name.rs @@ -0,0 +1,191 @@ +use alloc::vec::Vec; + +use crate::error::{Error, Result}; +use crate::reader::{Reader, is_regular}; +use crate::string::ascii_hex::decode_hex_digit; + +/// A PostScript name object. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Name<'a> { + data: &'a [u8], + literal: bool, +} + +impl<'a> Name<'a> { + pub(crate) fn new(data: &'a [u8], literal: bool) -> Self { + Self { data, literal } + } + + /// Returns `true` if this is a literal name. + pub fn is_literal(&self) -> bool { + self.literal + } + + /// Returns the name as a string if it is valid UTF-8, or + /// `None` if it contains non-ASCII bytes. + pub fn as_str(&self) -> Option<&'a str> { + core::str::from_utf8(self.data).ok() + } + + /// Decode the name into `out`, replacing any previous contents. + pub fn decode_into(&self, out: &mut Vec) -> Result<()> { + out.clear(); + + // Fast path: no escape sequences. + if !self.data.contains(&b'#') { + out.extend_from_slice(self.data); + return Ok(()); + } + + // Slow path: Process escape sequences. + let mut inner = Reader::new(self.data); + + while let Some(b) = inner.read_byte() { + if b == b'#' { + let hex = inner.read_bytes(2).ok_or(Error::SyntaxError)?; + let hi = decode_hex_digit(hex[0]).ok_or(Error::SyntaxError)?; + let lo = decode_hex_digit(hex[1]).ok_or(Error::SyntaxError)?; + out.push(hi << 4 | lo); + } else { + out.push(b); + } + } + + Ok(()) + } + + /// Decode the name. + pub fn decode(&self) -> Result> { + let mut out = Vec::new(); + self.decode_into(&mut out)?; + Ok(out) + } +} + +pub(crate) fn parse_literal<'a>(r: &mut Reader<'a>) -> Option<&'a [u8]> { + r.forward_tag(b"/")?; + let start = r.offset(); + while r.eat(is_regular).is_some() {} + r.range(start..r.offset()) +} + +pub(crate) fn parse_executable<'a>(r: &mut Reader<'a>) -> Option<&'a [u8]> { + let start = r.offset(); + r.forward_while(is_regular); + if r.offset() == start { + return None; + } + r.range(start..r.offset()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn read_literal(input: &[u8]) -> Option> { + let mut r = Reader::new(input); + parse_literal(&mut r).map(|d| Name::new(d, true)) + } + + fn read_executable(input: &[u8]) -> Option> { + let mut r = Reader::new(input); + parse_executable(&mut r).map(|d| Name::new(d, false)) + } + + #[test] + fn literal_simple() { + let n = read_literal(b"/Name1").unwrap(); + assert_eq!(n.as_str().unwrap(), "Name1"); + assert!(n.is_literal()); + } + + #[test] + fn literal_empty_name() { + let n = read_literal(b"/").unwrap(); + assert_eq!(n.as_str().unwrap(), ""); + assert!(n.is_literal()); + } + + #[test] + fn literal_with_hex_escape() { + let n = read_literal(b"/lime#20Green").unwrap(); + assert_eq!(n.as_str().unwrap(), "lime#20Green"); + assert_eq!(n.decode().unwrap(), b"lime Green"); + } + + #[test] + fn literal_multiple_hex_escapes() { + let n = read_literal(b"/paired#28#29parentheses").unwrap(); + assert_eq!(n.decode().unwrap(), b"paired()parentheses"); + } + + #[test] + fn literal_special_chars() { + let n = read_literal(b"/A;Name_With-Various***Characters?").unwrap(); + assert_eq!(n.as_str().unwrap(), "A;Name_With-Various***Characters?"); + } + + #[test] + fn literal_stops_at_delimiter() { + let mut r = Reader::new(b"/Name(rest"); + let data = parse_literal(&mut r).unwrap(); + assert_eq!(data, b"Name"); + assert_eq!(r.peek_byte(), Some(b'(')); + } + + #[test] + fn literal_stops_at_whitespace() { + let mut r = Reader::new(b"/Name rest"); + let data = parse_literal(&mut r).unwrap(); + assert_eq!(data, b"Name"); + assert_eq!(r.peek_byte(), Some(b' ')); + } + + #[test] + fn literal_not_a_name() { + assert!(read_literal(b"Name").is_none()); + } + + #[test] + fn executable_simple() { + let n = read_executable(b"beginbfchar ").unwrap(); + assert_eq!(n.as_str().unwrap(), "beginbfchar"); + assert!(!n.is_literal()); + } + + #[test] + fn executable_stops_at_delimiter() { + let mut r = Reader::new(b"def/name"); + let data = parse_executable(&mut r).unwrap(); + assert_eq!(data, b"def"); + assert_eq!(r.peek_byte(), Some(b'/')); + } + + #[test] + fn executable_at_eof() { + let n = read_executable(b"endcmap").unwrap(); + assert_eq!(n.as_str().unwrap(), "endcmap"); + } + + #[test] + fn executable_empty() { + assert!(read_executable(b"").is_none()); + } + + #[test] + fn executable_starts_at_delimiter() { + assert!(read_executable(b"(foo)").is_none()); + } + + #[test] + fn decode_no_escapes() { + let n = Name::new(b"simple", true); + assert_eq!(n.decode().unwrap(), b"simple"); + } + + #[test] + fn decode_with_escapes() { + let n = Name::new(b"lime#20Green", true); + assert_eq!(n.decode().unwrap(), b"lime Green"); + } +} diff --git a/vendor/hayro-postscript/src/number.rs b/vendor/hayro-postscript/src/number.rs new file mode 100644 index 0000000000..5c6d3ba10f --- /dev/null +++ b/vendor/hayro-postscript/src/number.rs @@ -0,0 +1,177 @@ +use crate::error::{Error, Result}; +use crate::reader::{Reader, is_delimiter, is_whitespace}; + +/// A PostScript number object (integer or real). +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum Number { + Integer(i32), + Real(f32), +} + +impl Number { + /// Return the value as an `i32`. Reals are truncated. + pub fn as_i32(self) -> i32 { + match self { + Self::Integer(v) => v, + Self::Real(v) => v as i32, + } + } + + /// Return the value as an `f32`. + pub fn as_f32(self) -> f32 { + match self { + Self::Integer(v) => v as f32, + Self::Real(v) => v, + } + } + + /// Return the value as an `f64`. + pub fn as_f64(self) -> f64 { + match self { + Self::Integer(v) => v as f64, + Self::Real(v) => v as f64, + } + } +} + +fn is_terminated(r: &Reader<'_>) -> bool { + match r.peek_byte() { + None => true, + Some(b) => is_whitespace(b) || is_delimiter(b), + } +} + +pub(crate) fn read(r: &mut Reader<'_>) -> Result { + let saved = r.offset(); + + // Optional sign. + let first = r.peek_byte().ok_or(Error::SyntaxError)?; + let has_sign = first == b'+' || first == b'-'; + + if has_sign { + r.forward(); + } + + // Consume leading digits. + let digit_start = r.offset(); + r.forward_while(|b| b.is_ascii_digit()); + let has_digits = r.offset() > digit_start; + + // Check if number is a radix number. + if !has_sign && has_digits && r.peek_byte() == Some(b'#') { + let base_bytes = r.range(digit_start..r.offset()).ok_or(Error::SyntaxError)?; + let base_str = core::str::from_utf8(base_bytes).map_err(|_| Error::SyntaxError)?; + let base = base_str.parse::().map_err(|_| Error::SyntaxError)?; + + if !(2..=36).contains(&base) { + return Err(Error::SyntaxError); + } + + // Skip `#`. + r.forward(); + + let num_start = r.offset(); + r.forward_while(|b| b.is_ascii_alphanumeric()); + + if r.offset() == num_start || !is_terminated(r) { + return Err(Error::SyntaxError); + } + + let num_bytes = r.range(num_start..r.offset()).ok_or(Error::SyntaxError)?; + let num_str = core::str::from_utf8(num_bytes).map_err(|_| Error::SyntaxError)?; + let value = i32::from_str_radix(num_str, base).map_err(|_| Error::SyntaxError)?; + + return Ok(Number::Integer(value)); + } + + // Check for real number indicators: `.` or `e`/`E`. + let has_dot = r.peek_byte() == Some(b'.'); + + if has_dot { + r.forward(); // skip '.' + r.forward_while(|b| b.is_ascii_digit()); + } + + // At this point we need at least some digits (before or after the dot). + if !has_digits && !has_dot { + return Err(Error::SyntaxError); + } + + let has_exponent = matches!(r.peek_byte(), Some(b'e' | b'E')); + if has_exponent { + r.forward(); + + // Optional exponent sign. + if matches!(r.peek_byte(), Some(b'+' | b'-')) { + r.forward(); + } + + r.forward_while(|b| b.is_ascii_digit()); + } + + if !is_terminated(r) { + return Err(Error::SyntaxError); + } + + let token = r.range(saved..r.offset()).ok_or(Error::SyntaxError)?; + let str = core::str::from_utf8(token).map_err(|_| Error::SyntaxError)?; + + if has_dot || has_exponent { + let value = str.parse::().map_err(|_| Error::SyntaxError)?; + + Ok(Number::Real(value)) + } else { + if !has_digits { + return Err(Error::SyntaxError); + } + + let value = str.parse::().map_err(|_| Error::SyntaxError)?; + + Ok(Number::Integer(value)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn read_num(input: &[u8]) -> Result { + let mut r = Reader::new(input); + read(&mut r) + } + + #[test] + fn signed_integers() { + assert_eq!(read_num(b"123 ").unwrap(), Number::Integer(123)); + assert_eq!(read_num(b"-98 ").unwrap(), Number::Integer(-98)); + assert_eq!(read_num(b"43445 ").unwrap(), Number::Integer(43445)); + assert_eq!(read_num(b"0 ").unwrap(), Number::Integer(0)); + assert_eq!(read_num(b"+17 ").unwrap(), Number::Integer(17)); + } + + #[test] + fn real_numbers() { + assert_eq!(read_num(b"-.002 ").unwrap(), Number::Real(-0.002)); + assert_eq!(read_num(b"34.5 ").unwrap(), Number::Real(34.5)); + assert_eq!(read_num(b"-3.62 ").unwrap(), Number::Real(-3.62)); + assert_eq!(read_num(b"123.6e10 ").unwrap(), Number::Real(123.6e10)); + assert_eq!(read_num(b"1.0E-5 ").unwrap(), Number::Real(1.0E-5)); + assert_eq!(read_num(b"1E6 ").unwrap(), Number::Real(1E6)); + assert_eq!(read_num(b"-1. ").unwrap(), Number::Real(-1.0)); + assert_eq!(read_num(b"0.0 ").unwrap(), Number::Real(0.0)); + } + + #[test] + fn radix_numbers() { + assert_eq!(read_num(b"8#1777 ").unwrap(), Number::Integer(0o1777)); + assert_eq!(read_num(b"16#FFFE ").unwrap(), Number::Integer(0xFFFE)); + assert_eq!(read_num(b"2#1000 ").unwrap(), Number::Integer(0b1000)); + } + + #[test] + fn invalid() { + assert!(read_num(b"abc").is_err()); + assert!(read_num(b"+abc").is_err()); + assert!(read_num(b"1a").is_err()); + } +} diff --git a/vendor/hayro-postscript/src/object.rs b/vendor/hayro-postscript/src/object.rs new file mode 100644 index 0000000000..7c20075860 --- /dev/null +++ b/vendor/hayro-postscript/src/object.rs @@ -0,0 +1,226 @@ +use crate::array::{self, Array}; +use crate::error::{Error, Result}; +use crate::name::{self, Name}; +use crate::number::{self, Number}; +use crate::reader::Reader; +use crate::string::{self, String}; + +/// A PostScript object. +#[derive(Debug, Clone, PartialEq)] +pub enum Object<'a> { + /// A number object. + Number(Number), + /// A name object. + Name(Name<'a>), + /// A string object. + String(String<'a>), + /// An array object. + Array(Array<'a>), +} + +pub(crate) fn read<'a>(r: &mut Reader<'a>) -> Result> { + // PdfCraft patch: `<<` and `>>` are skipped by looping instead of + // recursing once per delimiter, so a long run cannot overflow the stack. + loop { + skip_whitespace_and_comments(r); + + let b = r.peek_byte().ok_or(Error::SyntaxError)?; + + return match b { + b'(' => string::parse_literal(r) + .map(|s| Object::String(String::from_literal(s))) + .ok_or(Error::SyntaxError), + b'<' => { + if r.peek_bytes(2) == Some(b"<~") { + string::parse_ascii85(r) + .map(|s| Object::String(String::from_ascii85(s))) + .ok_or(Error::SyntaxError) + } else if r.peek_bytes(2) == Some(b"<<") { + // TODO: Proper dict support. For now, skip `<<` and return + // the next object so callers see the inner tokens. + r.forward(); + r.forward(); + continue; + } else { + string::parse_hex(r) + .map(|s| Object::String(String::from_hex(s))) + .ok_or(Error::SyntaxError) + } + } + b'/' => name::parse_literal(r) + .map(|s| Object::Name(Name::new(s, true))) + .ok_or(Error::SyntaxError), + b'[' => array::parse(r).map(|d| Object::Array(Array::new(d))), + b'>' => { + if r.peek_bytes(2) == Some(b">>") { + // TODO: Proper dict support. Skip `>>` closing delimiter. + r.forward(); + r.forward(); + continue; + } else { + Err(Error::SyntaxError) + } + } + b'{' => { + r.forward(); + Err(Error::UnsupportedType) + } + b'.' | b'+' | b'-' | b'0'..=b'9' => number::read(r).map(Object::Number), + _ => name::parse_executable(r) + .map(|s| Object::Name(Name::new(s, false))) + .ok_or(Error::SyntaxError), + }; + } +} + +pub(crate) fn at_end(r: &mut Reader<'_>) -> bool { + skip_whitespace_and_comments(r); + r.peek_byte().is_none() +} + +pub(crate) fn skip_whitespace_and_comments(r: &mut Reader<'_>) { + loop { + match r.peek_byte() { + Some(b) if crate::reader::is_whitespace(b) => { + r.forward(); + } + Some(b'%') => { + r.forward(); + r.forward_while(|b| !crate::reader::is_eol(b)); + } + _ => return, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn read_one(input: &[u8]) -> Result> { + let mut r = Reader::new(input); + read(&mut r) + } + + fn read_ok(input: &[u8]) -> Object<'_> { + read_one(input).unwrap() + } + + fn read_err(input: &[u8]) -> Error { + read_one(input).unwrap_err() + } + + #[test] + fn integer() { + assert_eq!(read_ok(b"42 "), Object::Number(Number::Integer(42))); + } + + #[test] + fn negative_integer() { + assert_eq!(read_ok(b"-7 "), Object::Number(Number::Integer(-7))); + } + + #[test] + fn literal_name() { + assert_eq!( + read_ok(b"/CMapName "), + Object::Name(Name::new(b"CMapName", true)) + ); + } + + #[test] + fn executable_name() { + let obj = read_ok(b"beginbfchar "); + assert_eq!(obj, Object::Name(Name::new(b"beginbfchar", false))); + } + + #[test] + fn literal_string() { + assert_eq!( + read_ok(b"(Hello)"), + Object::String(String::from_literal(b"Hello")) + ); + } + + #[test] + fn hex_string() { + assert_eq!( + read_ok(b"<48656C6C6F>"), + Object::String(String::from_hex(b"48656C6C6F")) + ); + } + + #[test] + fn ascii85_string() { + assert_eq!( + read_ok(b"<~87cURDZ~>"), + Object::String(String::from_ascii85(b"87cURDZ")) + ); + } + + #[test] + fn array_simple() { + let obj = read_ok(b"[1 2 3]"); + assert_eq!(obj, Object::Array(Array::new(b"1 2 3"))); + } + + #[test] + fn stray_close_bracket() { + assert_eq!(read_err(b"]"), Error::SyntaxError); + } + + #[test] + fn stray_gt() { + assert_eq!(read_err(b">x"), Error::SyntaxError); + } + + #[test] + fn skips_whitespace() { + assert_eq!(read_ok(b" \t\n 42 "), Object::Number(Number::Integer(42))); + } + + #[test] + fn skips_comments() { + assert_eq!( + read_ok(b"% this is a comment\n42 "), + Object::Number(Number::Integer(42)) + ); + } + + #[test] + fn eof() { + assert!(read_one(b"").is_err()); + assert!(read_one(b" ").is_err()); + assert!(read_one(b"% comment only\n").is_err()); + } + + // PdfCraft patch: `<<` and `>>` runs are skipped without recursion. + #[test] + fn long_open_dict_run_does_not_overflow() { + let input = alloc::vec![b'<'; 1_000_000]; + assert_eq!(read_err(&input), Error::SyntaxError); + } + + #[test] + fn long_close_dict_run_does_not_overflow() { + let input = b">>".repeat(500_000); + assert_eq!(read_err(&input), Error::SyntaxError); + } + + #[test] + fn dict_delimiters_are_skipped() { + let mut r = Reader::new(b"<< /A 1 >>"); + assert_eq!(read(&mut r), Ok(Object::Name(Name::new(b"A", true)))); + assert_eq!(read(&mut r), Ok(Object::Number(Number::Integer(1)))); + assert_eq!(read(&mut r), Err(Error::SyntaxError)); + } + + #[test] + fn nested_dict_delimiters_are_skipped() { + let mut r = Reader::new(b"<<<< /X >>>> 7 <<\n% c\n<< >> 8"); + assert_eq!(read(&mut r), Ok(Object::Name(Name::new(b"X", true)))); + assert_eq!(read(&mut r), Ok(Object::Number(Number::Integer(7)))); + assert_eq!(read(&mut r), Ok(Object::Number(Number::Integer(8)))); + assert!(at_end(&mut r)); + } +} diff --git a/vendor/hayro-postscript/src/reader.rs b/vendor/hayro-postscript/src/reader.rs new file mode 100644 index 0000000000..f8a4967462 --- /dev/null +++ b/vendor/hayro-postscript/src/reader.rs @@ -0,0 +1,136 @@ +use core::ops::Range; + +#[derive(Clone, Debug)] +pub(crate) struct Reader<'a> { + pub(crate) data: &'a [u8], + pub(crate) offset: usize, +} + +impl<'a> Reader<'a> { + #[inline] + pub(crate) fn new(data: &'a [u8]) -> Self { + Self { data, offset: 0 } + } + + #[inline] + pub(crate) fn jump(&mut self, offset: usize) { + self.offset = offset; + } + + #[inline] + pub(crate) fn range(&self, range: Range) -> Option<&'a [u8]> { + self.data.get(range) + } + + #[inline] + pub(crate) fn offset(&self) -> usize { + self.offset + } + + #[inline] + pub(crate) fn read_bytes(&mut self, len: usize) -> Option<&'a [u8]> { + let v = self.peek_bytes(len)?; + self.offset += len; + Some(v) + } + + #[inline] + pub(crate) fn read_byte(&mut self) -> Option { + let v = self.peek_byte()?; + self.offset += 1; + Some(v) + } + + #[inline] + pub(crate) fn peek_bytes(&self, len: usize) -> Option<&'a [u8]> { + self.data.get(self.offset..self.offset + len) + } + + #[inline] + pub(crate) fn peek_byte(&self) -> Option { + self.data.get(self.offset).copied() + } + + #[inline] + pub(crate) fn eat(&mut self, f: impl Fn(u8) -> bool) -> Option { + let val = self.peek_byte()?; + if f(val) { + self.forward(); + Some(val) + } else { + None + } + } + + #[inline] + pub(crate) fn forward(&mut self) { + self.offset += 1; + } + + #[inline] + pub(crate) fn forward_while(&mut self, f: impl Fn(u8) -> bool) { + while let Some(b) = self.peek_byte() { + if f(b) { + self.forward(); + } else { + break; + } + } + } + + #[inline] + pub(crate) fn forward_tag(&mut self, tag: &[u8]) -> Option<()> { + self.peek_tag(tag)?; + self.offset += tag.len(); + Some(()) + } + + #[inline] + pub(crate) fn peek_tag(&self, tag: &[u8]) -> Option<()> { + let mut cloned = self.clone(); + + for b in tag.iter().copied() { + if cloned.peek_byte() == Some(b) { + cloned.forward(); + } else { + return None; + } + } + + Some(()) + } + + #[inline] + pub(crate) fn skip_eol(&mut self) { + while let Some(b) = self.peek_byte() { + if is_eol(b) { + self.forward(); + } else { + return; + } + } + } +} + +#[inline(always)] +pub(crate) fn is_whitespace(b: u8) -> bool { + matches!(b, 0x00 | 0x09 | 0x0a | 0x0c | 0x0d | 0x20) +} + +#[inline(always)] +pub(crate) fn is_delimiter(b: u8) -> bool { + matches!( + b, + b'(' | b')' | b'<' | b'>' | b'[' | b']' | b'{' | b'}' | b'/' | b'%' + ) +} + +#[inline(always)] +pub(crate) fn is_regular(b: u8) -> bool { + !is_whitespace(b) && !is_delimiter(b) +} + +#[inline(always)] +pub(crate) fn is_eol(b: u8) -> bool { + matches!(b, 0x0a | 0x0d) +} diff --git a/vendor/hayro-postscript/src/string.rs b/vendor/hayro-postscript/src/string.rs new file mode 100644 index 0000000000..ed39d57c73 --- /dev/null +++ b/vendor/hayro-postscript/src/string.rs @@ -0,0 +1,288 @@ +mod ascii_85; +pub(crate) mod ascii_hex; +mod literal; + +use alloc::vec::Vec; + +use crate::error::{Error, Result}; +use crate::reader::Reader; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum StringInner<'a> { + Literal(&'a [u8]), + Hex(&'a [u8]), + Ascii85(&'a [u8]), +} + +/// A PostScript string object. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct String<'a> { + inner: StringInner<'a>, +} + +impl<'a> String<'a> { + pub(crate) const fn from_literal(data: &'a [u8]) -> Self { + Self { + inner: StringInner::Literal(data), + } + } + + pub(crate) const fn from_hex(data: &'a [u8]) -> Self { + Self { + inner: StringInner::Hex(data), + } + } + + pub(crate) const fn from_ascii85(data: &'a [u8]) -> Self { + Self { + inner: StringInner::Ascii85(data), + } + } + + /// Decode the string content into `out`, replacing any previous contents. + pub fn decode_into(&self, out: &mut Vec) -> Result<()> { + out.clear(); + match self.inner { + StringInner::Literal(data) => literal::decode_into(data, out), + StringInner::Hex(data) => ascii_hex::decode_into(data, out), + StringInner::Ascii85(data) => ascii_85::decode_into(data, out), + } + .ok_or(Error::SyntaxError) + } + + /// Decode the string content. + pub fn decode(&self) -> Result> { + let mut out = Vec::new(); + self.decode_into(&mut out)?; + Ok(out) + } +} + +pub(crate) fn parse_literal<'a>(r: &mut Reader<'a>) -> Option<&'a [u8]> { + let start = r.offset(); + skip_literal(r)?; + let end = r.offset(); + // Exclude outer parentheses. + r.range(start + 1..end - 1) +} + +pub(crate) fn parse_hex<'a>(r: &mut Reader<'a>) -> Option<&'a [u8]> { + r.forward_tag(b"<")?; + let start = r.offset(); + while let Some(b) = r.read_byte() { + if b == b'>' { + return r.range(start..r.offset() - 1); + } + } + None +} + +pub(crate) fn parse_ascii85<'a>(r: &mut Reader<'a>) -> Option<&'a [u8]> { + r.forward_tag(b"<~")?; + let start = r.offset(); + loop { + let b = r.read_byte()?; + if b == b'~' { + let end = r.offset() - 1; + r.forward_tag(b">")?; + return r.range(start..end); + } + } +} + +fn skip_literal(r: &mut Reader<'_>) -> Option<()> { + r.forward_tag(b"(")?; + let mut depth = 1_u32; + + while depth > 0 { + let byte = r.read_byte()?; + match byte { + b'\\' => { + let _ = r.read_byte()?; + } + b'(' => depth += 1, + b')' => depth -= 1, + _ => {} + } + } + + Some(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn decode_literal(input: &[u8]) -> Result> { + let mut r = Reader::new(input); + let data = parse_literal(&mut r).ok_or(Error::SyntaxError)?; + String::from_literal(data).decode() + } + + #[test] + fn literal_empty() { + assert_eq!(decode_literal(b"()").unwrap(), b""); + } + + #[test] + fn literal_simple() { + assert_eq!(decode_literal(b"(Hello)").unwrap(), b"Hello"); + } + + #[test] + fn literal_nested_parens() { + assert_eq!( + decode_literal(b"(Hi (()) there)").unwrap(), + b"Hi (()) there" + ); + } + + #[test] + fn literal_escape_n() { + assert_eq!(decode_literal(b"(a\\nb)").unwrap(), b"a\nb"); + } + + #[test] + fn literal_escape_r() { + assert_eq!(decode_literal(b"(a\\rb)").unwrap(), b"a\rb"); + } + + #[test] + fn literal_escape_t() { + assert_eq!(decode_literal(b"(a\\tb)").unwrap(), b"a\tb"); + } + + #[test] + fn literal_escape_b() { + assert_eq!(decode_literal(b"(a\\bb)").unwrap(), &[b'a', 0x08, b'b']); + } + + #[test] + fn literal_escape_f() { + assert_eq!(decode_literal(b"(a\\fb)").unwrap(), &[b'a', 0x0C, b'b']); + } + + #[test] + fn literal_escape_backslash() { + assert_eq!(decode_literal(b"(a\\\\b)").unwrap(), b"a\\b"); + } + + #[test] + fn literal_escape_parens() { + assert_eq!(decode_literal(b"(Hi \\()").unwrap(), b"Hi ("); + } + + #[test] + fn literal_octal_three_digits() { + assert_eq!(decode_literal(b"(\\053)").unwrap(), b"+"); + } + + #[test] + fn literal_octal_two_digits() { + assert_eq!(decode_literal(b"(\\36)").unwrap(), b"\x1e"); + } + + #[test] + fn literal_octal_one_digit() { + assert_eq!(decode_literal(b"(\\3)").unwrap(), b"\x03"); + } + + #[test] + fn literal_line_continuation_lf() { + assert_eq!(decode_literal(b"(Hi \\\nthere)").unwrap(), b"Hi there"); + } + + #[test] + fn literal_line_continuation_cr() { + assert_eq!(decode_literal(b"(Hi \\\rthere)").unwrap(), b"Hi there"); + } + + #[test] + fn literal_line_continuation_crlf() { + assert_eq!(decode_literal(b"(Hi \\\r\nthere)").unwrap(), b"Hi there"); + } + + #[test] + fn literal_bare_eol_lf() { + assert_eq!(decode_literal(b"(a\nb)").unwrap(), b"a\nb"); + } + + #[test] + fn literal_bare_eol_cr() { + assert_eq!(decode_literal(b"(a\rb)").unwrap(), b"a\nb"); + } + + #[test] + fn literal_bare_eol_crlf() { + assert_eq!(decode_literal(b"(a\r\nb)").unwrap(), b"a\nb"); + } + + fn decode_hex(input: &[u8]) -> Result> { + let mut r = Reader::new(input); + let data = parse_hex(&mut r).ok_or(Error::SyntaxError)?; + String::from_hex(data).decode() + } + + #[test] + fn hex_simple() { + assert_eq!(decode_hex(b"<48656C6C6F>").unwrap(), b"Hello"); + } + + #[test] + fn hex_with_whitespace() { + assert_eq!(decode_hex(b"<48 65 6C 6C 6F>").unwrap(), b"Hello"); + } + + #[test] + fn hex_odd_nibble() { + assert_eq!(decode_hex(b"").unwrap(), &[0xAB, 0xC0]); + } + + #[test] + fn hex_empty() { + assert_eq!(decode_hex(b"<>").unwrap(), b""); + } + + #[test] + fn hex_lowercase() { + assert_eq!(decode_hex(b"").unwrap(), &[0xAB, 0xCD]); + } + + #[test] + fn hex_mixed_case() { + assert_eq!(decode_hex(b"").unwrap(), &[0xAB, 0x3E]); + } + + fn decode_a85(input: &[u8]) -> Result> { + let mut r = Reader::new(input); + let data = parse_ascii85(&mut r).ok_or(Error::SyntaxError)?; + String::from_ascii85(data).decode() + } + + #[test] + fn ascii85_simple() { + // "Hello" in ASCII85 is "87cURDZ" + assert_eq!(decode_a85(b"<~87cURDZ~>").unwrap(), b"Hello"); + } + + #[test] + fn ascii85_empty() { + assert_eq!(decode_a85(b"<~~>").unwrap(), b""); + } + + #[test] + fn ascii85_z_shorthand() { + assert_eq!(decode_a85(b"<~z~>").unwrap(), &[0, 0, 0, 0]); + } + + #[test] + fn ascii85_partial_group() { + let result = decode_a85(b"<~87~>").unwrap(); + assert_eq!(result.len(), 1); + } + + #[test] + fn ascii85_with_whitespace() { + assert_eq!(decode_a85(b"<~87cU RDZ~>").unwrap(), b"Hello"); + } +} diff --git a/vendor/hayro-postscript/src/string/ascii_85.rs b/vendor/hayro-postscript/src/string/ascii_85.rs new file mode 100644 index 0000000000..93f7f50274 --- /dev/null +++ b/vendor/hayro-postscript/src/string/ascii_85.rs @@ -0,0 +1,90 @@ +// Keep in sync with `hayro-syntax/src/filter/ascii_85.rs`. + +use crate::reader::{Reader, is_whitespace}; +use alloc::vec::Vec; + +pub(crate) fn decode_into(data: &[u8], out: &mut Vec) -> Option<()> { + const POW_85: [u32; 5] = [52200625, 614125, 7225, 85, 1]; + + let mut reader = Reader::new(data); + + let mut read_byte = || -> Option { + loop { + let b = reader.read_byte()?; + + // White space characters should be ignored. + if !is_whitespace(b) { + return Some(b); + } + } + }; + + let flush_group = |group: &mut Vec, decoded: &mut Vec| -> Option<()> { + let (digits, output_len): ([u32; 5], usize) = match group.len() { + 0 => return Some(()), + 1 => return None, // A single character is not valid. + 2 => ( + [group[0], group[1], b'u', b'u', b'u'].map(|b| (b - b'!') as u32), + 1, + ), + 3 => ( + [group[0], group[1], group[2], b'u', b'u'].map(|b| (b - b'!') as u32), + 2, + ), + 4 => ( + [group[0], group[1], group[2], group[3], b'u'].map(|b| (b - b'!') as u32), + 3, + ), + 5 => ( + [group[0], group[1], group[2], group[3], group[4]].map(|b| (b - b'!') as u32), + 4, + ), + _ => unreachable!(), + }; + + let value = digits[0] + .checked_mul(POW_85[0])? + .checked_add(digits[1].checked_mul(POW_85[1])?)? + .checked_add(digits[2].checked_mul(POW_85[2])?)? + .checked_add(digits[3].checked_mul(POW_85[3])?)? + .checked_add(digits[4])?; + + decoded.extend_from_slice(&value.to_be_bytes()[..output_len]); + group.clear(); + Some(()) + }; + + out.reserve(data.len() * 4 / 5); + let mut group = Vec::with_capacity(5); + + loop { + let Some(b) = read_byte() else { + // Be lenient and accept what we have (see PDFBOX-5910). + flush_group(&mut group, out)?; + + return Some(()); + }; + + match b { + b'!'..=b'u' => { + group.push(b); + + if group.len() == 5 { + flush_group(&mut group, out)?; + } + } + b'z' => { + flush_group(&mut group, out)?; + out.extend_from_slice(&[0, 0, 0, 0]); + } + b'~' => { + // Technically requires a '>', but there is a PDF where it isn't + // appended and decodes fine in other viewers. + flush_group(&mut group, out)?; + + return Some(()); + } + _ => return None, // Invalid character. + } + } +} diff --git a/vendor/hayro-postscript/src/string/ascii_hex.rs b/vendor/hayro-postscript/src/string/ascii_hex.rs new file mode 100644 index 0000000000..bdf74389f4 --- /dev/null +++ b/vendor/hayro-postscript/src/string/ascii_hex.rs @@ -0,0 +1,59 @@ +// Keep in sync with `hayro-syntax/src/filter/ascii_hex.rs`. + +use crate::reader::is_whitespace; +use alloc::vec::Vec; + +pub(crate) fn decode_into(data: &[u8], out: &mut Vec) -> Option<()> { + let has_whitespace = data.iter().any(|&b| is_whitespace(b)); + + out.reserve(data.len().div_ceil(2)); + + if !has_whitespace { + // Fast path, don't need to worry about white spaces. + let mut i = 0; + while i + 1 < data.len() { + out.push(decode_hex_digit(data[i])? << 4 | decode_hex_digit(data[i + 1])?); + i += 2; + } + if i < data.len() { + out.push(decode_hex_digit(data[i])? << 4); + } + } else { + // Slow path, need to strip white spaces. + let mut iter = data.iter().copied(); + let mut read_byte = || -> Option { + loop { + let b = iter.next()?; + if !is_whitespace(b) { + return Some(b); + } + } + }; + + loop { + match (read_byte(), read_byte()) { + (Some(hi), Some(lo)) => { + out.push(decode_hex_digit(hi)? << 4 | decode_hex_digit(lo)?); + } + (Some(hi), None) => { + out.push(decode_hex_digit(hi)? << 4); + + break; + } + (None, _) => break, + } + } + } + + Some(()) +} + +#[inline(always)] +pub(crate) fn decode_hex_digit(c: u8) -> Option { + match c { + b'0'..=b'9' => Some(c - b'0'), + b'A'..=b'F' => Some(c - b'A' + 10), + b'a'..=b'f' => Some(c - b'a' + 10), + _ => None, + } +} diff --git a/vendor/hayro-postscript/src/string/literal.rs b/vendor/hayro-postscript/src/string/literal.rs new file mode 100644 index 0000000000..37a15934ff --- /dev/null +++ b/vendor/hayro-postscript/src/string/literal.rs @@ -0,0 +1,85 @@ +// Keep in sync with `hayro-syntax/src/object/string.rs` (`read_literal`). + +use alloc::vec::Vec; + +use crate::reader::Reader; + +pub(crate) fn decode_into(data: &[u8], out: &mut Vec) -> Option<()> { + let mut r = Reader::new(data); + + while let Some(byte) = r.read_byte() { + match byte { + b'\\' => { + let next = r.read_byte()?; + + if is_octal_digit(next) { + let second = r.read_byte(); + let third = r.read_byte(); + + let bytes = match (second, third) { + (Some(n1), Some(n2)) => match (is_octal_digit(n1), is_octal_digit(n2)) { + (true, true) => [next, n1, n2], + (true, _) => { + r.jump(r.offset() - 1); + [b'0', next, n1] + } + _ => { + r.jump(r.offset() - 2); + [b'0', b'0', next] + } + }, + (Some(n1), None) => { + if is_octal_digit(n1) { + [b'0', next, n1] + } else { + r.jump(r.offset() - 1); + [b'0', b'0', next] + } + } + _ => [b'0', b'0', next], + }; + + let str = core::str::from_utf8(&bytes).unwrap(); + + if let Ok(num) = u8::from_str_radix(str, 8) { + out.push(num); + } + } else { + match next { + b'n' => out.push(0xA), + b'r' => out.push(0xD), + b't' => out.push(0x9), + b'b' => out.push(0x8), + b'f' => out.push(0xC), + b'(' => out.push(b'('), + b')' => out.push(b')'), + b'\\' => out.push(b'\\'), + b'\n' | b'\r' => { + // "If the \ is followed immediately by a newline + // (CR, LF, or CR-LF pair), the scanner ignores + // both the initial \ and the newline; this breaks + // a string into multiple lines without including + // the newline character as part of the string." + r.skip_eol(); + } + _ => out.push(next), + } + } + } + b'(' | b')' => out.push(byte), + // "But if a newline appears without a preceding \, the result is + // equivalent to \n." + b'\n' | b'\r' => { + out.push(b'\n'); + r.skip_eol(); + } + other => out.push(other), + } + } + + Some(()) +} + +fn is_octal_digit(byte: u8) -> bool { + matches!(byte, b'0'..=b'7') +} diff --git a/vendor/hayro/src/lib.rs b/vendor/hayro/src/lib.rs index a5ce6c2a94..37d1a5b078 100644 --- a/vendor/hayro/src/lib.rs +++ b/vendor/hayro/src/lib.rs @@ -61,7 +61,7 @@ use vello_cpu::{Level, Pixmap, RenderMode}; mod renderer; /// PdfCraft patch: exported for its regression test. -pub use renderer::{image_resampling_size, tiling_cell_scale, usable_cell_scale}; +pub use renderer::{image_resampling_size, tiling_cell_pixels, tiling_cell_scale, usable_cell_scale}; /// PdfCraft patch: exported for its regression test. #[doc(hidden)] pub use renderer::set_skip_offscreen_paths; diff --git a/vendor/hayro/src/renderer.rs b/vendor/hayro/src/renderer.rs index 8909cb62a4..242c54ec2b 100644 --- a/vendor/hayro/src/renderer.rs +++ b/vendor/hayro/src/renderer.rs @@ -1302,13 +1302,18 @@ impl Renderer { xs = tiling_cell_scale(xs, t.x_step, MAX_PIXMAP_SIZE); ys = tiling_cell_scale(ys, t.y_step, MAX_PIXMAP_SIZE); - let x_step = xs * t.x_step; - let y_step = ys * t.y_step; + // PdfCraft patch (25): the cell pixmap repeats every `pix_width` pixels, + // so one step must be exactly that many pixels. The cell is drawn at the + // scale that makes it so, and the paint transform below maps the pixmap + // back onto pattern space: cells sit at whole multiples of the step at + // any device scale. Drawing at the unrounded scale repeated the cell a + // fraction of a pixel too early or late, and the error grew with every + // step away from the pattern's origin. + let (pix_width, xs) = tiling_cell_pixels(xs, t.x_step, MAX_PIXMAP_SIZE); + let (pix_height, ys) = tiling_cell_pixels(ys, t.y_step, MAX_PIXMAP_SIZE); - let scaled_width = bbox.width() as f32 * xs; - let scaled_height = bbox.height() as f32 * ys; - let pix_width = x_step.abs().round() as u16; - let pix_height = y_step.abs().round() as u16; + let scaled_width = bbox.width() * xs; + let scaled_height = bbox.height() * ys; let mut renderer = Self { ctx: RenderContext::new_with( @@ -1332,7 +1337,7 @@ impl Renderer { preview: self.preview, image_transparency_stack: Vec::new(), }; - let mut initial_transform = Affine::scale_non_uniform(xs as f64, ys as f64) + let mut initial_transform = Affine::scale_non_uniform(xs, ys) * Affine::translate((-bbox.x0, -bbox.y0)); t.interpret(&mut renderer, initial_transform, is_stroke); let mut pix = Pixmap::new(pix_width, pix_height); @@ -1341,14 +1346,14 @@ impl Renderer { renderer.ctx.render_to_pixmap(&mut resources, &mut pix); // TODO: Fix these - if x_step < 0.0 { + if t.x_step < 0.0 { initial_transform *= - Affine::new([-1.0, 0.0, 0.0, 1.0, scaled_width as f64, 0.0]); + Affine::new([-1.0, 0.0, 0.0, 1.0, scaled_width, 0.0]); } - if y_step < 0.0 { + if t.y_step < 0.0 { initial_transform *= - Affine::new([1.0, 0.0, 0.0, -1.0, 0.0, scaled_height as f64]); + Affine::new([1.0, 0.0, 0.0, -1.0, 0.0, scaled_height]); } paint_transform = @@ -2186,3 +2191,26 @@ pub fn tiling_cell_scale(scale: f32, step: f32, max_pixels: f32) -> f32 { scale } } + +/// PdfCraft patch (25): the side of a tiling cell pixmap in pixels, and the scale to draw the +/// cell at so that one `step` spans exactly that many pixels. The pixmap repeats every whole +/// number of pixels; drawing the cell at `scale` itself would repeat it at `round(scale × step)` +/// instead of `scale × step`, a fraction of a pixel off at every step (ISO 32000-2 8.7.3.1: cells +/// are displaced by multiples of `/XStep` and `/YStep`). The side is kept within 1 and +/// `max_pixels` (itself at most `u16::MAX`). When `scale × step` isn't finite and positive, +/// `scale` is kept and the side is `max_pixels` for an infinite product, 1 otherwise. +pub fn tiling_cell_pixels(scale: f32, step: f32, max_pixels: f32) -> (u16, f64) { + // A whole number of pixels; `max` and `min` (not `clamp`, which panics on NaN) make a NaN cap 1. + let max = f64::from(max_pixels).floor().max(1.0).min(f64::from(u16::MAX)); + let (scale, step) = (f64::from(scale), f64::from(step.abs())); + let exact = scale * step; + if !(exact.is_finite() && exact > 0.0) { + let pixels = if exact == f64::INFINITY { max } else { 1.0 }; + // In 1..=u16::MAX, so the cast is exact. + return (pixels as u16, scale); + } + let pixels = exact.round().max(1.0).min(max); + // `pixels` is in 1..=u16::MAX, so the cast is exact; `step` is positive and finite here + // (`exact` is), so the division is too. + (pixels as u16, pixels / step) +} diff --git a/xtask/src/layers.rs b/xtask/src/layers.rs index 8ad15733a2..b961ebef66 100644 --- a/xtask/src/layers.rs +++ b/xtask/src/layers.rs @@ -182,6 +182,34 @@ impl std::fmt::Display for Violation { } } +/// Layer and testkit rules for one dependency of `c` that is itself a workspace crate. +fn check_workspace_dep(c: &Crate, class: Class, layer: u8, d: &Dep, out: &mut Vec) { + let dep_class = classify(&d.name); + // Test support is a dev-dependency only (`Class::Testkit`) and so never reaches + // the product graph a standalone crate publishes. Checking it against the + // standalone allow-list would stop `cos` using the shared oracles in its own + // tests, which is the one thing those crates exist for. + let testkit_dev = dep_class == Some(Class::Testkit) && d.kind == DepKind::Dev; + if matches!(class, Class::Standalone(_)) && !testkit_dev && !standalone_allowed(&c.name, &d.name) { + out.push(Violation::StandaloneHasWorkspaceDep { krate: c.name.clone(), dep: d.name.clone() }); + return; + } + match dep_class { + None => {} + Some(Class::Testkit) if d.kind != DepKind::Dev && class != Class::Testkit => { + out.push(Violation::TestkitAsNormalDep { krate: c.name.clone(), dep: d.name.clone() }); + } + Some(Class::Testkit) => {} + Some(dc) => { + let to = dc.layer().unwrap_or(u8::MAX); + let ok = to < layer || (to == layer && sideways_allowed(&c.name, &d.name)); + if !ok { + out.push(Violation::Upward { krate: c.name.clone(), dep: d.name.clone(), from: layer, to: to.min(8), kind: d.kind }); + } + } + } +} + pub fn check(crates: &[Crate]) -> Vec { let mut out = Vec::new(); for c in crates { @@ -198,30 +226,7 @@ pub fn check(crates: &[Crate]) -> Vec { continue; } if d.workspace { - let dep_class = classify(&d.name); - // Test support is a dev-dependency only (`Class::Testkit`) and so never reaches - // the product graph a standalone crate publishes. Checking it against the - // standalone allow-list would stop `cos` using the shared oracles in its own - // tests, which is the one thing those crates exist for. - let testkit_dev = dep_class == Some(Class::Testkit) && d.kind == DepKind::Dev; - if matches!(class, Class::Standalone(_)) && !testkit_dev && !standalone_allowed(&c.name, &d.name) { - out.push(Violation::StandaloneHasWorkspaceDep { krate: c.name.clone(), dep: d.name.clone() }); - continue; - } - match dep_class { - None => {} - Some(Class::Testkit) if d.kind != DepKind::Dev && class != Class::Testkit => { - out.push(Violation::TestkitAsNormalDep { krate: c.name.clone(), dep: d.name.clone() }); - } - Some(Class::Testkit) => {} - Some(dc) => { - let to = dc.layer().unwrap_or(u8::MAX); - let ok = to < layer || (to == layer && sideways_allowed(&c.name, &d.name)); - if !ok { - out.push(Violation::Upward { krate: c.name.clone(), dep: d.name.clone(), from: layer, to: to.min(8), kind: d.kind }); - } - } - } + check_workspace_dep(c, class, layer, d, &mut out); } else if layer < UI_MIN_LAYER && is_ui_crate(&d.name) && !(class == Class::Testkit || d.kind == DepKind::Dev && d.name == "egui_kittest") { out.push(Violation::UiBelowL7 { krate: c.name.clone(), dep: d.name.clone(), layer }); diff --git a/xtask/src/parity.rs b/xtask/src/parity.rs index 5466776102..ac32f32e85 100644 --- a/xtask/src/parity.rs +++ b/xtask/src/parity.rs @@ -104,6 +104,18 @@ fn valid_milestone(m: &str) -> bool { m == "none" || m.strip_prefix('M').and_then(|n| n.parse::().ok()).is_some_and(|n| n <= 14) } +/// Why an `evidence` entry (`path.rs::test_fn`) does not resolve to a test in the source tree, if it doesn't. +fn evidence_error(ev: &str, repo: &Path) -> Option { + let Some((path, func)) = ev.split_once("::") else { + return Some(format!("evidence {ev:?} must be `path.rs::test_fn`")); + }; + match std::fs::read_to_string(repo.join(path)) { + Ok(src) if src.contains(&format!("fn {func}(")) => None, + Ok(_) => Some(format!("evidence: no `fn {func}` in {path}")), + Err(_) => Some(format!("evidence: {path} does not exist")), + } +} + /// Validate features against the registry, tool table and source tree; returns the errors. pub fn validate(features: &[Feature], commands: &HashSet, tools: &HashSet, repo: &Path) -> Vec { let mut errors = Vec::new(); @@ -143,14 +155,8 @@ pub fn validate(features: &[Feature], commands: &HashSet, tools: &HashSe errors.push(e("shipped features must cite at least one test in `evidence`".into())); } for ev in &f.evidence { - let Some((path, func)) = ev.split_once("::") else { - errors.push(e(format!("evidence {ev:?} must be `path.rs::test_fn`"))); - continue; - }; - match std::fs::read_to_string(repo.join(path)) { - Ok(src) if src.contains(&format!("fn {func}(")) => {} - Ok(_) => errors.push(e(format!("evidence: no `fn {func}` in {path}"))), - Err(_) => errors.push(e(format!("evidence: {path} does not exist"))), + if let Some(m) = evidence_error(ev, repo) { + errors.push(e(m)); } } }