command_palette.rs

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