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);
314
315struct LineCacheEntry {
317 line: std::rc::Rc<ShapedLine>,
318 last_used: u64,
319}
320
321pub struct FontState {
323 pub font_cx: parley::FontContext,
324 pub layout_cx: parley::LayoutContext<()>,
325 pub scale_cx: swash::scale::ScaleContext,
326 pub atlas: Atlas,
327 raster_cache: HashMap<GlyphKey, RasterGlyph>,
329 raster_cache_bytes: usize,
331 line_cache: HashMap<LineCacheKey, LineCacheEntry>,
338 rich_cache: HashMap<RichCacheKey, RichCacheEntry>,
340 rich_clock: u64,
342 line_clock: u64,
344 glyph_clock: u64,
346 pub shape_calls: usize,
348}
349
350impl FontState {
351 fn new() -> Self {
352 Self {
353 font_cx: parley::FontContext::new(),
354 layout_cx: parley::LayoutContext::<()>::new(),
355 scale_cx: swash::scale::ScaleContext::new(),
356 atlas: Atlas::new(ATLAS_SIZE, ATLAS_SIZE),
357 raster_cache: HashMap::new(),
358 raster_cache_bytes: 0,
359 line_cache: HashMap::new(),
360 rich_cache: HashMap::new(),
361 rich_clock: 0,
362 line_clock: 0,
363 glyph_clock: 0,
364 shape_calls: 0,
365 }
366 }
367}
368
369thread_local! {
370 static FONT_STATE: RefCell<Option<FontState>> = const { RefCell::new(None) }; static TEXT_DPR: std::cell::Cell<f32> = const { std::cell::Cell::new(1.0) };
376}
377
378pub fn set_text_dpr(dpr: f32) {
380 TEXT_DPR.with(|c| c.set(if dpr > 0.0 { dpr } else { 1.0 }));
381}
382
383fn text_dpr() -> f32 {
384 TEXT_DPR.with(|c| c.get())
385}
386
387pub fn with_font<F, R>(f: F) -> R
389where
390 F: FnOnce(&mut FontState) -> R,
391{
392 FONT_STATE.with(|cell| {
393 let mut opt = cell.borrow_mut();
394 if opt.is_none() {
395 *opt = Some(FontState::new());
396 }
397 f(opt.as_mut().unwrap())
398 })
399}
400
401const LINE_CACHE_LIMIT: usize = 4096;
410
411const LINE_CACHE_TARGET: usize = LINE_CACHE_LIMIT - LINE_CACHE_LIMIT / 4;
413
414fn evict_line_cache_lru(fs: &mut FontState) {
416 if fs.line_cache.len() <= LINE_CACHE_TARGET {
417 return;
418 }
419 let mut by_age: Vec<(u64, LineCacheKey)> = fs.line_cache.iter().map(|(k, v)| (v.last_used, k.clone())).collect();
420 by_age.sort_unstable_by_key(|&(last_used, _)| last_used);
421 let remove = fs.line_cache.len().saturating_sub(LINE_CACHE_TARGET);
422 for (_, key) in by_age.into_iter().take(remove) {
423 fs.line_cache.remove(&key);
424 }
425}
426
427const RASTER_CACHE_BUDGET_BYTES: usize = 32 * 1024 * 1024;
429const RASTER_CACHE_TARGET_BYTES: usize = RASTER_CACHE_BUDGET_BYTES * 3 / 4;
431
432fn insert_raster_glyph(fs: &mut FontState, key: GlyphKey, mut glyph: RasterGlyph) {
434 fs.glyph_clock += 1;
435 glyph.last_used = fs.glyph_clock;
436 let bytes = glyph.data.len();
437 if let Some(old) = fs.raster_cache.insert(key, glyph) {
438 fs.raster_cache_bytes = fs.raster_cache_bytes.saturating_sub(old.data.len());
439 }
440 fs.raster_cache_bytes += bytes;
441 trim_raster_cache(fs);
442}
443
444fn trim_raster_cache(fs: &mut FontState) {
449 if fs.raster_cache_bytes <= RASTER_CACHE_BUDGET_BYTES {
450 return;
451 }
452 let mut candidates: Vec<(u64, GlyphKey, usize)> =
453 fs.raster_cache.iter().map(|(&key, g)| (g.last_used, key, g.data.len())).collect();
454 candidates.sort_unstable_by_key(|&(last_used, _, _)| last_used);
455 for (_, key, bytes) in candidates {
456 if fs.raster_cache_bytes <= RASTER_CACHE_TARGET_BYTES {
457 break;
458 }
459 fs.raster_cache.remove(&key);
460 fs.raster_cache_bytes = fs.raster_cache_bytes.saturating_sub(bytes);
461 }
462}
463
464#[derive(Clone, PartialEq, Eq, Hash)]
470enum TextKey {
471 Owned(String),
472 Shared(std::rc::Rc<str>, Option<(usize, usize)>),
473}
474
475impl TextKey {
476 fn owned(text: &str) -> Self {
477 TextKey::Owned(text.to_string())
478 }
479}
480
481struct ShapedGlyph {
483 raster_key: GlyphKey,
485 glyph_id: u16,
487 x: f32,
489 w: f32,
491 #[allow(dead_code)]
493 y: f32,
494 ascent: f32,
496 descent: f32,
498 cluster: u32,
501}
502
503struct ShapedRun {
505 glyphs: Vec<ShapedGlyph>,
506 baseline_y: f32,
508 font: parley::FontData,
512 norm_coords: std::rc::Rc<[swash::NormalizedCoord]>,
514 raster_size: f32,
516}
517
518struct ShapedLine {
520 runs: Vec<ShapedRun>,
521 max_x: f32,
523 #[allow(dead_code)]
525 max_y: f32,
526 visual_lines: Vec<(usize, usize)>,
528}
529
530fn shape_text(
535 fs: &mut FontState,
536 text: &str,
537 raster_px: f32,
538 max_width_px: Option<f32>,
539 font_stack: &str,
540) -> std::rc::Rc<ShapedLine> {
541 shape_text_keyed(fs, text, TextKey::owned(text), raster_px, max_width_px, font_stack)
542}
543
544fn shape_text_keyed(
547 fs: &mut FontState,
548 text: &str,
549 text_key: TextKey,
550 raster_px: f32,
551 max_width_px: Option<f32>,
552 font_stack: &str,
553) -> std::rc::Rc<ShapedLine> {
554 let font_stack_hash = {
555 let mut h = DefaultHasher::new();
556 font_stack.hash(&mut h);
557 h.finish()
558 };
559 let key = (text_key, raster_px.to_bits(), max_width_px.map(|w| w.to_bits()), font_stack_hash);
560 if let Some(entry) = fs.line_cache.get_mut(&key) {
561 fs.line_clock += 1;
562 entry.last_used = fs.line_clock;
563 return std::rc::Rc::clone(&entry.line);
564 }
565
566 fs.shape_calls += 1;
567 let dpr = text_dpr();
568
569 let scale = 1.0f32;
572 let font_size_px = raster_px / dpr;
573
574 let wrap_opt = max_width_px.filter(|&w| w > 0.0);
576
577 let mut builder = fs.layout_cx.ranged_builder(&mut fs.font_cx, text, scale, true);
578 builder.push_default(parley::StyleProperty::FontSize(font_size_px));
579 builder.push_default(parley::StyleProperty::LineHeight(parley::LineHeight::FontSizeRelative(1.2)));
585 builder.push_default(parley::StyleProperty::FontFamily(parley::FontFamily::Source(std::borrow::Cow::Borrowed(
588 font_stack,
589 ))));
590 builder.push_default(parley::StyleProperty::WordBreak(parley::WordBreak::KeepAll));
593 builder.push_default(parley::StyleProperty::OverflowWrap(parley::OverflowWrap::Anywhere));
594 let mut layout: parley::Layout<()> = builder.build(text);
595 layout.break_all_lines(wrap_opt);
596 layout.align(parley::Alignment::Start, parley::AlignmentOptions::default());
599
600 let mut runs = Vec::new();
604 let mut max_x = 0.0f32;
605 let mut max_y = 0.0f32;
606 let mut visual_lines = Vec::new();
607
608 for line in layout.lines() {
609 let mut line_start = usize::MAX;
611 let mut line_end = 0usize;
612 for run in line.runs() {
613 let range = run.text_range();
614 line_start = line_start.min(range.start);
615 line_end = line_end.max(range.end);
616 }
617 visual_lines.push(if line_start == usize::MAX { (0, 0) } else { (line_start, line_end) });
618
619 let line_m = line.metrics();
620 let baseline_y = line_m.baseline * dpr; for item in line.items() {
623 let parley::PositionedLayoutItem::GlyphRun(gr) = item else {
624 continue;
625 };
626
627 let run_metrics = gr.run().font_metrics();
631 let ascent = run_metrics.ascent * dpr;
632 let descent = run_metrics.descent * dpr;
633 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();
644 let norm_coords: std::rc::Rc<[swash::NormalizedCoord]> =
650 gr.run().normalized_coords().iter().map(|c| c.to_bits()).collect();
651 let run_font = gr.run().font().clone();
652 let mut pen_x = gr.offset();
653 let run_baseline = gr.baseline();
654 for cluster in gr.run().visual_clusters() {
655 let cluster_byte = cluster.text_range().start as u32;
656 for g in cluster.glyphs() {
657 let glyph_id = match narrow_glyph_id(g.id) {
660 Some(id) => id,
661 None => {
662 log::warn!("mgui-text: glyph id {} 超出 swash 的 u16 范围,跳过该字形", g.id);
663 pen_x += g.advance;
664 continue;
665 }
666 };
667 let size_bits = font_size_phys.to_bits(); let x_bin = 0; let y_bin = 0;
670 let raster_key =
671 GlyphKey::new(raster_font_id(font_blob_id, &norm_coords), glyph_id, size_bits, x_bin, y_bin, 0);
672 if !fs.raster_cache.contains_key(&raster_key) {
674 if let Some(rg) =
675 rasterize_one_glyph(&run_font, font_size_phys, glyph_id, &norm_coords, &mut fs.scale_cx)
676 {
677 insert_raster_glyph(fs, raster_key, rg);
678 }
679 }
680 let gx = pen_x + g.x;
681 run_glyphs.push(ShapedGlyph {
682 raster_key,
683 glyph_id,
684 x: gx * dpr, w: g.advance * dpr, y: (run_baseline + g.y) * dpr, ascent,
688 descent,
689 cluster: cluster_byte,
690 });
691 max_x = max_x.max((gx + g.advance) * dpr);
692 max_y = max_y.max(baseline_y + descent);
693 pen_x += g.advance;
694 }
695 }
696
697 if !run_glyphs.is_empty() {
698 runs.push(ShapedRun {
699 glyphs: run_glyphs,
700 baseline_y,
701 font: run_font,
702 norm_coords,
703 raster_size: font_size_phys,
704 });
705 }
706 }
707 }
708
709 if max_y == 0.0 {
711 max_y = raster_px * 1.2;
712 }
713
714 let line = std::rc::Rc::new(ShapedLine { runs, max_x, max_y, visual_lines });
715 if fs.line_cache.len() >= LINE_CACHE_LIMIT {
716 evict_line_cache_lru(fs);
717 }
718 fs.line_clock += 1;
719 let entry = LineCacheEntry { line: std::rc::Rc::clone(&line), last_used: fs.line_clock };
720 fs.line_cache.insert(key, entry);
721 line
722}
723
724#[derive(Clone)]
732pub struct AtlasSnapshot {
733 pub width: u32,
734 pub height: u32,
735 pub dirty: bool,
736 pub dirty_y: (u32, u32),
739 pub pixels: Option<Vec<u8>>,
741}
742
743pub fn atlas_snapshot() -> AtlasSnapshot {
745 with_font(|fs| {
746 let dirty = fs.atlas.is_dirty();
747 let (y0, y1) = if dirty {
748 let (a, b) = fs.atlas.dirty_rows.unwrap_or((0, fs.atlas.height));
749 (a.min(fs.atlas.height), b.min(fs.atlas.height))
750 } else {
751 (0, 0)
752 };
753 let pixels = if dirty {
754 let w = fs.atlas.width as usize;
755 Some(fs.atlas.pixels()[(y0 as usize * w)..(y1 as usize * w)].to_vec())
756 } else {
757 None
758 };
759 AtlasSnapshot { width: fs.atlas.width, height: fs.atlas.height, dirty, dirty_y: (y0, y1), pixels }
760 })
761}
762
763pub fn atlas_clear_dirty() {
765 with_font(|fs| {
766 fs.atlas.clear_dirty();
767 })
768}
769
770pub fn atlas_generation() -> u64 {
772 with_font(|fs| fs.atlas.generation)
773}
774
775#[derive(Clone, Copy, Debug, Default)]
777pub struct AtlasStats {
778 pub width: u32,
779 pub height: u32,
780 pub glyph_count: usize,
781 pub used_height: u32,
783 pub dirty: bool,
784}
785
786pub fn atlas_stats() -> AtlasStats {
787 with_font(|fs| {
788 let atlas = &fs.atlas;
789 AtlasStats {
790 width: atlas.width,
791 height: atlas.height,
792 glyph_count: atlas.entries.len(),
793 used_height: (atlas.next_y + atlas.row_height).min(atlas.height),
794 dirty: atlas.dirty,
795 }
796 })
797}
798
799pub fn with_atlas<R>(f: impl FnOnce(u32, u32, &[u8]) -> R) -> R {
804 with_font(|fs| {
805 let atlas = &fs.atlas;
806 f(atlas.width, atlas.height, &atlas.pixels)
807 })
808}
809
810pub struct TextRenderObject {
815 text: String,
816 size_px: f32,
817 color: Color,
818 max_width: Option<f32>,
820 max_width_explicit: bool,
823 size: Size,
825 element_id: Option<ElementId>,
826}
827
828impl TextRenderObject {
829 pub fn new(text: String, size_px: f32, color: Color) -> Self {
830 Self { text, size_px, color, max_width: None, max_width_explicit: false, size: Size::ZERO, element_id: None }
831 }
832
833 pub fn with_max_width(mut self, max_width: f32) -> Self {
834 self.max_width = Some(max_width);
835 self.max_width_explicit = true;
836 self
837 }
838
839 pub fn set_max_width(&mut self, max_width: Option<f32>) {
840 self.max_width = max_width;
841 self.max_width_explicit = max_width.is_some();
842 }
843
844 fn measure(&self) -> Size {
846 let dpr = text_dpr();
847 let raster_px = self.size_px * dpr;
848 let width = with_font(|fs| {
849 let line = shape_text(fs, &self.text, raster_px, self.max_width, DEFAULT_FONT_STACK);
850 let max_x = line.max_x / dpr;
851 if max_x == 0.0 && !self.text.is_empty() {
852 self.text.chars().count() as f32 * FALLBACK_ADVANCE_X
853 } else {
854 max_x
855 }
856 });
857 let height = text_visual_height(&self.text, self.size_px, self.max_width);
860 Size::new(width, height)
861 }
862}
863
864pub fn measure_text_width(text: &str, size_px: f32) -> f32 {
868 measure_text_width_styled(text, size_px, DEFAULT_FONT_STACK)
869}
870
871pub fn measure_text_width_styled(text: &str, size_px: f32, font_stack: &str) -> f32 {
873 if text.is_empty() {
874 return 0.0;
875 }
876 with_font(|fs| {
877 let dpr = text_dpr();
879 let raster_px = size_px * dpr;
880 let line = shape_text(fs, text, raster_px, None, font_stack);
881 let w = line.max_x / dpr;
882 if w == 0.0 {
883 text.chars().count() as f32 * FALLBACK_ADVANCE_X
884 } else {
885 w
886 }
887 })
888}
889
890pub fn text_visual_height(text: &str, size_px: f32, max_width_px: Option<f32>) -> f32 {
900 text_visual_height_styled(text, size_px, max_width_px, DEFAULT_FONT_STACK)
901}
902
903pub fn text_visual_height_styled(text: &str, size_px: f32, max_width_px: Option<f32>, font_stack: &str) -> f32 {
905 if text.is_empty() {
906 return size_px;
907 }
908 with_font(|fs| {
909 let dpr = text_dpr();
910 let raster_px = size_px * dpr;
911 let line = shape_text(fs, text, raster_px, max_width_px, font_stack);
912
913 if line.runs.is_empty() {
914 return size_px;
915 }
916
917 let first_run = &line.runs[0];
919 let first_ascent = first_run.glyphs.first().map(|g| g.ascent).unwrap_or(raster_px);
920 let first_baseline = first_run.baseline_y;
921 let visual_top = first_baseline - first_ascent;
922
923 let mut visual_bottom = 0.0f32;
925 for run in &line.runs {
926 for sg in &run.glyphs {
927 let bottom = run.baseline_y + sg.descent;
928 visual_bottom = visual_bottom.max(bottom);
929 }
930 }
931
932 if visual_bottom > visual_top {
933 (visual_bottom - visual_top) / dpr
934 } else {
935 size_px
936 }
937 })
938}
939
940pub fn paint_text_line(
946 text: &str,
947 size_px: f32,
948 color: Color,
949 offset: Point,
950 list: &mut PaintList,
951 max_width_px: Option<f32>,
952) -> f32 {
953 paint_text_line_impl(text, TextKey::owned(text), size_px, color, offset, list, max_width_px, DEFAULT_FONT_STACK)
954}
955
956#[allow(clippy::too_many_arguments)]
958pub fn paint_text_line_styled(
959 text: &str,
960 size_px: f32,
961 color: Color,
962 offset: Point,
963 list: &mut PaintList,
964 max_width_px: Option<f32>,
965 font_stack: &str,
966) -> f32 {
967 paint_text_line_impl(text, TextKey::owned(text), size_px, color, offset, list, max_width_px, font_stack)
968}
969
970#[allow(clippy::too_many_arguments)]
975pub fn paint_text_span(
976 text: &std::rc::Rc<str>,
977 range: Option<(usize, usize)>,
978 size_px: f32,
979 color: Color,
980 offset: Point,
981 list: &mut PaintList,
982 max_width_px: Option<f32>,
983) -> f32 {
984 let (start, end) = match range {
985 Some(r) => clamp_char_range(text, r),
986 None => (0, text.len()),
987 };
988 paint_text_line_impl(
989 &text[start..end],
990 TextKey::Shared(std::rc::Rc::clone(text), range),
991 size_px,
992 color,
993 offset,
994 list,
995 max_width_px,
996 DEFAULT_FONT_STACK,
997 )
998}
999
1000pub fn text_ascent(text: &str, size_px: f32) -> f32 {
1006 if text.is_empty() {
1007 return size_px;
1008 }
1009 with_font(|fs| {
1010 let dpr = text_dpr();
1011 let shaped = shape_text(fs, text, size_px * dpr, None, DEFAULT_FONT_STACK);
1012 first_glyph_ascent(&shaped).map(|a| a / dpr).unwrap_or(size_px)
1013 })
1014}
1015
1016pub fn text_span_ascent(text: &std::rc::Rc<str>, range: Option<(usize, usize)>, size_px: f32) -> f32 {
1019 let (start, end) = match range {
1020 Some(r) => clamp_char_range(text, r),
1021 None => (0, text.len()),
1022 };
1023 if start >= end {
1024 return size_px;
1025 }
1026 with_font(|fs| {
1027 let dpr = text_dpr();
1028 let shaped = shape_text_keyed(
1029 fs,
1030 &text[start..end],
1031 TextKey::Shared(std::rc::Rc::clone(text), range),
1032 size_px * dpr,
1033 None,
1034 DEFAULT_FONT_STACK,
1035 );
1036 first_glyph_ascent(&shaped).map(|a| a / dpr).unwrap_or(size_px)
1037 })
1038}
1039
1040fn first_glyph_ascent(shaped: &ShapedLine) -> Option<f32> {
1041 shaped.runs.first().and_then(|r| r.glyphs.first()).map(|g| g.ascent)
1042}
1043
1044fn clamp_char_range(text: &str, range: (usize, usize)) -> (usize, usize) {
1046 let mut start = range.0.min(text.len());
1047 let mut end = range.1.min(text.len());
1048 while !text.is_char_boundary(start) {
1049 start += 1;
1050 }
1051 while !text.is_char_boundary(end) {
1052 end -= 1;
1053 }
1054 if end < start {
1055 end = start;
1056 }
1057 (start, end)
1058}
1059
1060#[allow(clippy::too_many_arguments)]
1062fn paint_text_line_impl(
1063 text: &str,
1064 text_key: TextKey,
1065 size_px: f32,
1066 color: Color,
1067 offset: Point,
1068 list: &mut PaintList,
1069 max_width_px: Option<f32>,
1070 font_stack: &str,
1071) -> f32 {
1072 if text.is_empty() {
1073 return 0.0;
1074 }
1075 let width = with_font(|fs| {
1076 let dpr = text_dpr();
1077 let raster_px = size_px * dpr;
1078 let shaped = shape_text_keyed(fs, text, text_key, raster_px, max_width_px, font_stack);
1079
1080 let first_run = match shaped.runs.first() {
1084 Some(r) => r,
1085 None => return 0.0,
1086 };
1087 let first_ascent = first_run.glyphs.first().map(|g| g.ascent).unwrap_or(raster_px);
1088 let first_baseline = first_run.baseline_y;
1089 let anchor = first_baseline - first_ascent; let mut max_x = 0.0f32;
1092 for run in &shaped.runs {
1093 for sg in &run.glyphs {
1094 if !fs.raster_cache.contains_key(&sg.raster_key) {
1097 if let Some(rg) =
1098 rasterize_one_glyph(&run.font, run.raster_size, sg.glyph_id, &run.norm_coords, &mut fs.scale_cx)
1099 {
1100 insert_raster_glyph(fs, sg.raster_key, rg);
1101 }
1102 }
1103 let Some(r) = fs.raster_cache.get_mut(&sg.raster_key) else {
1107 continue;
1108 };
1109 if r.width == 0 || r.height == 0 {
1110 continue;
1111 }
1112 fs.glyph_clock += 1;
1113 r.last_used = fs.glyph_clock;
1114 let entry = fs.atlas.get_or_insert(sg.raster_key, &r.data, r.width, r.height);
1115
1116 let x = offset.x + (sg.x + r.left as f32) / dpr;
1118 let glyph_visual_top = run.baseline_y - r.top as f32;
1123 let y = offset.y + (glyph_visual_top - anchor) / dpr;
1124
1125 let rect = Rect::new(x, y, r.width as f32 / dpr, r.height as f32 / dpr);
1126 list.push(PaintCommand::TexturedRect {
1127 rect,
1128 color,
1129 uv: entry.uv,
1130 texture_id: 0,
1131 mode: mgui_core::paint::TextureMode::Mask,
1132 });
1133 max_x = max_x.max((sg.x + sg.w) / dpr);
1134 }
1135 }
1136 if max_x == 0.0 {
1137 max_x = text.chars().count() as f32 * FALLBACK_ADVANCE_X;
1138 }
1139 max_x
1140 });
1141 width
1142}
1143
1144pub fn wrapped_line_ranges(text: &str, size_px: f32, max_width: f32) -> Vec<(usize, usize)> {
1159 if text.is_empty() {
1160 return vec![(0, 0)];
1161 }
1162 if max_width <= 0.0 {
1163 return vec![(0, text.len())];
1164 }
1165 with_font(|fs| {
1166 let dpr = text_dpr();
1167 let raster_px = size_px * dpr;
1168 let shaped = shape_text(fs, text, raster_px, Some(max_width), DEFAULT_FONT_STACK);
1169 shaped.visual_lines.clone()
1170 })
1171}
1172
1173pub fn measure_char_prefix_widths(text: &str, size_px: f32, font_stack: &str) -> Vec<f32> {
1174 if text.is_empty() {
1175 return vec![0.0];
1176 }
1177 with_font(|fs| {
1178 let dpr = text_dpr();
1179 let raster_px = size_px * dpr;
1180 let shaped = shape_text(fs, text, raster_px, None, font_stack);
1181
1182 let char_count = text.chars().count();
1183 let mut widths = vec![0.0f32; char_count + 1];
1184
1185 let mut byte_x: Vec<(u32, f32)> = Vec::new();
1188 for run in &shaped.runs {
1189 for sg in &run.glyphs {
1190 match byte_x.last_mut() {
1191 Some((b, _)) if *b == sg.cluster => {}
1192 _ => byte_x.push((sg.cluster, sg.x)),
1193 }
1194 }
1195 }
1196
1197 let mut prev = 0.0f32;
1200 let mut bi = 0usize;
1201 for (ci, (byte_pos, _)) in text.char_indices().enumerate() {
1202 while bi < byte_x.len() && byte_x[bi].0 <= byte_pos as u32 {
1203 prev = byte_x[bi].1 / dpr;
1204 bi += 1;
1205 }
1206 widths[ci] = prev;
1207 }
1208 widths[char_count] = shaped.max_x / dpr;
1209 widths
1210 })
1211}
1212
1213fn rasterize_one_glyph(
1215 font: &parley::FontData,
1216 font_size: f32,
1217 glyph_id: u16,
1218 norm_coords: &[swash::NormalizedCoord],
1219 scale_cx: &mut swash::scale::ScaleContext,
1220) -> Option<RasterGlyph> {
1221 let bytes = font.data.data();
1223 if bytes.is_empty() {
1224 return None;
1225 }
1226 let font_ref = swash::FontRef::from_index(bytes, font.index as usize)?;
1227 let mut scaler =
1228 scale_cx.builder(font_ref).size(font_size).normalized_coords(norm_coords.iter()).hint(true).build();
1229 let image = swash::scale::Render::new(&[
1230 swash::scale::Source::ColorOutline(0),
1231 swash::scale::Source::ColorBitmap(swash::scale::StrikeWith::BestFit),
1232 swash::scale::Source::Outline,
1233 ])
1234 .render(&mut scaler, glyph_id)?;
1235 if image.placement.width == 0 || image.placement.height == 0 {
1236 return Some(RasterGlyph { data: Vec::new(), width: 0, height: 0, left: 0, top: 0, last_used: 0 });
1241 }
1242 Some(RasterGlyph {
1243 data: image.data.to_vec(),
1244 width: image.placement.width,
1245 height: image.placement.height,
1246 left: image.placement.left,
1247 top: image.placement.top,
1248 last_used: 0,
1249 })
1250}
1251
1252impl RenderObject for TextRenderObject {
1253 fn layout(&mut self, _bc: BoxConstraints, _ctx: &mut LayoutContext) -> Size {
1254 let s = self.measure();
1265 self.size = s;
1266 s
1267 }
1268
1269 fn content_size(&self) -> Size {
1270 self.size
1271 }
1272
1273 fn paint(&self, offset: Point, list: &mut PaintList) {
1274 paint_text_line(&self.text, self.size_px, self.color, offset, list, self.max_width);
1275 }
1276
1277 fn set_element_id(&mut self, id: ElementId) {
1278 self.element_id = Some(id);
1279 }
1280
1281 fn hit_test(&self, position: Point, offset: Point) -> Option<ElementId> {
1282 let r = Rect::new(offset.x, offset.y, self.size.width, self.size.height);
1286 if r.contains(position) {
1287 self.element_id
1288 } else {
1289 None
1290 }
1291 }
1292}
1293
1294#[cfg(test)]
1299mod tests {
1300 use super::*;
1301
1302 fn mk_key(id: u32) -> GlyphKey {
1303 GlyphKey(id as u64)
1304 }
1305
1306 #[test]
1307 fn atlas_get_or_insert_dedupes() {
1308 let mut a = Atlas::new(64, 64);
1309 let k = mk_key(1);
1310 let e1 = a.get_or_insert(k, &[255; 8], 2, 4);
1311 let e2 = a.get_or_insert(k, &[0; 8], 2, 4);
1312 assert_eq!(e1.uv, e2.uv, "重复 key 必须返回同一 entry");
1313 assert_eq!(a.glyph_count(), 1);
1314 }
1315
1316 #[test]
1317 fn atlas_wraps_to_next_row() {
1318 let mut a = Atlas::new(20, 20);
1319 let k1 = mk_key(1);
1321 a.get_or_insert(k1, &[1; 64], 16, 4);
1322 let k2 = mk_key(2);
1324 let e2 = a.get_or_insert(k2, &[2; 64], 16, 4);
1325 assert!(e2.uv[1] > 0.0, "第二个 glyph 应该换行,uv.v0 > 0");
1326 }
1327
1328 #[test]
1329 fn atlas_dirty_flag_lifecycle() {
1330 let mut a = Atlas::new(64, 64);
1331 assert!(!a.is_dirty());
1333 a.get_or_insert(mk_key(1), &[255; 8], 2, 4);
1335 assert!(a.is_dirty(), "get_or_insert 后应该 dirty");
1336 a.clear_dirty();
1338 assert!(!a.is_dirty());
1339 a.get_or_insert(mk_key(1), &[0; 8], 2, 4);
1341 assert!(!a.is_dirty(), "重复 key 不应触发 dirty");
1342 a.get_or_insert(mk_key(2), &[0; 8], 2, 4);
1344 assert!(a.is_dirty());
1345 }
1346
1347 #[test]
1350 fn atlas_snapshot_uploads_only_dirty_rows() {
1351 let width = with_font(|fs| {
1353 fs.atlas = Atlas::new(ATLAS_SIZE, ATLAS_SIZE);
1354 fs.atlas.width
1355 });
1356 with_font(|fs| {
1357 fs.atlas.get_or_insert(GlyphKey::new(7, 7, 0, 0, 0, 0), &[9u8; 16], 4, 4);
1358 fs.atlas.get_or_insert(GlyphKey::new(7, 8, 0, 0, 0, 0), &[9u8; 16], 4, 4);
1359 assert_eq!(fs.atlas.dirty_rows, Some((1, 5)), "同一行的写入应合并为单行带");
1360 });
1361 let snap = atlas_snapshot();
1362 assert!(snap.dirty);
1363 assert_eq!(snap.dirty_y, (1, 5));
1364 assert_eq!(snap.pixels.as_ref().map(Vec::len), Some(width as usize * 4), "快照只拷贝 dirty 行");
1365 atlas_clear_dirty();
1366 let clean = atlas_snapshot();
1367 assert!(!clean.dirty);
1368 assert_eq!(clean.dirty_y, (0, 0));
1369 assert!(clean.pixels.is_none());
1370 }
1371
1372 #[test]
1374 fn atlas_auto_expands_when_full() {
1375 let mut a = Atlas::new(32, 32);
1376 let e_before = a.get_or_insert(mk_key(1), &[100; 9], 3, 3);
1378 let uv_scalar_before = e_before.uv[0]; let big: Vec<u8> = vec![200; 400]; for i in 2..10 {
1384 a.get_or_insert(mk_key(i), &big, 20, 20);
1385 }
1386 assert!(a.width >= 32, "atlas 应保持原尺寸或扩容");
1388 assert!(a.glyph_count() >= 8, "扩容后应能放下 8+ glyphs,实际 {}", a.glyph_count());
1389
1390 if a.width > 32 {
1392 let e_after = a.get_or_insert(mk_key(1), &[0; 9], 3, 3);
1394 let expected = uv_scalar_before / 2.0;
1397 assert!((e_after.uv[0] - expected).abs() < 0.01, "扩容后 uv.u0 应为 {expected}, 实际 {}", e_after.uv[0]);
1398 }
1399 }
1400
1401 #[test]
1403 fn atlas_accepts_new_glyphs_after_expansion() {
1404 let mut a = Atlas::new(16, 16);
1405 a.get_or_insert(mk_key(1), &[50; 144], 12, 12);
1407 let e2 = a.get_or_insert(mk_key(2), &[100; 144], 12, 12);
1409 assert!(a.width > 16 || a.height > 16, "应该扩容了");
1410 let e1 = a.get_or_insert(mk_key(1), &[0; 144], 12, 12);
1412 assert!(e2.uv[1] >= e1.uv[1], "第二个 glyph 应在第一个下方");
1413 }
1414
1415 #[test]
1416 fn text_measure_produces_nonzero_size() {
1417 let t = TextRenderObject::new("Hello".into(), 24.0, Color::WHITE);
1418 let s = t.measure();
1419 assert!(s.width > 0.0, "width should be > 0 for 'Hello'");
1420 assert!(s.height > 0.0, "height should be > 0");
1421 }
1422
1423 #[test]
1424 fn text_paint_emits_textured_rects() {
1425 let t = TextRenderObject::new("Hi".into(), 24.0, Color::WHITE);
1426 let mut list = PaintList::new();
1427 t.paint(Point::new(0.0, 0.0), &mut list);
1428 assert!(!list.is_empty(), "paint should emit at least 1 textured rect");
1430 for cmd in &list.commands {
1431 match cmd {
1432 PaintCommand::TexturedRect { texture_id, uv, .. } => {
1433 assert_eq!(*texture_id, 0);
1434 assert!(uv[0] < uv[2]);
1435 assert!(uv[1] < uv[3]);
1436 }
1437 _ => panic!("expected TexturedRect, got Rect"),
1438 }
1439 }
1440 }
1441
1442 #[test]
1443 fn text_paint_with_offset_shifts_rects() {
1444 let t = TextRenderObject::new("X".into(), 24.0, Color::WHITE);
1445 let mut list = PaintList::new();
1446 t.paint(Point::new(100.0, 50.0), &mut list);
1447 for cmd in &list.commands {
1449 if let PaintCommand::TexturedRect { rect, .. } = cmd {
1450 assert!(rect.x >= 100.0 - 1.0, "x={}", rect.x);
1451 assert!(rect.y >= 50.0 - 1.0, "y={}", rect.y);
1452 }
1453 }
1454 }
1455
1456 #[test]
1458 fn shape_line_cache_hits_second_paint() {
1459 let mut list1 = PaintList::new();
1460 paint_text_line("cache-hit-test", 20.0, Color::WHITE, Point::ZERO, &mut list1, None);
1461 let calls_1 = with_font(|fs| fs.shape_calls);
1462
1463 let mut list2 = PaintList::new();
1464 paint_text_line("cache-hit-test", 20.0, Color::WHITE, Point::new(5.0, 5.0), &mut list2, None);
1465 let calls_2 = with_font(|fs| fs.shape_calls);
1466
1467 assert_eq!(calls_1, calls_2, "第二次 paint 应命中缓存,不再 shape");
1468 assert_eq!(list1.commands.len(), list2.commands.len(), "缓存命中的绘制输出数量应一致");
1469 }
1470
1471 #[test]
1473 fn shape_line_cache_evicts_lru_at_limit() {
1474 let fake_line =
1475 || std::rc::Rc::new(ShapedLine { runs: Vec::new(), max_x: 0.0, max_y: 0.0, visual_lines: Vec::new() });
1476 let hot_key = (TextKey::Owned("hot-entry".to_string()), 0, None, 0);
1477 let oldest_key = (TextKey::Owned("fake-entry-0".to_string()), 0, None, 0);
1478 with_font(|fs| {
1479 fs.line_cache.clear();
1480 fs.line_clock = 0;
1481 fs.line_clock += 1;
1482 fs.line_cache.insert(hot_key.clone(), LineCacheEntry { line: fake_line(), last_used: fs.line_clock });
1483 for i in 0..LINE_CACHE_LIMIT - 1 {
1484 fs.line_clock += 1;
1485 fs.line_cache.insert(
1486 (TextKey::Owned(format!("fake-entry-{i}")), 0, None, 0),
1487 LineCacheEntry { line: fake_line(), last_used: fs.line_clock },
1488 );
1489 }
1490 fs.line_clock += 1;
1492 fs.line_cache.get_mut(&hot_key).expect("hot entry").last_used = fs.line_clock;
1493 });
1494 let mut list = PaintList::new();
1496 paint_text_line("trigger-evict", 14.0, Color::WHITE, Point::ZERO, &mut list, None);
1497 with_font(|fs| {
1498 assert!(fs.line_cache.len() <= LINE_CACHE_LIMIT, "超限后应回收到上限内");
1499 assert!(fs.line_cache.len() >= LINE_CACHE_TARGET, "LRU 只应淘汰最旧 1/4");
1500 assert!(fs.line_cache.contains_key(&hot_key), "刚访问过的热条目不应被淘汰");
1501 assert!(!fs.line_cache.contains_key(&oldest_key), "最久未访问的条目应被淘汰");
1502 fs.line_cache.clear();
1503 });
1504 }
1505
1506 #[test]
1508 fn paint_rebuilds_evicted_raster_glyphs() {
1509 let mut first = PaintList::new();
1510 paint_text_line("raster-rebuild-test", 18.0, Color::WHITE, Point::ZERO, &mut first, None);
1511 assert!(!first.commands.is_empty());
1512
1513 with_font(|fs| {
1514 fs.raster_cache.clear();
1515 fs.raster_cache_bytes = 0;
1516 });
1517
1518 let mut second = PaintList::new();
1519 paint_text_line("raster-rebuild-test", 18.0, Color::WHITE, Point::ZERO, &mut second, None);
1520 assert_eq!(first.commands.len(), second.commands.len(), "位图淘汰后应重建 glyph,而不是丢字");
1521 assert!(!second.commands.is_empty());
1522 }
1523
1524 #[test]
1528 fn zero_size_glyphs_are_cached_not_rerasterized() {
1529 with_font(|fs| {
1530 fs.raster_cache.clear();
1531 fs.raster_cache_bytes = 0;
1532 let _ = shape_text(fs, "a b c", 13.0, None, DEFAULT_FONT_STACK);
1533 let cached = fs.raster_cache.len();
1534 assert!(
1535 fs.raster_cache.values().any(|g| g.width == 0 && g.height == 0),
1536 "空格等零尺寸 glyph 必须缓存占位,不能每次重栅格化"
1537 );
1538 let _ = shape_text(fs, "a b c d", 13.0, None, DEFAULT_FONT_STACK);
1541 assert_eq!(fs.raster_cache.len(), cached + 1, "除新字符外不得新增栅格化条目");
1542 fs.raster_cache.clear();
1543 fs.raster_cache_bytes = 0;
1544 });
1545 }
1546
1547 #[test]
1549 fn raster_cache_trims_to_budget() {
1550 with_font(|fs| {
1551 fs.raster_cache.clear();
1552 fs.raster_cache_bytes = 0;
1553 let chunk = vec![0u8; 8 * 1024 * 1024];
1554 for i in 0..5u16 {
1555 insert_raster_glyph(
1556 fs,
1557 GlyphKey::new(0, i, 0, 0, 0, 0),
1558 RasterGlyph { data: chunk.clone(), width: 2048, height: 1024, left: 0, top: 0, last_used: 0 },
1559 );
1560 }
1561 assert!(fs.raster_cache_bytes <= RASTER_CACHE_TARGET_BYTES, "应回收到目标水位");
1563 assert_eq!(fs.raster_cache.len(), 3, "LRU 应保留最近的条目");
1564 assert!(!fs.raster_cache.contains_key(&GlyphKey::new(0, 0, 0, 0, 0, 0)), "最旧条目应被淘汰");
1565 assert!(fs.raster_cache.contains_key(&GlyphKey::new(0, 4, 0, 0, 0, 0)), "最新条目应保留");
1566 fs.raster_cache.clear();
1567 fs.raster_cache_bytes = 0;
1568 });
1569 }
1570
1571 #[test]
1574 fn paint_text_line_dpr_rasterizes_at_physical_resolution() {
1575 fn paint_once(dpr: f32) -> (f32, f32, f32) {
1576 set_text_dpr(dpr);
1577 let mut list = PaintList::new();
1578 let width = paint_text_line("H", 24.0, Color::WHITE, Point::ZERO, &mut list, None);
1579 let (rect_w, uv_span) = match &list.commands[0] {
1580 PaintCommand::TexturedRect { rect, uv, .. } => (rect.width, (uv[2] - uv[0]) * ATLAS_SIZE as f32),
1581 _ => panic!("expected TexturedRect"),
1582 };
1583 set_text_dpr(1.0); (rect_w, uv_span, width)
1585 }
1586
1587 let (w1, span1, ret1) = paint_once(1.0);
1588 let (w2, span2, ret2) = paint_once(2.0);
1589
1590 assert!((w1 - w2).abs() <= 2.0, "rect 逻辑尺寸应 dpr 无关(允许取整 ≤2px): dpr1={w1} vs dpr2={w2}");
1592 assert!((ret1 - ret2).abs() < 0.5 && ret1 > 0.0, "返回宽度(逻辑)应 dpr 无关: {ret1} vs {ret2}");
1593 assert!(span2 > span1 * 1.5, "atlas 位图分辨率应随 dpr 变大: dpr1={span1}px vs dpr2={span2}px");
1594 let mw = measure_text_width("H", 24.0);
1595 assert!((ret1 - mw).abs() < 0.5, "paint 宽度应与 measure 一致(TextField 光标定位依赖): {ret1} vs {mw}");
1596 }
1597}
1598
1599pub fn is_rtl_text(text: &str) -> bool {
1605 for ch in text.chars() {
1606 let code = ch as u32;
1607 let rtl = matches!(
1608 code,
1609 0x0590..=0x05FF | 0x0600..=0x06FF | 0x0700..=0x074F | 0x0750..=0x077F | 0x0780..=0x07BF | 0x0860..=0x086F | 0x08A0..=0x08FF | 0xFB1D..=0xFB4F | 0xFB50..=0xFDFF | 0xFE70..=0xFEFF );
1620 if rtl {
1621 return true;
1622 }
1623 if ch.is_alphabetic() {
1624 return false;
1625 }
1626 }
1627 false
1628}
1629
1630pub fn mirror_carets_for_rtl(widths: &[f32]) -> Vec<f32> {
1636 let chars = widths.len().saturating_sub(1);
1637 if chars == 0 {
1638 return widths.to_vec();
1639 }
1640 let mut carets = vec![0.0f32; chars + 1];
1641 carets[0] = widths[chars];
1642 carets[1..=chars].copy_from_slice(&widths[..chars]);
1643 carets
1644}
1645
1646pub fn measure_caret_positions(text: &str, size_px: f32, font_stack: &str) -> Vec<f32> {
1648 let widths = measure_char_prefix_widths(text, size_px, font_stack);
1649 if is_rtl_text(text) {
1650 mirror_carets_for_rtl(&widths)
1651 } else {
1652 widths
1653 }
1654}
1655
1656pub fn nearest_caret_index(carets: &[f32], x: f32) -> usize {
1658 carets
1659 .iter()
1660 .enumerate()
1661 .min_by(|(ia, a), (ib, b)| (**a - x).abs().total_cmp(&(**b - x).abs()).then_with(|| ia.cmp(ib)))
1662 .map(|(index, _)| index)
1663 .unwrap_or(0)
1664}
1665
1666#[cfg(test)]
1667mod rtl_tests {
1668 use super::*;
1669
1670 #[test]
1671 fn detects_base_direction() {
1672 assert!(is_rtl_text("مرحبا بالعالم"));
1673 assert!(is_rtl_text("שלום"));
1674 assert!(!is_rtl_text("hello مرحبا")); assert!(!is_rtl_text("123 !?"));
1676 assert!(is_rtl_text("123 مرحبا")); }
1678
1679 #[test]
1680 fn rtl_caret_mirroring_and_nearest_index() {
1681 let widths = [0.0, 10.0, 25.0, 40.0];
1683 let carets = mirror_carets_for_rtl(&widths);
1684 assert_eq!(carets, vec![40.0, 0.0, 10.0, 25.0]);
1685 assert_eq!(nearest_caret_index(&carets, 38.0), 0, "靠近右缘 → 文本起点");
1686 assert_eq!(nearest_caret_index(&carets, 2.0), 1);
1687 assert_eq!(nearest_caret_index(&carets, 24.0), 3, "靠近左缘 → 文本末尾");
1688 assert_eq!(mirror_carets_for_rtl(&[0.0]), vec![0.0]);
1690 assert_eq!(nearest_caret_index(&widths, 12.0), 1);
1691 }
1692}
1693
1694#[derive(Clone, Debug, PartialEq)]
1701pub struct RichTextSpan {
1702 pub text: String,
1703 pub size_px: f32,
1704 pub color: Option<Color>,
1706 pub font_stack: Option<String>,
1708 pub weight: Option<u16>,
1715 pub italic: bool,
1717}
1718
1719impl RichTextSpan {
1720 pub fn new(text: impl Into<String>) -> Self {
1721 Self { text: text.into(), size_px: 15.0, color: None, font_stack: None, weight: None, italic: false }
1722 }
1723
1724 pub fn with_size(mut self, size_px: f32) -> Self {
1725 self.size_px = size_px;
1726 self
1727 }
1728
1729 pub fn with_color(mut self, color: Color) -> Self {
1730 self.color = Some(color);
1731 self
1732 }
1733
1734 pub fn with_font_stack(mut self, stack: impl Into<String>) -> Self {
1735 self.font_stack = Some(stack.into());
1736 self
1737 }
1738
1739 pub fn with_weight(mut self, weight: u16) -> Self {
1741 self.weight = Some(weight.clamp(1, 1000));
1742 self
1743 }
1744
1745 pub fn bold(self) -> Self {
1747 self.with_weight(700)
1748 }
1749
1750 pub fn with_italic(mut self, italic: bool) -> Self {
1751 self.italic = italic;
1752 self
1753 }
1754
1755 pub fn italic(self) -> Self {
1757 self.with_italic(true)
1758 }
1759}
1760
1761pub type InlinePainter = std::rc::Rc<dyn Fn(&mut PaintList, Rect)>;
1763
1764#[derive(Clone)]
1766pub struct InlineItem {
1767 pub width: f32,
1768 pub height: f32,
1769 pub painter: InlinePainter,
1770}
1771
1772impl InlineItem {
1773 pub fn new(width: f32, height: f32, painter: impl Fn(&mut PaintList, Rect) + 'static) -> Self {
1774 Self { width, height, painter: std::rc::Rc::new(painter) }
1775 }
1776}
1777
1778impl std::fmt::Debug for InlineItem {
1779 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1780 f.debug_struct("InlineItem").field("width", &self.width).field("height", &self.height).finish()
1781 }
1782}
1783
1784impl PartialEq for InlineItem {
1785 fn eq(&self, other: &Self) -> bool {
1786 self.width == other.width && self.height == other.height && std::rc::Rc::ptr_eq(&self.painter, &other.painter)
1787 }
1788}
1789
1790#[derive(Clone, Debug, PartialEq)]
1792pub enum RichItem {
1793 Text(RichTextSpan),
1794 Inline(InlineItem),
1795}
1796
1797#[derive(Clone, Debug, PartialEq)]
1799pub struct RichText {
1800 text: std::rc::Rc<str>,
1801 spans: Vec<RichTextSpan>,
1802 ranges: Vec<(usize, usize)>,
1803 inlines: Vec<(usize, InlineItem)>,
1805}
1806
1807impl RichText {
1808 pub fn new(spans: Vec<RichTextSpan>) -> Self {
1809 Self::from_items(spans.into_iter().map(RichItem::Text).collect())
1810 }
1811
1812 pub fn from_items(items: Vec<RichItem>) -> Self {
1813 let mut text = String::new();
1814 let mut spans = Vec::new();
1815 let mut ranges = Vec::new();
1816 let mut inlines = Vec::new();
1817 for item in items {
1818 match item {
1819 RichItem::Text(span) => {
1820 let start = text.len();
1821 text.push_str(&span.text);
1822 spans.push(span);
1823 ranges.push((start, text.len()));
1824 }
1825 RichItem::Inline(inline) => inlines.push((text.len(), inline)),
1826 }
1827 }
1828 Self { text: text.into(), spans, ranges, inlines }
1829 }
1830
1831 pub fn plain_text(&self) -> &str {
1833 &self.text
1834 }
1835
1836 pub fn spans(&self) -> &[RichTextSpan] {
1837 &self.spans
1838 }
1839
1840 pub fn is_empty(&self) -> bool {
1841 self.text.is_empty() && self.inlines.is_empty()
1842 }
1843}
1844
1845struct RichShapedGlyph {
1846 raster_key: GlyphKey,
1847 glyph_id: u16,
1848 x: f32,
1849 span: u16,
1851}
1852
1853struct RichShapedRun {
1854 glyphs: Vec<RichShapedGlyph>,
1855 baseline_y: f32,
1856 ascent: f32,
1858 font: parley::FontData,
1861 norm_coords: std::rc::Rc<[swash::NormalizedCoord]>,
1862 raster_size: f32,
1863}
1864
1865struct RichInlineBox {
1867 id: u16,
1869 x: f32,
1870 y: f32,
1871 width: f32,
1872 height: f32,
1873 line_baseline: f32,
1875}
1876
1877struct RichShapedLine {
1878 runs: Vec<RichShapedRun>,
1879 inline_boxes: Vec<RichInlineBox>,
1880 max_x: f32,
1881 max_y: f32,
1882}
1883
1884#[derive(Clone, PartialEq, Eq, Hash)]
1885struct RichCacheKey {
1886 text: std::rc::Rc<str>,
1887 styles: Vec<(usize, usize, u32, u64)>,
1889 inlines: Vec<(usize, u32, u32)>,
1891 width_bits: Option<u32>,
1892 dpr_bits: u32,
1893}
1894
1895struct RichCacheEntry {
1896 line: std::rc::Rc<RichShapedLine>,
1897 last_used: u64,
1898}
1899
1900fn rich_style_signature(rich: &RichText) -> Vec<(usize, usize, u32, u64)> {
1901 rich.ranges
1902 .iter()
1903 .zip(&rich.spans)
1904 .map(|((start, end), span)| {
1905 let stack = span.font_stack.as_deref().unwrap_or(DEFAULT_FONT_STACK);
1906 let mut h = DefaultHasher::new();
1907 stack.hash(&mut h);
1908 span.weight.unwrap_or(400).hash(&mut h);
1911 span.italic.hash(&mut h);
1912 (*start, *end, span.size_px.max(1.0).to_bits(), h.finish())
1913 })
1914 .collect()
1915}
1916
1917fn span_index_at(ranges: &[(usize, usize)], byte: usize) -> u16 {
1918 ranges.iter().position(|(start, end)| byte >= *start && byte < *end).unwrap_or(0) as u16
1919}
1920
1921fn shape_rich(fs: &mut FontState, rich: &RichText, max_width_px: Option<f32>) -> std::rc::Rc<RichShapedLine> {
1923 let dpr = text_dpr();
1924 let key = RichCacheKey {
1925 text: std::rc::Rc::clone(&rich.text),
1926 styles: rich_style_signature(rich),
1927 inlines: rich
1928 .inlines
1929 .iter()
1930 .map(|(index, inline)| (*index, inline.width.to_bits(), inline.height.to_bits()))
1931 .collect(),
1932 width_bits: max_width_px.map(|w| w.to_bits()),
1933 dpr_bits: dpr.to_bits(),
1934 };
1935 if let Some(entry) = fs.rich_cache.get_mut(&key) {
1936 fs.rich_clock += 1;
1937 entry.last_used = fs.rich_clock;
1938 return std::rc::Rc::clone(&entry.line);
1939 }
1940
1941 let text: &str = &rich.text;
1942 let mut builder = fs.layout_cx.ranged_builder(&mut fs.font_cx, text, 1.0, true);
1943 builder.push_default(parley::StyleProperty::FontSize(15.0));
1944 builder.push_default(parley::StyleProperty::LineHeight(parley::LineHeight::FontSizeRelative(1.2)));
1946 builder.push_default(parley::StyleProperty::FontFamily(parley::FontFamily::Source(std::borrow::Cow::Borrowed(
1947 DEFAULT_FONT_STACK,
1948 ))));
1949 builder.push_default(parley::StyleProperty::WordBreak(parley::WordBreak::KeepAll));
1950 builder.push_default(parley::StyleProperty::OverflowWrap(parley::OverflowWrap::Anywhere));
1951 for ((start, end), span) in rich.ranges.iter().zip(&rich.spans) {
1952 if span.size_px > 0.0 {
1953 builder.push(parley::StyleProperty::FontSize(span.size_px), *start..*end);
1954 }
1955 if let Some(stack) = &span.font_stack {
1956 builder.push(
1957 parley::StyleProperty::FontFamily(parley::FontFamily::Source(std::borrow::Cow::Borrowed(stack))),
1958 *start..*end,
1959 );
1960 }
1961 if let Some(weight) = span.weight {
1963 builder.push(parley::StyleProperty::FontWeight(parley::FontWeight::new(weight as f32)), *start..*end);
1964 }
1965 if span.italic {
1966 builder.push(parley::StyleProperty::FontStyle(parley::FontStyle::Italic), *start..*end);
1967 }
1968 }
1969 for (id, (index, inline)) in rich.inlines.iter().enumerate() {
1970 builder.push_inline_box(parley::InlineBox {
1971 id: id as u64,
1972 index: *index,
1973 width: inline.width,
1974 height: inline.height,
1975 kind: parley::InlineBoxKind::InFlow,
1983 baseline: None,
1984 vertical_align: parley::VerticalAlign::BASELINE,
1985 });
1986 }
1987 let mut layout: parley::Layout<()> = builder.build(text);
1988 let wrap_opt = max_width_px.filter(|w| *w > 0.0);
1989 layout.break_all_lines(wrap_opt);
1990 layout.align(parley::Alignment::Start, parley::AlignmentOptions::default());
1991
1992 let mut runs = Vec::new();
1993 let mut inline_boxes = Vec::new();
1994 let mut max_x = 0.0f32;
1995 let mut max_y = 0.0f32;
1996 for line in layout.lines() {
1997 let line_m = line.metrics();
1998 let baseline_y = line_m.baseline * dpr;
1999 for item in line.items() {
2000 let parley::PositionedLayoutItem::GlyphRun(gr) = item else {
2001 if let parley::PositionedLayoutItem::InlineBox(b) = item {
2002 inline_boxes.push(RichInlineBox {
2003 id: b.id as u16,
2004 x: b.x,
2005 y: b.y,
2006 width: b.width,
2007 height: b.height,
2008 line_baseline: baseline_y,
2009 });
2010 max_x = max_x.max((b.x + b.width) * dpr);
2011 max_y = max_y.max((b.y + b.height) * dpr);
2012 }
2013 continue;
2014 };
2015 let run_metrics = gr.run().font_metrics();
2016 let ascent = run_metrics.ascent * dpr;
2017 let descent = run_metrics.descent * dpr;
2018 let font_size_phys = gr.run().font_size() * dpr;
2019 let font_blob_id = gr.run().font().data.id() as usize;
2020 let norm_coords: std::rc::Rc<[swash::NormalizedCoord]> =
2023 gr.run().normalized_coords().iter().map(|c| c.to_bits()).collect();
2024 let run_font = gr.run().font().clone();
2025 let mut pen_x = gr.offset();
2026 let mut run_glyphs = Vec::new();
2027 for cluster in gr.run().visual_clusters() {
2028 let cluster_byte = cluster.text_range().start;
2029 let span = span_index_at(&rich.ranges, cluster_byte);
2030 for g in cluster.glyphs() {
2031 let glyph_id = match narrow_glyph_id(g.id) {
2034 Some(id) => id,
2035 None => {
2036 log::warn!("mgui-text: glyph id {} 超出 swash 的 u16 范围,跳过该字形", g.id);
2037 pen_x += g.advance;
2038 continue;
2039 }
2040 };
2041 let raster_key = GlyphKey::new(
2042 raster_font_id(font_blob_id, &norm_coords),
2043 glyph_id,
2044 font_size_phys.to_bits(),
2045 0,
2046 0,
2047 0,
2048 );
2049 if !fs.raster_cache.contains_key(&raster_key) {
2050 if let Some(rg) =
2051 rasterize_one_glyph(&run_font, font_size_phys, glyph_id, &norm_coords, &mut fs.scale_cx)
2052 {
2053 insert_raster_glyph(fs, raster_key, rg);
2054 }
2055 }
2056 let gx = pen_x + g.x;
2057 run_glyphs.push(RichShapedGlyph { raster_key, glyph_id, x: gx * dpr, span });
2058 max_x = max_x.max((gx + g.advance) * dpr);
2059 max_y = max_y.max(baseline_y + descent);
2060 pen_x += g.advance;
2061 }
2062 }
2063 if !run_glyphs.is_empty() {
2064 runs.push(RichShapedRun {
2065 glyphs: run_glyphs,
2066 baseline_y,
2067 ascent,
2068 font: run_font,
2069 norm_coords,
2070 raster_size: font_size_phys,
2071 });
2072 }
2073 }
2074 }
2075 if max_y == 0.0 {
2076 max_y = rich.spans.iter().map(|s| s.size_px).fold(15.0, f32::max) * 1.2 * dpr;
2077 }
2078
2079 let line = std::rc::Rc::new(RichShapedLine { runs, inline_boxes, max_x, max_y });
2080 if fs.rich_cache.len() >= LINE_CACHE_LIMIT {
2081 fs.rich_cache.clear();
2082 }
2083 fs.rich_clock += 1;
2084 fs.rich_cache.insert(key, RichCacheEntry { line: std::rc::Rc::clone(&line), last_used: fs.rich_clock });
2085 line
2086}
2087
2088pub fn rich_text_size(rich: &RichText, max_width: Option<f32>) -> Size {
2090 if rich.is_empty() {
2091 return Size::ZERO;
2092 }
2093 with_font(|fs| {
2094 let dpr = text_dpr();
2095 let shaped = shape_rich(fs, rich, max_width);
2096 let first_baseline = shaped.runs.first().map(|r| r.baseline_y);
2097 let (anchor, fallback_h) = match first_baseline {
2098 Some(baseline) => {
2099 let first_ascent =
2101 shaped.runs.iter().filter(|r| r.baseline_y == baseline).map(|r| r.ascent).fold(0.0f32, f32::max);
2102 let inline_top = shaped
2103 .inline_boxes
2104 .iter()
2105 .filter(|b| b.line_baseline == baseline)
2106 .map(|b| b.y * dpr)
2107 .fold(f32::INFINITY, f32::min);
2108 ((baseline - first_ascent).min(inline_top), 0.0)
2110 }
2111 None => (0.0, shaped.max_y),
2112 };
2113 let height = if shaped.max_y > anchor { (shaped.max_y - anchor) / dpr } else { fallback_h / dpr };
2114 Size::new(shaped.max_x / dpr, height)
2115 })
2116}
2117
2118#[derive(Clone, Debug, PartialEq)]
2120pub struct RichTextLayout {
2121 pub size: Size,
2122 pub inline_rects: Vec<Rect>,
2123}
2124
2125pub fn rich_text_layout(rich: &RichText, max_width: Option<f32>) -> RichTextLayout {
2127 if rich.is_empty() {
2128 return RichTextLayout { size: Size::ZERO, inline_rects: Vec::new() };
2129 }
2130 with_font(|fs| {
2131 let dpr = text_dpr();
2132 let shaped = shape_rich(fs, rich, max_width);
2133 let first_baseline = shaped.runs.first().map(|r| r.baseline_y);
2134 let anchor = match first_baseline {
2135 Some(baseline) => {
2136 let first_ascent =
2137 shaped.runs.iter().filter(|r| r.baseline_y == baseline).map(|r| r.ascent).fold(0.0f32, f32::max);
2138 let inline_top = shaped
2139 .inline_boxes
2140 .iter()
2141 .filter(|b| b.line_baseline == baseline)
2142 .map(|b| b.y * dpr)
2143 .fold(f32::INFINITY, f32::min);
2144 (baseline - first_ascent).min(inline_top)
2145 }
2146 None => 0.0,
2147 };
2148 let height = if shaped.max_y > anchor { (shaped.max_y - anchor) / dpr } else { 0.0 };
2149 let mut inline_rects = vec![Rect::new(0.0, 0.0, 0.0, 0.0); rich.inlines.len()];
2150 for b in &shaped.inline_boxes {
2151 if let Some(slot) = inline_rects.get_mut(b.id as usize) {
2152 *slot = Rect::new(b.x, (b.y * dpr - anchor) / dpr, b.width, b.height);
2153 }
2154 }
2155 RichTextLayout { size: Size::new(shaped.max_x / dpr, height), inline_rects }
2156 })
2157}
2158
2159pub fn paint_rich_text(rich: &RichText, offset: Point, list: &mut PaintList, max_width: Option<f32>) -> f32 {
2161 paint_rich_text_with_default(rich, Color::WHITE, offset, list, max_width)
2162}
2163
2164pub fn paint_rich_text_with_default(
2166 rich: &RichText,
2167 default_color: Color,
2168 offset: Point,
2169 list: &mut PaintList,
2170 max_width: Option<f32>,
2171) -> f32 {
2172 if rich.is_empty() {
2173 return 0.0;
2174 }
2175 with_font(|fs| {
2176 let dpr = text_dpr();
2177 let shaped = shape_rich(fs, rich, max_width);
2178 let Some(first_run) = shaped.runs.first() else {
2179 return 0.0;
2180 };
2181 let first_baseline = first_run.baseline_y;
2182 let first_ascent =
2183 shaped.runs.iter().filter(|r| r.baseline_y == first_baseline).map(|r| r.ascent).fold(0.0f32, f32::max);
2184 let inline_top = shaped
2185 .inline_boxes
2186 .iter()
2187 .filter(|b| b.line_baseline == first_baseline)
2188 .map(|b| b.y * dpr)
2189 .fold(f32::INFINITY, f32::min);
2190 let anchor = (first_baseline - first_ascent).min(inline_top);
2191
2192 for run in &shaped.runs {
2193 for sg in &run.glyphs {
2194 if !fs.raster_cache.contains_key(&sg.raster_key) {
2195 if let Some(rg) =
2196 rasterize_one_glyph(&run.font, run.raster_size, sg.glyph_id, &run.norm_coords, &mut fs.scale_cx)
2197 {
2198 insert_raster_glyph(fs, sg.raster_key, rg);
2199 }
2200 }
2201 let Some(r) = fs.raster_cache.get_mut(&sg.raster_key) else {
2202 continue;
2203 };
2204 if r.width == 0 || r.height == 0 {
2205 continue;
2206 }
2207 fs.glyph_clock += 1;
2208 r.last_used = fs.glyph_clock;
2209 let entry = fs.atlas.get_or_insert(sg.raster_key, &r.data, r.width, r.height);
2210
2211 let x = offset.x + (sg.x + r.left as f32) / dpr;
2212 let glyph_visual_top = run.baseline_y - r.top as f32;
2213 let y = offset.y + (glyph_visual_top - anchor) / dpr;
2214 let rect = Rect::new(x, y, r.width as f32 / dpr, r.height as f32 / dpr);
2215 let color = rich.spans.get(sg.span as usize).and_then(|s| s.color).unwrap_or(default_color);
2216 list.push(PaintCommand::TexturedRect {
2217 rect,
2218 color,
2219 uv: entry.uv,
2220 texture_id: 0,
2221 mode: mgui_core::paint::TextureMode::Mask,
2222 });
2223 }
2224 }
2225 for b in &shaped.inline_boxes {
2226 if let Some((_, inline)) = rich.inlines.get(b.id as usize) {
2227 let rect = Rect::new(offset.x + b.x, offset.y + b.y - anchor / dpr, b.width, b.height);
2228 (inline.painter)(list, rect);
2229 }
2230 }
2231 shaped.max_x / dpr
2232 })
2233}
2234
2235#[cfg(test)]
2236mod rich_text_tests {
2237 use super::*;
2238
2239 #[test]
2240 fn mixed_styles_measure_and_paint_with_span_colors() {
2241 set_text_dpr(1.0);
2242 let red = Color::from_rgb8(255, 0, 0);
2243 let rich = RichText::new(vec![
2244 RichTextSpan::new("Hello ").with_size(18.0).with_color(Color::WHITE),
2245 RichTextSpan::new("World").with_size(30.0).with_color(red),
2246 ]);
2247 let size = rich_text_size(&rich, None);
2248 assert!(size.width > 0.0, "宽度必须 > 0");
2249 assert!(size.height >= 30.0, "高度应容纳 30px 字号: {size:?}");
2250
2251 let mut list = PaintList::new();
2252 let width = paint_rich_text(&rich, Point::ZERO, &mut list, None);
2253 assert!((width - size.width).abs() < 0.5, "绘制宽度应与测量一致: {width} vs {}", size.width);
2254 let colors: Vec<Color> = list
2255 .commands
2256 .iter()
2257 .filter_map(|c| match c {
2258 PaintCommand::TexturedRect { color, .. } => Some(*color),
2259 _ => None,
2260 })
2261 .collect();
2262 assert!(colors.contains(&Color::WHITE), "应包含第一段白色字形");
2263 assert!(colors.contains(&red), "应包含第二段红色字形");
2264 }
2265
2266 #[test]
2267 fn inline_item_measures_paints_and_sits_on_baseline() {
2268 use std::cell::RefCell;
2269 set_text_dpr(1.0);
2270 let captured: std::rc::Rc<RefCell<Option<Rect>>> = std::rc::Rc::new(RefCell::new(None));
2271 let cap = captured.clone();
2272 let rich = RichText::from_items(vec![
2273 RichItem::Text(RichTextSpan::new("A").with_size(16.0)),
2274 RichItem::Inline(InlineItem::new(30.0, 24.0, move |_list, rect| *cap.borrow_mut() = Some(rect))),
2275 RichItem::Text(RichTextSpan::new("B").with_size(16.0)),
2276 ]);
2277 let size = rich_text_size(&rich, None);
2278 assert!(size.width >= 30.0, "宽度应包含内联项: {size:?}");
2279 assert!(size.height >= 20.0, "高度应容纳内联项: {size:?}");
2280
2281 let mut list = PaintList::new();
2282 let width = paint_rich_text(&rich, Point::new(10.0, 5.0), &mut list, None);
2283 assert!(width >= 30.0);
2284 let rect = captured.borrow().expect("内联项绘制回调应被调用");
2285 assert!((rect.width - 30.0).abs() < 0.01 && (rect.height - 24.0).abs() < 0.01, "{rect:?}");
2286 assert!(rect.x >= 10.0 && rect.y >= 5.0, "内联项应带 offset: {rect:?}");
2287 }
2288
2289 #[test]
2290 fn inline_items_wrap_when_narrow() {
2291 set_text_dpr(1.0);
2292 let rich = RichText::from_items(vec![
2293 RichItem::Inline(InlineItem::new(40.0, 20.0, |_, _| {})),
2294 RichItem::Inline(InlineItem::new(40.0, 20.0, |_, _| {})),
2295 ]);
2296 let one_line = rich_text_size(&rich, None);
2297 let wrapped = rich_text_size(&rich, Some(50.0));
2298 assert!(one_line.width > wrapped.width, "窄宽度应减少行宽: {one_line:?} vs {wrapped:?}");
2299 assert!(
2300 wrapped.height > one_line.height * 1.5,
2301 "两个 40 宽内联项在 50 宽内应换行: {one_line:?} vs {wrapped:?}"
2302 );
2303 }
2304
2305 #[test]
2306 fn soft_wrap_uses_max_width() {
2307 set_text_dpr(1.0);
2308 let rich = RichText::new(vec![RichTextSpan::new("word ".repeat(40)).with_size(16.0)]);
2309 let single = rich_text_size(&rich, None);
2310 let wrapped = rich_text_size(&rich, Some(120.0));
2311 assert!(single.height > 0.0 && wrapped.height > 0.0);
2312 assert!(wrapped.height > single.height * 2.0, "换行后高度应显著增加: {single:?} vs {wrapped:?}");
2313 assert!(wrapped.width <= 130.0, "换行后宽度应受 max_width 约束: {wrapped:?}");
2314 }
2315
2316 #[test]
2327 fn trailing_spaces_hang_instead_of_forming_a_phantom_line() {
2328 set_text_dpr(1.0);
2329 let size = 16.0;
2330 let visible = "aaa bbb";
2331 let text = "aaa bbb ";
2332 let w_visible = measure_text_width(visible, size);
2333 let w_full = measure_text_width(text, size);
2334 assert!(w_full > w_visible + 1.0, "前置条件:尾空格要确实更宽,否则这个用例没有鉴别力");
2335 let max_width = (w_visible + w_full) * 0.5;
2336
2337 let ranges = wrapped_line_ranges(text, size, max_width);
2338 assert_eq!(ranges.len(), 1, "尾空格该挂在行外,不该另起一行:{ranges:?}(max_width={max_width})");
2339 assert_eq!(ranges[0], (0, text.len()), "唯一一行要覆盖全文,包括挂出去的空格");
2340
2341 let h = text_visual_height(text, size, Some(max_width));
2343 let h_visible_only = text_visual_height(visible, size, Some(max_width));
2344 assert!((h - h_visible_only).abs() < 0.5, "多三个尾空格不该改变块高:全文={h} 仅可见={h_visible_only}");
2345 }
2346
2347 #[test]
2348 fn span_builders_set_weight_and_italic() {
2349 assert_eq!(RichTextSpan::new("x").weight, None, "默认不指定字重(跟随 400)");
2350 assert!(!RichTextSpan::new("x").italic);
2351 assert_eq!(RichTextSpan::new("x").bold().weight, Some(700));
2352 assert_eq!(RichTextSpan::new("x").with_weight(500).weight, Some(500));
2353 assert_eq!(RichTextSpan::new("x").with_weight(0).weight, Some(1), "非法值夹紧到 ≥1");
2354 assert!(RichTextSpan::new("x").italic().italic);
2355 assert!(!RichTextSpan::new("x").with_italic(true).with_italic(false).italic);
2356 }
2357
2358 #[test]
2359 fn bold_span_is_wider_and_cache_keeps_weights_apart() {
2360 set_text_dpr(1.0);
2361 let text = "Handgloves 字重";
2362 let regular = RichText::new(vec![RichTextSpan::new(text).with_size(20.0)]);
2363 let bold = RichText::new(vec![RichTextSpan::new(text).with_size(20.0).bold()]);
2364
2365 let w_regular = rich_text_size(®ular, None).width;
2366 let w_bold = rich_text_size(&bold, None).width;
2367 assert!(w_bold > w_regular + 0.5, "粗体字面应比常规更宽: regular={w_regular} bold={w_bold}");
2368 assert!((rich_text_size(®ular, None).width - w_regular).abs() < 0.01, "缓存不能把粗体轮廓复用给常规 span");
2370
2371 let mut list = PaintList::new();
2372 let painted = paint_rich_text(&bold, Point::ZERO, &mut list, None);
2373 assert!((painted - w_bold).abs() < 0.5, "绘制宽度应与测量一致: {painted} vs {w_bold}");
2374 let glyphs = list.commands.iter().filter(|c| matches!(c, PaintCommand::TexturedRect { .. })).count();
2375 assert!(glyphs > 4, "粗体也应画出成片字形,实际 {glyphs}");
2376 }
2377
2378 #[test]
2379 fn italic_span_paints_without_changing_line_box() {
2380 set_text_dpr(1.0);
2381 let text = "Italic style";
2382 let regular = RichText::new(vec![RichTextSpan::new(text).with_size(18.0)]);
2383 let italic = RichText::new(vec![RichTextSpan::new(text).with_size(18.0).italic()]);
2384 let mut list = PaintList::new();
2385 let painted = paint_rich_text(&italic, Point::ZERO, &mut list, None);
2386 let glyphs = list.commands.iter().filter(|c| matches!(c, PaintCommand::TexturedRect { .. })).count();
2387 assert!(glyphs > 4, "斜体应照常成片绘制,实际 {glyphs}");
2388 let w_italic = rich_text_size(&italic, None).width;
2389 assert!(w_italic > 0.0, "斜体宽度有效: {w_italic}");
2390 assert!((painted - w_italic).abs() < 0.5, "斜体绘制宽度应与测量一致: {painted} vs {w_italic}");
2391 assert!(
2393 w_italic.abs() < rich_text_size(®ular, None).width * 2.0,
2394 "斜体宽度应与常规同量级: italic={w_italic}"
2395 );
2396 }
2397
2398 #[test]
2399 fn raster_font_id_folds_variation_coords() {
2400 assert_eq!(raster_font_id(42, &[]), 42);
2402 let a: [swash::NormalizedCoord; 1] = [1];
2403 let b: [swash::NormalizedCoord; 1] = [2];
2404 let coords_a: &[swash::NormalizedCoord] = &a;
2405 let coords_b: &[swash::NormalizedCoord] = &b;
2406 assert_ne!(raster_font_id(42, coords_a), raster_font_id(42, coords_b), "不同可变轴坐标必须是不同栅格身份");
2407 assert_eq!(raster_font_id(42, coords_a), raster_font_id(42, coords_a), "同坐标必须稳定(缓存命中)");
2408 assert_ne!(raster_font_id(42, coords_a), raster_font_id(43, coords_a), "不同 blob 也必须区分");
2409 }
2410}
2411
2412#[cfg(test)]
2417mod multiline_regression {
2418 use super::*;
2419
2420 #[test]
2422 fn multiline_text_lines_have_distinct_y() {
2423 let mut list = PaintList::new();
2424 paint_text_line("第一行AAA\n第二行BBB", 20.0, Color::WHITE, Point::new(50.0, 100.0), &mut list, None);
2425 let ys: Vec<f32> = list
2426 .commands
2427 .iter()
2428 .filter_map(|c| match c {
2429 PaintCommand::TexturedRect { rect, .. } => Some((rect.y * 10.0).round() / 10.0),
2430 _ => None,
2431 })
2432 .collect();
2433 assert!(!ys.is_empty(), "应画出 glyph");
2434 let y0 = ys[0];
2435 assert!(ys.iter().any(|&y| (y - y0).abs() > 20.0), "多行文本各行 y 必须拉开,实际全部≈{}: {:?}", y0, ys);
2436 }
2437
2438 #[test]
2440 fn wrapped_text_lines_have_distinct_y() {
2441 let mut list = PaintList::new();
2442 paint_text_line(
2444 "第一行文本内容比较长需要折行",
2445 20.0,
2446 Color::WHITE,
2447 Point::new(0.0, 0.0),
2448 &mut list,
2449 Some(60.0),
2450 );
2451 let ys: Vec<f32> = list
2452 .commands
2453 .iter()
2454 .filter_map(|c| match c {
2455 PaintCommand::TexturedRect { rect, .. } => Some((rect.y * 10.0).round() / 10.0),
2456 _ => None,
2457 })
2458 .collect();
2459 let y0 = ys[0];
2460 assert!(ys.iter().any(|&y| (y - y0).abs() > 20.0), "soft-wrap 多行 y 必须拉开,实际全部≈{}: {:?}", y0, ys);
2461 }
2462}