rustyfi-backend 0.1.1

Box/glue model, typesetting context, line and page breaking for SATySFi
Documentation
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
use crate::font::FontKey;
use crate::graphics::{Color, GraphicsElem};
use crate::length::Length;
use crate::math::MathGlyph;
use crate::tabular::TabularBox;
use crate::vbox::VertBox;

/// Which font/size a string box is set in (`horz_string_info`).
#[derive(Clone, Debug, PartialEq)]
pub struct HorzStringInfo {
    pub font: FontKey,
    pub size: Length,
    /// A manual baseline raise (`ScriptFont::rising` scaled by the
    /// run's font size — `fontInfo.ml`'s `get_font_with_ratio`). Both PDF
    /// writers add it to the placed `ty` before `Tj`.
    pub rising: Length,
    /// `set-text-color`'s value at the time this run/glyph was built
    /// (`Context::text_color`). `Color::Gray(0.0)` (black) is the default and
    /// both writers emit NO color op for a black run.
    pub color: Color,
}

/// An index into `DocumentValue::images` (rustyfi-lang). Boxes carry this
/// rather than the decoded bytes, so cloning a box (routine during line
/// breaking) never copies image data.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct ImageId(pub usize);

/// An opaque index into a lang-side table of deferred page-break-hook
/// closures (`Interp::hooks`). `break_pages` places the box this token lives
/// in like any other content and never learns what the hook computes; a
/// lang-side post-pass (`fire_hooks`) reads the token back once geometry is
/// final. `DecoId`/`GraphicsFnId` below follow the same pattern.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct HookId(pub usize);

/// Deferred *decoration* closures (`Interp::decos`) for frames.
/// `fire_hooks` fires one with the frame's placed `(x, y, w, h, d)` and
/// accumulates the returned graphics onto the page.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct DecoId(pub usize);

/// Deferred `inline-graphics-outer` callbacks (`Interp::outer_graphics`),
/// read back by `resolve_outer_graphics_*` once line layout has resolved the
/// box's width.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct GraphicsFnId(pub usize);

/// A decoded raster image, referenced via its `ImageId`. Mirrors v0.0.6's
/// `ImageInfo` (`imageInfo.ml`).
///
/// Every source format is flattened to 8-bit `DeviceRGB` and any alpha
/// channel is dropped; transparency (`/SMask`) is unimplemented. `jpeg_dct`
/// additionally carries the source's original, still-DCT-encoded bytes for a
/// baseline JPEG, so `write_image_xobjects` can embed those directly instead
/// of re-encoding the flattened RGB8 samples.
#[derive(Clone, Debug, PartialEq)]
pub struct ImageResource {
    /// Row-major, top-to-bottom, 3-bytes-per-pixel RGB8 samples with no
    /// padding — exactly what `pdf_writer::Chunk::image_xobject` wants for a
    /// `DeviceRGB` image at `bits_per_component(8)`.
    pub samples: Vec<u8>,
    pub px_w: u32,
    pub px_h: u32,
    /// `Some` for a baseline (or extended-sequential) 8-bit JPEG with 1 or 3
    /// color components — see `sniff_baseline_jpeg_dct` for exactly which
    /// qualify. `None` for every non-JPEG source, and for a JPEG this port
    /// cannot map to a PDF colorspace without guessing (progressive, 12-bit,
    /// or 4-component CMYK/YCCK).
    pub jpeg_dct: Option<JpegDct>,
    /// `Some` when this resource is an imported page of an external PDF
    /// (`load-pdf-image`) rather than a decoded raster image;
    /// `samples`/`px_w`/`px_h` are then left empty, and PDF-page consumers
    /// branch on this field instead.
    pub pdf: Option<PdfPageResource>,
}

/// An embedded page of an external PDF (`load-pdf-image`), carrying just
/// enough of the source page's object graph to re-emit it as a PDF **Form
/// XObject**. Deliberately `lopdf`-free plain data so `rustyfi-backend` need
/// not depend on `lopdf`.
#[derive(Clone, Debug, PartialEq)]
pub struct PdfPageResource {
    /// The source page's `/MediaBox`, `(x0, y0, x1, y1)` in raw PDF points
    /// (upstream `loadPdf.ml`: MediaBox only, no `/CropBox` fallback).
    pub media_box: (f64, f64, f64, f64),
    /// The page's content stream(s), already inflated (`/FlateDecode`
    /// resolved) and concatenated (with a separating space per PDF rules
    /// when a page has more than one content stream) — ready to wrap
    /// verbatim in a Form XObject's stream body.
    pub content: Vec<u8>,
    /// The imported object subtree reachable from the page's `/Resources`,
    /// self-contained and keyed by source object number so the writer can
    /// remap references to freshly allocated output `Ref`s. Local id `0` is
    /// reserved (PDF object number 0 is always free/unused in a well-formed
    /// file) and holds the page's own `/Resources` dictionary itself
    /// (whether it was a direct or an indirect object in the source); every
    /// other entry is a real source object number.
    pub resources: ImportedObjects,
}

/// A serialized subtree of a *foreign* PDF's object graph. See
/// `PdfPageResource::resources` for the local-id convention.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ImportedObjects(pub Vec<(u32, ObjRepr)>);

/// A minimal sum type mirroring the PDF object grammar, just enough to
/// re-emit an imported object verbatim. `Ref(u32)` refers to another entry's
/// local id in the same `ImportedObjects` table; the writer treats an
/// unresolved `Ref` as an importer bug rather than fetching it.
#[derive(Clone, Debug, PartialEq)]
pub enum ObjRepr {
    Null,
    Bool(bool),
    Int(i64),
    Real(f64),
    /// A PDF name's raw bytes, without the leading `/` and with `#xx`
    /// escapes already decoded (mirrors `lopdf::Object::Name`).
    Name(Vec<u8>),
    /// A PDF string's raw bytes (mirrors `lopdf::Object::String`, literal or
    /// hex — both collapse to bytes here since we only ever re-emit them).
    String(Vec<u8>),
    Ref(u32),
    Array(Vec<ObjRepr>),
    Dict(Vec<(Vec<u8>, ObjRepr)>),
    /// A stream object: its dictionary entries (excluding `/Length`, which
    /// the writer derives) plus already-decompressed content bytes. The
    /// writer decides filtering/compression at write time; the imported
    /// content is kept in cleartext form here so no `lopdf`-specific codec
    /// state needs to cross the boundary.
    Stream(Vec<(Vec<u8>, ObjRepr)>, Vec<u8>),
}

/// The original, still-DCT-encoded bytes of a source JPEG, plus enough
/// metadata (`components`) for the writer to pick the matching
/// `/ColorSpace`. Never re-derived from the flattened `samples`, which have
/// already lost the JPEG's own subsampling/quantization.
#[derive(Clone, Debug, PartialEq)]
pub struct JpegDct {
    /// The complete original file contents, `FFD8` (SOI) to `FFD9` (EOI),
    /// byte-for-byte — exactly the stream a `/Filter /DCTDecode` XObject wants.
    pub bytes: Vec<u8>,
    /// Color components from the JPEG's SOF marker: `1` (grayscale ->
    /// `/DeviceGray`) or `3` (YCbCr/RGB -> `/DeviceRGB`).
    /// `sniff_baseline_jpeg_dct` never returns any other value.
    pub components: u8,
}

impl ImageResource {
    /// Scan raw file bytes for a JPEG **SOF0** (baseline DCT) or **SOF1**
    /// (extended sequential DCT) marker — the two variants a `/DCTDecode`
    /// XObject can safely wrap verbatim, matching upstream's own JPEG
    /// special-case (`imageInfo.ml`'s bypass of decode/re-encode for `Jpeg`).
    /// Returns `None`, meaning "fall back to the flattened RGB8 embedding",
    /// for:
    ///
    /// - anything that isn't a JPEG (no `FFD8` SOI marker);
    /// - a malformed/truncated JPEG (a segment length running past the end of
    ///   the buffer, or scan data reached before any SOF marker);
    /// - progressive, lossless, arithmetic-coded, or hierarchical JPEGs (any
    ///   SOF other than `0xC0`/`0xC1`) — viewer `DCTDecode` support for these
    ///   is inconsistent, so only the two universally-supported variants are
    ///   trusted;
    /// - non-8-bit sample precision;
    /// - anything other than 1 or 3 color components — in particular
    ///   4-component CMYK/YCCK, whose correct embedding depends on an Adobe
    ///   APP14 transform flag (some store inverted samples) this port does not
    ///   interpret.
    ///
    /// `bytes` is consumed so the `Some` case hands the file contents into
    /// `JpegDct` with no copy.
    pub fn sniff_baseline_jpeg_dct(bytes: Vec<u8>) -> Option<JpegDct> {
        if bytes.len() < 4 || bytes[0] != 0xFF || bytes[1] != 0xD8 {
            return None; // no SOI marker: not a JPEG.
        }
        let mut i = 2usize;
        while i < bytes.len() {
            if bytes[i] != 0xFF {
                return None; // not aligned on a marker; bail rather than guess.
            }
            // Marker codes may be preceded by any number of 0xFF fill bytes.
            let mut j = i + 1;
            while j < bytes.len() && bytes[j] == 0xFF {
                j += 1;
            }
            if j >= bytes.len() {
                return None;
            }
            let marker = bytes[j];
            i = j + 1;
            // Standalone markers carry no length-prefixed segment: SOI
            // (stray, shouldn't recur but is harmless), EOI, TEM, RSTn.
            if marker == 0xD8 || marker == 0xD9 || marker == 0x01 || (0xD0..=0xD7).contains(&marker)
            {
                continue;
            }
            if i + 2 > bytes.len() {
                return None;
            }
            let seg_len = u16::from_be_bytes([bytes[i], bytes[i + 1]]) as usize;
            if seg_len < 2 || i + seg_len > bytes.len() {
                return None;
            }
            if marker == 0xDA {
                return None; // start-of-scan reached before any SOF: bail.
            }
            // SOF0..SOF15 (0xC0..0xCF) except 0xC4 (DHT), 0xC8 (JPG
            // extension, reserved), 0xCC (DAC) — those codes overlap the
            // SOF range but aren't frame headers.
            let is_sof = (0xC0..=0xCF).contains(&marker) && ![0xC4, 0xC8, 0xCC].contains(&marker);
            if is_sof {
                if marker != 0xC0 && marker != 0xC1 {
                    return None; // progressive/lossless/hierarchical: bail.
                }
                // Segment payload after the 2-byte length: precision(1),
                // height(2 BE), width(2 BE), num_components(1).
                let payload = &bytes[i + 2..i + seg_len];
                if payload.len() < 6 {
                    return None;
                }
                let precision = payload[0];
                let components = payload[5];
                return if precision == 8 && (components == 1 || components == 3) {
                    Some(JpegDct { bytes, components })
                } else {
                    None
                };
            }
            i += seg_len;
        }
        None
    }

    /// Intrinsic dimensions for aspect-ratio math (`use-image-by-width`):
    /// pixel extents for a raster resource, MediaBox point extents for an
    /// imported PDF page. Both ratios are dimensionless (px/px or pt/pt), so
    /// callers apply the same `height = width * ih/iw` regardless of kind —
    /// only the placement CTM needs to know which units these are.
    pub fn intrinsic_dims_pt(&self) -> (f64, f64) {
        if let Some(pdf) = &self.pdf {
            let (x0, y0, x1, y1) = pdf.media_box;
            (x1 - x0, y1 - y0)
        } else {
            (self.px_w as f64, self.px_h as f64)
        }
    }
}

/// A milestone-1 subset of `pure_horz_box` from horzBox.ml, keeping its
/// vocabulary so the full port extends rather than replaces it.
///
/// The `#[subast]` list names every *other* box type reachable from a field
/// of this enum; self-recursion (`Discretionary`, `Frame`) is implicit. It is
/// what [`crate::visit`]'s generated traversal descends through, and it is
/// **unchecked on stable Rust** — see that module's "The one trap" note and
/// the `tests/visit_reachability.rs` test standing in for the missing check.
#[derive(Clone, Debug, PartialEq, syan::visit::Ast)]
#[subast(
    crate::hbox::PureHorzBox,
    crate::vbox::VertBox,
    crate::graphics::GraphicsElem,
    crate::tabular::TabularBox
)]
pub enum PureHorzBox {
    /// Fixed text with pre-measured dimensions.
    InnerString {
        info: HorzStringInfo,
        text: String,
        width: Length,
        height: Length,
        depth: Length,
    },
    /// Interword glue.
    OuterEmpty {
        natural: Length,
        shrinkable: Length,
        stretchable: Length,
    },
    /// Infinitely stretchable glue (`inline-fil`).
    OuterFil,
    /// A fixed-width empty box with no stretch/shrink (`inline-skip`;
    /// v0.0.6: `PHSFixedEmpty`). Unlike `OuterEmpty` this is never a legal
    /// line-break point (see `is_glue`).
    FixedEmpty { width: Length },
    /// A raster image placed at a fixed on-page size (`use-image-by-width`).
    /// `width`/`height` are already-computed on-page dimensions (v0.0.6
    /// `ImageInfo.get_height_from_width`). Like `FixedEmpty`, never a legal
    /// line-break point (`is_glue`).
    Image {
        width: Length,
        height: Length,
        image: ImageId,
    },
    /// A break point that may or may not be taken (v0.0.6's
    /// `LBDiscretionary(penalty, id, pre, post_nobreak, post_break)`,
    /// `ref:src/backend/lineBreakBox.ml:22-27`). If the paragraph breaker
    /// chooses to break here, `pre_break` renders at the end of the closed
    /// line and `post_break` at the start of the next; otherwise `no_break`
    /// renders in its place. UAX#14 only needs zero-width inter-chunk
    /// break points with all three slots empty. Unlike `OuterEmpty`/`OuterFil`
    /// this is not "glue" (see `is_glue`) — it is scored separately via
    /// `is_break_point`/`break_penalty`.
    Discretionary {
        penalty: i32,
        pre_break: Vec<PureHorzBox>,
        post_break: Vec<PureHorzBox>,
        no_break: Vec<PureHorzBox>,
    },
    /// A box carrying resolved `graphics` elements (`inline-graphics`;
    /// v0.0.6: `PHGFixedGraphics`), coordinates already relative to the
    /// box's baseline-left origin. Carries a real depth (graphics can extend
    /// below the baseline), so both `height` and `depth` feed line metrics.
    /// Never a legal line-break point (see `is_glue`).
    Graphics {
        width: Length,
        height: Length,
        depth: Length,
        elems: Vec<GraphicsElem>,
        /// True when the callback ignored its placed-point argument, so its
        /// `elems` are PAGE-ABSOLUTE (e.g. a slydifi frame background /
        /// full-page decoration built with `fun _ -> …`). Such graphics must
        /// be emitted with an IDENTITY `cm` — NOT translated by the box's
        /// placed position — otherwise the whole decoration shifts off the
        /// page (the box is often placed at a negative text-origin). For an
        /// ordinary position-relative callback this is false and the writer's
        /// per-box `cm` translate applies as usual.
        origin_independent: bool,
    },
    /// `inline-graphics-outer` (v0.0.6 `PHGOuterFilGraphics`,
    /// vminst.ml:1891): a graphics box whose WIDTH stretches like
    /// `inline-fil` (upstream widinfo `{natural = 0; stretchable = Fils(1)}`,
    /// lineBreak.ml:40-48). `width` starts at ZERO and is written by
    /// `justify_line` with the box's per-fil slack share; the box is then
    /// replaced by a resolved `Graphics` in a lang-side post-pass that fires
    /// `fn_id`'s callback with that width. NOT glue (upstream's box is pure
    /// content, never a break point), but counted as a fil by
    /// `measure`/`justify_line`.
    GraphicsOuter {
        height: Length,
        depth: Length,
        width: Length,
        fn_id: GraphicsFnId,
    },
    /// A laid-out inline math run (`${…}`): one box carrying its own
    /// pre-shifted sub-glyphs, each with a vertical offset relative to this
    /// box's baseline (`MathGlyph::dy`) — the line model has only a
    /// horizontal `dx` per box and a single `baseline_y` per line, so a
    /// superscript can't be a separate box. `width`/`height`/`depth` are the
    /// run's outer metrics (computed by `read_math`), so the line breaker
    /// never re-enters the math engine. Never a legal line-break point (see
    /// `is_glue`) — a math run is laid out and flowed atomically.
    ///
    /// `rules`: filled paths the run needs alongside its glyphs — the
    /// fraction bar and radical sign/overbar are `Fill`s, not glyphs, since
    /// neither is drawable through a font's `Tj`. Box-local, y-**up**
    /// coordinates relative to this box's own baseline-left origin, exactly
    /// `PureHorzBox::Graphics::elems`' convention. `natural_width` is
    /// unaffected — a bar/radical-sign always sits within `glyphs`'
    /// already-measured span. Empty for the `read_math` path and for every
    /// atom `layout_math_atom` doesn't specially handle.
    Math {
        width: Length,
        height: Length,
        depth: Length,
        glyphs: Vec<MathGlyph>,
        rules: Vec<GraphicsElem>,
    },
    /// A deferred page-break hook (`hook-page-break`; v0.0.6's
    /// `PHGHookPageBreak`). Zero-width, renders nothing.
    HookPageBreak { id: HookId },
    /// A ruled grid box (`tabular`; v0.0.6's `PHGFixedTabular`), carrying
    /// each cell's already-laid-out inline run (`tabular::TabularCellBox`)
    /// plus the resolved rule graphics from the user's callback. The PDF
    /// writers recurse into it in `emit_box`, which is also where its three
    /// coordinate frames are reconciled.
    Tabular(TabularBox),
    /// An inline box carrying a whole block (`embed-block-top`; upstream's
    /// `PHGEmbeddedVert`/`HorzEmbeddedVertBreakable`). `block` is already
    /// broken into `VertBox` lines, which the writer stacks from the box's
    /// placed origin. ATOMIC — it does not split across a page boundary.
    EmbeddedBlock {
        width: Length,
        height: Length,
        depth: Length,
        block: Vec<VertBox>,
        /// Which of the block's lines sits on the surrounding text baseline:
        /// `false` = the FIRST line (`embed-block-top`, `adjust_to_first_line`),
        /// `true` = the LAST line (`embed-block-bottom`, `adjust_to_last_line`).
        /// Governs both this box's height/depth split and where the writers
        /// anchor the block's inner lines (`place_embedded_block`).
        anchor_last: bool,
        /// Built by `embed-block-BREAKABLE` (upstream
        /// `HorzEmbeddedVertBreakable`) rather than `embed-block-top`/`-bottom`
        /// (`HorzEmbeddedVert`). The breakable one is not laid out as inline
        /// content at all: the line breaker flushes the current line, splices
        /// the block's own vertical boxes straight into the vertical list
        /// (`AlreadyVert`, `lineBreak.ml:809-818`), and starts a fresh line.
        /// See `break_into_lines`.
        breakable: bool,
    },
    /// An UNBREAKABLE inline frame (`inline-frame-outer`/`-inner`; upstream
    /// `PHGOuterFrame`/`PHGInnerFrame`) — ATOMIC: contents are pre-fit at
    /// their natural width (`fit_cell`) and the frame never splits across a
    /// line break, matching upstream's model. `inline-frame-breakable` is NOT
    /// this variant — see [`PureHorzBox::InlineFrameMarker`].
    ///
    /// `width`/`height`/`depth` are the OUTER dims (padding included, baseline
    /// unshifted — padding grows the box, upstream lineBreak.ml's frame
    /// metrics). `contents` carry x-offsets from the frame's left edge (pad-L
    /// already applied), all on the frame's own baseline. `deco` is fired
    /// lang-side after placement; the writers draw nothing for it here.
    Frame {
        width: Length,
        height: Length,
        depth: Length,
        deco: DecoId,
        contents: Vec<(Length, PureHorzBox)>,
    },
    /// A placed block-frame marker (`VertBox::FrameStart`/`FrameEnd` after
    /// page breaking) — zero-width, renders nothing (writers' wildcard arm),
    /// read back by `fire_hooks` only.
    FrameMarker { id: DecoId, end: bool },
    /// One boundary of an inline BREAKABLE frame (`inline-frame-breakable`;
    /// upstream `HorzFrameBreakable`) — the horizontal twin of
    /// [`PureHorzBox::FrameMarker`], and for the same reason.
    ///
    /// Upstream keeps a breakable frame TRANSPARENT to the paragraph breaker:
    /// `LBFrameBreakable` threads the enclosing width map straight through its
    /// contents (`lineBreak.ml:1094`), so glue and discretionaries *inside* the
    /// frame are ordinary DP nodes of the enclosing paragraph, and `cut`
    /// (`:824`) re-frames the resulting fragments one line at a time
    /// (`append_framed_lines`), firing `decoS` for an unbroken frame and
    /// `decoH`/`decoM`/`decoT` per fragment for a broken one.
    ///
    /// This port's breaker is a flat index DP over one `Vec<PureHorzBox>`, so
    /// the same transparency is spelled the other way round: the primitive
    /// SPLICES the frame's contents into the paragraph stream (padding-L and
    /// -R as `FixedEmpty`, upstream's `append_horz_padding`) and brackets them
    /// with this zero-width marker pair, so the inner boxes simply *are* the
    /// paragraph's boxes. `fire_hooks` reassembles the fragments by walking
    /// the markers.
    ///
    /// `height`/`depth` are the WHOLE frame's padded content extent
    /// (`content ± pad`), carried on BOTH markers so that any line holding
    /// either one reserves the frame's full vertical extent. Upstream instead
    /// sizes each fragment from its own contents; for an unbroken frame (every
    /// bundled caller: `\ref`, `\href`, TOC entries — all zero-padding) the two
    /// agree exactly, and for a broken one this over-reserves a fragment by the
    /// difference between the frame's tallest content and that fragment's,
    /// which is zero for uniform text.
    InlineFrameMarker {
        id: DecoId,
        end: bool,
        height: Length,
        depth: Length,
    },
    /// `add-footnote`'s marker (v0.0.6 `PHGFootnote(imvblst)`,
    /// `horzBox.ml:283` → `ImHorzFootnote`, `:306`): a zero-width/height/
    /// depth inline box carrying the footnote's already-assembled block.
    /// Rides the paragraph like `HookPageBreak` (writers skip it via their
    /// wildcard arm); `chop_page` (pagebreak.rs) extracts it when the line
    /// carrying it is COMMITTED to a page, reserves the block's stacked
    /// height at the page bottom, and bottom-places the block in the same
    /// column (upstream `pageBreak.ml:131-142` + `handlePdf.ml:400-403`).
    /// The marker itself stays in the placed line's contents (render-inert)
    /// — extraction is a read-only scan, unlike upstream's removing
    /// `embed_page_info` (`pageInfo.ml:47`). Consequence: the block payload
    /// appears both (inert) inside its referencing line and (rendered) as
    /// bottom-placed lines — any future exhaustive consumer of a placed
    /// line's contents must treat this variant as inert or it will
    /// double-count the body.
    Footnote { block: Vec<VertBox> },
    /// An INERT reflow marker for emphasis runs (`\emph`/`\bold` in the
    /// repo-controlled stdlibs that opt in) and list-bullet fencing,
    /// emitted by the `inline-mark` primitive. Zero width/height/depth and
    /// renders nothing, so it contributes zero advance wherever it rides in a
    /// placed line's `contents`. Read only by the reflow HTML walker (the
    /// `html-support` branch's `reflow/inline.rs`), which uses
    /// `EmphStart`/`EmphEnd` to wrap `<em>`/`<strong>` and
    /// `BulletStart`/`BulletEnd` to suppress the drawn bullet/number glyph run
    /// (the real marker comes from the `<ul>`/`<ol>` itself).
    InlineMark(InlineMarkKind),
}

/// The marker kind a `PureHorzBox::InlineMark` carries. `strong` is chosen AT
/// THE WRAP SITE (which stdlib command calls `inline-mark` with which tag),
/// not recovered from the box tree: `\emph` -> `strong: false` (`<em>`),
/// `\bold`/`\strong` -> `strong: true` (`<strong>`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum InlineMarkKind {
    /// Opens `<em>` (`strong = false`) or `<strong>` (`strong = true`).
    EmphStart { strong: bool },
    /// Closes the innermost open emphasis span.
    EmphEnd,
    /// Opens a fence around a drawn bullet/number glyph run (`itemize.satyh`'s
    /// `make-bullet`/`enumerate-item`'s numeral) — the reflow walker drops
    /// everything between this and the matching `BulletEnd`, since the real
    /// `<ul>`/`<ol>` marker replaces it.
    BulletStart,
    /// Closes the bullet fence.
    BulletEnd,
}

/// TeX's forced-break convention: a discretionary penalty this low or
/// lower means the paragraph breaker must end a line there. `text_to_boxes`
/// uses this to turn a UAX#14 `Mandatory` boundary (e.g. a literal newline)
/// into a break the DP cannot skip over (see `linebreak.rs`'s `floor`).
pub const FORCED_BREAK_PENALTY: i32 = -10_000;

/// The mirror convention at the other extreme: a `Discretionary` carrying this
/// penalty offers NO break at all — it exists only to render its `no_break`
/// slot, unbreakably.
///
/// This is upstream's `LBPure(lphb)`, the `PreventBreak` arm of
/// `discretionary_if_breakable` (`convertText.ml:189-190`). A pure glue box is
/// not a breakpoint but its stretch/shrink still count toward the line's
/// elasticity (`lineBreak.ml`'s `add_width_all`).
///
/// The port's box model has no separate "pure elastic box": a bare
/// `OuterEmpty` IS a breakpoint (`is_glue`). So `PreventBreak` is modelled as a
/// `Discretionary` with every break slot empty, its content in `no_break`, and
/// this penalty — which `is_break_point` reads as "not a candidate", keeping
/// one code path in `text_to_boxes` for both arms.
pub const NO_BREAK_PENALTY: i32 = i32::MAX;

impl PureHorzBox {
    pub fn natural_width(&self) -> Length {
        match self {
            PureHorzBox::InnerString { width, .. } => *width,
            PureHorzBox::OuterEmpty { natural, .. } => *natural,
            PureHorzBox::OuterFil => Length::ZERO,
            PureHorzBox::FixedEmpty { width } => *width,
            PureHorzBox::Image { width, .. } => *width,
            // Un-taken discretionary: renders as `no_break` (hyphenation —
            // `linebreak.rs`'s `line_content` handles the taken case, which
            // never reaches this generic accessor). Empty for
            // UAX#14-only discretionaries, hence zero then.
            PureHorzBox::Discretionary { no_break, .. } => no_break
                .iter()
                .map(PureHorzBox::natural_width)
                .fold(Length::ZERO, |acc, w| acc + w),
            PureHorzBox::Graphics { width, .. } => *width,
            // Fil semantics: zero natural width, like `OuterFil`.
            PureHorzBox::GraphicsOuter { .. } => Length::ZERO,
            PureHorzBox::Math { width, .. } => *width,
            // `EvHorzHookPageBreak` has width `Length.zero` (pageInfo.ml:42).
            PureHorzBox::HookPageBreak { .. } => Length::ZERO,
            PureHorzBox::Tabular(tab) => tab.width,
            PureHorzBox::EmbeddedBlock { width, .. } => *width,
            PureHorzBox::Frame { width, .. } => *width,
            PureHorzBox::FrameMarker { .. } => Length::ZERO,
            PureHorzBox::InlineFrameMarker { .. } => Length::ZERO,
            // `ImHorzFootnote` is skipped by every width scan upstream,
            // lineBreak.ml:1200/1254.
            PureHorzBox::Footnote { .. } => Length::ZERO,
            PureHorzBox::InlineMark(_) => Length::ZERO,
        }
    }

    /// `false` for every variant except the two glue kinds.
    pub fn is_glue(&self) -> bool {
        matches!(
            self,
            PureHorzBox::OuterEmpty { .. } | PureHorzBox::OuterFil
        )
    }

    /// A legal paragraph-break candidate: glue (today's only breakpoints)
    /// or a discretionary (UAX#14/hyphenation break points). CJK text has
    /// no glue at all, so discretionaries are its *only* break candidates.
    ///
    /// EXCEPT a `NO_BREAK_PENALTY` discretionary, which is upstream's
    /// `LBPure(glue)` in disguise (see that constant): it renders its
    /// `no_break` slot and offers no edge.
    pub fn is_break_point(&self) -> bool {
        match self {
            PureHorzBox::Discretionary { penalty, .. } => *penalty != NO_BREAK_PENALTY,
            _ => self.is_glue(),
        }
    }

    /// The break's own penalty (TeX's discretionary/`\penalty`
    /// convention): 0 for glue (no preference either way), a
    /// discretionary's own `penalty` otherwise.
    pub(crate) fn break_penalty(&self) -> i32 {
        match self {
            PureHorzBox::Discretionary { penalty, .. } => *penalty,
            _ => 0,
        }
    }

    /// Whether breaking here is not just legal but mandatory
    /// (`penalty <= FORCED_BREAK_PENALTY`).
    pub(crate) fn is_forced_break(&self) -> bool {
        self.break_penalty() <= FORCED_BREAK_PENALTY
    }
}

/// `horz_box`: the wrapper stays even though `Pure` is its only variant so
/// far, keeping line-break input the shape lineBreak.ml expects.
#[derive(Clone, Debug, PartialEq)]
pub enum HorzBox {
    Pure(PureHorzBox),
}