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