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
 13pub struct MouseContextMenu {
 14    pub(crate) position: Point<Pixels>,
 15    pub(crate) context_menu: View<ui::ContextMenu>,
 16    _subscription: Subscription,
 17}
 18
 19impl MouseContextMenu {
 20    pub(crate) fn new(
 21        position: Point<Pixels>,
 22        context_menu: View<ui::ContextMenu>,
 23        cx: &mut ViewContext<Editor>,
 24    ) -> Self {
 25        let context_menu_focus = context_menu.focus_handle(cx);
 26        cx.focus(&context_menu_focus);
 27
 28        let _subscription =
 29            cx.subscribe(&context_menu, move |this, _, _event: &DismissEvent, cx| {
 30                this.mouse_context_menu.take();
 31                if context_menu_focus.contains_focused(cx) {
 32                    this.focus(cx);
 33                }
 34            });
 35
 36        Self {
 37            position,
 38            context_menu,
 39            _subscription,
 40        }
 41    }
 42}
 43
 44fn display_ranges<'a>(
 45    display_map: &'a DisplaySnapshot,
 46    selections: &'a SelectionsCollection,
 47) -> impl Iterator<Item = Range<DisplayPoint>> + 'a {
 48    let pending = selections
 49        .pending
 50        .as_ref()
 51        .map(|pending| &pending.selection);
 52    selections
 53        .disjoint
 54        .iter()
 55        .chain(pending)
 56        .map(move |s| s.start.to_display_point(&display_map)..s.end.to_display_point(&display_map))
 57}
 58
 59pub fn deploy_context_menu(
 60    editor: &mut Editor,
 61    position: Point<Pixels>,
 62    point: DisplayPoint,
 63    cx: &mut ViewContext<Editor>,
 64) {
 65    if !editor.is_focused(cx) {
 66        editor.focus(cx);
 67    }
 68
 69    // Don't show context menu for inline editors
 70    if editor.mode() != EditorMode::Full {
 71        return;
 72    }
 73
 74    let context_menu = if let Some(custom) = editor.custom_context_menu.take() {
 75        let menu = custom(editor, point, cx);
 76        editor.custom_context_menu = Some(custom);
 77        let Some(menu) = menu else {
 78            return;
 79        };
 80        menu
 81    } else {
 82        // Don't show the context menu if there isn't a project associated with this editor
 83        if editor.project.is_none() {
 84            return;
 85        }
 86
 87        let display_map = editor.selections.display_map(cx);
 88        let buffer = &editor.snapshot(cx).buffer_snapshot;
 89        let anchor = buffer.anchor_before(point.to_point(&display_map));
 90        if !display_ranges(&display_map, &editor.selections).any(|r| r.contains(&point)) {
 91            // Move the cursor to the clicked location so that dispatched actions make sense
 92            editor.change_selections(None, cx, |s| {
 93                s.clear_disjoint();
 94                s.set_pending_anchor_range(anchor..anchor, SelectMode::Character);
 95            });
 96        }
 97
 98        let focus = cx.focused();
 99        ui::ContextMenu::build(cx, |menu, _cx| {
100            let builder = menu
101                .action("Rename Symbol", Box::new(Rename))
102                .action("Go to Definition", Box::new(GoToDefinition))
103                .action("Go to Type Definition", Box::new(GoToTypeDefinition))
104                .action("Go to Implementation", Box::new(GoToImplementation))
105                .action("Find All References", Box::new(FindAllReferences))
106                .action(
107                    "Code Actions",
108                    Box::new(ToggleCodeActions {
109                        deployed_from_indicator: None,
110                    }),
111                )
112                .separator()
113                .action("Cut", Box::new(Cut))
114                .action("Copy", Box::new(Copy))
115                .action("Paste", Box::new(Paste))
116                .separator()
117                .when(cfg!(target_os = "macos"), |builder| {
118                    builder.action("Reveal in Finder", Box::new(RevealInFileManager))
119                })
120                .when(cfg!(not(target_os = "macos")), |builder| {
121                    builder.action("Reveal in File Manager", Box::new(RevealInFileManager))
122                })
123                .action("Open in Terminal", Box::new(OpenInTerminal))
124                .action("Copy Permalink", Box::new(CopyPermalinkToLine));
125            match focus {
126                Some(focus) => builder.context(focus),
127                None => builder,
128            }
129        })
130    };
131    let mouse_context_menu = MouseContextMenu::new(position, context_menu, cx);
132    editor.mouse_context_menu = Some(mouse_context_menu);
133    cx.notify();
134}
135
136#[cfg(test)]
137mod tests {
138    use super::*;
139    use crate::{editor_tests::init_test, test::editor_lsp_test_context::EditorLspTestContext};
140    use indoc::indoc;
141
142    #[gpui::test]
143    async fn test_mouse_context_menu(cx: &mut gpui::TestAppContext) {
144        init_test(cx, |_| {});
145
146        let mut cx = EditorLspTestContext::new_rust(
147            lsp::ServerCapabilities {
148                hover_provider: Some(lsp::HoverProviderCapability::Simple(true)),
149                ..Default::default()
150            },
151            cx,
152        )
153        .await;
154
155        cx.set_state(indoc! {"
156            fn teˇst() {
157                do_work();
158            }
159        "});
160        let point = cx.display_point(indoc! {"
161            fn test() {
162                do_wˇork();
163            }
164        "});
165        cx.editor(|editor, _app| assert!(editor.mouse_context_menu.is_none()));
166        cx.update_editor(|editor, cx| deploy_context_menu(editor, Default::default(), point, cx));
167
168        cx.assert_editor_state(indoc! {"
169            fn test() {
170                do_wˇork();
171            }
172        "});
173        cx.editor(|editor, _app| assert!(editor.mouse_context_menu.is_some()));
174    }
175}