mirror of
https://github.com/crossterm-rs/crossterm.git
synced 2025-05-05 15:32:57 +00:00
* Add is_ and as_ methods to the event enums Often application code only cares about a small subset of possible events. These methods make it simpler to write code which checks whether an event is a particular event type or converts events into the specific type (returning an Option). This can help simplify some nested match blocks. E.g.: ```rust match event { Event::Key(key) if key.kind == KeyEventKind::Press => { ... } } ``` becomes: ```rust if let Some(key) = event.as_key_press() { ... } ``` Similar flexible methods are aded across all the event enums: - `Event::is_focus_gained()` - `Event::is_focus_lost()` - `Event::is_key()` - `Event::is_mouse()` - `Event::is_paste()` - `Event::is_resize()` - `Event::is_key_press()` - `Event::as_key_press() -> Option<&KeyEvent>` - `MouseEventKind::is_*()` - `MouseButton::is_*()` - `KeyEventKind::is_*()` - `KeyEvent::is_press()` - `KeyEvent::is_release()` - `KeyEvent::is_repeat()` - `KeyCode::is_*()` - `KeyCode::is_function_key(n)` - `KeyCode::is_char(c)` - `KeyCode::as_char() -> Option<char>` - `KeyCode::is_media_key(media)` - `KeyCode::is_modifier(modifier)` - add is_key_release() and is_key_repeat() checks - add as_key_event() - rename as_key_press() to as_key_press_event() - add as_key_repeat_event() - add as_key_release_event() - add as_mouse_event() - add as_paste_event() - more tests - update event-match and key-display examples
47 lines
1.2 KiB
Rust
47 lines
1.2 KiB
Rust
//! Demonstrates the display format of key events.
|
|
//!
|
|
//! This example demonstrates the display format of key events, which is useful for displaying in
|
|
//! the help section of a terminal application.
|
|
//!
|
|
//! cargo run --example key-display
|
|
|
|
use std::io;
|
|
|
|
use crossterm::event::KeyModifiers;
|
|
use crossterm::{
|
|
event::{read, KeyCode},
|
|
terminal::{disable_raw_mode, enable_raw_mode},
|
|
};
|
|
|
|
const HELP: &str = r#"Key display
|
|
- Press any key to see its display format
|
|
- Use Esc to quit
|
|
"#;
|
|
|
|
fn main() -> io::Result<()> {
|
|
println!("{}", HELP);
|
|
enable_raw_mode()?;
|
|
if let Err(e) = print_events() {
|
|
println!("Error: {:?}\r", e);
|
|
}
|
|
disable_raw_mode()?;
|
|
Ok(())
|
|
}
|
|
|
|
fn print_events() -> io::Result<()> {
|
|
while let Ok(event) = read() {
|
|
let Some(event) = event.as_key_press_event() else {
|
|
continue;
|
|
};
|
|
let modifier = match event.modifiers {
|
|
KeyModifiers::NONE => "".to_string(),
|
|
_ => format!("{:}+", event.modifiers),
|
|
};
|
|
println!("Key pressed: {modifier}{code}\r", code = event.code);
|
|
if event.code == KeyCode::Esc {
|
|
break;
|
|
}
|
|
}
|
|
Ok(())
|
|
}
|