Skip to content

PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust

fix(redact): place glyphs with the inherited and ExtGState-set text state

aiongg22aa6d5f9afb
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index 32d3a1f15..f257865d3 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -985,7 +985,7 @@ fn recovered_render_password(cos: &pdfcraft_cos::Document) -> Option<String> {
///
/// Redaction decides what lies under a mark from the positions its own interpreter computes, and
/// its verify pass reuses them. Where they differ from the renderer's (a standard font without
-/// /Widths, whose advances the interpreter approximates; a CMap, or a font set outside `Tf`,
+/// /Widths, whose advances the interpreter approximates; a CMap
/// that it reads differently), a mark drawn over the text as displayed lies over glyphs the
/// interpreter believes are elsewhere: they stay in the file and nothing notices. The renderer is
/// what the user saw when placing the marks, so it is asked. `after` is written as a save would
diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs
index 958204bc5..8937cf678 100644
--- a/crates/engine/src/tests.rs
+++ b/crates/engine/src/tests.rs
@@ -2294,58 +2294,52 @@ fn mark_shown_text(s: &mut Session, id: DocId, needle: &str) {
s.apply(id, mark).unwrap();
}
-/// Redaction removes text by the positions its own interpreter works out. Here the font and size
-/// come from an ExtGState /Font entry (`gs`), which the renderer honours and the interpreter does
-/// not model, so it places no glyph under the mark the user drew over the word as displayed: it
-/// used to report success and leave the word in the file. The renderer is asked now, and the edit
-/// is refused.
+/// Redaction removes text by the positions its own interpreter works out, and the renderer has
+/// the last word: where the two disagree, a page that still shows a glyph mostly under a mark
+/// fails the edit. The check is run here on a page nothing was removed from, as if the
+/// interpreter had placed the word elsewhere. Only the overlay streams an apply added are left
+/// out: a content stream of the input labelled like one (`/PCMark /Redaction`) is checked too.
#[test]
-fn redaction_is_refused_when_the_page_still_shows_text_under_a_mark() {
+fn the_renderer_check_refuses_text_still_shown_under_a_mark() {
+ let mut s = Session::new().with_clock(|| 1_700_000_000);
+ let page = one_line_page_with("/Font << /F1 4 0 R >>", "/PCMark /Redaction", "BT /F1 16 Tf 20 150 Td (Public words then SECRET42) Tj ET");
+ let id = s.open("shown.pdf", None, Arc::new(page), None).unwrap();
+ mark_shown_text(&mut s, id, "SECRET42");
+ let doc = s.get(id).unwrap();
+ let mut cos = doc.editor.as_ref().unwrap().cos.clone();
+ let marks = pdfcraft_redact::marks(&cos);
+ let refused = |cos: &pdfcraft_cos::Document| {
+ let shown = shown_under_redactions(cos, &marks, &[], &doc.info.pages, None);
+ matches!(shown, Err(EditError::Redact(pdfcraft_redact::RedactError::Residue(n))) if n > 0)
+ };
+ assert!(refused(&cos));
+ // The page's contents as an array, as they are once an apply has added its overlay.
+ let page = pdfcraft_model::pages(&cos).swap_remove(0);
+ let contents = page.dict.get(b"Contents").cloned().unwrap();
+ cos.update_dict(page.obj, |d| d.set(b"Contents".to_vec(), pdfcraft_cos::Object::Array(vec![contents]))).unwrap();
+ assert!(refused(&cos), "the labelled input stream was not checked");
+}
+
+/// A word whose font and size an ExtGState /Font entry (`gs`) sets is placed where the renderer
+/// draws it, so a mark drawn over it as displayed takes it out of the file.
+#[test]
+fn a_word_in_a_font_set_by_an_extgstate_is_redacted() {
let line = "Public words then SECRET42 and more";
let mut s = Session::new().with_clock(|| 1_700_000_000);
let by_gs = one_line_page("/ExtGState << /GS1 << /Type /ExtGState /Font [4 0 R 16] >> >>", &format!("BT /GS1 gs 20 150 Td ({line}) Tj ET"));
let id = s.open("gs.pdf", None, Arc::new(by_gs), None).unwrap();
mark_shown_text(&mut s, id, "SECRET42");
- let refused = s.apply(id, Edit::ApplyRedactions { pages: None });
- assert!(matches!(refused, Err(EditError::Redact(pdfcraft_redact::RedactError::Residue(n))) if n > 0), "{refused:?}");
- // Nothing was changed: the mark is still pending and the page still shows the line.
- assert_eq!(s.get(id).unwrap().redaction_marks(), 1);
- assert_eq!(page_texts(&s, id), [line]);
-
- // The same line with its font set by `Tf`: the mark is applied and the word is gone.
- let by_tf = one_line_page("/Font << /F1 4 0 R >>", &format!("BT /F1 16 Tf 20 150 Td ({line}) Tj ET"));
- let id = s.open("tf.pdf", None, Arc::new(by_tf), None).unwrap();
- mark_shown_text(&mut s, id, "SECRET42");
s.apply(id, Edit::ApplyRedactions { pages: None }).unwrap();
let shown = page_texts(&s, id).swap_remove(0);
assert!(shown.starts_with("Public words then") && shown.ends_with("and more") && !shown.contains("SECRET42"), "{shown}");
-}
-
-/// Only the overlay a redaction adds is left out of the renderer's check. A page whose own content
-/// stream calls itself a redaction overlay (`/PCMark /Redaction`) is checked like any other.
-#[test]
-fn a_content_stream_labelled_as_a_redaction_overlay_is_still_checked() {
- let line = "Public words then SECRET42 and more";
- let mut s = Session::new().with_clock(|| 1_700_000_000);
- let forged = one_line_page_with(
- "/ExtGState << /GS1 << /Type /ExtGState /Font [4 0 R 16] >> >>",
- "/PCMark /Redaction",
- &format!("BT /GS1 gs 20 150 Td ({line}) Tj ET"),
+ let saved = s.save_bytes(id).unwrap();
+ let held = |d: &[u8]| d.windows(8).any(|w| w == b"SECRET42");
+ assert!(!held(&saved), "the saved file holds the redacted word");
+ let reopened = pdfcraft_cos::Document::open(saved).unwrap();
+ assert!(
+ !reopened.scan_objects().any(|(_, o)| matches!(&*o, pdfcraft_cos::Object::Stream(st) if st.decoded().is_ok_and(|d| held(&d)))),
+ "a saved stream holds the redacted word"
);
- let id = s.open("forged.pdf", None, Arc::new(forged), None).unwrap();
- mark_shown_text(&mut s, id, "SECRET42");
- let applied = s.apply(id, Edit::ApplyRedactions { pages: None });
- if applied.is_ok() {
- assert!(!page_texts(&s, id).concat().contains("SECRET42"), "the page still shows the redacted word");
- let saved = s.save_bytes(id).unwrap();
- let held = |d: &[u8]| d.windows(8).any(|w| w == b"SECRET42");
- assert!(!held(&saved), "the saved file holds the redacted word");
- let reopened = pdfcraft_cos::Document::open(saved).unwrap();
- assert!(
- !reopened.scan_objects().any(|(_, o)| matches!(&*o, pdfcraft_cos::Object::Stream(st) if st.decoded().is_ok_and(|d| held(&d)))),
- "a saved stream holds the redacted word"
- );
- }
}
#[test]
diff --git a/crates/redact/src/interp.rs b/crates/redact/src/interp.rs
index a608568f3..14dedbb34 100644
--- a/crates/redact/src/interp.rs
+++ b/crates/redact/src/interp.rs
@@ -690,6 +690,34 @@ fn prune_form_resources(doc: &Document, res: &mut Dict, content: &[Vec<u8>]) ->
Ok(())
}
+/// The font, writing direction and size an ExtGState's `/Font [font size]` entry sets, as `Tf`
+/// would (ISO 32000-2 §8.4.5); `None` when `name` sets no font. The metrics are cached with the
+/// fonts `Tf` names, under a key no resource name can take (a name cannot hold a null byte).
+fn extgstate_font(
+ doc: &Document,
+ scope: &mut Scope<'_>,
+ ext_gstates: &Dict,
+ name: &[u8],
+ fallback: &Rc<Metrics>,
+) -> Option<(Rc<Metrics>, bool, f64)> {
+ let state = doc.resolve(ext_gstates.get(name)?).as_dict().cloned()?;
+ let entry = doc.resolve(state.get(b"Font")?).as_array().cloned()?;
+ let [font, size] = entry.as_slice() else { return None };
+ let size = doc.resolve(size).as_f64()?;
+ let font_dict = doc.resolve(font).as_dict().cloned();
+ let vertical = font_dict.as_ref().is_some_and(|d| is_vertical(doc, d));
+ let key = [b"\0".as_slice(), name].concat();
+ let metrics = match scope.fonts.get(&key) {
+ Some(m) => m.clone(),
+ None => {
+ let m = font_dict.as_ref().map(|d| Rc::new(Metrics::from_dict(doc, d))).unwrap_or_else(|| fallback.clone());
+ scope.fonts.insert(key, m.clone());
+ m
+ }
+ };
+ Some((metrics, vertical, size))
+}
+
/// One glyph of a shown string.
struct Glyph {
bytes: std::ops::Range<usize>,
@@ -700,11 +728,9 @@ struct Glyph {
/// Process a scope's content streams (state flows from one stream to the next).
pub(crate) fn process(doc: &mut Document, scope: &mut Scope<'_>, streams: &[Vec<u8>], resources: &Dict, ctm: Matrix) -> Output {
- let mut out = Output::default();
- let fallback = Rc::new(Metrics::fallback());
- let mut gs = Gs {
+ let gs = Gs {
ctm,
- font: fallback.clone(),
+ font: Rc::new(Metrics::fallback()),
vertical: false,
size: 0.0,
char_spacing: 0.0,
@@ -714,9 +740,19 @@ pub(crate) fn process(doc: &mut Document, scope: &mut Scope<'_>, streams: &[Vec<
leading: 0.0,
rise: 0.0,
};
+ process_from(doc, scope, streams, resources, gs)
+}
+
+/// [`process`] from graphics state `gs`: a form XObject starts with its caller's, text state
+/// included (ISO 32000-2 §8.10.1), so text it shows without setting a font of its own is placed
+/// with the caller's font, size and spacing, as the renderer places it.
+fn process_from(doc: &mut Document, scope: &mut Scope<'_>, streams: &[Vec<u8>], resources: &Dict, mut gs: Gs) -> Output {
+ let mut out = Output::default();
+ let fallback = Rc::new(Metrics::fallback());
let mut stack: Vec<Gs> = Vec::new();
let (mut tm, mut tlm) = (Matrix::IDENTITY, Matrix::IDENTITY);
let fonts_res = res_dict(doc, resources, b"Font");
+ let ext_gstates = res_dict(doc, resources, b"ExtGState");
let mut xobjects = res_dict(doc, resources, b"XObject");
// The current path: its operators, its bounding box in user space, and whether it clips.
let mut path: Vec<Op> = Vec::new();
@@ -865,6 +901,11 @@ pub(crate) fn process(doc: &mut Document, scope: &mut Scope<'_>, streams: &[Vec<
};
}
}
+ b"gs" => {
+ if let Some((font, vertical, size)) = op.name(0).and_then(|n| extgstate_font(doc, scope, &ext_gstates, n, &fallback)) {
+ (gs.font, gs.vertical, gs.size) = (font, vertical, size);
+ }
+ }
b"Tc" => gs.char_spacing = op.num(0).unwrap_or(0.0),
b"Tw" => gs.word_spacing = op.num(0).unwrap_or(0.0),
b"Tz" => gs.scale = op.num(0).unwrap_or(100.0) / 100.0,
@@ -1223,7 +1264,7 @@ fn xobject(
let res = own.clone().unwrap_or_else(|| resources.clone());
let saved_fonts = std::mem::take(&mut scope.fonts);
scope.depth += 1;
- let inner = process(doc, scope, std::slice::from_ref(&data), &res, fctm);
+ let inner = process_from(doc, scope, std::slice::from_ref(&data), &res, Gs { ctm: fctm, ..gs.clone() });
scope.depth -= 1;
scope.fonts = saved_fonts;
out.residue += inner.residue;
diff --git a/crates/redact/src/tests.rs b/crates/redact/src/tests.rs
index 52d80eb26..882cc50ae 100644
--- a/crates/redact/src/tests.rs
+++ b/crates/redact/src/tests.rs
@@ -2463,6 +2463,7 @@ fn unused_descriptions_in_shared_or_inherited_resources_are_retired() {
mod property_retirement;
mod surviving_references;
+mod text_state;
/// `[(FIRSTARR)] [(LASTARR)] TJ` is malformed (a surplus array operand), but the operator still
/// draws only the one immediately before it (LASTARR, 7 glyphs, 35 pt wide from x = 10) -- not
diff --git a/crates/redact/src/tests/text_state.rs b/crates/redact/src/tests/text_state.rs
new file mode 100644
index 000000000..4e888f262
--- /dev/null
+++ b/crates/redact/src/tests/text_state.rs
@@ -0,0 +1,27 @@
+//! Glyphs are placed with the whole text state, wherever it was set.
+
+use super::*;
+
+const SECRET_AT_10_100: [f64; 4] = [5.0, 95.0, 45.0, 110.0];
+
+#[test]
+fn a_font_set_by_an_extgstate_places_its_glyphs() {
+ let mut doc = one_page(b"BT /GS1 gs 10 100 Td (SECRET) Tj ET", "/ExtGState << /GS1 << /Type /ExtGState /Font [5 0 R 10] >> >>", vec![]);
+ // "ET" spans x 30–40.
+ assert_eq!(under(&mut doc, 0, &[[30.0, 95.0, 40.0, 110.0]]), 2);
+ mark(&mut doc, 0, &[SECRET_AT_10_100], "");
+ assert_eq!(apply(&mut doc, None).unwrap().glyphs, 6);
+ assert!(!content(&doc, 0).contains("SECRET"));
+}
+
+#[test]
+fn a_form_inherits_the_text_state_of_the_page_that_draws_it() {
+ // The form shows text with the font, size and spacing the page set before `Do`.
+ let form = stream("/Type /XObject /Subtype /Form /BBox [0 0 300 300]", b"BT 10 100 Td (SECRET) Tj ET");
+ let mut doc = one_page(b"/F1 10 Tf 1 Tc /Fm Do", "/XObject << /Fm 7 0 R >>", vec![form]);
+ // Glyphs 5 pt wide, 1 pt apart: the last one spans x 40–45.
+ assert_eq!(under(&mut doc, 0, &[[40.0, 95.0, 46.0, 110.0]]), 1);
+ mark(&mut doc, 0, &[SECRET_AT_10_100], "");
+ let r = apply(&mut doc, None).unwrap();
+ assert_eq!((r.glyphs, r.forms_rewritten), (6, 1), "{r:?}");
+}