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