1use crate::schema::{
22 ColorRole, DecorationKind, EditGroupStatus, GutterDecorationKind, HoverPhase, Paint, Severity,
23};
24use std::rc::Rc;
25
26pub const DECORATION_LEN: usize = 44;
28
29pub const SYNTAX_SPAN_LEN: usize = 28;
31
32pub const CODE_EDIT_LEN: usize = 24;
35
36#[derive(Clone, Copy, Debug, Eq, PartialEq)]
38pub enum RecordFieldType {
39 U32,
40 U64,
41 Role {
44 name: &'static str,
45 optional: bool,
46 },
47 Paint,
49 Flag,
51 F32,
53 Text,
56}
57
58#[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#[derive(Clone, Copy, Debug, Eq, PartialEq)]
71pub struct RecordSchema {
72 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
82pub 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
123pub 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
137pub const FOLD_LEN: usize = 16;
139
140pub const GUTTER_DECORATION_LEN: usize = 28;
142
143pub 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
157pub 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
187pub 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
201pub 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
217pub const CONTENT_PADDING_LEN: usize = 8;
220
221#[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 pub fn is_empty(&self) -> bool {
237 self.top_dp == 0.0 && self.bottom_dp == 0.0
238 }
239
240 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 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
262pub const VIEW_ZONE_LEN: usize = 16;
264
265pub 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
287pub(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#[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#[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 pub const fn at(position: Position) -> Self {
342 Self {
343 start: position,
344 end: position,
345 }
346 }
347
348 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#[derive(Clone, Debug, PartialEq)]
367pub struct Decoration {
368 pub version: u32,
370 pub kind: DecorationKind,
371 pub severity: Option<Severity>,
373 pub color: Option<ColorRole>,
376 pub range: CodeRange,
377 pub id: u64,
380 pub text: String,
382}
383
384impl Decoration {
385 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 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 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 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 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 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 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 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#[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 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 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 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#[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 pub const fn role(version: u32, range: CodeRange, role: ColorRole) -> Self {
682 Self::new(version, range, Paint::Role(role))
683 }
684}
685
686#[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 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
743pub 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#[derive(Clone, Debug, PartialEq)]
785pub struct CodeChange {
786 pub version: u32,
787 pub range: CodeRange,
788 pub text: String,
789}
790
791impl CodeChange {
792 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#[derive(Clone, Copy, Debug, Eq, PartialEq)]
816pub struct EditRejected {
817 pub request_id: u32,
819 pub base_version: u32,
820 pub current_version: u32,
822 pub range: CodeRange,
824}
825
826#[derive(Clone, Copy, Debug, Eq, PartialEq)]
832pub struct CodeHover {
833 pub decoration: Option<u64>,
835 pub position: Position,
836 pub phase: HoverPhase,
837}
838
839#[derive(Clone, Copy, Debug, Eq, PartialEq)]
844pub struct SaveRequest {
845 pub version: u32,
847}
848
849#[derive(Clone, Copy, Debug, Eq, PartialEq)]
851pub struct Fold {
852 pub version: u32,
854 pub start_line: u32,
856 pub end_line: u32,
859 pub collapsed: bool,
860}
861
862impl Fold {
863 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 pub const fn collapsed(mut self) -> Self {
875 self.collapsed = true;
876 self
877 }
878}
879
880#[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 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#[derive(Clone, Copy, Debug, Eq, PartialEq)]
949pub struct GutterDecoration {
950 pub version: u32,
952 pub line: u32,
953 pub kind: GutterDecorationKind,
954 pub color: Option<ColorRole>,
955 pub id: u64,
958 pub glyph: u32,
960}
961
962impl GutterDecoration {
963 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 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 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 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#[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 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#[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 pub fn with_text(mut self, text: impl Into<String>) -> Self {
1109 self.text = text.into();
1110 self
1111 }
1112}
1113
1114#[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 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 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 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
1201pub 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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1222pub enum WordWrap {
1223 #[default]
1225 Off,
1226 Viewport,
1228 Column(u32),
1230 Bounded(u32),
1232}
1233
1234impl WordWrap {
1235 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 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
1268pub const SELECTION_LEN: usize = 16;
1271
1272pub 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
1284pub 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#[derive(Clone, Debug, PartialEq, Eq)]
1307pub struct SelectionsChange {
1308 pub version: u32,
1309 pub selections: Vec<(Position, Position)>,
1311}
1312
1313impl SelectionsChange {
1314 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#[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 pub fn is_caret(&self) -> bool {
1344 self.anchor == self.active
1345 }
1346
1347 pub fn range(&self) -> CodeRange {
1349 CodeRange::new(self.anchor.min(self.active), self.anchor.max(self.active))
1350 }
1351}
1352
1353#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1355pub struct VisibleRange {
1356 pub version: u32,
1357 pub first_line: u32,
1359 pub last_line: u32,
1361}
1362
1363#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1365pub struct FoldChange {
1366 pub start_line: u32,
1368 pub collapsed: bool,
1369}
1370
1371#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
1377pub struct CodeEditorColors {
1378 pub container: Option<ColorRole>,
1380 pub gutter: Option<ColorRole>,
1382 pub line_number: Option<ColorRole>,
1383 pub current_line_number: Option<ColorRole>,
1385 pub current_line: Option<ColorRole>,
1387 pub current_line_gutter: Option<ColorRole>,
1390}
1391
1392impl CodeEditorColors {
1393 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 pub fn is_empty(&self) -> bool {
1438 *self == Self::new()
1439 }
1440
1441 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 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#[derive(Clone, Copy, Debug, PartialEq)]
1484pub struct CodeMetrics {
1485 pub line_height_px: f64,
1489}
1490
1491#[derive(Clone, Copy, Debug, PartialEq)]
1493pub struct CodeScroll {
1494 pub offset_px: f64,
1497}
1498
1499#[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 pub fn bottom(&self) -> f32 {
1525 self.y + self.height
1526 }
1527
1528 pub fn right(&self) -> f32 {
1530 self.x + self.width
1531 }
1532}
1533
1534#[derive(Clone, Copy, Debug, PartialEq)]
1540pub struct CaretRect {
1541 pub position: Position,
1543 pub rect: CodeRect,
1544}
1545
1546impl CaretRect {
1547 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
1559pub type PositionAnswer = Option<CodeRect>;
1562
1563type PositionCallback = Box<dyn FnOnce(PositionAnswer)>;
1564
1565thread_local! {
1566 static POSITION_QUERIES: std::cell::RefCell<Vec<(u32, PositionCallback)>> =
1568 const { std::cell::RefCell::new(Vec::new()) };
1569 static NEXT_POSITION_QUERY: std::cell::Cell<u32> = const { std::cell::Cell::new(1) };
1571}
1572
1573pub 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
1598pub(crate) fn deliver_position_rect(request: u32, answer: PositionAnswer) -> bool {
1601 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#[doc(hidden)]
1620pub fn reset_position_queries() {
1621 POSITION_QUERIES.with_borrow_mut(Vec::clear);
1622}
1623
1624#[derive(Clone, Debug)]
1632pub struct CodePointer {
1633 pub event: crate::PointerEvent,
1634 pub position: Option<Position>,
1637}
1638
1639impl CodePointer {
1640 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
1681pub 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
1713pub 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#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1750pub struct EditGroupResult {
1751 pub request_id: u32,
1753 pub status: EditGroupStatus,
1754 pub base_version: u32,
1756 pub current_version: u32,
1759 pub index: u32,
1762}
1763
1764impl EditGroupResult {
1765 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}