context_menu.rs

  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    delay_cancel: 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            delay_cancel: false,
183            anchor_position: Default::default(),
184            anchor_corner: AnchorCorner::TopLeft,
185            position_mode: OverlayPositionMode::Window,
186            items: Default::default(),
187            selected_index: Default::default(),
188            visible: Default::default(),
189            previously_focused_view_id: Default::default(),
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            self.selected_index = Some(ix);
206            cx.notify();
207            cx.spawn(|this, mut cx| async move {
208                cx.background().timer(Duration::from_millis(50)).await;
209                this.update(&mut cx, |this, cx| this.cancel(&Default::default(), cx))?;
210                anyhow::Ok(())
211            })
212            .detach_and_log_err(cx);
213        }
214    }
215
216    fn confirm(&mut self, _: &Confirm, cx: &mut ViewContext<Self>) {
217        if let Some(ix) = self.selected_index {
218            if let Some(ContextMenuItem::Item { action, .. }) = self.items.get(ix) {
219                match action {
220                    ContextMenuItemAction::Action(action) => {
221                        let window_id = cx.window_id();
222                        let view_id = self.parent_view_id;
223                        let action = action.boxed_clone();
224                        cx.app_context()
225                            .spawn(|mut cx| async move {
226                                cx.dispatch_action(window_id, view_id, action.as_ref())
227                            })
228                            .detach_and_log_err(cx);
229                    }
230                    ContextMenuItemAction::Handler(handler) => handler(cx),
231                }
232                self.reset(cx);
233            }
234        }
235    }
236
237    pub fn delay_cancel(&mut self) {
238        self.delay_cancel = true;
239    }
240
241    fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
242        if !self.delay_cancel {
243            self.reset(cx);
244            let show_count = self.show_count;
245            cx.defer(move |this, cx| {
246                if cx.handle().is_focused(cx) && this.show_count == show_count {
247                    let window_id = cx.window_id();
248                    (**cx).focus(window_id, this.previously_focused_view_id.take());
249                }
250            });
251        } else {
252            self.delay_cancel = false;
253        }
254    }
255
256    fn reset(&mut self, cx: &mut ViewContext<Self>) {
257        self.items.clear();
258        self.visible = false;
259        self.selected_index.take();
260        cx.notify();
261    }
262
263    fn select_first(&mut self, _: &SelectFirst, cx: &mut ViewContext<Self>) {
264        self.selected_index = self.items.iter().position(|item| item.is_action());
265        cx.notify();
266    }
267
268    fn select_last(&mut self, _: &SelectLast, cx: &mut ViewContext<Self>) {
269        for (ix, item) in self.items.iter().enumerate().rev() {
270            if item.is_action() {
271                self.selected_index = Some(ix);
272                cx.notify();
273                break;
274            }
275        }
276    }
277
278    fn select_next(&mut self, _: &SelectNext, cx: &mut ViewContext<Self>) {
279        if let Some(ix) = self.selected_index {
280            for (ix, item) in self.items.iter().enumerate().skip(ix + 1) {
281                if item.is_action() {
282                    self.selected_index = Some(ix);
283                    cx.notify();
284                    break;
285                }
286            }
287        } else {
288            self.select_first(&Default::default(), cx);
289        }
290    }
291
292    fn select_prev(&mut self, _: &SelectPrev, cx: &mut ViewContext<Self>) {
293        if let Some(ix) = self.selected_index {
294            for (ix, item) in self.items.iter().enumerate().take(ix).rev() {
295                if item.is_action() {
296                    self.selected_index = Some(ix);
297                    cx.notify();
298                    break;
299                }
300            }
301        } else {
302            self.select_last(&Default::default(), cx);
303        }
304    }
305
306    pub fn toggle(
307        &mut self,
308        anchor_position: Vector2F,
309        anchor_corner: AnchorCorner,
310        items: Vec<ContextMenuItem>,
311        cx: &mut ViewContext<Self>,
312    ) {
313        if self.visible() {
314            self.cancel(&Cancel, cx);
315        } else {
316            let mut items = items.into_iter().peekable();
317            if items.peek().is_some() {
318                self.items = items.collect();
319                self.anchor_position = anchor_position;
320                self.anchor_corner = anchor_corner;
321                self.visible = true;
322                self.show_count += 1;
323                if !cx.is_self_focused() {
324                    self.previously_focused_view_id = cx.focused_view_id();
325                }
326                cx.focus_self();
327            } else {
328                self.visible = false;
329            }
330        }
331        cx.notify();
332    }
333
334    pub fn show(
335        &mut self,
336        anchor_position: Vector2F,
337        anchor_corner: AnchorCorner,
338        items: Vec<ContextMenuItem>,
339        cx: &mut ViewContext<Self>,
340    ) {
341        let mut items = items.into_iter().peekable();
342        if items.peek().is_some() {
343            self.items = items.collect();
344            self.anchor_position = anchor_position;
345            self.anchor_corner = anchor_corner;
346            self.visible = true;
347            self.show_count += 1;
348            if !cx.is_self_focused() {
349                self.previously_focused_view_id = cx.focused_view_id();
350            }
351            cx.focus_self();
352        } else {
353            self.visible = false;
354        }
355        cx.notify();
356    }
357
358    pub fn set_position_mode(&mut self, mode: OverlayPositionMode) {
359        self.position_mode = mode;
360    }
361
362    fn render_menu_for_measurement(&self, cx: &mut ViewContext<Self>) -> impl Element<ContextMenu> {
363        let style = theme::current(cx).context_menu.clone();
364        Flex::row()
365            .with_child(
366                Flex::column().with_children(self.items.iter().enumerate().map(|(ix, item)| {
367                    match item {
368                        ContextMenuItem::Item { label, .. } => {
369                            let style = style.item.in_state(self.selected_index == Some(ix));
370                            let style = style.style_for(&mut Default::default());
371
372                            match label {
373                                ContextMenuItemLabel::String(label) => {
374                                    Label::new(label.to_string(), style.label.clone())
375                                        .contained()
376                                        .with_style(style.container)
377                                        .into_any()
378                                }
379                                ContextMenuItemLabel::Element(element) => {
380                                    element(&mut Default::default(), style)
381                                }
382                            }
383                        }
384
385                        ContextMenuItem::Static(f) => f(cx),
386
387                        ContextMenuItem::Separator => Empty::new()
388                            .collapsed()
389                            .contained()
390                            .with_style(style.separator)
391                            .constrained()
392                            .with_height(1.)
393                            .into_any(),
394                    }
395                })),
396            )
397            .with_child(
398                Flex::column()
399                    .with_children(self.items.iter().enumerate().map(|(ix, item)| {
400                        match item {
401                            ContextMenuItem::Item { action, .. } => {
402                                let style = style.item.in_state(self.selected_index == Some(ix));
403                                let style = style.style_for(&mut Default::default());
404
405                                match action {
406                                    ContextMenuItemAction::Action(action) => KeystrokeLabel::new(
407                                        self.parent_view_id,
408                                        action.boxed_clone(),
409                                        style.keystroke.container,
410                                        style.keystroke.text.clone(),
411                                    )
412                                    .into_any(),
413                                    ContextMenuItemAction::Handler(_) => Empty::new().into_any(),
414                                }
415                            }
416
417                            ContextMenuItem::Static(_) => Empty::new().into_any(),
418
419                            ContextMenuItem::Separator => Empty::new()
420                                .collapsed()
421                                .constrained()
422                                .with_height(1.)
423                                .contained()
424                                .with_style(style.separator)
425                                .into_any(),
426                        }
427                    }))
428                    .contained()
429                    .with_margin_left(style.keystroke_margin),
430            )
431            .contained()
432            .with_style(style.container)
433    }
434
435    fn render_menu(&self, cx: &mut ViewContext<Self>) -> impl Element<ContextMenu> {
436        enum Menu {}
437        enum MenuItem {}
438
439        let style = theme::current(cx).context_menu.clone();
440
441        MouseEventHandler::<Menu, ContextMenu>::new(0, cx, |_, cx| {
442            Flex::column()
443                .with_children(self.items.iter().enumerate().map(|(ix, item)| {
444                    match item {
445                        ContextMenuItem::Item { label, action } => {
446                            let action = action.clone();
447                            let view_id = self.parent_view_id;
448                            MouseEventHandler::<MenuItem, ContextMenu>::new(ix, cx, |state, _| {
449                                let style = style.item.in_state(self.selected_index == Some(ix));
450                                let style = style.style_for(state);
451                                let keystroke = match &action {
452                                    ContextMenuItemAction::Action(action) => Some(
453                                        KeystrokeLabel::new(
454                                            view_id,
455                                            action.boxed_clone(),
456                                            style.keystroke.container,
457                                            style.keystroke.text.clone(),
458                                        )
459                                        .flex_float(),
460                                    ),
461                                    ContextMenuItemAction::Handler(_) => None,
462                                };
463
464                                Flex::row()
465                                    .with_child(match label {
466                                        ContextMenuItemLabel::String(label) => {
467                                            Label::new(label.clone(), style.label.clone())
468                                                .contained()
469                                                .into_any()
470                                        }
471                                        ContextMenuItemLabel::Element(element) => {
472                                            element(state, style)
473                                        }
474                                    })
475                                    .with_children(keystroke)
476                                    .contained()
477                                    .with_style(style.container)
478                            })
479                            .with_cursor_style(CursorStyle::PointingHand)
480                            .on_up(MouseButton::Left, |_, _, _| {}) // Capture these events
481                            .on_down(MouseButton::Left, |_, _, _| {}) // Capture these events
482                            .on_click(MouseButton::Left, move |_, menu, cx| {
483                                menu.cancel(&Default::default(), cx);
484                                let window_id = cx.window_id();
485                                match &action {
486                                    ContextMenuItemAction::Action(action) => {
487                                        let action = action.boxed_clone();
488                                        cx.app_context()
489                                            .spawn(|mut cx| async move {
490                                                cx.dispatch_action(
491                                                    window_id,
492                                                    view_id,
493                                                    action.as_ref(),
494                                                )
495                                            })
496                                            .detach_and_log_err(cx);
497                                    }
498                                    ContextMenuItemAction::Handler(handler) => handler(cx),
499                                }
500                            })
501                            .on_drag(MouseButton::Left, |_, _, _| {})
502                            .into_any()
503                        }
504
505                        ContextMenuItem::Static(f) => f(cx),
506
507                        ContextMenuItem::Separator => Empty::new()
508                            .constrained()
509                            .with_height(1.)
510                            .contained()
511                            .with_style(style.separator)
512                            .into_any(),
513                    }
514                }))
515                .contained()
516                .with_style(style.container)
517        })
518        .on_down_out(MouseButton::Left, |_, this, cx| {
519            this.cancel(&Default::default(), cx);
520        })
521        .on_down_out(MouseButton::Right, |_, this, cx| {
522            this.cancel(&Default::default(), cx);
523        })
524    }
525}