1use std::ops::Range;
2
3use crate::{
4 selections_collection::SelectionsCollection, Copy, CopyPermalinkToLine, Cut, DisplayPoint,
5 DisplaySnapshot, Editor, EditorMode, FindAllReferences, GoToDefinition, GoToImplementation,
6 GoToTypeDefinition, Paste, Rename, RevealInFileManager, SelectMode, ToDisplayPoint,
7 ToggleCodeActions,
8};
9use gpui::prelude::FluentBuilder;
10use gpui::{DismissEvent, Pixels, Point, Subscription, View, ViewContext};
11use workspace::OpenInTerminal;
12
13pub enum MenuPosition {
14 /// When the editor is scrolled, the context menu stays on the exact
15 /// same position on the screen, never disappearing.
16 PinnedToScreen(Point<Pixels>),
17 /// When the editor is scrolled, the context menu follows the position it is associated with.
18 /// Disappears when the position is no longer visible.
19 PinnedToEditor {
20 source: multi_buffer::Anchor,
21 offset_x: Pixels,
22 offset_y: Pixels,
23 },
24}
25
26pub struct MouseContextMenu {
27 pub(crate) position: MenuPosition,
28 pub(crate) context_menu: View<ui::ContextMenu>,
29 _subscription: Subscription,
30}
31
32impl MouseContextMenu {
33 pub(crate) fn pinned_to_editor(
34 editor: &mut Editor,
35 source: multi_buffer::Anchor,
36 position: Point<Pixels>,
37 context_menu: View<ui::ContextMenu>,
38 cx: &mut ViewContext<Editor>,
39 ) -> Option<Self> {
40 let context_menu_focus = context_menu.focus_handle(cx);
41 cx.focus(&context_menu_focus);
42
43 let _subscription = cx.subscribe(
44 &context_menu,
45 move |editor, _, _event: &DismissEvent, cx| {
46 editor.mouse_context_menu.take();
47 if context_menu_focus.contains_focused(cx) {
48 editor.focus(cx);
49 }
50 },
51 );
52
53 let editor_snapshot = editor.snapshot(cx);
54 let source_point = editor.to_pixel_point(source, &editor_snapshot, cx)?;
55 let offset = position - source_point;
56
57 Some(Self {
58 position: MenuPosition::PinnedToEditor {
59 source,
60 offset_x: offset.x,
61 offset_y: offset.y,
62 },
63 context_menu,
64 _subscription,
65 })
66 }
67
68 pub(crate) fn pinned_to_screen(
69 position: Point<Pixels>,
70 context_menu: View<ui::ContextMenu>,
71 cx: &mut ViewContext<Editor>,
72 ) -> Self {
73 let context_menu_focus = context_menu.focus_handle(cx);
74 cx.focus(&context_menu_focus);
75
76 let _subscription = cx.subscribe(
77 &context_menu,
78 move |editor, _, _event: &DismissEvent, cx| {
79 editor.mouse_context_menu.take();
80 if context_menu_focus.contains_focused(cx) {
81 editor.focus(cx);
82 }
83 },
84 );
85
86 Self {
87 position: MenuPosition::PinnedToScreen(position),
88 context_menu,
89 _subscription,
90 }
91 }
92}
93
94fn display_ranges<'a>(
95 display_map: &'a DisplaySnapshot,
96 selections: &'a SelectionsCollection,
97) -> impl Iterator<Item = Range<DisplayPoint>> + 'a {
98 let pending = selections
99 .pending
100 .as_ref()
101 .map(|pending| &pending.selection);
102 selections
103 .disjoint
104 .iter()
105 .chain(pending)
106 .map(move |s| s.start.to_display_point(&display_map)..s.end.to_display_point(&display_map))
107}
108
109pub fn deploy_context_menu(
110 editor: &mut Editor,
111 position: Point<Pixels>,
112 point: DisplayPoint,
113 cx: &mut ViewContext<Editor>,
114) {
115 if !editor.is_focused(cx) {
116 editor.focus(cx);
117 }
118
119 // Don't show context menu for inline editors
120 if editor.mode() != EditorMode::Full {
121 return;
122 }
123
124 let display_map = editor.selections.display_map(cx);
125 let source_anchor = display_map.display_point_to_anchor(point, text::Bias::Right);
126 let context_menu = if let Some(custom) = editor.custom_context_menu.take() {
127 let menu = custom(editor, point, cx);
128 editor.custom_context_menu = Some(custom);
129 let Some(menu) = menu else {
130 return;
131 };
132 menu
133 } else {
134 // Don't show the context menu if there isn't a project associated with this editor
135 if editor.project.is_none() {
136 return;
137 }
138
139 let display_map = editor.selections.display_map(cx);
140 let buffer = &editor.snapshot(cx).buffer_snapshot;
141 let anchor = buffer.anchor_before(point.to_point(&display_map));
142 if !display_ranges(&display_map, &editor.selections).any(|r| r.contains(&point)) {
143 // Move the cursor to the clicked location so that dispatched actions make sense
144 editor.change_selections(None, cx, |s| {
145 s.clear_disjoint();
146 s.set_pending_anchor_range(anchor..anchor, SelectMode::Character);
147 });
148 }
149
150 let focus = cx.focused();
151 ui::ContextMenu::build(cx, |menu, _cx| {
152 let builder = menu
153 .on_blur_subscription(Subscription::new(|| {}))
154 .action("Rename Symbol", Box::new(Rename))
155 .action("Go to Definition", Box::new(GoToDefinition))
156 .action("Go to Type Definition", Box::new(GoToTypeDefinition))
157 .action("Go to Implementation", Box::new(GoToImplementation))
158 .action("Find All References", Box::new(FindAllReferences))
159 .action(
160 "Code Actions",
161 Box::new(ToggleCodeActions {
162 deployed_from_indicator: None,
163 }),
164 )
165 .separator()
166 .action("Cut", Box::new(Cut))
167 .action("Copy", Box::new(Copy))
168 .action("Paste", Box::new(Paste))
169 .separator()
170 .when(cfg!(target_os = "macos"), |builder| {
171 builder.action("Reveal in Finder", Box::new(RevealInFileManager))
172 })
173 .when(cfg!(not(target_os = "macos")), |builder| {
174 builder.action("Reveal in File Manager", Box::new(RevealInFileManager))
175 })
176 .action("Open in Terminal", Box::new(OpenInTerminal))
177 .action("Copy Permalink", Box::new(CopyPermalinkToLine));
178 match focus {
179 Some(focus) => builder.context(focus),
180 None => builder,
181 }
182 })
183 };
184
185 editor.mouse_context_menu =
186 MouseContextMenu::pinned_to_editor(editor, source_anchor, position, context_menu, cx);
187 cx.notify();
188}
189
190#[cfg(test)]
191mod tests {
192 use super::*;
193 use crate::{editor_tests::init_test, test::editor_lsp_test_context::EditorLspTestContext};
194 use indoc::indoc;
195
196 #[gpui::test]
197 async fn test_mouse_context_menu(cx: &mut gpui::TestAppContext) {
198 init_test(cx, |_| {});
199
200 let mut cx = EditorLspTestContext::new_rust(
201 lsp::ServerCapabilities {
202 hover_provider: Some(lsp::HoverProviderCapability::Simple(true)),
203 ..Default::default()
204 },
205 cx,
206 )
207 .await;
208
209 cx.set_state(indoc! {"
210 fn teˇst() {
211 do_work();
212 }
213 "});
214 let point = cx.display_point(indoc! {"
215 fn test() {
216 do_wˇork();
217 }
218 "});
219 cx.editor(|editor, _app| assert!(editor.mouse_context_menu.is_none()));
220 cx.update_editor(|editor, cx| deploy_context_menu(editor, Default::default(), point, cx));
221
222 cx.assert_editor_state(indoc! {"
223 fn test() {
224 do_wˇork();
225 }
226 "});
227 cx.editor(|editor, _app| assert!(editor.mouse_context_menu.is_some()));
228 }
229}