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"))]
275impl CoreTextFontCacheEntry {
276 /// Creates an empty unpopulated CoreText cache slot.
277 ///
278 /// # Returns
279 ///
280 /// - `Self` - Empty CoreText cache slot.
281 #[must_use]
282 pub(crate) const fn empty() -> Self {
283 Self {
284 style_sig: 0,
285 referenced: false,
286 font: null_mut(),
287 ascent: 0.0,
288 descent: 0.0,
289 fallback_fonts: [null_mut(); CORETEXT_FALLBACK_SLOTS],
290 }
291 }
292}
293
294/// Construction helpers for the thread-local Apple CoreText handle cache.
295#[cfg(any(target_os = "macos", target_os = "ios"))]
296impl CoreTextFontCache {
297 /// Creates an empty, zero-allocation fixed-slot Clock-LRU CoreText font handle cache.
298 ///
299 /// # Returns
300 ///
301 /// - `Self` - Empty thread-local CoreText handle cache.
302 #[must_use]
303 pub(crate) const fn new() -> Self {
304 Self {
305 gray_space: null_mut(),
306 scratch_ctx: null_mut(),
307 scratch_buf: Vec::new(),
308 scratch_w: 0,
309 scratch_h: 0,
310 count: 0,
311 clock_hand: 0,
312 index: [CORETEXT_INDEX_EMPTY; CORETEXT_FONT_INDEX_CAP],
313 slots: [CoreTextFontCacheEntry::empty(); CORETEXT_FONT_CACHE_SLOTS],
314 }
315 }
316}
317
318/// Automatic CoreFoundation and CoreGraphics handle release on thread exit.
319#[cfg(any(target_os = "macos", target_os = "ios"))]
320impl Drop for CoreTextFontCache {
321 /// Releases the scratch `CGBitmapContextRef`, every cached `CTFontRef`, and the singleton `CGColorSpaceRef`.
322 ///
323 /// # Arguments
324 ///
325 /// - `&Self` - Dropping CoreText cache.
326 fn drop(&mut self) {
327 let Self {
328 gray_space,
329 scratch_ctx,
330 count,
331 slots,
332 ..
333 } = self;
334 release_coretext_cache(*gray_space, *scratch_ctx, &mut slots[..*count]);
335 *scratch_ctx = null_mut();
336 *gray_space = null_mut();
337 *count = 0;
338 }
339}
340
341/// Construction helpers for lazily resolved FreeType face slots.
342#[cfg(any(target_os = "linux", target_os = "android"))]
343impl FtLazyFace {
344 /// Creates an unprobed lazy face slot incurring zero filesystem or FreeType overhead until first demand.
345 ///
346 /// # Returns
347 ///
348 /// - `Self` - Empty unprobed FreeType face slot.
349 #[must_use]
350 pub(crate) const fn unprobed() -> Self {
351 Self {
352 probed: false,
353 face: null_mut(),
354 last_size_px: 0,
355 }
356 }
357}
358
359/// Construction helpers for Android NDK `AFontMatcher` fallback face slots.
360#[cfg(target_os = "android")]
361impl FtAndroidFallbackFace {
362 /// Creates an empty Android fallback face cache slot.
363 ///
364 /// # Returns
365 ///
366 /// - `Self` - Empty Android fallback slot.
367 #[must_use]
368 pub(crate) const fn empty() -> Self {
369 Self {
370 path_hash: 0,
371 collection_index: 0,
372 referenced: false,
373 slot: FtLazyFace::unprobed(),
374 }
375 }
376}
377
378/// Automatic FreeType face, library, and Android `AFontMatcher` release on thread exit.
379#[cfg(any(target_os = "linux", target_os = "android"))]
380impl Drop for FreeTypeRuntime {
381 /// Releases all lazily opened `FT_Face` handles, `FT_Library`, and Android `AFontMatcher`.
382 ///
383 /// # Arguments
384 ///
385 /// - `&Self` - Dropping per-thread FreeType runtime.
386 fn drop(&mut self) {
387 release_freetype_runtime(self);
388 }
389}
390
391/// Construction helpers for the thread-local Web offscreen glyph canvas scratchpad.
392#[cfg(target_arch = "wasm32")]
393impl WebFontScratch {
394 /// Creates an empty, zero-DOM-allocation Web font scratchpad.
395 ///
396 /// # Returns
397 ///
398 /// - `Self` - Empty lazy Web font scratchpad.
399 #[must_use]
400 pub(crate) const fn new() -> Self {
401 Self {
402 readback_canvas: None,
403 readback_ctx2d: None,
404 readback_width: 0,
405 readback_height: 0,
406 readback_last_sig: u32::MAX,
407 gpu_canvas: None,
408 gpu_ctx2d: None,
409 gpu_width: 0,
410 gpu_height: 0,
411 gpu_last_sig: u32::MAX,
412 css_cache: WebCssFontCache::new(),
413 total_readbacks: 0,
414 total_gpu_strip_batches: 0,
415 }
416 }
417}
418
419/// Construction helpers for fixed-slot Win32 GDI cache entries.
420#[cfg(target_os = "windows")]
421impl Win32FontCacheEntry {
422 /// Creates an empty unpopulated Win32 GDI font cache slot.
423 ///
424 /// # Returns
425 ///
426 /// - `Self` - Empty Win32 cache slot.
427 #[must_use]
428 pub(crate) const fn empty() -> Self {
429 Self {
430 style_sig: 0,
431 referenced: false,
432 hfont: null_mut(),
433 ascent: 0,
434 descent: 0,
435 }
436 }
437}
438
439/// Construction helpers for the thread-local Win32 GDI + lazy DirectWrite font handle cache.
440#[cfg(target_os = "windows")]
441impl Win32FontCache {
442 /// Creates an empty, zero-allocation fixed-slot Clock-LRU Win32 font handle cache.
443 ///
444 /// # Returns
445 ///
446 /// - `Self` - Empty thread-local Win32 handle cache.
447 #[must_use]
448 pub(crate) const fn new() -> Self {
449 Self {
450 hdc: null_mut(),
451 dwrite_attempted: false,
452 dwrite_factory: null_mut(),
453 count: 0,
454 clock_hand: 0,
455 index: [WIN32_INDEX_EMPTY; WIN32_FONT_INDEX_CAP],
456 slots: [Win32FontCacheEntry::empty(); WIN32_FONT_CACHE_SLOTS],
457 raw_buf: Vec::new(),
458 }
459 }
460}
461
462/// Automatic Win32 GDI `HFONT`, memory `HDC`, and lazy COM `IDWriteFactory` release on thread exit.
463#[cfg(target_os = "windows")]
464impl Drop for Win32FontCache {
465 /// Deletes every cached `HFONT`, the persistent memory `HDC`, and any lazily initialized `IDWriteFactory`.
466 ///
467 /// # Arguments
468 ///
469 /// - `&Self` - Dropping Win32 GDI cache.
470 fn drop(&mut self) {
471 let Self {
472 hdc,
473 dwrite_factory,
474 count,
475 slots,
476 ..
477 } = self;
478 release_win32_cache(*hdc, *dwrite_factory, &mut slots[..*count]);
479 *hdc = null_mut();
480 *dwrite_factory = null_mut();
481 *count = 0;
482 }
483}