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) -> Element<ContextMenu>>;
 30
 31type ContextMenuItemBuilder =
 32    Box<dyn Fn(&mut MouseState, &theme::ContextMenuItem) -> Element<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>) -> Element<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(
332        &self,
333        cx: &mut ViewContext<Self>,
334    ) -> impl Drawable<ContextMenu> {
335        let window_id = cx.window_id();
336        let style = cx.global::<Settings>().theme.context_menu.clone();
337        Flex::row()
338            .with_child(
339                Flex::column()
340                    .with_children(self.items.iter().enumerate().map(|(ix, item)| {
341                        match item {
342                            ContextMenuItem::Item { label, .. } => {
343                                let style = style.item.style_for(
344                                    &mut Default::default(),
345                                    Some(ix) == self.selected_index,
346                                );
347
348                                match label {
349                                    ContextMenuItemLabel::String(label) => {
350                                        Label::new(label.to_string(), style.label.clone())
351                                            .contained()
352                                            .with_style(style.container)
353                                            .boxed()
354                                    }
355                                    ContextMenuItemLabel::Element(element) => {
356                                        element(&mut Default::default(), style)
357                                    }
358                                }
359                            }
360
361                            ContextMenuItem::Static(f) => f(cx),
362
363                            ContextMenuItem::Separator => Empty::new()
364                                .collapsed()
365                                .contained()
366                                .with_style(style.separator)
367                                .constrained()
368                                .with_height(1.)
369                                .boxed(),
370                        }
371                    }))
372                    .boxed(),
373            )
374            .with_child(
375                Flex::column()
376                    .with_children(self.items.iter().enumerate().map(|(ix, item)| {
377                        match item {
378                            ContextMenuItem::Item { action, .. } => {
379                                let style = style.item.style_for(
380                                    &mut Default::default(),
381                                    Some(ix) == self.selected_index,
382                                );
383                                let (action, view_id) = match action {
384                                    ContextMenuAction::ParentAction { action } => {
385                                        (action.boxed_clone(), self.parent_view_id)
386                                    }
387                                    ContextMenuAction::ViewAction { action, for_view } => {
388                                        (action.boxed_clone(), *for_view)
389                                    }
390                                };
391
392                                KeystrokeLabel::new(
393                                    window_id,
394                                    view_id,
395                                    action.boxed_clone(),
396                                    style.keystroke.container,
397                                    style.keystroke.text.clone(),
398                                )
399                                .boxed()
400                            }
401
402                            ContextMenuItem::Static(_) => Empty::new().boxed(),
403
404                            ContextMenuItem::Separator => Empty::new()
405                                .collapsed()
406                                .constrained()
407                                .with_height(1.)
408                                .contained()
409                                .with_style(style.separator)
410                                .boxed(),
411                        }
412                    }))
413                    .contained()
414                    .with_margin_left(style.keystroke_margin)
415                    .boxed(),
416            )
417            .contained()
418            .with_style(style.container)
419    }
420
421    fn render_menu(&self, cx: &mut ViewContext<Self>) -> impl Drawable<ContextMenu> {
422        enum Menu {}
423        enum MenuItem {}
424
425        let style = cx.global::<Settings>().theme.context_menu.clone();
426
427        let window_id = cx.window_id();
428        MouseEventHandler::<Menu, ContextMenu>::new(0, cx, |_, cx| {
429            Flex::column()
430                .with_children(self.items.iter().enumerate().map(|(ix, item)| {
431                    match item {
432                        ContextMenuItem::Item { label, action } => {
433                            let (action, view_id) = match action {
434                                ContextMenuAction::ParentAction { action } => {
435                                    (action.boxed_clone(), self.parent_view_id)
436                                }
437                                ContextMenuAction::ViewAction { action, for_view } => {
438                                    (action.boxed_clone(), *for_view)
439                                }
440                            };
441
442                            MouseEventHandler::<MenuItem, ContextMenu>::new(ix, cx, |state, _| {
443                                let style =
444                                    style.item.style_for(state, Some(ix) == self.selected_index);
445
446                                Flex::row()
447                                    .with_child(match label {
448                                        ContextMenuItemLabel::String(label) => {
449                                            Label::new(label.clone(), style.label.clone())
450                                                .contained()
451                                                .boxed()
452                                        }
453                                        ContextMenuItemLabel::Element(element) => {
454                                            element(state, style)
455                                        }
456                                    })
457                                    .with_child({
458                                        KeystrokeLabel::new(
459                                            window_id,
460                                            view_id,
461                                            action.boxed_clone(),
462                                            style.keystroke.container,
463                                            style.keystroke.text.clone(),
464                                        )
465                                        .flex_float()
466                                        .boxed()
467                                    })
468                                    .contained()
469                                    .with_style(style.container)
470                                    .boxed()
471                            })
472                            .with_cursor_style(CursorStyle::PointingHand)
473                            .on_up(MouseButton::Left, |_, _, _| {}) // Capture these events
474                            .on_down(MouseButton::Left, |_, _, _| {}) // Capture these events
475                            .on_click(MouseButton::Left, move |_, _, cx| {
476                                cx.dispatch_action(Clicked);
477                                let window_id = cx.window_id();
478                                cx.dispatch_any_action_at(window_id, view_id, action.boxed_clone());
479                            })
480                            .on_drag(MouseButton::Left, |_, _, _| {})
481                            .boxed()
482                        }
483
484                        ContextMenuItem::Static(f) => f(cx),
485
486                        ContextMenuItem::Separator => Empty::new()
487                            .constrained()
488                            .with_height(1.)
489                            .contained()
490                            .with_style(style.separator)
491                            .boxed(),
492                    }
493                }))
494                .contained()
495                .with_style(style.container)
496                .boxed()
497        })
498        .on_down_out(MouseButton::Left, |_, _, cx| cx.dispatch_action(Cancel))
499        .on_down_out(MouseButton::Right, |_, _, cx| cx.dispatch_action(Cancel))
500    }
501}