minicrossterm/examples/command_bar.rs

95 lines
2.4 KiB
Rust
Raw Normal View History

2019-09-16 21:34:08 +10:00
use std::sync::{Arc, Mutex};
use std::{thread, time};
2018-08-22 02:05:53 +10:00
2019-04-05 03:46:43 +11:00
use crossterm::{
2019-09-19 03:31:12 +10:00
cursor, input, terminal, ClearType, Crossterm, InputEvent, KeyEvent, RawScreen, Result,
Terminal, TerminalCursor,
2019-04-05 03:46:43 +11:00
};
2019-09-19 03:31:12 +10:00
fn log(input_buf: Arc<Mutex<String>>) -> Vec<thread::JoinHandle<()>> {
let mut threads = Vec::with_capacity(10);
let (_, term_height) = terminal().terminal_size();
for i in 0..1 {
let input_buffer = input_buf.clone();
let crossterm = Crossterm::new();
let join = thread::spawn(move || {
let cursor = crossterm.cursor();
let terminal = crossterm.terminal();
for j in 0..1000 {
if let Err(_) = swap_write(
format!("Some output: {} from thread: {}", j, i).as_ref(),
&input_buffer.lock().unwrap(),
&terminal,
&cursor,
term_height,
) {
return;
}
thread::sleep(time::Duration::from_millis(100));
}
});
threads.push(join);
}
threads
}
fn swap_write(
msg: &str,
input_buf: &String,
terminal: &Terminal,
cursor: &TerminalCursor,
term_height: u16,
) -> Result<()> {
cursor.goto(0, term_height)?;
terminal.clear(ClearType::CurrentLine)?;
terminal.write(format!("{}\r\n", msg))?;
terminal.write(format!("> {}", input_buf)).map(|_| ())
}
2019-09-17 18:50:39 +10:00
// cargo run --example command_bar
2019-09-19 03:31:12 +10:00
fn main() -> Result<()> {
let _screen = RawScreen::into_raw_mode();
2019-09-19 03:31:12 +10:00
cursor().hide()?;
2018-08-22 02:05:53 +10:00
let input_buf = Arc::new(Mutex::new(String::new()));
2018-08-22 02:05:53 +10:00
let threads = log(input_buf.clone());
2018-08-22 02:05:53 +10:00
2018-08-24 06:16:31 +10:00
let mut count = 0;
2018-08-24 02:15:18 +10:00
thread::spawn(move || {
let input = input();
let mut stdin = input.read_async();
2018-08-22 02:05:53 +10:00
loop {
match stdin.next() {
2019-04-05 03:46:43 +11:00
Some(InputEvent::Keyboard(KeyEvent::Char('\n'))) => {
input_buf.lock().unwrap().clear();
}
2019-04-05 03:46:43 +11:00
Some(InputEvent::Keyboard(KeyEvent::Char(character))) => {
input_buf.lock().unwrap().push(character as char);
}
_ => {}
2018-08-22 02:05:53 +10:00
}
thread::sleep(time::Duration::from_millis(10));
count += 1;
}
})
.join()
.expect("Couldn't join");
2018-08-22 02:05:53 +10:00
for thread in threads {
thread.join().expect("Couldn't join");
2018-08-22 02:05:53 +10:00
}
2019-09-19 03:31:12 +10:00
cursor().show()
}