pdfsift 0.1.0

PDF to structured Markdown for LLM agents. Heuristics only: no AI model, no network.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
//! Extraction: PDFium characters → [`Char`]. The only part of `layout` that touches PDFium
//! (through `pdfium-render` and, for marked content, the raw handle in [`crate::tags`]).

use std::collections::BTreeMap;

use pdfium_render::prelude::*;

use super::{Artifact, Char, CharKind, CharSource, Figure, Rect, Style};
use crate::tags::{Elem, Mark, MarkValue, ObjMarks, RawPage};

/// Reads every character of a page, in PDFium's text order (which follows the
/// content stream). Characters PDFium cannot place (no box, no origin, NaN) are
/// skipped; they are junk for layout purposes.
///
/// With `raw` (the same page on a raw PDFium handle), each char also gets its source
/// object and marked-content signals ([`CharSource`], achado 007). Every char is
/// classified and normalized ([`classify`], [`split_ligature`]).
pub fn page_chars(page: &PdfPage, raw: Option<&RawPage>) -> Vec<Char> {
    let page_h = page.height().value;
    let Ok(text) = page.text() else {
        return Vec::new();
    };
    let chars = text.chars();
    let total = chars.len();
    let signals = raw
        .map(|r| PageSignals::new(&r.object_marks(), &r.char_objects(), &r.structure()))
        // The raw char -> object map comes from a second text page; it lines up with this
        // one only if both have the same number of chars (true on the whole corpus,
        // achado 007). Otherwise no signals rather than wrong ones.
        .filter(|s| s.char_count() == total);
    let figures = figure_forms(page);
    let mut out = Vec::new();
    // Iterate by index: the crate's iterator stops at the first char it fails to read,
    // and the index is what links a char to the raw signals.
    for i in 0..total {
        let Ok(c) = chars.get(i as PdfPageTextCharIndex) else {
            continue;
        };
        let Some(ch) = c.unicode_char() else { continue };
        let Ok(r) = c.loose_bounds() else { continue };
        let generated = c.is_generated().unwrap_or(false);
        let size = c.scaled_font_size().value;
        let bbox = Rect::new(
            r.left().value,
            page_h - r.top().value,
            r.right().value,
            page_h - r.bottom().value,
        );
        let finite = [bbox.left, bbox.top, bbox.right, bbox.bottom, size]
            .iter()
            .all(|v| v.is_finite());
        if !finite {
            continue;
        }
        // Generated characters (PDFium's inferred spaces and "\r\n") often have a
        // degenerate box; they only matter as separators, so keep them regardless.
        let baseline = match c.origin_y() {
            Ok(y) if y.value.is_finite() => page_h - y.value,
            _ => bbox.bottom,
        };
        let raw_name = c.font_name();
        let font = strip_subset(&raw_name).to_string();
        let style = style_from_font(
            &font,
            c.font_is_bold_reenforced(),
            c.font_is_italic(),
            c.font_is_fixed_pitch(),
        );
        // PDFium's hyphen flag is only asked for hyphen-like chars. An error counts as
        // "yes" for U+0002, which PDFium emits for nothing but line-end hyphens.
        let (ch, kind) = classify(ch, || c.is_hyphen().unwrap_or(ch == '\u{2}'));
        let mut source = signals.as_ref().map(|s| s.source(i)).unwrap_or_default();
        source.figure = signals.as_ref().and_then(|s| s.form_of(i)).and_then(|t| {
            let rect = figures.get(t as usize).copied().flatten()?;
            Some(Figure { object: t, rect })
        });
        out.extend(split_ligature(Char {
            ch,
            bbox,
            baseline,
            size,
            font,
            style,
            generated,
            kind,
            source,
        }));
    }
    out
}

/// Character kind and normalized character (achado 003, findings 1 and 3).
///
/// - U+0002 flagged by `FPDFText_IsHyphen` is PDFium's line-end hyphen: it becomes `-`
///   with [`CharKind::LineEndHyphen`]. It is never deleted here: it is a real compound
///   hyphen in 4 of 5 Chrome cases and in 3 to 7 cases per hyphenating producer.
/// - A `-`, U+2010 or U+00AD that PDFium flags as a line-end hyphen is the same thing.
/// - Any other U+00AD is [`CharKind::SoftHyphen`] (Typst leaves the author's unused ones).
///
/// A U+0002 that PDFium does not flag is left alone (a control char: a word separator).
/// `is_hyphen` is only called for hyphen-like chars.
pub fn classify(ch: char, is_hyphen: impl FnOnce() -> bool) -> (char, CharKind) {
    if !matches!(ch, '\u{2}' | '-' | '\u{2010}' | '\u{AD}') {
        return (ch, CharKind::Text);
    }
    if is_hyphen() {
        ('-', CharKind::LineEndHyphen)
    } else if ch == '\u{AD}' {
        (ch, CharKind::SoftHyphen)
    } else {
        (ch, CharKind::Text)
    }
}

/// Letters of a Latin presentation-form ligature (U+FB00–U+FB06, their NFKC forms).
pub fn ligature_letters(ch: char) -> Option<&'static str> {
    Some(match ch {
        '\u{FB00}' => "ff",
        '\u{FB01}' => "fi",
        '\u{FB02}' => "fl",
        '\u{FB03}' => "ffi",
        '\u{FB04}' => "ffl",
        '\u{FB05}' | '\u{FB06}' => "st",
        _ => return None,
    })
}

/// Replaces a presentation-form ligature by one char per letter, splitting its box into
/// equal parts with the same baseline. No corpus PDF reaches this (PDFium applies
/// Chrome's ActualText, and the other producers map ligatures 1→n in ToUnicode, achado
/// 003 finding 4), but other PDFs can. Splitting, rather than one char with two letters,
/// keeps `Char::ch` a single char and mirrors what PDFium itself does with Chrome's
/// ActualText ligatures (`f` 324.18–326.47, `i` 326.47–328.76): adjacent boxes and zero
/// gap, so the letters stay in one word.
pub fn split_ligature(c: Char) -> Vec<Char> {
    let Some(letters) = ligature_letters(c.ch) else {
        return vec![c];
    };
    let n = letters.chars().count() as f32;
    let w = c.bbox.width() / n;
    letters
        .chars()
        .enumerate()
        .map(|(i, ch)| {
            let left = c.bbox.left + w * i as f32;
            Char {
                ch,
                bbox: Rect::new(left, c.bbox.top, left + w, c.bbox.bottom),
                ..c.clone()
            }
        })
        .collect()
}

/// Marked-content signals of one page object (flattened depth-first).
#[derive(Clone, Debug, Default, PartialEq)]
struct ObjSignals {
    mcid: Option<i32>,
    actual_text: Option<String>,
    artifact: Option<Artifact>,
    /// Some text-page char comes from this object.
    has_chars: bool,
}

/// Everything extraction reads from the raw handle for one page, as plain data, so the
/// logic is testable without PDFium.
#[derive(Clone, Debug, Default)]
pub struct PageSignals {
    /// Flat object index of each raw text-page char.
    char_obj: Vec<Option<u32>>,
    objects: Vec<ObjSignals>,
    /// MCID -> ActualText of the structure element that owns it (or of its nearest
    /// ancestor with one). LibreOffice tagged: 99 `Span`s with U+00AD (achado 007, finding 4).
    struct_actual: BTreeMap<i32, String>,
    /// MCID -> level of the nearest `H1`..`H6` ancestor element.
    struct_heading: BTreeMap<i32, u8>,
    /// Top-level object index of the form XObject each raw char is drawn in (None
    /// outside forms).
    char_form: Vec<Option<u32>>,
}

impl PageSignals {
    /// `marks`: [`RawPage::object_marks`]; `char_paths`: [`RawPage::char_objects`];
    /// `tree`: [`RawPage::structure`].
    pub fn new(marks: &[ObjMarks], char_paths: &[Option<Vec<usize>>], tree: &[Elem]) -> Self {
        let mut objects = Vec::new();
        let mut index = BTreeMap::new();
        for (i, m) in marks.iter().enumerate() {
            flatten(m, vec![i], &[], &mut objects, &mut index, 0);
        }
        let char_obj: Vec<Option<u32>> = char_paths
            .iter()
            .map(|p| p.as_ref().and_then(|p| index.get(p).copied()))
            .collect();
        for o in char_obj.iter().flatten() {
            if let Some(obj) = objects.get_mut(*o as usize) {
                obj.has_chars = true;
            }
        }
        let char_form = char_paths
            .iter()
            .map(|p| match p.as_deref() {
                Some([top, _, ..]) => u32::try_from(*top).ok(),
                _ => None,
            })
            .collect();
        let mut struct_actual = BTreeMap::new();
        for e in tree {
            collect_struct_actual(e, None, &mut struct_actual, 0);
        }
        let mut struct_heading = BTreeMap::new();
        for e in tree {
            collect_struct_heading(e, None, &mut struct_heading, 0);
        }
        PageSignals {
            char_obj,
            objects,
            struct_actual,
            struct_heading,
            char_form,
        }
    }

    /// Top-level index of the form XObject raw char `i` is drawn in.
    pub fn form_of(&self, i: usize) -> Option<u32> {
        self.char_form.get(i).copied().flatten()
    }

    pub fn char_count(&self) -> usize {
        self.char_obj.len()
    }

    /// Signals of raw text-page char `i`.
    pub fn source(&self, i: usize) -> CharSource {
        let Some(o) = self.char_obj.get(i).copied().flatten() else {
            return CharSource::default();
        };
        let Some(obj) = self.objects.get(o as usize) else {
            return CharSource::default();
        };
        // First char of its object: the previous raw char comes from another object
        // (generated chars have none, so a generated space before it also counts).
        let first = i == 0 || self.char_obj.get(i - 1).copied().flatten() != Some(o);
        let hidden_text_before = if first && o > 0 {
            self.objects
                .get(o as usize - 1)
                .filter(|p| !p.has_chars)
                .and_then(|p| p.actual_text.clone())
        } else {
            None
        };
        CharSource {
            object: Some(o),
            mcid: obj.mcid,
            actual_text: obj.actual_text.clone(),
            struct_actual_text: obj.mcid.and_then(|m| self.struct_actual.get(&m).cloned()),
            struct_heading: obj.mcid.and_then(|m| self.struct_heading.get(&m).copied()),
            artifact: obj.artifact.clone(),
            hidden_text_before,
            figure: None,
        }
    }
}

const MAX_DEPTH: usize = 64;

/// Depth-first, pre-order: each object, then the children of a form XObject. Children
/// inherit their ancestors' marks (outermost first), so "innermost" looks at the child's
/// own marks before the form's.
fn flatten<'m>(
    m: &'m ObjMarks,
    path: Vec<usize>,
    outer: &[&'m Mark],
    objects: &mut Vec<ObjSignals>,
    index: &mut BTreeMap<Vec<usize>, u32>,
    depth: usize,
) {
    let Ok(flat) = u32::try_from(objects.len()) else {
        return;
    };
    let mut chain: Vec<&Mark> = outer.to_vec();
    chain.extend(m.marks.iter());
    objects.push(obj_signals(&chain));
    if depth < MAX_DEPTH {
        for (j, child) in m.children.iter().enumerate() {
            let mut p = path.clone();
            p.push(j);
            flatten(child, p, &chain, objects, index, depth + 1);
        }
    }
    index.insert(path, flat);
}

fn obj_signals(chain: &[&Mark]) -> ObjSignals {
    let mcid = chain.iter().rev().find_map(|m| match m.get("MCID") {
        Some(MarkValue::Int(v)) => Some(*v),
        _ => None,
    });
    let actual_text = chain
        .iter()
        .rev()
        .find_map(|m| m.str_param("ActualText"))
        .map(str::to_string);
    let artifact = chain
        .iter()
        .rev()
        .find(|m| m.name == "Artifact")
        .map(|m| Artifact {
            // Always None with PDFium chromium/8179, which cannot read name values
            // (achado 007, finding 1); kept for a PDFium that can, or a string Subtype.
            subtype: match m.get("Subtype") {
                Some(MarkValue::Name(s) | MarkValue::Str(s)) => Some(s.clone()),
                _ => None,
            },
            has_params: !m.params.is_empty(),
            pagination: m.get("Subtype").is_some()
                || matches!(m.get("Type"), Some(MarkValue::Name(t)) if t == "Pagination"),
        });
    ObjSignals {
        mcid,
        actual_text,
        artifact,
        has_chars: false,
    }
}

/// MCID -> ActualText, the innermost element with an ActualText winning (by the standard
/// it replaces the whole subtree's content, so an inherited one still covers the MCID).
fn collect_struct_actual(
    e: &Elem,
    inherited: Option<&str>,
    out: &mut BTreeMap<i32, String>,
    depth: usize,
) {
    let at = e.actual_text.as_deref().or(inherited);
    if let Some(at) = at {
        for m in &e.mcids {
            out.entry(*m).or_insert_with(|| at.to_string());
        }
    }
    if depth < MAX_DEPTH {
        for c in &e.children {
            collect_struct_actual(c, at, out, depth + 1);
        }
    }
}

/// MCID -> heading level of the nearest `H1`..`H6` element at or above it. Only the
/// standard names are read (no RoleMap): a custom role is simply not a heading.
fn collect_struct_heading(
    e: &Elem,
    inherited: Option<u8>,
    out: &mut BTreeMap<i32, u8>,
    depth: usize,
) {
    let own = e
        .kind
        .strip_prefix('H')
        .and_then(|n| n.parse::<u8>().ok())
        .filter(|n| (1..=6).contains(n));
    let level = own.or(inherited);
    if let Some(l) = level {
        for m in &e.mcids {
            out.entry(*m).or_insert(l);
        }
    }
    if depth < MAX_DEPTH {
        for c in &e.children {
            collect_struct_heading(c, level, out, depth + 1);
        }
    }
}

/// Bounding boxes of small, roughly square vector paths: candidates for list bullets
/// drawn as shapes instead of glyphs (Chrome draws `•`, `◦`, `▪` this way). The
/// grouping stage decides, relative to the font size of the line next to them, which
/// ones are really markers. Only top-level page objects are scanned (not form XObjects).
pub fn page_path_marks(page: &PdfPage) -> Vec<Rect> {
    // Absolute bounds, in points, wide enough for bullets of 6–20 pt text.
    const MIN_SIDE: f32 = 1.0;
    const MAX_SIDE: f32 = 12.0;
    let page_h = page.height().value;
    let mut out = Vec::new();
    for obj in page.objects().iter() {
        if obj.object_type() != PdfPageObjectType::Path {
            continue;
        }
        let Ok(q) = obj.bounds() else { continue };
        let r = q.to_rect();
        let rect = Rect::new(
            r.left().value,
            page_h - r.top().value,
            r.right().value,
            page_h - r.bottom().value,
        );
        let (w, h) = (rect.width(), rect.height());
        let ok = w.is_finite()
            && h.is_finite()
            && (MIN_SIDE..=MAX_SIDE).contains(&w)
            && (MIN_SIDE..=MAX_SIDE).contains(&h)
            && w <= 1.5 * h
            && h <= 1.5 * w;
        if ok {
            out.push(rect);
        }
    }
    out
}

/// A form XObject covering at least this share of the page area is a page wrapper
/// (pdfTeX `\includepdf`, imposition tools), not a figure. Figures with text measured
/// in achado 012: 13 % (arXiv 2509.23299 p. 2), 18 % (Word diagram, 2509.09931 p. 2),
/// 34 % (USGS map, fs20243057 p. 1).
const FIGURE_MAX_PAGE_SHARE: f32 = 0.5;

/// For each top-level page object, its bounds (top-origin) when it is a form XObject
/// smaller than [`FIGURE_MAX_PAGE_SHARE`] of the page: a figure whose text labels must
/// not shape the page columns (achado 012, item 1). Indices match the raw handle's
/// (`FPDFPage_GetObject`), since both walk the same page object list.
pub fn figure_forms(page: &PdfPage) -> Vec<Option<Rect>> {
    let page_h = page.height().value;
    let page_area = page.width().value * page_h;
    page.objects()
        .iter()
        .map(|obj| {
            if obj.object_type() != PdfPageObjectType::XObjectForm {
                return None;
            }
            let r = obj.bounds().ok()?.to_rect();
            let rect = Rect::new(
                r.left().value,
                page_h - r.top().value,
                r.right().value,
                page_h - r.bottom().value,
            );
            let area = rect.width() * rect.height();
            (area.is_finite() && page_area > 0.0 && area < FIGURE_MAX_PAGE_SHARE * page_area)
                .then_some(rect)
        })
        .collect()
}

/// Thin horizontal vector paths (rules): at most `MAX_THICK` pt tall and at least
/// `MIN_LEN` pt long, top-level page objects only. Column detection uses the ones that
/// cross a gutter to cut it (booktabs rules of a `table*`, achado 012). Filled thin
/// rectangles count too: Word and LibreOffice draw table borders that way.
pub fn page_rules(page: &PdfPage) -> Vec<Rect> {
    // booktabs: 0.4–0.8 pt; a 3 pt bar is still a rule, a shaded box is not.
    const MAX_THICK: f32 = 3.0;
    const MIN_LEN: f32 = 20.0;
    let page_h = page.height().value;
    let mut out = Vec::new();
    for obj in page.objects().iter() {
        if obj.object_type() != PdfPageObjectType::Path {
            continue;
        }
        let Ok(q) = obj.bounds() else { continue };
        let r = q.to_rect();
        let rect = Rect::new(
            r.left().value,
            page_h - r.top().value,
            r.right().value,
            page_h - r.bottom().value,
        );
        let (w, h) = (rect.width(), rect.height());
        if w.is_finite() && h.is_finite() && h <= MAX_THICK && w >= MIN_LEN {
            out.push(rect);
        }
    }
    out
}

/// Strips the 6-uppercase-letter subset prefix (`JUNBRM+LMRoman10-Regular`).
pub fn strip_subset(name: &str) -> &str {
    match name.split_once('+') {
        Some((tag, rest)) if tag.len() == 6 && tag.bytes().all(|b| b.is_ascii_uppercase()) => rest,
        _ => name,
    }
}

/// Bold/italic/mono from the font name first, descriptor flags second.
/// The reported weight is ignored on purpose: LaTeX mono reports 840 and LibreOffice
/// reports 400 even for `Arial-BoldMT` (docs/achados/001-kitchen-sink.md, finding 2).
pub fn style_from_font(
    name: &str,
    force_bold: bool,
    italic_flag: bool,
    fixed_pitch: bool,
) -> Style {
    let lower = name.to_ascii_lowercase();
    let has = |words: &[&str]| words.iter().any(|w| lower.contains(w));
    Style {
        bold: force_bold || has(&["bold", "black", "heavy", "semibold", "demibold"]),
        italic: italic_flag || has(&["italic", "oblique", "slant"]),
        mono: fixed_pitch
            || has(&[
                "mono",
                "courier",
                "consolas",
                "code",
                "menlo",
                "typewriter",
                "lmtt",
                "cmtt",
            ]),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn subset_prefix_is_stripped_only_when_well_formed() {
        assert_eq!(
            strip_subset("JUNBRM+LMRoman10-Regular"),
            "LMRoman10-Regular"
        );
        assert_eq!(strip_subset("Arial-BoldMT"), "Arial-BoldMT");
        assert_eq!(strip_subset("abc+Foo"), "abc+Foo");
        assert_eq!(strip_subset("AAAAAA+"), "");
    }

    #[test]
    fn style_comes_from_the_name() {
        let s = style_from_font("LMRoman10-BoldItalic", false, false, false);
        assert!(s.bold && s.italic && !s.mono);
        let s = style_from_font("LMMono10-Regular", false, false, false);
        assert!(s.mono && !s.bold);
        let s = style_from_font("Arial-BoldMT", false, false, false);
        assert!(s.bold);
        let s = style_from_font("TimesNewRomanPSMT", false, false, false);
        assert_eq!(s, Style::default());
    }

    #[test]
    fn hyphens_are_classified_not_deleted() {
        assert_eq!(classify('\u{2}', || true), ('-', CharKind::LineEndHyphen));
        // A U+0002 PDFium does not flag stays a control char (a word separator).
        assert_eq!(classify('\u{2}', || false), ('\u{2}', CharKind::Text));
        assert_eq!(
            classify('\u{AD}', || false),
            ('\u{AD}', CharKind::SoftHyphen)
        );
        assert_eq!(classify('\u{AD}', || true), ('-', CharKind::LineEndHyphen));
        assert_eq!(classify('-', || false), ('-', CharKind::Text));
        // PDFium is not even asked for ordinary letters.
        assert_eq!(classify('a', || panic!("asked")), ('a', CharKind::Text));
    }

    fn letter(ch: char, left: f32, right: f32) -> Char {
        Char {
            ch,
            bbox: Rect::new(left, 90.0, right, 102.0),
            baseline: 100.0,
            size: 10.0,
            font: "Serif".into(),
            style: Style::default(),
            generated: false,
            kind: CharKind::Text,
            source: CharSource {
                object: Some(3),
                ..Default::default()
            },
        }
    }

    #[test]
    fn ligatures_split_into_adjacent_letters() {
        let parts = split_ligature(letter('\u{FB03}', 10.0, 25.0));
        let text: String = parts.iter().map(|c| c.ch).collect();
        assert_eq!(text, "ffi");
        let edges: Vec<(f32, f32)> = parts.iter().map(|c| (c.bbox.left, c.bbox.right)).collect();
        assert_eq!(edges, [(10.0, 15.0), (15.0, 20.0), (20.0, 25.0)]);
        assert!(
            parts
                .iter()
                .all(|c| c.baseline == 100.0 && c.source.object == Some(3))
        );
        assert_eq!(split_ligature(letter('f', 0.0, 3.0)).len(), 1);
        for (lig, s) in [('\u{FB00}', "ff"), ('\u{FB01}', "fi"), ('\u{FB02}', "fl")] {
            assert_eq!(ligature_letters(lig), Some(s));
        }
        assert_eq!(ligature_letters('\u{FB06}'), Some("st"));
        assert_eq!(ligature_letters('\u{FB07}'), None);
        // The split letters form one word.
        let mut chars = vec![letter('o', 5.0, 10.0)];
        chars.extend(split_ligature(letter('\u{FB01}', 10.0, 16.0)));
        chars.push(letter('m', 16.0, 22.0));
        let words = crate::layout::group::words(&chars);
        assert_eq!(words.len(), 1);
        assert_eq!(words[0].text, "ofim");
    }

    fn mark(name: &str, params: &[(&str, MarkValue)]) -> Mark {
        Mark {
            name: name.into(),
            params: params
                .iter()
                .map(|(k, v)| (k.to_string(), v.clone()))
                .collect(),
        }
    }

    fn obj(marks: Vec<Mark>) -> ObjMarks {
        ObjMarks {
            marks,
            children: Vec::new(),
        }
    }

    fn elem(kind: &str, actual: Option<&str>, mcids: Vec<i32>, children: Vec<Elem>) -> Elem {
        Elem {
            kind: kind.into(),
            alt: None,
            actual_text: actual.map(String::from),
            expansion: None,
            mcids,
            children,
        }
    }

    #[test]
    fn page_signals_follow_achado_007() {
        let str_ = |s: &str| MarkValue::Str(s.into());
        let marks = vec![
            // 0: Typst line "sa", MCID 60.
            obj(vec![mark("Span", &[("MCID", MarkValue::Int(60))])]),
            // 1: Typst real hyphen: Span(MCID) > Span(ActualText="-").
            obj(vec![
                mark("Span", &[("MCID", MarkValue::Int(60))]),
                mark("Span", &[("ActualText", str_("-"))]),
            ]),
            // 2: the repeated hyphen, which yields no chars.
            obj(vec![mark("Span", &[("ActualText", str_("-"))])]),
            // 3: next line "gem"; MCID 61 is a structure Span with ActualText U+00AD.
            obj(vec![mark("Span", &[("MCID", MarkValue::Int(61))])]),
            // 4: a pagination artifact (PDFium returns its name values as unreadable).
            obj(vec![mark(
                "Artifact",
                &[("Subtype", MarkValue::Other("name"))],
            )]),
            // 5: a form XObject whose child 0 inherits the form's MCID.
            ObjMarks {
                marks: vec![mark("P", &[("MCID", MarkValue::Int(7))])],
                children: vec![obj(vec![mark("Span", &[("ActualText", str_("fi"))])])],
            },
        ];
        let paths = vec![
            Some(vec![0]),
            Some(vec![0]),
            Some(vec![1]),
            None, // generated "\r\n"
            Some(vec![3]),
            Some(vec![3]),
            Some(vec![4]),
            Some(vec![5, 0]),
            Some(vec![9]), // unknown object: no signals
        ];
        let tree = vec![elem(
            "P",
            None,
            vec![60],
            vec![elem("Span", Some("\u{AD}"), vec![61], Vec::new())],
        )];
        let s = PageSignals::new(&marks, &paths, &tree);
        assert_eq!(s.char_count(), 9);
        assert_eq!(s.struct_actual.get(&61).map(String::as_str), Some("\u{AD}"));
        assert!(!s.struct_actual.contains_key(&60));

        let hyphen = s.source(2);
        assert_eq!(hyphen.object, Some(1));
        assert_eq!(hyphen.mcid, Some(60));
        assert_eq!(hyphen.actual_text.as_deref(), Some("-"));
        // Object 0 has chars, so nothing is hidden before the hyphen.
        assert_eq!(hyphen.hidden_text_before, None);

        assert_eq!(s.source(3), CharSource::default());
        let g = s.source(4);
        assert_eq!(g.hidden_text_before.as_deref(), Some("-"));
        assert_eq!(g.struct_actual_text.as_deref(), Some("\u{AD}"));
        // Only the first char of an object carries it.
        assert_eq!(s.source(5).hidden_text_before, None);

        let a = s.source(6).artifact.expect("artifact");
        assert_eq!((a.subtype, a.has_params, a.pagination), (None, true, true));

        let child = s.source(7);
        // Flat index: objects 0..=5 are 0..=5, the form's child is 6.
        assert_eq!(child.object, Some(6));
        assert_eq!(child.mcid, Some(7));
        assert_eq!(child.actual_text.as_deref(), Some("fi"));

        assert_eq!(s.source(8), CharSource::default());
        assert_eq!(s.source(99), CharSource::default());
    }
}