justerm_core/grid.rs
1//! The grid — the 2D array of cells representing the current screen.
2//!
3//! Rows are stored as separate `Vec`s (not one flat buffer) so the scrollback
4//! ring (a later slice) can move whole rows in/out cheaply.
5
6use crate::cell::{Cell, CellFlags};
7use core::num::NonZeroU32;
8use std::collections::BTreeMap;
9use std::ops::{Deref, DerefMut};
10
11/// A row's combining clusters: column → the combining marks attached to that
12/// column's base glyph. Sparse (most rows have none) and **flag-gated** — an
13/// entry is only ever read when the cell at that column has its
14/// `COMBINED_PRESENT` bit set (xterm's `_combined` invariant, #45). Stale entries
15/// left by an overwrite/erase are therefore harmless; only live entries must be
16/// carried when cells move column (ICH/DCH/reflow).
17type Combining = BTreeMap<usize, Vec<char>>;
18
19/// A row's hyperlinks: column → the global `hyperlink_pool` index (OSC 8). Same
20/// per-row, flag-gated sparse-map design as [`Combining`], gated by the cell's
21/// `LINK_PRESENT` bit instead (xterm's `_extendedAttrs` / `HAS_EXTENDED`, #46).
22type Links = BTreeMap<usize, NonZeroU32>;
23
24/// Re-key a sparse column map to follow a `copy_within(src, dst)` cell shift: the
25/// live entry for a moved cell travels to the cell's new column. Vacated source
26/// keys whose cell loses its gate bit are left stale — harmless under the
27/// flag-gate — so only the live carry is done. Generic over the value type so the
28/// combining and link maps share one implementation.
29fn move_map<V>(map: &mut BTreeMap<usize, V>, src: std::ops::Range<usize>, dst: usize) {
30 if map.is_empty() {
31 return;
32 }
33 let start = src.start;
34 let moved: Vec<(usize, V)> = src
35 .filter_map(|s| map.remove(&s).map(|v| (dst + (s - start), v)))
36 .collect();
37 for (col, v) in moved {
38 map.insert(col, v);
39 }
40}
41
42/// One row of cells **plus** its per-row, column-keyed combining and link maps.
43///
44/// The maps ride with the row through scroll / scrollback / reflow for free (the
45/// row is the unit that moves), which is why combining (#45) and hyperlinks (#46)
46/// live here rather than in global per-cell indices — no leak, cleared on row
47/// reuse. `Row` derefs to `[Cell]`, so index/iterate/slice sites are unchanged;
48/// the maps are reached through the dedicated methods so the flag-gate (read iff
49/// the cell's `COMBINED_PRESENT` / `LINK_PRESENT` bit is set) is never bypassed.
50#[derive(Clone, Debug, PartialEq, Eq, Default)]
51pub struct Row {
52 cells: Vec<Cell>,
53 combining: Combining,
54 links: Links,
55}
56
57impl Row {
58 /// A row of `cols` blank cells.
59 pub(crate) fn blank(cols: usize) -> Row {
60 Row {
61 cells: vec![Cell::default(); cols],
62 combining: Combining::new(),
63 links: Links::new(),
64 }
65 }
66
67 /// Wrap a cell vector as a row with no combining marks or links.
68 pub(crate) fn from_cells(cells: Vec<Cell>) -> Row {
69 Row {
70 cells,
71 combining: Combining::new(),
72 links: Links::new(),
73 }
74 }
75
76 /// Build a row from cells and its maps (the reflow re-split path).
77 pub(crate) fn new(cells: Vec<Cell>, combining: Combining, links: Links) -> Row {
78 Row {
79 cells,
80 combining,
81 links,
82 }
83 }
84
85 /// Consume the row into its cells, combining map, and link map (the reflow
86 /// join path).
87 pub(crate) fn into_parts(self) -> (Vec<Cell>, Combining, Links) {
88 (self.cells, self.combining, self.links)
89 }
90
91 /// Resize to `cols`, padding with blanks or truncating; map entries for
92 /// dropped columns are pruned (xterm's shrink-prune).
93 pub(crate) fn resize(&mut self, cols: usize) {
94 self.cells.resize(cols, Cell::default());
95 if self
96 .combining
97 .keys()
98 .next_back()
99 .is_some_and(|&m| m >= cols)
100 {
101 self.combining.retain(|&col, _| col < cols);
102 }
103 if self.links.keys().next_back().is_some_and(|&m| m >= cols) {
104 self.links.retain(|&col, _| col < cols);
105 }
106 }
107
108 /// Empty the row, keeping the cell allocation — for recycling a row buffer
109 /// (`scroll_up_recycle`). Clears cells and both maps so a reused row never
110 /// surfaces a previous occupant's marks or links.
111 pub(crate) fn clear(&mut self) {
112 self.cells.clear();
113 self.combining.clear();
114 self.links.clear();
115 }
116
117 /// The combining marks at `col`, or `None`. Flag-gated: returns `Some` only
118 /// when the cell carries the `COMBINED_PRESENT` bit, so a stale map entry is
119 /// never surfaced.
120 pub(crate) fn combining_at(&self, col: usize) -> Option<&[char]> {
121 if self.cells[col].is_combined() {
122 self.combining.get(&col).map(Vec::as_slice)
123 } else {
124 None
125 }
126 }
127
128 /// The hyperlink-pool index at `col`, or `None`. Flag-gated by the cell's
129 /// `LINK_PRESENT` bit (mirror of [`Row::combining_at`]).
130 pub(crate) fn link_at(&self, col: usize) -> Option<NonZeroU32> {
131 if self.cells[col].is_linked() {
132 self.links.get(&col).copied()
133 } else {
134 None
135 }
136 }
137
138 /// Attach a combining mark to `col`'s glyph. The first mark on a cell starts a
139 /// fresh cluster — dropping any stale entry an overwrite left behind (the bit
140 /// was clear) — and sets the presence bit; subsequent marks append. Mirrors
141 /// xterm's `addCodepointToCell`.
142 pub(crate) fn push_combining(&mut self, col: usize, mark: char) {
143 if self.cells[col].is_combined() {
144 self.combining.entry(col).or_default().push(mark);
145 } else {
146 self.cells[col].set_combined(true);
147 self.combining.insert(col, vec![mark]);
148 }
149 }
150
151 /// Stamp `col`'s glyph with a hyperlink-pool index, setting the presence bit
152 /// (the print path calls this on every cell written while a link is open).
153 pub(crate) fn set_link(&mut self, col: usize, link: NonZeroU32) {
154 self.cells[col].set_linked(true);
155 self.links.insert(col, link);
156 }
157
158 /// Re-key both maps to follow a `copy_within(src, dst)` cell shift (ICH/DCH),
159 /// so a cluster or link stays attached to its glyph at the new column.
160 pub(crate) fn move_maps(&mut self, src: std::ops::Range<usize>, dst: usize) {
161 move_map(&mut self.combining, src.clone(), dst);
162 move_map(&mut self.links, src, dst);
163 }
164}
165
166impl Deref for Row {
167 type Target = [Cell];
168 fn deref(&self) -> &[Cell] {
169 &self.cells
170 }
171}
172
173impl DerefMut for Row {
174 fn deref_mut(&mut self) -> &mut [Cell] {
175 &mut self.cells
176 }
177}
178
179/// Re-wrap physical `rows` to `new_cols`. Soft-wrapped rows (WRAPLINE on the
180/// last cell) are joined into logical lines, then each logical line is re-split
181/// at `new_cols` with WRAPLINE set on every segment but the last. Trailing blank
182/// rows are absorbed (re-created by the caller's row-count fit). See #7.
183///
184/// `points` are `(row, col)` coordinates to track through the reflow (the cursor
185/// and any selection anchors); the returned `Vec` maps each to its new position,
186/// index-aligned with the input.
187///
188/// Common-90%: trailing blanks on a hard-ended row are trimmed, and a wide-char
189/// split across the new boundary is not yet special-cased.
190pub(crate) fn reflow(
191 rows: Vec<Row>,
192 new_cols: usize,
193 points: &[(usize, usize)],
194) -> (Vec<Row>, Vec<(usize, usize)>) {
195 // 1. Join soft-wrapped rows into logical lines, recording each tracked
196 // point's logical coordinate (line index + offset within the line). The
197 // combining map is carried alongside: a row's entries are re-keyed by the
198 // join offset so a cluster stays attached to its glyph across the wrap.
199 let mut logical: Vec<Vec<Cell>> = Vec::new();
200 let mut logical_comb: Vec<Combining> = Vec::new();
201 let mut logical_links: Vec<Links> = Vec::new();
202 let mut current: Vec<Cell> = Vec::new();
203 let mut current_comb: Combining = Combining::new();
204 let mut current_links: Links = Links::new();
205 // Per point: (logical line, offset, found-yet).
206 let mut tracked: Vec<(usize, usize, bool)> = vec![(0, 0, false); points.len()];
207 for (i, row) in rows.into_iter().enumerate() {
208 for (pi, &(pr, pc)) in points.iter().enumerate() {
209 if i == pr && !tracked[pi].2 {
210 tracked[pi] = (logical.len(), current.len() + pc, true);
211 }
212 }
213 let soft = row.last().is_some_and(|c| c.is_wrapline());
214 let base = current.len();
215 let (cells, comb, links) = row.into_parts();
216 // Carry live map entries, re-keyed to the logical-line offset (flag-gated:
217 // a stale entry whose cell lost its bit is dropped).
218 for (col, marks) in comb {
219 if cells[col].is_combined() {
220 current_comb.insert(base + col, marks);
221 }
222 }
223 for (col, link) in links {
224 if cells[col].is_linked() {
225 current_links.insert(base + col, link);
226 }
227 }
228 if soft {
229 let mut cells = cells;
230 // A wide char that wrapped at the boundary (write_glyph / relocate_cluster_wide) left a
231 // leading-spacer placeholder in the vacated last column. It is a wrap artefact, not
232 // content — drop it on the join so the logical line (and re-split) never carries a
233 // phantom blank into accessible_text / search / copy (#303). The `soft` flag was already
234 // read from this cell above, so removing it now is safe.
235 if cells.last().is_some_and(Cell::is_leading_spacer) {
236 cells.pop();
237 }
238 current.extend(cells.into_iter().map(|mut c| {
239 c.remove_flags(CellFlags::WRAPLINE);
240 c
241 }));
242 } else {
243 let mut cells = cells;
244 while cells.last() == Some(&Cell::default()) {
245 cells.pop();
246 }
247 current.extend(cells);
248 logical.push(std::mem::take(&mut current));
249 logical_comb.push(std::mem::take(&mut current_comb));
250 logical_links.push(std::mem::take(&mut current_links));
251 }
252 }
253 if !current.is_empty() {
254 logical.push(current);
255 logical_comb.push(current_comb);
256 logical_links.push(current_links);
257 }
258 // Trailing blank lines are absorbed, not preserved as rows (the maps are
259 // trimmed in lockstep so all three stay index-aligned).
260 while logical.last().is_some_and(|l| l.is_empty()) {
261 logical.pop();
262 logical_comb.pop();
263 logical_links.pop();
264 }
265
266 // 2. Re-split each logical line into `new_cols`-wide rows, mapping each
267 // tracked point to its new (row, col).
268 let mut out: Vec<Row> = Vec::new();
269 let mut new_points = vec![(0usize, 0usize); points.len()];
270 for (li, line) in logical.iter().enumerate() {
271 let comb = &logical_comb[li];
272 let links = &logical_links[li];
273 let start = out.len();
274 if line.is_empty() {
275 out.push(Row::blank(new_cols));
276 } else {
277 let mut i = 0;
278 while i < line.len() {
279 let mut take = (line.len() - i).min(new_cols);
280 // Don't split a wide char from its spacer: if the row would end
281 // on a WIDE_CHAR lead, drop it to the next row (xterm's newCols-1).
282 if i + take < line.len() && line[i + take - 1].is_wide() {
283 take -= 1;
284 }
285 let take = take.max(1); // guard the 1-col degenerate case
286 // Segment maps: entries in [i, i+take) re-keyed to col - i.
287 let seg_comb: Combining = comb
288 .range(i..i + take)
289 .map(|(&col, marks)| (col - i, marks.clone()))
290 .collect();
291 let seg_links: Links = links
292 .range(i..i + take)
293 .map(|(&col, &link)| (col - i, link))
294 .collect();
295 let mut row = Row::new(line[i..i + take].to_vec(), seg_comb, seg_links);
296 row.resize(new_cols);
297 i += take;
298 if i < line.len() {
299 row[new_cols - 1].insert_flags(CellFlags::WRAPLINE);
300 }
301 out.push(row);
302 }
303 }
304 for (pi, &(pl, poff, _)) in tracked.iter().enumerate() {
305 if pl == li {
306 let off = poff.min(line.len());
307 new_points[pi] = (start + off / new_cols, off % new_cols);
308 }
309 }
310 }
311 // A point whose logical line was trimmed (trailing blank) clamps to the end.
312 for (pi, &(pl, _, _)) in tracked.iter().enumerate() {
313 if pl >= logical.len() {
314 new_points[pi] = (out.len().saturating_sub(1), 0);
315 }
316 }
317
318 (out, new_points)
319}
320
321/// The current screen: `rows` × `cols` cells.
322#[derive(Clone, Debug)]
323pub struct Grid {
324 cols: usize,
325 rows: usize,
326 lines: Vec<Row>,
327}
328
329impl Grid {
330 /// A blank grid of the given size.
331 pub fn new(cols: usize, rows: usize) -> Self {
332 let lines = vec![Row::blank(cols); rows];
333 Grid { cols, rows, lines }
334 }
335
336 pub fn cols(&self) -> usize {
337 self.cols
338 }
339
340 pub fn rows(&self) -> usize {
341 self.rows
342 }
343
344 /// Read a cell. Panics on out-of-bounds (callers clamp to the grid).
345 pub fn cell(&self, row: usize, col: usize) -> &Cell {
346 &self.lines[row][col]
347 }
348
349 /// Mutable access to a cell.
350 pub fn cell_mut(&mut self, row: usize, col: usize) -> &mut Cell {
351 &mut self.lines[row][col]
352 }
353
354 /// Read a whole row.
355 pub fn row(&self, row: usize) -> &[Cell] {
356 &self.lines[row]
357 }
358
359 /// Read a whole row including its combining map — for combining-aware reads
360 /// (text extraction, serialization).
361 pub(crate) fn row_ref(&self, row: usize) -> &Row {
362 &self.lines[row]
363 }
364
365 /// Mutable access to a whole row (cells + combining map) — for in-row cell
366 /// shifts (ICH/DCH), which must re-key combining alongside the cell move.
367 pub(crate) fn row_mut(&mut self, row: usize) -> &mut Row {
368 &mut self.lines[row]
369 }
370
371 /// A clone of a whole row (cells + combining map) — for the sub-region scroll
372 /// eviction, which copies row 0 out to scrollback (the full-screen path moves
373 /// the row instead, via `scroll_up_recycle`).
374 pub(crate) fn row_owned(&self, row: usize) -> Row {
375 self.lines[row].clone()
376 }
377
378 /// Scroll the rows `[top..=bottom]` up by one line: the top line of the
379 /// region is dropped and a blank line appears at `bottom`. Rows outside the
380 /// region are untouched.
381 ///
382 /// `rotate_left` moves whole-row `Vec` *handles* (24 bytes each), not cell
383 /// data — cheap even at the screen's bounded row count, so the per-newline
384 /// scrollback cost lives in the *eviction*, not here (see `scroll_up_recycle`
385 /// and ADR-0009).
386 pub fn scroll_up_region(&mut self, top: usize, bottom: usize) {
387 // Rotate the region's top line to its bottom, then blank it: every line
388 // in the region shifts up one and the region's bottom becomes empty.
389 self.lines[top..=bottom].rotate_left(1);
390 for cell in self.lines[bottom].iter_mut() {
391 cell.reset();
392 }
393 }
394
395 /// Full-screen scroll up that **moves** the evicted top row out instead of
396 /// copying it (`Term::linefeed`'s hot path): `rotate_left` puts logical row 0
397 /// in the bottom slot, then a recycled `blank` is swapped into that slot and
398 /// the evicted row returned by value (the caller pushes it into scrollback).
399 /// The grid clears + fits `blank` to `cols`, so the caller may hand it a
400 /// dirty recycled row — reusing its allocation, so a steady-state flood does
401 /// no per-line alloc/copy (ADR-0009). No ring: the win is recycling the row
402 /// buffer, not making the cheap handle-rotate O(1).
403 pub(crate) fn scroll_up_recycle(&mut self, mut blank: Row) -> Row {
404 blank.clear(); // drop any recycled content (keeps the allocation)
405 blank.resize(self.cols);
406 self.lines.rotate_left(1); // logical row 0 -> the bottom slot
407 let last = self.rows - 1;
408 std::mem::replace(&mut self.lines[last], blank)
409 }
410
411 /// Extract all rows, leaving the grid empty. Used by `Term::resize` to
412 /// reflow the screen together with scrollback as one stream.
413 pub(crate) fn take_lines(&mut self) -> Vec<Row> {
414 std::mem::take(&mut self.lines)
415 }
416
417 /// Replace the screen with `lines` at `cols` x `rows`: each row is fit to
418 /// `cols` and the screen is padded with blank rows / truncated to `rows`.
419 pub(crate) fn set_screen(&mut self, mut lines: Vec<Row>, cols: usize, rows: usize) {
420 for row in &mut lines {
421 row.resize(cols);
422 }
423 while lines.len() < rows {
424 lines.push(Row::blank(cols));
425 }
426 lines.truncate(rows);
427 self.lines = lines;
428 self.cols = cols;
429 self.rows = rows;
430 }
431
432 /// Reset every cell to a blank default. Used when switching to the alt
433 /// screen (which always starts cleared).
434 pub fn clear(&mut self) {
435 for row in &mut self.lines {
436 for cell in row.iter_mut() {
437 cell.reset();
438 }
439 }
440 }
441
442 /// Scroll the rows `[top..=bottom]` down by one line: a blank line appears at
443 /// `top` and the bottom region line is dropped. Rows outside are untouched.
444 /// Used by RI (reverse index) at the top margin.
445 pub fn scroll_down_region(&mut self, top: usize, bottom: usize) {
446 // Rotate the region's bottom line to its top, then blank it: every line
447 // in the region shifts down one and the region's top becomes empty.
448 self.lines[top..=bottom].rotate_right(1);
449 for cell in self.lines[top].iter_mut() {
450 cell.reset();
451 }
452 }
453}
454
455#[cfg(test)]
456mod tests {
457 use super::*;
458
459 /// A grid whose row `r` carries the char `'a' + r` in column 0 — a distinct
460 /// marker per logical row so a scroll's row mapping is observable.
461 fn stamped(cols: usize, rows: usize) -> Grid {
462 let mut g = Grid::new(cols, rows);
463 for r in 0..rows {
464 g.cell_mut(r, 0).set_c(char::from(b'a' + r as u8));
465 }
466 g
467 }
468
469 /// Column-0 chars read top-to-bottom in *logical* row order.
470 fn col0(g: &Grid) -> String {
471 (0..g.rows()).map(|r| g.cell(r, 0).c()).collect()
472 }
473
474 #[test]
475 fn full_screen_scroll_up_shifts_content_and_blanks_bottom() {
476 let mut g = stamped(2, 3); // logical col0 = "abc"
477 g.scroll_up_region(0, 2);
478 assert_eq!(col0(&g), "bc "); // shifted up, bottom blanked
479 }
480
481 #[test]
482 fn full_screen_scroll_down_shifts_content_and_blanks_top() {
483 // RI at the top margin: blank appears at the top, the bottom line is lost.
484 let mut g = stamped(2, 3); // "abc"
485 g.scroll_down_region(0, 2);
486 assert_eq!(col0(&g), " ab");
487 }
488
489 #[test]
490 fn sub_region_scroll_leaves_rows_outside_the_region_untouched() {
491 let mut g = stamped(2, 4); // "abcd"
492 g.scroll_up_region(0, 1); // sub-region [0..=1] only
493 // rows 0..=1 ("ab") scroll up → "b" then blank; rows 2,3 ("c","d") stay.
494 assert_eq!(col0(&g), "b cd");
495 }
496
497 #[test]
498 fn scroll_up_recycle_moves_out_row0_and_blanks_a_dirty_recycled_row() {
499 let mut g = stamped(2, 3); // "abc"
500 // Hand it a *dirty* recycled row (full width, stale content) — the new
501 // bottom must come out blank, not carrying the recycled row's text.
502 let mut x = Cell::default();
503 x.set_c('X');
504 let dirty = Row::from_cells(vec![x; 2]);
505 let evicted = g.scroll_up_recycle(dirty);
506 assert_eq!(evicted[0].c(), 'a'); // logical row 0 moved out, not copied
507 assert_eq!(col0(&g), "bc "); // shifted up; bottom blank, NOT "bcX"
508 }
509
510 #[test]
511 fn take_lines_returns_rows_in_logical_order_after_a_scroll() {
512 // `reflow` assumes logical row order; `take_lines` must deliver it.
513 let mut g = stamped(1, 3); // "abc"
514 g.scroll_up_region(0, 2); // "bc "
515 let lines = g.take_lines();
516 let got: String = lines.iter().map(|r| r[0].c()).collect();
517 assert_eq!(got, "bc ");
518 }
519}