context_menu.rs

  1use gpui::{
  2    elements::*, geometry::vector::Vector2F, impl_internal_actions, keymap, platform::CursorStyle,
  3    Action, AppContext, Axis, Entity, MouseButton, MutableAppContext, RenderContext,
  4    SizeConstraint, Subscription, View, ViewContext,
  5};
  6use menu::*;
  7use settings::Settings;
  8use std::{any::TypeId, time::Duration};
  9
 10#[derive(Copy, Clone, PartialEq)]
 11struct Clicked;
 12
 13impl_internal_actions!(context_menu, [Clicked]);
 14
 15pub fn init(cx: &mut MutableAppContext) {
 16    cx.add_action(ContextMenu::select_first);
 17    cx.add_action(ContextMenu::select_last);
 18    cx.add_action(ContextMenu::select_next);
 19    cx.add_action(ContextMenu::select_prev);
 20    cx.add_action(ContextMenu::clicked);
 21    cx.add_action(ContextMenu::confirm);
 22    cx.add_action(ContextMenu::cancel);
 23}
 24
 25pub enum ContextMenuItem {
 26    Item {
 27        label: String,
 28        action: Box<dyn Action>,
 29    },
 30    Separator,
 31}
 32
 33impl ContextMenuItem {
 34    pub fn item(label: impl ToString, action: impl 'static + Action) -> Self {
 35        Self::Item {
 36            label: label.to_string(),
 37            action: Box::new(action),
 38        }
 39    }
 40
 41    pub fn separator() -> Self {
 42        Self::Separator
 43    }
 44
 45    fn is_separator(&self) -> bool {
 46        matches!(self, Self::Separator)
 47    }
 48
 49    fn action_id(&self) -> Option<TypeId> {
 50        match self {
 51            ContextMenuItem::Item { action, .. } => Some(action.id()),
 52            ContextMenuItem::Separator => None,
 53        }
 54    }
 55}
 56
 57pub struct ContextMenu {
 58    show_count: usize,
 59    position: Vector2F,
 60    items: Vec<ContextMenuItem>,
 61    selected_index: Option<usize>,
 62    visible: bool,
 63    previously_focused_view_id: Option<usize>,
 64    clicked: bool,
 65    _actions_observation: Subscription,
 66}
 67
 68impl Entity for ContextMenu {
 69    type Event = ();
 70}
 71
 72impl View for ContextMenu {
 73    fn ui_name() -> &'static str {
 74        "ContextMenu"
 75    }
 76
 77    fn keymap_context(&self, _: &AppContext) -> keymap::Context {
 78        let mut cx = Self::default_keymap_context();
 79        cx.set.insert("menu".into());
 80        cx
 81    }
 82
 83    fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
 84        if !self.visible {
 85            return Empty::new().boxed();
 86        }
 87
 88        // Render the menu once at minimum width.
 89        let mut collapsed_menu = self.render_menu_for_measurement(cx).boxed();
 90        let expanded_menu = self
 91            .render_menu(cx)
 92            .constrained()
 93            .dynamically(move |constraint, cx| {
 94                SizeConstraint::strict_along(
 95                    Axis::Horizontal,
 96                    collapsed_menu.layout(constraint, cx).x(),
 97                )
 98            })
 99            .boxed();
100
101        Overlay::new(expanded_menu)
102            .hoverable(true)
103            .fit_mode(OverlayFitMode::SnapToWindow)
104            .with_abs_position(self.position)
105            .boxed()
106    }
107
108    fn on_blur(&mut self, cx: &mut ViewContext<Self>) {
109        self.reset(cx);
110    }
111}
112
113impl ContextMenu {
114    pub fn new(cx: &mut ViewContext<Self>) -> Self {
115        Self {
116            show_count: 0,
117            position: Default::default(),
118            items: Default::default(),
119            selected_index: Default::default(),
120            visible: Default::default(),
121            previously_focused_view_id: Default::default(),
122            clicked: false,
123            _actions_observation: cx.observe_actions(Self::action_dispatched),
124        }
125    }
126
127    pub fn visible(&self) -> bool {
128        self.visible
129    }
130
131    fn action_dispatched(&mut self, action_id: TypeId, cx: &mut ViewContext<Self>) {
132        if let Some(ix) = self
133            .items
134            .iter()
135            .position(|item| item.action_id() == Some(action_id))
136        {
137            if self.clicked {
138                self.cancel(&Default::default(), cx);
139            } else {
140                self.selected_index = Some(ix);
141                cx.notify();
142                cx.spawn(|this, mut cx| async move {
143                    cx.background().timer(Duration::from_millis(50)).await;
144                    this.update(&mut cx, |this, cx| this.cancel(&Default::default(), cx));
145                })
146                .detach();
147            }
148        }
149    }
150
151    fn clicked(&mut self, _: &Clicked, _: &mut ViewContext<Self>) {
152        self.clicked = true;
153    }
154
155    fn confirm(&mut self, _: &Confirm, cx: &mut ViewContext<Self>) {
156        if let Some(ix) = self.selected_index {
157            if let Some(ContextMenuItem::Item { action, .. }) = self.items.get(ix) {
158                let window_id = cx.window_id();
159                let view_id = cx.view_id();
160                cx.dispatch_action_at(window_id, view_id, action.as_ref());
161                self.reset(cx);
162            }
163        }
164    }
165
166    fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
167        self.reset(cx);
168        let show_count = self.show_count;
169        cx.defer(move |this, cx| {
170            if cx.handle().is_focused(cx) && this.show_count == show_count {
171                let window_id = cx.window_id();
172                (**cx).focus(window_id, this.previously_focused_view_id.take());
173            }
174        });
175    }
176
177    fn reset(&mut self, cx: &mut ViewContext<Self>) {
178        self.items.clear();
179        self.visible = false;
180        self.selected_index.take();
181        self.clicked = false;
182        cx.notify();
183    }
184
185    fn select_first(&mut self, _: &SelectFirst, cx: &mut ViewContext<Self>) {
186        self.selected_index = self.items.iter().position(|item| !item.is_separator());
187        cx.notify();
188    }
189
190    fn select_last(&mut self, _: &SelectLast, cx: &mut ViewContext<Self>) {
191        for (ix, item) in self.items.iter().enumerate().rev() {
192            if !item.is_separator() {
193                self.selected_index = Some(ix);
194                cx.notify();
195                break;
196            }
197        }
198    }
199
200    fn select_next(&mut self, _: &SelectNext, cx: &mut ViewContext<Self>) {
201        if let Some(ix) = self.selected_index {
202            for (ix, item) in self.items.iter().enumerate().skip(ix + 1) {
203                if !item.is_separator() {
204                    self.selected_index = Some(ix);
205                    cx.notify();
206                    break;
207                }
208            }
209        } else {
210            self.select_first(&Default::default(), cx);
211        }
212    }
213
214    fn select_prev(&mut self, _: &SelectPrev, cx: &mut ViewContext<Self>) {
215        if let Some(ix) = self.selected_index {
216            for (ix, item) in self.items.iter().enumerate().take(ix).rev() {
217                if !item.is_separator() {
218                    self.selected_index = Some(ix);
219                    cx.notify();
220                    break;
221                }
222            }
223        } else {
224            self.select_last(&Default::default(), cx);
225        }
226    }
227
228    pub fn show(
229        &mut self,
230        position: Vector2F,
231        items: impl IntoIterator<Item = ContextMenuItem>,
232        cx: &mut ViewContext<Self>,
233    ) {
234        let mut items = items.into_iter().peekable();
235        if items.peek().is_some() {
236            self.items = items.collect();
237            self.position = position;
238            self.visible = true;
239            self.show_count += 1;
240            if !cx.is_self_focused() {
241                self.previously_focused_view_id = cx.focused_view_id(cx.window_id());
242            }
243            cx.focus_self();
244        } else {
245            self.visible = false;
246        }
247        cx.notify();
248    }
249
250    fn render_menu_for_measurement(&self, cx: &mut RenderContext<Self>) -> impl Element {
251        let style = cx.global::<Settings>().theme.context_menu.clone();
252        Flex::row()
253            .with_child(
254                Flex::column()
255                    .with_children(self.items.iter().enumerate().map(|(ix, item)| {
256                        match item {
257                            ContextMenuItem::Item { label, .. } => {
258                                let style = style
259                                    .item
260                                    .style_for(Default::default(), Some(ix) == self.selected_index);
261                                Label::new(label.to_string(), style.label.clone())
262                                    .contained()
263                                    .with_style(style.container)
264                                    .boxed()
265                            }
266                            ContextMenuItem::Separator => Empty::new()
267                                .collapsed()
268                                .contained()
269                                .with_style(style.separator)
270                                .constrained()
271                                .with_height(1.)
272                                .boxed(),
273                        }
274                    }))
275                    .boxed(),
276            )
277            .with_child(
278                Flex::column()
279                    .with_children(self.items.iter().enumerate().map(|(ix, item)| {
280                        match item {
281                            ContextMenuItem::Item { action, .. } => {
282                                let style = style
283                                    .item
284                                    .style_for(Default::default(), Some(ix) == self.selected_index);
285                                KeystrokeLabel::new(
286                                    action.boxed_clone(),
287                                    style.keystroke.container,
288                                    style.keystroke.text.clone(),
289                                )
290                                .boxed()
291                            }
292                            ContextMenuItem::Separator => Empty::new()
293                                .collapsed()
294                                .constrained()
295                                .with_height(1.)
296                                .contained()
297                                .with_style(style.separator)
298                                .boxed(),
299                        }
300                    }))
301                    .contained()
302                    .with_margin_left(style.keystroke_margin)
303                    .boxed(),
304            )
305            .contained()
306            .with_style(style.container)
307    }
308
309    fn render_menu(&self, cx: &mut RenderContext<Self>) -> impl Element {
310        enum Menu {}
311        enum MenuItem {}
312        let style = cx.global::<Settings>().theme.context_menu.clone();
313        MouseEventHandler::new::<Menu, _, _>(0, cx, |_, cx| {
314            Flex::column()
315                .with_children(self.items.iter().enumerate().map(|(ix, item)| {
316                    match item {
317                        ContextMenuItem::Item { label, action } => {
318                            let action = action.boxed_clone();
319                            MouseEventHandler::new::<MenuItem, _, _>(ix, cx, |state, _| {
320                                let style =
321                                    style.item.style_for(state, Some(ix) == self.selected_index);
322                                Flex::row()
323                                    .with_child(
324                                        Label::new(label.to_string(), style.label.clone()).boxed(),
325                                    )
326                                    .with_child({
327                                        KeystrokeLabel::new(
328                                            action.boxed_clone(),
329                                            style.keystroke.container,
330                                            style.keystroke.text.clone(),
331                                        )
332                                        .flex_float()
333                                        .boxed()
334                                    })
335                                    .contained()
336                                    .with_style(style.container)
337                                    .boxed()
338                            })
339                            .with_cursor_style(CursorStyle::PointingHand)
340                            .on_click(MouseButton::Left, move |_, cx| {
341                                cx.dispatch_action(Clicked);
342                                cx.dispatch_any_action(action.boxed_clone());
343                            })
344                            .boxed()
345                        }
346                        ContextMenuItem::Separator => Empty::new()
347                            .constrained()
348                            .with_height(1.)
349                            .contained()
350                            .with_style(style.separator)
351                            .boxed(),
352                    }
353                }))
354                .contained()
355                .with_style(style.container)
356                .boxed()
357        })
358        .on_down_out(MouseButton::Left, |_, cx| cx.dispatch_action(Cancel))
359        .on_down_out(MouseButton::Right, |_, cx| cx.dispatch_action(Cancel))
360    }
361}