1
//! A helper module to extract final, absolute glyph positions from a layout.
2
//! This is useful for renderers that work with simple lists of glyphs.
3

            
4
use azul_core::{
5
    dom::NodeId,
6
    geom::{LogicalPosition, LogicalSize},
7
    ui_solver::GlyphInstance,
8
};
9
use azul_css::props::{basic::ColorU, style::StyleBackgroundContent};
10

            
11
use crate::text3::cache::{
12
    get_item_vertical_metrics_approx, InlineBorderInfo, LoadedFonts, ParsedFontTrait, Point,
13
    ShapedGlyph, ShapedItem, UnifiedLayout,
14
};
15

            
16
/// Represents a single glyph ready for rendering, with an absolute position on the baseline.
17
#[derive(Debug, Copy, Clone, PartialEq)]
18
pub struct PositionedGlyph {
19
    pub glyph_id: u16,
20
    /// The absolute position of the glyph's origin on the baseline.
21
    pub position: Point,
22
    /// The advance width of the glyph, useful for caret placement.
23
    pub advance: f32,
24
}
25

            
26
/// A simple glyph run without font reference - used when fonts aren't available.
27
/// The font can be looked up later via `font_hash` if needed.
28
#[derive(Debug, Clone)]
29
pub struct SimpleGlyphRun {
30
    /// The glyphs in this run, with their positions relative to the start of the run.
31
    pub glyphs: Vec<GlyphInstance>,
32
    /// The color of the text in this glyph run.
33
    pub color: ColorU,
34
    /// Background color for this run (rendered behind text)
35
    pub background_color: Option<ColorU>,
36
    /// Full background content layers (for gradients, images, etc.)
37
    pub background_content: Vec<StyleBackgroundContent>,
38
    /// Border information for inline elements
39
    pub border: Option<InlineBorderInfo>,
40
    /// A hash of the font, useful for caching purposes.
41
    pub font_hash: u64,
42
    /// The font size in pixels.
43
    pub font_size_px: f32,
44
    /// Text decoration (underline, strikethrough, overline)
45
    pub text_decoration: crate::text3::cache::TextDecoration,
46
    /// Whether this is an IME composition preview (should be rendered with special styling)
47
    pub is_ime_preview: bool,
48
    /// The source DOM node that generated this text run (for hit-testing)
49
    pub source_node_id: Option<NodeId>,
50
}
51

            
52
/// #25: the STORED form of a paint run's glyphs — 8 B/glyph instead of the
53
/// 20 B `GlyphInstance`. Exploits two invariants of the simple-run contract:
54
/// `size` is never populated (both builders emit `LogicalSize::default()`),
55
/// and `point.y` is the run baseline for every glyph except detail glyphs
56
/// with vertical offsets. Anything that deviates goes in `exceptions` as a
57
/// FULL instance, so expansion is bit-exact BY CONSTRUCTION — there is no
58
/// lossy path, only a smaller encoding for the invariant-conforming bulk.
59
#[derive(Debug, Clone, PartialEq, Default)]
60
pub struct CompactGlyphs {
61
    /// `(glyph index, pen x)` per glyph, in paint order.
62
    pub xs: Vec<(u32, f32)>,
63
    /// The y (baseline) shared by every non-exception glyph. Bit pattern
64
    /// of the first instance's y (float identity — the NaN rule).
65
    pub y: f32,
66
    /// The size shared by every non-exception glyph (today always
67
    /// `LogicalSize::default()` — kept as data, not assumption).
68
    pub size: LogicalSize,
69
    /// `(position in xs, full original instance)` for glyphs whose y or
70
    /// size deviate from the shared values. Sorted by position.
71
    pub exceptions: Vec<(u32, GlyphInstance)>,
72
}
73

            
74
impl CompactGlyphs {
75
    /// Compacts a transient instance list. Exact: `expand()` of the result
76
    /// reproduces `v` bit for bit (floats compared as bit patterns when
77
    /// choosing the shared y/size — NaNs become exceptions, never a match).
78
    #[must_use]
79
197761
    pub fn from_instances(v: &[GlyphInstance]) -> Self {
80
197761
        let (y, size) = v
81
197761
            .first()
82
197761
            .map_or_else(|| (0.0, LogicalSize::default()), |g| (g.point.y, g.size));
83
197761
        let mut xs = Vec::with_capacity(v.len());
84
197761
        let mut exceptions = Vec::new();
85
2767914
        for (i, g) in v.iter().enumerate() {
86
2767914
            xs.push((g.index, g.point.x));
87
2767914
            let same_y = g.point.y.to_bits() == y.to_bits();
88
2767914
            let same_size = g.size.width.to_bits() == size.width.to_bits()
89
2767913
                && g.size.height.to_bits() == size.height.to_bits();
90
2767914
            if !(same_y && same_size) {
91
4
                exceptions.push((u32::try_from(i).unwrap_or(u32::MAX), *g));
92
2767910
            }
93
        }
94
197761
        Self {
95
197761
            xs,
96
197761
            y,
97
197761
            size,
98
197761
            exceptions,
99
197761
        }
100
197761
    }
101

            
102
    #[must_use]
103
1791058
    pub const fn len(&self) -> usize {
104
1791058
        self.xs.len()
105
1791058
    }
106

            
107
    #[must_use]
108
1
    pub const fn is_empty(&self) -> bool {
109
1
        self.xs.is_empty()
110
1
    }
111

            
112
    /// Reconstructs instance `i` exactly as it was compacted.
113
    #[must_use]
114
19911869
    pub fn get(&self, i: usize) -> Option<GlyphInstance> {
115
19911869
        let &(index, x) = self.xs.get(i)?;
116
19911867
        let iu = u32::try_from(i).unwrap_or(u32::MAX);
117
19911867
        if let Ok(e) = self.exceptions.binary_search_by_key(&iu, |&(p, _)| p) {
118
5
            return Some(self.exceptions[e].1);
119
19911862
        }
120
19911862
        Some(GlyphInstance {
121
19911862
            index,
122
19911862
            point: LogicalPosition { x, y: self.y },
123
19911862
            size: self.size,
124
19911862
        })
125
19911869
    }
126

            
127
    #[must_use]
128
1193635
    pub fn first(&self) -> Option<GlyphInstance> {
129
1193635
        self.get(0)
130
1193635
    }
131

            
132
    #[must_use]
133
1193635
    pub fn last(&self) -> Option<GlyphInstance> {
134
1193635
        self.get(self.len().wrapping_sub(1))
135
1193635
    }
136

            
137
    /// Exact expansion, in order.
138
597418
    pub fn iter(&self) -> impl Iterator<Item = GlyphInstance> + '_ {
139
17524599
        (0..self.len()).map(|i| self.get(i).expect("index in range"))
140
597418
    }
141

            
142
    /// The paint expansion: every instance translated by `(dx, dy)` — the
143
    /// same Vec the DL generator built by copy-then-offset before #25.
144
    #[must_use]
145
597412
    pub fn to_vec_offset(&self, dx: f32, dy: f32) -> Vec<GlyphInstance> {
146
597412
        self.iter()
147
17524585
            .map(|mut g| {
148
17524585
                g.point.x += dx;
149
17524585
                g.point.y += dy;
150
17524585
                g
151
17524585
            })
152
597412
            .collect()
153
597412
    }
154

            
155
    /// Heap bytes retained by this encoding (memory report).
156
    #[must_use]
157
5
    pub const fn retained_bytes(&self) -> usize {
158
5
        self.xs.capacity() * size_of::<(u32, f32)>()
159
5
            + self.exceptions.capacity() * size_of::<(u32, GlyphInstance)>()
160
5
    }
161
}
162

            
163
/// #25: the STORED paint run — [`SimpleGlyphRun`]'s header with the glyph
164
/// list compacted. `SimpleGlyphRun` remains the TRANSIENT form the two
165
/// builders produce and the equivalence gates compare; the store chokepoint
166
/// (`CachedInlineLayout` construction) converts once, the same shape as the
167
/// §3.2 dense retirement.
168
#[derive(Debug, Clone)]
169
pub struct CompactGlyphRun {
170
    pub glyphs: CompactGlyphs,
171
    pub color: ColorU,
172
    pub background_color: Option<ColorU>,
173
    pub background_content: Vec<StyleBackgroundContent>,
174
    pub border: Option<InlineBorderInfo>,
175
    pub font_hash: u64,
176
    pub font_size_px: f32,
177
    pub text_decoration: crate::text3::cache::TextDecoration,
178
    pub is_ime_preview: bool,
179
    pub source_node_id: Option<NodeId>,
180
}
181

            
182
impl From<SimpleGlyphRun> for CompactGlyphRun {
183
197755
    fn from(r: SimpleGlyphRun) -> Self {
184
197755
        Self {
185
197755
            glyphs: CompactGlyphs::from_instances(&r.glyphs),
186
197755
            color: r.color,
187
197755
            background_color: r.background_color,
188
197755
            background_content: r.background_content,
189
197755
            border: r.border,
190
197755
            font_hash: r.font_hash,
191
197755
            font_size_px: r.font_size_px,
192
197755
            text_decoration: r.text_decoration,
193
197755
            is_ime_preview: r.is_ime_preview,
194
197755
            source_node_id: r.source_node_id,
195
197755
        }
196
197755
    }
197
}
198

            
199
impl CompactGlyphRun {
200
    /// The transient form back — for gates and any reader that wants the
201
    /// instance list. Exact inverse of the `From` conversion.
202
    #[must_use]
203
1
    pub fn expand(&self) -> SimpleGlyphRun {
204
1
        SimpleGlyphRun {
205
1
            glyphs: self.glyphs.iter().collect(),
206
1
            color: self.color,
207
1
            background_color: self.background_color,
208
1
            background_content: self.background_content.clone(),
209
1
            border: self.border,
210
1
            font_hash: self.font_hash,
211
1
            font_size_px: self.font_size_px,
212
1
            text_decoration: self.text_decoration,
213
1
            is_ime_preview: self.is_ime_preview,
214
1
            source_node_id: self.source_node_id,
215
1
        }
216
1
    }
217
}
218

            
219
/// Bit-exact run equality for the #25 roundtrip gate. Floats compare as
220
/// BIT PATTERNS — a NaN that survives the compact/expand roundtrip must
221
/// count as equal (derived `PartialEq` would call that a divergence and
222
/// a lossy roundtrip that maps NaN to NaN would pass; both wrong ways).
223
#[must_use]
224
1
pub fn simple_runs_bit_equal(a: &SimpleGlyphRun, b: &SimpleGlyphRun) -> bool {
225
9
    let f = |x: f32, y: f32| x.to_bits() == y.to_bits();
226
1
    a.color == b.color
227
1
        && a.background_color == b.background_color
228
1
        && a.background_content == b.background_content
229
1
        && a.border == b.border
230
1
        && a.font_hash == b.font_hash
231
1
        && f(a.font_size_px, b.font_size_px)
232
1
        && a.text_decoration == b.text_decoration
233
1
        && a.is_ime_preview == b.is_ime_preview
234
1
        && a.source_node_id == b.source_node_id
235
1
        && a.glyphs.len() == b.glyphs.len()
236
2
        && a.glyphs.iter().zip(b.glyphs.iter()).all(|(g, h)| {
237
2
            g.index == h.index
238
2
                && f(g.point.x, h.point.x)
239
2
                && f(g.point.y, h.point.y)
240
2
                && f(g.size.width, h.size.width)
241
2
                && f(g.size.height, h.size.height)
242
2
        })
243
1
}
244

            
245
/// Groups glyphs into runs without requiring font references.
246
/// Use this when you only need glyph positions and don't need font references.
247
#[allow(clippy::float_cmp)] // intentional exact compare: change-detection / identity fast-path / cache-key match
248
#[allow(clippy::too_many_lines)] // large but cohesive: single-purpose layout/render/parse routine (one branch per case)
249
#[must_use]
250
90
pub fn get_glyph_runs_simple(layout: &UnifiedLayout) -> Vec<SimpleGlyphRun> {
251
90
    let mut runs: Vec<SimpleGlyphRun> = Vec::new();
252
90
    let mut current_run: Option<SimpleGlyphRun> = None;
253
    // Baseline the open run sits on. Runs merge across layout items when
254
    // their style matches, and the style predicate below has no notion of
255
    // WHERE the glyphs are — so every line of a paragraph merged into one
256
    // run, hence one `DisplayListItem::Text`, hence one damage rect
257
    // covering all of them. Breaking on the baseline makes a line the unit
258
    // of damage, so editing line 3 of a paragraph does not repaint lines
259
    // 1 and 2.
260
90
    let mut current_baseline: Option<f32> = None;
261

            
262
1834
    for item in &layout.items {
263
1744
        let (item_ascent, _) = get_item_vertical_metrics_approx(&item.item);
264
1744
        let baseline_y = item.position.y + item_ascent;
265

            
266
1744
        let mut process_glyphs =
267
            |positioned_glyphs: &[ShapedGlyph],
268
             item_origin_x: f32,
269
             writing_mode: crate::text3::cache::WritingMode,
270
             source_node_id: Option<NodeId>,
271
1740
             style: &crate::text3::cache::StyleProperties| {
272
1740
                let mut pen_x = item_origin_x;
273

            
274
3487
                for glyph in positioned_glyphs {
275
1747
                    let glyph_color = style.color;
276
1747
                    let glyph_background = style.background_color;
277
1747
                    let glyph_background_content = style.background_content.clone();
278
1747
                    let glyph_border = style.border;
279
1747
                    let font_hash = glyph.font_hash;
280
1747
                    let font_size_px = style.font_size_px;
281
1747
                    let text_decoration = style.text_decoration;
282

            
283
1747
                    let absolute_position = LogicalPosition {
284
1747
                        x: pen_x + glyph.offset.x,
285
1747
                        y: baseline_y - glyph.offset.y,
286
1747
                    };
287

            
288
1747
                    let instance =
289
1747
                        glyph.into_glyph_instance_at_simple(writing_mode, absolute_position);
290

            
291
1747
                    if let Some(run) = current_run.as_mut() {
292
                        // changes (font, color, border, size). Per spec, text-decoration
293
                        // changes do not affect shaping (shaping is done upstream in
294
                        // default.rs), but we still break rendering runs for correct drawing.
295
                        // Border/margin/padding changes break both shaping and rendering runs.
296
1662
                        if current_baseline == Some(baseline_y)
297
1571
                            && run.font_hash == font_hash
298
1570
                            && run.color == glyph_color
299
1492
                            && run.background_color == glyph_background
300
1492
                            && run.background_content == glyph_background_content
301
1491
                            && run.border == glyph_border
302
1491
                            && run.font_size_px == font_size_px
303
1478
                            && run.text_decoration == text_decoration
304
1477
                            && run.source_node_id == source_node_id
305
1476
                        {
306
1476
                            run.glyphs.push(instance);
307
1546
                        } else {
308
186
                            runs.push(run.clone());
309
186
                            current_baseline = Some(baseline_y);
310
186
                            current_run = Some(SimpleGlyphRun {
311
186
                                glyphs: vec![instance],
312
186
                                color: glyph_color,
313
186
                                background_color: glyph_background,
314
186
                                background_content: glyph_background_content.clone(),
315
186
                                border: glyph_border,
316
186
                                font_hash,
317
186
                                font_size_px,
318
186
                                text_decoration,
319
186
                                is_ime_preview: false,
320
186
                                source_node_id,
321
186
                            });
322
186
                        }
323
85
                    } else {
324
85
                        current_baseline = Some(baseline_y);
325
85
                        current_run = Some(SimpleGlyphRun {
326
85
                            glyphs: vec![instance],
327
85
                            color: glyph_color,
328
85
                            background_color: glyph_background,
329
85
                            background_content: glyph_background_content.clone(),
330
85
                            border: glyph_border,
331
85
                            font_hash,
332
85
                            font_size_px,
333
85
                            text_decoration,
334
85
                            is_ime_preview: false,
335
85
                            source_node_id,
336
85
                        });
337
85
                    }
338

            
339
1747
                    pen_x += glyph.advance + glyph.kerning;
340
                }
341
1740
            };
342

            
343
1744
        match &item.item {
344
1738
            ShapedItem::Cluster(cluster) => {
345
1738
                let writing_mode = cluster.style.writing_mode;
346
1738
                process_glyphs(
347
1738
                    &cluster.glyphs,
348
1738
                    item.position.x,
349
1738
                    writing_mode,
350
1738
                    cluster.source_node_id,
351
1738
                    &cluster.style,
352
1738
                );
353
1738
            }
354
2
            ShapedItem::CombinedBlock { glyphs, style, .. } => {
355
2
                // CombinedBlock (tate-chu-yoko) carries raw per-glyph advances/GPOS
356
2
                // offsets, NOT pre-accumulated pen positions. Feed the WHOLE slice to
357
2
                // `process_glyphs` in ONE call so the pen advances between glyphs;
358
2
                // calling it once per glyph reset pen_x each time and stacked every
359
2
                // glyph at the same x (mirrors get_glyph_positions). Use None for
360
2
                // source_node_id (tate-chu-yoko has no single source node).
361
2
                let writing_mode = style.writing_mode;
362
2
                process_glyphs(glyphs, item.position.x, writing_mode, None, style);
363
2
            }
364
4
            _ => {}
365
        }
366
    }
367

            
368
90
    if let Some(run) = current_run {
369
85
        runs.push(run);
370
85
    }
371

            
372
90
    suppress_split_border_fragments(&mut runs);
373

            
374
90
    runs
375
90
}
376

            
377
/// +spec:box-model:6c62d3 - suppress margins/borders/padding at inline box split points
378
/// CSS 2.2 §9.4.2: When an inline box is split across lines, margins, borders,
379
/// and padding have no visible effect at the split points.
380
/// Post-process: for runs from the same `source_node_id` that have borders,
381
/// mark intermediate fragments so `left_inset()`/`right_inset()` suppress edges.
382
/// Shared by [`get_glyph_runs_simple`] and its dense twin
383
/// (`crate::text3::dense::get_glyph_runs_simple_dense`) so the fragment
384
/// semantics cannot drift between the two walkers.
385
167604
pub(crate) fn suppress_split_border_fragments(runs: &mut [SimpleGlyphRun]) {
386
167604
    if runs.len() > 1 {
387
20389
        let mut i = 0;
388
72635
        while i < runs.len() {
389
52246
            if let Some(node_id) = runs[i].source_node_id {
390
51290
                if runs[i].border.is_some() {
391
53
                    let start = i;
392
53
                    let mut end = i + 1;
393
199
                    while end < runs.len()
394
166
                        && runs[end].source_node_id == Some(node_id)
395
146
                        && runs[end].border.is_some()
396
146
                    {
397
146
                        end += 1;
398
146
                    }
399
53
                    if end - start > 1 {
400
23
                        if let Some(ref mut b) = runs[start].border {
401
23
                            b.is_last_fragment = false;
402
23
                        }
403
123
                        for run in &mut runs[start + 1..end - 1] {
404
123
                            if let Some(ref mut b) = run.border {
405
123
                                b.is_first_fragment = false;
406
123
                                b.is_last_fragment = false;
407
123
                            }
408
                        }
409
23
                        if let Some(ref mut b) = runs[end - 1].border {
410
23
                            b.is_first_fragment = false;
411
23
                        }
412
30
                    }
413
53
                    i = end;
414
53
                    continue;
415
51237
                }
416
956
            }
417
52193
            i += 1;
418
        }
419
147215
    }
420
167604
}
421

            
422
/// A glyph run optimized for PDF rendering.
423
///
424
/// Groups glyphs by font, color, size, and style, while breaking at line boundaries.
425
/// This struct is used by the PDF renderer to efficiently render text with proper
426
/// styling, including inline background colors for `<span>` elements.
427
///
428
/// # Z-Order for Inline Backgrounds
429
///
430
/// The `background_color` field enables proper z-ordering of inline backgrounds:
431
/// - PDF renderers should iterate over all runs and render backgrounds FIRST
432
/// - Then iterate again and render all text SECOND
433
/// - This ensures backgrounds appear behind text, not on top of it
434
///
435
/// The display list (`paint_inline_content`) does NOT emit `push_rect()` for inline
436
/// backgrounds because that would cause double-rendering and z-order issues.
437
#[derive(Debug, Clone)]
438
pub struct PdfGlyphRun<T: ParsedFontTrait> {
439
    /// The glyphs in this run with their absolute positions
440
    pub glyphs: Vec<PdfPositionedGlyph>,
441
    /// The color of the text
442
    pub color: ColorU,
443
    /// Background color for inline elements (e.g., `<span style="background: yellow">`)
444
    ///
445
    /// This is rendered as a filled rectangle behind the text by the PDF renderer.
446
    /// The rectangle spans from ascent to descent and covers the full width of the run.
447
    pub background_color: Option<ColorU>,
448
    /// The font used for this run
449
    pub font: T,
450
    /// Font hash for identification
451
    pub font_hash: u64,
452
    /// Font size in pixels
453
    pub font_size_px: f32,
454
    /// Text decoration flags
455
    pub text_decoration: crate::text3::cache::TextDecoration,
456
    /// The line index this run belongs to (for breaking runs at line boundaries)
457
    pub line_index: usize,
458
    /// Text direction for this run
459
    pub direction: crate::text3::cache::BidiDirection,
460
    /// Writing mode for this run
461
    pub writing_mode: crate::text3::cache::WritingMode,
462
    /// The starting position (baseline) of this run - used for `SetTextMatrix`
463
    pub baseline_start: Point,
464
    /// Original cluster text for debugging/CID mapping
465
    pub cluster_texts: Vec<String>,
466
}
467

            
468
/// A glyph with its absolute position and cluster text for PDF rendering
469
#[derive(Debug, Clone)]
470
pub struct PdfPositionedGlyph {
471
    /// Glyph ID
472
    pub glyph_id: u16,
473
    /// Absolute position on the baseline (Y-down coordinate system)
474
    pub position: Point,
475
    /// The advance width of this glyph
476
    pub advance: f32,
477
    /// The Unicode character(s) this glyph represents (for PDF `ToUnicode` `CMap`)
478
    /// This is extracted from the cluster text using the glyph's `cluster_offset`
479
    pub unicode_codepoint: String,
480
}
481

            
482
/// Extract glyph runs optimized for PDF rendering.
483
/// This function:
484
/// - Groups consecutive glyphs by font, color, size, style, and line
485
/// - Breaks runs at line boundaries (different `line_index`)
486
/// - Preserves absolute positioning for each glyph (critical for RTL and complex scripts)
487
/// - Includes cluster text for proper CID/Unicode mapping
488
#[allow(clippy::float_cmp)] // intentional exact compare: change-detection / identity fast-path / cache-key match
489
#[must_use]
490
24
pub fn get_glyph_runs_pdf<T: ParsedFontTrait>(
491
24
    layout: &UnifiedLayout,
492
24
    fonts: &LoadedFonts<T>,
493
24
) -> Vec<PdfGlyphRun<T>> {
494
24
    let mut runs: Vec<PdfGlyphRun<T>> = Vec::new();
495
24
    let mut current_run: Option<PdfGlyphRun<T>> = None;
496

            
497
160
    for positioned_item in &layout.items {
498
        // Only process text clusters
499
136
        let ShapedItem::Cluster(cluster) = &positioned_item.item else {
500
4
            continue; // Skip non-text items
501
        };
502

            
503
132
        if cluster.glyphs.is_empty() {
504
1
            continue;
505
131
        }
506

            
507
        // Calculate the baseline position for this cluster
508
131
        let (item_ascent, _) = get_item_vertical_metrics_approx(&positioned_item.item);
509
131
        let baseline_y = positioned_item.position.y + item_ascent;
510

            
511
        // Process each glyph in the cluster
512
131
        let mut pen_x = positioned_item.position.x;
513

            
514
        // For extracting the correct unicode codepoint per glyph, we need to track
515
        // which portion of the cluster text each glyph represents.
516
        // The cluster_offset in ShapedGlyph is the byte offset into cluster.text
517
131
        let cluster_text = cluster.text();
518
131
        let cluster_glyphs_count = cluster.glyphs.len();
519

            
520
143
        for (glyph_idx, glyph) in cluster.glyphs.iter().enumerate() {
521
143
            let glyph_color = cluster.style.color;
522
143
            let glyph_background = cluster.style.background_color;
523
143
            let font_hash = glyph.font_hash;
524
143
            let font_size_px = cluster.style.font_size_px;
525
143
            let text_decoration = cluster.style.text_decoration;
526
143
            let line_index = positioned_item.line_index;
527
143
            let direction = cluster.direction;
528
143
            let writing_mode = cluster.style.writing_mode;
529

            
530
            // Look up the font from the fonts container
531
143
            let font = match fonts.get_by_hash(font_hash) {
532
140
                Some(f) => f.clone(),
533
3
                None => continue, // Skip glyphs with unknown fonts
534
            };
535

            
536
            // Calculate absolute glyph position on baseline
537
140
            let glyph_position = Point {
538
140
                x: pen_x + glyph.offset.x,
539
140
                y: baseline_y - glyph.offset.y, // Y-down: subtract positive GPOS offset
540
140
            };
541

            
542
            // Extract the unicode codepoint for this specific glyph
543
            // For simple 1:1 mappings, each glyph gets one character
544
            // For complex scripts (ligatures, etc.), we may need to assign
545
            // the whole cluster text to the first glyph, or split it appropriately
546
140
            let unicode_codepoint = if cluster_glyphs_count == 1 {
547
                // Simple case: one glyph represents the entire cluster
548
122
                cluster_text.to_string()
549
            } else {
550
                // Multiple glyphs in cluster - try to extract the character at cluster_offset
551
                // cluster_offset is the byte offset into the cluster text
552
18
                let byte_offset = glyph.cluster_offset as usize;
553
18
                if byte_offset < cluster_text.len() {
554
                    // Get the character at this byte offset
555
12
                    cluster_text[byte_offset..]
556
12
                        .chars()
557
12
                        .next()
558
12
                        .map_or_else(|| cluster_text.to_string(), |c| c.to_string())
559
                } else {
560
                    // Fallback: if offset is out of range, use the whole cluster for first glyph
561
                    // or empty for subsequent glyphs (they share the same codepoint)
562
6
                    if glyph_idx == 0 {
563
3
                        cluster_text.to_string()
564
                    } else {
565
3
                        String::new()
566
                    }
567
                }
568
            };
569

            
570
140
            let pdf_glyph = PdfPositionedGlyph {
571
140
                glyph_id: glyph.glyph_id,
572
140
                position: glyph_position,
573
140
                advance: glyph.advance,
574
140
                unicode_codepoint,
575
140
            };
576

            
577
            // Font hash change = font change (shaping must break per spec).
578
            // Border/background change = margin/border/padding non-zero (shaping must break).
579
            // Text-decoration change = rendering-only break (shaping unaffected per spec).
580
140
            let should_break = current_run.as_ref().is_some_and(|run| {
581
118
                run.font_hash != font_hash
582
118
                    || run.color != glyph_color
583
117
                    || run.background_color != glyph_background
584
116
                    || run.font_size_px != font_size_px
585
114
                    || run.text_decoration != text_decoration
586
114
                    || run.line_index != line_index
587
108
                    || run.direction != direction
588
107
                    || run.writing_mode != writing_mode
589
118
            });
590

            
591
140
            if should_break {
592
                // Finalize the current run and start a new one
593
12
                if let Some(run) = current_run.take() {
594
12
                    runs.push(run);
595
12
                }
596
128
            }
597

            
598
140
            if let Some(run) = current_run.as_mut() {
599
107
                // Add to existing run
600
107
                run.glyphs.push(pdf_glyph);
601
107
                run.cluster_texts.push(cluster.text().to_string());
602
121
            } else {
603
33
                // Start a new run
604
33
                current_run = Some(PdfGlyphRun {
605
33
                    glyphs: vec![pdf_glyph],
606
33
                    color: glyph_color,
607
33
                    background_color: glyph_background,
608
33
                    font: font.clone(),
609
33
                    font_hash,
610
33
                    font_size_px,
611
33
                    text_decoration,
612
33
                    line_index,
613
33
                    direction,
614
33
                    writing_mode,
615
33
                    baseline_start: Point {
616
33
                        x: pen_x,
617
33
                        y: baseline_y,
618
33
                    },
619
33
                    cluster_texts: vec![cluster.text().to_string()],
620
33
                });
621
33
            }
622

            
623
            // Advance pen position - DON'T add kerning here because it's already
624
            // included in the positioned_item.position.x from the layout engine!
625
            // We only advance by the base advance to track our position within this cluster
626
140
            pen_x += glyph.advance + glyph.kerning;
627
        }
628
    }
629

            
630
    // Push the final run if any
631
24
    if let Some(run) = current_run {
632
21
        runs.push(run);
633
21
    }
634

            
635
24
    runs
636
24
}
637

            
638
/// Transforms the final layout into a simple list of glyphs and their absolute positions.
639
///
640
/// This function iterates through all positioned items in a layout, filtering for text clusters
641
/// and combined text blocks. It calculates the absolute baseline position for each glyph within
642
/// these items and returns a flat vector of `PositionedGlyph` structs. This is useful for
643
/// rendering or for clients that need a lower-level representation of the text layout.
644
///
645
/// # Arguments
646
///
647
/// - `layout` - A reference to the final `UnifiedLayout` produced by the pipeline.
648
///
649
/// # Returns
650
///
651
/// A `Vec<PositionedGlyph>` containing all glyphs from the layout with their
652
/// absolute baseline positions.
653
#[must_use]
654
44
pub fn get_glyph_positions(layout: &UnifiedLayout) -> Vec<PositionedGlyph> {
655
44
    let mut final_glyphs = Vec::new();
656

            
657
982
    for item in &layout.items {
658
938
        let (item_ascent, _) = get_item_vertical_metrics_approx(&item.item);
659
938
        let baseline_y = item.position.y + item_ascent;
660

            
661
938
        let mut process_glyphs = |positioned_glyphs: &[ShapedGlyph], item_origin_x: f32| {
662
934
            let mut pen_x = item_origin_x;
663
11877
            for glyph in positioned_glyphs {
664
10943
                // The glyph's final position is its origin on the baseline.
665
10943
                // GPOS y-offsets shift the glyph up or down relative to the baseline.
666
10943
                // In a Y-down coordinate system, a positive GPOS offset (up) means
667
10943
                // subtracting from Y.
668
10943
                let glyph_pos = Point {
669
10943
                    x: pen_x + glyph.offset.x,
670
10943
                    y: baseline_y - glyph.offset.y,
671
10943
                };
672
10943

            
673
10943
                final_glyphs.push(PositionedGlyph {
674
10943
                    glyph_id: glyph.glyph_id,
675
10943
                    position: glyph_pos,
676
10943
                    advance: glyph.advance,
677
10943
                });
678
10943

            
679
10943
                // Advance the pen for the next glyph in the cluster/block.
680
10943
                pen_x += glyph.advance + glyph.kerning;
681
10943
            }
682
934
        };
683

            
684
938
        match &item.item {
685
931
            ShapedItem::Cluster(cluster) => {
686
931
                process_glyphs(&cluster.glyphs, item.position.x);
687
931
            }
688
3
            ShapedItem::CombinedBlock { glyphs, .. } => {
689
3
                // This assumes horizontal layout for the combined block's glyphs.
690
3
                process_glyphs(glyphs, item.position.x);
691
3
            }
692
4
            _ => {
693
4
                // Ignore non-text items like objects, breaks, etc.
694
4
            }
695
        }
696
    }
697

            
698
44
    final_glyphs
699
44
}
700

            
701
/// Adversarial unit tests generated for `layout/src/text3/glyphs.rs`.
702
///
703
/// The three public entry points are pure transforms over a `UnifiedLayout`, so the
704
/// interesting failure modes are all in the pen arithmetic (NaN / ±inf / negative
705
/// kerning), the run-splitting predicates (which use `==` on `f32`), the UTF-8 slicing
706
/// in the PDF codepoint extraction, and the inline-box fragment post-pass.
707
///
708
/// Fixtures use `units_per_em == 0` metrics on purpose: that makes
709
/// `get_item_vertical_metrics_approx` skip the glyph, so ascent is exactly `0.0` and the
710
/// baseline lands exactly on `item.position.y`. Every asserted coordinate is therefore
711
/// exact rather than approximate.
712
///
713
/// Where a function has surprising-but-real behaviour, the test PINS it and says so
714
/// (see `pdf_cluster_offset_inside_multibyte_char_panics` and
715
/// `pdf_unknown_font_glyph_does_not_advance_the_pen`, both of which are genuine bugs).
716
///
717
/// Note: `Point`'s `PartialEq` is `round_eq` (rounds to `isize`), so all coordinate
718
/// assertions compare the raw `f32` fields instead of whole `Point`s.
719
#[cfg(test)]
720
#[allow(
721
    clippy::float_cmp,
722
    clippy::too_many_lines,
723
    clippy::unreadable_literal,
724
    clippy::similar_names,
725
    clippy::cast_precision_loss,
726
    clippy::cast_possible_truncation
727
)]
728
mod autotest_generated {
729
    use std::sync::Arc;
730

            
731
    use azul_core::geom::LogicalSize;
732
    use rust_fontconfig::FontId;
733

            
734
    use super::*;
735
    use crate::text3::{
736
        cache::{
737
            BidiDirection, BreakType, ClearType, ContentIndex, Glyph, GlyphKind, GraphemeClusterId,
738
            InlineBreak, InlineContent, InlineSpace, LayoutError, LayoutFontMetrics, OverflowInfo,
739
            PositionedItem, Rect, ShallowClone, ShapedCluster, StyleProperties, TextDecoration,
740
            VerticalMetrics, WritingMode,
741
        },
742
        script::{Language, Script},
743
    };
744

            
745
    const FONT_A: u64 = 0xAAAA_AAAA;
746
    const FONT_B: u64 = 0xBBBB_BBBB;
747

            
748
    // ---------------------------------------------------------------------
749
    // Fixtures
750
    // ---------------------------------------------------------------------
751

            
752
    /// `units_per_em == 0` => `get_item_vertical_metrics_approx` returns `(0.0, 0.0)`,
753
    /// so `baseline_y == item.position.y` and every coordinate below is exact.
754
    fn zero_metrics() -> LayoutFontMetrics {
755
        LayoutFontMetrics {
756
            ascent: 0.0,
757
            descent: 0.0,
758
            line_gap: 0.0,
759
            units_per_em: 0,
760
            x_height: None,
761
            cap_height: None,
762
        }
763
    }
764

            
765
    fn style() -> Arc<StyleProperties> {
766
        Arc::new(StyleProperties::default())
767
    }
768

            
769
    fn styled(f: impl FnOnce(&mut StyleProperties)) -> Arc<StyleProperties> {
770
        let mut s = StyleProperties::default();
771
        f(&mut s);
772
        Arc::new(s)
773
    }
774

            
775
    fn rgba(r: u8, g: u8, b: u8, a: u8) -> ColorU {
776
        ColorU { r, g, b, a }
777
    }
778

            
779
    /// A glyph with the standard degenerate metrics, sitting at font `FONT_A`.
780
    fn glyph(glyph_id: u16, advance: f32, st: &Arc<StyleProperties>) -> ShapedGlyph {
781
        ShapedGlyph {
782
            kind: GlyphKind::Character,
783
            glyph_id,
784
            cluster_offset: 0,
785
            advance,
786
            kerning: 0.0,
787
            offset: Point { x: 0.0, y: 0.0 },
788
            vertical_advance: 0.0,
789
            vertical_offset: Point { x: 0.0, y: 0.0 },
790
            script: Script::Latin,
791
            font_hash: FONT_A,
792
            font_metrics: zero_metrics(),
793
        }
794
    }
795

            
796
    /// Returns the `ShapedCluster` (not the `ShapedItem`) so tests can override
797
    /// `direction` / `style` / `text` before wrapping it with [`item`].
798
    fn cluster(text: &str, glyphs: Vec<ShapedGlyph>, st: &Arc<StyleProperties>) -> ShapedCluster {
799
        ShapedCluster {
800
            flags: crate::text3::cache::ClusterFlags::classify(text),
801
            source_text: Arc::from(text),
802
            source_byte_len: text.len() as u16,
803
            source_cluster_id: GraphemeClusterId {
804
                source_run: 0,
805
                start_byte_in_run: 0,
806
            },
807
            source_content_index: ContentIndex {
808
                run_index: 0,
809
                item_index: 0,
810
            },
811
            source_node_id: None,
812
            glyphs: glyphs.into_iter().collect(),
813
            advance: 0.0,
814
            direction: BidiDirection::Ltr,
815
            style: st.clone(),
816
            marker_position_outside: None,
817
            is_first_fragment: true,
818
            is_last_fragment: true,
819
        }
820
    }
821

            
822
    fn item(c: ShapedCluster) -> ShapedItem {
823
        ShapedItem::Cluster(c)
824
    }
825

            
826
    fn combined(glyphs: Vec<ShapedGlyph>) -> ShapedItem {
827
        ShapedItem::CombinedBlock {
828
            style: Arc::new(StyleProperties::default()),
829
            source: ContentIndex {
830
                run_index: 0,
831
                item_index: 0,
832
            },
833
            glyphs: glyphs.into_iter().collect(),
834
            // height 0 keeps the fallback ascent (`0.8 * height`) at exactly 0.
835
            bounds: Rect {
836
                x: 0.0,
837
                y: 0.0,
838
                width: 0.0,
839
                height: 0.0,
840
            },
841
            baseline_offset: 0.0,
842
        }
843
    }
844

            
845
    fn tab() -> ShapedItem {
846
        ShapedItem::Tab {
847
            source: ContentIndex {
848
                run_index: 0,
849
                item_index: 0,
850
            },
851
            bounds: Rect {
852
                x: 0.0,
853
                y: 0.0,
854
                width: 8.0,
855
                height: 0.0,
856
            },
857
        }
858
    }
859

            
860
    fn hard_break() -> ShapedItem {
861
        ShapedItem::Break {
862
            source: ContentIndex {
863
                run_index: 0,
864
                item_index: 0,
865
            },
866
            break_info: InlineBreak {
867
                break_type: BreakType::Hard,
868
                clear: ClearType::None,
869
                content_index: 0,
870
            },
871
        }
872
    }
873

            
874
    fn object() -> ShapedItem {
875
        ShapedItem::Object {
876
            source: ContentIndex {
877
                run_index: 0,
878
                item_index: 0,
879
            },
880
            bounds: Rect {
881
                x: 0.0,
882
                y: 0.0,
883
                width: 10.0,
884
                height: 10.0,
885
            },
886
            baseline_offset: 0.0,
887
            content: InlineContent::Space(InlineSpace {
888
                width: 10.0,
889
                is_breaking: false,
890
                is_stretchy: false,
891
            }),
892
        }
893
    }
894

            
895
    fn at(i: ShapedItem, x: f32, y: f32, line_index: usize) -> PositionedItem {
896
        PositionedItem {
897
            item: i,
898
            position: Point { x, y },
899
            line_index,
900
        }
901
    }
902

            
903
    fn layout(items: Vec<PositionedItem>) -> UnifiedLayout {
904
        UnifiedLayout {
905
            items,
906
            overflow: OverflowInfo::default(),
907
        }
908
    }
909

            
910
    fn border() -> InlineBorderInfo {
911
        InlineBorderInfo {
912
            left: 2.0,
913
            right: 2.0,
914
            ..InlineBorderInfo::default()
915
        }
916
    }
917

            
918
    /// A minimal in-memory `ParsedFontTrait` so `LoadedFonts` can be populated
919
    /// without touching the filesystem or fontconfig.
920
    #[derive(Debug, Clone)]
921
    struct TestFont {
922
        hash: u64,
923
    }
924

            
925
    impl ShallowClone for TestFont {
926
        fn shallow_clone(&self) -> Self {
927
            self.clone()
928
        }
929
    }
930

            
931
    impl ParsedFontTrait for TestFont {
932
        fn shape_text(
933
            &self,
934
            _text: &str,
935
            _script: Script,
936
            _language: Language,
937
            _direction: BidiDirection,
938
            _style: &StyleProperties,
939
        ) -> Result<Vec<Glyph>, LayoutError> {
940
            Ok(Vec::new())
941
        }
942
        fn get_hash(&self) -> u64 {
943
            self.hash
944
        }
945
        fn get_glyph_size(&self, _glyph_id: u16, font_size: f32) -> Option<LogicalSize> {
946
            Some(LogicalSize {
947
                width: font_size,
948
                height: font_size,
949
            })
950
        }
951
        fn get_hyphen_glyph_and_advance(&self, font_size: f32) -> Option<(u16, f32)> {
952
            Some((1, font_size * 0.3))
953
        }
954
        fn get_kashida_glyph_and_advance(&self, font_size: f32) -> Option<(u16, f32)> {
955
            Some((2, font_size * 0.2))
956
        }
957
        fn has_glyph(&self, _codepoint: u32) -> bool {
958
            true
959
        }
960
        fn get_vertical_metrics(&self, _glyph_id: u16) -> Option<VerticalMetrics> {
961
            None
962
        }
963
        fn get_font_metrics(&self) -> LayoutFontMetrics {
964
            zero_metrics()
965
        }
966
        fn num_glyphs(&self) -> u16 {
967
            10
968
        }
969
        fn get_space_width(&self) -> Option<usize> {
970
            Some(500)
971
        }
972
    }
973

            
974
    fn fonts_with(hashes: &[u64]) -> LoadedFonts<TestFont> {
975
        let mut fonts = LoadedFonts::new();
976
        for &h in hashes {
977
            fonts.insert(FontId::new(), TestFont { hash: h });
978
        }
979
        fonts
980
    }
981

            
982
    fn no_fonts() -> LoadedFonts<TestFont> {
983
        LoadedFonts::new()
984
    }
985

            
986
    // =====================================================================
987
    // get_glyph_positions
988
    // =====================================================================
989

            
990
    #[test]
991
    fn positions_empty_layout_yields_no_glyphs() {
992
        assert!(get_glyph_positions(&layout(Vec::new())).is_empty());
993
    }
994

            
995
    #[test]
996
    fn positions_ignore_non_text_items() {
997
        // Object / Tab / Break carry no glyphs and must be skipped, not panicked on.
998
        let l = layout(vec![
999
            at(object(), 0.0, 0.0, 0),
            at(tab(), 10.0, 0.0, 0),
            at(hard_break(), 20.0, 0.0, 0),
        ]);
        assert!(get_glyph_positions(&l).is_empty());
    }
    #[test]
    fn positions_cluster_without_glyphs_yields_nothing() {
        let st = style();
        let l = layout(vec![at(item(cluster("abc", Vec::new(), &st)), 0.0, 0.0, 0)]);
        assert!(get_glyph_positions(&l).is_empty());
    }
    #[test]
    fn positions_pen_advances_by_advance_plus_kerning() {
        let st = style();
        let mut g0 = glyph(1, 10.0, &st);
        g0.kerning = 2.0;
        let mut g1 = glyph(2, 10.0, &st);
        g1.kerning = 2.0;
        let g2 = glyph(3, 10.0, &st);
        let l = layout(vec![at(
            item(cluster("abc", vec![g0, g1, g2], &st)),
            100.0,
            50.0,
            0,
        )]);
        let out = get_glyph_positions(&l);
        assert_eq!(out.len(), 3);
        assert_eq!(out[0].position.x, 100.0);
        assert_eq!(out[1].position.x, 112.0, "advance 10 + kerning 2");
        assert_eq!(out[2].position.x, 124.0);
        // upem == 0 => ascent == 0 => baseline == item.position.y, exactly.
        for g in &out {
            assert_eq!(g.position.y, 50.0);
        }
    }
    #[test]
    fn positions_negative_kerning_walks_the_pen_backwards() {
        // Kerning is unbounded below; a tighter-than-advance kern makes x decrease.
        let st = style();
        let mut g = glyph(1, 10.0, &st);
        g.kerning = -12.0;
        let l = layout(vec![at(
            item(cluster("aaa", vec![g.clone(), g.clone(), g], &st)),
            0.0,
            0.0,
            0,
        )]);
        let out = get_glyph_positions(&l);
        assert_eq!(out[0].position.x, 0.0);
        assert_eq!(out[1].position.x, -2.0);
        assert_eq!(out[2].position.x, -4.0);
    }
    #[test]
    fn positions_gpos_y_offset_is_subtracted_in_y_down_space() {
        let st = style();
        let mut g = glyph(1, 10.0, &st);
        g.offset = Point { x: 3.0, y: 7.0 };
        let l = layout(vec![at(item(cluster("a", vec![g], &st)), 0.0, 100.0, 0)]);
        let out = get_glyph_positions(&l);
        assert_eq!(out[0].position.x, 3.0, "x offset is added");
        assert_eq!(
            out[0].position.y, 93.0,
            "positive GPOS y (up) subtracts in Y-down space"
        );
    }
    #[test]
    fn positions_combined_block_glyphs_do_not_stack_at_one_x() {
        // Regression: CombinedBlock carries raw advances, so the pen must accumulate
        // across the whole slice instead of resetting per glyph.
        let st = style();
        let l = layout(vec![at(
            combined(vec![glyph(1, 10.0, &st), glyph(2, 10.0, &st)]),
            100.0,
            0.0,
            0,
        )]);
        let out = get_glyph_positions(&l);
        assert_eq!(out.len(), 2);
        assert_eq!(out[0].position.x, 100.0);
        assert_eq!(out[1].position.x, 110.0);
    }
    #[test]
    fn positions_round_trip_glyph_id_and_advance_verbatim() {
        let st = style();
        let mut g = glyph(u16::MAX, f32::MIN_POSITIVE, &st);
        g.advance = f32::MIN_POSITIVE;
        let l = layout(vec![at(
            item(cluster("\u{10FFFF}", vec![g], &st)),
            0.0,
            0.0,
            0,
        )]);
        let out = get_glyph_positions(&l);
        assert_eq!(
            out[0].glyph_id,
            u16::MAX,
            "glyph id is copied, not truncated"
        );
        assert_eq!(
            out[0].advance,
            f32::MIN_POSITIVE,
            "advance is copied verbatim"
        );
    }
    #[test]
    fn positions_nan_advance_poisons_later_glyphs_but_does_not_panic() {
        let st = style();
        let l = layout(vec![at(
            item(cluster(
                "ab",
                vec![glyph(1, f32::NAN, &st), glyph(2, 10.0, &st)],
                &st,
            )),
            0.0,
            0.0,
            0,
        )]);
        let out = get_glyph_positions(&l);
        assert_eq!(out.len(), 2);
        assert_eq!(
            out[0].position.x, 0.0,
            "first glyph is placed before the NaN advance"
        );
        assert!(
            out[1].position.x.is_nan(),
            "NaN advance propagates into the pen — pinned, not fixed"
        );
    }
    #[test]
    fn positions_huge_advances_saturate_to_infinity_without_panicking() {
        let st = style();
        let l = layout(vec![at(
            item(cluster(
                "abc",
                vec![
                    glyph(1, f32::MAX, &st),
                    glyph(2, f32::MAX, &st),
                    glyph(3, 1.0, &st),
                ],
                &st,
            )),
            0.0,
            0.0,
            0,
        )]);
        let out = get_glyph_positions(&l);
        assert_eq!(out[0].position.x, 0.0);
        assert_eq!(out[1].position.x, f32::MAX);
        assert!(
            out[2].position.x.is_infinite() && out[2].position.x.is_sign_positive(),
            "f32 saturates on overflow instead of wrapping/panicking"
        );
    }
    #[test]
    fn positions_ten_thousand_glyphs_do_not_overflow() {
        let st = style();
        let glyphs: Vec<ShapedGlyph> = (0..10_000u32)
            .map(|i| glyph((i % 65536) as u16, 1.0, &st))
            .collect();
        let l = layout(vec![at(item(cluster("x", glyphs, &st)), 0.0, 0.0, 0)]);
        let out = get_glyph_positions(&l);
        assert_eq!(out.len(), 10_000);
        assert_eq!(
            out[9_999].position.x, 9_999.0,
            "integral f32 accumulation is exact here"
        );
    }
    #[test]
    fn positions_pen_resets_at_each_item_origin() {
        let st = style();
        let l = layout(vec![
            at(
                item(cluster("a", vec![glyph(1, 10.0, &st)], &st)),
                0.0,
                0.0,
                0,
            ),
            at(
                item(cluster("b", vec![glyph(2, 10.0, &st)], &st)),
                200.0,
                30.0,
                1,
            ),
        ]);
        let out = get_glyph_positions(&l);
        assert_eq!(
            out[1].position.x, 200.0,
            "pen restarts from the item origin"
        );
        assert_eq!(out[1].position.y, 30.0);
    }
    // =====================================================================
    // get_glyph_runs_simple
    // =====================================================================
    #[test]
    fn simple_empty_layout_yields_no_runs() {
        assert!(get_glyph_runs_simple(&layout(Vec::new())).is_empty());
    }
    #[test]
    fn simple_non_text_items_yield_no_runs() {
        let l = layout(vec![
            at(object(), 0.0, 0.0, 0),
            at(tab(), 0.0, 0.0, 0),
            at(hard_break(), 0.0, 0.0, 0),
        ]);
        assert!(get_glyph_runs_simple(&l).is_empty());
    }
    #[test]
    fn simple_uniform_glyphs_merge_into_one_run_across_items() {
        // The current run is NOT flushed at item boundaries — only on a style change.
        let st = style();
        let l = layout(vec![
            at(
                item(cluster(
                    "ab",
                    vec![glyph(1, 10.0, &st), glyph(2, 10.0, &st)],
                    &st,
                )),
                0.0,
                0.0,
                0,
            ),
            at(
                item(cluster(
                    "cd",
                    vec![glyph(3, 10.0, &st), glyph(4, 10.0, &st)],
                    &st,
                )),
                50.0,
                0.0,
                1,
            ),
        ]);
        let runs = get_glyph_runs_simple(&l);
        assert_eq!(
            runs.len(),
            1,
            "identical style => one run, even across lines"
        );
        assert_eq!(runs[0].glyphs.len(), 4);
        assert_eq!(
            runs[0].glyphs[2].point.x, 50.0,
            "pen still restarts per item"
        );
    }
    #[test]
    fn simple_color_change_splits_the_run() {
        let a = styled(|s| s.color = rgba(255, 0, 0, 255));
        let b = styled(|s| s.color = rgba(0, 0, 255, 255));
        let l = layout(vec![
            // (2026-08-10, per-glyph style removed: a style change can only
            // occur at a CLUSTER boundary — the pipeline splits runs by style
            // BEFORE shaping — so this fixture uses one cluster per style,
            // the only shape the engine can actually produce.)
            at(
                item(cluster("a", vec![glyph(1, 10.0, &a)], &a)),
                0.0,
                0.0,
                0,
            ),
            at(
                item(cluster("b", vec![glyph(2, 10.0, &b)], &b)),
                10.0,
                0.0,
                0,
            ),
        ]);
        let runs = get_glyph_runs_simple(&l);
        assert_eq!(runs.len(), 2);
        assert_eq!(runs[0].color, rgba(255, 0, 0, 255));
        assert_eq!(runs[1].color, rgba(0, 0, 255, 255));
    }
    #[test]
    fn simple_font_hash_change_splits_the_run() {
        let st = style();
        let mut g1 = glyph(2, 10.0, &st);
        g1.font_hash = FONT_B;
        let l = layout(vec![at(
            item(cluster("ab", vec![glyph(1, 10.0, &st), g1], &st)),
            0.0,
            0.0,
            0,
        )]);
        let runs = get_glyph_runs_simple(&l);
        assert_eq!(runs.len(), 2);
        assert_eq!(runs[0].font_hash, FONT_A);
        assert_eq!(runs[1].font_hash, FONT_B);
    }
    #[test]
    fn simple_font_size_and_decoration_changes_split_the_run() {
        let a = style();
        let b = styled(|s| s.font_size_px = 24.0);
        let c = styled(|s| {
            s.font_size_px = 24.0;
            s.text_decoration = TextDecoration {
                underline: true,
                strikethrough: false,
                overline: false,
            };
        });
        let l = layout(vec![
            // (2026-08-10, per-glyph style removed: a style change can only
            // occur at a CLUSTER boundary — the pipeline splits runs by style
            // BEFORE shaping — so this fixture uses one cluster per style,
            // the only shape the engine can actually produce.)
            at(
                item(cluster("a", vec![glyph(1, 10.0, &a)], &a)),
                0.0,
                0.0,
                0,
            ),
            at(
                item(cluster("b", vec![glyph(2, 10.0, &b)], &b)),
                10.0,
                0.0,
                0,
            ),
            at(
                item(cluster("c", vec![glyph(3, 10.0, &c)], &c)),
                20.0,
                0.0,
                0,
            ),
        ]);
        let runs = get_glyph_runs_simple(&l);
        assert_eq!(
            runs.len(),
            3,
            "size change and decoration change both break"
        );
        assert_eq!(runs[0].font_size_px, 16.0);
        assert_eq!(runs[1].font_size_px, 24.0);
        assert!(runs[2].text_decoration.underline);
    }
    #[test]
    fn simple_background_content_change_splits_the_run() {
        let a = style();
        let b = styled(|s| {
            s.background_content = vec![StyleBackgroundContent::Color(rgba(1, 2, 3, 4))];
        });
        let l = layout(vec![
            // (2026-08-10, per-glyph style removed: a style change can only
            // occur at a CLUSTER boundary — the pipeline splits runs by style
            // BEFORE shaping — so this fixture uses one cluster per style,
            // the only shape the engine can actually produce.)
            at(
                item(cluster("a", vec![glyph(1, 10.0, &a)], &a)),
                0.0,
                0.0,
                0,
            ),
            at(
                item(cluster("b", vec![glyph(2, 10.0, &b)], &b)),
                10.0,
                0.0,
                0,
            ),
        ]);
        let runs = get_glyph_runs_simple(&l);
        assert_eq!(runs.len(), 2);
        assert!(runs[0].background_content.is_empty());
        assert_eq!(runs[1].background_content.len(), 1);
    }
    #[test]
    fn simple_source_node_id_change_splits_the_run() {
        let st = style();
        let mut c0 = cluster("a", vec![glyph(1, 10.0, &st)], &st);
        c0.source_node_id = Some(NodeId::new(3));
        let mut c1 = cluster("b", vec![glyph(2, 10.0, &st)], &st);
        c1.source_node_id = Some(NodeId::new(4));
        let l = layout(vec![at(item(c0), 0.0, 0.0, 0), at(item(c1), 10.0, 0.0, 0)]);
        let runs = get_glyph_runs_simple(&l);
        assert_eq!(
            runs.len(),
            2,
            "hit-testing identity must not be merged away"
        );
        assert_eq!(runs[0].source_node_id, Some(NodeId::new(3)));
        assert_eq!(runs[1].source_node_id, Some(NodeId::new(4)));
    }
    #[test]
    fn simple_nan_font_size_forces_one_run_per_glyph() {
        // The run predicate compares font sizes with `==`. NaN != NaN, so a NaN
        // font-size defeats run coalescing entirely: N glyphs => N runs.
        let nan = styled(|s| s.font_size_px = f32::NAN);
        let l = layout(vec![at(
            item(cluster(
                "abc",
                vec![
                    glyph(1, 10.0, &nan),
                    glyph(2, 10.0, &nan),
                    glyph(3, 10.0, &nan),
                ],
                &nan,
            )),
            0.0,
            0.0,
            0,
        )]);
        let runs = get_glyph_runs_simple(&l);
        assert_eq!(runs.len(), 3, "NaN never compares equal => no coalescing");
        assert!(runs.iter().all(|r| r.glyphs.len() == 1));
    }
    #[test]
    fn simple_combined_block_with_no_glyphs_is_a_no_op() {
        // `glyphs.first()` is None => the default writing mode is used and nothing
        // is emitted. Must not panic on the empty slice.
        let l = layout(vec![at(combined(Vec::new()), 0.0, 0.0, 0)]);
        assert!(get_glyph_runs_simple(&l).is_empty());
    }
    #[test]
    fn simple_never_marks_runs_as_ime_preview() {
        let st = style();
        let l = layout(vec![at(
            item(cluster("a", vec![glyph(1, 10.0, &st)], &st)),
            0.0,
            0.0,
            0,
        )]);
        let runs = get_glyph_runs_simple(&l);
        assert!(!runs[0].is_ime_preview, "this path never sets the IME flag");
    }
    #[test]
    fn simple_run_glyphs_agree_with_get_glyph_positions() {
        // Cross-function invariant: both walk Cluster + CombinedBlock with the same
        // pen arithmetic, so the flattened runs must match the positions 1:1.
        let st = style();
        let l = layout(vec![
            at(
                item(cluster(
                    "ab",
                    vec![glyph(1, 10.0, &st), glyph(2, 7.5, &st)],
                    &st,
                )),
                12.0,
                40.0,
                0,
            ),
            at(tab(), 30.0, 40.0, 0),
            at(
                combined(vec![glyph(3, 5.0, &st), glyph(4, 5.0, &st)]),
                60.0,
                80.0,
                1,
            ),
        ]);
        let positions = get_glyph_positions(&l);
        let flat: Vec<GlyphInstance> = get_glyph_runs_simple(&l)
            .into_iter()
            .flat_map(|r| r.glyphs)
            .collect();
        assert_eq!(flat.len(), positions.len(), "same glyph count");
        assert_eq!(flat.len(), 4, "the Tab contributes nothing");
        for (inst, pos) in flat.iter().zip(positions.iter()) {
            assert_eq!(inst.index, u32::from(pos.glyph_id));
            assert_eq!(inst.point.x, pos.position.x);
            assert_eq!(inst.point.y, pos.position.y);
        }
    }
    // --- inline-box split post-pass (CSS 2.2 §9.4.2) ----------------------
    /// n same-node bordered clusters whose only difference is colour => n runs.
    fn bordered_fragments(n: usize) -> UnifiedLayout {
        let node = NodeId::new(7);
        let items = (0..n)
            .map(|i| {
                let st = styled(|s| {
                    s.border = Some(border());
                    s.color = rgba(u8::try_from(i % 256).unwrap_or(0), 0, 0, 255);
                });
                let mut c = cluster("x", vec![glyph(1, 10.0, &st)], &st);
                c.source_node_id = Some(node);
                at(item(c), i as f32 * 10.0, 0.0, i)
            })
            .collect();
        layout(items)
    }
    #[test]
    fn simple_two_fragment_split_suppresses_the_inner_edges() {
        let runs = get_glyph_runs_simple(&bordered_fragments(2));
        assert_eq!(runs.len(), 2);
        let first = runs[0].border.expect("border survives run splitting");
        let last = runs[1].border.expect("border survives run splitting");
        assert!(first.is_first_fragment && !first.is_last_fragment);
        assert!(!last.is_first_fragment && last.is_last_fragment);
    }
    #[test]
    fn simple_three_fragment_split_strips_both_edges_from_the_middle() {
        let runs = get_glyph_runs_simple(&bordered_fragments(3));
        assert_eq!(runs.len(), 3);
        let mid = runs[1].border.expect("border survives run splitting");
        assert!(
            !mid.is_first_fragment && !mid.is_last_fragment,
            "an intermediate fragment draws neither the start nor the end edge"
        );
        assert!(!runs[0].border.unwrap().is_last_fragment);
        assert!(!runs[2].border.unwrap().is_first_fragment);
    }
    #[test]
    fn simple_fragment_scan_terminates_on_a_long_run_chain() {
        // The post-pass advances `i = end` and `continue`s; guard against a
        // non-advancing scan by driving 64 consecutive same-node fragments.
        let runs = get_glyph_runs_simple(&bordered_fragments(64));
        assert_eq!(runs.len(), 64);
        assert!(!runs[0].border.unwrap().is_last_fragment);
        assert!(!runs[63].border.unwrap().is_first_fragment);
        for r in &runs[1..63] {
            let b = r.border.unwrap();
            assert!(!b.is_first_fragment && !b.is_last_fragment);
        }
    }
    #[test]
    fn simple_border_without_source_node_id_is_left_untouched() {
        // No node id => the fragments cannot be proven to belong to one inline box,
        // so both edges stay drawn.
        let a = styled(|s| {
            s.border = Some(border());
            s.color = rgba(255, 0, 0, 255);
        });
        let b = styled(|s| {
            s.border = Some(border());
            s.color = rgba(0, 255, 0, 255);
        });
        let l = layout(vec![
            // (2026-08-10, per-glyph style removed: a style change can only
            // occur at a CLUSTER boundary — the pipeline splits runs by style
            // BEFORE shaping — so this fixture uses one cluster per style,
            // the only shape the engine can actually produce.)
            at(
                item(cluster("a", vec![glyph(1, 10.0, &a)], &a)),
                0.0,
                0.0,
                0,
            ),
            at(
                item(cluster("b", vec![glyph(2, 10.0, &b)], &b)),
                10.0,
                0.0,
                0,
            ),
        ]);
        let runs = get_glyph_runs_simple(&l);
        assert_eq!(runs.len(), 2);
        for r in &runs {
            let bd = r.border.unwrap();
            assert!(bd.is_first_fragment && bd.is_last_fragment);
        }
    }
    #[test]
    fn simple_single_bordered_run_keeps_both_edges() {
        let runs = get_glyph_runs_simple(&bordered_fragments(1));
        assert_eq!(runs.len(), 1);
        let b = runs[0].border.unwrap();
        assert!(
            b.is_first_fragment && b.is_last_fragment,
            "an unsplit inline box draws both edges"
        );
    }
    // =====================================================================
    // get_glyph_runs_pdf
    // =====================================================================
    #[test]
    fn pdf_empty_layout_yields_no_runs() {
        let runs = get_glyph_runs_pdf(&layout(Vec::new()), &fonts_with(&[FONT_A]));
        assert!(runs.is_empty());
    }
    #[test]
    fn pdf_glyphs_with_unknown_fonts_are_dropped() {
        let st = style();
        let l = layout(vec![at(
            item(cluster(
                "ab",
                vec![glyph(1, 10.0, &st), glyph(2, 10.0, &st)],
                &st,
            )),
            0.0,
            0.0,
            0,
        )]);
        assert!(
            get_glyph_runs_pdf(&l, &no_fonts()).is_empty(),
            "no font => no run (glyphs are skipped, not defaulted)"
        );
    }
    #[test]
    fn pdf_ignores_combined_blocks_unlike_get_glyph_positions() {
        // Tate-chu-yoko blocks are silently dropped by the PDF path.
        let st = style();
        let l = layout(vec![at(
            combined(vec![glyph(1, 10.0, &st), glyph(2, 10.0, &st)]),
            0.0,
            0.0,
            0,
        )]);
        assert_eq!(get_glyph_positions(&l).len(), 2);
        assert!(
            get_glyph_runs_pdf(&l, &fonts_with(&[FONT_A])).is_empty(),
            "CombinedBlock never reaches the PDF run builder"
        );
    }
    #[test]
    fn pdf_empty_and_non_text_items_are_skipped() {
        let st = style();
        let l = layout(vec![
            at(item(cluster("", Vec::new(), &st)), 0.0, 0.0, 0),
            at(tab(), 0.0, 0.0, 0),
            at(hard_break(), 0.0, 0.0, 0),
            at(object(), 0.0, 0.0, 0),
            at(
                item(cluster("a", vec![glyph(1, 10.0, &st)], &st)),
                5.0,
                0.0,
                0,
            ),
        ]);
        let runs = get_glyph_runs_pdf(&l, &fonts_with(&[FONT_A]));
        assert_eq!(runs.len(), 1, "only the one real cluster survives");
        assert_eq!(runs[0].glyphs.len(), 1);
    }
    #[test]
    fn pdf_single_glyph_cluster_maps_the_whole_cluster_text() {
        let st = style();
        let l = layout(vec![at(
            item(cluster("\u{1F600}", vec![glyph(1, 10.0, &st)], &st)),
            0.0,
            0.0,
            0,
        )]);
        let runs = get_glyph_runs_pdf(&l, &fonts_with(&[FONT_A]));
        assert_eq!(
            runs[0].glyphs[0].unicode_codepoint, "\u{1F600}",
            "a 1:1 cluster carries its full (astral) text for ToUnicode"
        );
    }
    #[test]
    fn pdf_multi_glyph_cluster_offset_past_the_end_falls_back() {
        // byte_offset >= len => whole text for glyph 0, empty for the rest.
        let st = style();
        let mut g0 = glyph(1, 10.0, &st);
        g0.cluster_offset = 99;
        let mut g1 = glyph(2, 10.0, &st);
        g1.cluster_offset = 99;
        let l = layout(vec![at(
            item(cluster("ab", vec![g0, g1], &st)),
            0.0,
            0.0,
            0,
        )]);
        let runs = get_glyph_runs_pdf(&l, &fonts_with(&[FONT_A]));
        assert_eq!(runs[0].glyphs[0].unicode_codepoint, "ab");
        assert_eq!(runs[0].glyphs[1].unicode_codepoint, "");
    }
    #[test]
    fn pdf_cluster_offset_u32_max_does_not_overflow() {
        let st = style();
        let mut g0 = glyph(1, 10.0, &st);
        g0.cluster_offset = u32::MAX;
        let mut g1 = glyph(2, 10.0, &st);
        g1.cluster_offset = u32::MAX;
        let l = layout(vec![at(
            item(cluster("ab", vec![g0, g1], &st)),
            0.0,
            0.0,
            0,
        )]);
        let runs = get_glyph_runs_pdf(&l, &fonts_with(&[FONT_A]));
        // `u32::MAX as usize` is not < 2, so both take the out-of-range fallback.
        assert_eq!(runs[0].glyphs[0].unicode_codepoint, "ab");
        assert_eq!(runs[0].glyphs[1].unicode_codepoint, "");
    }
    #[test]
    fn pdf_empty_cluster_text_with_several_glyphs_yields_empty_codepoints() {
        let st = style();
        let l = layout(vec![at(
            item(cluster(
                "",
                vec![glyph(1, 10.0, &st), glyph(2, 10.0, &st)],
                &st,
            )),
            0.0,
            0.0,
            0,
        )]);
        let runs = get_glyph_runs_pdf(&l, &fonts_with(&[FONT_A]));
        assert_eq!(runs[0].glyphs.len(), 2);
        assert!(runs[0]
            .glyphs
            .iter()
            .all(|g| g.unicode_codepoint.is_empty()));
    }
    /// BUG (pinned): the codepoint extractor slices `cluster_text[byte_offset..]`
    /// after only checking `byte_offset < len`, never that the offset is a UTF-8
    /// char boundary. A multi-glyph cluster over a multi-byte character (any
    /// decomposed/combining sequence where the shaper reports a mid-char offset)
    /// therefore panics inside `get_glyph_runs_pdf` instead of degrading.
    /// The correct behaviour would be `is_char_boundary()` + fallback.
    #[test]
    #[should_panic(expected = "char boundary")]
    fn pdf_cluster_offset_inside_multibyte_char_panics() {
        let st = style();
        let g0 = glyph(1, 10.0, &st); // cluster_offset 0 — fine
        let mut g1 = glyph(2, 10.0, &st);
        g1.cluster_offset = 1; // 1 < 2, but it is inside 'é'
        let l = layout(vec![at(item(cluster("é", vec![g0, g1], &st)), 0.0, 0.0, 0)]);
        let _ = get_glyph_runs_pdf(&l, &fonts_with(&[FONT_A]));
    }
    /// BUG (pinned): the `continue` that drops an unknown-font glyph happens BEFORE
    /// `pen_x += advance + kerning`, so every glyph after a dropped one is rendered
    /// one advance too far to the left. A font that fails to load silently shifts
    /// the rest of the cluster instead of just omitting a glyph.
    #[test]
    fn pdf_unknown_font_glyph_does_not_advance_the_pen() {
        let st = style();
        let mut g0 = glyph(1, 40.0, &st);
        g0.font_hash = FONT_B; // not in LoadedFonts
        let g1 = glyph(2, 10.0, &st); // FONT_A
        let l = layout(vec![at(
            item(cluster("ab", vec![g0, g1], &st)),
            100.0,
            0.0,
            0,
        )]);
        let runs = get_glyph_runs_pdf(&l, &fonts_with(&[FONT_A]));
        assert_eq!(runs.len(), 1);
        assert_eq!(runs[0].glyphs.len(), 1, "the unknown-font glyph is dropped");
        assert_eq!(
            runs[0].glyphs[0].position.x, 100.0,
            "pinned: the surviving glyph sits at the origin — the dropped glyph's 40px advance \
             was never applied, so it renders 40px too far left"
        );
    }
    #[test]
    fn pdf_line_index_change_breaks_the_run() {
        let st = style();
        let l = layout(vec![
            at(
                item(cluster("a", vec![glyph(1, 10.0, &st)], &st)),
                0.0,
                0.0,
                0,
            ),
            at(
                item(cluster("b", vec![glyph(2, 10.0, &st)], &st)),
                0.0,
                20.0,
                1,
            ),
        ]);
        let runs = get_glyph_runs_pdf(&l, &fonts_with(&[FONT_A]));
        assert_eq!(runs.len(), 2, "runs must not straddle a line boundary");
        assert_eq!(runs[0].line_index, 0);
        assert_eq!(runs[1].line_index, 1);
    }
    #[test]
    fn pdf_direction_change_breaks_the_run() {
        let st = style();
        let ltr = cluster("a", vec![glyph(1, 10.0, &st)], &st);
        let mut rtl = cluster("\u{05D0}", vec![glyph(2, 10.0, &st)], &st);
        rtl.direction = BidiDirection::Rtl;
        let l = layout(vec![
            at(item(ltr), 0.0, 0.0, 0),
            at(item(rtl), 10.0, 0.0, 0),
        ]);
        let runs = get_glyph_runs_pdf(&l, &fonts_with(&[FONT_A]));
        assert_eq!(runs.len(), 2);
        assert_eq!(runs[0].direction, BidiDirection::Ltr);
        assert_eq!(runs[1].direction, BidiDirection::Rtl);
    }
    #[test]
    fn pdf_writing_mode_change_breaks_the_run() {
        // writing_mode is read from the CLUSTER style while size/colour come from the
        // GLYPH style — this pins that the cluster-level property still breaks runs.
        let st = style();
        let vertical = styled(|s| s.writing_mode = WritingMode::VerticalRl);
        let horiz = cluster("a", vec![glyph(1, 10.0, &st)], &st);
        let mut vert = cluster("b", vec![glyph(2, 10.0, &st)], &st);
        vert.style = vertical;
        let l = layout(vec![
            at(item(horiz), 0.0, 0.0, 0),
            at(item(vert), 10.0, 0.0, 0),
        ]);
        let runs = get_glyph_runs_pdf(&l, &fonts_with(&[FONT_A]));
        assert_eq!(runs.len(), 2);
        assert_eq!(runs[0].writing_mode, WritingMode::HorizontalTb);
        assert_eq!(runs[1].writing_mode, WritingMode::VerticalRl);
    }
    #[test]
    fn pdf_background_color_change_breaks_the_run() {
        let plain = style();
        let highlighted = styled(|s| s.background_color = Some(rgba(255, 255, 0, 255)));
        let l = layout(vec![
            // (2026-08-10, per-glyph style removed: a style change can only
            // occur at a CLUSTER boundary — the pipeline splits runs by style
            // BEFORE shaping — so this fixture uses one cluster per style,
            // the only shape the engine can actually produce.)
            at(
                item(cluster("a", vec![glyph(1, 10.0, &plain)], &plain)),
                0.0,
                0.0,
                0,
            ),
            at(
                item(cluster(
                    "b",
                    vec![glyph(2, 10.0, &highlighted)],
                    &highlighted,
                )),
                10.0,
                0.0,
                0,
            ),
        ]);
        let runs = get_glyph_runs_pdf(&l, &fonts_with(&[FONT_A]));
        assert_eq!(
            runs.len(),
            2,
            "inline <span> background must get its own run"
        );
        assert_eq!(runs[0].background_color, None);
        assert_eq!(runs[1].background_color, Some(rgba(255, 255, 0, 255)));
    }
    #[test]
    fn pdf_nan_font_size_breaks_every_glyph_into_its_own_run() {
        // `run.font_size_px != font_size_px` is always TRUE for NaN, so coalescing
        // is defeated — the mirror image of `simple_nan_font_size_forces_one_run_per_glyph`.
        let nan = styled(|s| s.font_size_px = f32::NAN);
        let l = layout(vec![at(
            item(cluster(
                "abc",
                vec![
                    glyph(1, 10.0, &nan),
                    glyph(2, 10.0, &nan),
                    glyph(3, 10.0, &nan),
                ],
                &nan,
            )),
            0.0,
            0.0,
            0,
        )]);
        let runs = get_glyph_runs_pdf(&l, &fonts_with(&[FONT_A]));
        assert_eq!(runs.len(), 3);
    }
    #[test]
    fn pdf_cluster_texts_are_parallel_to_glyphs() {
        // Every run must be able to map glyph i back to its cluster text.
        let st = style();
        let l = layout(vec![
            at(
                item(cluster(
                    "ab",
                    vec![glyph(1, 10.0, &st), glyph(2, 10.0, &st)],
                    &st,
                )),
                0.0,
                0.0,
                0,
            ),
            at(
                item(cluster("c", vec![glyph(3, 10.0, &st)], &st)),
                20.0,
                0.0,
                0,
            ),
        ]);
        let runs = get_glyph_runs_pdf(&l, &fonts_with(&[FONT_A]));
        assert_eq!(runs.len(), 1, "same style + same line => one run");
        assert_eq!(
            runs[0].cluster_texts.len(),
            runs[0].glyphs.len(),
            "cluster_texts is per-glyph, not per-cluster"
        );
        assert_eq!(runs[0].cluster_texts, vec!["ab", "ab", "c"]);
    }
    #[test]
    fn pdf_baseline_start_is_the_pen_before_the_gpos_offset() {
        let st = style();
        let mut g = glyph(1, 10.0, &st);
        g.offset = Point { x: 5.0, y: 2.0 };
        let l = layout(vec![at(item(cluster("a", vec![g], &st)), 100.0, 20.0, 0)]);
        let runs = get_glyph_runs_pdf(&l, &fonts_with(&[FONT_A]));
        assert_eq!(
            runs[0].baseline_start.x, 100.0,
            "text matrix origin excludes GPOS x"
        );
        assert_eq!(
            runs[0].baseline_start.y, 20.0,
            "baseline == item y (ascent 0)"
        );
        assert_eq!(
            runs[0].glyphs[0].position.x, 105.0,
            "the glyph itself carries GPOS x"
        );
        assert_eq!(
            runs[0].glyphs[0].position.y, 18.0,
            "GPOS y is subtracted (Y-down)"
        );
    }
    #[test]
    fn pdf_pen_accumulates_advance_plus_kerning_within_a_cluster() {
        let st = style();
        let mut g0 = glyph(1, 10.0, &st);
        g0.kerning = -3.0;
        let g1 = glyph(2, 10.0, &st);
        let l = layout(vec![at(
            item(cluster("ab", vec![g0, g1], &st)),
            0.0,
            0.0,
            0,
        )]);
        let runs = get_glyph_runs_pdf(&l, &fonts_with(&[FONT_A]));
        assert_eq!(runs[0].glyphs[0].position.x, 0.0);
        assert_eq!(runs[0].glyphs[1].position.x, 7.0, "advance 10 + kerning -3");
    }
    #[test]
    fn pdf_infinite_advance_does_not_panic() {
        let st = style();
        let l = layout(vec![at(
            item(cluster(
                "ab",
                vec![glyph(1, f32::INFINITY, &st), glyph(2, 10.0, &st)],
                &st,
            )),
            0.0,
            0.0,
            0,
        )]);
        let runs = get_glyph_runs_pdf(&l, &fonts_with(&[FONT_A]));
        assert_eq!(runs[0].glyphs.len(), 2);
        assert!(runs[0].glyphs[1].position.x.is_infinite());
        assert!(
            runs[0].glyphs[0].advance.is_infinite(),
            "advance is copied verbatim"
        );
    }
    // ==================================================================
    // #25: compact glyph-run roundtrip exactness
    // ==================================================================
    fn gi(index: u32, x: f32, y: f32, w: f32, h: f32) -> GlyphInstance {
        GlyphInstance {
            index,
            point: LogicalPosition { x, y },
            size: LogicalSize {
                width: w,
                height: h,
            },
        }
    }
    fn roundtrip(v: Vec<GlyphInstance>) -> (CompactGlyphs, Vec<GlyphInstance>) {
        let c = CompactGlyphs::from_instances(&v);
        let out: Vec<GlyphInstance> = c.iter().collect();
        (c, out)
    }
    /// Bit-exact instance equality (NaN-tolerant — the derived `==` is not).
    fn instances_bit_equal(a: &[GlyphInstance], b: &[GlyphInstance]) -> bool {
        let f = |x: f32, y: f32| x.to_bits() == y.to_bits();
        a.len() == b.len()
            && a.iter().zip(b.iter()).all(|(g, h)| {
                g.index == h.index
                    && f(g.point.x, h.point.x)
                    && f(g.point.y, h.point.y)
                    && f(g.size.width, h.size.width)
                    && f(g.size.height, h.size.height)
            })
    }
    #[test]
    fn compact_glyphs_roundtrips_a_uniform_run_with_no_exceptions() {
        let v = vec![
            gi(5, 0.0, 12.5, 0.0, 0.0),
            gi(9, 6.0, 12.5, 0.0, 0.0),
            gi(2, 11.0, 12.5, 0.0, 0.0),
        ];
        let (c, out) = roundtrip(v.clone());
        assert!(instances_bit_equal(&v, &out));
        assert!(
            c.exceptions.is_empty(),
            "uniform y/size must compact without exceptions — the whole point of the encoding \
             (got {} exceptions)",
            c.exceptions.len()
        );
        assert_eq!(c.len(), 3);
        assert!(instances_bit_equal(&[c.first().unwrap()], &v[..1]));
        assert!(instances_bit_equal(&[c.last().unwrap()], &v[2..]));
    }
    #[test]
    fn compact_glyphs_routes_y_deviants_through_exceptions_exactly() {
        // A combining mark with a vertical offset: y deviates mid-run.
        let v = vec![
            gi(1, 0.0, 10.0, 0.0, 0.0),
            gi(2, 6.0, 7.25, 0.0, 0.0), // mark, raised
            gi(3, 6.0, 10.0, 0.0, 0.0),
        ];
        let (c, out) = roundtrip(v.clone());
        assert!(instances_bit_equal(&v, &out));
        assert_eq!(c.exceptions.len(), 1);
        assert_eq!(c.exceptions[0].0, 1);
    }
    #[test]
    fn compact_glyphs_first_exception_covers_the_shared_slot_choice() {
        // The FIRST glyph defines the shared y — a later majority does not
        // re-vote. Glyph 0 deviating from the rest must still roundtrip.
        let v = vec![
            gi(1, 0.0, 3.0, 0.0, 0.0),
            gi(2, 5.0, 9.0, 0.0, 0.0),
            gi(3, 9.0, 9.0, 0.0, 0.0),
        ];
        let (c, out) = roundtrip(v.clone());
        assert!(instances_bit_equal(&v, &out));
        // shared y = 3.0 (first), so glyphs 1..3 are the exceptions.
        assert_eq!(c.exceptions.len(), 2);
        assert!(instances_bit_equal(&[c.first().unwrap()], &v[..1]));
        assert!(instances_bit_equal(&[c.last().unwrap()], &v[2..]));
    }
    #[test]
    fn compact_glyphs_roundtrips_nan_and_size_deviants() {
        // NaN y: to_bits comparison makes it an exception (NaN != NaN under
        // `==`, which would silently mark EVERY glyph exceptional or none).
        let v = vec![
            gi(1, 0.0, f32::NAN, 1.0, 2.0),
            gi(2, 4.0, f32::NAN, 1.0, 2.0),
            gi(3, 8.0, f32::NAN, 3.0, 2.0), // size deviates too
        ];
        let (c, out) = roundtrip(v.clone());
        assert!(instances_bit_equal(&v, &out));
        // Same-bit NaNs MATCH the shared slot (bit compare): only the size
        // deviant is an exception.
        assert_eq!(c.exceptions.len(), 1);
        assert_eq!(c.exceptions[0].0, 2);
    }
    #[test]
    fn compact_glyphs_empty_run_is_empty() {
        let (c, out) = roundtrip(Vec::new());
        assert!(c.is_empty());
        assert!(out.is_empty());
        assert!(c.first().is_none());
        assert!(c.last().is_none());
        assert_eq!(c.retained_bytes(), 0);
    }
    #[test]
    fn compact_glyphs_offset_expansion_matches_manual_offset() {
        let v = vec![gi(1, 1.0, 2.0, 0.0, 0.0), gi(2, 3.5, 2.0, 0.0, 0.0)];
        let c = CompactGlyphs::from_instances(&v);
        let shifted = c.to_vec_offset(10.0, 20.0);
        let manual: Vec<GlyphInstance> = v
            .iter()
            .map(|g| {
                let mut g = *g;
                g.point.x += 10.0;
                g.point.y += 20.0;
                g
            })
            .collect();
        assert!(instances_bit_equal(&shifted, &manual));
    }
    #[test]
    fn compact_run_roundtrip_preserves_the_header() {
        let style = styled(|s| {
            s.color = rgba(10, 20, 30, 255);
        });
        let l = layout(vec![at(
            item(cluster(
                "ab",
                vec![glyph(4, 6.0, &style), glyph(7, 6.0, &style)],
                &style,
            )),
            0.0,
            0.0,
            0,
        )]);
        let runs = get_glyph_runs_simple(&l);
        assert_eq!(runs.len(), 1);
        let compact = CompactGlyphRun::from(runs[0].clone());
        assert!(
            simple_runs_bit_equal(&compact.expand(), &runs[0]),
            "builder-produced run must roundtrip bit-exactly"
        );
    }
}