1use futures::FutureExt;
2use gpui::{
3 actions,
4 elements::{Flex, MouseEventHandler, Padding, Text},
5 impl_internal_actions,
6 platform::{CursorStyle, MouseButton},
7 AppContext, Axis, Element, ElementBox, ModelHandle, RenderContext, 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 RenderContext<Editor>,
286 ) -> Option<(DisplayPoint, Vec<ElementBox>)> {
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 RenderContext<Editor>) -> ElementBox {
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 .boxed()
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 .boxed()
357 }
358 }));
359 flex.contained()
360 .with_style(style.hover_popover.container)
361 .boxed()
362 })
363 .on_move(|_, _| {}) // Consume move events so they don't reach regions underneath.
364 .with_cursor_style(CursorStyle::Arrow)
365 .with_padding(Padding {
366 bottom: HOVER_POPOVER_GAP,
367 top: HOVER_POPOVER_GAP,
368 ..Default::default()
369 })
370 .boxed()
371 }
372}
373
374#[derive(Debug, Clone)]
375pub struct DiagnosticPopover {
376 local_diagnostic: DiagnosticEntry<Anchor>,
377 primary_diagnostic: Option<DiagnosticEntry<Anchor>>,
378}
379
380impl DiagnosticPopover {
381 pub fn render(&self, style: &EditorStyle, cx: &mut RenderContext<Editor>) -> ElementBox {
382 enum PrimaryDiagnostic {}
383
384 let mut text_style = style.hover_popover.prose.clone();
385 text_style.font_size = style.text.font_size;
386
387 let container_style = match self.local_diagnostic.diagnostic.severity {
388 DiagnosticSeverity::HINT => style.hover_popover.info_container,
389 DiagnosticSeverity::INFORMATION => style.hover_popover.info_container,
390 DiagnosticSeverity::WARNING => style.hover_popover.warning_container,
391 DiagnosticSeverity::ERROR => style.hover_popover.error_container,
392 _ => style.hover_popover.container,
393 };
394
395 let tooltip_style = cx.global::<Settings>().theme.tooltip.clone();
396
397 MouseEventHandler::<DiagnosticPopover>::new(0, cx, |_, _| {
398 Text::new(self.local_diagnostic.diagnostic.message.clone(), text_style)
399 .with_soft_wrap(true)
400 .contained()
401 .with_style(container_style)
402 .boxed()
403 })
404 .with_padding(Padding {
405 top: HOVER_POPOVER_GAP,
406 bottom: HOVER_POPOVER_GAP,
407 ..Default::default()
408 })
409 .on_move(|_, _| {}) // Consume move events so they don't reach regions underneath.
410 .on_click(MouseButton::Left, |_, cx| {
411 cx.dispatch_action(GoToDiagnostic)
412 })
413 .with_cursor_style(CursorStyle::PointingHand)
414 .with_tooltip::<PrimaryDiagnostic, _>(
415 0,
416 "Go To Diagnostic".to_string(),
417 Some(Box::new(crate::GoToDiagnostic)),
418 tooltip_style,
419 cx,
420 )
421 .boxed()
422 }
423
424 pub fn activation_info(&self) -> (usize, Anchor) {
425 let entry = self
426 .primary_diagnostic
427 .as_ref()
428 .unwrap_or(&self.local_diagnostic);
429
430 (entry.diagnostic.group_id, entry.range.start.clone())
431 }
432}
433
434#[cfg(test)]
435mod tests {
436 use indoc::indoc;
437
438 use language::{Diagnostic, DiagnosticSet};
439 use lsp::LanguageServerId;
440 use project::HoverBlock;
441 use smol::stream::StreamExt;
442
443 use crate::test::editor_lsp_test_context::EditorLspTestContext;
444
445 use super::*;
446
447 #[gpui::test]
448 async fn test_mouse_hover_info_popover(cx: &mut gpui::TestAppContext) {
449 let mut cx = EditorLspTestContext::new_rust(
450 lsp::ServerCapabilities {
451 hover_provider: Some(lsp::HoverProviderCapability::Simple(true)),
452 ..Default::default()
453 },
454 cx,
455 )
456 .await;
457
458 // Basic hover delays and then pops without moving the mouse
459 cx.set_state(indoc! {"
460 fn ˇtest() { println!(); }
461 "});
462 let hover_point = cx.display_point(indoc! {"
463 fn test() { printˇln!(); }
464 "});
465
466 cx.update_editor(|editor, cx| {
467 hover_at(
468 editor,
469 &HoverAt {
470 point: Some(hover_point),
471 },
472 cx,
473 )
474 });
475 assert!(!cx.editor(|editor, _| editor.hover_state.visible()));
476
477 // After delay, hover should be visible.
478 let symbol_range = cx.lsp_range(indoc! {"
479 fn test() { «println!»(); }
480 "});
481 let mut requests =
482 cx.handle_request::<lsp::request::HoverRequest, _, _>(move |_, _, _| async move {
483 Ok(Some(lsp::Hover {
484 contents: lsp::HoverContents::Markup(lsp::MarkupContent {
485 kind: lsp::MarkupKind::Markdown,
486 value: indoc! {"
487 # Some basic docs
488 Some test documentation"}
489 .to_string(),
490 }),
491 range: Some(symbol_range),
492 }))
493 });
494 cx.foreground()
495 .advance_clock(Duration::from_millis(HOVER_DELAY_MILLIS + 100));
496 requests.next().await;
497
498 cx.editor(|editor, _| {
499 assert!(editor.hover_state.visible());
500 assert_eq!(
501 editor.hover_state.info_popover.clone().unwrap().contents,
502 vec![
503 HoverBlock {
504 text: "Some basic docs".to_string(),
505 language: None
506 },
507 HoverBlock {
508 text: "Some test documentation".to_string(),
509 language: None
510 }
511 ]
512 )
513 });
514
515 // Mouse moved with no hover response dismisses
516 let hover_point = cx.display_point(indoc! {"
517 fn teˇst() { println!(); }
518 "});
519 let mut request = cx
520 .lsp
521 .handle_request::<lsp::request::HoverRequest, _, _>(|_, _| async move { Ok(None) });
522 cx.update_editor(|editor, cx| {
523 hover_at(
524 editor,
525 &HoverAt {
526 point: Some(hover_point),
527 },
528 cx,
529 )
530 });
531 cx.foreground()
532 .advance_clock(Duration::from_millis(HOVER_DELAY_MILLIS + 100));
533 request.next().await;
534 cx.editor(|editor, _| {
535 assert!(!editor.hover_state.visible());
536 });
537 }
538
539 #[gpui::test]
540 async fn test_keyboard_hover_info_popover(cx: &mut gpui::TestAppContext) {
541 let mut cx = EditorLspTestContext::new_rust(
542 lsp::ServerCapabilities {
543 hover_provider: Some(lsp::HoverProviderCapability::Simple(true)),
544 ..Default::default()
545 },
546 cx,
547 )
548 .await;
549
550 // Hover with keyboard has no delay
551 cx.set_state(indoc! {"
552 fˇn test() { println!(); }
553 "});
554 cx.update_editor(|editor, cx| hover(editor, &Hover, cx));
555 let symbol_range = cx.lsp_range(indoc! {"
556 «fn» test() { println!(); }
557 "});
558 cx.handle_request::<lsp::request::HoverRequest, _, _>(move |_, _, _| async move {
559 Ok(Some(lsp::Hover {
560 contents: lsp::HoverContents::Markup(lsp::MarkupContent {
561 kind: lsp::MarkupKind::Markdown,
562 value: indoc! {"
563 # Some other basic docs
564 Some other test documentation"}
565 .to_string(),
566 }),
567 range: Some(symbol_range),
568 }))
569 })
570 .next()
571 .await;
572
573 cx.condition(|editor, _| editor.hover_state.visible()).await;
574 cx.editor(|editor, _| {
575 assert_eq!(
576 editor.hover_state.info_popover.clone().unwrap().contents,
577 vec![
578 HoverBlock {
579 text: "Some other basic docs".to_string(),
580 language: None
581 },
582 HoverBlock {
583 text: "Some other test documentation".to_string(),
584 language: None
585 }
586 ]
587 )
588 });
589 }
590
591 #[gpui::test]
592 async fn test_hover_diagnostic_and_info_popovers(cx: &mut gpui::TestAppContext) {
593 let mut cx = EditorLspTestContext::new_rust(
594 lsp::ServerCapabilities {
595 hover_provider: Some(lsp::HoverProviderCapability::Simple(true)),
596 ..Default::default()
597 },
598 cx,
599 )
600 .await;
601
602 // Hover with just diagnostic, pops DiagnosticPopover immediately and then
603 // info popover once request completes
604 cx.set_state(indoc! {"
605 fn teˇst() { println!(); }
606 "});
607
608 // Send diagnostic to client
609 let range = cx.text_anchor_range(indoc! {"
610 fn «test»() { println!(); }
611 "});
612 cx.update_buffer(|buffer, cx| {
613 let snapshot = buffer.text_snapshot();
614 let set = DiagnosticSet::from_sorted_entries(
615 vec![DiagnosticEntry {
616 range,
617 diagnostic: Diagnostic {
618 message: "A test diagnostic message.".to_string(),
619 ..Default::default()
620 },
621 }],
622 &snapshot,
623 );
624 buffer.update_diagnostics(LanguageServerId(0), set, cx);
625 });
626
627 // Hover pops diagnostic immediately
628 cx.update_editor(|editor, cx| hover(editor, &Hover, cx));
629 cx.foreground().run_until_parked();
630
631 cx.editor(|Editor { hover_state, .. }, _| {
632 assert!(hover_state.diagnostic_popover.is_some() && hover_state.info_popover.is_none())
633 });
634
635 // Info Popover shows after request responded to
636 let range = cx.lsp_range(indoc! {"
637 fn «test»() { println!(); }
638 "});
639 cx.handle_request::<lsp::request::HoverRequest, _, _>(move |_, _, _| async move {
640 Ok(Some(lsp::Hover {
641 contents: lsp::HoverContents::Markup(lsp::MarkupContent {
642 kind: lsp::MarkupKind::Markdown,
643 value: indoc! {"
644 # Some other basic docs
645 Some other test documentation"}
646 .to_string(),
647 }),
648 range: Some(range),
649 }))
650 });
651 cx.foreground()
652 .advance_clock(Duration::from_millis(HOVER_DELAY_MILLIS + 100));
653
654 cx.foreground().run_until_parked();
655 cx.editor(|Editor { hover_state, .. }, _| {
656 hover_state.diagnostic_popover.is_some() && hover_state.info_task.is_some()
657 });
658 }
659}