mouse_context_menu.rs

  1use std::ops::Range;
  2
  3use crate::{
  4    selections_collection::SelectionsCollection, Copy, CopyPermalinkToLine, Cut, DisplayPoint,
  5    DisplaySnapshot, Editor, EditorMode, FindAllReferences, GoToDefinition, GoToImplementation,
  6    GoToTypeDefinition, Paste, Rename, RevealInFileManager, SelectMode, ToDisplayPoint,
  7    ToggleCodeActions,
  8};
  9use gpui::prelude::FluentBuilder;
 10use gpui::{DismissEvent, Pixels, Point, Subscription, View, ViewContext};
 11use workspace::OpenInTerminal;
 12
 13#[derive(Debug)]
 14pub enum MenuPosition {
 15    /// When the editor is scrolled, the context menu stays on the exact
 16    /// same position on the screen, never disappearing.
 17    PinnedToScreen(Point<Pixels>),
 18    /// When the editor is scrolled, the context menu follows the position it is associated with.
 19    /// Disappears when the position is no longer visible.
 20    PinnedToEditor {
 21        source: multi_buffer::Anchor,
 22        offset_x: Pixels,
 23        offset_y: Pixels,
 24    },
 25}
 26
 27pub struct MouseContextMenu {
 28    pub(crate) position: MenuPosition,
 29    pub(crate) context_menu: View<ui::ContextMenu>,
 30    _subscription: Subscription,
 31}
 32
 33impl std::fmt::Debug for MouseContextMenu {
 34    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 35        f.debug_struct("MouseContextMenu")
 36            .field("position", &self.position)
 37            .field("context_menu", &self.context_menu)
 38            .finish()
 39    }
 40}
 41
 42impl MouseContextMenu {
 43    pub(crate) fn pinned_to_editor(
 44        editor: &mut Editor,
 45        source: multi_buffer::Anchor,
 46        position: Point<Pixels>,
 47        context_menu: View<ui::ContextMenu>,
 48        cx: &mut ViewContext<Editor>,
 49    ) -> Option<Self> {
 50        let context_menu_focus = context_menu.focus_handle(cx);
 51        cx.focus(&context_menu_focus);
 52
 53        let _subscription = cx.subscribe(
 54            &context_menu,
 55            move |editor, _, _event: &DismissEvent, cx| {
 56                editor.mouse_context_menu.take();
 57                if context_menu_focus.contains_focused(cx) {
 58                    editor.focus(cx);
 59                }
 60            },
 61        );
 62
 63        let editor_snapshot = editor.snapshot(cx);
 64        let source_point = editor.to_pixel_point(source, &editor_snapshot, cx)?;
 65        let offset = position - source_point;
 66
 67        Some(Self {
 68            position: MenuPosition::PinnedToEditor {
 69                source,
 70                offset_x: offset.x,
 71                offset_y: offset.y,
 72            },
 73            context_menu,
 74            _subscription,
 75        })
 76    }
 77
 78    pub(crate) fn pinned_to_screen(
 79        position: Point<Pixels>,
 80        context_menu: View<ui::ContextMenu>,
 81        cx: &mut ViewContext<Editor>,
 82    ) -> Self {
 83        let context_menu_focus = context_menu.focus_handle(cx);
 84        cx.focus(&context_menu_focus);
 85
 86        let _subscription = cx.subscribe(
 87            &context_menu,
 88            move |editor, _, _event: &DismissEvent, cx| {
 89                editor.mouse_context_menu.take();
 90                if context_menu_focus.contains_focused(cx) {
 91                    editor.focus(cx);
 92                }
 93            },
 94        );
 95
 96        Self {
 97            position: MenuPosition::PinnedToScreen(position),
 98            context_menu,
 99            _subscription,
100        }
101    }
102}
103
104fn display_ranges<'a>(
105    display_map: &'a DisplaySnapshot,
106    selections: &'a SelectionsCollection,
107) -> impl Iterator<Item = Range<DisplayPoint>> + 'a {
108    let pending = selections
109        .pending
110        .as_ref()
111        .map(|pending| &pending.selection);
112    selections
113        .disjoint
114        .iter()
115        .chain(pending)
116        .map(move |s| s.start.to_display_point(&display_map)..s.end.to_display_point(&display_map))
117}
118
119pub fn deploy_context_menu(
120    editor: &mut Editor,
121    position: Point<Pixels>,
122    point: DisplayPoint,
123    cx: &mut ViewContext<Editor>,
124) {
125    if !editor.is_focused(cx) {
126        editor.focus(cx);
127    }
128
129    // Don't show context menu for inline editors
130    if editor.mode() != EditorMode::Full {
131        return;
132    }
133
134    let display_map = editor.selections.display_map(cx);
135    let source_anchor = display_map.display_point_to_anchor(point, text::Bias::Right);
136    let context_menu = if let Some(custom) = editor.custom_context_menu.take() {
137        let menu = custom(editor, point, cx);
138        editor.custom_context_menu = Some(custom);
139        let Some(menu) = menu else {
140            return;
141        };
142        menu
143    } else {
144        // Don't show the context menu if there isn't a project associated with this editor
145        if editor.project.is_none() {
146            return;
147        }
148
149        let display_map = editor.selections.display_map(cx);
150        let buffer = &editor.snapshot(cx).buffer_snapshot;
151        let anchor = buffer.anchor_before(point.to_point(&display_map));
152        if !display_ranges(&display_map, &editor.selections).any(|r| r.contains(&point)) {
153            // Move the cursor to the clicked location so that dispatched actions make sense
154            editor.change_selections(None, cx, |s| {
155                s.clear_disjoint();
156                s.set_pending_anchor_range(anchor..anchor, SelectMode::Character);
157            });
158        }
159
160        let focus = cx.focused();
161        ui::ContextMenu::build(cx, |menu, _cx| {
162            let builder = menu
163                .on_blur_subscription(Subscription::new(|| {}))
164                .action("Rename Symbol", Box::new(Rename))
165                .action("Go to Definition", Box::new(GoToDefinition))
166                .action("Go to Type Definition", Box::new(GoToTypeDefinition))
167                .action("Go to Implementation", Box::new(GoToImplementation))
168                .action("Find All References", Box::new(FindAllReferences))
169                .action(
170                    "Code Actions",
171                    Box::new(ToggleCodeActions {
172                        deployed_from_indicator: None,
173                    }),
174                )
175                .separator()
176                .action("Cut", Box::new(Cut))
177                .action("Copy", Box::new(Copy))
178                .action("Paste", Box::new(Paste))
179                .separator()
180                .when(cfg!(target_os = "macos"), |builder| {
181                    builder.action("Reveal in Finder", Box::new(RevealInFileManager))
182                })
183                .when(cfg!(not(target_os = "macos")), |builder| {
184                    builder.action("Reveal in File Manager", Box::new(RevealInFileManager))
185                })
186                .action("Open in Terminal", Box::new(OpenInTerminal))
187                .action("Copy Permalink", Box::new(CopyPermalinkToLine));
188            match focus {
189                Some(focus) => builder.context(focus),
190                None => builder,
191            }
192        })
193    };
194
195    editor.mouse_context_menu =
196        MouseContextMenu::pinned_to_editor(editor, source_anchor, position, context_menu, cx);
197    cx.notify();
198}
199
200#[cfg(test)]
201mod tests {
202    use super::*;
203    use crate::{editor_tests::init_test, test::editor_lsp_test_context::EditorLspTestContext};
204    use indoc::indoc;
205
206    #[gpui::test]
207    async fn test_mouse_context_menu(cx: &mut gpui::TestAppContext) {
208        init_test(cx, |_| {});
209
210        let mut cx = EditorLspTestContext::new_rust(
211            lsp::ServerCapabilities {
212                hover_provider: Some(lsp::HoverProviderCapability::Simple(true)),
213                ..Default::default()
214            },
215            cx,
216        )
217        .await;
218
219        cx.set_state(indoc! {"
220            fn teˇst() {
221                do_work();
222            }
223        "});
224        let point = cx.display_point(indoc! {"
225            fn test() {
226                do_wˇork();
227            }
228        "});
229        cx.editor(|editor, _app| assert!(editor.mouse_context_menu.is_none()));
230        cx.update_editor(|editor, cx| deploy_context_menu(editor, Default::default(), point, cx));
231
232        cx.assert_editor_state(indoc! {"
233            fn test() {
234                do_wˇork();
235            }
236        "});
237        cx.editor(|editor, _app| assert!(editor.mouse_context_menu.is_some()));
238    }
239}