base_keymap_picker.rs

  1use super::base_keymap_setting::BaseKeymap;
  2use fuzzy::{StringMatch, StringMatchCandidate, match_strings};
  3use gpui::{
  4    App, Context, DismissEvent, Entity, EventEmitter, Focusable, Render, Task, WeakEntity, Window,
  5    actions,
  6};
  7use picker::{Picker, PickerDelegate};
  8use project::Fs;
  9use settings::{Settings, update_settings_file};
 10use std::sync::Arc;
 11use ui::{ListItem, ListItemSpacing, prelude::*};
 12use util::ResultExt;
 13use workspace::{ModalView, Workspace, ui::HighlightedLabel};
 14
 15actions!(
 16    welcome,
 17    [
 18        /// Toggles the base keymap selector modal.
 19        ToggleBaseKeymapSelector
 20    ]
 21);
 22
 23pub fn init(cx: &mut App) {
 24    cx.observe_new(|workspace: &mut Workspace, _window, _cx| {
 25        workspace.register_action(toggle);
 26    })
 27    .detach();
 28}
 29
 30pub fn toggle(
 31    workspace: &mut Workspace,
 32    _: &ToggleBaseKeymapSelector,
 33    window: &mut Window,
 34    cx: &mut Context<Workspace>,
 35) {
 36    let fs = workspace.app_state().fs.clone();
 37    workspace.toggle_modal(window, cx, |window, cx| {
 38        BaseKeymapSelector::new(
 39            BaseKeymapSelectorDelegate::new(cx.entity().downgrade(), fs, cx),
 40            window,
 41            cx,
 42        )
 43    });
 44}
 45
 46pub struct BaseKeymapSelector {
 47    picker: Entity<Picker<BaseKeymapSelectorDelegate>>,
 48}
 49
 50impl Focusable for BaseKeymapSelector {
 51    fn focus_handle(&self, cx: &App) -> gpui::FocusHandle {
 52        self.picker.focus_handle(cx)
 53    }
 54}
 55
 56impl EventEmitter<DismissEvent> for BaseKeymapSelector {}
 57impl ModalView for BaseKeymapSelector {}
 58
 59impl BaseKeymapSelector {
 60    pub fn new(
 61        delegate: BaseKeymapSelectorDelegate,
 62        window: &mut Window,
 63        cx: &mut Context<BaseKeymapSelector>,
 64    ) -> Self {
 65        let picker = cx.new(|cx| Picker::uniform_list(delegate, window, cx));
 66        Self { picker }
 67    }
 68}
 69
 70impl Render for BaseKeymapSelector {
 71    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
 72        v_flex().w(rems(34.)).child(self.picker.clone())
 73    }
 74}
 75
 76pub struct BaseKeymapSelectorDelegate {
 77    selector: WeakEntity<BaseKeymapSelector>,
 78    matches: Vec<StringMatch>,
 79    selected_index: usize,
 80    fs: Arc<dyn Fs>,
 81}
 82
 83impl BaseKeymapSelectorDelegate {
 84    fn new(
 85        selector: WeakEntity<BaseKeymapSelector>,
 86        fs: Arc<dyn Fs>,
 87        cx: &mut Context<BaseKeymapSelector>,
 88    ) -> Self {
 89        let base = BaseKeymap::get(None, cx);
 90        let selected_index = BaseKeymap::OPTIONS
 91            .iter()
 92            .position(|(_, value)| value == base)
 93            .unwrap_or(0);
 94        Self {
 95            selector,
 96            matches: Vec::new(),
 97            selected_index,
 98            fs,
 99        }
100    }
101}
102
103impl PickerDelegate for BaseKeymapSelectorDelegate {
104    type ListItem = ui::ListItem;
105
106    fn placeholder_text(&self, _window: &mut Window, _cx: &mut App) -> Arc<str> {
107        "Select a base keymap...".into()
108    }
109
110    fn match_count(&self) -> usize {
111        self.matches.len()
112    }
113
114    fn selected_index(&self) -> usize {
115        self.selected_index
116    }
117
118    fn set_selected_index(
119        &mut self,
120        ix: usize,
121        _window: &mut Window,
122        _: &mut Context<Picker<BaseKeymapSelectorDelegate>>,
123    ) {
124        self.selected_index = ix;
125    }
126
127    fn update_matches(
128        &mut self,
129        query: String,
130        window: &mut Window,
131        cx: &mut Context<Picker<BaseKeymapSelectorDelegate>>,
132    ) -> Task<()> {
133        let background = cx.background_executor().clone();
134        let candidates = BaseKeymap::names()
135            .enumerate()
136            .map(|(id, name)| StringMatchCandidate::new(id, name))
137            .collect::<Vec<_>>();
138
139        cx.spawn_in(window, async move |this, cx| {
140            let matches = if query.is_empty() {
141                candidates
142                    .into_iter()
143                    .enumerate()
144                    .map(|(index, candidate)| StringMatch {
145                        candidate_id: index,
146                        string: candidate.string,
147                        positions: Vec::new(),
148                        score: 0.0,
149                    })
150                    .collect()
151            } else {
152                match_strings(
153                    &candidates,
154                    &query,
155                    false,
156                    true,
157                    100,
158                    &Default::default(),
159                    background,
160                )
161                .await
162            };
163
164            this.update(cx, |this, _| {
165                this.delegate.matches = matches;
166                this.delegate.selected_index = this
167                    .delegate
168                    .selected_index
169                    .min(this.delegate.matches.len().saturating_sub(1));
170            })
171            .log_err();
172        })
173    }
174
175    fn confirm(
176        &mut self,
177        _: bool,
178        _: &mut Window,
179        cx: &mut Context<Picker<BaseKeymapSelectorDelegate>>,
180    ) {
181        if let Some(selection) = self.matches.get(self.selected_index) {
182            let base_keymap = BaseKeymap::from_names(&selection.string);
183
184            telemetry::event!(
185                "Settings Changed",
186                setting = "keymap",
187                value = base_keymap.to_string()
188            );
189
190            update_settings_file::<BaseKeymap>(self.fs.clone(), cx, move |setting, _| {
191                *setting = Some(base_keymap)
192            });
193        }
194
195        self.selector
196            .update(cx, |_, cx| {
197                cx.emit(DismissEvent);
198            })
199            .ok();
200    }
201
202    fn dismissed(&mut self, _: &mut Window, cx: &mut Context<Picker<BaseKeymapSelectorDelegate>>) {
203        self.selector
204            .update(cx, |_, cx| {
205                cx.emit(DismissEvent);
206            })
207            .log_err();
208    }
209
210    fn render_match(
211        &self,
212        ix: usize,
213        selected: bool,
214        _window: &mut Window,
215        _cx: &mut Context<Picker<Self>>,
216    ) -> Option<Self::ListItem> {
217        let keymap_match = &self.matches[ix];
218
219        Some(
220            ListItem::new(ix)
221                .inset(true)
222                .spacing(ListItemSpacing::Sparse)
223                .toggle_state(selected)
224                .child(HighlightedLabel::new(
225                    keymap_match.string.clone(),
226                    keymap_match.positions.clone(),
227                )),
228        )
229    }
230}