2023-09-07 02:45:15 +02:00
|
|
|
//! Listen to keyboard events.
|
|
|
|
|
use crate::core;
|
2024-06-11 19:41:05 +02:00
|
|
|
use crate::core::event;
|
2024-01-16 13:28:00 +01:00
|
|
|
use crate::core::keyboard::{Event, Key, Modifiers};
|
2023-09-07 02:45:15 +02:00
|
|
|
use crate::subscription::{self, Subscription};
|
|
|
|
|
use crate::MaybeSend;
|
|
|
|
|
|
|
|
|
|
/// Listens to keyboard key presses and calls the given function
|
2024-07-16 15:41:28 +02:00
|
|
|
/// to map them into actual messages.
|
2023-09-07 02:45:15 +02:00
|
|
|
///
|
|
|
|
|
/// If the function returns `None`, the key press will be simply
|
|
|
|
|
/// ignored.
|
|
|
|
|
pub fn on_key_press<Message>(
|
2024-01-16 13:28:00 +01:00
|
|
|
f: fn(Key, Modifiers) -> Option<Message>,
|
2023-09-07 02:45:15 +02:00
|
|
|
) -> Subscription<Message>
|
|
|
|
|
where
|
|
|
|
|
Message: MaybeSend + 'static,
|
|
|
|
|
{
|
|
|
|
|
#[derive(Hash)]
|
|
|
|
|
struct OnKeyPress;
|
|
|
|
|
|
2024-06-11 19:41:05 +02:00
|
|
|
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),
|
|
|
|
|
_ => None,
|
2023-09-07 02:45:15 +02:00
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Listens to keyboard key releases and calls the given function
|
2024-07-16 15:41:28 +02:00
|
|
|
/// to map them into actual messages.
|
2023-09-07 02:45:15 +02:00
|
|
|
///
|
|
|
|
|
/// If the function returns `None`, the key release will be simply
|
|
|
|
|
/// ignored.
|
|
|
|
|
pub fn on_key_release<Message>(
|
2024-01-16 13:28:00 +01:00
|
|
|
f: fn(Key, Modifiers) -> Option<Message>,
|
2023-09-07 02:45:15 +02:00
|
|
|
) -> Subscription<Message>
|
|
|
|
|
where
|
|
|
|
|
Message: MaybeSend + 'static,
|
|
|
|
|
{
|
|
|
|
|
#[derive(Hash)]
|
2023-09-07 02:46:19 +02:00
|
|
|
struct OnKeyRelease;
|
2023-09-07 02:45:15 +02:00
|
|
|
|
2024-06-11 19:41:05 +02:00
|
|
|
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),
|
|
|
|
|
_ => None,
|
|
|
|
|
})
|
2023-09-07 02:45:15 +02:00
|
|
|
}
|