shpool-vterm 0.1.0

An in-memory terminal to support session restore in shpool.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
// The MIT License (MIT)
//
// Copyright (c) 2016 Jesse Luehrs
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

use smallvec::{smallvec, SmallVec};
use std::sync::OnceLock;

// TODO: read all of this from terminfo.
// https://github.com/meh/rust-terminfo/issues/41#issuecomment-3693863276
// might be a good place to start (look into the terminfo-lean crate for
// better licencing).

/// A position within the terminal. Generally, this refers to a grid
/// mode view of the terminal, not the underlying logical lines mode
/// that we actually store the data in.
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub struct Pos {
    pub row: usize,
    pub col: usize,
}

impl Pos {
    /// Ensure that the cursor is within the given region
    /// by moving to the closest edge if it is out of bounds.
    pub fn clamp_to<R>(&mut self, region: R)
    where
        R: Region,
    {
        let (low_row, high_row) = region.row_bounds();
        if self.row < low_row {
            self.row = low_row;
        }
        if self.row >= high_row {
            self.row = high_row - 1;
        }

        let (low_col, high_col) = region.col_bounds();
        if self.col < low_col {
            self.col = low_col;
        }
        if self.col >= high_col {
            self.col = high_col - 1;
        }
    }
}

pub trait Region {
    /// [low, high) bounds on valid rows for this region.
    fn row_bounds(&self) -> (usize, usize);
    /// [low, high) bounds on valid cols for this region.
    fn col_bounds(&self) -> (usize, usize);
}

impl Region for crate::Size {
    fn row_bounds(&self) -> (usize, usize) {
        (0, self.height)
    }
    fn col_bounds(&self) -> (usize, usize) {
        (0, self.width)
    }
}

impl Region for &crate::Size {
    fn row_bounds(&self) -> (usize, usize) {
        (0, self.height)
    }
    fn col_bounds(&self) -> (usize, usize) {
        (0, self.width)
    }
}

#[derive(Debug, Eq, PartialEq, Clone, Default)]
pub enum ScrollRegion {
    #[default]
    TrackSize,
    Window {
        // The start of the scroll region (inclusive, zero indexed).
        top: usize,
        // The end of the scroll region (exclusive, zero indexed). We use
        // a closed open range so this is 1 higher than the actual bottom
        // line included in the scroll region window.
        bottom: usize,
    },
}

impl ScrollRegion {
    pub fn as_region<'a, 'b>(
        &'a self,
        size: &'b crate::Size,
    ) -> (&'a ScrollRegion, &'b crate::Size) {
        (self, size)
    }
}

impl Region for (&ScrollRegion, &crate::Size) {
    fn row_bounds(&self) -> (usize, usize) {
        match self.0 {
            ScrollRegion::TrackSize => (0, self.1.height),
            ScrollRegion::Window { top, bottom } => (*top, *bottom),
        }
    }
    fn col_bounds(&self) -> (usize, usize) {
        (0, self.1.width)
    }
}

impl AsTermInput for ScrollRegion {
    fn term_input_into(&self, buf: &mut Vec<u8>) {
        if let ScrollRegion::Window { top, bottom } = self {
            // We have a zero index [) (clopen) range and we need a 1 indexed
            // [] (fully closed) range, so we need to shift top up, but bottom
            // is already right.
            ControlCodes::set_scroll_region((top + 1) as u16, *bottom as u16).term_input_into(buf);
        }
    }
}

/// OriginMode indicates the origin position for the terminal's
/// coordinate system. OriginMode::Term is the "normal" behavior
/// for the terminal. (1, 1) refers to the upper leftmost cell in
/// the terminal's visible window. In OriginMode::ScrollRegion,
/// (1, 1) referrs to the upper leftmost cell in the currently
/// configured scoll region, if there is one, and the upper leftmost
/// cell in the terminal overall if there is no current scroll region.
///
/// This construct is often referred to as the "DECOM bit."
#[derive(Debug, Eq, PartialEq, Clone, Default, Copy)]
pub enum OriginMode {
    /// (physical_row, physical_col) = (logical_row, logical_col)
    #[default]
    Term,
    /// (physical_row, physical_col) =
    ///     (logical_row + (top_margin - 1), logical_col)
    ScrollRegion,
}

pub trait AsTermInput {
    fn term_input_into(&self, buf: &mut Vec<u8>);
}

#[derive(Debug)]
#[must_use = "this struct does nothing unless you call term_input_into"]
pub struct Raw {
    inner: Vec<u8>,
}

#[allow(dead_code)]
impl Raw {
    pub fn new(inner: Vec<u8>) -> Self {
        Raw { inner }
    }
}

impl std::convert::From<&str> for Raw {
    fn from(value: &str) -> Self {
        Raw { inner: Vec::from(value.as_bytes()) }
    }
}

impl AsTermInput for Raw {
    fn term_input_into(&self, buf: &mut Vec<u8>) {
        buf.extend_from_slice(self.inner.as_slice());
    }
}

#[derive(Default, Debug, Eq, PartialEq, Clone)]
#[must_use = "this struct does nothing unless you call term_input_into"]
pub struct Attrs {
    pub fgcolor: Color,
    pub bgcolor: Color,
    pub font_weight: Option<FontWeight>,
    pub italic: bool,
    pub underline: Option<UnderlineStyle>,
    pub inverse: bool,
    pub blink: Option<BlinkStyle>,
    pub conceal: bool,
    pub strikethrough: bool,
    pub framed: Option<FrameStyle>,
    pub overline: bool,
    // The link this cell points to, if any. Set by OSC 8.
    pub link_target: Option<LinkTarget>,
}

#[derive(Debug, Eq, PartialEq, Clone)]
pub struct LinkTarget {
    pub params: SmallVec<[u8; 8]>,
    pub url: SmallVec<[u8; 8]>,
}

#[derive(Debug, Eq, PartialEq, Clone)]
pub enum UnderlineStyle {
    Single,
    Double,
}

#[derive(Debug, Eq, PartialEq, Clone)]
pub enum FontWeight {
    Bold,
    Faint,
}

#[derive(Debug, Eq, PartialEq, Clone)]
pub enum BlinkStyle {
    Slow,
    Rapid,
}

#[derive(Debug, Eq, PartialEq, Clone)]
pub enum FrameStyle {
    Frame,
    Circle,
}

impl std::fmt::Display for Attrs {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if !matches!(self.fgcolor, Color::Default) {
            write!(f, "<FG {:?}>", self.fgcolor)?;
        }

        if !matches!(self.bgcolor, Color::Default) {
            write!(f, "<BG {:?}>", self.bgcolor)?;
        }

        match self.font_weight {
            Some(FontWeight::Bold) => write!(f, "b")?,
            Some(FontWeight::Faint) => write!(f, "f")?,
            _ => {}
        }
        if self.italic {
            write!(f, "i")?;
        }
        match self.underline {
            Some(UnderlineStyle::Single) => write!(f, "_")?,
            Some(UnderlineStyle::Double) => write!(f, "‗")?,
            _ => {}
        }
        if self.inverse {
            write!(f, "<")?;
        }
        match self.blink {
            Some(BlinkStyle::Slow) => write!(f, "*")?,
            Some(BlinkStyle::Rapid) => write!(f, "!")?,
            _ => {}
        }
        if self.conceal {
            write!(f, "?")?;
        }
        if self.strikethrough {
            write!(f, "-")?;
        }
        match self.framed {
            Some(FrameStyle::Frame) => write!(f, "â–¡")?,
            Some(FrameStyle::Circle) => write!(f, "â—‹")?,
            _ => {}
        }
        if self.overline {
            write!(f, "‾")?;
        }

        if let Some(link_target) = &self.link_target {
            write!(
                f,
                "href({})={}",
                String::from_utf8_lossy(link_target.params.as_slice()),
                String::from_utf8_lossy(&link_target.url)
            )?;
        }

        Ok(())
    }
}

impl Attrs {
    pub fn has_attrs(&self) -> bool {
        !matches!(self.fgcolor, Color::Default)
            || !matches!(self.bgcolor, Color::Default)
            || self.font_weight.is_some()
            || self.italic
            || self.underline.is_some()
            || self.inverse
            || self.blink.is_some()
            || self.conceal
            || self.strikethrough
            || self.framed.is_some()
            || self.overline
            || self.link_target.is_some()
    }

    /// Given another set of attributes, generate the minimal control codes
    /// which will transition the terminal to the other set of attributes
    /// from this one.
    pub fn transition_to(&self, next: &Self) -> Vec<ControlCode> {
        let mut codes = vec![];

        let controls = control_codes();

        if self.fgcolor != next.fgcolor {
            codes.push(next.fgcolor.fgcode());
        }

        if self.bgcolor != next.bgcolor {
            codes.push(next.bgcolor.bgcode());
        }

        if self.italic && !next.italic {
            codes.push(controls.undo_italic.clone());
        } else if !self.italic && next.italic {
            codes.push(controls.italic.clone());
        }

        match (&self.underline, &next.underline) {
            (None, None) => {}
            (Some(_), None) => codes.push(controls.undo_underline.clone()),
            (None, Some(style)) => match style {
                UnderlineStyle::Single => codes.push(controls.underline.clone()),
                UnderlineStyle::Double => codes.push(controls.double_underline.clone()),
            },
            (Some(old), Some(new)) if old == new => {}
            (Some(_), Some(style)) => {
                codes.push(controls.undo_underline.clone());
                match style {
                    UnderlineStyle::Single => codes.push(controls.underline.clone()),
                    UnderlineStyle::Double => codes.push(controls.double_underline.clone()),
                }
            }
        }

        if self.inverse && !next.inverse {
            codes.push(controls.undo_inverse.clone());
        } else if !self.inverse && next.inverse {
            codes.push(controls.inverse.clone());
        }

        match (&self.font_weight, &next.font_weight) {
            (None, None) => {}
            (Some(_), None) => codes.push(controls.reset_font_weight.clone()),
            (None, Some(style)) => match style {
                FontWeight::Bold => codes.push(controls.bold.clone()),
                FontWeight::Faint => codes.push(controls.faint.clone()),
            },
            (Some(old), Some(new)) if old == new => {}
            (Some(_), Some(style)) => {
                codes.push(controls.reset_font_weight.clone());
                match style {
                    FontWeight::Bold => codes.push(controls.bold.clone()),
                    FontWeight::Faint => codes.push(controls.faint.clone()),
                }
            }
        }

        match (&self.blink, &next.blink) {
            (None, None) => {}
            (Some(_), None) => codes.push(controls.undo_blink.clone()),
            (None, Some(style)) => match style {
                BlinkStyle::Slow => codes.push(controls.slow_blink.clone()),
                BlinkStyle::Rapid => codes.push(controls.rapid_blink.clone()),
            },
            (Some(old), Some(new)) if old == new => {}
            (Some(_), Some(style)) => {
                codes.push(controls.undo_blink.clone());
                match style {
                    BlinkStyle::Slow => codes.push(controls.slow_blink.clone()),
                    BlinkStyle::Rapid => codes.push(controls.rapid_blink.clone()),
                }
            }
        }

        if self.conceal && !next.conceal {
            codes.push(controls.undo_conceal.clone());
        } else if !self.conceal && next.conceal {
            codes.push(controls.conceal.clone());
        }

        if self.strikethrough && !next.strikethrough {
            codes.push(controls.undo_strikethrough.clone());
        } else if !self.strikethrough && next.strikethrough {
            codes.push(controls.strikethrough.clone());
        }

        match (&self.framed, &next.framed) {
            (None, None) => {}
            (Some(_), None) => codes.push(controls.undo_framed.clone()),
            (None, Some(style)) => match style {
                FrameStyle::Frame => codes.push(controls.framed.clone()),
                FrameStyle::Circle => codes.push(controls.encircled.clone()),
            },
            (Some(old), Some(new)) if old == new => {}
            (Some(_), Some(style)) => {
                codes.push(controls.undo_framed.clone());
                match style {
                    FrameStyle::Frame => codes.push(controls.framed.clone()),
                    FrameStyle::Circle => codes.push(controls.encircled.clone()),
                }
            }
        }

        if self.overline && !next.overline {
            codes.push(controls.undo_overline.clone());
        } else if !self.overline && next.overline {
            codes.push(controls.overline.clone());
        }

        match (&self.link_target, &next.link_target) {
            (None, None) => {}
            (Some(_), None) => codes.push(controls.end_link.clone()),
            (None, Some(target)) => {
                codes.push(ControlCodes::start_link(target.params.clone(), target.url.clone()))
            }
            (Some(old), Some(new)) if old == new => {}
            (Some(_), Some(new)) => {
                codes.push(controls.end_link.clone());
                codes.push(ControlCodes::start_link(new.params.clone(), new.url.clone()));
            }
        }

        ControlCode::fuse_csi(codes)
    }
}

// A dictionary of standard control codes. Access codes via the
// control_codes() function. Most are constant struct members.
// Codes with dynamic params are generated on the fly via methods.
#[allow(dead_code)]
pub struct ControlCodes {
    pub clear_screen: ControlCode,
    pub clear_attrs: ControlCode,
    pub fgcolor_default: ControlCode,
    pub bgcolor_default: ControlCode,
    pub underline: ControlCode,
    pub double_underline: ControlCode,
    pub undo_underline: ControlCode,
    pub bold: ControlCode,
    pub faint: ControlCode,
    pub reset_font_weight: ControlCode,
    pub italic: ControlCode,
    pub undo_italic: ControlCode,
    pub inverse: ControlCode,
    pub undo_inverse: ControlCode,
    pub slow_blink: ControlCode,
    pub rapid_blink: ControlCode,
    pub undo_blink: ControlCode,
    pub conceal: ControlCode,
    pub undo_conceal: ControlCode,
    pub strikethrough: ControlCode,
    pub undo_strikethrough: ControlCode,
    pub framed: ControlCode,
    pub encircled: ControlCode,
    pub undo_framed: ControlCode,
    pub overline: ControlCode,
    pub undo_overline: ControlCode,
    pub save_cursor_position: ControlCode,
    pub restore_cursor_position: ControlCode,
    pub save_cursor: ControlCode,
    pub restore_cursor: ControlCode,
    pub insert_character: ControlCode,
    pub delete_character: ControlCode,
    pub enable_alt_screen: ControlCode,
    pub disable_alt_screen: ControlCode,
    pub erase_to_end: ControlCode,
    pub erase_from_start: ControlCode,
    pub erase_screen: ControlCode,
    pub erase_scrollback: ControlCode,
    pub erase_to_end_of_line: ControlCode,
    pub erase_to_start_of_line: ControlCode,
    pub erase_line: ControlCode,
    pub device_status_report: ControlCode,
    pub unset_scroll_region: ControlCode,
    pub enable_scroll_region_origin_mode: ControlCode,
    pub disable_scroll_region_origin_mode: ControlCode,
    pub end_link: ControlCode,
    pub show_cursor: ControlCode,
    pub hide_cursor: ControlCode,
    pub enable_application_keypad_mode: ControlCode,
    pub disable_application_keypad_mode: ControlCode,
    pub enable_paste_mode: ControlCode,
    pub disable_paste_mode: ControlCode,
}

#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum ControlCode {
    OSC {
        params: SmallVec<[SmallVec<[u8; 8]>; 2]>,
        term: OSCTerm,
    },
    CSI {
        params: SmallVec<[SmallVec<[u16; 4]>; 2]>,
        intermediates: SmallVec<[u8; 8]>,
        action: char,
    },
    ESC {
        intermediates: SmallVec<[u8; 8]>,
        byte: u8,
    },
    __NonExhaustive,
}

#[derive(Clone, Debug, Default, Eq, PartialEq)]
#[allow(dead_code)]
pub enum OSCTerm {
    #[default]
    St,
    Bel,
}

// Assertions proving that we are using no more memory than needed with the
// capacity. A smallvec is internally a discriminated union, so there is a
// minimum size from the variant where the vector is boxed (which takes at least
// a machine word in the enum part).
static_assertions::const_assert!(
    (std::mem::size_of::<SmallVec<[u8; 8]>>() == std::mem::size_of::<SmallVec<[u8; 1]>>())
        || std::mem::size_of::<usize>() != 8
);
static_assertions::const_assert!(
    (std::mem::size_of::<SmallVec<[u16; 4]>>() == std::mem::size_of::<SmallVec<[u16; 1]>>())
        || std::mem::size_of::<usize>() != 8
);

impl AsTermInput for ControlCode {
    fn term_input_into(&self, buf: &mut Vec<u8>) {
        match self {
            ControlCode::OSC { params, term } => {
                buf.extend_from_slice(b"\x1b]"); // OSC
                for (i, param) in params.iter().enumerate() {
                    if i != 0 {
                        buf.push(b';');
                    }
                    buf.extend_from_slice(param);
                }
                term.term_input_into(buf);
            }
            ControlCode::CSI { params, intermediates, action } => {
                buf.extend_from_slice(b"\x1b["); // CSI
                buf.extend_from_slice(intermediates);

                for (i, param) in params.iter().enumerate() {
                    if i != 0 {
                        buf.push(b';');
                    }

                    for (j, subparam) in param.iter().enumerate() {
                        if j != 0 {
                            buf.push(b':');
                        }
                        extend_itoa(buf, *subparam);
                    }
                }

                let mut action_buf = [0; 4];
                buf.extend_from_slice(action.encode_utf8(&mut action_buf).as_bytes());
            }
            ControlCode::ESC { intermediates, byte } => {
                buf.extend_from_slice(b"\x1b"); // ESC
                buf.extend_from_slice(intermediates);
                buf.push(*byte);
            }
            _ => {}
        }
    }
}

impl AsTermInput for OSCTerm {
    fn term_input_into(&self, buf: &mut Vec<u8>) {
        match self {
            OSCTerm::St => buf.extend_from_slice(b"\x1b\\"),
            OSCTerm::Bel => buf.push(b'\x07'),
        }
    }
}

impl std::fmt::Display for ControlCode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ControlCode::CSI { params, intermediates, action } => {
                write!(f, "CSI ")?;
                for intermediate in intermediates {
                    write!(f, "{} ", *intermediate as char)?;
                }
                for (i, param) in params.iter().enumerate() {
                    if i != 0 {
                        write!(f, "; ")?;
                    }
                    for (j, subparam) in param.iter().enumerate() {
                        if j != 0 {
                            write!(f, ": ")?;
                        }
                        write!(f, "{} ", subparam)?;
                    }
                }
                write!(f, "{}", action)?;
            }
            ControlCode::ESC { intermediates, byte } => {
                write!(f, "ESC ")?;
                for intermediate in intermediates {
                    write!(f, "{} ", *intermediate as char)?;
                }
                write!(f, "{}", byte)?;
            }
            _ => write!(f, "<display unimpl>")?,
        }

        Ok(())
    }
}

impl ControlCode {
    fn fuse_csi<I>(control_codes: I) -> Vec<Self>
    where
        I: IntoIterator<Item = Self>,
    {
        let mut fused_codes = vec![];
        let mut current_params = smallvec![];
        let mut current_intermediates = smallvec![];
        let mut current_action = None;
        for code in control_codes.into_iter() {
            if let ControlCode::CSI { params, intermediates, action } = code {
                if let Some(cur_action) = current_action {
                    if cur_action == action && current_intermediates == intermediates {
                        current_params.extend(params);
                    } else {
                        fused_codes.push(ControlCode::CSI {
                            params: std::mem::take(&mut current_params),
                            intermediates: std::mem::take(&mut current_intermediates),
                            action: cur_action,
                        });
                        current_action = Some(action);
                        current_intermediates = intermediates;
                        current_params = params;
                    }
                } else {
                    current_action = Some(action);
                    current_intermediates = intermediates;
                    current_params.extend(params);
                }
            } else {
                if let Some(action) = current_action {
                    fused_codes.push(ControlCode::CSI {
                        params: std::mem::take(&mut current_params),
                        intermediates: std::mem::take(&mut current_intermediates),
                        action,
                    });
                    current_action = None;
                }
                fused_codes.push(code);
            }
        }

        if let Some(action) = current_action {
            fused_codes.push(ControlCode::CSI {
                params: std::mem::take(&mut current_params),
                intermediates: std::mem::take(&mut current_intermediates),
                action,
            })
        }

        fused_codes
    }
}

static CONTROL_CODES: OnceLock<ControlCodes> = OnceLock::new();

pub fn control_codes() -> &'static ControlCodes {
    CONTROL_CODES.get_or_init(|| ControlCodes {
        clear_screen: ControlCode::CSI {
            params: smallvec![],
            intermediates: smallvec![],
            action: 'J',
        },
        clear_attrs: ControlCode::CSI {
            params: smallvec![],
            intermediates: smallvec![],
            action: 'm',
        },
        fgcolor_default: ControlCode::CSI {
            params: smallvec![smallvec![39]],
            intermediates: smallvec![],
            action: 'm',
        },
        bgcolor_default: ControlCode::CSI {
            params: smallvec![smallvec![49]],
            intermediates: smallvec![],
            action: 'm',
        },
        underline: ControlCode::CSI {
            params: smallvec![smallvec![4]],
            intermediates: smallvec![],
            action: 'm',
        },
        double_underline: ControlCode::CSI {
            params: smallvec![smallvec![21]],
            intermediates: smallvec![],
            action: 'm',
        },
        undo_underline: ControlCode::CSI {
            params: smallvec![smallvec![24]],
            intermediates: smallvec![],
            action: 'm',
        },
        bold: ControlCode::CSI {
            params: smallvec![smallvec![1]],
            intermediates: smallvec![],
            action: 'm',
        },
        faint: ControlCode::CSI {
            params: smallvec![smallvec![2]],
            intermediates: smallvec![],
            action: 'm',
        },
        reset_font_weight: ControlCode::CSI {
            params: smallvec![smallvec![22]],
            intermediates: smallvec![],
            action: 'm',
        },
        italic: ControlCode::CSI {
            params: smallvec![smallvec![3]],
            intermediates: smallvec![],
            action: 'm',
        },
        undo_italic: ControlCode::CSI {
            params: smallvec![smallvec![23]],
            intermediates: smallvec![],
            action: 'm',
        },
        inverse: ControlCode::CSI {
            params: smallvec![smallvec![7]],
            intermediates: smallvec![],
            action: 'm',
        },
        undo_inverse: ControlCode::CSI {
            params: smallvec![smallvec![27]],
            intermediates: smallvec![],
            action: 'm',
        },
        slow_blink: ControlCode::CSI {
            params: smallvec![smallvec![5]],
            intermediates: smallvec![],
            action: 'm',
        },
        rapid_blink: ControlCode::CSI {
            params: smallvec![smallvec![6]],
            intermediates: smallvec![],
            action: 'm',
        },
        undo_blink: ControlCode::CSI {
            params: smallvec![smallvec![25]],
            intermediates: smallvec![],
            action: 'm',
        },
        conceal: ControlCode::CSI {
            params: smallvec![smallvec![8]],
            intermediates: smallvec![],
            action: 'm',
        },
        undo_conceal: ControlCode::CSI {
            params: smallvec![smallvec![28]],
            intermediates: smallvec![],
            action: 'm',
        },
        strikethrough: ControlCode::CSI {
            params: smallvec![smallvec![9]],
            intermediates: smallvec![],
            action: 'm',
        },
        undo_strikethrough: ControlCode::CSI {
            params: smallvec![smallvec![29]],
            intermediates: smallvec![],
            action: 'm',
        },
        framed: ControlCode::CSI {
            params: smallvec![smallvec![51]],
            intermediates: smallvec![],
            action: 'm',
        },
        encircled: ControlCode::CSI {
            params: smallvec![smallvec![52]],
            intermediates: smallvec![],
            action: 'm',
        },
        undo_framed: ControlCode::CSI {
            params: smallvec![smallvec![54]],
            intermediates: smallvec![],
            action: 'm',
        },
        overline: ControlCode::CSI {
            params: smallvec![smallvec![53]],
            intermediates: smallvec![],
            action: 'm',
        },
        undo_overline: ControlCode::CSI {
            params: smallvec![smallvec![55]],
            intermediates: smallvec![],
            action: 'm',
        },
        save_cursor_position: ControlCode::CSI {
            params: smallvec![],
            intermediates: smallvec![],
            action: 's',
        },
        restore_cursor_position: ControlCode::CSI {
            params: smallvec![],
            intermediates: smallvec![],
            action: 'u',
        },
        save_cursor: ControlCode::ESC { intermediates: smallvec![], byte: b'7' },
        restore_cursor: ControlCode::ESC { intermediates: smallvec![], byte: b'8' },
        insert_character: ControlCode::CSI {
            params: smallvec![smallvec![1]],
            intermediates: smallvec![],
            action: '@',
        },
        delete_character: ControlCode::CSI {
            params: smallvec![smallvec![1]],
            intermediates: smallvec![],
            action: 'P',
        },
        enable_alt_screen: ControlCode::CSI {
            params: smallvec![smallvec![1049]],
            intermediates: smallvec![b'?'],
            action: 'h',
        },
        disable_alt_screen: ControlCode::CSI {
            params: smallvec![smallvec![1049]],
            intermediates: smallvec![b'?'],
            action: 'l',
        },
        erase_to_end: ControlCode::CSI {
            params: smallvec![smallvec![0]],
            intermediates: smallvec![],
            action: 'J',
        },
        erase_from_start: ControlCode::CSI {
            params: smallvec![smallvec![1]],
            intermediates: smallvec![],
            action: 'J',
        },
        erase_screen: ControlCode::CSI {
            params: smallvec![smallvec![2]],
            intermediates: smallvec![],
            action: 'J',
        },
        erase_scrollback: ControlCode::CSI {
            params: smallvec![smallvec![3]],
            intermediates: smallvec![],
            action: 'J',
        },
        erase_to_end_of_line: ControlCode::CSI {
            params: smallvec![smallvec![0]],
            intermediates: smallvec![],
            action: 'K',
        },
        erase_to_start_of_line: ControlCode::CSI {
            params: smallvec![smallvec![1]],
            intermediates: smallvec![],
            action: 'K',
        },
        erase_line: ControlCode::CSI {
            params: smallvec![smallvec![2]],
            intermediates: smallvec![],
            action: 'K',
        },
        device_status_report: ControlCode::CSI {
            params: smallvec![smallvec![6]],
            intermediates: smallvec![],
            action: 'n',
        },
        unset_scroll_region: ControlCode::CSI {
            params: smallvec![],
            intermediates: smallvec![],
            action: 'r',
        },
        enable_scroll_region_origin_mode: ControlCode::CSI {
            params: smallvec![smallvec![6]],
            intermediates: smallvec![b'?'],
            action: 'h',
        },
        disable_scroll_region_origin_mode: ControlCode::CSI {
            params: smallvec![smallvec![6]],
            intermediates: smallvec![b'?'],
            action: 'l',
        },
        end_link: ControlCode::OSC { params: smallvec![smallvec![b'8']], term: OSCTerm::default() },
        show_cursor: ControlCode::CSI {
            params: smallvec![smallvec![25]],
            intermediates: smallvec![b'?'],
            action: 'h',
        },
        hide_cursor: ControlCode::CSI {
            params: smallvec![smallvec![25]],
            intermediates: smallvec![b'?'],
            action: 'l',
        },
        enable_application_keypad_mode: ControlCode::CSI {
            params: smallvec![smallvec![1]],
            intermediates: smallvec![b'?'],
            action: 'h',
        },
        disable_application_keypad_mode: ControlCode::CSI {
            params: smallvec![smallvec![1]],
            intermediates: smallvec![b'?'],
            action: 'l',
        },
        enable_paste_mode: ControlCode::CSI {
            params: smallvec![smallvec![2004]],
            intermediates: smallvec![b'?'],
            action: 'h',
        },
        disable_paste_mode: ControlCode::CSI {
            params: smallvec![smallvec![2004]],
            intermediates: smallvec![b'?'],
            action: 'l',
        },
    })
}

#[allow(dead_code)]
impl ControlCodes {
    pub fn fgcolor_idx(i: u8) -> ControlCode {
        if i < 8 {
            ControlCode::CSI {
                params: smallvec![smallvec![(i + 30) as u16]],
                intermediates: smallvec![],
                action: 'm',
            }
        } else if i < 16 {
            ControlCode::CSI {
                params: smallvec![smallvec![(i + 82) as u16]],
                intermediates: smallvec![],
                action: 'm',
            }
        } else {
            ControlCode::CSI {
                params: smallvec![smallvec![38], smallvec![5], smallvec![i as u16]],
                intermediates: smallvec![],
                action: 'm',
            }
        }
    }

    pub fn fgcolor_rgb(r: u8, g: u8, b: u8) -> ControlCode {
        ControlCode::CSI {
            params: smallvec![
                smallvec![38],
                smallvec![2],
                smallvec![r as u16],
                smallvec![g as u16],
                smallvec![b as u16]
            ],
            intermediates: smallvec![],
            action: 'm',
        }
    }

    pub fn bgcolor_idx(i: u8) -> ControlCode {
        if i < 8 {
            ControlCode::CSI {
                params: smallvec![smallvec![(i + 40) as u16]],
                intermediates: smallvec![],
                action: 'm',
            }
        } else if i < 16 {
            ControlCode::CSI {
                params: smallvec![smallvec![(i + 92) as u16]],
                intermediates: smallvec![],
                action: 'm',
            }
        } else {
            ControlCode::CSI {
                params: smallvec![smallvec![48], smallvec![5], smallvec![i as u16]],
                intermediates: smallvec![],
                action: 'm',
            }
        }
    }

    pub fn bgcolor_rgb(r: u8, g: u8, b: u8) -> ControlCode {
        ControlCode::CSI {
            params: smallvec![
                smallvec![48],
                smallvec![2],
                smallvec![r as u16],
                smallvec![g as u16],
                smallvec![b as u16]
            ],
            intermediates: smallvec![],
            action: 'm',
        }
    }

    pub fn cursor_up(n: u16) -> ControlCode {
        Self::move_cursor(n, 'A')
    }

    pub fn cursor_down(n: u16) -> ControlCode {
        Self::move_cursor(n, 'B')
    }

    pub fn cursor_forward(n: u16) -> ControlCode {
        Self::move_cursor(n, 'C')
    }

    pub fn cursor_backwards(n: u16) -> ControlCode {
        Self::move_cursor(n, 'D')
    }

    pub fn cursor_next_line(n: u16) -> ControlCode {
        Self::move_cursor(n, 'E')
    }

    pub fn cursor_prev_line(n: u16) -> ControlCode {
        Self::move_cursor(n, 'F')
    }

    pub fn cursor_position(row: u16, col: u16) -> ControlCode {
        if row == 1 && col == 1 {
            ControlCode::CSI { params: smallvec![], intermediates: smallvec![], action: 'H' }
        } else {
            ControlCode::CSI {
                params: smallvec![smallvec![row], smallvec![col]],
                intermediates: smallvec![],
                action: 'H',
            }
        }
    }

    pub fn cursor_horizontal_absolute(col: u16) -> ControlCode {
        ControlCode::CSI {
            params: smallvec![smallvec![col]],
            intermediates: smallvec![],
            action: 'G',
        }
    }

    fn move_cursor(n: u16, action: char) -> ControlCode {
        if n == 1 {
            ControlCode::CSI { params: smallvec![], intermediates: smallvec![], action }
        } else {
            ControlCode::CSI { params: smallvec![smallvec![n]], intermediates: smallvec![], action }
        }
    }

    pub fn scroll_up(n: u16) -> ControlCode {
        if n == 1 {
            ControlCode::CSI { params: smallvec![], intermediates: smallvec![], action: 'S' }
        } else {
            ControlCode::CSI {
                params: smallvec![smallvec![n]],
                intermediates: smallvec![],
                action: 'S',
            }
        }
    }

    pub fn scroll_down(n: u16) -> ControlCode {
        if n == 1 {
            ControlCode::CSI { params: smallvec![], intermediates: smallvec![], action: 'T' }
        } else {
            ControlCode::CSI {
                params: smallvec![smallvec![n]],
                intermediates: smallvec![],
                action: 'T',
            }
        }
    }

    pub fn insert_lines(n: u16) -> ControlCode {
        if n == 1 {
            ControlCode::CSI { params: smallvec![], intermediates: smallvec![], action: 'L' }
        } else {
            ControlCode::CSI {
                params: smallvec![smallvec![n]],
                intermediates: smallvec![],
                action: 'L',
            }
        }
    }

    pub fn delete_lines(n: u16) -> ControlCode {
        if n == 1 {
            ControlCode::CSI { params: smallvec![], intermediates: smallvec![], action: 'M' }
        } else {
            ControlCode::CSI {
                params: smallvec![smallvec![n]],
                intermediates: smallvec![],
                action: 'M',
            }
        }
    }

    pub fn insert_character(n: u16) -> ControlCode {
        if n == 1 {
            ControlCode::CSI { params: smallvec![], intermediates: smallvec![], action: '@' }
        } else {
            ControlCode::CSI {
                params: smallvec![smallvec![n]],
                intermediates: smallvec![],
                action: '@',
            }
        }
    }

    pub fn delete_character(n: u16) -> ControlCode {
        if n == 1 {
            ControlCode::CSI { params: smallvec![], intermediates: smallvec![], action: 'P' }
        } else {
            ControlCode::CSI {
                params: smallvec![smallvec![n]],
                intermediates: smallvec![],
                action: 'P',
            }
        }
    }

    /// 1-indexed, inclusive on both ends (closed, closed).
    pub fn set_scroll_region(top: u16, bottom: u16) -> ControlCode {
        ControlCode::CSI {
            params: smallvec![smallvec![top], smallvec![bottom]],
            intermediates: smallvec![],
            action: 'r',
        }
    }

    pub fn set_title_and_icon_name(title: SmallVec<[u8; 8]>) -> ControlCode {
        ControlCode::OSC { params: smallvec![smallvec![b'0'], title], term: OSCTerm::default() }
    }

    pub fn set_icon_name(icon_name: SmallVec<[u8; 8]>) -> ControlCode {
        ControlCode::OSC { params: smallvec![smallvec![b'1'], icon_name], term: OSCTerm::default() }
    }

    pub fn set_title(title: SmallVec<[u8; 8]>) -> ControlCode {
        ControlCode::OSC { params: smallvec![smallvec![b'2'], title], term: OSCTerm::default() }
    }

    pub fn set_working_dir(host: SmallVec<[u8; 8]>, dir: SmallVec<[u8; 8]>) -> ControlCode {
        ControlCode::OSC { params: smallvec![smallvec![b'7'], host, dir], term: OSCTerm::default() }
    }

    pub fn start_link(params: SmallVec<[u8; 8]>, url: SmallVec<[u8; 8]>) -> ControlCode {
        ControlCode::OSC {
            params: smallvec![smallvec![b'8'], params, url,],
            term: OSCTerm::default(),
        }
    }

    pub fn set_color_indices<I>(indices: I) -> ControlCode
    where
        I: IntoIterator<Item = (usize, SmallVec<[u8; 8]>)>,
    {
        let mut params = smallvec![smallvec![b'4']];
        for (idx, spec) in indices {
            params.push(SmallVec::from(format!("{idx}").as_bytes()));
            params.push(spec);
        }
        ControlCode::OSC { params, term: OSCTerm::default() }
    }

    pub fn reset_color_indices<I>(indices: I) -> ControlCode
    where
        I: IntoIterator<Item = usize>,
    {
        let mut params = smallvec![smallvec![b'1', b'0', b'4']];
        for idx in indices {
            params.push(SmallVec::from(format!("{idx}").as_bytes()));
        }
        ControlCode::OSC { params, term: OSCTerm::default() }
    }

    pub fn set_functional_color<'a, I>(offset: usize, specs: I) -> ControlCode
    where
        I: IntoIterator<Item = &'a [u8]>,
    {
        let mut params = smallvec![smallvec![b'1', b'0' + offset as u8]];
        for spec in specs {
            params.push(SmallVec::from(spec));
        }
        ControlCode::OSC { params, term: OSCTerm::default() }
    }
}

/// Represents a foreground or background color for cells.
#[derive(Eq, PartialEq, Debug, Copy, Clone, Default)]
#[allow(dead_code)]
pub enum Color {
    /// The default terminal color.
    #[default]
    Default,

    /// An indexed terminal color.
    Idx(u8),

    /// An RGB terminal color. The parameters are (red, green, blue).
    Rgb(u8, u8, u8),
}

impl Color {
    fn bgcode(&self) -> ControlCode {
        match self {
            Color::Default => control_codes().bgcolor_default.clone(),
            Color::Idx(i) => ControlCodes::bgcolor_idx(*i),
            Color::Rgb(r, g, b) => ControlCodes::bgcolor_rgb(*r, *g, *b),
        }
    }

    fn fgcode(&self) -> ControlCode {
        match self {
            Color::Default => control_codes().fgcolor_default.clone(),
            Color::Idx(i) => ControlCodes::fgcolor_idx(*i),
            Color::Rgb(r, g, b) => ControlCodes::fgcolor_rgb(*r, *g, *b),
        }
    }
}

#[derive(Default, Debug)]
#[must_use = "this struct does nothing unless you call term_input_into"]
pub struct Crlf;

impl AsTermInput for Crlf {
    fn term_input_into(&self, buf: &mut Vec<u8>) {
        buf.extend_from_slice(b"\r\n");
    }
}

fn extend_itoa<I: itoa::Integer>(buf: &mut Vec<u8>, i: I) {
    let mut itoa_buf = itoa::Buffer::new();
    buf.extend_from_slice(itoa_buf.format(i).as_bytes());
}