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