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