1use std::ops::Range;
2
3use crate::GoToDeclaration;
4use crate::{
5 selections_collection::SelectionsCollection, Copy, CopyPermalinkToLine, Cut, DisplayPoint,
6 DisplaySnapshot, Editor, EditorMode, FindAllReferences, GoToDefinition, GoToImplementation,
7 GoToTypeDefinition, Paste, Rename, RevealInFileManager, SelectMode, ToDisplayPoint,
8 ToggleCodeActions,
9};
10use gpui::prelude::FluentBuilder;
11use gpui::{DismissEvent, Pixels, Point, Subscription, View, ViewContext};
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 ui::ContextMenu::build(cx, |menu, _cx| {
163 let builder = menu
164 .on_blur_subscription(Subscription::new(|| {}))
165 .action("Rename Symbol", Box::new(Rename))
166 .action("Go to Definition", Box::new(GoToDefinition))
167 .action("Go to Declaration", Box::new(GoToDeclaration))
168 .action("Go to Type Definition", Box::new(GoToTypeDefinition))
169 .action("Go to Implementation", Box::new(GoToImplementation))
170 .action("Find All References", Box::new(FindAllReferences))
171 .action(
172 "Code Actions",
173 Box::new(ToggleCodeActions {
174 deployed_from_indicator: None,
175 }),
176 )
177 .separator()
178 .action("Cut", Box::new(Cut))
179 .action("Copy", Box::new(Copy))
180 .action("Paste", Box::new(Paste))
181 .separator()
182 .when(cfg!(target_os = "macos"), |builder| {
183 builder.action("Reveal in Finder", Box::new(RevealInFileManager))
184 })
185 .when(cfg!(not(target_os = "macos")), |builder| {
186 builder.action("Reveal in File Manager", Box::new(RevealInFileManager))
187 })
188 .action("Open in Terminal", Box::new(OpenInTerminal))
189 .action("Copy Permalink", Box::new(CopyPermalinkToLine));
190 match focus {
191 Some(focus) => builder.context(focus),
192 None => builder,
193 }
194 })
195 };
196
197 editor.mouse_context_menu =
198 MouseContextMenu::pinned_to_editor(editor, source_anchor, position, context_menu, cx);
199 cx.notify();
200}
201
202#[cfg(test)]
203mod tests {
204 use super::*;
205 use crate::{editor_tests::init_test, test::editor_lsp_test_context::EditorLspTestContext};
206 use indoc::indoc;
207
208 #[gpui::test]
209 async fn test_mouse_context_menu(cx: &mut gpui::TestAppContext) {
210 init_test(cx, |_| {});
211
212 let mut cx = EditorLspTestContext::new_rust(
213 lsp::ServerCapabilities {
214 hover_provider: Some(lsp::HoverProviderCapability::Simple(true)),
215 ..Default::default()
216 },
217 cx,
218 )
219 .await;
220
221 cx.set_state(indoc! {"
222 fn teˇst() {
223 do_work();
224 }
225 "});
226 let point = cx.display_point(indoc! {"
227 fn test() {
228 do_wˇork();
229 }
230 "});
231 cx.editor(|editor, _app| assert!(editor.mouse_context_menu.is_none()));
232 cx.update_editor(|editor, cx| deploy_context_menu(editor, Default::default(), point, cx));
233
234 cx.assert_editor_state(indoc! {"
235 fn test() {
236 do_wˇork();
237 }
238 "});
239 cx.editor(|editor, _app| assert!(editor.mouse_context_menu.is_some()));
240 }
241}