command_palette.rs

  1use collections::{CommandPaletteFilter, HashMap};
  2use fuzzy::{StringMatch, StringMatchCandidate};
  3use gpui::{
  4    actions, div, Action, AppContext, Component, Div, EventEmitter, FocusHandle, Keystroke,
  5    ParentElement, Render, StatelessInteractive, Styled, View, ViewContext, VisualContext,
  6    WeakView, WindowContext,
  7};
  8use picker::{Picker, PickerDelegate};
  9use std::cmp::{self, Reverse};
 10use theme::ActiveTheme;
 11use ui::{v_stack, Label, StyledExt};
 12use util::{
 13    channel::{parse_zed_link, ReleaseChannel, RELEASE_CHANNEL},
 14    ResultExt,
 15};
 16use workspace::{Modal, ModalEvent, Workspace};
 17use zed_actions::OpenZedURL;
 18
 19actions!(Toggle);
 20
 21pub fn init(cx: &mut AppContext) {
 22    cx.set_global(HitCounts::default());
 23    cx.observe_new_views(CommandPalette::register).detach();
 24}
 25
 26pub struct CommandPalette {
 27    picker: View<Picker<CommandPaletteDelegate>>,
 28}
 29
 30impl CommandPalette {
 31    fn register(workspace: &mut Workspace, _: &mut ViewContext<Workspace>) {
 32        workspace.register_action(|workspace, _: &Toggle, cx| {
 33            let Some(previous_focus_handle) = cx.focused() else {
 34                return;
 35            };
 36            workspace.toggle_modal(cx, move |cx| CommandPalette::new(previous_focus_handle, cx));
 37        });
 38    }
 39
 40    fn new(previous_focus_handle: FocusHandle, cx: &mut ViewContext<Self>) -> Self {
 41        let filter = cx.try_global::<CommandPaletteFilter>();
 42
 43        let commands = cx
 44            .available_actions()
 45            .into_iter()
 46            .filter_map(|action| {
 47                let name = action.name();
 48                let namespace = name.split("::").next().unwrap_or("malformed action name");
 49                if filter.is_some_and(|f| f.filtered_namespaces.contains(namespace)) {
 50                    return None;
 51                }
 52
 53                Some(Command {
 54                    name: humanize_action_name(&name),
 55                    action,
 56                    keystrokes: vec![], // todo!()
 57                })
 58            })
 59            .collect();
 60
 61        let delegate =
 62            CommandPaletteDelegate::new(cx.view().downgrade(), commands, previous_focus_handle);
 63
 64        let picker = cx.build_view(|cx| Picker::new(delegate, cx));
 65        Self { picker }
 66    }
 67}
 68
 69impl EventEmitter<ModalEvent> for CommandPalette {}
 70impl Modal for CommandPalette {
 71    fn focus(&self, cx: &mut WindowContext) {
 72        self.picker.update(cx, |picker, cx| picker.focus(cx));
 73    }
 74}
 75
 76impl Render for CommandPalette {
 77    type Element = Div<Self>;
 78
 79    fn render(&mut self, _cx: &mut ViewContext<Self>) -> Self::Element {
 80        v_stack().w_96().child(self.picker.clone())
 81    }
 82}
 83
 84pub type CommandPaletteInterceptor =
 85    Box<dyn Fn(&str, &AppContext) -> Option<CommandInterceptResult>>;
 86
 87pub struct CommandInterceptResult {
 88    pub action: Box<dyn Action>,
 89    pub string: String,
 90    pub positions: Vec<usize>,
 91}
 92
 93pub struct CommandPaletteDelegate {
 94    command_palette: WeakView<CommandPalette>,
 95    commands: Vec<Command>,
 96    matches: Vec<StringMatch>,
 97    selected_ix: usize,
 98    previous_focus_handle: FocusHandle,
 99}
100
101struct Command {
102    name: String,
103    action: Box<dyn Action>,
104    keystrokes: Vec<Keystroke>,
105}
106
107impl Clone for Command {
108    fn clone(&self) -> Self {
109        Self {
110            name: self.name.clone(),
111            action: self.action.boxed_clone(),
112            keystrokes: self.keystrokes.clone(),
113        }
114    }
115}
116/// Hit count for each command in the palette.
117/// We only account for commands triggered directly via command palette and not by e.g. keystrokes because
118/// if an user already knows a keystroke for a command, they are unlikely to use a command palette to look for it.
119#[derive(Default)]
120struct HitCounts(HashMap<String, usize>);
121
122impl CommandPaletteDelegate {
123    fn new(
124        command_palette: WeakView<CommandPalette>,
125        commands: Vec<Command>,
126        previous_focus_handle: FocusHandle,
127    ) -> Self {
128        Self {
129            command_palette,
130            matches: commands
131                .iter()
132                .enumerate()
133                .map(|(i, command)| StringMatch {
134                    candidate_id: i,
135                    string: command.name.clone(),
136                    positions: Vec::new(),
137                    score: 0.0,
138                })
139                .collect(),
140            commands,
141            selected_ix: 0,
142            previous_focus_handle,
143        }
144    }
145}
146
147impl PickerDelegate for CommandPaletteDelegate {
148    type ListItem = Div<Picker<Self>>;
149
150    fn match_count(&self) -> usize {
151        self.matches.len()
152    }
153
154    fn selected_index(&self) -> usize {
155        self.selected_ix
156    }
157
158    fn set_selected_index(&mut self, ix: usize, _: &mut ViewContext<Picker<Self>>) {
159        self.selected_ix = ix;
160    }
161
162    fn update_matches(
163        &mut self,
164        query: String,
165        cx: &mut ViewContext<Picker<Self>>,
166    ) -> gpui::Task<()> {
167        let mut commands = self.commands.clone();
168
169        cx.spawn(move |picker, mut cx| async move {
170            cx.read_global::<HitCounts, _>(|hit_counts, _| {
171                commands.sort_by_key(|action| {
172                    (
173                        Reverse(hit_counts.0.get(&action.name).cloned()),
174                        action.name.clone(),
175                    )
176                });
177            })
178            .ok();
179
180            let candidates = commands
181                .iter()
182                .enumerate()
183                .map(|(ix, command)| StringMatchCandidate {
184                    id: ix,
185                    string: command.name.to_string(),
186                    char_bag: command.name.chars().collect(),
187                })
188                .collect::<Vec<_>>();
189            let mut matches = if query.is_empty() {
190                candidates
191                    .into_iter()
192                    .enumerate()
193                    .map(|(index, candidate)| StringMatch {
194                        candidate_id: index,
195                        string: candidate.string,
196                        positions: Vec::new(),
197                        score: 0.0,
198                    })
199                    .collect()
200            } else {
201                fuzzy::match_strings(
202                    &candidates,
203                    &query,
204                    true,
205                    10000,
206                    &Default::default(),
207                    cx.background_executor().clone(),
208                )
209                .await
210            };
211
212            let mut intercept_result = cx
213                .try_read_global(|interceptor: &CommandPaletteInterceptor, cx| {
214                    (interceptor)(&query, cx)
215                })
216                .flatten();
217
218            if *RELEASE_CHANNEL == ReleaseChannel::Dev {
219                if parse_zed_link(&query).is_some() {
220                    intercept_result = Some(CommandInterceptResult {
221                        action: OpenZedURL { url: query.clone() }.boxed_clone(),
222                        string: query.clone(),
223                        positions: vec![],
224                    })
225                }
226            }
227            if let Some(CommandInterceptResult {
228                action,
229                string,
230                positions,
231            }) = intercept_result
232            {
233                if let Some(idx) = matches
234                    .iter()
235                    .position(|m| commands[m.candidate_id].action.type_id() == action.type_id())
236                {
237                    matches.remove(idx);
238                }
239                commands.push(Command {
240                    name: string.clone(),
241                    action,
242                    keystrokes: vec![],
243                });
244                matches.insert(
245                    0,
246                    StringMatch {
247                        candidate_id: commands.len() - 1,
248                        string,
249                        positions,
250                        score: 0.0,
251                    },
252                )
253            }
254            picker
255                .update(&mut cx, |picker, _| {
256                    let delegate = &mut picker.delegate;
257                    delegate.commands = commands;
258                    delegate.matches = matches;
259                    if delegate.matches.is_empty() {
260                        delegate.selected_ix = 0;
261                    } else {
262                        delegate.selected_ix =
263                            cmp::min(delegate.selected_ix, delegate.matches.len() - 1);
264                    }
265                })
266                .log_err();
267        })
268    }
269
270    fn dismissed(&mut self, cx: &mut ViewContext<Picker<Self>>) {
271        self.command_palette
272            .update(cx, |_, cx| cx.emit(ModalEvent::Dismissed))
273            .log_err();
274    }
275
276    fn confirm(&mut self, _: bool, cx: &mut ViewContext<Picker<Self>>) {
277        if self.matches.is_empty() {
278            self.dismissed(cx);
279            return;
280        }
281        let action_ix = self.matches[self.selected_ix].candidate_id;
282        let command = self.commands.swap_remove(action_ix);
283        cx.update_global(|hit_counts: &mut HitCounts, _| {
284            *hit_counts.0.entry(command.name).or_default() += 1;
285        });
286        let action = command.action;
287        cx.focus(&self.previous_focus_handle);
288        cx.dispatch_action(action);
289        self.dismissed(cx);
290    }
291
292    fn render_match(
293        &self,
294        ix: usize,
295        selected: bool,
296        cx: &mut ViewContext<Picker<Self>>,
297    ) -> Self::ListItem {
298        let colors = cx.theme().colors();
299        let Some(command) = self
300            .matches
301            .get(ix)
302            .and_then(|m| self.commands.get(m.candidate_id))
303        else {
304            return div();
305        };
306
307        div()
308            .px_1()
309            .text_color(colors.text)
310            .text_ui()
311            .bg(colors.ghost_element_background)
312            .rounded_md()
313            .when(selected, |this| this.bg(colors.ghost_element_selected))
314            .hover(|this| this.bg(colors.ghost_element_hover))
315            .child(Label::new(command.name.clone()))
316    }
317
318    // fn render_match(
319    //     &self,
320    //     ix: usize,
321    //     mouse_state: &mut MouseState,
322    //     selected: bool,
323    //     cx: &gpui::AppContext,
324    // ) -> AnyElement<Picker<Self>> {
325    //     let mat = &self.matches[ix];
326    //     let command = &self.actions[mat.candidate_id];
327    //     let theme = theme::current(cx);
328    //     let style = theme.picker.item.in_state(selected).style_for(mouse_state);
329    //     let key_style = &theme.command_palette.key.in_state(selected);
330    //     let keystroke_spacing = theme.command_palette.keystroke_spacing;
331
332    //     Flex::row()
333    //         .with_child(
334    //             Label::new(mat.string.clone(), style.label.clone())
335    //                 .with_highlights(mat.positions.clone()),
336    //         )
337    //         .with_children(command.keystrokes.iter().map(|keystroke| {
338    //             Flex::row()
339    //                 .with_children(
340    //                     [
341    //                         (keystroke.ctrl, "^"),
342    //                         (keystroke.alt, "⌥"),
343    //                         (keystroke.cmd, "⌘"),
344    //                         (keystroke.shift, "⇧"),
345    //                     ]
346    //                     .into_iter()
347    //                     .filter_map(|(modifier, label)| {
348    //                         if modifier {
349    //                             Some(
350    //                                 Label::new(label, key_style.label.clone())
351    //                                     .contained()
352    //                                     .with_style(key_style.container),
353    //                             )
354    //                         } else {
355    //                             None
356    //                         }
357    //                     }),
358    //                 )
359    //                 .with_child(
360    //                     Label::new(keystroke.key.clone(), key_style.label.clone())
361    //                         .contained()
362    //                         .with_style(key_style.container),
363    //                 )
364    //                 .contained()
365    //                 .with_margin_left(keystroke_spacing)
366    //                 .flex_float()
367    //         }))
368    //         .contained()
369    //         .with_style(style.container)
370    //         .into_any()
371    // }
372}
373
374fn humanize_action_name(name: &str) -> String {
375    let capacity = name.len() + name.chars().filter(|c| c.is_uppercase()).count();
376    let mut result = String::with_capacity(capacity);
377    for char in name.chars() {
378        if char == ':' {
379            if result.ends_with(':') {
380                result.push(' ');
381            } else {
382                result.push(':');
383            }
384        } else if char == '_' {
385            result.push(' ');
386        } else if char.is_uppercase() {
387            if !result.ends_with(' ') {
388                result.push(' ');
389            }
390            result.extend(char.to_lowercase());
391        } else {
392            result.push(char);
393        }
394    }
395    result
396}
397
398impl std::fmt::Debug for Command {
399    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
400        f.debug_struct("Command")
401            .field("name", &self.name)
402            .field("keystrokes", &self.keystrokes)
403            .finish()
404    }
405}
406
407// #[cfg(test)]
408// mod tests {
409//     use std::sync::Arc;
410
411//     use super::*;
412//     use editor::Editor;
413//     use gpui::{executor::Deterministic, TestAppContext};
414//     use project::Project;
415//     use workspace::{AppState, Workspace};
416
417//     #[test]
418//     fn test_humanize_action_name() {
419//         assert_eq!(
420//             humanize_action_name("editor::GoToDefinition"),
421//             "editor: go to definition"
422//         );
423//         assert_eq!(
424//             humanize_action_name("editor::Backspace"),
425//             "editor: backspace"
426//         );
427//         assert_eq!(
428//             humanize_action_name("go_to_line::Deploy"),
429//             "go to line: deploy"
430//         );
431//     }
432
433//     #[gpui::test]
434//     async fn test_command_palette(deterministic: Arc<Deterministic>, cx: &mut TestAppContext) {
435//         let app_state = init_test(cx);
436
437//         let project = Project::test(app_state.fs.clone(), [], cx).await;
438//         let window = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
439//         let workspace = window.root(cx);
440//         let editor = window.add_view(cx, |cx| {
441//             let mut editor = Editor::single_line(None, cx);
442//             editor.set_text("abc", cx);
443//             editor
444//         });
445
446//         workspace.update(cx, |workspace, cx| {
447//             cx.focus(&editor);
448//             workspace.add_item(Box::new(editor.clone()), cx)
449//         });
450
451//         workspace.update(cx, |workspace, cx| {
452//             toggle_command_palette(workspace, &Toggle, cx);
453//         });
454
455//         let palette = workspace.read_with(cx, |workspace, _| {
456//             workspace.modal::<CommandPalette>().unwrap()
457//         });
458
459//         palette
460//             .update(cx, |palette, cx| {
461//                 // Fill up palette's command list by running an empty query;
462//                 // we only need it to subsequently assert that the palette is initially
463//                 // sorted by command's name.
464//                 palette.delegate_mut().update_matches("".to_string(), cx)
465//             })
466//             .await;
467
468//         palette.update(cx, |palette, _| {
469//             let is_sorted =
470//                 |actions: &[Command]| actions.windows(2).all(|pair| pair[0].name <= pair[1].name);
471//             assert!(is_sorted(&palette.delegate().actions));
472//         });
473
474//         palette
475//             .update(cx, |palette, cx| {
476//                 palette
477//                     .delegate_mut()
478//                     .update_matches("bcksp".to_string(), cx)
479//             })
480//             .await;
481
482//         palette.update(cx, |palette, cx| {
483//             assert_eq!(palette.delegate().matches[0].string, "editor: backspace");
484//             palette.confirm(&Default::default(), cx);
485//         });
486//         deterministic.run_until_parked();
487//         editor.read_with(cx, |editor, cx| {
488//             assert_eq!(editor.text(cx), "ab");
489//         });
490
491//         // Add namespace filter, and redeploy the palette
492//         cx.update(|cx| {
493//             cx.update_default_global::<CommandPaletteFilter, _, _>(|filter, _| {
494//                 filter.filtered_namespaces.insert("editor");
495//             })
496//         });
497
498//         workspace.update(cx, |workspace, cx| {
499//             toggle_command_palette(workspace, &Toggle, cx);
500//         });
501
502//         // Assert editor command not present
503//         let palette = workspace.read_with(cx, |workspace, _| {
504//             workspace.modal::<CommandPalette>().unwrap()
505//         });
506
507//         palette
508//             .update(cx, |palette, cx| {
509//                 palette
510//                     .delegate_mut()
511//                     .update_matches("bcksp".to_string(), cx)
512//             })
513//             .await;
514
515//         palette.update(cx, |palette, _| {
516//             assert!(palette.delegate().matches.is_empty())
517//         });
518//     }
519
520//     fn init_test(cx: &mut TestAppContext) -> Arc<AppState> {
521//         cx.update(|cx| {
522//             let app_state = AppState::test(cx);
523//             theme::init(cx);
524//             language::init(cx);
525//             editor::init(cx);
526//             workspace::init(app_state.clone(), cx);
527//             init(cx);
528//             Project::init_settings(cx);
529//             app_state
530//         })
531//     }
532// }