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(|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            this.update(&mut cx, |this, _| {
205                this.hover_state.diagnostic_popover =
206                    local_diagnostic.map(|local_diagnostic| DiagnosticPopover {
207                        local_diagnostic,
208                        primary_diagnostic,
209                    });
210            })?;
211
212            // Construct new hover popover from hover request
213            let hover_popover = hover_request.await.ok().flatten().and_then(|hover_result| {
214                if hover_result.contents.is_empty() {
215                    return None;
216                }
217
218                // Create symbol range of anchors for highlighting and filtering
219                // of future requests.
220                let range = if let Some(range) = hover_result.range {
221                    let start = snapshot
222                        .buffer_snapshot
223                        .anchor_in_excerpt(excerpt_id.clone(), range.start);
224                    let end = snapshot
225                        .buffer_snapshot
226                        .anchor_in_excerpt(excerpt_id.clone(), range.end);
227
228                    start..end
229                } else {
230                    anchor..anchor
231                };
232
233                Some(InfoPopover {
234                    project: project.clone(),
235                    symbol_range: range,
236                    contents: hover_result.contents,
237                })
238            });
239
240            this.update(&mut cx, |this, cx| {
241                if let Some(hover_popover) = hover_popover.as_ref() {
242                    // Highlight the selected symbol using a background highlight
243                    this.highlight_background::<HoverState>(
244                        vec![hover_popover.symbol_range.clone()],
245                        |theme| theme.editor.hover_popover.highlight,
246                        cx,
247                    );
248                } else {
249                    this.clear_background_highlights::<HoverState>(cx);
250                }
251
252                this.hover_state.info_popover = hover_popover;
253                cx.notify();
254            })?;
255
256            Ok::<_, anyhow::Error>(())
257        }
258        .log_err()
259    });
260
261    editor.hover_state.info_task = Some(task);
262}
263
264#[derive(Default)]
265pub struct HoverState {
266    pub info_popover: Option<InfoPopover>,
267    pub diagnostic_popover: Option<DiagnosticPopover>,
268    pub triggered_from: Option<Anchor>,
269    pub info_task: Option<Task<Option<()>>>,
270}
271
272impl HoverState {
273    pub fn visible(&self) -> bool {
274        self.info_popover.is_some() || self.diagnostic_popover.is_some()
275    }
276
277    pub fn render(
278        &self,
279        snapshot: &EditorSnapshot,
280        style: &EditorStyle,
281        visible_rows: Range<u32>,
282        cx: &mut ViewContext<Editor>,
283    ) -> Option<(DisplayPoint, Vec<AnyElement<Editor>>)> {
284        // If there is a diagnostic, position the popovers based on that.
285        // Otherwise use the start of the hover range
286        let anchor = self
287            .diagnostic_popover
288            .as_ref()
289            .map(|diagnostic_popover| &diagnostic_popover.local_diagnostic.range.start)
290            .or_else(|| {
291                self.info_popover
292                    .as_ref()
293                    .map(|info_popover| &info_popover.symbol_range.start)
294            })?;
295        let point = anchor.to_display_point(&snapshot.display_snapshot);
296
297        // Don't render if the relevant point isn't on screen
298        if !self.visible() || !visible_rows.contains(&point.row()) {
299            return None;
300        }
301
302        let mut elements = Vec::new();
303
304        if let Some(diagnostic_popover) = self.diagnostic_popover.as_ref() {
305            elements.push(diagnostic_popover.render(style, cx));
306        }
307        if let Some(info_popover) = self.info_popover.as_ref() {
308            elements.push(info_popover.render(style, cx));
309        }
310
311        Some((point, elements))
312    }
313}
314
315#[derive(Debug, Clone)]
316pub struct InfoPopover {
317    pub project: ModelHandle<Project>,
318    pub symbol_range: Range<Anchor>,
319    pub contents: Vec<HoverBlock>,
320}
321
322impl InfoPopover {
323    pub fn render(&self, style: &EditorStyle, cx: &mut ViewContext<Editor>) -> AnyElement<Editor> {
324        MouseEventHandler::<InfoPopover, _>::new(0, cx, |_, cx| {
325            let mut flex = Flex::new(Axis::Vertical).scrollable::<HoverBlock>(1, None, cx);
326            flex.extend(self.contents.iter().map(|content| {
327                let languages = self.project.read(cx).languages();
328                if let Some(language) = content.language.clone().and_then(|language| {
329                    languages.language_for_name(&language).now_or_never()?.ok()
330                }) {
331                    let runs = language
332                        .highlight_text(&content.text.as_str().into(), 0..content.text.len());
333
334                    Text::new(content.text.clone(), style.text.clone())
335                        .with_soft_wrap(true)
336                        .with_highlights(
337                            runs.iter()
338                                .filter_map(|(range, id)| {
339                                    id.style(style.theme.syntax.as_ref())
340                                        .map(|style| (range.clone(), style))
341                                })
342                                .collect(),
343                        )
344                        .into_any()
345                } else {
346                    let mut text_style = style.hover_popover.prose.clone();
347                    text_style.font_size = style.text.font_size;
348
349                    Text::new(content.text.clone(), text_style)
350                        .with_soft_wrap(true)
351                        .contained()
352                        .with_style(style.hover_popover.block_style)
353                        .into_any()
354                }
355            }));
356            flex.contained().with_style(style.hover_popover.container)
357        })
358        .on_move(|_, _, _| {}) // Consume move events so they don't reach regions underneath.
359        .with_cursor_style(CursorStyle::Arrow)
360        .with_padding(Padding {
361            bottom: HOVER_POPOVER_GAP,
362            top: HOVER_POPOVER_GAP,
363            ..Default::default()
364        })
365        .into_any()
366    }
367}
368
369#[derive(Debug, Clone)]
370pub struct DiagnosticPopover {
371    local_diagnostic: DiagnosticEntry<Anchor>,
372    primary_diagnostic: Option<DiagnosticEntry<Anchor>>,
373}
374
375impl DiagnosticPopover {
376    pub fn render(&self, style: &EditorStyle, cx: &mut ViewContext<Editor>) -> AnyElement<Editor> {
377        enum PrimaryDiagnostic {}
378
379        let mut text_style = style.hover_popover.prose.clone();
380        text_style.font_size = style.text.font_size;
381
382        let container_style = match self.local_diagnostic.diagnostic.severity {
383            DiagnosticSeverity::HINT => style.hover_popover.info_container,
384            DiagnosticSeverity::INFORMATION => style.hover_popover.info_container,
385            DiagnosticSeverity::WARNING => style.hover_popover.warning_container,
386            DiagnosticSeverity::ERROR => style.hover_popover.error_container,
387            _ => style.hover_popover.container,
388        };
389
390        let tooltip_style = cx.global::<Settings>().theme.tooltip.clone();
391
392        MouseEventHandler::<DiagnosticPopover, _>::new(0, cx, |_, _| {
393            Text::new(self.local_diagnostic.diagnostic.message.clone(), text_style)
394                .with_soft_wrap(true)
395                .contained()
396                .with_style(container_style)
397        })
398        .with_padding(Padding {
399            top: HOVER_POPOVER_GAP,
400            bottom: HOVER_POPOVER_GAP,
401            ..Default::default()
402        })
403        .on_move(|_, _, _| {}) // Consume move events so they don't reach regions underneath.
404        .on_click(MouseButton::Left, |_, _, cx| {
405            cx.dispatch_action(GoToDiagnostic)
406        })
407        .with_cursor_style(CursorStyle::PointingHand)
408        .with_tooltip::<PrimaryDiagnostic>(
409            0,
410            "Go To Diagnostic".to_string(),
411            Some(Box::new(crate::GoToDiagnostic)),
412            tooltip_style,
413            cx,
414        )
415        .into_any()
416    }
417
418    pub fn activation_info(&self) -> (usize, Anchor) {
419        let entry = self
420            .primary_diagnostic
421            .as_ref()
422            .unwrap_or(&self.local_diagnostic);
423
424        (entry.diagnostic.group_id, entry.range.start.clone())
425    }
426}
427
428#[cfg(test)]
429mod tests {
430    use indoc::indoc;
431
432    use language::{Diagnostic, DiagnosticSet};
433    use lsp::LanguageServerId;
434    use project::HoverBlock;
435    use smol::stream::StreamExt;
436
437    use crate::test::editor_lsp_test_context::EditorLspTestContext;
438
439    use super::*;
440
441    #[gpui::test]
442    async fn test_mouse_hover_info_popover(cx: &mut gpui::TestAppContext) {
443        let mut cx = EditorLspTestContext::new_rust(
444            lsp::ServerCapabilities {
445                hover_provider: Some(lsp::HoverProviderCapability::Simple(true)),
446                ..Default::default()
447            },
448            cx,
449        )
450        .await;
451
452        // Basic hover delays and then pops without moving the mouse
453        cx.set_state(indoc! {"
454            fn ˇtest() { println!(); }
455        "});
456        let hover_point = cx.display_point(indoc! {"
457            fn test() { printˇln!(); }
458        "});
459
460        cx.update_editor(|editor, cx| {
461            hover_at(
462                editor,
463                &HoverAt {
464                    point: Some(hover_point),
465                },
466                cx,
467            )
468        });
469        assert!(!cx.editor(|editor, _| editor.hover_state.visible()));
470
471        // After delay, hover should be visible.
472        let symbol_range = cx.lsp_range(indoc! {"
473            fn test() { «println!»(); }
474        "});
475        let mut requests =
476            cx.handle_request::<lsp::request::HoverRequest, _, _>(move |_, _, _| async move {
477                Ok(Some(lsp::Hover {
478                    contents: lsp::HoverContents::Markup(lsp::MarkupContent {
479                        kind: lsp::MarkupKind::Markdown,
480                        value: indoc! {"
481                            # Some basic docs
482                            Some test documentation"}
483                        .to_string(),
484                    }),
485                    range: Some(symbol_range),
486                }))
487            });
488        cx.foreground()
489            .advance_clock(Duration::from_millis(HOVER_DELAY_MILLIS + 100));
490        requests.next().await;
491
492        cx.editor(|editor, _| {
493            assert!(editor.hover_state.visible());
494            assert_eq!(
495                editor.hover_state.info_popover.clone().unwrap().contents,
496                vec![
497                    HoverBlock {
498                        text: "Some basic docs".to_string(),
499                        language: None
500                    },
501                    HoverBlock {
502                        text: "Some test documentation".to_string(),
503                        language: None
504                    }
505                ]
506            )
507        });
508
509        // Mouse moved with no hover response dismisses
510        let hover_point = cx.display_point(indoc! {"
511            fn teˇst() { println!(); }
512        "});
513        let mut request = cx
514            .lsp
515            .handle_request::<lsp::request::HoverRequest, _, _>(|_, _| async move { Ok(None) });
516        cx.update_editor(|editor, cx| {
517            hover_at(
518                editor,
519                &HoverAt {
520                    point: Some(hover_point),
521                },
522                cx,
523            )
524        });
525        cx.foreground()
526            .advance_clock(Duration::from_millis(HOVER_DELAY_MILLIS + 100));
527        request.next().await;
528        cx.editor(|editor, _| {
529            assert!(!editor.hover_state.visible());
530        });
531    }
532
533    #[gpui::test]
534    async fn test_keyboard_hover_info_popover(cx: &mut gpui::TestAppContext) {
535        let mut cx = EditorLspTestContext::new_rust(
536            lsp::ServerCapabilities {
537                hover_provider: Some(lsp::HoverProviderCapability::Simple(true)),
538                ..Default::default()
539            },
540            cx,
541        )
542        .await;
543
544        // Hover with keyboard has no delay
545        cx.set_state(indoc! {"
546            fˇn test() { println!(); }
547        "});
548        cx.update_editor(|editor, cx| hover(editor, &Hover, cx));
549        let symbol_range = cx.lsp_range(indoc! {"
550            «fn» test() { println!(); }
551        "});
552        cx.handle_request::<lsp::request::HoverRequest, _, _>(move |_, _, _| async move {
553            Ok(Some(lsp::Hover {
554                contents: lsp::HoverContents::Markup(lsp::MarkupContent {
555                    kind: lsp::MarkupKind::Markdown,
556                    value: indoc! {"
557                        # Some other basic docs
558                        Some other test documentation"}
559                    .to_string(),
560                }),
561                range: Some(symbol_range),
562            }))
563        })
564        .next()
565        .await;
566
567        cx.condition(|editor, _| editor.hover_state.visible()).await;
568        cx.editor(|editor, _| {
569            assert_eq!(
570                editor.hover_state.info_popover.clone().unwrap().contents,
571                vec![
572                    HoverBlock {
573                        text: "Some other basic docs".to_string(),
574                        language: None
575                    },
576                    HoverBlock {
577                        text: "Some other test documentation".to_string(),
578                        language: None
579                    }
580                ]
581            )
582        });
583    }
584
585    #[gpui::test]
586    async fn test_hover_diagnostic_and_info_popovers(cx: &mut gpui::TestAppContext) {
587        let mut cx = EditorLspTestContext::new_rust(
588            lsp::ServerCapabilities {
589                hover_provider: Some(lsp::HoverProviderCapability::Simple(true)),
590                ..Default::default()
591            },
592            cx,
593        )
594        .await;
595
596        // Hover with just diagnostic, pops DiagnosticPopover immediately and then
597        // info popover once request completes
598        cx.set_state(indoc! {"
599            fn teˇst() { println!(); }
600        "});
601
602        // Send diagnostic to client
603        let range = cx.text_anchor_range(indoc! {"
604            fn «test»() { println!(); }
605        "});
606        cx.update_buffer(|buffer, cx| {
607            let snapshot = buffer.text_snapshot();
608            let set = DiagnosticSet::from_sorted_entries(
609                vec![DiagnosticEntry {
610                    range,
611                    diagnostic: Diagnostic {
612                        message: "A test diagnostic message.".to_string(),
613                        ..Default::default()
614                    },
615                }],
616                &snapshot,
617            );
618            buffer.update_diagnostics(LanguageServerId(0), set, cx);
619        });
620
621        // Hover pops diagnostic immediately
622        cx.update_editor(|editor, cx| hover(editor, &Hover, cx));
623        cx.foreground().run_until_parked();
624
625        cx.editor(|Editor { hover_state, .. }, _| {
626            assert!(hover_state.diagnostic_popover.is_some() && hover_state.info_popover.is_none())
627        });
628
629        // Info Popover shows after request responded to
630        let range = cx.lsp_range(indoc! {"
631            fn «test»() { println!(); }
632        "});
633        cx.handle_request::<lsp::request::HoverRequest, _, _>(move |_, _, _| async move {
634            Ok(Some(lsp::Hover {
635                contents: lsp::HoverContents::Markup(lsp::MarkupContent {
636                    kind: lsp::MarkupKind::Markdown,
637                    value: indoc! {"
638                        # Some other basic docs
639                        Some other test documentation"}
640                    .to_string(),
641                }),
642                range: Some(range),
643            }))
644        });
645        cx.foreground()
646            .advance_clock(Duration::from_millis(HOVER_DELAY_MILLIS + 100));
647
648        cx.foreground().run_until_parked();
649        cx.editor(|Editor { hover_state, .. }, _| {
650            hover_state.diagnostic_popover.is_some() && hover_state.info_task.is_some()
651        });
652    }
653}