tastty-core 0.1.0

Sans-IO core of the tastty terminal session library: VT parser, screen buffer, and byte encoders.
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
//! Virtual terminal screen state, events, modes, and text extraction.

use std::sync::Arc;

use crate::host_profile::HostProfile;

mod events;
pub mod logical_line;
mod modes;
mod ops;
mod osc;
mod palette;
mod reflow;
mod selection;
mod state;
mod terminfo;
#[cfg(feature = "widget")]
mod tui_term_impl;
mod types;

pub use events::{
    ClipboardTarget, ColorTarget, ProgressState, ScreenEvent, SemanticPrompt, XtGetTcapEntry,
    XtWinOpsReport,
};
pub use logical_line::{LogicalLineOptions, LogicalLineSpan, LogicalLines};
pub use modes::TerminalMode;
pub use selection::{SelectionMode, SelectionRange};
pub use types::{
    AbsolutePosition, CellPixelSize, ColorRole, CursorShape, CursorStyle, DirtyState,
    FormattedOptions, PlainOptions, Position, TerminalSize,
};

pub(crate) use modes::{
    MODE_ALL_DEC, MODE_ALTERNATE_SCREEN, MODE_ALTERNATE_SCROLL, MODE_APPLICATION_CURSOR,
    MODE_BACKSPACE_BS, MODE_BRACKETED_PASTE, MODE_COLOR_SCHEME_UPDATES, MODE_DEC_ALLOW_80_132,
    MODE_DECCOLM, MODE_FOCUS_IN_OUT, MODE_GRAPHEME_CLUSTER, MODE_HIDE_CURSOR, MODE_IN_BAND_RESIZE,
    MODE_INSERT, MODE_LINE_WRAP, MODE_LNM, MODE_MOUSE_REPORT_ALL_MOTION,
    MODE_MOUSE_REPORT_CELL_MOTION, MODE_MOUSE_REPORT_CLICK, MODE_MOUSE_X10, MODE_REVERSE_VIDEO,
    MODE_SGR_MOUSE, MODE_SGR_PIXEL_MOUSE, MODE_SYNC_UPDATE,
};
pub(crate) use palette::{
    PALETTE_SIZE, default_xterm_color, default_xterm_palette, parse_x11_color,
};
pub(crate) use state::{
    Charset, DcsHandler, KittyFlagStack, LastPrinted, TitleStackEntry, TitleStackTarget,
};
pub(crate) use terminfo::{xtgettcap_is_tn, xtgettcap_lookup};

/// In-memory terminal screen with primary/alternate buffers and mode state.
#[derive(Clone, Debug)]
pub struct Screen {
    pub(super) grid: crate::grid::Grid,
    pub(super) alternate_grid: crate::grid::Grid,

    pub(super) attrs: crate::attrs::Attrs,
    pub(super) saved_attrs: crate::attrs::Attrs,

    pub(super) charsets: [Charset; 4],
    pub(super) active_charset: usize,
    pub(super) saved_charsets: [Charset; 4],
    pub(super) saved_active_charset: usize,

    pub(super) cursor_style: CursorStyle,

    pub(super) title: String,
    pub(super) icon_name: String,
    pub(super) title_stack: Vec<TitleStackEntry>,
    pub(super) cwd: Option<String>,

    pub(super) hyperlink: Option<Arc<crate::cell::Hyperlink>>,

    pub(super) modes: u32,
    pub(super) saved_modes: u32,
    pub(super) saved_modes_mask: u32,
    pub(crate) dcs_handler: DcsHandler,

    pub(super) default_fg: crate::attrs::Color,
    pub(super) default_bg: crate::attrs::Color,
    pub(super) default_cursor_color: crate::attrs::Color,
    pub(super) palette: Box<[(u8, u8, u8); PALETTE_SIZE]>,

    pub(super) pixel_cell_size: CellPixelSize,

    pub(super) pending_events: Vec<ScreenEvent>,

    pub(super) print_buffer: String,

    pub(super) kitty_flags: KittyFlagStack,
    pub(super) kitty_flags_alt: KittyFlagStack,

    pub(super) host_profile: Arc<HostProfile>,

    pub(in crate::screen) selection: Option<selection::SelectionState>,

    pub(super) last_printed: Option<LastPrinted>,
}

fn row_text(row: &crate::row::Row, cols: u16) -> String {
    let mut text = String::new();
    let mut col = 0;
    while col < cols {
        if let Some(cell) = row.get(col) {
            if cell.is_wide_continuation() {
                col += 1;
                continue;
            }
            let contents = cell.contents();
            if contents.is_empty() {
                text.push(' ');
            } else {
                text.push_str(contents);
            }
            col += if cell.is_wide() { 2 } else { 1 };
        } else {
            text.push(' ');
            col += 1;
        }
    }
    text
}

impl Screen {
    pub(crate) fn new(size: crate::grid::Size, scrollback_len: usize) -> Self {
        Self::with_profile(size, scrollback_len, Arc::new(HostProfile::default()))
    }

    pub(crate) fn with_profile(
        size: crate::grid::Size,
        scrollback_len: usize,
        profile: Arc<HostProfile>,
    ) -> Self {
        let mut grid = crate::grid::Grid::new(size, scrollback_len);
        grid.allocate_rows();
        Self {
            grid,
            alternate_grid: crate::grid::Grid::new(size, 0),
            attrs: crate::attrs::Attrs::default(),
            saved_attrs: crate::attrs::Attrs::default(),
            charsets: [Charset::default(); 4],
            active_charset: 0,
            saved_charsets: [Charset::default(); 4],
            saved_active_charset: 0,
            cursor_style: CursorStyle::Default,
            title: String::new(),
            icon_name: String::new(),
            title_stack: Vec::new(),
            cwd: None,
            hyperlink: None,
            modes: MODE_LINE_WRAP,
            saved_modes: 0,
            saved_modes_mask: 0,
            dcs_handler: DcsHandler::None,
            default_fg: profile.default_fg,
            default_bg: profile.default_bg,
            default_cursor_color: profile.default_cursor_color,
            palette: default_xterm_palette(),
            pixel_cell_size: CellPixelSize::default(),
            pending_events: Vec::new(),
            print_buffer: String::new(),
            kitty_flags: KittyFlagStack::default(),
            kitty_flags_alt: KittyFlagStack::default(),
            host_profile: profile,
            selection: None,
            last_printed: None,
        }
    }

    /// Resize the virtual screen buffers.
    ///
    /// The primary buffer reflows wrap-preservingly; the alternate
    /// buffer is resized geometrically without reflow.
    ///
    /// Resets the active character set to G0 so post-resize bytes are
    /// interpreted with a known starting charset. This avoids the cmatrix
    /// resize bug where stale SO state from before the resize bleeds into
    /// the post-resize content.
    ///
    /// [`AbsolutePosition`] handles held by callers are not remapped
    /// across this call: rows that previously sat at one absolute index
    /// may move to a different one after reflow re-buckets the buffer.
    /// Callers that hold absolute positions (selection anchors, search
    /// hits, scrollback bookmarks) must re-resolve them after a resize.
    /// The active selection is dropped here for the same reason.
    pub fn set_size(&mut self, size: TerminalSize) {
        let prev = self.grid().size();
        let size_changed = prev.rows != size.rows || prev.cols != size.cols;
        let had_selection = self.selection.is_some();
        let grid_size = crate::grid::Size {
            rows: size.rows,
            cols: size.cols,
        };
        reflow::reflow_primary(self, grid_size);
        self.alternate_grid.resize_simple(grid_size);
        self.reset_charset();
        self.selection = None;
        if size_changed && had_selection {
            self.pending_events.push(ScreenEvent::SelectionInvalidated);
        }
    }

    #[must_use]
    /// Return the current screen size.
    pub fn size(&self) -> TerminalSize {
        let size = self.grid().size();
        TerminalSize {
            rows: size.rows,
            cols: size.cols,
        }
    }

    /// Set the viewport offset into scrollback history.
    pub fn set_scrollback(&mut self, rows: usize) {
        self.grid_mut().set_scrollback(rows);
    }

    #[must_use]
    /// Return the current viewport offset into scrollback history.
    pub fn scrollback(&self) -> usize {
        self.grid().scrollback()
    }

    /// Number of scrollback rows available in the buffer.
    #[must_use]
    pub fn scrollback_available(&self) -> usize {
        self.grid().scrollback_available()
    }

    /// Absolute row index of the oldest currently-addressable row.
    ///
    /// This is the row id of the first retained scrollback row when
    /// scrollback is non-empty, and the row id of the live drawing
    /// region's top row otherwise. Use this when joining scrollback
    /// and viewport rows into one logical buffer (oldest scrollback
    /// first, then visible rows): the absolute row of `lines[i]` in
    /// such a buffer is `scrollback_origin_row() + i` while `i` stays
    /// within the joined slice's bounds.
    ///
    /// Combined with [`Screen::visible_to_absolute`] and
    /// [`Screen::absolute_to_visible`], this completes the mapping
    /// between local coordinates in derived text views and the
    /// scrollback-stable [`AbsolutePosition`] used by the selection
    /// API and other history-aware callers.
    #[must_use]
    pub fn scrollback_origin_row(&self) -> u64 {
        self.grid()
            .pushed_to_scrollback()
            .saturating_sub(self.grid().scrollback_available() as u64)
    }

    /// Return the text contents of scrollback rows, oldest first.
    /// If `limit` is `Some(n)`, only the most recent `n` rows are returned.
    #[must_use]
    pub fn scrollback_contents(&self, limit: Option<usize>) -> Vec<String> {
        self.grid().scrollback_contents(limit)
    }

    /// Scroll the viewport up by `count` rows into history.
    pub fn scroll_up(&mut self, count: usize) {
        let available = self.grid().scrollback_available();
        let current = self.grid().scrollback();
        let new_offset = (current + count).min(available);
        self.grid_mut().set_scrollback(new_offset);
    }

    /// Scroll the viewport down by `count` rows (towards live output).
    pub fn scroll_down(&mut self, count: usize) {
        let current = self.grid().scrollback();
        let new_offset = current.saturating_sub(count);
        self.grid_mut().set_scrollback(new_offset);
    }

    /// Reset the scrollback viewport to the bottom (live output).
    pub fn scroll_reset(&mut self) {
        self.grid_mut().set_scrollback(0);
    }

    /// Set the scrollback viewport to an absolute offset.
    /// 0 = live output, scrollback_available() = oldest history.
    /// Values beyond available scrollback are clamped.
    pub fn scroll_to(&mut self, offset: usize) {
        self.grid_mut().set_scrollback(offset);
    }

    #[must_use]
    /// Return the current zero-based cursor position.
    pub fn cursor(&self) -> Position {
        let pos = self.grid().pos();
        Position {
            row: pos.row,
            col: pos.col,
        }
    }

    /// Convert a viewport-relative [`Position`] to its scrollback-stable
    /// [`AbsolutePosition`].
    ///
    /// Use this to anchor a selection at a click location: the click
    /// arrives in viewport coordinates, but the selection state must
    /// outlive subsequent scrolling and so is stored as
    /// `AbsolutePosition`. Returns `None` if `pos` lies outside the
    /// current viewport (`row >= rows` or `col >= cols`).
    ///
    /// The returned absolute row accounts for the current scrollback
    /// view offset: when the user has scrolled history into view, row
    /// 0 of the viewport is a scrollback row, not the live drawing
    /// region's top.
    #[must_use]
    pub fn visible_to_absolute(&self, pos: Position) -> Option<AbsolutePosition> {
        let size = self.size();
        if pos.row >= size.rows || pos.col >= size.cols {
            return None;
        }
        let viewport_top = self
            .grid()
            .pushed_to_scrollback()
            .saturating_sub(self.grid().scrollback() as u64);
        Some(AbsolutePosition {
            row: viewport_top.saturating_add(u64::from(pos.row)),
            col: pos.col,
        })
    }

    /// Begin a selection anchored at `anchor` with the given mode.
    ///
    /// Replaces any prior selection. The cursor end starts at the
    /// anchor; call [`Screen::selection_extend`] to extend the
    /// selection to a different cell. The mode is set once at
    /// `selection_start` time and is preserved by subsequent
    /// extensions.
    ///
    /// `anchor` is a [scrollback-stable coordinate](AbsolutePosition);
    /// embedders translating a click event use
    /// [`Screen::visible_to_absolute`] to obtain it.
    pub fn selection_start(&mut self, anchor: AbsolutePosition, mode: SelectionMode) {
        self.selection = Some(selection::SelectionState::new(anchor, mode));
    }

    /// Extend the active selection's cursor end to `to`.
    ///
    /// The anchor is unchanged. If `to` precedes the anchor in
    /// reading order, the selection is reported with `start` and
    /// `end` swapped by [`Screen::selection_range`]; the un-normalized
    /// anchor/cursor pair is preserved internally so an embedder can
    /// implement direction-aware extension semantics on top.
    ///
    /// No-op when there is no active selection.
    pub fn selection_extend(&mut self, to: AbsolutePosition) {
        if let Some(state) = self.selection.as_mut() {
            state.extend(to);
        }
    }

    /// Drop the active selection.
    ///
    /// Call when the embedder's selection UI ends (mouse release that
    /// did not become a real selection, scroll-to-bottom, terminal
    /// reset). After this, [`Screen::selection_range`] and
    /// [`Screen::selected_text`] return `None`.
    pub fn selection_clear(&mut self) {
        self.selection = None;
    }

    /// Return the active selection's normalized range, or `None` if
    /// no selection is active.
    ///
    /// `start` and `end` are sorted into row-major reading order
    /// regardless of the order the embedder anchored or extended the
    /// selection, so renderers can iterate `start..=end` directly.
    #[must_use]
    pub fn selection_range(&self) -> Option<SelectionRange> {
        self.selection
            .as_ref()
            .map(selection::SelectionState::range)
    }

    /// Return the text covered by the active selection.
    ///
    /// Returns `None` when no selection is active or when one of the
    /// selection's endpoints has aged out of scrollback (so the text
    /// can no longer be reconstructed).
    ///
    /// # Geometry
    ///
    /// - [`SelectionMode::Linear`] joins each row's slice in reading
    ///   order. Rows ended by a soft wrap (overflow off the right
    ///   edge) are concatenated continuously; rows ended by a hard
    ///   line break are joined with `'\n'`. Trailing whitespace is
    ///   trimmed per row, matching the typical terminal-selection
    ///   clipboard behaviour.
    /// - [`SelectionMode::Line`] is identical to
    ///   [`SelectionMode::Linear`] except both endpoints are extended
    ///   to the row's first and last columns, so the copied text
    ///   covers complete rows from anchor's row through cursor's row.
    ///
    /// Wide cells are emitted once from the lead-half cell; the
    /// trailing continuation cell is skipped.
    #[must_use]
    pub fn selected_text(&self) -> Option<String> {
        let state = self.selection.as_ref()?;
        selection::selected_text(self, state)
    }

    /// Convert an [`AbsolutePosition`] to a viewport-relative
    /// [`Position`], if the row is currently visible.
    ///
    /// Returns `None` when the absolute row is outside the current
    /// viewport, either because it has scrolled above the top of the
    /// viewport into deeper history, because it has aged out of the
    /// scrollback cap entirely, or because it has not yet been
    /// written. Renderers drawing a stored selection use this to map
    /// the absolute endpoints back to drawable cells; an absolute row
    /// that returns `None` falls outside the current rendering pass.
    #[must_use]
    pub fn absolute_to_visible(&self, abs: AbsolutePosition) -> Option<Position> {
        let size = self.size();
        if abs.col >= size.cols {
            return None;
        }
        let viewport_top = self
            .grid()
            .pushed_to_scrollback()
            .saturating_sub(self.grid().scrollback() as u64);
        let row_offset = abs.row.checked_sub(viewport_top)?;
        if row_offset >= u64::from(size.rows) {
            return None;
        }
        Some(Position {
            row: row_offset as u16,
            col: abs.col,
        })
    }

    #[must_use]
    /// Return one visible row as plain text padded to the column count.
    ///
    /// Empty cells are rendered as spaces and trailing empty cells are
    /// preserved, so the returned string is always exactly
    /// [`TerminalSize::cols`] characters wide unless the row contains
    /// multi-byte glyphs. Callers that want the trimmed shape can call
    /// `.trim_end()` at the use site.
    pub fn row_text(&self, row: u16) -> Option<String> {
        let cols = self.grid().size().cols;
        self.grid().visible_row(row).map(|row| row_text(row, cols))
    }

    #[must_use]
    /// Return all visible screen rows as plain text padded to the column
    /// count. See [`Screen::row_text`] for the per-row shape.
    pub fn visible_text_rows(&self) -> Vec<String> {
        let cols = self.grid().size().cols;
        self.grid()
            .visible_rows()
            .map(|row| row_text(row, cols))
            .collect()
    }

    #[must_use]
    /// Return visible screen contents as plain text.
    pub fn contents(&self) -> String {
        let mut contents = String::new();
        let size = self.grid().size();
        let mut wrapping = false;
        for row in self.grid().visible_rows() {
            let mut prev_col = 0u16;
            let mut prev_was_wide = false;
            for col in 0..size.cols {
                if prev_was_wide {
                    prev_was_wide = false;
                    continue;
                }
                if let Some(cell) = row.get(col) {
                    prev_was_wide = cell.is_wide();
                    if cell.has_contents() {
                        if !wrapping {
                            for _ in 0..(col - prev_col) {
                                contents.push(' ');
                            }
                        }
                        wrapping = false;
                        prev_col = col;
                        contents.push_str(cell.contents());
                        prev_col += if cell.is_wide() { 2 } else { 1 };
                    }
                }
            }
            if !row.wrapped() {
                contents.push('\n');
            }
            wrapping = row.wrapped();
        }
        while contents.ends_with('\n') {
            contents.truncate(contents.len() - 1);
        }
        contents
    }

    /// Extract text between two visible-grid positions, inclusive.
    ///
    /// `start` must precede or equal `end` in row-major reading order;
    /// callers that may have arbitrary endpoints should sort first.
    /// Both positions are clamped to the visible grid before extraction.
    /// Non-wrapped rows are joined with '\n'; wrapped rows are
    /// concatenated directly (the soft wrap is invisible to the user).
    /// Empty cells are rendered as spaces and trailing empty cells in
    /// each row are preserved, matching [`Screen::row_text`].
    #[must_use]
    pub fn contents_between(&self, start: Position, end: Position) -> String {
        let TerminalSize {
            rows: max_rows,
            cols: max_cols,
        } = self.size();
        if max_rows == 0 || max_cols == 0 {
            return String::new();
        }
        let start_row = start.row.min(max_rows - 1);
        let start_col = start.col.min(max_cols - 1);
        let end_row = end.row.min(max_rows - 1);
        let end_col = end.col.min(max_cols - 1);

        let rows: Vec<_> = self.grid().visible_rows().collect();
        let mut result = String::new();
        for row_idx in start_row..=end_row {
            let row = &rows[row_idx as usize];
            let col_start = if row_idx == start_row { start_col } else { 0 };
            let col_end = if row_idx == end_row {
                end_col
            } else {
                max_cols - 1
            };

            if row_idx > start_row && !rows[(row_idx - 1) as usize].wrapped() {
                result.push('\n');
            }

            let mut row_text = String::new();
            let mut col = col_start;
            while col <= col_end {
                if let Some(cell) = row.get(col) {
                    if cell.is_wide_continuation() {
                        col += 1;
                        continue;
                    }
                    let c = cell.contents();
                    if c.is_empty() {
                        row_text.push(' ');
                    } else {
                        row_text.push_str(c);
                    }
                }
                col += 1;
            }
            result.push_str(&row_text);
        }
        result
    }

    /// Serialize the visible screen as VT escape bytes.
    ///
    /// A fresh `Parser` fed these bytes reproduces the same visual state.
    ///
    /// With [`FormattedOptions::join_wrapped`] set, the inter-row CRLF is
    /// suppressed for rows whose predecessor was soft-wrapped, so a logical
    /// line that the terminal split across columns reappears as one line.
    /// Explicit newlines emitted by the child process are preserved either
    /// way.
    ///
    /// With [`FormattedOptions::include_scrollback`] set, scrollback rows
    /// are emitted oldest-first before the live drawing region; the
    /// viewport scroll offset is ignored. With
    /// [`FormattedOptions::trim_trailing_blanks`] cleared, the output
    /// keeps one CRLF-separated entry per remaining row.
    #[must_use]
    pub fn contents_formatted(&self, opts: FormattedOptions) -> Vec<u8> {
        let size = self.grid().size();
        let mut out = Vec::with_capacity(size.rows as usize * size.cols as usize * 2);
        let default_attrs = crate::attrs::Attrs::default();
        let mut current_attrs = default_attrs;

        // contents_formatted treats a row as displayable if it has either
        // content OR non-default attrs (a bg-fill row is meaningful here);
        // contents_plain trims on content alone. The walks share row
        // gathering and span building; only the trim predicate differs.
        let rows = logical_line::gather_rows(self.grid(), opts.include_scrollback);
        let upper_bound = if opts.trim_trailing_blanks {
            rows.iter()
                .rposition(|gathered| {
                    (0..size.cols).any(|col| {
                        gathered
                            .row
                            .get(col)
                            .is_some_and(|c| c.has_contents() || *c.attrs() != default_attrs)
                    })
                })
                .map(|last| last + 1)
                .unwrap_or(0)
        } else {
            rows.len()
        };
        let line_iter = logical_line::from_rows(rows, upper_bound, opts.join_wrapped, size.cols);

        let mut is_first_emitted_row = true;
        for span in line_iter {
            for (offset, row) in span.rows.iter().enumerate() {
                let prev_wrapped = offset > 0;
                if !(is_first_emitted_row || (opts.join_wrapped && prev_wrapped)) {
                    out.extend_from_slice(b"\r\n");
                }
                is_first_emitted_row = false;

                let mut last_col: u16 = 0;
                let mut row_has_content = false;
                for col in 0..size.cols {
                    if let Some(cell) = row.get(col)
                        && (cell.has_contents() || *cell.attrs() != default_attrs)
                    {
                        last_col = col;
                        row_has_content = true;
                    }
                }

                if !row_has_content {
                    continue;
                }

                let mut prev_was_wide = false;
                for col in 0..=last_col {
                    if prev_was_wide {
                        prev_was_wide = false;
                        continue;
                    }
                    if let Some(cell) = row.get(col) {
                        prev_was_wide = cell.is_wide();
                        let cell_attrs = *cell.attrs();
                        if cell_attrs != current_attrs {
                            out.extend_from_slice(&cell_attrs.to_escape_sequence(&current_attrs));
                            current_attrs = cell_attrs;
                        }
                        let contents = cell.contents();
                        if contents.is_empty() {
                            out.push(b' ');
                        } else {
                            out.extend_from_slice(contents.as_bytes());
                        }
                    } else {
                        out.push(b' ');
                    }
                }
            }
        }

        if current_attrs != default_attrs {
            out.extend_from_slice(b"\x1b[0m");
        }
        out
    }

    /// Walk logical lines on the screen.
    ///
    /// A logical line is a contiguous run of physical rows joined back
    /// together at every soft-wrap boundary, or a single row when
    /// `join_wrapped` is unset. This is the canonical row-walking
    /// primitive shared by [`Screen::contents_plain`],
    /// [`Screen::contents_formatted`], and out-of-crate consumers
    /// (notably the `tastty-driver` content-search engine), so wrap
    /// handling stays in one place. Each yielded [`LogicalLineSpan`] carries
    /// the scrollback-stable [`AbsolutePosition`] range it covers, plus a
    /// [`LogicalLineSpan::cells`] iterator that pairs each cell with
    /// its absolute position.
    pub fn logical_lines(
        &self,
        opts: logical_line::LogicalLineOptions,
    ) -> logical_line::LogicalLines<'_> {
        logical_line::iter(self, opts)
    }

    /// Serialize the visible screen as plain UTF-8 text.
    ///
    /// Drops all SGR styling and OSC 8 hyperlink targets and returns only
    /// the displayable characters. [Wide-character][tr11] continuation
    /// cells are skipped so each wide character appears once at its
    /// starting column;
    /// empty cells expand to a single space; trailing blank rows and
    /// trailing blank columns are trimmed; rows are joined with a single
    /// LF.
    ///
    /// With [`PlainOptions::join_wrapped`] set, soft-wrapped physical rows
    /// are concatenated without an intervening LF, so a single logical
    /// line that the terminal split across columns reappears as one line.
    /// Explicit newlines emitted by the child process are preserved
    /// either way.
    ///
    /// With [`PlainOptions::include_scrollback`] set, scrollback rows are
    /// emitted oldest-first before the live drawing region; the viewport
    /// scroll offset is ignored. With
    /// [`PlainOptions::trim_trailing_blanks`] cleared, the output keeps
    /// one LF-separated entry per remaining row.
    ///
    /// When [`PlainOptions::include_scrollback`] is unset, the walk follows
    /// the Grid's visible rows and so transparently respects
    /// the active scrollback offset: when the viewport is scrolled into
    /// history, the returned text reflects the historical region
    /// currently in view.
    ///
    /// [tr11]: https://www.unicode.org/reports/tr11/
    #[must_use]
    pub fn contents_plain(&self, opts: PlainOptions) -> String {
        let size = self.grid().size();
        let line_opts = logical_line::LogicalLineOptions {
            include_scrollback: opts.include_scrollback,
            trim_trailing_blanks: opts.trim_trailing_blanks,
            join_wrapped: opts.join_wrapped,
        };

        let mut out = String::with_capacity((size.rows as usize) * (size.cols as usize));
        let mut is_first_emitted_row = true;
        for span in self.logical_lines(line_opts) {
            for (offset, row) in span.rows.iter().enumerate() {
                let prev_wrapped = offset > 0;
                if !(is_first_emitted_row || (opts.join_wrapped && prev_wrapped)) {
                    out.push('\n');
                }
                is_first_emitted_row = false;

                let mut last_col: Option<u16> = None;
                for col in 0..size.cols {
                    if row.get(col).is_some_and(crate::cell::Cell::has_contents) {
                        last_col = Some(col);
                    }
                }
                let Some(last_col) = last_col else {
                    continue;
                };

                let mut prev_was_wide = false;
                for col in 0..=last_col {
                    if prev_was_wide {
                        prev_was_wide = false;
                        continue;
                    }
                    if let Some(cell) = row.get(col) {
                        prev_was_wide = cell.is_wide();
                        let contents = cell.contents();
                        if contents.is_empty() {
                            out.push(' ');
                        } else {
                            out.push_str(contents);
                        }
                    } else {
                        out.push(' ');
                    }
                }
            }
        }
        out
    }

    #[must_use]
    /// Return a visible cell by zero-based row and column.
    pub fn cell(&self, row: u16, col: u16) -> Option<&crate::cell::Cell> {
        self.grid().visible_cell(crate::grid::Pos { row, col })
    }

    /// Iterate every visible cell of the active grid in row-major order,
    /// skipping the trailing halves of [wide characters](https://www.unicode.org/reports/tr11/).
    pub fn cells(&self) -> impl Iterator<Item = (Position, &crate::cell::Cell)> {
        let cols = self.grid().size().cols;
        self.grid()
            .visible_rows()
            .enumerate()
            .flat_map(move |(r, row)| {
                (0..cols).filter_map(move |c| {
                    let cell = row.get(c)?;
                    (!cell.is_wide_continuation()).then_some((
                        Position {
                            row: r as u16,
                            col: c,
                        },
                        cell,
                    ))
                })
            })
    }

    /// Iterate the cells of one visible row of the active grid, skipping
    /// wide-character continuations. Rows outside `0..self.size().rows` yield
    /// an empty iterator.
    pub fn row_cells(&self, row: u16) -> impl Iterator<Item = (Position, &crate::cell::Cell)> {
        let cols = self.grid().size().cols;
        self.grid().visible_row(row).into_iter().flat_map(move |r| {
            (0..cols).filter_map(move |c| {
                let cell = r.get(c)?;
                (!cell.is_wide_continuation()).then_some((Position { row, col: c }, cell))
            })
        })
    }

    /// Iterate the indices of drawing rows whose contents have changed
    /// since the last [`Screen::clear_dirty`].
    ///
    /// Yielded items are `(row_index, DirtyState)` in ascending order
    /// of `row_index`. Indices address the active grid's drawing rows
    /// (the same coordinate space as [`Screen::row_cells`] when the
    /// scrollback offset is zero) and never include scrollback. Rows
    /// reported [`DirtyState::Clean`] are filtered out, so every
    /// emitted entry's state is [`DirtyState::Dirty`].
    ///
    /// The intended use is in embedders that copy [`Screen`] cells
    /// into a separate buffer (for example a `ratatui::Buffer`) once
    /// per frame: iterate `dirty_rows`, copy the affected rows, then
    /// call [`Screen::clear_dirty`]. Wire-path consumers (parsers,
    /// byte snapshots) do not need this API.
    ///
    /// # Caveats
    ///
    /// * The iterator reflects the active grid only; an
    ///   alternate-screen swap marks every row of the new active
    ///   grid dirty, which is what most embedders want.
    /// * Scrolling the viewport into history (a non-zero
    ///   [`Screen::scrollback`] offset) does not mark any rows
    ///   dirty. Embedders that expose a scrollback view must redraw
    ///   on offset change themselves.
    /// * The mark is conservative; see [`DirtyState::Dirty`].
    pub fn dirty_rows(&self) -> impl Iterator<Item = (u16, DirtyState)> + '_ {
        self.grid()
            .dirty_row_indices()
            .map(|idx| (idx, DirtyState::Dirty))
    }

    /// Reset every drawing row of the active grid to
    /// [`DirtyState::Clean`].
    ///
    /// Pair with [`Screen::dirty_rows`]: read the dirty list, perform
    /// the per-row copy, then call this. The inactive grid's dirty
    /// state is untouched; switching grids via the alternate-screen
    /// modes flips dirty marks on the newly active rows on entry and
    /// exit so the embedder's first post-swap frame redraws fully.
    pub fn clear_dirty(&mut self) {
        self.grid_mut().clear_dirty();
    }

    #[must_use]
    /// Return the current cursor style.
    pub fn cursor_style(&self) -> CursorStyle {
        self.cursor_style
    }

    /// Return the configured pixel size for one cell.
    ///
    /// A returned width or height of zero means "unknown": the embedder
    /// has not reported a per-cell pixel size, so XTWINOPS replies that
    /// require pixel dimensions (CSI 14 t / CSI 16 t) will be suppressed.
    #[must_use]
    pub fn pixel_cell_size(&self) -> CellPixelSize {
        self.pixel_cell_size
    }

    /// Set the configured pixel size for one cell.
    ///
    /// Pass [`CellPixelSize::default`] (or any value with a zero
    /// dimension) to mark the size as unknown.
    pub fn set_pixel_cell_size(&mut self, size: CellPixelSize) {
        self.pixel_cell_size = size;
    }

    /// Drain pending screen events.
    pub fn drain_events(&mut self) -> Vec<ScreenEvent> {
        std::mem::take(&mut self.pending_events)
    }

    #[must_use]
    /// Return the current window title.
    pub fn title(&self) -> &str {
        &self.title
    }

    #[must_use]
    /// Return the current icon name.
    pub fn icon_name(&self) -> &str {
        &self.icon_name
    }

    #[must_use]
    /// Return the current working directory URI as last set by OSC 7,
    /// or `None` if the program has never set one (or it has been cleared
    /// by RIS). The value is the raw URI string as received on the wire;
    /// callers that want the path component parse it themselves.
    pub fn cwd(&self) -> Option<&str> {
        self.cwd.as_deref()
    }

    #[must_use]
    /// Return active Kitty keyboard enhancement flags.
    pub fn kitty_keyboard_flags(&self) -> u8 {
        self.kitty_flags.current()
    }

    /// Return the [`HostProfile`] driving terminal identity and default-color
    /// replies for this screen.
    ///
    /// Useful when feeding events through
    /// [`auto_reply_bytes`](crate::host_reply::auto_reply_bytes) without
    /// keeping a separate `Arc<HostProfile>` handle alongside the parser.
    #[must_use]
    pub fn host_profile(&self) -> &HostProfile {
        &self.host_profile
    }

    /// Current default foreground. Seeded from [`HostProfile::default_fg`];
    /// mutated by [OSC 10][xterm-ctlseqs], reset by
    /// [OSC 110][xterm-ctlseqs].
    ///
    /// [xterm-ctlseqs]: https://invisible-island.net/xterm/ctlseqs/ctlseqs.html
    #[must_use]
    pub fn default_fg(&self) -> crate::attrs::Color {
        self.default_fg
    }

    /// Current default background. Seeded from [`HostProfile::default_bg`];
    /// mutated by [OSC 11][xterm-ctlseqs], reset by
    /// [OSC 111][xterm-ctlseqs].
    ///
    /// [xterm-ctlseqs]: https://invisible-island.net/xterm/ctlseqs/ctlseqs.html
    #[must_use]
    pub fn default_bg(&self) -> crate::attrs::Color {
        self.default_bg
    }

    /// Current default cursor color. Seeded from
    /// [`HostProfile::default_cursor_color`]; mutated by
    /// [OSC 12][xterm-ctlseqs], reset by [OSC 112][xterm-ctlseqs].
    ///
    /// [xterm-ctlseqs]: https://invisible-island.net/xterm/ctlseqs/ctlseqs.html
    #[must_use]
    pub fn default_cursor_color(&self) -> crate::attrs::Color {
        self.default_cursor_color
    }

    /// Resolve a [`Color`] to a concrete RGB triple against the live
    /// palette and the role's default slot.
    ///
    /// - [`Color::Rgb`] returns its components unchanged.
    /// - [`Color::Index`] looks up the 256-entry palette mutated by
    ///   [OSC 4][xterm-ctlseqs] / [OSC 104][xterm-ctlseqs].
    /// - [`Color::Default`] reads the role's default slot
    ///   ([`default_fg`] / [`default_bg`] / [`default_cursor_color`])
    ///   and resolves it again, so an indexed default also walks the
    ///   palette.
    ///
    /// If the default slot itself holds [`Color::Default`] the resolver
    /// falls back to xterm palette index 7 for foreground and cursor
    /// roles, and index 0 for background. Stock [`HostProfile`] seeds
    /// every slot with [`Color::Rgb`], so the fallback only triggers
    /// for embedders that intentionally configure a non-RGB seed.
    ///
    /// [`Color`]: crate::Color
    /// [`Color::Rgb`]: crate::Color::Rgb
    /// [`Color::Index`]: crate::Color::Index
    /// [`Color::Default`]: crate::Color::Default
    /// [`default_fg`]: Self::default_fg
    /// [`default_bg`]: Self::default_bg
    /// [`default_cursor_color`]: Self::default_cursor_color
    /// [xterm-ctlseqs]: https://invisible-island.net/xterm/ctlseqs/ctlseqs.html
    #[must_use]
    pub fn resolve_color(&self, color: crate::attrs::Color, role: ColorRole) -> (u8, u8, u8) {
        match color {
            crate::attrs::Color::Rgb(r, g, b) => (r, g, b),
            crate::attrs::Color::Index(i) => self.palette[usize::from(i)],
            crate::attrs::Color::Default => match role {
                ColorRole::Foreground => self.resolve_default(self.default_fg, 7),
                ColorRole::Background => self.resolve_default(self.default_bg, 0),
                ColorRole::CursorColor => self.resolve_default(self.default_cursor_color, 7),
            },
        }
    }

    /// Active horizontal tab stops on the current grid, in ascending
    /// column order.
    ///
    /// Default stops are seeded every 8 columns (8, 16, 24, ...) per
    /// [VT100 chapter 3][vt100-ch3]. `HTS` (`ESC H`) inserts a stop at
    /// the current column, `TBC` (`CSI g`) clears one or all, and `\t`
    /// consults the set to advance the cursor.
    ///
    /// Reflects the active grid: switching to or from the alternate
    /// screen changes the iterated columns.
    ///
    /// [vt100-ch3]: https://vt100.net/docs/vt100-ug/chapter3.html
    #[doc(alias = "HTS")]
    #[doc(alias = "TBC")]
    pub fn tab_stops(&self) -> impl Iterator<Item = u16> + '_ {
        self.grid().tab_stops()
    }

    fn resolve_default(&self, slot: crate::attrs::Color, fallback_index: u8) -> (u8, u8, u8) {
        match slot {
            crate::attrs::Color::Rgb(r, g, b) => (r, g, b),
            crate::attrs::Color::Index(i) => self.palette[usize::from(i)],
            crate::attrs::Color::Default => self.palette[usize::from(fallback_index)],
        }
    }

    pub(crate) fn grid(&self) -> &crate::grid::Grid {
        if self.has_mode_bit(MODE_ALTERNATE_SCREEN) {
            &self.alternate_grid
        } else {
            &self.grid
        }
    }

    pub(super) fn grid_mut(&mut self) -> &mut crate::grid::Grid {
        if self.has_mode_bit(MODE_ALTERNATE_SCREEN) {
            &mut self.alternate_grid
        } else {
            &mut self.grid
        }
    }

    pub(super) fn enter_alternate_grid(&mut self) {
        self.grid_mut().set_scrollback(0);
        self.set_mode(MODE_ALTERNATE_SCREEN);
        self.alternate_grid.allocate_rows();
        // Visible content jumps to the alternate grid's rows; embedders
        // copying Screen -> buffer must recopy every row on the next
        // frame.
        self.alternate_grid.mark_all_dirty();
        std::mem::swap(&mut self.kitty_flags, &mut self.kitty_flags_alt);
        let new_flags = self.kitty_flags.current();
        let old_flags = self.kitty_flags_alt.current();
        if new_flags != old_flags {
            self.pending_events
                .push(ScreenEvent::KittyFlagsChanged(new_flags));
        }
    }

    pub(super) fn exit_alternate_grid(&mut self) {
        self.clear_mode(MODE_ALTERNATE_SCREEN);
        // Same reason as enter: visible content snaps back to the
        // primary grid, so every row needs recopy on the next frame.
        self.grid.mark_all_dirty();
        std::mem::swap(&mut self.kitty_flags, &mut self.kitty_flags_alt);
        let new_flags = self.kitty_flags.current();
        let old_flags = self.kitty_flags_alt.current();
        if new_flags != old_flags {
            self.pending_events
                .push(ScreenEvent::KittyFlagsChanged(new_flags));
        }
    }

    pub(crate) fn kitty_push(&mut self, flags: u8) {
        let old = self.kitty_flags.current();
        self.kitty_flags.push(flags);
        let new = self.kitty_flags.current();
        if old != new {
            self.pending_events
                .push(ScreenEvent::KittyFlagsChanged(new));
        }
    }

    pub(crate) fn kitty_pop(&mut self, count: u16) {
        let old = self.kitty_flags.current();
        self.kitty_flags.pop(count);
        let new = self.kitty_flags.current();
        if old != new {
            self.pending_events
                .push(ScreenEvent::KittyFlagsChanged(new));
        }
    }

    pub(crate) fn kitty_set(&mut self, flags: u8, mode: u16) {
        let old = self.kitty_flags.current();
        self.kitty_flags.set(flags, mode);
        let new = self.kitty_flags.current();
        if old != new {
            self.pending_events
                .push(ScreenEvent::KittyFlagsChanged(new));
        }
    }

    pub(crate) fn kitty_query(&mut self) {
        let flags = self.kitty_flags.current();
        self.pending_events
            .push(ScreenEvent::KittyKeyboardQuery { flags });
    }

    pub(super) fn save_cursor(&mut self) {
        self.grid_mut().save_cursor();
        self.saved_attrs = self.attrs;
        self.saved_charsets = self.charsets;
        self.saved_active_charset = self.active_charset;
    }

    pub(super) fn restore_cursor(&mut self) {
        self.grid_mut().restore_cursor();
        self.attrs = self.saved_attrs;
        self.charsets = self.saved_charsets;
        self.active_charset = self.saved_active_charset;
    }

    pub(super) fn set_mode(&mut self, mode: u32) {
        self.modes |= mode;
    }

    pub(super) fn clear_mode(&mut self, mode: u32) {
        self.modes &= !mode;
    }

    /// Set or clear a mode flag, emitting a `ModeChanged` event if the mode
    /// is externally meaningful and the value actually changed.
    pub(super) fn set_mode_with_event(&mut self, flag: u32, enabled: bool) {
        let was = self.has_mode_bit(flag);
        if enabled {
            self.set_mode(flag);
        } else {
            self.clear_mode(flag);
        }
        if was != enabled
            && let Some(mode) = TerminalMode::from_mode_flag(flag)
        {
            self.pending_events
                .push(ScreenEvent::ModeChanged { mode, enabled });
        }
    }

    /// Return whether the externally meaningful `mode` is currently active.
    ///
    /// This is the canonical accessor for the boolean state behind every
    /// `TerminalMode` variant. Embedders that need to react to a mode
    /// change (input encoding, mouse routing, focus reports, sync-update
    /// frame batching) read it through this method; the per-mode getter
    /// surface that previously exposed each variant individually has
    /// been removed.
    #[must_use]
    pub fn mode(&self, mode: TerminalMode) -> bool {
        self.has_mode_bit(mode.mode_bit())
    }

    pub(super) fn has_mode_bit(&self, bit: u32) -> bool {
        self.modes & bit != 0
    }
}

pub(crate) fn u16_to_u8(i: u16) -> Option<u8> {
    u8::try_from(i).ok()
}

#[cfg(test)]
mod tests;