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