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