1use crate::{
2 Copy, CopyAndTrim, CopyPermalinkToLine, Cut, DisplayPoint, DisplaySnapshot, Editor,
3 EvaluateSelectedText, FindAllReferences, GoToDeclaration, GoToDefinition, GoToImplementation,
4 GoToTypeDefinition, Paste, Rename, RevealInFileManager, SelectMode, SelectionEffects,
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(SelectionEffects::no_scroll(), 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 = window.is_action_available(&EvaluateSelectedText, cx);
203
204 ui::ContextMenu::build(window, cx, |menu, _window, _cx| {
205 let builder = menu
206 .on_blur_subscription(Subscription::new(|| {}))
207 .when(evaluate_selection && has_selections, |builder| {
208 builder
209 .action("Evaluate Selection", Box::new(EvaluateSelectedText))
210 .separator()
211 })
212 .action("Go to Definition", Box::new(GoToDefinition))
213 .action("Go to Declaration", Box::new(GoToDeclaration))
214 .action("Go to Type Definition", Box::new(GoToTypeDefinition))
215 .action("Go to Implementation", Box::new(GoToImplementation))
216 .action("Find All References", Box::new(FindAllReferences))
217 .separator()
218 .action("Rename Symbol", Box::new(Rename))
219 .action("Format Buffer", Box::new(Format))
220 .when(has_selections, |cx| {
221 cx.action("Format Selections", Box::new(FormatSelections))
222 })
223 .action(
224 "Show Code Actions",
225 Box::new(ToggleCodeActions {
226 deployed_from: None,
227 quick_launch: false,
228 }),
229 )
230 .separator()
231 .action("Cut", Box::new(Cut))
232 .action("Copy", Box::new(Copy))
233 .action("Copy and Trim", Box::new(CopyAndTrim))
234 .action("Paste", Box::new(Paste))
235 .separator()
236 .action_disabled_when(
237 !has_reveal_target,
238 if cfg!(target_os = "macos") {
239 "Reveal in Finder"
240 } else {
241 "Reveal in File Manager"
242 },
243 Box::new(RevealInFileManager),
244 )
245 .action_disabled_when(
246 !has_reveal_target,
247 "Open in Terminal",
248 Box::new(OpenInTerminal),
249 )
250 .action_disabled_when(
251 !has_git_repo,
252 "Copy Permalink",
253 Box::new(CopyPermalinkToLine),
254 );
255 match focus {
256 Some(focus) => builder.context(focus),
257 None => builder,
258 }
259 })
260 };
261
262 editor.mouse_context_menu = match position {
263 Some(position) => MouseContextMenu::pinned_to_editor(
264 editor,
265 source_anchor,
266 position,
267 context_menu,
268 window,
269 cx,
270 ),
271 None => {
272 let character_size = editor.character_dimensions(window);
273 let menu_position = MenuPosition::PinnedToEditor {
274 source: source_anchor,
275 offset: gpui::point(character_size.em_width, character_size.line_height),
276 };
277 Some(MouseContextMenu::new(
278 editor,
279 menu_position,
280 context_menu,
281 window,
282 cx,
283 ))
284 }
285 };
286 cx.notify();
287}
288
289#[cfg(test)]
290mod tests {
291 use super::*;
292 use crate::{editor_tests::init_test, test::editor_lsp_test_context::EditorLspTestContext};
293 use indoc::indoc;
294
295 #[gpui::test]
296 async fn test_mouse_context_menu(cx: &mut gpui::TestAppContext) {
297 init_test(cx, |_| {});
298
299 let mut cx = EditorLspTestContext::new_rust(
300 lsp::ServerCapabilities {
301 hover_provider: Some(lsp::HoverProviderCapability::Simple(true)),
302 ..Default::default()
303 },
304 cx,
305 )
306 .await;
307
308 cx.set_state(indoc! {"
309 fn teˇst() {
310 do_work();
311 }
312 "});
313 let point = cx.display_point(indoc! {"
314 fn test() {
315 do_wˇork();
316 }
317 "});
318 cx.editor(|editor, _window, _app| assert!(editor.mouse_context_menu.is_none()));
319 cx.update_editor(|editor, window, cx| {
320 deploy_context_menu(editor, Some(Default::default()), point, window, cx)
321 });
322
323 cx.assert_editor_state(indoc! {"
324 fn test() {
325 do_wˇork();
326 }
327 "});
328 cx.editor(|editor, _window, _app| assert!(editor.mouse_context_menu.is_some()));
329 }
330}