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