mouse_context_menu.rs

  1use crate::actions::FormatSelections;
  2use crate::{
  3    actions::Format, selections_collection::SelectionsCollection, Copy, CopyPermalinkToLine, Cut,
  4    DisplayPoint, DisplaySnapshot, Editor, EditorMode, FindAllReferences, GoToDeclaration,
  5    GoToDefinition, GoToImplementation, GoToTypeDefinition, Paste, Rename, RevealInFileManager,
  6    SelectMode, ToDisplayPoint, ToggleCodeActions,
  7};
  8use gpui::prelude::FluentBuilder;
  9use gpui::{Context, DismissEvent, Entity, Focusable as _, Pixels, Point, Subscription, Window};
 10use std::ops::Range;
 11use text::PointUtf16;
 12use workspace::OpenInTerminal;
 13
 14#[derive(Debug)]
 15pub enum MenuPosition {
 16    /// When the editor is scrolled, the context menu stays on the exact
 17    /// same position on the screen, never disappearing.
 18    PinnedToScreen(Point<Pixels>),
 19    /// When the editor is scrolled, the context menu follows the position it is associated with.
 20    /// Disappears when the position is no longer visible.
 21    PinnedToEditor {
 22        source: multi_buffer::Anchor,
 23        offset: Point<Pixels>,
 24    },
 25}
 26
 27pub struct MouseContextMenu {
 28    pub(crate) position: MenuPosition,
 29    pub(crate) context_menu: Entity<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: Entity<ui::ContextMenu>,
 48        window: &mut Window,
 49        cx: &mut Context<Editor>,
 50    ) -> Option<Self> {
 51        let editor_snapshot = editor.snapshot(window, cx);
 52        let content_origin = editor.last_bounds?.origin
 53            + Point {
 54                x: editor.gutter_dimensions.width,
 55                y: Pixels(0.0),
 56            };
 57        let source_position = editor.to_pixel_point(source, &editor_snapshot, window)?;
 58        let menu_position = MenuPosition::PinnedToEditor {
 59            source,
 60            offset: position - (source_position + content_origin),
 61        };
 62        return Some(MouseContextMenu::new(
 63            menu_position,
 64            context_menu,
 65            window,
 66            cx,
 67        ));
 68    }
 69
 70    pub(crate) fn new(
 71        position: MenuPosition,
 72        context_menu: Entity<ui::ContextMenu>,
 73        window: &mut Window,
 74        cx: &mut Context<Editor>,
 75    ) -> Self {
 76        let context_menu_focus = context_menu.focus_handle(cx);
 77        window.focus(&context_menu_focus);
 78
 79        let _subscription = cx.subscribe_in(
 80            &context_menu,
 81            window,
 82            move |editor, _, _event: &DismissEvent, window, cx| {
 83                editor.mouse_context_menu.take();
 84                if context_menu_focus.contains_focused(window, cx) {
 85                    window.focus(&editor.focus_handle(cx));
 86                }
 87            },
 88        );
 89
 90        Self {
 91            position,
 92            context_menu,
 93            _subscription,
 94        }
 95    }
 96}
 97
 98fn display_ranges<'a>(
 99    display_map: &'a DisplaySnapshot,
100    selections: &'a SelectionsCollection,
101) -> impl Iterator<Item = Range<DisplayPoint>> + 'a {
102    let pending = selections
103        .pending
104        .as_ref()
105        .map(|pending| &pending.selection);
106    selections
107        .disjoint
108        .iter()
109        .chain(pending)
110        .map(move |s| s.start.to_display_point(display_map)..s.end.to_display_point(display_map))
111}
112
113pub fn deploy_context_menu(
114    editor: &mut Editor,
115    position: Option<Point<Pixels>>,
116    point: DisplayPoint,
117    window: &mut Window,
118    cx: &mut Context<Editor>,
119) {
120    if !editor.is_focused(window) {
121        window.focus(&editor.focus_handle(cx));
122    }
123
124    // Don't show context menu for inline editors
125    if editor.mode() != EditorMode::Full {
126        return;
127    }
128
129    let display_map = editor.selections.display_map(cx);
130    let source_anchor = display_map.display_point_to_anchor(point, text::Bias::Right);
131    let context_menu = if let Some(custom) = editor.custom_context_menu.take() {
132        let menu = custom(editor, point, window, cx);
133        editor.custom_context_menu = Some(custom);
134        let Some(menu) = menu else {
135            return;
136        };
137        menu
138    } else {
139        // Don't show the context menu if there isn't a project associated with this editor
140        if editor.project.is_none() {
141            return;
142        }
143
144        let display_map = editor.selections.display_map(cx);
145        let buffer = &editor.snapshot(window, cx).buffer_snapshot;
146        let anchor = buffer.anchor_before(point.to_point(&display_map));
147        if !display_ranges(&display_map, &editor.selections).any(|r| r.contains(&point)) {
148            // Move the cursor to the clicked location so that dispatched actions make sense
149            editor.change_selections(None, window, cx, |s| {
150                s.clear_disjoint();
151                s.set_pending_anchor_range(anchor..anchor, SelectMode::Character);
152            });
153        }
154
155        let focus = window.focused(cx);
156        let has_reveal_target = editor.target_file(cx).is_some();
157        let has_selections = editor
158            .selections
159            .all::<PointUtf16>(cx)
160            .into_iter()
161            .any(|s| !s.is_empty());
162        let has_git_repo = editor.project.as_ref().map_or(false, |project| {
163            project.update(cx, |project, cx| {
164                project.get_first_worktree_root_repo(cx).is_some()
165            })
166        });
167
168        ui::ContextMenu::build(window, cx, |menu, _window, _cx| {
169            let builder = menu
170                .on_blur_subscription(Subscription::new(|| {}))
171                .action("Go to Definition", Box::new(GoToDefinition))
172                .action("Go to Declaration", Box::new(GoToDeclaration))
173                .action("Go to Type Definition", Box::new(GoToTypeDefinition))
174                .action("Go to Implementation", Box::new(GoToImplementation))
175                .action("Find All References", Box::new(FindAllReferences))
176                .separator()
177                .action("Rename Symbol", Box::new(Rename))
178                .action("Format Buffer", Box::new(Format))
179                .when(has_selections, |cx| {
180                    cx.action("Format Selections", Box::new(FormatSelections))
181                })
182                .action(
183                    "Code Actions",
184                    Box::new(ToggleCodeActions {
185                        deployed_from_indicator: None,
186                    }),
187                )
188                .separator()
189                .action("Cut", Box::new(Cut))
190                .action("Copy", Box::new(Copy))
191                .action("Paste", Box::new(Paste))
192                .separator()
193                .map(|builder| {
194                    let reveal_in_finder_label = if cfg!(target_os = "macos") {
195                        "Reveal in Finder"
196                    } else {
197                        "Reveal in File Manager"
198                    };
199                    const OPEN_IN_TERMINAL_LABEL: &str = "Open in Terminal";
200                    if has_reveal_target {
201                        builder
202                            .action(reveal_in_finder_label, Box::new(RevealInFileManager))
203                            .action(OPEN_IN_TERMINAL_LABEL, Box::new(OpenInTerminal))
204                    } else {
205                        builder
206                            .disabled_action(reveal_in_finder_label, Box::new(RevealInFileManager))
207                            .disabled_action(OPEN_IN_TERMINAL_LABEL, Box::new(OpenInTerminal))
208                    }
209                })
210                .map(|builder| {
211                    const COPY_PERMALINK_LABEL: &str = "Copy Permalink";
212                    if has_git_repo {
213                        builder.action(COPY_PERMALINK_LABEL, Box::new(CopyPermalinkToLine))
214                    } else {
215                        builder.disabled_action(COPY_PERMALINK_LABEL, Box::new(CopyPermalinkToLine))
216                    }
217                });
218            match focus {
219                Some(focus) => builder.context(focus),
220                None => builder,
221            }
222        })
223    };
224
225    editor.mouse_context_menu = match position {
226        Some(position) => MouseContextMenu::pinned_to_editor(
227            editor,
228            source_anchor,
229            position,
230            context_menu,
231            window,
232            cx,
233        ),
234        None => {
235            let character_size = editor.character_size(window);
236            let menu_position = MenuPosition::PinnedToEditor {
237                source: source_anchor,
238                offset: gpui::point(character_size.width, character_size.height),
239            };
240            Some(MouseContextMenu::new(
241                menu_position,
242                context_menu,
243                window,
244                cx,
245            ))
246        }
247    };
248    cx.notify();
249}
250
251#[cfg(test)]
252mod tests {
253    use super::*;
254    use crate::{editor_tests::init_test, test::editor_lsp_test_context::EditorLspTestContext};
255    use indoc::indoc;
256
257    #[gpui::test]
258    async fn test_mouse_context_menu(cx: &mut gpui::TestAppContext) {
259        init_test(cx, |_| {});
260
261        let mut cx = EditorLspTestContext::new_rust(
262            lsp::ServerCapabilities {
263                hover_provider: Some(lsp::HoverProviderCapability::Simple(true)),
264                ..Default::default()
265            },
266            cx,
267        )
268        .await;
269
270        cx.set_state(indoc! {"
271            fn teˇst() {
272                do_work();
273            }
274        "});
275        let point = cx.display_point(indoc! {"
276            fn test() {
277                do_wˇork();
278            }
279        "});
280        cx.editor(|editor, _window, _app| assert!(editor.mouse_context_menu.is_none()));
281        cx.update_editor(|editor, window, cx| {
282            deploy_context_menu(editor, Some(Default::default()), point, window, cx)
283        });
284
285        cx.assert_editor_state(indoc! {"
286            fn test() {
287                do_wˇork();
288            }
289        "});
290        cx.editor(|editor, _window, _app| assert!(editor.mouse_context_menu.is_some()));
291    }
292}