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, BlockProperties, BlockStyle, CustomBlockId, 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, 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<CustomBlockId>,
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, true, true, 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, true, 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(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 priority: 0,
453 });
454 }
455
456 for entry in &group.entries[*start_ix..ix] {
457 let mut diagnostic = entry.diagnostic.clone();
458 if diagnostic.is_primary {
459 group_state.primary_excerpt_ix = group_state.excerpts.len() - 1;
460 diagnostic.message =
461 entry.diagnostic.message.split('\n').skip(1).collect();
462 }
463
464 if !diagnostic.message.is_empty() {
465 group_state.block_count += 1;
466 blocks_to_add.push(BlockProperties {
467 position: (excerpt_id, entry.range.start),
468 height: diagnostic.message.matches('\n').count() as u32 + 1,
469 style: BlockStyle::Fixed,
470 render: diagnostic_block_renderer(
471 diagnostic, None, true, true,
472 ),
473 disposition: BlockDisposition::Below,
474 priority: 0,
475 });
476 }
477 }
478
479 pending_range.take();
480 }
481
482 if let Some(entry) = resolved_entry {
483 pending_range = Some((entry.range.clone(), ix));
484 }
485 }
486
487 new_group_ixs.push(path_state.diagnostic_groups.len());
488 path_state.diagnostic_groups.push(group_state);
489 } else if let Some((_, group_state)) = to_remove {
490 excerpts.remove_excerpts(group_state.excerpts.iter().copied(), cx);
491 blocks_to_remove.extend(group_state.blocks.iter().copied());
492 } else if let Some((_, group_state)) = to_keep {
493 prev_excerpt_id = *group_state.excerpts.last().unwrap();
494 first_excerpt_id.get_or_insert(prev_excerpt_id);
495 path_state.diagnostic_groups.push(group_state);
496 }
497 }
498
499 excerpts.snapshot(cx)
500 });
501
502 self.editor.update(cx, |editor, cx| {
503 editor.remove_blocks(blocks_to_remove, None, cx);
504 let block_ids = editor.insert_blocks(
505 blocks_to_add.into_iter().flat_map(|block| {
506 let (excerpt_id, text_anchor) = block.position;
507 Some(BlockProperties {
508 position: excerpts_snapshot.anchor_in_excerpt(excerpt_id, text_anchor)?,
509 height: block.height,
510 style: block.style,
511 render: block.render,
512 disposition: block.disposition,
513 priority: 0,
514 })
515 }),
516 Some(Autoscroll::fit()),
517 cx,
518 );
519
520 let mut block_ids = block_ids.into_iter();
521 for ix in new_group_ixs {
522 let group_state = &mut path_state.diagnostic_groups[ix];
523 group_state.blocks = block_ids.by_ref().take(group_state.block_count).collect();
524 }
525 });
526
527 if path_state.diagnostic_groups.is_empty() {
528 self.path_states.remove(path_ix);
529 }
530
531 self.editor.update(cx, |editor, cx| {
532 let groups;
533 let mut selections;
534 let new_excerpt_ids_by_selection_id;
535 if was_empty {
536 groups = self.path_states.first()?.diagnostic_groups.as_slice();
537 new_excerpt_ids_by_selection_id = [(0, ExcerptId::min())].into_iter().collect();
538 selections = vec![Selection {
539 id: 0,
540 start: 0,
541 end: 0,
542 reversed: false,
543 goal: SelectionGoal::None,
544 }];
545 } else {
546 groups = self.path_states.get(path_ix)?.diagnostic_groups.as_slice();
547 new_excerpt_ids_by_selection_id =
548 editor.change_selections(Some(Autoscroll::fit()), cx, |s| s.refresh());
549 selections = editor.selections.all::<usize>(cx);
550 }
551
552 // If any selection has lost its position, move it to start of the next primary diagnostic.
553 let snapshot = editor.snapshot(cx);
554 for selection in &mut selections {
555 if let Some(new_excerpt_id) = new_excerpt_ids_by_selection_id.get(&selection.id) {
556 let group_ix = match groups.binary_search_by(|probe| {
557 probe
558 .excerpts
559 .last()
560 .unwrap()
561 .cmp(new_excerpt_id, &snapshot.buffer_snapshot)
562 }) {
563 Ok(ix) | Err(ix) => ix,
564 };
565 if let Some(group) = groups.get(group_ix) {
566 if let Some(offset) = excerpts_snapshot
567 .anchor_in_excerpt(
568 group.excerpts[group.primary_excerpt_ix],
569 group.primary_diagnostic.range.start,
570 )
571 .map(|anchor| anchor.to_offset(&excerpts_snapshot))
572 {
573 selection.start = offset;
574 selection.end = offset;
575 }
576 }
577 }
578 }
579 editor.change_selections(None, cx, |s| {
580 s.select(selections);
581 });
582 Some(())
583 });
584
585 if self.path_states.is_empty() {
586 if self.editor.focus_handle(cx).is_focused(cx) {
587 cx.focus(&self.focus_handle);
588 }
589 } else if self.focus_handle.is_focused(cx) {
590 let focus_handle = self.editor.focus_handle(cx);
591 cx.focus(&focus_handle);
592 }
593
594 #[cfg(test)]
595 self.check_invariants(cx);
596
597 cx.notify();
598 }
599
600 #[cfg(test)]
601 fn check_invariants(&self, cx: &mut ViewContext<Self>) {
602 let mut excerpts = Vec::new();
603 for (id, buffer, _) in self.excerpts.read(cx).snapshot(cx).excerpts() {
604 if let Some(file) = buffer.file() {
605 excerpts.push((id, file.path().clone()));
606 }
607 }
608
609 let mut prev_path = None;
610 for (_, path) in &excerpts {
611 if let Some(prev_path) = prev_path {
612 if path < prev_path {
613 panic!("excerpts are not sorted by path {:?}", excerpts);
614 }
615 }
616 prev_path = Some(path);
617 }
618 }
619}
620
621impl FocusableView for ProjectDiagnosticsEditor {
622 fn focus_handle(&self, _: &AppContext) -> FocusHandle {
623 self.focus_handle.clone()
624 }
625}
626
627impl Item for ProjectDiagnosticsEditor {
628 type Event = EditorEvent;
629
630 fn to_item_events(event: &EditorEvent, f: impl FnMut(ItemEvent)) {
631 Editor::to_item_events(event, f)
632 }
633
634 fn deactivated(&mut self, cx: &mut ViewContext<Self>) {
635 self.editor.update(cx, |editor, cx| editor.deactivated(cx));
636 }
637
638 fn navigate(&mut self, data: Box<dyn Any>, cx: &mut ViewContext<Self>) -> bool {
639 self.editor
640 .update(cx, |editor, cx| editor.navigate(data, cx))
641 }
642
643 fn tab_tooltip_text(&self, _: &AppContext) -> Option<SharedString> {
644 Some("Project Diagnostics".into())
645 }
646
647 fn tab_content(&self, params: TabContentParams, _: &WindowContext) -> AnyElement {
648 if self.summary.error_count == 0 && self.summary.warning_count == 0 {
649 Label::new("No problems")
650 .color(params.text_color())
651 .into_any_element()
652 } else {
653 h_flex()
654 .gap_1()
655 .when(self.summary.error_count > 0, |then| {
656 then.child(
657 h_flex()
658 .gap_1()
659 .child(Icon::new(IconName::XCircle).color(Color::Error))
660 .child(
661 Label::new(self.summary.error_count.to_string())
662 .color(params.text_color()),
663 ),
664 )
665 })
666 .when(self.summary.warning_count > 0, |then| {
667 then.child(
668 h_flex()
669 .gap_1()
670 .child(Icon::new(IconName::ExclamationTriangle).color(Color::Warning))
671 .child(
672 Label::new(self.summary.warning_count.to_string())
673 .color(params.text_color()),
674 ),
675 )
676 })
677 .into_any_element()
678 }
679 }
680
681 fn telemetry_event_text(&self) -> Option<&'static str> {
682 Some("project diagnostics")
683 }
684
685 fn for_each_project_item(
686 &self,
687 cx: &AppContext,
688 f: &mut dyn FnMut(gpui::EntityId, &dyn project::Item),
689 ) {
690 self.editor.for_each_project_item(cx, f)
691 }
692
693 fn is_singleton(&self, _: &AppContext) -> bool {
694 false
695 }
696
697 fn set_nav_history(&mut self, nav_history: ItemNavHistory, cx: &mut ViewContext<Self>) {
698 self.editor.update(cx, |editor, _| {
699 editor.set_nav_history(Some(nav_history));
700 });
701 }
702
703 fn clone_on_split(
704 &self,
705 _workspace_id: Option<workspace::WorkspaceId>,
706 cx: &mut ViewContext<Self>,
707 ) -> Option<View<Self>>
708 where
709 Self: Sized,
710 {
711 Some(cx.new_view(|cx| {
712 ProjectDiagnosticsEditor::new(self.project.clone(), self.workspace.clone(), cx)
713 }))
714 }
715
716 fn is_dirty(&self, cx: &AppContext) -> bool {
717 self.excerpts.read(cx).is_dirty(cx)
718 }
719
720 fn has_conflict(&self, cx: &AppContext) -> bool {
721 self.excerpts.read(cx).has_conflict(cx)
722 }
723
724 fn can_save(&self, _: &AppContext) -> bool {
725 true
726 }
727
728 fn save(
729 &mut self,
730 format: bool,
731 project: Model<Project>,
732 cx: &mut ViewContext<Self>,
733 ) -> Task<Result<()>> {
734 self.editor.save(format, project, cx)
735 }
736
737 fn save_as(
738 &mut self,
739 _: Model<Project>,
740 _: ProjectPath,
741 _: &mut ViewContext<Self>,
742 ) -> Task<Result<()>> {
743 unreachable!()
744 }
745
746 fn reload(&mut self, project: Model<Project>, cx: &mut ViewContext<Self>) -> Task<Result<()>> {
747 self.editor.reload(project, cx)
748 }
749
750 fn act_as_type<'a>(
751 &'a self,
752 type_id: TypeId,
753 self_handle: &'a View<Self>,
754 _: &'a AppContext,
755 ) -> Option<AnyView> {
756 if type_id == TypeId::of::<Self>() {
757 Some(self_handle.to_any())
758 } else if type_id == TypeId::of::<Editor>() {
759 Some(self.editor.to_any())
760 } else {
761 None
762 }
763 }
764
765 fn breadcrumb_location(&self) -> ToolbarItemLocation {
766 ToolbarItemLocation::PrimaryLeft
767 }
768
769 fn breadcrumbs(&self, theme: &theme::Theme, cx: &AppContext) -> Option<Vec<BreadcrumbText>> {
770 self.editor.breadcrumbs(theme, cx)
771 }
772
773 fn added_to_workspace(&mut self, workspace: &mut Workspace, cx: &mut ViewContext<Self>) {
774 self.editor
775 .update(cx, |editor, cx| editor.added_to_workspace(workspace, cx));
776 }
777}
778
779const DIAGNOSTIC_HEADER: &str = "diagnostic header";
780
781fn diagnostic_header_renderer(diagnostic: Diagnostic) -> RenderBlock {
782 let (message, code_ranges) = highlight_diagnostic_message(&diagnostic, None);
783 let message: SharedString = message;
784 Box::new(move |cx| {
785 let highlight_style: HighlightStyle = cx.theme().colors().text_accent.into();
786 h_flex()
787 .id(DIAGNOSTIC_HEADER)
788 .h(2. * cx.line_height())
789 .pl_10()
790 .pr_5()
791 .w_full()
792 .justify_between()
793 .gap_2()
794 .child(
795 h_flex()
796 .gap_3()
797 .map(|stack| {
798 stack.child(
799 svg()
800 .size(cx.text_style().font_size)
801 .flex_none()
802 .map(|icon| {
803 if diagnostic.severity == DiagnosticSeverity::ERROR {
804 icon.path(IconName::XCircle.path())
805 .text_color(Color::Error.color(cx))
806 } else {
807 icon.path(IconName::ExclamationTriangle.path())
808 .text_color(Color::Warning.color(cx))
809 }
810 }),
811 )
812 })
813 .child(
814 h_flex()
815 .gap_1()
816 .child(
817 StyledText::new(message.clone()).with_highlights(
818 &cx.text_style(),
819 code_ranges
820 .iter()
821 .map(|range| (range.clone(), highlight_style)),
822 ),
823 )
824 .when_some(diagnostic.code.as_ref(), |stack, code| {
825 stack.child(
826 div()
827 .child(SharedString::from(format!("({code})")))
828 .text_color(cx.theme().colors().text_muted),
829 )
830 }),
831 ),
832 )
833 .child(
834 h_flex()
835 .gap_1()
836 .when_some(diagnostic.source.as_ref(), |stack, source| {
837 stack.child(
838 div()
839 .child(SharedString::from(source.clone()))
840 .text_color(cx.theme().colors().text_muted),
841 )
842 }),
843 )
844 .into_any_element()
845 })
846}
847
848fn compare_diagnostics(
849 old: &DiagnosticEntry<language::Anchor>,
850 new: &DiagnosticEntry<language::Anchor>,
851 snapshot: &language::BufferSnapshot,
852) -> Ordering {
853 use language::ToOffset;
854
855 // The diagnostics may point to a previously open Buffer for this file.
856 if !old.range.start.is_valid(snapshot) || !new.range.start.is_valid(snapshot) {
857 return Ordering::Greater;
858 }
859
860 old.range
861 .start
862 .to_offset(snapshot)
863 .cmp(&new.range.start.to_offset(snapshot))
864 .then_with(|| {
865 old.range
866 .end
867 .to_offset(snapshot)
868 .cmp(&new.range.end.to_offset(snapshot))
869 })
870 .then_with(|| old.diagnostic.message.cmp(&new.diagnostic.message))
871}