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