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            .aligned()
103            .top()
104            .named("picker")
105    }
106
107    fn keymap_context(&self, _: &AppContext) -> keymap::Context {
108        let mut cx = Self::default_keymap_context();
109        cx.set.insert("menu".into());
110        cx
111    }
112
113    fn on_focus(&mut self, cx: &mut ViewContext<Self>) {
114        cx.focus(&self.query_editor);
115    }
116}
117
118impl<D: PickerDelegate> Picker<D> {
119    pub fn init(cx: &mut MutableAppContext) {
120        cx.add_action(Self::select_first);
121        cx.add_action(Self::select_last);
122        cx.add_action(Self::select_next);
123        cx.add_action(Self::select_prev);
124        cx.add_action(Self::select_index);
125        cx.add_action(Self::confirm);
126        cx.add_action(Self::cancel);
127    }
128
129    pub fn new(delegate: WeakViewHandle<D>, cx: &mut ViewContext<Self>) -> Self {
130        let query_editor = cx.add_view(|cx| {
131            Editor::single_line(Some(|theme| theme.selector.input_editor.clone()), cx)
132        });
133        cx.subscribe(&query_editor, Self::on_query_editor_event)
134            .detach();
135        let this = Self {
136            query_editor,
137            list_state: Default::default(),
138            delegate,
139            max_size: vec2f(540., 420.),
140            confirmed: false,
141        };
142        cx.defer(|this, cx| {
143            if let Some(delegate) = this.delegate.upgrade(cx) {
144                cx.observe(&delegate, |_, _, cx| cx.notify()).detach();
145                this.update_matches(String::new(), cx)
146            }
147        });
148        this
149    }
150
151    pub fn with_max_size(mut self, width: f32, height: f32) -> Self {
152        self.max_size = vec2f(width, height);
153        self
154    }
155
156    pub fn query(&self, cx: &AppContext) -> String {
157        self.query_editor.read(cx).text(cx)
158    }
159
160    fn on_query_editor_event(
161        &mut self,
162        _: ViewHandle<Editor>,
163        event: &editor::Event,
164        cx: &mut ViewContext<Self>,
165    ) {
166        match event {
167            editor::Event::BufferEdited { .. } => self.update_matches(self.query(cx), cx),
168            editor::Event::Blurred if !self.confirmed => {
169                if let Some(delegate) = self.delegate.upgrade(cx) {
170                    delegate.update(cx, |delegate, cx| {
171                        delegate.dismiss(cx);
172                    })
173                }
174            }
175            _ => {}
176        }
177    }
178
179    pub fn update_matches(&mut self, query: String, cx: &mut ViewContext<Self>) {
180        if let Some(delegate) = self.delegate.upgrade(cx) {
181            let update = delegate.update(cx, |d, cx| d.update_matches(query, cx));
182            cx.spawn(|this, mut cx| async move {
183                update.await;
184                this.update(&mut cx, |this, cx| {
185                    if let Some(delegate) = this.delegate.upgrade(cx) {
186                        let delegate = delegate.read(cx);
187                        let index = delegate.selected_index();
188                        let target = if delegate.center_selection_after_match_updates() {
189                            ScrollTarget::Center(index)
190                        } else {
191                            ScrollTarget::Show(index)
192                        };
193                        this.list_state.scroll_to(target);
194                        cx.notify();
195                    }
196                });
197            })
198            .detach()
199        }
200    }
201
202    pub fn select_first(&mut self, _: &SelectFirst, cx: &mut ViewContext<Self>) {
203        if let Some(delegate) = self.delegate.upgrade(cx) {
204            let index = 0;
205            delegate.update(cx, |delegate, cx| delegate.set_selected_index(0, cx));
206            self.list_state.scroll_to(ScrollTarget::Show(index));
207            cx.notify();
208        }
209    }
210
211    pub fn select_index(&mut self, action: &SelectIndex, cx: &mut ViewContext<Self>) {
212        if let Some(delegate) = self.delegate.upgrade(cx) {
213            let index = action.0;
214            self.confirmed = true;
215            delegate.update(cx, |delegate, cx| {
216                delegate.set_selected_index(index, cx);
217                delegate.confirm(cx);
218            });
219        }
220    }
221
222    pub fn select_last(&mut self, _: &SelectLast, cx: &mut ViewContext<Self>) {
223        if let Some(delegate) = self.delegate.upgrade(cx) {
224            let index = delegate.update(cx, |delegate, cx| {
225                let match_count = delegate.match_count();
226                let index = if match_count > 0 { match_count - 1 } else { 0 };
227                delegate.set_selected_index(index, cx);
228                index
229            });
230            self.list_state.scroll_to(ScrollTarget::Show(index));
231            cx.notify();
232        }
233    }
234
235    pub fn select_next(&mut self, _: &SelectNext, cx: &mut ViewContext<Self>) {
236        if let Some(delegate) = self.delegate.upgrade(cx) {
237            let index = delegate.update(cx, |delegate, cx| {
238                let mut selected_index = delegate.selected_index();
239                if selected_index + 1 < delegate.match_count() {
240                    selected_index += 1;
241                    delegate.set_selected_index(selected_index, cx);
242                }
243                selected_index
244            });
245            self.list_state.scroll_to(ScrollTarget::Show(index));
246            cx.notify();
247        }
248    }
249
250    pub fn select_prev(&mut self, _: &SelectPrev, cx: &mut ViewContext<Self>) {
251        if let Some(delegate) = self.delegate.upgrade(cx) {
252            let index = delegate.update(cx, |delegate, cx| {
253                let mut selected_index = delegate.selected_index();
254                if selected_index > 0 {
255                    selected_index -= 1;
256                    delegate.set_selected_index(selected_index, cx);
257                }
258                selected_index
259            });
260            self.list_state.scroll_to(ScrollTarget::Show(index));
261            cx.notify();
262        }
263    }
264
265    fn confirm(&mut self, _: &Confirm, cx: &mut ViewContext<Self>) {
266        if let Some(delegate) = self.delegate.upgrade(cx) {
267            self.confirmed = true;
268            delegate.update(cx, |delegate, cx| delegate.confirm(cx));
269        }
270    }
271
272    fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
273        if let Some(delegate) = self.delegate.upgrade(cx) {
274            delegate.update(cx, |delegate, cx| delegate.dismiss(cx));
275        }
276    }
277}