1use collections::{CommandPaletteFilter, HashMap};
2use fuzzy::{StringMatch, StringMatchCandidate};
3use gpui::{
4 actions, div, prelude::*, Action, AppContext, Component, Div, EventEmitter, FocusHandle,
5 Keystroke, ParentComponent, Render, Styled, View, ViewContext, VisualContext, WeakView,
6 WindowContext,
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::{Modal, ModalEvent, 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 = 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<ModalEvent> for CommandPalette {}
73impl Modal for CommandPalette {
74 fn focus(&self, cx: &mut WindowContext) {
75 self.picker.update(cx, |picker, cx| picker.focus(cx));
76 }
77}
78
79impl Render for CommandPalette {
80 type Element = Div<Self>;
81
82 fn render(&mut self, _cx: &mut ViewContext<Self>) -> Self::Element {
83 v_stack().w_96().child(self.picker.clone())
84 }
85}
86
87pub type CommandPaletteInterceptor =
88 Box<dyn Fn(&str, &AppContext) -> Option<CommandInterceptResult>>;
89
90pub struct CommandInterceptResult {
91 pub action: Box<dyn Action>,
92 pub string: String,
93 pub positions: Vec<usize>,
94}
95
96pub struct CommandPaletteDelegate {
97 command_palette: WeakView<CommandPalette>,
98 commands: Vec<Command>,
99 matches: Vec<StringMatch>,
100 selected_ix: usize,
101 previous_focus_handle: FocusHandle,
102}
103
104struct Command {
105 name: String,
106 action: Box<dyn Action>,
107 keystrokes: Vec<Keystroke>,
108}
109
110impl Clone for Command {
111 fn clone(&self) -> Self {
112 Self {
113 name: self.name.clone(),
114 action: self.action.boxed_clone(),
115 keystrokes: self.keystrokes.clone(),
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 = Div<Picker<Self>>;
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(ModalEvent::Dismissed))
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 ) -> Self::ListItem {
296 let colors = cx.theme().colors();
297 let Some(r#match) = self.matches.get(ix) else {
298 return div();
299 };
300 let Some(command) = self.commands.get(r#match.candidate_id) else {
301 return div();
302 };
303
304 div()
305 .px_1()
306 .text_color(colors.text)
307 .text_ui()
308 .bg(colors.ghost_element_background)
309 .rounded_md()
310 .when(selected, |this| this.bg(colors.ghost_element_selected))
311 .hover(|this| this.bg(colors.ghost_element_hover))
312 .child(
313 h_stack()
314 .justify_between()
315 .child(HighlightedLabel::new(
316 command.name.clone(),
317 r#match.positions.clone(),
318 ))
319 .children(KeyBinding::for_action(&*command.action, cx)),
320 )
321 }
322}
323
324fn humanize_action_name(name: &str) -> String {
325 let capacity = name.len() + name.chars().filter(|c| c.is_uppercase()).count();
326 let mut result = String::with_capacity(capacity);
327 for char in name.chars() {
328 if char == ':' {
329 if result.ends_with(':') {
330 result.push(' ');
331 } else {
332 result.push(':');
333 }
334 } else if char == '_' {
335 result.push(' ');
336 } else if char.is_uppercase() {
337 if !result.ends_with(' ') {
338 result.push(' ');
339 }
340 result.extend(char.to_lowercase());
341 } else {
342 result.push(char);
343 }
344 }
345 result
346}
347
348impl std::fmt::Debug for Command {
349 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
350 f.debug_struct("Command")
351 .field("name", &self.name)
352 .field("keystrokes", &self.keystrokes)
353 .finish()
354 }
355}
356
357#[cfg(test)]
358mod tests {
359 use std::sync::Arc;
360
361 use super::*;
362 use editor::Editor;
363 use gpui::TestAppContext;
364 use project::Project;
365 use workspace::{AppState, Workspace};
366
367 #[test]
368 fn test_humanize_action_name() {
369 assert_eq!(
370 humanize_action_name("editor::GoToDefinition"),
371 "editor: go to definition"
372 );
373 assert_eq!(
374 humanize_action_name("editor::Backspace"),
375 "editor: backspace"
376 );
377 assert_eq!(
378 humanize_action_name("go_to_line::Deploy"),
379 "go to line: deploy"
380 );
381 }
382
383 #[gpui::test]
384 async fn test_command_palette(cx: &mut TestAppContext) {
385 let app_state = init_test(cx);
386
387 let project = Project::test(app_state.fs.clone(), [], cx).await;
388 let (workspace, mut cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
389 let cx = &mut cx;
390
391 let editor = cx.build_view(|cx| {
392 let mut editor = Editor::single_line(cx);
393 editor.set_text("abc", cx);
394 editor
395 });
396
397 workspace.update(cx, |workspace, cx| {
398 workspace.add_item(Box::new(editor.clone()), cx);
399 editor.update(cx, |editor, cx| editor.focus(cx))
400 });
401
402 cx.simulate_keystrokes("cmd-shift-p");
403
404 let palette = workspace.update(cx, |workspace, cx| {
405 workspace
406 .current_modal::<CommandPalette>(cx)
407 .unwrap()
408 .read(cx)
409 .picker
410 .clone()
411 });
412
413 palette.update(cx, |palette, _| {
414 assert!(palette.delegate.commands.len() > 5);
415 let is_sorted =
416 |actions: &[Command]| actions.windows(2).all(|pair| pair[0].name <= pair[1].name);
417 assert!(is_sorted(&palette.delegate.commands));
418 });
419
420 cx.simulate_keystrokes("b c k s p");
421
422 palette.update(cx, |palette, _| {
423 assert_eq!(palette.delegate.matches[0].string, "editor: backspace");
424 });
425
426 cx.simulate_keystrokes("enter");
427
428 workspace.update(cx, |workspace, cx| {
429 assert!(workspace.current_modal::<CommandPalette>(cx).is_none());
430 assert_eq!(editor.read(cx).text(cx), "ab")
431 });
432
433 // Add namespace filter, and redeploy the palette
434 cx.update(|cx| {
435 cx.set_global(CommandPaletteFilter::default());
436 cx.update_global::<CommandPaletteFilter, _>(|filter, _| {
437 filter.filtered_namespaces.insert("editor");
438 })
439 });
440
441 cx.simulate_keystrokes("cmd-shift-p");
442 cx.simulate_keystrokes("b c k s p");
443
444 let palette = workspace.update(cx, |workspace, cx| {
445 workspace
446 .current_modal::<CommandPalette>(cx)
447 .unwrap()
448 .read(cx)
449 .picker
450 .clone()
451 });
452 palette.update(cx, |palette, _| {
453 assert!(palette.delegate.matches.is_empty())
454 });
455 }
456
457 fn init_test(cx: &mut TestAppContext) -> Arc<AppState> {
458 cx.update(|cx| {
459 let app_state = AppState::test(cx);
460 theme::init(cx);
461 language::init(cx);
462 editor::init(cx);
463 workspace::init(app_state.clone(), cx);
464 init(cx);
465 Project::init_settings(cx);
466 settings::load_default_keymap(cx);
467 app_state
468 })
469 }
470}