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