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 settings::Settings;
 12use std::{any::TypeId, borrow::Cow, sync::Arc, time::Duration};
 13
 14pub fn init(cx: &mut AppContext) {
 15    cx.add_action(ContextMenu::select_first);
 16    cx.add_action(ContextMenu::select_last);
 17    cx.add_action(ContextMenu::select_next);
 18    cx.add_action(ContextMenu::select_prev);
 19    cx.add_action(ContextMenu::confirm);
 20    cx.add_action(ContextMenu::cancel);
 21}
 22
 23pub type StaticItem = Box<dyn Fn(&mut AppContext) -> AnyElement<ContextMenu>>;
 24
 25type ContextMenuItemBuilder =
 26    Box<dyn Fn(&mut MouseState, &theme::ContextMenuItem) -> AnyElement<ContextMenu>>;
 27
 28pub enum ContextMenuItemLabel {
 29    String(Cow<'static, str>),
 30    Element(ContextMenuItemBuilder),
 31}
 32
 33impl From<Cow<'static, str>> for ContextMenuItemLabel {
 34    fn from(s: Cow<'static, str>) -> Self {
 35        Self::String(s)
 36    }
 37}
 38
 39impl From<&'static str> for ContextMenuItemLabel {
 40    fn from(s: &'static str) -> Self {
 41        Self::String(s.into())
 42    }
 43}
 44
 45impl From<String> for ContextMenuItemLabel {
 46    fn from(s: String) -> Self {
 47        Self::String(s.into())
 48    }
 49}
 50
 51impl<T> From<T> for ContextMenuItemLabel
 52where
 53    T: 'static + Fn(&mut MouseState, &theme::ContextMenuItem) -> AnyElement<ContextMenu>,
 54{
 55    fn from(f: T) -> Self {
 56        Self::Element(Box::new(f))
 57    }
 58}
 59
 60pub enum ContextMenuItemAction {
 61    Action(Box<dyn Action>),
 62    Handler(Arc<dyn Fn(&mut ViewContext<ContextMenu>)>),
 63}
 64
 65impl Clone for ContextMenuItemAction {
 66    fn clone(&self) -> Self {
 67        match self {
 68            Self::Action(action) => Self::Action(action.boxed_clone()),
 69            Self::Handler(handler) => Self::Handler(handler.clone()),
 70        }
 71    }
 72}
 73
 74pub enum ContextMenuItem {
 75    Item {
 76        label: ContextMenuItemLabel,
 77        action: ContextMenuItemAction,
 78    },
 79    Static(StaticItem),
 80    Separator,
 81}
 82
 83impl ContextMenuItem {
 84    pub fn action(label: impl Into<ContextMenuItemLabel>, action: impl 'static + Action) -> Self {
 85        Self::Item {
 86            label: label.into(),
 87            action: ContextMenuItemAction::Action(Box::new(action)),
 88        }
 89    }
 90
 91    pub fn handler(
 92        label: impl Into<ContextMenuItemLabel>,
 93        handler: impl 'static + Fn(&mut ViewContext<ContextMenu>),
 94    ) -> Self {
 95        Self::Item {
 96            label: label.into(),
 97            action: ContextMenuItemAction::Handler(Arc::new(handler)),
 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, .. } => match action {
112                ContextMenuItemAction::Action(action) => Some(action.id()),
113                ContextMenuItemAction::Handler(_) => None,
114            },
115            ContextMenuItem::Static(..) | ContextMenuItem::Separator => None,
116        }
117    }
118}
119
120pub struct ContextMenu {
121    show_count: usize,
122    anchor_position: Vector2F,
123    anchor_corner: AnchorCorner,
124    position_mode: OverlayPositionMode,
125    items: Vec<ContextMenuItem>,
126    selected_index: Option<usize>,
127    visible: bool,
128    previously_focused_view_id: Option<usize>,
129    clicked: bool,
130    parent_view_id: usize,
131    _actions_observation: Subscription,
132}
133
134impl Entity for ContextMenu {
135    type Event = ();
136}
137
138impl View for ContextMenu {
139    fn ui_name() -> &'static str {
140        "ContextMenu"
141    }
142
143    fn update_keymap_context(&self, keymap: &mut KeymapContext, _: &AppContext) {
144        Self::reset_to_default_keymap_context(keymap);
145        keymap.add_identifier("menu");
146    }
147
148    fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
149        if !self.visible {
150            return Empty::new().into_any();
151        }
152
153        // Render the menu once at minimum width.
154        let mut collapsed_menu = self.render_menu_for_measurement(cx);
155        let expanded_menu =
156            self.render_menu(cx)
157                .constrained()
158                .dynamically(move |constraint, view, cx| {
159                    SizeConstraint::strict_along(
160                        Axis::Horizontal,
161                        collapsed_menu.layout(constraint, view, cx).0.x(),
162                    )
163                });
164
165        Overlay::new(expanded_menu)
166            .with_hoverable(true)
167            .with_fit_mode(OverlayFitMode::SnapToWindow)
168            .with_anchor_position(self.anchor_position)
169            .with_anchor_corner(self.anchor_corner)
170            .with_position_mode(self.position_mode)
171            .into_any()
172    }
173
174    fn focus_out(&mut self, _: AnyViewHandle, cx: &mut ViewContext<Self>) {
175        self.reset(cx);
176    }
177}
178
179impl ContextMenu {
180    pub fn new(parent_view_id: usize, cx: &mut ViewContext<Self>) -> Self {
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 confirm(&mut self, _: &Confirm, cx: &mut ViewContext<Self>) {
222        if let Some(ix) = self.selected_index {
223            if let Some(ContextMenuItem::Item { action, .. }) = self.items.get(ix) {
224                match action {
225                    ContextMenuItemAction::Action(action) => {
226                        let window_id = cx.window_id();
227                        let view_id = self.parent_view_id;
228                        let action = action.boxed_clone();
229                        cx.app_context()
230                            .spawn(|mut cx| async move {
231                                cx.dispatch_action(window_id, view_id, action.as_ref())
232                            })
233                            .detach_and_log_err(cx);
234                    }
235                    ContextMenuItemAction::Handler(handler) => handler(cx),
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
379                                match action {
380                                    ContextMenuItemAction::Action(action) => KeystrokeLabel::new(
381                                        self.parent_view_id,
382                                        action.boxed_clone(),
383                                        style.keystroke.container,
384                                        style.keystroke.text.clone(),
385                                    )
386                                    .into_any(),
387                                    ContextMenuItemAction::Handler(_) => Empty::new().into_any(),
388                                }
389                            }
390
391                            ContextMenuItem::Static(_) => Empty::new().into_any(),
392
393                            ContextMenuItem::Separator => Empty::new()
394                                .collapsed()
395                                .constrained()
396                                .with_height(1.)
397                                .contained()
398                                .with_style(style.separator)
399                                .into_any(),
400                        }
401                    }))
402                    .contained()
403                    .with_margin_left(style.keystroke_margin),
404            )
405            .contained()
406            .with_style(style.container)
407    }
408
409    fn render_menu(&self, cx: &mut ViewContext<Self>) -> impl Element<ContextMenu> {
410        enum Menu {}
411        enum MenuItem {}
412
413        let style = cx.global::<Settings>().theme.context_menu.clone();
414
415        MouseEventHandler::<Menu, ContextMenu>::new(0, cx, |_, cx| {
416            Flex::column()
417                .with_children(self.items.iter().enumerate().map(|(ix, item)| {
418                    match item {
419                        ContextMenuItem::Item { label, action } => {
420                            let action = action.clone();
421                            let view_id = self.parent_view_id;
422                            MouseEventHandler::<MenuItem, ContextMenu>::new(ix, cx, |state, _| {
423                                let style =
424                                    style.item.style_for(state, Some(ix) == self.selected_index);
425                                let keystroke = match &action {
426                                    ContextMenuItemAction::Action(action) => Some(
427                                        KeystrokeLabel::new(
428                                            view_id,
429                                            action.boxed_clone(),
430                                            style.keystroke.container,
431                                            style.keystroke.text.clone(),
432                                        )
433                                        .flex_float(),
434                                    ),
435                                    ContextMenuItemAction::Handler(_) => None,
436                                };
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_children(keystroke)
450                                    .contained()
451                                    .with_style(style.container)
452                            })
453                            .with_cursor_style(CursorStyle::PointingHand)
454                            .on_up(MouseButton::Left, |_, _, _| {}) // Capture these events
455                            .on_down(MouseButton::Left, |_, _, _| {}) // Capture these events
456                            .on_click(MouseButton::Left, move |_, menu, cx| {
457                                menu.clicked = true;
458                                let window_id = cx.window_id();
459                                match &action {
460                                    ContextMenuItemAction::Action(action) => {
461                                        let action = action.boxed_clone();
462                                        cx.app_context()
463                                            .spawn(|mut cx| async move {
464                                                cx.dispatch_action(
465                                                    window_id,
466                                                    view_id,
467                                                    action.as_ref(),
468                                                )
469                                            })
470                                            .detach_and_log_err(cx);
471                                    }
472                                    ContextMenuItemAction::Handler(handler) => handler(cx),
473                                }
474                            })
475                            .on_drag(MouseButton::Left, |_, _, _| {})
476                            .into_any()
477                        }
478
479                        ContextMenuItem::Static(f) => f(cx),
480
481                        ContextMenuItem::Separator => Empty::new()
482                            .constrained()
483                            .with_height(1.)
484                            .contained()
485                            .with_style(style.separator)
486                            .into_any(),
487                    }
488                }))
489                .contained()
490                .with_style(style.container)
491        })
492        .on_down_out(MouseButton::Left, |_, this, cx| {
493            this.cancel(&Default::default(), cx);
494        })
495        .on_down_out(MouseButton::Right, |_, this, cx| {
496            this.cancel(&Default::default(), cx);
497        })
498    }
499}