1use auto_update::{AutoUpdateStatus, AutoUpdater, DismissErrorMessage};
2use editor::Editor;
3use futures::StreamExt;
4use gpui::{
5 actions, svg, AppContext, CursorStyle, EventEmitter, InteractiveElement as _, Model,
6 ParentElement as _, Render, SharedString, StatefulInteractiveElement, Styled, View,
7 ViewContext, VisualContext as _,
8};
9use language::{LanguageRegistry, LanguageServerBinaryStatus, LanguageServerName};
10use project::{LanguageServerProgress, Project};
11use smallvec::SmallVec;
12use std::{cmp::Reverse, fmt::Write, sync::Arc};
13use ui::prelude::*;
14use util::ResultExt;
15use workspace::{item::ItemHandle, StatusItemView, Workspace};
16
17actions!(activity_indicator, [ShowErrorMessage]);
18
19const DOWNLOAD_ICON: &str = "icons/download.svg";
20const WARNING_ICON: &str = "icons/warning.svg";
21
22pub enum Event {
23 ShowError { lsp_name: Arc<str>, error: String },
24}
25
26pub struct ActivityIndicator {
27 statuses: Vec<LspStatus>,
28 project: Model<Project>,
29 auto_updater: Option<Model<AutoUpdater>>,
30}
31
32struct LspStatus {
33 name: LanguageServerName,
34 status: LanguageServerBinaryStatus,
35}
36
37struct PendingWork<'a> {
38 language_server_name: &'a str,
39 progress_token: &'a str,
40 progress: &'a LanguageServerProgress,
41}
42
43#[derive(Default)]
44struct Content {
45 icon: Option<&'static str>,
46 message: String,
47 on_click: Option<Arc<dyn Fn(&mut ActivityIndicator, &mut ViewContext<ActivityIndicator>)>>,
48}
49
50impl ActivityIndicator {
51 pub fn new(
52 workspace: &mut Workspace,
53 languages: Arc<LanguageRegistry>,
54 cx: &mut ViewContext<Workspace>,
55 ) -> View<ActivityIndicator> {
56 let project = workspace.project().clone();
57 let auto_updater = AutoUpdater::get(cx);
58 let this = cx.new_view(|cx: &mut ViewContext<Self>| {
59 let mut status_events = languages.language_server_binary_statuses();
60 cx.spawn(|this, mut cx| async move {
61 while let Some((name, status)) = status_events.next().await {
62 this.update(&mut cx, |this, cx| {
63 this.statuses.retain(|s| s.name != name);
64 this.statuses.push(LspStatus { name, status });
65 cx.notify();
66 })?;
67 }
68 anyhow::Ok(())
69 })
70 .detach();
71 cx.observe(&project, |_, _, cx| cx.notify()).detach();
72
73 if let Some(auto_updater) = auto_updater.as_ref() {
74 cx.observe(auto_updater, |_, _, cx| cx.notify()).detach();
75 }
76
77 Self {
78 statuses: Default::default(),
79 project: project.clone(),
80 auto_updater,
81 }
82 });
83
84 cx.subscribe(&this, move |workspace, _, event, cx| match event {
85 Event::ShowError { lsp_name, error } => {
86 if let Some(buffer) = project
87 .update(cx, |project, cx| project.create_buffer(error, None, cx))
88 .log_err()
89 {
90 buffer.update(cx, |buffer, cx| {
91 buffer.edit(
92 [(0..0, format!("Language server error: {}\n\n", lsp_name))],
93 None,
94 cx,
95 );
96 });
97 workspace.add_item_to_active_pane(
98 Box::new(
99 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
100 ),
101 cx,
102 );
103 }
104 }
105 })
106 .detach();
107 this
108 }
109
110 fn show_error_message(&mut self, _: &ShowErrorMessage, cx: &mut ViewContext<Self>) {
111 self.statuses.retain(|status| {
112 if let LanguageServerBinaryStatus::Failed { error } = &status.status {
113 cx.emit(Event::ShowError {
114 lsp_name: status.name.0.clone(),
115 error: error.clone(),
116 });
117 false
118 } else {
119 true
120 }
121 });
122
123 cx.notify();
124 }
125
126 fn dismiss_error_message(&mut self, _: &DismissErrorMessage, cx: &mut ViewContext<Self>) {
127 if let Some(updater) = &self.auto_updater {
128 updater.update(cx, |updater, cx| {
129 updater.dismiss_error(cx);
130 });
131 }
132 cx.notify();
133 }
134
135 fn pending_language_server_work<'a>(
136 &self,
137 cx: &'a AppContext,
138 ) -> impl Iterator<Item = PendingWork<'a>> {
139 self.project
140 .read(cx)
141 .language_server_statuses()
142 .rev()
143 .filter_map(|status| {
144 if status.pending_work.is_empty() {
145 None
146 } else {
147 let mut pending_work = status
148 .pending_work
149 .iter()
150 .map(|(token, progress)| PendingWork {
151 language_server_name: status.name.as_str(),
152 progress_token: token.as_str(),
153 progress,
154 })
155 .collect::<SmallVec<[_; 4]>>();
156 pending_work.sort_by_key(|work| Reverse(work.progress.last_update_at));
157 Some(pending_work)
158 }
159 })
160 .flatten()
161 }
162
163 fn content_to_render(&mut self, cx: &mut ViewContext<Self>) -> Content {
164 // Show any language server has pending activity.
165 let mut pending_work = self.pending_language_server_work(cx);
166 if let Some(PendingWork {
167 language_server_name,
168 progress_token,
169 progress,
170 }) = pending_work.next()
171 {
172 let mut message = language_server_name.to_string();
173
174 message.push_str(": ");
175 if let Some(progress_message) = progress.message.as_ref() {
176 message.push_str(progress_message);
177 } else {
178 message.push_str(progress_token);
179 }
180
181 if let Some(percentage) = progress.percentage {
182 write!(&mut message, " ({}%)", percentage).unwrap();
183 }
184
185 let additional_work_count = pending_work.count();
186 if additional_work_count > 0 {
187 write!(&mut message, " + {} more", additional_work_count).unwrap();
188 }
189
190 return Content {
191 icon: None,
192 message,
193 on_click: None,
194 };
195 }
196
197 // Show any language server installation info.
198 let mut downloading = SmallVec::<[_; 3]>::new();
199 let mut checking_for_update = SmallVec::<[_; 3]>::new();
200 let mut failed = SmallVec::<[_; 3]>::new();
201 for status in &self.statuses {
202 match status.status {
203 LanguageServerBinaryStatus::CheckingForUpdate => {
204 checking_for_update.push(status.name.0.as_ref())
205 }
206 LanguageServerBinaryStatus::Downloading => downloading.push(status.name.0.as_ref()),
207 LanguageServerBinaryStatus::Failed { .. } => failed.push(status.name.0.as_ref()),
208 LanguageServerBinaryStatus::Downloaded | LanguageServerBinaryStatus::Cached => {}
209 }
210 }
211
212 if !downloading.is_empty() {
213 return Content {
214 icon: Some(DOWNLOAD_ICON),
215 message: format!("Downloading {}...", downloading.join(", "),),
216 on_click: None,
217 };
218 }
219
220 if !checking_for_update.is_empty() {
221 return Content {
222 icon: Some(DOWNLOAD_ICON),
223 message: format!(
224 "Checking for updates to {}...",
225 checking_for_update.join(", "),
226 ),
227 on_click: None,
228 };
229 }
230
231 if !failed.is_empty() {
232 return Content {
233 icon: Some(WARNING_ICON),
234 message: format!(
235 "Failed to download {}. Click to show error.",
236 failed.join(", "),
237 ),
238 on_click: Some(Arc::new(|this, cx| {
239 this.show_error_message(&Default::default(), cx)
240 })),
241 };
242 }
243
244 // Show any formatting failure
245 if let Some(failure) = self.project.read(cx).last_formatting_failure() {
246 return Content {
247 icon: Some(WARNING_ICON),
248 message: format!("Formatting failed: {}. Click to see logs.", failure),
249 on_click: Some(Arc::new(|_, cx| {
250 cx.dispatch_action(Box::new(workspace::OpenLog));
251 })),
252 };
253 }
254
255 // Show any application auto-update info.
256 if let Some(updater) = &self.auto_updater {
257 return match &updater.read(cx).status() {
258 AutoUpdateStatus::Checking => Content {
259 icon: Some(DOWNLOAD_ICON),
260 message: "Checking for Zed updates…".to_string(),
261 on_click: None,
262 },
263 AutoUpdateStatus::Downloading => Content {
264 icon: Some(DOWNLOAD_ICON),
265 message: "Downloading Zed update…".to_string(),
266 on_click: None,
267 },
268 AutoUpdateStatus::Installing => Content {
269 icon: Some(DOWNLOAD_ICON),
270 message: "Installing Zed update…".to_string(),
271 on_click: None,
272 },
273 AutoUpdateStatus::Updated => Content {
274 icon: None,
275 message: "Click to restart and update Zed".to_string(),
276 on_click: Some(Arc::new(|_, cx| {
277 workspace::restart(&Default::default(), cx)
278 })),
279 },
280 AutoUpdateStatus::Errored => Content {
281 icon: Some(WARNING_ICON),
282 message: "Auto update failed".to_string(),
283 on_click: Some(Arc::new(|this, cx| {
284 this.dismiss_error_message(&Default::default(), cx)
285 })),
286 },
287 AutoUpdateStatus::Idle => Default::default(),
288 };
289 }
290
291 Default::default()
292 }
293}
294
295impl EventEmitter<Event> for ActivityIndicator {}
296
297impl Render for ActivityIndicator {
298 fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
299 let content = self.content_to_render(cx);
300
301 let mut result = h_flex()
302 .id("activity-indicator")
303 .on_action(cx.listener(Self::show_error_message))
304 .on_action(cx.listener(Self::dismiss_error_message));
305
306 if let Some(on_click) = content.on_click {
307 result = result
308 .cursor(CursorStyle::PointingHand)
309 .on_click(cx.listener(move |this, _, cx| {
310 on_click(this, cx);
311 }))
312 }
313
314 result
315 .children(content.icon.map(|icon| svg().path(icon)))
316 .child(Label::new(SharedString::from(content.message)).size(LabelSize::Small))
317 }
318}
319
320impl StatusItemView for ActivityIndicator {
321 fn set_active_pane_item(&mut self, _: Option<&dyn ItemHandle>, _: &mut ViewContext<Self>) {}
322}