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