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
use crate::Result;
use crossterm::cursor::*;
use crossterm::queue;
use std::{cell::RefCell, rc::Rc};

#[derive(Debug, Clone)]
pub struct Raw<W: std::io::Write> {
    pub raw: Rc<RefCell<W>>,
}
impl<W: std::io::Write> std::io::Write for Raw<W> {
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        self.raw.borrow_mut().write(buf)
    }
    fn flush(&mut self) -> std::io::Result<()> {
        self.raw.borrow_mut().flush()
    }
}

impl<W: std::io::Write> Raw<W> {
    pub fn restore_position(&mut self) -> Result<()> {
        queue!(self, RestorePosition)?;
        Ok(())
    }

    pub fn save_position(&mut self) -> Result<()> {
        queue!(self, SavePosition)?;
        Ok(())
    }

    pub fn move_down(&mut self, n: u16) -> Result<()> {
        queue!(self, MoveDown(n))?;
        Ok(())
    }

    pub fn move_up(&mut self, n: u16) -> Result<()> {
        queue!(self, MoveUp(n))?;
        Ok(())
    }

    pub fn show(&mut self) -> Result<()> {
        queue!(self, Show)?;
        Ok(())
    }

    pub fn hide(&mut self) -> Result<()> {
        queue!(self, Hide)?;
        Ok(())
    }

    pub fn goto(&mut self, x: u16, y: u16) -> Result<()> {
        queue!(self, MoveTo(x, y))?;
        Ok(())
    }

    pub fn size(&self) -> Result<(usize, usize)> {
        Ok(crossterm::terminal::size().map(|(w, h)| (w as usize, h as usize))?)
    }

    pub fn get_current_pos(&mut self) -> Result<(usize, usize)> {
        // position only uses stdout()
        Ok(crossterm::cursor::position().map(|(w, h)| (w as usize, h as usize))?)
    }
}