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