hover_popover.rs

  1use futures::FutureExt;
  2use gpui::{
  3    actions,
  4    elements::{Flex, MouseEventHandler, Padding, Text},
  5    impl_internal_actions,
  6    platform::{CursorStyle, MouseButton},
  7    AnyElement, AppContext, Axis, Element, ModelHandle, Task, ViewContext,
  8};
  9use language::{Bias, DiagnosticEntry, DiagnosticSeverity};
 10use project::{HoverBlock, Project};
 11use settings::Settings;
 12use std::{ops::Range, time::Duration};
 13use util::TryFutureExt;
 14
 15use crate::{
 16    display_map::ToDisplayPoint, Anchor, AnchorRangeExt, DisplayPoint, Editor, EditorSnapshot,
 17    EditorStyle, GoToDiagnostic, RangeToAnchorExt,
 18};
 19
 20pub const HOVER_DELAY_MILLIS: u64 = 350;
 21pub const HOVER_REQUEST_DELAY_MILLIS: u64 = 200;
 22
 23pub const MIN_POPOVER_CHARACTER_WIDTH: f32 = 20.;
 24pub const MIN_POPOVER_LINE_HEIGHT: f32 = 4.;
 25pub const HOVER_POPOVER_GAP: f32 = 10.;
 26
 27#[derive(Clone, PartialEq)]
 28pub struct HoverAt {
 29    pub point: Option<DisplayPoint>,
 30}
 31
 32#[derive(Copy, Clone, PartialEq)]
 33pub struct HideHover;
 34
 35actions!(editor, [Hover]);
 36impl_internal_actions!(editor, [HoverAt, HideHover]);
 37
 38pub fn init(cx: &mut AppContext) {
 39    cx.add_action(hover);
 40    cx.add_action(hover_at);
 41    cx.add_action(hide_hover);
 42}
 43
 44/// Bindable action which uses the most recent selection head to trigger a hover
 45pub fn hover(editor: &mut Editor, _: &Hover, cx: &mut ViewContext<Editor>) {
 46    let head = editor.selections.newest_display(cx).head();
 47    show_hover(editor, head, true, cx);
 48}
 49
 50/// The internal hover action dispatches between `show_hover` or `hide_hover`
 51/// depending on whether a point to hover over is provided.
 52pub fn hover_at(editor: &mut Editor, action: &HoverAt, cx: &mut ViewContext<Editor>) {
 53    if cx.global::<Settings>().hover_popover_enabled {
 54        if let Some(point) = action.point {
 55            show_hover(editor, point, false, cx);
 56        } else {
 57            hide_hover(editor, &HideHover, cx);
 58        }
 59    }
 60}
 61
 62/// Hides the type information popup.
 63/// Triggered by the `Hover` action when the cursor is not over a symbol or when the
 64/// selections changed.
 65pub fn hide_hover(editor: &mut Editor, _: &HideHover, cx: &mut ViewContext<Editor>) -> bool {
 66    let did_hide = editor.hover_state.info_popover.take().is_some()
 67        | editor.hover_state.diagnostic_popover.take().is_some();
 68
 69    editor.hover_state.info_task = None;
 70    editor.hover_state.triggered_from = None;
 71
 72    editor.clear_background_highlights::<HoverState>(cx);
 73
 74    if did_hide {
 75        cx.notify();
 76    }
 77
 78    did_hide
 79}
 80
 81/// Queries the LSP and shows type info and documentation
 82/// about the symbol the mouse is currently hovering over.
 83/// Triggered by the `Hover` action when the cursor may be over a symbol.
 84fn show_hover(
 85    editor: &mut Editor,
 86    point: DisplayPoint,
 87    ignore_timeout: bool,
 88    cx: &mut ViewContext<Editor>,
 89) {
 90    if editor.pending_rename.is_some() {
 91        return;
 92    }
 93
 94    let snapshot = editor.snapshot(cx);
 95    let multibuffer_offset = point.to_offset(&snapshot.display_snapshot, Bias::Left);
 96
 97    let (buffer, buffer_position) = if let Some(output) = editor
 98        .buffer
 99        .read(cx)
100        .text_anchor_for_position(multibuffer_offset, cx)
101    {
102        output
103    } else {
104        return;
105    };
106
107    let excerpt_id = if let Some((excerpt_id, _, _)) = editor
108        .buffer()
109        .read(cx)
110        .excerpt_containing(multibuffer_offset, cx)
111    {
112        excerpt_id
113    } else {
114        return;
115    };
116
117    let project = if let Some(project) = editor.project.clone() {
118        project
119    } else {
120        return;
121    };
122
123    if !ignore_timeout {
124        if let Some(InfoPopover { symbol_range, .. }) = &editor.hover_state.info_popover {
125            if symbol_range
126                .to_offset(&snapshot.buffer_snapshot)
127                .contains(&multibuffer_offset)
128            {
129                // Hover triggered from same location as last time. Don't show again.
130                return;
131            } else {
132                hide_hover(editor, &HideHover, cx);
133            }
134        }
135    }
136
137    // Get input anchor
138    let anchor = snapshot
139        .buffer_snapshot
140        .anchor_at(multibuffer_offset, Bias::Left);
141
142    // Don't request again if the location is the same as the previous request
143    if let Some(triggered_from) = &editor.hover_state.triggered_from {
144        if triggered_from
145            .cmp(&anchor, &snapshot.buffer_snapshot)
146            .is_eq()
147        {
148            return;
149        }
150    }
151
152    let task = cx.spawn_weak(|this, mut cx| {
153        async move {
154            // If we need to delay, delay a set amount initially before making the lsp request
155            let delay = if !ignore_timeout {
156                // Construct delay task to wait for later
157                let total_delay = Some(
158                    cx.background()
159                        .timer(Duration::from_millis(HOVER_DELAY_MILLIS)),
160                );
161
162                cx.background()
163                    .timer(Duration::from_millis(HOVER_REQUEST_DELAY_MILLIS))
164                    .await;
165                total_delay
166            } else {
167                None
168            };
169
170            // query the LSP for hover info
171            let hover_request = cx.update(|cx| {
172                project.update(cx, |project, cx| {
173                    project.hover(&buffer, buffer_position, cx)
174                })
175            });
176
177            if let Some(delay) = delay {
178                delay.await;
179            }
180
181            // If there's a diagnostic, assign it on the hover state and notify
182            let local_diagnostic = snapshot
183                .buffer_snapshot
184                .diagnostics_in_range::<_, usize>(multibuffer_offset..multibuffer_offset, false)
185                // Find the entry with the most specific range
186                .min_by_key(|entry| entry.range.end - entry.range.start)
187                .map(|entry| DiagnosticEntry {
188                    diagnostic: entry.diagnostic,
189                    range: entry.range.to_anchors(&snapshot.buffer_snapshot),
190                });
191
192            // Pull the primary diagnostic out so we can jump to it if the popover is clicked
193            let primary_diagnostic = local_diagnostic.as_ref().and_then(|local_diagnostic| {
194                snapshot
195                    .buffer_snapshot
196                    .diagnostic_group::<usize>(local_diagnostic.diagnostic.group_id)
197                    .find(|diagnostic| diagnostic.diagnostic.is_primary)
198                    .map(|entry| DiagnosticEntry {
199                        diagnostic: entry.diagnostic,
200                        range: entry.range.to_anchors(&snapshot.buffer_snapshot),
201                    })
202            });
203
204            if let Some(this) = this.upgrade(&cx) {
205                this.update(&mut cx, |this, _| {
206                    this.hover_state.diagnostic_popover =
207                        local_diagnostic.map(|local_diagnostic| DiagnosticPopover {
208                            local_diagnostic,
209                            primary_diagnostic,
210                        });
211                })?;
212            }
213
214            // Construct new hover popover from hover request
215            let hover_popover = hover_request.await.ok().flatten().and_then(|hover_result| {
216                if hover_result.contents.is_empty() {
217                    return None;
218                }
219
220                // Create symbol range of anchors for highlighting and filtering
221                // of future requests.
222                let range = if let Some(range) = hover_result.range {
223                    let start = snapshot
224                        .buffer_snapshot
225                        .anchor_in_excerpt(excerpt_id.clone(), range.start);
226                    let end = snapshot
227                        .buffer_snapshot
228                        .anchor_in_excerpt(excerpt_id.clone(), range.end);
229
230                    start..end
231                } else {
232                    anchor..anchor
233                };
234
235                Some(InfoPopover {
236                    project: project.clone(),
237                    symbol_range: range,
238                    contents: hover_result.contents,
239                })
240            });
241
242            if let Some(this) = this.upgrade(&cx) {
243                this.update(&mut cx, |this, cx| {
244                    if let Some(hover_popover) = hover_popover.as_ref() {
245                        // Highlight the selected symbol using a background highlight
246                        this.highlight_background::<HoverState>(
247                            vec![hover_popover.symbol_range.clone()],
248                            |theme| theme.editor.hover_popover.highlight,
249                            cx,
250                        );
251                    } else {
252                        this.clear_background_highlights::<HoverState>(cx);
253                    }
254
255                    this.hover_state.info_popover = hover_popover;
256                    cx.notify();
257                })?;
258            }
259            Ok::<_, anyhow::Error>(())
260        }
261        .log_err()
262    });
263
264    editor.hover_state.info_task = Some(task);
265}
266
267#[derive(Default)]
268pub struct HoverState {
269    pub info_popover: Option<InfoPopover>,
270    pub diagnostic_popover: Option<DiagnosticPopover>,
271    pub triggered_from: Option<Anchor>,
272    pub info_task: Option<Task<Option<()>>>,
273}
274
275impl HoverState {
276    pub fn visible(&self) -> bool {
277        self.info_popover.is_some() || self.diagnostic_popover.is_some()
278    }
279
280    pub fn render(
281        &self,
282        snapshot: &EditorSnapshot,
283        style: &EditorStyle,
284        visible_rows: Range<u32>,
285        cx: &mut ViewContext<Editor>,
286    ) -> Option<(DisplayPoint, Vec<AnyElement<Editor>>)> {
287        // If there is a diagnostic, position the popovers based on that.
288        // Otherwise use the start of the hover range
289        let anchor = self
290            .diagnostic_popover
291            .as_ref()
292            .map(|diagnostic_popover| &diagnostic_popover.local_diagnostic.range.start)
293            .or_else(|| {
294                self.info_popover
295                    .as_ref()
296                    .map(|info_popover| &info_popover.symbol_range.start)
297            })?;
298        let point = anchor.to_display_point(&snapshot.display_snapshot);
299
300        // Don't render if the relevant point isn't on screen
301        if !self.visible() || !visible_rows.contains(&point.row()) {
302            return None;
303        }
304
305        let mut elements = Vec::new();
306
307        if let Some(diagnostic_popover) = self.diagnostic_popover.as_ref() {
308            elements.push(diagnostic_popover.render(style, cx));
309        }
310        if let Some(info_popover) = self.info_popover.as_ref() {
311            elements.push(info_popover.render(style, cx));
312        }
313
314        Some((point, elements))
315    }
316}
317
318#[derive(Debug, Clone)]
319pub struct InfoPopover {
320    pub project: ModelHandle<Project>,
321    pub symbol_range: Range<Anchor>,
322    pub contents: Vec<HoverBlock>,
323}
324
325impl InfoPopover {
326    pub fn render(&self, style: &EditorStyle, cx: &mut ViewContext<Editor>) -> AnyElement<Editor> {
327        MouseEventHandler::<InfoPopover, _>::new(0, cx, |_, cx| {
328            let mut flex = Flex::new(Axis::Vertical).scrollable::<HoverBlock>(1, None, cx);
329            flex.extend(self.contents.iter().map(|content| {
330                let languages = self.project.read(cx).languages();
331                if let Some(language) = content.language.clone().and_then(|language| {
332                    languages.language_for_name(&language).now_or_never()?.ok()
333                }) {
334                    let runs = language
335                        .highlight_text(&content.text.as_str().into(), 0..content.text.len());
336
337                    Text::new(content.text.clone(), style.text.clone())
338                        .with_soft_wrap(true)
339                        .with_highlights(
340                            runs.iter()
341                                .filter_map(|(range, id)| {
342                                    id.style(style.theme.syntax.as_ref())
343                                        .map(|style| (range.clone(), style))
344                                })
345                                .collect(),
346                        )
347                        .into_any()
348                } else {
349                    let mut text_style = style.hover_popover.prose.clone();
350                    text_style.font_size = style.text.font_size;
351
352                    Text::new(content.text.clone(), text_style)
353                        .with_soft_wrap(true)
354                        .contained()
355                        .with_style(style.hover_popover.block_style)
356                        .into_any()
357                }
358            }));
359            flex.contained().with_style(style.hover_popover.container)
360        })
361        .on_move(|_, _, _| {}) // Consume move events so they don't reach regions underneath.
362        .with_cursor_style(CursorStyle::Arrow)
363        .with_padding(Padding {
364            bottom: HOVER_POPOVER_GAP,
365            top: HOVER_POPOVER_GAP,
366            ..Default::default()
367        })
368        .into_any()
369    }
370}
371
372#[derive(Debug, Clone)]
373pub struct DiagnosticPopover {
374    local_diagnostic: DiagnosticEntry<Anchor>,
375    primary_diagnostic: Option<DiagnosticEntry<Anchor>>,
376}
377
378impl DiagnosticPopover {
379    pub fn render(&self, style: &EditorStyle, cx: &mut ViewContext<Editor>) -> AnyElement<Editor> {
380        enum PrimaryDiagnostic {}
381
382        let mut text_style = style.hover_popover.prose.clone();
383        text_style.font_size = style.text.font_size;
384
385        let container_style = match self.local_diagnostic.diagnostic.severity {
386            DiagnosticSeverity::HINT => style.hover_popover.info_container,
387            DiagnosticSeverity::INFORMATION => style.hover_popover.info_container,
388            DiagnosticSeverity::WARNING => style.hover_popover.warning_container,
389            DiagnosticSeverity::ERROR => style.hover_popover.error_container,
390            _ => style.hover_popover.container,
391        };
392
393        let tooltip_style = cx.global::<Settings>().theme.tooltip.clone();
394
395        MouseEventHandler::<DiagnosticPopover, _>::new(0, cx, |_, _| {
396            Text::new(self.local_diagnostic.diagnostic.message.clone(), text_style)
397                .with_soft_wrap(true)
398                .contained()
399                .with_style(container_style)
400        })
401        .with_padding(Padding {
402            top: HOVER_POPOVER_GAP,
403            bottom: HOVER_POPOVER_GAP,
404            ..Default::default()
405        })
406        .on_move(|_, _, _| {}) // Consume move events so they don't reach regions underneath.
407        .on_click(MouseButton::Left, |_, _, cx| {
408            cx.dispatch_action(GoToDiagnostic)
409        })
410        .with_cursor_style(CursorStyle::PointingHand)
411        .with_tooltip::<PrimaryDiagnostic>(
412            0,
413            "Go To Diagnostic".to_string(),
414            Some(Box::new(crate::GoToDiagnostic)),
415            tooltip_style,
416            cx,
417        )
418        .into_any()
419    }
420
421    pub fn activation_info(&self) -> (usize, Anchor) {
422        let entry = self
423            .primary_diagnostic
424            .as_ref()
425            .unwrap_or(&self.local_diagnostic);
426
427        (entry.diagnostic.group_id, entry.range.start.clone())
428    }
429}
430
431#[cfg(test)]
432mod tests {
433    use indoc::indoc;
434
435    use language::{Diagnostic, DiagnosticSet};
436    use lsp::LanguageServerId;
437    use project::HoverBlock;
438    use smol::stream::StreamExt;
439
440    use crate::test::editor_lsp_test_context::EditorLspTestContext;
441
442    use super::*;
443
444    #[gpui::test]
445    async fn test_mouse_hover_info_popover(cx: &mut gpui::TestAppContext) {
446        let mut cx = EditorLspTestContext::new_rust(
447            lsp::ServerCapabilities {
448                hover_provider: Some(lsp::HoverProviderCapability::Simple(true)),
449                ..Default::default()
450            },
451            cx,
452        )
453        .await;
454
455        // Basic hover delays and then pops without moving the mouse
456        cx.set_state(indoc! {"
457            fn ˇtest() { println!(); }
458        "});
459        let hover_point = cx.display_point(indoc! {"
460            fn test() { printˇln!(); }
461        "});
462
463        cx.update_editor(|editor, cx| {
464            hover_at(
465                editor,
466                &HoverAt {
467                    point: Some(hover_point),
468                },
469                cx,
470            )
471        });
472        assert!(!cx.editor(|editor, _| editor.hover_state.visible()));
473
474        // After delay, hover should be visible.
475        let symbol_range = cx.lsp_range(indoc! {"
476            fn test() { «println!»(); }
477        "});
478        let mut requests =
479            cx.handle_request::<lsp::request::HoverRequest, _, _>(move |_, _, _| async move {
480                Ok(Some(lsp::Hover {
481                    contents: lsp::HoverContents::Markup(lsp::MarkupContent {
482                        kind: lsp::MarkupKind::Markdown,
483                        value: indoc! {"
484                            # Some basic docs
485                            Some test documentation"}
486                        .to_string(),
487                    }),
488                    range: Some(symbol_range),
489                }))
490            });
491        cx.foreground()
492            .advance_clock(Duration::from_millis(HOVER_DELAY_MILLIS + 100));
493        requests.next().await;
494
495        cx.editor(|editor, _| {
496            assert!(editor.hover_state.visible());
497            assert_eq!(
498                editor.hover_state.info_popover.clone().unwrap().contents,
499                vec![
500                    HoverBlock {
501                        text: "Some basic docs".to_string(),
502                        language: None
503                    },
504                    HoverBlock {
505                        text: "Some test documentation".to_string(),
506                        language: None
507                    }
508                ]
509            )
510        });
511
512        // Mouse moved with no hover response dismisses
513        let hover_point = cx.display_point(indoc! {"
514            fn teˇst() { println!(); }
515        "});
516        let mut request = cx
517            .lsp
518            .handle_request::<lsp::request::HoverRequest, _, _>(|_, _| async move { Ok(None) });
519        cx.update_editor(|editor, cx| {
520            hover_at(
521                editor,
522                &HoverAt {
523                    point: Some(hover_point),
524                },
525                cx,
526            )
527        });
528        cx.foreground()
529            .advance_clock(Duration::from_millis(HOVER_DELAY_MILLIS + 100));
530        request.next().await;
531        cx.editor(|editor, _| {
532            assert!(!editor.hover_state.visible());
533        });
534    }
535
536    #[gpui::test]
537    async fn test_keyboard_hover_info_popover(cx: &mut gpui::TestAppContext) {
538        let mut cx = EditorLspTestContext::new_rust(
539            lsp::ServerCapabilities {
540                hover_provider: Some(lsp::HoverProviderCapability::Simple(true)),
541                ..Default::default()
542            },
543            cx,
544        )
545        .await;
546
547        // Hover with keyboard has no delay
548        cx.set_state(indoc! {"
549            fˇn test() { println!(); }
550        "});
551        cx.update_editor(|editor, cx| hover(editor, &Hover, cx));
552        let symbol_range = cx.lsp_range(indoc! {"
553            «fn» test() { println!(); }
554        "});
555        cx.handle_request::<lsp::request::HoverRequest, _, _>(move |_, _, _| async move {
556            Ok(Some(lsp::Hover {
557                contents: lsp::HoverContents::Markup(lsp::MarkupContent {
558                    kind: lsp::MarkupKind::Markdown,
559                    value: indoc! {"
560                        # Some other basic docs
561                        Some other test documentation"}
562                    .to_string(),
563                }),
564                range: Some(symbol_range),
565            }))
566        })
567        .next()
568        .await;
569
570        cx.condition(|editor, _| editor.hover_state.visible()).await;
571        cx.editor(|editor, _| {
572            assert_eq!(
573                editor.hover_state.info_popover.clone().unwrap().contents,
574                vec![
575                    HoverBlock {
576                        text: "Some other basic docs".to_string(),
577                        language: None
578                    },
579                    HoverBlock {
580                        text: "Some other test documentation".to_string(),
581                        language: None
582                    }
583                ]
584            )
585        });
586    }
587
588    #[gpui::test]
589    async fn test_hover_diagnostic_and_info_popovers(cx: &mut gpui::TestAppContext) {
590        let mut cx = EditorLspTestContext::new_rust(
591            lsp::ServerCapabilities {
592                hover_provider: Some(lsp::HoverProviderCapability::Simple(true)),
593                ..Default::default()
594            },
595            cx,
596        )
597        .await;
598
599        // Hover with just diagnostic, pops DiagnosticPopover immediately and then
600        // info popover once request completes
601        cx.set_state(indoc! {"
602            fn teˇst() { println!(); }
603        "});
604
605        // Send diagnostic to client
606        let range = cx.text_anchor_range(indoc! {"
607            fn «test»() { println!(); }
608        "});
609        cx.update_buffer(|buffer, cx| {
610            let snapshot = buffer.text_snapshot();
611            let set = DiagnosticSet::from_sorted_entries(
612                vec![DiagnosticEntry {
613                    range,
614                    diagnostic: Diagnostic {
615                        message: "A test diagnostic message.".to_string(),
616                        ..Default::default()
617                    },
618                }],
619                &snapshot,
620            );
621            buffer.update_diagnostics(LanguageServerId(0), set, cx);
622        });
623
624        // Hover pops diagnostic immediately
625        cx.update_editor(|editor, cx| hover(editor, &Hover, cx));
626        cx.foreground().run_until_parked();
627
628        cx.editor(|Editor { hover_state, .. }, _| {
629            assert!(hover_state.diagnostic_popover.is_some() && hover_state.info_popover.is_none())
630        });
631
632        // Info Popover shows after request responded to
633        let range = cx.lsp_range(indoc! {"
634            fn «test»() { println!(); }
635        "});
636        cx.handle_request::<lsp::request::HoverRequest, _, _>(move |_, _, _| async move {
637            Ok(Some(lsp::Hover {
638                contents: lsp::HoverContents::Markup(lsp::MarkupContent {
639                    kind: lsp::MarkupKind::Markdown,
640                    value: indoc! {"
641                        # Some other basic docs
642                        Some other test documentation"}
643                    .to_string(),
644                }),
645                range: Some(range),
646            }))
647        });
648        cx.foreground()
649            .advance_clock(Duration::from_millis(HOVER_DELAY_MILLIS + 100));
650
651        cx.foreground().run_until_parked();
652        cx.editor(|Editor { hover_state, .. }, _| {
653            hover_state.diagnostic_popover.is_some() && hover_state.info_task.is_some()
654        });
655    }
656}