1use gpui::{
2 anyhow,
3 elements::*,
4 geometry::vector::Vector2F,
5 impl_internal_actions,
6 keymap_matcher::KeymapContext,
7 platform::{CursorStyle, MouseButton},
8 Action, AnyViewHandle, AppContext, Axis, Entity, MouseState, SizeConstraint, Subscription,
9 View, ViewContext,
10};
11use menu::*;
12use settings::Settings;
13use std::{any::TypeId, borrow::Cow, time::Duration};
14
15#[derive(Copy, Clone, PartialEq)]
16struct Clicked;
17
18impl_internal_actions!(context_menu, [Clicked]);
19
20pub fn init(cx: &mut AppContext) {
21 cx.add_action(ContextMenu::select_first);
22 cx.add_action(ContextMenu::select_last);
23 cx.add_action(ContextMenu::select_next);
24 cx.add_action(ContextMenu::select_prev);
25 cx.add_action(ContextMenu::clicked);
26 cx.add_action(ContextMenu::confirm);
27 cx.add_action(ContextMenu::cancel);
28}
29
30pub type StaticItem = Box<dyn Fn(&mut AppContext) -> AnyElement<ContextMenu>>;
31
32type ContextMenuItemBuilder =
33 Box<dyn Fn(&mut MouseState, &theme::ContextMenuItem) -> AnyElement<ContextMenu>>;
34
35pub enum ContextMenuItemLabel {
36 String(Cow<'static, str>),
37 Element(ContextMenuItemBuilder),
38}
39
40impl From<Cow<'static, str>> for ContextMenuItemLabel {
41 fn from(s: Cow<'static, str>) -> Self {
42 Self::String(s)
43 }
44}
45
46impl From<&'static str> for ContextMenuItemLabel {
47 fn from(s: &'static str) -> Self {
48 Self::String(s.into())
49 }
50}
51
52impl From<String> for ContextMenuItemLabel {
53 fn from(s: String) -> Self {
54 Self::String(s.into())
55 }
56}
57
58impl<T> From<T> for ContextMenuItemLabel
59where
60 T: 'static + Fn(&mut MouseState, &theme::ContextMenuItem) -> AnyElement<ContextMenu>,
61{
62 fn from(f: T) -> Self {
63 Self::Element(Box::new(f))
64 }
65}
66
67pub enum ContextMenuItem {
68 Item {
69 label: ContextMenuItemLabel,
70 action: Box<dyn Action>,
71 },
72 Static(StaticItem),
73 Separator,
74}
75
76impl ContextMenuItem {
77 pub fn item(label: impl Into<ContextMenuItemLabel>, action: impl 'static + Action) -> Self {
78 Self::Item {
79 label: label.into(),
80 action: Box::new(action),
81 }
82 }
83
84 pub fn separator() -> Self {
85 Self::Separator
86 }
87
88 fn is_action(&self) -> bool {
89 matches!(self, Self::Item { .. })
90 }
91
92 fn action_id(&self) -> Option<TypeId> {
93 match self {
94 ContextMenuItem::Item { action, .. } => Some(action.id()),
95 ContextMenuItem::Static(..) | ContextMenuItem::Separator => None,
96 }
97 }
98}
99
100pub struct ContextMenu {
101 show_count: usize,
102 anchor_position: Vector2F,
103 anchor_corner: AnchorCorner,
104 position_mode: OverlayPositionMode,
105 items: Vec<ContextMenuItem>,
106 selected_index: Option<usize>,
107 visible: bool,
108 previously_focused_view_id: Option<usize>,
109 clicked: bool,
110 parent_view_id: usize,
111 _actions_observation: Subscription,
112}
113
114impl Entity for ContextMenu {
115 type Event = ();
116}
117
118impl View for ContextMenu {
119 fn ui_name() -> &'static str {
120 "ContextMenu"
121 }
122
123 fn keymap_context(&self, _: &AppContext) -> KeymapContext {
124 let mut cx = Self::default_keymap_context();
125 cx.add_identifier("menu");
126 cx
127 }
128
129 fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
130 if !self.visible {
131 return Empty::new().into_any();
132 }
133
134 // Render the menu once at minimum width.
135 let mut collapsed_menu = self.render_menu_for_measurement(cx);
136 let expanded_menu =
137 self.render_menu(cx)
138 .constrained()
139 .dynamically(move |constraint, view, cx| {
140 SizeConstraint::strict_along(
141 Axis::Horizontal,
142 collapsed_menu.layout(constraint, view, cx).0.x(),
143 )
144 });
145
146 Overlay::new(expanded_menu)
147 .with_hoverable(true)
148 .with_fit_mode(OverlayFitMode::SnapToWindow)
149 .with_anchor_position(self.anchor_position)
150 .with_anchor_corner(self.anchor_corner)
151 .with_position_mode(self.position_mode)
152 .into_any()
153 }
154
155 fn focus_out(&mut self, _: AnyViewHandle, cx: &mut ViewContext<Self>) {
156 self.reset(cx);
157 }
158}
159
160impl ContextMenu {
161 pub fn new(cx: &mut ViewContext<Self>) -> Self {
162 let parent_view_id = cx.parent().unwrap();
163
164 Self {
165 show_count: 0,
166 anchor_position: Default::default(),
167 anchor_corner: AnchorCorner::TopLeft,
168 position_mode: OverlayPositionMode::Window,
169 items: Default::default(),
170 selected_index: Default::default(),
171 visible: Default::default(),
172 previously_focused_view_id: Default::default(),
173 clicked: false,
174 parent_view_id,
175 _actions_observation: cx.observe_actions(Self::action_dispatched),
176 }
177 }
178
179 pub fn visible(&self) -> bool {
180 self.visible
181 }
182
183 fn action_dispatched(&mut self, action_id: TypeId, cx: &mut ViewContext<Self>) {
184 if let Some(ix) = self
185 .items
186 .iter()
187 .position(|item| item.action_id() == Some(action_id))
188 {
189 if self.clicked {
190 self.cancel(&Default::default(), cx);
191 } else {
192 self.selected_index = Some(ix);
193 cx.notify();
194 cx.spawn(|this, mut cx| async move {
195 cx.background().timer(Duration::from_millis(50)).await;
196 this.update(&mut cx, |this, cx| this.cancel(&Default::default(), cx))?;
197 anyhow::Ok(())
198 })
199 .detach_and_log_err(cx);
200 }
201 }
202 }
203
204 fn clicked(&mut self, _: &Clicked, _: &mut ViewContext<Self>) {
205 self.clicked = true;
206 }
207
208 fn confirm(&mut self, _: &Confirm, cx: &mut ViewContext<Self>) {
209 if let Some(ix) = self.selected_index {
210 if let Some(ContextMenuItem::Item { action, .. }) = self.items.get(ix) {
211 cx.dispatch_any_action(action.boxed_clone());
212 self.reset(cx);
213 }
214 }
215 }
216
217 fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
218 self.reset(cx);
219 let show_count = self.show_count;
220 cx.defer(move |this, cx| {
221 if cx.handle().is_focused(cx) && this.show_count == show_count {
222 let window_id = cx.window_id();
223 (**cx).focus(window_id, this.previously_focused_view_id.take());
224 }
225 });
226 }
227
228 fn reset(&mut self, cx: &mut ViewContext<Self>) {
229 self.items.clear();
230 self.visible = false;
231 self.selected_index.take();
232 self.clicked = false;
233 cx.notify();
234 }
235
236 fn select_first(&mut self, _: &SelectFirst, cx: &mut ViewContext<Self>) {
237 self.selected_index = self.items.iter().position(|item| item.is_action());
238 cx.notify();
239 }
240
241 fn select_last(&mut self, _: &SelectLast, cx: &mut ViewContext<Self>) {
242 for (ix, item) in self.items.iter().enumerate().rev() {
243 if item.is_action() {
244 self.selected_index = Some(ix);
245 cx.notify();
246 break;
247 }
248 }
249 }
250
251 fn select_next(&mut self, _: &SelectNext, cx: &mut ViewContext<Self>) {
252 if let Some(ix) = self.selected_index {
253 for (ix, item) in self.items.iter().enumerate().skip(ix + 1) {
254 if item.is_action() {
255 self.selected_index = Some(ix);
256 cx.notify();
257 break;
258 }
259 }
260 } else {
261 self.select_first(&Default::default(), cx);
262 }
263 }
264
265 fn select_prev(&mut self, _: &SelectPrev, cx: &mut ViewContext<Self>) {
266 if let Some(ix) = self.selected_index {
267 for (ix, item) in self.items.iter().enumerate().take(ix).rev() {
268 if item.is_action() {
269 self.selected_index = Some(ix);
270 cx.notify();
271 break;
272 }
273 }
274 } else {
275 self.select_last(&Default::default(), cx);
276 }
277 }
278
279 pub fn show(
280 &mut self,
281 anchor_position: Vector2F,
282 anchor_corner: AnchorCorner,
283 items: Vec<ContextMenuItem>,
284 cx: &mut ViewContext<Self>,
285 ) {
286 let mut items = items.into_iter().peekable();
287 if items.peek().is_some() {
288 self.items = items.collect();
289 self.anchor_position = anchor_position;
290 self.anchor_corner = anchor_corner;
291 self.visible = true;
292 self.show_count += 1;
293 if !cx.is_self_focused() {
294 self.previously_focused_view_id = cx.focused_view_id();
295 }
296 cx.focus_self();
297 } else {
298 self.visible = false;
299 }
300 cx.notify();
301 }
302
303 pub fn set_position_mode(&mut self, mode: OverlayPositionMode) {
304 self.position_mode = mode;
305 }
306
307 fn render_menu_for_measurement(&self, cx: &mut ViewContext<Self>) -> impl Element<ContextMenu> {
308 let style = cx.global::<Settings>().theme.context_menu.clone();
309 Flex::row()
310 .with_child(
311 Flex::column().with_children(self.items.iter().enumerate().map(|(ix, item)| {
312 match item {
313 ContextMenuItem::Item { label, .. } => {
314 let style = style.item.style_for(
315 &mut Default::default(),
316 Some(ix) == self.selected_index,
317 );
318
319 match label {
320 ContextMenuItemLabel::String(label) => {
321 Label::new(label.to_string(), style.label.clone())
322 .contained()
323 .with_style(style.container)
324 .into_any()
325 }
326 ContextMenuItemLabel::Element(element) => {
327 element(&mut Default::default(), style)
328 }
329 }
330 }
331
332 ContextMenuItem::Static(f) => f(cx),
333
334 ContextMenuItem::Separator => Empty::new()
335 .collapsed()
336 .contained()
337 .with_style(style.separator)
338 .constrained()
339 .with_height(1.)
340 .into_any(),
341 }
342 })),
343 )
344 .with_child(
345 Flex::column()
346 .with_children(self.items.iter().enumerate().map(|(ix, item)| {
347 match item {
348 ContextMenuItem::Item { action, .. } => {
349 let style = style.item.style_for(
350 &mut Default::default(),
351 Some(ix) == self.selected_index,
352 );
353
354 KeystrokeLabel::new(
355 self.parent_view_id,
356 action.boxed_clone(),
357 style.keystroke.container,
358 style.keystroke.text.clone(),
359 )
360 .into_any()
361 }
362
363 ContextMenuItem::Static(_) => Empty::new().into_any(),
364
365 ContextMenuItem::Separator => Empty::new()
366 .collapsed()
367 .constrained()
368 .with_height(1.)
369 .contained()
370 .with_style(style.separator)
371 .into_any(),
372 }
373 }))
374 .contained()
375 .with_margin_left(style.keystroke_margin),
376 )
377 .contained()
378 .with_style(style.container)
379 }
380
381 fn render_menu(&self, cx: &mut ViewContext<Self>) -> impl Element<ContextMenu> {
382 enum Menu {}
383 enum MenuItem {}
384
385 let style = cx.global::<Settings>().theme.context_menu.clone();
386
387 MouseEventHandler::<Menu, ContextMenu>::new(0, cx, |_, cx| {
388 Flex::column()
389 .with_children(self.items.iter().enumerate().map(|(ix, item)| {
390 match item {
391 ContextMenuItem::Item { label, action } => {
392 let action = action.boxed_clone();
393 let view_id = self.parent_view_id;
394 MouseEventHandler::<MenuItem, ContextMenu>::new(ix, cx, |state, _| {
395 let style =
396 style.item.style_for(state, Some(ix) == self.selected_index);
397
398 Flex::row()
399 .with_child(match label {
400 ContextMenuItemLabel::String(label) => {
401 Label::new(label.clone(), style.label.clone())
402 .contained()
403 .into_any()
404 }
405 ContextMenuItemLabel::Element(element) => {
406 element(state, style)
407 }
408 })
409 .with_child({
410 KeystrokeLabel::new(
411 view_id,
412 action.boxed_clone(),
413 style.keystroke.container,
414 style.keystroke.text.clone(),
415 )
416 .flex_float()
417 })
418 .contained()
419 .with_style(style.container)
420 })
421 .with_cursor_style(CursorStyle::PointingHand)
422 .on_up(MouseButton::Left, |_, _, _| {}) // Capture these events
423 .on_down(MouseButton::Left, |_, _, _| {}) // Capture these events
424 .on_click(MouseButton::Left, move |_, _, cx| {
425 let window_id = cx.window_id();
426 cx.dispatch_action(Clicked);
427 cx.dispatch_any_action_at(window_id, view_id, action.boxed_clone());
428 })
429 .on_drag(MouseButton::Left, |_, _, _| {})
430 .into_any()
431 }
432
433 ContextMenuItem::Static(f) => f(cx),
434
435 ContextMenuItem::Separator => Empty::new()
436 .constrained()
437 .with_height(1.)
438 .contained()
439 .with_style(style.separator)
440 .into_any(),
441 }
442 }))
443 .contained()
444 .with_style(style.container)
445 })
446 .on_down_out(MouseButton::Left, |_, _, cx| cx.dispatch_action(Cancel))
447 .on_down_out(MouseButton::Right, |_, _, cx| cx.dispatch_action(Cancel))
448 }
449}