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