keyboard-codes 0.3.0

Cross-platform keyboard key code mapping and conversion
Documentation
# keyboard-codes


[![Crates.io](https://img.shields.io/crates/v/keyboard-codes.svg)](https://crates.io/crates/keyboard-codes)
[![Documentation](https://docs.rs/keyboard-codes/badge.svg)](https://docs.rs/keyboard-codes)
[![License](https://img.shields.io/crates/l/keyboard-codes.svg)](https://github.com/ymc-github/keyboard-codes/blob/main/LICENSE)
[![Build Status](https://github.com/ymc-github/keyboard-codes/actions/workflows/ci.yml/badge.svg)](https://github.com/ymc-github/keyboard-codes/actions)

A comprehensive cross-platform Rust library for keyboard key code mapping and conversion. Supports Windows, Linux, and macOS with bidirectional conversion between key names and platform-specific codes.

## Features


- **Cross-platform Support**: Comprehensive key code mappings for Windows, Linux, and macOS
- **Comprehensive Key Definitions**: Standard keys, modifiers, function keys, media keys, and more
- **Bidirectional Conversion**: Convert between key names and platform-specific codes
- **Flexible Parsing**: Support for aliases, case-insensitive matching, and multiple shortcut formats
- **Custom Key Mapping**: Support for custom keys and macros with platform-specific codes
- **Shortcut Parsing**: Advanced parsing of keyboard shortcuts with modifier combinations
- **Zero Dependencies** (core functionality)
- **Serde Support**: Optional serialization/deserialization
- **PHF Support**: Optional perfect hash functions for faster lookups

## Installation


Add this to your `Cargo.toml`:

```toml
[dependencies]
keyboard-codes = "0.2.0"
```

### Optional Features


- `serde`: Enables serialization/deserialization support for all key types
- `phf`: Uses perfect hash functions for faster string lookups

```toml
[dependencies]
keyboard-codes = { version = "0.2.0", features = ["serde", "phf"] }
```

## Quick Start


```rust
use keyboard_codes::{Key, Modifier, Platform, KeyCodeMapper};

// Parse keys from strings
let enter_key: Key = "Enter".parse().unwrap();
let shift_mod: Modifier = "Shift".parse().unwrap();

// Convert to platform-specific codes
let windows_code = enter_key.to_code(Platform::Windows);
let linux_code = enter_key.to_code(Platform::Linux);

// Parse from codes
let key_from_code = Key::from_code(0x0D, Platform::Windows).unwrap();

// Get current platform
let current_platform = keyboard_codes::current_platform();
```

## Usage Examples


### Basic Key Operations


```rust
use keyboard_codes::{Key, Modifier, Platform, KeyCodeMapper};

// String parsing
assert_eq!("Escape".parse::<Key>().unwrap(), Key::Escape);
assert_eq!("Shift".parse::<Modifier>().unwrap(), Modifier::Shift);

// Code conversion
assert_eq!(Key::Enter.to_code(Platform::Windows), 0x0D);
assert_eq!(Key::Enter.to_code(Platform::Linux), 28);
assert_eq!(Key::Enter.to_code(Platform::MacOS), 36);

// Reverse lookup
assert_eq!(Key::from_code(0x1B, Platform::Windows), Some(Key::Escape));
assert_eq!(Modifier::from_code(42, Platform::Linux), Some(Modifier::LeftShift));
```

### Advanced Shortcut Parsing


```rust
use keyboard_codes::{
    parse_shortcut_with_aliases, 
    parse_shortcut_flexible, 
    parse_shortcut_sequence,
    parse_input,
    Shortcut
};

// Parse shortcuts with alias support
let shortcut = parse_shortcut_with_aliases("ctrl+shift+a").unwrap();
assert_eq!(shortcut.modifiers, vec![Modifier::Control, Modifier::Shift]);
assert_eq!(shortcut.key, Key::A);

// Flexible separator support (+, -, space)
let shortcut = parse_shortcut_flexible("ctrl-shift a").unwrap();

// Parse sequence of shortcuts
let shortcuts = parse_shortcut_sequence("ctrl+a, cmd+q, shift+enter").unwrap();

// Auto-detect single key or shortcut
let single_key = parse_input("a").unwrap(); // Single key
let shortcut = parse_input("ctrl+a").unwrap(); // Shortcut

// Alias support for modifiers and keys
let shortcut = parse_shortcut_with_aliases("cmd+esc").unwrap(); // Meta+Escape
```

### Custom Key Mapping


```rust
use keyboard_codes::{CustomKey, CustomKeyMap, Platform};

let mut custom_map = CustomKeyMap::new();

// Create a custom macro key
let mut macro_key = CustomKey::new("MyMacro");
macro_key.add_platform_code(Platform::Windows, 0x100)
         .add_platform_code(Platform::Linux, 200);

custom_map.add_key(macro_key).unwrap();

// Use the custom key
if let Some(key) = custom_map.parse_by_name("MyMacro") {
    let code = key.code(Platform::Windows).unwrap();
    println!("Custom key code: {}", code);
}

// Lookup by code
if let Some(key) = custom_map.parse_by_code(200, Platform::Linux) {
    println!("Found custom key: {}", key.name());
}
```

### Platform Detection


```rust
use keyboard_codes::{current_platform, Key, KeyCodeMapper};

let platform = current_platform();
let key = Key::A;
let code = key.to_code(platform);

println!("Key {} has code {} on {}", key, code, platform);
```

## Supported Key Types


### Standard Keys

- **Function Keys**: Escape, Enter, Tab, Backspace, Space, Insert, Delete, etc.
- **Navigation Keys**: Arrow keys, Home, End, PageUp, PageDown
- **Alphabet Keys**: A through Z
- **Number Keys**: 0-9 (both main keyboard and numpad)
- **Function Keys**: F1 through F24
- **Special Keys**: CapsLock, NumLock, ScrollLock, Pause, Apps, Sleep, etc.

### Modifier Keys

- **Basic Modifiers**: Alt, Control, Shift, Meta
- **Side-specific Modifiers**: LeftAlt, RightAlt, LeftControl, RightControl, LeftShift, RightShift, LeftMeta, RightMeta

### Media Keys

- **Media Control**: Play/Pause, Stop, Next, Previous
- **Volume Control**: VolumeUp, VolumeDown, VolumeMute
- **Browser Control**: Back, Forward, Refresh, Home

## Alias Support


The library provides extensive alias support for convenient parsing:

### Modifier Aliases

- `ctrl`, `ctl``Control`
- `shft``Shift`
- `altgr`, `opt`, `option``Alt`
- `win`, `windows`, `cmd`, `command`, `super``Meta`
- `lctrl`, `lctl``LeftControl`
- `rshift`, `rshft``RightShift`
- And many more...

### Key Aliases

- `esc``Escape`
- `return``Enter`
- `back`, `bs``Backspace`
- `del``Delete`
- `ins``Insert`
- `pgup``PageUp`
- `pgdn`, `pagedown``PageDown`
- `left``ArrowLeft`
- `right``ArrowRight`
- `up``ArrowUp`
- `down``ArrowDown`
- `0`-`9``D0`-`D9`

## Platform Support


| Platform | Key Code Range | Notes |
|----------|----------------|-------|
| Windows  | 0x00 - 0xFF    | Virtual key codes |
| Linux    | 0x00 - 0x2FF   | Input event codes |
| macOS    | 0x00 - 0x7F    | Key codes |

## Error Handling


The library provides comprehensive error handling through the `KeyParseError` enum:

```rust
use keyboard_codes::KeyParseError;

match "UnknownKey".parse::<Key>() {
    Ok(key) => println!("Parsed key: {}", key),
    Err(KeyParseError::UnknownKey(name)) => println!("Unknown key: {}", name),
    Err(KeyParseError::UnknownModifier(modifier)) => println!("Unknown modifier: {}", modifier),
    Err(KeyParseError::InvalidShortcutFormat(msg)) => println!("Invalid shortcut format: {}", msg),
    Err(e) => println!("Other error: {}", e),
}
```

## Utility Functions


```rust
use keyboard_codes::{utils, Platform};

// Validate key codes
assert!(utils::is_valid_key_code(0x41, Platform::Windows));
assert!(!utils::is_valid_key_code(0x1000, Platform::Windows));

// Normalize key codes
let normalized = utils::normalize_key_code(0x141, Platform::Windows); // Returns 0x41

// Validate key names
assert!(utils::is_valid_key_name("Enter"));
assert!(!utils::is_valid_key_name("123"));
```

## API Overview


### Main Types

- `Key`: Keyboard key enumeration (150+ keys)
- `Modifier`: Modifier key enumeration (12 variants)
- `Platform`: Platform type enumeration (Windows, Linux, macOS)
- `CustomKey`: Custom key definition
- `CustomKeyMap`: Custom key mapping manager
- `Shortcut`: Parsed keyboard shortcut with modifiers

### Core Traits

- `KeyCodeMapper`: Key code mapping trait for bidirectional conversion
- `FromStr`: String parsing support for keys and modifiers
- `Display`: String representation support

### Main Modules

- `mapping::standard`: Standard key code mappings
- `mapping::custom`: Custom key mapping functionality
- `parser`: Advanced input parsing with alias support
- `types`: Core type definitions
- `utils`: Utility functions and helpers

## Feature Flags


- **default**: No additional features
- **serde**: Enables `Serialize` and `Deserialize` implementations for all types
- **phf**: Uses perfect hash functions for faster string-to-key parsing


## Example Directory Structure

```
├── examples/
│   ├── basic_usage.rs          # Basic usage example
│   ├── game_input_system.rs    # Game input system
│   ├── gui_shortcuts.rs        # GUI application shortcuts  
│   ├── macro_system.rs         # Automation macro system
│   ├── config_management.rs    # Cross-platform config management
│   ├── validation_tool.rs      # Testing validation tool
│   └── advanced_parsing.rs    # Advanced parsing features
```


## Contributing


Contributions are welcome! Please feel free to submit pull requests, open issues, or suggest new features.

## License


This project is licensed under either of:

- Apache License, Version 2.0 ([LICENSE-APACHE]LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
- MIT license ([LICENSE-MIT]LICENSE-MIT or http://opensource.org/licenses/MIT)

at your option.

## Acknowledgments


- Key code mappings are based on platform documentation and cross-referenced across multiple sources
- Inspired by the need for consistent cross-platform key handling in Rust applications