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