compose-rust 0.0.3

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
//! 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, 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;

/// 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 `(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),
    ],
};

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]),
        };
        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(),
        }
    }

    /// 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()
    }
}

/// 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,
}