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::{DismissEvent, Pixels, Point, Subscription, View, ViewContext};
 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_x: Pixels,
 24        offset_y: Pixels,
 25    },
 26}
 27
 28pub struct MouseContextMenu {
 29    pub(crate) position: MenuPosition,
 30    pub(crate) context_menu: View<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: View<ui::ContextMenu>,
 49        cx: &mut ViewContext<Editor>,
 50    ) -> Option<Self> {
 51        let context_menu_focus = context_menu.focus_handle(cx);
 52        cx.focus(&context_menu_focus);
 53
 54        let _subscription = cx.subscribe(
 55            &context_menu,
 56            move |editor, _, _event: &DismissEvent, cx| {
 57                editor.mouse_context_menu.take();
 58                if context_menu_focus.contains_focused(cx) {
 59                    editor.focus(cx);
 60                }
 61            },
 62        );
 63
 64        let editor_snapshot = editor.snapshot(cx);
 65        let source_point = editor.to_pixel_point(source, &editor_snapshot, cx)?;
 66        let offset = position - source_point;
 67
 68        Some(Self {
 69            position: MenuPosition::PinnedToEditor {
 70                source,
 71                offset_x: offset.x,
 72                offset_y: offset.y,
 73            },
 74            context_menu,
 75            _subscription,
 76        })
 77    }
 78
 79    pub(crate) fn pinned_to_screen(
 80        position: Point<Pixels>,
 81        context_menu: View<ui::ContextMenu>,
 82        cx: &mut ViewContext<Editor>,
 83    ) -> Self {
 84        let context_menu_focus = context_menu.focus_handle(cx);
 85        cx.focus(&context_menu_focus);
 86
 87        let _subscription = cx.subscribe(
 88            &context_menu,
 89            move |editor, _, _event: &DismissEvent, cx| {
 90                editor.mouse_context_menu.take();
 91                if context_menu_focus.contains_focused(cx) {
 92                    editor.focus(cx);
 93                }
 94            },
 95        );
 96
 97        Self {
 98            position: MenuPosition::PinnedToScreen(position),
 99            context_menu,
100            _subscription,
101        }
102    }
103}
104
105fn display_ranges<'a>(
106    display_map: &'a DisplaySnapshot,
107    selections: &'a SelectionsCollection,
108) -> impl Iterator<Item = Range<DisplayPoint>> + 'a {
109    let pending = selections
110        .pending
111        .as_ref()
112        .map(|pending| &pending.selection);
113    selections
114        .disjoint
115        .iter()
116        .chain(pending)
117        .map(move |s| s.start.to_display_point(display_map)..s.end.to_display_point(display_map))
118}
119
120pub fn deploy_context_menu(
121    editor: &mut Editor,
122    position: Point<Pixels>,
123    point: DisplayPoint,
124    cx: &mut ViewContext<Editor>,
125) {
126    if !editor.is_focused(cx) {
127        editor.focus(cx);
128    }
129
130    // Don't show context menu for inline editors
131    if editor.mode() != EditorMode::Full {
132        return;
133    }
134
135    let display_map = editor.selections.display_map(cx);
136    let source_anchor = display_map.display_point_to_anchor(point, text::Bias::Right);
137    let context_menu = if let Some(custom) = editor.custom_context_menu.take() {
138        let menu = custom(editor, point, cx);
139        editor.custom_context_menu = Some(custom);
140        let Some(menu) = menu else {
141            return;
142        };
143        menu
144    } else {
145        // Don't show the context menu if there isn't a project associated with this editor
146        if editor.project.is_none() {
147            return;
148        }
149
150        let display_map = editor.selections.display_map(cx);
151        let buffer = &editor.snapshot(cx).buffer_snapshot;
152        let anchor = buffer.anchor_before(point.to_point(&display_map));
153        if !display_ranges(&display_map, &editor.selections).any(|r| r.contains(&point)) {
154            // Move the cursor to the clicked location so that dispatched actions make sense
155            editor.change_selections(None, cx, |s| {
156                s.clear_disjoint();
157                s.set_pending_anchor_range(anchor..anchor, SelectMode::Character);
158            });
159        }
160
161        let focus = cx.focused();
162        let has_reveal_target = editor.target_file(cx).is_some();
163        let reveal_in_finder_label = if cfg!(target_os = "macos") {
164            "Reveal in Finder"
165        } else {
166            "Reveal in File Manager"
167        };
168        let has_selections = editor
169            .selections
170            .all::<PointUtf16>(cx)
171            .into_iter()
172            .any(|s| !s.is_empty());
173
174        ui::ContextMenu::build(cx, |menu, _cx| {
175            let builder = menu
176                .on_blur_subscription(Subscription::new(|| {}))
177                .action("Go to Definition", Box::new(GoToDefinition))
178                .action("Go to Declaration", Box::new(GoToDeclaration))
179                .action("Go to Type Definition", Box::new(GoToTypeDefinition))
180                .action("Go to Implementation", Box::new(GoToImplementation))
181                .action("Find All References", Box::new(FindAllReferences))
182                .separator()
183                .action("Rename Symbol", Box::new(Rename))
184                .action("Format Buffer", Box::new(Format))
185                .when(has_selections, |cx| {
186                    cx.action("Format Selections", Box::new(FormatSelections))
187                })
188                .action(
189                    "Code Actions",
190                    Box::new(ToggleCodeActions {
191                        deployed_from_indicator: None,
192                    }),
193                )
194                .separator()
195                .action("Cut", Box::new(Cut))
196                .action("Copy", Box::new(Copy))
197                .action("Paste", Box::new(Paste))
198                .separator()
199                .map(|builder| {
200                    if has_reveal_target {
201                        builder.action(reveal_in_finder_label, Box::new(RevealInFileManager))
202                    } else {
203                        builder
204                            .disabled_action(reveal_in_finder_label, Box::new(RevealInFileManager))
205                    }
206                })
207                .action("Open in Terminal", Box::new(OpenInTerminal))
208                .action("Copy Permalink", Box::new(CopyPermalinkToLine));
209            match focus {
210                Some(focus) => builder.context(focus),
211                None => builder,
212            }
213        })
214    };
215
216    editor.mouse_context_menu =
217        MouseContextMenu::pinned_to_editor(editor, source_anchor, position, context_menu, cx);
218    cx.notify();
219}
220
221#[cfg(test)]
222mod tests {
223    use super::*;
224    use crate::{editor_tests::init_test, test::editor_lsp_test_context::EditorLspTestContext};
225    use indoc::indoc;
226
227    #[gpui::test]
228    async fn test_mouse_context_menu(cx: &mut gpui::TestAppContext) {
229        init_test(cx, |_| {});
230
231        let mut cx = EditorLspTestContext::new_rust(
232            lsp::ServerCapabilities {
233                hover_provider: Some(lsp::HoverProviderCapability::Simple(true)),
234                ..Default::default()
235            },
236            cx,
237        )
238        .await;
239
240        cx.set_state(indoc! {"
241            fn teˇst() {
242                do_work();
243            }
244        "});
245        let point = cx.display_point(indoc! {"
246            fn test() {
247                do_wˇork();
248            }
249        "});
250        cx.editor(|editor, _app| assert!(editor.mouse_context_menu.is_none()));
251        cx.update_editor(|editor, cx| deploy_context_menu(editor, Default::default(), point, cx));
252
253        cx.assert_editor_state(indoc! {"
254            fn test() {
255                do_wˇork();
256            }
257        "});
258        cx.editor(|editor, _app| assert!(editor.mouse_context_menu.is_some()));
259    }
260}