Skip to main content

btn_recognizer/key/
config.rs

1use std::collections::{HashMap, HashSet};
2use std::error::Error;
3use std::fmt;
4use std::time::Duration;
5
6use super::types::{ChordId, ControlId, KeyId, RawLevel};
7
8#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9pub enum ActiveLevel {
10    Low,
11    High,
12}
13
14impl ActiveLevel {
15    pub const fn is_pressed(self, raw_level: RawLevel) -> bool {
16        match self {
17            Self::Low => matches!(raw_level, RawLevel::Low),
18            Self::High => matches!(raw_level, RawLevel::High),
19        }
20    }
21}
22
23#[derive(Debug, Clone, PartialEq, Eq)]
24pub struct ButtonConfig {
25    pub id: KeyId,
26    pub active_level: ActiveLevel,
27    pub debounce: DebounceConfig,
28    /// Logical state assumed before the first sample is processed.
29    pub initially_pressed: bool,
30}
31
32impl ButtonConfig {
33    pub fn active_low(id: KeyId, debounce: Duration) -> Self {
34        Self {
35            id,
36            active_level: ActiveLevel::Low,
37            debounce: DebounceConfig::symmetric(debounce),
38            initially_pressed: false,
39        }
40    }
41}
42
43#[derive(Debug, Clone, Copy, PartialEq, Eq)]
44pub struct DebounceConfig {
45    pub press: Duration,
46    pub release: Duration,
47}
48
49impl DebounceConfig {
50    pub const fn symmetric(duration: Duration) -> Self {
51        Self {
52            press: duration,
53            release: duration,
54        }
55    }
56}
57
58#[derive(Debug, Clone, Copy, PartialEq, Eq)]
59pub enum ChordReleasePolicy {
60    /// Release the virtual control as soon as any member is released.
61    AnyMember,
62    /// Keep the virtual control down until every member is released.
63    AllMembers,
64}
65
66#[derive(Debug, Clone, PartialEq, Eq)]
67pub struct ChordConfig {
68    pub id: ChordId,
69    pub members: Vec<KeyId>,
70    pub window: Duration,
71    pub priority: i16,
72    pub release: ChordReleasePolicy,
73}
74
75#[derive(Debug, Clone, PartialEq, Eq)]
76pub struct RepeatConfig {
77    /// Time from the original down edge to the first repeat.
78    pub starts_after: Duration,
79    pub interval: Duration,
80}
81
82#[derive(Debug, Clone, Copy, PartialEq, Eq)]
83pub enum HoldAfterTapPolicy {
84    /// A later hold replaces taps still waiting in the multi-tap window.
85    CancelPendingTaps,
86    /// Emit already completed taps before starting the hold.
87    CommitPendingTaps,
88}
89
90#[derive(Debug, Clone, PartialEq, Eq)]
91pub struct GestureConfig {
92    /// Maximum down-to-up duration that can be counted as a tap.
93    pub tap_max: Duration,
94    /// Maximum delay from one tap release to the next down edge.
95    pub multi_tap_window: Duration,
96    /// Emit immediately after this many taps. Must be at least one.
97    pub max_taps: u8,
98    /// Strictly increasing hold thresholds. The first starts a hold; later
99    /// values are milestones.
100    pub hold_thresholds: Vec<Duration>,
101    pub repeat: Option<RepeatConfig>,
102    pub hold_after_tap: HoldAfterTapPolicy,
103}
104
105impl Default for GestureConfig {
106    fn default() -> Self {
107        Self {
108            tap_max: Duration::from_millis(500),
109            multi_tap_window: Duration::from_millis(500),
110            max_taps: 2,
111            hold_thresholds: vec![Duration::from_secs(1), Duration::from_secs(3)],
112            repeat: None,
113            hold_after_tap: HoldAfterTapPolicy::CancelPendingTaps,
114        }
115    }
116}
117
118impl GestureConfig {
119    pub fn validate(&self) -> Result<(), ConfigError> {
120        validate_gesture_config(self, None)
121    }
122}
123
124#[derive(Debug, Clone, PartialEq, Eq)]
125pub struct FrameworkConfig {
126    pub buttons: Vec<ButtonConfig>,
127    pub chords: Vec<ChordConfig>,
128    pub default_gestures: GestureConfig,
129    pub gesture_overrides: HashMap<ControlId, GestureConfig>,
130}
131
132impl FrameworkConfig {
133    pub fn new(buttons: Vec<ButtonConfig>) -> Self {
134        Self {
135            buttons,
136            chords: Vec::new(),
137            default_gestures: GestureConfig::default(),
138            gesture_overrides: HashMap::new(),
139        }
140    }
141
142    pub fn validate(&self) -> Result<(), ConfigError> {
143        let mut key_ids = HashSet::with_capacity(self.buttons.len());
144        for button in &self.buttons {
145            if !key_ids.insert(button.id) {
146                return Err(ConfigError::DuplicateKey(button.id));
147            }
148        }
149
150        validate_gesture_config(&self.default_gestures, None)?;
151        for (&control, config) in &self.gesture_overrides {
152            match control {
153                ControlId::Key(key) if !key_ids.contains(&key) => {
154                    return Err(ConfigError::UnknownKey(key));
155                }
156                ControlId::Chord(chord)
157                    if !self.chords.iter().any(|candidate| candidate.id == chord) =>
158                {
159                    return Err(ConfigError::UnknownChord(chord));
160                }
161                _ => {}
162            }
163            validate_gesture_config(config, Some(control))?;
164        }
165
166        let mut chord_ids = HashSet::with_capacity(self.chords.len());
167        let mut normalized_members = Vec::with_capacity(self.chords.len());
168        for chord in &self.chords {
169            if !chord_ids.insert(chord.id) {
170                return Err(ConfigError::DuplicateChord(chord.id));
171            }
172            if chord.members.len() < 2 {
173                return Err(ConfigError::ChordTooSmall(chord.id));
174            }
175
176            let members: HashSet<_> = chord.members.iter().copied().collect();
177            if members.len() != chord.members.len() {
178                return Err(ConfigError::DuplicateChordMember(chord.id));
179            }
180            if let Some(&unknown) = members.iter().find(|key| !key_ids.contains(key)) {
181                return Err(ConfigError::UnknownChordMember {
182                    chord: chord.id,
183                    key: unknown,
184                });
185            }
186            normalized_members.push((chord.id, members));
187        }
188
189        for (index, (left_id, left)) in normalized_members.iter().enumerate() {
190            for (right_id, right) in normalized_members.iter().skip(index + 1) {
191                if left == right {
192                    return Err(ConfigError::DuplicateChordMembers {
193                        first: *left_id,
194                        second: *right_id,
195                    });
196                }
197                if left.is_subset(right) || right.is_subset(left) {
198                    return Err(ConfigError::SubsetChords {
199                        first: *left_id,
200                        second: *right_id,
201                    });
202                }
203            }
204        }
205
206        Ok(())
207    }
208
209    pub fn gesture_config(&self, control: ControlId) -> &GestureConfig {
210        self.gesture_overrides
211            .get(&control)
212            .unwrap_or(&self.default_gestures)
213    }
214}
215
216pub(crate) fn validate_gesture_config(
217    config: &GestureConfig,
218    control: Option<ControlId>,
219) -> Result<(), ConfigError> {
220    if config.max_taps == 0 {
221        return Err(ConfigError::ZeroMaxTaps(control));
222    }
223
224    if config
225        .hold_thresholds
226        .windows(2)
227        .any(|pair| pair[0] >= pair[1])
228    {
229        return Err(ConfigError::UnorderedHoldThresholds(control));
230    }
231
232    if let Some(repeat) = &config.repeat {
233        if repeat.interval.is_zero() {
234            return Err(ConfigError::ZeroRepeatInterval(control));
235        }
236        let Some(&first_hold) = config.hold_thresholds.first() else {
237            return Err(ConfigError::RepeatWithoutHold(control));
238        };
239        if repeat.starts_after < first_hold {
240            return Err(ConfigError::RepeatBeforeHold(control));
241        }
242    }
243
244    Ok(())
245}
246
247#[derive(Debug, Clone, PartialEq, Eq)]
248pub enum ConfigError {
249    DuplicateKey(KeyId),
250    DuplicateChord(ChordId),
251    UnknownKey(KeyId),
252    UnknownChord(ChordId),
253    ChordTooSmall(ChordId),
254    DuplicateChordMember(ChordId),
255    UnknownChordMember { chord: ChordId, key: KeyId },
256    DuplicateChordMembers { first: ChordId, second: ChordId },
257    SubsetChords { first: ChordId, second: ChordId },
258    ZeroMaxTaps(Option<ControlId>),
259    UnorderedHoldThresholds(Option<ControlId>),
260    ZeroRepeatInterval(Option<ControlId>),
261    RepeatWithoutHold(Option<ControlId>),
262    RepeatBeforeHold(Option<ControlId>),
263}
264
265impl fmt::Display for ConfigError {
266    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
267        match self {
268            Self::DuplicateKey(key) => write!(f, "duplicate button id {key}"),
269            Self::DuplicateChord(chord) => write!(f, "duplicate chord id {chord}"),
270            Self::UnknownKey(key) => write!(f, "unknown button id {key}"),
271            Self::UnknownChord(chord) => write!(f, "unknown chord id {chord}"),
272            Self::ChordTooSmall(chord) => {
273                write!(f, "{chord} must contain at least two buttons")
274            }
275            Self::DuplicateChordMember(chord) => {
276                write!(f, "{chord} contains a duplicate button")
277            }
278            Self::UnknownChordMember { chord, key } => {
279                write!(f, "{chord} references unknown {key}")
280            }
281            Self::DuplicateChordMembers { first, second } => {
282                write!(f, "{first} and {second} contain the same buttons")
283            }
284            Self::SubsetChords { first, second } => {
285                write!(f, "{first} and {second} have an ambiguous subset relation")
286            }
287            Self::ZeroMaxTaps(control) => {
288                write!(f, "gesture config {control:?} has max_taps=0")
289            }
290            Self::UnorderedHoldThresholds(control) => write!(
291                f,
292                "gesture config {control:?} hold thresholds are not strictly increasing"
293            ),
294            Self::ZeroRepeatInterval(control) => {
295                write!(f, "gesture config {control:?} has a zero repeat interval")
296            }
297            Self::RepeatWithoutHold(control) => {
298                write!(f, "gesture config {control:?} enables repeat without hold")
299            }
300            Self::RepeatBeforeHold(control) => write!(
301                f,
302                "gesture config {control:?} starts repeat before the first hold threshold"
303            ),
304        }
305    }
306}
307
308impl Error for ConfigError {}
309
310#[cfg(test)]
311mod tests {
312    use super::*;
313
314    fn button(id: u16) -> ButtonConfig {
315        ButtonConfig::active_low(KeyId(id), Duration::from_millis(20))
316    }
317
318    fn framework() -> FrameworkConfig {
319        FrameworkConfig {
320            buttons: vec![button(1), button(2), button(3)],
321            chords: Vec::new(),
322            default_gestures: GestureConfig::default(),
323            gesture_overrides: HashMap::new(),
324        }
325    }
326
327    #[test]
328    fn valid_default_configuration() {
329        assert_eq!(framework().validate(), Ok(()));
330    }
331
332    #[test]
333    fn rejects_duplicate_buttons() {
334        let mut config = framework();
335        config.buttons.push(button(1));
336        assert_eq!(config.validate(), Err(ConfigError::DuplicateKey(KeyId(1))));
337    }
338
339    #[test]
340    fn rejects_subset_chords() {
341        let mut config = framework();
342        config.chords = vec![
343            ChordConfig {
344                id: ChordId(1),
345                members: vec![KeyId(1), KeyId(2)],
346                window: Duration::from_millis(50),
347                priority: 0,
348                release: ChordReleasePolicy::AnyMember,
349            },
350            ChordConfig {
351                id: ChordId(2),
352                members: vec![KeyId(1), KeyId(2), KeyId(3)],
353                window: Duration::from_millis(50),
354                priority: 1,
355                release: ChordReleasePolicy::AnyMember,
356            },
357        ];
358        assert_eq!(
359            config.validate(),
360            Err(ConfigError::SubsetChords {
361                first: ChordId(1),
362                second: ChordId(2),
363            })
364        );
365    }
366
367    #[test]
368    fn rejects_invalid_repeat() {
369        let mut config = framework();
370        config.default_gestures.repeat = Some(RepeatConfig {
371            starts_after: Duration::from_millis(500),
372            interval: Duration::from_millis(100),
373        });
374        assert_eq!(config.validate(), Err(ConfigError::RepeatBeforeHold(None)));
375    }
376}