frust-core 0.6.3

Frust's declarative View API, retained Widget tree, box-constraint layout and rebuild/layout/paint pass.
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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
//! Keyboard shortcuts: the [`Chord`] spec and the per-paint declaration table behind
//! [`PaintCtx::register_shortcut`](crate::widget::PaintCtx::register_shortcut).
//!
//! A widget declares a [`ShortcutDecl`] from its own `paint`, exactly like an overlay entry: the
//! root clears the table every paint, so a declarer that stops declaring (or unmounts) stops
//! matching after the next paint, with nothing to unregister. A declaration made while the root
//! paints a floated pod is stamped with that pod's [`OverlayKey`].
//!
//! A `Key` the focus path left unhandled is matched against the last paint's table in tier
//! order — declarations stamped with the topmost interactive overlay, then main-tree
//! [`ShortcutScope::Local`], then [`ShortcutScope::AppGlobal`] — newest declaration first within
//! a tier. While a modal pod is registered only that pod's tier is tried. Each candidate gets an [`InputEvent::Shortcut`](crate::event::InputEvent::Shortcut)
//! broadcast (wrapped in an overlay event for a stamped one); the declarer answers `Handled`, and
//! an unanswered delivery falls through to the next candidate.
//!
//! The thread-locals below are single-threaded RAII brackets, each scoped to one root's pass at a
//! time and safe to re-enter: `SHORTCUT_TABLE` collects a paint pass's declarations and
//! `SHORTCUT_PASS_OPEN` guards it; `CURRENT_OVERLAY` stamps those made while a pod paints;
//! `SHORTCUT_HANDLED` and `KEY_FORWARD`/`KEY_FORWARD_OPEN` bracket one key dispatch.

use std::cell::Cell;
use std::fmt;
use std::rc::Rc;

use crate::event::{Key, KeyEvent, Modifiers, NamedKey, PassBracket};
use crate::overlay::OverlayKey;

thread_local! {
    /// The next [`ShortcutId::next`] value; starts at `1` so `0` is never handed out.
    static NEXT_SHORTCUT_ID: Cell<u64> = const { Cell::new(1) };

    /// Declarations made so far in this thread's open paint pass, in paint order.
    static SHORTCUT_TABLE: Cell<Vec<ShortcutEntry>> = const { Cell::new(Vec::new()) };

    static SHORTCUT_PASS_OPEN: Cell<bool> = const { Cell::new(false) };

    /// The floated pod the root is painting, stamped onto every declaration it makes.
    static CURRENT_OVERLAY: Cell<Option<OverlayKey>> = const { Cell::new(None) };

    /// Raised when a widget answers a shortcut delivery `Handled` (containers drop the result).
    static SHORTCUT_HANDLED: Cell<bool> = const { Cell::new(false) };

    /// The pod this event pass asked declined keys be forwarded to.
    static KEY_FORWARD: Cell<Option<OverlayKey>> = const { Cell::new(None) };

    static KEY_FORWARD_OPEN: Cell<bool> = const { Cell::new(false) };
}

/// Whether `Mod` means Command (Apple targets) or Ctrl (everything else, `wasm32` included).
const MOD_IS_META: bool = cfg!(any(target_os = "macos", target_os = "ios"));

/// A shortcut's identity, owned by its declarer and quoted back by its delivery.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct ShortcutId(u64);

impl ShortcutId {
    /// Allocate an id unique on this thread. Call once when the declarer is built.
    pub fn next() -> Self {
        ShortcutId(NEXT_SHORTCUT_ID.with(|next| {
            let id = next.get();
            next.set(id.wrapping_add(1));
            id
        }))
    }

    /// The raw integer, for map keys; allocation order is not a contract.
    pub fn value(self) -> u64 {
        self.0
    }
}

/// Which tier a main-tree declaration joins; an overlay-stamped one is always tried first.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ShortcutScope {
    /// Tried before every app-global declaration.
    Local,
    /// The last tier: whatever no overlay or local declaration answered.
    AppGlobal,
}

/// A key plus the exact modifier set it must be pressed with.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Chord {
    /// A character key is stored lowercased and matched case-insensitively.
    pub key: Key,
    pub mods: Modifiers,
}

/// Why [`Chord::parse`] refused a spec.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ChordParseError {
    /// The spec was empty or whitespace.
    Empty,
    /// A token that is neither a modifier nor a key name.
    UnknownToken(String),
    /// A key the input vocabulary cannot deliver. Reserved: every key name the parser knows,
    /// function keys `F1`..`F24` included, is deliverable, so nothing produces it today.
    UnsupportedKey(String),
    /// Only modifiers, or an empty token between two `+`.
    MissingKey,
    /// More than one non-modifier token.
    MultipleKeys,
}

impl fmt::Display for ChordParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ChordParseError::Empty => f.write_str("empty chord"),
            ChordParseError::UnknownToken(token) => write!(f, "unknown chord token `{token}`"),
            ChordParseError::UnsupportedKey(token) => {
                write!(f, "key `{token}` is not in the input vocabulary")
            }
            ChordParseError::MissingKey => f.write_str("chord names no key"),
            ChordParseError::MultipleKeys => f.write_str("chord names more than one key"),
        }
    }
}

impl std::error::Error for ChordParseError {}

impl Chord {
    /// A chord from its parts; a character key is lowercased so it matches either case, and a
    /// Shift-insensitive symbol key (see [`Chord::matches`]) drops `mods.shift`.
    pub fn new(key: Key, mods: Modifiers) -> Self {
        let key = match key {
            Key::Character(text) => Key::Character(text.to_lowercase()),
            named => named,
        };
        let mut mods = mods;
        if shift_insensitive(&key) {
            mods.shift = false;
        }
        Chord { key, mods }
    }

    /// Parse `"Mod+K"`, `"Shift+Tab"`, `"Ctrl+Shift+P"`, `"1"`, `"F2"`: `+`-separated, case-insensitive
    /// modifiers then one key. `Mod` is Command on macOS/iOS and Ctrl elsewhere, chosen at compile
    /// time, so a web build running on a Mac maps it to Ctrl. A symbol key (`+`, `?`, `!`) ignores
    /// Shift, so `"Shift+?"` parses as `"?"`; spell `Shift+1` as `!`.
    pub fn parse(spec: &str) -> Result<Chord, ChordParseError> {
        let spec = spec.trim();
        if spec.is_empty() {
            return Err(ChordParseError::Empty);
        }
        // A trailing `++` names the plus key itself.
        let (head, plus) = match spec.strip_suffix("++") {
            Some(head) => (head, true),
            None if spec == "+" => ("", true),
            None => (spec, false),
        };
        let mut mods = Modifiers::default();
        let mut key = plus.then(|| Key::Character("+".to_string()));
        let tokens = (!head.is_empty()).then(|| head.split('+'));
        for token in tokens.into_iter().flatten() {
            let token = token.trim();
            if token.is_empty() {
                return Err(ChordParseError::MissingKey);
            }
            if apply_modifier(&mut mods, token) {
                continue;
            }
            let parsed = parse_key(token)?;
            if key.replace(parsed).is_some() {
                return Err(ChordParseError::MultipleKeys);
            }
        }
        let key = key.ok_or(ChordParseError::MissingKey)?;
        Ok(Chord::new(key, mods))
    }

    /// Whether `event` presses this chord: the same key (characters case-insensitively) and
    /// exactly the same modifiers. A symbol key (a character that is neither alphanumeric nor
    /// whitespace) ignores `event.modifiers.shift`, because shells report Shift for the keys
    /// that need it; ctrl, alt and meta still compare. An auto-repeat matches like a fresh press.
    pub fn matches(&self, event: &KeyEvent) -> bool {
        let mut held = event.modifiers;
        if shift_insensitive(&self.key) {
            held.shift = false;
        }
        if held != self.mods {
            return false;
        }
        match (&self.key, &event.key) {
            (Key::Named(want), Key::Named(got)) => want == got,
            (Key::Character(want), Key::Character(got)) => *want == got.to_lowercase(),
            _ => false,
        }
    }

    /// The chord as a hint surface shows it, by `Mod`'s compile-time rule: `"⌘K"`, `"⇧⌘P"` on
    /// macOS/iOS (symbols in ⌃⌥⇧⌘ order, unseparated), `"Ctrl+K"`, `"Ctrl+Shift+P"` elsewhere.
    pub fn display(&self) -> String {
        self.display_for(MOD_IS_META)
    }

    fn display_for(&self, apple: bool) -> String {
        let m = self.mods;
        let key = key_label(&self.key, apple);
        let held = if apple {
            [(m.ctrl, "⌃"), (m.alt, "⌥"), (m.shift, "⇧"), (m.meta, "⌘")]
        } else {
            [
                (m.ctrl, "Ctrl"),
                (m.alt, "Alt"),
                (m.shift, "Shift"),
                (m.meta, "Super"),
            ]
        };
        let mut parts: Vec<&str> = held.iter().filter(|(on, _)| *on).map(|(_, n)| *n).collect();
        parts.push(&key);
        parts.join(if apple { "" } else { "+" })
    }
}

/// Whether `key` is a symbol character whose Shift state a chord ignores.
fn shift_insensitive(key: &Key) -> bool {
    match key {
        Key::Character(text) => {
            !text.is_empty()
                && text
                    .chars()
                    .all(|c| !c.is_alphanumeric() && !c.is_whitespace())
        }
        Key::Named(_) => false,
    }
}

/// How [`Chord::display`] names `key`: characters uppercased, Apple's key symbols when `apple`.
fn key_label(key: &Key, apple: bool) -> String {
    let named = match key {
        Key::Character(text) if text == " " => "Space",
        Key::Character(text) => return text.to_uppercase(),
        Key::Named(named) => match (named, apple) {
            (NamedKey::Enter, true) => "↩",
            (NamedKey::Enter, false) => "Enter",
            (NamedKey::Backspace, true) => "⌫",
            (NamedKey::Backspace, false) => "Backspace",
            (NamedKey::Delete, true) => "⌦",
            (NamedKey::Delete, false) => "Delete",
            (NamedKey::Escape, true) => "⎋",
            (NamedKey::Escape, false) => "Esc",
            (NamedKey::Tab, true) => "⇥",
            (NamedKey::Tab, false) => "Tab",
            (NamedKey::ArrowLeft, _) => "←",
            (NamedKey::ArrowRight, _) => "→",
            (NamedKey::ArrowUp, _) => "↑",
            (NamedKey::ArrowDown, _) => "↓",
            (NamedKey::Home, _) => "Home",
            (NamedKey::End, _) => "End",
            (NamedKey::Insert, _) => "Insert",
            (NamedKey::Copy, _) => "Copy",
            (NamedKey::Cut, _) => "Cut",
            (NamedKey::Paste, _) => "Paste",
            (
                NamedKey::F1
                | NamedKey::F2
                | NamedKey::F3
                | NamedKey::F4
                | NamedKey::F5
                | NamedKey::F6
                | NamedKey::F7
                | NamedKey::F8
                | NamedKey::F9
                | NamedKey::F10
                | NamedKey::F11
                | NamedKey::F12
                | NamedKey::F13
                | NamedKey::F14
                | NamedKey::F15
                | NamedKey::F16
                | NamedKey::F17
                | NamedKey::F18
                | NamedKey::F19
                | NamedKey::F20
                | NamedKey::F21
                | NamedKey::F22
                | NamedKey::F23
                | NamedKey::F24,
                _,
            ) => return format!("F{}", named.function_number().unwrap_or(0)),
        },
    };
    named.to_string()
}

/// Set the modifier `token` names and return `true`, or `false` when it names none.
fn apply_modifier(mods: &mut Modifiers, token: &str) -> bool {
    match token.to_ascii_lowercase().as_str() {
        "mod" if MOD_IS_META => mods.meta = true,
        "mod" => mods.ctrl = true,
        "ctrl" | "control" => mods.ctrl = true,
        "shift" => mods.shift = true,
        "alt" | "option" | "opt" => mods.alt = true,
        "meta" | "cmd" | "command" | "super" | "win" => mods.meta = true,
        _ => return false,
    }
    true
}

/// The key one non-modifier token names.
fn parse_key(token: &str) -> Result<Key, ChordParseError> {
    if token.chars().count() == 1 {
        return Ok(Key::Character(token.to_lowercase()));
    }
    let lower = token.to_ascii_lowercase();
    let named = match lower.as_str() {
        "enter" | "return" => NamedKey::Enter,
        "backspace" => NamedKey::Backspace,
        "delete" | "del" => NamedKey::Delete,
        "left" | "arrowleft" => NamedKey::ArrowLeft,
        "right" | "arrowright" => NamedKey::ArrowRight,
        "up" | "arrowup" => NamedKey::ArrowUp,
        "down" | "arrowdown" => NamedKey::ArrowDown,
        "home" => NamedKey::Home,
        "end" => NamedKey::End,
        "escape" | "esc" => NamedKey::Escape,
        "tab" => NamedKey::Tab,
        "insert" | "ins" => NamedKey::Insert,
        "copy" => NamedKey::Copy,
        "cut" => NamedKey::Cut,
        "paste" => NamedKey::Paste,
        "space" => return Ok(Key::Character(" ".to_string())),
        _ => match function_key(&lower) {
            Some(named) => named,
            None => return Err(ChordParseError::UnknownToken(token.to_string())),
        },
    };
    Ok(Key::Named(named))
}

/// `f1`..`f24` (already lowercased) as a function key.
fn function_key(lower: &str) -> Option<NamedKey> {
    let digits = lower.strip_prefix('f')?;
    if !digits.bytes().all(|b| b.is_ascii_digit()) {
        return None;
    }
    NamedKey::function(digits.parse::<u8>().ok()?)
}

/// One shortcut a widget declares for the paint pass in progress.
#[derive(Clone, Debug, PartialEq)]
pub struct ShortcutDecl {
    pub id: ShortcutId,
    pub chord: Chord,
    /// What a hint surface shows for it.
    pub label: String,
    pub scope: ShortcutScope,
}

/// One declaration as a palette or help overlay lists it
/// ([`RenderRoot::shortcut_hints`](crate::app::RenderRoot::shortcut_hints)).
#[derive(Clone, Debug, PartialEq)]
pub struct ShortcutHint {
    pub chord: Chord,
    pub label: String,
    pub scope: ShortcutScope,
}

/// A declaration as the root keeps it: stamped with the floated pod that declared it, if any.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct ShortcutEntry {
    pub(crate) decl: ShortcutDecl,
    pub(crate) overlay: Option<OverlayKey>,
}

/// The [`PassBracket`] around one declaration pass: enter clears, `take` drains.
pub(crate) struct ShortcutPaintPass(PassBracket<Vec<ShortcutEntry>>);

impl ShortcutPaintPass {
    pub(crate) fn enter() -> Self {
        ShortcutPaintPass(PassBracket::enter(&SHORTCUT_TABLE, &SHORTCUT_PASS_OPEN))
    }

    pub(crate) fn take(&self) -> Vec<ShortcutEntry> {
        self.0.take()
    }
}

/// Record `decl` in this thread's open pass, stamped with the pod being painted.
pub(crate) fn register(decl: ShortcutDecl) {
    let overlay = CURRENT_OVERLAY.with(Cell::get);
    SHORTCUT_TABLE.with(|table| {
        let mut entries = table.take();
        entries.push(ShortcutEntry { decl, overlay });
        table.set(entries);
    });
}

/// Stamps declarations with `key` while held; restores the enclosing stamp on drop.
pub(crate) struct OverlayStamp(Option<OverlayKey>);

impl OverlayStamp {
    pub(crate) fn enter(key: OverlayKey) -> Self {
        OverlayStamp(CURRENT_OVERLAY.with(|slot| slot.replace(Some(key))))
    }
}

impl Drop for OverlayStamp {
    fn drop(&mut self) {
        CURRENT_OVERLAY.with(|slot| slot.set(self.0));
    }
}

/// Note that a widget answered a shortcut delivery `Handled` (behind `ChildPod`'s dispatch).
pub(crate) fn note_handled() {
    SHORTCUT_HANDLED.with(|flag| flag.set(true));
}

/// Brackets one delivery's handled flag: enter lowers it, drop restores the enclosing value.
pub(crate) struct DeliveryProbe(bool);

impl DeliveryProbe {
    pub(crate) fn enter() -> Self {
        DeliveryProbe(SHORTCUT_HANDLED.with(|flag| flag.replace(false)))
    }

    /// Whether a widget answered this delivery.
    pub(crate) fn handled(&self) -> bool {
        SHORTCUT_HANDLED.with(Cell::get)
    }
}

impl Drop for DeliveryProbe {
    fn drop(&mut self) {
        SHORTCUT_HANDLED.with(|flag| flag.set(self.0));
    }
}

/// Record a forward request (behind `EventCtx::forward_declined_keys_to`); last writer wins.
pub(crate) fn request_key_forward(key: OverlayKey) {
    KEY_FORWARD.with(|slot| slot.set(Some(key)));
}

/// The [`PassBracket`] around one event pass's forward request: enter clears, `take` drains.
pub(crate) struct KeyForwardPass(PassBracket<Option<OverlayKey>>);

impl KeyForwardPass {
    pub(crate) fn enter() -> Self {
        KeyForwardPass(PassBracket::enter(&KEY_FORWARD, &KEY_FORWARD_OPEN))
    }

    pub(crate) fn take(&self) -> Option<OverlayKey> {
        self.0.take()
    }
}

/// The last paint's declarations, in paint order: the snapshot `RenderRoot` matches keys against.
#[derive(Clone, Debug, Default)]
pub(crate) struct ShortcutTable {
    entries: Vec<ShortcutEntry>,
}

impl ShortcutTable {
    pub(crate) fn new(entries: Vec<ShortcutEntry>) -> Self {
        Self { entries }
    }

    #[cfg(test)]
    pub(crate) fn entries(&self) -> &[ShortcutEntry] {
        &self.entries
    }

    /// Every declaration `filter` keeps, reachable or not, as hints in paint order.
    pub(crate) fn hints(&self, mut filter: impl FnMut(&ShortcutHint) -> bool) -> Vec<ShortcutHint> {
        let hints = self.entries.iter().map(|e| ShortcutHint {
            chord: e.decl.chord.clone(),
            label: e.decl.label.clone(),
            scope: e.decl.scope,
        });
        hints.filter(|hint| filter(hint)).collect()
    }

    /// Every declaration as a shared snapshot, which the owning root hands to its contexts.
    pub(crate) fn publish(&self) -> Rc<[ShortcutHint]> {
        self.hints(|_| true).into()
    }

    /// The declarations `event` presses, as `(id, overlay stamp)` in delivery order: the
    /// `top_overlay` pod's, then (unless `masked`, a modal pod's mask) main-tree `Local`, then
    /// `AppGlobal`, newest first in each. Any other floated pod's declarations are left out.
    pub(crate) fn candidates(
        &self,
        event: &KeyEvent,
        top_overlay: Option<OverlayKey>,
        masked: bool,
    ) -> Vec<(ShortcutId, Option<OverlayKey>)> {
        let tiers: [&dyn Fn(&ShortcutEntry) -> bool; 3] = [
            &|e| e.overlay.is_some() && e.overlay == top_overlay,
            &|e| e.overlay.is_none() && e.decl.scope == ShortcutScope::Local,
            &|e| e.overlay.is_none() && e.decl.scope == ShortcutScope::AppGlobal,
        ];
        let mut out = Vec::new();
        for in_tier in &tiers[..if masked { 1 } else { 3 }] {
            let tier: Vec<_> = self
                .entries
                .iter()
                .rev()
                .filter(|e| in_tier(e) && e.decl.chord.matches(event))
                .map(|e| (e.decl.id, e.overlay))
                .collect();
            #[cfg(debug_assertions)]
            if tier.len() > 1 {
                log::warn!(
                    "frust-core: {} shortcuts in one tier match {:?}; the last declared wins",
                    tier.len(),
                    event.key
                );
            }
            out.extend(tier);
        }
        out
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::widget::PaintCtx;
    use kurbo::{Point, Size};

    fn mods(shift: bool, ctrl: bool, alt: bool, meta: bool) -> Modifiers {
        Modifiers {
            shift,
            ctrl,
            alt,
            meta,
        }
    }

    fn press(key: Key, modifiers: Modifiers) -> KeyEvent {
        KeyEvent {
            key,
            modifiers,
            repeat: false,
        }
    }

    fn character(text: &str) -> Key {
        Key::Character(text.to_string())
    }

    fn decl(chord: &str, scope: ShortcutScope) -> ShortcutDecl {
        ShortcutDecl {
            id: ShortcutId::next(),
            chord: Chord::parse(chord).expect("valid chord"),
            label: chord.to_string(),
            scope,
        }
    }

    #[test]
    fn mod_maps_to_meta_on_apple_targets_and_ctrl_elsewhere() {
        let chord = Chord::parse("Mod+K").unwrap();
        let apple = cfg!(any(target_os = "macos", target_os = "ios"));
        assert_eq!(chord.mods, mods(false, !apple, false, apple));
        assert_eq!(chord.key, character("k"));
    }

    #[test]
    fn parses_named_keys_modifier_stacks_and_bare_characters() {
        assert_eq!(
            Chord::parse("Shift+Tab").unwrap(),
            Chord::new(Key::Named(NamedKey::Tab), mods(true, false, false, false))
        );
        assert_eq!(
            Chord::parse("Ctrl+Shift+P").unwrap(),
            Chord::new(character("p"), mods(true, true, false, false))
        );
        assert_eq!(
            Chord::parse("1").unwrap(),
            Chord::new(character("1"), Modifiers::default())
        );
        assert_eq!(
            Chord::parse(" cmd + alt + Esc ").unwrap(),
            Chord::new(Key::Named(NamedKey::Escape), mods(false, false, true, true))
        );
        assert_eq!(
            Chord::parse("Ctrl++").unwrap(),
            Chord::new(character("+"), mods(false, true, false, false))
        );
        assert_eq!(Chord::parse("Space").unwrap().key, character(" "));
    }

    #[test]
    fn function_keys_parse_case_blind_and_display_without_apple_symbols() {
        let f2 = Chord::new(Key::Named(NamedKey::F2), Modifiers::default());
        assert_eq!(Chord::parse("F2"), Ok(f2));
        assert_eq!(Chord::parse("f24").unwrap().key, Key::Named(NamedKey::F24));
        assert_eq!(
            Chord::parse("shift+f5").unwrap(),
            Chord::new(Key::Named(NamedKey::F5), mods(true, false, false, false))
        );
        let ctrl = Chord::parse("Ctrl+F12").unwrap();
        assert_eq!(ctrl.key, Key::Named(NamedKey::F12));
        assert!(ctrl.mods.ctrl);
        let key = Key::Named(NamedKey::F2);
        let cmd_f2 = Chord::new(key.clone(), mods(false, false, false, true));
        assert_eq!(cmd_f2.display_for(true), "⌘F2");
        let ctrl_f2 = Chord::new(key, mods(false, true, false, false));
        assert_eq!(ctrl_f2.display_for(false), "Ctrl+F2");
    }

    #[test]
    fn unknown_tokens_and_malformed_specs_are_typed_errors() {
        assert_eq!(
            Chord::parse("Hyper+K"),
            Err(ChordParseError::UnknownToken("Hyper".to_string()))
        );
        assert_eq!(
            Chord::parse("Ctrl+Banana"),
            Err(ChordParseError::UnknownToken("Banana".to_string()))
        );
        assert_eq!(
            Chord::parse("F0"),
            Err(ChordParseError::UnknownToken("F0".to_string()))
        );
        assert_eq!(
            Chord::parse("F25"),
            Err(ChordParseError::UnknownToken("F25".to_string()))
        );
        assert_eq!(Chord::parse("F+1"), Err(ChordParseError::MultipleKeys));
        assert_eq!(Chord::parse(""), Err(ChordParseError::Empty));
        assert_eq!(Chord::parse("Shift"), Err(ChordParseError::MissingKey));
        assert_eq!(Chord::parse("Ctrl+"), Err(ChordParseError::MissingKey));
        assert_eq!(Chord::parse("K+J"), Err(ChordParseError::MultipleKeys));
        let message = Chord::parse("Hyper+K").unwrap_err().to_string();
        assert!(message.contains("Hyper"), "{message}");
    }

    #[test]
    fn matching_is_exact_on_modifiers_case_blind_on_characters_and_ignores_repeat() {
        let chord = Chord::parse("Ctrl+K").unwrap();
        let ctrl = mods(false, true, false, false);
        assert!(chord.matches(&press(character("k"), ctrl)));
        assert!(chord.matches(&press(character("K"), ctrl)));
        let mut held = press(character("k"), ctrl);
        held.repeat = true;
        assert!(chord.matches(&held), "an auto-repeat matches too");
        assert!(!chord.matches(&press(character("k"), Modifiers::default())));
        assert!(!chord.matches(&press(character("k"), mods(true, true, false, false))));
        assert!(!chord.matches(&press(character("j"), ctrl)));
        assert!(!chord.matches(&press(Key::Named(NamedKey::Tab), ctrl)));
    }

    #[test]
    fn display_follows_the_platform_rule() {
        let chord = |spec: &str| Chord::parse(spec).unwrap();
        assert_eq!(chord("Ctrl+K").display_for(false), "Ctrl+K");
        assert_eq!(chord("Ctrl+K").display_for(true), "⌃K");
        assert_eq!(chord("Meta+Shift+P").display_for(true), "⇧⌘P");
        assert_eq!(chord("Meta+Shift+P").display_for(false), "Shift+Super+P");
        assert_eq!(chord("Alt+Ctrl+Space").display_for(false), "Ctrl+Alt+Space");
        assert_eq!(chord("Shift+Tab").display_for(false), "Shift+Tab");
        assert_eq!(chord("Shift+Tab").display_for(true), "⇧⇥");
        assert_eq!(chord("Esc").display_for(false), "Esc");
        assert_eq!(chord("Cmd+Enter").display_for(true), "⌘↩");
        assert_eq!(chord("Cmd+Enter").display_for(false), "Super+Enter");
        assert_eq!(chord("1").display(), "1");
        let apple = cfg!(any(target_os = "macos", target_os = "ios"));
        let expected = if apple { "⌘K" } else { "Ctrl+K" };
        assert_eq!(chord("Mod+K").display(), expected);
    }

    #[test]
    fn publish_snapshots_the_table_as_one_shared_rc() {
        let table = ShortcutTable::new(vec![
            ShortcutEntry {
                decl: decl("Mod+K", ShortcutScope::AppGlobal),
                overlay: None,
            },
            ShortcutEntry {
                decl: decl("Esc", ShortcutScope::Local),
                overlay: Some(OverlayKey::next()),
            },
        ]);
        let first = table.publish();
        let labels: Vec<_> = first.iter().map(|h| h.label.as_str()).collect();
        assert_eq!(labels, ["Mod+K", "Esc"]);
        assert!(ShortcutTable::default().publish().is_empty());
        assert_eq!(first.len(), 2, "a held snapshot is unaffected");
    }

    #[test]
    fn symbol_chords_ignore_shift_and_the_rest_stay_exact() {
        let (ctrl, shift) = (
            mods(false, true, false, false),
            mods(true, false, false, false),
        );
        let both = mods(true, true, false, false);
        let plus = Chord::parse("Ctrl++").unwrap();
        assert!(plus.matches(&press(character("+"), both)));
        assert!(plus.matches(&press(character("+"), ctrl)));
        assert!(
            !plus.matches(&press(character("+"), shift)),
            "ctrl still counts"
        );
        let query = Chord::parse("?").unwrap();
        assert!(query.matches(&press(character("?"), shift)));
        assert!(query.matches(&press(character("?"), Modifiers::default())));
        assert_eq!(Chord::parse("Shift+?").unwrap(), query);
        assert_eq!(query.display_for(false), "?");
        let space = Chord::parse("Shift+Space").unwrap();
        assert!(!space.matches(&press(character(" "), Modifiers::default())));
        assert!(space.matches(&press(character(" "), shift)));
        let digit = Chord::parse("1").unwrap();
        assert!(!digit.matches(&press(character("1"), shift)));
        let palette = Chord::parse("Ctrl+Shift+P").unwrap();
        assert!(!palette.matches(&press(character("p"), ctrl)));
        assert!(palette.matches(&press(character("P"), both)));
    }

    #[test]
    fn hints_list_every_declaration_in_paint_order_through_the_filter() {
        let (global, local, floated) = (
            decl("Mod+K", ShortcutScope::AppGlobal),
            decl("Mod+B", ShortcutScope::Local),
            decl("Esc", ShortcutScope::Local),
        );
        let table = ShortcutTable::new(vec![
            ShortcutEntry {
                decl: global.clone(),
                overlay: None,
            },
            ShortcutEntry {
                decl: local.clone(),
                overlay: None,
            },
            ShortcutEntry {
                decl: floated.clone(),
                overlay: Some(OverlayKey::next()),
            },
        ]);
        let all = table.hints(|_| true);
        let labels: Vec<_> = all.iter().map(|h| h.label.as_str()).collect();
        assert_eq!(labels, ["Mod+K", "Mod+B", "Esc"]);
        assert_eq!(
            all[0],
            ShortcutHint {
                chord: global.chord,
                label: global.label,
                scope: ShortcutScope::AppGlobal,
            }
        );
        let local_only = table.hints(|h| h.scope == ShortcutScope::Local);
        assert_eq!(local_only.len(), 2);
        assert!(ShortcutTable::default().hints(|_| true).is_empty());
    }

    #[test]
    fn candidates_follow_tier_order_newest_first() {
        let (top, other) = (OverlayKey::next(), OverlayKey::next());
        let global = decl("Ctrl+K", ShortcutScope::AppGlobal);
        let local_old = decl("Ctrl+K", ShortcutScope::Local);
        let local_new = decl("Ctrl+K", ShortcutScope::Local);
        let in_top = decl("Ctrl+K", ShortcutScope::AppGlobal);
        let in_other = decl("Ctrl+K", ShortcutScope::Local);
        let unrelated = decl("Ctrl+J", ShortcutScope::Local);
        let stamped = |d: &ShortcutDecl, overlay| ShortcutEntry {
            decl: d.clone(),
            overlay,
        };
        let table = ShortcutTable::new(vec![
            stamped(&global, None),
            stamped(&local_old, None),
            stamped(&in_top, Some(top)),
            stamped(&local_new, None),
            stamped(&in_other, Some(other)),
            stamped(&unrelated, None),
        ]);
        let event = press(character("k"), mods(false, true, false, false));
        assert_eq!(
            table.candidates(&event, Some(top), false),
            vec![
                (in_top.id, Some(top)),
                (local_new.id, None),
                (local_old.id, None),
                (global.id, None),
            ],
            "overlay tier, then Local (last declared first), then AppGlobal"
        );
        assert_eq!(
            table.candidates(&event, None, false).len(),
            3,
            "with no interactive pod on top, no stamped declaration is reachable"
        );
        assert_eq!(
            table.candidates(&event, Some(top), true),
            vec![(in_top.id, Some(top))],
            "a modal pod masks both main-tree tiers"
        );
    }

    #[test]
    fn the_table_is_pass_scoped_and_stamps_the_pod_being_painted() {
        let pass = ShortcutPaintPass::enter();
        let (plain, floated) = (
            decl("1", ShortcutScope::Local),
            decl("2", ShortcutScope::Local),
        );
        let key = OverlayKey::next();
        register(plain.clone());
        {
            let _stamp = OverlayStamp::enter(key);
            register(floated.clone());
        }
        let drained = pass.take();
        assert_eq!(
            drained.iter().map(|e| e.overlay).collect::<Vec<_>>(),
            vec![None, Some(key)]
        );
        assert!(pass.take().is_empty(), "the drain empties the table");
        drop(pass);
        register(plain);
        let next = ShortcutPaintPass::enter();
        assert!(next.take().is_empty(), "a stray declaration never leaks in");
    }

    #[test]
    fn declaring_counts_as_a_paint_publication() {
        let _pass = ShortcutPaintPass::enter();
        let mut ctx = PaintCtx::new(Point::ZERO, Size::new(10.0, 10.0));
        assert_eq!(ctx.paint_publications(), 0);
        ctx.register_shortcut(decl("Mod+S", ShortcutScope::AppGlobal));
        assert_eq!(
            ctx.paint_publications(),
            1,
            "a retained boundary must refuse to replay a declaring body"
        );
    }

    #[test]
    fn a_forward_request_is_pass_scoped_and_nests() {
        let (outer_key, inner_key) = (OverlayKey::next(), OverlayKey::next());
        let outer = KeyForwardPass::enter();
        request_key_forward(outer_key);
        {
            let inner = KeyForwardPass::enter();
            assert_eq!(inner.take(), None, "a nested pass starts empty");
            request_key_forward(inner_key);
            assert_eq!(inner.take(), Some(inner_key));
        }
        assert_eq!(
            outer.take(),
            Some(outer_key),
            "and hands the enclosing request back"
        );
        drop(outer);
        request_key_forward(inner_key);
        assert_eq!(
            KeyForwardPass::enter().take(),
            None,
            "a stray request never leaks in"
        );
    }

    #[test]
    fn a_delivery_probe_brackets_the_handled_flag() {
        let outer = DeliveryProbe::enter();
        note_handled();
        {
            let inner = DeliveryProbe::enter();
            assert!(!inner.handled(), "a nested delivery starts unanswered");
        }
        assert!(outer.handled(), "and hands the enclosing answer back");
        drop(outer);
        assert!(!DeliveryProbe::enter().handled());
    }
}