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