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