context_menu.rs

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