tinsel 1.1.0

Clean terminal output with a little sparkle: live step lists, spinners, tables, trees, prompts and full-screen apps.
Documentation
use std::io;
use std::time::{Duration, Instant};

use super::{Event, Key, input};
use crate::term;

/// Keys read one at a time in the normal terminal, outside a full-screen [`run`](super::run):
/// for a loop that redraws now and then and reacts to a key in between.
///
/// While it's open, what's typed isn't shown and Ctrl-C arrives as `Key::Ctrl('c')` instead
/// of stopping the program. Dropping it puts the terminal back. While a
/// [`prompt::script`](crate::prompt::script) runs on this thread, keys come from the script
/// instead, and once it has none left nothing is pressed.
///
/// ```no_run
/// use std::time::Duration;
/// use tinsel::app::{Key, Keys};
///
/// let mut keys = Keys::open()?;
/// loop {
///     // show what changed
///     match keys.next(Duration::from_secs(4))? {
///         Some(Key::Char('q') | Key::Ctrl('c')) => break,
///         _ => {}
///     }
/// }
/// # Ok::<(), std::io::Error>(())
/// ```
pub struct Keys {
    decoder: input::Decoder,
    keyboard: term::Keyboard,
    raw: Option<term::RawMode>,
}

impl std::fmt::Debug for Keys {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Keys")
            .field("scripted", &self.raw.is_none())
            .finish_non_exhaustive()
    }
}

impl Keys {
    /// Start reading keys from the terminal on stdin. Fails without one.
    ///
    /// # Errors
    ///
    /// An I/O error when there's no terminal on stdin, or it can't be put into raw mode.
    pub fn open() -> io::Result<Keys> {
        let raw = if crate::prompt::scripted() {
            None
        } else {
            Some(term::RawMode::enter()?)
        };
        Ok(Keys {
            decoder: input::Decoder::new(),
            keyboard: term::Keyboard::default(),
            raw,
        })
    }

    /// The next key, waiting up to `timeout` (to within a tenth of a second) for one, or
    /// `None` if nothing was pressed. Mouse reports and anything else that isn't a key are
    /// skipped. Once the terminal has gone (its window closed), this is an error.
    ///
    /// # Errors
    ///
    /// An I/O error once the terminal has gone.
    pub fn next(&mut self, timeout: Duration) -> io::Result<Option<Key>> {
        if self.raw.is_none() {
            return Ok(crate::prompt::next_scripted());
        }
        let deadline = Instant::now() + timeout;
        loop {
            if let Some(key) = self.take(false) {
                return Ok(Some(key));
            }
            let mut buf = [0u8; 256];
            let n = self.keyboard.read(&mut buf)?;
            self.decoder.push(&buf[..n]);
            // a pause ends whatever was half read, such as a lone Esc
            if n == 0 {
                if let Some(key) = self.take(true) {
                    return Ok(Some(key));
                }
            }
            if Instant::now() >= deadline {
                return Ok(self.take(true));
            }
        }
    }

    fn take(&mut self, done: bool) -> Option<Key> {
        while let Some(event) = self.decoder.next(done) {
            if let Some(Event::Key(key)) = event {
                return Some(key);
            }
        }
        None
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn keys_come_from_a_script_and_then_stop() {
        let _script = crate::prompt::script([Key::Char('r'), Key::Ctrl('c')]);
        let mut keys = Keys::open().unwrap();
        let wait = Duration::from_secs(5);
        assert_eq!(keys.next(wait).unwrap(), Some(Key::Char('r')));
        assert_eq!(keys.next(wait).unwrap(), Some(Key::Ctrl('c')));
        assert_eq!(keys.next(wait).unwrap(), None);
    }

    #[test]
    fn half_read_bytes_become_keys() {
        let mut keys = Keys {
            decoder: input::Decoder::new(),
            keyboard: term::Keyboard::default(),
            raw: None,
        };
        keys.decoder.push(b"\x1b[Ax\x1b");
        assert_eq!(keys.take(false), Some(Key::Up));
        assert_eq!(keys.take(false), Some(Key::Char('x')));
        assert_eq!(keys.take(false), None);
        assert_eq!(keys.take(true), Some(Key::Esc));
    }
}