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