retach 0.10.0

Persistent terminal sessions with native scrollback passthrough
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
use unicode_width::UnicodeWidthChar;
use vte::{Params, Perform};

use super::cell::Cell;
use super::grid::{ActiveCharset, Charset, CursorShape, Grid, MouseEncoding, TerminalModes};
use super::style::{Style, StyleId};
use super::ScreenState;

/// Truncate to at most `max_bytes`, never splitting a UTF-8 char.
///
/// `&s[..max_bytes]` panics if `max_bytes` is not a char boundary; this
/// backs off to the nearest boundary at or below the limit.
fn truncate_at_char_boundary(s: &str, max_bytes: usize) -> &str {
    if s.len() <= max_bytes {
        return s;
    }
    let mut end = max_bytes;
    while !s.is_char_boundary(end) {
        end -= 1;
    }
    &s[..end]
}

/// Maximum combining marks (diacritics, etc.) attached to a single base character.
/// Unicode NFC normalization typically produces 0-3 marks; 16 handles extreme
/// cases (e.g. Zalgo text) without unbounded allocation per cell.
const MAX_COMBINING: usize = 16;

/// VTE `Perform` implementation that translates escape sequences into grid mutations.
pub(super) struct ScreenPerformer<'a> {
    pub(super) grid: &'a mut Grid,
    pub(super) state: &'a mut ScreenState,
}

impl<'a> ScreenPerformer<'a> {
    /// Intern a style, triggering GC if the table is full and retrying.
    fn intern_with_gc(&mut self, style: Style) -> StyleId {
        let id = self.grid.style_table_mut().intern(style);
        if id.is_default() && !style.is_default() && self.grid.style_table().is_full() {
            self.grid.compact_styles(self.state.saved_grid.as_ref());
            self.grid.style_table_mut().intern(style)
        } else {
            id
        }
    }

    /// Blank cell with current background color (BCE — Background Color Erase)
    fn blank_cell(&mut self) -> Cell {
        let style = Style {
            bg: self.state.current_style.bg,
            ..Style::default()
        };
        let id = self.intern_with_gc(style);
        Cell::new(' ', id, 1)
    }

    fn scroll_up(&mut self) {
        let fill = self.blank_cell();
        self.grid.scroll_up(self.state.in_alt_screen, fill);
    }

    fn scroll_up_no_capture(&mut self) {
        let fill = self.blank_cell();
        self.grid.scroll_up_no_capture(fill);
    }

    fn scroll_down(&mut self) {
        let fill = self.blank_cell();
        self.grid.scroll_down(fill);
    }

    /// Map a character through the active DEC charset (line drawing)
    fn map_charset(&self, c: char) -> char {
        let charset = match self.grid.modes().active_charset {
            ActiveCharset::G0 => self.grid.modes().g0_charset,
            ActiveCharset::G1 => self.grid.modes().g1_charset,
        };
        match charset {
            Charset::LineDrawing => match c {
                'j' => '',
                'k' => '',
                'l' => '',
                'm' => '',
                'n' => '',
                'q' => '',
                't' => '',
                'u' => '',
                'v' => '',
                'w' => '',
                'x' => '',
                'a' => '',
                '`' => '',
                _ => c,
            },
            Charset::Ascii => c,
        }
    }

    /// Save full cursor state: position, style, charsets, autowrap mode, wrap_pending.
    /// Used by CSI s, ESC 7, and mode 1048h.
    fn save_cursor(&mut self) {
        self.state.saved_cursor_state = Some(super::SavedCursor {
            x: self.grid.cursor_x(),
            y: self.grid.cursor_y(),
            style: self.state.current_style,
            g0_charset: self.grid.modes().g0_charset,
            g1_charset: self.grid.modes().g1_charset,
            active_charset: self.grid.modes().active_charset,
            autowrap_mode: self.grid.modes().autowrap_mode,
            origin_mode: self.grid.modes().origin_mode,
            wrap_pending: self.grid.wrap_pending(),
        });
    }

    /// Restore full cursor state saved by [`save_cursor`].
    /// Used by CSI u, ESC 8, and mode 1048l.
    fn restore_cursor(&mut self) {
        if let Some(ref saved) = self.state.saved_cursor_state {
            let x = saved.x.min(self.grid.cols() - 1);
            let y = saved.y.min(self.grid.rows() - 1);
            let style = saved.style;
            let g0 = saved.g0_charset;
            let g1 = saved.g1_charset;
            let active = saved.active_charset;
            let autowrap = saved.autowrap_mode;
            let origin = saved.origin_mode;
            let wrap_pending = saved.wrap_pending;
            self.grid.set_wrap_pending(wrap_pending);
            self.grid.set_cursor_x_unclamped(x);
            self.grid.set_cursor_y_unclamped(y);
            self.state.current_style = style;
            self.grid.modes_mut().g0_charset = g0;
            self.grid.modes_mut().g1_charset = g1;
            self.grid.modes_mut().active_charset = active;
            self.grid.modes_mut().autowrap_mode = autowrap;
            self.grid.modes_mut().origin_mode = origin;
        }
    }

    /// Enter alt screen: save grid/modes/scroll-region, clear screen, reset cursor and scroll region.
    /// If `save_cursor` is true, also save cursor state (mode 1049).
    /// Ignored if already in alt screen (prevents overwriting the saved main screen).
    fn enter_alt_screen(&mut self, save_cursor: bool) {
        if self.state.in_alt_screen {
            return;
        }
        if save_cursor {
            self.save_cursor();
        }
        use super::grid::SavedGrid;
        // Save main screen scroll region before overwriting it.
        self.state.saved_scroll_region = Some((self.grid.scroll_top(), self.grid.scroll_bottom()));
        // Save visible rows; scrollback stays in the active grid
        let saved_visible = self.grid.drain_visible();
        let scrollback_limit = self.grid.scrollback_limit();
        self.state.saved_grid = Some(SavedGrid::new(saved_visible, scrollback_limit));
        // Create blank visible rows for alt screen
        self.grid.fill_visible_blank();
        self.grid.set_scrollback_limit(0);
        self.state.saved_modes = Some(self.grid.modes().clone());
        self.state.in_alt_screen = true;
        self.grid.set_cursor_x_unclamped(0);
        self.grid.set_cursor_y_unclamped(0);
        self.grid.reset_scroll_region();
        self.grid.set_wrap_pending(false);
    }

    /// Exit alt screen: restore grid/modes, reset scroll region.
    /// If `restore_cursor` is true, also restore cursor state (mode 1049).
    /// Ignored if not currently in alt screen.
    fn exit_alt_screen(&mut self, do_restore_cursor: bool) {
        if !self.state.in_alt_screen {
            return;
        }
        self.state.in_alt_screen = false;
        if let Some(saved) = self.state.saved_grid.take() {
            // Remove alt screen visible rows, restore saved visible rows
            let (visible_cells, scrollback_limit) = saved.into_parts();
            self.grid.replace_visible(visible_cells);
            self.grid.set_scrollback_limit(scrollback_limit);
            // Adjust visible rows for current dimensions (may have resized during alt screen)
            self.grid.adjust_visible_to_fit();
            let cols_usize = self.grid.cols() as usize;
            for y in 0..self.grid.visible_row_count() {
                self.grid
                    .visible_row_mut(y)
                    .fix_wide_char_orphan_at_boundary(cols_usize);
                self.grid
                    .visible_row_mut(y)
                    .resize(cols_usize, Cell::default());
            }
        }
        if let Some(modes) = self.state.saved_modes.take() {
            self.grid.set_modes(modes);
        }
        if do_restore_cursor {
            self.restore_cursor();
        }
        // Restore the main screen scroll region saved on alt screen entry.
        // Fallback to full-screen reset if somehow missing (defensive).
        if let Some(sr) = self.state.saved_scroll_region.take() {
            let bottom_max = self.grid.rows().saturating_sub(1);
            let top = sr.0.min(bottom_max);
            let bottom = sr.1.min(bottom_max).max(top);
            self.grid.set_scroll_region(top, bottom);
        } else {
            self.grid.reset_scroll_region();
        }

        // Compact styles after alt screen — apps like vim/htop create
        // many unique styles that become dead when returning to main screen.
        self.grid.compact_styles(None);
    }

    // --- CSI command methods ---

    fn csi_cursor_up(&mut self, n: u16) {
        self.grid.set_wrap_pending(false);
        let top = if self.grid.cursor_y() >= self.grid.scroll_top() {
            self.grid.scroll_top()
        } else {
            0
        };
        self.grid
            .set_cursor_y_unclamped(self.grid.cursor_y().saturating_sub(n).max(top));
    }

    fn csi_cursor_down(&mut self, n: u16) {
        self.grid.set_wrap_pending(false);
        let bottom = if self.grid.cursor_y() <= self.grid.scroll_bottom() {
            self.grid.scroll_bottom()
        } else {
            self.grid.rows() - 1
        };
        self.grid
            .set_cursor_y_unclamped(self.grid.cursor_y().saturating_add(n).min(bottom));
    }

    fn csi_cursor_forward(&mut self, n: u16) {
        self.grid.set_wrap_pending(false);
        self.grid.set_cursor_x_unclamped(
            self.grid
                .cursor_x()
                .saturating_add(n)
                .min(self.grid.cols() - 1),
        );
    }

    fn csi_cursor_back(&mut self, n: u16) {
        self.grid.set_wrap_pending(false);
        self.grid
            .set_cursor_x_unclamped(self.grid.cursor_x().saturating_sub(n));
    }

    fn csi_cursor_next_line(&mut self, n: u16) {
        self.grid.set_wrap_pending(false);
        self.grid.set_cursor_x_unclamped(0);
        let bottom = if self.grid.cursor_y() <= self.grid.scroll_bottom() {
            self.grid.scroll_bottom()
        } else {
            self.grid.rows() - 1
        };
        self.grid
            .set_cursor_y_unclamped(self.grid.cursor_y().saturating_add(n).min(bottom));
    }

    fn csi_cursor_prev_line(&mut self, n: u16) {
        self.grid.set_wrap_pending(false);
        self.grid.set_cursor_x_unclamped(0);
        let top = if self.grid.cursor_y() >= self.grid.scroll_top() {
            self.grid.scroll_top()
        } else {
            0
        };
        self.grid
            .set_cursor_y_unclamped(self.grid.cursor_y().saturating_sub(n).max(top));
    }

    fn csi_cursor_horizontal_absolute(&mut self, col: u16) {
        self.grid.set_wrap_pending(false);
        self.grid
            .set_cursor_x_unclamped(col.saturating_sub(1).min(self.grid.cols() - 1));
    }

    fn csi_cursor_position(&mut self, row: u16, col: u16) {
        self.grid.set_wrap_pending(false);
        if self.grid.modes().origin_mode {
            let top = self.grid.scroll_top();
            let bottom = self.grid.scroll_bottom();
            self.grid
                .set_cursor_y_unclamped(top.saturating_add(row.saturating_sub(1)).min(bottom));
        } else {
            self.grid
                .set_cursor_y_unclamped(row.saturating_sub(1).min(self.grid.rows() - 1));
        }
        self.grid
            .set_cursor_x_unclamped(col.saturating_sub(1).min(self.grid.cols() - 1));
    }

    fn csi_line_position_absolute(&mut self, row: u16) {
        self.grid.set_wrap_pending(false);
        if self.grid.modes().origin_mode {
            let top = self.grid.scroll_top();
            let bottom = self.grid.scroll_bottom();
            self.grid
                .set_cursor_y_unclamped(top.saturating_add(row.saturating_sub(1)).min(bottom));
        } else {
            self.grid
                .set_cursor_y_unclamped(row.saturating_sub(1).min(self.grid.rows() - 1));
        }
    }

    fn csi_erase_display(&mut self, mode: u16) {
        let blank = self.blank_cell();
        match mode {
            0 => {
                let y = self.grid.cursor_y() as usize;
                let x = self.grid.cursor_x() as usize;
                let cols = self.grid.cols() as usize;
                self.grid.erase_cells(y, x, cols, blank);
                self.grid
                    .erase_rows(y + 1, self.grid.rows() as usize, blank);
            }
            1 => {
                let y = self.grid.cursor_y() as usize;
                let x = self.grid.cursor_x() as usize;
                self.grid.erase_rows(0, y, blank);
                let end = (x + 1).min(self.grid.cols() as usize);
                self.grid.erase_cells(y, 0, end, blank);
            }
            2 => {
                self.grid.erase_rows(0, self.grid.rows() as usize, blank);
            }
            3 => {
                // ED 3 = Erase Saved Lines (xterm): scrollback only, visible screen untouched
                self.grid.clear_scrollback();
                // Forward to outer terminal so it clears its native scrollback too
                self.state.push_passthrough(b"\x1b[3J".to_vec());
            }
            _ => {}
        }
    }

    fn csi_erase_line(&mut self, mode: u16) {
        let blank = self.blank_cell();
        let y = self.grid.cursor_y() as usize;
        let x = self.grid.cursor_x() as usize;
        match mode {
            0 => {
                let cols = self.grid.cols() as usize;
                self.grid.erase_cells(y, x, cols, blank);
            }
            1 => {
                let end = (x + 1).min(self.grid.cols() as usize);
                self.grid.erase_cells(y, 0, end, blank);
            }
            2 => {
                self.grid
                    .erase_cells(y, 0, self.grid.cols() as usize, blank);
            }
            _ => {}
        }
    }

    fn csi_erase_character(&mut self, n: u16) {
        let blank = self.blank_cell();
        let n = n as usize;
        let y = self.grid.cursor_y() as usize;
        let x = self.grid.cursor_x() as usize;
        if y < self.grid.rows() as usize {
            let end = (x + n).min(self.grid.cols() as usize);
            self.grid.erase_cells(y, x, end, blank);
        }
    }

    fn csi_delete_character(&mut self, n: u16) {
        let blank = self.blank_cell();
        let n = n as usize;
        let y = self.grid.cursor_y() as usize;
        let x = self.grid.cursor_x() as usize;
        let cols = self.grid.cols() as usize;
        if y < self.grid.rows() as usize {
            self.grid.fixup_wide_char_at(x, y);
            let delete_count = n.min(cols.saturating_sub(x));
            for _ in 0..delete_count {
                self.grid.visible_row_mut(y).remove(x);
                self.grid.visible_row_mut(y).push(blank);
            }
            // Fix orphaned continuation cell(s) that shifted into position x
            if x < cols && self.grid.visible_row(y)[x].width == 0 {
                self.grid.visible_row_mut(y)[x] = blank;
                self.grid.visible_row_mut(y).clear_combining(x as u16);
                // If the continuation was part of a wide char whose first half
                // is also now at x-1 as an orphan, fixup_wide_char handles it
                // but we already blanked position x, so the base at x-1 with
                // width==2 now has no continuation — blank it too.
                if x > 0 && self.grid.visible_row(y)[x - 1].width == 2 {
                    self.grid.visible_row_mut(y)[x - 1] = blank;
                    self.grid.visible_row_mut(y).clear_combining((x - 1) as u16);
                }
            }
        }
    }

    fn csi_insert_character(&mut self, n: u16) {
        let blank = self.blank_cell();
        let n = n as usize;
        let y = self.grid.cursor_y() as usize;
        let x = self.grid.cursor_x() as usize;
        let cols = self.grid.cols() as usize;
        if y < self.grid.rows() as usize {
            self.grid.fixup_wide_char_at(x, y);
            for _ in 0..n.min(cols.saturating_sub(x)) {
                self.grid.visible_row_mut(y).pop();
                self.grid.visible_row_mut(y).insert(x, blank);
            }
            let last = cols - 1;
            if self.grid.visible_row(y)[last].width == 2 {
                self.grid.visible_row_mut(y)[last] = blank;
                self.grid.visible_row_mut(y).clear_combining(last as u16);
            } else if self.grid.visible_row(y)[last].width == 0 {
                // Orphaned continuation cell: its base was pushed off-screen
                self.grid.visible_row_mut(y)[last] = blank;
                self.grid.visible_row_mut(y).clear_combining(last as u16);
                if last > 0 && self.grid.visible_row(y)[last - 1].width == 2 {
                    self.grid.visible_row_mut(y)[last - 1] = blank;
                    self.grid
                        .visible_row_mut(y)
                        .clear_combining((last - 1) as u16);
                }
            }
        }
    }

    fn csi_scroll_up_n(&mut self, n: u16) {
        let n = n.min(self.grid.rows());
        for _ in 0..n {
            self.scroll_up_no_capture();
        }
    }

    fn csi_scroll_down_n(&mut self, n: u16) {
        let n = n.min(self.grid.rows());
        for _ in 0..n {
            self.scroll_down();
        }
    }

    fn csi_delete_lines(&mut self, n: u16) {
        let blank = self.blank_cell();
        let n = n as usize;
        let y = self.grid.cursor_y() as usize;
        let top = self.grid.scroll_top() as usize;
        let bottom = self.grid.scroll_bottom() as usize;
        if y >= top && y <= bottom {
            self.grid.set_wrap_pending(false);
            let n = n.min(bottom - y + 1);
            for _ in 0..n {
                if y <= bottom && bottom < self.grid.visible_row_count() {
                    self.grid.remove_visible_row(y);
                    self.grid
                        .insert_visible_row(bottom, self.grid.new_blank_row(blank));
                }
            }
        }
    }

    fn csi_insert_lines(&mut self, n: u16) {
        let blank = self.blank_cell();
        let n = n as usize;
        let y = self.grid.cursor_y() as usize;
        let top = self.grid.scroll_top() as usize;
        let bottom = self.grid.scroll_bottom() as usize;
        if y >= top && y <= bottom {
            self.grid.set_wrap_pending(false);
            let n = n.min(bottom - y + 1);
            for _ in 0..n {
                if y <= bottom && bottom < self.grid.visible_row_count() {
                    self.grid.remove_visible_row(bottom);
                    self.grid
                        .insert_visible_row(y, self.grid.new_blank_row(blank));
                }
            }
        }
    }

    fn csi_set_scrolling_region(&mut self, top: u16, bottom: u16) {
        let top = top.saturating_sub(1);
        let bottom = bottom.saturating_sub(1).min(self.grid.rows() - 1);
        if top <= bottom {
            self.grid.set_scroll_region(top, bottom);
            self.grid.set_cursor_x_unclamped(0);
            if self.grid.modes().origin_mode {
                self.grid.set_cursor_y_unclamped(top);
            } else {
                self.grid.set_cursor_y_unclamped(0);
            }
            self.grid.set_wrap_pending(false);
        }
    }

    /// Attach a zero-width combining mark to the previous cell.
    fn handle_combining_mark(&mut self, c: char) {
        let cx = self.grid.cursor_x() as usize;
        let cy = self.grid.cursor_y() as usize;
        if cy >= self.grid.rows() as usize {
            return;
        }
        let tx = if self.grid.wrap_pending() {
            cx
        } else if cx > 0 {
            cx - 1
        } else {
            return;
        };
        if tx >= self.grid.cols() as usize {
            return;
        }
        let tx = if self.grid.visible_row(cy)[tx].width == 0 && tx > 0 {
            tx - 1
        } else {
            tx
        };
        if self.grid.visible_row(cy).combining_len(tx as u16) < MAX_COMBINING {
            self.grid.visible_row_mut(cy).push_combining(tx as u16, c);
        }
    }

    /// Execute a deferred line wrap: advance to column 0 of the next row,
    /// scrolling if at the bottom of the scroll region.
    fn perform_deferred_wrap(&mut self) {
        self.grid.set_wrap_pending(false);
        self.grid.set_cursor_x_unclamped(0);
        if self.grid.cursor_y() == self.grid.scroll_bottom() {
            self.scroll_up();
        } else if self.grid.cursor_y() < self.grid.rows() - 1 {
            self.grid.set_cursor_y_unclamped(self.grid.cursor_y() + 1);
        }
    }

    /// Standard (non-DEC-private) mode set/reset — `CSI Pn h` / `CSI Pn l`.
    fn csi_set_mode(&mut self, ps: &[Vec<u16>], enable: bool) {
        for param in ps {
            // IRM (mode 4): insert/replace. Other standard modes are not implemented.
            if param.first().copied() == Some(4) {
                self.grid.modes_mut().insert_mode = enable;
            }
        }
    }

    fn csi_set_dec_private_mode(&mut self, ps: &[Vec<u16>], enable: bool) {
        for param in ps {
            match param.first().copied() {
                Some(1) => self.grid.modes_mut().cursor_key_mode = enable,
                Some(6) => {
                    self.grid.modes_mut().origin_mode = enable;
                    if enable {
                        self.grid.set_cursor_x_unclamped(0);
                        self.grid.set_cursor_y_unclamped(self.grid.scroll_top());
                        self.grid.set_wrap_pending(false);
                    }
                }
                Some(7) => self.grid.modes_mut().autowrap_mode = enable,
                Some(12) => {} // Cursor blink — cosmetic, ignore
                Some(25) => self.grid.set_cursor_visible(enable),
                Some(1000 | 1002 | 1003) => {
                    self.grid.modes_mut().mouse_modes.set(param[0], enable);
                }
                Some(1005 | 1006) => {
                    self.grid.modes_mut().mouse_encoding = if enable {
                        MouseEncoding::from_param(param[0]).unwrap_or(MouseEncoding::X10)
                    } else {
                        MouseEncoding::X10
                    };
                }
                Some(1004) => self.grid.modes_mut().focus_reporting = enable,
                Some(1048) => {
                    if enable {
                        self.save_cursor();
                    } else {
                        self.restore_cursor();
                    }
                }
                Some(2004) => self.grid.modes_mut().bracketed_paste = enable,
                Some(1049) => {
                    if enable {
                        self.enter_alt_screen(true);
                    } else {
                        self.exit_alt_screen(true);
                    }
                }
                Some(1047 | 47) => {
                    if enable {
                        self.enter_alt_screen(false);
                    } else {
                        self.exit_alt_screen(false);
                    }
                }
                _ => {}
            }
        }
    }
}

impl<'a> Perform for ScreenPerformer<'a> {
    fn print(&mut self, c: char) {
        self.state.last_printed_char = c; // Save pre-map char for REP
        let c = self.map_charset(c);
        let char_width = UnicodeWidthChar::width(c).unwrap_or(0) as u16;

        if char_width == 0 {
            self.handle_combining_mark(c);
            return;
        }

        if self.grid.wrap_pending() && self.grid.modes().autowrap_mode {
            self.perform_deferred_wrap();
        }

        // Wide char at end of line: fill margin cell with space and wrap
        if char_width == 2 && self.grid.cursor_x() >= self.grid.cols() - 1 {
            if self.grid.modes().autowrap_mode {
                if self.grid.cols() < 2 {
                    return;
                }
                let x = self.grid.cursor_x() as usize;
                let y = self.grid.cursor_y() as usize;
                if x < self.grid.cols() as usize && y < self.grid.rows() as usize {
                    let blank = self.blank_cell();
                    self.grid.visible_row_mut(y)[x] = blank;
                }
                self.perform_deferred_wrap();
            } else {
                return;
            }
        }

        let x = self.grid.cursor_x() as usize;
        let y = self.grid.cursor_y() as usize;
        if x < self.grid.cols() as usize && y < self.grid.rows() as usize {
            // IRM (insert mode): make room by shifting existing cells right,
            // so typing at the start of a line pushes text over instead of overwriting it.
            if self.grid.modes().insert_mode {
                self.csi_insert_character(char_width);
            }
            let sid = self.intern_with_gc(self.state.current_style);
            self.grid
                .set_cell(x, y, Cell::new(c, sid, char_width as u8));

            let new_x = self.grid.cursor_x() + char_width;
            if new_x >= self.grid.cols() {
                self.grid.set_cursor_x_unclamped(self.grid.cols() - 1);
                if self.grid.modes().autowrap_mode {
                    self.grid.set_wrap_pending(true);
                }
            } else {
                self.grid.set_cursor_x_unclamped(new_x);
            }
        }
    }

    fn execute(&mut self, byte: u8) {
        match byte {
            0x0D => {
                // CR
                self.grid.set_cursor_x_unclamped(0);
                self.grid.set_wrap_pending(false);
            }
            0x0A..=0x0C => {
                // LF, VT, FF — all treated as line feed
                self.grid.set_wrap_pending(false);
                if self.grid.cursor_y() == self.grid.scroll_bottom() {
                    self.scroll_up();
                } else if self.grid.cursor_y() < self.grid.rows() - 1 {
                    self.grid.set_cursor_y_unclamped(self.grid.cursor_y() + 1);
                }
            }
            0x08 => {
                // BS
                self.grid.set_wrap_pending(false);
                if self.grid.cursor_x() > 0 {
                    self.grid.set_cursor_x_unclamped(self.grid.cursor_x() - 1);
                }
            }
            0x09 => {
                // Tab
                self.grid.set_wrap_pending(false);
                let cur_x = self.grid.cursor_x();
                let next = self.grid.next_tab_stop(cur_x);
                self.grid.set_cursor_x_unclamped(next);
            }
            0x0E => {
                // SO — Shift Out (activate G1)
                self.grid.modes_mut().active_charset = ActiveCharset::G1;
            }
            0x0F => {
                // SI — Shift In (activate G0)
                self.grid.modes_mut().active_charset = ActiveCharset::G0;
            }
            0x07 => {
                // Bell — forward to outer terminal
                self.state.push_passthrough(vec![0x07]);
            }
            _ => {}
        }
    }

    fn csi_dispatch(&mut self, params: &Params, intermediates: &[u8], _ignore: bool, action: char) {
        let ps: Vec<Vec<u16>> = params.iter().map(|p| p.to_vec()).collect();
        let p = |i: usize, default: u16| -> u16 {
            ps.get(i)
                .and_then(|v| v.first().copied())
                .filter(|&v| v != 0)
                .unwrap_or(default)
        };

        match action {
            'A' => self.csi_cursor_up(p(0, 1)),
            'B' => self.csi_cursor_down(p(0, 1)),
            'C' => self.csi_cursor_forward(p(0, 1)),
            'D' => self.csi_cursor_back(p(0, 1)),
            'E' => self.csi_cursor_next_line(p(0, 1)),
            'F' => self.csi_cursor_prev_line(p(0, 1)),
            'G' => self.csi_cursor_horizontal_absolute(p(0, 1)),
            'H' | 'f' => self.csi_cursor_position(p(0, 1), p(1, 1)),
            'd' => self.csi_line_position_absolute(p(0, 1)),
            'J' => self.csi_erase_display(p(0, 0)),
            'K' => self.csi_erase_line(p(0, 0)),
            'X' => self.csi_erase_character(p(0, 1)),
            'P' => self.csi_delete_character(p(0, 1)),
            '@' => self.csi_insert_character(p(0, 1)),
            'b' => {
                let c = self.state.last_printed_char;
                for _ in 0..p(0, 1) {
                    self.print(c);
                }
            }
            'm' if intermediates.is_empty() => self.state.current_style.apply_sgr(&ps),
            'n' if intermediates.is_empty() => match p(0, 0) {
                5 => {
                    // DSR — Device Status Report: reply "terminal OK"
                    self.state.push_response(b"\x1b[0n".to_vec());
                }
                6 => {
                    use super::style::write_u16;
                    let mut r = Vec::with_capacity(16);
                    r.extend_from_slice(b"\x1b[");
                    let row = if self.grid.modes().origin_mode {
                        self.grid.cursor_y().saturating_sub(self.grid.scroll_top()) + 1
                    } else {
                        self.grid.cursor_y() + 1
                    };
                    write_u16(&mut r, row);
                    r.push(b';');
                    write_u16(&mut r, self.grid.cursor_x() + 1);
                    r.push(b'R');
                    self.state.push_response(r);
                }
                _ => {}
            },
            'c' => {
                if intermediates.is_empty() {
                    if p(0, 0) == 0 {
                        // Primary DA: VT220 (62) with ANSI color (22).
                        self.state.push_response(b"\x1b[?62;22c".to_vec());
                    }
                } else if intermediates == b">" && p(0, 0) == 0 {
                    self.state.push_response(b"\x1b[>0;10;1c".to_vec());
                }
            }
            'q' if intermediates == b" " => {
                self.grid.modes_mut().cursor_shape = CursorShape::from_param(p(0, 0) as u8)
            }
            'S' => self.csi_scroll_up_n(p(0, 1)),
            'T' if ps.len() <= 1 => self.csi_scroll_down_n(p(0, 1)),
            'M' => self.csi_delete_lines(p(0, 1)),
            'L' => self.csi_insert_lines(p(0, 1)),
            'r' if intermediates.is_empty() => {
                self.csi_set_scrolling_region(p(0, 1), p(1, self.grid.rows()))
            }
            's' if intermediates.is_empty() => self.save_cursor(),
            'u' if intermediates.is_empty() => self.restore_cursor(),
            'g' if intermediates.is_empty() => {
                // TBC — Tab Clear
                match p(0, 0) {
                    0 => {
                        // Clear tab stop at cursor
                        self.grid.clear_tab_stop(self.grid.cursor_x());
                    }
                    3 => {
                        // Clear all tab stops
                        self.grid.clear_all_tab_stops();
                    }
                    _ => {}
                }
            }
            't' => {
                let cmd = p(0, 0);
                let scope = p(1, 0);
                match cmd {
                    22 if scope == 0 || scope == 2 => {
                        if self.state.title_stack.len() < 16 {
                            let mut t = self.state.title.clone();
                            // Safe: `title` was stored via
                            // truncate_at_char_boundary(…, 4096), so it is
                            // already ≤4096 bytes and this truncate is a
                            // no-op kept as a defensive bound. (String::
                            // truncate would panic on a non-boundary index.)
                            t.truncate(4096);
                            self.state.title_stack.push(t);
                        }
                    }
                    23 if scope == 0 || scope == 2 => {
                        if let Some(title) = self.state.title_stack.pop() {
                            self.state.title = title;
                        }
                    }
                    _ => {}
                }
            }
            'h' | 'l' if intermediates == b"?" => self.csi_set_dec_private_mode(&ps, action == 'h'),
            'h' | 'l' if intermediates.is_empty() => self.csi_set_mode(&ps, action == 'h'),
            _ => {}
        }
    }

    fn esc_dispatch(&mut self, intermediates: &[u8], _ignore: bool, byte: u8) {
        match (intermediates, byte) {
            ([], b'H') => {
                // HTS — Horizontal Tab Set
                self.grid.set_tab_stop(self.grid.cursor_x());
            }
            ([], b'D') => {
                // IND — Index (scroll up at bottom margin)
                self.grid.set_wrap_pending(false);
                if self.grid.cursor_y() == self.grid.scroll_bottom() {
                    self.scroll_up();
                } else if self.grid.cursor_y() < self.grid.rows() - 1 {
                    self.grid.set_cursor_y_unclamped(self.grid.cursor_y() + 1);
                }
            }
            ([], b'E') => {
                // NEL — Next Line (CR + LF)
                self.grid.set_cursor_x_unclamped(0);
                self.grid.set_wrap_pending(false);
                if self.grid.cursor_y() == self.grid.scroll_bottom() {
                    self.scroll_up();
                } else if self.grid.cursor_y() < self.grid.rows() - 1 {
                    self.grid.set_cursor_y_unclamped(self.grid.cursor_y() + 1);
                }
            }
            ([], b'M') => {
                // RI — Reverse Index (scroll down at top margin)
                self.grid.set_wrap_pending(false);
                if self.grid.cursor_y() == self.grid.scroll_top() {
                    self.scroll_down();
                } else if self.grid.cursor_y() > 0 {
                    self.grid.set_cursor_y_unclamped(self.grid.cursor_y() - 1);
                }
            }
            ([], b'7') => self.save_cursor(), // DECSC — Save Cursor
            ([], b'8') => self.restore_cursor(), // DECRC — Restore Cursor
            ([], b'c') => {
                // RIS — Full Reset
                self.grid.set_cursor_x_unclamped(0);
                self.grid.set_cursor_y_unclamped(0);
                self.grid.reset_scroll_region();
                self.grid.set_cursor_visible(true);
                self.grid.set_wrap_pending(false);
                self.grid.set_modes(TerminalModes::default());
                self.state.current_style = Style::default();
                // Restore scrollback_limit before discarding saved_grid —
                // alt screen entry sets it to 0, and the original is saved
                // inside SavedGrid. Without this, RIS during alt screen
                // permanently kills scrollback capture.
                if let Some(ref saved) = self.state.saved_grid {
                    self.grid.set_scrollback_limit(saved.scrollback_limit());
                }
                self.state.in_alt_screen = false;
                self.state.saved_grid = None;
                self.state.saved_modes = None;
                self.state.saved_cursor_state = None;
                self.state.saved_scroll_region = None;
                self.state.title.clear();
                self.state.title_stack.clear();
                self.state.last_printed_char = ' ';
                self.grid.reset_tab_stops();
                self.grid.style_table_mut().reset();
                self.grid
                    .erase_rows(0, self.grid.rows() as usize, Cell::default());
                // Clear scrollback (real terminals do this on RIS)
                self.grid.clear_scrollback();
                // Forward \e[3J to clear outer terminal's native scrollback.
                // We don't forward \ec itself — that would reset the outer
                // terminal's state and interfere with retach's rendering.
                self.state.push_passthrough(b"\x1b[3J".to_vec());
            }
            ([], b'=') => {
                // DECKPAM — Keypad Application Mode
                self.grid.modes_mut().keypad_app_mode = true;
            }
            ([], b'>') => {
                // DECKPNM — Keypad Numeric Mode
                self.grid.modes_mut().keypad_app_mode = false;
            }
            ([b'('], b'B') => {
                self.grid.modes_mut().g0_charset = Charset::Ascii;
            }
            ([b'('], b'0') => {
                self.grid.modes_mut().g0_charset = Charset::LineDrawing;
            }
            ([b')'], b'B') => {
                self.grid.modes_mut().g1_charset = Charset::Ascii;
            }
            ([b')'], b'0') => {
                self.grid.modes_mut().g1_charset = Charset::LineDrawing;
            }
            ([b'#'], b'8') => {
                // DECALN — Screen Alignment Pattern
                self.grid.reset_scroll_region();
                self.grid.set_cursor_x_unclamped(0);
                self.grid.set_cursor_y_unclamped(0);
                self.grid.set_wrap_pending(false);
                let sid = self.intern_with_gc(Style::default());
                let e_cell = Cell::new('E', sid, 1);
                for y in 0..self.grid.rows() as usize {
                    for x in 0..self.grid.cols() as usize {
                        self.grid.set_cell(x, y, e_cell);
                    }
                }
            }
            _ => {}
        }
    }

    fn osc_dispatch(&mut self, params: &[&[u8]], bell_terminated: bool) {
        if params.is_empty() {
            return;
        }
        // params[0] is the OSC number as bytes
        let osc_num = std::str::from_utf8(params[0])
            .ok()
            .and_then(|s| s.parse::<u16>().ok());

        // Set window title (OSC 0 / OSC 2) — handled locally
        if let Some(0 | 2) = osc_num {
            if params.len() >= 2 {
                if let Ok(title) = std::str::from_utf8(params[1]) {
                    // Char-boundary-safe: a plain `title[..4096]` byte slice
                    // panics on multi-byte UTF-8 straddling the limit. Today
                    // vte's default `no_std` feature caps OSC data at 1024
                    // bytes, but any crate enabling vte/`std` removes that
                    // cap (cargo feature unification), so guard here.
                    self.state.title = truncate_at_char_boundary(title, 4096).to_string();
                }
            }
            return;
        }

        // All other OSC sequences: reconstruct and forward to the outer terminal.
        // This covers notifications (777, 9), clipboard (52), hyperlinks (8), etc.
        let mut buf = Vec::new();
        buf.extend_from_slice(b"\x1b]");
        for (i, param) in params.iter().enumerate() {
            if i > 0 {
                buf.push(b';');
            }
            buf.extend_from_slice(param);
        }
        if bell_terminated {
            buf.push(0x07); // BEL terminator
        } else {
            buf.extend_from_slice(b"\x1b\\"); // ST terminator
        }
        // Text notifications go to a separate consumable queue so they are
        // delivered exactly once (by the relay or on reconnect).
        // Other OSC sequences (clipboard, hyperlinks, etc.) go to passthrough.
        if matches!(osc_num, Some(9 | 777 | 99)) {
            self.state.push_notification(buf);
        } else {
            self.state.push_passthrough(buf);
        }
    }

    fn hook(&mut self, _params: &Params, _intermediates: &[u8], _ignore: bool, _action: char) {
        #[cfg(feature = "tracing")]
        tracing::debug!(action = %_action, "dropping DCS sequence (not supported)");
    }
    fn put(&mut self, _byte: u8) {}
    fn unhook(&mut self) {}
}

#[cfg(test)]
mod tests {
    use super::truncate_at_char_boundary;

    #[test]
    fn truncate_shorter_string_untouched() {
        assert_eq!(truncate_at_char_boundary("abc", 10), "abc");
    }

    #[test]
    fn truncate_ascii_cuts_exactly() {
        assert_eq!(truncate_at_char_boundary("abcdef", 4), "abcd");
    }

    #[test]
    fn truncate_multibyte_straddling_limit_backs_off() {
        // 'é' is 2 bytes: "aé" is bytes [a, 0xC3, 0xA9]. Cutting at 2 lands
        // mid-'é'; the old `&s[..max]` slice panicked here.
        assert_eq!(truncate_at_char_boundary("", 2), "a");
    }

    #[test]
    fn truncate_at_exact_char_boundary_keeps_char() {
        // "éé" is 4 bytes; byte 2 is a valid boundary.
        assert_eq!(truncate_at_char_boundary("éé", 2), "é");
    }

    #[test]
    fn truncate_four_byte_char_straddling_limit() {
        // '🦀' is 4 bytes. "ab🦀" cut at 5 lands mid-crab.
        assert_eq!(truncate_at_char_boundary("ab🦀", 5), "ab");
    }
}