Skip to content

Commit

Permalink
Add keyboard handling example and update documentation (#294)
Browse files Browse the repository at this point in the history
* Add keyboard handling example

* Update documentation about handling keyboard input

* Run cargo fmt to pass all CL

* Fix to pass CL
  • Loading branch information
GNUSheep authored Jan 31, 2024
1 parent 88d6b60 commit 03c443b
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 0 deletions.
10 changes: 10 additions & 0 deletions examples/keyboard_handler/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
[package]
name = "keyboard_handler"
edition = "2021"
license.workspace = true
version.workspace = true

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
floem = { path = "../.." }
31 changes: 31 additions & 0 deletions examples/keyboard_handler/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
use floem::{
event::{Event, EventListener},
keyboard::Key,
unit::UnitExt,
view::View,
views::{stack, text, Decorators},
};

fn app_view() -> impl View {
let view =
stack((text("Example: Keyboard event handler").style(|s| s.padding(10.0)),)).style(|s| {
s.size(100.pct(), 100.pct())
.flex_col()
.items_center()
.justify_center()
});
view.keyboard_navigatable()
.on_event_stop(EventListener::KeyDown, move |e| {
if let Event::KeyDown(e) = e {
if e.key.logical_key == Key::Character("q".into()) {
println!("Goodbye :)");
std::process::exit(0)
}
println!("Key pressed in KeyCode: {:?}", e.key.physical_key);
}
})
}

fn main() {
floem::launch(app_view);
}
4 changes: 4 additions & 0 deletions src/views/decorator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,8 @@ pub trait Decorators: View + Sized {
}

/// Add an handler for pressing down a specific key.
///
/// NOTE: View should have `.keyboard_navigable()` in order to receive keyboard events
fn on_key_down(
mut self,
key: Key,
Expand All @@ -112,6 +114,8 @@ pub trait Decorators: View + Sized {
}

/// Add an handler for a specific key being released.
///
/// NOTE: View should have `.keyboard_navigable()` in order to receive keyboard events
fn on_key_up(
mut self,
key: Key,
Expand Down

0 comments on commit 03c443b

Please sign in to comment.