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
25//
26pub enum ContextMenuItem {
27 Item {
28 label: String,
29 action: Box<dyn Action>,
30 },
31 Separator,
32}
33
34impl ContextMenuItem {
35 pub fn item(label: impl ToString, action: impl 'static + Action) -> Self {
36 Self::Item {
37 label: label.to_string(),
38 action: Box::new(action),
39 }
40 }
41
42 pub fn separator() -> Self {
43 Self::Separator
44 }
45
46 fn is_separator(&self) -> bool {
47 matches!(self, Self::Separator)
48 }
49
50 fn action_id(&self) -> Option<TypeId> {
51 match self {
52 ContextMenuItem::Item { action, .. } => Some(action.id()),
53 ContextMenuItem::Separator => None,
54 }
55 }
56}
57
58pub struct ContextMenu {
59 show_count: usize,
60 position: Vector2F,
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) -> keymap::Context {
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 .hoverable(true)
104 .fit_mode(OverlayFitMode::SnapToWindow)
105 .with_abs_position(self.position)
106 .boxed()
107 }
108
109 fn on_blur(&mut self, cx: &mut ViewContext<Self>) {
110 self.reset(cx);
111 }
112}
113
114impl ContextMenu {
115 pub fn new(cx: &mut ViewContext<Self>) -> Self {
116 Self {
117 show_count: 0,
118 position: Default::default(),
119 items: Default::default(),
120 selected_index: Default::default(),
121 visible: Default::default(),
122 previously_focused_view_id: Default::default(),
123 clicked: false,
124 _actions_observation: cx.observe_actions(Self::action_dispatched),
125 }
126 }
127
128 pub fn visible(&self) -> bool {
129 self.visible
130 }
131
132 fn action_dispatched(&mut self, action_id: TypeId, cx: &mut ViewContext<Self>) {
133 if let Some(ix) = self
134 .items
135 .iter()
136 .position(|item| item.action_id() == Some(action_id))
137 {
138 if self.clicked {
139 self.cancel(&Default::default(), cx);
140 } else {
141 self.selected_index = Some(ix);
142 cx.notify();
143 cx.spawn(|this, mut cx| async move {
144 cx.background().timer(Duration::from_millis(50)).await;
145 this.update(&mut cx, |this, cx| this.cancel(&Default::default(), cx));
146 })
147 .detach();
148 }
149 }
150 }
151
152 fn clicked(&mut self, _: &Clicked, _: &mut ViewContext<Self>) {
153 self.clicked = true;
154 }
155
156 fn confirm(&mut self, _: &Confirm, cx: &mut ViewContext<Self>) {
157 if let Some(ix) = self.selected_index {
158 if let Some(ContextMenuItem::Item { action, .. }) = self.items.get(ix) {
159 let window_id = cx.window_id();
160 let view_id = cx.view_id();
161 cx.dispatch_action_at(window_id, view_id, action.as_ref());
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 position: Vector2F,
232 items: impl IntoIterator<Item = ContextMenuItem>,
233 cx: &mut ViewContext<Self>,
234 ) {
235 let mut items = items.into_iter().peekable();
236 if items.peek().is_some() {
237 self.items = items.collect();
238 self.position = position;
239 self.visible = true;
240 self.show_count += 1;
241 if !cx.is_self_focused() {
242 self.previously_focused_view_id = cx.focused_view_id(cx.window_id());
243 }
244 cx.focus_self();
245 } else {
246 self.visible = false;
247 }
248 cx.notify();
249 }
250
251 fn render_menu_for_measurement(&self, cx: &mut RenderContext<Self>) -> impl Element {
252 let style = cx.global::<Settings>().theme.context_menu.clone();
253 Flex::row()
254 .with_child(
255 Flex::column()
256 .with_children(self.items.iter().enumerate().map(|(ix, item)| {
257 match item {
258 ContextMenuItem::Item { label, .. } => {
259 let style = style
260 .item
261 .style_for(Default::default(), Some(ix) == self.selected_index);
262
263 Label::new(label.to_string(), style.label.clone())
264 .contained()
265 .with_style(style.container)
266 .boxed()
267 }
268 ContextMenuItem::Separator => Empty::new()
269 .collapsed()
270 .contained()
271 .with_style(style.separator)
272 .constrained()
273 .with_height(1.)
274 .boxed(),
275 }
276 }))
277 .boxed(),
278 )
279 .with_child(
280 Flex::column()
281 .with_children(self.items.iter().enumerate().map(|(ix, item)| {
282 match item {
283 ContextMenuItem::Item { action, .. } => {
284 let style = style
285 .item
286 .style_for(Default::default(), Some(ix) == self.selected_index);
287 KeystrokeLabel::new(
288 action.boxed_clone(),
289 style.keystroke.container,
290 style.keystroke.text.clone(),
291 )
292 .boxed()
293 }
294 ContextMenuItem::Separator => Empty::new()
295 .collapsed()
296 .constrained()
297 .with_height(1.)
298 .contained()
299 .with_style(style.separator)
300 .boxed(),
301 }
302 }))
303 .contained()
304 .with_margin_left(style.keystroke_margin)
305 .boxed(),
306 )
307 .contained()
308 .with_style(style.container)
309 }
310
311 fn render_menu(&self, cx: &mut RenderContext<Self>) -> impl Element {
312 enum Menu {}
313 enum MenuItem {}
314 let style = cx.global::<Settings>().theme.context_menu.clone();
315 MouseEventHandler::new::<Menu, _, _>(0, cx, |_, cx| {
316 Flex::column()
317 .with_children(self.items.iter().enumerate().map(|(ix, item)| {
318 match item {
319 ContextMenuItem::Item { label, action } => {
320 let action = action.boxed_clone();
321 MouseEventHandler::new::<MenuItem, _, _>(ix, cx, |state, _| {
322 let style =
323 style.item.style_for(state, Some(ix) == self.selected_index);
324
325 Flex::row()
326 .with_child(
327 Label::new(label.to_string(), style.label.clone())
328 .contained()
329 .boxed(),
330 )
331 .with_child({
332 KeystrokeLabel::new(
333 action.boxed_clone(),
334 style.keystroke.container,
335 style.keystroke.text.clone(),
336 )
337 .flex_float()
338 .boxed()
339 })
340 .contained()
341 .with_style(style.container)
342 .boxed()
343 })
344 .with_cursor_style(CursorStyle::PointingHand)
345 .on_click(MouseButton::Left, move |_, cx| {
346 cx.dispatch_action(Clicked);
347 cx.dispatch_any_action(action.boxed_clone());
348 })
349 .boxed()
350 }
351 ContextMenuItem::Separator => Empty::new()
352 .constrained()
353 .with_height(1.)
354 .contained()
355 .with_style(style.separator)
356 .boxed(),
357 }
358 }))
359 .contained()
360 .with_style(style.container)
361 .boxed()
362 })
363 .on_down_out(MouseButton::Left, |_, cx| cx.dispatch_action(Cancel))
364 .on_down_out(MouseButton::Right, |_, cx| cx.dispatch_action(Cancel))
365 }
366}