diagnostics.rs

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