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