context_menu.rs

  1use gpui::{
  2    elements::*, geometry::vector::Vector2F, impl_internal_actions, keymap, platform::CursorStyle,
  3    Action, AppContext, Axis, Entity, MutableAppContext, RenderContext, SizeConstraint,
  4    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    fn action_dispatched(&mut self, action_id: TypeId, cx: &mut ViewContext<Self>) {
128        if let Some(ix) = self
129            .items
130            .iter()
131            .position(|item| item.action_id() == Some(action_id))
132        {
133            if self.clicked {
134                self.cancel(&Default::default(), cx);
135            } else {
136                self.selected_index = Some(ix);
137                cx.notify();
138                cx.spawn(|this, mut cx| async move {
139                    cx.background().timer(Duration::from_millis(50)).await;
140                    this.update(&mut cx, |this, cx| this.cancel(&Default::default(), cx));
141                })
142                .detach();
143            }
144        }
145    }
146
147    fn clicked(&mut self, _: &Clicked, _: &mut ViewContext<Self>) {
148        self.clicked = true;
149    }
150
151    fn confirm(&mut self, _: &Confirm, cx: &mut ViewContext<Self>) {
152        if let Some(ix) = self.selected_index {
153            if let Some(ContextMenuItem::Item { action, .. }) = self.items.get(ix) {
154                let window_id = cx.window_id();
155                let view_id = cx.view_id();
156                cx.dispatch_action_at(window_id, view_id, action.as_ref());
157                self.reset(cx);
158            }
159        }
160    }
161
162    fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
163        self.reset(cx);
164        let show_count = self.show_count;
165        cx.defer(move |this, cx| {
166            if cx.handle().is_focused(cx) && this.show_count == show_count {
167                let window_id = cx.window_id();
168                (**cx).focus(window_id, this.previously_focused_view_id.take());
169            }
170        });
171    }
172
173    fn reset(&mut self, cx: &mut ViewContext<Self>) {
174        self.items.clear();
175        self.visible = false;
176        self.selected_index.take();
177        self.clicked = false;
178        cx.notify();
179    }
180
181    fn select_first(&mut self, _: &SelectFirst, cx: &mut ViewContext<Self>) {
182        self.selected_index = self.items.iter().position(|item| !item.is_separator());
183        cx.notify();
184    }
185
186    fn select_last(&mut self, _: &SelectLast, cx: &mut ViewContext<Self>) {
187        for (ix, item) in self.items.iter().enumerate().rev() {
188            if !item.is_separator() {
189                self.selected_index = Some(ix);
190                cx.notify();
191                break;
192            }
193        }
194    }
195
196    fn select_next(&mut self, _: &SelectNext, cx: &mut ViewContext<Self>) {
197        if let Some(ix) = self.selected_index {
198            for (ix, item) in self.items.iter().enumerate().skip(ix + 1) {
199                if !item.is_separator() {
200                    self.selected_index = Some(ix);
201                    cx.notify();
202                    break;
203                }
204            }
205        } else {
206            self.select_first(&Default::default(), cx);
207        }
208    }
209
210    fn select_prev(&mut self, _: &SelectPrev, cx: &mut ViewContext<Self>) {
211        if let Some(ix) = self.selected_index {
212            for (ix, item) in self.items.iter().enumerate().take(ix).rev() {
213                if !item.is_separator() {
214                    self.selected_index = Some(ix);
215                    cx.notify();
216                    break;
217                }
218            }
219        } else {
220            self.select_last(&Default::default(), cx);
221        }
222    }
223
224    pub fn show(
225        &mut self,
226        position: Vector2F,
227        items: impl IntoIterator<Item = ContextMenuItem>,
228        cx: &mut ViewContext<Self>,
229    ) {
230        let mut items = items.into_iter().peekable();
231        if items.peek().is_some() {
232            self.items = items.collect();
233            self.position = position;
234            self.visible = true;
235            self.show_count += 1;
236            if !cx.is_self_focused() {
237                self.previously_focused_view_id = cx.focused_view_id(cx.window_id());
238            }
239            cx.focus_self();
240        } else {
241            self.visible = false;
242        }
243        cx.notify();
244    }
245
246    fn render_menu_for_measurement(&self, cx: &mut RenderContext<Self>) -> impl Element {
247        let style = cx.global::<Settings>().theme.context_menu.clone();
248        Flex::row()
249            .with_child(
250                Flex::column()
251                    .with_children(self.items.iter().enumerate().map(|(ix, item)| {
252                        match item {
253                            ContextMenuItem::Item { label, .. } => {
254                                let style = style
255                                    .item
256                                    .style_for(Default::default(), Some(ix) == self.selected_index);
257                                Label::new(label.to_string(), style.label.clone())
258                                    .contained()
259                                    .with_style(style.container)
260                                    .boxed()
261                            }
262                            ContextMenuItem::Separator => Empty::new()
263                                .collapsed()
264                                .contained()
265                                .with_style(style.separator)
266                                .constrained()
267                                .with_height(1.)
268                                .boxed(),
269                        }
270                    }))
271                    .boxed(),
272            )
273            .with_child(
274                Flex::column()
275                    .with_children(self.items.iter().enumerate().map(|(ix, item)| {
276                        match item {
277                            ContextMenuItem::Item { action, .. } => {
278                                let style = style
279                                    .item
280                                    .style_for(Default::default(), Some(ix) == self.selected_index);
281                                KeystrokeLabel::new(
282                                    action.boxed_clone(),
283                                    style.keystroke.container,
284                                    style.keystroke.text.clone(),
285                                )
286                                .boxed()
287                            }
288                            ContextMenuItem::Separator => Empty::new()
289                                .collapsed()
290                                .constrained()
291                                .with_height(1.)
292                                .contained()
293                                .with_style(style.separator)
294                                .boxed(),
295                        }
296                    }))
297                    .contained()
298                    .with_margin_left(style.keystroke_margin)
299                    .boxed(),
300            )
301            .contained()
302            .with_style(style.container)
303    }
304
305    fn render_menu(&self, cx: &mut RenderContext<Self>) -> impl Element {
306        enum Menu {}
307        enum MenuItem {}
308        let style = cx.global::<Settings>().theme.context_menu.clone();
309        MouseEventHandler::new::<Menu, _, _>(0, cx, |_, cx| {
310            Flex::column()
311                .with_children(self.items.iter().enumerate().map(|(ix, item)| {
312                    match item {
313                        ContextMenuItem::Item { label, action } => {
314                            let action = action.boxed_clone();
315                            MouseEventHandler::new::<MenuItem, _, _>(ix, cx, |state, _| {
316                                let style =
317                                    style.item.style_for(state, Some(ix) == self.selected_index);
318                                Flex::row()
319                                    .with_child(
320                                        Label::new(label.to_string(), style.label.clone()).boxed(),
321                                    )
322                                    .with_child({
323                                        KeystrokeLabel::new(
324                                            action.boxed_clone(),
325                                            style.keystroke.container,
326                                            style.keystroke.text.clone(),
327                                        )
328                                        .flex_float()
329                                        .boxed()
330                                    })
331                                    .contained()
332                                    .with_style(style.container)
333                                    .boxed()
334                            })
335                            .with_cursor_style(CursorStyle::PointingHand)
336                            .on_click(move |_, _, cx| {
337                                cx.dispatch_action(Clicked);
338                                cx.dispatch_any_action(action.boxed_clone());
339                            })
340                            .boxed()
341                        }
342                        ContextMenuItem::Separator => Empty::new()
343                            .constrained()
344                            .with_height(1.)
345                            .contained()
346                            .with_style(style.separator)
347                            .boxed(),
348                    }
349                }))
350                .contained()
351                .with_style(style.container)
352                .boxed()
353        })
354        .on_mouse_down_out(|_, cx| cx.dispatch_action(Cancel))
355        .on_right_mouse_down_out(|_, cx| cx.dispatch_action(Cancel))
356    }
357}