Skip to main content

docling_pdf/
textparse.rs

1//! Pure-Rust PDF text extraction (replacing pdfium's glyph layer).
2//!
3//! pdfium reports *rendered* glyph boxes, which diverge from docling's
4//! `docling-parse` C++ parser at exactly the points that drive conformance:
5//! generated spaces get a zero-width box, combining diacritics get a real-width
6//! box, and ligature/fraction glyphs land at different x. This module instead
7//! reconstructs each glyph's box from the **font's own advance widths** and the
8//! PDF text/graphics matrices — the same information docling-parse uses — so a
9//! space is as wide as the font says and a combining mark has zero advance.
10//!
11//! The output is the same [`Glyph`] stream pdfium produces (native PDF
12//! coordinates, y-up), fed straight into the existing docling-parse line
13//! sanitizer ([`crate::dp_lines`]). Only the digital text layer is handled here;
14//! pages without one still fall back to OCR upstream.
15
16use std::collections::{HashMap, HashSet};
17use std::sync::Arc;
18
19use lopdf::{Dictionary, Document, Object};
20
21use crate::pdfium_backend::Glyph;
22use crate::tounicode::parse_tounicode;
23
24/// Per-document caches for the content-stream interpreter. Fonts are indirect
25/// objects shared by many pages, but were fully re-parsed — ToUnicode CMap
26/// decompression + tokenization, embedded Type1 program scan, width tables —
27/// for **every page and every Form XObject invocation**; decoded form content
28/// streams were likewise re-inflated on every `Do`. Cached per document,
29/// keyed by the referenced object id (fonts also by resource name — the
30/// `/Font` entry a page binds the object to). Inline (non-reference) dicts
31/// are rare and stay uncached.
32#[derive(Default)]
33struct DocCaches {
34    fonts: HashMap<(lopdf::ObjectId, Vec<u8>), Arc<Font>>,
35    forms: HashMap<lopdf::ObjectId, Arc<lopdf::content::Content>>,
36    /// Forms decoded once and not (yet) cached (#994). A form enters
37    /// [`Self::forms`] on its *second* sighting: a shared header/footer form
38    /// is decoded twice and then hits the cache on every later page, while
39    /// a generator's one-form-per-page body (each page's chart in its own
40    /// form, used once) is dropped with its page instead of every decoded
41    /// `Content` — many times its stream's size — living until the document
42    /// ends. Caching on first use made peak RSS grow ~45 MB per page on such
43    /// files (7 GiB at 60 pages of the issue's repro, flat ~0.6 GiB now).
44    /// Only ids are kept here, so the set itself stays tiny.
45    forms_seen: HashSet<lopdf::ObjectId>,
46}
47
48/// A 2×3 affine matrix `[a b c d e f]`: maps `(x,y)` → `(a·x+c·y+e, b·x+d·y+f)`.
49#[derive(Clone, Copy)]
50struct Mat {
51    a: f64,
52    b: f64,
53    c: f64,
54    d: f64,
55    e: f64,
56    f: f64,
57}
58
59impl Mat {
60    const ID: Mat = Mat {
61        a: 1.0,
62        b: 0.0,
63        c: 0.0,
64        d: 1.0,
65        e: 0.0,
66        f: 0.0,
67    };
68
69    /// `self ∘ m`: the matrix that applies `self` first, then `m`.
70    fn then(self, m: Mat) -> Mat {
71        Mat {
72            a: self.a * m.a + self.b * m.c,
73            b: self.a * m.b + self.b * m.d,
74            c: self.c * m.a + self.d * m.c,
75            d: self.c * m.b + self.d * m.d,
76            e: self.e * m.a + self.f * m.c + m.e,
77            f: self.e * m.b + self.f * m.d + m.f,
78        }
79    }
80
81    fn apply(self, x: f64, y: f64) -> (f64, f64) {
82        (
83            self.a * x + self.c * y + self.e,
84            self.b * x + self.d * y + self.f,
85        )
86    }
87}
88
89/// A parsed font: how to turn raw string bytes into (unicode, advance) pairs.
90struct Font {
91    /// 2-byte codes (Type0 / Identity-H) vs 1-byte (simple fonts).
92    two_byte: bool,
93    /// code → Unicode string (from ToUnicode; may be multi-char, e.g. ligatures).
94    to_unicode: HashMap<u32, String>,
95    /// For codes ToUnicode lacks (ISO 32000-1, 9.10.2).
96    cid_fallback: CidFallback,
97    /// code → glyph advance, in 1000-unit glyph space.
98    widths: HashMap<u32, f64>,
99    default_width: f64,
100    /// 1-byte fallback decoding when ToUnicode lacks a code (WinAnsi-ish).
101    simple_encoding: Option<HashMap<u8, char>>,
102    /// code → raw `/Differences` glyph name, for placeholder names (`g115`,
103    /// `SM590000`) that have no Unicode mapping; they override the base
104    /// encoding (see [`unknown_name_text`]).
105    fallback_names: HashMap<u8, String>,
106    /// The unmapped codes whose embedded glyph paints nothing — semantic
107    /// spaces (docling-parse 7.24's blank glyph programs: the redp5110
108    /// list's `/g3`). Every other unmapped code reads U+FFFD.
109    blank_codes: HashSet<u32>,
110    /// code → char from the embedded Type1 font program's own `/Encoding` vector,
111    /// used only as a last resort for glyphs the base encoding leaves unmapped
112    /// (standard TeX math fonts: `λ`, `≤`, …).
113    program_encoding: HashMap<u8, char>,
114    /// A symbolic simple font without a declared base encoding: the text of
115    /// each code its embedded program's builtin encoding resolves
116    /// (docling-parse 7.25, #1113 — 2203.01017's `Dingbats` check marks are
117    /// `a19` / `a23`, `✓` / `✗`, not the `3` / `7` the Latin tables read).
118    /// It outranks every encoding table but a `/Differences` entry
119    /// ([`Font::diff_codes`]); empty for every other font and in a build
120    /// without the renderer.
121    builtin: HashMap<u8, String>,
122    /// The codes `/Differences` names.
123    diff_codes: HashSet<u8>,
124    ascent: f64,
125    descent: f64,
126    /// code → its embedded glyph's ink extent `(y_min, y_max)` in 1000-unit
127    /// em, for a font whose descriptor metrics docling-parse rejects
128    /// ([`font_ascent_descent`]'s third value): docling-parse 7.24 boxes such
129    /// a font's glyphs by their outline's control box, so a glyph drawn
130    /// under the baseline — 2305.03393's `_` in `PMC5406406_003_01.png` —
131    /// is a cell of its own, not part of the word. Empty for every other
132    /// font, a glyph with no ink, and a build without the renderer.
133    ink_y: HashMap<u32, (f64, f64)>,
134    hash: u64,
135    /// Whether the font's docling-parse name marks a math face
136    /// ([`is_math_font_name`]) — for the word contraction's local
137    /// attachments (#921).
138    math: bool,
139    /// Weight and slant read from the `/BaseFont` name (the heading
140    /// hierarchy's style signal, #302).
141    style: crate::font_style::FontStyle,
142}
143
144impl Font {
145    /// The text of `code` and its advance; the flag marks a blank unmapped
146    /// glyph, whose box has no height.
147    ///
148    /// A code no source maps to Unicode is visibly painted but carries no
149    /// text: docling-parse 7.24 emits U+FFFD for it, and docling turns a NUL
150    /// into U+FFFD too (docling#5070), so the loss stays visible and counted
151    /// by the text-quality check instead of silently dropping the glyph
152    /// (`mL⁻¹` reading `mL1`). A glyph whose embedded program paints nothing
153    /// is a space — a word boundary — instead.
154    fn decode_code(&self, code: u32) -> (Option<String>, f64, bool) {
155        let w = self
156            .widths
157            .get(&code)
158            .copied()
159            .unwrap_or(self.default_width);
160        if let Some(s) = self.to_unicode.get(&code) {
161            return (Some(decompose_ligatures(s)), w, false);
162        }
163        let unmapped = |font: &Font| {
164            let blank = font.blank_codes.contains(&code);
165            (
166                Some(if blank { " " } else { "\u{FFFD}" }.to_string()),
167                w,
168                blank,
169            )
170        };
171        if !self.two_byte {
172            // A placeholder `/Differences` name (no Unicode) overrides the
173            // base encoding. docling-parse 7.24 reads a bare glyph index
174            // (`g115`, `gid00043`) as unmapped and any other unknown name as
175            // its text (`SM590000`, the redp5110 bullets).
176            if let Some(name) = self.fallback_names.get(&(code as u8)) {
177                return match unknown_name_text(name) {
178                    Some(text) => (Some(text), w, false),
179                    None => unmapped(self),
180                };
181            }
182            // docling-parse 7.25's `get_correct_character`: after
183            // `/Differences` and `/ToUnicode`, a symbolic font's builtin
184            // encoding — "the producer's own statement of what each code
185            // draws" — before any base-font or Latin table.
186            if !self.diff_codes.contains(&(code as u8)) {
187                if let Some(text) = self.builtin.get(&(code as u8)) {
188                    return (Some(decompose_ligatures(text)), w, false);
189                }
190            }
191            if let Some(enc) = &self.simple_encoding {
192                if let Some(&ch) = enc.get(&(code as u8)) {
193                    return (Some(decompose_ligatures(&ch.to_string())), w, false);
194                }
195            }
196            // Last resort: the embedded Type1 font program's own `/Encoding`
197            // vector (`dup N /glyphname put`). Standard TeX math fonts (CMMI, CMSY,
198            // …) ship no PDF `/Encoding` and no ToUnicode, so a glyph like `λ`
199            // (CMMI code 21 → `/lambda`) or `≤` (CMSY code 20 → `/lessequal`) has
200            // no other mapping and would otherwise be silently dropped. docling
201            // recovers these from the same font program. This only fills codes the
202            // base encoding left unmapped, so it never changes an existing decode.
203            if let Some(&ch) = self.program_encoding.get(&(code as u8)) {
204                return (Some(decompose_ligatures(&ch.to_string())), w, false);
205            }
206        } else {
207            match self.cid_fallback {
208                CidFallback::None => {}
209                CidFallback::UnicodeCodes { .. } => {
210                    if let Some(ch) = unicode_cmap_char(code).filter(|c| !c.is_control()) {
211                        return (Some(ch.to_string()), w, false);
212                    }
213                }
214                CidFallback::Collection(table) => {
215                    if let Some(s) = collection_text(table, code) {
216                        return (Some(decompose_ligatures(&s)), w, false);
217                    }
218                }
219            }
220        }
221        unmapped(self)
222    }
223}
224
225/// Spell out Latin presentation-form ligatures (`fi`→`fi`, `ffi`→`ffi`, …) the way
226/// docling does, so `configuration`/`difficult` don't keep the ligature glyph.
227/// The chars share the ligature's box, so the line sanitizer recomposes them.
228fn decompose_ligatures(s: &str) -> String {
229    if !s.chars().any(|c| ('\u{FB00}'..='\u{FB06}').contains(&c)) {
230        return s.to_string();
231    }
232    s.chars()
233        .map(|c| {
234            match c {
235                '\u{FB00}' => "ff",
236                '\u{FB01}' => "fi",
237                '\u{FB02}' => "fl",
238                '\u{FB03}' => "ffi",
239                '\u{FB04}' => "ffl",
240                // U+FB05 is LATIN SMALL LIGATURE LONG S T (`ſt`): `st`, as
241                // docling's ligature map and Unicode's decomposition (#1001).
242                '\u{FB05}' => "st",
243                '\u{FB06}' => "st",
244                _ => return c.to_string(),
245            }
246            .to_string()
247        })
248        .collect()
249}
250
251fn hash_name(name: &[u8]) -> u64 {
252    use std::hash::{Hash, Hasher};
253    let mut h = std::collections::hash_map::DefaultHasher::new();
254    name.hash(&mut h);
255    h.finish()
256}
257
258/// Resolve a possibly-indirect object to a dictionary.
259fn as_dict<'a>(doc: &'a Document, obj: &'a Object) -> Option<&'a Dictionary> {
260    match obj {
261        Object::Dictionary(d) => Some(d),
262        Object::Reference(id) => doc.get_object(*id).ok().and_then(|o| o.as_dict().ok()),
263        _ => None,
264    }
265}
266
267fn deref<'a>(doc: &'a Document, obj: &'a Object) -> Option<&'a Object> {
268    match obj {
269        Object::Reference(id) => doc.get_object(*id).ok(),
270        other => Some(other),
271    }
272}
273
274/// The font identity the line sanitizer's `enforce_same_font` compares —
275/// docling-parse's `page_font::init_font_name`: `/FontDescriptor/FontName`
276/// (the descendant CIDFont's for a Type0), else `/Name`, else `/BaseFont`
277/// (its `base_font`), else the literal `"null"`. The resource key (`/F1`,
278/// `/F2`) is deliberately **not** part of it: a producer that references one
279/// face twice — the same Helvetica under two keys, one re-encoded so a code
280/// maps to the `fi` glyph — draws one word across the two resources, and
281/// docling-parse reads both as the same font. Keyed by resource name (as
282/// this port was until #728) the `fi` ligature, which bridges fonts, glued
283/// itself to the preceding run while the font barrier then cut it off from
284/// its own word (`fi nancial`); docling's `financial` needs the two
285/// resources to compare equal.
286/// docling-parse's `has_math_positioning_semantics`, the font-name half: a
287/// TeX math or symbol face (`cmmi`, `cmsy`, `cmex`, `cmr`, `cmbx`, `msam`,
288/// `msbm`) or any name saying `math`, `symbol` or `mtextra`.
289fn is_math_font_name(name: &[u8]) -> bool {
290    let lower = name.to_ascii_lowercase();
291    [
292        "cmmi", "cmsy", "cmex", "cmr", "cmbx", "msam", "msbm", "math", "symbol", "mtextra",
293    ]
294    .iter()
295    .any(|t| lower.windows(t.len()).any(|w| w == t.as_bytes()))
296}
297
298fn sanitizer_font_name(doc: &Document, fdict: &Dictionary, two_byte: bool) -> Vec<u8> {
299    let descriptor_font_name = |owner: &Dictionary| {
300        owner
301            .get(b"FontDescriptor")
302            .ok()
303            .and_then(|o| as_dict(doc, o))
304            .and_then(|fd| fd.get(b"FontName").ok())
305            .and_then(|o| deref(doc, o))
306            .and_then(|o| o.as_name().ok().map(<[u8]>::to_vec))
307    };
308    if let Some(n) = descriptor_font_name(fdict) {
309        return n;
310    }
311    if two_byte {
312        let descendant = fdict
313            .get(b"DescendantFonts")
314            .ok()
315            .and_then(|o| deref(doc, o))
316            .and_then(|o| match o {
317                Object::Array(a) => a.first(),
318                _ => None,
319            })
320            .and_then(|o| as_dict(doc, o));
321        if let Some(n) = descendant.and_then(descriptor_font_name) {
322            return n;
323        }
324    }
325    if let Some(n) = fdict
326        .get(b"Name")
327        .ok()
328        .and_then(|o| deref(doc, o))
329        .and_then(|o| o.as_name().ok())
330    {
331        return n.to_vec();
332    }
333    // docling-parse's `base_font` keeps the subset prefix (`ABCDEF+Helvetica`):
334    // two subsets of one face are two fonts there, and so here.
335    if let Some(n) = fdict.get(b"BaseFont").ok().and_then(|o| o.as_name().ok()) {
336        return n.to_vec();
337    }
338    b"null".to_vec()
339}
340
341/// Parse one font dictionary into a [`Font`].
342fn parse_font(doc: &Document, name: &[u8], fdict: &Dictionary) -> Font {
343    let subtype: &[u8] = fdict
344        .get(b"Subtype")
345        .ok()
346        .and_then(|o| o.as_name().ok())
347        .unwrap_or(&[]);
348    let two_byte = subtype == b"Type0".as_slice();
349
350    let mut to_unicode = fdict
351        .get(b"ToUnicode")
352        .ok()
353        .and_then(|o| deref(doc, o))
354        .and_then(|o| o.as_stream().ok())
355        .and_then(|s| s.decompressed_content().ok())
356        .map(|data| parse_tounicode(&data))
357        .unwrap_or_default();
358    if !two_byte {
359        if let Some(diffs) = differences_array(doc, fdict) {
360            reconcile_stale_tounicode(&mut to_unicode, &diffs);
361        }
362    }
363    let sanitizer_name = sanitizer_font_name(doc, fdict, two_byte);
364    // Symbol / ZapfDingbats mapped into the private-use "symbol charset"
365    // (`U+F000` + byte): docling-parse 7.25 reads the glyph's text through
366    // the face's own encoding instead (docling-parse#431, #1113 — redp5110's
367    // `U+F0AE` is `→`, a Word bullet `U+F0B7` is `•`).
368    let raw_base = fdict.get(b"BaseFont").ok().and_then(|o| o.as_name().ok());
369    let names: Vec<&[u8]> = std::iter::once(sanitizer_name.as_slice())
370        .chain(raw_base)
371        .collect();
372    if let Some(face) = crate::symbol_fonts::symbol_face(&names) {
373        for value in to_unicode.values_mut() {
374            if let Some(ch) = crate::symbol_fonts::fold_private_use(face, value) {
375                *value = ch.to_string();
376            }
377        }
378    }
379
380    let cid_fallback = if two_byte {
381        cid_fallback(doc, fdict)
382    } else {
383        CidFallback::None
384    };
385
386    let (mut widths, mut default_width) = if two_byte {
387        cid_widths(doc, fdict)
388    } else {
389        simple_widths(doc, fdict)
390    };
391
392    let simple_encoding = if two_byte {
393        None
394    } else {
395        Some(simple_encoding_table(doc, fdict))
396    };
397
398    // A standard-14 font referenced without an embedded program usually ships
399    // no `/Widths` and no `/FontDescriptor` either (ReportLab's default, #187).
400    // Every advance then resolved to 0, the cells collapsed to zero width, and
401    // the page's whole text layer was silently dropped — while pdfium, with
402    // its built-in metrics, reads the same file fine. Fill the widths from the
403    // built-in Adobe Core 14 AFM tables via the font's own code→char decode
404    // (base encoding + `/Differences`), so an explicit `/Widths` always wins.
405    if !two_byte && widths.is_empty() && default_width == 0.0 {
406        if let Some(std14) = base_font_name(fdict).and_then(|n| crate::std14::widths_for(&n)) {
407            if let Some(enc) = &simple_encoding {
408                for (&code, &ch) in enc {
409                    if let Some(w) = std14.width(ch) {
410                        widths.insert(u32::from(code), w);
411                    }
412                }
413            }
414            // Codes the table misses still advance a typical width instead of
415            // stacking at x=0 (the failure mode this whole branch fixes).
416            default_width = 500.0;
417        } else if let Some(face) = crate::symbol_fonts::symbol_face(&[base_font_name(fdict)
418            .as_deref()
419            .unwrap_or_default()])
420        {
421            // The two symbol faces are no std14 text faces: their AFM
422            // advances by code, as docling-parse's base font reads them.
423            for code in 0..=255u8 {
424                if let Some(w) = crate::symbol_fonts::face_width(face, code) {
425                    widths.insert(u32::from(code), w);
426                }
427            }
428            default_width = 500.0;
429        } else {
430            // Any other simple font without `/Widths` (a non-embedded
431            // Georgia, Verdana, Tahoma …; the spec requires `/Widths`
432            // outside the standard 14, but such files exist, #1153) advanced
433            // 0 per glyph, and its zero-width line was dropped with all its
434            // text. docling-parse reads the face's AFM; without one, the
435            // descriptor's `/AvgWidth`, else a typical 500 units, keeps the
436            // text with approximate geometry.
437            default_width = fdict
438                .get(b"FontDescriptor")
439                .ok()
440                .and_then(|o| as_dict(doc, o))
441                .and_then(|d| d.get(b"AvgWidth").ok())
442                .and_then(num)
443                .filter(|w| *w > 0.0)
444                .unwrap_or(500.0);
445        }
446    }
447    let fallback_names = if two_byte {
448        HashMap::new()
449    } else {
450        differences_gid_names(doc, fdict)
451    };
452    let program_encoding = if two_byte {
453        HashMap::new()
454    } else {
455        type1_program_encoding(doc, fdict)
456    };
457
458    let (ascent, descent, ink_boxes) = font_ascent_descent(doc, fdict, two_byte);
459    let mut font = Font {
460        two_byte,
461        to_unicode,
462        cid_fallback,
463        widths,
464        default_width,
465        simple_encoding,
466        fallback_names,
467        blank_codes: HashSet::new(),
468        program_encoding,
469        builtin: HashMap::new(),
470        diff_codes: differences_codes(doc, fdict),
471        ascent,
472        descent,
473        ink_y: HashMap::new(),
474        hash: hash_name(&sanitizer_name),
475        math: is_math_font_name(&sanitizer_name),
476        style: crate::font_style::parse_font_style(&String::from_utf8_lossy(
477            &base_font_name(fdict).unwrap_or_else(|| name.to_vec()),
478        )),
479    };
480    font.blank_codes = blank_codes(doc, fdict, &font);
481    if !two_byte && subtype != b"Type3".as_slice() && uses_builtin_encoding(doc, fdict) {
482        font.builtin = builtin_encoding(doc, fdict, &font);
483    }
484    if ink_boxes {
485        font.ink_y = ink_extents(doc, fdict, &font);
486    }
487    font
488}
489
490/// docling-parse 7.25's `uses_builtin_encoding` for a simple, non-Type 3
491/// font: the descriptor flags it symbolic (bit 3) and the PDF declares no
492/// base encoding — no `/Encoding` name, no `/BaseEncoding` in an `/Encoding`
493/// dictionary (a bare `/Differences` overrides only the codes it lists,
494/// 9.6.6.1).
495fn uses_builtin_encoding(doc: &Document, fdict: &Dictionary) -> bool {
496    let symbolic = fdict
497        .get(b"FontDescriptor")
498        .ok()
499        .and_then(|o| as_dict(doc, o))
500        .and_then(|fd| fd.get(b"Flags").ok())
501        .and_then(|o| deref(doc, o))
502        .and_then(num)
503        .is_some_and(|f| (f as i64) & 4 != 0);
504    let declared_base = match fdict.get(b"Encoding").ok().and_then(|o| deref(doc, o)) {
505        Some(Object::Name(_)) => true,
506        Some(Object::Dictionary(d)) => d.get(b"BaseEncoding").is_ok(),
507        _ => false,
508    };
509    symbolic && !declared_base
510}
511
512/// The codes a simple font's `/Differences` names.
513fn differences_codes(doc: &Document, fdict: &Dictionary) -> HashSet<u8> {
514    let mut codes = HashSet::new();
515    let mut code = 0i64;
516    for el in differences_array(doc, fdict).unwrap_or_default() {
517        match el {
518            Object::Integer(i) => code = i,
519            Object::Real(r) => code = r as i64,
520            Object::Name(_) => {
521                if (0..=255).contains(&code) {
522                    codes.insert(code as u8);
523                }
524                code += 1;
525            }
526            _ => {}
527        }
528    }
529    codes
530}
531
532/// [`Font::builtin`]: read from the embedded program only when a declared
533/// code is left to it — not covered by `/ToUnicode` or `/Differences`
534/// (docling-parse reads the program lazily, on the first code that needs it).
535#[cfg(feature = "render")]
536fn builtin_encoding(doc: &Document, fdict: &Dictionary, font: &Font) -> HashMap<u8, String> {
537    let mut codes: Vec<u32> = font.widths.keys().copied().collect();
538    if codes.is_empty() {
539        codes.extend(0..=255);
540    }
541    let needed = codes.iter().any(|&c| {
542        c <= 255 && !font.to_unicode.contains_key(&c) && !font.diff_codes.contains(&(c as u8))
543    });
544    if !needed {
545        return HashMap::new();
546    }
547    crate::render::font::LoadedFont::load(doc, fdict).builtin_encoding_text()
548}
549
550/// Without the renderer there is no program to read: the font keeps the
551/// encoding tables' reading.
552#[cfg(not(feature = "render"))]
553fn builtin_encoding(_doc: &Document, _fdict: &Dictionary, _font: &Font) -> HashMap<u8, String> {
554    HashMap::new()
555}
556
557/// The ink extents of `font`'s declared codes ([`Font::ink_y`]), read from
558/// its embedded program; nothing past a CID font's first 4096 codes.
559#[cfg(feature = "render")]
560fn ink_extents(doc: &Document, fdict: &Dictionary, font: &Font) -> HashMap<u32, (f64, f64)> {
561    const MAX_CODES: usize = 4096;
562    let loaded = crate::render::font::LoadedFont::load(doc, fdict);
563    if !loaded.has_program() {
564        return HashMap::new();
565    }
566    let mut codes: Vec<u32> = font.widths.keys().copied().collect();
567    if !font.two_byte {
568        codes.extend(0..=255);
569        codes.sort_unstable();
570        codes.dedup();
571    }
572    codes
573        .into_iter()
574        .take(MAX_CODES)
575        .filter_map(|c| Some((c, loaded.glyph_ink_y(c)??)))
576        .collect()
577}
578
579/// Without the renderer there is no program to read: the font keeps its
580/// loose box (docling-parse's own fallback when FreeType resolves no glyph).
581#[cfg(not(feature = "render"))]
582fn ink_extents(_doc: &Document, _fdict: &Dictionary, _font: &Font) -> HashMap<u32, (f64, f64)> {
583    HashMap::new()
584}
585
586/// The codes `font` leaves unmapped whose embedded glyph paints nothing
587/// ([`Font::blank_codes`]). The program is loaded only when the font has
588/// unmapped codes among those it declares widths for; without the
589/// renderer (the wasm text-layer build) there is no program to ask, and
590/// every unmapped glyph reads U+FFFD.
591#[cfg(feature = "render")]
592fn blank_codes(doc: &Document, fdict: &Dictionary, font: &Font) -> HashSet<u32> {
593    // A CID font can declare tens of thousands of widths: past this many
594    // unmapped codes nothing is classified (the glyphs read U+FFFD).
595    const MAX_CANDIDATES: usize = 4096;
596    let unmapped: Vec<u32> = font
597        .widths
598        .keys()
599        .copied()
600        .filter(|&c| font.decode_code(c).0.as_deref() == Some("\u{FFFD}"))
601        .take(MAX_CANDIDATES + 1)
602        .collect();
603    if unmapped.is_empty() || unmapped.len() > MAX_CANDIDATES {
604        return HashSet::new();
605    }
606    let loaded = crate::render::font::LoadedFont::load(doc, fdict);
607    unmapped
608        .into_iter()
609        .filter(|&c| loaded.glyph_has_ink(c) == Some(false))
610        .collect()
611}
612
613#[cfg(not(feature = "render"))]
614fn blank_codes(_doc: &Document, _fdict: &Dictionary, _font: &Font) -> HashSet<u32> {
615    HashSet::new()
616}
617
618#[derive(Clone, Copy)]
619enum CidFallback {
620    None,
621    UnicodeCodes { utf16: bool },
622    Collection(&'static [u8]),
623}
624
625/// A Unicode CMap code retains its original bytes for ToUnicode lookups;
626/// a four-byte UTF-16 code is a packed surrogate pair, not a scalar value.
627pub(crate) fn unicode_cmap_char(code: u32) -> Option<char> {
628    if code <= 0xffff {
629        char::from_u32(code)
630    } else {
631        let units = [(code >> 16) as u16, code as u16];
632        let mut chars = char::decode_utf16(units);
633        let ch = chars.next()?.ok()?;
634        chars.next().is_none().then_some(ch)
635    }
636}
637
638#[cfg(not(feature = "cid-collections"))]
639fn collection_table(_ordering: &[u8]) -> Option<&'static [u8]> {
640    None
641}
642
643#[cfg(feature = "cid-collections")]
644fn collection_table(ordering: &[u8]) -> Option<&'static [u8]> {
645    macro_rules! table {
646        ($file:literal) => {
647            include_bytes!(concat!(env!("OUT_DIR"), "/", $file))
648        };
649    }
650    Some(match ordering {
651        b"Japan1" => table!("Adobe-Japan1-UCS2"),
652        b"GB1" => table!("Adobe-GB1-UCS2"),
653        b"CNS1" => table!("Adobe-CNS1-UCS2"),
654        b"Korea1" => table!("Adobe-Korea1-UCS2"),
655        b"KR" => table!("Adobe-KR-UCS2"),
656        _ => return None,
657    })
658}
659
660/// The text of `cid` in a table build.rs wrote: the CID count, then three
661/// bytes per CID (0 for none, a code point, or 0x110000 + the offset of a
662/// length-prefixed UTF-8 string after the entries).
663pub(crate) fn collection_text(table: &[u8], cid: u32) -> Option<String> {
664    let n = u32::from_le_bytes(table.get(..4)?.try_into().ok()?) as usize;
665    let at = 4 + 3 * usize::try_from(cid).ok().filter(|&c| c < n)?;
666    let &[a, b, c] = table.get(at..at + 3)? else {
667        return None;
668    };
669    match u32::from_be_bytes([0, a, b, c]) {
670        0 => None,
671        v @ ..0x110000 => char::from_u32(v).map(String::from),
672        v => {
673            let at = 4 + 3 * n + (v - 0x110000) as usize;
674            let len = *table.get(at)? as usize;
675            std::str::from_utf8(table.get(at + 1..at + 1 + len)?)
676                .ok()
677                .map(str::to_owned)
678        }
679    }
680}
681
682fn cid_fallback(doc: &Document, fdict: &Dictionary) -> CidFallback {
683    let encoding = fdict
684        .get(b"Encoding")
685        .ok()
686        .and_then(|o| deref(doc, o))
687        .and_then(|o| o.as_name().ok())
688        .unwrap_or(&[]);
689    if encoding.starts_with(b"Uni")
690        && (encoding.windows(4).any(|w| w == b"UCS2") || encoding.windows(5).any(|w| w == b"UTF16"))
691    {
692        return CidFallback::UnicodeCodes {
693            utf16: encoding.windows(5).any(|w| w == b"UTF16"),
694        };
695    }
696    if encoding != b"Identity-H" && encoding != b"Identity-V" {
697        // Other CMaps need code → CID tables that are not bundled.
698        return CidFallback::None;
699    }
700    cid_collection(doc, fdict).map_or(CidFallback::None, CidFallback::Collection)
701}
702
703/// The CID → Unicode table of the character collection a Type0 font uses.
704pub(crate) fn cid_collection(doc: &Document, fdict: &Dictionary) -> Option<&'static [u8]> {
705    let Object::Array(descendants) = deref(doc, fdict.get(b"DescendantFonts").ok()?)? else {
706        return None;
707    };
708    let descendant = as_dict(doc, descendants.first()?)?;
709    let info = as_dict(doc, descendant.get(b"CIDSystemInfo").ok()?)?;
710    let registry = deref(doc, info.get(b"Registry").ok()?)?.as_str().ok()?;
711    let ordering = deref(doc, info.get(b"Ordering").ok()?)?.as_str().ok()?;
712    (registry == b"Adobe").then(|| collection_table(ordering))?
713}
714
715/// A simple font's `/Encoding` `/Differences` array, dereferenced.
716fn differences_array(doc: &Document, fdict: &Dictionary) -> Option<Vec<Object>> {
717    let enc = fdict.get(b"Encoding").ok().and_then(|o| deref(doc, o))?;
718    let diffs = enc.as_dict().ok()?.get(b"Differences").ok()?;
719    match deref(doc, diffs)? {
720        Object::Array(a) => Some(a.clone()),
721        _ => None,
722    }
723}
724
725/// A ToUnicode CMap copied from the *original* font while the glyphs were
726/// re-encoded: the encrypted `2206.01062_pg3` fixture (a Quartz re-save of
727/// pdfTeX output) keeps the T1-encoding CMap, keyed on the old codes, next
728/// to a `/Differences [33 /f_f_i /f_i /f_f /f_l]` that names the ligatures at
729/// new ones, so the CMap maps code 33 to `!` — its own identity — and
730/// `difficulties` read `di ! culties`, in docling's pdfium chain too. A
731/// ToUnicode entry that is the code's identity, for a code whose
732/// `/Differences` name resolves to something else, is that stale copy: the
733/// name wins. A CMap that disagrees any other way is left alone — ToUnicode
734/// is the producer's word on what the glyph means.
735///
736/// The name also wins over a ToUnicode value that says nothing (#1121):
737/// docling-parse's `has_to_unicode` discards an empty value and a single
738/// NUL, U+FFFD or Unicode noncharacter for a code `/Differences` names, and
739/// resolves the name instead. A figure embedded in 1503.04203 re-encodes
740/// its TeX glyphs to code 33 with `/Differences [33 /minus]` and a CMap
741/// `<21> <0000>` — the glyph's old code written as its Unicode — so
742/// `Q = −1/2` read `Q = � 12` and `√Δ²` read `p�2`.
743fn reconcile_stale_tounicode(to_unicode: &mut HashMap<u32, String>, diffs: &[Object]) {
744    let says_nothing = |value: &str| {
745        let mut chars = value.chars();
746        match (chars.next(), chars.next()) {
747            (None, _) => true,
748            (Some(c), None) => {
749                let cp = c as u32;
750                cp == 0 || cp == 0xFFFD || (0xFDD0..=0xFDEF).contains(&cp) || cp & 0xFFFE == 0xFFFE
751            }
752            _ => false,
753        }
754    };
755    let mut code = 0u8;
756    for el in diffs {
757        match el {
758            Object::Integer(i) => code = *i as u8,
759            Object::Name(name) => {
760                if let Some(ch) = glyph_name_to_char(name) {
761                    let identity = (code as char).to_string();
762                    let current = to_unicode.get(&u32::from(code));
763                    if (ch.to_string() != identity && current == Some(&identity))
764                        || current.is_some_and(|v| says_nothing(v))
765                    {
766                        to_unicode.insert(u32::from(code), ch.to_string());
767                    }
768                }
769                code = code.wrapping_add(1);
770            }
771            _ => {}
772        }
773    }
774}
775
776/// Collect `/Differences` entries whose glyph name is a GID placeholder
777/// (`g115`, `cid42`, `glyph7`, `index9`, `SM590000`) with no Unicode mapping
778/// (subsetted fonts with no ToUnicode); [`unknown_name_text`] decides what
779/// each reads as. The placeholder-name restriction keeps real Adobe glyph
780/// names on the normal path so this never invents garbage on the clean files.
781fn differences_gid_names(doc: &Document, fdict: &Dictionary) -> HashMap<u8, String> {
782    let mut map = HashMap::new();
783    let Some(Object::Dictionary(enc)) = fdict.get(b"Encoding").ok().and_then(|o| deref(doc, o))
784    else {
785        return map;
786    };
787    let Some(Object::Array(diffs)) = enc.get(b"Differences").ok().and_then(|o| deref(doc, o))
788    else {
789        return map;
790    };
791    let mut code = 0u8;
792    for el in diffs {
793        match el {
794            Object::Integer(i) => code = *i as u8,
795            Object::Name(name) => {
796                if glyph_name_to_char(name).is_none() && is_gid_name(name) {
797                    map.insert(code, String::from_utf8_lossy(name).into_owned());
798                }
799                code = code.wrapping_add(1);
800            }
801            _ => {}
802        }
803    }
804    map
805}
806
807/// Parse the embedded Type1 font program's built-in `/Encoding` vector
808/// (`dup <code> /<glyphname> put` entries in the clear-text header before
809/// `eexec`) into `code → char`. This is how docling recovers glyphs from
810/// standard TeX math fonts (CMMI/CMSY/…) that carry no PDF `/Encoding` and no
811/// ToUnicode — e.g. CMMI's `dup 21 /lambda` or CMSY's `dup 20 /lessequal`.
812/// Only `FontFile` (Type1) is parsed; CFF (`FontFile3`) and TrueType
813/// (`FontFile2`) store their encoding in a binary table and are left alone.
814fn type1_program_encoding(doc: &Document, fdict: &Dictionary) -> HashMap<u8, char> {
815    let mut map = HashMap::new();
816    let Some(desc) = fdict
817        .get(b"FontDescriptor")
818        .ok()
819        .and_then(|o| deref(doc, o))
820        .and_then(|o| o.as_dict().ok())
821    else {
822        return map;
823    };
824    let Some(data) = desc
825        .get(b"FontFile")
826        .ok()
827        .and_then(|o| deref(doc, o))
828        .and_then(|o| o.as_stream().ok())
829        .and_then(|s| s.decompressed_content().ok())
830    else {
831        return map;
832    };
833    // The clear-text header (PostScript) ends at `eexec`; the rest is encrypted.
834    let head_end = data
835        .windows(5)
836        .position(|w| w == b"eexec")
837        .unwrap_or(data.len());
838    let head = String::from_utf8_lossy(&data[..head_end]);
839    // Scan for `dup <code> /<name> put` tokens.
840    let toks: Vec<&str> = head.split_whitespace().collect();
841    for w in toks.windows(4) {
842        if w[0] == "dup" && w[3] == "put" {
843            if let (Ok(code), Some(name)) = (w[1].parse::<u32>(), w[2].strip_prefix('/')) {
844                if code <= 255 {
845                    if let Some(ch) = glyph_name_to_char(name.as_bytes()) {
846                        map.insert(code as u8, ch);
847                    }
848                }
849            }
850        }
851    }
852    map
853}
854
855/// The reading text docling-parse 7.24 keeps for a `/Differences` glyph name
856/// no table resolves (`resolve_unknown_name`): the name without any
857/// `.suffix` — `None` when that is a bare glyph index
858/// (`(gid|glyph|g|cid|index)\d+`, any case), which names a glyph of the
859/// font program but carries no text (docling-parse#238), so it is unmapped.
860fn unknown_name_text(name: &str) -> Option<String> {
861    let stem = name.rsplit_once('.').map_or(name, |(s, _)| s);
862    (!is_index_name(stem)).then(|| stem.to_string())
863}
864
865/// docling-parse's index-style glyph name, `(gid|glyph|g|cid|index)` then
866/// hexadecimal digits, case-insensitive (`re_gid`): `/gid00043`, `/g43`,
867/// `/cid43`, `/index43` from the subset generators, and since docling-parse
868/// 7.25 (#389 in docling-parse#431, #1113) Skia/PDF's `g%X` — `/g15C`,
869/// `/gA1` from Chrome's print-to-PDF and Notion exports, which read as
870/// their base encoding's letters before. The name points into the font
871/// program and carries no text.
872fn is_index_name(name: &str) -> bool {
873    let lower = name.to_ascii_lowercase();
874    ["gid", "glyph", "g", "cid", "index"].iter().any(|p| {
875        lower
876            .strip_prefix(p)
877            .is_some_and(|d| !d.is_empty() && d.bytes().all(|b| b.is_ascii_hexdigit()))
878    })
879}
880
881/// A glyph name that is a synthetic placeholder, not a real Adobe name:
882/// `g115`, `cid42`, `glyph7`, `index9`, `G12`, or a short-prefix code name like
883/// `SM590000` (IBM BookMaster). These carry no Unicode meaning (docling-parse
884/// keeps the code-like names as text, `SM590000`, and reads the glyph indexes
885/// as unmapped, see [`unknown_name_text`]). `afii####` / `uni####` are real Adobe names
886/// and excluded. The restriction keeps genuine glyph names on the Unicode path.
887fn is_gid_name(name: &[u8]) -> bool {
888    let Ok(s) = std::str::from_utf8(name) else {
889        return false;
890    };
891    if s.starts_with("afii") || s.starts_with("uni") {
892        return false;
893    }
894    if is_index_name(s) {
895        return true;
896    }
897    // Short alpha prefix (≤3 letters) followed by a run of ≥3 digits — synthetic
898    // code names like `SM590000`, distinct from real Adobe names (whole words or
899    // letter+`.suffix` variants).
900    let alpha = s.bytes().take_while(|b| b.is_ascii_alphabetic()).count();
901    let digits = s.len() - alpha;
902    (1..=3).contains(&alpha)
903        && digits >= 3
904        && s.as_bytes()[alpha..].iter().all(|b| b.is_ascii_digit())
905}
906
907/// The top and bottom of the font's loose char boxes above the baseline
908/// (1000-unit em) — docling-parse's: the ascent and descent, scaled by
909/// `CapHeight / Ascent` where the descriptor gives a cap height — and whether docling-parse 7.24 rejects its descriptor metrics
910/// (`invalid_vertical_metrics`, `init_ascent_and_descent`) — then it boxes
911/// each glyph by its embedded outline instead ([`Font::ink_y`]):
912///
913/// - an `/Ascent` or `/Descent` beyond ±8000 (`MAX_PLAUSIBLE_VERTICAL_METRIC`)
914///   is ignored for the `/FontBBox` edge, when that is usable;
915/// - metrics that do not straddle the baseline (`descent <= 0 <= ascent`,
916///   `descent < ascent` — `/Ascent 0 /Descent 0`, or a math font's two
917///   positive values) give way to a valid `/FontBBox`.
918fn font_ascent_descent(doc: &Document, fdict: &Dictionary, two_byte: bool) -> (f64, f64, bool) {
919    // For Type0, the descriptor lives on the descendant CIDFont.
920    let descr_owner = if two_byte {
921        fdict
922            .get(b"DescendantFonts")
923            .ok()
924            .and_then(|o| deref(doc, o))
925            .and_then(|o| match o {
926                Object::Array(a) => a.first(),
927                _ => None,
928            })
929            .and_then(|o| as_dict(doc, o))
930    } else {
931        Some(fdict)
932    };
933    let fd = descr_owner
934        .and_then(|d| d.get(b"FontDescriptor").ok())
935        .and_then(|o| as_dict(doc, o));
936    let read = |key: &[u8]| fd.and_then(|d| d.get(key).ok()).and_then(num);
937    let plausible = |v: f64| v.is_finite() && v.abs() <= 8000.0;
938    let bbox = fd
939        .and_then(|d| d.get(b"FontBBox").ok())
940        .and_then(|o| deref(doc, o))
941        .and_then(|o| match o {
942            Object::Array(a) if a.len() == 4 => {
943                let v: Vec<f64> = a.iter().filter_map(num).collect();
944                (v.len() == 4).then(|| [v[0], v[1], v[2], v[3]])
945            }
946            _ => None,
947        });
948    let usable = |v: f64| v.abs() > 1e-3 && plausible(v);
949    // docling-parse does not box a glyph between the font's descent and
950    // ascent but between both scaled by `CapHeight / Ascent`
951    // (`pdf_state<TEXT>`: `compute_rect(font_descent*ratio,
952    // font_ascent*ratio, width)`, the ratio taken when it lies in
953    // 0.05..=1): the box tops out at the capitals, and the descent shrinks
954    // in proportion. For most text faces that is a few percent (a
955    // Libertine line cell is 15.3 pt where the unscaled box is 16.0), and
956    // it is what keeps a face with inflated metrics readable: Cambria's
957    // regular face declares `/Ascent 3117 /Descent -2464 /CapHeight 667`,
958    // a 5.6 em box around every line unscaled — each line cell covering
959    // the four lines around it, none of them more than a fifth inside its
960    // own one-line layout region — and 1.19 em scaled (0.667 above the
961    // baseline, 0.527 below). A font without a `/CapHeight` keeps its
962    // metrics as they are (docling-parse reads a standard-14 face's from
963    // its AFM, like the ascent and descent this port defaults).
964    let cap_scaled = |asc: f64, desc: f64| {
965        let ratio = read(b"CapHeight")
966            .filter(|&c| plausible(c))
967            .map(|c| c / asc)
968            .filter(|r| (0.05..=1.0).contains(r))
969            .unwrap_or(1.0);
970        (asc * ratio, desc * ratio)
971    };
972    let mut invalid = false;
973    let asc = match read(b"Ascent") {
974        Some(v) if plausible(v) => v,
975        Some(_) => {
976            invalid = true;
977            bbox.map(|b| b[3]).filter(|&v| usable(v)).unwrap_or(750.0)
978        }
979        None => 750.0,
980    };
981    let desc = match read(b"Descent") {
982        Some(v) if plausible(v) => v,
983        Some(_) => {
984            invalid = true;
985            bbox.map(|b| b[1]).filter(|&v| usable(v)).unwrap_or(-250.0)
986        }
987        None => -250.0,
988    };
989    if !(desc <= 0.0 && asc >= 0.0 && desc < asc) {
990        if let Some(b) = bbox.filter(|b| {
991            b[1] <= 0.0 && b[3] >= 0.0 && b[1] < b[3] && plausible(b[1]) && plausible(b[3])
992        }) {
993            let (asc, desc) = cap_scaled(b[3], b[1]);
994            return (asc, desc, true);
995        }
996    }
997    // Some subsetted fonts carry a degenerate FontDescriptor (`/Ascent 0
998    // /Descent 0`) and no usable FontBBox either: the real metrics live in
999    // the font program. A zero-height loose box gives the line cells zero
1000    // area and the layout's region/text assignment drops them (2305's
1001    // References list lost every prose line, keeping only the URLs), so
1002    // fall back to typical text metrics.
1003    if asc - desc <= 1.0 {
1004        return (750.0, -250.0, invalid);
1005    }
1006    let (asc, desc) = cap_scaled(asc, desc);
1007    (asc, desc, invalid)
1008}
1009
1010/// The `/BaseFont` name with any `ABCDEF+` subset prefix stripped (#187).
1011fn base_font_name(fdict: &Dictionary) -> Option<Vec<u8>> {
1012    let name = fdict.get(b"BaseFont").ok()?.as_name().ok()?;
1013    let stripped = match name.iter().position(|&b| b == b'+') {
1014        Some(i) if i == 6 => &name[i + 1..],
1015        _ => name,
1016    };
1017    Some(stripped.to_vec())
1018}
1019
1020/// Simple-font widths: `/FirstChar` + `/Widths` array, `/MissingWidth` default.
1021fn simple_widths(doc: &Document, fdict: &Dictionary) -> (HashMap<u32, f64>, f64) {
1022    let mut map = HashMap::new();
1023    let first = fdict
1024        .get(b"FirstChar")
1025        .ok()
1026        .and_then(|o| o.as_i64().ok())
1027        .unwrap_or(0) as u32;
1028    if let Some(Object::Array(arr)) = fdict.get(b"Widths").ok().and_then(|o| deref(doc, o)) {
1029        for (i, w) in arr.iter().enumerate() {
1030            if let Some(w) = num(w) {
1031                map.insert(first + i as u32, w);
1032            }
1033        }
1034    }
1035    let dw = fdict
1036        .get(b"FontDescriptor")
1037        .ok()
1038        .and_then(|o| as_dict(doc, o))
1039        .and_then(|d| d.get(b"MissingWidth").ok())
1040        .and_then(num)
1041        .unwrap_or(0.0);
1042    (map, dw)
1043}
1044
1045/// CIDFont widths: the `/W` array on the descendant font (`/DW` default = 1000).
1046fn cid_widths(doc: &Document, fdict: &Dictionary) -> (HashMap<u32, f64>, f64) {
1047    let mut map = HashMap::new();
1048    let Some(desc) = fdict
1049        .get(b"DescendantFonts")
1050        .ok()
1051        .and_then(|o| deref(doc, o))
1052        .and_then(|o| match o {
1053            Object::Array(a) => a.first(),
1054            _ => None,
1055        })
1056        .and_then(|o| as_dict(doc, o))
1057    else {
1058        return (map, 1000.0);
1059    };
1060    let dw = desc.get(b"DW").ok().and_then(num).unwrap_or(1000.0);
1061    if let Some(Object::Array(w)) = desc.get(b"W").ok().and_then(|o| deref(doc, o)) {
1062        let mut i = 0;
1063        while i < w.len() {
1064            let c = w.get(i).and_then(num);
1065            match (c, w.get(i + 1)) {
1066                // `c [w1 w2 ...]`: consecutive CIDs starting at c.
1067                (Some(c), Some(Object::Array(list))) => {
1068                    for (k, wv) in list.iter().enumerate() {
1069                        if let Some(wv) = num(wv) {
1070                            map.insert(c as u32 + k as u32, wv);
1071                        }
1072                    }
1073                    i += 2;
1074                }
1075                // `c_first c_last w`: a run all of width w.
1076                (Some(c1), Some(o2)) => {
1077                    if let (Some(c2), Some(wv)) = (num(o2), w.get(i + 2).and_then(num)) {
1078                        for cid in c1 as u32..=c2 as u32 {
1079                            map.insert(cid, wv);
1080                        }
1081                    }
1082                    i += 3;
1083                }
1084                _ => break,
1085            }
1086        }
1087    }
1088    (map, dw)
1089}
1090
1091fn num(o: &Object) -> Option<f64> {
1092    match o {
1093        Object::Integer(i) => Some(*i as f64),
1094        Object::Real(r) => Some(real(*r)),
1095        _ => None,
1096    }
1097}
1098
1099/// lopdf keeps a real as an `f32`; docling-parse reads the same token as a
1100/// double. The shortest decimal that round-trips the `f32` is the token the
1101/// file wrote (for any real written with the precision `f32` holds), so
1102/// `90.144 + 1.44` meets `91.584` here as it does there.
1103fn real(r: f32) -> f64 {
1104    use std::fmt::Write as _;
1105    let mut buf = String::with_capacity(16);
1106    let _ = write!(buf, "{r}");
1107    buf.parse().unwrap_or(r as f64)
1108}
1109
1110/// Decode a PDF string literal into codes, retaining packed UTF-16 pairs
1111/// as the original four-byte keys used by ToUnicode.
1112fn codes(font: &Font, bytes: &[u8]) -> Vec<u32> {
1113    if font.two_byte {
1114        let mut units = bytes
1115            .chunks(2)
1116            .map(|c| {
1117                if c.len() == 2 {
1118                    ((c[0] as u32) << 8) | c[1] as u32
1119                } else {
1120                    c[0] as u32
1121                }
1122            })
1123            .peekable();
1124        let utf16 = matches!(font.cid_fallback, CidFallback::UnicodeCodes { utf16: true });
1125        let mut out = Vec::with_capacity(bytes.len() / 2 + 1);
1126        while let Some(mut code) = units.next() {
1127            if utf16 && (0xd800..=0xdbff).contains(&code) {
1128                if let Some(low) = units.next_if(|u| (0xdc00..=0xdfff).contains(u)) {
1129                    code = (code << 16) | low;
1130                }
1131            }
1132            out.push(code);
1133        }
1134        out
1135    } else {
1136        bytes.iter().map(|&b| b as u32).collect()
1137    }
1138}
1139
1140/// A page's display box, in PDF user space: the `/CropBox` clipped to the
1141/// `/MediaBox`, both inherited through the page tree and normalized — a
1142/// missing or empty MediaBox is US Letter, an empty CropBox is the MediaBox
1143/// (pdfium's `CPDF_Page::UpdateDimensions`). pdfium reports the page size from
1144/// this box, renders exactly it, and translates every content coordinate so
1145/// its lower-left corner is the origin (`m_PageMatrix`); docling's backends
1146/// inherit that frame, so text cells, `prov` boxes and destinations all count
1147/// from the CropBox corner, not the MediaBox one. The parser used to flip
1148/// glyphs with the MediaBox *height* and no translation at all, so a page
1149/// whose boxes do not start at (0, 0) — a trimmed book page with
1150/// `MediaBox [-56 -58 576 723]` / `CropBox [1 -0.6 519 666]`, or a LaTeX
1151/// figure cropped to `[156 147 637 391]` — had its text displaced against the
1152/// rendered bitmap by the box offset, the bottom lines pushed past the page
1153/// edge and clamped to `t = b`.
1154#[derive(Debug, Clone, Copy, PartialEq)]
1155pub(crate) struct PageBox {
1156    /// Left edge, user space.
1157    pub l: f32,
1158    /// Bottom edge, user space.
1159    pub b: f32,
1160    pub w: f32,
1161    pub h: f32,
1162}
1163
1164impl PageBox {
1165    /// Top edge, user space — the y that becomes `0` in the y-down frame.
1166    pub fn top(&self) -> f32 {
1167        self.b + self.h
1168    }
1169}
1170
1171/// A page-tree rect attribute (`/MediaBox`, `/CropBox`), inherited from the
1172/// nearest ancestor that sets it, as normalized `(l, b, r, t)`.
1173fn inherited_rect(
1174    doc: &Document,
1175    page_id: lopdf::ObjectId,
1176    key: &[u8],
1177) -> Option<(f32, f32, f32, f32)> {
1178    let mut id = page_id;
1179    for _ in 0..32 {
1180        let dict = doc.get_object(id).ok()?.as_dict().ok()?;
1181        if let Some(Object::Array(a)) = dict.get(key).ok().and_then(|o| deref(doc, o)) {
1182            let v: Vec<f32> = a.iter().filter_map(|o| num(o).map(|x| x as f32)).collect();
1183            if v.len() == 4 && v.iter().all(|x| x.is_finite()) {
1184                return Some((
1185                    v[0].min(v[2]),
1186                    v[1].min(v[3]),
1187                    v[0].max(v[2]),
1188                    v[1].max(v[3]),
1189                ));
1190            }
1191            return None;
1192        }
1193        id = dict.get(b"Parent").ok()?.as_reference().ok()?;
1194    }
1195    None
1196}
1197
1198pub(crate) fn page_box(doc: &Document, page_id: lopdf::ObjectId) -> PageBox {
1199    let nonempty = |r: &(f32, f32, f32, f32)| r.2 > r.0 && r.3 > r.1;
1200    let media = inherited_rect(doc, page_id, b"MediaBox")
1201        .filter(nonempty)
1202        .unwrap_or((0.0, 0.0, 612.0, 792.0));
1203    let crop = inherited_rect(doc, page_id, b"CropBox")
1204        .map(|c| {
1205            (
1206                c.0.max(media.0),
1207                c.1.max(media.1),
1208                c.2.min(media.2),
1209                c.3.min(media.3),
1210            )
1211        })
1212        .filter(nonempty)
1213        .unwrap_or(media);
1214    PageBox {
1215        l: crop.0,
1216        b: crop.1,
1217        w: crop.2 - crop.0,
1218        h: crop.3 - crop.1,
1219    }
1220}
1221
1222/// A content stream's decoded bytes — a page's, a Form XObject's or a Type 3
1223/// glyph procedure's — keeping what a damaged Flate stream inflates before
1224/// its error (#1154). lopdf's decoder loses the output of the read that
1225/// failed, so a short stream (all of it one read) comes back empty, and a
1226/// stream it cannot decode at all comes back raw from `get_page_content` —
1227/// compressed bytes the tokenizer rejects with the rest of the content.
1228/// docling-parse (`qpdf_stream_decoder::decode_damaged_stream`, per stream
1229/// since docling-parse#451) and pdfium keep the intact prefix; so does this.
1230/// `None` only for a Flate stream nothing can be read from.
1231pub(crate) fn content_stream_bytes(stream: &lopdf::Stream) -> Option<Vec<u8>> {
1232    let predictor = stream
1233        .dict
1234        .get(b"DecodeParms")
1235        .ok()
1236        .and_then(|o| o.as_dict().ok())
1237        .and_then(|d| d.get(b"Predictor").ok())
1238        .and_then(|o| o.as_i64().ok())
1239        .unwrap_or(1);
1240    let plain_flate = predictor <= 1
1241        && matches!(
1242            stream.filters().unwrap_or_default().as_slice(),
1243            [f] if *f == b"FlateDecode" || *f == b"Fl"
1244        );
1245    if plain_flate {
1246        let out = inflate_prefix(&stream.content);
1247        if !out.is_empty() {
1248            return Some(out);
1249        }
1250    }
1251    // Everything else — and a Flate stream without a zlib header, which
1252    // lopdf retries as raw deflate — as lopdf decodes it.
1253    match stream.decompressed_content() {
1254        Ok(data) => Some(data),
1255        Err(_) if plain_flate => None,
1256        // Anything else as lopdf has always handed it over.
1257        Err(_) => Some(stream.content.clone()),
1258    }
1259}
1260
1261/// zlib inflate up to the first error, keeping everything before it —
1262/// pdfium's `FlateModule`. Stepped through `Decompress` because a
1263/// `read::ZlibDecoder` drops what the failing read had already inflated.
1264pub(crate) fn inflate_prefix(data: &[u8]) -> Vec<u8> {
1265    let mut dec = flate2::Decompress::new(true);
1266    let mut out = Vec::new();
1267    let mut buf = vec![0u8; 1 << 16];
1268    loop {
1269        let (in_before, out_before) = (dec.total_in(), dec.total_out());
1270        let input = &data[(in_before as usize).min(data.len())..];
1271        let status = dec.decompress(input, &mut buf, flate2::FlushDecompress::None);
1272        let written = (dec.total_out() - out_before) as usize;
1273        out.extend_from_slice(&buf[..written]);
1274        match status {
1275            Ok(flate2::Status::Ok) if written > 0 || dec.total_in() > in_before => {}
1276            _ => break,
1277        }
1278    }
1279    out
1280}
1281
1282/// A page's content — every stream of its `/Contents`, decoded by
1283/// [`content_stream_bytes`], each followed by a newline as lopdf's
1284/// `get_page_content` joins them. An undecodable stream drops out instead of
1285/// spilling its raw bytes into the content of the others.
1286pub(crate) fn page_content(doc: &Document, page_id: lopdf::ObjectId) -> Vec<u8> {
1287    let mut content = Vec::new();
1288    for id in doc.get_page_contents(page_id) {
1289        if let Some(data) = doc
1290            .get_object(id)
1291            .and_then(Object::as_stream)
1292            .ok()
1293            .and_then(content_stream_bytes)
1294        {
1295            content.extend_from_slice(&data);
1296            content.push(b'\n');
1297        }
1298    }
1299    content
1300}
1301
1302/// Page size (width, height) in PDF points — the display box's, like pdfium's
1303/// `FPDF_GetPageWidthF/HeightF`.
1304fn page_size(doc: &Document, page_id: lopdf::ObjectId) -> (f32, f32) {
1305    let pb = page_box(doc, page_id);
1306    (pb.w, pb.h)
1307}
1308
1309/// Localize where a page's text is lost, for the `text_layer` diagnostic.
1310/// Extraction can come up empty at three different points — no content stream
1311/// reached the parser, the stream did not decode into operators, or it ran but
1312/// produced no glyphs (fonts/encodings) — and from the outside all three look
1313/// the same. Report them per page.
1314pub fn content_diagnosis(bytes: &[u8]) -> String {
1315    let Some(doc) = load_document(bytes) else {
1316        return "document does not load".into();
1317    };
1318    let mut pages: Vec<_> = doc.get_pages().into_iter().collect();
1319    pages.sort_by_key(|(n, _)| *n);
1320    let mut out = String::new();
1321    let mut caches = DocCaches::default();
1322    for (n, pid) in pages.into_iter().take(4) {
1323        let content_bytes = page_content(&doc, pid);
1324        let ops = lopdf::content::Content::decode(&content_bytes)
1325            .map(|c| c.operations.len())
1326            .ok();
1327        let res = page_res(&doc, pid);
1328        let fonts = res.map(|r| fonts_from_res(&doc, r, &mut caches).len());
1329        let glyphs = page_glyphs_cached(&doc, pid, &mut caches).len();
1330        out.push_str(&format!(
1331            "\n   page {n}: content {} B, ops {}, resources {}, fonts {}, glyphs {}",
1332            content_bytes.len(),
1333            ops.map_or("UNDECODABLE".to_string(), |n| n.to_string()),
1334            if res.is_some() { "ok" } else { "MISSING" },
1335            fonts.map_or("-".to_string(), |n| n.to_string()),
1336            glyphs,
1337        ));
1338    }
1339    out
1340}
1341
1342/// Is this "text layer" a vestige rather than the document's text?
1343///
1344/// Scanned forms often carry a handful of typed-in strings — a date filled
1345/// into three form fields, say — on top of pages that are otherwise images.
1346/// Treating that as a real text layer is the worst of both worlds: the text
1347/// path proudly extracts thirteen characters, and no OCR ever runs on the
1348/// letter the pages actually show. The reported form did exactly this (3
1349/// lines, 13 chars, 3 pages).
1350///
1351/// The rule is deliberately tight so genuinely sparse *digital* documents are
1352/// not misrouted into OCR: only a document averaging at most one line per page
1353/// **and** totalling fewer than 32 characters is called vestigial.
1354pub fn text_layer_is_vestigial(pages: &[crate::pdfium_backend::PdfPage]) -> bool {
1355    let mut tally = TextLayerTally::default();
1356    pages.iter().for_each(|p| tally.add(p));
1357    tally.is_vestigial()
1358}
1359
1360/// [`text_layer_is_vestigial`]'s counts, accumulated a page at a time so a
1361/// streaming caller need not keep the pages around to decide.
1362#[derive(Debug, Default, Clone, Copy)]
1363pub struct TextLayerTally {
1364    pages: usize,
1365    lines: usize,
1366    chars: usize,
1367}
1368
1369impl TextLayerTally {
1370    pub fn add(&mut self, page: &crate::pdfium_backend::PdfPage) {
1371        self.pages += 1;
1372        self.lines += page.cells.len();
1373        self.chars += page
1374            .cells
1375            .iter()
1376            .map(|c| c.text.chars().count())
1377            .sum::<usize>();
1378    }
1379
1380    /// The verdict over the pages added so far.
1381    pub fn is_vestigial(&self) -> bool {
1382        self.lines == 0 || (self.lines <= self.pages && self.chars < 32)
1383    }
1384
1385    /// Whether the pages added so far already rule vestigial out for a
1386    /// document of `total_pages`, whatever the remaining pages hold — both
1387    /// counts only grow, so a caller may stop parsing pages it does not need.
1388    pub fn proves_text(&self, total_pages: usize) -> bool {
1389        self.lines > 0 && (self.lines > total_pages || self.chars >= 32)
1390    }
1391}
1392
1393/// Why the cross-reference repair did or did not fire, for the `text_layer`
1394/// diagnostic. A PDF that will not load is indistinguishable from a scan in
1395/// production (both convert to nothing), so the reason has to be askable.
1396pub fn xref_repair_status(bytes: &[u8]) -> String {
1397    if Document::load_mem(bytes).is_ok() {
1398        return "loads unaided; no repair needed".into();
1399    }
1400    match pad_short_xref_entries(bytes) {
1401        Ok(fixed) => match Document::load_mem(&fixed) {
1402            Ok(_) => "repaired: cross-reference entries padded to 20 bytes".into(),
1403            Err(e) => format!("padded the entries, but it still will not load: {e}"),
1404        },
1405        Err(why) => format!("repair declined — {why}"),
1406    }
1407}
1408
1409/// Load a PDF, repairing the one malformation that otherwise costs us the whole
1410/// document: **19-byte cross-reference entries**.
1411///
1412/// The spec fixes an xref entry at 20 bytes — `nnnnnnnnnn ggggg n` plus a
1413/// *two*-byte EOL. Some generators (an Austrian telecom's invoices, for one)
1414/// emit a bare LF instead, making each entry 19 bytes. lopdf rejects the file
1415/// outright (`invalid file trailer`) where pdfium reads it happily, so a
1416/// perfectly good text layer looked to the browser exactly like a scan and cost
1417/// ten seconds of OCR.
1418///
1419/// Padding is only attempted when it cannot move anything the xref points at:
1420/// a single `xref` section that begins after the last object. The repair then
1421/// has to prove itself — the padded bytes are used only if they load — so a
1422/// mis-repair degrades to today's behaviour rather than to silent garbage.
1423pub(crate) fn load_document(bytes: &[u8]) -> Option<Document> {
1424    open_document(bytes, None).ok()
1425}
1426
1427/// Why [`open_document`] could not hand back a readable document.
1428#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1429pub(crate) enum OpenError {
1430    /// lopdf cannot read the file even after the repairs.
1431    Unreadable,
1432    /// The file is encrypted and the password given (or none) does not open it.
1433    Password,
1434}
1435
1436/// Load `bytes` with the document's password. lopdf decrypts while reading —
1437/// with `password`, or the empty user password most "protected" PDFs carry
1438/// (what every viewer opens silently) — so every reader downstream sees plain
1439/// streams; a file the password does not open loads with its streams still
1440/// encrypted, which is reported as [`OpenError::Password`] rather than handed
1441/// on as a document whose every stream decodes to nothing.
1442pub(crate) fn open_document(bytes: &[u8], password: Option<&str>) -> Result<Document, OpenError> {
1443    let Some(doc) = load_document_raw(bytes, password) else {
1444        // lopdf refuses to load at all under a *wrong* password (a missing
1445        // one loads the file with its streams still encrypted); tell the two
1446        // apart by loading without it.
1447        if password.is_some() && load_document_raw(bytes, None).is_some_and(|d| d.is_encrypted()) {
1448            return Err(OpenError::Password);
1449        }
1450        return Err(OpenError::Unreadable);
1451    };
1452    if doc.is_encrypted() {
1453        return Err(OpenError::Password);
1454    }
1455    Ok(doc)
1456}
1457
1458fn load_options(password: Option<&str>) -> lopdf::LoadOptions {
1459    lopdf::LoadOptions {
1460        password: password.map(str::to_string),
1461        ..lopdf::LoadOptions::default()
1462    }
1463}
1464
1465fn load_document_raw(bytes: &[u8], password: Option<&str>) -> Option<Document> {
1466    // Try progressively more repair, and accept a candidate only once the pages
1467    // actually carry content — a document whose streams were dropped still
1468    // "loads", so loading alone is not evidence the repair helped. A
1469    // well-formed file returns on the first attempt and pays for nothing.
1470    let mut fallback = None;
1471    if let Some(doc) = best_effort_load(bytes, password, &mut fallback) {
1472        return Some(doc);
1473    }
1474    let xref_fixed = pad_short_xref_entries(bytes).ok();
1475    if let Some(fixed) = &xref_fixed {
1476        if let Some(doc) = best_effort_load(fixed, password, &mut fallback) {
1477            return Some(doc);
1478        }
1479    }
1480    // Both defects can coexist, and the second only becomes visible once the
1481    // first is repaired, so build on whatever the previous step produced.
1482    let lengths_fixed = fix_stream_lengths(xref_fixed.as_deref().unwrap_or(bytes));
1483    if let Some(doc) = best_effort_load(&lengths_fixed, password, &mut fallback) {
1484        return Some(doc);
1485    }
1486    fallback
1487}
1488
1489/// Load `data`, returning it only when its pages carry content; a document that
1490/// merely parses is remembered as the fallback for when nothing does better.
1491fn best_effort_load(
1492    data: &[u8],
1493    password: Option<&str>,
1494    fallback: &mut Option<Document>,
1495) -> Option<Document> {
1496    match Document::load_mem_with_options(data, load_options(password)) {
1497        Ok(doc) if has_page_content(&doc) => Some(doc),
1498        Ok(doc) => {
1499            fallback.get_or_insert(doc);
1500            None
1501        }
1502        Err(_) => None,
1503    }
1504}
1505
1506/// Does any page actually hand us a content stream? A document whose streams
1507/// were dropped still parses — it simply has nothing to read — so this is what
1508/// tells a successful repair from a pointless one.
1509fn has_page_content(doc: &Document) -> bool {
1510    doc.get_pages()
1511        .into_values()
1512        .take(4)
1513        .any(|pid| !page_content(doc, pid).is_empty())
1514}
1515
1516/// Correct `/Length` values that disagree with where `endstream` actually is.
1517///
1518/// The same generator that writes short xref entries also overstates its
1519/// content-stream lengths by a byte or two. lopdf trusts `/Length`, reads past
1520/// the data, fails to find `endstream` there and drops the stream — the object
1521/// comes back as a bare dictionary, so the page has no content at all and the
1522/// document looks like a scan. pdfium instead trusts `endstream`, which is what
1523/// this does.
1524///
1525/// The rewrite is length-preserving: the corrected number is written over the
1526/// old digits and padded with spaces, so every byte offset in the file — and
1527/// therefore the whole cross-reference table — stays valid.
1528fn fix_stream_lengths(bytes: &[u8]) -> Vec<u8> {
1529    let mut out = bytes.to_vec();
1530    let mut i = 0;
1531    while let Some(rel) = find(&out[i..], b"stream") {
1532        let kw = i + rel;
1533        i = kw + 6;
1534        // Skip `endstream` (the keyword we are measuring *to*).
1535        if kw >= 3 && &out[kw - 3..kw] == b"end" {
1536            continue;
1537        }
1538        // The stream data starts after the EOL that follows the keyword.
1539        let mut data = kw + 6;
1540        if out.get(data..data + 2) == Some(b"\r\n".as_slice()) {
1541            data += 2;
1542        } else if matches!(out.get(data), Some(b'\n' | b'\r')) {
1543            data += 1;
1544        }
1545        let Some(end) = find(&out[data..], b"endstream").map(|r| data + r) else {
1546            continue;
1547        };
1548        // `/Length <digits>` in the dictionary just before the keyword.
1549        let dict_start = out[..kw].iter().rposition(|&c| c == b'<').unwrap_or(0);
1550        let Some(lrel) = find(&out[dict_start..kw], b"/Length") else {
1551            continue;
1552        };
1553        let mut d = dict_start + lrel + 7;
1554        while matches!(out.get(d), Some(b' ')) {
1555            d += 1;
1556        }
1557        let digits = out[d..].iter().take_while(|c| c.is_ascii_digit()).count();
1558        if digits == 0 {
1559            continue;
1560        }
1561        let declared: usize = match std::str::from_utf8(&out[d..d + digits])
1562            .ok()
1563            .and_then(|s| s.parse().ok())
1564        {
1565            Some(v) => v,
1566            None => continue,
1567        };
1568        let actual = end - data;
1569        // Only shrink, and only when the new value fits the space the old one
1570        // occupied — growing the number would move every following byte.
1571        let replacement = actual.to_string();
1572        if actual == declared || replacement.len() > digits {
1573            continue;
1574        }
1575        out[d..d + digits].fill(b' ');
1576        out[d..d + replacement.len()].copy_from_slice(replacement.as_bytes());
1577    }
1578    out
1579}
1580
1581fn find(haystack: &[u8], needle: &[u8]) -> Option<usize> {
1582    haystack.windows(needle.len()).position(|w| w == needle)
1583}
1584
1585/// Rewrite a classic cross-reference table's entries to the spec's 20 bytes,
1586/// or `None` when the file's shape makes that unsafe (see [`load_document`]).
1587pub(crate) fn pad_short_xref_entries(bytes: &[u8]) -> Result<Vec<u8>, &'static str> {
1588    // Exactly one xref section, and it must start after every object, so that
1589    // growing it shifts nothing the table's offsets refer to.
1590    let is_boundary = |i: usize| i == 0 || matches!(bytes[i - 1], b'\n' | b'\r');
1591    let mut starts = (0..bytes.len().saturating_sub(4))
1592        .filter(|&i| &bytes[i..i + 4] == b"xref" && is_boundary(i));
1593    let xref_at = starts
1594        .next()
1595        .ok_or("no classic `xref` section (an xref stream?)")?;
1596    if starts.next().is_some() {
1597        return Err("more than one xref section (incremental update)");
1598    }
1599    let last_obj = bytes
1600        .windows(3)
1601        .rposition(|w| w == b"obj")
1602        .ok_or("no objects found")?;
1603    if last_obj > xref_at {
1604        return Err("an object follows the xref — padding would move it");
1605    }
1606
1607    let mut out = bytes[..xref_at].to_vec();
1608    out.extend_from_slice(b"xref\n");
1609    let mut i = xref_at + 4;
1610    let skip_ws = |i: &mut usize| {
1611        while matches!(bytes.get(*i), Some(b'\r' | b'\n' | b' ')) {
1612            *i += 1;
1613        }
1614    };
1615    loop {
1616        skip_ws(&mut i);
1617        // Either the next subsection header ("first count") or the trailer.
1618        if bytes[i..].starts_with(b"trailer") {
1619            out.extend_from_slice(&bytes[i..]);
1620            return Ok(out);
1621        }
1622        let header_end = i + bytes[i..]
1623            .iter()
1624            .position(|c| matches!(c, b'\n' | b'\r'))
1625            .ok_or("subsection header runs off the end")?;
1626        let header = std::str::from_utf8(&bytes[i..header_end])
1627            .map_err(|_| "subsection header is not text")?
1628            .trim();
1629        let mut parts = header.split_whitespace();
1630        let count: usize = parts
1631            .nth(1)
1632            .and_then(|c| c.parse().ok())
1633            .ok_or("unparseable subsection header")?;
1634        if parts.next().is_some() || count == 0 {
1635            return Err("unexpected subsection header shape");
1636        }
1637        out.extend_from_slice(header.as_bytes());
1638        out.push(b'\n');
1639        i = header_end;
1640        for _ in 0..count {
1641            skip_ws(&mut i);
1642            // `nnnnnnnnnn ggggg n` — the 18 bytes before whatever EOL follows.
1643            let entry = bytes.get(i..i + 18).ok_or("xref entry runs off the end")?;
1644            let well_formed = entry[..10].iter().all(u8::is_ascii_digit)
1645                && entry[10] == b' '
1646                && entry[11..16].iter().all(u8::is_ascii_digit)
1647                && entry[16] == b' '
1648                && matches!(entry[17], b'n' | b'f');
1649            if !well_formed {
1650                return Err("xref entry is not `nnnnnnnnnn ggggg n`");
1651            }
1652            out.extend_from_slice(entry);
1653            out.extend_from_slice(b" \n"); // the spec's 2-byte EOL -> 20 bytes
1654            i += 18;
1655        }
1656    }
1657}
1658
1659/// Debug: raw glyph stream `(ch, ll, lr, lb, lt)` (native coords) for page
1660/// `index`, before the sanitizer. For comparing char cells to docling-parse.
1661pub fn debug_glyphs(bytes: &[u8], index: usize) -> Vec<(char, f32, f32, f32, f32)> {
1662    let Some(doc) = load_document(bytes) else {
1663        return Vec::new();
1664    };
1665    let mut pages: Vec<_> = doc.get_pages().into_iter().collect();
1666    pages.sort_by_key(|(n, _)| *n);
1667    let Some((_, pid)) = pages.get(index) else {
1668        return Vec::new();
1669    };
1670    page_glyphs(&doc, *pid)
1671        .into_iter()
1672        .map(|g| (g.ch, g.ll, g.lr, g.lb, g.lt))
1673        .collect()
1674}
1675
1676/// Public entry: per-page (width, height, line cells) for a PDF, via the Rust
1677/// text parser + the docling-parse line sanitizer. Used by the pipeline and the
1678/// `textparse_dump` example.
1679pub fn pdf_textlines(bytes: &[u8]) -> Vec<(f32, f32, Vec<crate::pdfium_backend::TextCell>)> {
1680    let Some(doc) = load_document(bytes) else {
1681        return Vec::new();
1682    };
1683    let mut caches = DocCaches::default();
1684    let mut pages: Vec<_> = doc.get_pages().into_iter().collect();
1685    pages.sort_by_key(|(n, _)| *n);
1686    pages
1687        .into_iter()
1688        .map(|(_, pid)| {
1689            let (w, h) = page_size(&doc, pid);
1690            let glyphs = page_glyphs_cached(&doc, pid, &mut caches);
1691            let cells = crate::dp_lines::line_cells(&glyphs, h, true);
1692            (w, h, cells)
1693        })
1694        .collect()
1695}
1696
1697/// Debug/diagnostic entry: per-page (width, height, word cells) for a PDF, via
1698/// the Rust parser glyphs run through the docling-parse word grouping. Used to
1699/// compare parser word cells against docling-parse's `word_cells` oracle (roadmap
1700/// item 6).
1701pub fn pdf_words(bytes: &[u8]) -> Vec<(f32, f32, Vec<crate::pdfium_backend::TextCell>)> {
1702    let Some(doc) = load_document(bytes) else {
1703        return Vec::new();
1704    };
1705    let mut caches = DocCaches::default();
1706    let mut pages: Vec<_> = doc.get_pages().into_iter().collect();
1707    pages.sort_by_key(|(n, _)| *n);
1708    pages
1709        .into_iter()
1710        .map(|(_, pid)| {
1711            let (w, h) = page_size(&doc, pid);
1712            let glyphs = page_glyphs_cached(&doc, pid, &mut caches);
1713            let cells = crate::dp_lines::word_cells(&glyphs, h, true);
1714            (w, h, cells)
1715        })
1716        .collect()
1717}
1718
1719/// One page's text cells from the pure-Rust parser: prose line cells, per-word
1720/// cells, and code line cells — all from a single glyph parse. Replaces the
1721/// pdfium text path (roadmap item 6) when the parser drop is enabled.
1722#[derive(Default)]
1723pub struct PageParserCells {
1724    pub prose: Vec<crate::pdfium_backend::TextCell>,
1725    pub words: Vec<crate::pdfium_backend::TextCell>,
1726    pub code: Vec<crate::pdfium_backend::TextCell>,
1727    /// Drawn checkbox squares (#609), in the cells' frame.
1728    pub checkboxes: Vec<crate::checkbox::CheckBox>,
1729    /// Image placements (#999), in the cells' frame — see
1730    /// [`crate::pdfium_backend::PdfPage::bitmaps`].
1731    pub bitmaps: Vec<[f32; 4]>,
1732    /// The page's shapes for the reading-order separators (#1092).
1733    pub shapes: PageShapes,
1734}
1735
1736/// The parser text layer, driven one page at a time: the document is loaded
1737/// (and repaired, see [`load_document`]) once, the font/form caches persist
1738/// across pages, and each page's glyphs are parsed only when asked for.
1739///
1740/// The eager whole-document walk this replaces ran *before* the first page
1741/// was rendered, so on a long PDF it was a serial prefix the page-worker pool
1742/// sat idle through — 6.2 s on the 1913-page .NET reference, in front of a
1743/// pipeline that otherwise overlaps parsing with inference — and a `--pages`
1744/// window still paid for every page in the file. Pulling pages on demand
1745/// keeps the parse on the producer thread but interleaved with rendering,
1746/// and skips unselected pages entirely. Output per page is unchanged: same
1747/// glyph walk, same shared caches, same contraction.
1748pub struct PageTextParser {
1749    doc: Document,
1750    caches: DocCaches,
1751    /// Page object ids in document order (page 1 first).
1752    pages: Vec<lopdf::ObjectId>,
1753    /// How words split where no space glyph does (#921); from
1754    /// `DOCLING_RS_PDF_WORD_GAP` unless [`Self::set_word_gap`] says.
1755    word_gap: crate::dp_lines::WordGap,
1756    /// Whether [`Self::text_page`]'s page keeps typographic punctuation as
1757    /// drawn (#921); `DOCLING_RS_PDF_KEEP_TYPOGRAPHY` unless
1758    /// [`Self::set_keep_typography`] says.
1759    keep_typography: bool,
1760}
1761
1762impl PageTextParser {
1763    /// Load the document; `None` when lopdf cannot read it at all.
1764    pub fn open(bytes: &[u8]) -> Option<Self> {
1765        Self::open_with_password(bytes, None)
1766    }
1767
1768    /// [`open`](Self::open) with the document's password (an encrypted file
1769    /// the password does not open reads as `None` here; the pipeline reports
1770    /// it through [`crate::pdf_meta::PdfMeta::open_with_password`] first).
1771    pub fn open_with_password(bytes: &[u8], password: Option<&str>) -> Option<Self> {
1772        let doc = open_document(bytes, password).ok()?;
1773        let mut pages: Vec<_> = doc.get_pages().into_iter().collect();
1774        pages.sort_by_key(|(n, _)| *n);
1775        Some(Self {
1776            doc,
1777            caches: DocCaches::default(),
1778            pages: pages.into_iter().map(|(_, pid)| pid).collect(),
1779            word_gap: crate::dp_lines::WordGap::from_env(),
1780            keep_typography: crate::assemble::keep_typography_from_env(),
1781        })
1782    }
1783
1784    /// The word-gap rule the line and word cells are built with (#921);
1785    /// `None` keeps the environment's (`DOCLING_RS_PDF_WORD_GAP`, else
1786    /// `adaptive`).
1787    pub fn set_word_gap(&mut self, gap: Option<crate::dp_lines::WordGap>) {
1788        if let Some(g) = gap {
1789            self.word_gap = g;
1790        }
1791    }
1792
1793    /// Whether the pages [`Self::text_page`] builds keep typographic
1794    /// punctuation as drawn (#921); `None` keeps the environment's
1795    /// (`DOCLING_RS_PDF_KEEP_TYPOGRAPHY`, else folding).
1796    pub fn set_keep_typography(&mut self, keep: Option<bool>) {
1797        if let Some(k) = keep {
1798            self.keep_typography = k;
1799        }
1800    }
1801
1802    /// The glyph boxes and font styles of the 0-based page `index` — the
1803    /// heading-hierarchy stage's style signal (#302): every non-space glyph's
1804    /// box (font ascent + descent at its size — the font-size proxy pdfium's
1805    /// loose char box also gave) in top-left coordinates, with the weight
1806    /// class and slant its `/BaseFont` name declares. Empty for a page
1807    /// without a text layer (a scan), and the stage falls back to its other
1808    /// signals.
1809    pub(crate) fn glyph_styles(
1810        &mut self,
1811        index: usize,
1812    ) -> Vec<crate::heading_hierarchy::GlyphStyle> {
1813        let Some(&pid) = self.pages.get(index) else {
1814            return Vec::new();
1815        };
1816        let (_w, h) = page_size(&self.doc, pid);
1817        let glyphs = page_glyphs_cached(&self.doc, pid, &mut self.caches);
1818        // Font hash → style, over the fonts the walk just parsed (an inline,
1819        // uncached font dictionary reads as unstyled).
1820        let styles: HashMap<u64, crate::font_style::FontStyle> = self
1821            .caches
1822            .fonts
1823            .values()
1824            .map(|f| (f.hash, f.style))
1825            .collect();
1826        glyphs
1827            .iter()
1828            .filter(|g| !g.ch.is_whitespace() && g.ll.is_finite())
1829            .map(|g| {
1830                let st = styles.get(&g.font).copied().unwrap_or_default();
1831                crate::heading_hierarchy::GlyphStyle {
1832                    l: g.ll,
1833                    t: h - g.lt,
1834                    r: g.lr,
1835                    b: h - g.lb,
1836                    height: g.height(),
1837                    weight_cls: crate::font_style::weight_class(st.weight),
1838                    italic: st.italic,
1839                    styled: st.known,
1840                }
1841            })
1842            .collect()
1843    }
1844
1845    /// The characters of the 0-based page `index` as the script-position
1846    /// stage measures them (#1005, docling's `read_page_chars`): every
1847    /// visible, non-blank glyph with its font-metric box, baseline and drawn
1848    /// size in the unrotated page frame (y up), and beside it the same box in
1849    /// the display frame (`/Rotate` applied, top-left origin: the frame the
1850    /// items' boxes live in). Invisible text (`Tr` 3 / 7, an OCR layer over a
1851    /// scan) is left out, as docling leaves it: it follows the scanned lines,
1852    /// not a typeset baseline.
1853    pub(crate) fn script_chars(
1854        &mut self,
1855        index: usize,
1856    ) -> Vec<(crate::script_position::ScriptChar, [f32; 4])> {
1857        let Some(&pid) = self.pages.get(index) else {
1858            return Vec::new();
1859        };
1860        let (w, h) = page_size(&self.doc, pid);
1861        let rotation = page_rotation(&self.doc, pid);
1862        page_glyphs_cached(&self.doc, pid, &mut self.caches)
1863            .iter()
1864            .filter(|g| !g.invisible && !g.ch.is_whitespace() && g.ll.is_finite())
1865            .filter_map(|g| {
1866                let [_, y, size] = g.pen?;
1867                let c = crate::script_position::ScriptChar {
1868                    text: g.ch,
1869                    left: g.ll,
1870                    bottom: g.lb,
1871                    right: g.lr,
1872                    top: g.lt,
1873                    baseline: y,
1874                    size,
1875                    horizontal: g.quad.is_none(),
1876                };
1877                let (l, t, r, b) = crate::pdfium_backend::to_display_frame(
1878                    (g.ll, h - g.lt, g.lr, h - g.lb),
1879                    rotation,
1880                    w,
1881                    h,
1882                );
1883                Some((c, [l, t, r, b]))
1884            })
1885            .collect()
1886    }
1887
1888    /// Prose, word and code cells of the 0-based page `index` — empty for an
1889    /// index the parser's page tree doesn't have (a damaged file whose page
1890    /// tree disagrees with the object model's count).
1891    pub fn cells(&mut self, index: usize) -> PageParserCells {
1892        let Some(&pid) = self.pages.get(index) else {
1893            return PageParserCells::default();
1894        };
1895        let (_w, h) = page_size(&self.doc, pid);
1896        let (glyphs, inks, bitmaps, shapes) =
1897            page_glyphs_and_inks(&self.doc, pid, &mut self.caches);
1898        let (prose, words) =
1899            crate::dp_lines::line_and_word_cells_with(&glyphs, h, true, self.word_gap);
1900        PageParserCells {
1901            prose,
1902            words,
1903            code: crate::pdfium_backend::code_cells_from_glyphs(&glyphs, h),
1904            checkboxes: crate::checkbox::find(&inks, h),
1905            bitmaps,
1906            shapes,
1907        }
1908    }
1909
1910    /// Pages in the document's page tree.
1911    pub fn page_count(&self) -> usize {
1912        self.pages.len()
1913    }
1914
1915    /// The 0-based page `index` as the text-layer-only conversion sees it —
1916    /// one element of [`pdf_text_pages`], parsed on demand so a caller can
1917    /// drop each page once it is assembled instead of holding the whole
1918    /// document's cells. A blank page (no cells) for an index the page tree
1919    /// doesn't have.
1920    pub fn text_page(&mut self, index: usize) -> crate::pdfium_backend::PdfPage {
1921        let (w, h, (glyphs, inks, _, shapes)) = match self.pages.get(index) {
1922            Some(&pid) => {
1923                let (w, h) = page_size(&self.doc, pid);
1924                (w, h, page_glyphs_and_inks(&self.doc, pid, &mut self.caches))
1925            }
1926            None => (0.0, 0.0, Default::default()),
1927        };
1928        let (mut prose, mut words) =
1929            crate::dp_lines::line_and_word_cells_with(&glyphs, h, true, self.word_gap);
1930        drop_overpainted_cells(&mut prose);
1931        drop_overpainted_cells(&mut words);
1932        crate::pdfium_backend::PdfPage {
1933            #[cfg(feature = "ocr-prep")]
1934            image_layout: None,
1935            width: w,
1936            height: h,
1937            // Cells are native PDF points; there is no rendered bitmap.
1938            scale: 1.0,
1939            cells: prose,
1940            code_cells: crate::pdfium_backend::code_cells_from_glyphs(&glyphs, h),
1941            word_cells: words,
1942            checkboxes: crate::checkbox::find(&inks, h),
1943            bitmaps: Vec::new(),
1944            shapes,
1945            #[cfg(feature = "ocr-prep")]
1946            image: image::RgbImage::new(1, 1),
1947            links: Vec::new(),
1948            rotation: 0,
1949            keep_typography: self.keep_typography,
1950            #[cfg(feature = "render")]
1951            embedded_images: Vec::new(),
1952            #[cfg(feature = "render")]
1953            pending_image: None,
1954        }
1955    }
1956}
1957
1958/// Full parser text layer: prose + word + code cells per page, glyphs parsed once.
1959/// `prose`/`words` come from the docling-parse contraction ([`crate::dp_lines`]);
1960/// `code` splits only at the parser's own space glyphs (monospace keeps its
1961/// source spacing). The eager form of [`PageTextParser`].
1962pub fn pdf_all_cells(bytes: &[u8]) -> Vec<PageParserCells> {
1963    let Some(mut parser) = PageTextParser::open(bytes) else {
1964        return Vec::new();
1965    };
1966    (0..parser.pages.len()).map(|i| parser.cells(i)).collect()
1967}
1968
1969/// Whole pages for the text-layer-only conversion ([`crate::convert_text_layer`]):
1970/// the parser's prose/word/code cells plus page geometry, assembled into
1971/// [`PdfPage`]s with no rendered image and no link annotations. Everything here
1972/// is pure Rust (lopdf), so it compiles without the `ml` feature — including on
1973/// wasm32. A page the parser can't read (no text layer) comes back with empty
1974/// cells; there is no pdfium fallback on this path.
1975pub fn pdf_text_pages(bytes: &[u8]) -> Vec<crate::pdfium_backend::PdfPage> {
1976    let Some(mut parser) = PageTextParser::open(bytes) else {
1977        return Vec::new();
1978    };
1979    (0..parser.page_count())
1980        .map(|i| parser.text_page(i))
1981        .collect()
1982}
1983
1984/// Drop line cells that are *painted over each other* — glyphs used as artwork.
1985///
1986/// Some generators draw their logo with a symbol font: on the reporting
1987/// invoice, a `TeleLogo` Type1 paints the T-Mobile mark by stacking the glyphs
1988/// encoded as `"` and `==` on top of one another, and the flat text-layer
1989/// output opened with that garbage. Nothing in the font metadata gives it away
1990/// (the *text* fonts in the same file are also flagged symbolic, and the logo
1991/// font names its glyphs `quotedbl` &c.), but the geometry does: two cells with
1992/// different text where one lies inside the other on the same line is
1993/// physically impossible for prose — ink from two words never occupies the
1994/// same box. Both cells of such a pair are paint, not text.
1995///
1996/// Containment (not mere overlap) keeps this narrow: adjacent words touch but
1997/// never contain each other, and a same-text near-duplicate (double-draw faux
1998/// bold) is left alone for the sanitizer's usual handling. Applied on the
1999/// flat/browser path only — the ML pipeline's text layer is byte-pinned by the
2000/// PDF corpus, and there the layout model already sinks logo marks into
2001/// `picture` regions.
2002fn drop_overpainted_cells(cells: &mut Vec<crate::pdfium_backend::TextCell>) {
2003    let mut paint = vec![false; cells.len()];
2004    for i in 0..cells.len() {
2005        for j in 0..cells.len() {
2006            if i == j || cells[i].text == cells[j].text {
2007                continue;
2008            }
2009            let (a, b) = (&cells[i], &cells[j]);
2010            // Same line band: the vertical overlap covers most of the shorter.
2011            let vo = (a.b.min(b.b) - a.t.max(b.t)).max(0.0);
2012            if vo < 0.6 * (a.b - a.t).min(b.b - b.t) {
2013                continue;
2014            }
2015            // … and the two sit at one height. The overlap alone says nothing
2016            // when the font's vertical metrics are inflated (#1129: a face
2017            // whose ascent and descent make every cell 55 pt tall on lines
2018            // 11.7 pt apart — each line overlaps the next by four fifths, and
2019            // a short line under a long one read as paint: 37 of the page's
2020            // 44 lines went, and its table with them. That face has a cap
2021            // height and its boxes are scaled back now,
2022            // `font_ascent_descent`; one without is boxed as it claims). A
2023            // cell's height is the font's claim; its width per character is
2024            // what was drawn, and lines of prose are never set closer than
2025            // that, so a shift of more than half of it is another line,
2026            // however tall the boxes.
2027            let shift = ((a.t + a.b) - (b.t + b.b)).abs() / 2.0;
2028            if shift > 0.5 * a.mean_advance().min(b.mean_advance()) {
2029                continue;
2030            }
2031            // `a` horizontally inside `b` (with a small tolerance).
2032            let ho = (a.r.min(b.r) - a.l.max(b.l)).max(0.0);
2033            if ho >= 0.8 * (a.r - a.l) && (a.r - a.l) <= (b.r - b.l) {
2034                paint[i] = true;
2035                paint[j] = true;
2036            }
2037        }
2038    }
2039    let mut keep = paint.iter().map(|p| !p);
2040    cells.retain(|_| keep.next().unwrap());
2041}
2042
2043/// The text-state scalars inherited by a Form XObject when it is invoked via
2044/// `Do` (the PDF graphics state includes the text parameters, but not the text
2045/// matrices, which a form re-establishes inside its own `BT`/`ET`).
2046#[derive(Clone, Copy)]
2047struct TextState {
2048    tc: f64,
2049    tw: f64,
2050    th: f64,
2051    tl: f64,
2052    trise: f64,
2053    fsize: f64,
2054    /// The text rendering mode (`Tr`).
2055    tr: i64,
2056}
2057
2058impl TextState {
2059    const INIT: TextState = TextState {
2060        tc: 0.0,
2061        tw: 0.0,
2062        th: 1.0,
2063        tl: 0.0,
2064        trise: 0.0,
2065        fsize: 0.0,
2066        tr: 0,
2067    };
2068}
2069
2070/// pdfium's `CPDF_Page::GetPageRotation` — the inherited `/Rotate`, in
2071/// quarter turns, as degrees (`pdf_meta`'s rule).
2072fn page_rotation(doc: &Document, pid: lopdf::ObjectId) -> u16 {
2073    let mut id = pid;
2074    for _ in 0..32 {
2075        let Ok(dict) = doc.get_dictionary(id) else {
2076            return 0;
2077        };
2078        if let Some(obj) = dict.get(b"Rotate").ok().and_then(|o| deref(doc, o)) {
2079            let quarter = (num(obj).unwrap_or(0.0) as i64 / 90).rem_euclid(4);
2080            return (quarter * 90) as u16;
2081        }
2082        match dict.get(b"Parent").ok().and_then(|o| o.as_reference().ok()) {
2083            Some(parent) => id = parent,
2084            None => return 0,
2085        }
2086    }
2087    0
2088}
2089
2090/// The effective `/Resources` dictionary for a page: its own (inline or via
2091/// reference), else the nearest ancestor's in the page tree — ISO 32000-1
2092/// 7.7.3.4 makes `/Resources` inheritable. Walked by hand rather than through
2093/// lopdf's `get_page_resources`, which collects an ancestor's `/Resources`
2094/// only when it is an indirect reference: an *inline* dictionary on the
2095/// `/Pages` node — the R&OS php pdf writer puts the one font there and gives
2096/// each page only `/Type`, `/Parent` and `/Contents` (#1130) — was dropped,
2097/// every font went missing and the whole text layer read as empty. A
2098/// `/Resources` that does not resolve to a dictionary is skipped in favour of
2099/// the next ancestor's (pdf.js and poppler read such files the same way).
2100pub(crate) fn page_res(doc: &Document, page_id: lopdf::ObjectId) -> Option<&Dictionary> {
2101    let mut id = page_id;
2102    // The page-tree depth lopdf itself tolerates; also ends a `/Parent` cycle.
2103    for _ in 0..32 {
2104        let dict = doc.get_object(id).ok()?.as_dict().ok()?;
2105        if let Some(res) = dict.get(b"Resources").ok().and_then(|o| as_dict(doc, o)) {
2106            return Some(res);
2107        }
2108        id = dict.get(b"Parent").ok()?.as_reference().ok()?;
2109    }
2110    None
2111}
2112
2113/// Build the code→[`Font`] map for a resources dictionary's `/Font` sub-dict,
2114/// reusing the per-document cache for fonts referenced indirectly (the common
2115/// case — the same font objects recur on every page).
2116fn fonts_from_res(
2117    doc: &Document,
2118    res: &Dictionary,
2119    caches: &mut DocCaches,
2120) -> HashMap<Vec<u8>, Arc<Font>> {
2121    let mut map = HashMap::new();
2122    let font_dict = res
2123        .get(b"Font")
2124        .ok()
2125        .and_then(|o| deref(doc, o))
2126        .and_then(|o| o.as_dict().ok());
2127    if let Some(fd) = font_dict {
2128        for (name, value) in fd.iter() {
2129            let font = match value {
2130                Object::Reference(id) => {
2131                    let key = (*id, name.clone());
2132                    if let Some(f) = caches.fonts.get(&key) {
2133                        Arc::clone(f)
2134                    } else if let Some(fdict) = deref(doc, value).and_then(|o| o.as_dict().ok()) {
2135                        let f = Arc::new(parse_font(doc, name, fdict));
2136                        caches.fonts.insert(key, Arc::clone(&f));
2137                        f
2138                    } else {
2139                        continue;
2140                    }
2141                }
2142                _ => {
2143                    if let Some(fdict) = deref(doc, value).and_then(|o| o.as_dict().ok()) {
2144                        Arc::new(parse_font(doc, name, fdict))
2145                    } else {
2146                        continue;
2147                    }
2148                }
2149            };
2150            map.insert(name.clone(), font);
2151        }
2152    }
2153    map
2154}
2155
2156/// Extract every glyph on a page as a native-coordinate [`Glyph`].
2157/// [`PageTextParser::glyph_styles`] for the given **1-based** pages of a
2158/// document, keyed by page number — a separate, on-demand pass (no
2159/// rendering), so the extraction pipeline stays byte-identical whether or not
2160/// the heading-hierarchy stage runs. Empty when lopdf cannot open the file.
2161pub(crate) fn glyph_styles(
2162    bytes: &[u8],
2163    pages: &[usize],
2164) -> HashMap<usize, Vec<crate::heading_hierarchy::GlyphStyle>> {
2165    let mut out = HashMap::new();
2166    let Some(mut parser) = PageTextParser::open(bytes) else {
2167        return out;
2168    };
2169    for &page_no in pages {
2170        if page_no == 0 {
2171            continue;
2172        }
2173        let styles = parser.glyph_styles(page_no - 1);
2174        if !styles.is_empty() {
2175            out.insert(page_no, styles);
2176        }
2177    }
2178    out
2179}
2180
2181pub(crate) fn page_glyphs(doc: &Document, page_id: lopdf::ObjectId) -> Vec<Glyph> {
2182    page_glyphs_cached(doc, page_id, &mut DocCaches::default())
2183}
2184
2185/// [`page_glyphs`] with an explicit per-document cache, so a multi-page walk
2186/// parses each font / decodes each form once instead of once per page.
2187fn page_glyphs_cached(
2188    doc: &Document,
2189    page_id: lopdf::ObjectId,
2190    caches: &mut DocCaches,
2191) -> Vec<Glyph> {
2192    page_glyphs_and_inks(doc, page_id, caches).0
2193}
2194
2195/// [`page_glyphs_cached`] plus the small painted path pieces the same walk
2196/// passed — what [`crate::checkbox::find`] looks for checkbox squares in
2197/// (#609) — the page's image placements (#999, `[l, t, r, b]` top-left
2198/// page points clipped to the page, the cells' frame), and its shapes for the
2199/// reading-order separators (#1092, [`PageShapes`]).
2200fn page_glyphs_and_inks(
2201    doc: &Document,
2202    page_id: lopdf::ObjectId,
2203    caches: &mut DocCaches,
2204) -> (
2205    Vec<Glyph>,
2206    Vec<crate::checkbox::Ink>,
2207    Vec<[f32; 4]>,
2208    PageShapes,
2209) {
2210    let mut out = Vec::new();
2211    let mut inks = Vec::new();
2212    // The assembled content-stream bytes (an empty Vec when the page has
2213    // none), damaged Flate streams read as far as they inflate (#1154).
2214    let content_bytes = page_content(doc, page_id);
2215    let Ok(content) = lopdf::content::Content::decode(&content_bytes) else {
2216        return (out, inks, Vec::new(), PageShapes::default());
2217    };
2218    let mut bitmaps = Vec::new();
2219    let mut page_shapes = PageShapes::default();
2220    if let Some(res) = page_res(doc, page_id) {
2221        // pdfium's page matrix: user space translated so the display box's
2222        // lower-left corner is the origin (see [`PageBox`]).
2223        let pb = page_box(doc, page_id);
2224        let base = Mat {
2225            e: -(pb.l as f64),
2226            f: -(pb.b as f64),
2227            ..Mat::ID
2228        };
2229        let mut shapes = Shapes::default();
2230        run_content(
2231            doc,
2232            res,
2233            &content,
2234            base,
2235            TextState::INIT,
2236            0,
2237            caches,
2238            &mut out,
2239            &mut inks,
2240            ShapeGs::INIT,
2241            &mut shapes,
2242        );
2243        out.retain(|g| on_page(g, pb.w, pb.h));
2244        drop_overprinted_spaces(&mut out);
2245        drop_letter_spacing_spaces(&mut out);
2246        drop_shadow_runs(&mut out);
2247        let (w, h) = (f64::from(pb.w), f64::from(pb.h));
2248        inks.retain(|ink| match *ink {
2249            crate::checkbox::Ink::Bitmap { l, b, r, t } => {
2250                let (l, r, b, t) = (l.max(0.0), r.min(w), b.max(0.0), t.min(h));
2251                if r > l && t > b {
2252                    bitmaps.push([l as f32, (h - t) as f32, r as f32, (h - b) as f32]);
2253                }
2254                false
2255            }
2256            _ => true,
2257        });
2258        let top_left =
2259            |[l, b, r, t]: [f64; 4]| [l as f32, (h - t) as f32, r as f32, (h - b) as f32];
2260        page_shapes.lines = shapes.lines.into_iter().map(top_left).collect();
2261        if shapes.boxes.len() <= MAX_SHAPE_BOXES {
2262            page_shapes.boxes = connected_boxes(&shapes.boxes)
2263                .into_iter()
2264                .map(top_left)
2265                .collect();
2266        } else {
2267            docling_core::debug_log!(
2268                "textparse: {} painted paths on the page; their boxes are not merged",
2269                shapes.boxes.len()
2270            );
2271        }
2272    }
2273    (out, inks, bitmaps, page_shapes)
2274}
2275
2276/// A page's shapes for the reading-order separators (#1092), in the cells'
2277/// frame (`[l, t, r, b]`, top-left page points): docling-parse's
2278/// `get_shape_lines` and `get_connected_shape_bounding_boxes`.
2279#[derive(Default, Clone, Debug, PartialEq)]
2280pub struct PageShapes {
2281    pub lines: Vec<[f32; 4]>,
2282    pub boxes: Vec<[f32; 4]>,
2283}
2284
2285/// Drop a run of glyphs painted again over itself — a text shadow. A word
2286/// processor exports a heading with a shadow effect as the same run drawn
2287/// twice: the shadow, then the text over it, shifted by a fraction of a point
2288/// (0.5–0.8 pt up and left, black under red, in the manuals that showed it).
2289/// docling-parse keeps both copies and reads `Safety instructions Safety
2290/// instructions`; pdfium's text page, behind docling's pypdfium2 backend,
2291/// drops the second, and the page shows the heading once. A deliberate
2292/// divergence (`docs/MIGRATION.md` §4 item 25): a glyph that repeats an
2293/// earlier one — same character, font and size, its pen shifted from the
2294/// earlier pen by at most 0.15 em on each axis, and by less than the earlier
2295/// glyph's step to its own successor — starts a copy when the glyphs after it
2296/// repeat the earlier one's successors by the same offset and size, and the
2297/// whole stretch that keeps the offset is dropped. Two glyphs at least: a lone
2298/// mark stamped twice is left alone, and so is the per-glyph re-stamp the
2299/// sanitizer already folds (`dp_lines`, the overprint duplicate). Text that
2300/// really repeats sits an advance apart or more — a doubled letter (`ll`,
2301/// 0.22 em in Helvetica), a word set twice (`very very`), the same text on
2302/// the next line or in the next table cell — and is kept, and so is a run of
2303/// one character set tighter than a shadow's shift (dot leaders squeezed by
2304/// `Tc`): its glyph two on is farther than the next one. A line stamped two
2305/// or three times at a small offset to fake bold reads once the same way. The
2306/// original must start within the 1024 glyphs before its copy, so a shadowed
2307/// block longer than that is not caught; a shadowed heading is drawn right
2308/// after itself. A rotated run, whose pen positions are not compared here, is
2309/// left alone.
2310fn drop_shadow_runs(glyphs: &mut Vec<Glyph>) {
2311    // How far back a copy's original may start.
2312    const LOOKBACK: usize = 1024;
2313    // The largest shift of a copy, per axis, in ems of the glyph's size.
2314    const NEAR_EM: f32 = 0.15;
2315    // How much the shift and the size may vary along a copy, in ems.
2316    const SAME_EM: f32 = 0.01;
2317    let pen = |g: &Glyph| if g.quad.is_none() { g.pen } else { None };
2318    let n = glyphs.len();
2319    let mut keep = vec![true; n];
2320    // The glyphs a copy may start on, by character and font, in stream
2321    // order: kept (not part of a copy), upright, sized and not whitespace. A
2322    // copy repeats both, so a glyph walks only its own list back through the
2323    // window; scanning the whole window nearly doubled a `--text-layer-only`
2324    // read of pages without a shadow.
2325    let mut earlier: HashMap<(char, u64), Vec<usize>> = HashMap::new();
2326    let mut j = 0;
2327    while j < n {
2328        let b = &glyphs[j];
2329        // A copy starts where a run starts: not on a glyph that continues
2330        // the one drawn just before it (its pen within an em ahead on the
2331        // same baseline). `PAT` drawn 0.3 pt off `BAT` repeats its `AT`
2332        // at one shift, and lost both letters (#1151); docling-parse keeps
2333        // the word, a different text. A shadow's first glyph follows the
2334        // original's last one — far ahead of it, or behind.
2335        let continues = j > 0
2336            && match (pen(b), pen(&glyphs[j - 1])) {
2337                (Some([xb, yb, sb]), Some([xp, yp, _])) => {
2338                    (yb - yp).abs() <= NEAR_EM * sb && xb > xp && xb - xp <= sb
2339                }
2340                _ => false,
2341            };
2342        let start = pen(b).filter(|p| p[2] > 0.0 && !b.ch.is_whitespace() && !continues);
2343        let mut copy = 0;
2344        if let Some([xj, yj, sj]) = start {
2345            let lo = j.saturating_sub(LOOKBACK);
2346            let candidates = earlier.entry((b.ch, b.font)).or_default();
2347            for &i in candidates.iter().rev().take_while(|&&i| i >= lo) {
2348                let Some([xi, yi, si]) = pen(&glyphs[i]) else {
2349                    continue;
2350                };
2351                if (si - sj).abs() > SAME_EM * sj {
2352                    continue;
2353                }
2354                let (dx, dy) = (xj - xi, yj - yi);
2355                if dx.abs() > NEAR_EM * sj || dy.abs() > NEAR_EM * sj {
2356                    continue;
2357                }
2358                // A shadow is shifted: the characters one glyph expands to
2359                // (a code-like name read as `SM590000`, a decomposed
2360                // ligature) share the glyph's pen and are not a copy.
2361                if dx.abs() + dy.abs() <= SAME_EM * sj {
2362                    continue;
2363                }
2364                // And it lies over its original, nearer to it than the
2365                // original's next glyph is: one character set tighter than
2366                // half the largest shift (dot leaders squeezed by `Tc`) meets
2367                // its own successors at one offset two glyphs on.
2368                if let Some([xn, yn, _]) = glyphs.get(i + 1).and_then(pen) {
2369                    let step = (xn - xi).abs().max((yn - yi).abs());
2370                    if step > SAME_EM * sj && dx.abs().max(dy.abs()) >= step {
2371                        continue;
2372                    }
2373                }
2374                // The copy goes on while each next glyph repeats the
2375                // original's next one by the same shift; the original
2376                // ends before the copy starts.
2377                let mut m = 1;
2378                while j + m < n && i + m < j {
2379                    let (a, b) = (&glyphs[i + m], &glyphs[j + m]);
2380                    let (Some([xa, ya, sa]), Some([xb, yb, sb])) = (pen(a), pen(b)) else {
2381                        break;
2382                    };
2383                    if a.ch != b.ch
2384                        || a.font != b.font
2385                        || (sa - sb).abs() > SAME_EM * sj
2386                        || ((xb - xa) - dx).abs() > SAME_EM * sj
2387                        || ((yb - ya) - dy).abs() > SAME_EM * sj
2388                    {
2389                        break;
2390                    }
2391                    m += 1;
2392                }
2393                if m >= 2 {
2394                    copy = m;
2395                    break;
2396                }
2397            }
2398            if copy == 0 {
2399                candidates.push(j);
2400            }
2401        }
2402        if copy > 0 {
2403            keep[j..j + copy].iter_mut().for_each(|k| *k = false);
2404            j += copy;
2405        } else {
2406            j += 1;
2407        }
2408    }
2409    let mut it = keep.into_iter();
2410    glyphs.retain(|_| it.next().unwrap_or(true));
2411}
2412
2413/// How many marked-content spans may be open for one's `/ActualText` to be
2414/// read (see [`apply_actual_text`]); real documents nest a few.
2415const MAX_ACTUAL_TEXT_DEPTH: usize = 64;
2416
2417/// Put a marked-content span's `/ActualText` in place of the glyphs drawn
2418/// inside it, as docling-parse does since 7.9 (`apply_actual_text`,
2419/// docling-parse#300, on by default; PDF 32000-1 §14.9.4). A writer draws a
2420/// glyph cluster whose characters the font cannot spell this way: a base
2421/// letter and a zero-advance accent whose code collides with a Latin letter
2422/// (`Oreši` read as `OresMi`, docling#3783), or the Arabic marks of a
2423/// LibreOffice font subset whose `/ToUnicode` skips them, so the byte reads as
2424/// WinAnsi (`منعًا` as `منع8ا`). docling-parse's rules, cell for cell: a span
2425/// with no glyphs (over graphics) is left alone, and so is a text implausibly
2426/// long for it (more than 8 characters and 4 per cell: `/Alt` written into
2427/// the wrong key); an empty text removes the glyphs; as many characters as
2428/// cells replace them one by one, keeping each cell's geometry; any other
2429/// count puts the whole text on the span's first cell, over the union of the
2430/// span's boxes, its baseline running to the cell that reaches furthest along
2431/// it (an accent drawn after its base letter trails behind it). Nested spans
2432/// apply innermost first, so the outer text wins. docling-parse has a cell per
2433/// character code; a code whose `/ToUnicode` spells several characters is
2434/// several glyphs here, all on the code's pen, and counts as one cell.
2435///
2436/// Each `EMC` rewrites the glyphs under its span, so a crafted nest of spans
2437/// over the same glyphs would cost glyphs × depth: past
2438/// [`MAX_ACTUAL_TEXT_DEPTH`] open spans, a span still pairs with its `EMC` but
2439/// its `/ActualText` is not read.
2440fn apply_actual_text(out: &mut Vec<Glyph>, begin: usize, text: &str) {
2441    let begin = begin.min(out.len());
2442    let mut cells: Vec<std::ops::Range<usize>> = Vec::new();
2443    for i in begin..out.len() {
2444        match cells.last_mut() {
2445            Some(cell) if out[i].pen.is_some() && out[i].pen == out[cell.end - 1].pen => {
2446                cell.end = i + 1;
2447            }
2448            _ => cells.push(i..i + 1),
2449        }
2450    }
2451    if cells.is_empty() {
2452        return;
2453    }
2454    let chars: Vec<char> = text.chars().collect();
2455    if chars.len() > (4 * cells.len()).max(8) {
2456        return;
2457    }
2458    if chars.is_empty() {
2459        out.truncate(begin);
2460        return;
2461    }
2462    if chars.len() == cells.len() {
2463        // Each cell's first glyph takes its character, the rest of the cell
2464        // goes: one pass, writing behind the cells read.
2465        for (w, (cell, &ch)) in cells.iter().zip(&chars).enumerate() {
2466            out[begin + w] = Glyph {
2467                ch,
2468                ..out[cell.start]
2469            };
2470        }
2471        out.truncate(begin + cells.len());
2472        return;
2473    }
2474    // The leading edge (quad corners 0 and 3) stays the first cell's; the
2475    // trailing one (1 and 2) is the cell's that reaches furthest along the
2476    // baseline, projected on it so a rotated run keeps its direction.
2477    let quad_of = |g: &Glyph| {
2478        g.quad
2479            .unwrap_or([g.ll, g.lb, g.lr, g.lb, g.lr, g.lt, g.ll, g.lt])
2480    };
2481    let mut merged = Glyph { ..out[begin] };
2482    let mut quad = quad_of(&merged);
2483    let dir = (quad[2] - quad[0], quad[3] - quad[1]);
2484    let along = |q: &[f32; 8]| q[2] * dir.0 + q[3] * dir.1;
2485    let mut reach = along(&quad);
2486    for g in &out[begin + 1..] {
2487        merged.l = merged.l.min(g.l);
2488        merged.b = merged.b.min(g.b);
2489        merged.r = merged.r.max(g.r);
2490        merged.t = merged.t.max(g.t);
2491        merged.ll = merged.ll.min(g.ll);
2492        merged.lb = merged.lb.min(g.lb);
2493        merged.lr = merged.lr.max(g.lr);
2494        merged.lt = merged.lt.max(g.lt);
2495        let q = quad_of(g);
2496        if along(&q) > reach {
2497            reach = along(&q);
2498            quad[2..6].copy_from_slice(&q[2..6]);
2499        }
2500    }
2501    if merged.quad.is_some() {
2502        merged.quad = Some(quad);
2503    }
2504    out.truncate(begin);
2505    // The characters of one cell share its box, as a ligature's do.
2506    out.extend(chars.iter().map(|&ch| Glyph { ch, ..merged }));
2507}
2508
2509/// Drop a space glyph the next glyph is drawn over (#992). A typesetter
2510/// that sets a superscript footnote marker as `( 1 )` — space glyphs around
2511/// the raised digit — and then cancels each space's advance with a negative
2512/// `TJ` offset (Arbortext on EUR-Lex: the `1` starts 0.05 pt *before* its
2513/// space begins) renders `(1)`; the spaces exist in the content stream
2514/// only. docling-parse keeps them as characters and its line cell reads
2515/// `( 1 )`; pdftotext and pdfium, which break words by geometry alone,
2516/// read `(1)`, and so does the page. A deliberate divergence
2517/// (`docs/MIGRATION.md` §4 item 22): a space whose successor in stream
2518/// order sits on the same line and starts within the first 30 % of the
2519/// space's advance — the pen went back to (or before) where the space
2520/// began, so it left no gap — is not a character of the text. A space
2521/// followed by a glyph on another line (a trailing space before the
2522/// cursor jumps to the next line's left margin, far to the left of it) or
2523/// by one that starts past that mark (a kerned pair, a justified word gap
2524/// pulled in a little) is kept; the word-gap rules then see the geometry
2525/// as before.
2526fn drop_overprinted_spaces(glyphs: &mut Vec<Glyph>) {
2527    if glyphs.len() < 2 {
2528        return;
2529    }
2530    let overprinted = |sp: &Glyph, next: &Glyph| {
2531        if sp.ch != ' ' || next.ch == ' ' {
2532            return false;
2533        }
2534        // Upright glyphs only: a rotated run's loose boxes are the extents
2535        // of its quads, every glyph of a 90° line shares one left edge and
2536        // the advance runs along y, so the test below would read every
2537        // space of a landscape slide drawn through a 90° `cm` as
2538        // overprinted (`Nullammollis`, odf_presentation_02).
2539        if sp.quad.is_some() || next.quad.is_some() {
2540            return false;
2541        }
2542        let width = sp.lr - sp.ll;
2543        if !width.is_finite() || width <= 0.0 || !next.ll.is_finite() {
2544            return false;
2545        }
2546        // Same line: the loose boxes overlap vertically (a raised digit's box
2547        // still overlaps its neighbours' em boxes).
2548        let same_line = next.lb < sp.lt && next.lt > sp.lb;
2549        same_line && next.ll >= sp.ll - 0.1 * width && next.ll <= sp.ll + 0.3 * width
2550    };
2551    let mut keep = vec![true; glyphs.len()];
2552    for i in 0..glyphs.len() - 1 {
2553        if overprinted(&glyphs[i], &glyphs[i + 1]) {
2554            keep[i] = false;
2555        }
2556    }
2557    let mut it = keep.into_iter();
2558    glyphs.retain(|_| it.next().unwrap_or(true));
2559}
2560
2561/// The share of a space's advance its successor may start at and still have
2562/// taken part of the space back ([`drop_letter_spacing_spaces`]): a word
2563/// space set at its width, or stretched by justification, is at or past 1.
2564const TAKEN_BACK_SPACE: f32 = 0.95;
2565
2566/// How much wider than its letter spacing a letter-spaced line's word spaces
2567/// are, at least ([`drop_letter_spacing_spaces`]). EUR-Lex's headings: 3.
2568const WORD_OVER_LETTER_SPACING: f32 = 1.5;
2569
2570/// Points two letter gaps may differ by and still be one letter spacing —
2571/// `dp_lines`' tolerance for a tracking set without space glyphs (#921): a
2572/// typesetter spaces a word with one cursor move, which rounding blurs.
2573fn letter_spacing_tolerance(gap: f32) -> f32 {
2574    (0.08 * gap).max(0.25)
2575}
2576
2577/// Drop the space glyphs a typesetter spaces the letters of a word with
2578/// (#1139). Arbortext sets a letter-spaced heading (EUR-Lex: `1.1.1. KPI
2579/// bezogen auf den Umsatz (Umsatz-KPI)`) as letter, space glyph, letter, and
2580/// moves the pen after each space: back by a fifth of its advance inside a
2581/// word, forward by one and a half advances between words. On the page that
2582/// is tracking — letters 1.7 pt apart, words 5.1 pt apart — but with a space
2583/// glyph at every letter the line read `K P I b e z o g e n a u f …`, one
2584/// "word" per letter; pdftotext reads the words. docling-parse keeps every
2585/// space glyph as a character, so this is a deliberate divergence like
2586/// [`drop_overprinted_spaces`] (`docs/MIGRATION.md`), and as narrow:
2587///
2588/// * a *chain* is a stretch of the stream where single glyphs and space
2589///   glyphs alternate on one line — every glyph stands alone between two
2590///   spaces, which no run of words does;
2591/// * in it, three or more consecutive spaces between letters, each with part
2592///   of its advance taken back (the next letter starts before
2593///   [`TAKEN_BACK_SPACE`] of it) and all leaving the same gap in points, are
2594///   letter spacing — unless the letters are one character repeated (`C C C
2595///   C`, a row of tokens);
2596/// * every space of the chain that leaves that gap goes with them (the short
2597///   words of the heading, `K P I`, `a u f`; its brackets and hyphen), and
2598///   the others stay: they are the word spaces;
2599/// * those word spaces, and the spaces between the chain and its neighbours,
2600///   have to be plainly wider ([`WORD_OVER_LETTER_SPACING`]). A tightened
2601///   line sets `x y z` between two words with the same shrunken space on
2602///   either side, and kerning pulls a space in before `A`, `V` or `T`:
2603///   there the letters are no closer than the words, and the chain is left
2604///   as it is drawn.
2605///
2606/// The letters then stand apart with no space glyph between them, which is
2607/// what `dp_lines::tracked_gaps` reads as tracking inside one word.
2608fn drop_letter_spacing_spaces(glyphs: &mut Vec<Glyph>) {
2609    let boxed =
2610        |g: &Glyph| g.quad.is_none() && [g.ll, g.lb, g.lr, g.lt].iter().all(|v| v.is_finite());
2611    let same_line = |a: &Glyph, b: &Glyph| b.lb < a.lt && b.lt > a.lb;
2612    // `glyphs[i]`, a space, `glyphs[i + 2]`: two glyphs of one line with one
2613    // space glyph between them, the second to the right of the first.
2614    let link = |i: usize| -> bool {
2615        let (Some(a), Some(sp), Some(b)) = (glyphs.get(i), glyphs.get(i + 1), glyphs.get(i + 2))
2616        else {
2617            return false;
2618        };
2619        a.ch != ' '
2620            && sp.ch == ' '
2621            && b.ch != ' '
2622            && boxed(a)
2623            && boxed(sp)
2624            && boxed(b)
2625            && sp.lr > sp.ll
2626            && same_line(a, sp)
2627            && same_line(a, b)
2628            && b.ll >= a.lr
2629    };
2630    // A glyph with another right before or after it on its line, no space
2631    // between: part of a word, not a letter standing alone.
2632    let in_word_before = |i: usize| {
2633        i > 0
2634            && glyphs[i - 1].ch != ' '
2635            && boxed(&glyphs[i - 1])
2636            && same_line(&glyphs[i - 1], &glyphs[i])
2637    };
2638    let in_word_after = |i: usize| {
2639        glyphs
2640            .get(i + 1)
2641            .is_some_and(|n| n.ch != ' ' && boxed(n) && same_line(n, &glyphs[i]))
2642    };
2643
2644    // The spaces to drop, by index.
2645    let mut dropped: Vec<usize> = Vec::new();
2646    let mut i = 0;
2647    while i < glyphs.len() {
2648        if !link(i) {
2649            i += 1;
2650            continue;
2651        }
2652        // The chain's glyphs, `first`, `first + 2`, … `last`.
2653        let first = i;
2654        let mut last = i;
2655        while link(last) {
2656            last += 2;
2657        }
2658        i = last + 1;
2659        // Space `k` sits between glyphs `first + 2k` and `first + 2k + 2`.
2660        let spaces = (last - first) / 2;
2661        let gap = |k: usize| glyphs[first + 2 * k + 2].ll - glyphs[first + 2 * k].lr;
2662        let taken_back = |k: usize| {
2663            let sp = &glyphs[first + 2 * k + 1];
2664            glyphs[first + 2 * k + 2].ll - sp.ll <= TAKEN_BACK_SPACE * (sp.lr - sp.ll)
2665        };
2666        // The chain's end glyphs may belong to the words beside it; the
2667        // spaces next to those are what lies between it and its neighbours.
2668        let (lo_k, hi_k) = (
2669            usize::from(in_word_before(first)),
2670            spaces - usize::from(in_word_after(last)),
2671        );
2672        if hi_k < lo_k + 3 {
2673            continue;
2674        }
2675        let letter = |k: usize| glyphs[first + 2 * k].ch.is_alphabetic();
2676
2677        // The letter spacings of the chain: a stretch of three or more spaces
2678        // between letters, each taken back, all leaving one gap.
2679        let mut spacings: Vec<(f32, f32)> = Vec::new();
2680        let mut k = lo_k;
2681        while k < hi_k {
2682            if !(taken_back(k) && letter(k) && letter(k + 1)) {
2683                k += 1;
2684                continue;
2685            }
2686            let (mut lo, mut hi) = (gap(k), gap(k));
2687            let mut end = k + 1;
2688            while end < hi_k
2689                && taken_back(end)
2690                && letter(end + 1)
2691                && hi.max(gap(end)) - lo.min(gap(end)) <= letter_spacing_tolerance(lo)
2692            {
2693                lo = lo.min(gap(end));
2694                hi = hi.max(gap(end));
2695                end += 1;
2696            }
2697            let one_char = (k..=end).all(|j| glyphs[first + 2 * j].ch == glyphs[first + 2 * k].ch);
2698            if end - k >= 3 && !one_char {
2699                spacings.push((lo, hi));
2700            }
2701            k = end.max(k + 1);
2702        }
2703        if spacings.is_empty() {
2704            continue;
2705        }
2706        let spaced = |k: usize| {
2707            (lo_k..hi_k).contains(&k)
2708                && taken_back(k)
2709                && spacings.iter().any(|&(lo, hi)| {
2710                    let tol = letter_spacing_tolerance(lo);
2711                    gap(k) >= lo - tol && gap(k) <= hi + tol
2712                })
2713        };
2714        // Every other space of the chain, and the two beside it, is a word
2715        // space, and a word space is plainly wider than the letter spacing.
2716        // Where one is not, the line has no letter spacing to tell from its
2717        // word spacing, and stays as it is drawn.
2718        let widest = spacings.iter().map(|s| s.1).fold(0.0, f32::max);
2719        if (0..spaces).any(|k| !spaced(k) && gap(k) < WORD_OVER_LETTER_SPACING * widest) {
2720            continue;
2721        }
2722        dropped.extend(
2723            (lo_k..hi_k)
2724                .filter(|&k| spaced(k))
2725                .map(|k| first + 2 * k + 1),
2726        );
2727    }
2728    if dropped.is_empty() {
2729        return;
2730    }
2731    let mut keep = vec![true; glyphs.len()];
2732    for at in dropped {
2733        keep[at] = false;
2734        // The letter after it is as far from its neighbour as before: say
2735        // that the gap is letter spacing, for a word left alone on its line
2736        // cell (a justified heading's `KPI`, `auf`) has no chain of its own
2737        // for the word contraction to recognise it by.
2738        glyphs[at + 1].spaced = true;
2739    }
2740    let mut it = keep.into_iter();
2741    glyphs.retain(|_| it.next().unwrap_or(true));
2742}
2743
2744/// Whether a glyph is on the page (#529): docling-parse keeps a character
2745/// only when its whole box lies inside the display box — the CropBox, or
2746/// the MediaBox without one — edges included, so a FrameMaker print slug
2747/// drawn beside the CropBox or a tiled page's neighbouring text beyond the
2748/// MediaBox never becomes a cell, and a line crossing the edge is cut at the
2749/// last glyph that fits (`Crossing the rig`). The box is docling-parse's
2750/// char box — the advance by the font's ascent/descent, the loose box here
2751/// (its axis-aligned extent for rotated text) — in the frame `page_glyphs`
2752/// already moved to the display box's corner, so the page is `[0, w] × [0,
2753/// h]`. A glyph without a finite box is kept, as before. (A standard-14 font
2754/// without a FontDescriptor gets the 750 / −250 default ascent / descent
2755/// here where docling-parse reads the AFM's — Helvetica's 718 / −207 — so
2756/// for those a glyph within ~0.04 em of the top or bottom edge can fall the
2757/// other way; horizontally the advance is the same.)
2758fn on_page(g: &Glyph, w: f32, h: f32) -> bool {
2759    // f32 noise only: docling-parse already drops a glyph 0.01 pt over.
2760    const EPS: f32 = 1e-3;
2761    let (l, b, r, t) = if [g.ll, g.lb, g.lr, g.lt].iter().all(|v| v.is_finite()) {
2762        (g.ll, g.lb, g.lr, g.lt)
2763    } else {
2764        (g.l, g.b, g.r, g.t)
2765    };
2766    if ![l, b, r, t].iter().all(|v| v.is_finite()) {
2767        return true;
2768    }
2769    l >= -EPS && b >= -EPS && r <= w + EPS && t <= h + EPS
2770}
2771
2772/// Run a content stream's operators, emitting glyphs into `out`. Recurses into
2773/// Form XObjects on `Do` (bulk body text in heavy PDFs lives inside a form, not
2774/// the page content stream). `res` is the resources dict in scope (the page's,
2775/// or the form's own); `base_ctm` is the CTM at the point of invocation.
2776#[allow(clippy::too_many_arguments)]
2777fn run_content(
2778    doc: &Document,
2779    res: &Dictionary,
2780    content: &lopdf::content::Content,
2781    base_ctm: Mat,
2782    init: TextState,
2783    depth: u32,
2784    caches: &mut DocCaches,
2785    out: &mut Vec<Glyph>,
2786    inks: &mut Vec<crate::checkbox::Ink>,
2787    shape_init: ShapeGs,
2788    shapes: &mut Shapes,
2789) {
2790    let fonts = fonts_from_res(doc, res, caches);
2791    let xobjects = res
2792        .get(b"XObject")
2793        .ok()
2794        .and_then(|o| deref(doc, o))
2795        .and_then(|o| o.as_dict().ok());
2796
2797    // Graphics + text state. `q`/`Q` save and restore the whole graphics state,
2798    // which includes the text parameters (Tc, Tw, Tz, TL, Tfs, Trise, font) —
2799    // *not* the text matrix (that is reset by BT). Saving only the CTM let a Tc
2800    // set inside a `q…Q` block leak out and drift every later glyph.
2801    #[allow(clippy::type_complexity)]
2802    let mut gstate_stack: Vec<(Mat, f64, f64, f64, f64, f64, f64, i64, Option<&Arc<Font>>)> =
2803        Vec::new();
2804    let mut ctm = base_ctm;
2805    let mut tm = Mat::ID;
2806    let mut tlm = Mat::ID;
2807    let mut font: Option<&Arc<Font>> = None;
2808    let mut fsize = init.fsize;
2809    let mut tc = init.tc; // char spacing
2810    let mut tw = init.tw; // word spacing
2811    let mut th = init.th; // horizontal scale (Tz/100)
2812    let mut tl = init.tl; // leading
2813    let mut trise = init.trise;
2814    let mut tr = init.tr; // rendering mode
2815
2816    let op_f = |operands: &[Object], i: usize| operands.get(i).and_then(num).unwrap_or(0.0);
2817    // The path under construction, already in page space (a path is built
2818    // under one CTM — `cm` is not allowed inside it), for the checkbox
2819    // squares (#609). Text extraction never reads it.
2820    let mut path: Vec<PathPiece> = Vec::new();
2821    let (mut cur, mut start) = ((0.0, 0.0), (0.0, 0.0));
2822    // Whether the fill colour is (near) white, saved/restored with `q`/`Q`:
2823    // a white-filled stroked box is a checkbox outline, a coloured one a
2824    // chart legend's swatch. The initial fill colour is black.
2825    let mut fill_light = false;
2826    let mut fill_stack: Vec<bool> = Vec::new();
2827    // Open marked-content sequences (`BMC`/`BDC` … `EMC`): where each one's
2828    // glyphs start in `out`, and its inline `/ActualText`, if any.
2829    let mut marked: Vec<(usize, Option<String>)> = Vec::new();
2830    // The reading-order shapes (#1092): docling-parse's view of the path
2831    // under construction, its graphics state and the pending clip.
2832    let mut shape_gs = shape_init;
2833    let mut shape_stack: Vec<ShapeGs> = Vec::new();
2834    let mut shape_path: Vec<ShapeSub> = Vec::new();
2835    let mut clip_pending = false;
2836    let ext_gstates = res
2837        .get(b"ExtGState")
2838        .ok()
2839        .and_then(|o| deref(doc, o))
2840        .and_then(|o| o.as_dict().ok());
2841    let colorspaces = res
2842        .get(b"ColorSpace")
2843        .ok()
2844        .and_then(|o| deref(doc, o))
2845        .and_then(|o| o.as_dict().ok());
2846
2847    for op in &content.operations {
2848        let operands = &op.operands;
2849        let shown = out.len();
2850        match op.operator.as_str() {
2851            "q" => {
2852                gstate_stack.push((ctm, tc, tw, th, tl, trise, fsize, tr, font));
2853                fill_stack.push(fill_light);
2854                shape_stack.push(shape_gs.clone());
2855            }
2856            "BMC" => marked.push((out.len(), None)),
2857            // Only an inline property list is read: a named one (`/OC /MC0`)
2858            // would need the `/Properties` resource, as in docling-parse.
2859            "BDC" => {
2860                let actual = operands
2861                    .get(1)
2862                    .filter(|_| marked.len() < MAX_ACTUAL_TEXT_DEPTH)
2863                    .and_then(|o| o.as_dict().ok())
2864                    .and_then(|d| d.get(b"ActualText").ok())
2865                    .and_then(|o| match o {
2866                        Object::String(bytes, _) => Some(crate::info::decode_text(bytes)),
2867                        _ => None,
2868                    });
2869                marked.push((out.len(), actual));
2870            }
2871            "EMC" => {
2872                if let Some((begin, Some(text))) = marked.pop() {
2873                    apply_actual_text(out, begin, &text);
2874                }
2875                // Shows no text: the invisible-mode stamp below has nothing
2876                // new to mark, and the span may have shortened `out`.
2877                continue;
2878            }
2879            "Q" => {
2880                fill_light = fill_stack.pop().unwrap_or(false);
2881                if let Some(gs) = shape_stack.pop() {
2882                    shape_gs = gs;
2883                }
2884                if let Some((c, a, b, h, l, r, fs, mode, f)) = gstate_stack.pop() {
2885                    ctm = c;
2886                    tc = a;
2887                    tw = b;
2888                    th = h;
2889                    tl = l;
2890                    trise = r;
2891                    fsize = fs;
2892                    tr = mode;
2893                    font = f;
2894                }
2895            }
2896            "cm" => {
2897                let m = Mat {
2898                    a: op_f(operands, 0),
2899                    b: op_f(operands, 1),
2900                    c: op_f(operands, 2),
2901                    d: op_f(operands, 3),
2902                    e: op_f(operands, 4),
2903                    f: op_f(operands, 5),
2904                };
2905                ctm = m.then(ctm);
2906            }
2907            "BT" => {
2908                tm = Mat::ID;
2909                tlm = Mat::ID;
2910            }
2911            "ET" => {}
2912            "Tf" => {
2913                if let Some(Object::Name(n)) = operands.first() {
2914                    font = fonts.get(n.as_slice());
2915                }
2916                fsize = op_f(operands, 1);
2917            }
2918            "Td" => {
2919                tlm = Mat {
2920                    a: 1.0,
2921                    b: 0.0,
2922                    c: 0.0,
2923                    d: 1.0,
2924                    e: op_f(operands, 0),
2925                    f: op_f(operands, 1),
2926                }
2927                .then(tlm);
2928                tm = tlm;
2929            }
2930            "TD" => {
2931                tl = -op_f(operands, 1);
2932                tlm = Mat {
2933                    a: 1.0,
2934                    b: 0.0,
2935                    c: 0.0,
2936                    d: 1.0,
2937                    e: op_f(operands, 0),
2938                    f: op_f(operands, 1),
2939                }
2940                .then(tlm);
2941                tm = tlm;
2942            }
2943            "Tm" => {
2944                tlm = Mat {
2945                    a: op_f(operands, 0),
2946                    b: op_f(operands, 1),
2947                    c: op_f(operands, 2),
2948                    d: op_f(operands, 3),
2949                    e: op_f(operands, 4),
2950                    f: op_f(operands, 5),
2951                };
2952                tm = tlm;
2953            }
2954            "T*" => {
2955                tlm = Mat {
2956                    a: 1.0,
2957                    b: 0.0,
2958                    c: 0.0,
2959                    d: 1.0,
2960                    e: 0.0,
2961                    f: -tl,
2962                }
2963                .then(tlm);
2964                tm = tlm;
2965            }
2966            "Tc" => tc = op_f(operands, 0),
2967            "Tw" => tw = op_f(operands, 0),
2968            "Tz" => th = op_f(operands, 0) / 100.0,
2969            "TL" => tl = op_f(operands, 0),
2970            "Ts" => trise = op_f(operands, 0),
2971            "Tr" => tr = op_f(operands, 0) as i64,
2972            "Tj" | "'" | "\"" => {
2973                if op.operator == "'" || op.operator == "\"" {
2974                    // move to next line first
2975                    tlm = Mat {
2976                        a: 1.0,
2977                        b: 0.0,
2978                        c: 0.0,
2979                        d: 1.0,
2980                        e: 0.0,
2981                        f: -tl,
2982                    }
2983                    .then(tlm);
2984                    tm = tlm;
2985                }
2986                if op.operator == "\"" {
2987                    // `aw ac string "` sets word- and char-spacing before
2988                    // showing the string (PDF 32000-1 §9.4.3), persisting after.
2989                    tw = op_f(operands, 0);
2990                    tc = op_f(operands, 1);
2991                }
2992                if let (Some(f), Some(Object::String(s, _))) = (font, operands.last()) {
2993                    let first = out.len();
2994                    show_text(f, s, fsize, tc, tw, th, trise, &mut tm, ctm, out);
2995                    stamp_clip(&mut out[first..], shape_gs.clip_box);
2996                }
2997            }
2998            "TJ" => {
2999                if let (Some(f), Some(Object::Array(arr))) = (font, operands.first()) {
3000                    let first = out.len();
3001                    for el in arr {
3002                        match el {
3003                            Object::String(s, _) => {
3004                                show_text(f, s, fsize, tc, tw, th, trise, &mut tm, ctm, out)
3005                            }
3006                            other => {
3007                                if let Some(adj) = num(other) {
3008                                    // negative number moves text right (PDF: subtract)
3009                                    let tx = -adj / 1000.0 * fsize * th;
3010                                    tm = Mat {
3011                                        a: 1.0,
3012                                        b: 0.0,
3013                                        c: 0.0,
3014                                        d: 1.0,
3015                                        e: tx,
3016                                        f: 0.0,
3017                                    }
3018                                    .then(tm);
3019                                }
3020                            }
3021                        }
3022                    }
3023                    stamp_clip(&mut out[first..], shape_gs.clip_box);
3024                }
3025            }
3026            "m" => {
3027                cur = ctm.apply(op_f(operands, 0), op_f(operands, 1));
3028                start = cur;
3029                shape_path.push(ShapeSub::at(cur));
3030            }
3031            "l" => {
3032                let p = ctm.apply(op_f(operands, 0), op_f(operands, 1));
3033                path.push(PathPiece::Line(cur, p));
3034                cur = p;
3035                if let Some(sub) = shape_path.last_mut() {
3036                    sub.lines.push((sub.cur, p));
3037                    sub.pts.push(p);
3038                    sub.cur = p;
3039                }
3040            }
3041            "c" | "v" | "y" => {
3042                let pts: Vec<(f64, f64)> = (0..operands.len() / 2)
3043                    .map(|k| ctm.apply(op_f(operands, 2 * k), op_f(operands, 2 * k + 1)))
3044                    .collect();
3045                if let Some(&end) = pts.last() {
3046                    path.push(PathPiece::Curve(
3047                        std::iter::once(cur).chain(pts.iter().copied()).collect(),
3048                    ));
3049                    cur = end;
3050                    if let Some(sub) = shape_path.last_mut() {
3051                        sub.pts.extend(pts.iter().copied());
3052                        sub.cur = end;
3053                    }
3054                }
3055            }
3056            "h" => {
3057                if cur != start {
3058                    path.push(PathPiece::Line(cur, start));
3059                }
3060                cur = start;
3061                // docling-parse closes the subpath and opens the next one at
3062                // its start, where a following `l` continues.
3063                if let Some(sub) = shape_path.last_mut() {
3064                    sub.closed = true;
3065                    sub.pts.push(sub.start);
3066                    let at = sub.start;
3067                    shape_path.push(ShapeSub::at(at));
3068                }
3069            }
3070            "re" => {
3071                let (x, y, w, h) = (
3072                    op_f(operands, 0),
3073                    op_f(operands, 1),
3074                    op_f(operands, 2),
3075                    op_f(operands, 3),
3076                );
3077                path.push(PathPiece::Rect([
3078                    ctm.apply(x, y),
3079                    ctm.apply(x + w, y),
3080                    ctm.apply(x + w, y + h),
3081                    ctm.apply(x, y + h),
3082                ]));
3083                cur = ctm.apply(x, y);
3084                start = cur;
3085                // `m` + three `l` + `h`, as docling-parse builds it.
3086                let c = [
3087                    ctm.apply(x, y),
3088                    ctm.apply(x + w, y),
3089                    ctm.apply(x + w, y + h),
3090                    ctm.apply(x, y + h),
3091                ];
3092                shape_path.push(ShapeSub {
3093                    start: c[0],
3094                    cur: c[3],
3095                    pts: vec![c[0], c[1], c[2], c[3], c[0]],
3096                    lines: vec![(c[0], c[1]), (c[1], c[2]), (c[2], c[3])],
3097                    closed: true,
3098                });
3099                shape_path.push(ShapeSub::at(c[0]));
3100            }
3101            "S" | "s" | "f" | "F" | "f*" | "B" | "B*" | "b" | "b*" => {
3102                let op = op.operator.as_str();
3103                if matches!(op, "s" | "b" | "b*") && cur != start {
3104                    path.push(PathPiece::Line(cur, start));
3105                }
3106                let stroke = matches!(op, "S" | "s" | "B" | "B*" | "b" | "b*");
3107                let fill = !matches!(op, "S" | "s");
3108                paint_path(&path, stroke, fill, fill_light, inks);
3109                path.clear();
3110                // `s`, `f`, `f*`, `b`, `b*` close the last subpath first.
3111                if !matches!(op, "S" | "B" | "B*") {
3112                    if let Some(sub) = shape_path.last_mut() {
3113                        sub.closed = true;
3114                    }
3115                }
3116                let scale = (ctm.a * ctm.d - ctm.b * ctm.c).abs().sqrt();
3117                record_shape(
3118                    &shape_path,
3119                    stroke,
3120                    fill,
3121                    &shape_gs,
3122                    if scale > 0.0 { scale } else { 1.0 },
3123                    shapes,
3124                );
3125                // A pending `W` takes effect after the painting operator.
3126                if std::mem::take(&mut clip_pending) {
3127                    capture_clip(&shape_path, &mut shape_gs);
3128                }
3129                shape_path.clear();
3130            }
3131            "n" => {
3132                path.clear();
3133                if std::mem::take(&mut clip_pending) {
3134                    capture_clip(&shape_path, &mut shape_gs);
3135                }
3136                shape_path.clear();
3137            }
3138            "W" | "W*" => clip_pending = true,
3139            "w" => shape_gs.line_width = op_f(operands, 0),
3140            "gs" => {
3141                let params = operands
3142                    .first()
3143                    .and_then(|o| o.as_name().ok())
3144                    .and_then(|n| ext_gstates?.get(n).ok())
3145                    .and_then(|o| deref(doc, o))
3146                    .and_then(|o| o.as_dict().ok());
3147                if let Some(params) = params {
3148                    let get = |k: &[u8]| params.get(k).ok().and_then(num);
3149                    if let Some(lw) = get(b"LW") {
3150                        shape_gs.line_width = lw;
3151                    }
3152                    if let Some(a) = get(b"CA") {
3153                        shape_gs.stroke_alpha = a;
3154                    }
3155                    if let Some(a) = get(b"ca") {
3156                        shape_gs.fill_alpha = a;
3157                    }
3158                }
3159            }
3160            // The fill colour, by its components: gray `g`, `rg`, CMYK `k`,
3161            // and `sc`/`scn` by operand count (a pattern name is not light).
3162            "g" | "rg" | "k" | "sc" | "scn" => {
3163                // docling-parse: a colour resolves a pattern fill; a pattern
3164                // name in `scn` makes it one.
3165                if matches!(op.operator.as_str(), "scn")
3166                    && matches!(operands.last(), Some(Object::Name(_)))
3167                {
3168                    shape_gs.fill_pattern = true;
3169                } else if !operands.is_empty() {
3170                    shape_gs.fill_pattern = false;
3171                }
3172                let v: Vec<f64> = operands
3173                    .iter()
3174                    .map(num)
3175                    .collect::<Option<_>>()
3176                    .unwrap_or_default();
3177                fill_light = match v.as_slice() {
3178                    [g] => *g >= 0.9,
3179                    [r, g, b] => r.min(*g).min(*b) >= 0.9,
3180                    [c, m, y, k] => c.max(*m).max(*y).max(*k) <= 0.1,
3181                    _ => false,
3182                };
3183            }
3184            "cs" => {
3185                fill_light = false;
3186                // A Pattern space carries no colour until `scn` names one.
3187                let pattern = match operands.first() {
3188                    Some(Object::Name(n)) if n.as_slice() == b"Pattern" => true,
3189                    Some(Object::Name(n)) => colorspaces
3190                        .and_then(|cs| cs.get(n).ok())
3191                        .and_then(|o| deref(doc, o))
3192                        .is_some_and(|o| match o {
3193                            Object::Name(f) => f.as_slice() == b"Pattern",
3194                            Object::Array(a) => a
3195                                .first()
3196                                .and_then(|f| f.as_name().ok())
3197                                .is_some_and(|f| f == b"Pattern"),
3198                            _ => false,
3199                        }),
3200                    _ => false,
3201                };
3202                if pattern {
3203                    shape_gs.fill_pattern = true;
3204                }
3205            }
3206            // An inline image: the unit square under the CTM (#999).
3207            "BI" => inks.push(image_ink(ctm)),
3208            "Do" => {
3209                // Invoke a Form XObject: bulk body text in many PDFs lives inside
3210                // a form, reached only here. An image XObject carries no text,
3211                // only its placement (#999).
3212                if depth >= 8 {
3213                    continue;
3214                }
3215                let Some(Object::Name(n)) = operands.first() else {
3216                    continue;
3217                };
3218                let obj = xobjects.and_then(|d| d.get(n.as_slice()).ok());
3219                let form_id = match obj {
3220                    Some(Object::Reference(id)) => Some(*id),
3221                    _ => None,
3222                };
3223                let stream = obj
3224                    .and_then(|o| deref(doc, o))
3225                    .and_then(|o| o.as_stream().ok());
3226                let Some(stream) = stream else { continue };
3227                let is_form = stream
3228                    .dict
3229                    .get(b"Subtype")
3230                    .ok()
3231                    .and_then(|o| o.as_name().ok())
3232                    == Some(b"Form".as_slice());
3233                if !is_form {
3234                    let is_image = stream
3235                        .dict
3236                        .get(b"Subtype")
3237                        .ok()
3238                        .and_then(|o| o.as_name().ok())
3239                        == Some(b"Image".as_slice());
3240                    if is_image {
3241                        inks.push(image_ink(ctm));
3242                    }
3243                    continue;
3244                }
3245                // Decode a reused form's content once per document
3246                // (headers/footers and bulk body text invoke the same form on
3247                // every page); see `DocCaches::forms_seen` for single-use ones.
3248                let cached = form_id.and_then(|id| caches.forms.get(&id).cloned());
3249                let form_content = match cached {
3250                    Some(c) => c,
3251                    None => {
3252                        let Some(data) = content_stream_bytes(stream) else {
3253                            continue;
3254                        };
3255                        let Ok(c) = lopdf::content::Content::decode(&data) else {
3256                            continue;
3257                        };
3258                        let c = Arc::new(c);
3259                        if let Some(id) = form_id {
3260                            if !caches.forms_seen.insert(id) {
3261                                caches.forms.insert(id, Arc::clone(&c));
3262                            }
3263                        }
3264                        c
3265                    }
3266                };
3267                // The form's /Matrix maps form space into the CTM at invocation.
3268                let form_mat = match stream.dict.get(b"Matrix").ok() {
3269                    Some(Object::Array(a)) if a.len() == 6 => {
3270                        let v: Vec<f64> = a.iter().filter_map(num).collect();
3271                        if v.len() == 6 {
3272                            Mat {
3273                                a: v[0],
3274                                b: v[1],
3275                                c: v[2],
3276                                d: v[3],
3277                                e: v[4],
3278                                f: v[5],
3279                            }
3280                        } else {
3281                            Mat::ID
3282                        }
3283                    }
3284                    _ => Mat::ID,
3285                };
3286                // The form's own /Resources, falling back to the inherited ones.
3287                let form_res = stream
3288                    .dict
3289                    .get(b"Resources")
3290                    .ok()
3291                    .and_then(|o| deref(doc, o))
3292                    .and_then(|o| o.as_dict().ok())
3293                    .unwrap_or(res);
3294                let state = TextState {
3295                    tc,
3296                    tw,
3297                    th,
3298                    tl,
3299                    trise,
3300                    fsize,
3301                    tr,
3302                };
3303                run_content(
3304                    doc,
3305                    form_res,
3306                    &form_content,
3307                    form_mat.then(ctm),
3308                    state,
3309                    depth + 1,
3310                    caches,
3311                    out,
3312                    inks,
3313                    shape_gs.clone(),
3314                    shapes,
3315                );
3316            }
3317            _ => {}
3318        }
3319        // Invisible text (`Tr` 3, or 7: clip only) — an OCR layer over a scan
3320        // follows the scanned lines, not a typeset baseline (#1005).
3321        if matches!(tr, 3 | 7) {
3322            for g in &mut out[shown..] {
3323                g.invisible = true;
3324            }
3325        }
3326    }
3327}
3328
3329/// An image placement's box — the unit square under `ctm`, y-up page
3330/// points — as an [`Ink::Bitmap`](crate::checkbox::Ink::Bitmap).
3331fn image_ink(ctm: Mat) -> crate::checkbox::Ink {
3332    let pts = [(0.0, 0.0), (1.0, 0.0), (0.0, 1.0), (1.0, 1.0)].map(|(x, y)| ctm.apply(x, y));
3333    let (mut l, mut b, mut r, mut t) = (
3334        f64::INFINITY,
3335        f64::INFINITY,
3336        f64::NEG_INFINITY,
3337        f64::NEG_INFINITY,
3338    );
3339    for (x, y) in pts {
3340        (l, b, r, t) = (l.min(x), b.min(y), r.max(x), t.max(y));
3341    }
3342    crate::checkbox::Ink::Bitmap { l, b, r, t }
3343}
3344
3345/// The page's vector shapes as docling-parse's page decoder reports them to
3346/// docling's reading order (#1092): `get_shape_lines` — every stroked,
3347/// axis-aligned straight segment, clipped — and the boxes
3348/// `get_connected_shape_bounding_boxes` merges — every visible painted path,
3349/// its stroke's half width included, clipped. `[l, b, r, t]`, page points,
3350/// bottom-left origin, in the frame `run_content` walks (the display box's
3351/// lower-left corner at the origin, before `/Rotate`).
3352#[derive(Default, Clone, Debug, PartialEq)]
3353pub(crate) struct Shapes {
3354    pub lines: Vec<[f64; 4]>,
3355    pub boxes: Vec<[f64; 4]>,
3356}
3357
3358/// More painted paths than this on a page and their boxes are not merged —
3359/// docling-parse's merge is quadratic in them, and a page that dense (a map,
3360/// a seat plan, text drawn as outlines) yields no trustworthy rule anyway;
3361/// the stroked lines still count.
3362const MAX_SHAPE_BOXES: usize = 10_000;
3363
3364/// One subpath of the shape path under construction, page space: what
3365/// docling-parse's `page_item<PAGE_SHAPE>` keeps of it.
3366struct ShapeSub {
3367    start: (f64, f64),
3368    cur: (f64, f64),
3369    /// Every point the path passes or is controlled by — a curve's control
3370    /// points included, as docling-parse's segment data has them.
3371    pts: Vec<(f64, f64)>,
3372    /// Its straight segments, in order.
3373    lines: Vec<((f64, f64), (f64, f64))>,
3374    closed: bool,
3375}
3376
3377impl ShapeSub {
3378    fn at(p: (f64, f64)) -> Self {
3379        ShapeSub {
3380            start: p,
3381            cur: p,
3382            pts: vec![p],
3383            lines: Vec::new(),
3384            closed: false,
3385        }
3386    }
3387
3388    /// `keep_shape`: two points at least, spanning more than a speck (the
3389    /// box diagonal, squared, over 1e-3).
3390    fn kept(&self) -> bool {
3391        let Some((l, b, r, t)) = bbox_of(&self.pts) else {
3392            return false;
3393        };
3394        self.pts.len() >= 2 && (r - l).powi(2) + (t - b).powi(2) >= 1e-3
3395    }
3396}
3397
3398fn bbox_of(pts: &[(f64, f64)]) -> Option<(f64, f64, f64, f64)> {
3399    let (&first, rest) = pts.split_first()?;
3400    Some(rest.iter().fold(
3401        (first.0, first.1, first.0, first.1),
3402        |(l, b, r, t), &(x, y)| (l.min(x), b.min(y), r.max(x), t.max(y)),
3403    ))
3404}
3405
3406/// The graphics state docling-parse's shapes read: line width (user space),
3407/// stroke and fill alpha (`CA` / `ca`), whether the fill colour is a pattern
3408/// not yet resolved to a paint, and the clip paths' boxes. Saved and
3409/// restored with `q` / `Q`.
3410#[derive(Clone)]
3411struct ShapeGs {
3412    line_width: f64,
3413    stroke_alpha: f64,
3414    fill_alpha: f64,
3415    fill_pattern: bool,
3416    clips: Vec<[f64; 4]>,
3417    /// The clip in force as one box: the intersection of each capture's
3418    /// box (the union of its subpaths' points), an empty intersection a
3419    /// zero-size box — docling-parse 7.26's `clip_bbox`, which every glyph
3420    /// carries (#1150, [`Glyph::clip`]).
3421    clip_box: Option<[f64; 4]>,
3422}
3423
3424impl ShapeGs {
3425    const INIT: ShapeGs = ShapeGs {
3426        line_width: 1.0,
3427        stroke_alpha: 1.0,
3428        fill_alpha: 1.0,
3429        fill_pattern: false,
3430        clips: Vec::new(),
3431        clip_box: None,
3432    };
3433}
3434
3435/// Give the glyphs a text operator just drew the clip box in force.
3436fn stamp_clip(glyphs: &mut [Glyph], clip: Option<[f64; 4]>) {
3437    let clip = clip.map(|c| c.map(|v| v as f32));
3438    for g in glyphs {
3439        g.clip = clip;
3440    }
3441}
3442
3443/// docling-parse's `bbox_intersects`: the boxes share area (a degenerate box
3444/// lying inside the other counts).
3445fn boxes_intersect(a: [f64; 4], b: [f64; 4]) -> bool {
3446    a[0] < b[2] && a[2] > b[0] && a[1] < b[3] && a[3] > b[1]
3447}
3448
3449/// `clipped_bbox`: a box cut to every clip path's box in turn; `None` once
3450/// one of them misses it.
3451fn clipped(mut bbox: [f64; 4], clips: &[[f64; 4]]) -> Option<[f64; 4]> {
3452    for c in clips {
3453        if !boxes_intersect(bbox, *c) {
3454            return None;
3455        }
3456        bbox = [
3457            bbox[0].max(c[0]),
3458            bbox[1].max(c[1]),
3459            bbox[2].min(c[2]),
3460            bbox[3].min(c[3]),
3461        ];
3462    }
3463    Some(bbox)
3464}
3465
3466/// `get_shape_lines`' `maybe_add_line` + `clip_axis_aligned_segment`: a
3467/// straight segment that is horizontal or vertical within 1e-3 (not both: a
3468/// point), cut to every clip path's box along its axis and dropped when one
3469/// misses it.
3470fn shape_line(a: (f64, f64), z: (f64, f64), clips: &[[f64; 4]], out: &mut Vec<[f64; 4]>) {
3471    const TOL: f64 = 1e-3;
3472    let horizontal = (z.1 - a.1).abs() <= TOL;
3473    let vertical = (z.0 - a.0).abs() <= TOL;
3474    if horizontal == vertical {
3475        return;
3476    }
3477    let mut bbox = [a.0.min(z.0), a.1.min(z.1), a.0.max(z.0), a.1.max(z.1)];
3478    for c in clips {
3479        if horizontal {
3480            if a.1 < c[1] - TOL || a.1 > c[3] + TOL {
3481                return;
3482            }
3483            bbox[0] = bbox[0].max(c[0]);
3484            bbox[2] = bbox[2].min(c[2]);
3485            if bbox[0] > bbox[2] + TOL {
3486                return;
3487            }
3488        } else {
3489            if a.0 < c[0] - TOL || a.0 > c[2] + TOL {
3490                return;
3491            }
3492            bbox[1] = bbox[1].max(c[1]);
3493            bbox[3] = bbox[3].min(c[3]);
3494            if bbox[1] > bbox[3] + TOL {
3495                return;
3496            }
3497        }
3498    }
3499    out.push(bbox);
3500}
3501
3502/// `capture_pending_clip`: each subpath of the clipping path with a segment
3503/// (two points or more) bounds what later operators paint — appended, which
3504/// approximates the intersection the spec asks for, as docling-parse does.
3505///
3506/// The capture's box as a whole — every point of its subpaths — narrows
3507/// the clip box ([`ShapeGs::clip_box`], docling-parse's
3508/// `intersect_clip_bbox`).
3509fn capture_clip(subs: &[ShapeSub], gs: &mut ShapeGs) {
3510    let mut group: Option<[f64; 4]> = None;
3511    for sub in subs.iter().filter(|s| s.pts.len() >= 2) {
3512        if let Some((l, b, r, t)) = bbox_of(&sub.pts) {
3513            gs.clips.push([l, b, r, t]);
3514            group = Some(match group {
3515                None => [l, b, r, t],
3516                Some(g) => [g[0].min(l), g[1].min(b), g[2].max(r), g[3].max(t)],
3517            });
3518        }
3519    }
3520    if let Some(g) = group {
3521        gs.clip_box = Some(match gs.clip_box {
3522            None => g,
3523            Some(c) => {
3524                let (x0, y0) = (c[0].max(g[0]), c[1].max(g[1]));
3525                // An empty intersection clips everything: a zero-size box.
3526                [x0, y0, c[2].min(g[2]).max(x0), c[3].min(g[3]).max(y0)]
3527            }
3528        });
3529    }
3530}
3531
3532/// docling-parse's `register_paths` for the reading-order geometry: a painted
3533/// path's kept subpaths become shape lines (when its stroke shows) and a
3534/// shape box (when anything of it shows). A fill whose colour is an
3535/// unresolved pattern paints nothing, so a fill-only path is no shape and a
3536/// fill-and-stroke one keeps its stroke. `scale` maps the user-space line
3537/// width to page space (the CTM's `sqrt|det|`; a hairline stays 0).
3538fn record_shape(
3539    subs: &[ShapeSub],
3540    stroke: bool,
3541    fill: bool,
3542    gs: &ShapeGs,
3543    scale: f64,
3544    shapes: &mut Shapes,
3545) {
3546    let kept: Vec<&ShapeSub> = subs.iter().filter(|s| s.kept()).collect();
3547    if kept.is_empty() {
3548        return;
3549    }
3550    let fill = fill && !gs.fill_pattern;
3551    if gs.fill_pattern && !stroke {
3552        return;
3553    }
3554    let strokes_visible = stroke && gs.stroke_alpha > 0.0;
3555    let visible = strokes_visible || (fill && gs.fill_alpha > 0.0);
3556    if strokes_visible {
3557        for sub in &kept {
3558            for &(a, z) in &sub.lines {
3559                shape_line(a, z, &gs.clips, &mut shapes.lines);
3560            }
3561            if sub.closed {
3562                shape_line(sub.cur, sub.start, &gs.clips, &mut shapes.lines);
3563            }
3564        }
3565    }
3566    if visible {
3567        let pts: Vec<(f64, f64)> = kept.iter().flat_map(|s| s.pts.iter().copied()).collect();
3568        if let Some((l, b, r, t)) = bbox_of(&pts) {
3569            let pad = if strokes_visible {
3570                (gs.line_width * scale).max(0.0) * 0.5
3571            } else {
3572                0.0
3573            };
3574            if let Some(bbox) = clipped([l - pad, b - pad, r + pad, t + pad], &gs.clips) {
3575                shapes.boxes.push(bbox);
3576            }
3577        }
3578    }
3579}
3580
3581/// `get_connected_shape_bounding_boxes`: each box in turn (unless already
3582/// taken) grows by every untaken box its growing union touches, until none
3583/// does — docling-parse's greedy pass, so a component finished early keeps a
3584/// box a later one would also have reached. Tolerance 0, as docling calls
3585/// it: two `re` that meet in the file meet here because [`real`] reads their
3586/// operands as the doubles docling-parse reads.
3587fn connected_boxes(boxes: &[[f64; 4]]) -> Vec<[f64; 4]> {
3588    let touches =
3589        |a: [f64; 4], b: [f64; 4]| a[0] <= b[2] && a[2] >= b[0] && a[1] <= b[3] && a[3] >= b[1];
3590    let mut taken = vec![false; boxes.len()];
3591    let mut out = Vec::new();
3592    for i in 0..boxes.len() {
3593        if taken[i] {
3594            continue;
3595        }
3596        taken[i] = true;
3597        let mut component = boxes[i];
3598        let mut changed = true;
3599        while changed {
3600            changed = false;
3601            for j in 0..boxes.len() {
3602                if !taken[j] && touches(component, boxes[j]) {
3603                    let b = boxes[j];
3604                    component = [
3605                        component[0].min(b[0]),
3606                        component[1].min(b[1]),
3607                        component[2].max(b[2]),
3608                        component[3].max(b[3]),
3609                    ];
3610                    taken[j] = true;
3611                    changed = true;
3612                }
3613            }
3614        }
3615        out.push(component);
3616    }
3617    out
3618}
3619
3620/// One piece of a path under construction, page space (see `run_content`).
3621enum PathPiece {
3622    Line((f64, f64), (f64, f64)),
3623    /// An `re`: its four corners, counter-clockwise from `(x, y)`.
3624    Rect([(f64, f64); 4]),
3625    /// A Bézier segment: its start and control/end points (their hull).
3626    Curve(Vec<(f64, f64)>),
3627}
3628
3629/// Record a painted path's pieces for the checkbox finder (#609): a stroked
3630/// line is a [`Seg`](crate::checkbox::Ink::Seg), a stroked rectangle that
3631/// stays axis-aligned a [`Rect`](crate::checkbox::Ink::Rect) (one filled
3632/// white too — still an outline), and a coloured fill or a curve only its
3633/// bounding box, a [`Blot`](crate::checkbox::Ink::Blot): a possible tick
3634/// mark, or a swatch. White fills draw nothing and are dropped. Only pieces small
3635/// enough to be a checkbox edge or a mark inside one are kept.
3636fn paint_path(
3637    path: &[PathPiece],
3638    stroke: bool,
3639    fill: bool,
3640    fill_light: bool,
3641    inks: &mut Vec<crate::checkbox::Ink>,
3642) {
3643    use crate::checkbox::Ink;
3644    let bbox = |pts: &mut dyn Iterator<Item = (f64, f64)>| {
3645        pts.fold(
3646            (
3647                f64::INFINITY,
3648                f64::INFINITY,
3649                f64::NEG_INFINITY,
3650                f64::NEG_INFINITY,
3651            ),
3652            |(l, b, r, t), (x, y)| (l.min(x), b.min(y), r.max(x), t.max(y)),
3653        )
3654    };
3655    let mut keep = |ink: Ink| {
3656        if ink.worth_keeping() {
3657            inks.push(ink);
3658        }
3659    };
3660    if fill && !fill_light {
3661        // A coloured fill is a blot — a tick mark, or (the size of a square)
3662        // a legend swatch, which `checkbox::find` then rules out. A white
3663        // fill is no ink on paper: it only leaves the stroke, if any, below.
3664        let (l, b, r, t) = bbox(&mut path.iter().flat_map(|p| match p {
3665            PathPiece::Line(a, z) => vec![*a, *z],
3666            PathPiece::Rect(c) => c.to_vec(),
3667            PathPiece::Curve(c) => c.clone(),
3668        }));
3669        if l.is_finite() {
3670            keep(Ink::Blot { l, b, r, t });
3671        }
3672        return;
3673    }
3674    if !stroke {
3675        return;
3676    }
3677    for piece in path {
3678        match piece {
3679            PathPiece::Line(a, z) => keep(Ink::Seg {
3680                x0: a.0,
3681                y0: a.1,
3682                x1: z.0,
3683                y1: z.1,
3684            }),
3685            PathPiece::Rect(c) => {
3686                let axis = ((c[0].1 - c[1].1).abs() < 1e-6 && (c[1].0 - c[2].0).abs() < 1e-6)
3687                    || ((c[0].0 - c[1].0).abs() < 1e-6 && (c[1].1 - c[2].1).abs() < 1e-6);
3688                if axis {
3689                    let (l, b, r, t) = bbox(&mut c.iter().copied());
3690                    keep(Ink::Rect { l, b, r, t });
3691                } else {
3692                    for k in 0..4 {
3693                        let (a, z) = (c[k], c[(k + 1) % 4]);
3694                        keep(Ink::Seg {
3695                            x0: a.0,
3696                            y0: a.1,
3697                            x1: z.0,
3698                            y1: z.1,
3699                        });
3700                    }
3701                }
3702            }
3703            PathPiece::Curve(c) => {
3704                let (l, b, r, t) = bbox(&mut c.iter().copied());
3705                keep(Ink::Blot { l, b, r, t });
3706            }
3707        }
3708    }
3709}
3710
3711#[allow(clippy::too_many_arguments)]
3712fn show_text(
3713    font: &Font,
3714    bytes: &[u8],
3715    fsize: f64,
3716    tc: f64,
3717    tw: f64,
3718    th: f64,
3719    trise: f64,
3720    tm: &mut Mat,
3721    ctm: Mat,
3722    out: &mut Vec<Glyph>,
3723) {
3724    for code in codes(font, bytes) {
3725        let (text, w, blank) = font.decode_code(code);
3726        let w0 = w / 1000.0; // advance in text-space (em) units
3727                             // The glyph→user transform: scale glyph space by font size, then Tm, CTM.
3728        let scale = Mat {
3729            a: fsize * th,
3730            b: 0.0,
3731            c: 0.0,
3732            d: fsize,
3733            e: 0.0,
3734            f: trise,
3735        };
3736        let trm = scale.then(*tm).then(ctm);
3737        // Box in glyph space (1000-unit em): x 0..w, y descent..ascent.
3738        // A blank unmapped glyph keeps its advance but no ink height
3739        // (docling-parse collapses its ascent and descent).
3740        let (desc, asc) = if blank {
3741            (0.0, 0.0)
3742        } else if let Some(&(lo, hi)) = font.ink_y.get(&code) {
3743            (lo / 1000.0, hi / 1000.0)
3744        } else {
3745            (font.descent / 1000.0, font.ascent / 1000.0)
3746        };
3747        let (x0, y0) = trm.apply(0.0, desc);
3748        let (x1, y1) = trm.apply(w0, desc);
3749        let (x2, y2) = trm.apply(w0, asc);
3750        let (x3, y3) = trm.apply(0.0, asc);
3751        let exact = {
3752            use std::hash::{Hash, Hasher};
3753            let mut h = std::collections::hash_map::DefaultHasher::new();
3754            [x0, y0, x1, y1, x2, y2, x3, y3]
3755                .map(f64::to_bits)
3756                .hash(&mut h);
3757            h.finish()
3758        };
3759        // Upright = the baseline runs left-to-right along +x. Only then is the
3760        // loose box the rectangle spanned by the baseline's x and the em's y
3761        // (a synthetic oblique's skew is ignored, as it always was). A rotated
3762        // matrix — the `0 s -s 0 tx ty Tm` landscape pages are built with
3763        // (#528) — collapsed that rectangle to zero width, and every such run
3764        // vanished; those glyphs keep their real quad (docling-parse's char
3765        // rect) and its extent instead.
3766        let upright = trm.a > 0.0 && trm.b.abs() <= 1e-6 * trm.a;
3767        let (left, bot, right, top, quad) = if upright {
3768            (x0.min(x1), y0.min(y3), x0.max(x1), y0.max(y3), None)
3769        } else {
3770            let (xs, ys) = ([x0, x1, x2, x3], [y0, y1, y2, y3]);
3771            let fold = |v: [f64; 4], f: fn(f64, f64) -> f64| v.into_iter().reduce(f).unwrap();
3772            let q = [x0, y0, x1, y1, x2, y2, x3, y3].map(|v| v as f32);
3773            (
3774                fold(xs, f64::min),
3775                fold(ys, f64::min),
3776                fold(xs, f64::max),
3777                fold(ys, f64::max),
3778                Some(q),
3779            )
3780        };
3781        // The pen's origin (rise included) and the font size's extent from
3782        // it, as docling-parse maps them (`map_text_point(0, rise)` and
3783        // `(0, rise + font_size)`).
3784        let (ox, oy) = trm.apply(0.0, 0.0);
3785        let (sx, sy) = trm.apply(0.0, 1.0);
3786        let pen = Some([ox as f32, oy as f32, (sx - ox).hypot(sy - oy) as f32]);
3787        if let Some(s) = text {
3788            // A run may map one code to multiple chars (ligature/fraction); share box.
3789            for ch in s.chars() {
3790                // A NUL from the `/ToUnicode` is an unmapped glyph too
3791                // (docling#5070): U+FFFD.
3792                let ch = if ch == '\u{0}' { '\u{FFFD}' } else { ch };
3793                out.push(Glyph {
3794                    ch,
3795                    l: left as f32,
3796                    b: bot as f32,
3797                    r: right as f32,
3798                    t: top as f32,
3799                    ll: left as f32,
3800                    lb: bot as f32,
3801                    lr: right as f32,
3802                    lt: top as f32,
3803                    font: font.hash,
3804                    quad,
3805                    pen,
3806                    math_font: font.math,
3807                    invisible: false,
3808                    spaced: false,
3809                    clip: None,
3810                    exact,
3811                });
3812            }
3813        }
3814        // Advance the text matrix. Word spacing applies to single-byte code 32.
3815        let is_space = !font.two_byte && code == 32;
3816        let tx = (w0 * fsize + tc + if is_space { tw } else { 0.0 }) * th;
3817        *tm = Mat {
3818            a: 1.0,
3819            b: 0.0,
3820            c: 0.0,
3821            d: 1.0,
3822            e: tx,
3823            f: 0.0,
3824        }
3825        .then(*tm);
3826    }
3827}
3828
3829/// Build a simple font's code→char table from its `/Encoding`: the base
3830/// encoding (WinAnsi / MacRoman / Standard / MacExpert) plus any
3831/// `/Differences` overrides (glyph names resolved through the Adobe Glyph
3832/// List).
3833fn simple_encoding_table(doc: &Document, fdict: &Dictionary) -> HashMap<u8, char> {
3834    let enc = fdict.get(b"Encoding").ok().and_then(|o| deref(doc, o));
3835    let base_name = match enc {
3836        Some(Object::Name(n)) => n.clone(),
3837        Some(Object::Dictionary(d)) => d
3838            .get(b"BaseEncoding")
3839            .ok()
3840            .and_then(|o| o.as_name().ok())
3841            .map(|n| n.to_vec())
3842            .unwrap_or_default(),
3843        _ => Vec::new(),
3844    };
3845    let face = || {
3846        let font_name = sanitizer_font_name(doc, fdict, false);
3847        let base = fdict.get(b"BaseFont").ok().and_then(|o| o.as_name().ok());
3848        let names: Vec<&[u8]> = std::iter::once(font_name.as_slice()).chain(base).collect();
3849        crate::symbol_fonts::symbol_face(&names)
3850    };
3851    let mut m = if base_name == b"MacRomanEncoding" {
3852        macroman_table()
3853    } else if base_name == b"StandardEncoding" || base_name == b"MacExpertEncoding" {
3854        // Read as WinAnsi before #1152: StandardEncoding's `quoteright` /
3855        // `quoteleft` / `fi` / `fl` / `AE` codes came out `'`/`` ` ``/`®`/`¯`/`á`.
3856        named_table(crate::encodings::by_name(&base_name).unwrap_or_default())
3857    } else if let Some(face) = base_name.is_empty().then(face).flatten() {
3858        // A font matched to Symbol or ZapfDingbats that names no encoding:
3859        // the face's own (docling-parse's base-font AFM, a "FontSpecific"
3860        // scheme), never the Latin tables — a non-embedded ZapfDingbats'
3861        // `l` is `●` (docling-parse#431, #1113). An embedded program's
3862        // builtin encoding still comes first ([`Font::builtin`]).
3863        crate::symbol_fonts::face_table(face)
3864    } else if base_name.is_empty() {
3865        // No PDF /Encoding at all: the font's *built-in* encoding applies. For
3866        // the standard TeX math fonts that is their fixed TeX layout — falling
3867        // back to StandardEncoding read CMSY's braces as `f`/`g`, `→` as `!`,
3868        // `∈` as `2` (2203's `{ahn,…}` author line). The font program (often
3869        // CFF, which this parser does not read) carries the same mapping;
3870        // docling-parse decodes it from there.
3871        // Otherwise a nonsymbolic Type 1 font's built-in encoding is
3872        // StandardEncoding (9.6.6.1; a non-embedded Core 14 Helvetica's, its
3873        // AFM's), as pdfium and docling-parse read it (#1152) — a WinAnsi
3874        // reading put `®` where the program draws `fi`. A TrueType or
3875        // symbolic face without an encoding keeps the WinAnsi stand-in.
3876        tex_math_builtin(fdict).unwrap_or_else(|| {
3877            if implied_standard_encoding(doc, fdict) {
3878                named_table(crate::encodings::STANDARD)
3879            } else {
3880                winansi_table()
3881            }
3882        })
3883    } else if base_name == b"WinAnsiEncoding" {
3884        let mut m = winansi_table();
3885        // PDF 32000-1:2008 Annex D.2, note 3 to the Latin set: "In
3886        // WinAnsiEncoding, all unused codes greater than 40 [octal] map to the
3887        // bullet character" — pdfium and pdf.js read them so. ReportLab draws
3888        // its default list bullet as `\177` in a non-embedded WinAnsi
3889        // Helvetica, which read U+FFFD before (#1102). Only a font that names
3890        // WinAnsiEncoding gets them: the no-/Encoding fallback above stands
3891        // in for a built-in encoding, where these codes stay undefined.
3892        for b in [0x7Fu8, 0x81, 0x8D, 0x8F, 0x90, 0x9D] {
3893            m.insert(b, '\u{2022}');
3894        }
3895        m
3896    } else {
3897        winansi_table()
3898    };
3899    // docling-parse#370: a font matched to Symbol or ZapfDingbats that
3900    // declares a Latin base encoding reads a code through that encoding only
3901    // where the face has the glyph the encoding names there; elsewhere its
3902    // own (AFM `FontSpecific`) code applies. Symbol + WinAnsi `a×b` reads
3903    // `α×β` — `multiply` is a Symbol glyph, `a` and `b` are not — and
3904    // MacRoman's `bullet` stays `•`.
3905    if let Some(latin) = crate::encodings::by_name(&base_name) {
3906        if let Some(face) = face() {
3907            let face_glyphs = match face {
3908                crate::symbol_fonts::SymbolFace::Symbol => crate::encodings::SYMBOL,
3909                crate::symbol_fonts::SymbolFace::ZapfDingbats => crate::encodings::ZAPF_DINGBATS,
3910            };
3911            let has = |n: &str| face_glyphs.iter().any(|&(_, g)| g == n);
3912            for code in 0..=255u8 {
3913                if crate::encodings::lookup(latin, code).is_some_and(has) {
3914                    continue;
3915                }
3916                if let Some(ch) = crate::symbol_fonts::face_text(face, code) {
3917                    m.insert(code, ch);
3918                }
3919            }
3920        }
3921    }
3922    // Apply /Differences: `code /glyphname /glyphname ... code ...`.
3923    if let Some(Object::Dictionary(d)) = enc {
3924        if let Some(Object::Array(diffs)) = d.get(b"Differences").ok().and_then(|o| deref(doc, o)) {
3925            let mut code = 0u8;
3926            for el in diffs {
3927                match el {
3928                    Object::Integer(i) => code = *i as u8,
3929                    Object::Name(name) => {
3930                        if let Some(ch) = glyph_name_to_char(name) {
3931                            m.insert(code, ch);
3932                        }
3933                        code = code.wrapping_add(1);
3934                    }
3935                    _ => {}
3936                }
3937            }
3938        }
3939    }
3940    m
3941}
3942
3943/// A code → glyph-name encoding ([`crate::encodings`]) read as text.
3944fn named_table(table: &[(u8, &str)]) -> HashMap<u8, char> {
3945    table
3946        .iter()
3947        .filter_map(|&(c, n)| glyph_name_to_char(n.as_bytes()).map(|ch| (c, ch)))
3948        .collect()
3949}
3950
3951/// A Type 1 font (`Type1` / `MMType1`) whose descriptor, if any, does not
3952/// flag it symbolic: StandardEncoding is its built-in encoding.
3953fn implied_standard_encoding(doc: &Document, fdict: &Dictionary) -> bool {
3954    let type1 = matches!(
3955        fdict.get(b"Subtype").ok().and_then(|o| o.as_name().ok()),
3956        Some(b"Type1" | b"MMType1")
3957    );
3958    let symbolic = fdict
3959        .get(b"FontDescriptor")
3960        .ok()
3961        .and_then(|o| as_dict(doc, o))
3962        .and_then(|fd| fd.get(b"Flags").ok())
3963        .and_then(|o| deref(doc, o))
3964        .and_then(num)
3965        .is_some_and(|f| (f as i64) & 4 != 0);
3966    type1 && !symbolic
3967}
3968
3969/// The fixed built-in encodings of the standard TeX math fonts (TeXbook
3970/// Appendix F), keyed off the base font name: `CMSY*` (symbols; `CMBSY` is its
3971/// bold) and `CMMI*` (math italic). These fonts ship no PDF `/Encoding` and no
3972/// ToUnicode, and their program is usually CFF — without this table the codes
3973/// fell through to StandardEncoding and rendered as the wrong ASCII.
3974fn tex_math_builtin(fdict: &Dictionary) -> Option<HashMap<u8, char>> {
3975    const CMSY: [char; 128] = [
3976        '−', '·', '×', '∗', '÷', '⋄', '±', '∓', '⊕', '⊖', '⊗', '⊘', '⊙', '◯', '∘', '•', '≍', '≡',
3977        '⊆', '⊇', '≤', '≥', '≼', '≽', '∼', '≈', '⊂', '⊃', '≪', '≫', '≺', '≻', '←', '→', '↑', '↓',
3978        '↔', '↗', '↘', '≃', '⇐', '⇒', '⇑', '⇓', '⇔', '↖', '↙', '∝', '′', '∞', '∈', '∋', '△', '▽',
3979        '\u{338}', '↦', '∀', '∃', '¬', '∅', 'ℜ', 'ℑ', '⊤', '⊥', 'ℵ', 'A', 'B', 'C', 'D', 'E', 'F',
3980        'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
3981        'Y', 'Z', '∪', '∩', '⊎', '∧', '∨', '⊢', '⊣', '⌊', '⌋', '⌈', '⌉', '{', '}', '⟨', '⟩', '|',
3982        '∥', '↕', '⇕', '\\', '≀', '√', '∐', '∇', '∫', '⊔', '⊓', '⊑', '⊒', '§', '†', '‡', '¶', '♣',
3983        '♢', '♡', '♠',
3984    ];
3985    const CMMI: [char; 128] = [
3986        'Γ', 'Δ', 'Θ', 'Λ', 'Ξ', 'Π', 'Σ', 'Υ', 'Φ', 'Ψ', 'Ω', 'α', 'β', 'γ', 'δ', 'ε', 'ζ', 'η',
3987        'θ', 'ι', 'κ', 'λ', 'μ', 'ν', 'ξ', 'π', 'ρ', 'σ', 'τ', 'υ', 'φ', 'χ', 'ψ', 'ω', 'ϵ', 'ϑ',
3988        'ϖ', 'ϱ', 'ς', 'ϕ', '↼', '↽', '⇀', '⇁', '↩', '↪', '▷', '◁', '0', '1', '2', '3', '4', '5',
3989        '6', '7', '8', '9', '.', ',', '<', '/', '>', '⋆', '∂', 'A', 'B', 'C', 'D', 'E', 'F', 'G',
3990        'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y',
3991        'Z', '♭', '♮', '♯', '⌣', '⌢', 'ℓ', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
3992        'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'ı', 'ȷ', '℘',
3993        '\u{20d7}', '⁀',
3994    ];
3995    let name = base_font_name(fdict)?;
3996    let up = name.to_ascii_uppercase();
3997    let table: &[char; 128] = if up.starts_with(b"CMSY") || up.starts_with(b"CMBSY") {
3998        &CMSY
3999    } else if up.starts_with(b"CMMI") {
4000        &CMMI
4001    } else {
4002        return None;
4003    };
4004    Some(
4005        table
4006            .iter()
4007            .enumerate()
4008            .map(|(i, &c)| (i as u8, c))
4009            .collect(),
4010    )
4011}
4012
4013/// The Adobe Glyph List's names for Latin-1 Supplement and Latin Extended-A
4014/// (plus `Euro`, `florin`, the comma-accent pairs): what a Type1 font's
4015/// `/Differences` or builtin encoding calls an accented or stroked letter.
4016/// 2203.01017v2 names `Ł` as `/Lslash` in a NimbusRomNo9L subset with no
4017/// ToUnicode, and the resolver, which knew only the ASCII, ligature and symbol
4018/// names, dropped the glyph outright (`Ł ukasz Kaiser` read `ukasz Kaiser`).
4019/// Sorted by name for the binary search in [`glyph_name_to_char`].
4020const AGL_LATIN: &[(&str, char)] = &[
4021    ("AE", '\u{00C6}'),
4022    ("Aacute", '\u{00C1}'),
4023    ("Abreve", '\u{0102}'),
4024    ("Acircumflex", '\u{00C2}'),
4025    ("Adieresis", '\u{00C4}'),
4026    ("Agrave", '\u{00C0}'),
4027    ("Amacron", '\u{0100}'),
4028    ("Aogonek", '\u{0104}'),
4029    ("Aring", '\u{00C5}'),
4030    ("Atilde", '\u{00C3}'),
4031    ("Cacute", '\u{0106}'),
4032    ("Ccaron", '\u{010C}'),
4033    ("Ccedilla", '\u{00C7}'),
4034    ("Ccircumflex", '\u{0108}'),
4035    ("Cdotaccent", '\u{010A}'),
4036    ("Dcaron", '\u{010E}'),
4037    ("Dcroat", '\u{0110}'),
4038    ("Eacute", '\u{00C9}'),
4039    ("Ebreve", '\u{0114}'),
4040    ("Ecaron", '\u{011A}'),
4041    ("Ecircumflex", '\u{00CA}'),
4042    ("Edieresis", '\u{00CB}'),
4043    ("Edotaccent", '\u{0116}'),
4044    ("Egrave", '\u{00C8}'),
4045    ("Emacron", '\u{0112}'),
4046    ("Eng", '\u{014A}'),
4047    ("Eogonek", '\u{0118}'),
4048    ("Eth", '\u{00D0}'),
4049    ("Euro", '\u{20AC}'),
4050    ("Gbreve", '\u{011E}'),
4051    ("Gcircumflex", '\u{011C}'),
4052    ("Gcommaaccent", '\u{0122}'),
4053    ("Gdotaccent", '\u{0120}'),
4054    ("Hbar", '\u{0126}'),
4055    ("Hcircumflex", '\u{0124}'),
4056    ("IJ", '\u{0132}'),
4057    ("Iacute", '\u{00CD}'),
4058    ("Ibreve", '\u{012C}'),
4059    ("Icircumflex", '\u{00CE}'),
4060    ("Idieresis", '\u{00CF}'),
4061    ("Idotaccent", '\u{0130}'),
4062    ("Igrave", '\u{00CC}'),
4063    ("Imacron", '\u{012A}'),
4064    ("Iogonek", '\u{012E}'),
4065    ("Itilde", '\u{0128}'),
4066    ("Jcircumflex", '\u{0134}'),
4067    ("Kcommaaccent", '\u{0136}'),
4068    ("Lacute", '\u{0139}'),
4069    ("Lcaron", '\u{013D}'),
4070    ("Lcommaaccent", '\u{013B}'),
4071    ("Ldot", '\u{013F}'),
4072    ("Lslash", '\u{0141}'),
4073    ("Nacute", '\u{0143}'),
4074    ("Ncaron", '\u{0147}'),
4075    ("Ncommaaccent", '\u{0145}'),
4076    ("Ntilde", '\u{00D1}'),
4077    ("OE", '\u{0152}'),
4078    ("Oacute", '\u{00D3}'),
4079    ("Obreve", '\u{014E}'),
4080    ("Ocircumflex", '\u{00D4}'),
4081    ("Odieresis", '\u{00D6}'),
4082    ("Ograve", '\u{00D2}'),
4083    ("Ohungarumlaut", '\u{0150}'),
4084    ("Omacron", '\u{014C}'),
4085    ("Oslash", '\u{00D8}'),
4086    ("Otilde", '\u{00D5}'),
4087    ("Racute", '\u{0154}'),
4088    ("Rcaron", '\u{0158}'),
4089    ("Rcommaaccent", '\u{0156}'),
4090    ("Sacute", '\u{015A}'),
4091    ("Scaron", '\u{0160}'),
4092    ("Scedilla", '\u{015E}'),
4093    ("Scircumflex", '\u{015C}'),
4094    ("Scommaaccent", '\u{0218}'),
4095    ("Tbar", '\u{0166}'),
4096    ("Tcaron", '\u{0164}'),
4097    ("Tcommaaccent", '\u{0162}'),
4098    ("Thorn", '\u{00DE}'),
4099    ("Uacute", '\u{00DA}'),
4100    ("Ubreve", '\u{016C}'),
4101    ("Ucircumflex", '\u{00DB}'),
4102    ("Udieresis", '\u{00DC}'),
4103    ("Ugrave", '\u{00D9}'),
4104    ("Uhungarumlaut", '\u{0170}'),
4105    ("Umacron", '\u{016A}'),
4106    ("Uogonek", '\u{0172}'),
4107    ("Uring", '\u{016E}'),
4108    ("Utilde", '\u{0168}'),
4109    ("Wcircumflex", '\u{0174}'),
4110    ("Yacute", '\u{00DD}'),
4111    ("Ycircumflex", '\u{0176}'),
4112    ("Ydieresis", '\u{0178}'),
4113    ("Zacute", '\u{0179}'),
4114    ("Zcaron", '\u{017D}'),
4115    ("Zdotaccent", '\u{017B}'),
4116    ("aacute", '\u{00E1}'),
4117    ("abreve", '\u{0103}'),
4118    ("acircumflex", '\u{00E2}'),
4119    ("acute", '\u{00B4}'),
4120    ("adieresis", '\u{00E4}'),
4121    ("ae", '\u{00E6}'),
4122    ("agrave", '\u{00E0}'),
4123    ("amacron", '\u{0101}'),
4124    ("aogonek", '\u{0105}'),
4125    ("aring", '\u{00E5}'),
4126    ("atilde", '\u{00E3}'),
4127    ("brokenbar", '\u{00A6}'),
4128    ("cacute", '\u{0107}'),
4129    ("ccaron", '\u{010D}'),
4130    ("ccedilla", '\u{00E7}'),
4131    ("ccircumflex", '\u{0109}'),
4132    ("cdotaccent", '\u{010B}'),
4133    ("cedilla", '\u{00B8}'),
4134    ("cent", '\u{00A2}'),
4135    ("currency", '\u{00A4}'),
4136    ("dcaron", '\u{010F}'),
4137    ("dcroat", '\u{0111}'),
4138    ("dieresis", '\u{00A8}'),
4139    ("dotlessi", '\u{0131}'),
4140    ("eacute", '\u{00E9}'),
4141    ("ebreve", '\u{0115}'),
4142    ("ecaron", '\u{011B}'),
4143    ("ecircumflex", '\u{00EA}'),
4144    ("edieresis", '\u{00EB}'),
4145    ("edotaccent", '\u{0117}'),
4146    ("egrave", '\u{00E8}'),
4147    ("emacron", '\u{0113}'),
4148    ("eng", '\u{014B}'),
4149    ("eogonek", '\u{0119}'),
4150    ("eth", '\u{00F0}'),
4151    ("exclamdown", '\u{00A1}'),
4152    ("florin", '\u{0192}'),
4153    ("gbreve", '\u{011F}'),
4154    ("gcircumflex", '\u{011D}'),
4155    ("gcommaaccent", '\u{0123}'),
4156    ("gdotaccent", '\u{0121}'),
4157    ("germandbls", '\u{00DF}'),
4158    ("guillemotleft", '\u{00AB}'),
4159    ("guillemotright", '\u{00BB}'),
4160    ("hbar", '\u{0127}'),
4161    ("hcircumflex", '\u{0125}'),
4162    ("iacute", '\u{00ED}'),
4163    ("ibreve", '\u{012D}'),
4164    ("icircumflex", '\u{00EE}'),
4165    ("idieresis", '\u{00EF}'),
4166    ("igrave", '\u{00EC}'),
4167    ("ij", '\u{0133}'),
4168    ("imacron", '\u{012B}'),
4169    ("iogonek", '\u{012F}'),
4170    ("itilde", '\u{0129}'),
4171    ("jcircumflex", '\u{0135}'),
4172    ("kcommaaccent", '\u{0137}'),
4173    ("kgreenlandic", '\u{0138}'),
4174    ("lacute", '\u{013A}'),
4175    ("lcaron", '\u{013E}'),
4176    ("lcommaaccent", '\u{013C}'),
4177    ("ldot", '\u{0140}'),
4178    ("logicalnot", '\u{00AC}'),
4179    ("longs", '\u{017F}'),
4180    ("lslash", '\u{0142}'),
4181    ("macron", '\u{00AF}'),
4182    ("nacute", '\u{0144}'),
4183    ("napostrophe", '\u{0149}'),
4184    ("ncaron", '\u{0148}'),
4185    ("ncommaaccent", '\u{0146}'),
4186    ("ntilde", '\u{00F1}'),
4187    ("oacute", '\u{00F3}'),
4188    ("obreve", '\u{014F}'),
4189    ("ocircumflex", '\u{00F4}'),
4190    ("odieresis", '\u{00F6}'),
4191    ("oe", '\u{0153}'),
4192    ("ograve", '\u{00F2}'),
4193    ("ohungarumlaut", '\u{0151}'),
4194    ("omacron", '\u{014D}'),
4195    ("onehalf", '\u{00BD}'),
4196    ("onequarter", '\u{00BC}'),
4197    ("onesuperior", '\u{00B9}'),
4198    ("ordfeminine", '\u{00AA}'),
4199    ("ordmasculine", '\u{00BA}'),
4200    ("oslash", '\u{00F8}'),
4201    ("otilde", '\u{00F5}'),
4202    ("paragraph", '\u{00B6}'),
4203    ("questiondown", '\u{00BF}'),
4204    ("racute", '\u{0155}'),
4205    ("rcaron", '\u{0159}'),
4206    ("rcommaaccent", '\u{0157}'),
4207    ("sacute", '\u{015B}'),
4208    ("scaron", '\u{0161}'),
4209    ("scedilla", '\u{015F}'),
4210    ("scircumflex", '\u{015D}'),
4211    ("scommaaccent", '\u{0219}'),
4212    ("section", '\u{00A7}'),
4213    ("sfthyphen", '\u{00AD}'),
4214    ("sterling", '\u{00A3}'),
4215    ("tbar", '\u{0167}'),
4216    ("tcaron", '\u{0165}'),
4217    ("tcommaaccent", '\u{0163}'),
4218    ("thorn", '\u{00FE}'),
4219    ("threequarters", '\u{00BE}'),
4220    ("threesuperior", '\u{00B3}'),
4221    ("twosuperior", '\u{00B2}'),
4222    ("uacute", '\u{00FA}'),
4223    ("ubreve", '\u{016D}'),
4224    ("ucircumflex", '\u{00FB}'),
4225    ("udieresis", '\u{00FC}'),
4226    ("ugrave", '\u{00F9}'),
4227    ("uhungarumlaut", '\u{0171}'),
4228    ("umacron", '\u{016B}'),
4229    ("uogonek", '\u{0173}'),
4230    ("uring", '\u{016F}'),
4231    ("utilde", '\u{0169}'),
4232    ("wcircumflex", '\u{0175}'),
4233    ("yacute", '\u{00FD}'),
4234    ("ycircumflex", '\u{0177}'),
4235    ("ydieresis", '\u{00FF}'),
4236    ("yen", '\u{00A5}'),
4237    ("zacute", '\u{017A}'),
4238    ("zcaron", '\u{017E}'),
4239    ("zdotaccent", '\u{017C}'),
4240];
4241
4242/// docling-parse 7.25's reading text of a PostScript glyph name in a
4243/// program's builtin encoding (`builtin_font_encoding::glyph_name_to_utf8`,
4244/// #1113): `.notdef` and an index-style name (`g12`, `gid00012`, `cid12`,
4245/// `index12`) carry none; a stylistic `.suffix` is dropped; then the glyph
4246/// tables (the symbol fonts' names, [`glyph_name_to_char`]'s), a `uniXXXX`
4247/// sequence (a ligature's code points), a `uXXXX`–`uXXXXXX` name.
4248pub(crate) fn builtin_glyph_text(name: &str) -> Option<String> {
4249    if name.is_empty() || name == ".notdef" {
4250        return None;
4251    }
4252    let name = match name.find('.') {
4253        Some(dot) if dot > 0 => &name[..dot],
4254        _ => name,
4255    };
4256    let lower = name.to_ascii_lowercase();
4257    let index_name = ["gid", "glyph", "g", "cid", "index"].iter().any(|p| {
4258        lower
4259            .strip_prefix(p)
4260            .is_some_and(|d| !d.is_empty() && d.bytes().all(|b| b.is_ascii_digit()))
4261    });
4262    if index_name {
4263        return None;
4264    }
4265    if let Some(c) = crate::symbol_fonts::symbol_glyph_char(name) {
4266        return Some(c.to_string());
4267    }
4268    let hex_points = |hex: &str, width: usize| -> Option<String> {
4269        (!hex.is_empty()
4270            && hex.len().is_multiple_of(width)
4271            && hex.bytes().all(|b| b.is_ascii_hexdigit()))
4272        .then(|| {
4273            (0..hex.len())
4274                .step_by(width)
4275                .map(|i| {
4276                    u32::from_str_radix(&hex[i..i + width], 16)
4277                        .ok()
4278                        .and_then(char::from_u32)
4279                })
4280                .collect::<Option<String>>()
4281        })
4282        .flatten()
4283    };
4284    if let Some(hex) = name.strip_prefix("uni") {
4285        if let Some(t) = hex_points(hex, 4) {
4286            return Some(t);
4287        }
4288    }
4289    if let Some(hex) = name.strip_prefix('u') {
4290        if (4..=6).contains(&hex.len()) {
4291            if let Some(t) = hex_points(hex, hex.len()) {
4292                return Some(t);
4293            }
4294        }
4295    }
4296    glyph_name_to_char(name.as_bytes()).map(String::from)
4297}
4298
4299/// Resolve an Adobe glyph name to Unicode: `uniXXXX`, single ASCII letters, the
4300/// digit/punctuation names from the Adobe Glyph List, and common typographic
4301/// names. A `.suffix` (`one.taboldstyle`, `a.sc`) is stripped and the base name
4302/// retried — docling renders these as the base character.
4303pub(crate) fn glyph_name_to_char(name: &[u8]) -> Option<char> {
4304    let s = std::str::from_utf8(name).ok()?;
4305    // `uniXXXX`. A name that merely starts with `uni` (`union`) goes on to
4306    // the tables: it used to end here, unresolved, for want of four digits.
4307    if let Some(cp) = s
4308        .strip_prefix("uni")
4309        .and_then(|hex| hex.get(0..4))
4310        .and_then(|hex| u32::from_str_radix(hex, 16).ok())
4311    {
4312        return char::from_u32(cp);
4313    }
4314    // Single ASCII letter names (`A`, `m`) map to themselves.
4315    if s.len() == 1 {
4316        let b = s.as_bytes()[0];
4317        if b.is_ascii_alphabetic() {
4318            return Some(b as char);
4319        }
4320    }
4321    let resolved = match s {
4322        "space" => ' ',
4323        "exclam" => '!',
4324        "quotedbl" => '"',
4325        "numbersign" => '#',
4326        "dollar" => '$',
4327        "percent" => '%',
4328        "ampersand" => '&',
4329        "quotesingle" => '\'',
4330        "parenleft" => '(',
4331        "parenright" => ')',
4332        "asterisk" => '*',
4333        "plus" => '+',
4334        "comma" => ',',
4335        "hyphen" => '-',
4336        "period" => '.',
4337        "slash" => '/',
4338        "zero" => '0',
4339        "one" => '1',
4340        "two" => '2',
4341        "three" => '3',
4342        "four" => '4',
4343        "five" => '5',
4344        "six" => '6',
4345        "seven" => '7',
4346        "eight" => '8',
4347        "nine" => '9',
4348        "colon" => ':',
4349        "semicolon" => ';',
4350        "less" => '<',
4351        "equal" => '=',
4352        "greater" => '>',
4353        "question" => '?',
4354        "at" => '@',
4355        "bracketleft" => '[',
4356        "backslash" => '\\',
4357        "bracketright" => ']',
4358        "asciicircum" => '^',
4359        "underscore" => '_',
4360        "grave" => '`',
4361        "braceleft" => '{',
4362        "bar" => '|',
4363        "braceright" => '}',
4364        "asciitilde" => '~',
4365        "bullet" => '\u{2022}',
4366        "periodcentered" => '\u{00B7}',
4367        "endash" => '\u{2013}',
4368        "emdash" => '\u{2014}',
4369        "quoteright" => '\u{2019}',
4370        "quoteleft" => '\u{2018}',
4371        "quotedblleft" => '\u{201C}',
4372        "quotedblright" => '\u{201D}',
4373        "quotedblbase" => '\u{201E}',
4374        "quotesinglbase" => '\u{201A}',
4375        // Latin f-ligatures named in `/Differences` (e.g. 2305's body font). These
4376        // map to the presentation-form code points, which `decompose_ligatures`
4377        // then spells back out (`ff`→"ff") — without them the glyph decodes to
4378        // nothing and the sanitizer fills the gap with a space (`di erences`).
4379        "ff" => '\u{FB00}',
4380        "fi" => '\u{FB01}',
4381        "fl" => '\u{FB02}',
4382        "ffi" => '\u{FB03}',
4383        "ffl" => '\u{FB04}',
4384        "ft" => '\u{FB05}',
4385        "st" => '\u{FB06}',
4386        "degree" => '\u{00B0}',
4387        "trademark" => '\u{2122}',
4388        "registered" => '\u{00AE}',
4389        "copyright" => '\u{00A9}',
4390        "ellipsis" => '\u{2026}',
4391        "minus" => '\u{2212}',
4392        "fraction" => '\u{2044}',
4393        "nbspace" => '\u{00A0}',
4394        // Greek + math glyph names (standard Adobe Glyph List). Standard TeX math
4395        // fonts (CMMI/CMSY/…) name their glyphs this way in the embedded font
4396        // program's `/Encoding`; without these a `λ`/`≤` decodes to nothing and is
4397        // dropped from body text (`and λ set to 0.5` → `and set to 0.5`).
4398        "alpha" => '\u{03B1}',
4399        "beta" => '\u{03B2}',
4400        "gamma" => '\u{03B3}',
4401        "delta" => '\u{03B4}',
4402        "epsilon" | "epsilon1" => '\u{03B5}',
4403        "zeta" => '\u{03B6}',
4404        "eta" => '\u{03B7}',
4405        "theta" | "theta1" => '\u{03B8}',
4406        "iota" => '\u{03B9}',
4407        "kappa" => '\u{03BA}',
4408        "lambda" => '\u{03BB}',
4409        "mu" => '\u{03BC}',
4410        "nu" => '\u{03BD}',
4411        "xi" => '\u{03BE}',
4412        "omicron" => '\u{03BF}',
4413        "pi" | "pi1" => '\u{03C0}',
4414        "rho" | "rho1" => '\u{03C1}',
4415        "sigma" => '\u{03C3}',
4416        "sigma1" => '\u{03C2}',
4417        "tau" => '\u{03C4}',
4418        "upsilon" => '\u{03C5}',
4419        "phi" | "phi1" => '\u{03C6}',
4420        "chi" => '\u{03C7}',
4421        "psi" => '\u{03C8}',
4422        "omega" | "omega1" => '\u{03C9}',
4423        "Gamma" => '\u{0393}',
4424        "Delta" => '\u{0394}',
4425        "Theta" => '\u{0398}',
4426        "Lambda" => '\u{039B}',
4427        "Xi" => '\u{039E}',
4428        "Pi" => '\u{03A0}',
4429        "Sigma" => '\u{03A3}',
4430        "Upsilon" => '\u{03A5}',
4431        "Phi" => '\u{03A6}',
4432        "Psi" => '\u{03A8}',
4433        "Omega" => '\u{03A9}',
4434        "lessequal" => '\u{2264}',
4435        "greaterequal" => '\u{2265}',
4436        "notequal" => '\u{2260}',
4437        "approxequal" => '\u{2248}',
4438        "equivalence" => '\u{2261}',
4439        "element" => '\u{2208}',
4440        "plusminus" => '\u{00B1}',
4441        "multiply" => '\u{00D7}',
4442        "divide" => '\u{00F7}',
4443        "infinity" => '\u{221E}',
4444        "partialdiff" => '\u{2202}',
4445        "gradient" => '\u{2207}',
4446        "summation" => '\u{2211}',
4447        "product" => '\u{220F}',
4448        "integral" => '\u{222B}',
4449        "radical" => '\u{221A}',
4450        "proportional" => '\u{221D}',
4451        "arrowright" => '\u{2192}',
4452        "arrowleft" => '\u{2190}',
4453        "arrowup" => '\u{2191}',
4454        "arrowdown" => '\u{2193}',
4455        "arrowboth" => '\u{2194}',
4456        "arrowdblright" => '\u{21D2}',
4457        "logicaland" => '\u{2227}',
4458        "logicalor" => '\u{2228}',
4459        "intersection" => '\u{2229}',
4460        "union" => '\u{222A}',
4461        "similar" => '\u{223C}',
4462        "congruent" => '\u{2245}',
4463        "dotmath" => '\u{22C5}',
4464        "asteriskmath" => '\u{2217}',
4465        _ => {
4466            if let Ok(i) = AGL_LATIN.binary_search_by_key(&s, |(n, _)| n) {
4467                return Some(AGL_LATIN[i].1);
4468            }
4469            // The math names the arms above leave out (#1121): the TeX math
4470            // fonts' own (`parenleftbig`, `radicalbig`, `integraldisplay`,
4471            // `prime`), then the Symbol font's — Glyph List names such as
4472            // `universal`, `existential`, `arrowup`, which a Latin Modern
4473            // math font's `/Differences` uses. The arms above keep their
4474            // readings where docling-parse's lists differ (`Delta` is the
4475            // Greek letter here, the Glyph List's `∆` increment sign there).
4476            // Last, the Adobe Glyph List in full (the `glyph-list` feature):
4477            // every name none of the above reads — the `afii` names of a
4478            // Cyrillic, Hebrew or Arabic font, the rest of the symbols.
4479            if let Some(ch) = crate::glyph_names::lookup(s)
4480                .or_else(|| crate::symbol_fonts::symbol_glyph_char(s))
4481                .or_else(|| crate::adobe_glyph_list::lookup(s))
4482            {
4483                return Some(ch);
4484            }
4485            // Strip an AGL `.suffix` (oldstyle/small-cap variant) and retry.
4486            if let Some((base, _)) = s.split_once('.') {
4487                if !base.is_empty() {
4488                    return glyph_name_to_char(base.as_bytes());
4489                }
4490            }
4491            // An AGL ligature name joins its components with `_` (`f_f_i`,
4492            // `f_l` — what a re-encoded Libertine subset calls them); joined,
4493            // the presentation-form arms above resolve them.
4494            if s.contains('_') {
4495                let joined: String = s.chars().filter(|&c| c != '_').collect();
4496                if !joined.is_empty() && joined.len() < s.len() {
4497                    return glyph_name_to_char(joined.as_bytes());
4498                }
4499            }
4500            return None;
4501        }
4502    };
4503    Some(resolved)
4504}
4505
4506/// Minimal WinAnsiEncoding (Latin-1-ish) for simple fonts lacking ToUnicode.
4507fn winansi_table() -> HashMap<u8, char> {
4508    let mut m = HashMap::new();
4509    for b in 0x20u8..=0x7e {
4510        m.insert(b, b as char);
4511    }
4512    // High range: Windows-1252 printable points that differ from Latin-1.
4513    let extra: &[(u8, char)] = &[
4514        (0x91, '\u{2018}'),
4515        (0x92, '\u{2019}'),
4516        (0x93, '\u{201C}'),
4517        (0x94, '\u{201D}'),
4518        (0x95, '\u{2022}'),
4519        (0x96, '\u{2013}'),
4520        (0x97, '\u{2014}'),
4521        (0x85, '\u{2026}'),
4522        (0xA0, '\u{00A0}'),
4523        // The rest of Windows-1252's 0x80–0x9F row. Left out, the German
4524        // opening quote `„` (0x84) vanished from the text layer while its
4525        // closing `“` (0x93) stayed (#922); `€ ‚ ƒ † ‡ ˆ ‰ Š ‹ Œ Ž ˜ ™ š › œ ž Ÿ`
4526        // were lost the same way. 0x81/0x8D/0x8F/0x90/0x9D (and 0x7F) are
4527        // unused; a font naming WinAnsiEncoding reads them as bullets
4528        // (`simple_encoding_table`, #1102).
4529        (0x80, '\u{20AC}'),
4530        (0x82, '\u{201A}'),
4531        (0x83, '\u{0192}'),
4532        (0x84, '\u{201E}'),
4533        (0x86, '\u{2020}'),
4534        (0x87, '\u{2021}'),
4535        (0x88, '\u{02C6}'),
4536        (0x89, '\u{2030}'),
4537        (0x8A, '\u{0160}'),
4538        (0x8B, '\u{2039}'),
4539        (0x8C, '\u{0152}'),
4540        (0x8E, '\u{017D}'),
4541        (0x98, '\u{02DC}'),
4542        (0x99, '\u{2122}'),
4543        (0x9A, '\u{0161}'),
4544        (0x9B, '\u{203A}'),
4545        (0x9C, '\u{0153}'),
4546        (0x9E, '\u{017E}'),
4547        (0x9F, '\u{0178}'),
4548    ];
4549    for &(b, c) in extra {
4550        m.insert(b, c);
4551    }
4552    for b in 0xA1u8..=0xFF {
4553        m.entry(b).or_insert(b as char);
4554    }
4555    m
4556}
4557
4558/// MacRomanEncoding: ASCII plus the whole high range, 0x80–0xFF, as Mac OS
4559/// Roman maps it (#744) — the table pdfium, pdftotext and pdf.js decode with.
4560/// Two codes follow the PDF reference instead of Apple's later revisions:
4561/// 0xDB is `currency` (¤, not €), and 0xF0 (`apple`, a private-use glyph) is
4562/// left unmapped. 0xCA, the PDF table's second `space`, reads as a no-break
4563/// space.
4564fn macroman_table() -> HashMap<u8, char> {
4565    #[rustfmt::skip]
4566    const HIGH: [char; 128] = [
4567        'Ä', 'Å', 'Ç', 'É', 'Ñ', 'Ö', 'Ü', 'á',  // 0x80
4568        'à', 'â', 'ä', 'ã', 'å', 'ç', 'é', 'è',  // 0x88
4569        'ê', 'ë', 'í', 'ì', 'î', 'ï', 'ñ', 'ó',  // 0x90
4570        'ò', 'ô', 'ö', 'õ', 'ú', 'ù', 'û', 'ü',  // 0x98
4571        '†', '°', '¢', '£', '§', '•', '¶', 'ß',  // 0xA0
4572        '®', '©', '™', '´', '¨', '≠', 'Æ', 'Ø',  // 0xA8
4573        '∞', '±', '≤', '≥', '¥', 'µ', '∂', '∑',  // 0xB0
4574        '∏', 'π', '∫', 'ª', 'º', 'Ω', 'æ', 'ø',  // 0xB8
4575        '¿', '¡', '¬', '√', 'ƒ', '≈', '∆', '«',  // 0xC0
4576        '»', '…', '\u{00A0}', 'À', 'Ã', 'Õ', 'Œ', 'œ',  // 0xC8
4577        '–', '—', '“', '”', '‘', '’', '÷', '◊',  // 0xD0
4578        'ÿ', 'Ÿ', '⁄', '¤', '‹', '›', 'fi', 'fl',  // 0xD8
4579        '‡', '·', '‚', '„', '‰', 'Â', 'Ê', 'Á',  // 0xE0
4580        'Ë', 'È', 'Í', 'Î', 'Ï', 'Ì', 'Ó', 'Ô',  // 0xE8
4581        '\0', 'Ò', 'Ú', 'Û', 'Ù', 'ı', 'ˆ', '˜',  // 0xF0
4582        '¯', '˘', '˙', '˚', '¸', '˝', '˛', 'ˇ',  // 0xF8
4583    ];
4584    let mut m = HashMap::new();
4585    for b in 0x20u8..=0x7e {
4586        m.insert(b, b as char);
4587    }
4588    for (b, &c) in (0x80u8..=0xFF).zip(HIGH.iter()) {
4589        if c != '\0' {
4590            m.insert(b, c);
4591        }
4592    }
4593    m
4594}
4595
4596#[cfg(test)]
4597mod glyph_names {
4598    /// `/Lslash` and the other Latin-1 / Latin Extended-A glyph names a Type1
4599    /// `/Differences` uses resolve (2203.01017v2's `Łukasz`); the table the
4600    /// lookup bisects is sorted and the ligature / symbol arms still win.
4601    #[test]
4602    fn latin_glyph_names_resolve() {
4603        for w in super::AGL_LATIN.windows(2) {
4604            assert!(
4605                w[0].0 < w[1].0,
4606                "AGL_LATIN not sorted at {:?} / {:?}",
4607                w[0].0,
4608                w[1].0
4609            );
4610        }
4611        for (name, ch) in [
4612            ("Lslash", 'Ł'),
4613            ("lslash", 'ł'),
4614            ("Aacute", 'Á'),
4615            ("aacute", 'á'),
4616            ("Scaron", 'Š'),
4617            ("germandbls", 'ß'),
4618            ("oe", 'œ'),
4619            ("Ydieresis", 'Ÿ'),
4620            ("Euro", '€'),
4621            ("Lslash.sc", 'Ł'),
4622            ("fi", '\u{FB01}'),
4623            ("Omega", '\u{03A9}'),
4624        ] {
4625            assert_eq!(
4626                super::glyph_name_to_char(name.as_bytes()),
4627                Some(ch),
4628                "{name}"
4629            );
4630        }
4631        assert_eq!(super::glyph_name_to_char(b"g123"), None);
4632        // AGL ligature names: components joined with `_`.
4633        assert_eq!(super::glyph_name_to_char(b"f_f_i"), Some('\u{FB03}'));
4634        assert_eq!(super::glyph_name_to_char(b"f_l"), Some('\u{FB02}'));
4635        assert_eq!(super::glyph_name_to_char(b"a_b"), None);
4636    }
4637
4638    /// The stale-CMap case: ToUnicode maps a code to its own identity while
4639    /// `/Differences` names a ligature there — the name wins; a CMap that
4640    /// maps the code anywhere else, or a code with no entry, is untouched.
4641    #[test]
4642    fn a_stale_tounicode_yields_to_differences() {
4643        use lopdf::Object;
4644        use std::collections::HashMap;
4645        let mut tu: HashMap<u32, String> = HashMap::new();
4646        tu.insert(33, "!".into()); // identity — stale
4647        tu.insert(34, "x".into()); // the producer meant it
4648        let diffs = vec![
4649            Object::Integer(33),
4650            Object::Name(b"f_f_i".to_vec()),
4651            Object::Name(b"f_i".to_vec()),
4652            Object::Name(b"f_f".to_vec()),
4653            Object::Integer(65),
4654            Object::Name(b"A".to_vec()), // identity on both sides: nothing to do
4655        ];
4656        super::reconcile_stale_tounicode(&mut tu, &diffs);
4657        assert_eq!(tu.get(&33).map(String::as_str), Some("\u{FB03}"));
4658        assert_eq!(tu.get(&34).map(String::as_str), Some("x"));
4659        assert_eq!(tu.get(&35), None);
4660        assert_eq!(tu.get(&65), None);
4661    }
4662
4663    /// #1121: a ToUnicode value that says nothing — empty, a NUL, U+FFFD, a
4664    /// noncharacter — yields to the `/Differences` name (docling-parse's
4665    /// `has_to_unicode`). 1503.04203's embedded figure maps its re-encoded
4666    /// TeX glyphs to `<0000>`: `/minus` and `/Delta` at code 33. A value that
4667    /// says something stays, and so does one whose name does not resolve.
4668    #[test]
4669    fn a_tounicode_value_that_says_nothing_yields_to_differences() {
4670        use lopdf::Object;
4671        use std::collections::HashMap;
4672        let name = |n: &str| Object::Name(n.as_bytes().to_vec());
4673        let mut tu: HashMap<u32, String> = HashMap::new();
4674        tu.insert(33, "\u{0}".into());
4675        tu.insert(34, "\u{FFFD}".into());
4676        tu.insert(35, "\u{FFFF}".into());
4677        tu.insert(36, String::new());
4678        tu.insert(37, "\u{0}".into()); // the name is unknown: left alone
4679        tu.insert(38, "\u{0}\u{0}".into()); // not a single code point
4680        tu.insert(39, "−".into()); // says something
4681        let diffs = vec![
4682            Object::Integer(33),
4683            name("minus"),
4684            name("Delta"),
4685            name("radicalbig"),
4686            name("parenleftbig"),
4687            name("nosuchglyphname"),
4688            name("plus"),
4689            name("hyphen"),
4690        ];
4691        super::reconcile_stale_tounicode(&mut tu, &diffs);
4692        let got = |c: u32| tu.get(&c).map(String::as_str);
4693        assert_eq!(got(33), Some("−"));
4694        assert_eq!(got(34), Some("Δ"));
4695        assert_eq!(got(35), Some("√"));
4696        assert_eq!(got(36), Some("("));
4697        assert_eq!(got(37), Some("\u{0}"));
4698        assert_eq!(got(38), Some("\u{0}\u{0}"));
4699        assert_eq!(got(39), Some("−"));
4700    }
4701
4702    /// #1121: the TeX delimiter and operator names resolve through the glyph
4703    /// rules, the Symbol font's Glyph List names through its table; the
4704    /// names this resolver already knew keep their reading, and a name that
4705    /// only starts with `uni` is no `uniXXXX`.
4706    #[test]
4707    fn tex_glyph_names_resolve() {
4708        let c = |n: &str| super::glyph_name_to_char(n.as_bytes());
4709        assert_eq!(c("parenleftbig"), Some('('));
4710        assert_eq!(c("parenrightBigg"), Some(')'));
4711        assert_eq!(c("integraldisplay"), Some('∫'));
4712        assert_eq!(c("trianglerightsld"), Some('▶'));
4713        assert_eq!(c("prime"), Some('′'));
4714        assert_eq!(c("universal"), Some('∀'));
4715        assert_eq!(c("existential"), Some('∃'));
4716        assert_eq!(c("arrowup"), Some('↑'));
4717        assert_eq!(c("union"), Some('∪'));
4718        assert_eq!(c("uni2212"), Some('−'));
4719        assert_eq!(c("minus"), Some('−'));
4720        assert_eq!(c("Delta"), Some('Δ'), "the Greek letter, not the list's ∆");
4721        assert_eq!(c("angbracketleft"), Some('⟨'));
4722        assert_eq!(c("nosuchglyphname"), None);
4723    }
4724}
4725
4726#[cfg(test)]
4727mod page_box_frame {
4728    use super::*;
4729    use lopdf::dictionary;
4730
4731    /// One page, `boxes` spliced into the page dictionary verbatim, one text
4732    /// run at user-space `(x, y)`.
4733    fn pdf(boxes: &str, x: f32, y: f32) -> Vec<u8> {
4734        pdf_content(
4735            boxes,
4736            &format!("BT /F1 12 Tf {x} {y} Td (First printing) Tj ET\n"),
4737        )
4738    }
4739
4740    /// One page, `boxes` spliced into the page dictionary, `content` as its
4741    /// content stream (font `/F1` = Helvetica).
4742    fn pdf_content(boxes: &str, content: &str) -> Vec<u8> {
4743        let objs: Vec<String> = vec![
4744            "<</Type/Catalog/Pages 2 0 R>>".into(),
4745            format!("<</Type/Pages/Kids[3 0 R]/Count 1{boxes}>>"),
4746            "<</Type/Page/Parent 2 0 R/Contents 4 0 R/Resources<</Font<</F1 5 0 R>>>>>>".into(),
4747            format!("<</Length {}>>stream\n{content}endstream", content.len()),
4748            "<</Type/Font/Subtype/Type1/BaseFont/Helvetica>>".into(),
4749        ];
4750        let mut out = b"%PDF-1.4\n".to_vec();
4751        let mut offsets = Vec::new();
4752        for (i, body) in objs.iter().enumerate() {
4753            offsets.push(out.len());
4754            out.extend_from_slice(format!("{} 0 obj{body}endobj\n", i + 1).as_bytes());
4755        }
4756        let xref_at = out.len();
4757        out.extend_from_slice(
4758            format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes(),
4759        );
4760        for off in &offsets {
4761            out.extend_from_slice(format!("{off:010} 00000 n \n").as_bytes());
4762        }
4763        out.extend_from_slice(
4764            format!(
4765                "trailer<</Size {}/Root 1 0 R>>\nstartxref\n{xref_at}\n%%EOF\n",
4766                objs.len() + 1
4767            )
4768            .as_bytes(),
4769        );
4770        out
4771    }
4772
4773    /// One page whose `/Contents` is an array of separate streams.
4774    fn pdf_content_streams(contents: &[&[u8]]) -> Vec<u8> {
4775        pdf_with_streams(
4776            contents
4777                .iter()
4778                .map(|content| lopdf::Stream::new(Dictionary::new(), content.to_vec()))
4779                .collect(),
4780        )
4781    }
4782
4783    /// [`pdf_content_streams`] with the streams' dictionaries spelled out.
4784    fn pdf_with_streams(contents: Vec<lopdf::Stream>) -> Vec<u8> {
4785        let mut doc = Document::with_version("1.5");
4786        let streams = contents
4787            .into_iter()
4788            .map(|stream| Object::Reference(doc.add_object(stream)))
4789            .collect::<Vec<_>>();
4790        let font_id = doc.add_object(dictionary! {
4791            "Type" => "Font",
4792            "Subtype" => "Type1",
4793            "BaseFont" => "Helvetica",
4794        });
4795        let resources_id = doc.add_object(dictionary! {
4796            "Font" => dictionary! { "F1" => Object::Reference(font_id) },
4797        });
4798        let pages_id = doc.new_object_id();
4799        let page_id = doc.add_object(dictionary! {
4800            "Type" => "Page",
4801            "Parent" => Object::Reference(pages_id),
4802            "MediaBox" => vec![0.into(), 0.into(), 300.into(), 400.into()],
4803            "Contents" => streams,
4804            "Resources" => Object::Reference(resources_id),
4805        });
4806        doc.objects.insert(
4807            pages_id,
4808            Object::Dictionary(dictionary! {
4809                "Type" => "Pages",
4810                "Kids" => vec![Object::Reference(page_id)],
4811                "Count" => 1,
4812            }),
4813        );
4814        let catalog_id = doc.add_object(dictionary! {
4815            "Type" => "Catalog",
4816            "Pages" => Object::Reference(pages_id),
4817        });
4818        doc.trailer.set("Root", Object::Reference(catalog_id));
4819        let mut out = Vec::new();
4820        doc.save_to(&mut out).expect("save synthetic PDF");
4821        out
4822    }
4823
4824    fn only_page(bytes: &[u8]) -> (PageBox, Vec<Glyph>) {
4825        let doc = load_document(bytes).expect("loads");
4826        let pid = *doc.get_pages().values().next().expect("one page");
4827        (page_box(&doc, pid), page_glyphs(&doc, pid))
4828    }
4829
4830    /// The trimmed-book-page shape: MediaBox and CropBox both away from the
4831    /// origin (inherited from `/Pages`). The display box is the CropBox, and a
4832    /// glyph's coordinates count from its lower-left corner — the same numbers
4833    /// the same text gets on a page whose CropBox *is* `[0 0 w h]`.
4834    #[test]
4835    fn glyphs_count_from_the_cropbox_corner_like_pdfium() {
4836        let (pb, shifted) = only_page(&pdf(
4837            "/MediaBox[-56.505 -58.25 576.303 723.31]/CropBox[1.095 -0.65 518.703 665.71]",
4838            37.0 + 1.095,
4839            58.0 - 0.65,
4840        ));
4841        assert!((pb.l - 1.095).abs() < 1e-3 && (pb.b + 0.65).abs() < 1e-3);
4842        assert!(
4843            (pb.w - 517.608).abs() < 1e-3 && (pb.h - 666.36).abs() < 1e-3,
4844            "{pb:?}"
4845        );
4846        let (pb0, plain) = only_page(&pdf("/MediaBox[0 0 517.608 666.36]", 37.0, 58.0));
4847        assert!((pb0.w - pb.w).abs() < 1e-3 && (pb0.h - pb.h).abs() < 1e-3);
4848        assert_eq!(shifted.len(), plain.len());
4849        assert!(!plain.is_empty());
4850        for (a, b) in shifted.iter().zip(&plain) {
4851            assert!(
4852                (a.l - b.l).abs() < 1e-3 && (a.b - b.b).abs() < 1e-3,
4853                "{:?} vs {:?}",
4854                (a.l, a.b),
4855                (b.l, b.b)
4856            );
4857        }
4858        assert!((plain[0].l - 37.0).abs() < 1e-3, "{}", plain[0].l);
4859    }
4860
4861    fn text(glyphs: &[Glyph]) -> String {
4862        glyphs.iter().map(|g| g.ch).collect()
4863    }
4864
4865    /// #529: text drawn outside the display box — a print slug beside the
4866    /// CropBox, a tiled page's neighbour beyond the MediaBox — is dropped,
4867    /// glyph by glyph like docling-parse, instead of being clamped onto the
4868    /// page edge; a line crossing the edge keeps the glyphs that fit.
4869    #[test]
4870    fn glyphs_outside_the_display_box_are_dropped() {
4871        let (_, g) = only_page(&pdf_content(
4872            "/MediaBox[0 0 400 400]/CropBox[100 100 400 400]",
4873            "BT /F1 14 Tf 120 300 Td (Visible.) Tj ET\nBT /F1 8 Tf 5 40 Td (Slug) Tj ET\n",
4874        ));
4875        assert_eq!(text(&g), "Visible.");
4876        let (_, g) = only_page(&pdf_content(
4877            "/MediaBox[0 0 300 400]",
4878            "BT /F1 14 Tf 40 300 Td (On page) Tj ET\nBT /F1 14 Tf 400 250 Td (Beyond) Tj ET\n",
4879        ));
4880        assert_eq!(text(&g), "On page");
4881        // docling-parse: "Crossing the right edge" on a 300 pt page → "Crossing the rig".
4882        let (_, g) = only_page(&pdf_content(
4883            "/MediaBox[0 0 300 400]",
4884            "BT /F1 14 Tf 200 250 Td (Crossing the right edge) Tj ET\n",
4885        ));
4886        assert_eq!(text(&g), "Crossing the rig");
4887    }
4888
4889    #[test]
4890    fn leading_comment_content_stream_does_not_hide_later_text() {
4891        // The comment has its own EOL; lopdf inserts another while assembling
4892        // the streams, which is the boundary its 0.44 parser stopped at.
4893        let (_, glyphs) = only_page(&pdf_content_streams(&[
4894            b"% CANON_PFINF_TYPE2_TEXTOFF\n",
4895            b"BT /F1 14 Tf 40 300 Td (Second stream text) Tj ET",
4896        ]));
4897        assert_eq!(text(&glyphs), "Second stream text");
4898    }
4899
4900    /// A FlateDecode stream whose data breaks off mid-way (a truncated or
4901    /// corrupted download) — #1154. qpdf and pdfium keep what inflated
4902    /// before the damage; lopdf's `decompressed_content` fails and its
4903    /// `get_page_content` then spliced the *compressed* bytes into the
4904    /// content, which tokenized as garbage. The prefix reads, alone or
4905    /// between intact streams.
4906    #[test]
4907    fn a_damaged_flate_stream_keeps_its_inflated_prefix() {
4908        use std::io::Write as _;
4909        // A sync-flushed deflate of the text, then bytes that are no valid
4910        // deflate block: flate2 fails inside the one read that would have
4911        // returned the text, so lopdf's decoder ends up with nothing.
4912        let mut z = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default());
4913        z.write_all(b"BT /F1 14 Tf 40 200 Td (Partial) Tj ET\n")
4914            .expect("deflate");
4915        z.flush().expect("sync flush");
4916        let mut data = z.get_ref().clone();
4917        data.extend_from_slice(b"\x07garbage\n");
4918        let damaged =
4919            || lopdf::Stream::new(dictionary! { "Filter" => "FlateDecode" }, data.clone());
4920        let plain = |s: &[u8]| lopdf::Stream::new(Dictionary::new(), s.to_vec());
4921
4922        let (_, alone) = only_page(&pdf_with_streams(vec![damaged()]));
4923        assert!(text(&alone).starts_with("Partial"), "{:?}", text(&alone));
4924
4925        let (_, glyphs) = only_page(&pdf_with_streams(vec![
4926            plain(b"BT /F1 14 Tf 40 300 Td (Before) Tj ET"),
4927            damaged(),
4928            plain(b"BT /F1 14 Tf 40 100 Td (After) Tj ET"),
4929        ]));
4930        let t = text(&glyphs);
4931        assert!(t.starts_with("Before") && t.ends_with("After"), "{t:?}");
4932        assert!(t.contains("Partial"), "{t:?}");
4933    }
4934
4935    /// The containment test is docling-parse's: the whole char box (advance
4936    /// × the font's ascent / descent) inside the display box, edges
4937    /// included — a Helvetica `W` at 50 pt (47.2 wide) ending exactly on the
4938    /// right edge stays, 0.01 pt further it goes; likewise on the left.
4939    #[test]
4940    fn a_glyph_on_the_edge_stays_one_over_it_goes() {
4941        let w_at = |x: f32, y: f32| {
4942            let (_, g) = only_page(&pdf_content(
4943                "/MediaBox[0 0 300 400]",
4944                &format!("BT /F1 50 Tf {x} {y} Td (W) Tj ET\n"),
4945            ));
4946            text(&g)
4947        };
4948        assert_eq!(w_at(252.8, 200.0), "W");
4949        assert_eq!(w_at(252.81, 200.0), "");
4950        assert_eq!(w_at(0.0, 200.0), "W");
4951        assert_eq!(w_at(-0.01, 200.0), "");
4952        // Vertically the box is the font's ascent / descent: a baseline far
4953        // enough up keeps the descender on the page, one at 0 does not.
4954        assert_eq!(w_at(100.0, 20.0), "W");
4955        assert_eq!(w_at(100.0, 0.0), "");
4956        assert_eq!(w_at(100.0, 380.0), "");
4957    }
4958
4959    /// pdfium's fallbacks: no MediaBox → Letter; a CropBox is clipped to the
4960    /// MediaBox, and one that misses it entirely is ignored.
4961    #[test]
4962    fn page_box_follows_pdfium_fallbacks() {
4963        let (pb, _) = only_page(&pdf("", 10.0, 10.0));
4964        assert_eq!((pb.l, pb.b, pb.w, pb.h), (0.0, 0.0, 612.0, 792.0));
4965        let (pb, _) = only_page(&pdf(
4966            "/MediaBox[0 0 500 700]/CropBox[-100 100 600 900]",
4967            10.0,
4968            10.0,
4969        ));
4970        assert_eq!((pb.l, pb.b, pb.w, pb.h), (0.0, 100.0, 500.0, 600.0));
4971        let (pb, _) = only_page(&pdf(
4972            "/MediaBox[0 0 500 700]/CropBox[800 800 900 900]",
4973            10.0,
4974            10.0,
4975        ));
4976        assert_eq!((pb.l, pb.b, pb.w, pb.h), (0.0, 0.0, 500.0, 700.0));
4977        // Reversed corners normalize.
4978        let (pb, _) = only_page(&pdf("/MediaBox[500 700 0 0]", 10.0, 10.0));
4979        assert_eq!((pb.l, pb.b, pb.w, pb.h), (0.0, 0.0, 500.0, 700.0));
4980    }
4981}
4982
4983/// #1130: `/Resources` inherited from the page tree (ISO 32000-1 7.7.3.4) —
4984/// above all an *inline* dictionary on a `/Pages` node, which lopdf's
4985/// `get_page_resources` never returns (it collects an ancestor's only when it
4986/// is a reference). The R&OS php pdf writer files in Govdocs1 (448692.pdf)
4987/// carry their one font that way; the text layer read as empty and the wasm
4988/// `DigitalConverter` refused the file as a scan.
4989#[cfg(test)]
4990mod inherited_resources {
4991    use super::*;
4992    use lopdf::dictionary;
4993
4994    /// Root `/Pages` (holding `root_res` inline and the MediaBox) → an
4995    /// intermediate `/Pages` (holding `mid_res`, if any) → one page with only
4996    /// `/Type`, `/Parent`, `/Contents` and, optionally, its own resources.
4997    fn pdf(root_res: Object, mid_res: Option<Object>, page_res: Option<Object>) -> Vec<u8> {
4998        let mut doc = Document::with_version("1.3");
4999        let content = doc.add_object(lopdf::Stream::new(
5000            Dictionary::new(),
5001            b"BT /F1 12 Tf 72 700 Td (Inherited resources) Tj ET".to_vec(),
5002        ));
5003        let root_id = doc.new_object_id();
5004        let mid_id = doc.new_object_id();
5005        let mut page = dictionary! {
5006            "Type" => "Page",
5007            "Parent" => Object::Reference(mid_id),
5008            "Contents" => vec![Object::Reference(content)],
5009        };
5010        if let Some(r) = page_res {
5011            page.set("Resources", r);
5012        }
5013        let page_id = doc.add_object(page);
5014        let mut mid = dictionary! {
5015            "Type" => "Pages",
5016            "Parent" => Object::Reference(root_id),
5017            "Kids" => vec![Object::Reference(page_id)],
5018            "Count" => 1,
5019        };
5020        if let Some(r) = mid_res {
5021            mid.set("Resources", r);
5022        }
5023        doc.objects.insert(mid_id, Object::Dictionary(mid));
5024        doc.objects.insert(
5025            root_id,
5026            Object::Dictionary(dictionary! {
5027                "Type" => "Pages",
5028                "Kids" => vec![Object::Reference(mid_id)],
5029                "Count" => 1,
5030                "Resources" => root_res,
5031                "MediaBox" => vec![0.into(), 0.into(), 595.into(), 842.into()],
5032            }),
5033        );
5034        let catalog = doc.add_object(dictionary! {
5035            "Type" => "Catalog",
5036            "Pages" => Object::Reference(root_id),
5037        });
5038        doc.trailer.set("Root", Object::Reference(catalog));
5039        let mut out = Vec::new();
5040        doc.save_to(&mut out).expect("save synthetic PDF");
5041        out
5042    }
5043
5044    fn fonts(base: &str) -> Object {
5045        Object::Dictionary(dictionary! {
5046            "Font" => dictionary! { "F1" => dictionary! {
5047                "Type" => "Font", "Subtype" => "Type1", "BaseFont" => base,
5048            }},
5049        })
5050    }
5051
5052    fn page_text(bytes: &[u8]) -> String {
5053        let pages = pdf_text_pages(bytes);
5054        assert_eq!(pages.len(), 1);
5055        pages[0]
5056            .cells
5057            .iter()
5058            .map(|c| c.text.as_str())
5059            .collect::<Vec<_>>()
5060            .join(" ")
5061    }
5062
5063    #[test]
5064    fn inline_resources_on_an_ancestor_pages_node_are_inherited() {
5065        let bytes = pdf(fonts("Helvetica"), None, None);
5066        assert_eq!(page_text(&bytes), "Inherited resources");
5067    }
5068
5069    /// The nearest node that sets `/Resources` wins: the page's own over the
5070    /// intermediate node's over the root's — and one that does not resolve to
5071    /// a dictionary is passed over for the next ancestor's.
5072    #[test]
5073    fn the_nearest_resources_dictionary_wins() {
5074        let doc_of = |b: &[u8]| load_document(b).expect("load");
5075        let font_of = |bytes: &[u8]| {
5076            let doc = doc_of(bytes);
5077            let pid = *doc.get_pages().values().next().unwrap();
5078            let res = page_res(&doc, pid).expect("resources");
5079            let f1 = res
5080                .get(b"Font")
5081                .ok()
5082                .and_then(|o| o.as_dict().ok())
5083                .and_then(|f| f.get(b"F1").ok())
5084                .and_then(|o| o.as_dict().ok())
5085                .and_then(|f| f.get(b"BaseFont").ok())
5086                .and_then(|o| o.as_name().ok())
5087                .map(|n| String::from_utf8_lossy(n).into_owned());
5088            f1.unwrap_or_default()
5089        };
5090        assert_eq!(font_of(&pdf(fonts("Root"), None, None)), "Root");
5091        assert_eq!(
5092            font_of(&pdf(fonts("Root"), Some(fonts("Mid")), None)),
5093            "Mid"
5094        );
5095        assert_eq!(
5096            font_of(&pdf(fonts("Root"), Some(fonts("Mid")), Some(fonts("Page")))),
5097            "Page"
5098        );
5099        assert_eq!(
5100            font_of(&pdf(fonts("Root"), Some(Object::Null), None)),
5101            "Root"
5102        );
5103    }
5104}
5105
5106#[cfg(test)]
5107mod xref_repair {
5108    /// Build a tiny one-page PDF whose cross-reference entries are either the
5109    /// spec's 20 bytes (`two_byte_eol`) or the 19-byte form some generators
5110    /// emit — everything else about the two files is identical.
5111    fn pdf_with_xref(two_byte_eol: bool) -> Vec<u8> {
5112        let content = b"BT /F1 12 Tf 72 700 Td (Invoice 922769430725) Tj ET\n";
5113        let stream = format!("<</Length {}>>stream\n", content.len()).into_bytes();
5114        let objs: Vec<Vec<u8>> = vec![
5115            b"<</Type/Catalog/Pages 2 0 R>>".to_vec(),
5116            b"<</Type/Pages/Kids[3 0 R]/Count 1>>".to_vec(),
5117            b"<</Type/Page/Parent 2 0 R/MediaBox[0 0 595 842]/Contents 4 0 R\
5118               /Resources<</Font<</F1 5 0 R>>>>>>"
5119                .to_vec(),
5120            [stream.as_slice(), content.as_slice(), b"endstream"].concat(),
5121            b"<</Type/Font/Subtype/Type1/BaseFont/Helvetica>>".to_vec(),
5122        ];
5123
5124        let mut out = b"%PDF-1.4\n".to_vec();
5125        let mut offsets = Vec::new();
5126        for (i, body) in objs.iter().enumerate() {
5127            offsets.push(out.len());
5128            out.extend_from_slice(format!("{} 0 obj", i + 1).as_bytes());
5129            out.extend_from_slice(body);
5130            out.extend_from_slice(b"endobj\n");
5131        }
5132        let xref_at = out.len();
5133        let eol: &[u8] = if two_byte_eol { b" \n" } else { b"\n" };
5134        out.extend_from_slice(format!("xref\n0 {}\n", objs.len() + 1).as_bytes());
5135        out.extend_from_slice(b"0000000000 65535 f");
5136        out.extend_from_slice(eol);
5137        for off in &offsets {
5138            out.extend_from_slice(format!("{off:010} 00000 n").as_bytes());
5139            out.extend_from_slice(eol);
5140        }
5141        out.extend_from_slice(
5142            format!("trailer<</Size {}/Root 1 0 R>>\n", objs.len() + 1).as_bytes(),
5143        );
5144        out.extend_from_slice(format!("startxref\n{xref_at}\n%%EOF\n").as_bytes());
5145        out
5146    }
5147
5148    /// A 19-byte cross-reference entry (a bare LF where the spec wants a
5149    /// two-byte EOL) used to make lopdf reject the whole file. Lopdf 0.45
5150    /// accepts it directly, so exercise the fallback itself and prove it still
5151    /// produces the exact 20-byte entries lopdf 0.44 needed.
5152    #[test]
5153    fn short_xref_entries_are_padded_for_fallback() {
5154        let good = pdf_with_xref(true);
5155        let broken = pdf_with_xref(false);
5156        assert!(
5157            broken.len() < good.len(),
5158            "the broken file is the shorter one"
5159        );
5160        assert!(
5161            lopdf::Document::load_mem(&good).is_ok(),
5162            "the control file must load unaided"
5163        );
5164        assert!(
5165            lopdf::Document::load_mem(&broken).is_ok(),
5166            "lopdf 0.45 should accept 19-byte entries"
5167        );
5168
5169        let repaired = super::pad_short_xref_entries(&broken).expect("repair short entries");
5170        assert_eq!(repaired, good, "repair should recreate the valid xref");
5171        assert!(
5172            lopdf::Document::load_mem(&repaired).is_ok(),
5173            "the bytes produced for lopdf 0.44 must load"
5174        );
5175
5176        let cells = |b: &[u8]| -> Vec<String> {
5177            super::pdf_textlines(b)
5178                .into_iter()
5179                .flat_map(|(_, _, c)| c.into_iter().map(|c| c.text))
5180                .collect()
5181        };
5182        let from_good = cells(&good);
5183        assert!(
5184            from_good.iter().any(|t| t.contains("922769430725")),
5185            "control text: {from_good:?}"
5186        );
5187        assert_eq!(
5188            cells(&repaired),
5189            from_good,
5190            "repair must match the good parse"
5191        );
5192    }
5193
5194    /// The same generator overstates `/Length`. Lopdf 0.45 recovers at
5195    /// `endstream`, so exercise our fallback directly and prove it still writes
5196    /// the exact length lopdf 0.44 needed without moving any bytes.
5197    #[test]
5198    fn overstated_stream_length_is_fixed_for_fallback() {
5199        let good = pdf_with_xref(true);
5200        // Inflate the content stream's /Length by one, exactly as the invoice
5201        // that prompted this does.
5202        let broken = {
5203            let at = good
5204                .windows(8)
5205                .position(|w| w == b"/Length ")
5206                .expect("a /Length")
5207                + 8;
5208            let digits = good[at..].iter().take_while(|c| c.is_ascii_digit()).count();
5209            let n: usize = std::str::from_utf8(&good[at..at + digits])
5210                .unwrap()
5211                .parse()
5212                .unwrap();
5213            let inflated = (n + 1).to_string();
5214            assert_eq!(inflated.len(), digits, "keep the digit count");
5215            let mut b = good.clone();
5216            b[at..at + digits].copy_from_slice(inflated.as_bytes());
5217            b
5218        };
5219        assert_eq!(broken.len(), good.len(), "the defect must not move bytes");
5220        // Lopdf 0.45 keeps the stream despite the overstated length.
5221        let raw = lopdf::Document::load_mem(&broken).expect("still loads");
5222        assert!(
5223            raw.get_pages()
5224                .into_values()
5225                .any(|p| !raw.get_page_content(p).is_empty()),
5226            "lopdf 0.45 should recover content at endstream"
5227        );
5228
5229        let repaired = super::fix_stream_lengths(&broken);
5230        assert_eq!(repaired.len(), broken.len(), "repair must preserve offsets");
5231        assert_eq!(repaired, good, "repair should restore the true length");
5232        let repaired_doc = lopdf::Document::load_mem(&repaired).expect("repaired PDF loads");
5233        assert!(
5234            repaired_doc
5235                .get_pages()
5236                .into_values()
5237                .any(|p| !repaired_doc.get_page_content(p).is_empty()),
5238            "the bytes produced for lopdf 0.44 must retain page content"
5239        );
5240
5241        // Ours recovers the same text the well-formed file gives.
5242        let text = |b: &[u8]| -> Vec<String> {
5243            super::pdf_textlines(b)
5244                .into_iter()
5245                .flat_map(|(_, _, c)| c.into_iter().map(|c| c.text))
5246                .collect()
5247        };
5248        let expected = text(&good);
5249        assert!(!expected.is_empty(), "control must produce text");
5250        assert_eq!(text(&repaired), expected);
5251    }
5252
5253    /// The repair only fires where padding cannot move an object: it declines a
5254    /// file whose xref precedes an object (an incremental update), rather than
5255    /// shifting every offset the table records.
5256    #[test]
5257    fn repair_declines_when_padding_would_move_objects() {
5258        let mut incremental = pdf_with_xref(false);
5259        incremental.extend_from_slice(b"6 0 obj<</Type/Whatever>>endobj\n");
5260        let declined = super::pad_short_xref_entries(&incremental).unwrap_err();
5261        assert!(
5262            declined.contains("object follows the xref"),
5263            "reason: {declined}"
5264        );
5265    }
5266}
5267
5268/// #187: standard-14 fonts referenced without an embedded program (and thus
5269/// usually without `/Widths` or a `/FontDescriptor`) must decode with the
5270/// built-in Adobe Core 14 metrics instead of collapsing every cell to zero
5271/// width — the failure mode where a valid text layer was silently dropped
5272/// while pdfium read the same file fine.
5273#[cfg(test)]
5274mod base14_fonts {
5275    /// A one-page PDF whose single `Tj` uses `fontdict` (no embedded program).
5276    fn pdf_with_font(fontdict: &[u8], text: &[u8]) -> Vec<u8> {
5277        let content = [b"BT /F1 12 Tf 72 700 Td (".as_slice(), text, b") Tj ET\n"].concat();
5278        pdf_with_content(fontdict, &content)
5279    }
5280
5281    /// A one-page A4 PDF drawing `content` with `fontdict` as `/F1`.
5282    pub(super) fn pdf_with_content(fontdict: &[u8], content: &[u8]) -> Vec<u8> {
5283        pdf_with_fonts(&[fontdict], content)
5284    }
5285
5286    /// A one-page A4 PDF drawing `content` with `fontdicts[i]` bound as
5287    /// `/F{i+1}` (objects 5, 6, …).
5288    fn pdf_with_fonts(fontdicts: &[&[u8]], content: &[u8]) -> Vec<u8> {
5289        let stream = format!("<</Length {}>>stream\n", content.len()).into_bytes();
5290        let font_res: String = fontdicts
5291            .iter()
5292            .enumerate()
5293            .map(|(i, _)| format!("/F{} {} 0 R", i + 1, i + 5))
5294            .collect();
5295        let mut objs: Vec<Vec<u8>> = vec![
5296            b"<</Type/Catalog/Pages 2 0 R>>".to_vec(),
5297            b"<</Type/Pages/Kids[3 0 R]/Count 1>>".to_vec(),
5298            format!(
5299                "<</Type/Page/Parent 2 0 R/MediaBox[0 0 595 842]/Contents 4 0 R\
5300                 /Resources<</Font<<{font_res}>>>>>>"
5301            )
5302            .into_bytes(),
5303            [stream.as_slice(), content, b"endstream"].concat(),
5304        ];
5305        objs.extend(fontdicts.iter().map(|d| d.to_vec()));
5306        let mut out = b"%PDF-1.4\n".to_vec();
5307        let mut offsets = Vec::new();
5308        for (i, body) in objs.iter().enumerate() {
5309            offsets.push(out.len());
5310            out.extend_from_slice(format!("{} 0 obj", i + 1).as_bytes());
5311            out.extend_from_slice(body);
5312            out.extend_from_slice(b"endobj\n");
5313        }
5314        let xref_at = out.len();
5315        out.extend_from_slice(format!("xref\n0 {}\n", objs.len() + 1).as_bytes());
5316        out.extend_from_slice(b"0000000000 65535 f \n");
5317        for off in &offsets {
5318            out.extend_from_slice(format!("{off:010} 00000 n \n").as_bytes());
5319        }
5320        out.extend_from_slice(
5321            format!("trailer<</Size {}/Root 1 0 R>>\n", objs.len() + 1).as_bytes(),
5322        );
5323        out.extend_from_slice(format!("startxref\n{xref_at}\n%%EOF\n").as_bytes());
5324        out
5325    }
5326
5327    /// The parsed cells of the only page.
5328    pub(super) fn cells(pdf: &[u8]) -> Vec<crate::pdfium_backend::TextCell> {
5329        super::pdf_textlines(pdf)
5330            .into_iter()
5331            .flat_map(|(_, _, c)| c)
5332            .collect()
5333    }
5334
5335    /// Text drawn with a rotated text matrix reads as one line in its own
5336    /// reading order, boxed by the run's axis-aligned extent (#528). The
5337    /// landscape case is `0 s -s 0 tx ty Tm` on a `/Rotate 90` page; every
5338    /// such run used to collapse to zero width and vanish (90°/270°/tilted)
5339    /// or read backwards (180°). Expected boxes are docling-parse 7.22's line
5340    /// cells for the same runs (y-up, PDF points).
5341    #[test]
5342    fn rotated_text_matrix_reads_in_order() {
5343        const HELV: &[u8] = b"<</Type/Font/Subtype/Type1/BaseFont/Helvetica>>";
5344        const TEXT: &str = "Upright text on a rotated page.";
5345        for (tm, [l, b, r, t]) in [
5346            ("0 14 -14 0 200 100", [189.9, 100.0, 202.9, 289.1]), // 90°
5347            ("-14 0 0 -14 350 300", [160.9, 289.9, 350.0, 302.9]), // 180°
5348            ("0 -14 14 0 200 500", [197.1, 310.9, 210.1, 500.0]), // 270°
5349            (
5350                "9.8995 9.8995 -9.8995 9.8995 100 100",
5351                [92.9, 98.0, 235.8, 240.8],
5352            ), // 45°
5353        ] {
5354            let content = format!("BT /F1 1 Tf {tm} Tm ({TEXT}) Tj ET\n");
5355            let pdf = pdf_with_content(HELV, content.as_bytes());
5356            let cs = cells(&pdf);
5357            assert_eq!(cs.len(), 1, "{tm}: {cs:?}");
5358            let c = &cs[0];
5359            assert_eq!(c.text, TEXT, "{tm}");
5360            // `cells` is top-left-origin on the 842 pt page. The descriptor-
5361            // less base-14 face gets the parser's 1-em box where docling-parse
5362            // reads Helvetica's AFM (718/−207) — the same ≤ 0.6 pt
5363            // across-the-baseline offset upright text has — so allow 1 pt.
5364            let got = [c.l, 842.0 - c.b, c.r, 842.0 - c.t];
5365            for (g, w) in got.iter().zip([l, b, r, t]) {
5366                assert!(
5367                    (g - w).abs() < 1.0,
5368                    "{tm}: box {got:?} vs docling-parse {:?}",
5369                    [l, b, r, t]
5370                );
5371            }
5372            let words: Vec<String> = super::pdf_words(&pdf)
5373                .into_iter()
5374                .flat_map(|(_, _, c)| c)
5375                .map(|c| c.text)
5376                .collect();
5377            assert_eq!(words, TEXT.split(' ').collect::<Vec<_>>(), "{tm}");
5378        }
5379    }
5380
5381    /// A rotated run past the page edge (a cover's spine title) is dropped
5382    /// by the on-page test (#529) — measured on the quad's extent, not the
5383    /// zero-width box rotated glyphs used to get — instead of clamping onto
5384    /// the edge as a zero-width cell. One inside the page is kept.
5385    #[test]
5386    fn rotated_text_off_the_page_is_dropped() {
5387        const HELV: &[u8] = b"<</Type/Font/Subtype/Type1/BaseFont/Helvetica>>";
5388        let off = pdf_with_content(
5389            HELV,
5390            b"BT /F1 1 Tf 0 14 -14 0 -4 200 Tm (Spine title) Tj ET\n",
5391        );
5392        assert!(cells(&off).is_empty(), "{:?}", cells(&off));
5393        let on = pdf_with_content(
5394            HELV,
5395            b"BT /F1 1 Tf 0 14 -14 0 30 200 Tm (Margin note) Tj ET\n",
5396        );
5397        assert_eq!(cells(&on).len(), 1);
5398    }
5399
5400    /// Upright text keeps the plain loose rectangle — no quad, and the
5401    /// sanitizer path is the one every pinned PDF baseline was made with.
5402    #[test]
5403    fn upright_glyphs_carry_no_quad() {
5404        let only_page = |pdf: &[u8]| {
5405            let doc = super::load_document(pdf).expect("loads");
5406            let pid = *doc.get_pages().values().next().expect("one page");
5407            super::page_glyphs(&doc, pid)
5408        };
5409        let pdf = pdf_with_font(b"<</Type/Font/Subtype/Type1/BaseFont/Helvetica>>", b"Plain");
5410        let glyphs = only_page(&pdf);
5411        assert!(!glyphs.is_empty());
5412        assert!(glyphs.iter().all(|g| g.quad.is_none() && g.lr > g.ll));
5413        // A 90° glyph's style height is its font size, not its advance.
5414        let pdf = pdf_with_content(
5415            b"<</Type/Font/Subtype/Type1/BaseFont/Helvetica>>",
5416            b"BT /F1 1 Tf 0 14 -14 0 200 100 Tm (W) Tj ET\n",
5417        );
5418        let glyphs = only_page(&pdf);
5419        let g = &glyphs[0];
5420        assert!(g.quad.is_some());
5421        // 14 pt × the face's 1-em box (no descriptor: ascent − descent = 1).
5422        assert!((g.height() - 14.0).abs() < 0.05, "{}", g.height());
5423    }
5424
5425    /// #609: ReportLab's chart axis sets each tick label with the *same* `Tm`
5426    /// inside its own `q … cm … Q`, so only the CTM stacks `3`…`8` one under
5427    /// another at one x. Each tick is its own line cell with its own box (as
5428    /// docling-parse reads it), not one `345678` cell boxed like the first.
5429    #[test]
5430    fn ticks_stacked_by_cm_are_separate_line_cells() {
5431        let mut content = String::new();
5432        for (k, tick) in "345678".chars().enumerate() {
5433            let y = 300.0 + 25.92 * k as f64;
5434            content.push_str(&format!(
5435                "q 1 0 0 1 125 {y} cm BT /F1 10 Tf 1 0 0 1 -5 -4 Tm ({tick}) Tj ET Q\n"
5436            ));
5437        }
5438        let pdf = pdf_with_content(
5439            b"<</Type/Font/Subtype/Type1/BaseFont/Times-Roman>>",
5440            content.as_bytes(),
5441        );
5442        let cells = cells(&pdf);
5443        let texts: Vec<&str> = cells.iter().map(|c| c.text.as_str()).collect();
5444        assert_eq!(texts, ["3", "4", "5", "6", "7", "8"]);
5445        for (k, c) in cells.iter().enumerate() {
5446            // Top-left y of a tick whose baseline is 4 pt under its cm origin.
5447            let base = 842.0 - (300.0 + 25.92 * k as f32 - 4.0);
5448            assert!((c.l - 120.0).abs() < 0.1, "{k}: l {}", c.l);
5449            assert!(
5450                c.t < base && base - c.t < 10.0,
5451                "{k}: t {} base {base}",
5452                c.t
5453            );
5454        }
5455    }
5456
5457    /// #609: the path walk finds drawn checkbox squares — ReportLab's four
5458    /// `m … l S` edges under a `cm`, and a stroked `re` with a tick inside
5459    /// (checked) — in the text cells' top-left frame, and a stroked box
5460    /// filled white; a filled bar, a big frame and a colour-filled legend
5461    /// swatch are not checkboxes.
5462    #[test]
5463    fn drawn_checkbox_squares_are_found() {
5464        let content = b"q 1 0 0 1 119.52 449.04 cm \
5465            n 0 12.96 m 12.96 12.96 l S n 0 0 m 12.96 0 l S \
5466            n 0 0 m 0 12.96 l S n 12.96 0 m 12.96 12.96 l S Q\n\
5467            200 400 10 10 re S 202 405 m 204.5 402 l 208.5 408.5 l S\n\
5468            300 400 12 12 re f 50 50 100 100 re S\n\
5469            q 0.2 0.4 0.8 rg 400 400 12 12 re B Q q 1 g 500 400 12 12 re B Q\n";
5470        let pdf = pdf_with_content(b"<</Type/Font/Subtype/Type1/BaseFont/Helvetica>>", content);
5471        let mut parser = super::PageTextParser::open(&pdf).expect("parses");
5472        let mut boxes = parser.cells(0).checkboxes;
5473        boxes.sort_by(|a, b| a.l.total_cmp(&b.l));
5474        let got: Vec<([i32; 4], bool)> = boxes
5475            .iter()
5476            .map(|c| {
5477                let r = |v: f32| (v * 100.0).round() as i32;
5478                ([r(c.l), r(c.t), r(c.r), r(c.b)], c.checked)
5479            })
5480            .collect();
5481        // Page height 842: y-up 449.04..462.0 → top-left 380.0..392.96.
5482        assert_eq!(
5483            got,
5484            [
5485                ([11952, 38000, 13248, 39296], false),
5486                ([20000, 43200, 21000, 44200], true),
5487                ([50000, 43000, 51200, 44200], false),
5488            ]
5489        );
5490    }
5491
5492    /// Every standard-14 alias/style decodes with real (positive-width) boxes.
5493    #[test]
5494    fn standard14_faces_get_builtin_widths() {
5495        for fontdict in [
5496            // ReportLab's default: base-14 Helvetica, WinAnsi, nothing else.
5497            b"<</Type/Font/Subtype/Type1/BaseFont/Helvetica/Encoding/WinAnsiEncoding>>".as_slice(),
5498            // No /Encoding at all (StandardEncoding-ish default).
5499            b"<</Type/Font/Subtype/Type1/BaseFont/Times-BoldItalic>>",
5500            // Substitution aliases + a subset prefix.
5501            b"<</Type/Font/Subtype/TrueType/BaseFont/Arial,Bold>>",
5502            b"<</Type/Font/Subtype/Type1/BaseFont/ABCDEF+Courier-Oblique>>",
5503        ] {
5504            let pdf = pdf_with_font(fontdict, b"Words have width now");
5505            let cs = cells(&pdf);
5506            let text: String = cs
5507                .iter()
5508                .map(|c| c.text.as_str())
5509                .collect::<Vec<_>>()
5510                .join(" ");
5511            assert!(
5512                text.contains("Words have width now"),
5513                "{}: text lost: {text:?}",
5514                String::from_utf8_lossy(fontdict)
5515            );
5516            assert!(
5517                cs.iter().all(|c| c.r > c.l),
5518                "{}: zero-width cells: {cs:?}",
5519                String::from_utf8_lossy(fontdict)
5520            );
5521        }
5522    }
5523
5524    /// MacRomanEncoding without a ToUnicode CMap (#744) — Word for Mac's
5525    /// Quartz output: the whole high range decodes, Danish æ ø å, é, ü, ß
5526    /// and § included, through the plain encoding name and as the base of a
5527    /// `/Differences` dictionary alike.
5528    #[test]
5529    fn macroman_fonts_keep_accented_letters() {
5530        let sentence = b"Bl\x8cb\xbergr\xbfd p\x8c \xbfen \xd0 caf\x8e M\x9fller, Stra\xa7e \xa4 3";
5531        for (fontdict, want) in [
5532            (
5533                b"<</Type/Font/Subtype/Type1/BaseFont/Helvetica/Encoding/MacRomanEncoding>>"
5534                    .as_slice(),
5535                "Blåbærgrød på øen – café Müller, Straße § 3",
5536            ),
5537            (
5538                b"<</Type/Font/Subtype/TrueType/BaseFont/ABCDEF+Arial\
5539                   /Encoding<</Type/Encoding/BaseEncoding/MacRomanEncoding/Differences[51/four]>>>>",
5540                "Blåbærgrød på øen – café Müller, Straße § 4",
5541            ),
5542        ] {
5543            let text: String = cells(&pdf_with_font(fontdict, sentence))
5544                .iter()
5545                .map(|c| c.text.as_str())
5546                .collect::<Vec<_>>()
5547                .join(" ");
5548            assert_eq!(text, want, "{}", String::from_utf8_lossy(fontdict));
5549        }
5550
5551        // The table itself: all of 0x80–0xFF but the Apple logo, ¤ at 0xDB.
5552        let table = super::macroman_table();
5553        assert_eq!(
5554            (0x80u8..=0xFF).filter(|b| table.contains_key(b)).count(),
5555            127
5556        );
5557        assert_eq!(table.get(&0xF0), None);
5558        assert_eq!(table[&0xDB], '¤');
5559        assert_eq!(
5560            [0x80, 0x8C, 0xAE, 0xAF, 0xBE, 0xBF, 0xFF].map(|b| table[&b]),
5561            ['Ä', 'å', 'Æ', 'Ø', 'æ', 'ø', 'ˇ']
5562        );
5563    }
5564
5565    /// WinAnsiEncoding's unused codes above octal 40 are bullets (PDF
5566    /// 32000-1 Annex D.2) — ReportLab's default list bullet is `\177` in a
5567    /// non-embedded WinAnsi Helvetica and read U+FFFD (#1102). A font
5568    /// without an `/Encoding` keeps them undefined.
5569    #[test]
5570    fn winansi_unused_codes_are_bullets() {
5571        let read = |fontdict: &[u8], text: &[u8]| -> String {
5572            cells(&pdf_with_font(fontdict, text))
5573                .iter()
5574                .map(|c| c.text.as_str())
5575                .collect::<Vec<_>>()
5576                .join(" ")
5577        };
5578        let winansi = b"<</Type/Font/Subtype/Type1/BaseFont/Helvetica/Encoding/WinAnsiEncoding>>";
5579        assert_eq!(read(winansi, b"\\177 Cut costs"), "\u{2022} Cut costs");
5580        for code in [0x7Fu8, 0x81, 0x8D, 0x8F, 0x90, 0x9D] {
5581            assert_eq!(
5582                read(winansi, &[b'x', code, b'x']),
5583                "x\u{2022}x",
5584                "{code:#x}"
5585            );
5586        }
5587        let dict = b"<</Type/Font/Subtype/TrueType/BaseFont/Arial\
5588                     /Encoding<</Type/Encoding/BaseEncoding/WinAnsiEncoding>>>>";
5589        assert_eq!(read(dict, b"\\177 Cut costs"), "\u{2022} Cut costs");
5590        let bare = b"<</Type/Font/Subtype/Type1/BaseFont/Helvetica>>";
5591        assert!(!read(bare, b"x\\177x").contains('\u{2022}'));
5592    }
5593
5594    /// Unmapped glyphs read U+FFFD (#1003, docling#5070): a ToUnicode NUL —
5595    /// docling's `test_threaded_page_backend_replaces_nul_with_replacement_char`
5596    /// case, `mg.mL \x00 1` — and a bare glyph-index `/Differences` name,
5597    /// while an unknown code-like name keeps its text without the slash
5598    /// (docling-parse 7.24's `SM590000`).
5599    #[test]
5600    fn unmapped_glyphs_read_as_the_replacement_char() {
5601        let cmap = b"/CIDInit /ProcSet findresource begin 12 dict begin begincmap\n\
5602            1 begincodespacerange <00> <FF> endcodespacerange\n\
5603            1 beginbfchar <7e> <0000> endbfchar\n\
5604            endcmap CMapName currentdict /CMap defineresource pop end end";
5605        let stream = [
5606            format!("<</Length {}>>stream\n", cmap.len()).as_bytes(),
5607            cmap.as_slice(),
5608            b"\nendstream",
5609        ]
5610        .concat();
5611        let pdf = pdf_with_fonts(
5612            &[
5613                b"<</Type/Font/Subtype/Type1/BaseFont/Helvetica/ToUnicode 6 0 R\
5614                   /Encoding<</Type/Encoding/Differences[1/g115 2/SM590000]>>>>",
5615                &stream,
5616            ],
5617            b"BT /F1 12 Tf 72 700 Td (mg.mL ~ 1 \x01 x \x02 y) Tj ET\n",
5618        );
5619        let text: String = cells(&pdf)
5620            .iter()
5621            .map(|c| c.text.as_str())
5622            .collect::<Vec<_>>()
5623            .join(" ");
5624        assert_eq!(text, "mg.mL \u{FFFD} 1 \u{FFFD} x SM590000 y");
5625    }
5626
5627    /// redp5110's subset font names every glyph by index (`/g115/g3 /g40…`):
5628    /// the painted ones read U+FFFD, the blank `/g3` program is a space, so
5629    /// the line keeps its words (docling-parse 7.24's line cell).
5630    #[cfg(feature = "render")]
5631    #[test]
5632    fn a_blank_glyph_program_is_a_space() {
5633        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
5634            .join("../../tests/data/pdf/sources/redp5110_sampled.pdf");
5635        let Ok(bytes) = std::fs::read(path) else {
5636            return;
5637        };
5638        let lines: Vec<String> = super::pdf_textlines(&bytes)
5639            .into_iter()
5640            .flat_map(|(_, _, c)| c)
5641            .map(|c| c.text)
5642            .collect();
5643        let want = "\u{FFFD} \u{FFFD}\u{FFFD}\u{FFFD}\u{FFFD}\u{FFFD}\u{FFFD}\u{FFFD} \
5644                    \u{FFFD}\u{FFFD}\u{FFFD} ";
5645        assert!(
5646            lines.iter().any(|l| l.starts_with(want)),
5647            "no `{want}` line in {:?}",
5648            lines
5649                .iter()
5650                .filter(|l| l.contains('\u{FFFD}'))
5651                .collect::<Vec<_>>()
5652        );
5653    }
5654
5655    /// 2305.03393's figure-caption font (`SFRM0900`) declares `/Ascent 0
5656    /// /Descent 0`, which docling-parse 7.24 rejects: its glyphs are boxed by
5657    /// their outline, so the underscores of `"PMC2807444_006_00.png"` — ink
5658    /// under the baseline — are line cells of their own, as docling-parse's
5659    /// are (same boxes to 0.01 pt), not part of the file name.
5660    #[cfg(feature = "render")]
5661    #[test]
5662    fn an_invalid_metric_font_is_boxed_by_its_ink() {
5663        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
5664            .join("../../tests/data/pdf/sources/2305.03393v1.pdf");
5665        let Ok(bytes) = std::fs::read(path) else {
5666            return;
5667        };
5668        let pages = super::pdf_textlines(&bytes);
5669        let line = |text: &str| {
5670            pages[9]
5671                .2
5672                .iter()
5673                .find(|c| c.text == text)
5674                .unwrap_or_else(|| panic!("no `{text}` line cell"))
5675                .clone()
5676        };
5677        let name = line("\"PMC2807444");
5678        let under: Vec<_> = pages[9].2.iter().filter(|c| c.text == "_").collect();
5679        assert_eq!(under.len(), 2, "two `_` cells");
5680        for u in under {
5681            assert!(
5682                u.t > name.b,
5683                "`_` under the digits' ink: {:?} vs {:?}",
5684                u,
5685                name
5686            );
5687            assert!(
5688                (u.b - u.t - 0.403).abs() < 0.01,
5689                "an outline-tight box: {u:?}"
5690            );
5691        }
5692    }
5693
5694    /// docling-parse's descriptor checks (`init_ascent_and_descent`): metrics
5695    /// that do not straddle the baseline give way to a valid `/FontBBox` and
5696    /// mark the font for outline boxes; an implausible one is ignored for its
5697    /// `/FontBBox` edge; plain metrics are kept.
5698    #[test]
5699    fn descriptor_metrics_follow_docling_parse() {
5700        use lopdf::{dictionary, Object};
5701        let font = |asc: Option<i64>, desc: Option<i64>, bbox: bool| {
5702            let mut fd = dictionary! { "Type" => "FontDescriptor", "FontName" => "X" };
5703            if let Some(a) = asc {
5704                fd.set("Ascent", a);
5705            }
5706            if let Some(d) = desc {
5707                fd.set("Descent", d);
5708            }
5709            if bbox {
5710                let b: Vec<Object> = [-196, -322, 1502, 937].map(Object::from).to_vec();
5711                fd.set("FontBBox", b);
5712            }
5713            let f = dictionary! {
5714                "Type" => "Font", "Subtype" => "Type1", "BaseFont" => "X",
5715                "FontDescriptor" => fd,
5716            };
5717            super::font_ascent_descent(&lopdf::Document::with_version("1.5"), &f, false)
5718        };
5719        assert_eq!(font(Some(0), Some(0), true), (937.0, -322.0, true));
5720        assert_eq!(font(Some(700), Some(200), true), (937.0, -322.0, true));
5721        assert_eq!(font(Some(90000), Some(-250), true), (937.0, -250.0, true));
5722        assert_eq!(font(Some(718), Some(-207), true), (718.0, -207.0, false));
5723        assert_eq!(font(Some(0), Some(0), false), (750.0, -250.0, false));
5724        assert_eq!(font(None, None, true), (750.0, -250.0, false));
5725    }
5726
5727    /// docling-parse boxes a glyph between the descent and the ascent scaled
5728    /// by `CapHeight / Ascent` (`pdf_state<TEXT>`'s `ratio`, taken in
5729    /// 0.05..=1): the box tops out at the capitals. For Arial that is a
5730    /// fifth off; for Cambria's regular face, whose descriptor claims 3117 /
5731    /// -2464, it is the difference between a 5.6 em box around every line and
5732    /// docling-parse's 1.19 em — its line cells on the page of #1129 are
5733    /// 11.9 pt tall at 10 pt, and so are ours. A cap height above the ascent
5734    /// or next to nothing is no ratio, and a descriptor without one leaves
5735    /// the metrics as they are.
5736    #[test]
5737    fn the_char_box_is_scaled_by_cap_height_over_ascent() {
5738        use lopdf::dictionary;
5739        let font = |asc: i64, desc: i64, cap: Option<i64>| {
5740            let mut fd = dictionary! {
5741                "Type" => "FontDescriptor", "FontName" => "X",
5742                "Ascent" => asc, "Descent" => desc,
5743            };
5744            if let Some(c) = cap {
5745                fd.set("CapHeight", c);
5746            }
5747            let f = dictionary! {
5748                "Type" => "Font", "Subtype" => "TrueType", "BaseFont" => "X",
5749                "FontDescriptor" => fd,
5750            };
5751            let (a, d, invalid) =
5752                super::font_ascent_descent(&lopdf::Document::with_version("1.5"), &f, false);
5753            assert!(!invalid);
5754            ((a * 10.0).round() / 10.0, (d * 10.0).round() / 10.0)
5755        };
5756        assert_eq!(font(905, -212, Some(716)), (716.0, -167.7));
5757        assert_eq!(font(3117, -2464, Some(667)), (667.0, -527.3));
5758        assert_eq!(font(1047, -299, Some(667)), (667.0, -190.5));
5759        assert_eq!(font(905, -212, None), (905.0, -212.0));
5760        assert_eq!(font(905, -212, Some(1200)), (905.0, -212.0));
5761        assert_eq!(font(905, -212, Some(10)), (905.0, -212.0));
5762        assert_eq!(font(905, -212, Some(0)), (905.0, -212.0));
5763    }
5764
5765    /// redp5110 p. 14 draws its navigation arrows in `SymbolMT`, whose
5766    /// `/ToUnicode` maps them into the private-use symbol charset
5767    /// (`U+F0AE`): read through Symbol's encoding they are `→`, as
5768    /// docling-parse 7.25 reads them (#1113).
5769    #[test]
5770    fn symbol_private_use_values_read_as_the_glyphs() {
5771        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
5772            .join("../../tests/data/pdf/sources/redp5110_sampled.pdf");
5773        let Ok(bytes) = std::fs::read(path) else {
5774            return;
5775        };
5776        let lines: Vec<String> = super::pdf_textlines(&bytes)
5777            .into_iter()
5778            .flat_map(|(_, _, c)| c)
5779            .map(|c| c.text)
5780            .collect();
5781        assert!(
5782            lines
5783                .iter()
5784                .any(|l| l.ends_with("click Schemas → HR_SCHEMA→")),
5785            "{:?}",
5786            lines
5787                .iter()
5788                .filter(|l| l.contains("Schemas"))
5789                .collect::<Vec<_>>()
5790        );
5791        assert!(lines.iter().all(|l| !l.contains('\u{F0AE}')));
5792    }
5793
5794    /// 2203.01017's p. 4 table marks its datasets with an embedded Type 1
5795    /// `Dingbats` — symbolic, no `/Encoding`, no `/ToUnicode` — whose
5796    /// program encodes code `3` as `/a19` and `7` as `/a23`: `✓` and `✗`
5797    /// through the builtin encoding, as docling-parse 7.25 reads them
5798    /// (#1113), where the Latin tables read the digits.
5799    #[cfg(feature = "render")]
5800    #[test]
5801    fn a_symbolic_font_reads_through_its_builtin_encoding() {
5802        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
5803            .join("../../tests/data/pdf/sources/2203.01017v2.pdf");
5804        let Ok(bytes) = std::fs::read(path) else {
5805            return;
5806        };
5807        let pages = super::pdf_textlines(&bytes);
5808        let text: Vec<&str> = pages[3].2.iter().map(|c| c.text.as_str()).collect();
5809        let page = text.join("\n");
5810        assert_eq!(page.matches('✓').count(), 11, "{text:?}");
5811        assert_eq!(page.matches('✗').count(), 1, "{text:?}");
5812        assert!(text.contains(&"✓ ✗ 145k JPEG"), "{text:?}");
5813    }
5814
5815    /// docling-parse 7.25's `glyph_name_to_utf8`.
5816    #[test]
5817    fn builtin_glyph_names_read_as_docling_parse() {
5818        let t = |n: &str| super::builtin_glyph_text(n);
5819        assert_eq!(t("a19").as_deref(), Some("✓"));
5820        assert_eq!(t("arrowright").as_deref(), Some("→"));
5821        assert_eq!(t("A").as_deref(), Some("A"));
5822        assert_eq!(t("one.oldstyle").as_deref(), Some("1"), "suffix dropped");
5823        assert_eq!(t("uni00660069").as_deref(), Some("fi"), "a uni sequence");
5824        assert_eq!(t("u1F600").as_deref(), Some("😀"));
5825        assert_eq!(t("g12"), None, "an index name");
5826        assert_eq!(t("GID00012"), None);
5827        assert_eq!(t("cid7"), None);
5828        assert_eq!(t(".notdef"), None);
5829        assert_eq!(t(""), None);
5830        assert_eq!(t("nosuchglyphname"), None);
5831    }
5832
5833    /// The page's image placements reach the cells (#999): the scan under
5834    /// the #999 fixture's one native word is the whole page.
5835    #[test]
5836    fn image_placements_are_the_pages_bitmaps() {
5837        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
5838            .join("../docling/tests/fixtures/partial_text_layer/scan_with_native_word.pdf");
5839        let bytes = std::fs::read(path).expect("fixture");
5840        let mut parser = super::PageTextParser::open(&bytes).expect("parser");
5841        let page = parser.cells(0);
5842        assert_eq!(page.bitmaps, vec![[0.0, 0.0, 612.0, 792.0]]);
5843        assert_eq!(page.words.len(), 1);
5844        assert!(page.checkboxes.is_empty());
5845    }
5846
5847    /// A `bfrange` whose destination is a surrogate pair steps its last code
5848    /// unit (#1003: equations.pdf's `H𝛂`, `<1d59> <1d5a> <d835dec2>`); a
5849    /// single-unit base keeps counting in code points.
5850    #[test]
5851    fn surrogate_pair_bfrange_maps_each_code() {
5852        let map = super::parse_tounicode(
5853            b"1 beginbfrange <1d59> <1d5a> <d835dec2> endbfrange\n\
5854              1 beginbfrange <0010> <0011> <0041> endbfrange",
5855        );
5856        assert_eq!(map.get(&0x1d59).map(String::as_str), Some("\u{1D6C2}"));
5857        assert_eq!(map.get(&0x1d5a).map(String::as_str), Some("\u{1D6C3}"));
5858        assert_eq!(map.get(&0x11).map(String::as_str), Some("B"));
5859    }
5860
5861    /// Which unknown glyph names are text and which are bare indexes
5862    /// (docling-parse's `resolve_unknown_name`; Skia's hexadecimal `g%X`
5863    /// since 7.25, #1113).
5864    #[test]
5865    fn unknown_glyph_names_follow_docling_parse() {
5866        for name in [
5867            "g115", "gid00043", "Glyph7", "cid42", "index9", "g3.alt", "g15C", "gA1", "G1F",
5868        ] {
5869            assert_eq!(super::unknown_name_text(name), None, "{name}");
5870            assert!(
5871                super::is_gid_name(name.split('.').next().unwrap().as_bytes()),
5872                "{name}"
5873            );
5874        }
5875        assert!(!super::is_gid_name(b"glyphs"), "not hexadecimal");
5876        assert!(!super::is_gid_name(b"uni0041"));
5877        assert_eq!(
5878            super::unknown_name_text("SM590000").as_deref(),
5879            Some("SM590000")
5880        );
5881        assert_eq!(
5882            super::unknown_name_text("SM590000.sc").as_deref(),
5883            Some("SM590000")
5884        );
5885    }
5886
5887    /// An explicit `/Widths` array always wins over the built-in metrics, and a
5888    /// non-standard face without `/Widths` stays as before (no invented boxes).
5889    #[test]
5890    fn explicit_widths_win_and_unknown_faces_are_untouched() {
5891        // Helvetica with explicit 100/1000-em widths: the word's box must be
5892        // ~4×100 units at 12pt = 4.8pt wide — far narrower than the ~2.7×
5893        // wider built-in Helvetica advances would make it.
5894        let explicit = pdf_with_font(
5895            b"<</Type/Font/Subtype/Type1/BaseFont/Helvetica/FirstChar 65\
5896               /Widths[100 100 100 100]/Encoding/WinAnsiEncoding>>",
5897            b"ABBA",
5898        );
5899        let builtin = pdf_with_font(
5900            b"<</Type/Font/Subtype/Type1/BaseFont/Helvetica/Encoding/WinAnsiEncoding>>",
5901            b"ABBA",
5902        );
5903        let w = |pdf: &[u8]| {
5904            let cs = cells(pdf);
5905            assert_eq!(cs.len(), 1, "one word cell: {cs:?}");
5906            cs[0].r - cs[0].l
5907        };
5908        let (we, wb) = (w(&explicit), w(&builtin));
5909        assert!(
5910            (we - 4.8).abs() < 0.1,
5911            "explicit widths must win: got {we}, want 4×100×12/1000"
5912        );
5913        assert!(
5914            wb > 2.0 * we,
5915            "built-in Helvetica is much wider: {wb} vs {we}"
5916        );
5917
5918        // An unknown face with no /Widths: still parses (text kept), but no
5919        // built-in table applies — the old zero-width behavior is preserved
5920        // rather than inventing Helvetica metrics for an arbitrary font.
5921        let unknown = pdf_with_font(
5922            b"<</Type/Font/Subtype/Type1/BaseFont/FancyCorp-Display>>",
5923            b"Mystery",
5924        );
5925        let cs = cells(&unknown);
5926        let text: String = cs.iter().map(|c| c.text.as_str()).collect();
5927        assert!(text.contains("Mystery"), "text still decodes: {cs:?}");
5928    }
5929
5930    /// #1121: a TeX math font names its glyphs at the low char codes —
5931    /// `/parenleftbig` at 0, `/parenrightbig` at 1 in Latin Modern's math
5932    /// extension font (1805.06723) — with no ToUnicode. The names are not
5933    /// Adobe Glyph List names; unresolved, the codes read U+FFFD
5934    /// (`rt�A(M)�`). They read as docling-parse reads them, and a font whose
5935    /// CMap maps the code to NUL reads its `/Differences` name.
5936    #[test]
5937    fn tex_math_glyphs_at_low_codes_decode() {
5938        let font = b"<</Type/Font/Subtype/Type1/BaseFont/ABCDEF+LMMathExtension10-Regular\
5939            /FirstChar 0/LastChar 90/Widths[458 458 0 0 0 0 0 0 0 0 0 0 0 0 0 0 597 597 \
5940            0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \
5941            0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 472]\
5942            /Encoding<</Type/Encoding/Differences[0/parenleftbig/parenrightbig \
5943            16/parenleftBig/parenrightBig 90/integraldisplay]>>>>";
5944        let text = |bytes: &[u8]| -> String {
5945            cells(&pdf_with_font(font, bytes))
5946                .iter()
5947                .map(|c| c.text.as_str())
5948                .collect()
5949        };
5950        assert_eq!(text(b"\\000\\001"), "()");
5951        assert_eq!(text(b"\\020\\021Z"), "()∫");
5952        assert!(!text(b"\\000\\001\\020\\021Z").contains('\u{FFFD}'));
5953    }
5954
5955    /// The Adobe Glyph List in full (the `glyph-list` feature): a Cyrillic
5956    /// font re-encoded with `/Differences` and no ToUnicode names its glyphs
5957    /// `afii10017`, `afii10018`, …. Unresolved, each read the Latin letter of
5958    /// the base encoding at its code — plausible text in the wrong script.
5959    #[cfg(feature = "glyph-list")]
5960    #[test]
5961    fn glyph_list_names_decode_a_reencoded_cyrillic_font() {
5962        let font = b"<</Type/Font/Subtype/Type1/BaseFont/ABCDEF+SchoolBookC\
5963            /FirstChar 65/LastChar 68/Widths[700 650 650 600]\
5964            /Encoding<</Type/Encoding/BaseEncoding/WinAnsiEncoding\
5965            /Differences[65/afii10017/afii10018/afii10019/afii10020]>>>>";
5966        let text: String = cells(&pdf_with_font(font, b"ABCD"))
5967            .iter()
5968            .map(|c| c.text.as_str())
5969            .collect();
5970        assert_eq!(text, "АБВГ");
5971    }
5972
5973    /// #1153: a simple font with no `/Widths` and no embedded program,
5974    /// outside the standard-14 names, advanced 0 per glyph and its line was
5975    /// dropped. docling-parse reads such faces by their AFM.
5976    #[test]
5977    fn widthless_fonts_outside_the_core_14_names_keep_their_text() {
5978        // #1153: no `/Widths`, no embedded program. The Monotype PostScript
5979        // names take the standard-14 metrics they substitute …
5980        let line = |base: &str, descriptor: &str| {
5981            let font = format!(
5982                "<</Type/Font/Subtype/TrueType/BaseFont/{base}/Encoding/WinAnsiEncoding{descriptor}>>"
5983            );
5984            let cs = cells(&pdf_with_font(font.as_bytes(), b"Hello World"));
5985            assert_eq!(cs.len(), 1, "{base}: {cs:?}");
5986            assert_eq!(cs[0].text, "Hello World", "{base}");
5987            cs[0].r - cs[0].l
5988        };
5989        // Helvetica's advances at 12 pt: docling-parse's ArialMT line is
5990        // 64.2 pt wide (10.0..74.2 at 10 pt scales the same way).
5991        let arial = line("ArialMT", "");
5992        assert!((arial - line("Arial", "")).abs() < 1e-3, "{arial}");
5993        for base in [
5994            "TimesNewRomanPSMT",
5995            "TimesNewRomanPS-BoldMT",
5996            "CourierNewPSMT",
5997        ] {
5998            line(base, "");
5999        }
6000        // … any other face a descriptor's `/AvgWidth`, else 500 units.
6001        let georgia = line("Georgia", "");
6002        assert!((georgia - 11.0 * 6.0).abs() < 0.5, "{georgia}");
6003        let avg = line(
6004            "Tahoma",
6005            "/FontDescriptor<</Type/FontDescriptor/FontName/Tahoma/Flags 32/AvgWidth 400\
6006             /FontBBox[0 -200 1000 800]/Ascent 800/Descent -200/CapHeight 700>>",
6007        );
6008        assert!((avg - 11.0 * 4.8).abs() < 0.5, "{avg}");
6009    }
6010
6011    /// A non-embedded ZapfDingbats or Symbol that names no encoding reads
6012    /// through the face's own (docling-parse's base-font AFM; its
6013    /// `annots_01`: `l` is `●`, #1113) and advances by its AFM widths — no
6014    /// Latin letters, no zero-width cells.
6015    #[test]
6016    fn non_embedded_symbol_faces_read_through_their_encoding() {
6017        let dingbats = pdf_with_font(
6018            b"<</Type/Font/Subtype/Type1/BaseFont/ZapfDingbats/Name/F3>>",
6019            b"l",
6020        );
6021        let cs = cells(&dingbats);
6022        assert_eq!(cs.len(), 1, "{cs:?}");
6023        assert_eq!(cs[0].text, "●");
6024        assert!(
6025            (cs[0].r - cs[0].l - 791.0 * 12.0 / 1000.0).abs() < 0.1,
6026            "{cs:?}"
6027        );
6028        let symbol = pdf_with_font(b"<</Type/Font/Subtype/Type1/BaseFont/Symbol>>", b"abg");
6029        let text: String = cells(&symbol).iter().map(|c| c.text.as_str()).collect();
6030        assert_eq!(text, "αβγ");
6031        let symbol = pdf_with_font(b"<</Type/Font/Subtype/Type1/BaseFont/Symbol>>", b"a\xd7b");
6032        let text: String = cells(&symbol).iter().map(|c| c.text.as_str()).collect();
6033        assert_eq!(text, "α⋅β");
6034    }
6035
6036    /// docling-parse#370 (#1152): a Symbol face that declares a Latin base
6037    /// encoding reads a code through it only where the face has the glyph
6038    /// it names — WinAnsi's `multiply` is a Symbol glyph, its `a` and `b`
6039    /// are not, so `a×b` reads `α×β`; MacRoman `ab` reads `αβ`, and
6040    /// MacRoman's `bullet` (0xA5, multi_page's list bullet) stays `•`.
6041    /// docling-parse's `test_symbol_follows_declared_winansi_where_it_has_the_glyph`
6042    /// and `test_unit_truetype_macroman.py`'s Symbol cases.
6043    #[test]
6044    fn a_symbol_face_follows_its_declared_encoding_where_it_has_the_glyph() {
6045        let read = |enc: &str, text: &[u8]| -> String {
6046            let font = format!("<</Type/Font/Subtype/Type1/BaseFont/Symbol/Encoding/{enc}>>");
6047            let pdf = pdf_with_font(font.as_bytes(), text);
6048            cells(&pdf).iter().map(|c| c.text.as_str()).collect()
6049        };
6050        assert_eq!(read("WinAnsiEncoding", b"a\xd7b"), "α×β");
6051        assert_eq!(read("MacRomanEncoding", b"ab"), "αβ");
6052        assert_eq!(read("MacRomanEncoding", b"\xa5"), "•");
6053    }
6054
6055    /// #1152: StandardEncoding — named, as a `/BaseEncoding`, or implied by
6056    /// a nonsymbolic Type 1 with no `/Encoding` — and MacExpertEncoding have
6057    /// their own tables; both read as WinAnsi before (`x'`®¯áñ¤Ðy`). The
6058    /// cells read pdfium's `x’‘fiflÆæ⁄—y`; docling-parse's `x''fiflÆæ⁄-y` is
6059    /// the same after the ASCII folding assembly applies to both.
6060    #[test]
6061    fn standard_and_mac_expert_encodings_have_their_own_tables() {
6062        let read = |font: &[u8], text: &[u8]| -> String {
6063            cells(&pdf_with_font(font, text))
6064                .iter()
6065                .map(|c| c.text.as_str())
6066                .collect()
6067        };
6068        let codes = b"x'`\xae\xaf\xe1\xf1\xa4\xd0y";
6069        for font in [
6070            b"<</Type/Font/Subtype/Type1/BaseFont/Helvetica/Encoding/StandardEncoding>>".as_slice(),
6071            b"<</Type/Font/Subtype/Type1/BaseFont/Helvetica>>",
6072            b"<</Type/Font/Subtype/Type1/BaseFont/Times-Roman/Encoding\
6073              <</Type/Encoding/BaseEncoding/StandardEncoding/Differences[200/zero]>>>>",
6074        ] {
6075            assert_eq!(
6076                read(font, codes),
6077                "x’‘fiflÆæ⁄—y",
6078                "{}",
6079                String::from_utf8_lossy(font)
6080            );
6081        }
6082        let expert = b"<</Type/Font/Subtype/Type1/BaseFont/ArialMT/Encoding/MacExpertEncoding>>";
6083        assert_eq!(read(expert, b"WX"), "fifl");
6084        // A TrueType face without an encoding keeps the WinAnsi stand-in.
6085        let tt = b"<</Type/Font/Subtype/TrueType/BaseFont/Helvetica>>";
6086        assert_eq!(read(tt, b"x\xe1y"), "xáy");
6087    }
6088
6089    /// docling-parse 7.26's duplicate passes (docling-parse#367, #1151):
6090    /// its `test_unit_overprinted_text.py` cases with docling-parse 7.27's
6091    /// line cells. Exact copies go wherever they fall, near copies on their
6092    /// own line within `min(0.5, 0.5 × width)`, and a word or line drawn
6093    /// again after other text within `min(0.5, 0.1 × its size)`; a copy 1 pt
6094    /// off its line — `shift1pt` — is the documented exception: docling-parse
6095    /// keeps both, the shadow pass ([`drop_shadow_runs`]) drops it.
6096    #[test]
6097    fn overprinted_text_reads_once() {
6098        const H: &[u8] =
6099            b"<</Type/Font/Subtype/Type1/BaseFont/Helvetica/Encoding/WinAnsiEncoding>>";
6100        const HB: &[u8] =
6101            b"<</Type/Font/Subtype/Type1/BaseFont/Helvetica-Bold/Encoding/WinAnsiEncoding>>";
6102        const A: &str = "ALPHA BETA GAMMA";
6103        const D: &str = "DELTA EPSILON ZETA";
6104        let lines = |fonts: &[&[u8]], content: &str| -> Vec<String> {
6105            cells(&pdf_with_fonts(fonts, content.as_bytes()))
6106                .into_iter()
6107                .map(|c| c.text)
6108                .collect()
6109        };
6110        let draws = |ds: &[(f32, f32, &str)]| -> String {
6111            ds.iter()
6112                .map(|(x, y, t)| format!("BT /F1 12 Tf {x} {y} Td ({t}) Tj ET\n"))
6113                .collect()
6114        };
6115        let cases: [(&str, String, Vec<&str>); 13] = [
6116            ("line3x", draws(&[(72.0, 700.0, A); 3]), vec![A]),
6117            ("exact2", draws(&[(72.0, 700.0, A); 2]), vec![A]),
6118            (
6119                "block3x",
6120                draws(&[(72.0, 700.0, A), (72.0, 660.0, D)].repeat(3)),
6121                vec![A, D],
6122            ),
6123            (
6124                "two_positions",
6125                draws(&[(72.0, 700.0, A), (72.0, 660.0, A)]),
6126                vec![A, A],
6127            ),
6128            (
6129                "nearby2",
6130                draws(&[(72.0, 700.0, A), (72.3, 700.0, A)]),
6131                vec![A],
6132            ),
6133            (
6134                "shift1pt",
6135                draws(&[(72.0, 700.0, A), (73.0, 700.0, A)]),
6136                vec![A],
6137            ),
6138            (
6139                "bat_pat",
6140                draws(&[(72.0, 700.0, "BAT"), (72.0, 660.0, D), (72.3, 700.0, "PAT")]),
6141                vec!["BAT", D, "PAT"],
6142            ),
6143            (
6144                "shifted_after",
6145                draws(&[(72.0, 700.0, A), (72.0, 660.0, D), (72.01, 700.01, A)]),
6146                vec![A, D],
6147            ),
6148            (
6149                "block_shift001",
6150                draws(&[
6151                    (72.0, 700.0, A),
6152                    (72.0, 660.0, D),
6153                    (72.01, 700.01, A),
6154                    (72.01, 660.01, D),
6155                ]),
6156                vec![A, D],
6157            ),
6158            (
6159                "token_alpha_beta",
6160                draws(&[
6161                    (72.0, 700.0, "TOKEN ALPHA"),
6162                    (72.0, 660.0, D),
6163                    (72.01, 700.01, "TOKEN BETA"),
6164                ]),
6165                vec!["TOKEN ALPHA", D, "TOKEN BETA"],
6166            ),
6167            (
6168                "rotated",
6169                "BT /F1 12 Tf 0 1 -1 0 300 200 Tm (ALPHA BETA) Tj ET\n\
6170                 BT /F1 12 Tf 0 1 -1 0 320 200 Tm (OTHER LINE) Tj ET\n\
6171                 BT /F1 12 Tf 0 1 -1 0 300.01 200.01 Tm (ALPHA BETA) Tj ET\n"
6172                    .to_string(),
6173                vec!["ALPHA BETA", "OTHER LINE"],
6174            ),
6175            (
6176                "small_partial",
6177                "BT /F1 1 Tf 72 700 Td (WORD) Tj ET\nBT /F1 12 Tf 72 660 Td (OTHER LINE) Tj ET\n\
6178                 BT /F1 1 Tf 72.25 700.25 Td (WORD) Tj ET\n"
6179                    .to_string(),
6180                vec!["WORD", "OTHER LINE", "WORD"],
6181            ),
6182            (
6183                "fonts",
6184                "BT /F1 12 Tf 72 700 Td (.) Tj ET\nBT /F1 12 Tf 72 660 Td (OTHER LINE) Tj ET\n\
6185                 BT /F2 12 Tf 72.01 700.01 Td (.) Tj ET\n"
6186                    .to_string(),
6187                vec![".", "OTHER LINE", "."],
6188            ),
6189        ];
6190        for (name, content, want) in cases {
6191            assert_eq!(lines(&[H, HB], &content), want, "{name}");
6192        }
6193    }
6194
6195    /// docling-parse 7.26's clip boundary (docling-parse#443, #1150): its
6196    /// `test_unit_clipped_cell_text.py` cases, word and line cells as
6197    /// docling-parse 7.27 lists them. A producer fits text into a table cell
6198    /// by clipping it there; the hidden end runs under the next column and
6199    /// read on into it (`AB-1001-XYZReplacement of …`).
6200    #[test]
6201    fn a_clip_that_cuts_a_glyph_separates_words_and_lines() {
6202        const HELV: &[u8] = b"<</Type/Font/Subtype/Type1/BaseFont/Helvetica>>";
6203        let read = |content: &str| -> (Vec<String>, Vec<String>) {
6204            let pdf = pdf_with_content(HELV, content.as_bytes());
6205            let words = super::pdf_words(&pdf)
6206                .into_iter()
6207                .flat_map(|(_, _, c)| c)
6208                .map(|c| c.text)
6209                .collect();
6210            let lines = cells(&pdf).into_iter().map(|c| c.text).collect();
6211            (words, lines)
6212        };
6213        // The table of docling-parse#404, every cell's text in its own clip.
6214        let rows = [
6215            ["Code", "Description", "Unit", "Amount"],
6216            [
6217                "AB-1001-XYZ",
6218                "Replacement of the ventilation unit, roof level",
6219                "pcs",
6220                "1",
6221            ],
6222            ["AB-1002", "Gutter cleaning", "m", "120"],
6223            [
6224                "AB-1003-LONG",
6225                "Repainting of window frames and fascia boards",
6226                "m2",
6227                "85",
6228            ],
6229        ];
6230        let columns = [72.0, 122.0, 252.0, 302.0, 372.0];
6231        let (top, row_h) = (720.0, 22.0);
6232        let mut table = String::from("0.5 w\n");
6233        for i in 0..=rows.len() {
6234            let y = top - i as f64 * row_h;
6235            table += &format!("{} {y} m {} {y} l S\n", columns[0], columns[4]);
6236        }
6237        for x in columns {
6238            table += &format!("{x} {top} m {x} {} l S\n", top - rows.len() as f64 * row_h);
6239        }
6240        for (r, row) in rows.iter().enumerate() {
6241            for (c, text) in row.iter().enumerate() {
6242                let (x0, x1) = (columns[c], columns[c + 1]);
6243                let y1 = top - r as f64 * row_h;
6244                let y0 = y1 - row_h;
6245                table += &format!(
6246                    "q {x0} {y0} {} {} re W n BT /F1 9 Tf {} {} Td ({text}) Tj ET Q\n",
6247                    x1 - x0,
6248                    y1 - y0,
6249                    x0 + 3.0,
6250                    y1 - 15.0
6251                );
6252            }
6253        }
6254        let (words, lines) = read(&table);
6255        let split = |s: &str| s.split(' ').map(String::from).collect::<Vec<_>>();
6256        let want_words: Vec<String> = rows.iter().flatten().flat_map(|t| split(t)).collect();
6257        assert_eq!(words, want_words);
6258        // Row 2 overflows nothing: neither clip cuts a glyph, and its code
6259        // and description stay one line across the two clips.
6260        assert_eq!(
6261            lines,
6262            [
6263                "Code",
6264                "Description",
6265                "Unit",
6266                "Amount",
6267                "AB-1001-XYZ",
6268                "Replacement of the ventilation unit, roof level",
6269                "pcs",
6270                "1",
6271                "AB-1002 Gutter cleaning",
6272                "m",
6273                "120",
6274                "AB-1003-LONG",
6275                "Repainting of window frames and fascia boards",
6276                "m2",
6277                "85",
6278            ]
6279        );
6280
6281        // Each run in its own clip, (text, x, clip width): Helvetica 10 pt.
6282        let runs = |rs: &[(&str, f64, f64)]| -> String {
6283            rs.iter()
6284                .map(|(t, x, w)| {
6285                    format!("q {x} 697 {w} 12 re W n BT /F1 10 Tf {x} 700 Td ({t}) Tj ET Q\n")
6286                })
6287                .collect()
6288        };
6289        // Clips that cut nothing: the runs still join.
6290        let (words, lines) = read(&runs(&[
6291            ("Hel", 100.0, 15.0),
6292            ("lo", 115.0, 7.78),
6293            ("World", 125.56, 26.11),
6294        ]));
6295        assert_eq!(
6296            (words, lines),
6297            (
6298                vec!["Hello".into(), "World".into()],
6299                vec!["Hello World".into()]
6300            )
6301        );
6302        // `Hello` clipped short, its hidden `lo` under `World`'s clip.
6303        for visible in [12.0, 20.0] {
6304            let (words, lines) = read(&runs(&[("Hello", 100.0, visible), ("World", 115.0, 26.11)]));
6305            assert_eq!(words, ["Hello", "World"], "{visible}");
6306            assert_eq!(lines, ["Hello", "World"], "{visible}");
6307        }
6308        // Only the overflowing glyph clipped: the unclipped ones lie inside
6309        // its box, and the word stays whole.
6310        let (words, lines) = read(
6311            "BT /F1 10 Tf 100 700 Td (Montclai) Tj ET\n\
6312             q 100 697 38 12 re W n BT /F1 10 Tf 137.23 700 Td (r) Tj ET Q\n",
6313        );
6314        assert_eq!(
6315            (words, lines),
6316            (vec!["Montclair".into()], vec!["Montclair".into()])
6317        );
6318        // A clip around a hyphen's ink is no cell: it hides less than a
6319        // fifth of the em.
6320        let mut x = 100.0;
6321        let mut content = String::new();
6322        for (t, adv) in [
6323            ("a", 5.56),
6324            ("u", 5.56),
6325            ("f", 2.78),
6326            ("g", 5.56),
6327            ("e", 5.56),
6328            ("-", 3.33),
6329        ] {
6330            let clip = if t == "-" {
6331                format!("{} 697 2.0 12 re W n ", x + 0.6)
6332            } else {
6333                format!("{x} 697 {adv} 12 re W n ")
6334            };
6335            content += &format!("q {clip}BT /F1 10 Tf {x} 700 Td ({t}) Tj ET Q\n");
6336            x += adv;
6337        }
6338        let (words, lines) = read(&content);
6339        assert_eq!(
6340            (words, lines),
6341            (vec!["aufge-".into()], vec!["aufge-".into()])
6342        );
6343        // A glyph repainted under a sliver clip: a box that cannot hold a
6344        // glyph is no cell either.
6345        let (_, lines) = read(
6346            "BT /F1 10 Tf 100 700 Td (d) Tj ET\n\
6347             q 105.3 697 0.3 12 re W n BT /F1 10 Tf 100 700 Td (d) Tj ET Q\n\
6348             BT /F1 10 Tf 105.56 700 Td (en) Tj ET\n",
6349        );
6350        assert_eq!(lines.len(), 1, "{lines:?}");
6351        // The same token in two clips is two tokens (the duplicate pass,
6352        // #1151, compares clips).
6353        let (_, lines) = read(
6354            "q 0 0 300 792 re W n BT /F1 12 Tf 72 700 Td (TOKEN) Tj ET Q\n\
6355             BT /F1 12 Tf 72 660 Td (OTHER LINE) Tj ET\n\
6356             q 0 0 400 792 re W n BT /F1 12 Tf 72.01 700.01 Td (TOKEN) Tj ET Q\n",
6357        );
6358        assert_eq!(lines, ["TOKEN", "OTHER LINE", "TOKEN"]);
6359    }
6360
6361    /// docling-parse's `test_small_text_keeps_repeated_letters`: a line at
6362    /// 12, 2, 1, 0.8 and 0.5 pt, drawn once or twice (`1 Tr` then `0 Tr`,
6363    /// fake bold), reads its letters once each — the doubled `mm` / `tt` /
6364    /// `ee` of `Committee` included, which a fixed 0.5 pt near-copy window
6365    /// took for re-stamps in the smallest sizes (#1151). The word spaces
6366    /// at ≤ 2 pt are docling-parse#437's em-based gap, not ported; only the
6367    /// letters are compared there.
6368    #[test]
6369    fn small_text_keeps_repeated_letters() {
6370        const T: &[u8] =
6371            b"<</Type/Font/Subtype/Type1/BaseFont/Times-Roman/Encoding/WinAnsiEncoding>>";
6372        const TEXT: &str = "Committee Participant benefits illegible";
6373        for size in ["12", "2", "1", "0.8", "0.5"] {
6374            for copies in [1, 2] {
6375                let run = format!("/F1 {size} Tf 50 400 Td ({TEXT}) Tj");
6376                let mut content = format!("BT 0 Tr {run} ET\n");
6377                if copies == 2 {
6378                    content = format!("BT 1 Tr {run} ET\n{content}");
6379                }
6380                let text: String = cells(&pdf_with_content(T, content.as_bytes()))
6381                    .iter()
6382                    .map(|c| c.text.as_str())
6383                    .collect::<Vec<_>>()
6384                    .join(" ");
6385                if size == "12" {
6386                    assert_eq!(text, TEXT, "{size} pt × {copies}");
6387                } else {
6388                    let letters =
6389                        |s: &str| s.chars().filter(|c| !c.is_whitespace()).collect::<String>();
6390                    assert_eq!(
6391                        letters(&text),
6392                        letters(TEXT),
6393                        "{size} pt × {copies}: {text:?}"
6394                    );
6395                }
6396            }
6397        }
6398    }
6399
6400    /// #728: one face bound under two resource keys — `/F1` Helvetica in
6401    /// WinAnsi, `/F2` the same Helvetica re-encoded so code 0x81 is the `fi`
6402    /// glyph — with every fi-word drawn in `/F2` right after an `/F1` run.
6403    /// docling-parse names a font by `/FontDescriptor/FontName` → `/Name` →
6404    /// `/BaseFont`, never by the resource key, so both resources are the same
6405    /// font and the line reads `financial`. Keyed by resource key the `fi`
6406    /// ligature (font-neutral in `applicable_for_merge`) joined the `/F1`
6407    /// run and the font barrier then split it from `nancial`.
6408    #[test]
6409    fn same_face_under_two_resource_keys_is_one_font_for_the_sanitizer() {
6410        let f1 = b"<</Type/Font/Subtype/Type1/BaseFont/Helvetica/Encoding/WinAnsiEncoding>>";
6411        let f2 = b"<</Type/Font/Subtype/Type1/BaseFont/Helvetica/Encoding<</Type/Encoding\
6412                   /BaseEncoding/WinAnsiEncoding/Differences[129/fi]>>>>";
6413        let content = b"BT 12 TL 72 720 Td \
6414            /F1 12 Tf (The ) Tj /F2 12 Tf (\\201nancial position) Tj \
6415            /F1 12 Tf ( of the company is shown in ) Tj /F2 12 Tf (\\201gure 3) Tj \
6416            /F1 12 Tf ( with the ) Tj /F2 12 Tf (\\201rst results.) Tj \
6417            T* T* /F2 12 Tf (Same words in /F2 only: \\201nancial, \\201gure, \\201rst.) Tj ET\n";
6418        let cs = cells(&pdf_with_fonts(&[f1, f2], content));
6419        let lines: Vec<&str> = cs.iter().map(|c| c.text.as_str()).collect();
6420        assert_eq!(
6421            lines,
6422            [
6423                "The financial position of the company is shown in figure 3 with the first results.",
6424                "Same words in /F2 only: financial, figure, first.",
6425            ],
6426            "{cs:?}"
6427        );
6428    }
6429
6430    /// Under `legacy` the font barrier itself is untouched: two *different*
6431    /// faces (regular and bold Helvetica, which docling-parse names apart) set
6432    /// flush against each other stay separate line cells, as
6433    /// `enforce_same_font` demands. docling-parse 7 dropped the barrier — its
6434    /// line runs follow geometry alone — so under the default `adaptive` the
6435    /// flush pair is one line and one word.
6436    #[test]
6437    fn different_faces_keep_the_font_barrier_only_under_legacy() {
6438        let f1 = b"<</Type/Font/Subtype/Type1/BaseFont/Helvetica/Encoding/WinAnsiEncoding>>";
6439        let f2 = b"<</Type/Font/Subtype/Type1/BaseFont/Helvetica-Bold/Encoding/WinAnsiEncoding>>";
6440        let content = b"BT 72 720 Td /F2 12 Tf (Total:) Tj /F1 12 Tf (42) Tj ET\n";
6441        let pdf = pdf_with_fonts(&[f1, f2], content);
6442        let lines = |gap| {
6443            let mut p = super::PageTextParser::open(&pdf).expect("opens");
6444            p.set_word_gap(Some(gap));
6445            p.cells(0)
6446                .prose
6447                .into_iter()
6448                .map(|c| c.text)
6449                .collect::<Vec<_>>()
6450        };
6451        assert_eq!(lines(crate::dp_lines::WordGap::Legacy), ["Total:", "42"]);
6452        assert_eq!(lines(crate::dp_lines::WordGap::Adaptive), ["Total:42"]);
6453    }
6454
6455    /// #992: a space glyph whose advance the next `TJ` offset takes back —
6456    /// EUR-Lex's superscript footnote marker `( 1 )`, set with spaces the
6457    /// digit is then drawn over — is not a character of the text: the page
6458    /// shows `(1)`, pdftotext and pdfium read `(1)`, and so does the line
6459    /// cell here (docling-parse keeps the spaces, `( 1 )`). A space the next
6460    /// glyph only kerns into (−100/1000 em, well past the space's start) is
6461    /// a real gap and stays, as does one before a jump to the next line.
6462    #[test]
6463    fn a_space_the_next_glyph_is_drawn_over_is_not_a_character() {
6464        let f1 = b"<</Type/Font/Subtype/Type1/BaseFont/Helvetica/Encoding/WinAnsiEncoding>>";
6465        let lines = |content: &[u8]| {
6466            let pdf = pdf_with_content(f1, content);
6467            super::PageTextParser::open(&pdf)
6468                .expect("opens")
6469                .cells(0)
6470                .prose
6471                .into_iter()
6472                .map(|c| c.text)
6473                .collect::<Vec<_>>()
6474        };
6475        // Helvetica's space is 278/1000 em: an offset of 300 moves the pen
6476        // back past where the space began, 100 leaves two thirds of it.
6477        assert_eq!(
6478            lines(b"BT /F1 12 Tf 72 700 Td [(EG \\() ( ) 300 (1) ( ) 300 (\\) erf)] TJ ET\n"),
6479            ["EG (1) erf"]
6480        );
6481        assert_eq!(
6482            lines(b"BT /F1 12 Tf 72 700 Td [(EG \\() ( ) 100 (1) ( ) 100 (\\) erf)] TJ ET\n"),
6483            ["EG ( 1 ) erf"]
6484        );
6485        // A trailing space, then the next line starts at the left margin.
6486        assert_eq!(
6487            lines(b"BT /F1 12 Tf 72 700 Td (first line ) Tj 0 -14 Td (second) Tj ET\n"),
6488            ["first line", "second"]
6489        );
6490        // A line drawn rotated 90° (a landscape slide on a portrait page,
6491        // #528): its glyphs' loose boxes stack on one left edge, which is
6492        // not an overprint — the space stays.
6493        assert_eq!(
6494            lines(b"BT 0 1 -1 0 300 100 Tm /F1 12 Tf (Nullam mollis) Tj ET\n"),
6495            ["Nullam mollis"]
6496        );
6497    }
6498
6499    /// One line of 7.5 pt Helvetica set the way Arbortext letter-spaces a
6500    /// heading (#1139): every glyph its own string, a space glyph after it,
6501    /// and a `TJ` offset after the space — `within` between the letters of a
6502    /// word, `between` between words (thousandths of an em, positive pulls
6503    /// the next glyph back). The line cells' words, in order.
6504    fn letter_spaced(words: &[&str], within: i32, between: i32) -> Vec<String> {
6505        letter_spaced_under(crate::dp_lines::WordGap::Adaptive, words, within, between)
6506    }
6507
6508    /// [`letter_spaced`] under the word-gap rule `gap`.
6509    fn letter_spaced_under(
6510        gap: crate::dp_lines::WordGap,
6511        words: &[&str],
6512        within: i32,
6513        between: i32,
6514    ) -> Vec<String> {
6515        let f1 = b"<</Type/Font/Subtype/Type1/BaseFont/Helvetica/Encoding/WinAnsiEncoding>>";
6516        let mut tj = String::new();
6517        for (wi, word) in words.iter().enumerate() {
6518            for (ci, ch) in word.chars().enumerate() {
6519                if wi + ci > 0 {
6520                    let offset = if ci == 0 { between } else { within };
6521                    tj.push_str(&format!("( ) {offset} "));
6522                }
6523                match ch {
6524                    '(' | ')' => tj.push_str(&format!("(\\{ch}) ")),
6525                    _ => tj.push_str(&format!("({ch}) ")),
6526                }
6527            }
6528        }
6529        let content = format!("BT /F1 7.5 Tf 1 0 0 1 72 700 Tm [{tj}] TJ ET\n");
6530        let pdf = pdf_with_content(f1, content.as_bytes());
6531        let mut parser = super::PageTextParser::open(&pdf).expect("opens");
6532        parser.set_word_gap(Some(gap));
6533        parser
6534            .cells(0)
6535            .prose
6536            .iter()
6537            .flat_map(|c| c.text.split(' ').map(str::to_owned).collect::<Vec<_>>())
6538            .collect()
6539    }
6540
6541    /// #1139: Arbortext letter-spaces a heading with a space glyph after
6542    /// every letter, taking a fifth of the space back inside a word and
6543    /// adding one and a half between words (EUR-Lex 02021R2178, Annex I:
6544    /// `1.1.1. KPI bezogen auf den Umsatz (Umsatz-KPI)`). The page shows
6545    /// tracking, pdftotext reads the words, and so does the line cell —
6546    /// where every letter was a word of its own (docling-parse keeps the
6547    /// space glyphs). Helvetica's space is 278/1000 em: an offset of 50
6548    /// leaves 0.82 of it, -400 makes it 2.44.
6549    #[test]
6550    fn letters_set_apart_with_space_glyphs_are_one_word() {
6551        let heading = ["KPI", "bezogen", "auf", "den", "Umsatz", "(Umsatz-KPI)"];
6552        assert_eq!(letter_spaced(&heading, 50, -400), heading);
6553        // A justified heading: its words 45 pt apart, each a line cell of
6554        // its own. `KPI` and `auf` have no chain of three letter gaps there
6555        // for the word contraction to know tracking by — the parser says so
6556        // (`Glyph::spaced`).
6557        assert_eq!(letter_spaced(&heading, 50, -6000), heading);
6558        // One word alone on its line.
6559        assert_eq!(letter_spaced(&["INHALT"], 50, 0), ["INHALT"]);
6560        // A fixed factor keeps the words too: the gaps are settled before
6561        // any threshold is asked.
6562        assert_eq!(
6563            letter_spaced_under(crate::dp_lines::WordGap::Factor(0.2), &heading, 50, -400),
6564            heading
6565        );
6566        // docling-parse ≤ 6's contraction (`pdf_word_gap=legacy`) knows no
6567        // tracking: it cuts at every letter gap, as it does for a tracking
6568        // set without space glyphs (#921).
6569        let legacy = letter_spaced_under(crate::dp_lines::WordGap::Legacy, &heading, 50, -400);
6570        assert_eq!(legacy[..3], ["K", "P", "I"], "{legacy:?}");
6571    }
6572
6573    /// What the rule of #1139 leaves as it is drawn: a line whose letters are
6574    /// no closer than its words has no letter spacing to tell from its word
6575    /// spacing.
6576    #[test]
6577    fn single_letters_between_spaces_are_not_always_letter_spacing() {
6578        let each = |words: &[&str]| -> Vec<String> {
6579            words
6580                .iter()
6581                .flat_map(|w| w.chars().map(String::from))
6582                .collect()
6583        };
6584        let heading = ["KPI", "bezogen", "auf"];
6585        // Spaces at their own width, or stretched: single letters, as set.
6586        assert_eq!(letter_spaced(&heading, 0, -400), each(&heading));
6587        assert_eq!(letter_spaced(&heading, -100, -400), each(&heading));
6588        // Word spaces not plainly wider than the letter spacing (0.82 of a
6589        // space against a whole one): no telling which is which.
6590        assert_eq!(letter_spaced(&heading, 50, 0), each(&heading));
6591        // A tightened line: `a b c d` between two words, every space pulled
6592        // in alike — its neighbours are as close as its letters.
6593        let f1 = b"<</Type/Font/Subtype/Type1/BaseFont/Helvetica/Encoding/WinAnsiEncoding>>";
6594        let line = |content: &[u8]| -> Vec<String> {
6595            super::PageTextParser::open(&pdf_with_content(f1, content))
6596                .expect("opens")
6597                .cells(0)
6598                .prose
6599                .into_iter()
6600                .map(|c| c.text)
6601                .collect()
6602        };
6603        assert_eq!(
6604            line(
6605                b"BT /F1 10 Tf 72 700 Td \
6606                  [(von) ( ) 50 (a) ( ) 50 (b) ( ) 50 (c) ( ) 50 (d) ( ) 50 (bis)] TJ ET\n"
6607            ),
6608            ["von a b c d bis"]
6609        );
6610        // One character repeated is a row of tokens, and a row of digits is
6611        // no word either.
6612        assert_eq!(letter_spaced(&["CCCCC"], 50, 0), each(&["CCCCC"]));
6613        assert_eq!(letter_spaced(&["12345"], 50, 0), each(&["12345"]));
6614    }
6615
6616    /// A text shadow: a word processor exports a heading with a shadow
6617    /// effect as the same run drawn twice — the shadow in black, then the
6618    /// text in colour over it, shifted up and left by a fraction of a point.
6619    /// pdfium's text page reads the heading once and so does the line cell
6620    /// here (docling-parse reads `Safety instructions Safety instructions`).
6621    /// #1092: docling-parse's view of a page's shapes — a stroked straight
6622    /// rule is a shape line and a shape box, a thin filled box only a box, a
6623    /// curve or a diagonal no line, a path outside the clip nothing, and a
6624    /// fill in an unresolved Pattern space nothing at all. In the cells'
6625    /// frame: top-left, on the 595 × 842 test page.
6626    #[test]
6627    fn the_page_shapes_follow_docling_parse() {
6628        let f1 = b"<</Type/Font/Subtype/Type1/BaseFont/Helvetica/Encoding/WinAnsiEncoding>>";
6629        let shapes = |content: &[u8]| {
6630            let pdf = pdf_with_content(f1, content);
6631            super::PageTextParser::open(&pdf)
6632                .expect("opens")
6633                .cells(0)
6634                .shapes
6635        };
6636        let s = shapes(b"2 w 72 400 m 540 400 l S\n");
6637        assert_eq!(s.lines, vec![[72.0, 442.0, 540.0, 442.0]]);
6638        // The stroke's half width pads the box.
6639        assert_eq!(s.boxes, vec![[71.0, 441.0, 541.0, 443.0]]);
6640
6641        let s = shapes(b"72 300 468 1 re f\n");
6642        assert!(s.lines.is_empty(), "a fill strokes no line");
6643        assert_eq!(s.boxes, vec![[72.0, 541.0, 540.0, 542.0]]);
6644
6645        // A stroked rectangle: four edges, `h`'s closing one included.
6646        let s = shapes(b"100 100 200 50 re S\n");
6647        assert_eq!(s.lines.len(), 4);
6648
6649        let s = shapes(b"72 400 m 100 450 l 200 300 300 500 400 400 c S\n");
6650        assert!(s.lines.is_empty(), "neither a diagonal nor a curve");
6651        assert_eq!(s.boxes.len(), 1);
6652
6653        let s = shapes(b"q 0 0 300 842 re W n 72 400 m 540 400 l S 400 100 m 400 700 l S Q\n");
6654        assert_eq!(
6655            s.lines,
6656            vec![[72.0, 442.0, 300.0, 442.0]],
6657            "cut to the clip"
6658        );
6659        assert_eq!(s.boxes.len(), 1, "the vertical rule is clipped away");
6660
6661        let s = shapes(b"/Pattern cs /P0 scn 72 300 468 1 re f\n");
6662        assert!(s.lines.is_empty() && s.boxes.is_empty());
6663
6664        // Two touching boxes merge into one component.
6665        let s = shapes(b"72 300 100 1 re f 172 300 100 1 re f 400 600 10 10 re f\n");
6666        assert_eq!(
6667            s.boxes,
6668            vec![[72.0, 541.0, 272.0, 542.0], [400.0, 232.0, 410.0, 242.0]]
6669        );
6670
6671        // A table rule a word processor draws piece by piece, cell borders
6672        // and their corner squares: `90.144 + 1.44` is `91.584` in the file
6673        // and in docling-parse's doubles, not in lopdf's `f32` reals cast to
6674        // `f64`, where every such joint missed by a hair and the rule fell
6675        // into pieces: `real` reads the operands as the file wrote them. A
6676        // gap the producer left (`147.5 + 159.86` = 307.36, then 307.37)
6677        // still parts two components, as in docling-parse.
6678        let s = shapes(
6679            b"56.64 690.22 33.504 1.44 re f 90.144 690.22 1.44 1.44 re f \
6680              91.584 690.22 54.48 1.44 re f 146.06 690.22 1.44 1.44 re f \
6681              147.5 690.22 159.86 1.44 re f 307.37 690.22 1.44 1.44 re f \
6682              308.81 690.22 50.304 1.44 re f\n",
6683        );
6684        let spans: Vec<(f32, f32)> = s.boxes.iter().map(|b| (b[0], b[2])).collect();
6685        assert_eq!(spans, vec![(56.64, 307.36), (307.37, 359.114)]);
6686    }
6687
6688    /// A transparent stroke or fill is no shape (`CA` / `ca` 0).
6689    #[test]
6690    fn transparent_paths_are_no_shapes() {
6691        let rule = |closed| super::ShapeSub {
6692            start: (0.0, 0.0),
6693            cur: (100.0, 0.0),
6694            pts: vec![(0.0, 0.0), (100.0, 0.0)],
6695            lines: vec![((0.0, 0.0), (100.0, 0.0))],
6696            closed,
6697        };
6698        let gs = |stroke_alpha, fill_alpha| super::ShapeGs {
6699            stroke_alpha,
6700            fill_alpha,
6701            ..super::ShapeGs::INIT
6702        };
6703        let mut shapes = super::Shapes::default();
6704        super::record_shape(&[rule(false)], true, false, &gs(0.0, 1.0), 1.0, &mut shapes);
6705        assert_eq!(shapes, super::Shapes::default());
6706        super::record_shape(&[rule(true)], false, true, &gs(1.0, 0.0), 1.0, &mut shapes);
6707        assert_eq!(shapes, super::Shapes::default());
6708        super::record_shape(&[rule(false)], true, false, &gs(0.5, 0.0), 1.0, &mut shapes);
6709        assert_eq!(shapes.lines.len(), 1);
6710    }
6711
6712    /// Text that really repeats sits an advance apart or more and stays: a
6713    /// word set twice, a doubled letter, the same words on the next line.
6714    #[test]
6715    fn a_run_drawn_again_over_itself_is_read_once() {
6716        let f1 = b"<</Type/Font/Subtype/Type1/BaseFont/Helvetica-Bold/Encoding/WinAnsiEncoding>>";
6717        let lines = |content: &[u8]| {
6718            let pdf = pdf_with_content(f1, content);
6719            super::PageTextParser::open(&pdf)
6720                .expect("opens")
6721                .cells(0)
6722                .prose
6723                .into_iter()
6724                .map(|c| c.text)
6725                .collect::<Vec<_>>()
6726        };
6727        // The shadow, then the text 0.5 pt up and left of it, at 18 pt.
6728        assert_eq!(
6729            lines(
6730                b"BT 0 g /F1 18 Tf 1 0 0 1 72 720 Tm (Safety instructions) Tj ET\n\
6731                  BT 0.8 0 0 rg /F1 18 Tf 1 0 0 1 71.5 720.5 Tm (Safety instructions) Tj ET\n"
6732            ),
6733            ["Safety instructions"]
6734        );
6735        // 0.8 pt at 14 pt, and the line under it untouched.
6736        assert_eq!(
6737            lines(
6738                b"BT /F1 14 Tf 1 0 0 1 72 656 Tm (Maintenance) Tj ET\n\
6739                  BT /F1 14 Tf 1 0 0 1 71.2 656.8 Tm (Maintenance) Tj ET\n\
6740                  BT /F1 11 Tf 1 0 0 1 72 632 Tm (Clean the filter) Tj ET\n"
6741            ),
6742            ["Maintenance", "Clean the filter"]
6743        );
6744        // A word set twice, a doubled letter, the same words a line apart.
6745        assert_eq!(
6746            lines(b"BT /F1 12 Tf 72 700 Td (very very small) Tj ET\n"),
6747            ["very very small"]
6748        );
6749        assert_eq!(
6750            lines(b"BT /F1 12 Tf 72 700 Td (Hello, all) Tj ET\n"),
6751            ["Hello, all"]
6752        );
6753        assert_eq!(
6754            lines(b"BT /F1 12 Tf 72 700 Td (Total) Tj 0 -14 Td (Total) Tj ET\n"),
6755            ["Total", "Total"]
6756        );
6757        // Dot leaders squeezed by `Tc` to 0.05, 0.07 and 0.1 em: two dots on,
6758        // a dot sits within a shadow's shift and the dots after it repeat by
6759        // the same offset, but the next dot is nearer still.
6760        for tc in ["-2.28", "-2.08", "-1.78"] {
6761            let content = format!(
6762                "BT /F1 10 Tf 72 700 Td (Contents) Tj {tc} Tc (..........) Tj 0 Tc ( 5) Tj ET\n"
6763            );
6764            assert_eq!(
6765                lines(content.as_bytes()),
6766                ["Contents.......... 5"],
6767                "Tc {tc}"
6768            );
6769        }
6770    }
6771
6772    /// docling-parse's `test_unit_actual_text.py` (docling-parse#300): a
6773    /// marked-content span's `/ActualText` replaces the glyphs drawn in it.
6774    #[test]
6775    fn actual_text_replaces_the_glyphs_of_its_span() {
6776        let helvetica = b"<</Type/Font/Subtype/Type1/BaseFont/Helvetica/Encoding/WinAnsiEncoding>>";
6777        // A non-embedded TrueType whose only code, 0x4D (`M` in WinAnsi), is a
6778        // zero-advance caron: drawn after `s` it makes `š`.
6779        let caron = b"<</Type/Font/Subtype/TrueType/BaseFont/SynthCaron/FirstChar 77/LastChar 77\
6780            /Widths[0]/Encoding/WinAnsiEncoding/FontDescriptor<</Type/FontDescriptor\
6781            /FontName/SynthCaron/Flags 32/FontBBox[-540 -200 0 800]/ItalicAngle 0/Ascent 800\
6782            /Descent -200/CapHeight 700/StemV 80>>>>";
6783        // Code 1 is the `fi` ligature: two glyphs on one pen, one cell.
6784        let ligature = b"<</Type/Font/Subtype/Type1/BaseFont/Helvetica\
6785            /Encoding<</Type/Encoding/BaseEncoding/WinAnsiEncoding/Differences[1/fi]>>>>";
6786        let text = |content: &str| {
6787            let pdf = pdf_with_fonts(&[helvetica, caron, ligature], content.as_bytes());
6788            super::PageTextParser::open(&pdf)
6789                .expect("opens")
6790                .cells(0)
6791                .prose
6792                .into_iter()
6793                .map(|c| c.text)
6794                .collect::<String>()
6795        };
6796        // Unmarked, the caron reads as its WinAnsi letter.
6797        assert_eq!(
6798            text("BT /F1 24 Tf 40 50 Td (Ore) Tj (s) Tj /F2 24 Tf <4D> Tj /F1 24 Tf (i) Tj ET"),
6799            "OresMi"
6800        );
6801        // Two cells, one character: the accent composes onto its base letter.
6802        assert_eq!(
6803            text(
6804                "BT /F1 24 Tf 40 50 Td (Ore) Tj /Span <</ActualText <FEFF0161>>> BDC \
6805                  (s) Tj /F2 24 Tf <4D> Tj EMC /F1 24 Tf (i) Tj ET"
6806            ),
6807            "Oreši"
6808        );
6809        // As many characters as cells: one for one.
6810        assert_eq!(
6811            text("BT /F1 24 Tf 40 50 Td /Span <</ActualText (ab)>> BDC (xy) Tj EMC (z) Tj ET"),
6812            "abz"
6813        );
6814        // A cell of two glyphs takes one character.
6815        assert_eq!(
6816            text("BT /F3 24 Tf 40 50 Td <01> Tj /F1 24 Tf (a) Tj ET"),
6817            "fia"
6818        );
6819        assert_eq!(
6820            text(
6821                "BT /F3 24 Tf 40 50 Td /Span <</ActualText (XY)>> BDC <01> Tj \
6822                  /F1 24 Tf (a) Tj EMC (z) Tj ET"
6823            ),
6824            "XYz"
6825        );
6826        // An empty text declares the glyphs not text (a visual line-break
6827        // hyphen); its advance may still read as a gap.
6828        let hyphen = text(
6829            "BT /F1 24 Tf 40 50 Td (exam) Tj /Span <</ActualText <FEFF>>> BDC (-) Tj EMC \
6830             (ple) Tj ET",
6831        );
6832        assert!(!hyphen.contains('-'), "{hyphen}");
6833        assert_eq!(hyphen.replace(' ', ""), "example");
6834        // `/Alt` written into the wrong key: implausibly long, ignored.
6835        assert_eq!(
6836            text(
6837                "BT /F1 24 Tf 40 50 Td /Span <</ActualText (A long description that belongs \
6838                  in Alt not here)>> BDC (ab) Tj EMC ET"
6839            ),
6840            "ab"
6841        );
6842        // Over graphics only: nothing to replace.
6843        assert_eq!(
6844            text(
6845                "BT /F1 24 Tf 40 50 Td (x) Tj ET /Span <</ActualText (ghost)>> BDC \
6846                  10 10 50 50 re f EMC"
6847            ),
6848            "x"
6849        );
6850        // A named property list is not resolved.
6851        assert_eq!(
6852            text("BT /F1 24 Tf 40 50 Td /OC /MC0 BDC (ok) Tj EMC ET"),
6853            "ok"
6854        );
6855        // Nested spans: the outer text describes the whole run.
6856        assert_eq!(
6857            text(
6858                "BT /F1 24 Tf 40 50 Td /Span <</ActualText (AB)>> BDC (a) Tj \
6859                  /Span <</ActualText (Z)>> BDC (b) Tj EMC EMC ET"
6860            ),
6861            "AB"
6862        );
6863        // A span nested past the depth limit keeps its glyphs.
6864        let nested = |depth: usize| {
6865            text(&format!(
6866                "BT /F1 24 Tf 40 50 Td {}/Span <</ActualText (z)>> BDC (a) Tj EMC{} ET",
6867                "/X BMC ".repeat(depth),
6868                " EMC".repeat(depth)
6869            ))
6870        };
6871        assert_eq!(nested(super::MAX_ACTUAL_TEXT_DEPTH - 1), "z");
6872        assert_eq!(nested(super::MAX_ACTUAL_TEXT_DEPTH), "a");
6873    }
6874
6875    /// One for one, each character keeps its cell's box, and a cell of
6876    /// several glyphs on one pen (a ligature's) becomes its first glyph.
6877    #[test]
6878    fn actual_text_one_for_one_keeps_each_cells_box() {
6879        let glyph = |ch, x: f32, pen: f32| super::Glyph {
6880            ch,
6881            l: x,
6882            b: 0.0,
6883            r: x + 5.0,
6884            t: 10.0,
6885            ll: x,
6886            lb: -2.0,
6887            lr: x + 5.0,
6888            lt: 10.0,
6889            font: 0,
6890            quad: None,
6891            pen: Some([pen, 0.0, 10.0]),
6892            math_font: false,
6893            invisible: false,
6894            spaced: false,
6895            clip: None,
6896            exact: 0,
6897        };
6898        let mut out = vec![
6899            glyph('o', 0.0, 0.0),
6900            glyph('f', 10.0, 10.0),
6901            glyph('i', 15.0, 10.0),
6902            glyph('a', 20.0, 20.0),
6903        ];
6904        super::apply_actual_text(&mut out, 1, "XY");
6905        let got: Vec<(char, f32)> = out.iter().map(|g| (g.ch, g.l)).collect();
6906        assert_eq!(got, [('o', 0.0), ('X', 10.0), ('Y', 20.0)]);
6907    }
6908
6909    /// The identity follows docling-parse's precedence: a `/FontDescriptor/FontName`
6910    /// wins over `/BaseFont`, so two dictionaries that share a `/BaseFont` but
6911    /// describe different programs are two fonts, and two that share the
6912    /// descriptor name are one whatever their `/BaseFont` says.
6913    #[test]
6914    fn math_faces_are_named_like_docling_parse_names_them() {
6915        for name in [
6916            "ABCDEF+CMR7",
6917            "CMMI10",
6918            "MSBM10",
6919            "Cambria-Math",
6920            "Symbol",
6921            "MTExtra",
6922        ] {
6923            assert!(super::is_math_font_name(name.as_bytes()), "{name}");
6924        }
6925        for name in ["Helvetica", "ABCDEF+TimesNewRomanPSMT", "Arial-BoldMT"] {
6926            assert!(!super::is_math_font_name(name.as_bytes()), "{name}");
6927        }
6928    }
6929
6930    #[test]
6931    fn sanitizer_font_name_follows_docling_parse_precedence() {
6932        use lopdf::{dictionary, Document, Object};
6933        let mut doc = Document::with_version("1.4");
6934        let fd_a =
6935            doc.add_object(dictionary! { "Type" => "FontDescriptor", "FontName" => "AAAAAA+Face" });
6936        let fd_b =
6937            doc.add_object(dictionary! { "Type" => "FontDescriptor", "FontName" => "BBBBBB+Face" });
6938        let with = |fd: Option<lopdf::ObjectId>, base: &str| {
6939            let mut d = dictionary! { "Type" => "Font", "Subtype" => "Type1", "BaseFont" => base };
6940            if let Some(id) = fd {
6941                d.set("FontDescriptor", Object::Reference(id));
6942            }
6943            d
6944        };
6945        let name = |d: &lopdf::Dictionary| {
6946            String::from_utf8(super::sanitizer_font_name(&doc, d, false)).unwrap()
6947        };
6948        assert_eq!(name(&with(Some(fd_a), "Face")), "AAAAAA+Face");
6949        assert_eq!(name(&with(Some(fd_b), "Face")), "BBBBBB+Face");
6950        assert_eq!(name(&with(None, "ABCDEF+Face")), "ABCDEF+Face");
6951        assert_eq!(
6952            name(&dictionary! { "Type" => "Font", "Name" => "F7" }),
6953            "F7"
6954        );
6955        assert_eq!(name(&dictionary! { "Type" => "Font" }), "null");
6956    }
6957}
6958
6959#[cfg(test)]
6960mod overpainted {
6961    use crate::pdfium_backend::TextCell;
6962
6963    fn cell(text: &str, l: f32, t: f32, r: f32, b: f32) -> TextCell {
6964        TextCell {
6965            text: text.into(),
6966            l,
6967            t,
6968            r,
6969            b,
6970        }
6971    }
6972
6973    /// The reporting invoice's logo: a `"` painted inside a `==` on one band —
6974    /// artwork drawn with glyphs. Both cells go; the real text on the next
6975    /// band stays.
6976    #[test]
6977    fn stacked_logo_glyphs_are_dropped() {
6978        let mut cells = vec![
6979            cell("\"", 72.7, 21.5, 86.4, 31.5),
6980            cell("==", 59.4, 21.5, 99.6, 31.5),
6981            cell("Herr", 65.2, 151.3, 81.7, 161.3),
6982        ];
6983        super::drop_overpainted_cells(&mut cells);
6984        assert_eq!(cells.len(), 1, "cells: {cells:?}");
6985        assert_eq!(cells[0].text, "Herr");
6986    }
6987
6988    /// Adjacent words on a line touch but never contain each other — prose is
6989    /// untouched, and so is a same-text near-duplicate (double-drawn faux
6990    /// bold), which is not evidence of artwork.
6991    #[test]
6992    fn prose_and_double_draw_are_kept() {
6993        let mut cells = vec![
6994            cell("Telefon", 354.3, 133.2, 381.5, 143.2),
6995            cell("0676/2000", 387.3, 133.2, 428.7, 143.2),
6996            cell("Bold", 100.0, 50.0, 130.0, 60.0),
6997            cell("Bold", 100.3, 50.0, 130.3, 60.0),
6998        ];
6999        super::drop_overpainted_cells(&mut cells);
7000        assert_eq!(cells.len(), 4);
7001    }
7002
7003    /// #1129: a face that declares an ascent of 3117 and a descent of -2464
7004    /// (Cambria's regular, read without its cap height) puts each of its
7005    /// lines in a box 5.6 em tall that overlaps the next line by four
7006    /// fifths. A short line under a long one was "one cell inside another on
7007    /// the same band" — paint — and both went: these are the issue page's
7008    /// cells, of whose 44 lines 7 were left. Lines one pitch apart are
7009    /// lines; the stacked logo, at one height, still goes.
7010    #[test]
7011    fn lines_of_a_tall_box_font_are_not_paint() {
7012        let mut cells = vec![
7013            cell(
7014                "17. Carefully pour off the supernatant from both tubes. Invert the",
7015                72.0,
7016                77.1,
7017                514.4,
7018                132.7,
7019            ),
7020            cell(
7021                "tubes and tap them gently on the surface of a clean paper towel.",
7022                72.0,
7023                88.8,
7024                453.0,
7025                144.4,
7026            ),
7027            cell("“Evidence A” DNA*", 77.6, 412.5, 150.6, 462.7),
7028            cell("“Evidence B” DNA*", 77.6, 423.0, 150.5, 473.2),
7029            cell("enzyme mixture*", 77.6, 444.1, 143.9, 494.4),
7030            // The same face painting a mark: two glyph runs at one height.
7031            cell("\"", 72.7, 600.0, 86.4, 655.6),
7032            cell("==", 59.4, 600.0, 99.6, 655.6),
7033        ];
7034        super::drop_overpainted_cells(&mut cells);
7035        let texts: Vec<&str> = cells.iter().map(|c| c.text.as_str()).collect();
7036        assert_eq!(texts.len(), 5, "{texts:?}");
7037        assert!(
7038            !texts.contains(&"==") && !texts.contains(&"\""),
7039            "{texts:?}"
7040        );
7041    }
7042
7043    /// The same through the parser: a paragraph and its short last line in a
7044    /// font whose descriptor declares an ascent of 3117 and a descent of
7045    /// -2464 and no cap height to scale them by ([`super::font_ascent_descent`]
7046    /// — with Cambria's `/CapHeight 667` the boxes are docling-parse's
7047    /// 1.19 em and the question does not arise). Every line and every word of
7048    /// the text-layer page (the browser's and `convert_text_layer`'s) is
7049    /// there; before, the page came back empty.
7050    #[test]
7051    fn a_tall_box_font_keeps_its_lines_on_the_text_layer_page() {
7052        let widths = "500 ".repeat(91);
7053        let font = format!(
7054            "<</Type/Font/Subtype/TrueType/BaseFont/Cambria/Encoding/WinAnsiEncoding\
7055             /FirstChar 32/LastChar 122/Widths[{widths}]\
7056             /FontDescriptor<</Type/FontDescriptor/FontName/Cambria/Flags 32\
7057             /FontBBox[-1475 -2464 2868 3117]/Ascent 3117/Descent -2464\
7058             /ItalicAngle 0/StemV 80>>>>"
7059        );
7060        let content = b"BT /F1 10 Tf 72 700 Td \
7061            (Carefully pour off the supernatant from both of the tubes) Tj \
7062            0 -12 Td (and tap them gently on the surface of a clean towel) Tj \
7063            0 -12 Td (to drain them.) Tj ET\n";
7064        let pdf = super::base14_fonts::pdf_with_content(font.as_bytes(), content);
7065        let page = super::pdf_text_pages(&pdf).remove(0);
7066        assert!(
7067            page.cells.iter().all(|c| c.b - c.t > 50.0),
7068            "the boxes are the font's 5.6 em: {:?}",
7069            page.cells
7070        );
7071        let lines: Vec<&str> = page.cells.iter().map(|c| c.text.as_str()).collect();
7072        assert_eq!(
7073            lines,
7074            [
7075                "Carefully pour off the supernatant from both of the tubes",
7076                "and tap them gently on the surface of a clean towel",
7077                "to drain them.",
7078            ]
7079        );
7080        assert_eq!(page.word_cells.len(), 24, "{:?}", page.word_cells);
7081    }
7082}
7083
7084#[cfg(test)]
7085mod vestigial_layer {
7086    use crate::pdfium_backend::{PdfPage, TextCell};
7087
7088    fn page_with(texts: &[&str]) -> PdfPage {
7089        let cells = texts
7090            .iter()
7091            .enumerate()
7092            .map(|(i, t)| TextCell {
7093                text: t.to_string(),
7094                l: 10.0,
7095                t: 10.0 + 12.0 * i as f32,
7096                r: 90.0,
7097                b: 20.0 + 12.0 * i as f32,
7098            })
7099            .collect();
7100        PdfPage::from_cells(595.0, 842.0, 1.0, cells)
7101    }
7102
7103    /// The reported scanned form: three typed-in field values ("03", "05",
7104    /// "2025") over three image pages. That must read as *no usable layer*,
7105    /// so the browser routes the document to OCR instead of extracting
7106    /// thirteen characters and skipping the letter entirely.
7107    #[test]
7108    fn typed_in_form_fields_are_not_a_text_layer() {
7109        let pages = vec![
7110            page_with(&["03", "05", "2025"]),
7111            page_with(&[]),
7112            page_with(&[]),
7113        ];
7114        assert!(super::text_layer_is_vestigial(&pages));
7115        assert!(super::text_layer_is_vestigial(&[page_with(&[])]));
7116    }
7117
7118    /// A short but genuine digital document — one page, a few real lines —
7119    /// keeps the fast text path.
7120    #[test]
7121    fn sparse_but_real_documents_pass() {
7122        let one_pager = vec![page_with(&[
7123            "Confidential briefing",
7124            "Prepared for the board meeting",
7125            "Do not distribute",
7126        ])];
7127        assert!(!super::text_layer_is_vestigial(&one_pager));
7128    }
7129}
7130
7131/// #994: decoded Form XObject content is cached per document only from a
7132/// form's second sighting, so one-form-per-page documents do not hold every
7133/// page's decoded form until the document ends.
7134#[cfg(test)]
7135mod form_cache {
7136    use lopdf::content::{Content, Operation};
7137    use lopdf::{dictionary, Document, Object, Stream};
7138
7139    fn form(doc: &mut Document, text: &str) -> lopdf::ObjectId {
7140        let ops = vec![
7141            Operation::new("BT", vec![]),
7142            Operation::new("Tf", vec!["F1".into(), 12.into()]),
7143            Operation::new("Td", vec![40.into(), 500.into()]),
7144            Operation::new("Tj", vec![Object::string_literal(text)]),
7145            Operation::new("ET", vec![]),
7146        ];
7147        let data = Content { operations: ops }.encode().unwrap();
7148        doc.add_object(Stream::new(
7149            dictionary! { "Type" => "XObject", "Subtype" => "Form",
7150            "BBox" => vec![0.into(), 0.into(), 595.into(), 842.into()] },
7151            data,
7152        ))
7153    }
7154
7155    #[test]
7156    fn single_use_forms_are_not_retained_shared_ones_are() {
7157        let mut doc = Document::with_version("1.5");
7158        let pages_id = doc.new_object_id();
7159        let font = doc.add_object(
7160            dictionary! { "Type" => "Font", "Subtype" => "Type1", "BaseFont" => "Helvetica" },
7161        );
7162        let header = form(&mut doc, "Header");
7163        let mut kids = Vec::new();
7164        let mut own_forms = Vec::new();
7165        for p in 0..3 {
7166            let own = form(&mut doc, &format!("Body{p}"));
7167            own_forms.push(own);
7168            let content = doc.add_object(Stream::new(
7169                dictionary! {},
7170                b"q /Hd Do Q q /Fx Do Q".to_vec(),
7171            ));
7172            kids.push(Object::Reference(doc.add_object(dictionary! {
7173                "Type" => "Page", "Parent" => pages_id,
7174                "MediaBox" => vec![0.into(), 0.into(), 595.into(), 842.into()],
7175                "Contents" => content,
7176                "Resources" => dictionary! {
7177                    "Font" => dictionary! { "F1" => font },
7178                    "XObject" => dictionary! { "Hd" => header, "Fx" => own },
7179                },
7180            })));
7181        }
7182        doc.objects.insert(
7183            pages_id,
7184            Object::Dictionary(dictionary! { "Type" => "Pages", "Kids" => kids, "Count" => 3 }),
7185        );
7186        let catalog = doc.add_object(dictionary! { "Type" => "Catalog", "Pages" => pages_id });
7187        doc.trailer.set("Root", catalog);
7188
7189        let mut caches = super::DocCaches::default();
7190        let mut pages: Vec<_> = doc.get_pages().into_iter().collect();
7191        pages.sort_by_key(|(n, _)| *n);
7192        for (i, (_, pid)) in pages.iter().enumerate() {
7193            let text: String = super::page_glyphs_cached(&doc, *pid, &mut caches)
7194                .iter()
7195                .map(|g| g.ch)
7196                .collect();
7197            // Both forms' text is still read, cached or not.
7198            assert!(text.contains("Header"), "page {i}: {text:?}");
7199            assert!(text.contains(&format!("Body{i}")), "page {i}: {text:?}");
7200        }
7201        // The shared header form is cached from its second page on; the
7202        // per-page forms, each used once, are not held.
7203        assert!(caches.forms.contains_key(&header));
7204        for own in &own_forms {
7205            assert!(!caches.forms.contains_key(own));
7206        }
7207        assert_eq!(caches.forms.len(), 1);
7208    }
7209}
7210
7211#[cfg(test)]
7212mod cid_collections {
7213    use super::base14_fonts::{cells, pdf_with_content};
7214
7215    fn type0(encoding: &str) -> Vec<u8> {
7216        format!(
7217            "<</Type/Font/Subtype/Type0/BaseFont/Test-Font-Light/Encoding/{encoding}\
7218             /DescendantFonts[<</Type/Font/Subtype/CIDFontType0/BaseFont/Test-Font-Light\
7219             /CIDSystemInfo<</Registry(Adobe)/Ordering(Japan1)/Supplement 7>>/DW 1000>>]>>"
7220        )
7221        .into_bytes()
7222    }
7223
7224    fn text(fontdict: &[u8], hex: &str) -> String {
7225        let content = format!("BT /F1 12 Tf 72 700 Td <{hex}> Tj ET\n");
7226        cells(&pdf_with_content(fontdict, content.as_bytes()))
7227            .iter()
7228            .map(|c| c.text.as_str())
7229            .collect()
7230    }
7231
7232    #[test]
7233    #[cfg(feature = "cid-collections")]
7234    fn identity_codes_read_through_the_collection() {
7235        assert_eq!(text(&type0("Identity-H"), "0CD40E8A07A0"), "日本語");
7236    }
7237
7238    #[test]
7239    fn unicode_keyed_cmaps_read_the_code() {
7240        assert_eq!(text(&type0("UniJIS-UCS2-H"), "65E5672C8A9E"), "日本語");
7241    }
7242
7243    #[test]
7244    #[cfg(feature = "cid-collections")]
7245    fn collection_ranges_keep_supplementary_characters() {
7246        assert_eq!(text(&type0("Identity-H"), "0CD44507450807A0"), "日𢭏𢭐語");
7247        let text = |o: &[u8], cid| super::collection_text(super::collection_table(o).unwrap(), cid);
7248        assert_eq!(text(b"Japan1", 0x2714).as_deref(), Some("🄐"));
7249        assert_eq!(text(b"CNS1", 0x3a32).as_deref(), Some("𡤃"));
7250    }
7251
7252    #[test]
7253    #[cfg(feature = "cid-collections")]
7254    fn collection_entries_are_plain_characters() {
7255        assert_eq!(text(&type0("Identity-H"), "046D"), "逢");
7256        let text = |o: &[u8], cid| super::collection_text(super::collection_table(o).unwrap(), cid);
7257        assert_eq!(text(b"Korea1", 8752), None);
7258        assert_eq!(text(b"KR", 11704), None);
7259        assert_eq!(text(b"Japan1", 0x1ffd).as_deref(), Some("sec"));
7260    }
7261
7262    #[test]
7263    fn tounicode_ranges_increment_the_utf16_string() {
7264        let map = super::parse_tounicode(
7265            b"3 beginbfrange\n\
7266              <01> <02> <d842dfb7>\n\
7267              <03> <04> <00660069>\n\
7268              <05> <06> <0061>\n\
7269              endbfrange",
7270        );
7271        assert_eq!(map[&1], "𠮷");
7272        assert_eq!(map[&2], "𠮸");
7273        assert_eq!(map[&3], "fi");
7274        assert_eq!(map[&4], "fj");
7275        assert_eq!(map[&5], "a");
7276        assert_eq!(map[&6], "b");
7277    }
7278
7279    #[test]
7280    fn tounicode_skips_lone_surrogates_overflows_and_huge_ranges() {
7281        let map = super::parse_tounicode(
7282            b"2 beginbfchar\n<01> <d842>\n<02> <0041>\nendbfchar\n\
7283              4 beginbfrange\n\
7284              <10> <11> [<dc00> <0042>]\n\
7285              <20> <22> <0041fffe>\n\
7286              <30> <31> <d842dfff>\n\
7287              <00010000> <ffffffff> <>\n\
7288              endbfrange",
7289        );
7290        assert!(!map.contains_key(&0x01));
7291        assert_eq!(map[&0x02], "A");
7292        assert!(!map.contains_key(&0x10));
7293        assert_eq!(map[&0x11], "B");
7294        assert_eq!(map[&0x20], "A\u{fffe}");
7295        assert_eq!(map[&0x21], "A\u{ffff}");
7296        assert!(!map.contains_key(&0x22));
7297        assert_eq!(map[&0x30], "\u{20bff}");
7298        assert!(!map.contains_key(&0x31));
7299        assert_eq!(map[&0x1ffff], "");
7300        assert_eq!(map.len(), 5 + 0x10000);
7301    }
7302
7303    #[test]
7304    fn utf16_pairs_are_one_glyph_and_one_advance() {
7305        let font = type0("UniJIS-UTF16-H");
7306        assert_eq!(text(&font, "65E5D842DFB78A9E"), "日𠮷語");
7307        let content = b"BT /F1 12 Tf 72 700 Td <65E5D842DFB78A9E> Tj ET\n";
7308        let pdf = pdf_with_content(&font, content);
7309        let doc = lopdf::Document::load_mem(&pdf).unwrap();
7310        let glyphs = super::page_glyphs(&doc, doc.get_pages()[&1]);
7311        assert_eq!(glyphs.len(), 3);
7312        assert!((glyphs[2].l - glyphs[0].l - 24.0).abs() < 0.001);
7313    }
7314
7315    #[test]
7316    fn utf16_codes_preserve_tounicode_keys_and_identity_cids() {
7317        use lopdf::{dictionary, Document};
7318        let doc = Document::with_version("1.4");
7319        let dict = dictionary! {"Subtype" => "Type0", "Encoding" => "UniJIS-UTF16-H"};
7320        let mut font = super::parse_font(&doc, b"F1", &dict);
7321        assert_eq!(
7322            super::codes(&font, &[0xd8, 0x42, 0xdf, 0xb7]),
7323            vec![0xd842dfb7]
7324        );
7325        font.to_unicode.insert(0xd842dfb7, "override".into());
7326        assert_eq!(font.decode_code(0xd842dfb7).0.as_deref(), Some("override"));
7327        assert_eq!(
7328            super::codes(&font, &[0xd8, 0x42, 0x65, 0xe5]),
7329            vec![0xd842, 0x65e5]
7330        );
7331        let dict = dictionary! {"Subtype" => "Type0", "Encoding" => "Identity-H"};
7332        let font = super::parse_font(&doc, b"F1", &dict);
7333        assert_eq!(
7334            super::codes(&font, &[0xd8, 0x42, 0xdf, 0xb7]),
7335            vec![0xd842, 0xdfb7]
7336        );
7337    }
7338}