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 languages = self
 512            .editor
 513            .read(cx)
 514            .project
 515            .as_ref()
 516            .unwrap()
 517            .read(cx)
 518            .languages()
 519            .clone();
 520        let was_empty = self.multibuffer.read(cx).is_empty();
 521        let buffer_snapshot = buffer.read(cx).snapshot();
 522        let buffer_id = buffer_snapshot.remote_id();
 523        let max_severity = if self.include_warnings {
 524            lsp::DiagnosticSeverity::WARNING
 525        } else {
 526            lsp::DiagnosticSeverity::ERROR
 527        };
 528
 529        cx.spawn_in(window, async move |this, mut cx| {
 530            let diagnostics = buffer_snapshot
 531                .diagnostics_in_range::<_, text::Anchor>(
 532                    Point::zero()..buffer_snapshot.max_point(),
 533                    false,
 534                )
 535                .collect::<Vec<_>>();
 536            let unchanged = this.update(cx, |this, _| {
 537                if this.diagnostics.get(&buffer_id).is_some_and(|existing| {
 538                    this.diagnostics_are_unchanged(existing, &diagnostics, &buffer_snapshot)
 539                }) {
 540                    return true;
 541                }
 542                this.diagnostics.insert(buffer_id, diagnostics.clone());
 543                return false;
 544            })?;
 545            if unchanged {
 546                return Ok(());
 547            }
 548
 549            let mut grouped: HashMap<usize, Vec<_>> = HashMap::default();
 550            for entry in diagnostics {
 551                grouped
 552                    .entry(entry.diagnostic.group_id)
 553                    .or_default()
 554                    .push(DiagnosticEntry {
 555                        range: entry.range.to_point(&buffer_snapshot),
 556                        diagnostic: entry.diagnostic,
 557                    })
 558            }
 559            let mut blocks: Vec<DiagnosticBlock> = Vec::new();
 560
 561            for (_, group) in grouped {
 562                let group_severity = group.iter().map(|d| d.diagnostic.severity).min();
 563                if group_severity.is_none_or(|s| s > max_severity) {
 564                    continue;
 565                }
 566                let more = cx.update(|_, cx| {
 567                    crate::diagnostic_renderer::DiagnosticRenderer::diagnostic_blocks_for_group(
 568                        group,
 569                        buffer_snapshot.remote_id(),
 570                        Some(this.clone()),
 571                        languages.clone(),
 572                        cx,
 573                    )
 574                })?;
 575
 576                for item in more {
 577                    let i = blocks
 578                        .binary_search_by(|probe| {
 579                            probe
 580                                .initial_range
 581                                .start
 582                                .cmp(&item.initial_range.start)
 583                                .then(probe.initial_range.end.cmp(&item.initial_range.end))
 584                                .then(Ordering::Greater)
 585                        })
 586                        .unwrap_or_else(|i| i);
 587                    blocks.insert(i, item);
 588                }
 589            }
 590
 591            let mut excerpt_ranges: Vec<ExcerptRange<Point>> = Vec::new();
 592            for b in blocks.iter() {
 593                let excerpt_range = context_range_for_entry(
 594                    b.initial_range.clone(),
 595                    DEFAULT_MULTIBUFFER_CONTEXT,
 596                    buffer_snapshot.clone(),
 597                    &mut cx,
 598                )
 599                .await;
 600                let i = excerpt_ranges
 601                    .binary_search_by(|probe| {
 602                        probe
 603                            .context
 604                            .start
 605                            .cmp(&excerpt_range.start)
 606                            .then(probe.context.end.cmp(&excerpt_range.end))
 607                            .then(probe.primary.start.cmp(&b.initial_range.start))
 608                            .then(probe.primary.end.cmp(&b.initial_range.end))
 609                            .then(cmp::Ordering::Greater)
 610                    })
 611                    .unwrap_or_else(|i| i);
 612                excerpt_ranges.insert(
 613                    i,
 614                    ExcerptRange {
 615                        context: excerpt_range,
 616                        primary: b.initial_range.clone(),
 617                    },
 618                )
 619            }
 620
 621            this.update_in(cx, |this, window, cx| {
 622                if let Some(block_ids) = this.blocks.remove(&buffer_id) {
 623                    this.editor.update(cx, |editor, cx| {
 624                        editor.display_map.update(cx, |display_map, cx| {
 625                            display_map.remove_blocks(block_ids.into_iter().collect(), cx)
 626                        });
 627                    })
 628                }
 629                let (anchor_ranges, _) = this.multibuffer.update(cx, |multi_buffer, cx| {
 630                    multi_buffer.set_excerpt_ranges_for_path(
 631                        PathKey::for_buffer(&buffer, cx),
 632                        buffer.clone(),
 633                        &buffer_snapshot,
 634                        excerpt_ranges,
 635                        cx,
 636                    )
 637                });
 638                #[cfg(test)]
 639                let cloned_blocks = blocks.clone();
 640
 641                if was_empty {
 642                    if 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
 655                let editor_blocks =
 656                    anchor_ranges
 657                        .into_iter()
 658                        .zip(blocks.into_iter())
 659                        .map(|(anchor, block)| {
 660                            let editor = this.editor.downgrade();
 661                            BlockProperties {
 662                                placement: BlockPlacement::Near(anchor.start),
 663                                height: Some(1),
 664                                style: BlockStyle::Flex,
 665                                render: Arc::new(move |bcx| {
 666                                    block.render_block(editor.clone(), bcx)
 667                                }),
 668                                priority: 1,
 669                                render_in_minimap: false,
 670                            }
 671                        });
 672                let block_ids = this.editor.update(cx, |editor, cx| {
 673                    editor.display_map.update(cx, |display_map, cx| {
 674                        display_map.insert_blocks(editor_blocks, cx)
 675                    })
 676                });
 677
 678                #[cfg(test)]
 679                {
 680                    for (block_id, block) in block_ids.iter().zip(cloned_blocks.iter()) {
 681                        let markdown = block.markdown.clone();
 682                        editor::test::set_block_content_for_tests(
 683                            &this.editor,
 684                            *block_id,
 685                            cx,
 686                            move |cx| {
 687                                markdown::MarkdownElement::rendered_text(
 688                                    markdown.clone(),
 689                                    cx,
 690                                    editor::hover_popover::diagnostics_markdown_style,
 691                                )
 692                            },
 693                        );
 694                    }
 695                }
 696
 697                this.blocks.insert(buffer_id, block_ids);
 698                cx.notify()
 699            })
 700        })
 701    }
 702
 703    pub fn cargo_diagnostics_sources(&self, cx: &App) -> Vec<ProjectPath> {
 704        let fetch_cargo_diagnostics = ProjectSettings::get_global(cx)
 705            .diagnostics
 706            .fetch_cargo_diagnostics();
 707        if !fetch_cargo_diagnostics {
 708            return Vec::new();
 709        }
 710        self.project
 711            .read(cx)
 712            .worktrees(cx)
 713            .filter_map(|worktree| {
 714                let _cargo_toml_entry = worktree.read(cx).entry_for_path("Cargo.toml")?;
 715                let rust_file_entry = worktree.read(cx).entries(false, 0).find(|entry| {
 716                    entry
 717                        .path
 718                        .extension()
 719                        .and_then(|extension| extension.to_str())
 720                        == Some("rs")
 721                })?;
 722                self.project.read(cx).path_for_entry(rust_file_entry.id, cx)
 723            })
 724            .collect()
 725    }
 726}
 727
 728impl Focusable for ProjectDiagnosticsEditor {
 729    fn focus_handle(&self, _: &App) -> FocusHandle {
 730        self.focus_handle.clone()
 731    }
 732}
 733
 734impl Item for ProjectDiagnosticsEditor {
 735    type Event = EditorEvent;
 736
 737    fn to_item_events(event: &EditorEvent, f: impl FnMut(ItemEvent)) {
 738        Editor::to_item_events(event, f)
 739    }
 740
 741    fn deactivated(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 742        self.editor
 743            .update(cx, |editor, cx| editor.deactivated(window, cx));
 744    }
 745
 746    fn navigate(
 747        &mut self,
 748        data: Box<dyn Any>,
 749        window: &mut Window,
 750        cx: &mut Context<Self>,
 751    ) -> bool {
 752        self.editor
 753            .update(cx, |editor, cx| editor.navigate(data, window, cx))
 754    }
 755
 756    fn tab_tooltip_text(&self, _: &App) -> Option<SharedString> {
 757        Some("Project Diagnostics".into())
 758    }
 759
 760    fn tab_content_text(&self, _detail: usize, _: &App) -> SharedString {
 761        "Diagnostics".into()
 762    }
 763
 764    fn tab_content(&self, params: TabContentParams, _window: &Window, _: &App) -> AnyElement {
 765        h_flex()
 766            .gap_1()
 767            .when(
 768                self.summary.error_count == 0 && self.summary.warning_count == 0,
 769                |then| {
 770                    then.child(
 771                        h_flex()
 772                            .gap_1()
 773                            .child(Icon::new(IconName::Check).color(Color::Success))
 774                            .child(Label::new("No problems").color(params.text_color())),
 775                    )
 776                },
 777            )
 778            .when(self.summary.error_count > 0, |then| {
 779                then.child(
 780                    h_flex()
 781                        .gap_1()
 782                        .child(Icon::new(IconName::XCircle).color(Color::Error))
 783                        .child(
 784                            Label::new(self.summary.error_count.to_string())
 785                                .color(params.text_color()),
 786                        ),
 787                )
 788            })
 789            .when(self.summary.warning_count > 0, |then| {
 790                then.child(
 791                    h_flex()
 792                        .gap_1()
 793                        .child(Icon::new(IconName::Warning).color(Color::Warning))
 794                        .child(
 795                            Label::new(self.summary.warning_count.to_string())
 796                                .color(params.text_color()),
 797                        ),
 798                )
 799            })
 800            .into_any_element()
 801    }
 802
 803    fn telemetry_event_text(&self) -> Option<&'static str> {
 804        Some("Project Diagnostics Opened")
 805    }
 806
 807    fn for_each_project_item(
 808        &self,
 809        cx: &App,
 810        f: &mut dyn FnMut(gpui::EntityId, &dyn project::ProjectItem),
 811    ) {
 812        self.editor.for_each_project_item(cx, f)
 813    }
 814
 815    fn is_singleton(&self, _: &App) -> bool {
 816        false
 817    }
 818
 819    fn set_nav_history(
 820        &mut self,
 821        nav_history: ItemNavHistory,
 822        _: &mut Window,
 823        cx: &mut Context<Self>,
 824    ) {
 825        self.editor.update(cx, |editor, _| {
 826            editor.set_nav_history(Some(nav_history));
 827        });
 828    }
 829
 830    fn clone_on_split(
 831        &self,
 832        _workspace_id: Option<workspace::WorkspaceId>,
 833        window: &mut Window,
 834        cx: &mut Context<Self>,
 835    ) -> Option<Entity<Self>>
 836    where
 837        Self: Sized,
 838    {
 839        Some(cx.new(|cx| {
 840            ProjectDiagnosticsEditor::new(
 841                self.include_warnings,
 842                self.project.clone(),
 843                self.workspace.clone(),
 844                window,
 845                cx,
 846            )
 847        }))
 848    }
 849
 850    fn is_dirty(&self, cx: &App) -> bool {
 851        self.multibuffer.read(cx).is_dirty(cx)
 852    }
 853
 854    fn has_deleted_file(&self, cx: &App) -> bool {
 855        self.multibuffer.read(cx).has_deleted_file(cx)
 856    }
 857
 858    fn has_conflict(&self, cx: &App) -> bool {
 859        self.multibuffer.read(cx).has_conflict(cx)
 860    }
 861
 862    fn can_save(&self, _: &App) -> bool {
 863        true
 864    }
 865
 866    fn save(
 867        &mut self,
 868        options: SaveOptions,
 869        project: Entity<Project>,
 870        window: &mut Window,
 871        cx: &mut Context<Self>,
 872    ) -> Task<Result<()>> {
 873        self.editor.save(options, project, window, cx)
 874    }
 875
 876    fn save_as(
 877        &mut self,
 878        _: Entity<Project>,
 879        _: ProjectPath,
 880        _window: &mut Window,
 881        _: &mut Context<Self>,
 882    ) -> Task<Result<()>> {
 883        unreachable!()
 884    }
 885
 886    fn reload(
 887        &mut self,
 888        project: Entity<Project>,
 889        window: &mut Window,
 890        cx: &mut Context<Self>,
 891    ) -> Task<Result<()>> {
 892        self.editor.reload(project, window, cx)
 893    }
 894
 895    fn act_as_type<'a>(
 896        &'a self,
 897        type_id: TypeId,
 898        self_handle: &'a Entity<Self>,
 899        _: &'a App,
 900    ) -> Option<AnyView> {
 901        if type_id == TypeId::of::<Self>() {
 902            Some(self_handle.to_any())
 903        } else if type_id == TypeId::of::<Editor>() {
 904            Some(self.editor.to_any())
 905        } else {
 906            None
 907        }
 908    }
 909
 910    fn as_searchable(&self, _: &Entity<Self>) -> Option<Box<dyn SearchableItemHandle>> {
 911        Some(Box::new(self.editor.clone()))
 912    }
 913
 914    fn breadcrumb_location(&self, _: &App) -> ToolbarItemLocation {
 915        ToolbarItemLocation::PrimaryLeft
 916    }
 917
 918    fn breadcrumbs(&self, theme: &theme::Theme, cx: &App) -> Option<Vec<BreadcrumbText>> {
 919        self.editor.breadcrumbs(theme, cx)
 920    }
 921
 922    fn added_to_workspace(
 923        &mut self,
 924        workspace: &mut Workspace,
 925        window: &mut Window,
 926        cx: &mut Context<Self>,
 927    ) {
 928        self.editor.update(cx, |editor, cx| {
 929            editor.added_to_workspace(workspace, window, cx)
 930        });
 931    }
 932}
 933
 934const DIAGNOSTIC_EXPANSION_ROW_LIMIT: u32 = 32;
 935
 936async fn context_range_for_entry(
 937    range: Range<Point>,
 938    context: u32,
 939    snapshot: BufferSnapshot,
 940    cx: &mut AsyncApp,
 941) -> Range<Point> {
 942    if let Some(rows) = heuristic_syntactic_expand(
 943        range.clone(),
 944        DIAGNOSTIC_EXPANSION_ROW_LIMIT,
 945        snapshot.clone(),
 946        cx,
 947    )
 948    .await
 949    {
 950        return Range {
 951            start: Point::new(*rows.start(), 0),
 952            end: snapshot.clip_point(Point::new(*rows.end(), u32::MAX), Bias::Left),
 953        };
 954    }
 955    Range {
 956        start: Point::new(range.start.row.saturating_sub(context), 0),
 957        end: snapshot.clip_point(Point::new(range.end.row + context, u32::MAX), Bias::Left),
 958    }
 959}
 960
 961/// Expands the input range using syntax information from TreeSitter. This expansion will be limited
 962/// to the specified `max_row_count`.
 963///
 964/// If there is a containing outline item that is less than `max_row_count`, it will be returned.
 965/// Otherwise fairly arbitrary heuristics are applied to attempt to return a logical block of code.
 966async fn heuristic_syntactic_expand(
 967    input_range: Range<Point>,
 968    max_row_count: u32,
 969    snapshot: BufferSnapshot,
 970    cx: &mut AsyncApp,
 971) -> Option<RangeInclusive<BufferRow>> {
 972    let input_row_count = input_range.end.row - input_range.start.row;
 973    if input_row_count > max_row_count {
 974        return None;
 975    }
 976
 977    // If the outline node contains the diagnostic and is small enough, just use that.
 978    let outline_range = snapshot.outline_range_containing(input_range.clone());
 979    if let Some(outline_range) = outline_range.clone() {
 980        // Remove blank lines from start and end
 981        if let Some(start_row) = (outline_range.start.row..outline_range.end.row)
 982            .find(|row| !snapshot.line_indent_for_row(*row).is_line_blank())
 983        {
 984            if let Some(end_row) = (outline_range.start.row..outline_range.end.row + 1)
 985                .rev()
 986                .find(|row| !snapshot.line_indent_for_row(*row).is_line_blank())
 987            {
 988                let row_count = end_row.saturating_sub(start_row);
 989                if row_count <= max_row_count {
 990                    return Some(RangeInclusive::new(
 991                        outline_range.start.row,
 992                        outline_range.end.row,
 993                    ));
 994                }
 995            }
 996        }
 997    }
 998
 999    let mut node = snapshot.syntax_ancestor(input_range.clone())?;
1000
1001    loop {
1002        let node_start = Point::from_ts_point(node.start_position());
1003        let node_end = Point::from_ts_point(node.end_position());
1004        let node_range = node_start..node_end;
1005        let row_count = node_end.row - node_start.row + 1;
1006        let mut ancestor_range = None;
1007        let reached_outline_node = cx.background_executor().scoped({
1008                 let node_range = node_range.clone();
1009                 let outline_range = outline_range.clone();
1010                 let ancestor_range =  &mut ancestor_range;
1011                |scope| {scope.spawn(async move {
1012                    // Stop if we've exceeded the row count or reached an outline node. Then, find the interval
1013                    // of node children which contains the query range. For example, this allows just returning
1014                    // the header of a declaration rather than the entire declaration.
1015                    if row_count > max_row_count || outline_range == Some(node_range.clone()) {
1016                        let mut cursor = node.walk();
1017                        let mut included_child_start = None;
1018                        let mut included_child_end = None;
1019                        let mut previous_end = node_start;
1020                        if cursor.goto_first_child() {
1021                            loop {
1022                                let child_node = cursor.node();
1023                                let child_range = previous_end..Point::from_ts_point(child_node.end_position());
1024                                if included_child_start.is_none() && child_range.contains(&input_range.start) {
1025                                    included_child_start = Some(child_range.start);
1026                                }
1027                                if child_range.contains(&input_range.end) {
1028                                    included_child_end = Some(child_range.end);
1029                                }
1030                                previous_end = child_range.end;
1031                                if !cursor.goto_next_sibling() {
1032                                    break;
1033                                }
1034                            }
1035                        }
1036                        let end = included_child_end.unwrap_or(node_range.end);
1037                        if let Some(start) = included_child_start {
1038                            let row_count = end.row - start.row;
1039                            if row_count < max_row_count {
1040                                *ancestor_range = Some(Some(RangeInclusive::new(start.row, end.row)));
1041                                return;
1042                            }
1043                        }
1044
1045                        log::info!(
1046                            "Expanding to ancestor started on {} node exceeding row limit of {max_row_count}.",
1047                            node.grammar_name()
1048                        );
1049                        *ancestor_range = Some(None);
1050                    }
1051                })
1052            }});
1053        reached_outline_node.await;
1054        if let Some(node) = ancestor_range {
1055            return node;
1056        }
1057
1058        let node_name = node.grammar_name();
1059        let node_row_range = RangeInclusive::new(node_range.start.row, node_range.end.row);
1060        if node_name.ends_with("block") {
1061            return Some(node_row_range);
1062        } else if node_name.ends_with("statement") || node_name.ends_with("declaration") {
1063            // Expand to the nearest dedent or blank line for statements and declarations.
1064            let tab_size = cx
1065                .update(|cx| snapshot.settings_at(node_range.start, cx).tab_size.get())
1066                .ok()?;
1067            let indent_level = snapshot
1068                .line_indent_for_row(node_range.start.row)
1069                .len(tab_size);
1070            let rows_remaining = max_row_count.saturating_sub(row_count);
1071            let Some(start_row) = (node_range.start.row.saturating_sub(rows_remaining)
1072                ..node_range.start.row)
1073                .rev()
1074                .find(|row| {
1075                    is_line_blank_or_indented_less(indent_level, *row, tab_size, &snapshot.clone())
1076                })
1077            else {
1078                return Some(node_row_range);
1079            };
1080            let rows_remaining = max_row_count.saturating_sub(node_range.end.row - start_row);
1081            let Some(end_row) = (node_range.end.row + 1
1082                ..cmp::min(
1083                    node_range.end.row + rows_remaining + 1,
1084                    snapshot.row_count(),
1085                ))
1086                .find(|row| {
1087                    is_line_blank_or_indented_less(indent_level, *row, tab_size, &snapshot.clone())
1088                })
1089            else {
1090                return Some(node_row_range);
1091            };
1092            return Some(RangeInclusive::new(start_row, end_row));
1093        }
1094
1095        // TODO: doing this instead of walking a cursor as that doesn't work - why?
1096        let Some(parent) = node.parent() else {
1097            log::info!(
1098                "Expanding to ancestor reached the top node, so using default context line count.",
1099            );
1100            return None;
1101        };
1102        node = parent;
1103    }
1104}
1105
1106fn is_line_blank_or_indented_less(
1107    indent_level: u32,
1108    row: u32,
1109    tab_size: u32,
1110    snapshot: &BufferSnapshot,
1111) -> bool {
1112    let line_indent = snapshot.line_indent_for_row(row);
1113    line_indent.is_line_blank() || line_indent.len(tab_size) < indent_level
1114}