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 .on_down(MouseButton::Left, move |_, cx| {
106 cx.dispatch_action(SelectIndex(ix))
107 })
108 .with_cursor_style(CursorStyle::PointingHand)
109 .boxed()
110 }));
111 },
112 )
113 .contained()
114 .with_margin_top(6.0)
115 .flex(1., false)
116 .boxed(),
117 )
118 })
119 .contained()
120 .with_style(container_style)
121 .constrained()
122 .with_max_width(self.max_size.x())
123 .with_max_height(self.max_size.y())
124 .named("picker")
125 }
126
127 fn keymap_context(&self, _: &AppContext) -> KeymapContext {
128 let mut cx = Self::default_keymap_context();
129 cx.add_identifier("menu");
130 cx
131 }
132
133 fn focus_in(&mut self, _: AnyViewHandle, cx: &mut ViewContext<Self>) {
134 if cx.is_self_focused() {
135 cx.focus(&self.query_editor);
136 }
137 }
138}
139
140impl<D: PickerDelegate> Picker<D> {
141 pub fn init(cx: &mut MutableAppContext) {
142 cx.add_action(Self::select_first);
143 cx.add_action(Self::select_last);
144 cx.add_action(Self::select_next);
145 cx.add_action(Self::select_prev);
146 cx.add_action(Self::select_index);
147 cx.add_action(Self::confirm);
148 cx.add_action(Self::cancel);
149 }
150
151 pub fn new<P>(placeholder: P, delegate: WeakViewHandle<D>, cx: &mut ViewContext<Self>) -> Self
152 where
153 P: Into<Arc<str>>,
154 {
155 let theme = Arc::new(Mutex::new(
156 Box::new(|theme: &theme::Theme| theme.picker.clone())
157 as Box<dyn Fn(&theme::Theme) -> theme::Picker>,
158 ));
159 let query_editor = cx.add_view({
160 let picker_theme = theme.clone();
161 |cx| {
162 let mut editor = Editor::single_line(
163 Some(Arc::new(move |theme| {
164 (picker_theme.lock())(theme).input_editor.clone()
165 })),
166 cx,
167 );
168 editor.set_placeholder_text(placeholder, cx);
169 editor
170 }
171 });
172 cx.subscribe(&query_editor, Self::on_query_editor_event)
173 .detach();
174 let this = Self {
175 query_editor,
176 list_state: Default::default(),
177 delegate,
178 max_size: vec2f(540., 420.),
179 theme,
180 confirmed: false,
181 };
182 cx.defer(|this, cx| {
183 if let Some(delegate) = this.delegate.upgrade(cx) {
184 cx.observe(&delegate, |_, _, cx| cx.notify()).detach();
185 this.update_matches(String::new(), cx)
186 }
187 });
188 this
189 }
190
191 pub fn with_max_size(mut self, width: f32, height: f32) -> Self {
192 self.max_size = vec2f(width, height);
193 self
194 }
195
196 pub fn with_theme<F>(self, theme: F) -> Self
197 where
198 F: 'static + Fn(&theme::Theme) -> theme::Picker,
199 {
200 *self.theme.lock() = Box::new(theme);
201 self
202 }
203
204 pub fn query(&self, cx: &AppContext) -> String {
205 self.query_editor.read(cx).text(cx)
206 }
207
208 pub fn set_query(&self, query: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
209 self.query_editor
210 .update(cx, |editor, cx| editor.set_text(query, cx));
211 }
212
213 fn on_query_editor_event(
214 &mut self,
215 _: ViewHandle<Editor>,
216 event: &editor::Event,
217 cx: &mut ViewContext<Self>,
218 ) {
219 match event {
220 editor::Event::BufferEdited { .. } => self.update_matches(self.query(cx), cx),
221 editor::Event::Blurred if !self.confirmed => {
222 if let Some(delegate) = self.delegate.upgrade(cx) {
223 delegate.update(cx, |delegate, cx| {
224 delegate.dismiss(cx);
225 })
226 }
227 }
228 _ => {}
229 }
230 }
231
232 pub fn update_matches(&mut self, query: String, cx: &mut ViewContext<Self>) {
233 if let Some(delegate) = self.delegate.upgrade(cx) {
234 let update = delegate.update(cx, |d, cx| d.update_matches(query, cx));
235 cx.spawn(|this, mut cx| async move {
236 update.await;
237 this.update(&mut cx, |this, cx| {
238 if let Some(delegate) = this.delegate.upgrade(cx) {
239 let delegate = delegate.read(cx);
240 let index = delegate.selected_index();
241 let target = if delegate.center_selection_after_match_updates() {
242 ScrollTarget::Center(index)
243 } else {
244 ScrollTarget::Show(index)
245 };
246 this.list_state.scroll_to(target);
247 cx.notify();
248 }
249 });
250 })
251 .detach()
252 }
253 }
254
255 pub fn select_first(&mut self, _: &SelectFirst, cx: &mut ViewContext<Self>) {
256 if let Some(delegate) = self.delegate.upgrade(cx) {
257 let index = 0;
258 delegate.update(cx, |delegate, cx| delegate.set_selected_index(0, cx));
259 self.list_state.scroll_to(ScrollTarget::Show(index));
260 cx.notify();
261 }
262 }
263
264 pub fn select_index(&mut self, action: &SelectIndex, cx: &mut ViewContext<Self>) {
265 if let Some(delegate) = self.delegate.upgrade(cx) {
266 let index = action.0;
267 self.confirmed = true;
268 delegate.update(cx, |delegate, cx| {
269 delegate.set_selected_index(index, cx);
270 delegate.confirm(cx);
271 });
272 }
273 }
274
275 pub fn select_last(&mut self, _: &SelectLast, cx: &mut ViewContext<Self>) {
276 if let Some(delegate) = self.delegate.upgrade(cx) {
277 let index = delegate.update(cx, |delegate, cx| {
278 let match_count = delegate.match_count();
279 let index = if match_count > 0 { match_count - 1 } else { 0 };
280 delegate.set_selected_index(index, cx);
281 index
282 });
283 self.list_state.scroll_to(ScrollTarget::Show(index));
284 cx.notify();
285 }
286 }
287
288 pub fn select_next(&mut self, _: &SelectNext, cx: &mut ViewContext<Self>) {
289 if let Some(delegate) = self.delegate.upgrade(cx) {
290 let index = delegate.update(cx, |delegate, cx| {
291 let mut selected_index = delegate.selected_index();
292 if selected_index + 1 < delegate.match_count() {
293 selected_index += 1;
294 delegate.set_selected_index(selected_index, cx);
295 }
296 selected_index
297 });
298 self.list_state.scroll_to(ScrollTarget::Show(index));
299 cx.notify();
300 }
301 }
302
303 pub fn select_prev(&mut self, _: &SelectPrev, cx: &mut ViewContext<Self>) {
304 if let Some(delegate) = self.delegate.upgrade(cx) {
305 let index = delegate.update(cx, |delegate, cx| {
306 let mut selected_index = delegate.selected_index();
307 if selected_index > 0 {
308 selected_index -= 1;
309 delegate.set_selected_index(selected_index, cx);
310 }
311 selected_index
312 });
313 self.list_state.scroll_to(ScrollTarget::Show(index));
314 cx.notify();
315 }
316 }
317
318 fn confirm(&mut self, _: &Confirm, cx: &mut ViewContext<Self>) {
319 if let Some(delegate) = self.delegate.upgrade(cx) {
320 self.confirmed = true;
321 delegate.update(cx, |delegate, cx| delegate.confirm(cx));
322 }
323 }
324
325 fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
326 if let Some(delegate) = self.delegate.upgrade(cx) {
327 delegate.update(cx, |delegate, cx| delegate.dismiss(cx));
328 }
329 }
330}