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        if menu.is_none() {
 78            return;
 79        }
 80        menu.unwrap()
 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        if !display_ranges(&display_map, &editor.selections).any(|r| r.contains(&point)) {
 89            // Move the cursor to the clicked location so that dispatched actions make sense
 90            editor.change_selections(None, cx, |s| {
 91                s.clear_disjoint();
 92                s.set_pending_display_range(point..point, SelectMode::Character);
 93            });
 94        }
 95
 96        let focus = cx.focused();
 97        ui::ContextMenu::build(cx, |menu, _cx| {
 98            let builder = menu
 99                .action("Rename Symbol", Box::new(Rename))
100                .action("Go to Definition", Box::new(GoToDefinition))
101                .action("Go to Type Definition", Box::new(GoToTypeDefinition))
102                .action("Go to Implementation", Box::new(GoToImplementation))
103                .action("Find All References", Box::new(FindAllReferences))
104                .action(
105                    "Code Actions",
106                    Box::new(ToggleCodeActions {
107                        deployed_from_indicator: None,
108                    }),
109                )
110                .separator()
111                .action("Cut", Box::new(Cut))
112                .action("Copy", Box::new(Copy))
113                .action("Paste", Box::new(Paste))
114                .separator()
115                .when(cfg!(target_os = "macos"), |builder| {
116                    builder.action("Reveal in Finder", Box::new(RevealInFileManager))
117                })
118                .when(cfg!(not(target_os = "macos")), |builder| {
119                    builder.action("Reveal in File Manager", Box::new(RevealInFileManager))
120                })
121                .action("Open in Terminal", Box::new(OpenInTerminal))
122                .action("Copy Permalink", Box::new(CopyPermalinkToLine));
123            match focus {
124                Some(focus) => builder.context(focus),
125                None => builder,
126            }
127        })
128    };
129    let mouse_context_menu = MouseContextMenu::new(position, context_menu, cx);
130    editor.mouse_context_menu = Some(mouse_context_menu);
131    cx.notify();
132}
133
134#[cfg(test)]
135mod tests {
136    use super::*;
137    use crate::{editor_tests::init_test, test::editor_lsp_test_context::EditorLspTestContext};
138    use indoc::indoc;
139
140    #[gpui::test]
141    async fn test_mouse_context_menu(cx: &mut gpui::TestAppContext) {
142        init_test(cx, |_| {});
143
144        let mut cx = EditorLspTestContext::new_rust(
145            lsp::ServerCapabilities {
146                hover_provider: Some(lsp::HoverProviderCapability::Simple(true)),
147                ..Default::default()
148            },
149            cx,
150        )
151        .await;
152
153        cx.set_state(indoc! {"
154            fn teˇst() {
155                do_work();
156            }
157        "});
158        let point = cx.display_point(indoc! {"
159            fn test() {
160                do_wˇork();
161            }
162        "});
163        cx.editor(|editor, _app| assert!(editor.mouse_context_menu.is_none()));
164        cx.update_editor(|editor, cx| deploy_context_menu(editor, Default::default(), point, cx));
165
166        cx.assert_editor_state(indoc! {"
167            fn test() {
168                do_wˇork();
169            }
170        "});
171        cx.editor(|editor, _app| assert!(editor.mouse_context_menu.is_some()));
172    }
173}