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::{BlockDisposition, 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                                    position: header_position,
443                                    height: 2,
444                                    style: BlockStyle::Sticky,
445                                    render: diagnostic_header_renderer(primary),
446                                    disposition: BlockDisposition::Above,
447                                    priority: 0,
448                                });
449                            }
450
451                            for entry in &group.entries[*start_ix..ix] {
452                                let mut diagnostic = entry.diagnostic.clone();
453                                if diagnostic.is_primary {
454                                    group_state.primary_excerpt_ix = group_state.excerpts.len() - 1;
455                                    diagnostic.message =
456                                        entry.diagnostic.message.split('\n').skip(1).collect();
457                                }
458
459                                if !diagnostic.message.is_empty() {
460                                    group_state.block_count += 1;
461                                    blocks_to_add.push(BlockProperties {
462                                        position: (excerpt_id, entry.range.start),
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                                        disposition: BlockDisposition::Below,
469                                        priority: 0,
470                                    });
471                                }
472                            }
473
474                            pending_range.take();
475                        }
476
477                        if let Some(entry) = resolved_entry {
478                            pending_range = Some((entry.range.clone(), ix));
479                        }
480                    }
481
482                    new_group_ixs.push(path_state.diagnostic_groups.len());
483                    path_state.diagnostic_groups.push(group_state);
484                } else if let Some((_, group_state)) = to_remove {
485                    excerpts.remove_excerpts(group_state.excerpts.iter().copied(), cx);
486                    blocks_to_remove.extend(group_state.blocks.iter().copied());
487                } else if let Some((_, group_state)) = to_keep {
488                    prev_excerpt_id = *group_state.excerpts.last().unwrap();
489                    first_excerpt_id.get_or_insert(prev_excerpt_id);
490                    path_state.diagnostic_groups.push(group_state);
491                }
492            }
493
494            excerpts.snapshot(cx)
495        });
496
497        self.editor.update(cx, |editor, cx| {
498            editor.remove_blocks(blocks_to_remove, None, cx);
499            let block_ids = editor.insert_blocks(
500                blocks_to_add.into_iter().flat_map(|block| {
501                    let (excerpt_id, text_anchor) = block.position;
502                    Some(BlockProperties {
503                        position: excerpts_snapshot.anchor_in_excerpt(excerpt_id, text_anchor)?,
504                        height: block.height,
505                        style: block.style,
506                        render: block.render,
507                        disposition: block.disposition,
508                        priority: 0,
509                    })
510                }),
511                Some(Autoscroll::fit()),
512                cx,
513            );
514
515            let mut block_ids = block_ids.into_iter();
516            for ix in new_group_ixs {
517                let group_state = &mut path_state.diagnostic_groups[ix];
518                group_state.blocks = block_ids.by_ref().take(group_state.block_count).collect();
519            }
520        });
521
522        if path_state.diagnostic_groups.is_empty() {
523            self.path_states.remove(path_ix);
524        }
525
526        self.editor.update(cx, |editor, cx| {
527            let groups;
528            let mut selections;
529            let new_excerpt_ids_by_selection_id;
530            if was_empty {
531                groups = self.path_states.first()?.diagnostic_groups.as_slice();
532                new_excerpt_ids_by_selection_id = [(0, ExcerptId::min())].into_iter().collect();
533                selections = vec![Selection {
534                    id: 0,
535                    start: 0,
536                    end: 0,
537                    reversed: false,
538                    goal: SelectionGoal::None,
539                }];
540            } else {
541                groups = self.path_states.get(path_ix)?.diagnostic_groups.as_slice();
542                new_excerpt_ids_by_selection_id =
543                    editor.change_selections(Some(Autoscroll::fit()), cx, |s| s.refresh());
544                selections = editor.selections.all::<usize>(cx);
545            }
546
547            // If any selection has lost its position, move it to start of the next primary diagnostic.
548            let snapshot = editor.snapshot(cx);
549            for selection in &mut selections {
550                if let Some(new_excerpt_id) = new_excerpt_ids_by_selection_id.get(&selection.id) {
551                    let group_ix = match groups.binary_search_by(|probe| {
552                        probe
553                            .excerpts
554                            .last()
555                            .unwrap()
556                            .cmp(new_excerpt_id, &snapshot.buffer_snapshot)
557                    }) {
558                        Ok(ix) | Err(ix) => ix,
559                    };
560                    if let Some(group) = groups.get(group_ix) {
561                        if let Some(offset) = excerpts_snapshot
562                            .anchor_in_excerpt(
563                                group.excerpts[group.primary_excerpt_ix],
564                                group.primary_diagnostic.range.start,
565                            )
566                            .map(|anchor| anchor.to_offset(&excerpts_snapshot))
567                        {
568                            selection.start = offset;
569                            selection.end = offset;
570                        }
571                    }
572                }
573            }
574            editor.change_selections(None, cx, |s| {
575                s.select(selections);
576            });
577            Some(())
578        });
579
580        if self.path_states.is_empty() {
581            if self.editor.focus_handle(cx).is_focused(cx) {
582                cx.focus(&self.focus_handle);
583            }
584        } else if self.focus_handle.is_focused(cx) {
585            let focus_handle = self.editor.focus_handle(cx);
586            cx.focus(&focus_handle);
587        }
588
589        #[cfg(test)]
590        self.check_invariants(cx);
591
592        cx.notify();
593    }
594
595    #[cfg(test)]
596    fn check_invariants(&self, cx: &mut ViewContext<Self>) {
597        let mut excerpts = Vec::new();
598        for (id, buffer, _) in self.excerpts.read(cx).snapshot(cx).excerpts() {
599            if let Some(file) = buffer.file() {
600                excerpts.push((id, file.path().clone()));
601            }
602        }
603
604        let mut prev_path = None;
605        for (_, path) in &excerpts {
606            if let Some(prev_path) = prev_path {
607                if path < prev_path {
608                    panic!("excerpts are not sorted by path {:?}", excerpts);
609                }
610            }
611            prev_path = Some(path);
612        }
613    }
614}
615
616impl FocusableView for ProjectDiagnosticsEditor {
617    fn focus_handle(&self, _: &AppContext) -> FocusHandle {
618        self.focus_handle.clone()
619    }
620}
621
622impl Item for ProjectDiagnosticsEditor {
623    type Event = EditorEvent;
624
625    fn to_item_events(event: &EditorEvent, f: impl FnMut(ItemEvent)) {
626        Editor::to_item_events(event, f)
627    }
628
629    fn deactivated(&mut self, cx: &mut ViewContext<Self>) {
630        self.editor.update(cx, |editor, cx| editor.deactivated(cx));
631    }
632
633    fn navigate(&mut self, data: Box<dyn Any>, cx: &mut ViewContext<Self>) -> bool {
634        self.editor
635            .update(cx, |editor, cx| editor.navigate(data, cx))
636    }
637
638    fn tab_tooltip_text(&self, _: &AppContext) -> Option<SharedString> {
639        Some("Project Diagnostics".into())
640    }
641
642    fn tab_content(&self, params: TabContentParams, _: &WindowContext) -> AnyElement {
643        h_flex()
644            .gap_1()
645            .when(
646                self.summary.error_count == 0 && self.summary.warning_count == 0,
647                |then| {
648                    then.child(
649                        h_flex()
650                            .gap_1()
651                            .child(Icon::new(IconName::Check).color(Color::Success))
652                            .child(Label::new("No problems").color(params.text_color())),
653                    )
654                },
655            )
656            .when(self.summary.error_count > 0, |then| {
657                then.child(
658                    h_flex()
659                        .gap_1()
660                        .child(Icon::new(IconName::XCircle).color(Color::Error))
661                        .child(
662                            Label::new(self.summary.error_count.to_string())
663                                .color(params.text_color()),
664                        ),
665                )
666            })
667            .when(self.summary.warning_count > 0, |then| {
668                then.child(
669                    h_flex()
670                        .gap_1()
671                        .child(Icon::new(IconName::Warning).color(Color::Warning))
672                        .child(
673                            Label::new(self.summary.warning_count.to_string())
674                                .color(params.text_color()),
675                        ),
676                )
677            })
678            .into_any_element()
679    }
680
681    fn telemetry_event_text(&self) -> Option<&'static str> {
682        Some("project diagnostics")
683    }
684
685    fn for_each_project_item(
686        &self,
687        cx: &AppContext,
688        f: &mut dyn FnMut(gpui::EntityId, &dyn project::Item),
689    ) {
690        self.editor.for_each_project_item(cx, f)
691    }
692
693    fn is_singleton(&self, _: &AppContext) -> bool {
694        false
695    }
696
697    fn set_nav_history(&mut self, nav_history: ItemNavHistory, cx: &mut ViewContext<Self>) {
698        self.editor.update(cx, |editor, _| {
699            editor.set_nav_history(Some(nav_history));
700        });
701    }
702
703    fn clone_on_split(
704        &self,
705        _workspace_id: Option<workspace::WorkspaceId>,
706        cx: &mut ViewContext<Self>,
707    ) -> Option<View<Self>>
708    where
709        Self: Sized,
710    {
711        Some(cx.new_view(|cx| {
712            ProjectDiagnosticsEditor::new(self.project.clone(), self.workspace.clone(), cx)
713        }))
714    }
715
716    fn is_dirty(&self, cx: &AppContext) -> bool {
717        self.excerpts.read(cx).is_dirty(cx)
718    }
719
720    fn has_conflict(&self, cx: &AppContext) -> bool {
721        self.excerpts.read(cx).has_conflict(cx)
722    }
723
724    fn can_save(&self, _: &AppContext) -> bool {
725        true
726    }
727
728    fn save(
729        &mut self,
730        format: bool,
731        project: Model<Project>,
732        cx: &mut ViewContext<Self>,
733    ) -> Task<Result<()>> {
734        self.editor.save(format, project, cx)
735    }
736
737    fn save_as(
738        &mut self,
739        _: Model<Project>,
740        _: ProjectPath,
741        _: &mut ViewContext<Self>,
742    ) -> Task<Result<()>> {
743        unreachable!()
744    }
745
746    fn reload(&mut self, project: Model<Project>, cx: &mut ViewContext<Self>) -> Task<Result<()>> {
747        self.editor.reload(project, cx)
748    }
749
750    fn act_as_type<'a>(
751        &'a self,
752        type_id: TypeId,
753        self_handle: &'a View<Self>,
754        _: &'a AppContext,
755    ) -> Option<AnyView> {
756        if type_id == TypeId::of::<Self>() {
757            Some(self_handle.to_any())
758        } else if type_id == TypeId::of::<Editor>() {
759            Some(self.editor.to_any())
760        } else {
761            None
762        }
763    }
764
765    fn breadcrumb_location(&self) -> ToolbarItemLocation {
766        ToolbarItemLocation::PrimaryLeft
767    }
768
769    fn breadcrumbs(&self, theme: &theme::Theme, cx: &AppContext) -> Option<Vec<BreadcrumbText>> {
770        self.editor.breadcrumbs(theme, cx)
771    }
772
773    fn added_to_workspace(&mut self, workspace: &mut Workspace, cx: &mut ViewContext<Self>) {
774        self.editor
775            .update(cx, |editor, cx| editor.added_to_workspace(workspace, cx));
776    }
777}
778
779const DIAGNOSTIC_HEADER: &str = "diagnostic header";
780
781fn diagnostic_header_renderer(diagnostic: Diagnostic) -> RenderBlock {
782    let (message, code_ranges) = highlight_diagnostic_message(&diagnostic, None);
783    let message: SharedString = message;
784    Box::new(move |cx| {
785        let highlight_style: HighlightStyle = cx.theme().colors().text_accent.into();
786        h_flex()
787            .id(DIAGNOSTIC_HEADER)
788            .h(2. * cx.line_height())
789            .pl_10()
790            .pr_5()
791            .w_full()
792            .justify_between()
793            .gap_2()
794            .child(
795                h_flex()
796                    .gap_3()
797                    .map(|stack| {
798                        stack.child(
799                            svg()
800                                .size(cx.text_style().font_size)
801                                .flex_none()
802                                .map(|icon| {
803                                    if diagnostic.severity == DiagnosticSeverity::ERROR {
804                                        icon.path(IconName::XCircle.path())
805                                            .text_color(Color::Error.color(cx))
806                                    } else {
807                                        icon.path(IconName::Warning.path())
808                                            .text_color(Color::Warning.color(cx))
809                                    }
810                                }),
811                        )
812                    })
813                    .child(
814                        h_flex()
815                            .gap_1()
816                            .child(
817                                StyledText::new(message.clone()).with_highlights(
818                                    &cx.text_style(),
819                                    code_ranges
820                                        .iter()
821                                        .map(|range| (range.clone(), highlight_style)),
822                                ),
823                            )
824                            .when_some(diagnostic.code.as_ref(), |stack, code| {
825                                stack.child(
826                                    div()
827                                        .child(SharedString::from(format!("({code})")))
828                                        .text_color(cx.theme().colors().text_muted),
829                                )
830                            }),
831                    ),
832            )
833            .child(
834                h_flex()
835                    .gap_1()
836                    .when_some(diagnostic.source.as_ref(), |stack, source| {
837                        stack.child(
838                            div()
839                                .child(SharedString::from(source.clone()))
840                                .text_color(cx.theme().colors().text_muted),
841                        )
842                    }),
843            )
844            .into_any_element()
845    })
846}
847
848fn compare_diagnostics(
849    old: &DiagnosticEntry<language::Anchor>,
850    new: &DiagnosticEntry<language::Anchor>,
851    snapshot: &language::BufferSnapshot,
852) -> Ordering {
853    use language::ToOffset;
854
855    // The diagnostics may point to a previously open Buffer for this file.
856    if !old.range.start.is_valid(snapshot) || !new.range.start.is_valid(snapshot) {
857        return Ordering::Greater;
858    }
859
860    old.range
861        .start
862        .to_offset(snapshot)
863        .cmp(&new.range.start.to_offset(snapshot))
864        .then_with(|| {
865            old.range
866                .end
867                .to_offset(snapshot)
868                .cmp(&new.range.end.to_offset(snapshot))
869        })
870        .then_with(|| old.diagnostic.message.cmp(&new.diagnostic.message))
871}