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