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
//! Logical-line iteration over a [`Screen`].
//!
//! A logical line is a contiguous run of physical rows that the terminal
//! presented as a single line of text: either one row (when soft wraps
//! are not joined) or several rows joined back together at every
//! position where the renderer overflowed the rightmost column rather
//! than emitting a line feed.
//!
//! [`Screen::logical_lines`] returns an iterator that walks the visible
//! grid (or, with `include_scrollback`, the scrollback then drawing
//! region) and yields one [`LogicalLineSpan`] per logical line. The
//! in-crate callers (`Screen::contents_plain`, `Screen::contents_formatted`,
//! reflow primitives) and out-of-crate callers (the `tastty-driver`
//! search engine) share this single walking implementation, so
//! row-level wrap handling is not re-derived at each call site.
//!
//! Each yielded span carries the inclusive absolute-row range it
//! covers and a [`LogicalLineSpan::cells`] iterator that yields each
//! cell paired with its scrollback-stable [`AbsolutePosition`]. That
//! pairing is what lets external consumers key a result (a search
//! match, a hover region, ...) to a position that survives subsequent
//! scrolling.

use super::{AbsolutePosition, Screen};
use crate::cell::Cell;
use crate::grid::Grid;
use crate::row::Row;

/// Knobs for [`Screen::logical_lines`].
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct LogicalLineOptions {
    /// Walk the scrollback rows (oldest first) before the live drawing
    /// region. The viewport scroll offset is ignored.
    pub include_scrollback: bool,
    /// Drop trailing rows that have no displayable text. "No
    /// displayable text" matches `Cell::has_contents() == false` for
    /// every cell in the row; callers that need to keep styling-only
    /// rows must walk via the in-crate `from_rows` entry point with a
    /// custom upper bound.
    pub trim_trailing_blanks: bool,
    /// Join soft-wrapped physical rows into a single span. With this
    /// disabled, every physical row is its own span.
    pub join_wrapped: bool,
}

/// One physical row paired with its scrollback-stable absolute index.
pub(crate) struct GatheredRow<'screen> {
    pub abs_row: u64,
    pub row: &'screen Row,
}

/// One logical line.
///
/// `rows.len()` (reported via [`LogicalLineSpan::row_count`]) is at
/// least 1 and is greater than 1 only when `join_wrapped` is set and
/// the renderer wrapped the line at its right edge.
///
/// [`LogicalLineSpan::start`] and [`LogicalLineSpan::end`] carry the
/// inclusive absolute-row range covered by the span, matching
/// [`SelectionRange`](crate::screen::SelectionRange)'s inclusive-pair
/// convention. `start.col` is always 0; `end.col` is the index of the
/// rightmost populated cell on the final row (`Cell::has_contents`),
/// or 0 when the final row carries no text.
pub struct LogicalLineSpan<'screen> {
    pub(crate) rows: Vec<&'screen Row>,
    /// Absolute position of the first cell of the span (column 0 on
    /// the first row).
    pub start: AbsolutePosition,
    /// Absolute position of the last populated cell on the final row,
    /// or `(end_row, 0)` when the final row carries no text.
    pub end: AbsolutePosition,
    pub(crate) cols: u16,
}

impl<'screen> LogicalLineSpan<'screen> {
    /// Number of physical rows joined into this logical line. Always
    /// at least 1; greater than 1 only when soft-wrap joining is on
    /// and the renderer wrapped the line at its right edge.
    #[must_use]
    pub fn row_count(&self) -> usize {
        self.rows.len()
    }

    /// Iterate the cells of this span in display order, paired with
    /// each cell's scrollback-stable [`AbsolutePosition`].
    ///
    /// Trailing halves of [wide characters](https://www.unicode.org/reports/tr11/)
    /// are skipped, so each wide cell appears exactly once at its
    /// lead-half column. Empty cells
    /// are yielded with their column index unchanged so callers can
    /// preserve column alignment when materializing the span as text.
    pub fn cells(&self) -> impl Iterator<Item = (AbsolutePosition, &'screen Cell)> + '_ {
        let start_row = self.start.row;
        let cols = self.cols;
        self.rows
            .iter()
            .enumerate()
            .flat_map(move |(row_offset, row)| {
                let abs_row = start_row + row_offset as u64;
                (0..cols).filter_map(move |col| {
                    let cell = row.get(col)?;
                    if cell.is_wide_continuation() {
                        return None;
                    }
                    Some((AbsolutePosition { row: abs_row, col }, cell))
                })
            })
    }
}

/// Iterator returned by [`Screen::logical_lines`].
pub struct LogicalLines<'screen> {
    rows: Vec<GatheredRow<'screen>>,
    cursor: usize,
    upper_bound: usize,
    join_wrapped: bool,
    cols: u16,
}

impl<'screen> Iterator for LogicalLines<'screen> {
    type Item = LogicalLineSpan<'screen>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.cursor >= self.upper_bound {
            return None;
        }
        let start = self.cursor;
        let mut end = start;
        if self.join_wrapped {
            while end + 1 < self.upper_bound && self.rows[end].row.wrapped() {
                end += 1;
            }
        }
        let span_rows: Vec<&Row> = self.rows[start..=end].iter().map(|g| g.row).collect();
        let start_pos = AbsolutePosition {
            row: self.rows[start].abs_row,
            col: 0,
        };
        let end_pos = AbsolutePosition {
            row: self.rows[end].abs_row,
            col: last_populated_col(self.rows[end].row, self.cols),
        };
        self.cursor = end + 1;
        Some(LogicalLineSpan {
            rows: span_rows,
            start: start_pos,
            end: end_pos,
            cols: self.cols,
        })
    }
}

fn last_populated_col(row: &Row, cols: u16) -> u16 {
    (0..cols)
        .rev()
        .find(|&col| row.get(col).is_some_and(crate::cell::Cell::has_contents))
        .unwrap_or(0)
}

/// Gather the rows that [`Screen::logical_lines`] would walk, paired
/// with each row's absolute index. Exposed so callers needing a
/// non-default trim predicate (currently `contents_formatted`, which
/// keeps rows whose cells carry only non-default attrs) can compute
/// their bound on the same row collection without re-deriving the
/// scrollback / viewport plumbing.
pub(crate) fn gather_rows(grid: &Grid, include_scrollback: bool) -> Vec<GatheredRow<'_>> {
    if include_scrollback {
        let scrollback_count = grid.scrollback_available() as u64;
        let base = grid.pushed_to_scrollback().saturating_sub(scrollback_count);
        grid.scrollback_rows()
            .chain(grid.drawing_rows())
            .enumerate()
            .map(|(j, row)| GatheredRow {
                abs_row: base + j as u64,
                row,
            })
            .collect()
    } else {
        let viewport_top = grid
            .pushed_to_scrollback()
            .saturating_sub(grid.scrollback() as u64);
        grid.visible_rows()
            .enumerate()
            .map(|(j, row)| GatheredRow {
                abs_row: viewport_top + j as u64,
                row,
            })
            .collect()
    }
}

/// Build a logical-line iterator from a pre-gathered row collection
/// and an explicit upper bound. `upper_bound` is clamped to
/// `rows.len()`; rows beyond it are skipped.
pub(crate) fn from_rows<'a>(
    rows: Vec<GatheredRow<'a>>,
    upper_bound: usize,
    join_wrapped: bool,
    cols: u16,
) -> LogicalLines<'a> {
    let upper_bound = upper_bound.min(rows.len());
    LogicalLines {
        rows,
        cursor: 0,
        upper_bound,
        join_wrapped,
        cols,
    }
}

pub(crate) fn iter<'a>(screen: &'a Screen, opts: LogicalLineOptions) -> LogicalLines<'a> {
    iter_grid(screen.grid(), opts)
}

pub(crate) fn iter_grid<'a>(grid: &'a Grid, opts: LogicalLineOptions) -> LogicalLines<'a> {
    let cols = grid.size().cols;
    let rows = gather_rows(grid, opts.include_scrollback);
    let upper_bound = if opts.trim_trailing_blanks {
        rows.iter()
            .rposition(|gathered| {
                (0..cols).any(|col| {
                    gathered
                        .row
                        .get(col)
                        .is_some_and(crate::cell::Cell::has_contents)
                })
            })
            .map(|last| last + 1)
            .unwrap_or(0)
    } else {
        rows.len()
    };
    from_rows(rows, upper_bound, opts.join_wrapped, cols)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::Parser;
    use crate::screen::TerminalSize;

    #[test]
    fn yields_one_span_per_row_when_join_disabled() {
        let mut parser = Parser::new(TerminalSize { rows: 4, cols: 8 }, 0);
        parser.process(b"abcdefghIJ");
        let opts = LogicalLineOptions {
            join_wrapped: false,
            trim_trailing_blanks: true,
            ..Default::default()
        };
        let spans: Vec<_> = parser.screen().logical_lines(opts).collect();
        assert_eq!(spans.len(), 2, "two rows have content");
        assert_eq!(spans[0].rows.len(), 1);
        assert_eq!(spans[1].rows.len(), 1);
    }

    #[test]
    fn joins_wrapped_continuation_into_one_span() {
        let mut parser = Parser::new(TerminalSize { rows: 4, cols: 8 }, 0);
        parser.process(b"abcdefghIJ");
        let opts = LogicalLineOptions {
            join_wrapped: true,
            trim_trailing_blanks: true,
            ..Default::default()
        };
        let spans: Vec<_> = parser.screen().logical_lines(opts).collect();
        assert_eq!(spans.len(), 1, "wrapped pair forms one logical line");
        assert_eq!(spans[0].rows.len(), 2);
    }

    #[test]
    fn explicit_newline_breaks_wrap_join() {
        let mut parser = Parser::new(TerminalSize { rows: 6, cols: 8 }, 0);
        parser.process(b"abcdefghIJ\r\nnext");
        let opts = LogicalLineOptions {
            join_wrapped: true,
            trim_trailing_blanks: true,
            ..Default::default()
        };
        let spans: Vec<_> = parser.screen().logical_lines(opts).collect();
        assert_eq!(spans.len(), 2, "explicit \\n must end the logical line");
        assert_eq!(spans[0].rows.len(), 2, "wrapped pair stays joined");
        assert_eq!(spans[1].rows.len(), 1, "next is its own span");
    }

    #[test]
    fn includes_scrollback_when_requested() {
        let mut parser = Parser::new(TerminalSize { rows: 3, cols: 10 }, 100);
        for i in 0..6 {
            parser.process(format!("line{i}\r\n").as_bytes());
        }
        assert!(parser.screen().scrollback_available() >= 4);

        let viewport_only = parser.screen().logical_lines(LogicalLineOptions {
            trim_trailing_blanks: true,
            ..Default::default()
        });
        assert_eq!(viewport_only.count(), 2);

        let with_history = parser.screen().logical_lines(LogicalLineOptions {
            include_scrollback: true,
            trim_trailing_blanks: true,
            ..Default::default()
        });
        assert_eq!(with_history.count(), 6);
    }

    #[test]
    fn trim_trailing_blanks_drops_empty_rows() {
        let mut parser = Parser::new(TerminalSize { rows: 5, cols: 10 }, 0);
        parser.process(b"hello");
        let trimmed = parser
            .screen()
            .logical_lines(LogicalLineOptions {
                trim_trailing_blanks: true,
                ..Default::default()
            })
            .count();
        assert_eq!(trimmed, 1);
        let untrimmed = parser
            .screen()
            .logical_lines(LogicalLineOptions {
                trim_trailing_blanks: false,
                ..Default::default()
            })
            .count();
        assert_eq!(untrimmed, 5);
    }

    #[test]
    fn from_rows_caps_at_caller_upper_bound() {
        let mut parser = Parser::new(TerminalSize { rows: 5, cols: 10 }, 0);
        parser.process(b"hello\r\nworld\r\n!");
        let cols = parser.screen().grid().size().cols;
        let rows = gather_rows(parser.screen().grid(), false);
        let iter = from_rows(rows, 2, false, cols);
        let spans: Vec<_> = iter.collect();
        assert_eq!(spans.len(), 2, "caller-supplied bound caps the walk");
    }

    #[test]
    fn single_row_span_carries_viewport_row_position() {
        let mut parser = Parser::new(TerminalSize { rows: 4, cols: 10 }, 0);
        parser.process(b"hello");
        let opts = LogicalLineOptions {
            trim_trailing_blanks: true,
            ..Default::default()
        };
        let spans: Vec<_> = parser.screen().logical_lines(opts).collect();
        assert_eq!(spans.len(), 1);
        let span = &spans[0];
        let abs_row_zero = parser
            .screen()
            .visible_to_absolute(crate::screen::Position { row: 0, col: 0 })
            .expect("viewport row 0 maps to an absolute row");
        assert_eq!(span.start, abs_row_zero);
        assert_eq!(span.end.row, abs_row_zero.row);
        assert_eq!(span.end.col, 4, "rightmost populated col of \"hello\" is 4");
    }

    #[test]
    fn wrapped_two_row_span_covers_both_absolute_rows() {
        let mut parser = Parser::new(TerminalSize { rows: 4, cols: 8 }, 0);
        parser.process(b"abcdefghIJ");
        let opts = LogicalLineOptions {
            join_wrapped: true,
            trim_trailing_blanks: true,
            ..Default::default()
        };
        let spans: Vec<_> = parser.screen().logical_lines(opts).collect();
        assert_eq!(spans.len(), 1);
        let span = &spans[0];
        let row0 = parser
            .screen()
            .visible_to_absolute(crate::screen::Position { row: 0, col: 0 })
            .unwrap();
        let row1 = parser
            .screen()
            .visible_to_absolute(crate::screen::Position { row: 1, col: 0 })
            .unwrap();
        assert_eq!(span.start.row, row0.row);
        assert_eq!(span.start.col, 0);
        assert_eq!(span.end.row, row1.row);
        assert_eq!(span.end.col, 1, "\"IJ\" populates cols 0..=1 on row 1");
    }

    #[test]
    fn scrollback_walk_yields_monotonic_contiguous_rows() {
        let mut parser = Parser::new(TerminalSize { rows: 3, cols: 10 }, 100);
        for i in 0..6 {
            parser.process(format!("line{i}\r\n").as_bytes());
        }
        let opts = LogicalLineOptions {
            include_scrollback: true,
            trim_trailing_blanks: true,
            ..Default::default()
        };
        let spans: Vec<_> = parser.screen().logical_lines(opts).collect();
        assert_eq!(spans.len(), 6);

        let oldest_scrollback = parser.screen().grid().pushed_to_scrollback()
            - parser.screen().scrollback_available() as u64;
        let pushed = parser.screen().grid().pushed_to_scrollback();
        let mut crossed_boundary = false;
        for (i, span) in spans.iter().enumerate() {
            let expected_row = oldest_scrollback + i as u64;
            assert_eq!(
                span.start.row, expected_row,
                "span {i} should start at absolute row {expected_row}"
            );
            assert_eq!(span.end.row, expected_row);
            if span.start.row >= pushed {
                crossed_boundary = true;
            }
        }
        assert!(
            crossed_boundary,
            "walk must include both scrollback and drawing rows"
        );
    }

    #[test]
    fn wrap_across_scrollback_boundary_yields_one_joined_span() {
        let mut parser = Parser::new(TerminalSize { rows: 2, cols: 8 }, 100);
        parser.process(b"abcdefghIJ\r\nnext");

        assert_eq!(parser.screen().scrollback_available(), 1);
        let scrollback_row = parser.screen().grid().pushed_to_scrollback() - 1;

        let opts = LogicalLineOptions {
            include_scrollback: true,
            join_wrapped: true,
            trim_trailing_blanks: true,
        };
        let spans: Vec<_> = parser.screen().logical_lines(opts).collect();
        assert_eq!(
            spans.len(),
            2,
            "wrap straddling the boundary plus a trailing line yields two spans"
        );

        let wrap_span = &spans[0];
        assert_eq!(wrap_span.rows.len(), 2, "wrap is joined into one span");
        assert_eq!(wrap_span.start.row, scrollback_row);
        assert_eq!(wrap_span.start.col, 0);
        assert_eq!(wrap_span.end.row, scrollback_row + 1);
        assert_eq!(
            wrap_span.end.col, 1,
            "\"IJ\" populates cols 0..=1 on the final row"
        );

        let next_span = &spans[1];
        assert_eq!(next_span.rows.len(), 1);
        assert_eq!(next_span.start.row, scrollback_row + 2);
        assert_eq!(next_span.end.row, scrollback_row + 2);
    }
}