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