1use fuzzy::{StringMatch, StringMatchCandidate};
2use gpui::{
3 actions,
4 elements::{ChildView, Flex, Label, ParentElement},
5 keymap::Keystroke,
6 Action, Element, Entity, MutableAppContext, View, ViewContext, ViewHandle,
7};
8use picker::{Picker, PickerDelegate};
9use settings::Settings;
10use std::cmp;
11use workspace::Workspace;
12
13pub fn init(cx: &mut MutableAppContext) {
14 cx.add_action(CommandPalette::toggle);
15 Picker::<CommandPalette>::init(cx);
16}
17
18actions!(command_palette, [Toggle]);
19
20pub struct CommandPalette {
21 picker: ViewHandle<Picker<Self>>,
22 actions: Vec<Command>,
23 matches: Vec<StringMatch>,
24 selected_ix: usize,
25 focused_view_id: usize,
26}
27
28pub enum Event {
29 Dismissed,
30}
31
32struct Command {
33 name: &'static str,
34 action: Box<dyn Action>,
35 keystrokes: Vec<Keystroke>,
36}
37
38impl CommandPalette {
39 pub fn new(focused_view_id: usize, cx: &mut ViewContext<Self>) -> Self {
40 let this = cx.weak_handle();
41 let actions = cx
42 .available_actions(cx.window_id(), focused_view_id)
43 .map(|(name, action, bindings)| Command {
44 name,
45 action,
46 keystrokes: bindings
47 .last()
48 .map_or(Vec::new(), |binding| binding.keystrokes().to_vec()),
49 })
50 .collect();
51 let picker = cx.add_view(|cx| Picker::new(this, cx));
52 Self {
53 picker,
54 actions,
55 matches: vec![],
56 selected_ix: 0,
57 focused_view_id,
58 }
59 }
60
61 fn toggle(_: &mut Workspace, _: &Toggle, cx: &mut ViewContext<Workspace>) {
62 let workspace = cx.handle();
63 let window_id = cx.window_id();
64 let focused_view_id = cx.focused_view_id(window_id).unwrap_or(workspace.id());
65
66 cx.as_mut().defer(move |cx| {
67 let this = cx.add_view(window_id, |cx| Self::new(focused_view_id, cx));
68 workspace.update(cx, |workspace, cx| {
69 workspace.toggle_modal(cx, |cx, _| {
70 cx.subscribe(&this, Self::on_event).detach();
71 this
72 });
73 });
74 });
75 }
76
77 fn on_event(
78 workspace: &mut Workspace,
79 _: ViewHandle<Self>,
80 event: &Event,
81 cx: &mut ViewContext<Workspace>,
82 ) {
83 match event {
84 Event::Dismissed => {
85 workspace.dismiss_modal(cx);
86 }
87 }
88 }
89}
90
91impl Entity for CommandPalette {
92 type Event = Event;
93}
94
95impl View for CommandPalette {
96 fn ui_name() -> &'static str {
97 "CommandPalette"
98 }
99
100 fn render(&mut self, _: &mut gpui::RenderContext<'_, Self>) -> gpui::ElementBox {
101 ChildView::new(self.picker.clone()).boxed()
102 }
103
104 fn on_focus(&mut self, cx: &mut ViewContext<Self>) {
105 cx.focus(&self.picker);
106 }
107}
108
109impl PickerDelegate for CommandPalette {
110 fn match_count(&self) -> usize {
111 self.matches.len()
112 }
113
114 fn selected_index(&self) -> usize {
115 self.selected_ix
116 }
117
118 fn set_selected_index(&mut self, ix: usize, _: &mut ViewContext<Self>) {
119 self.selected_ix = ix;
120 }
121
122 fn update_matches(
123 &mut self,
124 query: String,
125 cx: &mut gpui::ViewContext<Self>,
126 ) -> gpui::Task<()> {
127 let candidates = self
128 .actions
129 .iter()
130 .enumerate()
131 .map(|(ix, command)| StringMatchCandidate {
132 id: ix,
133 string: command.name.to_string(),
134 char_bag: command.name.chars().collect(),
135 })
136 .collect::<Vec<_>>();
137 cx.spawn(move |this, mut cx| async move {
138 let matches = fuzzy::match_strings(
139 &candidates,
140 &query,
141 true,
142 10000,
143 &Default::default(),
144 cx.background(),
145 )
146 .await;
147 this.update(&mut cx, |this, _| {
148 this.matches = matches;
149 if this.matches.is_empty() {
150 this.selected_ix = 0;
151 } else {
152 this.selected_ix = cmp::min(this.selected_ix, this.matches.len() - 1);
153 }
154 });
155 })
156 }
157
158 fn dismiss(&mut self, cx: &mut ViewContext<Self>) {
159 cx.emit(Event::Dismissed);
160 }
161
162 fn confirm(&mut self, cx: &mut ViewContext<Self>) {
163 if !self.matches.is_empty() {
164 let window_id = cx.window_id();
165 let action_ix = self.matches[self.selected_ix].candidate_id;
166 cx.dispatch_action_at(
167 window_id,
168 self.focused_view_id,
169 self.actions[action_ix].action.as_ref(),
170 )
171 }
172 cx.emit(Event::Dismissed);
173 }
174
175 fn render_match(&self, ix: usize, selected: bool, cx: &gpui::AppContext) -> gpui::ElementBox {
176 let mat = &self.matches[ix];
177 let command = &self.actions[mat.candidate_id];
178 let settings = cx.global::<Settings>();
179 let theme = &settings.theme;
180 let style = if selected {
181 &theme.selector.active_item
182 } else {
183 &theme.selector.item
184 };
185 let key_style = &theme.command_palette.key;
186 let keystroke_spacing = theme.command_palette.keystroke_spacing;
187
188 Flex::row()
189 .with_child(Label::new(mat.string.clone(), style.label.clone()).boxed())
190 .with_children(command.keystrokes.iter().map(|keystroke| {
191 Flex::row()
192 .with_children(
193 [
194 (keystroke.ctrl, "^"),
195 (keystroke.alt, "⎇"),
196 (keystroke.cmd, "⌘"),
197 (keystroke.shift, "⇧"),
198 ]
199 .into_iter()
200 .filter_map(|(modifier, label)| {
201 if modifier {
202 Some(
203 Label::new(label.into(), key_style.label.clone())
204 .contained()
205 .with_style(key_style.container)
206 .boxed(),
207 )
208 } else {
209 None
210 }
211 }),
212 )
213 .with_child(
214 Label::new(keystroke.key.clone(), key_style.label.clone())
215 .contained()
216 .with_style(key_style.container)
217 .boxed(),
218 )
219 .contained()
220 .with_margin_left(keystroke_spacing)
221 .flex_float()
222 .boxed()
223 }))
224 .contained()
225 .with_style(style.container)
226 .boxed()
227 }
228}
229
230impl std::fmt::Debug for Command {
231 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
232 f.debug_struct("Command")
233 .field("name", &self.name)
234 .field("keystrokes", &self.keystrokes)
235 .finish()
236 }
237}