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
extern crate libc;
use std::os::raw::*;
use super::{Width, Height};
const TIOCGWINSZ: c_int = 0x00005413;
#[derive(Debug)]
struct WinSize {
ws_row: c_ushort,
ws_col: c_ushort,
ws_xpixel: c_ushort,
ws_ypixel: c_ushort
}
pub fn terminal_size() -> Option<(Width, Height)> {
use self::libc::{isatty, STDOUT_FILENO};
use self::libc::funcs::bsd44::ioctl;
let is_tty: bool = unsafe{isatty(STDOUT_FILENO) == 1};
if !is_tty { return None; }
let (rows, cols) = unsafe {
let mut winsize = WinSize{ws_row: 0, ws_col: 0, ws_xpixel: 0, ws_ypixel: 0};
ioctl(STDOUT_FILENO, TIOCGWINSZ, &mut winsize);
let rows = if winsize.ws_row > 0 { winsize.ws_row } else { 0 };
let cols = if winsize.ws_col > 0 { winsize.ws_col } else { 0 };
(rows as u16, cols as u16)
};
if rows > 0 && cols > 0 {
Some((Width(cols), Height(rows)))
} else {
None
}
}
#[test]
fn compare_with_stty() {
use std::process::Command;
use std::process::Stdio;
let output = Command::new("stty").arg("size").arg("-F").arg("/dev/stderr").stderr(Stdio::inherit()).output().unwrap();
let stdout = String::from_utf8(output.stdout).unwrap();
assert!(output.status.success());
let mut data = stdout.split_whitespace();
let rows = u16::from_str_radix(data.next().unwrap(), 10).unwrap();
let cols = u16::from_str_radix(data.next().unwrap(), 10).unwrap();
println!("{}", stdout);
println!("{} {}", rows, cols);
if let Some((Width(w), Height(h))) = terminal_size() {
assert_eq!(rows, h);
assert_eq!(cols, w);
}
}