iced_futures/
keyboard.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
//! Listen to keyboard events.
use crate::core;
use crate::core::event;
use crate::core::keyboard::{Event, Key, Modifiers};
use crate::subscription::{self, Subscription};
use crate::MaybeSend;

/// Listens to keyboard key presses and calls the given function
/// to map them into actual messages.
///
/// If the function returns `None`, the key press will be simply
/// ignored.
pub fn on_key_press<Message>(
    f: fn(Key, Modifiers) -> Option<Message>,
) -> Subscription<Message>
where
    Message: MaybeSend + 'static,
{
    #[derive(Hash)]
    struct OnKeyPress;

    subscription::filter_map((OnKeyPress, f), move |event| match event {
        subscription::Event::Interaction {
            event:
                core::Event::Keyboard(Event::KeyPressed { key, modifiers, .. }),
            status: event::Status::Ignored,
            ..
        } => f(key, modifiers),
        subscription::Event::Interaction { .. } => None,
    })
}

/// Listens to keyboard key releases and calls the given function
/// to map them into actual messages.
///
/// If the function returns `None`, the key release will be simply
/// ignored.
pub fn on_key_release<Message>(
    f: fn(Key, Modifiers) -> Option<Message>,
) -> Subscription<Message>
where
    Message: MaybeSend + 'static,
{
    #[derive(Hash)]
    struct OnKeyRelease;

    subscription::filter_map((OnKeyRelease, f), move |event| match event {
        subscription::Event::Interaction {
            event:
                core::Event::Keyboard(Event::KeyReleased { key, modifiers, .. }),
            status: event::Status::Ignored,
            ..
        } => f(key, modifiers),
        subscription::Event::Interaction { .. } => None,
    })
}