euv-core 0.48.0

Core cross-platform runtime for euv featuring arena-based fine-grained reactivity, deterministic layout, flat scene graph, multi-mode rendering, and direct OS platform adapters.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
use super::*;

/// Default `NativeSystemFont` uses deterministic cross-platform rasterization.
impl Default for NativeSystemFont {
    /// Creates a deterministic `NativeSystemFont`.
    ///
    /// # Returns
    ///
    /// - `Self` - Deterministic font provider.
    fn default() -> Self {
        Self::deterministic()
    }
}

/// Construction and lazy-binding telemetry helpers for `NativeSystemFont`.
impl NativeSystemFont {
    /// Creates a `NativeSystemFont` descriptor with zero synchronous OS font probes, binding native faces lazily on first glyph miss.
    ///
    /// # Returns
    ///
    /// - `Self` - Native OS font provider with automatic deterministic fallback.
    #[must_use]
    pub fn system() -> Self {
        Self {
            info: probe_system_font(),
            deterministic_only: false,
        }
    }

    /// Creates a deterministic cross-platform font provider guaranteeing identical pixels on every OS.
    ///
    /// # Returns
    ///
    /// - `Self` - Deterministic bitmap/stroke font provider.
    #[must_use]
    pub fn deterministic() -> Self {
        Self {
            info: SystemFontInfo::new(
                FontRenderBackend::DeterministicBitmap,
                FONT_FAMILY_DETERMINISTIC.to_string(),
                true,
                false,
            ),
            deterministic_only: true,
        }
    }

    /// Returns the number of lazy primary OS font face binds performed on the current thread.
    ///
    /// # Returns
    ///
    /// - `usize` - Cumulative lazy primary font bind count on this thread (`0` right after `NativeSystemFont::system()`).
    #[must_use]
    pub fn thread_primary_font_binds() -> usize {
        THREAD_PRIMARY_FONT_BINDS.with(Cell::get)
    }

    /// Returns the number of lazy native fallback font loads (such as CJK or symbol cascades) performed on the current thread.
    ///
    /// # Returns
    ///
    /// - `usize` - Cumulative lazy fallback font load count on this thread.
    #[must_use]
    pub fn thread_fallback_font_loads() -> usize {
        THREAD_FALLBACK_FONT_LOADS.with(Cell::get)
    }
}

/// `SystemFontProvider` implementation delegating to OS native APIs with batched and zero-alloc staging paths.
impl SystemFontProvider for NativeSystemFont {
    /// Returns the active `SystemFontInfo`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Font provider reference.
    ///
    /// # Returns
    ///
    /// - `SystemFontInfo` - Provider capability descriptor.
    fn font_info(&self) -> SystemFontInfo {
        self.get_info().clone()
    }

    /// Rasterizes `key` via the native OS font engine, falling back to deterministic rasterization.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Font provider reference.
    /// - `GlyphKey` - Quantized glyph descriptor.
    ///
    /// # Returns
    ///
    /// - `Option<RasterizedGlyph>` - Rasterized alpha8 coverage bitmap.
    fn rasterize(&self, key: GlyphKey) -> Option<RasterizedGlyph> {
        if !self.get_deterministic_only()
            && let Some(native_glyph) = rasterize_native_glyph(key)
        {
            return Some(native_glyph);
        }
        Some(rasterize_glyph(key))
    }

    /// Batch-rasterizes `keys` in a single OS/Web pass (`<= 1` readback on Web software fallback) with deterministic fallback.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Font provider reference.
    /// - `&[GlyphKey]` - Slice of missing glyph keys to rasterize.
    ///
    /// # Returns
    ///
    /// - `Vec<Option<RasterizedGlyph>>` - Rasterized glyph results aligned 1:1 with `keys`.
    fn rasterize_batch(&self, keys: &[GlyphKey]) -> Vec<Option<RasterizedGlyph>> {
        if keys.is_empty() {
            return Vec::new();
        }
        if self.get_deterministic_only() {
            let mut results: Vec<Option<RasterizedGlyph>> = Vec::with_capacity(keys.len());
            for &key in keys.iter() {
                results.push(Some(rasterize_glyph(key)));
            }
            return results;
        }
        let mut native_batch: Vec<Option<RasterizedGlyph>> = rasterize_native_glyph_batch(keys);
        for (idx, &key) in keys.iter().enumerate() {
            let needs_fallback: bool = native_batch.get(idx).is_none_or(Option::is_none);
            if needs_fallback {
                let fallback: RasterizedGlyph = rasterize_glyph(key);
                if idx < native_batch.len() {
                    native_batch[idx] = Some(fallback);
                } else {
                    native_batch.push(Some(fallback));
                }
            }
        }
        native_batch
    }

    /// Rasterizes `key` directly into caller-owned reusable `dst` alpha8 staging buffer without per-glyph `vec![0; ...]` allocation.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Font provider reference.
    /// - `GlyphKey` - Quantized glyph descriptor.
    /// - `&mut Vec<u8>` - Reusable destination alpha8 staging buffer.
    ///
    /// # Returns
    ///
    /// - `Option<(u32, u32, u32)>` - Tuple `(width, height, advance)` when rasterization succeeded.
    fn rasterize_into(&self, key: GlyphKey, dst: &mut Vec<u8>) -> Option<(u32, u32, u32)> {
        if !self.get_deterministic_only()
            && let Some(metrics) = rasterize_native_glyph_into(key, dst)
        {
            return Some(metrics);
        }
        let glyph: RasterizedGlyph = rasterize_glyph(key);
        dst.clear();
        dst.extend_from_slice(glyph.get_coverage().as_slice());
        Some((glyph.get_width(), glyph.get_height(), glyph.get_advance()))
    }
}

/// Bounded pre-cached CSS font string operations eliminating per-glyph `format!` allocations.
impl WebCssFontCache {
    /// Creates an empty zero-allocation CSS font string cache.
    ///
    /// # Returns
    ///
    /// - `Self` - Empty CSS font cache.
    #[must_use]
    pub const fn new() -> Self {
        Self {
            entries: Vec::new(),
            evict_cursor: 0,
            hits: 0,
            misses: 0,
        }
    }

    /// Resolves the packed style signature and cached CSS `font` string for `key`, formatting only on first sight.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable CSS font string cache.
    /// - `GlyphKey` - Quantized glyph style descriptor.
    ///
    /// # Returns
    ///
    /// - `(u32, &str)` - Packed style signature and cached CSS font string slice.
    pub fn resolve(&mut self, key: GlyphKey) -> (u32, &str) {
        let style_sig: u32 = GlyphAtlas::pack_style_sig(
            key.get_size_tenths(),
            key.get_bold(),
            key.get_monospace(),
            key.get_italic(),
        );
        let Self {
            entries,
            evict_cursor,
            hits,
            misses,
        } = self;
        let mut found_idx: Option<usize> = None;
        for (idx, (sig, _)) in entries.iter().enumerate() {
            if *sig == style_sig {
                found_idx = Some(idx);
                break;
            }
        }
        if let Some(idx) = found_idx {
            *hits = hits.saturating_add(1);
            return (style_sig, entries[idx].1.as_str());
        }
        *misses = misses.saturating_add(1);
        let formatted: String = format_web_css_font(key);
        if entries.len() < WEB_FONT_CSS_CACHE_MAX {
            let idx: usize = entries.len();
            entries.push((style_sig, formatted));
            return (style_sig, entries[idx].1.as_str());
        }
        let slot: usize = *evict_cursor % WEB_FONT_CSS_CACHE_MAX;
        *evict_cursor = slot.wrapping_add(1) % WEB_FONT_CSS_CACHE_MAX;
        entries[slot] = (style_sig, formatted);
        (style_sig, entries[slot].1.as_str())
    }

    /// Returns the number of cached CSS font strings currently resident.
    ///
    /// # Arguments
    ///
    /// - `&Self` - CSS font cache reference.
    ///
    /// # Returns
    ///
    /// - `usize` - Number of cached style signatures.
    #[must_use]
    pub fn len(&self) -> usize {
        let Self { entries, .. } = self;
        entries.len()
    }

    /// Returns `true` when no CSS font strings are cached yet.
    ///
    /// # Arguments
    ///
    /// - `&Self` - CSS font cache reference.
    ///
    /// # Returns
    ///
    /// - `bool` - True when empty.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        let Self { entries, .. } = self;
        entries.is_empty()
    }

    /// Clears all cached CSS font strings while preserving hit/miss counters.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable CSS font cache.
    pub fn clear(&mut self) {
        let Self {
            entries,
            evict_cursor,
            ..
        } = self;
        entries.clear();
        *evict_cursor = 0;
    }
}

/// Construction helpers for fixed-slot CoreText cache entries.
#[cfg(any(target_os = "macos", target_os = "ios"))]
impl CoreTextFontCacheEntry {
    /// Creates an empty unpopulated CoreText cache slot.
    ///
    /// # Returns
    ///
    /// - `Self` - Empty CoreText cache slot.
    #[must_use]
    pub(crate) const fn empty() -> Self {
        Self {
            style_sig: 0,
            referenced: false,
            font: null_mut(),
            ascent: 0.0,
            descent: 0.0,
            fallback_fonts: [null_mut(); CORETEXT_FALLBACK_SLOTS],
        }
    }
}

/// Construction helpers for the thread-local Apple CoreText handle cache.
#[cfg(any(target_os = "macos", target_os = "ios"))]
impl CoreTextFontCache {
    /// Creates an empty, zero-allocation fixed-slot Clock-LRU CoreText font handle cache.
    ///
    /// # Returns
    ///
    /// - `Self` - Empty thread-local CoreText handle cache.
    #[must_use]
    pub(crate) const fn new() -> Self {
        Self {
            gray_space: null_mut(),
            scratch_ctx: null_mut(),
            scratch_buf: Vec::new(),
            scratch_w: 0,
            scratch_h: 0,
            count: 0,
            clock_hand: 0,
            index: [CORETEXT_INDEX_EMPTY; CORETEXT_FONT_INDEX_CAP],
            slots: [CoreTextFontCacheEntry::empty(); CORETEXT_FONT_CACHE_SLOTS],
        }
    }
}

/// Automatic CoreFoundation and CoreGraphics handle release on thread exit.
#[cfg(any(target_os = "macos", target_os = "ios"))]
impl Drop for CoreTextFontCache {
    /// Releases the scratch `CGBitmapContextRef`, every cached `CTFontRef`, and the singleton `CGColorSpaceRef`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Dropping CoreText cache.
    fn drop(&mut self) {
        let Self {
            gray_space,
            scratch_ctx,
            count,
            slots,
            ..
        } = self;
        release_coretext_cache(*gray_space, *scratch_ctx, &mut slots[..*count]);
        *scratch_ctx = null_mut();
        *gray_space = null_mut();
        *count = 0;
    }
}

/// Construction helpers for lazily resolved FreeType face slots.
#[cfg(any(target_os = "linux", target_os = "android"))]
impl FtLazyFace {
    /// Creates an unprobed lazy face slot incurring zero filesystem or FreeType overhead until first demand.
    ///
    /// # Returns
    ///
    /// - `Self` - Empty unprobed FreeType face slot.
    #[must_use]
    pub(crate) const fn unprobed() -> Self {
        Self {
            probed: false,
            face: null_mut(),
            last_size_px: 0,
        }
    }
}

/// Construction helpers for Android NDK `AFontMatcher` fallback face slots.
#[cfg(target_os = "android")]
impl FtAndroidFallbackFace {
    /// Creates an empty Android fallback face cache slot.
    ///
    /// # Returns
    ///
    /// - `Self` - Empty Android fallback slot.
    #[must_use]
    pub(crate) const fn empty() -> Self {
        Self {
            path_hash: 0,
            collection_index: 0,
            referenced: false,
            slot: FtLazyFace::unprobed(),
        }
    }
}

/// Automatic FreeType face, library, and Android `AFontMatcher` release on thread exit.
#[cfg(any(target_os = "linux", target_os = "android"))]
impl Drop for FreeTypeRuntime {
    /// Releases all lazily opened `FT_Face` handles, `FT_Library`, and Android `AFontMatcher`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Dropping per-thread FreeType runtime.
    fn drop(&mut self) {
        release_freetype_runtime(self);
    }
}

/// Construction helpers for the thread-local Web offscreen glyph canvas scratchpad.
#[cfg(target_arch = "wasm32")]
impl WebFontScratch {
    /// Creates an empty, zero-DOM-allocation Web font scratchpad.
    ///
    /// # Returns
    ///
    /// - `Self` - Empty lazy Web font scratchpad.
    #[must_use]
    pub(crate) const fn new() -> Self {
        Self {
            readback_canvas: None,
            readback_ctx2d: None,
            readback_width: 0,
            readback_height: 0,
            readback_last_sig: u32::MAX,
            gpu_canvas: None,
            gpu_ctx2d: None,
            gpu_width: 0,
            gpu_height: 0,
            gpu_last_sig: u32::MAX,
            css_cache: WebCssFontCache::new(),
            total_readbacks: 0,
            total_gpu_strip_batches: 0,
        }
    }
}

/// Construction helpers for fixed-slot Win32 GDI cache entries.
#[cfg(target_os = "windows")]
impl Win32FontCacheEntry {
    /// Creates an empty unpopulated Win32 GDI font cache slot.
    ///
    /// # Returns
    ///
    /// - `Self` - Empty Win32 cache slot.
    #[must_use]
    pub(crate) const fn empty() -> Self {
        Self {
            style_sig: 0,
            referenced: false,
            hfont: null_mut(),
            ascent: 0,
            descent: 0,
        }
    }
}

/// Construction helpers for the thread-local Win32 GDI + lazy DirectWrite font handle cache.
#[cfg(target_os = "windows")]
impl Win32FontCache {
    /// Creates an empty, zero-allocation fixed-slot Clock-LRU Win32 font handle cache.
    ///
    /// # Returns
    ///
    /// - `Self` - Empty thread-local Win32 handle cache.
    #[must_use]
    pub(crate) const fn new() -> Self {
        Self {
            hdc: null_mut(),
            dwrite_attempted: false,
            dwrite_factory: null_mut(),
            count: 0,
            clock_hand: 0,
            index: [WIN32_INDEX_EMPTY; WIN32_FONT_INDEX_CAP],
            slots: [Win32FontCacheEntry::empty(); WIN32_FONT_CACHE_SLOTS],
            raw_buf: Vec::new(),
        }
    }
}

/// Automatic Win32 GDI `HFONT`, memory `HDC`, and lazy COM `IDWriteFactory` release on thread exit.
#[cfg(target_os = "windows")]
impl Drop for Win32FontCache {
    /// Deletes every cached `HFONT`, the persistent memory `HDC`, and any lazily initialized `IDWriteFactory`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Dropping Win32 GDI cache.
    fn drop(&mut self) {
        let Self {
            hdc,
            dwrite_factory,
            count,
            slots,
            ..
        } = self;
        release_win32_cache(*hdc, *dwrite_factory, &mut slots[..*count]);
        *hdc = null_mut();
        *dwrite_factory = null_mut();
        *count = 0;
    }
}