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 buffer_snapshot = buffer.read(cx).snapshot();
 628                let excerpt_ranges: Vec<_> = excerpt_ranges
 629                    .into_iter()
 630                    .map(|range| ExcerptRange {
 631                        context: range.context.to_point(&buffer_snapshot),
 632                        primary: range.primary.to_point(&buffer_snapshot),
 633                    })
 634                    .collect();
 635                // TODO(cole): maybe should use the nonshrinking API?
 636                this.multibuffer.update(cx, |multi_buffer, cx| {
 637                    multi_buffer.set_excerpt_ranges_for_path(
 638                        PathKey::for_buffer(&buffer, cx),
 639                        buffer.clone(),
 640                        &buffer_snapshot,
 641                        excerpt_ranges.clone(),
 642                        cx,
 643                    )
 644                });
 645                let multibuffer_snapshot = this.multibuffer.read(cx).snapshot(cx);
 646                let anchor_ranges: Vec<Range<Anchor>> = excerpt_ranges
 647                    .into_iter()
 648                    .filter_map(|range| {
 649                        let text_range = buffer_snapshot.anchor_range_inside(range.primary);
 650                        let start = multibuffer_snapshot.anchor_in_buffer(text_range.start)?;
 651                        let end = multibuffer_snapshot.anchor_in_buffer(text_range.end)?;
 652                        Some(start..end)
 653                    })
 654                    .collect();
 655                #[cfg(test)]
 656                let cloned_blocks = result_blocks.clone();
 657
 658                if was_empty && let Some(anchor_range) = anchor_ranges.first() {
 659                    let range_to_select = anchor_range.start..anchor_range.start;
 660                    this.editor.update(cx, |editor, cx| {
 661                        editor.change_selections(Default::default(), window, cx, |s| {
 662                            s.select_anchor_ranges([range_to_select]);
 663                        })
 664                    });
 665                    if this.focus_handle.is_focused(window) {
 666                        this.editor.read(cx).focus_handle(cx).focus(window, cx);
 667                    }
 668                }
 669
 670                let editor_blocks = anchor_ranges
 671                    .into_iter()
 672                    .zip_eq(result_blocks.into_iter())
 673                    .filter_map(|(anchor, block)| {
 674                        let block = block?;
 675                        let editor = this.editor.downgrade();
 676                        Some(BlockProperties {
 677                            placement: BlockPlacement::Near(anchor.start),
 678                            height: Some(1),
 679                            style: BlockStyle::Flex,
 680                            render: Arc::new(move |bcx| block.render_block(editor.clone(), bcx)),
 681                            priority: 1,
 682                        })
 683                    });
 684
 685                let block_ids = this.editor.update(cx, |editor, cx| {
 686                    editor.display_map.update(cx, |display_map, cx| {
 687                        display_map.insert_blocks(editor_blocks, cx)
 688                    })
 689                });
 690
 691                #[cfg(test)]
 692                {
 693                    for (block_id, block) in
 694                        block_ids.iter().zip(cloned_blocks.into_iter().flatten())
 695                    {
 696                        let markdown = block.markdown.clone();
 697                        editor::test::set_block_content_for_tests(
 698                            &this.editor,
 699                            *block_id,
 700                            cx,
 701                            move |cx| {
 702                                markdown::MarkdownElement::rendered_text(
 703                                    markdown.clone(),
 704                                    cx,
 705                                    editor::hover_popover::diagnostics_markdown_style,
 706                                )
 707                            },
 708                        );
 709                    }
 710                }
 711
 712                this.blocks.insert(buffer_id, block_ids);
 713                cx.notify()
 714            })
 715        })
 716    }
 717
 718    fn update_diagnostic_summary(&mut self, cx: &mut Context<Self>) {
 719        self.summary = self.project.read(cx).diagnostic_summary(false, cx);
 720        cx.emit(EditorEvent::TitleChanged);
 721    }
 722}
 723
 724impl Focusable for ProjectDiagnosticsEditor {
 725    fn focus_handle(&self, _: &App) -> FocusHandle {
 726        self.focus_handle.clone()
 727    }
 728}
 729
 730impl Item for ProjectDiagnosticsEditor {
 731    type Event = EditorEvent;
 732
 733    fn to_item_events(event: &EditorEvent, f: &mut dyn FnMut(ItemEvent)) {
 734        Editor::to_item_events(event, f)
 735    }
 736
 737    fn deactivated(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 738        self.editor
 739            .update(cx, |editor, cx| editor.deactivated(window, cx));
 740    }
 741
 742    fn navigate(
 743        &mut self,
 744        data: Arc<dyn Any + Send>,
 745        window: &mut Window,
 746        cx: &mut Context<Self>,
 747    ) -> bool {
 748        self.editor
 749            .update(cx, |editor, cx| editor.navigate(data, window, cx))
 750    }
 751
 752    fn tab_tooltip_text(&self, _: &App) -> Option<SharedString> {
 753        Some("Project Diagnostics".into())
 754    }
 755
 756    fn tab_content_text(&self, _detail: usize, _: &App) -> SharedString {
 757        "Diagnostics".into()
 758    }
 759
 760    fn tab_content(&self, params: TabContentParams, _window: &Window, _: &App) -> AnyElement {
 761        h_flex()
 762            .gap_1()
 763            .when(
 764                self.summary.error_count == 0 && self.summary.warning_count == 0,
 765                |then| {
 766                    then.child(
 767                        h_flex()
 768                            .gap_1()
 769                            .child(Icon::new(IconName::Check).color(Color::Success))
 770                            .child(Label::new("No problems").color(params.text_color())),
 771                    )
 772                },
 773            )
 774            .when(self.summary.error_count > 0, |then| {
 775                then.child(
 776                    h_flex()
 777                        .gap_1()
 778                        .child(Icon::new(IconName::XCircle).color(Color::Error))
 779                        .child(
 780                            Label::new(self.summary.error_count.to_string())
 781                                .color(params.text_color()),
 782                        ),
 783                )
 784            })
 785            .when(self.summary.warning_count > 0, |then| {
 786                then.child(
 787                    h_flex()
 788                        .gap_1()
 789                        .child(Icon::new(IconName::Warning).color(Color::Warning))
 790                        .child(
 791                            Label::new(self.summary.warning_count.to_string())
 792                                .color(params.text_color()),
 793                        ),
 794                )
 795            })
 796            .into_any_element()
 797    }
 798
 799    fn telemetry_event_text(&self) -> Option<&'static str> {
 800        Some("Project Diagnostics Opened")
 801    }
 802
 803    fn for_each_project_item(
 804        &self,
 805        cx: &App,
 806        f: &mut dyn FnMut(gpui::EntityId, &dyn project::ProjectItem),
 807    ) {
 808        self.editor.for_each_project_item(cx, f)
 809    }
 810
 811    fn set_nav_history(
 812        &mut self,
 813        nav_history: ItemNavHistory,
 814        _: &mut Window,
 815        cx: &mut Context<Self>,
 816    ) {
 817        self.editor.update(cx, |editor, _| {
 818            editor.set_nav_history(Some(nav_history));
 819        });
 820    }
 821
 822    fn can_split(&self) -> bool {
 823        true
 824    }
 825
 826    fn clone_on_split(
 827        &self,
 828        _workspace_id: Option<workspace::WorkspaceId>,
 829        window: &mut Window,
 830        cx: &mut Context<Self>,
 831    ) -> Task<Option<Entity<Self>>>
 832    where
 833        Self: Sized,
 834    {
 835        Task::ready(Some(cx.new(|cx| {
 836            ProjectDiagnosticsEditor::new(
 837                self.include_warnings,
 838                self.project.clone(),
 839                self.workspace.clone(),
 840                window,
 841                cx,
 842            )
 843        })))
 844    }
 845
 846    fn is_dirty(&self, cx: &App) -> bool {
 847        self.multibuffer.read(cx).is_dirty(cx)
 848    }
 849
 850    fn has_deleted_file(&self, cx: &App) -> bool {
 851        self.multibuffer.read(cx).has_deleted_file(cx)
 852    }
 853
 854    fn has_conflict(&self, cx: &App) -> bool {
 855        self.multibuffer.read(cx).has_conflict(cx)
 856    }
 857
 858    fn can_save(&self, _: &App) -> bool {
 859        true
 860    }
 861
 862    fn save(
 863        &mut self,
 864        options: SaveOptions,
 865        project: Entity<Project>,
 866        window: &mut Window,
 867        cx: &mut Context<Self>,
 868    ) -> Task<Result<()>> {
 869        self.editor.save(options, project, window, cx)
 870    }
 871
 872    fn save_as(
 873        &mut self,
 874        _: Entity<Project>,
 875        _: ProjectPath,
 876        _window: &mut Window,
 877        _: &mut Context<Self>,
 878    ) -> Task<Result<()>> {
 879        unreachable!()
 880    }
 881
 882    fn reload(
 883        &mut self,
 884        project: Entity<Project>,
 885        window: &mut Window,
 886        cx: &mut Context<Self>,
 887    ) -> Task<Result<()>> {
 888        self.editor.reload(project, window, cx)
 889    }
 890
 891    fn act_as_type<'a>(
 892        &'a self,
 893        type_id: TypeId,
 894        self_handle: &'a Entity<Self>,
 895        _: &'a App,
 896    ) -> Option<gpui::AnyEntity> {
 897        if type_id == TypeId::of::<Self>() {
 898            Some(self_handle.clone().into())
 899        } else if type_id == TypeId::of::<Editor>() {
 900            Some(self.editor.clone().into())
 901        } else {
 902            None
 903        }
 904    }
 905
 906    fn as_searchable(&self, _: &Entity<Self>, _: &App) -> Option<Box<dyn SearchableItemHandle>> {
 907        Some(Box::new(self.editor.clone()))
 908    }
 909
 910    fn added_to_workspace(
 911        &mut self,
 912        workspace: &mut Workspace,
 913        window: &mut Window,
 914        cx: &mut Context<Self>,
 915    ) {
 916        self.editor.update(cx, |editor, cx| {
 917            editor.added_to_workspace(workspace, window, cx)
 918        });
 919    }
 920}
 921
 922impl DiagnosticsToolbarEditor for WeakEntity<ProjectDiagnosticsEditor> {
 923    fn include_warnings(&self, cx: &App) -> bool {
 924        self.read_with(cx, |project_diagnostics_editor, _cx| {
 925            project_diagnostics_editor.include_warnings
 926        })
 927        .unwrap_or(false)
 928    }
 929
 930    fn is_updating(&self, cx: &App) -> bool {
 931        self.read_with(cx, |project_diagnostics_editor, cx| {
 932            project_diagnostics_editor.update_excerpts_task.is_some()
 933                || project_diagnostics_editor
 934                    .project
 935                    .read(cx)
 936                    .language_servers_running_disk_based_diagnostics(cx)
 937                    .next()
 938                    .is_some()
 939        })
 940        .unwrap_or(false)
 941    }
 942
 943    fn stop_updating(&self, cx: &mut App) {
 944        let _ = self.update(cx, |project_diagnostics_editor, cx| {
 945            project_diagnostics_editor.update_excerpts_task = None;
 946            cx.notify();
 947        });
 948    }
 949
 950    fn refresh_diagnostics(&self, window: &mut Window, cx: &mut App) {
 951        let _ = self.update(cx, |project_diagnostics_editor, cx| {
 952            project_diagnostics_editor.refresh(window, cx);
 953        });
 954    }
 955
 956    fn toggle_warnings(&self, window: &mut Window, cx: &mut App) {
 957        let _ = self.update(cx, |project_diagnostics_editor, cx| {
 958            project_diagnostics_editor.toggle_warnings(&Default::default(), window, cx);
 959        });
 960    }
 961
 962    fn get_diagnostics_for_buffer(
 963        &self,
 964        buffer_id: text::BufferId,
 965        cx: &App,
 966    ) -> Vec<language::DiagnosticEntry<text::Anchor>> {
 967        self.read_with(cx, |project_diagnostics_editor, _cx| {
 968            project_diagnostics_editor
 969                .diagnostics
 970                .get(&buffer_id)
 971                .cloned()
 972                .unwrap_or_default()
 973        })
 974        .unwrap_or_default()
 975    }
 976}
 977const DIAGNOSTIC_EXPANSION_ROW_LIMIT: u32 = 32;
 978
 979async fn context_range_for_entry(
 980    range: Range<Point>,
 981    context: u32,
 982    snapshot: BufferSnapshot,
 983    cx: &mut AsyncApp,
 984) -> Range<text::Anchor> {
 985    let range = if let Some(rows) = heuristic_syntactic_expand(
 986        range.clone(),
 987        DIAGNOSTIC_EXPANSION_ROW_LIMIT,
 988        snapshot.clone(),
 989        cx,
 990    )
 991    .await
 992    {
 993        Range {
 994            start: Point::new(*rows.start(), 0),
 995            end: snapshot.clip_point(Point::new(*rows.end(), u32::MAX), Bias::Left),
 996        }
 997    } else {
 998        Range {
 999            start: Point::new(range.start.row.saturating_sub(context), 0),
1000            end: snapshot.clip_point(Point::new(range.end.row + context, u32::MAX), Bias::Left),
1001        }
1002    };
1003    snapshot.anchor_after(range.start)..snapshot.anchor_before(range.end)
1004}
1005
1006/// Expands the input range using syntax information from TreeSitter. This expansion will be limited
1007/// to the specified `max_row_count`.
1008///
1009/// If there is a containing outline item that is less than `max_row_count`, it will be returned.
1010/// Otherwise fairly arbitrary heuristics are applied to attempt to return a logical block of code.
1011async fn heuristic_syntactic_expand(
1012    input_range: Range<Point>,
1013    max_row_count: u32,
1014    snapshot: BufferSnapshot,
1015    cx: &mut AsyncApp,
1016) -> Option<RangeInclusive<BufferRow>> {
1017    let start = snapshot.clip_point(input_range.start, Bias::Right);
1018    let end = snapshot.clip_point(input_range.end, Bias::Left);
1019    let input_row_count = input_range.end.row - input_range.start.row;
1020    if input_row_count > max_row_count {
1021        return None;
1022    }
1023
1024    let input_range = start..end;
1025    // If the outline node contains the diagnostic and is small enough, just use that.
1026    let outline_range = snapshot.outline_range_containing(input_range.clone());
1027    if let Some(outline_range) = outline_range.clone() {
1028        // Remove blank lines from start and end
1029        if let Some(start_row) = (outline_range.start.row..outline_range.end.row)
1030            .find(|row| !snapshot.line_indent_for_row(*row).is_line_blank())
1031            && let Some(end_row) = (outline_range.start.row..outline_range.end.row + 1)
1032                .rev()
1033                .find(|row| !snapshot.line_indent_for_row(*row).is_line_blank())
1034        {
1035            let row_count = end_row.saturating_sub(start_row);
1036            if row_count <= max_row_count {
1037                return Some(RangeInclusive::new(
1038                    outline_range.start.row,
1039                    outline_range.end.row,
1040                ));
1041            }
1042        }
1043    }
1044
1045    let mut node = snapshot.syntax_ancestor(input_range.clone())?;
1046
1047    loop {
1048        let node_start = Point::from_ts_point(node.start_position());
1049        let node_end = Point::from_ts_point(node.end_position());
1050        let node_range = node_start..node_end;
1051        let row_count = node_end.row - node_start.row + 1;
1052        let mut ancestor_range = None;
1053        cx.background_executor()
1054            .await_on_background(async {
1055                // Stop if we've exceeded the row count or reached an outline node. Then, find the interval
1056                // of node children which contains the query range. For example, this allows just returning
1057                // the header of a declaration rather than the entire declaration.
1058                if row_count > max_row_count || outline_range == Some(node_range.clone()) {
1059                    let mut cursor = node.walk();
1060                    let mut included_child_start = None;
1061                    let mut included_child_end = None;
1062                    let mut previous_end = node_start;
1063                    if cursor.goto_first_child() {
1064                        loop {
1065                            let child_node = cursor.node();
1066                            let child_range =
1067                                previous_end..Point::from_ts_point(child_node.end_position());
1068                            if included_child_start.is_none()
1069                                && child_range.contains(&input_range.start)
1070                            {
1071                                included_child_start = Some(child_range.start);
1072                            }
1073                            if child_range.contains(&input_range.end) {
1074                                included_child_end = Some(child_range.end);
1075                            }
1076                            previous_end = child_range.end;
1077                            if !cursor.goto_next_sibling() {
1078                                break;
1079                            }
1080                        }
1081                    }
1082                    let end = included_child_end.unwrap_or(node_range.end);
1083                    if let Some(start) = included_child_start {
1084                        let row_count = end.row - start.row;
1085                        if row_count < max_row_count {
1086                            ancestor_range = Some(Some(RangeInclusive::new(start.row, end.row)));
1087                            return;
1088                        }
1089                    }
1090                    ancestor_range = Some(None);
1091                }
1092            })
1093            .await;
1094        if let Some(node) = ancestor_range {
1095            return node;
1096        }
1097
1098        let node_name = node.grammar_name();
1099        let node_row_range = RangeInclusive::new(node_range.start.row, node_range.end.row);
1100        if node_name.ends_with("block") {
1101            return Some(node_row_range);
1102        } else if node_name.ends_with("statement") || node_name.ends_with("declaration") {
1103            // Expand to the nearest dedent or blank line for statements and declarations.
1104            let tab_size =
1105                cx.update(|cx| snapshot.settings_at(node_range.start, cx).tab_size.get());
1106            let indent_level = snapshot
1107                .line_indent_for_row(node_range.start.row)
1108                .len(tab_size);
1109            let rows_remaining = max_row_count.saturating_sub(row_count);
1110            let Some(start_row) = (node_range.start.row.saturating_sub(rows_remaining)
1111                ..node_range.start.row)
1112                .rev()
1113                .find(|row| {
1114                    is_line_blank_or_indented_less(indent_level, *row, tab_size, &snapshot.clone())
1115                })
1116            else {
1117                return Some(node_row_range);
1118            };
1119            let rows_remaining = max_row_count.saturating_sub(node_range.end.row - start_row);
1120            let Some(end_row) = (node_range.end.row + 1
1121                ..cmp::min(
1122                    node_range.end.row + rows_remaining + 1,
1123                    snapshot.row_count(),
1124                ))
1125                .find(|row| {
1126                    is_line_blank_or_indented_less(indent_level, *row, tab_size, &snapshot.clone())
1127                })
1128            else {
1129                return Some(node_row_range);
1130            };
1131            return Some(RangeInclusive::new(start_row, end_row));
1132        }
1133
1134        // TODO: doing this instead of walking a cursor as that doesn't work - why?
1135        let Some(parent) = node.parent() else {
1136            log::info!(
1137                "Expanding to ancestor reached the top node, so using default context line count.",
1138            );
1139            return None;
1140        };
1141        node = parent;
1142    }
1143}
1144
1145fn is_line_blank_or_indented_less(
1146    indent_level: u32,
1147    row: u32,
1148    tab_size: u32,
1149    snapshot: &BufferSnapshot,
1150) -> bool {
1151    let line_indent = snapshot.line_indent_for_row(row);
1152    line_indent.is_line_blank() || line_indent.len(tab_size) < indent_level
1153}