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