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, SelectIndex, 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())(&cx.global::<settings::Settings>().theme);
 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 |_, _, cx| {
108                                    cx.dispatch_action(SelectIndex(ix))
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 keymap_context(&self, _: &AppContext) -> KeymapContext {
130        let mut cx = Self::default_keymap_context();
131        cx.add_identifier("menu");
132        cx
133    }
134
135    fn focus_in(&mut self, _: AnyViewHandle, cx: &mut ViewContext<Self>) {
136        if cx.is_self_focused() {
137            cx.focus(&self.query_editor);
138        }
139    }
140}
141
142impl<D: PickerDelegate> Modal for Picker<D> {
143    fn dismiss_on_event(event: &Self::Event) -> bool {
144        matches!(event, PickerEvent::Dismiss)
145    }
146}
147
148impl<D: PickerDelegate> Picker<D> {
149    pub fn init(cx: &mut AppContext) {
150        cx.add_action(Self::select_first);
151        cx.add_action(Self::select_last);
152        cx.add_action(Self::select_next);
153        cx.add_action(Self::select_prev);
154        cx.add_action(Self::select_index);
155        cx.add_action(Self::confirm);
156        cx.add_action(Self::cancel);
157    }
158
159    pub fn new(delegate: D, cx: &mut ViewContext<Self>) -> Self {
160        let theme = Arc::new(Mutex::new(
161            Box::new(|theme: &theme::Theme| theme.picker.clone())
162                as Box<dyn Fn(&theme::Theme) -> theme::Picker>,
163        ));
164        let placeholder_text = delegate.placeholder_text();
165        let query_editor = cx.add_view({
166            let picker_theme = theme.clone();
167            |cx| {
168                let mut editor = Editor::single_line(
169                    Some(Arc::new(move |theme| {
170                        (picker_theme.lock())(theme).input_editor.clone()
171                    })),
172                    cx,
173                );
174                editor.set_placeholder_text(placeholder_text, cx);
175                editor
176            }
177        });
178        cx.subscribe(&query_editor, Self::on_query_editor_event)
179            .detach();
180        let mut this = Self {
181            query_editor,
182            list_state: Default::default(),
183            delegate,
184            max_size: vec2f(540., 420.),
185            theme,
186            confirmed: false,
187            pending_update_matches: Task::ready(None),
188        };
189        this.update_matches(String::new(), cx);
190        this
191    }
192
193    pub fn with_max_size(mut self, width: f32, height: f32) -> Self {
194        self.max_size = vec2f(width, height);
195        self
196    }
197
198    pub fn with_theme<F>(self, theme: F) -> Self
199    where
200        F: 'static + Fn(&theme::Theme) -> theme::Picker,
201    {
202        *self.theme.lock() = Box::new(theme);
203        self
204    }
205
206    pub fn delegate(&self) -> &D {
207        &self.delegate
208    }
209
210    pub fn delegate_mut(&mut self) -> &mut D {
211        &mut self.delegate
212    }
213
214    pub fn query(&self, cx: &AppContext) -> String {
215        self.query_editor.read(cx).text(cx)
216    }
217
218    pub fn set_query(&self, query: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
219        self.query_editor
220            .update(cx, |editor, cx| editor.set_text(query, cx));
221    }
222
223    fn on_query_editor_event(
224        &mut self,
225        _: ViewHandle<Editor>,
226        event: &editor::Event,
227        cx: &mut ViewContext<Self>,
228    ) {
229        match event {
230            editor::Event::BufferEdited { .. } => self.update_matches(self.query(cx), cx),
231            editor::Event::Blurred if !self.confirmed => {
232                self.dismiss(cx);
233            }
234            _ => {}
235        }
236    }
237
238    pub fn update_matches(&mut self, query: String, cx: &mut ViewContext<Self>) {
239        let update = self.delegate.update_matches(query, cx);
240        self.matches_updated(cx);
241        self.pending_update_matches = cx.spawn_weak(|this, mut cx| async move {
242            update.await;
243            this.upgrade(&cx)?
244                .update(&mut cx, |this, cx| this.matches_updated(cx))
245                .log_err()
246        });
247    }
248
249    fn matches_updated(&mut self, cx: &mut ViewContext<Self>) {
250        let index = self.delegate.selected_index();
251        let target = if self.delegate.center_selection_after_match_updates() {
252            ScrollTarget::Center(index)
253        } else {
254            ScrollTarget::Show(index)
255        };
256        self.list_state.scroll_to(target);
257        cx.notify();
258    }
259
260    pub fn select_first(&mut self, _: &SelectFirst, cx: &mut ViewContext<Self>) {
261        if self.delegate.match_count() > 0 {
262            self.delegate.set_selected_index(0, cx);
263            self.list_state.scroll_to(ScrollTarget::Show(0));
264        }
265
266        cx.notify();
267    }
268
269    pub fn select_index(&mut self, action: &SelectIndex, cx: &mut ViewContext<Self>) {
270        let index = action.0;
271        if self.delegate.match_count() > 0 {
272            self.confirmed = true;
273            self.delegate.set_selected_index(index, cx);
274            self.delegate.confirm(cx);
275        }
276    }
277
278    pub fn select_last(&mut self, _: &SelectLast, cx: &mut ViewContext<Self>) {
279        let match_count = self.delegate.match_count();
280        if match_count > 0 {
281            let index = match_count - 1;
282            self.delegate.set_selected_index(index, cx);
283            self.list_state.scroll_to(ScrollTarget::Show(index));
284        }
285        cx.notify();
286    }
287
288    pub fn select_next(&mut self, _: &SelectNext, cx: &mut ViewContext<Self>) {
289        let next_index = self.delegate.selected_index() + 1;
290        if next_index < self.delegate.match_count() {
291            self.delegate.set_selected_index(next_index, cx);
292            self.list_state.scroll_to(ScrollTarget::Show(next_index));
293        }
294
295        cx.notify();
296    }
297
298    pub fn select_prev(&mut self, _: &SelectPrev, cx: &mut ViewContext<Self>) {
299        let mut selected_index = self.delegate.selected_index();
300        if selected_index > 0 {
301            selected_index -= 1;
302            self.delegate.set_selected_index(selected_index, cx);
303            self.list_state
304                .scroll_to(ScrollTarget::Show(selected_index));
305        }
306
307        cx.notify();
308    }
309
310    pub fn confirm(&mut self, _: &Confirm, cx: &mut ViewContext<Self>) {
311        self.confirmed = true;
312        self.delegate.confirm(cx);
313    }
314
315    fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
316        self.dismiss(cx);
317    }
318
319    fn dismiss(&mut self, cx: &mut ViewContext<Self>) {
320        cx.emit(PickerEvent::Dismiss);
321        self.delegate.dismissed(cx);
322    }
323}