# keyboard-codes
[](https://crates.io/crates/keyboard-codes)
[](https://docs.rs/keyboard-codes)
[](https://github.com/ymc-github/keyboard-codes/blob/main/LICENSE)
[](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
- **Custom Key Mapping**: Support for custom keys and macros
- **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.1"
```
### Optional Features
- `serde`: Enables serialization/deserialization support
- `phf`: Uses perfect hash functions for faster string lookups
```toml
[dependencies]
keyboard-codes = { version = "0.1", features = ["serde"] }
```
## 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));
```
### 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, 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, etc.
### Modifier Keys
- **Basic Modifiers**: Alt, Control, Shift, Meta
- **Side-specific Modifiers**: LeftAlt, RightAlt, LeftControl, RightControl, etc.
### Media Keys
- **Media Control**: Play/Pause, Stop, Next, Previous
- **Volume Control**: VolumeUp, VolumeDown, VolumeMute
- **Browser Control**: Back, Forward, Refresh, Home
## Platform Support
| 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(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"));
```
## 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
## 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