mouse_context_menu.rs

  1use crate::{
  2    Copy, CopyAndTrim, CopyPermalinkToLine, Cut, DisplayPoint, DisplaySnapshot, Editor,
  3    EvaluateSelectedText, FindAllReferences, GoToDeclaration, GoToDefinition, GoToImplementation,
  4    GoToTypeDefinition, Paste, Rename, RevealInFileManager, RunToCursor, SelectMode,
  5    SelectionEffects, SelectionExt, ToDisplayPoint, ToggleCodeActions,
  6    actions::{Format, FormatSelections},
  7    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    _dismiss_subscription: Subscription,
 32    _cursor_move_subscription: Subscription,
 33}
 34
 35impl std::fmt::Debug for MouseContextMenu {
 36    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 37        f.debug_struct("MouseContextMenu")
 38            .field("position", &self.position)
 39            .field("context_menu", &self.context_menu)
 40            .finish()
 41    }
 42}
 43
 44impl MouseContextMenu {
 45    pub(crate) fn pinned_to_editor(
 46        editor: &mut Editor,
 47        source: multi_buffer::Anchor,
 48        position: Point<Pixels>,
 49        context_menu: Entity<ui::ContextMenu>,
 50        window: &mut Window,
 51        cx: &mut Context<Editor>,
 52    ) -> Option<Self> {
 53        let editor_snapshot = editor.snapshot(window, cx);
 54        let content_origin = editor.last_bounds?.origin
 55            + Point {
 56                x: editor.gutter_dimensions.width,
 57                y: Pixels::ZERO,
 58            };
 59        let source_position = editor.to_pixel_point(source, &editor_snapshot, window)?;
 60        let menu_position = MenuPosition::PinnedToEditor {
 61            source,
 62            offset: position - (source_position + content_origin),
 63        };
 64        Some(MouseContextMenu::new(
 65            editor,
 66            menu_position,
 67            context_menu,
 68            window,
 69            cx,
 70        ))
 71    }
 72
 73    pub(crate) fn new(
 74        editor: &Editor,
 75        position: MenuPosition,
 76        context_menu: Entity<ui::ContextMenu>,
 77        window: &mut Window,
 78        cx: &mut Context<Editor>,
 79    ) -> Self {
 80        let context_menu_focus = context_menu.focus_handle(cx);
 81        window.focus(&context_menu_focus);
 82
 83        let _dismiss_subscription = cx.subscribe_in(&context_menu, window, {
 84            let context_menu_focus = context_menu_focus.clone();
 85            move |editor, _, _event: &DismissEvent, window, cx| {
 86                editor.mouse_context_menu.take();
 87                if context_menu_focus.contains_focused(window, cx) {
 88                    window.focus(&editor.focus_handle(cx));
 89                }
 90            }
 91        });
 92
 93        let selection_init = editor.selections.newest_anchor().clone();
 94
 95        let _cursor_move_subscription = cx.subscribe_in(
 96            &cx.entity(),
 97            window,
 98            move |editor, _, event: &crate::EditorEvent, window, cx| {
 99                let crate::EditorEvent::SelectionsChanged { local: true } = event else {
100                    return;
101                };
102                let display_snapshot = &editor
103                    .display_map
104                    .update(cx, |display_map, cx| display_map.snapshot(cx));
105                let selection_init_range = selection_init.display_range(display_snapshot);
106                let selection_now_range = editor
107                    .selections
108                    .newest_anchor()
109                    .display_range(display_snapshot);
110                if selection_now_range == selection_init_range {
111                    return;
112                }
113                editor.mouse_context_menu.take();
114                if context_menu_focus.contains_focused(window, cx) {
115                    window.focus(&editor.focus_handle(cx));
116                }
117            },
118        );
119
120        Self {
121            position,
122            context_menu,
123            _dismiss_subscription,
124            _cursor_move_subscription,
125        }
126    }
127}
128
129fn display_ranges<'a>(
130    display_map: &'a DisplaySnapshot,
131    selections: &'a SelectionsCollection,
132) -> impl Iterator<Item = Range<DisplayPoint>> + 'a {
133    let pending = selections.pending_anchor();
134    selections
135        .disjoint_anchors()
136        .iter()
137        .chain(pending)
138        .map(move |s| s.start.to_display_point(display_map)..s.end.to_display_point(display_map))
139}
140
141pub fn deploy_context_menu(
142    editor: &mut Editor,
143    position: Option<Point<Pixels>>,
144    point: DisplayPoint,
145    window: &mut Window,
146    cx: &mut Context<Editor>,
147) {
148    if !editor.is_focused(window) {
149        window.focus(&editor.focus_handle(cx));
150    }
151
152    // Don't show context menu for inline editors
153    if !editor.mode().is_full() {
154        return;
155    }
156
157    let display_map = editor.display_snapshot(cx);
158    let source_anchor = display_map.display_point_to_anchor(point, text::Bias::Right);
159    let context_menu = if let Some(custom) = editor.custom_context_menu.take() {
160        let menu = custom(editor, point, window, cx);
161        editor.custom_context_menu = Some(custom);
162        let Some(menu) = menu else {
163            return;
164        };
165        menu
166    } else {
167        // Don't show the context menu if there isn't a project associated with this editor
168        let Some(project) = editor.project.clone() else {
169            return;
170        };
171
172        let snapshot = editor.snapshot(window, cx);
173        let display_map = editor.display_snapshot(cx);
174        let buffer = snapshot.buffer_snapshot();
175        let anchor = buffer.anchor_before(point.to_point(&display_map));
176        if !display_ranges(&display_map, &editor.selections).any(|r| r.contains(&point)) {
177            // Move the cursor to the clicked location so that dispatched actions make sense
178            editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
179                s.clear_disjoint();
180                s.set_pending_anchor_range(anchor..anchor, SelectMode::Character);
181            });
182        }
183
184        let focus = window.focused(cx);
185        let has_reveal_target = editor.target_file(cx).is_some();
186        let has_selections = editor
187            .selections
188            .all::<PointUtf16>(&display_map)
189            .into_iter()
190            .any(|s| !s.is_empty());
191        let has_git_repo = buffer
192            .buffer_id_for_anchor(anchor)
193            .is_some_and(|buffer_id| {
194                project
195                    .read(cx)
196                    .git_store()
197                    .read(cx)
198                    .repository_and_path_for_buffer_id(buffer_id, cx)
199                    .is_some()
200            });
201
202        let evaluate_selection = window.is_action_available(&EvaluateSelectedText, cx);
203        let run_to_cursor = window.is_action_available(&RunToCursor, cx);
204
205        ui::ContextMenu::build(window, cx, |menu, _window, _cx| {
206            let builder = menu
207                .on_blur_subscription(Subscription::new(|| {}))
208                .when(run_to_cursor, |builder| {
209                    builder.action("Run to Cursor", Box::new(RunToCursor))
210                })
211                .when(evaluate_selection && has_selections, |builder| {
212                    builder.action("Evaluate Selection", Box::new(EvaluateSelectedText))
213                })
214                .when(
215                    run_to_cursor || (evaluate_selection && has_selections),
216                    |builder| builder.separator(),
217                )
218                .action("Go to Definition", Box::new(GoToDefinition))
219                .action("Go to Declaration", Box::new(GoToDeclaration))
220                .action("Go to Type Definition", Box::new(GoToTypeDefinition))
221                .action("Go to Implementation", Box::new(GoToImplementation))
222                .action("Find All References", Box::new(FindAllReferences))
223                .separator()
224                .action("Rename Symbol", Box::new(Rename))
225                .action("Format Buffer", Box::new(Format))
226                .when(has_selections, |cx| {
227                    cx.action("Format Selections", Box::new(FormatSelections))
228                })
229                .action(
230                    "Show Code Actions",
231                    Box::new(ToggleCodeActions {
232                        deployed_from: None,
233                        quick_launch: false,
234                    }),
235                )
236                .separator()
237                .action("Cut", Box::new(Cut))
238                .action("Copy", Box::new(Copy))
239                .action("Copy and Trim", Box::new(CopyAndTrim))
240                .action("Paste", Box::new(Paste))
241                .separator()
242                .action_disabled_when(
243                    !has_reveal_target,
244                    if cfg!(target_os = "macos") {
245                        "Reveal in Finder"
246                    } else {
247                        "Reveal in File Manager"
248                    },
249                    Box::new(RevealInFileManager),
250                )
251                .action_disabled_when(
252                    !has_reveal_target,
253                    "Open in Terminal",
254                    Box::new(OpenInTerminal),
255                )
256                .action_disabled_when(
257                    !has_git_repo,
258                    "Copy Permalink",
259                    Box::new(CopyPermalinkToLine),
260                );
261            match focus {
262                Some(focus) => builder.context(focus),
263                None => builder,
264            }
265        })
266    };
267
268    editor.mouse_context_menu = match position {
269        Some(position) => MouseContextMenu::pinned_to_editor(
270            editor,
271            source_anchor,
272            position,
273            context_menu,
274            window,
275            cx,
276        ),
277        None => {
278            let character_size = editor.character_dimensions(window);
279            let menu_position = MenuPosition::PinnedToEditor {
280                source: source_anchor,
281                offset: gpui::point(character_size.em_width, character_size.line_height),
282            };
283            Some(MouseContextMenu::new(
284                editor,
285                menu_position,
286                context_menu,
287                window,
288                cx,
289            ))
290        }
291    };
292    cx.notify();
293}
294
295#[cfg(test)]
296mod tests {
297    use super::*;
298    use crate::{editor_tests::init_test, test::editor_lsp_test_context::EditorLspTestContext};
299    use indoc::indoc;
300
301    #[gpui::test]
302    async fn test_mouse_context_menu(cx: &mut gpui::TestAppContext) {
303        init_test(cx, |_| {});
304
305        let mut cx = EditorLspTestContext::new_rust(
306            lsp::ServerCapabilities {
307                hover_provider: Some(lsp::HoverProviderCapability::Simple(true)),
308                ..Default::default()
309            },
310            cx,
311        )
312        .await;
313
314        cx.set_state(indoc! {"
315            fn teˇst() {
316                do_work();
317            }
318        "});
319        let point = cx.display_point(indoc! {"
320            fn test() {
321                do_wˇork();
322            }
323        "});
324        cx.editor(|editor, _window, _app| assert!(editor.mouse_context_menu.is_none()));
325        cx.update_editor(|editor, window, cx| {
326            deploy_context_menu(editor, Some(Default::default()), point, window, cx)
327        });
328
329        cx.assert_editor_state(indoc! {"
330            fn test() {
331                do_wˇork();
332            }
333        "});
334        cx.editor(|editor, _window, _app| assert!(editor.mouse_context_menu.is_some()));
335    }
336}