1use gpui::{Action, App, SharedString, Window};
2
3type CommandHandler = dyn Fn(&mut Window, &mut App);
6
7pub struct Command {
10 pub(crate) name: SharedString,
11 pub(crate) action: Box<dyn Action>,
12 pub(crate) category: SharedString,
13 pub(crate) keybinding: Option<SharedString>,
14 pub(crate) handler: Option<Box<CommandHandler>>,
15}
16
17impl Command {
18 pub fn new(name: impl Into<SharedString>, action: impl Action) -> Self {
21 Self {
22 name: name.into(),
23 action: Box::new(action),
24 category: SharedString::new_static("General"),
25 keybinding: None,
26 handler: None,
27 }
28 }
29
30 pub fn category(mut self, category: impl Into<SharedString>) -> Self {
32 self.category = category.into();
33 self
34 }
35
36 pub fn keybinding(mut self, binding: impl Into<SharedString>) -> Self {
38 self.keybinding = Some(binding.into());
39 self
40 }
41
42 pub fn handler(mut self, f: impl Fn(&mut Window, &mut App) + 'static) -> Self {
44 self.handler = Some(Box::new(f));
45 self
46 }
47
48 pub fn name(&self) -> &SharedString {
50 &self.name
51 }
52
53 pub fn category_name(&self) -> &SharedString {
55 &self.category
56 }
57
58 pub fn binding(&self) -> Option<&SharedString> {
60 self.keybinding.as_ref()
61 }
62
63 pub fn action(&self) -> &dyn Action {
65 self.action.as_ref()
66 }
67
68 pub fn run(&self, window: &mut Window, cx: &mut App) {
70 if let Some(handler) = &self.handler {
71 handler(window, cx);
72 }
73 }
74}
75
76#[cfg(test)]
77mod tests {
78 use super::*;
79 use gpui::actions;
80
81 actions!([SaveFile, ToggleSidebar]);
82
83 #[test]
84 fn builder_defaults() {
85 let command = Command::new("Save File", SaveFile);
86 assert_eq!(command.name(), "Save File");
87 assert_eq!(command.category_name(), "General");
88 assert!(command.binding().is_none());
89 assert_eq!(command.action().name(), "SaveFile");
90 }
91
92 #[test]
93 fn builder_chaining() {
94 let command = Command::new("Toggle Sidebar", ToggleSidebar)
95 .category("View")
96 .keybinding("cmd-b")
97 .handler(|_, _| {});
98 assert_eq!(command.category_name(), "View");
99 assert_eq!(command.binding().unwrap(), "cmd-b");
100 assert!(command.handler.is_some());
101 }
102}