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