Skip to main content

mgui_text/
text_field.rs

1//! TextFieldRenderObject — 文本输入框渲染(TextFieldWidget 在 mgui-components)
2//!
3//! 支持硬换行与可选 soft wrap:先按 `\n` 拆硬行,再按可用宽度拆视觉行。
4//! 视觉行布局同时驱动绘制、命中测试、IME 光标定位与内部垂直滚动。
5
6use mgui_core::{
7    BoxConstraints, Color, ElementId, LayoutContext, PaintCommand, PaintList, Point, Rect, RenderObject, Size,
8    StateApply,
9};
10use std::any::Any;
11
12use crate::runtime::current_text_runtime;
13use crate::text::{
14    is_rtl_text, measure_caret_positions, measure_text_width, nearest_caret_index, paint_text_line, text_visual_height,
15    wrapped_line_ranges,
16};
17
18/// 文本区行高与顶部内边距(无 soft wrap 的兼容接口)
19pub fn text_layout_metrics(height: f32, value: &str, font_size: f32) -> (f32, f32) {
20    let first_line = value.split('\n').next().unwrap_or("");
21    let line_h = text_visual_height(first_line, font_size, None);
22    let total_lines = value.split('\n').count().max(1);
23    let top_pad = if total_lines == 1 { (height - line_h).max(0.0) * 0.5 } else { RING_T + 2.0 };
24    (line_h, top_pad)
25}
26
27/// 文本框内边距(水平)
28const PAD_X: f32 = 10.0;
29/// 文本区左边距(供无障碍 TextRun 的 bounds/坐标计算)
30pub const TEXT_PAD_X: f32 = PAD_X;
31/// 光标宽度
32const CURSOR_W: f32 = 1.5;
33/// 焦点环厚度(内嵌,同 Button)
34const RING_T: f32 = 2.0;
35
36/// 一条视觉行(soft wrap 后)
37#[derive(Clone, Copy, Debug, PartialEq, Eq)]
38pub struct TextFieldLine {
39    /// 所属硬行(按 `\n` 拆分)
40    pub hard_line: usize,
41    /// 在 value 中的绝对字节范围 `[start, end)`(不含换行符)
42    pub start: usize,
43    pub end: usize,
44}
45
46/// TextField 的可视布局:视觉行 + 行高/滚动几何
47#[derive(Clone, Debug)]
48pub struct TextFieldLayout {
49    pub lines: Vec<TextFieldLine>,
50    pub line_h: f32,
51    pub top_pad: f32,
52    pub text_width: f32,
53    pub content_height: f32,
54    /// 文本可视区高度(不含上下 padding)
55    pub viewport_height: f32,
56    pub max_scroll: f32,
57    /// 已 clamp 的滚动偏移
58    pub scroll_y: f32,
59}
60
61/// 一条视觉行的无障碍文本数据(AccessKit `TextRun`)。
62///
63/// 硬换行行尾包含 `\n`(AccessKit 要求换行符计入该行字符数);
64/// `character_positions` 相对本行 bounds,RTL 从右缘起算。
65#[derive(Clone, Debug, PartialEq)]
66pub struct TextFieldLineRun {
67    pub value: String,
68    /// 本行首字符在完整 value 中的字符索引
69    pub start_char: usize,
70    /// 相对 TextField 左上角的逻辑像素边界
71    pub bounds: Rect,
72    pub character_positions: Option<Vec<f32>>,
73    pub character_widths: Option<Vec<f32>>,
74    pub rtl: bool,
75}
76
77impl TextFieldLayout {
78    /// 光标落在哪个视觉行:**边界判给下一行**(后行亲和)。
79    ///
80    /// soft wrap 边界那个 byte 同时是上一行的 `end` 与下一行的 `start`(中文每字可断、
81    /// 没有空格可吞时**必然**相等,英文挂尾空格同样相等)。End / Right / ↓ 与光标绘制、
82    /// 滚动定位用这个口径 —— 否则光标停在某行行首时按 End 会被判到上一行,行末就走不过去;
83    /// 绘制按后行也才对得上"在这里输入会落在哪"。Home 用 [`Self::cursor_line_upstream`]。
84    pub fn cursor_line(&self, cursor: usize) -> usize {
85        self.lines.iter().rposition(|line| line.start <= cursor).unwrap_or(0)
86    }
87
88    /// 光标落在哪个视觉行:**边界判给上一行**(前行亲和),目前只有 Home 用。
89    ///
90    /// 光标停在两行共用的边界 byte 上时(按 End 之后就是这个位置),Home 该回到**刚才那一行**
91    /// 的行首;用后行口径会算到下一行,Home 于是"没反应"(Gitee Go 首次 Linux 运行暴露:
92    /// 英文用例在 Windows 上恰好有空格可吞、边界不共享,本地一直测不出来)。
93    /// 硬换行不受影响:下一行 `start = end + 1`,等号取不到。
94    ///
95    /// 已知代价:真正的消歧要**记住光标是怎么走到边界的**(caret affinity 状态),
96    /// 两条口径各自只在半个场景里对。这里按"按键方向"分,换来的是 Home / End 都不空转;
97    /// 代价是"点击落在续行左缘再按 Home"会往上跳一行 —— 留着做光标亲和时一并收口。
98    pub fn cursor_line_upstream(&self, cursor: usize) -> usize {
99        let index = self.cursor_line(cursor);
100        if index > 0 && self.lines[index - 1].end >= cursor {
101            return index - 1;
102        }
103        index
104    }
105
106    pub fn line_text<'a>(&self, value: &'a str, index: usize) -> &'a str {
107        self.lines.get(index).map(|line| &value[line.start.min(value.len())..line.end.min(value.len())]).unwrap_or("")
108    }
109
110    /// 指定行内 byte 位置相对文本区左缘的 x(未加 PAD_X)
111    ///
112    /// 与 [`Self::cursor_x`] 的区别:soft wrap 边界处 byte 同时属于两行,
113    /// 这里强制按调用方指定的行计算(选区逐行高亮必须用这个)。
114    pub fn x_at_in_line(&self, value: &str, line_index: usize, byte: usize, font_size: f32) -> f32 {
115        let Some(line) = self.lines.get(line_index) else {
116            return 0.0;
117        };
118        let end = byte.clamp(line.start, line.end).min(value.len());
119        // 按整行计算光标表(RTL 需要完整行的视觉顺序,不能只看前缀切片)
120        let line_text = &value[line.start.min(value.len())..line.end.min(value.len())];
121        let char_index = value[line.start..end].chars().count();
122        // 光标测量必须与 paint_text_line 用同一字体栈,否则自定义字体下光标与文本错位。
123        let font_stack = current_text_runtime().font_stack();
124        measure_caret_positions(line_text, font_size, &font_stack).get(char_index).copied().unwrap_or(0.0)
125    }
126
127    /// 单行 LTR 文本的逐字符位置/宽度(相对文本区左缘)。
128    ///
129    /// 多行、soft wrap 后多行或 RTL 文本返回 None:AccessKit 的
130    /// character_positions 是单行标量,跨行/RTL 需要拆成多个 TextRun。
131    pub fn single_line_char_positions(&self, value: &str, font_size: f32) -> Option<(Vec<f32>, Vec<f32>)> {
132        if self.lines.len() != 1 {
133            return None;
134        }
135        let line = self.lines[0];
136        let text = &value[line.start.min(value.len())..line.end.min(value.len())];
137        if text.contains('\n') || is_rtl_text(text) {
138            return None;
139        }
140        let font_stack = current_text_runtime().font_stack();
141        let carets = measure_caret_positions(text, font_size, &font_stack);
142        let chars = text.chars().count();
143        if carets.len() < chars + 1 {
144            return None;
145        }
146        let mut positions = Vec::with_capacity(chars);
147        let mut widths = Vec::with_capacity(chars);
148        for i in 0..chars {
149            positions.push(carets[i]);
150            widths.push((carets[i + 1] - carets[i]).max(0.0));
151        }
152        Some((positions, widths))
153    }
154
155    /// 所有视觉行的无障碍 TextRun 数据(多行/RTL 支持)。
156    ///
157    /// 每个视觉行一个 run;硬换行行尾包含 `\n`,`value` 与
158    /// `character_lengths` 的字符数一致。位置相对该行 bounds:
159    /// LTR 从左边距起算,RTL 从右边距起算(AccessKit 约定)。
160    pub fn line_runs(&self, value: &str, font_size: f32) -> Vec<TextFieldLineRun> {
161        let mut runs = Vec::with_capacity(self.lines.len());
162        let mut start_char = 0usize;
163
164        for (index, line) in self.lines.iter().enumerate() {
165            let start = line.start.min(value.len());
166            let end = line.end.min(value.len()).max(start);
167            let text = &value[start..end];
168            let has_break = value.as_bytes().get(end) == Some(&b'\n');
169            let mut run_value = String::with_capacity(text.len() + usize::from(has_break));
170            run_value.push_str(text);
171            if has_break {
172                run_value.push('\n');
173            }
174
175            let rtl = is_rtl_text(text);
176            let chars = text.chars().count();
177            let font_stack = current_text_runtime().font_stack();
178            let carets = measure_caret_positions(text, font_size, &font_stack);
179            let (character_positions, character_widths, line_width) = if carets.len() > chars {
180                let width = if rtl { carets[0] } else { carets[chars] };
181                let mut positions = Vec::with_capacity(chars + usize::from(has_break));
182                let mut widths = Vec::with_capacity(chars + usize::from(has_break));
183                for i in 0..chars {
184                    if rtl {
185                        positions.push((width - carets[i]).max(0.0));
186                        widths.push((carets[i] - carets[i + 1]).max(0.0));
187                    } else {
188                        positions.push(carets[i]);
189                        widths.push((carets[i + 1] - carets[i]).max(0.0));
190                    }
191                }
192                if has_break {
193                    // 换行符不可见:零宽,位置在行末
194                    let break_pos = if rtl { (width - carets[chars]).max(0.0) } else { carets[chars] };
195                    positions.push(break_pos);
196                    widths.push(0.0);
197                }
198                (Some(positions), Some(widths), width.max(0.0))
199            } else {
200                (None, None, 0.0)
201            };
202
203            let y = self.top_pad + index as f32 * self.line_h - self.scroll_y;
204            runs.push(TextFieldLineRun {
205                value: run_value,
206                start_char,
207                bounds: Rect::new(PAD_X, y, line_width, self.line_h),
208                character_positions,
209                character_widths,
210                rtl,
211            });
212            start_char += chars + usize::from(has_break);
213        }
214        runs
215    }
216
217    /// 光标相对文本区左缘的 x(未加 PAD_X)
218    pub fn cursor_x(&self, value: &str, cursor: usize, font_size: f32) -> f32 {
219        self.x_at_in_line(value, self.cursor_line(cursor), cursor, font_size)
220    }
221
222    /// 光标相对 widget 顶部的 y(已含 top_pad 与滚动)
223    pub fn cursor_y(&self, cursor: usize) -> f32 {
224        self.top_pad + self.cursor_line(cursor) as f32 * self.line_h - self.scroll_y
225    }
226
227    /// 把局部坐标映射为 value 字节偏移
228    pub fn offset_at(&self, value: &str, x: f32, y: f32, font_size: f32) -> usize {
229        if self.lines.is_empty() {
230            return 0;
231        }
232        let text_y = y - self.top_pad + self.scroll_y;
233        let index =
234            ((text_y / self.line_h.max(0.001)).floor() as isize).clamp(0, (self.lines.len() - 1) as isize) as usize;
235        let line = self.lines[index];
236        let line_text = &value[line.start..line.end];
237        let font_stack = current_text_runtime().font_stack();
238        let carets = measure_caret_positions(line_text, font_size, &font_stack);
239        let local_x = (x - PAD_X).max(0.0);
240        // LTR/RTL 通用:取距离最近的逻辑光标位(RTL 的光标表为递减)
241        let char_col = nearest_caret_index(&carets, local_x).min(line_text.chars().count());
242        let byte_in_line = line_text.char_indices().nth(char_col).map(|(b, _)| b).unwrap_or(line_text.len());
243        (line.start + byte_in_line).min(value.len())
244    }
245
246    /// 保证 cursor 所在视觉行可见,返回新的 scroll_y
247    pub fn scroll_to_show(&self, cursor: usize) -> f32 {
248        let index = self.cursor_line(cursor);
249        let top = index as f32 * self.line_h;
250        let bottom = top + self.line_h;
251        let scroll = if top < self.scroll_y {
252            top
253        } else if bottom > self.scroll_y + self.viewport_height {
254            bottom - self.viewport_height
255        } else {
256            self.scroll_y
257        };
258        scroll.clamp(0.0, self.max_scroll)
259    }
260}
261
262/// 构建 TextField 视觉行布局(soft wrap 关闭时每条硬行只有一行)
263pub fn text_field_layout(
264    value: &str,
265    width: f32,
266    height: f32,
267    font_size: f32,
268    soft_wrap: bool,
269    scroll_y: f32,
270) -> TextFieldLayout {
271    let text_width = (width - PAD_X * 2.0).max(1.0);
272    let first_line = value.split('\n').next().unwrap_or("");
273    let line_h = text_visual_height(first_line, font_size, None).max(1.0);
274
275    let mut lines = Vec::new();
276    let mut hard_start = 0usize;
277    for (hard_line, hard_text) in value.split('\n').enumerate() {
278        let mut ranges =
279            if soft_wrap { wrapped_line_ranges(hard_text, font_size, text_width) } else { vec![(0, hard_text.len())] };
280        if ranges.is_empty() {
281            ranges.push((0, hard_text.len()));
282        }
283        // 保证覆盖整条硬行(尾随空格可能没有 glyph run)
284        if let Some(first) = ranges.first_mut() {
285            first.0 = 0;
286        }
287        if let Some(last) = ranges.last_mut() {
288            last.1 = hard_text.len().max(last.0);
289        }
290        for (start, end) in ranges {
291            lines.push(TextFieldLine { hard_line, start: hard_start + start, end: hard_start + end });
292        }
293        hard_start += hard_text.len() + 1;
294    }
295    if lines.is_empty() {
296        lines.push(TextFieldLine { hard_line: 0, start: 0, end: 0 });
297    }
298
299    let top_pad = if lines.len() == 1 { ((height - line_h) * 0.5).max(0.0) } else { RING_T + 2.0 };
300    let viewport_height = (height - top_pad * 2.0).max(line_h);
301    let content_height = lines.len() as f32 * line_h;
302    let max_scroll = (content_height - viewport_height).max(0.0);
303    let scroll_y = scroll_y.clamp(0.0, max_scroll);
304
305    TextFieldLayout { lines, line_h, top_pad, text_width, content_height, viewport_height, max_scroll, scroll_y }
306}
307
308// =============================================================================
309// TextFieldRenderObject
310// =============================================================================
311
312pub struct TextFieldRenderObject {
313    pub width: f32,
314    pub height: f32,
315    pub font_size: f32,
316    pub placeholder: String,
317    pub value: String,
318    pub cursor: usize,
319    pub preedit: Option<String>,
320    /// C1:preedit 内光标字节偏移区间
321    pub preedit_cursor: Option<(usize, usize)>,
322    pub focused: bool,
323    /// C1:光标是否可见(闪烁)
324    pub cursor_visible: bool,
325    pub bg_color: Color,
326    pub bg_focused_color: Color,
327    /// 未聚焦时的 1px 描边色(主题 input.border;TRANSPARENT = 不画)
328    pub border_color: Color,
329    /// 输入框圆角(主题 input.radius)
330    pub radius: f32,
331    pub focus_ring_color: Color,
332    pub text_color: Color,
333    pub placeholder_color: Color,
334    pub cursor_color: Color,
335    /// T2:文本选区 (start, end),start ≤ end,None = 无选区
336    pub selection: Option<(usize, usize)>,
337    /// P1-3.3:按宽度软换行
338    pub soft_wrap: bool,
339    /// P1-3.3:内部垂直滚动偏移
340    pub scroll_y: f32,
341    pub element_id: Option<ElementId>,
342}
343
344/// P0-1:TextField 的 State 在 `mgui-components`,RO 在本 crate。
345/// 跨 crate 无法 downcast State,因此由 State 构造这个纯数据 payload,
346/// RO 侧 `apply_state` 再把它写回自身(避免 State→RO 的循环依赖)。
347#[derive(Clone, Debug)]
348pub struct TextFieldApply {
349    pub width: f32,
350    pub height: f32,
351    pub font_size: f32,
352    pub placeholder: String,
353    pub value: String,
354    pub cursor: usize,
355    pub preedit: Option<String>,
356    pub preedit_cursor: Option<(usize, usize)>,
357    pub focused: bool,
358    pub cursor_visible: bool,
359    pub bg_color: Color,
360    pub bg_focused_color: Color,
361    pub border_color: Color,
362    pub radius: f32,
363    pub focus_ring_color: Color,
364    pub text_color: Color,
365    pub placeholder_color: Color,
366    pub cursor_color: Color,
367    pub selection: Option<(usize, usize)>,
368    pub soft_wrap: bool,
369    pub scroll_y: f32,
370}
371
372impl From<TextFieldApply> for TextFieldRenderObject {
373    fn from(a: TextFieldApply) -> Self {
374        Self {
375            width: a.width,
376            height: a.height,
377            font_size: a.font_size,
378            placeholder: a.placeholder,
379            value: a.value,
380            cursor: a.cursor,
381            preedit: a.preedit,
382            preedit_cursor: a.preedit_cursor,
383            focused: a.focused,
384            cursor_visible: a.cursor_visible,
385            bg_color: a.bg_color,
386            bg_focused_color: a.bg_focused_color,
387            border_color: a.border_color,
388            radius: a.radius,
389            focus_ring_color: a.focus_ring_color,
390            text_color: a.text_color,
391            placeholder_color: a.placeholder_color,
392            cursor_color: a.cursor_color,
393            selection: a.selection,
394            soft_wrap: a.soft_wrap,
395            scroll_y: a.scroll_y,
396            element_id: None,
397        }
398    }
399}
400
401impl RenderObject for TextFieldRenderObject {
402    fn layout(&mut self, constraints: BoxConstraints, _ctx: &mut LayoutContext) -> Size {
403        let s = Size::new(self.width, self.height);
404        self.width = constraints.constrain(s).width;
405        self.height = constraints.constrain(s).height;
406        Size::new(self.width, self.height)
407    }
408
409    fn paint(&self, offset: Point, list: &mut PaintList) {
410        let rect = Rect::new(offset.x, offset.y, self.width, self.height);
411        let radius = self.radius;
412
413        // 1. 背景 + 描边(未聚焦 1px 边框;聚焦 2px 焦点环)
414        if self.focused {
415            list.push(PaintCommand::Rect { rect, color: self.focus_ring_color, radius });
416            let inner =
417                Rect::new(offset.x + RING_T, offset.y + RING_T, self.width - RING_T * 2.0, self.height - RING_T * 2.0);
418            list.push(PaintCommand::Rect {
419                rect: inner,
420                color: self.bg_focused_color,
421                radius: (radius - RING_T).max(0.0),
422            });
423        } else if self.border_color.a > 0.0 {
424            list.push(PaintCommand::Rect { rect, color: self.border_color, radius });
425            let inner = Rect::new(offset.x + 1.0, offset.y + 1.0, self.width - 2.0, self.height - 2.0);
426            list.push(PaintCommand::Rect { rect: inner, color: self.bg_color, radius: (radius - 1.0).max(0.0) });
427        } else {
428            list.push(PaintCommand::Rect { rect, color: self.bg_color, radius });
429        }
430
431        let layout =
432            text_field_layout(&self.value, self.width, self.height, self.font_size, self.soft_wrap, self.scroll_y);
433        let text_x = offset.x + PAD_X;
434        let clip = Rect::new(
435            offset.x + PAD_X,
436            offset.y + RING_T,
437            (self.width - PAD_X * 2.0).max(1.0),
438            (self.height - RING_T * 2.0).max(1.0),
439        );
440        list.push(PaintCommand::PushClip(clip));
441
442        let has_preedit = self.preedit.as_ref().map(|p| !p.is_empty()).unwrap_or(false);
443
444        // Placeholder 单行(无 value/无 preedit 时)
445        if self.value.is_empty() && !has_preedit && !self.placeholder.is_empty() {
446            // 占位符按自身字形视觉高度居中:value 为空时 layout.line_h 只能
447            // 回退 font_size,对 ascent/descent 更大的字体(中文等)会整体偏下
448            let ph_line_h = text_visual_height(&self.placeholder, self.font_size, None);
449            let ph_total_h = text_visual_height(&self.placeholder, self.font_size, Some(layout.text_width));
450            let ph_top = offset.y + ((self.height - ph_total_h) * 0.5).max(0.0);
451            paint_text_line(
452                &self.placeholder,
453                self.font_size,
454                self.placeholder_color,
455                Point::new(text_x, ph_top),
456                list,
457                Some(layout.text_width),
458            );
459            if self.focused {
460                self.paint_cursor(list, text_x, ph_top, ph_line_h);
461            }
462            list.pop_clip();
463            return;
464        }
465
466        // 选区高亮(逐视觉行交集)
467        if let Some((sel_start, sel_end)) = self.selection {
468            let sel_color = Color::rgba(0.24, 0.47, 0.95, 0.35);
469            for (index, line) in layout.lines.iter().enumerate() {
470                let start = sel_start.max(line.start);
471                let end = sel_end.min(line.end);
472                if start >= end {
473                    continue;
474                }
475                let y = offset.y + layout.top_pad + index as f32 * layout.line_h - layout.scroll_y;
476                if y + layout.line_h < offset.y || y > offset.y + self.height {
477                    continue;
478                }
479                let prefix_w = layout.x_at_in_line(&self.value, index, start, self.font_size);
480                let end_w = layout.x_at_in_line(&self.value, index, end, self.font_size);
481                // RTL 时 end_w < prefix_w,选区块取两者之间的区间
482                let left = prefix_w.min(end_w);
483                list.push(PaintCommand::Rect {
484                    rect: Rect::new(text_x + left, y, (prefix_w - end_w).abs(), layout.line_h),
485                    color: sel_color,
486                    radius: 0.0,
487                });
488            }
489        }
490
491        // value 逐视觉行绘制(soft wrap 后每行单独绘制,不再二次换行)
492        for (index, line) in layout.lines.iter().enumerate() {
493            let y = offset.y + layout.top_pad + index as f32 * layout.line_h - layout.scroll_y;
494            if y + layout.line_h < offset.y || y > offset.y + self.height {
495                continue;
496            }
497            let text = &self.value[line.start..line.end];
498            paint_text_line(text, self.font_size, self.text_color, Point::new(text_x, y), list, None);
499        }
500
501        let cursor_index = layout.cursor_line(self.cursor);
502        let cursor_y = offset.y + layout.cursor_y(self.cursor);
503
504        if has_preedit {
505            let preedit = self.preedit.as_deref().unwrap_or("");
506            let line =
507                layout.lines.get(cursor_index).copied().unwrap_or(TextFieldLine { hard_line: 0, start: 0, end: 0 });
508            let prefix = &self.value[line.start.min(self.cursor)..self.cursor.min(line.end)];
509            let preedit_x = text_x + measure_text_width(prefix, self.font_size);
510            let cursor_in_preedit = self.preedit_cursor.map(|(s, _)| s.min(preedit.len())).unwrap_or(preedit.len());
511            let preedit_cursor_x = text_x
512                + measure_text_width(prefix, self.font_size)
513                + measure_text_width(&preedit[..cursor_in_preedit], self.font_size);
514
515            if !preedit.is_empty() {
516                paint_text_line(
517                    preedit,
518                    self.font_size,
519                    self.text_color,
520                    Point::new(preedit_x, cursor_y),
521                    list,
522                    Some((layout.text_width - (preedit_x - text_x)).max(1.0)),
523                );
524                let w_preedit = measure_text_width(preedit, self.font_size);
525                list.push(PaintCommand::Rect {
526                    rect: Rect::new(preedit_x, cursor_y + layout.line_h - 2.0, w_preedit, 1.5),
527                    color: self.text_color,
528                    radius: 0.0,
529                });
530            }
531            if self.focused && self.cursor_visible {
532                self.paint_cursor(list, preedit_cursor_x, cursor_y, layout.line_h);
533            }
534        } else {
535            let cursor_x = text_x + layout.cursor_x(&self.value, self.cursor, self.font_size);
536            if self.focused && self.cursor_visible {
537                self.paint_cursor(list, cursor_x, cursor_y, layout.line_h);
538            }
539        }
540
541        list.pop_clip();
542    }
543
544    fn hit_test(&self, position: Point, offset: Point) -> Option<ElementId> {
545        let rect = Rect::new(offset.x, offset.y, self.width, self.height);
546        if rect.contains(position) {
547            self.element_id
548        } else {
549            None
550        }
551    }
552
553    fn set_element_id(&mut self, id: ElementId) {
554        self.element_id = Some(id);
555    }
556
557    fn element_id(&self) -> Option<ElementId> {
558        self.element_id
559    }
560
561    fn content_size(&self) -> Size {
562        Size::new(self.width, self.height)
563    }
564
565    /// P0-1:就地写回 State 构造的视觉 payload,避免每次输入/闪烁重建 RO。
566    fn apply_state(&mut self, state: &mut dyn Any) -> StateApply {
567        let Some(a) = state.downcast_mut::<TextFieldApply>() else {
568            return StateApply::Unsupported;
569        };
570        if self.width == a.width
571            && self.height == a.height
572            && self.font_size == a.font_size
573            && self.placeholder == a.placeholder
574            && self.value == a.value
575            && self.cursor == a.cursor
576            && self.preedit == a.preedit
577            && self.preedit_cursor == a.preedit_cursor
578            && self.focused == a.focused
579            && self.cursor_visible == a.cursor_visible
580            && self.bg_color == a.bg_color
581            && self.bg_focused_color == a.bg_focused_color
582            && self.focus_ring_color == a.focus_ring_color
583            && self.text_color == a.text_color
584            && self.placeholder_color == a.placeholder_color
585            && self.cursor_color == a.cursor_color
586            && self.selection == a.selection
587            && self.soft_wrap == a.soft_wrap
588            && self.scroll_y == a.scroll_y
589        {
590            return StateApply::Unchanged;
591        }
592        self.width = a.width;
593        self.height = a.height;
594        self.font_size = a.font_size;
595        self.placeholder = std::mem::take(&mut a.placeholder);
596        self.value = std::mem::take(&mut a.value);
597        self.cursor = a.cursor;
598        self.preedit = a.preedit.take();
599        self.preedit_cursor = a.preedit_cursor;
600        self.focused = a.focused;
601        self.cursor_visible = a.cursor_visible;
602        self.bg_color = a.bg_color;
603        self.bg_focused_color = a.bg_focused_color;
604        self.focus_ring_color = a.focus_ring_color;
605        self.text_color = a.text_color;
606        self.placeholder_color = a.placeholder_color;
607        self.cursor_color = a.cursor_color;
608        self.selection = a.selection;
609        self.soft_wrap = a.soft_wrap;
610        self.scroll_y = a.scroll_y;
611        StateApply::Updated
612    }
613}
614
615impl TextFieldRenderObject {
616    fn paint_cursor(&self, list: &mut PaintList, x: f32, text_y: f32, line_h: f32) {
617        list.push(PaintCommand::Rect {
618            rect: Rect::new(x, text_y + 1.0, CURSOR_W, (line_h - 2.0).max(1.0)),
619            color: self.cursor_color,
620            radius: 0.0,
621        });
622    }
623}
624
625// =============================================================================
626// 测试
627// =============================================================================
628
629#[cfg(test)]
630mod tests {
631    use super::*;
632
633    #[test]
634    fn render_object_paints_bg_and_cursor() {
635        let mut ro = TextFieldRenderObject {
636            width: 200.0,
637            height: 40.0,
638            font_size: 16.0,
639            placeholder: String::new(),
640            value: String::new(),
641            cursor: 0,
642            preedit: None,
643            preedit_cursor: None,
644            focused: false,
645            cursor_visible: true,
646            bg_color: Color::BLACK,
647            bg_focused_color: Color::BLACK,
648            border_color: Color::TRANSPARENT,
649            radius: 6.0,
650            focus_ring_color: Color::WHITE,
651            text_color: Color::WHITE,
652            placeholder_color: Color::rgba(0.5, 0.5, 0.5, 1.0),
653            cursor_color: Color::WHITE,
654            selection: None,
655            soft_wrap: false,
656            scroll_y: 0.0,
657            element_id: None,
658        };
659        ro.layout(BoxConstraints::UNBOUNDED, &mut LayoutContext);
660
661        let mut list = PaintList::new();
662        ro.paint(Point::ZERO, &mut list);
663        let rects = list.commands.iter().filter(|c| matches!(c, PaintCommand::Rect { .. })).count();
664        assert_eq!(rects, 1, "未聚焦空值:仅背景");
665
666        let mut focused_ro = TextFieldRenderObject { focused: true, value: "hi".to_string(), cursor: 2, ..ro };
667        focused_ro.set_element_id(ElementId::default());
668        assert!(focused_ro.element_id().is_some());
669
670        let mut list = PaintList::new();
671        focused_ro.paint(Point::ZERO, &mut list);
672        let rects = list.commands.iter().filter(|c| matches!(c, PaintCommand::Rect { .. })).count();
673        let texts = list.commands.iter().filter(|c| matches!(c, PaintCommand::TexturedRect { .. })).count();
674        assert_eq!(rects, 3, "ring + bg + cursor");
675        assert!(texts >= 1, "文字至少 1 个 glyph rect");
676    }
677
678    #[test]
679    fn preedit_paints_underline() {
680        let mut ro = TextFieldRenderObject {
681            width: 200.0,
682            height: 40.0,
683            font_size: 16.0,
684            placeholder: String::new(),
685            value: "a".to_string(),
686            cursor: 1,
687            preedit: Some("中".to_string()),
688            preedit_cursor: None,
689            focused: true,
690            cursor_visible: true,
691            bg_color: Color::BLACK,
692            bg_focused_color: Color::BLACK,
693            border_color: Color::TRANSPARENT,
694            radius: 6.0,
695            focus_ring_color: Color::WHITE,
696            text_color: Color::WHITE,
697            placeholder_color: Color::rgba(0.5, 0.5, 0.5, 1.0),
698            cursor_color: Color::WHITE,
699            selection: None,
700            soft_wrap: false,
701            scroll_y: 0.0,
702            element_id: None,
703        };
704        ro.layout(BoxConstraints::UNBOUNDED, &mut LayoutContext);
705        let mut list = PaintList::new();
706        ro.paint(Point::ZERO, &mut list);
707        let rects = list.commands.iter().filter(|c| matches!(c, PaintCommand::Rect { .. })).count();
708        assert_eq!(rects, 4, "ring + bg + preedit 下划线 + 光标");
709    }
710
711    #[test]
712    fn placeholder_uses_own_glyph_metrics_for_vertical_centering() {
713        fn glyph_bounds(list: &PaintList) -> (f32, f32) {
714            let mut min = f32::INFINITY;
715            let mut max = f32::NEG_INFINITY;
716            for c in &list.commands {
717                if let PaintCommand::TexturedRect { rect, .. } = c {
718                    min = min.min(rect.y);
719                    max = max.max(rect.y + rect.height);
720                }
721            }
722            (min, max)
723        }
724        fn paint(value: &str, placeholder: &str) -> PaintList {
725            let mut ro = TextFieldRenderObject {
726                width: 240.0,
727                height: 48.0,
728                font_size: 16.0,
729                placeholder: placeholder.to_string(),
730                value: value.to_string(),
731                cursor: value.len(),
732                preedit: None,
733                preedit_cursor: None,
734                focused: false,
735                cursor_visible: true,
736                bg_color: Color::BLACK,
737                bg_focused_color: Color::BLACK,
738                border_color: Color::TRANSPARENT,
739                radius: 6.0,
740                focus_ring_color: Color::WHITE,
741                text_color: Color::WHITE,
742                placeholder_color: Color::rgba(0.5, 0.5, 0.5, 1.0),
743                cursor_color: Color::WHITE,
744                selection: None,
745                soft_wrap: false,
746                scroll_y: 0.0,
747                element_id: None,
748            };
749            ro.layout(BoxConstraints::UNBOUNDED, &mut LayoutContext);
750            let mut list = PaintList::new();
751            ro.paint(Point::ZERO, &mut list);
752            list
753        }
754
755        // 同一字符串作为 value 与 placeholder 时,字形必须落在同一 y。
756        // 旧实现 value 为空 → line_h 回退 font_size,中文 placeholder 整体偏下。
757        let ph = paint("", "Ag你好");
758        let value = paint("Ag你好", "");
759        let (ph_min, ph_max) = glyph_bounds(&ph);
760        let (v_min, v_max) = glyph_bounds(&value);
761        assert!((ph_min - v_min).abs() < 0.01, "placeholder 顶边应等于同文本 value 顶边");
762        assert!((ph_max - v_max).abs() < 0.01, "placeholder 底边应等于同文本 value 底边");
763    }
764
765    #[test]
766    fn soft_wrap_splits_long_line() {
767        let layout = text_field_layout("hello world hello world", 100.0, 80.0, 16.0, true, 0.0);
768        assert!(layout.lines.len() > 1, "长行应拆成多条视觉行");
769        assert_eq!(layout.lines[0].hard_line, 0);
770        assert!(layout.lines.iter().all(|line| line.start <= line.end));
771        assert_eq!(layout.lines.first().unwrap().start, 0);
772        assert_eq!(layout.lines.last().unwrap().end, "hello world hello world".len());
773    }
774
775    #[test]
776    fn hard_newlines_preserve_empty_lines() {
777        let value = "a\n\nb";
778        let layout = text_field_layout(value, 200.0, 100.0, 16.0, false, 0.0);
779        assert_eq!(layout.lines.len(), 3);
780        assert_eq!(layout.lines[1].start, 2);
781        assert_eq!(layout.lines[1].end, 2);
782        assert_eq!(layout.lines[2].start, 3);
783    }
784
785    #[test]
786    fn cursor_and_hit_test_follow_visual_lines() {
787        let value = "hello world hello world";
788        let layout = text_field_layout(value, 100.0, 80.0, 16.0, true, 0.0);
789        let second = layout.lines[1];
790        assert!(second.start > 0);
791
792        assert_eq!(layout.cursor_line(second.start), 1);
793        assert!(layout.cursor_x(value, second.start, 16.0).abs() < 0.01);
794        let y = layout.top_pad + layout.line_h * 1.5;
795        assert_eq!(layout.offset_at(value, PAD_X + 1.0, y, 16.0), second.start);
796    }
797
798    #[test]
799    fn line_runs_include_hard_break_and_offsets() {
800        let value = "ab\ncd";
801        let layout = text_field_layout(value, 200.0, 100.0, 16.0, false, 0.0);
802        let runs = layout.line_runs(value, 16.0);
803        assert_eq!(runs.len(), 2);
804        assert_eq!(runs[0].value, "ab\n");
805        assert_eq!(runs[0].start_char, 0);
806        assert_eq!(runs[1].value, "cd");
807        assert_eq!(runs[1].start_char, 3);
808        assert_eq!(runs[0].bounds.x, PAD_X);
809        assert_eq!(runs[1].bounds.y, layout.top_pad + layout.line_h);
810
811        let positions = runs[0].character_positions.as_ref().expect("positions");
812        let widths = runs[0].character_widths.as_ref().expect("widths");
813        assert_eq!(positions.len(), 3, "换行符计入字符数");
814        assert_eq!(widths.len(), 3);
815        assert_eq!(widths[2], 0.0, "换行符零宽");
816        assert!((positions[2] - (positions[1] + widths[1])).abs() < 0.01, "换行位置在行末");
817    }
818
819    #[test]
820    fn line_runs_cover_trailing_empty_line_and_soft_wrap() {
821        let value = "ab\n";
822        let layout = text_field_layout(value, 200.0, 100.0, 16.0, false, 0.0);
823        let runs = layout.line_runs(value, 16.0);
824        assert_eq!(runs.len(), 2);
825        assert_eq!(runs[0].value, "ab\n");
826        assert_eq!(runs[1].value, "");
827        assert_eq!(runs[1].start_char, 3);
828        assert_eq!(runs[1].character_positions.as_ref().map(Vec::len), Some(0));
829
830        let wrapped = "hello world hello world";
831        let layout = text_field_layout(wrapped, 100.0, 80.0, 16.0, true, 0.0);
832        let runs = layout.line_runs(wrapped, 16.0);
833        assert!(runs.len() > 1);
834        assert!(runs.iter().all(|run| !run.value.contains('\n')), "软换行不插入硬换行符");
835        assert_eq!(runs[0].start_char, 0);
836        for pair in runs.windows(2) {
837            assert_eq!(pair[1].start_char, pair[0].start_char + pair[0].value.chars().count());
838        }
839    }
840
841    #[test]
842    fn rtl_line_run_positions_start_at_right_edge() {
843        let value = "مرحبا";
844        let layout = text_field_layout(value, 200.0, 40.0, 16.0, false, 0.0);
845        let runs = layout.line_runs(value, 16.0);
846        assert_eq!(runs.len(), 1);
847        assert!(runs[0].rtl);
848        let positions = runs[0].character_positions.as_ref().expect("RTL positions");
849        let widths = runs[0].character_widths.as_ref().expect("RTL widths");
850        assert_eq!(positions.len(), 5);
851        assert_eq!(positions[0], 0.0, "RTL 从右缘起算");
852        assert!(widths.iter().all(|width| *width >= 0.0));
853        assert!(runs[0].bounds.width >= 0.0);
854    }
855
856    #[test]
857    fn soft_wrap_paints_multiple_visual_rows() {
858        let mut ro = TextFieldRenderObject {
859            width: 100.0,
860            height: 120.0,
861            font_size: 16.0,
862            placeholder: String::new(),
863            value: "hello world hello world".to_string(),
864            cursor: 0,
865            preedit: None,
866            preedit_cursor: None,
867            focused: false,
868            cursor_visible: true,
869            bg_color: Color::BLACK,
870            bg_focused_color: Color::BLACK,
871            border_color: Color::TRANSPARENT,
872            radius: 6.0,
873            focus_ring_color: Color::WHITE,
874            text_color: Color::WHITE,
875            placeholder_color: Color::rgba(0.5, 0.5, 0.5, 1.0),
876            cursor_color: Color::WHITE,
877            selection: None,
878            soft_wrap: true,
879            scroll_y: 0.0,
880            element_id: None,
881        };
882        ro.layout(BoxConstraints::UNBOUNDED, &mut LayoutContext);
883        let mut list = PaintList::new();
884        ro.paint(Point::ZERO, &mut list);
885        let mut rows: Vec<i32> = list
886            .commands
887            .iter()
888            .filter_map(|cmd| match cmd {
889                PaintCommand::TexturedRect { rect, .. } => Some(rect.y as i32),
890                _ => None,
891            })
892            .collect();
893        rows.sort_unstable();
894        rows.dedup();
895        assert!(rows.len() > 1, "soft wrap 应绘制多条视觉行(rows={rows:?})");
896    }
897
898    #[test]
899    fn scroll_to_show_last_line() {
900        let value = "one\ntwo\nthree\nfour\nfive";
901        let mut layout = text_field_layout(value, 200.0, 40.0, 16.0, false, 0.0);
902        assert!(layout.max_scroll > 0.0);
903        let cursor = value.rfind("five").unwrap();
904        layout.scroll_y = layout.scroll_to_show(cursor);
905        assert!(layout.scroll_y > 0.0, "光标在末尾时应向下滚动");
906        assert!(layout.scroll_y <= layout.max_scroll);
907    }
908
909    /// 回归:引入自定义字体栈后,光标 x 必须与绘制用同一字体栈度量。
910    /// 此前 cursor_x 硬编码 DEFAULT_FONT_STACK,而 paint_text_line 走当前 runtime,
911    /// 字体不同则光标与文本错位(光标前出现空白)。
912    #[test]
913    fn cursor_x_uses_current_runtime_font_stack() {
914        use crate::runtime::{with_text_runtime, TextRuntime};
915
916        let value = "Hello 世界 123";
917        let runtime = TextRuntime::with_config("'Courier New', monospace", 1.2);
918        with_text_runtime(&runtime, || {
919            let layout = text_field_layout(value, 400.0, 40.0, 16.0, false, 0.0);
920            let font_stack = current_text_runtime().font_stack();
921            let carets = measure_caret_positions(value, 16.0, &font_stack);
922            let expected_end = *carets.last().unwrap();
923            // 光标在文本末尾:应精确落在当前字体栈下整行前缀宽度处
924            let cursor_x = layout.cursor_x(value, value.len(), 16.0);
925            assert!(
926                (cursor_x - expected_end).abs() < 1e-3,
927                "cursor_x 必须用当前字体栈({font_stack}),实际 {cursor_x} vs 期望 {expected_end}"
928            );
929            // 与绘制同源的 measure_text_width 一致(不引入空白)
930            let painted_end = measure_text_width(value, 16.0);
931            assert!(
932                (cursor_x - painted_end).abs() < 1.0,
933                "光标应与绘制文本末端对齐: cursor_x={cursor_x} painted={painted_end}"
934            );
935            // 区分力自检:若自定义字体栈确实改变字宽,则旧硬编码 DEFAULT_FONT_STACK 下
936            // cursor_x 会落到 default_end 而非 expected_end —— 该断言确保回归可被捕获。
937            let default_end = *measure_caret_positions(value, 16.0, crate::text::DEFAULT_FONT_STACK).last().unwrap();
938            if (default_end - expected_end).abs() > 1.0 {
939                assert!(
940                    (cursor_x - default_end).abs() > 1.0,
941                    "当前字体字宽与默认字体栈不同时, cursor_x 不得仍取默认字体栈宽度(旧 bug)"
942                );
943            }
944        });
945    }
946}
947
948#[cfg(test)]
949mod apply_state_tests {
950    use super::*;
951
952    fn payload(value: &str, cursor: usize) -> TextFieldApply {
953        TextFieldApply {
954            width: 200.0,
955            height: 40.0,
956            font_size: 16.0,
957            placeholder: String::new(),
958            value: value.into(),
959            cursor,
960            preedit: None,
961            preedit_cursor: None,
962            focused: true,
963            cursor_visible: true,
964            bg_color: Color::BLACK,
965            bg_focused_color: Color::BLACK,
966            border_color: Color::TRANSPARENT,
967            radius: 6.0,
968            focus_ring_color: Color::WHITE,
969            text_color: Color::WHITE,
970            placeholder_color: Color::WHITE,
971            cursor_color: Color::WHITE,
972            selection: None,
973            soft_wrap: false,
974            scroll_y: 0.0,
975        }
976    }
977
978    #[test]
979    fn payload_apply_updates_text_field_in_place() {
980        let mut ro = TextFieldRenderObject::from(payload("a", 1));
981        let mut next = payload("ab", 2);
982        assert_eq!(ro.apply_state(&mut next), StateApply::Updated);
983        assert_eq!(ro.value, "ab");
984        assert_eq!(ro.cursor, 2);
985
986        let mut same = payload("ab", 2);
987        assert_eq!(ro.apply_state(&mut same), StateApply::Unchanged);
988    }
989}
990
991#[cfg(test)]
992mod soft_wrap_boundary_tests {
993    use super::*;
994
995    /// 中文每字可断,相邻视觉行**共用**边界 byte(`line.end == next.start`)。
996    /// 歧义按方向拆开:Home 判给上一行(End 之后能回到刚才那行行首),
997    /// End / 光标绘制判给下一行(在该行行首输入就该落在这里)。
998    /// 与字体度量无关,Windows / Linux 都稳定命中 —— Gitee Go 首次 Linux 运行暴露的
999    /// 就是这个口径差(英文用例恰好有空格可吞,Windows 本地一直测不出来)。
1000    #[test]
1001    fn cjk_wrap_boundary_resolves_by_affinity() {
1002        let value = "一二三四五六七八";
1003        let layout = text_field_layout(value, 60.0, 40.0, 16.0, true, 0.0);
1004        assert!(layout.lines.len() >= 2, "60px 宽应把 8 个字断成多行, 实际 {:?}", layout.lines);
1005        let boundary = layout.lines[0].end;
1006        assert_eq!(layout.lines[1].start, boundary, "中文换行没有可吞的空格 → 两行共用边界");
1007
1008        assert_eq!(layout.cursor_line_upstream(boundary), 0, "Home 口径:边界属上一行");
1009        assert_eq!(layout.cursor_line(boundary), 1, "End / 绘制口径:边界属下一行");
1010        // 非边界 byte 两个口径一致
1011        let mid = layout.lines[1].start + 3;
1012        assert_eq!(layout.cursor_line_upstream(mid), 1);
1013        assert_eq!(layout.cursor_line(mid), 1);
1014    }
1015
1016    #[test]
1017    fn hard_newline_boundaries_stay_unambiguous() {
1018        let value = "ab\ncd";
1019        let layout = text_field_layout(value, 200.0, 60.0, 16.0, true, 0.0);
1020        assert_eq!(layout.lines.len(), 2, "{:?}", layout.lines);
1021        assert_eq!(layout.cursor_line(2), 0, "行末(\\n 前)属第一行");
1022        assert_eq!(layout.cursor_line(3), 1, "第二行行首属第二行");
1023    }
1024}