Skip to main content

compose_rust/
code.rs

1//! A code editor's document as the Host sees it.
2//!
3//! The Renderer owns the text. It owns the caret, the selection, the scroll position, the
4//! undo history and the composition an input method is building, for the same reason a
5//! text field owns them: a round trip to this side per keystroke would add a frame of
6//! latency to every key. What the Host gets is each committed edit, in order, with the
7//! version of the document it produced, which is exactly what a language server or an
8//! extension host needs to follow along.
9//!
10//! What the Host says back is said as ranges. Colour runs for the syntax and decorations
11//! for diagnostics, lenses, hover anchors and inline suggestions, each a blob of
12//! fixed-length records carrying the document version its ranges were written against.
13//! The Renderer moves them along with whatever the reader typed since, so a list that took
14//! a language server a second to compute still lands on the text it was about.
15//!
16//! Positions are a line and a column counted from zero, and a column counts UTF-16 code
17//! units. That is the unit a language server and VS Code count in, and any other unit
18//! would make every application recount every range on the way through. A line ends at
19//! `\n`, `\r\n` or a lone `\r`, which is also the language server's rule.
20
21use crate::schema::{
22    ColorRole, DecorationKind, EditGroupStatus, GutterDecorationKind, HoverPhase, Paint, Severity,
23};
24use std::rc::Rc;
25
26/// Bytes of one decoration record.
27pub const DECORATION_LEN: usize = 44;
28
29/// Bytes of one syntax colour run record.
30pub const SYNTAX_SPAN_LEN: usize = 28;
31
32/// Bytes of one edit record inside a grouped edit: the range as four `u32`, then the
33/// text's `(offset, length)`.
34pub const CODE_EDIT_LEN: usize = 24;
35
36/// What one field of a code editor record holds.
37#[derive(Clone, Copy, Debug, Eq, PartialEq)]
38pub enum RecordFieldType {
39    U32,
40    U64,
41    /// A role tag in a `u16`. `optional` says that zero means "not given" rather than a
42    /// broken record.
43    Role {
44        name: &'static str,
45        optional: bool,
46    },
47    /// A `Paint` in a `u64`.
48    Paint,
49    /// A `u32` that is 0 or 1. Any other value makes the record unreadable.
50    Flag,
51    /// An `f32`, little-endian like every other field.
52    F32,
53    /// An `(offset, length)` pair of `u32` naming UTF-8 bytes behind the records, measured
54    /// from the start of the blob, the way a `Canvas` names the text it draws.
55    Text,
56}
57
58/// One field of a fixed-length record, at the byte it starts at.
59#[derive(Clone, Copy, Debug, Eq, PartialEq)]
60pub struct RecordField {
61    pub name: &'static str,
62    pub offset: u16,
63    pub ty: RecordFieldType,
64}
65
66/// A fixed-length record that travels inside a property's blob.
67///
68/// Codegen writes the Renderer's decoder from this, so the two sides read the same bytes
69/// at the same offsets and nobody keeps a second copy of the layout by hand.
70#[derive(Clone, Copy, Debug, Eq, PartialEq)]
71pub struct RecordSchema {
72    /// The Kotlin class the decoder produces.
73    pub name: &'static str,
74    pub length: u16,
75    pub fields: &'static [RecordField],
76}
77
78const fn field(name: &'static str, offset: u16, ty: RecordFieldType) -> RecordField {
79    RecordField { name, offset, ty }
80}
81
82/// One decoration: a version, a kind, a severity and a colour role, a range, the id the
83/// application gave it, and the text a lens or a suggestion shows. Bytes 10 and 11 are
84/// reserved and written as zero.
85pub const DECORATION_RECORD: RecordSchema = RecordSchema {
86    name: "DecorationRecord",
87    length: DECORATION_LEN as u16,
88    fields: &[
89        field("version", 0, RecordFieldType::U32),
90        field(
91            "kind",
92            4,
93            RecordFieldType::Role {
94                name: "DecorationKind",
95                optional: false,
96            },
97        ),
98        field(
99            "severity",
100            6,
101            RecordFieldType::Role {
102                name: "Severity",
103                optional: true,
104            },
105        ),
106        field(
107            "color",
108            8,
109            RecordFieldType::Role {
110                name: "ColorRole",
111                optional: true,
112            },
113        ),
114        field("startLine", 12, RecordFieldType::U32),
115        field("startColumn", 16, RecordFieldType::U32),
116        field("endLine", 20, RecordFieldType::U32),
117        field("endColumn", 24, RecordFieldType::U32),
118        field("id", 28, RecordFieldType::U64),
119        field("text", 36, RecordFieldType::Text),
120    ],
121};
122
123/// One colour run of the syntax: a version, a range and the paint it is drawn in.
124pub const SYNTAX_SPAN_RECORD: RecordSchema = RecordSchema {
125    name: "SyntaxSpanRecord",
126    length: SYNTAX_SPAN_LEN as u16,
127    fields: &[
128        field("version", 0, RecordFieldType::U32),
129        field("startLine", 4, RecordFieldType::U32),
130        field("startColumn", 8, RecordFieldType::U32),
131        field("endLine", 12, RecordFieldType::U32),
132        field("endColumn", 16, RecordFieldType::U32),
133        field("paint", 20, RecordFieldType::Paint),
134    ],
135};
136
137/// Bytes of one fold record.
138pub const FOLD_LEN: usize = 16;
139
140/// Bytes of one gutter decoration record.
141pub const GUTTER_DECORATION_LEN: usize = 28;
142
143/// One stretch of lines that can be folded: a version, the line it starts on, the last line
144/// it covers and whether it is folded now. Folding keeps `start_line` and hides the lines
145/// after it up to `end_line`.
146pub const FOLD_RECORD: RecordSchema = RecordSchema {
147    name: "FoldRecord",
148    length: FOLD_LEN as u16,
149    fields: &[
150        field("version", 0, RecordFieldType::U32),
151        field("startLine", 4, RecordFieldType::U32),
152        field("endLine", 8, RecordFieldType::U32),
153        field("collapsed", 12, RecordFieldType::Flag),
154    ],
155};
156
157/// One mark beside the line numbers: a version, the line, what it looks like, an optional
158/// colour role, the id the application gave it and the character a glyph shows. Bytes 24
159/// to 27 are reserved and written as zero.
160pub const GUTTER_DECORATION_RECORD: RecordSchema = RecordSchema {
161    name: "GutterDecorationRecord",
162    length: GUTTER_DECORATION_LEN as u16,
163    fields: &[
164        field("version", 0, RecordFieldType::U32),
165        field("line", 4, RecordFieldType::U32),
166        field(
167            "kind",
168            8,
169            RecordFieldType::Role {
170                name: "GutterDecorationKind",
171                optional: false,
172            },
173        ),
174        field(
175            "color",
176            10,
177            RecordFieldType::Role {
178                name: "ColorRole",
179                optional: true,
180            },
181        ),
182        field("id", 12, RecordFieldType::U64),
183        field("glyph", 20, RecordFieldType::U32),
184    ],
185};
186
187/// Bytes of a code editor's colour record.
188pub const CODE_EDITOR_COLORS_LEN: usize = 12;
189
190const fn optional_color(name: &'static str, offset: u16) -> RecordField {
191    field(
192        name,
193        offset,
194        RecordFieldType::Role {
195            name: "ColorRole",
196            optional: true,
197        },
198    )
199}
200
201/// The colours an application gives an editor: a role for the container, the gutter, a
202/// line number, the current line's number, the current line and the current line's part of
203/// the gutter. Zero leaves that part to the design system.
204pub const CODE_EDITOR_COLORS_RECORD: RecordSchema = RecordSchema {
205    name: "CodeEditorColorsRecord",
206    length: CODE_EDITOR_COLORS_LEN as u16,
207    fields: &[
208        optional_color("container", 0),
209        optional_color("gutter", 2),
210        optional_color("lineNumber", 4),
211        optional_color("currentLineNumber", 6),
212        optional_color("currentLine", 8),
213        optional_color("currentLineGutter", 10),
214    ],
215};
216
217/// Bytes of the `ContentPaddingDp` property: the room above the first line, then below the
218/// last, each an `f32` in dp.
219pub const CONTENT_PADDING_LEN: usize = 8;
220
221/// Room above the first line and below the last line of an editor, in dp. It lies inside the
222/// scrolled content, so the first line starts `top_dp` down and the room scrolls away with
223/// it, and the last line can be scrolled `bottom_dp` clear of the end of the view.
224#[derive(Clone, Copy, Debug, Default, PartialEq)]
225pub struct ContentPadding {
226    pub top_dp: f32,
227    pub bottom_dp: f32,
228}
229
230impl ContentPadding {
231    pub const fn new(top_dp: f32, bottom_dp: f32) -> Self {
232        Self { top_dp, bottom_dp }
233    }
234
235    /// Whether there is no room on either side, in which case there is nothing to send.
236    pub fn is_empty(&self) -> bool {
237        self.top_dp == 0.0 && self.bottom_dp == 0.0
238    }
239
240    /// The bytes the property carries: top, then bottom, little-endian.
241    pub fn to_bytes(&self) -> [u8; CONTENT_PADDING_LEN] {
242        let mut bytes = [0_u8; CONTENT_PADDING_LEN];
243        bytes[0..4].copy_from_slice(&self.top_dp.to_le_bytes());
244        bytes[4..8].copy_from_slice(&self.bottom_dp.to_le_bytes());
245        bytes
246    }
247
248    /// The padding read back. `None` where the bytes are not eight, or either side is below
249    /// zero or not a number, which the Renderer refuses as well.
250    pub fn from_bytes(bytes: &[u8]) -> Option<Self> {
251        if bytes.len() != CONTENT_PADDING_LEN {
252            return None;
253        }
254        let side = |at: usize| {
255            let value = f32::from_le_bytes(bytes[at..at + 4].try_into().ok()?);
256            (value.is_finite() && value >= 0.0).then_some(value)
257        };
258        Some(Self::new(side(0)?, side(4)?))
259    }
260}
261
262/// Bytes of one view zone record.
263pub const VIEW_ZONE_LEN: usize = 16;
264
265/// One view zone: the line it follows, its height in rows and the text it shows dimmed, which
266/// lies behind the records like a decoration's.
267pub const VIEW_ZONE_RECORD: RecordSchema = RecordSchema {
268    name: "ViewZoneRecord",
269    length: VIEW_ZONE_LEN as u16,
270    fields: &[
271        field("afterLine", 0, RecordFieldType::U32),
272        field("heightLines", 4, RecordFieldType::F32),
273        field("text", 8, RecordFieldType::Text),
274    ],
275};
276
277const fn hash_bytes(mut hash: u64, bytes: &[u8]) -> u64 {
278    let mut index = 0;
279    while index < bytes.len() {
280        hash ^= bytes[index] as u64;
281        hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
282        index += 1;
283    }
284    hash
285}
286
287/// Folds a record layout into the schema hash, so a Renderer built against another
288/// layout is refused at the handshake rather than reading the wrong bytes.
289pub(crate) const fn hash_record_schema(mut hash: u64, schema: RecordSchema) -> u64 {
290    hash = hash_bytes(hash, schema.name.as_bytes());
291    hash = hash_bytes(hash, &schema.length.to_le_bytes());
292    let mut index = 0;
293    while index < schema.fields.len() {
294        let field = schema.fields[index];
295        hash = hash_bytes(hash, field.name.as_bytes());
296        hash = hash_bytes(hash, &field.offset.to_le_bytes());
297        hash = match field.ty {
298            RecordFieldType::U32 => hash_bytes(hash, &[1]),
299            RecordFieldType::U64 => hash_bytes(hash, &[2]),
300            RecordFieldType::Role { name, optional } => {
301                let hash = hash_bytes(hash, &[3, optional as u8]);
302                hash_bytes(hash, name.as_bytes())
303            }
304            RecordFieldType::Paint => hash_bytes(hash, &[4]),
305            RecordFieldType::Text => hash_bytes(hash, &[5]),
306            RecordFieldType::Flag => hash_bytes(hash, &[6]),
307            RecordFieldType::F32 => hash_bytes(hash, &[7]),
308        };
309        index += 1;
310    }
311    hash
312}
313
314/// A place in the document: a line and a column, both from zero, the column in UTF-16
315/// code units.
316#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
317pub struct Position {
318    pub line: u32,
319    pub column: u32,
320}
321
322impl Position {
323    pub const fn new(line: u32, column: u32) -> Self {
324        Self { line, column }
325    }
326}
327
328/// A stretch of the document from `start` up to, and not including, `end`.
329#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
330pub struct CodeRange {
331    pub start: Position,
332    pub end: Position,
333}
334
335impl CodeRange {
336    pub const fn new(start: Position, end: Position) -> Self {
337        Self { start, end }
338    }
339
340    /// The empty range at one place, which is where an insertion goes.
341    pub const fn at(position: Position) -> Self {
342        Self {
343            start: position,
344            end: position,
345        }
346    }
347
348    /// A range given as four numbers, in the order a language server writes them.
349    pub const fn of(start_line: u32, start_column: u32, end_line: u32, end_column: u32) -> Self {
350        Self {
351            start: Position::new(start_line, start_column),
352            end: Position::new(end_line, end_column),
353        }
354    }
355
356    pub fn is_empty(&self) -> bool {
357        self.start == self.end
358    }
359}
360
361/// One thing drawn over the document, said as a range and never as a picture.
362///
363/// The colour of an underline is a role, never a literal, and is left to the design system
364/// where it is not given; the shape of the mark, a squiggle or a line, and its weight are
365/// always the design system's.
366#[derive(Clone, Debug, PartialEq)]
367pub struct Decoration {
368    /// The document version the range was written against.
369    pub version: u32,
370    pub kind: DecorationKind,
371    /// Only an underline has one.
372    pub severity: Option<Severity>,
373    /// The role an underline is drawn in. None leaves it to the design system, which picks
374    /// one that suits the severity.
375    pub color: Option<ColorRole>,
376    pub range: CodeRange,
377    /// The application's own name for this decoration, reported when it is pressed,
378    /// accepted or hovered. Zero means it cannot be pressed and is never reported.
379    pub id: u64,
380    /// What a lens, a suggestion or an after-line decoration shows. Empty for the other kinds.
381    pub text: String,
382}
383
384impl Decoration {
385    /// A diagnostic mark under a range.
386    pub fn underline(version: u32, range: CodeRange, severity: Severity) -> Self {
387        Self {
388            version,
389            kind: DecorationKind::Underline,
390            severity: Some(severity),
391            color: None,
392            range,
393            id: 0,
394            text: String::new(),
395        }
396    }
397
398    /// A short line of text shown above `line`, which reports `id` when pressed.
399    pub fn code_lens(version: u32, line: u32, text: impl Into<String>, id: u64) -> Self {
400        Self {
401            version,
402            kind: DecorationKind::CodeLens,
403            severity: None,
404            color: None,
405            range: CodeRange::at(Position::new(line, 0)),
406            id,
407            text: text.into(),
408        }
409    }
410
411    /// A range that reports `id` when a pointer comes to rest over it.
412    pub fn hover_anchor(version: u32, range: CodeRange, id: u64) -> Self {
413        Self {
414            version,
415            kind: DecorationKind::HoverAnchor,
416            severity: None,
417            color: None,
418            range,
419            id,
420            text: String::new(),
421        }
422    }
423
424    /// A suggestion shown faintly at `at`. Accepting it inserts `text` there as an
425    /// ordinary edit and then reports `id`.
426    pub fn ghost_text(version: u32, at: Position, text: impl Into<String>, id: u64) -> Self {
427        Self {
428            version,
429            kind: DecorationKind::GhostText,
430            severity: None,
431            color: None,
432            range: CodeRange::at(at),
433            id,
434            text: text.into(),
435        }
436    }
437
438    /// A tint across lines `line_start` to `line_end`, both included, the whole width of the
439    /// editor and past the end of each line. `color` is a role such as `DiffAdded`,
440    /// `DiffRemoved` or `DiffModified`, and the design system decides how strong the tint
441    /// of each is. The lines follow the reader's edits like every other decoration.
442    pub fn line_background(version: u32, line_start: u32, line_end: u32, color: ColorRole) -> Self {
443        Self {
444            version,
445            kind: DecorationKind::LineBackground,
446            severity: None,
447            color: Some(color),
448            range: CodeRange::of(line_start, 0, line_end, 0),
449            id: 0,
450            text: String::new(),
451        }
452    }
453
454    /// A tint over the characters of `range`, stronger than a line background in the same
455    /// role, for the part of a changed line that changed.
456    pub fn range_background(version: u32, range: CodeRange, color: ColorRole) -> Self {
457        Self {
458            version,
459            kind: DecorationKind::RangeBackground,
460            severity: None,
461            color: Some(color),
462            range,
463            id: 0,
464            text: String::new(),
465        }
466    }
467
468    /// Muted `text` after the last character of `line`, in the role `color`: who last
469    /// changed the line, or the value a debugger read for it. It is not text. It cannot be
470    /// selected or copied, the caret and End stop before it, a pointer over it is over no
471    /// character, and it moves with its line through the reader's edits.
472    pub fn after_line(version: u32, line: u32, text: impl Into<String>, color: ColorRole) -> Self {
473        Self {
474            version,
475            kind: DecorationKind::AfterLine,
476            severity: None,
477            color: Some(color),
478            range: CodeRange::at(Position::new(line, 0)),
479            id: 0,
480            text: text.into(),
481        }
482    }
483
484    /// Draws an underline in this role rather than the one the design system would pick.
485    pub fn with_color(mut self, role: ColorRole) -> Self {
486        self.color = Some(role);
487        self
488    }
489
490    pub fn with_id(mut self, id: u64) -> Self {
491        self.id = id;
492        self
493    }
494}
495
496fn put_u16(out: &mut Vec<u8>, value: u16) {
497    out.extend_from_slice(&value.to_le_bytes());
498}
499
500fn put_u32(out: &mut Vec<u8>, value: u32) {
501    out.extend_from_slice(&value.to_le_bytes());
502}
503
504fn put_u64(out: &mut Vec<u8>, value: u64) {
505    out.extend_from_slice(&value.to_le_bytes());
506}
507
508fn put_range(out: &mut Vec<u8>, range: CodeRange) {
509    put_u32(out, range.start.line);
510    put_u32(out, range.start.column);
511    put_u32(out, range.end.line);
512    put_u32(out, range.end.column);
513}
514
515fn word(record: &[u8], at: usize) -> u32 {
516    u32::from_le_bytes([record[at], record[at + 1], record[at + 2], record[at + 3]])
517}
518
519fn half(record: &[u8], at: usize) -> u16 {
520    u16::from_le_bytes([record[at], record[at + 1]])
521}
522
523fn long(record: &[u8], at: usize) -> u64 {
524    u64::from(word(record, at)) | (u64::from(word(record, at + 4)) << 32)
525}
526
527fn range_at(record: &[u8], at: usize) -> CodeRange {
528    CodeRange::of(
529        word(record, at),
530        word(record, at + 4),
531        word(record, at + 8),
532        word(record, at + 12),
533    )
534}
535
536/// The decorations over one editor, encoded and ready to travel.
537///
538/// Records first and the text they show after them, so the records stay fixed-length.
539/// Shared rather than copied, so the same list given again compares equal and costs no
540/// record at all.
541#[derive(Clone, Default, PartialEq)]
542pub struct Decorations {
543    bytes: Option<Rc<[u8]>>,
544}
545
546impl std::fmt::Debug for Decorations {
547    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
548        formatter
549            .debug_struct("Decorations")
550            .field("decorations", &self.decorations().len())
551            .finish()
552    }
553}
554
555impl Decorations {
556    pub fn new(decorations: impl IntoIterator<Item = Decoration>) -> Self {
557        let decorations: Vec<Decoration> = decorations.into_iter().collect();
558        let records_len = decorations.len() * DECORATION_LEN;
559        let mut bytes = Vec::with_capacity(records_len);
560        let mut texts = Vec::new();
561        for decoration in &decorations {
562            put_u32(&mut bytes, decoration.version);
563            put_u16(&mut bytes, decoration.kind as u16);
564            put_u16(
565                &mut bytes,
566                decoration.severity.map_or(0, |value| value as u16),
567            );
568            put_u16(&mut bytes, decoration.color.map_or(0, |value| value as u16));
569            put_u16(&mut bytes, 0);
570            put_range(&mut bytes, decoration.range);
571            put_u64(&mut bytes, decoration.id);
572            // An empty text points at the end of the records, which is where the text
573            // region starts, so a reader never sees an offset into the records themselves.
574            put_u32(&mut bytes, (records_len + texts.len()) as u32);
575            put_u32(&mut bytes, decoration.text.len() as u32);
576            texts.extend_from_slice(decoration.text.as_bytes());
577        }
578        bytes.extend_from_slice(&texts);
579        Self::from_bytes(bytes)
580    }
581
582    /// Adopts an already encoded list, which is what the protocol vectors carry.
583    pub fn from_bytes(bytes: impl Into<Rc<[u8]>>) -> Self {
584        let bytes = bytes.into();
585        Self {
586            bytes: (!bytes.is_empty()).then_some(bytes),
587        }
588    }
589
590    pub fn as_bytes(&self) -> &[u8] {
591        self.bytes.as_deref().unwrap_or(&[])
592    }
593
594    pub fn is_empty(&self) -> bool {
595        self.bytes.is_none()
596    }
597
598    /// The decorations this list holds, read back.
599    ///
600    /// The records end where the text region begins, which is the first offset any record
601    /// names for its text, or the end of the blob where none names one. A record whose
602    /// kind, severity or colour is not one this side knows is skipped, which is what the
603    /// Renderer does with it too.
604    pub fn decorations(&self) -> Vec<Decoration> {
605        let bytes = self.as_bytes();
606        let mut end = bytes.len();
607        let mut at = 0;
608        let mut found = Vec::new();
609        while at + DECORATION_LEN <= end {
610            let record = &bytes[at..at + DECORATION_LEN];
611            at += DECORATION_LEN;
612            let text_offset = word(record, 36) as usize;
613            let text_len = word(record, 40) as usize;
614            if text_len > 0 {
615                end = end.min(text_offset);
616            }
617            let Ok(kind) = DecorationKind::try_from(half(record, 4)) else {
618                continue;
619            };
620            let severity = match half(record, 6) {
621                0 => None,
622                tag => match Severity::try_from(tag) {
623                    Ok(severity) => Some(severity),
624                    Err(()) => continue,
625                },
626            };
627            let color = match half(record, 8) {
628                0 => None,
629                tag => match ColorRole::try_from(tag) {
630                    Ok(role) => Some(role),
631                    Err(()) => continue,
632                },
633            };
634            let text = if text_len == 0 {
635                String::new()
636            } else {
637                match bytes
638                    .get(text_offset..text_offset + text_len)
639                    .and_then(|run| std::str::from_utf8(run).ok())
640                {
641                    Some(text) => text.to_owned(),
642                    None => continue,
643                }
644            };
645            found.push(Decoration {
646                version: word(record, 0),
647                kind,
648                severity,
649                color,
650                range: range_at(record, 12),
651                id: long(record, 28),
652                text,
653            });
654        }
655        found
656    }
657}
658
659/// One colour run of the syntax.
660///
661/// A paint rather than a colour, and in practice a role: the code colour roles are what a
662/// highlighter on this side maps its token kinds onto, so the same run comes out in the
663/// right colour under every design system and in both light and dark.
664#[derive(Clone, Copy, Debug, PartialEq)]
665pub struct SyntaxSpan {
666    pub version: u32,
667    pub range: CodeRange,
668    pub paint: Paint,
669}
670
671impl SyntaxSpan {
672    pub const fn new(version: u32, range: CodeRange, paint: Paint) -> Self {
673        Self {
674            version,
675            range,
676            paint,
677        }
678    }
679
680    /// A run drawn in one colour role.
681    pub const fn role(version: u32, range: CodeRange, role: ColorRole) -> Self {
682        Self::new(version, range, Paint::Role(role))
683    }
684}
685
686/// The colour runs of one editor's syntax, encoded and ready to travel.
687#[derive(Clone, Default, PartialEq)]
688pub struct SyntaxSpans {
689    bytes: Option<Rc<[u8]>>,
690}
691
692impl std::fmt::Debug for SyntaxSpans {
693    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
694        formatter
695            .debug_struct("SyntaxSpans")
696            .field("spans", &(self.as_bytes().len() / SYNTAX_SPAN_LEN))
697            .finish()
698    }
699}
700
701impl SyntaxSpans {
702    pub fn new(spans: impl IntoIterator<Item = SyntaxSpan>) -> Self {
703        let mut bytes = Vec::new();
704        for span in spans {
705            put_u32(&mut bytes, span.version);
706            put_range(&mut bytes, span.range);
707            put_u64(&mut bytes, span.paint.to_bits());
708        }
709        Self::from_bytes(bytes)
710    }
711
712    pub fn from_bytes(bytes: impl Into<Rc<[u8]>>) -> Self {
713        let bytes = bytes.into();
714        Self {
715            bytes: (!bytes.is_empty()).then_some(bytes),
716        }
717    }
718
719    pub fn as_bytes(&self) -> &[u8] {
720        self.bytes.as_deref().unwrap_or(&[])
721    }
722
723    pub fn is_empty(&self) -> bool {
724        self.bytes.is_none()
725    }
726
727    /// The runs this list holds, read back. A run whose paint this side cannot read is
728    /// skipped.
729    pub fn spans(&self) -> Vec<SyntaxSpan> {
730        self.as_bytes()
731            .chunks_exact(SYNTAX_SPAN_LEN)
732            .filter_map(|record| {
733                Some(SyntaxSpan {
734                    version: word(record, 0),
735                    range: range_at(record, 4),
736                    paint: Paint::from_bits(long(record, 20))?,
737                })
738            })
739            .collect()
740    }
741}
742
743/// Where a position falls in `text`, as a byte offset, or None where the document has no
744/// such place: a line past the last one, a column past the end of its line, or a column
745/// that would split a character written as two UTF-16 units.
746pub fn byte_offset(text: &str, position: Position) -> Option<usize> {
747    let bytes = text.as_bytes();
748    let mut start = 0;
749    for _ in 0..position.line {
750        let at = bytes[start..]
751            .iter()
752            .position(|byte| *byte == b'\n' || *byte == b'\r')?
753            + start;
754        start = if bytes[at] == b'\r' && bytes.get(at + 1) == Some(&b'\n') {
755            at + 2
756        } else {
757            at + 1
758        };
759    }
760    let end = bytes[start..]
761        .iter()
762        .position(|byte| *byte == b'\n' || *byte == b'\r')
763        .map_or(bytes.len(), |offset| start + offset);
764    let mut units = 0_u32;
765    let mut offset = start;
766    for character in text[start..end].chars() {
767        if units == position.column {
768            return Some(offset);
769        }
770        units += character.len_utf16() as u32;
771        offset += character.len_utf8();
772        if units > position.column {
773            return None;
774        }
775    }
776    (units == position.column).then_some(offset)
777}
778
779/// One committed edit, as the Renderer reported it.
780///
781/// `range` is in the document as it stood before the edit, and `version` is the version
782/// the edit produced. The shape is a language server's `TextDocumentContentChangeEvent`,
783/// so forwarding one is a matter of copying four numbers and a string.
784#[derive(Clone, Debug, PartialEq)]
785pub struct CodeChange {
786    pub version: u32,
787    pub range: CodeRange,
788    pub text: String,
789}
790
791impl CodeChange {
792    /// Applies this edit to a copy of the document the Host keeps.
793    ///
794    /// Applying every change in the order they arrived, starting from the text the editor
795    /// was opened with, gives the text the reader sees. Returns false, and leaves `text`
796    /// alone, where the range does not fit the document, which means the copy has fallen
797    /// out of step with the editor.
798    pub fn apply_to(&self, text: &mut String) -> bool {
799        let (Some(start), Some(end)) = (
800            byte_offset(text, self.range.start),
801            byte_offset(text, self.range.end),
802        ) else {
803            return false;
804        };
805        if start > end {
806            return false;
807        }
808        text.replace_range(start..end, &self.text);
809        true
810    }
811}
812
813/// A Host edit the Renderer did not apply, because the reader had changed the same place
814/// since the version the edit was written against.
815#[derive(Clone, Copy, Debug, Eq, PartialEq)]
816pub struct EditRejected {
817    /// The id the application gave the edit.
818    pub request_id: u32,
819    pub base_version: u32,
820    /// The version the document had reached when the edit arrived.
821    pub current_version: u32,
822    /// The range exactly as it was sent.
823    pub range: CodeRange,
824}
825
826/// A pointer came to rest over a place in the editor, or left it.
827///
828/// How long it has to rest is the design system's, the same kind of delay a tooltip
829/// waits, and nothing is sent again while it stays. What to show is the application's,
830/// drawn with the overlay widgets it already has.
831#[derive(Clone, Copy, Debug, Eq, PartialEq)]
832pub struct CodeHover {
833    /// The id of the hover anchor under the pointer, or None where there is none.
834    pub decoration: Option<u64>,
835    pub position: Position,
836    pub phase: HoverPhase,
837}
838
839/// The reader pressed the save shortcut: Command S on macOS, Control S elsewhere.
840///
841/// Writing the file is this side's job, on a worker, never on the thread the editor runs
842/// on.
843#[derive(Clone, Copy, Debug, Eq, PartialEq)]
844pub struct SaveRequest {
845    /// The version of the document the reader saw when they pressed it.
846    pub version: u32,
847}
848
849/// One stretch of lines the reader can fold.
850#[derive(Clone, Copy, Debug, Eq, PartialEq)]
851pub struct Fold {
852    /// The document version the lines were written against.
853    pub version: u32,
854    /// The line that stays when the stretch is folded.
855    pub start_line: u32,
856    /// The last line the fold hides. Folding hides the lines after `start_line` up to and
857    /// including this one.
858    pub end_line: u32,
859    pub collapsed: bool,
860}
861
862impl Fold {
863    /// A stretch from `start_line` to `end_line`, unfolded.
864    pub const fn new(version: u32, start_line: u32, end_line: u32) -> Self {
865        Self {
866            version,
867            start_line,
868            end_line,
869            collapsed: false,
870        }
871    }
872
873    /// The same stretch, folded.
874    pub const fn collapsed(mut self) -> Self {
875        self.collapsed = true;
876        self
877    }
878}
879
880/// The stretches of one editor that can be folded, encoded and ready to travel.
881#[derive(Clone, Default, PartialEq)]
882pub struct Folds {
883    bytes: Option<Rc<[u8]>>,
884}
885
886impl std::fmt::Debug for Folds {
887    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
888        formatter
889            .debug_struct("Folds")
890            .field("folds", &(self.as_bytes().len() / FOLD_LEN))
891            .finish()
892    }
893}
894
895impl Folds {
896    pub fn new(folds: impl IntoIterator<Item = Fold>) -> Self {
897        let mut bytes = Vec::new();
898        for fold in folds {
899            put_u32(&mut bytes, fold.version);
900            put_u32(&mut bytes, fold.start_line);
901            put_u32(&mut bytes, fold.end_line);
902            put_u32(&mut bytes, u32::from(fold.collapsed));
903        }
904        Self::from_bytes(bytes)
905    }
906
907    pub fn from_bytes(bytes: impl Into<Rc<[u8]>>) -> Self {
908        let bytes = bytes.into();
909        Self {
910            bytes: (!bytes.is_empty()).then_some(bytes),
911        }
912    }
913
914    pub fn as_bytes(&self) -> &[u8] {
915        self.bytes.as_deref().unwrap_or(&[])
916    }
917
918    pub fn is_empty(&self) -> bool {
919        self.bytes.is_none()
920    }
921
922    /// The folds this list holds, read back. A record whose collapsed word is neither 0
923    /// nor 1 is skipped, which is what the Renderer does with it too.
924    pub fn folds(&self) -> Vec<Fold> {
925        self.as_bytes()
926            .chunks_exact(FOLD_LEN)
927            .filter_map(|record| {
928                Some(Fold {
929                    version: word(record, 0),
930                    start_line: word(record, 4),
931                    end_line: word(record, 8),
932                    collapsed: match word(record, 12) {
933                        0 => false,
934                        1 => true,
935                        _ => return None,
936                    },
937                })
938            })
939            .collect()
940    }
941}
942
943/// One mark beside a line number, said as a line and never as a picture.
944///
945/// The colour is a role, never a literal, and is left to the design system where it is not
946/// given. How big a dot is, how wide a bar and where each sits are always the design
947/// system's.
948#[derive(Clone, Copy, Debug, Eq, PartialEq)]
949pub struct GutterDecoration {
950    /// The document version the line was written against.
951    pub version: u32,
952    pub line: u32,
953    pub kind: GutterDecorationKind,
954    pub color: Option<ColorRole>,
955    /// The application's own name for it, reported when it is pressed. Zero means it
956    /// cannot be pressed.
957    pub id: u64,
958    /// The character a glyph shows, as a Unicode scalar value. Zero for the other kinds.
959    pub glyph: u32,
960}
961
962impl GutterDecoration {
963    /// A dot beside `line`.
964    pub const fn dot(version: u32, line: u32, id: u64) -> Self {
965        Self {
966            version,
967            line,
968            kind: GutterDecorationKind::Dot,
969            color: None,
970            id,
971            glyph: 0,
972        }
973    }
974
975    /// A bar the height of `line`.
976    pub const fn bar(version: u32, line: u32, id: u64) -> Self {
977        Self {
978            version,
979            line,
980            kind: GutterDecorationKind::Bar,
981            color: None,
982            id,
983            glyph: 0,
984        }
985    }
986
987    /// One character beside `line`.
988    pub const fn glyph(version: u32, line: u32, glyph: char, id: u64) -> Self {
989        Self {
990            version,
991            line,
992            kind: GutterDecorationKind::Glyph,
993            color: None,
994            id,
995            glyph: glyph as u32,
996        }
997    }
998
999    /// Draws the mark in this role rather than the one the design system would pick.
1000    pub const fn with_color(mut self, role: ColorRole) -> Self {
1001        self.color = Some(role);
1002        self
1003    }
1004
1005    pub const fn with_id(mut self, id: u64) -> Self {
1006        self.id = id;
1007        self
1008    }
1009}
1010
1011/// The marks beside the line numbers of one editor, encoded and ready to travel.
1012#[derive(Clone, Default, PartialEq)]
1013pub struct GutterDecorations {
1014    bytes: Option<Rc<[u8]>>,
1015}
1016
1017impl std::fmt::Debug for GutterDecorations {
1018    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1019        formatter
1020            .debug_struct("GutterDecorations")
1021            .field(
1022                "decorations",
1023                &(self.as_bytes().len() / GUTTER_DECORATION_LEN),
1024            )
1025            .finish()
1026    }
1027}
1028
1029impl GutterDecorations {
1030    pub fn new(decorations: impl IntoIterator<Item = GutterDecoration>) -> Self {
1031        let mut bytes = Vec::new();
1032        for decoration in decorations {
1033            put_u32(&mut bytes, decoration.version);
1034            put_u32(&mut bytes, decoration.line);
1035            put_u16(&mut bytes, decoration.kind as u16);
1036            put_u16(&mut bytes, decoration.color.map_or(0, |value| value as u16));
1037            put_u64(&mut bytes, decoration.id);
1038            put_u32(&mut bytes, decoration.glyph);
1039            put_u32(&mut bytes, 0);
1040        }
1041        Self::from_bytes(bytes)
1042    }
1043
1044    pub fn from_bytes(bytes: impl Into<Rc<[u8]>>) -> Self {
1045        let bytes = bytes.into();
1046        Self {
1047            bytes: (!bytes.is_empty()).then_some(bytes),
1048        }
1049    }
1050
1051    pub fn as_bytes(&self) -> &[u8] {
1052        self.bytes.as_deref().unwrap_or(&[])
1053    }
1054
1055    pub fn is_empty(&self) -> bool {
1056        self.bytes.is_none()
1057    }
1058
1059    /// The marks this list holds, read back. A record whose kind or colour this side does
1060    /// not know is skipped, which is what the Renderer does with it too.
1061    pub fn decorations(&self) -> Vec<GutterDecoration> {
1062        self.as_bytes()
1063            .chunks_exact(GUTTER_DECORATION_LEN)
1064            .filter_map(|record| {
1065                let kind = GutterDecorationKind::try_from(half(record, 8)).ok()?;
1066                let color = match half(record, 10) {
1067                    0 => None,
1068                    tag => Some(ColorRole::try_from(tag).ok()?),
1069                };
1070                Some(GutterDecoration {
1071                    version: word(record, 0),
1072                    line: word(record, 4),
1073                    kind,
1074                    color,
1075                    id: long(record, 12),
1076                    glyph: word(record, 20),
1077                })
1078            })
1079            .collect()
1080    }
1081}
1082
1083/// Room after a line that is not text: the blank rows a diff leaves on one side to line it up
1084/// with the other, or a note between two lines.
1085///
1086/// `after_line` is the line it follows in the document as it is when the list arrives, from
1087/// zero. The zone then follows that line through the reader's edits. `height_lines` is how
1088/// tall it is in rows, and need not be whole. The caret, a selection and a copy pass over it,
1089/// and the lines on screen are reported as the document's own lines. `text`, where there is
1090/// any, is drawn dimmed on its first row.
1091#[derive(Clone, Debug, PartialEq)]
1092pub struct ViewZone {
1093    pub after_line: u32,
1094    pub height_lines: f32,
1095    pub text: String,
1096}
1097
1098impl ViewZone {
1099    pub fn new(after_line: u32, height_lines: f32) -> Self {
1100        Self {
1101            after_line,
1102            height_lines,
1103            text: String::new(),
1104        }
1105    }
1106
1107    /// Shows `text`, dimmed, in the zone.
1108    pub fn with_text(mut self, text: impl Into<String>) -> Self {
1109        self.text = text.into();
1110        self
1111    }
1112}
1113
1114/// The view zones of one editor, encoded and ready to travel.
1115///
1116/// Records first and the text they show after them, the way decorations travel.
1117#[derive(Clone, Default, PartialEq)]
1118pub struct ViewZones {
1119    bytes: Option<Rc<[u8]>>,
1120}
1121
1122impl std::fmt::Debug for ViewZones {
1123    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1124        formatter
1125            .debug_struct("ViewZones")
1126            .field("zones", &self.zones().len())
1127            .finish()
1128    }
1129}
1130
1131impl ViewZones {
1132    pub fn new(zones: impl IntoIterator<Item = ViewZone>) -> Self {
1133        let zones: Vec<ViewZone> = zones.into_iter().collect();
1134        let records_len = zones.len() * VIEW_ZONE_LEN;
1135        let mut bytes = Vec::with_capacity(records_len);
1136        let mut texts = Vec::new();
1137        for zone in &zones {
1138            put_u32(&mut bytes, zone.after_line);
1139            put_u32(&mut bytes, zone.height_lines.to_bits());
1140            // An empty text points at the end of the records, as a decoration's does.
1141            put_u32(&mut bytes, (records_len + texts.len()) as u32);
1142            put_u32(&mut bytes, zone.text.len() as u32);
1143            texts.extend_from_slice(zone.text.as_bytes());
1144        }
1145        bytes.extend_from_slice(&texts);
1146        Self::from_bytes(bytes)
1147    }
1148
1149    /// Adopts an already encoded list, which is what the protocol vectors carry.
1150    pub fn from_bytes(bytes: impl Into<Rc<[u8]>>) -> Self {
1151        let bytes = bytes.into();
1152        Self {
1153            bytes: (!bytes.is_empty()).then_some(bytes),
1154        }
1155    }
1156
1157    pub fn as_bytes(&self) -> &[u8] {
1158        self.bytes.as_deref().unwrap_or(&[])
1159    }
1160
1161    pub fn is_empty(&self) -> bool {
1162        self.bytes.is_none()
1163    }
1164
1165    /// The zones this list holds, read back. A record whose text is not in the list, or is
1166    /// not UTF-8, is skipped, which is what the Renderer does with it too.
1167    pub fn zones(&self) -> Vec<ViewZone> {
1168        let bytes = self.as_bytes();
1169        let mut end = bytes.len();
1170        let mut at = 0;
1171        let mut found = Vec::new();
1172        while at + VIEW_ZONE_LEN <= end {
1173            let record = &bytes[at..at + VIEW_ZONE_LEN];
1174            at += VIEW_ZONE_LEN;
1175            let text_offset = word(record, 8) as usize;
1176            let text_len = word(record, 12) as usize;
1177            if text_len > 0 {
1178                end = end.min(text_offset);
1179            }
1180            let text = if text_len == 0 {
1181                String::new()
1182            } else {
1183                match bytes
1184                    .get(text_offset..text_offset + text_len)
1185                    .and_then(|run| std::str::from_utf8(run).ok())
1186                {
1187                    Some(text) => text.to_owned(),
1188                    None => continue,
1189                }
1190            };
1191            found.push(ViewZone {
1192                after_line: word(record, 0),
1193                height_lines: f32::from_bits(word(record, 4)),
1194                text,
1195            });
1196        }
1197        found
1198    }
1199}
1200
1201/// `text` as snippet text that stands for itself: a backslash in front of every `$`, `}`
1202/// and `\\`, so a name taken from the document cannot open a tab stop of its own when it is
1203/// put inside a snippet.
1204pub fn escape_snippet_text(text: &str) -> String {
1205    let mut escaped = String::with_capacity(text.len());
1206    for character in text.chars() {
1207        if matches!(character, '$' | '}' | '\\') {
1208            escaped.push('\\');
1209        }
1210        escaped.push(character);
1211    }
1212    escaped
1213}
1214
1215/// Where a code editor breaks a line too long for it onto the rows below.
1216///
1217/// A broken line is still one line of the document: its number is drawn on its first row
1218/// only, Up, Down, Home and End follow the rows, and the lines on screen are reported as
1219/// the document's own. A line breaks after the last space that fits, or where a word is
1220/// longer than the row, at the column itself.
1221#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1222pub enum WordWrap {
1223    /// No line breaks; a long line runs past the edge.
1224    #[default]
1225    Off,
1226    /// At the edge of the view.
1227    Viewport,
1228    /// At this many columns, whatever the width of the view.
1229    Column(u32),
1230    /// At this many columns, or at the edge of the view where that comes first.
1231    Bounded(u32),
1232}
1233
1234impl WordWrap {
1235    /// The integer the `WordWrap` property carries: the `WordWrapMode` tag in the low 16
1236    /// bits and the column count above them.
1237    pub fn to_value(self) -> i64 {
1238        let (mode, columns) = match self {
1239            Self::Off => (crate::schema::WordWrapMode::Off, 0),
1240            Self::Viewport => (crate::schema::WordWrapMode::Viewport, 0),
1241            Self::Column(columns) => (crate::schema::WordWrapMode::Column, columns),
1242            Self::Bounded(columns) => (crate::schema::WordWrapMode::Bounded, columns),
1243        };
1244        i64::from(u16::from(mode)) | (i64::from(columns) << 16)
1245    }
1246
1247    /// Reads back what [`WordWrap::to_value`] wrote, or None where the mode is not one, the
1248    /// value is below zero, or a mode that counts columns counts none.
1249    pub fn from_value(value: i64) -> Option<Self> {
1250        let columns = u32::try_from(value >> 16).ok()?;
1251        let mode = u16::try_from(value & 0xffff).ok()?;
1252        match mode {
1253            0 if columns == 0 => Some(Self::Off),
1254            _ if mode == u16::from(crate::schema::WordWrapMode::Viewport) && columns == 0 => {
1255                Some(Self::Viewport)
1256            }
1257            _ if mode == u16::from(crate::schema::WordWrapMode::Column) && columns > 0 => {
1258                Some(Self::Column(columns))
1259            }
1260            _ if mode == u16::from(crate::schema::WordWrapMode::Bounded) && columns > 0 => {
1261                Some(Self::Bounded(columns))
1262            }
1263            _ => None,
1264        }
1265    }
1266}
1267
1268/// Bytes of one selection in a list of them: the anchor's line and column, then the active
1269/// end's.
1270pub const SELECTION_LEN: usize = 16;
1271
1272/// Encodes selections the way `SetSelections` and `SelectionsChanged` carry them, each an
1273/// anchor and an active end, appending to `out`.
1274pub fn encode_selections(selections: &[(Position, Position)], out: &mut Vec<u8>) {
1275    out.reserve(selections.len() * SELECTION_LEN);
1276    for (anchor, active) in selections {
1277        put_u32(out, anchor.line);
1278        put_u32(out, anchor.column);
1279        put_u32(out, active.line);
1280        put_u32(out, active.column);
1281    }
1282}
1283
1284/// Reads back the selections [`encode_selections`] wrote, or None where the bytes are not
1285/// whole selections.
1286pub fn decode_selections(bytes: &[u8]) -> Option<Vec<(Position, Position)>> {
1287    if bytes.len() % SELECTION_LEN != 0 {
1288        return None;
1289    }
1290    Some(
1291        bytes
1292            .chunks_exact(SELECTION_LEN)
1293            .map(|record| {
1294                (
1295                    Position::new(word(record, 0), word(record, 4)),
1296                    Position::new(word(record, 8), word(record, 12)),
1297                )
1298            })
1299            .collect(),
1300    )
1301}
1302
1303/// Every selection of a code editor, as the Renderer reported it: sent while there is more
1304/// than one, and once more when it comes back to one. The first is the primary selection,
1305/// the one `SelectionChange` goes on reporting by itself.
1306#[derive(Clone, Debug, PartialEq, Eq)]
1307pub struct SelectionsChange {
1308    pub version: u32,
1309    /// Each an anchor and an active end.
1310    pub selections: Vec<(Position, Position)>,
1311}
1312
1313impl SelectionsChange {
1314    /// The selections a `SelectionsChanged` event carries, or None for any other event.
1315    pub fn from_payload(payload: &crate::schema::EventPayload<'_>) -> Option<Self> {
1316        match payload {
1317            crate::schema::EventPayload::SelectionsChanged {
1318                version,
1319                selections,
1320            } => Some(Self {
1321                version: *version,
1322                selections: decode_selections(selections)?,
1323            }),
1324            _ => None,
1325        }
1326    }
1327}
1328
1329/// The selection of a code editor, as the Renderer reported it.
1330///
1331/// `anchor` is where the selection started and `active` where the caret is, so a selection
1332/// made backwards has the anchor after the active end. Both are read against `version`,
1333/// the same series [`CodeChange`] counts.
1334#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1335pub struct SelectionChange {
1336    pub version: u32,
1337    pub anchor: Position,
1338    pub active: Position,
1339}
1340
1341impl SelectionChange {
1342    /// Whether nothing is selected and the caret is a single place.
1343    pub fn is_caret(&self) -> bool {
1344        self.anchor == self.active
1345    }
1346
1347    /// The selected stretch, with the earlier end first whichever way it was made.
1348    pub fn range(&self) -> CodeRange {
1349        CodeRange::new(self.anchor.min(self.active), self.anchor.max(self.active))
1350    }
1351}
1352
1353/// The lines of a code editor that are on screen.
1354#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1355pub struct VisibleRange {
1356    pub version: u32,
1357    /// The first line the reader can see.
1358    pub first_line: u32,
1359    /// The last line the reader can see. Lines a fold hides are not counted.
1360    pub last_line: u32,
1361}
1362
1363/// The reader folded or unfolded a stretch of a code editor.
1364#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1365pub struct FoldChange {
1366    /// The line the stretch starts on.
1367    pub start_line: u32,
1368    pub collapsed: bool,
1369}
1370
1371/// The colours of an editor's own parts, each a role of the theme.
1372///
1373/// A part that is not named keeps the colour the design system gives it, so an application
1374/// can set the container and the gutter and leave the rest. Roles and never literals: the
1375/// colours follow the theme from light to dark like every other colour here.
1376#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
1377pub struct CodeEditorColors {
1378    /// What the text sits on.
1379    pub container: Option<ColorRole>,
1380    /// What the line numbers sit on.
1381    pub gutter: Option<ColorRole>,
1382    pub line_number: Option<ColorRole>,
1383    /// The number of the line the caret is on.
1384    pub current_line_number: Option<ColorRole>,
1385    /// The band behind the line the caret is on.
1386    pub current_line: Option<ColorRole>,
1387    /// The gutter beside the line the caret is on, so the band runs across the whole row.
1388    /// Unset, the gutter keeps its own colour on that row.
1389    pub current_line_gutter: Option<ColorRole>,
1390}
1391
1392impl CodeEditorColors {
1393    /// Every part left to the design system.
1394    pub const fn new() -> Self {
1395        Self {
1396            container: None,
1397            gutter: None,
1398            line_number: None,
1399            current_line_number: None,
1400            current_line: None,
1401            current_line_gutter: None,
1402        }
1403    }
1404
1405    pub const fn container(mut self, role: ColorRole) -> Self {
1406        self.container = Some(role);
1407        self
1408    }
1409
1410    pub const fn gutter(mut self, role: ColorRole) -> Self {
1411        self.gutter = Some(role);
1412        self
1413    }
1414
1415    pub const fn line_number(mut self, role: ColorRole) -> Self {
1416        self.line_number = Some(role);
1417        self
1418    }
1419
1420    pub const fn current_line_number(mut self, role: ColorRole) -> Self {
1421        self.current_line_number = Some(role);
1422        self
1423    }
1424
1425    pub const fn current_line(mut self, role: ColorRole) -> Self {
1426        self.current_line = Some(role);
1427        self
1428    }
1429
1430    pub const fn current_line_gutter(mut self, role: ColorRole) -> Self {
1431        self.current_line_gutter = Some(role);
1432        self
1433    }
1434
1435    /// Whether every part is left to the design system, in which case there is nothing to
1436    /// send.
1437    pub fn is_empty(&self) -> bool {
1438        *self == Self::new()
1439    }
1440
1441    /// The record as it travels in the `CodeEditorColors` property.
1442    pub fn to_bytes(&self) -> [u8; CODE_EDITOR_COLORS_LEN] {
1443        let mut bytes = [0_u8; CODE_EDITOR_COLORS_LEN];
1444        let slots = [
1445            self.container,
1446            self.gutter,
1447            self.line_number,
1448            self.current_line_number,
1449            self.current_line,
1450            self.current_line_gutter,
1451        ];
1452        for (index, slot) in slots.into_iter().enumerate() {
1453            let tag = slot.map_or(0, |role| role as u16);
1454            bytes[index * 2..index * 2 + 2].copy_from_slice(&tag.to_le_bytes());
1455        }
1456        bytes
1457    }
1458
1459    /// The record read back. `None` where the bytes are not one whole record or name a
1460    /// role this side does not know, which is what the Renderer refuses too.
1461    pub fn from_bytes(bytes: &[u8]) -> Option<Self> {
1462        if bytes.len() != CODE_EDITOR_COLORS_LEN {
1463            return None;
1464        }
1465        let slot = |index: usize| -> Option<Option<ColorRole>> {
1466            match half(bytes, index * 2) {
1467                0 => Some(None),
1468                tag => ColorRole::try_from(tag).ok().map(Some),
1469            }
1470        };
1471        Some(Self {
1472            container: slot(0)?,
1473            gutter: slot(1)?,
1474            line_number: slot(2)?,
1475            current_line_number: slot(3)?,
1476            current_line: slot(4)?,
1477            current_line_gutter: slot(5)?,
1478        })
1479    }
1480}
1481
1482/// How an editor's rows are drawn, as the Renderer measured them.
1483#[derive(Clone, Copy, Debug, PartialEq)]
1484pub struct CodeMetrics {
1485    /// The height of one row in physical pixels. Every row of an editor has this height,
1486    /// so line `n` starts `n` times this far down when nothing is folded and no lens sits
1487    /// above a line.
1488    pub line_height_px: f64,
1489}
1490
1491/// How far an editor is scrolled.
1492#[derive(Clone, Copy, Debug, PartialEq)]
1493pub struct CodeScroll {
1494    /// The physical pixels of the document above the top of the view. The unit
1495    /// `Batch::set_scroll_offset` takes.
1496    pub offset_px: f64,
1497}
1498
1499/// A rectangle on screen, in the dp the window lays its content out in.
1500///
1501/// The editor's own scroll is already in it, and so is the window's zoom, because the zoom
1502/// is part of what a dp is there. The origin is the top left corner of the window's
1503/// content, which is where an overlay the application opens over the editor is placed
1504/// from, so a suggestion list or a hover card can be put at `x`, `y + height` as it is.
1505#[derive(Clone, Copy, Debug, Default, PartialEq)]
1506pub struct CodeRect {
1507    pub x: f32,
1508    pub y: f32,
1509    pub width: f32,
1510    pub height: f32,
1511}
1512
1513impl CodeRect {
1514    pub const fn new(x: f32, y: f32, width: f32, height: f32) -> Self {
1515        Self {
1516            x,
1517            y,
1518            width,
1519            height,
1520        }
1521    }
1522
1523    /// The bottom edge, which is where a list that opens under the caret starts.
1524    pub fn bottom(&self) -> f32 {
1525        self.y + self.height
1526    }
1527
1528    /// The right edge.
1529    pub fn right(&self) -> f32 {
1530        self.x + self.width
1531    }
1532}
1533
1534/// Where an editor draws its caret, as the Renderer reported it.
1535///
1536/// Sent when the caret moves or the view scrolls, at most once a frame, and only to an
1537/// editor whose application listens for it. The rectangle is the caret itself: as tall as
1538/// a row and as wide as the caret is drawn.
1539#[derive(Clone, Copy, Debug, PartialEq)]
1540pub struct CaretRect {
1541    /// The place in the document the caret stands at.
1542    pub position: Position,
1543    pub rect: CodeRect,
1544}
1545
1546impl CaretRect {
1547    /// The caret's place and rectangle out of a `CaretRect` event, or None for any other.
1548    pub fn from_payload(payload: &crate::schema::EventPayload<'_>) -> Option<Self> {
1549        match *payload {
1550            crate::schema::EventPayload::CaretRect { line, column, rect } => Some(Self {
1551                position: Position::new(line, column),
1552                rect,
1553            }),
1554            _ => None,
1555        }
1556    }
1557}
1558
1559/// What a position query is answered with: the rectangle a caret at that position would be
1560/// drawn in, or None where the position is not on screen.
1561pub type PositionAnswer = Option<CodeRect>;
1562
1563type PositionCallback = Box<dyn FnOnce(PositionAnswer)>;
1564
1565thread_local! {
1566    /// Callbacks waiting for their answer, by request number.
1567    static POSITION_QUERIES: std::cell::RefCell<Vec<(u32, PositionCallback)>> =
1568        const { std::cell::RefCell::new(Vec::new()) };
1569    /// The next request number. 0 is skipped so a zeroed record never looks like a query.
1570    static NEXT_POSITION_QUERY: std::cell::Cell<u32> = const { std::cell::Cell::new(1) };
1571}
1572
1573/// Numbers one question about where a position of an editor is on screen, and keeps
1574/// `on_answer` until the answer arrives.
1575///
1576/// The number goes into the command that asks it, `Batch::query_position_rect`, written by
1577/// whatever holds the editor's node. The Renderer answers every query exactly once, with
1578/// the rectangle a caret at that position would be drawn in, or with None where the
1579/// position is not on screen: scrolled away, folded, outside the document, or in an editor
1580/// that is gone. `on_answer` then runs on the UI thread, inside the call that carried the
1581/// answer, and anything it changes is in the batch that call returns.
1582///
1583/// It is how a hover card, a rename box or a parameter hint is put next to a word that is
1584/// not where the caret is.
1585pub fn position_query(on_answer: impl FnOnce(PositionAnswer) + 'static) -> u32 {
1586    let request = NEXT_POSITION_QUERY.with(|next| {
1587        let mut id = next.get();
1588        if id == 0 {
1589            id = 1;
1590        }
1591        next.set(id.wrapping_add(1));
1592        id
1593    });
1594    POSITION_QUERIES.with_borrow_mut(|waiting| waiting.push((request, Box::new(on_answer))));
1595    request
1596}
1597
1598/// Hands an answer to the callback that asked for it. Returns whether there was one; an
1599/// answer nobody is waiting for any more is ignored.
1600pub(crate) fn deliver_position_rect(request: u32, answer: PositionAnswer) -> bool {
1601    // Taken out before it runs: the callback may ask again, which edits the list.
1602    let callback = POSITION_QUERIES.with_borrow_mut(|waiting| {
1603        waiting
1604            .iter()
1605            .position(|(id, _)| *id == request)
1606            .map(|at| waiting.remove(at).1)
1607    });
1608    match callback {
1609        Some(callback) => {
1610            callback(answer);
1611            true
1612        }
1613        None => false,
1614    }
1615}
1616
1617/// Forgets every query still waiting. Used when a new `Host` takes over the thread: the
1618/// Renderer it talks to has never heard of them.
1619#[doc(hidden)]
1620pub fn reset_position_queries() {
1621    POSITION_QUERIES.with_borrow_mut(Vec::clear);
1622}
1623
1624/// A pointer event over a code editor, with the place in the text under the pointer.
1625///
1626/// Everything a node's pointer event says, under the same rules: the kinds the editor
1627/// subscribes to with `PointerKinds`, the buttons, the modifiers, the click count, a `Move`
1628/// at most once a frame, and a press held by the editor until it is released. Consuming a
1629/// `Down` keeps the caret where it was, which is what Cmd or Ctrl and a click needs to go to
1630/// a definition without moving the reader's caret.
1631#[derive(Clone, Debug)]
1632pub struct CodePointer {
1633    pub event: crate::PointerEvent,
1634    /// The character under the pointer, or None where it is over none: the gutter, past the
1635    /// end of a line, or below the last one.
1636    pub position: Option<Position>,
1637}
1638
1639impl CodePointer {
1640    /// The event out of a `CodePointer` payload, or None for any other.
1641    pub fn from_payload(payload: &crate::schema::EventPayload<'_>) -> Option<Self> {
1642        match *payload {
1643            crate::schema::EventPayload::CodePointer {
1644                kind,
1645                pointer_id,
1646                pointer_type,
1647                x,
1648                y,
1649                buttons,
1650                button,
1651                modifiers,
1652                click_count,
1653                delta_x,
1654                delta_y,
1655                delta_mode,
1656                timestamp_nanos,
1657                position,
1658            } => Some(Self {
1659                event: crate::PointerEvent::new(
1660                    kind,
1661                    pointer_id,
1662                    pointer_type,
1663                    x,
1664                    y,
1665                    buttons,
1666                    button,
1667                    modifiers,
1668                    click_count,
1669                    delta_x,
1670                    delta_y,
1671                    delta_mode,
1672                    timestamp_nanos,
1673                ),
1674                position,
1675            }),
1676            _ => None,
1677        }
1678    }
1679}
1680
1681/// Encodes the edits of one grouped edit the way `EditCodeGroup` carries them, appending to
1682/// `out`.
1683///
1684/// The blob is a `u32` count, then one 24-byte record per edit (the range, then the text's
1685/// offset and length) and then the texts one after another. A text's offset counts from
1686/// the start of the texts, not from the start of the blob. Fails only where a count, a
1687/// length or an offset does not fit a `u32`.
1688pub fn encode_edit_group(
1689    edits: &[(CodeRange, &str)],
1690    out: &mut Vec<u8>,
1691) -> Result<(), crate::protocol::ProtocolError> {
1692    use crate::protocol::ProtocolError;
1693    let count = u32::try_from(edits.len()).map_err(|_| ProtocolError::LengthOverflow)?;
1694    let texts: usize = edits.iter().map(|(_, text)| text.len()).sum();
1695    out.reserve(4 + edits.len() * CODE_EDIT_LEN + texts);
1696    put_u32(out, count);
1697    let mut offset = 0_u32;
1698    for (range, text) in edits {
1699        let len = u32::try_from(text.len()).map_err(|_| ProtocolError::LengthOverflow)?;
1700        put_range(out, *range);
1701        put_u32(out, offset);
1702        put_u32(out, len);
1703        offset = offset
1704            .checked_add(len)
1705            .ok_or(ProtocolError::LengthOverflow)?;
1706    }
1707    for (_, text) in edits {
1708        out.extend_from_slice(text.as_bytes());
1709    }
1710    Ok(())
1711}
1712
1713/// Reads back the edits [`encode_edit_group`] wrote, in the order they were sent.
1714///
1715/// None where the blob is not one: shorter than its count says, a text outside the blob or
1716/// not UTF-8, or bytes after the last text. The Renderer reads it under the same rules and
1717/// answers a blob it cannot read with a protocol error.
1718pub fn decode_edit_group(bytes: &[u8]) -> Option<Vec<(CodeRange, &str)>> {
1719    if bytes.len() < 4 {
1720        return None;
1721    }
1722    let count = word(bytes, 0) as usize;
1723    let texts_start = count.checked_mul(CODE_EDIT_LEN)?.checked_add(4)?;
1724    if texts_start > bytes.len() {
1725        return None;
1726    }
1727    let mut edits = Vec::with_capacity(count);
1728    let mut texts_end = texts_start;
1729    for index in 0..count {
1730        let record = &bytes[4 + index * CODE_EDIT_LEN..4 + (index + 1) * CODE_EDIT_LEN];
1731        let start = texts_start.checked_add(word(record, 16) as usize)?;
1732        let end = start.checked_add(word(record, 20) as usize)?;
1733        let text = std::str::from_utf8(bytes.get(start..end)?).ok()?;
1734        texts_end = texts_end.max(end);
1735        edits.push((range_at(record, 0), text));
1736    }
1737    (texts_end == bytes.len()).then_some(edits)
1738}
1739
1740/// What became of one grouped edit, as the Renderer reported it.
1741///
1742/// Exactly one arrives for every grouped edit that was sent with at least one edit in it,
1743/// after the changes it made. The group went in whole or not at all: `status` is
1744/// `Applied`, or the reason it stayed out, and each reason asks for something different.
1745/// `Rejected`: the reader changed a place the group would have written, so read the
1746/// document again and send the group again. `TooOld`: the version it was written against
1747/// is older than the editor remembers, so bring the application's copy of the document
1748/// back in step first. `Invalid`: the group itself makes no sense.
1749#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1750pub struct EditGroupResult {
1751    /// The id the application gave the group.
1752    pub request_id: u32,
1753    pub status: EditGroupStatus,
1754    /// The version the group was written against, as it was sent.
1755    pub base_version: u32,
1756    /// Where it went in, the version after its last change; where it did not, the version
1757    /// the document is at.
1758    pub current_version: u32,
1759    /// Where it went in, how many edits did; where it did not, the position in the group,
1760    /// as sent, of the edit that kept it out (0 where no one edit did).
1761    pub index: u32,
1762}
1763
1764impl EditGroupResult {
1765    /// The result out of a `CodeEditGroupResult` event, or None for any other.
1766    pub fn from_payload(payload: &crate::schema::EventPayload<'_>) -> Option<Self> {
1767        match *payload {
1768            crate::schema::EventPayload::CodeEditGroupResult {
1769                request_id,
1770                status,
1771                base_version,
1772                current_version,
1773                index,
1774            } => Some(Self {
1775                request_id,
1776                status,
1777                base_version,
1778                current_version,
1779                index,
1780            }),
1781            _ => None,
1782        }
1783    }
1784}