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