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