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