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