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
73
74
75
76
77
78
#[link(name="ncurses")]
extern {
    fn initscr();
    fn endwin();

    fn getch() -> u8;
    fn mvaddch(y: u64, x: u64, c: u8);
    #[link_name="move"]
    fn move_cursor(y: u64, x: u64);
    fn addch(c: u8);

    fn curs_set(on: u64);
    fn echo();
    fn noecho();

    fn cbreak();
    fn nocbreak();
}

/// The struct to control the ncurses terminal
/// Basically, it makes sure that the terminal 
/// gets created and deleted correctly
pub struct Console;

impl Drop for Console {
    /// De-initialize the terminal
    /// before deletion of the struct
    fn drop(&mut self){
        unsafe {
            nocbreak();
            curs_set(1);
            echo();
            endwin();
        }
    }
}

impl Console {

    /// Initialize the console, this probably should only be allowed once
    /// I have no idea what would happen if you try to create more than one
    /// on the same tty
    pub fn new() -> Console{
        unsafe {
            initscr();
            noecho();
            cbreak();
            curs_set(0);
        }
        Console
    }

    /// Read a single character from the input
    pub fn read(&self) -> char {
        unsafe {
            getch() as char
        }
    }

    /// Write a character to a specific place on-screen
    /// will not display if off-screen
    pub fn write(&self, x: u64, y: u64, c: char) {
        unsafe {
            mvaddch(y,x,c as u8);
        }
    }

    /// Print out an entire string char by char
    pub fn print(&self, x: u64, y: u64, s: String){
        unsafe {
            move_cursor(y,x);
            for c in s.chars() {
                addch(c as u8);
            }
        }
    }
}