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, Global, HighlightStyle, InteractiveElement, IntoElement, Model, ParentElement,
  20    Render, SharedString, Styled, StyledText, Subscription, Task, View, ViewContext, VisualContext,
  21    WeakView, WindowContext,
  22};
  23use language::{
  24    Bias, Buffer, BufferRow, BufferSnapshot, Diagnostic, DiagnosticEntry, DiagnosticSeverity,
  25    Point, Selection, SelectionGoal, ToTreeSitterPoint,
  26};
  27use lsp::LanguageServerId;
  28use project::{DiagnosticSummary, Project, ProjectPath};
  29use project_diagnostics_settings::ProjectDiagnosticsSettings;
  30use settings::Settings;
  31use std::{
  32    any::{Any, TypeId},
  33    cmp,
  34    cmp::Ordering,
  35    mem,
  36    ops::{Range, RangeInclusive},
  37    sync::Arc,
  38    time::Duration,
  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    searchable::SearchableItemHandle,
  47    ItemNavHistory, ToolbarItemLocation, Workspace,
  48};
  49
  50actions!(diagnostics, [Deploy, ToggleWarnings]);
  51
  52struct IncludeWarnings(bool);
  53impl Global for IncludeWarnings {}
  54
  55pub fn init(cx: &mut AppContext) {
  56    ProjectDiagnosticsSettings::register(cx);
  57    cx.observe_new_views(ProjectDiagnosticsEditor::register)
  58        .detach();
  59}
  60
  61struct ProjectDiagnosticsEditor {
  62    project: Model<Project>,
  63    workspace: WeakView<Workspace>,
  64    focus_handle: FocusHandle,
  65    editor: View<Editor>,
  66    summary: DiagnosticSummary,
  67    excerpts: Model<MultiBuffer>,
  68    path_states: Vec<PathState>,
  69    paths_to_update: BTreeSet<(ProjectPath, Option<LanguageServerId>)>,
  70    include_warnings: bool,
  71    context: u32,
  72    update_excerpts_task: Option<Task<Result<()>>>,
  73    _subscription: Subscription,
  74}
  75
  76struct PathState {
  77    path: ProjectPath,
  78    diagnostic_groups: Vec<DiagnosticGroupState>,
  79}
  80
  81struct DiagnosticGroupState {
  82    language_server_id: LanguageServerId,
  83    primary_diagnostic: DiagnosticEntry<language::Anchor>,
  84    primary_excerpt_ix: usize,
  85    excerpts: Vec<ExcerptId>,
  86    blocks: HashSet<CustomBlockId>,
  87    block_count: usize,
  88}
  89
  90impl EventEmitter<EditorEvent> for ProjectDiagnosticsEditor {}
  91
  92const DIAGNOSTICS_UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
  93
  94impl Render for ProjectDiagnosticsEditor {
  95    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
  96        let child = if self.path_states.is_empty() {
  97            div()
  98                .key_context("EmptyPane")
  99                .bg(cx.theme().colors().editor_background)
 100                .flex()
 101                .items_center()
 102                .justify_center()
 103                .size_full()
 104                .child(Label::new("No problems in workspace"))
 105        } else {
 106            div().size_full().child(self.editor.clone())
 107        };
 108
 109        div()
 110            .key_context("Diagnostics")
 111            .track_focus(&self.focus_handle(cx))
 112            .size_full()
 113            .on_action(cx.listener(Self::toggle_warnings))
 114            .child(child)
 115    }
 116}
 117
 118impl ProjectDiagnosticsEditor {
 119    fn register(workspace: &mut Workspace, _: &mut ViewContext<Workspace>) {
 120        workspace.register_action(Self::deploy);
 121    }
 122
 123    fn new_with_context(
 124        context: u32,
 125        include_warnings: bool,
 126        project_handle: Model<Project>,
 127        workspace: WeakView<Workspace>,
 128        cx: &mut ViewContext<Self>,
 129    ) -> Self {
 130        let project_event_subscription =
 131            cx.subscribe(&project_handle, |this, project, event, cx| match event {
 132                project::Event::DiskBasedDiagnosticsStarted { .. } => {
 133                    cx.notify();
 134                }
 135                project::Event::DiskBasedDiagnosticsFinished { language_server_id } => {
 136                    log::debug!("disk based diagnostics finished for server {language_server_id}");
 137                    this.update_stale_excerpts(cx);
 138                }
 139                project::Event::DiagnosticsUpdated {
 140                    language_server_id,
 141                    path,
 142                } => {
 143                    this.paths_to_update
 144                        .insert((path.clone(), Some(*language_server_id)));
 145                    this.summary = project.read(cx).diagnostic_summary(false, cx);
 146                    cx.emit(EditorEvent::TitleChanged);
 147
 148                    if this.editor.focus_handle(cx).contains_focused(cx) || this.focus_handle.contains_focused(cx) {
 149                        log::debug!("diagnostics updated for server {language_server_id}, path {path:?}. recording change");
 150                    } else {
 151                        log::debug!("diagnostics updated for server {language_server_id}, path {path:?}. updating excerpts");
 152                        this.update_stale_excerpts(cx);
 153                    }
 154                }
 155                _ => {}
 156            });
 157
 158        let focus_handle = cx.focus_handle();
 159        cx.on_focus_in(&focus_handle, |this, cx| this.focus_in(cx))
 160            .detach();
 161        cx.on_focus_out(&focus_handle, |this, _event, cx| this.focus_out(cx))
 162            .detach();
 163
 164        let excerpts = cx.new_model(|cx| MultiBuffer::new(project_handle.read(cx).capability()));
 165        let editor = cx.new_view(|cx| {
 166            let mut editor =
 167                Editor::for_multibuffer(excerpts.clone(), Some(project_handle.clone()), true, 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.update_stale_excerpts(cx),
 180                _ => {}
 181            }
 182        })
 183        .detach();
 184        cx.observe_global::<IncludeWarnings>(|this, cx| {
 185            this.include_warnings = cx.global::<IncludeWarnings>().0;
 186            this.update_all_excerpts(cx);
 187        })
 188        .detach();
 189
 190        let project = project_handle.read(cx);
 191        let mut this = Self {
 192            project: project_handle.clone(),
 193            context,
 194            summary: project.diagnostic_summary(false, cx),
 195            include_warnings,
 196            workspace,
 197            excerpts,
 198            focus_handle,
 199            editor,
 200            path_states: Default::default(),
 201            paths_to_update: Default::default(),
 202            update_excerpts_task: None,
 203            _subscription: project_event_subscription,
 204        };
 205        this.update_all_excerpts(cx);
 206        this
 207    }
 208
 209    fn update_stale_excerpts(&mut self, cx: &mut ViewContext<Self>) {
 210        if self.update_excerpts_task.is_some() {
 211            return;
 212        }
 213        let project_handle = self.project.clone();
 214        self.update_excerpts_task = Some(cx.spawn(|this, mut cx| async move {
 215            cx.background_executor()
 216                .timer(DIAGNOSTICS_UPDATE_DEBOUNCE)
 217                .await;
 218            loop {
 219                let Some((path, language_server_id)) = this.update(&mut cx, |this, _| {
 220                    let Some((path, language_server_id)) = this.paths_to_update.pop_first() else {
 221                        this.update_excerpts_task.take();
 222                        return None;
 223                    };
 224                    Some((path, language_server_id))
 225                })?
 226                else {
 227                    break;
 228                };
 229
 230                if let Some(buffer) = project_handle
 231                    .update(&mut cx, |project, cx| project.open_buffer(path.clone(), cx))?
 232                    .await
 233                    .log_err()
 234                {
 235                    this.update(&mut cx, |this, cx| {
 236                        this.update_excerpts(path, language_server_id, buffer, cx);
 237                    })?;
 238                }
 239            }
 240            Ok(())
 241        }));
 242    }
 243
 244    fn new(
 245        project_handle: Model<Project>,
 246        include_warnings: bool,
 247        workspace: WeakView<Workspace>,
 248        cx: &mut ViewContext<Self>,
 249    ) -> Self {
 250        Self::new_with_context(
 251            editor::DEFAULT_MULTIBUFFER_CONTEXT,
 252            include_warnings,
 253            project_handle,
 254            workspace,
 255            cx,
 256        )
 257    }
 258
 259    fn deploy(workspace: &mut Workspace, _: &Deploy, cx: &mut ViewContext<Workspace>) {
 260        if let Some(existing) = workspace.item_of_type::<ProjectDiagnosticsEditor>(cx) {
 261            workspace.activate_item(&existing, true, true, cx);
 262        } else {
 263            let workspace_handle = cx.view().downgrade();
 264
 265            let include_warnings = match cx.try_global::<IncludeWarnings>() {
 266                Some(include_warnings) => include_warnings.0,
 267                None => ProjectDiagnosticsSettings::get_global(cx).include_warnings,
 268            };
 269
 270            let diagnostics = cx.new_view(|cx| {
 271                ProjectDiagnosticsEditor::new(
 272                    workspace.project().clone(),
 273                    include_warnings,
 274                    workspace_handle,
 275                    cx,
 276                )
 277            });
 278            workspace.add_item_to_active_pane(Box::new(diagnostics), None, true, cx);
 279        }
 280    }
 281
 282    fn toggle_warnings(&mut self, _: &ToggleWarnings, cx: &mut ViewContext<Self>) {
 283        self.include_warnings = !self.include_warnings;
 284        cx.set_global(IncludeWarnings(self.include_warnings));
 285        self.update_all_excerpts(cx);
 286        cx.notify();
 287    }
 288
 289    fn focus_in(&mut self, cx: &mut ViewContext<Self>) {
 290        if self.focus_handle.is_focused(cx) && !self.path_states.is_empty() {
 291            self.editor.focus_handle(cx).focus(cx)
 292        }
 293    }
 294
 295    fn focus_out(&mut self, cx: &mut ViewContext<Self>) {
 296        if !self.focus_handle.is_focused(cx) && !self.editor.focus_handle(cx).is_focused(cx) {
 297            self.update_stale_excerpts(cx);
 298        }
 299    }
 300
 301    /// Enqueue an update of all excerpts. Updates all paths that either
 302    /// currently have diagnostics or are currently present in this view.
 303    fn update_all_excerpts(&mut self, cx: &mut ViewContext<Self>) {
 304        self.project.update(cx, |project, cx| {
 305            let mut paths = project
 306                .diagnostic_summaries(false, cx)
 307                .map(|(path, _, _)| (path, None))
 308                .collect::<BTreeSet<_>>();
 309            paths.extend(
 310                self.path_states
 311                    .iter()
 312                    .map(|state| (state.path.clone(), None)),
 313            );
 314            let paths_to_update = std::mem::take(&mut self.paths_to_update);
 315            paths.extend(paths_to_update.into_iter().map(|(path, _)| (path, None)));
 316            self.paths_to_update = paths;
 317        });
 318        self.update_stale_excerpts(cx);
 319    }
 320
 321    fn update_excerpts(
 322        &mut self,
 323        path_to_update: ProjectPath,
 324        server_to_update: Option<LanguageServerId>,
 325        buffer: Model<Buffer>,
 326        cx: &mut ViewContext<Self>,
 327    ) {
 328        let was_empty = self.path_states.is_empty();
 329        let snapshot = buffer.read(cx).snapshot();
 330        let path_ix = match self
 331            .path_states
 332            .binary_search_by_key(&&path_to_update, |e| &e.path)
 333        {
 334            Ok(ix) => ix,
 335            Err(ix) => {
 336                self.path_states.insert(
 337                    ix,
 338                    PathState {
 339                        path: path_to_update.clone(),
 340                        diagnostic_groups: Default::default(),
 341                    },
 342                );
 343                ix
 344            }
 345        };
 346
 347        let mut prev_excerpt_id = if path_ix > 0 {
 348            let prev_path_last_group = &self.path_states[path_ix - 1]
 349                .diagnostic_groups
 350                .last()
 351                .unwrap();
 352            *prev_path_last_group.excerpts.last().unwrap()
 353        } else {
 354            ExcerptId::min()
 355        };
 356
 357        let path_state = &mut self.path_states[path_ix];
 358        let mut new_group_ixs = Vec::new();
 359        let mut blocks_to_add = Vec::new();
 360        let mut blocks_to_remove = HashSet::default();
 361        let mut first_excerpt_id = None;
 362        let max_severity = if self.include_warnings {
 363            DiagnosticSeverity::WARNING
 364        } else {
 365            DiagnosticSeverity::ERROR
 366        };
 367        let excerpts_snapshot = self.excerpts.update(cx, |excerpts, cx| {
 368            let mut old_groups = mem::take(&mut path_state.diagnostic_groups)
 369                .into_iter()
 370                .enumerate()
 371                .peekable();
 372            let mut new_groups = snapshot
 373                .diagnostic_groups(server_to_update)
 374                .into_iter()
 375                .filter(|(_, group)| {
 376                    group.entries[group.primary_ix].diagnostic.severity <= max_severity
 377                })
 378                .peekable();
 379            loop {
 380                let mut to_insert = None;
 381                let mut to_remove = None;
 382                let mut to_keep = None;
 383                match (old_groups.peek(), new_groups.peek()) {
 384                    (None, None) => break,
 385                    (None, Some(_)) => to_insert = new_groups.next(),
 386                    (Some((_, old_group)), None) => {
 387                        if server_to_update.map_or(true, |id| id == old_group.language_server_id) {
 388                            to_remove = old_groups.next();
 389                        } else {
 390                            to_keep = old_groups.next();
 391                        }
 392                    }
 393                    (Some((_, old_group)), Some((new_language_server_id, new_group))) => {
 394                        let old_primary = &old_group.primary_diagnostic;
 395                        let new_primary = &new_group.entries[new_group.primary_ix];
 396                        match compare_diagnostics(old_primary, new_primary, &snapshot)
 397                            .then_with(|| old_group.language_server_id.cmp(new_language_server_id))
 398                        {
 399                            Ordering::Less => {
 400                                if server_to_update
 401                                    .map_or(true, |id| id == old_group.language_server_id)
 402                                {
 403                                    to_remove = old_groups.next();
 404                                } else {
 405                                    to_keep = old_groups.next();
 406                                }
 407                            }
 408                            Ordering::Equal => {
 409                                to_keep = old_groups.next();
 410                                new_groups.next();
 411                            }
 412                            Ordering::Greater => to_insert = new_groups.next(),
 413                        }
 414                    }
 415                }
 416
 417                if let Some((language_server_id, group)) = to_insert {
 418                    let mut group_state = DiagnosticGroupState {
 419                        language_server_id,
 420                        primary_diagnostic: group.entries[group.primary_ix].clone(),
 421                        primary_excerpt_ix: 0,
 422                        excerpts: Default::default(),
 423                        blocks: Default::default(),
 424                        block_count: 0,
 425                    };
 426                    let mut pending_range: Option<(Range<Point>, Range<Point>, usize)> = None;
 427                    let mut is_first_excerpt_for_group = true;
 428                    for (ix, entry) in group.entries.iter().map(Some).chain([None]).enumerate() {
 429                        let resolved_entry = entry.map(|e| e.resolve::<Point>(&snapshot));
 430                        let expanded_range = resolved_entry.as_ref().map(|entry| {
 431                            context_range_for_entry(entry, self.context, &snapshot, cx)
 432                        });
 433                        if let Some((range, context_range, start_ix)) = &mut pending_range {
 434                            if let Some(expanded_range) = expanded_range.clone() {
 435                                // If the entries are overlapping or next to each-other, merge them into one excerpt.
 436                                if context_range.end.row + 1 >= expanded_range.start.row {
 437                                    context_range.end = context_range.end.max(expanded_range.end);
 438                                    continue;
 439                                }
 440                            }
 441
 442                            let excerpt_id = excerpts
 443                                .insert_excerpts_after(
 444                                    prev_excerpt_id,
 445                                    buffer.clone(),
 446                                    [ExcerptRange {
 447                                        context: context_range.clone(),
 448                                        primary: Some(range.clone()),
 449                                    }],
 450                                    cx,
 451                                )
 452                                .pop()
 453                                .unwrap();
 454
 455                            prev_excerpt_id = excerpt_id;
 456                            first_excerpt_id.get_or_insert(prev_excerpt_id);
 457                            group_state.excerpts.push(excerpt_id);
 458                            let header_position = (excerpt_id, language::Anchor::MIN);
 459
 460                            if is_first_excerpt_for_group {
 461                                is_first_excerpt_for_group = false;
 462                                let mut primary =
 463                                    group.entries[group.primary_ix].diagnostic.clone();
 464                                primary.message =
 465                                    primary.message.split('\n').next().unwrap().to_string();
 466                                group_state.block_count += 1;
 467                                blocks_to_add.push(BlockProperties {
 468                                    placement: BlockPlacement::Above(header_position),
 469                                    height: 2,
 470                                    style: BlockStyle::Sticky,
 471                                    render: diagnostic_header_renderer(primary),
 472                                    priority: 0,
 473                                });
 474                            }
 475
 476                            for entry in &group.entries[*start_ix..ix] {
 477                                let mut diagnostic = entry.diagnostic.clone();
 478                                if diagnostic.is_primary {
 479                                    group_state.primary_excerpt_ix = group_state.excerpts.len() - 1;
 480                                    diagnostic.message =
 481                                        entry.diagnostic.message.split('\n').skip(1).collect();
 482                                }
 483
 484                                if !diagnostic.message.is_empty() {
 485                                    group_state.block_count += 1;
 486                                    blocks_to_add.push(BlockProperties {
 487                                        placement: BlockPlacement::Below((
 488                                            excerpt_id,
 489                                            entry.range.start,
 490                                        )),
 491                                        height: diagnostic.message.matches('\n').count() as u32 + 1,
 492                                        style: BlockStyle::Fixed,
 493                                        render: diagnostic_block_renderer(
 494                                            diagnostic, None, true, true,
 495                                        ),
 496                                        priority: 0,
 497                                    });
 498                                }
 499                            }
 500
 501                            pending_range.take();
 502                        }
 503
 504                        if let Some(entry) = resolved_entry.as_ref() {
 505                            let range = entry.range.clone();
 506                            pending_range = Some((range, expanded_range.unwrap(), ix));
 507                        }
 508                    }
 509
 510                    new_group_ixs.push(path_state.diagnostic_groups.len());
 511                    path_state.diagnostic_groups.push(group_state);
 512                } else if let Some((_, group_state)) = to_remove {
 513                    excerpts.remove_excerpts(group_state.excerpts.iter().copied(), cx);
 514                    blocks_to_remove.extend(group_state.blocks.iter().copied());
 515                } else if let Some((_, group_state)) = to_keep {
 516                    prev_excerpt_id = *group_state.excerpts.last().unwrap();
 517                    first_excerpt_id.get_or_insert(prev_excerpt_id);
 518                    path_state.diagnostic_groups.push(group_state);
 519                }
 520            }
 521
 522            excerpts.snapshot(cx)
 523        });
 524
 525        self.editor.update(cx, |editor, cx| {
 526            editor.remove_blocks(blocks_to_remove, None, cx);
 527            let block_ids = editor.insert_blocks(
 528                blocks_to_add.into_iter().flat_map(|block| {
 529                    let placement = match block.placement {
 530                        BlockPlacement::Above((excerpt_id, text_anchor)) => BlockPlacement::Above(
 531                            excerpts_snapshot.anchor_in_excerpt(excerpt_id, text_anchor)?,
 532                        ),
 533                        BlockPlacement::Below((excerpt_id, text_anchor)) => BlockPlacement::Below(
 534                            excerpts_snapshot.anchor_in_excerpt(excerpt_id, text_anchor)?,
 535                        ),
 536                        BlockPlacement::Replace(_) => {
 537                            unreachable!(
 538                                "no Replace block should have been pushed to blocks_to_add"
 539                            )
 540                        }
 541                    };
 542                    Some(BlockProperties {
 543                        placement,
 544                        height: block.height,
 545                        style: block.style,
 546                        render: block.render,
 547                        priority: 0,
 548                    })
 549                }),
 550                Some(Autoscroll::fit()),
 551                cx,
 552            );
 553
 554            let mut block_ids = block_ids.into_iter();
 555            for ix in new_group_ixs {
 556                let group_state = &mut path_state.diagnostic_groups[ix];
 557                group_state.blocks = block_ids.by_ref().take(group_state.block_count).collect();
 558            }
 559        });
 560
 561        if path_state.diagnostic_groups.is_empty() {
 562            self.path_states.remove(path_ix);
 563        }
 564
 565        self.editor.update(cx, |editor, cx| {
 566            let groups;
 567            let mut selections;
 568            let new_excerpt_ids_by_selection_id;
 569            if was_empty {
 570                groups = self.path_states.first()?.diagnostic_groups.as_slice();
 571                new_excerpt_ids_by_selection_id = [(0, ExcerptId::min())].into_iter().collect();
 572                selections = vec![Selection {
 573                    id: 0,
 574                    start: 0,
 575                    end: 0,
 576                    reversed: false,
 577                    goal: SelectionGoal::None,
 578                }];
 579            } else {
 580                groups = self.path_states.get(path_ix)?.diagnostic_groups.as_slice();
 581                new_excerpt_ids_by_selection_id =
 582                    editor.change_selections(Some(Autoscroll::fit()), cx, |s| s.refresh());
 583                selections = editor.selections.all::<usize>(cx);
 584            }
 585
 586            // If any selection has lost its position, move it to start of the next primary diagnostic.
 587            let snapshot = editor.snapshot(cx);
 588            for selection in &mut selections {
 589                if let Some(new_excerpt_id) = new_excerpt_ids_by_selection_id.get(&selection.id) {
 590                    let group_ix = match groups.binary_search_by(|probe| {
 591                        probe
 592                            .excerpts
 593                            .last()
 594                            .unwrap()
 595                            .cmp(new_excerpt_id, &snapshot.buffer_snapshot)
 596                    }) {
 597                        Ok(ix) | Err(ix) => ix,
 598                    };
 599                    if let Some(group) = groups.get(group_ix) {
 600                        if let Some(offset) = excerpts_snapshot
 601                            .anchor_in_excerpt(
 602                                group.excerpts[group.primary_excerpt_ix],
 603                                group.primary_diagnostic.range.start,
 604                            )
 605                            .map(|anchor| anchor.to_offset(&excerpts_snapshot))
 606                        {
 607                            selection.start = offset;
 608                            selection.end = offset;
 609                        }
 610                    }
 611                }
 612            }
 613            editor.change_selections(None, cx, |s| {
 614                s.select(selections);
 615            });
 616            Some(())
 617        });
 618
 619        if self.path_states.is_empty() {
 620            if self.editor.focus_handle(cx).is_focused(cx) {
 621                cx.focus(&self.focus_handle);
 622            }
 623        } else if self.focus_handle.is_focused(cx) {
 624            let focus_handle = self.editor.focus_handle(cx);
 625            cx.focus(&focus_handle);
 626        }
 627
 628        #[cfg(test)]
 629        self.check_invariants(cx);
 630
 631        cx.notify();
 632    }
 633
 634    #[cfg(test)]
 635    fn check_invariants(&self, cx: &mut ViewContext<Self>) {
 636        let mut excerpts = Vec::new();
 637        for (id, buffer, _) in self.excerpts.read(cx).snapshot(cx).excerpts() {
 638            if let Some(file) = buffer.file() {
 639                excerpts.push((id, file.path().clone()));
 640            }
 641        }
 642
 643        let mut prev_path = None;
 644        for (_, path) in &excerpts {
 645            if let Some(prev_path) = prev_path {
 646                if path < prev_path {
 647                    panic!("excerpts are not sorted by path {:?}", excerpts);
 648                }
 649            }
 650            prev_path = Some(path);
 651        }
 652    }
 653}
 654
 655impl FocusableView for ProjectDiagnosticsEditor {
 656    fn focus_handle(&self, _: &AppContext) -> FocusHandle {
 657        self.focus_handle.clone()
 658    }
 659}
 660
 661impl Item for ProjectDiagnosticsEditor {
 662    type Event = EditorEvent;
 663
 664    fn to_item_events(event: &EditorEvent, f: impl FnMut(ItemEvent)) {
 665        Editor::to_item_events(event, f)
 666    }
 667
 668    fn deactivated(&mut self, cx: &mut ViewContext<Self>) {
 669        self.editor.update(cx, |editor, cx| editor.deactivated(cx));
 670    }
 671
 672    fn navigate(&mut self, data: Box<dyn Any>, cx: &mut ViewContext<Self>) -> bool {
 673        self.editor
 674            .update(cx, |editor, cx| editor.navigate(data, cx))
 675    }
 676
 677    fn tab_tooltip_text(&self, _: &AppContext) -> Option<SharedString> {
 678        Some("Project Diagnostics".into())
 679    }
 680
 681    fn tab_content(&self, params: TabContentParams, _: &WindowContext) -> AnyElement {
 682        h_flex()
 683            .gap_1()
 684            .when(
 685                self.summary.error_count == 0 && self.summary.warning_count == 0,
 686                |then| {
 687                    then.child(
 688                        h_flex()
 689                            .gap_1()
 690                            .child(Icon::new(IconName::Check).color(Color::Success))
 691                            .child(Label::new("No problems").color(params.text_color())),
 692                    )
 693                },
 694            )
 695            .when(self.summary.error_count > 0, |then| {
 696                then.child(
 697                    h_flex()
 698                        .gap_1()
 699                        .child(Icon::new(IconName::XCircle).color(Color::Error))
 700                        .child(
 701                            Label::new(self.summary.error_count.to_string())
 702                                .color(params.text_color()),
 703                        ),
 704                )
 705            })
 706            .when(self.summary.warning_count > 0, |then| {
 707                then.child(
 708                    h_flex()
 709                        .gap_1()
 710                        .child(Icon::new(IconName::Warning).color(Color::Warning))
 711                        .child(
 712                            Label::new(self.summary.warning_count.to_string())
 713                                .color(params.text_color()),
 714                        ),
 715                )
 716            })
 717            .into_any_element()
 718    }
 719
 720    fn telemetry_event_text(&self) -> Option<&'static str> {
 721        Some("project diagnostics")
 722    }
 723
 724    fn for_each_project_item(
 725        &self,
 726        cx: &AppContext,
 727        f: &mut dyn FnMut(gpui::EntityId, &dyn project::ProjectItem),
 728    ) {
 729        self.editor.for_each_project_item(cx, f)
 730    }
 731
 732    fn is_singleton(&self, _: &AppContext) -> bool {
 733        false
 734    }
 735
 736    fn set_nav_history(&mut self, nav_history: ItemNavHistory, cx: &mut ViewContext<Self>) {
 737        self.editor.update(cx, |editor, _| {
 738            editor.set_nav_history(Some(nav_history));
 739        });
 740    }
 741
 742    fn clone_on_split(
 743        &self,
 744        _workspace_id: Option<workspace::WorkspaceId>,
 745        cx: &mut ViewContext<Self>,
 746    ) -> Option<View<Self>>
 747    where
 748        Self: Sized,
 749    {
 750        Some(cx.new_view(|cx| {
 751            ProjectDiagnosticsEditor::new(
 752                self.project.clone(),
 753                self.include_warnings,
 754                self.workspace.clone(),
 755                cx,
 756            )
 757        }))
 758    }
 759
 760    fn is_dirty(&self, cx: &AppContext) -> bool {
 761        self.excerpts.read(cx).is_dirty(cx)
 762    }
 763
 764    fn has_deleted_file(&self, cx: &AppContext) -> bool {
 765        self.excerpts.read(cx).has_deleted_file(cx)
 766    }
 767
 768    fn has_conflict(&self, cx: &AppContext) -> bool {
 769        self.excerpts.read(cx).has_conflict(cx)
 770    }
 771
 772    fn can_save(&self, _: &AppContext) -> bool {
 773        true
 774    }
 775
 776    fn save(
 777        &mut self,
 778        format: bool,
 779        project: Model<Project>,
 780        cx: &mut ViewContext<Self>,
 781    ) -> Task<Result<()>> {
 782        self.editor.save(format, project, cx)
 783    }
 784
 785    fn save_as(
 786        &mut self,
 787        _: Model<Project>,
 788        _: ProjectPath,
 789        _: &mut ViewContext<Self>,
 790    ) -> Task<Result<()>> {
 791        unreachable!()
 792    }
 793
 794    fn reload(&mut self, project: Model<Project>, cx: &mut ViewContext<Self>) -> Task<Result<()>> {
 795        self.editor.reload(project, cx)
 796    }
 797
 798    fn act_as_type<'a>(
 799        &'a self,
 800        type_id: TypeId,
 801        self_handle: &'a View<Self>,
 802        _: &'a AppContext,
 803    ) -> Option<AnyView> {
 804        if type_id == TypeId::of::<Self>() {
 805            Some(self_handle.to_any())
 806        } else if type_id == TypeId::of::<Editor>() {
 807            Some(self.editor.to_any())
 808        } else {
 809            None
 810        }
 811    }
 812
 813    fn as_searchable(&self, _: &View<Self>) -> Option<Box<dyn SearchableItemHandle>> {
 814        Some(Box::new(self.editor.clone()))
 815    }
 816
 817    fn breadcrumb_location(&self, _: &AppContext) -> ToolbarItemLocation {
 818        ToolbarItemLocation::PrimaryLeft
 819    }
 820
 821    fn breadcrumbs(&self, theme: &theme::Theme, cx: &AppContext) -> Option<Vec<BreadcrumbText>> {
 822        self.editor.breadcrumbs(theme, cx)
 823    }
 824
 825    fn added_to_workspace(&mut self, workspace: &mut Workspace, cx: &mut ViewContext<Self>) {
 826        self.editor
 827            .update(cx, |editor, cx| editor.added_to_workspace(workspace, cx));
 828    }
 829}
 830
 831const DIAGNOSTIC_HEADER: &str = "diagnostic header";
 832
 833fn diagnostic_header_renderer(diagnostic: Diagnostic) -> RenderBlock {
 834    let (message, code_ranges) = highlight_diagnostic_message(&diagnostic, None);
 835    let message: SharedString = message;
 836    Arc::new(move |cx| {
 837        let color = cx.theme().colors();
 838        let highlight_style: HighlightStyle = color.text_accent.into();
 839
 840        h_flex()
 841            .id(DIAGNOSTIC_HEADER)
 842            .block_mouse_down()
 843            .h(2. * cx.line_height())
 844            .w_full()
 845            .px_9()
 846            .justify_between()
 847            .gap_2()
 848            .child(
 849                h_flex()
 850                    .gap_2()
 851                    .px_1()
 852                    .rounded_md()
 853                    .bg(color.surface_background.opacity(0.5))
 854                    .map(|stack| {
 855                        stack.child(
 856                            svg()
 857                                .size(cx.text_style().font_size)
 858                                .flex_none()
 859                                .map(|icon| {
 860                                    if diagnostic.severity == DiagnosticSeverity::ERROR {
 861                                        icon.path(IconName::XCircle.path())
 862                                            .text_color(Color::Error.color(cx))
 863                                    } else {
 864                                        icon.path(IconName::Warning.path())
 865                                            .text_color(Color::Warning.color(cx))
 866                                    }
 867                                }),
 868                        )
 869                    })
 870                    .child(
 871                        h_flex()
 872                            .gap_1()
 873                            .child(
 874                                StyledText::new(message.clone()).with_highlights(
 875                                    &cx.text_style(),
 876                                    code_ranges
 877                                        .iter()
 878                                        .map(|range| (range.clone(), highlight_style)),
 879                                ),
 880                            )
 881                            .when_some(diagnostic.code.as_ref(), |stack, code| {
 882                                stack.child(
 883                                    div()
 884                                        .child(SharedString::from(format!("({code})")))
 885                                        .text_color(color.text_muted),
 886                                )
 887                            }),
 888                    ),
 889            )
 890            .when_some(diagnostic.source.as_ref(), |stack, source| {
 891                stack.child(
 892                    div()
 893                        .child(SharedString::from(source.clone()))
 894                        .text_color(color.text_muted),
 895                )
 896            })
 897            .into_any_element()
 898    })
 899}
 900
 901fn compare_diagnostics(
 902    old: &DiagnosticEntry<language::Anchor>,
 903    new: &DiagnosticEntry<language::Anchor>,
 904    snapshot: &language::BufferSnapshot,
 905) -> Ordering {
 906    use language::ToOffset;
 907
 908    // The diagnostics may point to a previously open Buffer for this file.
 909    if !old.range.start.is_valid(snapshot) || !new.range.start.is_valid(snapshot) {
 910        return Ordering::Greater;
 911    }
 912
 913    old.range
 914        .start
 915        .to_offset(snapshot)
 916        .cmp(&new.range.start.to_offset(snapshot))
 917        .then_with(|| {
 918            old.range
 919                .end
 920                .to_offset(snapshot)
 921                .cmp(&new.range.end.to_offset(snapshot))
 922        })
 923        .then_with(|| old.diagnostic.message.cmp(&new.diagnostic.message))
 924}
 925
 926const DIAGNOSTIC_EXPANSION_ROW_LIMIT: u32 = 32;
 927
 928fn context_range_for_entry(
 929    entry: &DiagnosticEntry<Point>,
 930    context: u32,
 931    snapshot: &BufferSnapshot,
 932    cx: &AppContext,
 933) -> Range<Point> {
 934    if let Some(rows) = heuristic_syntactic_expand(
 935        entry.range.clone(),
 936        DIAGNOSTIC_EXPANSION_ROW_LIMIT,
 937        snapshot,
 938        cx,
 939    ) {
 940        return Range {
 941            start: Point::new(*rows.start(), 0),
 942            end: snapshot.clip_point(Point::new(*rows.end(), u32::MAX), Bias::Left),
 943        };
 944    }
 945    Range {
 946        start: Point::new(entry.range.start.row.saturating_sub(context), 0),
 947        end: snapshot.clip_point(
 948            Point::new(entry.range.end.row + context, u32::MAX),
 949            Bias::Left,
 950        ),
 951    }
 952}
 953
 954/// Expands the input range using syntax information from TreeSitter. This expansion will be limited
 955/// to the specified `max_row_count`.
 956///
 957/// If there is a containing outline item that is less than `max_row_count`, it will be returned.
 958/// Otherwise fairly arbitrary heuristics are applied to attempt to return a logical block of code.
 959fn heuristic_syntactic_expand<'a>(
 960    input_range: Range<Point>,
 961    max_row_count: u32,
 962    snapshot: &'a BufferSnapshot,
 963    cx: &'a AppContext,
 964) -> Option<RangeInclusive<BufferRow>> {
 965    let input_row_count = input_range.end.row - input_range.start.row;
 966    if input_row_count > max_row_count {
 967        return None;
 968    }
 969
 970    // If the outline node contains the diagnostic and is small enough, just use that.
 971    let outline_range = snapshot.outline_range_containing(input_range.clone());
 972    if let Some(outline_range) = outline_range.clone() {
 973        // Remove blank lines from start and end
 974        if let Some(start_row) = (outline_range.start.row..outline_range.end.row)
 975            .find(|row| !snapshot.line_indent_for_row(*row).is_line_blank())
 976        {
 977            if let Some(end_row) = (outline_range.start.row..outline_range.end.row + 1)
 978                .rev()
 979                .find(|row| !snapshot.line_indent_for_row(*row).is_line_blank())
 980            {
 981                let row_count = end_row.saturating_sub(start_row);
 982                if row_count <= max_row_count {
 983                    return Some(RangeInclusive::new(
 984                        outline_range.start.row,
 985                        outline_range.end.row,
 986                    ));
 987                }
 988            }
 989        }
 990    }
 991
 992    let mut node = snapshot.syntax_ancestor(input_range.clone())?;
 993    loop {
 994        let node_start = Point::from_ts_point(node.start_position());
 995        let node_end = Point::from_ts_point(node.end_position());
 996        let node_range = node_start..node_end;
 997        let row_count = node_end.row - node_start.row + 1;
 998
 999        // Stop if we've exceeded the row count or reached an outline node. Then, find the interval
1000        // of node children which contains the query range. For example, this allows just returning
1001        // the header of a declaration rather than the entire declaration.
1002        if row_count > max_row_count || outline_range == Some(node_range.clone()) {
1003            let mut cursor = node.walk();
1004            let mut included_child_start = None;
1005            let mut included_child_end = None;
1006            let mut previous_end = node_start;
1007            if cursor.goto_first_child() {
1008                loop {
1009                    let child_node = cursor.node();
1010                    let child_range = previous_end..Point::from_ts_point(child_node.end_position());
1011                    if included_child_start.is_none() && child_range.contains(&input_range.start) {
1012                        included_child_start = Some(child_range.start);
1013                    }
1014                    if child_range.contains(&input_range.end) {
1015                        included_child_end = Some(child_range.end);
1016                    }
1017                    previous_end = child_range.end;
1018                    if !cursor.goto_next_sibling() {
1019                        break;
1020                    }
1021                }
1022            }
1023            let end = included_child_end.unwrap_or(node_range.end);
1024            if let Some(start) = included_child_start {
1025                let row_count = end.row - start.row;
1026                if row_count < max_row_count {
1027                    return Some(RangeInclusive::new(start.row, end.row));
1028                }
1029            }
1030
1031            log::info!(
1032                "Expanding to ancestor started on {} node exceeding row limit of {max_row_count}.",
1033                node.grammar_name()
1034            );
1035            return None;
1036        }
1037
1038        let node_name = node.grammar_name();
1039        let node_row_range = RangeInclusive::new(node_range.start.row, node_range.end.row);
1040        if node_name.ends_with("block") {
1041            return Some(node_row_range);
1042        } else if node_name.ends_with("statement") || node_name.ends_with("declaration") {
1043            // Expand to the nearest dedent or blank line for statements and declarations.
1044            let tab_size = snapshot.settings_at(node_range.start, cx).tab_size.get();
1045            let indent_level = snapshot
1046                .line_indent_for_row(node_range.start.row)
1047                .len(tab_size);
1048            let rows_remaining = max_row_count.saturating_sub(row_count);
1049            let Some(start_row) = (node_range.start.row.saturating_sub(rows_remaining)
1050                ..node_range.start.row)
1051                .rev()
1052                .find(|row| is_line_blank_or_indented_less(indent_level, *row, tab_size, snapshot))
1053            else {
1054                return Some(node_row_range);
1055            };
1056            let rows_remaining = max_row_count.saturating_sub(node_range.end.row - start_row);
1057            let Some(end_row) = (node_range.end.row + 1
1058                ..cmp::min(
1059                    node_range.end.row + rows_remaining + 1,
1060                    snapshot.row_count(),
1061                ))
1062                .find(|row| is_line_blank_or_indented_less(indent_level, *row, tab_size, snapshot))
1063            else {
1064                return Some(node_row_range);
1065            };
1066            return Some(RangeInclusive::new(start_row, end_row));
1067        }
1068
1069        // TODO: doing this instead of walking a cursor as that doesn't work - why?
1070        let Some(parent) = node.parent() else {
1071            log::info!(
1072                "Expanding to ancestor reached the top node, so using default context line count.",
1073            );
1074            return None;
1075        };
1076        node = parent;
1077    }
1078}
1079
1080fn is_line_blank_or_indented_less(
1081    indent_level: u32,
1082    row: u32,
1083    tab_size: u32,
1084    snapshot: &BufferSnapshot,
1085) -> bool {
1086    let line_indent = snapshot.line_indent_for_row(row);
1087    line_indent.is_line_blank() || line_indent.len(tab_size) < indent_level
1088}