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
106impl Atlas {
107 pub fn new(width: u32, height: u32) -> Self {
108 Self {
109 width,
110 height,
111 next_x: 0,
112 next_y: 0,
113 row_height: 0,
114 pixels: vec![0; (width * height) as usize],
115 entries: HashMap::new(),
116 dirty: false,
117 dirty_rows: None,
118 generation: 1,
119 }
120 }
121
122 fn expand_2x(&mut self) {
125 let new_w = (self.width * 2).min(MAX_ATLAS_SIZE);
126 let new_h = (self.height * 2).min(MAX_ATLAS_SIZE);
127 if new_w == self.width && new_h == self.height {
128 return; }
130 let old_w = self.width;
131 let old_h = self.height;
132 let new_size = (new_w * new_h) as usize;
133 let mut new_pixels = vec![0u8; new_size];
134 for row in 0..old_h as usize {
136 let src_start = row * old_w as usize;
137 let dst_start = row * new_w as usize;
138 new_pixels[dst_start..dst_start + old_w as usize]
139 .copy_from_slice(&self.pixels[src_start..src_start + old_w as usize]);
140 }
141 self.pixels = new_pixels;
142 let scale_u = old_w as f32 / new_w as f32; let scale_v = old_h as f32 / new_h as f32;
145 for entry in self.entries.values_mut() {
146 entry.uv[0] *= scale_u;
147 entry.uv[1] *= scale_v;
148 entry.uv[2] *= scale_u;
149 entry.uv[3] *= scale_v;
150 }
151 self.width = new_w;
152 self.height = new_h;
153 self.dirty = true;
154 self.dirty_rows = Some((0, new_h));
155 self.generation += 1;
156 mgui_core::element::request_full_repaint();
158 }
159
160 fn clear_atlas(&mut self) {
163 self.entries.clear();
164 self.pixels.fill(0);
165 self.next_x = 0;
166 self.next_y = 0;
167 self.row_height = 0;
168 self.dirty = true;
169 self.dirty_rows = Some((0, self.height));
170 self.generation += 1;
171 mgui_core::element::request_full_repaint();
172 }
173
174 pub fn get_or_insert(&mut self, key: GlyphKey, bitmap: &[u8], w: u32, h: u32) -> AtlasEntry {
178 if let Some(&e) = self.entries.get(&key) {
179 return e;
180 }
181 let alloc_w = w + ATLAS_PADDING * 2;
183 let alloc_h = h + ATLAS_PADDING * 2;
184 if self.next_x + alloc_w > self.width {
186 self.next_x = 0;
187 self.next_y += self.row_height;
188 self.row_height = 0;
189 }
190 if self.next_y + alloc_h > self.height {
191 if self.width >= MAX_ATLAS_SIZE && self.height >= MAX_ATLAS_SIZE {
193 self.clear_atlas();
194 } else {
195 self.expand_2x();
196 }
197 return self.get_or_insert(key, bitmap, w, h);
199 }
200 let dst_x = self.next_x + ATLAS_PADDING;
201 let dst_y = self.next_y + ATLAS_PADDING;
202
203 for row in 0..h {
205 let src_start = (row * w) as usize;
206 let src_end = src_start + w as usize;
207 let dst_row = (dst_y + row) as usize * self.width as usize + dst_x as usize;
208 self.pixels[dst_row..dst_row + w as usize].copy_from_slice(&bitmap[src_start..src_end]);
209 }
210
211 let u0 = dst_x as f32 / self.width as f32;
213 let v0 = dst_y as f32 / self.height as f32;
214 let u1 = (dst_x + w) as f32 / self.width as f32;
215 let v1 = (dst_y + h) as f32 / self.height as f32;
216
217 let entry = AtlasEntry { uv: [u0, v0, u1, v1], width: w, height: h };
218 self.entries.insert(key, entry);
219 self.next_x += alloc_w;
220 if alloc_h > self.row_height {
221 self.row_height = alloc_h;
222 }
223 self.mark_rows_written(dst_y, h);
225 self.generation += 1;
226 entry
227 }
228
229 fn mark_rows_written(&mut self, y: u32, h: u32) {
231 self.dirty = true;
232 let end = (y + h).min(self.height);
233 self.dirty_rows = Some(match self.dirty_rows {
234 Some((top, bottom)) => (top.min(y), bottom.max(end)),
235 None => (y, end),
236 });
237 }
238
239 pub fn pixels(&self) -> &[u8] {
241 &self.pixels
242 }
243
244 #[allow(dead_code)]
246 pub fn glyph_count(&self) -> usize {
247 self.entries.len()
248 }
249
250 pub fn is_dirty(&self) -> bool {
252 self.dirty
253 }
254
255 pub fn clear_dirty(&mut self) {
257 self.dirty = false;
258 self.dirty_rows = None;
259 }
260}
261
262#[derive(Clone)]
268struct RasterGlyph {
269 data: Vec<u8>,
270 width: u32,
271 height: u32,
272 left: i32,
274 top: i32,
275 last_used: u64,
277}
278
279type LineCacheKey = (TextKey, u32, Option<u32>, u64);
282
283struct LineCacheEntry {
285 line: std::rc::Rc<ShapedLine>,
286 last_used: u64,
287}
288
289pub struct FontState {
291 pub font_cx: parley::FontContext,
292 pub layout_cx: parley::LayoutContext<()>,
293 pub scale_cx: swash::scale::ScaleContext,
294 pub atlas: Atlas,
295 raster_cache: HashMap<GlyphKey, RasterGlyph>,
297 raster_cache_bytes: usize,
299 line_cache: HashMap<LineCacheKey, LineCacheEntry>,
306 rich_cache: HashMap<RichCacheKey, RichCacheEntry>,
308 rich_clock: u64,
310 line_clock: u64,
312 glyph_clock: u64,
314 pub shape_calls: usize,
316}
317
318impl FontState {
319 fn new() -> Self {
320 Self {
321 font_cx: parley::FontContext::new(),
322 layout_cx: parley::LayoutContext::<()>::new(),
323 scale_cx: swash::scale::ScaleContext::new(),
324 atlas: Atlas::new(ATLAS_SIZE, ATLAS_SIZE),
325 raster_cache: HashMap::new(),
326 raster_cache_bytes: 0,
327 line_cache: HashMap::new(),
328 rich_cache: HashMap::new(),
329 rich_clock: 0,
330 line_clock: 0,
331 glyph_clock: 0,
332 shape_calls: 0,
333 }
334 }
335}
336
337thread_local! {
338 static FONT_STATE: RefCell<Option<FontState>> = const { RefCell::new(None) }; static TEXT_DPR: std::cell::Cell<f32> = const { std::cell::Cell::new(1.0) };
344}
345
346pub fn set_text_dpr(dpr: f32) {
348 TEXT_DPR.with(|c| c.set(if dpr > 0.0 { dpr } else { 1.0 }));
349}
350
351fn text_dpr() -> f32 {
352 TEXT_DPR.with(|c| c.get())
353}
354
355pub fn with_font<F, R>(f: F) -> R
357where
358 F: FnOnce(&mut FontState) -> R,
359{
360 FONT_STATE.with(|cell| {
361 let mut opt = cell.borrow_mut();
362 if opt.is_none() {
363 *opt = Some(FontState::new());
364 }
365 f(opt.as_mut().unwrap())
366 })
367}
368
369const LINE_CACHE_LIMIT: usize = 4096;
378
379const LINE_CACHE_TARGET: usize = LINE_CACHE_LIMIT - LINE_CACHE_LIMIT / 4;
381
382fn evict_line_cache_lru(fs: &mut FontState) {
384 if fs.line_cache.len() <= LINE_CACHE_TARGET {
385 return;
386 }
387 let mut by_age: Vec<(u64, LineCacheKey)> = fs.line_cache.iter().map(|(k, v)| (v.last_used, k.clone())).collect();
388 by_age.sort_unstable_by_key(|&(last_used, _)| last_used);
389 let remove = fs.line_cache.len().saturating_sub(LINE_CACHE_TARGET);
390 for (_, key) in by_age.into_iter().take(remove) {
391 fs.line_cache.remove(&key);
392 }
393}
394
395const RASTER_CACHE_BUDGET_BYTES: usize = 32 * 1024 * 1024;
397const RASTER_CACHE_TARGET_BYTES: usize = RASTER_CACHE_BUDGET_BYTES * 3 / 4;
399
400fn insert_raster_glyph(fs: &mut FontState, key: GlyphKey, mut glyph: RasterGlyph) {
402 fs.glyph_clock += 1;
403 glyph.last_used = fs.glyph_clock;
404 let bytes = glyph.data.len();
405 if let Some(old) = fs.raster_cache.insert(key, glyph) {
406 fs.raster_cache_bytes = fs.raster_cache_bytes.saturating_sub(old.data.len());
407 }
408 fs.raster_cache_bytes += bytes;
409 trim_raster_cache(fs);
410}
411
412fn trim_raster_cache(fs: &mut FontState) {
417 if fs.raster_cache_bytes <= RASTER_CACHE_BUDGET_BYTES {
418 return;
419 }
420 let mut candidates: Vec<(u64, GlyphKey, usize)> =
421 fs.raster_cache.iter().map(|(&key, g)| (g.last_used, key, g.data.len())).collect();
422 candidates.sort_unstable_by_key(|&(last_used, _, _)| last_used);
423 for (_, key, bytes) in candidates {
424 if fs.raster_cache_bytes <= RASTER_CACHE_TARGET_BYTES {
425 break;
426 }
427 fs.raster_cache.remove(&key);
428 fs.raster_cache_bytes = fs.raster_cache_bytes.saturating_sub(bytes);
429 }
430}
431
432#[derive(Clone, PartialEq, Eq, Hash)]
438enum TextKey {
439 Owned(String),
440 Shared(std::rc::Rc<str>, Option<(usize, usize)>),
441}
442
443impl TextKey {
444 fn owned(text: &str) -> Self {
445 TextKey::Owned(text.to_string())
446 }
447}
448
449struct ShapedGlyph {
451 raster_key: GlyphKey,
453 glyph_id: u16,
455 x: f32,
457 w: f32,
459 #[allow(dead_code)]
461 y: f32,
462 ascent: f32,
464 descent: f32,
466 cluster: u32,
469}
470
471struct ShapedRun {
473 glyphs: Vec<ShapedGlyph>,
474 baseline_y: f32,
476 font: parley::Font,
478 norm_coords: std::rc::Rc<[swash::NormalizedCoord]>,
480 raster_size: f32,
482}
483
484struct ShapedLine {
486 runs: Vec<ShapedRun>,
487 max_x: f32,
489 #[allow(dead_code)]
491 max_y: f32,
492 visual_lines: Vec<(usize, usize)>,
494}
495
496fn shape_text(
501 fs: &mut FontState,
502 text: &str,
503 raster_px: f32,
504 max_width_px: Option<f32>,
505 font_stack: &str,
506) -> std::rc::Rc<ShapedLine> {
507 shape_text_keyed(fs, text, TextKey::owned(text), raster_px, max_width_px, font_stack)
508}
509
510fn shape_text_keyed(
513 fs: &mut FontState,
514 text: &str,
515 text_key: TextKey,
516 raster_px: f32,
517 max_width_px: Option<f32>,
518 font_stack: &str,
519) -> std::rc::Rc<ShapedLine> {
520 let font_stack_hash = {
521 let mut h = DefaultHasher::new();
522 font_stack.hash(&mut h);
523 h.finish()
524 };
525 let key = (text_key, raster_px.to_bits(), max_width_px.map(|w| w.to_bits()), font_stack_hash);
526 if let Some(entry) = fs.line_cache.get_mut(&key) {
527 fs.line_clock += 1;
528 entry.last_used = fs.line_clock;
529 return std::rc::Rc::clone(&entry.line);
530 }
531
532 fs.shape_calls += 1;
533 let dpr = text_dpr();
534
535 let scale = 1.0f32;
538 let font_size_px = raster_px / dpr;
539
540 let wrap_opt = max_width_px.filter(|&w| w > 0.0);
542
543 let mut builder = fs.layout_cx.ranged_builder(&mut fs.font_cx, text, scale, true);
544 builder.push_default(parley::StyleProperty::FontSize(font_size_px));
545 builder.push_default(parley::StyleProperty::LineHeight(1.2));
546 builder.push_default(parley::StyleProperty::FontStack(parley::FontStack::Source(std::borrow::Cow::Borrowed(
548 font_stack,
549 ))));
550 builder.push_default(parley::StyleProperty::WordBreak(parley::swash::text::WordBreakStrength::KeepAll));
552 builder.push_default(parley::StyleProperty::OverflowWrap(parley::OverflowWrap::Anywhere));
553 let mut layout: parley::Layout<()> = builder.build(text);
554 layout.break_all_lines(wrap_opt);
555 layout.align(wrap_opt, parley::Alignment::Start, parley::AlignmentOptions::default());
556
557 let mut runs = Vec::new();
561 let mut max_x = 0.0f32;
562 let mut max_y = 0.0f32;
563 let mut visual_lines = Vec::new();
564
565 for line in layout.lines() {
566 let mut line_start = usize::MAX;
568 let mut line_end = 0usize;
569 for run in line.runs() {
570 let range = run.text_range();
571 line_start = line_start.min(range.start);
572 line_end = line_end.max(range.end);
573 }
574 visual_lines.push(if line_start == usize::MAX { (0, 0) } else { (line_start, line_end) });
575
576 let line_m = line.metrics();
577 let baseline_y = line_m.baseline * dpr; for item in line.items() {
580 let parley::PositionedLayoutItem::GlyphRun(gr) = item else {
581 continue;
582 };
583
584 let run_metrics = gr.run().metrics();
586 let ascent = run_metrics.ascent * dpr;
587 let descent = run_metrics.descent * dpr;
588 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();
599 let norm_coords: std::rc::Rc<[swash::NormalizedCoord]> = gr.run().normalized_coords().to_vec().into();
601 let run_font = gr.run().font().clone();
602 let mut pen_x = gr.offset();
603 let run_baseline = gr.baseline();
604 for cluster in gr.run().visual_clusters() {
605 let cluster_byte = cluster.text_range().start as u32;
606 for g in cluster.glyphs() {
607 let glyph_id = g.id; let size_bits = font_size_phys.to_bits(); let x_bin = 0; let y_bin = 0;
611 let raster_key = GlyphKey::new(font_blob_id, glyph_id, size_bits, x_bin, y_bin, 0);
612 if !fs.raster_cache.contains_key(&raster_key) {
614 if let Some(rg) =
615 rasterize_one_glyph(&run_font, font_size_phys, glyph_id, &norm_coords, &mut fs.scale_cx)
616 {
617 insert_raster_glyph(fs, raster_key, rg);
618 }
619 }
620 let gx = pen_x + g.x;
621 run_glyphs.push(ShapedGlyph {
622 raster_key,
623 glyph_id,
624 x: gx * dpr, w: g.advance * dpr, y: (run_baseline + g.y) * dpr, ascent,
628 descent,
629 cluster: cluster_byte,
630 });
631 max_x = max_x.max((gx + g.advance) * dpr);
632 max_y = max_y.max(baseline_y + descent);
633 pen_x += g.advance;
634 }
635 }
636
637 if !run_glyphs.is_empty() {
638 runs.push(ShapedRun {
639 glyphs: run_glyphs,
640 baseline_y,
641 font: run_font,
642 norm_coords,
643 raster_size: font_size_phys,
644 });
645 }
646 }
647 }
648
649 if max_y == 0.0 {
651 max_y = raster_px * 1.2;
652 }
653
654 let line = std::rc::Rc::new(ShapedLine { runs, max_x, max_y, visual_lines });
655 if fs.line_cache.len() >= LINE_CACHE_LIMIT {
656 evict_line_cache_lru(fs);
657 }
658 fs.line_clock += 1;
659 let entry = LineCacheEntry { line: std::rc::Rc::clone(&line), last_used: fs.line_clock };
660 fs.line_cache.insert(key, entry);
661 line
662}
663
664#[derive(Clone)]
672pub struct AtlasSnapshot {
673 pub width: u32,
674 pub height: u32,
675 pub dirty: bool,
676 pub dirty_y: (u32, u32),
679 pub pixels: Option<Vec<u8>>,
681}
682
683pub fn atlas_snapshot() -> AtlasSnapshot {
685 with_font(|fs| {
686 let dirty = fs.atlas.is_dirty();
687 let (y0, y1) = if dirty {
688 let (a, b) = fs.atlas.dirty_rows.unwrap_or((0, fs.atlas.height));
689 (a.min(fs.atlas.height), b.min(fs.atlas.height))
690 } else {
691 (0, 0)
692 };
693 let pixels = if dirty {
694 let w = fs.atlas.width as usize;
695 Some(fs.atlas.pixels()[(y0 as usize * w)..(y1 as usize * w)].to_vec())
696 } else {
697 None
698 };
699 AtlasSnapshot { width: fs.atlas.width, height: fs.atlas.height, dirty, dirty_y: (y0, y1), pixels }
700 })
701}
702
703pub fn atlas_clear_dirty() {
705 with_font(|fs| {
706 fs.atlas.clear_dirty();
707 })
708}
709
710pub fn atlas_generation() -> u64 {
712 with_font(|fs| fs.atlas.generation)
713}
714
715#[derive(Clone, Copy, Debug, Default)]
717pub struct AtlasStats {
718 pub width: u32,
719 pub height: u32,
720 pub glyph_count: usize,
721 pub used_height: u32,
723 pub dirty: bool,
724}
725
726pub fn atlas_stats() -> AtlasStats {
727 with_font(|fs| {
728 let atlas = &fs.atlas;
729 AtlasStats {
730 width: atlas.width,
731 height: atlas.height,
732 glyph_count: atlas.entries.len(),
733 used_height: (atlas.next_y + atlas.row_height).min(atlas.height),
734 dirty: atlas.dirty,
735 }
736 })
737}
738
739pub fn with_atlas<R>(f: impl FnOnce(u32, u32, &[u8]) -> R) -> R {
744 with_font(|fs| {
745 let atlas = &fs.atlas;
746 f(atlas.width, atlas.height, &atlas.pixels)
747 })
748}
749
750pub struct TextRenderObject {
755 text: String,
756 size_px: f32,
757 color: Color,
758 max_width: Option<f32>,
760 max_width_explicit: bool,
763 size: Size,
765 element_id: Option<ElementId>,
766}
767
768impl TextRenderObject {
769 pub fn new(text: String, size_px: f32, color: Color) -> Self {
770 Self { text, size_px, color, max_width: None, max_width_explicit: false, size: Size::ZERO, element_id: None }
771 }
772
773 pub fn with_max_width(mut self, max_width: f32) -> Self {
774 self.max_width = Some(max_width);
775 self.max_width_explicit = true;
776 self
777 }
778
779 pub fn set_max_width(&mut self, max_width: Option<f32>) {
780 self.max_width = max_width;
781 self.max_width_explicit = max_width.is_some();
782 }
783
784 fn measure(&self) -> Size {
786 let dpr = text_dpr();
787 let raster_px = self.size_px * dpr;
788 let width = with_font(|fs| {
789 let line = shape_text(fs, &self.text, raster_px, self.max_width, DEFAULT_FONT_STACK);
790 let max_x = line.max_x / dpr;
791 if max_x == 0.0 && !self.text.is_empty() {
792 self.text.chars().count() as f32 * FALLBACK_ADVANCE_X
793 } else {
794 max_x
795 }
796 });
797 let height = text_visual_height(&self.text, self.size_px, self.max_width);
800 Size::new(width, height)
801 }
802}
803
804pub fn measure_text_width(text: &str, size_px: f32) -> f32 {
808 measure_text_width_styled(text, size_px, DEFAULT_FONT_STACK)
809}
810
811pub fn measure_text_width_styled(text: &str, size_px: f32, font_stack: &str) -> f32 {
813 if text.is_empty() {
814 return 0.0;
815 }
816 with_font(|fs| {
817 let dpr = text_dpr();
819 let raster_px = size_px * dpr;
820 let line = shape_text(fs, text, raster_px, None, font_stack);
821 let w = line.max_x / dpr;
822 if w == 0.0 {
823 text.chars().count() as f32 * FALLBACK_ADVANCE_X
824 } else {
825 w
826 }
827 })
828}
829
830pub fn text_visual_height(text: &str, size_px: f32, max_width_px: Option<f32>) -> f32 {
840 text_visual_height_styled(text, size_px, max_width_px, DEFAULT_FONT_STACK)
841}
842
843pub fn text_visual_height_styled(text: &str, size_px: f32, max_width_px: Option<f32>, font_stack: &str) -> f32 {
845 if text.is_empty() {
846 return size_px;
847 }
848 with_font(|fs| {
849 let dpr = text_dpr();
850 let raster_px = size_px * dpr;
851 let line = shape_text(fs, text, raster_px, max_width_px, font_stack);
852
853 if line.runs.is_empty() {
854 return size_px;
855 }
856
857 let first_run = &line.runs[0];
859 let first_ascent = first_run.glyphs.first().map(|g| g.ascent).unwrap_or(raster_px);
860 let first_baseline = first_run.baseline_y;
861 let visual_top = first_baseline - first_ascent;
862
863 let mut visual_bottom = 0.0f32;
865 for run in &line.runs {
866 for sg in &run.glyphs {
867 let bottom = run.baseline_y + sg.descent;
868 visual_bottom = visual_bottom.max(bottom);
869 }
870 }
871
872 if visual_bottom > visual_top {
873 (visual_bottom - visual_top) / dpr
874 } else {
875 size_px
876 }
877 })
878}
879
880pub fn paint_text_line(
886 text: &str,
887 size_px: f32,
888 color: Color,
889 offset: Point,
890 list: &mut PaintList,
891 max_width_px: Option<f32>,
892) -> f32 {
893 paint_text_line_impl(text, TextKey::owned(text), size_px, color, offset, list, max_width_px, DEFAULT_FONT_STACK)
894}
895
896#[allow(clippy::too_many_arguments)]
898pub fn paint_text_line_styled(
899 text: &str,
900 size_px: f32,
901 color: Color,
902 offset: Point,
903 list: &mut PaintList,
904 max_width_px: Option<f32>,
905 font_stack: &str,
906) -> f32 {
907 paint_text_line_impl(text, TextKey::owned(text), size_px, color, offset, list, max_width_px, font_stack)
908}
909
910#[allow(clippy::too_many_arguments)]
915pub fn paint_text_span(
916 text: &std::rc::Rc<str>,
917 range: Option<(usize, usize)>,
918 size_px: f32,
919 color: Color,
920 offset: Point,
921 list: &mut PaintList,
922 max_width_px: Option<f32>,
923) -> f32 {
924 let (start, end) = match range {
925 Some(r) => clamp_char_range(text, r),
926 None => (0, text.len()),
927 };
928 paint_text_line_impl(
929 &text[start..end],
930 TextKey::Shared(std::rc::Rc::clone(text), range),
931 size_px,
932 color,
933 offset,
934 list,
935 max_width_px,
936 DEFAULT_FONT_STACK,
937 )
938}
939
940pub fn text_ascent(text: &str, size_px: f32) -> f32 {
946 if text.is_empty() {
947 return size_px;
948 }
949 with_font(|fs| {
950 let dpr = text_dpr();
951 let shaped = shape_text(fs, text, size_px * dpr, None, DEFAULT_FONT_STACK);
952 first_glyph_ascent(&shaped).map(|a| a / dpr).unwrap_or(size_px)
953 })
954}
955
956pub fn text_span_ascent(text: &std::rc::Rc<str>, range: Option<(usize, usize)>, size_px: f32) -> f32 {
959 let (start, end) = match range {
960 Some(r) => clamp_char_range(text, r),
961 None => (0, text.len()),
962 };
963 if start >= end {
964 return size_px;
965 }
966 with_font(|fs| {
967 let dpr = text_dpr();
968 let shaped = shape_text_keyed(
969 fs,
970 &text[start..end],
971 TextKey::Shared(std::rc::Rc::clone(text), range),
972 size_px * dpr,
973 None,
974 DEFAULT_FONT_STACK,
975 );
976 first_glyph_ascent(&shaped).map(|a| a / dpr).unwrap_or(size_px)
977 })
978}
979
980fn first_glyph_ascent(shaped: &ShapedLine) -> Option<f32> {
981 shaped.runs.first().and_then(|r| r.glyphs.first()).map(|g| g.ascent)
982}
983
984fn clamp_char_range(text: &str, range: (usize, usize)) -> (usize, usize) {
986 let mut start = range.0.min(text.len());
987 let mut end = range.1.min(text.len());
988 while !text.is_char_boundary(start) {
989 start += 1;
990 }
991 while !text.is_char_boundary(end) {
992 end -= 1;
993 }
994 if end < start {
995 end = start;
996 }
997 (start, end)
998}
999
1000#[allow(clippy::too_many_arguments)]
1002fn paint_text_line_impl(
1003 text: &str,
1004 text_key: TextKey,
1005 size_px: f32,
1006 color: Color,
1007 offset: Point,
1008 list: &mut PaintList,
1009 max_width_px: Option<f32>,
1010 font_stack: &str,
1011) -> f32 {
1012 if text.is_empty() {
1013 return 0.0;
1014 }
1015 let width = with_font(|fs| {
1016 let dpr = text_dpr();
1017 let raster_px = size_px * dpr;
1018 let shaped = shape_text_keyed(fs, text, text_key, raster_px, max_width_px, font_stack);
1019
1020 let first_run = match shaped.runs.first() {
1024 Some(r) => r,
1025 None => return 0.0,
1026 };
1027 let first_ascent = first_run.glyphs.first().map(|g| g.ascent).unwrap_or(raster_px);
1028 let first_baseline = first_run.baseline_y;
1029 let anchor = first_baseline - first_ascent; let mut max_x = 0.0f32;
1032 for run in &shaped.runs {
1033 for sg in &run.glyphs {
1034 if !fs.raster_cache.contains_key(&sg.raster_key) {
1037 if let Some(rg) =
1038 rasterize_one_glyph(&run.font, run.raster_size, sg.glyph_id, &run.norm_coords, &mut fs.scale_cx)
1039 {
1040 insert_raster_glyph(fs, sg.raster_key, rg);
1041 }
1042 }
1043 let Some(r) = fs.raster_cache.get_mut(&sg.raster_key) else {
1047 continue;
1048 };
1049 if r.width == 0 || r.height == 0 {
1050 continue;
1051 }
1052 fs.glyph_clock += 1;
1053 r.last_used = fs.glyph_clock;
1054 let entry = fs.atlas.get_or_insert(sg.raster_key, &r.data, r.width, r.height);
1055
1056 let x = offset.x + (sg.x + r.left as f32) / dpr;
1058 let glyph_visual_top = run.baseline_y - r.top as f32;
1063 let y = offset.y + (glyph_visual_top - anchor) / dpr;
1064
1065 let rect = Rect::new(x, y, r.width as f32 / dpr, r.height as f32 / dpr);
1066 list.push(PaintCommand::TexturedRect {
1067 rect,
1068 color,
1069 uv: entry.uv,
1070 texture_id: 0,
1071 mode: mgui_core::paint::TextureMode::Mask,
1072 });
1073 max_x = max_x.max((sg.x + sg.w) / dpr);
1074 }
1075 }
1076 if max_x == 0.0 {
1077 max_x = text.chars().count() as f32 * FALLBACK_ADVANCE_X;
1078 }
1079 max_x
1080 });
1081 width
1082}
1083
1084pub fn wrapped_line_ranges(text: &str, size_px: f32, max_width: f32) -> Vec<(usize, usize)> {
1099 if text.is_empty() {
1100 return vec![(0, 0)];
1101 }
1102 if max_width <= 0.0 {
1103 return vec![(0, text.len())];
1104 }
1105 with_font(|fs| {
1106 let dpr = text_dpr();
1107 let raster_px = size_px * dpr;
1108 let shaped = shape_text(fs, text, raster_px, Some(max_width), DEFAULT_FONT_STACK);
1109 shaped.visual_lines.clone()
1110 })
1111}
1112
1113pub fn measure_char_prefix_widths(text: &str, size_px: f32, font_stack: &str) -> Vec<f32> {
1114 if text.is_empty() {
1115 return vec![0.0];
1116 }
1117 with_font(|fs| {
1118 let dpr = text_dpr();
1119 let raster_px = size_px * dpr;
1120 let shaped = shape_text(fs, text, raster_px, None, font_stack);
1121
1122 let char_count = text.chars().count();
1123 let mut widths = vec![0.0f32; char_count + 1];
1124
1125 let mut byte_x: Vec<(u32, f32)> = Vec::new();
1128 for run in &shaped.runs {
1129 for sg in &run.glyphs {
1130 match byte_x.last_mut() {
1131 Some((b, _)) if *b == sg.cluster => {}
1132 _ => byte_x.push((sg.cluster, sg.x)),
1133 }
1134 }
1135 }
1136
1137 let mut prev = 0.0f32;
1140 let mut bi = 0usize;
1141 for (ci, (byte_pos, _)) in text.char_indices().enumerate() {
1142 while bi < byte_x.len() && byte_x[bi].0 <= byte_pos as u32 {
1143 prev = byte_x[bi].1 / dpr;
1144 bi += 1;
1145 }
1146 widths[ci] = prev;
1147 }
1148 widths[char_count] = shaped.max_x / dpr;
1149 widths
1150 })
1151}
1152
1153fn rasterize_one_glyph(
1155 font: &parley::Font,
1156 font_size: f32,
1157 glyph_id: u16,
1158 norm_coords: &[swash::NormalizedCoord],
1159 scale_cx: &mut swash::scale::ScaleContext,
1160) -> Option<RasterGlyph> {
1161 let bytes = font.data.data();
1163 if bytes.is_empty() {
1164 return None;
1165 }
1166 let font_ref = swash::FontRef::from_index(bytes, font.index as usize)?;
1167 let mut scaler =
1168 scale_cx.builder(font_ref).size(font_size).normalized_coords(norm_coords.iter()).hint(true).build();
1169 let image = swash::scale::Render::new(&[
1170 swash::scale::Source::ColorOutline(0),
1171 swash::scale::Source::ColorBitmap(swash::scale::StrikeWith::BestFit),
1172 swash::scale::Source::Outline,
1173 ])
1174 .render(&mut scaler, glyph_id)?;
1175 if image.placement.width == 0 || image.placement.height == 0 {
1176 return Some(RasterGlyph { data: Vec::new(), width: 0, height: 0, left: 0, top: 0, last_used: 0 });
1181 }
1182 Some(RasterGlyph {
1183 data: image.data.to_vec(),
1184 width: image.placement.width,
1185 height: image.placement.height,
1186 left: image.placement.left,
1187 top: image.placement.top,
1188 last_used: 0,
1189 })
1190}
1191
1192impl RenderObject for TextRenderObject {
1193 fn layout(&mut self, _bc: BoxConstraints, _ctx: &mut LayoutContext) -> Size {
1194 let s = self.measure();
1205 self.size = s;
1206 s
1207 }
1208
1209 fn content_size(&self) -> Size {
1210 self.size
1211 }
1212
1213 fn paint(&self, offset: Point, list: &mut PaintList) {
1214 paint_text_line(&self.text, self.size_px, self.color, offset, list, self.max_width);
1215 }
1216
1217 fn set_element_id(&mut self, id: ElementId) {
1218 self.element_id = Some(id);
1219 }
1220
1221 fn hit_test(&self, position: Point, offset: Point) -> Option<ElementId> {
1222 let r = Rect::new(offset.x, offset.y, self.size.width, self.size.height);
1226 if r.contains(position) {
1227 self.element_id
1228 } else {
1229 None
1230 }
1231 }
1232}
1233
1234#[cfg(test)]
1239mod tests {
1240 use super::*;
1241
1242 fn mk_key(id: u32) -> GlyphKey {
1243 GlyphKey(id as u64)
1244 }
1245
1246 #[test]
1247 fn atlas_get_or_insert_dedupes() {
1248 let mut a = Atlas::new(64, 64);
1249 let k = mk_key(1);
1250 let e1 = a.get_or_insert(k, &[255; 8], 2, 4);
1251 let e2 = a.get_or_insert(k, &[0; 8], 2, 4);
1252 assert_eq!(e1.uv, e2.uv, "重复 key 必须返回同一 entry");
1253 assert_eq!(a.glyph_count(), 1);
1254 }
1255
1256 #[test]
1257 fn atlas_wraps_to_next_row() {
1258 let mut a = Atlas::new(20, 20);
1259 let k1 = mk_key(1);
1261 a.get_or_insert(k1, &[1; 64], 16, 4);
1262 let k2 = mk_key(2);
1264 let e2 = a.get_or_insert(k2, &[2; 64], 16, 4);
1265 assert!(e2.uv[1] > 0.0, "第二个 glyph 应该换行,uv.v0 > 0");
1266 }
1267
1268 #[test]
1269 fn atlas_dirty_flag_lifecycle() {
1270 let mut a = Atlas::new(64, 64);
1271 assert!(!a.is_dirty());
1273 a.get_or_insert(mk_key(1), &[255; 8], 2, 4);
1275 assert!(a.is_dirty(), "get_or_insert 后应该 dirty");
1276 a.clear_dirty();
1278 assert!(!a.is_dirty());
1279 a.get_or_insert(mk_key(1), &[0; 8], 2, 4);
1281 assert!(!a.is_dirty(), "重复 key 不应触发 dirty");
1282 a.get_or_insert(mk_key(2), &[0; 8], 2, 4);
1284 assert!(a.is_dirty());
1285 }
1286
1287 #[test]
1290 fn atlas_snapshot_uploads_only_dirty_rows() {
1291 let width = with_font(|fs| {
1293 fs.atlas = Atlas::new(ATLAS_SIZE, ATLAS_SIZE);
1294 fs.atlas.width
1295 });
1296 with_font(|fs| {
1297 fs.atlas.get_or_insert(GlyphKey::new(7, 7, 0, 0, 0, 0), &[9u8; 16], 4, 4);
1298 fs.atlas.get_or_insert(GlyphKey::new(7, 8, 0, 0, 0, 0), &[9u8; 16], 4, 4);
1299 assert_eq!(fs.atlas.dirty_rows, Some((1, 5)), "同一行的写入应合并为单行带");
1300 });
1301 let snap = atlas_snapshot();
1302 assert!(snap.dirty);
1303 assert_eq!(snap.dirty_y, (1, 5));
1304 assert_eq!(snap.pixels.as_ref().map(Vec::len), Some(width as usize * 4), "快照只拷贝 dirty 行");
1305 atlas_clear_dirty();
1306 let clean = atlas_snapshot();
1307 assert!(!clean.dirty);
1308 assert_eq!(clean.dirty_y, (0, 0));
1309 assert!(clean.pixels.is_none());
1310 }
1311
1312 #[test]
1314 fn atlas_auto_expands_when_full() {
1315 let mut a = Atlas::new(32, 32);
1316 let e_before = a.get_or_insert(mk_key(1), &[100; 9], 3, 3);
1318 let uv_scalar_before = e_before.uv[0]; let big: Vec<u8> = vec![200; 400]; for i in 2..10 {
1324 a.get_or_insert(mk_key(i), &big, 20, 20);
1325 }
1326 assert!(a.width >= 32, "atlas 应保持原尺寸或扩容");
1328 assert!(a.glyph_count() >= 8, "扩容后应能放下 8+ glyphs,实际 {}", a.glyph_count());
1329
1330 if a.width > 32 {
1332 let e_after = a.get_or_insert(mk_key(1), &[0; 9], 3, 3);
1334 let expected = uv_scalar_before / 2.0;
1337 assert!((e_after.uv[0] - expected).abs() < 0.01, "扩容后 uv.u0 应为 {expected}, 实际 {}", e_after.uv[0]);
1338 }
1339 }
1340
1341 #[test]
1343 fn atlas_accepts_new_glyphs_after_expansion() {
1344 let mut a = Atlas::new(16, 16);
1345 a.get_or_insert(mk_key(1), &[50; 144], 12, 12);
1347 let e2 = a.get_or_insert(mk_key(2), &[100; 144], 12, 12);
1349 assert!(a.width > 16 || a.height > 16, "应该扩容了");
1350 let e1 = a.get_or_insert(mk_key(1), &[0; 144], 12, 12);
1352 assert!(e2.uv[1] >= e1.uv[1], "第二个 glyph 应在第一个下方");
1353 }
1354
1355 #[test]
1356 fn text_measure_produces_nonzero_size() {
1357 let t = TextRenderObject::new("Hello".into(), 24.0, Color::WHITE);
1358 let s = t.measure();
1359 assert!(s.width > 0.0, "width should be > 0 for 'Hello'");
1360 assert!(s.height > 0.0, "height should be > 0");
1361 }
1362
1363 #[test]
1364 fn text_paint_emits_textured_rects() {
1365 let t = TextRenderObject::new("Hi".into(), 24.0, Color::WHITE);
1366 let mut list = PaintList::new();
1367 t.paint(Point::new(0.0, 0.0), &mut list);
1368 assert!(!list.is_empty(), "paint should emit at least 1 textured rect");
1370 for cmd in &list.commands {
1371 match cmd {
1372 PaintCommand::TexturedRect { texture_id, uv, .. } => {
1373 assert_eq!(*texture_id, 0);
1374 assert!(uv[0] < uv[2]);
1375 assert!(uv[1] < uv[3]);
1376 }
1377 _ => panic!("expected TexturedRect, got Rect"),
1378 }
1379 }
1380 }
1381
1382 #[test]
1383 fn text_paint_with_offset_shifts_rects() {
1384 let t = TextRenderObject::new("X".into(), 24.0, Color::WHITE);
1385 let mut list = PaintList::new();
1386 t.paint(Point::new(100.0, 50.0), &mut list);
1387 for cmd in &list.commands {
1389 if let PaintCommand::TexturedRect { rect, .. } = cmd {
1390 assert!(rect.x >= 100.0 - 1.0, "x={}", rect.x);
1391 assert!(rect.y >= 50.0 - 1.0, "y={}", rect.y);
1392 }
1393 }
1394 }
1395
1396 #[test]
1398 fn shape_line_cache_hits_second_paint() {
1399 let mut list1 = PaintList::new();
1400 paint_text_line("cache-hit-test", 20.0, Color::WHITE, Point::ZERO, &mut list1, None);
1401 let calls_1 = with_font(|fs| fs.shape_calls);
1402
1403 let mut list2 = PaintList::new();
1404 paint_text_line("cache-hit-test", 20.0, Color::WHITE, Point::new(5.0, 5.0), &mut list2, None);
1405 let calls_2 = with_font(|fs| fs.shape_calls);
1406
1407 assert_eq!(calls_1, calls_2, "第二次 paint 应命中缓存,不再 shape");
1408 assert_eq!(list1.commands.len(), list2.commands.len(), "缓存命中的绘制输出数量应一致");
1409 }
1410
1411 #[test]
1413 fn shape_line_cache_evicts_lru_at_limit() {
1414 let fake_line =
1415 || std::rc::Rc::new(ShapedLine { runs: Vec::new(), max_x: 0.0, max_y: 0.0, visual_lines: Vec::new() });
1416 let hot_key = (TextKey::Owned("hot-entry".to_string()), 0, None, 0);
1417 let oldest_key = (TextKey::Owned("fake-entry-0".to_string()), 0, None, 0);
1418 with_font(|fs| {
1419 fs.line_cache.clear();
1420 fs.line_clock = 0;
1421 fs.line_clock += 1;
1422 fs.line_cache.insert(hot_key.clone(), LineCacheEntry { line: fake_line(), last_used: fs.line_clock });
1423 for i in 0..LINE_CACHE_LIMIT - 1 {
1424 fs.line_clock += 1;
1425 fs.line_cache.insert(
1426 (TextKey::Owned(format!("fake-entry-{i}")), 0, None, 0),
1427 LineCacheEntry { line: fake_line(), last_used: fs.line_clock },
1428 );
1429 }
1430 fs.line_clock += 1;
1432 fs.line_cache.get_mut(&hot_key).expect("hot entry").last_used = fs.line_clock;
1433 });
1434 let mut list = PaintList::new();
1436 paint_text_line("trigger-evict", 14.0, Color::WHITE, Point::ZERO, &mut list, None);
1437 with_font(|fs| {
1438 assert!(fs.line_cache.len() <= LINE_CACHE_LIMIT, "超限后应回收到上限内");
1439 assert!(fs.line_cache.len() >= LINE_CACHE_TARGET, "LRU 只应淘汰最旧 1/4");
1440 assert!(fs.line_cache.contains_key(&hot_key), "刚访问过的热条目不应被淘汰");
1441 assert!(!fs.line_cache.contains_key(&oldest_key), "最久未访问的条目应被淘汰");
1442 fs.line_cache.clear();
1443 });
1444 }
1445
1446 #[test]
1448 fn paint_rebuilds_evicted_raster_glyphs() {
1449 let mut first = PaintList::new();
1450 paint_text_line("raster-rebuild-test", 18.0, Color::WHITE, Point::ZERO, &mut first, None);
1451 assert!(!first.commands.is_empty());
1452
1453 with_font(|fs| {
1454 fs.raster_cache.clear();
1455 fs.raster_cache_bytes = 0;
1456 });
1457
1458 let mut second = PaintList::new();
1459 paint_text_line("raster-rebuild-test", 18.0, Color::WHITE, Point::ZERO, &mut second, None);
1460 assert_eq!(first.commands.len(), second.commands.len(), "位图淘汰后应重建 glyph,而不是丢字");
1461 assert!(!second.commands.is_empty());
1462 }
1463
1464 #[test]
1468 fn zero_size_glyphs_are_cached_not_rerasterized() {
1469 with_font(|fs| {
1470 fs.raster_cache.clear();
1471 fs.raster_cache_bytes = 0;
1472 let _ = shape_text(fs, "a b c", 13.0, None, DEFAULT_FONT_STACK);
1473 let cached = fs.raster_cache.len();
1474 assert!(
1475 fs.raster_cache.values().any(|g| g.width == 0 && g.height == 0),
1476 "空格等零尺寸 glyph 必须缓存占位,不能每次重栅格化"
1477 );
1478 let _ = shape_text(fs, "a b c d", 13.0, None, DEFAULT_FONT_STACK);
1481 assert_eq!(fs.raster_cache.len(), cached + 1, "除新字符外不得新增栅格化条目");
1482 fs.raster_cache.clear();
1483 fs.raster_cache_bytes = 0;
1484 });
1485 }
1486
1487 #[test]
1489 fn raster_cache_trims_to_budget() {
1490 with_font(|fs| {
1491 fs.raster_cache.clear();
1492 fs.raster_cache_bytes = 0;
1493 let chunk = vec![0u8; 8 * 1024 * 1024];
1494 for i in 0..5u16 {
1495 insert_raster_glyph(
1496 fs,
1497 GlyphKey::new(0, i, 0, 0, 0, 0),
1498 RasterGlyph { data: chunk.clone(), width: 2048, height: 1024, left: 0, top: 0, last_used: 0 },
1499 );
1500 }
1501 assert!(fs.raster_cache_bytes <= RASTER_CACHE_TARGET_BYTES, "应回收到目标水位");
1503 assert_eq!(fs.raster_cache.len(), 3, "LRU 应保留最近的条目");
1504 assert!(!fs.raster_cache.contains_key(&GlyphKey::new(0, 0, 0, 0, 0, 0)), "最旧条目应被淘汰");
1505 assert!(fs.raster_cache.contains_key(&GlyphKey::new(0, 4, 0, 0, 0, 0)), "最新条目应保留");
1506 fs.raster_cache.clear();
1507 fs.raster_cache_bytes = 0;
1508 });
1509 }
1510
1511 #[test]
1514 fn paint_text_line_dpr_rasterizes_at_physical_resolution() {
1515 fn paint_once(dpr: f32) -> (f32, f32, f32) {
1516 set_text_dpr(dpr);
1517 let mut list = PaintList::new();
1518 let width = paint_text_line("H", 24.0, Color::WHITE, Point::ZERO, &mut list, None);
1519 let (rect_w, uv_span) = match &list.commands[0] {
1520 PaintCommand::TexturedRect { rect, uv, .. } => (rect.width, (uv[2] - uv[0]) * ATLAS_SIZE as f32),
1521 _ => panic!("expected TexturedRect"),
1522 };
1523 set_text_dpr(1.0); (rect_w, uv_span, width)
1525 }
1526
1527 let (w1, span1, ret1) = paint_once(1.0);
1528 let (w2, span2, ret2) = paint_once(2.0);
1529
1530 assert!((w1 - w2).abs() <= 2.0, "rect 逻辑尺寸应 dpr 无关(允许取整 ≤2px): dpr1={w1} vs dpr2={w2}");
1532 assert!((ret1 - ret2).abs() < 0.5 && ret1 > 0.0, "返回宽度(逻辑)应 dpr 无关: {ret1} vs {ret2}");
1533 assert!(span2 > span1 * 1.5, "atlas 位图分辨率应随 dpr 变大: dpr1={span1}px vs dpr2={span2}px");
1534 let mw = measure_text_width("H", 24.0);
1535 assert!((ret1 - mw).abs() < 0.5, "paint 宽度应与 measure 一致(TextField 光标定位依赖): {ret1} vs {mw}");
1536 }
1537}
1538
1539pub fn is_rtl_text(text: &str) -> bool {
1545 for ch in text.chars() {
1546 let code = ch as u32;
1547 let rtl = matches!(
1548 code,
1549 0x0590..=0x05FF | 0x0600..=0x06FF | 0x0700..=0x074F | 0x0750..=0x077F | 0x0780..=0x07BF | 0x0860..=0x086F | 0x08A0..=0x08FF | 0xFB1D..=0xFB4F | 0xFB50..=0xFDFF | 0xFE70..=0xFEFF );
1560 if rtl {
1561 return true;
1562 }
1563 if ch.is_alphabetic() {
1564 return false;
1565 }
1566 }
1567 false
1568}
1569
1570pub fn mirror_carets_for_rtl(widths: &[f32]) -> Vec<f32> {
1576 let chars = widths.len().saturating_sub(1);
1577 if chars == 0 {
1578 return widths.to_vec();
1579 }
1580 let mut carets = vec![0.0f32; chars + 1];
1581 carets[0] = widths[chars];
1582 carets[1..=chars].copy_from_slice(&widths[..chars]);
1583 carets
1584}
1585
1586pub fn measure_caret_positions(text: &str, size_px: f32, font_stack: &str) -> Vec<f32> {
1588 let widths = measure_char_prefix_widths(text, size_px, font_stack);
1589 if is_rtl_text(text) {
1590 mirror_carets_for_rtl(&widths)
1591 } else {
1592 widths
1593 }
1594}
1595
1596pub fn nearest_caret_index(carets: &[f32], x: f32) -> usize {
1598 carets
1599 .iter()
1600 .enumerate()
1601 .min_by(|(ia, a), (ib, b)| (**a - x).abs().total_cmp(&(**b - x).abs()).then_with(|| ia.cmp(ib)))
1602 .map(|(index, _)| index)
1603 .unwrap_or(0)
1604}
1605
1606#[cfg(test)]
1607mod rtl_tests {
1608 use super::*;
1609
1610 #[test]
1611 fn detects_base_direction() {
1612 assert!(is_rtl_text("مرحبا بالعالم"));
1613 assert!(is_rtl_text("שלום"));
1614 assert!(!is_rtl_text("hello مرحبا")); assert!(!is_rtl_text("123 !?"));
1616 assert!(is_rtl_text("123 مرحبا")); }
1618
1619 #[test]
1620 fn rtl_caret_mirroring_and_nearest_index() {
1621 let widths = [0.0, 10.0, 25.0, 40.0];
1623 let carets = mirror_carets_for_rtl(&widths);
1624 assert_eq!(carets, vec![40.0, 0.0, 10.0, 25.0]);
1625 assert_eq!(nearest_caret_index(&carets, 38.0), 0, "靠近右缘 → 文本起点");
1626 assert_eq!(nearest_caret_index(&carets, 2.0), 1);
1627 assert_eq!(nearest_caret_index(&carets, 24.0), 3, "靠近左缘 → 文本末尾");
1628 assert_eq!(mirror_carets_for_rtl(&[0.0]), vec![0.0]);
1630 assert_eq!(nearest_caret_index(&widths, 12.0), 1);
1631 }
1632}
1633
1634#[derive(Clone, Debug, PartialEq)]
1640pub struct RichTextSpan {
1641 pub text: String,
1642 pub size_px: f32,
1643 pub color: Option<Color>,
1645 pub font_stack: Option<String>,
1647}
1648
1649impl RichTextSpan {
1650 pub fn new(text: impl Into<String>) -> Self {
1651 Self { text: text.into(), size_px: 15.0, color: None, font_stack: None }
1652 }
1653
1654 pub fn with_size(mut self, size_px: f32) -> Self {
1655 self.size_px = size_px;
1656 self
1657 }
1658
1659 pub fn with_color(mut self, color: Color) -> Self {
1660 self.color = Some(color);
1661 self
1662 }
1663
1664 pub fn with_font_stack(mut self, stack: impl Into<String>) -> Self {
1665 self.font_stack = Some(stack.into());
1666 self
1667 }
1668}
1669
1670pub type InlinePainter = std::rc::Rc<dyn Fn(&mut PaintList, Rect)>;
1672
1673#[derive(Clone)]
1675pub struct InlineItem {
1676 pub width: f32,
1677 pub height: f32,
1678 pub painter: InlinePainter,
1679}
1680
1681impl InlineItem {
1682 pub fn new(width: f32, height: f32, painter: impl Fn(&mut PaintList, Rect) + 'static) -> Self {
1683 Self { width, height, painter: std::rc::Rc::new(painter) }
1684 }
1685}
1686
1687impl std::fmt::Debug for InlineItem {
1688 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1689 f.debug_struct("InlineItem").field("width", &self.width).field("height", &self.height).finish()
1690 }
1691}
1692
1693impl PartialEq for InlineItem {
1694 fn eq(&self, other: &Self) -> bool {
1695 self.width == other.width && self.height == other.height && std::rc::Rc::ptr_eq(&self.painter, &other.painter)
1696 }
1697}
1698
1699#[derive(Clone, Debug, PartialEq)]
1701pub enum RichItem {
1702 Text(RichTextSpan),
1703 Inline(InlineItem),
1704}
1705
1706#[derive(Clone, Debug, PartialEq)]
1708pub struct RichText {
1709 text: std::rc::Rc<str>,
1710 spans: Vec<RichTextSpan>,
1711 ranges: Vec<(usize, usize)>,
1712 inlines: Vec<(usize, InlineItem)>,
1714}
1715
1716impl RichText {
1717 pub fn new(spans: Vec<RichTextSpan>) -> Self {
1718 Self::from_items(spans.into_iter().map(RichItem::Text).collect())
1719 }
1720
1721 pub fn from_items(items: Vec<RichItem>) -> Self {
1722 let mut text = String::new();
1723 let mut spans = Vec::new();
1724 let mut ranges = Vec::new();
1725 let mut inlines = Vec::new();
1726 for item in items {
1727 match item {
1728 RichItem::Text(span) => {
1729 let start = text.len();
1730 text.push_str(&span.text);
1731 spans.push(span);
1732 ranges.push((start, text.len()));
1733 }
1734 RichItem::Inline(inline) => inlines.push((text.len(), inline)),
1735 }
1736 }
1737 Self { text: text.into(), spans, ranges, inlines }
1738 }
1739
1740 pub fn plain_text(&self) -> &str {
1742 &self.text
1743 }
1744
1745 pub fn spans(&self) -> &[RichTextSpan] {
1746 &self.spans
1747 }
1748
1749 pub fn is_empty(&self) -> bool {
1750 self.text.is_empty() && self.inlines.is_empty()
1751 }
1752}
1753
1754struct RichShapedGlyph {
1755 raster_key: GlyphKey,
1756 glyph_id: u16,
1757 x: f32,
1758 span: u16,
1760}
1761
1762struct RichShapedRun {
1763 glyphs: Vec<RichShapedGlyph>,
1764 baseline_y: f32,
1765 ascent: f32,
1767 font: parley::Font,
1768 norm_coords: std::rc::Rc<[swash::NormalizedCoord]>,
1769 raster_size: f32,
1770}
1771
1772struct RichInlineBox {
1774 id: u16,
1776 x: f32,
1777 y: f32,
1778 width: f32,
1779 height: f32,
1780 line_baseline: f32,
1782}
1783
1784struct RichShapedLine {
1785 runs: Vec<RichShapedRun>,
1786 inline_boxes: Vec<RichInlineBox>,
1787 max_x: f32,
1788 max_y: f32,
1789}
1790
1791#[derive(Clone, PartialEq, Eq, Hash)]
1792struct RichCacheKey {
1793 text: std::rc::Rc<str>,
1794 styles: Vec<(usize, usize, u32, u64)>,
1796 inlines: Vec<(usize, u32, u32)>,
1798 width_bits: Option<u32>,
1799 dpr_bits: u32,
1800}
1801
1802struct RichCacheEntry {
1803 line: std::rc::Rc<RichShapedLine>,
1804 last_used: u64,
1805}
1806
1807fn rich_style_signature(rich: &RichText) -> Vec<(usize, usize, u32, u64)> {
1808 rich.ranges
1809 .iter()
1810 .zip(&rich.spans)
1811 .map(|((start, end), span)| {
1812 let stack = span.font_stack.as_deref().unwrap_or(DEFAULT_FONT_STACK);
1813 let mut h = DefaultHasher::new();
1814 stack.hash(&mut h);
1815 (*start, *end, span.size_px.max(1.0).to_bits(), h.finish())
1816 })
1817 .collect()
1818}
1819
1820fn span_index_at(ranges: &[(usize, usize)], byte: usize) -> u16 {
1821 ranges.iter().position(|(start, end)| byte >= *start && byte < *end).unwrap_or(0) as u16
1822}
1823
1824fn shape_rich(fs: &mut FontState, rich: &RichText, max_width_px: Option<f32>) -> std::rc::Rc<RichShapedLine> {
1826 let dpr = text_dpr();
1827 let key = RichCacheKey {
1828 text: std::rc::Rc::clone(&rich.text),
1829 styles: rich_style_signature(rich),
1830 inlines: rich
1831 .inlines
1832 .iter()
1833 .map(|(index, inline)| (*index, inline.width.to_bits(), inline.height.to_bits()))
1834 .collect(),
1835 width_bits: max_width_px.map(|w| w.to_bits()),
1836 dpr_bits: dpr.to_bits(),
1837 };
1838 if let Some(entry) = fs.rich_cache.get_mut(&key) {
1839 fs.rich_clock += 1;
1840 entry.last_used = fs.rich_clock;
1841 return std::rc::Rc::clone(&entry.line);
1842 }
1843
1844 let text: &str = &rich.text;
1845 let mut builder = fs.layout_cx.ranged_builder(&mut fs.font_cx, text, 1.0, true);
1846 builder.push_default(parley::StyleProperty::FontSize(15.0));
1847 builder.push_default(parley::StyleProperty::LineHeight(1.2));
1848 builder.push_default(parley::StyleProperty::FontStack(parley::FontStack::Source(std::borrow::Cow::Borrowed(
1849 DEFAULT_FONT_STACK,
1850 ))));
1851 builder.push_default(parley::StyleProperty::WordBreak(parley::swash::text::WordBreakStrength::KeepAll));
1852 builder.push_default(parley::StyleProperty::OverflowWrap(parley::OverflowWrap::Anywhere));
1853 for ((start, end), span) in rich.ranges.iter().zip(&rich.spans) {
1854 if span.size_px > 0.0 {
1855 builder.push(parley::StyleProperty::FontSize(span.size_px), *start..*end);
1856 }
1857 if let Some(stack) = &span.font_stack {
1858 builder.push(
1859 parley::StyleProperty::FontStack(parley::FontStack::Source(std::borrow::Cow::Borrowed(stack))),
1860 *start..*end,
1861 );
1862 }
1863 }
1864 for (id, (index, inline)) in rich.inlines.iter().enumerate() {
1865 builder.push_inline_box(parley::InlineBox {
1866 id: id as u64,
1867 index: *index,
1868 width: inline.width,
1869 height: inline.height,
1870 });
1871 }
1872 let mut layout: parley::Layout<()> = builder.build(text);
1873 let wrap_opt = max_width_px.filter(|w| *w > 0.0);
1874 layout.break_all_lines(wrap_opt);
1875 layout.align(wrap_opt, parley::Alignment::Start, parley::AlignmentOptions::default());
1876
1877 let mut runs = Vec::new();
1878 let mut inline_boxes = Vec::new();
1879 let mut max_x = 0.0f32;
1880 let mut max_y = 0.0f32;
1881 for line in layout.lines() {
1882 let line_m = line.metrics();
1883 let baseline_y = line_m.baseline * dpr;
1884 for item in line.items() {
1885 let parley::PositionedLayoutItem::GlyphRun(gr) = item else {
1886 if let parley::PositionedLayoutItem::InlineBox(b) = item {
1887 inline_boxes.push(RichInlineBox {
1888 id: b.id as u16,
1889 x: b.x,
1890 y: b.y,
1891 width: b.width,
1892 height: b.height,
1893 line_baseline: baseline_y,
1894 });
1895 max_x = max_x.max((b.x + b.width) * dpr);
1896 max_y = max_y.max((b.y + b.height) * dpr);
1897 }
1898 continue;
1899 };
1900 let run_metrics = gr.run().metrics();
1901 let ascent = run_metrics.ascent * dpr;
1902 let descent = run_metrics.descent * dpr;
1903 let font_size_phys = gr.run().font_size() * dpr;
1904 let font_blob_id = gr.run().font().data.id() as usize;
1905 let norm_coords: std::rc::Rc<[swash::NormalizedCoord]> = gr.run().normalized_coords().to_vec().into();
1906 let run_font = gr.run().font().clone();
1907 let mut pen_x = gr.offset();
1908 let mut run_glyphs = Vec::new();
1909 for cluster in gr.run().visual_clusters() {
1910 let cluster_byte = cluster.text_range().start;
1911 let span = span_index_at(&rich.ranges, cluster_byte);
1912 for g in cluster.glyphs() {
1913 let raster_key = GlyphKey::new(font_blob_id, g.id, font_size_phys.to_bits(), 0, 0, 0);
1914 if !fs.raster_cache.contains_key(&raster_key) {
1915 if let Some(rg) =
1916 rasterize_one_glyph(&run_font, font_size_phys, g.id, &norm_coords, &mut fs.scale_cx)
1917 {
1918 insert_raster_glyph(fs, raster_key, rg);
1919 }
1920 }
1921 let gx = pen_x + g.x;
1922 run_glyphs.push(RichShapedGlyph { raster_key, glyph_id: g.id, x: gx * dpr, span });
1923 max_x = max_x.max((gx + g.advance) * dpr);
1924 max_y = max_y.max(baseline_y + descent);
1925 pen_x += g.advance;
1926 }
1927 }
1928 if !run_glyphs.is_empty() {
1929 runs.push(RichShapedRun {
1930 glyphs: run_glyphs,
1931 baseline_y,
1932 ascent,
1933 font: run_font,
1934 norm_coords,
1935 raster_size: font_size_phys,
1936 });
1937 }
1938 }
1939 }
1940 if max_y == 0.0 {
1941 max_y = rich.spans.iter().map(|s| s.size_px).fold(15.0, f32::max) * 1.2 * dpr;
1942 }
1943
1944 let line = std::rc::Rc::new(RichShapedLine { runs, inline_boxes, max_x, max_y });
1945 if fs.rich_cache.len() >= LINE_CACHE_LIMIT {
1946 fs.rich_cache.clear();
1947 }
1948 fs.rich_clock += 1;
1949 fs.rich_cache.insert(key, RichCacheEntry { line: std::rc::Rc::clone(&line), last_used: fs.rich_clock });
1950 line
1951}
1952
1953pub fn rich_text_size(rich: &RichText, max_width: Option<f32>) -> Size {
1955 if rich.is_empty() {
1956 return Size::ZERO;
1957 }
1958 with_font(|fs| {
1959 let dpr = text_dpr();
1960 let shaped = shape_rich(fs, rich, max_width);
1961 let first_baseline = shaped.runs.first().map(|r| r.baseline_y);
1962 let (anchor, fallback_h) = match first_baseline {
1963 Some(baseline) => {
1964 let first_ascent =
1966 shaped.runs.iter().filter(|r| r.baseline_y == baseline).map(|r| r.ascent).fold(0.0f32, f32::max);
1967 let inline_top = shaped
1968 .inline_boxes
1969 .iter()
1970 .filter(|b| b.line_baseline == baseline)
1971 .map(|b| b.y * dpr)
1972 .fold(f32::INFINITY, f32::min);
1973 ((baseline - first_ascent).min(inline_top), 0.0)
1975 }
1976 None => (0.0, shaped.max_y),
1977 };
1978 let height = if shaped.max_y > anchor { (shaped.max_y - anchor) / dpr } else { fallback_h / dpr };
1979 Size::new(shaped.max_x / dpr, height)
1980 })
1981}
1982
1983#[derive(Clone, Debug, PartialEq)]
1985pub struct RichTextLayout {
1986 pub size: Size,
1987 pub inline_rects: Vec<Rect>,
1988}
1989
1990pub fn rich_text_layout(rich: &RichText, max_width: Option<f32>) -> RichTextLayout {
1992 if rich.is_empty() {
1993 return RichTextLayout { size: Size::ZERO, inline_rects: Vec::new() };
1994 }
1995 with_font(|fs| {
1996 let dpr = text_dpr();
1997 let shaped = shape_rich(fs, rich, max_width);
1998 let first_baseline = shaped.runs.first().map(|r| r.baseline_y);
1999 let anchor = match first_baseline {
2000 Some(baseline) => {
2001 let first_ascent =
2002 shaped.runs.iter().filter(|r| r.baseline_y == baseline).map(|r| r.ascent).fold(0.0f32, f32::max);
2003 let inline_top = shaped
2004 .inline_boxes
2005 .iter()
2006 .filter(|b| b.line_baseline == baseline)
2007 .map(|b| b.y * dpr)
2008 .fold(f32::INFINITY, f32::min);
2009 (baseline - first_ascent).min(inline_top)
2010 }
2011 None => 0.0,
2012 };
2013 let height = if shaped.max_y > anchor { (shaped.max_y - anchor) / dpr } else { 0.0 };
2014 let mut inline_rects = vec![Rect::new(0.0, 0.0, 0.0, 0.0); rich.inlines.len()];
2015 for b in &shaped.inline_boxes {
2016 if let Some(slot) = inline_rects.get_mut(b.id as usize) {
2017 *slot = Rect::new(b.x, (b.y * dpr - anchor) / dpr, b.width, b.height);
2018 }
2019 }
2020 RichTextLayout { size: Size::new(shaped.max_x / dpr, height), inline_rects }
2021 })
2022}
2023
2024pub fn paint_rich_text(rich: &RichText, offset: Point, list: &mut PaintList, max_width: Option<f32>) -> f32 {
2026 paint_rich_text_with_default(rich, Color::WHITE, offset, list, max_width)
2027}
2028
2029pub fn paint_rich_text_with_default(
2031 rich: &RichText,
2032 default_color: Color,
2033 offset: Point,
2034 list: &mut PaintList,
2035 max_width: Option<f32>,
2036) -> f32 {
2037 if rich.is_empty() {
2038 return 0.0;
2039 }
2040 with_font(|fs| {
2041 let dpr = text_dpr();
2042 let shaped = shape_rich(fs, rich, max_width);
2043 let Some(first_run) = shaped.runs.first() else {
2044 return 0.0;
2045 };
2046 let first_baseline = first_run.baseline_y;
2047 let first_ascent =
2048 shaped.runs.iter().filter(|r| r.baseline_y == first_baseline).map(|r| r.ascent).fold(0.0f32, f32::max);
2049 let inline_top = shaped
2050 .inline_boxes
2051 .iter()
2052 .filter(|b| b.line_baseline == first_baseline)
2053 .map(|b| b.y * dpr)
2054 .fold(f32::INFINITY, f32::min);
2055 let anchor = (first_baseline - first_ascent).min(inline_top);
2056
2057 for run in &shaped.runs {
2058 for sg in &run.glyphs {
2059 if !fs.raster_cache.contains_key(&sg.raster_key) {
2060 if let Some(rg) =
2061 rasterize_one_glyph(&run.font, run.raster_size, sg.glyph_id, &run.norm_coords, &mut fs.scale_cx)
2062 {
2063 insert_raster_glyph(fs, sg.raster_key, rg);
2064 }
2065 }
2066 let Some(r) = fs.raster_cache.get_mut(&sg.raster_key) else {
2067 continue;
2068 };
2069 if r.width == 0 || r.height == 0 {
2070 continue;
2071 }
2072 fs.glyph_clock += 1;
2073 r.last_used = fs.glyph_clock;
2074 let entry = fs.atlas.get_or_insert(sg.raster_key, &r.data, r.width, r.height);
2075
2076 let x = offset.x + (sg.x + r.left as f32) / dpr;
2077 let glyph_visual_top = run.baseline_y - r.top as f32;
2078 let y = offset.y + (glyph_visual_top - anchor) / dpr;
2079 let rect = Rect::new(x, y, r.width as f32 / dpr, r.height as f32 / dpr);
2080 let color = rich.spans.get(sg.span as usize).and_then(|s| s.color).unwrap_or(default_color);
2081 list.push(PaintCommand::TexturedRect {
2082 rect,
2083 color,
2084 uv: entry.uv,
2085 texture_id: 0,
2086 mode: mgui_core::paint::TextureMode::Mask,
2087 });
2088 }
2089 }
2090 for b in &shaped.inline_boxes {
2091 if let Some((_, inline)) = rich.inlines.get(b.id as usize) {
2092 let rect = Rect::new(offset.x + b.x, offset.y + b.y - anchor / dpr, b.width, b.height);
2093 (inline.painter)(list, rect);
2094 }
2095 }
2096 shaped.max_x / dpr
2097 })
2098}
2099
2100#[cfg(test)]
2101mod rich_text_tests {
2102 use super::*;
2103
2104 #[test]
2105 fn mixed_styles_measure_and_paint_with_span_colors() {
2106 set_text_dpr(1.0);
2107 let red = Color::from_rgb8(255, 0, 0);
2108 let rich = RichText::new(vec![
2109 RichTextSpan::new("Hello ").with_size(18.0).with_color(Color::WHITE),
2110 RichTextSpan::new("World").with_size(30.0).with_color(red),
2111 ]);
2112 let size = rich_text_size(&rich, None);
2113 assert!(size.width > 0.0, "宽度必须 > 0");
2114 assert!(size.height >= 30.0, "高度应容纳 30px 字号: {size:?}");
2115
2116 let mut list = PaintList::new();
2117 let width = paint_rich_text(&rich, Point::ZERO, &mut list, None);
2118 assert!((width - size.width).abs() < 0.5, "绘制宽度应与测量一致: {width} vs {}", size.width);
2119 let colors: Vec<Color> = list
2120 .commands
2121 .iter()
2122 .filter_map(|c| match c {
2123 PaintCommand::TexturedRect { color, .. } => Some(*color),
2124 _ => None,
2125 })
2126 .collect();
2127 assert!(colors.contains(&Color::WHITE), "应包含第一段白色字形");
2128 assert!(colors.contains(&red), "应包含第二段红色字形");
2129 }
2130
2131 #[test]
2132 fn inline_item_measures_paints_and_sits_on_baseline() {
2133 use std::cell::RefCell;
2134 set_text_dpr(1.0);
2135 let captured: std::rc::Rc<RefCell<Option<Rect>>> = std::rc::Rc::new(RefCell::new(None));
2136 let cap = captured.clone();
2137 let rich = RichText::from_items(vec![
2138 RichItem::Text(RichTextSpan::new("A").with_size(16.0)),
2139 RichItem::Inline(InlineItem::new(30.0, 24.0, move |_list, rect| *cap.borrow_mut() = Some(rect))),
2140 RichItem::Text(RichTextSpan::new("B").with_size(16.0)),
2141 ]);
2142 let size = rich_text_size(&rich, None);
2143 assert!(size.width >= 30.0, "宽度应包含内联项: {size:?}");
2144 assert!(size.height >= 20.0, "高度应容纳内联项: {size:?}");
2145
2146 let mut list = PaintList::new();
2147 let width = paint_rich_text(&rich, Point::new(10.0, 5.0), &mut list, None);
2148 assert!(width >= 30.0);
2149 let rect = captured.borrow().expect("内联项绘制回调应被调用");
2150 assert!((rect.width - 30.0).abs() < 0.01 && (rect.height - 24.0).abs() < 0.01, "{rect:?}");
2151 assert!(rect.x >= 10.0 && rect.y >= 5.0, "内联项应带 offset: {rect:?}");
2152 }
2153
2154 #[test]
2155 fn inline_items_wrap_when_narrow() {
2156 set_text_dpr(1.0);
2157 let rich = RichText::from_items(vec![
2158 RichItem::Inline(InlineItem::new(40.0, 20.0, |_, _| {})),
2159 RichItem::Inline(InlineItem::new(40.0, 20.0, |_, _| {})),
2160 ]);
2161 let one_line = rich_text_size(&rich, None);
2162 let wrapped = rich_text_size(&rich, Some(50.0));
2163 assert!(one_line.width > wrapped.width, "窄宽度应减少行宽: {one_line:?} vs {wrapped:?}");
2164 assert!(
2165 wrapped.height > one_line.height * 1.5,
2166 "两个 40 宽内联项在 50 宽内应换行: {one_line:?} vs {wrapped:?}"
2167 );
2168 }
2169
2170 #[test]
2171 fn soft_wrap_uses_max_width() {
2172 set_text_dpr(1.0);
2173 let rich = RichText::new(vec![RichTextSpan::new("word ".repeat(40)).with_size(16.0)]);
2174 let single = rich_text_size(&rich, None);
2175 let wrapped = rich_text_size(&rich, Some(120.0));
2176 assert!(single.height > 0.0 && wrapped.height > 0.0);
2177 assert!(wrapped.height > single.height * 2.0, "换行后高度应显著增加: {single:?} vs {wrapped:?}");
2178 assert!(wrapped.width <= 130.0, "换行后宽度应受 max_width 约束: {wrapped:?}");
2179 }
2180}
2181
2182#[cfg(test)]
2187mod multiline_regression {
2188 use super::*;
2189
2190 #[test]
2192 fn multiline_text_lines_have_distinct_y() {
2193 let mut list = PaintList::new();
2194 paint_text_line("第一行AAA\n第二行BBB", 20.0, Color::WHITE, Point::new(50.0, 100.0), &mut list, None);
2195 let ys: Vec<f32> = list
2196 .commands
2197 .iter()
2198 .filter_map(|c| match c {
2199 PaintCommand::TexturedRect { rect, .. } => Some((rect.y * 10.0).round() / 10.0),
2200 _ => None,
2201 })
2202 .collect();
2203 assert!(!ys.is_empty(), "应画出 glyph");
2204 let y0 = ys[0];
2205 assert!(ys.iter().any(|&y| (y - y0).abs() > 20.0), "多行文本各行 y 必须拉开,实际全部≈{}: {:?}", y0, ys);
2206 }
2207
2208 #[test]
2210 fn wrapped_text_lines_have_distinct_y() {
2211 let mut list = PaintList::new();
2212 paint_text_line(
2214 "第一行文本内容比较长需要折行",
2215 20.0,
2216 Color::WHITE,
2217 Point::new(0.0, 0.0),
2218 &mut list,
2219 Some(60.0),
2220 );
2221 let ys: Vec<f32> = list
2222 .commands
2223 .iter()
2224 .filter_map(|c| match c {
2225 PaintCommand::TexturedRect { rect, .. } => Some((rect.y * 10.0).round() / 10.0),
2226 _ => None,
2227 })
2228 .collect();
2229 let y0 = ys[0];
2230 assert!(ys.iter().any(|&y| (y - y0).abs() > 20.0), "soft-wrap 多行 y 必须拉开,实际全部≈{}: {:?}", y0, ys);
2231 }
2232}