mouse_context_menu.rs

  1use std::ops::Range;
  2
  3use crate::{
  4    actions::Format, selections_collection::SelectionsCollection, Copy, CopyPermalinkToLine, Cut,
  5    DisplayPoint, DisplaySnapshot, Editor, EditorMode, FindAllReferences, GoToDeclaration,
  6    GoToDefinition, GoToImplementation, GoToTypeDefinition, Paste, Rename, RevealInFileManager,
  7    SelectMode, ToDisplayPoint, 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("Go to Definition", Box::new(GoToDefinition))
165                .action("Go to Declaration", Box::new(GoToDeclaration))
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                .separator()
170                .action("Rename Symbol", Box::new(Rename))
171                .action("Format Buffer", Box::new(Format))
172                .action(
173                    "Code Actions",
174                    Box::new(ToggleCodeActions {
175                        deployed_from_indicator: None,
176                    }),
177                )
178                .separator()
179                .action("Cut", Box::new(Cut))
180                .action("Copy", Box::new(Copy))
181                .action("Paste", Box::new(Paste))
182                .separator()
183                .when(cfg!(target_os = "macos"), |builder| {
184                    builder.action("Reveal in Finder", Box::new(RevealInFileManager))
185                })
186                .when(cfg!(not(target_os = "macos")), |builder| {
187                    builder.action("Reveal in File Manager", Box::new(RevealInFileManager))
188                })
189                .action("Open in Terminal", Box::new(OpenInTerminal))
190                .action("Copy Permalink", Box::new(CopyPermalinkToLine));
191            match focus {
192                Some(focus) => builder.context(focus),
193                None => builder,
194            }
195        })
196    };
197
198    editor.mouse_context_menu =
199        MouseContextMenu::pinned_to_editor(editor, source_anchor, position, context_menu, cx);
200    cx.notify();
201}
202
203#[cfg(test)]
204mod tests {
205    use super::*;
206    use crate::{editor_tests::init_test, test::editor_lsp_test_context::EditorLspTestContext};
207    use indoc::indoc;
208
209    #[gpui::test]
210    async fn test_mouse_context_menu(cx: &mut gpui::TestAppContext) {
211        init_test(cx, |_| {});
212
213        let mut cx = EditorLspTestContext::new_rust(
214            lsp::ServerCapabilities {
215                hover_provider: Some(lsp::HoverProviderCapability::Simple(true)),
216                ..Default::default()
217            },
218            cx,
219        )
220        .await;
221
222        cx.set_state(indoc! {"
223            fn teˇst() {
224                do_work();
225            }
226        "});
227        let point = cx.display_point(indoc! {"
228            fn test() {
229                do_wˇork();
230            }
231        "});
232        cx.editor(|editor, _app| assert!(editor.mouse_context_menu.is_none()));
233        cx.update_editor(|editor, cx| deploy_context_menu(editor, Default::default(), point, cx));
234
235        cx.assert_editor_state(indoc! {"
236            fn test() {
237                do_wˇork();
238            }
239        "});
240        cx.editor(|editor, _app| assert!(editor.mouse_context_menu.is_some()));
241    }
242}