1use crate::input::ElementId;
2use crate::{ControlInput, LayoutNode, Target, menu::MenuPopup};
3use std::{
4 fmt,
5 str::FromStr,
6 time::{Duration, Instant},
7};
8use xrack_runtime::{ActionKey, ControlAction, Node, RowKey};
9
10const MAX_STROKES: usize = 4;
11const STROKE_TIMEOUT: Duration = Duration::from_secs(1);
12
13#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
14pub struct ShortcutModifiers {
15 pub ctrl: bool,
16 pub alt: bool,
17 pub shift: bool,
18 pub super_key: bool,
19}
20
21#[derive(Clone, Copy, Debug, PartialEq, Eq)]
22pub enum ShortcutKey {
23 Character(char),
24 Function(u8),
25 Escape,
26}
27
28#[derive(Clone, Copy, Debug, PartialEq, Eq)]
29pub struct MenuShortcut {
30 key: ShortcutKey,
31 modifiers: ShortcutModifiers,
32}
33
34impl MenuShortcut {
35 pub(crate) fn is_escape(self) -> bool {
36 self.key == ShortcutKey::Escape
37 }
38
39 pub fn new(key: ShortcutKey, modifiers: ShortcutModifiers) -> Option<Self> {
40 let key = match key {
41 ShortcutKey::Character(key)
42 if key.is_ascii_alphanumeric()
43 && (modifiers.ctrl || modifiers.alt || modifiers.super_key) =>
44 {
45 ShortcutKey::Character(key.to_ascii_uppercase())
46 }
47 ShortcutKey::Function(1..=12) | ShortcutKey::Escape => key,
48 _ => return None,
49 };
50 Some(Self { key, modifiers })
51 }
52}
53
54impl FromStr for MenuShortcut {
55 type Err = ();
56
57 fn from_str(value: &str) -> Result<Self, Self::Err> {
58 let mut parts = value.split('+');
59 let key = parts.next_back().ok_or(())?.trim();
60 let key = if key.eq_ignore_ascii_case("Escape") {
61 ShortcutKey::Escape
62 } else if let Some(function) = key.strip_prefix(['F', 'f']).filter(|_| key.len() > 1) {
63 ShortcutKey::Function(function.parse().map_err(|_| ())?)
64 } else {
65 let mut chars = key.chars();
66 let key = chars.next().ok_or(())?;
67 if chars.next().is_some() {
68 return Err(());
69 }
70 ShortcutKey::Character(key)
71 };
72 let mut modifiers = ShortcutModifiers::default();
73 for modifier in parts {
74 let flag = match modifier.trim().to_ascii_lowercase().as_str() {
75 "ctrl" => &mut modifiers.ctrl,
76 "alt" => &mut modifiers.alt,
77 "shift" => &mut modifiers.shift,
78 "super" => &mut modifiers.super_key,
79 "primary" if cfg!(any(target_os = "macos", target_os = "ios")) => {
80 &mut modifiers.super_key
81 }
82 "primary" => &mut modifiers.ctrl,
83 _ => return Err(()),
84 };
85 if std::mem::replace(flag, true) {
86 return Err(());
87 }
88 }
89 Self::new(key, modifiers).ok_or(())
90 }
91}
92
93impl fmt::Display for MenuShortcut {
94 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
95 if self.modifiers.ctrl {
96 f.write_str("Ctrl+")?;
97 }
98 if self.modifiers.alt {
99 f.write_str(if cfg!(any(target_os = "macos", target_os = "ios")) {
100 "Option+"
101 } else {
102 "Alt+"
103 })?;
104 }
105 if self.modifiers.shift {
106 f.write_str("Shift+")?;
107 }
108 if self.modifiers.super_key {
109 f.write_str(if cfg!(any(target_os = "macos", target_os = "ios")) {
110 "Cmd+"
111 } else {
112 "Super+"
113 })?;
114 }
115 match self.key {
116 ShortcutKey::Character(key) => write!(f, "{key}"),
117 ShortcutKey::Function(key) => write!(f, "F{key}"),
118 ShortcutKey::Escape => f.write_str("Escape"),
119 }
120 }
121}
122
123#[derive(Clone, Debug, PartialEq, Eq)]
125pub enum ShortcutOutcome {
126 Unmatched,
127 Consumed,
128 Activate(ControlInput),
129 Ambiguous(Vec<ControlInput>),
130}
131
132#[derive(Clone, Debug, PartialEq, Eq)]
133pub(crate) struct Binding {
134 keys: Vec<MenuShortcut>,
135 target: ControlInput,
136 element_id: Option<ElementId>,
137 row_key: Option<RowKey>,
138 command: Option<ActionKey>,
139 auto_repeat: bool,
140}
141
142pub(crate) fn bindings(
143 scene: &Node,
144 layout: &LayoutNode,
145 scope: &[usize],
146 popup: Option<&MenuPopup>,
147 focus: Option<&Target>,
148) -> Vec<Binding> {
149 let mut bindings = Vec::new();
150 crate::menu::visit_shortcut_presentations(scene, layout, scope, popup, |node, path| {
151 let action = match node.kind {
152 "Shortcut" => ControlAction::ActivateShortcut,
153 "MenuItem" => ControlAction::ActivateMenuItem,
154 _ => ControlAction::ActivateAction,
155 };
156 if node.boolean("focus-within", false)
157 && !focus.is_some_and(|focus| {
158 let parent = path.split_last().map_or(path, |(_, parent)| parent);
159 focus.path.starts_with(parent) && crate::input::valid(focus, scene, layout)
160 })
161 {
162 return;
163 }
164 let single = if node.properties.contains_key("sequences") {
165 None
166 } else {
167 node.text("sequence").or_else(|| node.text("shortcut"))
168 };
169 let limit = if action == ControlAction::ActivateShortcut {
170 MAX_STROKES
171 } else {
172 1
173 };
174 for value in node
175 .strings("sequences")
176 .iter()
177 .map(String::as_str)
178 .chain(single)
179 {
180 let Ok(keys) = value
181 .split(',')
182 .take(limit + 1)
183 .map(str::parse)
184 .collect::<Result<Vec<_>, _>>()
185 else {
186 continue;
187 };
188 if keys.len() > limit {
189 continue;
190 }
191 bindings.push(Binding {
192 keys,
193 target: ControlInput {
194 path: path.to_vec(),
195 action,
196 },
197 element_id: ElementId::of(node),
198 row_key: scene.row_key_at(path),
199 command: node.action,
200 auto_repeat: node.boolean("auto-repeat", false),
201 });
202 }
203 });
204 bindings
205}
206
207#[derive(Clone, Debug)]
208pub(crate) struct PendingShortcut {
209 bindings: Vec<Binding>,
210 scope: Vec<usize>,
211 matched: usize,
212 expires: Instant,
213}
214
215impl PendingShortcut {
216 pub(crate) fn retain_active(&mut self, scope: &[usize], active: &[Binding]) -> bool {
217 if self.scope != scope || self.expires <= Instant::now() {
218 return false;
219 }
220 self.bindings.retain(|binding| active.contains(binding));
221 !self.bindings.is_empty()
222 }
223}
224
225pub(crate) fn press(
226 pending: &mut Option<PendingShortcut>,
227 active: Vec<Binding>,
228 scope: &[usize],
229 key: MenuShortcut,
230 repeat: bool,
231 now: Instant,
232) -> ShortcutOutcome {
233 let previous = pending
234 .take()
235 .filter(|old| old.expires > now && old.scope == scope);
236 if repeat && previous.is_some() {
237 *pending = previous;
238 return ShortcutOutcome::Consumed;
239 }
240 let mut matched = 1;
241 let mut candidates = Vec::new();
242 if let Some(old) = previous {
243 candidates = old
244 .bindings
245 .into_iter()
246 .filter(|binding| {
247 binding.keys.get(old.matched) == Some(&key) && active.contains(binding)
248 })
249 .collect();
250 if !candidates.is_empty() {
251 matched = old.matched + 1;
252 }
253 }
254 if candidates.is_empty() {
255 candidates = active
256 .into_iter()
257 .filter(|binding| binding.keys.first() == Some(&key))
258 .collect();
259 }
260 let (exact, prefixes): (Vec<_>, Vec<_>) = candidates
261 .into_iter()
262 .partition(|binding| binding.keys.len() == matched);
263 let has_prefix = !prefixes.is_empty();
264 if has_prefix && !repeat {
265 *pending = Some(PendingShortcut {
266 bindings: prefixes,
267 scope: scope.to_vec(),
268 matched,
269 expires: now + STROKE_TIMEOUT,
270 });
271 }
272 resolve(exact, has_prefix, repeat)
273}
274
275pub(crate) fn single_action(bindings: Vec<Binding>, key: MenuShortcut) -> Option<ControlInput> {
276 let (exact, prefixes): (Vec<_>, Vec<_>) = bindings
277 .into_iter()
278 .filter(|binding| binding.keys.first() == Some(&key))
279 .partition(|binding| binding.keys.len() == 1);
280 match resolve(exact, !prefixes.is_empty(), false) {
281 ShortcutOutcome::Activate(action) => Some(action),
282 _ => None,
283 }
284}
285
286fn resolve(exact: Vec<Binding>, has_prefix: bool, repeat: bool) -> ShortcutOutcome {
287 let mut distinct: Vec<Binding> = Vec::new();
288 for binding in exact {
289 if let Some(same) = distinct.iter_mut().find(|other| {
290 binding.target == other.target
291 || binding.command.is_some() && binding.command == other.command
292 }) {
293 if repeat && binding.auto_repeat {
294 *same = binding;
295 }
296 } else {
297 distinct.push(binding);
298 }
299 }
300 match (distinct.len(), has_prefix, repeat) {
301 (0, false, _) => ShortcutOutcome::Unmatched,
302 (0, true, _) => ShortcutOutcome::Consumed,
303 (1, false, _) => {
304 let Some(binding) = distinct.pop() else {
305 return ShortcutOutcome::Unmatched;
306 };
307 if !repeat || binding.auto_repeat && binding.keys.len() == 1 {
308 ShortcutOutcome::Activate(binding.target)
309 } else {
310 ShortcutOutcome::Consumed
311 }
312 }
313 (_, _, true) => ShortcutOutcome::Consumed,
314 _ => ShortcutOutcome::Ambiguous(
315 distinct
316 .into_iter()
317 .filter_map(|binding| {
318 (binding.command.is_none()
319 && binding.target.action == ControlAction::ActivateShortcut)
320 .then_some(ControlInput {
321 path: binding.target.path,
322 action: ControlAction::AmbiguousShortcut,
323 })
324 })
325 .collect(),
326 ),
327 }
328}
329
330#[cfg(test)]
331mod tests {
332 use super::*;
333
334 #[test]
335 fn a_complete_sequence_that_is_also_a_prefix_reports_ambiguity() {
336 let first = "F11".parse().unwrap();
337 let second = "F12".parse().unwrap();
338 let binding = |index, keys| Binding {
339 keys,
340 target: ControlInput {
341 path: vec![index],
342 action: ControlAction::ActivateShortcut,
343 },
344 element_id: None,
345 row_key: None,
346 command: None,
347 auto_repeat: false,
348 };
349 let short = binding(0, vec![first]);
350 let long = binding(1, vec![first, second]);
351 let active = vec![short, long.clone()];
352 let mut pending = None;
353 let now = Instant::now();
354 assert_eq!(
355 press(&mut pending, active.clone(), &[], first, false, now),
356 ShortcutOutcome::Ambiguous(vec![ControlInput {
357 path: vec![0],
358 action: ControlAction::AmbiguousShortcut
359 }]),
360 );
361 assert_eq!(
362 press(&mut pending, active, &[], second, false, now),
363 ShortcutOutcome::Activate(long.target),
364 );
365 }
366}