NLinker icon

Async stdin with Termion

NLinker | PRO | 07/10/19 09:20:23 PM UTC | 0 ⭐ | 1177 👁️ | Never ⏰ | []
Rust |

1.56 KB

|

None

|

0 👍

/

0 👎

use termion::event::Key;
use termion::input::TermRead;
use termion::raw::IntoRawMode;
use termion::async_stdin;
use std::io::{Read, Write, stdout, stdin};
use std::thread;
use std::time::Duration;
 
 
fn main() {
    let mut stdout = stdout().into_raw_mode().unwrap();
    let mut stdin = async_stdin().keys();
 
    write!(stdout,
           "{}{}q to exit. Type stuff, use alt, and so on.{}",
           termion::clear::All,
           termion::cursor::Goto(1, 1),
           termion::cursor::Hide)
        .unwrap();
    stdout.flush().unwrap();
 
    loop {
        if let Some(c) = stdin.next() {
            write!(stdout,
                   "{}{}",
                   termion::cursor::Goto(1, 1),
                   termion::clear::CurrentLine)
                .unwrap();
            match c.unwrap() {
                Key::Char('q') => break,
                Key::Char(c) => print!("'{}' ", c),
                Key::Alt(c) => print!("^{} ", c),
                Key::Ctrl(c) => print!("*{} ", c),
                Key::Esc => print!("ESC "),
                Key::Left => print!("← "),
                Key::Right => print!("→ "),
                Key::Up => print!("↑ "),
                Key::Down => print!("↓ "),
                Key::Backspace => print!("× "),
                _ => {}
            }
            stdout.flush().unwrap();
        }
        write!(stdout, ".").unwrap();
        stdout.flush().unwrap();
        thread::sleep(Duration::from_millis(50));
    }
 
    write!(stdout, "{}", termion::cursor::Show).unwrap();
}

Comments