Skip to main content

termion/sys/unix/
size.rs

1use std::{io, mem};
2
3use super::cvt;
4use super::libc::{c_ushort, ioctl, STDOUT_FILENO, TIOCGWINSZ};
5
6#[repr(C)]
7struct TermSize {
8    row: c_ushort,
9    col: c_ushort,
10    x: c_ushort,
11    y: c_ushort,
12}
13/// Get the size (columns, rows) of the terminal.
14pub fn terminal_size() -> io::Result<(u16, u16)> {
15    unsafe {
16        let mut size: TermSize = mem::zeroed();
17        cvt(ioctl(STDOUT_FILENO, TIOCGWINSZ.into(), &mut size as *mut _))?;
18        Ok((size.col as u16, size.row as u16))
19    }
20}
21
22/// Get the size (columns, rows) of the terminal from descriptor object.
23pub fn terminal_size_fd(fd: &impl std::os::fd::AsRawFd) -> io::Result<(u16, u16)> {
24    unsafe {
25        let mut size: TermSize = mem::zeroed();
26        cvt(ioctl(fd.as_raw_fd(), TIOCGWINSZ, &mut size as *mut _))?;
27        Ok((size.col as u16, size.row as u16))
28    }
29}
30
31/// Get the size of the terminal in pixels.
32pub fn terminal_size_pixels() -> io::Result<(u16, u16)> {
33    unsafe {
34        let mut size: TermSize = mem::zeroed();
35        cvt(ioctl(STDOUT_FILENO, TIOCGWINSZ.into(), &mut size as *mut _))?;
36        Ok((size.x as u16, size.y as u16))
37    }
38}
39
40/// Get the size of the terminal in pixels from descriptor object.
41pub fn terminal_size_pixels_fd(fd: &impl std::os::fd::AsRawFd) -> io::Result<(u16, u16)> {
42    unsafe {
43        let mut size: TermSize = mem::zeroed();
44        cvt(ioctl(fd.as_raw_fd(), TIOCGWINSZ, &mut size as *mut _))?;
45        Ok((size.x as u16, size.y as u16))
46    }
47}