1pub mod items;
2mod toolbar_controls;
3
4mod buffer_diagnostics;
5mod diagnostic_renderer;
6
7#[cfg(test)]
8mod diagnostics_tests;
9
10use anyhow::Result;
11use buffer_diagnostics::BufferDiagnosticsEditor;
12use collections::{BTreeSet, HashMap, HashSet};
13use diagnostic_renderer::DiagnosticBlock;
14use editor::{
15 Editor, EditorEvent, ExcerptRange, MultiBuffer, PathKey,
16 display_map::{BlockPlacement, BlockProperties, BlockStyle, CustomBlockId},
17 multibuffer_context_lines,
18};
19use gpui::{
20 AnyElement, AnyView, App, AsyncApp, Context, Entity, EventEmitter, FocusHandle, FocusOutEvent,
21 Focusable, Global, InteractiveElement, IntoElement, ParentElement, Render, SharedString,
22 Styled, Subscription, Task, WeakEntity, Window, actions, div,
23};
24use itertools::Itertools as _;
25use language::{
26 Bias, Buffer, BufferRow, BufferSnapshot, DiagnosticEntry, DiagnosticEntryRef, Point,
27 ToTreeSitterPoint,
28};
29use project::{
30 DiagnosticSummary, Project, ProjectPath,
31 project_settings::{DiagnosticSeverity, ProjectSettings},
32};
33use settings::Settings;
34use std::{
35 any::{Any, TypeId},
36 cmp,
37 ops::{Range, RangeInclusive},
38 sync::Arc,
39 time::Duration,
40};
41use text::{BufferId, OffsetRangeExt};
42use theme::ActiveTheme;
43use toolbar_controls::DiagnosticsToolbarEditor;
44pub use toolbar_controls::ToolbarControls;
45use ui::{Icon, IconName, Label, h_flex, prelude::*};
46use util::ResultExt;
47use workspace::{
48 ItemNavHistory, ToolbarItemLocation, Workspace,
49 item::{BreadcrumbText, Item, ItemEvent, ItemHandle, SaveOptions, TabContentParams},
50 searchable::SearchableItemHandle,
51};
52
53actions!(
54 diagnostics,
55 [
56 /// Opens the project diagnostics view.
57 Deploy,
58 /// Toggles the display of warning-level diagnostics.
59 ToggleWarnings,
60 /// Toggles automatic refresh of diagnostics.
61 ToggleDiagnosticsRefresh
62 ]
63);
64
65#[derive(Default)]
66pub(crate) struct IncludeWarnings(bool);
67impl Global for IncludeWarnings {}
68
69pub fn init(cx: &mut App) {
70 editor::set_diagnostic_renderer(diagnostic_renderer::DiagnosticRenderer {}, cx);
71 cx.observe_new(ProjectDiagnosticsEditor::register).detach();
72 cx.observe_new(BufferDiagnosticsEditor::register).detach();
73}
74
75pub(crate) struct ProjectDiagnosticsEditor {
76 project: Entity<Project>,
77 workspace: WeakEntity<Workspace>,
78 focus_handle: FocusHandle,
79 editor: Entity<Editor>,
80 diagnostics: HashMap<BufferId, Vec<DiagnosticEntry<text::Anchor>>>,
81 blocks: HashMap<BufferId, Vec<CustomBlockId>>,
82 summary: DiagnosticSummary,
83 multibuffer: Entity<MultiBuffer>,
84 paths_to_update: BTreeSet<ProjectPath>,
85 include_warnings: bool,
86 update_excerpts_task: Option<Task<Result<()>>>,
87 diagnostic_summary_update: Task<()>,
88 _subscription: Subscription,
89}
90
91impl EventEmitter<EditorEvent> for ProjectDiagnosticsEditor {}
92
93const DIAGNOSTICS_UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
94const DIAGNOSTICS_SUMMARY_UPDATE_DEBOUNCE: Duration = Duration::from_millis(30);
95
96impl Render for ProjectDiagnosticsEditor {
97 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
98 let warning_count = if self.include_warnings {
99 self.summary.warning_count
100 } else {
101 0
102 };
103
104 let child =
105 if warning_count + self.summary.error_count == 0 && self.editor.read(cx).is_empty(cx) {
106 let label = if self.summary.warning_count == 0 {
107 SharedString::new_static("No problems in workspace")
108 } else {
109 SharedString::new_static("No errors in workspace")
110 };
111 v_flex()
112 .key_context("EmptyPane")
113 .size_full()
114 .gap_1()
115 .justify_center()
116 .items_center()
117 .text_center()
118 .bg(cx.theme().colors().editor_background)
119 .child(Label::new(label).color(Color::Muted))
120 .when(self.summary.warning_count > 0, |this| {
121 let plural_suffix = if self.summary.warning_count > 1 {
122 "s"
123 } else {
124 ""
125 };
126 let label = format!(
127 "Show {} warning{}",
128 self.summary.warning_count, plural_suffix
129 );
130 this.child(
131 Button::new("diagnostics-show-warning-label", label).on_click(
132 cx.listener(|this, _, window, cx| {
133 this.toggle_warnings(&Default::default(), window, cx);
134 cx.notify();
135 }),
136 ),
137 )
138 })
139 } else {
140 div().size_full().child(self.editor.clone())
141 };
142
143 div()
144 .key_context("Diagnostics")
145 .track_focus(&self.focus_handle(cx))
146 .size_full()
147 .on_action(cx.listener(Self::toggle_warnings))
148 .on_action(cx.listener(Self::toggle_diagnostics_refresh))
149 .child(child)
150 }
151}
152
153#[derive(PartialEq, Eq, Copy, Clone, Debug)]
154enum RetainExcerpts {
155 All,
156 Dirty,
157}
158
159impl ProjectDiagnosticsEditor {
160 pub fn register(
161 workspace: &mut Workspace,
162 _window: Option<&mut Window>,
163 _: &mut Context<Workspace>,
164 ) {
165 workspace.register_action(Self::deploy);
166 }
167
168 fn new(
169 include_warnings: bool,
170 project_handle: Entity<Project>,
171 workspace: WeakEntity<Workspace>,
172 window: &mut Window,
173 cx: &mut Context<Self>,
174 ) -> Self {
175 let project_event_subscription = cx.subscribe_in(
176 &project_handle,
177 window,
178 |this, _project, event, window, cx| match event {
179 project::Event::DiskBasedDiagnosticsStarted { .. } => {
180 cx.notify();
181 }
182 project::Event::DiskBasedDiagnosticsFinished { language_server_id } => {
183 log::debug!("disk based diagnostics finished for server {language_server_id}");
184 this.close_diagnosticless_buffers(
185 window,
186 cx,
187 this.editor.focus_handle(cx).contains_focused(window, cx)
188 || this.focus_handle.contains_focused(window, cx),
189 );
190 }
191 project::Event::DiagnosticsUpdated {
192 language_server_id,
193 paths,
194 } => {
195 this.paths_to_update.extend(paths.clone());
196 this.diagnostic_summary_update = cx.spawn(async move |this, cx| {
197 cx.background_executor()
198 .timer(DIAGNOSTICS_SUMMARY_UPDATE_DEBOUNCE)
199 .await;
200 this.update(cx, |this, cx| {
201 this.update_diagnostic_summary(cx);
202 })
203 .log_err();
204 });
205
206 log::debug!(
207 "diagnostics updated for server {language_server_id}, \
208 paths {paths:?}. updating excerpts"
209 );
210 this.update_stale_excerpts(window, cx);
211 }
212 _ => {}
213 },
214 );
215
216 let focus_handle = cx.focus_handle();
217 cx.on_focus_in(&focus_handle, window, Self::focus_in)
218 .detach();
219 cx.on_focus_out(&focus_handle, window, Self::focus_out)
220 .detach();
221
222 let excerpts = cx.new(|cx| MultiBuffer::new(project_handle.read(cx).capability()));
223 let editor = cx.new(|cx| {
224 let mut editor =
225 Editor::for_multibuffer(excerpts.clone(), Some(project_handle.clone()), window, cx);
226 editor.set_vertical_scroll_margin(5, cx);
227 editor.disable_inline_diagnostics();
228 editor.set_max_diagnostics_severity(
229 if include_warnings {
230 DiagnosticSeverity::Warning
231 } else {
232 DiagnosticSeverity::Error
233 },
234 cx,
235 );
236 editor.set_all_diagnostics_active(cx);
237 editor
238 });
239 cx.subscribe_in(
240 &editor,
241 window,
242 |this, _editor, event: &EditorEvent, window, cx| {
243 cx.emit(event.clone());
244 match event {
245 EditorEvent::Focused => {
246 if this.multibuffer.read(cx).is_empty() {
247 window.focus(&this.focus_handle);
248 }
249 }
250 EditorEvent::Blurred => this.close_diagnosticless_buffers(window, cx, false),
251 EditorEvent::Saved => this.close_diagnosticless_buffers(window, cx, true),
252 EditorEvent::SelectionsChanged { .. } => {
253 this.close_diagnosticless_buffers(window, cx, true)
254 }
255 _ => {}
256 }
257 },
258 )
259 .detach();
260 cx.observe_global_in::<IncludeWarnings>(window, |this, window, cx| {
261 let include_warnings = cx.global::<IncludeWarnings>().0;
262 this.include_warnings = include_warnings;
263 this.editor.update(cx, |editor, cx| {
264 editor.set_max_diagnostics_severity(
265 if include_warnings {
266 DiagnosticSeverity::Warning
267 } else {
268 DiagnosticSeverity::Error
269 },
270 cx,
271 )
272 });
273 this.refresh(window, cx);
274 })
275 .detach();
276
277 let project = project_handle.read(cx);
278 let mut this = Self {
279 project: project_handle.clone(),
280 summary: project.diagnostic_summary(false, cx),
281 diagnostics: Default::default(),
282 blocks: Default::default(),
283 include_warnings,
284 workspace,
285 multibuffer: excerpts,
286 focus_handle,
287 editor,
288 paths_to_update: Default::default(),
289 update_excerpts_task: None,
290 diagnostic_summary_update: Task::ready(()),
291 _subscription: project_event_subscription,
292 };
293 this.refresh(window, cx);
294 this
295 }
296
297 /// Closes all excerpts of buffers that:
298 /// - have no diagnostics anymore
299 /// - are saved (not dirty)
300 /// - and, if `retain_selections` is true, do not have selections within them
301 fn close_diagnosticless_buffers(
302 &mut self,
303 _window: &mut Window,
304 cx: &mut Context<Self>,
305 retain_selections: bool,
306 ) {
307 let buffer_ids = self.multibuffer.read(cx).all_buffer_ids();
308 let selected_buffers = self.editor.update(cx, |editor, cx| {
309 editor
310 .selections
311 .all_anchors(cx)
312 .iter()
313 .filter_map(|anchor| anchor.start.buffer_id)
314 .collect::<HashSet<_>>()
315 });
316 for buffer_id in buffer_ids {
317 if retain_selections && selected_buffers.contains(&buffer_id) {
318 continue;
319 }
320 let has_no_blocks = self
321 .blocks
322 .get(&buffer_id)
323 .is_none_or(|blocks| blocks.is_empty());
324 if !has_no_blocks {
325 continue;
326 }
327 let is_dirty = self
328 .multibuffer
329 .read(cx)
330 .buffer(buffer_id)
331 .is_none_or(|buffer| buffer.read(cx).is_dirty());
332 if is_dirty {
333 continue;
334 }
335 self.multibuffer.update(cx, |b, cx| {
336 b.remove_excerpts_for_buffer(buffer_id, cx);
337 });
338 }
339 }
340
341 fn update_stale_excerpts(&mut self, window: &mut Window, cx: &mut Context<Self>) {
342 if self.update_excerpts_task.is_some() {
343 return;
344 }
345
346 let project_handle = self.project.clone();
347 self.update_excerpts_task = Some(cx.spawn_in(window, async move |this, cx| {
348 cx.background_executor()
349 .timer(DIAGNOSTICS_UPDATE_DEBOUNCE)
350 .await;
351 loop {
352 let Some(path) = this.update(cx, |this, cx| {
353 let Some(path) = this.paths_to_update.pop_first() else {
354 this.update_excerpts_task = None;
355 cx.notify();
356 return None;
357 };
358 Some(path)
359 })?
360 else {
361 break;
362 };
363
364 if let Some(buffer) = project_handle
365 .update(cx, |project, cx| project.open_buffer(path.clone(), cx))?
366 .await
367 .log_err()
368 {
369 this.update_in(cx, |this, window, cx| {
370 let focused = this.editor.focus_handle(cx).contains_focused(window, cx)
371 || this.focus_handle.contains_focused(window, cx);
372 let retain_excerpts = if focused {
373 RetainExcerpts::All
374 } else {
375 RetainExcerpts::Dirty
376 };
377 this.update_excerpts(buffer, retain_excerpts, window, cx)
378 })?
379 .await?;
380 }
381 }
382 Ok(())
383 }));
384 }
385
386 fn deploy(
387 workspace: &mut Workspace,
388 _: &Deploy,
389 window: &mut Window,
390 cx: &mut Context<Workspace>,
391 ) {
392 if let Some(existing) = workspace.item_of_type::<ProjectDiagnosticsEditor>(cx) {
393 let is_active = workspace
394 .active_item(cx)
395 .is_some_and(|item| item.item_id() == existing.item_id());
396
397 workspace.activate_item(&existing, true, !is_active, window, cx);
398 } else {
399 let workspace_handle = cx.entity().downgrade();
400
401 let include_warnings = match cx.try_global::<IncludeWarnings>() {
402 Some(include_warnings) => include_warnings.0,
403 None => ProjectSettings::get_global(cx).diagnostics.include_warnings,
404 };
405
406 let diagnostics = cx.new(|cx| {
407 ProjectDiagnosticsEditor::new(
408 include_warnings,
409 workspace.project().clone(),
410 workspace_handle,
411 window,
412 cx,
413 )
414 });
415 workspace.add_item_to_active_pane(Box::new(diagnostics), None, true, window, cx);
416 }
417 }
418
419 fn toggle_warnings(&mut self, _: &ToggleWarnings, _: &mut Window, cx: &mut Context<Self>) {
420 cx.set_global(IncludeWarnings(!self.include_warnings));
421 }
422
423 fn toggle_diagnostics_refresh(
424 &mut self,
425 _: &ToggleDiagnosticsRefresh,
426 window: &mut Window,
427 cx: &mut Context<Self>,
428 ) {
429 if self.update_excerpts_task.is_some() {
430 self.update_excerpts_task = None;
431 } else {
432 self.refresh(window, cx);
433 }
434 cx.notify();
435 }
436
437 fn focus_in(&mut self, window: &mut Window, cx: &mut Context<Self>) {
438 if self.focus_handle.is_focused(window) && !self.multibuffer.read(cx).is_empty() {
439 self.editor.focus_handle(cx).focus(window)
440 }
441 }
442
443 fn focus_out(&mut self, _: FocusOutEvent, window: &mut Window, cx: &mut Context<Self>) {
444 if !self.focus_handle.is_focused(window) && !self.editor.focus_handle(cx).is_focused(window)
445 {
446 self.close_diagnosticless_buffers(window, cx, false);
447 }
448 }
449
450 /// Clears all diagnostics in this view, and refetches them from the project.
451 fn refresh(&mut self, window: &mut Window, cx: &mut Context<Self>) {
452 self.diagnostics.clear();
453 self.editor.update(cx, |editor, cx| {
454 for (_, block_ids) in self.blocks.drain() {
455 editor.display_map.update(cx, |display_map, cx| {
456 display_map.remove_blocks(block_ids.into_iter().collect(), cx)
457 });
458 }
459 });
460 self.multibuffer
461 .update(cx, |multibuffer, cx| multibuffer.clear(cx));
462 self.project.update(cx, |project, cx| {
463 self.paths_to_update = project
464 .diagnostic_summaries(false, cx)
465 .map(|(project_path, _, _)| project_path)
466 .collect::<BTreeSet<_>>();
467 });
468
469 self.update_stale_excerpts(window, cx);
470 }
471
472 fn diagnostics_are_unchanged(
473 &self,
474 existing: &[DiagnosticEntry<text::Anchor>],
475 new: &[DiagnosticEntryRef<'_, text::Anchor>],
476 snapshot: &BufferSnapshot,
477 ) -> bool {
478 if existing.len() != new.len() {
479 return false;
480 }
481 existing.iter().zip(new.iter()).all(|(existing, new)| {
482 existing.diagnostic.message == new.diagnostic.message
483 && existing.diagnostic.severity == new.diagnostic.severity
484 && existing.diagnostic.is_primary == new.diagnostic.is_primary
485 && existing.range.to_offset(snapshot) == new.range.to_offset(snapshot)
486 })
487 }
488
489 fn update_excerpts(
490 &mut self,
491 buffer: Entity<Buffer>,
492 retain_excerpts: RetainExcerpts,
493 window: &mut Window,
494 cx: &mut Context<Self>,
495 ) -> Task<Result<()>> {
496 let was_empty = self.multibuffer.read(cx).is_empty();
497 let buffer_snapshot = buffer.read(cx).snapshot();
498 let buffer_id = buffer_snapshot.remote_id();
499
500 let max_severity = if self.include_warnings {
501 lsp::DiagnosticSeverity::WARNING
502 } else {
503 lsp::DiagnosticSeverity::ERROR
504 };
505
506 cx.spawn_in(window, async move |this, cx| {
507 let diagnostics = buffer_snapshot
508 .diagnostics_in_range::<_, text::Anchor>(
509 Point::zero()..buffer_snapshot.max_point(),
510 false,
511 )
512 .collect::<Vec<_>>();
513
514 let unchanged = this.update(cx, |this, _| {
515 if this.diagnostics.get(&buffer_id).is_some_and(|existing| {
516 this.diagnostics_are_unchanged(existing, &diagnostics, &buffer_snapshot)
517 }) {
518 return true;
519 }
520 this.diagnostics.insert(
521 buffer_id,
522 diagnostics
523 .iter()
524 .map(DiagnosticEntryRef::to_owned)
525 .collect(),
526 );
527 false
528 })?;
529 if unchanged {
530 return Ok(());
531 }
532
533 let mut grouped: HashMap<usize, Vec<_>> = HashMap::default();
534 for entry in diagnostics {
535 grouped
536 .entry(entry.diagnostic.group_id)
537 .or_default()
538 .push(DiagnosticEntryRef {
539 range: entry.range.to_point(&buffer_snapshot),
540 diagnostic: entry.diagnostic,
541 })
542 }
543 let mut blocks: Vec<DiagnosticBlock> = Vec::new();
544
545 for (_, group) in grouped {
546 let group_severity = group.iter().map(|d| d.diagnostic.severity).min();
547 if group_severity.is_none_or(|s| s > max_severity) {
548 continue;
549 }
550 let more = cx.update(|_, cx| {
551 crate::diagnostic_renderer::DiagnosticRenderer::diagnostic_blocks_for_group(
552 group,
553 buffer_snapshot.remote_id(),
554 Some(Arc::new(this.clone())),
555 cx,
556 )
557 })?;
558
559 blocks.extend(more);
560 }
561
562 let mut excerpt_ranges: Vec<ExcerptRange<Point>> = this.update(cx, |this, cx| {
563 this.multibuffer.update(cx, |multi_buffer, cx| {
564 let is_dirty = multi_buffer
565 .buffer(buffer_id)
566 .is_none_or(|buffer| buffer.read(cx).is_dirty());
567 match retain_excerpts {
568 RetainExcerpts::Dirty if !is_dirty => Vec::new(),
569 RetainExcerpts::All | RetainExcerpts::Dirty => multi_buffer
570 .excerpts_for_buffer(buffer_id, cx)
571 .into_iter()
572 .map(|(_, range)| ExcerptRange {
573 context: range.context.to_point(&buffer_snapshot),
574 primary: range.primary.to_point(&buffer_snapshot),
575 })
576 .collect(),
577 }
578 })
579 })?;
580 let mut result_blocks = vec![None; excerpt_ranges.len()];
581 let context_lines = cx.update(|_, cx| multibuffer_context_lines(cx))?;
582 for b in blocks {
583 let excerpt_range = context_range_for_entry(
584 b.initial_range.clone(),
585 context_lines,
586 buffer_snapshot.clone(),
587 cx,
588 )
589 .await;
590
591 let i = excerpt_ranges
592 .binary_search_by(|probe| {
593 probe
594 .context
595 .start
596 .cmp(&excerpt_range.start)
597 .then(probe.context.end.cmp(&excerpt_range.end))
598 .then(probe.primary.start.cmp(&b.initial_range.start))
599 .then(probe.primary.end.cmp(&b.initial_range.end))
600 .then(cmp::Ordering::Greater)
601 })
602 .unwrap_or_else(|i| i);
603 excerpt_ranges.insert(
604 i,
605 ExcerptRange {
606 context: excerpt_range,
607 primary: b.initial_range.clone(),
608 },
609 );
610 result_blocks.insert(i, Some(b));
611 }
612
613 this.update_in(cx, |this, window, cx| {
614 if let Some(block_ids) = this.blocks.remove(&buffer_id) {
615 this.editor.update(cx, |editor, cx| {
616 editor.display_map.update(cx, |display_map, cx| {
617 display_map.remove_blocks(block_ids.into_iter().collect(), cx)
618 });
619 })
620 }
621 let (anchor_ranges, _) = this.multibuffer.update(cx, |multi_buffer, cx| {
622 multi_buffer.set_excerpt_ranges_for_path(
623 PathKey::for_buffer(&buffer, cx),
624 buffer.clone(),
625 &buffer_snapshot,
626 excerpt_ranges,
627 cx,
628 )
629 });
630 #[cfg(test)]
631 let cloned_blocks = result_blocks.clone();
632
633 if was_empty && let Some(anchor_range) = anchor_ranges.first() {
634 let range_to_select = anchor_range.start..anchor_range.start;
635 this.editor.update(cx, |editor, cx| {
636 editor.change_selections(Default::default(), window, cx, |s| {
637 s.select_anchor_ranges([range_to_select]);
638 })
639 });
640 if this.focus_handle.is_focused(window) {
641 this.editor.read(cx).focus_handle(cx).focus(window);
642 }
643 }
644
645 let editor_blocks = anchor_ranges
646 .into_iter()
647 .zip_eq(result_blocks.into_iter())
648 .filter_map(|(anchor, block)| {
649 let block = block?;
650 let editor = this.editor.downgrade();
651 Some(BlockProperties {
652 placement: BlockPlacement::Near(anchor.start),
653 height: Some(1),
654 style: BlockStyle::Flex,
655 render: Arc::new(move |bcx| block.render_block(editor.clone(), bcx)),
656 priority: 1,
657 })
658 });
659
660 let block_ids = this.editor.update(cx, |editor, cx| {
661 editor.display_map.update(cx, |display_map, cx| {
662 display_map.insert_blocks(editor_blocks, cx)
663 })
664 });
665
666 #[cfg(test)]
667 {
668 for (block_id, block) in
669 block_ids.iter().zip(cloned_blocks.into_iter().flatten())
670 {
671 let markdown = block.markdown.clone();
672 editor::test::set_block_content_for_tests(
673 &this.editor,
674 *block_id,
675 cx,
676 move |cx| {
677 markdown::MarkdownElement::rendered_text(
678 markdown.clone(),
679 cx,
680 editor::hover_popover::diagnostics_markdown_style,
681 )
682 },
683 );
684 }
685 }
686
687 this.blocks.insert(buffer_id, block_ids);
688 cx.notify()
689 })
690 })
691 }
692
693 fn update_diagnostic_summary(&mut self, cx: &mut Context<Self>) {
694 self.summary = self.project.read(cx).diagnostic_summary(false, cx);
695 cx.emit(EditorEvent::TitleChanged);
696 }
697}
698
699impl Focusable for ProjectDiagnosticsEditor {
700 fn focus_handle(&self, _: &App) -> FocusHandle {
701 self.focus_handle.clone()
702 }
703}
704
705impl Item for ProjectDiagnosticsEditor {
706 type Event = EditorEvent;
707
708 fn to_item_events(event: &EditorEvent, f: impl FnMut(ItemEvent)) {
709 Editor::to_item_events(event, f)
710 }
711
712 fn deactivated(&mut self, window: &mut Window, cx: &mut Context<Self>) {
713 self.editor
714 .update(cx, |editor, cx| editor.deactivated(window, cx));
715 }
716
717 fn navigate(
718 &mut self,
719 data: Box<dyn Any>,
720 window: &mut Window,
721 cx: &mut Context<Self>,
722 ) -> bool {
723 self.editor
724 .update(cx, |editor, cx| editor.navigate(data, window, cx))
725 }
726
727 fn tab_tooltip_text(&self, _: &App) -> Option<SharedString> {
728 Some("Project Diagnostics".into())
729 }
730
731 fn tab_content_text(&self, _detail: usize, _: &App) -> SharedString {
732 "Diagnostics".into()
733 }
734
735 fn tab_content(&self, params: TabContentParams, _window: &Window, _: &App) -> AnyElement {
736 h_flex()
737 .gap_1()
738 .when(
739 self.summary.error_count == 0 && self.summary.warning_count == 0,
740 |then| {
741 then.child(
742 h_flex()
743 .gap_1()
744 .child(Icon::new(IconName::Check).color(Color::Success))
745 .child(Label::new("No problems").color(params.text_color())),
746 )
747 },
748 )
749 .when(self.summary.error_count > 0, |then| {
750 then.child(
751 h_flex()
752 .gap_1()
753 .child(Icon::new(IconName::XCircle).color(Color::Error))
754 .child(
755 Label::new(self.summary.error_count.to_string())
756 .color(params.text_color()),
757 ),
758 )
759 })
760 .when(self.summary.warning_count > 0, |then| {
761 then.child(
762 h_flex()
763 .gap_1()
764 .child(Icon::new(IconName::Warning).color(Color::Warning))
765 .child(
766 Label::new(self.summary.warning_count.to_string())
767 .color(params.text_color()),
768 ),
769 )
770 })
771 .into_any_element()
772 }
773
774 fn telemetry_event_text(&self) -> Option<&'static str> {
775 Some("Project Diagnostics Opened")
776 }
777
778 fn for_each_project_item(
779 &self,
780 cx: &App,
781 f: &mut dyn FnMut(gpui::EntityId, &dyn project::ProjectItem),
782 ) {
783 self.editor.for_each_project_item(cx, f)
784 }
785
786 fn set_nav_history(
787 &mut self,
788 nav_history: ItemNavHistory,
789 _: &mut Window,
790 cx: &mut Context<Self>,
791 ) {
792 self.editor.update(cx, |editor, _| {
793 editor.set_nav_history(Some(nav_history));
794 });
795 }
796
797 fn can_split(&self) -> bool {
798 true
799 }
800
801 fn clone_on_split(
802 &self,
803 _workspace_id: Option<workspace::WorkspaceId>,
804 window: &mut Window,
805 cx: &mut Context<Self>,
806 ) -> Task<Option<Entity<Self>>>
807 where
808 Self: Sized,
809 {
810 Task::ready(Some(cx.new(|cx| {
811 ProjectDiagnosticsEditor::new(
812 self.include_warnings,
813 self.project.clone(),
814 self.workspace.clone(),
815 window,
816 cx,
817 )
818 })))
819 }
820
821 fn is_dirty(&self, cx: &App) -> bool {
822 self.multibuffer.read(cx).is_dirty(cx)
823 }
824
825 fn has_deleted_file(&self, cx: &App) -> bool {
826 self.multibuffer.read(cx).has_deleted_file(cx)
827 }
828
829 fn has_conflict(&self, cx: &App) -> bool {
830 self.multibuffer.read(cx).has_conflict(cx)
831 }
832
833 fn can_save(&self, _: &App) -> bool {
834 true
835 }
836
837 fn save(
838 &mut self,
839 options: SaveOptions,
840 project: Entity<Project>,
841 window: &mut Window,
842 cx: &mut Context<Self>,
843 ) -> Task<Result<()>> {
844 self.editor.save(options, project, window, cx)
845 }
846
847 fn save_as(
848 &mut self,
849 _: Entity<Project>,
850 _: ProjectPath,
851 _window: &mut Window,
852 _: &mut Context<Self>,
853 ) -> Task<Result<()>> {
854 unreachable!()
855 }
856
857 fn reload(
858 &mut self,
859 project: Entity<Project>,
860 window: &mut Window,
861 cx: &mut Context<Self>,
862 ) -> Task<Result<()>> {
863 self.editor.reload(project, window, cx)
864 }
865
866 fn act_as_type<'a>(
867 &'a self,
868 type_id: TypeId,
869 self_handle: &'a Entity<Self>,
870 _: &'a App,
871 ) -> Option<AnyView> {
872 if type_id == TypeId::of::<Self>() {
873 Some(self_handle.to_any())
874 } else if type_id == TypeId::of::<Editor>() {
875 Some(self.editor.to_any())
876 } else {
877 None
878 }
879 }
880
881 fn as_searchable(&self, _: &Entity<Self>) -> Option<Box<dyn SearchableItemHandle>> {
882 Some(Box::new(self.editor.clone()))
883 }
884
885 fn breadcrumb_location(&self, _: &App) -> ToolbarItemLocation {
886 ToolbarItemLocation::PrimaryLeft
887 }
888
889 fn breadcrumbs(&self, theme: &theme::Theme, cx: &App) -> Option<Vec<BreadcrumbText>> {
890 self.editor.breadcrumbs(theme, cx)
891 }
892
893 fn added_to_workspace(
894 &mut self,
895 workspace: &mut Workspace,
896 window: &mut Window,
897 cx: &mut Context<Self>,
898 ) {
899 self.editor.update(cx, |editor, cx| {
900 editor.added_to_workspace(workspace, window, cx)
901 });
902 }
903}
904
905impl DiagnosticsToolbarEditor for WeakEntity<ProjectDiagnosticsEditor> {
906 fn include_warnings(&self, cx: &App) -> bool {
907 self.read_with(cx, |project_diagnostics_editor, _cx| {
908 project_diagnostics_editor.include_warnings
909 })
910 .unwrap_or(false)
911 }
912
913 fn is_updating(&self, cx: &App) -> bool {
914 self.read_with(cx, |project_diagnostics_editor, cx| {
915 project_diagnostics_editor.update_excerpts_task.is_some()
916 || project_diagnostics_editor
917 .project
918 .read(cx)
919 .language_servers_running_disk_based_diagnostics(cx)
920 .next()
921 .is_some()
922 })
923 .unwrap_or(false)
924 }
925
926 fn stop_updating(&self, cx: &mut App) {
927 let _ = self.update(cx, |project_diagnostics_editor, cx| {
928 project_diagnostics_editor.update_excerpts_task = None;
929 cx.notify();
930 });
931 }
932
933 fn refresh_diagnostics(&self, window: &mut Window, cx: &mut App) {
934 let _ = self.update(cx, |project_diagnostics_editor, cx| {
935 project_diagnostics_editor.refresh(window, cx);
936 });
937 }
938
939 fn toggle_warnings(&self, window: &mut Window, cx: &mut App) {
940 let _ = self.update(cx, |project_diagnostics_editor, cx| {
941 project_diagnostics_editor.toggle_warnings(&Default::default(), window, cx);
942 });
943 }
944
945 fn get_diagnostics_for_buffer(
946 &self,
947 buffer_id: text::BufferId,
948 cx: &App,
949 ) -> Vec<language::DiagnosticEntry<text::Anchor>> {
950 self.read_with(cx, |project_diagnostics_editor, _cx| {
951 project_diagnostics_editor
952 .diagnostics
953 .get(&buffer_id)
954 .cloned()
955 .unwrap_or_default()
956 })
957 .unwrap_or_default()
958 }
959}
960const DIAGNOSTIC_EXPANSION_ROW_LIMIT: u32 = 32;
961
962async fn context_range_for_entry(
963 range: Range<Point>,
964 context: u32,
965 snapshot: BufferSnapshot,
966 cx: &mut AsyncApp,
967) -> Range<Point> {
968 if let Some(rows) = heuristic_syntactic_expand(
969 range.clone(),
970 DIAGNOSTIC_EXPANSION_ROW_LIMIT,
971 snapshot.clone(),
972 cx,
973 )
974 .await
975 {
976 return Range {
977 start: Point::new(*rows.start(), 0),
978 end: snapshot.clip_point(Point::new(*rows.end(), u32::MAX), Bias::Left),
979 };
980 }
981 Range {
982 start: Point::new(range.start.row.saturating_sub(context), 0),
983 end: snapshot.clip_point(Point::new(range.end.row + context, u32::MAX), Bias::Left),
984 }
985}
986
987/// Expands the input range using syntax information from TreeSitter. This expansion will be limited
988/// to the specified `max_row_count`.
989///
990/// If there is a containing outline item that is less than `max_row_count`, it will be returned.
991/// Otherwise fairly arbitrary heuristics are applied to attempt to return a logical block of code.
992async fn heuristic_syntactic_expand(
993 input_range: Range<Point>,
994 max_row_count: u32,
995 snapshot: BufferSnapshot,
996 cx: &mut AsyncApp,
997) -> Option<RangeInclusive<BufferRow>> {
998 let input_row_count = input_range.end.row - input_range.start.row;
999 if input_row_count > max_row_count {
1000 return None;
1001 }
1002
1003 // If the outline node contains the diagnostic and is small enough, just use that.
1004 let outline_range = snapshot.outline_range_containing(input_range.clone());
1005 if let Some(outline_range) = outline_range.clone() {
1006 // Remove blank lines from start and end
1007 if let Some(start_row) = (outline_range.start.row..outline_range.end.row)
1008 .find(|row| !snapshot.line_indent_for_row(*row).is_line_blank())
1009 && let Some(end_row) = (outline_range.start.row..outline_range.end.row + 1)
1010 .rev()
1011 .find(|row| !snapshot.line_indent_for_row(*row).is_line_blank())
1012 {
1013 let row_count = end_row.saturating_sub(start_row);
1014 if row_count <= max_row_count {
1015 return Some(RangeInclusive::new(
1016 outline_range.start.row,
1017 outline_range.end.row,
1018 ));
1019 }
1020 }
1021 }
1022
1023 let mut node = snapshot.syntax_ancestor(input_range.clone())?;
1024
1025 loop {
1026 let node_start = Point::from_ts_point(node.start_position());
1027 let node_end = Point::from_ts_point(node.end_position());
1028 let node_range = node_start..node_end;
1029 let row_count = node_end.row - node_start.row + 1;
1030 let mut ancestor_range = None;
1031 let reached_outline_node = cx.background_executor().scoped({
1032 let node_range = node_range.clone();
1033 let outline_range = outline_range.clone();
1034 let ancestor_range = &mut ancestor_range;
1035 |scope| {
1036 scope.spawn(async move {
1037 // Stop if we've exceeded the row count or reached an outline node. Then, find the interval
1038 // of node children which contains the query range. For example, this allows just returning
1039 // the header of a declaration rather than the entire declaration.
1040 if row_count > max_row_count || outline_range == Some(node_range.clone()) {
1041 let mut cursor = node.walk();
1042 let mut included_child_start = None;
1043 let mut included_child_end = None;
1044 let mut previous_end = node_start;
1045 if cursor.goto_first_child() {
1046 loop {
1047 let child_node = cursor.node();
1048 let child_range =
1049 previous_end..Point::from_ts_point(child_node.end_position());
1050 if included_child_start.is_none()
1051 && child_range.contains(&input_range.start)
1052 {
1053 included_child_start = Some(child_range.start);
1054 }
1055 if child_range.contains(&input_range.end) {
1056 included_child_end = Some(child_range.end);
1057 }
1058 previous_end = child_range.end;
1059 if !cursor.goto_next_sibling() {
1060 break;
1061 }
1062 }
1063 }
1064 let end = included_child_end.unwrap_or(node_range.end);
1065 if let Some(start) = included_child_start {
1066 let row_count = end.row - start.row;
1067 if row_count < max_row_count {
1068 *ancestor_range =
1069 Some(Some(RangeInclusive::new(start.row, end.row)));
1070 return;
1071 }
1072 }
1073 *ancestor_range = Some(None);
1074 }
1075 })
1076 }
1077 });
1078 reached_outline_node.await;
1079 if let Some(node) = ancestor_range {
1080 return node;
1081 }
1082
1083 let node_name = node.grammar_name();
1084 let node_row_range = RangeInclusive::new(node_range.start.row, node_range.end.row);
1085 if node_name.ends_with("block") {
1086 return Some(node_row_range);
1087 } else if node_name.ends_with("statement") || node_name.ends_with("declaration") {
1088 // Expand to the nearest dedent or blank line for statements and declarations.
1089 let tab_size = cx
1090 .update(|cx| snapshot.settings_at(node_range.start, cx).tab_size.get())
1091 .ok()?;
1092 let indent_level = snapshot
1093 .line_indent_for_row(node_range.start.row)
1094 .len(tab_size);
1095 let rows_remaining = max_row_count.saturating_sub(row_count);
1096 let Some(start_row) = (node_range.start.row.saturating_sub(rows_remaining)
1097 ..node_range.start.row)
1098 .rev()
1099 .find(|row| {
1100 is_line_blank_or_indented_less(indent_level, *row, tab_size, &snapshot.clone())
1101 })
1102 else {
1103 return Some(node_row_range);
1104 };
1105 let rows_remaining = max_row_count.saturating_sub(node_range.end.row - start_row);
1106 let Some(end_row) = (node_range.end.row + 1
1107 ..cmp::min(
1108 node_range.end.row + rows_remaining + 1,
1109 snapshot.row_count(),
1110 ))
1111 .find(|row| {
1112 is_line_blank_or_indented_less(indent_level, *row, tab_size, &snapshot.clone())
1113 })
1114 else {
1115 return Some(node_row_range);
1116 };
1117 return Some(RangeInclusive::new(start_row, end_row));
1118 }
1119
1120 // TODO: doing this instead of walking a cursor as that doesn't work - why?
1121 let Some(parent) = node.parent() else {
1122 log::info!(
1123 "Expanding to ancestor reached the top node, so using default context line count.",
1124 );
1125 return None;
1126 };
1127 node = parent;
1128 }
1129}
1130
1131fn is_line_blank_or_indented_less(
1132 indent_level: u32,
1133 row: u32,
1134 tab_size: u32,
1135 snapshot: &BufferSnapshot,
1136) -> bool {
1137 let line_indent = snapshot.line_indent_for_row(row);
1138 line_indent.is_line_blank() || line_indent.len(tab_size) < indent_level
1139}