Skip to main content

gpui_commands/
registry.rs

1use crate::Command;
2use gpui::{App, DummyKeyboardMapper, Global, KeyBinding};
3use std::any::TypeId;
4use std::collections::HashMap;
5
6/// The single source of truth for every command an app supports.
7#[derive(Default)]
8pub struct CommandRegistry {
9    commands: Vec<Command>,
10    by_action_type: HashMap<TypeId, ()>,
11}
12
13impl Global for CommandRegistry {}
14
15impl CommandRegistry {
16    /// Create an empty registry.
17    pub fn new() -> Self {
18        Self::default()
19    }
20
21    /// Register a command.
22    ///
23    /// # Panics
24    ///
25    /// - If the command has no handler.
26    /// - If a command for the same action type is already registered,
27    ///   mirroring GPUI's own duplicate-action convention.
28    #[track_caller]
29    pub fn register(&mut self, command: Command) {
30        assert!(
31            command.handler.is_some(),
32            "command `{}` requires a handler",
33            command.name()
34        );
35        let type_id = command.action().as_any().type_id();
36        assert!(
37            self.by_action_type.insert(type_id, ()).is_none(),
38            "command for action `{}` already registered",
39            command.action().name()
40        );
41        self.commands.push(command);
42    }
43
44    /// All registered commands, in registration order.
45    pub fn commands(&self) -> &[Command] {
46        &self.commands
47    }
48
49    /// Register every command's keybinding with GPUI. Commands without a
50    /// keybinding are skipped. Call this once, after all registrations.
51    ///
52    /// # Panics
53    ///
54    /// If any keybinding string fails to parse.
55    pub fn install_keybindings(&self, cx: &mut App) {
56        let bindings: Vec<KeyBinding> = self
57            .commands
58            .iter()
59            .filter_map(|command| {
60                let binding = command.binding()?;
61                let action = command.action().boxed_clone();
62                Some(
63                    KeyBinding::load(
64                        binding.as_str(),
65                        action,
66                        None,
67                        false,
68                        None,
69                        &DummyKeyboardMapper,
70                    )
71                    .unwrap_or_else(|error| {
72                        panic!(
73                            "invalid keybinding `{}` for command `{}`: {error}",
74                            binding,
75                            command.name()
76                        )
77                    }),
78                )
79            })
80            .collect();
81        cx.bind_keys(bindings);
82    }
83}
84
85#[cfg(test)]
86mod tests {
87    use super::*;
88    use crate::Command;
89    use gpui::actions;
90
91    actions!([Ping, Pong]);
92
93    #[test]
94    fn register_and_introspect() {
95        let mut registry = CommandRegistry::new();
96        registry.register(Command::new("Ping", Ping).handler(|_, _| {}));
97        registry.register(Command::new("Pong", Pong).handler(|_, _| {}));
98        assert_eq!(registry.commands().len(), 2);
99        assert_eq!(registry.commands()[0].name(), "Ping");
100        assert_eq!(registry.commands()[1].category_name(), "General");
101    }
102
103    #[test]
104    #[should_panic(expected = "already registered")]
105    fn duplicate_action_type_panics() {
106        let mut registry = CommandRegistry::new();
107        registry.register(Command::new("Ping", Ping).handler(|_, _| {}));
108        registry.register(Command::new("Ping Again", Ping).handler(|_, _| {}));
109    }
110
111    #[test]
112    #[should_panic(expected = "requires a handler")]
113    fn missing_handler_panics() {
114        let mut registry = CommandRegistry::new();
115        registry.register(Command::new("Ping", Ping));
116    }
117}