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, 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, ListItemSpacing};
 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.new_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    fn render(&mut self, _cx: &mut ViewContext<Self>) -> impl IntoElement {
 87        v_stack().w(rems(34.)).child(self.picker.clone())
 88    }
 89}
 90
 91pub type CommandPaletteInterceptor =
 92    Box<dyn Fn(&str, &AppContext) -> Option<CommandInterceptResult>>;
 93
 94pub struct CommandInterceptResult {
 95    pub action: Box<dyn Action>,
 96    pub string: String,
 97    pub positions: Vec<usize>,
 98}
 99
100pub struct CommandPaletteDelegate {
101    command_palette: WeakView<CommandPalette>,
102    all_commands: Vec<Command>,
103    commands: Vec<Command>,
104    matches: Vec<StringMatch>,
105    selected_ix: usize,
106    previous_focus_handle: FocusHandle,
107}
108
109struct Command {
110    name: String,
111    action: Box<dyn Action>,
112}
113
114impl Clone for Command {
115    fn clone(&self) -> Self {
116        Self {
117            name: self.name.clone(),
118            action: self.action.boxed_clone(),
119        }
120    }
121}
122
123/// Hit count for each command in the palette.
124/// We only account for commands triggered directly via command palette and not by e.g. keystrokes because
125/// if an user already knows a keystroke for a command, they are unlikely to use a command palette to look for it.
126#[derive(Default)]
127struct HitCounts(HashMap<String, usize>);
128
129impl CommandPaletteDelegate {
130    fn new(
131        command_palette: WeakView<CommandPalette>,
132        commands: Vec<Command>,
133        previous_focus_handle: FocusHandle,
134    ) -> Self {
135        Self {
136            command_palette,
137            all_commands: commands.clone(),
138            matches: vec![],
139            commands,
140            selected_ix: 0,
141            previous_focus_handle,
142        }
143    }
144}
145
146impl PickerDelegate for CommandPaletteDelegate {
147    type ListItem = ListItem;
148
149    fn placeholder_text(&self) -> Arc<str> {
150        "Execute a command...".into()
151    }
152
153    fn match_count(&self) -> usize {
154        self.matches.len()
155    }
156
157    fn selected_index(&self) -> usize {
158        self.selected_ix
159    }
160
161    fn set_selected_index(&mut self, ix: usize, _: &mut ViewContext<Picker<Self>>) {
162        self.selected_ix = ix;
163    }
164
165    fn update_matches(
166        &mut self,
167        query: String,
168        cx: &mut ViewContext<Picker<Self>>,
169    ) -> gpui::Task<()> {
170        let mut commands = self.all_commands.clone();
171
172        cx.spawn(move |picker, mut cx| async move {
173            cx.read_global::<HitCounts, _>(|hit_counts, _| {
174                commands.sort_by_key(|action| {
175                    (
176                        Reverse(hit_counts.0.get(&action.name).cloned()),
177                        action.name.clone(),
178                    )
179                });
180            })
181            .ok();
182
183            let candidates = commands
184                .iter()
185                .enumerate()
186                .map(|(ix, command)| StringMatchCandidate {
187                    id: ix,
188                    string: command.name.to_string(),
189                    char_bag: command.name.chars().collect(),
190                })
191                .collect::<Vec<_>>();
192            let mut matches = if query.is_empty() {
193                candidates
194                    .into_iter()
195                    .enumerate()
196                    .map(|(index, candidate)| StringMatch {
197                        candidate_id: index,
198                        string: candidate.string,
199                        positions: Vec::new(),
200                        score: 0.0,
201                    })
202                    .collect()
203            } else {
204                fuzzy::match_strings(
205                    &candidates,
206                    &query,
207                    true,
208                    10000,
209                    &Default::default(),
210                    cx.background_executor().clone(),
211                )
212                .await
213            };
214
215            let mut intercept_result = cx
216                .try_read_global(|interceptor: &CommandPaletteInterceptor, cx| {
217                    (interceptor)(&query, cx)
218                })
219                .flatten();
220
221            if *RELEASE_CHANNEL == ReleaseChannel::Dev {
222                if parse_zed_link(&query).is_some() {
223                    intercept_result = Some(CommandInterceptResult {
224                        action: OpenZedURL { url: query.clone() }.boxed_clone(),
225                        string: query.clone(),
226                        positions: vec![],
227                    })
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                });
247                matches.insert(
248                    0,
249                    StringMatch {
250                        candidate_id: commands.len() - 1,
251                        string,
252                        positions,
253                        score: 0.0,
254                    },
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(DismissEvent))
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        self.matches.clear();
288        self.commands.clear();
289        cx.update_global(|hit_counts: &mut HitCounts, _| {
290            *hit_counts.0.entry(command.name).or_default() += 1;
291        });
292        let action = command.action;
293        cx.focus(&self.previous_focus_handle);
294        cx.window_context()
295            .spawn(move |mut cx| async move { cx.update(|_, cx| cx.dispatch_action(action)) })
296            .detach_and_log_err(cx);
297        self.dismissed(cx);
298    }
299
300    fn render_match(
301        &self,
302        ix: usize,
303        selected: bool,
304        cx: &mut ViewContext<Picker<Self>>,
305    ) -> Option<Self::ListItem> {
306        let r#match = self.matches.get(ix)?;
307        let command = self.commands.get(r#match.candidate_id)?;
308        Some(
309            ListItem::new(ix)
310                .inset(true)
311                .spacing(ListItemSpacing::Sparse)
312                .selected(selected)
313                .child(
314                    h_stack()
315                        .w_full()
316                        .justify_between()
317                        .child(HighlightedLabel::new(
318                            command.name.clone(),
319                            r#match.positions.clone(),
320                        ))
321                        .children(KeyBinding::for_action_in(
322                            &*command.action,
323                            &self.previous_focus_handle,
324                            cx,
325                        )),
326                ),
327        )
328    }
329}
330
331fn humanize_action_name(name: &str) -> String {
332    let capacity = name.len() + name.chars().filter(|c| c.is_uppercase()).count();
333    let mut result = String::with_capacity(capacity);
334    for char in name.chars() {
335        if char == ':' {
336            if result.ends_with(':') {
337                result.push(' ');
338            } else {
339                result.push(':');
340            }
341        } else if char == '_' {
342            result.push(' ');
343        } else if char.is_uppercase() {
344            if !result.ends_with(' ') {
345                result.push(' ');
346            }
347            result.extend(char.to_lowercase());
348        } else {
349            result.push(char);
350        }
351    }
352    result
353}
354
355impl std::fmt::Debug for Command {
356    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
357        f.debug_struct("Command")
358            .field("name", &self.name)
359            .finish_non_exhaustive()
360    }
361}
362
363#[cfg(test)]
364mod tests {
365    use std::sync::Arc;
366
367    use super::*;
368    use editor::Editor;
369    use go_to_line::GoToLine;
370    use gpui::TestAppContext;
371    use language::Point;
372    use project::Project;
373    use settings::KeymapFile;
374    use workspace::{AppState, Workspace};
375
376    #[test]
377    fn test_humanize_action_name() {
378        assert_eq!(
379            humanize_action_name("editor::GoToDefinition"),
380            "editor: go to definition"
381        );
382        assert_eq!(
383            humanize_action_name("editor::Backspace"),
384            "editor: backspace"
385        );
386        assert_eq!(
387            humanize_action_name("go_to_line::Deploy"),
388            "go to line: deploy"
389        );
390    }
391
392    #[gpui::test]
393    async fn test_command_palette(cx: &mut TestAppContext) {
394        let app_state = init_test(cx);
395        let project = Project::test(app_state.fs.clone(), [], cx).await;
396        let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
397
398        let editor = cx.new_view(|cx| {
399            let mut editor = Editor::single_line(cx);
400            editor.set_text("abc", cx);
401            editor
402        });
403
404        workspace.update(cx, |workspace, cx| {
405            workspace.add_item(Box::new(editor.clone()), cx);
406            editor.update(cx, |editor, cx| editor.focus(cx))
407        });
408
409        cx.simulate_keystrokes("cmd-shift-p");
410
411        let palette = workspace.update(cx, |workspace, cx| {
412            workspace
413                .active_modal::<CommandPalette>(cx)
414                .unwrap()
415                .read(cx)
416                .picker
417                .clone()
418        });
419
420        palette.update(cx, |palette, _| {
421            assert!(palette.delegate.commands.len() > 5);
422            let is_sorted =
423                |actions: &[Command]| actions.windows(2).all(|pair| pair[0].name <= pair[1].name);
424            assert!(is_sorted(&palette.delegate.commands));
425        });
426
427        cx.simulate_input("bcksp");
428
429        palette.update(cx, |palette, _| {
430            assert_eq!(palette.delegate.matches[0].string, "editor: backspace");
431        });
432
433        cx.simulate_keystrokes("enter");
434
435        workspace.update(cx, |workspace, cx| {
436            assert!(workspace.active_modal::<CommandPalette>(cx).is_none());
437            assert_eq!(editor.read(cx).text(cx), "ab")
438        });
439
440        // Add namespace filter, and redeploy the palette
441        cx.update(|cx| {
442            cx.set_global(CommandPaletteFilter::default());
443            cx.update_global::<CommandPaletteFilter, _>(|filter, _| {
444                filter.hidden_namespaces.insert("editor");
445            })
446        });
447
448        cx.simulate_keystrokes("cmd-shift-p");
449        cx.simulate_input("bcksp");
450
451        let palette = workspace.update(cx, |workspace, cx| {
452            workspace
453                .active_modal::<CommandPalette>(cx)
454                .unwrap()
455                .read(cx)
456                .picker
457                .clone()
458        });
459        palette.update(cx, |palette, _| {
460            assert!(palette.delegate.matches.is_empty())
461        });
462    }
463
464    #[gpui::test]
465    async fn test_go_to_line(cx: &mut TestAppContext) {
466        let app_state = init_test(cx);
467        let project = Project::test(app_state.fs.clone(), [], cx).await;
468        let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
469
470        cx.simulate_keystrokes("cmd-n");
471
472        let editor = workspace.update(cx, |workspace, cx| {
473            workspace.active_item_as::<Editor>(cx).unwrap()
474        });
475        editor.update(cx, |editor, cx| editor.set_text("1\n2\n3\n4\n5\n6\n", cx));
476
477        cx.simulate_keystrokes("cmd-shift-p");
478        cx.simulate_input("go to line: Toggle");
479        cx.simulate_keystrokes("enter");
480
481        workspace.update(cx, |workspace, cx| {
482            assert!(workspace.active_modal::<GoToLine>(cx).is_some())
483        });
484
485        cx.simulate_keystrokes("3 enter");
486
487        editor.update(cx, |editor, cx| {
488            assert!(editor.focus_handle(cx).is_focused(cx));
489            assert_eq!(
490                editor.selections.last::<Point>(cx).range().start,
491                Point::new(2, 0)
492            );
493        });
494    }
495
496    fn init_test(cx: &mut TestAppContext) -> Arc<AppState> {
497        cx.update(|cx| {
498            let app_state = AppState::test(cx);
499            theme::init(theme::LoadThemes::JustBase, cx);
500            language::init(cx);
501            editor::init(cx);
502            menu::init();
503            go_to_line::init(cx);
504            workspace::init(app_state.clone(), cx);
505            init(cx);
506            Project::init_settings(cx);
507            KeymapFile::parse(
508                r#"[
509                    {
510                        "bindings": {
511                            "cmd-n": "workspace::NewFile",
512                            "enter": "menu::Confirm",
513                            "cmd-shift-p": "command_palette::Toggle"
514                        }
515                    }
516                ]"#,
517            )
518            .unwrap()
519            .add_to_cx(cx)
520            .unwrap();
521            app_state
522        })
523    }
524}