vt100/parser.rs
1/// A parser for terminal output which produces an in-memory representation of
2/// the terminal contents.
3pub struct Parser<CB: crate::callbacks::Callbacks = ()> {
4 parser: vte::Parser,
5 screen: crate::perform::WrappedScreen<CB>,
6}
7
8impl Parser {
9 /// Creates a new terminal parser of the given size and with the given
10 /// amount of scrollback.
11 #[must_use]
12 pub fn new(rows: u16, cols: u16, scrollback_len: usize) -> Self {
13 Self {
14 parser: vte::Parser::new(),
15 screen: crate::perform::WrappedScreen::new(
16 rows,
17 cols,
18 scrollback_len,
19 ),
20 }
21 }
22}
23
24impl<CB: crate::callbacks::Callbacks> Parser<CB> {
25 /// Creates a new terminal parser of the given size and with the given
26 /// amount of scrollback. Terminal events will be reported via method
27 /// calls on the provided [`Callbacks`](crate::callbacks::Callbacks)
28 /// implementation.
29 pub fn new_with_callbacks(
30 rows: u16,
31 cols: u16,
32 scrollback_len: usize,
33 callbacks: CB,
34 ) -> Self {
35 Self {
36 parser: vte::Parser::new(),
37 screen: crate::perform::WrappedScreen::new_with_callbacks(
38 rows,
39 cols,
40 scrollback_len,
41 callbacks,
42 ),
43 }
44 }
45
46 /// Processes the contents of the given byte string, and updates the
47 /// in-memory terminal state.
48 pub fn process(&mut self, bytes: &[u8]) {
49 self.parser.advance(&mut self.screen, bytes);
50 }
51
52 /// Returns a reference to a [`Screen`](crate::Screen) object containing
53 /// the terminal state.
54 #[must_use]
55 pub fn screen(&self) -> &crate::Screen {
56 &self.screen.screen
57 }
58
59 /// Returns a mutable reference to a [`Screen`](crate::Screen) object
60 /// containing the terminal state.
61 #[must_use]
62 pub fn screen_mut(&mut self) -> &mut crate::Screen {
63 &mut self.screen.screen
64 }
65
66 /// Returns a reference to the [`Callbacks`](crate::callbacks::Callbacks)
67 /// state object passed into the constructor.
68 pub fn callbacks(&self) -> &CB {
69 &self.screen.callbacks
70 }
71
72 /// Returns a mutable reference to the
73 /// [`Callbacks`](crate::callbacks::Callbacks) state object passed into
74 /// the constructor.
75 pub fn callbacks_mut(&mut self) -> &mut CB {
76 &mut self.screen.callbacks
77 }
78}
79
80impl Default for Parser {
81 /// Returns a parser with dimensions 80x24 and no scrollback.
82 fn default() -> Self {
83 Self::new(24, 80, 0)
84 }
85}
86
87impl std::io::Write for Parser {
88 fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
89 self.process(buf);
90 Ok(buf.len())
91 }
92
93 fn flush(&mut self) -> std::io::Result<()> {
94 Ok(())
95 }
96}