aboutsummaryrefslogtreecommitdiffstats
path: root/src/term.rs
blob: 149f00f1d28b24e223ee5aade3ba90fb775003de (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
use libc::{termios, winsize};

pub fn size() -> Option<winsize> {
    unsafe {
        let mut window: winsize = std::mem::zeroed();
        if libc::ioctl(1, libc::TIOCGWINSZ, &mut window) < 0 {
            return None;
        }
        return Some(window);
    }
}

fn get_attr() -> Option<termios> {
    unsafe {
        let mut attr: termios = std::mem::zeroed();
        if libc::tcgetattr(1, &mut attr) < 0 {
            return None;
        }
        return Some(attr);
    }
}

fn set_attr(attrs: &termios) -> Option<()> {
    unsafe {
        if libc::tcsetattr(1, libc::TCSANOW, attrs) < 0 {
            return None;
        }
        return Some(());
    }
}

fn make_raw() -> termios {
    unsafe {
        let mut attr: termios = std::mem::zeroed();
        libc::cfmakeraw(&mut attr);
        return attr;
    }
}

pub struct RawHandle {
    old: termios,
}

impl Drop for RawHandle {
    fn drop(&mut self) {
        set_attr(&self.old);
    }
}

pub fn raw() -> Option<RawHandle> {
    let old = match get_attr() {
        Some(old) => old,
        None => {
            return None;
        }
    };
    if let None = set_attr(&make_raw()) {
        return None;
    }
    return Some(RawHandle { old: old });
}