lingxia-terminal 0.7.0

Terminal backend integration helpers for LingXia hosts
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
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
//! Shared `libghostty-vt` FFI bindings + render-state snapshot.
//!
//! Rewritten to match the **actual** upstream API at GHOSTTY_REV
//! `ca7516bea60190ee2e9a4f9182b61d318d107c6e` — `include/ghostty/vt/*.h`.
//! Key lifecycle:
//!
//! 1. `terminal = ghostty_terminal_new(NULL_alloc, opts)`
//! 2. `state    = ghostty_render_state_new(NULL_alloc)`
//! 3. `iter     = ghostty_render_state_row_iterator_new(NULL_alloc)`
//! 4. `cells    = ghostty_render_state_row_cells_new(NULL_alloc)`
//!
//! Per-frame:
//!   - `ghostty_render_state_update(state, terminal)` to refresh
//!   - `ghostty_render_state_get(state, DATA_ROW_ITERATOR, &iter)` to bind iterator
//!   - while `row_iterator_next(iter)` is true:
//!       - `row_get(iter, DIRTY, &dirty)`, skip if false
//!       - `row_get(iter, CELLS, &cells)` to bind cells iterator to the current row
//!       - while `row_cells_next(cells)` is true:
//!           - `row_cells_get(cells, RAW|STYLE|BG|FG, &out)`
//!
//! All `_next` functions return `bool`. The `_get` family uses an enum
//! key and writes to a typed `void*` out; key→type contract is per
//! upstream header comments.
//!
//! libghostty-vt is NOT thread-safe; we serialize via a Mutex. The
//! renderer reads a cloned `ScreenSnapshot` so the parser lock is
//! released between feeds and frames.

#![allow(non_camel_case_types, dead_code)]

use std::os::raw::{c_int, c_void};
use std::sync::Arc;
use std::sync::OnceLock;
use std::sync::atomic::{AtomicBool, AtomicU16, AtomicU32, AtomicU64, Ordering};
use std::time::Instant;

use parking_lot::Mutex;

fn perf_trace_enabled() -> bool {
    static ENABLED: OnceLock<bool> = OnceLock::new();
    *ENABLED.get_or_init(|| {
        std::env::var_os("LINGXIA_GHOSTTY_PROFILE").is_some_and(|v| !v.is_empty() && v != "0")
    })
}

fn perf_trace_verbose() -> bool {
    static ENABLED: OnceLock<bool> = OnceLock::new();
    *ENABLED.get_or_init(|| {
        std::env::var_os("LINGXIA_GHOSTTY_PROFILE_VERBOSE")
            .is_some_and(|v| !v.is_empty() && v != "0")
    })
}

// ── Opaque types ───────────────────────────────────────────────────────

pub type GhosttyTerminal = *mut c_void;
pub type GhosttyRenderState = *mut c_void;
pub type GhosttyRowIterator = *mut c_void;
pub type GhosttyRowCells = *mut c_void;
pub type GhosttyAllocator = c_void;
pub type GhosttyResult = c_int;

// ── Enums (keys) ───────────────────────────────────────────────────────
//
// Integer values mirror `include/ghostty/vt/terminal.h` and `render.h`
// at the pinned revision. Keep in sync on GHOSTTY_REV bumps.

/// `GHOSTTY_TERMINAL_DATA_*` keys for `ghostty_terminal_get`.
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub enum GhosttyTerminalData {
    Invalid = 0,
    Cols = 1,
    Rows = 2,
    CursorX = 3,
    CursorY = 4,
    CursorPendingWrap = 5,
    ActiveScreen = 6,
    CursorVisible = 7,
    Scrollbar = 9,
    Title = 12,
}

/// `GhosttyTerminalScrollbar` — current viewport position in the full
/// active screen including scrollback.
#[repr(C)]
#[derive(Debug, Clone, Copy, Default)]
pub struct GhosttyTerminalScrollbar {
    pub total: u64,
    pub offset: u64,
    pub len: u64,
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct GhosttyScrollbar {
    pub total: u64,
    pub offset: u64,
    pub len: u64,
}

/// `GHOSTTY_TERMINAL_SCREEN_*` values.
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GhosttyTerminalScreen {
    Primary = 0,
    Alternate = 1,
}

/// `GHOSTTY_SCROLL_VIEWPORT_*` values.
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GhosttyTerminalScrollViewportTag {
    Top = 0,
    Bottom = 1,
    Delta = 2,
}

/// Payload for `GHOSTTY_SCROLL_VIEWPORT_DELTA`.
#[repr(C)]
#[derive(Clone, Copy)]
pub union GhosttyTerminalScrollViewportValue {
    /// Row delta. Up is negative, down is positive.
    pub delta: isize,
    pub _padding: [u64; 2],
}

/// Tagged viewport scroll request.
#[repr(C)]
#[derive(Clone, Copy)]
pub struct GhosttyTerminalScrollViewport {
    pub tag: GhosttyTerminalScrollViewportTag,
    pub value: GhosttyTerminalScrollViewportValue,
}

/// `GHOSTTY_TERMINAL_OPT_*` keys for `ghostty_terminal_set`.
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub enum GhosttyTerminalOption {
    Userdata = 0,
    WritePty = 1,
    Bell = 2,
    Enquiry = 3,
    Xtversion = 4,
    TitleChanged = 5,
    Size = 6,
    ColorScheme = 7,
    DeviceAttributes = 8,
    ColorForeground = 11,
    ColorBackground = 12,
    ColorCursor = 13,
    /// `GhosttyColorRgb[256]*` — full 256-entry palette.
    ColorPalette = 14,
}

/// `GHOSTTY_RENDER_STATE_DATA_*` keys for `ghostty_render_state_get`.
/// `RowIterator` (4) binds an existing row-iterator handle to this state.
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub enum GhosttyRenderStateData {
    Invalid = 0,
    Cols = 1,
    Rows = 2,
    Dirty = 3,
    RowIterator = 4,
    ColorBackground = 5,
    ColorForeground = 6,
    ColorCursor = 7,
    ColorCursorHasValue = 8,
    ColorPalette = 9,
    CursorVisualStyle = 10,
    CursorVisible = 11,
    CursorBlinking = 12,
    CursorPasswordInput = 13,
    CursorViewportHasValue = 14,
    CursorViewportX = 15,
    CursorViewportY = 16,
    CursorViewportWideTail = 17,
}

#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GhosttyRenderStateDirty {
    False = 0,
    Partial = 1,
    Full = 2,
}

#[repr(C)]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum GhosttyRenderStateCursorVisualStyle {
    Bar = 0,
    #[default]
    Block = 1,
    Underline = 2,
    BlockHollow = 3,
}

/// `GHOSTTY_RENDER_STATE_ROW_DATA_*` keys for `ghostty_render_state_row_get`.
/// `Cells` (3) binds a cells iterator to the current row.
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub enum GhosttyRenderStateRowData {
    Invalid = 0,
    Dirty = 1,
    Raw = 2,
    Cells = 3,
}

/// `GHOSTTY_RENDER_STATE_ROW_CELLS_DATA_*` keys.
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub enum GhosttyRenderStateRowCellsData {
    Invalid = 0,
    Raw = 1,
    Style = 2,
    GraphemesLen = 3,
    GraphemesBuf = 4,
    BgColor = 5,
    FgColor = 6,
}

/// `GHOSTTY_CELL_DATA_*` keys for `ghostty_cell_get`. Integer values
/// per `include/ghostty/vt/screen.h` at the pinned revision — the RAW
/// we get from row_cells is an **opaque `GhosttyCell` u64 handle**, not
/// a packed codepoint. Reading the codepoint requires this accessor.
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub enum GhosttyCellData {
    Invalid = 0,
    Codepoint = 1,
    ContentTag = 2,
    Wide = 3,
    HasText = 4,
    HasStyling = 5,
    StyleId = 6,
    HasHyperlink = 7,
    Protected = 8,
    SemanticContent = 9,
    ColorPalette = 10,
    ColorRgb = 11,
}

#[repr(C)]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum GhosttyCellWide {
    #[default]
    Narrow = 0,
    Wide = 1,
    SpacerTail = 2,
    SpacerHead = 3,
}

/// Opaque cell snapshot returned by `row_cells_get(RAW, ...)`.
/// `typedef uint64_t GhosttyCell;` upstream.
pub type GhosttyCell = u64;

/// Packed 16-bit terminal mode — see `include/ghostty/vt/modes.h`.
/// Bits 0–14 hold the numeric mode value; bit 15 is the ANSI flag
/// (1 = ANSI, 0 = DEC private). Constructed via [`ghostty_mode`].
pub type GhosttyMode = u16;

/// Pack a mode value + ANSI flag into a [`GhosttyMode`]. Mirrors the
/// inline `ghostty_mode_new` helper the C header ships.
#[inline]
pub const fn ghostty_mode(value: u16, ansi: bool) -> GhosttyMode {
    (value & 0x7FFF) | ((ansi as u16) << 15)
}

// Pre-packed DEC private modes we care about on Windows. Keep the
// numeric values synced with `modes.h`.
pub const MODE_NORMAL_MOUSE: GhosttyMode = ghostty_mode(1000, false);
pub const MODE_BUTTON_MOUSE: GhosttyMode = ghostty_mode(1002, false);
pub const MODE_ANY_MOUSE: GhosttyMode = ghostty_mode(1003, false);
pub const MODE_X10_MOUSE: GhosttyMode = ghostty_mode(9, false);
pub const MODE_SGR_MOUSE: GhosttyMode = ghostty_mode(1006, false);
pub const MODE_ALT_SCROLL: GhosttyMode = ghostty_mode(1007, false);
/// DEC private mode 2004 — bracketed paste. Apps that set this want
/// pasted text wrapped in `ESC[200~ … ESC[201~` so the line editor can
/// distinguish typed-from-pasted input (e.g. to bypass auto-indent).
pub const MODE_BRACKETED_PASTE: GhosttyMode = ghostty_mode(2004, false);
/// DEC private mode 1 — DECCKM (cursor key mode). When set, arrow
/// keys send `ESC O [ABCD]` (application mode) instead of the default
/// `ESC [ [ABCD]` (cursor mode). Interactive readers like readline
/// and vim set this to distinguish their keymap lookup.
pub const MODE_DECCKM: GhosttyMode = ghostty_mode(1, false);

const GHOSTTY_DA_CONFORMANCE_LEVEL_2: u16 = 62;
const GHOSTTY_DA_FEATURE_SELECTIVE_ERASE: u16 = 6;
const GHOSTTY_DA_FEATURE_WINDOWING: u16 = 18;
const GHOSTTY_DA_FEATURE_ANSI_COLOR: u16 = 22;
const GHOSTTY_DA_FEATURE_RECTANGULAR_EDITING: u16 = 28;
const GHOSTTY_DA_FEATURE_CLIPBOARD: u16 = 52;
const GHOSTTY_DA_DEVICE_TYPE_VT220: u16 = 1;

#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub struct GhosttyTerminalOptions {
    pub cols: u16,
    pub rows: u16,
    pub max_scrollback: usize,
}

/// `GhosttyColorRgb` — R,G,B bytes per upstream `color.h`.
#[repr(C)]
#[derive(Debug, Clone, Copy, Default)]
pub struct GhosttyColorRgb {
    pub r: u8,
    pub g: u8,
    pub b: u8,
}

#[repr(C)]
#[derive(Debug, Clone, Copy, Default)]
pub struct GhosttyString {
    pub ptr: *const u8,
    pub len: usize,
}

#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GhosttyColorScheme {
    Light = 0,
    Dark = 1,
}

#[repr(C)]
#[derive(Debug, Clone, Copy, Default)]
pub struct GhosttySizeReportSize {
    pub rows: u16,
    pub columns: u16,
    pub cell_width: u32,
    pub cell_height: u32,
}

#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub struct GhosttyDeviceAttributesPrimary {
    pub conformance_level: u16,
    pub features: [u16; 64],
    pub num_features: usize,
}

impl Default for GhosttyDeviceAttributesPrimary {
    fn default() -> Self {
        Self {
            conformance_level: 0,
            features: [0; 64],
            num_features: 0,
        }
    }
}

#[repr(C)]
#[derive(Debug, Clone, Copy, Default)]
pub struct GhosttyDeviceAttributesSecondary {
    pub device_type: u16,
    pub firmware_version: u16,
    pub rom_cartridge: u16,
}

#[repr(C)]
#[derive(Debug, Clone, Copy, Default)]
pub struct GhosttyDeviceAttributesTertiary {
    pub unit_id: u32,
}

#[repr(C)]
#[derive(Debug, Clone, Copy, Default)]
pub struct GhosttyDeviceAttributes {
    pub primary: GhosttyDeviceAttributesPrimary,
    pub secondary: GhosttyDeviceAttributesSecondary,
    pub tertiary: GhosttyDeviceAttributesTertiary,
}

// ── Style (`style.h`) ──────────────────────────────────────────────────
//
// `row_cells_get(STYLE, out)` writes a `GhosttyStyle` by value. Caller
// sets `.size = sizeof(GhosttyStyle)` first so the library knows how
// many bytes it may write (versioned-struct forward-compat pattern).

/// `GhosttyStyleColor` — tagged color (None | Palette | Rgb). The
/// union is laid out as `u64` here because we only care about the tag
/// for now; per-cell fg/bg also come in via the cheaper FG_COLOR /
/// BG_COLOR accessor on row_cells, so we don't need to decode the
/// union value at read-cell time.
#[repr(C)]
#[derive(Debug, Clone, Copy, Default)]
pub struct GhosttyStyleColor {
    pub tag: u32,
    pub _pad: u32,
    pub value: u64,
}

/// `GhosttyStyle` — SGR-derived attributes for the current cell.
/// Layout matches `include/ghostty/vt/style.h` at GHOSTTY_REV; the
/// `size` prefix lets upstream add trailing fields without breaking
/// older callers.
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub struct GhosttyStyle {
    pub size: usize,
    pub fg_color: GhosttyStyleColor,
    pub bg_color: GhosttyStyleColor,
    pub underline_color: GhosttyStyleColor,
    pub bold: bool,
    pub italic: bool,
    pub faint: bool,
    pub blink: bool,
    pub inverse: bool,
    pub invisible: bool,
    pub strikethrough: bool,
    pub overline: bool,
    pub underline: c_int,
}

impl GhosttyStyle {
    fn new() -> Self {
        Self {
            size: std::mem::size_of::<GhosttyStyle>(),
            fg_color: GhosttyStyleColor::default(),
            bg_color: GhosttyStyleColor::default(),
            underline_color: GhosttyStyleColor::default(),
            bold: false,
            italic: false,
            faint: false,
            blink: false,
            inverse: false,
            invisible: false,
            strikethrough: false,
            overline: false,
            underline: 0,
        }
    }
}

// Attr bits packed into `Cell.attrs`. Kept in sync with the HLSL
// pixel shader's interpretation (bit 0 = bold, 1 = italic, 2 =
// underline, 3 = strike, 4 = inverse).
pub const ATTR_BOLD: u8 = 1 << 0;
pub const ATTR_ITALIC: u8 = 1 << 1;
pub const ATTR_UNDERLINE: u8 = 1 << 2;
pub const ATTR_STRIKE: u8 = 1 << 3;
pub const ATTR_INVERSE: u8 = 1 << 4;

// ── Raw FFI ────────────────────────────────────────────────────────────

unsafe extern "C" {
    // Terminal (`terminal.h`)
    pub fn ghostty_terminal_new(
        allocator: *const GhosttyAllocator,
        out_terminal: *mut GhosttyTerminal,
        options: GhosttyTerminalOptions,
    ) -> GhosttyResult;
    pub fn ghostty_terminal_free(terminal: GhosttyTerminal);
    pub fn ghostty_terminal_resize(
        terminal: GhosttyTerminal,
        cols: u16,
        rows: u16,
        cell_width_px: u32,
        cell_height_px: u32,
    ) -> GhosttyResult;
    /// `value` semantics depend on `option`:
    ///   - `Userdata`: opaque host pointer stored on the terminal
    ///   - `WritePty`: host callback function pointer
    ///   - color knobs (FG/BG/CURSOR): pointer to a single `GhosttyColorRgb`
    ///   - palette: pointer to `GhosttyColorRgb[256]`
    /// Passing `value = NULL` clears the override and restores the
    /// built-in defaults where supported.
    pub fn ghostty_terminal_set(
        terminal: GhosttyTerminal,
        option: GhosttyTerminalOption,
        value: *const c_void,
    ) -> GhosttyResult;
    pub fn ghostty_terminal_vt_write(terminal: GhosttyTerminal, data: *const u8, len: usize);
    pub fn ghostty_terminal_scroll_viewport(
        terminal: GhosttyTerminal,
        behavior: GhosttyTerminalScrollViewport,
    );
    pub fn ghostty_terminal_get(
        terminal: GhosttyTerminal,
        key: GhosttyTerminalData,
        out: *mut c_void,
    ) -> GhosttyResult;

    /// Query whether a terminal mode is currently set. `out_value` is a
    /// `bool` (1 byte). Returns `GHOSTTY_SUCCESS` on success.
    pub fn ghostty_terminal_mode_get(
        terminal: GhosttyTerminal,
        mode: GhosttyMode,
        out_value: *mut bool,
    ) -> GhosttyResult;

    // Render state (`render.h`)
    pub fn ghostty_render_state_new(
        allocator: *const GhosttyAllocator,
        out_state: *mut GhosttyRenderState,
    ) -> GhosttyResult;
    pub fn ghostty_render_state_free(state: GhosttyRenderState);
    pub fn ghostty_render_state_update(
        state: GhosttyRenderState,
        terminal: GhosttyTerminal,
    ) -> GhosttyResult;
    pub fn ghostty_render_state_get(
        state: GhosttyRenderState,
        key: GhosttyRenderStateData,
        out: *mut c_void,
    ) -> GhosttyResult;

    pub fn ghostty_render_state_row_iterator_new(
        allocator: *const GhosttyAllocator,
        out_iter: *mut GhosttyRowIterator,
    ) -> GhosttyResult;
    pub fn ghostty_render_state_row_iterator_free(iter: GhosttyRowIterator);
    /// Returns `bool` per upstream signature. Rust `bool` is 1 byte —
    /// matches MSVC/gcc/clang C99 `_Bool` layout.
    pub fn ghostty_render_state_row_iterator_next(iter: GhosttyRowIterator) -> bool;
    pub fn ghostty_render_state_row_get(
        iter: GhosttyRowIterator,
        key: GhosttyRenderStateRowData,
        out: *mut c_void,
    ) -> GhosttyResult;

    pub fn ghostty_render_state_row_cells_new(
        allocator: *const GhosttyAllocator,
        out_cells: *mut GhosttyRowCells,
    ) -> GhosttyResult;
    pub fn ghostty_render_state_row_cells_free(cells: GhosttyRowCells);
    pub fn ghostty_render_state_row_cells_next(cells: GhosttyRowCells) -> bool;
    pub fn ghostty_render_state_row_cells_get(
        cells: GhosttyRowCells,
        key: GhosttyRenderStateRowCellsData,
        out: *mut c_void,
    ) -> GhosttyResult;

    // Cell accessor (`screen.h`). Decodes fields out of the opaque
    // `GhosttyCell` u64 we get from row_cells RAW.
    pub fn ghostty_cell_get(
        cell: GhosttyCell,
        key: GhosttyCellData,
        out: *mut c_void,
    ) -> GhosttyResult;
}

// ── Theme ──────────────────────────────────────────────────────────────

/// Default colors handed to libghostty via `ghostty_terminal_set`.
///
/// libghostty owns the SGR-color resolution: it looks up palette
/// indices, applies bold/bright remaps, and falls back to the default
/// fg/bg for unstyled cells. Pushing the user's theme in here means
/// `read_cell` doesn't need any special-casing — every cell's fg/bg
/// already arrives themed.
#[derive(Debug, Clone)]
pub struct ThemeColors {
    pub fg: [u8; 3],
    pub bg: [u8; 3],
    /// Full 256-entry palette. Indices 0–15 are the user's ANSI
    /// theme; 16–231 form the standard xterm 6×6×6 cube; 232–255 form
    /// the 24-step grayscale ramp.
    pub palette: [[u8; 3]; 256],
}

impl ThemeColors {
    /// Build a 256-color palette from a 16-entry ANSI base.
    pub fn from_ansi16(fg: [u8; 3], bg: [u8; 3], ansi16: [[u8; 3]; 16]) -> Self {
        let mut palette = [[0u8; 3]; 256];
        for i in 0..16 {
            palette[i] = ansi16[i];
        }
        let step = |x: u8| -> u8 { if x == 0 { 0 } else { 55 + 40 * x } };
        for i in 16..232 {
            let idx = (i - 16) as u8;
            let r = idx / 36;
            let g = (idx / 6) % 6;
            let b = idx % 6;
            palette[i] = [step(r), step(g), step(b)];
        }
        for i in 232..256 {
            let v = 8u8.saturating_add(((i - 232) as u8).saturating_mul(10));
            palette[i] = [v, v, v];
        }
        Self { fg, bg, palette }
    }
}

unsafe fn apply_theme_to_terminal(terminal: GhosttyTerminal, theme: &ThemeColors) {
    let fg = GhosttyColorRgb {
        r: theme.fg[0],
        g: theme.fg[1],
        b: theme.fg[2],
    };
    let bg = GhosttyColorRgb {
        r: theme.bg[0],
        g: theme.bg[1],
        b: theme.bg[2],
    };
    let palette: [GhosttyColorRgb; 256] = std::array::from_fn(|i| GhosttyColorRgb {
        r: theme.palette[i][0],
        g: theme.palette[i][1],
        b: theme.palette[i][2],
    });
    let check = |rc: GhosttyResult, what: &'static str| {
        if rc != 0 {
            eprintln!("ghostty_terminal_set({what}) failed: rc={rc}");
        }
    };
    unsafe {
        check(
            ghostty_terminal_set(
                terminal,
                GhosttyTerminalOption::ColorForeground,
                &fg as *const _ as *const c_void,
            ),
            "ColorForeground",
        );
        check(
            ghostty_terminal_set(
                terminal,
                GhosttyTerminalOption::ColorBackground,
                &bg as *const _ as *const c_void,
            ),
            "ColorBackground",
        );
        check(
            ghostty_terminal_set(
                terminal,
                GhosttyTerminalOption::ColorPalette,
                palette.as_ptr() as *const c_void,
            ),
            "ColorPalette",
        );
    }
}

// ── Snapshot (renderer's view) ─────────────────────────────────────────

#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Cell {
    pub text: String,
    /// Foreground RGBA (0xRRGGBBAA).
    pub fg: u32,
    /// Background RGBA.
    pub bg: u32,
    pub attrs: u8,
    pub wide: bool,
    pub _pad: [u8; 2],
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Cursor {
    pub col: u16,
    pub row: u16,
    pub visible: bool,
    pub style: GhosttyRenderStateCursorVisualStyle,
}

#[derive(Debug, Clone, Default)]
pub struct ScreenSnapshot {
    pub cols: u16,
    pub rows: u16,
    pub cells: Vec<Cell>,
    pub dirty_rows: Vec<u16>,
    pub cursor: Cursor,
    pub default_fg: u32,
    pub default_bg: u32,
    pub title: Option<String>,
    pub generation: u64,
}

// ── Safe wrapper ───────────────────────────────────────────────────────

pub struct VtScreen {
    inner: Arc<Mutex<VtInner>>,
}

pub type PtyWriteCallback = Arc<dyn Fn(&[u8]) + Send + Sync + 'static>;

struct VtCallbackState {
    write_pty: PtyWriteCallback,
    enquiry_response: Box<[u8]>,
    rows: AtomicU16,
    cols: AtomicU16,
    cell_width: AtomicU32,
    cell_height: AtomicU32,
    dark_mode: AtomicBool,
    device_attributes: GhosttyDeviceAttributes,
}

struct VtInner {
    terminal: GhosttyTerminal,
    render_state: GhosttyRenderState,
    row_iter: GhosttyRowIterator,
    row_cells: GhosttyRowCells,
    callback_state: Option<Box<VtCallbackState>>,
    cols: u16,
    rows: u16,
    generation: u64,
    force_full_snapshot: bool,
    scratch_cols: u16,
    scratch_rows: u16,
    scratch: Vec<Cell>,
    last_cursor: Cursor,
}

unsafe impl Send for VtInner {}

fn default_device_attributes() -> GhosttyDeviceAttributes {
    let mut features = [0_u16; 64];
    features[0] = GHOSTTY_DA_FEATURE_SELECTIVE_ERASE;
    features[1] = GHOSTTY_DA_FEATURE_WINDOWING;
    features[2] = GHOSTTY_DA_FEATURE_ANSI_COLOR;
    features[3] = GHOSTTY_DA_FEATURE_RECTANGULAR_EDITING;
    features[4] = GHOSTTY_DA_FEATURE_CLIPBOARD;
    GhosttyDeviceAttributes {
        primary: GhosttyDeviceAttributesPrimary {
            conformance_level: GHOSTTY_DA_CONFORMANCE_LEVEL_2,
            features,
            num_features: 5,
        },
        secondary: GhosttyDeviceAttributesSecondary {
            device_type: GHOSTTY_DA_DEVICE_TYPE_VT220,
            firmware_version: 0,
            rom_cartridge: 0,
        },
        tertiary: GhosttyDeviceAttributesTertiary { unit_id: 0 },
    }
}

impl VtScreen {
    pub fn new(cols: u16, rows: u16, theme: Option<&ThemeColors>) -> Result<Self, String> {
        Self::new_with_write_pty(cols, rows, theme, None)
    }

    pub fn new_with_write_pty(
        cols: u16,
        rows: u16,
        theme: Option<&ThemeColors>,
        write_pty: Option<PtyWriteCallback>,
    ) -> Result<Self, String> {
        let mut terminal: GhosttyTerminal = std::ptr::null_mut();
        let options = GhosttyTerminalOptions {
            cols,
            rows,
            max_scrollback: 10_000,
        };
        // SAFETY: out param; allocator NULL = upstream default.
        let rc = unsafe { ghostty_terminal_new(std::ptr::null(), &mut terminal, options) };
        if rc != 0 || terminal.is_null() {
            return Err(format!("ghostty_terminal_new failed: rc={rc}"));
        }

        let mut callback_state = write_pty.map(|write_pty| {
            Box::new(VtCallbackState {
                write_pty,
                enquiry_response: b"LingXia".to_vec().into_boxed_slice(),
                rows: AtomicU16::new(rows),
                cols: AtomicU16::new(cols),
                cell_width: AtomicU32::new(1),
                cell_height: AtomicU32::new(1),
                dark_mode: AtomicBool::new(false),
                device_attributes: default_device_attributes(),
            })
        });
        if let Some(state) = callback_state.as_mut() {
            let userdata = state.as_mut() as *mut VtCallbackState as *mut c_void;
            let rc = unsafe {
                ghostty_terminal_set(terminal, GhosttyTerminalOption::Userdata, userdata)
            };
            if rc != 0 {
                unsafe { ghostty_terminal_free(terminal) };
                return Err(format!("ghostty_terminal_set(USERDATA) failed: rc={rc}"));
            }

            let rc = unsafe {
                ghostty_terminal_set(
                    terminal,
                    GhosttyTerminalOption::WritePty,
                    vt_write_pty_callback as *const c_void,
                )
            };
            if rc != 0 {
                unsafe { ghostty_terminal_free(terminal) };
                return Err(format!("ghostty_terminal_set(WRITE_PTY) failed: rc={rc}"));
            }

            let callback_options = [
                (
                    GhosttyTerminalOption::Enquiry,
                    vt_enquiry_callback as *const c_void,
                    "ENQUIRY",
                ),
                (
                    GhosttyTerminalOption::Size,
                    vt_size_callback as *const c_void,
                    "SIZE",
                ),
                (
                    GhosttyTerminalOption::ColorScheme,
                    vt_color_scheme_callback as *const c_void,
                    "COLOR_SCHEME",
                ),
                (
                    GhosttyTerminalOption::DeviceAttributes,
                    vt_device_attributes_callback as *const c_void,
                    "DEVICE_ATTRIBUTES",
                ),
                (
                    GhosttyTerminalOption::Xtversion,
                    vt_xtversion_callback as *const c_void,
                    "XTVERSION",
                ),
            ];

            for (option, callback, label) in callback_options {
                let rc = unsafe { ghostty_terminal_set(terminal, option, callback) };
                if rc != 0 {
                    unsafe { ghostty_terminal_free(terminal) };
                    return Err(format!("ghostty_terminal_set({label}) failed: rc={rc}"));
                }
            }
        }

        let mut render_state: GhosttyRenderState = std::ptr::null_mut();
        let mut row_iter: GhosttyRowIterator = std::ptr::null_mut();
        let mut row_cells: GhosttyRowCells = std::ptr::null_mut();

        let enable_render_state = std::env::var("LINGXIA_GHOSTTY_VT_RENDER_STATE")
            .map(|s| matches!(s.as_str(), "0" | "false" | "no" | "off"))
            .map(|disabled| !disabled)
            .unwrap_or(true);

        if enable_render_state {
            // SAFETY: out param; allocator NULL = default.
            let rc = unsafe { ghostty_render_state_new(std::ptr::null(), &mut render_state) };
            if rc != 0 || render_state.is_null() {
                // SAFETY: terminal owned; free on partial init failure.
                unsafe { ghostty_terminal_free(terminal) };
                return Err(format!("ghostty_render_state_new failed: rc={rc}"));
            }

            // SAFETY: out param.
            let rc =
                unsafe { ghostty_render_state_row_iterator_new(std::ptr::null(), &mut row_iter) };
            if rc != 0 || row_iter.is_null() {
                unsafe { ghostty_render_state_free(render_state) };
                unsafe { ghostty_terminal_free(terminal) };
                return Err(format!(
                    "ghostty_render_state_row_iterator_new failed: rc={rc}"
                ));
            }

            // SAFETY: out param.
            let rc =
                unsafe { ghostty_render_state_row_cells_new(std::ptr::null(), &mut row_cells) };
            if rc != 0 || row_cells.is_null() {
                unsafe { ghostty_render_state_row_iterator_free(row_iter) };
                unsafe { ghostty_render_state_free(render_state) };
                unsafe { ghostty_terminal_free(terminal) };
                return Err(format!(
                    "ghostty_render_state_row_cells_new failed: rc={rc}"
                ));
            }
        } else {
            eprintln!(
                "VtScreen::new: render_state disabled via \
                 LINGXIA_GHOSTTY_VT_RENDER_STATE=0 — terminal output will \
                 parse but cells won't render."
            );
        }

        if let Some(theme) = theme {
            unsafe { apply_theme_to_terminal(terminal, theme) };
        }

        Ok(Self {
            inner: Arc::new(Mutex::new(VtInner {
                terminal,
                render_state,
                row_iter,
                row_cells,
                callback_state,
                cols,
                rows,
                generation: 0,
                force_full_snapshot: true,
                scratch_cols: cols,
                scratch_rows: rows,
                scratch: Vec::with_capacity(cols as usize * rows as usize),
                last_cursor: Cursor::default(),
            })),
        })
    }

    /// Replace the default fg/bg/palette. Bumps the snapshot
    /// generation so the next prepaint repaints with the new colors.
    pub fn set_theme(&self, theme: &ThemeColors) {
        let mut inner = self.inner.lock();
        unsafe { apply_theme_to_terminal(inner.terminal, theme) };
        inner.force_full_snapshot = true;
        inner.generation = inner.generation.wrapping_add(1);
    }

    /// Force the next `snapshot()` to report a new generation so the
    /// renderer's `needs_draw` gate treats the frame as dirty even
    /// though no VT bytes or theme changes landed. Used by opacity-
    /// only appearance updates, where `config.background_opacity`
    /// changes on the renderer side but the VT screen itself is
    /// untouched.
    pub fn bump_generation(&self) {
        let mut inner = self.inner.lock();
        inner.generation = inner.generation.wrapping_add(1);
    }

    pub fn generation(&self) -> u64 {
        self.inner.lock().generation
    }

    /// Feed bytes from the PTY into the parser. Non-reentrant per
    /// upstream: do not call from inside a registered callback.
    pub fn feed(&self, bytes: &[u8]) {
        let mut inner = self.inner.lock();
        // SAFETY: terminal valid; bytes live for the call.
        unsafe { ghostty_terminal_vt_write(inner.terminal, bytes.as_ptr(), bytes.len()) };
        inner.generation = inner.generation.wrapping_add(1);
    }

    pub fn resize(
        &self,
        cols: u16,
        rows: u16,
        cell_width_px: u32,
        cell_height_px: u32,
    ) -> Result<(), String> {
        let mut inner = self.inner.lock();
        // SAFETY: terminal valid.
        let rc = unsafe {
            ghostty_terminal_resize(inner.terminal, cols, rows, cell_width_px, cell_height_px)
        };
        if rc != 0 {
            return Err(format!("ghostty_terminal_resize failed: rc={rc}"));
        }
        inner.cols = cols;
        inner.rows = rows;
        if let Some(state) = inner.callback_state.as_ref() {
            state.cols.store(cols, Ordering::Release);
            state.rows.store(rows, Ordering::Release);
            state
                .cell_width
                .store(cell_width_px.max(1), Ordering::Release);
            state
                .cell_height
                .store(cell_height_px.max(1), Ordering::Release);
        }
        let total = cols as usize * rows as usize;
        inner.scratch.clear();
        inner.scratch.resize(total, Cell::default());
        inner.scratch_cols = cols;
        inner.scratch_rows = rows;
        inner.force_full_snapshot = true;
        inner.generation = inner.generation.wrapping_add(1);
        Ok(())
    }

    pub fn snapshot(&self) -> ScreenSnapshot {
        let snapshot_started = perf_trace_enabled().then(Instant::now);
        let mut inner = self.inner.lock();

        let requested_cols = inner.cols;
        let requested_rows = inner.rows;

        if inner.render_state.is_null() {
            // Render-state path disabled — return empty snapshot. The
            // renderer still clears the pane to the background.
            return ScreenSnapshot {
                cols: requested_cols,
                rows: requested_rows,
                cells: Vec::new(),
                dirty_rows: Vec::new(),
                cursor: Cursor::default(),
                default_fg: 0xffffffff,
                default_bg: 0x282c34ff,
                title: None,
                generation: inner.generation,
            };
        }

        // SAFETY: state + terminal valid for the lifetime of `inner`.
        let rc = unsafe { ghostty_render_state_update(inner.render_state, inner.terminal) };
        if rc != 0 {
            eprintln!("ghostty_render_state_update rc={rc}");
        }

        // Palette defaults. Cells with no explicit SGR color report
        // FG_COLOR / BG_COLOR as (0,0,0) — the renderer is expected to
        // substitute the terminal's default foreground/background from
        // the render state. Without this, the pwsh banner (and any
        // unstyled text) renders black-on-black.
        let mut default_fg = GhosttyColorRgb {
            r: 0xCC,
            g: 0xCC,
            b: 0xCC,
        };
        let mut default_bg = GhosttyColorRgb::default();
        // SAFETY: out params typed as GhosttyColorRgb per render.h.
        unsafe {
            let _ = ghostty_render_state_get(
                inner.render_state,
                GhosttyRenderStateData::ColorForeground,
                &mut default_fg as *mut _ as *mut c_void,
            );
            let _ = ghostty_render_state_get(
                inner.render_state,
                GhosttyRenderStateData::ColorBackground,
                &mut default_bg as *mut _ as *mut c_void,
            );
        }

        // Ghostty's render-state dimensions can lag the host resize by a
        // frame or two. Snapshot the actual render-state geometry so we
        // don't invent blank tail rows from our requested size while the
        // terminal catches up asynchronously.
        let mut cols = requested_cols;
        let mut rows = requested_rows;
        unsafe {
            let _ = ghostty_render_state_get(
                inner.render_state,
                GhosttyRenderStateData::Cols,
                &mut cols as *mut _ as *mut c_void,
            );
            let _ = ghostty_render_state_get(
                inner.render_state,
                GhosttyRenderStateData::Rows,
                &mut rows as *mut _ as *mut c_void,
            );
        }
        cols = cols.max(1);
        rows = rows.max(1);

        let mut force_all_dirty = inner.force_full_snapshot;
        let mut full_redraw = force_all_dirty;
        let mut state_dirty = GhosttyRenderStateDirty::False;
        // SAFETY: DIRTY out param is sized for the enum.
        unsafe {
            let _ = ghostty_render_state_get(
                inner.render_state,
                GhosttyRenderStateData::Dirty,
                &mut state_dirty as *mut _ as *mut c_void,
            );
        }
        if state_dirty == GhosttyRenderStateDirty::Full {
            full_redraw = true;
        }

        let total = cols as usize * rows as usize;
        if inner.scratch.len() != total || inner.scratch_cols != cols || inner.scratch_rows != rows
        {
            inner.scratch.clear();
            inner.scratch.resize(total, Cell::default());
            inner.scratch_cols = cols;
            inner.scratch_rows = rows;
            force_all_dirty = true;
            full_redraw = true;
        }

        let mut dirty_rows: Vec<u16> = Vec::new();

        // Bind the row iterator to the current state.
        // SAFETY: state + iter valid.
        let rc = unsafe {
            ghostty_render_state_get(
                inner.render_state,
                GhosttyRenderStateData::RowIterator,
                &mut inner.row_iter as *mut _ as *mut c_void,
            )
        };
        if rc != 0 {
            eprintln!("ghostty_render_state_get(ROW_ITERATOR) rc={rc}");
            return empty_snapshot(cols, rows, inner.generation);
        }

        let mut row_idx: u16 = 0;
        // SAFETY: row_iter valid; `_next` returns bool.
        while unsafe { ghostty_render_state_row_iterator_next(inner.row_iter) } {
            if row_idx >= rows {
                break;
            }

            let mut dirty = GhosttyRenderStateDirty::False;
            // SAFETY: DIRTY out param is sized for the enum.
            unsafe {
                let _ = ghostty_render_state_row_get(
                    inner.row_iter,
                    GhosttyRenderStateRowData::Dirty,
                    &mut dirty as *mut _ as *mut c_void,
                );
            }

            if !full_redraw && dirty == GhosttyRenderStateDirty::False {
                row_idx += 1;
                continue;
            }
            let mut row_changed = force_all_dirty;

            // Bind the cells iterator to the current row.
            // SAFETY: iter + cells valid.
            let rc = unsafe {
                ghostty_render_state_row_get(
                    inner.row_iter,
                    GhosttyRenderStateRowData::Cells,
                    &mut inner.row_cells as *mut _ as *mut c_void,
                )
            };
            if rc != 0 {
                eprintln!("row_get(CELLS) rc={rc} at row {row_idx}");
                row_idx += 1;
                continue;
            }

            let row_start = row_idx as usize * cols as usize;
            let mut col_idx: u16 = 0;
            // SAFETY: cells valid; `_next` returns bool.
            while unsafe { ghostty_render_state_row_cells_next(inner.row_cells) } {
                if col_idx >= cols {
                    break;
                }
                let cell = read_cell(inner.row_cells, default_fg, default_bg);
                let idx = row_start + col_idx as usize;
                row_changed |= inner.scratch[idx] != cell;
                inner.scratch[idx] = cell;
                col_idx += 1;
            }
            // Clear trailing cells in the row.
            for c in col_idx..cols {
                let idx = row_start + c as usize;
                row_changed |= inner.scratch[idx] != Cell::default();
                inner.scratch[idx] = Cell::default();
            }

            if row_changed {
                dirty_rows.push(row_idx);
            }

            row_idx += 1;
        }

        if full_redraw && row_idx < rows {
            eprintln!(
                "vt snapshot full redraw ended early: iter_rows={row_idx} expected_rows={rows} cols={cols}"
            );
            for trailing_row in row_idx..rows {
                let row_start = trailing_row as usize * cols as usize;
                let row_end = row_start + cols as usize;
                let mut row_changed = force_all_dirty;
                for cell in &mut inner.scratch[row_start..row_end] {
                    row_changed |= *cell != Cell::default();
                    *cell = Cell::default();
                }
                if row_changed {
                    dirty_rows.push(trailing_row);
                }
            }
        }

        inner.force_full_snapshot = false;

        // Cursor read from the render state keys (not the terminal, to
        // stay consistent with the render snapshot).
        let mut visible: bool = false;
        let mut col_u16: u16 = 0;
        let mut row_u16: u16 = 0;
        let mut cursor_style = GhosttyRenderStateCursorVisualStyle::Block;
        // SAFETY: out params sized per upstream render.h.
        unsafe {
            let _ = ghostty_render_state_get(
                inner.render_state,
                GhosttyRenderStateData::CursorViewportX,
                &mut col_u16 as *mut _ as *mut c_void,
            );
            let _ = ghostty_render_state_get(
                inner.render_state,
                GhosttyRenderStateData::CursorViewportY,
                &mut row_u16 as *mut _ as *mut c_void,
            );
            let _ = ghostty_render_state_get(
                inner.render_state,
                GhosttyRenderStateData::CursorVisible,
                &mut visible as *mut _ as *mut c_void,
            );
            let _ = ghostty_render_state_get(
                inner.render_state,
                GhosttyRenderStateData::CursorVisualStyle,
                &mut cursor_style as *mut _ as *mut c_void,
            );
        }

        let cursor = Cursor {
            col: col_u16,
            row: row_u16,
            visible,
            style: cursor_style,
        };
        let previous_cursor = inner.last_cursor;
        if previous_cursor != cursor {
            if previous_cursor.visible && previous_cursor.row < rows {
                push_unique_row(&mut dirty_rows, previous_cursor.row);
            }
            if cursor.visible && cursor.row < rows {
                push_unique_row(&mut dirty_rows, cursor.row);
            }
            inner.last_cursor = cursor;
        }
        dirty_rows.sort_unstable();

        let clone_started = perf_trace_enabled().then(Instant::now);
        let cells = inner.scratch.clone();
        let clone_elapsed_ms =
            clone_started.map(|started| started.elapsed().as_secs_f64() * 1000.0);
        let title = terminal_title(&inner);
        let snapshot = ScreenSnapshot {
            cols,
            rows,
            cells,
            dirty_rows,
            cursor,
            default_fg: pack_rgb(default_fg, 0xFF),
            default_bg: pack_rgb(default_bg, 0xFF),
            title,
            generation: inner.generation,
        };

        if let Some(started) = snapshot_started {
            let total_ms = started.elapsed().as_secs_f64() * 1000.0;
            static LAST_LOGGED_GENERATION: AtomicU64 = AtomicU64::new(u64::MAX);
            let previous = LAST_LOGGED_GENERATION.load(Ordering::Relaxed);
            let generation_changed = previous != snapshot.generation
                && LAST_LOGGED_GENERATION
                    .compare_exchange(
                        previous,
                        snapshot.generation,
                        Ordering::Relaxed,
                        Ordering::Relaxed,
                    )
                    .is_ok();
            let should_log = perf_trace_verbose() || generation_changed || total_ms >= 2.0;
            if should_log {
                eprintln!(
                    "vt_snapshot rows={} cols={} dirty_rows={} full_redraw={} cells={} clone_ms={:.3} total_ms={:.3}",
                    rows,
                    cols,
                    snapshot.dirty_rows.len(),
                    full_redraw,
                    snapshot.cells.len(),
                    clone_elapsed_ms.unwrap_or_default(),
                    total_ms
                );
            }
        }

        snapshot
    }

    pub fn size(&self) -> (u16, u16) {
        let inner = self.inner.lock();
        (inner.cols, inner.rows)
    }

    pub fn set_dark_mode(&self, dark: bool) {
        let inner = self.inner.lock();
        if let Some(state) = inner.callback_state.as_ref() {
            state.dark_mode.store(dark, Ordering::Release);
        }
    }

    /// Returns `true` when at least one mouse-tracking mode is set
    /// (X10 / normal / button / any). Host-view mouse handlers gate
    /// mouse reporting on this so wheel / click / move don't leak
    /// escape sequences into shells that didn't ask for them.
    pub fn mouse_tracking_active(&self) -> bool {
        self.mode_active(MODE_NORMAL_MOUSE)
            || self.mode_active(MODE_BUTTON_MOUSE)
            || self.mode_active(MODE_ANY_MOUSE)
            || self.mode_active(MODE_X10_MOUSE)
    }

    /// SGR (1006) mouse format is the extended coord encoding.
    /// Callers use it to choose the report syntax; the default
    /// xterm legacy mouse report uses a different byte layout.
    pub fn is_sgr_mouse(&self) -> bool {
        self.mode_active(MODE_SGR_MOUSE)
    }

    /// Alt-screen scroll (1007): when set, mouse wheel in alt-screen
    /// apps is translated to arrow keys (up/down) rather than SGR
    /// reports. Apps like less / vim opt in.
    pub fn is_alt_scroll(&self) -> bool {
        self.mode_active(MODE_ALT_SCROLL)
    }

    /// Current viewport scrollbar state. Returns `None` when the C API
    /// query fails; callers should hide scrollbar UI in that case.
    pub fn scrollbar(&self) -> Option<GhosttyScrollbar> {
        let inner = self.inner.lock();
        if inner.terminal.is_null() {
            return None;
        }
        let mut scrollbar = GhosttyTerminalScrollbar::default();
        let rc = unsafe {
            ghostty_terminal_get(
                inner.terminal,
                GhosttyTerminalData::Scrollbar,
                &mut scrollbar as *mut _ as *mut c_void,
            )
        };
        (rc == 0).then_some(GhosttyScrollbar {
            total: scrollbar.total,
            offset: scrollbar.offset,
            len: scrollbar.len,
        })
    }

    /// Returns `true` while the alternate screen buffer is active.
    pub fn is_alternate_screen(&self) -> bool {
        let inner = self.inner.lock();
        if inner.terminal.is_null() {
            return false;
        }
        let mut screen = GhosttyTerminalScreen::Primary;
        let rc = unsafe {
            ghostty_terminal_get(
                inner.terminal,
                GhosttyTerminalData::ActiveScreen,
                &mut screen as *mut _ as *mut c_void,
            )
        };
        rc == 0 && screen == GhosttyTerminalScreen::Alternate
    }

    /// Scroll the visible viewport by terminal rows. Negative is up;
    /// positive is down. Returns `true` when a scroll request was sent.
    pub fn scroll_viewport_delta(&self, delta_rows: isize) -> bool {
        if delta_rows == 0 {
            return false;
        }
        let mut inner = self.inner.lock();
        if inner.terminal.is_null() {
            return false;
        }
        let behavior = GhosttyTerminalScrollViewport {
            tag: GhosttyTerminalScrollViewportTag::Delta,
            value: GhosttyTerminalScrollViewportValue { delta: delta_rows },
        };
        unsafe { ghostty_terminal_scroll_viewport(inner.terminal, behavior) };
        inner.force_full_snapshot = true;
        inner.generation = inner.generation.wrapping_add(1);
        true
    }

    /// Bracketed-paste mode (2004). When `true`, paste operations
    /// should wrap the payload in `ESC[200~ … ESC[201~` so the shell
    /// can treat it as a single paste.
    pub fn is_bracketed_paste(&self) -> bool {
        self.mode_active(MODE_BRACKETED_PASTE)
    }

    /// DECCKM (mode 1). When `true`, arrow keys must be encoded in
    /// application-cursor form (`ESC O A/B/C/D`) rather than the
    /// default cursor form (`ESC [ A/B/C/D`).
    pub fn is_decckm(&self) -> bool {
        self.mode_active(MODE_DECCKM)
    }

    /// Generic mode query — returns `false` when the FFI call fails
    /// or the mode isn't set. Never panics.
    pub fn mode_active(&self, mode: GhosttyMode) -> bool {
        let inner = self.inner.lock();
        if inner.terminal.is_null() {
            return false;
        }
        let mut on: bool = false;
        // SAFETY: terminal valid; `on` is a 1-byte C `_Bool`.
        let rc = unsafe { ghostty_terminal_mode_get(inner.terminal, mode, &mut on) };
        rc == 0 && on
    }
}

unsafe extern "C" fn vt_write_pty_callback(
    _terminal: GhosttyTerminal,
    userdata: *mut c_void,
    data: *const u8,
    len: usize,
) {
    if userdata.is_null() || data.is_null() || len == 0 {
        return;
    }

    let state = unsafe { &*(userdata as *const VtCallbackState) };
    let bytes = unsafe { std::slice::from_raw_parts(data, len) };
    (state.write_pty)(bytes);
}

unsafe extern "C" fn vt_enquiry_callback(
    _terminal: GhosttyTerminal,
    userdata: *mut c_void,
) -> GhosttyString {
    if userdata.is_null() {
        return GhosttyString {
            ptr: std::ptr::null(),
            len: 0,
        };
    }

    let state = unsafe { &*(userdata as *const VtCallbackState) };
    GhosttyString {
        ptr: state.enquiry_response.as_ptr(),
        len: state.enquiry_response.len(),
    }
}

unsafe extern "C" fn vt_size_callback(
    _terminal: GhosttyTerminal,
    userdata: *mut c_void,
    out_size: *mut GhosttySizeReportSize,
) -> bool {
    if userdata.is_null() || out_size.is_null() {
        return false;
    }

    let state = unsafe { &*(userdata as *const VtCallbackState) };
    unsafe {
        *out_size = GhosttySizeReportSize {
            rows: state.rows.load(Ordering::Acquire).max(1),
            columns: state.cols.load(Ordering::Acquire).max(1),
            cell_width: state.cell_width.load(Ordering::Acquire).max(1),
            cell_height: state.cell_height.load(Ordering::Acquire).max(1),
        };
    }
    true
}

unsafe extern "C" fn vt_color_scheme_callback(
    _terminal: GhosttyTerminal,
    userdata: *mut c_void,
    out_scheme: *mut GhosttyColorScheme,
) -> bool {
    if userdata.is_null() || out_scheme.is_null() {
        return false;
    }

    let state = unsafe { &*(userdata as *const VtCallbackState) };
    unsafe {
        *out_scheme = if state.dark_mode.load(Ordering::Acquire) {
            GhosttyColorScheme::Dark
        } else {
            GhosttyColorScheme::Light
        };
    }
    true
}

unsafe extern "C" fn vt_device_attributes_callback(
    _terminal: GhosttyTerminal,
    userdata: *mut c_void,
    out_attrs: *mut GhosttyDeviceAttributes,
) -> bool {
    if userdata.is_null() || out_attrs.is_null() {
        return false;
    }

    let state = unsafe { &*(userdata as *const VtCallbackState) };
    unsafe {
        *out_attrs = state.device_attributes;
    }
    true
}

unsafe extern "C" fn vt_xtversion_callback(
    _terminal: GhosttyTerminal,
    _userdata: *mut c_void,
) -> GhosttyString {
    GhosttyString {
        ptr: std::ptr::null(),
        len: 0,
    }
}

fn empty_snapshot(cols: u16, rows: u16, generation: u64) -> ScreenSnapshot {
    ScreenSnapshot {
        cols,
        rows,
        cells: Vec::new(),
        dirty_rows: Vec::new(),
        cursor: Cursor::default(),
        default_fg: 0xffffffff,
        default_bg: 0x282c34ff,
        title: None,
        generation,
    }
}

fn pack_rgb(c: GhosttyColorRgb, a: u8) -> u32 {
    ((c.r as u32) << 24) | ((c.g as u32) << 16) | ((c.b as u32) << 8) | (a as u32)
}

fn push_unique_row(rows: &mut Vec<u16>, row: u16) {
    if !rows.contains(&row) {
        rows.push(row);
    }
}

fn terminal_title(inner: &VtInner) -> Option<String> {
    if inner.terminal.is_null() {
        return None;
    }
    let mut title = GhosttyString::default();
    let rc = unsafe {
        ghostty_terminal_get(
            inner.terminal,
            GhosttyTerminalData::Title,
            &mut title as *mut _ as *mut c_void,
        )
    };
    if rc != 0 || title.ptr.is_null() || title.len == 0 {
        return None;
    }
    let bytes = unsafe { std::slice::from_raw_parts(title.ptr, title.len) };
    std::str::from_utf8(bytes)
        .ok()
        .map(str::trim)
        .filter(|value| !value.is_empty())
        .map(ToOwned::to_owned)
}

fn read_cell(
    cells: GhosttyRowCells,
    default_fg: GhosttyColorRgb,
    default_bg: GhosttyColorRgb,
) -> Cell {
    // RAW here is an **opaque `GhosttyCell` u64 snapshot**, not a packed
    // codepoint. Decode fields via `ghostty_cell_get(cell, KEY, &out)`
    // per `screen.h`. Previous code bitshifted RAW directly and produced
    // nonsense codepoints (U+015C etc. for the "PowerShell" banner).
    let mut raw: GhosttyCell = 0;
    let mut style = GhosttyStyle::new();
    // BG_COLOR / FG_COLOR write a `GhosttyColorRgb` (3 bytes: R, G, B)
    // to the out pointer — NOT a packed u32.
    let mut bg = GhosttyColorRgb::default();
    let mut fg = GhosttyColorRgb::default();

    // SAFETY: out params typed per upstream contract (RAW=GhosttyCell u64,
    // STYLE=GhosttyStyle by value with `size` set to sizeof, BG/FG=GhosttyColorRgb).
    unsafe {
        let _ = ghostty_render_state_row_cells_get(
            cells,
            GhosttyRenderStateRowCellsData::Raw,
            &mut raw as *mut _ as *mut c_void,
        );
        let _ = ghostty_render_state_row_cells_get(
            cells,
            GhosttyRenderStateRowCellsData::Style,
            &mut style as *mut _ as *mut c_void,
        );
        let _ = ghostty_render_state_row_cells_get(
            cells,
            GhosttyRenderStateRowCellsData::BgColor,
            &mut bg as *mut _ as *mut c_void,
        );
        let _ = ghostty_render_state_row_cells_get(
            cells,
            GhosttyRenderStateRowCellsData::FgColor,
            &mut fg as *mut _ as *mut c_void,
        );
    }

    // Gate text decode on HAS_TEXT — blank cells can carry opaque metadata
    // we'd otherwise rasterize as visible glyphs.
    let mut has_text: bool = false;
    let mut wide_mode = GhosttyCellWide::Narrow;
    // SAFETY: `has_text` is a C `_Bool` (1 byte); `wide_mode` matches the
    // upstream enum representation.
    unsafe {
        let _ = ghostty_cell_get(
            raw,
            GhosttyCellData::HasText,
            &mut has_text as *mut _ as *mut c_void,
        );
        let _ = ghostty_cell_get(
            raw,
            GhosttyCellData::Wide,
            &mut wide_mode as *mut _ as *mut c_void,
        );
    }
    let is_spacer = matches!(
        wide_mode,
        GhosttyCellWide::SpacerTail | GhosttyCellWide::SpacerHead
    );
    let text = if has_text && !is_spacer {
        read_cell_text(cells, raw)
    } else {
        String::new()
    };
    let wide = wide_mode == GhosttyCellWide::Wide;

    // Substitute the palette's default fg/bg when the cell's style
    // reports no SGR override (tag == GHOSTTY_STYLE_COLOR_NONE). The
    // row_cells FG_COLOR / BG_COLOR accessors return (0,0,0) for
    // unstyled cells, so without this substitution default-bg cells
    // would paint pure black. Keying off the style tag (not the RGB
    // value) is the correct test: an explicit `SGR 40` or
    // `48;2;0;0;0` sets tag = PALETTE(0) / RGB(0,0,0) while still
    // requesting solid black.
    const STYLE_COLOR_TAG_NONE: u32 = 0;
    let fg_was_default = style.fg_color.tag == STYLE_COLOR_TAG_NONE;
    let bg_was_default = style.bg_color.tag == STYLE_COLOR_TAG_NONE;
    let fg = if fg_was_default { default_fg } else { fg };
    let bg = if bg_was_default { default_bg } else { bg };

    // Pack RGB into the 0xRRGGBBAA u32 our HLSL `unpackRGBA` expects
    // (high byte = R, low byte = A). Default-bg cells carry alpha=0
    // as a sentinel so the renderer can apply pane background opacity
    // while explicit SGR backgrounds stay solid.
    let bg_alpha: u8 = if bg_was_default { 0 } else { 0xFF };

    // Pack style flags into the attrs byte the renderer (and HLSL
    // pixel shader) interpret. Underline is an `int` upstream
    // (0 = none, 1 = single, 2 = double, 3 = curly, ...); any non-zero
    // value enables our single underline rendering for now.
    let mut attrs: u8 = 0;
    if style.bold {
        attrs |= ATTR_BOLD;
    }
    if style.italic {
        attrs |= ATTR_ITALIC;
    }
    if style.underline != 0 {
        attrs |= ATTR_UNDERLINE;
    }
    if style.strikethrough {
        attrs |= ATTR_STRIKE;
    }
    if style.inverse {
        attrs |= ATTR_INVERSE;
    }

    Cell {
        text,
        fg: pack_rgb(fg, 0xFF),
        bg: pack_rgb(bg, bg_alpha),
        attrs,
        wide,
        _pad: [0; 2],
    }
}

fn read_cell_text(cells: GhosttyRowCells, raw: GhosttyCell) -> String {
    let mut graphemes_len: u32 = 0;
    // SAFETY: GRAPHEMES_LEN writes a uint32_t.
    unsafe {
        let _ = ghostty_render_state_row_cells_get(
            cells,
            GhosttyRenderStateRowCellsData::GraphemesLen,
            &mut graphemes_len as *mut _ as *mut c_void,
        );
    }
    if graphemes_len > 0 && graphemes_len <= 64 {
        let mut codepoints = vec![0u32; graphemes_len as usize];
        // SAFETY: buffer has graphemes_len u32 slots as required by render.h.
        unsafe {
            let _ = ghostty_render_state_row_cells_get(
                cells,
                GhosttyRenderStateRowCellsData::GraphemesBuf,
                codepoints.as_mut_ptr() as *mut c_void,
            );
        }
        let mut text = String::with_capacity(codepoints.len());
        for codepoint in codepoints {
            if let Some(ch) = char::from_u32(codepoint) {
                text.push(ch);
            }
        }
        return text;
    }

    let mut codepoint: u32 = 0;
    // SAFETY: CODEPOINT writes a uint32_t.
    unsafe {
        let _ = ghostty_cell_get(
            raw,
            GhosttyCellData::Codepoint,
            &mut codepoint as *mut _ as *mut c_void,
        );
    }
    char::from_u32(codepoint)
        .filter(|ch| *ch != '\0')
        .map(String::from)
        .unwrap_or_default()
}

impl Drop for VtScreen {
    fn drop(&mut self) {
        if let Some(mutex) = Arc::get_mut(&mut self.inner) {
            let inner = mutex.get_mut();
            // Free in reverse-creation order: cells, iter, state, terminal.
            // SAFETY: unique owner via Arc::get_mut.
            if !inner.row_cells.is_null() {
                unsafe { ghostty_render_state_row_cells_free(inner.row_cells) };
                inner.row_cells = std::ptr::null_mut();
            }
            if !inner.row_iter.is_null() {
                unsafe { ghostty_render_state_row_iterator_free(inner.row_iter) };
                inner.row_iter = std::ptr::null_mut();
            }
            if !inner.render_state.is_null() {
                unsafe { ghostty_render_state_free(inner.render_state) };
                inner.render_state = std::ptr::null_mut();
            }
            if !inner.terminal.is_null() {
                unsafe { ghostty_terminal_free(inner.terminal) };
                inner.terminal = std::ptr::null_mut();
            }
        }
    }
}