aboutsummaryrefslogtreecommitdiffstats
path: root/src/cursor.rs
blob: e6f99f1bd2a49fbda3ab899182834f08851ce6cf (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
use std::io::{self, Write};

#[derive(Debug, Clone, Copy)]
pub enum Direction {
    Up,
    Down,
    Left,
    Right,
}

pub fn fmove_cursor(direction: Direction, n: usize, stdout: &mut dyn Write) -> std::io::Result<()> {
    if n == 0 {
        return Ok(());
    }

    let code = match direction {
        Direction::Up => 'A',
        Direction::Down => 'B',
        Direction::Right => 'C',
        Direction::Left => 'D',
    };

    write!(stdout, "\x1b[{n}{code}")
}

pub fn move_cursor(direction: Direction, n: usize) {
    fmove_cursor(direction, n, &mut std::io::stdout()).unwrap()
}

pub fn f_save(stdout: &mut dyn Write) -> std::io::Result<()> {
    stdout.write_all(b"\x1b[s")
}

pub fn f_restore(stdout: &mut dyn Write) -> std::io::Result<()> {
    stdout.write_all(b"\x1b[u")
}

pub fn save() {
    f_save(&mut std::io::stdout().lock()).unwrap();
}

pub fn restore() {
    f_restore(&mut std::io::stdout().lock()).unwrap();
}

/// Represents a cursor position
#[derive(Debug, Clone, Copy)]
pub struct CursorPos {
    pub row: usize,
    pub col: usize,
}

impl Default for CursorPos {
    fn default() -> Self {
        Self { row: 1, col: 1 }
    }
}

impl CursorPos {
    pub fn f_go_to(&self, stdout: &mut dyn Write) -> std::io::Result<()> {
        write!(stdout, "\x1b[{};{}H", self.row, self.col)
    }

    pub fn go_to(&self) {
        let mut stdout = io::stdout().lock();
        self.f_go_to(&mut stdout).unwrap();
        stdout.flush().unwrap();
    }
}