gyscos / cursive

A Text User Interface library for the Rust programming language
MIT License
4.26k stars 243 forks source link

Add method to return character from char event. #744

Closed timdubbins closed 1 year ago

timdubbins commented 1 year ago

Firstly, thank you for this library. I've really enjoyed hacking my way through it.

This is a minor proposal that helped me clean up some ugly code. Here's an example:

use cursive::event::{Event, EventResult, EventTrigger};
use cursive::views::TextView;

fn main() {
    let mut siv = cursive::default();
    siv.add_layer(TextView::new("enter uppercased character:"));

    siv.set_on_pre_event_inner(uppercased(), move |event| {
        // use the method here
        let c = event.char().expect("only chars are triggered");
        Some(EventResult::with_cb(move |siv| {
            siv.add_layer(TextView::new(format!("do something useful with: {}", c)))
        }))
    });

    siv.set_on_pre_event(Event::Char('q'), |siv| siv.quit());
    siv.run();
}

fn uppercased() -> EventTrigger {
    EventTrigger::from_fn(|e| matches!(e, Event::Char('A'..='Z')))
}

This Event::chars() method allows us to access the inputted character without creating a mapping, which is a bit tedious when you want to capture a range of values (as we do in the example).

gyscos commented 1 year ago

Thanks for the PR! I think in this case a match self might be shorter and simpler than a if let.

Also, should it maybe also return the char for AltChar and CtrlChar events?