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, SharedString, StatelessInteractive, Styled, View, ViewContext,
  6    VisualContext, WeakView, WindowContext,
  7};
  8use picker::{Picker, PickerDelegate};
  9use std::cmp::{self, Reverse};
 10use theme::ActiveTheme;
 11use ui::{v_stack, HighlightedLabel, 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 placeholder_text(&self) -> Arc<str> {
151        "Execute a command...".into()
152    }
153
154    fn match_count(&self) -> usize {
155        self.matches.len()
156    }
157
158    fn selected_index(&self) -> usize {
159        self.selected_ix
160    }
161
162    fn set_selected_index(&mut self, ix: usize, _: &mut ViewContext<Picker<Self>>) {
163        self.selected_ix = ix;
164    }
165
166    fn update_matches(
167        &mut self,
168        query: String,
169        cx: &mut ViewContext<Picker<Self>>,
170    ) -> gpui::Task<()> {
171        let mut commands = self.commands.clone();
172
173        cx.spawn(move |picker, mut cx| async move {
174            cx.read_global::<HitCounts, _>(|hit_counts, _| {
175                commands.sort_by_key(|action| {
176                    (
177                        Reverse(hit_counts.0.get(&action.name).cloned()),
178                        action.name.clone(),
179                    )
180                });
181            })
182            .ok();
183
184            let candidates = commands
185                .iter()
186                .enumerate()
187                .map(|(ix, command)| StringMatchCandidate {
188                    id: ix,
189                    string: command.name.to_string(),
190                    char_bag: command.name.chars().collect(),
191                })
192                .collect::<Vec<_>>();
193            let mut matches = if query.is_empty() {
194                candidates
195                    .into_iter()
196                    .enumerate()
197                    .map(|(index, candidate)| StringMatch {
198                        candidate_id: index,
199                        string: candidate.string,
200                        positions: Vec::new(),
201                        score: 0.0,
202                    })
203                    .collect()
204            } else {
205                fuzzy::match_strings(
206                    &candidates,
207                    &query,
208                    true,
209                    10000,
210                    &Default::default(),
211                    cx.background_executor().clone(),
212                )
213                .await
214            };
215
216            let mut intercept_result = cx
217                .try_read_global(|interceptor: &CommandPaletteInterceptor, cx| {
218                    (interceptor)(&query, cx)
219                })
220                .flatten();
221
222            if *RELEASE_CHANNEL == ReleaseChannel::Dev {
223                if parse_zed_link(&query).is_some() {
224                    intercept_result = Some(CommandInterceptResult {
225                        action: OpenZedURL { url: query.clone() }.boxed_clone(),
226                        string: query.clone(),
227                        positions: vec![],
228                    })
229                }
230            }
231            if let Some(CommandInterceptResult {
232                action,
233                string,
234                positions,
235            }) = intercept_result
236            {
237                if let Some(idx) = matches
238                    .iter()
239                    .position(|m| commands[m.candidate_id].action.type_id() == action.type_id())
240                {
241                    matches.remove(idx);
242                }
243                commands.push(Command {
244                    name: string.clone(),
245                    action,
246                    keystrokes: vec![],
247                });
248                matches.insert(
249                    0,
250                    StringMatch {
251                        candidate_id: commands.len() - 1,
252                        string,
253                        positions,
254                        score: 0.0,
255                    },
256                )
257            }
258            picker
259                .update(&mut cx, |picker, _| {
260                    let delegate = &mut picker.delegate;
261                    delegate.commands = commands;
262                    delegate.matches = matches;
263                    if delegate.matches.is_empty() {
264                        delegate.selected_ix = 0;
265                    } else {
266                        delegate.selected_ix =
267                            cmp::min(delegate.selected_ix, delegate.matches.len() - 1);
268                    }
269                })
270                .log_err();
271        })
272    }
273
274    fn dismissed(&mut self, cx: &mut ViewContext<Picker<Self>>) {
275        self.command_palette
276            .update(cx, |_, cx| cx.emit(ModalEvent::Dismissed))
277            .log_err();
278    }
279
280    fn confirm(&mut self, _: bool, cx: &mut ViewContext<Picker<Self>>) {
281        if self.matches.is_empty() {
282            self.dismissed(cx);
283            return;
284        }
285        let action_ix = self.matches[self.selected_ix].candidate_id;
286        let command = self.commands.swap_remove(action_ix);
287        cx.update_global(|hit_counts: &mut HitCounts, _| {
288            *hit_counts.0.entry(command.name).or_default() += 1;
289        });
290        let action = command.action;
291        cx.focus(&self.previous_focus_handle);
292        cx.dispatch_action(action);
293        self.dismissed(cx);
294    }
295
296    fn render_match(
297        &self,
298        ix: usize,
299        selected: bool,
300        cx: &mut ViewContext<Picker<Self>>,
301    ) -> Self::ListItem {
302        let colors = cx.theme().colors();
303        let Some(r#match) = self.matches.get(ix) else {
304            return div();
305        };
306        let Some(command) = self.commands.get(r#match.candidate_id) else {
307            return div();
308        };
309
310        div()
311            .px_1()
312            .text_color(colors.text)
313            .text_ui()
314            .bg(colors.ghost_element_background)
315            .rounded_md()
316            .when(selected, |this| this.bg(colors.ghost_element_selected))
317            .hover(|this| this.bg(colors.ghost_element_hover))
318            .child(HighlightedLabel::new(
319                command.name.clone(),
320                r#match.positions.clone(),
321            ))
322    }
323
324    // fn render_match(
325    //     &self,
326    //     ix: usize,
327    //     mouse_state: &mut MouseState,
328    //     selected: bool,
329    //     cx: &gpui::AppContext,
330    // ) -> AnyElement<Picker<Self>> {
331    //     let mat = &self.matches[ix];
332    //     let command = &self.actions[mat.candidate_id];
333    //     let theme = theme::current(cx);
334    //     let style = theme.picker.item.in_state(selected).style_for(mouse_state);
335    //     let key_style = &theme.command_palette.key.in_state(selected);
336    //     let keystroke_spacing = theme.command_palette.keystroke_spacing;
337
338    //     Flex::row()
339    //         .with_child(
340    //             Label::new(mat.string.clone(), style.label.clone())
341    //                 .with_highlights(mat.positions.clone()),
342    //         )
343    //         .with_children(command.keystrokes.iter().map(|keystroke| {
344    //             Flex::row()
345    //                 .with_children(
346    //                     [
347    //                         (keystroke.ctrl, "^"),
348    //                         (keystroke.alt, "⌥"),
349    //                         (keystroke.cmd, "⌘"),
350    //                         (keystroke.shift, "⇧"),
351    //                     ]
352    //                     .into_iter()
353    //                     .filter_map(|(modifier, label)| {
354    //                         if modifier {
355    //                             Some(
356    //                                 Label::new(label, key_style.label.clone())
357    //                                     .contained()
358    //                                     .with_style(key_style.container),
359    //                             )
360    //                         } else {
361    //                             None
362    //                         }
363    //                     }),
364    //                 )
365    //                 .with_child(
366    //                     Label::new(keystroke.key.clone(), key_style.label.clone())
367    //                         .contained()
368    //                         .with_style(key_style.container),
369    //                 )
370    //                 .contained()
371    //                 .with_margin_left(keystroke_spacing)
372    //                 .flex_float()
373    //         }))
374    //         .contained()
375    //         .with_style(style.container)
376    //         .into_any()
377    // }
378}
379
380fn humanize_action_name(name: &str) -> String {
381    let capacity = name.len() + name.chars().filter(|c| c.is_uppercase()).count();
382    let mut result = String::with_capacity(capacity);
383    for char in name.chars() {
384        if char == ':' {
385            if result.ends_with(':') {
386                result.push(' ');
387            } else {
388                result.push(':');
389            }
390        } else if char == '_' {
391            result.push(' ');
392        } else if char.is_uppercase() {
393            if !result.ends_with(' ') {
394                result.push(' ');
395            }
396            result.extend(char.to_lowercase());
397        } else {
398            result.push(char);
399        }
400    }
401    result
402}
403
404impl std::fmt::Debug for Command {
405    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
406        f.debug_struct("Command")
407            .field("name", &self.name)
408            .field("keystrokes", &self.keystrokes)
409            .finish()
410    }
411}
412
413// #[cfg(test)]
414// mod tests {
415//     use std::sync::Arc;
416
417//     use super::*;
418//     use editor::Editor;
419//     use gpui::{executor::Deterministic, TestAppContext};
420//     use project::Project;
421//     use workspace::{AppState, Workspace};
422
423//     #[test]
424//     fn test_humanize_action_name() {
425//         assert_eq!(
426//             humanize_action_name("editor::GoToDefinition"),
427//             "editor: go to definition"
428//         );
429//         assert_eq!(
430//             humanize_action_name("editor::Backspace"),
431//             "editor: backspace"
432//         );
433//         assert_eq!(
434//             humanize_action_name("go_to_line::Deploy"),
435//             "go to line: deploy"
436//         );
437//     }
438
439//     #[gpui::test]
440//     async fn test_command_palette(deterministic: Arc<Deterministic>, cx: &mut TestAppContext) {
441//         let app_state = init_test(cx);
442
443//         let project = Project::test(app_state.fs.clone(), [], cx).await;
444//         let window = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
445//         let workspace = window.root(cx);
446//         let editor = window.add_view(cx, |cx| {
447//             let mut editor = Editor::single_line(None, cx);
448//             editor.set_text("abc", cx);
449//             editor
450//         });
451
452//         workspace.update(cx, |workspace, cx| {
453//             cx.focus(&editor);
454//             workspace.add_item(Box::new(editor.clone()), cx)
455//         });
456
457//         workspace.update(cx, |workspace, cx| {
458//             toggle_command_palette(workspace, &Toggle, cx);
459//         });
460
461//         let palette = workspace.read_with(cx, |workspace, _| {
462//             workspace.modal::<CommandPalette>().unwrap()
463//         });
464
465//         palette
466//             .update(cx, |palette, cx| {
467//                 // Fill up palette's command list by running an empty query;
468//                 // we only need it to subsequently assert that the palette is initially
469//                 // sorted by command's name.
470//                 palette.delegate_mut().update_matches("".to_string(), cx)
471//             })
472//             .await;
473
474//         palette.update(cx, |palette, _| {
475//             let is_sorted =
476//                 |actions: &[Command]| actions.windows(2).all(|pair| pair[0].name <= pair[1].name);
477//             assert!(is_sorted(&palette.delegate().actions));
478//         });
479
480//         palette
481//             .update(cx, |palette, cx| {
482//                 palette
483//                     .delegate_mut()
484//                     .update_matches("bcksp".to_string(), cx)
485//             })
486//             .await;
487
488//         palette.update(cx, |palette, cx| {
489//             assert_eq!(palette.delegate().matches[0].string, "editor: backspace");
490//             palette.confirm(&Default::default(), cx);
491//         });
492//         deterministic.run_until_parked();
493//         editor.read_with(cx, |editor, cx| {
494//             assert_eq!(editor.text(cx), "ab");
495//         });
496
497//         // Add namespace filter, and redeploy the palette
498//         cx.update(|cx| {
499//             cx.update_default_global::<CommandPaletteFilter, _, _>(|filter, _| {
500//                 filter.filtered_namespaces.insert("editor");
501//             })
502//         });
503
504//         workspace.update(cx, |workspace, cx| {
505//             toggle_command_palette(workspace, &Toggle, cx);
506//         });
507
508//         // Assert editor command not present
509//         let palette = workspace.read_with(cx, |workspace, _| {
510//             workspace.modal::<CommandPalette>().unwrap()
511//         });
512
513//         palette
514//             .update(cx, |palette, cx| {
515//                 palette
516//                     .delegate_mut()
517//                     .update_matches("bcksp".to_string(), cx)
518//             })
519//             .await;
520
521//         palette.update(cx, |palette, _| {
522//             assert!(palette.delegate().matches.is_empty())
523//         });
524//     }
525
526//     fn init_test(cx: &mut TestAppContext) -> Arc<AppState> {
527//         cx.update(|cx| {
528//             let app_state = AppState::test(cx);
529//             theme::init(cx);
530//             language::init(cx);
531//             editor::init(cx);
532//             workspace::init(app_state.clone(), cx);
533//             init(cx);
534//             Project::init_settings(cx);
535//             app_state
536//         })
537//     }
538// }