diagnostics.rs

   1pub mod items;
   2mod toolbar_controls;
   3
   4#[cfg(test)]
   5mod diagnostics_tests;
   6
   7use anyhow::Result;
   8use collections::{BTreeSet, HashSet};
   9use editor::{
  10    diagnostic_block_renderer,
  11    display_map::{BlockPlacement, BlockProperties, BlockStyle, CustomBlockId, RenderBlock},
  12    highlight_diagnostic_message,
  13    scroll::Autoscroll,
  14    Editor, EditorEvent, ExcerptId, ExcerptRange, MultiBuffer, ToOffset,
  15};
  16use gpui::{
  17    actions, div, svg, AnyElement, AnyView, App, AsyncApp, Context, Entity, EventEmitter,
  18    FocusHandle, Focusable, Global, HighlightStyle, InteractiveElement, IntoElement, ParentElement,
  19    Render, SharedString, Styled, StyledText, Subscription, Task, WeakEntity, Window,
  20};
  21use language::{
  22    Bias, Buffer, BufferRow, BufferSnapshot, Diagnostic, DiagnosticEntry, DiagnosticSeverity,
  23    Point, Selection, SelectionGoal, ToTreeSitterPoint,
  24};
  25use lsp::LanguageServerId;
  26use project::{project_settings::ProjectSettings, DiagnosticSummary, Project, ProjectPath};
  27use settings::Settings;
  28use std::{
  29    any::{Any, TypeId},
  30    cmp,
  31    cmp::Ordering,
  32    mem,
  33    ops::{Range, RangeInclusive},
  34    sync::Arc,
  35    time::Duration,
  36};
  37use theme::ActiveTheme;
  38pub use toolbar_controls::ToolbarControls;
  39use ui::{h_flex, prelude::*, Icon, IconName, Label};
  40use util::ResultExt;
  41use workspace::{
  42    item::{BreadcrumbText, Item, ItemEvent, ItemHandle, TabContentParams},
  43    searchable::SearchableItemHandle,
  44    ItemNavHistory, ToolbarItemLocation, Workspace,
  45};
  46
  47actions!(diagnostics, [Deploy, ToggleWarnings]);
  48
  49struct IncludeWarnings(bool);
  50impl Global for IncludeWarnings {}
  51
  52pub fn init(cx: &mut App) {
  53    cx.observe_new(ProjectDiagnosticsEditor::register).detach();
  54}
  55
  56struct ProjectDiagnosticsEditor {
  57    project: Entity<Project>,
  58    workspace: WeakEntity<Workspace>,
  59    focus_handle: FocusHandle,
  60    editor: Entity<Editor>,
  61    summary: DiagnosticSummary,
  62    excerpts: Entity<MultiBuffer>,
  63    path_states: Vec<PathState>,
  64    paths_to_update: BTreeSet<(ProjectPath, Option<LanguageServerId>)>,
  65    include_warnings: bool,
  66    context: u32,
  67    update_excerpts_task: Option<Task<Result<()>>>,
  68    _subscription: Subscription,
  69}
  70
  71struct PathState {
  72    path: ProjectPath,
  73    diagnostic_groups: Vec<DiagnosticGroupState>,
  74}
  75
  76struct DiagnosticGroupState {
  77    language_server_id: LanguageServerId,
  78    primary_diagnostic: DiagnosticEntry<language::Anchor>,
  79    primary_excerpt_ix: usize,
  80    excerpts: Vec<ExcerptId>,
  81    blocks: HashSet<CustomBlockId>,
  82    block_count: usize,
  83}
  84
  85impl EventEmitter<EditorEvent> for ProjectDiagnosticsEditor {}
  86
  87const DIAGNOSTICS_UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
  88
  89impl Render for ProjectDiagnosticsEditor {
  90    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
  91        let warning_count = if self.include_warnings {
  92            self.summary.warning_count
  93        } else {
  94            0
  95        };
  96
  97        let child = if warning_count + self.summary.error_count == 0 {
  98            let label = if self.summary.warning_count == 0 {
  99                SharedString::new_static("No problems in workspace")
 100            } else {
 101                SharedString::new_static("No errors in workspace")
 102            };
 103            v_flex()
 104                .key_context("EmptyPane")
 105                .size_full()
 106                .gap_1()
 107                .justify_center()
 108                .items_center()
 109                .text_center()
 110                .bg(cx.theme().colors().editor_background)
 111                .child(Label::new(label).color(Color::Muted))
 112                .when(self.summary.warning_count > 0, |this| {
 113                    let plural_suffix = if self.summary.warning_count > 1 {
 114                        "s"
 115                    } else {
 116                        ""
 117                    };
 118                    let label = format!(
 119                        "Show {} warning{}",
 120                        self.summary.warning_count, plural_suffix
 121                    );
 122                    this.child(
 123                        Button::new("diagnostics-show-warning-label", label).on_click(cx.listener(
 124                            |this, _, window, cx| {
 125                                this.toggle_warnings(&Default::default(), window, cx);
 126                                cx.notify();
 127                            },
 128                        )),
 129                    )
 130                })
 131        } else {
 132            div().size_full().child(self.editor.clone())
 133        };
 134
 135        div()
 136            .key_context("Diagnostics")
 137            .track_focus(&self.focus_handle(cx))
 138            .size_full()
 139            .on_action(cx.listener(Self::toggle_warnings))
 140            .child(child)
 141    }
 142}
 143
 144impl ProjectDiagnosticsEditor {
 145    fn register(
 146        workspace: &mut Workspace,
 147        _window: Option<&mut Window>,
 148        _: &mut Context<Workspace>,
 149    ) {
 150        workspace.register_action(Self::deploy);
 151    }
 152
 153    fn new_with_context(
 154        context: u32,
 155        include_warnings: bool,
 156        project_handle: Entity<Project>,
 157        workspace: WeakEntity<Workspace>,
 158        window: &mut Window,
 159        cx: &mut Context<Self>,
 160    ) -> Self {
 161        let project_event_subscription =
 162            cx.subscribe_in(&project_handle, window, |this, project, event, window, cx| match event {
 163                project::Event::DiskBasedDiagnosticsStarted { .. } => {
 164                    cx.notify();
 165                }
 166                project::Event::DiskBasedDiagnosticsFinished { language_server_id } => {
 167                    log::debug!("disk based diagnostics finished for server {language_server_id}");
 168                    this.update_stale_excerpts(window, cx);
 169                }
 170                project::Event::DiagnosticsUpdated {
 171                    language_server_id,
 172                    path,
 173                } => {
 174                    this.paths_to_update
 175                        .insert((path.clone(), Some(*language_server_id)));
 176                    this.summary = project.read(cx).diagnostic_summary(false, cx);
 177                    cx.emit(EditorEvent::TitleChanged);
 178
 179                    if this.editor.focus_handle(cx).contains_focused(window, cx) || this.focus_handle.contains_focused(window, cx) {
 180                        log::debug!("diagnostics updated for server {language_server_id}, path {path:?}. recording change");
 181                    } else {
 182                        log::debug!("diagnostics updated for server {language_server_id}, path {path:?}. updating excerpts");
 183                        this.update_stale_excerpts(window, cx);
 184                    }
 185                }
 186                _ => {}
 187            });
 188
 189        let focus_handle = cx.focus_handle();
 190        cx.on_focus_in(&focus_handle, window, |this, window, cx| {
 191            this.focus_in(window, cx)
 192        })
 193        .detach();
 194        cx.on_focus_out(&focus_handle, window, |this, _event, window, cx| {
 195            this.focus_out(window, cx)
 196        })
 197        .detach();
 198
 199        let excerpts = cx.new(|cx| MultiBuffer::new(project_handle.read(cx).capability()));
 200        let editor = cx.new(|cx| {
 201            let mut editor = Editor::for_multibuffer(
 202                excerpts.clone(),
 203                Some(project_handle.clone()),
 204                true,
 205                window,
 206                cx,
 207            );
 208            editor.set_vertical_scroll_margin(5, cx);
 209            editor.disable_inline_diagnostics();
 210            editor
 211        });
 212        cx.subscribe_in(
 213            &editor,
 214            window,
 215            |this, _editor, event: &EditorEvent, window, cx| {
 216                cx.emit(event.clone());
 217                match event {
 218                    EditorEvent::Focused => {
 219                        if this.path_states.is_empty() {
 220                            window.focus(&this.focus_handle);
 221                        }
 222                    }
 223                    EditorEvent::Blurred => this.update_stale_excerpts(window, cx),
 224                    _ => {}
 225                }
 226            },
 227        )
 228        .detach();
 229        cx.observe_global_in::<IncludeWarnings>(window, |this, window, cx| {
 230            this.include_warnings = cx.global::<IncludeWarnings>().0;
 231            this.update_all_excerpts(window, cx);
 232        })
 233        .detach();
 234
 235        let project = project_handle.read(cx);
 236        let mut this = Self {
 237            project: project_handle.clone(),
 238            context,
 239            summary: project.diagnostic_summary(false, cx),
 240            include_warnings,
 241            workspace,
 242            excerpts,
 243            focus_handle,
 244            editor,
 245            path_states: Default::default(),
 246            paths_to_update: Default::default(),
 247            update_excerpts_task: None,
 248            _subscription: project_event_subscription,
 249        };
 250        this.update_all_excerpts(window, cx);
 251        this
 252    }
 253
 254    fn update_stale_excerpts(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 255        if self.update_excerpts_task.is_some() {
 256            return;
 257        }
 258        let project_handle = self.project.clone();
 259        self.update_excerpts_task = Some(cx.spawn_in(window, |this, mut cx| async move {
 260            cx.background_executor()
 261                .timer(DIAGNOSTICS_UPDATE_DEBOUNCE)
 262                .await;
 263            loop {
 264                let Some((path, language_server_id)) = this.update(&mut cx, |this, _| {
 265                    let Some((path, language_server_id)) = this.paths_to_update.pop_first() else {
 266                        this.update_excerpts_task.take();
 267                        return None;
 268                    };
 269                    Some((path, language_server_id))
 270                })?
 271                else {
 272                    break;
 273                };
 274
 275                if let Some(buffer) = project_handle
 276                    .update(&mut cx, |project, cx| project.open_buffer(path.clone(), cx))?
 277                    .await
 278                    .log_err()
 279                {
 280                    this.update_in(&mut cx, |this, window, cx| {
 281                        this.update_excerpts(path, language_server_id, buffer, window, cx)
 282                    })?
 283                    .await?;
 284                }
 285            }
 286            Ok(())
 287        }));
 288    }
 289
 290    fn new(
 291        project_handle: Entity<Project>,
 292        include_warnings: bool,
 293        workspace: WeakEntity<Workspace>,
 294        window: &mut Window,
 295        cx: &mut Context<Self>,
 296    ) -> Self {
 297        Self::new_with_context(
 298            editor::DEFAULT_MULTIBUFFER_CONTEXT,
 299            include_warnings,
 300            project_handle,
 301            workspace,
 302            window,
 303            cx,
 304        )
 305    }
 306
 307    fn deploy(
 308        workspace: &mut Workspace,
 309        _: &Deploy,
 310        window: &mut Window,
 311        cx: &mut Context<Workspace>,
 312    ) {
 313        if let Some(existing) = workspace.item_of_type::<ProjectDiagnosticsEditor>(cx) {
 314            workspace.activate_item(&existing, true, true, window, cx);
 315        } else {
 316            let workspace_handle = cx.entity().downgrade();
 317
 318            let include_warnings = match cx.try_global::<IncludeWarnings>() {
 319                Some(include_warnings) => include_warnings.0,
 320                None => ProjectSettings::get_global(cx).diagnostics.include_warnings,
 321            };
 322
 323            let diagnostics = cx.new(|cx| {
 324                ProjectDiagnosticsEditor::new(
 325                    workspace.project().clone(),
 326                    include_warnings,
 327                    workspace_handle,
 328                    window,
 329                    cx,
 330                )
 331            });
 332            workspace.add_item_to_active_pane(Box::new(diagnostics), None, true, window, cx);
 333        }
 334    }
 335
 336    fn toggle_warnings(&mut self, _: &ToggleWarnings, window: &mut Window, cx: &mut Context<Self>) {
 337        self.include_warnings = !self.include_warnings;
 338        cx.set_global(IncludeWarnings(self.include_warnings));
 339        self.update_all_excerpts(window, cx);
 340        cx.notify();
 341    }
 342
 343    fn focus_in(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 344        if self.focus_handle.is_focused(window) && !self.path_states.is_empty() {
 345            self.editor.focus_handle(cx).focus(window)
 346        }
 347    }
 348
 349    fn focus_out(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 350        if !self.focus_handle.is_focused(window) && !self.editor.focus_handle(cx).is_focused(window)
 351        {
 352            self.update_stale_excerpts(window, cx);
 353        }
 354    }
 355
 356    /// Enqueue an update of all excerpts. Updates all paths that either
 357    /// currently have diagnostics or are currently present in this view.
 358    fn update_all_excerpts(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 359        self.project.update(cx, |project, cx| {
 360            let mut paths = project
 361                .diagnostic_summaries(false, cx)
 362                .map(|(path, _, _)| (path, None))
 363                .collect::<BTreeSet<_>>();
 364            paths.extend(
 365                self.path_states
 366                    .iter()
 367                    .map(|state| (state.path.clone(), None)),
 368            );
 369            let paths_to_update = std::mem::take(&mut self.paths_to_update);
 370            paths.extend(paths_to_update.into_iter().map(|(path, _)| (path, None)));
 371            self.paths_to_update = paths;
 372        });
 373        self.update_stale_excerpts(window, cx);
 374    }
 375
 376    fn update_excerpts(
 377        &mut self,
 378        path_to_update: ProjectPath,
 379        server_to_update: Option<LanguageServerId>,
 380        buffer: Entity<Buffer>,
 381        window: &mut Window,
 382        cx: &mut Context<Self>,
 383    ) -> Task<Result<()>> {
 384        let was_empty = self.path_states.is_empty();
 385        let snapshot = buffer.read(cx).snapshot();
 386        let path_ix = match self
 387            .path_states
 388            .binary_search_by_key(&&path_to_update, |e| &e.path)
 389        {
 390            Ok(ix) => ix,
 391            Err(ix) => {
 392                self.path_states.insert(
 393                    ix,
 394                    PathState {
 395                        path: path_to_update.clone(),
 396                        diagnostic_groups: Default::default(),
 397                    },
 398                );
 399                ix
 400            }
 401        };
 402        let mut prev_excerpt_id = if path_ix > 0 {
 403            let prev_path_last_group = &self.path_states[path_ix - 1]
 404                .diagnostic_groups
 405                .last()
 406                .unwrap();
 407            *prev_path_last_group.excerpts.last().unwrap()
 408        } else {
 409            ExcerptId::min()
 410        };
 411
 412        let mut new_group_ixs = Vec::new();
 413        let mut blocks_to_add = Vec::new();
 414        let mut blocks_to_remove = HashSet::default();
 415        let mut first_excerpt_id = None;
 416        let max_severity = if self.include_warnings {
 417            DiagnosticSeverity::WARNING
 418        } else {
 419            DiagnosticSeverity::ERROR
 420        };
 421        let excerpts = self.excerpts.clone().downgrade();
 422        let context = self.context;
 423        let editor = self.editor.clone().downgrade();
 424        cx.spawn_in(window, move |this, mut cx| async move {
 425            let mut old_groups = this
 426                .update(&mut cx, |this, _| {
 427                    mem::take(&mut this.path_states[path_ix].diagnostic_groups)
 428                })?
 429                .into_iter()
 430                .enumerate()
 431                .peekable();
 432            let mut new_groups = snapshot
 433                .diagnostic_groups(server_to_update)
 434                .into_iter()
 435                .filter(|(_, group)| {
 436                    group.entries[group.primary_ix].diagnostic.severity <= max_severity
 437                })
 438                .peekable();
 439            loop {
 440                let mut to_insert = None;
 441                let mut to_remove = None;
 442                let mut to_keep = None;
 443                match (old_groups.peek(), new_groups.peek()) {
 444                    (None, None) => break,
 445                    (None, Some(_)) => to_insert = new_groups.next(),
 446                    (Some((_, old_group)), None) => {
 447                        if server_to_update.map_or(true, |id| id == old_group.language_server_id) {
 448                            to_remove = old_groups.next();
 449                        } else {
 450                            to_keep = old_groups.next();
 451                        }
 452                    }
 453                    (Some((_, old_group)), Some((new_language_server_id, new_group))) => {
 454                        let old_primary = &old_group.primary_diagnostic;
 455                        let new_primary = &new_group.entries[new_group.primary_ix];
 456                        match compare_diagnostics(old_primary, new_primary, &snapshot)
 457                            .then_with(|| old_group.language_server_id.cmp(new_language_server_id))
 458                        {
 459                            Ordering::Less => {
 460                                if server_to_update
 461                                    .map_or(true, |id| id == old_group.language_server_id)
 462                                {
 463                                    to_remove = old_groups.next();
 464                                } else {
 465                                    to_keep = old_groups.next();
 466                                }
 467                            }
 468                            Ordering::Equal => {
 469                                to_keep = old_groups.next();
 470                                new_groups.next();
 471                            }
 472                            Ordering::Greater => to_insert = new_groups.next(),
 473                        }
 474                    }
 475                }
 476
 477                if let Some((language_server_id, group)) = to_insert {
 478                    let mut group_state = DiagnosticGroupState {
 479                        language_server_id,
 480                        primary_diagnostic: group.entries[group.primary_ix].clone(),
 481                        primary_excerpt_ix: 0,
 482                        excerpts: Default::default(),
 483                        blocks: Default::default(),
 484                        block_count: 0,
 485                    };
 486                    let mut pending_range: Option<(Range<Point>, Range<Point>, usize)> = None;
 487                    let mut is_first_excerpt_for_group = true;
 488                    for (ix, entry) in group.entries.iter().map(Some).chain([None]).enumerate() {
 489                        let resolved_entry = entry.map(|e| e.resolve::<Point>(&snapshot));
 490                        let expanded_range = if let Some(entry) = &resolved_entry {
 491                            Some(
 492                                context_range_for_entry(
 493                                    entry.range.clone(),
 494                                    context,
 495                                    snapshot.clone(),
 496                                    (*cx).clone(),
 497                                )
 498                                .await,
 499                            )
 500                        } else {
 501                            None
 502                        };
 503                        if let Some((range, context_range, start_ix)) = &mut pending_range {
 504                            if let Some(expanded_range) = expanded_range.clone() {
 505                                // If the entries are overlapping or next to each-other, merge them into one excerpt.
 506                                if context_range.end.row + 1 >= expanded_range.start.row {
 507                                    context_range.end = context_range.end.max(expanded_range.end);
 508                                    continue;
 509                                }
 510                            }
 511
 512                            let excerpt_id = excerpts.update(&mut cx, |excerpts, cx| {
 513                                excerpts
 514                                    .insert_excerpts_after(
 515                                        prev_excerpt_id,
 516                                        buffer.clone(),
 517                                        [ExcerptRange {
 518                                            context: context_range.clone(),
 519                                            primary: Some(range.clone()),
 520                                        }],
 521                                        cx,
 522                                    )
 523                                    .pop()
 524                                    .unwrap()
 525                            })?;
 526
 527                            prev_excerpt_id = excerpt_id;
 528                            first_excerpt_id.get_or_insert(prev_excerpt_id);
 529                            group_state.excerpts.push(excerpt_id);
 530                            let header_position = (excerpt_id, language::Anchor::MIN);
 531
 532                            if is_first_excerpt_for_group {
 533                                is_first_excerpt_for_group = false;
 534                                let mut primary =
 535                                    group.entries[group.primary_ix].diagnostic.clone();
 536                                primary.message =
 537                                    primary.message.split('\n').next().unwrap().to_string();
 538                                group_state.block_count += 1;
 539                                blocks_to_add.push(BlockProperties {
 540                                    placement: BlockPlacement::Above(header_position),
 541                                    height: 2,
 542                                    style: BlockStyle::Sticky,
 543                                    render: diagnostic_header_renderer(primary),
 544                                    priority: 0,
 545                                });
 546                            }
 547
 548                            for entry in &group.entries[*start_ix..ix] {
 549                                let mut diagnostic = entry.diagnostic.clone();
 550                                if diagnostic.is_primary {
 551                                    group_state.primary_excerpt_ix = group_state.excerpts.len() - 1;
 552                                    diagnostic.message =
 553                                        entry.diagnostic.message.split('\n').skip(1).collect();
 554                                }
 555
 556                                if !diagnostic.message.is_empty() {
 557                                    group_state.block_count += 1;
 558                                    blocks_to_add.push(BlockProperties {
 559                                        placement: BlockPlacement::Below((
 560                                            excerpt_id,
 561                                            entry.range.start,
 562                                        )),
 563                                        height: diagnostic.message.matches('\n').count() as u32 + 1,
 564                                        style: BlockStyle::Fixed,
 565                                        render: diagnostic_block_renderer(diagnostic, None, true),
 566                                        priority: 0,
 567                                    });
 568                                }
 569                            }
 570
 571                            pending_range.take();
 572                        }
 573
 574                        if let Some(entry) = resolved_entry.as_ref() {
 575                            let range = entry.range.clone();
 576                            pending_range = Some((range, expanded_range.unwrap(), ix));
 577                        }
 578                    }
 579
 580                    this.update(&mut cx, |this, _| {
 581                        new_group_ixs.push(this.path_states[path_ix].diagnostic_groups.len());
 582                        this.path_states[path_ix]
 583                            .diagnostic_groups
 584                            .push(group_state);
 585                    })?;
 586                } else if let Some((_, group_state)) = to_remove {
 587                    excerpts.update(&mut cx, |excerpts, cx| {
 588                        excerpts.remove_excerpts(group_state.excerpts.iter().copied(), cx)
 589                    })?;
 590                    blocks_to_remove.extend(group_state.blocks.iter().copied());
 591                } else if let Some((_, group_state)) = to_keep {
 592                    prev_excerpt_id = *group_state.excerpts.last().unwrap();
 593                    first_excerpt_id.get_or_insert(prev_excerpt_id);
 594
 595                    this.update(&mut cx, |this, _| {
 596                        this.path_states[path_ix]
 597                            .diagnostic_groups
 598                            .push(group_state)
 599                    })?;
 600                }
 601            }
 602
 603            let excerpts_snapshot =
 604                excerpts.update(&mut cx, |excerpts, cx| excerpts.snapshot(cx))?;
 605            editor.update(&mut cx, |editor, cx| {
 606                editor.remove_blocks(blocks_to_remove, None, cx);
 607                let block_ids = editor.insert_blocks(
 608                    blocks_to_add.into_iter().flat_map(|block| {
 609                        let placement = match block.placement {
 610                            BlockPlacement::Above((excerpt_id, text_anchor)) => {
 611                                BlockPlacement::Above(
 612                                    excerpts_snapshot.anchor_in_excerpt(excerpt_id, text_anchor)?,
 613                                )
 614                            }
 615                            BlockPlacement::Below((excerpt_id, text_anchor)) => {
 616                                BlockPlacement::Below(
 617                                    excerpts_snapshot.anchor_in_excerpt(excerpt_id, text_anchor)?,
 618                                )
 619                            }
 620                            BlockPlacement::Replace(_) => {
 621                                unreachable!(
 622                                    "no Replace block should have been pushed to blocks_to_add"
 623                                )
 624                            }
 625                        };
 626                        Some(BlockProperties {
 627                            placement,
 628                            height: block.height,
 629                            style: block.style,
 630                            render: block.render,
 631                            priority: 0,
 632                        })
 633                    }),
 634                    Some(Autoscroll::fit()),
 635                    cx,
 636                );
 637
 638                let mut block_ids = block_ids.into_iter();
 639                this.update(cx, |this, _| {
 640                    for ix in new_group_ixs {
 641                        let group_state = &mut this.path_states[path_ix].diagnostic_groups[ix];
 642                        group_state.blocks =
 643                            block_ids.by_ref().take(group_state.block_count).collect();
 644                    }
 645                })?;
 646                Result::<(), anyhow::Error>::Ok(())
 647            })??;
 648
 649            this.update_in(&mut cx, |this, window, cx| {
 650                if this.path_states[path_ix].diagnostic_groups.is_empty() {
 651                    this.path_states.remove(path_ix);
 652                }
 653
 654                this.editor.update(cx, |editor, cx| {
 655                    let groups;
 656                    let mut selections;
 657                    let new_excerpt_ids_by_selection_id;
 658                    if was_empty {
 659                        groups = this.path_states.first()?.diagnostic_groups.as_slice();
 660                        new_excerpt_ids_by_selection_id =
 661                            [(0, ExcerptId::min())].into_iter().collect();
 662                        selections = vec![Selection {
 663                            id: 0,
 664                            start: 0,
 665                            end: 0,
 666                            reversed: false,
 667                            goal: SelectionGoal::None,
 668                        }];
 669                    } else {
 670                        groups = this.path_states.get(path_ix)?.diagnostic_groups.as_slice();
 671                        new_excerpt_ids_by_selection_id =
 672                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 673                                s.refresh()
 674                            });
 675                        selections = editor.selections.all::<usize>(cx);
 676                    }
 677
 678                    // If any selection has lost its position, move it to start of the next primary diagnostic.
 679                    let snapshot = editor.snapshot(window, cx);
 680                    for selection in &mut selections {
 681                        if let Some(new_excerpt_id) =
 682                            new_excerpt_ids_by_selection_id.get(&selection.id)
 683                        {
 684                            let group_ix = match groups.binary_search_by(|probe| {
 685                                probe
 686                                    .excerpts
 687                                    .last()
 688                                    .unwrap()
 689                                    .cmp(new_excerpt_id, &snapshot.buffer_snapshot)
 690                            }) {
 691                                Ok(ix) | Err(ix) => ix,
 692                            };
 693                            if let Some(group) = groups.get(group_ix) {
 694                                if let Some(offset) = excerpts_snapshot
 695                                    .anchor_in_excerpt(
 696                                        group.excerpts[group.primary_excerpt_ix],
 697                                        group.primary_diagnostic.range.start,
 698                                    )
 699                                    .map(|anchor| anchor.to_offset(&excerpts_snapshot))
 700                                {
 701                                    selection.start = offset;
 702                                    selection.end = offset;
 703                                }
 704                            }
 705                        }
 706                    }
 707                    editor.change_selections(None, window, cx, |s| {
 708                        s.select(selections);
 709                    });
 710                    Some(())
 711                });
 712            })?;
 713
 714            this.update_in(&mut cx, |this, window, cx| {
 715                if this.path_states.is_empty() {
 716                    if this.editor.focus_handle(cx).is_focused(window) {
 717                        window.focus(&this.focus_handle);
 718                    }
 719                } else if this.focus_handle.is_focused(window) {
 720                    let focus_handle = this.editor.focus_handle(cx);
 721                    window.focus(&focus_handle);
 722                }
 723
 724                #[cfg(test)]
 725                this.check_invariants(cx);
 726
 727                cx.notify();
 728            })
 729        })
 730    }
 731
 732    #[cfg(test)]
 733    fn check_invariants(&self, cx: &mut Context<Self>) {
 734        let mut excerpts = Vec::new();
 735        for (id, buffer, _) in self.excerpts.read(cx).snapshot(cx).excerpts() {
 736            if let Some(file) = buffer.file() {
 737                excerpts.push((id, file.path().clone()));
 738            }
 739        }
 740
 741        let mut prev_path = None;
 742        for (_, path) in &excerpts {
 743            if let Some(prev_path) = prev_path {
 744                if path < prev_path {
 745                    panic!("excerpts are not sorted by path {:?}", excerpts);
 746                }
 747            }
 748            prev_path = Some(path);
 749        }
 750    }
 751}
 752
 753impl Focusable for ProjectDiagnosticsEditor {
 754    fn focus_handle(&self, _: &App) -> FocusHandle {
 755        self.focus_handle.clone()
 756    }
 757}
 758
 759impl Item for ProjectDiagnosticsEditor {
 760    type Event = EditorEvent;
 761
 762    fn to_item_events(event: &EditorEvent, f: impl FnMut(ItemEvent)) {
 763        Editor::to_item_events(event, f)
 764    }
 765
 766    fn deactivated(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 767        self.editor
 768            .update(cx, |editor, cx| editor.deactivated(window, cx));
 769    }
 770
 771    fn navigate(
 772        &mut self,
 773        data: Box<dyn Any>,
 774        window: &mut Window,
 775        cx: &mut Context<Self>,
 776    ) -> bool {
 777        self.editor
 778            .update(cx, |editor, cx| editor.navigate(data, window, cx))
 779    }
 780
 781    fn tab_tooltip_text(&self, _: &App) -> Option<SharedString> {
 782        Some("Project Diagnostics".into())
 783    }
 784
 785    fn tab_content(&self, params: TabContentParams, _window: &Window, _: &App) -> AnyElement {
 786        h_flex()
 787            .gap_1()
 788            .when(
 789                self.summary.error_count == 0 && self.summary.warning_count == 0,
 790                |then| {
 791                    then.child(
 792                        h_flex()
 793                            .gap_1()
 794                            .child(Icon::new(IconName::Check).color(Color::Success))
 795                            .child(Label::new("No problems").color(params.text_color())),
 796                    )
 797                },
 798            )
 799            .when(self.summary.error_count > 0, |then| {
 800                then.child(
 801                    h_flex()
 802                        .gap_1()
 803                        .child(Icon::new(IconName::XCircle).color(Color::Error))
 804                        .child(
 805                            Label::new(self.summary.error_count.to_string())
 806                                .color(params.text_color()),
 807                        ),
 808                )
 809            })
 810            .when(self.summary.warning_count > 0, |then| {
 811                then.child(
 812                    h_flex()
 813                        .gap_1()
 814                        .child(Icon::new(IconName::Warning).color(Color::Warning))
 815                        .child(
 816                            Label::new(self.summary.warning_count.to_string())
 817                                .color(params.text_color()),
 818                        ),
 819                )
 820            })
 821            .into_any_element()
 822    }
 823
 824    fn telemetry_event_text(&self) -> Option<&'static str> {
 825        Some("Project Diagnostics Opened")
 826    }
 827
 828    fn for_each_project_item(
 829        &self,
 830        cx: &App,
 831        f: &mut dyn FnMut(gpui::EntityId, &dyn project::ProjectItem),
 832    ) {
 833        self.editor.for_each_project_item(cx, f)
 834    }
 835
 836    fn is_singleton(&self, _: &App) -> bool {
 837        false
 838    }
 839
 840    fn set_nav_history(
 841        &mut self,
 842        nav_history: ItemNavHistory,
 843        _: &mut Window,
 844        cx: &mut Context<Self>,
 845    ) {
 846        self.editor.update(cx, |editor, _| {
 847            editor.set_nav_history(Some(nav_history));
 848        });
 849    }
 850
 851    fn clone_on_split(
 852        &self,
 853        _workspace_id: Option<workspace::WorkspaceId>,
 854        window: &mut Window,
 855        cx: &mut Context<Self>,
 856    ) -> Option<Entity<Self>>
 857    where
 858        Self: Sized,
 859    {
 860        Some(cx.new(|cx| {
 861            ProjectDiagnosticsEditor::new(
 862                self.project.clone(),
 863                self.include_warnings,
 864                self.workspace.clone(),
 865                window,
 866                cx,
 867            )
 868        }))
 869    }
 870
 871    fn is_dirty(&self, cx: &App) -> bool {
 872        self.excerpts.read(cx).is_dirty(cx)
 873    }
 874
 875    fn has_deleted_file(&self, cx: &App) -> bool {
 876        self.excerpts.read(cx).has_deleted_file(cx)
 877    }
 878
 879    fn has_conflict(&self, cx: &App) -> bool {
 880        self.excerpts.read(cx).has_conflict(cx)
 881    }
 882
 883    fn can_save(&self, _: &App) -> bool {
 884        true
 885    }
 886
 887    fn save(
 888        &mut self,
 889        format: bool,
 890        project: Entity<Project>,
 891        window: &mut Window,
 892        cx: &mut Context<Self>,
 893    ) -> Task<Result<()>> {
 894        self.editor.save(format, project, window, cx)
 895    }
 896
 897    fn save_as(
 898        &mut self,
 899        _: Entity<Project>,
 900        _: ProjectPath,
 901        _window: &mut Window,
 902        _: &mut Context<Self>,
 903    ) -> Task<Result<()>> {
 904        unreachable!()
 905    }
 906
 907    fn reload(
 908        &mut self,
 909        project: Entity<Project>,
 910        window: &mut Window,
 911        cx: &mut Context<Self>,
 912    ) -> Task<Result<()>> {
 913        self.editor.reload(project, window, cx)
 914    }
 915
 916    fn act_as_type<'a>(
 917        &'a self,
 918        type_id: TypeId,
 919        self_handle: &'a Entity<Self>,
 920        _: &'a App,
 921    ) -> Option<AnyView> {
 922        if type_id == TypeId::of::<Self>() {
 923            Some(self_handle.to_any())
 924        } else if type_id == TypeId::of::<Editor>() {
 925            Some(self.editor.to_any())
 926        } else {
 927            None
 928        }
 929    }
 930
 931    fn as_searchable(&self, _: &Entity<Self>) -> Option<Box<dyn SearchableItemHandle>> {
 932        Some(Box::new(self.editor.clone()))
 933    }
 934
 935    fn breadcrumb_location(&self, _: &App) -> ToolbarItemLocation {
 936        ToolbarItemLocation::PrimaryLeft
 937    }
 938
 939    fn breadcrumbs(&self, theme: &theme::Theme, cx: &App) -> Option<Vec<BreadcrumbText>> {
 940        self.editor.breadcrumbs(theme, cx)
 941    }
 942
 943    fn added_to_workspace(
 944        &mut self,
 945        workspace: &mut Workspace,
 946        window: &mut Window,
 947        cx: &mut Context<Self>,
 948    ) {
 949        self.editor.update(cx, |editor, cx| {
 950            editor.added_to_workspace(workspace, window, cx)
 951        });
 952    }
 953}
 954
 955const DIAGNOSTIC_HEADER: &str = "diagnostic header";
 956
 957fn diagnostic_header_renderer(diagnostic: Diagnostic) -> RenderBlock {
 958    let (message, code_ranges) = highlight_diagnostic_message(&diagnostic, None);
 959    let message: SharedString = message;
 960    Arc::new(move |cx| {
 961        let color = cx.theme().colors();
 962        let highlight_style: HighlightStyle = color.text_accent.into();
 963
 964        h_flex()
 965            .id(DIAGNOSTIC_HEADER)
 966            .block_mouse_down()
 967            .h(2. * cx.window.line_height())
 968            .w_full()
 969            .px_9()
 970            .justify_between()
 971            .gap_2()
 972            .child(
 973                h_flex()
 974                    .gap_2()
 975                    .px_1()
 976                    .rounded_sm()
 977                    .bg(color.surface_background.opacity(0.5))
 978                    .map(|stack| {
 979                        stack.child(
 980                            svg()
 981                                .size(cx.window.text_style().font_size)
 982                                .flex_none()
 983                                .map(|icon| {
 984                                    if diagnostic.severity == DiagnosticSeverity::ERROR {
 985                                        icon.path(IconName::XCircle.path())
 986                                            .text_color(Color::Error.color(cx))
 987                                    } else {
 988                                        icon.path(IconName::Warning.path())
 989                                            .text_color(Color::Warning.color(cx))
 990                                    }
 991                                }),
 992                        )
 993                    })
 994                    .child(
 995                        h_flex()
 996                            .gap_1()
 997                            .child(
 998                                StyledText::new(message.clone()).with_default_highlights(
 999                                    &cx.window.text_style(),
1000                                    code_ranges
1001                                        .iter()
1002                                        .map(|range| (range.clone(), highlight_style)),
1003                                ),
1004                            )
1005                            .when_some(diagnostic.code.as_ref(), |stack, code| {
1006                                stack.child(
1007                                    div()
1008                                        .child(SharedString::from(format!("({code:?})")))
1009                                        .text_color(color.text_muted),
1010                                )
1011                            }),
1012                    ),
1013            )
1014            .when_some(diagnostic.source.as_ref(), |stack, source| {
1015                stack.child(
1016                    div()
1017                        .child(SharedString::from(source.clone()))
1018                        .text_color(color.text_muted),
1019                )
1020            })
1021            .into_any_element()
1022    })
1023}
1024
1025fn compare_diagnostics(
1026    old: &DiagnosticEntry<language::Anchor>,
1027    new: &DiagnosticEntry<language::Anchor>,
1028    snapshot: &language::BufferSnapshot,
1029) -> Ordering {
1030    use language::ToOffset;
1031
1032    // The diagnostics may point to a previously open Buffer for this file.
1033    if !old.range.start.is_valid(snapshot) || !new.range.start.is_valid(snapshot) {
1034        return Ordering::Greater;
1035    }
1036
1037    old.range
1038        .start
1039        .to_offset(snapshot)
1040        .cmp(&new.range.start.to_offset(snapshot))
1041        .then_with(|| {
1042            old.range
1043                .end
1044                .to_offset(snapshot)
1045                .cmp(&new.range.end.to_offset(snapshot))
1046        })
1047        .then_with(|| old.diagnostic.message.cmp(&new.diagnostic.message))
1048}
1049
1050const DIAGNOSTIC_EXPANSION_ROW_LIMIT: u32 = 32;
1051
1052fn context_range_for_entry(
1053    range: Range<Point>,
1054    context: u32,
1055    snapshot: BufferSnapshot,
1056    cx: AsyncApp,
1057) -> Task<Range<Point>> {
1058    cx.spawn(move |cx| async move {
1059        if let Some(rows) = heuristic_syntactic_expand(
1060            range.clone(),
1061            DIAGNOSTIC_EXPANSION_ROW_LIMIT,
1062            snapshot.clone(),
1063            cx,
1064        )
1065        .await
1066        {
1067            return Range {
1068                start: Point::new(*rows.start(), 0),
1069                end: snapshot.clip_point(Point::new(*rows.end(), u32::MAX), Bias::Left),
1070            };
1071        }
1072        Range {
1073            start: Point::new(range.start.row.saturating_sub(context), 0),
1074            end: snapshot.clip_point(Point::new(range.end.row + context, u32::MAX), Bias::Left),
1075        }
1076    })
1077}
1078
1079/// Expands the input range using syntax information from TreeSitter. This expansion will be limited
1080/// to the specified `max_row_count`.
1081///
1082/// If there is a containing outline item that is less than `max_row_count`, it will be returned.
1083/// Otherwise fairly arbitrary heuristics are applied to attempt to return a logical block of code.
1084async fn heuristic_syntactic_expand(
1085    input_range: Range<Point>,
1086    max_row_count: u32,
1087    snapshot: BufferSnapshot,
1088    cx: AsyncApp,
1089) -> Option<RangeInclusive<BufferRow>> {
1090    let input_row_count = input_range.end.row - input_range.start.row;
1091    if input_row_count > max_row_count {
1092        return None;
1093    }
1094
1095    // If the outline node contains the diagnostic and is small enough, just use that.
1096    let outline_range = snapshot.outline_range_containing(input_range.clone());
1097    if let Some(outline_range) = outline_range.clone() {
1098        // Remove blank lines from start and end
1099        if let Some(start_row) = (outline_range.start.row..outline_range.end.row)
1100            .find(|row| !snapshot.line_indent_for_row(*row).is_line_blank())
1101        {
1102            if let Some(end_row) = (outline_range.start.row..outline_range.end.row + 1)
1103                .rev()
1104                .find(|row| !snapshot.line_indent_for_row(*row).is_line_blank())
1105            {
1106                let row_count = end_row.saturating_sub(start_row);
1107                if row_count <= max_row_count {
1108                    return Some(RangeInclusive::new(
1109                        outline_range.start.row,
1110                        outline_range.end.row,
1111                    ));
1112                }
1113            }
1114        }
1115    }
1116
1117    let mut node = snapshot.syntax_ancestor(input_range.clone())?;
1118
1119    loop {
1120        let node_start = Point::from_ts_point(node.start_position());
1121        let node_end = Point::from_ts_point(node.end_position());
1122        let node_range = node_start..node_end;
1123        let row_count = node_end.row - node_start.row + 1;
1124        let mut ancestor_range = None;
1125        let reached_outline_node = cx.background_executor().scoped({
1126                 let node_range = node_range.clone();
1127                 let outline_range = outline_range.clone();
1128                 let ancestor_range =  &mut ancestor_range;
1129                |scope| {scope.spawn(async move {
1130                    // Stop if we've exceeded the row count or reached an outline node. Then, find the interval
1131                    // of node children which contains the query range. For example, this allows just returning
1132                    // the header of a declaration rather than the entire declaration.
1133                    if row_count > max_row_count || outline_range == Some(node_range.clone()) {
1134                        let mut cursor = node.walk();
1135                        let mut included_child_start = None;
1136                        let mut included_child_end = None;
1137                        let mut previous_end = node_start;
1138                        if cursor.goto_first_child() {
1139                            loop {
1140                                let child_node = cursor.node();
1141                                let child_range = previous_end..Point::from_ts_point(child_node.end_position());
1142                                if included_child_start.is_none() && child_range.contains(&input_range.start) {
1143                                    included_child_start = Some(child_range.start);
1144                                }
1145                                if child_range.contains(&input_range.end) {
1146                                    included_child_end = Some(child_range.end);
1147                                }
1148                                previous_end = child_range.end;
1149                                if !cursor.goto_next_sibling() {
1150                                    break;
1151                                }
1152                            }
1153                        }
1154                        let end = included_child_end.unwrap_or(node_range.end);
1155                        if let Some(start) = included_child_start {
1156                            let row_count = end.row - start.row;
1157                            if row_count < max_row_count {
1158                                *ancestor_range = Some(Some(RangeInclusive::new(start.row, end.row)));
1159                                return;
1160                            }
1161                        }
1162
1163                        log::info!(
1164                            "Expanding to ancestor started on {} node exceeding row limit of {max_row_count}.",
1165                            node.grammar_name()
1166                        );
1167                        *ancestor_range = Some(None);
1168                    }
1169                })
1170            }});
1171        reached_outline_node.await;
1172        if let Some(node) = ancestor_range {
1173            return node;
1174        }
1175
1176        let node_name = node.grammar_name();
1177        let node_row_range = RangeInclusive::new(node_range.start.row, node_range.end.row);
1178        if node_name.ends_with("block") {
1179            return Some(node_row_range);
1180        } else if node_name.ends_with("statement") || node_name.ends_with("declaration") {
1181            // Expand to the nearest dedent or blank line for statements and declarations.
1182            let tab_size = cx
1183                .update(|cx| snapshot.settings_at(node_range.start, cx).tab_size.get())
1184                .ok()?;
1185            let indent_level = snapshot
1186                .line_indent_for_row(node_range.start.row)
1187                .len(tab_size);
1188            let rows_remaining = max_row_count.saturating_sub(row_count);
1189            let Some(start_row) = (node_range.start.row.saturating_sub(rows_remaining)
1190                ..node_range.start.row)
1191                .rev()
1192                .find(|row| {
1193                    is_line_blank_or_indented_less(indent_level, *row, tab_size, &snapshot.clone())
1194                })
1195            else {
1196                return Some(node_row_range);
1197            };
1198            let rows_remaining = max_row_count.saturating_sub(node_range.end.row - start_row);
1199            let Some(end_row) = (node_range.end.row + 1
1200                ..cmp::min(
1201                    node_range.end.row + rows_remaining + 1,
1202                    snapshot.row_count(),
1203                ))
1204                .find(|row| {
1205                    is_line_blank_or_indented_less(indent_level, *row, tab_size, &snapshot.clone())
1206                })
1207            else {
1208                return Some(node_row_range);
1209            };
1210            return Some(RangeInclusive::new(start_row, end_row));
1211        }
1212
1213        // TODO: doing this instead of walking a cursor as that doesn't work - why?
1214        let Some(parent) = node.parent() else {
1215            log::info!(
1216                "Expanding to ancestor reached the top node, so using default context line count.",
1217            );
1218            return None;
1219        };
1220        node = parent;
1221    }
1222}
1223
1224fn is_line_blank_or_indented_less(
1225    indent_level: u32,
1226    row: u32,
1227    tab_size: u32,
1228    snapshot: &BufferSnapshot,
1229) -> bool {
1230    let line_indent = snapshot.line_indent_for_row(row);
1231    line_indent.is_line_blank() || line_indent.len(tab_size) < indent_level
1232}