1use collections::{CommandPaletteFilter, HashMap};
2use fuzzy::{StringMatch, StringMatchCandidate};
3use gpui::{
4 actions, div, Action, AppContext, Component, Div, EventEmitter, FocusHandle, Keystroke,
5 ParentElement, Render, StatelessInteractive, Styled, View, ViewContext, VisualContext,
6 WeakView, WindowContext,
7};
8use picker::{Picker, PickerDelegate};
9use std::cmp::{self, Reverse};
10use theme::ActiveTheme;
11use ui::{modal, Label};
12use util::{
13 channel::{parse_zed_link, ReleaseChannel, RELEASE_CHANNEL},
14 ResultExt,
15};
16use workspace::{Modal, ModalEvent, Workspace};
17use zed_actions::OpenZedURL;
18
19actions!(Toggle);
20
21pub fn init(cx: &mut AppContext) {
22 cx.set_global(HitCounts::default());
23 cx.observe_new_views(CommandPalette::register).detach();
24}
25
26pub struct CommandPalette {
27 picker: View<Picker<CommandPaletteDelegate>>,
28}
29
30impl CommandPalette {
31 fn register(workspace: &mut Workspace, _: &mut ViewContext<Workspace>) {
32 workspace.register_action(|workspace, _: &Toggle, cx| {
33 let Some(previous_focus_handle) = cx.focused() else {
34 return;
35 };
36 workspace.toggle_modal(cx, move |cx| CommandPalette::new(previous_focus_handle, cx));
37 });
38 }
39
40 fn new(previous_focus_handle: FocusHandle, cx: &mut ViewContext<Self>) -> Self {
41 let filter = cx.try_global::<CommandPaletteFilter>();
42
43 let commands = cx
44 .available_actions()
45 .into_iter()
46 .filter_map(|action| {
47 let name = action.name();
48 let namespace = name.split("::").next().unwrap_or("malformed action name");
49 if filter.is_some_and(|f| f.filtered_namespaces.contains(namespace)) {
50 return None;
51 }
52
53 Some(Command {
54 name: humanize_action_name(&name),
55 action,
56 keystrokes: vec![], // todo!()
57 })
58 })
59 .collect();
60
61 let delegate =
62 CommandPaletteDelegate::new(cx.view().downgrade(), commands, previous_focus_handle);
63
64 let picker = cx.build_view(|cx| Picker::new(delegate, cx));
65 Self { picker }
66 }
67}
68
69impl EventEmitter<ModalEvent> for CommandPalette {}
70impl Modal for CommandPalette {
71 fn focus(&self, cx: &mut WindowContext) {
72 self.picker.update(cx, |picker, cx| picker.focus(cx));
73 }
74}
75
76impl Render for CommandPalette {
77 type Element = Div<Self>;
78
79 fn render(&mut self, cx: &mut ViewContext<Self>) -> Self::Element {
80 modal(cx).w_96().child(self.picker.clone())
81 }
82}
83
84pub type CommandPaletteInterceptor =
85 Box<dyn Fn(&str, &AppContext) -> Option<CommandInterceptResult>>;
86
87pub struct CommandInterceptResult {
88 pub action: Box<dyn Action>,
89 pub string: String,
90 pub positions: Vec<usize>,
91}
92
93pub struct CommandPaletteDelegate {
94 command_palette: WeakView<CommandPalette>,
95 commands: Vec<Command>,
96 matches: Vec<StringMatch>,
97 selected_ix: usize,
98 previous_focus_handle: FocusHandle,
99}
100
101struct Command {
102 name: String,
103 action: Box<dyn Action>,
104 keystrokes: Vec<Keystroke>,
105}
106
107impl Clone for Command {
108 fn clone(&self) -> Self {
109 Self {
110 name: self.name.clone(),
111 action: self.action.boxed_clone(),
112 keystrokes: self.keystrokes.clone(),
113 }
114 }
115}
116/// Hit count for each command in the palette.
117/// We only account for commands triggered directly via command palette and not by e.g. keystrokes because
118/// if an user already knows a keystroke for a command, they are unlikely to use a command palette to look for it.
119#[derive(Default)]
120struct HitCounts(HashMap<String, usize>);
121
122impl CommandPaletteDelegate {
123 fn new(
124 command_palette: WeakView<CommandPalette>,
125 commands: Vec<Command>,
126 previous_focus_handle: FocusHandle,
127 ) -> Self {
128 Self {
129 command_palette,
130 matches: commands
131 .iter()
132 .enumerate()
133 .map(|(i, command)| StringMatch {
134 candidate_id: i,
135 string: command.name.clone(),
136 positions: Vec::new(),
137 score: 0.0,
138 })
139 .collect(),
140 commands,
141 selected_ix: 0,
142 previous_focus_handle,
143 }
144 }
145}
146
147impl PickerDelegate for CommandPaletteDelegate {
148 type ListItem = Div<Picker<Self>>;
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(ModalEvent::Dismissed))
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(command) = self
300 .matches
301 .get(ix)
302 .and_then(|m| self.commands.get(m.candidate_id))
303 else {
304 return div();
305 };
306
307 div()
308 .text_color(colors.text)
309 .when(selected, |s| {
310 s.border_l_10().border_color(colors.terminal_ansi_yellow)
311 })
312 .hover(|style| {
313 style
314 .bg(colors.element_active)
315 .text_color(colors.text_accent)
316 })
317 .child(Label::new(command.name.clone()))
318 }
319
320 // fn render_match(
321 // &self,
322 // ix: usize,
323 // mouse_state: &mut MouseState,
324 // selected: bool,
325 // cx: &gpui::AppContext,
326 // ) -> AnyElement<Picker<Self>> {
327 // let mat = &self.matches[ix];
328 // let command = &self.actions[mat.candidate_id];
329 // let theme = theme::current(cx);
330 // let style = theme.picker.item.in_state(selected).style_for(mouse_state);
331 // let key_style = &theme.command_palette.key.in_state(selected);
332 // let keystroke_spacing = theme.command_palette.keystroke_spacing;
333
334 // Flex::row()
335 // .with_child(
336 // Label::new(mat.string.clone(), style.label.clone())
337 // .with_highlights(mat.positions.clone()),
338 // )
339 // .with_children(command.keystrokes.iter().map(|keystroke| {
340 // Flex::row()
341 // .with_children(
342 // [
343 // (keystroke.ctrl, "^"),
344 // (keystroke.alt, "⌥"),
345 // (keystroke.cmd, "⌘"),
346 // (keystroke.shift, "⇧"),
347 // ]
348 // .into_iter()
349 // .filter_map(|(modifier, label)| {
350 // if modifier {
351 // Some(
352 // Label::new(label, key_style.label.clone())
353 // .contained()
354 // .with_style(key_style.container),
355 // )
356 // } else {
357 // None
358 // }
359 // }),
360 // )
361 // .with_child(
362 // Label::new(keystroke.key.clone(), key_style.label.clone())
363 // .contained()
364 // .with_style(key_style.container),
365 // )
366 // .contained()
367 // .with_margin_left(keystroke_spacing)
368 // .flex_float()
369 // }))
370 // .contained()
371 // .with_style(style.container)
372 // .into_any()
373 // }
374}
375
376fn humanize_action_name(name: &str) -> String {
377 let capacity = name.len() + name.chars().filter(|c| c.is_uppercase()).count();
378 let mut result = String::with_capacity(capacity);
379 for char in name.chars() {
380 if char == ':' {
381 if result.ends_with(':') {
382 result.push(' ');
383 } else {
384 result.push(':');
385 }
386 } else if char == '_' {
387 result.push(' ');
388 } else if char.is_uppercase() {
389 if !result.ends_with(' ') {
390 result.push(' ');
391 }
392 result.extend(char.to_lowercase());
393 } else {
394 result.push(char);
395 }
396 }
397 result
398}
399
400impl std::fmt::Debug for Command {
401 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
402 f.debug_struct("Command")
403 .field("name", &self.name)
404 .field("keystrokes", &self.keystrokes)
405 .finish()
406 }
407}
408
409// #[cfg(test)]
410// mod tests {
411// use std::sync::Arc;
412
413// use super::*;
414// use editor::Editor;
415// use gpui::{executor::Deterministic, TestAppContext};
416// use project::Project;
417// use workspace::{AppState, Workspace};
418
419// #[test]
420// fn test_humanize_action_name() {
421// assert_eq!(
422// humanize_action_name("editor::GoToDefinition"),
423// "editor: go to definition"
424// );
425// assert_eq!(
426// humanize_action_name("editor::Backspace"),
427// "editor: backspace"
428// );
429// assert_eq!(
430// humanize_action_name("go_to_line::Deploy"),
431// "go to line: deploy"
432// );
433// }
434
435// #[gpui::test]
436// async fn test_command_palette(deterministic: Arc<Deterministic>, cx: &mut TestAppContext) {
437// let app_state = init_test(cx);
438
439// let project = Project::test(app_state.fs.clone(), [], cx).await;
440// let window = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
441// let workspace = window.root(cx);
442// let editor = window.add_view(cx, |cx| {
443// let mut editor = Editor::single_line(None, cx);
444// editor.set_text("abc", cx);
445// editor
446// });
447
448// workspace.update(cx, |workspace, cx| {
449// cx.focus(&editor);
450// workspace.add_item(Box::new(editor.clone()), cx)
451// });
452
453// workspace.update(cx, |workspace, cx| {
454// toggle_command_palette(workspace, &Toggle, cx);
455// });
456
457// let palette = workspace.read_with(cx, |workspace, _| {
458// workspace.modal::<CommandPalette>().unwrap()
459// });
460
461// palette
462// .update(cx, |palette, cx| {
463// // Fill up palette's command list by running an empty query;
464// // we only need it to subsequently assert that the palette is initially
465// // sorted by command's name.
466// palette.delegate_mut().update_matches("".to_string(), cx)
467// })
468// .await;
469
470// palette.update(cx, |palette, _| {
471// let is_sorted =
472// |actions: &[Command]| actions.windows(2).all(|pair| pair[0].name <= pair[1].name);
473// assert!(is_sorted(&palette.delegate().actions));
474// });
475
476// palette
477// .update(cx, |palette, cx| {
478// palette
479// .delegate_mut()
480// .update_matches("bcksp".to_string(), cx)
481// })
482// .await;
483
484// palette.update(cx, |palette, cx| {
485// assert_eq!(palette.delegate().matches[0].string, "editor: backspace");
486// palette.confirm(&Default::default(), cx);
487// });
488// deterministic.run_until_parked();
489// editor.read_with(cx, |editor, cx| {
490// assert_eq!(editor.text(cx), "ab");
491// });
492
493// // Add namespace filter, and redeploy the palette
494// cx.update(|cx| {
495// cx.update_default_global::<CommandPaletteFilter, _, _>(|filter, _| {
496// filter.filtered_namespaces.insert("editor");
497// })
498// });
499
500// workspace.update(cx, |workspace, cx| {
501// toggle_command_palette(workspace, &Toggle, cx);
502// });
503
504// // Assert editor command not present
505// let palette = workspace.read_with(cx, |workspace, _| {
506// workspace.modal::<CommandPalette>().unwrap()
507// });
508
509// palette
510// .update(cx, |palette, cx| {
511// palette
512// .delegate_mut()
513// .update_matches("bcksp".to_string(), cx)
514// })
515// .await;
516
517// palette.update(cx, |palette, _| {
518// assert!(palette.delegate().matches.is_empty())
519// });
520// }
521
522// fn init_test(cx: &mut TestAppContext) -> Arc<AppState> {
523// cx.update(|cx| {
524// let app_state = AppState::test(cx);
525// theme::init(cx);
526// language::init(cx);
527// editor::init(cx);
528// workspace::init(app_state.clone(), cx);
529// init(cx);
530// Project::init_settings(cx);
531// app_state
532// })
533// }
534// }