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(&*command.action, cx)),
315 ),
316 )
317 }
318}
319
320fn humanize_action_name(name: &str) -> String {
321 let capacity = name.len() + name.chars().filter(|c| c.is_uppercase()).count();
322 let mut result = String::with_capacity(capacity);
323 for char in name.chars() {
324 if char == ':' {
325 if result.ends_with(':') {
326 result.push(' ');
327 } else {
328 result.push(':');
329 }
330 } else if char == '_' {
331 result.push(' ');
332 } else if char.is_uppercase() {
333 if !result.ends_with(' ') {
334 result.push(' ');
335 }
336 result.extend(char.to_lowercase());
337 } else {
338 result.push(char);
339 }
340 }
341 result
342}
343
344impl std::fmt::Debug for Command {
345 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
346 f.debug_struct("Command")
347 .field("name", &self.name)
348 .field("keystrokes", &self.keystrokes)
349 .finish()
350 }
351}
352
353#[cfg(test)]
354mod tests {
355 use std::sync::Arc;
356
357 use super::*;
358 use editor::Editor;
359 use gpui::TestAppContext;
360 use project::Project;
361 use workspace::{AppState, Workspace};
362
363 #[test]
364 fn test_humanize_action_name() {
365 assert_eq!(
366 humanize_action_name("editor::GoToDefinition"),
367 "editor: go to definition"
368 );
369 assert_eq!(
370 humanize_action_name("editor::Backspace"),
371 "editor: backspace"
372 );
373 assert_eq!(
374 humanize_action_name("go_to_line::Deploy"),
375 "go to line: deploy"
376 );
377 }
378
379 #[gpui::test]
380 async fn test_command_palette(cx: &mut TestAppContext) {
381 let app_state = init_test(cx);
382
383 let project = Project::test(app_state.fs.clone(), [], cx).await;
384 let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
385
386 let editor = cx.build_view(|cx| {
387 let mut editor = Editor::single_line(cx);
388 editor.set_text("abc", cx);
389 editor
390 });
391
392 workspace.update(cx, |workspace, cx| {
393 workspace.add_item(Box::new(editor.clone()), cx);
394 editor.update(cx, |editor, cx| editor.focus(cx))
395 });
396
397 cx.simulate_keystrokes("cmd-shift-p");
398
399 let palette = workspace.update(cx, |workspace, cx| {
400 workspace
401 .active_modal::<CommandPalette>(cx)
402 .unwrap()
403 .read(cx)
404 .picker
405 .clone()
406 });
407
408 palette.update(cx, |palette, _| {
409 assert!(palette.delegate.commands.len() > 5);
410 let is_sorted =
411 |actions: &[Command]| actions.windows(2).all(|pair| pair[0].name <= pair[1].name);
412 assert!(is_sorted(&palette.delegate.commands));
413 });
414
415 cx.simulate_input("bcksp");
416
417 palette.update(cx, |palette, _| {
418 assert_eq!(palette.delegate.matches[0].string, "editor: backspace");
419 });
420
421 cx.simulate_keystrokes("enter");
422
423 workspace.update(cx, |workspace, cx| {
424 assert!(workspace.active_modal::<CommandPalette>(cx).is_none());
425 assert_eq!(editor.read(cx).text(cx), "ab")
426 });
427
428 // Add namespace filter, and redeploy the palette
429 cx.update(|cx| {
430 cx.set_global(CommandPaletteFilter::default());
431 cx.update_global::<CommandPaletteFilter, _>(|filter, _| {
432 filter.filtered_namespaces.insert("editor");
433 })
434 });
435
436 cx.simulate_keystrokes("cmd-shift-p");
437 cx.simulate_input("bcksp");
438
439 let palette = workspace.update(cx, |workspace, cx| {
440 workspace
441 .active_modal::<CommandPalette>(cx)
442 .unwrap()
443 .read(cx)
444 .picker
445 .clone()
446 });
447 palette.update(cx, |palette, _| {
448 assert!(palette.delegate.matches.is_empty())
449 });
450 }
451
452 fn init_test(cx: &mut TestAppContext) -> Arc<AppState> {
453 cx.update(|cx| {
454 let app_state = AppState::test(cx);
455 theme::init(theme::LoadThemes::JustBase, cx);
456 language::init(cx);
457 editor::init(cx);
458 workspace::init(app_state.clone(), cx);
459 init(cx);
460 Project::init_settings(cx);
461 settings::load_default_keymap(cx);
462 app_state
463 })
464 }
465}