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, 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 !self.get_deterministic_only()
96 && let Some(native_glyph) = rasterize_native_glyph(key)
97 {
98 return Some(native_glyph);
99 }
100 Some(rasterize_glyph(key))
101 }
102
103 /// Batch-rasterizes `keys` in a single OS/Web pass (`<= 1` readback on Web software fallback) with deterministic fallback.
104 ///
105 /// # Arguments
106 ///
107 /// - `&Self` - Font provider reference.
108 /// - `&[GlyphKey]` - Slice of missing glyph keys to rasterize.
109 ///
110 /// # Returns
111 ///
112 /// - `Vec<Option<RasterizedGlyph>>` - Rasterized glyph results aligned 1:1 with `keys`.
113 fn rasterize_batch(&self, keys: &[GlyphKey]) -> Vec<Option<RasterizedGlyph>> {
114 if keys.is_empty() {
115 return Vec::new();
116 }
117 if self.get_deterministic_only() {
118 let mut results: Vec<Option<RasterizedGlyph>> = Vec::with_capacity(keys.len());
119 for &key in keys.iter() {
120 results.push(Some(rasterize_glyph(key)));
121 }
122 return results;
123 }
124 let mut native_batch: Vec<Option<RasterizedGlyph>> = rasterize_native_glyph_batch(keys);
125 for (idx, &key) in keys.iter().enumerate() {
126 let needs_fallback: bool = native_batch.get(idx).is_none_or(Option::is_none);
127 if needs_fallback {
128 let fallback: RasterizedGlyph = rasterize_glyph(key);
129 if idx < native_batch.len() {
130 native_batch[idx] = Some(fallback);
131 } else {
132 native_batch.push(Some(fallback));
133 }
134 }
135 }
136 native_batch
137 }
138
139 /// Rasterizes `key` directly into caller-owned reusable `dst` alpha8 staging buffer without per-glyph `vec![0; ...]` allocation.
140 ///
141 /// # Arguments
142 ///
143 /// - `&Self` - Font provider reference.
144 /// - `GlyphKey` - Quantized glyph descriptor.
145 /// - `&mut Vec<u8>` - Reusable destination alpha8 staging buffer.
146 ///
147 /// # Returns
148 ///
149 /// - `Option<(u32, u32, u32)>` - Tuple `(width, height, advance)` when rasterization succeeded.
150 fn rasterize_into(&self, key: GlyphKey, dst: &mut Vec<u8>) -> Option<(u32, u32, u32)> {
151 if !self.get_deterministic_only()
152 && let Some(metrics) = rasterize_native_glyph_into(key, dst)
153 {
154 return Some(metrics);
155 }
156 let glyph: RasterizedGlyph = rasterize_glyph(key);
157 dst.clear();
158 dst.extend_from_slice(glyph.get_coverage().as_slice());
159 Some((glyph.get_width(), glyph.get_height(), glyph.get_advance()))
160 }
161}
162
163/// Bounded pre-cached CSS font string operations eliminating per-glyph `format!` allocations.
164impl WebCssFontCache {
165 /// Creates an empty zero-allocation CSS font string cache.
166 ///
167 /// # Returns
168 ///
169 /// - `Self` - Empty CSS font cache.
170 #[must_use]
171 pub const fn new() -> Self {
172 Self {
173 entries: Vec::new(),
174 evict_cursor: 0,
175 hits: 0,
176 misses: 0,
177 }
178 }
179
180 /// Resolves the packed style signature and cached CSS `font` string for `key`, formatting only on first sight.
181 ///
182 /// # Arguments
183 ///
184 /// - `&Self` - Mutable CSS font string cache.
185 /// - `GlyphKey` - Quantized glyph style descriptor.
186 ///
187 /// # Returns
188 ///
189 /// - `(u32, &str)` - Packed style signature and cached CSS font string slice.
190 pub fn resolve(&mut self, key: GlyphKey) -> (u32, &str) {
191 let style_sig: u32 = GlyphAtlas::pack_style_sig(
192 key.get_size_tenths(),
193 key.get_bold(),
194 key.get_monospace(),
195 key.get_italic(),
196 );
197 let Self {
198 entries,
199 evict_cursor,
200 hits,
201 misses,
202 } = self;
203 let mut found_idx: Option<usize> = None;
204 for (idx, (sig, _)) in entries.iter().enumerate() {
205 if *sig == style_sig {
206 found_idx = Some(idx);
207 break;
208 }
209 }
210 if let Some(idx) = found_idx {
211 *hits = hits.saturating_add(1);
212 return (style_sig, entries[idx].1.as_str());
213 }
214 *misses = misses.saturating_add(1);
215 let formatted: String = format_web_css_font(key);
216 if entries.len() < WEB_FONT_CSS_CACHE_MAX {
217 let idx: usize = entries.len();
218 entries.push((style_sig, formatted));
219 return (style_sig, entries[idx].1.as_str());
220 }
221 let slot: usize = *evict_cursor % WEB_FONT_CSS_CACHE_MAX;
222 *evict_cursor = slot.wrapping_add(1) % WEB_FONT_CSS_CACHE_MAX;
223 entries[slot] = (style_sig, formatted);
224 (style_sig, entries[slot].1.as_str())
225 }
226
227 /// Returns the number of cached CSS font strings currently resident.
228 ///
229 /// # Arguments
230 ///
231 /// - `&Self` - CSS font cache reference.
232 ///
233 /// # Returns
234 ///
235 /// - `usize` - Number of cached style signatures.
236 #[must_use]
237 pub fn len(&self) -> usize {
238 let Self { entries, .. } = self;
239 entries.len()
240 }
241
242 /// Returns `true` when no CSS font strings are cached yet.
243 ///
244 /// # Arguments
245 ///
246 /// - `&Self` - CSS font cache reference.
247 ///
248 /// # Returns
249 ///
250 /// - `bool` - True when empty.
251 #[must_use]
252 pub fn is_empty(&self) -> bool {
253 let Self { entries, .. } = self;
254 entries.is_empty()
255 }
256
257 /// Clears all cached CSS font strings while preserving hit/miss counters.
258 ///
259 /// # Arguments
260 ///
261 /// - `&Self` - Mutable CSS font cache.
262 pub fn clear(&mut self) {
263 let Self {
264 entries,
265 evict_cursor,
266 ..
267 } = self;
268 entries.clear();
269 *evict_cursor = 0;
270 }
271}
272
273/// Construction helpers for fixed-slot CoreText cache entries.
274#[cfg(any(target_os = "macos", target_os = "ios", target_os = "watchos"))]
275/// Inherent implementation of [`CoreTextFontCacheEntry`].
276impl CoreTextFontCacheEntry {
277 /// Creates an empty unpopulated CoreText cache slot.
278 ///
279 /// # Returns
280 ///
281 /// - `Self` - Empty CoreText cache slot.
282 #[must_use]
283 pub(crate) const fn empty() -> Self {
284 Self {
285 style_sig: 0,
286 referenced: false,
287 font: null_mut(),
288 ascent: 0.0,
289 descent: 0.0,
290 fallback_fonts: [null_mut(); CORETEXT_FALLBACK_SLOTS],
291 }
292 }
293}
294
295/// Construction helpers for the thread-local Apple CoreText handle cache.
296#[cfg(any(target_os = "macos", target_os = "ios", target_os = "watchos"))]
297/// Inherent implementation of [`CoreTextFontCache`].
298impl CoreTextFontCache {
299 /// Creates an empty, zero-allocation fixed-slot Clock-LRU CoreText font handle cache.
300 ///
301 /// # Returns
302 ///
303 /// - `Self` - Empty thread-local CoreText handle cache.
304 #[must_use]
305 pub(crate) const fn new() -> Self {
306 Self {
307 gray_space: null_mut(),
308 scratch_ctx: null_mut(),
309 scratch_buf: Vec::new(),
310 scratch_w: 0,
311 scratch_h: 0,
312 count: 0,
313 clock_hand: 0,
314 index: [CORETEXT_INDEX_EMPTY; CORETEXT_FONT_INDEX_CAP],
315 slots: [CoreTextFontCacheEntry::empty(); CORETEXT_FONT_CACHE_SLOTS],
316 }
317 }
318}
319
320/// Automatic CoreFoundation and CoreGraphics handle release on thread exit.
321#[cfg(any(target_os = "macos", target_os = "ios", target_os = "watchos"))]
322/// Implements [`Drop`] for [`CoreTextFontCache`].
323impl Drop for CoreTextFontCache {
324 /// Releases the scratch `CGBitmapContextRef`, every cached `CTFontRef`, and the singleton `CGColorSpaceRef`.
325 ///
326 /// # Arguments
327 ///
328 /// - `&Self` - Dropping CoreText cache.
329 fn drop(&mut self) {
330 let Self {
331 gray_space,
332 scratch_ctx,
333 count,
334 slots,
335 ..
336 } = self;
337 release_coretext_cache(*gray_space, *scratch_ctx, &mut slots[..*count]);
338 *scratch_ctx = null_mut();
339 *gray_space = null_mut();
340 *count = 0;
341 }
342}
343
344/// Construction helpers for lazily resolved FreeType face slots.
345#[cfg(any(target_os = "linux", target_os = "android"))]
346/// Inherent implementation of [`FtLazyFace`].
347impl FtLazyFace {
348 /// Creates an unprobed lazy face slot incurring zero filesystem or FreeType overhead until first demand.
349 ///
350 /// # Returns
351 ///
352 /// - `Self` - Empty unprobed FreeType face slot.
353 #[must_use]
354 pub(crate) const fn unprobed() -> Self {
355 Self {
356 probed: false,
357 face: null_mut(),
358 last_size_px: 0,
359 }
360 }
361}
362
363/// Construction helpers for Android NDK `AFontMatcher` fallback face slots.
364#[cfg(target_os = "android")]
365/// Inherent implementation of [`FtAndroidFallbackFace`].
366impl FtAndroidFallbackFace {
367 /// Creates an empty Android fallback face cache slot.
368 ///
369 /// # Returns
370 ///
371 /// - `Self` - Empty Android fallback slot.
372 #[must_use]
373 pub(crate) const fn empty() -> Self {
374 Self {
375 path_hash: 0,
376 collection_index: 0,
377 referenced: false,
378 slot: FtLazyFace::unprobed(),
379 }
380 }
381}
382
383/// Automatic FreeType face, library, and Android `AFontMatcher` release on thread exit.
384#[cfg(any(target_os = "linux", target_os = "android"))]
385/// Implements [`Drop`] for [`FreeTypeRuntime`].
386impl Drop for FreeTypeRuntime {
387 /// Releases all lazily opened `FT_Face` handles, `FT_Library`, and Android `AFontMatcher`.
388 ///
389 /// # Arguments
390 ///
391 /// - `&Self` - Dropping per-thread FreeType runtime.
392 fn drop(&mut self) {
393 release_freetype_runtime(self);
394 }
395}
396
397/// Construction helpers for the thread-local Web offscreen glyph canvas scratchpad.
398#[cfg(target_arch = "wasm32")]
399/// Inherent implementation of [`WebFontScratch`].
400impl WebFontScratch {
401 /// Creates an empty, zero-DOM-allocation Web font scratchpad.
402 ///
403 /// # Returns
404 ///
405 /// - `Self` - Empty lazy Web font scratchpad.
406 #[must_use]
407 pub(crate) const fn new() -> Self {
408 Self {
409 readback_canvas: None,
410 readback_ctx2d: None,
411 readback_width: 0,
412 readback_height: 0,
413 readback_last_sig: u32::MAX,
414 gpu_canvas: None,
415 gpu_ctx2d: None,
416 gpu_width: 0,
417 gpu_height: 0,
418 gpu_last_sig: u32::MAX,
419 css_cache: WebCssFontCache::new(),
420 total_readbacks: 0,
421 total_gpu_strip_batches: 0,
422 }
423 }
424}
425
426/// Construction helpers for fixed-slot Win32 GDI cache entries.
427#[cfg(target_os = "windows")]
428/// Inherent implementation of [`Win32FontCacheEntry`].
429impl Win32FontCacheEntry {
430 /// Creates an empty unpopulated Win32 GDI font cache slot.
431 ///
432 /// # Returns
433 ///
434 /// - `Self` - Empty Win32 cache slot.
435 #[must_use]
436 pub(crate) const fn empty() -> Self {
437 Self {
438 style_sig: 0,
439 referenced: false,
440 hfont: null_mut(),
441 ascent: 0,
442 descent: 0,
443 }
444 }
445}
446
447/// Construction helpers for the thread-local Win32 GDI + lazy DirectWrite font handle cache.
448#[cfg(target_os = "windows")]
449/// Inherent implementation of [`Win32FontCache`].
450impl Win32FontCache {
451 /// Creates an empty, zero-allocation fixed-slot Clock-LRU Win32 font handle cache.
452 ///
453 /// # Returns
454 ///
455 /// - `Self` - Empty thread-local Win32 handle cache.
456 #[must_use]
457 pub(crate) const fn new() -> Self {
458 Self {
459 hdc: null_mut(),
460 dwrite_attempted: false,
461 dwrite_factory: null_mut(),
462 count: 0,
463 clock_hand: 0,
464 index: [WIN32_INDEX_EMPTY; WIN32_FONT_INDEX_CAP],
465 slots: [Win32FontCacheEntry::empty(); WIN32_FONT_CACHE_SLOTS],
466 raw_buf: Vec::new(),
467 }
468 }
469}
470
471/// Automatic Win32 GDI `HFONT`, memory `HDC`, and lazy COM `IDWriteFactory` release on thread exit.
472#[cfg(target_os = "windows")]
473/// Implements [`Drop`] for [`Win32FontCache`].
474impl Drop for Win32FontCache {
475 /// Deletes every cached `HFONT`, the persistent memory `HDC`, and any lazily initialized `IDWriteFactory`.
476 ///
477 /// # Arguments
478 ///
479 /// - `&Self` - Dropping Win32 GDI cache.
480 fn drop(&mut self) {
481 let Self {
482 hdc,
483 dwrite_factory,
484 count,
485 slots,
486 ..
487 } = self;
488 release_win32_cache(*hdc, *dwrite_factory, &mut slots[..*count]);
489 *hdc = null_mut();
490 *dwrite_factory = null_mut();
491 *count = 0;
492 }
493}