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