Skip to main content

term_size/platform/
unix.rs

1
2use libc::{STDOUT_FILENO, STDIN_FILENO, STDERR_FILENO, c_int, c_ulong, winsize};
3use std::mem::zeroed;
4
5// Unfortunately the actual command is not standardised...
6#[cfg(any(target_os = "linux", target_os = "android"))]
7static TIOCGWINSZ: c_ulong = 0x5413;
8
9#[cfg(any(target_os = "macos",
10            target_os = "ios",
11            target_os = "bitrig",
12            target_os = "dragonfly",
13            target_os = "freebsd",
14            target_os = "netbsd",
15            target_os = "openbsd"))]
16static TIOCGWINSZ: c_ulong = 0x40087468;
17
18#[cfg(target_os = "solaris")]
19static TIOCGWINSZ: c_ulong = 0x5468;
20
21extern "C" {
22    fn ioctl(fd: c_int, request: c_ulong, ...) -> c_int;
23}
24
25/// Runs the ioctl command. Returns (0, 0) if all of the streams are not to a terminal, or
26/// there is an error. (0, 0) is an invalid size to have anyway, which is why
27/// it can be used as a nil value.
28unsafe fn get_dimensions_any() -> winsize {
29    let mut window: winsize = zeroed();
30    let mut result = ioctl(STDOUT_FILENO, TIOCGWINSZ, &mut window);
31
32    if result == -1 {
33        window = zeroed();
34        result = ioctl(STDIN_FILENO, TIOCGWINSZ, &mut window);
35        if result == -1 {
36            window = zeroed();
37            result = ioctl(STDERR_FILENO, TIOCGWINSZ, &mut window);
38            if result == -1 {
39                return zeroed();
40            }
41        }
42    }
43    window
44}
45
46/// Runs the ioctl command. Returns (0, 0) if the output is not to a terminal, or
47/// there is an error. (0, 0) is an invalid size to have anyway, which is why
48/// it can be used as a nil value.
49unsafe fn get_dimensions_out() -> winsize {
50    let mut window: winsize = zeroed();
51    let result = ioctl(STDOUT_FILENO, TIOCGWINSZ, &mut window);
52
53    if result != -1 {
54        return window;
55    }
56    zeroed()
57}
58
59/// Runs the ioctl command. Returns (0, 0) if the input is not to a terminal, or
60/// there is an error. (0, 0) is an invalid size to have anyway, which is why
61/// it can be used as a nil value.
62unsafe fn get_dimensions_in() -> winsize {
63    let mut window: winsize = zeroed();
64    let result = ioctl(STDIN_FILENO, TIOCGWINSZ, &mut window);
65
66    if result != -1 {
67        return window;
68    }
69    zeroed()
70}
71
72/// Runs the ioctl command. Returns (0, 0) if the error is not to a terminal, or
73/// there is an error. (0, 0) is an invalid size to have anyway, which is why
74/// it can be used as a nil value.
75unsafe fn get_dimensions_err() -> winsize {
76    let mut window: winsize = zeroed();
77    let result = ioctl(STDERR_FILENO, TIOCGWINSZ, &mut window);
78
79    if result != -1 {
80        return window;
81    }
82    zeroed()
83}
84
85/// Query the current processes's output (`stdout`), input (`stdin`), and error (`stderr`) in
86/// that order, in the attempt to determine terminal width. If one of those streams is actually
87/// a tty, this function returns its width and height as a number of characters.
88///
89/// # Errors
90/// 
91/// If *all* of the streams are not ttys or return any errors this function will return `None`.
92/// 
93/// # Example
94/// 
95/// To get the dimensions of your terminal window, simply use the following:
96/// 
97/// ```no_run
98/// # use term_size;
99/// if let Some((w, h)) = term_size::dimensions() {
100///     println!("Width: {}\nHeight: {}", w, h);
101/// } else {
102///     println!("Unable to get term size :(")
103/// }
104/// ```
105pub fn dimensions() -> Option<(usize, usize)> {
106    let w = unsafe { get_dimensions_any() };
107
108    if w.ws_col == 0 || w.ws_row == 0 {
109        None
110    } else {
111        Some((w.ws_col as usize, w.ws_row as usize))
112    }
113}
114
115/// Query the current processes's output (`stdout`) *only*, in the attempt to determine
116/// terminal width. If that stream is actually a tty, this function returns its width
117/// and height as a number of characters.
118///
119/// # Errors
120/// 
121/// If the stream is not a tty or return any errors this function will return `None`.
122/// 
123/// # Example
124/// 
125/// To get the dimensions of your terminal window, simply use the following:
126/// 
127/// ```no_run
128/// # use term_size;
129/// if let Some((w, h)) = term_size::dimensions_stdout() {
130///     println!("Width: {}\nHeight: {}", w, h);
131/// } else {
132///     println!("Unable to get term size :(")
133/// }
134/// ```
135pub fn dimensions_stdout() -> Option<(usize, usize)> {
136    let w = unsafe { get_dimensions_out() };
137
138    if w.ws_col == 0 || w.ws_row == 0 {
139        None
140    } else {
141        Some((w.ws_col as usize, w.ws_row as usize))
142    }
143}
144
145/// Query the current processes's input (`stdin`) *only*, in the attempt to determine
146/// terminal width. If that stream is actually a tty, this function returns its width
147/// and height as a number of characters.
148///
149/// # Errors
150/// 
151/// If the stream is not a tty or return any errors this function will return `None`.
152/// 
153/// # Example
154/// 
155/// To get the dimensions of your terminal window, simply use the following:
156/// 
157/// ```no_run
158/// # use term_size;
159/// if let Some((w, h)) = term_size::dimensions_stdin() {
160///     println!("Width: {}\nHeight: {}", w, h);
161/// } else {
162///     println!("Unable to get term size :(")
163/// }
164/// ```
165pub fn dimensions_stdin() -> Option<(usize, usize)> {
166    let w = unsafe { get_dimensions_in() };
167
168    if w.ws_col == 0 || w.ws_row == 0 {
169        None
170    } else {
171        Some((w.ws_col as usize, w.ws_row as usize))
172    }
173}
174
175/// Query the current processes's error output (`stderr`) *only*, in the attempt to determine
176/// terminal width. If that stream is actually a tty, this function returns its width
177/// and height as a number of characters.
178///
179/// # Errors
180/// 
181/// If the stream is not a tty or return any errors this function will return `None`.
182/// 
183/// # Example
184/// 
185/// To get the dimensions of your terminal window, simply use the following:
186/// 
187/// ```no_run
188/// # use term_size;
189/// if let Some((w, h)) = term_size::dimensions_stderr() {
190///     println!("Width: {}\nHeight: {}", w, h);
191/// } else {
192///     println!("Unable to get term size :(")
193/// }
194/// ```
195pub fn dimensions_stderr() -> Option<(usize, usize)> {
196    let w = unsafe { get_dimensions_err() };
197
198    if w.ws_col == 0 || w.ws_row == 0 {
199        None
200    } else {
201        Some((w.ws_col as usize, w.ws_row as usize))
202    }
203}