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, SelectFirst, 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 pending_update_matches: Task<Option<()>>,
28}
29
30pub trait PickerDelegate: Sized + 'static {
31 fn placeholder_text(&self) -> Arc<str>;
32 fn match_count(&self) -> usize;
33 fn selected_index(&self) -> usize;
34 fn set_selected_index(&mut self, ix: usize, cx: &mut ViewContext<Picker<Self>>);
35 fn update_matches(&mut self, query: String, cx: &mut ViewContext<Picker<Self>>) -> Task<()>;
36 fn confirm(&mut self, cx: &mut ViewContext<Picker<Self>>);
37 fn dismissed(&mut self, cx: &mut ViewContext<Picker<Self>>);
38 fn render_match(
39 &self,
40 ix: usize,
41 state: &mut MouseState,
42 selected: bool,
43 cx: &AppContext,
44 ) -> AnyElement<Picker<Self>>;
45 fn center_selection_after_match_updates(&self) -> bool {
46 false
47 }
48}
49
50impl<D: PickerDelegate> Entity for Picker<D> {
51 type Event = PickerEvent;
52}
53
54impl<D: PickerDelegate> View for Picker<D> {
55 fn ui_name() -> &'static str {
56 "Picker"
57 }
58
59 fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
60 let theme = (self.theme.lock())(&cx.global::<settings::Settings>().theme);
61 let query = self.query(cx);
62 let match_count = self.delegate.match_count();
63
64 let container_style;
65 let editor_style;
66 if query.is_empty() && match_count == 0 {
67 container_style = theme.empty_container;
68 editor_style = theme.empty_input_editor.container;
69 } else {
70 container_style = theme.container;
71 editor_style = theme.input_editor.container;
72 };
73
74 Flex::new(Axis::Vertical)
75 .with_child(
76 ChildView::new(&self.query_editor, cx)
77 .contained()
78 .with_style(editor_style),
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 .into_any(),
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 |_, picker, cx| {
108 picker.select_index(ix, cx);
109 })
110 .with_cursor_style(CursorStyle::PointingHand)
111 .into_any()
112 }));
113 },
114 )
115 .contained()
116 .with_margin_top(6.0)
117 .flex(1., false)
118 .into_any(),
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 .into_any_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::confirm);
155 cx.add_action(Self::cancel);
156 }
157
158 pub fn new(delegate: D, cx: &mut ViewContext<Self>) -> Self {
159 let theme = Arc::new(Mutex::new(
160 Box::new(|theme: &theme::Theme| theme.picker.clone())
161 as Box<dyn Fn(&theme::Theme) -> theme::Picker>,
162 ));
163 let placeholder_text = delegate.placeholder_text();
164 let query_editor = cx.add_view({
165 let picker_theme = theme.clone();
166 |cx| {
167 let mut editor = Editor::single_line(
168 Some(Arc::new(move |theme| {
169 (picker_theme.lock())(theme).input_editor.clone()
170 })),
171 cx,
172 );
173 editor.set_placeholder_text(placeholder_text, cx);
174 editor
175 }
176 });
177 cx.subscribe(&query_editor, Self::on_query_editor_event)
178 .detach();
179 let mut this = Self {
180 query_editor,
181 list_state: Default::default(),
182 delegate,
183 max_size: vec2f(540., 420.),
184 theme,
185 confirmed: false,
186 pending_update_matches: Task::ready(None),
187 };
188 this.update_matches(String::new(), cx);
189 this
190 }
191
192 pub fn with_max_size(mut self, width: f32, height: f32) -> Self {
193 self.max_size = vec2f(width, height);
194 self
195 }
196
197 pub fn with_theme<F>(self, theme: F) -> Self
198 where
199 F: 'static + Fn(&theme::Theme) -> theme::Picker,
200 {
201 *self.theme.lock() = Box::new(theme);
202 self
203 }
204
205 pub fn delegate(&self) -> &D {
206 &self.delegate
207 }
208
209 pub fn delegate_mut(&mut self) -> &mut D {
210 &mut self.delegate
211 }
212
213 pub fn query(&self, cx: &AppContext) -> String {
214 self.query_editor.read(cx).text(cx)
215 }
216
217 pub fn set_query(&self, query: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
218 self.query_editor
219 .update(cx, |editor, cx| editor.set_text(query, cx));
220 }
221
222 fn on_query_editor_event(
223 &mut self,
224 _: ViewHandle<Editor>,
225 event: &editor::Event,
226 cx: &mut ViewContext<Self>,
227 ) {
228 match event {
229 editor::Event::BufferEdited { .. } => self.update_matches(self.query(cx), cx),
230 editor::Event::Blurred if !self.confirmed => {
231 self.dismiss(cx);
232 }
233 _ => {}
234 }
235 }
236
237 pub fn update_matches(&mut self, query: String, cx: &mut ViewContext<Self>) {
238 let update = self.delegate.update_matches(query, cx);
239 self.matches_updated(cx);
240 self.pending_update_matches = cx.spawn(|this, mut cx| async move {
241 update.await;
242 this.update(&mut cx, |this, cx| this.matches_updated(cx))
243 .log_err()
244 });
245 }
246
247 fn matches_updated(&mut self, cx: &mut ViewContext<Self>) {
248 let index = self.delegate.selected_index();
249 let target = if self.delegate.center_selection_after_match_updates() {
250 ScrollTarget::Center(index)
251 } else {
252 ScrollTarget::Show(index)
253 };
254 self.list_state.scroll_to(target);
255 cx.notify();
256 }
257
258 pub fn select_first(&mut self, _: &SelectFirst, cx: &mut ViewContext<Self>) {
259 if self.delegate.match_count() > 0 {
260 self.delegate.set_selected_index(0, cx);
261 self.list_state.scroll_to(ScrollTarget::Show(0));
262 }
263
264 cx.notify();
265 }
266
267 pub fn select_index(&mut self, index: usize, cx: &mut ViewContext<Self>) {
268 if self.delegate.match_count() > 0 {
269 self.confirmed = true;
270 self.delegate.set_selected_index(index, cx);
271 self.delegate.confirm(cx);
272 }
273 }
274
275 pub fn select_last(&mut self, _: &SelectLast, cx: &mut ViewContext<Self>) {
276 let match_count = self.delegate.match_count();
277 if match_count > 0 {
278 let index = match_count - 1;
279 self.delegate.set_selected_index(index, cx);
280 self.list_state.scroll_to(ScrollTarget::Show(index));
281 }
282 cx.notify();
283 }
284
285 pub fn select_next(&mut self, _: &SelectNext, cx: &mut ViewContext<Self>) {
286 let next_index = self.delegate.selected_index() + 1;
287 if next_index < self.delegate.match_count() {
288 self.delegate.set_selected_index(next_index, cx);
289 self.list_state.scroll_to(ScrollTarget::Show(next_index));
290 }
291
292 cx.notify();
293 }
294
295 pub fn select_prev(&mut self, _: &SelectPrev, cx: &mut ViewContext<Self>) {
296 let mut selected_index = self.delegate.selected_index();
297 if selected_index > 0 {
298 selected_index -= 1;
299 self.delegate.set_selected_index(selected_index, cx);
300 self.list_state
301 .scroll_to(ScrollTarget::Show(selected_index));
302 }
303
304 cx.notify();
305 }
306
307 pub fn confirm(&mut self, _: &Confirm, cx: &mut ViewContext<Self>) {
308 self.confirmed = true;
309 self.delegate.confirm(cx);
310 }
311
312 fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
313 self.dismiss(cx);
314 }
315
316 fn dismiss(&mut self, cx: &mut ViewContext<Self>) {
317 cx.emit(PickerEvent::Dismiss);
318 self.delegate.dismissed(cx);
319 }
320}