1use crate::actions::FormatSelections;
2use crate::{
3 actions::Format, selections_collection::SelectionsCollection, Copy, CopyPermalinkToLine, Cut,
4 DisplayPoint, DisplaySnapshot, Editor, EditorMode, FindAllReferences, GoToDeclaration,
5 GoToDefinition, GoToImplementation, GoToTypeDefinition, Paste, Rename, RevealInFileManager,
6 SelectMode, ToDisplayPoint, ToggleCodeActions,
7};
8use gpui::prelude::FluentBuilder;
9use gpui::{DismissEvent, Pixels, Point, Subscription, View, ViewContext};
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: View<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: View<ui::ContextMenu>,
48 cx: &mut ViewContext<Editor>,
49 ) -> Option<Self> {
50 let editor_snapshot = editor.snapshot(cx);
51 let content_origin = editor.last_bounds?.origin
52 + Point {
53 x: editor.gutter_dimensions.width,
54 y: Pixels(0.0),
55 };
56 let source_position = editor.to_pixel_point(source, &editor_snapshot, cx)?;
57 let menu_position = MenuPosition::PinnedToEditor {
58 source,
59 offset: position - (source_position + content_origin),
60 };
61 return Some(MouseContextMenu::new(menu_position, context_menu, cx));
62 }
63
64 pub(crate) fn new(
65 position: MenuPosition,
66 context_menu: View<ui::ContextMenu>,
67 cx: &mut ViewContext<Editor>,
68 ) -> Self {
69 let context_menu_focus = context_menu.focus_handle(cx);
70 cx.focus(&context_menu_focus);
71
72 let _subscription = cx.subscribe(
73 &context_menu,
74 move |editor, _, _event: &DismissEvent, cx| {
75 editor.mouse_context_menu.take();
76 if context_menu_focus.contains_focused(cx) {
77 editor.focus(cx);
78 }
79 },
80 );
81
82 Self {
83 position,
84 context_menu,
85 _subscription,
86 }
87 }
88}
89
90fn display_ranges<'a>(
91 display_map: &'a DisplaySnapshot,
92 selections: &'a SelectionsCollection,
93) -> impl Iterator<Item = Range<DisplayPoint>> + 'a {
94 let pending = selections
95 .pending
96 .as_ref()
97 .map(|pending| &pending.selection);
98 selections
99 .disjoint
100 .iter()
101 .chain(pending)
102 .map(move |s| s.start.to_display_point(display_map)..s.end.to_display_point(display_map))
103}
104
105pub fn deploy_context_menu(
106 editor: &mut Editor,
107 position: Option<Point<Pixels>>,
108 point: DisplayPoint,
109 cx: &mut ViewContext<Editor>,
110) {
111 if !editor.is_focused(cx) {
112 editor.focus(cx);
113 }
114
115 // Don't show context menu for inline editors
116 if editor.mode() != EditorMode::Full {
117 return;
118 }
119
120 let display_map = editor.selections.display_map(cx);
121 let source_anchor = display_map.display_point_to_anchor(point, text::Bias::Right);
122 let context_menu = if let Some(custom) = editor.custom_context_menu.take() {
123 let menu = custom(editor, point, cx);
124 editor.custom_context_menu = Some(custom);
125 let Some(menu) = menu else {
126 return;
127 };
128 menu
129 } else {
130 // Don't show the context menu if there isn't a project associated with this editor
131 if editor.project.is_none() {
132 return;
133 }
134
135 let display_map = editor.selections.display_map(cx);
136 let buffer = &editor.snapshot(cx).buffer_snapshot;
137 let anchor = buffer.anchor_before(point.to_point(&display_map));
138 if !display_ranges(&display_map, &editor.selections).any(|r| r.contains(&point)) {
139 // Move the cursor to the clicked location so that dispatched actions make sense
140 editor.change_selections(None, cx, |s| {
141 s.clear_disjoint();
142 s.set_pending_anchor_range(anchor..anchor, SelectMode::Character);
143 });
144 }
145
146 let focus = cx.focused();
147 let has_reveal_target = editor.target_file(cx).is_some();
148 let reveal_in_finder_label = if cfg!(target_os = "macos") {
149 "Reveal in Finder"
150 } else {
151 "Reveal in File Manager"
152 };
153 let has_selections = editor
154 .selections
155 .all::<PointUtf16>(cx)
156 .into_iter()
157 .any(|s| !s.is_empty());
158
159 ui::ContextMenu::build(cx, |menu, _cx| {
160 let builder = menu
161 .on_blur_subscription(Subscription::new(|| {}))
162 .action("Go to Definition", Box::new(GoToDefinition))
163 .action("Go to Declaration", Box::new(GoToDeclaration))
164 .action("Go to Type Definition", Box::new(GoToTypeDefinition))
165 .action("Go to Implementation", Box::new(GoToImplementation))
166 .action("Find All References", Box::new(FindAllReferences))
167 .separator()
168 .action("Rename Symbol", Box::new(Rename))
169 .action("Format Buffer", Box::new(Format))
170 .when(has_selections, |cx| {
171 cx.action("Format Selections", Box::new(FormatSelections))
172 })
173 .action(
174 "Code Actions",
175 Box::new(ToggleCodeActions {
176 deployed_from_indicator: None,
177 }),
178 )
179 .separator()
180 .action("Cut", Box::new(Cut))
181 .action("Copy", Box::new(Copy))
182 .action("Paste", Box::new(Paste))
183 .separator()
184 .map(|builder| {
185 if has_reveal_target {
186 builder.action(reveal_in_finder_label, Box::new(RevealInFileManager))
187 } else {
188 builder
189 .disabled_action(reveal_in_finder_label, Box::new(RevealInFileManager))
190 }
191 })
192 .action("Open in Terminal", Box::new(OpenInTerminal))
193 .action("Copy Permalink", Box::new(CopyPermalinkToLine));
194 match focus {
195 Some(focus) => builder.context(focus),
196 None => builder,
197 }
198 })
199 };
200
201 editor.mouse_context_menu = match position {
202 Some(position) => {
203 MouseContextMenu::pinned_to_editor(editor, source_anchor, position, context_menu, cx)
204 }
205 None => {
206 let menu_position = MenuPosition::PinnedToEditor {
207 source: source_anchor,
208 offset: editor.character_size(cx),
209 };
210 Some(MouseContextMenu::new(menu_position, context_menu, cx))
211 }
212 };
213 cx.notify();
214}
215
216#[cfg(test)]
217mod tests {
218 use super::*;
219 use crate::{editor_tests::init_test, test::editor_lsp_test_context::EditorLspTestContext};
220 use indoc::indoc;
221
222 #[gpui::test]
223 async fn test_mouse_context_menu(cx: &mut gpui::TestAppContext) {
224 init_test(cx, |_| {});
225
226 let mut cx = EditorLspTestContext::new_rust(
227 lsp::ServerCapabilities {
228 hover_provider: Some(lsp::HoverProviderCapability::Simple(true)),
229 ..Default::default()
230 },
231 cx,
232 )
233 .await;
234
235 cx.set_state(indoc! {"
236 fn teˇst() {
237 do_work();
238 }
239 "});
240 let point = cx.display_point(indoc! {"
241 fn test() {
242 do_wˇork();
243 }
244 "});
245 cx.editor(|editor, _app| assert!(editor.mouse_context_menu.is_none()));
246 cx.update_editor(|editor, cx| {
247 deploy_context_menu(editor, Some(Default::default()), point, cx)
248 });
249
250 cx.assert_editor_state(indoc! {"
251 fn test() {
252 do_wˇork();
253 }
254 "});
255 cx.editor(|editor, _app| assert!(editor.mouse_context_menu.is_some()));
256 }
257}