diff options
author | 2023-09-07 02:45:15 +0200 | |
---|---|---|
committer | 2023-09-07 02:45:15 +0200 | |
commit | 08a031cbe5913c249efa7fc82556d5d95f981c4c (patch) | |
tree | 8b8db2279c04393a8b8e39ed0a74b922c91c8dea /futures/src/keyboard.rs | |
parent | a56b25b9096d47ada3c4349f5b91110dfaa92bf6 (diff) | |
download | iced-08a031cbe5913c249efa7fc82556d5d95f981c4c.tar.gz iced-08a031cbe5913c249efa7fc82556d5d95f981c4c.tar.bz2 iced-08a031cbe5913c249efa7fc82556d5d95f981c4c.zip |
Introduce `keyboard::on_key_press` and `on_key_release`
Also rename `subscription::events*` to `event::listen*`.
Diffstat (limited to '')
-rw-r--r-- | futures/src/keyboard.rs | 61 |
1 files changed, 61 insertions, 0 deletions
diff --git a/futures/src/keyboard.rs b/futures/src/keyboard.rs new file mode 100644 index 00000000..1ddca0bb --- /dev/null +++ b/futures/src/keyboard.rs @@ -0,0 +1,61 @@ +//! Listen to keyboard events. +use crate::core; +use crate::core::keyboard::{Event, KeyCode, Modifiers}; +use crate::subscription::{self, Subscription}; +use crate::MaybeSend; + +/// Listens to keyboard key presses and calls the given function +/// 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(KeyCode, Modifiers) -> Option<Message>, +) -> Subscription<Message> +where + Message: MaybeSend + 'static, +{ + #[derive(Hash)] + struct OnKeyPress; + + subscription::filter_map((OnKeyPress, f), move |event, status| { + match (event, status) { + ( + core::Event::Keyboard(Event::KeyPressed { + key_code, + modifiers, + }), + core::event::Status::Ignored, + ) => f(key_code, modifiers), + _ => None, + } + }) +} + +/// Listens to keyboard key releases and calls the given function +/// 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(KeyCode, Modifiers) -> Option<Message>, +) -> Subscription<Message> +where + Message: MaybeSend + 'static, +{ + #[derive(Hash)] + struct OnKeyPress; + + subscription::filter_map((OnKeyPress, f), move |event, status| { + match (event, status) { + ( + core::Event::Keyboard(Event::KeyReleased { + key_code, + modifiers, + }), + core::event::Status::Ignored, + ) => f(key_code, modifiers), + _ => None, + } + }) +} |