tty_interface/
device.rs

1use crate::{pos, Position, Result, Vector};
2
3/// An output device to be controlled for displaying an interface.
4pub trait Device: std::io::Write {
5    /// Retrieve the device's terminal viewport size.
6    fn get_terminal_size(&mut self) -> Result<Vector>;
7
8    /// Enable "raw mode" in the terminal.
9    fn enable_raw_mode(&mut self) -> Result<()>;
10
11    /// Restore the configuration before the terminal was placed in "raw mode".
12    fn disable_raw_mode(&mut self) -> Result<()>;
13
14    /// Retrieve the cursor's absolute position in the device's buffer.
15    fn get_cursor_position(&mut self) -> Result<Position>;
16}
17
18impl Device for std::io::Stdout {
19    fn get_terminal_size(&mut self) -> Result<Vector> {
20        let (columns, lines) = crossterm::terminal::size()?;
21        Ok(Vector::new(columns, lines))
22    }
23
24    fn enable_raw_mode(&mut self) -> Result<()> {
25        crossterm::terminal::enable_raw_mode()?;
26        Ok(())
27    }
28
29    fn disable_raw_mode(&mut self) -> Result<()> {
30        crossterm::terminal::disable_raw_mode()?;
31        Ok(())
32    }
33
34    fn get_cursor_position(&mut self) -> Result<Position> {
35        let (column, row) = crossterm::cursor::position()?;
36        Ok(pos!(column, row))
37    }
38}