diagnostics.rs

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