Skip to main content

docling_pdf/
pdfium_backend.rs

1//! pdfium-based text extraction and page rendering.
2//!
3//! Text is reconstructed the way docling's `docling-parse` does it, so the
4//! output spacing matches the groundtruth: the page's **character** stream is
5//! grouped into **words** (split at a horizontal gap wider than a fraction of
6//! the font height — font-relative, so letter-tracking in display titles does
7//! not split a word) and words into **lines** (by baseline). pdfium-render's
8//! safe API only exposes whole style runs / `GetBoundedText`, so the character
9//! loop is driven through the raw `PdfiumLibraryBindings` FFI on a second handle
10//! to the same bytes (no fork; stays publishable).
11
12#[cfg(feature = "ocr-prep")]
13use image::RgbImage;
14#[cfg(feature = "ml")]
15use pdfium_render::prelude::*;
16
17/// A run of text with its bounding box, in PDF points with a **top-left** origin
18/// (pdfium's native origin is bottom-left; we flip it to match docling's
19/// `BoundingBox(..., origin=TOPLEFT)`).
20#[derive(Debug, Clone)]
21pub struct TextCell {
22    pub text: String,
23    pub l: f32,
24    pub t: f32,
25    pub r: f32,
26    pub b: f32,
27}
28
29/// Pixels-per-point used to render page images. Layout is scale-invariant (it
30/// scales normalized boxes by the page point size), but OCR benefits from the
31/// extra resolution.
32pub const RENDER_SCALE: f32 = 2.0;
33
34/// One page's geometry, extracted text cells, and a rendered RGB image. The
35/// image is rendered at [`RENDER_SCALE`] pixels per PDF point; `image px =
36/// page point × scale`.
37#[derive(Clone)]
38pub struct PdfPage {
39    pub width: f32,
40    pub height: f32,
41    pub scale: f32,
42    pub cells: Vec<TextCell>,
43    /// Same text grouped for code regions: split only at pdfium space glyphs, so
44    /// monospace runs keep their source spacing instead of the prose heuristic's.
45    pub code_cells: Vec<TextCell>,
46    /// Per-word cells (one per word, not joined into lines) for TableFormer cell
47    /// matching.
48    pub word_cells: Vec<TextCell>,
49    /// The rendered page bitmap. Present whenever pixels are available at all
50    /// (`ocr-prep` ⊂ `ml`): the native pipeline renders it with pdfium, the
51    /// browser pipeline receives it from the host canvas. Picture regions are
52    /// cropped out of it.
53    #[cfg(feature = "ocr-prep")]
54    pub image: RgbImage,
55    /// The **scale-1.0** page image the layout model runs on (docling parity:
56    /// its layout stage calls `page.get_image(scale=1.0)` — pdfium at 1.5×,
57    /// PIL-BICUBIC down to point size — a *different* image from the 2×
58    /// OCR/crop bitmap above, and a different resampling regime than
59    /// stretching that bitmap). `None` on paths without a pdfium renderer
60    /// (browser, METS/TIFF), which fall back to stretching [`Self::image`].
61    #[cfg(feature = "ocr-prep")]
62    pub image_layout: Option<RgbImage>,
63    /// Hyperlink annotations on the page (rect in top-left page coords + target
64    /// URI), restricted to web/mail/tel schemes. Used only by strict Markdown.
65    pub links: Vec<LinkAnnot>,
66    /// The page's `/Rotate` value (0/90/180/270) when it was normalized away
67    /// before inference: a scanned page with `/Rotate` displays its raster
68    /// rotated, which turns OCR into garbage — so extraction un-rotates the
69    /// bitmaps (and swaps `width`/`height`) and records the display rotation
70    /// here. Assembly rotates the finished geometry *back* by this many
71    /// degrees clockwise, so emitted locations and the page size stay in
72    /// display space (matching docling and every PDF viewer). Always 0 for
73    /// text-layer pages (their cells live in display space already) and on
74    /// paths without a pdfium renderer.
75    pub rotation: u16,
76}
77
78impl PdfPage {
79    /// A page built from recognized cells alone — the browser pipeline's
80    /// shape (#157), where the bitmap lives on the JS side. Exists so callers
81    /// compile identically with and without the `ml` feature: under a
82    /// feature-unified workspace build the struct carries the `image` field,
83    /// which a plain literal in a non-`ml` consumer can't spell.
84    #[cfg(feature = "ocr-prep")]
85    pub fn from_cells(width: f32, height: f32, scale: f32, cells: Vec<TextCell>) -> Self {
86        Self {
87            width,
88            height,
89            scale,
90            cells,
91            code_cells: Vec::new(),
92            word_cells: Vec::new(),
93            #[cfg(feature = "ocr-prep")]
94            image: RgbImage::new(0, 0),
95            #[cfg(feature = "ocr-prep")]
96            image_layout: None,
97            links: Vec::new(),
98            rotation: 0,
99        }
100    }
101
102    /// Same as [`from_cells`](Self::from_cells) but carrying the rendered page
103    /// bitmap, so picture regions can be cropped out of it (#157: the browser
104    /// pipeline gets the same figure bytes the native one does).
105    #[cfg(feature = "ocr-prep")]
106    pub fn from_cells_with_image(
107        width: f32,
108        height: f32,
109        scale: f32,
110        cells: Vec<TextCell>,
111        image: RgbImage,
112    ) -> Self {
113        Self {
114            image,
115            ..Self::from_cells(width, height, scale, cells)
116        }
117    }
118
119    /// Un-rotate the page's bitmaps by `deg` (clockwise 90° steps) and record
120    /// the compensating display rotation, composing with any rotation already
121    /// recorded: the raster becomes upright for inference while assembly
122    /// still maps the finished geometry back into display space. Handles both
123    /// `/Rotate` normalization (extraction) and content-detected orientation
124    /// (#225) — the two compose additively (axis-aligned 90° rotations
125    /// commute through the dimension swaps). Link rectangles follow the
126    /// raster; `width`/`height` swap on odd quarter-turns.
127    #[cfg(feature = "ocr-prep")]
128    pub(crate) fn unrotate(&mut self, deg: u16) {
129        if deg == 0 {
130            return;
131        }
132        use image::imageops::{rotate180, rotate270, rotate90};
133        // Display = upright rotated `deg`° clockwise, so upright = display
134        // rotated the complementary amount clockwise.
135        let un = |img: &RgbImage| match deg {
136            90 => rotate270(img),
137            180 => rotate180(img),
138            _ => rotate90(img),
139        };
140        if self.image.width() > 1 {
141            self.image = un(&self.image);
142        }
143        self.image_layout = self.image_layout.as_ref().map(&un);
144        let (width, height) = (self.width, self.height);
145        // Link rects follow the raster from display into upright space (the
146        // inverse of the geometry rotation assembly applies at the end).
147        for l in &mut self.links {
148            let (nl, nt, nr, nb) = match deg {
149                90 => (l.t, width - l.r, l.b, width - l.l),
150                180 => (width - l.r, height - l.b, width - l.l, height - l.t),
151                _ => (height - l.b, l.l, height - l.t, l.r),
152            };
153            (l.l, l.t, l.r, l.b) = (nl, nt, nr, nb);
154        }
155        if deg != 180 {
156            (self.width, self.height) = (height, width);
157        }
158        self.rotation = (self.rotation + deg) % 360;
159    }
160}
161
162/// A PDF link annotation: its rectangle (top-left page coordinates, matching
163/// [`TextCell`]) and target URI.
164#[derive(Debug, Clone)]
165pub struct LinkAnnot {
166    pub l: f32,
167    pub t: f32,
168    pub r: f32,
169    pub b: f32,
170    pub uri: String,
171}
172
173#[cfg(feature = "ml")]
174/// A parsed PDF: per-page text cells and page images.
175pub struct PdfDocument {
176    pub pages: Vec<PdfPage>,
177}
178
179/// Whether to use the docling-parse line sanitizer ([`crate::dp_lines`]) for prose
180/// reconstruction — the default. Set `DOCLING_LEGACY_LINES` to fall back to the
181/// older gap-heuristic `lines_from_glyphs`.
182pub(crate) fn use_dp_lines() -> bool {
183    !docling_core::env::flag("DOCLING_LEGACY_LINES")
184}
185
186/// Whether to source **word** cells from the pure-Rust parser (roadmap item 6),
187/// the default. The parser's `word_cells` reproduce docling-parse's word grouping
188/// byte-for-byte — the per-word tokens TableFormer matches table-grid cells
189/// against — which moves table extraction closer to docling on the heavy
190/// multi-column fixtures. Set `DOCLING_PDFIUM_WORDS` to keep pdfium's word cells,
191/// or `DOCLING_PDFIUM_TEXT` to fall back to pdfium for all text.
192pub(crate) fn use_parser_words() -> bool {
193    !docling_core::env::flag("DOCLING_PDFIUM_WORDS")
194        && !docling_core::env::flag("DOCLING_PDFIUM_TEXT")
195}
196
197/// Whether to source **code** cells from the parser too (the default) — the last
198/// text layer to leave pdfium, fully retiring its text path. The parser's
199/// gap-based code grouping ([`code_cells_from_glyphs`]) reconstructs monospace
200/// spacing from positioning gaps (`function add(a, b) { … }`), so it no longer
201/// drops the inter-token spaces the old space-glyph-only grouping lost
202/// (`functionadd`). Reverts to pdfium with `DOCLING_PDFIUM_WORDS` (alongside word
203/// cells) or `DOCLING_PDFIUM_TEXT` (all text).
204pub(crate) fn use_parser_code() -> bool {
205    use_parser_words()
206}
207
208#[cfg(feature = "ml")]
209/// Try binding pdfium from a directory (or a literal library file path):
210/// `<dir>/<platform library name>` first, else `<dir>` itself as the file.
211fn try_bind_dir(path: &str) -> Option<Box<dyn pdfium_render::prelude::PdfiumLibraryBindings>> {
212    let name = Pdfium::pdfium_platform_library_name_at_path(path);
213    if let Ok(b) = Pdfium::bind_to_library(&name) {
214        return Some(b);
215    }
216    Pdfium::bind_to_library(path).ok()
217}
218
219#[cfg(feature = "ml")]
220/// Bind to the pdfium dynamic library. Honors `PDFIUM_DYNAMIC_LIB_PATH` (a
221/// directory or file) first; else falls back to `.pdfium/lib` relative to the
222/// current directory (the layout `scripts/install/download_dependencies.sh` and
223/// `scripts/install/pdf_setup.sh` both produce); else the system library.
224fn bind() -> Result<Pdfium, PdfiumError> {
225    if let Some(path) = docling_core::env::nonempty("PDFIUM_DYNAMIC_LIB_PATH") {
226        if let Some(b) = try_bind_dir(&path) {
227            return Ok(Pdfium::new(b));
228        }
229    }
230    // No env var (or it didn't resolve): fall back to `.pdfium/lib` relative to
231    // the current directory — mirroring `layout.rs`/`ocr.rs`'s `.models/…`
232    // defaults — the layout `scripts/install/download_dependencies.sh` (and
233    // `scripts/install/pdf_setup.sh`) produce, so a checkout with the dependencies
234    // downloaded next to it needs no env var at all.
235    if let Some(b) = try_bind_dir(&crate::resolve_asset(".pdfium/lib")) {
236        return Ok(Pdfium::new(b));
237    }
238    Pdfium::bind_to_system_library().map(Pdfium::new)
239}
240
241#[cfg(feature = "ml")]
242impl PdfDocument {
243    /// Parse a PDF from bytes, optionally decrypting with `password`.
244    ///
245    /// Note: this materialises **every** page's rendered bitmap in memory at
246    /// once. For large documents prefer [`for_each_page`], which streams.
247    pub fn open(bytes: &[u8], password: Option<&str>) -> Result<Self, PdfiumError> {
248        let pdfium = bind()?;
249        let ffi = FfiText::load(pdfium.bindings(), bytes, password);
250        let doc = pdfium.load_pdf_from_byte_slice(bytes, password)?;
251        let mut rust = rust_parser_cells(bytes);
252        let mut pages = Vec::new();
253        for (i, page) in doc.pages().iter().enumerate() {
254            let rc = rust.as_mut().and_then(|v| v.get_mut(i).map(std::mem::take));
255            pages.push(extract_page(&page, &ffi, i as i32, rc, true)?);
256        }
257        Ok(PdfDocument { pages })
258    }
259}
260
261#[cfg(feature = "ml")]
262/// Per-page prose line cells from the pure-Rust text parser. This is the
263/// **default** text layer (it matches docling-parse's char geometry and is a
264/// strict improvement on byte-conformance — e.g. it recovers the Arabic
265/// sentence-period attachment in `right_to_left_01`). Set `DOCLING_PDFIUM_TEXT`
266/// to fall back to pdfium's text layer. The parser returns an empty page when a
267/// PDF (or a page) has no parseable text layer; the caller keeps pdfium's cells
268/// in that case, so scanned/edge-case pages are unaffected.
269fn rust_parser_cells(bytes: &[u8]) -> Option<Vec<crate::textparse::PageParserCells>> {
270    if docling_core::env::flag("DOCLING_PDFIUM_TEXT") {
271        return None;
272    }
273    Some(crate::timing::timed("textparse", || {
274        crate::textparse::pdf_all_cells(bytes)
275    }))
276}
277
278#[cfg(feature = "ml")]
279/// Number of pages in a PDF, without rendering any of them — used to decide
280/// whether a document is worth spinning up the parallel worker pool.
281pub fn page_count(bytes: &[u8], password: Option<&str>) -> Result<usize, PdfiumError> {
282    let pdfium = bind()?;
283    let doc = pdfium.load_pdf_from_byte_slice(bytes, password)?;
284    Ok(doc.pages().len() as usize)
285}
286
287#[cfg(feature = "ml")]
288/// Render + extract pages one at a time, handing each (owned) [`PdfPage`] to `f`.
289/// Only one page bitmap is resident at a time — a rendered page is ~5 MB, so a
290/// large PDF would otherwise hold gigabytes of bitmaps at once. `f` receives the
291/// zero-based page index and the total page count.
292///
293/// `render_image` controls whether the page bitmap is rasterized at all: layout,
294/// OCR, TableFormer, and picture cropping all need it, but a caller that skips
295/// every one of those (the `no_ocr` fast path) doesn't, and rasterizing +
296/// downsampling a page is by far the most expensive step per page — skipping it
297/// is most of `no_ocr`'s speedup. `PdfPage::image` is a 1×1 placeholder when
298/// `false`; do not read it.
299///
300/// `range` restricts the walk to a **0-based inclusive** page window (issue
301/// #80's `--pages`); out-of-window pages are skipped *before* text extraction
302/// and rasterization, so a 3-page window over a 500-page PDF costs three
303/// pages, not five hundred. `f` still receives the absolute page index, so
304/// downstream page numbering refers to the source document.
305///
306/// `E` is the caller's error type; pdfium errors convert into it via `From`.
307pub fn for_each_page<E, F>(
308    bytes: &[u8],
309    password: Option<&str>,
310    render_image: bool,
311    range: Option<(usize, usize)>,
312    mut f: F,
313) -> Result<(), E>
314where
315    E: From<PdfiumError>,
316    F: FnMut(usize, usize, PdfPage) -> Result<(), E>,
317{
318    let pdfium = bind()?;
319    let ffi = FfiText::load(pdfium.bindings(), bytes, password);
320    let doc = pdfium.load_pdf_from_byte_slice(bytes, password)?;
321    let mut rust = rust_parser_cells(bytes);
322    let pages = doc.pages();
323    let total = pages.len() as usize;
324    let (first, last) = range.unwrap_or((0, total.saturating_sub(1)));
325    for (i, page) in pages.iter().enumerate() {
326        if i < first || i > last {
327            continue;
328        }
329        let rc = rust.as_mut().and_then(|v| v.get_mut(i).map(std::mem::take));
330        let extracted = extract_page(&page, &ffi, i as i32, rc, render_image)?;
331        f(i, total, extracted)?;
332    }
333    Ok(())
334}
335
336#[cfg(feature = "ml")]
337fn extract_page(
338    page: &pdfium_render::prelude::PdfPage<'_>,
339    ffi: &FfiText<'_>,
340    index: i32,
341    rust_cells: Option<crate::textparse::PageParserCells>,
342    render_image: bool,
343) -> Result<PdfPage, PdfiumError> {
344    let width = page.width().value;
345    let height = page.height().value;
346
347    // Default: use the pure-Rust text parser instead of pdfium's text layer
348    // (override with `DOCLING_PDFIUM_TEXT`). Prose line cells always come from the
349    // parser; word and code cells do too unless `DOCLING_PDFIUM_WORDS` keeps them
350    // on pdfium (the parser's word grouping reproduces docling-parse's, which
351    // TableFormer matches against — roadmap item 6). A page the parser couldn't
352    // read (no text layer) keeps pdfium's cells.
353    let rc = rust_cells.unwrap_or_default();
354    let need_pdfium_prose = rc.prose.is_empty();
355    let need_pdfium_words = !use_parser_words() || rc.words.is_empty();
356    let need_pdfium_code = !use_parser_code() || rc.code.is_empty();
357
358    // The parser covers prose/words/code from one shared glyph pass, so on the
359    // common (parser-succeeded) page all three are already satisfied and this
360    // pdfium FFI call — otherwise fully discarded below — is skipped outright.
361    let (mut cells, mut code_cells, mut word_cells) =
362        if need_pdfium_prose || need_pdfium_words || need_pdfium_code {
363            let (mut cells, code_cells, word_cells) =
364                crate::timing::timed("ffi.page_cells", || ffi.page_cells(index, height));
365            if cells.is_empty() {
366                cells = segment_cells(&page.text()?, height);
367            }
368            (cells, code_cells, word_cells)
369        } else {
370            (Vec::new(), Vec::new(), Vec::new())
371        };
372    if !rc.prose.is_empty() {
373        cells = rc.prose;
374    }
375    if use_parser_words() && !rc.words.is_empty() {
376        word_cells = rc.words;
377    }
378    if use_parser_code() && !rc.code.is_empty() {
379        code_cells = rc.code;
380    }
381
382    let image = if render_image {
383        // docling renders at 1.5× the target scale and downsamples "to make it
384        // sharper" (pypdfium2 → PIL BICUBIC). Replicate exactly: the TableFormer
385        // model is pixel-sensitive, so the page bitmap must match byte-for-byte.
386        // `CatmullRom` is the same a=-0.5 cubic kernel as PIL's BICUBIC.
387        const SUPERSAMPLE: f32 = 1.5;
388        let tw = (width * RENDER_SCALE * SUPERSAMPLE).round().max(1.0) as i32;
389        let th = (height * RENDER_SCALE * SUPERSAMPLE).round().max(1.0) as i32;
390        let cfg = PdfRenderConfig::new()
391            .set_target_width(tw)
392            .set_target_height(th);
393        let big = crate::timing::timed("pdfium.render", || {
394            page.render_with_config(&cfg)
395                .map(|b| b.as_image().into_rgb8())
396        })?;
397        let dw = (width * RENDER_SCALE).round().max(1.0) as u32;
398        let dh = (height * RENDER_SCALE).round().max(1.0) as u32;
399        crate::timing::timed("image.resize", || fast_downscale(&big, dw, dh))
400    } else {
401        RgbImage::new(1, 1)
402    };
403    // The layout model's input image, built exactly like docling's
404    // `get_page_image(scale=1.0)`: a pdfium render at 1.5× (pypdfium2 sizes
405    // with `ceil`), PIL-BICUBIC down to the point-size image (PIL `resize`'s
406    // default kernel; Python `round` = ties-to-even). Distinct from the 2×
407    // bitmap above — resampling 1224→640 and 612→640 are different regimes,
408    // and the heron model's borderline scores follow the pixels.
409    let image_layout = if render_image {
410        let tw = f64::from(width * 1.5).ceil().max(1.0) as i32;
411        let th = f64::from(height * 1.5).ceil().max(1.0) as i32;
412        let cfg = PdfRenderConfig::new()
413            .set_target_width(tw)
414            .set_target_height(th);
415        let big = crate::timing::timed("pdfium.render_layout", || {
416            page.render_with_config(&cfg)
417                .map(|b| b.as_image().into_rgb8())
418        })?;
419        let dw = f64::from(width).round_ties_even().max(1.0) as u32;
420        let dh = f64::from(height).round_ties_even().max(1.0) as u32;
421        Some(crate::timing::timed("image.resize_layout", || {
422            crate::resample::pil_resize(&big, dw, dh, crate::resample::PilFilter::Bicubic)
423        }))
424    } else {
425        None
426    };
427
428    let links = extract_links(page, height);
429
430    // `/Rotate` normalization for scanned pages: pdfium renders the page as a
431    // viewer displays it — `/Rotate` applied — so a rotated scan hands layout
432    // and OCR a sideways/upside-down raster and the recognition output is
433    // garbage. A page with a text layer needs none of this (its cells carry
434    // the geometry; the models never see its pixels decide text), so the
435    // normalization is gated to pages with no cells at all — exactly the set
436    // the OCR path fires on. The bitmaps are un-rotated to upright (lossless
437    // 90° steps), `width`/`height` swap to the upright box, and the display
438    // rotation is recorded so assembly can rotate the finished geometry back
439    // into display space (docling reports rotated pages in display coords).
440    let rotation = match page.rotation() {
441        Ok(PdfPageRenderRotation::Degrees90) => 90u16,
442        Ok(PdfPageRenderRotation::Degrees180) => 180,
443        Ok(PdfPageRenderRotation::Degrees270) => 270,
444        _ => 0,
445    };
446    let scanned = cells.is_empty() && word_cells.is_empty() && code_cells.is_empty();
447    let mut page = PdfPage {
448        width,
449        height,
450        scale: RENDER_SCALE,
451        image_layout,
452        cells,
453        code_cells,
454        word_cells,
455        image,
456        links,
457        rotation: 0,
458    };
459    if rotation != 0 && scanned && render_image {
460        page.unrotate(rotation);
461    }
462    Ok(page)
463}
464
465#[cfg(feature = "ml")]
466/// The supersample→target downscale via `fast_image_resize` (SIMD convolution;
467/// the same a=-0.5 Catmull-Rom kernel as `image::imageops::resize(...,
468/// CatmullRom)` and PIL BICUBIC — see the render comment above). Set
469/// `DOCLING_RS_SLOW_RESIZE=1` to fall back to the `image`-crate scalar resize
470/// (byte-parity with the pre-SIMD pipeline, several times slower).
471fn fast_downscale(big: &RgbImage, dw: u32, dh: u32) -> RgbImage {
472    use fast_image_resize as fir;
473    static SLOW: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
474    let slow = *SLOW.get_or_init(|| docling_core::env::flag("DOCLING_RS_SLOW_RESIZE"));
475    if !slow {
476        if let Some(out) = (|| {
477            let src = fir::images::ImageRef::new(
478                big.width(),
479                big.height(),
480                big.as_raw(),
481                fir::PixelType::U8x3,
482            )
483            .ok()?;
484            let mut dst = fir::images::Image::new(dw, dh, fir::PixelType::U8x3);
485            fir::Resizer::new()
486                .resize(
487                    &src,
488                    &mut dst,
489                    &fir::ResizeOptions::new()
490                        .resize_alg(fir::ResizeAlg::Convolution(fir::FilterType::CatmullRom)),
491                )
492                .ok()?;
493            RgbImage::from_raw(dw, dh, dst.into_vec())
494        })() {
495            return out;
496        }
497        // Unreachable in practice; fall through to the scalar path on any error.
498    }
499    image::imageops::resize(big, dw, dh, image::imageops::FilterType::CatmullRom)
500}
501
502#[cfg(feature = "ml")]
503/// Collect web/mail/tel hyperlink annotations on a page, mapping each link's
504/// rectangle into top-left page coordinates (like [`TextCell`]). `file://` and
505/// in-document destinations are skipped — only externally meaningful targets are
506/// rendered. pdfium occasionally lists a link twice; rects are kept as-is and the
507/// caller dedupes by resolved anchor text.
508fn extract_links(page: &pdfium_render::prelude::PdfPage<'_>, page_h: f32) -> Vec<LinkAnnot> {
509    let mut out = Vec::new();
510    for link in page.links().iter() {
511        let Some(uri) = link
512            .action()
513            .and_then(|a| a.as_uri_action().and_then(|u| u.uri().ok()))
514        else {
515            continue;
516        };
517        let scheme_ok = ["http://", "https://", "mailto:", "tel:"]
518            .iter()
519            .any(|s| uri.starts_with(s));
520        if !scheme_ok {
521            continue;
522        }
523        if let Ok(rect) = link.rect() {
524            out.push(LinkAnnot {
525                l: rect.left().value,
526                t: page_h - rect.top().value,
527                r: rect.right().value,
528                b: page_h - rect.bottom().value,
529                uri,
530            });
531        }
532    }
533    out
534}
535
536#[cfg(feature = "ml")]
537/// Fallback line cells from pdfium-render's style segments (one cell per
538/// segment). Used only when the raw-FFI text page can't be loaded.
539fn segment_cells(text: &PdfPageText, page_h: f32) -> Vec<TextCell> {
540    text.segments()
541        .iter()
542        .filter_map(|seg| {
543            let s = seg.text();
544            if s.trim().is_empty() {
545                return None;
546            }
547            let r = seg.bounds();
548            Some(TextCell {
549                text: s,
550                l: r.left().value,
551                t: page_h - r.top().value,
552                r: r.right().value,
553                b: page_h - r.bottom().value,
554            })
555        })
556        .collect()
557}
558
559#[cfg(feature = "ml")]
560/// A second, raw-FFI handle on the same PDF used to drive the character loop
561/// (`FPDFText_GetUnicode`/`GetCharBox`) that pdfium-render's safe API doesn't
562/// expose. Closes the document on drop.
563struct FfiText<'a> {
564    bindings: &'a dyn PdfiumLibraryBindings,
565    doc: FPDF_DOCUMENT,
566}
567
568/// One glyph: codepoint + native (y-up) box edges. `l/b/r/t` is pdfium's *tight*
569/// ink box (used by the legacy `lines_from_glyphs`); `ll/lb/lr/lt` is the *loose*
570/// box (font ascent/descent + advance — uniform per font/size), which the
571/// docling-parse-style sanitizer needs so adjacent glyphs share a top edge.
572pub(crate) struct Glyph {
573    pub(crate) ch: char,
574    pub(crate) l: f32,
575    pub(crate) b: f32,
576    pub(crate) r: f32,
577    pub(crate) t: f32,
578    pub(crate) ll: f32,
579    pub(crate) lb: f32,
580    pub(crate) lr: f32,
581    pub(crate) lt: f32,
582    /// Hash of the PDF font name + flags (0 when not fetched). The sanitizer uses
583    /// it for docling-parse's `enforce_same_font` (keeps a bold label and regular
584    /// value as separate line cells, e.g. `LABEL : value`).
585    pub(crate) font: u64,
586}
587
588#[cfg(feature = "ml")]
589impl<'a> FfiText<'a> {
590    fn load(bindings: &'a dyn PdfiumLibraryBindings, bytes: &[u8], password: Option<&str>) -> Self {
591        let doc = bindings.FPDF_LoadMemDocument(bytes, password);
592        FfiText { bindings, doc }
593    }
594
595    /// Reconstruct line cells for page `index` (zero-based) via the
596    /// chars→words→lines grouping. Returns `(prose_cells, code_cells)` — the same
597    /// glyphs grouped two ways (gap-heuristic for prose, space-glyph-only for
598    /// code). Both empty on any failure (caller falls back).
599    fn page_cells(&self, index: i32, page_h: f32) -> (Vec<TextCell>, Vec<TextCell>, Vec<TextCell>) {
600        let empty = || (Vec::new(), Vec::new(), Vec::new());
601        if self.doc.is_null() {
602            return empty();
603        }
604        let b = self.bindings;
605        let page = b.FPDF_LoadPage(self.doc, index);
606        if page.is_null() {
607            return empty();
608        }
609        let tp = b.FPDFText_LoadPage(page);
610        let out = if tp.is_null() {
611            empty()
612        } else {
613            let dp = use_dp_lines();
614            let g = glyphs(b, tp, dp);
615            b.FPDFText_ClosePage(tp);
616            // Prose line cells: the docling-parse-style sanitizer (behind a flag
617            // while it's validated) or the legacy gap-heuristic reconstruction.
618            let prose = if dp {
619                crate::dp_lines::line_cells(&g, page_h, false)
620            } else {
621                lines_from_glyphs(&g, page_h, Grouping::Prose)
622            };
623            (
624                prose,
625                lines_from_glyphs(&g, page_h, Grouping::CodeSpaceOnly),
626                words_from_glyphs(&g, page_h),
627            )
628        };
629        b.FPDF_ClosePage(page);
630        out
631    }
632}
633
634#[cfg(feature = "ml")]
635impl Drop for FfiText<'_> {
636    fn drop(&mut self) {
637        if !self.doc.is_null() {
638            self.bindings.FPDF_CloseDocument(self.doc);
639        }
640    }
641}
642
643#[cfg(feature = "ml")]
644/// Read every glyph (codepoint + native box) from the text page, in document
645/// order. A space glyph is kept as a word-boundary marker (NaN box, char `' '`);
646/// pdfium emits these on most lines and they pin word splits exactly. Hard line
647/// breaks are dropped (line structure comes from geometry); the gap heuristic in
648/// [`lines_from_glyphs`] is the fallback for the lines pdfium leaves space-less.
649/// Debug helper: the raw pdfium glyph stream (codepoint + native bottom-left
650/// box) for a page, in pdfium's character order. For comparing against
651/// docling-parse's char cells.
652pub fn debug_glyphs(bytes: &[u8], index: i32) -> Vec<(char, f32, f32)> {
653    let Ok(pdfium) = bind() else {
654        return Vec::new();
655    };
656    let ffi = FfiText::load(pdfium.bindings(), bytes, None);
657    if ffi.doc.is_null() {
658        return Vec::new();
659    }
660    let b = ffi.bindings;
661    let page = b.FPDF_LoadPage(ffi.doc, index);
662    if page.is_null() {
663        return Vec::new();
664    }
665    let tp = b.FPDFText_LoadPage(page);
666    let mut out = Vec::new();
667    if !tp.is_null() {
668        for g in glyphs(b, tp, true) {
669            out.push((g.ch, g.ll, g.lr));
670        }
671        b.FPDFText_ClosePage(tp);
672    }
673    b.FPDF_ClosePage(page);
674    out
675}
676
677#[cfg(feature = "ml")]
678/// One text object on a page, for the hidden-layer diagnostic.
679#[derive(Debug, Clone)]
680pub struct DebugTextObject {
681    /// True when the object is drawn invisibly (text render mode 3) — the marker of
682    /// a hidden duplicate text layer.
683    pub invisible: bool,
684    /// Bounding box in native PDF points (bottom-left origin).
685    pub l: f32,
686    pub b: f32,
687    pub r: f32,
688    pub t: f32,
689    /// The object's text (best-effort; empty if it could not be read).
690    pub text: String,
691}
692
693#[cfg(feature = "ml")]
694/// Diagnostic: every text object on page `index`, each tagged visible/invisible
695/// (via the object-level [`FPDFTextObj_GetTextRenderMode`], which — unlike the
696/// per-character render-mode API — is available on the default pdfium binding).
697/// A hidden duplicate text layer shows up as invisible objects repeating the
698/// visible text. Used by the `dump_render_modes` example.
699///
700/// [`FPDFTextObj_GetTextRenderMode`]: pdfium_render::prelude::PdfiumLibraryBindings::FPDFTextObj_GetTextRenderMode
701pub fn debug_text_objects(bytes: &[u8], index: i32) -> Vec<DebugTextObject> {
702    let Ok(pdfium) = bind() else {
703        return Vec::new();
704    };
705    let ffi = FfiText::load(pdfium.bindings(), bytes, None);
706    if ffi.doc.is_null() {
707        return Vec::new();
708    }
709    let b = ffi.bindings;
710    let page = b.FPDF_LoadPage(ffi.doc, index);
711    if page.is_null() {
712        return Vec::new();
713    }
714    let tp = b.FPDFText_LoadPage(page);
715    let mut out = Vec::new();
716    let n = b.FPDFPage_CountObjects(page);
717    for i in 0..n {
718        let obj = b.FPDFPage_GetObject(page, i);
719        if obj.is_null() || b.FPDFPageObj_GetType(obj) != FPDF_PAGEOBJ_TEXT as i32 {
720            continue;
721        }
722        let (mut l, mut bot, mut r, mut top) = (0f32, 0f32, 0f32, 0f32);
723        if b.FPDFPageObj_GetBounds(obj, &mut l, &mut bot, &mut r, &mut top) == 0 {
724            continue;
725        }
726        let invisible = b.FPDFTextObj_GetTextRenderMode(obj) == INVISIBLE_RENDER_MODE;
727        let text = if tp.is_null() {
728            String::new()
729        } else {
730            // FPDFTextObj_GetText returns the count of UTF-16 code units, including
731            // the trailing NUL; call once for the size, once to fill.
732            let need = b.FPDFTextObj_GetText(obj, tp, std::ptr::null_mut(), 0);
733            if need <= 1 {
734                String::new()
735            } else {
736                let mut buf = vec![0u16; need as usize];
737                b.FPDFTextObj_GetText(obj, tp, buf.as_mut_ptr(), need);
738                if let Some(&0) = buf.last() {
739                    buf.pop();
740                }
741                String::from_utf16_lossy(&buf)
742            }
743        };
744        out.push(DebugTextObject {
745            invisible,
746            l,
747            b: bot,
748            r,
749            t: top,
750            text,
751        });
752    }
753    if !tp.is_null() {
754        b.FPDFText_ClosePage(tp);
755    }
756    b.FPDF_ClosePage(page);
757    out
758}
759
760#[cfg(feature = "ml")]
761/// Hash a glyph's PDF font name + flags, for `enforce_same_font`. 0 if unavailable.
762fn font_hash(b: &dyn PdfiumLibraryBindings, tp: FPDF_TEXTPAGE, i: i32) -> u64 {
763    use std::hash::{Hash, Hasher};
764    let mut flags: std::os::raw::c_int = 0;
765    let len = b.FPDFText_GetFontInfo(tp, i, std::ptr::null_mut(), 0, &mut flags);
766    if len == 0 {
767        return 0;
768    }
769    let mut buf = vec![0u8; len as usize];
770    b.FPDFText_GetFontInfo(
771        tp,
772        i,
773        buf.as_mut_ptr() as *mut std::os::raw::c_void,
774        len,
775        &mut flags,
776    );
777    let mut h = std::collections::hash_map::DefaultHasher::new();
778    buf.hash(&mut h);
779    flags.hash(&mut h);
780    h.finish()
781}
782
783#[cfg(feature = "ml")]
784/// pdfium text render mode 3: the glyph is drawn with neither fill nor stroke —
785/// an invisible glyph. Web-to-PDF exporters put a hidden plain-text copy of
786/// syntax-highlighted code (and other "copy"/accessibility layers) in this mode,
787/// which the char-level text API then extracts as a duplicate of the visible text.
788const INVISIBLE_RENDER_MODE: i32 = 3;
789
790#[cfg(feature = "ml")]
791fn glyphs(b: &dyn PdfiumLibraryBindings, tp: FPDF_TEXTPAGE, fetch_font: bool) -> Vec<Glyph> {
792    let n = b.FPDFText_CountChars(tp);
793    let mut out = Vec::with_capacity(n.max(0) as usize);
794    for i in 0..n {
795        let ch = match char::from_u32(b.FPDFText_GetUnicode(tp, i)) {
796            Some(c) => c,
797            None => continue,
798        };
799        if ch == '\r' || ch == '\n' {
800            continue;
801        }
802        // Spaces are font-neutral (0): pdfium's generated spaces carry a default
803        // font that would otherwise block every word↔space merge under
804        // enforce_same_font; docling-parse's spaces inherit the run's font.
805        let font = if fetch_font && !ch.is_whitespace() {
806            font_hash(b, tp, i)
807        } else {
808            0
809        };
810        let (mut l, mut r, mut bot, mut top) = (0f64, 0f64, 0f64, 0f64);
811        let has_box = b.FPDFText_GetCharBox(tp, i, &mut l, &mut r, &mut bot, &mut top) != 0;
812        // Loose box: font ascent/descent + glyph advance, uniform per font/size.
813        let mut lr = FS_RECTF {
814            left: 0.0,
815            top: 0.0,
816            right: 0.0,
817            bottom: 0.0,
818        };
819        let (ll, lb, lrt, ltop) = if b.FPDFText_GetLooseCharBox(tp, i, &mut lr) != 0 {
820            (lr.left, lr.bottom, lr.right, lr.top)
821        } else if has_box {
822            (l as f32, bot as f32, r as f32, top as f32)
823        } else {
824            (f32::NAN, 0.0, 0.0, 0.0)
825        };
826        if ch.is_whitespace() {
827            // Keep the space *with its box* (the docling-parse-style line sanitizer
828            // needs literal space glyphs); NaN `l` if pdfium reports no box (the
829            // legacy `lines_from_glyphs` ignores the box and only flags a space).
830            out.push(Glyph {
831                ch: ' ',
832                l: if has_box { l as f32 } else { f32::NAN },
833                b: if has_box { bot as f32 } else { 0.0 },
834                r: if has_box { r as f32 } else { 0.0 },
835                t: if has_box { top as f32 } else { 0.0 },
836                ll,
837                lb,
838                lr: lrt,
839                lt: ltop,
840                font,
841            });
842            continue;
843        }
844        if !has_box {
845            continue;
846        }
847        out.push(Glyph {
848            ch,
849            l: l as f32,
850            b: bot as f32,
851            r: r as f32,
852            t: top as f32,
853            ll,
854            lb,
855            lr: lrt,
856            lt: ltop,
857            font,
858        });
859    }
860    // pdfium splits the Arabic lam-alef ligature into two chars at the *same* x
861    // (it's one glyph) in visual order — `alef-variant, lam`. docling-parse and
862    // logical order are `lam, alef-variant`. Detect the ligature by the shared x
863    // and swap. The shared-x test reliably distinguishes a true ligature from a
864    // genuine `alef + lam` sequence (the article `ال`, or `فعالة`), whose two
865    // glyphs sit at different x and must NOT be reordered.
866    for i in 0..out.len().saturating_sub(1) {
867        let same_x = out[i].l.is_finite()
868            && out[i + 1].l.is_finite()
869            && (out[i].l - out[i + 1].l).abs() < 1.0;
870        if same_x
871            && matches!(out[i].ch, '\u{0622}' | '\u{0623}' | '\u{0625}' | '\u{0627}')
872            && out[i + 1].ch == '\u{0644}'
873        {
874            out.swap(i, i + 1);
875        }
876    }
877    // Reconstruct degenerate (zero-width) loose space boxes by spanning the gap to
878    // the next glyph on the same line, so the sanitizer keeps them as word
879    // separators rather than dropping them (which would merge `Information systems`
880    // → `Informationsystems`). pdfium gives generated spaces a zero-width box at a
881    // wrong baseline; a wrap (different baseline) or a touching gap is left alone.
882    for i in 0..out.len() {
883        if out[i].ch != ' ' || (out[i].lr - out[i].ll).abs() >= 0.5 {
884            continue;
885        }
886        let prev = out[..i]
887            .iter()
888            .rev()
889            .find(|g| g.ch != ' ' && g.ll.is_finite())
890            .map(|g| (g.lr, g.lb, g.lt));
891        let next = out[i + 1..]
892            .iter()
893            .find(|g| g.ch != ' ' && g.ll.is_finite())
894            .map(|g| (g.ll, g.lb));
895        if let (Some((plr, plb, plt)), Some((nll, nlb))) = (prev, next) {
896            let line_h = (plt - plb).abs().max(1.0);
897            if (plb - nlb).abs() < line_h * 0.5 && nll > plr + 0.5 {
898                out[i].ll = plr;
899                out[i].lr = nll;
900                out[i].lb = plb;
901                out[i].lt = plt;
902            }
903        }
904    }
905    out
906}
907
908/// How [`lines_from_glyphs`] splits a line into words.
909#[derive(Clone, Copy, PartialEq)]
910enum Grouping {
911    /// Gap heuristic + punctuation glue (`engines,`, `[37`, `98.5`) — prose.
912    Prose,
913    /// Split only at literal space glyphs, never glue — pdfium code cells.
914    /// pdfium's monospace listings carry a real space glyph at every source space,
915    /// and its overhanging loose boxes would make the gap heuristic over-split
916    /// (`f un c t i o n`), so honouring just the spaces reproduces the spacing.
917    CodeSpaceOnly,
918    /// Split on the inter-glyph **gap** (or a space glyph), but never glue — for
919    /// the parser's code cells: the parser emits no space glyphs (a source space
920    /// is a positioning gap), and its clean advance boxes make the gap reliable.
921    /// Unlike [`Grouping::Prose`] there is no punctuation glue, so a real gap
922    /// always splits (`et al. 2000`, not `et al.2000`) while genuinely touching
923    /// tokens stay joined (`add(a,` / `b)`).
924    CodeGap,
925}
926
927/// Group glyphs (document order) into words then lines, the way docling-parse
928/// does: a new **word** starts where the horizontal gap to the previous glyph
929/// exceeds ~0.2 × the font height (a real space is ~0.3 × height; letter
930/// tracking is smaller, so titles don't shatter); a new **line** starts where
931/// the baseline drops by ~half the font height (a superscript rises without
932/// dropping, so it stays on its line). Coordinates are flipped to top-left.
933/// See [`Grouping`] for how each mode decides word boundaries.
934fn lines_from_glyphs(gs: &[Glyph], page_h: f32, mode: Grouping) -> Vec<TextCell> {
935    let mut cells: Vec<TextCell> = Vec::new();
936    let mut words: Vec<String> = Vec::new(); // words on the current line
937    let mut word = String::new();
938    // current line bounding box, native
939    let (mut ll, mut lb, mut lr, mut lt) = (
940        f32::INFINITY,
941        f32::INFINITY,
942        f32::NEG_INFINITY,
943        f32::NEG_INFINITY,
944    );
945    // Tallest glyph seen on the current line: the word-gap threshold is relative
946    // to it, so a small-font run on the line (a superscript citation) isn't split
947    // at its tight digit gaps, while a big display title isn't split at its wider
948    // letter tracking. A real inter-word space is ~0.3× the font height.
949    let mut line_h: f32 = 0.0;
950    let mut prev: Option<&Glyph> = None;
951    // A space glyph between non-space glyphs pins a word split the gap heuristic
952    // can miss (tight justified spacing); it carries no geometry.
953    let mut pending_space = false;
954
955    for g in gs {
956        if g.ch == ' ' {
957            pending_space = true;
958            continue;
959        }
960        let h = (g.t - g.b).abs().max(1.0);
961        let (mut new_word, mut new_line) = (false, false);
962        if let Some(p) = prev {
963            // A new line drops the baseline *and* resets x leftward; requiring the
964            // x-reset avoids a descending comma/semicolon faking a line break. A
965            // *large* drop (≥1.5× the line height — a skipped line, e.g. a centered
966            // page-number footer below a short last word) is always a new line,
967            // even without the x-reset.
968            // LTR wraps reset x leftward (`g.l < p.r`); RTL (Arabic) wraps reset
969            // rightward (the new line begins at the far right). A large drop
970            // (≥1.5× line height) is a new line regardless of x.
971            let x_reset = if is_arabic(g.ch) || is_arabic(p.ch) {
972                g.l > p.r
973            } else {
974                g.l < p.r
975            };
976            new_line = (p.b - g.b > h * 0.5 && x_reset) || (p.b - g.b > line_h.max(h) * 1.5);
977            // Don't split before closing punctuation, after opening punctuation, or
978            // after a period that runs into a digit/lowercase letter — docling
979            // keeps `engines,` / `[37` / `i.e.` / `98.5` together even across a
980            // space or gap.
981            let glued = is_close_punct(g.ch)
982                || is_open_punct(p.ch)
983                || (p.ch.is_ascii_digit() && g.ch.is_ascii_digit())
984                || (p.ch == '.'
985                    && !pending_space
986                    && (g.ch.is_ascii_digit() || g.ch.is_ascii_lowercase()));
987            let word_gap = line_h.max(h) * 0.25;
988            new_word = if mode == Grouping::CodeSpaceOnly {
989                new_line || pending_space
990            } else if mode == Grouping::CodeGap {
991                // Gap-based, no glue: a real gap always splits, touching tokens join.
992                new_line || pending_space || g.l - p.r > word_gap
993            } else if is_arabic(g.ch) || is_arabic(p.ch) {
994                // RTL runs right-to-left, so the inter-word gap is `p.l - g.r`. A
995                // real word space has a gap; pdfium also emits spurious zero-gap
996                // space glyphs inside words (`التي`), so require the gap rather
997                // than trusting a bare space glyph.
998                new_line || (p.l - g.r > word_gap && !glued)
999            } else {
1000                new_line || ((pending_space || g.l - p.r > word_gap) && !glued)
1001            };
1002        }
1003        pending_space = false;
1004        if new_line {
1005            push_word(&mut word, &mut words);
1006            push_line(&mut words, (ll, lb, lr, lt), page_h, &mut cells);
1007            (ll, lb, lr, lt) = (
1008                f32::INFINITY,
1009                f32::INFINITY,
1010                f32::NEG_INFINITY,
1011                f32::NEG_INFINITY,
1012            );
1013            line_h = 0.0;
1014        } else if new_word {
1015            push_word(&mut word, &mut words);
1016        }
1017        word.push(g.ch);
1018        ll = ll.min(g.l);
1019        lb = lb.min(g.b);
1020        lr = lr.max(g.r);
1021        lt = lt.max(g.t);
1022        line_h = line_h.max(h);
1023        prev = Some(g);
1024    }
1025    push_word(&mut word, &mut words);
1026    push_line(&mut words, (ll, lb, lr, lt), page_h, &mut cells);
1027    cells
1028}
1029
1030/// Code line cells from the **parser**'s glyph stream. Unlike pdfium — whose
1031/// monospace listings carry explicit space glyphs (so [`Grouping::CodeSpaceOnly`]
1032/// keeps their spacing) — the parser emits no space glyphs: a source space is a
1033/// positioning gap. So code cells use [`Grouping::CodeGap`], which splits on the
1034/// inter-glyph gap (a space wherever it exceeds ~0.25× the line height) but never
1035/// glues punctuation, so `et al. 2000` keeps its space while `add(a,` / `b)` stay
1036/// joined. The parser's clean advance boxes make the gap heuristic reliable here,
1037/// where pdfium's overhanging loose boxes would over-split (`f un c t i o n`).
1038pub(crate) fn code_cells_from_glyphs(gs: &[Glyph], page_h: f32) -> Vec<TextCell> {
1039    lines_from_glyphs(gs, page_h, Grouping::CodeGap)
1040}
1041
1042/// Per-word cells (each word's text + top-left bbox), using the same word/line
1043/// splitting as [`lines_from_glyphs`] but emitting one cell per word instead of
1044/// joining into lines — the legacy gap-heuristic word grouping, kept for the
1045/// pdfium word path (`DOCLING_PDFIUM_WORDS`). The default parser path uses
1046/// [`crate::dp_lines::word_cells`] instead.
1047pub(crate) fn words_from_glyphs(gs: &[Glyph], page_h: f32) -> Vec<TextCell> {
1048    let mut cells = Vec::new();
1049    let mut word = String::new();
1050    let inf = (
1051        f32::INFINITY,
1052        f32::INFINITY,
1053        f32::NEG_INFINITY,
1054        f32::NEG_INFINITY,
1055    );
1056    let (mut wl, mut wb, mut wr, mut wt) = inf;
1057    let mut line_h: f32 = 0.0;
1058    let mut prev: Option<&Glyph> = None;
1059    let mut pending_space = false;
1060    for g in gs {
1061        if g.ch == ' ' {
1062            pending_space = true;
1063            continue;
1064        }
1065        let h = (g.t - g.b).abs().max(1.0);
1066        let mut new_line = false;
1067        let mut new_word = false;
1068        if let Some(p) = prev {
1069            // LTR wraps reset x leftward (`g.l < p.r`); RTL (Arabic) wraps reset
1070            // rightward (the new line begins at the far right). A large drop
1071            // (≥1.5× line height) is a new line regardless of x.
1072            let x_reset = if is_arabic(g.ch) || is_arabic(p.ch) {
1073                g.l > p.r
1074            } else {
1075                g.l < p.r
1076            };
1077            new_line = (p.b - g.b > h * 0.5 && x_reset) || (p.b - g.b > line_h.max(h) * 1.5);
1078            // No digit-digit glue here (unlike the prose grouping): table cells in
1079            // adjacent columns are numeric and a column gap must still split them
1080            // (`0.965` `0.934`, not `0.9650.934`). Intra-number digits have no gap
1081            // so they stay together regardless.
1082            let glued = is_close_punct(g.ch)
1083                || is_open_punct(p.ch)
1084                || (p.ch == '.'
1085                    && !pending_space
1086                    && (g.ch.is_ascii_digit() || g.ch.is_ascii_lowercase()));
1087            let word_gap = line_h.max(h) * 0.25;
1088            new_word = new_line || ((pending_space || g.l - p.r > word_gap) && !glued);
1089        }
1090        pending_space = false;
1091        if new_word && !word.is_empty() {
1092            cells.push(TextCell {
1093                text: std::mem::take(&mut word),
1094                l: wl,
1095                t: page_h - wt,
1096                r: wr,
1097                b: page_h - wb,
1098            });
1099            (wl, wb, wr, wt) = inf;
1100        }
1101        if new_line {
1102            line_h = 0.0;
1103        }
1104        word.push(g.ch);
1105        wl = wl.min(g.l);
1106        wb = wb.min(g.b);
1107        wr = wr.max(g.r);
1108        wt = wt.max(g.t);
1109        line_h = line_h.max(h);
1110        prev = Some(g);
1111    }
1112    if !word.is_empty() {
1113        cells.push(TextCell {
1114            text: word,
1115            l: wl,
1116            t: page_h - wt,
1117            r: wr,
1118            b: page_h - wb,
1119        });
1120    }
1121    cells
1122}
1123
1124fn is_arabic(c: char) -> bool {
1125    ('\u{0600}'..='\u{06FF}').contains(&c)
1126}
1127
1128fn is_close_punct(c: char) -> bool {
1129    matches!(
1130        c,
1131        ',' | '.' | ';' | '!' | '?' | ')' | ']' | '}' | '%' | '\'' | '\u{2019}' | '\u{2018}'
1132    )
1133}
1134
1135fn is_open_punct(c: char) -> bool {
1136    // `@` glues to what follows (`mAP @0.5`, `bpf@zurich`, `@decorator`).
1137    matches!(c, '(' | '[' | '{' | '@')
1138}
1139
1140fn push_word(word: &mut String, words: &mut Vec<String>) {
1141    if !word.is_empty() {
1142        words.push(std::mem::take(word));
1143    }
1144}
1145
1146fn push_line(
1147    words: &mut Vec<String>,
1148    bbox: (f32, f32, f32, f32),
1149    page_h: f32,
1150    cells: &mut Vec<TextCell>,
1151) {
1152    if words.is_empty() {
1153        return;
1154    }
1155    let text = std::mem::take(words).join(" ");
1156    let (l, b, r, t) = bbox;
1157    cells.push(TextCell {
1158        text,
1159        l,
1160        t: page_h - t,
1161        r,
1162        b: page_h - b,
1163    });
1164}