items.rs

  1use editor::{Editor, GoToNextDiagnostic};
  2use gpui::{
  3    elements::*, platform::CursorStyle, serde_json, Entity, ModelHandle, MutableAppContext,
  4    RenderContext, Subscription, View, ViewContext, ViewHandle, WeakViewHandle,
  5};
  6use language::Diagnostic;
  7use project::Project;
  8use settings::Settings;
  9use workspace::StatusItemView;
 10
 11pub struct DiagnosticIndicator {
 12    summary: project::DiagnosticSummary,
 13    active_editor: Option<WeakViewHandle<Editor>>,
 14    current_diagnostic: Option<Diagnostic>,
 15    check_in_progress: bool,
 16    _observe_active_editor: Option<Subscription>,
 17}
 18
 19pub fn init(cx: &mut MutableAppContext) {
 20    cx.add_action(DiagnosticIndicator::go_to_next_diagnostic);
 21}
 22
 23impl DiagnosticIndicator {
 24    pub fn new(project: &ModelHandle<Project>, cx: &mut ViewContext<Self>) -> Self {
 25        cx.subscribe(project, |this, project, event, cx| match event {
 26            project::Event::DiskBasedDiagnosticsUpdated => {
 27                cx.notify();
 28            }
 29            project::Event::DiskBasedDiagnosticsStarted => {
 30                this.check_in_progress = true;
 31                cx.notify();
 32            }
 33            project::Event::DiskBasedDiagnosticsFinished => {
 34                this.summary = project.read(cx).diagnostic_summary(cx);
 35                this.check_in_progress = false;
 36                cx.notify();
 37            }
 38            _ => {}
 39        })
 40        .detach();
 41        Self {
 42            summary: project.read(cx).diagnostic_summary(cx),
 43            check_in_progress: project.read(cx).is_running_disk_based_diagnostics(),
 44            active_editor: None,
 45            current_diagnostic: None,
 46            _observe_active_editor: None,
 47        }
 48    }
 49
 50    fn go_to_next_diagnostic(&mut self, _: &GoToNextDiagnostic, cx: &mut ViewContext<Self>) {
 51        if let Some(editor) = self.active_editor.as_ref().and_then(|e| e.upgrade(cx)) {
 52            editor.update(cx, |editor, cx| {
 53                editor.go_to_diagnostic(editor::Direction::Next, cx);
 54            })
 55        }
 56    }
 57
 58    fn update(&mut self, editor: ViewHandle<Editor>, cx: &mut ViewContext<Self>) {
 59        let editor = editor.read(cx);
 60        let buffer = editor.buffer().read(cx);
 61        let cursor_position = editor
 62            .newest_selection_with_snapshot::<usize>(&buffer.read(cx))
 63            .head();
 64        let new_diagnostic = buffer
 65            .read(cx)
 66            .diagnostics_in_range::<_, usize>(cursor_position..cursor_position, false)
 67            .filter(|entry| !entry.range.is_empty())
 68            .min_by_key(|entry| (entry.diagnostic.severity, entry.range.len()))
 69            .map(|entry| entry.diagnostic);
 70        if new_diagnostic != self.current_diagnostic {
 71            self.current_diagnostic = new_diagnostic;
 72            cx.notify();
 73        }
 74    }
 75}
 76
 77impl Entity for DiagnosticIndicator {
 78    type Event = ();
 79}
 80
 81impl View for DiagnosticIndicator {
 82    fn ui_name() -> &'static str {
 83        "DiagnosticIndicator"
 84    }
 85
 86    fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
 87        enum Summary {}
 88        enum Message {}
 89
 90        let in_progress = self.check_in_progress;
 91        let mut element = Flex::row().with_child(
 92            MouseEventHandler::new::<Summary, _, _>(0, cx, |state, cx| {
 93                let style = &cx
 94                    .global::<Settings>()
 95                    .theme
 96                    .workspace
 97                    .status_bar
 98                    .diagnostics;
 99
100                let summary_style = if self.summary.error_count > 0 {
101                    &style.summary_error
102                } else if self.summary.warning_count > 0 {
103                    &style.summary_warning
104                } else {
105                    &style.summary_ok
106                };
107
108                let summary_style = if state.hovered {
109                    summary_style.hover()
110                } else {
111                    &summary_style.default
112                };
113
114                let mut summary_row = Flex::row();
115                if self.summary.error_count > 0 {
116                    summary_row.add_children([
117                        Svg::new("icons/error-solid-14.svg")
118                            .with_color(style.icon_color_error)
119                            .constrained()
120                            .with_width(style.icon_width)
121                            .aligned()
122                            .contained()
123                            .with_margin_right(style.icon_spacing)
124                            .named("error-icon"),
125                        Label::new(
126                            self.summary.error_count.to_string(),
127                            summary_style.text.clone(),
128                        )
129                        .aligned()
130                        .boxed(),
131                    ]);
132                }
133
134                if self.summary.warning_count > 0 {
135                    summary_row.add_children([
136                        Svg::new("icons/warning-solid-14.svg")
137                            .with_color(style.icon_color_warning)
138                            .constrained()
139                            .with_width(style.icon_width)
140                            .aligned()
141                            .contained()
142                            .with_margin_right(style.icon_spacing)
143                            .with_margin_left(if self.summary.error_count > 0 {
144                                style.summary_spacing
145                            } else {
146                                0.
147                            })
148                            .named("warning-icon"),
149                        Label::new(
150                            self.summary.warning_count.to_string(),
151                            summary_style.text.clone(),
152                        )
153                        .aligned()
154                        .boxed(),
155                    ]);
156                }
157
158                if self.summary.error_count == 0 && self.summary.warning_count == 0 {
159                    summary_row.add_child(
160                        Svg::new("icons/no-error-solid-14.svg")
161                            .with_color(style.icon_color_ok)
162                            .constrained()
163                            .with_width(style.icon_width)
164                            .aligned()
165                            .named("ok-icon"),
166                    );
167                }
168
169                summary_row
170                    .constrained()
171                    .with_height(style.height)
172                    .contained()
173                    .with_style(summary_style.container)
174                    .boxed()
175            })
176            .with_cursor_style(CursorStyle::PointingHand)
177            .on_click(|cx| cx.dispatch_action(crate::Deploy))
178            .aligned()
179            .boxed(),
180        );
181
182        let style = &cx.global::<Settings>().theme.workspace.status_bar;
183        let item_spacing = style.item_spacing;
184        let message_style = &style.diagnostics.message;
185
186        if in_progress {
187            element.add_child(
188                Label::new("checking…".into(), message_style.default.text.clone())
189                    .aligned()
190                    .contained()
191                    .with_margin_left(item_spacing)
192                    .boxed(),
193            );
194        } else if let Some(diagnostic) = &self.current_diagnostic {
195            let message_style = message_style.clone();
196            element.add_child(
197                MouseEventHandler::new::<Message, _, _>(0, cx, |state, _| {
198                    Label::new(
199                        diagnostic.message.split('\n').next().unwrap().to_string(),
200                        if state.hovered {
201                            message_style.hover().text.clone()
202                        } else {
203                            message_style.default.text.clone()
204                        },
205                    )
206                    .aligned()
207                    .contained()
208                    .with_margin_left(item_spacing)
209                    .boxed()
210                })
211                .with_cursor_style(CursorStyle::PointingHand)
212                .on_click(|cx| cx.dispatch_action(GoToNextDiagnostic))
213                .boxed(),
214            );
215        }
216
217        element.named("diagnostic indicator")
218    }
219
220    fn debug_json(&self, _: &gpui::AppContext) -> serde_json::Value {
221        serde_json::json!({ "summary": self.summary })
222    }
223}
224
225impl StatusItemView for DiagnosticIndicator {
226    fn set_active_pane_item(
227        &mut self,
228        active_pane_item: Option<&dyn workspace::ItemHandle>,
229        cx: &mut ViewContext<Self>,
230    ) {
231        if let Some(editor) = active_pane_item.and_then(|item| item.downcast::<Editor>()) {
232            self.active_editor = Some(editor.downgrade());
233            self._observe_active_editor = Some(cx.observe(&editor, Self::update));
234            self.update(editor, cx);
235        } else {
236            self.active_editor = None;
237            self.current_diagnostic = None;
238            self._observe_active_editor = None;
239        }
240        cx.notify();
241    }
242}