| 1 |
//! This shows how an application can write on stderr |
| 2 |
//! instead of stdout, thus making it possible to |
| 3 |
//! the command API instead of the "old style" direct |
| 4 |
//! unbuffered API. |
| 5 |
//! |
| 6 |
//! This particular example is only suited to Unix |
| 7 |
//! for now. |
| 8 |
//! |
| 9 |
//! cargo run --example stderr |
| 10 |
|
| 11 |
use std::io; |
| 12 |
|
| 13 |
use crossterm::{ |
| 14 |
cursor::{Hide, MoveTo, Show}, |
| 15 |
event, |
| 16 |
event::{Event, KeyCode, KeyEvent}, |
| 17 |
execute, queue, |
| 18 |
style::Print, |
| 19 |
terminal::{self, EnterAlternateScreen, LeaveAlternateScreen}, |
| 20 |
}; |
| 21 |
|
| 22 |
const TEXT: &str = r#" |
| 23 |
This screen is ran on stderr. |
| 24 |
And when you hit enter, it prints on stdout. |
| 25 |
This makes it possible to run an application and choose what will |
| 26 |
be sent to any application calling yours. |
| 27 |
|
| 28 |
For example, assuming you build this example with |
| 29 |
|
| 30 |
cargo build --bin stderr |
| 31 |
|
| 32 |
and then you run it with |
| 33 |
|
| 34 |
cd "$(target/debug/stderr)" |
| 35 |
|
| 36 |
what the application prints on stdout is used as argument to cd. |
| 37 |
|
| 38 |
Try it out. |
| 39 |
|
| 40 |
Hit any key to quit this screen: |
| 41 |
|
| 42 |
1 will print `..` |
| 43 |
2 will print `/` |
| 44 |
3 will print `~` |
| 45 |
Any other key will print this text (so that you may copy-paste) |
| 46 |
"#; |
| 47 |
|
| 48 |
fn run_app<W>(write: &mut W) -> io::Result<char> |
| 49 |
where |
| 50 |
W: io::Write, |
| 51 |
{ |
| 52 |
queue!( |
| 53 |
write, |
| 54 |
EnterAlternateScreen, // enter alternate screen |
| 55 |
Hide // hide the cursor |
| 56 |
)?; |
| 57 |
|
| 58 |
let mut y = 1; |
| 59 |
for line in TEXT.split('\n') { |
| 60 |
queue!(write, MoveTo(1, y), Print(line.to_string()))?; |
| 61 |
y += 1; |
| 62 |
} |
| 63 |
|
| 64 |
write.flush()?; |
| 65 |
|
| 66 |
terminal::enable_raw_mode()?; |
| 67 |
let user_char = read_char()?; // we wait for the user to hit a key |
| 68 |
execute!(write, Show, LeaveAlternateScreen)?; // restore the cursor and leave the alternate screen |
| 69 |
|
| 70 |
terminal::disable_raw_mode()?; |
| 71 |
|
| 72 |
Ok(user_char) |
| 73 |
} |
| 74 |
|
| 75 |
pub fn read_char() -> io::Result<char> { |
| 76 |
loop { |
| 77 |
if let Event::Key(KeyEvent { |
| 78 |
code: KeyCode::Char(c), |
| 79 |
.. |
| 80 |
}) = event::read()? |
| 81 |
{ |
| 82 |
return Ok(c); |
| 83 |
} |
| 84 |
} |
| 85 |
} |
| 86 |
|
| 87 |
// cargo run --example stderr |
| 88 |
fn main() { |
| 89 |
match run_app(&mut io::stderr()).unwrap() { |
| 90 |
'1' => print!(".."), |
| 91 |
'2' => print!("/"), |
| 92 |
'3' => print!("~"), |
| 93 |
_ => println!("{}", TEXT), |
| 94 |
} |
| 95 |
} |