Added the ability to pause the terminal (#47)

This commit is contained in:
Timon 2018-11-21 22:57:39 +01:00 committed by GitHub
parent f068ae69b1
commit b82736912d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 61 additions and 3 deletions

View File

@ -109,7 +109,7 @@ pub fn print_all_foreground_colors() {
);
#[cfg(unix)]
println!("{}", style("RGB color (10,10,10) ")).with(Color::AnsiValue(50));
println!("{}", style("RGB color (10,10,10) ").with(Color::AnsiValue(50)));
}
/// Print all available foreground colors | demonstration.

View File

@ -14,4 +14,9 @@ mod input;
mod some_types;
mod terminal;
fn main() {}
use crossterm::input::{TerminalInput, KeyEvent};
fn main() {
println!("Press 'x' to quit...");
TerminalInput::wait_until(KeyEvent::OnKeyPress(b'x'));
}

View File

@ -1,6 +1,6 @@
extern crate crossterm;
use self::crossterm::input::input;
use self::crossterm::input::{input, TerminalInput, KeyEvent};
use self::crossterm::Screen;
pub fn read_char() {
@ -20,3 +20,8 @@ pub fn read_line() {
Err(e) => println!("error: {}", e),
}
}
pub fn pause_terminal() {
println!("Press 'x' to quit...");
TerminalInput::wait_until(KeyEvent::OnKeyPress(b'x'));
}

View File

@ -3,6 +3,7 @@
use super::*;
use Screen;
use std::{thread, time::Duration};
/// Struct that stores an specific platform implementation for input related actions.
///
@ -158,6 +159,43 @@ impl<'stdout> TerminalInput<'stdout> {
self.terminal_input
.read_until_async(delimiter, &self.stdout)
}
/// This will prevent the current thread from continuing until the passed `KeyEvent` has happened.
///
/// ```
/// use crossterm::input::{TerminalInput, KeyEvent};
///
/// fn main() {
/// println!("Press 'x' to quit...");
/// TerminalInput::wait_until(KeyEvent::OnKeyPress(b'x'));
/// }
/// ```
pub fn wait_until(key_event: KeyEvent) {
let screen = Screen::new(true);
let input = from_screen(&screen);
let mut stdin = input.read_async().bytes();
loop {
let pressed_key: Option<Result<u8, Error>> = stdin.next();
match pressed_key {
Some(Ok(value)) => {
match key_event {
KeyEvent::OnKeyPress(ascii_code) => if value == ascii_code { break; },
KeyEvent::OnEnter => if value == b'\r' { break; },
KeyEvent::OnAnyKeyPress => {
break;
}
}
}
_ => {}
}
// some sleeping time so that we don't 'dos' our cpu.
thread::sleep(Duration::from_millis(10));
}
}
}
/// Get an Terminal Input implementation whereon input related actions can be performed.

View File

@ -47,6 +47,16 @@ pub struct AsyncReader {
recv: mpsc::Receiver<io::Result<u8>>,
}
// This enum represents a key event that from the user.
pub enum KeyEvent {
/// Represents a specific key press.
OnKeyPress(u8),
/// Represents a key press from any key.
OnAnyKeyPress,
/// Represents a key press from enter.
OnEnter,
}
impl Read for AsyncReader {
/// Read from the byte stream.
///