command_palette.rs

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