picker.rs

  1use editor::Editor;
  2use gpui::{
  3    elements::*,
  4    geometry::vector::{vec2f, Vector2F},
  5    keymap_matcher::KeymapContext,
  6    platform::{CursorStyle, MouseButton},
  7    AnyElement, AnyViewHandle, AppContext, Axis, Entity, MouseState, Task, View, ViewContext,
  8    ViewHandle,
  9};
 10use menu::{Cancel, Confirm, SecondaryConfirm, SelectFirst, SelectLast, SelectNext, SelectPrev};
 11use parking_lot::Mutex;
 12use std::{cmp, sync::Arc};
 13use util::ResultExt;
 14use workspace::Modal;
 15
 16#[derive(Clone, Copy)]
 17pub enum PickerEvent {
 18    Dismiss,
 19}
 20
 21pub struct Picker<D: PickerDelegate> {
 22    delegate: D,
 23    query_editor: ViewHandle<Editor>,
 24    list_state: UniformListState,
 25    max_size: Vector2F,
 26    theme: Arc<Mutex<Box<dyn Fn(&theme::Theme) -> theme::Picker>>>,
 27    confirmed: bool,
 28    pending_update_matches: Option<Task<Option<()>>>,
 29    confirm_on_update: Option<bool>,
 30    has_focus: bool,
 31}
 32
 33pub trait PickerDelegate: Sized + 'static {
 34    fn placeholder_text(&self) -> Arc<str>;
 35    fn match_count(&self) -> usize;
 36    fn selected_index(&self) -> usize;
 37    fn set_selected_index(&mut self, ix: usize, cx: &mut ViewContext<Picker<Self>>);
 38    fn update_matches(&mut self, query: String, cx: &mut ViewContext<Picker<Self>>) -> Task<()>;
 39    fn confirm(&mut self, secondary: bool, cx: &mut ViewContext<Picker<Self>>);
 40    fn dismissed(&mut self, cx: &mut ViewContext<Picker<Self>>);
 41    fn render_match(
 42        &self,
 43        ix: usize,
 44        state: &mut MouseState,
 45        selected: bool,
 46        cx: &AppContext,
 47    ) -> AnyElement<Picker<Self>>;
 48    fn center_selection_after_match_updates(&self) -> bool {
 49        false
 50    }
 51    fn render_header(
 52        &self,
 53        _cx: &mut ViewContext<Picker<Self>>,
 54    ) -> Option<AnyElement<Picker<Self>>> {
 55        None
 56    }
 57    fn render_footer(
 58        &self,
 59        _cx: &mut ViewContext<Picker<Self>>,
 60    ) -> Option<AnyElement<Picker<Self>>> {
 61        None
 62    }
 63}
 64
 65impl<D: PickerDelegate> Entity for Picker<D> {
 66    type Event = PickerEvent;
 67}
 68
 69impl<D: PickerDelegate> View for Picker<D> {
 70    fn ui_name() -> &'static str {
 71        "Picker"
 72    }
 73
 74    fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
 75        let theme = (self.theme.lock())(theme::current(cx).as_ref());
 76        let query = self.query(cx);
 77        let match_count = self.delegate.match_count();
 78
 79        let container_style;
 80        let editor_style;
 81        if query.is_empty() && match_count == 0 {
 82            container_style = theme.empty_container;
 83            editor_style = theme.empty_input_editor.container;
 84        } else {
 85            container_style = theme.container;
 86            editor_style = theme.input_editor.container;
 87        };
 88
 89        Flex::new(Axis::Vertical)
 90            .with_child(
 91                ChildView::new(&self.query_editor, cx)
 92                    .contained()
 93                    .with_style(editor_style),
 94            )
 95            .with_children(self.delegate.render_header(cx))
 96            .with_children(if match_count == 0 {
 97                if query.is_empty() {
 98                    None
 99                } else {
100                    Some(
101                        Label::new("No matches", theme.no_matches.label.clone())
102                            .contained()
103                            .with_style(theme.no_matches.container)
104                            .into_any(),
105                    )
106                }
107            } else {
108                Some(
109                    UniformList::new(
110                        self.list_state.clone(),
111                        match_count,
112                        cx,
113                        move |this, mut range, items, cx| {
114                            let selected_ix = this.delegate.selected_index();
115                            range.end = cmp::min(range.end, this.delegate.match_count());
116                            items.extend(range.map(move |ix| {
117                                MouseEventHandler::new::<D, _>(ix, cx, |state, cx| {
118                                    this.delegate.render_match(ix, state, ix == selected_ix, cx)
119                                })
120                                // Capture mouse events
121                                .on_down(MouseButton::Left, |_, _, _| {})
122                                .on_up(MouseButton::Left, |_, _, _| {})
123                                .on_click(MouseButton::Left, move |click, picker, cx| {
124                                    picker.select_index(ix, click.cmd, cx);
125                                })
126                                .with_cursor_style(CursorStyle::PointingHand)
127                                .into_any()
128                            }));
129                        },
130                    )
131                    .contained()
132                    .with_margin_top(6.0)
133                    .flex(1., false)
134                    .into_any(),
135                )
136            })
137            .with_children(self.delegate.render_footer(cx))
138            .contained()
139            .with_style(container_style)
140            .constrained()
141            .with_max_width(self.max_size.x())
142            .with_max_height(self.max_size.y())
143            .into_any_named("picker")
144    }
145
146    fn update_keymap_context(&self, keymap: &mut KeymapContext, _: &AppContext) {
147        Self::reset_to_default_keymap_context(keymap);
148        keymap.add_identifier("menu");
149    }
150
151    fn focus_in(&mut self, _: AnyViewHandle, cx: &mut ViewContext<Self>) {
152        self.has_focus = true;
153        if cx.is_self_focused() {
154            cx.focus(&self.query_editor);
155        }
156    }
157
158    fn focus_out(&mut self, _: AnyViewHandle, _: &mut ViewContext<Self>) {
159        self.has_focus = false;
160    }
161}
162
163impl<D: PickerDelegate> Modal for Picker<D> {
164    fn has_focus(&self) -> bool {
165        self.has_focus
166    }
167
168    fn dismiss_on_event(event: &Self::Event) -> bool {
169        matches!(event, PickerEvent::Dismiss)
170    }
171}
172
173impl<D: PickerDelegate> Picker<D> {
174    pub fn init(cx: &mut AppContext) {
175        cx.add_action(Self::select_first);
176        cx.add_action(Self::select_last);
177        cx.add_action(Self::select_next);
178        cx.add_action(Self::select_prev);
179        cx.add_action(Self::confirm);
180        cx.add_action(Self::secondary_confirm);
181        cx.add_action(Self::cancel);
182    }
183
184    pub fn new(delegate: D, cx: &mut ViewContext<Self>) -> Self {
185        let theme = Arc::new(Mutex::new(
186            Box::new(|theme: &theme::Theme| theme.picker.clone())
187                as Box<dyn Fn(&theme::Theme) -> theme::Picker>,
188        ));
189        let placeholder_text = delegate.placeholder_text();
190        let query_editor = cx.add_view({
191            let picker_theme = theme.clone();
192            |cx| {
193                let mut editor = Editor::single_line(
194                    Some(Arc::new(move |theme| {
195                        (picker_theme.lock())(theme).input_editor.clone()
196                    })),
197                    cx,
198                );
199                editor.set_placeholder_text(placeholder_text, cx);
200                editor
201            }
202        });
203        cx.subscribe(&query_editor, Self::on_query_editor_event)
204            .detach();
205        let mut this = Self {
206            query_editor,
207            list_state: Default::default(),
208            delegate,
209            max_size: vec2f(540., 420.),
210            theme,
211            confirmed: false,
212            pending_update_matches: None,
213            confirm_on_update: None,
214            has_focus: false,
215        };
216        this.update_matches(String::new(), cx);
217        this
218    }
219
220    pub fn with_max_size(mut self, width: f32, height: f32) -> Self {
221        self.max_size = vec2f(width, height);
222        self
223    }
224
225    pub fn with_theme<F>(self, theme: F) -> Self
226    where
227        F: 'static + Fn(&theme::Theme) -> theme::Picker,
228    {
229        *self.theme.lock() = Box::new(theme);
230        self
231    }
232
233    pub fn delegate(&self) -> &D {
234        &self.delegate
235    }
236
237    pub fn delegate_mut(&mut self) -> &mut D {
238        &mut self.delegate
239    }
240
241    pub fn query(&self, cx: &AppContext) -> String {
242        self.query_editor.read(cx).text(cx)
243    }
244
245    pub fn set_query(&self, query: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
246        self.query_editor
247            .update(cx, |editor, cx| editor.set_text(query, cx));
248    }
249
250    fn on_query_editor_event(
251        &mut self,
252        _: ViewHandle<Editor>,
253        event: &editor::Event,
254        cx: &mut ViewContext<Self>,
255    ) {
256        match event {
257            editor::Event::BufferEdited { .. } => self.update_matches(self.query(cx), cx),
258            editor::Event::Blurred if !self.confirmed => {
259                self.dismiss(cx);
260            }
261            _ => {}
262        }
263    }
264
265    pub fn update_matches(&mut self, query: String, cx: &mut ViewContext<Self>) {
266        let update = self.delegate.update_matches(query, cx);
267        self.matches_updated(cx);
268        self.pending_update_matches = Some(cx.spawn(|this, mut cx| async move {
269            update.await;
270            this.update(&mut cx, |this, cx| {
271                this.matches_updated(cx);
272            })
273            .log_err()
274        }));
275    }
276
277    fn matches_updated(&mut self, cx: &mut ViewContext<Self>) {
278        let index = self.delegate.selected_index();
279        let target = if self.delegate.center_selection_after_match_updates() {
280            ScrollTarget::Center(index)
281        } else {
282            ScrollTarget::Show(index)
283        };
284        self.list_state.scroll_to(target);
285        self.pending_update_matches = None;
286        if let Some(secondary) = self.confirm_on_update.take() {
287            self.confirmed = true;
288            self.delegate.confirm(secondary, cx)
289        }
290        cx.notify();
291    }
292
293    pub fn select_first(&mut self, _: &SelectFirst, cx: &mut ViewContext<Self>) {
294        if self.delegate.match_count() > 0 {
295            self.delegate.set_selected_index(0, cx);
296            self.list_state.scroll_to(ScrollTarget::Show(0));
297        }
298
299        cx.notify();
300    }
301
302    pub fn select_index(&mut self, index: usize, cmd: bool, cx: &mut ViewContext<Self>) {
303        if self.delegate.match_count() > 0 {
304            self.confirmed = true;
305            self.delegate.set_selected_index(index, cx);
306            self.delegate.confirm(cmd, cx);
307        }
308    }
309
310    pub fn select_last(&mut self, _: &SelectLast, cx: &mut ViewContext<Self>) {
311        let match_count = self.delegate.match_count();
312        if match_count > 0 {
313            let index = match_count - 1;
314            self.delegate.set_selected_index(index, cx);
315            self.list_state.scroll_to(ScrollTarget::Show(index));
316        }
317        cx.notify();
318    }
319
320    pub fn select_next(&mut self, _: &SelectNext, cx: &mut ViewContext<Self>) {
321        let next_index = self.delegate.selected_index() + 1;
322        if next_index < self.delegate.match_count() {
323            self.delegate.set_selected_index(next_index, cx);
324            self.list_state.scroll_to(ScrollTarget::Show(next_index));
325        }
326
327        cx.notify();
328    }
329
330    pub fn select_prev(&mut self, _: &SelectPrev, cx: &mut ViewContext<Self>) {
331        let mut selected_index = self.delegate.selected_index();
332        if selected_index > 0 {
333            selected_index -= 1;
334            self.delegate.set_selected_index(selected_index, cx);
335            self.list_state
336                .scroll_to(ScrollTarget::Show(selected_index));
337        }
338
339        cx.notify();
340    }
341
342    pub fn confirm(&mut self, _: &Confirm, cx: &mut ViewContext<Self>) {
343        if self.pending_update_matches.is_some() {
344            self.confirm_on_update = Some(false)
345        } else {
346            self.confirmed = true;
347            self.delegate.confirm(false, cx);
348        }
349    }
350
351    pub fn secondary_confirm(&mut self, _: &SecondaryConfirm, cx: &mut ViewContext<Self>) {
352        if self.pending_update_matches.is_some() {
353            self.confirm_on_update = Some(true)
354        } else {
355            self.confirmed = true;
356            self.delegate.confirm(true, cx);
357        }
358    }
359
360    fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
361        self.dismiss(cx);
362    }
363
364    fn dismiss(&mut self, cx: &mut ViewContext<Self>) {
365        cx.emit(PickerEvent::Dismiss);
366        self.delegate.dismissed(cx);
367    }
368}