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