context_menu.rs

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