tastty-driver 0.1.0

Terminal automation driver built on tastty
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
use std::collections::BTreeSet;

use tastty::{Attrs, CursorStyle, Hyperlink, Position, Screen, TerminalMode, TerminalSize};

/// Rich terminal snapshot returned by driver operations.
///
/// Stores one row-major table of [`CellSnapshot`] values plus the
/// scalar metadata. [`Snapshot::lines`] and [`Snapshot::style_runs`]
/// derive from the cell table on each call.
#[derive(Debug, Eq, PartialEq)]
#[non_exhaustive]
pub struct Snapshot {
    pub(crate) size: TerminalSize,
    pub(crate) cursor: Position,
    pub(crate) cursor_visible: bool,
    pub(crate) alternate_screen: bool,
    pub(crate) title: String,
    pub(crate) icon_name: String,
    pub(crate) cells: Vec<Vec<CellSnapshot>>,
}

impl Snapshot {
    /// Current terminal size.
    #[must_use]
    pub fn size(&self) -> TerminalSize {
        self.size
    }

    /// Zero-based cursor position.
    #[must_use]
    pub fn cursor(&self) -> Position {
        self.cursor
    }

    /// Whether the cursor is visible.
    #[must_use]
    pub fn cursor_visible(&self) -> bool {
        self.cursor_visible
    }

    /// Whether the alternate screen buffer is active.
    #[must_use]
    pub fn alternate_screen(&self) -> bool {
        self.alternate_screen
    }

    /// Window title set through OSC 0/1/2.
    #[must_use]
    pub fn title(&self) -> &str {
        &self.title
    }

    /// Window icon name set through OSC 0/1.
    #[must_use]
    pub fn icon_name(&self) -> &str {
        &self.icon_name
    }

    /// Visible cells with text and style data, row-major.
    ///
    /// The outer index is the zero-based row and the inner index is
    /// the zero-based column. Wide character continuation cells
    /// occupy the trailing column slot and carry
    /// [`CellSnapshot::wide_continuation`] set.
    #[must_use]
    pub fn cells(&self) -> &[Vec<CellSnapshot>] {
        &self.cells
    }

    /// Visible screen rows as plain text, padded with spaces out to
    /// the column count.
    ///
    /// Each row in the returned vector preserves the cell-grid width:
    /// empty cells render as single spaces, wide character
    /// continuation halves are skipped, and trailing empty cells are
    /// preserved so a row's character count always reflects the
    /// column width. Trim per row at the use site for display.
    ///
    /// Derived from [`Self::cells`] on every call.
    #[must_use]
    pub fn lines(&self) -> Vec<String> {
        let cols = self.size.cols;
        self.cells
            .iter()
            .map(|row| line_from_row(row, cols))
            .collect()
    }

    /// Visible text of a single row, with the same per-row padding
    /// contract as [`Self::lines`]. Returns `None` when `row` is past
    /// the visible region.
    #[must_use]
    pub fn line(&self, row: u16) -> Option<String> {
        self.cells
            .get(row as usize)
            .map(|cells| line_from_row(cells, self.size.cols))
    }

    /// Per-row style runs grouped from adjacent cells with equal
    /// attributes.
    ///
    /// Derived from [`Self::cells`] on every call.
    #[must_use]
    pub fn style_runs(&self) -> Vec<Vec<StyleRun>> {
        self.cells
            .iter()
            .map(|row| style_runs_for_row(row))
            .collect()
    }

    /// Return visible text rows joined by newlines.
    ///
    /// Each row preserves the per-row padding shape of
    /// [`Self::lines`]. A regex anchored with `$` against the joined
    /// text matches the end of a row only when the row is full; for
    /// substring or `.*`-style matches anchoring is unaffected.
    #[must_use]
    pub fn text(&self) -> String {
        self.lines().join("\n")
    }

    /// Iterate over [OSC 8][osc8] hyperlink runs visible in this snapshot.
    ///
    /// Walks [`Self::cells`] row-major and yields one
    /// `(`[`Position`]`, &`[`Hyperlink`]`)` pair per maximal run of
    /// adjacent cells that share the same `Hyperlink` value. The
    /// position is the row and column of the first cell of the run.
    /// Wide-cell continuation halves (cells with
    /// [`CellSnapshot::wide_continuation`] set) are skipped during
    /// the walk, so a hyperlink covering a single wide character
    /// surfaces as one run, not two.
    ///
    /// Cells without a hyperlink act as run boundaries: a `None`
    /// cell sandwiched between two cells carrying the same link
    /// yields two separate entries. The walk also stops at row
    /// boundaries. OSC 8 has no wire convention for continuing a
    /// link across a line wrap, so a link that extends to the end
    /// of one row and resumes at the start of the next surfaces as
    /// two entries.
    ///
    /// [osc8]: https://gist.github.com/egmontkob/eb8d45597f7db55ec41d6c0ffc6f3bb3
    pub fn hyperlinks(&self) -> impl Iterator<Item = (Position, &Hyperlink)> + '_ {
        self.cells
            .iter()
            .enumerate()
            .flat_map(|(row, row_cells)| row_hyperlinks(row as u16, row_cells))
    }
}

fn line_from_row(cells: &[CellSnapshot], cols: u16) -> String {
    let mut text = String::new();
    let mut col: u16 = 0;
    while col < cols {
        if let Some(cell) = cells.get(col as usize) {
            if cell.wide_continuation {
                col += 1;
                continue;
            }
            if cell.contents.is_empty() {
                text.push(' ');
            } else {
                text.push_str(&cell.contents);
            }
            col += if cell.wide { 2 } else { 1 };
        } else {
            text.push(' ');
            col += 1;
        }
    }
    text
}

fn row_hyperlinks(row: u16, cells: &[CellSnapshot]) -> Vec<(Position, &Hyperlink)> {
    let mut out: Vec<(Position, &Hyperlink)> = Vec::new();
    let mut prev: Option<&Hyperlink> = None;

    for (col, cell) in cells.iter().enumerate() {
        if cell.wide_continuation {
            continue;
        }
        match cell.hyperlink.as_ref() {
            Some(link) => {
                if prev != Some(link) {
                    out.push((
                        Position {
                            row,
                            col: col as u16,
                        },
                        link,
                    ));
                }
                prev = Some(link);
            }
            None => prev = None,
        }
    }

    out
}

/// Snapshot of one visible terminal cell.
///
/// Stored row-major inside [`Snapshot::cells`]: the outer index is the
/// zero-based row and the inner index is the zero-based column. The
/// snapshot has no `position` field of its own; callers that need
/// `(row, col)` derive them from the indices used to reach the cell.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub struct CellSnapshot {
    /// Cell text contents. Empty cells use an empty string.
    pub contents: String,
    /// Complete SGR attributes.
    pub attrs: Attrs,
    /// Whether the cell starts a wide character.
    pub wide: bool,
    /// Whether the cell is the continuation half of a wide character.
    pub wide_continuation: bool,
    /// OSC 8 hyperlink association, if present.
    ///
    /// Cloned from the parser-side [`Hyperlink`]; both `id` and `uri`
    /// keep their `Arc<str>` payloads so the snapshot stays cheap to
    /// hold and to clone.
    pub hyperlink: Option<Hyperlink>,
}

/// Plain text snapshot including retained scrollback before visible rows.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub struct ScrollbackSnapshot {
    /// Retained scrollback rows followed by visible screen rows.
    pub lines: Vec<String>,
    /// Number of rows in [`Self::lines`] that came from scrollback.
    pub scrollback_lines: usize,
}

/// Terminal mode and metadata state captured from one screen view.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub struct InspectSnapshot {
    /// Every [`TerminalMode`](tastty::TerminalMode) variant whose bit is
    /// currently set on the source screen.
    ///
    /// The set covers each variant whose state is observable through
    /// [`Screen::mode`](tastty::Screen::mode); adding a new variant to
    /// `TerminalMode` is paired with a one-line addition in the snapshot
    /// populator, so callers reading `modes` see the full active mode set
    /// without growing this struct's public API. Iteration order follows
    /// the [`Ord`] derive on `TerminalMode` (declaration order); membership
    /// is checked through [`BTreeSet::contains`].
    pub modes: BTreeSet<TerminalMode>,
    /// Current cursor style.
    pub cursor_style: CursorStyle,
    /// Current Kitty keyboard enhancement flags.
    pub kitty_keyboard_flags: u8,
    /// Window title set through OSC 0/1/2.
    pub title: String,
    /// Window icon name set through OSC 0/1.
    pub icon_name: String,
    /// Current terminal size.
    pub size: TerminalSize,
}

/// Adjacent cell range sharing the same style.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub struct StyleRun {
    /// Inclusive starting column.
    pub start_col: u16,
    /// Exclusive ending column.
    pub end_col: u16,
    /// Complete SGR attributes shared by the range.
    pub attrs: Attrs,
}

pub(crate) fn snapshot_from_screen(screen: &Screen) -> Snapshot {
    let size = screen.size();
    let mut cells = Vec::with_capacity(size.rows as usize);

    for row in 0..size.rows {
        let mut row_cells: Vec<CellSnapshot> = Vec::with_capacity(size.cols as usize);
        for col in 0..size.cols {
            if let Some(cell) = screen.cell(row, col) {
                row_cells.push(CellSnapshot {
                    contents: cell.contents().to_string(),
                    attrs: *cell.attrs(),
                    wide: cell.is_wide(),
                    wide_continuation: cell.is_wide_continuation(),
                    hyperlink: cell.hyperlink().cloned(),
                });
            }
        }
        cells.push(row_cells);
    }

    Snapshot {
        size,
        cursor: screen.cursor(),
        cursor_visible: !screen.mode(TerminalMode::HideCursor),
        alternate_screen: screen.mode(TerminalMode::AlternateScreen),
        title: screen.title().to_string(),
        icon_name: screen.icon_name().to_string(),
        cells,
    }
}

fn style_runs_for_row(cells: &[CellSnapshot]) -> Vec<StyleRun> {
    let mut runs: Vec<StyleRun> = Vec::new();

    for (col, cell) in cells.iter().enumerate() {
        if cell.wide_continuation {
            continue;
        }
        let col = col as u16;

        if let Some(last) = runs.last_mut()
            && last.attrs == cell.attrs
            && last.end_col == col
        {
            last.end_col = col + cell_width(cell);
            continue;
        }

        runs.push(StyleRun {
            start_col: col,
            end_col: col + cell_width(cell),
            attrs: cell.attrs,
        });
    }

    runs
}

fn cell_width(cell: &CellSnapshot) -> u16 {
    if cell.wide { 2 } else { 1 }
}

pub(crate) fn scrollback_snapshot_from_screen(
    screen: &Screen,
    limit: Option<usize>,
) -> ScrollbackSnapshot {
    let mut lines = screen.scrollback_contents(limit);
    let scrollback_lines = lines.len();
    lines.extend(screen.visible_text_rows());
    ScrollbackSnapshot {
        lines,
        scrollback_lines,
    }
}

pub(crate) fn inspect_snapshot_from_screen(screen: &Screen) -> InspectSnapshot {
    let candidates = [
        TerminalMode::ApplicationCursor,
        TerminalMode::BracketedPaste,
        TerminalMode::MouseReportClick,
        TerminalMode::MouseReportCellMotion,
        TerminalMode::MouseReportAllMotion,
        TerminalMode::FocusInOut,
        TerminalMode::SgrMouse,
        TerminalMode::SgrPixelMouse,
        TerminalMode::SyncUpdate,
        TerminalMode::GraphemeCluster,
        TerminalMode::ColorSchemeUpdates,
        TerminalMode::InBandResize,
        TerminalMode::AlternateScreen,
        TerminalMode::HideCursor,
        TerminalMode::ReverseVideo,
        TerminalMode::AlternateScroll,
        TerminalMode::MouseReportX10,
        TerminalMode::BackspaceBs,
        TerminalMode::LineFeedNewLine,
    ];
    let modes = candidates.into_iter().filter(|m| screen.mode(*m)).collect();
    InspectSnapshot {
        modes,
        cursor_style: screen.cursor_style(),
        kitty_keyboard_flags: screen.kitty_keyboard_flags(),
        title: screen.title().to_string(),
        icon_name: screen.icon_name().to_string(),
        size: screen.size(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::BTreeSet;
    use tastty::{Parser, TerminalSize};

    #[test]
    fn inspect_modes_collects_active_terminal_modes() {
        let mut parser = Parser::new(TerminalSize { rows: 4, cols: 16 }, 0);
        // ?2004h -> bracketed paste, ?25l -> hide cursor, ?1049h -> alt screen,
        // ?5h -> reverse video, ?67h -> backspace-bs (DECBKM). The last two
        // exercise variants the prior boolean-field shape did not surface.
        parser.process(b"\x1b[?2004h\x1b[?25l\x1b[?1049h\x1b[?5h\x1b[?67h");

        let snapshot = inspect_snapshot_from_screen(parser.screen());

        let expected: BTreeSet<TerminalMode> = [
            TerminalMode::BracketedPaste,
            TerminalMode::HideCursor,
            TerminalMode::AlternateScreen,
            TerminalMode::ReverseVideo,
            TerminalMode::BackspaceBs,
        ]
        .into_iter()
        .collect();
        assert_eq!(snapshot.modes, expected);
    }

    #[test]
    fn inspect_modes_empty_for_default_screen() {
        let parser = Parser::new(TerminalSize { rows: 4, cols: 16 }, 0);
        let snapshot = inspect_snapshot_from_screen(parser.screen());
        assert!(snapshot.modes.is_empty());
    }

    #[test]
    fn cell_snapshots_indexed_by_column() {
        let mut parser = Parser::new(TerminalSize { rows: 1, cols: 5 }, 0);
        parser.process(b"abcde");
        let snap = snapshot_from_screen(parser.screen());
        let row = &snap.cells()[0];
        assert_eq!(row.len(), 5);
        for (col, cell) in row.iter().enumerate() {
            let glyph = b"abcde"[col] as char;
            assert_eq!(cell.contents, glyph.to_string(), "col={col}");
        }
    }

    #[test]
    fn snapshot_preserves_osc8_hyperlink_directly() {
        let mut parser = Parser::new(TerminalSize { rows: 1, cols: 4 }, 0);
        parser.process(b"\x1b]8;;https://example.com/\x1b\\X\x1b]8;;\x1b\\");
        let snap = snapshot_from_screen(parser.screen());
        let cell = &snap.cells()[0][0];
        let link = cell
            .hyperlink
            .as_ref()
            .expect("OSC 8 hyperlink should be captured on the cell");
        assert_eq!(link.uri.as_ref(), "https://example.com/");
        assert!(link.id.is_none());
    }

    #[test]
    fn hyperlinks_empty_when_no_links_present() {
        let mut parser = Parser::new(TerminalSize { rows: 2, cols: 4 }, 0);
        parser.process(b"abcdEFGH");
        let snap = snapshot_from_screen(parser.screen());
        assert_eq!(snap.hyperlinks().count(), 0);
    }

    #[test]
    fn hyperlinks_yields_single_run_for_contiguous_same_link() {
        let mut parser = Parser::new(TerminalSize { rows: 1, cols: 6 }, 0);
        parser.process(b"\x1b]8;;https://example.com/\x1b\\ABC\x1b]8;;\x1b\\");
        let snap = snapshot_from_screen(parser.screen());
        let links: Vec<_> = snap.hyperlinks().collect();
        assert_eq!(links.len(), 1);
        let (pos, link) = links[0];
        assert_eq!(pos, Position { row: 0, col: 0 });
        assert_eq!(link.uri.as_ref(), "https://example.com/");
    }

    #[test]
    fn hyperlinks_splits_runs_on_uri_change() {
        let mut parser = Parser::new(TerminalSize { rows: 1, cols: 6 }, 0);
        parser.process(b"\x1b]8;;https://a/\x1b\\X\x1b]8;;https://b/\x1b\\Y\x1b]8;;\x1b\\");
        let snap = snapshot_from_screen(parser.screen());
        let links: Vec<_> = snap.hyperlinks().collect();
        assert_eq!(links.len(), 2);
        assert_eq!(links[0].0, Position { row: 0, col: 0 });
        assert_eq!(links[0].1.uri.as_ref(), "https://a/");
        assert_eq!(links[1].0, Position { row: 0, col: 1 });
        assert_eq!(links[1].1.uri.as_ref(), "https://b/");
    }

    #[test]
    fn hyperlinks_splits_runs_on_id_change_with_same_uri() {
        let mut parser = Parser::new(TerminalSize { rows: 1, cols: 6 }, 0);
        parser.process(
            b"\x1b]8;id=a;https://example.com/\x1b\\X\
              \x1b]8;id=b;https://example.com/\x1b\\Y\
              \x1b]8;;\x1b\\",
        );
        let snap = snapshot_from_screen(parser.screen());
        let links: Vec<_> = snap.hyperlinks().collect();
        assert_eq!(links.len(), 2);
        assert_eq!(links[0].1.id.as_deref().map(AsRef::as_ref), Some("a"));
        assert_eq!(links[1].1.id.as_deref().map(AsRef::as_ref), Some("b"));
    }

    #[test]
    fn hyperlinks_treats_unlinked_cells_as_boundaries() {
        let mut parser = Parser::new(TerminalSize { rows: 1, cols: 6 }, 0);
        parser.process(
            b"\x1b]8;;https://example.com/\x1b\\A\x1b]8;;\x1b\\B\
              \x1b]8;;https://example.com/\x1b\\C\x1b]8;;\x1b\\",
        );
        let snap = snapshot_from_screen(parser.screen());
        let links: Vec<_> = snap.hyperlinks().collect();
        assert_eq!(links.len(), 2);
        assert_eq!(links[0].0, Position { row: 0, col: 0 });
        assert_eq!(links[1].0, Position { row: 0, col: 2 });
        assert_eq!(links[0].1, links[1].1);
    }

    #[test]
    fn hyperlinks_skips_wide_cell_continuation() {
        let mut parser = Parser::new(TerminalSize { rows: 1, cols: 4 }, 0);
        // CJK ideograph "中" is double-width; the OSC 8 region wraps it
        // plus a following ASCII char, so the run spans cells 0..=2 with
        // cell 1 being the wide continuation half.
        parser.process("\x1b]8;;https://example.com/\x1b\\中X\x1b]8;;\x1b\\".as_bytes());
        let snap = snapshot_from_screen(parser.screen());
        assert!(snap.cells()[0][1].wide_continuation);
        let links: Vec<_> = snap.hyperlinks().collect();
        assert_eq!(links.len(), 1);
        assert_eq!(links[0].0, Position { row: 0, col: 0 });
    }

    #[test]
    fn hyperlinks_does_not_cross_row_boundaries() {
        let mut parser = Parser::new(TerminalSize { rows: 2, cols: 4 }, 0);
        // Open a link, write enough characters to wrap from row 0 into
        // row 1, then close the link. OSC 8 has no wire convention for
        // continuing a link across a line wrap, so the two rows should
        // surface as two separate runs.
        parser.process(b"\x1b]8;;https://example.com/\x1b\\ABCDEFGH\x1b]8;;\x1b\\");
        let snap = snapshot_from_screen(parser.screen());
        let links: Vec<_> = snap.hyperlinks().collect();
        assert_eq!(links.len(), 2);
        assert_eq!(links[0].0, Position { row: 0, col: 0 });
        assert_eq!(links[1].0, Position { row: 1, col: 0 });
        assert_eq!(links[0].1, links[1].1);
    }

    #[test]
    fn lines_pad_each_row_to_column_width() {
        let mut parser = Parser::new(TerminalSize { rows: 2, cols: 8 }, 0);
        parser.process(b"hi");
        let snap = snapshot_from_screen(parser.screen());
        let lines = snap.lines();
        assert_eq!(lines.len(), 2);
        assert_eq!(lines[0].chars().count(), 8);
        assert!(lines[0].starts_with("hi"));
        assert!(lines[0].ends_with("      "));
        assert_eq!(lines[1].chars().count(), 8);
        assert_eq!(lines[1], "        ");
    }

    #[test]
    fn line_returns_same_padding_as_lines_for_indexed_row() {
        let mut parser = Parser::new(TerminalSize { rows: 2, cols: 6 }, 0);
        parser.process(b"ab");
        let snap = snapshot_from_screen(parser.screen());
        let lines = snap.lines();
        assert_eq!(snap.line(0), Some(lines[0].clone()));
        assert_eq!(snap.line(1), Some(lines[1].clone()));
        assert_eq!(snap.line(2), None);
    }

    #[test]
    fn lines_render_wide_glyph_in_one_char_and_pad_to_column_width() {
        let mut parser = Parser::new(TerminalSize { rows: 1, cols: 6 }, 0);
        parser.process("中X".as_bytes());
        let snap = snapshot_from_screen(parser.screen());

        // cells() column 0 is the wide head, column 1 is the continuation,
        // column 2 is the trailing ASCII.
        let row = &snap.cells()[0];
        assert!(row[0].wide);
        assert!(row[1].wide_continuation);
        assert_eq!(row[2].contents, "X");

        let line = snap.line(0).expect("row 0 visible");
        // Two chars of content (the wide glyph counts as one char) and
        // three padding spaces out to the cell-grid width.
        assert_eq!(line.chars().count(), 5);
        assert!(line.starts_with("中X"));
        assert!(line.ends_with("   "));
    }

    #[test]
    fn text_joins_padded_rows_with_newlines() {
        let mut parser = Parser::new(TerminalSize { rows: 2, cols: 4 }, 0);
        parser.process(b"ab\r\ncd");
        let snap = snapshot_from_screen(parser.screen());
        let text = snap.text();
        let parts: Vec<&str> = text.split('\n').collect();
        assert_eq!(parts.len(), 2);
        assert!(parts[0].starts_with("ab"));
        assert!(parts[1].starts_with("cd"));
        assert_eq!(parts[0].chars().count(), 4);
        assert_eq!(parts[1].chars().count(), 4);
    }

    #[test]
    fn style_runs_group_adjacent_cells_with_same_attrs() {
        let mut parser = Parser::new(TerminalSize { rows: 1, cols: 6 }, 0);
        // "AB" in red, then default-colored "CD".
        parser.process(b"\x1b[31mAB\x1b[0mCD");
        let snap = snapshot_from_screen(parser.screen());

        let runs = snap.style_runs();
        assert_eq!(runs.len(), 1);
        let row0 = &runs[0];
        assert!(
            row0.len() >= 2,
            "expected at least two runs for split styling, got {row0:?}"
        );
        assert_eq!(row0[0].start_col, 0);
        assert_eq!(row0[0].end_col, 2);
        assert_eq!(row0[1].start_col, 2);
    }

    #[test]
    fn accessors_match_construction_inputs() {
        let mut parser = Parser::new(TerminalSize { rows: 4, cols: 12 }, 0);
        parser.process(b"\x1b[?25lhello");
        let snap = snapshot_from_screen(parser.screen());

        assert_eq!(snap.size(), TerminalSize { rows: 4, cols: 12 });
        assert_eq!(snap.cursor(), Position { row: 0, col: 5 });
        assert!(!snap.cursor_visible());
        assert!(!snap.alternate_screen());
        assert_eq!(snap.title(), "");
        assert_eq!(snap.icon_name(), "");
    }
}