fux 0.11.0

Minimal persistent terminal multiplexer built on bevy_ecs
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
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
//! Wire-level snapshot types shared by the session server and the viewer: pane cells, per-viewer
//! frames and private history views. Frames are derived data; the ECS World is authoritative.

use crate::ids::{PaneId, TabId};
use crate::layout::Rect;
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use unicode_segmentation::UnicodeSegmentation as _;
use unicode_width::UnicodeWidthStr as _;

pub const MAX_DIM: u16 = crate::terminal::MAX_DIM;
pub const MAX_CELL_TEXT_BYTES: usize = 22;
pub const MAX_TITLE_BYTES: usize = 1024;

/// `text` without control characters, at most `max_chars` characters: the one rule for titles,
/// labels and notices that cross the wire or reach the screen.
#[must_use]
pub fn printable(text: &str, max_chars: usize) -> String {
    text.chars()
        .filter(|character| !character.is_control())
        .take(max_chars)
        .collect()
}
pub const MAX_LABEL_BYTES: usize = 128;
pub const MAX_PANES: usize = 128;
pub const MAX_TABS: usize = 32;
/// One maximum-size pane across a frame (`MAX_DIM * MAX_DIM`).
pub const MAX_TOTAL_CELLS: usize = 262_144;
pub const MAX_MESSAGE_BYTES: usize = 512;

#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum CellKind {
    #[default]
    Blank,
    Text,
    WideLeading,
    WideContinuation,
}

impl CellKind {
    /// The kebab-case wire name.
    #[must_use]
    pub const fn name(self) -> &'static str {
        match self {
            Self::Blank => "blank",
            Self::Text => "text",
            Self::WideLeading => "wide-leading",
            Self::WideContinuation => "wide-continuation",
        }
    }
}

/// A cell colour. On the wire it is `null` (the terminal default), a palette index, or an
/// `[r, g, b]` triple.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum Color {
    #[default]
    Default,
    Indexed(u8),
    Rgb(u8, u8, u8),
}

impl From<vt100::Color> for Color {
    fn from(value: vt100::Color) -> Self {
        match value {
            vt100::Color::Default => Self::Default,
            vt100::Color::Idx(index) => Self::Indexed(index),
            vt100::Color::Rgb(red, green, blue) => Self::Rgb(red, green, blue),
        }
    }
}

impl Color {
    /// Exact length of this colour's compact JSON encoding.
    const fn encoded_len(self) -> usize {
        match self {
            Self::Default => 4,
            Self::Indexed(index) => digits(index),
            Self::Rgb(red, green, blue) => 4 + digits(red) + digits(green) + digits(blue),
        }
    }
}

/// Decimal digit count of a byte.
const fn digits(value: u8) -> usize {
    if value >= 100 {
        3
    } else if value >= 10 {
        2
    } else {
        1
    }
}

/// Decimal digit count of a `u16`.
pub(crate) const fn digits_u16(value: u16) -> usize {
    if value >= 10_000 {
        5
    } else if value >= 1_000 {
        4
    } else if value >= 100 {
        3
    } else if value >= 10 {
        2
    } else {
        1
    }
}

/// Attribute bits of a wire style: `[foreground, background, attributes]`. The bit layout
/// mirrors vt100's text mode so a style converts without branching.
pub const ATTR_BOLD: u8 = 0b0000_0001;
pub const ATTR_DIM: u8 = 0b0000_0010;
pub const ATTR_ITALIC: u8 = 0b0000_0100;
pub const ATTR_UNDERLINE: u8 = 0b0000_1000;
pub const ATTR_INVERSE: u8 = 0b0001_0000;
const ATTR_ALL: u8 = ATTR_BOLD | ATTR_DIM | ATTR_ITALIC | ATTR_UNDERLINE | ATTR_INVERSE;

/// The wire shape of a [`CellStyle`]: `[foreground, background, attributes]`.
#[derive(Serialize, Deserialize)]
struct WireStyle(Color, Color, u8);

#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
#[serde(into = "WireStyle", try_from = "WireStyle")]
pub struct CellStyle {
    pub foreground: Color,
    pub background: Color,
    pub bold: bool,
    pub dim: bool,
    pub italic: bool,
    pub underline: bool,
    pub inverse: bool,
}

impl From<CellStyle> for WireStyle {
    fn from(style: CellStyle) -> Self {
        Self(style.foreground, style.background, style.attributes())
    }
}

impl TryFrom<WireStyle> for CellStyle {
    type Error = String;

    fn try_from(WireStyle(foreground, background, attributes): WireStyle) -> Result<Self, String> {
        if attributes & !ATTR_ALL != 0 {
            return Err(format!("unknown style attribute bits {attributes:#x}"));
        }
        Ok(Self {
            foreground,
            background,
            bold: attributes & ATTR_BOLD != 0,
            dim: attributes & ATTR_DIM != 0,
            italic: attributes & ATTR_ITALIC != 0,
            underline: attributes & ATTR_UNDERLINE != 0,
            inverse: attributes & ATTR_INVERSE != 0,
        })
    }
}

impl CellStyle {
    #[must_use]
    pub fn is_default(&self) -> bool {
        *self == Self::default()
    }

    /// The attribute bitset carried on the wire.
    #[must_use]
    pub const fn attributes(&self) -> u8 {
        (if self.bold { ATTR_BOLD } else { 0 })
            | (if self.dim { ATTR_DIM } else { 0 })
            | (if self.italic { ATTR_ITALIC } else { 0 })
            | (if self.underline { ATTR_UNDERLINE } else { 0 })
            | (if self.inverse { ATTR_INVERSE } else { 0 })
    }

    /// Exact length of this style's compact JSON encoding.
    const fn encoded_len(&self) -> usize {
        // `[` fg `,` bg `,` attrs `]`
        4 + self.foreground.encoded_len()
            + self.background.encoded_len()
            + digits(self.attributes())
    }

    #[must_use]
    pub fn from_vt100(cell: &vt100::Cell) -> Self {
        Self {
            foreground: cell.fgcolor().into(),
            background: cell.bgcolor().into(),
            bold: cell.bold(),
            dim: cell.dim(),
            italic: cell.italic(),
            underline: cell.underline(),
            inverse: cell.inverse(),
        }
    }
}

/// The kind a vt100 cell has on the wire and in a grid.
#[must_use]
pub fn kind_of(cell: &vt100::Cell) -> CellKind {
    if cell.is_wide_continuation() {
        CellKind::WideContinuation
    } else if cell.is_wide() {
        CellKind::WideLeading
    } else if cell.has_contents() {
        CellKind::Text
    } else {
        CellKind::Blank
    }
}

/// The text and kind a vt100 cell contributes to a frame. Content a cell cannot carry (a
/// zero-width or multi-grapheme sequence, a control character, a width that disagrees with the
/// emulator's) shows as a blank of the same style instead of invalidating the frame.
#[must_use]
pub fn classify(cell: &vt100::Cell) -> (&str, CellKind) {
    if !cell.has_contents() {
        // Empty text cannot carry, so the general path below would yield this exact result;
        // skipping it avoids validating the (empty) contents for every blank cell.
        return match kind_of(cell) {
            CellKind::WideContinuation => ("", CellKind::WideContinuation),
            CellKind::Blank | CellKind::Text | CellKind::WideLeading => ("", CellKind::Blank),
        };
    }
    let text = cell.contents();
    let kind = kind_of(cell);
    let carried = match kind {
        CellKind::Text => one_grapheme_of_width(text, 1),
        CellKind::WideLeading => one_grapheme_of_width(text, 2),
        CellKind::Blank | CellKind::WideContinuation => text.is_empty(),
    };
    match (carried, kind) {
        (true, kind) => (text, kind),
        (false, CellKind::WideContinuation) => ("", CellKind::WideContinuation),
        (false, _) => ("", CellKind::Blank),
    }
}

fn one_grapheme_of_width(text: &str, width: usize) -> bool {
    if let [byte] = text.as_bytes() {
        // Printable ASCII: the common case needs no segmentation.
        return width == 1 && (0x20..0x7f).contains(byte);
    }
    text.len() <= MAX_CELL_TEXT_BYTES
        && !text.chars().any(char::is_control)
        && text.graphemes(true).count() == 1
        && text.width() == width
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct Cell {
    pub text: String,
    pub kind: CellKind,
    pub style: CellStyle,
}

impl Default for Cell {
    fn default() -> Self {
        Self {
            text: String::new(),
            kind: CellKind::Blank,
            style: CellStyle::default(),
        }
    }
}

impl Cell {
    #[must_use]
    pub fn from_vt100(cell: &vt100::Cell) -> Self {
        let (text, kind) = classify(cell);
        Self {
            text: text.to_owned(),
            kind,
            style: CellStyle::from_vt100(cell),
        }
    }

    #[must_use]
    pub fn valid(&self) -> bool {
        self.text.len() <= MAX_CELL_TEXT_BYTES
            && !self.text.chars().any(char::is_control)
            && match self.kind {
                CellKind::Blank | CellKind::WideContinuation => self.text.is_empty(),
                CellKind::Text => self.text.graphemes(true).count() == 1 && self.text.width() == 1,
                CellKind::WideLeading => {
                    self.text.graphemes(true).count() == 1 && self.text.width() == 2
                }
            }
    }
}

#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
pub struct Cursor {
    pub row: u16,
    pub column: u16,
    pub hidden: bool,
}

#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum MouseMode {
    #[default]
    None,
    Press,
    PressRelease,
    ButtonMotion,
    AnyMotion,
}

#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum MouseEncoding {
    #[default]
    Default,
    Utf8,
    Sgr,
}

#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
pub struct PaneModes {
    pub alternate_screen: bool,
    pub application_keypad: bool,
    pub application_cursor: bool,
    pub bracketed_paste: bool,
    pub mouse_mode: MouseMode,
    pub mouse_encoding: MouseEncoding,
}

impl PaneModes {
    #[must_use]
    pub fn from_vt100(screen: &vt100::Screen) -> Self {
        let mouse_mode = match screen.mouse_protocol_mode() {
            vt100::MouseProtocolMode::None => MouseMode::None,
            vt100::MouseProtocolMode::Press => MouseMode::Press,
            vt100::MouseProtocolMode::PressRelease => MouseMode::PressRelease,
            vt100::MouseProtocolMode::ButtonMotion => MouseMode::ButtonMotion,
            vt100::MouseProtocolMode::AnyMotion => MouseMode::AnyMotion,
        };
        let mouse_encoding = match screen.mouse_protocol_encoding() {
            vt100::MouseProtocolEncoding::Default => MouseEncoding::Default,
            vt100::MouseProtocolEncoding::Utf8 => MouseEncoding::Utf8,
            vt100::MouseProtocolEncoding::Sgr => MouseEncoding::Sgr,
        };
        Self {
            alternate_screen: screen.alternate_screen(),
            application_keypad: screen.application_keypad(),
            application_cursor: screen.application_cursor(),
            bracketed_paste: screen.bracketed_paste(),
            mouse_mode,
            mouse_encoding,
        }
    }
}

/// Ownership of ordinary right-clicks in a pane; Alt-right-click always opens fux's menu.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize, clap::ValueEnum)]
#[serde(rename_all = "kebab-case")]
#[value(rename_all = "kebab-case")]
pub enum RightClickPolicy {
    #[default]
    Auto,
    Fux,
    Pane,
}

impl RightClickPolicy {
    pub fn name(self) -> &'static str {
        match self {
            Self::Auto => "auto",
            Self::Fux => "fux",
            Self::Pane => "pane",
        }
    }

    pub fn is_auto(&self) -> bool {
        *self == Self::Auto
    }
    pub fn next(self) -> Self {
        match self {
            Self::Auto => Self::Fux,
            Self::Fux => Self::Pane,
            Self::Pane => Self::Auto,
        }
    }
}

/// One rendered pane surface, either the live screen or a private history viewport.
#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
pub struct PaneView {
    pub rows: u16,
    pub columns: u16,
    pub cells: Vec<Cell>,
    pub cursor: Cursor,
    pub modes: PaneModes,
    pub title: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub label: Option<String>,
    #[serde(default, skip_serializing_if = "RightClickPolicy::is_auto")]
    pub right_click: RightClickPolicy,
    /// One flag per row; true means the row continues into the next without a newline.
    pub wrapped_rows: Vec<bool>,
    /// History rows above the live screen that this view starts at (0 = live).
    pub offset: u32,
    /// Final process status once the pane's process has exited.
    pub exit: Option<u32>,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)]
#[error("pane view exceeds frame bounds")]
pub struct PaneViewError;

impl PaneView {
    /// A full view of a vt100 screen, built through the wire path tests exercise elsewhere.
    #[cfg(test)]
    pub fn from_screen(
        screen: &vt100::Screen,
        title: &str,
        offset: u32,
        exit: Option<u32>,
    ) -> Result<Self, PaneViewError> {
        Self::from_update(&PaneUpdate::full_from_screen(screen, title, offset, exit)?)
    }

    #[must_use]
    pub fn valid(&self) -> bool {
        self.shape_valid() && self.cells.iter().all(Cell::valid)
    }

    /// The bounds and counts alone; cells are validated when they are produced.
    #[must_use]
    pub fn shape_valid(&self) -> bool {
        self.rows <= MAX_DIM
            && self.columns <= MAX_DIM
            && self.cells.len() == usize::from(self.rows) * usize::from(self.columns)
            && self.wrapped_rows.len() == usize::from(self.rows)
            && self.title.len() <= MAX_TITLE_BYTES
            && self.label.as_ref().is_none_or(|label| {
                label.len() <= MAX_LABEL_BYTES && !label.chars().any(char::is_control)
            })
    }

    /// A view from a full update; every row must be carried exactly once. Nothing is allocated
    /// before the update's dimensions and counts are checked.
    pub fn from_update(update: &PaneUpdate) -> Result<Self, PaneViewError> {
        if !update.full || !update.within_bounds() {
            return Err(PaneViewError);
        }
        let mut view = Self {
            rows: update.rows,
            columns: update.columns,
            cells: vec![Cell::default(); usize::from(update.rows) * usize::from(update.columns)],
            wrapped_rows: vec![false; usize::from(update.rows)],
            ..Self::default()
        };
        view.apply_rows(update)?;
        view.apply_meta(update);
        if update.lines.len() != usize::from(update.rows) {
            return Err(PaneViewError);
        }
        Ok(view)
    }

    /// Applies an update: a full one replaces the view, a delta replaces the carried rows.
    pub fn apply(&mut self, update: &PaneUpdate) -> Result<(), PaneViewError> {
        if update.full {
            *self = Self::from_update(update)?;
            return Ok(());
        }
        if (update.rows, update.columns) != (self.rows, self.columns) || !update.within_bounds() {
            return Err(PaneViewError);
        }
        self.apply_rows(update)?;
        self.apply_meta(update);
        Ok(())
    }

    fn apply_meta(&mut self, update: &PaneUpdate) {
        self.cursor = update.cursor;
        self.modes = update.modes;
        self.title.clone_from(&update.title);
        self.label.clone_from(&update.label);
        self.right_click = update.right_click;
        self.offset = update.offset;
        self.exit = update.exit;
    }

    fn apply_rows(&mut self, update: &PaneUpdate) -> Result<(), PaneViewError> {
        if update.title.len() > MAX_TITLE_BYTES
            || update.label.as_ref().is_some_and(|label| {
                label.len() > MAX_LABEL_BYTES || label.chars().any(char::is_control)
            })
        {
            return Err(PaneViewError);
        }
        let columns = usize::from(self.columns);
        let mut cells = update.cells.as_slice();
        let mut seen = vec![false; usize::from(self.rows)];
        for line in &update.lines {
            let row = usize::from(line.row);
            let flag = seen.get_mut(row).ok_or(PaneViewError)?;
            if *flag {
                return Err(PaneViewError);
            }
            *flag = true;
            let (carried, rest) = cells
                .split_at_checked(usize::from(line.len))
                .ok_or(PaneViewError)?;
            cells = rest;
            let target = self
                .cells
                .get_mut(row * columns..(row + 1) * columns)
                .ok_or(PaneViewError)?;
            expand(carried, target)?;
            if let Some(wrapped) = self.wrapped_rows.get_mut(row) {
                *wrapped = line.wrapped;
            }
        }
        if !cells.is_empty() {
            return Err(PaneViewError);
        }
        Ok(())
    }

    #[must_use]
    pub fn cell(&self, row: u16, column: u16) -> Option<&Cell> {
        if row >= self.rows || column >= self.columns {
            return None;
        }
        let index = usize::from(row)
            .checked_mul(usize::from(self.columns))?
            .checked_add(usize::from(column))?;
        self.cells.get(index)
    }

    /// Text of the rectangle from `start` to `end` (inclusive, row-major), joining wrapped rows
    /// and skipping wide-cell continuations so copied text matches what is displayed.
    #[must_use]
    pub fn text_between(&self, start: (u16, u16), end: (u16, u16)) -> String {
        let (start, end) = if start <= end {
            (start, end)
        } else {
            (end, start)
        };
        let mut output = String::new();
        let last_row = end.0.min(self.rows.saturating_sub(1));
        for row in start.0..=last_row {
            let first = if row == start.0 { start.1 } else { 0 };
            let last = if row == end.0 {
                end.1
            } else {
                self.columns.saturating_sub(1)
            };
            let mut line = String::new();
            for column in first..=last.min(self.columns.saturating_sub(1)) {
                if let Some(cell) = self.cell(row, column)
                    && cell.kind != CellKind::WideContinuation
                {
                    if cell.kind == CellKind::Blank {
                        line.push(' ');
                    } else {
                        line.push_str(&cell.text);
                    }
                }
            }
            output.push_str(line.trim_end_matches(' '));
            let wrapped = self
                .wrapped_rows
                .get(usize::from(row))
                .copied()
                .unwrap_or(false);
            if row != last_row && !wrapped {
                output.push('\n');
            }
        }
        output
    }
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct TabEntry {
    pub id: TabId,
    pub label: String,
    pub layout_generation: u64,
    /// Deterministic insertion target for transfers from another tab.
    pub first_pane: Option<PaneId>,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PaneRect {
    pub pane: PaneId,
    pub rect: Rect,
}

/// Everything one viewer needs to paint: its own tab, focus and layout over the shared panes.
#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Frame {
    pub viewer: crate::ids::ViewerId,
    pub server_instance: String,
    pub workspace: String,
    pub workspace_stream: u64,
    pub workspace_label: Option<String>,
    /// Increases with every published frame for this viewer; mouse events echo it.
    pub generation: u64,
    pub layout_generation: u64,
    pub zoomed: Option<PaneId>,
    pub tabs: Vec<TabEntry>,
    pub active_tab: Option<TabId>,
    pub focused: Option<PaneId>,
    /// Content rectangles of the panes visible in the active tab; the viewer's last row is the
    /// bar and the one-cell gaps between siblings carry the separators.
    pub layout: Vec<PaneRect>,
    pub panes: BTreeMap<PaneId, PaneView>,
    /// Set once the workspace has retired; viewers exit with this code.
    pub exit_code: Option<u32>,
    /// A short, sanitized notice for this viewer (for example a rejected command).
    pub message: Option<String>,
}

/// Sparse workspace presentation. An explicit null label clears a previous manual label.
#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct WorkspacePresentation {
    pub label: Option<String>,
}

fn valid_workspace_label(label: Option<&str>) -> bool {
    label.is_none_or(|label| label.len() <= 128 && !label.chars().any(char::is_control))
}

impl Frame {
    #[must_use]
    pub fn workspace_display_name(&self) -> &str {
        self.workspace_label.as_deref().unwrap_or(&self.workspace)
    }

    #[must_use]
    pub fn valid(&self) -> bool {
        valid_workspace_label(self.workspace_label.as_deref())
            && self
                .zoomed
                .is_none_or(|pane| self.focused == Some(pane) && self.layout.len() == 1)
            && self.tabs.len() <= MAX_TABS
            && self.panes.len() <= MAX_PANES
            && self.layout.len() <= MAX_PANES
            && self.server_instance.len() <= 128
            && self.workspace.len() <= 64
            && self
                .tabs
                .iter()
                .all(|tab| tab.label.len() <= MAX_LABEL_BYTES)
            && self.panes.values().all(PaneView::shape_valid)
            && self
                .panes
                .values()
                .map(|pane| pane.cells.len())
                .sum::<usize>()
                <= MAX_TOTAL_CELLS
            && self
                .layout
                .iter()
                .all(|entry| self.panes.contains_key(&entry.pane))
            && self
                .active_tab
                .is_none_or(|active| self.tabs.iter().any(|tab| tab.id == active))
            && self
                .focused
                .is_none_or(|focused| self.layout.iter().any(|entry| entry.pane == focused))
            && self
                .message
                .as_ref()
                .is_none_or(|message| message.len() <= MAX_MESSAGE_BYTES)
    }

    #[must_use]
    pub fn pane(&self, id: PaneId) -> Option<&PaneView> {
        self.panes.get(&id)
    }

    /// Applies one update from the server. A full update replaces every pane; a delta replaces
    /// the carried rows of the panes it names. Panes that left the layout are dropped.
    pub fn apply(&mut self, update: FrameUpdate) -> Result<(), FrameError> {
        if !update.within_bounds(self) {
            return Err(FrameError::Invalid);
        }
        if update.full {
            self.panes.clear();
        }
        let shown: Vec<PaneId> = update.layout.iter().map(|entry| entry.pane).collect();
        for (id, pane) in update.panes {
            if !shown.contains(&id) {
                continue;
            }
            match self.panes.get_mut(&id) {
                Some(view) if !pane.full => view.apply(&pane)?,
                _ => {
                    self.panes.insert(id, PaneView::from_update(&pane)?);
                }
            }
        }
        if let Some(viewer) = update.viewer {
            self.viewer = viewer;
        }
        if let Some(instance) = update.server_instance {
            self.server_instance = instance;
        }
        self.workspace = update.workspace;
        if update.full {
            self.workspace_label = None;
        }
        if let Some(presentation) = update.workspace_presentation {
            self.workspace_label = presentation.label;
        }
        if let Some(stream) = update.workspace_stream {
            self.workspace_stream = stream;
        }
        self.generation = update.generation;
        self.layout_generation = update.layout_generation;
        self.zoomed = update.zoomed;
        if let Some(tabs) = update.tabs {
            self.tabs = tabs;
        }
        self.active_tab = update.active_tab;
        self.focused = update.focused;
        self.layout = update.layout;
        self.exit_code = update.exit_code;
        self.message = update.message;
        self.panes.retain(|id, _| shown.contains(id));
        if self.valid() {
            Ok(())
        } else {
            Err(FrameError::Invalid)
        }
    }

    #[must_use]
    pub fn focused_pane(&self) -> Option<&PaneView> {
        self.panes.get(&self.focused?)
    }

    #[must_use]
    pub fn rect(&self, id: PaneId) -> Option<Rect> {
        self.layout
            .iter()
            .find(|entry| entry.pane == id)
            .map(|entry| entry.rect)
    }

    /// The pane whose outer rectangle contains the zero-based screen position.
    #[must_use]
    pub fn pane_at(&self, x: u16, y: u16) -> Option<PaneRect> {
        self.layout
            .iter()
            .copied()
            .find(|entry| entry.rect.contains(x, y))
    }
}

/// A frame or update that violates the documented bounds.
#[derive(Debug, thiserror::Error)]
pub enum FrameError {
    #[error(transparent)]
    Pane(#[from] PaneViewError),
    #[error("frame violates its bounds")]
    Invalid,
}

fn is_false(value: &bool) -> bool {
    !*value
}

fn is_zero_u16(value: &u16) -> bool {
    *value == 0
}

fn is_zero_u32(value: &u32) -> bool {
    *value == 0
}

/// One carried row of a pane update: the row, whether it wraps into the next, and how many wire
/// cells encode it.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Line {
    pub row: u16,
    #[serde(default, skip_serializing_if = "is_false")]
    pub wrapped: bool,
    pub len: u16,
}

/// A cell on the wire: text with its kind and style, or a run of blank cells sharing a style.
/// Absent fields take their defaults, so a blank default cell is `{}` and a run `{"run":40}`.
#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct WireCell {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub text: Option<String>,
    /// `text` implies `Text`, no text implies `Blank`; only the wide kinds are spelled out.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub kind: Option<CellKind>,
    #[serde(default, skip_serializing_if = "CellStyle::is_default")]
    pub style: CellStyle,
    /// Number of cells a blank stands for; 0 and 1 mean one.
    #[serde(default, skip_serializing_if = "is_zero_u16")]
    pub run: u16,
}

impl WireCell {
    /// Exact length of this cell's compact JSON encoding, so a capture can be bounded without
    /// encoding every row twice.
    #[must_use]
    pub fn encoded_len(&self) -> usize {
        let mut fields = 0_usize;
        let mut len = 2; // `{` and `}`
        if let Some(text) = &self.text {
            fields += 1;
            len += 9 + json_string_len(text); // `"text":"` … `"`
        }
        if let Some(kind) = self.kind {
            fields += 1;
            len += 7 + 2 + kind.name().len(); // `"kind":` `"` … `"`
        }
        if !self.style.is_default() {
            fields += 1;
            len += 8 + self.style.encoded_len(); // `"style":` …
        }
        if self.run != 0 {
            fields += 1;
            len += 6 + digits_u16(self.run); // `"run":` …
        }
        len + fields.saturating_sub(1) // commas between fields
    }

    fn matches_blank(&self, kind: CellKind, style: CellStyle) -> bool {
        self.text.is_none() && self.kind.unwrap_or_default() == kind && self.style == style
    }
}

/// Length of `text` as a JSON string body under serde_json's escaping rules (`"` and `\\` gain
/// a backslash, the short control escapes take two bytes, other control characters six).
fn json_string_len(text: &str) -> usize {
    text.bytes()
        .map(|byte| match byte {
            b'"' | b'\\' | 0x08 | 0x09 | 0x0a | 0x0c | 0x0d => 2,
            0x00..=0x1f => 6,
            _ => 1,
        })
        .sum()
}

/// Appends one cell to the wire row that starts at `row_start`, extending a run of equal blanks
/// within that row instead of adding a cell.
pub fn push_wire(
    cells: &mut Vec<WireCell>,
    row_start: usize,
    text: &str,
    kind: CellKind,
    style: CellStyle,
) {
    if text.is_empty() {
        if let Some(last) = cells.get_mut(row_start..).and_then(<[WireCell]>::last_mut)
            && last.matches_blank(kind, style)
            && last.run < u16::MAX
        {
            last.run = last.run.max(1).saturating_add(1);
            return;
        }
        cells.push(WireCell {
            text: None,
            kind: (kind != CellKind::Blank).then_some(kind),
            style,
            run: 0,
        });
        return;
    }
    cells.push(WireCell {
        text: Some(text.to_owned()),
        kind: (kind != CellKind::Text).then_some(kind),
        style,
        run: 0,
    });
}

/// Appends one vt100 cell (a missing one as a default blank) to the wire row starting at
/// `row_start`, classifying its text and style at emission time.
pub fn push_vt100(cells: &mut Vec<WireCell>, row_start: usize, cell: Option<&vt100::Cell>) {
    match cell {
        Some(cell) => {
            let (text, kind) = classify(cell);
            push_wire(cells, row_start, text, kind, CellStyle::from_vt100(cell));
        }
        None => push_wire(cells, row_start, "", CellKind::Blank, CellStyle::default()),
    }
}

/// Expands one carried row into exactly `target.len()` validated cells.
fn expand(carried: &[WireCell], target: &mut [Cell]) -> Result<(), PaneViewError> {
    let mut column = 0_usize;
    for wire in carried {
        let cell = match &wire.text {
            Some(text) => Cell {
                text: text.clone(),
                kind: wire.kind.unwrap_or(CellKind::Text),
                style: wire.style,
            },
            None => Cell {
                text: String::new(),
                kind: wire.kind.unwrap_or(CellKind::Blank),
                style: wire.style,
            },
        };
        if !cell.valid() {
            return Err(PaneViewError);
        }
        let count = if cell.text.is_empty() {
            usize::from(wire.run.max(1))
        } else if wire.run > 1 {
            return Err(PaneViewError);
        } else {
            1
        };
        let slots = target
            .get_mut(column..column.saturating_add(count))
            .ok_or(PaneViewError)?;
        if slots.len() != count {
            return Err(PaneViewError);
        }
        for slot in slots {
            slot.clone_from(&cell);
        }
        column = column.saturating_add(count);
    }
    if column != target.len() {
        return Err(PaneViewError);
    }
    Ok(())
}

/// Deserializes at most `limit` elements, so a hostile peer cannot make the receiver allocate
/// beyond the documented bounds before the update is checked.
fn bounded_seq<'de, D, T>(deserializer: D, limit: usize) -> Result<Vec<T>, D::Error>
where
    D: serde::Deserializer<'de>,
    T: serde::Deserialize<'de>,
{
    struct Bounded<T>(usize, std::marker::PhantomData<T>);
    impl<'de, T: serde::Deserialize<'de>> serde::de::Visitor<'de> for Bounded<T> {
        type Value = Vec<T>;
        fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
            write!(formatter, "a sequence of at most {} elements", self.0)
        }
        fn visit_seq<A: serde::de::SeqAccess<'de>>(self, mut seq: A) -> Result<Vec<T>, A::Error> {
            let mut items = Vec::new();
            while let Some(item) = seq.next_element()? {
                if items.len() >= self.0 {
                    return Err(serde::de::Error::custom("sequence exceeds its bound"));
                }
                items.push(item);
            }
            Ok(items)
        }
    }
    deserializer.deserialize_seq(Bounded(limit, std::marker::PhantomData))
}

fn bounded_lines<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<Vec<Line>, D::Error> {
    bounded_seq(deserializer, usize::from(MAX_DIM))
}

fn bounded_cells<'de, D: serde::Deserializer<'de>>(
    deserializer: D,
) -> Result<Vec<WireCell>, D::Error> {
    bounded_seq(deserializer, MAX_TOTAL_CELLS)
}

/// One pane on the wire: its metadata and either every row (`full`) or the rows that changed
/// since the viewer's previous update.
#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PaneUpdate {
    pub rows: u16,
    pub columns: u16,
    pub cursor: Cursor,
    pub modes: PaneModes,
    pub title: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub label: Option<String>,
    #[serde(default, skip_serializing_if = "RightClickPolicy::is_auto")]
    pub right_click: RightClickPolicy,
    #[serde(default, skip_serializing_if = "is_false")]
    pub full: bool,
    /// The carried rows, each followed in `cells` by `len` wire cells.
    #[serde(
        default,
        skip_serializing_if = "Vec::is_empty",
        deserialize_with = "bounded_lines"
    )]
    pub lines: Vec<Line>,
    #[serde(
        default,
        skip_serializing_if = "Vec::is_empty",
        deserialize_with = "bounded_cells"
    )]
    pub cells: Vec<WireCell>,
    #[serde(default, skip_serializing_if = "is_zero_u32")]
    pub offset: u32,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub exit: Option<u32>,
}

impl PaneUpdate {
    /// The documented bounds a receiver checks before it allocates anything: dimensions, the
    /// carried rows and the wire cells (a line cannot need more wire cells than columns).
    #[must_use]
    pub fn within_bounds(&self) -> bool {
        self.rows <= MAX_DIM
            && self.columns <= MAX_DIM
            && self.lines.len() <= usize::from(self.rows)
            && self.cells.len() <= self.lines.len().saturating_mul(usize::from(self.columns))
            && self.title.len() <= MAX_TITLE_BYTES
            && self.label.as_ref().is_none_or(|label| {
                label.len() <= MAX_LABEL_BYTES && !label.chars().any(char::is_control)
            })
    }

    /// A full update of a vt100 screen (history views and tests).
    pub fn full_from_screen(
        screen: &vt100::Screen,
        title: &str,
        offset: u32,
        exit: Option<u32>,
    ) -> Result<Self, PaneViewError> {
        let (rows, columns) = screen.size();
        if rows > MAX_DIM || columns > MAX_DIM || title.len() > MAX_TITLE_BYTES {
            return Err(PaneViewError);
        }
        let (cursor_row, cursor_column) = screen.cursor_position();
        let mut update = Self {
            rows,
            columns,
            cursor: Cursor {
                row: cursor_row,
                column: cursor_column,
                hidden: screen.hide_cursor(),
            },
            modes: PaneModes::from_vt100(screen),
            title: title.to_owned(),
            label: None,
            right_click: RightClickPolicy::Auto,
            full: true,
            lines: Vec::with_capacity(usize::from(rows)),
            cells: Vec::new(),
            offset,
            exit,
        };
        for row in 0..rows {
            let start = update.cells.len();
            for column in 0..columns {
                push_vt100(&mut update.cells, start, screen.cell(row, column));
            }
            update.lines.push(Line {
                row,
                wrapped: screen.row_wrapped(row),
                len: u16::try_from(update.cells.len() - start).unwrap_or(u16::MAX),
            });
        }
        Ok(update)
    }

    /// Folds a later update for the same pane into this one: rows the later one carries replace
    /// the rows carried here, everything else stays.
    pub fn merge(&mut self, newer: Self) {
        if newer.full || (self.rows, self.columns) != (newer.rows, newer.columns) {
            *self = newer;
            return;
        }
        let mut rows: BTreeMap<u16, (bool, Vec<WireCell>)> = BTreeMap::new();
        let mut cells = self.cells.iter();
        for line in &self.lines {
            let carried: Vec<WireCell> = cells
                .by_ref()
                .take(usize::from(line.len))
                .cloned()
                .collect();
            rows.insert(line.row, (line.wrapped, carried));
        }
        let mut cells = newer.cells.into_iter();
        for line in newer.lines {
            let carried: Vec<WireCell> = cells.by_ref().take(usize::from(line.len)).collect();
            rows.insert(line.row, (line.wrapped, carried));
        }
        self.lines.clear();
        self.cells.clear();
        for (row, (wrapped, carried)) in rows {
            self.lines.push(Line {
                row,
                wrapped,
                len: u16::try_from(carried.len()).unwrap_or(u16::MAX),
            });
            self.cells.extend(carried);
        }
        self.cursor = newer.cursor;
        self.modes = newer.modes;
        self.title = newer.title;
        self.label = newer.label;
        self.right_click = newer.right_click;
        self.offset = newer.offset;
        self.exit = newer.exit;
    }
}

/// One frame on the wire: the viewer's metadata plus the panes that changed (or, when `full`,
/// every visible pane in full).
#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct FrameUpdate {
    /// Connection identity is required on full frames and inherited by ordinary deltas.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub viewer: Option<crate::ids::ViewerId>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub server_instance: Option<String>,
    pub workspace: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub workspace_stream: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub workspace_presentation: Option<WorkspacePresentation>,
    pub generation: u64,
    pub layout_generation: u64,
    pub zoomed: Option<PaneId>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tabs: Option<Vec<TabEntry>>,
    pub active_tab: Option<TabId>,
    pub focused: Option<PaneId>,
    pub layout: Vec<PaneRect>,
    #[serde(deserialize_with = "bounded_panes")]
    pub panes: BTreeMap<PaneId, PaneUpdate>,
    pub exit_code: Option<u32>,
    pub message: Option<String>,
    #[serde(default, skip_serializing_if = "is_false")]
    pub full: bool,
}

/// Deserializes the panes of one update while bounding their number and their wire cells in
/// total, so a hostile peer's 16 MiB frame cannot decode into more than the frame's cell budget.
fn bounded_panes<'de, D>(deserializer: D) -> Result<BTreeMap<PaneId, PaneUpdate>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    struct Panes;
    impl<'de> serde::de::Visitor<'de> for Panes {
        type Value = BTreeMap<PaneId, PaneUpdate>;
        fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
            write!(
                formatter,
                "at most {MAX_PANES} panes within {MAX_TOTAL_CELLS} wire cells"
            )
        }
        fn visit_map<A: serde::de::MapAccess<'de>>(
            self,
            mut map: A,
        ) -> Result<Self::Value, A::Error> {
            let mut panes = BTreeMap::new();
            let mut cells = 0_usize;
            while let Some((id, pane)) = map.next_entry::<PaneId, PaneUpdate>()? {
                cells = cells.saturating_add(pane.cells.len());
                if panes.len() >= MAX_PANES || cells > MAX_TOTAL_CELLS {
                    return Err(serde::de::Error::custom("frame update exceeds its bounds"));
                }
                panes.insert(id, pane);
            }
            Ok(panes)
        }
    }
    deserializer.deserialize_map(Panes)
}

impl FrameUpdate {
    /// Whether applying this update onto `held` stays within the documented bounds: pane counts,
    /// every pane's own bounds and the total cell budget after the update, checked before any
    /// pane is allocated.
    #[must_use]
    pub fn within_bounds(&self, held: &Frame) -> bool {
        if self
            .workspace_presentation
            .as_ref()
            .is_some_and(|presentation| !valid_workspace_label(presentation.label.as_deref()))
            || self.panes.len() > MAX_PANES
            || self
                .server_instance
                .as_ref()
                .is_some_and(|instance| instance.len() > 128)
            || self.viewer.is_some() != self.server_instance.is_some()
            || self.viewer.is_some() != self.workspace_stream.is_some()
            || self.workspace_stream == Some(0)
            || (self.full && (self.viewer.is_none() || self.tabs.is_none()))
            || self.layout.len() > MAX_PANES
            || self.tabs.as_ref().is_some_and(|tabs| tabs.len() > MAX_TABS)
        {
            return false;
        }
        // Only the panes the update leaves in the layout cost anything: carried ones at the
        // size they will have, held ones the update does not name at the size they have.
        let mut cells = 0_usize;
        for (id, pane) in &self.panes {
            if !pane.within_bounds() {
                return false;
            }
            if !self.shows(*id) {
                continue;
            }
            let size = match held.panes.get(id) {
                Some(view) if !pane.full && !self.full => view.cells.len(),
                _ => usize::from(pane.rows).saturating_mul(usize::from(pane.columns)),
            };
            cells = cells.saturating_add(size);
        }
        if !self.full {
            cells = held
                .panes
                .iter()
                .filter(|(id, _)| !self.panes.contains_key(id) && self.shows(**id))
                .fold(cells, |sum, (_, view)| sum.saturating_add(view.cells.len()));
        }
        cells <= MAX_TOTAL_CELLS
    }

    fn shows(&self, pane: PaneId) -> bool {
        self.layout.iter().any(|entry| entry.pane == pane)
    }

    /// Folds a later update into this one so that applying the result equals applying both in
    /// order: later metadata wins, later rows replace earlier rows, untouched panes stay.
    pub fn merge(&mut self, newer: Self) {
        if newer.full {
            *self = newer;
            return;
        }
        // A pane the newer update's layout no longer shows is dropped on apply, so carrying it
        // would only cost memory.
        self.panes
            .retain(|id, _| newer.layout.iter().any(|entry| entry.pane == *id));
        for (id, pane) in newer.panes {
            match self.panes.get_mut(&id) {
                Some(existing) => existing.merge(pane),
                None => {
                    self.panes.insert(id, pane);
                }
            }
        }
        if newer.viewer.is_some() {
            self.viewer = newer.viewer;
        }
        if newer.server_instance.is_some() {
            self.server_instance = newer.server_instance;
        }
        self.workspace = newer.workspace;
        if newer.workspace_presentation.is_some() {
            self.workspace_presentation = newer.workspace_presentation;
        }
        if newer.workspace_stream.is_some() {
            self.workspace_stream = newer.workspace_stream;
        }
        self.generation = newer.generation;
        self.layout_generation = newer.layout_generation;
        self.zoomed = newer.zoomed;
        if newer.tabs.is_some() {
            self.tabs = newer.tabs;
        }
        self.active_tab = newer.active_tab;
        self.focused = newer.focused;
        self.layout = newer.layout;
        self.exit_code = newer.exit_code;
        if newer.message.is_some() {
            self.message = newer.message;
        }
    }
}

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

    fn styled(foreground: Color, background: Color, attributes: u8) -> CellStyle {
        CellStyle::try_from(WireStyle(foreground, background, attributes)).expect("known bits")
    }

    #[test]
    fn styles_travel_as_compact_arrays_and_round_trip() {
        let style = styled(
            Color::Indexed(1),
            Color::Rgb(0, 128, 255),
            ATTR_BOLD | ATTR_INVERSE,
        );
        let json = serde_json::to_string(&style).expect("encode");
        assert_eq!(json, "[1,[0,128,255],17]");
        assert_eq!(
            serde_json::from_str::<CellStyle>(&json).expect("decode"),
            style
        );
        assert_eq!(
            serde_json::to_string(&CellStyle::default()).expect("encode"),
            "[null,null,0]"
        );
        let cell = WireCell {
            text: Some("".into()),
            kind: Some(CellKind::WideLeading),
            style: styled(Color::Indexed(1), Color::Default, ATTR_BOLD),
            run: 0,
        };
        assert_eq!(
            serde_json::to_string(&cell).expect("encode"),
            r#"{"text":"日","kind":"wide-leading","style":[1,null,1]}"#
        );
    }

    #[test]
    fn unknown_style_bits_are_rejected() {
        let error = serde_json::from_str::<CellStyle>("[null,null,32]").expect_err("bit 5");
        assert!(
            error.to_string().contains("unknown style attribute bits"),
            "{error}"
        );
        assert!(serde_json::from_str::<CellStyle>("[null,null]").is_err());
        assert!(serde_json::from_str::<CellStyle>(r#"{"foreground":null}"#).is_err());
    }

    fn encoded(value: &impl Serialize) -> usize {
        serde_json::to_vec(value).expect("encode").len()
    }

    #[test]
    fn encoded_len_matches_serde_json_exactly() {
        let colors = [
            Color::Default,
            Color::Indexed(0),
            Color::Indexed(9),
            Color::Indexed(10),
            Color::Indexed(255),
            Color::Rgb(0, 100, 7),
            Color::Rgb(255, 255, 255),
        ];
        let texts = [
            "",
            "a",
            "",
            "\"",
            "\\",
            "\n",
            "\u{1}",
            "é",
            "tab\there",
            "\u{7f}",
        ];
        let kinds = [
            None,
            Some(CellKind::WideLeading),
            Some(CellKind::WideContinuation),
        ];
        let runs = [
            0_u16,
            1,
            9,
            10,
            99,
            100,
            999,
            1_000,
            9_999,
            10_000,
            u16::MAX,
        ];
        let mut cells = Vec::new();
        for (index, &foreground) in colors.iter().enumerate() {
            for (offset, &background) in colors.iter().enumerate() {
                let attributes = u8::try_from((index * 7 + offset) % 32).expect("small");
                let style = styled(foreground, background, attributes);
                let text = texts
                    .get((index + offset) % texts.len())
                    .copied()
                    .unwrap_or("");
                let kind = kinds.get(index % kinds.len()).copied().flatten();
                let run = runs.get(offset % runs.len()).copied().unwrap_or(0);
                for cell in [
                    WireCell {
                        text: Some(text.into()),
                        kind,
                        style,
                        run: 0,
                    },
                    WireCell {
                        text: None,
                        kind,
                        style,
                        run,
                    },
                    WireCell {
                        text: None,
                        kind: None,
                        style,
                        run,
                    },
                    WireCell {
                        text: None,
                        kind: None,
                        style: CellStyle::default(),
                        run,
                    },
                ] {
                    assert_eq!(cell.encoded_len(), encoded(&cell), "{cell:?}");
                    cells.push(cell);
                }
            }
        }
        for (row, wrapped) in [(0_u16, false), (7, true), (10, false), (65_535, true)] {
            let line = crate::proto::control::CaptureLine {
                row,
                wrapped,
                cells: cells.clone(),
            };
            assert_eq!(line.encoded_len(), encoded(&line));
            let empty = crate::proto::control::CaptureLine {
                row,
                wrapped,
                cells: Vec::new(),
            };
            assert_eq!(empty.encoded_len(), encoded(&empty));
        }
    }

    #[test]
    fn workspace_labels_are_sparse_clearable_and_validated_before_apply() {
        let mut frame = Frame::default();
        let named = FrameUpdate {
            workspace_presentation: Some(WorkspacePresentation {
                label: Some("Build 界".into()),
            }),
            ..FrameUpdate::default()
        };
        assert!(frame.apply(named.clone()).is_ok());
        assert!(frame.apply(FrameUpdate::default()).is_ok());
        assert_eq!(frame.workspace_label.as_deref(), Some("Build 界"));
        let clear = FrameUpdate {
            workspace_presentation: Some(WorkspacePresentation { label: None }),
            ..FrameUpdate::default()
        };
        let mut merged = named;
        merged.merge(clear);
        merged.merge(FrameUpdate::default());
        assert!(frame.apply(merged).is_ok());
        assert_eq!(frame.workspace_label, None);
        for label in ["bad\nlabel".to_owned(), "x".repeat(129)] {
            let before = frame.clone();
            assert!(
                frame
                    .apply(FrameUpdate {
                        workspace_presentation: Some(WorkspacePresentation { label: Some(label) }),
                        ..FrameUpdate::default()
                    })
                    .is_err()
            );
            assert_eq!(frame, before);
        }
        frame.workspace_label = Some("old workspace".into());
        assert!(
            frame
                .apply(FrameUpdate {
                    full: true,
                    viewer: Some(crate::ids::ViewerId(1)),
                    server_instance: Some("instance".into()),
                    workspace_stream: Some(2),
                    tabs: Some(Vec::new()),
                    ..FrameUpdate::default()
                })
                .is_ok()
        );
        assert_eq!(frame.workspace_label, None);
    }

    #[test]
    fn pane_label_clearing_survives_coalescing_without_touching_application_title()
    -> Result<(), Box<dyn std::error::Error>> {
        let mut parser = vt100::Parser::new(2, 8, 0);
        parser.process(b"content");
        let mut full = PaneUpdate::full_from_screen(parser.screen(), "application", 0, None)?;
        full.label = Some("manual".into());
        let mut view = PaneView::from_update(&full)?;
        let clear = PaneUpdate {
            rows: 2,
            columns: 8,
            title: "new title".into(),
            ..PaneUpdate::default()
        };
        view.apply(&clear)?;
        full.merge(clear);
        assert_eq!(PaneView::from_update(&full)?, view);
        assert_eq!(view.label, None);
        assert_eq!(view.title, "new title");
        let before = view.clone();
        for label in ["x".repeat(MAX_LABEL_BYTES + 1), "bad\x1b".into()] {
            let invalid = PaneUpdate {
                label: Some(label),
                ..PaneUpdate::default()
            };
            assert!(!invalid.within_bounds());
            assert!(view.apply(&invalid).is_err());
            assert_eq!(view, before);
        }
        Ok(())
    }

    #[test]
    fn sparse_connection_identity_survives_wire_roundtrip_and_coalescing()
    -> Result<(), Box<dyn std::error::Error>> {
        let full = FrameUpdate {
            full: true,
            server_instance: Some("instance".into()),
            workspace_stream: Some(1),
            viewer: Some(crate::ids::ViewerId(7)),
            workspace: "default".into(),
            tabs: Some(vec![TabEntry {
                id: TabId(1),
                label: "main".into(),
                layout_generation: 5,
                first_pane: None,
            }]),
            generation: 1,
            ..FrameUpdate::default()
        };
        let delta = FrameUpdate {
            workspace: "default".into(),
            generation: 2,
            ..FrameUpdate::default()
        };
        let encoded = serde_json::to_value(&delta)?;
        assert!(encoded.get("viewer").is_none());
        assert!(encoded.get("server_instance").is_none());
        assert!(encoded.get("tabs").is_none());
        assert!(encoded.get("workspace_stream").is_none());
        let delta: FrameUpdate = serde_json::from_value(encoded)?;
        let mut direct = Frame::default();
        direct.apply(full.clone())?;
        direct.apply(delta.clone())?;
        assert_eq!(direct.viewer, crate::ids::ViewerId(7));
        assert_eq!(direct.server_instance, "instance");
        assert_eq!(direct.workspace_stream, 1);
        assert_eq!(direct.tabs.len(), 1);
        let mut merged = full;
        merged.merge(delta);
        let mut coalesced = Frame::default();
        coalesced.apply(merged)?;
        assert_eq!(coalesced, direct);
        let clear = FrameUpdate {
            tabs: Some(Vec::new()),
            workspace: "default".into(),
            generation: 3,
            ..FrameUpdate::default()
        };
        let mut compacted = clear.clone();
        compacted.merge(FrameUpdate {
            workspace: "default".into(),
            generation: 4,
            ..FrameUpdate::default()
        });
        direct.apply(compacted)?;
        assert!(
            direct.tabs.is_empty(),
            "an explicit empty catalog survives a later omitted catalog"
        );
        let before = direct.clone();
        for stream in [None, Some(0)] {
            assert!(
                direct
                    .apply(FrameUpdate {
                        full: true,
                        viewer: Some(crate::ids::ViewerId(7)),
                        server_instance: Some("instance".into()),
                        workspace_stream: stream,
                        tabs: Some(Vec::new()),
                        ..FrameUpdate::default()
                    })
                    .is_err()
            );
            assert_eq!(direct, before);
        }
        assert!(
            direct
                .apply(FrameUpdate {
                    full: true,
                    ..FrameUpdate::default()
                })
                .is_err()
        );
        assert_eq!(direct, before);
        assert!(
            direct
                .apply(FrameUpdate {
                    full: true,
                    viewer: Some(crate::ids::ViewerId(7)),
                    server_instance: Some("instance".into()),
                    workspace_stream: Some(1),
                    ..FrameUpdate::default()
                })
                .is_err()
        );
        assert_eq!(direct, before);
        assert!(
            direct
                .apply(FrameUpdate {
                    viewer: Some(crate::ids::ViewerId(9)),
                    ..FrameUpdate::default()
                })
                .is_err()
        );
        assert_eq!(direct, before);
        let replacement = FrameUpdate {
            full: true,
            viewer: Some(crate::ids::ViewerId(9)),
            server_instance: Some("replacement".into()),
            workspace_stream: Some(2),
            tabs: Some(Vec::new()),
            ..FrameUpdate::default()
        };
        direct.apply(replacement)?;
        assert_eq!(direct.viewer, crate::ids::ViewerId(9));
        assert_eq!(direct.server_instance, "replacement");
        assert_eq!(direct.workspace_stream, 2);
        assert!(direct.tabs.is_empty());
        Ok(())
    }

    #[test]
    fn coalesced_updates_keep_latest_layout_revision_and_zoom() {
        let mut queued = FrameUpdate::default();
        queued.merge(FrameUpdate {
            server_instance: Some("observed-instance".into()),
            workspace_stream: Some(1),
            viewer: Some(crate::ids::ViewerId(7)),
            layout_generation: 4,
            zoomed: Some(PaneId(7)),
            ..FrameUpdate::default()
        });
        assert_eq!(queued.layout_generation, 4);
        assert_eq!(queued.server_instance.as_deref(), Some("observed-instance"));
        assert_eq!(queued.viewer, Some(crate::ids::ViewerId(7)));
        assert_eq!(queued.zoomed, Some(PaneId(7)));
        queued.merge(FrameUpdate {
            layout_generation: 5,
            zoomed: None,
            ..FrameUpdate::default()
        });
        assert_eq!(queued.layout_generation, 5);
        assert_eq!(queued.zoomed, None);
    }

    #[test]
    fn full_updates_round_trip_to_the_screen_view() {
        let mut parser = vt100::Parser::new(3, 8, 0);
        parser.process("e\u{301}界x\x1b[1;31mred\r\n  wrap".as_bytes());
        let update =
            PaneUpdate::full_from_screen(parser.screen(), "t", 2, Some(1)).unwrap_or_default();
        let rebuilt = PaneView::from_update(&update).unwrap_or_default();
        assert_eq!(rebuilt.rows, 3);
        assert_eq!(rebuilt.title, "t");
        assert_eq!(rebuilt.exit, Some(1));
        let json = serde_json::to_string(&update).unwrap_or_default();
        let parsed: PaneUpdate = serde_json::from_str(&json).unwrap_or_default();
        assert_eq!(parsed, update);
        assert!(json.contains("\"run\":"), "blank runs are compact: {json}");
    }

    #[test]
    fn hostile_updates_are_rejected_before_anything_is_allocated() {
        let huge = PaneUpdate {
            rows: u16::MAX,
            columns: u16::MAX,
            full: true,
            ..PaneUpdate::default()
        };
        assert!(PaneView::from_update(&huge).is_err());
        let shown = |ids: std::ops::RangeInclusive<u32>| -> Vec<PaneRect> {
            ids.map(|id| PaneRect {
                pane: PaneId(id),
                rect: Rect::default(),
            })
            .collect()
        };
        let mut frame = Frame::default();
        let mut update = FrameUpdate {
            layout: shown(1..=1),
            ..FrameUpdate::default()
        };
        update.panes.insert(PaneId(1), huge);
        assert!(frame.apply(update).is_err());
        // Legal panes whose total exceeds the frame budget are refused as a whole.
        let mut update = FrameUpdate {
            layout: shown(1..=8),
            ..FrameUpdate::default()
        };
        for id in 1..=8 {
            update.panes.insert(
                PaneId(id),
                PaneUpdate {
                    rows: MAX_DIM,
                    columns: MAX_DIM,
                    full: true,
                    ..PaneUpdate::default()
                },
            );
        }
        assert!(!update.within_bounds(&frame));
        // The wire itself is bounded: more carried lines than a pane can have are refused while
        // decoding, before the update is looked at.
        let oversized = PaneUpdate {
            rows: 1,
            columns: 1,
            full: true,
            lines: vec![Line::default(); usize::from(MAX_DIM) + 1],
            ..PaneUpdate::default()
        };
        let json = serde_json::to_string(&oversized).unwrap_or_default();
        assert!(json.contains("\"lines\""));
        assert!(serde_json::from_str::<PaneUpdate>(&json).is_err());
        let fitting = PaneUpdate {
            lines: vec![Line::default(); usize::from(MAX_DIM)],
            ..oversized
        };
        let json = serde_json::to_string(&fitting).unwrap_or_default();
        assert!(
            serde_json::from_str::<PaneUpdate>(&json).is_ok(),
            "decodes; rejected later"
        );
    }

    #[test]
    fn a_large_viewer_switches_tabs_within_the_cell_budget() {
        let big = || PaneUpdate {
            rows: MAX_DIM,
            columns: MAX_DIM,
            full: true,
            lines: (0..MAX_DIM)
                .map(|row| Line {
                    row,
                    wrapped: false,
                    len: 1,
                })
                .collect(),
            cells: vec![
                WireCell {
                    run: MAX_DIM,
                    ..WireCell::default()
                };
                usize::from(MAX_DIM)
            ],
            ..PaneUpdate::default()
        };
        let switch = |id: u32| {
            let mut update = FrameUpdate {
                layout: vec![PaneRect {
                    pane: PaneId(id),
                    rect: Rect {
                        x: 0,
                        y: 0,
                        width: MAX_DIM,
                        height: MAX_DIM,
                    },
                }],
                ..FrameUpdate::default()
            };
            update.panes.insert(PaneId(id), big());
            update
        };
        // Attach, then switch to a tab whose pane fills the whole budget on its own.
        let mut frame = Frame::default();
        assert!(frame.apply(switch(1)).is_ok());
        assert!(
            frame.apply(switch(2)).is_ok(),
            "the left pane does not count"
        );
        assert_eq!(frame.panes.len(), 1);
        // Several switches merged while the viewer was not reading apply as one.
        let mut merged = switch(3);
        merged.merge(switch(4));
        merged.merge(switch(5));
        assert_eq!(
            merged.panes.len(),
            1,
            "panes that left the layout are pruned"
        );
        assert!(frame.apply(merged).is_ok());
        assert!(frame.panes.contains_key(&PaneId(5)));
        // The wire bound: 129 panes, or more wire cells than the budget, are refused at decoding.
        let mut update = FrameUpdate::default();
        for id in 1..=129 {
            update.panes.insert(PaneId(id), PaneUpdate::default());
        }
        let json = serde_json::to_string(&update).unwrap_or_default();
        assert!(serde_json::from_str::<FrameUpdate>(&json).is_err());
    }

    #[test]
    fn vt100_conversion_keeps_combining_text_and_wide_cells() {
        let mut parser = vt100::Parser::new(2, 6, 0);
        parser.process("e\u{301}界x".as_bytes());
        let view = PaneView::from_screen(parser.screen(), "", 0, None).unwrap_or_default();
        assert_eq!(
            view.cell(0, 0).map(|cell| cell.text.as_str()),
            Some("e\u{301}")
        );
        assert_eq!(
            view.cell(0, 1).map(|cell| cell.kind),
            Some(CellKind::WideLeading)
        );
        assert_eq!(
            view.cell(0, 2).map(|cell| cell.kind),
            Some(CellKind::WideContinuation)
        );
        assert_eq!(view.text_between((0, 0), (0, 5)), "e\u{301}界x");
    }

    #[test]
    fn cells_reject_terminal_controls_and_multiple_clusters() {
        for text in ["\u{1b}[2J", "\n", "ab", "a\u{85}", ""] {
            let cell = Cell {
                text: text.to_owned(),
                kind: CellKind::Text,
                style: CellStyle::default(),
            };
            assert!(!cell.valid(), "accepted unsafe cell {text:?}");
        }
        for text in ["🇰🇷", ""] {
            assert!(
                Cell {
                    text: text.to_owned(),
                    kind: CellKind::WideLeading,
                    style: CellStyle::default(),
                }
                .valid()
            );
        }
    }

    #[test]
    fn wrapped_rows_join_and_blank_tails_are_trimmed() {
        let mut parser = vt100::Parser::new(3, 4, 0);
        parser.process(b"abcdef\r\nxy");
        let view = PaneView::from_screen(parser.screen(), "", 0, None).unwrap_or_default();
        assert_eq!(view.text_between((0, 0), (2, 3)), "abcdef\nxy");
        assert_eq!(view.text_between((2, 3), (1, 0)), "ef\nxy");
    }

    #[test]
    fn frame_validation_rejects_dangling_references() {
        let mut frame = Frame::default();
        frame.layout.push(PaneRect {
            pane: PaneId(7),
            rect: Rect::default(),
        });
        assert!(!frame.valid());
        frame.layout.clear();
        frame.focused = Some(PaneId(1));
        assert!(!frame.valid());
        frame.focused = None;
        frame.active_tab = Some(TabId(3));
        assert!(!frame.valid());
        frame.active_tab = None;
        assert!(frame.valid());
        let oversized = PaneView {
            rows: u16::MAX,
            columns: u16::MAX,
            ..PaneView::default()
        };
        frame.panes.insert(PaneId(1), oversized);
        assert!(!frame.valid());
    }
}