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
23const ATLAS_SIZE: u32 = 1024;
25const ATLAS_PADDING: u32 = 1;
27const FALLBACK_ADVANCE_X: f32 = 8.0;
29const MAX_ATLAS_SIZE: u32 = 8192;
31
32pub const DEFAULT_FONT_STACK: &str =
36 "system-ui, 'Segoe UI', Tahoma, 'Arial', 'Segoe UI Symbol', 'Microsoft YaHei UI', 'Segoe UI Emoji', sans-serif";
37
38#[derive(Clone, Copy, Debug)]
44#[allow(dead_code)]
45pub struct AtlasEntry {
46 pub uv: [f32; 4],
48 pub width: u32,
49 pub height: u32,
50}
51
52pub struct Atlas {
59 width: u32,
60 height: u32,
61 next_x: u32,
63 next_y: u32,
65 row_height: u32,
67 pixels: Vec<u8>,
69 entries: HashMap<GlyphKey, AtlasEntry>,
71 dirty: bool,
73 dirty_rows: Option<(u32, u32)>,
77 generation: u64,
80}
81
82#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
83pub struct GlyphKey(pub u64);
84
85fn narrow_glyph_id(id: u32) -> Option<u16> {
94 if id <= u16::MAX as u32 {
95 Some(id as u16)
96 } else {
97 None
98 }
99}
100
101impl GlyphKey {
102 pub fn new(
104 font_blob_id: usize,
105 glyph_id: u16,
106 size_px_bits: u32,
107 x_bin: i32,
108 y_bin: i32,
109 subpixel_bits: u8,
110 ) -> Self {
111 let mut h = DefaultHasher::new();
112 font_blob_id.hash(&mut h);
113 glyph_id.hash(&mut h);
114 size_px_bits.hash(&mut h);
115 x_bin.hash(&mut h);
116 y_bin.hash(&mut h);
117 subpixel_bits.hash(&mut h);
118 GlyphKey(h.finish())
119 }
120}
121
122fn raster_font_id(font_blob_id: usize, coords: &[swash::NormalizedCoord]) -> usize {
127 if coords.is_empty() {
128 return font_blob_id;
129 }
130 let mut h = DefaultHasher::new();
131 font_blob_id.hash(&mut h);
132 for c in coords {
133 c.hash(&mut h);
134 }
135 h.finish() as usize
136}
137
138impl Atlas {
139 pub fn new(width: u32, height: u32) -> Self {
140 Self {
141 width,
142 height,
143 next_x: 0,
144 next_y: 0,
145 row_height: 0,
146 pixels: vec![0; (width * height) as usize],
147 entries: HashMap::new(),
148 dirty: false,
149 dirty_rows: None,
150 generation: 1,
151 }
152 }
153
154 fn expand_2x(&mut self) {
157 let new_w = (self.width * 2).min(MAX_ATLAS_SIZE);
158 let new_h = (self.height * 2).min(MAX_ATLAS_SIZE);
159 if new_w == self.width && new_h == self.height {
160 return; }
162 let old_w = self.width;
163 let old_h = self.height;
164 let new_size = (new_w * new_h) as usize;
165 let mut new_pixels = vec![0u8; new_size];
166 for row in 0..old_h as usize {
168 let src_start = row * old_w as usize;
169 let dst_start = row * new_w as usize;
170 new_pixels[dst_start..dst_start + old_w as usize]
171 .copy_from_slice(&self.pixels[src_start..src_start + old_w as usize]);
172 }
173 self.pixels = new_pixels;
174 let scale_u = old_w as f32 / new_w as f32; let scale_v = old_h as f32 / new_h as f32;
177 for entry in self.entries.values_mut() {
178 entry.uv[0] *= scale_u;
179 entry.uv[1] *= scale_v;
180 entry.uv[2] *= scale_u;
181 entry.uv[3] *= scale_v;
182 }
183 self.width = new_w;
184 self.height = new_h;
185 self.dirty = true;
186 self.dirty_rows = Some((0, new_h));
187 self.generation += 1;
188 mgui_core::element::request_full_repaint();
190 }
191
192 fn clear_atlas(&mut self) {
195 self.entries.clear();
196 self.pixels.fill(0);
197 self.next_x = 0;
198 self.next_y = 0;
199 self.row_height = 0;
200 self.dirty = true;
201 self.dirty_rows = Some((0, self.height));
202 self.generation += 1;
203 mgui_core::element::request_full_repaint();
204 }
205
206 pub fn get_or_insert(&mut self, key: GlyphKey, bitmap: &[u8], w: u32, h: u32) -> AtlasEntry {
210 if let Some(&e) = self.entries.get(&key) {
211 return e;
212 }
213 let alloc_w = w + ATLAS_PADDING * 2;
215 let alloc_h = h + ATLAS_PADDING * 2;
216 if self.next_x + alloc_w > self.width {
218 self.next_x = 0;
219 self.next_y += self.row_height;
220 self.row_height = 0;
221 }
222 if self.next_y + alloc_h > self.height {
223 if self.width >= MAX_ATLAS_SIZE && self.height >= MAX_ATLAS_SIZE {
225 self.clear_atlas();
226 } else {
227 self.expand_2x();
228 }
229 return self.get_or_insert(key, bitmap, w, h);
231 }
232 let dst_x = self.next_x + ATLAS_PADDING;
233 let dst_y = self.next_y + ATLAS_PADDING;
234
235 for row in 0..h {
237 let src_start = (row * w) as usize;
238 let src_end = src_start + w as usize;
239 let dst_row = (dst_y + row) as usize * self.width as usize + dst_x as usize;
240 self.pixels[dst_row..dst_row + w as usize].copy_from_slice(&bitmap[src_start..src_end]);
241 }
242
243 let u0 = dst_x as f32 / self.width as f32;
245 let v0 = dst_y as f32 / self.height as f32;
246 let u1 = (dst_x + w) as f32 / self.width as f32;
247 let v1 = (dst_y + h) as f32 / self.height as f32;
248
249 let entry = AtlasEntry { uv: [u0, v0, u1, v1], width: w, height: h };
250 self.entries.insert(key, entry);
251 self.next_x += alloc_w;
252 if alloc_h > self.row_height {
253 self.row_height = alloc_h;
254 }
255 self.mark_rows_written(dst_y, h);
257 self.generation += 1;
258 entry
259 }
260
261 fn mark_rows_written(&mut self, y: u32, h: u32) {
263 self.dirty = true;
264 let end = (y + h).min(self.height);
265 self.dirty_rows = Some(match self.dirty_rows {
266 Some((top, bottom)) => (top.min(y), bottom.max(end)),
267 None => (y, end),
268 });
269 }
270
271 pub fn pixels(&self) -> &[u8] {
273 &self.pixels
274 }
275
276 #[allow(dead_code)]
278 pub fn glyph_count(&self) -> usize {
279 self.entries.len()
280 }
281
282 pub fn is_dirty(&self) -> bool {
284 self.dirty
285 }
286
287 pub fn clear_dirty(&mut self) {
289 self.dirty = false;
290 self.dirty_rows = None;
291 }
292}
293
294#[derive(Clone)]
300struct RasterGlyph {
301 data: Vec<u8>,
302 width: u32,
303 height: u32,
304 left: i32,
306 top: i32,
307 last_used: u64,
309}
310
311type LineCacheKey = (TextKey, u32, Option<u32>, u64, u32);
316
317struct LineCacheEntry {
319 line: std::rc::Rc<ShapedLine>,
320 last_used: u64,
321}
322
323pub struct FontState {
325 pub font_cx: parley::FontContext,
326 pub layout_cx: parley::LayoutContext<()>,
327 pub scale_cx: swash::scale::ScaleContext,
328 pub atlas: Atlas,
329 raster_cache: HashMap<GlyphKey, RasterGlyph>,
331 raster_cache_bytes: usize,
333 line_cache: HashMap<LineCacheKey, LineCacheEntry>,
340 rich_cache: HashMap<RichCacheKey, RichCacheEntry>,
342 rich_clock: u64,
344 line_clock: u64,
346 glyph_clock: u64,
348 pub shape_calls: usize,
350}
351
352impl FontState {
353 fn new() -> Self {
354 Self {
355 font_cx: parley::FontContext::new(),
356 layout_cx: parley::LayoutContext::<()>::new(),
357 scale_cx: swash::scale::ScaleContext::new(),
358 atlas: Atlas::new(ATLAS_SIZE, ATLAS_SIZE),
359 raster_cache: HashMap::new(),
360 raster_cache_bytes: 0,
361 line_cache: HashMap::new(),
362 rich_cache: HashMap::new(),
363 rich_clock: 0,
364 line_clock: 0,
365 glyph_clock: 0,
366 shape_calls: 0,
367 }
368 }
369}
370
371thread_local! {
372 static FONT_STATE: RefCell<Option<FontState>> = const { RefCell::new(None) }; static TEXT_DPR: std::cell::Cell<f32> = const { std::cell::Cell::new(1.0) };
378
379 static TEXT_LINE_HEIGHT: std::cell::Cell<f32> = const { std::cell::Cell::new(1.2) };
383}
384
385pub fn set_text_dpr(dpr: f32) {
387 TEXT_DPR.with(|c| c.set(if dpr > 0.0 { dpr } else { 1.0 }));
388}
389
390fn text_dpr() -> f32 {
391 TEXT_DPR.with(|c| c.get())
392}
393
394pub fn set_text_line_height(line_height: f32) {
398 let v = if line_height.is_finite() && line_height > 0.0 { line_height } else { 1.2 };
399 TEXT_LINE_HEIGHT.with(|c| c.set(v));
400}
401
402pub fn text_line_height() -> f32 {
404 TEXT_LINE_HEIGHT.with(|c| c.get())
405}
406
407pub fn with_font<F, R>(f: F) -> R
409where
410 F: FnOnce(&mut FontState) -> R,
411{
412 FONT_STATE.with(|cell| {
413 let mut opt = cell.borrow_mut();
414 if opt.is_none() {
415 *opt = Some(FontState::new());
416 }
417 f(opt.as_mut().unwrap())
418 })
419}
420
421const LINE_CACHE_LIMIT: usize = 4096;
430
431const LINE_CACHE_TARGET: usize = LINE_CACHE_LIMIT - LINE_CACHE_LIMIT / 4;
433
434fn evict_line_cache_lru(fs: &mut FontState) {
436 if fs.line_cache.len() <= LINE_CACHE_TARGET {
437 return;
438 }
439 let mut by_age: Vec<(u64, LineCacheKey)> = fs.line_cache.iter().map(|(k, v)| (v.last_used, k.clone())).collect();
440 by_age.sort_unstable_by_key(|&(last_used, _)| last_used);
441 let remove = fs.line_cache.len().saturating_sub(LINE_CACHE_TARGET);
442 for (_, key) in by_age.into_iter().take(remove) {
443 fs.line_cache.remove(&key);
444 }
445}
446
447const RASTER_CACHE_BUDGET_BYTES: usize = 32 * 1024 * 1024;
449const RASTER_CACHE_TARGET_BYTES: usize = RASTER_CACHE_BUDGET_BYTES * 3 / 4;
451
452fn insert_raster_glyph(fs: &mut FontState, key: GlyphKey, mut glyph: RasterGlyph) {
454 fs.glyph_clock += 1;
455 glyph.last_used = fs.glyph_clock;
456 let bytes = glyph.data.len();
457 if let Some(old) = fs.raster_cache.insert(key, glyph) {
458 fs.raster_cache_bytes = fs.raster_cache_bytes.saturating_sub(old.data.len());
459 }
460 fs.raster_cache_bytes += bytes;
461 trim_raster_cache(fs);
462}
463
464fn trim_raster_cache(fs: &mut FontState) {
469 if fs.raster_cache_bytes <= RASTER_CACHE_BUDGET_BYTES {
470 return;
471 }
472 let mut candidates: Vec<(u64, GlyphKey, usize)> =
473 fs.raster_cache.iter().map(|(&key, g)| (g.last_used, key, g.data.len())).collect();
474 candidates.sort_unstable_by_key(|&(last_used, _, _)| last_used);
475 for (_, key, bytes) in candidates {
476 if fs.raster_cache_bytes <= RASTER_CACHE_TARGET_BYTES {
477 break;
478 }
479 fs.raster_cache.remove(&key);
480 fs.raster_cache_bytes = fs.raster_cache_bytes.saturating_sub(bytes);
481 }
482}
483
484#[derive(Clone, PartialEq, Eq, Hash)]
490enum TextKey {
491 Owned(String),
492 Shared(std::rc::Rc<str>, Option<(usize, usize)>),
493}
494
495impl TextKey {
496 fn owned(text: &str) -> Self {
497 TextKey::Owned(text.to_string())
498 }
499}
500
501struct ShapedGlyph {
503 raster_key: GlyphKey,
505 glyph_id: u16,
507 x: f32,
509 w: f32,
511 #[allow(dead_code)]
513 y: f32,
514 ascent: f32,
516 descent: f32,
518 cluster: u32,
521}
522
523struct ShapedRun {
525 glyphs: Vec<ShapedGlyph>,
526 baseline_y: f32,
528 font: parley::FontData,
532 norm_coords: std::rc::Rc<[swash::NormalizedCoord]>,
534 raster_size: f32,
536}
537
538struct ShapedLine {
540 runs: Vec<ShapedRun>,
541 max_x: f32,
543 #[allow(dead_code)]
545 max_y: f32,
546 visual_lines: Vec<(usize, usize)>,
548}
549
550fn shape_text(
555 fs: &mut FontState,
556 text: &str,
557 raster_px: f32,
558 max_width_px: Option<f32>,
559 font_stack: &str,
560) -> std::rc::Rc<ShapedLine> {
561 shape_text_keyed(fs, text, TextKey::owned(text), raster_px, max_width_px, font_stack)
562}
563
564fn shape_text_keyed(
567 fs: &mut FontState,
568 text: &str,
569 text_key: TextKey,
570 raster_px: f32,
571 max_width_px: Option<f32>,
572 font_stack: &str,
573) -> std::rc::Rc<ShapedLine> {
574 let font_stack_hash = {
575 let mut h = DefaultHasher::new();
576 font_stack.hash(&mut h);
577 h.finish()
578 };
579 let line_height = text_line_height();
580 let key =
581 (text_key, raster_px.to_bits(), max_width_px.map(|w| w.to_bits()), font_stack_hash, line_height.to_bits());
582 if let Some(entry) = fs.line_cache.get_mut(&key) {
583 fs.line_clock += 1;
584 entry.last_used = fs.line_clock;
585 return std::rc::Rc::clone(&entry.line);
586 }
587
588 fs.shape_calls += 1;
589 let dpr = text_dpr();
590
591 let scale = 1.0f32;
594 let font_size_px = raster_px / dpr;
595
596 let wrap_opt = max_width_px.filter(|&w| w > 0.0);
598
599 let mut builder = fs.layout_cx.ranged_builder(&mut fs.font_cx, text, scale, true);
600 builder.push_default(parley::StyleProperty::FontSize(font_size_px));
601 builder.push_default(parley::StyleProperty::LineHeight(parley::LineHeight::FontSizeRelative(line_height)));
607 builder.push_default(parley::StyleProperty::FontFamily(parley::FontFamily::Source(std::borrow::Cow::Borrowed(
610 font_stack,
611 ))));
612 builder.push_default(parley::StyleProperty::WordBreak(parley::WordBreak::KeepAll));
615 builder.push_default(parley::StyleProperty::OverflowWrap(parley::OverflowWrap::Anywhere));
616 let mut layout: parley::Layout<()> = builder.build(text);
617 layout.break_all_lines(wrap_opt);
618 layout.align(parley::Alignment::Start, parley::AlignmentOptions::default());
621
622 let mut runs = Vec::new();
626 let mut max_x = 0.0f32;
627 let mut max_y = 0.0f32;
628 let mut visual_lines = Vec::new();
629
630 for line in layout.lines() {
631 let mut line_start = usize::MAX;
633 let mut line_end = 0usize;
634 for run in line.runs() {
635 let range = run.text_range();
636 line_start = line_start.min(range.start);
637 line_end = line_end.max(range.end);
638 }
639 visual_lines.push(if line_start == usize::MAX { (0, 0) } else { (line_start, line_end) });
640
641 let line_m = line.metrics();
642 let baseline_y = line_m.baseline * dpr; for item in line.items() {
645 let parley::PositionedLayoutItem::GlyphRun(gr) = item else {
646 continue;
647 };
648
649 let run_metrics = gr.run().font_metrics();
653 let ascent = run_metrics.ascent * dpr;
654 let descent = run_metrics.descent * dpr;
655 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();
666 let norm_coords: std::rc::Rc<[swash::NormalizedCoord]> =
672 gr.run().normalized_coords().iter().map(|c| c.to_bits()).collect();
673 let run_font = gr.run().font().clone();
674 let mut pen_x = gr.offset();
675 let run_baseline = gr.baseline();
676 for cluster in gr.run().visual_clusters() {
677 let cluster_byte = cluster.text_range().start as u32;
678 for g in cluster.glyphs() {
679 let glyph_id = match narrow_glyph_id(g.id) {
682 Some(id) => id,
683 None => {
684 log::warn!("mgui-text: glyph id {} 超出 swash 的 u16 范围,跳过该字形", g.id);
685 pen_x += g.advance;
686 continue;
687 }
688 };
689 let size_bits = font_size_phys.to_bits(); let x_bin = 0; let y_bin = 0;
692 let raster_key =
693 GlyphKey::new(raster_font_id(font_blob_id, &norm_coords), glyph_id, size_bits, x_bin, y_bin, 0);
694 if !fs.raster_cache.contains_key(&raster_key) {
696 if let Some(rg) =
697 rasterize_one_glyph(&run_font, font_size_phys, glyph_id, &norm_coords, &mut fs.scale_cx)
698 {
699 insert_raster_glyph(fs, raster_key, rg);
700 }
701 }
702 let gx = pen_x + g.x;
703 run_glyphs.push(ShapedGlyph {
704 raster_key,
705 glyph_id,
706 x: gx * dpr, w: g.advance * dpr, y: (run_baseline + g.y) * dpr, ascent,
710 descent,
711 cluster: cluster_byte,
712 });
713 max_x = max_x.max((gx + g.advance) * dpr);
714 max_y = max_y.max(baseline_y + descent);
715 pen_x += g.advance;
716 }
717 }
718
719 if !run_glyphs.is_empty() {
720 runs.push(ShapedRun {
721 glyphs: run_glyphs,
722 baseline_y,
723 font: run_font,
724 norm_coords,
725 raster_size: font_size_phys,
726 });
727 }
728 }
729 }
730
731 if max_y == 0.0 {
733 max_y = raster_px * 1.2;
734 }
735
736 let line = std::rc::Rc::new(ShapedLine { runs, max_x, max_y, visual_lines });
737 if fs.line_cache.len() >= LINE_CACHE_LIMIT {
738 evict_line_cache_lru(fs);
739 }
740 fs.line_clock += 1;
741 let entry = LineCacheEntry { line: std::rc::Rc::clone(&line), last_used: fs.line_clock };
742 fs.line_cache.insert(key, entry);
743 line
744}
745
746#[derive(Clone)]
754pub struct AtlasSnapshot {
755 pub width: u32,
756 pub height: u32,
757 pub dirty: bool,
758 pub dirty_y: (u32, u32),
761 pub pixels: Option<Vec<u8>>,
763}
764
765pub fn atlas_snapshot() -> AtlasSnapshot {
767 with_font(|fs| {
768 let dirty = fs.atlas.is_dirty();
769 let (y0, y1) = if dirty {
770 let (a, b) = fs.atlas.dirty_rows.unwrap_or((0, fs.atlas.height));
771 (a.min(fs.atlas.height), b.min(fs.atlas.height))
772 } else {
773 (0, 0)
774 };
775 let pixels = if dirty {
776 let w = fs.atlas.width as usize;
777 Some(fs.atlas.pixels()[(y0 as usize * w)..(y1 as usize * w)].to_vec())
778 } else {
779 None
780 };
781 AtlasSnapshot { width: fs.atlas.width, height: fs.atlas.height, dirty, dirty_y: (y0, y1), pixels }
782 })
783}
784
785pub fn atlas_clear_dirty() {
787 with_font(|fs| {
788 fs.atlas.clear_dirty();
789 })
790}
791
792pub fn atlas_generation() -> u64 {
794 with_font(|fs| fs.atlas.generation)
795}
796
797#[derive(Clone, Copy, Debug, Default)]
799pub struct AtlasStats {
800 pub width: u32,
801 pub height: u32,
802 pub glyph_count: usize,
803 pub used_height: u32,
805 pub dirty: bool,
806}
807
808pub fn atlas_stats() -> AtlasStats {
809 with_font(|fs| {
810 let atlas = &fs.atlas;
811 AtlasStats {
812 width: atlas.width,
813 height: atlas.height,
814 glyph_count: atlas.entries.len(),
815 used_height: (atlas.next_y + atlas.row_height).min(atlas.height),
816 dirty: atlas.dirty,
817 }
818 })
819}
820
821pub fn with_atlas<R>(f: impl FnOnce(u32, u32, &[u8]) -> R) -> R {
826 with_font(|fs| {
827 let atlas = &fs.atlas;
828 f(atlas.width, atlas.height, &atlas.pixels)
829 })
830}
831
832pub struct TextRenderObject {
837 text: String,
838 size_px: f32,
839 color: Color,
840 max_width: Option<f32>,
842 max_width_explicit: bool,
845 size: Size,
847 element_id: Option<ElementId>,
848}
849
850impl TextRenderObject {
851 pub fn new(text: String, size_px: f32, color: Color) -> Self {
852 Self { text, size_px, color, max_width: None, max_width_explicit: false, size: Size::ZERO, element_id: None }
853 }
854
855 pub fn with_max_width(mut self, max_width: f32) -> Self {
856 self.max_width = Some(max_width);
857 self.max_width_explicit = true;
858 self
859 }
860
861 pub fn set_max_width(&mut self, max_width: Option<f32>) {
862 self.max_width = max_width;
863 self.max_width_explicit = max_width.is_some();
864 }
865
866 fn measure(&self) -> Size {
868 let dpr = text_dpr();
869 let raster_px = self.size_px * dpr;
870 let width = with_font(|fs| {
871 let line = shape_text(fs, &self.text, raster_px, self.max_width, DEFAULT_FONT_STACK);
872 let max_x = line.max_x / dpr;
873 if max_x == 0.0 && !self.text.is_empty() {
874 self.text.chars().count() as f32 * FALLBACK_ADVANCE_X
875 } else {
876 max_x
877 }
878 });
879 let height = text_visual_height(&self.text, self.size_px, self.max_width);
882 Size::new(width, height)
883 }
884}
885
886pub fn measure_text_width(text: &str, size_px: f32) -> f32 {
890 measure_text_width_styled(text, size_px, DEFAULT_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 text_visual_height_styled(text, size_px, max_width_px, DEFAULT_FONT_STACK)
923}
924
925pub fn text_visual_height_styled(text: &str, size_px: f32, max_width_px: Option<f32>, font_stack: &str) -> f32 {
927 if text.is_empty() {
928 return size_px;
929 }
930 with_font(|fs| {
931 let dpr = text_dpr();
932 let raster_px = size_px * dpr;
933 let line = shape_text(fs, text, raster_px, max_width_px, font_stack);
934
935 if line.runs.is_empty() {
936 return size_px;
937 }
938
939 let first_run = &line.runs[0];
941 let first_ascent = first_run.glyphs.first().map(|g| g.ascent).unwrap_or(raster_px);
942 let first_baseline = first_run.baseline_y;
943 let visual_top = first_baseline - first_ascent;
944
945 let mut visual_bottom = 0.0f32;
947 for run in &line.runs {
948 for sg in &run.glyphs {
949 let bottom = run.baseline_y + sg.descent;
950 visual_bottom = visual_bottom.max(bottom);
951 }
952 }
953
954 if visual_bottom > visual_top {
955 (visual_bottom - visual_top) / dpr
956 } else {
957 size_px
958 }
959 })
960}
961
962pub fn paint_text_line(
968 text: &str,
969 size_px: f32,
970 color: Color,
971 offset: Point,
972 list: &mut PaintList,
973 max_width_px: Option<f32>,
974) -> f32 {
975 paint_text_line_impl(text, TextKey::owned(text), size_px, color, offset, list, max_width_px, DEFAULT_FONT_STACK)
976}
977
978#[allow(clippy::too_many_arguments)]
980pub fn paint_text_line_styled(
981 text: &str,
982 size_px: f32,
983 color: Color,
984 offset: Point,
985 list: &mut PaintList,
986 max_width_px: Option<f32>,
987 font_stack: &str,
988) -> f32 {
989 paint_text_line_impl(text, TextKey::owned(text), size_px, color, offset, list, max_width_px, font_stack)
990}
991
992#[allow(clippy::too_many_arguments)]
997pub fn paint_text_span(
998 text: &std::rc::Rc<str>,
999 range: Option<(usize, usize)>,
1000 size_px: f32,
1001 color: Color,
1002 offset: Point,
1003 list: &mut PaintList,
1004 max_width_px: Option<f32>,
1005) -> f32 {
1006 let (start, end) = match range {
1007 Some(r) => clamp_char_range(text, r),
1008 None => (0, text.len()),
1009 };
1010 paint_text_line_impl(
1011 &text[start..end],
1012 TextKey::Shared(std::rc::Rc::clone(text), range),
1013 size_px,
1014 color,
1015 offset,
1016 list,
1017 max_width_px,
1018 DEFAULT_FONT_STACK,
1019 )
1020}
1021
1022pub fn text_ascent(text: &str, size_px: f32) -> f32 {
1028 if text.is_empty() {
1029 return size_px;
1030 }
1031 with_font(|fs| {
1032 let dpr = text_dpr();
1033 let shaped = shape_text(fs, text, size_px * dpr, None, DEFAULT_FONT_STACK);
1034 first_glyph_ascent(&shaped).map(|a| a / dpr).unwrap_or(size_px)
1035 })
1036}
1037
1038pub fn text_span_ascent(text: &std::rc::Rc<str>, range: Option<(usize, usize)>, size_px: f32) -> f32 {
1041 let (start, end) = match range {
1042 Some(r) => clamp_char_range(text, r),
1043 None => (0, text.len()),
1044 };
1045 if start >= end {
1046 return size_px;
1047 }
1048 with_font(|fs| {
1049 let dpr = text_dpr();
1050 let shaped = shape_text_keyed(
1051 fs,
1052 &text[start..end],
1053 TextKey::Shared(std::rc::Rc::clone(text), range),
1054 size_px * dpr,
1055 None,
1056 DEFAULT_FONT_STACK,
1057 );
1058 first_glyph_ascent(&shaped).map(|a| a / dpr).unwrap_or(size_px)
1059 })
1060}
1061
1062fn first_glyph_ascent(shaped: &ShapedLine) -> Option<f32> {
1063 shaped.runs.first().and_then(|r| r.glyphs.first()).map(|g| g.ascent)
1064}
1065
1066fn clamp_char_range(text: &str, range: (usize, usize)) -> (usize, usize) {
1068 let mut start = range.0.min(text.len());
1069 let mut end = range.1.min(text.len());
1070 while !text.is_char_boundary(start) {
1071 start += 1;
1072 }
1073 while !text.is_char_boundary(end) {
1074 end -= 1;
1075 }
1076 if end < start {
1077 end = start;
1078 }
1079 (start, end)
1080}
1081
1082#[allow(clippy::too_many_arguments)]
1084fn paint_text_line_impl(
1085 text: &str,
1086 text_key: TextKey,
1087 size_px: f32,
1088 color: Color,
1089 offset: Point,
1090 list: &mut PaintList,
1091 max_width_px: Option<f32>,
1092 font_stack: &str,
1093) -> f32 {
1094 if text.is_empty() {
1095 return 0.0;
1096 }
1097 let width = with_font(|fs| {
1098 let dpr = text_dpr();
1099 let raster_px = size_px * dpr;
1100 let shaped = shape_text_keyed(fs, text, text_key, raster_px, max_width_px, font_stack);
1101
1102 let first_run = match shaped.runs.first() {
1106 Some(r) => r,
1107 None => return 0.0,
1108 };
1109 let first_ascent = first_run.glyphs.first().map(|g| g.ascent).unwrap_or(raster_px);
1110 let first_baseline = first_run.baseline_y;
1111 let anchor = first_baseline - first_ascent; let mut max_x = 0.0f32;
1114 for run in &shaped.runs {
1115 for sg in &run.glyphs {
1116 if !fs.raster_cache.contains_key(&sg.raster_key) {
1119 if let Some(rg) =
1120 rasterize_one_glyph(&run.font, run.raster_size, sg.glyph_id, &run.norm_coords, &mut fs.scale_cx)
1121 {
1122 insert_raster_glyph(fs, sg.raster_key, rg);
1123 }
1124 }
1125 let Some(r) = fs.raster_cache.get_mut(&sg.raster_key) else {
1129 continue;
1130 };
1131 if r.width == 0 || r.height == 0 {
1132 continue;
1133 }
1134 fs.glyph_clock += 1;
1135 r.last_used = fs.glyph_clock;
1136 let entry = fs.atlas.get_or_insert(sg.raster_key, &r.data, r.width, r.height);
1137
1138 let x = offset.x + (sg.x + r.left as f32) / dpr;
1140 let glyph_visual_top = run.baseline_y - r.top as f32;
1145 let y = offset.y + (glyph_visual_top - anchor) / dpr;
1146
1147 let rect = Rect::new(x, y, r.width as f32 / dpr, r.height as f32 / dpr);
1148 list.push(PaintCommand::TexturedRect {
1149 rect,
1150 color,
1151 uv: entry.uv,
1152 texture_id: 0,
1153 mode: mgui_core::paint::TextureMode::Mask,
1154 });
1155 max_x = max_x.max((sg.x + sg.w) / dpr);
1156 }
1157 }
1158 if max_x == 0.0 {
1159 max_x = text.chars().count() as f32 * FALLBACK_ADVANCE_X;
1160 }
1161 max_x
1162 });
1163 width
1164}
1165
1166pub fn wrapped_line_ranges(text: &str, size_px: f32, max_width: f32) -> Vec<(usize, usize)> {
1181 if text.is_empty() {
1182 return vec![(0, 0)];
1183 }
1184 if max_width <= 0.0 {
1185 return vec![(0, text.len())];
1186 }
1187 with_font(|fs| {
1188 let dpr = text_dpr();
1189 let raster_px = size_px * dpr;
1190 let shaped = shape_text(fs, text, raster_px, Some(max_width), DEFAULT_FONT_STACK);
1191 shaped.visual_lines.clone()
1192 })
1193}
1194
1195pub fn measure_char_prefix_widths(text: &str, size_px: f32, font_stack: &str) -> Vec<f32> {
1196 if text.is_empty() {
1197 return vec![0.0];
1198 }
1199 with_font(|fs| {
1200 let dpr = text_dpr();
1201 let raster_px = size_px * dpr;
1202 let shaped = shape_text(fs, text, raster_px, None, font_stack);
1203
1204 let char_count = text.chars().count();
1205 let mut widths = vec![0.0f32; char_count + 1];
1206
1207 let mut byte_x: Vec<(u32, f32)> = Vec::new();
1210 for run in &shaped.runs {
1211 for sg in &run.glyphs {
1212 match byte_x.last_mut() {
1213 Some((b, _)) if *b == sg.cluster => {}
1214 _ => byte_x.push((sg.cluster, sg.x)),
1215 }
1216 }
1217 }
1218
1219 let mut prev = 0.0f32;
1222 let mut bi = 0usize;
1223 for (ci, (byte_pos, _)) in text.char_indices().enumerate() {
1224 while bi < byte_x.len() && byte_x[bi].0 <= byte_pos as u32 {
1225 prev = byte_x[bi].1 / dpr;
1226 bi += 1;
1227 }
1228 widths[ci] = prev;
1229 }
1230 widths[char_count] = shaped.max_x / dpr;
1231 widths
1232 })
1233}
1234
1235fn rasterize_one_glyph(
1237 font: &parley::FontData,
1238 font_size: f32,
1239 glyph_id: u16,
1240 norm_coords: &[swash::NormalizedCoord],
1241 scale_cx: &mut swash::scale::ScaleContext,
1242) -> Option<RasterGlyph> {
1243 let bytes = font.data.data();
1245 if bytes.is_empty() {
1246 return None;
1247 }
1248 let font_ref = swash::FontRef::from_index(bytes, font.index as usize)?;
1249 let mut scaler =
1250 scale_cx.builder(font_ref).size(font_size).normalized_coords(norm_coords.iter()).hint(true).build();
1251 let image = swash::scale::Render::new(&[
1252 swash::scale::Source::ColorOutline(0),
1253 swash::scale::Source::ColorBitmap(swash::scale::StrikeWith::BestFit),
1254 swash::scale::Source::Outline,
1255 ])
1256 .render(&mut scaler, glyph_id)?;
1257 if image.placement.width == 0 || image.placement.height == 0 {
1258 return Some(RasterGlyph { data: Vec::new(), width: 0, height: 0, left: 0, top: 0, last_used: 0 });
1263 }
1264 Some(RasterGlyph {
1265 data: image.data.to_vec(),
1266 width: image.placement.width,
1267 height: image.placement.height,
1268 left: image.placement.left,
1269 top: image.placement.top,
1270 last_used: 0,
1271 })
1272}
1273
1274impl RenderObject for TextRenderObject {
1275 fn layout(&mut self, _bc: BoxConstraints, _ctx: &mut LayoutContext) -> Size {
1276 let s = self.measure();
1287 self.size = s;
1288 s
1289 }
1290
1291 fn content_size(&self) -> Size {
1292 self.size
1293 }
1294
1295 fn paint(&self, offset: Point, list: &mut PaintList) {
1296 paint_text_line(&self.text, self.size_px, self.color, offset, list, self.max_width);
1297 }
1298
1299 fn set_element_id(&mut self, id: ElementId) {
1300 self.element_id = Some(id);
1301 }
1302
1303 fn hit_test(&self, position: Point, offset: Point) -> Option<ElementId> {
1304 let r = Rect::new(offset.x, offset.y, self.size.width, self.size.height);
1308 if r.contains(position) {
1309 self.element_id
1310 } else {
1311 None
1312 }
1313 }
1314}
1315
1316#[cfg(test)]
1321mod tests {
1322 use super::*;
1323
1324 fn mk_key(id: u32) -> GlyphKey {
1325 GlyphKey(id as u64)
1326 }
1327
1328 #[test]
1329 fn atlas_get_or_insert_dedupes() {
1330 let mut a = Atlas::new(64, 64);
1331 let k = mk_key(1);
1332 let e1 = a.get_or_insert(k, &[255; 8], 2, 4);
1333 let e2 = a.get_or_insert(k, &[0; 8], 2, 4);
1334 assert_eq!(e1.uv, e2.uv, "重复 key 必须返回同一 entry");
1335 assert_eq!(a.glyph_count(), 1);
1336 }
1337
1338 #[test]
1339 fn atlas_wraps_to_next_row() {
1340 let mut a = Atlas::new(20, 20);
1341 let k1 = mk_key(1);
1343 a.get_or_insert(k1, &[1; 64], 16, 4);
1344 let k2 = mk_key(2);
1346 let e2 = a.get_or_insert(k2, &[2; 64], 16, 4);
1347 assert!(e2.uv[1] > 0.0, "第二个 glyph 应该换行,uv.v0 > 0");
1348 }
1349
1350 #[test]
1351 fn atlas_dirty_flag_lifecycle() {
1352 let mut a = Atlas::new(64, 64);
1353 assert!(!a.is_dirty());
1355 a.get_or_insert(mk_key(1), &[255; 8], 2, 4);
1357 assert!(a.is_dirty(), "get_or_insert 后应该 dirty");
1358 a.clear_dirty();
1360 assert!(!a.is_dirty());
1361 a.get_or_insert(mk_key(1), &[0; 8], 2, 4);
1363 assert!(!a.is_dirty(), "重复 key 不应触发 dirty");
1364 a.get_or_insert(mk_key(2), &[0; 8], 2, 4);
1366 assert!(a.is_dirty());
1367 }
1368
1369 #[test]
1372 fn atlas_snapshot_uploads_only_dirty_rows() {
1373 let width = with_font(|fs| {
1375 fs.atlas = Atlas::new(ATLAS_SIZE, ATLAS_SIZE);
1376 fs.atlas.width
1377 });
1378 with_font(|fs| {
1379 fs.atlas.get_or_insert(GlyphKey::new(7, 7, 0, 0, 0, 0), &[9u8; 16], 4, 4);
1380 fs.atlas.get_or_insert(GlyphKey::new(7, 8, 0, 0, 0, 0), &[9u8; 16], 4, 4);
1381 assert_eq!(fs.atlas.dirty_rows, Some((1, 5)), "同一行的写入应合并为单行带");
1382 });
1383 let snap = atlas_snapshot();
1384 assert!(snap.dirty);
1385 assert_eq!(snap.dirty_y, (1, 5));
1386 assert_eq!(snap.pixels.as_ref().map(Vec::len), Some(width as usize * 4), "快照只拷贝 dirty 行");
1387 atlas_clear_dirty();
1388 let clean = atlas_snapshot();
1389 assert!(!clean.dirty);
1390 assert_eq!(clean.dirty_y, (0, 0));
1391 assert!(clean.pixels.is_none());
1392 }
1393
1394 #[test]
1396 fn atlas_auto_expands_when_full() {
1397 let mut a = Atlas::new(32, 32);
1398 let e_before = a.get_or_insert(mk_key(1), &[100; 9], 3, 3);
1400 let uv_scalar_before = e_before.uv[0]; let big: Vec<u8> = vec![200; 400]; for i in 2..10 {
1406 a.get_or_insert(mk_key(i), &big, 20, 20);
1407 }
1408 assert!(a.width >= 32, "atlas 应保持原尺寸或扩容");
1410 assert!(a.glyph_count() >= 8, "扩容后应能放下 8+ glyphs,实际 {}", a.glyph_count());
1411
1412 if a.width > 32 {
1414 let e_after = a.get_or_insert(mk_key(1), &[0; 9], 3, 3);
1416 let expected = uv_scalar_before / 2.0;
1419 assert!((e_after.uv[0] - expected).abs() < 0.01, "扩容后 uv.u0 应为 {expected}, 实际 {}", e_after.uv[0]);
1420 }
1421 }
1422
1423 #[test]
1425 fn atlas_accepts_new_glyphs_after_expansion() {
1426 let mut a = Atlas::new(16, 16);
1427 a.get_or_insert(mk_key(1), &[50; 144], 12, 12);
1429 let e2 = a.get_or_insert(mk_key(2), &[100; 144], 12, 12);
1431 assert!(a.width > 16 || a.height > 16, "应该扩容了");
1432 let e1 = a.get_or_insert(mk_key(1), &[0; 144], 12, 12);
1434 assert!(e2.uv[1] >= e1.uv[1], "第二个 glyph 应在第一个下方");
1435 }
1436
1437 #[test]
1438 fn text_measure_produces_nonzero_size() {
1439 let t = TextRenderObject::new("Hello".into(), 24.0, Color::WHITE);
1440 let s = t.measure();
1441 assert!(s.width > 0.0, "width should be > 0 for 'Hello'");
1442 assert!(s.height > 0.0, "height should be > 0");
1443 }
1444
1445 #[test]
1446 fn text_paint_emits_textured_rects() {
1447 let t = TextRenderObject::new("Hi".into(), 24.0, Color::WHITE);
1448 let mut list = PaintList::new();
1449 t.paint(Point::new(0.0, 0.0), &mut list);
1450 assert!(!list.is_empty(), "paint should emit at least 1 textured rect");
1452 for cmd in &list.commands {
1453 match cmd {
1454 PaintCommand::TexturedRect { texture_id, uv, .. } => {
1455 assert_eq!(*texture_id, 0);
1456 assert!(uv[0] < uv[2]);
1457 assert!(uv[1] < uv[3]);
1458 }
1459 _ => panic!("expected TexturedRect, got Rect"),
1460 }
1461 }
1462 }
1463
1464 #[test]
1465 fn text_paint_with_offset_shifts_rects() {
1466 let t = TextRenderObject::new("X".into(), 24.0, Color::WHITE);
1467 let mut list = PaintList::new();
1468 t.paint(Point::new(100.0, 50.0), &mut list);
1469 for cmd in &list.commands {
1471 if let PaintCommand::TexturedRect { rect, .. } = cmd {
1472 assert!(rect.x >= 100.0 - 1.0, "x={}", rect.x);
1473 assert!(rect.y >= 50.0 - 1.0, "y={}", rect.y);
1474 }
1475 }
1476 }
1477
1478 #[test]
1480 fn shape_line_cache_hits_second_paint() {
1481 let mut list1 = PaintList::new();
1482 paint_text_line("cache-hit-test", 20.0, Color::WHITE, Point::ZERO, &mut list1, None);
1483 let calls_1 = with_font(|fs| fs.shape_calls);
1484
1485 let mut list2 = PaintList::new();
1486 paint_text_line("cache-hit-test", 20.0, Color::WHITE, Point::new(5.0, 5.0), &mut list2, None);
1487 let calls_2 = with_font(|fs| fs.shape_calls);
1488
1489 assert_eq!(calls_1, calls_2, "第二次 paint 应命中缓存,不再 shape");
1490 assert_eq!(list1.commands.len(), list2.commands.len(), "缓存命中的绘制输出数量应一致");
1491 }
1492
1493 #[test]
1494 fn line_height_is_in_shape_cache_key_and_changes_geometry() {
1495 set_text_line_height(1.2);
1497 let mut list = PaintList::new();
1498 paint_text_line("leading-probe", 20.0, Color::WHITE, Point::ZERO, &mut list, None);
1499 let find_line = |fs: &FontState, lhs: u32| -> Option<std::rc::Rc<ShapedLine>> {
1500 fs.line_cache
1501 .iter()
1502 .find(|(k, _)| k.0 == TextKey::Owned("leading-probe".into()) && k.4 == lhs)
1503 .map(|(_, e)| std::rc::Rc::clone(&e.line))
1504 };
1505 let line_12 = with_font(|fs| find_line(fs, 1.2f32.to_bits()));
1506 assert!(line_12.is_some(), "1.2 行高的 shaped line 应入缓存");
1507
1508 set_text_line_height(1.8);
1509 paint_text_line("leading-probe", 20.0, Color::WHITE, Point::ZERO, &mut PaintList::new(), None);
1510 let line_18 = with_font(|fs| find_line(fs, 1.8f32.to_bits()));
1511 assert!(line_18.is_some(), "切到 1.8 后必须重新 shape 并建新 key,不能命中旧行高缓存");
1512 assert!(
1513 !std::rc::Rc::ptr_eq(&line_12.unwrap(), &line_18.unwrap()),
1514 "两种行高必须是不同的 shaped line,不能串缓存"
1515 );
1516 set_text_line_height(1.2);
1517 }
1518
1519 #[test]
1520 fn set_text_line_height_rejects_invalid_values() {
1521 set_text_line_height(0.0);
1522 assert_eq!(text_line_height(), 1.2);
1523 set_text_line_height(-3.0);
1524 assert_eq!(text_line_height(), 1.2);
1525 set_text_line_height(f32::NAN);
1526 assert_eq!(text_line_height(), 1.2);
1527 set_text_line_height(1.5);
1528 assert_eq!(text_line_height(), 1.5);
1529 set_text_line_height(1.2);
1530 }
1531
1532 #[test]
1534 fn shape_line_cache_evicts_lru_at_limit() {
1535 let fake_line =
1536 || std::rc::Rc::new(ShapedLine { runs: Vec::new(), max_x: 0.0, max_y: 0.0, visual_lines: Vec::new() });
1537 let hot_key = (TextKey::Owned("hot-entry".to_string()), 0, None, 0, 1.2f32.to_bits());
1538 let oldest_key = (TextKey::Owned("fake-entry-0".to_string()), 0, None, 0, 1.2f32.to_bits());
1539 with_font(|fs| {
1540 fs.line_cache.clear();
1541 fs.line_clock = 0;
1542 fs.line_clock += 1;
1543 fs.line_cache.insert(hot_key.clone(), LineCacheEntry { line: fake_line(), last_used: fs.line_clock });
1544 for i in 0..LINE_CACHE_LIMIT - 1 {
1545 fs.line_clock += 1;
1546 fs.line_cache.insert(
1547 (TextKey::Owned(format!("fake-entry-{i}")), 0, None, 0, 1.2f32.to_bits()),
1548 LineCacheEntry { line: fake_line(), last_used: fs.line_clock },
1549 );
1550 }
1551 fs.line_clock += 1;
1553 fs.line_cache.get_mut(&hot_key).expect("hot entry").last_used = fs.line_clock;
1554 });
1555 let mut list = PaintList::new();
1557 paint_text_line("trigger-evict", 14.0, Color::WHITE, Point::ZERO, &mut list, None);
1558 with_font(|fs| {
1559 assert!(fs.line_cache.len() <= LINE_CACHE_LIMIT, "超限后应回收到上限内");
1560 assert!(fs.line_cache.len() >= LINE_CACHE_TARGET, "LRU 只应淘汰最旧 1/4");
1561 assert!(fs.line_cache.contains_key(&hot_key), "刚访问过的热条目不应被淘汰");
1562 assert!(!fs.line_cache.contains_key(&oldest_key), "最久未访问的条目应被淘汰");
1563 fs.line_cache.clear();
1564 });
1565 }
1566
1567 #[test]
1569 fn paint_rebuilds_evicted_raster_glyphs() {
1570 let mut first = PaintList::new();
1571 paint_text_line("raster-rebuild-test", 18.0, Color::WHITE, Point::ZERO, &mut first, None);
1572 assert!(!first.commands.is_empty());
1573
1574 with_font(|fs| {
1575 fs.raster_cache.clear();
1576 fs.raster_cache_bytes = 0;
1577 });
1578
1579 let mut second = PaintList::new();
1580 paint_text_line("raster-rebuild-test", 18.0, Color::WHITE, Point::ZERO, &mut second, None);
1581 assert_eq!(first.commands.len(), second.commands.len(), "位图淘汰后应重建 glyph,而不是丢字");
1582 assert!(!second.commands.is_empty());
1583 }
1584
1585 #[test]
1589 fn zero_size_glyphs_are_cached_not_rerasterized() {
1590 with_font(|fs| {
1591 fs.raster_cache.clear();
1592 fs.raster_cache_bytes = 0;
1593 let _ = shape_text(fs, "a b c", 13.0, None, DEFAULT_FONT_STACK);
1594 let cached = fs.raster_cache.len();
1595 assert!(
1596 fs.raster_cache.values().any(|g| g.width == 0 && g.height == 0),
1597 "空格等零尺寸 glyph 必须缓存占位,不能每次重栅格化"
1598 );
1599 let _ = shape_text(fs, "a b c d", 13.0, None, DEFAULT_FONT_STACK);
1602 assert_eq!(fs.raster_cache.len(), cached + 1, "除新字符外不得新增栅格化条目");
1603 fs.raster_cache.clear();
1604 fs.raster_cache_bytes = 0;
1605 });
1606 }
1607
1608 #[test]
1610 fn raster_cache_trims_to_budget() {
1611 with_font(|fs| {
1612 fs.raster_cache.clear();
1613 fs.raster_cache_bytes = 0;
1614 let chunk = vec![0u8; 8 * 1024 * 1024];
1615 for i in 0..5u16 {
1616 insert_raster_glyph(
1617 fs,
1618 GlyphKey::new(0, i, 0, 0, 0, 0),
1619 RasterGlyph { data: chunk.clone(), width: 2048, height: 1024, left: 0, top: 0, last_used: 0 },
1620 );
1621 }
1622 assert!(fs.raster_cache_bytes <= RASTER_CACHE_TARGET_BYTES, "应回收到目标水位");
1624 assert_eq!(fs.raster_cache.len(), 3, "LRU 应保留最近的条目");
1625 assert!(!fs.raster_cache.contains_key(&GlyphKey::new(0, 0, 0, 0, 0, 0)), "最旧条目应被淘汰");
1626 assert!(fs.raster_cache.contains_key(&GlyphKey::new(0, 4, 0, 0, 0, 0)), "最新条目应保留");
1627 fs.raster_cache.clear();
1628 fs.raster_cache_bytes = 0;
1629 });
1630 }
1631
1632 #[test]
1635 fn paint_text_line_dpr_rasterizes_at_physical_resolution() {
1636 fn paint_once(dpr: f32) -> (f32, f32, f32) {
1637 set_text_dpr(dpr);
1638 let mut list = PaintList::new();
1639 let width = paint_text_line("H", 24.0, Color::WHITE, Point::ZERO, &mut list, None);
1640 let (rect_w, uv_span) = match &list.commands[0] {
1641 PaintCommand::TexturedRect { rect, uv, .. } => (rect.width, (uv[2] - uv[0]) * ATLAS_SIZE as f32),
1642 _ => panic!("expected TexturedRect"),
1643 };
1644 set_text_dpr(1.0); (rect_w, uv_span, width)
1646 }
1647
1648 let (w1, span1, ret1) = paint_once(1.0);
1649 let (w2, span2, ret2) = paint_once(2.0);
1650
1651 assert!((w1 - w2).abs() <= 2.0, "rect 逻辑尺寸应 dpr 无关(允许取整 ≤2px): dpr1={w1} vs dpr2={w2}");
1653 assert!((ret1 - ret2).abs() < 0.5 && ret1 > 0.0, "返回宽度(逻辑)应 dpr 无关: {ret1} vs {ret2}");
1654 assert!(span2 > span1 * 1.5, "atlas 位图分辨率应随 dpr 变大: dpr1={span1}px vs dpr2={span2}px");
1655 let mw = measure_text_width("H", 24.0);
1656 assert!((ret1 - mw).abs() < 0.5, "paint 宽度应与 measure 一致(TextField 光标定位依赖): {ret1} vs {mw}");
1657 }
1658}
1659
1660pub fn is_rtl_text(text: &str) -> bool {
1666 for ch in text.chars() {
1667 let code = ch as u32;
1668 let rtl = matches!(
1669 code,
1670 0x0590..=0x05FF | 0x0600..=0x06FF | 0x0700..=0x074F | 0x0750..=0x077F | 0x0780..=0x07BF | 0x0860..=0x086F | 0x08A0..=0x08FF | 0xFB1D..=0xFB4F | 0xFB50..=0xFDFF | 0xFE70..=0xFEFF );
1681 if rtl {
1682 return true;
1683 }
1684 if ch.is_alphabetic() {
1685 return false;
1686 }
1687 }
1688 false
1689}
1690
1691pub fn mirror_carets_for_rtl(widths: &[f32]) -> Vec<f32> {
1697 let chars = widths.len().saturating_sub(1);
1698 if chars == 0 {
1699 return widths.to_vec();
1700 }
1701 let mut carets = vec![0.0f32; chars + 1];
1702 carets[0] = widths[chars];
1703 carets[1..=chars].copy_from_slice(&widths[..chars]);
1704 carets
1705}
1706
1707pub fn measure_caret_positions(text: &str, size_px: f32, font_stack: &str) -> Vec<f32> {
1709 let widths = measure_char_prefix_widths(text, size_px, font_stack);
1710 if is_rtl_text(text) {
1711 mirror_carets_for_rtl(&widths)
1712 } else {
1713 widths
1714 }
1715}
1716
1717pub fn nearest_caret_index(carets: &[f32], x: f32) -> usize {
1719 carets
1720 .iter()
1721 .enumerate()
1722 .min_by(|(ia, a), (ib, b)| (**a - x).abs().total_cmp(&(**b - x).abs()).then_with(|| ia.cmp(ib)))
1723 .map(|(index, _)| index)
1724 .unwrap_or(0)
1725}
1726
1727#[cfg(test)]
1728mod rtl_tests {
1729 use super::*;
1730
1731 #[test]
1732 fn detects_base_direction() {
1733 assert!(is_rtl_text("مرحبا بالعالم"));
1734 assert!(is_rtl_text("שלום"));
1735 assert!(!is_rtl_text("hello مرحبا")); assert!(!is_rtl_text("123 !?"));
1737 assert!(is_rtl_text("123 مرحبا")); }
1739
1740 #[test]
1741 fn rtl_caret_mirroring_and_nearest_index() {
1742 let widths = [0.0, 10.0, 25.0, 40.0];
1744 let carets = mirror_carets_for_rtl(&widths);
1745 assert_eq!(carets, vec![40.0, 0.0, 10.0, 25.0]);
1746 assert_eq!(nearest_caret_index(&carets, 38.0), 0, "靠近右缘 → 文本起点");
1747 assert_eq!(nearest_caret_index(&carets, 2.0), 1);
1748 assert_eq!(nearest_caret_index(&carets, 24.0), 3, "靠近左缘 → 文本末尾");
1749 assert_eq!(mirror_carets_for_rtl(&[0.0]), vec![0.0]);
1751 assert_eq!(nearest_caret_index(&widths, 12.0), 1);
1752 }
1753}
1754
1755#[derive(Clone, Debug, PartialEq)]
1762pub struct RichTextSpan {
1763 pub text: String,
1764 pub size_px: f32,
1765 pub color: Option<Color>,
1767 pub font_stack: Option<String>,
1769 pub weight: Option<u16>,
1776 pub italic: bool,
1778}
1779
1780impl RichTextSpan {
1781 pub fn new(text: impl Into<String>) -> Self {
1782 Self { text: text.into(), size_px: 15.0, color: None, font_stack: None, weight: None, italic: false }
1783 }
1784
1785 pub fn with_size(mut self, size_px: f32) -> Self {
1786 self.size_px = size_px;
1787 self
1788 }
1789
1790 pub fn with_color(mut self, color: Color) -> Self {
1791 self.color = Some(color);
1792 self
1793 }
1794
1795 pub fn with_font_stack(mut self, stack: impl Into<String>) -> Self {
1796 self.font_stack = Some(stack.into());
1797 self
1798 }
1799
1800 pub fn with_weight(mut self, weight: u16) -> Self {
1802 self.weight = Some(weight.clamp(1, 1000));
1803 self
1804 }
1805
1806 pub fn bold(self) -> Self {
1808 self.with_weight(700)
1809 }
1810
1811 pub fn with_italic(mut self, italic: bool) -> Self {
1812 self.italic = italic;
1813 self
1814 }
1815
1816 pub fn italic(self) -> Self {
1818 self.with_italic(true)
1819 }
1820}
1821
1822pub type InlinePainter = std::rc::Rc<dyn Fn(&mut PaintList, Rect)>;
1824
1825#[derive(Clone)]
1827pub struct InlineItem {
1828 pub width: f32,
1829 pub height: f32,
1830 pub painter: InlinePainter,
1831}
1832
1833impl InlineItem {
1834 pub fn new(width: f32, height: f32, painter: impl Fn(&mut PaintList, Rect) + 'static) -> Self {
1835 Self { width, height, painter: std::rc::Rc::new(painter) }
1836 }
1837}
1838
1839impl std::fmt::Debug for InlineItem {
1840 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1841 f.debug_struct("InlineItem").field("width", &self.width).field("height", &self.height).finish()
1842 }
1843}
1844
1845impl PartialEq for InlineItem {
1846 fn eq(&self, other: &Self) -> bool {
1847 self.width == other.width && self.height == other.height && std::rc::Rc::ptr_eq(&self.painter, &other.painter)
1848 }
1849}
1850
1851#[derive(Clone, Debug, PartialEq)]
1853pub enum RichItem {
1854 Text(RichTextSpan),
1855 Inline(InlineItem),
1856}
1857
1858#[derive(Clone, Debug, PartialEq)]
1860pub struct RichText {
1861 text: std::rc::Rc<str>,
1862 spans: Vec<RichTextSpan>,
1863 ranges: Vec<(usize, usize)>,
1864 inlines: Vec<(usize, InlineItem)>,
1866}
1867
1868impl RichText {
1869 pub fn new(spans: Vec<RichTextSpan>) -> Self {
1870 Self::from_items(spans.into_iter().map(RichItem::Text).collect())
1871 }
1872
1873 pub fn from_items(items: Vec<RichItem>) -> Self {
1874 let mut text = String::new();
1875 let mut spans = Vec::new();
1876 let mut ranges = Vec::new();
1877 let mut inlines = Vec::new();
1878 for item in items {
1879 match item {
1880 RichItem::Text(span) => {
1881 let start = text.len();
1882 text.push_str(&span.text);
1883 spans.push(span);
1884 ranges.push((start, text.len()));
1885 }
1886 RichItem::Inline(inline) => inlines.push((text.len(), inline)),
1887 }
1888 }
1889 Self { text: text.into(), spans, ranges, inlines }
1890 }
1891
1892 pub fn plain_text(&self) -> &str {
1894 &self.text
1895 }
1896
1897 pub fn spans(&self) -> &[RichTextSpan] {
1898 &self.spans
1899 }
1900
1901 pub fn is_empty(&self) -> bool {
1902 self.text.is_empty() && self.inlines.is_empty()
1903 }
1904}
1905
1906struct RichShapedGlyph {
1907 raster_key: GlyphKey,
1908 glyph_id: u16,
1909 x: f32,
1910 span: u16,
1912}
1913
1914struct RichShapedRun {
1915 glyphs: Vec<RichShapedGlyph>,
1916 baseline_y: f32,
1917 ascent: f32,
1919 font: parley::FontData,
1922 norm_coords: std::rc::Rc<[swash::NormalizedCoord]>,
1923 raster_size: f32,
1924}
1925
1926struct RichInlineBox {
1928 id: u16,
1930 x: f32,
1931 y: f32,
1932 width: f32,
1933 height: f32,
1934 line_baseline: f32,
1936}
1937
1938struct RichShapedLine {
1939 runs: Vec<RichShapedRun>,
1940 inline_boxes: Vec<RichInlineBox>,
1941 max_x: f32,
1942 max_y: f32,
1943}
1944
1945#[derive(Clone, PartialEq, Eq, Hash)]
1946struct RichCacheKey {
1947 text: std::rc::Rc<str>,
1948 styles: Vec<(usize, usize, u32, u64)>,
1950 inlines: Vec<(usize, u32, u32)>,
1952 width_bits: Option<u32>,
1953 dpr_bits: u32,
1954 line_height_bits: u32,
1956}
1957
1958struct RichCacheEntry {
1959 line: std::rc::Rc<RichShapedLine>,
1960 last_used: u64,
1961}
1962
1963fn rich_style_signature(rich: &RichText) -> Vec<(usize, usize, u32, u64)> {
1964 rich.ranges
1965 .iter()
1966 .zip(&rich.spans)
1967 .map(|((start, end), span)| {
1968 let stack = span.font_stack.as_deref().unwrap_or(DEFAULT_FONT_STACK);
1969 let mut h = DefaultHasher::new();
1970 stack.hash(&mut h);
1971 span.weight.unwrap_or(400).hash(&mut h);
1974 span.italic.hash(&mut h);
1975 (*start, *end, span.size_px.max(1.0).to_bits(), h.finish())
1976 })
1977 .collect()
1978}
1979
1980fn span_index_at(ranges: &[(usize, usize)], byte: usize) -> u16 {
1981 ranges.iter().position(|(start, end)| byte >= *start && byte < *end).unwrap_or(0) as u16
1982}
1983
1984fn shape_rich(fs: &mut FontState, rich: &RichText, max_width_px: Option<f32>) -> std::rc::Rc<RichShapedLine> {
1986 let dpr = text_dpr();
1987 let key = RichCacheKey {
1988 text: std::rc::Rc::clone(&rich.text),
1989 styles: rich_style_signature(rich),
1990 inlines: rich
1991 .inlines
1992 .iter()
1993 .map(|(index, inline)| (*index, inline.width.to_bits(), inline.height.to_bits()))
1994 .collect(),
1995 width_bits: max_width_px.map(|w| w.to_bits()),
1996 dpr_bits: dpr.to_bits(),
1997 line_height_bits: text_line_height().to_bits(),
1998 };
1999 if let Some(entry) = fs.rich_cache.get_mut(&key) {
2000 fs.rich_clock += 1;
2001 entry.last_used = fs.rich_clock;
2002 return std::rc::Rc::clone(&entry.line);
2003 }
2004
2005 let text: &str = &rich.text;
2006 let mut builder = fs.layout_cx.ranged_builder(&mut fs.font_cx, text, 1.0, true);
2007 builder.push_default(parley::StyleProperty::FontSize(15.0));
2008 builder.push_default(parley::StyleProperty::LineHeight(parley::LineHeight::FontSizeRelative(text_line_height())));
2010 builder.push_default(parley::StyleProperty::FontFamily(parley::FontFamily::Source(std::borrow::Cow::Borrowed(
2011 DEFAULT_FONT_STACK,
2012 ))));
2013 builder.push_default(parley::StyleProperty::WordBreak(parley::WordBreak::KeepAll));
2014 builder.push_default(parley::StyleProperty::OverflowWrap(parley::OverflowWrap::Anywhere));
2015 for ((start, end), span) in rich.ranges.iter().zip(&rich.spans) {
2016 if span.size_px > 0.0 {
2017 builder.push(parley::StyleProperty::FontSize(span.size_px), *start..*end);
2018 }
2019 if let Some(stack) = &span.font_stack {
2020 builder.push(
2021 parley::StyleProperty::FontFamily(parley::FontFamily::Source(std::borrow::Cow::Borrowed(stack))),
2022 *start..*end,
2023 );
2024 }
2025 if let Some(weight) = span.weight {
2027 builder.push(parley::StyleProperty::FontWeight(parley::FontWeight::new(weight as f32)), *start..*end);
2028 }
2029 if span.italic {
2030 builder.push(parley::StyleProperty::FontStyle(parley::FontStyle::Italic), *start..*end);
2031 }
2032 }
2033 for (id, (index, inline)) in rich.inlines.iter().enumerate() {
2034 builder.push_inline_box(parley::InlineBox {
2035 id: id as u64,
2036 index: *index,
2037 width: inline.width,
2038 height: inline.height,
2039 kind: parley::InlineBoxKind::InFlow,
2047 baseline: None,
2048 vertical_align: parley::VerticalAlign::BASELINE,
2049 });
2050 }
2051 let mut layout: parley::Layout<()> = builder.build(text);
2052 let wrap_opt = max_width_px.filter(|w| *w > 0.0);
2053 layout.break_all_lines(wrap_opt);
2054 layout.align(parley::Alignment::Start, parley::AlignmentOptions::default());
2055
2056 let mut runs = Vec::new();
2057 let mut inline_boxes = Vec::new();
2058 let mut max_x = 0.0f32;
2059 let mut max_y = 0.0f32;
2060 for line in layout.lines() {
2061 let line_m = line.metrics();
2062 let baseline_y = line_m.baseline * dpr;
2063 for item in line.items() {
2064 let parley::PositionedLayoutItem::GlyphRun(gr) = item else {
2065 if let parley::PositionedLayoutItem::InlineBox(b) = item {
2066 inline_boxes.push(RichInlineBox {
2067 id: b.id as u16,
2068 x: b.x,
2069 y: b.y,
2070 width: b.width,
2071 height: b.height,
2072 line_baseline: baseline_y,
2073 });
2074 max_x = max_x.max((b.x + b.width) * dpr);
2075 max_y = max_y.max((b.y + b.height) * dpr);
2076 }
2077 continue;
2078 };
2079 let run_metrics = gr.run().font_metrics();
2080 let ascent = run_metrics.ascent * dpr;
2081 let descent = run_metrics.descent * dpr;
2082 let font_size_phys = gr.run().font_size() * dpr;
2083 let font_blob_id = gr.run().font().data.id() as usize;
2084 let norm_coords: std::rc::Rc<[swash::NormalizedCoord]> =
2087 gr.run().normalized_coords().iter().map(|c| c.to_bits()).collect();
2088 let run_font = gr.run().font().clone();
2089 let mut pen_x = gr.offset();
2090 let mut run_glyphs = Vec::new();
2091 for cluster in gr.run().visual_clusters() {
2092 let cluster_byte = cluster.text_range().start;
2093 let span = span_index_at(&rich.ranges, cluster_byte);
2094 for g in cluster.glyphs() {
2095 let glyph_id = match narrow_glyph_id(g.id) {
2098 Some(id) => id,
2099 None => {
2100 log::warn!("mgui-text: glyph id {} 超出 swash 的 u16 范围,跳过该字形", g.id);
2101 pen_x += g.advance;
2102 continue;
2103 }
2104 };
2105 let raster_key = GlyphKey::new(
2106 raster_font_id(font_blob_id, &norm_coords),
2107 glyph_id,
2108 font_size_phys.to_bits(),
2109 0,
2110 0,
2111 0,
2112 );
2113 if !fs.raster_cache.contains_key(&raster_key) {
2114 if let Some(rg) =
2115 rasterize_one_glyph(&run_font, font_size_phys, glyph_id, &norm_coords, &mut fs.scale_cx)
2116 {
2117 insert_raster_glyph(fs, raster_key, rg);
2118 }
2119 }
2120 let gx = pen_x + g.x;
2121 run_glyphs.push(RichShapedGlyph { raster_key, glyph_id, x: gx * dpr, span });
2122 max_x = max_x.max((gx + g.advance) * dpr);
2123 max_y = max_y.max(baseline_y + descent);
2124 pen_x += g.advance;
2125 }
2126 }
2127 if !run_glyphs.is_empty() {
2128 runs.push(RichShapedRun {
2129 glyphs: run_glyphs,
2130 baseline_y,
2131 ascent,
2132 font: run_font,
2133 norm_coords,
2134 raster_size: font_size_phys,
2135 });
2136 }
2137 }
2138 }
2139 if max_y == 0.0 {
2140 max_y = rich.spans.iter().map(|s| s.size_px).fold(15.0, f32::max) * 1.2 * dpr;
2141 }
2142
2143 let line = std::rc::Rc::new(RichShapedLine { runs, inline_boxes, max_x, max_y });
2144 if fs.rich_cache.len() >= LINE_CACHE_LIMIT {
2145 fs.rich_cache.clear();
2146 }
2147 fs.rich_clock += 1;
2148 fs.rich_cache.insert(key, RichCacheEntry { line: std::rc::Rc::clone(&line), last_used: fs.rich_clock });
2149 line
2150}
2151
2152pub fn rich_text_size(rich: &RichText, max_width: Option<f32>) -> Size {
2154 if rich.is_empty() {
2155 return Size::ZERO;
2156 }
2157 with_font(|fs| {
2158 let dpr = text_dpr();
2159 let shaped = shape_rich(fs, rich, max_width);
2160 let first_baseline = shaped.runs.first().map(|r| r.baseline_y);
2161 let (anchor, fallback_h) = match first_baseline {
2162 Some(baseline) => {
2163 let first_ascent =
2165 shaped.runs.iter().filter(|r| r.baseline_y == baseline).map(|r| r.ascent).fold(0.0f32, f32::max);
2166 let inline_top = shaped
2167 .inline_boxes
2168 .iter()
2169 .filter(|b| b.line_baseline == baseline)
2170 .map(|b| b.y * dpr)
2171 .fold(f32::INFINITY, f32::min);
2172 ((baseline - first_ascent).min(inline_top), 0.0)
2174 }
2175 None => (0.0, shaped.max_y),
2176 };
2177 let height = if shaped.max_y > anchor { (shaped.max_y - anchor) / dpr } else { fallback_h / dpr };
2178 Size::new(shaped.max_x / dpr, height)
2179 })
2180}
2181
2182#[derive(Clone, Debug, PartialEq)]
2184pub struct RichTextLayout {
2185 pub size: Size,
2186 pub inline_rects: Vec<Rect>,
2187}
2188
2189pub fn rich_text_layout(rich: &RichText, max_width: Option<f32>) -> RichTextLayout {
2191 if rich.is_empty() {
2192 return RichTextLayout { size: Size::ZERO, inline_rects: Vec::new() };
2193 }
2194 with_font(|fs| {
2195 let dpr = text_dpr();
2196 let shaped = shape_rich(fs, rich, max_width);
2197 let first_baseline = shaped.runs.first().map(|r| r.baseline_y);
2198 let anchor = match first_baseline {
2199 Some(baseline) => {
2200 let first_ascent =
2201 shaped.runs.iter().filter(|r| r.baseline_y == baseline).map(|r| r.ascent).fold(0.0f32, f32::max);
2202 let inline_top = shaped
2203 .inline_boxes
2204 .iter()
2205 .filter(|b| b.line_baseline == baseline)
2206 .map(|b| b.y * dpr)
2207 .fold(f32::INFINITY, f32::min);
2208 (baseline - first_ascent).min(inline_top)
2209 }
2210 None => 0.0,
2211 };
2212 let height = if shaped.max_y > anchor { (shaped.max_y - anchor) / dpr } else { 0.0 };
2213 let mut inline_rects = vec![Rect::new(0.0, 0.0, 0.0, 0.0); rich.inlines.len()];
2214 for b in &shaped.inline_boxes {
2215 if let Some(slot) = inline_rects.get_mut(b.id as usize) {
2216 *slot = Rect::new(b.x, (b.y * dpr - anchor) / dpr, b.width, b.height);
2217 }
2218 }
2219 RichTextLayout { size: Size::new(shaped.max_x / dpr, height), inline_rects }
2220 })
2221}
2222
2223pub fn paint_rich_text(rich: &RichText, offset: Point, list: &mut PaintList, max_width: Option<f32>) -> f32 {
2225 paint_rich_text_with_default(rich, Color::WHITE, offset, list, max_width)
2226}
2227
2228pub fn paint_rich_text_with_default(
2230 rich: &RichText,
2231 default_color: Color,
2232 offset: Point,
2233 list: &mut PaintList,
2234 max_width: Option<f32>,
2235) -> f32 {
2236 if rich.is_empty() {
2237 return 0.0;
2238 }
2239 with_font(|fs| {
2240 let dpr = text_dpr();
2241 let shaped = shape_rich(fs, rich, max_width);
2242 let Some(first_run) = shaped.runs.first() else {
2243 return 0.0;
2244 };
2245 let first_baseline = first_run.baseline_y;
2246 let first_ascent =
2247 shaped.runs.iter().filter(|r| r.baseline_y == first_baseline).map(|r| r.ascent).fold(0.0f32, f32::max);
2248 let inline_top = shaped
2249 .inline_boxes
2250 .iter()
2251 .filter(|b| b.line_baseline == first_baseline)
2252 .map(|b| b.y * dpr)
2253 .fold(f32::INFINITY, f32::min);
2254 let anchor = (first_baseline - first_ascent).min(inline_top);
2255
2256 for run in &shaped.runs {
2257 for sg in &run.glyphs {
2258 if !fs.raster_cache.contains_key(&sg.raster_key) {
2259 if let Some(rg) =
2260 rasterize_one_glyph(&run.font, run.raster_size, sg.glyph_id, &run.norm_coords, &mut fs.scale_cx)
2261 {
2262 insert_raster_glyph(fs, sg.raster_key, rg);
2263 }
2264 }
2265 let Some(r) = fs.raster_cache.get_mut(&sg.raster_key) else {
2266 continue;
2267 };
2268 if r.width == 0 || r.height == 0 {
2269 continue;
2270 }
2271 fs.glyph_clock += 1;
2272 r.last_used = fs.glyph_clock;
2273 let entry = fs.atlas.get_or_insert(sg.raster_key, &r.data, r.width, r.height);
2274
2275 let x = offset.x + (sg.x + r.left as f32) / dpr;
2276 let glyph_visual_top = run.baseline_y - r.top as f32;
2277 let y = offset.y + (glyph_visual_top - anchor) / dpr;
2278 let rect = Rect::new(x, y, r.width as f32 / dpr, r.height as f32 / dpr);
2279 let color = rich.spans.get(sg.span as usize).and_then(|s| s.color).unwrap_or(default_color);
2280 list.push(PaintCommand::TexturedRect {
2281 rect,
2282 color,
2283 uv: entry.uv,
2284 texture_id: 0,
2285 mode: mgui_core::paint::TextureMode::Mask,
2286 });
2287 }
2288 }
2289 for b in &shaped.inline_boxes {
2290 if let Some((_, inline)) = rich.inlines.get(b.id as usize) {
2291 let rect = Rect::new(offset.x + b.x, offset.y + b.y - anchor / dpr, b.width, b.height);
2292 (inline.painter)(list, rect);
2293 }
2294 }
2295 shaped.max_x / dpr
2296 })
2297}
2298
2299#[cfg(test)]
2300mod rich_text_tests {
2301 use super::*;
2302
2303 #[test]
2304 fn mixed_styles_measure_and_paint_with_span_colors() {
2305 set_text_dpr(1.0);
2306 let red = Color::from_rgb8(255, 0, 0);
2307 let rich = RichText::new(vec![
2308 RichTextSpan::new("Hello ").with_size(18.0).with_color(Color::WHITE),
2309 RichTextSpan::new("World").with_size(30.0).with_color(red),
2310 ]);
2311 let size = rich_text_size(&rich, None);
2312 assert!(size.width > 0.0, "宽度必须 > 0");
2313 assert!(size.height >= 30.0, "高度应容纳 30px 字号: {size:?}");
2314
2315 let mut list = PaintList::new();
2316 let width = paint_rich_text(&rich, Point::ZERO, &mut list, None);
2317 assert!((width - size.width).abs() < 0.5, "绘制宽度应与测量一致: {width} vs {}", size.width);
2318 let colors: Vec<Color> = list
2319 .commands
2320 .iter()
2321 .filter_map(|c| match c {
2322 PaintCommand::TexturedRect { color, .. } => Some(*color),
2323 _ => None,
2324 })
2325 .collect();
2326 assert!(colors.contains(&Color::WHITE), "应包含第一段白色字形");
2327 assert!(colors.contains(&red), "应包含第二段红色字形");
2328 }
2329
2330 #[test]
2331 fn inline_item_measures_paints_and_sits_on_baseline() {
2332 use std::cell::RefCell;
2333 set_text_dpr(1.0);
2334 let captured: std::rc::Rc<RefCell<Option<Rect>>> = std::rc::Rc::new(RefCell::new(None));
2335 let cap = captured.clone();
2336 let rich = RichText::from_items(vec![
2337 RichItem::Text(RichTextSpan::new("A").with_size(16.0)),
2338 RichItem::Inline(InlineItem::new(30.0, 24.0, move |_list, rect| *cap.borrow_mut() = Some(rect))),
2339 RichItem::Text(RichTextSpan::new("B").with_size(16.0)),
2340 ]);
2341 let size = rich_text_size(&rich, None);
2342 assert!(size.width >= 30.0, "宽度应包含内联项: {size:?}");
2343 assert!(size.height >= 20.0, "高度应容纳内联项: {size:?}");
2344
2345 let mut list = PaintList::new();
2346 let width = paint_rich_text(&rich, Point::new(10.0, 5.0), &mut list, None);
2347 assert!(width >= 30.0);
2348 let rect = captured.borrow().expect("内联项绘制回调应被调用");
2349 assert!((rect.width - 30.0).abs() < 0.01 && (rect.height - 24.0).abs() < 0.01, "{rect:?}");
2350 assert!(rect.x >= 10.0 && rect.y >= 5.0, "内联项应带 offset: {rect:?}");
2351 }
2352
2353 #[test]
2354 fn inline_items_wrap_when_narrow() {
2355 set_text_dpr(1.0);
2356 let rich = RichText::from_items(vec![
2357 RichItem::Inline(InlineItem::new(40.0, 20.0, |_, _| {})),
2358 RichItem::Inline(InlineItem::new(40.0, 20.0, |_, _| {})),
2359 ]);
2360 let one_line = rich_text_size(&rich, None);
2361 let wrapped = rich_text_size(&rich, Some(50.0));
2362 assert!(one_line.width > wrapped.width, "窄宽度应减少行宽: {one_line:?} vs {wrapped:?}");
2363 assert!(
2364 wrapped.height > one_line.height * 1.5,
2365 "两个 40 宽内联项在 50 宽内应换行: {one_line:?} vs {wrapped:?}"
2366 );
2367 }
2368
2369 #[test]
2370 fn soft_wrap_uses_max_width() {
2371 set_text_dpr(1.0);
2372 let rich = RichText::new(vec![RichTextSpan::new("word ".repeat(40)).with_size(16.0)]);
2373 let single = rich_text_size(&rich, None);
2374 let wrapped = rich_text_size(&rich, Some(120.0));
2375 assert!(single.height > 0.0 && wrapped.height > 0.0);
2376 assert!(wrapped.height > single.height * 2.0, "换行后高度应显著增加: {single:?} vs {wrapped:?}");
2377 assert!(wrapped.width <= 130.0, "换行后宽度应受 max_width 约束: {wrapped:?}");
2378 }
2379
2380 #[test]
2391 fn trailing_spaces_hang_instead_of_forming_a_phantom_line() {
2392 set_text_dpr(1.0);
2393 let size = 16.0;
2394 let visible = "aaa bbb";
2395 let text = "aaa bbb ";
2396 let w_visible = measure_text_width(visible, size);
2397 let w_full = measure_text_width(text, size);
2398 assert!(w_full > w_visible + 1.0, "前置条件:尾空格要确实更宽,否则这个用例没有鉴别力");
2399 let max_width = (w_visible + w_full) * 0.5;
2400
2401 let ranges = wrapped_line_ranges(text, size, max_width);
2402 assert_eq!(ranges.len(), 1, "尾空格该挂在行外,不该另起一行:{ranges:?}(max_width={max_width})");
2403 assert_eq!(ranges[0], (0, text.len()), "唯一一行要覆盖全文,包括挂出去的空格");
2404
2405 let h = text_visual_height(text, size, Some(max_width));
2407 let h_visible_only = text_visual_height(visible, size, Some(max_width));
2408 assert!((h - h_visible_only).abs() < 0.5, "多三个尾空格不该改变块高:全文={h} 仅可见={h_visible_only}");
2409 }
2410
2411 #[test]
2412 fn span_builders_set_weight_and_italic() {
2413 assert_eq!(RichTextSpan::new("x").weight, None, "默认不指定字重(跟随 400)");
2414 assert!(!RichTextSpan::new("x").italic);
2415 assert_eq!(RichTextSpan::new("x").bold().weight, Some(700));
2416 assert_eq!(RichTextSpan::new("x").with_weight(500).weight, Some(500));
2417 assert_eq!(RichTextSpan::new("x").with_weight(0).weight, Some(1), "非法值夹紧到 ≥1");
2418 assert!(RichTextSpan::new("x").italic().italic);
2419 assert!(!RichTextSpan::new("x").with_italic(true).with_italic(false).italic);
2420 }
2421
2422 #[test]
2423 fn bold_span_is_wider_and_cache_keeps_weights_apart() {
2424 set_text_dpr(1.0);
2425 let text = "Handgloves 字重";
2426 let regular = RichText::new(vec![RichTextSpan::new(text).with_size(20.0)]);
2427 let bold = RichText::new(vec![RichTextSpan::new(text).with_size(20.0).bold()]);
2428
2429 let w_regular = rich_text_size(®ular, None).width;
2430 let w_bold = rich_text_size(&bold, None).width;
2431 assert!(w_bold > w_regular + 0.5, "粗体字面应比常规更宽: regular={w_regular} bold={w_bold}");
2432 assert!((rich_text_size(®ular, None).width - w_regular).abs() < 0.01, "缓存不能把粗体轮廓复用给常规 span");
2434
2435 let mut list = PaintList::new();
2436 let painted = paint_rich_text(&bold, Point::ZERO, &mut list, None);
2437 assert!((painted - w_bold).abs() < 0.5, "绘制宽度应与测量一致: {painted} vs {w_bold}");
2438 let glyphs = list.commands.iter().filter(|c| matches!(c, PaintCommand::TexturedRect { .. })).count();
2439 assert!(glyphs > 4, "粗体也应画出成片字形,实际 {glyphs}");
2440 }
2441
2442 #[test]
2443 fn italic_span_paints_without_changing_line_box() {
2444 set_text_dpr(1.0);
2445 let text = "Italic style";
2446 let regular = RichText::new(vec![RichTextSpan::new(text).with_size(18.0)]);
2447 let italic = RichText::new(vec![RichTextSpan::new(text).with_size(18.0).italic()]);
2448 let mut list = PaintList::new();
2449 let painted = paint_rich_text(&italic, Point::ZERO, &mut list, None);
2450 let glyphs = list.commands.iter().filter(|c| matches!(c, PaintCommand::TexturedRect { .. })).count();
2451 assert!(glyphs > 4, "斜体应照常成片绘制,实际 {glyphs}");
2452 let w_italic = rich_text_size(&italic, None).width;
2453 assert!(w_italic > 0.0, "斜体宽度有效: {w_italic}");
2454 assert!((painted - w_italic).abs() < 0.5, "斜体绘制宽度应与测量一致: {painted} vs {w_italic}");
2455 assert!(
2457 w_italic.abs() < rich_text_size(®ular, None).width * 2.0,
2458 "斜体宽度应与常规同量级: italic={w_italic}"
2459 );
2460 }
2461
2462 #[test]
2463 fn raster_font_id_folds_variation_coords() {
2464 assert_eq!(raster_font_id(42, &[]), 42);
2466 let a: [swash::NormalizedCoord; 1] = [1];
2467 let b: [swash::NormalizedCoord; 1] = [2];
2468 let coords_a: &[swash::NormalizedCoord] = &a;
2469 let coords_b: &[swash::NormalizedCoord] = &b;
2470 assert_ne!(raster_font_id(42, coords_a), raster_font_id(42, coords_b), "不同可变轴坐标必须是不同栅格身份");
2471 assert_eq!(raster_font_id(42, coords_a), raster_font_id(42, coords_a), "同坐标必须稳定(缓存命中)");
2472 assert_ne!(raster_font_id(42, coords_a), raster_font_id(43, coords_a), "不同 blob 也必须区分");
2473 }
2474}
2475
2476#[cfg(test)]
2481mod multiline_regression {
2482 use super::*;
2483
2484 #[test]
2486 fn multiline_text_lines_have_distinct_y() {
2487 let mut list = PaintList::new();
2488 paint_text_line("第一行AAA\n第二行BBB", 20.0, Color::WHITE, Point::new(50.0, 100.0), &mut list, None);
2489 let ys: Vec<f32> = list
2490 .commands
2491 .iter()
2492 .filter_map(|c| match c {
2493 PaintCommand::TexturedRect { rect, .. } => Some((rect.y * 10.0).round() / 10.0),
2494 _ => None,
2495 })
2496 .collect();
2497 assert!(!ys.is_empty(), "应画出 glyph");
2498 let y0 = ys[0];
2499 assert!(ys.iter().any(|&y| (y - y0).abs() > 20.0), "多行文本各行 y 必须拉开,实际全部≈{}: {:?}", y0, ys);
2500 }
2501
2502 #[test]
2504 fn wrapped_text_lines_have_distinct_y() {
2505 let mut list = PaintList::new();
2506 paint_text_line(
2508 "第一行文本内容比较长需要折行",
2509 20.0,
2510 Color::WHITE,
2511 Point::new(0.0, 0.0),
2512 &mut list,
2513 Some(60.0),
2514 );
2515 let ys: Vec<f32> = list
2516 .commands
2517 .iter()
2518 .filter_map(|c| match c {
2519 PaintCommand::TexturedRect { rect, .. } => Some((rect.y * 10.0).round() / 10.0),
2520 _ => None,
2521 })
2522 .collect();
2523 let y0 = ys[0];
2524 assert!(ys.iter().any(|&y| (y - y0).abs() > 20.0), "soft-wrap 多行 y 必须拉开,实际全部≈{}: {:?}", y0, ys);
2525 }
2526}