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