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