Advertisement
NLinker

Async stdin with Termion

Jul 10th, 2019
636
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.56 KB | None | 0 0
  1. use termion::event::Key;
  2. use termion::input::TermRead;
  3. use termion::raw::IntoRawMode;
  4. use termion::async_stdin;
  5. use std::io::{Read, Write, stdout, stdin};
  6. use std::thread;
  7. use std::time::Duration;
  8.  
  9.  
  10. fn main() {
  11.     let mut stdout = stdout().into_raw_mode().unwrap();
  12.     let mut stdin = async_stdin().keys();
  13.  
  14.     write!(stdout,
  15.            "{}{}q to exit. Type stuff, use alt, and so on.{}",
  16.            termion::clear::All,
  17.            termion::cursor::Goto(1, 1),
  18.            termion::cursor::Hide)
  19.         .unwrap();
  20.     stdout.flush().unwrap();
  21.  
  22.     loop {
  23.         if let Some(c) = stdin.next() {
  24.             write!(stdout,
  25.                    "{}{}",
  26.                    termion::cursor::Goto(1, 1),
  27.                    termion::clear::CurrentLine)
  28.                 .unwrap();
  29.             match c.unwrap() {
  30.                 Key::Char('q') => break,
  31.                 Key::Char(c) => print!("'{}' ", c),
  32.                 Key::Alt(c) => print!("^{} ", c),
  33.                 Key::Ctrl(c) => print!("*{} ", c),
  34.                 Key::Esc => print!("ESC "),
  35.                 Key::Left => print!("← "),
  36.                 Key::Right => print!("→ "),
  37.                 Key::Up => print!("↑ "),
  38.                 Key::Down => print!("↓ "),
  39.                 Key::Backspace => print!("× "),
  40.                 _ => {}
  41.             }
  42.             stdout.flush().unwrap();
  43.         }
  44.         write!(stdout, ".").unwrap();
  45.         stdout.flush().unwrap();
  46.         thread::sleep(Duration::from_millis(50));
  47.     }
  48.  
  49.     write!(stdout, "{}", termion::cursor::Show).unwrap();
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement