quadraui 0.6.0

Cross-platform Rust UI toolkit: write one AppLogic and run it unmodified on TUI, GTK4 (Linux), macOS, and Windows backends
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
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
//! `Terminal` primitive: a 2D grid of styled cells, used as the rendering
//! surface for VT100-compatible terminal emulators.
//!
//! The primitive is a *snapshot* — the source-of-truth (vimcode's
//! `vt100::Parser` + `TerminalPane` history ring buffer) lives in the
//! engine. Each frame the engine builds a fresh `Terminal` describing
//! the cells visible at the current scroll offset, including any
//! selection / cursor / find-match overlays.
//!
//! Per-cell foreground/background are explicit `Color` values rather than
//! palette indices — vimcode resolves vt100 palette colors through the
//! active theme before populating the cell grid, so the primitive is
//! palette-agnostic.
//!
//! # Backend contract
//!
//! **Purely declarative.** Iterate `cells[row][col]` and rasterise each
//! cell at its grid position. Per-cell `bold` / `italic` / `underline`
//! flags map to the backend's font/attr system. The `selected` /
//! `is_cursor` / `is_find_match` overlays use theme colours; backends
//! typically invert fg/bg for cursor cells and apply a colour
//! highlight for selection / find matches.
//!
//! Mouse interaction (selection drag, click-to-position) and keyboard
//! input (forward to PTY) live **outside** the primitive — they're the
//! app/backend's responsibility. The primitive is a paint snapshot,
//! not an interactive widget.
//!
//! For high-FPS terminals (60+ fps), backends may compare consecutive
//! `Terminal` snapshots and only repaint changed cells. Reference
//! implementations currently repaint the whole grid each frame — fine
//! for typical workloads, optimise when profiling shows it's hot.

use crate::event::Rect;
use crate::types::{Color, Modifiers, WidgetId};
use serde::{Deserialize, Serialize};

/// Declarative description of a terminal cell grid.
///
/// `cells[row][col]` — outer Vec is rows top-to-bottom, inner Vec is
/// columns left-to-right. Rows may be ragged (different lengths) but
/// backends should treat missing trailing cells as blank.
///
/// Stays a plain, non-`#[non_exhaustive]` struct: a published consumer
/// builds it with an exhaustive struct literal today, so marking it
/// `#[non_exhaustive]` would break that consumer's build. `Default` is
/// still provided for consumers that want the
/// `Default::default()`-plus-field-assignment pattern.
///
/// # Examples
///
/// ```
/// use quadraui::{Color, Terminal, TerminalCell, TerminalHit, WidgetId};
///
/// let cell = TerminalCell {
///     text: "$".to_string(),
///     fg: Color::rgb(200, 200, 200),
///     bg: Color::rgb(0, 0, 0),
///     bold: false,
///     italic: false,
///     underline: false,
///     dim: false,
///     selected: false,
///     is_cursor: true,
///     cursor_shape: Default::default(),
///     cursor_blinking: false,
///     is_find_match: false,
///     is_find_active: false,
/// };
///
/// let mut terminal = Terminal::default();
/// terminal.id = WidgetId::new("terminal:shell");
/// terminal.cells = vec![vec![cell]];
///
/// let layout = terminal.layout(80.0, 24.0, 1.0, 1.0);
/// assert_eq!(layout.hit_test(0.0, 0.0), TerminalHit::Cell { row: 0, col: 0 });
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Terminal {
    pub id: WidgetId,
    pub cells: Vec<Vec<TerminalCell>>,
    /// When present, the rasteriser draws a themed scrollbar using the
    /// same style as editor scrollbars (`Backend::draw_scrollbar`).
    #[serde(default)]
    pub scrollbar: Option<TerminalScrollbar>,
}

impl Default for Terminal {
    /// An empty-id terminal with no cells and no scrollbar.
    fn default() -> Self {
        Self {
            id: WidgetId::new(""),
            cells: Vec::new(),
            scrollbar: None,
        }
    }
}

/// Scrollbar state for a `Terminal`. The rasteriser constructs a
/// [`crate::Scrollbar::vertical`] from these values and the terminal's
/// rect, then delegates to `Backend::draw_scrollbar` for themed
/// rendering.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct TerminalScrollbar {
    pub total_lines: usize,
    pub visible_lines: usize,
    pub scroll_offset: usize,
    /// When `true`, `scroll_offset = 0` means "at the bottom" (live
    /// view) and increasing offset scrolls up into history. The
    /// rasteriser flips the offset before constructing the visual
    /// scrollbar so the thumb sits at the bottom when offset is 0.
    #[serde(default)]
    pub inverted: bool,
    /// Scrollbar width in surface-native units (pixels for GTK, cells
    /// for TUI). When `None`, the rasteriser picks a default (8px GTK,
    /// 1 cell TUI).
    #[serde(default)]
    pub width: Option<u16>,
}

impl TerminalScrollbar {
    /// Scroll offset suitable for `Scrollbar::vertical`. When
    /// `inverted`, flips so offset 0 maps to the track bottom.
    pub fn effective_scroll_offset(&self) -> usize {
        if self.inverted {
            self.total_lines
                .saturating_sub(self.visible_lines)
                .saturating_sub(self.scroll_offset)
        } else {
            self.scroll_offset
        }
    }
}

/// One styled cell in a `Terminal`. Carries the rendered grapheme
/// cluster, RGB foreground/background, attributes, and overlay flags
/// (cursor / selection / find match) that the backend interprets
/// visually.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TerminalCell {
    /// The cell's full grapheme cluster — a base character plus any
    /// combining marks (accents, etc.) vt100 appended to it, e.g. `"a"`,
    /// `"日"`, or `"e\u{0301}"`. **Not** guaranteed to be a single
    /// `char`: use [`TerminalCell::cell_width`] rather than
    /// `text.chars().count()` to measure it. Blank / never-written cells
    /// store a single space (`" "`), matching vt100's own convention for
    /// an empty cell.
    pub text: String,
    pub fg: Color,
    pub bg: Color,
    #[serde(default)]
    pub bold: bool,
    #[serde(default)]
    pub italic: bool,
    #[serde(default)]
    pub underline: bool,
    /// SGR 2 (faint/dim) — `vt100::Cell::dim()`. Rasterisers don't
    /// apply a separate font attribute for it (unlike bold/italic/underline):
    /// faint text has no font-weight equivalent, so
    /// [`crate::terminal_style::resolve_cell_style`] folds it into the
    /// resolved foreground colour instead, blending toward the
    /// resolved background so it reads as "faded" on both dark and
    /// light themes.
    #[serde(default)]
    pub dim: bool,
    /// Cell is part of the user's mouse selection.
    #[serde(default)]
    pub selected: bool,
    /// Cell holds the VT100 cursor position. Backends typically render
    /// this with inverted colours — except when [`cursor_shape`](Self::cursor_shape)
    /// is [`TerminalCursorShape::Underline`] or [`TerminalCursorShape::Bar`],
    /// where inverting the whole cell would look like a solid block again;
    /// see [`crate::terminal_style::resolve_cell_style`]'s doc for the
    /// shape-dependent color rule and [`crate::terminal_style::cursor_accent_rect`]
    /// for the separate accent geometry pixel-based rasterisers paint on top.
    #[serde(default)]
    pub is_cursor: bool,
    /// Shape of the VT100 cursor at this cell, from the child program's
    /// most recent DECSCUSR request (`ESC [ Ps SP q`) — see
    /// [`crate::terminal_engine::TerminalSession::cursor_shape`].
    /// Meaningful only when [`is_cursor`](Self::is_cursor)
    /// is `true`; every other cell carries the default (`Block`).
    #[serde(default)]
    pub cursor_shape: TerminalCursorShape,
    /// `true` when the child requested a *blinking* DECSCUSR variant
    /// (odd `Ps` values `1`/`3`/`5`) rather than steady (`2`/`4`/`6`).
    /// Meaningful only when [`is_cursor`](Self::is_cursor) is `true`.
    /// Pixel-based rasterisers (GTK/macOS/win, via
    /// [`crate::terminal_style::cursor_blink_visible`]) toggle the
    /// cursor's visibility on a wall-clock timer when this is set; the
    /// TUI rasteriser ignores it.
    #[serde(default)]
    pub cursor_blinking: bool,
    /// Cell is part of a non-active find match (dim highlight).
    #[serde(default)]
    pub is_find_match: bool,
    /// Cell is part of the currently-selected find match (bright highlight).
    #[serde(default)]
    pub is_find_active: bool,
}

/// Shape of the VT100 cursor, as steered by the child program's DECSCUSR
/// (`ESC [ Ps SP q`) request — see
/// [`crate::terminal_engine::TerminalSession::cursor_shape`].
///
/// Distinct from [`crate::primitives::editor::CursorShape`], even though
/// the three variants happen to share the same DECSCUSR vocabulary: a
/// shell's insert-mode bar cursor and an editor's insert-mode bar cursor
/// are unrelated primitives' concepts, so this crate keeps them as separate
/// types rather than reusing one across `Terminal` and `Editor`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub enum TerminalCursorShape {
    /// Filled block — the default when the child never sends DECSCUSR.
    #[default]
    Block,
    /// Underline.
    Underline,
    /// Thin vertical bar, common in shells' insert-mode line editors
    /// (e.g. zsh/vim insert mode).
    Bar,
}

impl TerminalCell {
    /// Display width of this cell's grapheme cluster in terminal columns
    /// — `1` for ordinary text, `2` for CJK / emoji / other fullwidth
    /// glyphs. Combining marks trailing the base character add no width.
    ///
    /// Deliberately *derived* from `text` rather than cached in a
    /// separate field: `text` is the single source of truth, so there is
    /// no way for a cell's stored width to drift from its own content.
    /// Delegates to [`crate::text_util::display_width`] — the same
    /// `unicode-width`-backed table vt100 itself consults when it
    /// decides whether to reserve a spacer column for a wide character,
    /// so this always agrees with vt100's own column
    /// accounting for cells built by [`crate::terminal_engine`].
    pub fn cell_width(&self) -> u16 {
        crate::text_util::display_width(&self.text) as u16
    }
}

// ── D6 Layout API ───────────────────────────────────────────────────────────
//
// Per Decision D6: primitives return fully-resolved `Layout` structs.
// Ninth and last primitive on the new shape. Terminal is a uniform cell
// grid — layout here just resolves viewport dimensions to grid sizes
// and provides click-to-cell mapping. The cell contents are rendered
// directly from `cells[row][col]`; the layout method doesn't walk
// them.

/// Cell dimensions supplied by the backend. TUI passes `(1.0, 1.0)`
/// (char-cell units) for this embedded [`Terminal`] primitive's own layout;
/// native backends pass the font's advance width and line height.
///
/// Reused for a second, distinct purpose: outside this
/// primitive, [`crate::tui::backend::TuiBackend::cell_pixel_size`] carries
/// the *real* pixel size of a terminal cell — genuinely non-identity on TUI
/// — so SGR-Pixels mouse reports (`?1016h`) can be divided back into
/// fractional cell coordinates. Don't assume `(1.0, 1.0)` from this doc
/// alone when reading code that touches that field.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct TerminalCellSize {
    pub width: f32,
    pub height: f32,
}

impl TerminalCellSize {
    pub fn new(width: f32, height: f32) -> Self {
        Self { width, height }
    }
}

/// Classification of a hit-test result. For terminals every click maps
/// to a grid cell (row, col) — except clicks outside the viewport or
/// below the last rendered row.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TerminalHit {
    Cell { row: u16, col: u16 },
    Empty,
}

/// Fully-resolved terminal layout. Because the cell grid is uniform,
/// there's no `visible_cells` list — backends iterate
/// `terminal.cells` directly at grid positions. The layout provides
/// the viewport → grid conversion and click hit-testing.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct TerminalLayout {
    pub viewport_width: f32,
    pub viewport_height: f32,
    pub cell_size: TerminalCellSize,
    /// Number of rows that fit in the viewport (may differ from
    /// `terminal.cells.len()`; use `grid_rows.min(cells.len())` when
    /// iterating).
    pub grid_rows: u16,
    /// Number of columns that fit in the viewport.
    pub grid_cols: u16,
}

impl TerminalLayout {
    /// Convert a point in the viewport to a grid cell, or `Empty` if
    /// the point is outside the rendered grid.
    pub fn hit_test(&self, x: f32, y: f32) -> TerminalHit {
        if x < 0.0
            || y < 0.0
            || x >= self.viewport_width
            || y >= self.viewport_height
            || self.cell_size.width <= 0.0
            || self.cell_size.height <= 0.0
        {
            return TerminalHit::Empty;
        }
        let col = (x / self.cell_size.width).floor() as u32;
        let row = (y / self.cell_size.height).floor() as u32;
        if row < self.grid_rows as u32 && col < self.grid_cols as u32 {
            TerminalHit::Cell {
                row: row as u16,
                col: col as u16,
            }
        } else {
            TerminalHit::Empty
        }
    }

    /// Rectangle occupied by cell `(row, col)`, or `None` if the cell
    /// is outside the grid.
    pub fn cell_bounds(&self, row: u16, col: u16) -> Option<Rect> {
        if row >= self.grid_rows || col >= self.grid_cols {
            return None;
        }
        Some(Rect::new(
            col as f32 * self.cell_size.width,
            row as f32 * self.cell_size.height,
            self.cell_size.width,
            self.cell_size.height,
        ))
    }
}

impl Terminal {
    /// Compare `self` against the previously-painted `prev` snapshot and
    /// return the indices of rows whose cell content differs.
    ///
    /// Returns `None` when a full repaint is required rather than a
    /// row-by-row diff: the two grids have different row counts, so
    /// `prev`'s row `i` doesn't necessarily correspond to `self`'s row
    /// `i` (a resize/reflow shifted everything). Returns `Some(rows)`
    /// otherwise — sorted ascending, deduplicated, and possibly empty
    /// (e.g. a cursor-blink tick that produced an identical grid).
    ///
    /// `TerminalCell` compares by value, so any change to a
    /// cell's glyph, colour, or overlay flag (`selected` / `is_cursor` /
    /// `is_find_match` / `is_find_active`) — i.e. scroll, selection,
    /// cursor move, and find-highlight updates — registers the owning
    /// row as dirty; there is nothing overlay-specific for a caller to
    /// special-case.
    pub fn dirty_rows(&self, prev: &Terminal) -> Option<Vec<usize>> {
        if self.cells.len() != prev.cells.len() {
            return None;
        }
        Some(
            self.cells
                .iter()
                .zip(prev.cells.iter())
                .enumerate()
                .filter_map(|(i, (a, b))| (a != b).then_some(i))
                .collect(),
        )
    }

    /// Compute viewport → grid conversion. The layout is uniform-cell,
    /// so this is just division; there's no per-cell work.
    ///
    /// # Arguments
    ///
    /// - `viewport_width`, `viewport_height` — pane dimensions.
    /// - `cell_width`, `cell_height` — cell dimensions. TUI passes
    ///   `(1.0, 1.0)`; native backends pass the font's advance width
    ///   and line height.
    pub fn layout(
        &self,
        viewport_width: f32,
        viewport_height: f32,
        cell_width: f32,
        cell_height: f32,
    ) -> TerminalLayout {
        let grid_cols = if cell_width > 0.0 {
            (viewport_width / cell_width).floor().max(0.0) as u16
        } else {
            0
        };
        let grid_rows = if cell_height > 0.0 {
            (viewport_height / cell_height).floor().max(0.0) as u16
        } else {
            0
        };
        TerminalLayout {
            viewport_width,
            viewport_height,
            cell_size: TerminalCellSize::new(cell_width, cell_height),
            grid_rows,
            grid_cols,
        }
    }
}

// ── Split-pane layout ───────────────────────────────────────────────────────

/// Layout geometry for a side-by-side terminal split. The divider
/// occupies one `cell_width` column between the two panes. An optional
/// scrollbar strip is reserved at the right edge.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct TerminalSplitLayout {
    /// Left pane region.
    pub left: Rect,
    /// Right pane region.
    pub right: Rect,
    /// X-coordinate of the divider column's left edge.
    pub divider_x: f32,
    /// Width of the divider column (one `cell_width`).
    pub divider_width: f32,
    /// Cell dimensions used for coordinate-to-cell conversion.
    pub cell_size: TerminalCellSize,
    /// Scrollbar strip bounds (right edge of area). `None` when
    /// `scrollbar_width` was 0.
    pub scrollbar: Option<Rect>,
}

impl TerminalSplitLayout {
    /// Compute a two-pane split layout from a containing area, left
    /// pane column count, cell dimensions, and optional scrollbar width.
    ///
    /// TUI callers pass `cell_width = 1.0, cell_height = 1.0`;
    /// GTK callers pass the font's advance width and line height.
    /// Pass `scrollbar_width = 0.0` to omit the scrollbar zone.
    pub fn new(
        area: Rect,
        left_cols: usize,
        cell_width: f32,
        cell_height: f32,
        scrollbar_width: f32,
    ) -> Self {
        let sb_w = if scrollbar_width > 0.0 {
            scrollbar_width.min(area.width)
        } else {
            0.0
        };
        let usable_w = (area.width - sb_w).max(0.0);
        let left_w = (left_cols as f32 * cell_width).min(usable_w);
        let divider_x = area.x + left_w;
        let divider_w = cell_width.min((usable_w - left_w).max(0.0));
        let right_x = divider_x + divider_w;
        let right_w = (usable_w - left_w - divider_w).max(0.0);
        let scrollbar = if sb_w > 0.0 {
            Some(Rect::new(area.x + usable_w, area.y, sb_w, area.height))
        } else {
            None
        };
        Self {
            left: Rect::new(area.x, area.y, left_w, area.height),
            right: Rect::new(right_x, area.y, right_w, area.height),
            divider_x,
            divider_width: divider_w,
            cell_size: TerminalCellSize::new(cell_width, cell_height),
            scrollbar,
        }
    }

    /// Resolve an absolute point to a split zone with pane-relative cell
    /// coordinates. Converts pixel/cell positions to `(col, row)` within
    /// the hit pane using the stored `cell_size`.
    pub fn hit_test(&self, x: f32, y: f32) -> TerminalSplitHit {
        if y < self.left.y || y >= self.left.y + self.left.height {
            return TerminalSplitHit::Outside;
        }
        if let Some(sb) = self.scrollbar {
            if x >= sb.x && x < sb.x + sb.width {
                return TerminalSplitHit::Scrollbar;
            }
        }
        if x >= self.left.x && x < self.left.x + self.left.width {
            let col = ((x - self.left.x) / self.cell_size.width).floor() as u16;
            let row = ((y - self.left.y) / self.cell_size.height).floor() as u16;
            TerminalSplitHit::LeftPane { col, row }
        } else if x >= self.divider_x && x < self.divider_x + self.divider_width {
            TerminalSplitHit::Divider
        } else if x >= self.right.x && x < self.right.x + self.right.width {
            let col = ((x - self.right.x) / self.cell_size.width).floor() as u16;
            let row = ((y - self.right.y) / self.cell_size.height).floor() as u16;
            TerminalSplitHit::RightPane { col, row }
        } else {
            TerminalSplitHit::Outside
        }
    }
}

/// Result of [`TerminalSplitLayout::hit_test`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TerminalSplitHit {
    LeftPane { col: u16, row: u16 },
    RightPane { col: u16, row: u16 },
    Divider,
    Scrollbar,
    Outside,
}

/// Events a `Terminal` emits back to the app. Currently unused by vimcode
/// (the terminal panel handles its own input directly via the engine's
/// `terminal_*` methods), but defined for plugin invariants §10 — a
/// plugin-declared terminal would route events through this enum.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum TerminalEvent {
    /// A key was pressed with the terminal focused. Routed to the
    /// underlying PTY by the app.
    KeyPressed { key: String, modifiers: Modifiers },
    /// User started selecting at `(row, col)` (0-based, content area).
    SelectStart { row: u16, col: u16 },
    /// User dragged the selection to a new endpoint.
    SelectExtend { row: u16, col: u16 },
    /// User released the mouse button — selection is finalised.
    SelectEnd,
    /// Mouse wheel scroll: positive = scroll content downward (toward
    /// live), negative = scroll backward into history.
    Scroll { delta: i32 },
}

// ── PaintSurface paint ────────────────────────────────────────────
//
// `gtk::terminal::draw_terminal_cells`,
// `macos::terminal::draw_terminal_cells` and
// `win::terminal::draw_terminal_cells` each independently walked
// `term.cells[row][col]` and painted every cell's background + glyph
// with their own Cairo / CoreGraphics / Direct2D calls — all three
// already shared the geometry helpers in `crate::terminal_style`
// (`resolve_cell_style`, `wide_cell_advance`, `wide_glyph_x_scale`,
// `divider_geometry`), so only the actual paint calls were duplicated.
// `paint`/`paint_divider` below are the one shared implementation,
// written against [`crate::paint_surface::PaintSurface`].
//
// Per-cell glyph styling (`TerminalCell::bold`/`italic`/`underline`) and
// the wide-glyph horizontal scale both needed a new
// verb this trait didn't have — [`PaintSurface::surface_draw_text_run_styled`]
// — so unifying this primitive wouldn't force GTK's full
// bold/italic/underline support and Windows's bold support to regress to
// macOS's weaker (undocumented, deliberately deferred) "no
// per-cell styling at all" posture. See that method's own doc for
// exactly which of the three flags (plus `scale_x`) each backend's
// `PaintSurface` override actually applies — this crate's own
// `paint_surface.rs` is sealed (`pub(crate)`, no downstream consumer
// can see it), so growing its vocabulary here is not a breaking change.
//
// GTK's dirty-row repaint cache (`TermPaintCache`) stays in
// `GtkBackend::draw_terminal` — it's a frame-to-frame *caching* decision
// (which rows even need repainting this frame), not a paint-time
// concern, so it has nothing to do with how a given row's cells get
// painted. `paint`'s own `dirty_rows` parameter is the same "paint only
// these rows" contract `draw_terminal_cells` already had; macOS and
// Windows simply never call it with anything but `None` (full repaint
// every frame), but nothing stops a future caching layer on either from
// reusing this without a fourth per-backend dirty-row implementation.
//
// GTK's pre-unification `draw_terminal_cells` painted glyphs straight
// through `pangocairo::functions::show_layout`, bypassing the
// `painted_text` tracking every other primitive's rasteriser already
// routed through — so a terminal's cell content never reached
// `FrameInventory::text_runs()` on GTK. `paint` reaches glyphs
// through `surface_draw_text_run_styled`, whose `GtkBackend` override
// goes through `super::painted_text::show_layout` like every other
// verb — this gap closes as a side effect of unification.
//
// `#[allow(dead_code)]`: only *called* once a real pixel backend is
// compiled in, exercised by each backend's own `Backend::draw_terminal`/
// `draw_terminal_divider` call sites plus this module's own
// `RecordingSurface` tests on every leg that enables one of the three
// cfg'd features.
#[cfg(any(
    feature = "gtk",
    feature = "win",
    all(feature = "macos", target_os = "macos")
))]
#[allow(dead_code)]
mod native_surface_paint {
    use super::Terminal;
    use crate::paint_surface::PaintSurface;
    use crate::terminal_style::{
        cursor_accent_rect, cursor_accent_visible, divider_geometry, resolve_cell_style,
        wide_cell_advance, wide_glyph_x_scale,
    };
    use crate::theme::Theme;
    use crate::Rect;

    /// Paint `term`'s cell grid into the rectangular region starting at
    /// `(x, y)` on `surface`. The caller is responsible for filling the
    /// surrounding background first (see each `Backend::draw_terminal`
    /// impl's own pane-clear posture — that decision stays per-backend,
    /// not part of this shared fn).
    ///
    /// `cell_area_w`/`cell_area_h` clip painting to the pane's own
    /// bounds — cells past the right edge, or rows whose top has reached
    /// the bottom, stop being drawn rather than bleeding past the pane.
    /// `line_height`/`char_width` are the per-cell
    /// dimensions in surface-native units.
    ///
    /// `dirty_rows`: `None` paints every row; `Some(rows)` paints only
    /// the rows whose index appears in `rows` (sorted ascending) and
    /// leaves every other row's pixels untouched — see this module's
    /// doc for why only `GtkBackend` currently passes `Some(_)`.
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn paint(
        term: &Terminal,
        surface: &mut dyn PaintSurface,
        theme: &Theme,
        x: f32,
        y: f32,
        cell_area_w: f32,
        cell_area_h: f32,
        line_height: f32,
        char_width: f32,
        dirty_rows: Option<&[usize]>,
    ) {
        for (row_idx, row) in term.cells.iter().enumerate() {
            let row_y = y + row_idx as f32 * line_height;
            // Stop once a row's top has reached the pane bottom — such a
            // row belongs to a taller (pre-resize) grid and would bleed
            // past the pane. A row that merely straddles the bottom edge
            // is still drawn (and clipped by whatever the host paints
            // over it).
            if row_y >= y + cell_area_h {
                break;
            }
            if let Some(rows) = dirty_rows {
                if rows.binary_search(&row_idx).is_err() {
                    continue;
                }
            }
            let mut cell_x = x;
            let mut col = 0usize;
            while col < row.len() {
                let cell = &row[col];
                // Double-width glyphs (CJK, emoji, ...) get a
                // two-column cell: the vt100 grid already reserves the
                // following column as an empty continuation
                // placeholder, so claim it here rather than letting it
                // paint its own (mismatched) background over the
                // glyph's right half.
                let (cell_w, cols_advanced) = wide_cell_advance(&cell.text, char_width as f64);
                let cell_w = cell_w as f32;
                let is_wide = cols_advanced == 2;

                if cell_x + cell_w > x + cell_area_w {
                    break;
                }
                let (cell_bg, cell_fg) = resolve_cell_style(cell, theme);
                surface.surface_fill_rect(Rect::new(cell_x, row_y, cell_w, line_height), cell_bg);

                if cell.text != " " && cell.text != "\0" && !cell.text.is_empty() {
                    let s = cell.text.as_str();
                    let cell_rect = Rect::new(cell_x, row_y, cell_w, line_height);
                    let scale_x = if is_wide {
                        // The font each backend falls back to for CJK/emoji rarely lays the
                        // glyph out at exactly two cells — scale it to fill `cell_w` instead of
                        // leaving a ragged gap or overlap.
                        let (natural_w, _) = surface.surface_measure_text(s);
                        wide_glyph_x_scale(natural_w as f64, cell_w as f64) as f32
                    } else {
                        1.0
                    };
                    surface.surface_draw_text_run_styled(
                        cell_rect,
                        s,
                        cell_fg,
                        cell.bold,
                        cell.italic,
                        cell.underline,
                        scale_x,
                    );
                }

                // Underline/Bar cursor accent — `Block`
                // is already fully painted above via `resolve_cell_style`'s
                // colour invert, so `cursor_accent_rect` returns `None`
                // for it and this is a no-op. `cell.fg` (the cell's own,
                // un-inverted foreground) is the accent colour, mirroring
                // how the `Block` invert uses it as the new background.
                if cursor_accent_visible(cell) {
                    if let Some(accent) =
                        cursor_accent_rect(cell.cursor_shape, cell_x, row_y, cell_w, line_height)
                    {
                        surface.surface_fill_rect(accent, cell.fg);
                    }
                }

                cell_x += cell_w;
                col += cols_advanced;
            }
        }
    }

    /// Draw a vertical divider line for a terminal split pane. Paints a
    /// 1-unit-wide line at `x` from `y` to `y + height` using
    /// `theme.separator`. Geometry comes from
    /// [`crate::terminal_style::divider_geometry`].
    pub(crate) fn paint_divider(
        surface: &mut dyn PaintSurface,
        x: f32,
        y: f32,
        height: f32,
        theme: &Theme,
    ) {
        let g = divider_geometry(x as f64, y as f64, height as f64);
        surface.surface_fill_rect(
            Rect::new(g.x as f32, g.y as f32, g.width as f32, g.height as f32),
            theme.separator,
        );
    }

    #[cfg(test)]
    mod tests {
        use super::*;
        use crate::backend::ImagePaintResult;
        use crate::event::Viewport;
        use crate::primitives::terminal::{TerminalCell, TerminalCursorShape};
        use crate::types::{Color, WidgetId};
        use crate::Image;

        /// Records every drawing verb `paint` issues — mirrors
        /// `primitives::chart`/`primitives::find_replace`/
        /// `primitives::text_display`'s own `RecordingSurface`
        #[derive(Default)]
        struct RecordingSurface {
            fills: Vec<(Rect, Color)>,
            styled_runs: Vec<(Rect, String, Color, bool, bool, bool, f32)>,
        }

        impl PaintSurface for RecordingSurface {
            fn surface_begin_frame(&mut self, _viewport: Viewport) {}
            fn surface_end_frame(&mut self) {}
            fn surface_viewport(&self) -> Viewport {
                Viewport::new(200.0, 100.0, 1.0)
            }
            fn surface_line_height(&self) -> f32 {
                20.0
            }
            fn surface_char_width(&self) -> f32 {
                10.0
            }
            fn surface_measure_text(&self, text: &str) -> (f32, f32) {
                (text.chars().count() as f32 * 10.0, 20.0)
            }
            fn surface_fill_rect(&mut self, rect: Rect, color: Color) {
                self.fills.push((rect, color));
            }
            /// Test-only recorder — `paint` never calls this verb
            /// (see this module's own doc for why no primitive here has been
            /// migrated onto it yet); this exists only so `RecordingSurface`
            /// satisfies the trait. Records into the same `fills` list as
            /// `surface_fill_rect` (radius dropped) — no test asserts on it
            /// today.
            fn surface_fill_rounded_rect(&mut self, rect: Rect, _radius: f32, color: Color) {
                self.fills.push((rect, color));
            }
            fn surface_stroke_rect(&mut self, _rect: Rect, _color: Color, _stroke_width: f32) {}
            fn surface_stroke_rounded_rect(
                &mut self,
                _rect: Rect,
                _radius: f32,
                _color: Color,
                _stroke_width: f32,
            ) {
            }
            fn surface_draw_text_run(&mut self, _rect: Rect, _text: &str, _color: Color) {}
            fn surface_draw_text_run_styled(
                &mut self,
                rect: Rect,
                text: &str,
                color: Color,
                bold: bool,
                italic: bool,
                underline: bool,
                scale_x: f32,
            ) {
                self.styled_runs.push((
                    rect,
                    text.to_string(),
                    color,
                    bold,
                    italic,
                    underline,
                    scale_x,
                ));
            }
            fn surface_draw_line(
                &mut self,
                _from: crate::Point,
                _to: crate::Point,
                _color: Color,
                _stroke_width: f32,
            ) {
            }
            fn surface_push_clip(&mut self, _rect: Rect) {}
            fn surface_pop_clip(&mut self) {}
            fn surface_draw_image(&mut self, _rect: Rect, _image: &Image) -> ImagePaintResult {
                ImagePaintResult::Unsupported
            }
        }

        fn cell(ch: char, fg: Color, bg: Color) -> TerminalCell {
            TerminalCell {
                text: ch.to_string(),
                fg,
                bg,
                bold: false,
                italic: false,
                underline: false,
                dim: false,
                selected: false,
                is_cursor: false,
                is_find_match: false,
                is_find_active: false,
                cursor_shape: TerminalCursorShape::Block,
                cursor_blinking: false,
            }
        }

        #[test]
        fn cell_background_and_glyph_paint_at_the_grid_position() {
            let fg = Color::rgb(255, 255, 255);
            let bg = Color::rgb(10, 20, 30);
            let term = Terminal {
                id: WidgetId::new("term"),
                cells: vec![vec![cell('A', fg, bg)]],
                scrollbar: None,
            };
            let theme = Theme::default();
            let mut surface = RecordingSurface::default();

            paint(
                &term,
                &mut surface,
                &theme,
                0.0,
                0.0,
                200.0,
                100.0,
                20.0,
                10.0,
                None,
            );

            assert!(
                surface
                    .fills
                    .iter()
                    .any(|&(r, c)| r == Rect::new(0.0, 0.0, 10.0, 20.0) && c == bg),
                "expected the cell's own background fill, fills were {:?}",
                surface.fills,
            );
            assert!(
                surface
                    .styled_runs
                    .iter()
                    .any(|(r, t, c, ..)| t == "A" && *c == fg && r.x == 0.0 && r.y == 0.0),
                "expected the glyph painted in the cell's fg colour, got {:?}",
                surface.styled_runs,
            );
        }

        #[test]
        fn blank_and_nul_cells_paint_background_only() {
            let bg = Color::rgb(10, 20, 30);
            let term = Terminal {
                id: WidgetId::new("term"),
                cells: vec![vec![
                    cell(' ', Color::rgb(0, 0, 0), bg),
                    cell('\0', Color::rgb(0, 0, 0), bg),
                ]],
                scrollbar: None,
            };
            let theme = Theme::default();
            let mut surface = RecordingSurface::default();

            paint(
                &term,
                &mut surface,
                &theme,
                0.0,
                0.0,
                200.0,
                100.0,
                20.0,
                10.0,
                None,
            );

            assert_eq!(
                surface.fills.len(),
                2,
                "both cells should still fill their background"
            );
            assert!(
                surface.styled_runs.is_empty(),
                "space and NUL cells must not paint a glyph, got {:?}",
                surface.styled_runs,
            );
        }

        #[test]
        fn bold_italic_underline_flags_reach_the_styled_run() {
            let term = Terminal {
                id: WidgetId::new("term"),
                cells: vec![vec![TerminalCell {
                    bold: true,
                    italic: true,
                    underline: true,
                    ..cell('X', Color::rgb(255, 255, 255), Color::rgb(0, 0, 0))
                }]],
                scrollbar: None,
            };
            let theme = Theme::default();
            let mut surface = RecordingSurface::default();

            paint(
                &term,
                &mut surface,
                &theme,
                0.0,
                0.0,
                200.0,
                100.0,
                20.0,
                10.0,
                None,
            );

            let (_, _, _, bold, italic, underline, _) = surface.styled_runs[0];
            assert!(bold && italic && underline);
        }

        /// A `dim` cell reaches the styled run with its foreground already
        /// blended toward the background — `paint` sources `cell_fg` from
        /// [`crate::terminal_style::resolve_cell_style`], the single place
        /// SGR 2 (faint) is applied, so every pixel backend
        /// (GTK/macOS/win, all routed through this shared `paint`) gets the
        /// dimmed colour for free with no per-backend styling flag.
        #[test]
        fn dim_flag_dims_the_color_reaching_the_styled_run() {
            let fg = Color::rgb(200, 200, 200);
            let bg = Color::rgb(0, 0, 0);
            let term = Terminal {
                id: WidgetId::new("term"),
                cells: vec![vec![TerminalCell {
                    dim: true,
                    ..cell('X', fg, bg)
                }]],
                scrollbar: None,
            };
            let theme = Theme::default();
            let mut surface = RecordingSurface::default();

            paint(
                &term,
                &mut surface,
                &theme,
                0.0,
                0.0,
                200.0,
                100.0,
                20.0,
                10.0,
                None,
            );

            let (_, _, color, _, _, _, _) = surface.styled_runs[0];
            assert_eq!(
                color,
                Color::rgb(100, 100, 100),
                "dim cell's glyph color must be blended 50% toward its background"
            );
        }

        /// A `Bar`/`Underline` cursor cell paints its
        /// normal (uninverted) background fill *plus* a second, smaller
        /// accent fill in the cell's own foreground colour — unlike
        /// `Block`, which paints only the (inverted) background fill
        /// with no accent. This is the shared logic every pixel backend
        /// (GTK/macOS/win) gets for free through this one `paint` fn.
        #[test]
        fn cursor_shape_accent_paints_a_second_smaller_fill() {
            let fg = Color::rgb(200, 30, 30);
            let bg = Color::rgb(10, 10, 10);

            for shape in [TerminalCursorShape::Underline, TerminalCursorShape::Bar] {
                let term = Terminal {
                    id: WidgetId::new("term"),
                    cells: vec![vec![TerminalCell {
                        is_cursor: true,
                        cursor_shape: shape,
                        ..cell(' ', fg, bg)
                    }]],
                    scrollbar: None,
                };
                let theme = Theme::default();
                let mut surface = RecordingSurface::default();

                paint(
                    &term,
                    &mut surface,
                    &theme,
                    0.0,
                    0.0,
                    200.0,
                    100.0,
                    20.0,
                    10.0,
                    None,
                );

                // Exactly two fills: the normal (uninverted) cell
                // background, plus the accent stripe in the cell's fg.
                assert_eq!(
                    surface.fills.len(),
                    2,
                    "{shape:?}: expected a background fill plus one accent fill, got {:?}",
                    surface.fills,
                );
                assert!(
                    surface
                        .fills
                        .iter()
                        .any(|&(r, c)| c == bg && r.width == 10.0 && r.height == 20.0),
                    "{shape:?}: the full 10x20 cell background should still be the cell's own \
                     (uninverted) bg, got {:?}",
                    surface.fills,
                );
                assert!(
                    surface
                        .fills
                        .iter()
                        .any(|&(r, c)| c == fg && (r.width < 10.0 || r.height < 20.0)),
                    "{shape:?}: expected a smaller accent fill in the cell's fg colour, got {:?}",
                    surface.fills,
                );
            }
        }

        /// A `Block` cursor cell paints only the (inverted) background
        /// fill — no second accent fill, unlike `Underline`/`Bar` above.
        #[test]
        fn block_cursor_shape_paints_no_accent_fill() {
            let fg = Color::rgb(200, 30, 30);
            let bg = Color::rgb(10, 10, 10);
            let term = Terminal {
                id: WidgetId::new("term"),
                cells: vec![vec![TerminalCell {
                    is_cursor: true,
                    ..cell(' ', fg, bg)
                }]],
                scrollbar: None,
            };
            let theme = Theme::default();
            let mut surface = RecordingSurface::default();

            paint(
                &term,
                &mut surface,
                &theme,
                0.0,
                0.0,
                200.0,
                100.0,
                20.0,
                10.0,
                None,
            );

            assert_eq!(
                surface.fills.len(),
                1,
                "Block cursor should paint exactly one (inverted) background fill, got {:?}",
                surface.fills,
            );
        }

        #[test]
        fn dirty_rows_filter_skips_untouched_rows() {
            let painted = Color::rgb(200, 200, 200);
            let term = Terminal {
                id: WidgetId::new("term"),
                cells: vec![
                    vec![cell('A', painted, painted)],
                    vec![cell('B', painted, painted)],
                ],
                scrollbar: None,
            };
            let theme = Theme::default();
            let mut surface = RecordingSurface::default();

            paint(
                &term,
                &mut surface,
                &theme,
                0.0,
                0.0,
                200.0,
                100.0,
                20.0,
                10.0,
                Some(&[1]),
            );

            assert!(
                surface.fills.iter().all(|(r, _)| r.y == 20.0),
                "only row 1 (y=20) should have painted anything, fills were {:?}",
                surface.fills,
            );
        }

        #[test]
        fn paint_divider_fills_the_separator_geometry() {
            let theme = Theme::default();
            let mut surface = RecordingSurface::default();

            paint_divider(&mut surface, 10.0, 5.0, 40.0, &theme);

            assert!(
                surface.fills.iter().any(|&(_, c)| c == theme.separator),
                "expected a fill in theme.separator, fills were {:?}",
                surface.fills,
            );
        }

        // ── Grapheme clusters ───────────────────────────────────────────

        /// A combining mark appended to a base character (e.g. `e` +
        /// U+0301 COMBINING ACUTE ACCENT) must reach the rasteriser as one
        /// glyph run, not just the base character — dropping the mark would be
        /// a defect.
        #[test]
        fn combining_mark_grapheme_paints_as_one_glyph_run() {
            let fg = Color::rgb(255, 255, 255);
            let bg = Color::rgb(0, 0, 0);
            let term = Terminal {
                id: WidgetId::new("term"),
                cells: vec![vec![TerminalCell {
                    text: "e\u{0301}".to_string(),
                    ..cell('e', fg, bg)
                }]],
                scrollbar: None,
            };
            let theme = Theme::default();
            let mut surface = RecordingSurface::default();

            paint(
                &term,
                &mut surface,
                &theme,
                0.0,
                0.0,
                200.0,
                100.0,
                20.0,
                10.0,
                None,
            );

            assert!(
                surface
                    .styled_runs
                    .iter()
                    .any(|(_, t, ..)| t == "e\u{0301}"),
                "expected the full grapheme cluster painted as one run, got {:?}",
                surface.styled_runs,
            );
        }

        /// A combining-mark grapheme is still a single (narrow) column —
        /// the trailing mark must not be double-counted as a second
        /// character's worth of width.
        #[test]
        fn combining_mark_grapheme_advances_a_single_column() {
            let fg = Color::rgb(255, 255, 255);
            let bg = Color::rgb(0, 0, 0);
            let row = vec![
                TerminalCell {
                    text: "e\u{0301}".to_string(),
                    ..cell('e', fg, bg)
                },
                cell('B', fg, Color::rgb(9, 9, 9)),
            ];
            let term = Terminal {
                id: WidgetId::new("term"),
                cells: vec![row],
                scrollbar: None,
            };
            let theme = Theme::default();
            let mut surface = RecordingSurface::default();

            paint(
                &term,
                &mut surface,
                &theme,
                0.0,
                0.0,
                200.0,
                100.0,
                20.0,
                10.0,
                None,
            );

            assert!(
                surface
                    .fills
                    .iter()
                    .any(|&(r, c)| r.x == 10.0 && c == Color::rgb(9, 9, 9)),
                "second cell should start at x=10 (one column over), fills were {:?}",
                surface.fills,
            );
        }
    }
}

#[cfg(any(
    feature = "gtk",
    feature = "win",
    all(feature = "macos", target_os = "macos")
))]
#[allow(unused_imports)]
pub(crate) use native_surface_paint::{paint, paint_divider};

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

    #[test]
    fn split_layout_basic() {
        let area = Rect::new(0.0, 0.0, 80.0, 24.0);
        let sl = TerminalSplitLayout::new(area, 40, 1.0, 1.0, 0.0);
        assert_eq!(sl.left, Rect::new(0.0, 0.0, 40.0, 24.0));
        assert_eq!(sl.divider_x, 40.0);
        assert_eq!(sl.divider_width, 1.0);
        assert_eq!(sl.right, Rect::new(41.0, 0.0, 39.0, 24.0));
        assert!(sl.scrollbar.is_none());
    }

    #[test]
    fn split_layout_pixel_units() {
        let area = Rect::new(10.0, 5.0, 800.0, 600.0);
        let sl = TerminalSplitLayout::new(area, 40, 8.0, 16.0, 0.0);
        assert_eq!(sl.left, Rect::new(10.0, 5.0, 320.0, 600.0));
        assert_eq!(sl.divider_x, 330.0);
        assert_eq!(sl.divider_width, 8.0);
        assert_eq!(sl.right, Rect::new(338.0, 5.0, 472.0, 600.0));
    }

    #[test]
    fn split_layout_left_cols_exceed_area() {
        let area = Rect::new(0.0, 0.0, 20.0, 10.0);
        let sl = TerminalSplitLayout::new(area, 30, 1.0, 1.0, 0.0);
        assert_eq!(sl.left.width, 20.0);
        assert_eq!(sl.divider_width, 0.0);
        assert_eq!(sl.right.width, 0.0);
    }

    #[test]
    fn split_layout_zero_left_cols() {
        let area = Rect::new(0.0, 0.0, 80.0, 24.0);
        let sl = TerminalSplitLayout::new(area, 0, 1.0, 1.0, 0.0);
        assert_eq!(sl.left.width, 0.0);
        assert_eq!(sl.divider_x, 0.0);
        assert_eq!(sl.divider_width, 1.0);
        assert_eq!(sl.right.width, 79.0);
    }

    #[test]
    fn split_hit_test_cell_coords() {
        let area = Rect::new(0.0, 0.0, 80.0, 24.0);
        let sl = TerminalSplitLayout::new(area, 40, 1.0, 1.0, 0.0);
        assert_eq!(
            sl.hit_test(10.0, 5.0),
            TerminalSplitHit::LeftPane { col: 10, row: 5 }
        );
        assert_eq!(sl.hit_test(40.0, 5.0), TerminalSplitHit::Divider);
        assert_eq!(
            sl.hit_test(50.0, 5.0),
            TerminalSplitHit::RightPane { col: 9, row: 5 }
        );
        assert_eq!(sl.hit_test(50.0, 30.0), TerminalSplitHit::Outside);
        assert_eq!(sl.hit_test(-1.0, 5.0), TerminalSplitHit::Outside);
    }

    #[test]
    fn split_hit_test_pixel_units() {
        let area = Rect::new(10.0, 5.0, 800.0, 600.0);
        let sl = TerminalSplitLayout::new(area, 40, 8.0, 16.0, 0.0);
        // Click at x=26 (offset 16 from left=10) → col 2
        assert_eq!(
            sl.hit_test(26.0, 21.0),
            TerminalSplitHit::LeftPane { col: 2, row: 1 }
        );
        // Right pane starts at 338.0; click at 354.0 → offset 16 → col 2
        assert_eq!(
            sl.hit_test(354.0, 37.0),
            TerminalSplitHit::RightPane { col: 2, row: 2 }
        );
    }

    #[test]
    fn split_layout_with_scrollbar() {
        let area = Rect::new(0.0, 0.0, 80.0, 24.0);
        let sl = TerminalSplitLayout::new(area, 40, 1.0, 1.0, 1.0);
        // Scrollbar takes 1 cell from the right edge.
        let sb = sl.scrollbar.unwrap();
        assert_eq!(sb.x, 79.0);
        assert_eq!(sb.width, 1.0);
        // Right pane is narrower by 1.
        assert_eq!(sl.right.width, 38.0);
    }

    #[test]
    fn split_hit_test_scrollbar() {
        let area = Rect::new(0.0, 0.0, 80.0, 24.0);
        let sl = TerminalSplitLayout::new(area, 40, 1.0, 1.0, 1.0);
        assert_eq!(sl.hit_test(79.0, 5.0), TerminalSplitHit::Scrollbar);
        // Just inside right pane (not scrollbar).
        assert_eq!(
            sl.hit_test(78.0, 5.0),
            TerminalSplitHit::RightPane { col: 37, row: 5 }
        );
    }

    #[test]
    fn effective_scroll_offset_non_inverted() {
        let sb = TerminalScrollbar {
            total_lines: 500,
            visible_lines: 24,
            scroll_offset: 100,
            inverted: false,
            width: None,
        };
        assert_eq!(sb.effective_scroll_offset(), 100);
    }

    #[test]
    fn effective_scroll_offset_inverted_at_bottom() {
        let sb = TerminalScrollbar {
            total_lines: 500,
            visible_lines: 24,
            scroll_offset: 0,
            inverted: true,
            width: None,
        };
        // offset 0 = live view → thumb at bottom → effective = max
        assert_eq!(sb.effective_scroll_offset(), 476);
    }

    #[test]
    fn effective_scroll_offset_inverted_at_top() {
        let sb = TerminalScrollbar {
            total_lines: 500,
            visible_lines: 24,
            scroll_offset: 476,
            inverted: true,
            width: None,
        };
        // fully scrolled into history → thumb at top → effective = 0
        assert_eq!(sb.effective_scroll_offset(), 0);
    }

    #[test]
    fn effective_scroll_offset_inverted_midpoint() {
        let sb = TerminalScrollbar {
            total_lines: 500,
            visible_lines: 24,
            scroll_offset: 200,
            inverted: true,
            width: None,
        };
        assert_eq!(sb.effective_scroll_offset(), 276);
    }

    #[test]
    fn effective_scroll_offset_inverted_no_overflow() {
        let sb = TerminalScrollbar {
            total_lines: 24,
            visible_lines: 24,
            scroll_offset: 0,
            inverted: true,
            width: None,
        };
        // total == visible → no scrollable range
        assert_eq!(sb.effective_scroll_offset(), 0);
    }

    // ── dirty_rows ───────────────────────────────────────────────────

    fn cell(ch: char) -> TerminalCell {
        TerminalCell {
            text: ch.to_string(),
            fg: Color::rgb(255, 255, 255),
            bg: Color::rgb(0, 0, 0),
            bold: false,
            italic: false,
            underline: false,
            dim: false,
            selected: false,
            is_cursor: false,
            is_find_match: false,
            is_find_active: false,
            cursor_shape: TerminalCursorShape::Block,
            cursor_blinking: false,
        }
    }

    // ── TerminalCell::cell_width ────────────────────────────────────────

    #[test]
    fn cell_width_narrow_text_is_one() {
        assert_eq!(cell('a').cell_width(), 1);
        assert_eq!(cell(' ').cell_width(), 1);
    }

    #[test]
    fn cell_width_wide_cjk_is_two() {
        assert_eq!(cell('日').cell_width(), 2);
        assert_eq!(cell('中').cell_width(), 2);
    }

    #[test]
    fn cell_width_combining_mark_does_not_add_width() {
        let c = TerminalCell {
            text: "e\u{0301}".to_string(),
            ..cell('e')
        };
        assert_eq!(
            c.cell_width(),
            1,
            "base char + combining accent is still one column"
        );
    }

    fn grid(rows: &[&str]) -> Terminal {
        Terminal {
            id: WidgetId::new("term"),
            cells: rows
                .iter()
                .map(|row| row.chars().map(cell).collect())
                .collect(),
            scrollbar: None,
        }
    }

    #[test]
    fn dirty_rows_identical_grids_are_clean() {
        let prev = grid(&["abc", "def"]);
        let next = grid(&["abc", "def"]);
        assert_eq!(next.dirty_rows(&prev), Some(vec![]));
    }

    #[test]
    fn dirty_rows_flags_only_changed_rows() {
        let prev = grid(&["abc", "def", "ghi"]);
        let next = grid(&["abc", "XYZ", "ghi"]);
        assert_eq!(next.dirty_rows(&prev), Some(vec![1]));
    }

    #[test]
    fn dirty_rows_flags_multiple_changed_rows() {
        let prev = grid(&["abc", "def", "ghi"]);
        let next = grid(&["AAA", "def", "GGG"]);
        assert_eq!(next.dirty_rows(&prev), Some(vec![0, 2]));
    }

    #[test]
    fn dirty_rows_none_when_row_count_differs() {
        let prev = grid(&["abc", "def"]);
        let next = grid(&["abc", "def", "ghi"]);
        assert_eq!(next.dirty_rows(&prev), None);
    }

    #[test]
    fn dirty_rows_row_length_change_counts_as_dirty() {
        // Same row count, but one row grew (ragged rows) — the
        // `Vec<TerminalCell>` equality is length-sensitive, so this
        // must show up as dirty rather than silently comparing equal.
        let prev = grid(&["ab", "cd"]);
        let next = grid(&["abc", "cd"]);
        assert_eq!(next.dirty_rows(&prev), Some(vec![0]));
    }

    #[test]
    fn dirty_rows_overlay_flag_change_is_dirty() {
        // Cursor / selection / find-highlight overlays are plain
        // `TerminalCell` fields, so a flag-only change (same glyph and
        // colour) still registers the row as dirty.
        let prev = grid(&["abc"]);
        let mut next = grid(&["abc"]);
        next.cells[0][1].is_cursor = true;
        assert_eq!(next.dirty_rows(&prev), Some(vec![0]));
    }

    #[test]
    fn terminal_roundtrip_serde() {
        let term = Terminal {
            id: WidgetId::new("terminal-0"),
            cells: vec![
                vec![
                    TerminalCell {
                        text: "$".to_string(),
                        fg: Color::rgb(200, 200, 200),
                        bg: Color::rgb(20, 20, 20),
                        bold: true,
                        italic: false,
                        underline: false,
                        dim: false,
                        selected: false,
                        is_cursor: false,
                        is_find_match: false,
                        is_find_active: false,
                        cursor_shape: TerminalCursorShape::Block,
                        cursor_blinking: false,
                    },
                    TerminalCell {
                        // Base char + combining acute accent — a
                        // multi-codepoint grapheme cluster, not just a
                        // single `char`.
                        text: "e\u{0301}".to_string(),
                        fg: Color::rgb(200, 200, 200),
                        bg: Color::rgb(20, 20, 20),
                        bold: false,
                        italic: false,
                        underline: false,
                        dim: false,
                        selected: false,
                        is_cursor: true,
                        is_find_match: false,
                        is_find_active: false,
                        cursor_shape: TerminalCursorShape::Block,
                        cursor_blinking: false,
                    },
                ],
                vec![TerminalCell {
                    text: "m".to_string(),
                    fg: Color::rgb(255, 100, 50),
                    bg: Color::rgb(20, 20, 20),
                    bold: false,
                    italic: false,
                    underline: true,
                    dim: false,
                    selected: true,
                    is_cursor: false,
                    is_find_match: true,
                    is_find_active: false,
                    cursor_shape: TerminalCursorShape::Block,
                    cursor_blinking: false,
                }],
            ],
            scrollbar: None,
        };
        let json = serde_json::to_string(&term).unwrap();
        let back: Terminal = serde_json::from_str(&json).unwrap();
        assert_eq!(term, back);
    }

    #[test]
    fn terminal_scrollbar_serde_round_trip() {
        let term = Terminal {
            id: WidgetId::new("t"),
            cells: vec![vec![TerminalCell {
                text: "x".to_string(),
                fg: Color::rgb(200, 200, 200),
                bg: Color::rgb(20, 20, 20),
                bold: false,
                italic: false,
                underline: false,
                dim: false,
                selected: false,
                is_cursor: false,
                is_find_match: false,
                is_find_active: false,
                cursor_shape: TerminalCursorShape::Block,
                cursor_blinking: false,
            }]],
            scrollbar: Some(TerminalScrollbar {
                total_lines: 500,
                visible_lines: 24,
                scroll_offset: 100,
                inverted: false,
                width: None,
            }),
        };
        let json = serde_json::to_string(&term).unwrap();
        let back: Terminal = serde_json::from_str(&json).unwrap();
        assert_eq!(term, back);
        let sb = back.scrollbar.unwrap();
        assert_eq!(sb.total_lines, 500);
        assert_eq!(sb.visible_lines, 24);
        assert_eq!(sb.scroll_offset, 100);
    }

    #[test]
    fn terminal_event_roundtrip_serde() {
        let events = vec![
            TerminalEvent::KeyPressed {
                key: "a".to_string(),
                modifiers: Modifiers::default(),
            },
            TerminalEvent::SelectStart { row: 5, col: 10 },
            TerminalEvent::SelectExtend { row: 6, col: 20 },
            TerminalEvent::SelectEnd,
            TerminalEvent::Scroll { delta: -3 },
        ];
        for event in &events {
            let json = serde_json::to_string(event).unwrap();
            let back: TerminalEvent = serde_json::from_str(&json).unwrap();
            assert_eq!(event, &back);
        }
    }

    // ── D6 Terminal layout API tests ──────────────────────────────────

    fn make_term(rows: usize, cols: usize) -> Terminal {
        let cell = TerminalCell {
            text: " ".to_string(),
            fg: Color::rgb(200, 200, 200),
            bg: Color::rgb(20, 20, 20),
            bold: false,
            italic: false,
            underline: false,
            dim: false,
            selected: false,
            is_cursor: false,
            is_find_match: false,
            is_find_active: false,
            cursor_shape: TerminalCursorShape::Block,
            cursor_blinking: false,
        };
        Terminal {
            id: WidgetId::new("term"),
            cells: (0..rows).map(|_| vec![cell.clone(); cols]).collect(),
            scrollbar: None,
        }
    }

    #[test]
    fn terminal_layout_tui_cells() {
        let term = make_term(24, 80);
        let layout = term.layout(80.0, 24.0, 1.0, 1.0);
        assert_eq!(layout.grid_rows, 24);
        assert_eq!(layout.grid_cols, 80);
        // Click at (5, 3) → cell (row=3, col=5).
        match layout.hit_test(5.5, 3.5) {
            TerminalHit::Cell { row, col } => {
                assert_eq!(row, 3);
                assert_eq!(col, 5);
            }
            _ => panic!(),
        }
    }

    #[test]
    fn terminal_layout_pixel_cells() {
        // Native: 800x600 viewport, 8 px × 16 px cells = 100 cols × 37 rows.
        let term = make_term(37, 100);
        let layout = term.layout(800.0, 600.0, 8.0, 16.0);
        assert_eq!(layout.grid_cols, 100);
        assert_eq!(layout.grid_rows, 37); // 600/16 = 37.5 → 37
                                          // Click at (160, 48) → col=20, row=3.
        match layout.hit_test(160.0, 48.0) {
            TerminalHit::Cell { row, col } => {
                assert_eq!(col, 20);
                assert_eq!(row, 3);
            }
            _ => panic!(),
        }
    }

    #[test]
    fn terminal_layout_hit_test_outside() {
        let term = make_term(10, 20);
        let layout = term.layout(20.0, 10.0, 1.0, 1.0);
        assert_eq!(layout.hit_test(-1.0, 5.0), TerminalHit::Empty);
        assert_eq!(layout.hit_test(5.0, -1.0), TerminalHit::Empty);
        assert_eq!(layout.hit_test(100.0, 5.0), TerminalHit::Empty);
    }

    #[test]
    fn terminal_layout_cell_bounds() {
        let term = make_term(10, 20);
        let layout = term.layout(20.0, 10.0, 1.0, 1.0);
        let r = layout.cell_bounds(3, 5).unwrap();
        assert_eq!(r.x, 5.0);
        assert_eq!(r.y, 3.0);
        assert_eq!(r.width, 1.0);
        assert_eq!(r.height, 1.0);
        // Out of range → None.
        assert!(layout.cell_bounds(99, 0).is_none());
        assert!(layout.cell_bounds(0, 99).is_none());
    }
}