Refactoring Unix routines for terminal info (#154)

This commit is contained in:
svartalf 2019-06-21 19:11:50 +03:00 committed by Timon
parent e1b8da03ba
commit 0f1e275216

View File

@ -1,36 +1,25 @@
use libc::{c_ushort, ioctl, STDOUT_FILENO, TIOCGWINSZ};
use libc::{ioctl, winsize, STDOUT_FILENO, TIOCGWINSZ};
pub fn exit() {
::std::process::exit(0);
}
/// A representation of the size of the current terminal.
#[repr(C)]
#[derive(Debug)]
pub struct UnixSize {
/// number of rows
pub rows: c_ushort,
/// number of columns
pub cols: c_ushort,
pub ws_xpixel: c_ushort,
pub ws_ypixel: c_ushort,
}
/// Get the current terminal size.
pub fn get_terminal_size() -> (u16, u16) {
// http://rosettacode.org/wiki/Terminal_control/Dimensions#Library:_BSD_libc
let us = UnixSize {
rows: 0,
cols: 0,
let mut size = winsize {
ws_row: 0,
ws_col: 0,
ws_xpixel: 0,
ws_ypixel: 0,
};
let r = unsafe { ioctl(STDOUT_FILENO, TIOCGWINSZ.into(), &us) };
let r = unsafe { ioctl(STDOUT_FILENO, TIOCGWINSZ.into(), &mut size) };
if r == 0 {
// because crossterm works starts counting at 0 and unix terminal starts at cell 1 you have subtract one to get 0-based results.
(us.cols - 1, us.rows - 1)
// because crossterm works starts counting at 0
// and unix terminal starts at cell 1
// you have subtract one to get 0-based results.
(size.ws_col - 1, size.ws_row - 1)
} else {
(0, 0)
}