keybinds-rs
[!CAUTION] This crate is work in progress yet.
keybinds-rs is a small Rust crate to define/parse/match key bindings.
- Provide a syntax to easily define key bindings in a configuration file like
Ctrl+A
- Support key sequences like
Ctrl+X CtrolS
- Parse/Generate the key bindings configuration using serde
- Platform-agnostic core API with minimal dependencies
- TODO: Support several platforms as optional features
Usage
This crate is platform-agnostic. Define key bindings by KeyBinds
and build KeyBindMatcher
instance with it.
Pass each key input to the trigger
method and it returns a triggered action. Key sequence and key combination
can be parsed using FromStr
trait.
use ;
// Actions triggered by key bindings
// Key bindings to trigger the actions
let keybinds = new;
let mut matcher = new;
// Trigger `SayHello` action
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
// Trigger `OpenFile` action
let action = matcher.trigger;
assert_eq!;
// Trigger `ExitApp` action
assert_eq!;
assert_eq!;
Syntax for key sequence and combination
Keys are joint with +
as a key combination like Ctrl+a
. The last key must be a normal key and others must be modifier
keys.
Normal keys are a single character (e.g. a
, X
, あ
) or a special key name (e.g. Up
, Enter
, Tab
). Note that
upper case characters like A
are equivalent to the lower case ones like a
. For representing A
key, explicitly
specify Shift
modifier key.
The following modifier keys are available:
Ctrl
: Ctrl keyCmd
: Command keyMod
: Command key on macOS, Ctrl key on other platformsShift
: Shift keyAlt
: Alt keyOption
: An alias to Alt key
here are some examples of key combinations:
a
Enter
Mod+x
Ctrl+Shift+Left
Key combinations are joint with whitespaces as a key sequence. When key combinations are input in the order, they trigger the action.
Here are some examples of key sequences:
h e l l o
Ctrl+x Ctrl+c
serde support
Parsing key bindings configurations
KeyBinds
implements serde's Deserialize
trait. This is an example to parse key bindings as TOML.
use Deserialize;
use ;
// Actions triggered by key bindings
// Configuration file format of your application
let configuration = r#"
[bindings]
"Ctrl+Shift+Enter" = "OpenFile"
"Ctrl+x Ctrl+c" = "ExitApp"
"#;
// Parse the TOML input
let config: Config = from_str.unwrap;
// Use the key bindings parsed from the TOML input
let mut matcher = new;
let action = matcher.trigger;
assert_eq!;
License
This crate is licensed under the MIT license.