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, 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.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)
312                .inset(true)
313                .spacing(ListItemSpacing::Sparse)
314                .selected(selected)
315                .child(
316                    h_stack()
317                        .w_full()
318                        .justify_between()
319                        .child(HighlightedLabel::new(
320                            command.name.clone(),
321                            r#match.positions.clone(),
322                        ))
323                        .children(KeyBinding::for_action_in(
324                            &*command.action,
325                            &self.previous_focus_handle,
326                            cx,
327                        )),
328                ),
329        )
330    }
331}
332
333fn humanize_action_name(name: &str) -> String {
334    let capacity = name.len() + name.chars().filter(|c| c.is_uppercase()).count();
335    let mut result = String::with_capacity(capacity);
336    for char in name.chars() {
337        if char == ':' {
338            if result.ends_with(':') {
339                result.push(' ');
340            } else {
341                result.push(':');
342            }
343        } else if char == '_' {
344            result.push(' ');
345        } else if char.is_uppercase() {
346            if !result.ends_with(' ') {
347                result.push(' ');
348            }
349            result.extend(char.to_lowercase());
350        } else {
351            result.push(char);
352        }
353    }
354    result
355}
356
357impl std::fmt::Debug for Command {
358    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
359        f.debug_struct("Command")
360            .field("name", &self.name)
361            .finish_non_exhaustive()
362    }
363}
364
365#[cfg(test)]
366mod tests {
367    use std::sync::Arc;
368
369    use super::*;
370    use editor::Editor;
371    use go_to_line::GoToLine;
372    use gpui::TestAppContext;
373    use language::Point;
374    use project::Project;
375    use workspace::{AppState, Workspace};
376
377    #[test]
378    fn test_humanize_action_name() {
379        assert_eq!(
380            humanize_action_name("editor::GoToDefinition"),
381            "editor: go to definition"
382        );
383        assert_eq!(
384            humanize_action_name("editor::Backspace"),
385            "editor: backspace"
386        );
387        assert_eq!(
388            humanize_action_name("go_to_line::Deploy"),
389            "go to line: deploy"
390        );
391    }
392
393    #[gpui::test]
394    async fn test_command_palette(cx: &mut TestAppContext) {
395        let app_state = init_test(cx);
396        let project = Project::test(app_state.fs.clone(), [], cx).await;
397        let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
398
399        let editor = cx.build_view(|cx| {
400            let mut editor = Editor::single_line(cx);
401            editor.set_text("abc", cx);
402            editor
403        });
404
405        workspace.update(cx, |workspace, cx| {
406            workspace.add_item(Box::new(editor.clone()), cx);
407            editor.update(cx, |editor, cx| editor.focus(cx))
408        });
409
410        cx.simulate_keystrokes("cmd-shift-p");
411
412        let palette = workspace.update(cx, |workspace, cx| {
413            workspace
414                .active_modal::<CommandPalette>(cx)
415                .unwrap()
416                .read(cx)
417                .picker
418                .clone()
419        });
420
421        palette.update(cx, |palette, _| {
422            assert!(palette.delegate.commands.len() > 5);
423            let is_sorted =
424                |actions: &[Command]| actions.windows(2).all(|pair| pair[0].name <= pair[1].name);
425            assert!(is_sorted(&palette.delegate.commands));
426        });
427
428        cx.simulate_input("bcksp");
429
430        palette.update(cx, |palette, _| {
431            assert_eq!(palette.delegate.matches[0].string, "editor: backspace");
432        });
433
434        cx.simulate_keystrokes("enter");
435
436        workspace.update(cx, |workspace, cx| {
437            assert!(workspace.active_modal::<CommandPalette>(cx).is_none());
438            assert_eq!(editor.read(cx).text(cx), "ab")
439        });
440
441        // Add namespace filter, and redeploy the palette
442        cx.update(|cx| {
443            cx.set_global(CommandPaletteFilter::default());
444            cx.update_global::<CommandPaletteFilter, _>(|filter, _| {
445                filter.hidden_namespaces.insert("editor");
446            })
447        });
448
449        cx.simulate_keystrokes("cmd-shift-p");
450        cx.simulate_input("bcksp");
451
452        let palette = workspace.update(cx, |workspace, cx| {
453            workspace
454                .active_modal::<CommandPalette>(cx)
455                .unwrap()
456                .read(cx)
457                .picker
458                .clone()
459        });
460        palette.update(cx, |palette, _| {
461            assert!(palette.delegate.matches.is_empty())
462        });
463    }
464
465    #[gpui::test]
466    async fn test_go_to_line(cx: &mut TestAppContext) {
467        let app_state = init_test(cx);
468        let project = Project::test(app_state.fs.clone(), [], cx).await;
469        let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
470
471        cx.simulate_keystrokes("cmd-n");
472
473        let editor = workspace.update(cx, |workspace, cx| {
474            workspace.active_item_as::<Editor>(cx).unwrap()
475        });
476        editor.update(cx, |editor, cx| editor.set_text("1\n2\n3\n4\n5\n6\n", cx));
477
478        cx.simulate_keystrokes("cmd-shift-p");
479        cx.simulate_input("go to line: Toggle");
480        cx.simulate_keystrokes("enter");
481
482        workspace.update(cx, |workspace, cx| {
483            assert!(workspace.active_modal::<GoToLine>(cx).is_some())
484        });
485
486        cx.simulate_keystrokes("3 enter");
487
488        editor.update(cx, |editor, cx| {
489            assert!(editor.focus_handle(cx).is_focused(cx));
490            assert_eq!(
491                editor.selections.last::<Point>(cx).range().start,
492                Point::new(2, 0)
493            );
494        });
495    }
496
497    fn init_test(cx: &mut TestAppContext) -> Arc<AppState> {
498        cx.update(|cx| {
499            let app_state = AppState::test(cx);
500            theme::init(theme::LoadThemes::JustBase, cx);
501            language::init(cx);
502            editor::init(cx);
503            menu::init();
504            go_to_line::init(cx);
505            workspace::init(app_state.clone(), cx);
506            init(cx);
507            Project::init_settings(cx);
508            settings::load_default_keymap(cx);
509            app_state
510        })
511    }
512}