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