Skip to main content

euv_core/font/system/
impl.rs

1use super::*;
2
3/// Default `NativeSystemFont` uses deterministic cross-platform rasterization.
4impl Default for NativeSystemFont {
5    /// Creates a deterministic `NativeSystemFont`.
6    ///
7    /// # Returns
8    ///
9    /// - `Self` - Deterministic font provider.
10    fn default() -> Self {
11        Self::deterministic()
12    }
13}
14
15/// Construction and lazy-binding telemetry helpers for `NativeSystemFont`.
16impl NativeSystemFont {
17    /// Creates a `NativeSystemFont` descriptor with zero synchronous OS font probes, binding native faces lazily on first glyph miss.
18    ///
19    /// # Returns
20    ///
21    /// - `Self` - Native OS font provider with automatic deterministic fallback.
22    #[must_use]
23    pub fn system() -> Self {
24        Self {
25            info: probe_system_font(),
26            deterministic_only: false,
27        }
28    }
29
30    /// Creates a deterministic cross-platform font provider guaranteeing identical pixels on every OS.
31    ///
32    /// # Returns
33    ///
34    /// - `Self` - Deterministic bitmap/stroke font provider.
35    #[must_use]
36    pub fn deterministic() -> Self {
37        Self {
38            info: SystemFontInfo::new(
39                FontRenderBackend::DeterministicBitmap,
40                FONT_FAMILY_DETERMINISTIC.to_string(),
41                true,
42                false,
43            ),
44            deterministic_only: true,
45        }
46    }
47
48    /// Returns the number of lazy primary OS font face binds performed on the current thread.
49    ///
50    /// # Returns
51    ///
52    /// - `usize` - Cumulative lazy primary font bind count on this thread (`0` right after `NativeSystemFont::system()`).
53    #[must_use]
54    pub fn thread_primary_font_binds() -> usize {
55        THREAD_PRIMARY_FONT_BINDS.with(Cell::get)
56    }
57
58    /// Returns the number of lazy native fallback font loads (such as CJK or symbol cascades) performed on the current thread.
59    ///
60    /// # Returns
61    ///
62    /// - `usize` - Cumulative lazy fallback font load count on this thread.
63    #[must_use]
64    pub fn thread_fallback_font_loads() -> usize {
65        THREAD_FALLBACK_FONT_LOADS.with(Cell::get)
66    }
67}
68
69/// `SystemFontProvider` implementation delegating to OS native APIs with batched and zero-alloc staging paths.
70impl SystemFontProvider for NativeSystemFont {
71    /// Returns the active `SystemFontInfo`.
72    ///
73    /// # Arguments
74    ///
75    /// - `&Self` - Font provider reference.
76    ///
77    /// # Returns
78    ///
79    /// - `SystemFontInfo` - Provider capability descriptor.
80    fn font_info(&self) -> SystemFontInfo {
81        self.get_info().clone()
82    }
83
84    /// Rasterizes `key` via the native OS font engine, routing gigantic sizes (`> 512px`) through exact Euclidean SDF reconstruction and falling back to deterministic rasterization.
85    ///
86    /// # Arguments
87    ///
88    /// - `&Self` - Font provider reference.
89    /// - `GlyphKey` - Quantized glyph descriptor.
90    ///
91    /// # Returns
92    ///
93    /// - `Option<RasterizedGlyph>` - Rasterized alpha8 coverage bitmap.
94    fn rasterize(&self, key: GlyphKey) -> Option<RasterizedGlyph> {
95        if key.uses_analytic_sdf_fallback() {
96            let canonical_key: GlyphKey = key.with_physical_size(GLYPH_SDF_CANONICAL_PX);
97            let canonical_glyph: RasterizedGlyph = if !self.get_deterministic_only()
98                && let Some(native_canonical) = rasterize_native_glyph(canonical_key)
99            {
100                native_canonical
101            } else {
102                rasterize_glyph(canonical_key)
103            };
104            let sdf_field: SdfGlyphField = build_glyph_sdf_field(
105                &canonical_glyph,
106                GLYPH_SDF_CANONICAL_PX,
107                GLYPH_SDF_DEFAULT_SPREAD_PX,
108            );
109            return Some(evaluate_glyph_sdf(&sdf_field, key.physical_size_px()));
110        }
111        if !self.get_deterministic_only()
112            && let Some(native_glyph) = rasterize_native_glyph(key)
113        {
114            return Some(native_glyph);
115        }
116        Some(rasterize_glyph(key))
117    }
118
119    /// Batch-rasterizes `keys` in a single OS/Web pass (`<= 1` readback on Web software fallback) with analytic SDF reconstruction for gigantic sizes and deterministic fallback.
120    ///
121    /// # Arguments
122    ///
123    /// - `&Self` - Font provider reference.
124    /// - `&[GlyphKey]` - Slice of missing glyph keys to rasterize.
125    ///
126    /// # Returns
127    ///
128    /// - `Vec<Option<RasterizedGlyph>>` - Rasterized glyph results aligned 1:1 with `keys`.
129    fn rasterize_batch(&self, keys: &[GlyphKey]) -> Vec<Option<RasterizedGlyph>> {
130        if keys.is_empty() {
131            return Vec::new();
132        }
133        if self.get_deterministic_only() {
134            let mut results: Vec<Option<RasterizedGlyph>> = Vec::with_capacity(keys.len());
135            for &key in keys.iter() {
136                results.push(Some(rasterize_glyph(key)));
137            }
138            return results;
139        }
140        let has_oversized: bool = keys.iter().any(GlyphKey::uses_analytic_sdf_fallback);
141        if has_oversized {
142            let mut results: Vec<Option<RasterizedGlyph>> = Vec::with_capacity(keys.len());
143            for &key in keys.iter() {
144                results.push(self.rasterize(key));
145            }
146            return results;
147        }
148        let mut native_batch: Vec<Option<RasterizedGlyph>> = rasterize_native_glyph_batch(keys);
149        for (idx, &key) in keys.iter().enumerate() {
150            let needs_fallback: bool = native_batch.get(idx).is_none_or(Option::is_none);
151            if needs_fallback {
152                let fallback: RasterizedGlyph = rasterize_glyph(key);
153                if idx < native_batch.len() {
154                    native_batch[idx] = Some(fallback);
155                } else {
156                    native_batch.push(Some(fallback));
157                }
158            }
159        }
160        native_batch
161    }
162
163    /// Rasterizes `key` directly into caller-owned reusable `dst` alpha8 staging buffer without per-glyph `vec![0; ...]` allocation.
164    ///
165    /// # Arguments
166    ///
167    /// - `&Self` - Font provider reference.
168    /// - `GlyphKey` - Quantized glyph descriptor.
169    /// - `&mut Vec<u8>` - Reusable destination alpha8 staging buffer.
170    ///
171    /// # Returns
172    ///
173    /// - `Option<(u32, u32, u32)>` - Tuple `(width, height, advance)` when rasterization succeeded.
174    fn rasterize_into(&self, key: GlyphKey, dst: &mut Vec<u8>) -> Option<(u32, u32, u32)> {
175        if key.uses_analytic_sdf_fallback() {
176            let glyph: RasterizedGlyph = self.rasterize(key)?;
177            dst.clear();
178            dst.extend_from_slice(glyph.get_coverage().as_slice());
179            return Some((glyph.get_width(), glyph.get_height(), glyph.get_advance()));
180        }
181        if !self.get_deterministic_only()
182            && let Some(metrics) = rasterize_native_glyph_into(key, dst)
183        {
184            return Some(metrics);
185        }
186        let glyph: RasterizedGlyph = rasterize_glyph(key);
187        dst.clear();
188        dst.extend_from_slice(glyph.get_coverage().as_slice());
189        Some((glyph.get_width(), glyph.get_height(), glyph.get_advance()))
190    }
191}
192
193/// Bounded pre-cached CSS font string operations eliminating per-glyph `format!` allocations.
194impl WebCssFontCache {
195    /// Creates an empty zero-allocation CSS font string cache.
196    ///
197    /// # Returns
198    ///
199    /// - `Self` - Empty CSS font cache.
200    #[must_use]
201    pub const fn new() -> Self {
202        Self {
203            entries: Vec::new(),
204            evict_cursor: 0,
205            hits: 0,
206            misses: 0,
207        }
208    }
209
210    /// Resolves the packed style signature and cached CSS `font` string for `key`, formatting only on first sight.
211    ///
212    /// # Arguments
213    ///
214    /// - `&Self` - Mutable CSS font string cache.
215    /// - `GlyphKey` - Quantized glyph style descriptor.
216    ///
217    /// # Returns
218    ///
219    /// - `(u32, &str)` - Packed style signature and cached CSS font string slice.
220    pub fn resolve(&mut self, key: GlyphKey) -> (u32, &str) {
221        let style_sig: u32 = GlyphAtlas::pack_style_sig(
222            key.get_size_tenths(),
223            key.get_bold(),
224            key.get_monospace(),
225            key.get_italic(),
226        );
227        let Self {
228            entries,
229            evict_cursor,
230            hits,
231            misses,
232        } = self;
233        let mut found_idx: Option<usize> = None;
234        for (idx, (sig, _)) in entries.iter().enumerate() {
235            if *sig == style_sig {
236                found_idx = Some(idx);
237                break;
238            }
239        }
240        if let Some(idx) = found_idx {
241            *hits = hits.saturating_add(1);
242            return (style_sig, entries[idx].1.as_str());
243        }
244        *misses = misses.saturating_add(1);
245        let formatted: String = format_web_css_font(key);
246        if entries.len() < WEB_FONT_CSS_CACHE_MAX {
247            let idx: usize = entries.len();
248            entries.push((style_sig, formatted));
249            return (style_sig, entries[idx].1.as_str());
250        }
251        let slot: usize = *evict_cursor % WEB_FONT_CSS_CACHE_MAX;
252        *evict_cursor = slot.wrapping_add(1) % WEB_FONT_CSS_CACHE_MAX;
253        entries[slot] = (style_sig, formatted);
254        (style_sig, entries[slot].1.as_str())
255    }
256
257    /// Returns the number of cached CSS font strings currently resident.
258    ///
259    /// # Arguments
260    ///
261    /// - `&Self` - CSS font cache reference.
262    ///
263    /// # Returns
264    ///
265    /// - `usize` - Number of cached style signatures.
266    #[must_use]
267    pub fn len(&self) -> usize {
268        let Self { entries, .. } = self;
269        entries.len()
270    }
271
272    /// Returns `true` when no CSS font strings are cached yet.
273    ///
274    /// # Arguments
275    ///
276    /// - `&Self` - CSS font cache reference.
277    ///
278    /// # Returns
279    ///
280    /// - `bool` - True when empty.
281    #[must_use]
282    pub fn is_empty(&self) -> bool {
283        let Self { entries, .. } = self;
284        entries.is_empty()
285    }
286
287    /// Clears all cached CSS font strings while preserving hit/miss counters.
288    ///
289    /// # Arguments
290    ///
291    /// - `&Self` - Mutable CSS font cache.
292    pub fn clear(&mut self) {
293        let Self {
294            entries,
295            evict_cursor,
296            ..
297        } = self;
298        entries.clear();
299        *evict_cursor = 0;
300    }
301}
302
303/// Construction helpers for fixed-slot CoreText cache entries.
304#[cfg(any(target_os = "macos", target_os = "ios", target_os = "watchos"))]
305/// Inherent implementation of [`CoreTextFontCacheEntry`].
306impl CoreTextFontCacheEntry {
307    /// Creates an empty unpopulated CoreText cache slot.
308    ///
309    /// # Returns
310    ///
311    /// - `Self` - Empty CoreText cache slot.
312    #[must_use]
313    pub(crate) const fn empty() -> Self {
314        Self {
315            style_sig: 0,
316            referenced: false,
317            font: null_mut(),
318            ascent: 0.0,
319            descent: 0.0,
320            fallback_fonts: [null_mut(); CORETEXT_FALLBACK_SLOTS],
321        }
322    }
323}
324
325/// Construction helpers for the thread-local Apple CoreText handle cache.
326#[cfg(any(target_os = "macos", target_os = "ios", target_os = "watchos"))]
327/// Inherent implementation of [`CoreTextFontCache`].
328impl CoreTextFontCache {
329    /// Creates an empty, zero-allocation fixed-slot Clock-LRU CoreText font handle cache.
330    ///
331    /// # Returns
332    ///
333    /// - `Self` - Empty thread-local CoreText handle cache.
334    #[must_use]
335    pub(crate) const fn new() -> Self {
336        Self {
337            gray_space: null_mut(),
338            scratch_ctx: null_mut(),
339            scratch_buf: Vec::new(),
340            scratch_w: 0,
341            scratch_h: 0,
342            count: 0,
343            clock_hand: 0,
344            index: [CORETEXT_INDEX_EMPTY; CORETEXT_FONT_INDEX_CAP],
345            slots: [CoreTextFontCacheEntry::empty(); CORETEXT_FONT_CACHE_SLOTS],
346        }
347    }
348}
349
350/// Automatic CoreFoundation and CoreGraphics handle release on thread exit.
351#[cfg(any(target_os = "macos", target_os = "ios", target_os = "watchos"))]
352/// Implements [`Drop`] for [`CoreTextFontCache`].
353impl Drop for CoreTextFontCache {
354    /// Releases the scratch `CGBitmapContextRef`, every cached `CTFontRef`, and the singleton `CGColorSpaceRef`.
355    ///
356    /// # Arguments
357    ///
358    /// - `&Self` - Dropping CoreText cache.
359    fn drop(&mut self) {
360        let Self {
361            gray_space,
362            scratch_ctx,
363            count,
364            slots,
365            ..
366        } = self;
367        release_coretext_cache(*gray_space, *scratch_ctx, &mut slots[..*count]);
368        *scratch_ctx = null_mut();
369        *gray_space = null_mut();
370        *count = 0;
371    }
372}
373
374/// Construction helpers for lazily resolved FreeType face slots.
375#[cfg(any(target_os = "linux", target_os = "android"))]
376/// Inherent implementation of [`FtLazyFace`].
377impl FtLazyFace {
378    /// Creates an unprobed lazy face slot incurring zero filesystem or FreeType overhead until first demand.
379    ///
380    /// # Returns
381    ///
382    /// - `Self` - Empty unprobed FreeType face slot.
383    #[must_use]
384    pub(crate) const fn unprobed() -> Self {
385        Self {
386            probed: false,
387            face: null_mut(),
388            last_size_tenths: 0,
389        }
390    }
391}
392
393/// Construction helpers for Android NDK `AFontMatcher` fallback face slots.
394#[cfg(target_os = "android")]
395/// Inherent implementation of [`FtAndroidFallbackFace`].
396impl FtAndroidFallbackFace {
397    /// Creates an empty Android fallback face cache slot.
398    ///
399    /// # Returns
400    ///
401    /// - `Self` - Empty Android fallback slot.
402    #[must_use]
403    pub(crate) const fn empty() -> Self {
404        Self {
405            path_hash: 0,
406            collection_index: 0,
407            referenced: false,
408            slot: FtLazyFace::unprobed(),
409        }
410    }
411}
412
413/// Automatic FreeType face, library, and Android `AFontMatcher` release on thread exit.
414#[cfg(any(target_os = "linux", target_os = "android"))]
415/// Implements [`Drop`] for [`FreeTypeRuntime`].
416impl Drop for FreeTypeRuntime {
417    /// Releases all lazily opened `FT_Face` handles, `FT_Library`, and Android `AFontMatcher`.
418    ///
419    /// # Arguments
420    ///
421    /// - `&Self` - Dropping per-thread FreeType runtime.
422    fn drop(&mut self) {
423        release_freetype_runtime(self);
424    }
425}
426
427/// Construction helpers for the thread-local Web offscreen glyph canvas scratchpad.
428#[cfg(target_arch = "wasm32")]
429/// Inherent implementation of [`WebFontScratch`].
430impl WebFontScratch {
431    /// Creates an empty, zero-DOM-allocation Web font scratchpad.
432    ///
433    /// # Returns
434    ///
435    /// - `Self` - Empty lazy Web font scratchpad.
436    #[must_use]
437    pub(crate) const fn new() -> Self {
438        Self {
439            readback_canvas: None,
440            readback_ctx2d: None,
441            readback_width: 0,
442            readback_height: 0,
443            readback_last_sig: u32::MAX,
444            gpu_canvas: None,
445            gpu_ctx2d: None,
446            gpu_width: 0,
447            gpu_height: 0,
448            gpu_last_sig: u32::MAX,
449            css_cache: WebCssFontCache::new(),
450            total_readbacks: 0,
451            total_gpu_strip_batches: 0,
452        }
453    }
454}
455
456/// Construction helpers for fixed-slot Win32 GDI cache entries.
457#[cfg(target_os = "windows")]
458/// Inherent implementation of [`Win32FontCacheEntry`].
459impl Win32FontCacheEntry {
460    /// Creates an empty unpopulated Win32 GDI font cache slot.
461    ///
462    /// # Returns
463    ///
464    /// - `Self` - Empty Win32 cache slot.
465    #[must_use]
466    pub(crate) const fn empty() -> Self {
467        Self {
468            style_sig: 0,
469            referenced: false,
470            hfont: null_mut(),
471            ascent: 0,
472            descent: 0,
473        }
474    }
475}
476
477/// Construction helpers for the thread-local Win32 GDI + lazy DirectWrite font handle cache.
478#[cfg(target_os = "windows")]
479/// Inherent implementation of [`Win32FontCache`].
480impl Win32FontCache {
481    /// Creates an empty, zero-allocation fixed-slot Clock-LRU Win32 font handle cache.
482    ///
483    /// # Returns
484    ///
485    /// - `Self` - Empty thread-local Win32 handle cache.
486    #[must_use]
487    pub(crate) const fn new() -> Self {
488        Self {
489            hdc: null_mut(),
490            dwrite_attempted: false,
491            dwrite_factory: null_mut(),
492            count: 0,
493            clock_hand: 0,
494            index: [WIN32_INDEX_EMPTY; WIN32_FONT_INDEX_CAP],
495            slots: [Win32FontCacheEntry::empty(); WIN32_FONT_CACHE_SLOTS],
496            raw_buf: Vec::new(),
497        }
498    }
499}
500
501/// Automatic Win32 GDI `HFONT`, memory `HDC`, and lazy COM `IDWriteFactory` release on thread exit.
502#[cfg(target_os = "windows")]
503/// Implements [`Drop`] for [`Win32FontCache`].
504impl Drop for Win32FontCache {
505    /// Deletes every cached `HFONT`, the persistent memory `HDC`, and any lazily initialized `IDWriteFactory`.
506    ///
507    /// # Arguments
508    ///
509    /// - `&Self` - Dropping Win32 GDI cache.
510    fn drop(&mut self) {
511        let Self {
512            hdc,
513            dwrite_factory,
514            count,
515            slots,
516            ..
517        } = self;
518        release_win32_cache(*hdc, *dwrite_factory, &mut slots[..*count]);
519        *hdc = null_mut();
520        *dwrite_factory = null_mut();
521        *count = 0;
522    }
523}