Skip to content

Commit

Permalink
Release v0.1.0
Browse files Browse the repository at this point in the history
  • Loading branch information
rezigned committed Jul 30, 2023
0 parents commit 932863f
Show file tree
Hide file tree
Showing 13 changed files with 787 additions and 0 deletions.
21 changes: 21 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
name: Rust

on:
push:
branches: [ "main" ]
pull_request:
branches: [ "main" ]

env:
CARGO_TERM_COLOR: always

jobs:
build:
runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v3
- name: Build
run: cargo build --verbose
- name: Run tests
run: cargo test --verbose
7 changes: 7 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
/target
Cargo.lock
.DS_Store

# Devenv
.devenv*
devenv.local.nix
32 changes: 32 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
[package]
name = "keymap"
description = "A library for defining and parsing input events from configuration"
authors = ["Marut Khumtong <[email protected]>"]
version = "0.1.0"
homepage = "https://github.com/rezigned/keymap-rs"
repository = "https://github.com/rezigned/keymap-rs"
edition = "2021"
keywords = ["terminal", "event", "config", "keymapping", "keybinding"]
license = "MIT"

[dependencies]
crossterm = { version = "0.26", optional = true }
termion = { version = "2.0", optional = true }
pom = "3.3.0"
serde = { version = "1.0", features = ["derive"] }
strum = "0.25"
strum_macros = "0.25"

[features]
default = ["crossterm"]

[dev-dependencies]
toml = "0.7"

[[example]]
name = "crossterm"
required-features = ["crossterm"]

[[example]]
name = "termion"
required-features = ["termion"]
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2023 Marut Khumtong

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
61 changes: 61 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
# keymap-rs

[![crates.io](https://img.shields.io/crates/v/keymap.svg)](https://crates.io/crates/keymap)
[![Rust](https://github.com/rezigned/keymap-rs/actions/workflows/ci.yml/badge.svg)](https://github.com/rezigned/keymap-rs/actions/workflows/ci.yml)
[![License: MIT](https://img.shields.io/badge/License-MIT-brightgreen.svg)](https://opensource.org/licenses/MIT)

`keymap-rs` is a library for defining input events from configurations and mapping them to the terminal library's event. (such as [crossterm](https://github.com/crossterm-rs/crossterm) or [termion](https://gitlab.redox-os.org/redox-os/termion))

## Getting started

_Please check the [examples](examples/) directory for complete examples._

<details>
<summary>
Click to show <code>Cargo.toml</code>.
</summary>

```toml
[dependencies]
keymap = "0.1"
```
</details>

Let's started by defining a simple structure for mapping input key to `String`.

```rs
use keymap::{KeyMap, Key};
use serde::Deserialize;

#[derive(Deserialize)]
struct Config(pub HashMap<KeyMap, String>)

let config = r#"
up = "Up"
down = "Down"
g = "Top"
G = "Bottom" # This is the same as `shift-g`
esc = "Quit"
"
```
Then in your terminal library of choice (we'll be using [crossterm](https://github.com/crossterm-rs/crossterm) as an example). You can use any deserializer (e.g. `toml`, `json`, etc.) to deserialize a key from the configuration above into the terminal library's event (e.g. `crossterm::event::KeyEvent`).
```rs
let mapping: Config = toml::from_str(config).unwrap();
// Read input event
match read()? {
Event::Key(key) => {
// `Key::from` will convert `crossterm::event::KeyEvent` to `keymap::Key`
if let Some(action) = config.0.get(&Key::from(key)) {
match action {
"Up" => println!("Move up!"),
"Down" => println!("Move down!"),
// ...
"Quit" => break,
}
}
}
}
```
35 changes: 35 additions & 0 deletions examples/config.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
use std::collections::HashMap;

use keymap::KeyMap;
use serde::Deserialize;
use strum_macros::Display;

#[derive(Debug, Deserialize, PartialEq, Display)]
pub(crate) enum Action {
Bottom,
Down,
Explode,
Jump,
Top,
Up,
Quit,
}

#[allow(unused)]
#[derive(Debug, Deserialize)]
pub(crate) struct Config(pub HashMap<KeyMap, Action>);

#[allow(unused)]
pub(crate) const CONFIG_DATA: &str = r#"
up = "Up"
down = "Down"
ctrl-z = "Explode"
shift-g = "Bottom"
g = "Top"
q = "Quit"
esc = "Quit"
space = "Jump"
"#;

#[allow(unused)]
fn main() {}
48 changes: 48 additions & 0 deletions examples/crossterm.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
use std::io::{self, Stdout};
mod config;

use config::{Action, Config, CONFIG_DATA};
use crossterm::{
cursor,
event::{read, Event},
execute,
style::Print,
terminal::{disable_raw_mode, enable_raw_mode},
};
use keymap::Key;

fn main() -> io::Result<()> {
let mut stdout = io::stdout();
enable_raw_mode()?;

read_event(&mut stdout)?;

disable_raw_mode()
}

fn read_event(stdout: &mut Stdout) -> io::Result<()> {
let config: Config = toml::from_str(CONFIG_DATA).unwrap();

loop {
let event = read()?;

match event {
Event::Key(key) => {
if let Some((k, action)) = config.0.get_key_value(&Key::from(key)) {
if *action == Action::Quit {
break;
}

execute!(
stdout,
Print(format!("key:{} - {}\n", k, action)),
cursor::MoveToNextLine(1),
)?;
}
}
_ => (),
}
}

Ok(())
}
34 changes: 34 additions & 0 deletions examples/termion.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
mod config;

use config::{CONFIG_DATA, Config, Action};
use keymap::Key;
use termion::event::Event;
use termion::input::{TermRead, MouseTerminal};
use termion::raw::IntoRawMode;
use std::io::{Write, stdout, stdin};

fn main() {
let stdin = stdin();
let mut stdout = MouseTerminal::from(stdout().into_raw_mode().unwrap());

stdout.flush().unwrap();

// Parse key event
let bindings: Config = toml::from_str(CONFIG_DATA).unwrap();

for c in stdin.events() {
let evt = c.unwrap();

if let Event::Key(key) = evt {
if let Some((k, action)) = bindings.keys.get_key_value(&Key::from(key)) {
if *action == Action::Quit {
break;
}

write!(stdout, "{}{}key:{k} - {}", termion::clear::All, termion::cursor::Goto(1, 1), action).unwrap();
}
}

stdout.flush().unwrap();
}
}
Loading

0 comments on commit 932863f

Please sign in to comment.