command_palette.rs

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