command_palette.rs

  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 = if query.is_empty() {
139                candidates
140                    .into_iter()
141                    .enumerate()
142                    .map(|(index, candidate)| StringMatch {
143                        candidate_id: index,
144                        string: candidate.string,
145                        positions: Vec::new(),
146                        score: 0.0,
147                    })
148                    .collect()
149            } else {
150                fuzzy::match_strings(
151                    &candidates,
152                    &query,
153                    true,
154                    10000,
155                    &Default::default(),
156                    cx.background(),
157                )
158                .await
159            };
160            this.update(&mut cx, |this, _| {
161                this.matches = matches;
162                if this.matches.is_empty() {
163                    this.selected_ix = 0;
164                } else {
165                    this.selected_ix = cmp::min(this.selected_ix, this.matches.len() - 1);
166                }
167            });
168        })
169    }
170
171    fn dismiss(&mut self, cx: &mut ViewContext<Self>) {
172        cx.emit(Event::Dismissed);
173    }
174
175    fn confirm(&mut self, cx: &mut ViewContext<Self>) {
176        if !self.matches.is_empty() {
177            let window_id = cx.window_id();
178            let action_ix = self.matches[self.selected_ix].candidate_id;
179            cx.dispatch_action_at(
180                window_id,
181                self.focused_view_id,
182                self.actions[action_ix].action.as_ref(),
183            )
184        }
185        cx.emit(Event::Dismissed);
186    }
187
188    fn render_match(&self, ix: usize, selected: bool, cx: &gpui::AppContext) -> gpui::ElementBox {
189        let mat = &self.matches[ix];
190        let command = &self.actions[mat.candidate_id];
191        let settings = cx.global::<Settings>();
192        let theme = &settings.theme;
193        let style = if selected {
194            &theme.selector.active_item
195        } else {
196            &theme.selector.item
197        };
198        let key_style = &theme.command_palette.key;
199        let keystroke_spacing = theme.command_palette.keystroke_spacing;
200
201        Flex::row()
202            .with_child(
203                Label::new(mat.string.clone(), style.label.clone())
204                    .with_highlights(mat.positions.clone())
205                    .boxed(),
206            )
207            .with_children(command.keystrokes.iter().map(|keystroke| {
208                Flex::row()
209                    .with_children(
210                        [
211                            (keystroke.ctrl, "^"),
212                            (keystroke.alt, ""),
213                            (keystroke.cmd, ""),
214                            (keystroke.shift, ""),
215                        ]
216                        .into_iter()
217                        .filter_map(|(modifier, label)| {
218                            if modifier {
219                                Some(
220                                    Label::new(label.into(), key_style.label.clone())
221                                        .contained()
222                                        .with_style(key_style.container)
223                                        .boxed(),
224                                )
225                            } else {
226                                None
227                            }
228                        }),
229                    )
230                    .with_child(
231                        Label::new(keystroke.key.clone(), key_style.label.clone())
232                            .contained()
233                            .with_style(key_style.container)
234                            .boxed(),
235                    )
236                    .contained()
237                    .with_margin_left(keystroke_spacing)
238                    .flex_float()
239                    .boxed()
240            }))
241            .contained()
242            .with_style(style.container)
243            .boxed()
244    }
245}
246
247impl std::fmt::Debug for Command {
248    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
249        f.debug_struct("Command")
250            .field("name", &self.name)
251            .field("keystrokes", &self.keystrokes)
252            .finish()
253    }
254}