use tokio::io::AsyncWriteExt as _;
use crate::private::Output as _;
pub struct ScreenGuard {
cleaned_up: bool,
}
impl ScreenGuard {
pub async fn new() -> crate::error::Result<Self> {
write_stdout(&mut tokio::io::stdout(), crate::INIT).await?;
Ok(Self { cleaned_up: false })
}
pub async fn cleanup(&mut self) -> crate::error::Result<()> {
if self.cleaned_up {
return Ok(());
}
self.cleaned_up = true;
write_stdout(&mut tokio::io::stdout(), crate::DEINIT).await
}
}
impl Drop for ScreenGuard {
fn drop(&mut self) {
use std::io::Write as _;
if !self.cleaned_up {
let mut stdout = std::io::stdout();
let _ = stdout.write_all(crate::DEINIT);
let _ = stdout.flush();
}
}
}
pub struct Output {
stdout: tokio::io::Stdout,
screen: Option<ScreenGuard>,
cur: vt100::Parser,
next: vt100::Parser,
}
impl crate::private::Output for Output {
fn cur(&self) -> &vt100::Parser {
&self.cur
}
fn cur_mut(&mut self) -> &mut vt100::Parser {
&mut self.cur
}
fn next(&self) -> &vt100::Parser {
&self.next
}
fn next_mut(&mut self) -> &mut vt100::Parser {
&mut self.next
}
}
impl crate::Textmode for Output {}
impl Output {
pub async fn new() -> crate::error::Result<Self> {
let mut self_ = Self::new_without_screen();
self_.screen = Some(ScreenGuard::new().await?);
Ok(self_)
}
#[must_use]
pub fn new_without_screen() -> Self {
let (rows, cols) = match terminal_size::terminal_size() {
Some((terminal_size::Width(w), terminal_size::Height(h))) => {
(h, w)
}
_ => (24, 80),
};
let cur = vt100::Parser::new(rows, cols, 0);
let next = vt100::Parser::new(rows, cols, 0);
Self {
stdout: tokio::io::stdout(),
screen: None,
cur,
next,
}
}
pub fn take_screen_guard(&mut self) -> Option<ScreenGuard> {
self.screen.take()
}
pub async fn refresh(&mut self) -> crate::error::Result<()> {
let diff = self.next().screen().state_diff(self.cur().screen());
write_stdout(&mut self.stdout, &diff).await?;
self.cur_mut().process(&diff);
Ok(())
}
pub async fn hard_refresh(&mut self) -> crate::error::Result<()> {
let contents = self.next().screen().state_formatted();
write_stdout(&mut self.stdout, &contents).await?;
self.cur_mut().process(&contents);
Ok(())
}
}
async fn write_stdout(
stdout: &mut tokio::io::Stdout,
buf: &[u8],
) -> crate::error::Result<()> {
stdout
.write_all(buf)
.await
.map_err(crate::error::Error::WriteStdout)?;
stdout
.flush()
.await
.map_err(crate::error::Error::WriteStdout)?;
Ok(())
}