right_click_menu.rs

  1use std::{cell::RefCell, rc::Rc};
  2
  3use gpui::{
  4    AnyElement, App, Bounds, Corner, DismissEvent, DispatchPhase, Element, ElementId, Entity,
  5    Focusable as _, GlobalElementId, Hitbox, HitboxBehavior, InteractiveElement, IntoElement,
  6    LayoutId, ManagedView, MouseButton, MouseDownEvent, ParentElement, Pixels, Point, Window,
  7    anchored, 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 source_location(&self) -> Option<&'static core::panic::Location<'static>> {
120        None
121    }
122
123    fn request_layout(
124        &mut self,
125        id: Option<&GlobalElementId>,
126        _inspector_id: Option<&gpui::InspectorElementId>,
127        window: &mut Window,
128        cx: &mut App,
129    ) -> (gpui::LayoutId, Self::RequestLayoutState) {
130        self.with_element_state(
131            id.unwrap(),
132            window,
133            cx,
134            |this, element_state, window, cx| {
135                let mut menu_layout_id = None;
136
137                let menu_element = element_state.menu.borrow_mut().as_mut().map(|menu| {
138                    let mut anchored = anchored().snap_to_window_with_margin(px(8.));
139                    if let Some(anchor) = this.anchor {
140                        anchored = anchored.anchor(anchor);
141                    }
142                    anchored = anchored.position(*element_state.position.borrow());
143
144                    let mut element = deferred(anchored.child(div().occlude().child(menu.clone())))
145                        .with_priority(1)
146                        .into_any();
147
148                    menu_layout_id = Some(element.request_layout(window, cx));
149                    element
150                });
151
152                let mut child_element = this
153                    .child_builder
154                    .take()
155                    .map(|child_builder| (child_builder)(element_state.menu.borrow().is_some()));
156
157                let child_layout_id = child_element
158                    .as_mut()
159                    .map(|child_element| child_element.request_layout(window, cx));
160
161                let layout_id = window.request_layout(
162                    gpui::Style::default(),
163                    menu_layout_id.into_iter().chain(child_layout_id),
164                    cx,
165                );
166
167                (
168                    layout_id,
169                    RequestLayoutState {
170                        child_element,
171                        child_layout_id,
172                        menu_element,
173                    },
174                )
175            },
176        )
177    }
178
179    fn prepaint(
180        &mut self,
181        _id: Option<&GlobalElementId>,
182        _inspector_id: Option<&gpui::InspectorElementId>,
183        bounds: Bounds<Pixels>,
184        request_layout: &mut Self::RequestLayoutState,
185        window: &mut Window,
186        cx: &mut App,
187    ) -> PrepaintState {
188        let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal);
189
190        if let Some(child) = request_layout.child_element.as_mut() {
191            child.prepaint(window, cx);
192        }
193
194        if let Some(menu) = request_layout.menu_element.as_mut() {
195            menu.prepaint(window, cx);
196        }
197
198        PrepaintState {
199            hitbox,
200            child_bounds: request_layout
201                .child_layout_id
202                .map(|layout_id| window.layout_bounds(layout_id)),
203        }
204    }
205
206    fn paint(
207        &mut self,
208        id: Option<&GlobalElementId>,
209        _inspector_id: Option<&gpui::InspectorElementId>,
210        _bounds: Bounds<gpui::Pixels>,
211        request_layout: &mut Self::RequestLayoutState,
212        prepaint_state: &mut Self::PrepaintState,
213        window: &mut Window,
214        cx: &mut App,
215    ) {
216        self.with_element_state(
217            id.unwrap(),
218            window,
219            cx,
220            |this, element_state, window, cx| {
221                if let Some(mut child) = request_layout.child_element.take() {
222                    child.paint(window, cx);
223                }
224
225                if let Some(mut menu) = request_layout.menu_element.take() {
226                    menu.paint(window, cx);
227                    return;
228                }
229
230                let Some(builder) = this.menu_builder.take() else {
231                    return;
232                };
233
234                let attach = this.attach;
235                let menu = element_state.menu.clone();
236                let position = element_state.position.clone();
237                let child_bounds = prepaint_state.child_bounds;
238
239                let hitbox_id = prepaint_state.hitbox.id;
240                window.on_mouse_event(move |event: &MouseDownEvent, phase, window, cx| {
241                    if phase == DispatchPhase::Bubble
242                        && event.button == MouseButton::Right
243                        && hitbox_id.is_hovered(window)
244                    {
245                        cx.stop_propagation();
246                        window.prevent_default();
247
248                        let new_menu = (builder)(window, cx);
249                        let menu2 = menu.clone();
250                        let previous_focus_handle = window.focused(cx);
251
252                        window
253                            .subscribe(&new_menu, cx, move |modal, _: &DismissEvent, window, cx| {
254                                if modal.focus_handle(cx).contains_focused(window, cx) {
255                                    if let Some(previous_focus_handle) =
256                                        previous_focus_handle.as_ref()
257                                    {
258                                        window.focus(previous_focus_handle);
259                                    }
260                                }
261                                *menu2.borrow_mut() = None;
262                                window.refresh();
263                            })
264                            .detach();
265                        window.focus(&new_menu.focus_handle(cx));
266                        *menu.borrow_mut() = Some(new_menu);
267                        *position.borrow_mut() = if let Some(child_bounds) = child_bounds {
268                            if let Some(attach) = attach {
269                                child_bounds.corner(attach)
270                            } else {
271                                window.mouse_position()
272                            }
273                        } else {
274                            window.mouse_position()
275                        };
276                        window.refresh();
277                    }
278                });
279            },
280        )
281    }
282}
283
284impl<M: ManagedView> IntoElement for RightClickMenu<M> {
285    type Element = Self;
286
287    fn into_element(self) -> Self::Element {
288        self
289    }
290}