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::ZERO,
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.pending_anchor();
134 selections
135 .disjoint_anchors()
136 .iter()
137 .chain(pending)
138 .map(move |s| s.start.to_display_point(display_map)..s.end.to_display_point(display_map))
139}
140
141pub fn deploy_context_menu(
142 editor: &mut Editor,
143 position: Option<Point<Pixels>>,
144 point: DisplayPoint,
145 window: &mut Window,
146 cx: &mut Context<Editor>,
147) {
148 if !editor.is_focused(window) {
149 window.focus(&editor.focus_handle(cx));
150 }
151
152 // Don't show context menu for inline editors
153 if !editor.mode().is_full() {
154 return;
155 }
156
157 let display_map = editor.selections.display_map(cx);
158 let source_anchor = display_map.display_point_to_anchor(point, text::Bias::Right);
159 let context_menu = if let Some(custom) = editor.custom_context_menu.take() {
160 let menu = custom(editor, point, window, cx);
161 editor.custom_context_menu = Some(custom);
162 let Some(menu) = menu else {
163 return;
164 };
165 menu
166 } else {
167 // Don't show the context menu if there isn't a project associated with this editor
168 let Some(project) = editor.project.clone() else {
169 return;
170 };
171
172 let display_map = editor.selections.display_map(cx);
173 let buffer = &editor.snapshot(window, cx).buffer_snapshot;
174 let anchor = buffer.anchor_before(point.to_point(&display_map));
175 if !display_ranges(&display_map, &editor.selections).any(|r| r.contains(&point)) {
176 // Move the cursor to the clicked location so that dispatched actions make sense
177 editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
178 s.clear_disjoint();
179 s.set_pending_anchor_range(anchor..anchor, SelectMode::Character);
180 });
181 }
182
183 let focus = window.focused(cx);
184 let has_reveal_target = editor.target_file(cx).is_some();
185 let has_selections = editor
186 .selections
187 .all::<PointUtf16>(cx)
188 .into_iter()
189 .any(|s| !s.is_empty());
190 let has_git_repo = buffer
191 .buffer_id_for_anchor(anchor)
192 .is_some_and(|buffer_id| {
193 project
194 .read(cx)
195 .git_store()
196 .read(cx)
197 .repository_and_path_for_buffer_id(buffer_id, cx)
198 .is_some()
199 });
200
201 let evaluate_selection = window.is_action_available(&EvaluateSelectedText, cx);
202 let run_to_cursor = window.is_action_available(&RunToCursor, cx);
203
204 ui::ContextMenu::build(window, cx, |menu, _window, _cx| {
205 let builder = menu
206 .on_blur_subscription(Subscription::new(|| {}))
207 .when(run_to_cursor, |builder| {
208 builder.action("Run to Cursor", Box::new(RunToCursor))
209 })
210 .when(evaluate_selection && has_selections, |builder| {
211 builder.action("Evaluate Selection", Box::new(EvaluateSelectedText))
212 })
213 .when(
214 run_to_cursor || (evaluate_selection && has_selections),
215 |builder| builder.separator(),
216 )
217 .action("Go to Definition", Box::new(GoToDefinition))
218 .action("Go to Declaration", Box::new(GoToDeclaration))
219 .action("Go to Type Definition", Box::new(GoToTypeDefinition))
220 .action("Go to Implementation", Box::new(GoToImplementation))
221 .action("Find All References", Box::new(FindAllReferences))
222 .separator()
223 .action("Rename Symbol", Box::new(Rename))
224 .action("Format Buffer", Box::new(Format))
225 .when(has_selections, |cx| {
226 cx.action("Format Selections", Box::new(FormatSelections))
227 })
228 .action(
229 "Show Code Actions",
230 Box::new(ToggleCodeActions {
231 deployed_from: None,
232 quick_launch: false,
233 }),
234 )
235 .separator()
236 .action("Cut", Box::new(Cut))
237 .action("Copy", Box::new(Copy))
238 .action("Copy and Trim", Box::new(CopyAndTrim))
239 .action("Paste", Box::new(Paste))
240 .separator()
241 .action_disabled_when(
242 !has_reveal_target,
243 if cfg!(target_os = "macos") {
244 "Reveal in Finder"
245 } else {
246 "Reveal in File Manager"
247 },
248 Box::new(RevealInFileManager),
249 )
250 .action_disabled_when(
251 !has_reveal_target,
252 "Open in Terminal",
253 Box::new(OpenInTerminal),
254 )
255 .action_disabled_when(
256 !has_git_repo,
257 "Copy Permalink",
258 Box::new(CopyPermalinkToLine),
259 );
260 match focus {
261 Some(focus) => builder.context(focus),
262 None => builder,
263 }
264 })
265 };
266
267 editor.mouse_context_menu = match position {
268 Some(position) => MouseContextMenu::pinned_to_editor(
269 editor,
270 source_anchor,
271 position,
272 context_menu,
273 window,
274 cx,
275 ),
276 None => {
277 let character_size = editor.character_dimensions(window);
278 let menu_position = MenuPosition::PinnedToEditor {
279 source: source_anchor,
280 offset: gpui::point(character_size.em_width, character_size.line_height),
281 };
282 Some(MouseContextMenu::new(
283 editor,
284 menu_position,
285 context_menu,
286 window,
287 cx,
288 ))
289 }
290 };
291 cx.notify();
292}
293
294#[cfg(test)]
295mod tests {
296 use super::*;
297 use crate::{editor_tests::init_test, test::editor_lsp_test_context::EditorLspTestContext};
298 use indoc::indoc;
299
300 #[gpui::test]
301 async fn test_mouse_context_menu(cx: &mut gpui::TestAppContext) {
302 init_test(cx, |_| {});
303
304 let mut cx = EditorLspTestContext::new_rust(
305 lsp::ServerCapabilities {
306 hover_provider: Some(lsp::HoverProviderCapability::Simple(true)),
307 ..Default::default()
308 },
309 cx,
310 )
311 .await;
312
313 cx.set_state(indoc! {"
314 fn teˇst() {
315 do_work();
316 }
317 "});
318 let point = cx.display_point(indoc! {"
319 fn test() {
320 do_wˇork();
321 }
322 "});
323 cx.editor(|editor, _window, _app| assert!(editor.mouse_context_menu.is_none()));
324 cx.update_editor(|editor, window, cx| {
325 deploy_context_menu(editor, Some(Default::default()), point, window, cx)
326 });
327
328 cx.assert_editor_state(indoc! {"
329 fn test() {
330 do_wˇork();
331 }
332 "});
333 cx.editor(|editor, _window, _app| assert!(editor.mouse_context_menu.is_some()));
334 }
335}