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::{
 11    BinaryStatus, LanguageRegistry, LanguageServerId, LanguageServerName,
 12    LanguageServerStatusUpdate, ServerHealth,
 13};
 14use project::{
 15    EnvironmentErrorMessage, LanguageServerProgress, LspStoreEvent, Project,
 16    ProjectEnvironmentEvent,
 17    git_store::{GitStoreEvent, Repository},
 18};
 19use smallvec::SmallVec;
 20use std::{
 21    cmp::Reverse,
 22    collections::HashSet,
 23    fmt::Write,
 24    path::Path,
 25    sync::Arc,
 26    time::{Duration, Instant},
 27};
 28use ui::{ButtonLike, ContextMenu, PopoverMenu, PopoverMenuHandle, Tooltip, prelude::*};
 29use util::truncate_and_trailoff;
 30use workspace::{StatusItemView, Workspace, item::ItemHandle};
 31
 32const GIT_OPERATION_DELAY: Duration = Duration::from_millis(0);
 33
 34actions!(
 35    activity_indicator,
 36    [
 37        /// Displays error messages from language servers in the status bar.
 38        ShowErrorMessage
 39    ]
 40);
 41
 42pub enum Event {
 43    ShowStatus {
 44        server_name: LanguageServerName,
 45        status: SharedString,
 46    },
 47}
 48
 49pub struct ActivityIndicator {
 50    statuses: Vec<ServerStatus>,
 51    project: Entity<Project>,
 52    auto_updater: Option<Entity<AutoUpdater>>,
 53    context_menu_handle: PopoverMenuHandle<ContextMenu>,
 54}
 55
 56#[derive(Debug)]
 57struct ServerStatus {
 58    name: LanguageServerName,
 59    status: LanguageServerStatusUpdate,
 60}
 61
 62struct PendingWork<'a> {
 63    language_server_id: LanguageServerId,
 64    progress_token: &'a str,
 65    progress: &'a LanguageServerProgress,
 66}
 67
 68struct Content {
 69    icon: Option<gpui::AnyElement>,
 70    message: String,
 71    on_click:
 72        Option<Arc<dyn Fn(&mut ActivityIndicator, &mut Window, &mut Context<ActivityIndicator>)>>,
 73    tooltip_message: Option<String>,
 74}
 75
 76impl ActivityIndicator {
 77    pub fn new(
 78        workspace: &mut Workspace,
 79        languages: Arc<LanguageRegistry>,
 80        window: &mut Window,
 81        cx: &mut Context<Workspace>,
 82    ) -> Entity<ActivityIndicator> {
 83        let project = workspace.project().clone();
 84        let auto_updater = AutoUpdater::get(cx);
 85        let workspace_handle = cx.entity();
 86        let this = cx.new(|cx| {
 87            let mut status_events = languages.language_server_binary_statuses();
 88            cx.spawn(async move |this, cx| {
 89                while let Some((name, binary_status)) = status_events.next().await {
 90                    this.update(cx, |this: &mut ActivityIndicator, cx| {
 91                        this.statuses.retain(|s| s.name != name);
 92                        this.statuses.push(ServerStatus {
 93                            name,
 94                            status: LanguageServerStatusUpdate::Binary(binary_status),
 95                        });
 96                        cx.notify();
 97                    })?;
 98                }
 99                anyhow::Ok(())
100            })
101            .detach();
102
103            cx.subscribe_in(
104                &workspace_handle,
105                window,
106                |activity_indicator, _, event, window, cx| match event {
107                    workspace::Event::ClearActivityIndicator { .. } => {
108                        if activity_indicator.statuses.pop().is_some() {
109                            activity_indicator.dismiss_error_message(
110                                &DismissErrorMessage,
111                                window,
112                                cx,
113                            );
114                            cx.notify();
115                        }
116                    }
117                    _ => {}
118                },
119            )
120            .detach();
121
122            cx.subscribe(
123                &project.read(cx).lsp_store(),
124                |activity_indicator, _, event, cx| match event {
125                    LspStoreEvent::LanguageServerUpdate { name, message, .. } => {
126                        if let proto::update_language_server::Variant::StatusUpdate(status_update) =
127                            message
128                        {
129                            let Some(name) = name.clone() else {
130                                return;
131                            };
132                            let status = match &status_update.status {
133                                Some(proto::status_update::Status::Binary(binary_status)) => {
134                                    if let Some(binary_status) =
135                                        proto::ServerBinaryStatus::from_i32(*binary_status)
136                                    {
137                                        let binary_status = match binary_status {
138                                            proto::ServerBinaryStatus::None => BinaryStatus::None,
139                                            proto::ServerBinaryStatus::CheckingForUpdate => {
140                                                BinaryStatus::CheckingForUpdate
141                                            }
142                                            proto::ServerBinaryStatus::Downloading => {
143                                                BinaryStatus::Downloading
144                                            }
145                                            proto::ServerBinaryStatus::Starting => {
146                                                BinaryStatus::Starting
147                                            }
148                                            proto::ServerBinaryStatus::Stopping => {
149                                                BinaryStatus::Stopping
150                                            }
151                                            proto::ServerBinaryStatus::Stopped => {
152                                                BinaryStatus::Stopped
153                                            }
154                                            proto::ServerBinaryStatus::Failed => {
155                                                let Some(error) = status_update.message.clone()
156                                                else {
157                                                    return;
158                                                };
159                                                BinaryStatus::Failed { error }
160                                            }
161                                        };
162                                        LanguageServerStatusUpdate::Binary(binary_status)
163                                    } else {
164                                        return;
165                                    }
166                                }
167                                Some(proto::status_update::Status::Health(health_status)) => {
168                                    if let Some(health) =
169                                        proto::ServerHealth::from_i32(*health_status)
170                                    {
171                                        let health = match health {
172                                            proto::ServerHealth::Ok => ServerHealth::Ok,
173                                            proto::ServerHealth::Warning => ServerHealth::Warning,
174                                            proto::ServerHealth::Error => ServerHealth::Error,
175                                        };
176                                        LanguageServerStatusUpdate::Health(
177                                            health,
178                                            status_update.message.clone().map(SharedString::from),
179                                        )
180                                    } else {
181                                        return;
182                                    }
183                                }
184                                None => return,
185                            };
186
187                            activity_indicator.statuses.retain(|s| s.name != name);
188                            activity_indicator
189                                .statuses
190                                .push(ServerStatus { name, status });
191                        }
192                        cx.notify()
193                    }
194                    _ => {}
195                },
196            )
197            .detach();
198
199            cx.subscribe(
200                &project.read(cx).environment().clone(),
201                |_, _, event, cx| match event {
202                    ProjectEnvironmentEvent::ErrorsUpdated => cx.notify(),
203                },
204            )
205            .detach();
206
207            cx.subscribe(
208                &project.read(cx).git_store().clone(),
209                |_, _, event: &GitStoreEvent, cx| match event {
210                    project::git_store::GitStoreEvent::JobsUpdated => cx.notify(),
211                    _ => {}
212                },
213            )
214            .detach();
215
216            if let Some(auto_updater) = auto_updater.as_ref() {
217                cx.observe(auto_updater, |_, _, cx| cx.notify()).detach();
218            }
219
220            Self {
221                statuses: Vec::new(),
222                project: project.clone(),
223                auto_updater,
224                context_menu_handle: Default::default(),
225            }
226        });
227
228        cx.subscribe_in(&this, window, move |_, _, event, window, cx| match event {
229            Event::ShowStatus {
230                server_name,
231                status,
232            } => {
233                let create_buffer = project.update(cx, |project, cx| project.create_buffer(cx));
234                let status = status.clone();
235                let server_name = server_name.clone();
236                cx.spawn_in(window, async move |workspace, cx| {
237                    let buffer = create_buffer.await?;
238                    buffer.update(cx, |buffer, cx| {
239                        buffer.edit(
240                            [(0..0, format!("Language server {server_name}:\n\n{status}"))],
241                            None,
242                            cx,
243                        );
244                        buffer.set_capability(language::Capability::ReadOnly, cx);
245                    })?;
246                    workspace.update_in(cx, |workspace, window, cx| {
247                        workspace.add_item_to_active_pane(
248                            Box::new(cx.new(|cx| {
249                                let mut editor = Editor::for_buffer(buffer, None, window, cx);
250                                editor.set_read_only(true);
251                                editor
252                            })),
253                            None,
254                            true,
255                            window,
256                            cx,
257                        );
258                    })?;
259
260                    anyhow::Ok(())
261                })
262                .detach();
263            }
264        })
265        .detach();
266        this
267    }
268
269    fn show_error_message(&mut self, _: &ShowErrorMessage, _: &mut Window, cx: &mut Context<Self>) {
270        let mut status_message_shown = false;
271        self.statuses.retain(|status| match &status.status {
272            LanguageServerStatusUpdate::Binary(BinaryStatus::Failed { error })
273                if !status_message_shown =>
274            {
275                cx.emit(Event::ShowStatus {
276                    server_name: status.name.clone(),
277                    status: SharedString::from(error),
278                });
279                status_message_shown = true;
280                false
281            }
282            LanguageServerStatusUpdate::Health(
283                ServerHealth::Error | ServerHealth::Warning,
284                status_string,
285            ) if !status_message_shown => match status_string {
286                Some(error) => {
287                    cx.emit(Event::ShowStatus {
288                        server_name: status.name.clone(),
289                        status: error.clone(),
290                    });
291                    status_message_shown = true;
292                    false
293                }
294                None => false,
295            },
296            _ => true,
297        });
298    }
299
300    fn dismiss_error_message(
301        &mut self,
302        _: &DismissErrorMessage,
303        _: &mut Window,
304        cx: &mut Context<Self>,
305    ) {
306        let error_dismissed = if let Some(updater) = &self.auto_updater {
307            updater.update(cx, |updater, cx| updater.dismiss_error(cx))
308        } else {
309            false
310        };
311        if error_dismissed {
312            return;
313        }
314
315        self.project.update(cx, |project, cx| {
316            if project.last_formatting_failure(cx).is_some() {
317                project.reset_last_formatting_failure(cx);
318                true
319            } else {
320                false
321            }
322        });
323    }
324
325    fn pending_language_server_work<'a>(
326        &self,
327        cx: &'a App,
328    ) -> impl Iterator<Item = PendingWork<'a>> {
329        self.project
330            .read(cx)
331            .language_server_statuses(cx)
332            .rev()
333            .filter_map(|(server_id, status)| {
334                if status.pending_work.is_empty() {
335                    None
336                } else {
337                    let mut pending_work = status
338                        .pending_work
339                        .iter()
340                        .map(|(token, progress)| PendingWork {
341                            language_server_id: server_id,
342                            progress_token: token.as_str(),
343                            progress,
344                        })
345                        .collect::<SmallVec<[_; 4]>>();
346                    pending_work.sort_by_key(|work| Reverse(work.progress.last_update_at));
347                    Some(pending_work)
348                }
349            })
350            .flatten()
351    }
352
353    fn pending_environment_errors<'a>(
354        &'a self,
355        cx: &'a App,
356    ) -> impl Iterator<Item = (&'a Arc<Path>, &'a EnvironmentErrorMessage)> {
357        self.project.read(cx).shell_environment_errors(cx)
358    }
359
360    fn content_to_render(&mut self, cx: &mut Context<Self>) -> Option<Content> {
361        // Show if any direnv calls failed
362        if let Some((abs_path, error)) = self.pending_environment_errors(cx).next() {
363            let abs_path = abs_path.clone();
364            return Some(Content {
365                icon: Some(
366                    Icon::new(IconName::Warning)
367                        .size(IconSize::Small)
368                        .into_any_element(),
369                ),
370                message: error.0.clone(),
371                on_click: Some(Arc::new(move |this, window, cx| {
372                    this.project.update(cx, |project, cx| {
373                        project.remove_environment_error(&abs_path, cx);
374                    });
375                    window.dispatch_action(Box::new(workspace::OpenLog), cx);
376                })),
377                tooltip_message: None,
378            });
379        }
380        // Show any language server has pending activity.
381        {
382            let mut pending_work = self.pending_language_server_work(cx);
383            if let Some(PendingWork {
384                progress_token,
385                progress,
386                ..
387            }) = pending_work.next()
388            {
389                let mut message = progress
390                    .title
391                    .as_deref()
392                    .unwrap_or(progress_token)
393                    .to_string();
394
395                if let Some(percentage) = progress.percentage {
396                    write!(&mut message, " ({}%)", percentage).unwrap();
397                }
398
399                if let Some(progress_message) = progress.message.as_ref() {
400                    message.push_str(": ");
401                    message.push_str(progress_message);
402                }
403
404                let additional_work_count = pending_work.count();
405                if additional_work_count > 0 {
406                    write!(&mut message, " + {} more", additional_work_count).unwrap();
407                }
408
409                return Some(Content {
410                    icon: Some(
411                        Icon::new(IconName::ArrowCircle)
412                            .size(IconSize::Small)
413                            .with_animation(
414                                "arrow-circle",
415                                Animation::new(Duration::from_secs(2)).repeat(),
416                                |icon, delta| {
417                                    icon.transform(Transformation::rotate(percentage(delta)))
418                                },
419                            )
420                            .into_any_element(),
421                    ),
422                    message,
423                    on_click: Some(Arc::new(Self::toggle_language_server_work_context_menu)),
424                    tooltip_message: None,
425                });
426            }
427        }
428
429        if let Some(session) = self
430            .project
431            .read(cx)
432            .dap_store()
433            .read(cx)
434            .sessions()
435            .find(|s| !s.read(cx).is_started())
436        {
437            return Some(Content {
438                icon: Some(
439                    Icon::new(IconName::ArrowCircle)
440                        .size(IconSize::Small)
441                        .with_animation(
442                            "arrow-circle",
443                            Animation::new(Duration::from_secs(2)).repeat(),
444                            |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
445                        )
446                        .into_any_element(),
447                ),
448                message: format!("Debug: {}", session.read(cx).adapter()),
449                tooltip_message: session.read(cx).label().map(|label| label.to_string()),
450                on_click: None,
451            });
452        }
453
454        let current_job = self
455            .project
456            .read(cx)
457            .active_repository(cx)
458            .map(|r| r.read(cx))
459            .and_then(Repository::current_job);
460        // Show any long-running git command
461        if let Some(job_info) = current_job
462            && Instant::now() - job_info.start >= GIT_OPERATION_DELAY
463        {
464            return Some(Content {
465                icon: Some(
466                    Icon::new(IconName::ArrowCircle)
467                        .size(IconSize::Small)
468                        .with_animation(
469                            "arrow-circle",
470                            Animation::new(Duration::from_secs(2)).repeat(),
471                            |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
472                        )
473                        .into_any_element(),
474                ),
475                message: job_info.message.into(),
476                on_click: None,
477                tooltip_message: None,
478            });
479        }
480
481        // Show any language server installation info.
482        let mut downloading = SmallVec::<[_; 3]>::new();
483        let mut checking_for_update = SmallVec::<[_; 3]>::new();
484        let mut failed = SmallVec::<[_; 3]>::new();
485        let mut health_messages = SmallVec::<[_; 3]>::new();
486        let mut servers_to_clear_statuses = HashSet::<LanguageServerName>::default();
487        for status in &self.statuses {
488            match &status.status {
489                LanguageServerStatusUpdate::Binary(
490                    BinaryStatus::Starting | BinaryStatus::Stopping,
491                ) => {}
492                LanguageServerStatusUpdate::Binary(BinaryStatus::Stopped) => {
493                    servers_to_clear_statuses.insert(status.name.clone());
494                }
495                LanguageServerStatusUpdate::Binary(BinaryStatus::CheckingForUpdate) => {
496                    checking_for_update.push(status.name.clone());
497                }
498                LanguageServerStatusUpdate::Binary(BinaryStatus::Downloading) => {
499                    downloading.push(status.name.clone());
500                }
501                LanguageServerStatusUpdate::Binary(BinaryStatus::Failed { .. }) => {
502                    failed.push(status.name.clone());
503                }
504                LanguageServerStatusUpdate::Binary(BinaryStatus::None) => {}
505                LanguageServerStatusUpdate::Health(health, server_status) => match server_status {
506                    Some(server_status) => {
507                        health_messages.push((status.name.clone(), *health, server_status.clone()));
508                    }
509                    None => {
510                        servers_to_clear_statuses.insert(status.name.clone());
511                    }
512                },
513            }
514        }
515        self.statuses
516            .retain(|status| !servers_to_clear_statuses.contains(&status.name));
517
518        health_messages.sort_by_key(|(_, health, _)| match health {
519            ServerHealth::Error => 2,
520            ServerHealth::Warning => 1,
521            ServerHealth::Ok => 0,
522        });
523
524        if !downloading.is_empty() {
525            return Some(Content {
526                icon: Some(
527                    Icon::new(IconName::Download)
528                        .size(IconSize::Small)
529                        .into_any_element(),
530                ),
531                message: format!(
532                    "Downloading {}...",
533                    downloading.iter().map(|name| name.as_ref()).fold(
534                        String::new(),
535                        |mut acc, s| {
536                            if !acc.is_empty() {
537                                acc.push_str(", ");
538                            }
539                            acc.push_str(s);
540                            acc
541                        }
542                    )
543                ),
544                on_click: Some(Arc::new(move |this, window, cx| {
545                    this.statuses
546                        .retain(|status| !downloading.contains(&status.name));
547                    this.dismiss_error_message(&DismissErrorMessage, window, cx)
548                })),
549                tooltip_message: None,
550            });
551        }
552
553        if !checking_for_update.is_empty() {
554            return Some(Content {
555                icon: Some(
556                    Icon::new(IconName::Download)
557                        .size(IconSize::Small)
558                        .into_any_element(),
559                ),
560                message: format!(
561                    "Checking for updates to {}...",
562                    checking_for_update.iter().map(|name| name.as_ref()).fold(
563                        String::new(),
564                        |mut acc, s| {
565                            if !acc.is_empty() {
566                                acc.push_str(", ");
567                            }
568                            acc.push_str(s);
569                            acc
570                        }
571                    ),
572                ),
573                on_click: Some(Arc::new(move |this, window, cx| {
574                    this.statuses
575                        .retain(|status| !checking_for_update.contains(&status.name));
576                    this.dismiss_error_message(&DismissErrorMessage, window, cx)
577                })),
578                tooltip_message: None,
579            });
580        }
581
582        if !failed.is_empty() {
583            return Some(Content {
584                icon: Some(
585                    Icon::new(IconName::Warning)
586                        .size(IconSize::Small)
587                        .into_any_element(),
588                ),
589                message: format!(
590                    "Failed to run {}. Click to show error.",
591                    failed
592                        .iter()
593                        .map(|name| name.as_ref())
594                        .fold(String::new(), |mut acc, s| {
595                            if !acc.is_empty() {
596                                acc.push_str(", ");
597                            }
598                            acc.push_str(s);
599                            acc
600                        }),
601                ),
602                on_click: Some(Arc::new(|this, window, cx| {
603                    this.show_error_message(&ShowErrorMessage, window, cx)
604                })),
605                tooltip_message: None,
606            });
607        }
608
609        // Show any formatting failure
610        if let Some(failure) = self.project.read(cx).last_formatting_failure(cx) {
611            return Some(Content {
612                icon: Some(
613                    Icon::new(IconName::Warning)
614                        .size(IconSize::Small)
615                        .into_any_element(),
616                ),
617                message: format!("Formatting failed: {failure}. Click to see logs."),
618                on_click: Some(Arc::new(|indicator, window, cx| {
619                    indicator.project.update(cx, |project, cx| {
620                        project.reset_last_formatting_failure(cx);
621                    });
622                    window.dispatch_action(Box::new(workspace::OpenLog), cx);
623                })),
624                tooltip_message: None,
625            });
626        }
627
628        // Show any health messages for the language servers
629        if let Some((server_name, health, message)) = health_messages.pop() {
630            let health_str = match health {
631                ServerHealth::Ok => format!("({server_name}) "),
632                ServerHealth::Warning => format!("({server_name}) Warning: "),
633                ServerHealth::Error => format!("({server_name}) Error: "),
634            };
635            let single_line_message = message
636                .lines()
637                .filter_map(|line| {
638                    let line = line.trim();
639                    if line.is_empty() { None } else { Some(line) }
640                })
641                .collect::<Vec<_>>()
642                .join(" ");
643            let mut altered_message = single_line_message != message;
644            let truncated_message = truncate_and_trailoff(
645                &single_line_message,
646                MAX_MESSAGE_LEN.saturating_sub(health_str.len()),
647            );
648            altered_message |= truncated_message != single_line_message;
649            let final_message = format!("{health_str}{truncated_message}");
650
651            let tooltip_message = if altered_message {
652                Some(format!("{health_str}{message}"))
653            } else {
654                None
655            };
656
657            return Some(Content {
658                icon: Some(
659                    Icon::new(IconName::Warning)
660                        .size(IconSize::Small)
661                        .into_any_element(),
662                ),
663                message: final_message,
664                tooltip_message,
665                on_click: Some(Arc::new(move |activity_indicator, window, cx| {
666                    if altered_message {
667                        activity_indicator.show_error_message(&ShowErrorMessage, window, cx)
668                    } else {
669                        activity_indicator
670                            .statuses
671                            .retain(|status| status.name != server_name);
672                        cx.notify();
673                    }
674                })),
675            });
676        }
677
678        // Show any application auto-update info.
679        if let Some(updater) = &self.auto_updater {
680            return match &updater.read(cx).status() {
681                AutoUpdateStatus::Checking => Some(Content {
682                    icon: Some(
683                        Icon::new(IconName::Download)
684                            .size(IconSize::Small)
685                            .into_any_element(),
686                    ),
687                    message: "Checking for Zed updates…".to_string(),
688                    on_click: Some(Arc::new(|this, window, cx| {
689                        this.dismiss_error_message(&DismissErrorMessage, window, cx)
690                    })),
691                    tooltip_message: None,
692                }),
693                AutoUpdateStatus::Downloading { version } => Some(Content {
694                    icon: Some(
695                        Icon::new(IconName::Download)
696                            .size(IconSize::Small)
697                            .into_any_element(),
698                    ),
699                    message: "Downloading Zed update…".to_string(),
700                    on_click: Some(Arc::new(|this, window, cx| {
701                        this.dismiss_error_message(&DismissErrorMessage, window, cx)
702                    })),
703                    tooltip_message: Some(Self::version_tooltip_message(version)),
704                }),
705                AutoUpdateStatus::Installing { version } => Some(Content {
706                    icon: Some(
707                        Icon::new(IconName::Download)
708                            .size(IconSize::Small)
709                            .into_any_element(),
710                    ),
711                    message: "Installing Zed update…".to_string(),
712                    on_click: Some(Arc::new(|this, window, cx| {
713                        this.dismiss_error_message(&DismissErrorMessage, window, cx)
714                    })),
715                    tooltip_message: Some(Self::version_tooltip_message(version)),
716                }),
717                AutoUpdateStatus::Updated { version } => Some(Content {
718                    icon: None,
719                    message: "Click to restart and update Zed".to_string(),
720                    on_click: Some(Arc::new(move |_, _, cx| workspace::reload(cx))),
721                    tooltip_message: Some(Self::version_tooltip_message(version)),
722                }),
723                AutoUpdateStatus::Errored => Some(Content {
724                    icon: Some(
725                        Icon::new(IconName::Warning)
726                            .size(IconSize::Small)
727                            .into_any_element(),
728                    ),
729                    message: "Auto update failed".to_string(),
730                    on_click: Some(Arc::new(|this, window, cx| {
731                        this.dismiss_error_message(&DismissErrorMessage, window, cx)
732                    })),
733                    tooltip_message: None,
734                }),
735                AutoUpdateStatus::Idle => None,
736            };
737        }
738
739        if let Some(extension_store) =
740            ExtensionStore::try_global(cx).map(|extension_store| extension_store.read(cx))
741            && let Some(extension_id) = extension_store.outstanding_operations().keys().next()
742        {
743            return Some(Content {
744                icon: Some(
745                    Icon::new(IconName::Download)
746                        .size(IconSize::Small)
747                        .into_any_element(),
748                ),
749                message: format!("Updating {extension_id} extension…"),
750                on_click: Some(Arc::new(|this, window, cx| {
751                    this.dismiss_error_message(&DismissErrorMessage, window, cx)
752                })),
753                tooltip_message: None,
754            });
755        }
756
757        None
758    }
759
760    fn version_tooltip_message(version: &VersionCheckType) -> String {
761        format!("Version: {}", {
762            match version {
763                auto_update::VersionCheckType::Sha(sha) => format!("{}", sha.short()),
764                auto_update::VersionCheckType::Semantic(semantic_version) => {
765                    semantic_version.to_string()
766                }
767            }
768        })
769    }
770
771    fn toggle_language_server_work_context_menu(
772        &mut self,
773        window: &mut Window,
774        cx: &mut Context<Self>,
775    ) {
776        self.context_menu_handle.toggle(window, cx);
777    }
778}
779
780impl EventEmitter<Event> for ActivityIndicator {}
781
782const MAX_MESSAGE_LEN: usize = 50;
783
784impl Render for ActivityIndicator {
785    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
786        let result = h_flex()
787            .id("activity-indicator")
788            .on_action(cx.listener(Self::show_error_message))
789            .on_action(cx.listener(Self::dismiss_error_message));
790        let Some(content) = self.content_to_render(cx) else {
791            return result;
792        };
793        let this = cx.entity().downgrade();
794        let truncate_content = content.message.len() > MAX_MESSAGE_LEN;
795        result.gap_2().child(
796            PopoverMenu::new("activity-indicator-popover")
797                .trigger(
798                    ButtonLike::new("activity-indicator-trigger").child(
799                        h_flex()
800                            .id("activity-indicator-status")
801                            .gap_2()
802                            .children(content.icon)
803                            .map(|button| {
804                                if truncate_content {
805                                    button
806                                        .child(
807                                            Label::new(truncate_and_trailoff(
808                                                &content.message,
809                                                MAX_MESSAGE_LEN,
810                                            ))
811                                            .size(LabelSize::Small),
812                                        )
813                                        .tooltip(Tooltip::text(content.message))
814                                } else {
815                                    button
816                                        .child(Label::new(content.message).size(LabelSize::Small))
817                                        .when_some(
818                                            content.tooltip_message,
819                                            |this, tooltip_message| {
820                                                this.tooltip(Tooltip::text(tooltip_message))
821                                            },
822                                        )
823                                }
824                            })
825                            .when_some(content.on_click, |this, handler| {
826                                this.on_click(cx.listener(move |this, _, window, cx| {
827                                    handler(this, window, cx);
828                                }))
829                                .cursor(CursorStyle::PointingHand)
830                            }),
831                    ),
832                )
833                .anchor(gpui::Corner::BottomLeft)
834                .menu(move |window, cx| {
835                    let strong_this = this.upgrade()?;
836                    let mut has_work = false;
837                    let menu = ContextMenu::build(window, cx, |mut menu, _, cx| {
838                        for work in strong_this.read(cx).pending_language_server_work(cx) {
839                            has_work = true;
840                            let this = this.clone();
841                            let mut title = work
842                                .progress
843                                .title
844                                .as_deref()
845                                .unwrap_or(work.progress_token)
846                                .to_owned();
847
848                            if work.progress.is_cancellable {
849                                let language_server_id = work.language_server_id;
850                                let token = work.progress_token.to_string();
851                                let title = SharedString::from(title);
852                                menu = menu.custom_entry(
853                                    move |_, _| {
854                                        h_flex()
855                                            .w_full()
856                                            .justify_between()
857                                            .child(Label::new(title.clone()))
858                                            .child(Icon::new(IconName::XCircle))
859                                            .into_any_element()
860                                    },
861                                    move |_, cx| {
862                                        this.update(cx, |this, cx| {
863                                            this.project.update(cx, |project, cx| {
864                                                project.cancel_language_server_work(
865                                                    language_server_id,
866                                                    Some(token.clone()),
867                                                    cx,
868                                                );
869                                            });
870                                            this.context_menu_handle.hide(cx);
871                                            cx.notify();
872                                        })
873                                        .ok();
874                                    },
875                                );
876                            } else {
877                                if let Some(progress_message) = work.progress.message.as_ref() {
878                                    title.push_str(": ");
879                                    title.push_str(progress_message);
880                                }
881
882                                menu = menu.label(title);
883                            }
884                        }
885                        menu
886                    });
887                    has_work.then_some(menu)
888                }),
889        )
890    }
891}
892
893impl StatusItemView for ActivityIndicator {
894    fn set_active_pane_item(
895        &mut self,
896        _: Option<&dyn ItemHandle>,
897        _window: &mut Window,
898        _: &mut Context<Self>,
899    ) {
900    }
901}
902
903#[cfg(test)]
904mod tests {
905    use gpui::SemanticVersion;
906    use release_channel::AppCommitSha;
907
908    use super::*;
909
910    #[test]
911    fn test_version_tooltip_message() {
912        let message = ActivityIndicator::version_tooltip_message(&VersionCheckType::Semantic(
913            SemanticVersion::new(1, 0, 0),
914        ));
915
916        assert_eq!(message, "Version: 1.0.0");
917
918        let message = ActivityIndicator::version_tooltip_message(&VersionCheckType::Sha(
919            AppCommitSha::new("14d9a4189f058d8736339b06ff2340101eaea5af".to_string()),
920        ));
921
922        assert_eq!(message, "Version: 14d9a41…");
923    }
924}