Skip to main content

repame_shell/
shortcuts.rs

1use std::cell::RefCell;
2use std::rc::Rc;
3
4use repose_core::input::{Key, Modifiers};
5use repose_core::shortcuts::{self, Action};
6
7pub fn game_shortcut_map(
8    pause: &'static str,
9    restart: &'static str,
10    confirm: &'static str,
11) -> shortcuts::ShortcutMap {
12    shortcuts::ShortcutMap::new()
13        .bind(Key::Escape, Modifiers::default(), action_for(pause))
14        .bind(Key::Character('r'), Modifiers::default(), action_for(restart))
15        .bind(Key::Enter, Modifiers::default(), action_for(confirm))
16}
17
18fn action_for(name: &'static str) -> Action {
19    Action::Custom(name.into())
20}
21
22#[derive(Default)]
23pub struct ShortcutEdges {
24    pub pause: bool,
25    pub restart: bool,
26    pub confirm: bool,
27}
28
29pub type SharedEdges = Rc<RefCell<ShortcutEdges>>;
30
31pub fn shared_edges() -> SharedEdges {
32    Rc::new(RefCell::new(ShortcutEdges::default()))
33}
34
35/// Overwrite the process-global default shortcut map (idempotent:
36/// same bindings every call, safe per frame and across test threads).
37pub fn install_map(map: shortcuts::ShortcutMap) {
38    shortcuts::set_default_map(map);
39}
40/// Install only the action handler into long-lived `edges`.
41/// The map itself is process-global (`install_map`, called alongside);
42/// pushing a scoped map per frame would leak a scope entry per frame
43/// and re-root `resolve_action` ordering.
44pub fn install_handler_into(edges: &SharedEdges, pause: &'static str, restart: &'static str, confirm: &'static str) {
45    let inner = edges.clone();
46    shortcuts::set(Some(Rc::new(move |action| {
47        let mut e = inner.borrow_mut();
48        match action {
49            Action::Custom(key) if key.as_ref() == pause => {
50                e.pause = true;
51                true
52            }
53            Action::Custom(key) if key.as_ref() == restart => {
54                e.restart = true;
55                true
56            }
57            Action::Custom(key) if key.as_ref() == confirm => {
58                e.confirm = true;
59                true
60            }
61            _ => false,
62        }
63    })));
64}
65
66pub fn install_into(
67    edges: &SharedEdges,
68    pause: &'static str,
69    restart: &'static str,
70    confirm: &'static str,
71) {
72    let _ = shortcuts::InstallShortcutMap(game_shortcut_map(pause, restart, confirm));
73    install_handler_into(edges, pause, restart, confirm);
74}
75
76pub fn take(edges: &SharedEdges) -> (bool, bool, bool) {
77    let mut e = edges.borrow_mut();
78    (
79        std::mem::take(&mut e.pause),
80        std::mem::take(&mut e.restart),
81        std::mem::take(&mut e.confirm),
82    )
83}