diagnostics.rs

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