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