Preserve graphics state across logical text annotations

This commit is contained in:
Dylan M. Taylor
2026-11-15 14:53:02 -05:00
parent 70c140f027
commit df3083222a
5 changed files with 212 additions and 23 deletions
+75 -5
View File
@@ -19,6 +19,9 @@ enum Kind {
pub(crate) struct Builder {
stack: Vec<(Group, Kind)>,
/// Logical text labels never share the graphics-state group stack.
text_labels: Vec<String>,
text_run: bool,
/// Which of the finished top-level nodes are optional-content layers.
pub top_layers: Vec<bool>,
pub skipped: Vec<String>,
@@ -34,14 +37,14 @@ pub(crate) fn group(name: &str) -> Group {
impl Builder {
pub fn new() -> Builder {
Builder { stack: vec![(group("page"), Kind::Plain)], top_layers: vec![], skipped: vec![], shapes: 0, base: 0 }
Builder { stack: vec![(group("page"), Kind::Plain)], text_labels: vec![], text_run: false, top_layers: vec![], skipped: vec![], shapes: 0, base: 0 }
}
/// A builder for content that will be placed inside this one's open groups and `wrap` more
/// groups (a pattern's `Pattern` and `Tile`, a soft mask's two), so its nesting limit counts
/// them.
pub fn nested(&self, wrap: usize) -> Builder {
Builder { base: self.base.saturating_add(self.stack.len()).saturating_add(wrap), ..Builder::new() }
Builder { base: self.base.saturating_add(self.stack.len()).saturating_add(self.text_labels.len()).saturating_add(wrap), ..Builder::new() }
}
pub fn depth(&self) -> usize {
@@ -50,7 +53,7 @@ impl Builder {
/// `wrap` more groups fit under the open ones within [`MAX_DEPTH`].
pub fn has_room(&self, wrap: usize) -> bool {
self.base.saturating_add(self.stack.len()).saturating_add(wrap) <= MAX_DEPTH
self.base.saturating_add(self.stack.len()).saturating_add(self.text_labels.len()).saturating_add(wrap) <= MAX_DEPTH
}
pub fn skip(&mut self, what: &str) {
@@ -60,6 +63,7 @@ impl Builder {
}
fn add(&mut self, n: Node, layer: bool) {
self.text_run = false;
if self.stack.len() == 1 {
self.top_layers.push(layer);
}
@@ -70,6 +74,9 @@ impl Builder {
/// Close every group opened above `depth`.
pub fn close_to(&mut self, depth: usize) {
if self.stack.len() > depth.max(1) {
self.text_run = false;
}
while self.stack.len() > depth.max(1) {
let Some((g, k)) = self.stack.pop() else { break };
// Empty clipping groups draw nothing.
@@ -83,6 +90,7 @@ impl Builder {
/// Open `g` as the group drawn into from now on; past [`MAX_DEPTH`] the group is dropped
/// (what would have been drawn inside it goes to the open group) and noted as skipped.
fn push_group(&mut self, g: Group, kind: Kind) {
self.text_run = false;
if self.base.saturating_add(self.stack.len()) >= MAX_DEPTH {
self.skip("group nesting limit");
return;
@@ -109,9 +117,71 @@ impl Builder {
self.push_group(g, Kind::Plain);
}
/// Start a bounded logical annotation independently of graphics-state nesting.
pub fn begin_text(&mut self, text: &str) -> bool {
self.text_run = false;
if self.text_labels.len() >= MAX_DEPTH {
self.skip("logical text nesting limit");
return false;
}
self.text_labels.push(format!("Text: {text}"));
true
}
pub fn end_text(&mut self) {
self.text_run = false;
self.text_labels.pop();
}
/// Add a finished node (an image, pattern tiles).
pub fn push(&mut self, n: Node) {
pub fn push(&mut self, mut n: Node) {
// Marked content is metadata, not a transparency boundary. Wrap only the
// painted node, without closing, splitting or reopening any live state group.
// Finished forms may already contain groups: metadata cannot extend the cap.
fn group_depth(n: &Node, at: usize) -> usize {
match n {
Node::Group(g) => {
if at >= MAX_DEPTH {
return MAX_DEPTH;
}
1 + g.children.iter().map(|n| group_depth(n, at + 1)).max().unwrap_or(0)
}
_ => 0,
}
}
let contained = if self.text_labels.is_empty() { 0 } else { group_depth(&n, 0) };
let room = MAX_DEPTH.saturating_sub(self.base.saturating_add(self.stack.len()).saturating_add(contained));
if self.text_labels.len() > room {
self.skip("group nesting limit");
}
// Keep consecutive glyphs of one annotation together only inside the same
// graphics-state container. A knockout parent's children must stay separate.
let coalesce = !self.text_labels.is_empty() && self.text_labels.len() <= room;
if self.text_run
&& coalesce
&& let Some((parent, _)) = self.stack.last_mut()
&& !parent.knockout
{
let mut target = parent.children.last_mut();
for _ in 1..self.text_labels.len() {
target = match target {
Some(Node::Group(g)) => g.children.first_mut(),
_ => None,
};
}
if let Some(Node::Group(g)) = target {
g.children.push(n);
return;
}
}
for label in self.text_labels.iter().take(room).rev() {
let mut g = group(label);
g.isolated = false;
g.children.push(n);
n = Node::Group(g);
}
self.add(n, false);
self.text_run = coalesce;
}
pub fn fill_stroke(&mut self, path: BezPath, transform: Affine, fill: Option<(Paint, f64, FillRule)>, stroke: Option<Stroke>) {
@@ -128,7 +198,7 @@ impl Builder {
None => (None, 1.0, FillRule::NonZero),
};
let s = Shape { name: name.into(), geom: Geom::Path(path), transform, fill: f, fill_opacity: fo, fill_rule: rule, stroke, opacity: 1.0 };
self.add(Node::Shape(s), false);
self.push(Node::Shape(s));
}
/// The finished top-level nodes and their layer flags.
+2 -2
View File
@@ -241,10 +241,10 @@ fn eps_fallback_font(name: &[u8]) -> Option<&'static [u8]> {
|| name.contains("roman")
{
NOTO_SERIF_REGULAR
} else if name.contains("bold") || name.contains("black") || name.contains("heavy") {
INTER_BOLD
} else if name.contains("semibold") || name.contains("demi") {
INTER_SEMIBOLD
} else if name.contains("bold") || name.contains("black") || name.contains("heavy") {
INTER_BOLD
} else if name.contains("italic") || name.contains("oblique") {
INTER_ITALIC
} else {
+29 -16
View File
@@ -209,7 +209,7 @@ pub(crate) struct Interp<'a> {
cur: Option<Point>,
start: Option<Point>,
pending_clip: Option<FillRule>,
marked: Vec<Option<usize>>,
marked: Vec<Marked>,
/// The page box in default user space (for `sh`).
page_box: [f64; 4],
budget: usize,
@@ -237,6 +237,12 @@ enum TextItem {
Adjust(f64),
}
enum Marked {
None,
Layer(usize),
Text,
}
impl<'a> Interp<'a> {
pub fn new(file: &'a File, page_box: [f64; 4]) -> Self {
Interp {
@@ -488,7 +494,7 @@ impl<'a> Interp<'a> {
}
"d1" => self.gs.lock_color = true,
"BI" => self.inline_image(&mut lx, res),
"BMC" => self.marked.push(None),
"BMC" => self.marked.push(Marked::None),
"BDC" => {
let layer = match (args.first().and_then(Obj::name), args.get(1)) {
(Some("OC"), Some(Obj::Name(prop))) => self
@@ -499,30 +505,37 @@ impl<'a> Interp<'a> {
(Some("OC"), Some(Obj::Dict(ocg))) => self.ocg_name(ocg),
_ => None,
};
let actual_text = match (args.first().and_then(Obj::name), args.get(1)) {
(Some("Span"), Some(Obj::Dict(props))) => props.get("ActualText").and_then(|v| match self.file.resolve(v) {
Obj::Str(bytes) => Some(crate::color::text_string(bytes)),
_ => None,
}),
_ => None,
let props = match args.get(1) {
Some(Obj::Name(name)) => self.file.get_dict(res, "Properties").and_then(|p| self.file.get_dict(p, name)),
Some(obj) => self.file.resolve(obj).dict(),
None => None,
};
let actual_text =
(args.first().and_then(Obj::name) == Some("Span")).then_some(props).flatten().and_then(|p| self.file.get(p, "ActualText")).and_then(
|v| match v {
Obj::Str(bytes) => Some(text_string(bytes)),
_ => None,
},
);
match (layer, actual_text) {
(Some(name), _) => {
self.marked.push(Some(self.b.depth()));
self.marked.push(Marked::Layer(self.b.depth()));
self.b.open(&name, true);
}
(None, Some(text)) => {
self.marked.push(Some(self.b.depth()));
self.b.open(&format!("Text: {text}"), false);
let mark = if self.b.begin_text(&text) { Marked::Text } else { Marked::None };
self.marked.push(mark);
}
(None, None) => self.marked.push(None),
(None, None) => self.marked.push(Marked::None),
}
}
"EMC" => {
if let Some(Some(d)) = self.marked.pop() {
self.close_to(d);
"EMC" => match self.marked.pop() {
Some(Marked::Layer(d)) => self.close_to(d),
Some(Marked::Text) => {
self.b.end_text();
}
}
_ => {}
},
_ => {}
}
// Colour operands set by the device-space shorthands.
+69
View File
@@ -1359,3 +1359,72 @@ fn clip_groups_nested_without_end_are_capped() {
assert!(inside[2] > 0.99 && inside[3] > 0.99, "the artwork draws inside the clips: {inside:?}");
assert!(outside[3] < 0.01, "and is clipped: {outside:?}");
}
#[test]
fn actual_text_named_properties_and_fallback_weights() {
let data =
page_pdf("/Span /P BDC 1 0 0 rg 10 10 20 20 re f EMC", "/Properties << /P 10 0 R >>", vec![(10, "<< /ActualText (Logical text) >>".into(), None)]);
assert_eq!(shape_names(&parse(&data).unwrap()), vec!["Text: Logical text"]);
use effectcraft_text::fonts::{INTER_BOLD, INTER_SEMIBOLD};
for name in [b"Inter-Semibold".as_slice(), b"Inter-Demi"] {
assert_eq!(eps_fallback_font(name), Some(INTER_SEMIBOLD));
}
for name in [b"Inter-Bold".as_slice(), b"Inter-Black", b"Inter-Heavy"] {
assert_eq!(eps_fallback_font(name), Some(INTER_BOLD));
}
}
#[test]
fn actual_text_does_not_change_graphics_state_or_compositing() {
let resources = "/ExtGState << /M << /BM /Multiply >> /N << /BM /Normal >> >>";
// Compare every pixel to the same operators without marked content. In particular,
// Multiply and the clip survive EMC, and a later graphics-state change still works.
for (marked, plain) in [
(
"/Span << /ActualText (A) >> BDC /M gs 0 1 1 rg 0 0 60 100 re f EMC 50 0 60 100 re f /N gs 0 0 1 rg 150 0 50 100 re f",
"/M gs 0 1 1 rg 0 0 60 100 re f 50 0 60 100 re f /N gs 0 0 1 rg 150 0 50 100 re f",
),
(
"/Span << /ActualText (A) >> BDC 0 0 100 100 re W n /M gs 0 1 1 rg 0 0 60 100 re f EMC 50 0 150 100 re f",
"0 0 100 100 re W n /M gs 0 1 1 rg 0 0 60 100 re f 50 0 150 100 re f",
),
(
"/Span << /ActualText (A) >> BDC q /M gs 0 1 1 rg 0 0 60 100 re f Q EMC 0 0 1 rg 100 0 100 100 re f",
"q /M gs 0 1 1 rg 0 0 60 100 re f Q 0 0 1 rg 100 0 100 100 re f",
),
] {
let draw = |ops| render(&parse(&page_pdf(&format!("1 1 0 rg 0 0 200 100 re f {ops}"), resources, vec![])).unwrap());
let (a, b) = (draw(marked), draw(plain));
for y in 0..100 {
for x in 0..200 {
assert_eq!(a.get(x, y), b.get(x, y), "pixel {x},{y}");
}
}
}
}
#[test]
fn logical_text_cannot_extend_finished_node_depth_limit() {
use crate::build::Builder;
use effectcraft_svg::Group;
let mut b = Builder::new();
assert!(b.begin_text("label"));
assert!(!b.nested(0).has_room(254));
let mut node = Node::Group(Group::new("leaf"));
for _ in 1..255 {
let mut parent = Group::new("nested");
parent.children.push(node);
node = Node::Group(parent);
}
b.push(node);
b.end_text();
let (nodes, _, skipped) = b.finish();
assert!(skipped.iter().any(|s| s == "group nesting limit"));
let mut current = nodes.first();
let mut depth = 1;
while let Some(Node::Group(g)) = current {
depth += 1;
current = g.children.first();
}
assert_eq!(depth, 256);
}
+37
View File
@@ -151,3 +151,40 @@ fn vertical_metrics_w2_and_dw2() {
let dw2 = doc("/DW2 [780 -1000]");
assert!(((base.1 - dw2.1) - 2).abs() <= 1, "vy 780 → 2 pt higher: {base:?} {dw2:?}");
}
#[test]
fn actual_text_does_not_combine_knockout_children() {
let plain = "1 0 0 rg 0 0 100 100 re f /H gs 0 0 1 rg 50 0 100 100 re f";
let marked = format!("/Span << /ActualText (Label) >> BDC {plain} EMC");
let a = render(&group_page("/Fm Do", "", "/Group << /S /Transparency /I true /K true >>", plain));
let b = render(&group_page("/Fm Do", "", "/Group << /S /Transparency /I true /K true >>", &marked));
for y in 0..100 {
for x in 0..200 {
assert!(near(a.get(x, y), b.get(x, y)), "pixel {x},{y}");
}
}
}
#[test]
fn actual_text_end_keeps_soft_mask_and_overlapping_paints() {
let plain = "/GS1 gs 1 0 0 rg 0 0 100 100 re f 0 0 1 rg 50 0 100 100 re f";
let marked = "/Span << /ActualText (Label) >> BDC /GS1 gs 1 0 0 rg 0 0 100 100 re f EMC 0 0 1 rg 50 0 100 100 re f";
let draw = |ops| {
let bytes = page_pdf(
ops,
"/ExtGState << /GS1 << /SMask << /S /Luminosity /G 10 0 R >> >> >>",
vec![(
10,
"<< /Type /XObject /Subtype /Form /BBox [0 0 200 100] /Group << /S /Transparency /CS /DeviceGray >> >>".into(),
Some(b"0.5 g 0 0 200 100 re f".to_vec()),
)],
);
render(&parse(&bytes).unwrap())
};
let (a, b) = (draw(plain), draw(marked));
for y in 0..100 {
for x in 0..200 {
assert!(near(a.get(x, y), b.get(x, y)), "pixel {x},{y}");
}
}
}