use std::io;
use std::mem;
use winapi::um::consoleapi::{GetConsoleMode, SetConsoleMode};
use winapi::um::wincon::{
CONSOLE_SCREEN_BUFFER_INFO,
GetConsoleScreenBufferInfo, SetConsoleTextAttribute,
};
use AsHandleRef;
pub fn screen_buffer_info<H: AsHandleRef>(
h: H,
) -> io::Result<ScreenBufferInfo> {
unsafe {
let mut info: CONSOLE_SCREEN_BUFFER_INFO = mem::zeroed();
let rc = GetConsoleScreenBufferInfo(h.as_raw(), &mut info);
if rc == 0 {
return Err(io::Error::last_os_error());
}
Ok(ScreenBufferInfo(info))
}
}
pub fn set_text_attributes<H: AsHandleRef>(
h: H,
attributes: u16,
) -> io::Result<()> {
if unsafe { SetConsoleTextAttribute(h.as_raw(), attributes) } == 0 {
Err(io::Error::last_os_error())
} else {
Ok(())
}
}
pub fn mode<H: AsHandleRef>(h: H) -> io::Result<u32> {
let mut mode = 0;
if unsafe { GetConsoleMode(h.as_raw(), &mut mode) } == 0 {
Err(io::Error::last_os_error())
} else {
Ok(mode)
}
}
pub fn set_mode<H: AsHandleRef>(h: H, mode: u32) -> io::Result<()> {
if unsafe { SetConsoleMode(h.as_raw(), mode) } == 0 {
Err(io::Error::last_os_error())
} else {
Ok(())
}
}
#[derive(Clone)]
pub struct ScreenBufferInfo(CONSOLE_SCREEN_BUFFER_INFO);
impl ScreenBufferInfo {
pub fn size(&self) -> (i16, i16) {
(self.0.dwSize.X, self.0.dwSize.Y)
}
pub fn cursor_position(&self) -> (i16, i16) {
(self.0.dwCursorPosition.X, self.0.dwCursorPosition.Y)
}
pub fn attributes(&self) -> u16 {
self.0.wAttributes
}
pub fn max_window_size(&self) -> (i16, i16) {
(self.0.dwMaximumWindowSize.X, self.0.dwMaximumWindowSize.Y)
}
}