1use std::{cell::RefCell, rc::Rc};
2
3use gpui::{
4 AnyElement, App, Bounds, Corner, DismissEvent, DispatchPhase, Element, ElementId, Entity,
5 Focusable as _, GlobalElementId, Hitbox, InteractiveElement, IntoElement, LayoutId,
6 ManagedView, MouseButton, MouseDownEvent, ParentElement, Pixels, Point, Window, anchored,
7 deferred, div, px,
8};
9
10pub struct RightClickMenu<M: ManagedView> {
11 id: ElementId,
12 child_builder: Option<Box<dyn FnOnce(bool) -> AnyElement + 'static>>,
13 menu_builder: Option<Rc<dyn Fn(&mut Window, &mut App) -> Entity<M> + 'static>>,
14 anchor: Option<Corner>,
15 attach: Option<Corner>,
16}
17
18impl<M: ManagedView> RightClickMenu<M> {
19 pub fn menu(mut self, f: impl Fn(&mut Window, &mut App) -> Entity<M> + 'static) -> Self {
20 self.menu_builder = Some(Rc::new(f));
21 self
22 }
23
24 pub fn trigger<F, E>(mut self, e: F) -> Self
25 where
26 F: FnOnce(bool) -> E + 'static,
27 E: IntoElement + 'static,
28 {
29 self.child_builder = Some(Box::new(move |is_menu_active| {
30 e(is_menu_active).into_any_element()
31 }));
32 self
33 }
34
35 /// anchor defines which corner of the menu to anchor to the attachment point
36 /// (by default the cursor position, but see attach)
37 pub fn anchor(mut self, anchor: Corner) -> Self {
38 self.anchor = Some(anchor);
39 self
40 }
41
42 /// attach defines which corner of the handle to attach the menu's anchor to
43 pub fn attach(mut self, attach: Corner) -> Self {
44 self.attach = Some(attach);
45 self
46 }
47
48 fn with_element_state<R>(
49 &mut self,
50 global_id: &GlobalElementId,
51 window: &mut Window,
52 cx: &mut App,
53 f: impl FnOnce(&mut Self, &mut MenuHandleElementState<M>, &mut Window, &mut App) -> R,
54 ) -> R {
55 window.with_optional_element_state::<MenuHandleElementState<M>, _>(
56 Some(global_id),
57 |element_state, window| {
58 let mut element_state = element_state.unwrap().unwrap_or_default();
59 let result = f(self, &mut element_state, window, cx);
60 (result, Some(element_state))
61 },
62 )
63 }
64}
65
66/// Creates a [`RightClickMenu`]
67pub fn right_click_menu<M: ManagedView>(id: impl Into<ElementId>) -> RightClickMenu<M> {
68 RightClickMenu {
69 id: id.into(),
70 child_builder: None,
71 menu_builder: None,
72 anchor: None,
73 attach: None,
74 }
75}
76
77pub struct MenuHandleElementState<M> {
78 menu: Rc<RefCell<Option<Entity<M>>>>,
79 position: Rc<RefCell<Point<Pixels>>>,
80}
81
82impl<M> Clone for MenuHandleElementState<M> {
83 fn clone(&self) -> Self {
84 Self {
85 menu: Rc::clone(&self.menu),
86 position: Rc::clone(&self.position),
87 }
88 }
89}
90
91impl<M> Default for MenuHandleElementState<M> {
92 fn default() -> Self {
93 Self {
94 menu: Rc::default(),
95 position: Rc::default(),
96 }
97 }
98}
99
100pub struct RequestLayoutState {
101 child_layout_id: Option<LayoutId>,
102 child_element: Option<AnyElement>,
103 menu_element: Option<AnyElement>,
104}
105
106pub struct PrepaintState {
107 hitbox: Hitbox,
108 child_bounds: Option<Bounds<Pixels>>,
109}
110
111impl<M: ManagedView> Element for RightClickMenu<M> {
112 type RequestLayoutState = RequestLayoutState;
113 type PrepaintState = PrepaintState;
114
115 fn id(&self) -> Option<ElementId> {
116 Some(self.id.clone())
117 }
118
119 fn request_layout(
120 &mut self,
121 id: Option<&GlobalElementId>,
122 window: &mut Window,
123 cx: &mut App,
124 ) -> (gpui::LayoutId, Self::RequestLayoutState) {
125 self.with_element_state(
126 id.unwrap(),
127 window,
128 cx,
129 |this, element_state, window, cx| {
130 let mut menu_layout_id = None;
131
132 let menu_element = element_state.menu.borrow_mut().as_mut().map(|menu| {
133 let mut anchored = anchored().snap_to_window_with_margin(px(8.));
134 if let Some(anchor) = this.anchor {
135 anchored = anchored.anchor(anchor);
136 }
137 anchored = anchored.position(*element_state.position.borrow());
138
139 let mut element = deferred(anchored.child(div().occlude().child(menu.clone())))
140 .with_priority(1)
141 .into_any();
142
143 menu_layout_id = Some(element.request_layout(window, cx));
144 element
145 });
146
147 let mut child_element = this
148 .child_builder
149 .take()
150 .map(|child_builder| (child_builder)(element_state.menu.borrow().is_some()));
151
152 let child_layout_id = child_element
153 .as_mut()
154 .map(|child_element| child_element.request_layout(window, cx));
155
156 let layout_id = window.request_layout(
157 gpui::Style::default(),
158 menu_layout_id.into_iter().chain(child_layout_id),
159 cx,
160 );
161
162 (
163 layout_id,
164 RequestLayoutState {
165 child_element,
166 child_layout_id,
167 menu_element,
168 },
169 )
170 },
171 )
172 }
173
174 fn prepaint(
175 &mut self,
176 _id: Option<&GlobalElementId>,
177 bounds: Bounds<Pixels>,
178 request_layout: &mut Self::RequestLayoutState,
179 window: &mut Window,
180 cx: &mut App,
181 ) -> PrepaintState {
182 let hitbox = window.insert_hitbox(bounds, false);
183
184 if let Some(child) = request_layout.child_element.as_mut() {
185 child.prepaint(window, cx);
186 }
187
188 if let Some(menu) = request_layout.menu_element.as_mut() {
189 menu.prepaint(window, cx);
190 }
191
192 PrepaintState {
193 hitbox,
194 child_bounds: request_layout
195 .child_layout_id
196 .map(|layout_id| window.layout_bounds(layout_id)),
197 }
198 }
199
200 fn paint(
201 &mut self,
202 id: Option<&GlobalElementId>,
203 _bounds: Bounds<gpui::Pixels>,
204 request_layout: &mut Self::RequestLayoutState,
205 prepaint_state: &mut Self::PrepaintState,
206 window: &mut Window,
207 cx: &mut App,
208 ) {
209 self.with_element_state(
210 id.unwrap(),
211 window,
212 cx,
213 |this, element_state, window, cx| {
214 if let Some(mut child) = request_layout.child_element.take() {
215 child.paint(window, cx);
216 }
217
218 if let Some(mut menu) = request_layout.menu_element.take() {
219 menu.paint(window, cx);
220 return;
221 }
222
223 let Some(builder) = this.menu_builder.take() else {
224 return;
225 };
226
227 let attach = this.attach;
228 let menu = element_state.menu.clone();
229 let position = element_state.position.clone();
230 let child_bounds = prepaint_state.child_bounds;
231
232 let hitbox_id = prepaint_state.hitbox.id;
233 window.on_mouse_event(move |event: &MouseDownEvent, phase, window, cx| {
234 if phase == DispatchPhase::Bubble
235 && event.button == MouseButton::Right
236 && hitbox_id.is_hovered(window)
237 {
238 cx.stop_propagation();
239 window.prevent_default();
240
241 let new_menu = (builder)(window, cx);
242 let menu2 = menu.clone();
243 let previous_focus_handle = window.focused(cx);
244
245 window
246 .subscribe(&new_menu, cx, move |modal, _: &DismissEvent, window, cx| {
247 if modal.focus_handle(cx).contains_focused(window, cx) {
248 if let Some(previous_focus_handle) =
249 previous_focus_handle.as_ref()
250 {
251 window.focus(previous_focus_handle);
252 }
253 }
254 *menu2.borrow_mut() = None;
255 window.refresh();
256 })
257 .detach();
258 window.focus(&new_menu.focus_handle(cx));
259 *menu.borrow_mut() = Some(new_menu);
260 *position.borrow_mut() = if let Some(child_bounds) = child_bounds {
261 if let Some(attach) = attach {
262 child_bounds.corner(attach)
263 } else {
264 window.mouse_position()
265 }
266 } else {
267 window.mouse_position()
268 };
269 window.refresh();
270 }
271 });
272 },
273 )
274 }
275}
276
277impl<M: ManagedView> IntoElement for RightClickMenu<M> {
278 type Element = Self;
279
280 fn into_element(self) -> Self::Element {
281 self
282 }
283}