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    Keystroke, 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::Workspace;
 20use zed_actions::OpenZedURL;
 21
 22actions!(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
 30pub struct CommandPalette {
 31    picker: View<Picker<CommandPaletteDelegate>>,
 32}
 33
 34impl CommandPalette {
 35    fn register(workspace: &mut Workspace, _: &mut ViewContext<Workspace>) {
 36        workspace.register_action(|workspace, _: &Toggle, cx| {
 37            let Some(previous_focus_handle) = cx.focused() else {
 38                return;
 39            };
 40            workspace.toggle_modal(cx, move |cx| CommandPalette::new(previous_focus_handle, cx));
 41        });
 42    }
 43
 44    fn new(previous_focus_handle: FocusHandle, cx: &mut ViewContext<Self>) -> Self {
 45        let filter = cx.try_global::<CommandPaletteFilter>();
 46
 47        let commands = cx
 48            .available_actions()
 49            .into_iter()
 50            .filter_map(|action| {
 51                let name = gpui::remove_the_2(action.name());
 52                let namespace = name.split("::").next().unwrap_or("malformed action name");
 53                if filter.is_some_and(|f| {
 54                    f.hidden_namespaces.contains(namespace)
 55                        || f.hidden_action_types.contains(&action.type_id())
 56                }) {
 57                    return None;
 58                }
 59
 60                Some(Command {
 61                    name: humanize_action_name(&name),
 62                    action,
 63                    keystrokes: vec![], // todo!()
 64                })
 65            })
 66            .collect();
 67
 68        let delegate =
 69            CommandPaletteDelegate::new(cx.view().downgrade(), commands, previous_focus_handle);
 70
 71        let picker = cx.build_view(|cx| Picker::new(delegate, cx));
 72        Self { picker }
 73    }
 74}
 75
 76impl EventEmitter<DismissEvent> for CommandPalette {}
 77
 78impl FocusableView for CommandPalette {
 79    fn focus_handle(&self, cx: &AppContext) -> FocusHandle {
 80        self.picker.focus_handle(cx)
 81    }
 82}
 83
 84impl Render for CommandPalette {
 85    type Element = Div;
 86
 87    fn render(&mut self, _cx: &mut ViewContext<Self>) -> Self::Element {
 88        v_stack().w(rems(34.)).child(self.picker.clone())
 89    }
 90}
 91
 92pub type CommandPaletteInterceptor =
 93    Box<dyn Fn(&str, &AppContext) -> Option<CommandInterceptResult>>;
 94
 95pub struct CommandInterceptResult {
 96    pub action: Box<dyn Action>,
 97    pub string: String,
 98    pub positions: Vec<usize>,
 99}
100
101pub struct CommandPaletteDelegate {
102    command_palette: WeakView<CommandPalette>,
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    keystrokes: Vec<Keystroke>,
113}
114
115impl Clone for Command {
116    fn clone(&self) -> Self {
117        Self {
118            name: self.name.clone(),
119            action: self.action.boxed_clone(),
120            keystrokes: self.keystrokes.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            matches: vec![],
140            commands,
141            selected_ix: 0,
142            previous_focus_handle,
143        }
144    }
145}
146
147impl PickerDelegate for CommandPaletteDelegate {
148    type ListItem = ListItem;
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(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        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    ) -> Option<Self::ListItem> {
302        let Some(r#match) = self.matches.get(ix) else {
303            return None;
304        };
305        let Some(command) = self.commands.get(r#match.candidate_id) else {
306            return None;
307        };
308
309        Some(
310            ListItem::new(ix).inset(true).selected(selected).child(
311                h_stack()
312                    .w_full()
313                    .justify_between()
314                    .child(HighlightedLabel::new(
315                        command.name.clone(),
316                        r#match.positions.clone(),
317                    ))
318                    .children(KeyBinding::for_action_in(
319                        &*command.action,
320                        &self.previous_focus_handle,
321                        cx,
322                    )),
323            ),
324        )
325    }
326}
327
328fn humanize_action_name(name: &str) -> String {
329    let capacity = name.len() + name.chars().filter(|c| c.is_uppercase()).count();
330    let mut result = String::with_capacity(capacity);
331    for char in name.chars() {
332        if char == ':' {
333            if result.ends_with(':') {
334                result.push(' ');
335            } else {
336                result.push(':');
337            }
338        } else if char == '_' {
339            result.push(' ');
340        } else if char.is_uppercase() {
341            if !result.ends_with(' ') {
342                result.push(' ');
343            }
344            result.extend(char.to_lowercase());
345        } else {
346            result.push(char);
347        }
348    }
349    result
350}
351
352impl std::fmt::Debug for Command {
353    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
354        f.debug_struct("Command")
355            .field("name", &self.name)
356            .field("keystrokes", &self.keystrokes)
357            .finish()
358    }
359}
360
361#[cfg(test)]
362mod tests {
363    use std::sync::Arc;
364
365    use super::*;
366    use editor::Editor;
367    use gpui::TestAppContext;
368    use project::Project;
369    use workspace::{AppState, Workspace};
370
371    #[test]
372    fn test_humanize_action_name() {
373        assert_eq!(
374            humanize_action_name("editor::GoToDefinition"),
375            "editor: go to definition"
376        );
377        assert_eq!(
378            humanize_action_name("editor::Backspace"),
379            "editor: backspace"
380        );
381        assert_eq!(
382            humanize_action_name("go_to_line::Deploy"),
383            "go to line: deploy"
384        );
385    }
386
387    #[gpui::test]
388    async fn test_command_palette(cx: &mut TestAppContext) {
389        let app_state = init_test(cx);
390
391        let project = Project::test(app_state.fs.clone(), [], cx).await;
392        let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
393
394        let editor = cx.build_view(|cx| {
395            let mut editor = Editor::single_line(cx);
396            editor.set_text("abc", cx);
397            editor
398        });
399
400        workspace.update(cx, |workspace, cx| {
401            workspace.add_item(Box::new(editor.clone()), cx);
402            editor.update(cx, |editor, cx| editor.focus(cx))
403        });
404
405        cx.simulate_keystrokes("cmd-shift-p");
406
407        let palette = workspace.update(cx, |workspace, cx| {
408            workspace
409                .active_modal::<CommandPalette>(cx)
410                .unwrap()
411                .read(cx)
412                .picker
413                .clone()
414        });
415
416        palette.update(cx, |palette, _| {
417            assert!(palette.delegate.commands.len() > 5);
418            let is_sorted =
419                |actions: &[Command]| actions.windows(2).all(|pair| pair[0].name <= pair[1].name);
420            assert!(is_sorted(&palette.delegate.commands));
421        });
422
423        cx.simulate_input("bcksp");
424
425        palette.update(cx, |palette, _| {
426            assert_eq!(palette.delegate.matches[0].string, "editor: backspace");
427        });
428
429        cx.simulate_keystrokes("enter");
430
431        workspace.update(cx, |workspace, cx| {
432            assert!(workspace.active_modal::<CommandPalette>(cx).is_none());
433            assert_eq!(editor.read(cx).text(cx), "ab")
434        });
435
436        // Add namespace filter, and redeploy the palette
437        cx.update(|cx| {
438            cx.set_global(CommandPaletteFilter::default());
439            cx.update_global::<CommandPaletteFilter, _>(|filter, _| {
440                filter.hidden_namespaces.insert("editor");
441            })
442        });
443
444        cx.simulate_keystrokes("cmd-shift-p");
445        cx.simulate_input("bcksp");
446
447        let palette = workspace.update(cx, |workspace, cx| {
448            workspace
449                .active_modal::<CommandPalette>(cx)
450                .unwrap()
451                .read(cx)
452                .picker
453                .clone()
454        });
455        palette.update(cx, |palette, _| {
456            assert!(palette.delegate.matches.is_empty())
457        });
458    }
459
460    fn init_test(cx: &mut TestAppContext) -> Arc<AppState> {
461        cx.update(|cx| {
462            let app_state = AppState::test(cx);
463            theme::init(theme::LoadThemes::JustBase, cx);
464            language::init(cx);
465            editor::init(cx);
466            workspace::init(app_state.clone(), cx);
467            init(cx);
468            Project::init_settings(cx);
469            settings::load_default_keymap(cx);
470            app_state
471        })
472    }
473}