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    Editor, EditorEvent, ExcerptId, ExcerptRange, MultiBuffer, ToOffset, diagnostic_block_renderer,
  11    display_map::{BlockPlacement, BlockProperties, BlockStyle, CustomBlockId, RenderBlock},
  12    highlight_diagnostic_message,
  13    scroll::Autoscroll,
  14};
  15use gpui::{
  16    AnyElement, AnyView, App, AsyncApp, Context, Entity, EventEmitter, FocusHandle, Focusable,
  17    Global, HighlightStyle, InteractiveElement, IntoElement, ParentElement, Render, SharedString,
  18    Styled, StyledText, Subscription, Task, WeakEntity, Window, actions, div, svg,
  19};
  20use language::{
  21    Bias, Buffer, BufferRow, BufferSnapshot, Diagnostic, DiagnosticEntry, DiagnosticSeverity,
  22    Point, Selection, SelectionGoal, ToTreeSitterPoint,
  23};
  24use lsp::LanguageServerId;
  25use project::{DiagnosticSummary, Project, ProjectPath, project_settings::ProjectSettings};
  26use settings::Settings;
  27use std::{
  28    any::{Any, TypeId},
  29    cmp,
  30    cmp::Ordering,
  31    mem,
  32    ops::{Range, RangeInclusive},
  33    sync::Arc,
  34    time::Duration,
  35};
  36use theme::ActiveTheme;
  37pub use toolbar_controls::ToolbarControls;
  38use ui::{Icon, IconName, Label, h_flex, prelude::*};
  39use util::ResultExt;
  40use workspace::{
  41    ItemNavHistory, ToolbarItemLocation, Workspace,
  42    item::{BreadcrumbText, Item, ItemEvent, ItemHandle, TabContentParams},
  43    searchable::SearchableItemHandle,
  44};
  45
  46actions!(diagnostics, [Deploy, ToggleWarnings]);
  47
  48struct IncludeWarnings(bool);
  49impl Global for IncludeWarnings {}
  50
  51pub fn init(cx: &mut App) {
  52    cx.observe_new(ProjectDiagnosticsEditor::register).detach();
  53}
  54
  55struct ProjectDiagnosticsEditor {
  56    project: Entity<Project>,
  57    workspace: WeakEntity<Workspace>,
  58    focus_handle: FocusHandle,
  59    editor: Entity<Editor>,
  60    summary: DiagnosticSummary,
  61    excerpts: Entity<MultiBuffer>,
  62    path_states: Vec<PathState>,
  63    paths_to_update: BTreeSet<(ProjectPath, Option<LanguageServerId>)>,
  64    include_warnings: bool,
  65    context: u32,
  66    update_excerpts_task: Option<Task<Result<()>>>,
  67    _subscription: Subscription,
  68}
  69
  70struct PathState {
  71    path: ProjectPath,
  72    diagnostic_groups: Vec<DiagnosticGroupState>,
  73}
  74
  75struct DiagnosticGroupState {
  76    language_server_id: LanguageServerId,
  77    primary_diagnostic: DiagnosticEntry<language::Anchor>,
  78    primary_excerpt_ix: usize,
  79    excerpts: Vec<ExcerptId>,
  80    blocks: HashSet<CustomBlockId>,
  81    block_count: usize,
  82}
  83
  84impl EventEmitter<EditorEvent> for ProjectDiagnosticsEditor {}
  85
  86const DIAGNOSTICS_UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
  87
  88impl Render for ProjectDiagnosticsEditor {
  89    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
  90        let warning_count = if self.include_warnings {
  91            self.summary.warning_count
  92        } else {
  93            0
  94        };
  95
  96        let child = if warning_count + self.summary.error_count == 0 {
  97            let label = if self.summary.warning_count == 0 {
  98                SharedString::new_static("No problems in workspace")
  99            } else {
 100                SharedString::new_static("No errors in workspace")
 101            };
 102            v_flex()
 103                .key_context("EmptyPane")
 104                .size_full()
 105                .gap_1()
 106                .justify_center()
 107                .items_center()
 108                .text_center()
 109                .bg(cx.theme().colors().editor_background)
 110                .child(Label::new(label).color(Color::Muted))
 111                .when(self.summary.warning_count > 0, |this| {
 112                    let plural_suffix = if self.summary.warning_count > 1 {
 113                        "s"
 114                    } else {
 115                        ""
 116                    };
 117                    let label = format!(
 118                        "Show {} warning{}",
 119                        self.summary.warning_count, plural_suffix
 120                    );
 121                    this.child(
 122                        Button::new("diagnostics-show-warning-label", label).on_click(cx.listener(
 123                            |this, _, window, cx| {
 124                                this.toggle_warnings(&Default::default(), window, cx);
 125                                cx.notify();
 126                            },
 127                        )),
 128                    )
 129                })
 130        } else {
 131            div().size_full().child(self.editor.clone())
 132        };
 133
 134        div()
 135            .key_context("Diagnostics")
 136            .track_focus(&self.focus_handle(cx))
 137            .size_full()
 138            .on_action(cx.listener(Self::toggle_warnings))
 139            .child(child)
 140    }
 141}
 142
 143impl ProjectDiagnosticsEditor {
 144    fn register(
 145        workspace: &mut Workspace,
 146        _window: Option<&mut Window>,
 147        _: &mut Context<Workspace>,
 148    ) {
 149        workspace.register_action(Self::deploy);
 150    }
 151
 152    fn new_with_context(
 153        context: u32,
 154        include_warnings: bool,
 155        project_handle: Entity<Project>,
 156        workspace: WeakEntity<Workspace>,
 157        window: &mut Window,
 158        cx: &mut Context<Self>,
 159    ) -> Self {
 160        let project_event_subscription =
 161            cx.subscribe_in(&project_handle, window, |this, project, event, window, cx| match event {
 162                project::Event::DiskBasedDiagnosticsStarted { .. } => {
 163                    cx.notify();
 164                }
 165                project::Event::DiskBasedDiagnosticsFinished { language_server_id } => {
 166                    log::debug!("disk based diagnostics finished for server {language_server_id}");
 167                    this.update_stale_excerpts(window, cx);
 168                }
 169                project::Event::DiagnosticsUpdated {
 170                    language_server_id,
 171                    path,
 172                } => {
 173                    this.paths_to_update
 174                        .insert((path.clone(), Some(*language_server_id)));
 175                    this.summary = project.read(cx).diagnostic_summary(false, cx);
 176                    cx.emit(EditorEvent::TitleChanged);
 177
 178                    if this.editor.focus_handle(cx).contains_focused(window, cx) || this.focus_handle.contains_focused(window, cx) {
 179                        log::debug!("diagnostics updated for server {language_server_id}, path {path:?}. recording change");
 180                    } else {
 181                        log::debug!("diagnostics updated for server {language_server_id}, path {path:?}. updating excerpts");
 182                        this.update_stale_excerpts(window, cx);
 183                    }
 184                }
 185                _ => {}
 186            });
 187
 188        let focus_handle = cx.focus_handle();
 189        cx.on_focus_in(&focus_handle, window, |this, window, cx| {
 190            this.focus_in(window, cx)
 191        })
 192        .detach();
 193        cx.on_focus_out(&focus_handle, window, |this, _event, window, cx| {
 194            this.focus_out(window, cx)
 195        })
 196        .detach();
 197
 198        let excerpts = cx.new(|cx| MultiBuffer::new(project_handle.read(cx).capability()));
 199        let editor = cx.new(|cx| {
 200            let mut editor =
 201                Editor::for_multibuffer(excerpts.clone(), Some(project_handle.clone()), window, cx);
 202            editor.set_vertical_scroll_margin(5, cx);
 203            editor.disable_inline_diagnostics();
 204            editor
 205        });
 206        cx.subscribe_in(
 207            &editor,
 208            window,
 209            |this, _editor, event: &EditorEvent, window, cx| {
 210                cx.emit(event.clone());
 211                match event {
 212                    EditorEvent::Focused => {
 213                        if this.path_states.is_empty() {
 214                            window.focus(&this.focus_handle);
 215                        }
 216                    }
 217                    EditorEvent::Blurred => this.update_stale_excerpts(window, cx),
 218                    _ => {}
 219                }
 220            },
 221        )
 222        .detach();
 223        cx.observe_global_in::<IncludeWarnings>(window, |this, window, cx| {
 224            this.include_warnings = cx.global::<IncludeWarnings>().0;
 225            this.update_all_excerpts(window, cx);
 226        })
 227        .detach();
 228
 229        let project = project_handle.read(cx);
 230        let mut this = Self {
 231            project: project_handle.clone(),
 232            context,
 233            summary: project.diagnostic_summary(false, cx),
 234            include_warnings,
 235            workspace,
 236            excerpts,
 237            focus_handle,
 238            editor,
 239            path_states: Default::default(),
 240            paths_to_update: Default::default(),
 241            update_excerpts_task: None,
 242            _subscription: project_event_subscription,
 243        };
 244        this.update_all_excerpts(window, cx);
 245        this
 246    }
 247
 248    fn update_stale_excerpts(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 249        if self.update_excerpts_task.is_some() {
 250            return;
 251        }
 252        let project_handle = self.project.clone();
 253        self.update_excerpts_task = Some(cx.spawn_in(window, async move |this, cx| {
 254            cx.background_executor()
 255                .timer(DIAGNOSTICS_UPDATE_DEBOUNCE)
 256                .await;
 257            loop {
 258                let Some((path, language_server_id)) = this.update(cx, |this, _| {
 259                    let Some((path, language_server_id)) = this.paths_to_update.pop_first() else {
 260                        this.update_excerpts_task.take();
 261                        return None;
 262                    };
 263                    Some((path, language_server_id))
 264                })?
 265                else {
 266                    break;
 267                };
 268
 269                if let Some(buffer) = project_handle
 270                    .update(cx, |project, cx| project.open_buffer(path.clone(), cx))?
 271                    .await
 272                    .log_err()
 273                {
 274                    this.update_in(cx, |this, window, cx| {
 275                        this.update_excerpts(path, language_server_id, buffer, window, cx)
 276                    })?
 277                    .await?;
 278                }
 279            }
 280            Ok(())
 281        }));
 282    }
 283
 284    fn new(
 285        project_handle: Entity<Project>,
 286        include_warnings: bool,
 287        workspace: WeakEntity<Workspace>,
 288        window: &mut Window,
 289        cx: &mut Context<Self>,
 290    ) -> Self {
 291        Self::new_with_context(
 292            editor::DEFAULT_MULTIBUFFER_CONTEXT,
 293            include_warnings,
 294            project_handle,
 295            workspace,
 296            window,
 297            cx,
 298        )
 299    }
 300
 301    fn deploy(
 302        workspace: &mut Workspace,
 303        _: &Deploy,
 304        window: &mut Window,
 305        cx: &mut Context<Workspace>,
 306    ) {
 307        if let Some(existing) = workspace.item_of_type::<ProjectDiagnosticsEditor>(cx) {
 308            let is_active = workspace
 309                .active_item(cx)
 310                .is_some_and(|item| item.item_id() == existing.item_id());
 311            workspace.activate_item(&existing, true, !is_active, window, cx);
 312        } else {
 313            let workspace_handle = cx.entity().downgrade();
 314
 315            let include_warnings = match cx.try_global::<IncludeWarnings>() {
 316                Some(include_warnings) => include_warnings.0,
 317                None => ProjectSettings::get_global(cx).diagnostics.include_warnings,
 318            };
 319
 320            let diagnostics = cx.new(|cx| {
 321                ProjectDiagnosticsEditor::new(
 322                    workspace.project().clone(),
 323                    include_warnings,
 324                    workspace_handle,
 325                    window,
 326                    cx,
 327                )
 328            });
 329            workspace.add_item_to_active_pane(Box::new(diagnostics), None, true, window, cx);
 330        }
 331    }
 332
 333    fn toggle_warnings(&mut self, _: &ToggleWarnings, window: &mut Window, cx: &mut Context<Self>) {
 334        self.include_warnings = !self.include_warnings;
 335        cx.set_global(IncludeWarnings(self.include_warnings));
 336        self.update_all_excerpts(window, cx);
 337        cx.notify();
 338    }
 339
 340    fn focus_in(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 341        if self.focus_handle.is_focused(window) && !self.path_states.is_empty() {
 342            self.editor.focus_handle(cx).focus(window)
 343        }
 344    }
 345
 346    fn focus_out(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 347        if !self.focus_handle.is_focused(window) && !self.editor.focus_handle(cx).is_focused(window)
 348        {
 349            self.update_stale_excerpts(window, cx);
 350        }
 351    }
 352
 353    /// Enqueue an update of all excerpts. Updates all paths that either
 354    /// currently have diagnostics or are currently present in this view.
 355    fn update_all_excerpts(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 356        self.project.update(cx, |project, cx| {
 357            let mut paths = project
 358                .diagnostic_summaries(false, cx)
 359                .map(|(path, _, _)| (path, None))
 360                .collect::<BTreeSet<_>>();
 361            paths.extend(
 362                self.path_states
 363                    .iter()
 364                    .map(|state| (state.path.clone(), None)),
 365            );
 366            let paths_to_update = std::mem::take(&mut self.paths_to_update);
 367            paths.extend(paths_to_update.into_iter().map(|(path, _)| (path, None)));
 368            self.paths_to_update = paths;
 369        });
 370        self.update_stale_excerpts(window, cx);
 371    }
 372
 373    fn update_excerpts(
 374        &mut self,
 375        path_to_update: ProjectPath,
 376        server_to_update: Option<LanguageServerId>,
 377        buffer: Entity<Buffer>,
 378        window: &mut Window,
 379        cx: &mut Context<Self>,
 380    ) -> Task<Result<()>> {
 381        let was_empty = self.path_states.is_empty();
 382        let snapshot = buffer.read(cx).snapshot();
 383        let path_ix = match self
 384            .path_states
 385            .binary_search_by_key(&&path_to_update, |e| &e.path)
 386        {
 387            Ok(ix) => ix,
 388            Err(ix) => {
 389                self.path_states.insert(
 390                    ix,
 391                    PathState {
 392                        path: path_to_update.clone(),
 393                        diagnostic_groups: Default::default(),
 394                    },
 395                );
 396                ix
 397            }
 398        };
 399        let mut prev_excerpt_id = if path_ix > 0 {
 400            let prev_path_last_group = &self.path_states[path_ix - 1]
 401                .diagnostic_groups
 402                .last()
 403                .unwrap();
 404            *prev_path_last_group.excerpts.last().unwrap()
 405        } else {
 406            ExcerptId::min()
 407        };
 408
 409        let mut new_group_ixs = Vec::new();
 410        let mut blocks_to_add = Vec::new();
 411        let mut blocks_to_remove = HashSet::default();
 412        let mut first_excerpt_id = None;
 413        let max_severity = if self.include_warnings {
 414            DiagnosticSeverity::WARNING
 415        } else {
 416            DiagnosticSeverity::ERROR
 417        };
 418        let excerpts = self.excerpts.clone().downgrade();
 419        let context = self.context;
 420        let editor = self.editor.clone().downgrade();
 421        cx.spawn_in(window, async move |this, cx| {
 422            let mut old_groups = this
 423                .update(cx, |this, _| {
 424                    mem::take(&mut this.path_states[path_ix].diagnostic_groups)
 425                })?
 426                .into_iter()
 427                .enumerate()
 428                .peekable();
 429            let mut new_groups = snapshot
 430                .diagnostic_groups(server_to_update)
 431                .into_iter()
 432                .filter(|(_, group)| {
 433                    group.entries[group.primary_ix].diagnostic.severity <= max_severity
 434                })
 435                .peekable();
 436            loop {
 437                let mut to_insert = None;
 438                let mut to_remove = None;
 439                let mut to_keep = None;
 440                match (old_groups.peek(), new_groups.peek()) {
 441                    (None, None) => break,
 442                    (None, Some(_)) => to_insert = new_groups.next(),
 443                    (Some((_, old_group)), None) => {
 444                        if server_to_update.map_or(true, |id| id == old_group.language_server_id) {
 445                            to_remove = old_groups.next();
 446                        } else {
 447                            to_keep = old_groups.next();
 448                        }
 449                    }
 450                    (Some((_, old_group)), Some((new_language_server_id, new_group))) => {
 451                        let old_primary = &old_group.primary_diagnostic;
 452                        let new_primary = &new_group.entries[new_group.primary_ix];
 453                        match compare_diagnostics(old_primary, new_primary, &snapshot)
 454                            .then_with(|| old_group.language_server_id.cmp(new_language_server_id))
 455                        {
 456                            Ordering::Less => {
 457                                if server_to_update
 458                                    .map_or(true, |id| id == old_group.language_server_id)
 459                                {
 460                                    to_remove = old_groups.next();
 461                                } else {
 462                                    to_keep = old_groups.next();
 463                                }
 464                            }
 465                            Ordering::Equal => {
 466                                to_keep = old_groups.next();
 467                                new_groups.next();
 468                            }
 469                            Ordering::Greater => to_insert = new_groups.next(),
 470                        }
 471                    }
 472                }
 473
 474                if let Some((language_server_id, group)) = to_insert {
 475                    let mut group_state = DiagnosticGroupState {
 476                        language_server_id,
 477                        primary_diagnostic: group.entries[group.primary_ix].clone(),
 478                        primary_excerpt_ix: 0,
 479                        excerpts: Default::default(),
 480                        blocks: Default::default(),
 481                        block_count: 0,
 482                    };
 483                    let mut pending_range: Option<(Range<Point>, Range<Point>, usize)> = None;
 484                    let mut is_first_excerpt_for_group = true;
 485                    for (ix, entry) in group.entries.iter().map(Some).chain([None]).enumerate() {
 486                        let resolved_entry = entry.map(|e| e.resolve::<Point>(&snapshot));
 487                        let expanded_range = if let Some(entry) = &resolved_entry {
 488                            Some(
 489                                context_range_for_entry(
 490                                    entry.range.clone(),
 491                                    context,
 492                                    snapshot.clone(),
 493                                    (**cx).clone(),
 494                                )
 495                                .await,
 496                            )
 497                        } else {
 498                            None
 499                        };
 500                        if let Some((range, context_range, start_ix)) = &mut pending_range {
 501                            if let Some(expanded_range) = expanded_range.clone() {
 502                                // If the entries are overlapping or next to each-other, merge them into one excerpt.
 503                                if context_range.end.row + 1 >= expanded_range.start.row {
 504                                    context_range.end = context_range.end.max(expanded_range.end);
 505                                    continue;
 506                                }
 507                            }
 508
 509                            let excerpt_id = excerpts.update(cx, |excerpts, cx| {
 510                                excerpts
 511                                    .insert_excerpts_after(
 512                                        prev_excerpt_id,
 513                                        buffer.clone(),
 514                                        [ExcerptRange {
 515                                            context: context_range.clone(),
 516                                            primary: range.clone(),
 517                                        }],
 518                                        cx,
 519                                    )
 520                                    .pop()
 521                                    .unwrap()
 522                            })?;
 523
 524                            prev_excerpt_id = excerpt_id;
 525                            first_excerpt_id.get_or_insert(prev_excerpt_id);
 526                            group_state.excerpts.push(excerpt_id);
 527                            let header_position = (excerpt_id, language::Anchor::MIN);
 528
 529                            if is_first_excerpt_for_group {
 530                                is_first_excerpt_for_group = false;
 531                                let mut primary =
 532                                    group.entries[group.primary_ix].diagnostic.clone();
 533                                primary.message =
 534                                    primary.message.split('\n').next().unwrap().to_string();
 535                                group_state.block_count += 1;
 536                                blocks_to_add.push(BlockProperties {
 537                                    placement: BlockPlacement::Above(header_position),
 538                                    height: Some(2),
 539                                    style: BlockStyle::Sticky,
 540                                    render: diagnostic_header_renderer(primary),
 541                                    priority: 0,
 542                                });
 543                            }
 544
 545                            for entry in &group.entries[*start_ix..ix] {
 546                                let mut diagnostic = entry.diagnostic.clone();
 547                                if diagnostic.is_primary {
 548                                    group_state.primary_excerpt_ix = group_state.excerpts.len() - 1;
 549                                    diagnostic.message =
 550                                        entry.diagnostic.message.split('\n').skip(1).collect();
 551                                }
 552
 553                                if !diagnostic.message.is_empty() {
 554                                    group_state.block_count += 1;
 555                                    blocks_to_add.push(BlockProperties {
 556                                        placement: BlockPlacement::Below((
 557                                            excerpt_id,
 558                                            entry.range.start,
 559                                        )),
 560                                        height: Some(
 561                                            diagnostic.message.matches('\n').count() as u32 + 1,
 562                                        ),
 563                                        style: BlockStyle::Fixed,
 564                                        render: diagnostic_block_renderer(diagnostic, None, true),
 565                                        priority: 0,
 566                                    });
 567                                }
 568                            }
 569
 570                            pending_range.take();
 571                        }
 572
 573                        if let Some(entry) = resolved_entry.as_ref() {
 574                            let range = entry.range.clone();
 575                            pending_range = Some((range, expanded_range.unwrap(), ix));
 576                        }
 577                    }
 578
 579                    this.update(cx, |this, _| {
 580                        new_group_ixs.push(this.path_states[path_ix].diagnostic_groups.len());
 581                        this.path_states[path_ix]
 582                            .diagnostic_groups
 583                            .push(group_state);
 584                    })?;
 585                } else if let Some((_, group_state)) = to_remove {
 586                    excerpts.update(cx, |excerpts, cx| {
 587                        excerpts.remove_excerpts(group_state.excerpts.iter().copied(), cx)
 588                    })?;
 589                    blocks_to_remove.extend(group_state.blocks.iter().copied());
 590                } else if let Some((_, group_state)) = to_keep {
 591                    prev_excerpt_id = *group_state.excerpts.last().unwrap();
 592                    first_excerpt_id.get_or_insert(prev_excerpt_id);
 593
 594                    this.update(cx, |this, _| {
 595                        this.path_states[path_ix]
 596                            .diagnostic_groups
 597                            .push(group_state)
 598                    })?;
 599                }
 600            }
 601
 602            let excerpts_snapshot = excerpts.update(cx, |excerpts, cx| excerpts.snapshot(cx))?;
 603            editor.update(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(_) | BlockPlacement::Near(_) => {
 619                                unreachable!(
 620                                    "no Near/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(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(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(async move |cx| {
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: &mut 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}