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