1#![allow(dead_code)]
5
6extern crate alloc;
7use alloc::collections::BTreeMap;
8use alloc::string::String;
9use alloc::vec::Vec;
10
11struct HeapBuf<T>(Vec<T>);
33
34impl<T> Default for HeapBuf<T> {
35 fn default() -> Self {
36 Self(Vec::new())
37 }
38}
39
40impl<T> alloc_no_stdlib::SliceWrapper<T> for HeapBuf<T> {
41 fn slice(&self) -> &[T] {
42 &self.0
43 }
44}
45
46impl<T> alloc_no_stdlib::SliceWrapperMut<T> for HeapBuf<T> {
47 fn slice_mut(&mut self) -> &mut [T] {
48 &mut self.0
49 }
50}
51
52struct HeapAllocator;
53
54impl<T: Clone + Default> alloc_no_stdlib::Allocator<T> for HeapAllocator {
55 type AllocatedMemory = HeapBuf<T>;
56
57 fn alloc_cell(&mut self, len: usize) -> HeapBuf<T> {
59 HeapBuf(alloc::vec![T::default(); len])
60 }
61
62 fn free_cell(&mut self, _data: HeapBuf<T>) {}
64}
65
66pub fn decompress_brotli(compressed: &[u8], decompressed_size: usize) -> Option<Vec<u8>> {
72 let mut s = brotli_decompressor::BrotliState::new(
73 HeapAllocator,
74 HeapAllocator,
75 HeapAllocator,
76 );
77
78 let mut out_vec = alloc::vec![0u8; decompressed_size.max(16)];
82
83 let mut available_in: usize = compressed.len();
84 let mut input_offset: usize = 0;
85 let mut available_out: usize = out_vec.len();
86 let mut output_offset: usize = 0;
87 let mut total_out: usize = 0;
88
89 let result = brotli_decompressor::BrotliDecompressStream(
90 &mut available_in,
91 &mut input_offset,
92 compressed,
93 &mut available_out,
94 &mut output_offset,
95 &mut out_vec,
96 &mut total_out,
97 &mut s,
98 );
99
100 if matches!(result, brotli_decompressor::BrotliResult::ResultSuccess) {
101 out_vec.truncate(total_out);
102 Some(out_vec)
103 } else {
104 crate::warn!(
105 "[FONT][BR] Brotli 展開に失敗 result={:?} in={} total_out={} in_left={}",
106 result,
107 compressed.len(),
108 total_out,
109 available_in
110 );
111 None
112 }
113}
114
115static WOFF2_KNOWN_TAGS: [&[u8; 4]; 63] = [
116 b"cmap", b"head", b"hhea", b"hmtx", b"maxp", b"name", b"OS/2", b"post",
117 b"cvt ", b"fpgm", b"glyf", b"loca", b"prep", b"CFF ", b"VORG", b"EBDT",
118 b"EBLC", b"gasp", b"hdmx", b"kern", b"LTSH", b"PCLT", b"VDMX", b"vhea",
119 b"vmtx", b"BASE", b"GDEF", b"GPOS", b"GSUB", b"JSTF", b"DSIG", b"MATH",
120 b"CBDT", b"CBLC", b"COLR", b"CPAL", b"SVG ", b"sbix", b"acnt", b"avar",
121 b"bdat", b"bloc", b"bsln", b"cvar", b"fdsc", b"fmtx", b"fvar", b"gvar",
122 b"hsty", b"just", b"lcar", b"mort", b"morx", b"opbd", b"prop", b"trak",
123 b"Zapf", b"Silf", b"Gloc", b"Glat", b"Feat", b"Sill", b"SVG ",
124];
125
126fn read_woff2_uint16(data: &[u8], offset: &mut usize) -> Option<u16> {
127 if *offset + 2 > data.len() {
128 return None;
129 }
130 let val = u16::from_be_bytes([data[*offset], data[*offset + 1]]);
131 *offset += 2;
132 Some(val)
133}
134
135fn read_woff2_uint32(data: &[u8], offset: &mut usize) -> Option<u32> {
136 if *offset + 4 > data.len() {
137 return None;
138 }
139 let val = u32::from_be_bytes([
140 data[*offset],
141 data[*offset + 1],
142 data[*offset + 2],
143 data[*offset + 3],
144 ]);
145 *offset += 4;
146 Some(val)
147}
148
149fn read_woff2_base128(data: &[u8], offset: &mut usize) -> Option<u32> {
150 let mut accum: u32 = 0;
151 for _ in 0..5 {
152 if *offset >= data.len() {
153 return None;
154 }
155 let code = data[*offset];
156 *offset += 1;
157 if accum & 0xFE00_0000 != 0 {
158 return None;
159 }
160 accum = (accum << 7) | ((code & 0x7F) as u32);
161 if (code & 0x80) == 0 {
162 return Some(accum);
163 }
164 }
165 None
166}
167
168struct Woff2Table {
169 tag: [u8; 4],
170 orig_length: u32,
171 transform_length: Option<u32>,
172 flags: u8,
173}
174
175pub fn decompress_woff2(bytes: &[u8]) -> Option<Vec<u8>> {
177 crate::kernel::window_mgr::kill_checkpoint();
178 if bytes.len() < 48 || &bytes[0..4] != b"wOF2" {
179 return None;
180 }
181 let mut offset = 4;
182 let flavor = read_woff2_uint32(bytes, &mut offset)?;
183 let _length = read_woff2_uint32(bytes, &mut offset)?;
184 let num_tables = read_woff2_uint16(bytes, &mut offset)? as usize;
185 let _reserved = read_woff2_uint16(bytes, &mut offset)?;
186 let total_sfnt_size = read_woff2_uint32(bytes, &mut offset)? as usize;
187 let total_compressed_size = read_woff2_uint32(bytes, &mut offset)? as usize;
188 let _major_version = read_woff2_uint16(bytes, &mut offset)?;
189 let _minor_version = read_woff2_uint16(bytes, &mut offset)?;
190 let _meta_offset = read_woff2_uint32(bytes, &mut offset)?;
191 let _meta_length = read_woff2_uint32(bytes, &mut offset)?;
192 let _meta_orig_length = read_woff2_uint32(bytes, &mut offset)?;
193 let _priv_offset = read_woff2_uint32(bytes, &mut offset)?;
194 let _priv_length = read_woff2_uint32(bytes, &mut offset)?;
195
196 let mut tables = Vec::with_capacity(num_tables);
197 let mut total_uncompressed_stream_len: usize = 0;
198
199 for _ in 0..num_tables {
200 if offset >= bytes.len() {
201 return None;
202 }
203 let flags = bytes[offset];
204 offset += 1;
205 let tag_idx = flags & 0x3F;
206
207 let tag = if tag_idx == 63 {
208 if offset + 4 > bytes.len() {
209 return None;
210 }
211 let t = [bytes[offset], bytes[offset + 1], bytes[offset + 2], bytes[offset + 3]];
212 offset += 4;
213 t
214 } else if (tag_idx as usize) < WOFF2_KNOWN_TAGS.len() {
215 *WOFF2_KNOWN_TAGS[tag_idx as usize]
216 } else {
217 return None;
218 };
219
220 let orig_length = read_woff2_base128(bytes, &mut offset)?;
221 let transform_version = (flags >> 6) & 0x03;
222
223 let is_glyf_or_loca = &tag == b"glyf" || &tag == b"loca";
241 let transformed = if is_glyf_or_loca {
242 transform_version == 0
243 } else {
244 transform_version != 0
245 };
246
247 let transform_length = if transformed {
248 let tl = read_woff2_base128(bytes, &mut offset)?;
249 total_uncompressed_stream_len += tl as usize;
250 Some(tl)
251 } else {
252 total_uncompressed_stream_len += orig_length as usize;
253 None
254 };
255
256 tables.push(Woff2Table {
257 tag,
258 orig_length,
259 transform_length,
260 flags,
261 });
262 }
263
264 if offset + total_compressed_size > bytes.len() {
265 return None;
266 }
267
268 let compressed_data = &bytes[offset..offset + total_compressed_size];
269 crate::warn!(
272 "[WOFF2] decompress compressed={} expected_uncompressed={}",
273 compressed_data.len(),
274 total_uncompressed_stream_len
275 );
276 let decompressed_stream = decompress_brotli(compressed_data, total_uncompressed_stream_len)?;
277 crate::kernel::window_mgr::kill_checkpoint();
278
279 let mut sfnt = Vec::with_capacity(total_sfnt_size.max(12 + num_tables * 16));
281
282 sfnt.extend_from_slice(&flavor.to_be_bytes());
284 sfnt.extend_from_slice(&(num_tables as u16).to_be_bytes());
285
286 let mut max_p2 = 1u16;
287 while max_p2 * 2 <= (num_tables as u16) {
288 max_p2 *= 2;
289 }
290 let search_range = max_p2 * 16;
291 let entry_selector = (16 - max_p2.leading_zeros() - 1) as u16;
292 let range_shift = (num_tables as u16) * 16 - search_range;
293
294 sfnt.extend_from_slice(&search_range.to_be_bytes());
295 sfnt.extend_from_slice(&entry_selector.to_be_bytes());
296 sfnt.extend_from_slice(&range_shift.to_be_bytes());
297
298 let table_dir_offset = 12;
300 let data_start_offset = table_dir_offset + num_tables * 16;
301
302 let mut sorted_indices: Vec<usize> = (0..num_tables).collect();
303 sorted_indices.sort_by_key(|&idx| tables[idx].tag);
304
305 sfnt.resize(data_start_offset, 0);
307
308 let mut stream_offset = 0usize;
319 let mut table_ranges: Vec<(usize, usize)> = Vec::with_capacity(num_tables);
320 for table in tables.iter().take(num_tables) {
321 let len = table.orig_length as usize;
322 let read_len = table.transform_length.map(|l| l as usize).unwrap_or(len);
323 if stream_offset + read_len > decompressed_stream.len() {
324 crate::warn!(
325 "[FONT][WOFF2] 展開ストリームが短い tag={:?} 必要={} 残り={}",
326 core::str::from_utf8(&table.tag).unwrap_or("????"),
327 read_len,
328 decompressed_stream.len().saturating_sub(stream_offset)
329 );
330 return None;
331 }
332 table_ranges.push((stream_offset, stream_offset + read_len));
333 stream_offset += read_len;
334 }
335
336 let mut rebuilt: alloc::collections::BTreeMap<usize, Vec<u8>> =
345 alloc::collections::BTreeMap::new();
346 {
347 let glyf_idx = tables.iter().take(num_tables).position(|t| {
348 &t.tag == b"glyf" && t.transform_length.is_some()
349 });
350 if let Some(gi) = glyf_idx {
351 let (rs, re) = table_ranges[gi];
352 let raw = decompressed_stream.get(rs..re)?;
353 match crate::kernel::woff2_glyf::reconstruct_glyf(raw) {
354 Some((glyf_data, loca_data, _fmt)) => {
355 crate::warn!(
356 "[FONT][WOFF2] glyf 変換を復元 {} -> {} バイト(loca {} バイト)",
357 raw.len(),
358 glyf_data.len(),
359 loca_data.len()
360 );
361 rebuilt.insert(gi, glyf_data);
362 if let Some(li) = tables
363 .iter()
364 .take(num_tables)
365 .position(|t| &t.tag == b"loca")
366 {
367 rebuilt.insert(li, loca_data);
368 }
369 }
370 None => {
371 crate::warn!(
372 "[FONT][WOFF2] glyf 変換の復元に失敗({} バイト)",
373 raw.len()
374 );
375 return None;
376 }
377 }
378 }
379 }
380
381 let mut current_data_offset = data_start_offset;
382
383 for &idx in &sorted_indices {
384 let table = &tables[idx];
385 let len = table.orig_length as usize;
386 let (rs, re) = table_ranges[idx];
387 let table_raw: &[u8] = match rebuilt.get(&idx) {
389 Some(v) => v.as_slice(),
390 None => &decompressed_stream[rs..re],
391 };
392 let len = if rebuilt.contains_key(&idx) {
393 table_raw.len()
394 } else {
395 len
396 };
397
398 let mut sum: u32 = 0;
400 let mut i = 0;
401 while i < table_raw.len() {
402 let b0 = table_raw[i] as u32;
403 let b1 = table_raw.get(i + 1).copied().unwrap_or(0) as u32;
404 let b2 = table_raw.get(i + 2).copied().unwrap_or(0) as u32;
405 let b3 = table_raw.get(i + 3).copied().unwrap_or(0) as u32;
406 sum = sum.wrapping_add((b0 << 24) | (b1 << 16) | (b2 << 8) | b3);
407 i += 4;
408 }
409
410 let dir_entry_pos = table_dir_offset + sorted_indices.iter().position(|&x| x == idx)? * 16;
411 sfnt[dir_entry_pos..dir_entry_pos + 4].copy_from_slice(&table.tag);
412 sfnt[dir_entry_pos + 4..dir_entry_pos + 8].copy_from_slice(&sum.to_be_bytes());
413 sfnt[dir_entry_pos + 8..dir_entry_pos + 12].copy_from_slice(&(current_data_offset as u32).to_be_bytes());
414 sfnt[dir_entry_pos + 12..dir_entry_pos + 16].copy_from_slice(&(len as u32).to_be_bytes());
415
416 sfnt.extend_from_slice(table_raw);
417 let padding = (4 - (table_raw.len() % 4)) % 4;
418 sfnt.extend(core::iter::repeat_n(0u8, padding));
419 current_data_offset += table_raw.len() + padding;
420 }
421
422 Some(sfnt)
423}
424
425use spin::Mutex;
426use ttf_parser::{Face, OutlineBuilder};
427
428fn f32_floor(x: f32) -> i32 {
429 if x >= 0.0 {
430 x as i32
431 } else {
432 (x - 1.0) as i32
433 }
434}
435
436fn f32_ceil(x: f32) -> i32 {
437 if x >= 0.0 {
438 (x + 1.0) as i32
439 } else {
440 x as i32
441 }
442}
443
444#[derive(Debug, Clone, Copy, PartialEq)]
445struct Point {
446 x: f32,
447 y: f32,
448}
449
450#[derive(Debug, Clone)]
451enum Segment {
452 Line(Point, Point),
453}
454
455struct GlyphOutlineBuilder {
457 segments: Vec<Segment>,
458 current: Point,
459 start: Point,
460 scale: f32,
461}
462
463impl GlyphOutlineBuilder {
464 fn new(scale: f32) -> Self {
465 Self {
466 segments: Vec::new(),
467 current: Point { x: 0.0, y: 0.0 },
468 start: Point { x: 0.0, y: 0.0 },
469 scale,
470 }
471 }
472
473 fn flatten_quad(&mut self, p0: Point, p1: Point, p2: Point) {
475 let steps = 6; let mut prev = p0;
477 for i in 1..=steps {
478 let t = (i as f32) / (steps as f32);
479 let mt = 1.0 - t;
480 let x = mt * mt * p0.x + 2.0 * mt * t * p1.x + t * t * p2.x;
482 let y = mt * mt * p0.y + 2.0 * mt * t * p1.y + t * t * p2.y;
483 let current = Point { x, y };
484 self.segments.push(Segment::Line(prev, current));
485 prev = current;
486 }
487 }
488}
489
490impl OutlineBuilder for GlyphOutlineBuilder {
491 fn move_to(&mut self, x: f32, y: f32) {
492 let p = Point {
493 x: x * self.scale,
494 y: y * self.scale,
495 };
496 self.current = p;
497 self.start = p;
498 }
499
500 fn line_to(&mut self, x: f32, y: f32) {
501 let p = Point {
502 x: x * self.scale,
503 y: y * self.scale,
504 };
505 self.segments.push(Segment::Line(self.current, p));
506 self.current = p;
507 }
508
509 fn quad_to(&mut self, x1: f32, y1: f32, x: f32, y: f32) {
510 let p1 = Point {
511 x: x1 * self.scale,
512 y: y1 * self.scale,
513 };
514 let p2 = Point {
515 x: x * self.scale,
516 y: y * self.scale,
517 };
518 self.flatten_quad(self.current, p1, p2);
519 self.current = p2;
520 }
521
522 fn curve_to(&mut self, _x1: f32, _y1: f32, _x2: f32, _y2: f32, x: f32, y: f32) {
523 let p2 = Point {
526 x: x * self.scale,
527 y: y * self.scale,
528 };
529 self.segments.push(Segment::Line(self.current, p2));
530 self.current = p2;
531 }
532
533 fn close(&mut self) {
534 if self.current != self.start {
535 self.segments.push(Segment::Line(self.current, self.start));
536 }
537 }
538}
539
540#[derive(Clone)]
542pub struct CachedGlyph {
543 pub width: u32,
544 pub height: u32,
545 pub x_offset: i32,
546 pub y_offset: i32,
547 pub advance: u32,
548 pub data: Vec<u8>, }
550
551#[derive(Clone)]
553pub struct CachedColorGlyph {
554 pub width: u32,
555 pub height: u32,
556 pub x_offset: i32,
557 pub y_offset: i32,
558 pub advance: u32,
559 pub data: Vec<u32>, }
561
562pub struct VectorFont {
564 face: Face<'static>,
565 primary_subsets: Vec<Face<'static>>,
568 fallbacks: Vec<Face<'static>>,
570 cache: BTreeMap<(char, u32), CachedGlyph>, color_cache: BTreeMap<(char, u32, u32, u32), CachedColorGlyph>, advance_cache: BTreeMap<(char, u32), u32>, }
574
575fn fallback_glyph_char(c: char) -> Option<char> {
578 let sub = match c {
579 '␣' => '_', '⇥' => '>', '↵' => '<', '⇠' => '<', '–' | '—' | '―' | '‐' | '‑' | '−' => '-',
586 '\u{2018}' | '\u{2019}' | '‚' | '‛' | '`' => '\'',
588 '\u{201C}' | '\u{201D}' | '„' | '‟' => '"',
589 '•' | '◦' | '‣' | '·' | '∙' => '*',
591 '×' => 'x',
593 '÷' => '/',
594 '…' => '.',
596 '\u{00A0}' | '\u{202F}' | '\u{2009}' | '\u{200A}' => ' ',
598 '\u{f060}' => '\u{2190}', '\u{f061}' => '\u{2192}', '\u{f062}' => '\u{2191}', '\u{f063}' => '\u{2193}', '\u{f053}' => '\u{2039}', '\u{f054}' => '\u{203A}', '\u{f077}' => '^', '\u{f078}' => 'v', '\u{f104}' => '\u{2039}', '\u{f105}' => '\u{203A}', '\u{f106}' => '^', '\u{f107}' => 'v', '\u{f00c}' => '\u{2713}', '\u{f00d}' => '\u{2715}', '\u{f05a}' => 'i', '\u{f35d}' => '↗', '\u{f10d}' => '"', '\u{f10e}' => '"', _ => return None,
648 };
649 Some(sub)
650}
651
652impl VectorFont {
653 pub fn new(font_bytes: &'static [u8]) -> Result<Self, ttf_parser::FaceParsingError> {
654 let face = Face::parse(font_bytes, 0)?;
655 Ok(Self {
656 face,
657 primary_subsets: Vec::new(),
658 fallbacks: Vec::new(),
659 cache: BTreeMap::new(),
660 color_cache: BTreeMap::new(),
661 advance_cache: BTreeMap::new(),
662 })
663 }
664
665 pub fn new_with_fallbacks(
669 font_bytes: &'static [u8],
670 fallback_bytes: &[&'static [u8]],
671 ) -> Result<Self, ttf_parser::FaceParsingError> {
672 crate::kernel::window_mgr::kill_checkpoint();
673 let face = Face::parse(font_bytes, 0)?;
674 let mut fallbacks = Vec::new();
675 for fb in fallback_bytes {
676 crate::kernel::window_mgr::kill_checkpoint();
677 if let Ok(f) = Face::parse(fb, 0) {
678 fallbacks.push(f);
679 }
680 }
681 Ok(Self {
682 face,
683 primary_subsets: Vec::new(),
684 fallbacks,
685 cache: BTreeMap::new(),
686 color_cache: BTreeMap::new(),
687 advance_cache: BTreeMap::new(),
688 })
689 }
690
691 pub fn add_primary_fallback(&mut self, font_bytes: &'static [u8]) -> Result<(), ttf_parser::FaceParsingError> {
693 let f = Face::parse(font_bytes, 0)?;
694 self.primary_subsets.push(f);
695 self.fallbacks.insert(0, Face::parse(font_bytes, 0)?);
696 self.cache.clear();
697 self.color_cache.clear();
698 self.advance_cache.clear();
699 Ok(())
700 }
701
702 pub fn set_primary(&mut self, font_bytes: &'static [u8]) -> Result<(), ttf_parser::FaceParsingError> {
708 let new_face = Face::parse(font_bytes, 0)?;
709 let old_primary = core::mem::replace(&mut self.face, new_face);
710 self.fallbacks.insert(0, old_primary);
711 self.cache.clear();
712 self.color_cache.clear();
713 self.advance_cache.clear();
714 Ok(())
715 }
716
717 pub fn primary_has_glyph(&self, c: char) -> bool {
728 self.face.glyph_index(c).is_some()
729 || self.primary_subsets.iter().any(|f| f.glyph_index(c).is_some())
730 }
731
732 pub fn has_glyph(&self, c: char) -> bool {
733 if ('\u{e000}'..='\u{f8ff}').contains(&c) {
738 return self.face.glyph_index(c).is_some();
739 }
740 if self.face.glyph_index(c).is_some() {
741 return true;
742 }
743 self.fallbacks.iter().any(|f| f.glyph_index(c).is_some())
744 }
745
746 pub fn get_glyph(&mut self, c: char, size_px: u32) -> Option<&CachedGlyph> {
747 let key = (c, size_px);
748 if self.cache.contains_key(&key) {
749 return self.cache.get(&key);
750 }
751
752 if self.cache.len() >= 8000 {
753 crate::info!(
754 "[vector_font] Cache limit (8000) reached. Clearing glyph cache to free memory."
755 );
756 self.cache.clear();
757 }
758
759 let (face_idx, glyph_id) = {
762 let find = |ch: char| -> Option<(usize, ttf_parser::GlyphId)> {
763 if let Some(id) = self.face.glyph_index(ch) {
764 return Some((0, id));
765 }
766 if ('\u{e000}'..='\u{f8ff}').contains(&ch) {
779 return None;
780 }
781 for (i, f) in self.fallbacks.iter().enumerate() {
782 if let Some(id) = f.glyph_index(ch) {
783 return Some((i + 1, id));
784 }
785 }
786 None
787 };
788 match find(c) {
789 Some(x) => x,
790 None => {
791 fallback_glyph_char(c).and_then(find)?
793 }
794 }
795 };
796 let face: &Face = if face_idx == 0 {
797 &self.face
798 } else {
799 &self.fallbacks[face_idx - 1]
800 };
801
802 let units_per_em = face.units_per_em() as f32;
803 let scale = (size_px as f32) / units_per_em;
804
805 let advance = crate::kernel::font_select::scaled_advance(
808 face.glyph_hor_advance(glyph_id)?,
809 face.units_per_em(),
810 size_px,
811 );
812
813 let mut builder = GlyphOutlineBuilder::new(scale);
816 face.outline_glyph(glyph_id, &mut builder);
817
818 if builder.segments.is_empty() {
821 let empty_glyph = CachedGlyph {
822 width: 0,
823 height: 0,
824 x_offset: 0,
825 y_offset: 0,
826 advance,
827 data: Vec::new(),
828 };
829 self.cache.insert(key, empty_glyph);
830 return self.cache.get(&key);
831 }
832
833 let bounding_box = face.glyph_bounding_box(glyph_id)?;
835
836 let scale_y = -scale;
838
839 let mut segments = builder.segments;
841 for seg in &mut segments {
842 match seg {
843 Segment::Line(p1, p2) => {
844 p1.y = -p1.y;
845 p2.y = -p2.y;
846 }
847 }
848 }
849
850 let bx0 = bounding_box.x_min as f32 * scale;
852 let by0 = bounding_box.y_max as f32 * scale_y; let bx1 = bounding_box.x_max as f32 * scale;
854 let by1 = bounding_box.y_min as f32 * scale_y; let gx0 = f32_floor(bx0) - 1;
857 let gy0 = f32_floor(by0) - 1;
858 let gx1 = f32_ceil(bx1) + 1;
859 let gy1 = f32_ceil(by1) + 1;
860
861 let width = (gx1 - gx0).max(1) as u32;
862 let height = (gy1 - gy0).max(1) as u32;
863 let x_offset = gx0;
864 let y_offset = gy0;
865
866 if width > 500 || height > 500 || width == 0 || height == 0 {
867 crate::warn!(
868 "[NET][DIAG] glyph c={:?} units_per_em={} scale={} bbox=({},{},{},{}) w={} h={} face_idx={}",
869 c,
870 units_per_em,
871 scale,
872 bounding_box.x_min,
873 bounding_box.y_min,
874 bounding_box.x_max,
875 bounding_box.y_max,
876 width,
877 height,
878 face_idx
879 );
880 }
881
882 let mut data = alloc::vec![0u8; (width * height) as usize];
888 let mut coverage = alloc::vec![0u8; width as usize];
889 let mut xs: alloc::vec::Vec<(f32, i8)> = alloc::vec::Vec::new();
890 let mut spans: alloc::vec::Vec<(f32, f32)> = alloc::vec::Vec::new();
891
892 for py in 0..height {
893 let screen_y = (gy0 + py as i32) as f32;
894 for c in coverage.iter_mut() {
895 *c = 0;
896 }
897
898 for sy in 0..4 {
900 let sub_y = screen_y + (sy as f32 + 0.5) / 4.0;
901
902 xs.clear();
904 for seg in &segments {
905 match seg {
906 Segment::Line(p1, p2) => {
907 let y_min = p1.y.min(p2.y);
908 let y_max = p1.y.max(p2.y);
909 if sub_y >= y_min && sub_y < y_max && p1.y != p2.y {
910 let t = (sub_y - p1.y) / (p2.y - p1.y);
911 let dir: i8 = if p2.y > p1.y { 1 } else { -1 };
912 xs.push((p1.x + t * (p2.x - p1.x), dir));
913 }
914 }
915 }
916 }
917 if xs.is_empty() {
918 continue;
919 }
920 crate::kernel::glyph_fill::nonzero_spans(&mut xs, &mut spans);
922
923 for &(span_start, span_end) in spans.iter() {
925 let px_lo = (f32_floor(span_start) - gx0 - 1).max(0) as u32;
929 let px_hi = ((f32_ceil(span_end) - gx0 + 1).max(0) as u32).min(width);
930 for px in px_lo..px_hi {
931 let screen_x = (gx0 + px as i32) as f32;
932 for sx in 0..4 {
933 let sub_x = screen_x + (sx as f32 + 0.5) / 4.0;
934 if sub_x >= span_start && sub_x < span_end {
935 coverage[px as usize] += 1;
936 }
937 }
938 }
939 }
940 }
941
942 for px in 0..width {
943 let alpha = ((coverage[px as usize] as u32 * 255) / 16).min(255) as u8;
944 data[(py * width + px) as usize] = alpha;
945 }
946 }
947
948 let cached = CachedGlyph {
949 width,
950 height,
951 x_offset,
952 y_offset,
953 advance,
954 data,
955 };
956
957 self.cache.insert(key, cached);
958 self.cache.get(&key)
959 }
960
961 pub fn get_color_glyph(
967 &mut self,
968 c: char,
969 size_px: u32,
970 fg_color: u32,
971 bg_color: u32,
972 ) -> Option<&CachedColorGlyph> {
973 let key = (c, size_px, fg_color, bg_color);
974 if self.color_cache.contains_key(&key) {
975 return self.color_cache.get(&key);
976 }
977
978 if self.color_cache.len() >= 16000 {
979 self.color_cache.clear();
980 }
981
982 let glyph = self.get_glyph(c, size_px)?.clone();
983
984 let mut color_data = Vec::with_capacity(glyph.data.len());
985 let fg_r = (fg_color >> 16) & 0xFF;
986 let fg_g = (fg_color >> 8) & 0xFF;
987 let fg_b = fg_color & 0xFF;
988 let bg_r = (bg_color >> 16) & 0xFF;
989 let bg_g = (bg_color >> 8) & 0xFF;
990 let bg_b = bg_color & 0xFF;
991
992 let from_framebuffer = bg_color == BG_FROM_FRAMEBUFFER;
993 for &alpha in &glyph.data {
994 if alpha == 0 {
995 color_data.push(0x00000000); } else if from_framebuffer && alpha != 255 {
997 color_data.push(((alpha as u32) << 24) | (fg_color & 0x00FF_FFFF));
1000 } else if alpha == 255 {
1001 color_data.push(fg_color | 0xFF000000); } else {
1003 let eff_alpha = crate::os_lib::web_engine::font_gamma::correct_glyph_coverage(
1004 alpha,
1005 fg_color,
1006 bg_color,
1007 );
1008 let a = eff_alpha as u32;
1009 let inv_a = 255 - a;
1010 let r = crate::kernel::draw::div_255_fast(fg_r * a + bg_r * inv_a);
1011 let g = crate::kernel::draw::div_255_fast(fg_g * a + bg_g * inv_a);
1012 let b = crate::kernel::draw::div_255_fast(fg_b * a + bg_b * inv_a);
1013 color_data.push(0xFF000000 | (r << 16) | (g << 8) | b);
1014 }
1015 }
1016
1017 let cached = CachedColorGlyph {
1018 width: glyph.width,
1019 height: glyph.height,
1020 x_offset: glyph.x_offset,
1021 y_offset: glyph.y_offset,
1022 advance: glyph.advance,
1023 data: color_data,
1024 };
1025
1026 self.color_cache.insert(key, cached);
1027 self.color_cache.get(&key)
1028 }
1029
1030 pub fn get_glyph_advance(&mut self, c: char, size_px: u32) -> u32 {
1033 let key = (c, size_px);
1034 if let Some(glyph) = self.cache.get(&key) {
1035 return glyph.advance;
1036 }
1037 if let Some(&adv) = self.advance_cache.get(&key) {
1038 return adv;
1039 }
1040
1041 let (face_idx, glyph_id) = {
1042 let find = |ch: char| -> Option<(usize, ttf_parser::GlyphId)> {
1043 if let Some(id) = self.face.glyph_index(ch) {
1044 return Some((0, id));
1045 }
1046 if ('\u{e000}'..='\u{f8ff}').contains(&ch) {
1059 return None;
1060 }
1061 for (i, f) in self.fallbacks.iter().enumerate() {
1062 if let Some(id) = f.glyph_index(ch) {
1063 return Some((i + 1, id));
1064 }
1065 }
1066 None
1067 };
1068 match find(c) {
1069 Some(x) => x,
1070 None => {
1071 if let Some(alt) = fallback_glyph_char(c).and_then(find) {
1072 alt
1073 } else {
1074 let default_adv = size_px / 2;
1075 self.advance_cache.insert(key, default_adv);
1076 return default_adv;
1077 }
1078 }
1079 }
1080 };
1081
1082 let face: &Face = if face_idx == 0 {
1083 &self.face
1084 } else {
1085 &self.fallbacks[face_idx - 1]
1086 };
1087 let advance = if let Some(adv) = face.glyph_hor_advance(glyph_id) {
1088 crate::kernel::font_select::scaled_advance(adv, face.units_per_em(), size_px)
1089 } else {
1090 size_px / 2
1091 };
1092
1093 if self.advance_cache.len() >= 10000 {
1094 self.advance_cache.clear();
1095 }
1096 self.advance_cache.insert(key, advance);
1097 advance
1098 }
1099
1100 pub fn get_string_width(&mut self, s: &str, size_px: u32) -> u32 {
1102 self.get_string_width_ls(s, size_px, 0)
1103 }
1104
1105 pub fn get_string_width_ls(&mut self, s: &str, size_px: u32, ls: i32) -> u32 {
1107 self.get_string_width_ls_ws(s, size_px, ls, 0)
1108 }
1109
1110 pub fn get_string_width_ls_ws(&mut self, s: &str, size_px: u32, ls: i32, ws: i32) -> u32 {
1112 self.string_width_sum(s, size_px, ls, ws).max(0) as u32
1113 }
1114
1115 pub fn string_width_sum(&mut self, s: &str, size_px: u32, ls: i32, ws: i32) -> i32 {
1120 let mut width = 0i32;
1121 for c in s.chars() {
1122 width += self.get_glyph_advance(c, size_px) as i32 + ls + if c == ' ' { ws } else { 0 };
1123 }
1124 width
1125 }
1126
1127 pub fn push_wrap_advances(&mut self, s: &str, size_px: u32, ls: i32, ws: i32, out: &mut Vec<i32>) {
1131 for c in s.chars() {
1132 let a = if c == '\n' || c == '\u{00AD}' {
1133 0
1134 } else {
1135 let extra = ls + if c == ' ' { ws } else { 0 };
1136 (self.get_glyph_advance(c, size_px) as i32 + extra).max(0)
1137 };
1138 out.push(a);
1139 }
1140 }
1141
1142 pub fn get_string_wrapped_size(&mut self, s: &str, size_px: u32, max_width: u32) -> (u32, u32) {
1150 self.get_string_wrapped_size_ls_ws(s, size_px, max_width, 0, 0)
1151 }
1152
1153 pub fn get_string_wrapped_size_ls(
1155 &mut self,
1156 s: &str,
1157 size_px: u32,
1158 max_width: u32,
1159 ls: i32,
1160 ) -> (u32, u32) {
1161 self.get_string_wrapped_size_ls_ws(s, size_px, max_width, ls, 0)
1162 }
1163
1164 pub fn get_string_wrapped_size_ls_ws(
1165 &mut self,
1166 s: &str,
1167 size_px: u32,
1168 max_width: u32,
1169 ls: i32,
1170 ws: i32,
1171 ) -> (u32, u32) {
1172 self.get_string_wrapped_size_ext(s, size_px, max_width, ls, ws, false, false, false)
1173 }
1174
1175 pub fn get_string_wrapped_size_ext(
1177 &mut self,
1178 s: &str,
1179 size_px: u32,
1180 max_width: u32,
1181 ls: i32,
1182 ws: i32,
1183 word_break_all: bool,
1184 overflow_wrap: bool,
1185 _white_space_pre_wrap: bool,
1186 ) -> (u32, u32) {
1187 let chars: alloc::vec::Vec<char> = s.chars().collect();
1188 let mut advances: alloc::vec::Vec<i32> = alloc::vec::Vec::with_capacity(chars.len());
1189 self.push_wrap_advances(s, size_px, ls, ws, &mut advances);
1190 wrapped_size_from_advances(&chars, &advances, size_px, max_width, word_break_all, overflow_wrap)
1191 }
1192}
1193
1194pub fn wrapped_size_from_advances(
1197 chars: &[char],
1198 advances: &[i32],
1199 size_px: u32,
1200 max_width: u32,
1201 word_break_all: bool,
1202 overflow_wrap: bool,
1203) -> (u32, u32) {
1204 wrapped_size_from_advances_poll(chars, advances, size_px, max_width, word_break_all, overflow_wrap, || false)
1205}
1206
1207pub fn wrapped_size_from_advances_poll(
1212 chars: &[char],
1213 advances: &[i32],
1214 size_px: u32,
1215 max_width: u32,
1216 word_break_all: bool,
1217 overflow_wrap: bool,
1218 mut poll: impl FnMut() -> bool,
1219) -> (u32, u32) {
1220 let line_height = size_px + 4;
1225 let breaks = crate::os_lib::layout::line_break::break_positions_poll(
1226 chars,
1227 advances,
1228 max_width.min(i32::MAX as u32) as i32,
1229 word_break_all,
1230 overflow_wrap,
1231 |c| !word_break_all && is_line_start_forbidden(c),
1232 |c| !word_break_all && is_line_end_forbidden(c),
1233 &mut poll,
1234 );
1235 let mut max_w = 0u32;
1236 let mut emitted_lines = 0u32;
1237 let mut line_w = 0i32;
1238 let mut line_w_no_trailing = 0i32;
1240 let mut seg_has_content = false;
1241 let mut bi = 0usize;
1242 for (i, &c) in chars.iter().enumerate() {
1243 if i & (crate::os_lib::layout::line_break::BREAK_POLL_EVERY - 1) == 0 && i != 0 && poll() {
1244 break;
1245 }
1246 if c == '\n' {
1247 max_w = max_w.max(line_w_no_trailing.max(0) as u32);
1248 emitted_lines += 1;
1249 line_w = 0;
1250 line_w_no_trailing = 0;
1251 seg_has_content = false;
1252 continue;
1253 }
1254 if bi < breaks.len() && breaks[bi] == i {
1255 bi += 1;
1256 max_w = max_w.max(line_w_no_trailing.max(0) as u32);
1257 emitted_lines += 1;
1258 line_w = 0;
1259 line_w_no_trailing = 0;
1260 }
1261 line_w += advances[i];
1262 if !c.is_whitespace() {
1263 line_w_no_trailing = line_w;
1264 }
1265 seg_has_content = true;
1266 }
1267 max_w = max_w.max(line_w_no_trailing.max(0) as u32);
1268 if seg_has_content {
1269 emitted_lines += 1;
1270 }
1271 (max_w, emitted_lines.max(1) * line_height)
1272}
1273
1274pub static GLOBAL_VECTOR_FONT: Mutex<Option<VectorFont>> = Mutex::new(None);
1276pub static GLOBAL_TERMINAL_FONT: Mutex<Option<VectorFont>> = Mutex::new(None);
1277
1278pub static CUSTOM_FONTS: Mutex<BTreeMap<String, VectorFont>> = Mutex::new(BTreeMap::new());
1295
1296static CUSTOM_FONTS_GEN: core::sync::atomic::AtomicU64 = core::sync::atomic::AtomicU64::new(0);
1302
1303fn looks_like_ttf_or_otf(bytes: &[u8]) -> bool {
1305 if bytes.len() < 4 {
1306 return false;
1307 }
1308 matches!(
1309 &bytes[0..4],
1310 [0x00, 0x01, 0x00, 0x00] | [b'O', b'T', b'T', b'O'] | [b't', b'r', b'u', b'e']
1311 )
1312}
1313
1314fn looks_like_woff2(bytes: &[u8]) -> bool {
1335 bytes.len() >= 4 && &bytes[0..4] == b"wOF2"
1336}
1337
1338pub const BG_FROM_FRAMEBUFFER: u32 = 0x0100_0000;
1352
1353pub fn font_key(family: &str, weight: u16) -> alloc::string::String {
1359 alloc::format!("{}|{}", family.trim().to_lowercase(), weight)
1360}
1361
1362pub fn register_custom_font_weighted(family: &str, weight: u16, bytes: Vec<u8>) -> bool {
1364 register_custom_font_inner(family, weight, bytes)
1365}
1366
1367pub fn register_custom_font(family: &str, bytes: Vec<u8>) -> bool {
1368 register_custom_font_inner(family, 400, bytes)
1369}
1370
1371static REGISTERED_FONTS: spin::Mutex<Vec<(alloc::string::String, usize, u64)>> = spin::Mutex::new(Vec::new());
1377static REGISTERED_FONT_URLS: spin::Mutex<alloc::collections::BTreeSet<alloc::string::String>> =
1379 spin::Mutex::new(alloc::collections::BTreeSet::new());
1380
1381pub fn is_font_url_registered(url: &str) -> bool {
1382 REGISTERED_FONT_URLS.lock().contains(url)
1383}
1384
1385pub fn mark_font_url_registered(url: &str) {
1386 REGISTERED_FONT_URLS.lock().insert(alloc::string::String::from(url));
1387}
1388
1389fn fnv1a64(bytes: &[u8]) -> u64 {
1390 let mut h: u64 = 0xcbf2_9ce4_8422_2325;
1391 for &b in bytes {
1392 h ^= b as u64;
1393 h = h.wrapping_mul(0x0000_0100_0000_01b3);
1394 }
1395 h
1396}
1397
1398fn register_custom_font_inner(family: &str, weight: u16, bytes: Vec<u8>) -> bool {
1399 crate::kernel::window_mgr::kill_checkpoint();
1400 let fingerprint = (font_key(family, weight), bytes.len(), fnv1a64(&bytes));
1401 if REGISTERED_FONTS.lock().contains(&fingerprint) {
1402 return true;
1403 }
1404 crate::warn!(
1421 "[FONT] 登録開始 family={} weight={} bytes={}",
1422 family,
1423 weight,
1424 bytes.len()
1425 );
1426 let fallback_chain: Vec<&'static [u8]> = DEFAULT_FONT_CHAIN
1430 .iter()
1431 .filter_map(|n| font_bytes(n))
1432 .collect();
1433 let mut font_bytes = if looks_like_woff2(&bytes) {
1434 match decompress_woff2(&bytes) {
1435 Some(sfnt) => sfnt,
1436 None => {
1437 crate::warn!(
1438 "[FONT] WOFF2 の展開に失敗 family={} bytes={}",
1439 family,
1440 bytes.len()
1441 );
1442 return false;
1443 }
1444 }
1445 } else if looks_like_ttf_or_otf(&bytes) {
1446 bytes
1447 } else {
1448 crate::warn!(
1449 "[FONT] 未知のフォント形式 family={} bytes={} head={:02x?}",
1450 family,
1451 bytes.len(),
1452 &bytes[..bytes.len().min(4)]
1453 );
1454 return false;
1455 };
1456
1457 font_bytes.shrink_to_fit();
1458 let leaked: &'static [u8] = Vec::leak(font_bytes);
1459 let _pf = crate::os_lib::web_engine::perf::start();
1460 crate::kernel::window_mgr::kill_checkpoint();
1461 crate::warn!("[FONT] 解析開始 family={} bytes={}", family, leaked.len());
1462 let _parsed = VectorFont::new_with_fallbacks(leaked, &fallback_chain);
1472 crate::os_lib::web_engine::perf::add(
1473 crate::os_lib::web_engine::perf::Slot::FontParse,
1474 _pf,
1475 );
1476 match _parsed {
1477 Ok(font) => {
1478 REGISTERED_FONTS.lock().push(fingerprint);
1479 let plain_font = VectorFont::new_with_fallbacks(leaked, &fallback_chain).ok();
1484 {
1485 let mut map = CUSTOM_FONTS.lock();
1486 CUSTOM_FONTS_GEN.fetch_add(1, core::sync::atomic::Ordering::AcqRel);
1487 let wkey = font_key(family, weight);
1488 if let Some(existing) = map.get_mut(&wkey) {
1489 let _ = existing.add_primary_fallback(leaked);
1492 } else {
1493 map.insert(wkey, font);
1494 }
1495 let plain = family.trim().to_lowercase();
1499 match map.entry(plain) {
1500 alloc::collections::btree_map::Entry::Vacant(slot) => {
1501 if let Some(f2) = plain_font {
1502 slot.insert(f2);
1503 }
1504 }
1505 alloc::collections::btree_map::Entry::Occupied(mut occ) => {
1506 let _ = occ.get_mut().add_primary_fallback(leaked);
1507 }
1508 }
1509 }
1510 let probe = |c: char| -> bool {
1534 CUSTOM_FONTS
1535 .lock()
1536 .get(&family.trim().to_lowercase())
1537 .map(|f| f.has_glyph(c))
1538 .unwrap_or(false)
1539 };
1540 crate::warn!(
1541 "[FONT] 登録完了 family={} bytes={} 字形F02D={} 字形F015={}",
1542 family,
1543 leaked.len(),
1544 probe('\u{f02d}'),
1545 probe('\u{f015}')
1546 );
1547 true
1548 }
1549 Err(e) => {
1550 crate::warn!(
1551 "[FONT] フォントのパースに失敗 family={} bytes={} err={:?}",
1552 family,
1553 leaked.len(),
1554 e
1555 );
1556 false
1557 }
1558 }
1559}
1560
1561pub fn has_custom_font_weighted(family: &str, weight: u16) -> bool {
1571 CUSTOM_FONTS.lock().contains_key(&font_key(family, weight))
1572}
1573
1574pub fn has_custom_font(family: &str) -> bool {
1575 CUSTOM_FONTS.lock().contains_key(&family.trim().to_lowercase())
1576}
1577
1578pub const AVAILABLE_FONTS: &[&str] = &[
1586 "Mplus1Code-Regular",
1587 "HackGenConsoleNF-Regular",
1588 "ipam",
1589 "ipag",
1590 "MPLUS2-Regular",
1591 "MPLUS2-Bold",
1592];
1593
1594pub const DEFAULT_FONT_CHAIN: [&str; 3] =
1596 ["Mplus1Code-Regular", "HackGenConsoleNF-Regular", "ipam"];
1597
1598pub fn font_bytes(name: &str) -> Option<&'static [u8]> {
1600 Some(match name {
1601 "Mplus1Code-Regular" => include_bytes!("../../fonts/Mplus1Code/Mplus1Code-Regular.ttf"),
1602 "HackGenConsoleNF-Regular" => {
1603 include_bytes!("../../fonts/HackGen/HackGenConsoleNF-Regular.ttf")
1604 }
1605 "ipam" => include_bytes!("../../fonts/ipa/ipam.ttf"),
1606 "ipag" | "IPAg" => include_bytes!("../../fonts/ipa/ipag.ttf"),
1607 "MPLUS2-Regular" => include_bytes!("../../fonts/MPLUS2/MPLUS2-Regular.ttf"),
1608 "MPLUS2-Bold" => include_bytes!("../../fonts/MPLUS2/MPLUS2-Bold.ttf"),
1609 _ => return None,
1610 })
1611}
1612
1613pub fn init_global_font_chain(names: &[&str]) {
1617 let mut bytes: Vec<&'static [u8]> = names.iter().filter_map(|n| font_bytes(n)).collect();
1618 if bytes.is_empty() {
1619 bytes = DEFAULT_FONT_CHAIN
1620 .iter()
1621 .filter_map(|n| font_bytes(n))
1622 .collect();
1623 }
1624 if bytes.is_empty() {
1625 crate::info!("[vector_font] No embedded fonts available for chain init!");
1626 return;
1627 }
1628 let primary = bytes[0];
1629 let fallbacks: Vec<&'static [u8]> = bytes[1..].to_vec();
1630 match VectorFont::new_with_fallbacks(primary, &fallbacks) {
1631 Ok(font) => {
1632 crate::info!(
1633 "[vector_font] Global font chain initialized ({} fonts).",
1634 bytes.len()
1635 );
1636 *GLOBAL_VECTOR_FONT.lock() = Some(font);
1637 }
1638 Err(e) => {
1639 crate::info!("[vector_font] Failed to init font chain: {:?}", e);
1640 }
1641 }
1642}
1643
1644pub fn init_global_font(font_bytes: &'static [u8]) {
1646 match VectorFont::new(font_bytes) {
1647 Ok(mut font) => {
1648 crate::info!("[vector_font] Successfully initialized global vector font.");
1649 crate::info!("[vector_font] Running test get_glyph('o', 16) for global font...");
1650 if font.get_glyph('o', 16).is_some() {
1651 crate::info!("[vector_font] Test get_glyph('o', 16) succeeded for global font!");
1652 } else {
1653 crate::info!("[vector_font] Test get_glyph('o', 16) failed for global font!");
1654 }
1655 *GLOBAL_VECTOR_FONT.lock() = Some(font);
1656 }
1657 Err(e) => {
1658 crate::info!(
1659 "[vector_font] Failed to initialize global vector font: {:?}",
1660 e
1661 );
1662 }
1663 }
1664}
1665
1666pub fn init_terminal_font() {
1668 let font_bytes = include_bytes!("../../fonts/Mplus1Code/Mplus1Code-Regular.ttf");
1669 match VectorFont::new(font_bytes) {
1670 Ok(mut font) => {
1671 crate::info!("[vector_font] Successfully initialized terminal monospace font.");
1672 crate::info!("[vector_font] Running test get_glyph('o', 16)...");
1673 if font.get_glyph('o', 16).is_some() {
1674 crate::info!("[vector_font] Test get_glyph('o', 16) succeeded!");
1675 } else {
1676 crate::info!("[vector_font] Test get_glyph('o', 16) failed!");
1677 }
1678 *GLOBAL_TERMINAL_FONT.lock() = Some(font);
1679 }
1680 Err(e) => {
1681 crate::info!(
1682 "[vector_font] Failed to initialize terminal monospace font: {:?}",
1683 e
1684 );
1685 }
1686 }
1687}
1688
1689fn pick_family_font(
1696 fonts: &BTreeMap<String, VectorFont>,
1697 family_list: &str,
1698 weight: u16,
1699 covered: &dyn Fn(&str, &VectorFont) -> bool,
1700) -> Option<(String, u16)> {
1701 let weights_of = |fam: &str| -> Vec<(u16, bool)> {
1704 let prefix = alloc::format!("{}|", fam);
1705 fonts
1706 .range(prefix.clone()..)
1707 .take_while(|(k, _)| k.starts_with(&prefix))
1708 .filter_map(|(k, font)| {
1709 let w = k.get(prefix.len()..)?.parse::<u16>().ok()?;
1710 Some((w, covered(k, font)))
1711 })
1712 .collect()
1713 };
1714 for fam in family_list.split(',') {
1715 let key = fam.trim().trim_matches('"').trim_matches('\'').to_lowercase();
1716 if key.is_empty() {
1717 continue;
1718 }
1719 let picked = crate::kernel::font_select::pick_weight_css(weight, &weights_of(&key));
1720 let hit = picked.map(|w| font_key(&key, w)).unwrap_or(key.clone());
1721 if fonts.contains_key(&hit) {
1722 return Some((hit, picked.unwrap_or(400)));
1723 }
1724 for cand in crate::kernel::font_select::generic_family_candidates(&key) {
1727 if let Some(w) = crate::kernel::font_select::pick_weight_css(weight, &weights_of(cand)) {
1728 let k = font_key(cand, w);
1729 if fonts.contains_key(&k) {
1730 return Some((k, w));
1731 }
1732 }
1733 }
1734 }
1735 None
1736}
1737
1738fn family_candidate_keys(fonts: &BTreeMap<String, VectorFont>, family_list: &str) -> Vec<String> {
1740 let mut out: Vec<String> = Vec::new();
1741 let add_prefix = |fam: &str, out: &mut Vec<String>| {
1742 let prefix = alloc::format!("{}|", fam);
1743 for (k, _) in fonts.range(prefix.clone()..).take_while(|(k, _)| k.starts_with(&prefix)) {
1744 if !out.iter().any(|x| x == k) {
1745 out.push(k.clone());
1746 }
1747 }
1748 };
1749 for fam in family_list.split(',') {
1750 let key = fam.trim().trim_matches('"').trim_matches('\'').to_lowercase();
1751 if key.is_empty() {
1752 continue;
1753 }
1754 add_prefix(&key, &mut out);
1755 for cand in crate::kernel::font_select::generic_family_candidates(&key) {
1756 add_prefix(cand, &mut out);
1757 }
1758 }
1759 out
1760}
1761
1762struct BatchTimer {
1765 start_us: u64,
1766 hold_start_us: u64,
1767 max_hold_us: u64,
1768 batches: u32,
1769}
1770
1771impl BatchTimer {
1772 fn new() -> Self {
1773 let t = crate::kernel::timer::get_system_time_us();
1774 Self { start_us: t, hold_start_us: t, max_hold_us: 0, batches: 0 }
1775 }
1776 fn locked(&mut self) {
1778 self.hold_start_us = crate::kernel::timer::get_system_time_us();
1779 }
1780 fn unlocked(&mut self) {
1782 let d = crate::kernel::timer::get_system_time_us().saturating_sub(self.hold_start_us);
1783 self.max_hold_us = self.max_hold_us.max(d);
1784 self.batches += 1;
1785 }
1786 fn report(&self, what: &str, bytes: usize) {
1787 let total = crate::kernel::timer::get_system_time_us().saturating_sub(self.start_us);
1788 if total > 200_000 {
1789 crate::warn!(
1790 "[FONT] 長い文字列を区切って処理 {} bytes={} 錠の回数={} 全体={}ms 1回の錠の最長={}us",
1791 what,
1792 bytes,
1793 self.batches,
1794 total / 1000,
1795 self.max_hold_us
1796 );
1797 }
1798 }
1799}
1800
1801fn select_family_font_batched(s: &str, family_list: &str, weight: u16, killable: bool) -> Option<(String, u16)> {
1806 use core::sync::atomic::Ordering;
1807 let mut restarts = 0u32;
1808 loop {
1809 let (gen0, keys) = {
1810 let fonts = CUSTOM_FONTS.lock();
1811 (CUSTOM_FONTS_GEN.load(Ordering::Acquire), family_candidate_keys(&fonts, family_list))
1812 };
1813 let mut ok: Vec<bool> = alloc::vec![true; keys.len()];
1814 let mut timer = BatchTimer::new();
1815 for chunk in crate::kernel::glyph_batch::char_chunks(s, crate::kernel::glyph_batch::MEASURE_BATCH_CHARS) {
1816 if !ok.iter().any(|&b| b) {
1817 break;
1818 }
1819 if killable {
1820 crate::kernel::window_mgr::kill_checkpoint();
1822 }
1823 {
1824 let fonts = CUSTOM_FONTS.lock();
1825 timer.locked();
1826 for (i, k) in keys.iter().enumerate() {
1827 if ok[i] {
1828 ok[i] = fonts
1829 .get(k)
1830 .is_some_and(|f| crate::kernel::font_select::covers_all(chunk, |c| f.primary_has_glyph(c)));
1831 }
1832 }
1833 }
1834 timer.unlocked();
1835 }
1836 timer.report("字形の有無", s.len());
1837 if killable {
1838 crate::kernel::window_mgr::kill_checkpoint();
1839 }
1840 let fonts = CUSTOM_FONTS.lock();
1841 if CUSTOM_FONTS_GEN.load(Ordering::Acquire) != gen0 && restarts < crate::kernel::glyph_batch::MAX_RESTARTS {
1842 restarts += 1;
1843 continue;
1844 }
1845 let covered = |k: &str, _: &VectorFont| keys.iter().position(|x| x == k).is_some_and(|i| ok[i]);
1847 return pick_family_font(&fonts, family_list, weight, &covered);
1848 }
1849}
1850
1851pub fn with_family_font_batched(
1866 s: &str,
1867 family_list: &str,
1868 weight: u16,
1869 batch: usize,
1870 killable: bool,
1871 mut step: impl FnMut(&mut VectorFont, u16, &str) -> bool,
1872) -> Option<u16> {
1873 use crate::kernel::glyph_batch::{char_chunks, fits_one_batch, MEASURE_BATCH_CHARS};
1874 if family_list.is_empty() {
1875 return None;
1876 }
1877 if fits_one_batch(s, batch.min(MEASURE_BATCH_CHARS)) {
1878 let mut fonts = CUSTOM_FONTS.lock();
1879 let covered =
1880 |_: &str, f: &VectorFont| crate::kernel::font_select::covers_all(s, |c| f.primary_has_glyph(c));
1881 let (key, w) = pick_family_font(&fonts, family_list, weight, &covered)?;
1882 let font = fonts.get_mut(&key)?;
1883 step(font, w, s);
1884 return Some(w);
1885 }
1886 let (key, w) = select_family_font_batched(s, family_list, weight, killable)?;
1887 let mut timer = BatchTimer::new();
1888 for chunk in char_chunks(s, batch) {
1889 if killable {
1890 crate::kernel::window_mgr::kill_checkpoint();
1891 }
1892 let cont = {
1893 let mut fonts = CUSTOM_FONTS.lock();
1894 timer.locked();
1895 match fonts.get_mut(&key) {
1896 Some(font) => step(font, w, chunk),
1897 None => false,
1898 }
1899 };
1900 timer.unlocked();
1901 if !cont {
1902 break;
1903 }
1904 }
1905 timer.report(if killable { "字幅" } else { "描画" }, s.len());
1906 Some(w)
1907}
1908
1909fn with_global_font_batched(s: &str, mut step: impl FnMut(&mut VectorFont, &str)) -> bool {
1916 use crate::kernel::glyph_batch::{char_chunks, MEASURE_BATCH_CHARS};
1917 let mut timer = BatchTimer::new();
1918 for (i, chunk) in char_chunks(s, MEASURE_BATCH_CHARS).enumerate() {
1919 if i > 0 {
1920 crate::kernel::window_mgr::kill_checkpoint();
1921 }
1922 {
1923 let mut g = GLOBAL_VECTOR_FONT.lock();
1924 timer.locked();
1925 let Some(font) = g.as_mut() else { return false };
1926 step(font, chunk);
1927 }
1928 timer.unlocked();
1929 }
1930 timer.report("内蔵フォントの字幅", s.len());
1931 true
1932}
1933
1934static MEASURE_CALLS: core::sync::atomic::AtomicU32 = core::sync::atomic::AtomicU32::new(0);
1936
1937#[inline]
1944fn measure_checkpoint() {
1945 const MEASURE_CHECK_EVERY: u32 = 512;
1946 let n = MEASURE_CALLS.fetch_add(1, core::sync::atomic::Ordering::Relaxed);
1947 if n.is_multiple_of(MEASURE_CHECK_EVERY) {
1948 crate::kernel::window_mgr::kill_checkpoint();
1949 }
1950}
1951
1952pub fn get_vector_string_width_family(
1963 s: &str,
1964 size_px: u32,
1965 family_list: &str,
1966 weight: u16,
1967 ls: i32,
1968 ws: i32,
1969) -> u32 {
1970 use crate::kernel::glyph_batch::MEASURE_BATCH_CHARS;
1971 measure_checkpoint();
1972 let mut total = 0i32;
1973 let hit = with_family_font_batched(s, family_list, weight, MEASURE_BATCH_CHARS, true, |f, _, chunk| {
1974 total += f.string_width_sum(chunk, size_px, ls, ws);
1975 true
1976 });
1977 if hit.is_some() {
1978 return total.max(0) as u32;
1979 }
1980 if crate::kernel::glyph_batch::fits_one_batch(s, MEASURE_BATCH_CHARS) {
1981 return get_vector_string_width_ls_ws(s, size_px, ls, ws);
1982 }
1983 let mut total = 0i32;
1984 if with_global_font_batched(s, |f, chunk| total += f.string_width_sum(chunk, size_px, ls, ws)) {
1985 total.max(0) as u32
1986 } else {
1987 get_vector_string_width_ls_ws(s, size_px, ls, ws)
1988 }
1989}
1990
1991#[allow(clippy::too_many_arguments)]
1996pub fn get_vector_string_wrapped_size_family(
1997 s: &str,
1998 size_px: u32,
1999 max_width: u32,
2000 ls: i32,
2001 ws: i32,
2002 word_break_all: bool,
2003 overflow_wrap: bool,
2004 white_space_pre_wrap: bool,
2005 family_list: &str,
2006 weight: u16,
2007) -> (u32, u32) {
2008 use crate::kernel::glyph_batch::MEASURE_BATCH_CHARS;
2009 measure_checkpoint();
2010 let short = crate::kernel::glyph_batch::fits_one_batch(s, MEASURE_BATCH_CHARS);
2011 let mut advances: Vec<i32> = Vec::new();
2012 let hit = with_family_font_batched(s, family_list, weight, MEASURE_BATCH_CHARS, true, |f, _, chunk| {
2013 f.push_wrap_advances(chunk, size_px, ls, ws, &mut advances);
2014 true
2015 });
2016 if hit.is_none() {
2017 if short {
2018 return get_vector_string_wrapped_size_ext(
2019 s, size_px, max_width, ls, ws, word_break_all, overflow_wrap, white_space_pre_wrap,
2020 );
2021 }
2022 advances.clear();
2023 if !with_global_font_batched(s, |f, chunk| f.push_wrap_advances(chunk, size_px, ls, ws, &mut advances)) {
2024 return get_vector_string_wrapped_size_ext(
2025 s, size_px, max_width, ls, ws, word_break_all, overflow_wrap, white_space_pre_wrap,
2026 );
2027 }
2028 }
2029 let chars: Vec<char> = s.chars().collect();
2030 if chars.len() != advances.len() {
2031 return get_vector_string_wrapped_size_ext(
2033 s, size_px, max_width, ls, ws, word_break_all, overflow_wrap, white_space_pre_wrap,
2034 );
2035 }
2036 wrapped_size_from_advances_poll(
2038 &chars,
2039 &advances,
2040 size_px,
2041 max_width,
2042 word_break_all,
2043 overflow_wrap,
2044 crate::kernel::window_mgr::layout_check,
2045 )
2046}
2047
2048pub fn get_vector_string_width(s: &str, size_px: u32) -> u32 {
2049 if let Some(ref mut font) = *GLOBAL_VECTOR_FONT.lock() {
2050 font.get_string_width(s, size_px)
2051 } else {
2052 s.len() as u32 * (size_px / 2) }
2054}
2055
2056pub fn get_vector_string_width_ls(s: &str, size_px: u32, ls: i32) -> u32 {
2058 get_vector_string_width_ls_ws(s, size_px, ls, 0)
2059}
2060
2061pub fn get_vector_string_width_ls_ws(s: &str, size_px: u32, ls: i32, ws: i32) -> u32 {
2063 if let Some(ref mut font) = *GLOBAL_VECTOR_FONT.lock() {
2064 font.get_string_width_ls_ws(s, size_px, ls, ws)
2065 } else {
2066 let space_count = s.chars().filter(|&c| c == ' ').count() as i32;
2067 let base = s.len() as i32 * (size_px / 2) as i32
2068 + s.chars().count() as i32 * ls
2069 + space_count * ws;
2070 base.max(0) as u32
2071 }
2072}
2073
2074pub fn get_vector_char_width(c: char, size_px: u32) -> u32 {
2077 if let Some(ref mut font) = *GLOBAL_VECTOR_FONT.lock() {
2078 font.get_glyph_advance(c, size_px)
2079 } else {
2080 size_px / 2
2081 }
2082}
2083
2084pub fn get_vector_string_wrapped_size(s: &str, size_px: u32, max_width: u32) -> (u32, u32) {
2085 if let Some(ref mut font) = *GLOBAL_VECTOR_FONT.lock() {
2086 font.get_string_wrapped_size(s, size_px, max_width)
2087 } else {
2088 let char_w = size_px / 2;
2089 let max_chars = (max_width / char_w).max(1);
2090 let chars_count = s.chars().count() as u32;
2091 let lines = chars_count.div_ceil(max_chars);
2092 (
2093 max_width.min(chars_count * char_w),
2094 lines.max(1) * (size_px + 4),
2095 )
2096 }
2097}
2098
2099pub fn get_vector_string_wrapped_size_ls(
2101 s: &str,
2102 size_px: u32,
2103 max_width: u32,
2104 ls: i32,
2105) -> (u32, u32) {
2106 get_vector_string_wrapped_size_ls_ws(s, size_px, max_width, ls, 0)
2107}
2108
2109pub fn get_vector_string_wrapped_size_ls_ws(
2111 s: &str,
2112 size_px: u32,
2113 max_width: u32,
2114 ls: i32,
2115 ws: i32,
2116) -> (u32, u32) {
2117 if let Some(ref mut font) = *GLOBAL_VECTOR_FONT.lock() {
2118 font.get_string_wrapped_size_ls_ws(s, size_px, max_width, ls, ws)
2119 } else {
2120 let char_w = ((size_px / 2) as i32 + ls).max(1) as u32;
2121 let max_chars = (max_width / char_w).max(1);
2122 let chars_count = s.chars().count() as u32;
2123 let lines = chars_count.div_ceil(max_chars);
2124 (
2125 max_width.min(chars_count * char_w),
2126 lines.max(1) * (size_px + 4),
2127 )
2128 }
2129}
2130
2131pub fn get_vector_string_wrapped_size_ext(
2132 s: &str,
2133 size_px: u32,
2134 max_width: u32,
2135 ls: i32,
2136 ws: i32,
2137 word_break_all: bool,
2138 overflow_wrap: bool,
2139 white_space_pre_wrap: bool,
2140) -> (u32, u32) {
2141 if let Some(ref mut font) = *GLOBAL_VECTOR_FONT.lock() {
2142 font.get_string_wrapped_size_ext(s, size_px, max_width, ls, ws, word_break_all, overflow_wrap, white_space_pre_wrap)
2143 } else {
2144 let char_w = ((size_px / 2) as i32 + ls).max(1) as u32;
2145 let max_chars = (max_width / char_w).max(1);
2146 let chars_count = s.chars().count() as u32;
2147 let lines = chars_count.div_ceil(max_chars);
2148 (
2149 max_width.min(chars_count * char_w),
2150 lines.max(1) * (size_px + 4),
2151 )
2152 }
2153}
2154
2155pub fn is_line_start_forbidden(c: char) -> bool {
2156 matches!(
2157 c,
2158 '、' | '。'
2159 | ','
2160 | '.'
2161 | '・'
2162 | ':'
2163 | ';'
2164 | '?'
2165 | '!'
2166 | ')'
2167 | ']'
2168 | '}'
2169 | '〉'
2170 | '》'
2171 | '』'
2172 | '」'
2173 | '〕'
2174 | 'ー'
2175 | '〜'
2176 | '々'
2177 | '〆'
2178 | 'ぁ'
2179 | 'ぃ'
2180 | 'ぅ'
2181 | 'ぇ'
2182 | 'ぉ'
2183 | 'っ'
2184 | 'ゃ'
2185 | 'ゅ'
2186 | 'ょ'
2187 | 'ゎ'
2188 | 'ァ'
2189 | 'ィ'
2190 | 'ゥ'
2191 | 'ェ'
2192 | 'ォ'
2193 | 'ッ'
2194 | 'ャ'
2195 | 'ュ'
2196 | 'ョ'
2197 | 'ヮ'
2198 | 'ヶ'
2199 | 'ヵ'
2200 )
2201}
2202
2203pub fn is_line_end_forbidden(c: char) -> bool {
2204 matches!(c, '(' | '[' | '{' | '〈' | '《' | '『' | '「' | '〔')
2205}