npcterm 1.3.0

Headless terminal emulator for AI agents with full PTY access over MCP
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
use std::collections::VecDeque;
use std::fmt;
use unicode_width::UnicodeWidthChar;

use super::cell::{
    CellAttributes, CharacterSet, Color, Cursor, SavedCursorState,
    TerminalCell,
};

/// Terminal grid with scrollback buffer and dirty tracking
pub struct TerminalGrid {
    /// Screen rows (visible portion)
    rows: Vec<Vec<TerminalCell>>,
    /// Scrollback buffer (lines that have scrolled off the top)
    scrollback: VecDeque<Vec<TerminalCell>>,
    /// Maximum scrollback lines
    max_scrollback: usize,
    /// Terminal dimensions
    cols: usize,
    rows_count: usize,
    /// Cursor state
    pub cursor: Cursor,
    /// Current cell attributes (for new characters)
    pub current_attrs: CellAttributes,
    pub current_fg: Color,
    pub current_bg: Color,
    /// Scroll region (for CSI scrolling)
    scroll_region_top: usize,
    scroll_region_bottom: usize,
    /// Saved cursor state (for DECSC/DECRC)
    saved_cursor: Option<SavedCursorState>,
    /// Alternate screen buffer
    alt_screen: Option<Vec<Vec<TerminalCell>>>,
    /// Tab stops (every 8 columns by default)
    tab_stops: Vec<bool>,
    /// DEC Private Modes
    pub application_cursor_keys: bool,
    pub bracketed_paste_mode: bool,
    pub focus_event_mode: bool,
    pub synchronized_output: bool,
    sync_snapshot: Option<Vec<Vec<TerminalCell>>>,
    sync_cursor_snapshot: Option<Cursor>,
    /// Mouse tracking modes
    pub mouse_normal_tracking: bool,
    pub mouse_button_tracking: bool,
    pub mouse_any_event_tracking: bool,
    pub mouse_utf8_mode: bool,
    pub mouse_sgr_mode: bool,
    pub mouse_urxvt_mode: bool,
    /// Line Feed/New Line Mode (LNM)
    pub lnm_mode: bool,
    /// Auto-wrap mode (DECAWM)
    pub auto_wrap_mode: bool,
    /// Pending wrap flag
    wrap_pending: bool,
    /// Insert/Replace mode (IRM)
    pub insert_mode: bool,
    /// Origin mode (DECOM)
    pub origin_mode: bool,
    /// Response queue for DSR and other queries
    response_queue: Vec<String>,
    /// Character sets
    pub charset_g0: CharacterSet,
    pub charset_g1: CharacterSet,
    pub charset_use_g0: bool,
    /// Generation counter - incremented on content changes
    generation: u64,

    // === NpcTerm39 additions ===
    /// Track which rows changed since last read (consumed by tick/events)
    dirty_rows: Vec<bool>,
    /// Global dirty flag
    dirty_flag: bool,
    /// Track which rows changed since last agent read (independent from tick)
    read_dirty_rows: Vec<bool>,
    read_dirty_flag: bool,
    /// Track which rows changed since last viewer broadcast (independent from tick and agent)
    #[cfg(feature = "viewer")]
    viewer_dirty_rows: Vec<bool>,
    #[cfg(feature = "viewer")]
    viewer_dirty_flag: bool,
    /// Bell character received
    pub bell_pending: bool,
}

impl TerminalGrid {
    pub fn new(cols: usize, rows: usize, max_scrollback: usize) -> Self {
        let mut tab_stops = vec![false; cols];
        for i in (0..cols).step_by(8) {
            tab_stops[i] = true;
        }

        Self {
            rows: vec![vec![TerminalCell::default(); cols]; rows],
            scrollback: VecDeque::new(),
            max_scrollback,
            cols,
            rows_count: rows,
            cursor: Cursor::default(),
            current_attrs: CellAttributes::default(),
            current_fg: Color::Default,
            current_bg: Color::Default,
            scroll_region_top: 0,
            scroll_region_bottom: rows.saturating_sub(1),
            saved_cursor: None,
            alt_screen: None,
            tab_stops,
            application_cursor_keys: false,
            bracketed_paste_mode: false,
            focus_event_mode: false,
            synchronized_output: false,
            sync_snapshot: None,
            sync_cursor_snapshot: None,
            mouse_normal_tracking: false,
            mouse_button_tracking: false,
            mouse_any_event_tracking: false,
            mouse_utf8_mode: false,
            mouse_sgr_mode: false,
            mouse_urxvt_mode: false,
            lnm_mode: false,
            auto_wrap_mode: true,
            wrap_pending: false,
            insert_mode: false,
            origin_mode: false,
            response_queue: Vec::new(),
            charset_g0: CharacterSet::Ascii,
            charset_g1: CharacterSet::Ascii,
            charset_use_g0: true,
            generation: 0,
            dirty_rows: vec![false; rows],
            dirty_flag: false,
            read_dirty_rows: vec![true; rows],
            read_dirty_flag: true,
            #[cfg(feature = "viewer")]
            viewer_dirty_rows: vec![true; rows],
            #[cfg(feature = "viewer")]
            viewer_dirty_flag: true,
            bell_pending: false,
        }
    }

    pub fn cols(&self) -> usize {
        self.cols
    }

    pub fn rows(&self) -> usize {
        self.rows_count
    }

    pub fn scroll_region_top(&self) -> usize {
        self.scroll_region_top
    }

    pub fn scroll_region_bottom(&self) -> usize {
        self.scroll_region_bottom
    }

    pub fn scrollback_len(&self) -> usize {
        self.scrollback.len()
    }

    #[allow(dead_code)]
    pub fn generation(&self) -> u64 {
        self.generation
    }

    /// Get all visible rows
    pub fn get_rows(&self) -> &[Vec<TerminalCell>] {
        &self.rows
    }

    /// Get scrollback buffer
    pub fn get_scrollback(&self) -> &VecDeque<Vec<TerminalCell>> {
        &self.scrollback
    }

    fn drain_dirty_vec(flags: &mut Vec<bool>) -> Vec<usize> {
        let dirty: Vec<usize> = flags
            .iter()
            .enumerate()
            .filter(|(_, d)| **d)
            .map(|(i, _)| i)
            .collect();
        flags.fill(false);
        dirty
    }

    /// Take dirty rows (returns changed indices and clears tracking)
    pub fn take_dirty_rows(&mut self) -> Vec<usize> {
        self.dirty_flag = false;
        Self::drain_dirty_vec(&mut self.dirty_rows)
    }

    /// Check if screen has changed since last read
    pub fn is_dirty(&self) -> bool {
        self.dirty_flag
    }

    /// Get which rows are dirty without clearing
    pub fn peek_dirty_rows(&self) -> Vec<usize> {
        self.dirty_rows
            .iter()
            .enumerate()
            .filter(|(_, d)| **d)
            .map(|(i, _)| i)
            .collect()
    }

    /// Take read-dirty rows (returns changed indices and clears read tracking)
    pub fn take_read_dirty_rows(&mut self) -> Vec<usize> {
        self.read_dirty_flag = false;
        Self::drain_dirty_vec(&mut self.read_dirty_rows)
    }

    /// Clear read-dirty state without allocating
    pub fn clear_read_dirty(&mut self) {
        self.read_dirty_rows.fill(false);
        self.read_dirty_flag = false;
    }

    /// Check if any rows have changed since last agent read
    pub fn has_read_dirty(&self) -> bool {
        self.read_dirty_flag
    }

    /// Take viewer-dirty rows (returns changed indices and clears viewer tracking)
    #[cfg(feature = "viewer")]
    pub fn take_viewer_dirty_rows(&mut self) -> Vec<usize> {
        self.viewer_dirty_flag = false;
        Self::drain_dirty_vec(&mut self.viewer_dirty_rows)
    }

    /// Check if any rows have changed since last viewer broadcast
    #[cfg(feature = "viewer")]
    pub fn has_viewer_dirty(&self) -> bool {
        self.viewer_dirty_flag
    }

    fn mark_dirty(&mut self, row: usize) {
        if row < self.dirty_rows.len() {
            self.dirty_rows[row] = true;
            self.read_dirty_rows[row] = true;
            #[cfg(feature = "viewer")]
            { self.viewer_dirty_rows[row] = true; }
        }
        self.dirty_flag = true;
        self.read_dirty_flag = true;
        #[cfg(feature = "viewer")]
        { self.viewer_dirty_flag = true; }
    }

    fn mark_all_dirty(&mut self) {
        self.dirty_rows.fill(true);
        self.read_dirty_rows.fill(true);
        #[cfg(feature = "viewer")]
        self.viewer_dirty_rows.fill(true);
        self.dirty_flag = true;
        self.read_dirty_flag = true;
        #[cfg(feature = "viewer")]
        { self.viewer_dirty_flag = true; }
    }

    /// Get the currently active character set
    pub fn active_charset(&self) -> CharacterSet {
        if self.charset_use_g0 {
            self.charset_g0
        } else {
            self.charset_g1
        }
    }

    /// Map a character through the active character set
    pub fn map_char(&self, c: char) -> char {
        match self.active_charset() {
            CharacterSet::Ascii => c,
            CharacterSet::DecSpecialGraphics => match c {
                '_' => ' ',
                '`' => '',
                'a' => '',
                'b' => '',
                'c' => '',
                'd' => '',
                'e' => '',
                'f' => '°',
                'g' => '±',
                'h' => '',
                'i' => '',
                'j' => '',
                'k' => '',
                'l' => '',
                'm' => '',
                'n' => '',
                'o' => '',
                'p' => '',
                'q' => '',
                'r' => '',
                's' => '',
                't' => '',
                'u' => '',
                'v' => '',
                'w' => '',
                'x' => '',
                'y' => '',
                'z' => '',
                '{' => 'π',
                '|' => '',
                '}' => '£',
                '~' => '·',
                _ => c,
            },
        }
    }

    pub fn set_charset_g0(&mut self, charset: CharacterSet) {
        self.charset_g0 = charset;
    }

    pub fn set_charset_g1(&mut self, charset: CharacterSet) {
        self.charset_g1 = charset;
    }

    pub fn shift_in(&mut self) {
        self.charset_use_g0 = true;
    }

    pub fn shift_out(&mut self) {
        self.charset_use_g0 = false;
    }

    pub fn queue_response(&mut self, response: String) {
        self.response_queue.push(response);
    }

    pub fn take_responses(&mut self) -> Vec<String> {
        std::mem::take(&mut self.response_queue)
    }

    pub fn queue_cursor_position_report(&mut self) {
        let (row, col) = if self.origin_mode {
            let row = (self.cursor.y.saturating_sub(self.scroll_region_top)) + 1;
            let col = self.cursor.x + 1;
            (row, col)
        } else {
            let row = self.cursor.y + 1;
            let col = self.cursor.x + 1;
            (row, col)
        };
        let response = format!("\x1b[{};{}R", row, col);
        self.queue_response(response);
    }

    pub fn get_cell(&self, x: usize, y: usize) -> Option<&TerminalCell> {
        self.rows.get(y)?.get(x)
    }

    #[allow(dead_code)]
    pub fn get_render_cell(&self, x: usize, y: usize) -> Option<&TerminalCell> {
        if let Some(snapshot) = &self.sync_snapshot {
            snapshot.get(y)?.get(x)
        } else {
            self.rows.get(y)?.get(x)
        }
    }

    #[allow(dead_code)]
    pub fn get_render_cursor(&self) -> &Cursor {
        if let Some(cursor) = &self.sync_cursor_snapshot {
            cursor
        } else {
            &self.cursor
        }
    }

    pub fn get_cell_mut(&mut self, x: usize, y: usize) -> Option<&mut TerminalCell> {
        self.rows.get_mut(y)?.get_mut(x)
    }

    #[allow(dead_code)]
    pub fn get_scrollback_line(&self, idx: usize) -> Option<&Vec<TerminalCell>> {
        self.scrollback.get(idx)
    }

    pub fn begin_synchronized_output(&mut self) {
        if !self.synchronized_output {
            self.synchronized_output = true;
            self.sync_snapshot = Some(self.rows.clone());
            self.sync_cursor_snapshot = Some(self.cursor);
        }
    }

    pub fn end_synchronized_output(&mut self) {
        self.synchronized_output = false;
        self.sync_snapshot = None;
        self.sync_cursor_snapshot = None;
        self.generation = self.generation.wrapping_add(1);
        self.mark_all_dirty();
    }

    /// Write a character at the current cursor position
    pub fn put_char(&mut self, c: char) {
        if self.cursor.y >= self.rows_count {
            return;
        }

        match c {
            '\n' => self.linefeed(),
            '\r' => self.carriage_return(),
            '\t' => self.tab(),
            '\x08' => self.backspace(),
            c if c.is_control() => {}
            c => {
                let c = self.map_char(c);
                let char_width = if c.is_ascii() {
                    1
                } else {
                    c.width().unwrap_or(0)
                };

                if char_width == 0 {
                    return;
                }

                if self.wrap_pending && self.auto_wrap_mode {
                    self.wrap_pending = false;
                    if self.cursor.y == self.rows_count - 1 {
                        self.scroll_up(1);
                        self.cursor.x = 0;
                    } else {
                        self.cursor.x = 0;
                        self.cursor.y += 1;
                    }
                }

                let fg = self.current_fg;
                let bg = self.current_bg;
                let attrs = self.current_attrs;

                if char_width == 2 {
                    if self.cursor.x + 1 >= self.cols {
                        if self.auto_wrap_mode {
                            if self.cursor.y == self.rows_count - 1 {
                                self.scroll_up(1);
                                self.cursor.x = 0;
                            } else {
                                self.cursor.x = 0;
                                self.cursor.y += 1;
                            }
                        } else {
                            return;
                        }
                    }

                    if let Some(cell) = self.get_cell_mut(self.cursor.x, self.cursor.y) {
                        cell.c = c;
                        cell.fg = fg;
                        cell.bg = bg;
                        cell.attrs = attrs;
                        cell.wide = true;
                    }

                    if let Some(cell) = self.get_cell_mut(self.cursor.x + 1, self.cursor.y) {
                        cell.c = ' ';
                        cell.fg = fg;
                        cell.bg = bg;
                        cell.attrs = attrs;
                        cell.wide = false;
                    }

                    self.mark_dirty(self.cursor.y);
                    self.cursor.x += 2;

                    if self.cursor.x >= self.cols {
                        if self.auto_wrap_mode {
                            self.cursor.x = self.cols - 1;
                            self.wrap_pending = true;
                        } else {
                            self.cursor.x = self.cols - 1;
                        }
                    }
                } else {
                    if self.cursor.x < self.cols {
                        if let Some(cell) = self.get_cell_mut(self.cursor.x, self.cursor.y) {
                            cell.c = c;
                            cell.fg = fg;
                            cell.bg = bg;
                            cell.attrs = attrs;
                            cell.wide = false;
                        }
                        self.mark_dirty(self.cursor.y);
                        self.cursor.x += 1;

                        if self.cursor.x >= self.cols {
                            if self.auto_wrap_mode {
                                self.cursor.x = self.cols - 1;
                                self.wrap_pending = true;
                            } else {
                                self.cursor.x = self.cols - 1;
                            }
                        }
                    }
                }

                self.generation = self.generation.wrapping_add(1);
            }
        }
    }

    fn linefeed(&mut self) {
        self.wrap_pending = false;
        if self.lnm_mode {
            self.cursor.x = 0;
        }
        if self.cursor.y == self.scroll_region_bottom {
            self.scroll_up(1);
        } else if self.cursor.y < self.rows_count - 1 {
            self.cursor.y += 1;
        }
    }

    fn carriage_return(&mut self) {
        self.wrap_pending = false;
        self.cursor.x = 0;
    }

    pub fn reverse_linefeed(&mut self) {
        if self.cursor.y == self.scroll_region_top {
            self.scroll_down(1);
        } else if self.cursor.y > 0 {
            self.cursor.y -= 1;
        }
    }

    pub fn next_line(&mut self) {
        self.carriage_return();
        self.linefeed();
    }

    pub fn reset(&mut self) {
        self.clear_screen();
        self.cursor = Cursor::default();
        self.current_attrs = CellAttributes::default();
        self.current_fg = Color::Default;
        self.current_bg = Color::Default;
        self.scroll_region_top = 0;
        self.scroll_region_bottom = self.rows_count.saturating_sub(1);
        self.saved_cursor = None;
        self.alt_screen = None;
        self.scrollback.clear();
        self.application_cursor_keys = false;
        self.bracketed_paste_mode = false;
        self.focus_event_mode = false;
        self.synchronized_output = false;
        self.sync_snapshot = None;
        self.sync_cursor_snapshot = None;
        self.mouse_normal_tracking = false;
        self.mouse_button_tracking = false;
        self.mouse_any_event_tracking = false;
        self.mouse_utf8_mode = false;
        self.mouse_sgr_mode = false;
        self.mouse_urxvt_mode = false;
        self.lnm_mode = false;
        self.auto_wrap_mode = true;
        self.wrap_pending = false;
        self.insert_mode = false;
        self.origin_mode = false;
        self.charset_g0 = CharacterSet::Ascii;
        self.charset_g1 = CharacterSet::Ascii;
        self.charset_use_g0 = true;
        self.response_queue.clear();
        self.mark_all_dirty();
    }

    fn tab(&mut self) {
        self.wrap_pending = false;
        for x in (self.cursor.x + 1)..self.cols {
            if self.tab_stops[x] {
                self.cursor.x = x;
                return;
            }
        }
        self.cursor.x = self.cols.saturating_sub(1);
    }

    fn backspace(&mut self) {
        self.wrap_pending = false;
        if self.cursor.x > 0 {
            self.cursor.x -= 1;
        }
    }

    pub fn scroll_up(&mut self, n: usize) {
        for _ in 0..n {
            if self.scroll_region_top < self.rows_count {
                let line = self.rows.remove(self.scroll_region_top);

                if self.alt_screen.is_none() {
                    self.scrollback.push_back(line);
                    if self.scrollback.len() > self.max_scrollback {
                        self.scrollback.pop_front();
                    }
                }

                let insert_pos = self.scroll_region_bottom.min(self.rows_count - 1);
                self.rows
                    .insert(insert_pos, vec![TerminalCell::default(); self.cols]);
            }
        }
        self.generation = self.generation.wrapping_add(1);
        self.mark_all_dirty();
    }

    pub fn scroll_down(&mut self, n: usize) {
        for _ in 0..n {
            if self.scroll_region_bottom < self.rows_count {
                self.rows.remove(self.scroll_region_bottom);
                self.rows.insert(
                    self.scroll_region_top,
                    vec![TerminalCell::default(); self.cols],
                );
            }
        }
        self.generation = self.generation.wrapping_add(1);
        self.mark_all_dirty();
    }

    pub fn clear_screen(&mut self) {
        let bg = self.current_bg;
        for row in &mut self.rows {
            for cell in row {
                cell.erase(bg);
            }
        }
        self.generation = self.generation.wrapping_add(1);
        self.mark_all_dirty();
    }

    pub fn clear_line(&mut self) {
        let bg = self.current_bg;
        if let Some(row) = self.rows.get_mut(self.cursor.y) {
            for cell in row {
                cell.erase(bg);
            }
            self.generation = self.generation.wrapping_add(1);
            self.mark_dirty(self.cursor.y);
        }
    }

    pub fn erase_to_eol(&mut self) {
        let bg = self.current_bg;
        if let Some(row) = self.rows.get_mut(self.cursor.y) {
            for x in self.cursor.x..self.cols {
                if let Some(cell) = row.get_mut(x) {
                    cell.erase(bg);
                }
            }
            self.generation = self.generation.wrapping_add(1);
            self.mark_dirty(self.cursor.y);
        }
    }

    pub fn erase_to_bol(&mut self) {
        let bg = self.current_bg;
        if let Some(row) = self.rows.get_mut(self.cursor.y) {
            for x in 0..=self.cursor.x {
                if let Some(cell) = row.get_mut(x) {
                    cell.erase(bg);
                }
            }
            self.generation = self.generation.wrapping_add(1);
            self.mark_dirty(self.cursor.y);
        }
    }

    pub fn erase_to_eos(&mut self) {
        self.erase_to_eol();
        let bg = self.current_bg;
        for y in (self.cursor.y + 1)..self.rows_count {
            if let Some(row) = self.rows.get_mut(y) {
                for cell in row {
                    cell.erase(bg);
                }
            }
            self.mark_dirty(y);
        }
        self.generation = self.generation.wrapping_add(1);
    }

    pub fn erase_from_bos(&mut self) {
        let bg = self.current_bg;
        for y in 0..self.cursor.y {
            if let Some(row) = self.rows.get_mut(y) {
                for cell in row {
                    cell.erase(bg);
                }
            }
            self.mark_dirty(y);
        }
        self.erase_to_bol();
        self.generation = self.generation.wrapping_add(1);
    }

    pub fn delete_chars(&mut self, n: usize) {
        if let Some(row) = self.rows.get_mut(self.cursor.y) {
            let start = self.cursor.x;
            let end = self.cols;
            let n = n.min(end.saturating_sub(start));

            for x in start..(end - n) {
                if let Some(src_cell) = row.get(x + n).cloned() {
                    if let Some(cell) = row.get_mut(x) {
                        *cell = src_cell;
                    }
                }
            }

            let bg = self.current_bg;
            for x in (end - n)..end {
                if let Some(cell) = row.get_mut(x) {
                    cell.erase(bg);
                }
            }
            self.generation = self.generation.wrapping_add(1);
            self.mark_dirty(self.cursor.y);
        }
    }

    pub fn insert_chars(&mut self, n: usize) {
        if let Some(row) = self.rows.get_mut(self.cursor.y) {
            let start = self.cursor.x;
            let end = self.cols;
            let n = n.min(end.saturating_sub(start));

            for x in (start + n..end).rev() {
                if let Some(src_cell) = row.get(x - n).cloned() {
                    if let Some(cell) = row.get_mut(x) {
                        *cell = src_cell;
                    }
                }
            }

            let bg = self.current_bg;
            for x in start..(start + n).min(end) {
                if let Some(cell) = row.get_mut(x) {
                    cell.erase(bg);
                }
            }
            self.generation = self.generation.wrapping_add(1);
            self.mark_dirty(self.cursor.y);
        }
    }

    pub fn erase_chars(&mut self, n: usize) {
        let bg = self.current_bg;
        if let Some(row) = self.rows.get_mut(self.cursor.y) {
            for x in self.cursor.x..(self.cursor.x + n).min(self.cols) {
                if let Some(cell) = row.get_mut(x) {
                    cell.erase(bg);
                }
            }
            self.generation = self.generation.wrapping_add(1);
            self.mark_dirty(self.cursor.y);
        }
    }

    pub fn goto(&mut self, x: usize, y: usize) {
        self.wrap_pending = false;
        self.cursor.x = x.min(self.cols.saturating_sub(1));
        self.cursor.y = y.min(self.rows_count.saturating_sub(1));
    }

    pub fn goto_origin_aware(&mut self, x: usize, y: usize) {
        self.wrap_pending = false;
        if self.origin_mode {
            let actual_y = (self.scroll_region_top + y).min(self.scroll_region_bottom);
            self.cursor.x = x.min(self.cols.saturating_sub(1));
            self.cursor.y = actual_y;
        } else {
            self.goto(x, y);
        }
    }

    pub fn move_cursor(&mut self, dx: isize, dy: isize) {
        self.wrap_pending = false;
        let new_x = (self.cursor.x as isize + dx).max(0) as usize;
        let new_y = (self.cursor.y as isize + dy).max(0) as usize;
        self.goto(new_x, new_y);
    }

    pub fn set_origin_mode(&mut self, enabled: bool) {
        self.origin_mode = enabled;
        if enabled {
            self.cursor.x = 0;
            self.cursor.y = self.scroll_region_top;
        } else {
            self.cursor.x = 0;
            self.cursor.y = 0;
        }
    }

    pub fn save_cursor_position(&mut self) {
        self.save_cursor();
    }

    pub fn restore_cursor_position(&mut self) {
        if let Some(saved) = self.saved_cursor {
            self.cursor = saved.cursor;
        }
    }

    pub fn save_cursor(&mut self) {
        self.saved_cursor = Some(SavedCursorState {
            cursor: self.cursor,
            attrs: self.current_attrs,
            fg: self.current_fg,
            bg: self.current_bg,
        });
    }

    pub fn restore_cursor(&mut self) {
        if let Some(saved) = self.saved_cursor {
            self.cursor = saved.cursor;
            self.current_attrs = saved.attrs;
            self.current_fg = saved.fg;
            self.current_bg = saved.bg;
        }
    }

    pub fn use_alt_screen(&mut self) {
        if self.alt_screen.is_none() {
            self.save_cursor();
            self.alt_screen = Some(self.rows.clone());
            self.clear_screen();
            self.cursor = Cursor::default();
            self.generation = self.generation.wrapping_add(1);
            self.mark_all_dirty();
        }
    }

    pub fn use_main_screen(&mut self) {
        if let Some(mut main_screen) = self.alt_screen.take() {
            let current_cols = self.cols;
            let current_rows = self.rows_count;

            for row in &mut main_screen {
                row.resize(current_cols, TerminalCell::default());
            }

            match current_rows.cmp(&main_screen.len()) {
                std::cmp::Ordering::Greater => {
                    main_screen.resize(current_rows, vec![TerminalCell::default(); current_cols]);
                }
                std::cmp::Ordering::Less => {
                    main_screen.truncate(current_rows);
                }
                std::cmp::Ordering::Equal => {}
            }

            self.rows = main_screen;
            self.restore_cursor();
            self.cursor.x = self.cursor.x.min(current_cols.saturating_sub(1));
            self.cursor.y = self.cursor.y.min(current_rows.saturating_sub(1));
            self.scroll_region_top = 0;
            self.scroll_region_bottom = current_rows.saturating_sub(1);
            self.generation = self.generation.wrapping_add(1);
            self.mark_all_dirty();
        }
    }

    pub fn set_scroll_region(&mut self, top: usize, bottom: usize) {
        let top = top.min(self.rows_count.saturating_sub(2));
        let bottom = bottom.min(self.rows_count.saturating_sub(1));

        if top < bottom {
            self.scroll_region_top = top;
            self.scroll_region_bottom = bottom;
        } else {
            self.scroll_region_top = 0;
            self.scroll_region_bottom = self.rows_count.saturating_sub(1);
        }

        if self.origin_mode {
            self.cursor.x = 0;
            self.cursor.y = self.scroll_region_top;
        } else {
            self.cursor.x = 0;
            self.cursor.y = 0;
        }
    }

    #[allow(dead_code)]
    pub fn set_cursor(&mut self, x: usize, y: usize, visible: bool) {
        self.cursor.x = x.min(self.cols.saturating_sub(1));
        self.cursor.y = y.min(self.rows_count.saturating_sub(1));
        self.cursor.visible = visible;
    }
}

impl fmt::Debug for TerminalGrid {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("TerminalGrid")
            .field("cols", &self.cols)
            .field("rows", &self.rows_count)
            .field("scrollback_lines", &self.scrollback.len())
            .field("cursor", &self.cursor)
            .finish()
    }
}