use crate::key::Key;
use crate::msg::Size;
use std::io::{self, Write};
use std::sync::{Arc, Mutex, PoisonError};
use std::time::Duration;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Input {
Key(Key),
Resize(Size),
Interrupt,
Terminate,
}
pub type InputSink = Box<dyn Fn(Input) -> bool + Send + 'static>;
pub trait Backend {
fn enter(&mut self) -> io::Result<()>;
fn leave(&mut self) -> io::Result<()>;
fn size(&mut self) -> io::Result<Size>;
fn start_input(&mut self, sink: InputSink);
fn output(&mut self) -> &mut dyn Write;
}
#[derive(Debug, Clone)]
pub struct TestBackend {
size: Size,
inputs: Vec<Input>,
gap: Duration,
screen: Screen,
}
#[derive(Debug, Clone, Default)]
pub struct Screen(Arc<Mutex<Vec<u8>>>);
impl Screen {
#[must_use]
pub fn raw(&self) -> String {
String::from_utf8_lossy(&self.0.lock().unwrap_or_else(PoisonError::into_inner)).into_owned()
}
#[must_use]
pub fn text(&self) -> String {
crate::style::strip_ansi(&self.raw())
}
}
impl Write for Screen {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.0
.lock()
.unwrap_or_else(PoisonError::into_inner)
.extend_from_slice(buf);
Ok(buf.len())
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
impl TestBackend {
#[must_use]
pub fn new(columns: u16, rows: u16) -> Self {
Self {
size: Size::new(columns, rows),
inputs: Vec::new(),
gap: Duration::from_millis(5),
screen: Screen::default(),
}
}
#[must_use]
pub fn keys(self, keys: impl IntoIterator<Item = Key>) -> Self {
self.inputs(keys.into_iter().map(Input::Key))
}
#[must_use]
pub fn inputs(mut self, inputs: impl IntoIterator<Item = Input>) -> Self {
self.inputs = inputs.into_iter().collect();
self
}
#[must_use]
pub const fn gap(mut self, gap: Duration) -> Self {
self.gap = gap;
self
}
#[must_use]
pub fn screen(&self) -> Screen {
self.screen.clone()
}
}
impl Backend for TestBackend {
fn enter(&mut self) -> io::Result<()> {
Ok(())
}
fn leave(&mut self) -> io::Result<()> {
Ok(())
}
fn size(&mut self) -> io::Result<Size> {
Ok(self.size)
}
fn start_input(&mut self, sink: InputSink) {
let (inputs, gap) = (self.inputs.clone(), self.gap);
drop(std::thread::spawn(move || {
for input in inputs {
std::thread::sleep(gap);
if !sink(input) {
break;
}
}
}));
}
fn output(&mut self) -> &mut dyn Write {
&mut self.screen
}
}