mouse_context_menu.rs

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