keyfork/keyfork-prompt/src/alternate_screen.rs

89 lines
1.9 KiB
Rust
Raw Normal View History

use std::{
io::Write,
os::fd::AsRawFd,
sync::{Arc, Mutex},
};
use crossterm::{
cursor::MoveTo,
terminal::{EnterAlternateScreen, LeaveAlternateScreen},
ExecutableCommand,
};
use crate::Result;
pub(crate) struct AlternateScreen<W>
where
W: Write + AsRawFd + Sized,
{
write: Arc<Mutex<W>>,
}
impl<W> AlternateScreen<W>
where
W: Write + AsRawFd + Sized,
{
pub(crate) fn new(write_handle: Arc<Mutex<W>>) -> Result<Self> {
let mut write = write_handle.lock().unwrap();
write.execute(EnterAlternateScreen)?.execute(MoveTo(0, 0))?;
drop(write);
Ok(Self {
write: write_handle,
})
}
pub(crate) fn arc_mutex(self) -> Arc<Mutex<Self>> {
Arc::new(Mutex::new(self))
}
}
impl<W> Write for AlternateScreen<W>
where
W: Write + AsRawFd + Sized,
{
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
self.write.lock().unwrap().write(buf)
}
fn flush(&mut self) -> std::io::Result<()> {
self.write.lock().unwrap().flush()
}
}
impl<W> AsRawFd for AlternateScreen<W>
where
W: Write + AsRawFd + Sized,
{
fn as_raw_fd(&self) -> std::os::fd::RawFd {
self.write.lock().unwrap().as_raw_fd()
}
}
/*
impl<W> ExecutableCommand for AlternateScreen<W>
where
W: Write + AsRawFd + Sized,
{
fn execute(&mut self, command: impl crossterm::Command) -> std::io::Result<&mut Self> {
let mut write = self.write.lock().unwrap();
match write.execute(command) {
Ok(_) => {
drop(write);
Ok(self)
}
Err(e) => Err(e),
}
}
}
*/
impl<W> Drop for AlternateScreen<W>
where
W: Write + AsRawFd + Sized,
{
fn drop(&mut self) {
let mut write_handle = self.write.lock().unwrap();
write_handle.execute(LeaveAlternateScreen).unwrap();
}
}