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