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 std::{any::TypeId, borrow::Cow, sync::Arc, time::Duration};
 12use theme::ToggleState;
 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    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            anchor_position: Default::default(),
183            anchor_corner: AnchorCorner::TopLeft,
184            position_mode: OverlayPositionMode::Window,
185            items: Default::default(),
186            selected_index: Default::default(),
187            visible: Default::default(),
188            previously_focused_view_id: Default::default(),
189            parent_view_id,
190            _actions_observation: cx.observe_actions(Self::action_dispatched),
191        }
192    }
193
194    pub fn visible(&self) -> bool {
195        self.visible
196    }
197
198    fn action_dispatched(&mut self, action_id: TypeId, cx: &mut ViewContext<Self>) {
199        if let Some(ix) = self
200            .items
201            .iter()
202            .position(|item| item.action_id() == Some(action_id))
203        {
204            self.selected_index = Some(ix);
205            cx.notify();
206            cx.spawn(|this, mut cx| async move {
207                cx.background().timer(Duration::from_millis(50)).await;
208                this.update(&mut cx, |this, cx| this.cancel(&Default::default(), cx))?;
209                anyhow::Ok(())
210            })
211            .detach_and_log_err(cx);
212        }
213    }
214
215    fn confirm(&mut self, _: &Confirm, cx: &mut ViewContext<Self>) {
216        if let Some(ix) = self.selected_index {
217            if let Some(ContextMenuItem::Item { action, .. }) = self.items.get(ix) {
218                match action {
219                    ContextMenuItemAction::Action(action) => {
220                        let window_id = cx.window_id();
221                        let view_id = self.parent_view_id;
222                        let action = action.boxed_clone();
223                        cx.app_context()
224                            .spawn(|mut cx| async move {
225                                cx.dispatch_action(window_id, view_id, action.as_ref())
226                            })
227                            .detach_and_log_err(cx);
228                    }
229                    ContextMenuItemAction::Handler(handler) => handler(cx),
230                }
231                self.reset(cx);
232            }
233        }
234    }
235
236    fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
237        self.reset(cx);
238        let show_count = self.show_count;
239        cx.defer(move |this, cx| {
240            if cx.handle().is_focused(cx) && this.show_count == show_count {
241                let window_id = cx.window_id();
242                (**cx).focus(window_id, this.previously_focused_view_id.take());
243            }
244        });
245    }
246
247    fn reset(&mut self, cx: &mut ViewContext<Self>) {
248        self.items.clear();
249        self.visible = false;
250        self.selected_index.take();
251        cx.notify();
252    }
253
254    fn select_first(&mut self, _: &SelectFirst, cx: &mut ViewContext<Self>) {
255        self.selected_index = self.items.iter().position(|item| item.is_action());
256        cx.notify();
257    }
258
259    fn select_last(&mut self, _: &SelectLast, cx: &mut ViewContext<Self>) {
260        for (ix, item) in self.items.iter().enumerate().rev() {
261            if item.is_action() {
262                self.selected_index = Some(ix);
263                cx.notify();
264                break;
265            }
266        }
267    }
268
269    fn select_next(&mut self, _: &SelectNext, cx: &mut ViewContext<Self>) {
270        if let Some(ix) = self.selected_index {
271            for (ix, item) in self.items.iter().enumerate().skip(ix + 1) {
272                if item.is_action() {
273                    self.selected_index = Some(ix);
274                    cx.notify();
275                    break;
276                }
277            }
278        } else {
279            self.select_first(&Default::default(), cx);
280        }
281    }
282
283    fn select_prev(&mut self, _: &SelectPrev, cx: &mut ViewContext<Self>) {
284        if let Some(ix) = self.selected_index {
285            for (ix, item) in self.items.iter().enumerate().take(ix).rev() {
286                if item.is_action() {
287                    self.selected_index = Some(ix);
288                    cx.notify();
289                    break;
290                }
291            }
292        } else {
293            self.select_last(&Default::default(), cx);
294        }
295    }
296
297    pub fn show(
298        &mut self,
299        anchor_position: Vector2F,
300        anchor_corner: AnchorCorner,
301        items: Vec<ContextMenuItem>,
302        cx: &mut ViewContext<Self>,
303    ) {
304        let mut items = items.into_iter().peekable();
305        if items.peek().is_some() {
306            self.items = items.collect();
307            self.anchor_position = anchor_position;
308            self.anchor_corner = anchor_corner;
309            self.visible = true;
310            self.show_count += 1;
311            if !cx.is_self_focused() {
312                self.previously_focused_view_id = cx.focused_view_id();
313            }
314            cx.focus_self();
315        } else {
316            self.visible = false;
317        }
318        cx.notify();
319    }
320
321    pub fn set_position_mode(&mut self, mode: OverlayPositionMode) {
322        self.position_mode = mode;
323    }
324
325    fn render_menu_for_measurement(&self, cx: &mut ViewContext<Self>) -> impl Element<ContextMenu> {
326        let style = theme::current(cx).context_menu.clone();
327        Flex::row()
328            .with_child(
329                Flex::column().with_children(self.items.iter().enumerate().map(|(ix, item)| {
330                    match item {
331                        ContextMenuItem::Item { label, .. } => {
332                            let toggle_state = if Some(ix) == self.selected_index {
333                                ToggleState::Active
334                            } else {
335                                ToggleState::Inactive
336                            };
337                            let style = style.item.in_state(toggle_state);
338                            let style = style.style_for(&mut Default::default());
339
340                            match label {
341                                ContextMenuItemLabel::String(label) => {
342                                    Label::new(label.to_string(), style.label.clone())
343                                        .contained()
344                                        .with_style(style.container)
345                                        .into_any()
346                                }
347                                ContextMenuItemLabel::Element(element) => {
348                                    element(&mut Default::default(), style)
349                                }
350                            }
351                        }
352
353                        ContextMenuItem::Static(f) => f(cx),
354
355                        ContextMenuItem::Separator => Empty::new()
356                            .collapsed()
357                            .contained()
358                            .with_style(style.separator)
359                            .constrained()
360                            .with_height(1.)
361                            .into_any(),
362                    }
363                })),
364            )
365            .with_child(
366                Flex::column()
367                    .with_children(self.items.iter().enumerate().map(|(ix, item)| {
368                        match item {
369                            ContextMenuItem::Item { action, .. } => {
370                                let toggle_state = if Some(ix) == self.selected_index {
371                                    ToggleState::Active
372                                } else {
373                                    ToggleState::Inactive
374                                };
375                                let style = style.item.in_state(toggle_state);
376                                let style = style.style_for(&mut Default::default());
377
378                                match action {
379                                    ContextMenuItemAction::Action(action) => KeystrokeLabel::new(
380                                        self.parent_view_id,
381                                        action.boxed_clone(),
382                                        style.keystroke.container,
383                                        style.keystroke.text.clone(),
384                                    )
385                                    .into_any(),
386                                    ContextMenuItemAction::Handler(_) => Empty::new().into_any(),
387                                }
388                            }
389
390                            ContextMenuItem::Static(_) => Empty::new().into_any(),
391
392                            ContextMenuItem::Separator => Empty::new()
393                                .collapsed()
394                                .constrained()
395                                .with_height(1.)
396                                .contained()
397                                .with_style(style.separator)
398                                .into_any(),
399                        }
400                    }))
401                    .contained()
402                    .with_margin_left(style.keystroke_margin),
403            )
404            .contained()
405            .with_style(style.container)
406    }
407
408    fn render_menu(&self, cx: &mut ViewContext<Self>) -> impl Element<ContextMenu> {
409        enum Menu {}
410        enum MenuItem {}
411
412        let style = theme::current(cx).context_menu.clone();
413
414        MouseEventHandler::<Menu, ContextMenu>::new(0, cx, |_, cx| {
415            Flex::column()
416                .with_children(self.items.iter().enumerate().map(|(ix, item)| {
417                    match item {
418                        ContextMenuItem::Item { label, action } => {
419                            let action = action.clone();
420                            let view_id = self.parent_view_id;
421                            MouseEventHandler::<MenuItem, ContextMenu>::new(ix, cx, |state, _| {
422                                let toggle_state = if Some(ix) == self.selected_index {
423                                    ToggleState::Active
424                                } else {
425                                    ToggleState::Inactive
426                                };
427                                let style = style.item.in_state(toggle_state);
428                                let style = style.style_for(state);
429                                let keystroke = match &action {
430                                    ContextMenuItemAction::Action(action) => Some(
431                                        KeystrokeLabel::new(
432                                            view_id,
433                                            action.boxed_clone(),
434                                            style.keystroke.container,
435                                            style.keystroke.text.clone(),
436                                        )
437                                        .flex_float(),
438                                    ),
439                                    ContextMenuItemAction::Handler(_) => None,
440                                };
441
442                                Flex::row()
443                                    .with_child(match label {
444                                        ContextMenuItemLabel::String(label) => {
445                                            Label::new(label.clone(), style.label.clone())
446                                                .contained()
447                                                .into_any()
448                                        }
449                                        ContextMenuItemLabel::Element(element) => {
450                                            element(state, style)
451                                        }
452                                    })
453                                    .with_children(keystroke)
454                                    .contained()
455                                    .with_style(style.container)
456                            })
457                            .with_cursor_style(CursorStyle::PointingHand)
458                            .on_up(MouseButton::Left, |_, _, _| {}) // Capture these events
459                            .on_down(MouseButton::Left, |_, _, _| {}) // Capture these events
460                            .on_click(MouseButton::Left, move |_, menu, cx| {
461                                menu.cancel(&Default::default(), cx);
462                                let window_id = cx.window_id();
463                                match &action {
464                                    ContextMenuItemAction::Action(action) => {
465                                        let action = action.boxed_clone();
466                                        cx.app_context()
467                                            .spawn(|mut cx| async move {
468                                                cx.dispatch_action(
469                                                    window_id,
470                                                    view_id,
471                                                    action.as_ref(),
472                                                )
473                                            })
474                                            .detach_and_log_err(cx);
475                                    }
476                                    ContextMenuItemAction::Handler(handler) => handler(cx),
477                                }
478                            })
479                            .on_drag(MouseButton::Left, |_, _, _| {})
480                            .into_any()
481                        }
482
483                        ContextMenuItem::Static(f) => f(cx),
484
485                        ContextMenuItem::Separator => Empty::new()
486                            .constrained()
487                            .with_height(1.)
488                            .contained()
489                            .with_style(style.separator)
490                            .into_any(),
491                    }
492                }))
493                .contained()
494                .with_style(style.container)
495        })
496        .on_down_out(MouseButton::Left, |_, this, cx| {
497            this.cancel(&Default::default(), cx);
498        })
499        .on_down_out(MouseButton::Right, |_, this, cx| {
500            this.cancel(&Default::default(), cx);
501        })
502    }
503}