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