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