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