neco-editor-viewport 0.2.0

Viewport geometry calculations for editor rendering
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
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
//! Viewport geometry calculations for editor rendering.
//!
//! Pure geometry: converts between byte offsets, logical/visual lines,
//! and pixel coordinates. No DOM or Canvas dependency.

use neco_textview::{LineIndex, Selection, TextViewError};
use neco_wrap::{
    LayoutMode, LineLayoutPolicy, VisualLayoutSpace, WidthPolicy, WrapMap, WrapPolicy,
};
use std::fmt;

/// Host-injected font metrics. Plain struct (parameter bag).
#[derive(Debug, Clone, Copy)]
pub struct ViewportMetrics {
    pub line_height: f64,
    pub char_width: f64,
    pub cjk_char_width: f64,
    pub tab_width: u32,
}

/// Computed layout measurements.
#[derive(Debug, Clone, Copy)]
pub struct ViewportLayout {
    pub gutter_width: f64,
    pub content_left: f64,
}

/// Axis-aligned rectangle in pixel coordinates.
#[derive(Debug, Clone, Copy)]
pub struct Rect {
    pub x: f64,
    pub y: f64,
    pub width: f64,
    pub height: f64,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct VisualLineFrame {
    layout: VisualLayoutSpace,
}

impl VisualLineFrame {
    pub const fn logical_line(&self) -> u32 {
        self.layout.logical_line()
    }

    pub const fn visual_line(&self) -> u32 {
        self.layout.visual_line()
    }

    pub const fn inline_advance(&self) -> u32 {
        self.layout.inline_advance()
    }

    pub const fn block_advance(&self) -> u32 {
        self.layout.block_advance()
    }

    pub const fn layout_mode(&self) -> LayoutMode {
        self.layout.layout_mode()
    }
}

/// Errors returned by viewport operations.
#[non_exhaustive]
#[derive(Debug)]
pub enum ViewportError {
    TextView(TextViewError),
}

impl fmt::Display for ViewportError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::TextView(e) => write!(f, "text view error: {e}"),
        }
    }
}

impl std::error::Error for ViewportError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::TextView(e) => Some(e),
        }
    }
}

impl From<TextViewError> for ViewportError {
    fn from(e: TextViewError) -> Self {
        Self::TextView(e)
    }
}

// ---------------------------------------------------------------------------
// Helper
// ---------------------------------------------------------------------------

/// Compute the visual width in pixels of `text[start_byte..end_byte]` considering tabs.
fn text_width(
    text: &str,
    start_byte: usize,
    end_byte: usize,
    metrics: &ViewportMetrics,
    width_policy: &WidthPolicy,
) -> f64 {
    let slice = &text[start_byte..end_byte];
    slice
        .chars()
        .map(|ch| char_pixel_width(ch, metrics, width_policy))
        .sum()
}

fn char_pixel_width(ch: char, metrics: &ViewportMetrics, width_policy: &WidthPolicy) -> f64 {
    let advance = width_policy.advance_of(ch);
    if ch == '\t' {
        f64::from(advance) * metrics.char_width
    } else if advance >= 2 {
        metrics.cjk_char_width
    } else {
        metrics.char_width
    }
}

fn u32_to_usize(v: u32) -> usize {
    usize::try_from(v).expect("u32 exceeds usize::MAX")
}

// ---------------------------------------------------------------------------
// Public functions
// ---------------------------------------------------------------------------

/// Returns `(first_visual_line, last_visual_line)` visible in the viewport.
///
/// Clamps to `0..total_visual_lines - 1`.
pub fn visible_line_range(
    scroll_top: f64,
    container_height: f64,
    wrap_map: &WrapMap,
    metrics: &ViewportMetrics,
) -> (u32, u32) {
    let total = wrap_map.total_visual_lines();
    if total == 0 {
        return (0, 0);
    }
    let max_line = total - 1;

    let first_f = scroll_top / metrics.line_height;
    let first = if first_f < 0.0 {
        0u32
    } else {
        let v = first_f as u64;
        u32::try_from(v.min(u64::from(max_line))).expect("clamped value fits u32")
    };

    let last_f = (scroll_top + container_height) / metrics.line_height;
    let last_raw = if last_f < 0.0 {
        0u64
    } else {
        // Subtract 1 because the range is inclusive; if exactly on a boundary
        // the pixel row above is the last visible line. Use ceil-1 approach:
        // any fractional part means we can see part of that line.
        let ceil = last_f.ceil() as u64;
        if ceil == 0 {
            0
        } else {
            ceil - 1
        }
    };
    let last = u32::try_from(last_raw.min(u64::from(max_line))).expect("clamped value fits u32");

    (first, last)
}

/// Compute the pixel rectangle for the caret at `offset`.
pub fn caret_rect(
    text: &str,
    offset: usize,
    line_index: &LineIndex,
    wrap_map: &WrapMap,
    metrics: &ViewportMetrics,
    layout: &ViewportLayout,
) -> Result<Rect, ViewportError> {
    caret_rect_with_width_policy(
        text,
        offset,
        line_index,
        wrap_map,
        metrics,
        layout,
        &WidthPolicy::cjk_grid(metrics.tab_width),
    )
}

pub fn caret_rect_with_width_policy(
    text: &str,
    offset: usize,
    line_index: &LineIndex,
    wrap_map: &WrapMap,
    metrics: &ViewportMetrics,
    layout: &ViewportLayout,
    width_policy: &WidthPolicy,
) -> Result<Rect, ViewportError> {
    let line = line_index.line_of_offset(offset)?;
    let line_range = line_index.line_range(line)?;
    let byte_in_line = offset - line_range.start();
    let byte_in_line_u32 =
        u32::try_from(byte_in_line).expect("byte offset in line exceeds u32::MAX");

    let visual_line = wrap_map.to_visual_line(line, byte_in_line_u32);

    // Determine the start byte (within the line) of this visual sub-line.
    let (_, vl_start_in_line) = wrap_map.from_visual_line(visual_line);
    let vl_start_abs = line_range.start() + u32_to_usize(vl_start_in_line);

    let x = layout.content_left + text_width(text, vl_start_abs, offset, metrics, width_policy);
    let y = f64::from(visual_line) * metrics.line_height;

    Ok(Rect {
        x,
        y,
        width: 2.0,
        height: metrics.line_height,
    })
}

/// Compute the pixel rectangles that cover `selection`.
pub fn selection_rects(
    text: &str,
    selection: &Selection,
    line_index: &LineIndex,
    wrap_map: &WrapMap,
    metrics: &ViewportMetrics,
    layout: &ViewportLayout,
) -> Result<Vec<Rect>, ViewportError> {
    selection_rects_with_width_policy(
        text,
        selection,
        line_index,
        wrap_map,
        metrics,
        layout,
        &WidthPolicy::cjk_grid(metrics.tab_width),
    )
}

pub fn selection_rects_with_width_policy(
    text: &str,
    selection: &Selection,
    line_index: &LineIndex,
    wrap_map: &WrapMap,
    metrics: &ViewportMetrics,
    layout: &ViewportLayout,
    width_policy: &WidthPolicy,
) -> Result<Vec<Rect>, ViewportError> {
    let range = selection.range();
    if range.is_empty() {
        return Ok(Vec::new());
    }

    let start_offset = range.start();
    let end_offset = range.end();

    let start_line = line_index.line_of_offset(start_offset)?;
    let start_line_range = line_index.line_range(start_line)?;
    let start_byte_in_line = start_offset - start_line_range.start();
    let start_byte_u32 =
        u32::try_from(start_byte_in_line).expect("byte offset in line exceeds u32::MAX");
    let first_vl = wrap_map.to_visual_line(start_line, start_byte_u32);

    let end_line = line_index.line_of_offset(end_offset)?;
    let end_line_range = line_index.line_range(end_line)?;
    let end_byte_in_line = end_offset - end_line_range.start();
    let end_byte_u32 =
        u32::try_from(end_byte_in_line).expect("byte offset in line exceeds u32::MAX");
    let last_vl = wrap_map.to_visual_line(end_line, end_byte_u32);

    let mut rects = Vec::new();

    for vl in first_vl..=last_vl {
        let (log_line, vl_start_in_line) = wrap_map.from_visual_line(vl);
        let lr = line_index.line_range(log_line)?;
        let vl_start_abs = lr.start() + u32_to_usize(vl_start_in_line);

        // Determine end of this visual line.
        let total_vl = wrap_map.total_visual_lines();
        let vl_end_abs = if vl + 1 < total_vl {
            let (next_log, next_start_in_line) = wrap_map.from_visual_line(vl + 1);
            if next_log == log_line {
                lr.start() + u32_to_usize(next_start_in_line)
            } else {
                lr.end()
            }
        } else {
            lr.end()
        };

        // Clamp selection to this visual line.
        let sel_start = start_offset.max(vl_start_abs);
        let sel_end = end_offset.min(vl_end_abs);

        if sel_start >= sel_end {
            continue;
        }

        let x =
            layout.content_left + text_width(text, vl_start_abs, sel_start, metrics, width_policy);
        let w = text_width(text, sel_start, sel_end, metrics, width_policy);
        let y = f64::from(vl) * metrics.line_height;

        rects.push(Rect {
            x,
            y,
            width: w,
            height: metrics.line_height,
        });
    }

    Ok(rects)
}

/// Convert a click at pixel `(x, y)` to a byte offset in `text`.
#[allow(clippy::too_many_arguments)]
pub fn hit_test(
    x: f64,
    y: f64,
    scroll_top: f64,
    text: &str,
    line_index: &LineIndex,
    wrap_map: &WrapMap,
    metrics: &ViewportMetrics,
    layout: &ViewportLayout,
) -> usize {
    hit_test_with_width_policy(
        x,
        y,
        scroll_top,
        text,
        line_index,
        wrap_map,
        metrics,
        layout,
        &WidthPolicy::cjk_grid(metrics.tab_width),
    )
}

#[allow(clippy::too_many_arguments)]
pub fn hit_test_with_width_policy(
    x: f64,
    y: f64,
    scroll_top: f64,
    text: &str,
    line_index: &LineIndex,
    wrap_map: &WrapMap,
    metrics: &ViewportMetrics,
    layout: &ViewportLayout,
    width_policy: &WidthPolicy,
) -> usize {
    let total_vl = wrap_map.total_visual_lines();
    if total_vl == 0 {
        return 0;
    }

    // Determine visual line from y coordinate.
    let vl_f = (y + scroll_top) / metrics.line_height;
    let vl_raw = if vl_f < 0.0 { 0u64 } else { vl_f as u64 };
    let vl = u32::try_from(vl_raw.min(u64::from(total_vl - 1))).expect("clamped value fits u32");

    let (log_line, vl_start_in_line) = wrap_map.from_visual_line(vl);
    let lr = match line_index.line_range(log_line) {
        Ok(r) => r,
        Err(_) => return text.len(),
    };
    let vl_start_abs = lr.start() + u32_to_usize(vl_start_in_line);

    // Determine end of this visual line.
    let vl_end_abs = if vl + 1 < total_vl {
        let (next_log, next_start_in_line) = wrap_map.from_visual_line(vl + 1);
        if next_log == log_line {
            lr.start() + u32_to_usize(next_start_in_line)
        } else {
            lr.end()
        }
    } else {
        lr.end()
    };

    // x relative to content area.
    let rel_x = (x - layout.content_left).max(0.0);

    // Walk characters to find the offset.
    let slice = &text[vl_start_abs..vl_end_abs];
    let mut accum = 0.0;
    for (i, ch) in slice.char_indices() {
        let cw = char_pixel_width(ch, metrics, width_policy);
        // If click is within the first half of the character, place caret before it.
        if rel_x < accum + cw * 0.5 {
            return vl_start_abs + i;
        }
        accum += cw;
    }

    // Past end of visual line: clamp to end.
    vl_end_abs
}

/// Compute the line-number gutter width for `total_lines` lines.
pub fn gutter_width(total_lines: u32, metrics: &ViewportMetrics) -> f64 {
    let digit_count = total_lines.max(1).ilog10() + 1;
    f64::from(digit_count) * metrics.char_width + metrics.char_width
}

/// Return the Y pixel coordinate for the top of `visual_line`.
pub fn line_top(visual_line: u32, metrics: &ViewportMetrics) -> f64 {
    f64::from(visual_line) * metrics.line_height
}

#[allow(clippy::too_many_arguments)]
pub fn visual_line_frame(
    text: &str,
    visual_line: u32,
    line_index: &LineIndex,
    wrap_map: &WrapMap,
    _metrics: &ViewportMetrics,
    _layout: &ViewportLayout,
    width_policy: &WidthPolicy,
    line_layout_policy: &LineLayoutPolicy,
) -> Result<VisualLineFrame, ViewportError> {
    let (logical_line, vl_start_in_line) = wrap_map.from_visual_line(visual_line);
    let line_range = line_index.line_range(logical_line)?;
    let total_vl = wrap_map.total_visual_lines();
    let vl_end_in_line = if visual_line + 1 < total_vl {
        let (next_logical_line, next_start_in_line) = wrap_map.from_visual_line(visual_line + 1);
        if next_logical_line == logical_line {
            next_start_in_line
        } else {
            u32::try_from(line_range.end() - line_range.start()).expect("line length fits u32")
        }
    } else {
        u32::try_from(line_range.end() - line_range.start()).expect("line length fits u32")
    };
    let line_text = &text[line_range.start()..line_range.end()];
    let local_visual_line = visual_line - wrap_map.to_visual_line(logical_line, 0);
    let wrap_policy = WrapPolicy::code_with_width_policy(*width_policy);
    let visual_layout = wrap_map.visual_layout_space(
        logical_line,
        local_visual_line,
        line_text,
        &wrap_policy,
        line_layout_policy,
    );
    debug_assert_eq!(
        visual_layout.inline_advance(),
        line_layout_policy.redistributed_inline_width(
            width_policy.text_width(
                &line_text[u32_to_usize(vl_start_in_line)..u32_to_usize(vl_end_in_line)]
            ),
            wrap_map.max_width(),
        )
    );
    Ok(VisualLineFrame {
        layout: visual_layout,
    })
}

/// Compute a new `scroll_top` that reveals the caret at `offset`, or `None` if already visible.
pub fn scroll_to_reveal(
    _text: &str,
    offset: usize,
    scroll_top: f64,
    container_height: f64,
    line_index: &LineIndex,
    wrap_map: &WrapMap,
    metrics: &ViewportMetrics,
) -> Result<Option<f64>, ViewportError> {
    let line = line_index.line_of_offset(offset)?;
    let line_range = line_index.line_range(line)?;
    let byte_in_line = offset - line_range.start();
    let byte_in_line_u32 =
        u32::try_from(byte_in_line).expect("byte offset in line exceeds u32::MAX");
    let vl = wrap_map.to_visual_line(line, byte_in_line_u32);

    let top = f64::from(vl) * metrics.line_height;
    let bottom = top + metrics.line_height;

    if top < scroll_top {
        // Caret is above the viewport.
        Ok(Some(top))
    } else if bottom > scroll_top + container_height {
        // Caret is below the viewport.
        Ok(Some(bottom - container_height))
    } else {
        Ok(None)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use neco_wrap::{LineLayoutPolicy, WidthPolicy, WrapMap, WrapPolicy};

    fn default_metrics() -> ViewportMetrics {
        ViewportMetrics {
            line_height: 20.0,
            char_width: 8.0,
            cjk_char_width: 14.0,
            tab_width: 4,
        }
    }

    fn default_width_policy() -> WidthPolicy {
        WidthPolicy::cjk_grid(4)
    }

    fn default_line_layout_policy() -> LineLayoutPolicy {
        LineLayoutPolicy::horizontal_ltr()
    }

    fn default_layout() -> ViewportLayout {
        ViewportLayout {
            gutter_width: 40.0,
            content_left: 48.0,
        }
    }

    fn make_wrap_map(text: &str, max_width: u32) -> WrapMap {
        let lines: Vec<&str> = text.split('\n').collect();
        WrapMap::new(lines.iter().copied(), max_width, &WrapPolicy::code())
    }

    // -----------------------------------------------------------------------
    // visible_line_range
    // -----------------------------------------------------------------------

    #[test]
    fn visible_line_range_single_line() {
        let text = "hello";
        let wm = make_wrap_map(text, 80);
        let metrics = default_metrics();
        let (first, last) = visible_line_range(0.0, 100.0, &wm, &metrics);
        assert_eq!(first, 0);
        assert_eq!(last, 0);
    }

    #[test]
    fn visible_line_range_multi_line() {
        let text = "aaa\nbbb\nccc\nddd\neee";
        let wm = make_wrap_map(text, 80);
        let metrics = default_metrics();
        // Container shows 3 lines (60px / 20px = 3 lines).
        let (first, last) = visible_line_range(0.0, 60.0, &wm, &metrics);
        assert_eq!(first, 0);
        assert_eq!(last, 2);
    }

    #[test]
    fn visible_line_range_scrolled() {
        let text = "aaa\nbbb\nccc\nddd\neee";
        let wm = make_wrap_map(text, 80);
        let metrics = default_metrics();
        // scroll_top=40 means first visible is line 2.
        let (first, last) = visible_line_range(40.0, 40.0, &wm, &metrics);
        assert_eq!(first, 2);
        assert_eq!(last, 3);
    }

    #[test]
    fn visible_line_range_with_wrapping() {
        // "ab cd ef" with max_width=4 wraps into 3 visual lines.
        let text = "ab cd ef";
        let wm = make_wrap_map(text, 4);
        let metrics = default_metrics();
        let total = wm.total_visual_lines();
        assert_eq!(total, 3);
        let (first, last) = visible_line_range(0.0, 60.0, &wm, &metrics);
        assert_eq!(first, 0);
        assert_eq!(last, 2);
    }

    #[test]
    fn visible_line_range_clamps_past_end() {
        let text = "aaa\nbbb";
        let wm = make_wrap_map(text, 80);
        let metrics = default_metrics();
        let (first, last) = visible_line_range(0.0, 1000.0, &wm, &metrics);
        assert_eq!(first, 0);
        assert_eq!(last, 1);
    }

    // -----------------------------------------------------------------------
    // caret_rect
    // -----------------------------------------------------------------------

    #[test]
    fn caret_rect_line_start() {
        let text = "hello\nworld";
        let li = LineIndex::new(text);
        let wm = make_wrap_map(text, 80);
        let metrics = default_metrics();
        let layout = default_layout();
        let width_policy = default_width_policy();

        let r = caret_rect_with_width_policy(text, 0, &li, &wm, &metrics, &layout, &width_policy)
            .unwrap();
        assert!((r.x - layout.content_left).abs() < f64::EPSILON);
        assert!((r.y - 0.0).abs() < f64::EPSILON);
        assert!((r.height - 20.0).abs() < f64::EPSILON);
    }

    #[test]
    fn caret_rect_line_middle() {
        let text = "hello\nworld";
        let li = LineIndex::new(text);
        let wm = make_wrap_map(text, 80);
        let metrics = default_metrics();
        let layout = default_layout();
        let width_policy = default_width_policy();

        // offset 3 = 'l' in "hello", x = content_left + 3 * char_width
        let r = caret_rect_with_width_policy(text, 3, &li, &wm, &metrics, &layout, &width_policy)
            .unwrap();
        let expected_x = layout.content_left + 3.0 * metrics.char_width;
        assert!((r.x - expected_x).abs() < f64::EPSILON);
        assert!((r.y - 0.0).abs() < f64::EPSILON);
    }

    #[test]
    fn caret_rect_second_line() {
        let text = "hello\nworld";
        let li = LineIndex::new(text);
        let wm = make_wrap_map(text, 80);
        let metrics = default_metrics();
        let layout = default_layout();
        let width_policy = default_width_policy();

        // offset 6 = start of "world", visual line 1.
        let r = caret_rect_with_width_policy(text, 6, &li, &wm, &metrics, &layout, &width_policy)
            .unwrap();
        assert!((r.x - layout.content_left).abs() < f64::EPSILON);
        assert!((r.y - 20.0).abs() < f64::EPSILON);
    }

    #[test]
    fn caret_rect_wrapped_line() {
        // "ab cd ef" wraps at width 4 into 3 visual lines:
        // vl0: "ab " (bytes 0..3), vl1: "cd " (bytes 3..6), vl2: "ef" (bytes 6..8)
        let text = "ab cd ef";
        let li = LineIndex::new(text);
        let wm = make_wrap_map(text, 4);
        let metrics = default_metrics();
        let layout = default_layout();
        let width_policy = default_width_policy();

        // offset 4 = 'd' in "cd ", which is on visual line 1, column 1.
        let r = caret_rect_with_width_policy(text, 4, &li, &wm, &metrics, &layout, &width_policy)
            .unwrap();
        let expected_x = layout.content_left + 1.0 * metrics.char_width;
        assert!((r.x - expected_x).abs() < f64::EPSILON);
        assert!((r.y - 20.0).abs() < f64::EPSILON);
    }

    // -----------------------------------------------------------------------
    // hit_test
    // -----------------------------------------------------------------------

    #[test]
    fn hit_test_basic() {
        let text = "hello\nworld";
        let li = LineIndex::new(text);
        let wm = make_wrap_map(text, 80);
        let metrics = default_metrics();
        let layout = default_layout();
        let width_policy = default_width_policy();

        // Click at start of first line.
        let offset = hit_test_with_width_policy(
            layout.content_left,
            0.0,
            0.0,
            text,
            &li,
            &wm,
            &metrics,
            &layout,
            &width_policy,
        );
        assert_eq!(offset, 0);
    }

    #[test]
    fn hit_test_middle_of_line() {
        let text = "hello";
        let li = LineIndex::new(text);
        let wm = make_wrap_map(text, 80);
        let metrics = default_metrics();
        let layout = default_layout();
        let width_policy = default_width_policy();

        // Click at x = content_left + 2.5 * char_width -> offset 3 (past midpoint of char 2).
        let x = layout.content_left + 2.5 * metrics.char_width;
        let offset = hit_test_with_width_policy(
            x,
            0.0,
            0.0,
            text,
            &li,
            &wm,
            &metrics,
            &layout,
            &width_policy,
        );
        assert_eq!(offset, 3);
    }

    #[test]
    fn hit_test_gutter_area_clamps_to_line_start() {
        let text = "hello\nworld";
        let li = LineIndex::new(text);
        let wm = make_wrap_map(text, 80);
        let metrics = default_metrics();
        let layout = default_layout();
        let width_policy = default_width_policy();

        // Click in gutter (x=0), second line (y=25).
        let offset = hit_test_with_width_policy(
            0.0,
            25.0,
            0.0,
            text,
            &li,
            &wm,
            &metrics,
            &layout,
            &width_policy,
        );
        assert_eq!(offset, 6); // start of "world"
    }

    #[test]
    fn hit_test_wrapped_line() {
        let text = "ab cd ef";
        let li = LineIndex::new(text);
        let wm = make_wrap_map(text, 4);
        let metrics = default_metrics();
        let layout = default_layout();
        let width_policy = default_width_policy();

        // Click on visual line 2 (y=40..60), at content_left -> offset 6 ("ef").
        let offset = hit_test_with_width_policy(
            layout.content_left,
            45.0,
            0.0,
            text,
            &li,
            &wm,
            &metrics,
            &layout,
            &width_policy,
        );
        assert_eq!(offset, 6);
    }

    #[test]
    fn hit_test_past_end_of_line() {
        let text = "hi";
        let li = LineIndex::new(text);
        let wm = make_wrap_map(text, 80);
        let metrics = default_metrics();
        let layout = default_layout();
        let width_policy = default_width_policy();

        // Click far to the right.
        let offset = hit_test_with_width_policy(
            layout.content_left + 500.0,
            0.0,
            0.0,
            text,
            &li,
            &wm,
            &metrics,
            &layout,
            &width_policy,
        );
        assert_eq!(offset, 2);
    }

    // -----------------------------------------------------------------------
    // gutter_width
    // -----------------------------------------------------------------------

    #[test]
    fn gutter_width_1_line() {
        let metrics = default_metrics();
        let w = gutter_width(1, &metrics);
        // 1 digit + 1 padding = 2 * 8 = 16
        assert!((w - 16.0).abs() < f64::EPSILON);
    }

    #[test]
    fn gutter_width_10_lines() {
        let metrics = default_metrics();
        let w = gutter_width(10, &metrics);
        // 2 digits + 1 padding = 3 * 8 = 24
        assert!((w - 24.0).abs() < f64::EPSILON);
    }

    #[test]
    fn gutter_width_100_lines() {
        let metrics = default_metrics();
        let w = gutter_width(100, &metrics);
        // 3 digits + 1 padding = 4 * 8 = 32
        assert!((w - 32.0).abs() < f64::EPSILON);
    }

    #[test]
    fn gutter_width_1000_lines() {
        let metrics = default_metrics();
        let w = gutter_width(1000, &metrics);
        // 4 digits + 1 padding = 5 * 8 = 40
        assert!((w - 40.0).abs() < f64::EPSILON);
    }

    // -----------------------------------------------------------------------
    // line_top
    // -----------------------------------------------------------------------

    #[test]
    fn line_top_zero() {
        let metrics = default_metrics();
        assert!((line_top(0, &metrics) - 0.0).abs() < f64::EPSILON);
    }

    #[test]
    fn line_top_five() {
        let metrics = default_metrics();
        assert!((line_top(5, &metrics) - 100.0).abs() < f64::EPSILON);
    }

    #[test]
    fn line_top_ten() {
        let metrics = default_metrics();
        assert!((line_top(10, &metrics) - 200.0).abs() < f64::EPSILON);
    }

    // -----------------------------------------------------------------------
    // scroll_to_reveal
    // -----------------------------------------------------------------------

    #[test]
    fn scroll_to_reveal_already_visible() {
        let text = "aaa\nbbb\nccc\nddd\neee";
        let li = LineIndex::new(text);
        let wm = make_wrap_map(text, 80);
        let metrics = default_metrics();

        // Offset 4 is line 1, visual line 1. scroll_top=0, container=100.
        let result = scroll_to_reveal(text, 4, 0.0, 100.0, &li, &wm, &metrics).unwrap();
        assert!(result.is_none());
    }

    #[test]
    fn scroll_to_reveal_above_viewport() {
        let text = "aaa\nbbb\nccc\nddd\neee";
        let li = LineIndex::new(text);
        let wm = make_wrap_map(text, 80);
        let metrics = default_metrics();

        // Offset 0 is visual line 0 (top=0). scroll_top=40 means it is above.
        let result = scroll_to_reveal(text, 0, 40.0, 40.0, &li, &wm, &metrics).unwrap();
        assert_eq!(result, Some(0.0));
    }

    #[test]
    fn scroll_to_reveal_below_viewport() {
        let text = "aaa\nbbb\nccc\nddd\neee";
        let li = LineIndex::new(text);
        let wm = make_wrap_map(text, 80);
        let metrics = default_metrics();

        // Offset 16 is line 4, visual line 4 (top=80, bottom=100).
        // scroll_top=0, container=40 -> viewport covers 0..40. Line 4 is below.
        let result = scroll_to_reveal(text, 16, 0.0, 40.0, &li, &wm, &metrics).unwrap();
        // new scroll_top = bottom - container_height = 100 - 40 = 60
        assert_eq!(result, Some(60.0));
    }

    // -----------------------------------------------------------------------
    // selection_rects
    // -----------------------------------------------------------------------

    #[test]
    fn selection_rects_empty_selection() {
        let text = "hello";
        let li = LineIndex::new(text);
        let wm = make_wrap_map(text, 80);
        let metrics = default_metrics();
        let layout = default_layout();
        let width_policy = default_width_policy();

        let sel = Selection::cursor(2);
        let rects = selection_rects_with_width_policy(
            text,
            &sel,
            &li,
            &wm,
            &metrics,
            &layout,
            &width_policy,
        )
        .unwrap();
        assert!(rects.is_empty());
    }

    #[test]
    fn selection_rects_single_line() {
        let text = "hello";
        let li = LineIndex::new(text);
        let wm = make_wrap_map(text, 80);
        let metrics = default_metrics();
        let layout = default_layout();
        let width_policy = default_width_policy();

        let sel = Selection::new(1, 4); // "ell"
        let rects = selection_rects_with_width_policy(
            text,
            &sel,
            &li,
            &wm,
            &metrics,
            &layout,
            &width_policy,
        )
        .unwrap();
        assert_eq!(rects.len(), 1);
        let r = &rects[0];
        let expected_x = layout.content_left + 1.0 * metrics.char_width;
        assert!((r.x - expected_x).abs() < f64::EPSILON);
        assert!((r.width - 3.0 * metrics.char_width).abs() < f64::EPSILON);
    }

    #[test]
    fn selection_rects_multi_line() {
        let text = "aaa\nbbb\nccc";
        let li = LineIndex::new(text);
        let wm = make_wrap_map(text, 80);
        let metrics = default_metrics();
        let layout = default_layout();
        let width_policy = default_width_policy();

        // Select from middle of line 0 to middle of line 2.
        let sel = Selection::new(1, 9); // "aa\nbbb\nc"
        let rects = selection_rects_with_width_policy(
            text,
            &sel,
            &li,
            &wm,
            &metrics,
            &layout,
            &width_policy,
        )
        .unwrap();
        assert_eq!(rects.len(), 3);
    }

    // -----------------------------------------------------------------------
    // roundtrip: caret_rect -> hit_test
    // -----------------------------------------------------------------------

    #[test]
    fn roundtrip_caret_hit_test() {
        let text = "hello\nworld";
        let li = LineIndex::new(text);
        let wm = make_wrap_map(text, 80);
        let metrics = default_metrics();
        let layout = default_layout();
        let width_policy = default_width_policy();

        for offset in [0, 3, 5, 6, 9, 11] {
            let r = caret_rect_with_width_policy(
                text,
                offset,
                &li,
                &wm,
                &metrics,
                &layout,
                &width_policy,
            )
            .unwrap();
            // Hit test at the caret position should return the same offset.
            let got = hit_test_with_width_policy(
                r.x,
                r.y,
                0.0,
                text,
                &li,
                &wm,
                &metrics,
                &layout,
                &width_policy,
            );
            assert_eq!(got, offset, "roundtrip failed at offset {offset}");
        }
    }

    #[test]
    fn roundtrip_caret_hit_test_wrapped() {
        let text = "ab cd ef";
        let li = LineIndex::new(text);
        let wm = make_wrap_map(text, 4);
        let metrics = default_metrics();
        let layout = default_layout();
        let width_policy = default_width_policy();

        for offset in [0, 3, 6] {
            let r = caret_rect_with_width_policy(
                text,
                offset,
                &li,
                &wm,
                &metrics,
                &layout,
                &width_policy,
            )
            .unwrap();
            let got = hit_test_with_width_policy(
                r.x,
                r.y,
                0.0,
                text,
                &li,
                &wm,
                &metrics,
                &layout,
                &width_policy,
            );
            assert_eq!(got, offset, "roundtrip failed at offset {offset}");
        }
    }

    // -----------------------------------------------------------------------
    // text_width helper
    // -----------------------------------------------------------------------

    #[test]
    fn text_width_with_tabs() {
        let metrics = default_metrics();
        let width_policy = default_width_policy();
        let text = "a\tb";
        // 'a' = 8, '\t' = 4*8=32, 'b' = 8 -> total 48
        let w = text_width(text, 0, text.len(), &metrics, &width_policy);
        assert!((w - 48.0).abs() < f64::EPSILON);
    }

    #[test]
    fn text_width_empty() {
        let metrics = default_metrics();
        let width_policy = default_width_policy();
        let w = text_width("hello", 2, 2, &metrics, &width_policy);
        assert!((w - 0.0).abs() < f64::EPSILON);
    }

    #[test]
    fn text_width_uses_measured_cjk_width_without_changing_tabs() {
        let metrics = default_metrics();
        let width_policy = default_width_policy();
        let text = "aあ\tb";

        let w = text_width(text, 0, text.len(), &metrics, &width_policy);

        assert!((w - 62.0).abs() < f64::EPSILON);
    }

    #[test]
    fn caret_rect_uses_measured_cjk_width() {
        let text = "aあ";
        let li = LineIndex::new(text);
        let wm = make_wrap_map(text, 80);
        let metrics = default_metrics();
        let layout = default_layout();
        let width_policy = WidthPolicy::cjk_grid(4);

        let r = caret_rect_with_width_policy(
            text,
            text.len(),
            &li,
            &wm,
            &metrics,
            &layout,
            &width_policy,
        )
        .unwrap();

        let expected_x = layout.content_left + 22.0;
        assert!((r.x - expected_x).abs() < f64::EPSILON);
    }

    #[test]
    fn hit_test_uses_measured_cjk_width() {
        let text = "aあb";
        let li = LineIndex::new(text);
        let wm = make_wrap_map(text, 80);
        let metrics = default_metrics();
        let layout = default_layout();
        let width_policy = WidthPolicy::cjk_grid(4);

        let got = hit_test_with_width_policy(
            layout.content_left + 23.0,
            0.0,
            0.0,
            text,
            &li,
            &wm,
            &metrics,
            &layout,
            &width_policy,
        );

        assert_eq!(got, "aあ".len());
    }

    #[test]
    fn caret_rect_uses_measured_width_for_cjk_grid() {
        let text = "aあ";
        let li = LineIndex::new(text);
        let wm = make_wrap_map(text, 80);
        let metrics = default_metrics();
        let layout = default_layout();
        let width_policy = WidthPolicy::cjk_grid(4);

        let r = caret_rect_with_width_policy(
            text,
            "aあ".len(),
            &li,
            &wm,
            &metrics,
            &layout,
            &width_policy,
        )
        .unwrap();

        let expected_x = layout.content_left + metrics.char_width + metrics.cjk_char_width;
        assert!((r.x - expected_x).abs() < f64::EPSILON);
    }

    #[test]
    fn visual_line_frame_exposes_visual_layout_space() {
        let text = "ab cd";
        let li = LineIndex::new(text);
        let wm = make_wrap_map(text, 3);
        let metrics = default_metrics();
        let layout = default_layout();
        let width_policy = default_width_policy();

        let frame = visual_line_frame(
            text,
            1,
            &li,
            &wm,
            &metrics,
            &layout,
            &width_policy,
            &default_line_layout_policy(),
        )
        .unwrap();

        assert_eq!(frame.logical_line(), 0);
        assert_eq!(frame.visual_line(), 1);
        assert_eq!(frame.inline_advance(), 2);
        assert_eq!(frame.block_advance(), 1);
        assert_eq!(frame.layout_mode(), LayoutMode::HorizontalLtr);
    }

    #[test]
    fn visual_line_frame_uses_line_layout_policy_width_redistribution() {
        fn justify_to_max(_line_width: u32, max_width: u32) -> u32 {
            max_width
        }

        let text = "ab";
        let li = LineIndex::new(text);
        let wm = make_wrap_map(text, 6);
        let metrics = default_metrics();
        let layout = default_layout();
        let width_policy = default_width_policy();
        let line_layout_policy = LineLayoutPolicy::new(LayoutMode::HorizontalLtr, justify_to_max);

        let frame = visual_line_frame(
            text,
            0,
            &li,
            &wm,
            &metrics,
            &layout,
            &width_policy,
            &line_layout_policy,
        )
        .unwrap();

        assert_eq!(frame.inline_advance(), 6);
        assert_eq!(frame.layout_mode(), LayoutMode::HorizontalLtr);
    }
}