pub use crossterm::terminal::ClearType as ClrT;
use crossterm::{
cursor, execute, queue,
style::Print,
terminal::{
disable_raw_mode, enable_raw_mode, size, Clear, EnterAlternateScreen, LeaveAlternateScreen,
SetSize,
},
};
use std::{
fmt::Display,
io::{stdout, Stdout, Write},
};
use thiserror::Error;
pub mod stylize;
#[derive(Debug)]
pub struct Yogurt {
stdout: Stdout,
size: Option<Point>,
}
impl Default for Yogurt {
fn default() -> Self {
Yogurt::new()
}
}
impl Yogurt {
pub fn print(&mut self, displ: impl Display) -> Result<()> {
queue! {
self.stdout,
Print(displ),
}?;
Ok(())
}
pub fn mv(&mut self, point: impl Into<Point>) -> Result<()> {
let point = Into::<Point>::into(point);
queue! {
self.stdout,
cursor::MoveTo(point.x, point.y),
}?;
Ok(())
}
pub fn mv_print(&mut self, point: impl Into<Point>, displ: impl Display) -> Result<()> {
self.mv(point)?;
self.print(displ)?;
Ok(())
}
pub fn flush(&mut self) -> Result<()> {
self.stdout.flush()?;
Ok(())
}
pub fn new() -> Self {
Yogurt {
stdout: stdout(),
size: None,
}
}
pub fn enter_alt(&mut self) -> Result<()> {
self.size = Some(Point::from(size()?));
execute! {
self.stdout,
EnterAlternateScreen
}?;
enable_raw_mode()?;
Ok(())
}
pub fn leave_alt(&mut self) -> Result<()> {
if let Some(size) = self.size.take() {
execute! {
self.stdout,
LeaveAlternateScreen,
SetSize(size.x, size.y),
}?;
disable_raw_mode()?;
Ok(())
} else {
Err(Yarr::NotInAltMode)
}
}
pub fn clear(&mut self, cleartype: ClrT) -> Result<()> {
queue! {
self.stdout,
Clear(cleartype),
}?;
Ok(())
}
}
#[derive(Debug)]
pub struct Point {
pub x: u16,
pub y: u16,
}
impl From<(u16, u16)> for Point {
fn from(t: (u16, u16)) -> Self {
Point { x: t.0, y: t.1 }
}
}
impl From<Point> for (u16, u16) {
fn from(point: Point) -> Self {
(point.x, point.y)
}
}
#[non_exhaustive]
#[derive(Error, Debug)]
pub enum Yarr {
#[error(transparent)]
IO(#[from] std::io::Error),
#[error("tried to leave alternate mode, but wasn't in it already")]
NotInAltMode,
}
pub type Result<T> = core::result::Result<T, Yarr>;