aboutsummaryrefslogtreecommitdiffstats
path: root/src/blocking.rs
blob: 538f051f863f5b764663ea1198abe5c71dbcafd5 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
use std::io::Write as _;

use super::private::TextmodeImpl as _;

pub struct Textmode {
    cur: vt100::Parser,
    next: vt100::Parser,
}

impl super::private::TextmodeImpl for Textmode {
    fn cur(&self) -> &vt100::Parser {
        &self.cur
    }

    fn cur_mut(&mut self) -> &mut vt100::Parser {
        &mut self.cur
    }

    fn next(&self) -> &vt100::Parser {
        &self.next
    }

    fn next_mut(&mut self) -> &mut vt100::Parser {
        &mut self.next
    }
}

impl super::TextmodeExt for Textmode {}

impl Textmode {
    pub fn new() -> std::io::Result<Self> {
        let (rows, cols) = match terminal_size::terminal_size() {
            Some((terminal_size::Width(w), terminal_size::Height(h))) => {
                (h, w)
            }
            _ => (24, 80),
        };
        let cur = vt100::Parser::new(rows, cols, 0);
        let next = vt100::Parser::new(rows, cols, 0);

        let self_ = Self { cur, next };
        self_.write_stdout(super::INIT)?;
        Ok(self_)
    }

    pub fn refresh(&mut self) -> std::io::Result<()> {
        let diffs = &[
            self.next().screen().contents_diff(self.cur().screen()),
            self.next().screen().input_mode_diff(self.cur().screen()),
            self.next().screen().title_diff(self.cur().screen()),
            self.next().screen().bells_diff(self.cur().screen()),
        ];
        for diff in diffs {
            self.write_stdout(&diff)?;
            self.cur_mut().process(&diff);
        }
        Ok(())
    }

    fn write_stdout(&self, buf: &[u8]) -> std::io::Result<()> {
        let mut stdout = std::io::stdout();
        stdout.write_all(buf)?;
        stdout.flush()?;
        Ok(())
    }
}

impl Drop for Textmode {
    fn drop(&mut self) {
        let _ = self.write_stdout(super::DEINIT);
    }
}