picker.rs

  1use editor::Editor;
  2use gpui::{
  3    elements::{
  4        ChildView, EventHandler, Flex, Label, ParentElement, ScrollTarget, UniformList,
  5        UniformListState,
  6    },
  7    geometry::vector::{vec2f, Vector2F},
  8    keymap, AppContext, Axis, Element, ElementBox, Entity, MutableAppContext, RenderContext, Task,
  9    View, ViewContext, ViewHandle, WeakViewHandle,
 10};
 11use settings::Settings;
 12use std::cmp;
 13use workspace::menu::{
 14    Cancel, Confirm, SelectFirst, SelectIndex, SelectLast, SelectNext, SelectPrev,
 15};
 16
 17pub struct Picker<D: PickerDelegate> {
 18    delegate: WeakViewHandle<D>,
 19    query_editor: ViewHandle<Editor>,
 20    list_state: UniformListState,
 21    max_size: Vector2F,
 22    confirmed: bool,
 23}
 24
 25pub trait PickerDelegate: View {
 26    fn match_count(&self) -> usize;
 27    fn selected_index(&self) -> usize;
 28    fn set_selected_index(&mut self, ix: usize, cx: &mut ViewContext<Self>);
 29    fn update_matches(&mut self, query: String, cx: &mut ViewContext<Self>) -> Task<()>;
 30    fn confirm(&mut self, cx: &mut ViewContext<Self>);
 31    fn dismiss(&mut self, cx: &mut ViewContext<Self>);
 32    fn render_match(&self, ix: usize, selected: bool, cx: &AppContext) -> ElementBox;
 33    fn center_selection_after_match_updates(&self) -> bool {
 34        false
 35    }
 36}
 37
 38impl<D: PickerDelegate> Entity for Picker<D> {
 39    type Event = ();
 40}
 41
 42impl<D: PickerDelegate> View for Picker<D> {
 43    fn ui_name() -> &'static str {
 44        "Picker"
 45    }
 46
 47    fn render(&mut self, cx: &mut RenderContext<Self>) -> gpui::ElementBox {
 48        let settings = cx.global::<Settings>();
 49        let delegate = self.delegate.clone();
 50        let match_count = if let Some(delegate) = delegate.upgrade(cx.app) {
 51            delegate.read(cx).match_count()
 52        } else {
 53            0
 54        };
 55
 56        Flex::new(Axis::Vertical)
 57            .with_child(
 58                ChildView::new(&self.query_editor)
 59                    .contained()
 60                    .with_style(settings.theme.selector.input_editor.container)
 61                    .boxed(),
 62            )
 63            .with_child(
 64                if match_count == 0 {
 65                    Label::new(
 66                        "No matches".into(),
 67                        settings.theme.selector.empty.label.clone(),
 68                    )
 69                    .contained()
 70                    .with_style(settings.theme.selector.empty.container)
 71                } else {
 72                    UniformList::new(
 73                        self.list_state.clone(),
 74                        match_count,
 75                        move |mut range, items, cx| {
 76                            let cx = cx.as_ref();
 77                            let delegate = delegate.upgrade(cx).unwrap();
 78                            let delegate = delegate.read(cx);
 79                            let selected_ix = delegate.selected_index();
 80                            range.end = cmp::min(range.end, delegate.match_count());
 81                            items.extend(range.map(move |ix| {
 82                                EventHandler::new(delegate.render_match(ix, ix == selected_ix, cx))
 83                                    .on_mouse_down(move |cx| {
 84                                        cx.dispatch_action(SelectIndex(ix));
 85                                        true
 86                                    })
 87                                    .boxed()
 88                            }));
 89                        },
 90                    )
 91                    .contained()
 92                    .with_margin_top(6.0)
 93                }
 94                .flex(1., false)
 95                .boxed(),
 96            )
 97            .contained()
 98            .with_style(settings.theme.selector.container)
 99            .constrained()
100            .with_max_width(self.max_size.x())
101            .with_max_height(self.max_size.y())
102            .named("picker")
103    }
104
105    fn keymap_context(&self, _: &AppContext) -> keymap::Context {
106        let mut cx = Self::default_keymap_context();
107        cx.set.insert("menu".into());
108        cx
109    }
110
111    fn on_focus(&mut self, cx: &mut ViewContext<Self>) {
112        cx.focus(&self.query_editor);
113    }
114}
115
116impl<D: PickerDelegate> Picker<D> {
117    pub fn init(cx: &mut MutableAppContext) {
118        cx.add_action(Self::select_first);
119        cx.add_action(Self::select_last);
120        cx.add_action(Self::select_next);
121        cx.add_action(Self::select_prev);
122        cx.add_action(Self::select_index);
123        cx.add_action(Self::confirm);
124        cx.add_action(Self::cancel);
125    }
126
127    pub fn new(delegate: WeakViewHandle<D>, cx: &mut ViewContext<Self>) -> Self {
128        let query_editor = cx.add_view(|cx| {
129            Editor::single_line(Some(|theme| theme.selector.input_editor.clone()), cx)
130        });
131        cx.subscribe(&query_editor, Self::on_query_editor_event)
132            .detach();
133        let this = Self {
134            query_editor,
135            list_state: Default::default(),
136            delegate,
137            max_size: vec2f(540., 420.),
138            confirmed: false,
139        };
140        cx.defer(|this, cx| {
141            if let Some(delegate) = this.delegate.upgrade(cx) {
142                cx.observe(&delegate, |_, _, cx| cx.notify()).detach();
143                this.update_matches(String::new(), cx)
144            }
145        });
146        this
147    }
148
149    pub fn with_max_size(mut self, width: f32, height: f32) -> Self {
150        self.max_size = vec2f(width, height);
151        self
152    }
153
154    pub fn query(&self, cx: &AppContext) -> String {
155        self.query_editor.read(cx).text(cx)
156    }
157
158    fn on_query_editor_event(
159        &mut self,
160        _: ViewHandle<Editor>,
161        event: &editor::Event,
162        cx: &mut ViewContext<Self>,
163    ) {
164        match event {
165            editor::Event::BufferEdited { .. } => self.update_matches(self.query(cx), cx),
166            editor::Event::Blurred if !self.confirmed => {
167                if let Some(delegate) = self.delegate.upgrade(cx) {
168                    delegate.update(cx, |delegate, cx| {
169                        delegate.dismiss(cx);
170                    })
171                }
172            }
173            _ => {}
174        }
175    }
176
177    pub fn update_matches(&mut self, query: String, cx: &mut ViewContext<Self>) {
178        if let Some(delegate) = self.delegate.upgrade(cx) {
179            let update = delegate.update(cx, |d, cx| d.update_matches(query, cx));
180            cx.spawn(|this, mut cx| async move {
181                update.await;
182                this.update(&mut cx, |this, cx| {
183                    if let Some(delegate) = this.delegate.upgrade(cx) {
184                        let delegate = delegate.read(cx);
185                        let index = delegate.selected_index();
186                        let target = if delegate.center_selection_after_match_updates() {
187                            ScrollTarget::Center(index)
188                        } else {
189                            ScrollTarget::Show(index)
190                        };
191                        this.list_state.scroll_to(target);
192                        cx.notify();
193                    }
194                });
195            })
196            .detach()
197        }
198    }
199
200    pub fn select_first(&mut self, _: &SelectFirst, cx: &mut ViewContext<Self>) {
201        if let Some(delegate) = self.delegate.upgrade(cx) {
202            let index = 0;
203            delegate.update(cx, |delegate, cx| delegate.set_selected_index(0, cx));
204            self.list_state.scroll_to(ScrollTarget::Show(index));
205            cx.notify();
206        }
207    }
208
209    pub fn select_index(&mut self, action: &SelectIndex, cx: &mut ViewContext<Self>) {
210        if let Some(delegate) = self.delegate.upgrade(cx) {
211            let index = action.0;
212            self.confirmed = true;
213            delegate.update(cx, |delegate, cx| {
214                delegate.set_selected_index(index, cx);
215                delegate.confirm(cx);
216            });
217        }
218    }
219
220    pub fn select_last(&mut self, _: &SelectLast, cx: &mut ViewContext<Self>) {
221        if let Some(delegate) = self.delegate.upgrade(cx) {
222            let index = delegate.update(cx, |delegate, cx| {
223                let match_count = delegate.match_count();
224                let index = if match_count > 0 { match_count - 1 } else { 0 };
225                delegate.set_selected_index(index, cx);
226                index
227            });
228            self.list_state.scroll_to(ScrollTarget::Show(index));
229            cx.notify();
230        }
231    }
232
233    pub fn select_next(&mut self, _: &SelectNext, cx: &mut ViewContext<Self>) {
234        if let Some(delegate) = self.delegate.upgrade(cx) {
235            let index = delegate.update(cx, |delegate, cx| {
236                let mut selected_index = delegate.selected_index();
237                if selected_index + 1 < delegate.match_count() {
238                    selected_index += 1;
239                    delegate.set_selected_index(selected_index, cx);
240                }
241                selected_index
242            });
243            self.list_state.scroll_to(ScrollTarget::Show(index));
244            cx.notify();
245        }
246    }
247
248    pub fn select_prev(&mut self, _: &SelectPrev, cx: &mut ViewContext<Self>) {
249        if let Some(delegate) = self.delegate.upgrade(cx) {
250            let index = delegate.update(cx, |delegate, cx| {
251                let mut selected_index = delegate.selected_index();
252                if selected_index > 0 {
253                    selected_index -= 1;
254                    delegate.set_selected_index(selected_index, cx);
255                }
256                selected_index
257            });
258            self.list_state.scroll_to(ScrollTarget::Show(index));
259            cx.notify();
260        }
261    }
262
263    fn confirm(&mut self, _: &Confirm, cx: &mut ViewContext<Self>) {
264        if let Some(delegate) = self.delegate.upgrade(cx) {
265            self.confirmed = true;
266            delegate.update(cx, |delegate, cx| delegate.confirm(cx));
267        }
268    }
269
270    fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
271        if let Some(delegate) = self.delegate.upgrade(cx) {
272            delegate.update(cx, |delegate, cx| delegate.dismiss(cx));
273        }
274    }
275}