From 08a031cbe5913c249efa7fc82556d5d95f981c4c Mon Sep 17 00:00:00 2001 From: Héctor Ramón Jiménez Date: Thu, 7 Sep 2023 02:45:15 +0200 Subject: Introduce `keyboard::on_key_press` and `on_key_release` Also rename `subscription::events*` to `event::listen*`. --- futures/src/keyboard.rs | 61 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 futures/src/keyboard.rs (limited to 'futures/src/keyboard.rs') 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( + f: fn(KeyCode, Modifiers) -> Option, +) -> Subscription +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( + f: fn(KeyCode, Modifiers) -> Option, +) -> Subscription +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, + } + }) +} -- cgit From d21f0698b505d699c44e9414f902dbeca9474e39 Mon Sep 17 00:00:00 2001 From: Héctor Ramón Jiménez Date: Thu, 7 Sep 2023 02:46:19 +0200 Subject: Add hotkey support for `stopwatch` example --- futures/src/keyboard.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'futures/src/keyboard.rs') diff --git a/futures/src/keyboard.rs b/futures/src/keyboard.rs index 1ddca0bb..af68e1f2 100644 --- a/futures/src/keyboard.rs +++ b/futures/src/keyboard.rs @@ -44,9 +44,9 @@ where Message: MaybeSend + 'static, { #[derive(Hash)] - struct OnKeyPress; + struct OnKeyRelease; - subscription::filter_map((OnKeyPress, f), move |event, status| { + subscription::filter_map((OnKeyRelease, f), move |event, status| { match (event, status) { ( core::Event::Keyboard(Event::KeyReleased { -- cgit