1
//! DENSE TEXT MODEL — compact-record text types, introduced ALONGSIDE the
2
//! current `PositionedItem`/`ShapedCluster` model rather than replacing it.
3
//!
4
//! Nothing consumes these yet: this module stakes the types, their size
5
//! pins live in `tests/struct_sizes.rs`, and [`DenseText::from_unified`]
6
//! is the bridge that lets consumers migrate one at a time while the
7
//! equivalence test (`text3_dense_equivalence.rs`) proves the conversion
8
//! loses nothing the current model knows. The plan's own gates (T1
9
//! source-reproduction + id-integrity, T2 cache identity, the shaping
10
//! goldens) all pin the semantics this model must preserve.
11
//!
12
//! Per-record budget vs the current model, from the plan's §3.5/§3.6
13
//! arithmetic: `ClusterCompact` is 16 B against today's ~200 B
14
//! `PositionedItem` chain, with run-level data amortised over ~42
15
//! clusters/run and per-glyph detail only where ligatures / marks /
16
//! GPOS offsets actually occur.
17

            
18
use alloc::{sync::Arc, vec::Vec};
19

            
20
use azul_core::{
21
    dom::NodeId,
22
    geom::{LogicalPosition, LogicalSize},
23
    ui_solver::GlyphInstance,
24
};
25

            
26
use super::{
27
    cache::{
28
        BidiDirection, ClusterFlags, LayoutFontMetrics, LoadedFonts, ParsedFontTrait, Point,
29
        PositionedItem, ShapedItem, StyleProperties, UnifiedLayout,
30
    },
31
    glyphs::{PdfGlyphRun, PdfPositionedGlyph, PositionedGlyph, SimpleGlyphRun},
32
};
33
use crate::text3::script::Script;
34

            
35
/// One per shaped cluster. Dense, POD, no Drop glue, no owned heap.
36
#[repr(C)]
37
#[derive(Debug, Copy, Clone, PartialEq)]
38
pub struct ClusterCompact {
39
    /// Glyph to draw when the cluster has no detail entry.
40
    pub glyph_id: u16,
41
    /// Precomputed classification — the same word the retained cluster
42
    /// carries since 48c9bbcdf.
43
    pub flags: ClusterFlags,
44
    /// The cluster's BASE advance — equal to the sparse cluster's
45
    /// `advance` and to `ShapedItem::bounds().width` (d2 redefinition;
46
    /// was kerning-folded). Sound because a kerned cluster ALWAYS has a
47
    /// detail entry (`needs_detail` includes kerning != 0), and every
48
    /// walker derives detail-cluster pens from `DetailGlyph.advance`
49
    /// (kerning-folded there), never from this field.
50
    pub advance: f32,
51
    /// == `GraphemeClusterId::start_byte_in_run`; the run supplies
52
    /// `source_run`, so the id reconstructs exactly.
53
    pub start_byte: u32,
54
    /// Inline-axis position within the IFC; `y` comes from the line.
55
    pub x: f32,
56
}
57

            
58
/// One per shaped RUN (~one per 42 clusters on the measured corpus):
59
/// everything that is uniform across a run, amortised.
60
#[derive(Debug, Clone)]
61
pub struct DenseRun {
62
    pub style: Arc<StyleProperties>,
63
    pub font_hash: u64,
64
    /// ONE copy per run (today: one 32-B copy per GLYPH).
65
    pub font_metrics: LayoutFontMetrics,
66
    pub source_run: u32,
67
    /// Dense index into the DOM node table; `u32::MAX` = none.
68
    pub source_node: u32,
69
    /// The run's source text, shared — the single copy that replaces
70
    /// every per-cluster `String`.
71
    pub text: Arc<str>,
72
    /// Range into [`DenseText::clusters`].
73
    pub clusters: core::ops::Range<u32>,
74
    /// (d6h) Reconstructs a cluster's `source_content_index.item_index`:
75
    /// `item_base + start_byte` when [`Self::item_linear`], else
76
    /// `item_base` verbatim. (0/linear for plain runs; the segment offset
77
    /// for override-segmented runs, closing the §10 "item-index-blind"
78
    /// gap.)
79
    pub item_base: u32,
80
    /// (#25b) Which item-index model this run follows. `true` = the
81
    /// linear post-layout model (`item_base + start_byte`); `false` =
82
    /// CONSTANT `item_base` for every cluster — the shape produced by
83
    /// paths that never restamp `item_index` per cluster. Before this
84
    /// flag, a constant-index run DEGENERATED into one run per cluster
85
    /// (the linear delta changed every cluster), ~25 KB/IFC of `DenseRun`
86
    /// headers for zero information.
87
    pub item_linear: bool,
88
    pub script: Script,
89
    /// Bidi direction — uniform per run BY CONSTRUCTION (the builder
90
    /// splits on it): mixed-bidi text in one styled run must not share a
91
    /// dense run, both for the PDF walker's run predicate and for RTL
92
    /// border-fragment assignment.
93
    pub direction: BidiDirection,
94
    /// The item's own solved block-axis position (`PositionedItem.position.y`),
95
    /// amortised per run because the builder splits on it.
96
    ///
97
    /// This exists because "y comes from the line" is FALSE. `LineRecord`
98
    /// stores one y, frozen from whichever cluster opened the line, and every
99
    /// walker that reconstructed a baseline as `line.top_y + ascent` silently
100
    /// assumed every cluster on the line shared that y. A line mixing font
101
    /// sizes breaks it: the taller run sits on a different baseline, and its
102
    /// glyphs were emitted 12.8px off at 16px/32px (and 1.98px off on the
103
    /// real-world mixed-font line that exposed this). The sparse reference
104
    /// always used the ITEM's own `position.y`; this is that value, kept at
105
    /// run granularity so the amortisation still holds — runs are ~1 per 42
106
    /// clusters, and y changes exactly where the run already splits (style,
107
    /// font metrics), so in practice this costs no extra runs at all.
108
    pub y: f32,
109
}
110

            
111
/// One per line: replaces per-cluster `line_index` + `position.y`.
112
#[derive(Debug, Clone, Copy, PartialEq)]
113
pub struct LineRecord {
114
    pub clusters: (u32, u32),
115
    pub baseline_y: f32,
116
    pub top_y: f32,
117
    pub height: f32,
118
    /// The source `PositionedItem::line_index` — kept because record
119
    /// ORDINALS diverge from it when a line carries no clusters (only
120
    /// objects), and the PDF walker reports/breaks on the source index.
121
    pub source_index: u32,
122
}
123

            
124
/// Detail entry for clusters that need more than one glyph or non-zero
125
/// GPOS offsets (ligatures, combining marks, kashida).
126
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
127
pub struct ClusterDetail {
128
    pub cluster: u32,
129
    pub glyphs: (u32, u32),
130
    /// (d4) The cluster's SOURCE byte length. Needed because a
131
    /// ligature-fused cluster spans multiple graphemes, so
132
    /// "next grapheme boundary" under-measures it; simple clusters
133
    /// reconstruct their length grapheme-exactly (T1) and stay 16 B.
134
    pub byte_len: u32,
135
}
136

            
137
#[repr(C)]
138
#[derive(Debug, Copy, Clone, PartialEq)]
139
pub struct DetailGlyph {
140
    pub glyph_id: u16,
141
    pub cluster_offset: u16,
142
    /// Advance incl. kerning.
143
    pub advance: f32,
144
    pub offset_x: f32,
145
    pub offset_y: f32,
146
    /// (d6h) The kerning HALF of `advance` — walkers keep consuming the
147
    /// folded `advance`; the sparse expander un-folds via this.
148
    pub kerning: f32,
149
    /// (d6h) `ShapedGlyph::kind` — non-Character kinds (hyphen …) force
150
    /// a detail entry so the expander can reproduce them.
151
    pub kind: super::cache::GlyphKind,
152
    /// (d6h) Vertical-text pair, exact-roundtrip completeness.
153
    pub vertical_advance: f32,
154
    pub vertical_offset_x: f32,
155
    pub vertical_offset_y: f32,
156
}
157

            
158
/// The dense view of a laid-out IFC. Step 1: derived FROM the current
159
/// `UnifiedLayout`; later steps make this the source of truth.
160
#[derive(Debug, Clone, Default)]
161
pub struct DenseText {
162
    pub clusters: Vec<ClusterCompact>,
163
    pub runs: Vec<DenseRun>,
164
    pub lines: Vec<LineRecord>,
165
    pub details: Vec<ClusterDetail>,
166
    pub detail_glyphs: Vec<DetailGlyph>,
167
}
168

            
169
impl Default for LineRecord {
170
    fn default() -> Self {
171
        Self {
172
            clusters: (0, 0),
173
            baseline_y: 0.0,
174
            top_y: 0.0,
175
            height: 0.0,
176
            source_index: 0,
177
        }
178
    }
179
}
180

            
181
/// (#25b) Finalize a closing run's item-index model from the surviving
182
/// viability bases. Linear preferred when both hold (single-cluster runs
183
/// then keep the pre-#25b encoding byte-for-byte). At least one base is
184
/// always `Some` — the split above opens a fresh run (both seeded) the
185
/// moment neither model fits.
186
199057
fn close_item_model(r: &mut DenseRun, linear: Option<u32>, constant: Option<u32>) {
187
199057
    match (linear, constant) {
188
11323
        (Some(b), _) => {
189
11323
            r.item_base = b;
190
11323
            r.item_linear = true;
191
11323
        }
192
187734
        (None, Some(b)) => {
193
187734
            r.item_base = b;
194
187734
            r.item_linear = false;
195
187734
        }
196
        (None, None) => {
197
            debug_assert!(false, "a run closed with no surviving item model");
198
            r.item_base = 0;
199
            r.item_linear = true;
200
        }
201
    }
202
199057
}
203

            
204
impl DenseText {
205
    /// Build the dense view from the current model. Clusters keep their
206
    /// item order; runs split where (style Arc identity, `font_hash` of the
207
    /// first glyph, `source_run`, `source_node`) change; lines come from the
208
    /// items' `line_index`. Non-cluster items (objects, breaks, combined
209
    /// blocks, tabs) are SKIPPED here — they stay on the sparse side per
210
    /// the plan's `AtomicItem` design and migrate in a later step.
211
    #[must_use]
212
167466
    pub fn from_unified(layout: &UnifiedLayout) -> Self {
213
167466
        Self::from_unified_with_content(layout, &[])
214
167466
    }
215

            
216
    /// Identical to [`Self::from_unified`] — the `content` parameter is
217
    /// IGNORED since 3c: every cluster carries its logical item's shared
218
    /// text Arc (`ShapedCluster::source_text`), which is the text its
219
    /// `start_byte` actually indexes (correct for override-segmented
220
    /// runs, where the old `content.get(source_run)` mapping was not).
221
    /// Kept for signature compatibility with the gate tests.
222
    #[must_use]
223
167916
    pub fn from_unified_with_content(
224
167916
        layout: &UnifiedLayout,
225
167916
        content: &[super::cache::InlineContent],
226
167916
    ) -> Self {
227
167916
        let _ = content;
228
167916
        let mut dense = Self::default();
229
167916
        let mut current_run: Option<DenseRun> = None;
230
167916
        let mut current_line: Option<(usize, LineRecord)> = None;
231
        // The current run's resolved line height — the d3 fill for
232
        // `LineRecord.height` (max over the line's clusters).
233
167916
        let mut current_run_lh = 0.0f32;
234
        // (#25b) The open run's still-viable item-index models: LINEAR
235
        // base (item_index − start_byte of the seed cluster) and CONSTANT
236
        // base (the seed's item_index). `None` = that model already broke
237
        // mid-run. Finalized into the run at close by `close_item_model`.
238
167916
        let mut item_run_linear_base: Option<u32> = None;
239
167916
        let mut item_run_const_base: Option<u32> = None;
240

            
241
2950640
        for item in &layout.items {
242
            let PositionedItem {
243
2782724
                item: shaped,
244
2782724
                position,
245
2782724
                line_index,
246
2782724
            } = item;
247
2782724
            let ShapedItem::Cluster(c) = shaped else {
248
1485
                continue;
249
            };
250
2781239
            let first_glyph = c.glyphs.first();
251
2781239
            let font_hash = first_glyph.map_or(0, |g| g.font_hash);
252
2781239
            let font_metrics = first_glyph.map_or(
253
2781239
                LayoutFontMetrics {
254
2781239
                    ascent: 0.0,
255
2781239
                    descent: 0.0,
256
2781239
                    cap_height: None,
257
2781239
                    x_height: None,
258
2781239
                    line_gap: 0.0,
259
2781239
                    units_per_em: 0,
260
2781239
                },
261
                |g| g.font_metrics,
262
            );
263
2781239
            let source_node = c
264
2781239
                .source_node_id
265
2781239
                .map_or(u32::MAX, |n| u32::try_from(n.index()).unwrap_or(u32::MAX));
266
2781239
            let script = first_glyph.map_or(Script::Latin, |g| g.script);
267
2781239
            let cluster_index = u32::try_from(dense.clusters.len()).unwrap_or(u32::MAX);
268

            
269
            // Run split on any amortised-field change. The source-text
270
            // Arc identity is part of the predicate since 3c: clusters
271
            // carry their LOGICAL ITEM's shared Arc (offset-correct for
272
            // override-segmented runs, where the old content.get(run)
273
            // mapping was wrong — §10 finding 1), and one item's clusters
274
            // all share one Arc by construction.
275
            // (d6h/#25b) Item-index model viability for the OPEN run.
276
            // Two models can reconstruct item_index: LINEAR
277
            // (item_base + start_byte — the post-layout restamped shape)
278
            // and CONSTANT (item_base verbatim — paths that never restamp
279
            // per cluster). The run stays open while EITHER still holds;
280
            // close picks linear when both do (single-cluster runs keep
281
            // today's encoding). Before this, a constant-index run split
282
            // on EVERY cluster (the linear delta changed each time) —
283
            // one DenseRun header per cluster for zero information.
284
            // wrapping arithmetic keeps a malformed (item_index <
285
            // start_byte) pair from panicking — the split still isolates
286
            // it when neither model fits.
287
2781239
            let item_index = c.source_content_index.item_index;
288
2781239
            let start_byte = c.source_cluster_id.start_byte_in_run;
289
2781239
            let fits_linear =
290
2781239
                item_run_linear_base.is_some_and(|b| item_index == b.wrapping_add(start_byte));
291
2781239
            let fits_const = item_run_const_base.is_some_and(|b| item_index == b);
292
2781239
            let split = match &current_run {
293
166529
                None => true,
294
2614710
                Some(r) => {
295
2614710
                    !Arc::ptr_eq(&r.style, &c.style)
296
2613969
                        || !Arc::ptr_eq(&r.text, &c.source_text)
297
2611879
                        || r.font_hash != font_hash
298
2611789
                        || r.source_run != c.source_cluster_id.source_run
299
2611789
                        || r.source_node != source_node
300
2611789
                        || r.direction != c.direction
301
                        // The item's own y is amortised on the run, so a
302
                        // change in it MUST open a new run — otherwise the
303
                        // run's y would silently describe only its first
304
                        // cluster, which is the per-line freeze one level down.
305
2611789
                        || (r.y - position.y).abs() > 0.001
306
2582182
                        || (!fits_linear && !fits_const)
307
                }
308
            };
309
2781239
            if split {
310
199057
                if let Some(mut r) = current_run.take() {
311
32528
                    r.clusters.end = cluster_index;
312
32528
                    close_item_model(&mut r, item_run_linear_base, item_run_const_base);
313
32528
                    dense.runs.push(r);
314
166529
                }
315
                // Fresh run: both models start viable, seeded from this
316
                // cluster.
317
199057
                item_run_linear_base = Some(item_index.wrapping_sub(start_byte));
318
199057
                item_run_const_base = Some(item_index);
319
199057
                current_run_lh = if font_metrics.units_per_em == 0 {
320
24
                    0.0
321
                } else {
322
199033
                    c.style
323
199033
                        .line_height
324
199033
                        .resolve_with_metrics(c.style.font_size_px, &font_metrics)
325
                };
326
199057
                current_run = Some(DenseRun {
327
199057
                    style: c.style.clone(),
328
199057
                    font_hash,
329
199057
                    font_metrics,
330
199057
                    source_run: c.source_cluster_id.source_run,
331
199057
                    source_node,
332
199057
                    // The cluster's own shared source Arc (3c) — the text
333
199057
                    // `ClusterCompact.start_byte` actually indexes into,
334
199057
                    // for EVERY case including override segments.
335
199057
                    text: c.source_text.clone(),
336
199057
                    clusters: cluster_index..cluster_index,
337
199057
                    // Placeholders — `close_item_model` writes the real
338
199057
                    // values from the surviving model at run close.
339
199057
                    item_base: 0,
340
199057
                    item_linear: true,
341
199057
                    script,
342
199057
                    direction: c.direction,
343
199057
                    y: position.y,
344
199057
                });
345
            } else {
346
                // Staying in the run: a cluster that fits only one model
347
                // permanently kills the other (viability is monotonic —
348
                // a broken model cannot come back later in the run).
349
2582182
                if !fits_linear {
350
2582152
                    item_run_linear_base = None;
351
2582152
                }
352
2582182
                if !fits_const {
353
20
                    item_run_const_base = None;
354
2582162
                }
355
            }
356

            
357
            // Line records from line_index transitions.
358
2614710
            match &mut current_line {
359
2614710
                Some((idx, rec)) if *idx == *line_index => {
360
2584453
                    rec.clusters.1 = cluster_index + 1;
361
2584453
                    rec.height = rec.height.max(current_run_lh);
362
2584453
                }
363
                _ => {
364
196786
                    if let Some((_, rec)) = current_line.take() {
365
30257
                        dense.lines.push(rec);
366
166529
                    }
367
196786
                    current_line = Some((
368
196786
                        *line_index,
369
196786
                        LineRecord {
370
196786
                            clusters: (cluster_index, cluster_index + 1),
371
196786
                            baseline_y: position.y,
372
196786
                            top_y: position.y,
373
196786
                            // d3: filled with the max resolved line height of
374
196786
                            // the line's clusters (was always 0.0).
375
196786
                            height: current_run_lh,
376
196786
                            source_index: u32::try_from(*line_index).unwrap_or(u32::MAX),
377
196786
                        },
378
196786
                    ));
379
                }
380
            }
381

            
382
            // Detail side table for multi-glyph / offset clusters —
383
            // (d6h) non-Character kinds and vertical metrics also force
384
            // an entry so the sparse expander loses nothing.
385
            //
386
            // A cluster without a detail entry is reconstructed ENTIRELY from
387
            // the compact record, and the compact record has no byte length —
388
            // `cluster_byte_len` falls back to "the next grapheme at
389
            // start_byte". So a detail is also required whenever the cluster's
390
            // true `source_byte_len` is NOT that grapheme length. The case
391
            // that makes this reachable is a LIGATURE: "fi" fused into
392
            // exactly one glyph with no offsets, no kerning, kind Character —
393
            // satisfying none of the other clauses — while spanning TWO
394
            // graphemes. Without this clause every such cluster silently
395
            // shrank to its first grapheme on the way through the dense
396
            // model, and pdftotext read "Confgure" out of documents that
397
            // said "Configure". `ShapedCluster::source_byte_len`'s doc states
398
            // the invariant: "Stored, not re-derived: ligature-fused clusters
399
            // span MULTIPLE graphemes, so 'next grapheme boundary' cannot
400
            // reconstruct the slice in general." This mirrors the READ-side
401
            // fallback exactly, so predicate and fallback cannot disagree.
402
2781239
            let compact_len_reconstructible = {
403
                use unicode_segmentation::UnicodeSegmentation;
404
2781239
                let start = c.source_cluster_id.start_byte_in_run as usize;
405
2781239
                let grapheme_len = c
406
2781239
                    .source_text
407
2781239
                    .get(start..)
408
2781239
                    .and_then(|s| s.graphemes(true).next())
409
2781239
                    .map_or(0, str::len);
410
2781239
                usize::from(c.source_byte_len) == grapheme_len
411
            };
412
2781239
            let needs_detail = c.glyphs.len() != 1
413
2781228
                || !compact_len_reconstructible
414
2779761
                || c.glyphs.first().is_some_and(|g| {
415
2779761
                    g.offset.x != 0.0
416
2779761
                        || g.offset.y != 0.0
417
2779761
                        || g.kerning != 0.0
418
2743495
                        || g.kind != super::cache::GlyphKind::Character
419
2743455
                        || g.vertical_advance != 0.0
420
2743385
                        || g.vertical_offset.x != 0.0
421
2743385
                        || g.vertical_offset.y != 0.0
422
2779761
                });
423
2781239
            if needs_detail {
424
37854
                let start = u32::try_from(dense.detail_glyphs.len()).unwrap_or(u32::MAX);
425
75699
                for g in &c.glyphs {
426
37845
                    dense.detail_glyphs.push(DetailGlyph {
427
37845
                        glyph_id: g.glyph_id,
428
37845
                        cluster_offset: u16::try_from(g.cluster_offset).unwrap_or(u16::MAX),
429
37845
                        advance: g.advance + g.kerning,
430
37845
                        offset_x: g.offset.x,
431
37845
                        offset_y: g.offset.y,
432
37845
                        kerning: g.kerning,
433
37845
                        kind: g.kind,
434
37845
                        vertical_advance: g.vertical_advance,
435
37845
                        vertical_offset_x: g.vertical_offset.x,
436
37845
                        vertical_offset_y: g.vertical_offset.y,
437
37845
                    });
438
37845
                }
439
37854
                let end = u32::try_from(dense.detail_glyphs.len()).unwrap_or(u32::MAX);
440
37854
                dense.details.push(ClusterDetail {
441
37854
                    cluster: cluster_index,
442
37854
                    glyphs: (start, end),
443
37854
                    byte_len: u32::from(c.source_byte_len),
444
37854
                });
445
2743385
            }
446

            
447
            // (d6h) Bits 7-10 pack the ShapedCluster fields the compact
448
            // record has no room for — DENSE-SIDE ONLY (classify() never
449
            // sets them; equivalence pins mask them off).
450
2781239
            let mut packed = c.flags.0;
451
2781239
            if c.is_first_fragment {
452
2781209
                packed |= ClusterFlags::DENSE_IS_FIRST_FRAGMENT;
453
2781209
            }
454
2781239
            if c.is_last_fragment {
455
2781209
                packed |= ClusterFlags::DENSE_IS_LAST_FRAGMENT;
456
2781209
            }
457
2781239
            if let Some(outside) = c.marker_position_outside {
458
1560
                packed |= ClusterFlags::DENSE_MARKER_SOME;
459
1560
                if outside {
460
1560
                    packed |= ClusterFlags::DENSE_MARKER_OUTSIDE;
461
1560
                }
462
2779679
            }
463
2781239
            dense.clusters.push(ClusterCompact {
464
2781239
                glyph_id: first_glyph.map_or(0, |g| g.glyph_id),
465
2781239
                flags: ClusterFlags(packed),
466
2781239
                advance: c.advance,
467
2781239
                start_byte: c.source_cluster_id.start_byte_in_run,
468
2781239
                x: position.x,
469
            });
470
        }
471
167916
        if let Some(mut r) = current_run.take() {
472
166529
            r.clusters.end = u32::try_from(dense.clusters.len()).unwrap_or(u32::MAX);
473
166529
            close_item_model(&mut r, item_run_linear_base, item_run_const_base);
474
166529
            dense.runs.push(r);
475
166531
        }
476
167916
        if let Some((_, rec)) = current_line.take() {
477
166529
            dense.lines.push(rec);
478
166531
        }
479
167916
        dense
480
167916
    }
481

            
482
    /// (d4) The source byte length of cluster `ci`: the detail table's
483
    /// stored length when present (ligature clusters span multiple
484
    /// graphemes), else the grapheme at `start_byte` in the run text —
485
    /// exact for simple clusters by T1.
486
    #[must_use]
487
21228698
    pub fn cluster_byte_len(&self, ci: u32) -> u32 {
488
        use unicode_segmentation::UnicodeSegmentation;
489
21228698
        if let Ok(i) = self.details.binary_search_by_key(&ci, |d| d.cluster) {
490
540
            return self.details[i].byte_len;
491
21228158
        }
492
21228158
        let c = &self.clusters[ci as usize];
493
21228158
        let run = self
494
21228158
            .runs
495
21228158
            .iter()
496
40771388
            .find(|r| r.clusters.contains(&ci))
497
21228158
            .expect("cluster belongs to a run by construction");
498
21228158
        run.text
499
21228158
            .get(c.start_byte as usize..)
500
21228158
            .and_then(|s| s.graphemes(true).next())
501
21228158
            .map_or(0, |g| g.len() as u32)
502
21228698
    }
503

            
504
    /// (d6b) The caret-stop list — the PRIMITIVE the whole cursor-movement
505
    /// library reduces to (left/right/home/end are offset arithmetic over
506
    /// it; selection ranges bound by it). Same output as the sparse
507
    /// `UnifiedLayout::grapheme_stops`: cluster ids sorted by
508
    /// (run, byte), deduped, grapheme-continuation clusters excluded —
509
    /// via the precomputed flag instead of the text probe (the flags are
510
    /// pinned equal to the sparse classification by the base gate).
511
    #[must_use]
512
8290
    pub fn grapheme_stops(&self) -> Vec<azul_core::selection::GraphemeClusterId> {
513
        use azul_core::selection::GraphemeClusterId;
514
8290
        let mut stops: Vec<GraphemeClusterId> = self
515
8290
            .runs
516
8290
            .iter()
517
426380
            .flat_map(|r| (r.clusters.start..r.clusters.end).map(move |ci| (ci, r)))
518
426380
            .filter(|(ci, _)| {
519
426380
                !self.clusters[*ci as usize]
520
426380
                    .flags
521
426380
                    .has(ClusterFlags::GRAPHEME_CONTINUATION)
522
426380
            })
523
8290
            .map(|(ci, r)| GraphemeClusterId {
524
425870
                source_run: r.source_run,
525
425870
                start_byte_in_run: self.clusters[ci as usize].start_byte,
526
425870
            })
527
8290
            .collect();
528
835160
        stops.sort_by_key(|id| (id.source_run, id.start_byte_in_run));
529
8290
        stops.dedup();
530
8290
        stops
531
8290
    }
532

            
533
    /// (d6e) The cluster's source text slice (run text at `start_byte` for
534
    /// `cluster_byte_len` bytes) — the word-boundary predicate's input.
535
81350
    fn cluster_text_slice(&self, ci: u32) -> &str {
536
81350
        let c = &self.clusters[ci as usize];
537
81350
        let run = self
538
81350
            .runs
539
81350
            .iter()
540
266630
            .find(|r| r.clusters.contains(&ci))
541
81350
            .expect("cluster belongs to a run by construction");
542
81350
        let start = c.start_byte as usize;
543
81350
        let len = self.cluster_byte_len(ci) as usize;
544
81350
        run.text.get(start..start + len).unwrap_or("")
545
81350
    }
546

            
547
    /// (d6e) Word-boundary predicate — same as the sparse
548
    /// `cluster_is_word_boundary`: no word character in the cluster text
549
    /// (whitespace AND punctuation are boundaries).
550
81350
    fn cluster_is_word_boundary(&self, ci: u32) -> bool {
551
81350
        !self
552
81350
            .cluster_text_slice(ci)
553
81350
            .chars()
554
81350
            .any(super::cache::is_word_char)
555
81350
    }
556

            
557
    /// (d6e) Visual line start — cluster by id, min-x cluster on its
558
    /// line, Leading affinity (mirrors the sparse flow).
559
    #[must_use]
560
4350
    pub fn move_cursor_to_line_start(
561
4350
        &self,
562
4350
        cursor: azul_core::selection::TextCursor,
563
4350
    ) -> azul_core::selection::TextCursor {
564
        use azul_core::selection::{CursorAffinity, GraphemeClusterId, TextCursor};
565
4350
        let Some((_, line_ord)) = self.find_cursor_cluster(&cursor) else {
566
            return cursor;
567
        };
568
4350
        let l = &self.lines[line_ord];
569
67540
        let best = (l.clusters.0..l.clusters.1).min_by(|a, b| {
570
67540
            self.clusters[*a as usize]
571
67540
                .x
572
67540
                .partial_cmp(&self.clusters[*b as usize].x)
573
67540
                .unwrap_or(core::cmp::Ordering::Equal)
574
67540
        });
575
4350
        let Some(ci) = best else { return cursor };
576
13770
        let run = self.runs.iter().find(|r| r.clusters.contains(&ci));
577
4350
        let Some(run) = run else { return cursor };
578
4350
        TextCursor {
579
4350
            cluster_id: GraphemeClusterId {
580
4350
                source_run: run.source_run,
581
4350
                start_byte_in_run: self.clusters[ci as usize].start_byte,
582
4350
            },
583
4350
            affinity: CursorAffinity::Leading,
584
4350
        }
585
4350
    }
586

            
587
    /// (d6e) Visual line end — max-x cluster on the line, Trailing.
588
    #[must_use]
589
4340
    pub fn move_cursor_to_line_end(
590
4340
        &self,
591
4340
        cursor: azul_core::selection::TextCursor,
592
4340
    ) -> azul_core::selection::TextCursor {
593
        use azul_core::selection::{CursorAffinity, GraphemeClusterId, TextCursor};
594
4340
        let Some((_, line_ord)) = self.find_cursor_cluster(&cursor) else {
595
            return cursor;
596
        };
597
4340
        let l = &self.lines[line_ord];
598
67440
        let best = (l.clusters.0..l.clusters.1).max_by(|a, b| {
599
67440
            self.clusters[*a as usize]
600
67440
                .x
601
67440
                .partial_cmp(&self.clusters[*b as usize].x)
602
67440
                .unwrap_or(core::cmp::Ordering::Equal)
603
67440
        });
604
4340
        let Some(ci) = best else { return cursor };
605
13760
        let run = self.runs.iter().find(|r| r.clusters.contains(&ci));
606
4340
        let Some(run) = run else { return cursor };
607
4340
        TextCursor {
608
4340
            cluster_id: GraphemeClusterId {
609
4340
                source_run: run.source_run,
610
4340
                start_byte_in_run: self.clusters[ci as usize].start_byte,
611
4340
            },
612
4340
            affinity: CursorAffinity::Trailing,
613
4340
        }
614
4340
    }
615

            
616
    /// (d6e) Cursor at index `ci`, given affinity.
617
10610
    fn cursor_at_index(
618
10610
        &self,
619
10610
        ci: u32,
620
10610
        affinity: azul_core::selection::CursorAffinity,
621
10610
    ) -> Option<azul_core::selection::TextCursor> {
622
        use azul_core::selection::{GraphemeClusterId, TextCursor};
623
10610
        let c = self.clusters.get(ci as usize)?;
624
28160
        let run = self.runs.iter().find(|r| r.clusters.contains(&ci))?;
625
10610
        Some(TextCursor {
626
10610
            cluster_id: GraphemeClusterId {
627
10610
                source_run: run.source_run,
628
10610
                start_byte_in_run: c.start_byte,
629
10610
            },
630
10610
            affinity,
631
10610
        })
632
10610
    }
633

            
634
    /// (d6e) One word left — mirrors the sparse two-phase flow (skip
635
    /// boundary clusters, then skip the word, land Leading on its first
636
    /// cluster). Identical for pure-cluster layouts (the dense domain).
637
    #[must_use]
638
4340
    pub fn move_cursor_to_prev_word(
639
4340
        &self,
640
4340
        cursor: azul_core::selection::TextCursor,
641
4340
    ) -> azul_core::selection::TextCursor {
642
        use azul_core::selection::CursorAffinity;
643
4340
        let Some((current, _)) = self.find_cursor_cluster(&cursor) else {
644
            return cursor;
645
        };
646
4340
        let mut pos = if cursor.affinity == CursorAffinity::Leading {
647
2170
            current.checked_sub(1)
648
        } else {
649
2170
            Some(current)
650
        };
651
4830
        while let Some(p) = pos {
652
4790
            if !self.cluster_is_word_boundary(p) {
653
4300
                break;
654
490
            }
655
490
            pos = p.checked_sub(1);
656
        }
657
36080
        while let Some(p) = pos {
658
36040
            if self.cluster_is_word_boundary(p) {
659
4060
                if p + 1 < self.clusters.len() as u32 {
660
4060
                    if let Some(c) = self.cursor_at_index(p + 1, CursorAffinity::Leading) {
661
4060
                        return c;
662
                    }
663
                }
664
                break;
665
31980
            }
666
31980
            if p == 0 {
667
240
                if let Some(c) = self.cursor_at_index(0, CursorAffinity::Leading) {
668
240
                    return c;
669
                }
670
                break;
671
31740
            }
672
31740
            pos = p.checked_sub(1);
673
        }
674
40
        if pos.is_none() {
675
40
            if let Some(c) = self.cursor_at_index(0, CursorAffinity::Leading) {
676
40
                return c;
677
            }
678
        }
679
        cursor
680
4340
    }
681

            
682
    /// (d6h) The per-run resolved ascent — the baseline distance from an
683
    /// item's TOP (metrics + half-leading), the same math the walkers
684
    /// derive inline. What makes per-item `position.y` reconstructible
685
    /// on MIXED-SIZE lines: the d6h expansion gate caught that sparse
686
    /// `position.y` is per-item (baseline-aligned tops differ when font
687
    /// sizes mix), while the line record's y is only the FIRST item's.
688
    #[must_use]
689
109420
    pub fn resolved_run_ascent(run: &DenseRun) -> f32 {
690
109420
        let m = &run.font_metrics;
691
109420
        if m.units_per_em == 0 {
692
            return 0.0;
693
109420
        }
694
109420
        let scale = run.style.font_size_px / f32::from(m.units_per_em);
695
109420
        let font_ascent = m.ascent * scale;
696
109420
        let font_descent = (-m.descent * scale).max(0.0);
697
109420
        let ad = font_ascent + font_descent;
698
109420
        let lh = run
699
109420
            .style
700
109420
            .line_height
701
109420
            .resolve_with_metrics(run.style.font_size_px, m);
702
109420
        font_ascent + (lh - ad) / 2.0
703
109420
    }
704

            
705
    /// The run containing cluster `ci` (runs partition clusters in
706
    /// order, so this is a binary search).
707
    #[must_use]
708
21939094
    pub fn run_of(&self, ci: u32) -> Option<&DenseRun> {
709
47301123
        let idx = self.runs.partition_point(|r| r.clusters.end <= ci);
710
21939094
        self.runs.get(idx).filter(|r| r.clusters.contains(&ci))
711
21939094
    }
712

            
713
    /// (d6g, y-semantics fixed in d6h) The sparse `PositionedItem`
714
    /// fields for cluster `i`: `(x, y, line_index)`. `y` is the ITEM's
715
    /// top — the line record's recorded first-item top, baseline-aligned
716
    /// across mixed-size runs via the run ascents (same-run clusters
717
    /// reduce to the recorded value). `line_index` is the line's
718
    /// `source_index`. `None` when `i` is out of range.
719
    #[must_use]
720
1700
    pub fn positioned_cluster(&self, i: u32) -> Option<(f32, f32, usize)> {
721
1700
        let c = self.clusters.get(i as usize)?;
722
1690
        let li = self
723
1690
            .lines
724
3430
            .partition_point(|l| l.clusters.1 <= i)
725
1690
            .min(self.lines.len().checked_sub(1)?);
726
1690
        let line = &self.lines[li];
727
1690
        if i < line.clusters.0 || i >= line.clusters.1 {
728
            return None;
729
1690
        }
730
1690
        let first_run = self.run_of(line.clusters.0)?;
731
1690
        let my_run = self.run_of(i)?;
732
        // Same run ⟹ bit-exact recorded value (no float round-trip).
733
1690
        let y = if core::ptr::eq(first_run, my_run) {
734
1660
            line.baseline_y
735
        } else {
736
30
            line.baseline_y + Self::resolved_run_ascent(first_run)
737
30
                - Self::resolved_run_ascent(my_run)
738
        };
739
1690
        Some((c.x, y, line.source_index as usize))
740
1700
    }
741

            
742
    /// (d6h) FULL sparse materialization: rebuild the `PositionedItem`
743
    /// vec these arrays were built from — exact (`PartialEq`) for
744
    /// pure-cluster layouts, pinned by the equivalence gate. Transient:
745
    /// the page clipper (print/PDF) expands on demand once the retained
746
    /// sparse form retires; nothing stores the result.
747
    #[must_use]
748
451746
    pub fn to_unified_items(&self) -> Vec<PositionedItem> {
749
        use super::cache::{
750
            ClusterFlags, ContentIndex, GlyphKind, GraphemeClusterId, Point, ShapedCluster,
751
            ShapedGlyph, ShapedGlyphVec, ShapedItem,
752
        };
753
451746
        let mut out = Vec::with_capacity(self.clusters.len());
754
451746
        let mut line_cursor = 0usize;
755
451746
        let mut detail_cursor = 0usize;
756
1217980
        for run in &self.runs {
757
766234
            let source_node_id =
758
766234
                (run.source_node != u32::MAX).then(|| NodeId::new(run.source_node as usize));
759
21916894
            for ci in run.clusters.clone() {
760
21916894
                let c = &self.clusters[ci as usize];
761
22226672
                while line_cursor < self.lines.len() && self.lines[line_cursor].clusters.1 <= ci {
762
309778
                    line_cursor += 1;
763
309778
                }
764
21916894
                let line = &self.lines[line_cursor.min(self.lines.len().saturating_sub(1))];
765
22708630
                while detail_cursor < self.details.len() && self.details[detail_cursor].cluster < ci
766
791736
                {
767
791736
                    detail_cursor += 1;
768
791736
                }
769
21916894
                let detail = self.details.get(detail_cursor).filter(|d| d.cluster == ci);
770
21916894
                let glyphs: ShapedGlyphVec = match detail {
771
791766
                    Some(d) => (d.glyphs.0..d.glyphs.1)
772
791766
                        .map(|gi| {
773
791766
                            let dg = &self.detail_glyphs[gi as usize];
774
791766
                            ShapedGlyph {
775
791766
                                kind: dg.kind,
776
791766
                                glyph_id: dg.glyph_id,
777
791766
                                cluster_offset: u32::from(dg.cluster_offset),
778
791766
                                advance: dg.advance - dg.kerning,
779
791766
                                kerning: dg.kerning,
780
791766
                                offset: Point {
781
791766
                                    x: dg.offset_x,
782
791766
                                    y: dg.offset_y,
783
791766
                                },
784
791766
                                vertical_advance: dg.vertical_advance,
785
791766
                                vertical_offset: Point {
786
791766
                                    x: dg.vertical_offset_x,
787
791766
                                    y: dg.vertical_offset_y,
788
791766
                                },
789
791766
                                script: run.script,
790
791766
                                font_hash: run.font_hash,
791
791766
                                font_metrics: run.font_metrics,
792
791766
                            }
793
791766
                        })
794
791766
                        .collect(),
795
21125128
                    None => core::iter::once(ShapedGlyph {
796
21125128
                        kind: GlyphKind::Character,
797
21125128
                        glyph_id: c.glyph_id,
798
21125128
                        cluster_offset: 0,
799
21125128
                        advance: c.advance,
800
21125128
                        kerning: 0.0,
801
21125128
                        offset: Point { x: 0.0, y: 0.0 },
802
21125128
                        vertical_advance: 0.0,
803
21125128
                        vertical_offset: Point { x: 0.0, y: 0.0 },
804
21125128
                        script: run.script,
805
21125128
                        font_hash: run.font_hash,
806
21125128
                        font_metrics: run.font_metrics,
807
21125128
                    })
808
21125128
                    .collect(),
809
                };
810
21916894
                let byte_len = detail.map_or_else(|| self.cluster_byte_len(ci), |d| d.byte_len);
811
21916894
                let f = c.flags.0;
812
21916894
                out.push(PositionedItem {
813
                    item: ShapedItem::Cluster(ShapedCluster {
814
21916894
                        source_text: run.text.clone(),
815
21916894
                        source_byte_len: u16::try_from(byte_len).unwrap_or(u16::MAX),
816
21916894
                        source_cluster_id: GraphemeClusterId {
817
21916894
                            source_run: run.source_run,
818
21916894
                            start_byte_in_run: c.start_byte,
819
21916894
                        },
820
                        source_content_index: ContentIndex {
821
21916894
                            run_index: run.source_run,
822
                            // (#25b) Two reconstruction models — see
823
                            // `DenseRun::item_linear`.
824
21916894
                            item_index: if run.item_linear {
825
7851
                                run.item_base.wrapping_add(c.start_byte)
826
                            } else {
827
21909043
                                run.item_base
828
                            },
829
                        },
830
21916894
                        source_node_id,
831
21916894
                        glyphs,
832
21916894
                        flags: ClusterFlags(f & ClusterFlags::CLASSIFY_MASK),
833
21916894
                        advance: c.advance,
834
21916894
                        direction: run.direction,
835
21916894
                        style: run.style.clone(),
836
21916894
                        marker_position_outside: (f & ClusterFlags::DENSE_MARKER_SOME != 0)
837
21916894
                            .then_some(f & ClusterFlags::DENSE_MARKER_OUTSIDE != 0),
838
21916894
                        is_first_fragment: f & ClusterFlags::DENSE_IS_FIRST_FRAGMENT != 0,
839
21916894
                        is_last_fragment: f & ClusterFlags::DENSE_IS_LAST_FRAGMENT != 0,
840
                    }),
841
                    position: Point {
842
21916894
                        x: c.x,
843
                        // (d6h) Per-item y on mixed-size lines: the
844
                        // record holds the line's FIRST item top;
845
                        // baseline-align via run ascents. Same run ⟹
846
                        // the recorded value bit-exactly.
847
21916894
                        y: match self.run_of(line.clusters.0) {
848
21916894
                            Some(fr) if !core::ptr::eq(fr, run) => {
849
46140
                                line.baseline_y + Self::resolved_run_ascent(fr)
850
46140
                                    - Self::resolved_run_ascent(run)
851
                            }
852
21870754
                            _ => line.baseline_y,
853
                        },
854
                    },
855
21916894
                    line_index: line.source_index as usize,
856
                });
857
            }
858
        }
859
451746
        out
860
451746
    }
861

            
862
    /// (d6f) The single (direction, step) dispatch over the dense
863
    /// movement library — twin of the window's `resolve_step_static`.
864
    #[must_use]
865
11650
    pub fn resolve_step(
866
11650
        &self,
867
11650
        cursor: &azul_core::selection::TextCursor,
868
11650
        direction: azul_core::events::SelectionDirection,
869
11650
        step: azul_core::events::SelectionStep,
870
11650
    ) -> azul_core::selection::TextCursor {
871
        use azul_core::events::{SelectionDirection as D, SelectionStep as S};
872
11650
        match (direction, step) {
873
1190
            (D::Backward, S::Character) => self.move_cursor_left(*cursor),
874
1170
            (D::Forward, S::Character) => self.move_cursor_right(*cursor),
875
1160
            (D::Backward, S::Word) => self.move_cursor_to_prev_word(*cursor),
876
1160
            (D::Forward, S::Word) => self.move_cursor_to_next_word(*cursor),
877
1160
            (D::Backward, S::VisualLine) => self.move_cursor_up(*cursor, &mut None),
878
1160
            (D::Forward, S::VisualLine) => self.move_cursor_down(*cursor, &mut None),
879
1170
            (D::Backward, S::Line) => self.move_cursor_to_line_start(*cursor),
880
1160
            (D::Forward, S::Line) => self.move_cursor_to_line_end(*cursor),
881
1160
            (D::Backward, S::Document) => self.first_cluster_cursor().unwrap_or(*cursor),
882
1160
            (D::Forward, S::Document) => self.last_cluster_cursor().unwrap_or(*cursor),
883
        }
884
11650
    }
885

            
886
    /// (d6e) One word right — mirrors the sparse flow (skip the current
887
    /// word, then boundary clusters, land Leading on the next word; end
888
    /// of text falls to the last cluster Trailing).
889
    #[must_use]
890
4340
    pub fn move_cursor_to_next_word(
891
4340
        &self,
892
4340
        cursor: azul_core::selection::TextCursor,
893
4340
    ) -> azul_core::selection::TextCursor {
894
        use azul_core::selection::CursorAffinity;
895
4340
        let Some((current, _)) = self.find_cursor_cluster(&cursor) else {
896
            return cursor;
897
        };
898
4340
        let len = self.clusters.len() as u32;
899
4340
        let start = if cursor.affinity == CursorAffinity::Trailing {
900
2170
            current + 1
901
        } else {
902
2170
            current
903
        };
904
4340
        if start >= len {
905
40
            return cursor;
906
4300
        }
907
4300
        let mut pos = start;
908
32540
        while pos < len && !self.cluster_is_word_boundary(pos) {
909
28240
            pos += 1;
910
28240
        }
911
8600
        while pos < len {
912
8220
            if !self.cluster_is_word_boundary(pos) {
913
3920
                if let Some(c) = self.cursor_at_index(pos, CursorAffinity::Leading) {
914
3920
                    return c;
915
                }
916
4300
            }
917
4300
            pos += 1;
918
        }
919
380
        self.last_cluster_cursor().unwrap_or(cursor)
920
4340
    }
921

            
922
    /// (d6d) Point -> cursor hit test — the SAME weighted-distance scan
923
    /// as the sparse `hittest_cursor` (vertical distance x2 + horizontal
924
    /// outside-distance; closest cluster wins; affinity by midpoint).
925
    /// Cluster geometry from the dense arrays: x/width from
926
    /// `ClusterCompact` (base advance == bounds().width), y/height from the
927
    /// line record + the run's resolved line height. Also the
928
    /// click-to-position primitive.
929
    #[must_use]
930
9480
    pub fn hittest_cursor(&self, point: Point) -> Option<azul_core::selection::TextCursor> {
931
        use azul_core::selection::{CursorAffinity, GraphemeClusterId, TextCursor};
932
9480
        if self.clusters.is_empty() {
933
            return None;
934
9480
        }
935
9480
        let mut best: Option<(f32, u32, &DenseRun, f32)> = None; // (dist, ci, run, x)
936
9480
        let mut line_iter = self.lines.iter().peekable();
937
501700
        for (ci, run) in self
938
9480
            .runs
939
9480
            .iter()
940
501700
            .flat_map(|r| (r.clusters.start..r.clusters.end).map(move |i| (i, r)))
941
        {
942
501700
            let c = &self.clusters[ci as usize];
943
549680
            while let Some(l) = line_iter.peek() {
944
549680
                if ci >= l.clusters.1 {
945
47980
                    line_iter.next();
946
47980
                } else {
947
501700
                    break;
948
                }
949
            }
950
501700
            let (top_y, line_h) = line_iter.peek().map_or((0.0, 0.0), |l| (l.top_y, l.height));
951
501700
            let m = &run.font_metrics;
952
501700
            let h = if m.units_per_em == 0 {
953
                line_h
954
            } else {
955
501700
                run.style
956
501700
                    .line_height
957
501700
                    .resolve_with_metrics(run.style.font_size_px, m)
958
            };
959
501700
            let center_y = top_y + h / 2.0;
960
501700
            let vertical = (point.y - center_y).abs();
961
501700
            let horizontal = if point.x < c.x {
962
213500
                c.x - point.x
963
288200
            } else if point.x > c.x + c.advance {
964
209760
                point.x - (c.x + c.advance)
965
            } else {
966
78440
                0.0
967
            };
968
501700
            let dist = vertical.mul_add(2.0, horizontal);
969
501700
            if best.is_none_or(|(d, ..)| dist < d) {
970
125840
                best = Some((dist, ci, run, c.x));
971
375860
            }
972
        }
973
9480
        let (_, ci, run, x) = best?;
974
9480
        let c = &self.clusters[ci as usize];
975
9480
        let affinity = if point.x < x + c.advance / 2.0 {
976
2750
            CursorAffinity::Leading
977
        } else {
978
6730
            CursorAffinity::Trailing
979
        };
980
9480
        Some(TextCursor {
981
9480
            cluster_id: GraphemeClusterId {
982
9480
                source_run: run.source_run,
983
9480
                start_byte_in_run: c.start_byte,
984
9480
            },
985
9480
            affinity,
986
9480
        })
987
9480
    }
988

            
989
    /// (d6d) Locate a cursor's cluster index + its line ordinal.
990
26690
    fn find_cursor_cluster(
991
26690
        &self,
992
26690
        cursor: &azul_core::selection::TextCursor,
993
26690
    ) -> Option<(u32, usize)> {
994
88170
        for r in &self.runs {
995
88170
            if r.source_run != cursor.cluster_id.source_run {
996
                continue;
997
88170
            }
998
735490
            for ci in r.clusters.start..r.clusters.end {
999
735490
                if self.clusters[ci as usize].start_byte == cursor.cluster_id.start_byte_in_run {
26690
                    let line = self
26690
                        .lines
26690
                        .iter()
88170
                        .position(|l| ci >= l.clusters.0 && ci < l.clusters.1)?;
26690
                    return Some((ci, line));
708800
                }
            }
        }
        None
26690
    }
    /// (d6d) One line up, preserving the horizontal goal column — mirrors
    /// the sparse `move_cursor_up` flow: current cluster by id, `goal_x`
    /// seeded from affinity (Trailing = x + advance), target line's
    /// mid-height, then the weighted hit test.
    #[must_use]
4660
    pub fn move_cursor_up(
4660
        &self,
4660
        cursor: azul_core::selection::TextCursor,
4660
        goal_x: &mut Option<f32>,
4660
    ) -> azul_core::selection::TextCursor {
        use azul_core::selection::CursorAffinity;
4660
        let Some((ci, line_ord)) = self.find_cursor_cluster(&cursor) else {
            return cursor;
        };
4660
        if line_ord == 0 {
960
            return cursor;
3700
        }
3700
        let c = &self.clusters[ci as usize];
3700
        let current_x = goal_x.unwrap_or_else(|| {
3700
            let x = match cursor.affinity {
1850
                CursorAffinity::Leading => c.x,
1850
                CursorAffinity::Trailing => c.x + c.advance,
            };
3700
            *goal_x = Some(x);
3700
            x
3700
        });
3700
        let target = &self.lines[line_ord - 1];
3700
        let target_y = target.top_y + target.height / 2.0;
3700
        self.hittest_cursor(Point {
3700
            x: current_x,
3700
            y: target_y,
3700
        })
3700
        .unwrap_or(cursor)
4660
    }
    /// (d6d) One line down — see [`Self::move_cursor_up`].
    #[must_use]
4660
    pub fn move_cursor_down(
4660
        &self,
4660
        cursor: azul_core::selection::TextCursor,
4660
        goal_x: &mut Option<f32>,
4660
    ) -> azul_core::selection::TextCursor {
        use azul_core::selection::CursorAffinity;
4660
        let Some((ci, line_ord)) = self.find_cursor_cluster(&cursor) else {
            return cursor;
        };
4660
        if line_ord + 1 >= self.lines.len() {
1240
            return cursor;
3420
        }
3420
        let c = &self.clusters[ci as usize];
3420
        let current_x = goal_x.unwrap_or_else(|| {
3420
            let x = match cursor.affinity {
1710
                CursorAffinity::Leading => c.x,
1710
                CursorAffinity::Trailing => c.x + c.advance,
            };
3420
            *goal_x = Some(x);
3420
            x
3420
        });
3420
        let target = &self.lines[line_ord + 1];
3420
        let target_y = target.top_y + target.height / 2.0;
3420
        self.hittest_cursor(Point {
3420
            x: current_x,
3420
            y: target_y,
3420
        })
3420
        .unwrap_or(cursor)
4660
    }
    /// (d6c) One caret stop left — IDENTICAL to the sparse
    /// `move_cursor_left` by construction: the stops list is pinned equal
    /// (`grapheme_stops` gate) and the offset arithmetic is the SAME static
    /// helper the sparse implementation uses.
    #[must_use]
4090
    pub fn move_cursor_left(
4090
        &self,
4090
        cursor: azul_core::selection::TextCursor,
4090
    ) -> azul_core::selection::TextCursor {
        use super::cache::UnifiedLayout;
4090
        let stops = self.grapheme_stops();
4090
        if stops.is_empty() {
            return cursor;
4090
        }
4090
        let Some(offset) = UnifiedLayout::grapheme_caret_offset(&stops, &cursor) else {
            return cursor;
        };
4090
        UnifiedLayout::cursor_from_grapheme_offset(&stops, offset.saturating_sub(1))
4090
    }
    /// (d6c) One caret stop right — see [`Self::move_cursor_left`].
    #[must_use]
4070
    pub fn move_cursor_right(
4070
        &self,
4070
        cursor: azul_core::selection::TextCursor,
4070
    ) -> azul_core::selection::TextCursor {
        use super::cache::UnifiedLayout;
4070
        let stops = self.grapheme_stops();
4070
        if stops.is_empty() {
            return cursor;
4070
        }
4070
        let Some(offset) = UnifiedLayout::grapheme_caret_offset(&stops, &cursor) else {
            return cursor;
        };
4070
        UnifiedLayout::cursor_from_grapheme_offset(&stops, (offset + 1).min(stops.len()))
4070
    }
    /// (d6f) Leading cursor on the FIRST cluster — sparse
    /// `get_first_cluster_cursor` twin.
    #[must_use]
2350
    pub fn first_cluster_cursor(&self) -> Option<azul_core::selection::TextCursor> {
2350
        self.cursor_at_index(0, azul_core::selection::CursorAffinity::Leading)
2350
    }
    /// (d4) The trailing cursor on the LAST cluster — the dense twin of
    /// the sparse `items.iter().rev().find_map(Cluster)` scans (which
    /// skip trailing non-clusters, exactly as taking the last dense
    /// cluster does). `None` when the layout has no clusters.
    #[must_use]
3644
    pub fn last_cluster_cursor(&self) -> Option<azul_core::selection::TextCursor> {
3644
        let last_ci = u32::try_from(self.clusters.len()).ok()?.checked_sub(1)?;
3624
        let c = self.clusters.last()?;
3624
        let run = self
3624
            .runs
3624
            .iter()
3624
            .rev()
3624
            .find(|r| r.clusters.contains(&last_ci))?;
3624
        Some(azul_core::selection::TextCursor {
3624
            cluster_id: azul_core::selection::GraphemeClusterId {
3624
                source_run: run.source_run,
3624
                start_byte_in_run: c.start_byte,
3624
            },
3624
            affinity: azul_core::selection::CursorAffinity::Trailing,
3624
        })
3644
    }
    /// (d4) Cursor for an IFC-wide byte offset — the dense twin of the
    /// sparse accumulation walk: clusters in item order, each
    /// contributing `cluster_byte_len`, first cluster whose span
    /// contains the offset wins; past-the-end falls to the last cluster.
    #[must_use]
980
    pub fn byte_offset_to_cursor(
980
        &self,
980
        byte_offset: u32,
980
    ) -> Option<azul_core::selection::TextCursor> {
        use azul_core::selection::{CursorAffinity, GraphemeClusterId, TextCursor};
980
        let cursor_at = |ci: u32| -> Option<TextCursor> {
980
            let c = self.clusters.get(ci as usize)?;
2600
            let run = self.runs.iter().find(|r| r.clusters.contains(&ci))?;
980
            Some(TextCursor {
980
                cluster_id: GraphemeClusterId {
980
                    source_run: run.source_run,
980
                    start_byte_in_run: c.start_byte,
980
                },
980
                affinity: CursorAffinity::Trailing,
980
            })
980
        };
980
        if self.clusters.is_empty() {
            return None;
980
        }
980
        if byte_offset == 0 {
30
            return cursor_at(0);
950
        }
950
        let mut acc = 0u32;
21090
        for ci in 0..self.clusters.len() as u32 {
21090
            let len = self.cluster_byte_len(ci);
21090
            let end = acc + len;
21090
            if byte_offset >= acc && byte_offset <= end {
920
                return cursor_at(ci);
20170
            }
20170
            acc = end;
        }
30
        cursor_at(self.clusters.len() as u32 - 1)
980
    }
}
/// §3.2 step 3: the dense twin of [`super::glyphs::get_glyph_positions`]
/// (the reference walker the other two consumers agree with). Walks the
/// dense arrays only. Positions agree EXACTLY with the reference for
/// uniform-font clusters (the run's metrics reproduce the per-item
/// ascent math); multi-font fallback clusters would need the per-glyph
/// metrics the detail table deliberately does not carry — the atomics /
/// combined blocks stay on the sparse side and are not walked here.
///
/// `PositionedGlyph.advance` reports the PAINTED advance (incl. kerning,
/// as the dense model folds it) — the reference reports the base advance
/// and advances its pen by base+kerning; positions are identical either
/// way, which is what the agreement gate compares.
#[must_use]
30
pub fn get_glyph_positions_dense(dense: &DenseText) -> Vec<PositionedGlyph> {
30
    let mut out = Vec::with_capacity(dense.clusters.len());
30
    let mut line_iter = dense.lines.iter().peekable();
30
    let mut detail_iter = dense.details.iter().peekable();
920
    for (ci, run) in dense
30
        .runs
30
        .iter()
920
        .flat_map(|r| (r.clusters.start..r.clusters.end).map(move |i| (i, r)))
    {
920
        let c = &dense.clusters[ci as usize];
        // Advance the line cursor to the record containing this cluster.
970
        while let Some(l) = line_iter.peek() {
970
            if ci >= l.clusters.1 {
50
                line_iter.next();
50
            } else {
920
                break;
            }
        }
920
        let top_y = line_iter.peek().map_or(0.0, |l| l.top_y);
        // Per-run ascent: the same math the reference derives per item
        // (metrics + half-leading), amortised — run metrics are uniform.
920
        let m = &run.font_metrics;
920
        let ascent = if m.units_per_em == 0 {
            0.0
        } else {
920
            let scale = run.style.font_size_px / f32::from(m.units_per_em);
920
            let font_ascent = m.ascent * scale;
920
            let font_descent = (-m.descent * scale).max(0.0);
920
            let ad = font_ascent + font_descent;
920
            let lh = run
920
                .style
920
                .line_height
920
                .resolve_with_metrics(run.style.font_size_px, m);
920
            font_ascent + (lh - ad) / 2.0
        };
        // The RUN's own solved y, not the line's: a line mixing sizes puts
        // its taller run on a different baseline (see DenseRun::y).
920
        let baseline_y = run.y + ascent;
        // Detail cluster? (details are in cluster order.)
920
        let detail = loop {
920
            match detail_iter.peek() {
                Some(d) if d.cluster < ci => {
                    detail_iter.next();
                }
                Some(d) if d.cluster == ci => break Some(**d),
920
                _ => break None,
            }
        };
920
        match detail {
            Some(d) => {
                let mut pen_x = c.x;
                for dg in &dense.detail_glyphs[d.glyphs.0 as usize..d.glyphs.1 as usize] {
                    out.push(PositionedGlyph {
                        glyph_id: dg.glyph_id,
                        position: Point {
                            x: pen_x + dg.offset_x,
                            y: baseline_y - dg.offset_y,
                        },
                        advance: dg.advance,
                    });
                    pen_x += dg.advance;
                }
            }
920
            None => {
920
                out.push(PositionedGlyph {
920
                    glyph_id: c.glyph_id,
920
                    position: Point {
920
                        x: c.x,
920
                        y: baseline_y,
920
                    },
920
                    advance: c.advance,
920
                });
920
            }
        }
    }
30
    out
30
}
/// §3.2 step 4: the dense twin of [`super::glyphs::get_glyph_runs_simple`]
/// (the paint-path consumer). Same walk as [`get_glyph_positions_dense`];
/// the run-merge predicate is the REFERENCE's — painted VALUES on the same
/// baseline, not Arc identity — so two dense runs that split only on style
/// Arc identity or `source_run` merge back into one paint run exactly as
/// the reference merges glyphs from different shaping runs. The border
/// fragment post-process is literally shared
/// ([`super::glyphs::suppress_split_border_fragments`]), so CSS 2.2 §9.4.2
/// split-point suppression cannot drift between the walkers.
///
/// Same documented limits as the position walker: combined blocks
/// (tate-chu-yoko) stay on the sparse side per the plan's `AtomicItem`
/// design, and a multi-font-fallback CLUSTER would split mid-cluster in
/// the reference but not here (the detail table carries no per-glyph
/// font hash) — both migrate in a later step; the agreement gate covers
/// the dense-expressible subset.
#[allow(clippy::float_cmp)] // intentional exact compare: same predicate as the reference walker
#[must_use]
167514
pub fn get_glyph_runs_simple_dense(dense: &DenseText) -> Vec<SimpleGlyphRun> {
167514
    let mut runs: Vec<SimpleGlyphRun> = Vec::new();
167514
    let mut current_run: Option<SimpleGlyphRun> = None;
167514
    let mut current_baseline: Option<f32> = None;
167514
    let mut line_iter = dense.lines.iter().peekable();
167514
    let mut detail_iter = dense.details.iter().peekable();
2769557
    for (ci, run) in dense
167514
        .runs
167514
        .iter()
2769557
        .flat_map(|r| (r.clusters.start..r.clusters.end).map(move |i| (i, r)))
    {
2769557
        let c = &dense.clusters[ci as usize];
        // Detail cluster? (details are in cluster order.) Resolved FIRST:
        // a zero-glyph detail cluster contributes nothing and must not
        // open a run (the reference's per-glyph loop never runs there).
2769557
        let detail = loop {
2807301
            match detail_iter.peek() {
563481
                Some(d) if d.cluster < ci => {
37744
                    detail_iter.next();
37744
                }
525737
                Some(d) if d.cluster == ci => break Some(**d),
2731783
                _ => break None,
            }
        };
2769557
        if detail.is_some_and(|d| d.glyphs.0 == d.glyphs.1) {
10
            continue;
2769547
        }
        // Line cursor + per-run ascent: identical to the position walker.
2799194
        while let Some(l) = line_iter.peek() {
2799194
            if ci >= l.clusters.1 {
29647
                line_iter.next();
29647
            } else {
2769547
                break;
            }
        }
2769547
        let top_y = line_iter.peek().map_or(0.0, |l| l.top_y);
2769547
        let m = &run.font_metrics;
2769547
        let ascent = if m.units_per_em == 0 {
4
            0.0
        } else {
2769543
            let scale = run.style.font_size_px / f32::from(m.units_per_em);
2769543
            let font_ascent = m.ascent * scale;
2769543
            let font_descent = (-m.descent * scale).max(0.0);
2769543
            let ad = font_ascent + font_descent;
2769543
            let lh = run
2769543
                .style
2769543
                .line_height
2769543
                .resolve_with_metrics(run.style.font_size_px, m);
2769543
            font_ascent + (lh - ad) / 2.0
        };
        // The RUN's own solved y, not the line's: a line mixing sizes puts
        // its taller run on a different baseline (see DenseRun::y).
2769547
        let baseline_y = run.y + ascent;
2769547
        let style = &run.style;
2769547
        let source_node_id =
2769547
            (run.source_node != u32::MAX).then(|| NodeId::new(run.source_node as usize));
        // The reference predicate, evaluated per CLUSTER — every compared
        // field is uniform within a cluster there, so boundaries are
        // identical.
2769547
        let merges = current_run.as_ref().is_some_and(|r| {
2603430
            current_baseline == Some(baseline_y)
2573703
                && r.font_hash == run.font_hash
2573533
                && r.color == style.color
2573153
                && r.background_color == style.background_color
2573143
                && r.background_content == style.background_content
2573123
                && r.border == style.border
2573103
                && r.font_size_px == style.font_size_px
2573083
                && r.text_decoration == style.text_decoration
2573083
                && r.source_node_id == source_node_id
2603430
        });
2769547
        if !merges {
197934
            if let Some(prev) = current_run.take() {
31817
                runs.push(prev);
166117
            }
197934
            current_baseline = Some(baseline_y);
197934
            current_run = Some(SimpleGlyphRun {
197934
                glyphs: Vec::new(),
197934
                color: style.color,
197934
                background_color: style.background_color,
197934
                background_content: style.background_content.clone(),
197934
                border: style.border,
197934
                font_hash: run.font_hash,
197934
                font_size_px: style.font_size_px,
197934
                text_decoration: style.text_decoration,
197934
                is_ime_preview: false,
197934
                source_node_id,
197934
            });
2571613
        }
2769547
        let out = &mut current_run
2769547
            .as_mut()
2769547
            .expect("opened above when absent")
2769547
            .glyphs;
2769547
        match detail {
37764
            Some(d) => {
37764
                let mut pen_x = c.x;
37765
                for dg in &dense.detail_glyphs[d.glyphs.0 as usize..d.glyphs.1 as usize] {
37765
                    out.push(GlyphInstance {
37765
                        index: u32::from(dg.glyph_id),
37765
                        point: LogicalPosition {
37765
                            x: pen_x + dg.offset_x,
37765
                            y: baseline_y - dg.offset_y,
37765
                        },
37765
                        size: LogicalSize::default(),
37765
                    });
37765
                    pen_x += dg.advance;
37765
                }
            }
2731783
            None => {
2731783
                out.push(GlyphInstance {
2731783
                    index: u32::from(c.glyph_id),
2731783
                    point: LogicalPosition {
2731783
                        x: c.x,
2731783
                        y: baseline_y,
2731783
                    },
2731783
                    size: LogicalSize::default(),
2731783
                });
2731783
            }
        }
    }
167514
    if let Some(r) = current_run {
166117
        runs.push(r);
166121
    }
167514
    super::glyphs::suppress_split_border_fragments(&mut runs);
167514
    runs
167514
}
/// §3.2 step 5: the dense twin of [`super::glyphs::get_glyph_runs_pdf`]
/// (printpdf's frozen contract: `cluster.glyphs` iteration +
/// `glyph.font_hash`). Same walk as the other dense twins; the run
/// predicate is the reference's (font, colour, background, size,
/// decoration, LINE index, direction, writing mode — note: no border, no
/// background layers, no source node).
///
/// The per-cluster TEXT — which the reference reads from
/// `ShapedCluster::text` — is reconstructed here as the grapheme cluster
/// at `start_byte` in the run's shared source text: the same
/// segmentation shaping used to build the cluster, so the two agree
/// byte-for-byte (the agreement gate pins it, and 3c deletes the
/// per-cluster copy on the strength of exactly this equivalence).
/// Styles that rewrite text between source and shaping (text-transform)
/// keep the sparse walker until the transform story lands.
///
/// `PdfPositionedGlyph::advance` reports the PAINTED advance for detail
/// glyphs (kerning folded, as the dense model stores it) where the
/// reference reports the base advance — positions are identical either
/// way, same documented divergence as the position walker.
#[allow(clippy::float_cmp)] // intentional exact compare: same predicate as the reference walker
#[allow(clippy::too_many_lines)] // one cohesive walk, mirrors the reference's structure
#[must_use]
5
pub fn get_glyph_runs_pdf_dense<T: ParsedFontTrait>(
5
    dense: &DenseText,
5
    fonts: &LoadedFonts<T>,
5
) -> Vec<PdfGlyphRun<T>> {
    use unicode_segmentation::UnicodeSegmentation;
5
    let mut runs: Vec<PdfGlyphRun<T>> = Vec::new();
5
    let mut current_run: Option<PdfGlyphRun<T>> = None;
5
    let mut line_iter = dense.lines.iter().peekable();
5
    let mut detail_iter = dense.details.iter().peekable();
110
    for (ci, run) in dense
5
        .runs
5
        .iter()
110
        .flat_map(|r| (r.clusters.start..r.clusters.end).map(move |i| (i, r)))
    {
110
        let c = &dense.clusters[ci as usize];
        // Detail resolution first: a zero-glyph cluster contributes
        // nothing (the reference skips `cluster.glyphs.is_empty()`).
110
        let detail = loop {
110
            match detail_iter.peek() {
                Some(d) if d.cluster < ci => {
                    detail_iter.next();
                }
                Some(d) if d.cluster == ci => break Some(**d),
110
                _ => break None,
            }
        };
110
        if detail.is_some_and(|d| d.glyphs.0 == d.glyphs.1) {
            continue;
110
        }
        // A glyph whose font is not loaded is skipped WITHOUT breaking
        // the open run, exactly as the reference's per-glyph `continue`.
110
        let Some(font) = fonts.get_by_hash(run.font_hash) else {
            continue;
        };
        // Line cursor: source line index + per-run ascent → baseline.
115
        while let Some(l) = line_iter.peek() {
115
            if ci >= l.clusters.1 {
5
                line_iter.next();
5
            } else {
110
                break;
            }
        }
110
        let (top_y, line_index) = line_iter
110
            .peek()
110
            .map_or((0.0, 0usize), |l| (l.top_y, l.source_index as usize));
110
        let m = &run.font_metrics;
110
        let ascent = if m.units_per_em == 0 {
            0.0
        } else {
110
            let scale = run.style.font_size_px / f32::from(m.units_per_em);
110
            let font_ascent = m.ascent * scale;
110
            let font_descent = (-m.descent * scale).max(0.0);
110
            let ad = font_ascent + font_descent;
110
            let lh = run
110
                .style
110
                .line_height
110
                .resolve_with_metrics(run.style.font_size_px, m);
110
            font_ascent + (lh - ad) / 2.0
        };
        // The RUN's own solved y, not the line's: a line mixing sizes puts
        // its taller run on a different baseline (see DenseRun::y).
110
        let baseline_y = run.y + ascent;
110
        let style = &run.style;
        // The cluster's source text: `cluster_byte_len` bytes at start_byte in
        // the shared run text.
        //
        // NOT "the next grapheme". A LIGATURE-FUSED cluster spans several
        // graphemes — "fi" is two — so a grapheme walk returns "f" and the
        // second character is lost. That is what `ClusterDetail.byte_len`
        // exists to record, in its own words: "a ligature-fused cluster spans
        // multiple graphemes, so 'next grapheme boundary' under-measures it".
        // The sparse expander and the word-boundary predicate both ask
        // `cluster_byte_len`; this walker asked the graphemes, and the
        // difference reached users as PDF text: every ligated word came out of
        // pdftotext with its second letter missing — "Configure" -> "Confgure",
        // "filter" -> "flter", "offline" -> "offine" — because the ToUnicode
        // entry for the ligature glyph said "f".
110
        let start = c.start_byte as usize;
110
        let len = dense.cluster_byte_len(ci) as usize;
110
        let cluster_text: &str = run
110
            .text
110
            .get(start..start.saturating_add(len))
            // A byte length that is not a char boundary would slice-panic;
            // fall back to the old grapheme walk rather than take the process
            // down over a malformed record.
110
            .or_else(|| {
                run.text
                    .get(start..)
                    .and_then(|s| s.graphemes(true).next())
            })
110
            .unwrap_or("");
        // The reference predicate, evaluated per CLUSTER (all compared
        // fields are uniform within a cluster in dense scope).
110
        let merges = current_run.as_ref().is_some_and(|r| {
105
            r.font_hash == run.font_hash
105
                && r.color == style.color
104
                && r.background_color == style.background_color
104
                && r.font_size_px == style.font_size_px
104
                && r.text_decoration == style.text_decoration
104
                && r.line_index == line_index
99
                && r.direction == run.direction
99
                && r.writing_mode == style.writing_mode
105
        });
110
        if !merges {
11
            if let Some(prev) = current_run.take() {
6
                runs.push(prev);
6
            }
11
            current_run = Some(PdfGlyphRun {
11
                glyphs: Vec::new(),
11
                color: style.color,
11
                background_color: style.background_color,
11
                font: font.clone(),
11
                font_hash: run.font_hash,
11
                font_size_px: style.font_size_px,
11
                text_decoration: style.text_decoration,
11
                line_index,
11
                direction: run.direction,
11
                writing_mode: style.writing_mode,
11
                baseline_start: Point {
11
                    x: c.x,
11
                    y: baseline_y,
11
                },
11
                cluster_texts: Vec::new(),
11
            });
99
        }
110
        let open = current_run.as_mut().expect("opened above when absent");
110
        if let Some(d) = detail {
            let dgs = &dense.detail_glyphs[d.glyphs.0 as usize..d.glyphs.1 as usize];
            let count = dgs.len();
            let mut pen_x = c.x;
            for (glyph_idx, dg) in dgs.iter().enumerate() {
                // The reference's per-glyph codepoint split, verbatim.
                let unicode_codepoint = if count == 1 {
                    cluster_text.to_string()
                } else {
                    let byte_offset = dg.cluster_offset as usize;
                    if byte_offset < cluster_text.len() {
                        cluster_text[byte_offset..]
                            .chars()
                            .next()
                            .map_or_else(|| cluster_text.to_string(), |ch| ch.to_string())
                    } else if glyph_idx == 0 {
                        cluster_text.to_string()
                    } else {
                        String::new()
                    }
                };
                open.glyphs.push(PdfPositionedGlyph {
                    glyph_id: dg.glyph_id,
                    position: Point {
                        x: pen_x + dg.offset_x,
                        y: baseline_y - dg.offset_y,
                    },
                    advance: dg.advance,
                    unicode_codepoint,
                });
                open.cluster_texts.push(cluster_text.to_string());
                pen_x += dg.advance;
            }
110
        } else {
110
            open.glyphs.push(PdfPositionedGlyph {
110
                glyph_id: c.glyph_id,
110
                position: Point {
110
                    x: c.x,
110
                    y: baseline_y,
110
                },
110
                advance: c.advance,
110
                unicode_codepoint: cluster_text.to_string(),
110
            });
110
            open.cluster_texts.push(cluster_text.to_string());
110
        }
    }
5
    if let Some(r) = current_run {
5
        runs.push(r);
5
    }
5
    runs
5
}