Skip to main content

openlogi_core/config/
key_trigger.rs

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