Skip to main content

openlogi_core/config/
key_trigger.rs

1//! Keyboard key triggers and the global keyboard-bindings section.
2
3use serde::{Deserialize, Serialize};
4
5use crate::binding::Action;
6
7/// Detectable modifier state for a keyboard trigger. A leaf-level duplicate of
8/// `openlogi_hook::KeyModifiers` — core must not depend on hook, so the four
9/// bools are mirrored here and converted at the agent boundary (which depends
10/// on both crates). `Fn` is absent: firmware-internal, unusable as a trigger
11/// (function-key-remapper spec, Appendix A).
12#[derive(
13    Debug, Clone, Copy, Default, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize,
14)]
15#[expect(
16    clippy::struct_excessive_bools,
17    reason = "four independent modifier flags mirrored from the OS hook"
18)]
19pub struct KeyModifiers {
20    /// Shift held.
21    pub shift: bool,
22    /// Control held.
23    pub control: bool,
24    /// Option/Alt held.
25    pub option: bool,
26    /// Command held.
27    pub command: bool,
28}
29
30impl KeyModifiers {
31    /// True when no modifiers are held.
32    #[must_use]
33    pub fn is_empty(&self) -> bool {
34        !self.shift && !self.control && !self.option && !self.command
35    }
36}
37
38/// A keyboard trigger: a keycode plus an optional modifier mask. The parse
39/// format is `[mod+]+key`, e.g. `"f1"`, `"shift+cmd+f5"`. Modifier names:
40/// `shift`, `control` (alias `ctrl`), `option` (alias `alt`), `command`
41/// (alias `cmd`). Key names: `esc`, `f1`..`f19` (macOS virtual keycodes).
42///
43/// Serializes as its string form (via `Display`) so it can be a TOML map key:
44/// `[keyboard.bindings]` keys are `"f1"`, `"shift+f2"`, etc.
45#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
46pub struct KeyTrigger {
47    /// Platform virtual keycode (macOS `kVK_*`).
48    pub keycode: u16,
49    /// Modifier mask that must also be held.
50    pub modifiers: KeyModifiers,
51}
52
53impl std::fmt::Display for KeyTrigger {
54    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
55        let mut parts: Vec<&str> = Vec::new();
56        let m = &self.modifiers;
57        if m.shift {
58            parts.push("shift");
59        }
60        if m.control {
61            parts.push("control");
62        }
63        if m.option {
64            parts.push("option");
65        }
66        if m.command {
67            parts.push("command");
68        }
69        parts.push(keycode_to_name(self.keycode).ok_or(std::fmt::Error)?);
70        write!(f, "{}", parts.join("+"))
71    }
72}
73
74/// Reverse lookup for the parse table — needed so `Display` can render a
75/// parsed trigger back to its canonical name.
76fn keycode_to_name(code: u16) -> Option<&'static str> {
77    Some(match code {
78        0x35 => "esc",
79        0x7A => "f1",
80        0x78 => "f2",
81        0x63 => "f3",
82        0x76 => "f4",
83        0x60 => "f5",
84        0x61 => "f6",
85        0x62 => "f7",
86        0x64 => "f8",
87        0x65 => "f9",
88        0x6D => "f10",
89        0x67 => "f11",
90        0x6F => "f12",
91        0x69 => "f13",
92        0x6B => "f14",
93        0x71 => "f15",
94        0x6A => "f16",
95        0x40 => "f17",
96        0x4F => "f18",
97        0x50 => "f19",
98        _ => return None,
99    })
100}
101
102// String-form serde so KeyTrigger can be a TOML map key.
103impl Serialize for KeyTrigger {
104    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
105        s.collect_str(self)
106    }
107}
108impl<'de> Deserialize<'de> for KeyTrigger {
109    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
110        let s = String::deserialize(d)?;
111        s.parse().map_err(serde::de::Error::custom)
112    }
113}
114
115/// Error returned by [`KeyTrigger`]'s `FromStr` impl.
116#[derive(Debug)]
117pub struct ParseTriggerError(pub String);
118impl std::fmt::Display for ParseTriggerError {
119    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
120        write!(f, "invalid key trigger: {}", self.0)
121    }
122}
123impl std::error::Error for ParseTriggerError {}
124
125impl std::str::FromStr for KeyTrigger {
126    type Err = ParseTriggerError;
127    fn from_str(s: &str) -> Result<Self, Self::Err> {
128        let mut mods = KeyModifiers::default();
129        let parts: Vec<&str> = s.split('+').map(str::trim).collect();
130        if parts.is_empty() || parts.iter().any(|p| p.is_empty()) {
131            return Err(ParseTriggerError("empty segment".into()));
132        }
133        // All but the last segment must be modifiers; the last is the key.
134        let (mod_parts, key_part) = parts.split_at(parts.len() - 1);
135        for part in mod_parts {
136            match part.to_ascii_lowercase().as_str() {
137                "shift" => mods.shift = true,
138                "control" | "ctrl" => mods.control = true,
139                "option" | "alt" => mods.option = true,
140                "command" | "cmd" => mods.command = true,
141                other => return Err(ParseTriggerError(format!("unknown modifier '{other}'"))),
142            }
143        }
144        let keycode = match key_part[0].to_ascii_lowercase().as_str() {
145            "esc" => 0x35,
146            "f1" => 0x7A,
147            "f2" => 0x78,
148            "f3" => 0x63,
149            "f4" => 0x76,
150            "f5" => 0x60,
151            "f6" => 0x61,
152            "f7" => 0x62,
153            "f8" => 0x64,
154            "f9" => 0x65,
155            "f10" => 0x6D,
156            "f11" => 0x67,
157            "f12" => 0x6F,
158            "f13" => 0x69,
159            "f14" => 0x6B,
160            "f15" => 0x71,
161            "f16" => 0x6A,
162            "f17" => 0x40,
163            "f18" => 0x4F,
164            "f19" => 0x50,
165            other => return Err(ParseTriggerError(format!("unknown key '{other}'"))),
166        };
167        Ok(KeyTrigger {
168            keycode,
169            modifiers: mods,
170        })
171    }
172}
173
174/// The top-level `[keyboard]` table. Bindings are keyed by [`KeyTrigger`].
175#[derive(Debug, Clone, Default, Serialize, Deserialize)]
176pub struct KeyboardConfig {
177    /// Function-key trigger → action map for the remapper.
178    #[serde(default, skip_serializing_if = "std::collections::HashMap::is_empty")]
179    pub bindings: std::collections::HashMap<KeyTrigger, Action>,
180}