1pub mod items;
2mod project_diagnostics_settings;
3mod toolbar_controls;
4
5#[cfg(test)]
6mod diagnostics_tests;
7
8use anyhow::Result;
9use collections::{BTreeSet, HashSet};
10use editor::{
11 diagnostic_block_renderer,
12 display_map::{BlockPlacement, BlockProperties, BlockStyle, CustomBlockId, RenderBlock},
13 highlight_diagnostic_message,
14 scroll::Autoscroll,
15 Editor, EditorEvent, ExcerptId, ExcerptRange, MultiBuffer, ToOffset,
16};
17use gpui::{
18 actions, div, svg, AnyElement, AnyView, AppContext, Context, EventEmitter, FocusHandle,
19 FocusableView, Global, HighlightStyle, InteractiveElement, IntoElement, Model, ParentElement,
20 Render, SharedString, Styled, StyledText, Subscription, Task, View, ViewContext, VisualContext,
21 WeakView, WindowContext,
22};
23use language::{
24 Bias, Buffer, Diagnostic, DiagnosticEntry, DiagnosticSeverity, Point, Selection, SelectionGoal,
25};
26use lsp::LanguageServerId;
27use project::{DiagnosticSummary, Project, ProjectPath};
28use project_diagnostics_settings::ProjectDiagnosticsSettings;
29use settings::Settings;
30use std::{
31 any::{Any, TypeId},
32 cmp::Ordering,
33 mem,
34 ops::Range,
35 sync::Arc,
36 time::Duration,
37};
38use theme::ActiveTheme;
39pub use toolbar_controls::ToolbarControls;
40use ui::{h_flex, prelude::*, Icon, IconName, Label};
41use util::ResultExt;
42use workspace::{
43 item::{BreadcrumbText, Item, ItemEvent, ItemHandle, TabContentParams},
44 ItemNavHistory, ToolbarItemLocation, Workspace,
45};
46
47actions!(diagnostics, [Deploy, ToggleWarnings]);
48
49struct IncludeWarnings(bool);
50impl Global for IncludeWarnings {}
51
52pub fn init(cx: &mut AppContext) {
53 ProjectDiagnosticsSettings::register(cx);
54 cx.observe_new_views(ProjectDiagnosticsEditor::register)
55 .detach();
56}
57
58struct ProjectDiagnosticsEditor {
59 project: Model<Project>,
60 workspace: WeakView<Workspace>,
61 focus_handle: FocusHandle,
62 editor: View<Editor>,
63 summary: DiagnosticSummary,
64 excerpts: Model<MultiBuffer>,
65 path_states: Vec<PathState>,
66 paths_to_update: BTreeSet<(ProjectPath, Option<LanguageServerId>)>,
67 include_warnings: bool,
68 context: u32,
69 update_excerpts_task: Option<Task<Result<()>>>,
70 _subscription: Subscription,
71}
72
73struct PathState {
74 path: ProjectPath,
75 diagnostic_groups: Vec<DiagnosticGroupState>,
76}
77
78struct DiagnosticGroupState {
79 language_server_id: LanguageServerId,
80 primary_diagnostic: DiagnosticEntry<language::Anchor>,
81 primary_excerpt_ix: usize,
82 excerpts: Vec<ExcerptId>,
83 blocks: HashSet<CustomBlockId>,
84 block_count: usize,
85}
86
87impl EventEmitter<EditorEvent> for ProjectDiagnosticsEditor {}
88
89const DIAGNOSTICS_UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
90
91impl Render for ProjectDiagnosticsEditor {
92 fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
93 let child = if self.path_states.is_empty() {
94 div()
95 .bg(cx.theme().colors().editor_background)
96 .flex()
97 .items_center()
98 .justify_center()
99 .size_full()
100 .child(Label::new("No problems in workspace"))
101 } else {
102 div().size_full().child(self.editor.clone())
103 };
104
105 div()
106 .track_focus(&self.focus_handle(cx))
107 .when(self.path_states.is_empty(), |el| {
108 el.key_context("EmptyPane")
109 })
110 .size_full()
111 .on_action(cx.listener(Self::toggle_warnings))
112 .child(child)
113 }
114}
115
116impl ProjectDiagnosticsEditor {
117 fn register(workspace: &mut Workspace, _: &mut ViewContext<Workspace>) {
118 workspace.register_action(Self::deploy);
119 }
120
121 fn new_with_context(
122 context: u32,
123 include_warnings: bool,
124 project_handle: Model<Project>,
125 workspace: WeakView<Workspace>,
126 cx: &mut ViewContext<Self>,
127 ) -> Self {
128 let project_event_subscription =
129 cx.subscribe(&project_handle, |this, project, event, cx| match event {
130 project::Event::DiskBasedDiagnosticsStarted { .. } => {
131 cx.notify();
132 }
133 project::Event::DiskBasedDiagnosticsFinished { language_server_id } => {
134 log::debug!("disk based diagnostics finished for server {language_server_id}");
135 this.update_stale_excerpts(cx);
136 }
137 project::Event::DiagnosticsUpdated {
138 language_server_id,
139 path,
140 } => {
141 this.paths_to_update
142 .insert((path.clone(), Some(*language_server_id)));
143 this.summary = project.read(cx).diagnostic_summary(false, cx);
144 cx.emit(EditorEvent::TitleChanged);
145
146 if this.editor.focus_handle(cx).contains_focused(cx) || this.focus_handle.contains_focused(cx) {
147 log::debug!("diagnostics updated for server {language_server_id}, path {path:?}. recording change");
148 } else {
149 log::debug!("diagnostics updated for server {language_server_id}, path {path:?}. updating excerpts");
150 this.update_stale_excerpts(cx);
151 }
152 }
153 _ => {}
154 });
155
156 let focus_handle = cx.focus_handle();
157 cx.on_focus_in(&focus_handle, |this, cx| this.focus_in(cx))
158 .detach();
159 cx.on_focus_out(&focus_handle, |this, _event, cx| this.focus_out(cx))
160 .detach();
161
162 let excerpts = cx.new_model(|cx| MultiBuffer::new(project_handle.read(cx).capability()));
163 let editor = cx.new_view(|cx| {
164 let mut editor =
165 Editor::for_multibuffer(excerpts.clone(), Some(project_handle.clone()), false, cx);
166 editor.set_vertical_scroll_margin(5, cx);
167 editor
168 });
169 cx.subscribe(&editor, |this, _editor, event: &EditorEvent, cx| {
170 cx.emit(event.clone());
171 match event {
172 EditorEvent::Focused => {
173 if this.path_states.is_empty() {
174 cx.focus(&this.focus_handle);
175 }
176 }
177 EditorEvent::Blurred => this.update_stale_excerpts(cx),
178 _ => {}
179 }
180 })
181 .detach();
182 cx.observe_global::<IncludeWarnings>(|this, cx| {
183 this.include_warnings = cx.global::<IncludeWarnings>().0;
184 this.update_all_excerpts(cx);
185 })
186 .detach();
187
188 let project = project_handle.read(cx);
189 let mut this = Self {
190 project: project_handle.clone(),
191 context,
192 summary: project.diagnostic_summary(false, cx),
193 include_warnings,
194 workspace,
195 excerpts,
196 focus_handle,
197 editor,
198 path_states: Default::default(),
199 paths_to_update: Default::default(),
200 update_excerpts_task: None,
201 _subscription: project_event_subscription,
202 };
203 this.update_all_excerpts(cx);
204 this
205 }
206
207 fn update_stale_excerpts(&mut self, cx: &mut ViewContext<Self>) {
208 if self.update_excerpts_task.is_some() {
209 return;
210 }
211 let project_handle = self.project.clone();
212 self.update_excerpts_task = Some(cx.spawn(|this, mut cx| async move {
213 cx.background_executor()
214 .timer(DIAGNOSTICS_UPDATE_DEBOUNCE)
215 .await;
216 loop {
217 let Some((path, language_server_id)) = this.update(&mut cx, |this, _| {
218 let Some((path, language_server_id)) = this.paths_to_update.pop_first() else {
219 this.update_excerpts_task.take();
220 return None;
221 };
222 Some((path, language_server_id))
223 })?
224 else {
225 break;
226 };
227
228 if let Some(buffer) = project_handle
229 .update(&mut cx, |project, cx| project.open_buffer(path.clone(), cx))?
230 .await
231 .log_err()
232 {
233 this.update(&mut cx, |this, cx| {
234 this.update_excerpts(path, language_server_id, buffer, cx);
235 })?;
236 }
237 }
238 Ok(())
239 }));
240 }
241
242 fn new(
243 project_handle: Model<Project>,
244 include_warnings: bool,
245 workspace: WeakView<Workspace>,
246 cx: &mut ViewContext<Self>,
247 ) -> Self {
248 Self::new_with_context(
249 editor::DEFAULT_MULTIBUFFER_CONTEXT,
250 include_warnings,
251 project_handle,
252 workspace,
253 cx,
254 )
255 }
256
257 fn deploy(workspace: &mut Workspace, _: &Deploy, cx: &mut ViewContext<Workspace>) {
258 if let Some(existing) = workspace.item_of_type::<ProjectDiagnosticsEditor>(cx) {
259 workspace.activate_item(&existing, true, true, cx);
260 } else {
261 let workspace_handle = cx.view().downgrade();
262
263 let include_warnings = match cx.try_global::<IncludeWarnings>() {
264 Some(include_warnings) => include_warnings.0,
265 None => ProjectDiagnosticsSettings::get_global(cx).include_warnings,
266 };
267
268 let diagnostics = cx.new_view(|cx| {
269 ProjectDiagnosticsEditor::new(
270 workspace.project().clone(),
271 include_warnings,
272 workspace_handle,
273 cx,
274 )
275 });
276 workspace.add_item_to_active_pane(Box::new(diagnostics), None, true, cx);
277 }
278 }
279
280 fn toggle_warnings(&mut self, _: &ToggleWarnings, cx: &mut ViewContext<Self>) {
281 self.include_warnings = !self.include_warnings;
282 cx.set_global(IncludeWarnings(self.include_warnings));
283 self.update_all_excerpts(cx);
284 cx.notify();
285 }
286
287 fn focus_in(&mut self, cx: &mut ViewContext<Self>) {
288 if self.focus_handle.is_focused(cx) && !self.path_states.is_empty() {
289 self.editor.focus_handle(cx).focus(cx)
290 }
291 }
292
293 fn focus_out(&mut self, cx: &mut ViewContext<Self>) {
294 if !self.focus_handle.is_focused(cx) && !self.editor.focus_handle(cx).is_focused(cx) {
295 self.update_stale_excerpts(cx);
296 }
297 }
298
299 /// Enqueue an update of all excerpts. Updates all paths that either
300 /// currently have diagnostics or are currently present in this view.
301 fn update_all_excerpts(&mut self, cx: &mut ViewContext<Self>) {
302 self.project.update(cx, |project, cx| {
303 let mut paths = project
304 .diagnostic_summaries(false, cx)
305 .map(|(path, _, _)| (path, None))
306 .collect::<BTreeSet<_>>();
307 paths.extend(
308 self.path_states
309 .iter()
310 .map(|state| (state.path.clone(), None)),
311 );
312 let paths_to_update = std::mem::take(&mut self.paths_to_update);
313 paths.extend(paths_to_update.into_iter().map(|(path, _)| (path, None)));
314 self.paths_to_update = paths;
315 });
316 self.update_stale_excerpts(cx);
317 }
318
319 fn update_excerpts(
320 &mut self,
321 path_to_update: ProjectPath,
322 server_to_update: Option<LanguageServerId>,
323 buffer: Model<Buffer>,
324 cx: &mut ViewContext<Self>,
325 ) {
326 let was_empty = self.path_states.is_empty();
327 let snapshot = buffer.read(cx).snapshot();
328 let path_ix = match self
329 .path_states
330 .binary_search_by_key(&&path_to_update, |e| &e.path)
331 {
332 Ok(ix) => ix,
333 Err(ix) => {
334 self.path_states.insert(
335 ix,
336 PathState {
337 path: path_to_update.clone(),
338 diagnostic_groups: Default::default(),
339 },
340 );
341 ix
342 }
343 };
344
345 let mut prev_excerpt_id = if path_ix > 0 {
346 let prev_path_last_group = &self.path_states[path_ix - 1]
347 .diagnostic_groups
348 .last()
349 .unwrap();
350 *prev_path_last_group.excerpts.last().unwrap()
351 } else {
352 ExcerptId::min()
353 };
354
355 let path_state = &mut self.path_states[path_ix];
356 let mut new_group_ixs = Vec::new();
357 let mut blocks_to_add = Vec::new();
358 let mut blocks_to_remove = HashSet::default();
359 let mut first_excerpt_id = None;
360 let max_severity = if self.include_warnings {
361 DiagnosticSeverity::WARNING
362 } else {
363 DiagnosticSeverity::ERROR
364 };
365 let excerpts_snapshot = self.excerpts.update(cx, |excerpts, cx| {
366 let mut old_groups = mem::take(&mut path_state.diagnostic_groups)
367 .into_iter()
368 .enumerate()
369 .peekable();
370 let mut new_groups = snapshot
371 .diagnostic_groups(server_to_update)
372 .into_iter()
373 .filter(|(_, group)| {
374 group.entries[group.primary_ix].diagnostic.severity <= max_severity
375 })
376 .peekable();
377 loop {
378 let mut to_insert = None;
379 let mut to_remove = None;
380 let mut to_keep = None;
381 match (old_groups.peek(), new_groups.peek()) {
382 (None, None) => break,
383 (None, Some(_)) => to_insert = new_groups.next(),
384 (Some((_, old_group)), None) => {
385 if server_to_update.map_or(true, |id| id == old_group.language_server_id) {
386 to_remove = old_groups.next();
387 } else {
388 to_keep = old_groups.next();
389 }
390 }
391 (Some((_, old_group)), Some((new_language_server_id, new_group))) => {
392 let old_primary = &old_group.primary_diagnostic;
393 let new_primary = &new_group.entries[new_group.primary_ix];
394 match compare_diagnostics(old_primary, new_primary, &snapshot)
395 .then_with(|| old_group.language_server_id.cmp(new_language_server_id))
396 {
397 Ordering::Less => {
398 if server_to_update
399 .map_or(true, |id| id == old_group.language_server_id)
400 {
401 to_remove = old_groups.next();
402 } else {
403 to_keep = old_groups.next();
404 }
405 }
406 Ordering::Equal => {
407 to_keep = old_groups.next();
408 new_groups.next();
409 }
410 Ordering::Greater => to_insert = new_groups.next(),
411 }
412 }
413 }
414
415 if let Some((language_server_id, group)) = to_insert {
416 let mut group_state = DiagnosticGroupState {
417 language_server_id,
418 primary_diagnostic: group.entries[group.primary_ix].clone(),
419 primary_excerpt_ix: 0,
420 excerpts: Default::default(),
421 blocks: Default::default(),
422 block_count: 0,
423 };
424 let mut pending_range: Option<(Range<Point>, usize)> = None;
425 let mut is_first_excerpt_for_group = true;
426 for (ix, entry) in group.entries.iter().map(Some).chain([None]).enumerate() {
427 let resolved_entry = entry.map(|e| e.resolve::<Point>(&snapshot));
428 if let Some((range, start_ix)) = &mut pending_range {
429 if let Some(entry) = resolved_entry.as_ref() {
430 if entry.range.start.row <= range.end.row + 1 + self.context * 2 {
431 range.end = range.end.max(entry.range.end);
432 continue;
433 }
434 }
435
436 let excerpt_start =
437 Point::new(range.start.row.saturating_sub(self.context), 0);
438 let excerpt_end = snapshot.clip_point(
439 Point::new(range.end.row + self.context, u32::MAX),
440 Bias::Left,
441 );
442
443 let excerpt_id = excerpts
444 .insert_excerpts_after(
445 prev_excerpt_id,
446 buffer.clone(),
447 [ExcerptRange {
448 context: excerpt_start..excerpt_end,
449 primary: Some(range.clone()),
450 }],
451 cx,
452 )
453 .pop()
454 .unwrap();
455
456 prev_excerpt_id = excerpt_id;
457 first_excerpt_id.get_or_insert(prev_excerpt_id);
458 group_state.excerpts.push(excerpt_id);
459 let header_position = (excerpt_id, language::Anchor::MIN);
460
461 if is_first_excerpt_for_group {
462 is_first_excerpt_for_group = false;
463 let mut primary =
464 group.entries[group.primary_ix].diagnostic.clone();
465 primary.message =
466 primary.message.split('\n').next().unwrap().to_string();
467 group_state.block_count += 1;
468 blocks_to_add.push(BlockProperties {
469 placement: BlockPlacement::Above(header_position),
470 height: 2,
471 style: BlockStyle::Sticky,
472 render: diagnostic_header_renderer(primary),
473 priority: 0,
474 });
475 }
476
477 for entry in &group.entries[*start_ix..ix] {
478 let mut diagnostic = entry.diagnostic.clone();
479 if diagnostic.is_primary {
480 group_state.primary_excerpt_ix = group_state.excerpts.len() - 1;
481 diagnostic.message =
482 entry.diagnostic.message.split('\n').skip(1).collect();
483 }
484
485 if !diagnostic.message.is_empty() {
486 group_state.block_count += 1;
487 blocks_to_add.push(BlockProperties {
488 placement: BlockPlacement::Below((
489 excerpt_id,
490 entry.range.start,
491 )),
492 height: diagnostic.message.matches('\n').count() as u32 + 1,
493 style: BlockStyle::Fixed,
494 render: diagnostic_block_renderer(
495 diagnostic, None, true, true,
496 ),
497 priority: 0,
498 });
499 }
500 }
501
502 pending_range.take();
503 }
504
505 if let Some(entry) = resolved_entry {
506 pending_range = Some((entry.range.clone(), ix));
507 }
508 }
509
510 new_group_ixs.push(path_state.diagnostic_groups.len());
511 path_state.diagnostic_groups.push(group_state);
512 } else if let Some((_, group_state)) = to_remove {
513 excerpts.remove_excerpts(group_state.excerpts.iter().copied(), cx);
514 blocks_to_remove.extend(group_state.blocks.iter().copied());
515 } else if let Some((_, group_state)) = to_keep {
516 prev_excerpt_id = *group_state.excerpts.last().unwrap();
517 first_excerpt_id.get_or_insert(prev_excerpt_id);
518 path_state.diagnostic_groups.push(group_state);
519 }
520 }
521
522 excerpts.snapshot(cx)
523 });
524
525 self.editor.update(cx, |editor, cx| {
526 editor.remove_blocks(blocks_to_remove, None, cx);
527 let block_ids = editor.insert_blocks(
528 blocks_to_add.into_iter().flat_map(|block| {
529 let placement = match block.placement {
530 BlockPlacement::Above((excerpt_id, text_anchor)) => BlockPlacement::Above(
531 excerpts_snapshot.anchor_in_excerpt(excerpt_id, text_anchor)?,
532 ),
533 BlockPlacement::Below((excerpt_id, text_anchor)) => BlockPlacement::Below(
534 excerpts_snapshot.anchor_in_excerpt(excerpt_id, text_anchor)?,
535 ),
536 BlockPlacement::Replace(_) => {
537 unreachable!(
538 "no Replace block should have been pushed to blocks_to_add"
539 )
540 }
541 };
542 Some(BlockProperties {
543 placement,
544 height: block.height,
545 style: block.style,
546 render: block.render,
547 priority: 0,
548 })
549 }),
550 Some(Autoscroll::fit()),
551 cx,
552 );
553
554 let mut block_ids = block_ids.into_iter();
555 for ix in new_group_ixs {
556 let group_state = &mut path_state.diagnostic_groups[ix];
557 group_state.blocks = block_ids.by_ref().take(group_state.block_count).collect();
558 }
559 });
560
561 if path_state.diagnostic_groups.is_empty() {
562 self.path_states.remove(path_ix);
563 }
564
565 self.editor.update(cx, |editor, cx| {
566 let groups;
567 let mut selections;
568 let new_excerpt_ids_by_selection_id;
569 if was_empty {
570 groups = self.path_states.first()?.diagnostic_groups.as_slice();
571 new_excerpt_ids_by_selection_id = [(0, ExcerptId::min())].into_iter().collect();
572 selections = vec![Selection {
573 id: 0,
574 start: 0,
575 end: 0,
576 reversed: false,
577 goal: SelectionGoal::None,
578 }];
579 } else {
580 groups = self.path_states.get(path_ix)?.diagnostic_groups.as_slice();
581 new_excerpt_ids_by_selection_id =
582 editor.change_selections(Some(Autoscroll::fit()), cx, |s| s.refresh());
583 selections = editor.selections.all::<usize>(cx);
584 }
585
586 // If any selection has lost its position, move it to start of the next primary diagnostic.
587 let snapshot = editor.snapshot(cx);
588 for selection in &mut selections {
589 if let Some(new_excerpt_id) = new_excerpt_ids_by_selection_id.get(&selection.id) {
590 let group_ix = match groups.binary_search_by(|probe| {
591 probe
592 .excerpts
593 .last()
594 .unwrap()
595 .cmp(new_excerpt_id, &snapshot.buffer_snapshot)
596 }) {
597 Ok(ix) | Err(ix) => ix,
598 };
599 if let Some(group) = groups.get(group_ix) {
600 if let Some(offset) = excerpts_snapshot
601 .anchor_in_excerpt(
602 group.excerpts[group.primary_excerpt_ix],
603 group.primary_diagnostic.range.start,
604 )
605 .map(|anchor| anchor.to_offset(&excerpts_snapshot))
606 {
607 selection.start = offset;
608 selection.end = offset;
609 }
610 }
611 }
612 }
613 editor.change_selections(None, cx, |s| {
614 s.select(selections);
615 });
616 Some(())
617 });
618
619 if self.path_states.is_empty() {
620 if self.editor.focus_handle(cx).is_focused(cx) {
621 cx.focus(&self.focus_handle);
622 }
623 } else if self.focus_handle.is_focused(cx) {
624 let focus_handle = self.editor.focus_handle(cx);
625 cx.focus(&focus_handle);
626 }
627
628 #[cfg(test)]
629 self.check_invariants(cx);
630
631 cx.notify();
632 }
633
634 #[cfg(test)]
635 fn check_invariants(&self, cx: &mut ViewContext<Self>) {
636 let mut excerpts = Vec::new();
637 for (id, buffer, _) in self.excerpts.read(cx).snapshot(cx).excerpts() {
638 if let Some(file) = buffer.file() {
639 excerpts.push((id, file.path().clone()));
640 }
641 }
642
643 let mut prev_path = None;
644 for (_, path) in &excerpts {
645 if let Some(prev_path) = prev_path {
646 if path < prev_path {
647 panic!("excerpts are not sorted by path {:?}", excerpts);
648 }
649 }
650 prev_path = Some(path);
651 }
652 }
653}
654
655impl FocusableView for ProjectDiagnosticsEditor {
656 fn focus_handle(&self, _: &AppContext) -> FocusHandle {
657 self.focus_handle.clone()
658 }
659}
660
661impl Item for ProjectDiagnosticsEditor {
662 type Event = EditorEvent;
663
664 fn to_item_events(event: &EditorEvent, f: impl FnMut(ItemEvent)) {
665 Editor::to_item_events(event, f)
666 }
667
668 fn deactivated(&mut self, cx: &mut ViewContext<Self>) {
669 self.editor.update(cx, |editor, cx| editor.deactivated(cx));
670 }
671
672 fn navigate(&mut self, data: Box<dyn Any>, cx: &mut ViewContext<Self>) -> bool {
673 self.editor
674 .update(cx, |editor, cx| editor.navigate(data, cx))
675 }
676
677 fn tab_tooltip_text(&self, _: &AppContext) -> Option<SharedString> {
678 Some("Project Diagnostics".into())
679 }
680
681 fn tab_content(&self, params: TabContentParams, _: &WindowContext) -> AnyElement {
682 h_flex()
683 .gap_1()
684 .when(
685 self.summary.error_count == 0 && self.summary.warning_count == 0,
686 |then| {
687 then.child(
688 h_flex()
689 .gap_1()
690 .child(Icon::new(IconName::Check).color(Color::Success))
691 .child(Label::new("No problems").color(params.text_color())),
692 )
693 },
694 )
695 .when(self.summary.error_count > 0, |then| {
696 then.child(
697 h_flex()
698 .gap_1()
699 .child(Icon::new(IconName::XCircle).color(Color::Error))
700 .child(
701 Label::new(self.summary.error_count.to_string())
702 .color(params.text_color()),
703 ),
704 )
705 })
706 .when(self.summary.warning_count > 0, |then| {
707 then.child(
708 h_flex()
709 .gap_1()
710 .child(Icon::new(IconName::Warning).color(Color::Warning))
711 .child(
712 Label::new(self.summary.warning_count.to_string())
713 .color(params.text_color()),
714 ),
715 )
716 })
717 .into_any_element()
718 }
719
720 fn telemetry_event_text(&self) -> Option<&'static str> {
721 Some("project diagnostics")
722 }
723
724 fn for_each_project_item(
725 &self,
726 cx: &AppContext,
727 f: &mut dyn FnMut(gpui::EntityId, &dyn project::ProjectItem),
728 ) {
729 self.editor.for_each_project_item(cx, f)
730 }
731
732 fn is_singleton(&self, _: &AppContext) -> bool {
733 false
734 }
735
736 fn set_nav_history(&mut self, nav_history: ItemNavHistory, cx: &mut ViewContext<Self>) {
737 self.editor.update(cx, |editor, _| {
738 editor.set_nav_history(Some(nav_history));
739 });
740 }
741
742 fn clone_on_split(
743 &self,
744 _workspace_id: Option<workspace::WorkspaceId>,
745 cx: &mut ViewContext<Self>,
746 ) -> Option<View<Self>>
747 where
748 Self: Sized,
749 {
750 Some(cx.new_view(|cx| {
751 ProjectDiagnosticsEditor::new(
752 self.project.clone(),
753 self.include_warnings,
754 self.workspace.clone(),
755 cx,
756 )
757 }))
758 }
759
760 fn is_dirty(&self, cx: &AppContext) -> bool {
761 self.excerpts.read(cx).is_dirty(cx)
762 }
763
764 fn has_deleted_file(&self, cx: &AppContext) -> bool {
765 self.excerpts.read(cx).has_deleted_file(cx)
766 }
767
768 fn has_conflict(&self, cx: &AppContext) -> bool {
769 self.excerpts.read(cx).has_conflict(cx)
770 }
771
772 fn can_save(&self, _: &AppContext) -> bool {
773 true
774 }
775
776 fn save(
777 &mut self,
778 format: bool,
779 project: Model<Project>,
780 cx: &mut ViewContext<Self>,
781 ) -> Task<Result<()>> {
782 self.editor.save(format, project, cx)
783 }
784
785 fn save_as(
786 &mut self,
787 _: Model<Project>,
788 _: ProjectPath,
789 _: &mut ViewContext<Self>,
790 ) -> Task<Result<()>> {
791 unreachable!()
792 }
793
794 fn reload(&mut self, project: Model<Project>, cx: &mut ViewContext<Self>) -> Task<Result<()>> {
795 self.editor.reload(project, cx)
796 }
797
798 fn act_as_type<'a>(
799 &'a self,
800 type_id: TypeId,
801 self_handle: &'a View<Self>,
802 _: &'a AppContext,
803 ) -> Option<AnyView> {
804 if type_id == TypeId::of::<Self>() {
805 Some(self_handle.to_any())
806 } else if type_id == TypeId::of::<Editor>() {
807 Some(self.editor.to_any())
808 } else {
809 None
810 }
811 }
812
813 fn breadcrumb_location(&self, _: &AppContext) -> ToolbarItemLocation {
814 ToolbarItemLocation::PrimaryLeft
815 }
816
817 fn breadcrumbs(&self, theme: &theme::Theme, cx: &AppContext) -> Option<Vec<BreadcrumbText>> {
818 self.editor.breadcrumbs(theme, cx)
819 }
820
821 fn added_to_workspace(&mut self, workspace: &mut Workspace, cx: &mut ViewContext<Self>) {
822 self.editor
823 .update(cx, |editor, cx| editor.added_to_workspace(workspace, cx));
824 }
825}
826
827const DIAGNOSTIC_HEADER: &str = "diagnostic header";
828
829fn diagnostic_header_renderer(diagnostic: Diagnostic) -> RenderBlock {
830 let (message, code_ranges) = highlight_diagnostic_message(&diagnostic, None);
831 let message: SharedString = message;
832 Arc::new(move |cx| {
833 let highlight_style: HighlightStyle = cx.theme().colors().text_accent.into();
834 h_flex()
835 .id(DIAGNOSTIC_HEADER)
836 .block_mouse_down()
837 .h(2. * cx.line_height())
838 .pl_10()
839 .pr_5()
840 .w_full()
841 .justify_between()
842 .gap_2()
843 .child(
844 h_flex()
845 .gap_3()
846 .map(|stack| {
847 stack.child(
848 svg()
849 .size(cx.text_style().font_size)
850 .flex_none()
851 .map(|icon| {
852 if diagnostic.severity == DiagnosticSeverity::ERROR {
853 icon.path(IconName::XCircle.path())
854 .text_color(Color::Error.color(cx))
855 } else {
856 icon.path(IconName::Warning.path())
857 .text_color(Color::Warning.color(cx))
858 }
859 }),
860 )
861 })
862 .child(
863 h_flex()
864 .gap_1()
865 .child(
866 StyledText::new(message.clone()).with_highlights(
867 &cx.text_style(),
868 code_ranges
869 .iter()
870 .map(|range| (range.clone(), highlight_style)),
871 ),
872 )
873 .when_some(diagnostic.code.as_ref(), |stack, code| {
874 stack.child(
875 div()
876 .child(SharedString::from(format!("({code})")))
877 .text_color(cx.theme().colors().text_muted),
878 )
879 }),
880 ),
881 )
882 .child(
883 h_flex()
884 .gap_1()
885 .when_some(diagnostic.source.as_ref(), |stack, source| {
886 stack.child(
887 div()
888 .child(SharedString::from(source.clone()))
889 .text_color(cx.theme().colors().text_muted),
890 )
891 }),
892 )
893 .into_any_element()
894 })
895}
896
897fn compare_diagnostics(
898 old: &DiagnosticEntry<language::Anchor>,
899 new: &DiagnosticEntry<language::Anchor>,
900 snapshot: &language::BufferSnapshot,
901) -> Ordering {
902 use language::ToOffset;
903
904 // The diagnostics may point to a previously open Buffer for this file.
905 if !old.range.start.is_valid(snapshot) || !new.range.start.is_valid(snapshot) {
906 return Ordering::Greater;
907 }
908
909 old.range
910 .start
911 .to_offset(snapshot)
912 .cmp(&new.range.start.to_offset(snapshot))
913 .then_with(|| {
914 old.range
915 .end
916 .to_offset(snapshot)
917 .cmp(&new.range.end.to_offset(snapshot))
918 })
919 .then_with(|| old.diagnostic.message.cmp(&new.diagnostic.message))
920}