1use std::cell::RefCell;
10use std::rc::Rc;
11
12use gpui_kit::assets::IconName;
13use gpui_kit::component::button::{Button, ButtonVariants as _};
14use gpui_kit::component::menu::{DropdownMenu as _, PopupMenu, PopupMenuItem};
15use gpui_kit::component::{Icon, Sizable as _, v_flex};
16use gpui_kit::{
17 Action, App, Context, IntoElement, KeyBinding, ParentElement as _, SharedString, Styled as _, Window, div,
18};
19use kitchen_ui::theme::color;
20use schemars::JsonSchema;
21use serde::de::DeserializeOwned;
22use serde_json::Value;
23
24pub type RunFn = Rc<dyn Fn(Value, &mut Window, &mut App) -> Result<Value, String>>;
27pub type EnabledFn = Rc<dyn Fn(&App) -> Result<(), String>>;
29pub type CheckedFn = Rc<dyn Fn(&App) -> bool>;
31pub type MenuProvider = Rc<dyn Fn(&App) -> Vec<MenuItem>>;
34
35#[derive(Clone, Debug, PartialEq, Action)]
37#[action(namespace = kitchen, no_json)]
38pub struct RunCommand {
39 pub id: SharedString,
41}
42
43#[derive(Clone)]
45pub struct CommandSpec {
46 pub id: SharedString,
48 pub title: SharedString,
50 pub icon: IconName,
52 pub hint: SharedString,
54 pub group: SharedString,
56 pub key: Option<SharedString>,
58 pub args: Option<Value>,
60 pub read_only: bool,
62 pub enabled: EnabledFn,
64 pub checked: Option<CheckedFn>,
66 pub run: RunFn,
68}
69
70impl CommandSpec {
71 pub fn new(
73 id: impl Into<SharedString>,
74 title: impl Into<SharedString>,
75 icon: IconName,
76 run: impl Fn(&mut Window, &mut App) + 'static,
77 ) -> Self {
78 Self::raw(
79 id,
80 title,
81 icon,
82 None,
83 Rc::new(move |_, window, cx| {
84 run(window, cx);
85 Ok(Value::Null)
86 }),
87 )
88 }
89
90 pub fn with_args<A: DeserializeOwned + JsonSchema + 'static>(
93 id: impl Into<SharedString>,
94 title: impl Into<SharedString>,
95 icon: IconName,
96 run: impl Fn(A, &mut Window, &mut App) -> Result<Value, String> + 'static,
97 ) -> Self {
98 let schema = serde_json::to_value(schemars::schema_for!(A)).ok();
99 Self::raw(
100 id,
101 title,
102 icon,
103 schema,
104 Rc::new(move |args, window, cx| {
105 let args = if args.is_null() { Value::Object(Default::default()) } else { args };
107 let a: A = serde_json::from_value(args).map_err(|e| format!("arguments: {e}"))?;
108 run(a, window, cx)
109 }),
110 )
111 }
112
113 pub fn raw(
115 id: impl Into<SharedString>,
116 title: impl Into<SharedString>,
117 icon: IconName,
118 args: Option<Value>,
119 run: RunFn,
120 ) -> Self {
121 Self {
122 id: id.into(),
123 title: title.into(),
124 icon,
125 hint: SharedString::default(),
126 group: "Commands".into(),
127 key: None,
128 args,
129 read_only: false,
130 enabled: Rc::new(|_| Ok(())),
131 checked: None,
132 run,
133 }
134 }
135
136 pub fn hint(mut self, hint: impl Into<SharedString>) -> Self {
138 self.hint = hint.into();
139 self
140 }
141
142 pub fn group(mut self, group: impl Into<SharedString>) -> Self {
144 self.group = group.into();
145 self
146 }
147
148 pub fn key(mut self, key: impl Into<SharedString>) -> Self {
150 self.key = Some(key.into());
151 self
152 }
153
154 pub fn read_only(mut self) -> Self {
156 self.read_only = true;
157 self
158 }
159
160 pub fn enabled(mut self, enabled: impl Fn(&App) -> Result<(), String> + 'static) -> Self {
162 self.enabled = Rc::new(enabled);
163 self
164 }
165
166 pub fn checked(mut self, checked: impl Fn(&App) -> bool + 'static) -> Self {
168 self.checked = Some(Rc::new(checked));
169 self
170 }
171
172 pub fn key_label(&self) -> Option<String> {
174 self.key.as_deref().map(key_label)
175 }
176}
177
178#[derive(Clone, Debug, PartialEq)]
180pub enum MenuItem {
181 Command(SharedString),
183 Run {
186 title: SharedString,
188 icon: Option<IconName>,
190 command: SharedString,
192 args: Value,
194 checked: bool,
196 },
197 Provided(SharedString),
199 Separator,
201 Label(SharedString),
203 Submenu {
205 title: SharedString,
207 icon: Option<IconName>,
209 items: Vec<MenuItem>,
211 },
212}
213
214impl MenuItem {
215 pub fn command(id: impl Into<SharedString>) -> Self {
217 MenuItem::Command(id.into())
218 }
219
220 pub fn submenu(title: impl Into<SharedString>, items: Vec<MenuItem>) -> Self {
222 MenuItem::Submenu { title: title.into(), icon: None, items }
223 }
224
225 pub fn submenu_with_icon(title: impl Into<SharedString>, icon: IconName, items: Vec<MenuItem>) -> Self {
227 MenuItem::Submenu { title: title.into(), icon: Some(icon), items }
228 }
229
230 pub fn run(title: impl Into<SharedString>, command: impl Into<SharedString>, args: Value) -> Self {
232 MenuItem::Run { title: title.into(), icon: None, command: command.into(), args, checked: false }
233 }
234
235 pub fn provided(id: impl Into<SharedString>) -> Self {
237 MenuItem::Provided(id.into())
238 }
239
240 pub fn label(text: impl Into<SharedString>) -> Self {
242 MenuItem::Label(text.into())
243 }
244
245 pub fn icon(mut self, with: IconName) -> Self {
247 match &mut self {
248 MenuItem::Run { icon, .. } | MenuItem::Submenu { icon, .. } => *icon = Some(with),
249 _ => {}
250 }
251 self
252 }
253
254 pub fn checked(mut self, on: bool) -> Self {
256 if let MenuItem::Run { checked, .. } = &mut self {
257 *checked = on;
258 }
259 self
260 }
261}
262
263#[derive(Clone, Debug, PartialEq)]
265pub struct MenuSpec {
266 pub title: SharedString,
268 pub hint: SharedString,
270 pub items: Vec<MenuItem>,
272}
273
274impl MenuSpec {
275 pub fn new(title: impl Into<SharedString>, items: Vec<MenuItem>) -> Self {
277 Self { title: title.into(), hint: SharedString::default(), items }
278 }
279
280 pub fn hint(mut self, hint: impl Into<SharedString>) -> Self {
282 self.hint = hint.into();
283 self
284 }
285
286 pub fn command_ids(&self) -> Vec<SharedString> {
288 fn walk(items: &[MenuItem], out: &mut Vec<SharedString>) {
289 for i in items {
290 match i {
291 MenuItem::Command(id) | MenuItem::Run { command: id, .. } => out.push(id.clone()),
292 MenuItem::Submenu { items, .. } => walk(items, out),
293 _ => {}
294 }
295 }
296 }
297 let mut out = Vec::new();
298 walk(&self.items, &mut out);
299 out
300 }
301}
302
303#[derive(Clone, Default)]
306pub struct Registry {
307 commands: Rc<RefCell<Vec<CommandSpec>>>,
308 providers: Rc<RefCell<Vec<(SharedString, MenuProvider)>>>,
309}
310
311impl Registry {
312 pub fn new(commands: Vec<CommandSpec>) -> Self {
314 let r = Self::default();
315 r.extend(commands);
316 r
317 }
318
319 pub fn add(&self, command: CommandSpec) {
321 let mut list = self.commands.borrow_mut();
322 match list.iter_mut().find(|c| c.id == command.id) {
323 Some(c) => *c = command,
324 None => list.push(command),
325 }
326 }
327
328 pub fn extend(&self, commands: impl IntoIterator<Item = CommandSpec>) {
330 for c in commands {
331 self.add(c);
332 }
333 }
334
335 pub fn remove(&self, id: &str) -> bool {
337 let mut list = self.commands.borrow_mut();
338 let n = list.len();
339 list.retain(|c| c.id != id);
340 list.len() != n
341 }
342
343 pub fn get(&self, id: &str) -> Option<CommandSpec> {
345 self.commands.borrow().iter().find(|c| c.id == id).cloned()
346 }
347
348 pub fn all(&self) -> Vec<CommandSpec> {
350 self.commands.borrow().clone()
351 }
352
353 pub fn len(&self) -> usize {
355 self.commands.borrow().len()
356 }
357
358 pub fn is_empty(&self) -> bool {
360 self.commands.borrow().is_empty()
361 }
362
363 pub fn provide(&self, id: impl Into<SharedString>, provider: impl Fn(&App) -> Vec<MenuItem> + 'static) {
366 let id = id.into();
367 let mut list = self.providers.borrow_mut();
368 list.retain(|(p, _)| *p != id);
369 list.push((id, Rc::new(provider)));
370 }
371
372 pub fn provided(&self, id: &str, cx: &App) -> Vec<MenuItem> {
374 let provider = self.providers.borrow().iter().find(|(p, _)| p == id).map(|(_, f)| f.clone());
375 provider.map(|f| f(cx)).unwrap_or_default()
376 }
377
378 pub fn check(&self, id: &str, cx: &App) -> Result<(), String> {
380 let c = self.get(id).ok_or_else(|| format!("no command {id:?}"))?;
381 (c.enabled)(cx)
382 }
383
384 pub fn run(&self, id: &str, args: Value, window: &mut Window, cx: &mut App) -> Result<Value, String> {
386 self.run_as(crate::activity::Actor::Person, "app", id, args, window, cx)
387 }
388
389 pub fn run_as(
392 &self,
393 actor: crate::activity::Actor,
394 via: &str,
395 id: &str,
396 args: Value,
397 window: &mut Window,
398 cx: &mut App,
399 ) -> Result<Value, String> {
400 let Some(c) = self.get(id) else { return Err(format!("no command {id:?}")) };
401 let result = (c.enabled)(cx).and_then(|_| (c.run)(args.clone(), window, cx));
402 crate::activity::command(actor, id, &c.title, &c.group, via, &args, &result);
403 result
404 }
405
406 pub fn bind_keys(&self, context: Option<&str>, cx: &mut App) -> Vec<String> {
410 let mut bindings = Vec::new();
411 let mut bad = Vec::new();
412 let context = match context.map(gpui_kit::KeyBindingContextPredicate::parse).transpose() {
413 Ok(c) => c.map(Rc::new),
414 Err(e) => return vec![format!("context {context:?}: {e}")],
415 };
416 for c in self.all() {
417 let Some(key) = c.key.clone() else { continue };
418 match KeyBinding::load(&key, Box::new(RunCommand { id: c.id.clone() }), context.clone(), false, None, cx) {
419 Ok(b) => bindings.push(b),
420 Err(e) => bad.push(format!("{}: {key}: {e:?}", c.id)),
421 }
422 }
423 cx.bind_keys(bindings);
424 bad
425 }
426
427 pub fn menu_button(&self, id: impl Into<SharedString>, menu: &MenuSpec) -> gpui_kit::AnyElement {
430 let registry = self.clone();
431 let items = Rc::new(menu.items.clone());
432 let mut button = Button::new(id.into()).ghost().small().label(menu.title.clone());
433 if !menu.hint.is_empty() {
434 button = button.tooltip(menu.hint.clone());
435 }
436 button
438 .dropdown_menu(move |m, window, cx| {
439 registry.fill_menu(
440 m.min_w(gpui_kit::px(240.)).scrollable(true).max_h(gpui_kit::px(560.)),
441 &items,
442 window,
443 cx,
444 )
445 })
446 .into_any_element()
447 }
448
449 pub fn fill_menu(
451 &self,
452 mut menu: PopupMenu,
453 items: &[MenuItem],
454 window: &mut Window,
455 cx: &mut Context<PopupMenu>,
456 ) -> PopupMenu {
457 for item in items {
458 menu = match item {
459 MenuItem::Separator => menu.separator(),
460 MenuItem::Label(text) => menu.label(text.clone()),
461 MenuItem::Submenu { title, icon, items } => {
462 let (registry, items) = (self.clone(), items.clone());
463 menu.submenu_with_icon(icon.map(Icon::new), title.clone(), window, cx, move |m, window, cx| {
464 registry.fill_menu(m, &items, window, cx)
465 })
466 }
467 MenuItem::Command(id) => match self.get(id) {
468 Some(c) => menu.item(self.menu_item(&c, cx)),
469 None => menu.item(PopupMenuItem::new(format!("{id} (not registered)")).disabled(true)),
471 },
472 MenuItem::Run { title, icon, command, args, checked } => match self.get(command) {
473 Some(c) => menu.item(self.run_item(&c, title, icon.unwrap_or(c.icon), args, *checked, cx)),
474 None => menu.item(PopupMenuItem::new(format!("{title} ({command} not registered)")).disabled(true)),
475 },
476 MenuItem::Provided(id) => {
477 let items = self.provided(id, cx);
478 self.fill_menu(menu, &items, window, cx)
479 }
480 };
481 }
482 menu
483 }
484
485 fn run_item(
487 &self,
488 c: &CommandSpec,
489 title: &SharedString,
490 icon: IconName,
491 args: &Value,
492 checked: bool,
493 cx: &App,
494 ) -> PopupMenuItem {
495 match (c.enabled)(cx) {
496 Ok(()) => {
497 let (registry, id, args) = (self.clone(), c.id.clone(), args.clone());
498 PopupMenuItem::new(title.clone()).icon(Icon::new(icon)).checked(checked).on_click(
499 move |_, window, cx| {
500 if let Err(e) =
501 registry.run_as(crate::activity::Actor::Person, "menu", &id, args.clone(), window, cx)
502 {
503 eprintln!("{id}: {e}");
504 }
505 },
506 )
507 }
508 Err(why) => {
509 let title = title.clone();
510 PopupMenuItem::element(move |_, _| {
511 v_flex()
512 .child(div().text_color(color::text_disabled()).child(title.clone()))
513 .child(div().text_xs().text_color(color::text_muted()).child(why.clone()))
514 })
515 .icon(Icon::new(icon))
516 .disabled(true)
517 }
518 }
519 }
520
521 fn menu_item(&self, c: &CommandSpec, cx: &App) -> PopupMenuItem {
522 let action = Box::new(RunCommand { id: c.id.clone() });
523 match (c.enabled)(cx) {
524 Ok(()) => {
525 let (registry, id) = (self.clone(), c.id.clone());
526 let checked = c.checked.as_ref().is_some_and(|f| f(cx));
527 PopupMenuItem::new(c.title.clone()).icon(Icon::new(c.icon)).checked(checked).action(action).on_click(
529 move |_, window, cx| {
530 if let Err(e) =
531 registry.run_as(crate::activity::Actor::Person, "menu", &id, Value::Null, window, cx)
532 {
533 eprintln!("{id}: {e}");
534 }
535 },
536 )
537 }
538 Err(why) => {
539 let title = c.title.clone();
540 PopupMenuItem::element(move |_, _| {
541 v_flex()
542 .child(div().text_color(color::text_disabled()).child(title.clone()))
543 .child(div().text_xs().text_color(color::text_muted()).child(why.clone()))
544 })
545 .icon(Icon::new(c.icon))
546 .disabled(true)
547 }
548 }
549 }
550}
551
552pub fn key_label(key: &str) -> String {
555 key.split_whitespace().map(stroke_label).collect::<Vec<_>>().join(" ")
557}
558
559fn stroke_label(stroke: &str) -> String {
560 let mac = cfg!(target_os = "macos");
561 let parts: Vec<&str> = stroke.split('-').collect();
562 let (mods, key) = match parts.as_slice() {
564 [mods @ .., "", ""] => (mods, "-"),
565 [mods @ .., key] => (mods, *key),
566 [] => (&[][..], ""),
567 };
568 let mut out: Vec<String> = mods
569 .iter()
570 .map(|m| match (*m, mac) {
571 ("secondary" | "cmd", true) => "⌘".into(),
572 ("secondary" | "ctrl", false) => "Ctrl".into(),
573 ("ctrl", true) => "⌃".into(),
574 ("cmd", false) => "Super".into(),
575 ("shift", true) => "⇧".into(),
576 ("shift", false) => "Shift".into(),
577 ("alt", true) => "⌥".into(),
578 ("alt", false) => "Alt".into(),
579 (other, _) => other.to_string(),
580 })
581 .collect();
582 let key = match key {
583 k if k.len() == 1 => k.to_uppercase(),
584 k if k.starts_with('f') && k[1..].parse::<u8>().is_ok() => k.to_uppercase(),
585 "escape" => "Esc".into(),
586 k => {
587 let mut c = k.chars();
588 c.next().map(|f| f.to_uppercase().collect::<String>() + c.as_str()).unwrap_or_default()
589 }
590 };
591 out.push(key);
592 if mac { out.concat() } else { out.join("+") }
593}
594
595#[cfg(test)]
596mod tests {
597 use super::*;
598
599 #[test]
600 fn keys_read_as_people_write_them() {
601 if cfg!(target_os = "macos") {
602 assert_eq!(key_label("secondary-shift-s"), "⌘⇧S");
603 } else {
604 assert_eq!(key_label("secondary-shift-s"), "Ctrl+Shift+S");
605 assert_eq!(key_label("secondary-,"), "Ctrl+,");
606 assert_eq!(key_label("ctrl--"), "Ctrl+-");
607 assert_eq!(key_label("secondary-k secondary-s"), "Ctrl+K Ctrl+S");
608 }
609 assert_eq!(key_label("f3"), "F3");
610 assert_eq!(key_label("escape"), "Esc");
611 }
612
613 #[test]
614 fn menus_list_their_commands() {
615 let m = MenuSpec::new(
616 "File",
617 vec![
618 MenuItem::command("file.open"),
619 MenuItem::Separator,
620 MenuItem::submenu("Recent", vec![MenuItem::command("file.recent.1")]),
621 ],
622 );
623 assert_eq!(m.command_ids(), vec![SharedString::from("file.open"), SharedString::from("file.recent.1")]);
624 }
625
626 #[test]
627 fn a_registry_replaces_a_command_with_the_same_id() {
628 let r = Registry::new(vec![
629 CommandSpec::new("a", "A", IconName::Plus, |_, _| {}),
630 CommandSpec::new("b", "B", IconName::Plus, |_, _| {}),
631 ]);
632 r.add(CommandSpec::new("a", "A again", IconName::Plus, |_, _| {}));
633 assert_eq!(r.len(), 2);
634 assert_eq!(r.get("a").unwrap().title.as_ref(), "A again");
635 assert!(r.remove("b") && !r.remove("b"));
636 }
637
638 #[derive(serde::Deserialize, JsonSchema)]
639 #[allow(dead_code)]
640 struct Threshold {
641 level: f64,
643 }
644
645 #[test]
646 fn typed_commands_publish_their_schema() {
647 let c = CommandSpec::with_args::<Threshold>("t", "Threshold", IconName::Plus, |a, _, _| {
648 Ok(serde_json::json!(a.level))
649 });
650 let schema = c.args.unwrap();
651 assert_eq!(schema["properties"]["level"]["type"], "number");
652 assert_eq!(schema["required"][0], "level");
653 }
654}