Unify keyboard subscriptions into listen

This commit is contained in:
Héctor Ramón Jiménez 2025-12-02 18:35:50 +01:00
parent 0df5765e2f
commit 7e5b6f6802
No known key found for this signature in database
GPG key ID: 7CC46565708259A7
9 changed files with 77 additions and 96 deletions

View file

@ -1,66 +1,18 @@
//! Listen to keyboard events.
use crate::MaybeSend;
use crate::core;
use crate::core::event;
use crate::core::keyboard::{Event, Key, Modifiers, key};
use crate::core::keyboard::Event;
use crate::subscription::{self, Subscription};
/// 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, key::Physical, Modifiers) -> Option<Message>,
) -> Subscription<Message>
where
Message: MaybeSend + 'static,
{
/// Returns a [`Subscription`] that listens to ignored keyboard events.
pub fn listen() -> Subscription<Event> {
#[derive(Hash)]
struct OnKeyPress;
struct Listen;
subscription::filter_map((OnKeyPress, f), move |event| match event {
subscription::filter_map(Listen, move |event| match event {
subscription::Event::Interaction {
event:
core::Event::Keyboard(Event::KeyPressed {
key,
physical_key,
modifiers,
..
}),
status: event::Status::Ignored,
event: core::Event::Keyboard(event),
..
} => f(key, physical_key, modifiers),
_ => 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, key::Physical, 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,
physical_key,
modifiers,
..
}),
status: event::Status::Ignored,
..
} => f(key, physical_key, modifiers),
} => Some(event),
_ => None,
})
}