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