items.rs

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