Skip to main content

mgui_text/
text.rs

1//! TextRenderObject + parley 富文本布局 + swash 栅格化 + 字形图集
2//!
3//! 阶段 4-P(parley):
4//! - 用 `parley::FontContext` + `LayoutContext` 替代 cosmic-text 的 `FontSystem` + `Buffer`
5//! - `swash::scale::ScaleContext` 栅格化(re-exported by parley)
6//! - R8 灰度 glyph atlas,按行打包,key = 自造 GlyphKey
7//! - paint 时按 glyph 提交 `PaintCommand::TexturedRect`
8//!
9//! 设计取舍:
10//! - 整个 UI 层是单线程的(refs + Rc),不需要 Mutex 包裹 FontState
11//! - `parley::FontContext` 不是 `Sync`,所以用 `thread_local!` 是最自然的做法
12//! - **公共 API 不变**:measure_text_width / text_visual_height / paint_text_line 签名与行为保持一致
13
14use 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
23/// Atlas 尺寸(单侧);足够装 200+ 256px glyph,或 2000+ 64px glyph
24const ATLAS_SIZE: u32 = 1024;
25/// glyph 之间的 padding(防止双线性采样溢出)
26const ATLAS_PADDING: u32 = 1;
27/// 找不到字形时的回退尺寸(占位)
28const FALLBACK_ADVANCE_X: f32 = 8.0;
29/// atlas 最大尺寸(再扩就清 atlas,让 glyph 重新栅格化)
30const MAX_ATLAS_SIZE: u32 = 8192;
31
32/// 默认字体栈(CSS 格式):覆盖特殊符号、CJK、emoji 的 fallback 链。
33/// 旧版文本 API 的隐式默认值;`*_styled` 版 API 可显式传入自定义字体栈
34/// (代码编辑器用等宽字体栈,UI 组件沿用此默认)。
35pub 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// =============================================================================
39// Atlas
40// =============================================================================
41
42/// 单个 glyph 在 atlas 中的位置
43#[derive(Clone, Copy, Debug)]
44#[allow(dead_code)]
45pub struct AtlasEntry {
46    /// 归一化纹理坐标 (u0, v0, u1, v1),左下角原点(WGPU 约定)
47    pub uv: [f32; 4],
48    pub width: u32,
49    pub height: u32,
50}
51
52/// 简单的行式(Row-based)glyph atlas
53///
54/// - 维护当前行 y 位置 + 行内 x 位置
55/// - 放不下当前行就换行(y += row_height, x = 0, row_height = 0)
56/// - 整个 atlas 满了就 `panic`(阶段 3 简化;后续 LRU/扩容)
57/// - `dirty` 标记:从上次 `clear_dirty` 起,是否有新像素写入
58pub struct Atlas {
59    width: u32,
60    height: u32,
61    /// 下一个空位的 x
62    next_x: u32,
63    /// 当前行底部的 y
64    next_y: u32,
65    /// 当前行最高 glyph 的高度
66    row_height: u32,
67    /// 单通道灰度像素
68    pixels: Vec<u8>,
69    /// glyph → atlas entry
70    entries: HashMap<GlyphKey, AtlasEntry>,
71    /// 自上次 `clear_dirty` 起是否有新写入
72    dirty: bool,
73    /// 本次 dirty 的行区间 `[top, bottom)`。glyph 写入只影响少数行,
74    /// 上传时整行宽度(行宽保持 atlas 宽度,满足 256 字节对齐)只发这一段,
75    /// 避免每写一个 glyph 就整张(最大 64 MiB)拷贝 + 上传。
76    dirty_rows: Option<(u32, u32)>,
77    /// 内容版本:写 glyph / 扩容 / 清空时 +1。CPU 侧(软件光栅器)用它
78    /// 判断是否需要重新读取 atlas,不参与 GPU 上传的 dirty 语义。
79    generation: u64,
80}
81
82#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
83pub struct GlyphKey(pub u64);
84
85impl GlyphKey {
86    /// 从 parley run + glyph 派生:font_blob_id + glyph_id + size_bits + x_bin + y_bin
87    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    /// 扩容到 2× 尺寸,旧 glyph 保持在左上角象限。
123    /// 已有 entry 的 uv 都除以 2(归一化到新尺寸)。
124    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; // 已经封顶,不该走到这(外层已拦截)
129        }
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        // 把旧像素复制到新 buffer 的左上角
135        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        // 所有 entry 的 uv 都除以 2(归一化到新尺寸,旧 glyph 保持左上角相对位置)
143        let scale_u = old_w as f32 / new_w as f32; // = 0.5 when 2x
144        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        // 归一化 UV 变了:所有 layer 缓存的 PaintList 必须重画
157        mgui_core::element::request_full_repaint();
158    }
159
160    /// atlas 已满且无法再扩:清空所有 glyph,让后续按需重新栅格化。
161    /// 触发条件只有极端情况(8K atlas 也装不下),此时性能比 panic 重要。
162    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    /// 查询或插入一个 glyph
175    ///
176    /// `bitmap` 是 R8 灰度数据,长度 = `w * h`
177    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        // 申请空间:加 padding 防止双线性采样溢出
182        let alloc_w = w + ATLAS_PADDING * 2;
183        let alloc_h = h + ATLAS_PADDING * 2;
184        // 放不下当前行 → 换行
185        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            // atlas 满了:自动扩容 2×,若已到 MAX 则清空(性能 > panic)
192            if self.width >= MAX_ATLAS_SIZE && self.height >= MAX_ATLAS_SIZE {
193                self.clear_atlas();
194            } else {
195                self.expand_2x();
196            }
197            // 扩容/清空后重试(递归一次,再满就是 bug)
198            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        // 写入像素(R8)
204        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        // 归一化坐标(WGPU 纹理坐标 v 朝上,所以我们用 (0,0) = 左下)
212        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        // 写入了新像素 → 标 dirty 行区间(renderer 只上传这几行)
224        self.mark_rows_written(dst_y, h);
225        self.generation += 1;
226        entry
227    }
228
229    /// 记录一次 glyph 写入影响的行区间(与已有区间合并)
230    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    /// 整个 atlas 像素(用于上传到 GPU)
240    pub fn pixels(&self) -> &[u8] {
241        &self.pixels
242    }
243
244    /// 已有 glyph 数量
245    #[allow(dead_code)]
246    pub fn glyph_count(&self) -> usize {
247        self.entries.len()
248    }
249
250    /// 是否有新像素写入(自上次 `clear_dirty` 以来)
251    pub fn is_dirty(&self) -> bool {
252        self.dirty
253    }
254
255    /// 清 dirty 标记(GPU 已上传后调用)
256    pub fn clear_dirty(&mut self) {
257        self.dirty = false;
258        self.dirty_rows = None;
259    }
260}
261
262// =============================================================================
263// FontState(全局 thread_local) — parley 版
264// =============================================================================
265
266/// 栅格化后的 glyph 位图(缓存,避免每次重 rasterize)
267#[derive(Clone)]
268struct RasterGlyph {
269    data: Vec<u8>,
270    width: u32,
271    height: u32,
272    /// 栅格化时 glyph 相对 baseline 的 left/top offset(物理像素)
273    left: i32,
274    top: i32,
275    /// 最近一次被绘制/插入的时钟(LRU 预算用)
276    last_used: u64,
277}
278
279/// shaped-line 缓存 key:
280/// `(text, raster_px_bits, max_width_bits, font_stack_hash)`。
281type LineCacheKey = (TextKey, u32, Option<u32>, u64);
282
283/// shaped-line 缓存条目(带访问时钟,用于 LRU 淘汰)。
284struct LineCacheEntry {
285    line: std::rc::Rc<ShapedLine>,
286    last_used: u64,
287}
288
289/// 文字渲染所需全局状态 — parley + swash 版
290pub 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    /// 栅格化缓存:GlyphKey → 位图
296    raster_cache: HashMap<GlyphKey, RasterGlyph>,
297    /// 位图缓存当前总字节(增量维护,预算判断 O(1))
298    raster_cache_bytes: usize,
299    /// shaped-line 缓存(fps 优化):shape 一次,之后每帧只查表。
300    ///
301    /// **为什么必须有**:parley shaping 也不是零成本(每行 0.05~0.5ms+),
302    /// UI 文本几乎不变 — 每帧重 shape 纯浪费。debug build 放大 10-30 倍。
303    /// key = (TextKey, raster_px_bits, max_width_bits, font_stack_hash);
304    /// raster_px 已含 dpr → dpr 变化自动 miss;font_stack hash → 不同字体栈互不串缓存
305    line_cache: HashMap<LineCacheKey, LineCacheEntry>,
306    /// 富文本 shaped-line 缓存(P3-3)
307    rich_cache: HashMap<RichCacheKey, RichCacheEntry>,
308    /// 富文本缓存访问时钟
309    rich_clock: u64,
310    /// 全局访问时钟(LRU)
311    line_clock: u64,
312    /// glyph 位图缓存的访问时钟(LRU 预算)
313    glyph_clock: u64,
314    /// shaping 执行次数(测试观测缓存命中用)
315    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) };    /// 文字栅格化 DPR(物理/逻辑像素比)。
339    ///
340    /// **模糊修复**:glyph 必须按物理分辨率栅格化,否则 dpr=1.25/1.5 的
341    /// Windows 缩放下,低分辨率位图被 GPU 拉伸 → 文字发虚。
342    /// runtime 在每次 CPU paint 前调 `set_text_dpr(gpu.scale_factor)`。
343    static TEXT_DPR: std::cell::Cell<f32> = const { std::cell::Cell::new(1.0) };
344}
345
346/// 设置文字栅格化 DPR(在 CPU paint 之前调用;≤0 视为 1.0)
347pub 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
355/// 在全局 FontState 上执行操作(惰性初始化)
356pub 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
369// =============================================================================
370// Shaped-line 缓存(fps 优化)
371// =============================================================================
372
373/// 缓存条目上限。超过按 LRU 淘汰最旧 1/4(不是整体 clear)。
374///
375/// 整体 clear 会让下一次所有可见行全部重新 shape,造成周期性卡顿;
376/// 只淘汰最久未用条目可以保留仍在上屏的文本。
377const LINE_CACHE_LIMIT: usize = 4096;
378
379/// 超限时回收到本上限(LRU 保留最近 3/4)。
380const LINE_CACHE_TARGET: usize = LINE_CACHE_LIMIT - LINE_CACHE_LIMIT / 4;
381
382/// 淘汰最久未访问的条目,使缓存回到 `LINE_CACHE_TARGET`。
383fn 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
395/// glyph 位图缓存预算(CPU 内存)。条目可在缺字时按需重建,因此可以安全淘汰。
396const RASTER_CACHE_BUDGET_BYTES: usize = 32 * 1024 * 1024;
397/// 回收目标水位(留 headroom,避免每插入一个 glyph 都触发全表扫描)。
398const RASTER_CACHE_TARGET_BYTES: usize = RASTER_CACHE_BUDGET_BYTES * 3 / 4;
399
400/// 插入一个栅格化位图并维护字节计数/预算。
401fn 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
412/// 超预算时按 LRU 淘汰 glyph 位图。
413///
414/// paint 路径在缺字时可以用 `ShapedRun` 里的字体上下文重新栅格化,
415/// 所以淘汰不会导致文字缺失。
416fn 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/// shaped-line 缓存 key 的文本部分。
433///
434/// - `Owned`:普通 `&str` 调用方(每次查询克隆一份,与旧行为一致)
435/// - `Shared`:命令携带整串 `Rc<str>` + 可选字节区间 —— 命中路径只 bump
436///   引用计数,编辑器逐语法 span 绘制(整行共享)时零字符串分配
437#[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
449/// 缓存后的单个 glyph(shaping 结果,物理像素坐标系)
450struct ShapedGlyph {
451    /// 自造栅格化 key(font_blob_id + glyph_id + size + subpixel)
452    raster_key: GlyphKey,
453    /// 原始 glyph id(栅格化缓存被预算淘汰后按需重建用)
454    glyph_id: u16,
455    /// pen x(parley positioned_glyphs 的 g.x,物理像素)
456    x: f32,
457    /// advance 宽度(物理像素)
458    w: f32,
459    /// baseline y(parley positioned_glyphs 的 g.y,物理像素)
460    #[allow(dead_code)]
461    y: f32,
462    /// ascent(该行/该 run 向上延伸的物理像素)
463    ascent: f32,
464    /// descent(该 run 向下延伸的物理像素)
465    descent: f32,
466    /// 该 glyph 所属 cluster 的起始字节偏移(相对 shape_text 的完整输入文本)。
467    /// glyph → 源文本字节映射,编辑器光标/选区的字节偏移 ↔ x 坐标换算依赖它。
468    cluster: u32,
469}
470
471/// 缓存后的一行(单行文本 = 1 个 run)
472struct ShapedRun {
473    glyphs: Vec<ShapedGlyph>,
474    /// 该行 baseline y(物理像素)— 行间定位不可缺:缺了它多行会塌到同一 y 重叠
475    baseline_y: f32,
476    /// 本 run 的字体(栅格化缓存 miss 时按需重建 glyph 位图)
477    font: parley::Font,
478    /// 字体变体坐标(同上)
479    norm_coords: std::rc::Rc<[swash::NormalizedCoord]>,
480    /// 物理字号(同上)
481    raster_size: f32,
482}
483
484/// 缓存后的一整段 shaped 文本
485struct ShapedLine {
486    runs: Vec<ShapedRun>,
487    /// max(x + w)(物理像素);无 glyph = 0
488    max_x: f32,
489    /// max(baseline_y + descent)(物理像素);多行总视觉高
490    #[allow(dead_code)]
491    max_y: f32,
492    /// soft wrap 后的每条视觉行字节区间(相对输入文本);空文本 = [(0,0)]
493    visual_lines: Vec<(usize, usize)>,
494}
495
496/// 取 shaped line(带缓存):命中 O(1),miss 时 parley shaping 后插入。
497///
498/// `raster_px` 是物理字号(= 逻辑字号 × dpr);key 含它 → dpr 变化自动 miss。
499/// `max_width_px` 是逻辑像素宽度上限(soft wrap);0 或 None = 单行不换行。
500fn 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
510/// `shape_text` 的显式 key 版本:共享文本(Rc + 区间)由调用方直接传 key,
511/// 缓存命中路径不再克隆全文。
512fn 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    // parley 坐标系:scale=1.0, FontSize=逻辑像素,layout 输出=逻辑像素
536    // 后续 glyph 坐标 × dpr 转回物理像素(栅格化需要)
537    let scale = 1.0f32;
538    let font_size_px = raster_px / dpr;
539
540    // parley:单行或软换行。wrap_opt 用逻辑像素,和 layout 输出坐标系一致
541    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    // CSS 格式字体栈:fontique 会按顺序 fallback(CJK/symbol 字符能落到后备字体)
547    builder.push_default(parley::StyleProperty::FontStack(parley::FontStack::Source(std::borrow::Cow::Borrowed(
548        font_stack,
549    ))));
550    // KeepAll:CJK 字间不拆(只在空格/标点处断);OverflowWrap::Anywhere 防止超长拉丁词撑破容器
551    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    // 遍历 parley 的 lines → GlyphRun → positioned_glyphs
558    // 注意:parley 现在输出逻辑像素坐标(scale=dpr, FontSize=逻辑像素)
559    // 我们后面 pipeline 全用物理像素,所以这里统一 × dpr
560    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        // 视觉行覆盖的源文本字节区间(用于 TextField soft wrap 的光标/命中映射)
567        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; // 逻辑 → 物理
578
579        for item in line.items() {
580            let parley::PositionedLayoutItem::GlyphRun(gr) = item else {
581                continue;
582            };
583
584            // 每个 run 有自己的 ascent/descent(字体 fallback 时不同 run 字体不同)
585            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(); // 逻辑像素
589            let font_size_phys = font_size_logical * dpr; // 物理像素(栅格化用)
590            let font_blob_id = gr.run().font().data.id() as usize; // Blob<u8>::id() 全局唯一
591
592            // 每个 glyph 拿 x/y/advance + 自造 raster key + 所属 cluster 字节偏移。
593            // 遍历 visual clusters(GlyphRun::glyphs() 的内部实现即
594            // run.visual_clusters().flat_map(cluster.glyphs());单一默认样式时
595            // GlyphRun 覆盖整个 run,skip/take 不生效)。glyph x = cluster 相对 x + pen,
596            // pen 按逐 glyph advance 累计 —— 与 positioned_glyphs 语义逐位一致,
597            // 额外获得 glyph → 源文本字节偏移映射(cluster.text_range().start)。
598            let mut run_glyphs: Vec<ShapedGlyph> = Vec::new();
599            // 预先拿 normalized coords 供栅格化用(按 run 共享,供缓存淘汰后重建)
600            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; // parley 0.4 GlyphId = u16
608                    let size_bits = font_size_phys.to_bits(); // raster key 用物理像素
609                    let x_bin = 0; // 暂时不用 subpixel precision(后续优化)
610                    let y_bin = 0;
611                    let raster_key = GlyphKey::new(font_blob_id, glyph_id, size_bits, x_bin, y_bin, 0);
612                    // 栅格化缓存 miss 时即时栅格化
613                    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,                   // 逻辑 → 物理
625                        w: g.advance * dpr,            // 逻辑 → 物理
626                        y: (run_baseline + g.y) * dpr, // 逻辑 → 物理
627                        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    // 无任何 glyph(纯空白文本):给合理的兜底 max_y
650    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/// Atlas 当前状态快照
665///
666/// Renderer 拿到 snapshot 后决定:
667/// - size 变化 → 重建 GPU texture
668/// - dirty 变化 → `write_texture` 上传 `dirty_y` 行区间(`pixels` 已按
669///   整行宽度打包,行宽 = atlas 宽度 → 满足 256 字节对齐)
670/// - 否则 → 复用 cache 的 view/sampler
671#[derive(Clone)]
672pub struct AtlasSnapshot {
673    pub width: u32,
674    pub height: u32,
675    pub dirty: bool,
676    /// 本次 dirty 的行区间 `[top, bottom)`(整行宽度);其余行 GPU 侧保持原值。
677    /// `dirty=false` 时为 `(0, 0)`。
678    pub dirty_y: (u32, u32),
679    /// 像素数据:`dirty_y` 区间内的整行(长度 = width × 行数),不 dirty 时 None
680    pub pixels: Option<Vec<u8>>,
681}
682
683/// 拿到 atlas 快照
684pub 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
703/// 清 atlas dirty 标记(GPU 上传后调用)
704pub fn atlas_clear_dirty() {
705    with_font(|fs| {
706        fs.atlas.clear_dirty();
707    })
708}
709
710/// atlas 内容版本(写 glyph/扩容/清空时递增,与 GPU dirty 独立)
711pub fn atlas_generation() -> u64 {
712    with_font(|fs| fs.atlas.generation)
713}
714
715/// atlas 汇总(Inspector/诊断用;不拷贝像素)
716#[derive(Clone, Copy, Debug, Default)]
717pub struct AtlasStats {
718    pub width: u32,
719    pub height: u32,
720    pub glyph_count: usize,
721    /// 已分配到的最底行(包含当前行的行高)
722    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
739/// CPU 侧直接访问 atlas 像素(R8,行优先,左上原点,零拷贝)。
740///
741/// 软件光栅器逐 glyph 采样用:闭包内**不得**再调用 shaping / 栅格化 API
742/// (`with_font` 的 RefCell 正被借用,重入会 panic)。
743pub 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
750// =============================================================================
751// TextRenderObject
752// =============================================================================
753
754pub struct TextRenderObject {
755    text: String,
756    size_px: f32,
757    color: Color,
758    /// soft wrap 最大宽度(逻辑像素);None = 单行不换行
759    max_width: Option<f32>,
760    /// max_width 是否用户显式设置(true = 布局不刷新;false = 每轮 layout 用
761    /// 当前约束刷新,避免"第一次遇到的窄约束"永久粘滞导致意外折行叠影)
762    max_width_explicit: bool,
763    /// layout 阶段算的尺寸
764    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    /// 内部:测文字尺寸(走 shape_text 缓存,与 paint 同源)
785    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        // height 用 text_visual_height(同源于 paint_text_line 的 row_max_top 对齐)
798        // ——单行/多行都走这里,容器居中永不漂
799        let height = text_visual_height(&self.text, self.size_px, self.max_width);
800        Size::new(width, height)
801    }
802}
803
804/// 阶段 2-E:测一段文本的宽度(shaping 后,逻辑像素)
805///
806/// TextField 光标定位用:光标 x = 文本起点 + `measure_text_width(value[..cursor])`
807pub fn measure_text_width(text: &str, size_px: f32) -> f32 {
808    measure_text_width_styled(text, size_px, DEFAULT_FONT_STACK)
809}
810
811/// `measure_text_width` 的字体栈参数化版本(编辑器等宽字体栈用)
812pub 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        // 与 paint_text_line 同一 shape 缓存 → 宽度恒一致(TextField 光标依赖)
818        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
830/// 单行文本真实视觉高度(parley 版)
831///
832/// TextField/ButtonRO 等容器用它算垂直居中,保证 paint 出来后 glyph visual center
833/// 跟容器 center 对齐。
834///
835/// parley 直接给 ascent/descent/baseline:
836///   视觉顶 = baseline_y - ascent  (第一行)
837///   视觉底 = baseline_y + descent (每行 max)
838/// 不需要 cosmic-text 时代的"去栅格化拿 placement.top"那套 hack。
839pub 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
843/// `text_visual_height` 的字体栈参数化版本
844pub 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        // 首行视觉顶 = baseline - ascent
858        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        // 所有 run 算视觉底 = max(baseline_y + descent)
864        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
880/// 阶段 2-E:画一行/多行文字(glyph → scale → atlas → TexturedRect)
881///
882/// 从 `TextRenderObject::paint` 抽出,TextField 复用。
883/// 返回最大宽度(shaping 后)。
884/// `max_width_px` = 软换行宽度上限;None = 单行
885pub 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/// `paint_text_line` 的字体栈参数化版本(编辑器语法着色逐 token 绘制用)
897#[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/// 共享整串 + 可选字节区间绘制(编辑器逐语法 span 复用整行 `Rc<str>`)。
911///
912/// shaping 缓存 key 直接携带 `Rc<str>` + 区间 → 命中路径零字符串分配;
913/// 区间越界/落在字符中间时夹取到合法边界(高亮防抖期间 span 可能滞后于文档)。
914#[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
940/// 文本首行字体 ascent(逻辑像素)。
941///
942/// 语法高亮按 span 分别绘制时,不同 fallback 字体(中文 vs 拉丁)的 ascent
943/// 不同;直接把同一个 y 传给每个 span 会让基线错位。调用方用
944/// `origin.y + (canonical - span_ascent)` 对齐到同一条基线。
945pub 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
956/// 共享整串 + 区间的首行字体 ascent(逻辑像素)。
957/// 与 `paint_text_span` 使用同一 shape 缓存 key,不产生额外 shaping。
958pub 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
984/// 把字节区间夹到 `text` 的合法字符边界内(滞后 span 防御)
985fn 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/// paint 共享实现(公开 API 的字体栈/key 在此收敛)
1001#[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        // ===== Step 1:栅格化 + 锚定 =====
1021        // 首行视觉顶 = baseline - ascent — 锚定 offset.y 到视觉顶
1022        // 后续行用各自的 baseline 差保持行距(parley 自动给 baseline 间距)
1023        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; // 首行视觉顶(物理像素)
1030
1031        let mut max_x = 0.0f32;
1032        for run in &shaped.runs {
1033            for sg in &run.glyphs {
1034                // 栅格化通常在 shape_text 完成;若位图被预算淘汰,这里用 run 携带的
1035                // 字体上下文按需重建(line cache 命中时不会再走 shape_text)。
1036                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                // 性能:禁止 clone RasterGlyph(位图 Vec<u8> 每 glyph 每帧全量克隆,
1044                // 编辑器大文本量 3000+ glyph/帧 时是首要 CPU 热点)——
1045                // raster_cache(&mut)与 atlas(&mut)是 disjoint 字段借用,可零拷贝共存。
1046                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                // x = offset + (pen_x + placement_left) / dpr
1057                let x = offset.x + (sg.x + r.left as f32) / dpr;
1058                // y = offset + (glyph_visual_top - anchor) / dpr
1059                //   glyph_visual_top = baseline_y - ascent_of_this_glyph_row + placement_top
1060                //   但 run 级 ascent 与 glyph 级栅格化的 placement.top 可能不同,
1061                //   所以用 run.baseline_y - placement.top 作为 glyph 在 layout 内的视觉顶
1062                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
1084/// 测单行文本每个字符的起始 x(前缀宽度,逻辑像素)
1085///
1086/// 编辑器光标/选区的字节偏移 ↔ x 坐标换算用:
1087/// - 返回 `vec.len() == char_count + 1`
1088/// - `widths[i]` = 第 i 个字符的**起始** x(= 前 i 个字符的前缀宽度)
1089/// - `widths[char_count]` = 整行宽度
1090/// - 光标落在字符 i 前 → `x = widths[i]`;选区 `[a, b)` → `[widths[a], widths[b])`
1091/// - 无 glyph 的字符(合字/零宽)沿用前一个字符的起始 x
1092/// - 空文本返回 `vec![0.0]`
1093///
1094/// 单行 shape(不换行);多行文本请按行分别调用。
1095/// soft wrap 后的视觉行字节区间(相对传入文本)。
1096///
1097/// TextField 用它对每条硬换行行做布局映射;空文本返回 `[(0, 0)]`。
1098pub 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        // cluster 起始字节 → 该 cluster 首个 glyph 的 x(物理像素);
1126        // 合字/组合序列的多个 glyph 同属一个 cluster,只记首 glyph 位置
1127        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        // 前缀宽度(逻辑像素):字符 i 的起始 x = 最后一个 cluster 起始字节 ≤
1138        // 该字符字节位置的 glyph x;落单字符(无 glyph)沿用前值
1139        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
1153/// 从 parley Font 拿原始 bytes,栅格化一个 glyph
1154fn 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    // parley::Font = peniko::Font = FontData { data: Blob<u8>, index: u32 }
1162    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        // 零尺寸 glyph(空格等无 ink 字符)必须缓存占位:直接返回 None 会让
1177        // 每次 shape/paint 都重新走 swash(实测一次 ~80µs,而空格占代码行
1178        // 多数 glyph)—— 100k 行滚动实测每行 15 次 miss 几乎全是空格。
1179        // paint 见到 width/height == 0 直接跳过,不会进 atlas。
1180        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        // 自动 soft wrap:非显式 max_width 时用当前约束刷新。
1195        // 单行 TextWidget 不应被 Flex 的 BoxConstraints 给误开 soft-wrap —— 但 Button 的
1196        // tight constraint(明确是要约束内容)仍应传递。区分:explicit max_width 不覆盖。
1197        // if !self.max_width_explicit {
1198        //     self.max_width = if bc.max_width.is_finite() && bc.max_width > 0.0 {
1199        //         Some(bc.max_width)
1200        //     } else {
1201        //         None
1202        //     };
1203        // }
1204        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        // bugfix(双击标题无效):文本默认不参与 hit_test → 点击标题落穿,
1223        // 事件冒泡链上没有 GestureDetector,双击永远无法识别。
1224        // 文本整块 layout 尺寸作为命中区。
1225        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// =============================================================================
1235// 测试
1236// =============================================================================
1237
1238#[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        // 第一个 16x4 占了 row 0
1260        let k1 = mk_key(1);
1261        a.get_or_insert(k1, &[1; 64], 16, 4);
1262        // 第二个 16x4 必须换行(放不下 16+padding)
1263        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        // 新建 atlas 不脏
1272        assert!(!a.is_dirty());
1273        // 写入后变脏
1274        a.get_or_insert(mk_key(1), &[255; 8], 2, 4);
1275        assert!(a.is_dirty(), "get_or_insert 后应该 dirty");
1276        // 清掉 dirty
1277        a.clear_dirty();
1278        assert!(!a.is_dirty());
1279        // 重复 key 不重新写入,不触发 dirty
1280        a.get_or_insert(mk_key(1), &[0; 8], 2, 4);
1281        assert!(!a.is_dirty(), "重复 key 不应触发 dirty");
1282        // 新 key 再次 dirty
1283        a.get_or_insert(mk_key(2), &[0; 8], 2, 4);
1284        assert!(a.is_dirty());
1285    }
1286
1287    /// GPU 上传只覆盖本次写入的行区间:避免每写一个 glyph 就整张拷贝/上传
1288    /// (4096² = 16 MiB,8192² 封顶时 64 MiB)。
1289    #[test]
1290    fn atlas_snapshot_uploads_only_dirty_rows() {
1291        // 每个测试线程有独立 FontState;先复位 atlas 排除前序 shape 的条目
1292        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    /// atlas 自动扩容:塞满 32×32 小 atlas,不应 panic,而是自动扩到 64×64
1313    #[test]
1314    fn atlas_auto_expands_when_full() {
1315        let mut a = Atlas::new(32, 32);
1316        // 先塞 1 个 glyph 当参照(记录它的 uv,扩容后要能除以 2)
1317        let e_before = a.get_or_insert(mk_key(1), &[100; 9], 3, 3);
1318        let uv_scalar_before = e_before.uv[0]; // 单轴归一化值
1319
1320        // 塞满 atlas — 每行放 14×14 的 glyph(= 196px + padding),大约 2 行就满
1321        // 用大 glyph 加速测试:20×20 会每行只能放 1 个,很快就触发扩容
1322        let big: Vec<u8> = vec![200; 400]; // 20×20
1323        for i in 2..10 {
1324            a.get_or_insert(mk_key(i), &big, 20, 20);
1325        }
1326        // 不该 panic,如果没扩容,最多只能放 ~3 个 20×20 glyph
1327        assert!(a.width >= 32, "atlas 应保持原尺寸或扩容");
1328        assert!(a.glyph_count() >= 8, "扩容后应能放下 8+ glyphs,实际 {}", a.glyph_count());
1329
1330        // 扩容了(至少一次):参照 glyph 的 uv 应该被缩放
1331        if a.width > 32 {
1332            // 新 atlas 宽度翻倍到 64,所以原 uv 应该 ≈ 原来的一半
1333            let e_after = a.get_or_insert(mk_key(1), &[0; 9], 3, 3);
1334            // 归一化坐标用像素位置 / atlas.width 计算,
1335            // 扩容把 width 翻倍,所以原像素位置的 uv 值 = 旧值 / 2
1336            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    /// 边界:扩容后新 glyph 继续能放下
1342    #[test]
1343    fn atlas_accepts_new_glyphs_after_expansion() {
1344        let mut a = Atlas::new(16, 16);
1345        // 先塞一个 12×12 的,占满 atlas 高度
1346        a.get_or_insert(mk_key(1), &[50; 144], 12, 12);
1347        // 再塞一个 12×12 的 — 会扩容(不能放同一行也没换行空间)
1348        let e2 = a.get_or_insert(mk_key(2), &[100; 144], 12, 12);
1349        assert!(a.width > 16 || a.height > 16, "应该扩容了");
1350        // 第二次的 uv.v0 应该 > 第一次(换到第二行)
1351        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        // "Hi" 2 个 ASCII 字符,应该 2 个 TexturedRect
1369        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        // 所有 rect 的 x/y 应该 >= offset
1388        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    /// 缓存命中:同一文本第二次 paint 不再 shape(输出仍一致)
1397    #[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    /// 防膨胀:超过 LINE_CACHE_LIMIT 时按 LRU 回收,热条目保留
1412    #[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            // 最旧条目刚被重新访问 → 淘汰时必须保留
1431            fs.line_clock += 1;
1432            fs.line_cache.get_mut(&hot_key).expect("hot entry").last_used = fs.line_clock;
1433        });
1434        // 新 paint 触发超限回收
1435        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    /// 位图被预算淘汰后,线缓存命中时 paint 路径必须能按需重建 glyph。
1447    #[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    /// 零尺寸 glyph(空格等)也必须进 raster_cache:否则每次 shape 都重新
1465    /// 走 swash 栅格化(实测一次 ~80µs),代码行里空格占多数 glyph →
1466    /// 快速滚动时每行十几毫秒的重复栅格化。
1467    #[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            // 新文本行(line cache miss)必须重新 shape:只有新字符 'd' 需要
1479            // 栅格化,空格不得再次进入栅格化流程
1480            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    /// glyph 位图缓存超预算时按 LRU 回收到目标水位。
1488    #[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            // 5 × 8 MiB 超过 32 MiB 预算 → 淘汰最旧的两条,保留 3 × 8 MiB。
1502            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    /// DPR 栅格化:rect 逻辑尺寸 dpr 无关;atlas 位图分辨率随 dpr 翻倍;
1512    /// paint 返回宽度与 measure_text_width 一致(TextField 光标定位依赖)
1513    #[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); // 恢复默认,避免污染其它测试
1524            (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        // 物理像素取整会让逻辑宽度差 1px(macOS 实测 dpr1=15 / dpr2=14),允许 ≤2px
1531        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
1539// =============================================================================
1540// RTL(P3-5b):方向判定 + 方向感知的光标位置
1541// =============================================================================
1542
1543/// 文本主方向是否 RTL(首个强方向字符决定;无强方向字符按 LTR)。
1544pub 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   // Hebrew
1550            | 0x0600..=0x06FF // Arabic
1551            | 0x0700..=0x074F // Syriac
1552            | 0x0750..=0x077F // Arabic Supplement
1553            | 0x0780..=0x07BF // Thaana
1554            | 0x0860..=0x086F // Syriac Supplement
1555            | 0x08A0..=0x08FF // Arabic Extended-A
1556            | 0xFB1D..=0xFB4F // Hebrew presentation
1557            | 0xFB50..=0xFDFF // Arabic presentation A
1558            | 0xFE70..=0xFEFF // Arabic presentation B
1559        );
1560        if rtl {
1561            return true;
1562        }
1563        if ch.is_alphabetic() {
1564            return false;
1565        }
1566    }
1567    false
1568}
1569
1570/// 把 LTR 前缀宽度表镜像为 RTL 光标表(纯函数,便于测试)。
1571///
1572/// 输入 `widths[i]` = 第 i 个字符的左缘 x(末项为整行宽)。
1573/// RTL 视觉顺序相反:`carets[0]` = 整行宽(最右),`carets[n]` = 最左字符左缘(≈0),
1574/// `carets[c] = widths[c-1]`。混合双向文本按首强方向整体镜像。
1575pub 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
1586/// 方向感知的光标 x 表(逻辑字符边界,长度 = char_count + 1,单位逻辑像素)。
1587pub 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
1596/// 光标表中离 `x` 最近的逻辑位置(LTR/RTL 通用;距离相同取较小下标)。
1597pub 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 مرحبا")); // 首个强字符是拉丁
1615        assert!(!is_rtl_text("123 !?"));
1616        assert!(is_rtl_text("123 مرحبا")); // 数字无方向,首个字母决定
1617    }
1618
1619    #[test]
1620    fn rtl_caret_mirroring_and_nearest_index() {
1621        // 合成宽度:3 个字符,起点 0/10/25,整行 40
1622        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        // LTR 表保持不变
1629        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// =============================================================================
1635// 富文本(P3-3 第一切片):同一段落内混排字号 / 颜色 / 字体栈
1636// =============================================================================
1637
1638/// 富文本样式 span。颜色只影响绘制,不参与 shape 缓存 key。
1639#[derive(Clone, Debug, PartialEq)]
1640pub struct RichTextSpan {
1641    pub text: String,
1642    pub size_px: f32,
1643    pub color: Color,
1644    /// None = [`DEFAULT_FONT_STACK`]
1645    pub font_stack: Option<String>,
1646}
1647
1648impl RichTextSpan {
1649    pub fn new(text: impl Into<String>) -> Self {
1650        Self { text: text.into(), size_px: 15.0, color: Color::WHITE, font_stack: None }
1651    }
1652
1653    pub fn with_size(mut self, size_px: f32) -> Self {
1654        self.size_px = size_px;
1655        self
1656    }
1657
1658    pub fn with_color(mut self, color: Color) -> Self {
1659        self.color = color;
1660        self
1661    }
1662
1663    pub fn with_font_stack(mut self, stack: impl Into<String>) -> Self {
1664        self.font_stack = Some(stack.into());
1665        self
1666    }
1667}
1668
1669/// 内联项绘制回调(逻辑坐标 rect,相对 RichText 原点)。
1670pub type InlinePainter = std::rc::Rc<dyn Fn(&mut PaintList, Rect)>;
1671
1672/// 内联项:固定尺寸、底部对齐到文本基线,绘制由调用方回调完成(绘制型,无命中/状态)。
1673#[derive(Clone)]
1674pub struct InlineItem {
1675    pub width: f32,
1676    pub height: f32,
1677    pub painter: InlinePainter,
1678}
1679
1680impl InlineItem {
1681    pub fn new(width: f32, height: f32, painter: impl Fn(&mut PaintList, Rect) + 'static) -> Self {
1682        Self { width, height, painter: std::rc::Rc::new(painter) }
1683    }
1684}
1685
1686impl std::fmt::Debug for InlineItem {
1687    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1688        f.debug_struct("InlineItem").field("width", &self.width).field("height", &self.height).finish()
1689    }
1690}
1691
1692impl PartialEq for InlineItem {
1693    fn eq(&self, other: &Self) -> bool {
1694        self.width == other.width && self.height == other.height && std::rc::Rc::ptr_eq(&self.painter, &other.painter)
1695    }
1696}
1697
1698/// 富文本 item:文本 span 或内联绘制项。
1699#[derive(Clone, Debug, PartialEq)]
1700pub enum RichItem {
1701    Text(RichTextSpan),
1702    Inline(InlineItem),
1703}
1704
1705/// 预处理后的富文本:拼接文本 + 文本 span 的字节区间 + 内联项(一次构造,多次测量/绘制)。
1706#[derive(Clone, Debug, PartialEq)]
1707pub struct RichText {
1708    text: std::rc::Rc<str>,
1709    spans: Vec<RichTextSpan>,
1710    ranges: Vec<(usize, usize)>,
1711    /// (字节偏移, 内联项);offset 即内联项在文本流中的位置
1712    inlines: Vec<(usize, InlineItem)>,
1713}
1714
1715impl RichText {
1716    pub fn new(spans: Vec<RichTextSpan>) -> Self {
1717        Self::from_items(spans.into_iter().map(RichItem::Text).collect())
1718    }
1719
1720    pub fn from_items(items: Vec<RichItem>) -> Self {
1721        let mut text = String::new();
1722        let mut spans = Vec::new();
1723        let mut ranges = Vec::new();
1724        let mut inlines = Vec::new();
1725        for item in items {
1726            match item {
1727                RichItem::Text(span) => {
1728                    let start = text.len();
1729                    text.push_str(&span.text);
1730                    spans.push(span);
1731                    ranges.push((start, text.len()));
1732                }
1733                RichItem::Inline(inline) => inlines.push((text.len(), inline)),
1734            }
1735        }
1736        Self { text: text.into(), spans, ranges, inlines }
1737    }
1738
1739    /// 纯文本(a11y label / 测试断言用;内联项不含文本)
1740    pub fn plain_text(&self) -> &str {
1741        &self.text
1742    }
1743
1744    pub fn spans(&self) -> &[RichTextSpan] {
1745        &self.spans
1746    }
1747
1748    pub fn is_empty(&self) -> bool {
1749        self.text.is_empty() && self.inlines.is_empty()
1750    }
1751}
1752
1753struct RichShapedGlyph {
1754    raster_key: GlyphKey,
1755    glyph_id: u16,
1756    x: f32,
1757    /// 所属 span 下标(绘制时取 color)
1758    span: u16,
1759}
1760
1761struct RichShapedRun {
1762    glyphs: Vec<RichShapedGlyph>,
1763    baseline_y: f32,
1764    /// 本 run 的字体 ascent(混合字号时首行视觉顶取最大值)
1765    ascent: f32,
1766    font: parley::Font,
1767    norm_coords: std::rc::Rc<[swash::NormalizedCoord]>,
1768    raster_size: f32,
1769}
1770
1771/// 布局后的内联项(parley 逻辑坐标,绘制时 ×dpr 再减锚点)
1772struct RichInlineBox {
1773    /// 对应 `rich.inlines` 下标
1774    id: u16,
1775    x: f32,
1776    y: f32,
1777    width: f32,
1778    height: f32,
1779    /// 所在行的基线(物理像素),用于首行视觉顶计算
1780    line_baseline: f32,
1781}
1782
1783struct RichShapedLine {
1784    runs: Vec<RichShapedRun>,
1785    inline_boxes: Vec<RichInlineBox>,
1786    max_x: f32,
1787    max_y: f32,
1788}
1789
1790#[derive(Clone, PartialEq, Eq, Hash)]
1791struct RichCacheKey {
1792    text: std::rc::Rc<str>,
1793    /// (start, end, size_bits, font_stack_hash)
1794    styles: Vec<(usize, usize, u32, u64)>,
1795    /// (byte index, width_bits, height_bits)
1796    inlines: Vec<(usize, u32, u32)>,
1797    width_bits: Option<u32>,
1798    dpr_bits: u32,
1799}
1800
1801struct RichCacheEntry {
1802    line: std::rc::Rc<RichShapedLine>,
1803    last_used: u64,
1804}
1805
1806fn rich_style_signature(rich: &RichText) -> Vec<(usize, usize, u32, u64)> {
1807    rich.ranges
1808        .iter()
1809        .zip(&rich.spans)
1810        .map(|((start, end), span)| {
1811            let stack = span.font_stack.as_deref().unwrap_or(DEFAULT_FONT_STACK);
1812            let mut h = DefaultHasher::new();
1813            stack.hash(&mut h);
1814            (*start, *end, span.size_px.max(1.0).to_bits(), h.finish())
1815        })
1816        .collect()
1817}
1818
1819fn span_index_at(ranges: &[(usize, usize)], byte: usize) -> u16 {
1820    ranges.iter().position(|(start, end)| byte >= *start && byte < *end).unwrap_or(0) as u16
1821}
1822
1823/// 富文本 shaping(带缓存):混排 span 用 parley ranged style,字号/字体栈逐 span 生效。
1824fn shape_rich(fs: &mut FontState, rich: &RichText, max_width_px: Option<f32>) -> std::rc::Rc<RichShapedLine> {
1825    let dpr = text_dpr();
1826    let key = RichCacheKey {
1827        text: std::rc::Rc::clone(&rich.text),
1828        styles: rich_style_signature(rich),
1829        inlines: rich
1830            .inlines
1831            .iter()
1832            .map(|(index, inline)| (*index, inline.width.to_bits(), inline.height.to_bits()))
1833            .collect(),
1834        width_bits: max_width_px.map(|w| w.to_bits()),
1835        dpr_bits: dpr.to_bits(),
1836    };
1837    if let Some(entry) = fs.rich_cache.get_mut(&key) {
1838        fs.rich_clock += 1;
1839        entry.last_used = fs.rich_clock;
1840        return std::rc::Rc::clone(&entry.line);
1841    }
1842
1843    let text: &str = &rich.text;
1844    let mut builder = fs.layout_cx.ranged_builder(&mut fs.font_cx, text, 1.0, true);
1845    builder.push_default(parley::StyleProperty::FontSize(15.0));
1846    builder.push_default(parley::StyleProperty::LineHeight(1.2));
1847    builder.push_default(parley::StyleProperty::FontStack(parley::FontStack::Source(std::borrow::Cow::Borrowed(
1848        DEFAULT_FONT_STACK,
1849    ))));
1850    builder.push_default(parley::StyleProperty::WordBreak(parley::swash::text::WordBreakStrength::KeepAll));
1851    builder.push_default(parley::StyleProperty::OverflowWrap(parley::OverflowWrap::Anywhere));
1852    for ((start, end), span) in rich.ranges.iter().zip(&rich.spans) {
1853        if span.size_px > 0.0 {
1854            builder.push(parley::StyleProperty::FontSize(span.size_px), *start..*end);
1855        }
1856        if let Some(stack) = &span.font_stack {
1857            builder.push(
1858                parley::StyleProperty::FontStack(parley::FontStack::Source(std::borrow::Cow::Borrowed(stack))),
1859                *start..*end,
1860            );
1861        }
1862    }
1863    for (id, (index, inline)) in rich.inlines.iter().enumerate() {
1864        builder.push_inline_box(parley::InlineBox {
1865            id: id as u64,
1866            index: *index,
1867            width: inline.width,
1868            height: inline.height,
1869        });
1870    }
1871    let mut layout: parley::Layout<()> = builder.build(text);
1872    let wrap_opt = max_width_px.filter(|w| *w > 0.0);
1873    layout.break_all_lines(wrap_opt);
1874    layout.align(wrap_opt, parley::Alignment::Start, parley::AlignmentOptions::default());
1875
1876    let mut runs = Vec::new();
1877    let mut inline_boxes = Vec::new();
1878    let mut max_x = 0.0f32;
1879    let mut max_y = 0.0f32;
1880    for line in layout.lines() {
1881        let line_m = line.metrics();
1882        let baseline_y = line_m.baseline * dpr;
1883        for item in line.items() {
1884            let parley::PositionedLayoutItem::GlyphRun(gr) = item else {
1885                if let parley::PositionedLayoutItem::InlineBox(b) = item {
1886                    inline_boxes.push(RichInlineBox {
1887                        id: b.id as u16,
1888                        x: b.x,
1889                        y: b.y,
1890                        width: b.width,
1891                        height: b.height,
1892                        line_baseline: baseline_y,
1893                    });
1894                    max_x = max_x.max((b.x + b.width) * dpr);
1895                    max_y = max_y.max((b.y + b.height) * dpr);
1896                }
1897                continue;
1898            };
1899            let run_metrics = gr.run().metrics();
1900            let ascent = run_metrics.ascent * dpr;
1901            let descent = run_metrics.descent * dpr;
1902            let font_size_phys = gr.run().font_size() * dpr;
1903            let font_blob_id = gr.run().font().data.id() as usize;
1904            let norm_coords: std::rc::Rc<[swash::NormalizedCoord]> = gr.run().normalized_coords().to_vec().into();
1905            let run_font = gr.run().font().clone();
1906            let mut pen_x = gr.offset();
1907            let mut run_glyphs = Vec::new();
1908            for cluster in gr.run().visual_clusters() {
1909                let cluster_byte = cluster.text_range().start;
1910                let span = span_index_at(&rich.ranges, cluster_byte);
1911                for g in cluster.glyphs() {
1912                    let raster_key = GlyphKey::new(font_blob_id, g.id, font_size_phys.to_bits(), 0, 0, 0);
1913                    if !fs.raster_cache.contains_key(&raster_key) {
1914                        if let Some(rg) =
1915                            rasterize_one_glyph(&run_font, font_size_phys, g.id, &norm_coords, &mut fs.scale_cx)
1916                        {
1917                            insert_raster_glyph(fs, raster_key, rg);
1918                        }
1919                    }
1920                    let gx = pen_x + g.x;
1921                    run_glyphs.push(RichShapedGlyph { raster_key, glyph_id: g.id, x: gx * dpr, span });
1922                    max_x = max_x.max((gx + g.advance) * dpr);
1923                    max_y = max_y.max(baseline_y + descent);
1924                    pen_x += g.advance;
1925                }
1926            }
1927            if !run_glyphs.is_empty() {
1928                runs.push(RichShapedRun {
1929                    glyphs: run_glyphs,
1930                    baseline_y,
1931                    ascent,
1932                    font: run_font,
1933                    norm_coords,
1934                    raster_size: font_size_phys,
1935                });
1936            }
1937        }
1938    }
1939    if max_y == 0.0 {
1940        max_y = rich.spans.iter().map(|s| s.size_px).fold(15.0, f32::max) * 1.2 * dpr;
1941    }
1942
1943    let line = std::rc::Rc::new(RichShapedLine { runs, inline_boxes, max_x, max_y });
1944    if fs.rich_cache.len() >= LINE_CACHE_LIMIT {
1945        fs.rich_cache.clear();
1946    }
1947    fs.rich_clock += 1;
1948    fs.rich_cache.insert(key, RichCacheEntry { line: std::rc::Rc::clone(&line), last_used: fs.rich_clock });
1949    line
1950}
1951
1952/// 测量富文本(逻辑像素)。`max_width` = soft wrap 宽度上限。
1953pub fn rich_text_size(rich: &RichText, max_width: Option<f32>) -> Size {
1954    if rich.is_empty() {
1955        return Size::ZERO;
1956    }
1957    with_font(|fs| {
1958        let dpr = text_dpr();
1959        let shaped = shape_rich(fs, rich, max_width);
1960        let first_baseline = shaped.runs.first().map(|r| r.baseline_y);
1961        let (anchor, fallback_h) = match first_baseline {
1962            Some(baseline) => {
1963                // 首行视觉顶 = baseline − 首行最大 ascent;内联项更高时取内联项顶部
1964                let first_ascent =
1965                    shaped.runs.iter().filter(|r| r.baseline_y == baseline).map(|r| r.ascent).fold(0.0f32, f32::max);
1966                let inline_top = shaped
1967                    .inline_boxes
1968                    .iter()
1969                    .filter(|b| b.line_baseline == baseline)
1970                    .map(|b| b.y * dpr)
1971                    .fold(f32::INFINITY, f32::min);
1972                // 布局坐标中的视觉顶:字形顶与内联项顶取更小者
1973                ((baseline - first_ascent).min(inline_top), 0.0)
1974            }
1975            None => (0.0, shaped.max_y),
1976        };
1977        let height = if shaped.max_y > anchor { (shaped.max_y - anchor) / dpr } else { fallback_h / dpr };
1978        Size::new(shaped.max_x / dpr, height)
1979    })
1980}
1981
1982/// 富文本布局结果:整体尺寸 + 每个内联项的相对矩形(逻辑像素,原点 = 文本视觉左上)。
1983#[derive(Clone, Debug, PartialEq)]
1984pub struct RichTextLayout {
1985    pub size: Size,
1986    pub inline_rects: Vec<Rect>,
1987}
1988
1989/// 仅布局:供交互型内联 Widget 定位子元素(不绘制)。
1990pub fn rich_text_layout(rich: &RichText, max_width: Option<f32>) -> RichTextLayout {
1991    if rich.is_empty() {
1992        return RichTextLayout { size: Size::ZERO, inline_rects: Vec::new() };
1993    }
1994    with_font(|fs| {
1995        let dpr = text_dpr();
1996        let shaped = shape_rich(fs, rich, max_width);
1997        let first_baseline = shaped.runs.first().map(|r| r.baseline_y);
1998        let anchor = match first_baseline {
1999            Some(baseline) => {
2000                let first_ascent =
2001                    shaped.runs.iter().filter(|r| r.baseline_y == baseline).map(|r| r.ascent).fold(0.0f32, f32::max);
2002                let inline_top = shaped
2003                    .inline_boxes
2004                    .iter()
2005                    .filter(|b| b.line_baseline == baseline)
2006                    .map(|b| b.y * dpr)
2007                    .fold(f32::INFINITY, f32::min);
2008                (baseline - first_ascent).min(inline_top)
2009            }
2010            None => 0.0,
2011        };
2012        let height = if shaped.max_y > anchor { (shaped.max_y - anchor) / dpr } else { 0.0 };
2013        let mut inline_rects = vec![Rect::new(0.0, 0.0, 0.0, 0.0); rich.inlines.len()];
2014        for b in &shaped.inline_boxes {
2015            if let Some(slot) = inline_rects.get_mut(b.id as usize) {
2016                *slot = Rect::new(b.x, (b.y * dpr - anchor) / dpr, b.width, b.height);
2017            }
2018        }
2019        RichTextLayout { size: Size::new(shaped.max_x / dpr, height), inline_rects }
2020    })
2021}
2022
2023/// 绘制富文本,返回最大行宽(逻辑像素)。
2024pub fn paint_rich_text(rich: &RichText, offset: Point, list: &mut PaintList, max_width: Option<f32>) -> f32 {
2025    if rich.is_empty() {
2026        return 0.0;
2027    }
2028    with_font(|fs| {
2029        let dpr = text_dpr();
2030        let shaped = shape_rich(fs, rich, max_width);
2031        let Some(first_run) = shaped.runs.first() else {
2032            return 0.0;
2033        };
2034        let first_baseline = first_run.baseline_y;
2035        let first_ascent =
2036            shaped.runs.iter().filter(|r| r.baseline_y == first_baseline).map(|r| r.ascent).fold(0.0f32, f32::max);
2037        let inline_top = shaped
2038            .inline_boxes
2039            .iter()
2040            .filter(|b| b.line_baseline == first_baseline)
2041            .map(|b| b.y * dpr)
2042            .fold(f32::INFINITY, f32::min);
2043        let anchor = (first_baseline - first_ascent).min(inline_top);
2044
2045        for run in &shaped.runs {
2046            for sg in &run.glyphs {
2047                if !fs.raster_cache.contains_key(&sg.raster_key) {
2048                    if let Some(rg) =
2049                        rasterize_one_glyph(&run.font, run.raster_size, sg.glyph_id, &run.norm_coords, &mut fs.scale_cx)
2050                    {
2051                        insert_raster_glyph(fs, sg.raster_key, rg);
2052                    }
2053                }
2054                let Some(r) = fs.raster_cache.get_mut(&sg.raster_key) else {
2055                    continue;
2056                };
2057                if r.width == 0 || r.height == 0 {
2058                    continue;
2059                }
2060                fs.glyph_clock += 1;
2061                r.last_used = fs.glyph_clock;
2062                let entry = fs.atlas.get_or_insert(sg.raster_key, &r.data, r.width, r.height);
2063
2064                let x = offset.x + (sg.x + r.left as f32) / dpr;
2065                let glyph_visual_top = run.baseline_y - r.top as f32;
2066                let y = offset.y + (glyph_visual_top - anchor) / dpr;
2067                let rect = Rect::new(x, y, r.width as f32 / dpr, r.height as f32 / dpr);
2068                let color = rich.spans.get(sg.span as usize).map(|s| s.color).unwrap_or(Color::WHITE);
2069                list.push(PaintCommand::TexturedRect {
2070                    rect,
2071                    color,
2072                    uv: entry.uv,
2073                    texture_id: 0,
2074                    mode: mgui_core::paint::TextureMode::Mask,
2075                });
2076            }
2077        }
2078        for b in &shaped.inline_boxes {
2079            if let Some((_, inline)) = rich.inlines.get(b.id as usize) {
2080                let rect = Rect::new(offset.x + b.x, offset.y + b.y - anchor / dpr, b.width, b.height);
2081                (inline.painter)(list, rect);
2082            }
2083        }
2084        shaped.max_x / dpr
2085    })
2086}
2087
2088#[cfg(test)]
2089mod rich_text_tests {
2090    use super::*;
2091
2092    #[test]
2093    fn mixed_styles_measure_and_paint_with_span_colors() {
2094        set_text_dpr(1.0);
2095        let red = Color::from_rgb8(255, 0, 0);
2096        let rich = RichText::new(vec![
2097            RichTextSpan::new("Hello ").with_size(18.0).with_color(Color::WHITE),
2098            RichTextSpan::new("World").with_size(30.0).with_color(red),
2099        ]);
2100        let size = rich_text_size(&rich, None);
2101        assert!(size.width > 0.0, "宽度必须 > 0");
2102        assert!(size.height >= 30.0, "高度应容纳 30px 字号: {size:?}");
2103
2104        let mut list = PaintList::new();
2105        let width = paint_rich_text(&rich, Point::ZERO, &mut list, None);
2106        assert!((width - size.width).abs() < 0.5, "绘制宽度应与测量一致: {width} vs {}", size.width);
2107        let colors: Vec<Color> = list
2108            .commands
2109            .iter()
2110            .filter_map(|c| match c {
2111                PaintCommand::TexturedRect { color, .. } => Some(*color),
2112                _ => None,
2113            })
2114            .collect();
2115        assert!(colors.contains(&Color::WHITE), "应包含第一段白色字形");
2116        assert!(colors.contains(&red), "应包含第二段红色字形");
2117    }
2118
2119    #[test]
2120    fn inline_item_measures_paints_and_sits_on_baseline() {
2121        use std::cell::RefCell;
2122        set_text_dpr(1.0);
2123        let captured: std::rc::Rc<RefCell<Option<Rect>>> = std::rc::Rc::new(RefCell::new(None));
2124        let cap = captured.clone();
2125        let rich = RichText::from_items(vec![
2126            RichItem::Text(RichTextSpan::new("A").with_size(16.0)),
2127            RichItem::Inline(InlineItem::new(30.0, 24.0, move |_list, rect| *cap.borrow_mut() = Some(rect))),
2128            RichItem::Text(RichTextSpan::new("B").with_size(16.0)),
2129        ]);
2130        let size = rich_text_size(&rich, None);
2131        assert!(size.width >= 30.0, "宽度应包含内联项: {size:?}");
2132        assert!(size.height >= 20.0, "高度应容纳内联项: {size:?}");
2133
2134        let mut list = PaintList::new();
2135        let width = paint_rich_text(&rich, Point::new(10.0, 5.0), &mut list, None);
2136        assert!(width >= 30.0);
2137        let rect = captured.borrow().expect("内联项绘制回调应被调用");
2138        assert!((rect.width - 30.0).abs() < 0.01 && (rect.height - 24.0).abs() < 0.01, "{rect:?}");
2139        assert!(rect.x >= 10.0 && rect.y >= 5.0, "内联项应带 offset: {rect:?}");
2140    }
2141
2142    #[test]
2143    fn inline_items_wrap_when_narrow() {
2144        set_text_dpr(1.0);
2145        let rich = RichText::from_items(vec![
2146            RichItem::Inline(InlineItem::new(40.0, 20.0, |_, _| {})),
2147            RichItem::Inline(InlineItem::new(40.0, 20.0, |_, _| {})),
2148        ]);
2149        let one_line = rich_text_size(&rich, None);
2150        let wrapped = rich_text_size(&rich, Some(50.0));
2151        assert!(one_line.width > wrapped.width, "窄宽度应减少行宽: {one_line:?} vs {wrapped:?}");
2152        assert!(
2153            wrapped.height > one_line.height * 1.5,
2154            "两个 40 宽内联项在 50 宽内应换行: {one_line:?} vs {wrapped:?}"
2155        );
2156    }
2157
2158    #[test]
2159    fn soft_wrap_uses_max_width() {
2160        set_text_dpr(1.0);
2161        let rich = RichText::new(vec![RichTextSpan::new("word ".repeat(40)).with_size(16.0)]);
2162        let single = rich_text_size(&rich, None);
2163        let wrapped = rich_text_size(&rich, Some(120.0));
2164        assert!(single.height > 0.0 && wrapped.height > 0.0);
2165        assert!(wrapped.height > single.height * 2.0, "换行后高度应显著增加: {single:?} vs {wrapped:?}");
2166        assert!(wrapped.width <= 130.0, "换行后宽度应受 max_width 约束: {wrapped:?}");
2167    }
2168}
2169
2170// =============================================================================
2171// 多行文本 y 定位回归测试
2172// =============================================================================
2173
2174#[cfg(test)]
2175mod multiline_regression {
2176    use super::*;
2177
2178    /// 显式换行符 → 两行 y 必须不同(修复前:两行 y 相同 → 完全重叠)
2179    #[test]
2180    fn multiline_text_lines_have_distinct_y() {
2181        let mut list = PaintList::new();
2182        paint_text_line("第一行AAA\n第二行BBB", 20.0, Color::WHITE, Point::new(50.0, 100.0), &mut list, None);
2183        let ys: Vec<f32> = list
2184            .commands
2185            .iter()
2186            .filter_map(|c| match c {
2187                PaintCommand::TexturedRect { rect, .. } => Some((rect.y * 10.0).round() / 10.0),
2188                _ => None,
2189            })
2190            .collect();
2191        assert!(!ys.is_empty(), "应画出 glyph");
2192        let y0 = ys[0];
2193        assert!(ys.iter().any(|&y| (y - y0).abs() > 20.0), "多行文本各行 y 必须拉开,实际全部≈{}: {:?}", y0, ys);
2194    }
2195
2196    /// 窄 max_width soft-wrap → 两行同样不能重叠
2197    #[test]
2198    fn wrapped_text_lines_have_distinct_y() {
2199        let mut list = PaintList::new();
2200        // "第一行文本内容比较长" 在 60px 宽下必然折行
2201        paint_text_line(
2202            "第一行文本内容比较长需要折行",
2203            20.0,
2204            Color::WHITE,
2205            Point::new(0.0, 0.0),
2206            &mut list,
2207            Some(60.0),
2208        );
2209        let ys: Vec<f32> = list
2210            .commands
2211            .iter()
2212            .filter_map(|c| match c {
2213                PaintCommand::TexturedRect { rect, .. } => Some((rect.y * 10.0).round() / 10.0),
2214                _ => None,
2215            })
2216            .collect();
2217        let y0 = ys[0];
2218        assert!(ys.iter().any(|&y| (y - y0).abs() > 20.0), "soft-wrap 多行 y 必须拉开,实际全部≈{}: {:?}", y0, ys);
2219    }
2220}