1use std::cell::RefCell;
15use std::collections::hash_map::DefaultHasher;
16use std::collections::HashMap;
17use std::hash::{Hash, Hasher};
18
19use mgui_core::{
20 BoxConstraints, Color, ElementId, LayoutContext, PaintCommand, PaintList, Point, Rect, RenderObject, Size,
21};
22
23use crate::runtime::{current_text_runtime, default_text_runtime};
24
25const ATLAS_SIZE: u32 = 1024;
27const ATLAS_PADDING: u32 = 1;
29const FALLBACK_ADVANCE_X: f32 = 8.0;
31const MAX_ATLAS_SIZE: u32 = 8192;
33
34pub const DEFAULT_FONT_STACK: &str =
38 "system-ui, 'Segoe UI', Tahoma, 'Arial', 'Segoe UI Symbol', 'Microsoft YaHei UI', 'Segoe UI Emoji', sans-serif";
39
40#[derive(Clone, Copy, Debug)]
46#[allow(dead_code)]
47pub struct AtlasEntry {
48 pub uv: [f32; 4],
50 pub width: u32,
51 pub height: u32,
52}
53
54pub struct Atlas {
61 width: u32,
62 height: u32,
63 next_x: u32,
65 next_y: u32,
67 row_height: u32,
69 pixels: Vec<u8>,
71 entries: HashMap<GlyphKey, AtlasEntry>,
73 dirty: bool,
75 dirty_rows: Option<(u32, u32)>,
79 generation: u64,
82}
83
84#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
85pub struct GlyphKey(pub u64);
86
87fn narrow_glyph_id(id: u32) -> Option<u16> {
96 if id <= u16::MAX as u32 {
97 Some(id as u16)
98 } else {
99 None
100 }
101}
102
103impl GlyphKey {
104 pub fn new(
106 font_blob_id: usize,
107 glyph_id: u16,
108 size_px_bits: u32,
109 x_bin: i32,
110 y_bin: i32,
111 subpixel_bits: u8,
112 ) -> Self {
113 let mut h = DefaultHasher::new();
114 font_blob_id.hash(&mut h);
115 glyph_id.hash(&mut h);
116 size_px_bits.hash(&mut h);
117 x_bin.hash(&mut h);
118 y_bin.hash(&mut h);
119 subpixel_bits.hash(&mut h);
120 GlyphKey(h.finish())
121 }
122}
123
124fn raster_font_id(font_blob_id: usize, coords: &[swash::NormalizedCoord]) -> usize {
129 if coords.is_empty() {
130 return font_blob_id;
131 }
132 let mut h = DefaultHasher::new();
133 font_blob_id.hash(&mut h);
134 for c in coords {
135 c.hash(&mut h);
136 }
137 h.finish() as usize
138}
139
140impl Atlas {
141 pub fn new(width: u32, height: u32) -> Self {
142 Self {
143 width,
144 height,
145 next_x: 0,
146 next_y: 0,
147 row_height: 0,
148 pixels: vec![0; (width * height) as usize],
149 entries: HashMap::new(),
150 dirty: false,
151 dirty_rows: None,
152 generation: 1,
153 }
154 }
155
156 fn expand_2x(&mut self) {
159 let new_w = (self.width * 2).min(MAX_ATLAS_SIZE);
160 let new_h = (self.height * 2).min(MAX_ATLAS_SIZE);
161 if new_w == self.width && new_h == self.height {
162 return; }
164 let old_w = self.width;
165 let old_h = self.height;
166 let new_size = (new_w * new_h) as usize;
167 let mut new_pixels = vec![0u8; new_size];
168 for row in 0..old_h as usize {
170 let src_start = row * old_w as usize;
171 let dst_start = row * new_w as usize;
172 new_pixels[dst_start..dst_start + old_w as usize]
173 .copy_from_slice(&self.pixels[src_start..src_start + old_w as usize]);
174 }
175 self.pixels = new_pixels;
176 let scale_u = old_w as f32 / new_w as f32; let scale_v = old_h as f32 / new_h as f32;
179 for entry in self.entries.values_mut() {
180 entry.uv[0] *= scale_u;
181 entry.uv[1] *= scale_v;
182 entry.uv[2] *= scale_u;
183 entry.uv[3] *= scale_v;
184 }
185 self.width = new_w;
186 self.height = new_h;
187 self.dirty = true;
188 self.dirty_rows = Some((0, new_h));
189 self.generation += 1;
190 mgui_core::element::request_full_repaint();
192 }
193
194 fn clear_atlas(&mut self) {
197 self.entries.clear();
198 self.pixels.fill(0);
199 self.next_x = 0;
200 self.next_y = 0;
201 self.row_height = 0;
202 self.dirty = true;
203 self.dirty_rows = Some((0, self.height));
204 self.generation += 1;
205 mgui_core::element::request_full_repaint();
206 }
207
208 pub fn get_or_insert(&mut self, key: GlyphKey, bitmap: &[u8], w: u32, h: u32) -> AtlasEntry {
212 if let Some(&e) = self.entries.get(&key) {
213 return e;
214 }
215 let alloc_w = w + ATLAS_PADDING * 2;
217 let alloc_h = h + ATLAS_PADDING * 2;
218 if self.next_x + alloc_w > self.width {
220 self.next_x = 0;
221 self.next_y += self.row_height;
222 self.row_height = 0;
223 }
224 if self.next_y + alloc_h > self.height {
225 if self.width >= MAX_ATLAS_SIZE && self.height >= MAX_ATLAS_SIZE {
227 self.clear_atlas();
228 } else {
229 self.expand_2x();
230 }
231 return self.get_or_insert(key, bitmap, w, h);
233 }
234 let dst_x = self.next_x + ATLAS_PADDING;
235 let dst_y = self.next_y + ATLAS_PADDING;
236
237 for row in 0..h {
239 let src_start = (row * w) as usize;
240 let src_end = src_start + w as usize;
241 let dst_row = (dst_y + row) as usize * self.width as usize + dst_x as usize;
242 self.pixels[dst_row..dst_row + w as usize].copy_from_slice(&bitmap[src_start..src_end]);
243 }
244
245 let u0 = dst_x as f32 / self.width as f32;
247 let v0 = dst_y as f32 / self.height as f32;
248 let u1 = (dst_x + w) as f32 / self.width as f32;
249 let v1 = (dst_y + h) as f32 / self.height as f32;
250
251 let entry = AtlasEntry { uv: [u0, v0, u1, v1], width: w, height: h };
252 self.entries.insert(key, entry);
253 self.next_x += alloc_w;
254 if alloc_h > self.row_height {
255 self.row_height = alloc_h;
256 }
257 self.mark_rows_written(dst_y, h);
259 self.generation += 1;
260 entry
261 }
262
263 fn mark_rows_written(&mut self, y: u32, h: u32) {
265 self.dirty = true;
266 let end = (y + h).min(self.height);
267 self.dirty_rows = Some(match self.dirty_rows {
268 Some((top, bottom)) => (top.min(y), bottom.max(end)),
269 None => (y, end),
270 });
271 }
272
273 pub fn pixels(&self) -> &[u8] {
275 &self.pixels
276 }
277
278 #[allow(dead_code)]
280 pub fn glyph_count(&self) -> usize {
281 self.entries.len()
282 }
283
284 pub fn is_dirty(&self) -> bool {
286 self.dirty
287 }
288
289 pub fn clear_dirty(&mut self) {
291 self.dirty = false;
292 self.dirty_rows = None;
293 }
294}
295
296#[derive(Clone)]
302struct RasterGlyph {
303 data: Vec<u8>,
304 width: u32,
305 height: u32,
306 left: i32,
308 top: i32,
309 last_used: u64,
311}
312
313type LineCacheKey = (TextKey, u32, Option<u32>, u64, u32);
319
320struct LineCacheEntry {
322 line: std::rc::Rc<ShapedLine>,
323 last_used: u64,
324}
325
326pub struct FontState {
328 pub font_cx: parley::FontContext,
329 pub layout_cx: parley::LayoutContext<()>,
330 pub scale_cx: swash::scale::ScaleContext,
331 pub atlas: Atlas,
332 raster_cache: HashMap<GlyphKey, RasterGlyph>,
334 raster_cache_bytes: usize,
336 line_cache: HashMap<LineCacheKey, LineCacheEntry>,
343 rich_cache: HashMap<RichCacheKey, RichCacheEntry>,
345 rich_clock: u64,
347 line_clock: u64,
349 glyph_clock: u64,
351 pub shape_calls: usize,
353}
354
355impl FontState {
356 fn new() -> Self {
357 Self {
358 font_cx: parley::FontContext::new(),
359 layout_cx: parley::LayoutContext::<()>::new(),
360 scale_cx: swash::scale::ScaleContext::new(),
361 atlas: Atlas::new(ATLAS_SIZE, ATLAS_SIZE),
362 raster_cache: HashMap::new(),
363 raster_cache_bytes: 0,
364 line_cache: HashMap::new(),
365 rich_cache: HashMap::new(),
366 rich_clock: 0,
367 line_clock: 0,
368 glyph_clock: 0,
369 shape_calls: 0,
370 }
371 }
372}
373
374thread_local! {
375 static FONT_STATE: RefCell<Option<FontState>> = const { RefCell::new(None) };
376}
377
378pub fn set_text_dpr(dpr: f32) {
382 default_text_runtime().set_dpr(dpr);
383}
384
385fn text_dpr() -> f32 {
386 current_text_runtime().dpr()
387}
388
389pub fn set_text_line_height(line_height: f32) {
393 default_text_runtime().set_line_height(line_height);
394}
395
396pub fn text_line_height() -> f32 {
398 current_text_runtime().line_height()
399}
400
401pub fn with_font<F, R>(f: F) -> R
403where
404 F: FnOnce(&mut FontState) -> R,
405{
406 FONT_STATE.with(|cell| {
407 let mut opt = cell.borrow_mut();
408 if opt.is_none() {
409 *opt = Some(FontState::new());
410 }
411 f(opt.as_mut().unwrap())
412 })
413}
414
415pub fn reset_font_collection_without_system_fonts() {
435 with_font(|fs| {
436 fs.font_cx = parley::FontContext {
437 collection: parley::fontique::Collection::new(parley::fontique::CollectionOptions {
438 shared: false,
439 system_fonts: false,
440 }),
441 source_cache: parley::fontique::SourceCache::default(),
442 };
443 fs.atlas = Atlas::new(ATLAS_SIZE, ATLAS_SIZE);
444 fs.raster_cache.clear();
445 fs.raster_cache_bytes = 0;
446 fs.line_cache.clear();
447 fs.rich_cache.clear();
448 })
449}
450
451const LINE_CACHE_LIMIT: usize = 4096;
460
461const LINE_CACHE_TARGET: usize = LINE_CACHE_LIMIT - LINE_CACHE_LIMIT / 4;
463
464fn evict_line_cache_lru(fs: &mut FontState) {
466 if fs.line_cache.len() <= LINE_CACHE_TARGET {
467 return;
468 }
469 let mut by_age: Vec<(u64, LineCacheKey)> = fs.line_cache.iter().map(|(k, v)| (v.last_used, k.clone())).collect();
470 by_age.sort_unstable_by_key(|&(last_used, _)| last_used);
471 let remove = fs.line_cache.len().saturating_sub(LINE_CACHE_TARGET);
472 for (_, key) in by_age.into_iter().take(remove) {
473 fs.line_cache.remove(&key);
474 }
475}
476
477const RASTER_CACHE_BUDGET_BYTES: usize = 32 * 1024 * 1024;
479const RASTER_CACHE_TARGET_BYTES: usize = RASTER_CACHE_BUDGET_BYTES * 3 / 4;
481
482fn insert_raster_glyph(fs: &mut FontState, key: GlyphKey, mut glyph: RasterGlyph) {
484 fs.glyph_clock += 1;
485 glyph.last_used = fs.glyph_clock;
486 let bytes = glyph.data.len();
487 if let Some(old) = fs.raster_cache.insert(key, glyph) {
488 fs.raster_cache_bytes = fs.raster_cache_bytes.saturating_sub(old.data.len());
489 }
490 fs.raster_cache_bytes += bytes;
491 trim_raster_cache(fs);
492}
493
494fn trim_raster_cache(fs: &mut FontState) {
499 if fs.raster_cache_bytes <= RASTER_CACHE_BUDGET_BYTES {
500 return;
501 }
502 let mut candidates: Vec<(u64, GlyphKey, usize)> =
503 fs.raster_cache.iter().map(|(&key, g)| (g.last_used, key, g.data.len())).collect();
504 candidates.sort_unstable_by_key(|&(last_used, _, _)| last_used);
505 for (_, key, bytes) in candidates {
506 if fs.raster_cache_bytes <= RASTER_CACHE_TARGET_BYTES {
507 break;
508 }
509 fs.raster_cache.remove(&key);
510 fs.raster_cache_bytes = fs.raster_cache_bytes.saturating_sub(bytes);
511 }
512}
513
514#[derive(Clone, PartialEq, Eq, Hash)]
520enum TextKey {
521 Owned(String),
522 Shared(std::rc::Rc<str>, Option<(usize, usize)>),
523}
524
525impl TextKey {
526 fn owned(text: &str) -> Self {
527 TextKey::Owned(text.to_string())
528 }
529}
530
531struct ShapedGlyph {
533 raster_key: GlyphKey,
535 glyph_id: u16,
537 x: f32,
539 w: f32,
541 #[allow(dead_code)]
543 y: f32,
544 ascent: f32,
546 descent: f32,
548 cluster: u32,
551}
552
553struct ShapedRun {
555 glyphs: Vec<ShapedGlyph>,
556 baseline_y: f32,
558 font: parley::FontData,
562 norm_coords: std::rc::Rc<[swash::NormalizedCoord]>,
564 raster_size: f32,
566}
567
568struct ShapedLine {
570 runs: Vec<ShapedRun>,
571 max_x: f32,
573 #[allow(dead_code)]
575 max_y: f32,
576 visual_lines: Vec<(usize, usize)>,
578}
579
580fn shape_text(
585 fs: &mut FontState,
586 text: &str,
587 raster_px: f32,
588 max_width_px: Option<f32>,
589 font_stack: &str,
590) -> std::rc::Rc<ShapedLine> {
591 shape_text_keyed(fs, text, TextKey::owned(text), raster_px, max_width_px, font_stack)
592}
593
594fn shape_text_keyed(
597 fs: &mut FontState,
598 text: &str,
599 text_key: TextKey,
600 raster_px: f32,
601 max_width_px: Option<f32>,
602 font_stack: &str,
603) -> std::rc::Rc<ShapedLine> {
604 let runtime = current_text_runtime();
605 let font_stack_hash = {
606 let mut h = DefaultHasher::new();
607 runtime.style_generation().hash(&mut h);
610 font_stack.hash(&mut h);
611 h.finish()
612 };
613 let line_height = text_line_height();
614 let key =
615 (text_key, raster_px.to_bits(), max_width_px.map(|w| w.to_bits()), font_stack_hash, line_height.to_bits());
616 if let Some(entry) = fs.line_cache.get_mut(&key) {
617 fs.line_clock += 1;
618 entry.last_used = fs.line_clock;
619 return std::rc::Rc::clone(&entry.line);
620 }
621
622 fs.shape_calls += 1;
623 let dpr = text_dpr();
624
625 let scale = 1.0f32;
628 let font_size_px = raster_px / dpr;
629
630 let wrap_opt = max_width_px.filter(|&w| w > 0.0);
632
633 let mut builder = fs.layout_cx.ranged_builder(&mut fs.font_cx, text, scale, true);
634 builder.push_default(parley::StyleProperty::FontSize(font_size_px));
635 builder.push_default(parley::StyleProperty::LineHeight(parley::LineHeight::FontSizeRelative(line_height)));
641 builder.push_default(parley::StyleProperty::FontFamily(parley::FontFamily::Source(std::borrow::Cow::Borrowed(
644 font_stack,
645 ))));
646 builder.push_default(parley::StyleProperty::WordBreak(parley::WordBreak::KeepAll));
649 builder.push_default(parley::StyleProperty::OverflowWrap(parley::OverflowWrap::Anywhere));
650 let mut layout: parley::Layout<()> = builder.build(text);
651 layout.break_all_lines(wrap_opt);
652 layout.align(parley::Alignment::Start, parley::AlignmentOptions::default());
655
656 let mut runs = Vec::new();
660 let mut max_x = 0.0f32;
661 let mut max_y = 0.0f32;
662 let mut visual_lines = Vec::new();
663
664 for line in layout.lines() {
665 let mut line_start = usize::MAX;
667 let mut line_end = 0usize;
668 for run in line.runs() {
669 let range = run.text_range();
670 line_start = line_start.min(range.start);
671 line_end = line_end.max(range.end);
672 }
673 visual_lines.push(if line_start == usize::MAX { (0, 0) } else { (line_start, line_end) });
674
675 let line_m = line.metrics();
676 let baseline_y = line_m.baseline * dpr; for item in line.items() {
679 let parley::PositionedLayoutItem::GlyphRun(gr) = item else {
680 continue;
681 };
682
683 let run_metrics = gr.run().font_metrics();
687 let ascent = run_metrics.ascent * dpr;
688 let descent = run_metrics.descent * dpr;
689 let font_size_logical = gr.run().font_size(); let font_size_phys = font_size_logical * dpr; let font_blob_id = gr.run().font().data.id() as usize; let mut run_glyphs: Vec<ShapedGlyph> = Vec::new();
700 let norm_coords: std::rc::Rc<[swash::NormalizedCoord]> =
706 gr.run().normalized_coords().iter().map(|c| c.to_bits()).collect();
707 let run_font = gr.run().font().clone();
708 let mut pen_x = gr.offset();
709 let run_baseline = gr.baseline();
710 for cluster in gr.run().visual_clusters() {
711 let cluster_byte = cluster.text_range().start as u32;
712 for g in cluster.glyphs() {
713 let glyph_id = match narrow_glyph_id(g.id) {
716 Some(id) => id,
717 None => {
718 log::warn!("mgui-text: glyph id {} 超出 swash 的 u16 范围,跳过该字形", g.id);
719 pen_x += g.advance;
720 continue;
721 }
722 };
723 let size_bits = font_size_phys.to_bits(); let x_bin = 0; let y_bin = 0;
726 let raster_key =
727 GlyphKey::new(raster_font_id(font_blob_id, &norm_coords), glyph_id, size_bits, x_bin, y_bin, 0);
728 if !fs.raster_cache.contains_key(&raster_key) {
730 if let Some(rg) =
731 rasterize_one_glyph(&run_font, font_size_phys, glyph_id, &norm_coords, &mut fs.scale_cx)
732 {
733 insert_raster_glyph(fs, raster_key, rg);
734 }
735 }
736 let gx = pen_x + g.x;
737 run_glyphs.push(ShapedGlyph {
738 raster_key,
739 glyph_id,
740 x: gx * dpr, w: g.advance * dpr, y: (run_baseline + g.y) * dpr, ascent,
744 descent,
745 cluster: cluster_byte,
746 });
747 max_x = max_x.max((gx + g.advance) * dpr);
748 max_y = max_y.max(baseline_y + descent);
749 pen_x += g.advance;
750 }
751 }
752
753 if !run_glyphs.is_empty() {
754 runs.push(ShapedRun {
755 glyphs: run_glyphs,
756 baseline_y,
757 font: run_font,
758 norm_coords,
759 raster_size: font_size_phys,
760 });
761 }
762 }
763 }
764
765 if max_y == 0.0 {
767 max_y = raster_px * 1.2;
768 }
769
770 let line = std::rc::Rc::new(ShapedLine { runs, max_x, max_y, visual_lines });
771 if fs.line_cache.len() >= LINE_CACHE_LIMIT {
772 evict_line_cache_lru(fs);
773 }
774 fs.line_clock += 1;
775 let entry = LineCacheEntry { line: std::rc::Rc::clone(&line), last_used: fs.line_clock };
776 fs.line_cache.insert(key, entry);
777 line
778}
779
780#[derive(Clone)]
788pub struct AtlasSnapshot {
789 pub width: u32,
790 pub height: u32,
791 pub dirty: bool,
792 pub dirty_y: (u32, u32),
795 pub pixels: Option<Vec<u8>>,
797}
798
799pub fn atlas_snapshot() -> AtlasSnapshot {
801 with_font(|fs| {
802 let dirty = fs.atlas.is_dirty();
803 let (y0, y1) = if dirty {
804 let (a, b) = fs.atlas.dirty_rows.unwrap_or((0, fs.atlas.height));
805 (a.min(fs.atlas.height), b.min(fs.atlas.height))
806 } else {
807 (0, 0)
808 };
809 let pixels = if dirty {
810 let w = fs.atlas.width as usize;
811 Some(fs.atlas.pixels()[(y0 as usize * w)..(y1 as usize * w)].to_vec())
812 } else {
813 None
814 };
815 AtlasSnapshot { width: fs.atlas.width, height: fs.atlas.height, dirty, dirty_y: (y0, y1), pixels }
816 })
817}
818
819pub fn atlas_clear_dirty() {
821 with_font(|fs| {
822 fs.atlas.clear_dirty();
823 })
824}
825
826pub fn atlas_generation() -> u64 {
828 with_font(|fs| fs.atlas.generation)
829}
830
831#[derive(Clone, Copy, Debug, Default)]
833pub struct AtlasStats {
834 pub width: u32,
835 pub height: u32,
836 pub glyph_count: usize,
837 pub used_height: u32,
839 pub dirty: bool,
840}
841
842pub fn atlas_stats() -> AtlasStats {
843 with_font(|fs| {
844 let atlas = &fs.atlas;
845 AtlasStats {
846 width: atlas.width,
847 height: atlas.height,
848 glyph_count: atlas.entries.len(),
849 used_height: (atlas.next_y + atlas.row_height).min(atlas.height),
850 dirty: atlas.dirty,
851 }
852 })
853}
854
855pub fn with_atlas<R>(f: impl FnOnce(u32, u32, &[u8]) -> R) -> R {
860 with_font(|fs| {
861 let atlas = &fs.atlas;
862 f(atlas.width, atlas.height, &atlas.pixels)
863 })
864}
865
866pub struct TextRenderObject {
871 text: String,
872 size_px: f32,
873 color: Color,
874 max_width: Option<f32>,
876 max_width_explicit: bool,
879 size: Size,
881 element_id: Option<ElementId>,
882}
883
884impl TextRenderObject {
885 pub fn new(text: String, size_px: f32, color: Color) -> Self {
886 Self { text, size_px, color, max_width: None, max_width_explicit: false, size: Size::ZERO, element_id: None }
887 }
888
889 pub fn with_max_width(mut self, max_width: f32) -> Self {
890 self.max_width = Some(max_width);
891 self.max_width_explicit = true;
892 self
893 }
894
895 pub fn set_max_width(&mut self, max_width: Option<f32>) {
896 self.max_width = max_width;
897 self.max_width_explicit = max_width.is_some();
898 }
899
900 fn measure(&self) -> Size {
902 let dpr = text_dpr();
903 let raster_px = self.size_px * dpr;
904 let font_stack = current_text_runtime().font_stack();
905 let width = with_font(|fs| {
906 let line = shape_text(fs, &self.text, raster_px, self.max_width, &font_stack);
907 let max_x = line.max_x / dpr;
908 if max_x == 0.0 && !self.text.is_empty() {
909 self.text.chars().count() as f32 * FALLBACK_ADVANCE_X
910 } else {
911 max_x
912 }
913 });
914 let height = text_visual_height(&self.text, self.size_px, self.max_width);
917 Size::new(width, height)
918 }
919}
920
921pub fn measure_text_width(text: &str, size_px: f32) -> f32 {
925 let font_stack = current_text_runtime().font_stack();
926 measure_text_width_styled(text, size_px, &font_stack)
927}
928
929pub fn measure_text_width_styled(text: &str, size_px: f32, font_stack: &str) -> f32 {
931 if text.is_empty() {
932 return 0.0;
933 }
934 with_font(|fs| {
935 let dpr = text_dpr();
937 let raster_px = size_px * dpr;
938 let line = shape_text(fs, text, raster_px, None, font_stack);
939 let w = line.max_x / dpr;
940 if w == 0.0 {
941 text.chars().count() as f32 * FALLBACK_ADVANCE_X
942 } else {
943 w
944 }
945 })
946}
947
948pub fn text_visual_height(text: &str, size_px: f32, max_width_px: Option<f32>) -> f32 {
958 let font_stack = current_text_runtime().font_stack();
959 text_visual_height_styled(text, size_px, max_width_px, &font_stack)
960}
961
962pub fn text_visual_height_styled(text: &str, size_px: f32, max_width_px: Option<f32>, font_stack: &str) -> f32 {
964 if text.is_empty() {
965 return size_px;
966 }
967 with_font(|fs| {
968 let dpr = text_dpr();
969 let raster_px = size_px * dpr;
970 let line = shape_text(fs, text, raster_px, max_width_px, font_stack);
971
972 if line.runs.is_empty() {
973 return size_px;
974 }
975
976 let first_run = &line.runs[0];
978 let first_ascent = first_run.glyphs.first().map(|g| g.ascent).unwrap_or(raster_px);
979 let first_baseline = first_run.baseline_y;
980 let visual_top = first_baseline - first_ascent;
981
982 let mut visual_bottom = 0.0f32;
984 for run in &line.runs {
985 for sg in &run.glyphs {
986 let bottom = run.baseline_y + sg.descent;
987 visual_bottom = visual_bottom.max(bottom);
988 }
989 }
990
991 if visual_bottom > visual_top {
992 (visual_bottom - visual_top) / dpr
993 } else {
994 size_px
995 }
996 })
997}
998
999pub fn paint_text_line(
1005 text: &str,
1006 size_px: f32,
1007 color: Color,
1008 offset: Point,
1009 list: &mut PaintList,
1010 max_width_px: Option<f32>,
1011) -> f32 {
1012 let font_stack = current_text_runtime().font_stack();
1013 paint_text_line_impl(text, TextKey::owned(text), size_px, color, offset, list, max_width_px, &font_stack)
1014}
1015
1016#[allow(clippy::too_many_arguments)]
1018pub fn paint_text_line_styled(
1019 text: &str,
1020 size_px: f32,
1021 color: Color,
1022 offset: Point,
1023 list: &mut PaintList,
1024 max_width_px: Option<f32>,
1025 font_stack: &str,
1026) -> f32 {
1027 paint_text_line_impl(text, TextKey::owned(text), size_px, color, offset, list, max_width_px, font_stack)
1028}
1029
1030#[allow(clippy::too_many_arguments)]
1035pub fn paint_text_span(
1036 text: &std::rc::Rc<str>,
1037 range: Option<(usize, usize)>,
1038 size_px: f32,
1039 color: Color,
1040 offset: Point,
1041 list: &mut PaintList,
1042 max_width_px: Option<f32>,
1043) -> f32 {
1044 let (start, end) = match range {
1045 Some(r) => clamp_char_range(text, r),
1046 None => (0, text.len()),
1047 };
1048 let font_stack = current_text_runtime().font_stack();
1049 paint_text_line_impl(
1050 &text[start..end],
1051 TextKey::Shared(std::rc::Rc::clone(text), range),
1052 size_px,
1053 color,
1054 offset,
1055 list,
1056 max_width_px,
1057 &font_stack,
1058 )
1059}
1060
1061pub fn text_ascent(text: &str, size_px: f32) -> f32 {
1067 if text.is_empty() {
1068 return size_px;
1069 }
1070 let font_stack = current_text_runtime().font_stack();
1071 with_font(|fs| {
1072 let dpr = text_dpr();
1073 let shaped = shape_text(fs, text, size_px * dpr, None, &font_stack);
1074 first_glyph_ascent(&shaped).map(|a| a / dpr).unwrap_or(size_px)
1075 })
1076}
1077
1078pub fn text_span_ascent(text: &std::rc::Rc<str>, range: Option<(usize, usize)>, size_px: f32) -> f32 {
1081 let (start, end) = match range {
1082 Some(r) => clamp_char_range(text, r),
1083 None => (0, text.len()),
1084 };
1085 if start >= end {
1086 return size_px;
1087 }
1088 let font_stack = current_text_runtime().font_stack();
1089 with_font(|fs| {
1090 let dpr = text_dpr();
1091 let shaped = shape_text_keyed(
1092 fs,
1093 &text[start..end],
1094 TextKey::Shared(std::rc::Rc::clone(text), range),
1095 size_px * dpr,
1096 None,
1097 &font_stack,
1098 );
1099 first_glyph_ascent(&shaped).map(|a| a / dpr).unwrap_or(size_px)
1100 })
1101}
1102
1103fn first_glyph_ascent(shaped: &ShapedLine) -> Option<f32> {
1104 shaped.runs.first().and_then(|r| r.glyphs.first()).map(|g| g.ascent)
1105}
1106
1107fn clamp_char_range(text: &str, range: (usize, usize)) -> (usize, usize) {
1109 let mut start = range.0.min(text.len());
1110 let mut end = range.1.min(text.len());
1111 while !text.is_char_boundary(start) {
1112 start += 1;
1113 }
1114 while !text.is_char_boundary(end) {
1115 end -= 1;
1116 }
1117 if end < start {
1118 end = start;
1119 }
1120 (start, end)
1121}
1122
1123#[allow(clippy::too_many_arguments)]
1125fn paint_text_line_impl(
1126 text: &str,
1127 text_key: TextKey,
1128 size_px: f32,
1129 color: Color,
1130 offset: Point,
1131 list: &mut PaintList,
1132 max_width_px: Option<f32>,
1133 font_stack: &str,
1134) -> f32 {
1135 if text.is_empty() {
1136 return 0.0;
1137 }
1138 let width = with_font(|fs| {
1139 let dpr = text_dpr();
1140 let raster_px = size_px * dpr;
1141 let shaped = shape_text_keyed(fs, text, text_key, raster_px, max_width_px, font_stack);
1142
1143 let first_run = match shaped.runs.first() {
1147 Some(r) => r,
1148 None => return 0.0,
1149 };
1150 let first_ascent = first_run.glyphs.first().map(|g| g.ascent).unwrap_or(raster_px);
1151 let first_baseline = first_run.baseline_y;
1152 let anchor = first_baseline - first_ascent; let mut max_x = 0.0f32;
1155 for run in &shaped.runs {
1156 for sg in &run.glyphs {
1157 if !fs.raster_cache.contains_key(&sg.raster_key) {
1160 if let Some(rg) =
1161 rasterize_one_glyph(&run.font, run.raster_size, sg.glyph_id, &run.norm_coords, &mut fs.scale_cx)
1162 {
1163 insert_raster_glyph(fs, sg.raster_key, rg);
1164 }
1165 }
1166 let Some(r) = fs.raster_cache.get_mut(&sg.raster_key) else {
1170 continue;
1171 };
1172 if r.width == 0 || r.height == 0 {
1173 continue;
1174 }
1175 fs.glyph_clock += 1;
1176 r.last_used = fs.glyph_clock;
1177 let entry = fs.atlas.get_or_insert(sg.raster_key, &r.data, r.width, r.height);
1178
1179 let x = offset.x + (sg.x + r.left as f32) / dpr;
1181 let glyph_visual_top = run.baseline_y - r.top as f32;
1186 let y = offset.y + (glyph_visual_top - anchor) / dpr;
1187
1188 let rect = Rect::new(x, y, r.width as f32 / dpr, r.height as f32 / dpr);
1189 list.push(PaintCommand::TexturedRect {
1190 rect,
1191 color,
1192 uv: entry.uv,
1193 texture_id: 0,
1194 mode: mgui_core::paint::TextureMode::Mask,
1195 });
1196 max_x = max_x.max((sg.x + sg.w) / dpr);
1197 }
1198 }
1199 if max_x == 0.0 {
1200 max_x = text.chars().count() as f32 * FALLBACK_ADVANCE_X;
1201 }
1202 max_x
1203 });
1204 width
1205}
1206
1207pub fn wrapped_line_ranges(text: &str, size_px: f32, max_width: f32) -> Vec<(usize, usize)> {
1222 if text.is_empty() {
1223 return vec![(0, 0)];
1224 }
1225 if max_width <= 0.0 {
1226 return vec![(0, text.len())];
1227 }
1228 let font_stack = current_text_runtime().font_stack();
1229 with_font(|fs| {
1230 let dpr = text_dpr();
1231 let raster_px = size_px * dpr;
1232 let shaped = shape_text(fs, text, raster_px, Some(max_width), &font_stack);
1233 shaped.visual_lines.clone()
1234 })
1235}
1236
1237pub fn measure_char_prefix_widths(text: &str, size_px: f32, font_stack: &str) -> Vec<f32> {
1238 if text.is_empty() {
1239 return vec![0.0];
1240 }
1241 with_font(|fs| {
1242 let dpr = text_dpr();
1243 let raster_px = size_px * dpr;
1244 let shaped = shape_text(fs, text, raster_px, None, font_stack);
1245
1246 let char_count = text.chars().count();
1247 let mut widths = vec![0.0f32; char_count + 1];
1248
1249 let mut byte_x: Vec<(u32, f32)> = Vec::new();
1252 for run in &shaped.runs {
1253 for sg in &run.glyphs {
1254 match byte_x.last_mut() {
1255 Some((b, _)) if *b == sg.cluster => {}
1256 _ => byte_x.push((sg.cluster, sg.x)),
1257 }
1258 }
1259 }
1260
1261 let mut prev = 0.0f32;
1264 let mut bi = 0usize;
1265 for (ci, (byte_pos, _)) in text.char_indices().enumerate() {
1266 while bi < byte_x.len() && byte_x[bi].0 <= byte_pos as u32 {
1267 prev = byte_x[bi].1 / dpr;
1268 bi += 1;
1269 }
1270 widths[ci] = prev;
1271 }
1272 widths[char_count] = shaped.max_x / dpr;
1273 widths
1274 })
1275}
1276
1277fn rasterize_one_glyph(
1279 font: &parley::FontData,
1280 font_size: f32,
1281 glyph_id: u16,
1282 norm_coords: &[swash::NormalizedCoord],
1283 scale_cx: &mut swash::scale::ScaleContext,
1284) -> Option<RasterGlyph> {
1285 let bytes = font.data.data();
1287 if bytes.is_empty() {
1288 return None;
1289 }
1290 let font_ref = swash::FontRef::from_index(bytes, font.index as usize)?;
1291 let mut scaler =
1292 scale_cx.builder(font_ref).size(font_size).normalized_coords(norm_coords.iter()).hint(true).build();
1293 let image = swash::scale::Render::new(&[
1294 swash::scale::Source::ColorOutline(0),
1295 swash::scale::Source::ColorBitmap(swash::scale::StrikeWith::BestFit),
1296 swash::scale::Source::Outline,
1297 ])
1298 .render(&mut scaler, glyph_id)?;
1299 if image.placement.width == 0 || image.placement.height == 0 {
1300 return Some(RasterGlyph { data: Vec::new(), width: 0, height: 0, left: 0, top: 0, last_used: 0 });
1305 }
1306 Some(RasterGlyph {
1307 data: image.data.to_vec(),
1308 width: image.placement.width,
1309 height: image.placement.height,
1310 left: image.placement.left,
1311 top: image.placement.top,
1312 last_used: 0,
1313 })
1314}
1315
1316impl RenderObject for TextRenderObject {
1317 fn layout(&mut self, _bc: BoxConstraints, _ctx: &mut LayoutContext) -> Size {
1318 let s = self.measure();
1329 self.size = s;
1330 s
1331 }
1332
1333 fn content_size(&self) -> Size {
1334 self.size
1335 }
1336
1337 fn paint(&self, offset: Point, list: &mut PaintList) {
1338 paint_text_line(&self.text, self.size_px, self.color, offset, list, self.max_width);
1339 }
1340
1341 fn set_element_id(&mut self, id: ElementId) {
1342 self.element_id = Some(id);
1343 }
1344
1345 fn hit_test(&self, position: Point, offset: Point) -> Option<ElementId> {
1346 let r = Rect::new(offset.x, offset.y, self.size.width, self.size.height);
1350 if r.contains(position) {
1351 self.element_id
1352 } else {
1353 None
1354 }
1355 }
1356}
1357
1358#[cfg(test)]
1363mod tests {
1364 use super::*;
1365 use crate::runtime::{with_text_runtime, TextRuntime};
1366
1367 fn mk_key(id: u32) -> GlyphKey {
1368 GlyphKey(id as u64)
1369 }
1370
1371 #[test]
1372 fn atlas_get_or_insert_dedupes() {
1373 let mut a = Atlas::new(64, 64);
1374 let k = mk_key(1);
1375 let e1 = a.get_or_insert(k, &[255; 8], 2, 4);
1376 let e2 = a.get_or_insert(k, &[0; 8], 2, 4);
1377 assert_eq!(e1.uv, e2.uv, "重复 key 必须返回同一 entry");
1378 assert_eq!(a.glyph_count(), 1);
1379 }
1380
1381 #[test]
1382 fn atlas_wraps_to_next_row() {
1383 let mut a = Atlas::new(20, 20);
1384 let k1 = mk_key(1);
1386 a.get_or_insert(k1, &[1; 64], 16, 4);
1387 let k2 = mk_key(2);
1389 let e2 = a.get_or_insert(k2, &[2; 64], 16, 4);
1390 assert!(e2.uv[1] > 0.0, "第二个 glyph 应该换行,uv.v0 > 0");
1391 }
1392
1393 #[test]
1394 fn atlas_dirty_flag_lifecycle() {
1395 let mut a = Atlas::new(64, 64);
1396 assert!(!a.is_dirty());
1398 a.get_or_insert(mk_key(1), &[255; 8], 2, 4);
1400 assert!(a.is_dirty(), "get_or_insert 后应该 dirty");
1401 a.clear_dirty();
1403 assert!(!a.is_dirty());
1404 a.get_or_insert(mk_key(1), &[0; 8], 2, 4);
1406 assert!(!a.is_dirty(), "重复 key 不应触发 dirty");
1407 a.get_or_insert(mk_key(2), &[0; 8], 2, 4);
1409 assert!(a.is_dirty());
1410 }
1411
1412 #[test]
1415 fn atlas_snapshot_uploads_only_dirty_rows() {
1416 let width = with_font(|fs| {
1418 fs.atlas = Atlas::new(ATLAS_SIZE, ATLAS_SIZE);
1419 fs.atlas.width
1420 });
1421 with_font(|fs| {
1422 fs.atlas.get_or_insert(GlyphKey::new(7, 7, 0, 0, 0, 0), &[9u8; 16], 4, 4);
1423 fs.atlas.get_or_insert(GlyphKey::new(7, 8, 0, 0, 0, 0), &[9u8; 16], 4, 4);
1424 assert_eq!(fs.atlas.dirty_rows, Some((1, 5)), "同一行的写入应合并为单行带");
1425 });
1426 let snap = atlas_snapshot();
1427 assert!(snap.dirty);
1428 assert_eq!(snap.dirty_y, (1, 5));
1429 assert_eq!(snap.pixels.as_ref().map(Vec::len), Some(width as usize * 4), "快照只拷贝 dirty 行");
1430 atlas_clear_dirty();
1431 let clean = atlas_snapshot();
1432 assert!(!clean.dirty);
1433 assert_eq!(clean.dirty_y, (0, 0));
1434 assert!(clean.pixels.is_none());
1435 }
1436
1437 #[test]
1439 fn atlas_auto_expands_when_full() {
1440 let mut a = Atlas::new(32, 32);
1441 let e_before = a.get_or_insert(mk_key(1), &[100; 9], 3, 3);
1443 let uv_scalar_before = e_before.uv[0]; let big: Vec<u8> = vec![200; 400]; for i in 2..10 {
1449 a.get_or_insert(mk_key(i), &big, 20, 20);
1450 }
1451 assert!(a.width >= 32, "atlas 应保持原尺寸或扩容");
1453 assert!(a.glyph_count() >= 8, "扩容后应能放下 8+ glyphs,实际 {}", a.glyph_count());
1454
1455 if a.width > 32 {
1457 let e_after = a.get_or_insert(mk_key(1), &[0; 9], 3, 3);
1459 let expected = uv_scalar_before / 2.0;
1462 assert!((e_after.uv[0] - expected).abs() < 0.01, "扩容后 uv.u0 应为 {expected}, 实际 {}", e_after.uv[0]);
1463 }
1464 }
1465
1466 #[test]
1468 fn atlas_accepts_new_glyphs_after_expansion() {
1469 let mut a = Atlas::new(16, 16);
1470 a.get_or_insert(mk_key(1), &[50; 144], 12, 12);
1472 let e2 = a.get_or_insert(mk_key(2), &[100; 144], 12, 12);
1474 assert!(a.width > 16 || a.height > 16, "应该扩容了");
1475 let e1 = a.get_or_insert(mk_key(1), &[0; 144], 12, 12);
1477 assert!(e2.uv[1] >= e1.uv[1], "第二个 glyph 应在第一个下方");
1478 }
1479
1480 #[test]
1481 fn text_measure_produces_nonzero_size() {
1482 let t = TextRenderObject::new("Hello".into(), 24.0, Color::WHITE);
1483 let s = t.measure();
1484 assert!(s.width > 0.0, "width should be > 0 for 'Hello'");
1485 assert!(s.height > 0.0, "height should be > 0");
1486 }
1487
1488 #[test]
1489 fn text_paint_emits_textured_rects() {
1490 let t = TextRenderObject::new("Hi".into(), 24.0, Color::WHITE);
1491 let mut list = PaintList::new();
1492 t.paint(Point::new(0.0, 0.0), &mut list);
1493 assert!(!list.is_empty(), "paint should emit at least 1 textured rect");
1495 for cmd in &list.commands {
1496 match cmd {
1497 PaintCommand::TexturedRect { texture_id, uv, .. } => {
1498 assert_eq!(*texture_id, 0);
1499 assert!(uv[0] < uv[2]);
1500 assert!(uv[1] < uv[3]);
1501 }
1502 _ => panic!("expected TexturedRect, got Rect"),
1503 }
1504 }
1505 }
1506
1507 #[test]
1508 fn text_paint_with_offset_shifts_rects() {
1509 let t = TextRenderObject::new("X".into(), 24.0, Color::WHITE);
1510 let mut list = PaintList::new();
1511 t.paint(Point::new(100.0, 50.0), &mut list);
1512 for cmd in &list.commands {
1514 if let PaintCommand::TexturedRect { rect, .. } = cmd {
1515 assert!(rect.x >= 100.0 - 1.0, "x={}", rect.x);
1516 assert!(rect.y >= 50.0 - 1.0, "y={}", rect.y);
1517 }
1518 }
1519 }
1520
1521 #[test]
1523 fn shape_line_cache_hits_second_paint() {
1524 let mut list1 = PaintList::new();
1525 paint_text_line("cache-hit-test", 20.0, Color::WHITE, Point::ZERO, &mut list1, None);
1526 let calls_1 = with_font(|fs| fs.shape_calls);
1527
1528 let mut list2 = PaintList::new();
1529 paint_text_line("cache-hit-test", 20.0, Color::WHITE, Point::new(5.0, 5.0), &mut list2, None);
1530 let calls_2 = with_font(|fs| fs.shape_calls);
1531
1532 assert_eq!(calls_1, calls_2, "第二次 paint 应命中缓存,不再 shape");
1533 assert_eq!(list1.commands.len(), list2.commands.len(), "缓存命中的绘制输出数量应一致");
1534 }
1535
1536 #[test]
1537 fn line_height_is_in_shape_cache_key_and_changes_geometry() {
1538 set_text_line_height(1.2);
1540 let mut list = PaintList::new();
1541 paint_text_line("leading-probe", 20.0, Color::WHITE, Point::ZERO, &mut list, None);
1542 let find_line = |fs: &FontState, lhs: u32| -> Option<std::rc::Rc<ShapedLine>> {
1543 fs.line_cache
1544 .iter()
1545 .find(|(k, _)| k.0 == TextKey::Owned("leading-probe".into()) && k.4 == lhs)
1546 .map(|(_, e)| std::rc::Rc::clone(&e.line))
1547 };
1548 let line_12 = with_font(|fs| find_line(fs, 1.2f32.to_bits()));
1549 assert!(line_12.is_some(), "1.2 行高的 shaped line 应入缓存");
1550
1551 set_text_line_height(1.8);
1552 paint_text_line("leading-probe", 20.0, Color::WHITE, Point::ZERO, &mut PaintList::new(), None);
1553 let line_18 = with_font(|fs| find_line(fs, 1.8f32.to_bits()));
1554 assert!(line_18.is_some(), "切到 1.8 后必须重新 shape 并建新 key,不能命中旧行高缓存");
1555 assert!(
1556 !std::rc::Rc::ptr_eq(&line_12.unwrap(), &line_18.unwrap()),
1557 "两种行高必须是不同的 shaped line,不能串缓存"
1558 );
1559 set_text_line_height(1.2);
1560 }
1561
1562 #[test]
1563 fn set_text_line_height_rejects_invalid_values() {
1564 set_text_line_height(0.0);
1565 assert_eq!(text_line_height(), 1.2);
1566 set_text_line_height(-3.0);
1567 assert_eq!(text_line_height(), 1.2);
1568 set_text_line_height(f32::NAN);
1569 assert_eq!(text_line_height(), 1.2);
1570 set_text_line_height(1.5);
1571 assert_eq!(text_line_height(), 1.5);
1572 set_text_line_height(1.2);
1573 }
1574
1575 #[test]
1577 fn shape_line_cache_evicts_lru_at_limit() {
1578 let fake_line =
1579 || std::rc::Rc::new(ShapedLine { runs: Vec::new(), max_x: 0.0, max_y: 0.0, visual_lines: Vec::new() });
1580 let hot_key = (TextKey::Owned("hot-entry".to_string()), 0, None, 0, 1.2f32.to_bits());
1581 let oldest_key = (TextKey::Owned("fake-entry-0".to_string()), 0, None, 0, 1.2f32.to_bits());
1582 with_font(|fs| {
1583 fs.line_cache.clear();
1584 fs.line_clock = 0;
1585 fs.line_clock += 1;
1586 fs.line_cache.insert(hot_key.clone(), LineCacheEntry { line: fake_line(), last_used: fs.line_clock });
1587 for i in 0..LINE_CACHE_LIMIT - 1 {
1588 fs.line_clock += 1;
1589 fs.line_cache.insert(
1590 (TextKey::Owned(format!("fake-entry-{i}")), 0, None, 0, 1.2f32.to_bits()),
1591 LineCacheEntry { line: fake_line(), last_used: fs.line_clock },
1592 );
1593 }
1594 fs.line_clock += 1;
1596 fs.line_cache.get_mut(&hot_key).expect("hot entry").last_used = fs.line_clock;
1597 });
1598 let mut list = PaintList::new();
1600 paint_text_line("trigger-evict", 14.0, Color::WHITE, Point::ZERO, &mut list, None);
1601 with_font(|fs| {
1602 assert!(fs.line_cache.len() <= LINE_CACHE_LIMIT, "超限后应回收到上限内");
1603 assert!(fs.line_cache.len() >= LINE_CACHE_TARGET, "LRU 只应淘汰最旧 1/4");
1604 assert!(fs.line_cache.contains_key(&hot_key), "刚访问过的热条目不应被淘汰");
1605 assert!(!fs.line_cache.contains_key(&oldest_key), "最久未访问的条目应被淘汰");
1606 fs.line_cache.clear();
1607 });
1608 }
1609
1610 #[test]
1612 fn paint_rebuilds_evicted_raster_glyphs() {
1613 let mut first = PaintList::new();
1614 paint_text_line("raster-rebuild-test", 18.0, Color::WHITE, Point::ZERO, &mut first, None);
1615 assert!(!first.commands.is_empty());
1616
1617 with_font(|fs| {
1618 fs.raster_cache.clear();
1619 fs.raster_cache_bytes = 0;
1620 });
1621
1622 let mut second = PaintList::new();
1623 paint_text_line("raster-rebuild-test", 18.0, Color::WHITE, Point::ZERO, &mut second, None);
1624 assert_eq!(first.commands.len(), second.commands.len(), "位图淘汰后应重建 glyph,而不是丢字");
1625 assert!(!second.commands.is_empty());
1626 }
1627
1628 #[test]
1632 fn zero_size_glyphs_are_cached_not_rerasterized() {
1633 with_font(|fs| {
1634 fs.raster_cache.clear();
1635 fs.raster_cache_bytes = 0;
1636 let _ = shape_text(fs, "a b c", 13.0, None, DEFAULT_FONT_STACK);
1637 let cached = fs.raster_cache.len();
1638 assert!(
1639 fs.raster_cache.values().any(|g| g.width == 0 && g.height == 0),
1640 "空格等零尺寸 glyph 必须缓存占位,不能每次重栅格化"
1641 );
1642 let _ = shape_text(fs, "a b c d", 13.0, None, DEFAULT_FONT_STACK);
1645 assert_eq!(fs.raster_cache.len(), cached + 1, "除新字符外不得新增栅格化条目");
1646 fs.raster_cache.clear();
1647 fs.raster_cache_bytes = 0;
1648 });
1649 }
1650
1651 #[test]
1652 fn runtime_generation_invalidates_line_cache() {
1653 let a = TextRuntime::new();
1654 let b = TextRuntime::with_config("serif", 1.2);
1655 with_font(|fs| fs.line_cache.clear());
1656 let before = with_font(|fs| fs.shape_calls);
1657 with_text_runtime(&a, || {
1658 with_font(|fs| {
1659 let _ = shape_text(fs, "runtime-generation-key", 13.0, None, DEFAULT_FONT_STACK);
1660 });
1661 });
1662 let after_a = with_font(|fs| fs.shape_calls);
1663 assert_eq!(after_a, before + 1);
1664 with_text_runtime(&b, || {
1665 with_font(|fs| {
1666 let _ = shape_text(fs, "runtime-generation-key", 13.0, None, DEFAULT_FONT_STACK);
1667 });
1668 });
1669 let after_b = with_font(|fs| fs.shape_calls);
1670 assert_eq!(after_b, after_a + 1, "不同运行时 generation 不得命中同一 shaped line");
1671 }
1672
1673 #[test]
1675 fn raster_cache_trims_to_budget() {
1676 with_font(|fs| {
1677 fs.raster_cache.clear();
1678 fs.raster_cache_bytes = 0;
1679 let chunk = vec![0u8; 8 * 1024 * 1024];
1680 for i in 0..5u16 {
1681 insert_raster_glyph(
1682 fs,
1683 GlyphKey::new(0, i, 0, 0, 0, 0),
1684 RasterGlyph { data: chunk.clone(), width: 2048, height: 1024, left: 0, top: 0, last_used: 0 },
1685 );
1686 }
1687 assert!(fs.raster_cache_bytes <= RASTER_CACHE_TARGET_BYTES, "应回收到目标水位");
1689 assert_eq!(fs.raster_cache.len(), 3, "LRU 应保留最近的条目");
1690 assert!(!fs.raster_cache.contains_key(&GlyphKey::new(0, 0, 0, 0, 0, 0)), "最旧条目应被淘汰");
1691 assert!(fs.raster_cache.contains_key(&GlyphKey::new(0, 4, 0, 0, 0, 0)), "最新条目应保留");
1692 fs.raster_cache.clear();
1693 fs.raster_cache_bytes = 0;
1694 });
1695 }
1696
1697 #[test]
1700 fn paint_text_line_dpr_rasterizes_at_physical_resolution() {
1701 fn paint_once(dpr: f32) -> (f32, f32, f32) {
1702 set_text_dpr(dpr);
1703 let mut list = PaintList::new();
1704 let width = paint_text_line("H", 24.0, Color::WHITE, Point::ZERO, &mut list, None);
1705 let (rect_w, uv_span) = match &list.commands[0] {
1706 PaintCommand::TexturedRect { rect, uv, .. } => (rect.width, (uv[2] - uv[0]) * ATLAS_SIZE as f32),
1707 _ => panic!("expected TexturedRect"),
1708 };
1709 set_text_dpr(1.0); (rect_w, uv_span, width)
1711 }
1712
1713 let (w1, span1, ret1) = paint_once(1.0);
1714 let (w2, span2, ret2) = paint_once(2.0);
1715
1716 assert!((w1 - w2).abs() <= 2.0, "rect 逻辑尺寸应 dpr 无关(允许取整 ≤2px): dpr1={w1} vs dpr2={w2}");
1718 assert!((ret1 - ret2).abs() < 0.5 && ret1 > 0.0, "返回宽度(逻辑)应 dpr 无关: {ret1} vs {ret2}");
1719 assert!(span2 > span1 * 1.5, "atlas 位图分辨率应随 dpr 变大: dpr1={span1}px vs dpr2={span2}px");
1720 let mw = measure_text_width("H", 24.0);
1721 assert!((ret1 - mw).abs() < 0.5, "paint 宽度应与 measure 一致(TextField 光标定位依赖): {ret1} vs {mw}");
1722 }
1723}
1724
1725pub fn is_rtl_text(text: &str) -> bool {
1731 for ch in text.chars() {
1732 let code = ch as u32;
1733 let rtl = matches!(
1734 code,
1735 0x0590..=0x05FF | 0x0600..=0x06FF | 0x0700..=0x074F | 0x0750..=0x077F | 0x0780..=0x07BF | 0x0860..=0x086F | 0x08A0..=0x08FF | 0xFB1D..=0xFB4F | 0xFB50..=0xFDFF | 0xFE70..=0xFEFF );
1746 if rtl {
1747 return true;
1748 }
1749 if ch.is_alphabetic() {
1750 return false;
1751 }
1752 }
1753 false
1754}
1755
1756pub fn mirror_carets_for_rtl(widths: &[f32]) -> Vec<f32> {
1762 let chars = widths.len().saturating_sub(1);
1763 if chars == 0 {
1764 return widths.to_vec();
1765 }
1766 let mut carets = vec![0.0f32; chars + 1];
1767 carets[0] = widths[chars];
1768 carets[1..=chars].copy_from_slice(&widths[..chars]);
1769 carets
1770}
1771
1772pub fn measure_caret_positions(text: &str, size_px: f32, font_stack: &str) -> Vec<f32> {
1774 let widths = measure_char_prefix_widths(text, size_px, font_stack);
1775 if is_rtl_text(text) {
1776 mirror_carets_for_rtl(&widths)
1777 } else {
1778 widths
1779 }
1780}
1781
1782pub fn nearest_caret_index(carets: &[f32], x: f32) -> usize {
1784 carets
1785 .iter()
1786 .enumerate()
1787 .min_by(|(ia, a), (ib, b)| (**a - x).abs().total_cmp(&(**b - x).abs()).then_with(|| ia.cmp(ib)))
1788 .map(|(index, _)| index)
1789 .unwrap_or(0)
1790}
1791
1792#[cfg(test)]
1793mod rtl_tests {
1794 use super::*;
1795
1796 #[test]
1797 fn detects_base_direction() {
1798 assert!(is_rtl_text("مرحبا بالعالم"));
1799 assert!(is_rtl_text("שלום"));
1800 assert!(!is_rtl_text("hello مرحبا")); assert!(!is_rtl_text("123 !?"));
1802 assert!(is_rtl_text("123 مرحبا")); }
1804
1805 #[test]
1806 fn rtl_caret_mirroring_and_nearest_index() {
1807 let widths = [0.0, 10.0, 25.0, 40.0];
1809 let carets = mirror_carets_for_rtl(&widths);
1810 assert_eq!(carets, vec![40.0, 0.0, 10.0, 25.0]);
1811 assert_eq!(nearest_caret_index(&carets, 38.0), 0, "靠近右缘 → 文本起点");
1812 assert_eq!(nearest_caret_index(&carets, 2.0), 1);
1813 assert_eq!(nearest_caret_index(&carets, 24.0), 3, "靠近左缘 → 文本末尾");
1814 assert_eq!(mirror_carets_for_rtl(&[0.0]), vec![0.0]);
1816 assert_eq!(nearest_caret_index(&widths, 12.0), 1);
1817 }
1818}
1819
1820#[derive(Clone, Debug, PartialEq)]
1827pub struct RichTextSpan {
1828 pub text: String,
1829 pub size_px: f32,
1830 pub color: Option<Color>,
1832 pub font_stack: Option<String>,
1834 pub weight: Option<u16>,
1841 pub italic: bool,
1843}
1844
1845impl RichTextSpan {
1846 pub fn new(text: impl Into<String>) -> Self {
1847 Self { text: text.into(), size_px: 15.0, color: None, font_stack: None, weight: None, italic: false }
1848 }
1849
1850 pub fn with_size(mut self, size_px: f32) -> Self {
1851 self.size_px = size_px;
1852 self
1853 }
1854
1855 pub fn with_color(mut self, color: Color) -> Self {
1856 self.color = Some(color);
1857 self
1858 }
1859
1860 pub fn with_font_stack(mut self, stack: impl Into<String>) -> Self {
1861 self.font_stack = Some(stack.into());
1862 self
1863 }
1864
1865 pub fn with_weight(mut self, weight: u16) -> Self {
1867 self.weight = Some(weight.clamp(1, 1000));
1868 self
1869 }
1870
1871 pub fn bold(self) -> Self {
1873 self.with_weight(700)
1874 }
1875
1876 pub fn with_italic(mut self, italic: bool) -> Self {
1877 self.italic = italic;
1878 self
1879 }
1880
1881 pub fn italic(self) -> Self {
1883 self.with_italic(true)
1884 }
1885}
1886
1887pub type InlinePainter = std::rc::Rc<dyn Fn(&mut PaintList, Rect)>;
1889
1890#[derive(Clone)]
1892pub struct InlineItem {
1893 pub width: f32,
1894 pub height: f32,
1895 pub painter: InlinePainter,
1896}
1897
1898impl InlineItem {
1899 pub fn new(width: f32, height: f32, painter: impl Fn(&mut PaintList, Rect) + 'static) -> Self {
1900 Self { width, height, painter: std::rc::Rc::new(painter) }
1901 }
1902}
1903
1904impl std::fmt::Debug for InlineItem {
1905 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1906 f.debug_struct("InlineItem").field("width", &self.width).field("height", &self.height).finish()
1907 }
1908}
1909
1910impl PartialEq for InlineItem {
1911 fn eq(&self, other: &Self) -> bool {
1912 self.width == other.width && self.height == other.height && std::rc::Rc::ptr_eq(&self.painter, &other.painter)
1913 }
1914}
1915
1916#[derive(Clone, Debug, PartialEq)]
1918pub enum RichItem {
1919 Text(RichTextSpan),
1920 Inline(InlineItem),
1921}
1922
1923#[derive(Clone, Debug, PartialEq)]
1925pub struct RichText {
1926 text: std::rc::Rc<str>,
1927 spans: Vec<RichTextSpan>,
1928 ranges: Vec<(usize, usize)>,
1929 inlines: Vec<(usize, InlineItem)>,
1931}
1932
1933impl RichText {
1934 pub fn new(spans: Vec<RichTextSpan>) -> Self {
1935 Self::from_items(spans.into_iter().map(RichItem::Text).collect())
1936 }
1937
1938 pub fn from_items(items: Vec<RichItem>) -> Self {
1939 let mut text = String::new();
1940 let mut spans = Vec::new();
1941 let mut ranges = Vec::new();
1942 let mut inlines = Vec::new();
1943 for item in items {
1944 match item {
1945 RichItem::Text(span) => {
1946 let start = text.len();
1947 text.push_str(&span.text);
1948 spans.push(span);
1949 ranges.push((start, text.len()));
1950 }
1951 RichItem::Inline(inline) => inlines.push((text.len(), inline)),
1952 }
1953 }
1954 Self { text: text.into(), spans, ranges, inlines }
1955 }
1956
1957 pub fn plain_text(&self) -> &str {
1959 &self.text
1960 }
1961
1962 pub fn spans(&self) -> &[RichTextSpan] {
1963 &self.spans
1964 }
1965
1966 pub fn is_empty(&self) -> bool {
1967 self.text.is_empty() && self.inlines.is_empty()
1968 }
1969}
1970
1971struct RichShapedGlyph {
1972 raster_key: GlyphKey,
1973 glyph_id: u16,
1974 x: f32,
1975 span: u16,
1977}
1978
1979struct RichShapedRun {
1980 glyphs: Vec<RichShapedGlyph>,
1981 baseline_y: f32,
1982 ascent: f32,
1984 font: parley::FontData,
1987 norm_coords: std::rc::Rc<[swash::NormalizedCoord]>,
1988 raster_size: f32,
1989}
1990
1991struct RichInlineBox {
1993 id: u16,
1995 x: f32,
1996 y: f32,
1997 width: f32,
1998 height: f32,
1999 line_baseline: f32,
2001}
2002
2003struct RichShapedLine {
2004 runs: Vec<RichShapedRun>,
2005 inline_boxes: Vec<RichInlineBox>,
2006 max_x: f32,
2007 max_y: f32,
2008}
2009
2010#[derive(Clone, PartialEq, Eq, Hash)]
2011struct RichCacheKey {
2012 text: std::rc::Rc<str>,
2013 styles: Vec<(usize, usize, u32, u64)>,
2015 inlines: Vec<(usize, u32, u32)>,
2017 width_bits: Option<u32>,
2018 dpr_bits: u32,
2019 line_height_bits: u32,
2021}
2022
2023struct RichCacheEntry {
2024 line: std::rc::Rc<RichShapedLine>,
2025 last_used: u64,
2026}
2027
2028fn rich_style_signature(rich: &RichText) -> Vec<(usize, usize, u32, u64)> {
2029 let runtime = current_text_runtime();
2030 let default_stack = runtime.font_stack();
2031 rich.ranges
2032 .iter()
2033 .zip(&rich.spans)
2034 .map(|((start, end), span)| {
2035 let stack = span.font_stack.as_deref().unwrap_or(default_stack.as_str());
2036 let mut h = DefaultHasher::new();
2037 runtime.style_generation().hash(&mut h);
2038 stack.hash(&mut h);
2039 span.weight.unwrap_or(400).hash(&mut h);
2042 span.italic.hash(&mut h);
2043 (*start, *end, span.size_px.max(1.0).to_bits(), h.finish())
2044 })
2045 .collect()
2046}
2047
2048fn span_index_at(ranges: &[(usize, usize)], byte: usize) -> u16 {
2049 ranges.iter().position(|(start, end)| byte >= *start && byte < *end).unwrap_or(0) as u16
2050}
2051
2052fn shape_rich(fs: &mut FontState, rich: &RichText, max_width_px: Option<f32>) -> std::rc::Rc<RichShapedLine> {
2054 let dpr = text_dpr();
2055 let key = RichCacheKey {
2056 text: std::rc::Rc::clone(&rich.text),
2057 styles: rich_style_signature(rich),
2058 inlines: rich
2059 .inlines
2060 .iter()
2061 .map(|(index, inline)| (*index, inline.width.to_bits(), inline.height.to_bits()))
2062 .collect(),
2063 width_bits: max_width_px.map(|w| w.to_bits()),
2064 dpr_bits: dpr.to_bits(),
2065 line_height_bits: text_line_height().to_bits(),
2066 };
2067 if let Some(entry) = fs.rich_cache.get_mut(&key) {
2068 fs.rich_clock += 1;
2069 entry.last_used = fs.rich_clock;
2070 return std::rc::Rc::clone(&entry.line);
2071 }
2072
2073 let text: &str = &rich.text;
2074 let default_stack = current_text_runtime().font_stack();
2075 let mut builder = fs.layout_cx.ranged_builder(&mut fs.font_cx, text, 1.0, true);
2076 builder.push_default(parley::StyleProperty::FontSize(15.0));
2077 builder.push_default(parley::StyleProperty::LineHeight(parley::LineHeight::FontSizeRelative(text_line_height())));
2079 builder.push_default(parley::StyleProperty::FontFamily(parley::FontFamily::Source(std::borrow::Cow::Borrowed(
2080 default_stack.as_str(),
2081 ))));
2082 builder.push_default(parley::StyleProperty::WordBreak(parley::WordBreak::KeepAll));
2083 builder.push_default(parley::StyleProperty::OverflowWrap(parley::OverflowWrap::Anywhere));
2084 for ((start, end), span) in rich.ranges.iter().zip(&rich.spans) {
2085 if span.size_px > 0.0 {
2086 builder.push(parley::StyleProperty::FontSize(span.size_px), *start..*end);
2087 }
2088 if let Some(stack) = &span.font_stack {
2089 builder.push(
2090 parley::StyleProperty::FontFamily(parley::FontFamily::Source(std::borrow::Cow::Borrowed(stack))),
2091 *start..*end,
2092 );
2093 }
2094 if let Some(weight) = span.weight {
2096 builder.push(parley::StyleProperty::FontWeight(parley::FontWeight::new(weight as f32)), *start..*end);
2097 }
2098 if span.italic {
2099 builder.push(parley::StyleProperty::FontStyle(parley::FontStyle::Italic), *start..*end);
2100 }
2101 }
2102 for (id, (index, inline)) in rich.inlines.iter().enumerate() {
2103 builder.push_inline_box(parley::InlineBox {
2104 id: id as u64,
2105 index: *index,
2106 width: inline.width,
2107 height: inline.height,
2108 kind: parley::InlineBoxKind::InFlow,
2116 baseline: None,
2117 vertical_align: parley::VerticalAlign::BASELINE,
2118 });
2119 }
2120 let mut layout: parley::Layout<()> = builder.build(text);
2121 let wrap_opt = max_width_px.filter(|w| *w > 0.0);
2122 layout.break_all_lines(wrap_opt);
2123 layout.align(parley::Alignment::Start, parley::AlignmentOptions::default());
2124
2125 let mut runs = Vec::new();
2126 let mut inline_boxes = Vec::new();
2127 let mut max_x = 0.0f32;
2128 let mut max_y = 0.0f32;
2129 for line in layout.lines() {
2130 let line_m = line.metrics();
2131 let baseline_y = line_m.baseline * dpr;
2132 for item in line.items() {
2133 let parley::PositionedLayoutItem::GlyphRun(gr) = item else {
2134 if let parley::PositionedLayoutItem::InlineBox(b) = item {
2135 inline_boxes.push(RichInlineBox {
2136 id: b.id as u16,
2137 x: b.x,
2138 y: b.y,
2139 width: b.width,
2140 height: b.height,
2141 line_baseline: baseline_y,
2142 });
2143 max_x = max_x.max((b.x + b.width) * dpr);
2144 max_y = max_y.max((b.y + b.height) * dpr);
2145 }
2146 continue;
2147 };
2148 let run_metrics = gr.run().font_metrics();
2149 let ascent = run_metrics.ascent * dpr;
2150 let descent = run_metrics.descent * dpr;
2151 let font_size_phys = gr.run().font_size() * dpr;
2152 let font_blob_id = gr.run().font().data.id() as usize;
2153 let norm_coords: std::rc::Rc<[swash::NormalizedCoord]> =
2156 gr.run().normalized_coords().iter().map(|c| c.to_bits()).collect();
2157 let run_font = gr.run().font().clone();
2158 let mut pen_x = gr.offset();
2159 let mut run_glyphs = Vec::new();
2160 for cluster in gr.run().visual_clusters() {
2161 let cluster_byte = cluster.text_range().start;
2162 let span = span_index_at(&rich.ranges, cluster_byte);
2163 for g in cluster.glyphs() {
2164 let glyph_id = match narrow_glyph_id(g.id) {
2167 Some(id) => id,
2168 None => {
2169 log::warn!("mgui-text: glyph id {} 超出 swash 的 u16 范围,跳过该字形", g.id);
2170 pen_x += g.advance;
2171 continue;
2172 }
2173 };
2174 let raster_key = GlyphKey::new(
2175 raster_font_id(font_blob_id, &norm_coords),
2176 glyph_id,
2177 font_size_phys.to_bits(),
2178 0,
2179 0,
2180 0,
2181 );
2182 if !fs.raster_cache.contains_key(&raster_key) {
2183 if let Some(rg) =
2184 rasterize_one_glyph(&run_font, font_size_phys, glyph_id, &norm_coords, &mut fs.scale_cx)
2185 {
2186 insert_raster_glyph(fs, raster_key, rg);
2187 }
2188 }
2189 let gx = pen_x + g.x;
2190 run_glyphs.push(RichShapedGlyph { raster_key, glyph_id, x: gx * dpr, span });
2191 max_x = max_x.max((gx + g.advance) * dpr);
2192 max_y = max_y.max(baseline_y + descent);
2193 pen_x += g.advance;
2194 }
2195 }
2196 if !run_glyphs.is_empty() {
2197 runs.push(RichShapedRun {
2198 glyphs: run_glyphs,
2199 baseline_y,
2200 ascent,
2201 font: run_font,
2202 norm_coords,
2203 raster_size: font_size_phys,
2204 });
2205 }
2206 }
2207 }
2208 if max_y == 0.0 {
2209 max_y = rich.spans.iter().map(|s| s.size_px).fold(15.0, f32::max) * 1.2 * dpr;
2210 }
2211
2212 let line = std::rc::Rc::new(RichShapedLine { runs, inline_boxes, max_x, max_y });
2213 if fs.rich_cache.len() >= LINE_CACHE_LIMIT {
2214 fs.rich_cache.clear();
2215 }
2216 fs.rich_clock += 1;
2217 fs.rich_cache.insert(key, RichCacheEntry { line: std::rc::Rc::clone(&line), last_used: fs.rich_clock });
2218 line
2219}
2220
2221pub fn rich_text_size(rich: &RichText, max_width: Option<f32>) -> Size {
2223 if rich.is_empty() {
2224 return Size::ZERO;
2225 }
2226 with_font(|fs| {
2227 let dpr = text_dpr();
2228 let shaped = shape_rich(fs, rich, max_width);
2229 let first_baseline = shaped.runs.first().map(|r| r.baseline_y);
2230 let (anchor, fallback_h) = match first_baseline {
2231 Some(baseline) => {
2232 let first_ascent =
2234 shaped.runs.iter().filter(|r| r.baseline_y == baseline).map(|r| r.ascent).fold(0.0f32, f32::max);
2235 let inline_top = shaped
2236 .inline_boxes
2237 .iter()
2238 .filter(|b| b.line_baseline == baseline)
2239 .map(|b| b.y * dpr)
2240 .fold(f32::INFINITY, f32::min);
2241 ((baseline - first_ascent).min(inline_top), 0.0)
2243 }
2244 None => (0.0, shaped.max_y),
2245 };
2246 let height = if shaped.max_y > anchor { (shaped.max_y - anchor) / dpr } else { fallback_h / dpr };
2247 Size::new(shaped.max_x / dpr, height)
2248 })
2249}
2250
2251#[derive(Clone, Debug, PartialEq)]
2253pub struct RichTextLayout {
2254 pub size: Size,
2255 pub inline_rects: Vec<Rect>,
2256}
2257
2258pub fn rich_text_layout(rich: &RichText, max_width: Option<f32>) -> RichTextLayout {
2260 if rich.is_empty() {
2261 return RichTextLayout { size: Size::ZERO, inline_rects: Vec::new() };
2262 }
2263 with_font(|fs| {
2264 let dpr = text_dpr();
2265 let shaped = shape_rich(fs, rich, max_width);
2266 let first_baseline = shaped.runs.first().map(|r| r.baseline_y);
2267 let anchor = match first_baseline {
2268 Some(baseline) => {
2269 let first_ascent =
2270 shaped.runs.iter().filter(|r| r.baseline_y == baseline).map(|r| r.ascent).fold(0.0f32, f32::max);
2271 let inline_top = shaped
2272 .inline_boxes
2273 .iter()
2274 .filter(|b| b.line_baseline == baseline)
2275 .map(|b| b.y * dpr)
2276 .fold(f32::INFINITY, f32::min);
2277 (baseline - first_ascent).min(inline_top)
2278 }
2279 None => 0.0,
2280 };
2281 let height = if shaped.max_y > anchor { (shaped.max_y - anchor) / dpr } else { 0.0 };
2282 let mut inline_rects = vec![Rect::new(0.0, 0.0, 0.0, 0.0); rich.inlines.len()];
2283 for b in &shaped.inline_boxes {
2284 if let Some(slot) = inline_rects.get_mut(b.id as usize) {
2285 *slot = Rect::new(b.x, (b.y * dpr - anchor) / dpr, b.width, b.height);
2286 }
2287 }
2288 RichTextLayout { size: Size::new(shaped.max_x / dpr, height), inline_rects }
2289 })
2290}
2291
2292pub fn paint_rich_text(rich: &RichText, offset: Point, list: &mut PaintList, max_width: Option<f32>) -> f32 {
2294 paint_rich_text_with_default(rich, Color::WHITE, offset, list, max_width)
2295}
2296
2297pub fn paint_rich_text_with_default(
2299 rich: &RichText,
2300 default_color: Color,
2301 offset: Point,
2302 list: &mut PaintList,
2303 max_width: Option<f32>,
2304) -> f32 {
2305 if rich.is_empty() {
2306 return 0.0;
2307 }
2308 with_font(|fs| {
2309 let dpr = text_dpr();
2310 let shaped = shape_rich(fs, rich, max_width);
2311 let Some(first_run) = shaped.runs.first() else {
2312 return 0.0;
2313 };
2314 let first_baseline = first_run.baseline_y;
2315 let first_ascent =
2316 shaped.runs.iter().filter(|r| r.baseline_y == first_baseline).map(|r| r.ascent).fold(0.0f32, f32::max);
2317 let inline_top = shaped
2318 .inline_boxes
2319 .iter()
2320 .filter(|b| b.line_baseline == first_baseline)
2321 .map(|b| b.y * dpr)
2322 .fold(f32::INFINITY, f32::min);
2323 let anchor = (first_baseline - first_ascent).min(inline_top);
2324
2325 for run in &shaped.runs {
2326 for sg in &run.glyphs {
2327 if !fs.raster_cache.contains_key(&sg.raster_key) {
2328 if let Some(rg) =
2329 rasterize_one_glyph(&run.font, run.raster_size, sg.glyph_id, &run.norm_coords, &mut fs.scale_cx)
2330 {
2331 insert_raster_glyph(fs, sg.raster_key, rg);
2332 }
2333 }
2334 let Some(r) = fs.raster_cache.get_mut(&sg.raster_key) else {
2335 continue;
2336 };
2337 if r.width == 0 || r.height == 0 {
2338 continue;
2339 }
2340 fs.glyph_clock += 1;
2341 r.last_used = fs.glyph_clock;
2342 let entry = fs.atlas.get_or_insert(sg.raster_key, &r.data, r.width, r.height);
2343
2344 let x = offset.x + (sg.x + r.left as f32) / dpr;
2345 let glyph_visual_top = run.baseline_y - r.top as f32;
2346 let y = offset.y + (glyph_visual_top - anchor) / dpr;
2347 let rect = Rect::new(x, y, r.width as f32 / dpr, r.height as f32 / dpr);
2348 let color = rich.spans.get(sg.span as usize).and_then(|s| s.color).unwrap_or(default_color);
2349 list.push(PaintCommand::TexturedRect {
2350 rect,
2351 color,
2352 uv: entry.uv,
2353 texture_id: 0,
2354 mode: mgui_core::paint::TextureMode::Mask,
2355 });
2356 }
2357 }
2358 for b in &shaped.inline_boxes {
2359 if let Some((_, inline)) = rich.inlines.get(b.id as usize) {
2360 let rect = Rect::new(offset.x + b.x, offset.y + b.y - anchor / dpr, b.width, b.height);
2361 (inline.painter)(list, rect);
2362 }
2363 }
2364 shaped.max_x / dpr
2365 })
2366}
2367
2368#[cfg(test)]
2369mod rich_text_tests {
2370 use super::*;
2371
2372 #[test]
2373 fn mixed_styles_measure_and_paint_with_span_colors() {
2374 set_text_dpr(1.0);
2375 let red = Color::from_rgb8(255, 0, 0);
2376 let rich = RichText::new(vec![
2377 RichTextSpan::new("Hello ").with_size(18.0).with_color(Color::WHITE),
2378 RichTextSpan::new("World").with_size(30.0).with_color(red),
2379 ]);
2380 let size = rich_text_size(&rich, None);
2381 assert!(size.width > 0.0, "宽度必须 > 0");
2382 assert!(size.height >= 30.0, "高度应容纳 30px 字号: {size:?}");
2383
2384 let mut list = PaintList::new();
2385 let width = paint_rich_text(&rich, Point::ZERO, &mut list, None);
2386 assert!((width - size.width).abs() < 0.5, "绘制宽度应与测量一致: {width} vs {}", size.width);
2387 let colors: Vec<Color> = list
2388 .commands
2389 .iter()
2390 .filter_map(|c| match c {
2391 PaintCommand::TexturedRect { color, .. } => Some(*color),
2392 _ => None,
2393 })
2394 .collect();
2395 assert!(colors.contains(&Color::WHITE), "应包含第一段白色字形");
2396 assert!(colors.contains(&red), "应包含第二段红色字形");
2397 }
2398
2399 #[test]
2400 fn inline_item_measures_paints_and_sits_on_baseline() {
2401 use std::cell::RefCell;
2402 set_text_dpr(1.0);
2403 let captured: std::rc::Rc<RefCell<Option<Rect>>> = std::rc::Rc::new(RefCell::new(None));
2404 let cap = captured.clone();
2405 let rich = RichText::from_items(vec![
2406 RichItem::Text(RichTextSpan::new("A").with_size(16.0)),
2407 RichItem::Inline(InlineItem::new(30.0, 24.0, move |_list, rect| *cap.borrow_mut() = Some(rect))),
2408 RichItem::Text(RichTextSpan::new("B").with_size(16.0)),
2409 ]);
2410 let size = rich_text_size(&rich, None);
2411 assert!(size.width >= 30.0, "宽度应包含内联项: {size:?}");
2412 assert!(size.height >= 20.0, "高度应容纳内联项: {size:?}");
2413
2414 let mut list = PaintList::new();
2415 let width = paint_rich_text(&rich, Point::new(10.0, 5.0), &mut list, None);
2416 assert!(width >= 30.0);
2417 let rect = captured.borrow().expect("内联项绘制回调应被调用");
2418 assert!((rect.width - 30.0).abs() < 0.01 && (rect.height - 24.0).abs() < 0.01, "{rect:?}");
2419 assert!(rect.x >= 10.0 && rect.y >= 5.0, "内联项应带 offset: {rect:?}");
2420 }
2421
2422 #[test]
2423 fn inline_items_wrap_when_narrow() {
2424 set_text_dpr(1.0);
2425 let rich = RichText::from_items(vec![
2426 RichItem::Inline(InlineItem::new(40.0, 20.0, |_, _| {})),
2427 RichItem::Inline(InlineItem::new(40.0, 20.0, |_, _| {})),
2428 ]);
2429 let one_line = rich_text_size(&rich, None);
2430 let wrapped = rich_text_size(&rich, Some(50.0));
2431 assert!(one_line.width > wrapped.width, "窄宽度应减少行宽: {one_line:?} vs {wrapped:?}");
2432 assert!(
2433 wrapped.height > one_line.height * 1.5,
2434 "两个 40 宽内联项在 50 宽内应换行: {one_line:?} vs {wrapped:?}"
2435 );
2436 }
2437
2438 #[test]
2439 fn soft_wrap_uses_max_width() {
2440 set_text_dpr(1.0);
2441 let rich = RichText::new(vec![RichTextSpan::new("word ".repeat(40)).with_size(16.0)]);
2442 let single = rich_text_size(&rich, None);
2443 let wrapped = rich_text_size(&rich, Some(120.0));
2444 assert!(single.height > 0.0 && wrapped.height > 0.0);
2445 assert!(wrapped.height > single.height * 2.0, "换行后高度应显著增加: {single:?} vs {wrapped:?}");
2446 assert!(wrapped.width <= 130.0, "换行后宽度应受 max_width 约束: {wrapped:?}");
2447 }
2448
2449 #[test]
2460 fn trailing_spaces_hang_instead_of_forming_a_phantom_line() {
2461 set_text_dpr(1.0);
2462 let size = 16.0;
2463 let visible = "aaa bbb";
2464 let text = "aaa bbb ";
2465 let w_visible = measure_text_width(visible, size);
2466 let w_full = measure_text_width(text, size);
2467 assert!(w_full > w_visible + 1.0, "前置条件:尾空格要确实更宽,否则这个用例没有鉴别力");
2468 let max_width = (w_visible + w_full) * 0.5;
2469
2470 let ranges = wrapped_line_ranges(text, size, max_width);
2471 assert_eq!(ranges.len(), 1, "尾空格该挂在行外,不该另起一行:{ranges:?}(max_width={max_width})");
2472 assert_eq!(ranges[0], (0, text.len()), "唯一一行要覆盖全文,包括挂出去的空格");
2473
2474 let h = text_visual_height(text, size, Some(max_width));
2476 let h_visible_only = text_visual_height(visible, size, Some(max_width));
2477 assert!((h - h_visible_only).abs() < 0.5, "多三个尾空格不该改变块高:全文={h} 仅可见={h_visible_only}");
2478 }
2479
2480 #[test]
2481 fn span_builders_set_weight_and_italic() {
2482 assert_eq!(RichTextSpan::new("x").weight, None, "默认不指定字重(跟随 400)");
2483 assert!(!RichTextSpan::new("x").italic);
2484 assert_eq!(RichTextSpan::new("x").bold().weight, Some(700));
2485 assert_eq!(RichTextSpan::new("x").with_weight(500).weight, Some(500));
2486 assert_eq!(RichTextSpan::new("x").with_weight(0).weight, Some(1), "非法值夹紧到 ≥1");
2487 assert!(RichTextSpan::new("x").italic().italic);
2488 assert!(!RichTextSpan::new("x").with_italic(true).with_italic(false).italic);
2489 }
2490
2491 #[test]
2492 fn bold_span_is_wider_and_cache_keeps_weights_apart() {
2493 set_text_dpr(1.0);
2494 let text = "Handgloves 字重";
2495 let regular = RichText::new(vec![RichTextSpan::new(text).with_size(20.0)]);
2496 let bold = RichText::new(vec![RichTextSpan::new(text).with_size(20.0).bold()]);
2497
2498 let w_regular = rich_text_size(®ular, None).width;
2499 let w_bold = rich_text_size(&bold, None).width;
2500 assert!(w_bold > w_regular + 0.5, "粗体字面应比常规更宽: regular={w_regular} bold={w_bold}");
2501 assert!((rich_text_size(®ular, None).width - w_regular).abs() < 0.01, "缓存不能把粗体轮廓复用给常规 span");
2503
2504 let mut list = PaintList::new();
2505 let painted = paint_rich_text(&bold, Point::ZERO, &mut list, None);
2506 assert!((painted - w_bold).abs() < 0.5, "绘制宽度应与测量一致: {painted} vs {w_bold}");
2507 let glyphs = list.commands.iter().filter(|c| matches!(c, PaintCommand::TexturedRect { .. })).count();
2508 assert!(glyphs > 4, "粗体也应画出成片字形,实际 {glyphs}");
2509 }
2510
2511 #[test]
2512 fn italic_span_paints_without_changing_line_box() {
2513 set_text_dpr(1.0);
2514 let text = "Italic style";
2515 let regular = RichText::new(vec![RichTextSpan::new(text).with_size(18.0)]);
2516 let italic = RichText::new(vec![RichTextSpan::new(text).with_size(18.0).italic()]);
2517 let mut list = PaintList::new();
2518 let painted = paint_rich_text(&italic, Point::ZERO, &mut list, None);
2519 let glyphs = list.commands.iter().filter(|c| matches!(c, PaintCommand::TexturedRect { .. })).count();
2520 assert!(glyphs > 4, "斜体应照常成片绘制,实际 {glyphs}");
2521 let w_italic = rich_text_size(&italic, None).width;
2522 assert!(w_italic > 0.0, "斜体宽度有效: {w_italic}");
2523 assert!((painted - w_italic).abs() < 0.5, "斜体绘制宽度应与测量一致: {painted} vs {w_italic}");
2524 assert!(
2526 w_italic.abs() < rich_text_size(®ular, None).width * 2.0,
2527 "斜体宽度应与常规同量级: italic={w_italic}"
2528 );
2529 }
2530
2531 #[test]
2532 fn raster_font_id_folds_variation_coords() {
2533 assert_eq!(raster_font_id(42, &[]), 42);
2535 let a: [swash::NormalizedCoord; 1] = [1];
2536 let b: [swash::NormalizedCoord; 1] = [2];
2537 let coords_a: &[swash::NormalizedCoord] = &a;
2538 let coords_b: &[swash::NormalizedCoord] = &b;
2539 assert_ne!(raster_font_id(42, coords_a), raster_font_id(42, coords_b), "不同可变轴坐标必须是不同栅格身份");
2540 assert_eq!(raster_font_id(42, coords_a), raster_font_id(42, coords_a), "同坐标必须稳定(缓存命中)");
2541 assert_ne!(raster_font_id(42, coords_a), raster_font_id(43, coords_a), "不同 blob 也必须区分");
2542 }
2543}
2544
2545#[cfg(test)]
2550mod multiline_regression {
2551 use super::*;
2552
2553 #[test]
2555 fn multiline_text_lines_have_distinct_y() {
2556 let mut list = PaintList::new();
2557 paint_text_line("第一行AAA\n第二行BBB", 20.0, Color::WHITE, Point::new(50.0, 100.0), &mut list, None);
2558 let ys: Vec<f32> = list
2559 .commands
2560 .iter()
2561 .filter_map(|c| match c {
2562 PaintCommand::TexturedRect { rect, .. } => Some((rect.y * 10.0).round() / 10.0),
2563 _ => None,
2564 })
2565 .collect();
2566 assert!(!ys.is_empty(), "应画出 glyph");
2567 let y0 = ys[0];
2568 assert!(ys.iter().any(|&y| (y - y0).abs() > 20.0), "多行文本各行 y 必须拉开,实际全部≈{}: {:?}", y0, ys);
2569 }
2570
2571 #[test]
2573 fn wrapped_text_lines_have_distinct_y() {
2574 let mut list = PaintList::new();
2575 paint_text_line(
2577 "第一行文本内容比较长需要折行",
2578 20.0,
2579 Color::WHITE,
2580 Point::new(0.0, 0.0),
2581 &mut list,
2582 Some(60.0),
2583 );
2584 let ys: Vec<f32> = list
2585 .commands
2586 .iter()
2587 .filter_map(|c| match c {
2588 PaintCommand::TexturedRect { rect, .. } => Some((rect.y * 10.0).round() / 10.0),
2589 _ => None,
2590 })
2591 .collect();
2592 let y0 = ys[0];
2593 assert!(ys.iter().any(|&y| (y - y0).abs() > 20.0), "soft-wrap 多行 y 必须拉开,实际全部≈{}: {:?}", y0, ys);
2594 }
2595}