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::{ModalView, Workspace};
 20use zed_actions::OpenZedURL;
 21
 22actions!(Toggle);
 23
 24pub fn init(cx: &mut AppContext) {
 25    cx.set_global(HitCounts::default());
 26    cx.observe_new_views(CommandPalette::register).detach();
 27}
 28
 29impl ModalView for CommandPalette {}
 30
 31pub struct CommandPalette {
 32    picker: View<Picker<CommandPaletteDelegate>>,
 33}
 34
 35impl CommandPalette {
 36    fn register(workspace: &mut Workspace, _: &mut ViewContext<Workspace>) {
 37        workspace.register_action(|workspace, _: &Toggle, cx| {
 38            let Some(previous_focus_handle) = cx.focused() else {
 39                return;
 40            };
 41            workspace.toggle_modal(cx, move |cx| CommandPalette::new(previous_focus_handle, cx));
 42        });
 43    }
 44
 45    fn new(previous_focus_handle: FocusHandle, cx: &mut ViewContext<Self>) -> Self {
 46        let filter = cx.try_global::<CommandPaletteFilter>();
 47
 48        let commands = cx
 49            .available_actions()
 50            .into_iter()
 51            .filter_map(|action| {
 52                let name = gpui::remove_the_2(action.name());
 53                let namespace = name.split("::").next().unwrap_or("malformed action name");
 54                if filter.is_some_and(|f| {
 55                    f.hidden_namespaces.contains(namespace)
 56                        || f.hidden_action_types.contains(&action.type_id())
 57                }) {
 58                    return None;
 59                }
 60
 61                Some(Command {
 62                    name: humanize_action_name(&name),
 63                    action,
 64                    keystrokes: vec![], // todo!()
 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    commands: Vec<Command>,
105    matches: Vec<StringMatch>,
106    selected_ix: usize,
107    previous_focus_handle: FocusHandle,
108}
109
110struct Command {
111    name: String,
112    action: Box<dyn Action>,
113    keystrokes: Vec<Keystroke>,
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            keystrokes: self.keystrokes.clone(),
122        }
123    }
124}
125
126/// Hit count for each command in the palette.
127/// We only account for commands triggered directly via command palette and not by e.g. keystrokes because
128/// if an user already knows a keystroke for a command, they are unlikely to use a command palette to look for it.
129#[derive(Default)]
130struct HitCounts(HashMap<String, usize>);
131
132impl CommandPaletteDelegate {
133    fn new(
134        command_palette: WeakView<CommandPalette>,
135        commands: Vec<Command>,
136        previous_focus_handle: FocusHandle,
137    ) -> Self {
138        Self {
139            command_palette,
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.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            if let Some(CommandInterceptResult {
233                action,
234                string,
235                positions,
236            }) = intercept_result
237            {
238                if let Some(idx) = matches
239                    .iter()
240                    .position(|m| commands[m.candidate_id].action.type_id() == action.type_id())
241                {
242                    matches.remove(idx);
243                }
244                commands.push(Command {
245                    name: string.clone(),
246                    action,
247                    keystrokes: vec![],
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            picker
260                .update(&mut cx, |picker, _| {
261                    let delegate = &mut picker.delegate;
262                    delegate.commands = commands;
263                    delegate.matches = matches;
264                    if delegate.matches.is_empty() {
265                        delegate.selected_ix = 0;
266                    } else {
267                        delegate.selected_ix =
268                            cmp::min(delegate.selected_ix, delegate.matches.len() - 1);
269                    }
270                })
271                .log_err();
272        })
273    }
274
275    fn dismissed(&mut self, cx: &mut ViewContext<Picker<Self>>) {
276        self.command_palette
277            .update(cx, |_, cx| cx.emit(DismissEvent))
278            .log_err();
279    }
280
281    fn confirm(&mut self, _: bool, cx: &mut ViewContext<Picker<Self>>) {
282        if self.matches.is_empty() {
283            self.dismissed(cx);
284            return;
285        }
286        let action_ix = self.matches[self.selected_ix].candidate_id;
287        let command = self.commands.swap_remove(action_ix);
288        cx.update_global(|hit_counts: &mut HitCounts, _| {
289            *hit_counts.0.entry(command.name).or_default() += 1;
290        });
291        let action = command.action;
292        cx.focus(&self.previous_focus_handle);
293        cx.dispatch_action(action);
294        self.dismissed(cx);
295    }
296
297    fn render_match(
298        &self,
299        ix: usize,
300        selected: bool,
301        cx: &mut ViewContext<Picker<Self>>,
302    ) -> Option<Self::ListItem> {
303        let Some(r#match) = self.matches.get(ix) else {
304            return None;
305        };
306        let Some(command) = self.commands.get(r#match.candidate_id) else {
307            return None;
308        };
309
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            .field("keystrokes", &self.keystrokes)
358            .finish()
359    }
360}
361
362#[cfg(test)]
363mod tests {
364    use std::sync::Arc;
365
366    use super::*;
367    use editor::Editor;
368    use gpui::TestAppContext;
369    use project::Project;
370    use workspace::{AppState, Workspace};
371
372    #[test]
373    fn test_humanize_action_name() {
374        assert_eq!(
375            humanize_action_name("editor::GoToDefinition"),
376            "editor: go to definition"
377        );
378        assert_eq!(
379            humanize_action_name("editor::Backspace"),
380            "editor: backspace"
381        );
382        assert_eq!(
383            humanize_action_name("go_to_line::Deploy"),
384            "go to line: deploy"
385        );
386    }
387
388    #[gpui::test]
389    async fn test_command_palette(cx: &mut TestAppContext) {
390        let app_state = init_test(cx);
391
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    fn init_test(cx: &mut TestAppContext) -> Arc<AppState> {
462        cx.update(|cx| {
463            let app_state = AppState::test(cx);
464            theme::init(theme::LoadThemes::JustBase, cx);
465            language::init(cx);
466            editor::init(cx);
467            workspace::init(app_state.clone(), cx);
468            init(cx);
469            Project::init_settings(cx);
470            settings::load_default_keymap(cx);
471            app_state
472        })
473    }
474}