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, Diagnostic, DiagnosticEntry, DiagnosticSeverity, Point, Selection, SelectionGoal,
25};
26use lsp::LanguageServerId;
27use project::{DiagnosticSummary, Project, ProjectPath};
28use project_diagnostics_settings::ProjectDiagnosticsSettings;
29use settings::Settings;
30use std::{
31 any::{Any, TypeId},
32 cmp::Ordering,
33 mem,
34 ops::Range,
35 sync::Arc,
36 time::Duration,
37};
38use theme::ActiveTheme;
39pub use toolbar_controls::ToolbarControls;
40use ui::{h_flex, prelude::*, Icon, IconName, Label};
41use util::ResultExt;
42use workspace::{
43 item::{BreadcrumbText, Item, ItemEvent, ItemHandle, TabContentParams},
44 searchable::SearchableItemHandle,
45 ItemNavHistory, ToolbarItemLocation, Workspace,
46};
47
48actions!(diagnostics, [Deploy, ToggleWarnings]);
49
50struct IncludeWarnings(bool);
51impl Global for IncludeWarnings {}
52
53pub fn init(cx: &mut AppContext) {
54 ProjectDiagnosticsSettings::register(cx);
55 cx.observe_new_views(ProjectDiagnosticsEditor::register)
56 .detach();
57}
58
59struct ProjectDiagnosticsEditor {
60 project: Model<Project>,
61 workspace: WeakView<Workspace>,
62 focus_handle: FocusHandle,
63 editor: View<Editor>,
64 summary: DiagnosticSummary,
65 excerpts: Model<MultiBuffer>,
66 path_states: Vec<PathState>,
67 paths_to_update: BTreeSet<(ProjectPath, Option<LanguageServerId>)>,
68 include_warnings: bool,
69 context: u32,
70 update_excerpts_task: Option<Task<Result<()>>>,
71 _subscription: Subscription,
72}
73
74struct PathState {
75 path: ProjectPath,
76 diagnostic_groups: Vec<DiagnosticGroupState>,
77}
78
79struct DiagnosticGroupState {
80 language_server_id: LanguageServerId,
81 primary_diagnostic: DiagnosticEntry<language::Anchor>,
82 primary_excerpt_ix: usize,
83 excerpts: Vec<ExcerptId>,
84 blocks: HashSet<CustomBlockId>,
85 block_count: usize,
86}
87
88impl EventEmitter<EditorEvent> for ProjectDiagnosticsEditor {}
89
90const DIAGNOSTICS_UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
91
92impl Render for ProjectDiagnosticsEditor {
93 fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
94 let child = if self.path_states.is_empty() {
95 div()
96 .bg(cx.theme().colors().editor_background)
97 .flex()
98 .items_center()
99 .justify_center()
100 .size_full()
101 .child(Label::new("No problems in workspace"))
102 } else {
103 div().size_full().child(self.editor.clone())
104 };
105
106 div()
107 .track_focus(&self.focus_handle(cx))
108 .when(self.path_states.is_empty(), |el| {
109 el.key_context("EmptyPane")
110 })
111 .size_full()
112 .on_action(cx.listener(Self::toggle_warnings))
113 .child(child)
114 }
115}
116
117impl ProjectDiagnosticsEditor {
118 fn register(workspace: &mut Workspace, _: &mut ViewContext<Workspace>) {
119 workspace.register_action(Self::deploy);
120 }
121
122 fn new_with_context(
123 context: u32,
124 include_warnings: bool,
125 project_handle: Model<Project>,
126 workspace: WeakView<Workspace>,
127 cx: &mut ViewContext<Self>,
128 ) -> Self {
129 let project_event_subscription =
130 cx.subscribe(&project_handle, |this, project, event, cx| match event {
131 project::Event::DiskBasedDiagnosticsStarted { .. } => {
132 cx.notify();
133 }
134 project::Event::DiskBasedDiagnosticsFinished { language_server_id } => {
135 log::debug!("disk based diagnostics finished for server {language_server_id}");
136 this.update_stale_excerpts(cx);
137 }
138 project::Event::DiagnosticsUpdated {
139 language_server_id,
140 path,
141 } => {
142 this.paths_to_update
143 .insert((path.clone(), Some(*language_server_id)));
144 this.summary = project.read(cx).diagnostic_summary(false, cx);
145 cx.emit(EditorEvent::TitleChanged);
146
147 if this.editor.focus_handle(cx).contains_focused(cx) || this.focus_handle.contains_focused(cx) {
148 log::debug!("diagnostics updated for server {language_server_id}, path {path:?}. recording change");
149 } else {
150 log::debug!("diagnostics updated for server {language_server_id}, path {path:?}. updating excerpts");
151 this.update_stale_excerpts(cx);
152 }
153 }
154 _ => {}
155 });
156
157 let focus_handle = cx.focus_handle();
158 cx.on_focus_in(&focus_handle, |this, cx| this.focus_in(cx))
159 .detach();
160 cx.on_focus_out(&focus_handle, |this, _event, cx| this.focus_out(cx))
161 .detach();
162
163 let excerpts = cx.new_model(|cx| MultiBuffer::new(project_handle.read(cx).capability()));
164 let editor = cx.new_view(|cx| {
165 let mut editor =
166 Editor::for_multibuffer(excerpts.clone(), Some(project_handle.clone()), false, cx);
167 editor.set_vertical_scroll_margin(5, cx);
168 editor
169 });
170 cx.subscribe(&editor, |this, _editor, event: &EditorEvent, cx| {
171 cx.emit(event.clone());
172 match event {
173 EditorEvent::Focused => {
174 if this.path_states.is_empty() {
175 cx.focus(&this.focus_handle);
176 }
177 }
178 EditorEvent::Blurred => this.update_stale_excerpts(cx),
179 _ => {}
180 }
181 })
182 .detach();
183 cx.observe_global::<IncludeWarnings>(|this, cx| {
184 this.include_warnings = cx.global::<IncludeWarnings>().0;
185 this.update_all_excerpts(cx);
186 })
187 .detach();
188
189 let project = project_handle.read(cx);
190 let mut this = Self {
191 project: project_handle.clone(),
192 context,
193 summary: project.diagnostic_summary(false, cx),
194 include_warnings,
195 workspace,
196 excerpts,
197 focus_handle,
198 editor,
199 path_states: Default::default(),
200 paths_to_update: Default::default(),
201 update_excerpts_task: None,
202 _subscription: project_event_subscription,
203 };
204 this.update_all_excerpts(cx);
205 this
206 }
207
208 fn update_stale_excerpts(&mut self, cx: &mut ViewContext<Self>) {
209 if self.update_excerpts_task.is_some() {
210 return;
211 }
212 let project_handle = self.project.clone();
213 self.update_excerpts_task = Some(cx.spawn(|this, mut cx| async move {
214 cx.background_executor()
215 .timer(DIAGNOSTICS_UPDATE_DEBOUNCE)
216 .await;
217 loop {
218 let Some((path, language_server_id)) = this.update(&mut cx, |this, _| {
219 let Some((path, language_server_id)) = this.paths_to_update.pop_first() else {
220 this.update_excerpts_task.take();
221 return None;
222 };
223 Some((path, language_server_id))
224 })?
225 else {
226 break;
227 };
228
229 if let Some(buffer) = project_handle
230 .update(&mut cx, |project, cx| project.open_buffer(path.clone(), cx))?
231 .await
232 .log_err()
233 {
234 this.update(&mut cx, |this, cx| {
235 this.update_excerpts(path, language_server_id, buffer, cx);
236 })?;
237 }
238 }
239 Ok(())
240 }));
241 }
242
243 fn new(
244 project_handle: Model<Project>,
245 include_warnings: bool,
246 workspace: WeakView<Workspace>,
247 cx: &mut ViewContext<Self>,
248 ) -> Self {
249 Self::new_with_context(
250 editor::DEFAULT_MULTIBUFFER_CONTEXT,
251 include_warnings,
252 project_handle,
253 workspace,
254 cx,
255 )
256 }
257
258 fn deploy(workspace: &mut Workspace, _: &Deploy, cx: &mut ViewContext<Workspace>) {
259 if let Some(existing) = workspace.item_of_type::<ProjectDiagnosticsEditor>(cx) {
260 workspace.activate_item(&existing, true, true, cx);
261 } else {
262 let workspace_handle = cx.view().downgrade();
263
264 let include_warnings = match cx.try_global::<IncludeWarnings>() {
265 Some(include_warnings) => include_warnings.0,
266 None => ProjectDiagnosticsSettings::get_global(cx).include_warnings,
267 };
268
269 let diagnostics = cx.new_view(|cx| {
270 ProjectDiagnosticsEditor::new(
271 workspace.project().clone(),
272 include_warnings,
273 workspace_handle,
274 cx,
275 )
276 });
277 workspace.add_item_to_active_pane(Box::new(diagnostics), None, true, cx);
278 }
279 }
280
281 fn toggle_warnings(&mut self, _: &ToggleWarnings, cx: &mut ViewContext<Self>) {
282 self.include_warnings = !self.include_warnings;
283 cx.set_global(IncludeWarnings(self.include_warnings));
284 self.update_all_excerpts(cx);
285 cx.notify();
286 }
287
288 fn focus_in(&mut self, cx: &mut ViewContext<Self>) {
289 if self.focus_handle.is_focused(cx) && !self.path_states.is_empty() {
290 self.editor.focus_handle(cx).focus(cx)
291 }
292 }
293
294 fn focus_out(&mut self, cx: &mut ViewContext<Self>) {
295 if !self.focus_handle.is_focused(cx) && !self.editor.focus_handle(cx).is_focused(cx) {
296 self.update_stale_excerpts(cx);
297 }
298 }
299
300 /// Enqueue an update of all excerpts. Updates all paths that either
301 /// currently have diagnostics or are currently present in this view.
302 fn update_all_excerpts(&mut self, cx: &mut ViewContext<Self>) {
303 self.project.update(cx, |project, cx| {
304 let mut paths = project
305 .diagnostic_summaries(false, cx)
306 .map(|(path, _, _)| (path, None))
307 .collect::<BTreeSet<_>>();
308 paths.extend(
309 self.path_states
310 .iter()
311 .map(|state| (state.path.clone(), None)),
312 );
313 let paths_to_update = std::mem::take(&mut self.paths_to_update);
314 paths.extend(paths_to_update.into_iter().map(|(path, _)| (path, None)));
315 self.paths_to_update = paths;
316 });
317 self.update_stale_excerpts(cx);
318 }
319
320 fn update_excerpts(
321 &mut self,
322 path_to_update: ProjectPath,
323 server_to_update: Option<LanguageServerId>,
324 buffer: Model<Buffer>,
325 cx: &mut ViewContext<Self>,
326 ) {
327 let was_empty = self.path_states.is_empty();
328 let snapshot = buffer.read(cx).snapshot();
329 let path_ix = match self
330 .path_states
331 .binary_search_by_key(&&path_to_update, |e| &e.path)
332 {
333 Ok(ix) => ix,
334 Err(ix) => {
335 self.path_states.insert(
336 ix,
337 PathState {
338 path: path_to_update.clone(),
339 diagnostic_groups: Default::default(),
340 },
341 );
342 ix
343 }
344 };
345
346 let mut prev_excerpt_id = if path_ix > 0 {
347 let prev_path_last_group = &self.path_states[path_ix - 1]
348 .diagnostic_groups
349 .last()
350 .unwrap();
351 *prev_path_last_group.excerpts.last().unwrap()
352 } else {
353 ExcerptId::min()
354 };
355
356 let path_state = &mut self.path_states[path_ix];
357 let mut new_group_ixs = Vec::new();
358 let mut blocks_to_add = Vec::new();
359 let mut blocks_to_remove = HashSet::default();
360 let mut first_excerpt_id = None;
361 let max_severity = if self.include_warnings {
362 DiagnosticSeverity::WARNING
363 } else {
364 DiagnosticSeverity::ERROR
365 };
366 let excerpts_snapshot = self.excerpts.update(cx, |excerpts, cx| {
367 let mut old_groups = mem::take(&mut path_state.diagnostic_groups)
368 .into_iter()
369 .enumerate()
370 .peekable();
371 let mut new_groups = snapshot
372 .diagnostic_groups(server_to_update)
373 .into_iter()
374 .filter(|(_, group)| {
375 group.entries[group.primary_ix].diagnostic.severity <= max_severity
376 })
377 .peekable();
378 loop {
379 let mut to_insert = None;
380 let mut to_remove = None;
381 let mut to_keep = None;
382 match (old_groups.peek(), new_groups.peek()) {
383 (None, None) => break,
384 (None, Some(_)) => to_insert = new_groups.next(),
385 (Some((_, old_group)), None) => {
386 if server_to_update.map_or(true, |id| id == old_group.language_server_id) {
387 to_remove = old_groups.next();
388 } else {
389 to_keep = old_groups.next();
390 }
391 }
392 (Some((_, old_group)), Some((new_language_server_id, new_group))) => {
393 let old_primary = &old_group.primary_diagnostic;
394 let new_primary = &new_group.entries[new_group.primary_ix];
395 match compare_diagnostics(old_primary, new_primary, &snapshot)
396 .then_with(|| old_group.language_server_id.cmp(new_language_server_id))
397 {
398 Ordering::Less => {
399 if server_to_update
400 .map_or(true, |id| id == old_group.language_server_id)
401 {
402 to_remove = old_groups.next();
403 } else {
404 to_keep = old_groups.next();
405 }
406 }
407 Ordering::Equal => {
408 to_keep = old_groups.next();
409 new_groups.next();
410 }
411 Ordering::Greater => to_insert = new_groups.next(),
412 }
413 }
414 }
415
416 if let Some((language_server_id, group)) = to_insert {
417 let mut group_state = DiagnosticGroupState {
418 language_server_id,
419 primary_diagnostic: group.entries[group.primary_ix].clone(),
420 primary_excerpt_ix: 0,
421 excerpts: Default::default(),
422 blocks: Default::default(),
423 block_count: 0,
424 };
425 let mut pending_range: Option<(Range<Point>, usize)> = None;
426 let mut is_first_excerpt_for_group = true;
427 for (ix, entry) in group.entries.iter().map(Some).chain([None]).enumerate() {
428 let resolved_entry = entry.map(|e| e.resolve::<Point>(&snapshot));
429 if let Some((range, start_ix)) = &mut pending_range {
430 if let Some(entry) = resolved_entry.as_ref() {
431 if entry.range.start.row <= range.end.row + 1 + self.context * 2 {
432 range.end = range.end.max(entry.range.end);
433 continue;
434 }
435 }
436
437 let excerpt_start =
438 Point::new(range.start.row.saturating_sub(self.context), 0);
439 let excerpt_end = snapshot.clip_point(
440 Point::new(range.end.row + self.context, u32::MAX),
441 Bias::Left,
442 );
443
444 let excerpt_id = excerpts
445 .insert_excerpts_after(
446 prev_excerpt_id,
447 buffer.clone(),
448 [ExcerptRange {
449 context: excerpt_start..excerpt_end,
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 {
507 pending_range = Some((entry.range.clone(), 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 highlight_style: HighlightStyle = cx.theme().colors().text_accent.into();
839 h_flex()
840 .id(DIAGNOSTIC_HEADER)
841 .block_mouse_down()
842 .h(2. * cx.line_height())
843 .pl_10()
844 .pr_5()
845 .w_full()
846 .justify_between()
847 .gap_2()
848 .child(
849 h_flex()
850 .gap_3()
851 .map(|stack| {
852 stack.child(
853 svg()
854 .size(cx.text_style().font_size)
855 .flex_none()
856 .map(|icon| {
857 if diagnostic.severity == DiagnosticSeverity::ERROR {
858 icon.path(IconName::XCircle.path())
859 .text_color(Color::Error.color(cx))
860 } else {
861 icon.path(IconName::Warning.path())
862 .text_color(Color::Warning.color(cx))
863 }
864 }),
865 )
866 })
867 .child(
868 h_flex()
869 .gap_1()
870 .child(
871 StyledText::new(message.clone()).with_highlights(
872 &cx.text_style(),
873 code_ranges
874 .iter()
875 .map(|range| (range.clone(), highlight_style)),
876 ),
877 )
878 .when_some(diagnostic.code.as_ref(), |stack, code| {
879 stack.child(
880 div()
881 .child(SharedString::from(format!("({code})")))
882 .text_color(cx.theme().colors().text_muted),
883 )
884 }),
885 ),
886 )
887 .child(
888 h_flex()
889 .gap_1()
890 .when_some(diagnostic.source.as_ref(), |stack, source| {
891 stack.child(
892 div()
893 .child(SharedString::from(source.clone()))
894 .text_color(cx.theme().colors().text_muted),
895 )
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}