1
//! Glyph path and cell cache for CPU rendering.
2
//!
3
//! Two-level cache:
4
//! 1. **Path cache**: `PathStorage` objects keyed by (font, glyph, ppem). Avoids redundant path
5
//!    construction from font outlines.
6
//! 2. **Cell cache**: Rasterizer cells keyed by (font, glyph, ppem, scale, sub-pixel). Avoids the
7
//!    expensive path→cells conversion on every frame. Cells are computed at position (0,0) and
8
//!    offset at render time.
9

            
10
use std::collections::HashMap;
11

            
12
use agg_rust::{
13
    basics::{VertexD, VertexSource, PATH_CMD_STOP},
14
    path_storage::PathStorage,
15
    rasterizer_cells_aa::CellAa,
16
};
17

            
18
use crate::font::parsed::{build_glyph_path, OwnedGlyph, ParsedFont};
19

            
20
/// A `VertexSource` view over an already-built slice of path vertices.
21
///
22
/// Replaces the upstream-removed `RasterizerScanlineAa::add_path_vertices_transformed`:
23
/// wrap this in a `ConvTransform` and feed it to `add_path` to rasterize cached glyph
24
/// vertices under a transform WITHOUT cloning the (shared, immutable) `PathStorage`.
25
pub(crate) struct SliceVertexSource<'a> {
26
    verts: &'a [VertexD],
27
    pos: usize,
28
}
29

            
30
impl<'a> SliceVertexSource<'a> {
31
17367
    pub(crate) const fn new(verts: &'a [VertexD]) -> Self {
32
17367
        Self { verts, pos: 0 }
33
17367
    }
34
}
35

            
36
impl VertexSource for SliceVertexSource<'_> {
37
17367
    fn rewind(&mut self, _path_id: u32) {
38
17367
        self.pos = 0;
39
17367
    }
40

            
41
608898
    fn vertex(&mut self, x: &mut f64, y: &mut f64) -> u32 {
42
608898
        match self.verts.get(self.pos) {
43
591531
            Some(v) => {
44
591531
                self.pos += 1;
45
591531
                *x = v.x;
46
591531
                *y = v.y;
47
591531
                v.cmd
48
            }
49
17367
            None => PATH_CMD_STOP,
50
        }
51
608898
    }
52
}
53

            
54
/// Cache key for a glyph path.
55
/// ppem = 0 means unhinted (font-unit path), ppem > 0 means hinted at that size.
56
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
57
struct GlyphPathKey {
58
    font_hash: u64,
59
    glyph_id: u16,
60
    ppem: u16,
61
}
62

            
63
/// Cache key for pre-rasterized glyph cells.
64
/// Includes sub-pixel x/y fractional position quantized to 1/4 pixel.
65
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
66
struct GlyphCellKey {
67
    font_hash: u64,
68
    glyph_id: u16,
69
    ppem: u16,
70
    /// Scale factor encoded as fixed-point (scale * 65536) for unhinted glyphs.
71
    /// 0 for hinted glyphs (already in pixel coords).
72
    scale_fixed: u32,
73
    /// Sub-pixel x position, quantized to 1/`x_subsamples`-of-a-pixel for
74
    /// the LCD path and to 1/4 pixel for the grayscale path.
75
    subpx_x: u8,
76
    /// Sub-pixel y position quantized to 1/4 pixel (0..3).
77
    subpx_y: u8,
78
    /// Horizontal sub-samples per pixel the cells were rasterized at: 1 for
79
    /// the grayscale path, 3 for RGB LCD. Part of the key because the two
80
    /// produce completely different cell geometry for the same glyph.
81
    x_subsamples: u8,
82
}
83

            
84
/// Result of a cache lookup: the path plus whether it's hinted (pixel coords) or not.
85
pub struct CachedGlyph<'a> {
86
    pub path: &'a PathStorage,
87
    pub is_hinted: bool,
88
}
89

            
90
impl core::fmt::Debug for CachedGlyph<'_> {
91
    // `path` is agg_rust's PathStorage (not Debug); show the rest.
92
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
93
        f.debug_struct("CachedGlyph")
94
            .field("is_hinted", &self.is_hinted)
95
            .finish_non_exhaustive()
96
    }
97
}
98

            
99
/// Pre-rasterized glyph cells at a canonical position.
100
/// Contains the rasterizer's cell output for a glyph at sub-pixel position (`subpx_x`, `subpx_y`).
101
/// To render at actual position (x, y), add integer pixel offset to each cell.
102
struct CachedCells {
103
    cells: Vec<CellAa>,
104
}
105

            
106
/// Entries per GENERATION before rotating. Two generations are live, so
107
/// the cache holds up to twice this — the totals match the single-map
108
/// caps these replaced (8192 paths, 16384 cells).
109
const MAX_PATH_ENTRIES: usize = 4096;
110
/// See [`MAX_PATH_ENTRIES`]. Cell entries are larger than paths.
111
const MAX_CELL_ENTRIES: usize = 8192;
112

            
113
/// Cache of built glyph paths and pre-rasterized cells.
114
///
115
/// GENERATIONAL, because the previous scheme had a cliff: on reaching the
116
/// cap it called `clear()` and threw away EVERYTHING, so one glyph over
117
/// the line re-hinted the entire visible page — a multi-millisecond stall
118
/// landing on whichever keystroke happened to cross it.
119
///
120
/// Now a full young map is demoted to `*_prev` (an O(1) move) and a fresh
121
/// one starts. A lookup that misses young but hits prev is promoted back,
122
/// so the live working set survives a rotation and only genuinely cold
123
/// entries are dropped — and they are dropped one map at a time, never
124
/// all of them.
125
pub struct GlyphCache {
126
    paths: HashMap<GlyphPathKey, Option<(PathStorage, bool)>>,
127
    /// Previous generation, see the type docs.
128
    paths_prev: HashMap<GlyphPathKey, Option<(PathStorage, bool)>>,
129
    cells: HashMap<GlyphCellKey, Option<CachedCells>>,
130
    /// Previous generation, see the type docs.
131
    cells_prev: HashMap<GlyphCellKey, Option<CachedCells>>,
132
    /// Pre-blended LCD tiles (uniform-background fast path). `None` entry =
133
    /// glyph has no cells. Flat cap with full drop — see `MAX_TILE_ENTRIES`.
134
    lcd_tiles: HashMap<LcdTileKey, Option<LcdGlyphTile>>,
135
    /// LCD stripe order of the panel this cache's window is on.
136
    lcd_subpixel_order: LcdSubpixelOrder,
137
}
138

            
139
impl core::fmt::Debug for GlyphCache {
140
    // Values hold agg_rust PathStorage / CellAa (not Debug); show entry counts.
141
1
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
142
1
        f.debug_struct("GlyphCache")
143
1
            .field("paths", &self.paths.len())
144
1
            .field("cells", &self.cells.len())
145
1
            .finish_non_exhaustive()
146
1
    }
147
}
148

            
149
/// Re-exported for platform shells.
150
pub use agg_rust::pixfmt_lcd::LcdSubpixelOrder;
151

            
152
/// Quantize a fractional pixel position to 1/4 pixel (0..3).
153
#[inline]
154
#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] // bounded graphics/coord/font/
155
                                                                   // fixed-point/debug-marker cast
156
36845
fn quantize_subpx(frac: f32) -> u8 {
157
36845
    let f = frac - frac.floor();
158
36845
    (f * 4.0).min(3.0) as u8
159
36845
}
160

            
161
/// Horizontal sub-pixel buckets used by the LCD cell cache.
162
///
163
/// The obvious choice is 3 — one per RGB stripe — on the reasoning that a
164
/// 3x rasterizer cannot resolve finer. That reasoning is WRONG and the
165
/// reftests caught it: the uncached path translated the outline by a
166
/// FLOAT (`3.0 * px`), and the rasterizer carries sub-stripe precision
167
/// internally (24.8 fixed point), so exact fractional placement really did
168
/// render detail that 1/3-px bucketing throws away. Quantizing to thirds
169
/// moved four previously-passing text reftests into failure.
170
///
171
/// 16 buckets put the placement error at 1/16 px, an order of magnitude
172
/// below a stripe, at 16 cell sets per glyph instead of 3.
173
const LCD_SUBPX_BUCKETS: u8 = 16;
174

            
175
/// Quantize a fractional pixel position into one of [`LCD_SUBPX_BUCKETS`].
176
#[inline]
177
#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] // bounded graphics/coord/font/
178
                                                                   // fixed-point/debug-marker cast
179
8016289
fn quantize_subpx_lcd(frac: f32) -> u8 {
180
8016289
    let f = frac - frac.floor();
181
8016289
    (f * f32::from(LCD_SUBPX_BUCKETS)).min(f32::from(LCD_SUBPX_BUCKETS - 1)) as u8
182
8016289
}
183

            
184
impl Default for GlyphCache {
185
1
    fn default() -> Self {
186
1
        Self::new()
187
1
    }
188
}
189

            
190
impl GlyphCache {
191
    #[must_use]
192
1103
    pub fn new() -> Self {
193
1103
        Self {
194
1103
            paths: HashMap::new(),
195
1103
            paths_prev: HashMap::new(),
196
1103
            cells: HashMap::new(),
197
1103
            cells_prev: HashMap::new(),
198
1103
            lcd_tiles: HashMap::new(),
199
1103
            lcd_subpixel_order: LcdSubpixelOrder::Rgb,
200
1103
        }
201
1103
    }
202

            
203
    /// The panel stripe order LCD text is blended for.
204
    #[must_use]
205
276400
    pub const fn lcd_subpixel_order(&self) -> LcdSubpixelOrder {
206
276400
        self.lcd_subpixel_order
207
276400
    }
208

            
209
    /// Drops the pre-blended tiles on a change; the caller repaints what is on screen.
210
    pub fn set_lcd_subpixel_order(&mut self, order: LcdSubpixelOrder) -> bool {
211
        if self.lcd_subpixel_order == order {
212
            return false;
213
        }
214
        self.lcd_subpixel_order = order;
215
        self.lcd_tiles.clear();
216
        true
217
    }
218

            
219
    /// Entry count of the glyph-path cache (for leak probes).
220
    /// Counts BOTH generations — a probe watching for unbounded growth
221
    /// must see everything the cache is holding.
222
    #[must_use]
223
11
    pub fn paths_len(&self) -> usize {
224
11
        self.paths.len() + self.paths_prev.len()
225
11
    }
226

            
227
    /// Entry count of the pre-rasterized cell cache (for leak probes).
228
    /// Counts BOTH generations, see [`Self::paths_len`].
229
    #[must_use]
230
13
    pub fn cells_len(&self) -> usize {
231
13
        self.cells.len() + self.cells_prev.len()
232
13
    }
233

            
234
    /// Entries held in the PREVIOUS generation of either cache.
235
    ///
236
    /// Exists so a test can observe [`Self::gc`] actually running: without
237
    /// it, "did GC happen" is indistinguishable from "there was nothing to
238
    /// collect", and a test asserting the latter passes whether or not the
239
    /// GC hook is wired up at all.
240
    #[must_use]
241
    pub fn prev_generation_len(&self) -> usize {
242
        self.paths_prev.len() + self.cells_prev.len()
243
    }
244

            
245
    /// Get a cached path, or build it on cache miss.
246
    /// Returns `None` if the glyph has no outline (e.g. space character).
247
9345080
    pub fn get_or_build(
248
9345080
        &mut self,
249
9345080
        font_hash: u64,
250
9345080
        glyph_id: u16,
251
9345080
        glyph_data: &OwnedGlyph,
252
9345080
        parsed_font: &ParsedFont,
253
9345080
        ppem: u16,
254
9345080
    ) -> Option<CachedGlyph<'_>> {
255
9345080
        let key = GlyphPathKey {
256
9345080
            font_hash,
257
9345080
            glyph_id,
258
9345080
            ppem,
259
9345080
        };
260
        // Promote from the previous generation before considering a
261
        // rotation, so a live glyph is never rebuilt just because it aged
262
        // into the older map.
263
9345080
        if !self.paths.contains_key(&key) {
264
15374
            if let Some(v) = self.paths_prev.remove(&key) {
265
1
                self.paths.insert(key, v);
266
15373
            } else if self.paths.len() >= MAX_PATH_ENTRIES {
267
2
                self.paths_prev = core::mem::take(&mut self.paths);
268
15371
            }
269
9329706
        }
270
9345080
        let entry = self.paths.entry(key).or_insert_with(|| {
271
            // Only fires on a MISS, so this span is the true cost of
272
            // running the hinting interpreter for a glyph — as opposed
273
            // to `glyph_lcd_outline`, which is paid on every frame.
274
15373
            let _p = crate::probe::Probe::span("glyph_path_build");
275
            // Try hinted path first if ppem > 0
276
15373
            if ppem > 0 {
277
7097
                if let Some(path) = build_hinted_path(glyph_id, glyph_data, parsed_font, ppem) {
278
6628
                    return Some((path, true));
279
469
                }
280
8276
            }
281
            // Fall back to unhinted path
282
8745
            build_glyph_path(glyph_data).map(|p| (p, false))
283
15373
        });
284
9345080
        entry.as_ref().map(|(path, is_hinted)| CachedGlyph {
285
7994195
            path,
286
7994195
            is_hinted: *is_hinted,
287
7994195
        })
288
9345080
    }
289

            
290
    /// Promote `key` from the previous cell generation if it is there, and
291
    /// otherwise rotate when the young map is full. Mirrors what
292
    /// `get_or_build` does inline for paths.
293
7690401
    fn promote_or_rotate_cells(&mut self, key: &GlyphCellKey) {
294
7690401
        if self.cells.contains_key(key) {
295
7655857
            return;
296
34544
        }
297
34544
        if let Some(v) = self.cells_prev.remove(key) {
298
            self.cells.insert(*key, v);
299
34544
        } else if self.cells.len() >= MAX_CELL_ENTRIES {
300
2
            self.cells_prev = core::mem::take(&mut self.cells);
301
34542
        }
302
7690401
    }
303

            
304
    /// Drop the previous generation of both caches.
305
    ///
306
    /// Intended to be called AFTER a frame is presented, never during one:
307
    /// freeing thousands of `PathStorage`/cell vectors is exactly the kind
308
    /// of work that must not land on a keystroke. Rotation alone already
309
    /// bounds the cache, so this is an opportunity to return memory early,
310
    /// not a correctness requirement.
311
1
    pub fn gc(&mut self) {
312
1
        self.paths_prev = HashMap::new();
313
1
        self.cells_prev = HashMap::new();
314
1
    }
315

            
316
    /// Get cached rasterizer cells for a glyph, or build them from the path.
317
    ///
318
    /// - `glyph_x`, `glyph_y`: final pixel position (used for sub-pixel quantization)
319
    /// - `scale`: font-unit→pixel scale (0.0 for hinted glyphs)
320
    /// - `is_hinted`: whether the path is in pixel coords (hinted) or font units
321
    /// - `hint_correction`: `effective_px / ppem` for hinted glyphs (1.0 otherwise). A hinted
322
    ///   outline is built at the *integer* ppem; when the requested effective size (`font_size *
323
    ///   dpi`) is fractional this rescales it HORIZONTALLY back to the true target size, so the
324
    ///   glyph fills the advance the shaper measured at that size. The vertical axis is left at
325
    ///   the integer ppem: see [`hinted_outline_scale`].
326
    ///
327
    /// Returns the cached cells and the integer pixel offset to apply.
328
    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] // bounded graphics/coord/
329
                                                                       // font/fixed-point/
330
                                                                       // debug-marker cast
331
16412
    pub fn get_or_build_cells(
332
16412
        &mut self,
333
16412
        font_hash: u64,
334
16412
        glyph_id: u16,
335
16412
        ppem: u16,
336
16412
        glyph_x: f32,
337
16412
        glyph_y: f32,
338
16412
        scale: f32,
339
16412
        is_hinted: bool,
340
16412
        hint_correction: f32,
341
16412
    ) -> Option<(&[CellAa], i32, i32)> {
342
        // Hinted outline built at integer ppem needs rescaling only when the
343
        // effective size is fractional (hint_correction != 1). Otherwise it stays
344
        // pixel-grid-snapped (rounded placement) as hinting intends.
345
16412
        let rescale_hinted = is_hinted && (hint_correction - 1.0).abs() > 1e-4;
346
16412
        let grid_snapped = is_hinted && !rescale_hinted;
347

            
348
        // Sub-pixel HORIZONTAL positioning (default ON): even a grid-snapped
349
        // (hinted-at-integer-ppem) glyph places its ORIGIN at a 1/4-pixel X
350
        // bucket, so advances accumulate smoothly and the run lands where
351
        // CoreText (fractional-x) puts it, instead of each origin rounding to a
352
        // whole pixel. The grid-fitted OUTLINE is unchanged — only where we drop
353
        // it horizontally shifts — so vertical stems stay crisp. The Y baseline
354
        // stays grid-snapped (`subpx_y == 0` for grid_snapped). With
355
        // `AZ_TEXT_SUBPIXEL=0` the grid_snapped case reverts to integer X
356
        // (sub-pixel 0, rounded origin), the previous behaviour.
357
16412
        let subpx_x_snap = grid_snapped && !text_subpixel_enabled();
358
16412
        let subpx_x = if subpx_x_snap {
359
            0
360
        } else {
361
16412
            quantize_subpx(glyph_x)
362
        };
363
        // Hinted glyphs keep a grid-snapped baseline (the rescale is horizontal only).
364
16412
        let subpx_y = if is_hinted {
365
9
            0
366
        } else {
367
16403
            quantize_subpx(glyph_y)
368
        };
369
16412
        debug_assert!(
370
            (0.0..65536.0).contains(&scale),
371
            "scale out of range for fixed-point: {scale}"
372
        );
373
16412
        let scale_fixed = if is_hinted {
374
9
            if rescale_hinted {
375
                (hint_correction * 65536.0) as u32
376
            } else {
377
9
                0
378
            }
379
        } else {
380
16403
            (scale * 65536.0) as u32
381
        };
382

            
383
16412
        let cell_key = GlyphCellKey {
384
16412
            font_hash,
385
16412
            glyph_id,
386
16412
            ppem,
387
16412
            scale_fixed,
388
16412
            subpx_x,
389
16412
            subpx_y,
390
16412
            x_subsamples: 1,
391
16412
        };
392

            
393
        // Integer pixel offset — the cells are at sub-pixel origin, offset by int
394
        // part. `int_x + subpx_x*0.25` must reconstruct `glyph_x`, so the floor
395
        // pairs with the quantized fraction; only the integer-X-snap case rounds.
396
16412
        let int_x = if subpx_x_snap {
397
            glyph_x.round() as i32
398
        } else {
399
16412
            glyph_x.floor() as i32
400
        };
401
        // Pairs with `subpx_y` above: every hinted glyph rounds its baseline.
402
16412
        let int_y = if is_hinted {
403
9
            glyph_y.round() as i32
404
        } else {
405
16403
            glyph_y.floor() as i32
406
        };
407

            
408
16412
        self.promote_or_rotate_cells(&cell_key);
409
16412
        if !self.cells.contains_key(&cell_key) {
410
            // Build cells from cached path
411
16402
            let path_key = GlyphPathKey {
412
16402
                font_hash,
413
16402
                glyph_id,
414
16402
                ppem,
415
16402
            };
416
16402
            let path_entry = self.paths.get(&path_key);
417
16402
            let cached_cells = path_entry.and_then(|entry| {
418
                use agg_rust::{
419
                    basics::FillingRule, rasterizer_scanline_aa::RasterizerScanlineAa,
420
                    trans_affine::TransAffine,
421
                };
422
6
                let (path, _) = entry.as_ref()?;
423
6
                let frac_x = f64::from(subpx_x) * 0.25;
424
6
                let frac_y = f64::from(subpx_y) * 0.25;
425

            
426
6
                let mut ras = RasterizerScanlineAa::new();
427
6
                ras.filling_rule(FillingRule::NonZero);
428

            
429
6
                let transform = if is_hinted {
430
                    if rescale_hinted {
431
                        let (sx, sy) = hinted_outline_scale(hint_correction);
432
                        let mut t = TransAffine::new_scaling(sx, sy);
433
                        t.multiply(&TransAffine::new_translation(frac_x, frac_y));
434
                        t
435
                    } else {
436
                        TransAffine::new_translation(frac_x, frac_y)
437
                    }
438
                } else {
439
6
                    let mut t = TransAffine::new_scaling_uniform(f64::from(scale));
440
6
                    t.multiply(&TransAffine::new_translation(frac_x, frac_y));
441
6
                    t
442
                };
443

            
444
                // Feed the cached glyph vertices through the transform via ConvTransform
445
                // (upstream removed add_path_vertices_transformed), then flatten the
446
                // quadratic curve3 segments adaptively via ConvCurve. Without the
447
                // ConvCurve stage the rasterizer walks curve3 verbs as straight
448
                // lines THROUGH the control points, which turns every bowl into a
449
                // chiseled polygon — invisible at UI sizes, obvious "blocky" curves
450
                // at 24px+ (Lorem-ipsum headline comparison vs Chrome).
451
6
                let mut src = agg_rust::conv_curve::ConvCurve::new(
452
6
                    agg_rust::conv_transform::ConvTransform::new(
453
6
                        SliceVertexSource::new(path.vertices()),
454
6
                        transform,
455
                    ),
456
                );
457
6
                ras.add_path(&mut src, 0);
458
6
                let cells = ras.outline_cells_sorted();
459
6
                if cells.is_empty() {
460
                    None
461
                } else {
462
6
                    Some(CachedCells { cells })
463
                }
464
6
            });
465
16402
            self.cells.insert(cell_key, cached_cells);
466
10
        }
467

            
468
16412
        let entry = self.cells.get(&cell_key)?;
469
16412
        entry.as_ref().map(|cc| (cc.cells.as_slice(), int_x, int_y))
470
16412
    }
471

            
472
    /// Cached rasterizer cells for the **RGB LCD** path — the same idea as
473
    /// [`Self::get_or_build_cells`], but rasterized at 3 horizontal
474
    /// sub-samples per pixel so the cells address individual R/G/B stripes.
475
    ///
476
    /// WHY THIS EXISTS: the cell cache was built for the grayscale path, and
477
    /// the LCD path — added later, and on by default — never used it. It
478
    /// re-flattened and re-rasterized every glyph on screen on every frame,
479
    /// which measured 40 ms of a 46 ms frame for a 30-paragraph document
480
    /// (`layout/tests/frame_perf.rs`), against 0.8 ms for the whole layout.
481
    /// Grayscale, which does use the cache, renders the same document in
482
    /// 18 ms. This closes that gap.
483
    ///
484
    /// Returned offsets are `(cells, int_x, int_y)` where `int_x` is in
485
    /// WHOLE PIXELS — the caller multiplies by 3 when adding the cells,
486
    /// because the cells' own x axis is already in stripe units.
487
    ///
488
    /// Horizontal sub-pixel positioning buckets at 1/3 px rather than the
489
    /// grayscale path's 1/4 px: 1/3 px is exactly what a 3× rasterizer can
490
    /// resolve, so nothing visible is given up, and 3 buckets per glyph keeps
491
    /// the cache small. The baseline is always grid-snapped (crisp vertical),
492
    /// matching what the uncached LCD path did.
493
    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] // bounded graphics/coord/
494
                                                                       // font/fixed-point/
495
                                                                       // debug-marker cast
496
7673989
    pub fn get_or_build_cells_lcd(
497
7673989
        &mut self,
498
7673989
        font_hash: u64,
499
7673989
        glyph_id: u16,
500
7673989
        ppem: u16,
501
7673989
        glyph_x: f32,
502
7673989
        glyph_y: f32,
503
7673989
        scale: f32,
504
7673989
        is_hinted: bool,
505
7673989
        hint_correction: f32,
506
7673989
    ) -> Option<(&[CellAa], i32, i32)> {
507
7673989
        let _p = crate::probe::Probe::span("glyph_cache_lcd_lookup");
508

            
509
7673989
        let rescale_hinted = is_hinted && (hint_correction - 1.0).abs() > 1e-4;
510
7673989
        let subpx = text_subpixel_enabled();
511

            
512
        // Mirrors the uncached LCD path exactly: fractional x when sub-pixel
513
        // positioning is on, rounded x when it is off, always-rounded y.
514
7673989
        let (int_x, subpx_x) = if subpx {
515
7673989
            (glyph_x.floor() as i32, quantize_subpx_lcd(glyph_x))
516
        } else {
517
            (glyph_x.round() as i32, 0)
518
        };
519
7673989
        let int_y = glyph_y.round() as i32;
520

            
521
7673989
        debug_assert!(
522
            (0.0..65536.0).contains(&scale),
523
            "scale out of range for fixed-point: {scale}"
524
        );
525
7673989
        let scale_fixed = if is_hinted {
526
7666727
            if rescale_hinted {
527
                (hint_correction * 65536.0) as u32
528
            } else {
529
7666727
                0
530
            }
531
        } else {
532
7262
            (scale * 65536.0) as u32
533
        };
534

            
535
7673989
        let cell_key = GlyphCellKey {
536
7673989
            font_hash,
537
7673989
            glyph_id,
538
7673989
            ppem,
539
7673989
            scale_fixed,
540
7673989
            subpx_x,
541
7673989
            subpx_y: 0,
542
7673989
            x_subsamples: 3,
543
7673989
        };
544

            
545
7673989
        self.promote_or_rotate_cells(&cell_key);
546
7673989
        if !self.cells.contains_key(&cell_key) {
547
18142
            let path_key = GlyphPathKey {
548
18142
                font_hash,
549
18142
                glyph_id,
550
18142
                ppem,
551
18142
            };
552
18142
            let cached_cells = self.paths.get(&path_key).and_then(|entry| {
553
                use agg_rust::{
554
                    basics::FillingRule, rasterizer_scanline_aa::RasterizerScanlineAa,
555
                    trans_affine::TransAffine,
556
                };
557
18142
                let (path, _) = entry.as_ref()?;
558

            
559
                // Path units -> pixels, same rule as the uncached path: a
560
                // hinted outline at integer ppem is already pixel-space,
561
                // a fractional effective size rescales by hint_correction,
562
                // an unhinted outline is in font units.
563
17361
                let (path_scale_x, path_scale_y) = if is_hinted {
564
16916
                    if rescale_hinted {
565
                        hinted_outline_scale(hint_correction)
566
                    } else {
567
16916
                        (1.0, 1.0)
568
                    }
569
                } else {
570
445
                    (f64::from(scale), f64::from(scale))
571
                };
572

            
573
                // Triple the x axis, then shift by the sub-pixel bucket.
574
                // The bucket is a fraction of a PIXEL, and the axis is in
575
                // stripes, so it converts as `3 * k / BUCKETS`.
576
17361
                let frac_stripes = 3.0 * f64::from(subpx_x) / f64::from(LCD_SUBPX_BUCKETS);
577
17361
                let mut t = TransAffine::new_scaling(3.0 * path_scale_x, path_scale_y);
578
17361
                t.multiply(&TransAffine::new_translation(frac_stripes, 0.0));
579

            
580
17361
                let mut ras = RasterizerScanlineAa::new();
581
17361
                ras.filling_rule(FillingRule::NonZero);
582
                // ConvCurve flattens the quadratic curve3 verbs adaptively;
583
                // without it the rasterizer draws straight lines THROUGH the
584
                // control points and every bowl renders as a chiseled polygon.
585
17361
                let mut src = agg_rust::conv_curve::ConvCurve::new(
586
17361
                    agg_rust::conv_transform::ConvTransform::new(
587
17361
                        SliceVertexSource::new(path.vertices()),
588
17361
                        t,
589
                    ),
590
                );
591
17361
                ras.add_path(&mut src, 0);
592
17361
                let cells = ras.outline_cells_sorted();
593
17361
                if cells.is_empty() {
594
                    None
595
                } else {
596
17361
                    Some(CachedCells { cells })
597
                }
598
18142
            });
599
18142
            self.cells.insert(cell_key, cached_cells);
600
7655847
        }
601

            
602
7673989
        let entry = self.cells.get(&cell_key)?;
603
7673989
        entry.as_ref().map(|cc| (cc.cells.as_slice(), int_x, int_y))
604
7673989
    }
605
}
606

            
607
/// Build a hinted glyph path using TrueType bytecode hinting.
608
///
609
/// The returned path is in pixel coordinates (1 unit = 1 pixel at the given ppem).
610
/// Returns `None` if the glyph has no raw hinting data or hinting fails.
611
/// Read a glyph's left side bearing (font units) straight from the `hmtx`
612
/// table. Mirrors the `FreeType` `TT_Get_HMetrics` lookup used to place phantom
613
/// point pp1 at `xMin - lsb`. Returns `None` if hmtx is unavailable.
614
6636
fn glyph_lsb(parsed_font: &ParsedFont, glyph_id: u16) -> Option<i16> {
615
6636
    let (off, len) = parsed_font.hmtx_range;
616
6636
    if len == 0 {
617
        return None;
618
6636
    }
619
6636
    let bytes = parsed_font.original_bytes.as_ref()?;
620
6635
    let hmtx = bytes.as_ref().get(off..off + len)?;
621
6635
    let num = usize::from(parsed_font.hhea_table.num_h_metrics);
622
6635
    if num == 0 {
623
1
        return None;
624
6634
    }
625
6634
    let gid = usize::from(glyph_id);
626
    // longHorMetric[i] = { advanceWidth: u16, lsb: i16 } (4 bytes) for i < num;
627
    // trailing leftSideBearing: i16 array for the remaining glyphs.
628
6634
    let lsb_off = if gid < num {
629
6427
        gid * 4 + 2
630
    } else {
631
207
        num * 4 + (gid - num) * 2
632
    };
633
6634
    let b = hmtx.get(lsb_off..lsb_off + 2)?;
634
6632
    Some(i16::from_be_bytes([b[0], b[1]]))
635
6636
}
636

            
637
7103
fn build_hinted_path(
638
7103
    glyph_id: u16,
639
7103
    glyph: &OwnedGlyph,
640
7103
    parsed_font: &ParsedFont,
641
7103
    ppem: u16,
642
7103
) -> Option<PathStorage> {
643
    use allsorts::hinting::f26dot6::F26Dot6;
644
7103
    let raw_points = glyph.raw_points.as_ref()?;
645
6758
    let raw_on_curve = glyph.raw_on_curve.as_ref()?;
646
6758
    let raw_contour_ends = glyph.raw_contour_ends.as_ref()?;
647
6758
    let instructions = glyph.instructions.as_ref()?;
648

            
649
6758
    if raw_points.is_empty() || raw_contour_ends.is_empty() {
650
1
        return None;
651
6757
    }
652

            
653
6757
    let hint_mutex = parsed_font.hint_instance.as_ref()?;
654
6630
    let mut hint = hint_mutex.lock().ok()?;
655

            
656
6630
    let upem = parsed_font.font_metrics.units_per_em;
657
6630
    if upem == 0 {
658
1
        return None;
659
6629
    }
660

            
661
    // Set up hinting for this ppem (scales CVT, runs prep)
662
6629
    if hint.set_ppem(ppem, f64::from(ppem)).is_err() {
663
        return None;
664
6629
    }
665

            
666
    // Scale raw points from font units to F26Dot6
667
6629
    let scale = allsorts::hinting::f26dot6::compute_scale(ppem, upem);
668

            
669
6629
    let points_f26dot6: Vec<(i32, i32)> = raw_points
670
6629
        .iter()
671
155495
        .map(|&(x, y)| {
672
155495
            let sx = F26Dot6::from_funits(i32::from(x), scale);
673
155495
            let sy = F26Dot6::from_funits(i32::from(y), scale);
674
155495
            (sx.to_bits(), sy.to_bits())
675
155495
        })
676
6629
        .collect();
677

            
678
    // Scale advance width to F26Dot6 for phantom points
679
6629
    let adv_f26dot6 = F26Dot6::from_funits(i32::from(glyph.horz_advance), scale).to_bits();
680

            
681
    // Phantom point pp1.x = (xMin - lsb) scaled (FreeType tt_loader_set_pp).
682
    // Threading the real lsb makes left-side-bearing grid-fitting match FreeType
683
    // for fonts where lsb != xMin; when lsb is unavailable, fall back to xMin
684
    // (i.e. lsb == xMin => pp1.x = 0, the previous hardcoded behaviour).
685
6629
    let x_min = i32::from(glyph.bounding_box.min_x);
686
6629
    let lsb = glyph_lsb(parsed_font, glyph_id).map_or(x_min, i32::from);
687
6629
    let pp1_x_f26dot6 = F26Dot6::from_funits(x_min - lsb, scale).to_bits();
688

            
689
    // Run hinting and capture the POST-hinting on-curve flags. FLIPPT/FLIPRGON/
690
    // FLIPRGOFF can flip a point between on-curve and off-curve during the glyph
691
    // program; the contour builder must use the updated flags, not the original
692
    // raw_on_curve, or it treats a flipped control point as a line endpoint (and
693
    // vice versa), kinking the outline.
694
6629
    let Ok((hinted, hinted_on_curve)) = hint.hint_glyph_with_flags_pp1(
695
6629
        &points_f26dot6,
696
6629
        raw_on_curve,
697
6629
        raw_contour_ends,
698
6629
        instructions,
699
6629
        adv_f26dot6,
700
6629
        pp1_x_f26dot6,
701
6629
    ) else {
702
        return None;
703
    };
704
6629
    drop(hint);
705

            
706
    // Optional "light" hinting (CoreText / DirectWrite grayscale style): keep the
707
    // grid-fitted Y (baseline, x-height and horizontal stems snap crisply to the
708
    // pixel grid) but restore the UNHINTED fractional X, so vertical stems stay
709
    // sub-pixel-positioned and anti-alias to soft gray instead of snapping to a
710
    // hard full-black 1px column (Windows-style full grid-fit). This is what
711
    // converges our CPU text onto CoreText — full bytecode hinting over-snaps X,
712
    // rendering stems thinner + darker than CoreText's. On by default; set
713
    // AZ_HINT_LIGHT=0 to force Windows-style full grid-fit. The interpreter still
714
    // runs in full (its Y output + FLIP'd on-curve flags are used), so no hinting
715
    // correctness is lost — only the X axis is left sub-pixel for grayscale AA.
716
6629
    if hint_light_enabled() {
717
6629
        let light: Vec<(i32, i32)> = hinted
718
6629
            .iter()
719
6629
            .enumerate()
720
155495
            .map(|(i, &(hx, hy))| (points_f26dot6.get(i).map_or(hx, |p| p.0), hy))
721
6629
            .collect();
722
6629
        return build_path_from_contours(&light, &hinted_on_curve, raw_contour_ends);
723
    }
724

            
725
    // Build path from hinted points using TrueType quadratic contour conventions
726
    build_path_from_contours(&hinted, &hinted_on_curve, raw_contour_ends)
727
7103
}
728

            
729
/// Scaling Y would move the grid-fitted baseline and stems off the pixel grid.
730
fn hinted_outline_scale(hint_correction: f32) -> (f64, f64) {
731
    (f64::from(hint_correction), 1.0)
732
}
733

            
734
/// Whether to run the font's TrueType hinting bytecode AT ALL.
735
///
736
/// Platform default: OFF on macOS, ON elsewhere. CoreText never executes TT
737
/// instructions (no macOS browser hints text), so running the untuned
738
/// programs of Apple system fonts snapped individual glyphs' stems and
739
/// x-heights to DIFFERENT pixel rows than their neighbours — the reported
740
/// "the r is out of line with the ea", "the u is not tall enough".
741
/// `FreeType` and `ClearType` conventions expect grid-fitting, so Linux and
742
/// Windows keep
743
/// it. Override with `AZ_TEXT_HINTING=1` / `0`. Read once.
744
529794
pub(crate) fn text_hinting_enabled() -> bool {
745
    static V: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
746
529794
    *V.get_or_init(|| {
747
32
        std::env::var("AZ_TEXT_HINTING").map_or(cfg!(not(target_os = "macos")), |s| {
748
10
            !(s == "0" || s.eq_ignore_ascii_case("false"))
749
10
        })
750
32
    })
751
529794
}
752

            
753
/// Whether to apply CoreText-style "light" hinting (grid-fit Y only, fractional X).
754
/// ON by default (matches CoreText / modern browser grayscale rendering); set
755
/// `AZ_HINT_LIGHT=0` (or `false`) to force Windows-style full grid-fit. Read once.
756
1236450
pub(crate) fn hint_light_enabled() -> bool {
757
    static V: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
758
1236450
    *V.get_or_init(|| {
759
32
        std::env::var("AZ_HINT_LIGHT")
760
32
            .map(|s| !(s == "0" || s.eq_ignore_ascii_case("false")))
761
32
            .unwrap_or(true)
762
32
    })
763
1236450
}
764

            
765
/// Whether to place each glyph ORIGIN at a sub-pixel HORIZONTAL position (a
766
/// 1/4-pixel X bucket) instead of snapping it to a whole pixel.
767
///
768
/// ON by default. This is the horizontal half of the light-hinting philosophy
769
/// (crisp vertical, soft/sub-pixel horizontal): the grid-fitted glyph *outline*
770
/// still snaps its stems and baseline to the pixel grid, but the pen advances
771
/// accumulate at fractional precision so a run of glyphs lands where CoreText
772
/// (which positions glyphs at fractional x) puts them, rather than each origin
773
/// rounding to an integer pixel and drifting the whole line. Set
774
/// `AZ_TEXT_SUBPIXEL=0` (or `false`) to force integer X placement. Read once.
775
8016301
pub(crate) fn text_subpixel_enabled() -> bool {
776
    static V: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
777
8016301
    *V.get_or_init(|| {
778
32
        std::env::var("AZ_TEXT_SUBPIXEL")
779
32
            .map(|s| !(s == "0" || s.eq_ignore_ascii_case("false")))
780
32
            .unwrap_or(true)
781
32
    })
782
8016301
}
783

            
784
/// Build an agg `PathStorage` from TrueType contour data (points in `F26Dot6`).
785
///
786
/// Matches allsorts' `visit_simple_glyph_outline` algorithm exactly:
787
/// - On-curve points are endpoints of line/curve segments
788
/// - Off-curve points are quadratic Bézier control points
789
/// - Two consecutive off-curve points have an implicit on-curve midpoint
790
/// - Y is negated for screen coordinates (font Y-up → screen Y-down)
791
/// - The origin point is NOT revisited in the loop; `close()` handles the final segment
792
#[must_use]
793
6647
pub fn build_path_from_contours(
794
6647
    points: &[(i32, i32)],
795
6647
    on_curve: &[bool],
796
6647
    contour_ends: &[u16],
797
6647
) -> Option<PathStorage> {
798
    use agg_rust::basics::PATH_FLAGS_NONE;
799

            
800
6647
    let mut path = PathStorage::new();
801
6647
    let mut has_ops = false;
802
6647
    let mut contour_start = 0usize;
803

            
804
19784
    for &end_idx in contour_ends {
805
13137
        let end = end_idx as usize;
806
13137
        if end >= points.len() || contour_start > end {
807
7
            contour_start = end + 1;
808
7
            continue;
809
13130
        }
810

            
811
13130
        let pts = &points[contour_start..=end];
812
13130
        let flags = &on_curve[contour_start..=end];
813
13130
        let n = pts.len();
814
13130
        if n < 2 {
815
31
            contour_start = end + 1;
816
31
            continue;
817
13099
        }
818

            
819
        // Helper: get point as (f64, f64) with Y negated
820
187530
        let px = |i: usize| -> (f64, f64) {
821
187530
            (
822
187530
                f64::from(f26_to_px(pts[i].0)),
823
187530
                f64::from(-f26_to_px(pts[i].1)),
824
187530
            )
825
187530
        };
826
13099
        let mid =
827
32037
            |a: (f64, f64), b: (f64, f64)| -> (f64, f64) { ((a.0 + b.0) * 0.5, (a.1 + b.1) * 0.5) };
828

            
829
        // Determine origin and processing range (matching allsorts' calculate_origin)
830
13099
        let (origin, start, until) = if flags[0] {
831
13057
            (px(0), 1usize, n)
832
42
        } else if flags[n - 1] {
833
41
            (px(n - 1), 0usize, n - 1)
834
        } else {
835
1
            (mid(px(0), px(n - 1)), 0usize, n)
836
        };
837

            
838
13099
        path.move_to(origin.0, origin.1);
839
13099
        has_ops = true;
840

            
841
13099
        let mut i = start;
842
131272
        while i < until {
843
118173
            if flags[i] {
844
58409
                // On-curve: line segment
845
58409
                let to = px(i);
846
58409
                path.line_to(to.0, to.1);
847
58409
                i += 1;
848
58409
            } else {
849
                // Off-curve control point
850
59764
                let ctrl = px(i);
851
59764
                let next = i + 1;
852
59764
                if next < until {
853
56257
                    if flags[next] {
854
24221
                        // Next is on-curve: quad to it, consume both
855
24221
                        let to = px(next);
856
24221
                        path.curve3(ctrl.0, ctrl.1, to.0, to.1);
857
24221
                        i = next + 1;
858
32036
                    } else {
859
32036
                        // Next is also off-curve: quad to implicit midpoint
860
32036
                        let m = mid(ctrl, px(next));
861
32036
                        path.curve3(ctrl.0, ctrl.1, m.0, m.1);
862
32036
                        i = next;
863
32036
                    }
864
3507
                } else {
865
3507
                    // End of range: curve back to origin
866
3507
                    path.curve3(ctrl.0, ctrl.1, origin.0, origin.1);
867
3507
                    i = next;
868
3507
                }
869
            }
870
        }
871
13099
        path.close_polygon(PATH_FLAGS_NONE);
872

            
873
13099
        contour_start = end + 1;
874
    }
875

            
876
6647
    if !has_ops {
877
8
        return None;
878
6639
    }
879
6639
    Some(path)
880
6647
}
881

            
882
/// Convert `F26Dot6` value to pixel coordinate (f32).
883
#[inline]
884
#[allow(clippy::cast_precision_loss)] // bounded graphics/coord/font/fixed-point/debug-marker cast
885
375099
fn f26_to_px(v: i32) -> f32 {
886
375099
    v as f32 / 64.0
887
375099
}
888

            
889
#[cfg(test)]
890
#[allow(
891
    // exact float comparisons are intentional: power-of-two / midpoint
892
    // arithmetic with exactly representable results
893
    clippy::float_cmp,
894
    clippy::cast_precision_loss,
895
    clippy::cast_possible_truncation,
896
    clippy::cast_lossless
897
)]
898
mod autotest_generated {
899
    use std::{
900
        panic::{catch_unwind, AssertUnwindSafe},
901
        sync::Arc,
902
    };
903

            
904
    use agg_rust::basics::{
905
        PATH_CMD_CURVE3, PATH_CMD_END_POLY, PATH_CMD_LINE_TO, PATH_CMD_MOVE_TO, PATH_FLAGS_CLOSE,
906
    };
907
    use azul_core::resources::OwnedGlyphBoundingBox;
908

            
909
    use super::*;
910

            
911
    // ---------------------------------------------------------------------
912
    // helpers
913
    // ---------------------------------------------------------------------
914

            
915
    /// A real system/repo font, or `None` — font-dependent tests skip rather
916
    /// than guess. Source bytes are retained so `glyph_lsb` can read `hmtx`.
917
    fn test_font() -> Option<ParsedFont> {
918
        let candidates = [
919
            "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
920
            "/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf",
921
            "/System/Library/Fonts/Supplemental/Times New Roman.ttf",
922
            "C:/Windows/Fonts/arial.ttf",
923
            concat!(
924
                env!("CARGO_MANIFEST_DIR"),
925
                "/../examples/assets/fonts/SourceSerifPro-Regular.ttf"
926
            ),
927
        ];
928
        for path in candidates {
929
            let Ok(bytes) = std::fs::read(path) else {
930
                continue;
931
            };
932
            let arc = Arc::new(rust_fontconfig::FontBytes::Owned(Arc::from(
933
                bytes.as_slice(),
934
            )));
935
            if let Some(font) =
936
                ParsedFont::from_bytes(&bytes, 0, &mut Vec::new()).map(|f| f.with_source_bytes(arc))
937
            {
938
                return Some(font);
939
            }
940
        }
941
        None
942
    }
943

            
944
    /// A glyph with no outline at all (the "space character" shape the
945
    /// `get_or_build` doc mentions) — buildable without a font.
946
    fn empty_glyph() -> OwnedGlyph {
947
        OwnedGlyph {
948
            bounding_box: OwnedGlyphBoundingBox {
949
                max_x: 0,
950
                max_y: 0,
951
                min_x: 0,
952
                min_y: 0,
953
            },
954
            horz_advance: 0,
955
            outline: Vec::new(),
956
            phantom_points: None,
957
            raw_points: None,
958
            raw_on_curve: None,
959
            raw_contour_ends: None,
960
            instructions: None,
961
        }
962
    }
963

            
964
    /// `('A', decoded glyph)` from `font`, if the font has one with an outline.
965
    fn glyph_a(font: &ParsedFont) -> Option<(u16, Arc<OwnedGlyph>)> {
966
        let gid = font.lookup_glyph_index('A' as u32)?;
967
        let glyph = font.get_or_decode_glyph(gid)?;
968
        Some((gid, glyph))
969
    }
970

            
971
    // ---------------------------------------------------------------------
972
    // quantize_subpx — numeric
973
    // ---------------------------------------------------------------------
974

            
975
    #[test]
976
    fn quantize_subpx_zero_and_quarter_buckets() {
977
        assert_eq!(quantize_subpx(0.0), 0);
978
        assert_eq!(quantize_subpx(0.24), 0);
979
        assert_eq!(quantize_subpx(0.25), 1);
980
        assert_eq!(quantize_subpx(0.5), 2);
981
        assert_eq!(quantize_subpx(0.75), 3);
982
        // 0.999 * 4 == 3.996, clamped by `.min(3.0)` — must not reach bucket 4.
983
        assert_eq!(quantize_subpx(0.999), 3);
984
        // Only the fractional part matters: whole pixels drop out.
985
        assert_eq!(quantize_subpx(1.0), 0);
986
        assert_eq!(quantize_subpx(2.25), 1);
987
        assert_eq!(quantize_subpx(1024.5), 2);
988
    }
989

            
990
    #[test]
991
    fn quantize_subpx_negative_inputs_use_floor_not_truncation() {
992
        // frac - frac.floor() is always in [0, 1), so a negative x lands in the
993
        // bucket of its positive fractional remainder (-0.25 => 0.75 => 3).
994
        assert_eq!(quantize_subpx(-0.25), 3);
995
        assert_eq!(quantize_subpx(-0.5), 2);
996
        assert_eq!(quantize_subpx(-0.75), 1);
997
        assert_eq!(quantize_subpx(-1.0), 0);
998
        assert_eq!(quantize_subpx(-0.0), 0);
999
        assert_eq!(quantize_subpx(-7.25), 3);
    }
    #[test]
    fn quantize_subpx_nan_and_infinities_are_defined() {
        // NaN.floor() == NaN, NaN - NaN == NaN, and f32::min ignores NaN, so the
        // clamp yields 3.0. Defined and non-panicking, if arguably surprising:
        // a NaN position buckets as if it were 3/4 of a pixel.
        assert_eq!(quantize_subpx(f32::NAN), 3);
        assert_eq!(quantize_subpx(f32::INFINITY), 3);
        assert_eq!(quantize_subpx(f32::NEG_INFINITY), 3);
    }
    #[test]
    fn quantize_subpx_never_exceeds_three() {
        let extremes = [
            f32::MAX,
            f32::MIN,
            f32::MIN_POSITIVE,
            -f32::MIN_POSITIVE,
            f32::EPSILON,
            1e30,
            -1e30,
            16_777_216.0, // 2^24: f32 loses the fractional bit entirely
            -16_777_217.0,
            f32::NAN,
            f32::INFINITY,
            f32::NEG_INFINITY,
        ];
        for v in extremes {
            assert!(
                quantize_subpx(v) <= 3,
                "quantize_subpx({v}) escaped the 0..=3 bucket range"
            );
        }
        for i in -2000..2000 {
            let v = f64_to_f32(f64::from(i) * 0.017);
            assert!(quantize_subpx(v) <= 3, "quantize_subpx({v}) > 3");
        }
    }
    #[allow(clippy::cast_possible_truncation)]
    fn f64_to_f32(v: f64) -> f32 {
        v as f32
    }
    // ---------------------------------------------------------------------
    // f26_to_px — numeric
    // ---------------------------------------------------------------------
    #[test]
    fn f26_to_px_zero_and_exact_fractions() {
        assert_eq!(f26_to_px(0), 0.0);
        assert_eq!(f26_to_px(64), 1.0);
        assert_eq!(f26_to_px(-64), -1.0);
        assert_eq!(f26_to_px(32), 0.5);
        assert_eq!(f26_to_px(16), 0.25);
        assert_eq!(f26_to_px(1), 1.0 / 64.0);
        assert_eq!(f26_to_px(-1), -1.0 / 64.0);
    }
    #[test]
    fn f26_to_px_min_max_stay_finite() {
        // i32::MAX rounds up to 2^31 in f32; both ends are exactly ±2^25 px.
        assert_eq!(f26_to_px(i32::MAX), 33_554_432.0);
        assert_eq!(f26_to_px(i32::MIN), -33_554_432.0);
        assert!(f26_to_px(i32::MAX).is_finite());
        assert!(f26_to_px(i32::MIN).is_finite());
    }
    #[test]
    fn f26_to_px_round_trips_for_exactly_representable_inputs() {
        // /64 is a power-of-two scaling: exact (no rounding) for |v| <= 2^24.
        for v in [
            0,
            1,
            -1,
            63,
            64,
            -64,
            4096,
            -4096,
            8_388_607,
            -8_388_607,
            16_777_216,
            -16_777_216,
        ] {
            let px = f26_to_px(v);
            assert_eq!(px * 64.0, v as f32, "f26_to_px({v}) did not round-trip");
        }
    }
    #[test]
    fn f26_to_px_is_monotonic() {
        let ladder = [i32::MIN, -1_000_000, -64, -1, 0, 1, 64, 1_000_000, i32::MAX];
        for w in ladder.windows(2) {
            assert!(
                f26_to_px(w[0]) <= f26_to_px(w[1]),
                "f26_to_px is not monotonic between {} and {}",
                w[0],
                w[1]
            );
        }
    }
    // ---------------------------------------------------------------------
    // build_path_from_contours — structure / round-trip of the TrueType rules
    // ---------------------------------------------------------------------
    #[test]
    fn build_path_from_contours_empty_inputs_return_none() {
        assert!(build_path_from_contours(&[], &[], &[]).is_none());
        // Points but no contours => nothing emitted.
        assert!(build_path_from_contours(&[(0, 0), (64, 0)], &[true, true], &[]).is_none());
        // Contour end but no points => out-of-range end, skipped.
        assert!(build_path_from_contours(&[], &[], &[0]).is_none());
    }
    #[test]
    fn build_path_from_contours_single_point_contour_is_skipped() {
        // n < 2 => degenerate contour, no path ops at all.
        assert!(build_path_from_contours(&[(0, 0)], &[true], &[0]).is_none());
    }
    #[test]
    fn build_path_from_contours_out_of_range_contour_end_is_skipped_not_indexed() {
        let pts = [(0, 0), (64, 64)];
        let oc = [true, true];
        assert!(build_path_from_contours(&pts, &oc, &[10]).is_none());
        // u16::MAX end: `end + 1` must not overflow the usize cursor either.
        assert!(build_path_from_contours(&pts, &oc, &[u16::MAX]).is_none());
        // Skipping a bogus end still advances the cursor to `end + 1`, so every
        // later contour falls into the `contour_start > end` branch too. The
        // whole glyph fails closed (None) instead of indexing out of bounds.
        assert!(
            build_path_from_contours(&pts, &oc, &[99, 1]).is_none(),
            "a bogus contour end poisons the cursor for the rest of the glyph"
        );
    }
    #[test]
    fn build_path_from_contours_line_contour_emits_move_line_close() {
        let path = build_path_from_contours(&[(0, 0), (128, 64)], &[true, true], &[1])
            .expect("two on-curve points form a contour");
        let v = path.vertices();
        assert_eq!(v.len(), 3, "expected move_to + line_to + close");
        assert_eq!(v[0].cmd, PATH_CMD_MOVE_TO);
        assert_eq!(v[0].x, 0.0);
        assert_eq!(v[0].y, 0.0);
        assert_eq!(v[1].cmd, PATH_CMD_LINE_TO);
        assert_eq!(v[1].x, 2.0, "128 F26Dot6 units == 2 px");
        assert_eq!(v[1].y, -1.0, "Y must be negated for screen coords");
        assert_eq!(v[2].cmd, PATH_CMD_END_POLY | PATH_FLAGS_CLOSE);
    }
    #[test]
    fn build_path_from_contours_offcurve_point_becomes_curve3() {
        let path =
            build_path_from_contours(&[(0, 0), (64, 64), (128, 0)], &[true, false, true], &[2])
                .expect("on/off/on contour");
        let v = path.vertices();
        assert_eq!(v.len(), 4, "move_to + curve3(ctrl,to) + close");
        assert_eq!(v[0].cmd, PATH_CMD_MOVE_TO);
        assert_eq!(v[1].cmd, PATH_CMD_CURVE3);
        assert_eq!((v[1].x, v[1].y), (1.0, -1.0), "control point");
        assert_eq!(v[2].cmd, PATH_CMD_CURVE3);
        assert_eq!((v[2].x, v[2].y), (2.0, 0.0), "curve endpoint");
        assert_eq!(v[3].cmd, PATH_CMD_END_POLY | PATH_FLAGS_CLOSE);
    }
    #[test]
    fn build_path_from_contours_two_offcurve_points_insert_implicit_midpoint() {
        let path = build_path_from_contours(
            &[(0, 0), (64, 64), (128, 64), (192, 0)],
            &[true, false, false, true],
            &[3],
        )
        .expect("on/off/off/on contour");
        let v = path.vertices();
        assert_eq!(v.len(), 6, "move_to + 2 curve3 + close");
        // First quad ends at the implicit midpoint of the two control points:
        // mid((1,-1), (2,-1)) == (1.5, -1).
        assert_eq!((v[1].x, v[1].y), (1.0, -1.0));
        assert_eq!((v[2].x, v[2].y), (1.5, -1.0), "implicit on-curve midpoint");
        assert_eq!((v[3].x, v[3].y), (2.0, -1.0));
        assert_eq!((v[4].x, v[4].y), (3.0, 0.0));
    }
    #[test]
    fn build_path_from_contours_all_offcurve_closes_back_to_the_synthetic_origin() {
        // No on-curve point anywhere: origin is the midpoint of first & last,
        // and the final curve must return to it.
        let path =
            build_path_from_contours(&[(0, 0), (64, 64), (128, 0)], &[false, false, false], &[2])
                .expect("all-off-curve contour");
        let v = path.vertices();
        assert_eq!(v.len(), 8, "move_to + 3 curve3 + close");
        assert_eq!(v[0].cmd, PATH_CMD_MOVE_TO);
        assert_eq!((v[0].x, v[0].y), (1.0, 0.0), "origin = mid(first, last)");
        let last_pt = v[6];
        assert_eq!(
            (last_pt.x, last_pt.y),
            (v[0].x, v[0].y),
            "final curve3 must land back on the origin"
        );
        assert_eq!(v[7].cmd, PATH_CMD_END_POLY | PATH_FLAGS_CLOSE);
    }
    #[test]
    fn build_path_from_contours_leading_offcurve_uses_trailing_oncurve_as_origin() {
        // flags[0] off, flags[n-1] on => origin is the LAST point, range [0, n-1).
        let path = build_path_from_contours(&[(64, 64), (128, 0)], &[false, true], &[1])
            .expect("off/on contour");
        let v = path.vertices();
        assert_eq!(v.len(), 4);
        assert_eq!(v[0].cmd, PATH_CMD_MOVE_TO);
        assert_eq!((v[0].x, v[0].y), (2.0, 0.0), "origin is the on-curve point");
        assert_eq!(v[1].cmd, PATH_CMD_CURVE3);
        assert_eq!((v[2].x, v[2].y), (2.0, 0.0), "curve returns to the origin");
    }
    #[test]
    fn build_path_from_contours_multiple_contours_emit_multiple_subpaths() {
        let pts = [(0, 0), (64, 0), (0, 64), (64, 64)];
        let oc = [true; 4];
        let path = build_path_from_contours(&pts, &oc, &[1, 3]).expect("two contours");
        let v = path.vertices();
        assert_eq!(v.len(), 6, "two × (move_to + line_to + close)");
        let moves = v.iter().filter(|x| x.cmd == PATH_CMD_MOVE_TO).count();
        assert_eq!(moves, 2, "each contour must start its own subpath");
    }
    #[test]
    fn build_path_from_contours_non_monotonic_contour_ends_do_not_panic() {
        let pts = [(0, 0), (64, 0), (0, 64), (64, 64)];
        let oc = [true; 4];
        // Descending ends: the second contour has contour_start > end => skipped.
        let path = build_path_from_contours(&pts, &oc, &[1, 0]).expect("first contour builds");
        assert_eq!(path.vertices().len(), 3);
        // Duplicate ends: likewise skipped, not re-emitted.
        let dup = build_path_from_contours(&pts, &oc, &[1, 1]).expect("first contour builds");
        assert_eq!(dup.vertices().len(), 3);
    }
    #[test]
    fn build_path_from_contours_extra_on_curve_flags_are_harmless() {
        // on_curve longer than points: the extra flags must simply go unread.
        let path = build_path_from_contours(&[(0, 0), (64, 0)], &[true; 8], &[1])
            .expect("contour builds with a too-long flag slice");
        assert_eq!(path.vertices().len(), 3);
    }
    #[test]
    #[should_panic(expected = "out of range")]
    fn build_path_from_contours_short_on_curve_slice_panics() {
        // BUG (documented, not weakened): the bounds check only compares the
        // contour end against `points.len()`, then slices `on_curve` with the
        // same range. A caller passing a shorter `on_curve` than `points` gets
        // an index-out-of-bounds panic out of a `pub fn` that otherwise
        // signals failure by returning `None`.
        let _ = build_path_from_contours(&[(0, 0), (64, 0)], &[true], &[1]);
    }
    #[test]
    fn build_path_from_contours_extreme_coordinates_stay_finite() {
        let pts = [(i32::MIN, i32::MAX), (i32::MAX, i32::MIN), (0, 0)];
        let oc = [true, false, true];
        let path = build_path_from_contours(&pts, &oc, &[2]).expect("extreme contour still builds");
        for v in path.vertices() {
            assert!(
                v.x.is_finite() && v.y.is_finite(),
                "F26Dot6 extremes produced a non-finite vertex: ({}, {})",
                v.x,
                v.y
            );
        }
    }
    // ---------------------------------------------------------------------
    // env-backed predicates
    // ---------------------------------------------------------------------
    #[test]
    fn hint_light_enabled_is_stable_across_calls() {
        // OnceLock-backed: whatever the env says, every call must agree.
        let first = hint_light_enabled();
        assert_eq!(first, hint_light_enabled());
        assert_eq!(first, hint_light_enabled());
    }
    #[test]
    fn text_subpixel_enabled_is_stable_across_calls() {
        let first = text_subpixel_enabled();
        assert_eq!(first, text_subpixel_enabled());
        assert_eq!(first, text_subpixel_enabled());
    }
    // ---------------------------------------------------------------------
    // GlyphCache::new / paths_len / cells_len
    // ---------------------------------------------------------------------
    #[test]
    fn new_cache_is_empty_and_default_matches_new() {
        let cache = GlyphCache::new();
        assert_eq!(cache.paths_len(), 0);
        assert_eq!(cache.cells_len(), 0);
        let def = GlyphCache::default();
        assert_eq!(def.paths_len(), 0);
        assert_eq!(def.cells_len(), 0);
    }
    #[test]
    fn debug_impl_reports_entry_counts_without_touching_agg_types() {
        let cache = GlyphCache::new();
        let s = format!("{cache:?}");
        assert!(s.contains("GlyphCache"), "{s}");
        assert!(s.contains("paths"), "{s}");
        assert!(s.contains("cells"), "{s}");
    }
    // ---------------------------------------------------------------------
    // get_or_build_cells — numeric (needs no font: a path-cache miss is a
    // legitimate, reachable state)
    // ---------------------------------------------------------------------
    #[test]
    fn get_or_build_cells_without_a_cached_path_returns_none_and_negative_caches() {
        let mut cache = GlyphCache::new();
        let got = cache
            .get_or_build_cells(1, 2, 16, 0.0, 0.0, 1.0, false, 1.0)
            .map(|(cells, x, y)| (cells.len(), x, y));
        assert_eq!(got, None, "no path cached => no cells");
        assert_eq!(cache.cells_len(), 1, "the miss must be negative-cached");
        // Idempotent: a repeat lookup does not add a second entry.
        let again = cache
            .get_or_build_cells(1, 2, 16, 0.0, 0.0, 1.0, false, 1.0)
            .map(|(cells, _, _)| cells.len());
        assert_eq!(again, None);
        assert_eq!(cache.cells_len(), 1);
    }
    #[test]
    fn get_or_build_cells_keys_on_the_quarter_pixel_bucket_not_the_raw_position() {
        let mut cache = GlyphCache::new();
        // All of these have a fractional part < 0.25 => same sub-pixel bucket.
        for x in [0.0_f32, 0.1, 0.2, 5.24, 100.0] {
            let _ = cache.get_or_build_cells(7, 3, 16, x, 0.0, 1.0, false, 1.0);
        }
        assert_eq!(cache.cells_len(), 1, "same bucket must reuse one entry");
        // A different bucket (0.5 => bucket 2) is a different key.
        let _ = cache.get_or_build_cells(7, 3, 16, 0.5, 0.0, 1.0, false, 1.0);
        assert_eq!(cache.cells_len(), 2);
        // A different scale is a different key too (scale_fixed is in the key).
        let _ = cache.get_or_build_cells(7, 3, 16, 0.5, 0.0, 2.0, false, 1.0);
        assert_eq!(cache.cells_len(), 3);
    }
    #[test]
    fn get_or_build_cells_extreme_arguments_do_not_panic() {
        let mut cache = GlyphCache::new();
        // is_hinted + scale 0.0 keeps the fixed-point debug_assert satisfied
        // while pushing every *other* argument to its limit.
        for x in [
            0.0_f32,
            f32::MAX,
            f32::MIN,
            f32::NAN,
            f32::INFINITY,
            f32::NEG_INFINITY,
            -0.75,
        ] {
            let got = cache
                .get_or_build_cells(u64::MAX, u16::MAX, u16::MAX, x, x, 0.0, true, 1.0)
                .map(|(cells, _, _)| cells.len());
            assert_eq!(got, None, "empty path cache must yield None for x = {x}");
        }
        // Zero everywhere.
        let zeroed = cache
            .get_or_build_cells(0, 0, 0, 0.0, 0.0, 0.0, false, 0.0)
            .map(|(cells, _, _)| cells.len());
        assert_eq!(zeroed, None);
        // Largest in-range scale (the debug_assert's exclusive upper bound - 1).
        let big = cache
            .get_or_build_cells(0, 0, 0, 0.0, 0.0, 65_535.0, false, 1.0)
            .map(|(cells, _, _)| cells.len());
        assert_eq!(big, None);
    }
    #[test]
    fn get_or_build_cells_nan_hint_correction_falls_back_to_grid_snapped() {
        // (NaN - 1.0).abs() > 1e-4 is FALSE, so a NaN hint_correction is treated
        // exactly like the no-rescale case (scale_fixed = 0) rather than being
        // cast to a garbage fixed-point key. Same key => no extra entry.
        let mut cache = GlyphCache::new();
        let _ = cache.get_or_build_cells(9, 1, 12, 3.5, 4.5, 0.0, true, 1.0);
        assert_eq!(cache.cells_len(), 1);
        let _ = cache.get_or_build_cells(9, 1, 12, 3.5, 4.5, 0.0, true, f32::NAN);
        assert_eq!(
            cache.cells_len(),
            1,
            "NaN hint_correction must collapse onto the grid-snapped key"
        );
    }
    #[test]
    fn get_or_build_cells_negative_scale_is_debug_asserted() {
        let mut cache = GlyphCache::new();
        let res = catch_unwind(AssertUnwindSafe(|| {
            cache
                .get_or_build_cells(1, 1, 16, 0.0, 0.0, -1.0, false, 1.0)
                .map(|(cells, _, _)| cells.len())
        }));
        if cfg!(debug_assertions) {
            assert!(
                res.is_err(),
                "a negative scale must trip the fixed-point range debug_assert"
            );
        } else {
            // Release: the f32 -> u32 cast saturates to 0 instead of wrapping.
            assert_eq!(res.ok().flatten(), None);
        }
    }
    #[test]
    fn get_or_build_cells_rotates_generations_at_the_entry_limit() {
        let mut cache = GlyphCache::new();
        for i in 0..MAX_CELL_ENTRIES as u64 {
            let _ = cache.get_or_build_cells(i, 0, 16, 0.0, 0.0, 1.0, false, 1.0);
        }
        assert_eq!(cache.cells_len(), MAX_CELL_ENTRIES);
        // One past the limit rotates rather than clearing.
        let _ = cache.get_or_build_cells(u64::MAX, 0, 16, 0.0, 0.0, 1.0, false, 1.0);
        assert_eq!(
            cache.cells_len(),
            MAX_CELL_ENTRIES + 1,
            "rotation must DEMOTE the old generation, not delete it"
        );
        for i in 0..MAX_CELL_ENTRIES as u64 {
            let _ = cache.get_or_build_cells(1_000_000 + i, 0, 16, 0.0, 0.0, 1.0, false, 1.0);
        }
        assert!(
            cache.cells_len() <= 2 * MAX_CELL_ENTRIES,
            "cell cache must not grow unbounded, got {}",
            cache.cells_len()
        );
        // `gc()` is the post-present hook: it drops the older generation.
        cache.gc();
        assert!(
            cache.cells_len() <= MAX_CELL_ENTRIES,
            "gc() must release the previous generation"
        );
    }
    // ---------------------------------------------------------------------
    // get_or_build — needs a ParsedFont (skipped when no font is available)
    // ---------------------------------------------------------------------
    #[test]
    fn get_or_build_outlineless_glyph_returns_none_and_caches_the_miss() {
        let Some(font) = test_font() else {
            return; // no font on this machine: skip rather than guess
        };
        let mut cache = GlyphCache::new();
        let glyph = empty_glyph();
        let got = cache
            .get_or_build(1, 0, &glyph, &font, 0)
            .map(|c| c.is_hinted);
        assert_eq!(got, None, "a glyph with no outline must yield None");
        assert_eq!(cache.paths_len(), 1, "the miss must be negative-cached");
    }
    #[test]
    fn get_or_build_extreme_ids_and_ppem_do_not_panic() {
        let Some(font) = test_font() else {
            return;
        };
        let mut cache = GlyphCache::new();
        let glyph = empty_glyph();
        for (hash, gid, ppem) in [
            (0_u64, 0_u16, 0_u16),
            (u64::MAX, u16::MAX, u16::MAX),
            (u64::MAX, 0, 1),
            (0, u16::MAX, u16::MAX),
        ] {
            let got = cache
                .get_or_build(hash, gid, &glyph, &font, ppem)
                .map(|c| c.is_hinted);
            assert_eq!(got, None, "outline-less glyph at ppem {ppem}");
        }
        assert_eq!(
            cache.paths_len(),
            4,
            "each (hash, gid, ppem) is its own key"
        );
    }
    #[test]
    fn get_or_build_is_idempotent_and_ppem_is_part_of_the_key() {
        let Some(font) = test_font() else {
            return;
        };
        let Some((gid, glyph)) = glyph_a(&font) else {
            return;
        };
        let mut cache = GlyphCache::new();
        // ppem == 0 => unhinted path, in font units.
        let first = cache
            .get_or_build(font.hash, gid, &glyph, &font, 0)
            .map(|c| (c.is_hinted, c.path.total_vertices()));
        let Some((is_hinted, verts)) = first else {
            return; // 'A' has no outline in this font: nothing to assert
        };
        assert!(!is_hinted, "ppem == 0 must not produce a hinted path");
        assert!(verts > 0, "an outlined glyph must emit vertices");
        assert_eq!(cache.paths_len(), 1);
        // Second lookup is a cache hit: same result, no new entry.
        let second = cache
            .get_or_build(font.hash, gid, &glyph, &font, 0)
            .map(|c| (c.is_hinted, c.path.total_vertices()));
        assert_eq!(second, Some((is_hinted, verts)));
        assert_eq!(cache.paths_len(), 1, "a hit must not insert a second entry");
        // A different ppem is a different key.
        let _ = cache.get_or_build(font.hash, gid, &glyph, &font, 16);
        assert_eq!(cache.paths_len(), 2);
    }
    #[test]
    fn get_or_build_rotates_generations_at_the_entry_limit() {
        let Some(font) = test_font() else {
            return;
        };
        let mut cache = GlyphCache::new();
        let glyph = empty_glyph(); // no outline => cheap negative entries
        for i in 0..MAX_PATH_ENTRIES as u64 {
            let _ = cache.get_or_build(i, 0, &glyph, &font, 0);
        }
        assert_eq!(cache.paths_len(), MAX_PATH_ENTRIES);
        // One past the limit rotates: the full young map becomes `prev` and
        // a fresh one starts. Bounded, but NOT emptied.
        let _ = cache.get_or_build(u64::MAX, 0, &glyph, &font, 0);
        assert_eq!(
            cache.paths_len(),
            MAX_PATH_ENTRIES + 1,
            "rotation must DEMOTE the old generation, not delete it — clearing wholesale re-hints \
             the entire visible page on whichever keystroke happens to cross the limit"
        );
        // The point of keeping it: an entry that was live before the
        // rotation is served from `prev` and promoted, not rebuilt.
        let _ = cache.get_or_build(0, 0, &glyph, &font, 0);
        assert!(
            cache.paths_len() <= 2 * MAX_PATH_ENTRIES,
            "two generations is the whole budget; a third would be unbounded"
        );
        // Filling a second generation must evict the FIRST, never both.
        for i in 0..MAX_PATH_ENTRIES as u64 {
            let _ = cache.get_or_build(1_000_000 + i, 0, &glyph, &font, 0);
        }
        assert!(
            cache.paths_len() <= 2 * MAX_PATH_ENTRIES,
            "path cache must not grow unbounded, got {}",
            cache.paths_len()
        );
    }
    // ---------------------------------------------------------------------
    // glyph_lsb — numeric / bounds
    // ---------------------------------------------------------------------
    #[test]
    fn glyph_lsb_without_source_bytes_is_none() {
        let Some(font) = test_font() else {
            return;
        };
        let mut stripped = font;
        stripped.original_bytes = None;
        assert_eq!(
            glyph_lsb(&stripped, 0),
            None,
            "no retained font bytes => no hmtx to read"
        );
    }
    #[test]
    fn glyph_lsb_zero_h_metrics_is_none() {
        let Some(mut font) = test_font() else {
            return;
        };
        font.hhea_table.num_h_metrics = 0;
        assert_eq!(
            glyph_lsb(&font, 0),
            None,
            "num_h_metrics == 0 must bail out"
        );
    }
    #[test]
    fn glyph_lsb_reads_gid_zero_and_rejects_out_of_range_gids() {
        let Some(font) = test_font() else {
            return;
        };
        let (_, len) = font.hmtx_range;
        let num = usize::from(font.hhea_table.num_h_metrics);
        if len > 0 && num > 0 && font.original_bytes.is_some() {
            assert!(
                glyph_lsb(&font, 0).is_some(),
                "gid 0 sits inside hmtx and must read back"
            );
        }
        // A gid whose lsb offset lands past the table must be bounds-rejected,
        // not indexed. (Mirrors the impl's offset arithmetic to know it is out
        // of range for THIS font rather than assuming a glyph count.)
        let gid = usize::from(u16::MAX);
        let lsb_off = if gid < num {
            gid * 4 + 2
        } else {
            num * 4 + (gid - num) * 2
        };
        if lsb_off + 2 > len {
            assert_eq!(
                glyph_lsb(&font, u16::MAX),
                None,
                "an out-of-table gid must return None, not panic"
            );
        }
        // Sweep the boundary around num_h_metrics (long metrics -> trailing
        // lsb-only array) — none of these may panic.
        for gid in [0_u16, 1, u16::MAX] {
            let _ = glyph_lsb(&font, gid);
        }
    }
    // ---------------------------------------------------------------------
    // build_hinted_path — guard clauses (the interpreter path itself is only
    // smoke-tested at a realistic ppem)
    // ---------------------------------------------------------------------
    #[test]
    fn build_hinted_path_without_raw_hinting_data_is_none() {
        let Some(font) = test_font() else {
            return;
        };
        let glyph = empty_glyph(); // raw_points / instructions all None
        assert!(build_hinted_path(0, &glyph, &font, 16).is_none());
        assert!(
            build_hinted_path(u16::MAX, &glyph, &font, u16::MAX).is_none(),
            "missing raw data must short-circuit before any hinting arithmetic"
        );
    }
    #[test]
    fn build_hinted_path_with_empty_contours_is_none() {
        let Some(font) = test_font() else {
            return;
        };
        let mut glyph = empty_glyph();
        glyph.raw_points = Some(Vec::new());
        glyph.raw_on_curve = Some(Vec::new());
        glyph.raw_contour_ends = Some(Vec::new());
        glyph.instructions = Some(Vec::new());
        assert!(
            build_hinted_path(0, &glyph, &font, 16).is_none(),
            "an empty point/contour list must bail out, not hint an empty glyph"
        );
    }
    #[test]
    fn build_hinted_path_without_a_hint_instance_is_none() {
        let Some(mut font) = test_font() else {
            return;
        };
        let Some((gid, glyph)) = glyph_a(&font) else {
            return;
        };
        if glyph.raw_points.is_none() || glyph.instructions.is_none() {
            return; // CFF / composite glyph: nothing to hint, test not applicable
        }
        font.hint_instance = None;
        assert!(
            build_hinted_path(gid, &glyph, &font, 16).is_none(),
            "no interpreter => no hinted path"
        );
    }
    #[test]
    fn build_hinted_path_with_zero_upem_is_none() {
        let Some(mut font) = test_font() else {
            return;
        };
        let Some((gid, glyph)) = glyph_a(&font) else {
            return;
        };
        if font.hint_instance.is_none() || glyph.raw_points.is_none() {
            return; // the upem guard sits behind the hint-instance guard
        }
        font.font_metrics.units_per_em = 0;
        assert!(
            build_hinted_path(gid, &glyph, &font, 16).is_none(),
            "upem == 0 must bail out before the divide-by-upem scale"
        );
    }
    #[test]
    fn build_hinted_path_at_a_realistic_ppem_produces_a_finite_path() {
        let Some(font) = test_font() else {
            return;
        };
        let Some((gid, glyph)) = glyph_a(&font) else {
            return;
        };
        let Some(path) = build_hinted_path(gid, &glyph, &font, 16) else {
            return; // unhinted font (CFF / no instructions): nothing to assert
        };
        assert!(path.total_vertices() > 0, "hinted path must have vertices");
        for v in path.vertices() {
            assert!(
                v.x.is_finite() && v.y.is_finite(),
                "hinting produced a non-finite vertex: ({}, {})",
                v.x,
                v.y
            );
        }
    }
}
// ============================================================================
// Pre-blended LCD glyph tiles (uniform-background fast path)
// ============================================================================
/// A pre-blended LCD glyph: the FINAL RGBA pixels of one glyph composited
/// against a known solid opaque background through the exact colorimetric
/// pipeline (`PixfmtRgba32LcdLinear` + the FIR LUT). Where the display-list
/// generator PROVED the run sits on that background (`Text.uniform_bg`),
/// painting the glyph is an opaque row copy — the per-pixel linear blend
/// (~6 ms of every big.md repaint) runs once per (glyph, color, bg) ever.
#[derive(Debug, Clone)]
pub struct LcdGlyphTile {
    pub w: u32,
    pub h: u32,
    /// Offset from the glyph's (`int_x`, `int_y`) anchor to the tile's top-left.
    pub dx: i32,
    pub dy: i32,
    pub rgba: Vec<u8>,
}
#[derive(Clone, PartialEq, Eq, Hash)]
struct LcdTileKey {
    font_hash: u64,
    glyph_id: u16,
    ppem: u16,
    scale_fixed: u32,
    subpx_x: u8,
    color: (u8, u8, u8, u8),
    bg: (u8, u8, u8),
}
/// Entries per generation; a body-text document uses a few hundred
/// distinct (glyph, subpixel, color, bg) combinations at ~1 KB each.
const MAX_TILE_ENTRIES: usize = 4096;
impl GlyphCache {
    /// Pre-blended tile for one glyph on a uniform opaque background.
    /// `None` = the glyph produced no cells (whitespace) — nothing to paint.
    #[allow(clippy::too_many_arguments)]
342300
    pub fn get_or_build_lcd_tile(
342300
        &mut self,
342300
        font_hash: u64,
342300
        glyph_id: u16,
342300
        ppem: u16,
342300
        glyph_x: f32,
342300
        glyph_y: f32,
342300
        scale: f32,
342300
        is_hinted: bool,
342300
        hint_correction: f32,
342300
        color: azul_css::props::basic::color::ColorU,
342300
        bg: azul_css::props::basic::color::ColorU,
342300
        lut: &agg_rust::pixfmt_lcd::LcdDistributionLut,
342300
        params: agg_rust::pixfmt_lcd::LcdBlendParams,
342300
    ) -> Option<(LcdGlyphTile, i32, i32)> {
342300
        let rescale_hinted = is_hinted && (hint_correction - 1.0).abs() > 1e-4;
342300
        let subpx = text_subpixel_enabled();
342300
        let (int_x, subpx_x) = if subpx {
342300
            (glyph_x.floor() as i32, quantize_subpx_lcd(glyph_x))
        } else {
            (glyph_x.round() as i32, 0)
        };
342300
        let int_y = glyph_y.round() as i32;
342300
        let scale_fixed = if is_hinted {
335166
            if rescale_hinted {
                (hint_correction * 65536.0) as u32
            } else {
335166
                0
            }
        } else {
7134
            (scale * 65536.0) as u32
        };
342300
        let key = LcdTileKey {
342300
            font_hash,
342300
            glyph_id,
342300
            ppem,
342300
            scale_fixed,
342300
            subpx_x,
342300
            color: (color.r, color.g, color.b, color.a),
342300
            bg: (bg.r, bg.g, bg.b),
342300
        };
342300
        if let Some(hit) = self.lcd_tiles.get(&key) {
326670
            return hit.clone().map(|t| (t, int_x, int_y));
15630
        }
15630
        if self.lcd_tiles.len() >= MAX_TILE_ENTRIES {
            self.lcd_tiles.clear(); // simple full-drop; rebuild is cheap
15630
        }
        // Cells for THIS glyph (cached themselves), cloned so we can borrow
        // self mutably for the insert below.
15630
        let cells: Vec<CellAa> = self
15630
            .get_or_build_cells_lcd(
15630
                font_hash,
15630
                glyph_id,
15630
                ppem,
15630
                glyph_x,
15630
                glyph_y,
15630
                scale,
15630
                is_hinted,
15630
                hint_correction,
            )
15630
            .map(|(c, _, _)| c.to_vec())?;
9157
        if cells.is_empty() {
            self.lcd_tiles.insert(key, None);
            return None;
9157
        }
        // Cell bbox: x in STRIPE coords (3 per pixel), y in pixels.
9157
        let (mut min_sx, mut max_sx, mut min_y, mut max_y) =
9157
            (i32::MAX, i32::MIN, i32::MAX, i32::MIN);
730710
        for c in &cells {
721553
            min_sx = min_sx.min(c.x);
721553
            max_sx = max_sx.max(c.x);
721553
            min_y = min_y.min(c.y);
721553
            max_y = max_y.max(c.y);
721553
        }
        // Snap the stripe range outward to whole pixels, then pad 1 px on
        // each horizontal side: the 5-tap FIR distributes a stripe's energy
        // up to 2 STRIPES sideways, so a tile cut at the cell bbox would
        // lose the sub-pixel fringe the slow path paints into the dst.
9157
        let min_px = min_sx.div_euclid(3) - 1;
9157
        let max_px = max_sx.div_euclid(3) + 1;
9157
        let w = (max_px - min_px + 1).max(1) as u32;
9157
        let h = (max_y - min_y + 1).max(1) as u32;
9157
        if w > 512 || h > 512 {
            // Degenerate/huge glyph: no tile (caller falls back).
            self.lcd_tiles.insert(key, None);
            return None;
9157
        }
        // bg-filled tile, then the exact same sweep the slow path runs.
9157
        let mut rgba = vec![0u8; (w * h * 4) as usize];
1620674
        for px in rgba.chunks_exact_mut(4) {
1620674
            px[0] = bg.r;
1620674
            px[1] = bg.g;
1620674
            px[2] = bg.b;
1620674
            px[3] = 255;
1620674
        }
        {
            use agg_rust::{
                basics::FillingRule, pixfmt_lcd::PixfmtRgba32LcdLinear,
                rasterizer_scanline_aa::RasterizerScanlineAa, renderer_base::RendererBase,
                renderer_scanline::render_scanlines_aa_solid, rendering_buffer::RowAccessor,
                scanline_u::ScanlineU8,
            };
9157
            let mut ras = RasterizerScanlineAa::new();
9157
            ras.filling_rule(FillingRule::NonZero);
9157
            ras.add_cells_offset(&cells, -min_px * 3, -min_y);
9157
            let stride = (w * 4) as i32;
9157
            let mut ra = unsafe { RowAccessor::new_with_buf(rgba.as_mut_ptr(), w, h, stride) };
9157
            let mut pf = PixfmtRgba32LcdLinear::new(&mut ra, lut, params);
9157
            pf.set_subpixel_order(self.lcd_subpixel_order);
9157
            let mut rb = RendererBase::new(pf);
9157
            let mut sl = ScanlineU8::new();
9157
            let agg_color = agg_rust::color::Rgba8::new(
9157
                u32::from(color.r),
9157
                u32::from(color.g),
9157
                u32::from(color.b),
9157
                u32::from(color.a),
            );
9157
            render_scanlines_aa_solid(&mut ras, &mut sl, &mut rb, &agg_color);
        }
9157
        let tile = LcdGlyphTile {
9157
            w,
9157
            h,
9157
            dx: min_px,
9157
            dy: min_y,
9157
            rgba,
9157
        };
9157
        self.lcd_tiles.insert(key, Some(tile.clone()));
9157
        Some((tile, int_x, int_y))
342300
    }
}