activity_indicator.rs

  1use auto_update::{AutoUpdateStatus, AutoUpdater, DismissErrorMessage, VersionCheckType};
  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 { version } => 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: Some(Self::version_tooltip_message(&version)),
486                }),
487                AutoUpdateStatus::Installing { version } => 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: Some(Self::version_tooltip_message(&version)),
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(Self::version_tooltip_message(&version)),
512                }),
513                AutoUpdateStatus::Errored => Some(Content {
514                    icon: Some(
515                        Icon::new(IconName::Warning)
516                            .size(IconSize::Small)
517                            .into_any_element(),
518                    ),
519                    message: "Auto update failed".to_string(),
520                    on_click: Some(Arc::new(|this, window, cx| {
521                        this.dismiss_error_message(&DismissErrorMessage, window, cx)
522                    })),
523                    tooltip_message: None,
524                }),
525                AutoUpdateStatus::Idle => None,
526            };
527        }
528
529        if let Some(extension_store) =
530            ExtensionStore::try_global(cx).map(|extension_store| extension_store.read(cx))
531        {
532            if let Some(extension_id) = extension_store.outstanding_operations().keys().next() {
533                return Some(Content {
534                    icon: Some(
535                        Icon::new(IconName::Download)
536                            .size(IconSize::Small)
537                            .into_any_element(),
538                    ),
539                    message: format!("Updating {extension_id} extension…"),
540                    on_click: Some(Arc::new(|this, window, cx| {
541                        this.dismiss_error_message(&DismissErrorMessage, window, cx)
542                    })),
543                    tooltip_message: None,
544                });
545            }
546        }
547
548        None
549    }
550
551    fn version_tooltip_message(version: &VersionCheckType) -> String {
552        format!("Version: {}", {
553            match version {
554                auto_update::VersionCheckType::Sha(sha) => format!("{}", sha.short()),
555                auto_update::VersionCheckType::Semantic(semantic_version) => {
556                    semantic_version.to_string()
557                }
558            }
559        })
560    }
561
562    fn toggle_language_server_work_context_menu(
563        &mut self,
564        window: &mut Window,
565        cx: &mut Context<Self>,
566    ) {
567        self.context_menu_handle.toggle(window, cx);
568    }
569}
570
571impl EventEmitter<Event> for ActivityIndicator {}
572
573const MAX_MESSAGE_LEN: usize = 50;
574
575impl Render for ActivityIndicator {
576    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
577        let result = h_flex()
578            .id("activity-indicator")
579            .on_action(cx.listener(Self::show_error_message))
580            .on_action(cx.listener(Self::dismiss_error_message));
581        let Some(content) = self.content_to_render(cx) else {
582            return result;
583        };
584        let this = cx.entity().downgrade();
585        let truncate_content = content.message.len() > MAX_MESSAGE_LEN;
586        result.gap_2().child(
587            PopoverMenu::new("activity-indicator-popover")
588                .trigger(
589                    ButtonLike::new("activity-indicator-trigger").child(
590                        h_flex()
591                            .id("activity-indicator-status")
592                            .gap_2()
593                            .children(content.icon)
594                            .map(|button| {
595                                if truncate_content {
596                                    button
597                                        .child(
598                                            Label::new(truncate_and_trailoff(
599                                                &content.message,
600                                                MAX_MESSAGE_LEN,
601                                            ))
602                                            .size(LabelSize::Small),
603                                        )
604                                        .tooltip(Tooltip::text(content.message))
605                                } else {
606                                    button
607                                        .child(Label::new(content.message).size(LabelSize::Small))
608                                        .when_some(
609                                            content.tooltip_message,
610                                            |this, tooltip_message| {
611                                                this.tooltip(Tooltip::text(tooltip_message))
612                                            },
613                                        )
614                                }
615                            })
616                            .when_some(content.on_click, |this, handler| {
617                                this.on_click(cx.listener(move |this, _, window, cx| {
618                                    handler(this, window, cx);
619                                }))
620                                .cursor(CursorStyle::PointingHand)
621                            }),
622                    ),
623                )
624                .anchor(gpui::Corner::BottomLeft)
625                .menu(move |window, cx| {
626                    let strong_this = this.upgrade()?;
627                    let mut has_work = false;
628                    let menu = ContextMenu::build(window, cx, |mut menu, _, cx| {
629                        for work in strong_this.read(cx).pending_language_server_work(cx) {
630                            has_work = true;
631                            let this = this.clone();
632                            let mut title = work
633                                .progress
634                                .title
635                                .as_deref()
636                                .unwrap_or(work.progress_token)
637                                .to_owned();
638
639                            if work.progress.is_cancellable {
640                                let language_server_id = work.language_server_id;
641                                let token = work.progress_token.to_string();
642                                let title = SharedString::from(title);
643                                menu = menu.custom_entry(
644                                    move |_, _| {
645                                        h_flex()
646                                            .w_full()
647                                            .justify_between()
648                                            .child(Label::new(title.clone()))
649                                            .child(Icon::new(IconName::XCircle))
650                                            .into_any_element()
651                                    },
652                                    move |_, cx| {
653                                        this.update(cx, |this, cx| {
654                                            this.project.update(cx, |project, cx| {
655                                                project.cancel_language_server_work(
656                                                    language_server_id,
657                                                    Some(token.clone()),
658                                                    cx,
659                                                );
660                                            });
661                                            this.context_menu_handle.hide(cx);
662                                            cx.notify();
663                                        })
664                                        .ok();
665                                    },
666                                );
667                            } else {
668                                if let Some(progress_message) = work.progress.message.as_ref() {
669                                    title.push_str(": ");
670                                    title.push_str(progress_message);
671                                }
672
673                                menu = menu.label(title);
674                            }
675                        }
676                        menu
677                    });
678                    has_work.then_some(menu)
679                }),
680        )
681    }
682}
683
684impl StatusItemView for ActivityIndicator {
685    fn set_active_pane_item(
686        &mut self,
687        _: Option<&dyn ItemHandle>,
688        _window: &mut Window,
689        _: &mut Context<Self>,
690    ) {
691    }
692}
693
694#[cfg(test)]
695mod tests {
696    use gpui::SemanticVersion;
697    use release_channel::AppCommitSha;
698
699    use super::*;
700
701    #[test]
702    fn test_version_tooltip_message() {
703        let message = ActivityIndicator::version_tooltip_message(&VersionCheckType::Semantic(
704            SemanticVersion::new(1, 0, 0),
705        ));
706
707        assert_eq!(message, "Version: 1.0.0");
708
709        let message = ActivityIndicator::version_tooltip_message(&VersionCheckType::Sha(
710            AppCommitSha::new("14d9a4189f058d8736339b06ff2340101eaea5af".to_string()),
711        ));
712
713        assert_eq!(message, "Version: 14d9a41…");
714    }
715}