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 fn on_query_editor_event(
212 &mut self,
213 _: ViewHandle<Editor>,
214 event: &editor::Event,
215 cx: &mut ViewContext<Self>,
216 ) {
217 match event {
218 editor::Event::BufferEdited { .. } => self.update_matches(self.query(cx), cx),
219 editor::Event::Blurred if !self.confirmed => {
220 if let Some(delegate) = self.delegate.upgrade(cx) {
221 delegate.update(cx, |delegate, cx| {
222 delegate.dismiss(cx);
223 })
224 }
225 }
226 _ => {}
227 }
228 }
229
230 pub fn update_matches(&mut self, query: String, cx: &mut ViewContext<Self>) {
231 if let Some(delegate) = self.delegate.upgrade(cx) {
232 let update = delegate.update(cx, |d, cx| d.update_matches(query, cx));
233 cx.spawn(|this, mut cx| async move {
234 update.await;
235 this.update(&mut cx, |this, cx| {
236 if let Some(delegate) = this.delegate.upgrade(cx) {
237 let delegate = delegate.read(cx);
238 let index = delegate.selected_index();
239 let target = if delegate.center_selection_after_match_updates() {
240 ScrollTarget::Center(index)
241 } else {
242 ScrollTarget::Show(index)
243 };
244 this.list_state.scroll_to(target);
245 cx.notify();
246 }
247 });
248 })
249 .detach()
250 }
251 }
252
253 pub fn select_first(&mut self, _: &SelectFirst, cx: &mut ViewContext<Self>) {
254 if let Some(delegate) = self.delegate.upgrade(cx) {
255 let index = 0;
256 delegate.update(cx, |delegate, cx| delegate.set_selected_index(0, cx));
257 self.list_state.scroll_to(ScrollTarget::Show(index));
258 cx.notify();
259 }
260 }
261
262 pub fn select_index(&mut self, action: &SelectIndex, cx: &mut ViewContext<Self>) {
263 if let Some(delegate) = self.delegate.upgrade(cx) {
264 let index = action.0;
265 self.confirmed = true;
266 delegate.update(cx, |delegate, cx| {
267 delegate.set_selected_index(index, cx);
268 delegate.confirm(cx);
269 });
270 }
271 }
272
273 pub fn select_last(&mut self, _: &SelectLast, cx: &mut ViewContext<Self>) {
274 if let Some(delegate) = self.delegate.upgrade(cx) {
275 let index = delegate.update(cx, |delegate, cx| {
276 let match_count = delegate.match_count();
277 let index = if match_count > 0 { match_count - 1 } else { 0 };
278 delegate.set_selected_index(index, cx);
279 index
280 });
281 self.list_state.scroll_to(ScrollTarget::Show(index));
282 cx.notify();
283 }
284 }
285
286 pub fn select_next(&mut self, _: &SelectNext, cx: &mut ViewContext<Self>) {
287 if let Some(delegate) = self.delegate.upgrade(cx) {
288 let index = delegate.update(cx, |delegate, cx| {
289 let mut selected_index = delegate.selected_index();
290 if selected_index + 1 < delegate.match_count() {
291 selected_index += 1;
292 delegate.set_selected_index(selected_index, cx);
293 }
294 selected_index
295 });
296 self.list_state.scroll_to(ScrollTarget::Show(index));
297 cx.notify();
298 }
299 }
300
301 pub fn select_prev(&mut self, _: &SelectPrev, cx: &mut ViewContext<Self>) {
302 if let Some(delegate) = self.delegate.upgrade(cx) {
303 let index = delegate.update(cx, |delegate, cx| {
304 let mut selected_index = delegate.selected_index();
305 if selected_index > 0 {
306 selected_index -= 1;
307 delegate.set_selected_index(selected_index, cx);
308 }
309 selected_index
310 });
311 self.list_state.scroll_to(ScrollTarget::Show(index));
312 cx.notify();
313 }
314 }
315
316 fn confirm(&mut self, _: &Confirm, cx: &mut ViewContext<Self>) {
317 if let Some(delegate) = self.delegate.upgrade(cx) {
318 self.confirmed = true;
319 delegate.update(cx, |delegate, cx| delegate.confirm(cx));
320 }
321 }
322
323 fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
324 if let Some(delegate) = self.delegate.upgrade(cx) {
325 delegate.update(cx, |delegate, cx| delegate.dismiss(cx));
326 }
327 }
328}