use std::io::Write;
pub struct RealScreen {
hidden: bool,
}
impl RealScreen {
pub fn new() -> RealScreen {
RealScreen { hidden: false }
}
fn escape(&mut self, sequence: &str) -> Result<(), String> {
if !platform::stdout_is_terminal() {
return Ok(());
}
let mut out = std::io::stdout();
out.write_all(sequence.as_bytes())
.and_then(|()| out.flush())
.map_err(|err| format!("cannot write to the terminal: {err}"))
}
}
impl Default for RealScreen {
fn default() -> RealScreen {
RealScreen::new()
}
}
impl miruscriptx::value::Screen for RealScreen {
fn clear(&mut self) -> Result<(), String> {
self.escape("\x1b[2J\x1b[H")
}
fn move_to(&mut self, column: i64, row: i64) -> Result<(), String> {
if column < 0 || row < 0 {
return Err(format!(
"move_to expects a column and row that are not negative but got {column} and {row}"
));
}
self.escape(&format!("\x1b[{};{}H", row + 1, column + 1))
}
fn hide_cursor(&mut self) -> Result<(), String> {
self.escape("\x1b[?25l")?;
self.hidden = true;
Ok(())
}
fn show_cursor(&mut self) -> Result<(), String> {
self.escape("\x1b[?25h")?;
self.hidden = false;
Ok(())
}
fn size(&mut self) -> Result<(i64, i64), String> {
platform::terminal_size()
}
}
impl Drop for RealScreen {
fn drop(&mut self) {
if self.hidden {
let mut out = std::io::stdout();
let _ = out.write_all(b"\x1b[?25h");
let _ = out.flush();
}
}
}
#[cfg(unix)]
mod platform {
pub fn stdout_is_terminal() -> bool {
use std::os::fd::AsFd;
nix::unistd::isatty(std::io::stdout().as_fd()).unwrap_or(false)
}
pub fn terminal_size() -> Result<(i64, i64), String> {
use std::os::fd::AsRawFd;
if !stdout_is_terminal() {
return Err("this program's output is not a terminal, so it has no size".to_string());
}
#[repr(C)]
struct WinSize {
rows: libc_ushort,
columns: libc_ushort,
x_pixels: libc_ushort,
y_pixels: libc_ushort,
}
#[allow(non_camel_case_types)]
type libc_ushort = std::ffi::c_ushort;
#[cfg(any(target_os = "linux", target_os = "android"))]
const TIOCGWINSZ: std::ffi::c_ulong = 0x5413;
#[cfg(not(any(target_os = "linux", target_os = "android")))]
const TIOCGWINSZ: std::ffi::c_ulong = 0x4008_7468;
unsafe extern "C" {
fn ioctl(fd: std::ffi::c_int, request: std::ffi::c_ulong, ...) -> std::ffi::c_int;
}
let mut size = WinSize {
rows: 0,
columns: 0,
x_pixels: 0,
y_pixels: 0,
};
let result = unsafe { ioctl(std::io::stdout().as_raw_fd(), TIOCGWINSZ, &mut size) };
if result != 0 {
return Err("cannot read the terminal's size".to_string());
}
if size.columns == 0 || size.rows == 0 {
return Err("the terminal did not report a size".to_string());
}
Ok((i64::from(size.columns), i64::from(size.rows)))
}
}
#[cfg(windows)]
mod platform {
use windows_sys::Win32::Foundation::{HANDLE, INVALID_HANDLE_VALUE};
use windows_sys::Win32::System::Console::{
GetConsoleMode, GetConsoleScreenBufferInfo, GetStdHandle, CONSOLE_SCREEN_BUFFER_INFO,
STD_OUTPUT_HANDLE,
};
fn stdout_handle() -> Option<HANDLE> {
let handle = unsafe { GetStdHandle(STD_OUTPUT_HANDLE) };
if handle == INVALID_HANDLE_VALUE || handle.is_null() {
return None;
}
Some(handle)
}
pub fn stdout_is_terminal() -> bool {
let Some(handle) = stdout_handle() else {
return false;
};
let mut mode = 0u32;
unsafe { GetConsoleMode(handle, &mut mode) != 0 }
}
pub fn terminal_size() -> Result<(i64, i64), String> {
if !stdout_is_terminal() {
return Err("this program's output is not a terminal, so it has no size".to_string());
}
let handle = stdout_handle().ok_or("cannot reach the console")?;
let mut info: CONSOLE_SCREEN_BUFFER_INFO = unsafe { std::mem::zeroed() };
if unsafe { GetConsoleScreenBufferInfo(handle, &mut info) } == 0 {
return Err("cannot read the console's size".to_string());
}
let columns = i64::from(info.srWindow.Right - info.srWindow.Left + 1);
let rows = i64::from(info.srWindow.Bottom - info.srWindow.Top + 1);
if columns <= 0 || rows <= 0 {
return Err("the console did not report a size".to_string());
}
Ok((columns, rows))
}
}