iced_futures/
keyboard.rs

1//! Listen to keyboard events.
2use crate::MaybeSend;
3use crate::core;
4use crate::core::event;
5use crate::core::keyboard::{Event, Key, Modifiers};
6use crate::subscription::{self, Subscription};
7
8/// Listens to keyboard key presses and calls the given function
9/// to map them into actual messages.
10///
11/// If the function returns `None`, the key press will be simply
12/// ignored.
13pub fn on_key_press<Message>(
14    f: fn(Key, Modifiers) -> Option<Message>,
15) -> Subscription<Message>
16where
17    Message: MaybeSend + 'static,
18{
19    #[derive(Hash)]
20    struct OnKeyPress;
21
22    subscription::filter_map((OnKeyPress, f), move |event| match event {
23        subscription::Event::Interaction {
24            event:
25                core::Event::Keyboard(Event::KeyPressed { key, modifiers, .. }),
26            status: event::Status::Ignored,
27            ..
28        } => f(key, modifiers),
29        _ => None,
30    })
31}
32
33/// Listens to keyboard key releases and calls the given function
34/// to map them into actual messages.
35///
36/// If the function returns `None`, the key release will be simply
37/// ignored.
38pub fn on_key_release<Message>(
39    f: fn(Key, Modifiers) -> Option<Message>,
40) -> Subscription<Message>
41where
42    Message: MaybeSend + 'static,
43{
44    #[derive(Hash)]
45    struct OnKeyRelease;
46
47    subscription::filter_map((OnKeyRelease, f), move |event| match event {
48        subscription::Event::Interaction {
49            event:
50                core::Event::Keyboard(Event::KeyReleased { key, modifiers, .. }),
51            status: event::Status::Ignored,
52            ..
53        } => f(key, modifiers),
54        _ => None,
55    })
56}