Skip to repository content

tenant.openagents/omega

No repository description is available.

OpenAgents Git authority 2026-07-28T02:31:59.605Z Public web read
NIP-34 coordinate30617:7649603503856e5148d571eac2766b288a8ff1e9e35d380337a1d2b0015b4f92:omega
MaintainersHidden in public view
References2 branches · 1 tag
Read-only clonegit clone https://openagents.com/git/tenant.openagents/omega.git
Browse files

diagnostics.rs

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