PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust
M2.6: a page's forms and pictures read their resources in place
Grzegorz Martens1b61121c66dc
diff --git a/crates/edit/src/background.rs b/crates/edit/src/background.rsindex 7d745c0c1..376cb5a16 100644--- a/crates/edit/src/background.rs+++ b/crates/edit/src/background.rs@@ -98,8 +98,13 @@ pub fn page_background(doc: &Document, page: usize) -> Result<Option<Rgb>, EditE}b"sc" | b"scn" => st.fill = colour(st.space, op),b"gs" => {- if let Some(g) = op.name(0).and_then(|n| gstates.get(n)).map(|g| doc.resolve(g)).and_then(|g| g.as_dict().cloned()) {- apply_gstate(doc, &g, &mut st);+ let mut held = None;+ let gstate = match op.name(0).and_then(|n| gstates.get(n)) {+ Some(g) => crate::text::dict_in_place(doc, g, &mut held),+ None => None,+ };+ if let Some(g) = gstate {+ apply_gstate(doc, g, &mut st);}}b"re" => match op.nums::<4>() {diff --git a/crates/edit/src/images.rs b/crates/edit/src/images.rsindex f66e7f24e..71ae49941 100644--- a/crates/edit/src/images.rs+++ b/crates/edit/src/images.rs@@ -316,34 +316,34 @@ pub fn reading_images(doc: &Document, page: usize) -> Result<Vec<PageImage>, Ediforms: &mut Forms,out: &mut Vec<PageImage>,) -> Result<(), EditError> {- let xo = resources.get(b"XObject").map(|x| doc.resolve(x)).and_then(|x| x.as_dict().cloned()).unwrap_or_default();+ let mut held = None;+ let xo = crate::text::resource_dict(doc, resources, b"XObject", &mut held);for (i, op) in ops.iter().enumerate() {st.apply(op)?;let ctm = st.placement.matrix;if op.is("Do") {let Some(name) = op.name(0) else { continue };+ let drawn = xo.and_then(|xo| xo.get(name));if let Some(form) = crate::text::form_call(doc, resources, name, ctm, &forms.path, &mut forms.budget) {if let Some(r) = form.obj {forms.path.push(r);}let bounds =- xo.get(name).map(|o| doc.resolve(o)).and_then(|o| o.as_dict().and_then(|d| d.get(b"BBox")).map(|b| doc.resolve(b))).and_then(- |b| {- let a = b.as_array()?;- let [x0, y0, x1, y1] = a.as_slice() else { return None };- Some(form.ctm.bbox([x0.as_f64()?, y0.as_f64()?, x1.as_f64()?, y1.as_f64()?]))- },- );+ drawn.map(|o| doc.resolve(o)).and_then(|o| o.as_dict().and_then(|d| d.get(b"BBox")).map(|b| doc.resolve(b))).and_then(|b| {+ let a = b.as_array()?;+ let [x0, y0, x1, y1] = a.as_slice() else { return None };+ Some(form.ctm.bbox([x0.as_f64()?, y0.as_f64()?, x1.as_f64()?, y1.as_f64()?]))+ });let clip = bounds.map_or(st.placement.clip, |b| intersection(st.placement.clip, b).unwrap_or([0.0; 4]));let mut inner = ImageState::new(form.ctm, clip, st.placement.clips.clone());let piece = stream(op);- walk(doc, &parse(&form.data).ops, &form.resources, &mut inner, &|_| piece, forms, out)?;+ walk(doc, &parse(&form.data).ops, form.resources(resources), &mut inner, &|_| piece, forms, out)?;if form.obj.is_some() {forms.path.pop();}continue;}- let Some(r) = xo.get(name).and_then(Object::as_ref) else { continue };+ let Some(r) = drawn.and_then(Object::as_ref) else { continue };let obj = doc.get(r);let Object::Stream(s) = &*obj else { continue };if s.dict.name(b"Subtype") != Some(b"Image") {diff --git a/crates/edit/src/tests.rs b/crates/edit/src/tests.rsindex d45e983a2..6df9ab19d 100644--- a/crates/edit/src/tests.rs+++ b/crates/edit/src/tests.rs@@ -4584,6 +4584,41 @@ fn reading_follows_form_xobjects() {assert!(own[0].is_form && own[0].object == Some(pdfcraft_cos::ObjRef::new(6, 0)), "{own:?}");}+/// A page's `/XObject` and a form's `/Resources` are read wherever they are stored, and a form with+/// none of its own, or with something else there, uses the ones it was drawn with (PDF 1.1 files).+/// Each of these pages shows one line of text and one picture through one form.+#[test]+fn reading_follows_forms_however_their_resources_are_stored() {+ let body = "BT /F1 12 Tf 72 700 Td (In the form) Tj ET q 20 0 0 10 5 5 cm /Im Do Q";+ let (font, direct) = ("/Font << /F1 5 0 R >>", "/XObject << /Fm 6 0 R /Im 7 0 R >>");+ for (page, form) in [+ (format!("<< {font} {direct} >>"), ""),+ (format!("<< {font} /XObject 9 0 R >>"), ""),+ (format!("<< /Font 10 0 R {direct} >>"), ""),+ (format!("<< {font} {direct} >>"), "/Resources 99 0 R"),+ (format!("<< {font} {direct} >>"), "/Resources 12"),+ ("<< /XObject << /Fm 6 0 R >> >>".to_string(), "/Resources 8 0 R"),+ ("<< /XObject 9 0 R >>".to_string(), "/Resources << /Font << /F1 5 0 R >> /XObject 9 0 R >>"),+ ] {+ let doc = build(&[+ "<< /Type /Catalog /Pages 2 0 R >>",+ "<< /Type /Pages /Kids [3 0 R] /Count 1 >>",+ &format!("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 600 800] /Resources {page} /Contents 4 0 R >>"),+ &stream("", "/Fm Do"),+ "<< /Type /Font /Subtype /Type1 /BaseFont /Courier >>",+ &stream(&format!("/Type /XObject /Subtype /Form /BBox [0 0 600 800] {form}"), body),+ &stream("/Type /XObject /Subtype /Image /Width 1 /Height 1 /ColorSpace /DeviceGray /BitsPerComponent 8", "A"),+ "<< /Font << /F1 5 0 R >> /XObject 9 0 R >>",+ "<< /Fm 6 0 R /Im 7 0 R >>",+ "<< /F1 5 0 R >>",+ ]);+ let blocks = text::reading_blocks(&doc, 0).unwrap();+ let texts: Vec<(&str, &str)> = blocks.iter().map(|b| (b.text.as_str(), b.base_font.as_str())).collect();+ assert_eq!(texts, [("In the form", "Courier")], "{page} {form}");+ assert_eq!(images::reading_images(&doc, 0).unwrap().len(), 1, "{page} {form}");+ }+}+/// A chain of forms, each drawing the next twenty times, twelve deep: within the depth cap but/// 20^11 visits without a budget. Reading stops at the page's visit budget instead of hanging.#[test]diff --git a/crates/edit/src/text.rs b/crates/edit/src/text.rsindex 98824c769..fdceaa9b0 100644--- a/crates/edit/src/text.rs+++ b/crates/edit/src/text.rs@@ -53,7 +53,7 @@ use fallback::{use fallback::{add_type3_font, is_type3_fallback};use interp::{Origin, Paint, union};use lines::page_dict;-pub(crate) use lines::{FormBudget, content_streams, content_streams_within, form_call, rewritten_contents, splice};+pub(crate) use lines::{FormBudget, content_streams, content_streams_within, dict_in_place, form_call, resource_dict, rewritten_contents, splice};pub use lines::{MAX_FORM_DEPTH, MAX_FORM_VISITS, glyph_text_lines, text_lines};pub use rewrite::{LineEdit, replace_line, rewrite_block};use rewrite::{coincident_ops, rewrite_block_from};diff --git a/crates/edit/src/text/interp.rs b/crates/edit/src/text/interp.rsindex 2b55e51ef..2a9f6da61 100644--- a/crates/edit/src/text/interp.rs+++ b/crates/edit/src/text/interp.rs@@ -773,8 +773,9 @@ pub(super) fn interpret(// `Some(properties)`: read `/ActualText`, looking named property lists up in `properties`.logical_text: Option<&Dict>,) -> Result<Vec<Shown>, EditError> {- let fonts_res = resources.get(b"Font").map(|f| doc.resolve(f)).and_then(|f| f.as_dict().cloned()).unwrap_or_default();- let states = resources.get(b"ExtGState").map(|g| doc.resolve(g)).and_then(|g| g.as_dict().cloned()).unwrap_or_default();+ let (mut held_fonts, mut held_states, none) = (None, None, Dict::new());+ let fonts_res = super::resource_dict(doc, resources, b"Font", &mut held_fonts).unwrap_or(&none);+ let states = super::resource_dict(doc, resources, b"ExtGState", &mut held_states).unwrap_or(&none);let mut out: Vec<Shown> = Vec::new();let mut ts = carry.ts.clone();let mut at_bt = (0usize, ts.clone());@@ -881,8 +882,12 @@ pub(super) fn interpret(if let Some(name) = op.name(0) {select_gs(&mut ts.ext_gstate, name);}- let params = op.name(0).and_then(|name| states.get(name)).map(|p| doc.resolve(p));- if let Some(params) = params.as_deref().and_then(Object::as_dict) {+ let mut held = None;+ let params = match op.name(0).and_then(|name| states.get(name)) {+ Some(p) => super::dict_in_place(doc, p, &mut held),+ None => None,+ };+ if let Some(params) = params {ts.gs.apply(doc, params);// `/LW` sets the line width as `w` does (ISO 32000-2 §8.4.5).let lw = params.get(b"LW").and_then(|w| doc.resolve(w).as_f64()).filter(|w| w.is_finite());diff --git a/crates/edit/src/text/lines.rs b/crates/edit/src/text/lines.rsindex f811f34ea..85209a547 100644--- a/crates/edit/src/text/lines.rs+++ b/crates/edit/src/text/lines.rs@@ -1,3 +1,5 @@+use std::sync::Arc;+use super::fallback::{same_font, same_paint};use super::interp::{Carry, Origin, Pen, Shown, TextState, Ts, direction, interpret, to_frame, union};use super::{DecodeBudget, Dict, Document, EditError, HashMap, Matrix, Object, Op, Pieces, Stream, TextLine, parse, serialize_ops};@@ -452,10 +454,41 @@ impl FormBudget {pub(crate) struct FormCall {pub(crate) obj: Option<pdfcraft_cos::ObjRef>,pub(crate) data: Vec<u8>,- pub(crate) resources: Dict,+ /// The form, and its `/Resources` when they are an object of their own, which is what+ /// [`FormCall::resources`] reads.+ form: Arc<Object>,+ own: Option<Arc<Object>>,pub(crate) ctm: Matrix,}+impl FormCall {+ /// The resources its content is read with: its own, or if it has none, `drawn_with`, the ones+ /// it was drawn with (PDF 1.1 files). Read in place, as a page can draw a form thousands of times:+ /// a copy for each took time in the square of them.+ pub(crate) fn resources<'a>(&'a self, drawn_with: &'a Dict) -> &'a Dict {+ let direct = || match &*self.form {+ Object::Stream(s) => s.dict.get(b"Resources").and_then(Object::as_dict),+ _ => None,+ };+ self.own.as_deref().and_then(Object::as_dict).or_else(direct).unwrap_or(drawn_with)+ }+}++/// `o` as a dictionary, read in place for the same reason as [`FormCall::resources`]. `held` keeps it+/// when it is an object of its own. Nothing else is one, and [`Document::resolve`] would copy it.+pub(crate) fn dict_in_place<'a>(doc: &Document, o: &'a Object, held: &'a mut Option<Arc<Object>>) -> Option<&'a Dict> {+ match o {+ Object::Dict(dict) => Some(dict),+ Object::Ref(_) => held.insert(doc.resolve(o)).as_dict(),+ _ => None,+ }+}++/// The dictionary at `key` of `resources`, `/XObject` or `/Font`, say, as each form reads these.+pub(crate) fn resource_dict<'a>(doc: &Document, resources: &'a Dict, key: &[u8], held: &'a mut Option<Arc<Object>>) -> Option<&'a Dict> {+ dict_in_place(doc, resources.get(key)?, held)+}+/// The form XObject `name` in `resources`, drawn with `ctm`. `None` for images, missing names/// and forms already being read (`path`), and for forms nested too deep or past the page's/// budget, which `budget` records as truncated; each form entered counts one visit.@@ -472,13 +505,15 @@ pub(crate) fn form_call(if limited && budget.truncated {return None;}- let xobjects = resources.get(b"XObject").map(|x| doc.resolve(x)).and_then(|x| x.as_dict().cloned())?;- let o = xobjects.get(name)?;- let obj = o.as_ref();+ let mut held = None;+ let o = resource_dict(doc, resources, b"XObject", &mut held)?.get(name)?;+ // Only a reference can name a stream, so nothing else needs reading, or copying.+ let obj = Some(o.as_ref()?);if obj.is_some_and(|r| path.contains(&r)) {return None;}- let Object::Stream(s) = &*doc.resolve(o) else { return None };+ let form = doc.resolve(o);+ let Object::Stream(s) = &*form else { return None };if s.dict.name(b"Subtype") != Some(b"Form") {return None;}@@ -492,8 +527,7 @@ pub(crate) fn form_call(let v: Vec<f64> = a.iter().filter_map(|x| doc.resolve(x).as_f64()).collect();<[f64; 6]>::try_from(v).ok().filter(|v| v.iter().all(|x| x.is_finite()))});- // A form without its own resources uses the ones it was drawn with (PDF 1.1 files).- let own = s.dict.get(b"Resources").map(|r| doc.resolve(r)).and_then(|r| r.as_dict().cloned());+ let own = s.dict.get(b"Resources").filter(|r| matches!(r, Object::Ref(_))).map(|r| doc.resolve(r));let data = match budget.decode.decode(s) {Ok(data) => data,Err(_) if budget.decode.remaining() == 0 => {@@ -503,7 +537,7 @@ pub(crate) fn form_call(Err(_) => Vec::new(),};budget.visits = budget.visits.saturating_add(1);- Some(FormCall { obj, data, resources: own.unwrap_or_else(|| resources.clone()), ctm: m.map_or(ctm, |m| Matrix(m).then(&ctm)) })+ Some(FormCall { obj, data, form, own, ctm: m.map_or(ctm, |m| Matrix(m).then(&ctm)) })}/// The lines a page shows as it reads, including text drawn by form XObjects (which@@ -522,8 +556,9 @@ pub(super) fn reading_lines(doc: &Document, page: usize) -> Result<(Vec<TextLinefn walk(w: &mut Walk, ops: &[Op], resources: &Dict, carry: &mut Carry, stream: &dyn Fn(usize) -> usize) -> Result<(), EditError> {let mut cache = HashMap::new();let mut invoked = Vec::new();- let properties = resources.get(b"Properties").and_then(|o| w.doc.dict(o)).unwrap_or_default();- let shown = interpret(w.doc, ops, resources, &mut cache, carry, Some(&mut invoked), Some(&properties))?;+ let (mut held, none) = (None, Dict::new());+ let properties = resource_dict(w.doc, resources, b"Properties", &mut held).unwrap_or(&none);+ let shown = interpret(w.doc, ops, resources, &mut cache, carry, Some(&mut invoked), Some(properties))?;let mut last = None;let mut last_stream = None;let mut forms = invoked.into_iter().peekable();@@ -556,7 +591,7 @@ pub(super) fn reading_lines(doc: &Document, page: usize) -> Result<(Vec<TextLineif let Some(r) = form.obj {w.path.push(r);}- walk(w, &ops, &form.resources, &mut carry, &|_| stream)?;+ walk(w, &ops, form.resources(resources), &mut carry, &|_| stream)?;*text_left = carry.text_left;if form.obj.is_some() {w.path.pop();diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rsindex 1e25a919c..9553a5d10 100644--- a/crates/engine/src/tests.rs+++ b/crates/engine/src/tests.rs@@ -9225,8 +9225,7 @@ fn page_of_pictures(count: usize, side: usize) -> Vec<u8> {/// The allowance is the export's, not each picture's: a page of many small pictures stops where it/// runs out, the rest are left out and counted, and the page is listed, which is what the export's-/// warning goes by. A few large pictures are well within it, and all come through. 2,000 are enough-/// to show it: 10,000 behave the same, and take half a minute to read in a test build.+/// warning goes by. A few large pictures are well within it, and all come through.#[test]fn a_page_of_many_pictures_stops_at_the_exports_allowance() {let export = |pdf: Vec<u8>, work: &mut pdfcraft_cos::ImageBudget| {@@ -9240,10 +9239,10 @@ fn a_page_of_many_pictures_stops_at_the_exports_allowance() {assert!(cost > 0);let mut work = pdfcraft_cos::ImageBudget::with_work(100 * cost);- let (pages, truncated) = export(page_of_pictures(2_000, 2), &mut work);+ let (pages, truncated) = export(page_of_pictures(10_000, 2), &mut work);assert_eq!(pages[0].images.len(), 100);assert_eq!(truncated, vec![0]);- assert_eq!(work.refused(), 1_900);+ assert_eq!(work.refused(), 9_900);let mut s = Session::new();let id = s.open("large.pdf", None, Arc::new(page_of_pictures(3, 1_000)), None).unwrap();