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