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