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) -> AnyElement<ContextMenu>>;
30
31type ContextMenuItemBuilder =
32 Box<dyn Fn(&mut MouseState, &theme::ContextMenuItem) -> AnyElement<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>) -> AnyElement<Self> {
146 if !self.visible {
147 return Empty::new().into_any();
148 }
149
150 // Render the menu once at minimum width.
151 let mut collapsed_menu = self.render_menu_for_measurement(cx);
152 let expanded_menu =
153 self.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).0.x(),
159 )
160 });
161
162 Overlay::new(expanded_menu)
163 .with_hoverable(true)
164 .with_fit_mode(OverlayFitMode::SnapToWindow)
165 .with_anchor_position(self.anchor_position)
166 .with_anchor_corner(self.anchor_corner)
167 .with_position_mode(self.position_mode)
168 .into_any()
169 }
170
171 fn focus_out(&mut self, _: AnyViewHandle, cx: &mut ViewContext<Self>) {
172 self.reset(cx);
173 }
174}
175
176impl ContextMenu {
177 pub fn new(cx: &mut ViewContext<Self>) -> Self {
178 let parent_view_id = cx.parent().unwrap();
179
180 Self {
181 show_count: 0,
182 anchor_position: Default::default(),
183 anchor_corner: AnchorCorner::TopLeft,
184 position_mode: OverlayPositionMode::Window,
185 items: Default::default(),
186 selected_index: Default::default(),
187 visible: Default::default(),
188 previously_focused_view_id: Default::default(),
189 clicked: false,
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 if self.clicked {
206 self.cancel(&Default::default(), cx);
207 } else {
208 self.selected_index = Some(ix);
209 cx.notify();
210 cx.spawn(|this, mut cx| async move {
211 cx.background().timer(Duration::from_millis(50)).await;
212 this.update(&mut cx, |this, cx| this.cancel(&Default::default(), cx))
213 })
214 .detach_and_log_err(cx);
215 }
216 }
217 }
218
219 fn clicked(&mut self, _: &Clicked, _: &mut ViewContext<Self>) {
220 self.clicked = true;
221 }
222
223 fn confirm(&mut self, _: &Confirm, cx: &mut ViewContext<Self>) {
224 if let Some(ix) = self.selected_index {
225 if let Some(ContextMenuItem::Item { action, .. }) = self.items.get(ix) {
226 match action {
227 ContextMenuAction::ParentAction { action } => {
228 cx.dispatch_any_action(action.boxed_clone())
229 }
230 ContextMenuAction::ViewAction { action, for_view } => {
231 let window_id = cx.window_id();
232 cx.dispatch_any_action_at(window_id, *for_view, action.boxed_clone())
233 }
234 };
235 self.reset(cx);
236 }
237 }
238 }
239
240 fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
241 self.reset(cx);
242 let show_count = self.show_count;
243 cx.defer(move |this, cx| {
244 if cx.handle().is_focused(cx) && this.show_count == show_count {
245 let window_id = cx.window_id();
246 (**cx).focus(window_id, this.previously_focused_view_id.take());
247 }
248 });
249 }
250
251 fn reset(&mut self, cx: &mut ViewContext<Self>) {
252 self.items.clear();
253 self.visible = false;
254 self.selected_index.take();
255 self.clicked = false;
256 cx.notify();
257 }
258
259 fn select_first(&mut self, _: &SelectFirst, cx: &mut ViewContext<Self>) {
260 self.selected_index = self.items.iter().position(|item| item.is_action());
261 cx.notify();
262 }
263
264 fn select_last(&mut self, _: &SelectLast, cx: &mut ViewContext<Self>) {
265 for (ix, item) in self.items.iter().enumerate().rev() {
266 if item.is_action() {
267 self.selected_index = Some(ix);
268 cx.notify();
269 break;
270 }
271 }
272 }
273
274 fn select_next(&mut self, _: &SelectNext, cx: &mut ViewContext<Self>) {
275 if let Some(ix) = self.selected_index {
276 for (ix, item) in self.items.iter().enumerate().skip(ix + 1) {
277 if item.is_action() {
278 self.selected_index = Some(ix);
279 cx.notify();
280 break;
281 }
282 }
283 } else {
284 self.select_first(&Default::default(), cx);
285 }
286 }
287
288 fn select_prev(&mut self, _: &SelectPrev, cx: &mut ViewContext<Self>) {
289 if let Some(ix) = self.selected_index {
290 for (ix, item) in self.items.iter().enumerate().take(ix).rev() {
291 if item.is_action() {
292 self.selected_index = Some(ix);
293 cx.notify();
294 break;
295 }
296 }
297 } else {
298 self.select_last(&Default::default(), cx);
299 }
300 }
301
302 pub fn show(
303 &mut self,
304 anchor_position: Vector2F,
305 anchor_corner: AnchorCorner,
306 items: Vec<ContextMenuItem>,
307 cx: &mut ViewContext<Self>,
308 ) {
309 let mut items = items.into_iter().peekable();
310 if items.peek().is_some() {
311 self.items = items.collect();
312 self.anchor_position = anchor_position;
313 self.anchor_corner = anchor_corner;
314 self.visible = true;
315 self.show_count += 1;
316 if !cx.is_self_focused() {
317 self.previously_focused_view_id = cx.focused_view_id();
318 }
319 cx.focus_self();
320 } else {
321 self.visible = false;
322 }
323 cx.notify();
324 }
325
326 pub fn set_position_mode(&mut self, mode: OverlayPositionMode) {
327 self.position_mode = mode;
328 }
329
330 fn render_menu_for_measurement(&self, cx: &mut ViewContext<Self>) -> impl Element<ContextMenu> {
331 let style = cx.global::<Settings>().theme.context_menu.clone();
332 Flex::row()
333 .with_child(
334 Flex::column().with_children(self.items.iter().enumerate().map(|(ix, item)| {
335 match item {
336 ContextMenuItem::Item { label, .. } => {
337 let style = style.item.style_for(
338 &mut Default::default(),
339 Some(ix) == self.selected_index,
340 );
341
342 match label {
343 ContextMenuItemLabel::String(label) => {
344 Label::new(label.to_string(), style.label.clone())
345 .contained()
346 .with_style(style.container)
347 .into_any()
348 }
349 ContextMenuItemLabel::Element(element) => {
350 element(&mut Default::default(), style)
351 }
352 }
353 }
354
355 ContextMenuItem::Static(f) => f(cx),
356
357 ContextMenuItem::Separator => Empty::new()
358 .collapsed()
359 .contained()
360 .with_style(style.separator)
361 .constrained()
362 .with_height(1.)
363 .into_any(),
364 }
365 })),
366 )
367 .with_child(
368 Flex::column()
369 .with_children(self.items.iter().enumerate().map(|(ix, item)| {
370 match item {
371 ContextMenuItem::Item { action, .. } => {
372 let style = style.item.style_for(
373 &mut Default::default(),
374 Some(ix) == self.selected_index,
375 );
376 let (action, view_id) = match action {
377 ContextMenuAction::ParentAction { action } => {
378 (action.boxed_clone(), self.parent_view_id)
379 }
380 ContextMenuAction::ViewAction { action, for_view } => {
381 (action.boxed_clone(), *for_view)
382 }
383 };
384
385 KeystrokeLabel::new(
386 view_id,
387 action.boxed_clone(),
388 style.keystroke.container,
389 style.keystroke.text.clone(),
390 )
391 .into_any()
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, view_id) = match action {
424 ContextMenuAction::ParentAction { action } => {
425 (action.boxed_clone(), self.parent_view_id)
426 }
427 ContextMenuAction::ViewAction { action, for_view } => {
428 (action.boxed_clone(), *for_view)
429 }
430 };
431
432 MouseEventHandler::<MenuItem, ContextMenu>::new(ix, cx, |state, _| {
433 let style =
434 style.item.style_for(state, Some(ix) == self.selected_index);
435
436 Flex::row()
437 .with_child(match label {
438 ContextMenuItemLabel::String(label) => {
439 Label::new(label.clone(), style.label.clone())
440 .contained()
441 .into_any()
442 }
443 ContextMenuItemLabel::Element(element) => {
444 element(state, style)
445 }
446 })
447 .with_child({
448 KeystrokeLabel::new(
449 view_id,
450 action.boxed_clone(),
451 style.keystroke.container,
452 style.keystroke.text.clone(),
453 )
454 .flex_float()
455 })
456 .contained()
457 .with_style(style.container)
458 })
459 .with_cursor_style(CursorStyle::PointingHand)
460 .on_up(MouseButton::Left, |_, _, _| {}) // Capture these events
461 .on_down(MouseButton::Left, |_, _, _| {}) // Capture these events
462 .on_click(MouseButton::Left, move |_, _, cx| {
463 cx.dispatch_action(Clicked);
464 let window_id = cx.window_id();
465 cx.dispatch_any_action_at(window_id, view_id, action.boxed_clone());
466 })
467 .on_drag(MouseButton::Left, |_, _, _| {})
468 .into_any()
469 }
470
471 ContextMenuItem::Static(f) => f(cx),
472
473 ContextMenuItem::Separator => Empty::new()
474 .constrained()
475 .with_height(1.)
476 .contained()
477 .with_style(style.separator)
478 .into_any(),
479 }
480 }))
481 .contained()
482 .with_style(style.container)
483 })
484 .on_down_out(MouseButton::Left, |_, _, cx| cx.dispatch_action(Cancel))
485 .on_down_out(MouseButton::Right, |_, _, cx| cx.dispatch_action(Cancel))
486 }
487}