1use std::{
2 cmp::{self, Reverse},
3 sync::Arc,
4};
5
6use collections::{CommandPaletteFilter, HashMap};
7use fuzzy::{StringMatch, StringMatchCandidate};
8use gpui::{
9 actions, Action, AppContext, DismissEvent, Div, EventEmitter, FocusHandle, FocusableView,
10 Keystroke, ParentElement, Render, Styled, View, ViewContext, VisualContext, WeakView,
11};
12use picker::{Picker, PickerDelegate};
13
14use ui::{h_stack, prelude::*, v_stack, HighlightedLabel, KeyBinding, ListItem};
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<DismissEvent> 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;
82
83 fn render(&mut self, _cx: &mut ViewContext<Self>) -> Self::Element {
84 v_stack().min_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 = ListItem;
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(DismissEvent))
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 ) -> Option<Self::ListItem> {
298 let Some(r#match) = self.matches.get(ix) else {
299 return None;
300 };
301 let Some(command) = self.commands.get(r#match.candidate_id) else {
302 return None;
303 };
304
305 Some(
306 ListItem::new(ix).inset(true).selected(selected).child(
307 h_stack()
308 .w_full()
309 .justify_between()
310 .child(HighlightedLabel::new(
311 command.name.clone(),
312 r#match.positions.clone(),
313 ))
314 .children(KeyBinding::for_action_in(
315 &*command.action,
316 &self.previous_focus_handle,
317 cx,
318 )),
319 ),
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, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
389
390 let editor = cx.build_view(|cx| {
391 let mut editor = Editor::single_line(cx);
392 editor.set_text("abc", cx);
393 editor
394 });
395
396 workspace.update(cx, |workspace, cx| {
397 workspace.add_item(Box::new(editor.clone()), cx);
398 editor.update(cx, |editor, cx| editor.focus(cx))
399 });
400
401 cx.simulate_keystrokes("cmd-shift-p");
402
403 let palette = workspace.update(cx, |workspace, cx| {
404 workspace
405 .active_modal::<CommandPalette>(cx)
406 .unwrap()
407 .read(cx)
408 .picker
409 .clone()
410 });
411
412 palette.update(cx, |palette, _| {
413 assert!(palette.delegate.commands.len() > 5);
414 let is_sorted =
415 |actions: &[Command]| actions.windows(2).all(|pair| pair[0].name <= pair[1].name);
416 assert!(is_sorted(&palette.delegate.commands));
417 });
418
419 cx.simulate_input("bcksp");
420
421 palette.update(cx, |palette, _| {
422 assert_eq!(palette.delegate.matches[0].string, "editor: backspace");
423 });
424
425 cx.simulate_keystrokes("enter");
426
427 workspace.update(cx, |workspace, cx| {
428 assert!(workspace.active_modal::<CommandPalette>(cx).is_none());
429 assert_eq!(editor.read(cx).text(cx), "ab")
430 });
431
432 // Add namespace filter, and redeploy the palette
433 cx.update(|cx| {
434 cx.set_global(CommandPaletteFilter::default());
435 cx.update_global::<CommandPaletteFilter, _>(|filter, _| {
436 filter.filtered_namespaces.insert("editor");
437 })
438 });
439
440 cx.simulate_keystrokes("cmd-shift-p");
441 cx.simulate_input("bcksp");
442
443 let palette = workspace.update(cx, |workspace, cx| {
444 workspace
445 .active_modal::<CommandPalette>(cx)
446 .unwrap()
447 .read(cx)
448 .picker
449 .clone()
450 });
451 palette.update(cx, |palette, _| {
452 assert!(palette.delegate.matches.is_empty())
453 });
454 }
455
456 fn init_test(cx: &mut TestAppContext) -> Arc<AppState> {
457 cx.update(|cx| {
458 let app_state = AppState::test(cx);
459 theme::init(theme::LoadThemes::JustBase, cx);
460 language::init(cx);
461 editor::init(cx);
462 workspace::init(app_state.clone(), cx);
463 init(cx);
464 Project::init_settings(cx);
465 settings::load_default_keymap(cx);
466 app_state
467 })
468 }
469}