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