context_menu.rs

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