hover_popover.rs

   1use crate::{
   2    display_map::{InlayOffset, ToDisplayPoint},
   3    link_go_to_definition::{InlayHighlight, RangeInEditor},
   4    Anchor, AnchorRangeExt, DisplayPoint, Editor, EditorSettings, EditorSnapshot, EditorStyle,
   5    ExcerptId, Hover, RangeToAnchorExt,
   6};
   7use futures::FutureExt;
   8use gpui::{
   9    div, px, AnyElement, CursorStyle, Hsla, InteractiveElement, IntoElement, Model, MouseButton,
  10    ParentElement, Pixels, SharedString, Size, StatefulInteractiveElement, Styled, Task,
  11    ViewContext, WeakView,
  12};
  13use language::{markdown, Bias, DiagnosticEntry, Language, LanguageRegistry, ParsedMarkdown};
  14
  15use lsp::DiagnosticSeverity;
  16use project::{HoverBlock, HoverBlockKind, InlayHintLabelPart, Project};
  17use settings::Settings;
  18use std::{ops::Range, sync::Arc, time::Duration};
  19use ui::{prelude::*, Tooltip};
  20use util::TryFutureExt;
  21use workspace::Workspace;
  22
  23pub const HOVER_DELAY_MILLIS: u64 = 350;
  24pub const HOVER_REQUEST_DELAY_MILLIS: u64 = 200;
  25
  26pub const MIN_POPOVER_CHARACTER_WIDTH: f32 = 20.;
  27pub const MIN_POPOVER_LINE_HEIGHT: Pixels = px(4.);
  28pub const HOVER_POPOVER_GAP: Pixels = px(10.);
  29
  30/// Bindable action which uses the most recent selection head to trigger a hover
  31pub fn hover(editor: &mut Editor, _: &Hover, cx: &mut ViewContext<Editor>) {
  32    let head = editor.selections.newest_display(cx).head();
  33    show_hover(editor, head, true, cx);
  34}
  35
  36/// The internal hover action dispatches between `show_hover` or `hide_hover`
  37/// depending on whether a point to hover over is provided.
  38pub fn hover_at(editor: &mut Editor, point: Option<DisplayPoint>, cx: &mut ViewContext<Editor>) {
  39    if EditorSettings::get_global(cx).hover_popover_enabled {
  40        if let Some(point) = point {
  41            show_hover(editor, point, false, cx);
  42        } else {
  43            hide_hover(editor, cx);
  44        }
  45    }
  46}
  47
  48pub struct InlayHover {
  49    pub excerpt: ExcerptId,
  50    pub range: InlayHighlight,
  51    pub tooltip: HoverBlock,
  52}
  53
  54pub fn find_hovered_hint_part(
  55    label_parts: Vec<InlayHintLabelPart>,
  56    hint_start: InlayOffset,
  57    hovered_offset: InlayOffset,
  58) -> Option<(InlayHintLabelPart, Range<InlayOffset>)> {
  59    if hovered_offset >= hint_start {
  60        let mut hovered_character = (hovered_offset - hint_start).0;
  61        let mut part_start = hint_start;
  62        for part in label_parts {
  63            let part_len = part.value.chars().count();
  64            if hovered_character > part_len {
  65                hovered_character -= part_len;
  66                part_start.0 += part_len;
  67            } else {
  68                let part_end = InlayOffset(part_start.0 + part_len);
  69                return Some((part, part_start..part_end));
  70            }
  71        }
  72    }
  73    None
  74}
  75
  76pub fn hover_at_inlay(editor: &mut Editor, inlay_hover: InlayHover, cx: &mut ViewContext<Editor>) {
  77    if EditorSettings::get_global(cx).hover_popover_enabled {
  78        if editor.pending_rename.is_some() {
  79            return;
  80        }
  81
  82        let Some(project) = editor.project.clone() else {
  83            return;
  84        };
  85
  86        if let Some(InfoPopover { symbol_range, .. }) = &editor.hover_state.info_popover {
  87            if let RangeInEditor::Inlay(range) = symbol_range {
  88                if range == &inlay_hover.range {
  89                    // Hover triggered from same location as last time. Don't show again.
  90                    return;
  91                }
  92            }
  93            hide_hover(editor, cx);
  94        }
  95
  96        let task = cx.spawn(|this, mut cx| {
  97            async move {
  98                cx.background_executor()
  99                    .timer(Duration::from_millis(HOVER_DELAY_MILLIS))
 100                    .await;
 101                this.update(&mut cx, |this, _| {
 102                    this.hover_state.diagnostic_popover = None;
 103                })?;
 104
 105                let language_registry = project.update(&mut cx, |p, _| p.languages().clone())?;
 106                let blocks = vec![inlay_hover.tooltip];
 107                let parsed_content = parse_blocks(&blocks, &language_registry, None).await;
 108
 109                let hover_popover = InfoPopover {
 110                    project: project.clone(),
 111                    symbol_range: RangeInEditor::Inlay(inlay_hover.range.clone()),
 112                    blocks,
 113                    parsed_content,
 114                };
 115
 116                this.update(&mut cx, |this, cx| {
 117                    // Highlight the selected symbol using a background highlight
 118                    this.highlight_inlay_background::<HoverState>(
 119                        vec![inlay_hover.range],
 120                        |theme| theme.element_hover, // todo!("use a proper background here")
 121                        cx,
 122                    );
 123                    this.hover_state.info_popover = Some(hover_popover);
 124                    cx.notify();
 125                })?;
 126
 127                anyhow::Ok(())
 128            }
 129            .log_err()
 130        });
 131
 132        editor.hover_state.info_task = Some(task);
 133    }
 134}
 135
 136/// Hides the type information popup.
 137/// Triggered by the `Hover` action when the cursor is not over a symbol or when the
 138/// selections changed.
 139pub fn hide_hover(editor: &mut Editor, cx: &mut ViewContext<Editor>) -> bool {
 140    let did_hide = editor.hover_state.info_popover.take().is_some()
 141        | editor.hover_state.diagnostic_popover.take().is_some();
 142
 143    editor.hover_state.info_task = None;
 144    editor.hover_state.triggered_from = None;
 145
 146    editor.clear_background_highlights::<HoverState>(cx);
 147
 148    if did_hide {
 149        cx.notify();
 150    }
 151
 152    did_hide
 153}
 154
 155/// Queries the LSP and shows type info and documentation
 156/// about the symbol the mouse is currently hovering over.
 157/// Triggered by the `Hover` action when the cursor may be over a symbol.
 158fn show_hover(
 159    editor: &mut Editor,
 160    point: DisplayPoint,
 161    ignore_timeout: bool,
 162    cx: &mut ViewContext<Editor>,
 163) {
 164    if editor.pending_rename.is_some() {
 165        return;
 166    }
 167
 168    let snapshot = editor.snapshot(cx);
 169    let multibuffer_offset = point.to_offset(&snapshot.display_snapshot, Bias::Left);
 170
 171    let (buffer, buffer_position) = if let Some(output) = editor
 172        .buffer
 173        .read(cx)
 174        .text_anchor_for_position(multibuffer_offset, cx)
 175    {
 176        output
 177    } else {
 178        return;
 179    };
 180
 181    let excerpt_id = if let Some((excerpt_id, _, _)) = editor
 182        .buffer()
 183        .read(cx)
 184        .excerpt_containing(multibuffer_offset, cx)
 185    {
 186        excerpt_id
 187    } else {
 188        return;
 189    };
 190
 191    let project = if let Some(project) = editor.project.clone() {
 192        project
 193    } else {
 194        return;
 195    };
 196
 197    if !ignore_timeout {
 198        if let Some(InfoPopover { symbol_range, .. }) = &editor.hover_state.info_popover {
 199            if symbol_range
 200                .as_text_range()
 201                .map(|range| {
 202                    range
 203                        .to_offset(&snapshot.buffer_snapshot)
 204                        .contains(&multibuffer_offset)
 205                })
 206                .unwrap_or(false)
 207            {
 208                // Hover triggered from same location as last time. Don't show again.
 209                return;
 210            } else {
 211                hide_hover(editor, cx);
 212            }
 213        }
 214    }
 215
 216    // Get input anchor
 217    let anchor = snapshot
 218        .buffer_snapshot
 219        .anchor_at(multibuffer_offset, Bias::Left);
 220
 221    // Don't request again if the location is the same as the previous request
 222    if let Some(triggered_from) = &editor.hover_state.triggered_from {
 223        if triggered_from
 224            .cmp(&anchor, &snapshot.buffer_snapshot)
 225            .is_eq()
 226        {
 227            return;
 228        }
 229    }
 230
 231    let task = cx.spawn(|this, mut cx| {
 232        async move {
 233            // If we need to delay, delay a set amount initially before making the lsp request
 234            let delay = if !ignore_timeout {
 235                // Construct delay task to wait for later
 236                let total_delay = Some(
 237                    cx.background_executor()
 238                        .timer(Duration::from_millis(HOVER_DELAY_MILLIS)),
 239                );
 240
 241                cx.background_executor()
 242                    .timer(Duration::from_millis(HOVER_REQUEST_DELAY_MILLIS))
 243                    .await;
 244                total_delay
 245            } else {
 246                None
 247            };
 248
 249            // query the LSP for hover info
 250            let hover_request = cx.update(|cx| {
 251                project.update(cx, |project, cx| {
 252                    project.hover(&buffer, buffer_position, cx)
 253                })
 254            })?;
 255
 256            if let Some(delay) = delay {
 257                delay.await;
 258            }
 259
 260            // If there's a diagnostic, assign it on the hover state and notify
 261            let local_diagnostic = snapshot
 262                .buffer_snapshot
 263                .diagnostics_in_range::<_, usize>(multibuffer_offset..multibuffer_offset, false)
 264                // Find the entry with the most specific range
 265                .min_by_key(|entry| entry.range.end - entry.range.start)
 266                .map(|entry| DiagnosticEntry {
 267                    diagnostic: entry.diagnostic,
 268                    range: entry.range.to_anchors(&snapshot.buffer_snapshot),
 269                });
 270
 271            // Pull the primary diagnostic out so we can jump to it if the popover is clicked
 272            let primary_diagnostic = local_diagnostic.as_ref().and_then(|local_diagnostic| {
 273                snapshot
 274                    .buffer_snapshot
 275                    .diagnostic_group::<usize>(local_diagnostic.diagnostic.group_id)
 276                    .find(|diagnostic| diagnostic.diagnostic.is_primary)
 277                    .map(|entry| DiagnosticEntry {
 278                        diagnostic: entry.diagnostic,
 279                        range: entry.range.to_anchors(&snapshot.buffer_snapshot),
 280                    })
 281            });
 282
 283            this.update(&mut cx, |this, _| {
 284                this.hover_state.diagnostic_popover =
 285                    local_diagnostic.map(|local_diagnostic| DiagnosticPopover {
 286                        local_diagnostic,
 287                        primary_diagnostic,
 288                    });
 289            })?;
 290
 291            let hover_result = hover_request.await.ok().flatten();
 292            let hover_popover = match hover_result {
 293                Some(hover_result) if !hover_result.is_empty() => {
 294                    // Create symbol range of anchors for highlighting and filtering of future requests.
 295                    let range = if let Some(range) = hover_result.range {
 296                        let start = snapshot
 297                            .buffer_snapshot
 298                            .anchor_in_excerpt(excerpt_id.clone(), range.start);
 299                        let end = snapshot
 300                            .buffer_snapshot
 301                            .anchor_in_excerpt(excerpt_id.clone(), range.end);
 302
 303                        start..end
 304                    } else {
 305                        anchor..anchor
 306                    };
 307
 308                    let language_registry =
 309                        project.update(&mut cx, |p, _| p.languages().clone())?;
 310                    let blocks = hover_result.contents;
 311                    let language = hover_result.language;
 312                    let parsed_content = parse_blocks(&blocks, &language_registry, language).await;
 313
 314                    Some(InfoPopover {
 315                        project: project.clone(),
 316                        symbol_range: RangeInEditor::Text(range),
 317                        blocks,
 318                        parsed_content,
 319                    })
 320                }
 321
 322                _ => None,
 323            };
 324
 325            this.update(&mut cx, |this, cx| {
 326                if let Some(symbol_range) = hover_popover
 327                    .as_ref()
 328                    .and_then(|hover_popover| hover_popover.symbol_range.as_text_range())
 329                {
 330                    // Highlight the selected symbol using a background highlight
 331                    this.highlight_background::<HoverState>(
 332                        vec![symbol_range],
 333                        |theme| theme.element_hover, // todo! update theme
 334                        cx,
 335                    );
 336                } else {
 337                    this.clear_background_highlights::<HoverState>(cx);
 338                }
 339
 340                this.hover_state.info_popover = hover_popover;
 341                cx.notify();
 342                cx.refresh();
 343            })?;
 344
 345            Ok::<_, anyhow::Error>(())
 346        }
 347        .log_err()
 348    });
 349
 350    editor.hover_state.info_task = Some(task);
 351}
 352
 353async fn parse_blocks(
 354    blocks: &[HoverBlock],
 355    language_registry: &Arc<LanguageRegistry>,
 356    language: Option<Arc<Language>>,
 357) -> markdown::ParsedMarkdown {
 358    let mut text = String::new();
 359    let mut highlights = Vec::new();
 360    let mut region_ranges = Vec::new();
 361    let mut regions = Vec::new();
 362
 363    for block in blocks {
 364        match &block.kind {
 365            HoverBlockKind::PlainText => {
 366                markdown::new_paragraph(&mut text, &mut Vec::new());
 367                text.push_str(&block.text);
 368            }
 369
 370            HoverBlockKind::Markdown => {
 371                markdown::parse_markdown_block(
 372                    &block.text,
 373                    language_registry,
 374                    language.clone(),
 375                    &mut text,
 376                    &mut highlights,
 377                    &mut region_ranges,
 378                    &mut regions,
 379                )
 380                .await
 381            }
 382
 383            HoverBlockKind::Code { language } => {
 384                if let Some(language) = language_registry
 385                    .language_for_name(language)
 386                    .now_or_never()
 387                    .and_then(Result::ok)
 388                {
 389                    markdown::highlight_code(&mut text, &mut highlights, &block.text, &language);
 390                } else {
 391                    text.push_str(&block.text);
 392                }
 393            }
 394        }
 395    }
 396
 397    ParsedMarkdown {
 398        text: text.trim().to_string(),
 399        highlights,
 400        region_ranges,
 401        regions,
 402    }
 403}
 404
 405#[derive(Default)]
 406pub struct HoverState {
 407    pub info_popover: Option<InfoPopover>,
 408    pub diagnostic_popover: Option<DiagnosticPopover>,
 409    pub triggered_from: Option<Anchor>,
 410    pub info_task: Option<Task<Option<()>>>,
 411}
 412
 413impl HoverState {
 414    pub fn visible(&self) -> bool {
 415        self.info_popover.is_some() || self.diagnostic_popover.is_some()
 416    }
 417
 418    pub fn render(
 419        &mut self,
 420        snapshot: &EditorSnapshot,
 421        style: &EditorStyle,
 422        visible_rows: Range<u32>,
 423        max_size: Size<Pixels>,
 424        workspace: Option<WeakView<Workspace>>,
 425        cx: &mut ViewContext<Editor>,
 426    ) -> Option<(DisplayPoint, Vec<AnyElement>)> {
 427        // If there is a diagnostic, position the popovers based on that.
 428        // Otherwise use the start of the hover range
 429        let anchor = self
 430            .diagnostic_popover
 431            .as_ref()
 432            .map(|diagnostic_popover| &diagnostic_popover.local_diagnostic.range.start)
 433            .or_else(|| {
 434                self.info_popover
 435                    .as_ref()
 436                    .map(|info_popover| match &info_popover.symbol_range {
 437                        RangeInEditor::Text(range) => &range.start,
 438                        RangeInEditor::Inlay(range) => &range.inlay_position,
 439                    })
 440            })?;
 441        let point = anchor.to_display_point(&snapshot.display_snapshot);
 442
 443        // Don't render if the relevant point isn't on screen
 444        if !self.visible() || !visible_rows.contains(&point.row()) {
 445            return None;
 446        }
 447
 448        let mut elements = Vec::new();
 449
 450        if let Some(diagnostic_popover) = self.diagnostic_popover.as_ref() {
 451            elements.push(diagnostic_popover.render(style, max_size, cx));
 452        }
 453        if let Some(info_popover) = self.info_popover.as_mut() {
 454            elements.push(info_popover.render(style, max_size, workspace, cx));
 455        }
 456
 457        Some((point, elements))
 458    }
 459}
 460
 461#[derive(Debug, Clone)]
 462pub struct InfoPopover {
 463    pub project: Model<Project>,
 464    symbol_range: RangeInEditor,
 465    pub blocks: Vec<HoverBlock>,
 466    parsed_content: ParsedMarkdown,
 467}
 468
 469impl InfoPopover {
 470    pub fn render(
 471        &mut self,
 472        style: &EditorStyle,
 473        max_size: Size<Pixels>,
 474        workspace: Option<WeakView<Workspace>>,
 475        cx: &mut ViewContext<Editor>,
 476    ) -> AnyElement {
 477        div()
 478            .id("info_popover")
 479            .elevation_2(cx)
 480            .p_2()
 481            .overflow_y_scroll()
 482            .max_w(max_size.width)
 483            .max_h(max_size.height)
 484            // Prevent a mouse move on the popover from being propagated to the editor,
 485            // because that would dismiss the popover.
 486            .on_mouse_move(|_, cx| cx.stop_propagation())
 487            .child(crate::render_parsed_markdown(
 488                "content",
 489                &self.parsed_content,
 490                style,
 491                workspace,
 492                cx,
 493            ))
 494            .into_any_element()
 495    }
 496}
 497
 498#[derive(Debug, Clone)]
 499pub struct DiagnosticPopover {
 500    local_diagnostic: DiagnosticEntry<Anchor>,
 501    primary_diagnostic: Option<DiagnosticEntry<Anchor>>,
 502}
 503
 504impl DiagnosticPopover {
 505    pub fn render(
 506        &self,
 507        style: &EditorStyle,
 508        max_size: Size<Pixels>,
 509        cx: &mut ViewContext<Editor>,
 510    ) -> AnyElement {
 511        let text = match &self.local_diagnostic.diagnostic.source {
 512            Some(source) => format!("{source}: {}", self.local_diagnostic.diagnostic.message),
 513            None => self.local_diagnostic.diagnostic.message.clone(),
 514        };
 515
 516        let status_colors = cx.theme().status();
 517
 518        struct DiagnosticColors {
 519            pub background: Hsla,
 520            pub border: Hsla,
 521        }
 522
 523        let diagnostic_colors = match self.local_diagnostic.diagnostic.severity {
 524            DiagnosticSeverity::ERROR => DiagnosticColors {
 525                background: status_colors.error_background,
 526                border: status_colors.error_border,
 527            },
 528            DiagnosticSeverity::WARNING => DiagnosticColors {
 529                background: status_colors.warning_background,
 530                border: status_colors.warning_border,
 531            },
 532            DiagnosticSeverity::INFORMATION => DiagnosticColors {
 533                background: status_colors.info_background,
 534                border: status_colors.info_border,
 535            },
 536            DiagnosticSeverity::HINT => DiagnosticColors {
 537                background: status_colors.hint_background,
 538                border: status_colors.hint_border,
 539            },
 540            _ => DiagnosticColors {
 541                background: status_colors.ignored_background,
 542                border: status_colors.ignored_border,
 543            },
 544        };
 545
 546        div()
 547            .id("diagnostic")
 548            .elevation_2(cx)
 549            .overflow_y_scroll()
 550            .px_2()
 551            .py_1()
 552            .bg(diagnostic_colors.background)
 553            .text_color(style.text.color)
 554            .border_1()
 555            .border_color(diagnostic_colors.border)
 556            .rounded_md()
 557            .max_w(max_size.width)
 558            .max_h(max_size.height)
 559            .cursor(CursorStyle::PointingHand)
 560            .tooltip(move |cx| Tooltip::for_action("Go To Diagnostic", &crate::GoToDiagnostic, cx))
 561            // Prevent a mouse move on the popover from being propagated to the editor,
 562            // because that would dismiss the popover.
 563            .on_mouse_move(|_, cx| cx.stop_propagation())
 564            // Prevent a mouse down on the popover from being propagated to the editor,
 565            // because that would move the cursor.
 566            .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
 567            .on_click(cx.listener(|editor, _, cx| editor.go_to_diagnostic(&Default::default(), cx)))
 568            .child(SharedString::from(text))
 569            .into_any_element()
 570    }
 571
 572    pub fn activation_info(&self) -> (usize, Anchor) {
 573        let entry = self
 574            .primary_diagnostic
 575            .as_ref()
 576            .unwrap_or(&self.local_diagnostic);
 577
 578        (entry.diagnostic.group_id, entry.range.start.clone())
 579    }
 580}
 581
 582#[cfg(test)]
 583mod tests {
 584    use super::*;
 585    use crate::{
 586        editor_tests::init_test,
 587        element::PointForPosition,
 588        inlay_hint_cache::tests::{cached_hint_labels, visible_hint_labels},
 589        link_go_to_definition::update_inlay_link_and_hover_points,
 590        test::editor_lsp_test_context::EditorLspTestContext,
 591        InlayId,
 592    };
 593    use collections::BTreeSet;
 594    use gpui::{FontWeight, HighlightStyle, UnderlineStyle};
 595    use indoc::indoc;
 596    use language::{language_settings::InlayHintSettings, Diagnostic, DiagnosticSet};
 597    use lsp::LanguageServerId;
 598    use project::{HoverBlock, HoverBlockKind};
 599    use smol::stream::StreamExt;
 600    use unindent::Unindent;
 601    use util::test::marked_text_ranges;
 602
 603    #[gpui::test]
 604    async fn test_mouse_hover_info_popover(cx: &mut gpui::TestAppContext) {
 605        init_test(cx, |_| {});
 606
 607        let mut cx = EditorLspTestContext::new_rust(
 608            lsp::ServerCapabilities {
 609                hover_provider: Some(lsp::HoverProviderCapability::Simple(true)),
 610                ..Default::default()
 611            },
 612            cx,
 613        )
 614        .await;
 615
 616        // Basic hover delays and then pops without moving the mouse
 617        cx.set_state(indoc! {"
 618            fn ˇtest() { println!(); }
 619        "});
 620        let hover_point = cx.display_point(indoc! {"
 621            fn test() { printˇln!(); }
 622        "});
 623
 624        cx.update_editor(|editor, cx| hover_at(editor, Some(hover_point), cx));
 625        assert!(!cx.editor(|editor, _| editor.hover_state.visible()));
 626
 627        // After delay, hover should be visible.
 628        let symbol_range = cx.lsp_range(indoc! {"
 629            fn test() { «println!»(); }
 630        "});
 631        let mut requests =
 632            cx.handle_request::<lsp::request::HoverRequest, _, _>(move |_, _, _| async move {
 633                Ok(Some(lsp::Hover {
 634                    contents: lsp::HoverContents::Markup(lsp::MarkupContent {
 635                        kind: lsp::MarkupKind::Markdown,
 636                        value: "some basic docs".to_string(),
 637                    }),
 638                    range: Some(symbol_range),
 639                }))
 640            });
 641        cx.background_executor
 642            .advance_clock(Duration::from_millis(HOVER_DELAY_MILLIS + 100));
 643        requests.next().await;
 644
 645        cx.editor(|editor, _| {
 646            assert!(editor.hover_state.visible());
 647            assert_eq!(
 648                editor.hover_state.info_popover.clone().unwrap().blocks,
 649                vec![HoverBlock {
 650                    text: "some basic docs".to_string(),
 651                    kind: HoverBlockKind::Markdown,
 652                },]
 653            )
 654        });
 655
 656        // Mouse moved with no hover response dismisses
 657        let hover_point = cx.display_point(indoc! {"
 658            fn teˇst() { println!(); }
 659        "});
 660        let mut request = cx
 661            .lsp
 662            .handle_request::<lsp::request::HoverRequest, _, _>(|_, _| async move { Ok(None) });
 663        cx.update_editor(|editor, cx| hover_at(editor, Some(hover_point), cx));
 664        cx.background_executor
 665            .advance_clock(Duration::from_millis(HOVER_DELAY_MILLIS + 100));
 666        request.next().await;
 667        cx.editor(|editor, _| {
 668            assert!(!editor.hover_state.visible());
 669        });
 670    }
 671
 672    #[gpui::test]
 673    async fn test_keyboard_hover_info_popover(cx: &mut gpui::TestAppContext) {
 674        init_test(cx, |_| {});
 675
 676        let mut cx = EditorLspTestContext::new_rust(
 677            lsp::ServerCapabilities {
 678                hover_provider: Some(lsp::HoverProviderCapability::Simple(true)),
 679                ..Default::default()
 680            },
 681            cx,
 682        )
 683        .await;
 684
 685        // Hover with keyboard has no delay
 686        cx.set_state(indoc! {"
 687            fˇn test() { println!(); }
 688        "});
 689        cx.update_editor(|editor, cx| hover(editor, &Hover, cx));
 690        let symbol_range = cx.lsp_range(indoc! {"
 691            «fn» test() { println!(); }
 692        "});
 693        cx.handle_request::<lsp::request::HoverRequest, _, _>(move |_, _, _| async move {
 694            Ok(Some(lsp::Hover {
 695                contents: lsp::HoverContents::Markup(lsp::MarkupContent {
 696                    kind: lsp::MarkupKind::Markdown,
 697                    value: "some other basic docs".to_string(),
 698                }),
 699                range: Some(symbol_range),
 700            }))
 701        })
 702        .next()
 703        .await;
 704
 705        cx.condition(|editor, _| editor.hover_state.visible()).await;
 706        cx.editor(|editor, _| {
 707            assert_eq!(
 708                editor.hover_state.info_popover.clone().unwrap().blocks,
 709                vec![HoverBlock {
 710                    text: "some other basic docs".to_string(),
 711                    kind: HoverBlockKind::Markdown,
 712                }]
 713            )
 714        });
 715    }
 716
 717    #[gpui::test]
 718    async fn test_empty_hovers_filtered(cx: &mut gpui::TestAppContext) {
 719        init_test(cx, |_| {});
 720
 721        let mut cx = EditorLspTestContext::new_rust(
 722            lsp::ServerCapabilities {
 723                hover_provider: Some(lsp::HoverProviderCapability::Simple(true)),
 724                ..Default::default()
 725            },
 726            cx,
 727        )
 728        .await;
 729
 730        // Hover with keyboard has no delay
 731        cx.set_state(indoc! {"
 732            fˇn test() { println!(); }
 733        "});
 734        cx.update_editor(|editor, cx| hover(editor, &Hover, cx));
 735        let symbol_range = cx.lsp_range(indoc! {"
 736            «fn» test() { println!(); }
 737        "});
 738        cx.handle_request::<lsp::request::HoverRequest, _, _>(move |_, _, _| async move {
 739            Ok(Some(lsp::Hover {
 740                contents: lsp::HoverContents::Array(vec![
 741                    lsp::MarkedString::String("regular text for hover to show".to_string()),
 742                    lsp::MarkedString::String("".to_string()),
 743                    lsp::MarkedString::LanguageString(lsp::LanguageString {
 744                        language: "Rust".to_string(),
 745                        value: "".to_string(),
 746                    }),
 747                ]),
 748                range: Some(symbol_range),
 749            }))
 750        })
 751        .next()
 752        .await;
 753
 754        cx.condition(|editor, _| editor.hover_state.visible()).await;
 755        cx.editor(|editor, _| {
 756            assert_eq!(
 757                editor.hover_state.info_popover.clone().unwrap().blocks,
 758                vec![HoverBlock {
 759                    text: "regular text for hover to show".to_string(),
 760                    kind: HoverBlockKind::Markdown,
 761                }],
 762                "No empty string hovers should be shown"
 763            );
 764        });
 765    }
 766
 767    #[gpui::test]
 768    async fn test_line_ends_trimmed(cx: &mut gpui::TestAppContext) {
 769        init_test(cx, |_| {});
 770
 771        let mut cx = EditorLspTestContext::new_rust(
 772            lsp::ServerCapabilities {
 773                hover_provider: Some(lsp::HoverProviderCapability::Simple(true)),
 774                ..Default::default()
 775            },
 776            cx,
 777        )
 778        .await;
 779
 780        // Hover with keyboard has no delay
 781        cx.set_state(indoc! {"
 782            fˇn test() { println!(); }
 783        "});
 784        cx.update_editor(|editor, cx| hover(editor, &Hover, cx));
 785        let symbol_range = cx.lsp_range(indoc! {"
 786            «fn» test() { println!(); }
 787        "});
 788
 789        let code_str = "\nlet hovered_point: Vector2F // size = 8, align = 0x4\n";
 790        let markdown_string = format!("\n```rust\n{code_str}```");
 791
 792        let closure_markdown_string = markdown_string.clone();
 793        cx.handle_request::<lsp::request::HoverRequest, _, _>(move |_, _, _| {
 794            let future_markdown_string = closure_markdown_string.clone();
 795            async move {
 796                Ok(Some(lsp::Hover {
 797                    contents: lsp::HoverContents::Markup(lsp::MarkupContent {
 798                        kind: lsp::MarkupKind::Markdown,
 799                        value: future_markdown_string,
 800                    }),
 801                    range: Some(symbol_range),
 802                }))
 803            }
 804        })
 805        .next()
 806        .await;
 807
 808        cx.condition(|editor, _| editor.hover_state.visible()).await;
 809        cx.editor(|editor, _| {
 810            let blocks = editor.hover_state.info_popover.clone().unwrap().blocks;
 811            assert_eq!(
 812                blocks,
 813                vec![HoverBlock {
 814                    text: markdown_string,
 815                    kind: HoverBlockKind::Markdown,
 816                }],
 817            );
 818
 819            let rendered = smol::block_on(parse_blocks(&blocks, &Default::default(), None));
 820            assert_eq!(
 821                rendered.text,
 822                code_str.trim(),
 823                "Should not have extra line breaks at end of rendered hover"
 824            );
 825        });
 826    }
 827
 828    #[gpui::test]
 829    async fn test_hover_diagnostic_and_info_popovers(cx: &mut gpui::TestAppContext) {
 830        init_test(cx, |_| {});
 831
 832        let mut cx = EditorLspTestContext::new_rust(
 833            lsp::ServerCapabilities {
 834                hover_provider: Some(lsp::HoverProviderCapability::Simple(true)),
 835                ..Default::default()
 836            },
 837            cx,
 838        )
 839        .await;
 840
 841        // Hover with just diagnostic, pops DiagnosticPopover immediately and then
 842        // info popover once request completes
 843        cx.set_state(indoc! {"
 844            fn teˇst() { println!(); }
 845        "});
 846
 847        // Send diagnostic to client
 848        let range = cx.text_anchor_range(indoc! {"
 849            fn «test»() { println!(); }
 850        "});
 851        cx.update_buffer(|buffer, cx| {
 852            let snapshot = buffer.text_snapshot();
 853            let set = DiagnosticSet::from_sorted_entries(
 854                vec![DiagnosticEntry {
 855                    range,
 856                    diagnostic: Diagnostic {
 857                        message: "A test diagnostic message.".to_string(),
 858                        ..Default::default()
 859                    },
 860                }],
 861                &snapshot,
 862            );
 863            buffer.update_diagnostics(LanguageServerId(0), set, cx);
 864        });
 865
 866        // Hover pops diagnostic immediately
 867        cx.update_editor(|editor, cx| hover(editor, &Hover, cx));
 868        cx.background_executor.run_until_parked();
 869
 870        cx.editor(|Editor { hover_state, .. }, _| {
 871            assert!(hover_state.diagnostic_popover.is_some() && hover_state.info_popover.is_none())
 872        });
 873
 874        // Info Popover shows after request responded to
 875        let range = cx.lsp_range(indoc! {"
 876            fn «test»() { println!(); }
 877        "});
 878        cx.handle_request::<lsp::request::HoverRequest, _, _>(move |_, _, _| async move {
 879            Ok(Some(lsp::Hover {
 880                contents: lsp::HoverContents::Markup(lsp::MarkupContent {
 881                    kind: lsp::MarkupKind::Markdown,
 882                    value: "some new docs".to_string(),
 883                }),
 884                range: Some(range),
 885            }))
 886        });
 887        cx.background_executor
 888            .advance_clock(Duration::from_millis(HOVER_DELAY_MILLIS + 100));
 889
 890        cx.background_executor.run_until_parked();
 891        cx.editor(|Editor { hover_state, .. }, _| {
 892            hover_state.diagnostic_popover.is_some() && hover_state.info_task.is_some()
 893        });
 894    }
 895
 896    #[gpui::test]
 897    fn test_render_blocks(cx: &mut gpui::TestAppContext) {
 898        init_test(cx, |_| {});
 899
 900        let editor = cx.add_window(|cx| Editor::single_line(cx));
 901        editor
 902            .update(cx, |editor, _cx| {
 903                let style = editor.style.clone().unwrap();
 904
 905                struct Row {
 906                    blocks: Vec<HoverBlock>,
 907                    expected_marked_text: String,
 908                    expected_styles: Vec<HighlightStyle>,
 909                }
 910
 911                let rows = &[
 912                    // Strong emphasis
 913                    Row {
 914                        blocks: vec![HoverBlock {
 915                            text: "one **two** three".to_string(),
 916                            kind: HoverBlockKind::Markdown,
 917                        }],
 918                        expected_marked_text: "one «two» three".to_string(),
 919                        expected_styles: vec![HighlightStyle {
 920                            font_weight: Some(FontWeight::BOLD),
 921                            ..Default::default()
 922                        }],
 923                    },
 924                    // Links
 925                    Row {
 926                        blocks: vec![HoverBlock {
 927                            text: "one [two](https://the-url) three".to_string(),
 928                            kind: HoverBlockKind::Markdown,
 929                        }],
 930                        expected_marked_text: "one «two» three".to_string(),
 931                        expected_styles: vec![HighlightStyle {
 932                            underline: Some(UnderlineStyle {
 933                                thickness: 1.0.into(),
 934                                ..Default::default()
 935                            }),
 936                            ..Default::default()
 937                        }],
 938                    },
 939                    // Lists
 940                    Row {
 941                        blocks: vec![HoverBlock {
 942                            text: "
 943                            lists:
 944                            * one
 945                                - a
 946                                - b
 947                            * two
 948                                - [c](https://the-url)
 949                                - d"
 950                            .unindent(),
 951                            kind: HoverBlockKind::Markdown,
 952                        }],
 953                        expected_marked_text: "
 954                        lists:
 955                        - one
 956                          - a
 957                          - b
 958                        - two
 959                          - «c»
 960                          - d"
 961                        .unindent(),
 962                        expected_styles: vec![HighlightStyle {
 963                            underline: Some(UnderlineStyle {
 964                                thickness: 1.0.into(),
 965                                ..Default::default()
 966                            }),
 967                            ..Default::default()
 968                        }],
 969                    },
 970                    // Multi-paragraph list items
 971                    Row {
 972                        blocks: vec![HoverBlock {
 973                            text: "
 974                            * one two
 975                              three
 976
 977                            * four five
 978                                * six seven
 979                                  eight
 980
 981                                  nine
 982                                * ten
 983                            * six"
 984                                .unindent(),
 985                            kind: HoverBlockKind::Markdown,
 986                        }],
 987                        expected_marked_text: "
 988                        - one two three
 989                        - four five
 990                          - six seven eight
 991
 992                            nine
 993                          - ten
 994                        - six"
 995                            .unindent(),
 996                        expected_styles: vec![HighlightStyle {
 997                            underline: Some(UnderlineStyle {
 998                                thickness: 1.0.into(),
 999                                ..Default::default()
1000                            }),
1001                            ..Default::default()
1002                        }],
1003                    },
1004                ];
1005
1006                for Row {
1007                    blocks,
1008                    expected_marked_text,
1009                    expected_styles,
1010                } in &rows[0..]
1011                {
1012                    let rendered = smol::block_on(parse_blocks(&blocks, &Default::default(), None));
1013
1014                    let (expected_text, ranges) = marked_text_ranges(expected_marked_text, false);
1015                    let expected_highlights = ranges
1016                        .into_iter()
1017                        .zip(expected_styles.iter().cloned())
1018                        .collect::<Vec<_>>();
1019                    assert_eq!(
1020                        rendered.text, expected_text,
1021                        "wrong text for input {blocks:?}"
1022                    );
1023
1024                    let rendered_highlights: Vec<_> = rendered
1025                        .highlights
1026                        .iter()
1027                        .filter_map(|(range, highlight)| {
1028                            let highlight = highlight.to_highlight_style(&style.syntax)?;
1029                            Some((range.clone(), highlight))
1030                        })
1031                        .collect();
1032
1033                    assert_eq!(
1034                        rendered_highlights, expected_highlights,
1035                        "wrong highlights for input {blocks:?}"
1036                    );
1037                }
1038            })
1039            .unwrap();
1040    }
1041
1042    #[gpui::test]
1043    async fn test_hover_inlay_label_parts(cx: &mut gpui::TestAppContext) {
1044        init_test(cx, |settings| {
1045            settings.defaults.inlay_hints = Some(InlayHintSettings {
1046                enabled: true,
1047                show_type_hints: true,
1048                show_parameter_hints: true,
1049                show_other_hints: true,
1050            })
1051        });
1052
1053        let mut cx = EditorLspTestContext::new_rust(
1054            lsp::ServerCapabilities {
1055                inlay_hint_provider: Some(lsp::OneOf::Right(
1056                    lsp::InlayHintServerCapabilities::Options(lsp::InlayHintOptions {
1057                        resolve_provider: Some(true),
1058                        ..Default::default()
1059                    }),
1060                )),
1061                ..Default::default()
1062            },
1063            cx,
1064        )
1065        .await;
1066
1067        cx.set_state(indoc! {"
1068            struct TestStruct;
1069
1070            // ==================
1071
1072            struct TestNewType<T>(T);
1073
1074            fn main() {
1075                let variableˇ = TestNewType(TestStruct);
1076            }
1077        "});
1078
1079        let hint_start_offset = cx.ranges(indoc! {"
1080            struct TestStruct;
1081
1082            // ==================
1083
1084            struct TestNewType<T>(T);
1085
1086            fn main() {
1087                let variableˇ = TestNewType(TestStruct);
1088            }
1089        "})[0]
1090            .start;
1091        let hint_position = cx.to_lsp(hint_start_offset);
1092        let new_type_target_range = cx.lsp_range(indoc! {"
1093            struct TestStruct;
1094
1095            // ==================
1096
1097            struct «TestNewType»<T>(T);
1098
1099            fn main() {
1100                let variable = TestNewType(TestStruct);
1101            }
1102        "});
1103        let struct_target_range = cx.lsp_range(indoc! {"
1104            struct «TestStruct»;
1105
1106            // ==================
1107
1108            struct TestNewType<T>(T);
1109
1110            fn main() {
1111                let variable = TestNewType(TestStruct);
1112            }
1113        "});
1114
1115        let uri = cx.buffer_lsp_url.clone();
1116        let new_type_label = "TestNewType";
1117        let struct_label = "TestStruct";
1118        let entire_hint_label = ": TestNewType<TestStruct>";
1119        let closure_uri = uri.clone();
1120        cx.lsp
1121            .handle_request::<lsp::request::InlayHintRequest, _, _>(move |params, _| {
1122                let task_uri = closure_uri.clone();
1123                async move {
1124                    assert_eq!(params.text_document.uri, task_uri);
1125                    Ok(Some(vec![lsp::InlayHint {
1126                        position: hint_position,
1127                        label: lsp::InlayHintLabel::LabelParts(vec![lsp::InlayHintLabelPart {
1128                            value: entire_hint_label.to_string(),
1129                            ..Default::default()
1130                        }]),
1131                        kind: Some(lsp::InlayHintKind::TYPE),
1132                        text_edits: None,
1133                        tooltip: None,
1134                        padding_left: Some(false),
1135                        padding_right: Some(false),
1136                        data: None,
1137                    }]))
1138                }
1139            })
1140            .next()
1141            .await;
1142        cx.background_executor.run_until_parked();
1143        cx.update_editor(|editor, cx| {
1144            let expected_layers = vec![entire_hint_label.to_string()];
1145            assert_eq!(expected_layers, cached_hint_labels(editor));
1146            assert_eq!(expected_layers, visible_hint_labels(editor, cx));
1147        });
1148
1149        let inlay_range = cx
1150            .ranges(indoc! {"
1151                struct TestStruct;
1152
1153                // ==================
1154
1155                struct TestNewType<T>(T);
1156
1157                fn main() {
1158                    let variable« »= TestNewType(TestStruct);
1159                }
1160        "})
1161            .get(0)
1162            .cloned()
1163            .unwrap();
1164        let new_type_hint_part_hover_position = cx.update_editor(|editor, cx| {
1165            let snapshot = editor.snapshot(cx);
1166            let previous_valid = inlay_range.start.to_display_point(&snapshot);
1167            let next_valid = inlay_range.end.to_display_point(&snapshot);
1168            assert_eq!(previous_valid.row(), next_valid.row());
1169            assert!(previous_valid.column() < next_valid.column());
1170            let exact_unclipped = DisplayPoint::new(
1171                previous_valid.row(),
1172                previous_valid.column()
1173                    + (entire_hint_label.find(new_type_label).unwrap() + new_type_label.len() / 2)
1174                        as u32,
1175            );
1176            PointForPosition {
1177                previous_valid,
1178                next_valid,
1179                exact_unclipped,
1180                column_overshoot_after_line_end: 0,
1181            }
1182        });
1183        cx.update_editor(|editor, cx| {
1184            update_inlay_link_and_hover_points(
1185                &editor.snapshot(cx),
1186                new_type_hint_part_hover_position,
1187                editor,
1188                true,
1189                false,
1190                cx,
1191            );
1192        });
1193
1194        let resolve_closure_uri = uri.clone();
1195        cx.lsp
1196            .handle_request::<lsp::request::InlayHintResolveRequest, _, _>(
1197                move |mut hint_to_resolve, _| {
1198                    let mut resolved_hint_positions = BTreeSet::new();
1199                    let task_uri = resolve_closure_uri.clone();
1200                    async move {
1201                        let inserted = resolved_hint_positions.insert(hint_to_resolve.position);
1202                        assert!(inserted, "Hint {hint_to_resolve:?} was resolved twice");
1203
1204                        // `: TestNewType<TestStruct>`
1205                        hint_to_resolve.label = lsp::InlayHintLabel::LabelParts(vec![
1206                            lsp::InlayHintLabelPart {
1207                                value: ": ".to_string(),
1208                                ..Default::default()
1209                            },
1210                            lsp::InlayHintLabelPart {
1211                                value: new_type_label.to_string(),
1212                                location: Some(lsp::Location {
1213                                    uri: task_uri.clone(),
1214                                    range: new_type_target_range,
1215                                }),
1216                                tooltip: Some(lsp::InlayHintLabelPartTooltip::String(format!(
1217                                    "A tooltip for `{new_type_label}`"
1218                                ))),
1219                                ..Default::default()
1220                            },
1221                            lsp::InlayHintLabelPart {
1222                                value: "<".to_string(),
1223                                ..Default::default()
1224                            },
1225                            lsp::InlayHintLabelPart {
1226                                value: struct_label.to_string(),
1227                                location: Some(lsp::Location {
1228                                    uri: task_uri,
1229                                    range: struct_target_range,
1230                                }),
1231                                tooltip: Some(lsp::InlayHintLabelPartTooltip::MarkupContent(
1232                                    lsp::MarkupContent {
1233                                        kind: lsp::MarkupKind::Markdown,
1234                                        value: format!("A tooltip for `{struct_label}`"),
1235                                    },
1236                                )),
1237                                ..Default::default()
1238                            },
1239                            lsp::InlayHintLabelPart {
1240                                value: ">".to_string(),
1241                                ..Default::default()
1242                            },
1243                        ]);
1244
1245                        Ok(hint_to_resolve)
1246                    }
1247                },
1248            )
1249            .next()
1250            .await;
1251        cx.background_executor.run_until_parked();
1252
1253        cx.update_editor(|editor, cx| {
1254            update_inlay_link_and_hover_points(
1255                &editor.snapshot(cx),
1256                new_type_hint_part_hover_position,
1257                editor,
1258                true,
1259                false,
1260                cx,
1261            );
1262        });
1263        cx.background_executor
1264            .advance_clock(Duration::from_millis(HOVER_DELAY_MILLIS + 100));
1265        cx.background_executor.run_until_parked();
1266        cx.update_editor(|editor, cx| {
1267            let hover_state = &editor.hover_state;
1268            assert!(hover_state.diagnostic_popover.is_none() && hover_state.info_popover.is_some());
1269            let popover = hover_state.info_popover.as_ref().unwrap();
1270            let buffer_snapshot = editor.buffer().update(cx, |buffer, cx| buffer.snapshot(cx));
1271            assert_eq!(
1272                popover.symbol_range,
1273                RangeInEditor::Inlay(InlayHighlight {
1274                    inlay: InlayId::Hint(0),
1275                    inlay_position: buffer_snapshot.anchor_at(inlay_range.start, Bias::Right),
1276                    range: ": ".len()..": ".len() + new_type_label.len(),
1277                }),
1278                "Popover range should match the new type label part"
1279            );
1280            assert_eq!(
1281                popover.parsed_content.text,
1282                format!("A tooltip for `{new_type_label}`"),
1283                "Rendered text should not anyhow alter backticks"
1284            );
1285        });
1286
1287        let struct_hint_part_hover_position = cx.update_editor(|editor, cx| {
1288            let snapshot = editor.snapshot(cx);
1289            let previous_valid = inlay_range.start.to_display_point(&snapshot);
1290            let next_valid = inlay_range.end.to_display_point(&snapshot);
1291            assert_eq!(previous_valid.row(), next_valid.row());
1292            assert!(previous_valid.column() < next_valid.column());
1293            let exact_unclipped = DisplayPoint::new(
1294                previous_valid.row(),
1295                previous_valid.column()
1296                    + (entire_hint_label.find(struct_label).unwrap() + struct_label.len() / 2)
1297                        as u32,
1298            );
1299            PointForPosition {
1300                previous_valid,
1301                next_valid,
1302                exact_unclipped,
1303                column_overshoot_after_line_end: 0,
1304            }
1305        });
1306        cx.update_editor(|editor, cx| {
1307            update_inlay_link_and_hover_points(
1308                &editor.snapshot(cx),
1309                struct_hint_part_hover_position,
1310                editor,
1311                true,
1312                false,
1313                cx,
1314            );
1315        });
1316        cx.background_executor
1317            .advance_clock(Duration::from_millis(HOVER_DELAY_MILLIS + 100));
1318        cx.background_executor.run_until_parked();
1319        cx.update_editor(|editor, cx| {
1320            let hover_state = &editor.hover_state;
1321            assert!(hover_state.diagnostic_popover.is_none() && hover_state.info_popover.is_some());
1322            let popover = hover_state.info_popover.as_ref().unwrap();
1323            let buffer_snapshot = editor.buffer().update(cx, |buffer, cx| buffer.snapshot(cx));
1324            assert_eq!(
1325                popover.symbol_range,
1326                RangeInEditor::Inlay(InlayHighlight {
1327                    inlay: InlayId::Hint(0),
1328                    inlay_position: buffer_snapshot.anchor_at(inlay_range.start, Bias::Right),
1329                    range: ": ".len() + new_type_label.len() + "<".len()
1330                        ..": ".len() + new_type_label.len() + "<".len() + struct_label.len(),
1331                }),
1332                "Popover range should match the struct label part"
1333            );
1334            assert_eq!(
1335                popover.parsed_content.text,
1336                format!("A tooltip for {struct_label}"),
1337                "Rendered markdown element should remove backticks from text"
1338            );
1339        });
1340    }
1341}