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 dbg!("registering command palette toggle");
36 workspace.register_action(|workspace, _: &Toggle, cx| {
37 dbg!("got cmd-shift-p");
38 let Some(previous_focus_handle) = cx.focused() else {
39 return;
40 };
41 workspace.toggle_modal(cx, move |cx| CommandPalette::new(previous_focus_handle, cx));
42 });
43 }
44
45 fn new(previous_focus_handle: FocusHandle, cx: &mut ViewContext<Self>) -> Self {
46 let filter = cx.try_global::<CommandPaletteFilter>();
47
48 let commands = cx
49 .available_actions()
50 .into_iter()
51 .filter_map(|action| {
52 let name = action.name();
53 let namespace = name.split("::").next().unwrap_or("malformed action name");
54 if filter.is_some_and(|f| f.filtered_namespaces.contains(namespace)) {
55 return None;
56 }
57
58 Some(Command {
59 name: humanize_action_name(&name),
60 action,
61 keystrokes: vec![], // todo!()
62 })
63 })
64 .collect();
65
66 let delegate =
67 CommandPaletteDelegate::new(cx.view().downgrade(), commands, previous_focus_handle);
68
69 let picker = cx.build_view(|cx| Picker::new(delegate, cx));
70 Self { picker }
71 }
72}
73
74impl EventEmitter<ModalEvent> for CommandPalette {}
75impl Modal for CommandPalette {
76 fn focus(&self, cx: &mut WindowContext) {
77 self.picker.update(cx, |picker, cx| picker.focus(cx));
78 }
79}
80
81impl Render for CommandPalette {
82 type Element = Div<Self>;
83
84 fn render(&mut self, _cx: &mut ViewContext<Self>) -> Self::Element {
85 v_stack().w_96().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/// 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 = Div<Picker<Self>>;
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(ModalEvent::Dismissed))
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 ) -> Self::ListItem {
298 let colors = cx.theme().colors();
299 let Some(r#match) = self.matches.get(ix) else {
300 return div();
301 };
302 let Some(command) = self.commands.get(r#match.candidate_id) else {
303 return div();
304 };
305
306 div()
307 .px_1()
308 .text_color(colors.text)
309 .text_ui()
310 .bg(colors.ghost_element_background)
311 .rounded_md()
312 .when(selected, |this| this.bg(colors.ghost_element_selected))
313 .hover(|this| this.bg(colors.ghost_element_hover))
314 .child(
315 h_stack()
316 .justify_between()
317 .child(HighlightedLabel::new(
318 command.name.clone(),
319 r#match.positions.clone(),
320 ))
321 .children(KeyBinding::for_action(&*command.action, cx)),
322 )
323 }
324}
325
326fn humanize_action_name(name: &str) -> String {
327 let capacity = name.len() + name.chars().filter(|c| c.is_uppercase()).count();
328 let mut result = String::with_capacity(capacity);
329 for char in name.chars() {
330 if char == ':' {
331 if result.ends_with(':') {
332 result.push(' ');
333 } else {
334 result.push(':');
335 }
336 } else if char == '_' {
337 result.push(' ');
338 } else if char.is_uppercase() {
339 if !result.ends_with(' ') {
340 result.push(' ');
341 }
342 result.extend(char.to_lowercase());
343 } else {
344 result.push(char);
345 }
346 }
347 result
348}
349
350impl std::fmt::Debug for Command {
351 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
352 f.debug_struct("Command")
353 .field("name", &self.name)
354 .field("keystrokes", &self.keystrokes)
355 .finish()
356 }
357}
358
359// #[cfg(test)]
360// mod tests {
361// use std::sync::Arc;
362
363// use super::*;
364// use editor::Editor;
365// use gpui::{executor::Deterministic, TestAppContext};
366// use project::Project;
367// use workspace::{AppState, Workspace};
368
369// #[test]
370// fn test_humanize_action_name() {
371// assert_eq!(
372// humanize_action_name("editor::GoToDefinition"),
373// "editor: go to definition"
374// );
375// assert_eq!(
376// humanize_action_name("editor::Backspace"),
377// "editor: backspace"
378// );
379// assert_eq!(
380// humanize_action_name("go_to_line::Deploy"),
381// "go to line: deploy"
382// );
383// }
384
385// #[gpui::test]
386// async fn test_command_palette(deterministic: Arc<Deterministic>, cx: &mut TestAppContext) {
387// let app_state = init_test(cx);
388
389// let project = Project::test(app_state.fs.clone(), [], cx).await;
390// let window = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
391// let workspace = window.root(cx);
392// let editor = window.add_view(cx, |cx| {
393// let mut editor = Editor::single_line(None, cx);
394// editor.set_text("abc", cx);
395// editor
396// });
397
398// workspace.update(cx, |workspace, cx| {
399// cx.focus(&editor);
400// workspace.add_item(Box::new(editor.clone()), cx)
401// });
402
403// workspace.update(cx, |workspace, cx| {
404// toggle_command_palette(workspace, &Toggle, cx);
405// });
406
407// let palette = workspace.read_with(cx, |workspace, _| {
408// workspace.modal::<CommandPalette>().unwrap()
409// });
410
411// palette
412// .update(cx, |palette, cx| {
413// // Fill up palette's command list by running an empty query;
414// // we only need it to subsequently assert that the palette is initially
415// // sorted by command's name.
416// palette.delegate_mut().update_matches("".to_string(), cx)
417// })
418// .await;
419
420// palette.update(cx, |palette, _| {
421// let is_sorted =
422// |actions: &[Command]| actions.windows(2).all(|pair| pair[0].name <= pair[1].name);
423// assert!(is_sorted(&palette.delegate().actions));
424// });
425
426// palette
427// .update(cx, |palette, cx| {
428// palette
429// .delegate_mut()
430// .update_matches("bcksp".to_string(), cx)
431// })
432// .await;
433
434// palette.update(cx, |palette, cx| {
435// assert_eq!(palette.delegate().matches[0].string, "editor: backspace");
436// palette.confirm(&Default::default(), cx);
437// });
438// deterministic.run_until_parked();
439// editor.read_with(cx, |editor, cx| {
440// assert_eq!(editor.text(cx), "ab");
441// });
442
443// // Add namespace filter, and redeploy the palette
444// cx.update(|cx| {
445// cx.update_default_global::<CommandPaletteFilter, _, _>(|filter, _| {
446// filter.filtered_namespaces.insert("editor");
447// })
448// });
449
450// workspace.update(cx, |workspace, cx| {
451// toggle_command_palette(workspace, &Toggle, cx);
452// });
453
454// // Assert editor command not present
455// let palette = workspace.read_with(cx, |workspace, _| {
456// workspace.modal::<CommandPalette>().unwrap()
457// });
458
459// palette
460// .update(cx, |palette, cx| {
461// palette
462// .delegate_mut()
463// .update_matches("bcksp".to_string(), cx)
464// })
465// .await;
466
467// palette.update(cx, |palette, _| {
468// assert!(palette.delegate().matches.is_empty())
469// });
470// }
471
472// fn init_test(cx: &mut TestAppContext) -> Arc<AppState> {
473// cx.update(|cx| {
474// let app_state = AppState::test(cx);
475// theme::init(cx);
476// language::init(cx);
477// editor::init(cx);
478// workspace::init(app_state.clone(), cx);
479// init(cx);
480// Project::init_settings(cx);
481// app_state
482// })
483// }
484// }