mgui-text 0.8.0

平台无关文本服务:parley 排版 / swash 字形栅格化 / glyph atlas / TextField 布局
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
//! TextFieldRenderObject — 文本输入框渲染(TextFieldWidget 在 mgui-components)
//!
//! 支持硬换行与可选 soft wrap:先按 `\n` 拆硬行,再按可用宽度拆视觉行。
//! 视觉行布局同时驱动绘制、命中测试、IME 光标定位与内部垂直滚动。

use mgui_core::{
    BoxConstraints, Color, ElementId, LayoutContext, PaintCommand, PaintList, Point, Rect, RenderObject, Size,
    StateApply,
};
use std::any::Any;

use crate::text::{
    is_rtl_text, measure_caret_positions, measure_text_width, nearest_caret_index, paint_text_line, text_visual_height,
    wrapped_line_ranges, DEFAULT_FONT_STACK,
};

/// 文本区行高与顶部内边距(无 soft wrap 的兼容接口)
pub fn text_layout_metrics(height: f32, value: &str, font_size: f32) -> (f32, f32) {
    let first_line = value.split('\n').next().unwrap_or("");
    let line_h = text_visual_height(first_line, font_size, None);
    let total_lines = value.split('\n').count().max(1);
    let top_pad = if total_lines == 1 { (height - line_h).max(0.0) * 0.5 } else { RING_T + 2.0 };
    (line_h, top_pad)
}

/// 文本框内边距(水平)
const PAD_X: f32 = 10.0;
/// 文本区左边距(供无障碍 TextRun 的 bounds/坐标计算)
pub const TEXT_PAD_X: f32 = PAD_X;
/// 光标宽度
const CURSOR_W: f32 = 1.5;
/// 焦点环厚度(内嵌,同 Button)
const RING_T: f32 = 2.0;

/// 一条视觉行(soft wrap 后)
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct TextFieldLine {
    /// 所属硬行(按 `\n` 拆分)
    pub hard_line: usize,
    /// 在 value 中的绝对字节范围 `[start, end)`(不含换行符)
    pub start: usize,
    pub end: usize,
}

/// TextField 的可视布局:视觉行 + 行高/滚动几何
#[derive(Clone, Debug)]
pub struct TextFieldLayout {
    pub lines: Vec<TextFieldLine>,
    pub line_h: f32,
    pub top_pad: f32,
    pub text_width: f32,
    pub content_height: f32,
    /// 文本可视区高度(不含上下 padding)
    pub viewport_height: f32,
    pub max_scroll: f32,
    /// 已 clamp 的滚动偏移
    pub scroll_y: f32,
}

/// 一条视觉行的无障碍文本数据(AccessKit `TextRun`)。
///
/// 硬换行行尾包含 `\n`(AccessKit 要求换行符计入该行字符数);
/// `character_positions` 相对本行 bounds,RTL 从右缘起算。
#[derive(Clone, Debug, PartialEq)]
pub struct TextFieldLineRun {
    pub value: String,
    /// 本行首字符在完整 value 中的字符索引
    pub start_char: usize,
    /// 相对 TextField 左上角的逻辑像素边界
    pub bounds: Rect,
    pub character_positions: Option<Vec<f32>>,
    pub character_widths: Option<Vec<f32>>,
    pub rtl: bool,
}

impl TextFieldLayout {
    /// 光标落在哪个视觉行:**边界判给下一行**(后行亲和)。
    ///
    /// soft wrap 边界那个 byte 同时是上一行的 `end` 与下一行的 `start`(中文每字可断、
    /// 没有空格可吞时**必然**相等,英文挂尾空格同样相等)。End / Right / ↓ 与光标绘制、
    /// 滚动定位用这个口径 —— 否则光标停在某行行首时按 End 会被判到上一行,行末就走不过去;
    /// 绘制按后行也才对得上"在这里输入会落在哪"。Home 用 [`Self::cursor_line_upstream`]。
    pub fn cursor_line(&self, cursor: usize) -> usize {
        self.lines.iter().rposition(|line| line.start <= cursor).unwrap_or(0)
    }

    /// 光标落在哪个视觉行:**边界判给上一行**(前行亲和),目前只有 Home 用。
    ///
    /// 光标停在两行共用的边界 byte 上时(按 End 之后就是这个位置),Home 该回到**刚才那一行**
    /// 的行首;用后行口径会算到下一行,Home 于是"没反应"(Gitee Go 首次 Linux 运行暴露:
    /// 英文用例在 Windows 上恰好有空格可吞、边界不共享,本地一直测不出来)。
    /// 硬换行不受影响:下一行 `start = end + 1`,等号取不到。
    ///
    /// 已知代价:真正的消歧要**记住光标是怎么走到边界的**(caret affinity 状态),
    /// 两条口径各自只在半个场景里对。这里按"按键方向"分,换来的是 Home / End 都不空转;
    /// 代价是"点击落在续行左缘再按 Home"会往上跳一行 —— 留着做光标亲和时一并收口。
    pub fn cursor_line_upstream(&self, cursor: usize) -> usize {
        let index = self.cursor_line(cursor);
        if index > 0 && self.lines[index - 1].end >= cursor {
            return index - 1;
        }
        index
    }

    pub fn line_text<'a>(&self, value: &'a str, index: usize) -> &'a str {
        self.lines.get(index).map(|line| &value[line.start.min(value.len())..line.end.min(value.len())]).unwrap_or("")
    }

    /// 指定行内 byte 位置相对文本区左缘的 x(未加 PAD_X)
    ///
    /// 与 [`Self::cursor_x`] 的区别:soft wrap 边界处 byte 同时属于两行,
    /// 这里强制按调用方指定的行计算(选区逐行高亮必须用这个)。
    pub fn x_at_in_line(&self, value: &str, line_index: usize, byte: usize, font_size: f32) -> f32 {
        let Some(line) = self.lines.get(line_index) else {
            return 0.0;
        };
        let end = byte.clamp(line.start, line.end).min(value.len());
        // 按整行计算光标表(RTL 需要完整行的视觉顺序,不能只看前缀切片)
        let line_text = &value[line.start.min(value.len())..line.end.min(value.len())];
        let char_index = value[line.start..end].chars().count();
        measure_caret_positions(line_text, font_size, DEFAULT_FONT_STACK).get(char_index).copied().unwrap_or(0.0)
    }

    /// 单行 LTR 文本的逐字符位置/宽度(相对文本区左缘)。
    ///
    /// 多行、soft wrap 后多行或 RTL 文本返回 None:AccessKit 的
    /// character_positions 是单行标量,跨行/RTL 需要拆成多个 TextRun。
    pub fn single_line_char_positions(&self, value: &str, font_size: f32) -> Option<(Vec<f32>, Vec<f32>)> {
        if self.lines.len() != 1 {
            return None;
        }
        let line = self.lines[0];
        let text = &value[line.start.min(value.len())..line.end.min(value.len())];
        if text.contains('\n') || is_rtl_text(text) {
            return None;
        }
        let carets = measure_caret_positions(text, font_size, DEFAULT_FONT_STACK);
        let chars = text.chars().count();
        if carets.len() < chars + 1 {
            return None;
        }
        let mut positions = Vec::with_capacity(chars);
        let mut widths = Vec::with_capacity(chars);
        for i in 0..chars {
            positions.push(carets[i]);
            widths.push((carets[i + 1] - carets[i]).max(0.0));
        }
        Some((positions, widths))
    }

    /// 所有视觉行的无障碍 TextRun 数据(多行/RTL 支持)。
    ///
    /// 每个视觉行一个 run;硬换行行尾包含 `\n`,`value` 与
    /// `character_lengths` 的字符数一致。位置相对该行 bounds:
    /// LTR 从左边距起算,RTL 从右边距起算(AccessKit 约定)。
    pub fn line_runs(&self, value: &str, font_size: f32) -> Vec<TextFieldLineRun> {
        let mut runs = Vec::with_capacity(self.lines.len());
        let mut start_char = 0usize;

        for (index, line) in self.lines.iter().enumerate() {
            let start = line.start.min(value.len());
            let end = line.end.min(value.len()).max(start);
            let text = &value[start..end];
            let has_break = value.as_bytes().get(end) == Some(&b'\n');
            let mut run_value = String::with_capacity(text.len() + usize::from(has_break));
            run_value.push_str(text);
            if has_break {
                run_value.push('\n');
            }

            let rtl = is_rtl_text(text);
            let chars = text.chars().count();
            let carets = measure_caret_positions(text, font_size, DEFAULT_FONT_STACK);
            let (character_positions, character_widths, line_width) = if carets.len() > chars {
                let width = if rtl { carets[0] } else { carets[chars] };
                let mut positions = Vec::with_capacity(chars + usize::from(has_break));
                let mut widths = Vec::with_capacity(chars + usize::from(has_break));
                for i in 0..chars {
                    if rtl {
                        positions.push((width - carets[i]).max(0.0));
                        widths.push((carets[i] - carets[i + 1]).max(0.0));
                    } else {
                        positions.push(carets[i]);
                        widths.push((carets[i + 1] - carets[i]).max(0.0));
                    }
                }
                if has_break {
                    // 换行符不可见:零宽,位置在行末
                    let break_pos = if rtl { (width - carets[chars]).max(0.0) } else { carets[chars] };
                    positions.push(break_pos);
                    widths.push(0.0);
                }
                (Some(positions), Some(widths), width.max(0.0))
            } else {
                (None, None, 0.0)
            };

            let y = self.top_pad + index as f32 * self.line_h - self.scroll_y;
            runs.push(TextFieldLineRun {
                value: run_value,
                start_char,
                bounds: Rect::new(PAD_X, y, line_width, self.line_h),
                character_positions,
                character_widths,
                rtl,
            });
            start_char += chars + usize::from(has_break);
        }
        runs
    }

    /// 光标相对文本区左缘的 x(未加 PAD_X)
    pub fn cursor_x(&self, value: &str, cursor: usize, font_size: f32) -> f32 {
        self.x_at_in_line(value, self.cursor_line(cursor), cursor, font_size)
    }

    /// 光标相对 widget 顶部的 y(已含 top_pad 与滚动)
    pub fn cursor_y(&self, cursor: usize) -> f32 {
        self.top_pad + self.cursor_line(cursor) as f32 * self.line_h - self.scroll_y
    }

    /// 把局部坐标映射为 value 字节偏移
    pub fn offset_at(&self, value: &str, x: f32, y: f32, font_size: f32) -> usize {
        if self.lines.is_empty() {
            return 0;
        }
        let text_y = y - self.top_pad + self.scroll_y;
        let index =
            ((text_y / self.line_h.max(0.001)).floor() as isize).clamp(0, (self.lines.len() - 1) as isize) as usize;
        let line = self.lines[index];
        let line_text = &value[line.start..line.end];
        let carets = measure_caret_positions(line_text, font_size, DEFAULT_FONT_STACK);
        let local_x = (x - PAD_X).max(0.0);
        // LTR/RTL 通用:取距离最近的逻辑光标位(RTL 的光标表为递减)
        let char_col = nearest_caret_index(&carets, local_x).min(line_text.chars().count());
        let byte_in_line = line_text.char_indices().nth(char_col).map(|(b, _)| b).unwrap_or(line_text.len());
        (line.start + byte_in_line).min(value.len())
    }

    /// 保证 cursor 所在视觉行可见,返回新的 scroll_y
    pub fn scroll_to_show(&self, cursor: usize) -> f32 {
        let index = self.cursor_line(cursor);
        let top = index as f32 * self.line_h;
        let bottom = top + self.line_h;
        let scroll = if top < self.scroll_y {
            top
        } else if bottom > self.scroll_y + self.viewport_height {
            bottom - self.viewport_height
        } else {
            self.scroll_y
        };
        scroll.clamp(0.0, self.max_scroll)
    }
}

/// 构建 TextField 视觉行布局(soft wrap 关闭时每条硬行只有一行)
pub fn text_field_layout(
    value: &str,
    width: f32,
    height: f32,
    font_size: f32,
    soft_wrap: bool,
    scroll_y: f32,
) -> TextFieldLayout {
    let text_width = (width - PAD_X * 2.0).max(1.0);
    let first_line = value.split('\n').next().unwrap_or("");
    let line_h = text_visual_height(first_line, font_size, None).max(1.0);

    let mut lines = Vec::new();
    let mut hard_start = 0usize;
    for (hard_line, hard_text) in value.split('\n').enumerate() {
        let mut ranges =
            if soft_wrap { wrapped_line_ranges(hard_text, font_size, text_width) } else { vec![(0, hard_text.len())] };
        if ranges.is_empty() {
            ranges.push((0, hard_text.len()));
        }
        // 保证覆盖整条硬行(尾随空格可能没有 glyph run)
        if let Some(first) = ranges.first_mut() {
            first.0 = 0;
        }
        if let Some(last) = ranges.last_mut() {
            last.1 = hard_text.len().max(last.0);
        }
        for (start, end) in ranges {
            lines.push(TextFieldLine { hard_line, start: hard_start + start, end: hard_start + end });
        }
        hard_start += hard_text.len() + 1;
    }
    if lines.is_empty() {
        lines.push(TextFieldLine { hard_line: 0, start: 0, end: 0 });
    }

    let top_pad = if lines.len() == 1 { ((height - line_h) * 0.5).max(0.0) } else { RING_T + 2.0 };
    let viewport_height = (height - top_pad * 2.0).max(line_h);
    let content_height = lines.len() as f32 * line_h;
    let max_scroll = (content_height - viewport_height).max(0.0);
    let scroll_y = scroll_y.clamp(0.0, max_scroll);

    TextFieldLayout { lines, line_h, top_pad, text_width, content_height, viewport_height, max_scroll, scroll_y }
}

// =============================================================================
// TextFieldRenderObject
// =============================================================================

pub struct TextFieldRenderObject {
    pub width: f32,
    pub height: f32,
    pub font_size: f32,
    pub placeholder: String,
    pub value: String,
    pub cursor: usize,
    pub preedit: Option<String>,
    /// C1:preedit 内光标字节偏移区间
    pub preedit_cursor: Option<(usize, usize)>,
    pub focused: bool,
    /// C1:光标是否可见(闪烁)
    pub cursor_visible: bool,
    pub bg_color: Color,
    pub bg_focused_color: Color,
    /// 未聚焦时的 1px 描边色(主题 input.border;TRANSPARENT = 不画)
    pub border_color: Color,
    /// 输入框圆角(主题 input.radius)
    pub radius: f32,
    pub focus_ring_color: Color,
    pub text_color: Color,
    pub placeholder_color: Color,
    pub cursor_color: Color,
    /// T2:文本选区 (start, end),start ≤ end,None = 无选区
    pub selection: Option<(usize, usize)>,
    /// P1-3.3:按宽度软换行
    pub soft_wrap: bool,
    /// P1-3.3:内部垂直滚动偏移
    pub scroll_y: f32,
    pub element_id: Option<ElementId>,
}

/// P0-1:TextField 的 State 在 `mgui-components`,RO 在本 crate。
/// 跨 crate 无法 downcast State,因此由 State 构造这个纯数据 payload,
/// RO 侧 `apply_state` 再把它写回自身(避免 State→RO 的循环依赖)。
#[derive(Clone, Debug)]
pub struct TextFieldApply {
    pub width: f32,
    pub height: f32,
    pub font_size: f32,
    pub placeholder: String,
    pub value: String,
    pub cursor: usize,
    pub preedit: Option<String>,
    pub preedit_cursor: Option<(usize, usize)>,
    pub focused: bool,
    pub cursor_visible: bool,
    pub bg_color: Color,
    pub bg_focused_color: Color,
    pub border_color: Color,
    pub radius: f32,
    pub focus_ring_color: Color,
    pub text_color: Color,
    pub placeholder_color: Color,
    pub cursor_color: Color,
    pub selection: Option<(usize, usize)>,
    pub soft_wrap: bool,
    pub scroll_y: f32,
}

impl From<TextFieldApply> for TextFieldRenderObject {
    fn from(a: TextFieldApply) -> Self {
        Self {
            width: a.width,
            height: a.height,
            font_size: a.font_size,
            placeholder: a.placeholder,
            value: a.value,
            cursor: a.cursor,
            preedit: a.preedit,
            preedit_cursor: a.preedit_cursor,
            focused: a.focused,
            cursor_visible: a.cursor_visible,
            bg_color: a.bg_color,
            bg_focused_color: a.bg_focused_color,
            border_color: a.border_color,
            radius: a.radius,
            focus_ring_color: a.focus_ring_color,
            text_color: a.text_color,
            placeholder_color: a.placeholder_color,
            cursor_color: a.cursor_color,
            selection: a.selection,
            soft_wrap: a.soft_wrap,
            scroll_y: a.scroll_y,
            element_id: None,
        }
    }
}

impl RenderObject for TextFieldRenderObject {
    fn layout(&mut self, constraints: BoxConstraints, _ctx: &mut LayoutContext) -> Size {
        let s = Size::new(self.width, self.height);
        self.width = constraints.constrain(s).width;
        self.height = constraints.constrain(s).height;
        Size::new(self.width, self.height)
    }

    fn paint(&self, offset: Point, list: &mut PaintList) {
        let rect = Rect::new(offset.x, offset.y, self.width, self.height);
        let radius = self.radius;

        // 1. 背景 + 描边(未聚焦 1px 边框;聚焦 2px 焦点环)
        if self.focused {
            list.push(PaintCommand::Rect { rect, color: self.focus_ring_color, radius });
            let inner =
                Rect::new(offset.x + RING_T, offset.y + RING_T, self.width - RING_T * 2.0, self.height - RING_T * 2.0);
            list.push(PaintCommand::Rect {
                rect: inner,
                color: self.bg_focused_color,
                radius: (radius - RING_T).max(0.0),
            });
        } else if self.border_color.a > 0.0 {
            list.push(PaintCommand::Rect { rect, color: self.border_color, radius });
            let inner = Rect::new(offset.x + 1.0, offset.y + 1.0, self.width - 2.0, self.height - 2.0);
            list.push(PaintCommand::Rect { rect: inner, color: self.bg_color, radius: (radius - 1.0).max(0.0) });
        } else {
            list.push(PaintCommand::Rect { rect, color: self.bg_color, radius });
        }

        let layout =
            text_field_layout(&self.value, self.width, self.height, self.font_size, self.soft_wrap, self.scroll_y);
        let text_x = offset.x + PAD_X;
        let clip = Rect::new(
            offset.x + PAD_X,
            offset.y + RING_T,
            (self.width - PAD_X * 2.0).max(1.0),
            (self.height - RING_T * 2.0).max(1.0),
        );
        list.push(PaintCommand::PushClip(clip));

        let has_preedit = self.preedit.as_ref().map(|p| !p.is_empty()).unwrap_or(false);

        // Placeholder 单行(无 value/无 preedit 时)
        if self.value.is_empty() && !has_preedit && !self.placeholder.is_empty() {
            // 占位符按自身字形视觉高度居中:value 为空时 layout.line_h 只能
            // 回退 font_size,对 ascent/descent 更大的字体(中文等)会整体偏下
            let ph_line_h = text_visual_height(&self.placeholder, self.font_size, None);
            let ph_total_h = text_visual_height(&self.placeholder, self.font_size, Some(layout.text_width));
            let ph_top = offset.y + ((self.height - ph_total_h) * 0.5).max(0.0);
            paint_text_line(
                &self.placeholder,
                self.font_size,
                self.placeholder_color,
                Point::new(text_x, ph_top),
                list,
                Some(layout.text_width),
            );
            if self.focused {
                self.paint_cursor(list, text_x, ph_top, ph_line_h);
            }
            list.pop_clip();
            return;
        }

        // 选区高亮(逐视觉行交集)
        if let Some((sel_start, sel_end)) = self.selection {
            let sel_color = Color::rgba(0.24, 0.47, 0.95, 0.35);
            for (index, line) in layout.lines.iter().enumerate() {
                let start = sel_start.max(line.start);
                let end = sel_end.min(line.end);
                if start >= end {
                    continue;
                }
                let y = offset.y + layout.top_pad + index as f32 * layout.line_h - layout.scroll_y;
                if y + layout.line_h < offset.y || y > offset.y + self.height {
                    continue;
                }
                let prefix_w = layout.x_at_in_line(&self.value, index, start, self.font_size);
                let end_w = layout.x_at_in_line(&self.value, index, end, self.font_size);
                // RTL 时 end_w < prefix_w,选区块取两者之间的区间
                let left = prefix_w.min(end_w);
                list.push(PaintCommand::Rect {
                    rect: Rect::new(text_x + left, y, (prefix_w - end_w).abs(), layout.line_h),
                    color: sel_color,
                    radius: 0.0,
                });
            }
        }

        // value 逐视觉行绘制(soft wrap 后每行单独绘制,不再二次换行)
        for (index, line) in layout.lines.iter().enumerate() {
            let y = offset.y + layout.top_pad + index as f32 * layout.line_h - layout.scroll_y;
            if y + layout.line_h < offset.y || y > offset.y + self.height {
                continue;
            }
            let text = &self.value[line.start..line.end];
            paint_text_line(text, self.font_size, self.text_color, Point::new(text_x, y), list, None);
        }

        let cursor_index = layout.cursor_line(self.cursor);
        let cursor_y = offset.y + layout.cursor_y(self.cursor);

        if has_preedit {
            let preedit = self.preedit.as_deref().unwrap_or("");
            let line =
                layout.lines.get(cursor_index).copied().unwrap_or(TextFieldLine { hard_line: 0, start: 0, end: 0 });
            let prefix = &self.value[line.start.min(self.cursor)..self.cursor.min(line.end)];
            let preedit_x = text_x + measure_text_width(prefix, self.font_size);
            let cursor_in_preedit = self.preedit_cursor.map(|(s, _)| s.min(preedit.len())).unwrap_or(preedit.len());
            let preedit_cursor_x = text_x
                + measure_text_width(prefix, self.font_size)
                + measure_text_width(&preedit[..cursor_in_preedit], self.font_size);

            if !preedit.is_empty() {
                paint_text_line(
                    preedit,
                    self.font_size,
                    self.text_color,
                    Point::new(preedit_x, cursor_y),
                    list,
                    Some((layout.text_width - (preedit_x - text_x)).max(1.0)),
                );
                let w_preedit = measure_text_width(preedit, self.font_size);
                list.push(PaintCommand::Rect {
                    rect: Rect::new(preedit_x, cursor_y + layout.line_h - 2.0, w_preedit, 1.5),
                    color: self.text_color,
                    radius: 0.0,
                });
            }
            if self.focused && self.cursor_visible {
                self.paint_cursor(list, preedit_cursor_x, cursor_y, layout.line_h);
            }
        } else {
            let cursor_x = text_x + layout.cursor_x(&self.value, self.cursor, self.font_size);
            if self.focused && self.cursor_visible {
                self.paint_cursor(list, cursor_x, cursor_y, layout.line_h);
            }
        }

        list.pop_clip();
    }

    fn hit_test(&self, position: Point, offset: Point) -> Option<ElementId> {
        let rect = Rect::new(offset.x, offset.y, self.width, self.height);
        if rect.contains(position) {
            self.element_id
        } else {
            None
        }
    }

    fn set_element_id(&mut self, id: ElementId) {
        self.element_id = Some(id);
    }

    fn element_id(&self) -> Option<ElementId> {
        self.element_id
    }

    fn content_size(&self) -> Size {
        Size::new(self.width, self.height)
    }

    /// P0-1:就地写回 State 构造的视觉 payload,避免每次输入/闪烁重建 RO。
    fn apply_state(&mut self, state: &mut dyn Any) -> StateApply {
        let Some(a) = state.downcast_mut::<TextFieldApply>() else {
            return StateApply::Unsupported;
        };
        if self.width == a.width
            && self.height == a.height
            && self.font_size == a.font_size
            && self.placeholder == a.placeholder
            && self.value == a.value
            && self.cursor == a.cursor
            && self.preedit == a.preedit
            && self.preedit_cursor == a.preedit_cursor
            && self.focused == a.focused
            && self.cursor_visible == a.cursor_visible
            && self.bg_color == a.bg_color
            && self.bg_focused_color == a.bg_focused_color
            && self.focus_ring_color == a.focus_ring_color
            && self.text_color == a.text_color
            && self.placeholder_color == a.placeholder_color
            && self.cursor_color == a.cursor_color
            && self.selection == a.selection
            && self.soft_wrap == a.soft_wrap
            && self.scroll_y == a.scroll_y
        {
            return StateApply::Unchanged;
        }
        self.width = a.width;
        self.height = a.height;
        self.font_size = a.font_size;
        self.placeholder = std::mem::take(&mut a.placeholder);
        self.value = std::mem::take(&mut a.value);
        self.cursor = a.cursor;
        self.preedit = a.preedit.take();
        self.preedit_cursor = a.preedit_cursor;
        self.focused = a.focused;
        self.cursor_visible = a.cursor_visible;
        self.bg_color = a.bg_color;
        self.bg_focused_color = a.bg_focused_color;
        self.focus_ring_color = a.focus_ring_color;
        self.text_color = a.text_color;
        self.placeholder_color = a.placeholder_color;
        self.cursor_color = a.cursor_color;
        self.selection = a.selection;
        self.soft_wrap = a.soft_wrap;
        self.scroll_y = a.scroll_y;
        StateApply::Updated
    }
}

impl TextFieldRenderObject {
    fn paint_cursor(&self, list: &mut PaintList, x: f32, text_y: f32, line_h: f32) {
        list.push(PaintCommand::Rect {
            rect: Rect::new(x, text_y + 1.0, CURSOR_W, (line_h - 2.0).max(1.0)),
            color: self.cursor_color,
            radius: 0.0,
        });
    }
}

// =============================================================================
// 测试
// =============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn render_object_paints_bg_and_cursor() {
        let mut ro = TextFieldRenderObject {
            width: 200.0,
            height: 40.0,
            font_size: 16.0,
            placeholder: String::new(),
            value: String::new(),
            cursor: 0,
            preedit: None,
            preedit_cursor: None,
            focused: false,
            cursor_visible: true,
            bg_color: Color::BLACK,
            bg_focused_color: Color::BLACK,
            border_color: Color::TRANSPARENT,
            radius: 6.0,
            focus_ring_color: Color::WHITE,
            text_color: Color::WHITE,
            placeholder_color: Color::rgba(0.5, 0.5, 0.5, 1.0),
            cursor_color: Color::WHITE,
            selection: None,
            soft_wrap: false,
            scroll_y: 0.0,
            element_id: None,
        };
        ro.layout(BoxConstraints::UNBOUNDED, &mut LayoutContext);

        let mut list = PaintList::new();
        ro.paint(Point::ZERO, &mut list);
        let rects = list.commands.iter().filter(|c| matches!(c, PaintCommand::Rect { .. })).count();
        assert_eq!(rects, 1, "未聚焦空值:仅背景");

        let mut focused_ro = TextFieldRenderObject { focused: true, value: "hi".to_string(), cursor: 2, ..ro };
        focused_ro.set_element_id(ElementId::default());
        assert!(focused_ro.element_id().is_some());

        let mut list = PaintList::new();
        focused_ro.paint(Point::ZERO, &mut list);
        let rects = list.commands.iter().filter(|c| matches!(c, PaintCommand::Rect { .. })).count();
        let texts = list.commands.iter().filter(|c| matches!(c, PaintCommand::TexturedRect { .. })).count();
        assert_eq!(rects, 3, "ring + bg + cursor");
        assert!(texts >= 1, "文字至少 1 个 glyph rect");
    }

    #[test]
    fn preedit_paints_underline() {
        let mut ro = TextFieldRenderObject {
            width: 200.0,
            height: 40.0,
            font_size: 16.0,
            placeholder: String::new(),
            value: "a".to_string(),
            cursor: 1,
            preedit: Some("中".to_string()),
            preedit_cursor: None,
            focused: true,
            cursor_visible: true,
            bg_color: Color::BLACK,
            bg_focused_color: Color::BLACK,
            border_color: Color::TRANSPARENT,
            radius: 6.0,
            focus_ring_color: Color::WHITE,
            text_color: Color::WHITE,
            placeholder_color: Color::rgba(0.5, 0.5, 0.5, 1.0),
            cursor_color: Color::WHITE,
            selection: None,
            soft_wrap: false,
            scroll_y: 0.0,
            element_id: None,
        };
        ro.layout(BoxConstraints::UNBOUNDED, &mut LayoutContext);
        let mut list = PaintList::new();
        ro.paint(Point::ZERO, &mut list);
        let rects = list.commands.iter().filter(|c| matches!(c, PaintCommand::Rect { .. })).count();
        assert_eq!(rects, 4, "ring + bg + preedit 下划线 + 光标");
    }

    #[test]
    fn placeholder_uses_own_glyph_metrics_for_vertical_centering() {
        fn glyph_bounds(list: &PaintList) -> (f32, f32) {
            let mut min = f32::INFINITY;
            let mut max = f32::NEG_INFINITY;
            for c in &list.commands {
                if let PaintCommand::TexturedRect { rect, .. } = c {
                    min = min.min(rect.y);
                    max = max.max(rect.y + rect.height);
                }
            }
            (min, max)
        }
        fn paint(value: &str, placeholder: &str) -> PaintList {
            let mut ro = TextFieldRenderObject {
                width: 240.0,
                height: 48.0,
                font_size: 16.0,
                placeholder: placeholder.to_string(),
                value: value.to_string(),
                cursor: value.len(),
                preedit: None,
                preedit_cursor: None,
                focused: false,
                cursor_visible: true,
                bg_color: Color::BLACK,
                bg_focused_color: Color::BLACK,
                border_color: Color::TRANSPARENT,
                radius: 6.0,
                focus_ring_color: Color::WHITE,
                text_color: Color::WHITE,
                placeholder_color: Color::rgba(0.5, 0.5, 0.5, 1.0),
                cursor_color: Color::WHITE,
                selection: None,
                soft_wrap: false,
                scroll_y: 0.0,
                element_id: None,
            };
            ro.layout(BoxConstraints::UNBOUNDED, &mut LayoutContext);
            let mut list = PaintList::new();
            ro.paint(Point::ZERO, &mut list);
            list
        }

        // 同一字符串作为 value 与 placeholder 时,字形必须落在同一 y。
        // 旧实现 value 为空 → line_h 回退 font_size,中文 placeholder 整体偏下。
        let ph = paint("", "Ag你好");
        let value = paint("Ag你好", "");
        let (ph_min, ph_max) = glyph_bounds(&ph);
        let (v_min, v_max) = glyph_bounds(&value);
        assert!((ph_min - v_min).abs() < 0.01, "placeholder 顶边应等于同文本 value 顶边");
        assert!((ph_max - v_max).abs() < 0.01, "placeholder 底边应等于同文本 value 底边");
    }

    #[test]
    fn soft_wrap_splits_long_line() {
        let layout = text_field_layout("hello world hello world", 100.0, 80.0, 16.0, true, 0.0);
        assert!(layout.lines.len() > 1, "长行应拆成多条视觉行");
        assert_eq!(layout.lines[0].hard_line, 0);
        assert!(layout.lines.iter().all(|line| line.start <= line.end));
        assert_eq!(layout.lines.first().unwrap().start, 0);
        assert_eq!(layout.lines.last().unwrap().end, "hello world hello world".len());
    }

    #[test]
    fn hard_newlines_preserve_empty_lines() {
        let value = "a\n\nb";
        let layout = text_field_layout(value, 200.0, 100.0, 16.0, false, 0.0);
        assert_eq!(layout.lines.len(), 3);
        assert_eq!(layout.lines[1].start, 2);
        assert_eq!(layout.lines[1].end, 2);
        assert_eq!(layout.lines[2].start, 3);
    }

    #[test]
    fn cursor_and_hit_test_follow_visual_lines() {
        let value = "hello world hello world";
        let layout = text_field_layout(value, 100.0, 80.0, 16.0, true, 0.0);
        let second = layout.lines[1];
        assert!(second.start > 0);

        assert_eq!(layout.cursor_line(second.start), 1);
        assert!(layout.cursor_x(value, second.start, 16.0).abs() < 0.01);
        let y = layout.top_pad + layout.line_h * 1.5;
        assert_eq!(layout.offset_at(value, PAD_X + 1.0, y, 16.0), second.start);
    }

    #[test]
    fn line_runs_include_hard_break_and_offsets() {
        let value = "ab\ncd";
        let layout = text_field_layout(value, 200.0, 100.0, 16.0, false, 0.0);
        let runs = layout.line_runs(value, 16.0);
        assert_eq!(runs.len(), 2);
        assert_eq!(runs[0].value, "ab\n");
        assert_eq!(runs[0].start_char, 0);
        assert_eq!(runs[1].value, "cd");
        assert_eq!(runs[1].start_char, 3);
        assert_eq!(runs[0].bounds.x, PAD_X);
        assert_eq!(runs[1].bounds.y, layout.top_pad + layout.line_h);

        let positions = runs[0].character_positions.as_ref().expect("positions");
        let widths = runs[0].character_widths.as_ref().expect("widths");
        assert_eq!(positions.len(), 3, "换行符计入字符数");
        assert_eq!(widths.len(), 3);
        assert_eq!(widths[2], 0.0, "换行符零宽");
        assert!((positions[2] - (positions[1] + widths[1])).abs() < 0.01, "换行位置在行末");
    }

    #[test]
    fn line_runs_cover_trailing_empty_line_and_soft_wrap() {
        let value = "ab\n";
        let layout = text_field_layout(value, 200.0, 100.0, 16.0, false, 0.0);
        let runs = layout.line_runs(value, 16.0);
        assert_eq!(runs.len(), 2);
        assert_eq!(runs[0].value, "ab\n");
        assert_eq!(runs[1].value, "");
        assert_eq!(runs[1].start_char, 3);
        assert_eq!(runs[1].character_positions.as_ref().map(Vec::len), Some(0));

        let wrapped = "hello world hello world";
        let layout = text_field_layout(wrapped, 100.0, 80.0, 16.0, true, 0.0);
        let runs = layout.line_runs(wrapped, 16.0);
        assert!(runs.len() > 1);
        assert!(runs.iter().all(|run| !run.value.contains('\n')), "软换行不插入硬换行符");
        assert_eq!(runs[0].start_char, 0);
        for pair in runs.windows(2) {
            assert_eq!(pair[1].start_char, pair[0].start_char + pair[0].value.chars().count());
        }
    }

    #[test]
    fn rtl_line_run_positions_start_at_right_edge() {
        let value = "مرحبا";
        let layout = text_field_layout(value, 200.0, 40.0, 16.0, false, 0.0);
        let runs = layout.line_runs(value, 16.0);
        assert_eq!(runs.len(), 1);
        assert!(runs[0].rtl);
        let positions = runs[0].character_positions.as_ref().expect("RTL positions");
        let widths = runs[0].character_widths.as_ref().expect("RTL widths");
        assert_eq!(positions.len(), 5);
        assert_eq!(positions[0], 0.0, "RTL 从右缘起算");
        assert!(widths.iter().all(|width| *width >= 0.0));
        assert!(runs[0].bounds.width >= 0.0);
    }

    #[test]
    fn soft_wrap_paints_multiple_visual_rows() {
        let mut ro = TextFieldRenderObject {
            width: 100.0,
            height: 120.0,
            font_size: 16.0,
            placeholder: String::new(),
            value: "hello world hello world".to_string(),
            cursor: 0,
            preedit: None,
            preedit_cursor: None,
            focused: false,
            cursor_visible: true,
            bg_color: Color::BLACK,
            bg_focused_color: Color::BLACK,
            border_color: Color::TRANSPARENT,
            radius: 6.0,
            focus_ring_color: Color::WHITE,
            text_color: Color::WHITE,
            placeholder_color: Color::rgba(0.5, 0.5, 0.5, 1.0),
            cursor_color: Color::WHITE,
            selection: None,
            soft_wrap: true,
            scroll_y: 0.0,
            element_id: None,
        };
        ro.layout(BoxConstraints::UNBOUNDED, &mut LayoutContext);
        let mut list = PaintList::new();
        ro.paint(Point::ZERO, &mut list);
        let mut rows: Vec<i32> = list
            .commands
            .iter()
            .filter_map(|cmd| match cmd {
                PaintCommand::TexturedRect { rect, .. } => Some(rect.y as i32),
                _ => None,
            })
            .collect();
        rows.sort_unstable();
        rows.dedup();
        assert!(rows.len() > 1, "soft wrap 应绘制多条视觉行(rows={rows:?})");
    }

    #[test]
    fn scroll_to_show_last_line() {
        let value = "one\ntwo\nthree\nfour\nfive";
        let mut layout = text_field_layout(value, 200.0, 40.0, 16.0, false, 0.0);
        assert!(layout.max_scroll > 0.0);
        let cursor = value.rfind("five").unwrap();
        layout.scroll_y = layout.scroll_to_show(cursor);
        assert!(layout.scroll_y > 0.0, "光标在末尾时应向下滚动");
        assert!(layout.scroll_y <= layout.max_scroll);
    }
}

#[cfg(test)]
mod apply_state_tests {
    use super::*;

    fn payload(value: &str, cursor: usize) -> TextFieldApply {
        TextFieldApply {
            width: 200.0,
            height: 40.0,
            font_size: 16.0,
            placeholder: String::new(),
            value: value.into(),
            cursor,
            preedit: None,
            preedit_cursor: None,
            focused: true,
            cursor_visible: true,
            bg_color: Color::BLACK,
            bg_focused_color: Color::BLACK,
            border_color: Color::TRANSPARENT,
            radius: 6.0,
            focus_ring_color: Color::WHITE,
            text_color: Color::WHITE,
            placeholder_color: Color::WHITE,
            cursor_color: Color::WHITE,
            selection: None,
            soft_wrap: false,
            scroll_y: 0.0,
        }
    }

    #[test]
    fn payload_apply_updates_text_field_in_place() {
        let mut ro = TextFieldRenderObject::from(payload("a", 1));
        let mut next = payload("ab", 2);
        assert_eq!(ro.apply_state(&mut next), StateApply::Updated);
        assert_eq!(ro.value, "ab");
        assert_eq!(ro.cursor, 2);

        let mut same = payload("ab", 2);
        assert_eq!(ro.apply_state(&mut same), StateApply::Unchanged);
    }
}

#[cfg(test)]
mod soft_wrap_boundary_tests {
    use super::*;

    /// 中文每字可断,相邻视觉行**共用**边界 byte(`line.end == next.start`)。
    /// 歧义按方向拆开:Home 判给上一行(End 之后能回到刚才那行行首),
    /// End / 光标绘制判给下一行(在该行行首输入就该落在这里)。
    /// 与字体度量无关,Windows / Linux 都稳定命中 —— Gitee Go 首次 Linux 运行暴露的
    /// 就是这个口径差(英文用例恰好有空格可吞,Windows 本地一直测不出来)。
    #[test]
    fn cjk_wrap_boundary_resolves_by_affinity() {
        let value = "一二三四五六七八";
        let layout = text_field_layout(value, 60.0, 40.0, 16.0, true, 0.0);
        assert!(layout.lines.len() >= 2, "60px 宽应把 8 个字断成多行, 实际 {:?}", layout.lines);
        let boundary = layout.lines[0].end;
        assert_eq!(layout.lines[1].start, boundary, "中文换行没有可吞的空格 → 两行共用边界");

        assert_eq!(layout.cursor_line_upstream(boundary), 0, "Home 口径:边界属上一行");
        assert_eq!(layout.cursor_line(boundary), 1, "End / 绘制口径:边界属下一行");
        // 非边界 byte 两个口径一致
        let mid = layout.lines[1].start + 3;
        assert_eq!(layout.cursor_line_upstream(mid), 1);
        assert_eq!(layout.cursor_line(mid), 1);
    }

    #[test]
    fn hard_newline_boundaries_stay_unambiguous() {
        let value = "ab\ncd";
        let layout = text_field_layout(value, 200.0, 60.0, 16.0, true, 0.0);
        assert_eq!(layout.lines.len(), 2, "{:?}", layout.lines);
        assert_eq!(layout.cursor_line(2), 0, "行末(\\n 前)属第一行");
        assert_eq!(layout.cursor_line(3), 1, "第二行行首属第二行");
    }
}