Skip to main content

strat9_kernel/arch/x86_64/vga/
scrollback.rs

1/*
2 * This file is part of strat9-os.
3 *
4 * strat9-os is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * strat9-os is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with strat9-os. If not, see <https://www.gnu.org/licenses/>.
16 *
17 * Website: https://www.strat9-os.org
18 * Repository: https://github.com/strat9-os/strat9-os
19 *
20 * Copyright (C) 2023-26 Guillaume Gielly
21 */
22
23//! Scrollback buffer for the framebuffer terminal.
24//!
25//! Implements a ring-buffer of character cells for scrollback, plus
26//! a "current" partial row that accumulates characters before a newline
27//! finalises it into the ring.
28
29use alloc::vec::Vec;
30
31/// Maximum number of scrollback lines retained.
32pub(crate) const MAX_SCROLLBACK: usize = 500;
33
34/// A single character cell stored in the scrollback buffer.
35#[derive(Clone, Copy)]
36pub(crate) struct SbCell {
37    pub ch: char,
38    pub fg: u32, // packed pixel colour
39    pub bg: u32, // packed pixel colour
40}
41
42/// Ring-buffer scrollback store.
43///
44/// `rows` holds the completed rows (capped at `MAX_SCROLLBACK + visible_rows`).
45/// `cur_row` accumulates the line currently being typed.
46/// `row_head` is the ring-buffer insertion index.
47pub(crate) struct ScrollbackBuffer {
48    /// Completed rows (ring buffer).
49    pub rows: Vec<Vec<SbCell>>,
50    /// Current (partial) row being accumulated.
51    pub cur_row: Vec<SbCell>,
52    /// Ring-buffer head index.
53    pub row_head: usize,
54}
55
56impl ScrollbackBuffer {
57    /// Create an empty scrollback.
58    pub const fn new() -> Self {
59        Self {
60            rows: Vec::new(),
61            cur_row: Vec::new(),
62            row_head: 0,
63        }
64    }
65
66    /// Maximum number of rows the buffer can hold before trimming.
67    #[inline]
68    pub fn capacity(&self, visible_rows: usize) -> usize {
69        MAX_SCROLLBACK + visible_rows + 1
70    }
71
72    /// Access a completed row by logical (oldest=>newest) index.
73    pub fn row_at(&self, logical_idx: usize) -> Option<&Vec<SbCell>> {
74        if logical_idx >= self.rows.len() {
75            return None;
76        }
77        let phys = (self.row_head + logical_idx) % self.rows.len();
78        self.rows.get(phys)
79    }
80
81    /// Push a completed row into the ring, growing or wrapping as needed.
82    pub fn push_row(&mut self, row: Vec<SbCell>, visible_rows: usize) {
83        let cap = self.capacity(visible_rows);
84        if cap == 0 {
85            return;
86        }
87        if self.rows.len() < cap {
88            self.rows.push(row);
89            return;
90        }
91        if self.rows.is_empty() {
92            self.rows.push(row);
93            self.row_head = 0;
94            return;
95        }
96        self.rows[self.row_head] = row;
97        self.row_head = (self.row_head + 1) % self.rows.len();
98    }
99
100    /// Trim the buffer so it does not exceed `MAX_SCROLLBACK + visible_rows`.
101    #[inline]
102    pub fn trim(&mut self, visible_rows: usize) {
103        let cap = self.capacity(visible_rows);
104        if self.rows.len() <= cap {
105            return;
106        }
107        let remove_count = self.rows.len() - cap;
108        self.rows.drain(..remove_count);
109        self.row_head = 0;
110    }
111
112    /// Mirror a single character into the current (partial) row,
113    /// finalising it into the ring when a newline or overflow occurs.
114    ///
115    /// `cols` = current terminal width in columns.
116    /// `fg` / `bg` = packed foreground / background colours for the cell.
117    pub fn mirror_char(&mut self, c: char, cols: usize, fg: u32, bg: u32, visible_rows: usize) {
118        match c {
119            '\n' => {
120                let row = core::mem::take(&mut self.cur_row);
121                self.push_row(row, visible_rows);
122                self.trim(visible_rows);
123            }
124            '\r' => {
125                self.cur_row.clear();
126            }
127            '\t' => {
128                let stop = (self.cur_row.len() + 4) & !3;
129                let end = stop.min(cols);
130                while self.cur_row.len() < end {
131                    self.cur_row.push(SbCell { ch: ' ', fg, bg });
132                }
133                if self.cur_row.len() >= cols {
134                    let row = core::mem::take(&mut self.cur_row);
135                    self.push_row(row, visible_rows);
136                    self.trim(visible_rows);
137                }
138            }
139            '\u{8}' => {
140                self.cur_row.pop();
141            }
142            '\0' => {}
143            ch => {
144                self.cur_row.push(SbCell { ch, fg, bg });
145                if self.cur_row.len() >= cols {
146                    let row = core::mem::take(&mut self.cur_row);
147                    self.push_row(row, visible_rows);
148                    self.trim(visible_rows);
149                }
150            }
151        }
152    }
153}