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