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