1use gpui::{
2 anyhow,
3 elements::*,
4 geometry::vector::Vector2F,
5 keymap_matcher::KeymapContext,
6 platform::{CursorStyle, MouseButton},
7 Action, AnyViewHandle, AppContext, Axis, Entity, MouseState, SizeConstraint, Subscription,
8 View, ViewContext,
9};
10use menu::*;
11use std::{any::TypeId, borrow::Cow, sync::Arc, time::Duration};
12
13pub fn init(cx: &mut AppContext) {
14 cx.add_action(ContextMenu::select_first);
15 cx.add_action(ContextMenu::select_last);
16 cx.add_action(ContextMenu::select_next);
17 cx.add_action(ContextMenu::select_prev);
18 cx.add_action(ContextMenu::confirm);
19 cx.add_action(ContextMenu::cancel);
20}
21
22pub type StaticItem = Box<dyn Fn(&mut AppContext) -> AnyElement<ContextMenu>>;
23
24type ContextMenuItemBuilder =
25 Box<dyn Fn(&mut MouseState, &theme::ContextMenuItem) -> AnyElement<ContextMenu>>;
26
27pub enum ContextMenuItemLabel {
28 String(Cow<'static, str>),
29 Element(ContextMenuItemBuilder),
30}
31
32impl From<Cow<'static, str>> for ContextMenuItemLabel {
33 fn from(s: Cow<'static, str>) -> Self {
34 Self::String(s)
35 }
36}
37
38impl From<&'static str> for ContextMenuItemLabel {
39 fn from(s: &'static str) -> Self {
40 Self::String(s.into())
41 }
42}
43
44impl From<String> for ContextMenuItemLabel {
45 fn from(s: String) -> Self {
46 Self::String(s.into())
47 }
48}
49
50impl<T> From<T> for ContextMenuItemLabel
51where
52 T: 'static + Fn(&mut MouseState, &theme::ContextMenuItem) -> AnyElement<ContextMenu>,
53{
54 fn from(f: T) -> Self {
55 Self::Element(Box::new(f))
56 }
57}
58
59pub enum ContextMenuItemAction {
60 Action(Box<dyn Action>),
61 Handler(Arc<dyn Fn(&mut ViewContext<ContextMenu>)>),
62}
63
64impl Clone for ContextMenuItemAction {
65 fn clone(&self) -> Self {
66 match self {
67 Self::Action(action) => Self::Action(action.boxed_clone()),
68 Self::Handler(handler) => Self::Handler(handler.clone()),
69 }
70 }
71}
72
73pub enum ContextMenuItem {
74 Item {
75 label: ContextMenuItemLabel,
76 action: ContextMenuItemAction,
77 },
78 Static(StaticItem),
79 Separator,
80}
81
82impl ContextMenuItem {
83 pub fn action(label: impl Into<ContextMenuItemLabel>, action: impl 'static + Action) -> Self {
84 Self::Item {
85 label: label.into(),
86 action: ContextMenuItemAction::Action(Box::new(action)),
87 }
88 }
89
90 pub fn handler(
91 label: impl Into<ContextMenuItemLabel>,
92 handler: impl 'static + Fn(&mut ViewContext<ContextMenu>),
93 ) -> Self {
94 Self::Item {
95 label: label.into(),
96 action: ContextMenuItemAction::Handler(Arc::new(handler)),
97 }
98 }
99
100 pub fn separator() -> Self {
101 Self::Separator
102 }
103
104 fn is_action(&self) -> bool {
105 matches!(self, Self::Item { .. })
106 }
107
108 fn action_id(&self) -> Option<TypeId> {
109 match self {
110 ContextMenuItem::Item { action, .. } => match action {
111 ContextMenuItemAction::Action(action) => Some(action.id()),
112 ContextMenuItemAction::Handler(_) => None,
113 },
114 ContextMenuItem::Static(..) | ContextMenuItem::Separator => None,
115 }
116 }
117}
118
119pub struct ContextMenu {
120 show_count: usize,
121 anchor_position: Vector2F,
122 anchor_corner: AnchorCorner,
123 position_mode: OverlayPositionMode,
124 items: Vec<ContextMenuItem>,
125 selected_index: Option<usize>,
126 visible: bool,
127 delay_cancel: bool,
128 previously_focused_view_id: Option<usize>,
129 parent_view_id: usize,
130 _actions_observation: Subscription,
131}
132
133impl Entity for ContextMenu {
134 type Event = ();
135}
136
137impl View for ContextMenu {
138 fn ui_name() -> &'static str {
139 "ContextMenu"
140 }
141
142 fn update_keymap_context(&self, keymap: &mut KeymapContext, _: &AppContext) {
143 Self::reset_to_default_keymap_context(keymap);
144 keymap.add_identifier("menu");
145 }
146
147 fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
148 if !self.visible {
149 return Empty::new().into_any();
150 }
151
152 // Render the menu once at minimum width.
153 let mut collapsed_menu = self.render_menu_for_measurement(cx);
154 let expanded_menu =
155 self.render_menu(cx)
156 .constrained()
157 .dynamically(move |constraint, view, cx| {
158 SizeConstraint::strict_along(
159 Axis::Horizontal,
160 collapsed_menu.layout(constraint, view, cx).0.x(),
161 )
162 });
163
164 Overlay::new(expanded_menu)
165 .with_hoverable(true)
166 .with_fit_mode(OverlayFitMode::SnapToWindow)
167 .with_anchor_position(self.anchor_position)
168 .with_anchor_corner(self.anchor_corner)
169 .with_position_mode(self.position_mode)
170 .into_any()
171 }
172
173 fn focus_out(&mut self, _: AnyViewHandle, cx: &mut ViewContext<Self>) {
174 self.reset(cx);
175 }
176}
177
178impl ContextMenu {
179 pub fn new(parent_view_id: usize, cx: &mut ViewContext<Self>) -> Self {
180 Self {
181 show_count: 0,
182 delay_cancel: false,
183 anchor_position: Default::default(),
184 anchor_corner: AnchorCorner::TopLeft,
185 position_mode: OverlayPositionMode::Window,
186 items: Default::default(),
187 selected_index: Default::default(),
188 visible: Default::default(),
189 previously_focused_view_id: Default::default(),
190 parent_view_id,
191 _actions_observation: cx.observe_actions(Self::action_dispatched),
192 }
193 }
194
195 pub fn visible(&self) -> bool {
196 self.visible
197 }
198
199 fn action_dispatched(&mut self, action_id: TypeId, cx: &mut ViewContext<Self>) {
200 if let Some(ix) = self
201 .items
202 .iter()
203 .position(|item| item.action_id() == Some(action_id))
204 {
205 self.selected_index = Some(ix);
206 cx.notify();
207 cx.spawn(|this, mut cx| async move {
208 cx.background().timer(Duration::from_millis(50)).await;
209 this.update(&mut cx, |this, cx| this.cancel(&Default::default(), cx))?;
210 anyhow::Ok(())
211 })
212 .detach_and_log_err(cx);
213 }
214 }
215
216 fn confirm(&mut self, _: &Confirm, cx: &mut ViewContext<Self>) {
217 if let Some(ix) = self.selected_index {
218 if let Some(ContextMenuItem::Item { action, .. }) = self.items.get(ix) {
219 match action {
220 ContextMenuItemAction::Action(action) => {
221 let window = cx.window();
222 let view_id = self.parent_view_id;
223 let action = action.boxed_clone();
224 cx.app_context()
225 .spawn(|mut cx| async move {
226 cx.dispatch_action(window, view_id, action.as_ref())
227 })
228 .detach_and_log_err(cx);
229 }
230 ContextMenuItemAction::Handler(handler) => handler(cx),
231 }
232 self.reset(cx);
233 }
234 }
235 }
236
237 pub fn delay_cancel(&mut self) {
238 self.delay_cancel = true;
239 }
240
241 fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
242 if !self.delay_cancel {
243 self.reset(cx);
244 let show_count = self.show_count;
245 cx.defer(move |this, cx| {
246 if cx.handle().is_focused(cx) && this.show_count == show_count {
247 (**cx).focus(this.previously_focused_view_id.take());
248 }
249 });
250 } else {
251 self.delay_cancel = false;
252 }
253 }
254
255 fn reset(&mut self, cx: &mut ViewContext<Self>) {
256 self.items.clear();
257 self.visible = false;
258 self.selected_index.take();
259 cx.notify();
260 }
261
262 fn select_first(&mut self, _: &SelectFirst, cx: &mut ViewContext<Self>) {
263 self.selected_index = self.items.iter().position(|item| item.is_action());
264 cx.notify();
265 }
266
267 fn select_last(&mut self, _: &SelectLast, cx: &mut ViewContext<Self>) {
268 for (ix, item) in self.items.iter().enumerate().rev() {
269 if item.is_action() {
270 self.selected_index = Some(ix);
271 cx.notify();
272 break;
273 }
274 }
275 }
276
277 fn select_next(&mut self, _: &SelectNext, cx: &mut ViewContext<Self>) {
278 if let Some(ix) = self.selected_index {
279 for (ix, item) in self.items.iter().enumerate().skip(ix + 1) {
280 if item.is_action() {
281 self.selected_index = Some(ix);
282 cx.notify();
283 break;
284 }
285 }
286 } else {
287 self.select_first(&Default::default(), cx);
288 }
289 }
290
291 fn select_prev(&mut self, _: &SelectPrev, cx: &mut ViewContext<Self>) {
292 if let Some(ix) = self.selected_index {
293 for (ix, item) in self.items.iter().enumerate().take(ix).rev() {
294 if item.is_action() {
295 self.selected_index = Some(ix);
296 cx.notify();
297 break;
298 }
299 }
300 } else {
301 self.select_last(&Default::default(), cx);
302 }
303 }
304
305 pub fn toggle(
306 &mut self,
307 anchor_position: Vector2F,
308 anchor_corner: AnchorCorner,
309 items: Vec<ContextMenuItem>,
310 cx: &mut ViewContext<Self>,
311 ) {
312 if self.visible() {
313 self.cancel(&Cancel, cx);
314 } else {
315 let mut items = items.into_iter().peekable();
316 if items.peek().is_some() {
317 self.items = items.collect();
318 self.anchor_position = anchor_position;
319 self.anchor_corner = anchor_corner;
320 self.visible = true;
321 self.show_count += 1;
322 if !cx.is_self_focused() {
323 self.previously_focused_view_id = cx.focused_view_id();
324 }
325 cx.focus_self();
326 } else {
327 self.visible = false;
328 }
329 }
330 cx.notify();
331 }
332
333 pub fn show(
334 &mut self,
335 anchor_position: Vector2F,
336 anchor_corner: AnchorCorner,
337 items: Vec<ContextMenuItem>,
338 cx: &mut ViewContext<Self>,
339 ) {
340 let mut items = items.into_iter().peekable();
341 if items.peek().is_some() {
342 self.items = items.collect();
343 self.anchor_position = anchor_position;
344 self.anchor_corner = anchor_corner;
345 self.visible = true;
346 self.show_count += 1;
347 if !cx.is_self_focused() {
348 self.previously_focused_view_id = cx.focused_view_id();
349 }
350 cx.focus_self();
351 } else {
352 self.visible = false;
353 }
354 cx.notify();
355 }
356
357 pub fn set_position_mode(&mut self, mode: OverlayPositionMode) {
358 self.position_mode = mode;
359 }
360
361 fn render_menu_for_measurement(&self, cx: &mut ViewContext<Self>) -> impl Element<ContextMenu> {
362 let style = theme::current(cx).context_menu.clone();
363 Flex::row()
364 .with_child(
365 Flex::column().with_children(self.items.iter().enumerate().map(|(ix, item)| {
366 match item {
367 ContextMenuItem::Item { label, .. } => {
368 let style = style.item.in_state(self.selected_index == Some(ix));
369 let style = style.style_for(&mut Default::default());
370
371 match label {
372 ContextMenuItemLabel::String(label) => {
373 Label::new(label.to_string(), style.label.clone())
374 .contained()
375 .with_style(style.container)
376 .into_any()
377 }
378 ContextMenuItemLabel::Element(element) => {
379 element(&mut Default::default(), style)
380 }
381 }
382 }
383
384 ContextMenuItem::Static(f) => f(cx),
385
386 ContextMenuItem::Separator => Empty::new()
387 .collapsed()
388 .contained()
389 .with_style(style.separator)
390 .constrained()
391 .with_height(1.)
392 .into_any(),
393 }
394 })),
395 )
396 .with_child(
397 Flex::column()
398 .with_children(self.items.iter().enumerate().map(|(ix, item)| {
399 match item {
400 ContextMenuItem::Item { action, .. } => {
401 let style = style.item.in_state(self.selected_index == Some(ix));
402 let style = style.style_for(&mut Default::default());
403
404 match action {
405 ContextMenuItemAction::Action(action) => KeystrokeLabel::new(
406 self.parent_view_id,
407 action.boxed_clone(),
408 style.keystroke.container,
409 style.keystroke.text.clone(),
410 )
411 .into_any(),
412 ContextMenuItemAction::Handler(_) => Empty::new().into_any(),
413 }
414 }
415
416 ContextMenuItem::Static(_) => Empty::new().into_any(),
417
418 ContextMenuItem::Separator => Empty::new()
419 .collapsed()
420 .constrained()
421 .with_height(1.)
422 .contained()
423 .with_style(style.separator)
424 .into_any(),
425 }
426 }))
427 .contained()
428 .with_margin_left(style.keystroke_margin),
429 )
430 .contained()
431 .with_style(style.container)
432 }
433
434 fn render_menu(&self, cx: &mut ViewContext<Self>) -> impl Element<ContextMenu> {
435 enum Menu {}
436 enum MenuItem {}
437
438 let style = theme::current(cx).context_menu.clone();
439
440 MouseEventHandler::<Menu, ContextMenu>::new(0, cx, |_, cx| {
441 Flex::column()
442 .with_children(self.items.iter().enumerate().map(|(ix, item)| {
443 match item {
444 ContextMenuItem::Item { label, action } => {
445 let action = action.clone();
446 let view_id = self.parent_view_id;
447 MouseEventHandler::<MenuItem, ContextMenu>::new(ix, cx, |state, _| {
448 let style = style.item.in_state(self.selected_index == Some(ix));
449 let style = style.style_for(state);
450 let keystroke = match &action {
451 ContextMenuItemAction::Action(action) => Some(
452 KeystrokeLabel::new(
453 view_id,
454 action.boxed_clone(),
455 style.keystroke.container,
456 style.keystroke.text.clone(),
457 )
458 .flex_float(),
459 ),
460 ContextMenuItemAction::Handler(_) => None,
461 };
462
463 Flex::row()
464 .with_child(match label {
465 ContextMenuItemLabel::String(label) => {
466 Label::new(label.clone(), style.label.clone())
467 .contained()
468 .into_any()
469 }
470 ContextMenuItemLabel::Element(element) => {
471 element(state, style)
472 }
473 })
474 .with_children(keystroke)
475 .contained()
476 .with_style(style.container)
477 })
478 .with_cursor_style(CursorStyle::PointingHand)
479 .on_up(MouseButton::Left, |_, _, _| {}) // Capture these events
480 .on_down(MouseButton::Left, |_, _, _| {}) // Capture these events
481 .on_click(MouseButton::Left, move |_, menu, cx| {
482 menu.cancel(&Default::default(), cx);
483 let window = cx.window();
484 match &action {
485 ContextMenuItemAction::Action(action) => {
486 let action = action.boxed_clone();
487 cx.app_context()
488 .spawn(|mut cx| async move {
489 cx.dispatch_action(window, view_id, action.as_ref())
490 })
491 .detach_and_log_err(cx);
492 }
493 ContextMenuItemAction::Handler(handler) => handler(cx),
494 }
495 })
496 .on_drag(MouseButton::Left, |_, _, _| {})
497 .into_any()
498 }
499
500 ContextMenuItem::Static(f) => f(cx),
501
502 ContextMenuItem::Separator => Empty::new()
503 .constrained()
504 .with_height(1.)
505 .contained()
506 .with_style(style.separator)
507 .into_any(),
508 }
509 }))
510 .contained()
511 .with_style(style.container)
512 })
513 .on_down_out(MouseButton::Left, |_, this, cx| {
514 this.cancel(&Default::default(), cx);
515 })
516 .on_down_out(MouseButton::Right, |_, this, cx| {
517 this.cancel(&Default::default(), cx);
518 })
519 }
520}