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
85impl GlyphKey {
86 pub fn new(
88 font_blob_id: usize,
89 glyph_id: u16,
90 size_px_bits: u32,
91 x_bin: i32,
92 y_bin: i32,
93 subpixel_bits: u8,
94 ) -> Self {
95 let mut h = DefaultHasher::new();
96 font_blob_id.hash(&mut h);
97 glyph_id.hash(&mut h);
98 size_px_bits.hash(&mut h);
99 x_bin.hash(&mut h);
100 y_bin.hash(&mut h);
101 subpixel_bits.hash(&mut h);
102 GlyphKey(h.finish())
103 }
104}
105
106fn raster_font_id(font_blob_id: usize, coords: &[swash::NormalizedCoord]) -> usize {
111 if coords.is_empty() {
112 return font_blob_id;
113 }
114 let mut h = DefaultHasher::new();
115 font_blob_id.hash(&mut h);
116 for c in coords {
117 c.hash(&mut h);
118 }
119 h.finish() as usize
120}
121
122impl Atlas {
123 pub fn new(width: u32, height: u32) -> Self {
124 Self {
125 width,
126 height,
127 next_x: 0,
128 next_y: 0,
129 row_height: 0,
130 pixels: vec![0; (width * height) as usize],
131 entries: HashMap::new(),
132 dirty: false,
133 dirty_rows: None,
134 generation: 1,
135 }
136 }
137
138 fn expand_2x(&mut self) {
141 let new_w = (self.width * 2).min(MAX_ATLAS_SIZE);
142 let new_h = (self.height * 2).min(MAX_ATLAS_SIZE);
143 if new_w == self.width && new_h == self.height {
144 return; }
146 let old_w = self.width;
147 let old_h = self.height;
148 let new_size = (new_w * new_h) as usize;
149 let mut new_pixels = vec![0u8; new_size];
150 for row in 0..old_h as usize {
152 let src_start = row * old_w as usize;
153 let dst_start = row * new_w as usize;
154 new_pixels[dst_start..dst_start + old_w as usize]
155 .copy_from_slice(&self.pixels[src_start..src_start + old_w as usize]);
156 }
157 self.pixels = new_pixels;
158 let scale_u = old_w as f32 / new_w as f32; let scale_v = old_h as f32 / new_h as f32;
161 for entry in self.entries.values_mut() {
162 entry.uv[0] *= scale_u;
163 entry.uv[1] *= scale_v;
164 entry.uv[2] *= scale_u;
165 entry.uv[3] *= scale_v;
166 }
167 self.width = new_w;
168 self.height = new_h;
169 self.dirty = true;
170 self.dirty_rows = Some((0, new_h));
171 self.generation += 1;
172 mgui_core::element::request_full_repaint();
174 }
175
176 fn clear_atlas(&mut self) {
179 self.entries.clear();
180 self.pixels.fill(0);
181 self.next_x = 0;
182 self.next_y = 0;
183 self.row_height = 0;
184 self.dirty = true;
185 self.dirty_rows = Some((0, self.height));
186 self.generation += 1;
187 mgui_core::element::request_full_repaint();
188 }
189
190 pub fn get_or_insert(&mut self, key: GlyphKey, bitmap: &[u8], w: u32, h: u32) -> AtlasEntry {
194 if let Some(&e) = self.entries.get(&key) {
195 return e;
196 }
197 let alloc_w = w + ATLAS_PADDING * 2;
199 let alloc_h = h + ATLAS_PADDING * 2;
200 if self.next_x + alloc_w > self.width {
202 self.next_x = 0;
203 self.next_y += self.row_height;
204 self.row_height = 0;
205 }
206 if self.next_y + alloc_h > self.height {
207 if self.width >= MAX_ATLAS_SIZE && self.height >= MAX_ATLAS_SIZE {
209 self.clear_atlas();
210 } else {
211 self.expand_2x();
212 }
213 return self.get_or_insert(key, bitmap, w, h);
215 }
216 let dst_x = self.next_x + ATLAS_PADDING;
217 let dst_y = self.next_y + ATLAS_PADDING;
218
219 for row in 0..h {
221 let src_start = (row * w) as usize;
222 let src_end = src_start + w as usize;
223 let dst_row = (dst_y + row) as usize * self.width as usize + dst_x as usize;
224 self.pixels[dst_row..dst_row + w as usize].copy_from_slice(&bitmap[src_start..src_end]);
225 }
226
227 let u0 = dst_x as f32 / self.width as f32;
229 let v0 = dst_y as f32 / self.height as f32;
230 let u1 = (dst_x + w) as f32 / self.width as f32;
231 let v1 = (dst_y + h) as f32 / self.height as f32;
232
233 let entry = AtlasEntry { uv: [u0, v0, u1, v1], width: w, height: h };
234 self.entries.insert(key, entry);
235 self.next_x += alloc_w;
236 if alloc_h > self.row_height {
237 self.row_height = alloc_h;
238 }
239 self.mark_rows_written(dst_y, h);
241 self.generation += 1;
242 entry
243 }
244
245 fn mark_rows_written(&mut self, y: u32, h: u32) {
247 self.dirty = true;
248 let end = (y + h).min(self.height);
249 self.dirty_rows = Some(match self.dirty_rows {
250 Some((top, bottom)) => (top.min(y), bottom.max(end)),
251 None => (y, end),
252 });
253 }
254
255 pub fn pixels(&self) -> &[u8] {
257 &self.pixels
258 }
259
260 #[allow(dead_code)]
262 pub fn glyph_count(&self) -> usize {
263 self.entries.len()
264 }
265
266 pub fn is_dirty(&self) -> bool {
268 self.dirty
269 }
270
271 pub fn clear_dirty(&mut self) {
273 self.dirty = false;
274 self.dirty_rows = None;
275 }
276}
277
278#[derive(Clone)]
284struct RasterGlyph {
285 data: Vec<u8>,
286 width: u32,
287 height: u32,
288 left: i32,
290 top: i32,
291 last_used: u64,
293}
294
295type LineCacheKey = (TextKey, u32, Option<u32>, u64);
298
299struct LineCacheEntry {
301 line: std::rc::Rc<ShapedLine>,
302 last_used: u64,
303}
304
305pub struct FontState {
307 pub font_cx: parley::FontContext,
308 pub layout_cx: parley::LayoutContext<()>,
309 pub scale_cx: swash::scale::ScaleContext,
310 pub atlas: Atlas,
311 raster_cache: HashMap<GlyphKey, RasterGlyph>,
313 raster_cache_bytes: usize,
315 line_cache: HashMap<LineCacheKey, LineCacheEntry>,
322 rich_cache: HashMap<RichCacheKey, RichCacheEntry>,
324 rich_clock: u64,
326 line_clock: u64,
328 glyph_clock: u64,
330 pub shape_calls: usize,
332}
333
334impl FontState {
335 fn new() -> Self {
336 Self {
337 font_cx: parley::FontContext::new(),
338 layout_cx: parley::LayoutContext::<()>::new(),
339 scale_cx: swash::scale::ScaleContext::new(),
340 atlas: Atlas::new(ATLAS_SIZE, ATLAS_SIZE),
341 raster_cache: HashMap::new(),
342 raster_cache_bytes: 0,
343 line_cache: HashMap::new(),
344 rich_cache: HashMap::new(),
345 rich_clock: 0,
346 line_clock: 0,
347 glyph_clock: 0,
348 shape_calls: 0,
349 }
350 }
351}
352
353thread_local! {
354 static FONT_STATE: RefCell<Option<FontState>> = const { RefCell::new(None) }; static TEXT_DPR: std::cell::Cell<f32> = const { std::cell::Cell::new(1.0) };
360}
361
362pub fn set_text_dpr(dpr: f32) {
364 TEXT_DPR.with(|c| c.set(if dpr > 0.0 { dpr } else { 1.0 }));
365}
366
367fn text_dpr() -> f32 {
368 TEXT_DPR.with(|c| c.get())
369}
370
371pub fn with_font<F, R>(f: F) -> R
373where
374 F: FnOnce(&mut FontState) -> R,
375{
376 FONT_STATE.with(|cell| {
377 let mut opt = cell.borrow_mut();
378 if opt.is_none() {
379 *opt = Some(FontState::new());
380 }
381 f(opt.as_mut().unwrap())
382 })
383}
384
385const LINE_CACHE_LIMIT: usize = 4096;
394
395const LINE_CACHE_TARGET: usize = LINE_CACHE_LIMIT - LINE_CACHE_LIMIT / 4;
397
398fn evict_line_cache_lru(fs: &mut FontState) {
400 if fs.line_cache.len() <= LINE_CACHE_TARGET {
401 return;
402 }
403 let mut by_age: Vec<(u64, LineCacheKey)> = fs.line_cache.iter().map(|(k, v)| (v.last_used, k.clone())).collect();
404 by_age.sort_unstable_by_key(|&(last_used, _)| last_used);
405 let remove = fs.line_cache.len().saturating_sub(LINE_CACHE_TARGET);
406 for (_, key) in by_age.into_iter().take(remove) {
407 fs.line_cache.remove(&key);
408 }
409}
410
411const RASTER_CACHE_BUDGET_BYTES: usize = 32 * 1024 * 1024;
413const RASTER_CACHE_TARGET_BYTES: usize = RASTER_CACHE_BUDGET_BYTES * 3 / 4;
415
416fn insert_raster_glyph(fs: &mut FontState, key: GlyphKey, mut glyph: RasterGlyph) {
418 fs.glyph_clock += 1;
419 glyph.last_used = fs.glyph_clock;
420 let bytes = glyph.data.len();
421 if let Some(old) = fs.raster_cache.insert(key, glyph) {
422 fs.raster_cache_bytes = fs.raster_cache_bytes.saturating_sub(old.data.len());
423 }
424 fs.raster_cache_bytes += bytes;
425 trim_raster_cache(fs);
426}
427
428fn trim_raster_cache(fs: &mut FontState) {
433 if fs.raster_cache_bytes <= RASTER_CACHE_BUDGET_BYTES {
434 return;
435 }
436 let mut candidates: Vec<(u64, GlyphKey, usize)> =
437 fs.raster_cache.iter().map(|(&key, g)| (g.last_used, key, g.data.len())).collect();
438 candidates.sort_unstable_by_key(|&(last_used, _, _)| last_used);
439 for (_, key, bytes) in candidates {
440 if fs.raster_cache_bytes <= RASTER_CACHE_TARGET_BYTES {
441 break;
442 }
443 fs.raster_cache.remove(&key);
444 fs.raster_cache_bytes = fs.raster_cache_bytes.saturating_sub(bytes);
445 }
446}
447
448#[derive(Clone, PartialEq, Eq, Hash)]
454enum TextKey {
455 Owned(String),
456 Shared(std::rc::Rc<str>, Option<(usize, usize)>),
457}
458
459impl TextKey {
460 fn owned(text: &str) -> Self {
461 TextKey::Owned(text.to_string())
462 }
463}
464
465struct ShapedGlyph {
467 raster_key: GlyphKey,
469 glyph_id: u16,
471 x: f32,
473 w: f32,
475 #[allow(dead_code)]
477 y: f32,
478 ascent: f32,
480 descent: f32,
482 cluster: u32,
485}
486
487struct ShapedRun {
489 glyphs: Vec<ShapedGlyph>,
490 baseline_y: f32,
492 font: parley::Font,
494 norm_coords: std::rc::Rc<[swash::NormalizedCoord]>,
496 raster_size: f32,
498}
499
500struct ShapedLine {
502 runs: Vec<ShapedRun>,
503 max_x: f32,
505 #[allow(dead_code)]
507 max_y: f32,
508 visual_lines: Vec<(usize, usize)>,
510}
511
512fn shape_text(
517 fs: &mut FontState,
518 text: &str,
519 raster_px: f32,
520 max_width_px: Option<f32>,
521 font_stack: &str,
522) -> std::rc::Rc<ShapedLine> {
523 shape_text_keyed(fs, text, TextKey::owned(text), raster_px, max_width_px, font_stack)
524}
525
526fn shape_text_keyed(
529 fs: &mut FontState,
530 text: &str,
531 text_key: TextKey,
532 raster_px: f32,
533 max_width_px: Option<f32>,
534 font_stack: &str,
535) -> std::rc::Rc<ShapedLine> {
536 let font_stack_hash = {
537 let mut h = DefaultHasher::new();
538 font_stack.hash(&mut h);
539 h.finish()
540 };
541 let key = (text_key, raster_px.to_bits(), max_width_px.map(|w| w.to_bits()), font_stack_hash);
542 if let Some(entry) = fs.line_cache.get_mut(&key) {
543 fs.line_clock += 1;
544 entry.last_used = fs.line_clock;
545 return std::rc::Rc::clone(&entry.line);
546 }
547
548 fs.shape_calls += 1;
549 let dpr = text_dpr();
550
551 let scale = 1.0f32;
554 let font_size_px = raster_px / dpr;
555
556 let wrap_opt = max_width_px.filter(|&w| w > 0.0);
558
559 let mut builder = fs.layout_cx.ranged_builder(&mut fs.font_cx, text, scale, true);
560 builder.push_default(parley::StyleProperty::FontSize(font_size_px));
561 builder.push_default(parley::StyleProperty::LineHeight(1.2));
562 builder.push_default(parley::StyleProperty::FontStack(parley::FontStack::Source(std::borrow::Cow::Borrowed(
564 font_stack,
565 ))));
566 builder.push_default(parley::StyleProperty::WordBreak(parley::swash::text::WordBreakStrength::KeepAll));
568 builder.push_default(parley::StyleProperty::OverflowWrap(parley::OverflowWrap::Anywhere));
569 let mut layout: parley::Layout<()> = builder.build(text);
570 layout.break_all_lines(wrap_opt);
571 layout.align(wrap_opt, parley::Alignment::Start, parley::AlignmentOptions::default());
572
573 let mut runs = Vec::new();
577 let mut max_x = 0.0f32;
578 let mut max_y = 0.0f32;
579 let mut visual_lines = Vec::new();
580
581 for line in layout.lines() {
582 let mut line_start = usize::MAX;
584 let mut line_end = 0usize;
585 for run in line.runs() {
586 let range = run.text_range();
587 line_start = line_start.min(range.start);
588 line_end = line_end.max(range.end);
589 }
590 visual_lines.push(if line_start == usize::MAX { (0, 0) } else { (line_start, line_end) });
591
592 let line_m = line.metrics();
593 let baseline_y = line_m.baseline * dpr; for item in line.items() {
596 let parley::PositionedLayoutItem::GlyphRun(gr) = item else {
597 continue;
598 };
599
600 let run_metrics = gr.run().metrics();
602 let ascent = run_metrics.ascent * dpr;
603 let descent = run_metrics.descent * dpr;
604 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();
615 let norm_coords: std::rc::Rc<[swash::NormalizedCoord]> = gr.run().normalized_coords().to_vec().into();
617 let run_font = gr.run().font().clone();
618 let mut pen_x = gr.offset();
619 let run_baseline = gr.baseline();
620 for cluster in gr.run().visual_clusters() {
621 let cluster_byte = cluster.text_range().start as u32;
622 for g in cluster.glyphs() {
623 let glyph_id = g.id; let size_bits = font_size_phys.to_bits(); let x_bin = 0; let y_bin = 0;
627 let raster_key =
628 GlyphKey::new(raster_font_id(font_blob_id, &norm_coords), glyph_id, size_bits, x_bin, y_bin, 0);
629 if !fs.raster_cache.contains_key(&raster_key) {
631 if let Some(rg) =
632 rasterize_one_glyph(&run_font, font_size_phys, glyph_id, &norm_coords, &mut fs.scale_cx)
633 {
634 insert_raster_glyph(fs, raster_key, rg);
635 }
636 }
637 let gx = pen_x + g.x;
638 run_glyphs.push(ShapedGlyph {
639 raster_key,
640 glyph_id,
641 x: gx * dpr, w: g.advance * dpr, y: (run_baseline + g.y) * dpr, ascent,
645 descent,
646 cluster: cluster_byte,
647 });
648 max_x = max_x.max((gx + g.advance) * dpr);
649 max_y = max_y.max(baseline_y + descent);
650 pen_x += g.advance;
651 }
652 }
653
654 if !run_glyphs.is_empty() {
655 runs.push(ShapedRun {
656 glyphs: run_glyphs,
657 baseline_y,
658 font: run_font,
659 norm_coords,
660 raster_size: font_size_phys,
661 });
662 }
663 }
664 }
665
666 if max_y == 0.0 {
668 max_y = raster_px * 1.2;
669 }
670
671 let line = std::rc::Rc::new(ShapedLine { runs, max_x, max_y, visual_lines });
672 if fs.line_cache.len() >= LINE_CACHE_LIMIT {
673 evict_line_cache_lru(fs);
674 }
675 fs.line_clock += 1;
676 let entry = LineCacheEntry { line: std::rc::Rc::clone(&line), last_used: fs.line_clock };
677 fs.line_cache.insert(key, entry);
678 line
679}
680
681#[derive(Clone)]
689pub struct AtlasSnapshot {
690 pub width: u32,
691 pub height: u32,
692 pub dirty: bool,
693 pub dirty_y: (u32, u32),
696 pub pixels: Option<Vec<u8>>,
698}
699
700pub fn atlas_snapshot() -> AtlasSnapshot {
702 with_font(|fs| {
703 let dirty = fs.atlas.is_dirty();
704 let (y0, y1) = if dirty {
705 let (a, b) = fs.atlas.dirty_rows.unwrap_or((0, fs.atlas.height));
706 (a.min(fs.atlas.height), b.min(fs.atlas.height))
707 } else {
708 (0, 0)
709 };
710 let pixels = if dirty {
711 let w = fs.atlas.width as usize;
712 Some(fs.atlas.pixels()[(y0 as usize * w)..(y1 as usize * w)].to_vec())
713 } else {
714 None
715 };
716 AtlasSnapshot { width: fs.atlas.width, height: fs.atlas.height, dirty, dirty_y: (y0, y1), pixels }
717 })
718}
719
720pub fn atlas_clear_dirty() {
722 with_font(|fs| {
723 fs.atlas.clear_dirty();
724 })
725}
726
727pub fn atlas_generation() -> u64 {
729 with_font(|fs| fs.atlas.generation)
730}
731
732#[derive(Clone, Copy, Debug, Default)]
734pub struct AtlasStats {
735 pub width: u32,
736 pub height: u32,
737 pub glyph_count: usize,
738 pub used_height: u32,
740 pub dirty: bool,
741}
742
743pub fn atlas_stats() -> AtlasStats {
744 with_font(|fs| {
745 let atlas = &fs.atlas;
746 AtlasStats {
747 width: atlas.width,
748 height: atlas.height,
749 glyph_count: atlas.entries.len(),
750 used_height: (atlas.next_y + atlas.row_height).min(atlas.height),
751 dirty: atlas.dirty,
752 }
753 })
754}
755
756pub fn with_atlas<R>(f: impl FnOnce(u32, u32, &[u8]) -> R) -> R {
761 with_font(|fs| {
762 let atlas = &fs.atlas;
763 f(atlas.width, atlas.height, &atlas.pixels)
764 })
765}
766
767pub struct TextRenderObject {
772 text: String,
773 size_px: f32,
774 color: Color,
775 max_width: Option<f32>,
777 max_width_explicit: bool,
780 size: Size,
782 element_id: Option<ElementId>,
783}
784
785impl TextRenderObject {
786 pub fn new(text: String, size_px: f32, color: Color) -> Self {
787 Self { text, size_px, color, max_width: None, max_width_explicit: false, size: Size::ZERO, element_id: None }
788 }
789
790 pub fn with_max_width(mut self, max_width: f32) -> Self {
791 self.max_width = Some(max_width);
792 self.max_width_explicit = true;
793 self
794 }
795
796 pub fn set_max_width(&mut self, max_width: Option<f32>) {
797 self.max_width = max_width;
798 self.max_width_explicit = max_width.is_some();
799 }
800
801 fn measure(&self) -> Size {
803 let dpr = text_dpr();
804 let raster_px = self.size_px * dpr;
805 let width = with_font(|fs| {
806 let line = shape_text(fs, &self.text, raster_px, self.max_width, DEFAULT_FONT_STACK);
807 let max_x = line.max_x / dpr;
808 if max_x == 0.0 && !self.text.is_empty() {
809 self.text.chars().count() as f32 * FALLBACK_ADVANCE_X
810 } else {
811 max_x
812 }
813 });
814 let height = text_visual_height(&self.text, self.size_px, self.max_width);
817 Size::new(width, height)
818 }
819}
820
821pub fn measure_text_width(text: &str, size_px: f32) -> f32 {
825 measure_text_width_styled(text, size_px, DEFAULT_FONT_STACK)
826}
827
828pub fn measure_text_width_styled(text: &str, size_px: f32, font_stack: &str) -> f32 {
830 if text.is_empty() {
831 return 0.0;
832 }
833 with_font(|fs| {
834 let dpr = text_dpr();
836 let raster_px = size_px * dpr;
837 let line = shape_text(fs, text, raster_px, None, font_stack);
838 let w = line.max_x / dpr;
839 if w == 0.0 {
840 text.chars().count() as f32 * FALLBACK_ADVANCE_X
841 } else {
842 w
843 }
844 })
845}
846
847pub fn text_visual_height(text: &str, size_px: f32, max_width_px: Option<f32>) -> f32 {
857 text_visual_height_styled(text, size_px, max_width_px, DEFAULT_FONT_STACK)
858}
859
860pub fn text_visual_height_styled(text: &str, size_px: f32, max_width_px: Option<f32>, font_stack: &str) -> f32 {
862 if text.is_empty() {
863 return size_px;
864 }
865 with_font(|fs| {
866 let dpr = text_dpr();
867 let raster_px = size_px * dpr;
868 let line = shape_text(fs, text, raster_px, max_width_px, font_stack);
869
870 if line.runs.is_empty() {
871 return size_px;
872 }
873
874 let first_run = &line.runs[0];
876 let first_ascent = first_run.glyphs.first().map(|g| g.ascent).unwrap_or(raster_px);
877 let first_baseline = first_run.baseline_y;
878 let visual_top = first_baseline - first_ascent;
879
880 let mut visual_bottom = 0.0f32;
882 for run in &line.runs {
883 for sg in &run.glyphs {
884 let bottom = run.baseline_y + sg.descent;
885 visual_bottom = visual_bottom.max(bottom);
886 }
887 }
888
889 if visual_bottom > visual_top {
890 (visual_bottom - visual_top) / dpr
891 } else {
892 size_px
893 }
894 })
895}
896
897pub fn paint_text_line(
903 text: &str,
904 size_px: f32,
905 color: Color,
906 offset: Point,
907 list: &mut PaintList,
908 max_width_px: Option<f32>,
909) -> f32 {
910 paint_text_line_impl(text, TextKey::owned(text), size_px, color, offset, list, max_width_px, DEFAULT_FONT_STACK)
911}
912
913#[allow(clippy::too_many_arguments)]
915pub fn paint_text_line_styled(
916 text: &str,
917 size_px: f32,
918 color: Color,
919 offset: Point,
920 list: &mut PaintList,
921 max_width_px: Option<f32>,
922 font_stack: &str,
923) -> f32 {
924 paint_text_line_impl(text, TextKey::owned(text), size_px, color, offset, list, max_width_px, font_stack)
925}
926
927#[allow(clippy::too_many_arguments)]
932pub fn paint_text_span(
933 text: &std::rc::Rc<str>,
934 range: Option<(usize, usize)>,
935 size_px: f32,
936 color: Color,
937 offset: Point,
938 list: &mut PaintList,
939 max_width_px: Option<f32>,
940) -> f32 {
941 let (start, end) = match range {
942 Some(r) => clamp_char_range(text, r),
943 None => (0, text.len()),
944 };
945 paint_text_line_impl(
946 &text[start..end],
947 TextKey::Shared(std::rc::Rc::clone(text), range),
948 size_px,
949 color,
950 offset,
951 list,
952 max_width_px,
953 DEFAULT_FONT_STACK,
954 )
955}
956
957pub fn text_ascent(text: &str, size_px: f32) -> f32 {
963 if text.is_empty() {
964 return size_px;
965 }
966 with_font(|fs| {
967 let dpr = text_dpr();
968 let shaped = shape_text(fs, text, size_px * dpr, None, DEFAULT_FONT_STACK);
969 first_glyph_ascent(&shaped).map(|a| a / dpr).unwrap_or(size_px)
970 })
971}
972
973pub fn text_span_ascent(text: &std::rc::Rc<str>, range: Option<(usize, usize)>, size_px: f32) -> f32 {
976 let (start, end) = match range {
977 Some(r) => clamp_char_range(text, r),
978 None => (0, text.len()),
979 };
980 if start >= end {
981 return size_px;
982 }
983 with_font(|fs| {
984 let dpr = text_dpr();
985 let shaped = shape_text_keyed(
986 fs,
987 &text[start..end],
988 TextKey::Shared(std::rc::Rc::clone(text), range),
989 size_px * dpr,
990 None,
991 DEFAULT_FONT_STACK,
992 );
993 first_glyph_ascent(&shaped).map(|a| a / dpr).unwrap_or(size_px)
994 })
995}
996
997fn first_glyph_ascent(shaped: &ShapedLine) -> Option<f32> {
998 shaped.runs.first().and_then(|r| r.glyphs.first()).map(|g| g.ascent)
999}
1000
1001fn clamp_char_range(text: &str, range: (usize, usize)) -> (usize, usize) {
1003 let mut start = range.0.min(text.len());
1004 let mut end = range.1.min(text.len());
1005 while !text.is_char_boundary(start) {
1006 start += 1;
1007 }
1008 while !text.is_char_boundary(end) {
1009 end -= 1;
1010 }
1011 if end < start {
1012 end = start;
1013 }
1014 (start, end)
1015}
1016
1017#[allow(clippy::too_many_arguments)]
1019fn paint_text_line_impl(
1020 text: &str,
1021 text_key: TextKey,
1022 size_px: f32,
1023 color: Color,
1024 offset: Point,
1025 list: &mut PaintList,
1026 max_width_px: Option<f32>,
1027 font_stack: &str,
1028) -> f32 {
1029 if text.is_empty() {
1030 return 0.0;
1031 }
1032 let width = with_font(|fs| {
1033 let dpr = text_dpr();
1034 let raster_px = size_px * dpr;
1035 let shaped = shape_text_keyed(fs, text, text_key, raster_px, max_width_px, font_stack);
1036
1037 let first_run = match shaped.runs.first() {
1041 Some(r) => r,
1042 None => return 0.0,
1043 };
1044 let first_ascent = first_run.glyphs.first().map(|g| g.ascent).unwrap_or(raster_px);
1045 let first_baseline = first_run.baseline_y;
1046 let anchor = first_baseline - first_ascent; let mut max_x = 0.0f32;
1049 for run in &shaped.runs {
1050 for sg in &run.glyphs {
1051 if !fs.raster_cache.contains_key(&sg.raster_key) {
1054 if let Some(rg) =
1055 rasterize_one_glyph(&run.font, run.raster_size, sg.glyph_id, &run.norm_coords, &mut fs.scale_cx)
1056 {
1057 insert_raster_glyph(fs, sg.raster_key, rg);
1058 }
1059 }
1060 let Some(r) = fs.raster_cache.get_mut(&sg.raster_key) else {
1064 continue;
1065 };
1066 if r.width == 0 || r.height == 0 {
1067 continue;
1068 }
1069 fs.glyph_clock += 1;
1070 r.last_used = fs.glyph_clock;
1071 let entry = fs.atlas.get_or_insert(sg.raster_key, &r.data, r.width, r.height);
1072
1073 let x = offset.x + (sg.x + r.left as f32) / dpr;
1075 let glyph_visual_top = run.baseline_y - r.top as f32;
1080 let y = offset.y + (glyph_visual_top - anchor) / dpr;
1081
1082 let rect = Rect::new(x, y, r.width as f32 / dpr, r.height as f32 / dpr);
1083 list.push(PaintCommand::TexturedRect {
1084 rect,
1085 color,
1086 uv: entry.uv,
1087 texture_id: 0,
1088 mode: mgui_core::paint::TextureMode::Mask,
1089 });
1090 max_x = max_x.max((sg.x + sg.w) / dpr);
1091 }
1092 }
1093 if max_x == 0.0 {
1094 max_x = text.chars().count() as f32 * FALLBACK_ADVANCE_X;
1095 }
1096 max_x
1097 });
1098 width
1099}
1100
1101pub fn wrapped_line_ranges(text: &str, size_px: f32, max_width: f32) -> Vec<(usize, usize)> {
1116 if text.is_empty() {
1117 return vec![(0, 0)];
1118 }
1119 if max_width <= 0.0 {
1120 return vec![(0, text.len())];
1121 }
1122 with_font(|fs| {
1123 let dpr = text_dpr();
1124 let raster_px = size_px * dpr;
1125 let shaped = shape_text(fs, text, raster_px, Some(max_width), DEFAULT_FONT_STACK);
1126 shaped.visual_lines.clone()
1127 })
1128}
1129
1130pub fn measure_char_prefix_widths(text: &str, size_px: f32, font_stack: &str) -> Vec<f32> {
1131 if text.is_empty() {
1132 return vec![0.0];
1133 }
1134 with_font(|fs| {
1135 let dpr = text_dpr();
1136 let raster_px = size_px * dpr;
1137 let shaped = shape_text(fs, text, raster_px, None, font_stack);
1138
1139 let char_count = text.chars().count();
1140 let mut widths = vec![0.0f32; char_count + 1];
1141
1142 let mut byte_x: Vec<(u32, f32)> = Vec::new();
1145 for run in &shaped.runs {
1146 for sg in &run.glyphs {
1147 match byte_x.last_mut() {
1148 Some((b, _)) if *b == sg.cluster => {}
1149 _ => byte_x.push((sg.cluster, sg.x)),
1150 }
1151 }
1152 }
1153
1154 let mut prev = 0.0f32;
1157 let mut bi = 0usize;
1158 for (ci, (byte_pos, _)) in text.char_indices().enumerate() {
1159 while bi < byte_x.len() && byte_x[bi].0 <= byte_pos as u32 {
1160 prev = byte_x[bi].1 / dpr;
1161 bi += 1;
1162 }
1163 widths[ci] = prev;
1164 }
1165 widths[char_count] = shaped.max_x / dpr;
1166 widths
1167 })
1168}
1169
1170fn rasterize_one_glyph(
1172 font: &parley::Font,
1173 font_size: f32,
1174 glyph_id: u16,
1175 norm_coords: &[swash::NormalizedCoord],
1176 scale_cx: &mut swash::scale::ScaleContext,
1177) -> Option<RasterGlyph> {
1178 let bytes = font.data.data();
1180 if bytes.is_empty() {
1181 return None;
1182 }
1183 let font_ref = swash::FontRef::from_index(bytes, font.index as usize)?;
1184 let mut scaler =
1185 scale_cx.builder(font_ref).size(font_size).normalized_coords(norm_coords.iter()).hint(true).build();
1186 let image = swash::scale::Render::new(&[
1187 swash::scale::Source::ColorOutline(0),
1188 swash::scale::Source::ColorBitmap(swash::scale::StrikeWith::BestFit),
1189 swash::scale::Source::Outline,
1190 ])
1191 .render(&mut scaler, glyph_id)?;
1192 if image.placement.width == 0 || image.placement.height == 0 {
1193 return Some(RasterGlyph { data: Vec::new(), width: 0, height: 0, left: 0, top: 0, last_used: 0 });
1198 }
1199 Some(RasterGlyph {
1200 data: image.data.to_vec(),
1201 width: image.placement.width,
1202 height: image.placement.height,
1203 left: image.placement.left,
1204 top: image.placement.top,
1205 last_used: 0,
1206 })
1207}
1208
1209impl RenderObject for TextRenderObject {
1210 fn layout(&mut self, _bc: BoxConstraints, _ctx: &mut LayoutContext) -> Size {
1211 let s = self.measure();
1222 self.size = s;
1223 s
1224 }
1225
1226 fn content_size(&self) -> Size {
1227 self.size
1228 }
1229
1230 fn paint(&self, offset: Point, list: &mut PaintList) {
1231 paint_text_line(&self.text, self.size_px, self.color, offset, list, self.max_width);
1232 }
1233
1234 fn set_element_id(&mut self, id: ElementId) {
1235 self.element_id = Some(id);
1236 }
1237
1238 fn hit_test(&self, position: Point, offset: Point) -> Option<ElementId> {
1239 let r = Rect::new(offset.x, offset.y, self.size.width, self.size.height);
1243 if r.contains(position) {
1244 self.element_id
1245 } else {
1246 None
1247 }
1248 }
1249}
1250
1251#[cfg(test)]
1256mod tests {
1257 use super::*;
1258
1259 fn mk_key(id: u32) -> GlyphKey {
1260 GlyphKey(id as u64)
1261 }
1262
1263 #[test]
1264 fn atlas_get_or_insert_dedupes() {
1265 let mut a = Atlas::new(64, 64);
1266 let k = mk_key(1);
1267 let e1 = a.get_or_insert(k, &[255; 8], 2, 4);
1268 let e2 = a.get_or_insert(k, &[0; 8], 2, 4);
1269 assert_eq!(e1.uv, e2.uv, "重复 key 必须返回同一 entry");
1270 assert_eq!(a.glyph_count(), 1);
1271 }
1272
1273 #[test]
1274 fn atlas_wraps_to_next_row() {
1275 let mut a = Atlas::new(20, 20);
1276 let k1 = mk_key(1);
1278 a.get_or_insert(k1, &[1; 64], 16, 4);
1279 let k2 = mk_key(2);
1281 let e2 = a.get_or_insert(k2, &[2; 64], 16, 4);
1282 assert!(e2.uv[1] > 0.0, "第二个 glyph 应该换行,uv.v0 > 0");
1283 }
1284
1285 #[test]
1286 fn atlas_dirty_flag_lifecycle() {
1287 let mut a = Atlas::new(64, 64);
1288 assert!(!a.is_dirty());
1290 a.get_or_insert(mk_key(1), &[255; 8], 2, 4);
1292 assert!(a.is_dirty(), "get_or_insert 后应该 dirty");
1293 a.clear_dirty();
1295 assert!(!a.is_dirty());
1296 a.get_or_insert(mk_key(1), &[0; 8], 2, 4);
1298 assert!(!a.is_dirty(), "重复 key 不应触发 dirty");
1299 a.get_or_insert(mk_key(2), &[0; 8], 2, 4);
1301 assert!(a.is_dirty());
1302 }
1303
1304 #[test]
1307 fn atlas_snapshot_uploads_only_dirty_rows() {
1308 let width = with_font(|fs| {
1310 fs.atlas = Atlas::new(ATLAS_SIZE, ATLAS_SIZE);
1311 fs.atlas.width
1312 });
1313 with_font(|fs| {
1314 fs.atlas.get_or_insert(GlyphKey::new(7, 7, 0, 0, 0, 0), &[9u8; 16], 4, 4);
1315 fs.atlas.get_or_insert(GlyphKey::new(7, 8, 0, 0, 0, 0), &[9u8; 16], 4, 4);
1316 assert_eq!(fs.atlas.dirty_rows, Some((1, 5)), "同一行的写入应合并为单行带");
1317 });
1318 let snap = atlas_snapshot();
1319 assert!(snap.dirty);
1320 assert_eq!(snap.dirty_y, (1, 5));
1321 assert_eq!(snap.pixels.as_ref().map(Vec::len), Some(width as usize * 4), "快照只拷贝 dirty 行");
1322 atlas_clear_dirty();
1323 let clean = atlas_snapshot();
1324 assert!(!clean.dirty);
1325 assert_eq!(clean.dirty_y, (0, 0));
1326 assert!(clean.pixels.is_none());
1327 }
1328
1329 #[test]
1331 fn atlas_auto_expands_when_full() {
1332 let mut a = Atlas::new(32, 32);
1333 let e_before = a.get_or_insert(mk_key(1), &[100; 9], 3, 3);
1335 let uv_scalar_before = e_before.uv[0]; let big: Vec<u8> = vec![200; 400]; for i in 2..10 {
1341 a.get_or_insert(mk_key(i), &big, 20, 20);
1342 }
1343 assert!(a.width >= 32, "atlas 应保持原尺寸或扩容");
1345 assert!(a.glyph_count() >= 8, "扩容后应能放下 8+ glyphs,实际 {}", a.glyph_count());
1346
1347 if a.width > 32 {
1349 let e_after = a.get_or_insert(mk_key(1), &[0; 9], 3, 3);
1351 let expected = uv_scalar_before / 2.0;
1354 assert!((e_after.uv[0] - expected).abs() < 0.01, "扩容后 uv.u0 应为 {expected}, 实际 {}", e_after.uv[0]);
1355 }
1356 }
1357
1358 #[test]
1360 fn atlas_accepts_new_glyphs_after_expansion() {
1361 let mut a = Atlas::new(16, 16);
1362 a.get_or_insert(mk_key(1), &[50; 144], 12, 12);
1364 let e2 = a.get_or_insert(mk_key(2), &[100; 144], 12, 12);
1366 assert!(a.width > 16 || a.height > 16, "应该扩容了");
1367 let e1 = a.get_or_insert(mk_key(1), &[0; 144], 12, 12);
1369 assert!(e2.uv[1] >= e1.uv[1], "第二个 glyph 应在第一个下方");
1370 }
1371
1372 #[test]
1373 fn text_measure_produces_nonzero_size() {
1374 let t = TextRenderObject::new("Hello".into(), 24.0, Color::WHITE);
1375 let s = t.measure();
1376 assert!(s.width > 0.0, "width should be > 0 for 'Hello'");
1377 assert!(s.height > 0.0, "height should be > 0");
1378 }
1379
1380 #[test]
1381 fn text_paint_emits_textured_rects() {
1382 let t = TextRenderObject::new("Hi".into(), 24.0, Color::WHITE);
1383 let mut list = PaintList::new();
1384 t.paint(Point::new(0.0, 0.0), &mut list);
1385 assert!(!list.is_empty(), "paint should emit at least 1 textured rect");
1387 for cmd in &list.commands {
1388 match cmd {
1389 PaintCommand::TexturedRect { texture_id, uv, .. } => {
1390 assert_eq!(*texture_id, 0);
1391 assert!(uv[0] < uv[2]);
1392 assert!(uv[1] < uv[3]);
1393 }
1394 _ => panic!("expected TexturedRect, got Rect"),
1395 }
1396 }
1397 }
1398
1399 #[test]
1400 fn text_paint_with_offset_shifts_rects() {
1401 let t = TextRenderObject::new("X".into(), 24.0, Color::WHITE);
1402 let mut list = PaintList::new();
1403 t.paint(Point::new(100.0, 50.0), &mut list);
1404 for cmd in &list.commands {
1406 if let PaintCommand::TexturedRect { rect, .. } = cmd {
1407 assert!(rect.x >= 100.0 - 1.0, "x={}", rect.x);
1408 assert!(rect.y >= 50.0 - 1.0, "y={}", rect.y);
1409 }
1410 }
1411 }
1412
1413 #[test]
1415 fn shape_line_cache_hits_second_paint() {
1416 let mut list1 = PaintList::new();
1417 paint_text_line("cache-hit-test", 20.0, Color::WHITE, Point::ZERO, &mut list1, None);
1418 let calls_1 = with_font(|fs| fs.shape_calls);
1419
1420 let mut list2 = PaintList::new();
1421 paint_text_line("cache-hit-test", 20.0, Color::WHITE, Point::new(5.0, 5.0), &mut list2, None);
1422 let calls_2 = with_font(|fs| fs.shape_calls);
1423
1424 assert_eq!(calls_1, calls_2, "第二次 paint 应命中缓存,不再 shape");
1425 assert_eq!(list1.commands.len(), list2.commands.len(), "缓存命中的绘制输出数量应一致");
1426 }
1427
1428 #[test]
1430 fn shape_line_cache_evicts_lru_at_limit() {
1431 let fake_line =
1432 || std::rc::Rc::new(ShapedLine { runs: Vec::new(), max_x: 0.0, max_y: 0.0, visual_lines: Vec::new() });
1433 let hot_key = (TextKey::Owned("hot-entry".to_string()), 0, None, 0);
1434 let oldest_key = (TextKey::Owned("fake-entry-0".to_string()), 0, None, 0);
1435 with_font(|fs| {
1436 fs.line_cache.clear();
1437 fs.line_clock = 0;
1438 fs.line_clock += 1;
1439 fs.line_cache.insert(hot_key.clone(), LineCacheEntry { line: fake_line(), last_used: fs.line_clock });
1440 for i in 0..LINE_CACHE_LIMIT - 1 {
1441 fs.line_clock += 1;
1442 fs.line_cache.insert(
1443 (TextKey::Owned(format!("fake-entry-{i}")), 0, None, 0),
1444 LineCacheEntry { line: fake_line(), last_used: fs.line_clock },
1445 );
1446 }
1447 fs.line_clock += 1;
1449 fs.line_cache.get_mut(&hot_key).expect("hot entry").last_used = fs.line_clock;
1450 });
1451 let mut list = PaintList::new();
1453 paint_text_line("trigger-evict", 14.0, Color::WHITE, Point::ZERO, &mut list, None);
1454 with_font(|fs| {
1455 assert!(fs.line_cache.len() <= LINE_CACHE_LIMIT, "超限后应回收到上限内");
1456 assert!(fs.line_cache.len() >= LINE_CACHE_TARGET, "LRU 只应淘汰最旧 1/4");
1457 assert!(fs.line_cache.contains_key(&hot_key), "刚访问过的热条目不应被淘汰");
1458 assert!(!fs.line_cache.contains_key(&oldest_key), "最久未访问的条目应被淘汰");
1459 fs.line_cache.clear();
1460 });
1461 }
1462
1463 #[test]
1465 fn paint_rebuilds_evicted_raster_glyphs() {
1466 let mut first = PaintList::new();
1467 paint_text_line("raster-rebuild-test", 18.0, Color::WHITE, Point::ZERO, &mut first, None);
1468 assert!(!first.commands.is_empty());
1469
1470 with_font(|fs| {
1471 fs.raster_cache.clear();
1472 fs.raster_cache_bytes = 0;
1473 });
1474
1475 let mut second = PaintList::new();
1476 paint_text_line("raster-rebuild-test", 18.0, Color::WHITE, Point::ZERO, &mut second, None);
1477 assert_eq!(first.commands.len(), second.commands.len(), "位图淘汰后应重建 glyph,而不是丢字");
1478 assert!(!second.commands.is_empty());
1479 }
1480
1481 #[test]
1485 fn zero_size_glyphs_are_cached_not_rerasterized() {
1486 with_font(|fs| {
1487 fs.raster_cache.clear();
1488 fs.raster_cache_bytes = 0;
1489 let _ = shape_text(fs, "a b c", 13.0, None, DEFAULT_FONT_STACK);
1490 let cached = fs.raster_cache.len();
1491 assert!(
1492 fs.raster_cache.values().any(|g| g.width == 0 && g.height == 0),
1493 "空格等零尺寸 glyph 必须缓存占位,不能每次重栅格化"
1494 );
1495 let _ = shape_text(fs, "a b c d", 13.0, None, DEFAULT_FONT_STACK);
1498 assert_eq!(fs.raster_cache.len(), cached + 1, "除新字符外不得新增栅格化条目");
1499 fs.raster_cache.clear();
1500 fs.raster_cache_bytes = 0;
1501 });
1502 }
1503
1504 #[test]
1506 fn raster_cache_trims_to_budget() {
1507 with_font(|fs| {
1508 fs.raster_cache.clear();
1509 fs.raster_cache_bytes = 0;
1510 let chunk = vec![0u8; 8 * 1024 * 1024];
1511 for i in 0..5u16 {
1512 insert_raster_glyph(
1513 fs,
1514 GlyphKey::new(0, i, 0, 0, 0, 0),
1515 RasterGlyph { data: chunk.clone(), width: 2048, height: 1024, left: 0, top: 0, last_used: 0 },
1516 );
1517 }
1518 assert!(fs.raster_cache_bytes <= RASTER_CACHE_TARGET_BYTES, "应回收到目标水位");
1520 assert_eq!(fs.raster_cache.len(), 3, "LRU 应保留最近的条目");
1521 assert!(!fs.raster_cache.contains_key(&GlyphKey::new(0, 0, 0, 0, 0, 0)), "最旧条目应被淘汰");
1522 assert!(fs.raster_cache.contains_key(&GlyphKey::new(0, 4, 0, 0, 0, 0)), "最新条目应保留");
1523 fs.raster_cache.clear();
1524 fs.raster_cache_bytes = 0;
1525 });
1526 }
1527
1528 #[test]
1531 fn paint_text_line_dpr_rasterizes_at_physical_resolution() {
1532 fn paint_once(dpr: f32) -> (f32, f32, f32) {
1533 set_text_dpr(dpr);
1534 let mut list = PaintList::new();
1535 let width = paint_text_line("H", 24.0, Color::WHITE, Point::ZERO, &mut list, None);
1536 let (rect_w, uv_span) = match &list.commands[0] {
1537 PaintCommand::TexturedRect { rect, uv, .. } => (rect.width, (uv[2] - uv[0]) * ATLAS_SIZE as f32),
1538 _ => panic!("expected TexturedRect"),
1539 };
1540 set_text_dpr(1.0); (rect_w, uv_span, width)
1542 }
1543
1544 let (w1, span1, ret1) = paint_once(1.0);
1545 let (w2, span2, ret2) = paint_once(2.0);
1546
1547 assert!((w1 - w2).abs() <= 2.0, "rect 逻辑尺寸应 dpr 无关(允许取整 ≤2px): dpr1={w1} vs dpr2={w2}");
1549 assert!((ret1 - ret2).abs() < 0.5 && ret1 > 0.0, "返回宽度(逻辑)应 dpr 无关: {ret1} vs {ret2}");
1550 assert!(span2 > span1 * 1.5, "atlas 位图分辨率应随 dpr 变大: dpr1={span1}px vs dpr2={span2}px");
1551 let mw = measure_text_width("H", 24.0);
1552 assert!((ret1 - mw).abs() < 0.5, "paint 宽度应与 measure 一致(TextField 光标定位依赖): {ret1} vs {mw}");
1553 }
1554}
1555
1556pub fn is_rtl_text(text: &str) -> bool {
1562 for ch in text.chars() {
1563 let code = ch as u32;
1564 let rtl = matches!(
1565 code,
1566 0x0590..=0x05FF | 0x0600..=0x06FF | 0x0700..=0x074F | 0x0750..=0x077F | 0x0780..=0x07BF | 0x0860..=0x086F | 0x08A0..=0x08FF | 0xFB1D..=0xFB4F | 0xFB50..=0xFDFF | 0xFE70..=0xFEFF );
1577 if rtl {
1578 return true;
1579 }
1580 if ch.is_alphabetic() {
1581 return false;
1582 }
1583 }
1584 false
1585}
1586
1587pub fn mirror_carets_for_rtl(widths: &[f32]) -> Vec<f32> {
1593 let chars = widths.len().saturating_sub(1);
1594 if chars == 0 {
1595 return widths.to_vec();
1596 }
1597 let mut carets = vec![0.0f32; chars + 1];
1598 carets[0] = widths[chars];
1599 carets[1..=chars].copy_from_slice(&widths[..chars]);
1600 carets
1601}
1602
1603pub fn measure_caret_positions(text: &str, size_px: f32, font_stack: &str) -> Vec<f32> {
1605 let widths = measure_char_prefix_widths(text, size_px, font_stack);
1606 if is_rtl_text(text) {
1607 mirror_carets_for_rtl(&widths)
1608 } else {
1609 widths
1610 }
1611}
1612
1613pub fn nearest_caret_index(carets: &[f32], x: f32) -> usize {
1615 carets
1616 .iter()
1617 .enumerate()
1618 .min_by(|(ia, a), (ib, b)| (**a - x).abs().total_cmp(&(**b - x).abs()).then_with(|| ia.cmp(ib)))
1619 .map(|(index, _)| index)
1620 .unwrap_or(0)
1621}
1622
1623#[cfg(test)]
1624mod rtl_tests {
1625 use super::*;
1626
1627 #[test]
1628 fn detects_base_direction() {
1629 assert!(is_rtl_text("مرحبا بالعالم"));
1630 assert!(is_rtl_text("שלום"));
1631 assert!(!is_rtl_text("hello مرحبا")); assert!(!is_rtl_text("123 !?"));
1633 assert!(is_rtl_text("123 مرحبا")); }
1635
1636 #[test]
1637 fn rtl_caret_mirroring_and_nearest_index() {
1638 let widths = [0.0, 10.0, 25.0, 40.0];
1640 let carets = mirror_carets_for_rtl(&widths);
1641 assert_eq!(carets, vec![40.0, 0.0, 10.0, 25.0]);
1642 assert_eq!(nearest_caret_index(&carets, 38.0), 0, "靠近右缘 → 文本起点");
1643 assert_eq!(nearest_caret_index(&carets, 2.0), 1);
1644 assert_eq!(nearest_caret_index(&carets, 24.0), 3, "靠近左缘 → 文本末尾");
1645 assert_eq!(mirror_carets_for_rtl(&[0.0]), vec![0.0]);
1647 assert_eq!(nearest_caret_index(&widths, 12.0), 1);
1648 }
1649}
1650
1651#[derive(Clone, Debug, PartialEq)]
1658pub struct RichTextSpan {
1659 pub text: String,
1660 pub size_px: f32,
1661 pub color: Option<Color>,
1663 pub font_stack: Option<String>,
1665 pub weight: Option<u16>,
1671 pub italic: bool,
1673}
1674
1675impl RichTextSpan {
1676 pub fn new(text: impl Into<String>) -> Self {
1677 Self { text: text.into(), size_px: 15.0, color: None, font_stack: None, weight: None, italic: false }
1678 }
1679
1680 pub fn with_size(mut self, size_px: f32) -> Self {
1681 self.size_px = size_px;
1682 self
1683 }
1684
1685 pub fn with_color(mut self, color: Color) -> Self {
1686 self.color = Some(color);
1687 self
1688 }
1689
1690 pub fn with_font_stack(mut self, stack: impl Into<String>) -> Self {
1691 self.font_stack = Some(stack.into());
1692 self
1693 }
1694
1695 pub fn with_weight(mut self, weight: u16) -> Self {
1697 self.weight = Some(weight.clamp(1, 1000));
1698 self
1699 }
1700
1701 pub fn bold(self) -> Self {
1703 self.with_weight(700)
1704 }
1705
1706 pub fn with_italic(mut self, italic: bool) -> Self {
1707 self.italic = italic;
1708 self
1709 }
1710
1711 pub fn italic(self) -> Self {
1713 self.with_italic(true)
1714 }
1715}
1716
1717pub type InlinePainter = std::rc::Rc<dyn Fn(&mut PaintList, Rect)>;
1719
1720#[derive(Clone)]
1722pub struct InlineItem {
1723 pub width: f32,
1724 pub height: f32,
1725 pub painter: InlinePainter,
1726}
1727
1728impl InlineItem {
1729 pub fn new(width: f32, height: f32, painter: impl Fn(&mut PaintList, Rect) + 'static) -> Self {
1730 Self { width, height, painter: std::rc::Rc::new(painter) }
1731 }
1732}
1733
1734impl std::fmt::Debug for InlineItem {
1735 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1736 f.debug_struct("InlineItem").field("width", &self.width).field("height", &self.height).finish()
1737 }
1738}
1739
1740impl PartialEq for InlineItem {
1741 fn eq(&self, other: &Self) -> bool {
1742 self.width == other.width && self.height == other.height && std::rc::Rc::ptr_eq(&self.painter, &other.painter)
1743 }
1744}
1745
1746#[derive(Clone, Debug, PartialEq)]
1748pub enum RichItem {
1749 Text(RichTextSpan),
1750 Inline(InlineItem),
1751}
1752
1753#[derive(Clone, Debug, PartialEq)]
1755pub struct RichText {
1756 text: std::rc::Rc<str>,
1757 spans: Vec<RichTextSpan>,
1758 ranges: Vec<(usize, usize)>,
1759 inlines: Vec<(usize, InlineItem)>,
1761}
1762
1763impl RichText {
1764 pub fn new(spans: Vec<RichTextSpan>) -> Self {
1765 Self::from_items(spans.into_iter().map(RichItem::Text).collect())
1766 }
1767
1768 pub fn from_items(items: Vec<RichItem>) -> Self {
1769 let mut text = String::new();
1770 let mut spans = Vec::new();
1771 let mut ranges = Vec::new();
1772 let mut inlines = Vec::new();
1773 for item in items {
1774 match item {
1775 RichItem::Text(span) => {
1776 let start = text.len();
1777 text.push_str(&span.text);
1778 spans.push(span);
1779 ranges.push((start, text.len()));
1780 }
1781 RichItem::Inline(inline) => inlines.push((text.len(), inline)),
1782 }
1783 }
1784 Self { text: text.into(), spans, ranges, inlines }
1785 }
1786
1787 pub fn plain_text(&self) -> &str {
1789 &self.text
1790 }
1791
1792 pub fn spans(&self) -> &[RichTextSpan] {
1793 &self.spans
1794 }
1795
1796 pub fn is_empty(&self) -> bool {
1797 self.text.is_empty() && self.inlines.is_empty()
1798 }
1799}
1800
1801struct RichShapedGlyph {
1802 raster_key: GlyphKey,
1803 glyph_id: u16,
1804 x: f32,
1805 span: u16,
1807}
1808
1809struct RichShapedRun {
1810 glyphs: Vec<RichShapedGlyph>,
1811 baseline_y: f32,
1812 ascent: f32,
1814 font: parley::Font,
1815 norm_coords: std::rc::Rc<[swash::NormalizedCoord]>,
1816 raster_size: f32,
1817}
1818
1819struct RichInlineBox {
1821 id: u16,
1823 x: f32,
1824 y: f32,
1825 width: f32,
1826 height: f32,
1827 line_baseline: f32,
1829}
1830
1831struct RichShapedLine {
1832 runs: Vec<RichShapedRun>,
1833 inline_boxes: Vec<RichInlineBox>,
1834 max_x: f32,
1835 max_y: f32,
1836}
1837
1838#[derive(Clone, PartialEq, Eq, Hash)]
1839struct RichCacheKey {
1840 text: std::rc::Rc<str>,
1841 styles: Vec<(usize, usize, u32, u64)>,
1843 inlines: Vec<(usize, u32, u32)>,
1845 width_bits: Option<u32>,
1846 dpr_bits: u32,
1847}
1848
1849struct RichCacheEntry {
1850 line: std::rc::Rc<RichShapedLine>,
1851 last_used: u64,
1852}
1853
1854fn rich_style_signature(rich: &RichText) -> Vec<(usize, usize, u32, u64)> {
1855 rich.ranges
1856 .iter()
1857 .zip(&rich.spans)
1858 .map(|((start, end), span)| {
1859 let stack = span.font_stack.as_deref().unwrap_or(DEFAULT_FONT_STACK);
1860 let mut h = DefaultHasher::new();
1861 stack.hash(&mut h);
1862 span.weight.unwrap_or(400).hash(&mut h);
1865 span.italic.hash(&mut h);
1866 (*start, *end, span.size_px.max(1.0).to_bits(), h.finish())
1867 })
1868 .collect()
1869}
1870
1871fn span_index_at(ranges: &[(usize, usize)], byte: usize) -> u16 {
1872 ranges.iter().position(|(start, end)| byte >= *start && byte < *end).unwrap_or(0) as u16
1873}
1874
1875fn shape_rich(fs: &mut FontState, rich: &RichText, max_width_px: Option<f32>) -> std::rc::Rc<RichShapedLine> {
1877 let dpr = text_dpr();
1878 let key = RichCacheKey {
1879 text: std::rc::Rc::clone(&rich.text),
1880 styles: rich_style_signature(rich),
1881 inlines: rich
1882 .inlines
1883 .iter()
1884 .map(|(index, inline)| (*index, inline.width.to_bits(), inline.height.to_bits()))
1885 .collect(),
1886 width_bits: max_width_px.map(|w| w.to_bits()),
1887 dpr_bits: dpr.to_bits(),
1888 };
1889 if let Some(entry) = fs.rich_cache.get_mut(&key) {
1890 fs.rich_clock += 1;
1891 entry.last_used = fs.rich_clock;
1892 return std::rc::Rc::clone(&entry.line);
1893 }
1894
1895 let text: &str = &rich.text;
1896 let mut builder = fs.layout_cx.ranged_builder(&mut fs.font_cx, text, 1.0, true);
1897 builder.push_default(parley::StyleProperty::FontSize(15.0));
1898 builder.push_default(parley::StyleProperty::LineHeight(1.2));
1899 builder.push_default(parley::StyleProperty::FontStack(parley::FontStack::Source(std::borrow::Cow::Borrowed(
1900 DEFAULT_FONT_STACK,
1901 ))));
1902 builder.push_default(parley::StyleProperty::WordBreak(parley::swash::text::WordBreakStrength::KeepAll));
1903 builder.push_default(parley::StyleProperty::OverflowWrap(parley::OverflowWrap::Anywhere));
1904 for ((start, end), span) in rich.ranges.iter().zip(&rich.spans) {
1905 if span.size_px > 0.0 {
1906 builder.push(parley::StyleProperty::FontSize(span.size_px), *start..*end);
1907 }
1908 if let Some(stack) = &span.font_stack {
1909 builder.push(
1910 parley::StyleProperty::FontStack(parley::FontStack::Source(std::borrow::Cow::Borrowed(stack))),
1911 *start..*end,
1912 );
1913 }
1914 if let Some(weight) = span.weight {
1916 builder.push(parley::StyleProperty::FontWeight(parley::FontWeight::new(weight as f32)), *start..*end);
1917 }
1918 if span.italic {
1919 builder.push(parley::StyleProperty::FontStyle(parley::FontStyle::Italic), *start..*end);
1920 }
1921 }
1922 for (id, (index, inline)) in rich.inlines.iter().enumerate() {
1923 builder.push_inline_box(parley::InlineBox {
1924 id: id as u64,
1925 index: *index,
1926 width: inline.width,
1927 height: inline.height,
1928 });
1929 }
1930 let mut layout: parley::Layout<()> = builder.build(text);
1931 let wrap_opt = max_width_px.filter(|w| *w > 0.0);
1932 layout.break_all_lines(wrap_opt);
1933 layout.align(wrap_opt, parley::Alignment::Start, parley::AlignmentOptions::default());
1934
1935 let mut runs = Vec::new();
1936 let mut inline_boxes = Vec::new();
1937 let mut max_x = 0.0f32;
1938 let mut max_y = 0.0f32;
1939 for line in layout.lines() {
1940 let line_m = line.metrics();
1941 let baseline_y = line_m.baseline * dpr;
1942 for item in line.items() {
1943 let parley::PositionedLayoutItem::GlyphRun(gr) = item else {
1944 if let parley::PositionedLayoutItem::InlineBox(b) = item {
1945 inline_boxes.push(RichInlineBox {
1946 id: b.id as u16,
1947 x: b.x,
1948 y: b.y,
1949 width: b.width,
1950 height: b.height,
1951 line_baseline: baseline_y,
1952 });
1953 max_x = max_x.max((b.x + b.width) * dpr);
1954 max_y = max_y.max((b.y + b.height) * dpr);
1955 }
1956 continue;
1957 };
1958 let run_metrics = gr.run().metrics();
1959 let ascent = run_metrics.ascent * dpr;
1960 let descent = run_metrics.descent * dpr;
1961 let font_size_phys = gr.run().font_size() * dpr;
1962 let font_blob_id = gr.run().font().data.id() as usize;
1963 let norm_coords: std::rc::Rc<[swash::NormalizedCoord]> = gr.run().normalized_coords().to_vec().into();
1964 let run_font = gr.run().font().clone();
1965 let mut pen_x = gr.offset();
1966 let mut run_glyphs = Vec::new();
1967 for cluster in gr.run().visual_clusters() {
1968 let cluster_byte = cluster.text_range().start;
1969 let span = span_index_at(&rich.ranges, cluster_byte);
1970 for g in cluster.glyphs() {
1971 let raster_key = GlyphKey::new(
1972 raster_font_id(font_blob_id, &norm_coords),
1973 g.id,
1974 font_size_phys.to_bits(),
1975 0,
1976 0,
1977 0,
1978 );
1979 if !fs.raster_cache.contains_key(&raster_key) {
1980 if let Some(rg) =
1981 rasterize_one_glyph(&run_font, font_size_phys, g.id, &norm_coords, &mut fs.scale_cx)
1982 {
1983 insert_raster_glyph(fs, raster_key, rg);
1984 }
1985 }
1986 let gx = pen_x + g.x;
1987 run_glyphs.push(RichShapedGlyph { raster_key, glyph_id: g.id, x: gx * dpr, span });
1988 max_x = max_x.max((gx + g.advance) * dpr);
1989 max_y = max_y.max(baseline_y + descent);
1990 pen_x += g.advance;
1991 }
1992 }
1993 if !run_glyphs.is_empty() {
1994 runs.push(RichShapedRun {
1995 glyphs: run_glyphs,
1996 baseline_y,
1997 ascent,
1998 font: run_font,
1999 norm_coords,
2000 raster_size: font_size_phys,
2001 });
2002 }
2003 }
2004 }
2005 if max_y == 0.0 {
2006 max_y = rich.spans.iter().map(|s| s.size_px).fold(15.0, f32::max) * 1.2 * dpr;
2007 }
2008
2009 let line = std::rc::Rc::new(RichShapedLine { runs, inline_boxes, max_x, max_y });
2010 if fs.rich_cache.len() >= LINE_CACHE_LIMIT {
2011 fs.rich_cache.clear();
2012 }
2013 fs.rich_clock += 1;
2014 fs.rich_cache.insert(key, RichCacheEntry { line: std::rc::Rc::clone(&line), last_used: fs.rich_clock });
2015 line
2016}
2017
2018pub fn rich_text_size(rich: &RichText, max_width: Option<f32>) -> Size {
2020 if rich.is_empty() {
2021 return Size::ZERO;
2022 }
2023 with_font(|fs| {
2024 let dpr = text_dpr();
2025 let shaped = shape_rich(fs, rich, max_width);
2026 let first_baseline = shaped.runs.first().map(|r| r.baseline_y);
2027 let (anchor, fallback_h) = match first_baseline {
2028 Some(baseline) => {
2029 let first_ascent =
2031 shaped.runs.iter().filter(|r| r.baseline_y == baseline).map(|r| r.ascent).fold(0.0f32, f32::max);
2032 let inline_top = shaped
2033 .inline_boxes
2034 .iter()
2035 .filter(|b| b.line_baseline == baseline)
2036 .map(|b| b.y * dpr)
2037 .fold(f32::INFINITY, f32::min);
2038 ((baseline - first_ascent).min(inline_top), 0.0)
2040 }
2041 None => (0.0, shaped.max_y),
2042 };
2043 let height = if shaped.max_y > anchor { (shaped.max_y - anchor) / dpr } else { fallback_h / dpr };
2044 Size::new(shaped.max_x / dpr, height)
2045 })
2046}
2047
2048#[derive(Clone, Debug, PartialEq)]
2050pub struct RichTextLayout {
2051 pub size: Size,
2052 pub inline_rects: Vec<Rect>,
2053}
2054
2055pub fn rich_text_layout(rich: &RichText, max_width: Option<f32>) -> RichTextLayout {
2057 if rich.is_empty() {
2058 return RichTextLayout { size: Size::ZERO, inline_rects: Vec::new() };
2059 }
2060 with_font(|fs| {
2061 let dpr = text_dpr();
2062 let shaped = shape_rich(fs, rich, max_width);
2063 let first_baseline = shaped.runs.first().map(|r| r.baseline_y);
2064 let anchor = match first_baseline {
2065 Some(baseline) => {
2066 let first_ascent =
2067 shaped.runs.iter().filter(|r| r.baseline_y == baseline).map(|r| r.ascent).fold(0.0f32, f32::max);
2068 let inline_top = shaped
2069 .inline_boxes
2070 .iter()
2071 .filter(|b| b.line_baseline == baseline)
2072 .map(|b| b.y * dpr)
2073 .fold(f32::INFINITY, f32::min);
2074 (baseline - first_ascent).min(inline_top)
2075 }
2076 None => 0.0,
2077 };
2078 let height = if shaped.max_y > anchor { (shaped.max_y - anchor) / dpr } else { 0.0 };
2079 let mut inline_rects = vec![Rect::new(0.0, 0.0, 0.0, 0.0); rich.inlines.len()];
2080 for b in &shaped.inline_boxes {
2081 if let Some(slot) = inline_rects.get_mut(b.id as usize) {
2082 *slot = Rect::new(b.x, (b.y * dpr - anchor) / dpr, b.width, b.height);
2083 }
2084 }
2085 RichTextLayout { size: Size::new(shaped.max_x / dpr, height), inline_rects }
2086 })
2087}
2088
2089pub fn paint_rich_text(rich: &RichText, offset: Point, list: &mut PaintList, max_width: Option<f32>) -> f32 {
2091 paint_rich_text_with_default(rich, Color::WHITE, offset, list, max_width)
2092}
2093
2094pub fn paint_rich_text_with_default(
2096 rich: &RichText,
2097 default_color: Color,
2098 offset: Point,
2099 list: &mut PaintList,
2100 max_width: Option<f32>,
2101) -> f32 {
2102 if rich.is_empty() {
2103 return 0.0;
2104 }
2105 with_font(|fs| {
2106 let dpr = text_dpr();
2107 let shaped = shape_rich(fs, rich, max_width);
2108 let Some(first_run) = shaped.runs.first() else {
2109 return 0.0;
2110 };
2111 let first_baseline = first_run.baseline_y;
2112 let first_ascent =
2113 shaped.runs.iter().filter(|r| r.baseline_y == first_baseline).map(|r| r.ascent).fold(0.0f32, f32::max);
2114 let inline_top = shaped
2115 .inline_boxes
2116 .iter()
2117 .filter(|b| b.line_baseline == first_baseline)
2118 .map(|b| b.y * dpr)
2119 .fold(f32::INFINITY, f32::min);
2120 let anchor = (first_baseline - first_ascent).min(inline_top);
2121
2122 for run in &shaped.runs {
2123 for sg in &run.glyphs {
2124 if !fs.raster_cache.contains_key(&sg.raster_key) {
2125 if let Some(rg) =
2126 rasterize_one_glyph(&run.font, run.raster_size, sg.glyph_id, &run.norm_coords, &mut fs.scale_cx)
2127 {
2128 insert_raster_glyph(fs, sg.raster_key, rg);
2129 }
2130 }
2131 let Some(r) = fs.raster_cache.get_mut(&sg.raster_key) else {
2132 continue;
2133 };
2134 if r.width == 0 || r.height == 0 {
2135 continue;
2136 }
2137 fs.glyph_clock += 1;
2138 r.last_used = fs.glyph_clock;
2139 let entry = fs.atlas.get_or_insert(sg.raster_key, &r.data, r.width, r.height);
2140
2141 let x = offset.x + (sg.x + r.left as f32) / dpr;
2142 let glyph_visual_top = run.baseline_y - r.top as f32;
2143 let y = offset.y + (glyph_visual_top - anchor) / dpr;
2144 let rect = Rect::new(x, y, r.width as f32 / dpr, r.height as f32 / dpr);
2145 let color = rich.spans.get(sg.span as usize).and_then(|s| s.color).unwrap_or(default_color);
2146 list.push(PaintCommand::TexturedRect {
2147 rect,
2148 color,
2149 uv: entry.uv,
2150 texture_id: 0,
2151 mode: mgui_core::paint::TextureMode::Mask,
2152 });
2153 }
2154 }
2155 for b in &shaped.inline_boxes {
2156 if let Some((_, inline)) = rich.inlines.get(b.id as usize) {
2157 let rect = Rect::new(offset.x + b.x, offset.y + b.y - anchor / dpr, b.width, b.height);
2158 (inline.painter)(list, rect);
2159 }
2160 }
2161 shaped.max_x / dpr
2162 })
2163}
2164
2165#[cfg(test)]
2166mod rich_text_tests {
2167 use super::*;
2168
2169 #[test]
2170 fn mixed_styles_measure_and_paint_with_span_colors() {
2171 set_text_dpr(1.0);
2172 let red = Color::from_rgb8(255, 0, 0);
2173 let rich = RichText::new(vec![
2174 RichTextSpan::new("Hello ").with_size(18.0).with_color(Color::WHITE),
2175 RichTextSpan::new("World").with_size(30.0).with_color(red),
2176 ]);
2177 let size = rich_text_size(&rich, None);
2178 assert!(size.width > 0.0, "宽度必须 > 0");
2179 assert!(size.height >= 30.0, "高度应容纳 30px 字号: {size:?}");
2180
2181 let mut list = PaintList::new();
2182 let width = paint_rich_text(&rich, Point::ZERO, &mut list, None);
2183 assert!((width - size.width).abs() < 0.5, "绘制宽度应与测量一致: {width} vs {}", size.width);
2184 let colors: Vec<Color> = list
2185 .commands
2186 .iter()
2187 .filter_map(|c| match c {
2188 PaintCommand::TexturedRect { color, .. } => Some(*color),
2189 _ => None,
2190 })
2191 .collect();
2192 assert!(colors.contains(&Color::WHITE), "应包含第一段白色字形");
2193 assert!(colors.contains(&red), "应包含第二段红色字形");
2194 }
2195
2196 #[test]
2197 fn inline_item_measures_paints_and_sits_on_baseline() {
2198 use std::cell::RefCell;
2199 set_text_dpr(1.0);
2200 let captured: std::rc::Rc<RefCell<Option<Rect>>> = std::rc::Rc::new(RefCell::new(None));
2201 let cap = captured.clone();
2202 let rich = RichText::from_items(vec![
2203 RichItem::Text(RichTextSpan::new("A").with_size(16.0)),
2204 RichItem::Inline(InlineItem::new(30.0, 24.0, move |_list, rect| *cap.borrow_mut() = Some(rect))),
2205 RichItem::Text(RichTextSpan::new("B").with_size(16.0)),
2206 ]);
2207 let size = rich_text_size(&rich, None);
2208 assert!(size.width >= 30.0, "宽度应包含内联项: {size:?}");
2209 assert!(size.height >= 20.0, "高度应容纳内联项: {size:?}");
2210
2211 let mut list = PaintList::new();
2212 let width = paint_rich_text(&rich, Point::new(10.0, 5.0), &mut list, None);
2213 assert!(width >= 30.0);
2214 let rect = captured.borrow().expect("内联项绘制回调应被调用");
2215 assert!((rect.width - 30.0).abs() < 0.01 && (rect.height - 24.0).abs() < 0.01, "{rect:?}");
2216 assert!(rect.x >= 10.0 && rect.y >= 5.0, "内联项应带 offset: {rect:?}");
2217 }
2218
2219 #[test]
2220 fn inline_items_wrap_when_narrow() {
2221 set_text_dpr(1.0);
2222 let rich = RichText::from_items(vec![
2223 RichItem::Inline(InlineItem::new(40.0, 20.0, |_, _| {})),
2224 RichItem::Inline(InlineItem::new(40.0, 20.0, |_, _| {})),
2225 ]);
2226 let one_line = rich_text_size(&rich, None);
2227 let wrapped = rich_text_size(&rich, Some(50.0));
2228 assert!(one_line.width > wrapped.width, "窄宽度应减少行宽: {one_line:?} vs {wrapped:?}");
2229 assert!(
2230 wrapped.height > one_line.height * 1.5,
2231 "两个 40 宽内联项在 50 宽内应换行: {one_line:?} vs {wrapped:?}"
2232 );
2233 }
2234
2235 #[test]
2236 fn soft_wrap_uses_max_width() {
2237 set_text_dpr(1.0);
2238 let rich = RichText::new(vec![RichTextSpan::new("word ".repeat(40)).with_size(16.0)]);
2239 let single = rich_text_size(&rich, None);
2240 let wrapped = rich_text_size(&rich, Some(120.0));
2241 assert!(single.height > 0.0 && wrapped.height > 0.0);
2242 assert!(wrapped.height > single.height * 2.0, "换行后高度应显著增加: {single:?} vs {wrapped:?}");
2243 assert!(wrapped.width <= 130.0, "换行后宽度应受 max_width 约束: {wrapped:?}");
2244 }
2245
2246 #[test]
2247 fn span_builders_set_weight_and_italic() {
2248 assert_eq!(RichTextSpan::new("x").weight, None, "默认不指定字重(跟随 400)");
2249 assert!(!RichTextSpan::new("x").italic);
2250 assert_eq!(RichTextSpan::new("x").bold().weight, Some(700));
2251 assert_eq!(RichTextSpan::new("x").with_weight(500).weight, Some(500));
2252 assert_eq!(RichTextSpan::new("x").with_weight(0).weight, Some(1), "非法值夹紧到 ≥1");
2253 assert!(RichTextSpan::new("x").italic().italic);
2254 assert!(!RichTextSpan::new("x").with_italic(true).with_italic(false).italic);
2255 }
2256
2257 #[test]
2258 fn bold_span_is_wider_and_cache_keeps_weights_apart() {
2259 set_text_dpr(1.0);
2260 let text = "Handgloves 字重";
2261 let regular = RichText::new(vec![RichTextSpan::new(text).with_size(20.0)]);
2262 let bold = RichText::new(vec![RichTextSpan::new(text).with_size(20.0).bold()]);
2263
2264 let w_regular = rich_text_size(®ular, None).width;
2265 let w_bold = rich_text_size(&bold, None).width;
2266 assert!(w_bold > w_regular + 0.5, "粗体字面应比常规更宽: regular={w_regular} bold={w_bold}");
2267 assert!((rich_text_size(®ular, None).width - w_regular).abs() < 0.01, "缓存不能把粗体轮廓复用给常规 span");
2269
2270 let mut list = PaintList::new();
2271 let painted = paint_rich_text(&bold, Point::ZERO, &mut list, None);
2272 assert!((painted - w_bold).abs() < 0.5, "绘制宽度应与测量一致: {painted} vs {w_bold}");
2273 let glyphs = list.commands.iter().filter(|c| matches!(c, PaintCommand::TexturedRect { .. })).count();
2274 assert!(glyphs > 4, "粗体也应画出成片字形,实际 {glyphs}");
2275 }
2276
2277 #[test]
2278 fn italic_span_paints_without_changing_line_box() {
2279 set_text_dpr(1.0);
2280 let text = "Italic style";
2281 let regular = RichText::new(vec![RichTextSpan::new(text).with_size(18.0)]);
2282 let italic = RichText::new(vec![RichTextSpan::new(text).with_size(18.0).italic()]);
2283 let mut list = PaintList::new();
2284 let painted = paint_rich_text(&italic, Point::ZERO, &mut list, None);
2285 let glyphs = list.commands.iter().filter(|c| matches!(c, PaintCommand::TexturedRect { .. })).count();
2286 assert!(glyphs > 4, "斜体应照常成片绘制,实际 {glyphs}");
2287 let w_italic = rich_text_size(&italic, None).width;
2288 assert!(w_italic > 0.0, "斜体宽度有效: {w_italic}");
2289 assert!((painted - w_italic).abs() < 0.5, "斜体绘制宽度应与测量一致: {painted} vs {w_italic}");
2290 assert!(
2292 w_italic.abs() < rich_text_size(®ular, None).width * 2.0,
2293 "斜体宽度应与常规同量级: italic={w_italic}"
2294 );
2295 }
2296
2297 #[test]
2298 fn raster_font_id_folds_variation_coords() {
2299 assert_eq!(raster_font_id(42, &[]), 42);
2301 let a: [swash::NormalizedCoord; 1] = [1];
2302 let b: [swash::NormalizedCoord; 1] = [2];
2303 let coords_a: &[swash::NormalizedCoord] = &a;
2304 let coords_b: &[swash::NormalizedCoord] = &b;
2305 assert_ne!(raster_font_id(42, coords_a), raster_font_id(42, coords_b), "不同可变轴坐标必须是不同栅格身份");
2306 assert_eq!(raster_font_id(42, coords_a), raster_font_id(42, coords_a), "同坐标必须稳定(缓存命中)");
2307 assert_ne!(raster_font_id(42, coords_a), raster_font_id(43, coords_a), "不同 blob 也必须区分");
2308 }
2309}
2310
2311#[cfg(test)]
2316mod multiline_regression {
2317 use super::*;
2318
2319 #[test]
2321 fn multiline_text_lines_have_distinct_y() {
2322 let mut list = PaintList::new();
2323 paint_text_line("第一行AAA\n第二行BBB", 20.0, Color::WHITE, Point::new(50.0, 100.0), &mut list, None);
2324 let ys: Vec<f32> = list
2325 .commands
2326 .iter()
2327 .filter_map(|c| match c {
2328 PaintCommand::TexturedRect { rect, .. } => Some((rect.y * 10.0).round() / 10.0),
2329 _ => None,
2330 })
2331 .collect();
2332 assert!(!ys.is_empty(), "应画出 glyph");
2333 let y0 = ys[0];
2334 assert!(ys.iter().any(|&y| (y - y0).abs() > 20.0), "多行文本各行 y 必须拉开,实际全部≈{}: {:?}", y0, ys);
2335 }
2336
2337 #[test]
2339 fn wrapped_text_lines_have_distinct_y() {
2340 let mut list = PaintList::new();
2341 paint_text_line(
2343 "第一行文本内容比较长需要折行",
2344 20.0,
2345 Color::WHITE,
2346 Point::new(0.0, 0.0),
2347 &mut list,
2348 Some(60.0),
2349 );
2350 let ys: Vec<f32> = list
2351 .commands
2352 .iter()
2353 .filter_map(|c| match c {
2354 PaintCommand::TexturedRect { rect, .. } => Some((rect.y * 10.0).round() / 10.0),
2355 _ => None,
2356 })
2357 .collect();
2358 let y0 = ys[0];
2359 assert!(ys.iter().any(|&y| (y - y0).abs() > 20.0), "soft-wrap 多行 y 必须拉开,实际全部≈{}: {:?}", y0, ys);
2360 }
2361}