full_custom_input/
full-custom-input.rs

1use cool_rust_input::{
2    set_terminal_line, CoolInput, CustomInputHandler, HandlerContext, InputTransform,
3    KeyPressResult,
4};
5use crossterm::event::{Event, KeyCode};
6use crossterm::{
7    queue,
8    style::{Color, SetForegroundColor},
9};
10use std::io::stdout;
11
12pub struct CoolCustomInput;
13impl CustomInputHandler for CoolCustomInput {
14    fn handle_key_press(&mut self, key: &Event, _: HandlerContext) -> KeyPressResult {
15        if let Event::Key(key_event) = key {
16            if key_event.kind == crossterm::event::KeyEventKind::Press {
17                // Make escape stop the input
18                if let KeyCode::Esc = key_event.code {
19                    return KeyPressResult::Stop;
20                }
21                // Disallow the user pressing the character 'S'
22                if let KeyCode::Char(c) = key_event.code {
23                    if c == 's' || c == 'S' {
24                        return KeyPressResult::Handled;
25                    }
26                }
27            }
28        }
29        KeyPressResult::Continue
30    }
31    fn before_draw_text(&mut self, _: HandlerContext) {
32        let _ = queue!(stdout(), SetForegroundColor(Color::Green));
33    }
34    fn after_draw_text(&mut self, ctx: HandlerContext) {
35        let _ = queue!(stdout(), SetForegroundColor(Color::White));
36        let _ = set_terminal_line(
37            "Welcome to my cool text editor. Here you can write cool stuff! Press ESC to exit.",
38            5,
39            0,
40            true,
41        );
42        let _ = set_terminal_line("Rules:", 5, 1, true);
43        let _ = set_terminal_line("No typing the letter S", 10, 2, true);
44
45        let width = self.get_input_transform(ctx).size.0;
46        let _ = set_terminal_line(&String::from("_").repeat(width as usize), 5, 3, true);
47    }
48    fn get_input_transform(&mut self, ctx: HandlerContext) -> InputTransform {
49        let size = (ctx.terminal_size.0 - 10, ctx.terminal_size.1 - 5);
50        let offset = (5, 5);
51        InputTransform { size, offset }
52    }
53}
54
55fn main() -> Result<(), std::io::Error> {
56    let mut cool_input = CoolInput::new(CoolCustomInput, 0);
57    cool_input.listen()?;
58    Ok(())
59}