mouse_context_menu.rs

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