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