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 cx.dispatch_any_action(action.boxed_clone());
160 self.reset(cx);
161 }
162 }
163 }
164
165 fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
166 self.reset(cx);
167 let show_count = self.show_count;
168 cx.defer(move |this, cx| {
169 if cx.handle().is_focused(cx) && this.show_count == show_count {
170 let window_id = cx.window_id();
171 (**cx).focus(window_id, this.previously_focused_view_id.take());
172 }
173 });
174 }
175
176 fn reset(&mut self, cx: &mut ViewContext<Self>) {
177 self.items.clear();
178 self.visible = false;
179 self.selected_index.take();
180 self.clicked = false;
181 cx.notify();
182 }
183
184 fn select_first(&mut self, _: &SelectFirst, cx: &mut ViewContext<Self>) {
185 self.selected_index = self.items.iter().position(|item| !item.is_separator());
186 cx.notify();
187 }
188
189 fn select_last(&mut self, _: &SelectLast, cx: &mut ViewContext<Self>) {
190 for (ix, item) in self.items.iter().enumerate().rev() {
191 if !item.is_separator() {
192 self.selected_index = Some(ix);
193 cx.notify();
194 break;
195 }
196 }
197 }
198
199 fn select_next(&mut self, _: &SelectNext, cx: &mut ViewContext<Self>) {
200 if let Some(ix) = self.selected_index {
201 for (ix, item) in self.items.iter().enumerate().skip(ix + 1) {
202 if !item.is_separator() {
203 self.selected_index = Some(ix);
204 cx.notify();
205 break;
206 }
207 }
208 } else {
209 self.select_first(&Default::default(), cx);
210 }
211 }
212
213 fn select_prev(&mut self, _: &SelectPrev, cx: &mut ViewContext<Self>) {
214 if let Some(ix) = self.selected_index {
215 for (ix, item) in self.items.iter().enumerate().take(ix).rev() {
216 if !item.is_separator() {
217 self.selected_index = Some(ix);
218 cx.notify();
219 break;
220 }
221 }
222 } else {
223 self.select_last(&Default::default(), cx);
224 }
225 }
226
227 pub fn show(
228 &mut self,
229 position: Vector2F,
230 items: impl IntoIterator<Item = ContextMenuItem>,
231 cx: &mut ViewContext<Self>,
232 ) {
233 let mut items = items.into_iter().peekable();
234 if items.peek().is_some() {
235 self.items = items.collect();
236 self.position = position;
237 self.visible = true;
238 self.show_count += 1;
239 if !cx.is_self_focused() {
240 self.previously_focused_view_id = cx.focused_view_id(cx.window_id());
241 }
242 cx.focus_self();
243 } else {
244 self.visible = false;
245 }
246 cx.notify();
247 }
248
249 fn render_menu_for_measurement(&self, cx: &mut RenderContext<Self>) -> impl Element {
250 let style = cx.global::<Settings>().theme.context_menu.clone();
251 Flex::row()
252 .with_child(
253 Flex::column()
254 .with_children(self.items.iter().enumerate().map(|(ix, item)| {
255 match item {
256 ContextMenuItem::Item { label, .. } => {
257 let style = style
258 .item
259 .style_for(Default::default(), Some(ix) == self.selected_index);
260
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
323 Flex::row()
324 .with_child(
325 Label::new(label.to_string(), style.label.clone())
326 .contained()
327 .boxed(),
328 )
329 .with_child({
330 KeystrokeLabel::new(
331 action.boxed_clone(),
332 style.keystroke.container,
333 style.keystroke.text.clone(),
334 )
335 .flex_float()
336 .boxed()
337 })
338 .contained()
339 .with_style(style.container)
340 .boxed()
341 })
342 .with_cursor_style(CursorStyle::PointingHand)
343 .on_click(MouseButton::Left, move |_, cx| {
344 cx.dispatch_action(Clicked);
345 cx.dispatch_any_action(action.boxed_clone());
346 })
347 .boxed()
348 }
349 ContextMenuItem::Separator => Empty::new()
350 .constrained()
351 .with_height(1.)
352 .contained()
353 .with_style(style.separator)
354 .boxed(),
355 }
356 }))
357 .contained()
358 .with_style(style.container)
359 .boxed()
360 })
361 .on_down_out(MouseButton::Left, |_, cx| cx.dispatch_action(Cancel))
362 .on_down_out(MouseButton::Right, |_, cx| cx.dispatch_action(Cancel))
363 }
364}