1use auto_update::{AutoUpdateStatus, AutoUpdater, DismissErrorMessage};
2use editor::Editor;
3use extension::ExtensionStore;
4use futures::StreamExt;
5use gpui::{
6 actions, percentage, Animation, AnimationExt as _, AppContext, CursorStyle, EventEmitter,
7 InteractiveElement as _, Model, ParentElement as _, Render, SharedString,
8 StatefulInteractiveElement, Styled, Transformation, View, ViewContext, VisualContext as _,
9};
10use language::{
11 LanguageRegistry, LanguageServerBinaryStatus, LanguageServerId, LanguageServerName,
12};
13use project::{EnvironmentErrorMessage, LanguageServerProgress, Project, WorktreeId};
14use smallvec::SmallVec;
15use std::{cmp::Reverse, fmt::Write, sync::Arc, time::Duration};
16use ui::{prelude::*, ButtonLike, ContextMenu, PopoverMenu, PopoverMenuHandle, Tooltip};
17use util::truncate_and_trailoff;
18use workspace::{item::ItemHandle, StatusItemView, Workspace};
19
20actions!(activity_indicator, [ShowErrorMessage]);
21
22pub enum Event {
23 ShowError {
24 lsp_name: LanguageServerName,
25 error: String,
26 },
27}
28
29pub struct ActivityIndicator {
30 statuses: Vec<LspStatus>,
31 project: Model<Project>,
32 auto_updater: Option<Model<AutoUpdater>>,
33 context_menu_handle: PopoverMenuHandle<ContextMenu>,
34}
35
36struct LspStatus {
37 name: LanguageServerName,
38 status: LanguageServerBinaryStatus,
39}
40
41struct PendingWork<'a> {
42 language_server_id: LanguageServerId,
43 progress_token: &'a str,
44 progress: &'a LanguageServerProgress,
45}
46
47struct Content {
48 icon: Option<gpui::AnyElement>,
49 message: String,
50 on_click: Option<Arc<dyn Fn(&mut ActivityIndicator, &mut ViewContext<ActivityIndicator>)>>,
51}
52
53impl ActivityIndicator {
54 pub fn new(
55 workspace: &mut Workspace,
56 languages: Arc<LanguageRegistry>,
57 cx: &mut ViewContext<Workspace>,
58 ) -> View<ActivityIndicator> {
59 let project = workspace.project().clone();
60 let auto_updater = AutoUpdater::get(cx);
61 let this = cx.new_view(|cx: &mut ViewContext<Self>| {
62 let mut status_events = languages.language_server_binary_statuses();
63 cx.spawn(|this, mut cx| async move {
64 while let Some((name, status)) = status_events.next().await {
65 this.update(&mut cx, |this, cx| {
66 this.statuses.retain(|s| s.name != name);
67 this.statuses.push(LspStatus { name, status });
68 cx.notify();
69 })?;
70 }
71 anyhow::Ok(())
72 })
73 .detach();
74 cx.observe(&project, |_, _, cx| cx.notify()).detach();
75
76 if let Some(auto_updater) = auto_updater.as_ref() {
77 cx.observe(auto_updater, |_, _, cx| cx.notify()).detach();
78 }
79
80 Self {
81 statuses: Default::default(),
82 project: project.clone(),
83 auto_updater,
84 context_menu_handle: Default::default(),
85 }
86 });
87
88 cx.subscribe(&this, move |_, _, event, cx| match event {
89 Event::ShowError { lsp_name, error } => {
90 let create_buffer = project.update(cx, |project, cx| project.create_buffer(cx));
91 let project = project.clone();
92 let error = error.clone();
93 let lsp_name = lsp_name.clone();
94 cx.spawn(|workspace, mut cx| async move {
95 let buffer = create_buffer.await?;
96 buffer.update(&mut cx, |buffer, cx| {
97 buffer.edit(
98 [(
99 0..0,
100 format!("Language server error: {}\n\n{}", lsp_name, error),
101 )],
102 None,
103 cx,
104 );
105 buffer.set_capability(language::Capability::ReadOnly, cx);
106 })?;
107 workspace.update(&mut cx, |workspace, cx| {
108 workspace.add_item_to_active_pane(
109 Box::new(cx.new_view(|cx| {
110 Editor::for_buffer(buffer, Some(project.clone()), cx)
111 })),
112 None,
113 true,
114 cx,
115 );
116 })?;
117
118 anyhow::Ok(())
119 })
120 .detach();
121 }
122 })
123 .detach();
124 this
125 }
126
127 fn show_error_message(&mut self, _: &ShowErrorMessage, cx: &mut ViewContext<Self>) {
128 self.statuses.retain(|status| {
129 if let LanguageServerBinaryStatus::Failed { error } = &status.status {
130 cx.emit(Event::ShowError {
131 lsp_name: status.name.clone(),
132 error: error.clone(),
133 });
134 false
135 } else {
136 true
137 }
138 });
139
140 cx.notify();
141 }
142
143 fn dismiss_error_message(&mut self, _: &DismissErrorMessage, cx: &mut ViewContext<Self>) {
144 if let Some(updater) = &self.auto_updater {
145 updater.update(cx, |updater, cx| {
146 updater.dismiss_error(cx);
147 });
148 }
149 cx.notify();
150 }
151
152 fn pending_language_server_work<'a>(
153 &self,
154 cx: &'a AppContext,
155 ) -> impl Iterator<Item = PendingWork<'a>> {
156 self.project
157 .read(cx)
158 .language_server_statuses(cx)
159 .rev()
160 .filter_map(|(server_id, status)| {
161 if status.pending_work.is_empty() {
162 None
163 } else {
164 let mut pending_work = status
165 .pending_work
166 .iter()
167 .map(|(token, progress)| PendingWork {
168 language_server_id: server_id,
169 progress_token: token.as_str(),
170 progress,
171 })
172 .collect::<SmallVec<[_; 4]>>();
173 pending_work.sort_by_key(|work| Reverse(work.progress.last_update_at));
174 Some(pending_work)
175 }
176 })
177 .flatten()
178 }
179
180 fn pending_environment_errors<'a>(
181 &'a self,
182 cx: &'a AppContext,
183 ) -> impl Iterator<Item = (&'a WorktreeId, &'a EnvironmentErrorMessage)> {
184 self.project.read(cx).shell_environment_errors(cx)
185 }
186
187 fn content_to_render(&mut self, cx: &mut ViewContext<Self>) -> Option<Content> {
188 // Show if any direnv calls failed
189 if let Some((&worktree_id, error)) = self.pending_environment_errors(cx).next() {
190 return Some(Content {
191 icon: Some(
192 Icon::new(IconName::Warning)
193 .size(IconSize::Small)
194 .into_any_element(),
195 ),
196 message: error.0.clone(),
197 on_click: Some(Arc::new(move |this, cx| {
198 this.project.update(cx, |project, cx| {
199 project.remove_environment_error(cx, worktree_id);
200 });
201 cx.dispatch_action(Box::new(workspace::OpenLog));
202 })),
203 });
204 }
205 // Show any language server has pending activity.
206 let mut pending_work = self.pending_language_server_work(cx);
207 if let Some(PendingWork {
208 progress_token,
209 progress,
210 ..
211 }) = pending_work.next()
212 {
213 let mut message = progress
214 .title
215 .as_deref()
216 .unwrap_or(progress_token)
217 .to_string();
218
219 if let Some(percentage) = progress.percentage {
220 write!(&mut message, " ({}%)", percentage).unwrap();
221 }
222
223 if let Some(progress_message) = progress.message.as_ref() {
224 message.push_str(": ");
225 message.push_str(progress_message);
226 }
227
228 let additional_work_count = pending_work.count();
229 if additional_work_count > 0 {
230 write!(&mut message, " + {} more", additional_work_count).unwrap();
231 }
232
233 return Some(Content {
234 icon: Some(
235 Icon::new(IconName::ArrowCircle)
236 .size(IconSize::Small)
237 .with_animation(
238 "arrow-circle",
239 Animation::new(Duration::from_secs(2)).repeat(),
240 |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
241 )
242 .into_any_element(),
243 ),
244 message,
245 on_click: Some(Arc::new(Self::toggle_language_server_work_context_menu)),
246 });
247 }
248
249 // Show any language server installation info.
250 let mut downloading = SmallVec::<[_; 3]>::new();
251 let mut checking_for_update = SmallVec::<[_; 3]>::new();
252 let mut failed = SmallVec::<[_; 3]>::new();
253 for status in &self.statuses {
254 match status.status {
255 LanguageServerBinaryStatus::CheckingForUpdate => {
256 checking_for_update.push(status.name.clone())
257 }
258 LanguageServerBinaryStatus::Downloading => downloading.push(status.name.clone()),
259 LanguageServerBinaryStatus::Failed { .. } => failed.push(status.name.clone()),
260 LanguageServerBinaryStatus::None => {}
261 }
262 }
263
264 if !downloading.is_empty() {
265 return Some(Content {
266 icon: Some(
267 Icon::new(IconName::Download)
268 .size(IconSize::Small)
269 .into_any_element(),
270 ),
271 message: format!(
272 "Downloading {}...",
273 downloading.iter().map(|name| name.0.as_ref()).fold(
274 String::new(),
275 |mut acc, s| {
276 if !acc.is_empty() {
277 acc.push_str(", ");
278 }
279 acc.push_str(s);
280 acc
281 }
282 )
283 ),
284 on_click: Some(Arc::new(move |this, cx| {
285 this.statuses
286 .retain(|status| !downloading.contains(&status.name));
287 this.dismiss_error_message(&DismissErrorMessage, cx)
288 })),
289 });
290 }
291
292 if !checking_for_update.is_empty() {
293 return Some(Content {
294 icon: Some(
295 Icon::new(IconName::Download)
296 .size(IconSize::Small)
297 .into_any_element(),
298 ),
299 message: format!(
300 "Checking for updates to {}...",
301 checking_for_update.iter().map(|name| name.0.as_ref()).fold(
302 String::new(),
303 |mut acc, s| {
304 if !acc.is_empty() {
305 acc.push_str(", ");
306 }
307 acc.push_str(s);
308 acc
309 }
310 ),
311 ),
312 on_click: Some(Arc::new(move |this, cx| {
313 this.statuses
314 .retain(|status| !checking_for_update.contains(&status.name));
315 this.dismiss_error_message(&DismissErrorMessage, cx)
316 })),
317 });
318 }
319
320 if !failed.is_empty() {
321 return Some(Content {
322 icon: Some(
323 Icon::new(IconName::Warning)
324 .size(IconSize::Small)
325 .into_any_element(),
326 ),
327 message: format!(
328 "Failed to run {}. Click to show error.",
329 failed
330 .iter()
331 .map(|name| name.0.as_ref())
332 .fold(String::new(), |mut acc, s| {
333 if !acc.is_empty() {
334 acc.push_str(", ");
335 }
336 acc.push_str(s);
337 acc
338 }),
339 ),
340 on_click: Some(Arc::new(|this, cx| {
341 this.show_error_message(&Default::default(), cx)
342 })),
343 });
344 }
345
346 // Show any formatting failure
347 if let Some(failure) = self.project.read(cx).last_formatting_failure(cx) {
348 return Some(Content {
349 icon: Some(
350 Icon::new(IconName::Warning)
351 .size(IconSize::Small)
352 .into_any_element(),
353 ),
354 message: format!("Formatting failed: {}. Click to see logs.", failure),
355 on_click: Some(Arc::new(|_, cx| {
356 cx.dispatch_action(Box::new(workspace::OpenLog));
357 })),
358 });
359 }
360
361 // Show any application auto-update info.
362 if let Some(updater) = &self.auto_updater {
363 return match &updater.read(cx).status() {
364 AutoUpdateStatus::Checking => Some(Content {
365 icon: Some(
366 Icon::new(IconName::Download)
367 .size(IconSize::Small)
368 .into_any_element(),
369 ),
370 message: "Checking for Zed updates…".to_string(),
371 on_click: Some(Arc::new(|this, cx| {
372 this.dismiss_error_message(&DismissErrorMessage, cx)
373 })),
374 }),
375 AutoUpdateStatus::Downloading => Some(Content {
376 icon: Some(
377 Icon::new(IconName::Download)
378 .size(IconSize::Small)
379 .into_any_element(),
380 ),
381 message: "Downloading Zed update…".to_string(),
382 on_click: Some(Arc::new(|this, cx| {
383 this.dismiss_error_message(&DismissErrorMessage, cx)
384 })),
385 }),
386 AutoUpdateStatus::Installing => Some(Content {
387 icon: Some(
388 Icon::new(IconName::Download)
389 .size(IconSize::Small)
390 .into_any_element(),
391 ),
392 message: "Installing Zed update…".to_string(),
393 on_click: Some(Arc::new(|this, cx| {
394 this.dismiss_error_message(&DismissErrorMessage, cx)
395 })),
396 }),
397 AutoUpdateStatus::Updated { binary_path } => Some(Content {
398 icon: None,
399 message: "Click to restart and update Zed".to_string(),
400 on_click: Some(Arc::new({
401 let reload = workspace::Reload {
402 binary_path: Some(binary_path.clone()),
403 };
404 move |_, cx| workspace::reload(&reload, cx)
405 })),
406 }),
407 AutoUpdateStatus::Errored => Some(Content {
408 icon: Some(
409 Icon::new(IconName::Warning)
410 .size(IconSize::Small)
411 .into_any_element(),
412 ),
413 message: "Auto update failed".to_string(),
414 on_click: Some(Arc::new(|this, cx| {
415 this.dismiss_error_message(&DismissErrorMessage, cx)
416 })),
417 }),
418 AutoUpdateStatus::Idle => None,
419 };
420 }
421
422 if let Some(extension_store) =
423 ExtensionStore::try_global(cx).map(|extension_store| extension_store.read(cx))
424 {
425 if let Some(extension_id) = extension_store.outstanding_operations().keys().next() {
426 return Some(Content {
427 icon: Some(
428 Icon::new(IconName::Download)
429 .size(IconSize::Small)
430 .into_any_element(),
431 ),
432 message: format!("Updating {extension_id} extension…"),
433 on_click: Some(Arc::new(|this, cx| {
434 this.dismiss_error_message(&DismissErrorMessage, cx)
435 })),
436 });
437 }
438 }
439
440 None
441 }
442
443 fn toggle_language_server_work_context_menu(&mut self, cx: &mut ViewContext<Self>) {
444 self.context_menu_handle.toggle(cx);
445 }
446}
447
448impl EventEmitter<Event> for ActivityIndicator {}
449
450const MAX_MESSAGE_LEN: usize = 50;
451
452impl Render for ActivityIndicator {
453 fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
454 let result = h_flex()
455 .id("activity-indicator")
456 .on_action(cx.listener(Self::show_error_message))
457 .on_action(cx.listener(Self::dismiss_error_message));
458 let Some(content) = self.content_to_render(cx) else {
459 return result;
460 };
461 let this = cx.view().downgrade();
462 let truncate_content = content.message.len() > MAX_MESSAGE_LEN;
463 result.gap_2().child(
464 PopoverMenu::new("activity-indicator-popover")
465 .trigger(
466 ButtonLike::new("activity-indicator-trigger").child(
467 h_flex()
468 .id("activity-indicator-status")
469 .gap_2()
470 .children(content.icon)
471 .map(|button| {
472 if truncate_content {
473 button
474 .child(
475 Label::new(truncate_and_trailoff(
476 &content.message,
477 MAX_MESSAGE_LEN,
478 ))
479 .size(LabelSize::Small),
480 )
481 .tooltip(move |cx| Tooltip::text(&content.message, cx))
482 } else {
483 button.child(Label::new(content.message).size(LabelSize::Small))
484 }
485 })
486 .when_some(content.on_click, |this, handler| {
487 this.on_click(cx.listener(move |this, _, cx| {
488 handler(this, cx);
489 }))
490 .cursor(CursorStyle::PointingHand)
491 }),
492 ),
493 )
494 .anchor(gpui::AnchorCorner::BottomLeft)
495 .menu(move |cx| {
496 let strong_this = this.upgrade()?;
497 let mut has_work = false;
498 let menu = ContextMenu::build(cx, |mut menu, cx| {
499 for work in strong_this.read(cx).pending_language_server_work(cx) {
500 has_work = true;
501 let this = this.clone();
502 let mut title = work
503 .progress
504 .title
505 .as_deref()
506 .unwrap_or(work.progress_token)
507 .to_owned();
508
509 if work.progress.is_cancellable {
510 let language_server_id = work.language_server_id;
511 let token = work.progress_token.to_string();
512 let title = SharedString::from(title);
513 menu = menu.custom_entry(
514 move |_| {
515 h_flex()
516 .w_full()
517 .justify_between()
518 .child(Label::new(title.clone()))
519 .child(Icon::new(IconName::XCircle))
520 .into_any_element()
521 },
522 move |cx| {
523 this.update(cx, |this, cx| {
524 this.project.update(cx, |project, cx| {
525 project.cancel_language_server_work(
526 language_server_id,
527 Some(token.clone()),
528 cx,
529 );
530 });
531 this.context_menu_handle.hide(cx);
532 cx.notify();
533 })
534 .ok();
535 },
536 );
537 } else {
538 if let Some(progress_message) = work.progress.message.as_ref() {
539 title.push_str(": ");
540 title.push_str(progress_message);
541 }
542
543 menu = menu.label(title);
544 }
545 }
546 menu
547 });
548 has_work.then_some(menu)
549 }),
550 )
551 }
552}
553
554impl StatusItemView for ActivityIndicator {
555 fn set_active_pane_item(&mut self, _: Option<&dyn ItemHandle>, _: &mut ViewContext<Self>) {}
556}