diagnostics.rs

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