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(500., 420.),
140            confirmed: false,
141        };
142        cx.defer(|this, cx| this.update_matches(cx));
143        this
144    }
145
146    pub fn with_max_size(mut self, width: f32, height: f32) -> Self {
147        self.max_size = vec2f(width, height);
148        self
149    }
150
151    pub fn query(&self, cx: &AppContext) -> String {
152        self.query_editor.read(cx).text(cx)
153    }
154
155    fn on_query_editor_event(
156        &mut self,
157        _: ViewHandle<Editor>,
158        event: &editor::Event,
159        cx: &mut ViewContext<Self>,
160    ) {
161        match event {
162            editor::Event::BufferEdited { .. } => self.update_matches(cx),
163            editor::Event::Blurred if !self.confirmed => {
164                if let Some(delegate) = self.delegate.upgrade(cx) {
165                    delegate.update(cx, |delegate, cx| {
166                        delegate.dismiss(cx);
167                    })
168                }
169            }
170            _ => {}
171        }
172    }
173
174    fn update_matches(&mut self, cx: &mut ViewContext<Self>) {
175        if let Some(delegate) = self.delegate.upgrade(cx) {
176            let query = self.query(cx);
177            let update = delegate.update(cx, |d, cx| d.update_matches(query, cx));
178            cx.notify();
179            cx.spawn(|this, mut cx| async move {
180                update.await;
181                this.update(&mut cx, |this, cx| {
182                    if let Some(delegate) = this.delegate.upgrade(cx) {
183                        let delegate = delegate.read(cx);
184                        let index = delegate.selected_index();
185                        let target = if delegate.center_selection_after_match_updates() {
186                            ScrollTarget::Center(index)
187                        } else {
188                            ScrollTarget::Show(index)
189                        };
190                        this.list_state.scroll_to(target);
191                        cx.notify();
192                    }
193                });
194            })
195            .detach()
196        }
197    }
198
199    pub fn select_first(&mut self, _: &SelectFirst, cx: &mut ViewContext<Self>) {
200        if let Some(delegate) = self.delegate.upgrade(cx) {
201            let index = 0;
202            delegate.update(cx, |delegate, cx| delegate.set_selected_index(0, cx));
203            self.list_state.scroll_to(ScrollTarget::Show(index));
204            cx.notify();
205        }
206    }
207
208    pub fn select_index(&mut self, action: &SelectIndex, cx: &mut ViewContext<Self>) {
209        if let Some(delegate) = self.delegate.upgrade(cx) {
210            let index = action.0;
211            self.confirmed = true;
212            delegate.update(cx, |delegate, cx| {
213                delegate.set_selected_index(index, cx);
214                delegate.confirm(cx);
215            });
216        }
217    }
218
219    pub fn select_last(&mut self, _: &SelectLast, cx: &mut ViewContext<Self>) {
220        if let Some(delegate) = self.delegate.upgrade(cx) {
221            let index = delegate.update(cx, |delegate, cx| {
222                let match_count = delegate.match_count();
223                let index = if match_count > 0 { match_count - 1 } else { 0 };
224                delegate.set_selected_index(index, cx);
225                index
226            });
227            self.list_state.scroll_to(ScrollTarget::Show(index));
228            cx.notify();
229        }
230    }
231
232    pub fn select_next(&mut self, _: &SelectNext, cx: &mut ViewContext<Self>) {
233        if let Some(delegate) = self.delegate.upgrade(cx) {
234            let index = delegate.update(cx, |delegate, cx| {
235                let mut selected_index = delegate.selected_index();
236                if selected_index + 1 < delegate.match_count() {
237                    selected_index += 1;
238                    delegate.set_selected_index(selected_index, cx);
239                }
240                selected_index
241            });
242            self.list_state.scroll_to(ScrollTarget::Show(index));
243            cx.notify();
244        }
245    }
246
247    pub fn select_prev(&mut self, _: &SelectPrev, cx: &mut ViewContext<Self>) {
248        if let Some(delegate) = self.delegate.upgrade(cx) {
249            let index = delegate.update(cx, |delegate, cx| {
250                let mut selected_index = delegate.selected_index();
251                if selected_index > 0 {
252                    selected_index -= 1;
253                    delegate.set_selected_index(selected_index, cx);
254                }
255                selected_index
256            });
257            self.list_state.scroll_to(ScrollTarget::Show(index));
258            cx.notify();
259        }
260    }
261
262    fn confirm(&mut self, _: &Confirm, cx: &mut ViewContext<Self>) {
263        if let Some(delegate) = self.delegate.upgrade(cx) {
264            self.confirmed = true;
265            delegate.update(cx, |delegate, cx| delegate.confirm(cx));
266        }
267    }
268
269    fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
270        if let Some(delegate) = self.delegate.upgrade(cx) {
271            delegate.update(cx, |delegate, cx| delegate.dismiss(cx));
272        }
273    }
274}