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 keymap_context(&self, _: &AppContext) -> KeymapContext {
144        let mut cx = Self::default_keymap_context();
145        cx.add_identifier("menu");
146        cx
147    }
148
149    fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
150        if !self.visible {
151            return Empty::new().into_any();
152        }
153
154        // Render the menu once at minimum width.
155        let mut collapsed_menu = self.render_menu_for_measurement(cx);
156        let expanded_menu =
157            self.render_menu(cx)
158                .constrained()
159                .dynamically(move |constraint, view, cx| {
160                    SizeConstraint::strict_along(
161                        Axis::Horizontal,
162                        collapsed_menu.layout(constraint, view, cx).0.x(),
163                    )
164                });
165
166        Overlay::new(expanded_menu)
167            .with_hoverable(true)
168            .with_fit_mode(OverlayFitMode::SnapToWindow)
169            .with_anchor_position(self.anchor_position)
170            .with_anchor_corner(self.anchor_corner)
171            .with_position_mode(self.position_mode)
172            .into_any()
173    }
174
175    fn focus_out(&mut self, _: AnyViewHandle, cx: &mut ViewContext<Self>) {
176        self.reset(cx);
177    }
178}
179
180impl ContextMenu {
181    pub fn new(cx: &mut ViewContext<Self>) -> Self {
182        let parent_view_id = cx.parent().unwrap();
183
184        Self {
185            show_count: 0,
186            anchor_position: Default::default(),
187            anchor_corner: AnchorCorner::TopLeft,
188            position_mode: OverlayPositionMode::Window,
189            items: Default::default(),
190            selected_index: Default::default(),
191            visible: Default::default(),
192            previously_focused_view_id: Default::default(),
193            clicked: false,
194            parent_view_id,
195            _actions_observation: cx.observe_actions(Self::action_dispatched),
196        }
197    }
198
199    pub fn visible(&self) -> bool {
200        self.visible
201    }
202
203    fn action_dispatched(&mut self, action_id: TypeId, cx: &mut ViewContext<Self>) {
204        if let Some(ix) = self
205            .items
206            .iter()
207            .position(|item| item.action_id() == Some(action_id))
208        {
209            if self.clicked {
210                self.cancel(&Default::default(), cx);
211            } else {
212                self.selected_index = Some(ix);
213                cx.notify();
214                cx.spawn(|this, mut cx| async move {
215                    cx.background().timer(Duration::from_millis(50)).await;
216                    this.update(&mut cx, |this, cx| this.cancel(&Default::default(), cx))?;
217                    anyhow::Ok(())
218                })
219                .detach_and_log_err(cx);
220            }
221        }
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                    ContextMenuItemAction::Action(action) => {
229                        let window_id = cx.window_id();
230                        cx.dispatch_any_action_at(
231                            window_id,
232                            self.parent_view_id,
233                            action.boxed_clone(),
234                        );
235                    }
236                    ContextMenuItemAction::Handler(handler) => handler(cx),
237                }
238                self.reset(cx);
239            }
240        }
241    }
242
243    fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
244        self.reset(cx);
245        let show_count = self.show_count;
246        cx.defer(move |this, cx| {
247            if cx.handle().is_focused(cx) && this.show_count == show_count {
248                let window_id = cx.window_id();
249                (**cx).focus(window_id, this.previously_focused_view_id.take());
250            }
251        });
252    }
253
254    fn reset(&mut self, cx: &mut ViewContext<Self>) {
255        self.items.clear();
256        self.visible = false;
257        self.selected_index.take();
258        self.clicked = false;
259        cx.notify();
260    }
261
262    fn select_first(&mut self, _: &SelectFirst, cx: &mut ViewContext<Self>) {
263        self.selected_index = self.items.iter().position(|item| item.is_action());
264        cx.notify();
265    }
266
267    fn select_last(&mut self, _: &SelectLast, cx: &mut ViewContext<Self>) {
268        for (ix, item) in self.items.iter().enumerate().rev() {
269            if item.is_action() {
270                self.selected_index = Some(ix);
271                cx.notify();
272                break;
273            }
274        }
275    }
276
277    fn select_next(&mut self, _: &SelectNext, cx: &mut ViewContext<Self>) {
278        if let Some(ix) = self.selected_index {
279            for (ix, item) in self.items.iter().enumerate().skip(ix + 1) {
280                if item.is_action() {
281                    self.selected_index = Some(ix);
282                    cx.notify();
283                    break;
284                }
285            }
286        } else {
287            self.select_first(&Default::default(), cx);
288        }
289    }
290
291    fn select_prev(&mut self, _: &SelectPrev, cx: &mut ViewContext<Self>) {
292        if let Some(ix) = self.selected_index {
293            for (ix, item) in self.items.iter().enumerate().take(ix).rev() {
294                if item.is_action() {
295                    self.selected_index = Some(ix);
296                    cx.notify();
297                    break;
298                }
299            }
300        } else {
301            self.select_last(&Default::default(), cx);
302        }
303    }
304
305    pub fn show(
306        &mut self,
307        anchor_position: Vector2F,
308        anchor_corner: AnchorCorner,
309        items: Vec<ContextMenuItem>,
310        cx: &mut ViewContext<Self>,
311    ) {
312        let mut items = items.into_iter().peekable();
313        if items.peek().is_some() {
314            self.items = items.collect();
315            self.anchor_position = anchor_position;
316            self.anchor_corner = anchor_corner;
317            self.visible = true;
318            self.show_count += 1;
319            if !cx.is_self_focused() {
320                self.previously_focused_view_id = cx.focused_view_id();
321            }
322            cx.focus_self();
323        } else {
324            self.visible = false;
325        }
326        cx.notify();
327    }
328
329    pub fn set_position_mode(&mut self, mode: OverlayPositionMode) {
330        self.position_mode = mode;
331    }
332
333    fn render_menu_for_measurement(&self, cx: &mut ViewContext<Self>) -> impl Element<ContextMenu> {
334        let style = cx.global::<Settings>().theme.context_menu.clone();
335        Flex::row()
336            .with_child(
337                Flex::column().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                                        .into_any()
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                            .into_any(),
367                    }
368                })),
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
380                                match action {
381                                    ContextMenuItemAction::Action(action) => KeystrokeLabel::new(
382                                        self.parent_view_id,
383                                        action.boxed_clone(),
384                                        style.keystroke.container,
385                                        style.keystroke.text.clone(),
386                                    )
387                                    .into_any(),
388                                    ContextMenuItemAction::Handler(_) => Empty::new().into_any(),
389                                }
390                            }
391
392                            ContextMenuItem::Static(_) => Empty::new().into_any(),
393
394                            ContextMenuItem::Separator => Empty::new()
395                                .collapsed()
396                                .constrained()
397                                .with_height(1.)
398                                .contained()
399                                .with_style(style.separator)
400                                .into_any(),
401                        }
402                    }))
403                    .contained()
404                    .with_margin_left(style.keystroke_margin),
405            )
406            .contained()
407            .with_style(style.container)
408    }
409
410    fn render_menu(&self, cx: &mut ViewContext<Self>) -> impl Element<ContextMenu> {
411        enum Menu {}
412        enum MenuItem {}
413
414        let style = cx.global::<Settings>().theme.context_menu.clone();
415
416        MouseEventHandler::<Menu, ContextMenu>::new(0, cx, |_, cx| {
417            Flex::column()
418                .with_children(self.items.iter().enumerate().map(|(ix, item)| {
419                    match item {
420                        ContextMenuItem::Item { label, action } => {
421                            let action = action.clone();
422                            let view_id = self.parent_view_id;
423                            MouseEventHandler::<MenuItem, ContextMenu>::new(ix, cx, |state, _| {
424                                let style =
425                                    style.item.style_for(state, Some(ix) == self.selected_index);
426                                let keystroke = match &action {
427                                    ContextMenuItemAction::Action(action) => Some(
428                                        KeystrokeLabel::new(
429                                            view_id,
430                                            action.boxed_clone(),
431                                            style.keystroke.container,
432                                            style.keystroke.text.clone(),
433                                        )
434                                        .flex_float(),
435                                    ),
436                                    ContextMenuItemAction::Handler(_) => None,
437                                };
438
439                                Flex::row()
440                                    .with_child(match label {
441                                        ContextMenuItemLabel::String(label) => {
442                                            Label::new(label.clone(), style.label.clone())
443                                                .contained()
444                                                .into_any()
445                                        }
446                                        ContextMenuItemLabel::Element(element) => {
447                                            element(state, style)
448                                        }
449                                    })
450                                    .with_children(keystroke)
451                                    .contained()
452                                    .with_style(style.container)
453                            })
454                            .with_cursor_style(CursorStyle::PointingHand)
455                            .on_up(MouseButton::Left, |_, _, _| {}) // Capture these events
456                            .on_down(MouseButton::Left, |_, _, _| {}) // Capture these events
457                            .on_click(MouseButton::Left, move |_, menu, cx| {
458                                menu.clicked = true;
459                                let window_id = cx.window_id();
460                                match &action {
461                                    ContextMenuItemAction::Action(action) => {
462                                        cx.dispatch_any_action_at(
463                                            window_id,
464                                            view_id,
465                                            action.boxed_clone(),
466                                        );
467                                    }
468                                    ContextMenuItemAction::Handler(handler) => handler(cx),
469                                }
470                            })
471                            .on_drag(MouseButton::Left, |_, _, _| {})
472                            .into_any()
473                        }
474
475                        ContextMenuItem::Static(f) => f(cx),
476
477                        ContextMenuItem::Separator => Empty::new()
478                            .constrained()
479                            .with_height(1.)
480                            .contained()
481                            .with_style(style.separator)
482                            .into_any(),
483                    }
484                }))
485                .contained()
486                .with_style(style.container)
487        })
488        .on_down_out(MouseButton::Left, |_, this, cx| {
489            this.cancel(&Default::default(), cx);
490        })
491        .on_down_out(MouseButton::Right, |_, this, cx| {
492            this.cancel(&Default::default(), cx);
493        })
494    }
495}