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 project::HoverBlock;
440 use smol::stream::StreamExt;
441
442 use crate::test::editor_lsp_test_context::EditorLspTestContext;
443
444 use super::*;
445
446 #[gpui::test]
447 async fn test_mouse_hover_info_popover(cx: &mut gpui::TestAppContext) {
448 let mut cx = EditorLspTestContext::new_rust(
449 lsp::ServerCapabilities {
450 hover_provider: Some(lsp::HoverProviderCapability::Simple(true)),
451 ..Default::default()
452 },
453 cx,
454 )
455 .await;
456
457 // Basic hover delays and then pops without moving the mouse
458 cx.set_state(indoc! {"
459 fn ˇtest() { println!(); }
460 "});
461 let hover_point = cx.display_point(indoc! {"
462 fn test() { printˇln!(); }
463 "});
464
465 cx.update_editor(|editor, cx| {
466 hover_at(
467 editor,
468 &HoverAt {
469 point: Some(hover_point),
470 },
471 cx,
472 )
473 });
474 assert!(!cx.editor(|editor, _| editor.hover_state.visible()));
475
476 // After delay, hover should be visible.
477 let symbol_range = cx.lsp_range(indoc! {"
478 fn test() { «println!»(); }
479 "});
480 let mut requests =
481 cx.handle_request::<lsp::request::HoverRequest, _, _>(move |_, _, _| async move {
482 Ok(Some(lsp::Hover {
483 contents: lsp::HoverContents::Markup(lsp::MarkupContent {
484 kind: lsp::MarkupKind::Markdown,
485 value: indoc! {"
486 # Some basic docs
487 Some test documentation"}
488 .to_string(),
489 }),
490 range: Some(symbol_range),
491 }))
492 });
493 cx.foreground()
494 .advance_clock(Duration::from_millis(HOVER_DELAY_MILLIS + 100));
495 requests.next().await;
496
497 cx.editor(|editor, _| {
498 assert!(editor.hover_state.visible());
499 assert_eq!(
500 editor.hover_state.info_popover.clone().unwrap().contents,
501 vec![
502 HoverBlock {
503 text: "Some basic docs".to_string(),
504 language: None
505 },
506 HoverBlock {
507 text: "Some test documentation".to_string(),
508 language: None
509 }
510 ]
511 )
512 });
513
514 // Mouse moved with no hover response dismisses
515 let hover_point = cx.display_point(indoc! {"
516 fn teˇst() { println!(); }
517 "});
518 let mut request = cx
519 .lsp
520 .handle_request::<lsp::request::HoverRequest, _, _>(|_, _| async move { Ok(None) });
521 cx.update_editor(|editor, cx| {
522 hover_at(
523 editor,
524 &HoverAt {
525 point: Some(hover_point),
526 },
527 cx,
528 )
529 });
530 cx.foreground()
531 .advance_clock(Duration::from_millis(HOVER_DELAY_MILLIS + 100));
532 request.next().await;
533 cx.editor(|editor, _| {
534 assert!(!editor.hover_state.visible());
535 });
536 }
537
538 #[gpui::test]
539 async fn test_keyboard_hover_info_popover(cx: &mut gpui::TestAppContext) {
540 let mut cx = EditorLspTestContext::new_rust(
541 lsp::ServerCapabilities {
542 hover_provider: Some(lsp::HoverProviderCapability::Simple(true)),
543 ..Default::default()
544 },
545 cx,
546 )
547 .await;
548
549 // Hover with keyboard has no delay
550 cx.set_state(indoc! {"
551 fˇn test() { println!(); }
552 "});
553 cx.update_editor(|editor, cx| hover(editor, &Hover, cx));
554 let symbol_range = cx.lsp_range(indoc! {"
555 «fn» test() { println!(); }
556 "});
557 cx.handle_request::<lsp::request::HoverRequest, _, _>(move |_, _, _| async move {
558 Ok(Some(lsp::Hover {
559 contents: lsp::HoverContents::Markup(lsp::MarkupContent {
560 kind: lsp::MarkupKind::Markdown,
561 value: indoc! {"
562 # Some other basic docs
563 Some other test documentation"}
564 .to_string(),
565 }),
566 range: Some(symbol_range),
567 }))
568 })
569 .next()
570 .await;
571
572 cx.condition(|editor, _| editor.hover_state.visible()).await;
573 cx.editor(|editor, _| {
574 assert_eq!(
575 editor.hover_state.info_popover.clone().unwrap().contents,
576 vec![
577 HoverBlock {
578 text: "Some other basic docs".to_string(),
579 language: None
580 },
581 HoverBlock {
582 text: "Some other test documentation".to_string(),
583 language: None
584 }
585 ]
586 )
587 });
588 }
589
590 #[gpui::test]
591 async fn test_hover_diagnostic_and_info_popovers(cx: &mut gpui::TestAppContext) {
592 let mut cx = EditorLspTestContext::new_rust(
593 lsp::ServerCapabilities {
594 hover_provider: Some(lsp::HoverProviderCapability::Simple(true)),
595 ..Default::default()
596 },
597 cx,
598 )
599 .await;
600
601 // Hover with just diagnostic, pops DiagnosticPopover immediately and then
602 // info popover once request completes
603 cx.set_state(indoc! {"
604 fn teˇst() { println!(); }
605 "});
606
607 // Send diagnostic to client
608 let range = cx.text_anchor_range(indoc! {"
609 fn «test»() { println!(); }
610 "});
611 cx.update_buffer(|buffer, cx| {
612 let snapshot = buffer.text_snapshot();
613 let set = DiagnosticSet::from_sorted_entries(
614 vec![DiagnosticEntry {
615 range,
616 diagnostic: Diagnostic {
617 message: "A test diagnostic message.".to_string(),
618 ..Default::default()
619 },
620 }],
621 &snapshot,
622 );
623 buffer.update_diagnostics(set, cx);
624 });
625
626 // Hover pops diagnostic immediately
627 cx.update_editor(|editor, cx| hover(editor, &Hover, cx));
628 cx.foreground().run_until_parked();
629
630 cx.editor(|Editor { hover_state, .. }, _| {
631 assert!(hover_state.diagnostic_popover.is_some() && hover_state.info_popover.is_none())
632 });
633
634 // Info Popover shows after request responded to
635 let range = cx.lsp_range(indoc! {"
636 fn «test»() { println!(); }
637 "});
638 cx.handle_request::<lsp::request::HoverRequest, _, _>(move |_, _, _| async move {
639 Ok(Some(lsp::Hover {
640 contents: lsp::HoverContents::Markup(lsp::MarkupContent {
641 kind: lsp::MarkupKind::Markdown,
642 value: indoc! {"
643 # Some other basic docs
644 Some other test documentation"}
645 .to_string(),
646 }),
647 range: Some(range),
648 }))
649 });
650 cx.foreground()
651 .advance_clock(Duration::from_millis(HOVER_DELAY_MILLIS + 100));
652
653 cx.foreground().run_until_parked();
654 cx.editor(|Editor { hover_state, .. }, _| {
655 hover_state.diagnostic_popover.is_some() && hover_state.info_task.is_some()
656 });
657 }
658}