quadraui 0.6.1

Cross-platform Rust UI toolkit: write one AppLogic and run it unmodified on TUI, GTK4 (Linux), macOS, and Windows backends
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
//! Ordered, scope-aware key binding table.
//!
//! This type was removed from the public library API. It's kept here as a
//! copy-paste recipe: if an app wants scope-aware key resolution, copy this
//! file directly. If a real consumer shows up, it can be promoted back to
//! `compose::key_map` — the design doesn't need to change, only its address.
//!
//! Tests for this module are in `tests/key_map_recipe.rs` (a `[[test]]` target
//! that includes this file), not in this example's `#[cfg(test)]` block
//! (which is inert under `cargo test --workspace` since `[[example]]` targets
//! default to `test = false`).
//!
//! [`Backend::register_accelerator`](quadraui::Backend::register_accelerator)
//! only resolves `AcceleratorScope::Global` bindings — the backend doesn't
//! know which widget has focus or which app-defined mode is active, so
//! `TuiBackend::apply_accelerators` explicitly skips `Widget`/`Mode`-scoped
//! entries and leaves them as raw `KeyPressed` events.
//!
//! [`KeyMap`] resolves these scoped bindings. Apps declare an ordered table of
//! `(scope, binding, action id)` once; at each `KeyPressed` event they call
//! [`KeyMap::resolve`] with a [`KeyContext`] describing the current
//! focus/mode/blocked state, and get back the one `AcceleratorId` (if any)
//! that should fire.
//!
//! # Ordering = priority
//!
//! Entries are tried in registration order; the first entry whose key +
//! modifiers match **and** whose scope is currently active wins. Register
//! narrow, specific bindings first (e.g. `Widget(palette_id)` → `"palette.close"`)
//! and broad fallbacks after (e.g. `Global` → `"app.blur"`). When the palette
//! has focus the first entry's scope is active and wins; otherwise resolution
//! falls through to the next entry that matches the key.
//!
//! # Relationship to `Accelerator` / `Backend::register_accelerator`
//!
//! `KeyMap` is backend-agnostic and doesn't require registering anything with
//! a `Backend` — it resolves directly against raw `Key` + `Modifiers`, so it
//! works identically whether the native `KeyPressed` event came through
//! unmodified or already had `Global` accelerators peeled off upstream by the
//! backend. [`KeyMap::bind_accelerator`] lets apps build the table straight
//! from the same `Accelerator` values they already declare for
//! `register_accelerator`, so the two paths share one source of truth.

#![allow(dead_code)]

use quadraui::accelerator::{key_to_binding_name, parse_binding};
use quadraui::{
    Accelerator, AcceleratorId, AcceleratorScope, Key, KeyBinding, Modifiers, ParsedBinding,
    WidgetId,
};

/// One resolved row of the table: a scope, its parsed key binding, and
/// the action it fires. Kept private — apps interact with the table
/// through [`KeyMap::bind`] / [`KeyMap::resolve`], never this struct
/// directly.
#[derive(Debug, Clone)]
struct KeyMapEntry {
    scope: AcceleratorScope,
    binding: ParsedBinding,
    action: AcceleratorId,
}

/// An ordered `(AcceleratorScope, ParsedBinding, AcceleratorId)` table.
/// See the module docs for the resolution model.
#[derive(Debug, Clone, Default)]
pub struct KeyMap {
    entries: Vec<KeyMapEntry>,
}

impl KeyMap {
    /// An empty table.
    pub fn new() -> Self {
        Self::default()
    }

    /// Register `binding` at `scope` for `action`. Later calls are lower
    /// priority — see the module docs' "Ordering = priority" section.
    ///
    /// Silently skips unparseable `KeyBinding::Literal` strings, mirroring
    /// `Backend::register_accelerator`'s
    /// contract (an unparseable binding never matches rather than
    /// panicking or erroring).
    pub fn bind(
        &mut self,
        scope: AcceleratorScope,
        binding: KeyBinding,
        action: impl Into<AcceleratorId>,
    ) -> &mut Self {
        if let Some(parsed) = parse_binding(&binding) {
            self.entries.push(KeyMapEntry {
                scope,
                binding: parsed,
                action: action.into(),
            });
        }
        self
    }

    /// Register an already-declared [`Accelerator`] — the same value an
    /// app hands to `Backend::register_accelerator`, so a `Global`-scoped
    /// accelerator and its `KeyMap` entry never drift apart. See the
    /// module docs' "Relationship to `Accelerator`" section.
    pub fn bind_accelerator(&mut self, acc: &Accelerator) -> &mut Self {
        if let Some(parsed) = parse_binding(&acc.binding) {
            self.entries.push(KeyMapEntry {
                scope: acc.scope.clone(),
                binding: parsed,
                action: acc.id.clone(),
            });
        }
        self
    }

    /// Remove every entry bound to `action`, regardless of scope/binding.
    pub fn unbind(&mut self, action: &AcceleratorId) {
        self.entries.retain(|e| &e.action != action);
    }

    /// Number of registered entries.
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// Whether the table has no entries.
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    /// Resolve a native key press to the highest-priority matching action
    /// whose scope is active in `ctx`, or `None` if nothing matches.
    ///
    /// Apps typically call this from their `UiEvent::KeyPressed` arm
    /// before falling back to widget-local handling — a `Some` result
    /// means "dispatch this one action id"; a `None` result means "no
    /// declared binding claims this key, handle it (or ignore it) as
    /// before".
    pub fn resolve(
        &self,
        key: &Key,
        modifiers: Modifiers,
        ctx: &KeyContext,
    ) -> Option<AcceleratorId> {
        let key_name = key_to_binding_name(key);
        self.entries
            .iter()
            .find(|e| {
                e.binding.modifiers == modifiers
                    && e.binding.key == key_name
                    && ctx.scope_active(&e.scope)
            })
            .map(|e| e.action.clone())
    }
}

/// Per-frame state [`KeyMap::resolve`] evaluates a candidate entry's
/// [`AcceleratorScope`] against.
///
/// Cheap to construct fresh on every `KeyPressed` event — it borrows the
/// caller's own focus/mode bookkeeping rather than owning a copy.
#[derive(Debug, Clone, Copy, Default)]
pub struct KeyContext<'a> {
    /// Every [`WidgetId`] that currently "has focus" for the purpose of
    /// `AcceleratorScope::Widget` matching — the focused widget itself
    /// plus any ancestors that should also claim its widget-scoped
    /// bindings (e.g. a modal's own id, so its `Escape` binding fires
    /// no matter which child control inside it is focused). An
    /// `AcceleratorScope::Widget(id)` entry is active whenever `id`
    /// appears anywhere in this slice — order doesn't matter.
    pub focus_chain: &'a [WidgetId],
    /// The app-defined mode string (vim-like apps: `"n"`, `"i"`, `"v"`,
    /// …). `AcceleratorScope::Mode(m)` is active when this equals
    /// `Some(m)`.
    pub mode: Option<&'a str>,
    /// When `true`, `AcceleratorScope::Global` entries never match —
    /// the single flag that replaces the hand-repeated
    /// `!pty_active && !any_blocking_modal_active() && …` guard chain
    /// this type was filed to eliminate. Set it whenever *anything*
    /// should suppress global shortcuts (a blocking modal is open, a
    /// PTY has raw input focus, …); `Widget`/`Mode`-scoped entries are
    /// unaffected since their own scope already gates them precisely.
    pub global_blocked: bool,
}

impl<'a> KeyContext<'a> {
    /// A context with no focus chain, no mode, and `Global` unblocked.
    pub fn new() -> Self {
        Self {
            focus_chain: &[],
            mode: None,
            global_blocked: false,
        }
    }

    /// Set the focus chain (see [`Self::focus_chain`]).
    pub fn with_focus_chain(mut self, chain: &'a [WidgetId]) -> Self {
        self.focus_chain = chain;
        self
    }

    /// Set the active mode string (see [`Self::mode`]).
    pub fn with_mode(mut self, mode: &'a str) -> Self {
        self.mode = Some(mode);
        self
    }

    /// Mark `Global`-scope entries as blocked for this resolution (see
    /// [`Self::global_blocked`]).
    pub fn blocked(mut self) -> Self {
        self.global_blocked = true;
        self
    }

    fn scope_active(&self, scope: &AcceleratorScope) -> bool {
        match scope {
            AcceleratorScope::Global => !self.global_blocked,
            AcceleratorScope::Widget(id) => self.focus_chain.contains(id),
            AcceleratorScope::Mode(m) => self.mode == Some(m.as_str()),
        }
    }
}

// ─── Tests ──────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;

    fn mods_none() -> Modifiers {
        Modifiers::default()
    }

    fn ctrl() -> Modifiers {
        Modifiers {
            ctrl: true,
            ..Modifiers::default()
        }
    }

    #[test]
    fn empty_map_resolves_nothing() {
        let map = KeyMap::new();
        assert!(map.is_empty());
        assert_eq!(
            map.resolve(&Key::Char('p'), ctrl(), &KeyContext::new()),
            None
        );
    }

    #[test]
    fn global_scope_matches_by_default() {
        let mut map = KeyMap::new();
        map.bind(
            AcceleratorScope::Global,
            KeyBinding::Literal("Ctrl+P".into()),
            "palette.open",
        );
        assert_eq!(map.len(), 1);
        let id = map
            .resolve(&Key::Char('p'), ctrl(), &KeyContext::new())
            .unwrap();
        assert_eq!(id.as_str(), "palette.open");
    }

    #[test]
    fn global_scope_blocked_does_not_match() {
        let mut map = KeyMap::new();
        map.bind(
            AcceleratorScope::Global,
            KeyBinding::Literal("Ctrl+P".into()),
            "palette.open",
        );
        let ctx = KeyContext::new().blocked();
        assert_eq!(map.resolve(&Key::Char('p'), ctrl(), &ctx), None);
    }

    #[test]
    fn widget_scope_matches_when_in_focus_chain() {
        let mut map = KeyMap::new();
        let modal_id = WidgetId::new("modal:confirm");
        map.bind(
            AcceleratorScope::Widget(modal_id.clone()),
            KeyBinding::Literal("Escape".into()),
            "modal.close",
        );
        let chain = [WidgetId::new("modal:confirm:input"), modal_id.clone()];
        let ctx = KeyContext::new().with_focus_chain(&chain);
        let id = map
            .resolve(&Key::Named(quadraui::NamedKey::Escape), mods_none(), &ctx)
            .unwrap();
        assert_eq!(id.as_str(), "modal.close");
    }

    #[test]
    fn widget_scope_does_not_match_when_absent_from_focus_chain() {
        let mut map = KeyMap::new();
        map.bind(
            AcceleratorScope::Widget(WidgetId::new("modal:confirm")),
            KeyBinding::Literal("Escape".into()),
            "modal.close",
        );
        let chain = [WidgetId::new("editor:main")];
        let ctx = KeyContext::new().with_focus_chain(&chain);
        assert_eq!(
            map.resolve(&Key::Named(quadraui::NamedKey::Escape), mods_none(), &ctx),
            None
        );
    }

    #[test]
    fn mode_scope_matches_active_mode_only() {
        let mut map = KeyMap::new();
        map.bind(
            AcceleratorScope::Mode("n".into()),
            KeyBinding::Literal("d".into()),
            "vim.delete_line",
        );
        let ctx_normal = KeyContext::new().with_mode("n");
        assert_eq!(
            map.resolve(&Key::Char('d'), mods_none(), &ctx_normal)
                .as_ref()
                .map(AcceleratorId::as_str),
            Some("vim.delete_line")
        );

        let ctx_insert = KeyContext::new().with_mode("i");
        assert_eq!(map.resolve(&Key::Char('d'), mods_none(), &ctx_insert), None);
    }

    #[test]
    fn earlier_binding_wins_when_both_scopes_active() {
        let mut map = KeyMap::new();
        let palette_id = WidgetId::new("palette");
        map.bind(
            AcceleratorScope::Widget(palette_id.clone()),
            KeyBinding::Literal("Escape".into()),
            "palette.close",
        );
        map.bind(
            AcceleratorScope::Global,
            KeyBinding::Literal("Escape".into()),
            "app.blur",
        );

        let chain = [palette_id.clone()];
        let ctx_focused = KeyContext::new().with_focus_chain(&chain);
        assert_eq!(
            map.resolve(
                &Key::Named(quadraui::NamedKey::Escape),
                mods_none(),
                &ctx_focused
            )
            .as_ref()
            .map(AcceleratorId::as_str),
            Some("palette.close")
        );
    }

    #[test]
    fn falls_through_to_next_entry_when_first_scope_inactive() {
        let mut map = KeyMap::new();
        let palette_id = WidgetId::new("palette");
        map.bind(
            AcceleratorScope::Widget(palette_id),
            KeyBinding::Literal("Escape".into()),
            "palette.close",
        );
        map.bind(
            AcceleratorScope::Global,
            KeyBinding::Literal("Escape".into()),
            "app.blur",
        );

        // Palette not focused — falls through to the Global fallback.
        let ctx = KeyContext::new();
        assert_eq!(
            map.resolve(&Key::Named(quadraui::NamedKey::Escape), mods_none(), &ctx)
                .as_ref()
                .map(AcceleratorId::as_str),
            Some("app.blur")
        );
    }

    #[test]
    fn bind_accelerator_shares_scope_and_id() {
        let mut map = KeyMap::new();
        let acc = Accelerator {
            id: AcceleratorId::new("editor.save"),
            binding: KeyBinding::Save,
            scope: AcceleratorScope::Global,
            label: None,
        };
        map.bind_accelerator(&acc);
        let id = map
            .resolve(&Key::Char('s'), ctrl(), &KeyContext::new())
            .unwrap();
        assert_eq!(id, acc.id);
    }

    #[test]
    fn unparseable_literal_is_skipped_silently() {
        let mut map = KeyMap::new();
        map.bind(
            AcceleratorScope::Global,
            KeyBinding::Literal("".into()),
            "noop",
        );
        assert!(map.is_empty());
    }

    #[test]
    fn unbind_removes_all_entries_for_action() {
        let mut map = KeyMap::new();
        map.bind(
            AcceleratorScope::Global,
            KeyBinding::Literal("Ctrl+P".into()),
            "palette.open",
        );
        map.bind(
            AcceleratorScope::Mode("n".into()),
            KeyBinding::Literal("Ctrl+P".into()),
            "palette.open",
        );
        assert_eq!(map.len(), 2);
        map.unbind(&AcceleratorId::new("palette.open"));
        assert!(map.is_empty());
    }

    #[test]
    fn modifier_mismatch_does_not_match() {
        let mut map = KeyMap::new();
        map.bind(
            AcceleratorScope::Global,
            KeyBinding::Literal("Ctrl+P".into()),
            "palette.open",
        );
        assert_eq!(
            map.resolve(&Key::Char('p'), mods_none(), &KeyContext::new()),
            None
        );
    }
}