diagnostics.rs

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