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
415const LINE_CACHE_LIMIT: usize = 4096;
424
425const LINE_CACHE_TARGET: usize = LINE_CACHE_LIMIT - LINE_CACHE_LIMIT / 4;
427
428fn evict_line_cache_lru(fs: &mut FontState) {
430 if fs.line_cache.len() <= LINE_CACHE_TARGET {
431 return;
432 }
433 let mut by_age: Vec<(u64, LineCacheKey)> = fs.line_cache.iter().map(|(k, v)| (v.last_used, k.clone())).collect();
434 by_age.sort_unstable_by_key(|&(last_used, _)| last_used);
435 let remove = fs.line_cache.len().saturating_sub(LINE_CACHE_TARGET);
436 for (_, key) in by_age.into_iter().take(remove) {
437 fs.line_cache.remove(&key);
438 }
439}
440
441const RASTER_CACHE_BUDGET_BYTES: usize = 32 * 1024 * 1024;
443const RASTER_CACHE_TARGET_BYTES: usize = RASTER_CACHE_BUDGET_BYTES * 3 / 4;
445
446fn insert_raster_glyph(fs: &mut FontState, key: GlyphKey, mut glyph: RasterGlyph) {
448 fs.glyph_clock += 1;
449 glyph.last_used = fs.glyph_clock;
450 let bytes = glyph.data.len();
451 if let Some(old) = fs.raster_cache.insert(key, glyph) {
452 fs.raster_cache_bytes = fs.raster_cache_bytes.saturating_sub(old.data.len());
453 }
454 fs.raster_cache_bytes += bytes;
455 trim_raster_cache(fs);
456}
457
458fn trim_raster_cache(fs: &mut FontState) {
463 if fs.raster_cache_bytes <= RASTER_CACHE_BUDGET_BYTES {
464 return;
465 }
466 let mut candidates: Vec<(u64, GlyphKey, usize)> =
467 fs.raster_cache.iter().map(|(&key, g)| (g.last_used, key, g.data.len())).collect();
468 candidates.sort_unstable_by_key(|&(last_used, _, _)| last_used);
469 for (_, key, bytes) in candidates {
470 if fs.raster_cache_bytes <= RASTER_CACHE_TARGET_BYTES {
471 break;
472 }
473 fs.raster_cache.remove(&key);
474 fs.raster_cache_bytes = fs.raster_cache_bytes.saturating_sub(bytes);
475 }
476}
477
478#[derive(Clone, PartialEq, Eq, Hash)]
484enum TextKey {
485 Owned(String),
486 Shared(std::rc::Rc<str>, Option<(usize, usize)>),
487}
488
489impl TextKey {
490 fn owned(text: &str) -> Self {
491 TextKey::Owned(text.to_string())
492 }
493}
494
495struct ShapedGlyph {
497 raster_key: GlyphKey,
499 glyph_id: u16,
501 x: f32,
503 w: f32,
505 #[allow(dead_code)]
507 y: f32,
508 ascent: f32,
510 descent: f32,
512 cluster: u32,
515}
516
517struct ShapedRun {
519 glyphs: Vec<ShapedGlyph>,
520 baseline_y: f32,
522 font: parley::FontData,
526 norm_coords: std::rc::Rc<[swash::NormalizedCoord]>,
528 raster_size: f32,
530}
531
532struct ShapedLine {
534 runs: Vec<ShapedRun>,
535 max_x: f32,
537 #[allow(dead_code)]
539 max_y: f32,
540 visual_lines: Vec<(usize, usize)>,
542}
543
544fn shape_text(
549 fs: &mut FontState,
550 text: &str,
551 raster_px: f32,
552 max_width_px: Option<f32>,
553 font_stack: &str,
554) -> std::rc::Rc<ShapedLine> {
555 shape_text_keyed(fs, text, TextKey::owned(text), raster_px, max_width_px, font_stack)
556}
557
558fn shape_text_keyed(
561 fs: &mut FontState,
562 text: &str,
563 text_key: TextKey,
564 raster_px: f32,
565 max_width_px: Option<f32>,
566 font_stack: &str,
567) -> std::rc::Rc<ShapedLine> {
568 let runtime = current_text_runtime();
569 let font_stack_hash = {
570 let mut h = DefaultHasher::new();
571 runtime.style_generation().hash(&mut h);
574 font_stack.hash(&mut h);
575 h.finish()
576 };
577 let line_height = text_line_height();
578 let key =
579 (text_key, raster_px.to_bits(), max_width_px.map(|w| w.to_bits()), font_stack_hash, line_height.to_bits());
580 if let Some(entry) = fs.line_cache.get_mut(&key) {
581 fs.line_clock += 1;
582 entry.last_used = fs.line_clock;
583 return std::rc::Rc::clone(&entry.line);
584 }
585
586 fs.shape_calls += 1;
587 let dpr = text_dpr();
588
589 let scale = 1.0f32;
592 let font_size_px = raster_px / dpr;
593
594 let wrap_opt = max_width_px.filter(|&w| w > 0.0);
596
597 let mut builder = fs.layout_cx.ranged_builder(&mut fs.font_cx, text, scale, true);
598 builder.push_default(parley::StyleProperty::FontSize(font_size_px));
599 builder.push_default(parley::StyleProperty::LineHeight(parley::LineHeight::FontSizeRelative(line_height)));
605 builder.push_default(parley::StyleProperty::FontFamily(parley::FontFamily::Source(std::borrow::Cow::Borrowed(
608 font_stack,
609 ))));
610 builder.push_default(parley::StyleProperty::WordBreak(parley::WordBreak::KeepAll));
613 builder.push_default(parley::StyleProperty::OverflowWrap(parley::OverflowWrap::Anywhere));
614 let mut layout: parley::Layout<()> = builder.build(text);
615 layout.break_all_lines(wrap_opt);
616 layout.align(parley::Alignment::Start, parley::AlignmentOptions::default());
619
620 let mut runs = Vec::new();
624 let mut max_x = 0.0f32;
625 let mut max_y = 0.0f32;
626 let mut visual_lines = Vec::new();
627
628 for line in layout.lines() {
629 let mut line_start = usize::MAX;
631 let mut line_end = 0usize;
632 for run in line.runs() {
633 let range = run.text_range();
634 line_start = line_start.min(range.start);
635 line_end = line_end.max(range.end);
636 }
637 visual_lines.push(if line_start == usize::MAX { (0, 0) } else { (line_start, line_end) });
638
639 let line_m = line.metrics();
640 let baseline_y = line_m.baseline * dpr; for item in line.items() {
643 let parley::PositionedLayoutItem::GlyphRun(gr) = item else {
644 continue;
645 };
646
647 let run_metrics = gr.run().font_metrics();
651 let ascent = run_metrics.ascent * dpr;
652 let descent = run_metrics.descent * dpr;
653 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();
664 let norm_coords: std::rc::Rc<[swash::NormalizedCoord]> =
670 gr.run().normalized_coords().iter().map(|c| c.to_bits()).collect();
671 let run_font = gr.run().font().clone();
672 let mut pen_x = gr.offset();
673 let run_baseline = gr.baseline();
674 for cluster in gr.run().visual_clusters() {
675 let cluster_byte = cluster.text_range().start as u32;
676 for g in cluster.glyphs() {
677 let glyph_id = match narrow_glyph_id(g.id) {
680 Some(id) => id,
681 None => {
682 log::warn!("mgui-text: glyph id {} 超出 swash 的 u16 范围,跳过该字形", g.id);
683 pen_x += g.advance;
684 continue;
685 }
686 };
687 let size_bits = font_size_phys.to_bits(); let x_bin = 0; let y_bin = 0;
690 let raster_key =
691 GlyphKey::new(raster_font_id(font_blob_id, &norm_coords), glyph_id, size_bits, x_bin, y_bin, 0);
692 if !fs.raster_cache.contains_key(&raster_key) {
694 if let Some(rg) =
695 rasterize_one_glyph(&run_font, font_size_phys, glyph_id, &norm_coords, &mut fs.scale_cx)
696 {
697 insert_raster_glyph(fs, raster_key, rg);
698 }
699 }
700 let gx = pen_x + g.x;
701 run_glyphs.push(ShapedGlyph {
702 raster_key,
703 glyph_id,
704 x: gx * dpr, w: g.advance * dpr, y: (run_baseline + g.y) * dpr, ascent,
708 descent,
709 cluster: cluster_byte,
710 });
711 max_x = max_x.max((gx + g.advance) * dpr);
712 max_y = max_y.max(baseline_y + descent);
713 pen_x += g.advance;
714 }
715 }
716
717 if !run_glyphs.is_empty() {
718 runs.push(ShapedRun {
719 glyphs: run_glyphs,
720 baseline_y,
721 font: run_font,
722 norm_coords,
723 raster_size: font_size_phys,
724 });
725 }
726 }
727 }
728
729 if max_y == 0.0 {
731 max_y = raster_px * 1.2;
732 }
733
734 let line = std::rc::Rc::new(ShapedLine { runs, max_x, max_y, visual_lines });
735 if fs.line_cache.len() >= LINE_CACHE_LIMIT {
736 evict_line_cache_lru(fs);
737 }
738 fs.line_clock += 1;
739 let entry = LineCacheEntry { line: std::rc::Rc::clone(&line), last_used: fs.line_clock };
740 fs.line_cache.insert(key, entry);
741 line
742}
743
744#[derive(Clone)]
752pub struct AtlasSnapshot {
753 pub width: u32,
754 pub height: u32,
755 pub dirty: bool,
756 pub dirty_y: (u32, u32),
759 pub pixels: Option<Vec<u8>>,
761}
762
763pub fn atlas_snapshot() -> AtlasSnapshot {
765 with_font(|fs| {
766 let dirty = fs.atlas.is_dirty();
767 let (y0, y1) = if dirty {
768 let (a, b) = fs.atlas.dirty_rows.unwrap_or((0, fs.atlas.height));
769 (a.min(fs.atlas.height), b.min(fs.atlas.height))
770 } else {
771 (0, 0)
772 };
773 let pixels = if dirty {
774 let w = fs.atlas.width as usize;
775 Some(fs.atlas.pixels()[(y0 as usize * w)..(y1 as usize * w)].to_vec())
776 } else {
777 None
778 };
779 AtlasSnapshot { width: fs.atlas.width, height: fs.atlas.height, dirty, dirty_y: (y0, y1), pixels }
780 })
781}
782
783pub fn atlas_clear_dirty() {
785 with_font(|fs| {
786 fs.atlas.clear_dirty();
787 })
788}
789
790pub fn atlas_generation() -> u64 {
792 with_font(|fs| fs.atlas.generation)
793}
794
795#[derive(Clone, Copy, Debug, Default)]
797pub struct AtlasStats {
798 pub width: u32,
799 pub height: u32,
800 pub glyph_count: usize,
801 pub used_height: u32,
803 pub dirty: bool,
804}
805
806pub fn atlas_stats() -> AtlasStats {
807 with_font(|fs| {
808 let atlas = &fs.atlas;
809 AtlasStats {
810 width: atlas.width,
811 height: atlas.height,
812 glyph_count: atlas.entries.len(),
813 used_height: (atlas.next_y + atlas.row_height).min(atlas.height),
814 dirty: atlas.dirty,
815 }
816 })
817}
818
819pub fn with_atlas<R>(f: impl FnOnce(u32, u32, &[u8]) -> R) -> R {
824 with_font(|fs| {
825 let atlas = &fs.atlas;
826 f(atlas.width, atlas.height, &atlas.pixels)
827 })
828}
829
830pub struct TextRenderObject {
835 text: String,
836 size_px: f32,
837 color: Color,
838 max_width: Option<f32>,
840 max_width_explicit: bool,
843 size: Size,
845 element_id: Option<ElementId>,
846}
847
848impl TextRenderObject {
849 pub fn new(text: String, size_px: f32, color: Color) -> Self {
850 Self { text, size_px, color, max_width: None, max_width_explicit: false, size: Size::ZERO, element_id: None }
851 }
852
853 pub fn with_max_width(mut self, max_width: f32) -> Self {
854 self.max_width = Some(max_width);
855 self.max_width_explicit = true;
856 self
857 }
858
859 pub fn set_max_width(&mut self, max_width: Option<f32>) {
860 self.max_width = max_width;
861 self.max_width_explicit = max_width.is_some();
862 }
863
864 fn measure(&self) -> Size {
866 let dpr = text_dpr();
867 let raster_px = self.size_px * dpr;
868 let font_stack = current_text_runtime().font_stack();
869 let width = with_font(|fs| {
870 let line = shape_text(fs, &self.text, raster_px, self.max_width, &font_stack);
871 let max_x = line.max_x / dpr;
872 if max_x == 0.0 && !self.text.is_empty() {
873 self.text.chars().count() as f32 * FALLBACK_ADVANCE_X
874 } else {
875 max_x
876 }
877 });
878 let height = text_visual_height(&self.text, self.size_px, self.max_width);
881 Size::new(width, height)
882 }
883}
884
885pub fn measure_text_width(text: &str, size_px: f32) -> f32 {
889 let font_stack = current_text_runtime().font_stack();
890 measure_text_width_styled(text, size_px, &font_stack)
891}
892
893pub fn measure_text_width_styled(text: &str, size_px: f32, font_stack: &str) -> f32 {
895 if text.is_empty() {
896 return 0.0;
897 }
898 with_font(|fs| {
899 let dpr = text_dpr();
901 let raster_px = size_px * dpr;
902 let line = shape_text(fs, text, raster_px, None, font_stack);
903 let w = line.max_x / dpr;
904 if w == 0.0 {
905 text.chars().count() as f32 * FALLBACK_ADVANCE_X
906 } else {
907 w
908 }
909 })
910}
911
912pub fn text_visual_height(text: &str, size_px: f32, max_width_px: Option<f32>) -> f32 {
922 let font_stack = current_text_runtime().font_stack();
923 text_visual_height_styled(text, size_px, max_width_px, &font_stack)
924}
925
926pub fn text_visual_height_styled(text: &str, size_px: f32, max_width_px: Option<f32>, font_stack: &str) -> f32 {
928 if text.is_empty() {
929 return size_px;
930 }
931 with_font(|fs| {
932 let dpr = text_dpr();
933 let raster_px = size_px * dpr;
934 let line = shape_text(fs, text, raster_px, max_width_px, font_stack);
935
936 if line.runs.is_empty() {
937 return size_px;
938 }
939
940 let first_run = &line.runs[0];
942 let first_ascent = first_run.glyphs.first().map(|g| g.ascent).unwrap_or(raster_px);
943 let first_baseline = first_run.baseline_y;
944 let visual_top = first_baseline - first_ascent;
945
946 let mut visual_bottom = 0.0f32;
948 for run in &line.runs {
949 for sg in &run.glyphs {
950 let bottom = run.baseline_y + sg.descent;
951 visual_bottom = visual_bottom.max(bottom);
952 }
953 }
954
955 if visual_bottom > visual_top {
956 (visual_bottom - visual_top) / dpr
957 } else {
958 size_px
959 }
960 })
961}
962
963pub fn paint_text_line(
969 text: &str,
970 size_px: f32,
971 color: Color,
972 offset: Point,
973 list: &mut PaintList,
974 max_width_px: Option<f32>,
975) -> f32 {
976 let font_stack = current_text_runtime().font_stack();
977 paint_text_line_impl(text, TextKey::owned(text), size_px, color, offset, list, max_width_px, &font_stack)
978}
979
980#[allow(clippy::too_many_arguments)]
982pub fn paint_text_line_styled(
983 text: &str,
984 size_px: f32,
985 color: Color,
986 offset: Point,
987 list: &mut PaintList,
988 max_width_px: Option<f32>,
989 font_stack: &str,
990) -> f32 {
991 paint_text_line_impl(text, TextKey::owned(text), size_px, color, offset, list, max_width_px, font_stack)
992}
993
994#[allow(clippy::too_many_arguments)]
999pub fn paint_text_span(
1000 text: &std::rc::Rc<str>,
1001 range: Option<(usize, usize)>,
1002 size_px: f32,
1003 color: Color,
1004 offset: Point,
1005 list: &mut PaintList,
1006 max_width_px: Option<f32>,
1007) -> f32 {
1008 let (start, end) = match range {
1009 Some(r) => clamp_char_range(text, r),
1010 None => (0, text.len()),
1011 };
1012 let font_stack = current_text_runtime().font_stack();
1013 paint_text_line_impl(
1014 &text[start..end],
1015 TextKey::Shared(std::rc::Rc::clone(text), range),
1016 size_px,
1017 color,
1018 offset,
1019 list,
1020 max_width_px,
1021 &font_stack,
1022 )
1023}
1024
1025pub fn text_ascent(text: &str, size_px: f32) -> f32 {
1031 if text.is_empty() {
1032 return size_px;
1033 }
1034 let font_stack = current_text_runtime().font_stack();
1035 with_font(|fs| {
1036 let dpr = text_dpr();
1037 let shaped = shape_text(fs, text, size_px * dpr, None, &font_stack);
1038 first_glyph_ascent(&shaped).map(|a| a / dpr).unwrap_or(size_px)
1039 })
1040}
1041
1042pub fn text_span_ascent(text: &std::rc::Rc<str>, range: Option<(usize, usize)>, size_px: f32) -> f32 {
1045 let (start, end) = match range {
1046 Some(r) => clamp_char_range(text, r),
1047 None => (0, text.len()),
1048 };
1049 if start >= end {
1050 return size_px;
1051 }
1052 let font_stack = current_text_runtime().font_stack();
1053 with_font(|fs| {
1054 let dpr = text_dpr();
1055 let shaped = shape_text_keyed(
1056 fs,
1057 &text[start..end],
1058 TextKey::Shared(std::rc::Rc::clone(text), range),
1059 size_px * dpr,
1060 None,
1061 &font_stack,
1062 );
1063 first_glyph_ascent(&shaped).map(|a| a / dpr).unwrap_or(size_px)
1064 })
1065}
1066
1067fn first_glyph_ascent(shaped: &ShapedLine) -> Option<f32> {
1068 shaped.runs.first().and_then(|r| r.glyphs.first()).map(|g| g.ascent)
1069}
1070
1071fn clamp_char_range(text: &str, range: (usize, usize)) -> (usize, usize) {
1073 let mut start = range.0.min(text.len());
1074 let mut end = range.1.min(text.len());
1075 while !text.is_char_boundary(start) {
1076 start += 1;
1077 }
1078 while !text.is_char_boundary(end) {
1079 end -= 1;
1080 }
1081 if end < start {
1082 end = start;
1083 }
1084 (start, end)
1085}
1086
1087#[allow(clippy::too_many_arguments)]
1089fn paint_text_line_impl(
1090 text: &str,
1091 text_key: TextKey,
1092 size_px: f32,
1093 color: Color,
1094 offset: Point,
1095 list: &mut PaintList,
1096 max_width_px: Option<f32>,
1097 font_stack: &str,
1098) -> f32 {
1099 if text.is_empty() {
1100 return 0.0;
1101 }
1102 let width = with_font(|fs| {
1103 let dpr = text_dpr();
1104 let raster_px = size_px * dpr;
1105 let shaped = shape_text_keyed(fs, text, text_key, raster_px, max_width_px, font_stack);
1106
1107 let first_run = match shaped.runs.first() {
1111 Some(r) => r,
1112 None => return 0.0,
1113 };
1114 let first_ascent = first_run.glyphs.first().map(|g| g.ascent).unwrap_or(raster_px);
1115 let first_baseline = first_run.baseline_y;
1116 let anchor = first_baseline - first_ascent; let mut max_x = 0.0f32;
1119 for run in &shaped.runs {
1120 for sg in &run.glyphs {
1121 if !fs.raster_cache.contains_key(&sg.raster_key) {
1124 if let Some(rg) =
1125 rasterize_one_glyph(&run.font, run.raster_size, sg.glyph_id, &run.norm_coords, &mut fs.scale_cx)
1126 {
1127 insert_raster_glyph(fs, sg.raster_key, rg);
1128 }
1129 }
1130 let Some(r) = fs.raster_cache.get_mut(&sg.raster_key) else {
1134 continue;
1135 };
1136 if r.width == 0 || r.height == 0 {
1137 continue;
1138 }
1139 fs.glyph_clock += 1;
1140 r.last_used = fs.glyph_clock;
1141 let entry = fs.atlas.get_or_insert(sg.raster_key, &r.data, r.width, r.height);
1142
1143 let x = offset.x + (sg.x + r.left as f32) / dpr;
1145 let glyph_visual_top = run.baseline_y - r.top as f32;
1150 let y = offset.y + (glyph_visual_top - anchor) / dpr;
1151
1152 let rect = Rect::new(x, y, r.width as f32 / dpr, r.height as f32 / dpr);
1153 list.push(PaintCommand::TexturedRect {
1154 rect,
1155 color,
1156 uv: entry.uv,
1157 texture_id: 0,
1158 mode: mgui_core::paint::TextureMode::Mask,
1159 });
1160 max_x = max_x.max((sg.x + sg.w) / dpr);
1161 }
1162 }
1163 if max_x == 0.0 {
1164 max_x = text.chars().count() as f32 * FALLBACK_ADVANCE_X;
1165 }
1166 max_x
1167 });
1168 width
1169}
1170
1171pub fn wrapped_line_ranges(text: &str, size_px: f32, max_width: f32) -> Vec<(usize, usize)> {
1186 if text.is_empty() {
1187 return vec![(0, 0)];
1188 }
1189 if max_width <= 0.0 {
1190 return vec![(0, text.len())];
1191 }
1192 let font_stack = current_text_runtime().font_stack();
1193 with_font(|fs| {
1194 let dpr = text_dpr();
1195 let raster_px = size_px * dpr;
1196 let shaped = shape_text(fs, text, raster_px, Some(max_width), &font_stack);
1197 shaped.visual_lines.clone()
1198 })
1199}
1200
1201pub fn measure_char_prefix_widths(text: &str, size_px: f32, font_stack: &str) -> Vec<f32> {
1202 if text.is_empty() {
1203 return vec![0.0];
1204 }
1205 with_font(|fs| {
1206 let dpr = text_dpr();
1207 let raster_px = size_px * dpr;
1208 let shaped = shape_text(fs, text, raster_px, None, font_stack);
1209
1210 let char_count = text.chars().count();
1211 let mut widths = vec![0.0f32; char_count + 1];
1212
1213 let mut byte_x: Vec<(u32, f32)> = Vec::new();
1216 for run in &shaped.runs {
1217 for sg in &run.glyphs {
1218 match byte_x.last_mut() {
1219 Some((b, _)) if *b == sg.cluster => {}
1220 _ => byte_x.push((sg.cluster, sg.x)),
1221 }
1222 }
1223 }
1224
1225 let mut prev = 0.0f32;
1228 let mut bi = 0usize;
1229 for (ci, (byte_pos, _)) in text.char_indices().enumerate() {
1230 while bi < byte_x.len() && byte_x[bi].0 <= byte_pos as u32 {
1231 prev = byte_x[bi].1 / dpr;
1232 bi += 1;
1233 }
1234 widths[ci] = prev;
1235 }
1236 widths[char_count] = shaped.max_x / dpr;
1237 widths
1238 })
1239}
1240
1241fn rasterize_one_glyph(
1243 font: &parley::FontData,
1244 font_size: f32,
1245 glyph_id: u16,
1246 norm_coords: &[swash::NormalizedCoord],
1247 scale_cx: &mut swash::scale::ScaleContext,
1248) -> Option<RasterGlyph> {
1249 let bytes = font.data.data();
1251 if bytes.is_empty() {
1252 return None;
1253 }
1254 let font_ref = swash::FontRef::from_index(bytes, font.index as usize)?;
1255 let mut scaler =
1256 scale_cx.builder(font_ref).size(font_size).normalized_coords(norm_coords.iter()).hint(true).build();
1257 let image = swash::scale::Render::new(&[
1258 swash::scale::Source::ColorOutline(0),
1259 swash::scale::Source::ColorBitmap(swash::scale::StrikeWith::BestFit),
1260 swash::scale::Source::Outline,
1261 ])
1262 .render(&mut scaler, glyph_id)?;
1263 if image.placement.width == 0 || image.placement.height == 0 {
1264 return Some(RasterGlyph { data: Vec::new(), width: 0, height: 0, left: 0, top: 0, last_used: 0 });
1269 }
1270 Some(RasterGlyph {
1271 data: image.data.to_vec(),
1272 width: image.placement.width,
1273 height: image.placement.height,
1274 left: image.placement.left,
1275 top: image.placement.top,
1276 last_used: 0,
1277 })
1278}
1279
1280impl RenderObject for TextRenderObject {
1281 fn layout(&mut self, _bc: BoxConstraints, _ctx: &mut LayoutContext) -> Size {
1282 let s = self.measure();
1293 self.size = s;
1294 s
1295 }
1296
1297 fn content_size(&self) -> Size {
1298 self.size
1299 }
1300
1301 fn paint(&self, offset: Point, list: &mut PaintList) {
1302 paint_text_line(&self.text, self.size_px, self.color, offset, list, self.max_width);
1303 }
1304
1305 fn set_element_id(&mut self, id: ElementId) {
1306 self.element_id = Some(id);
1307 }
1308
1309 fn hit_test(&self, position: Point, offset: Point) -> Option<ElementId> {
1310 let r = Rect::new(offset.x, offset.y, self.size.width, self.size.height);
1314 if r.contains(position) {
1315 self.element_id
1316 } else {
1317 None
1318 }
1319 }
1320}
1321
1322#[cfg(test)]
1327mod tests {
1328 use super::*;
1329 use crate::runtime::{with_text_runtime, TextRuntime};
1330
1331 fn mk_key(id: u32) -> GlyphKey {
1332 GlyphKey(id as u64)
1333 }
1334
1335 #[test]
1336 fn atlas_get_or_insert_dedupes() {
1337 let mut a = Atlas::new(64, 64);
1338 let k = mk_key(1);
1339 let e1 = a.get_or_insert(k, &[255; 8], 2, 4);
1340 let e2 = a.get_or_insert(k, &[0; 8], 2, 4);
1341 assert_eq!(e1.uv, e2.uv, "重复 key 必须返回同一 entry");
1342 assert_eq!(a.glyph_count(), 1);
1343 }
1344
1345 #[test]
1346 fn atlas_wraps_to_next_row() {
1347 let mut a = Atlas::new(20, 20);
1348 let k1 = mk_key(1);
1350 a.get_or_insert(k1, &[1; 64], 16, 4);
1351 let k2 = mk_key(2);
1353 let e2 = a.get_or_insert(k2, &[2; 64], 16, 4);
1354 assert!(e2.uv[1] > 0.0, "第二个 glyph 应该换行,uv.v0 > 0");
1355 }
1356
1357 #[test]
1358 fn atlas_dirty_flag_lifecycle() {
1359 let mut a = Atlas::new(64, 64);
1360 assert!(!a.is_dirty());
1362 a.get_or_insert(mk_key(1), &[255; 8], 2, 4);
1364 assert!(a.is_dirty(), "get_or_insert 后应该 dirty");
1365 a.clear_dirty();
1367 assert!(!a.is_dirty());
1368 a.get_or_insert(mk_key(1), &[0; 8], 2, 4);
1370 assert!(!a.is_dirty(), "重复 key 不应触发 dirty");
1371 a.get_or_insert(mk_key(2), &[0; 8], 2, 4);
1373 assert!(a.is_dirty());
1374 }
1375
1376 #[test]
1379 fn atlas_snapshot_uploads_only_dirty_rows() {
1380 let width = with_font(|fs| {
1382 fs.atlas = Atlas::new(ATLAS_SIZE, ATLAS_SIZE);
1383 fs.atlas.width
1384 });
1385 with_font(|fs| {
1386 fs.atlas.get_or_insert(GlyphKey::new(7, 7, 0, 0, 0, 0), &[9u8; 16], 4, 4);
1387 fs.atlas.get_or_insert(GlyphKey::new(7, 8, 0, 0, 0, 0), &[9u8; 16], 4, 4);
1388 assert_eq!(fs.atlas.dirty_rows, Some((1, 5)), "同一行的写入应合并为单行带");
1389 });
1390 let snap = atlas_snapshot();
1391 assert!(snap.dirty);
1392 assert_eq!(snap.dirty_y, (1, 5));
1393 assert_eq!(snap.pixels.as_ref().map(Vec::len), Some(width as usize * 4), "快照只拷贝 dirty 行");
1394 atlas_clear_dirty();
1395 let clean = atlas_snapshot();
1396 assert!(!clean.dirty);
1397 assert_eq!(clean.dirty_y, (0, 0));
1398 assert!(clean.pixels.is_none());
1399 }
1400
1401 #[test]
1403 fn atlas_auto_expands_when_full() {
1404 let mut a = Atlas::new(32, 32);
1405 let e_before = a.get_or_insert(mk_key(1), &[100; 9], 3, 3);
1407 let uv_scalar_before = e_before.uv[0]; let big: Vec<u8> = vec![200; 400]; for i in 2..10 {
1413 a.get_or_insert(mk_key(i), &big, 20, 20);
1414 }
1415 assert!(a.width >= 32, "atlas 应保持原尺寸或扩容");
1417 assert!(a.glyph_count() >= 8, "扩容后应能放下 8+ glyphs,实际 {}", a.glyph_count());
1418
1419 if a.width > 32 {
1421 let e_after = a.get_or_insert(mk_key(1), &[0; 9], 3, 3);
1423 let expected = uv_scalar_before / 2.0;
1426 assert!((e_after.uv[0] - expected).abs() < 0.01, "扩容后 uv.u0 应为 {expected}, 实际 {}", e_after.uv[0]);
1427 }
1428 }
1429
1430 #[test]
1432 fn atlas_accepts_new_glyphs_after_expansion() {
1433 let mut a = Atlas::new(16, 16);
1434 a.get_or_insert(mk_key(1), &[50; 144], 12, 12);
1436 let e2 = a.get_or_insert(mk_key(2), &[100; 144], 12, 12);
1438 assert!(a.width > 16 || a.height > 16, "应该扩容了");
1439 let e1 = a.get_or_insert(mk_key(1), &[0; 144], 12, 12);
1441 assert!(e2.uv[1] >= e1.uv[1], "第二个 glyph 应在第一个下方");
1442 }
1443
1444 #[test]
1445 fn text_measure_produces_nonzero_size() {
1446 let t = TextRenderObject::new("Hello".into(), 24.0, Color::WHITE);
1447 let s = t.measure();
1448 assert!(s.width > 0.0, "width should be > 0 for 'Hello'");
1449 assert!(s.height > 0.0, "height should be > 0");
1450 }
1451
1452 #[test]
1453 fn text_paint_emits_textured_rects() {
1454 let t = TextRenderObject::new("Hi".into(), 24.0, Color::WHITE);
1455 let mut list = PaintList::new();
1456 t.paint(Point::new(0.0, 0.0), &mut list);
1457 assert!(!list.is_empty(), "paint should emit at least 1 textured rect");
1459 for cmd in &list.commands {
1460 match cmd {
1461 PaintCommand::TexturedRect { texture_id, uv, .. } => {
1462 assert_eq!(*texture_id, 0);
1463 assert!(uv[0] < uv[2]);
1464 assert!(uv[1] < uv[3]);
1465 }
1466 _ => panic!("expected TexturedRect, got Rect"),
1467 }
1468 }
1469 }
1470
1471 #[test]
1472 fn text_paint_with_offset_shifts_rects() {
1473 let t = TextRenderObject::new("X".into(), 24.0, Color::WHITE);
1474 let mut list = PaintList::new();
1475 t.paint(Point::new(100.0, 50.0), &mut list);
1476 for cmd in &list.commands {
1478 if let PaintCommand::TexturedRect { rect, .. } = cmd {
1479 assert!(rect.x >= 100.0 - 1.0, "x={}", rect.x);
1480 assert!(rect.y >= 50.0 - 1.0, "y={}", rect.y);
1481 }
1482 }
1483 }
1484
1485 #[test]
1487 fn shape_line_cache_hits_second_paint() {
1488 let mut list1 = PaintList::new();
1489 paint_text_line("cache-hit-test", 20.0, Color::WHITE, Point::ZERO, &mut list1, None);
1490 let calls_1 = with_font(|fs| fs.shape_calls);
1491
1492 let mut list2 = PaintList::new();
1493 paint_text_line("cache-hit-test", 20.0, Color::WHITE, Point::new(5.0, 5.0), &mut list2, None);
1494 let calls_2 = with_font(|fs| fs.shape_calls);
1495
1496 assert_eq!(calls_1, calls_2, "第二次 paint 应命中缓存,不再 shape");
1497 assert_eq!(list1.commands.len(), list2.commands.len(), "缓存命中的绘制输出数量应一致");
1498 }
1499
1500 #[test]
1501 fn line_height_is_in_shape_cache_key_and_changes_geometry() {
1502 set_text_line_height(1.2);
1504 let mut list = PaintList::new();
1505 paint_text_line("leading-probe", 20.0, Color::WHITE, Point::ZERO, &mut list, None);
1506 let find_line = |fs: &FontState, lhs: u32| -> Option<std::rc::Rc<ShapedLine>> {
1507 fs.line_cache
1508 .iter()
1509 .find(|(k, _)| k.0 == TextKey::Owned("leading-probe".into()) && k.4 == lhs)
1510 .map(|(_, e)| std::rc::Rc::clone(&e.line))
1511 };
1512 let line_12 = with_font(|fs| find_line(fs, 1.2f32.to_bits()));
1513 assert!(line_12.is_some(), "1.2 行高的 shaped line 应入缓存");
1514
1515 set_text_line_height(1.8);
1516 paint_text_line("leading-probe", 20.0, Color::WHITE, Point::ZERO, &mut PaintList::new(), None);
1517 let line_18 = with_font(|fs| find_line(fs, 1.8f32.to_bits()));
1518 assert!(line_18.is_some(), "切到 1.8 后必须重新 shape 并建新 key,不能命中旧行高缓存");
1519 assert!(
1520 !std::rc::Rc::ptr_eq(&line_12.unwrap(), &line_18.unwrap()),
1521 "两种行高必须是不同的 shaped line,不能串缓存"
1522 );
1523 set_text_line_height(1.2);
1524 }
1525
1526 #[test]
1527 fn set_text_line_height_rejects_invalid_values() {
1528 set_text_line_height(0.0);
1529 assert_eq!(text_line_height(), 1.2);
1530 set_text_line_height(-3.0);
1531 assert_eq!(text_line_height(), 1.2);
1532 set_text_line_height(f32::NAN);
1533 assert_eq!(text_line_height(), 1.2);
1534 set_text_line_height(1.5);
1535 assert_eq!(text_line_height(), 1.5);
1536 set_text_line_height(1.2);
1537 }
1538
1539 #[test]
1541 fn shape_line_cache_evicts_lru_at_limit() {
1542 let fake_line =
1543 || std::rc::Rc::new(ShapedLine { runs: Vec::new(), max_x: 0.0, max_y: 0.0, visual_lines: Vec::new() });
1544 let hot_key = (TextKey::Owned("hot-entry".to_string()), 0, None, 0, 1.2f32.to_bits());
1545 let oldest_key = (TextKey::Owned("fake-entry-0".to_string()), 0, None, 0, 1.2f32.to_bits());
1546 with_font(|fs| {
1547 fs.line_cache.clear();
1548 fs.line_clock = 0;
1549 fs.line_clock += 1;
1550 fs.line_cache.insert(hot_key.clone(), LineCacheEntry { line: fake_line(), last_used: fs.line_clock });
1551 for i in 0..LINE_CACHE_LIMIT - 1 {
1552 fs.line_clock += 1;
1553 fs.line_cache.insert(
1554 (TextKey::Owned(format!("fake-entry-{i}")), 0, None, 0, 1.2f32.to_bits()),
1555 LineCacheEntry { line: fake_line(), last_used: fs.line_clock },
1556 );
1557 }
1558 fs.line_clock += 1;
1560 fs.line_cache.get_mut(&hot_key).expect("hot entry").last_used = fs.line_clock;
1561 });
1562 let mut list = PaintList::new();
1564 paint_text_line("trigger-evict", 14.0, Color::WHITE, Point::ZERO, &mut list, None);
1565 with_font(|fs| {
1566 assert!(fs.line_cache.len() <= LINE_CACHE_LIMIT, "超限后应回收到上限内");
1567 assert!(fs.line_cache.len() >= LINE_CACHE_TARGET, "LRU 只应淘汰最旧 1/4");
1568 assert!(fs.line_cache.contains_key(&hot_key), "刚访问过的热条目不应被淘汰");
1569 assert!(!fs.line_cache.contains_key(&oldest_key), "最久未访问的条目应被淘汰");
1570 fs.line_cache.clear();
1571 });
1572 }
1573
1574 #[test]
1576 fn paint_rebuilds_evicted_raster_glyphs() {
1577 let mut first = PaintList::new();
1578 paint_text_line("raster-rebuild-test", 18.0, Color::WHITE, Point::ZERO, &mut first, None);
1579 assert!(!first.commands.is_empty());
1580
1581 with_font(|fs| {
1582 fs.raster_cache.clear();
1583 fs.raster_cache_bytes = 0;
1584 });
1585
1586 let mut second = PaintList::new();
1587 paint_text_line("raster-rebuild-test", 18.0, Color::WHITE, Point::ZERO, &mut second, None);
1588 assert_eq!(first.commands.len(), second.commands.len(), "位图淘汰后应重建 glyph,而不是丢字");
1589 assert!(!second.commands.is_empty());
1590 }
1591
1592 #[test]
1596 fn zero_size_glyphs_are_cached_not_rerasterized() {
1597 with_font(|fs| {
1598 fs.raster_cache.clear();
1599 fs.raster_cache_bytes = 0;
1600 let _ = shape_text(fs, "a b c", 13.0, None, DEFAULT_FONT_STACK);
1601 let cached = fs.raster_cache.len();
1602 assert!(
1603 fs.raster_cache.values().any(|g| g.width == 0 && g.height == 0),
1604 "空格等零尺寸 glyph 必须缓存占位,不能每次重栅格化"
1605 );
1606 let _ = shape_text(fs, "a b c d", 13.0, None, DEFAULT_FONT_STACK);
1609 assert_eq!(fs.raster_cache.len(), cached + 1, "除新字符外不得新增栅格化条目");
1610 fs.raster_cache.clear();
1611 fs.raster_cache_bytes = 0;
1612 });
1613 }
1614
1615 #[test]
1616 fn runtime_generation_invalidates_line_cache() {
1617 let a = TextRuntime::new();
1618 let b = TextRuntime::with_config("serif", 1.2);
1619 with_font(|fs| fs.line_cache.clear());
1620 let before = with_font(|fs| fs.shape_calls);
1621 with_text_runtime(&a, || {
1622 with_font(|fs| {
1623 let _ = shape_text(fs, "runtime-generation-key", 13.0, None, DEFAULT_FONT_STACK);
1624 });
1625 });
1626 let after_a = with_font(|fs| fs.shape_calls);
1627 assert_eq!(after_a, before + 1);
1628 with_text_runtime(&b, || {
1629 with_font(|fs| {
1630 let _ = shape_text(fs, "runtime-generation-key", 13.0, None, DEFAULT_FONT_STACK);
1631 });
1632 });
1633 let after_b = with_font(|fs| fs.shape_calls);
1634 assert_eq!(after_b, after_a + 1, "不同运行时 generation 不得命中同一 shaped line");
1635 }
1636
1637 #[test]
1639 fn raster_cache_trims_to_budget() {
1640 with_font(|fs| {
1641 fs.raster_cache.clear();
1642 fs.raster_cache_bytes = 0;
1643 let chunk = vec![0u8; 8 * 1024 * 1024];
1644 for i in 0..5u16 {
1645 insert_raster_glyph(
1646 fs,
1647 GlyphKey::new(0, i, 0, 0, 0, 0),
1648 RasterGlyph { data: chunk.clone(), width: 2048, height: 1024, left: 0, top: 0, last_used: 0 },
1649 );
1650 }
1651 assert!(fs.raster_cache_bytes <= RASTER_CACHE_TARGET_BYTES, "应回收到目标水位");
1653 assert_eq!(fs.raster_cache.len(), 3, "LRU 应保留最近的条目");
1654 assert!(!fs.raster_cache.contains_key(&GlyphKey::new(0, 0, 0, 0, 0, 0)), "最旧条目应被淘汰");
1655 assert!(fs.raster_cache.contains_key(&GlyphKey::new(0, 4, 0, 0, 0, 0)), "最新条目应保留");
1656 fs.raster_cache.clear();
1657 fs.raster_cache_bytes = 0;
1658 });
1659 }
1660
1661 #[test]
1664 fn paint_text_line_dpr_rasterizes_at_physical_resolution() {
1665 fn paint_once(dpr: f32) -> (f32, f32, f32) {
1666 set_text_dpr(dpr);
1667 let mut list = PaintList::new();
1668 let width = paint_text_line("H", 24.0, Color::WHITE, Point::ZERO, &mut list, None);
1669 let (rect_w, uv_span) = match &list.commands[0] {
1670 PaintCommand::TexturedRect { rect, uv, .. } => (rect.width, (uv[2] - uv[0]) * ATLAS_SIZE as f32),
1671 _ => panic!("expected TexturedRect"),
1672 };
1673 set_text_dpr(1.0); (rect_w, uv_span, width)
1675 }
1676
1677 let (w1, span1, ret1) = paint_once(1.0);
1678 let (w2, span2, ret2) = paint_once(2.0);
1679
1680 assert!((w1 - w2).abs() <= 2.0, "rect 逻辑尺寸应 dpr 无关(允许取整 ≤2px): dpr1={w1} vs dpr2={w2}");
1682 assert!((ret1 - ret2).abs() < 0.5 && ret1 > 0.0, "返回宽度(逻辑)应 dpr 无关: {ret1} vs {ret2}");
1683 assert!(span2 > span1 * 1.5, "atlas 位图分辨率应随 dpr 变大: dpr1={span1}px vs dpr2={span2}px");
1684 let mw = measure_text_width("H", 24.0);
1685 assert!((ret1 - mw).abs() < 0.5, "paint 宽度应与 measure 一致(TextField 光标定位依赖): {ret1} vs {mw}");
1686 }
1687}
1688
1689pub fn is_rtl_text(text: &str) -> bool {
1695 for ch in text.chars() {
1696 let code = ch as u32;
1697 let rtl = matches!(
1698 code,
1699 0x0590..=0x05FF | 0x0600..=0x06FF | 0x0700..=0x074F | 0x0750..=0x077F | 0x0780..=0x07BF | 0x0860..=0x086F | 0x08A0..=0x08FF | 0xFB1D..=0xFB4F | 0xFB50..=0xFDFF | 0xFE70..=0xFEFF );
1710 if rtl {
1711 return true;
1712 }
1713 if ch.is_alphabetic() {
1714 return false;
1715 }
1716 }
1717 false
1718}
1719
1720pub fn mirror_carets_for_rtl(widths: &[f32]) -> Vec<f32> {
1726 let chars = widths.len().saturating_sub(1);
1727 if chars == 0 {
1728 return widths.to_vec();
1729 }
1730 let mut carets = vec![0.0f32; chars + 1];
1731 carets[0] = widths[chars];
1732 carets[1..=chars].copy_from_slice(&widths[..chars]);
1733 carets
1734}
1735
1736pub fn measure_caret_positions(text: &str, size_px: f32, font_stack: &str) -> Vec<f32> {
1738 let widths = measure_char_prefix_widths(text, size_px, font_stack);
1739 if is_rtl_text(text) {
1740 mirror_carets_for_rtl(&widths)
1741 } else {
1742 widths
1743 }
1744}
1745
1746pub fn nearest_caret_index(carets: &[f32], x: f32) -> usize {
1748 carets
1749 .iter()
1750 .enumerate()
1751 .min_by(|(ia, a), (ib, b)| (**a - x).abs().total_cmp(&(**b - x).abs()).then_with(|| ia.cmp(ib)))
1752 .map(|(index, _)| index)
1753 .unwrap_or(0)
1754}
1755
1756#[cfg(test)]
1757mod rtl_tests {
1758 use super::*;
1759
1760 #[test]
1761 fn detects_base_direction() {
1762 assert!(is_rtl_text("مرحبا بالعالم"));
1763 assert!(is_rtl_text("שלום"));
1764 assert!(!is_rtl_text("hello مرحبا")); assert!(!is_rtl_text("123 !?"));
1766 assert!(is_rtl_text("123 مرحبا")); }
1768
1769 #[test]
1770 fn rtl_caret_mirroring_and_nearest_index() {
1771 let widths = [0.0, 10.0, 25.0, 40.0];
1773 let carets = mirror_carets_for_rtl(&widths);
1774 assert_eq!(carets, vec![40.0, 0.0, 10.0, 25.0]);
1775 assert_eq!(nearest_caret_index(&carets, 38.0), 0, "靠近右缘 → 文本起点");
1776 assert_eq!(nearest_caret_index(&carets, 2.0), 1);
1777 assert_eq!(nearest_caret_index(&carets, 24.0), 3, "靠近左缘 → 文本末尾");
1778 assert_eq!(mirror_carets_for_rtl(&[0.0]), vec![0.0]);
1780 assert_eq!(nearest_caret_index(&widths, 12.0), 1);
1781 }
1782}
1783
1784#[derive(Clone, Debug, PartialEq)]
1791pub struct RichTextSpan {
1792 pub text: String,
1793 pub size_px: f32,
1794 pub color: Option<Color>,
1796 pub font_stack: Option<String>,
1798 pub weight: Option<u16>,
1805 pub italic: bool,
1807}
1808
1809impl RichTextSpan {
1810 pub fn new(text: impl Into<String>) -> Self {
1811 Self { text: text.into(), size_px: 15.0, color: None, font_stack: None, weight: None, italic: false }
1812 }
1813
1814 pub fn with_size(mut self, size_px: f32) -> Self {
1815 self.size_px = size_px;
1816 self
1817 }
1818
1819 pub fn with_color(mut self, color: Color) -> Self {
1820 self.color = Some(color);
1821 self
1822 }
1823
1824 pub fn with_font_stack(mut self, stack: impl Into<String>) -> Self {
1825 self.font_stack = Some(stack.into());
1826 self
1827 }
1828
1829 pub fn with_weight(mut self, weight: u16) -> Self {
1831 self.weight = Some(weight.clamp(1, 1000));
1832 self
1833 }
1834
1835 pub fn bold(self) -> Self {
1837 self.with_weight(700)
1838 }
1839
1840 pub fn with_italic(mut self, italic: bool) -> Self {
1841 self.italic = italic;
1842 self
1843 }
1844
1845 pub fn italic(self) -> Self {
1847 self.with_italic(true)
1848 }
1849}
1850
1851pub type InlinePainter = std::rc::Rc<dyn Fn(&mut PaintList, Rect)>;
1853
1854#[derive(Clone)]
1856pub struct InlineItem {
1857 pub width: f32,
1858 pub height: f32,
1859 pub painter: InlinePainter,
1860}
1861
1862impl InlineItem {
1863 pub fn new(width: f32, height: f32, painter: impl Fn(&mut PaintList, Rect) + 'static) -> Self {
1864 Self { width, height, painter: std::rc::Rc::new(painter) }
1865 }
1866}
1867
1868impl std::fmt::Debug for InlineItem {
1869 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1870 f.debug_struct("InlineItem").field("width", &self.width).field("height", &self.height).finish()
1871 }
1872}
1873
1874impl PartialEq for InlineItem {
1875 fn eq(&self, other: &Self) -> bool {
1876 self.width == other.width && self.height == other.height && std::rc::Rc::ptr_eq(&self.painter, &other.painter)
1877 }
1878}
1879
1880#[derive(Clone, Debug, PartialEq)]
1882pub enum RichItem {
1883 Text(RichTextSpan),
1884 Inline(InlineItem),
1885}
1886
1887#[derive(Clone, Debug, PartialEq)]
1889pub struct RichText {
1890 text: std::rc::Rc<str>,
1891 spans: Vec<RichTextSpan>,
1892 ranges: Vec<(usize, usize)>,
1893 inlines: Vec<(usize, InlineItem)>,
1895}
1896
1897impl RichText {
1898 pub fn new(spans: Vec<RichTextSpan>) -> Self {
1899 Self::from_items(spans.into_iter().map(RichItem::Text).collect())
1900 }
1901
1902 pub fn from_items(items: Vec<RichItem>) -> Self {
1903 let mut text = String::new();
1904 let mut spans = Vec::new();
1905 let mut ranges = Vec::new();
1906 let mut inlines = Vec::new();
1907 for item in items {
1908 match item {
1909 RichItem::Text(span) => {
1910 let start = text.len();
1911 text.push_str(&span.text);
1912 spans.push(span);
1913 ranges.push((start, text.len()));
1914 }
1915 RichItem::Inline(inline) => inlines.push((text.len(), inline)),
1916 }
1917 }
1918 Self { text: text.into(), spans, ranges, inlines }
1919 }
1920
1921 pub fn plain_text(&self) -> &str {
1923 &self.text
1924 }
1925
1926 pub fn spans(&self) -> &[RichTextSpan] {
1927 &self.spans
1928 }
1929
1930 pub fn is_empty(&self) -> bool {
1931 self.text.is_empty() && self.inlines.is_empty()
1932 }
1933}
1934
1935struct RichShapedGlyph {
1936 raster_key: GlyphKey,
1937 glyph_id: u16,
1938 x: f32,
1939 span: u16,
1941}
1942
1943struct RichShapedRun {
1944 glyphs: Vec<RichShapedGlyph>,
1945 baseline_y: f32,
1946 ascent: f32,
1948 font: parley::FontData,
1951 norm_coords: std::rc::Rc<[swash::NormalizedCoord]>,
1952 raster_size: f32,
1953}
1954
1955struct RichInlineBox {
1957 id: u16,
1959 x: f32,
1960 y: f32,
1961 width: f32,
1962 height: f32,
1963 line_baseline: f32,
1965}
1966
1967struct RichShapedLine {
1968 runs: Vec<RichShapedRun>,
1969 inline_boxes: Vec<RichInlineBox>,
1970 max_x: f32,
1971 max_y: f32,
1972}
1973
1974#[derive(Clone, PartialEq, Eq, Hash)]
1975struct RichCacheKey {
1976 text: std::rc::Rc<str>,
1977 styles: Vec<(usize, usize, u32, u64)>,
1979 inlines: Vec<(usize, u32, u32)>,
1981 width_bits: Option<u32>,
1982 dpr_bits: u32,
1983 line_height_bits: u32,
1985}
1986
1987struct RichCacheEntry {
1988 line: std::rc::Rc<RichShapedLine>,
1989 last_used: u64,
1990}
1991
1992fn rich_style_signature(rich: &RichText) -> Vec<(usize, usize, u32, u64)> {
1993 let runtime = current_text_runtime();
1994 let default_stack = runtime.font_stack();
1995 rich.ranges
1996 .iter()
1997 .zip(&rich.spans)
1998 .map(|((start, end), span)| {
1999 let stack = span.font_stack.as_deref().unwrap_or(default_stack.as_str());
2000 let mut h = DefaultHasher::new();
2001 runtime.style_generation().hash(&mut h);
2002 stack.hash(&mut h);
2003 span.weight.unwrap_or(400).hash(&mut h);
2006 span.italic.hash(&mut h);
2007 (*start, *end, span.size_px.max(1.0).to_bits(), h.finish())
2008 })
2009 .collect()
2010}
2011
2012fn span_index_at(ranges: &[(usize, usize)], byte: usize) -> u16 {
2013 ranges.iter().position(|(start, end)| byte >= *start && byte < *end).unwrap_or(0) as u16
2014}
2015
2016fn shape_rich(fs: &mut FontState, rich: &RichText, max_width_px: Option<f32>) -> std::rc::Rc<RichShapedLine> {
2018 let dpr = text_dpr();
2019 let key = RichCacheKey {
2020 text: std::rc::Rc::clone(&rich.text),
2021 styles: rich_style_signature(rich),
2022 inlines: rich
2023 .inlines
2024 .iter()
2025 .map(|(index, inline)| (*index, inline.width.to_bits(), inline.height.to_bits()))
2026 .collect(),
2027 width_bits: max_width_px.map(|w| w.to_bits()),
2028 dpr_bits: dpr.to_bits(),
2029 line_height_bits: text_line_height().to_bits(),
2030 };
2031 if let Some(entry) = fs.rich_cache.get_mut(&key) {
2032 fs.rich_clock += 1;
2033 entry.last_used = fs.rich_clock;
2034 return std::rc::Rc::clone(&entry.line);
2035 }
2036
2037 let text: &str = &rich.text;
2038 let default_stack = current_text_runtime().font_stack();
2039 let mut builder = fs.layout_cx.ranged_builder(&mut fs.font_cx, text, 1.0, true);
2040 builder.push_default(parley::StyleProperty::FontSize(15.0));
2041 builder.push_default(parley::StyleProperty::LineHeight(parley::LineHeight::FontSizeRelative(text_line_height())));
2043 builder.push_default(parley::StyleProperty::FontFamily(parley::FontFamily::Source(std::borrow::Cow::Borrowed(
2044 default_stack.as_str(),
2045 ))));
2046 builder.push_default(parley::StyleProperty::WordBreak(parley::WordBreak::KeepAll));
2047 builder.push_default(parley::StyleProperty::OverflowWrap(parley::OverflowWrap::Anywhere));
2048 for ((start, end), span) in rich.ranges.iter().zip(&rich.spans) {
2049 if span.size_px > 0.0 {
2050 builder.push(parley::StyleProperty::FontSize(span.size_px), *start..*end);
2051 }
2052 if let Some(stack) = &span.font_stack {
2053 builder.push(
2054 parley::StyleProperty::FontFamily(parley::FontFamily::Source(std::borrow::Cow::Borrowed(stack))),
2055 *start..*end,
2056 );
2057 }
2058 if let Some(weight) = span.weight {
2060 builder.push(parley::StyleProperty::FontWeight(parley::FontWeight::new(weight as f32)), *start..*end);
2061 }
2062 if span.italic {
2063 builder.push(parley::StyleProperty::FontStyle(parley::FontStyle::Italic), *start..*end);
2064 }
2065 }
2066 for (id, (index, inline)) in rich.inlines.iter().enumerate() {
2067 builder.push_inline_box(parley::InlineBox {
2068 id: id as u64,
2069 index: *index,
2070 width: inline.width,
2071 height: inline.height,
2072 kind: parley::InlineBoxKind::InFlow,
2080 baseline: None,
2081 vertical_align: parley::VerticalAlign::BASELINE,
2082 });
2083 }
2084 let mut layout: parley::Layout<()> = builder.build(text);
2085 let wrap_opt = max_width_px.filter(|w| *w > 0.0);
2086 layout.break_all_lines(wrap_opt);
2087 layout.align(parley::Alignment::Start, parley::AlignmentOptions::default());
2088
2089 let mut runs = Vec::new();
2090 let mut inline_boxes = Vec::new();
2091 let mut max_x = 0.0f32;
2092 let mut max_y = 0.0f32;
2093 for line in layout.lines() {
2094 let line_m = line.metrics();
2095 let baseline_y = line_m.baseline * dpr;
2096 for item in line.items() {
2097 let parley::PositionedLayoutItem::GlyphRun(gr) = item else {
2098 if let parley::PositionedLayoutItem::InlineBox(b) = item {
2099 inline_boxes.push(RichInlineBox {
2100 id: b.id as u16,
2101 x: b.x,
2102 y: b.y,
2103 width: b.width,
2104 height: b.height,
2105 line_baseline: baseline_y,
2106 });
2107 max_x = max_x.max((b.x + b.width) * dpr);
2108 max_y = max_y.max((b.y + b.height) * dpr);
2109 }
2110 continue;
2111 };
2112 let run_metrics = gr.run().font_metrics();
2113 let ascent = run_metrics.ascent * dpr;
2114 let descent = run_metrics.descent * dpr;
2115 let font_size_phys = gr.run().font_size() * dpr;
2116 let font_blob_id = gr.run().font().data.id() as usize;
2117 let norm_coords: std::rc::Rc<[swash::NormalizedCoord]> =
2120 gr.run().normalized_coords().iter().map(|c| c.to_bits()).collect();
2121 let run_font = gr.run().font().clone();
2122 let mut pen_x = gr.offset();
2123 let mut run_glyphs = Vec::new();
2124 for cluster in gr.run().visual_clusters() {
2125 let cluster_byte = cluster.text_range().start;
2126 let span = span_index_at(&rich.ranges, cluster_byte);
2127 for g in cluster.glyphs() {
2128 let glyph_id = match narrow_glyph_id(g.id) {
2131 Some(id) => id,
2132 None => {
2133 log::warn!("mgui-text: glyph id {} 超出 swash 的 u16 范围,跳过该字形", g.id);
2134 pen_x += g.advance;
2135 continue;
2136 }
2137 };
2138 let raster_key = GlyphKey::new(
2139 raster_font_id(font_blob_id, &norm_coords),
2140 glyph_id,
2141 font_size_phys.to_bits(),
2142 0,
2143 0,
2144 0,
2145 );
2146 if !fs.raster_cache.contains_key(&raster_key) {
2147 if let Some(rg) =
2148 rasterize_one_glyph(&run_font, font_size_phys, glyph_id, &norm_coords, &mut fs.scale_cx)
2149 {
2150 insert_raster_glyph(fs, raster_key, rg);
2151 }
2152 }
2153 let gx = pen_x + g.x;
2154 run_glyphs.push(RichShapedGlyph { raster_key, glyph_id, x: gx * dpr, span });
2155 max_x = max_x.max((gx + g.advance) * dpr);
2156 max_y = max_y.max(baseline_y + descent);
2157 pen_x += g.advance;
2158 }
2159 }
2160 if !run_glyphs.is_empty() {
2161 runs.push(RichShapedRun {
2162 glyphs: run_glyphs,
2163 baseline_y,
2164 ascent,
2165 font: run_font,
2166 norm_coords,
2167 raster_size: font_size_phys,
2168 });
2169 }
2170 }
2171 }
2172 if max_y == 0.0 {
2173 max_y = rich.spans.iter().map(|s| s.size_px).fold(15.0, f32::max) * 1.2 * dpr;
2174 }
2175
2176 let line = std::rc::Rc::new(RichShapedLine { runs, inline_boxes, max_x, max_y });
2177 if fs.rich_cache.len() >= LINE_CACHE_LIMIT {
2178 fs.rich_cache.clear();
2179 }
2180 fs.rich_clock += 1;
2181 fs.rich_cache.insert(key, RichCacheEntry { line: std::rc::Rc::clone(&line), last_used: fs.rich_clock });
2182 line
2183}
2184
2185pub fn rich_text_size(rich: &RichText, max_width: Option<f32>) -> Size {
2187 if rich.is_empty() {
2188 return Size::ZERO;
2189 }
2190 with_font(|fs| {
2191 let dpr = text_dpr();
2192 let shaped = shape_rich(fs, rich, max_width);
2193 let first_baseline = shaped.runs.first().map(|r| r.baseline_y);
2194 let (anchor, fallback_h) = match first_baseline {
2195 Some(baseline) => {
2196 let first_ascent =
2198 shaped.runs.iter().filter(|r| r.baseline_y == baseline).map(|r| r.ascent).fold(0.0f32, f32::max);
2199 let inline_top = shaped
2200 .inline_boxes
2201 .iter()
2202 .filter(|b| b.line_baseline == baseline)
2203 .map(|b| b.y * dpr)
2204 .fold(f32::INFINITY, f32::min);
2205 ((baseline - first_ascent).min(inline_top), 0.0)
2207 }
2208 None => (0.0, shaped.max_y),
2209 };
2210 let height = if shaped.max_y > anchor { (shaped.max_y - anchor) / dpr } else { fallback_h / dpr };
2211 Size::new(shaped.max_x / dpr, height)
2212 })
2213}
2214
2215#[derive(Clone, Debug, PartialEq)]
2217pub struct RichTextLayout {
2218 pub size: Size,
2219 pub inline_rects: Vec<Rect>,
2220}
2221
2222pub fn rich_text_layout(rich: &RichText, max_width: Option<f32>) -> RichTextLayout {
2224 if rich.is_empty() {
2225 return RichTextLayout { size: Size::ZERO, inline_rects: Vec::new() };
2226 }
2227 with_font(|fs| {
2228 let dpr = text_dpr();
2229 let shaped = shape_rich(fs, rich, max_width);
2230 let first_baseline = shaped.runs.first().map(|r| r.baseline_y);
2231 let anchor = match first_baseline {
2232 Some(baseline) => {
2233 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)
2242 }
2243 None => 0.0,
2244 };
2245 let height = if shaped.max_y > anchor { (shaped.max_y - anchor) / dpr } else { 0.0 };
2246 let mut inline_rects = vec![Rect::new(0.0, 0.0, 0.0, 0.0); rich.inlines.len()];
2247 for b in &shaped.inline_boxes {
2248 if let Some(slot) = inline_rects.get_mut(b.id as usize) {
2249 *slot = Rect::new(b.x, (b.y * dpr - anchor) / dpr, b.width, b.height);
2250 }
2251 }
2252 RichTextLayout { size: Size::new(shaped.max_x / dpr, height), inline_rects }
2253 })
2254}
2255
2256pub fn paint_rich_text(rich: &RichText, offset: Point, list: &mut PaintList, max_width: Option<f32>) -> f32 {
2258 paint_rich_text_with_default(rich, Color::WHITE, offset, list, max_width)
2259}
2260
2261pub fn paint_rich_text_with_default(
2263 rich: &RichText,
2264 default_color: Color,
2265 offset: Point,
2266 list: &mut PaintList,
2267 max_width: Option<f32>,
2268) -> f32 {
2269 if rich.is_empty() {
2270 return 0.0;
2271 }
2272 with_font(|fs| {
2273 let dpr = text_dpr();
2274 let shaped = shape_rich(fs, rich, max_width);
2275 let Some(first_run) = shaped.runs.first() else {
2276 return 0.0;
2277 };
2278 let first_baseline = first_run.baseline_y;
2279 let first_ascent =
2280 shaped.runs.iter().filter(|r| r.baseline_y == first_baseline).map(|r| r.ascent).fold(0.0f32, f32::max);
2281 let inline_top = shaped
2282 .inline_boxes
2283 .iter()
2284 .filter(|b| b.line_baseline == first_baseline)
2285 .map(|b| b.y * dpr)
2286 .fold(f32::INFINITY, f32::min);
2287 let anchor = (first_baseline - first_ascent).min(inline_top);
2288
2289 for run in &shaped.runs {
2290 for sg in &run.glyphs {
2291 if !fs.raster_cache.contains_key(&sg.raster_key) {
2292 if let Some(rg) =
2293 rasterize_one_glyph(&run.font, run.raster_size, sg.glyph_id, &run.norm_coords, &mut fs.scale_cx)
2294 {
2295 insert_raster_glyph(fs, sg.raster_key, rg);
2296 }
2297 }
2298 let Some(r) = fs.raster_cache.get_mut(&sg.raster_key) else {
2299 continue;
2300 };
2301 if r.width == 0 || r.height == 0 {
2302 continue;
2303 }
2304 fs.glyph_clock += 1;
2305 r.last_used = fs.glyph_clock;
2306 let entry = fs.atlas.get_or_insert(sg.raster_key, &r.data, r.width, r.height);
2307
2308 let x = offset.x + (sg.x + r.left as f32) / dpr;
2309 let glyph_visual_top = run.baseline_y - r.top as f32;
2310 let y = offset.y + (glyph_visual_top - anchor) / dpr;
2311 let rect = Rect::new(x, y, r.width as f32 / dpr, r.height as f32 / dpr);
2312 let color = rich.spans.get(sg.span as usize).and_then(|s| s.color).unwrap_or(default_color);
2313 list.push(PaintCommand::TexturedRect {
2314 rect,
2315 color,
2316 uv: entry.uv,
2317 texture_id: 0,
2318 mode: mgui_core::paint::TextureMode::Mask,
2319 });
2320 }
2321 }
2322 for b in &shaped.inline_boxes {
2323 if let Some((_, inline)) = rich.inlines.get(b.id as usize) {
2324 let rect = Rect::new(offset.x + b.x, offset.y + b.y - anchor / dpr, b.width, b.height);
2325 (inline.painter)(list, rect);
2326 }
2327 }
2328 shaped.max_x / dpr
2329 })
2330}
2331
2332#[cfg(test)]
2333mod rich_text_tests {
2334 use super::*;
2335
2336 #[test]
2337 fn mixed_styles_measure_and_paint_with_span_colors() {
2338 set_text_dpr(1.0);
2339 let red = Color::from_rgb8(255, 0, 0);
2340 let rich = RichText::new(vec![
2341 RichTextSpan::new("Hello ").with_size(18.0).with_color(Color::WHITE),
2342 RichTextSpan::new("World").with_size(30.0).with_color(red),
2343 ]);
2344 let size = rich_text_size(&rich, None);
2345 assert!(size.width > 0.0, "宽度必须 > 0");
2346 assert!(size.height >= 30.0, "高度应容纳 30px 字号: {size:?}");
2347
2348 let mut list = PaintList::new();
2349 let width = paint_rich_text(&rich, Point::ZERO, &mut list, None);
2350 assert!((width - size.width).abs() < 0.5, "绘制宽度应与测量一致: {width} vs {}", size.width);
2351 let colors: Vec<Color> = list
2352 .commands
2353 .iter()
2354 .filter_map(|c| match c {
2355 PaintCommand::TexturedRect { color, .. } => Some(*color),
2356 _ => None,
2357 })
2358 .collect();
2359 assert!(colors.contains(&Color::WHITE), "应包含第一段白色字形");
2360 assert!(colors.contains(&red), "应包含第二段红色字形");
2361 }
2362
2363 #[test]
2364 fn inline_item_measures_paints_and_sits_on_baseline() {
2365 use std::cell::RefCell;
2366 set_text_dpr(1.0);
2367 let captured: std::rc::Rc<RefCell<Option<Rect>>> = std::rc::Rc::new(RefCell::new(None));
2368 let cap = captured.clone();
2369 let rich = RichText::from_items(vec![
2370 RichItem::Text(RichTextSpan::new("A").with_size(16.0)),
2371 RichItem::Inline(InlineItem::new(30.0, 24.0, move |_list, rect| *cap.borrow_mut() = Some(rect))),
2372 RichItem::Text(RichTextSpan::new("B").with_size(16.0)),
2373 ]);
2374 let size = rich_text_size(&rich, None);
2375 assert!(size.width >= 30.0, "宽度应包含内联项: {size:?}");
2376 assert!(size.height >= 20.0, "高度应容纳内联项: {size:?}");
2377
2378 let mut list = PaintList::new();
2379 let width = paint_rich_text(&rich, Point::new(10.0, 5.0), &mut list, None);
2380 assert!(width >= 30.0);
2381 let rect = captured.borrow().expect("内联项绘制回调应被调用");
2382 assert!((rect.width - 30.0).abs() < 0.01 && (rect.height - 24.0).abs() < 0.01, "{rect:?}");
2383 assert!(rect.x >= 10.0 && rect.y >= 5.0, "内联项应带 offset: {rect:?}");
2384 }
2385
2386 #[test]
2387 fn inline_items_wrap_when_narrow() {
2388 set_text_dpr(1.0);
2389 let rich = RichText::from_items(vec![
2390 RichItem::Inline(InlineItem::new(40.0, 20.0, |_, _| {})),
2391 RichItem::Inline(InlineItem::new(40.0, 20.0, |_, _| {})),
2392 ]);
2393 let one_line = rich_text_size(&rich, None);
2394 let wrapped = rich_text_size(&rich, Some(50.0));
2395 assert!(one_line.width > wrapped.width, "窄宽度应减少行宽: {one_line:?} vs {wrapped:?}");
2396 assert!(
2397 wrapped.height > one_line.height * 1.5,
2398 "两个 40 宽内联项在 50 宽内应换行: {one_line:?} vs {wrapped:?}"
2399 );
2400 }
2401
2402 #[test]
2403 fn soft_wrap_uses_max_width() {
2404 set_text_dpr(1.0);
2405 let rich = RichText::new(vec![RichTextSpan::new("word ".repeat(40)).with_size(16.0)]);
2406 let single = rich_text_size(&rich, None);
2407 let wrapped = rich_text_size(&rich, Some(120.0));
2408 assert!(single.height > 0.0 && wrapped.height > 0.0);
2409 assert!(wrapped.height > single.height * 2.0, "换行后高度应显著增加: {single:?} vs {wrapped:?}");
2410 assert!(wrapped.width <= 130.0, "换行后宽度应受 max_width 约束: {wrapped:?}");
2411 }
2412
2413 #[test]
2424 fn trailing_spaces_hang_instead_of_forming_a_phantom_line() {
2425 set_text_dpr(1.0);
2426 let size = 16.0;
2427 let visible = "aaa bbb";
2428 let text = "aaa bbb ";
2429 let w_visible = measure_text_width(visible, size);
2430 let w_full = measure_text_width(text, size);
2431 assert!(w_full > w_visible + 1.0, "前置条件:尾空格要确实更宽,否则这个用例没有鉴别力");
2432 let max_width = (w_visible + w_full) * 0.5;
2433
2434 let ranges = wrapped_line_ranges(text, size, max_width);
2435 assert_eq!(ranges.len(), 1, "尾空格该挂在行外,不该另起一行:{ranges:?}(max_width={max_width})");
2436 assert_eq!(ranges[0], (0, text.len()), "唯一一行要覆盖全文,包括挂出去的空格");
2437
2438 let h = text_visual_height(text, size, Some(max_width));
2440 let h_visible_only = text_visual_height(visible, size, Some(max_width));
2441 assert!((h - h_visible_only).abs() < 0.5, "多三个尾空格不该改变块高:全文={h} 仅可见={h_visible_only}");
2442 }
2443
2444 #[test]
2445 fn span_builders_set_weight_and_italic() {
2446 assert_eq!(RichTextSpan::new("x").weight, None, "默认不指定字重(跟随 400)");
2447 assert!(!RichTextSpan::new("x").italic);
2448 assert_eq!(RichTextSpan::new("x").bold().weight, Some(700));
2449 assert_eq!(RichTextSpan::new("x").with_weight(500).weight, Some(500));
2450 assert_eq!(RichTextSpan::new("x").with_weight(0).weight, Some(1), "非法值夹紧到 ≥1");
2451 assert!(RichTextSpan::new("x").italic().italic);
2452 assert!(!RichTextSpan::new("x").with_italic(true).with_italic(false).italic);
2453 }
2454
2455 #[test]
2456 fn bold_span_is_wider_and_cache_keeps_weights_apart() {
2457 set_text_dpr(1.0);
2458 let text = "Handgloves 字重";
2459 let regular = RichText::new(vec![RichTextSpan::new(text).with_size(20.0)]);
2460 let bold = RichText::new(vec![RichTextSpan::new(text).with_size(20.0).bold()]);
2461
2462 let w_regular = rich_text_size(®ular, None).width;
2463 let w_bold = rich_text_size(&bold, None).width;
2464 assert!(w_bold > w_regular + 0.5, "粗体字面应比常规更宽: regular={w_regular} bold={w_bold}");
2465 assert!((rich_text_size(®ular, None).width - w_regular).abs() < 0.01, "缓存不能把粗体轮廓复用给常规 span");
2467
2468 let mut list = PaintList::new();
2469 let painted = paint_rich_text(&bold, Point::ZERO, &mut list, None);
2470 assert!((painted - w_bold).abs() < 0.5, "绘制宽度应与测量一致: {painted} vs {w_bold}");
2471 let glyphs = list.commands.iter().filter(|c| matches!(c, PaintCommand::TexturedRect { .. })).count();
2472 assert!(glyphs > 4, "粗体也应画出成片字形,实际 {glyphs}");
2473 }
2474
2475 #[test]
2476 fn italic_span_paints_without_changing_line_box() {
2477 set_text_dpr(1.0);
2478 let text = "Italic style";
2479 let regular = RichText::new(vec![RichTextSpan::new(text).with_size(18.0)]);
2480 let italic = RichText::new(vec![RichTextSpan::new(text).with_size(18.0).italic()]);
2481 let mut list = PaintList::new();
2482 let painted = paint_rich_text(&italic, Point::ZERO, &mut list, None);
2483 let glyphs = list.commands.iter().filter(|c| matches!(c, PaintCommand::TexturedRect { .. })).count();
2484 assert!(glyphs > 4, "斜体应照常成片绘制,实际 {glyphs}");
2485 let w_italic = rich_text_size(&italic, None).width;
2486 assert!(w_italic > 0.0, "斜体宽度有效: {w_italic}");
2487 assert!((painted - w_italic).abs() < 0.5, "斜体绘制宽度应与测量一致: {painted} vs {w_italic}");
2488 assert!(
2490 w_italic.abs() < rich_text_size(®ular, None).width * 2.0,
2491 "斜体宽度应与常规同量级: italic={w_italic}"
2492 );
2493 }
2494
2495 #[test]
2496 fn raster_font_id_folds_variation_coords() {
2497 assert_eq!(raster_font_id(42, &[]), 42);
2499 let a: [swash::NormalizedCoord; 1] = [1];
2500 let b: [swash::NormalizedCoord; 1] = [2];
2501 let coords_a: &[swash::NormalizedCoord] = &a;
2502 let coords_b: &[swash::NormalizedCoord] = &b;
2503 assert_ne!(raster_font_id(42, coords_a), raster_font_id(42, coords_b), "不同可变轴坐标必须是不同栅格身份");
2504 assert_eq!(raster_font_id(42, coords_a), raster_font_id(42, coords_a), "同坐标必须稳定(缓存命中)");
2505 assert_ne!(raster_font_id(42, coords_a), raster_font_id(43, coords_a), "不同 blob 也必须区分");
2506 }
2507}
2508
2509#[cfg(test)]
2514mod multiline_regression {
2515 use super::*;
2516
2517 #[test]
2519 fn multiline_text_lines_have_distinct_y() {
2520 let mut list = PaintList::new();
2521 paint_text_line("第一行AAA\n第二行BBB", 20.0, Color::WHITE, Point::new(50.0, 100.0), &mut list, None);
2522 let ys: Vec<f32> = list
2523 .commands
2524 .iter()
2525 .filter_map(|c| match c {
2526 PaintCommand::TexturedRect { rect, .. } => Some((rect.y * 10.0).round() / 10.0),
2527 _ => None,
2528 })
2529 .collect();
2530 assert!(!ys.is_empty(), "应画出 glyph");
2531 let y0 = ys[0];
2532 assert!(ys.iter().any(|&y| (y - y0).abs() > 20.0), "多行文本各行 y 必须拉开,实际全部≈{}: {:?}", y0, ys);
2533 }
2534
2535 #[test]
2537 fn wrapped_text_lines_have_distinct_y() {
2538 let mut list = PaintList::new();
2539 paint_text_line(
2541 "第一行文本内容比较长需要折行",
2542 20.0,
2543 Color::WHITE,
2544 Point::new(0.0, 0.0),
2545 &mut list,
2546 Some(60.0),
2547 );
2548 let ys: Vec<f32> = list
2549 .commands
2550 .iter()
2551 .filter_map(|c| match c {
2552 PaintCommand::TexturedRect { rect, .. } => Some((rect.y * 10.0).round() / 10.0),
2553 _ => None,
2554 })
2555 .collect();
2556 let y0 = ys[0];
2557 assert!(ys.iter().any(|&y| (y - y0).abs() > 20.0), "soft-wrap 多行 y 必须拉开,实际全部≈{}: {:?}", y0, ys);
2558 }
2559}