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