use std::fs::File;
use std::io;
use std::os::fd::{AsRawFd as _, RawFd};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct WinSize {
pub rows: u16,
pub cols: u16,
pub pixel_width: u16,
pub pixel_height: u16,
}
#[derive(Debug)]
pub struct Master {
file: File,
}
impl Master {
#[must_use]
pub fn new(file: File) -> Self {
Self { file }
}
pub fn get_size(&self) -> io::Result<WinSize> {
let mut ws: libc::winsize = unsafe { std::mem::zeroed() };
let rc = unsafe { libc::ioctl(self.raw_fd(), libc::TIOCGWINSZ, &mut ws) };
if rc != 0 {
return Err(io::Error::last_os_error());
}
Ok(WinSize {
rows: ws.ws_row,
cols: ws.ws_col,
pixel_width: ws.ws_xpixel,
pixel_height: ws.ws_ypixel,
})
}
pub fn resize(&self, size: WinSize) -> io::Result<()> {
let ws = libc::winsize {
ws_row: size.rows,
ws_col: size.cols,
ws_xpixel: size.pixel_width,
ws_ypixel: size.pixel_height,
};
let rc = unsafe { libc::ioctl(self.raw_fd(), libc::TIOCSWINSZ, &ws) };
if rc != 0 {
return Err(io::Error::last_os_error());
}
Ok(())
}
#[must_use]
pub fn process_group_leader(&self) -> Option<i32> {
let mut pgrp: i32 = -1;
let rc = unsafe { libc::ioctl(self.raw_fd(), libc::TIOCGPGRP, &mut pgrp) };
(rc == 0 && pgrp > 0).then_some(pgrp)
}
#[must_use]
pub fn raw_fd(&self) -> RawFd {
self.file.as_raw_fd()
}
pub fn try_clone(&self) -> io::Result<File> {
self.file.try_clone()
}
}