1use core::cell::RefCell;
9use std::boxed::Box;
10use std::collections::HashMap;
11use std::sync::{Arc, OnceLock, RwLock};
12use std::vec;
13use std::vec::Vec;
14
15use ttf_parser::{Face, GlyphId, OutlineBuilder};
16
17#[derive(Clone)]
19pub struct CachedGlyph {
20 pub width: usize,
21 pub height: usize,
22 pub xmin: i32,
23 pub ymin: i32,
24 #[allow(dead_code)]
25 pub advance_width: i16,
26 pub bitmap: Vec<u8>,
27 pub color_rgba: Option<Vec<u8>>,
29}
30
31#[cfg(not(target_arch = "wasm32"))]
32enum SystemFontBacking {
33 #[cfg(target_os = "windows")]
34 WinMapped {
35 ptr: *const u8,
36 len: usize,
37 mapping: *mut core::ffi::c_void,
38 _file: std::fs::File,
39 },
40 #[cfg(unix)]
41 UnixMapped {
42 ptr: *const u8,
43 len: usize,
44 },
45 Heap(Box<[u8]>),
46}
47
48#[cfg(not(target_arch = "wasm32"))]
49unsafe impl Send for SystemFontBacking {}
51#[cfg(not(target_arch = "wasm32"))]
52unsafe impl Sync for SystemFontBacking {}
53
54#[cfg(not(target_arch = "wasm32"))]
55impl SystemFontBacking {
56 #[inline]
57 fn as_slice(&self) -> &[u8] {
58 match self {
59 #[cfg(target_os = "windows")]
60 Self::WinMapped { ptr, len, .. } => unsafe { core::slice::from_raw_parts(*ptr, *len) },
61 #[cfg(unix)]
62 Self::UnixMapped { ptr, len } => unsafe { core::slice::from_raw_parts(*ptr, *len) },
63 Self::Heap(b) => b,
64 }
65 }
66
67 #[inline]
68 fn is_mapped(&self) -> bool {
69 !matches!(self, Self::Heap(_))
70 }
71
72 #[inline]
73 fn len(&self) -> usize {
74 self.as_slice().len()
75 }
76}
77
78#[cfg(not(target_arch = "wasm32"))]
79impl Drop for SystemFontBacking {
80 fn drop(&mut self) {
81 match self {
82 #[cfg(target_os = "windows")]
83 Self::WinMapped { ptr, mapping, .. } => unsafe {
84 if !ptr.is_null() {
85 let _ = win_mmap::UnmapViewOfFile(*ptr as *const core::ffi::c_void);
86 }
87 if !mapping.is_null() {
88 let _ = win_mmap::CloseHandle(*mapping);
89 }
90 },
91 #[cfg(unix)]
92 Self::UnixMapped { ptr, len } => unsafe {
93 if !ptr.is_null() && *len > 0 {
94 let _ = unix_mmap::munmap(*ptr as *mut core::ffi::c_void, *len);
95 }
96 },
97 Self::Heap(_) => {}
98 }
99 }
100}
101
102#[cfg(target_os = "windows")]
103mod win_mmap {
104 use core::ffi::c_void;
105 use std::os::windows::io::AsRawHandle;
106
107 pub(super) const PAGE_READONLY: u32 = 0x02;
108 pub(super) const FILE_MAP_READ: u32 = 0x0004;
109
110 unsafe extern "system" {
111 pub(super) fn CreateFileMappingW(
112 hfile: *mut c_void,
113 attrs: *const c_void,
114 protect: u32,
115 max_size_high: u32,
116 max_size_low: u32,
117 name: *const u16,
118 ) -> *mut c_void;
119 pub(super) fn MapViewOfFile(
120 mapping: *mut c_void,
121 desired_access: u32,
122 file_offset_high: u32,
123 file_offset_low: u32,
124 bytes_to_map: usize,
125 ) -> *mut c_void;
126 pub(super) fn UnmapViewOfFile(base_addr: *const c_void) -> i32;
127 pub(super) fn CloseHandle(handle: *mut c_void) -> i32;
128 }
129
130 pub(super) fn map_readonly(path: &str) -> Option<super::SystemFontBacking> {
131 let file = std::fs::File::open(path).ok()?;
132 let len = file.metadata().ok()?.len() as usize;
133 if len < 64 {
134 return None;
135 }
136 unsafe {
137 let mapping = CreateFileMappingW(
138 file.as_raw_handle() as *mut c_void,
139 core::ptr::null(),
140 PAGE_READONLY,
141 0,
142 0,
143 core::ptr::null(),
144 );
145 if mapping.is_null() {
146 return None;
147 }
148 let view = MapViewOfFile(mapping, FILE_MAP_READ, 0, 0, 0);
149 if view.is_null() {
150 let _ = CloseHandle(mapping);
151 return None;
152 }
153 Some(super::SystemFontBacking::WinMapped {
154 ptr: view as *const u8,
155 len,
156 mapping,
157 _file: file,
158 })
159 }
160 }
161}
162
163#[cfg(unix)]
164mod unix_mmap {
165 use core::ffi::c_void;
166 use std::os::unix::io::AsRawFd;
167
168 const PROT_READ: i32 = 1;
169 const MAP_SHARED: i32 = 1;
170
171 unsafe extern "C" {
172 fn mmap(
173 addr: *mut c_void,
174 length: usize,
175 prot: i32,
176 flags: i32,
177 fd: i32,
178 offset: isize,
179 ) -> *mut c_void;
180 pub(super) fn munmap(addr: *mut c_void, length: usize) -> i32;
181 }
182
183 pub(super) fn map_readonly(path: &str) -> Option<super::SystemFontBacking> {
184 let file = std::fs::File::open(path).ok()?;
185 let len = file.metadata().ok()?.len() as usize;
186 if len < 64 {
187 return None;
188 }
189 unsafe {
190 let view = mmap(
191 core::ptr::null_mut(),
192 len,
193 PROT_READ,
194 MAP_SHARED,
195 file.as_raw_fd(),
196 0,
197 );
198 if view.is_null() || view as isize == -1 {
199 return None;
200 }
201 Some(super::SystemFontBacking::UnixMapped {
202 ptr: view as *const u8,
203 len,
204 })
205 }
206 }
207}
208
209struct LoadedFont {
210 bytes: &'static [u8],
211 face: Face<'static>,
212 #[cfg(not(target_arch = "wasm32"))]
213 backing: SystemFontBacking,
214}
215
216unsafe impl Send for LoadedFont {}
218unsafe impl Sync for LoadedFont {}
219
220impl LoadedFont {
221 #[cfg(not(target_arch = "wasm32"))]
222 fn from_backing(backing: SystemFontBacking) -> Option<Self> {
223 let slice = backing.as_slice();
224 let ptr = slice.as_ptr();
225 let len = slice.len();
226 let static_bytes: &'static [u8] = unsafe { core::slice::from_raw_parts(ptr, len) };
229 let face = Face::parse(static_bytes, 0).ok()?;
230 Some(Self {
231 bytes: static_bytes,
232 face,
233 backing,
234 })
235 }
236
237 #[cfg(not(target_arch = "wasm32"))]
238 #[inline]
239 fn is_mapped(&self) -> bool {
240 self.backing.is_mapped()
241 }
242}
243
244#[cfg(not(target_arch = "wasm32"))]
245const PRIMARY_FONT_CANDIDATES: &[&str] = &[
246 "/system.ttf",
247 "/system/fonts/RobotoStatic-Regular.ttf",
248 "/system/fonts/Roboto-Regular.ttf",
249 "C:\\Windows\\Fonts\\segoeui.ttf",
250 "C:\\Windows\\Fonts\\arial.ttf",
251 "/System/Library/Fonts/Supplemental/Arial.ttf",
252 "/System/Library/Fonts/Helvetica.ttc",
253 "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
254 "/usr/share/fonts/TTF/DejaVuSans.ttf",
255 "/usr/share/fonts/noto/NotoSans-Regular.ttf",
256 "/usr/share/fonts/liberation/LiberationSans-Regular.ttf",
257];
258
259#[cfg(not(target_arch = "wasm32"))]
260const FALLBACK_CJK_CANDIDATES: &[&str] = &[
261 "C:\\Windows\\Fonts\\msyh.ttc",
262 "C:\\Windows\\Fonts\\msyhbd.ttc",
263 "C:\\Windows\\Fonts\\simhei.ttf",
264 "/System/Library/Fonts/PingFang.ttc",
265 "/system/fonts/NotoSansCJK-Regular.ttc",
266 "/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc",
267 "/usr/share/fonts/noto-cjk/NotoSansCJK-Regular.ttc",
268 "/usr/share/fonts/truetype/wqy/wqy-microhei.ttc",
269];
270
271#[cfg(not(target_arch = "wasm32"))]
272static PRIMARY_FONT: OnceLock<Option<LoadedFont>> = OnceLock::new();
273
274#[cfg(not(target_arch = "wasm32"))]
275static FALLBACK_CJK_FONT: OnceLock<Option<LoadedFont>> = OnceLock::new();
276
277#[cfg(target_arch = "wasm32")]
278static WASM_SUBSET_TTF_BYTES: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/wasm_subset.ttf"));
279#[cfg(target_arch = "wasm32")]
280static WASM_FONT: OnceLock<Option<LoadedFont>> = OnceLock::new();
281
282static GLYPH_CACHE: OnceLock<RwLock<HashMap<(char, u16), Arc<CachedGlyph>>>> = OnceLock::new();
283
284const TLS_SLOT_COUNT: usize = 256;
285const MAX_GLYPH_CACHE_ENTRIES: usize = 4096;
286
287std::thread_local! {
288 static TLS_GLYPHS: RefCell<[Option<(char, u16, Arc<CachedGlyph>)>; TLS_SLOT_COUNT]> =
290 RefCell::new([const { None }; TLS_SLOT_COUNT]);
291
292 static TLS_ADVANCES: RefCell<[Option<(char, u8, f32)>; TLS_SLOT_COUNT]> =
294 RefCell::new([const { None }; TLS_SLOT_COUNT]);
295
296 static TLS_KERNING: RefCell<[Option<(char, char, u8, f32)>; TLS_SLOT_COUNT]> =
298 RefCell::new([const { None }; TLS_SLOT_COUNT]);
299}
300
301#[cfg(not(target_arch = "wasm32"))]
302fn load_first_valid_font(candidates: &[&str]) -> Option<LoadedFont> {
303 for path in candidates {
304 #[cfg(target_os = "windows")]
306 if let Some(mapped) = win_mmap::map_readonly(path) {
307 if let Some(loaded) = LoadedFont::from_backing(mapped) {
308 return Some(loaded);
309 }
310 }
311 #[cfg(unix)]
312 if let Some(mapped) = unix_mmap::map_readonly(path) {
313 if let Some(loaded) = LoadedFont::from_backing(mapped) {
314 return Some(loaded);
315 }
316 }
317 if let Ok(bytes) = std::fs::read(path) {
318 if let Some(loaded) =
319 LoadedFont::from_backing(SystemFontBacking::Heap(bytes.into_boxed_slice()))
320 {
321 return Some(loaded);
322 }
323 }
324 }
325 None
326}
327
328#[cfg(not(target_arch = "wasm32"))]
329fn primary_font() -> Option<&'static LoadedFont> {
330 PRIMARY_FONT
331 .get_or_init(|| {
332 load_first_valid_font(PRIMARY_FONT_CANDIDATES)
333 .or_else(|| load_first_valid_font(FALLBACK_CJK_CANDIDATES))
334 })
335 .as_ref()
336}
337
338#[cfg(not(target_arch = "wasm32"))]
339fn fallback_cjk_font() -> Option<&'static LoadedFont> {
340 FALLBACK_CJK_FONT
341 .get_or_init(|| load_first_valid_font(FALLBACK_CJK_CANDIDATES))
342 .as_ref()
343}
344
345#[cfg(target_arch = "wasm32")]
346fn primary_font() -> Option<&'static LoadedFont> {
347 WASM_FONT
348 .get_or_init(|| {
349 if WASM_SUBSET_TTF_BYTES.is_empty() {
350 return None;
351 }
352 let face = Face::parse(WASM_SUBSET_TTF_BYTES, 0).ok()?;
353 Some(LoadedFont {
354 bytes: WASM_SUBSET_TTF_BYTES,
355 face,
356 })
357 })
358 .as_ref()
359}
360
361#[inline]
362fn select_font_and_glyph(ch: char) -> Option<(&'static LoadedFont, GlyphId)> {
363 let primary = primary_font()?;
364 if let Some(gid) = primary.face.glyph_index(ch) {
365 if gid.0 != 0 {
366 return Some((primary, gid));
367 }
368 }
369 #[cfg(not(target_arch = "wasm32"))]
370 if !ch.is_ascii() && !ch.is_control() {
371 if let Some(cjk) = fallback_cjk_font() {
372 if let Some(gid) = cjk.face.glyph_index(ch) {
373 if gid.0 != 0 {
374 return Some((cjk, gid));
375 }
376 }
377 }
378 }
379 let fallback_gid = primary.face.glyph_index(ch).unwrap_or(GlyphId(0));
380 Some((primary, fallback_gid))
381}
382
383#[cfg(all(feature = "winit", not(target_arch = "wasm32")))]
386pub(crate) fn spawn_font_preload(preload_cjk: bool) {
387 if PRIMARY_FONT.get().is_some() && (!preload_cjk || FALLBACK_CJK_FONT.get().is_some()) {
388 return;
389 }
390 let _ = std::thread::Builder::new()
391 .name(std::string::String::from("velox-font-preload"))
392 .stack_size(128 * 1024)
393 .spawn(move || {
394 let _ = primary_font();
395 if preload_cjk {
396 let _ = fallback_cjk_font();
397 }
398 });
399}
400
401#[inline]
403pub fn has_system_font() -> bool {
404 primary_font().is_some()
405}
406
407#[allow(dead_code)]
409pub fn get_system_font_bytes() -> Option<&'static [u8]> {
410 primary_font().map(|f| f.bytes)
411}
412
413#[allow(dead_code)]
415#[inline]
416pub fn resolve_char_font_and_glyph(ch: char) -> Option<(&'static [u8], u16)> {
417 let (font, gid) = select_font_and_glyph(ch)?;
418 Some((font.bytes, gid.0))
419}
420
421#[cfg(feature = "gpu")]
423#[inline]
424pub(crate) fn with_char_face_and_glyph<R>(
425 ch: char,
426 f: impl FnOnce(&Face<'_>, GlyphId, u64) -> R,
427) -> Option<R> {
428 let (font, gid) = select_font_and_glyph(ch)?;
429 let font_key = font.bytes.as_ptr() as usize as u64;
430 Some(f(&font.face, gid, font_key))
431}
432
433#[cfg(feature = "swash")]
435pub(crate) fn with_styled_font_bytes<R>(
436 sample_char: char,
437 spec: crate::text_rich::FontSpec,
438 f: impl FnOnce(&[u8], u64) -> R,
439) -> Option<R> {
440 if spec == crate::text_rich::FontSpec::SANS {
441 let (font, _) = select_font_and_glyph(sample_char)?;
442 let key = font.bytes.as_ptr() as usize as u64;
443 return Some(f(font.bytes, key));
444 }
445 let (selected, _, _, _) = select_styled_font_and_glyph(sample_char, spec)?;
446 match selected {
447 SelectedFont::Static(sf) => {
448 let key = sf.bytes.as_ptr() as usize as u64;
449 Some(f(sf.bytes, key))
450 }
451 SelectedFont::Custom(cf) => {
452 let bytes = cf.raw_bytes();
453 let key = bytes.as_ptr() as usize as u64;
454 Some(f(bytes, key))
455 }
456 }
457}
458
459#[cfg(feature = "swash")]
461pub(crate) fn with_font_bytes_by_key<R>(font_key: u64, f: impl FnOnce(&[u8]) -> R) -> Option<R> {
462 if font_key == 0 {
463 return None;
464 }
465 #[cfg(not(target_arch = "wasm32"))]
466 {
467 let slots: [&OnceLock<Option<LoadedFont>>; 7] = [
468 &PRIMARY_FONT,
469 &FALLBACK_CJK_FONT,
470 &BOLD_FONT,
471 &ITALIC_FONT,
472 &MONO_FONT,
473 &MONO_BOLD_FONT,
474 &SERIF_FONT,
475 ];
476 for slot in slots {
477 if let Some(Some(font)) = slot.get() {
478 if (font.bytes.as_ptr() as usize as u64) == font_key {
479 return Some(f(font.bytes));
480 }
481 }
482 }
483 }
484 #[cfg(target_arch = "wasm32")]
485 if let Some(Some(font)) = WASM_FONT.get() {
486 if (font.bytes.as_ptr() as usize as u64) == font_key {
487 return Some(f(font.bytes));
488 }
489 }
490 if let Some(map) = CUSTOM_FONTS.get() {
491 if let Ok(r) = map.read() {
492 for cf in r.values() {
493 let bytes = cf.raw_bytes();
494 if (bytes.as_ptr() as usize as u64) == font_key {
495 return Some(f(bytes));
496 }
497 }
498 }
499 }
500 None
501}
502
503pub fn get_font_ascent_f32(fs: f32) -> i32 {
506 let fs = fs.max(8.0);
507 let fs_i = fs.round() as i32;
508 if let Some(font) = primary_font() {
509 let upem = font.face.units_per_em().max(1) as f32;
510 let scale = fs / upem;
511 let cap_h = font
512 .face
513 .capital_height()
514 .filter(|&h| h > 0)
515 .map(|h| (h as f32) * scale)
516 .unwrap_or(fs * 0.70);
517 let centered = ((fs + cap_h) * 0.5 + 0.5) as i32;
519 return centered.clamp(1, (fs_i - 2).max(1));
520 }
521 (fs_i * 4) / 5
522}
523
524#[allow(dead_code)]
526#[inline]
527pub fn get_font_ascent(font_size: u8) -> i32 {
528 get_font_ascent_f32((font_size.max(8)) as f32)
529}
530
531pub fn measure_ttf_line_width_f32(line: &str, font_size: u8) -> Option<f32> {
534 if primary_font().is_none() {
535 return None;
536 }
537 if line.is_empty() {
538 return Some(0.0);
539 }
540 let mut total_px = 0.0f32;
541 let mut prev: Option<char> = None;
542
543 for ch in line.chars() {
544 if let Some(p) = prev {
545 total_px += measure_ttf_kerning_f32(p, ch, font_size);
546 }
547 let adv = measure_ttf_char_advance_f32(ch, font_size)?;
548 total_px = (total_px + adv).max(0.0);
549 prev = Some(ch);
550 }
551 Some(total_px)
552}
553
554pub fn measure_ttf_line_width_exact(line: &str, font_size: u8) -> Option<i16> {
558 let total_px = measure_ttf_line_width_f32(line, font_size)?;
559 if total_px <= 0.0 {
560 return Some(0);
561 }
562 Some((total_px.ceil() as i32).clamp(1, i16::MAX as i32) as i16)
563}
564
565#[inline]
566fn compute_scaled_advance_f32(face: &Face<'_>, gid: GlyphId, font_size: u8) -> f32 {
567 let fs = font_size.max(8) as f32;
568 let upem = face.units_per_em().max(1) as f32;
569 let raw_adv = face.glyph_hor_advance(gid).unwrap_or(0) as f32;
570 ((raw_adv * fs) / upem).max(1.0)
571}
572
573#[inline]
575pub fn measure_ttf_char_advance_f32(ch: char, font_size: u8) -> Option<f32> {
576 let slot_idx = (((ch as usize).wrapping_mul(2654435761)) ^ (font_size as usize))
577 & (TLS_SLOT_COUNT - 1);
578 if let Some(adv) = TLS_ADVANCES.with(|tls| {
579 let borrow = tls.borrow();
580 match borrow[slot_idx] {
581 Some((c, fs, a)) if c == ch && fs == font_size => Some(a),
582 _ => None,
583 }
584 }) {
585 return Some(adv);
586 }
587
588 let (font, gid) = select_font_and_glyph(ch)?;
589 let adv = compute_scaled_advance_f32(&font.face, gid, font_size);
590 TLS_ADVANCES.with(|tls| {
591 tls.borrow_mut()[slot_idx] = Some((ch, font_size, adv));
592 });
593 Some(adv)
594}
595
596#[inline]
598pub fn measure_ttf_char_advance(ch: char, font_size: u8) -> Option<i16> {
599 measure_ttf_char_advance_f32(ch, font_size).map(|a| (a + 0.5) as i16)
600}
601
602#[inline]
604pub fn measure_ttf_kerning_f32(prev: char, curr: char, font_size: u8) -> f32 {
605 if prev.is_control() || curr.is_control() {
606 return 0.0;
607 }
608 let slot_idx = (((prev as usize).wrapping_mul(2654435761))
609 ^ ((curr as usize).wrapping_mul(2246822519))
610 ^ ((font_size as usize) << 3))
611 & (TLS_SLOT_COUNT - 1);
612
613 if let Some(k) = TLS_KERNING.with(|tls| {
614 let borrow = tls.borrow();
615 match borrow[slot_idx] {
616 Some((p, c, fs, val)) if p == prev && c == curr && fs == font_size => Some(val),
617 _ => None,
618 }
619 }) {
620 return k;
621 }
622
623 let kern_px = (|| -> Option<f32> {
624 let (f1, g1) = select_font_and_glyph(prev)?;
625 let (f2, g2) = select_font_and_glyph(curr)?;
626 if !core::ptr::eq(f1, f2) {
627 return Some(0.0);
628 }
629 let kern_table = f1.face.tables().kern?;
630 let mut raw_kern: i32 = 0;
631 for subtable in kern_table.subtables {
632 if subtable.horizontal && !subtable.variable {
633 if let Some(v) = subtable.glyphs_kerning(g1, g2) {
634 raw_kern += v as i32;
635 }
636 }
637 }
638 if raw_kern == 0 {
639 return Some(0.0);
640 }
641 let fs = font_size.max(8) as f32;
642 let upem = f1.face.units_per_em().max(1) as f32;
643 Some(((raw_kern as f32) * fs / upem).clamp(-32.0, 32.0))
644 })()
645 .unwrap_or(0.0);
646
647 TLS_KERNING.with(|tls| {
648 tls.borrow_mut()[slot_idx] = Some((prev, curr, font_size, kern_px));
649 });
650 kern_px
651}
652
653#[inline]
657pub fn measure_ttf_kerning(prev: char, curr: char, font_size: u8) -> i16 {
658 measure_ttf_kerning_f32(prev, curr, font_size).round() as i16
659}
660
661#[derive(Copy, Clone)]
662struct EdgeSegment {
663 x0: f32,
664 y0: f32,
665 x1: f32,
666 y1: f32,
667}
668
669struct ScaledOutlineCollector {
670 scale: f32,
671 subpath_start: Option<(f32, f32)>,
672 current: (f32, f32),
673 edges: Vec<EdgeSegment>,
674 min_x: f32,
675 min_y: f32,
676 max_x: f32,
677 max_y: f32,
678}
679
680impl ScaledOutlineCollector {
681 fn new(scale: f32) -> Self {
682 Self {
683 scale,
684 subpath_start: None,
685 current: (0.0, 0.0),
686 edges: Vec::with_capacity(32),
687 min_x: f32::INFINITY,
688 min_y: f32::INFINITY,
689 max_x: f32::NEG_INFINITY,
690 max_y: f32::NEG_INFINITY,
691 }
692 }
693
694 #[inline]
695 fn to_screen(&self, x: f32, y: f32) -> (f32, f32) {
696 (x * self.scale, -y * self.scale)
697 }
698
699 #[inline]
700 fn push_edge(&mut self, x0: f32, y0: f32, x1: f32, y1: f32) {
701 self.min_x = self.min_x.min(x0).min(x1);
702 self.max_x = self.max_x.max(x0).max(x1);
703 self.min_y = self.min_y.min(y0).min(y1);
704 self.max_y = self.max_y.max(y0).max(y1);
705 if (y1 - y0).abs() > 1e-6 {
706 self.edges.push(EdgeSegment { x0, y0, x1, y1 });
707 }
708 }
709
710 fn finish_subpath(&mut self) {
711 if let Some((sx, sy)) = self.subpath_start.take() {
712 let (cx, cy) = self.current;
713 if (cx - sx).abs() > 1e-5 || (cy - sy).abs() > 1e-5 {
714 self.push_edge(cx, cy, sx, sy);
715 }
716 self.current = (sx, sy);
717 }
718 }
719}
720
721impl OutlineBuilder for ScaledOutlineCollector {
722 fn move_to(&mut self, x: f32, y: f32) {
723 self.finish_subpath();
724 let pt = self.to_screen(x, y);
725 self.subpath_start = Some(pt);
726 self.current = pt;
727 }
728
729 fn line_to(&mut self, x: f32, y: f32) {
730 let (x0, y0) = self.current;
731 let (x1, y1) = self.to_screen(x, y);
732 if (x1 - x0).abs() > 1e-6 || (y1 - y0).abs() > 1e-6 {
733 self.push_edge(x0, y0, x1, y1);
734 }
735 self.current = (x1, y1);
736 }
737
738 fn quad_to(&mut self, x1: f32, y1: f32, x: f32, y: f32) {
739 let (sx0, sy0) = self.current;
740 let (cx, cy) = self.to_screen(x1, y1);
741 let (sx1, sy1) = self.to_screen(x, y);
742
743 let err = (cx - 0.5 * (sx0 + sx1)).abs() + (cy - 0.5 * (sy0 + sy1)).abs();
744 let steps = if err <= 0.1 {
745 1usize
746 } else {
747 ((err * 2.5).sqrt().ceil() as usize).clamp(2, 32)
748 };
749
750 let mut px = sx0;
751 let mut py = sy0;
752 let inv = 1.0 / (steps as f32);
753 for i in 1..=steps {
754 let t = (i as f32) * inv;
755 let u = 1.0 - t;
756 let nx = if i == steps {
757 sx1
758 } else {
759 u * u * sx0 + 2.0 * u * t * cx + t * t * sx1
760 };
761 let ny = if i == steps {
762 sy1
763 } else {
764 u * u * sy0 + 2.0 * u * t * cy + t * t * sy1
765 };
766 self.push_edge(px, py, nx, ny);
767 px = nx;
768 py = ny;
769 }
770 self.current = (sx1, sy1);
771 }
772
773 fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32) {
774 let (sx0, sy0) = self.current;
775 let (cx1, cy1) = self.to_screen(x1, y1);
776 let (cx2, cy2) = self.to_screen(x2, y2);
777 let (sx1, sy1) = self.to_screen(x, y);
778
779 let lx1 = sx0 + (sx1 - sx0) * (1.0 / 3.0);
780 let ly1 = sy0 + (sy1 - sy0) * (1.0 / 3.0);
781 let lx2 = sx0 + (sx1 - sx0) * (2.0 / 3.0);
782 let ly2 = sy0 + (sy1 - sy0) * (2.0 / 3.0);
783 let err1 = (cx1 - lx1).abs() + (cy1 - ly1).abs();
784 let err2 = (cx2 - lx2).abs() + (cy2 - ly2).abs();
785 let err = err1.max(err2);
786 let steps = if err <= 0.1 {
787 1usize
788 } else {
789 ((err * 3.0).sqrt().ceil() as usize).clamp(2, 48)
790 };
791
792 let mut px = sx0;
793 let mut py = sy0;
794 let inv = 1.0 / (steps as f32);
795 for i in 1..=steps {
796 let t = (i as f32) * inv;
797 let u = 1.0 - t;
798 let u2 = u * u;
799 let t2 = t * t;
800 let nx = if i == steps {
801 sx1
802 } else {
803 u2 * u * sx0 + 3.0 * u2 * t * cx1 + 3.0 * u * t2 * cx2 + t2 * t * sx1
804 };
805 let ny = if i == steps {
806 sy1
807 } else {
808 u2 * u * sy0 + 3.0 * u2 * t * cy1 + 3.0 * u * t2 * cy2 + t2 * t * sy1
809 };
810 self.push_edge(px, py, nx, ny);
811 px = nx;
812 py = ny;
813 }
814 self.current = (sx1, sy1);
815 }
816
817 fn close(&mut self) {
818 self.finish_subpath();
819 }
820}
821
822fn rasterize_glyph_outline(face: &Face<'_>, gid: GlyphId, fs: f32) -> CachedGlyph {
824 let fs = fs.max(8.0);
825 let upem = face.units_per_em().max(1) as f32;
826 let raw_adv = face.glyph_hor_advance(gid).unwrap_or(0) as f32;
827 let adv = (((raw_adv * fs) / upem).max(1.0) + 0.5) as i16;
828 let scale = fs / upem;
829
830 let mut collector = ScaledOutlineCollector::new(scale);
831 let outlined = face.outline_glyph(gid, &mut collector).is_some();
832 collector.finish_subpath();
833
834 if !outlined || collector.edges.is_empty() || !collector.min_x.is_finite() {
835 return CachedGlyph {
836 width: 0,
837 height: 0,
838 xmin: 0,
839 ymin: 0,
840 advance_width: adv,
841 bitmap: Vec::new(),
842 color_rgba: None,
843 };
844 }
845
846 let px_min_x = collector.min_x.floor() as i32;
847 let px_max_x = collector.max_x.ceil() as i32;
848 let px_min_y = collector.min_y.floor() as i32;
849 let px_max_y = collector.max_y.ceil() as i32;
850
851 let w = (px_max_x - px_min_x).clamp(0, 512) as usize;
852 let h = (px_max_y - px_min_y).clamp(0, 512) as usize;
853 if w == 0 || h == 0 {
854 return CachedGlyph {
855 width: 0,
856 height: 0,
857 xmin: 0,
858 ymin: 0,
859 advance_width: adv,
860 bitmap: Vec::new(),
861 color_rgba: None,
862 };
863 }
864
865 let ox = px_min_x as f32;
866 let oy = px_min_y as f32;
867 let wf = w as f32;
868 let area_stride = w + 1;
869 let mut area = vec![0.0f32; area_stride * h];
870
871 for seg in &collector.edges {
872 let sx0 = seg.x0 - ox;
873 let sy0 = seg.y0 - oy;
874 let sx1 = seg.x1 - ox;
875 let sy1 = seg.y1 - oy;
876
877 let (dir, ax0, ay0, ax1, ay1) = if sy1 > sy0 {
878 (1.0f32, sx0, sy0, sx1, sy1)
879 } else {
880 (-1.0f32, sx1, sy1, sx0, sy0)
881 };
882 let dy_total = ay1 - ay0;
883 if dy_total <= 1e-6 {
884 continue;
885 }
886
887 let r_start = (ay0.floor() as isize).max(0) as usize;
888 let r_end = ((ay1.ceil() as isize).min(h as isize)).max(0) as usize;
889 let inv_dy = 1.0 / dy_total;
890
891 for row in r_start..r_end {
892 let rf0 = row as f32;
893 let rf1 = (row + 1) as f32;
894 let ry0 = ay0.max(rf0);
895 let ry1 = ay1.min(rf1);
896 let dh = ry1 - ry0;
897 if dh <= 1e-6 {
898 continue;
899 }
900
901 let t0 = (ry0 - ay0) * inv_dy;
902 let t1 = (ry1 - ay0) * inv_dy;
903 let rx0 = (ax0 + (ax1 - ax0) * t0).clamp(0.0, wf);
904 let rx1 = (ax0 + (ax1 - ax0) * t1).clamp(0.0, wf);
905 let row_dh = dir * dh;
906 let row_off = row * area_stride;
907
908 let x_min = rx0.min(rx1);
909 let x_max = rx0.max(rx1);
910 if x_min >= wf {
911 continue;
912 }
913
914 let dx_abs = x_max - x_min;
915 if dx_abs <= 1e-6 {
916 let x_mid = 0.5 * (rx0 + rx1);
917 if x_mid < wf {
918 let col = (x_mid.floor() as usize).min(w - 1);
919 let frac = (x_mid - (col as f32)).clamp(0.0, 1.0);
920 area[row_off + col] += row_dh * (1.0 - frac);
921 area[row_off + col + 1] += row_dh * frac;
922 }
923 } else {
924 let c_first = (x_min.floor() as usize).min(w - 1);
925 let c_last = ((x_max.ceil() as usize).saturating_sub(1)).min(w - 1);
926 let inv_dx = 1.0 / dx_abs;
927 for col in c_first..=c_last {
928 let cf0 = col as f32;
929 let cf1 = (col + 1) as f32;
930 let cx0 = x_min.max(cf0);
931 let cx1 = x_max.min(cf1);
932 if cx1 <= cx0 {
933 continue;
934 }
935 let sub_dh = row_dh * ((cx1 - cx0) * inv_dx);
936 let mid_frac = (0.5 * (cx0 + cx1) - cf0).clamp(0.0, 1.0);
937 area[row_off + col] += sub_dh * (1.0 - mid_frac);
938 area[row_off + col + 1] += sub_dh * mid_frac;
939 }
940 }
941 }
942 }
943
944 let mut bitmap = vec![0u8; w * h];
945 for row in 0..h {
946 let row_off = row * area_stride;
947 let dst_off = row * w;
948 let mut acc = 0.0f32;
949 for col in 0..w {
950 acc += area[row_off + col];
951 let cov = acc.abs().min(1.0);
952 bitmap[dst_off + col] = (cov * 255.0 + 0.5) as u8;
953 }
954 }
955
956 CachedGlyph {
957 width: w,
958 height: h,
959 xmin: px_min_x,
960 ymin: -px_max_y,
962 advance_width: adv,
963 bitmap,
964 color_rgba: None,
965 }
966}
967
968#[cfg(not(target_arch = "wasm32"))]
973const BOLD_FONT_CANDIDATES: &[&str] = &[
974 "C:\\Windows\\Fonts\\segoeuib.ttf",
975 "C:\\Windows\\Fonts\\arialbd.ttf",
976 "/System/Library/Fonts/Supplemental/Arial Bold.ttf",
977 "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf",
978 "/usr/share/fonts/noto/NotoSans-Bold.ttf",
979 "/usr/share/fonts/liberation/LiberationSans-Bold.ttf",
980];
981
982#[cfg(not(target_arch = "wasm32"))]
983const ITALIC_FONT_CANDIDATES: &[&str] = &[
984 "C:\\Windows\\Fonts\\segoeuii.ttf",
985 "C:\\Windows\\Fonts\\ariali.ttf",
986 "/System/Library/Fonts/Supplemental/Arial Italic.ttf",
987 "/usr/share/fonts/truetype/dejavu/DejaVuSans-Oblique.ttf",
988 "/usr/share/fonts/noto/NotoSans-Italic.ttf",
989];
990
991#[cfg(not(target_arch = "wasm32"))]
992const MONO_FONT_CANDIDATES: &[&str] = &[
993 "C:\\Windows\\Fonts\\consola.ttf",
994 "C:\\Windows\\Fonts\\CascadiaMono.ttf",
995 "C:\\Windows\\Fonts\\cour.ttf",
996 "/System/Library/Fonts/Menlo.ttc",
997 "/System/Library/Fonts/SFNSMono.ttf",
998 "/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf",
999 "/usr/share/fonts/noto/NotoSansMono-Regular.ttf",
1000];
1001
1002#[cfg(not(target_arch = "wasm32"))]
1003const MONO_BOLD_FONT_CANDIDATES: &[&str] = &[
1004 "C:\\Windows\\Fonts\\consolab.ttf",
1005 "C:\\Windows\\Fonts\\courbd.ttf",
1006 "/usr/share/fonts/truetype/dejavu/DejaVuSansMono-Bold.ttf",
1007];
1008
1009#[cfg(not(target_arch = "wasm32"))]
1010const SERIF_FONT_CANDIDATES: &[&str] = &[
1011 "C:\\Windows\\Fonts\\georgia.ttf",
1012 "C:\\Windows\\Fonts\\times.ttf",
1013 "/System/Library/Fonts/Times.ttc",
1014 "/usr/share/fonts/truetype/dejavu/DejaVuSerif.ttf",
1015];
1016
1017#[cfg(not(target_arch = "wasm32"))]
1018static BOLD_FONT: OnceLock<Option<LoadedFont>> = OnceLock::new();
1019#[cfg(not(target_arch = "wasm32"))]
1020static ITALIC_FONT: OnceLock<Option<LoadedFont>> = OnceLock::new();
1021#[cfg(not(target_arch = "wasm32"))]
1022static MONO_FONT: OnceLock<Option<LoadedFont>> = OnceLock::new();
1023#[cfg(not(target_arch = "wasm32"))]
1024static MONO_BOLD_FONT: OnceLock<Option<LoadedFont>> = OnceLock::new();
1025#[cfg(not(target_arch = "wasm32"))]
1026static SERIF_FONT: OnceLock<Option<LoadedFont>> = OnceLock::new();
1027
1028enum FontBacking {
1029 #[allow(dead_code)]
1030 Static(&'static [u8]),
1031 Owned(Box<[u8]>),
1032}
1033
1034impl FontBacking {
1035 #[inline]
1036 fn owned_bytes(&self) -> usize {
1037 match self {
1038 Self::Static(_) => 0,
1039 Self::Owned(b) => b.len(),
1040 }
1041 }
1042
1043 #[cfg(feature = "swash")]
1044 #[inline]
1045 fn as_slice(&self) -> &[u8] {
1046 match self {
1047 Self::Static(b) => b,
1048 Self::Owned(b) => b,
1049 }
1050 }
1051}
1052
1053struct OwnedCustomFont {
1055 face: Face<'static>,
1057 _backing: FontBacking,
1058}
1059
1060unsafe impl Send for OwnedCustomFont {}
1062unsafe impl Sync for OwnedCustomFont {}
1063
1064impl OwnedCustomFont {
1065 fn from_static(bytes: &'static [u8]) -> Option<Self> {
1066 let face = Face::parse(bytes, 0).ok()?;
1067 Some(Self {
1068 face,
1069 _backing: FontBacking::Static(bytes),
1070 })
1071 }
1072
1073 fn from_vec(bytes: Vec<u8>) -> Option<Self> {
1074 let boxed = bytes.into_boxed_slice();
1075 let ptr = boxed.as_ptr();
1076 let len = boxed.len();
1077 let static_view: &'static [u8] = unsafe { core::slice::from_raw_parts(ptr, len) };
1080 let face = Face::parse(static_view, 0).ok()?;
1081 Some(Self {
1082 face,
1083 _backing: FontBacking::Owned(boxed),
1084 })
1085 }
1086
1087 #[inline]
1088 fn face(&self) -> &Face<'_> {
1089 &self.face
1090 }
1091
1092 #[cfg(feature = "swash")]
1093 #[inline]
1094 fn raw_bytes(&self) -> &[u8] {
1095 self._backing.as_slice()
1096 }
1097
1098 #[inline]
1099 fn owned_bytes(&self) -> usize {
1100 self._backing.owned_bytes()
1101 }
1102}
1103
1104enum SelectedFont {
1105 Static(&'static LoadedFont),
1106 Custom(Arc<OwnedCustomFont>),
1107}
1108
1109impl SelectedFont {
1110 #[inline]
1111 fn face(&self) -> &Face<'_> {
1112 match self {
1113 Self::Static(f) => &f.face,
1114 Self::Custom(f) => f.face(),
1115 }
1116 }
1117}
1118
1119static CUSTOM_FONTS: OnceLock<RwLock<HashMap<u32, Arc<OwnedCustomFont>>>> = OnceLock::new();
1120static STYLED_GLYPH_CACHE: OnceLock<RwLock<HashMap<(char, u16, u32), Arc<CachedGlyph>>>> =
1121 OnceLock::new();
1122
1123#[inline]
1124fn font_spec_family_bits(packed_key: u32) -> u32 {
1125 packed_key >> 16
1126}
1127
1128fn invalidate_styled_glyphs_for_spec(spec: crate::text_rich::FontSpec) {
1129 let target_family = font_spec_family_bits(spec.packed_key());
1130 if let Some(cache) = STYLED_GLYPH_CACHE.get() {
1131 if let Ok(mut c) = cache.write() {
1132 c.retain(|&(_, _, key), _| font_spec_family_bits(key) != target_family);
1134 }
1135 }
1136}
1137
1138#[cfg(not(target_arch = "wasm32"))]
1139fn load_static_candidate(candidates: &[&str]) -> Option<LoadedFont> {
1140 load_first_valid_font(candidates)
1141}
1142
1143pub fn register_font_bytes(spec: crate::text_rich::FontSpec, bytes: &'static [u8]) -> bool {
1147 let Some(owned) = OwnedCustomFont::from_static(bytes) else {
1148 return false;
1149 };
1150 let map = CUSTOM_FONTS.get_or_init(|| RwLock::new(HashMap::new()));
1151 if let Ok(mut w) = map.write() {
1152 w.insert(spec.packed_key(), Arc::new(owned));
1153 }
1154 invalidate_styled_glyphs_for_spec(spec);
1155 true
1156}
1157
1158pub fn register_font_vec(spec: crate::text_rich::FontSpec, bytes: Vec<u8>) -> bool {
1162 let Some(owned) = OwnedCustomFont::from_vec(bytes) else {
1163 return false;
1164 };
1165 let map = CUSTOM_FONTS.get_or_init(|| RwLock::new(HashMap::new()));
1166 if let Ok(mut w) = map.write() {
1167 w.insert(spec.packed_key(), Arc::new(owned));
1168 }
1169 invalidate_styled_glyphs_for_spec(spec);
1170 true
1171}
1172
1173pub fn unregister_font(spec: crate::text_rich::FontSpec) -> bool {
1175 let removed = CUSTOM_FONTS
1176 .get()
1177 .and_then(|m| m.write().ok().map(|mut w| w.remove(&spec.packed_key()).is_some()))
1178 .unwrap_or(false);
1179 if removed {
1180 invalidate_styled_glyphs_for_spec(spec);
1181 }
1182 removed
1183}
1184
1185pub fn registered_custom_font_count() -> usize {
1187 CUSTOM_FONTS
1188 .get()
1189 .and_then(|m| m.read().ok().map(|r| r.len()))
1190 .unwrap_or(0)
1191}
1192
1193pub fn registered_custom_font_bytes() -> usize {
1195 CUSTOM_FONTS
1196 .get()
1197 .and_then(|m| {
1198 m.read()
1199 .ok()
1200 .map(|r| r.values().map(|f| f.owned_bytes()).sum())
1201 })
1202 .unwrap_or(0)
1203}
1204
1205#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
1207pub struct FontMemoryStats {
1208 pub primary_bytes: usize,
1209 pub fallback_cjk_bytes: usize,
1210 pub bold_bytes: usize,
1211 pub italic_bytes: usize,
1212 pub mono_bytes: usize,
1213 pub mono_bold_bytes: usize,
1214 pub serif_bytes: usize,
1215 pub custom_font_bytes: usize,
1216 pub mapped_font_bytes: usize,
1218 pub heap_font_bytes: usize,
1220 pub glyph_cache_entries: usize,
1221 pub glyph_cache_bitmap_bytes: usize,
1222 pub styled_glyph_cache_entries: usize,
1223 pub styled_glyph_cache_bitmap_bytes: usize,
1224}
1225
1226impl FontMemoryStats {
1227 #[inline]
1229 pub const fn total_raw_font_bytes(&self) -> usize {
1230 self.primary_bytes
1231 + self.fallback_cjk_bytes
1232 + self.bold_bytes
1233 + self.italic_bytes
1234 + self.mono_bytes
1235 + self.mono_bold_bytes
1236 + self.serif_bytes
1237 + self.custom_font_bytes
1238 }
1239
1240 #[inline]
1242 pub const fn total_bitmap_bytes(&self) -> usize {
1243 self.glyph_cache_bitmap_bytes + self.styled_glyph_cache_bitmap_bytes
1244 }
1245}
1246
1247pub fn font_memory_stats() -> FontMemoryStats {
1249 let mut stats = FontMemoryStats::default();
1250 #[cfg(not(target_arch = "wasm32"))]
1251 {
1252 let mut record = |slot: &OnceLock<Option<LoadedFont>>| -> usize {
1253 let Some(f) = slot.get().and_then(|o| o.as_ref()) else {
1254 return 0;
1255 };
1256 let len = f.backing.len();
1257 if f.is_mapped() {
1258 stats.mapped_font_bytes += len;
1259 } else {
1260 stats.heap_font_bytes += len;
1261 }
1262 len
1263 };
1264 stats.primary_bytes = record(&PRIMARY_FONT);
1265 stats.fallback_cjk_bytes = record(&FALLBACK_CJK_FONT);
1266 stats.bold_bytes = record(&BOLD_FONT);
1267 stats.italic_bytes = record(&ITALIC_FONT);
1268 stats.mono_bytes = record(&MONO_FONT);
1269 stats.mono_bold_bytes = record(&MONO_BOLD_FONT);
1270 stats.serif_bytes = record(&SERIF_FONT);
1271 }
1272 stats.custom_font_bytes = registered_custom_font_bytes();
1273 stats.heap_font_bytes += stats.custom_font_bytes;
1274 if let Some(cache) = GLYPH_CACHE.get() {
1275 if let Ok(r) = cache.read() {
1276 stats.glyph_cache_entries = r.len();
1277 stats.glyph_cache_bitmap_bytes = r
1278 .values()
1279 .map(|g| {
1280 g.bitmap.capacity()
1281 + g.color_rgba.as_ref().map(|v| v.capacity()).unwrap_or(0)
1282 })
1283 .sum();
1284 }
1285 }
1286 if let Some(cache) = STYLED_GLYPH_CACHE.get() {
1287 if let Ok(r) = cache.read() {
1288 stats.styled_glyph_cache_entries = r.len();
1289 stats.styled_glyph_cache_bitmap_bytes = r
1290 .values()
1291 .map(|g| {
1292 g.bitmap.capacity()
1293 + g.color_rgba.as_ref().map(|v| v.capacity()).unwrap_or(0)
1294 })
1295 .sum();
1296 }
1297 }
1298 stats
1299}
1300
1301fn select_styled_font_and_glyph(
1302 ch: char,
1303 spec: crate::text_rich::FontSpec,
1304) -> Option<(SelectedFont, GlyphId, bool, bool)> {
1305 use crate::text_rich::{FontFamily, FontStyle};
1306 if let Some(map) = CUSTOM_FONTS.get() {
1308 if let Ok(r) = map.read() {
1309 if let Some(f) = r.get(&spec.packed_key()) {
1310 if let Some(gid) = f.face().glyph_index(ch).filter(|g| g.0 != 0) {
1311 return Some((SelectedFont::Custom(Arc::clone(f)), gid, false, false));
1312 }
1313 }
1314 let base_key = crate::text_rich::FontSpec {
1316 family: spec.family,
1317 weight: crate::text_rich::FontWeight::Normal,
1318 style: FontStyle::Normal,
1319 }
1320 .packed_key();
1321 if let Some(f) = r.get(&base_key) {
1322 if let Some(gid) = f.face().glyph_index(ch).filter(|g| g.0 != 0) {
1323 return Some((
1324 SelectedFont::Custom(Arc::clone(f)),
1325 gid,
1326 spec.weight.is_bold(),
1327 spec.style == FontStyle::Italic,
1328 ));
1329 }
1330 }
1331 }
1332 }
1333
1334 #[cfg(not(target_arch = "wasm32"))]
1335 {
1336 let (candidate, matched_bold, matched_italic): (Option<&'static LoadedFont>, bool, bool) =
1337 match spec.family {
1338 FontFamily::Mono => {
1339 if spec.weight.is_bold() {
1340 if let Some(f) = MONO_BOLD_FONT
1341 .get_or_init(|| load_static_candidate(MONO_BOLD_FONT_CANDIDATES))
1342 .as_ref()
1343 {
1344 (Some(f), true, false)
1345 } else {
1346 (
1347 MONO_FONT
1348 .get_or_init(|| load_static_candidate(MONO_FONT_CANDIDATES))
1349 .as_ref(),
1350 false,
1351 false,
1352 )
1353 }
1354 } else {
1355 (
1356 MONO_FONT
1357 .get_or_init(|| load_static_candidate(MONO_FONT_CANDIDATES))
1358 .as_ref(),
1359 false,
1360 false,
1361 )
1362 }
1363 }
1364 FontFamily::Serif => (
1365 SERIF_FONT
1366 .get_or_init(|| load_static_candidate(SERIF_FONT_CANDIDATES))
1367 .as_ref(),
1368 false,
1369 false,
1370 ),
1371 FontFamily::Sans | FontFamily::Custom(_) => {
1372 if spec.weight.is_bold() {
1373 (
1374 BOLD_FONT
1375 .get_or_init(|| load_static_candidate(BOLD_FONT_CANDIDATES))
1376 .as_ref(),
1377 true,
1378 false,
1379 )
1380 } else if spec.style == FontStyle::Italic {
1381 (
1382 ITALIC_FONT
1383 .get_or_init(|| load_static_candidate(ITALIC_FONT_CANDIDATES))
1384 .as_ref(),
1385 false,
1386 true,
1387 )
1388 } else {
1389 (None, false, false)
1390 }
1391 }
1392 };
1393
1394 if let Some(f) = candidate {
1395 if let Some(gid) = f.face.glyph_index(ch).filter(|g| g.0 != 0) {
1396 return Some((
1397 SelectedFont::Static(f),
1398 gid,
1399 spec.weight.is_bold() && !matched_bold,
1400 spec.style == FontStyle::Italic && !matched_italic,
1401 ));
1402 }
1403 }
1404 }
1405
1406 let (f, gid) = select_font_and_glyph(ch)?;
1407 Some((
1408 SelectedFont::Static(f),
1409 gid,
1410 spec.weight.is_bold(),
1411 spec.style == FontStyle::Italic,
1412 ))
1413}
1414
1415fn apply_faux_bold(g: &mut CachedGlyph) {
1416 if g.width == 0 || g.height == 0 || g.bitmap.is_empty() {
1417 return;
1418 }
1419 let old_w = g.width;
1420 let new_w = old_w + 1;
1421 let mut out = vec![0u8; new_w * g.height];
1422 for y in 0..g.height {
1423 for x in 0..old_w {
1424 let v = g.bitmap[y * old_w + x];
1425 let dst0 = &mut out[y * new_w + x];
1426 if v > *dst0 {
1427 *dst0 = v;
1428 }
1429 let dst1 = &mut out[y * new_w + x + 1];
1430 let boost = ((v as u16 * 220) >> 8) as u8;
1431 if boost > *dst1 {
1432 *dst1 = boost;
1433 }
1434 }
1435 }
1436 g.width = new_w;
1437 g.advance_width = g.advance_width.saturating_add(1);
1438 g.bitmap = out;
1439}
1440
1441fn apply_faux_italic(g: &mut CachedGlyph) {
1442 if g.width == 0 || g.height == 0 || g.bitmap.is_empty() {
1443 return;
1444 }
1445 let skew_px = ((g.height as f32) * 0.22).ceil() as usize;
1446 if skew_px == 0 {
1447 return;
1448 }
1449 let old_w = g.width;
1450 let new_w = old_w + skew_px;
1451 let mut out = vec![0u8; new_w * g.height];
1452 for y in 0..g.height {
1453 let shift = (((g.height - 1 - y) as f32) * 0.22).round() as usize;
1454 for x in 0..old_w {
1455 let nx = (x + shift).min(new_w - 1);
1456 let v = g.bitmap[y * old_w + x];
1457 let d = &mut out[y * new_w + nx];
1458 if v > *d {
1459 *d = v;
1460 }
1461 }
1462 }
1463 g.width = new_w;
1464 g.bitmap = out;
1465}
1466
1467fn synthesize_color_emoji_glyph(ch: char, fs: f32) -> CachedGlyph {
1469 let dim = (fs.round() as usize).clamp(8, 128);
1470 let mut rgba = vec![0u8; dim * dim * 4];
1471 let mut alpha = vec![0u8; dim * dim];
1472 let cx = (dim as f32) * 0.5;
1473 let cy = (dim as f32) * 0.5;
1474 let r = (dim as f32) * 0.44;
1475 let cp = ch as u32;
1476 let (base_r, base_g, base_b) = match cp % 6 {
1477 0 => (255u8, 204u8, 51u8), 1 => (239u8, 68u8, 68u8), 2 => (56u8, 189u8, 248u8), 3 => (52u8, 211u8, 153u8), 4 => (168u8, 85u8, 247u8), _ => (251u8, 146u8, 60u8), };
1484 for y in 0..dim {
1485 for x in 0..dim {
1486 let dx = (x as f32 + 0.5) - cx;
1487 let dy = (y as f32 + 0.5) - cy;
1488 let dist = (dx * dx + dy * dy).sqrt();
1489 let cov = (r + 0.5 - dist).clamp(0.0, 1.0);
1490 if cov > 0.0 {
1491 let hi = (1.0 - ((dx + r * 0.35).hypot(dy + r * 0.35) / (r * 1.6))).clamp(0.0, 0.35);
1493 let rr = ((base_r as f32) + (255.0 - base_r as f32) * hi).min(255.0);
1494 let gg = ((base_g as f32) + (255.0 - base_g as f32) * hi).min(255.0);
1495 let bb = ((base_b as f32) + (255.0 - base_b as f32) * hi).min(255.0);
1496 let a = (cov * 255.0 + 0.5) as u8;
1497 let idx = (y * dim + x) * 4;
1498 rgba[idx] = (rr * cov + 0.5) as u8;
1499 rgba[idx + 1] = (gg * cov + 0.5) as u8;
1500 rgba[idx + 2] = (bb * cov + 0.5) as u8;
1501 rgba[idx + 3] = a;
1502 alpha[y * dim + x] = a;
1503 }
1504 }
1505 }
1506 CachedGlyph {
1507 width: dim,
1508 height: dim,
1509 xmin: 0,
1510 ymin: -((dim as i32) / 6),
1511 advance_width: dim as i16,
1512 bitmap: alpha,
1513 color_rgba: Some(rgba),
1514 }
1515}
1516
1517pub fn measure_ttf_char_advance_styled_f32(
1519 ch: char,
1520 font_size: u8,
1521 spec: crate::text_rich::FontSpec,
1522) -> Option<f32> {
1523 if spec == crate::text_rich::FontSpec::SANS && !crate::text_rich::is_emoji_char(ch) {
1524 return measure_ttf_char_advance_f32(ch, font_size);
1525 }
1526 if crate::text_rich::is_emoji_char(ch) {
1527 return Some((font_size.max(8) as f32) * 1.05);
1528 }
1529 let (font, gid, faux_bold, _) = select_styled_font_and_glyph(ch, spec)?;
1530 let face = font.face();
1531 let upem = face.units_per_em().max(1) as f32;
1532 let raw_adv = face.glyph_hor_advance(gid).unwrap_or(0) as f32;
1533 let px = (raw_adv * (font_size.max(8) as f32)) / upem;
1534 Some((px + if faux_bold { 0.8 } else { 0.0 }).max(1.0))
1535}
1536
1537pub fn get_cached_glyph_styled_q4(
1539 ch: char,
1540 font_size_q4: u16,
1541 spec: crate::text_rich::FontSpec,
1542) -> Option<Arc<CachedGlyph>> {
1543 if spec == crate::text_rich::FontSpec::SANS && !crate::text_rich::is_emoji_char(ch) {
1544 return get_cached_glyph_q4(ch, font_size_q4);
1545 }
1546 let q4 = font_size_q4.clamp(32, 1020);
1547 let key = (ch, q4, spec.packed_key());
1548 let cache = STYLED_GLYPH_CACHE.get_or_init(|| RwLock::new(HashMap::new()));
1549 if let Ok(r) = cache.read() {
1550 if let Some(g) = r.get(&key) {
1551 return Some(Arc::clone(g));
1552 }
1553 }
1554 let fs = (q4 as f32) * 0.25;
1555 let glyph = if crate::text_rich::is_emoji_char(ch) {
1556 synthesize_color_emoji_glyph(ch, fs)
1557 } else {
1558 let (font, gid, faux_bold, faux_italic) = select_styled_font_and_glyph(ch, spec)?;
1559 let mut g = rasterize_glyph_outline(font.face(), gid, fs);
1560 if faux_bold {
1561 apply_faux_bold(&mut g);
1562 }
1563 if faux_italic {
1564 apply_faux_italic(&mut g);
1565 }
1566 g
1567 };
1568 let entry = Arc::new(glyph);
1569 if let Ok(mut w) = cache.write() {
1570 if w.len() >= MAX_GLYPH_CACHE_ENTRIES {
1571 w.clear();
1572 }
1573 w.insert(key, Arc::clone(&entry));
1574 }
1575 Some(entry)
1576}
1577
1578pub fn get_cached_glyph_q4(ch: char, font_size_q4: u16) -> Option<Arc<CachedGlyph>> {
1581 let q4 = font_size_q4.clamp(32, 1020);
1582 let slot_idx =
1583 (((ch as usize).wrapping_mul(2654435761)) ^ (q4 as usize)) & (TLS_SLOT_COUNT - 1);
1584 if let Some(hit) = TLS_GLYPHS.with(|tls| {
1585 let borrow = tls.borrow();
1586 match &borrow[slot_idx] {
1587 Some((c, fs, g)) if *c == ch && *fs == q4 => Some(Arc::clone(g)),
1588 _ => None,
1589 }
1590 }) {
1591 return Some(hit);
1592 }
1593
1594 let (font, gid) = select_font_and_glyph(ch)?;
1595 let cache = GLYPH_CACHE.get_or_init(|| RwLock::new(HashMap::new()));
1596 if let Ok(read_guard) = cache.read() {
1597 if let Some(g) = read_guard.get(&(ch, q4)) {
1598 let cloned = Arc::clone(g);
1599 TLS_GLYPHS.with(|tls| {
1600 tls.borrow_mut()[slot_idx] = Some((ch, q4, Arc::clone(&cloned)));
1601 });
1602 return Some(cloned);
1603 }
1604 }
1605 if let Ok(mut write_guard) = cache.write() {
1606 if let Some(g) = write_guard.get(&(ch, q4)) {
1607 let cloned = Arc::clone(g);
1608 TLS_GLYPHS.with(|tls| {
1609 tls.borrow_mut()[slot_idx] = Some((ch, q4, Arc::clone(&cloned)));
1610 });
1611 return Some(cloned);
1612 }
1613 if write_guard.len() >= MAX_GLYPH_CACHE_ENTRIES {
1614 write_guard.clear();
1615 }
1616 let entry = Arc::new(rasterize_glyph_outline(&font.face, gid, (q4 as f32) * 0.25));
1617 write_guard.insert((ch, q4), Arc::clone(&entry));
1618 TLS_GLYPHS.with(|tls| {
1619 tls.borrow_mut()[slot_idx] = Some((ch, q4, Arc::clone(&entry)));
1620 });
1621 return Some(entry);
1622 }
1623 None
1624}
1625
1626#[allow(dead_code)]
1628#[inline]
1629pub fn get_cached_glyph(ch: char, font_size: u8) -> Option<Arc<CachedGlyph>> {
1630 get_cached_glyph_q4(ch, (font_size.max(8) as u16) << 2)
1631}