Skip to main content

velox_engine/
text_rich.rs

1//! 现代多字族/字重富文本(`RichText` / `TextSpan`)、Unicode BiDi 双向视觉重排与 OpenType 简易塑形。
2//!
3//! 全模块 100% 无堆兼容,可在所有硬件与桌面目标上直接运行:
4//! - **多字族 / 字重 / 斜体**:[`FontFamily`]、[`FontWeight`]、[`FontStyle`]、[`FontSpec`];
5//! - **行内富文本**:[`TextSpan`]、[`RichTextSpec`]、[`RichText`](支持多色、多字号、多字重、斜体、等宽、
6//!   下划线、删除线、背景高亮、`line_height`、`letter_spacing` 与连字开关);
7//! - **Unicode BiDi(UAX #9 核心视觉重排)**:支持阿拉伯语 / 希伯来语 RTL 段落、数字与拉丁内嵌运行及对称括号镜像;
8//! - **轻量化塑形器(Shaper)**:支持编程连字(`->` / `<-` / `!=` / `<=` / `>=` / `=>`)与组合音标零步进叠加。
9
10use crate::arena::{SmallVec, StrRef};
11use crate::element::{Element, IntoElement};
12use crate::pod::FrameScope;
13use crate::style::{Color, TextAlign};
14
15/// 字体家族枚举(4 字节紧凑表示,支持系统通用族与自定义注册字族)。
16#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Default)]
17pub enum FontFamily {
18    /// 系统默认无衬线 UI 字体(如 Segoe UI / SF Pro / Roboto / Noto Sans)。
19    #[default]
20    Sans,
21    /// 等宽代码字体(如 Consolas / Cascadia Mono / Menlo / DejaVu Sans Mono)。
22    Mono,
23    /// 衬线阅读字体(如 Georgia / Times New Roman / Noto Serif)。
24    Serif,
25    /// 用户通过 `register_font_bytes` 注册的自定义字族 ID。
26    Custom(u16),
27}
28
29impl FontFamily {
30    #[inline(always)]
31    pub const fn tag(self) -> u32 {
32        match self {
33            Self::Sans => 0,
34            Self::Mono => 1,
35            Self::Serif => 2,
36            Self::Custom(id) => 0x1000 | (id as u32),
37        }
38    }
39}
40
41/// 字体字重(对应 CSS `font-weight: 300..=700`)。
42#[repr(u8)]
43#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Default)]
44pub enum FontWeight {
45    Light = 0,
46    #[default]
47    Normal = 1,
48    Medium = 2,
49    SemiBold = 3,
50    Bold = 4,
51}
52
53impl FontWeight {
54    #[inline(always)]
55    pub const fn is_bold(self) -> bool {
56        matches!(self, Self::SemiBold | Self::Bold)
57    }
58}
59
60/// 字体样式(常规 / 斜体)。
61#[repr(u8)]
62#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Default)]
63pub enum FontStyle {
64    #[default]
65    Normal = 0,
66    Italic = 1,
67}
68
69/// 文本装饰线位掩码(下划线 / 删除线)。
70#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Default)]
71pub struct TextDecoration(pub u8);
72
73impl TextDecoration {
74    pub const NONE: Self = Self(0);
75    pub const UNDERLINE: Self = Self(1 << 0);
76    pub const STRIKETHROUGH: Self = Self(1 << 1);
77
78    #[inline(always)]
79    pub const fn union(self, other: Self) -> Self {
80        Self(self.0 | other.0)
81    }
82
83    #[inline(always)]
84    pub const fn has_underline(self) -> bool {
85        (self.0 & Self::UNDERLINE.0) != 0
86    }
87
88    #[inline(always)]
89    pub const fn has_strikethrough(self) -> bool {
90        (self.0 & Self::STRIKETHROUGH.0) != 0
91    }
92}
93
94/// 完整字体匹配规格(字族 + 字重 + 斜体)。
95#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Default)]
96pub struct FontSpec {
97    pub family: FontFamily,
98    pub weight: FontWeight,
99    pub style: FontStyle,
100}
101
102impl FontSpec {
103    pub const SANS: Self = Self {
104        family: FontFamily::Sans,
105        weight: FontWeight::Normal,
106        style: FontStyle::Normal,
107    };
108
109    pub const SANS_BOLD: Self = Self {
110        family: FontFamily::Sans,
111        weight: FontWeight::Bold,
112        style: FontStyle::Normal,
113    };
114
115    pub const SANS_ITALIC: Self = Self {
116        family: FontFamily::Sans,
117        weight: FontWeight::Normal,
118        style: FontStyle::Italic,
119    };
120
121    pub const MONO: Self = Self {
122        family: FontFamily::Mono,
123        weight: FontWeight::Normal,
124        style: FontStyle::Normal,
125    };
126
127    pub const MONO_BOLD: Self = Self {
128        family: FontFamily::Mono,
129        weight: FontWeight::Bold,
130        style: FontStyle::Normal,
131    };
132
133    #[inline(always)]
134    pub const fn custom(id: u16) -> Self {
135        Self {
136            family: FontFamily::Custom(id),
137            weight: FontWeight::Normal,
138            style: FontStyle::Normal,
139        }
140    }
141
142    #[inline(always)]
143    pub const fn weight(mut self, w: FontWeight) -> Self {
144        self.weight = w;
145        self
146    }
147
148    #[inline(always)]
149    pub const fn bold(mut self) -> Self {
150        self.weight = FontWeight::Bold;
151        self
152    }
153
154    #[inline(always)]
155    pub const fn italic(mut self) -> Self {
156        self.style = FontStyle::Italic;
157        self
158    }
159
160    #[inline(always)]
161    pub const fn packed_key(self) -> u32 {
162        (self.family.tag() << 4) | ((self.weight as u32) << 1) | (self.style as u32)
163    }
164}
165
166/// 富文本段落内的单个样式化片段(Span)。
167#[derive(Copy, Clone, PartialEq, Eq, Debug)]
168pub struct TextSpan<'a> {
169    pub text: StrRef<'a>,
170    pub color: Option<Color>,
171    pub bg_color: Option<Color>,
172    pub font_size: Option<u8>,
173    pub font: FontSpec,
174    pub decoration: TextDecoration,
175    /// 字间距增量(单位 `0.25px`,范围 `-32px..+31.75px`)。
176    pub letter_spacing_q4: i8,
177    /// 是否启用编程连字塑形(如 `->` / `!=` / `<=` / `>=` / `=>`)。
178    pub ligatures: bool,
179    /// 可选交互链接 ID(供业务标识可点击超链接片段)。
180    pub link_id: Option<u32>,
181}
182
183impl<'a> TextSpan<'a> {
184    /// 构造默认无覆写样式的文本片段。
185    #[inline(always)]
186    pub fn new(text: impl Into<StrRef<'a>>) -> Self {
187        Self {
188            text: text.into(),
189            color: None,
190            bg_color: None,
191            font_size: None,
192            font: FontSpec::SANS,
193            decoration: TextDecoration::NONE,
194            letter_spacing_q4: 0,
195            ligatures: false,
196            link_id: None,
197        }
198    }
199
200    #[inline(always)]
201    pub const fn color(mut self, c: Color) -> Self {
202        self.color = Some(c);
203        self
204    }
205
206    #[inline(always)]
207    pub const fn bg(mut self, c: Color) -> Self {
208        self.bg_color = Some(c);
209        self
210    }
211
212    #[inline(always)]
213    pub const fn size(mut self, px: u8) -> Self {
214        self.font_size = Some(px);
215        self
216    }
217
218    #[inline(always)]
219    pub const fn font(mut self, font: FontSpec) -> Self {
220        self.font = font;
221        self
222    }
223
224    #[inline(always)]
225    pub const fn bold(mut self) -> Self {
226        self.font.weight = FontWeight::Bold;
227        self
228    }
229
230    #[inline(always)]
231    pub const fn italic(mut self) -> Self {
232        self.font.style = FontStyle::Italic;
233        self
234    }
235
236    #[inline(always)]
237    pub const fn mono(mut self) -> Self {
238        self.font.family = FontFamily::Mono;
239        self
240    }
241
242    #[inline(always)]
243    pub const fn underline(mut self) -> Self {
244        self.decoration = self.decoration.union(TextDecoration::UNDERLINE);
245        self
246    }
247
248    #[inline(always)]
249    pub const fn strikethrough(mut self) -> Self {
250        self.decoration = self.decoration.union(TextDecoration::STRIKETHROUGH);
251        self
252    }
253
254    #[inline(always)]
255    pub const fn letter_spacing_px(mut self, px: f32) -> Self {
256        let q = (px * 4.0) as i32;
257        self.letter_spacing_q4 = if q < -127 {
258            -127
259        } else if q > 127 {
260            127
261        } else {
262            q as i8
263        };
264        self
265    }
266
267    #[inline(always)]
268    pub const fn ligatures(mut self, enable: bool) -> Self {
269        self.ligatures = enable;
270        self
271    }
272
273    #[inline(always)]
274    pub const fn link_id(mut self, id: u32) -> Self {
275        self.link_id = Some(id);
276        self
277    }
278}
279
280/// 富文本段落完整规格(分配于 `ScratchArena`,通过 8B 引用挂入 `DrawPayload::RichText`)。
281#[derive(Copy, Clone, PartialEq, Eq, Debug)]
282pub struct RichTextSpec<'a> {
283    pub spans: &'a [TextSpan<'a>],
284    pub default_color: Color,
285    pub default_font_size: u8,
286    /// 行高百分比(如 `135` 表示 `1.35×` 基准字号,默认 `130`)。
287    pub line_height_pct: u16,
288    pub align: TextAlign,
289    /// 是否以 RTL(右至左)为段落基准方向(自动启用 Unicode BiDi 视觉重排)。
290    pub rtl_paragraph: bool,
291    /// 最大显示行数(`0` 表示不限制)。
292    pub max_lines: u8,
293    /// 是否禁止自动折行。
294    pub nowrap: bool,
295}
296
297impl<'a> RichTextSpec<'a> {
298    #[inline]
299    pub fn mix_hash(&self, h: &mut u32) {
300        let mut mix = |b: u8| {
301            *h ^= b as u32;
302            *h = h.wrapping_mul(0x0100_0193);
303        };
304        for b in self.default_color.0.to_le_bytes() {
305            mix(b);
306        }
307        mix(self.default_font_size);
308        for b in self.line_height_pct.to_le_bytes() {
309            mix(b);
310        }
311        mix(self.align as u8);
312        mix(if self.rtl_paragraph { 1 } else { 0 });
313        mix(self.max_lines);
314        mix(if self.nowrap { 1 } else { 0 });
315        for sp in self.spans {
316            for b in sp.font.packed_key().to_le_bytes() {
317                mix(b);
318            }
319            mix(sp.decoration.0);
320            mix(sp.letter_spacing_q4 as u8);
321            mix(if sp.ligatures { 1 } else { 0 });
322            if let Some(c) = sp.color {
323                mix(1);
324                for b in c.0.to_le_bytes() {
325                    mix(b);
326                }
327            } else {
328                mix(0);
329            }
330            if let Some(c) = sp.bg_color {
331                mix(1);
332                for b in c.0.to_le_bytes() {
333                    mix(b);
334                }
335            } else {
336                mix(0);
337            }
338            mix(sp.font_size.unwrap_or(0));
339            for &b in sp.text.as_str().as_bytes() {
340                mix(b);
341            }
342        }
343    }
344
345    /// 计算基准行高(像素)。
346    #[inline(always)]
347    pub fn line_height_px(&self, max_span_fs: u8) -> i16 {
348        let fs = max_span_fs.max(self.default_font_size).max(8) as i32;
349        let pct = self.line_height_pct.max(100) as i32;
350        ((fs * pct + 50) / 100).max(fs) as i16
351    }
352}
353
354/// 声明式富文本构建器(支持 `rich_text(cx, &[...]).line_height_pct(140).rtl(true)`)。
355#[derive(Copy, Clone, Debug)]
356pub struct RichText<'a> {
357    pub spec: RichTextSpec<'a>,
358}
359
360/// 构造一个行内富文本元素(片段切片分配于当前帧 `ScratchArena`)。
361#[inline]
362pub fn rich_text<'a>(cx: &'a FrameScope, spans: &[TextSpan<'a>]) -> RichText<'a> {
363    let alloc_spans = cx.arena().alloc_iter(spans.iter().copied());
364    RichText {
365        spec: RichTextSpec {
366            spans: alloc_spans,
367            default_color: Color::WHITE,
368            default_font_size: 14,
369            line_height_pct: 135,
370            align: TextAlign::Left,
371            rtl_paragraph: cx.is_rtl(),
372            max_lines: 0,
373            nowrap: false,
374        },
375    }
376}
377
378impl<'a> RichText<'a> {
379    #[inline(always)]
380    pub const fn color(mut self, c: Color) -> Self {
381        self.spec.default_color = c;
382        self
383    }
384
385    #[inline(always)]
386    pub const fn size(mut self, px: u8) -> Self {
387        self.spec.default_font_size = px;
388        self
389    }
390
391    #[inline(always)]
392    pub const fn line_height_pct(mut self, pct: u16) -> Self {
393        self.spec.line_height_pct = pct;
394        self
395    }
396
397    #[inline(always)]
398    pub const fn align(mut self, align: TextAlign) -> Self {
399        self.spec.align = align;
400        self
401    }
402
403    #[inline(always)]
404    pub const fn rtl(mut self, rtl: bool) -> Self {
405        self.spec.rtl_paragraph = rtl;
406        self
407    }
408
409    #[inline(always)]
410    pub const fn max_lines(mut self, n: u8) -> Self {
411        self.spec.max_lines = n;
412        self
413    }
414
415    #[inline(always)]
416    pub const fn nowrap(mut self) -> Self {
417        self.spec.nowrap = true;
418        self
419    }
420}
421
422impl<'a> IntoElement<'a> for RichText<'a> {
423    #[inline]
424    fn into_element(self, cx: &'a FrameScope) -> Element<'a> {
425        let spec_ref = cx.arena().alloc_temp(self.spec);
426        Element::RichText(spec_ref)
427    }
428}
429
430// ============================================================================
431// Unicode BiDi 双向文本视觉重排器(UAX #9 核心子集,零堆分配)
432// ============================================================================
433
434/// 单个 BiDi 字符类别。
435#[derive(Copy, Clone, PartialEq, Eq, Debug)]
436pub enum BidiClass {
437    Ltr,
438    Rtl,
439    Number,
440    Neutral,
441}
442
443/// 判定单个 Unicode 字符是否为强 RTL 字符(阿拉伯语 / 希伯来语 / 叙利亚语等)。
444#[inline]
445pub const fn is_rtl_char(ch: char) -> bool {
446    let cp = ch as u32;
447    (cp >= 0x0590 && cp <= 0x05FF)
448        || (cp >= 0x0600 && cp <= 0x06FF)
449        || (cp >= 0x0750 && cp <= 0x077F)
450        || (cp >= 0x08A0 && cp <= 0x08FF)
451        || (cp >= 0xFB1D && cp <= 0xFDFF)
452        || (cp >= 0xFE70 && cp <= 0xFEFF)
453}
454
455/// 判定字符是否为 Unicode 组合音标(零水平步进,叠加在前一基字符之上)。
456#[inline]
457pub const fn is_combining_mark(ch: char) -> bool {
458    let cp = ch as u32;
459    (cp >= 0x0300 && cp <= 0x036F)
460        || (cp >= 0x1AB0 && cp <= 0x1AFF)
461        || (cp >= 0x20D0 && cp <= 0x20FF)
462        || (cp >= 0xFE20 && cp <= 0xFE2F)
463}
464
465/// 判定字符是否为常见 Emoji 码点(用于触发彩色位图或 Emoji 回退字库)。
466#[inline]
467pub const fn is_emoji_char(ch: char) -> bool {
468    let cp = ch as u32;
469    (cp >= 0x1F300 && cp <= 0x1FAFF)
470        || (cp >= 0x2600 && cp <= 0x27BF)
471        || (cp >= 0x2300 && cp <= 0x23FF)
472}
473
474/// 对 RTL 视觉运行中的对称括号执行 Unicode Bidi_Mirrored 镜像。
475#[inline]
476pub const fn mirror_bidi_char(ch: char) -> char {
477    match ch {
478        '(' => ')',
479        ')' => '(',
480        '[' => ']',
481        ']' => '[',
482        '{' => '}',
483        '}' => '{',
484        '<' => '>',
485        '>' => '<',
486        '«' => '»',
487        '»' => '«',
488        _ => ch,
489    }
490}
491
492#[inline]
493pub const fn classify_bidi_char(ch: char) -> BidiClass {
494    if is_rtl_char(ch) {
495        BidiClass::Rtl
496    } else if ch.is_ascii_digit() {
497        BidiClass::Number
498    } else if ch.is_ascii_alphabetic() || (ch as u32 >= 0x00C0 && !ch.is_whitespace() && !ch.is_ascii_punctuation()) {
499        // CJK / Latin / Cyrillic / Greek 均归为强 LTR
500        if is_rtl_char(ch) {
501            BidiClass::Rtl
502        } else {
503            BidiClass::Ltr
504        }
505    } else {
506        BidiClass::Neutral
507    }
508}
509
510/// 判断字符串是否包含任意强 RTL 字符(纯 LTR 字符串直接走零开销快路径)。
511#[inline]
512pub fn contains_rtl(s: &str) -> bool {
513    s.chars().any(is_rtl_char)
514}
515
516/// 视觉顺序下的单个定向运行段(指向原字符串字节区间 `[start..end]`,`is_rtl` 表示需逐字符逆序绘制并镜像括号)。
517#[derive(Copy, Clone, PartialEq, Eq, Debug)]
518pub struct BidiVisualRun {
519    pub start: usize,
520    pub end: usize,
521    pub is_rtl: bool,
522}
523
524/// 对单行文本执行轻量化 UAX #9 双向视觉重排,返回从左到右绘制顺序的 [`BidiVisualRun`] 列表(无堆)。
525pub fn reorder_bidi_visual(line: &str, base_rtl: bool) -> SmallVec<BidiVisualRun, 32> {
526    let mut runs: SmallVec<BidiVisualRun, 32> = SmallVec::new();
527    if line.is_empty() {
528        return runs;
529    }
530    if !base_rtl && !contains_rtl(line) {
531        let _ = runs.push(BidiVisualRun {
532            start: 0,
533            end: line.len(),
534            is_rtl: false,
535        });
536        return runs;
537    }
538
539    // 1. 按逻辑顺序切分为同向运行(中性字符跟随当前有效方向,数字始终保持 LTR 内部顺序)
540    let mut cur_start = 0usize;
541    let mut cur_rtl = base_rtl;
542    let mut cur_is_num = false;
543    let mut initialized = false;
544
545    for (idx, ch) in line.char_indices() {
546        let cls = classify_bidi_char(ch);
547        let (want_rtl, want_num) = match cls {
548            BidiClass::Rtl => (true, false),
549            BidiClass::Ltr => (false, false),
550            BidiClass::Number => (false, true),
551            BidiClass::Neutral => {
552                if initialized {
553                    if cur_is_num {
554                        (base_rtl, false)
555                    } else {
556                        (cur_rtl, false)
557                    }
558                } else {
559                    (base_rtl, false)
560                }
561            }
562        };
563        if !initialized {
564            cur_start = idx;
565            cur_rtl = want_rtl;
566            cur_is_num = want_num;
567            initialized = true;
568        } else if want_rtl != cur_rtl || want_num != cur_is_num {
569            let _ = runs.push(BidiVisualRun {
570                start: cur_start,
571                end: idx,
572                is_rtl: cur_rtl,
573            });
574            cur_start = idx;
575            cur_rtl = want_rtl;
576            cur_is_num = want_num;
577        }
578    }
579    if initialized && cur_start < line.len() {
580        let _ = runs.push(BidiVisualRun {
581            start: cur_start,
582            end: line.len(),
583            is_rtl: cur_rtl,
584        });
585    }
586
587    // 2. 当基准方向为 RTL 时,整行运行按视觉从左到右逆排(其中 LTR 与 Number 运行内部保持正序)
588    if base_rtl && runs.len() > 1 {
589        let slice = runs.as_mut_slice();
590        slice.reverse();
591    }
592    runs
593}
594
595// ============================================================================
596// 轻量化 OpenType 塑形与编程连字(无堆)
597// ============================================================================
598
599/// 塑形后的单个字形槽位(含原始字符/连字替代字符、是否组合音标零步进)。
600#[derive(Copy, Clone, PartialEq, Eq, Debug)]
601pub struct ShapedGlyph {
602    pub ch: char,
603    pub is_combining: bool,
604    pub byte_offset: usize,
605}
606
607/// 对一段文本执行轻量化塑形(支持可选编程连字映射与组合音标标记)。
608pub fn shape_text_run(text: &str, ligatures: bool) -> SmallVec<ShapedGlyph, 128> {
609    let mut out: SmallVec<ShapedGlyph, 128> = SmallVec::new();
610    let bytes = text.as_bytes();
611    let mut i = 0usize;
612    while i < bytes.len() {
613        if ligatures && i + 1 < bytes.len() {
614            let lig = match (bytes[i], bytes[i + 1]) {
615                (b'-', b'>') => Some('→'),
616                (b'<', b'-') => Some('←'),
617                (b'!', b'=') => Some('≠'),
618                (b'<', b'=') => Some('≤'),
619                (b'>', b'=') => Some('≥'),
620                (b'=', b'>') => Some('⇒'),
621                _ => None,
622            };
623            if let Some(ch) = lig {
624                if !out.push(ShapedGlyph {
625                    ch,
626                    is_combining: false,
627                    byte_offset: i,
628                }) {
629                    break;
630                }
631                i += 2;
632                continue;
633            }
634        }
635        let Some(ch) = text[i..].chars().next() else {
636            break;
637        };
638        if !out.push(ShapedGlyph {
639            ch,
640            is_combining: is_combining_mark(ch),
641            byte_offset: i,
642        }) {
643            break;
644        }
645        i += ch.len_utf8();
646    }
647    out
648}
649
650/// 测量单段富文本单行逻辑像素宽度(支持自定义字族/字重、字距微调与 `letter_spacing`)。
651pub fn measure_rich_text_span_width_f32(span: &TextSpan<'_>, default_fs: u8) -> f32 {
652    let fs = span.font_size.unwrap_or(default_fs).max(8);
653    let ls = (span.letter_spacing_q4 as f32) * 0.25;
654    let shaped = shape_text_run(span.text.as_str(), span.ligatures);
655    let mut total = 0.0f32;
656    let mut prev: Option<char> = None;
657    for g in shaped.as_slice() {
658        if g.is_combining {
659            continue;
660        }
661        if let Some(p) = prev {
662            total += crate::display::measure_char_kerning_f32(p, g.ch, fs);
663            total += ls;
664        }
665        total += crate::display::measure_char_advance_styled_f32(g.ch, fs, span.font);
666        prev = Some(g.ch);
667    }
668    total.max(0.0)
669}
670
671#[inline(always)]
672fn ceil_i16(v: f32) -> i16 {
673    let i = v as i32;
674    let c = if (i as f32) < v { i + 1 } else { i };
675    c.clamp(0, i16::MAX as i32) as i16
676}
677
678/// 测量完整 [`RichTextSpec`] 在给定最大可用宽度下的尺寸 `(width_px, height_px)`。
679pub fn measure_rich_text_box(spec: &RichTextSpec<'_>, max_width: i16) -> (i16, i16) {
680    if spec.spans.is_empty() {
681        return (0, 0);
682    }
683    let avail_w = if spec.nowrap || max_width <= 0 {
684        f32::INFINITY
685    } else {
686        max_width as f32
687    };
688    let mut cur_line_w = 0.0f32;
689    let mut cur_line_max_fs = spec.default_font_size.max(8);
690    let mut max_line_w = 0.0f32;
691    let mut total_h = 0i32;
692    let mut line_count = 1u8;
693
694    for sp in spec.spans {
695        let fs = sp.font_size.unwrap_or(spec.default_font_size).max(8);
696        let ls = (sp.letter_spacing_q4 as f32) * 0.25;
697        let shaped = shape_text_run(sp.text.as_str(), sp.ligatures);
698        let mut prev: Option<char> = None;
699        for g in shaped.as_slice() {
700            if g.ch == '\n' {
701                max_line_w = max_line_w.max(cur_line_w);
702                total_h += spec.line_height_px(cur_line_max_fs) as i32;
703                cur_line_w = 0.0;
704                cur_line_max_fs = spec.default_font_size.max(8);
705                prev = None;
706                line_count = line_count.saturating_add(1);
707                if spec.max_lines > 0 && line_count > spec.max_lines {
708                    return (ceil_i16(max_line_w), total_h.min(i16::MAX as i32) as i16);
709                }
710                continue;
711            }
712            if g.is_combining {
713                continue;
714            }
715            let adv = crate::display::measure_char_advance_styled_f32(g.ch, fs, sp.font)
716                + if prev.is_some() { ls } else { 0.0 };
717            if cur_line_w > 0.0 && cur_line_w + adv > avail_w {
718                max_line_w = max_line_w.max(cur_line_w);
719                total_h += spec.line_height_px(cur_line_max_fs) as i32;
720                cur_line_w = adv;
721                cur_line_max_fs = fs;
722                prev = Some(g.ch);
723                line_count = line_count.saturating_add(1);
724                if spec.max_lines > 0 && line_count > spec.max_lines {
725                    return (ceil_i16(max_line_w), total_h.min(i16::MAX as i32) as i16);
726                }
727            } else {
728                cur_line_w += adv;
729                cur_line_max_fs = cur_line_max_fs.max(fs);
730                prev = Some(g.ch);
731            }
732        }
733    }
734    max_line_w = max_line_w.max(cur_line_w);
735    total_h += spec.line_height_px(cur_line_max_fs) as i32;
736    (
737        ceil_i16(max_line_w),
738        total_h.min(i16::MAX as i32) as i16,
739    )
740}