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