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