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