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