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, 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
40pub enum ContextMenuAction {
41 ParentAction {
42 action: Box<dyn Action>,
43 },
44 ViewAction {
45 action: Box<dyn Action>,
46 for_view: usize,
47 },
48}
49
50impl ContextMenuAction {
51 fn id(&self) -> TypeId {
52 match self {
53 ContextMenuAction::ParentAction { action } => action.id(),
54 ContextMenuAction::ViewAction { action, .. } => action.id(),
55 }
56 }
57}
58
59pub enum ContextMenuItem {
60 Item {
61 label: ContextMenuItemLabel,
62 action: ContextMenuAction,
63 },
64 Static(StaticItem),
65 Separator,
66}
67
68impl ContextMenuItem {
69 pub fn element_item(label: ContextMenuItemBuilder, action: impl 'static + Action) -> Self {
70 Self::Item {
71 label: ContextMenuItemLabel::Element(label),
72 action: ContextMenuAction::ParentAction {
73 action: Box::new(action),
74 },
75 }
76 }
77
78 pub fn item(label: impl Into<Cow<'static, str>>, action: impl 'static + Action) -> Self {
79 Self::Item {
80 label: ContextMenuItemLabel::String(label.into()),
81 action: ContextMenuAction::ParentAction {
82 action: Box::new(action),
83 },
84 }
85 }
86
87 pub fn item_for_view(
88 label: impl Into<Cow<'static, str>>,
89 view_id: usize,
90 action: impl 'static + Action,
91 ) -> Self {
92 Self::Item {
93 label: ContextMenuItemLabel::String(label.into()),
94 action: ContextMenuAction::ViewAction {
95 action: Box::new(action),
96 for_view: view_id,
97 },
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, .. } => Some(action.id()),
112 ContextMenuItem::Static(..) | ContextMenuItem::Separator => None,
113 }
114 }
115}
116
117pub struct ContextMenu {
118 show_count: usize,
119 anchor_position: Vector2F,
120 anchor_corner: AnchorCorner,
121 position_mode: OverlayPositionMode,
122 items: Vec<ContextMenuItem>,
123 selected_index: Option<usize>,
124 visible: bool,
125 previously_focused_view_id: Option<usize>,
126 clicked: bool,
127 parent_view_id: usize,
128 _actions_observation: Subscription,
129}
130
131impl Entity for ContextMenu {
132 type Event = ();
133}
134
135impl View for ContextMenu {
136 fn ui_name() -> &'static str {
137 "ContextMenu"
138 }
139
140 fn update_keymap_context(&self, keymap: &mut KeymapContext, _: &AppContext) {
141 Self::reset_to_default_keymap_context(keymap);
142 keymap.add_identifier("menu");
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 anyhow::Ok(())
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(&self, cx: &mut ViewContext<Self>) -> impl Element<ContextMenu> {
332 let style = cx.global::<Settings>().theme.context_menu.clone();
333 Flex::row()
334 .with_child(
335 Flex::column().with_children(self.items.iter().enumerate().map(|(ix, item)| {
336 match item {
337 ContextMenuItem::Item { label, .. } => {
338 let style = style.item.style_for(
339 &mut Default::default(),
340 Some(ix) == self.selected_index,
341 );
342
343 match label {
344 ContextMenuItemLabel::String(label) => {
345 Label::new(label.to_string(), style.label.clone())
346 .contained()
347 .with_style(style.container)
348 .into_any()
349 }
350 ContextMenuItemLabel::Element(element) => {
351 element(&mut Default::default(), style)
352 }
353 }
354 }
355
356 ContextMenuItem::Static(f) => f(cx),
357
358 ContextMenuItem::Separator => Empty::new()
359 .collapsed()
360 .contained()
361 .with_style(style.separator)
362 .constrained()
363 .with_height(1.)
364 .into_any(),
365 }
366 })),
367 )
368 .with_child(
369 Flex::column()
370 .with_children(self.items.iter().enumerate().map(|(ix, item)| {
371 match item {
372 ContextMenuItem::Item { action, .. } => {
373 let style = style.item.style_for(
374 &mut Default::default(),
375 Some(ix) == self.selected_index,
376 );
377 let (action, view_id) = match action {
378 ContextMenuAction::ParentAction { action } => {
379 (action.boxed_clone(), self.parent_view_id)
380 }
381 ContextMenuAction::ViewAction { action, for_view } => {
382 (action.boxed_clone(), *for_view)
383 }
384 };
385
386 KeystrokeLabel::new(
387 view_id,
388 action.boxed_clone(),
389 style.keystroke.container,
390 style.keystroke.text.clone(),
391 )
392 .into_any()
393 }
394
395 ContextMenuItem::Static(_) => Empty::new().into_any(),
396
397 ContextMenuItem::Separator => Empty::new()
398 .collapsed()
399 .constrained()
400 .with_height(1.)
401 .contained()
402 .with_style(style.separator)
403 .into_any(),
404 }
405 }))
406 .contained()
407 .with_margin_left(style.keystroke_margin),
408 )
409 .contained()
410 .with_style(style.container)
411 }
412
413 fn render_menu(&self, cx: &mut ViewContext<Self>) -> impl Element<ContextMenu> {
414 enum Menu {}
415 enum MenuItem {}
416
417 let style = cx.global::<Settings>().theme.context_menu.clone();
418
419 MouseEventHandler::<Menu, ContextMenu>::new(0, cx, |_, cx| {
420 Flex::column()
421 .with_children(self.items.iter().enumerate().map(|(ix, item)| {
422 match item {
423 ContextMenuItem::Item { label, action } => {
424 let (action, view_id) = match action {
425 ContextMenuAction::ParentAction { action } => {
426 (action.boxed_clone(), self.parent_view_id)
427 }
428 ContextMenuAction::ViewAction { action, for_view } => {
429 (action.boxed_clone(), *for_view)
430 }
431 };
432
433 MouseEventHandler::<MenuItem, ContextMenu>::new(ix, cx, |state, _| {
434 let style =
435 style.item.style_for(state, Some(ix) == self.selected_index);
436
437 Flex::row()
438 .with_child(match label {
439 ContextMenuItemLabel::String(label) => {
440 Label::new(label.clone(), style.label.clone())
441 .contained()
442 .into_any()
443 }
444 ContextMenuItemLabel::Element(element) => {
445 element(state, style)
446 }
447 })
448 .with_child({
449 KeystrokeLabel::new(
450 view_id,
451 action.boxed_clone(),
452 style.keystroke.container,
453 style.keystroke.text.clone(),
454 )
455 .flex_float()
456 })
457 .contained()
458 .with_style(style.container)
459 })
460 .with_cursor_style(CursorStyle::PointingHand)
461 .on_up(MouseButton::Left, |_, _, _| {}) // Capture these events
462 .on_down(MouseButton::Left, |_, _, _| {}) // Capture these events
463 .on_click(MouseButton::Left, move |_, _, cx| {
464 cx.dispatch_action(Clicked);
465 let window_id = cx.window_id();
466 cx.dispatch_any_action_at(window_id, view_id, action.boxed_clone());
467 })
468 .on_drag(MouseButton::Left, |_, _, _| {})
469 .into_any()
470 }
471
472 ContextMenuItem::Static(f) => f(cx),
473
474 ContextMenuItem::Separator => Empty::new()
475 .constrained()
476 .with_height(1.)
477 .contained()
478 .with_style(style.separator)
479 .into_any(),
480 }
481 }))
482 .contained()
483 .with_style(style.container)
484 })
485 .on_down_out(MouseButton::Left, |_, _, cx| cx.dispatch_action(Cancel))
486 .on_down_out(MouseButton::Right, |_, _, cx| cx.dispatch_action(Cancel))
487 }
488}