picker.rs

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