PDF import: a TJ whose kerning starts a new line comes in filled and stroked (#8543)

The reader fills every glyph of a text-showing operator, then strokes
them. When a TJ's kerning started a new line part way through, the
first line was finished before the stroke pass came back to it, so its
strokes found no filled glyph and came in as stroke-only type over
fill-only type.

A line a glyph doesn't fit is now parked while a stroke may still be
drawn over it, and a stroke-only glyph is matched against the open line
and then the parked lines, newest first. Parked lines are finished
oldest first before the open line, so drawing order is kept, and at
most 64 are parked.
This commit is contained in:
HassanKhan
2026-11-18 12:23:10 +05:00
parent 50c7208fe3
commit 851c7cb372
8 changed files with 241 additions and 34 deletions
+13 -3
View File
@@ -63,9 +63,19 @@ impl Builder<'_> {
pub(super) fn actual_glyph(&mut self, o: &craft_pdf::interpret::font::OutlineGlyph, m: Affine, at: Placement, look: Look, opacity: f32) -> bool {
let key = o.font_cache_key();
self.flush_glyphs();
// A fill and stroke callback for the same glyph consumes its text only once.
// A fill and stroke callback for the same glyph consumes its text only once, on a line
// the operator's kerning finished too.
let stroking = look.fill.is_none() && look.stroke.is_some();
if let Some(stroke) = &look.stroke
&& stroking
&& self.stroke_parked(|line| line.has_actual_fill(key, at))
&& let Some((line, _)) = self.parked.first_mut()
&& line.stroke_actual(key, at, stroke.clone(), look.overprint_stroke)
{
return true;
}
if let (Some(stroke), Some(line)) = (&look.stroke, &mut self.text)
&& look.fill.is_none()
&& stroking
&& line.stroke_actual(key, at, stroke.clone(), look.overprint_stroke)
{
return true;
@@ -87,7 +97,7 @@ impl Builder<'_> {
None => line.push_content(&look, at, opacity, advance, content),
};
if !self.text.as_mut().is_some_and(place) {
self.flush_text();
self.park_text(!stroking);
let mut line = TextLine::new(at, opacity);
if !place(&mut line) {
self.actual.pending = pending;
+109 -11
View File
@@ -12,6 +12,10 @@ use super::{
Upright, Walked, clipped, contains, fold_stop_opacity, function_paint, gradient_shape, is_rectangle, luminance, mask_spec, shading_gradient,
};
/// The most lines of type kept for a text-showing operator's stroke pass ([`Builder::park_text`]):
/// beyond them the oldest is finished, and strokes over its glyphs come in as type of their own.
const MAX_PARKED: usize = 64;
fn is_colour_face(face: &vectorcraft_text::FontFace) -> bool {
use skrifa::Tag;
use skrifa::raw::TableProvider;
@@ -37,6 +41,7 @@ impl<'p> Builder<'p> {
type3_run: None,
text: None,
text_glyphs: vec![],
parked: vec![],
text_as,
actual: Default::default(),
images: HashMap::new(),
@@ -119,6 +124,7 @@ impl<'p> Builder<'p> {
self.type3_run = None;
self.text = None;
self.text_glyphs.clear();
self.parked.clear();
self.mask = None;
self.masked.clear();
self.marked.clear();
@@ -450,11 +456,73 @@ impl<'p> Builder<'p> {
}
}
/// Finish the open line of type. `true`: it was kept as outlines instead ([`reshaped`]), which
/// are left open as the glyph run for an outline drawn next to join.
/// Finish the open line of type, after the lines parked before it ([`Self::park_text`]).
/// `true`: the open line was kept as outlines instead ([`reshaped`]), which are left open as
/// the glyph run for an outline drawn next to join.
pub(super) fn end_text(&mut self) -> bool {
self.release_parked(usize::MAX);
let glyphs = std::mem::take(&mut self.text_glyphs);
let Some(mut line) = self.text.take() else { return false };
let Some(line) = self.text.take() else { return false };
self.end_line(line, glyphs)
}
/// Finish the first `n` parked lines ([`Self::park_text`]), in the order they were drawn.
pub(super) fn release_parked(&mut self, n: usize) {
let n = n.min(self.parked.len());
if n == 0 {
return;
}
let lines: Vec<_> = self.parked.drain(..n).collect();
for (line, glyphs) in lines {
if self.end_line(line, glyphs) {
self.flush_glyphs();
}
}
}
/// The open line ends where glyph drawn next starts another. The reader fills every glyph of
/// a text-showing operator before it strokes them (fill and stroke rendering): a line that a
/// stroke may still be drawn over is parked instead of finished, so that the operator's
/// stroke pass still finds the glyphs it filled when its kerning started a new line part way
/// through (#8543). Any other line, or with `park` false, is finished with the lines parked
/// before it.
///
/// Parked lines are finished, oldest first, when the stroke pass goes past them (a stroke is
/// drawn over a later line, the open one, or none of them: [`Self::stroke_parked`]), when
/// anything else ends the open line ([`Self::end_text`]), and beyond [`MAX_PARKED`] lines.
pub(super) fn park_text(&mut self, park: bool) {
match self.text.take() {
Some(line) if park && line.awaits_stroke() => {
let glyphs = std::mem::take(&mut self.text_glyphs);
self.parked.push((line, glyphs));
self.release_parked(self.parked.len().saturating_sub(MAX_PARKED));
}
line => {
self.text = line;
self.flush_text();
}
}
}
/// Whether a stroke goes over a glyph of a parked line ([`Self::park_text`]), which `takes`
/// tells of each line (a glyph it filled that the stroke is drawn over). The open line comes
/// first, then the parked lines from the last parked back: the same glyph filled at the same
/// place twice is stroked where it was filled last, by the operator that strokes it. `true`:
/// a parked line takes it, the stroke pass is on it, and the lines before it are finished,
/// so it is the first. `false`: the open line takes it or none does, so the stroke pass is
/// past them all, and they are finished.
pub(super) fn stroke_parked(&mut self, takes: impl Fn(&TextLine) -> bool) -> bool {
if self.parked.is_empty() {
return false;
}
let found = if self.text.as_ref().is_some_and(&takes) { None } else { self.parked.iter().rposition(|(line, _)| takes(line)) };
self.release_parked(found.unwrap_or(usize::MAX));
found.is_some()
}
/// Finish `line` of type, whose `glyphs` are its outlines ([`Self::keep_glyph`]). `true`:
/// it was kept as them ([`Self::end_text`]).
fn end_line(&mut self, mut line: TextLine, glyphs: Vec<GlyphRun>) -> bool {
let held = std::mem::take(&mut line.held);
// Type the file names itself (ActualText) is in reading order as it stands.
let checked = !glyphs.is_empty() && line.mapped() && !line.has_type3;
@@ -880,13 +948,9 @@ impl<'p> Builder<'p> {
scale: f64,
overprint: bool,
) {
let Some((paint, stroke)) = drawn else { return };
let mut path = o.outline();
if path.elements().is_empty() {
return;
if let Some(g) = glyph_run(o, m, drawn, opacity, scale, overprint) {
self.text_glyphs.push(g);
}
path.apply_affine(m);
self.text_glyphs.push(GlyphRun { path, paint, opacity, stroke, scale, overprint });
}
fn type3_font_name(&mut self, key: u128) -> FontInfo {
@@ -1151,9 +1215,24 @@ impl<'p> Builder<'p> {
None => line.push(&look, at, opacity, advance, &text),
};
self.flush_glyphs();
let stroking = look.fill.is_none() && look.stroke.is_some();
// A stroke over a glyph filled on a line the same operator's kerning finished.
if let Some(s) = &look.stroke
&& stroking
&& self.stroke_parked(|line| line.has_filled(key, at, opacity, &text))
&& let Some((line, glyphs)) = self.parked.first_mut()
{
line.stroke_filled(key, at, opacity, &text, s.clone(), overprint);
if top.is_none()
&& let Some(g) = glyph_run(o, m, drawn, opacity, scale, overprint)
{
glyphs.push(g);
}
return true;
}
// A stroke over the glyph just filled (fill and stroke rendering).
if let (Some(s), Some(line)) = (&look.stroke, &mut self.text)
&& look.fill.is_none()
&& stroking
&& line.stroke_filled(key, at, opacity, &text, s.clone(), overprint)
{
// Upright glyphs aren't kept as outlines (nor, below, are those filled only): a
@@ -1164,7 +1243,7 @@ impl<'p> Builder<'p> {
return true;
}
if !self.text.as_mut().is_some_and(place) {
self.flush_text();
self.park_text(!stroking);
let mut line = TextLine::new(at, opacity);
place(&mut line);
self.text = Some(line);
@@ -1184,6 +1263,25 @@ impl<'p> Builder<'p> {
}
}
/// Glyph `o` placed by `m` and drawn with `drawn` as the outline it is kept as
/// ([`Builder::keep_glyph`]). Nothing for a glyph that shows nothing.
fn glyph_run(
o: &craft_pdf::interpret::font::OutlineGlyph,
m: Affine,
drawn: Option<(Paint, Option<StrokeProps>)>,
opacity: f32,
scale: f64,
overprint: bool,
) -> Option<GlyphRun> {
let (paint, stroke) = drawn?;
let mut path = o.outline();
if path.elements().is_empty() {
return None;
}
path.apply_affine(m);
Some(GlyphRun { path, paint, opacity, stroke, scale, overprint })
}
/// The characters of one glyph in the order they are drawn: a PDF names a ligature's characters
/// in logical order (lam then alef for لا), while a horizontal line of type is gathered glyph by
/// glyph in visual order and only then put back in logical order. Right-to-left characters are
+5
View File
@@ -94,6 +94,11 @@ pub(super) struct Builder<'p> {
/// kept as: what the line becomes when its type wouldn't draw as the file does
/// ([`super::reshaped`]).
pub(super) text_glyphs: Vec<GlyphRun>,
/// Lines of type a text-showing operator's fill pass finished (a `TJ`'s kerning starts a new
/// line part way through) that its stroke pass may still go over, oldest first, each with
/// its [`text_glyphs`](Self::text_glyphs): written before the open line, in this order
/// ([`Builder::park_text`]).
pub(super) parked: Vec<(TextLine, Vec<GlyphRun>)>,
pub(super) text_as: TextAs,
pub(super) actual: super::actual_text::ActualText,
pub(super) images: HashMap<String, ImageBlob>,
+37 -9
View File
@@ -576,6 +576,12 @@ impl TextLine {
true
}
/// Whether a glyph of an ActualText span was filled in `font` at `at`, not stroked yet
/// ([`stroke_actual`](Self::stroke_actual)).
pub fn has_actual_fill(&self, font: u128, at: Placement) -> bool {
self.actual_fills.contains_key(&(font, at.origin.x.to_bits(), at.origin.y.to_bits()))
}
/// Has the baseline turned (more than about 3° from the first glyph to the last)?
fn curved(&self) -> bool {
self.last_dir.dot(self.at.dir) < 0.9986
@@ -625,15 +631,7 @@ impl TextLine {
// A stroke at another opacity than the fill's (`CA` and `ca` differ), or over a
// translucent fill, is type of its own.
let opaque = opacity >= 0.999 && self.opacity >= 0.999;
let rest = if opaque { self.filled.get(self.stroked..) } else { None };
let found = rest.and_then(|rest| {
rest.iter().position(|g| {
g.font == font
&& g.at.same_as(&at)
&& self.runs.get(g.run).and_then(|(.., t)| t.get(g.start..g.start.saturating_add(g.len))) == Some(text)
})
});
let Some(index) = found.map(|i| self.stroked.saturating_add(i)) else {
let Some(index) = self.filled_index(font, at, opacity, text) else {
// Stroked text of its own (stroke rendering): no later stroke goes back over the
// glyphs filled before it, so no stroke looks through them again.
self.stroked = self.filled.len();
@@ -661,6 +659,36 @@ impl TextLine {
true
}
/// The glyph a stroke over glyph `text` drawn at `at` in `font` at `opacity` is drawn over
/// ([`stroke_filled`](Self::stroke_filled)): the next one filled so and not stroked yet, as
/// an index into [`filled`](Self::filled). `None` for a translucent fill or stroke.
fn filled_index(&self, font: u128, at: Placement, opacity: f32, text: &str) -> Option<usize> {
if opacity < 0.999 || self.opacity < 0.999 {
return None;
}
let i = self.filled.get(self.stroked..)?.iter().position(|g| {
g.font == font
&& g.at.same_as(&at)
&& self.runs.get(g.run).and_then(|(.., t)| t.get(g.start..g.start.saturating_add(g.len))) == Some(text)
})?;
Some(self.stroked.saturating_add(i))
}
/// Whether a stroke over glyph `text` drawn at `at` in `font` at `opacity` is drawn over a
/// glyph of this line filled so ([`stroke_filled`](Self::stroke_filled) then strokes it).
/// Unlike `stroke_filled`, which then gives the stroke the line's last glyph or ends what
/// later strokes may match, it changes nothing.
pub fn has_filled(&self, font: u128, at: Placement, opacity: f32, text: &str) -> bool {
self.filled_index(font, at, opacity, text).is_some()
}
/// Whether a stroke drawn later may still be drawn over a glyph of the line (fill and stroke
/// rendering): an opaque glyph filled and not stroked yet, or a filled glyph of an
/// ActualText span ([`stroke_actual`](Self::stroke_actual)).
pub fn awaits_stroke(&self) -> bool {
(self.opacity >= 0.999 && self.stroked < self.filled.len()) || !self.actual_fills.is_empty()
}
/// Restyle the glyphs gathered for a stroke ([`stroke_filled`](Self::stroke_filled)): their
/// text becomes a run of its own with the stroke, unless the run is stroked so already, and the
/// text before and after it in the run keeps its stroke. Text that comes right after a run
+63
View File
@@ -346,3 +346,66 @@ fn glyphs_filled_and_stroked_one_by_one_stay_one_run() {
assert_eq!(type_runs(content), [vec![("ABC".to_string(), true, true)]], "{content}");
}
}
/// Fill and stroke rendering of a `TJ` whose kerning starts a new line part way through: the
/// reader fills every glyph of the operator before it strokes them, and each part comes in as
/// type filled and stroked, in the order drawn, not as each part filled and then each part
/// stroked over it (#8543). So too a `TJ` that jumps back to start a line before it, one whose
/// kerning starts two new lines, and one in a span with replacement text (`ActualText`); small
/// kerning keeps one line as before.
#[test]
fn a_tj_whose_kerning_starts_a_new_line_is_filled_and_stroked() {
// Each type object as its text, and whether all of it is filled and all of it stroked.
let objects = |content: &str| -> Vec<(String, bool, bool)> {
type_runs(content)
.into_iter()
.map(|runs| (runs.iter().map(|r| r.0.as_str()).collect(), runs.iter().all(|r| r.1), runs.iter().all(|r| r.2)))
.collect()
};
let both = |text: &str| (text.to_string(), true, true);
for mode in ["2", "6"] {
let cases = [
("/F1 48 Tf 20 80 Td [(AB) -3500 (CD)] TJ", vec![both("AB"), both("CD")]),
("/F1 24 Tf 20 80 Td [(AB) -3500 (CD) -3500 (EF)] TJ", vec![both("AB"), both("CD"), both("EF")]),
("/F1 24 Tf 200 80 Td [(AB) 6000 (CD)] TJ", vec![both("AB"), both("CD")]),
("/F1 48 Tf 20 80 Td [(AB) -100 (CD)] TJ", vec![both("ABCD")]),
// In a span with replacement text, which places all of its text with the first glyph.
("/F1 48 Tf 20 80 Td /Span << /ActualText (ABCD) >> BDC [(AB) -3500 (CD)] TJ EMC", vec![both("ABCD")]),
];
for (show, want) in cases {
let content = format!("BT {mode} Tr {show} 0 Tr ET");
assert_eq!(objects(&content), want, "{content}: {:?}", type_runs(&content));
}
}
}
/// Stroke rendering (modes 1 and 5) of a `TJ` whose kerning starts a new line stays stroke only,
/// one type object per line (#8543).
#[test]
fn a_stroked_tj_whose_kerning_starts_a_new_line_stays_stroke_only() {
for mode in ["1", "5"] {
let content = format!("BT {mode} Tr /F1 48 Tf 20 80 Td [(AB) -3500 (CD)] TJ 0 Tr ET");
let want = [vec![("AB".to_string(), false, true)], vec![("CD".to_string(), false, true)]];
assert_eq!(type_runs(&content), want, "{content}");
}
}
/// Translucent type filled and stroked by a `TJ` whose kerning starts a new line stays a filled
/// object and a stroked one for each part, in the order the file draws them (#8015, #8543).
#[test]
fn a_translucent_tj_whose_kerning_starts_a_new_line_stays_fill_and_stroke_apart() {
use vectorcraft_testkit::pdf::{PdfPage, pdf};
let resources = "/Font << /F1 << /Type /Font /Subtype /Type1 /BaseFont /Helvetica >> >> /ExtGState << /G << /ca 0.5 /CA 0.5 >> >>";
let content = "/G gs 0 0 0 RG 1 1 0.8 rg 3 w BT 2 Tr /F1 48 Tf 20 80 Td [(AB) -3500 (CD)] TJ 0 Tr ET";
let bytes = pdf(&[PdfPage { resources: resources.into(), ..PdfPage::new(300.0, 200.0, content) }], None);
let d = import(&bytes).unwrap();
let mut types = vec![];
d.walk(|n| {
if let NodeKind::Text(t) = &n.kind {
let st = t.first_style();
types.push((t.plain_text(), n.opacity < 1.0, !st.fill.is_none(), !st.stroke.is_none()));
}
});
let part = |text: &str, fill: bool| (text.to_string(), true, fill, !fill);
assert_eq!(types, [part("AB", true), part("CD", true), part("AB", false), part("CD", false)], "{content}");
}
File diff suppressed because one or more lines are too long
+3 -2
View File
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long