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