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;
 14use zed_actions::agent::AddSelectionToThread;
 15
 16#[derive(Debug)]
 17pub enum MenuPosition {
 18    /// When the editor is scrolled, the context menu stays on the exact
 19    /// same position on the screen, never disappearing.
 20    PinnedToScreen(Point<Pixels>),
 21    /// When the editor is scrolled, the context menu follows the position it is associated with.
 22    /// Disappears when the position is no longer visible.
 23    PinnedToEditor {
 24        source: multi_buffer::Anchor,
 25        offset: Point<Pixels>,
 26    },
 27}
 28
 29pub struct MouseContextMenu {
 30    pub(crate) position: MenuPosition,
 31    pub(crate) context_menu: Entity<ui::ContextMenu>,
 32    _dismiss_subscription: Subscription,
 33    _cursor_move_subscription: Subscription,
 34}
 35
 36impl std::fmt::Debug for MouseContextMenu {
 37    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 38        f.debug_struct("MouseContextMenu")
 39            .field("position", &self.position)
 40            .field("context_menu", &self.context_menu)
 41            .finish()
 42    }
 43}
 44
 45impl MouseContextMenu {
 46    pub(crate) fn pinned_to_editor(
 47        editor: &mut Editor,
 48        source: multi_buffer::Anchor,
 49        position: Point<Pixels>,
 50        context_menu: Entity<ui::ContextMenu>,
 51        window: &mut Window,
 52        cx: &mut Context<Editor>,
 53    ) -> Option<Self> {
 54        let editor_snapshot = editor.snapshot(window, cx);
 55        let content_origin = editor.last_bounds?.origin
 56            + Point {
 57                x: editor.gutter_dimensions.width,
 58                y: Pixels::ZERO,
 59            };
 60        let source_position = editor.to_pixel_point(source, &editor_snapshot, window)?;
 61        let menu_position = MenuPosition::PinnedToEditor {
 62            source,
 63            offset: position - (source_position + content_origin),
 64        };
 65        Some(MouseContextMenu::new(
 66            editor,
 67            menu_position,
 68            context_menu,
 69            window,
 70            cx,
 71        ))
 72    }
 73
 74    pub(crate) fn new(
 75        editor: &Editor,
 76        position: MenuPosition,
 77        context_menu: Entity<ui::ContextMenu>,
 78        window: &mut Window,
 79        cx: &mut Context<Editor>,
 80    ) -> Self {
 81        let context_menu_focus = context_menu.focus_handle(cx);
 82        window.focus(&context_menu_focus);
 83
 84        let _dismiss_subscription = cx.subscribe_in(&context_menu, window, {
 85            let context_menu_focus = context_menu_focus.clone();
 86            move |editor, _, _event: &DismissEvent, window, cx| {
 87                editor.mouse_context_menu.take();
 88                if context_menu_focus.contains_focused(window, cx) {
 89                    window.focus(&editor.focus_handle(cx));
 90                }
 91            }
 92        });
 93
 94        let selection_init = editor.selections.newest_anchor().clone();
 95
 96        let _cursor_move_subscription = cx.subscribe_in(
 97            &cx.entity(),
 98            window,
 99            move |editor, _, event: &crate::EditorEvent, window, cx| {
100                let crate::EditorEvent::SelectionsChanged { local: true } = event else {
101                    return;
102                };
103                let display_snapshot = &editor
104                    .display_map
105                    .update(cx, |display_map, cx| display_map.snapshot(cx));
106                let selection_init_range = selection_init.display_range(display_snapshot);
107                let selection_now_range = editor
108                    .selections
109                    .newest_anchor()
110                    .display_range(display_snapshot);
111                if selection_now_range == selection_init_range {
112                    return;
113                }
114                editor.mouse_context_menu.take();
115                if context_menu_focus.contains_focused(window, cx) {
116                    window.focus(&editor.focus_handle(cx));
117                }
118            },
119        );
120
121        Self {
122            position,
123            context_menu,
124            _dismiss_subscription,
125            _cursor_move_subscription,
126        }
127    }
128}
129
130fn display_ranges<'a>(
131    display_map: &'a DisplaySnapshot,
132    selections: &'a SelectionsCollection,
133) -> impl Iterator<Item = Range<DisplayPoint>> + 'a {
134    let pending = selections.pending_anchor();
135    selections
136        .disjoint_anchors()
137        .iter()
138        .chain(pending)
139        .map(move |s| s.start.to_display_point(display_map)..s.end.to_display_point(display_map))
140}
141
142pub fn deploy_context_menu(
143    editor: &mut Editor,
144    position: Option<Point<Pixels>>,
145    point: DisplayPoint,
146    window: &mut Window,
147    cx: &mut Context<Editor>,
148) {
149    if !editor.is_focused(window) {
150        window.focus(&editor.focus_handle(cx));
151    }
152
153    // Don't show context menu for inline editors
154    if !editor.mode().is_full() {
155        return;
156    }
157
158    let display_map = editor.display_snapshot(cx);
159    let source_anchor = display_map.display_point_to_anchor(point, text::Bias::Right);
160    let context_menu = if let Some(custom) = editor.custom_context_menu.take() {
161        let menu = custom(editor, point, window, cx);
162        editor.custom_context_menu = Some(custom);
163        let Some(menu) = menu else {
164            return;
165        };
166        menu
167    } else {
168        // Don't show the context menu if there isn't a project associated with this editor
169        let Some(project) = editor.project.clone() else {
170            return;
171        };
172
173        let snapshot = editor.snapshot(window, cx);
174        let display_map = editor.display_snapshot(cx);
175        let buffer = snapshot.buffer_snapshot();
176        let anchor = buffer.anchor_before(point.to_point(&display_map));
177        if !display_ranges(&display_map, &editor.selections).any(|r| r.contains(&point)) {
178            // Move the cursor to the clicked location so that dispatched actions make sense
179            editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
180                s.clear_disjoint();
181                s.set_pending_anchor_range(anchor..anchor, SelectMode::Character);
182            });
183        }
184
185        let focus = window.focused(cx);
186        let has_reveal_target = editor.target_file(cx).is_some();
187        let has_selections = editor
188            .selections
189            .all::<PointUtf16>(&display_map)
190            .into_iter()
191            .any(|s| !s.is_empty());
192        let has_git_repo = buffer
193            .buffer_id_for_anchor(anchor)
194            .is_some_and(|buffer_id| {
195                project
196                    .read(cx)
197                    .git_store()
198                    .read(cx)
199                    .repository_and_path_for_buffer_id(buffer_id, cx)
200                    .is_some()
201            });
202
203        let evaluate_selection = window.is_action_available(&EvaluateSelectedText, cx);
204        let run_to_cursor = window.is_action_available(&RunToCursor, cx);
205
206        ui::ContextMenu::build(window, cx, |menu, _window, _cx| {
207            let builder = menu
208                .on_blur_subscription(Subscription::new(|| {}))
209                .when(run_to_cursor, |builder| {
210                    builder.action("Run to Cursor", Box::new(RunToCursor))
211                })
212                .when(evaluate_selection && has_selections, |builder| {
213                    builder.action("Evaluate Selection", Box::new(EvaluateSelectedText))
214                })
215                .when(
216                    run_to_cursor || (evaluate_selection && has_selections),
217                    |builder| builder.separator(),
218                )
219                .action("Go to Definition", Box::new(GoToDefinition))
220                .action("Go to Declaration", Box::new(GoToDeclaration))
221                .action("Go to Type Definition", Box::new(GoToTypeDefinition))
222                .action("Go to Implementation", Box::new(GoToImplementation))
223                .action("Find All References", Box::new(FindAllReferences))
224                .separator()
225                .action("Rename Symbol", Box::new(Rename))
226                .action("Format Buffer", Box::new(Format))
227                .when(has_selections, |cx| {
228                    cx.action("Format Selections", Box::new(FormatSelections))
229                })
230                .action(
231                    "Show Code Actions",
232                    Box::new(ToggleCodeActions {
233                        deployed_from: None,
234                        quick_launch: false,
235                    }),
236                )
237                .action("Add to Agent Thread", Box::new(AddSelectionToThread))
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}