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(parent_view_id: usize, cx: &mut ViewContext<Self>) -> Self {
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 parent_view_id,
190 _actions_observation: cx.observe_actions(Self::action_dispatched),
191 }
192 }
193
194 pub fn visible(&self) -> bool {
195 self.visible
196 }
197
198 fn action_dispatched(&mut self, action_id: TypeId, cx: &mut ViewContext<Self>) {
199 if let Some(ix) = self
200 .items
201 .iter()
202 .position(|item| item.action_id() == Some(action_id))
203 {
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 anyhow::Ok(())
210 })
211 .detach_and_log_err(cx);
212 }
213 }
214
215 fn confirm(&mut self, _: &Confirm, cx: &mut ViewContext<Self>) {
216 if let Some(ix) = self.selected_index {
217 if let Some(ContextMenuItem::Item { action, .. }) = self.items.get(ix) {
218 match action {
219 ContextMenuItemAction::Action(action) => {
220 let window_id = cx.window_id();
221 let view_id = self.parent_view_id;
222 let action = action.boxed_clone();
223 cx.app_context()
224 .spawn(|mut cx| async move {
225 cx.dispatch_action(window_id, view_id, action.as_ref())
226 })
227 .detach_and_log_err(cx);
228 }
229 ContextMenuItemAction::Handler(handler) => handler(cx),
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 cx.notify();
252 }
253
254 fn select_first(&mut self, _: &SelectFirst, cx: &mut ViewContext<Self>) {
255 self.selected_index = self.items.iter().position(|item| item.is_action());
256 cx.notify();
257 }
258
259 fn select_last(&mut self, _: &SelectLast, cx: &mut ViewContext<Self>) {
260 for (ix, item) in self.items.iter().enumerate().rev() {
261 if item.is_action() {
262 self.selected_index = Some(ix);
263 cx.notify();
264 break;
265 }
266 }
267 }
268
269 fn select_next(&mut self, _: &SelectNext, cx: &mut ViewContext<Self>) {
270 if let Some(ix) = self.selected_index {
271 for (ix, item) in self.items.iter().enumerate().skip(ix + 1) {
272 if item.is_action() {
273 self.selected_index = Some(ix);
274 cx.notify();
275 break;
276 }
277 }
278 } else {
279 self.select_first(&Default::default(), cx);
280 }
281 }
282
283 fn select_prev(&mut self, _: &SelectPrev, cx: &mut ViewContext<Self>) {
284 if let Some(ix) = self.selected_index {
285 for (ix, item) in self.items.iter().enumerate().take(ix).rev() {
286 if item.is_action() {
287 self.selected_index = Some(ix);
288 cx.notify();
289 break;
290 }
291 }
292 } else {
293 self.select_last(&Default::default(), cx);
294 }
295 }
296
297 pub fn show(
298 &mut self,
299 anchor_position: Vector2F,
300 anchor_corner: AnchorCorner,
301 items: Vec<ContextMenuItem>,
302 cx: &mut ViewContext<Self>,
303 ) {
304 let mut items = items.into_iter().peekable();
305 if items.peek().is_some() {
306 self.items = items.collect();
307 self.anchor_position = anchor_position;
308 self.anchor_corner = anchor_corner;
309 self.visible = true;
310 self.show_count += 1;
311 if !cx.is_self_focused() {
312 self.previously_focused_view_id = cx.focused_view_id();
313 }
314 cx.focus_self();
315 } else {
316 self.visible = false;
317 }
318 cx.notify();
319 }
320
321 pub fn set_position_mode(&mut self, mode: OverlayPositionMode) {
322 self.position_mode = mode;
323 }
324
325 fn render_menu_for_measurement(&self, cx: &mut ViewContext<Self>) -> impl Element<ContextMenu> {
326 let style = cx.global::<Settings>().theme.context_menu.clone();
327 Flex::row()
328 .with_child(
329 Flex::column().with_children(self.items.iter().enumerate().map(|(ix, item)| {
330 match item {
331 ContextMenuItem::Item { label, .. } => {
332 let style = style.item.style_for(
333 &mut Default::default(),
334 Some(ix) == self.selected_index,
335 );
336
337 match label {
338 ContextMenuItemLabel::String(label) => {
339 Label::new(label.to_string(), style.label.clone())
340 .contained()
341 .with_style(style.container)
342 .into_any()
343 }
344 ContextMenuItemLabel::Element(element) => {
345 element(&mut Default::default(), style)
346 }
347 }
348 }
349
350 ContextMenuItem::Static(f) => f(cx),
351
352 ContextMenuItem::Separator => Empty::new()
353 .collapsed()
354 .contained()
355 .with_style(style.separator)
356 .constrained()
357 .with_height(1.)
358 .into_any(),
359 }
360 })),
361 )
362 .with_child(
363 Flex::column()
364 .with_children(self.items.iter().enumerate().map(|(ix, item)| {
365 match item {
366 ContextMenuItem::Item { action, .. } => {
367 let style = style.item.style_for(
368 &mut Default::default(),
369 Some(ix) == self.selected_index,
370 );
371
372 match action {
373 ContextMenuItemAction::Action(action) => KeystrokeLabel::new(
374 self.parent_view_id,
375 action.boxed_clone(),
376 style.keystroke.container,
377 style.keystroke.text.clone(),
378 )
379 .into_any(),
380 ContextMenuItemAction::Handler(_) => Empty::new().into_any(),
381 }
382 }
383
384 ContextMenuItem::Static(_) => Empty::new().into_any(),
385
386 ContextMenuItem::Separator => Empty::new()
387 .collapsed()
388 .constrained()
389 .with_height(1.)
390 .contained()
391 .with_style(style.separator)
392 .into_any(),
393 }
394 }))
395 .contained()
396 .with_margin_left(style.keystroke_margin),
397 )
398 .contained()
399 .with_style(style.container)
400 }
401
402 fn render_menu(&self, cx: &mut ViewContext<Self>) -> impl Element<ContextMenu> {
403 enum Menu {}
404 enum MenuItem {}
405
406 let style = cx.global::<Settings>().theme.context_menu.clone();
407
408 MouseEventHandler::<Menu, ContextMenu>::new(0, cx, |_, cx| {
409 Flex::column()
410 .with_children(self.items.iter().enumerate().map(|(ix, item)| {
411 match item {
412 ContextMenuItem::Item { label, action } => {
413 let action = action.clone();
414 let view_id = self.parent_view_id;
415 MouseEventHandler::<MenuItem, ContextMenu>::new(ix, cx, |state, _| {
416 let style =
417 style.item.style_for(state, Some(ix) == self.selected_index);
418 let keystroke = match &action {
419 ContextMenuItemAction::Action(action) => Some(
420 KeystrokeLabel::new(
421 view_id,
422 action.boxed_clone(),
423 style.keystroke.container,
424 style.keystroke.text.clone(),
425 )
426 .flex_float(),
427 ),
428 ContextMenuItemAction::Handler(_) => None,
429 };
430
431 Flex::row()
432 .with_child(match label {
433 ContextMenuItemLabel::String(label) => {
434 Label::new(label.clone(), style.label.clone())
435 .contained()
436 .into_any()
437 }
438 ContextMenuItemLabel::Element(element) => {
439 element(state, style)
440 }
441 })
442 .with_children(keystroke)
443 .contained()
444 .with_style(style.container)
445 })
446 .with_cursor_style(CursorStyle::PointingHand)
447 .on_up(MouseButton::Left, |_, _, _| {}) // Capture these events
448 .on_down(MouseButton::Left, |_, _, _| {}) // Capture these events
449 .on_click(MouseButton::Left, move |_, menu, cx| {
450 menu.cancel(&Default::default(), cx);
451 let window_id = cx.window_id();
452 match &action {
453 ContextMenuItemAction::Action(action) => {
454 let action = action.boxed_clone();
455 cx.app_context()
456 .spawn(|mut cx| async move {
457 cx.dispatch_action(
458 window_id,
459 view_id,
460 action.as_ref(),
461 )
462 })
463 .detach_and_log_err(cx);
464 }
465 ContextMenuItemAction::Handler(handler) => handler(cx),
466 }
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, |_, this, cx| {
486 this.cancel(&Default::default(), cx);
487 })
488 .on_down_out(MouseButton::Right, |_, this, cx| {
489 this.cancel(&Default::default(), cx);
490 })
491 }
492}