compose-rust 0.0.10

Declarative UI in Rust, rendered by an AOT-compiled Compose Multiplatform engine.
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
//! A code editor's document as the Host sees it.
//!
//! The Renderer owns the text. It owns the caret, the selection, the scroll position, the
//! undo history and the composition an input method is building, for the same reason a
//! text field owns them: a round trip to this side per keystroke would add a frame of
//! latency to every key. What the Host gets is each committed edit, in order, with the
//! version of the document it produced, which is exactly what a language server or an
//! extension host needs to follow along.
//!
//! What the Host says back is said as ranges. Colour runs for the syntax and decorations
//! for diagnostics, lenses, hover anchors and inline suggestions, each a blob of
//! fixed-length records carrying the document version its ranges were written against.
//! The Renderer moves them along with whatever the reader typed since, so a list that took
//! a language server a second to compute still lands on the text it was about.
//!
//! Positions are a line and a column counted from zero, and a column counts UTF-16 code
//! units. That is the unit a language server and VS Code count in, and any other unit
//! would make every application recount every range on the way through. A line ends at
//! `\n`, `\r\n` or a lone `\r`, which is also the language server's rule.

use crate::schema::{
    ColorRole, DecorationKind, EditGroupStatus, GutterDecorationKind, HoverPhase, Paint, Severity,
};
use std::rc::Rc;

/// Bytes of one decoration record.
pub const DECORATION_LEN: usize = 44;

/// Bytes of one syntax colour run record.
pub const SYNTAX_SPAN_LEN: usize = 28;

/// Bytes of one edit record inside a grouped edit: the range as four `u32`, then the
/// text's `(offset, length)`.
pub const CODE_EDIT_LEN: usize = 24;

/// What one field of a code editor record holds.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum RecordFieldType {
    U32,
    U64,
    /// A role tag in a `u16`. `optional` says that zero means "not given" rather than a
    /// broken record.
    Role {
        name: &'static str,
        optional: bool,
    },
    /// A `Paint` in a `u64`.
    Paint,
    /// A `u32` that is 0 or 1. Any other value makes the record unreadable.
    Flag,
    /// An `f32`, little-endian like every other field.
    F32,
    /// An `(offset, length)` pair of `u32` naming UTF-8 bytes behind the records, measured
    /// from the start of the blob, the way a `Canvas` names the text it draws.
    Text,
}

/// One field of a fixed-length record, at the byte it starts at.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct RecordField {
    pub name: &'static str,
    pub offset: u16,
    pub ty: RecordFieldType,
}

/// A fixed-length record that travels inside a property's blob.
///
/// Codegen writes the Renderer's decoder from this, so the two sides read the same bytes
/// at the same offsets and nobody keeps a second copy of the layout by hand.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct RecordSchema {
    /// The Kotlin class the decoder produces.
    pub name: &'static str,
    pub length: u16,
    pub fields: &'static [RecordField],
}

const fn field(name: &'static str, offset: u16, ty: RecordFieldType) -> RecordField {
    RecordField { name, offset, ty }
}

/// One decoration: a version, a kind, a severity and a colour role, a range, the id the
/// application gave it, and the text a lens or a suggestion shows. Bytes 10 and 11 are
/// reserved and written as zero.
pub const DECORATION_RECORD: RecordSchema = RecordSchema {
    name: "DecorationRecord",
    length: DECORATION_LEN as u16,
    fields: &[
        field("version", 0, RecordFieldType::U32),
        field(
            "kind",
            4,
            RecordFieldType::Role {
                name: "DecorationKind",
                optional: false,
            },
        ),
        field(
            "severity",
            6,
            RecordFieldType::Role {
                name: "Severity",
                optional: true,
            },
        ),
        field(
            "color",
            8,
            RecordFieldType::Role {
                name: "ColorRole",
                optional: true,
            },
        ),
        field("startLine", 12, RecordFieldType::U32),
        field("startColumn", 16, RecordFieldType::U32),
        field("endLine", 20, RecordFieldType::U32),
        field("endColumn", 24, RecordFieldType::U32),
        field("id", 28, RecordFieldType::U64),
        field("text", 36, RecordFieldType::Text),
    ],
};

/// One colour run of the syntax: a version, a range and the paint it is drawn in.
pub const SYNTAX_SPAN_RECORD: RecordSchema = RecordSchema {
    name: "SyntaxSpanRecord",
    length: SYNTAX_SPAN_LEN as u16,
    fields: &[
        field("version", 0, RecordFieldType::U32),
        field("startLine", 4, RecordFieldType::U32),
        field("startColumn", 8, RecordFieldType::U32),
        field("endLine", 12, RecordFieldType::U32),
        field("endColumn", 16, RecordFieldType::U32),
        field("paint", 20, RecordFieldType::Paint),
    ],
};

/// Bytes of one fold record.
pub const FOLD_LEN: usize = 16;

/// Bytes of one gutter decoration record.
pub const GUTTER_DECORATION_LEN: usize = 28;

/// One stretch of lines that can be folded: a version, the line it starts on, the last line
/// it covers and whether it is folded now. Folding keeps `start_line` and hides the lines
/// after it up to `end_line`.
pub const FOLD_RECORD: RecordSchema = RecordSchema {
    name: "FoldRecord",
    length: FOLD_LEN as u16,
    fields: &[
        field("version", 0, RecordFieldType::U32),
        field("startLine", 4, RecordFieldType::U32),
        field("endLine", 8, RecordFieldType::U32),
        field("collapsed", 12, RecordFieldType::Flag),
    ],
};

/// One mark beside the line numbers: a version, the line, what it looks like, an optional
/// colour role, the id the application gave it and the character a glyph shows. Bytes 24
/// to 27 are reserved and written as zero.
pub const GUTTER_DECORATION_RECORD: RecordSchema = RecordSchema {
    name: "GutterDecorationRecord",
    length: GUTTER_DECORATION_LEN as u16,
    fields: &[
        field("version", 0, RecordFieldType::U32),
        field("line", 4, RecordFieldType::U32),
        field(
            "kind",
            8,
            RecordFieldType::Role {
                name: "GutterDecorationKind",
                optional: false,
            },
        ),
        field(
            "color",
            10,
            RecordFieldType::Role {
                name: "ColorRole",
                optional: true,
            },
        ),
        field("id", 12, RecordFieldType::U64),
        field("glyph", 20, RecordFieldType::U32),
    ],
};

/// Bytes of a code editor's colour record.
pub const CODE_EDITOR_COLORS_LEN: usize = 12;

const fn optional_color(name: &'static str, offset: u16) -> RecordField {
    field(
        name,
        offset,
        RecordFieldType::Role {
            name: "ColorRole",
            optional: true,
        },
    )
}

/// The colours an application gives an editor: a role for the container, the gutter, a
/// line number, the current line's number and the current line. Zero leaves that part to
/// the design system. Bytes 10 and 11 are reserved and written as zero.
pub const CODE_EDITOR_COLORS_RECORD: RecordSchema = RecordSchema {
    name: "CodeEditorColorsRecord",
    length: CODE_EDITOR_COLORS_LEN as u16,
    fields: &[
        optional_color("container", 0),
        optional_color("gutter", 2),
        optional_color("lineNumber", 4),
        optional_color("currentLineNumber", 6),
        optional_color("currentLine", 8),
    ],
};

/// Bytes of one view zone record.
pub const VIEW_ZONE_LEN: usize = 16;

/// One view zone: the line it follows, its height in rows and the text it shows dimmed, which
/// lies behind the records like a decoration's.
pub const VIEW_ZONE_RECORD: RecordSchema = RecordSchema {
    name: "ViewZoneRecord",
    length: VIEW_ZONE_LEN as u16,
    fields: &[
        field("afterLine", 0, RecordFieldType::U32),
        field("heightLines", 4, RecordFieldType::F32),
        field("text", 8, RecordFieldType::Text),
    ],
};

const fn hash_bytes(mut hash: u64, bytes: &[u8]) -> u64 {
    let mut index = 0;
    while index < bytes.len() {
        hash ^= bytes[index] as u64;
        hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
        index += 1;
    }
    hash
}

/// Folds a record layout into the schema hash, so a Renderer built against another
/// layout is refused at the handshake rather than reading the wrong bytes.
pub(crate) const fn hash_record_schema(mut hash: u64, schema: RecordSchema) -> u64 {
    hash = hash_bytes(hash, schema.name.as_bytes());
    hash = hash_bytes(hash, &schema.length.to_le_bytes());
    let mut index = 0;
    while index < schema.fields.len() {
        let field = schema.fields[index];
        hash = hash_bytes(hash, field.name.as_bytes());
        hash = hash_bytes(hash, &field.offset.to_le_bytes());
        hash = match field.ty {
            RecordFieldType::U32 => hash_bytes(hash, &[1]),
            RecordFieldType::U64 => hash_bytes(hash, &[2]),
            RecordFieldType::Role { name, optional } => {
                let hash = hash_bytes(hash, &[3, optional as u8]);
                hash_bytes(hash, name.as_bytes())
            }
            RecordFieldType::Paint => hash_bytes(hash, &[4]),
            RecordFieldType::Text => hash_bytes(hash, &[5]),
            RecordFieldType::Flag => hash_bytes(hash, &[6]),
            RecordFieldType::F32 => hash_bytes(hash, &[7]),
        };
        index += 1;
    }
    hash
}

/// A place in the document: a line and a column, both from zero, the column in UTF-16
/// code units.
#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct Position {
    pub line: u32,
    pub column: u32,
}

impl Position {
    pub const fn new(line: u32, column: u32) -> Self {
        Self { line, column }
    }
}

/// A stretch of the document from `start` up to, and not including, `end`.
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
pub struct CodeRange {
    pub start: Position,
    pub end: Position,
}

impl CodeRange {
    pub const fn new(start: Position, end: Position) -> Self {
        Self { start, end }
    }

    /// The empty range at one place, which is where an insertion goes.
    pub const fn at(position: Position) -> Self {
        Self {
            start: position,
            end: position,
        }
    }

    /// A range given as four numbers, in the order a language server writes them.
    pub const fn of(start_line: u32, start_column: u32, end_line: u32, end_column: u32) -> Self {
        Self {
            start: Position::new(start_line, start_column),
            end: Position::new(end_line, end_column),
        }
    }

    pub fn is_empty(&self) -> bool {
        self.start == self.end
    }
}

/// One thing drawn over the document, said as a range and never as a picture.
///
/// The colour of an underline is a role, never a literal, and is left to the design system
/// where it is not given; the shape of the mark, a squiggle or a line, and its weight are
/// always the design system's.
#[derive(Clone, Debug, PartialEq)]
pub struct Decoration {
    /// The document version the range was written against.
    pub version: u32,
    pub kind: DecorationKind,
    /// Only an underline has one.
    pub severity: Option<Severity>,
    /// The role an underline is drawn in. None leaves it to the design system, which picks
    /// one that suits the severity.
    pub color: Option<ColorRole>,
    pub range: CodeRange,
    /// The application's own name for this decoration, reported when it is pressed,
    /// accepted or hovered. Zero means it cannot be pressed and is never reported.
    pub id: u64,
    /// What a lens or a suggestion shows. Empty for the other two kinds.
    pub text: String,
}

impl Decoration {
    /// A diagnostic mark under a range.
    pub fn underline(version: u32, range: CodeRange, severity: Severity) -> Self {
        Self {
            version,
            kind: DecorationKind::Underline,
            severity: Some(severity),
            color: None,
            range,
            id: 0,
            text: String::new(),
        }
    }

    /// A short line of text shown above `line`, which reports `id` when pressed.
    pub fn code_lens(version: u32, line: u32, text: impl Into<String>, id: u64) -> Self {
        Self {
            version,
            kind: DecorationKind::CodeLens,
            severity: None,
            color: None,
            range: CodeRange::at(Position::new(line, 0)),
            id,
            text: text.into(),
        }
    }

    /// A range that reports `id` when a pointer comes to rest over it.
    pub fn hover_anchor(version: u32, range: CodeRange, id: u64) -> Self {
        Self {
            version,
            kind: DecorationKind::HoverAnchor,
            severity: None,
            color: None,
            range,
            id,
            text: String::new(),
        }
    }

    /// A suggestion shown faintly at `at`. Accepting it inserts `text` there as an
    /// ordinary edit and then reports `id`.
    pub fn ghost_text(version: u32, at: Position, text: impl Into<String>, id: u64) -> Self {
        Self {
            version,
            kind: DecorationKind::GhostText,
            severity: None,
            color: None,
            range: CodeRange::at(at),
            id,
            text: text.into(),
        }
    }

    /// A tint across lines `line_start` to `line_end`, both included, the whole width of the
    /// editor and past the end of each line. `color` is a role such as `DiffAdded`,
    /// `DiffRemoved` or `DiffModified`, and the design system decides how strong the tint
    /// of each is. The lines follow the reader's edits like every other decoration.
    pub fn line_background(version: u32, line_start: u32, line_end: u32, color: ColorRole) -> Self {
        Self {
            version,
            kind: DecorationKind::LineBackground,
            severity: None,
            color: Some(color),
            range: CodeRange::of(line_start, 0, line_end, 0),
            id: 0,
            text: String::new(),
        }
    }

    /// A tint over the characters of `range`, stronger than a line background in the same
    /// role, for the part of a changed line that changed.
    pub fn range_background(version: u32, range: CodeRange, color: ColorRole) -> Self {
        Self {
            version,
            kind: DecorationKind::RangeBackground,
            severity: None,
            color: Some(color),
            range,
            id: 0,
            text: String::new(),
        }
    }

    /// Draws an underline in this role rather than the one the design system would pick.
    pub fn with_color(mut self, role: ColorRole) -> Self {
        self.color = Some(role);
        self
    }

    pub fn with_id(mut self, id: u64) -> Self {
        self.id = id;
        self
    }
}

fn put_u16(out: &mut Vec<u8>, value: u16) {
    out.extend_from_slice(&value.to_le_bytes());
}

fn put_u32(out: &mut Vec<u8>, value: u32) {
    out.extend_from_slice(&value.to_le_bytes());
}

fn put_u64(out: &mut Vec<u8>, value: u64) {
    out.extend_from_slice(&value.to_le_bytes());
}

fn put_range(out: &mut Vec<u8>, range: CodeRange) {
    put_u32(out, range.start.line);
    put_u32(out, range.start.column);
    put_u32(out, range.end.line);
    put_u32(out, range.end.column);
}

fn word(record: &[u8], at: usize) -> u32 {
    u32::from_le_bytes([record[at], record[at + 1], record[at + 2], record[at + 3]])
}

fn half(record: &[u8], at: usize) -> u16 {
    u16::from_le_bytes([record[at], record[at + 1]])
}

fn long(record: &[u8], at: usize) -> u64 {
    u64::from(word(record, at)) | (u64::from(word(record, at + 4)) << 32)
}

fn range_at(record: &[u8], at: usize) -> CodeRange {
    CodeRange::of(
        word(record, at),
        word(record, at + 4),
        word(record, at + 8),
        word(record, at + 12),
    )
}

/// The decorations over one editor, encoded and ready to travel.
///
/// Records first and the text they show after them, so the records stay fixed-length.
/// Shared rather than copied, so the same list given again compares equal and costs no
/// record at all.
#[derive(Clone, Default, PartialEq)]
pub struct Decorations {
    bytes: Option<Rc<[u8]>>,
}

impl std::fmt::Debug for Decorations {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("Decorations")
            .field("decorations", &self.decorations().len())
            .finish()
    }
}

impl Decorations {
    pub fn new(decorations: impl IntoIterator<Item = Decoration>) -> Self {
        let decorations: Vec<Decoration> = decorations.into_iter().collect();
        let records_len = decorations.len() * DECORATION_LEN;
        let mut bytes = Vec::with_capacity(records_len);
        let mut texts = Vec::new();
        for decoration in &decorations {
            put_u32(&mut bytes, decoration.version);
            put_u16(&mut bytes, decoration.kind as u16);
            put_u16(
                &mut bytes,
                decoration.severity.map_or(0, |value| value as u16),
            );
            put_u16(&mut bytes, decoration.color.map_or(0, |value| value as u16));
            put_u16(&mut bytes, 0);
            put_range(&mut bytes, decoration.range);
            put_u64(&mut bytes, decoration.id);
            // An empty text points at the end of the records, which is where the text
            // region starts, so a reader never sees an offset into the records themselves.
            put_u32(&mut bytes, (records_len + texts.len()) as u32);
            put_u32(&mut bytes, decoration.text.len() as u32);
            texts.extend_from_slice(decoration.text.as_bytes());
        }
        bytes.extend_from_slice(&texts);
        Self::from_bytes(bytes)
    }

    /// Adopts an already encoded list, which is what the protocol vectors carry.
    pub fn from_bytes(bytes: impl Into<Rc<[u8]>>) -> Self {
        let bytes = bytes.into();
        Self {
            bytes: (!bytes.is_empty()).then_some(bytes),
        }
    }

    pub fn as_bytes(&self) -> &[u8] {
        self.bytes.as_deref().unwrap_or(&[])
    }

    pub fn is_empty(&self) -> bool {
        self.bytes.is_none()
    }

    /// The decorations this list holds, read back.
    ///
    /// The records end where the text region begins, which is the first offset any record
    /// names for its text, or the end of the blob where none names one. A record whose
    /// kind, severity or colour is not one this side knows is skipped, which is what the
    /// Renderer does with it too.
    pub fn decorations(&self) -> Vec<Decoration> {
        let bytes = self.as_bytes();
        let mut end = bytes.len();
        let mut at = 0;
        let mut found = Vec::new();
        while at + DECORATION_LEN <= end {
            let record = &bytes[at..at + DECORATION_LEN];
            at += DECORATION_LEN;
            let text_offset = word(record, 36) as usize;
            let text_len = word(record, 40) as usize;
            if text_len > 0 {
                end = end.min(text_offset);
            }
            let Ok(kind) = DecorationKind::try_from(half(record, 4)) else {
                continue;
            };
            let severity = match half(record, 6) {
                0 => None,
                tag => match Severity::try_from(tag) {
                    Ok(severity) => Some(severity),
                    Err(()) => continue,
                },
            };
            let color = match half(record, 8) {
                0 => None,
                tag => match ColorRole::try_from(tag) {
                    Ok(role) => Some(role),
                    Err(()) => continue,
                },
            };
            let text = if text_len == 0 {
                String::new()
            } else {
                match bytes
                    .get(text_offset..text_offset + text_len)
                    .and_then(|run| std::str::from_utf8(run).ok())
                {
                    Some(text) => text.to_owned(),
                    None => continue,
                }
            };
            found.push(Decoration {
                version: word(record, 0),
                kind,
                severity,
                color,
                range: range_at(record, 12),
                id: long(record, 28),
                text,
            });
        }
        found
    }
}

/// One colour run of the syntax.
///
/// A paint rather than a colour, and in practice a role: the code colour roles are what a
/// highlighter on this side maps its token kinds onto, so the same run comes out in the
/// right colour under every design system and in both light and dark.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct SyntaxSpan {
    pub version: u32,
    pub range: CodeRange,
    pub paint: Paint,
}

impl SyntaxSpan {
    pub const fn new(version: u32, range: CodeRange, paint: Paint) -> Self {
        Self {
            version,
            range,
            paint,
        }
    }

    /// A run drawn in one colour role.
    pub const fn role(version: u32, range: CodeRange, role: ColorRole) -> Self {
        Self::new(version, range, Paint::Role(role))
    }
}

/// The colour runs of one editor's syntax, encoded and ready to travel.
#[derive(Clone, Default, PartialEq)]
pub struct SyntaxSpans {
    bytes: Option<Rc<[u8]>>,
}

impl std::fmt::Debug for SyntaxSpans {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("SyntaxSpans")
            .field("spans", &(self.as_bytes().len() / SYNTAX_SPAN_LEN))
            .finish()
    }
}

impl SyntaxSpans {
    pub fn new(spans: impl IntoIterator<Item = SyntaxSpan>) -> Self {
        let mut bytes = Vec::new();
        for span in spans {
            put_u32(&mut bytes, span.version);
            put_range(&mut bytes, span.range);
            put_u64(&mut bytes, span.paint.to_bits());
        }
        Self::from_bytes(bytes)
    }

    pub fn from_bytes(bytes: impl Into<Rc<[u8]>>) -> Self {
        let bytes = bytes.into();
        Self {
            bytes: (!bytes.is_empty()).then_some(bytes),
        }
    }

    pub fn as_bytes(&self) -> &[u8] {
        self.bytes.as_deref().unwrap_or(&[])
    }

    pub fn is_empty(&self) -> bool {
        self.bytes.is_none()
    }

    /// The runs this list holds, read back. A run whose paint this side cannot read is
    /// skipped.
    pub fn spans(&self) -> Vec<SyntaxSpan> {
        self.as_bytes()
            .chunks_exact(SYNTAX_SPAN_LEN)
            .filter_map(|record| {
                Some(SyntaxSpan {
                    version: word(record, 0),
                    range: range_at(record, 4),
                    paint: Paint::from_bits(long(record, 20))?,
                })
            })
            .collect()
    }
}

/// Where a position falls in `text`, as a byte offset, or None where the document has no
/// such place: a line past the last one, a column past the end of its line, or a column
/// that would split a character written as two UTF-16 units.
pub fn byte_offset(text: &str, position: Position) -> Option<usize> {
    let bytes = text.as_bytes();
    let mut start = 0;
    for _ in 0..position.line {
        let at = bytes[start..]
            .iter()
            .position(|byte| *byte == b'\n' || *byte == b'\r')?
            + start;
        start = if bytes[at] == b'\r' && bytes.get(at + 1) == Some(&b'\n') {
            at + 2
        } else {
            at + 1
        };
    }
    let end = bytes[start..]
        .iter()
        .position(|byte| *byte == b'\n' || *byte == b'\r')
        .map_or(bytes.len(), |offset| start + offset);
    let mut units = 0_u32;
    let mut offset = start;
    for character in text[start..end].chars() {
        if units == position.column {
            return Some(offset);
        }
        units += character.len_utf16() as u32;
        offset += character.len_utf8();
        if units > position.column {
            return None;
        }
    }
    (units == position.column).then_some(offset)
}

/// One committed edit, as the Renderer reported it.
///
/// `range` is in the document as it stood before the edit, and `version` is the version
/// the edit produced. The shape is a language server's `TextDocumentContentChangeEvent`,
/// so forwarding one is a matter of copying four numbers and a string.
#[derive(Clone, Debug, PartialEq)]
pub struct CodeChange {
    pub version: u32,
    pub range: CodeRange,
    pub text: String,
}

impl CodeChange {
    /// Applies this edit to a copy of the document the Host keeps.
    ///
    /// Applying every change in the order they arrived, starting from the text the editor
    /// was opened with, gives the text the reader sees. Returns false, and leaves `text`
    /// alone, where the range does not fit the document, which means the copy has fallen
    /// out of step with the editor.
    pub fn apply_to(&self, text: &mut String) -> bool {
        let (Some(start), Some(end)) = (
            byte_offset(text, self.range.start),
            byte_offset(text, self.range.end),
        ) else {
            return false;
        };
        if start > end {
            return false;
        }
        text.replace_range(start..end, &self.text);
        true
    }
}

/// A Host edit the Renderer did not apply, because the reader had changed the same place
/// since the version the edit was written against.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct EditRejected {
    /// The id the application gave the edit.
    pub request_id: u32,
    pub base_version: u32,
    /// The version the document had reached when the edit arrived.
    pub current_version: u32,
    /// The range exactly as it was sent.
    pub range: CodeRange,
}

/// A pointer came to rest over a place in the editor, or left it.
///
/// How long it has to rest is the design system's, the same kind of delay a tooltip
/// waits, and nothing is sent again while it stays. What to show is the application's,
/// drawn with the overlay widgets it already has.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct CodeHover {
    /// The id of the hover anchor under the pointer, or None where there is none.
    pub decoration: Option<u64>,
    pub position: Position,
    pub phase: HoverPhase,
}

/// The reader pressed the save shortcut: Command S on macOS, Control S elsewhere.
///
/// Writing the file is this side's job, on a worker, never on the thread the editor runs
/// on.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct SaveRequest {
    /// The version of the document the reader saw when they pressed it.
    pub version: u32,
}

/// One stretch of lines the reader can fold.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Fold {
    /// The document version the lines were written against.
    pub version: u32,
    /// The line that stays when the stretch is folded.
    pub start_line: u32,
    /// The last line the fold hides. Folding hides the lines after `start_line` up to and
    /// including this one.
    pub end_line: u32,
    pub collapsed: bool,
}

impl Fold {
    /// A stretch from `start_line` to `end_line`, unfolded.
    pub const fn new(version: u32, start_line: u32, end_line: u32) -> Self {
        Self {
            version,
            start_line,
            end_line,
            collapsed: false,
        }
    }

    /// The same stretch, folded.
    pub const fn collapsed(mut self) -> Self {
        self.collapsed = true;
        self
    }
}

/// The stretches of one editor that can be folded, encoded and ready to travel.
#[derive(Clone, Default, PartialEq)]
pub struct Folds {
    bytes: Option<Rc<[u8]>>,
}

impl std::fmt::Debug for Folds {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("Folds")
            .field("folds", &(self.as_bytes().len() / FOLD_LEN))
            .finish()
    }
}

impl Folds {
    pub fn new(folds: impl IntoIterator<Item = Fold>) -> Self {
        let mut bytes = Vec::new();
        for fold in folds {
            put_u32(&mut bytes, fold.version);
            put_u32(&mut bytes, fold.start_line);
            put_u32(&mut bytes, fold.end_line);
            put_u32(&mut bytes, u32::from(fold.collapsed));
        }
        Self::from_bytes(bytes)
    }

    pub fn from_bytes(bytes: impl Into<Rc<[u8]>>) -> Self {
        let bytes = bytes.into();
        Self {
            bytes: (!bytes.is_empty()).then_some(bytes),
        }
    }

    pub fn as_bytes(&self) -> &[u8] {
        self.bytes.as_deref().unwrap_or(&[])
    }

    pub fn is_empty(&self) -> bool {
        self.bytes.is_none()
    }

    /// The folds this list holds, read back. A record whose collapsed word is neither 0
    /// nor 1 is skipped, which is what the Renderer does with it too.
    pub fn folds(&self) -> Vec<Fold> {
        self.as_bytes()
            .chunks_exact(FOLD_LEN)
            .filter_map(|record| {
                Some(Fold {
                    version: word(record, 0),
                    start_line: word(record, 4),
                    end_line: word(record, 8),
                    collapsed: match word(record, 12) {
                        0 => false,
                        1 => true,
                        _ => return None,
                    },
                })
            })
            .collect()
    }
}

/// One mark beside a line number, said as a line and never as a picture.
///
/// The colour is a role, never a literal, and is left to the design system where it is not
/// given. How big a dot is, how wide a bar and where each sits are always the design
/// system's.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct GutterDecoration {
    /// The document version the line was written against.
    pub version: u32,
    pub line: u32,
    pub kind: GutterDecorationKind,
    pub color: Option<ColorRole>,
    /// The application's own name for it, reported when it is pressed. Zero means it
    /// cannot be pressed.
    pub id: u64,
    /// The character a glyph shows, as a Unicode scalar value. Zero for the other kinds.
    pub glyph: u32,
}

impl GutterDecoration {
    /// A dot beside `line`.
    pub const fn dot(version: u32, line: u32, id: u64) -> Self {
        Self {
            version,
            line,
            kind: GutterDecorationKind::Dot,
            color: None,
            id,
            glyph: 0,
        }
    }

    /// A bar the height of `line`.
    pub const fn bar(version: u32, line: u32, id: u64) -> Self {
        Self {
            version,
            line,
            kind: GutterDecorationKind::Bar,
            color: None,
            id,
            glyph: 0,
        }
    }

    /// One character beside `line`.
    pub const fn glyph(version: u32, line: u32, glyph: char, id: u64) -> Self {
        Self {
            version,
            line,
            kind: GutterDecorationKind::Glyph,
            color: None,
            id,
            glyph: glyph as u32,
        }
    }

    /// Draws the mark in this role rather than the one the design system would pick.
    pub const fn with_color(mut self, role: ColorRole) -> Self {
        self.color = Some(role);
        self
    }

    pub const fn with_id(mut self, id: u64) -> Self {
        self.id = id;
        self
    }
}

/// The marks beside the line numbers of one editor, encoded and ready to travel.
#[derive(Clone, Default, PartialEq)]
pub struct GutterDecorations {
    bytes: Option<Rc<[u8]>>,
}

impl std::fmt::Debug for GutterDecorations {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("GutterDecorations")
            .field(
                "decorations",
                &(self.as_bytes().len() / GUTTER_DECORATION_LEN),
            )
            .finish()
    }
}

impl GutterDecorations {
    pub fn new(decorations: impl IntoIterator<Item = GutterDecoration>) -> Self {
        let mut bytes = Vec::new();
        for decoration in decorations {
            put_u32(&mut bytes, decoration.version);
            put_u32(&mut bytes, decoration.line);
            put_u16(&mut bytes, decoration.kind as u16);
            put_u16(&mut bytes, decoration.color.map_or(0, |value| value as u16));
            put_u64(&mut bytes, decoration.id);
            put_u32(&mut bytes, decoration.glyph);
            put_u32(&mut bytes, 0);
        }
        Self::from_bytes(bytes)
    }

    pub fn from_bytes(bytes: impl Into<Rc<[u8]>>) -> Self {
        let bytes = bytes.into();
        Self {
            bytes: (!bytes.is_empty()).then_some(bytes),
        }
    }

    pub fn as_bytes(&self) -> &[u8] {
        self.bytes.as_deref().unwrap_or(&[])
    }

    pub fn is_empty(&self) -> bool {
        self.bytes.is_none()
    }

    /// The marks this list holds, read back. A record whose kind or colour this side does
    /// not know is skipped, which is what the Renderer does with it too.
    pub fn decorations(&self) -> Vec<GutterDecoration> {
        self.as_bytes()
            .chunks_exact(GUTTER_DECORATION_LEN)
            .filter_map(|record| {
                let kind = GutterDecorationKind::try_from(half(record, 8)).ok()?;
                let color = match half(record, 10) {
                    0 => None,
                    tag => Some(ColorRole::try_from(tag).ok()?),
                };
                Some(GutterDecoration {
                    version: word(record, 0),
                    line: word(record, 4),
                    kind,
                    color,
                    id: long(record, 12),
                    glyph: word(record, 20),
                })
            })
            .collect()
    }
}

/// Room after a line that is not text: the blank rows a diff leaves on one side to line it up
/// with the other, or a note between two lines.
///
/// `after_line` is the line it follows in the document as it is when the list arrives, from
/// zero. The zone then follows that line through the reader's edits. `height_lines` is how
/// tall it is in rows, and need not be whole. The caret, a selection and a copy pass over it,
/// and the lines on screen are reported as the document's own lines. `text`, where there is
/// any, is drawn dimmed on its first row.
#[derive(Clone, Debug, PartialEq)]
pub struct ViewZone {
    pub after_line: u32,
    pub height_lines: f32,
    pub text: String,
}

impl ViewZone {
    pub fn new(after_line: u32, height_lines: f32) -> Self {
        Self {
            after_line,
            height_lines,
            text: String::new(),
        }
    }

    /// Shows `text`, dimmed, in the zone.
    pub fn with_text(mut self, text: impl Into<String>) -> Self {
        self.text = text.into();
        self
    }
}

/// The view zones of one editor, encoded and ready to travel.
///
/// Records first and the text they show after them, the way decorations travel.
#[derive(Clone, Default, PartialEq)]
pub struct ViewZones {
    bytes: Option<Rc<[u8]>>,
}

impl std::fmt::Debug for ViewZones {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("ViewZones")
            .field("zones", &self.zones().len())
            .finish()
    }
}

impl ViewZones {
    pub fn new(zones: impl IntoIterator<Item = ViewZone>) -> Self {
        let zones: Vec<ViewZone> = zones.into_iter().collect();
        let records_len = zones.len() * VIEW_ZONE_LEN;
        let mut bytes = Vec::with_capacity(records_len);
        let mut texts = Vec::new();
        for zone in &zones {
            put_u32(&mut bytes, zone.after_line);
            put_u32(&mut bytes, zone.height_lines.to_bits());
            // An empty text points at the end of the records, as a decoration's does.
            put_u32(&mut bytes, (records_len + texts.len()) as u32);
            put_u32(&mut bytes, zone.text.len() as u32);
            texts.extend_from_slice(zone.text.as_bytes());
        }
        bytes.extend_from_slice(&texts);
        Self::from_bytes(bytes)
    }

    /// Adopts an already encoded list, which is what the protocol vectors carry.
    pub fn from_bytes(bytes: impl Into<Rc<[u8]>>) -> Self {
        let bytes = bytes.into();
        Self {
            bytes: (!bytes.is_empty()).then_some(bytes),
        }
    }

    pub fn as_bytes(&self) -> &[u8] {
        self.bytes.as_deref().unwrap_or(&[])
    }

    pub fn is_empty(&self) -> bool {
        self.bytes.is_none()
    }

    /// The zones this list holds, read back. A record whose text is not in the list, or is
    /// not UTF-8, is skipped, which is what the Renderer does with it too.
    pub fn zones(&self) -> Vec<ViewZone> {
        let bytes = self.as_bytes();
        let mut end = bytes.len();
        let mut at = 0;
        let mut found = Vec::new();
        while at + VIEW_ZONE_LEN <= end {
            let record = &bytes[at..at + VIEW_ZONE_LEN];
            at += VIEW_ZONE_LEN;
            let text_offset = word(record, 8) as usize;
            let text_len = word(record, 12) as usize;
            if text_len > 0 {
                end = end.min(text_offset);
            }
            let text = if text_len == 0 {
                String::new()
            } else {
                match bytes
                    .get(text_offset..text_offset + text_len)
                    .and_then(|run| std::str::from_utf8(run).ok())
                {
                    Some(text) => text.to_owned(),
                    None => continue,
                }
            };
            found.push(ViewZone {
                after_line: word(record, 0),
                height_lines: f32::from_bits(word(record, 4)),
                text,
            });
        }
        found
    }
}

/// `text` as snippet text that stands for itself: a backslash in front of every `$`, `}`
/// and `\\`, so a name taken from the document cannot open a tab stop of its own when it is
/// put inside a snippet.
pub fn escape_snippet_text(text: &str) -> String {
    let mut escaped = String::with_capacity(text.len());
    for character in text.chars() {
        if matches!(character, '$' | '}' | '\\') {
            escaped.push('\\');
        }
        escaped.push(character);
    }
    escaped
}

/// Where a code editor breaks a line too long for it onto the rows below.
///
/// A broken line is still one line of the document: its number is drawn on its first row
/// only, Up, Down, Home and End follow the rows, and the lines on screen are reported as
/// the document's own. A line breaks after the last space that fits, or where a word is
/// longer than the row, at the column itself.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum WordWrap {
    /// No line breaks; a long line runs past the edge.
    #[default]
    Off,
    /// At the edge of the view.
    Viewport,
    /// At this many columns, whatever the width of the view.
    Column(u32),
    /// At this many columns, or at the edge of the view where that comes first.
    Bounded(u32),
}

impl WordWrap {
    /// The integer the `WordWrap` property carries: the `WordWrapMode` tag in the low 16
    /// bits and the column count above them.
    pub fn to_value(self) -> i64 {
        let (mode, columns) = match self {
            Self::Off => (crate::schema::WordWrapMode::Off, 0),
            Self::Viewport => (crate::schema::WordWrapMode::Viewport, 0),
            Self::Column(columns) => (crate::schema::WordWrapMode::Column, columns),
            Self::Bounded(columns) => (crate::schema::WordWrapMode::Bounded, columns),
        };
        i64::from(u16::from(mode)) | (i64::from(columns) << 16)
    }

    /// Reads back what [`WordWrap::to_value`] wrote, or None where the mode is not one, the
    /// value is below zero, or a mode that counts columns counts none.
    pub fn from_value(value: i64) -> Option<Self> {
        let columns = u32::try_from(value >> 16).ok()?;
        let mode = u16::try_from(value & 0xffff).ok()?;
        match mode {
            0 if columns == 0 => Some(Self::Off),
            _ if mode == u16::from(crate::schema::WordWrapMode::Viewport) && columns == 0 => {
                Some(Self::Viewport)
            }
            _ if mode == u16::from(crate::schema::WordWrapMode::Column) && columns > 0 => {
                Some(Self::Column(columns))
            }
            _ if mode == u16::from(crate::schema::WordWrapMode::Bounded) && columns > 0 => {
                Some(Self::Bounded(columns))
            }
            _ => None,
        }
    }
}

/// Bytes of one selection in a list of them: the anchor's line and column, then the active
/// end's.
pub const SELECTION_LEN: usize = 16;

/// Encodes selections the way `SetSelections` and `SelectionsChanged` carry them, each an
/// anchor and an active end, appending to `out`.
pub fn encode_selections(selections: &[(Position, Position)], out: &mut Vec<u8>) {
    out.reserve(selections.len() * SELECTION_LEN);
    for (anchor, active) in selections {
        put_u32(out, anchor.line);
        put_u32(out, anchor.column);
        put_u32(out, active.line);
        put_u32(out, active.column);
    }
}

/// Reads back the selections [`encode_selections`] wrote, or None where the bytes are not
/// whole selections.
pub fn decode_selections(bytes: &[u8]) -> Option<Vec<(Position, Position)>> {
    if bytes.len() % SELECTION_LEN != 0 {
        return None;
    }
    Some(
        bytes
            .chunks_exact(SELECTION_LEN)
            .map(|record| {
                (
                    Position::new(word(record, 0), word(record, 4)),
                    Position::new(word(record, 8), word(record, 12)),
                )
            })
            .collect(),
    )
}

/// Every selection of a code editor, as the Renderer reported it: sent while there is more
/// than one, and once more when it comes back to one. The first is the primary selection,
/// the one `SelectionChange` goes on reporting by itself.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SelectionsChange {
    pub version: u32,
    /// Each an anchor and an active end.
    pub selections: Vec<(Position, Position)>,
}

impl SelectionsChange {
    /// The selections a `SelectionsChanged` event carries, or None for any other event.
    pub fn from_payload(payload: &crate::schema::EventPayload<'_>) -> Option<Self> {
        match payload {
            crate::schema::EventPayload::SelectionsChanged {
                version,
                selections,
            } => Some(Self {
                version: *version,
                selections: decode_selections(selections)?,
            }),
            _ => None,
        }
    }
}

/// The selection of a code editor, as the Renderer reported it.
///
/// `anchor` is where the selection started and `active` where the caret is, so a selection
/// made backwards has the anchor after the active end. Both are read against `version`,
/// the same series [`CodeChange`] counts.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct SelectionChange {
    pub version: u32,
    pub anchor: Position,
    pub active: Position,
}

impl SelectionChange {
    /// Whether nothing is selected and the caret is a single place.
    pub fn is_caret(&self) -> bool {
        self.anchor == self.active
    }

    /// The selected stretch, with the earlier end first whichever way it was made.
    pub fn range(&self) -> CodeRange {
        CodeRange::new(self.anchor.min(self.active), self.anchor.max(self.active))
    }
}

/// The lines of a code editor that are on screen.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct VisibleRange {
    pub version: u32,
    /// The first line the reader can see.
    pub first_line: u32,
    /// The last line the reader can see. Lines a fold hides are not counted.
    pub last_line: u32,
}

/// The reader folded or unfolded a stretch of a code editor.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct FoldChange {
    /// The line the stretch starts on.
    pub start_line: u32,
    pub collapsed: bool,
}

/// The colours of an editor's own parts, each a role of the theme.
///
/// A part that is not named keeps the colour the design system gives it, so an application
/// can set the container and the gutter and leave the rest. Roles and never literals: the
/// colours follow the theme from light to dark like every other colour here.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct CodeEditorColors {
    /// What the text sits on.
    pub container: Option<ColorRole>,
    /// What the line numbers sit on.
    pub gutter: Option<ColorRole>,
    pub line_number: Option<ColorRole>,
    /// The number of the line the caret is on.
    pub current_line_number: Option<ColorRole>,
    /// The band behind the line the caret is on.
    pub current_line: Option<ColorRole>,
}

impl CodeEditorColors {
    /// Every part left to the design system.
    pub const fn new() -> Self {
        Self {
            container: None,
            gutter: None,
            line_number: None,
            current_line_number: None,
            current_line: None,
        }
    }

    pub const fn container(mut self, role: ColorRole) -> Self {
        self.container = Some(role);
        self
    }

    pub const fn gutter(mut self, role: ColorRole) -> Self {
        self.gutter = Some(role);
        self
    }

    pub const fn line_number(mut self, role: ColorRole) -> Self {
        self.line_number = Some(role);
        self
    }

    pub const fn current_line_number(mut self, role: ColorRole) -> Self {
        self.current_line_number = Some(role);
        self
    }

    pub const fn current_line(mut self, role: ColorRole) -> Self {
        self.current_line = Some(role);
        self
    }

    /// Whether every part is left to the design system, in which case there is nothing to
    /// send.
    pub fn is_empty(&self) -> bool {
        *self == Self::new()
    }

    /// The record as it travels in the `CodeEditorColors` property.
    pub fn to_bytes(&self) -> [u8; CODE_EDITOR_COLORS_LEN] {
        let mut bytes = [0_u8; CODE_EDITOR_COLORS_LEN];
        let slots = [
            self.container,
            self.gutter,
            self.line_number,
            self.current_line_number,
            self.current_line,
        ];
        for (index, slot) in slots.into_iter().enumerate() {
            let tag = slot.map_or(0, |role| role as u16);
            bytes[index * 2..index * 2 + 2].copy_from_slice(&tag.to_le_bytes());
        }
        bytes
    }

    /// The record read back. `None` where the bytes are not one whole record or name a
    /// role this side does not know, which is what the Renderer refuses too.
    pub fn from_bytes(bytes: &[u8]) -> Option<Self> {
        if bytes.len() != CODE_EDITOR_COLORS_LEN {
            return None;
        }
        let slot = |index: usize| -> Option<Option<ColorRole>> {
            match half(bytes, index * 2) {
                0 => Some(None),
                tag => ColorRole::try_from(tag).ok().map(Some),
            }
        };
        Some(Self {
            container: slot(0)?,
            gutter: slot(1)?,
            line_number: slot(2)?,
            current_line_number: slot(3)?,
            current_line: slot(4)?,
        })
    }
}

/// How an editor's rows are drawn, as the Renderer measured them.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct CodeMetrics {
    /// The height of one row in physical pixels. Every row of an editor has this height,
    /// so line `n` starts `n` times this far down when nothing is folded and no lens sits
    /// above a line.
    pub line_height_px: f64,
}

/// How far an editor is scrolled.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct CodeScroll {
    /// The physical pixels of the document above the top of the view. The unit
    /// `Batch::set_scroll_offset` takes.
    pub offset_px: f64,
}

/// A rectangle on screen, in the dp the window lays its content out in.
///
/// The editor's own scroll is already in it, and so is the window's zoom, because the zoom
/// is part of what a dp is there. The origin is the top left corner of the window's
/// content, which is where an overlay the application opens over the editor is placed
/// from, so a suggestion list or a hover card can be put at `x`, `y + height` as it is.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct CodeRect {
    pub x: f32,
    pub y: f32,
    pub width: f32,
    pub height: f32,
}

impl CodeRect {
    pub const fn new(x: f32, y: f32, width: f32, height: f32) -> Self {
        Self {
            x,
            y,
            width,
            height,
        }
    }

    /// The bottom edge, which is where a list that opens under the caret starts.
    pub fn bottom(&self) -> f32 {
        self.y + self.height
    }

    /// The right edge.
    pub fn right(&self) -> f32 {
        self.x + self.width
    }
}

/// Where an editor draws its caret, as the Renderer reported it.
///
/// Sent when the caret moves or the view scrolls, at most once a frame, and only to an
/// editor whose application listens for it. The rectangle is the caret itself: as tall as
/// a row and as wide as the caret is drawn.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct CaretRect {
    /// The place in the document the caret stands at.
    pub position: Position,
    pub rect: CodeRect,
}

impl CaretRect {
    /// The caret's place and rectangle out of a `CaretRect` event, or None for any other.
    pub fn from_payload(payload: &crate::schema::EventPayload<'_>) -> Option<Self> {
        match *payload {
            crate::schema::EventPayload::CaretRect { line, column, rect } => Some(Self {
                position: Position::new(line, column),
                rect,
            }),
            _ => None,
        }
    }
}

/// What a position query is answered with: the rectangle a caret at that position would be
/// drawn in, or None where the position is not on screen.
pub type PositionAnswer = Option<CodeRect>;

type PositionCallback = Box<dyn FnOnce(PositionAnswer)>;

thread_local! {
    /// Callbacks waiting for their answer, by request number.
    static POSITION_QUERIES: std::cell::RefCell<Vec<(u32, PositionCallback)>> =
        const { std::cell::RefCell::new(Vec::new()) };
    /// The next request number. 0 is skipped so a zeroed record never looks like a query.
    static NEXT_POSITION_QUERY: std::cell::Cell<u32> = const { std::cell::Cell::new(1) };
}

/// Numbers one question about where a position of an editor is on screen, and keeps
/// `on_answer` until the answer arrives.
///
/// The number goes into the command that asks it, `Batch::query_position_rect`, written by
/// whatever holds the editor's node. The Renderer answers every query exactly once, with
/// the rectangle a caret at that position would be drawn in, or with None where the
/// position is not on screen: scrolled away, folded, outside the document, or in an editor
/// that is gone. `on_answer` then runs on the UI thread, inside the call that carried the
/// answer, and anything it changes is in the batch that call returns.
///
/// It is how a hover card, a rename box or a parameter hint is put next to a word that is
/// not where the caret is.
pub fn position_query(on_answer: impl FnOnce(PositionAnswer) + 'static) -> u32 {
    let request = NEXT_POSITION_QUERY.with(|next| {
        let mut id = next.get();
        if id == 0 {
            id = 1;
        }
        next.set(id.wrapping_add(1));
        id
    });
    POSITION_QUERIES.with_borrow_mut(|waiting| waiting.push((request, Box::new(on_answer))));
    request
}

/// Hands an answer to the callback that asked for it. Returns whether there was one; an
/// answer nobody is waiting for any more is ignored.
pub(crate) fn deliver_position_rect(request: u32, answer: PositionAnswer) -> bool {
    // Taken out before it runs: the callback may ask again, which edits the list.
    let callback = POSITION_QUERIES.with_borrow_mut(|waiting| {
        waiting
            .iter()
            .position(|(id, _)| *id == request)
            .map(|at| waiting.remove(at).1)
    });
    match callback {
        Some(callback) => {
            callback(answer);
            true
        }
        None => false,
    }
}

/// Forgets every query still waiting. Used when a new `Host` takes over the thread: the
/// Renderer it talks to has never heard of them.
#[doc(hidden)]
pub fn reset_position_queries() {
    POSITION_QUERIES.with_borrow_mut(Vec::clear);
}

/// A pointer event over a code editor, with the place in the text under the pointer.
///
/// Everything a node's pointer event says, under the same rules: the kinds the editor
/// subscribes to with `PointerKinds`, the buttons, the modifiers, the click count, a `Move`
/// at most once a frame, and a press held by the editor until it is released. Consuming a
/// `Down` keeps the caret where it was, which is what Cmd or Ctrl and a click needs to go to
/// a definition without moving the reader's caret.
#[derive(Clone, Debug)]
pub struct CodePointer {
    pub event: crate::PointerEvent,
    /// The character under the pointer, or None where it is over none: the gutter, past the
    /// end of a line, or below the last one.
    pub position: Option<Position>,
}

impl CodePointer {
    /// The event out of a `CodePointer` payload, or None for any other.
    pub fn from_payload(payload: &crate::schema::EventPayload<'_>) -> Option<Self> {
        match *payload {
            crate::schema::EventPayload::CodePointer {
                kind,
                pointer_id,
                pointer_type,
                x,
                y,
                buttons,
                button,
                modifiers,
                click_count,
                delta_x,
                delta_y,
                delta_mode,
                timestamp_nanos,
                position,
            } => Some(Self {
                event: crate::PointerEvent::new(
                    kind,
                    pointer_id,
                    pointer_type,
                    x,
                    y,
                    buttons,
                    button,
                    modifiers,
                    click_count,
                    delta_x,
                    delta_y,
                    delta_mode,
                    timestamp_nanos,
                ),
                position,
            }),
            _ => None,
        }
    }
}

/// Encodes the edits of one grouped edit the way `EditCodeGroup` carries them, appending to
/// `out`.
///
/// The blob is a `u32` count, then one 24-byte record per edit (the range, then the text's
/// offset and length) and then the texts one after another. A text's offset counts from
/// the start of the texts, not from the start of the blob. Fails only where a count, a
/// length or an offset does not fit a `u32`.
pub fn encode_edit_group(
    edits: &[(CodeRange, &str)],
    out: &mut Vec<u8>,
) -> Result<(), crate::protocol::ProtocolError> {
    use crate::protocol::ProtocolError;
    let count = u32::try_from(edits.len()).map_err(|_| ProtocolError::LengthOverflow)?;
    let texts: usize = edits.iter().map(|(_, text)| text.len()).sum();
    out.reserve(4 + edits.len() * CODE_EDIT_LEN + texts);
    put_u32(out, count);
    let mut offset = 0_u32;
    for (range, text) in edits {
        let len = u32::try_from(text.len()).map_err(|_| ProtocolError::LengthOverflow)?;
        put_range(out, *range);
        put_u32(out, offset);
        put_u32(out, len);
        offset = offset
            .checked_add(len)
            .ok_or(ProtocolError::LengthOverflow)?;
    }
    for (_, text) in edits {
        out.extend_from_slice(text.as_bytes());
    }
    Ok(())
}

/// Reads back the edits [`encode_edit_group`] wrote, in the order they were sent.
///
/// None where the blob is not one: shorter than its count says, a text outside the blob or
/// not UTF-8, or bytes after the last text. The Renderer reads it under the same rules and
/// answers a blob it cannot read with a protocol error.
pub fn decode_edit_group(bytes: &[u8]) -> Option<Vec<(CodeRange, &str)>> {
    if bytes.len() < 4 {
        return None;
    }
    let count = word(bytes, 0) as usize;
    let texts_start = count.checked_mul(CODE_EDIT_LEN)?.checked_add(4)?;
    if texts_start > bytes.len() {
        return None;
    }
    let mut edits = Vec::with_capacity(count);
    let mut texts_end = texts_start;
    for index in 0..count {
        let record = &bytes[4 + index * CODE_EDIT_LEN..4 + (index + 1) * CODE_EDIT_LEN];
        let start = texts_start.checked_add(word(record, 16) as usize)?;
        let end = start.checked_add(word(record, 20) as usize)?;
        let text = std::str::from_utf8(bytes.get(start..end)?).ok()?;
        texts_end = texts_end.max(end);
        edits.push((range_at(record, 0), text));
    }
    (texts_end == bytes.len()).then_some(edits)
}

/// What became of one grouped edit, as the Renderer reported it.
///
/// Exactly one arrives for every grouped edit that was sent with at least one edit in it,
/// after the changes it made. The group went in whole or not at all: `status` is
/// `Applied`, or the reason it stayed out, and each reason asks for something different.
/// `Rejected`: the reader changed a place the group would have written, so read the
/// document again and send the group again. `TooOld`: the version it was written against
/// is older than the editor remembers, so bring the application's copy of the document
/// back in step first. `Invalid`: the group itself makes no sense.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct EditGroupResult {
    /// The id the application gave the group.
    pub request_id: u32,
    pub status: EditGroupStatus,
    /// The version the group was written against, as it was sent.
    pub base_version: u32,
    /// Where it went in, the version after its last change; where it did not, the version
    /// the document is at.
    pub current_version: u32,
    /// Where it went in, how many edits did; where it did not, the position in the group,
    /// as sent, of the edit that kept it out (0 where no one edit did).
    pub index: u32,
}

impl EditGroupResult {
    /// The result out of a `CodeEditGroupResult` event, or None for any other.
    pub fn from_payload(payload: &crate::schema::EventPayload<'_>) -> Option<Self> {
        match *payload {
            crate::schema::EventPayload::CodeEditGroupResult {
                request_id,
                status,
                base_version,
                current_version,
                index,
            } => Some(Self {
                request_id,
                status,
                base_version,
                current_version,
                index,
            }),
            _ => None,
        }
    }
}