Skip to main content

justerm_core/term/
logical.rs

1//! Viewport logical lines: the soft-wrap-joined text of everything touching the
2//! viewport, plus a per-char map back to the cell it came from.
3//!
4//! The returned shape and *why* this is core rather than consumer are stated in
5//! [`crate::logical`]. Read it there; this module is the `Term` half — the cell-aware
6//! assembly, which needs the whole buffer and so cannot live in a frame-mode consumer
7//! (ADR-0017).
8//!
9//! Two things are local to this site. It is the **first of the three alt-screen floor
10//! misses** (#113): the up-walk into scrollback stops at `abs_floor()`, because on the alt
11//! screen that scrollback belongs to the *primary* buffer — see
12//! `docs/map/invariant/alt-screen-buffer-floor.md`, where this is site one of the discovery
13//! history. And the walk deliberately reaches **past the viewport in both directions**, so a
14//! line wrapping in from above the top or out past the bottom still joins whole; the
15//! off-screen rows surface as an out-of-range `row` in `LogicalLine::cells` for the consumer
16//! to clip.
17//!
18//! Nothing here is `pub(super)`. The one entry point is public API, and every helper it
19//! walks with was already in `walk.rs` before this module existed — which is what made this
20//! the cheapest of #584's five slices rather than a measure of its importance.
21
22use crate::logical::LogicalLine;
23
24use super::Term;
25
26impl Term {
27    /// The viewport's logical lines (#113/ADR-0017): each line's text plus a
28    /// per-char map to its viewport `(row, col)`. Wide-char spacers are skipped
29    /// and trailing blanks trimmed (so the text is 1:1 with `cells`). Empty rows
30    /// are dropped. The cell-aware assembly the consumer can't do in frame mode.
31    ///
32    /// **The run walk is unbounded on purpose** (`docs/architecture.md`), and this is the
33    /// one of the three walks where that costs anything: normally `O(viewport)`, but on a
34    /// buffer whose whole scrollback is one soft-wrapped run it is `O(scrollback)` —
35    /// measured at 7.3 ms against 17 µs for the same bytes as short lines. If a bound is
36    /// ever wanted, two things are already decided and neither is obvious from here:
37    ///
38    /// - **It is a sibling, not a parameter.** Adding `max_run: Option<usize>` to this
39    ///   signature is a breaking change; the crate's idiom for exactly this is
40    ///   [`Term::search`] / [`Term::search_with`], and #844 pinned the growth rule on the
41    ///   options struct (*"a new option lands through `..Default::default()`"*). So a
42    ///   `viewport_logical_lines_with` is additive — meaning 1.0.0 does not gate it.
43    /// - **The hard part is the trim, not the counter** — see the trim below.
44    ///
45    /// Closed as #206 with the reach measured at zero: nothing outside this crate's tests
46    /// and benches calls this today. `benches/wrap_run.rs` re-measures on demand.
47    pub fn viewport_logical_lines(&self) -> Vec<LogicalLine> {
48        let rows = self.grid.rows();
49        let total = self.scrollback.len() + rows;
50        let top = self.scrollback.len() - self.display_offset; // abs line of viewport row 0
51        let bottom = top + rows; // abs lines [top, bottom) are on screen
52
53        // If viewport row 0 is a wrap-continuation, walk up into scrollback to
54        // the logical line's true start so an edge-spanning URL still matches —
55        // floored, because on alt that scrollback is the *primary* buffer's.
56        let floor = self.abs_floor();
57        let mut start = top;
58        while start > floor && self.abs_row(start - 1).is_wrapped() {
59            start -= 1;
60        }
61
62        let mut out = Vec::new();
63        let mut line = start;
64        while line < bottom {
65            // Accumulate one logical line forward while each row soft-wraps; the
66            // tail may run past `bottom` (off-screen below) — included too.
67            let mut text = String::new();
68            let mut map: Vec<(i32, usize)> = Vec::new();
69            let mut cur = line;
70            loop {
71                let cells = self.abs_line(cur);
72                for (col, cell) in cells.iter().enumerate() {
73                    if cell.is_spacer() {
74                        continue;
75                    }
76                    // Signed viewport row: < 0 above the top, >= rows below.
77                    let vrow = cur as i32 - top as i32;
78                    text.push(cell.c());
79                    map.push((vrow, col));
80                    // Combining marks (#45) ride the same cell — append each and
81                    // map it to that cell so `text` stays 1:1 with `cells`.
82                    if let Some(marks) = self.combining_at(cur, col) {
83                        for &m in marks {
84                            text.push(m);
85                            map.push((vrow, col));
86                        }
87                    }
88                }
89                let soft = self.abs_row(cur).is_wrapped();
90                if soft && cur + 1 < total {
91                    cur += 1;
92                } else {
93                    break;
94                }
95            }
96            // Trim trailing blanks (only the last row can have them), keeping
97            // `text` and `cells` in lockstep.
98            //
99            // "Only the last row can have them" is a premise about where the loop above
100            // stopped, and it is what a run-length bound (#206) would break: a window that
101            // cuts mid-run ends the text at a row that is *not* the logical end, where the
102            // padding this trims is not padding. The rule it would then be applying to
103            // written content is `only-U+0020-can-be-padding` (#685), so a bound has to
104            // re-answer that at the cut point rather than reuse this line.
105            let trimmed = text.trim_end_matches(' ');
106            map.truncate(trimmed.chars().count());
107            text.truncate(trimmed.len());
108            if !text.is_empty() {
109                out.push(LogicalLine { text, cells: map });
110            }
111            line = cur + 1;
112        }
113        out
114    }
115}