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