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