title_bar.rs

  1mod application_menu;
  2pub mod collab;
  3mod onboarding_banner;
  4pub mod platform_title_bar;
  5mod platforms;
  6mod system_window_tabs;
  7mod title_bar_settings;
  8
  9#[cfg(feature = "stories")]
 10mod stories;
 11
 12use crate::{
 13    application_menu::{ApplicationMenu, show_menus},
 14    platform_title_bar::PlatformTitleBar,
 15    system_window_tabs::SystemWindowTabs,
 16};
 17
 18#[cfg(not(target_os = "macos"))]
 19use crate::application_menu::{
 20    ActivateDirection, ActivateMenuLeft, ActivateMenuRight, OpenApplicationMenu,
 21};
 22
 23use auto_update::AutoUpdateStatus;
 24use call::ActiveCall;
 25use client::{Client, UserStore, zed_urls};
 26use cloud_llm_client::{Plan, PlanV1, PlanV2};
 27use gpui::{
 28    Action, AnyElement, App, Context, Corner, Element, Entity, Focusable, InteractiveElement,
 29    IntoElement, MouseButton, ParentElement, Render, StatefulInteractiveElement, Styled,
 30    Subscription, WeakEntity, Window, actions, div,
 31};
 32use onboarding_banner::OnboardingBanner;
 33use project::{
 34    Project, WorktreeSettings, git_store::GitStoreEvent, trusted_worktrees::TrustedWorktrees,
 35};
 36use remote::RemoteConnectionOptions;
 37use settings::{Settings, SettingsLocation};
 38use std::sync::Arc;
 39use theme::ActiveTheme;
 40use title_bar_settings::TitleBarSettings;
 41use ui::{
 42    Avatar, ButtonLike, Chip, ContextMenu, IconWithIndicator, Indicator, PopoverMenu,
 43    PopoverMenuHandle, TintColor, Tooltip, prelude::*,
 44};
 45use util::{ResultExt, rel_path::RelPath};
 46use workspace::{ToggleWorktreeSecurity, Workspace, notifications::NotifyResultExt};
 47use zed_actions::{OpenRecent, OpenRemote};
 48
 49pub use onboarding_banner::restore_banner;
 50
 51#[cfg(feature = "stories")]
 52pub use stories::*;
 53
 54const MAX_PROJECT_NAME_LENGTH: usize = 40;
 55const MAX_BRANCH_NAME_LENGTH: usize = 40;
 56const MAX_SHORT_SHA_LENGTH: usize = 8;
 57
 58actions!(
 59    collab,
 60    [
 61        /// Toggles the user menu dropdown.
 62        ToggleUserMenu,
 63        /// Toggles the project menu dropdown.
 64        ToggleProjectMenu,
 65        /// Switches to a different git branch.
 66        SwitchBranch
 67    ]
 68);
 69
 70pub fn init(cx: &mut App) {
 71    SystemWindowTabs::init(cx);
 72
 73    cx.observe_new(|workspace: &mut Workspace, window, cx| {
 74        let Some(window) = window else {
 75            return;
 76        };
 77        let item = cx.new(|cx| TitleBar::new("title-bar", workspace, window, cx));
 78        workspace.set_titlebar_item(item.into(), window, cx);
 79
 80        #[cfg(not(target_os = "macos"))]
 81        workspace.register_action(|workspace, action: &OpenApplicationMenu, window, cx| {
 82            if let Some(titlebar) = workspace
 83                .titlebar_item()
 84                .and_then(|item| item.downcast::<TitleBar>().ok())
 85            {
 86                titlebar.update(cx, |titlebar, cx| {
 87                    if let Some(ref menu) = titlebar.application_menu {
 88                        menu.update(cx, |menu, cx| menu.open_menu(action, window, cx));
 89                    }
 90                });
 91            }
 92        });
 93
 94        #[cfg(not(target_os = "macos"))]
 95        workspace.register_action(|workspace, _: &ActivateMenuRight, window, cx| {
 96            if let Some(titlebar) = workspace
 97                .titlebar_item()
 98                .and_then(|item| item.downcast::<TitleBar>().ok())
 99            {
100                titlebar.update(cx, |titlebar, cx| {
101                    if let Some(ref menu) = titlebar.application_menu {
102                        menu.update(cx, |menu, cx| {
103                            menu.navigate_menus_in_direction(ActivateDirection::Right, window, cx)
104                        });
105                    }
106                });
107            }
108        });
109
110        #[cfg(not(target_os = "macos"))]
111        workspace.register_action(|workspace, _: &ActivateMenuLeft, window, cx| {
112            if let Some(titlebar) = workspace
113                .titlebar_item()
114                .and_then(|item| item.downcast::<TitleBar>().ok())
115            {
116                titlebar.update(cx, |titlebar, cx| {
117                    if let Some(ref menu) = titlebar.application_menu {
118                        menu.update(cx, |menu, cx| {
119                            menu.navigate_menus_in_direction(ActivateDirection::Left, window, cx)
120                        });
121                    }
122                });
123            }
124        });
125    })
126    .detach();
127}
128
129pub struct TitleBar {
130    platform_titlebar: Entity<PlatformTitleBar>,
131    project: Entity<Project>,
132    user_store: Entity<UserStore>,
133    client: Arc<Client>,
134    workspace: WeakEntity<Workspace>,
135    application_menu: Option<Entity<ApplicationMenu>>,
136    _subscriptions: Vec<Subscription>,
137    banner: Entity<OnboardingBanner>,
138    screen_share_popover_handle: PopoverMenuHandle<ContextMenu>,
139}
140
141impl Render for TitleBar {
142    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
143        let title_bar_settings = *TitleBarSettings::get_global(cx);
144
145        let show_menus = show_menus(cx);
146
147        let mut children = Vec::new();
148
149        children.push(
150            h_flex()
151                .gap_1()
152                .map(|title_bar| {
153                    let mut render_project_items = title_bar_settings.show_branch_name
154                        || title_bar_settings.show_project_items;
155                    title_bar
156                        .when_some(
157                            self.application_menu.clone().filter(|_| !show_menus),
158                            |title_bar, menu| {
159                                render_project_items &=
160                                    !menu.update(cx, |menu, cx| menu.all_menus_shown(cx));
161                                title_bar.child(menu)
162                            },
163                        )
164                        .when(render_project_items, |title_bar| {
165                            title_bar
166                                .when(title_bar_settings.show_project_items, |title_bar| {
167                                    title_bar
168                                        .children(self.render_restricted_mode(cx))
169                                        .children(self.render_project_host(cx))
170                                        .child(self.render_project_name(cx))
171                                })
172                                .when(title_bar_settings.show_branch_name, |title_bar| {
173                                    title_bar.children(self.render_project_repo(cx))
174                                })
175                        })
176                })
177                .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
178                .into_any_element(),
179        );
180
181        children.push(self.render_collaborator_list(window, cx).into_any_element());
182
183        if title_bar_settings.show_onboarding_banner {
184            children.push(self.banner.clone().into_any_element())
185        }
186
187        let status = self.client.status();
188        let status = &*status.borrow();
189        let user = self.user_store.read(cx).current_user();
190
191        let signed_in = user.is_some();
192
193        children.push(
194            h_flex()
195                .map(|this| {
196                    if signed_in {
197                        this.pr_1p5()
198                    } else {
199                        this.pr_1()
200                    }
201                })
202                .gap_1()
203                .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
204                .children(self.render_call_controls(window, cx))
205                .children(self.render_connection_status(status, cx))
206                .when(
207                    user.is_none() && TitleBarSettings::get_global(cx).show_sign_in,
208                    |this| this.child(self.render_sign_in_button(cx)),
209                )
210                .when(TitleBarSettings::get_global(cx).show_user_menu, |this| {
211                    this.child(self.render_user_menu_button(cx))
212                })
213                .into_any_element(),
214        );
215
216        if show_menus {
217            self.platform_titlebar.update(cx, |this, _| {
218                this.set_children(
219                    self.application_menu
220                        .clone()
221                        .map(|menu| menu.into_any_element()),
222                );
223            });
224
225            let height = PlatformTitleBar::height(window);
226            let title_bar_color = self.platform_titlebar.update(cx, |platform_titlebar, cx| {
227                platform_titlebar.title_bar_color(window, cx)
228            });
229
230            v_flex()
231                .w_full()
232                .child(self.platform_titlebar.clone().into_any_element())
233                .child(
234                    h_flex()
235                        .bg(title_bar_color)
236                        .h(height)
237                        .pl_2()
238                        .justify_between()
239                        .w_full()
240                        .children(children),
241                )
242                .into_any_element()
243        } else {
244            self.platform_titlebar.update(cx, |this, _| {
245                this.set_children(children);
246            });
247            self.platform_titlebar.clone().into_any_element()
248        }
249    }
250}
251
252impl TitleBar {
253    pub fn new(
254        id: impl Into<ElementId>,
255        workspace: &Workspace,
256        window: &mut Window,
257        cx: &mut Context<Self>,
258    ) -> Self {
259        let project = workspace.project().clone();
260        let git_store = project.read(cx).git_store().clone();
261        let user_store = workspace.app_state().user_store.clone();
262        let client = workspace.app_state().client.clone();
263        let active_call = ActiveCall::global(cx);
264
265        let platform_style = PlatformStyle::platform();
266        let application_menu = match platform_style {
267            PlatformStyle::Mac => {
268                if option_env!("ZED_USE_CROSS_PLATFORM_MENU").is_some() {
269                    Some(cx.new(|cx| ApplicationMenu::new(window, cx)))
270                } else {
271                    None
272                }
273            }
274            PlatformStyle::Linux | PlatformStyle::Windows => {
275                Some(cx.new(|cx| ApplicationMenu::new(window, cx)))
276            }
277        };
278
279        let mut subscriptions = Vec::new();
280        subscriptions.push(
281            cx.observe(&workspace.weak_handle().upgrade().unwrap(), |_, _, cx| {
282                cx.notify()
283            }),
284        );
285        subscriptions.push(cx.subscribe(&project, |_, _, _: &project::Event, cx| cx.notify()));
286        subscriptions.push(cx.observe(&active_call, |this, _, cx| this.active_call_changed(cx)));
287        subscriptions.push(cx.observe_window_activation(window, Self::window_activation_changed));
288        subscriptions.push(
289            cx.subscribe(&git_store, move |_, _, event, cx| match event {
290                GitStoreEvent::ActiveRepositoryChanged(_)
291                | GitStoreEvent::RepositoryUpdated(_, _, true) => {
292                    cx.notify();
293                }
294                _ => {}
295            }),
296        );
297        subscriptions.push(cx.observe(&user_store, |_a, _, cx| cx.notify()));
298        if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
299            subscriptions.push(cx.subscribe(&trusted_worktrees, |_, _, _, cx| {
300                cx.notify();
301            }));
302        }
303
304        let banner = cx.new(|cx| {
305            OnboardingBanner::new(
306                "ACP Claude Code Onboarding",
307                IconName::AiClaude,
308                "Claude Code",
309                Some("Introducing:".into()),
310                zed_actions::agent::OpenClaudeCodeOnboardingModal.boxed_clone(),
311                cx,
312            )
313            // When updating this to a non-AI feature release, remove this line.
314            .visible_when(|cx| !project::DisableAiSettings::get_global(cx).disable_ai)
315        });
316
317        let platform_titlebar = cx.new(|cx| PlatformTitleBar::new(id, cx));
318
319        Self {
320            platform_titlebar,
321            application_menu,
322            workspace: workspace.weak_handle(),
323            project,
324            user_store,
325            client,
326            _subscriptions: subscriptions,
327            banner,
328            screen_share_popover_handle: PopoverMenuHandle::default(),
329        }
330    }
331
332    fn project_name(&self, cx: &Context<Self>) -> Option<SharedString> {
333        self.project
334            .read(cx)
335            .visible_worktrees(cx)
336            .map(|worktree| {
337                let worktree = worktree.read(cx);
338                let settings_location = SettingsLocation {
339                    worktree_id: worktree.id(),
340                    path: RelPath::empty(),
341                };
342
343                let settings = WorktreeSettings::get(Some(settings_location), cx);
344                let name = match &settings.project_name {
345                    Some(name) => name.as_str(),
346                    None => worktree.root_name_str(),
347                };
348                SharedString::new(name)
349            })
350            .next()
351    }
352
353    fn render_remote_project_connection(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
354        let options = self.project.read(cx).remote_connection_options(cx)?;
355        let host: SharedString = options.display_name().into();
356
357        let (nickname, tooltip_title, icon) = match options {
358            RemoteConnectionOptions::Ssh(options) => (
359                options.nickname.map(|nick| nick.into()),
360                "Remote Project",
361                IconName::Server,
362            ),
363            RemoteConnectionOptions::Wsl(_) => (None, "Remote Project", IconName::Linux),
364            RemoteConnectionOptions::Docker(_dev_container_connection) => {
365                (None, "Dev Container", IconName::Box)
366            }
367        };
368
369        let nickname = nickname.unwrap_or_else(|| host.clone());
370
371        let (indicator_color, meta) = match self.project.read(cx).remote_connection_state(cx)? {
372            remote::ConnectionState::Connecting => (Color::Info, format!("Connecting to: {host}")),
373            remote::ConnectionState::Connected => (Color::Success, format!("Connected to: {host}")),
374            remote::ConnectionState::HeartbeatMissed => (
375                Color::Warning,
376                format!("Connection attempt to {host} missed. Retrying..."),
377            ),
378            remote::ConnectionState::Reconnecting => (
379                Color::Warning,
380                format!("Lost connection to {host}. Reconnecting..."),
381            ),
382            remote::ConnectionState::Disconnected => {
383                (Color::Error, format!("Disconnected from {host}"))
384            }
385        };
386
387        let icon_color = match self.project.read(cx).remote_connection_state(cx)? {
388            remote::ConnectionState::Connecting => Color::Info,
389            remote::ConnectionState::Connected => Color::Default,
390            remote::ConnectionState::HeartbeatMissed => Color::Warning,
391            remote::ConnectionState::Reconnecting => Color::Warning,
392            remote::ConnectionState::Disconnected => Color::Error,
393        };
394
395        let meta = SharedString::from(meta);
396
397        Some(
398            ButtonLike::new("ssh-server-icon")
399                .child(
400                    h_flex()
401                        .gap_2()
402                        .max_w_32()
403                        .child(
404                            IconWithIndicator::new(
405                                Icon::new(icon).size(IconSize::Small).color(icon_color),
406                                Some(Indicator::dot().color(indicator_color)),
407                            )
408                            .indicator_border_color(Some(cx.theme().colors().title_bar_background))
409                            .into_any_element(),
410                        )
411                        .child(Label::new(nickname).size(LabelSize::Small).truncate()),
412                )
413                .tooltip(move |_window, cx| {
414                    Tooltip::with_meta(
415                        tooltip_title,
416                        Some(&OpenRemote {
417                            from_existing_connection: false,
418                            create_new_window: false,
419                        }),
420                        meta.clone(),
421                        cx,
422                    )
423                })
424                .on_click(|_, window, cx| {
425                    window.dispatch_action(
426                        OpenRemote {
427                            from_existing_connection: false,
428                            create_new_window: false,
429                        }
430                        .boxed_clone(),
431                        cx,
432                    );
433                })
434                .into_any_element(),
435        )
436    }
437
438    pub fn render_restricted_mode(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
439        let has_restricted_worktrees = TrustedWorktrees::try_get_global(cx)
440            .map(|trusted_worktrees| {
441                trusted_worktrees
442                    .read(cx)
443                    .has_restricted_worktrees(&self.project.read(cx).worktree_store(), cx)
444            })
445            .unwrap_or(false);
446        if !has_restricted_worktrees {
447            return None;
448        }
449
450        let button = Button::new("restricted_mode_trigger", "Restricted Mode")
451            .style(ButtonStyle::Tinted(TintColor::Warning))
452            .label_size(LabelSize::Small)
453            .color(Color::Warning)
454            .icon(IconName::Warning)
455            .icon_color(Color::Warning)
456            .icon_size(IconSize::Small)
457            .icon_position(IconPosition::Start)
458            .tooltip(|_, cx| {
459                Tooltip::with_meta(
460                    "You're in Restricted Mode",
461                    Some(&ToggleWorktreeSecurity),
462                    "Mark this project as trusted and unlock all features",
463                    cx,
464                )
465            })
466            .on_click({
467                cx.listener(move |this, _, window, cx| {
468                    this.workspace
469                        .update(cx, |workspace, cx| {
470                            workspace.show_worktree_trust_security_modal(true, window, cx)
471                        })
472                        .log_err();
473                })
474            });
475
476        if cfg!(macos_sdk_26) {
477            // Make up for Tahoe's traffic light buttons having less spacing around them
478            Some(div().child(button).ml_0p5().into_any_element())
479        } else {
480            Some(button.into_any_element())
481        }
482    }
483
484    pub fn render_project_host(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
485        if self.project.read(cx).is_via_remote_server() {
486            return self.render_remote_project_connection(cx);
487        }
488
489        if self.project.read(cx).is_disconnected(cx) {
490            return Some(
491                Button::new("disconnected", "Disconnected")
492                    .disabled(true)
493                    .color(Color::Disabled)
494                    .style(ButtonStyle::Subtle)
495                    .label_size(LabelSize::Small)
496                    .into_any_element(),
497            );
498        }
499
500        let host = self.project.read(cx).host()?;
501        let host_user = self.user_store.read(cx).get_cached_user(host.user_id)?;
502        let participant_index = self
503            .user_store
504            .read(cx)
505            .participant_indices()
506            .get(&host_user.id)?;
507        Some(
508            Button::new("project_owner_trigger", host_user.github_login.clone())
509                .color(Color::Player(participant_index.0))
510                .style(ButtonStyle::Subtle)
511                .label_size(LabelSize::Small)
512                .tooltip(Tooltip::text(format!(
513                    "{} is sharing this project. Click to follow.",
514                    host_user.github_login
515                )))
516                .on_click({
517                    let host_peer_id = host.peer_id;
518                    cx.listener(move |this, _, window, cx| {
519                        this.workspace
520                            .update(cx, |workspace, cx| {
521                                workspace.follow(host_peer_id, window, cx);
522                            })
523                            .log_err();
524                    })
525                })
526                .into_any_element(),
527        )
528    }
529
530    pub fn render_project_name(&self, cx: &mut Context<Self>) -> impl IntoElement {
531        let name = self.project_name(cx);
532        let is_project_selected = name.is_some();
533        let name = if let Some(name) = name {
534            util::truncate_and_trailoff(&name, MAX_PROJECT_NAME_LENGTH)
535        } else {
536            "Open Recent Project".to_string()
537        };
538
539        Button::new("project_name_trigger", name)
540            .when(!is_project_selected, |b| b.color(Color::Muted))
541            .style(ButtonStyle::Subtle)
542            .label_size(LabelSize::Small)
543            .tooltip(move |_window, cx| {
544                Tooltip::for_action(
545                    "Recent Projects",
546                    &zed_actions::OpenRecent {
547                        create_new_window: false,
548                    },
549                    cx,
550                )
551            })
552            .on_click(cx.listener(move |_, _, window, cx| {
553                window.dispatch_action(
554                    OpenRecent {
555                        create_new_window: false,
556                    }
557                    .boxed_clone(),
558                    cx,
559                );
560            }))
561    }
562
563    pub fn render_project_repo(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> {
564        let settings = TitleBarSettings::get_global(cx);
565        let repository = self.project.read(cx).active_repository(cx)?;
566        let repository_count = self.project.read(cx).repositories(cx).len();
567        let workspace = self.workspace.upgrade()?;
568        let repo = repository.read(cx);
569        let branch_name = repo
570            .branch
571            .as_ref()
572            .map(|branch| branch.name())
573            .map(|name| util::truncate_and_trailoff(name, MAX_BRANCH_NAME_LENGTH))
574            .or_else(|| {
575                repo.head_commit.as_ref().map(|commit| {
576                    commit
577                        .sha
578                        .chars()
579                        .take(MAX_SHORT_SHA_LENGTH)
580                        .collect::<String>()
581                })
582            })?;
583        let project_name = self.project_name(cx);
584        let repo_name = repo
585            .work_directory_abs_path
586            .file_name()
587            .and_then(|name| name.to_str())
588            .map(SharedString::new);
589        let show_repo_name =
590            repository_count > 1 && repo.branch.is_some() && repo_name != project_name;
591        let branch_name = if let Some(repo_name) = repo_name.filter(|_| show_repo_name) {
592            format!("{repo_name}/{branch_name}")
593        } else {
594            branch_name
595        };
596
597        Some(
598            Button::new("project_branch_trigger", branch_name)
599                .color(Color::Muted)
600                .style(ButtonStyle::Subtle)
601                .label_size(LabelSize::Small)
602                .tooltip(move |_window, cx| {
603                    Tooltip::with_meta(
604                        "Recent Branches",
605                        Some(&zed_actions::git::Branch),
606                        "Local branches only",
607                        cx,
608                    )
609                })
610                .on_click(move |_, window, cx| {
611                    let _ = workspace.update(cx, |this, cx| {
612                        window.focus(&this.active_pane().focus_handle(cx), cx);
613                        window.dispatch_action(zed_actions::git::Branch.boxed_clone(), cx);
614                    });
615                })
616                .when(settings.show_branch_icon, |branch_button| {
617                    let (icon, icon_color) = {
618                        let status = repo.status_summary();
619                        let tracked = status.index + status.worktree;
620                        if status.conflict > 0 {
621                            (IconName::Warning, Color::VersionControlConflict)
622                        } else if tracked.modified > 0 {
623                            (IconName::SquareDot, Color::VersionControlModified)
624                        } else if tracked.added > 0 || status.untracked > 0 {
625                            (IconName::SquarePlus, Color::VersionControlAdded)
626                        } else if tracked.deleted > 0 {
627                            (IconName::SquareMinus, Color::VersionControlDeleted)
628                        } else {
629                            (IconName::GitBranch, Color::Muted)
630                        }
631                    };
632
633                    branch_button
634                        .icon(icon)
635                        .icon_position(IconPosition::Start)
636                        .icon_color(icon_color)
637                        .icon_size(IconSize::Indicator)
638                }),
639        )
640    }
641
642    fn window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
643        if window.is_window_active() {
644            ActiveCall::global(cx)
645                .update(cx, |call, cx| call.set_location(Some(&self.project), cx))
646                .detach_and_log_err(cx);
647        } else if cx.active_window().is_none() {
648            ActiveCall::global(cx)
649                .update(cx, |call, cx| call.set_location(None, cx))
650                .detach_and_log_err(cx);
651        }
652        self.workspace
653            .update(cx, |workspace, cx| {
654                workspace.update_active_view_for_followers(window, cx);
655            })
656            .ok();
657    }
658
659    fn active_call_changed(&mut self, cx: &mut Context<Self>) {
660        cx.notify();
661    }
662
663    fn share_project(&mut self, cx: &mut Context<Self>) {
664        let active_call = ActiveCall::global(cx);
665        let project = self.project.clone();
666        active_call
667            .update(cx, |call, cx| call.share_project(project, cx))
668            .detach_and_log_err(cx);
669    }
670
671    fn unshare_project(&mut self, _: &mut Window, cx: &mut Context<Self>) {
672        let active_call = ActiveCall::global(cx);
673        let project = self.project.clone();
674        active_call
675            .update(cx, |call, cx| call.unshare_project(project, cx))
676            .log_err();
677    }
678
679    fn render_connection_status(
680        &self,
681        status: &client::Status,
682        cx: &mut Context<Self>,
683    ) -> Option<AnyElement> {
684        match status {
685            client::Status::ConnectionError
686            | client::Status::ConnectionLost
687            | client::Status::Reauthenticating
688            | client::Status::Reconnecting
689            | client::Status::ReconnectionError { .. } => Some(
690                div()
691                    .id("disconnected")
692                    .child(Icon::new(IconName::Disconnected).size(IconSize::Small))
693                    .tooltip(Tooltip::text("Disconnected"))
694                    .into_any_element(),
695            ),
696            client::Status::UpgradeRequired => {
697                let auto_updater = auto_update::AutoUpdater::get(cx);
698                let label = match auto_updater.map(|auto_update| auto_update.read(cx).status()) {
699                    Some(AutoUpdateStatus::Updated { .. }) => "Please restart Zed to Collaborate",
700                    Some(AutoUpdateStatus::Installing { .. })
701                    | Some(AutoUpdateStatus::Downloading { .. })
702                    | Some(AutoUpdateStatus::Checking) => "Updating...",
703                    Some(AutoUpdateStatus::Idle)
704                    | Some(AutoUpdateStatus::Errored { .. })
705                    | None => "Please update Zed to Collaborate",
706                };
707
708                Some(
709                    Button::new("connection-status", label)
710                        .label_size(LabelSize::Small)
711                        .on_click(|_, window, cx| {
712                            if let Some(auto_updater) = auto_update::AutoUpdater::get(cx)
713                                && auto_updater.read(cx).status().is_updated()
714                            {
715                                workspace::reload(cx);
716                                return;
717                            }
718                            auto_update::check(&Default::default(), window, cx);
719                        })
720                        .into_any_element(),
721                )
722            }
723            _ => None,
724        }
725    }
726
727    pub fn render_sign_in_button(&mut self, _: &mut Context<Self>) -> Button {
728        let client = self.client.clone();
729        Button::new("sign_in", "Sign in")
730            .label_size(LabelSize::Small)
731            .on_click(move |_, window, cx| {
732                let client = client.clone();
733                window
734                    .spawn(cx, async move |cx| {
735                        client
736                            .sign_in_with_optional_connect(true, cx)
737                            .await
738                            .notify_async_err(cx);
739                    })
740                    .detach();
741            })
742    }
743
744    pub fn render_user_menu_button(&mut self, cx: &mut Context<Self>) -> impl Element {
745        let user_store = self.user_store.read(cx);
746        let user = user_store.current_user();
747
748        let user_avatar = user.as_ref().map(|u| u.avatar_uri.clone());
749        let user_login = user.as_ref().map(|u| u.github_login.clone());
750
751        let is_signed_in = user.is_some();
752
753        let has_subscription_period = user_store.subscription_period().is_some();
754        let plan = user_store.plan().filter(|_| {
755            // Since the user might be on the legacy free plan we filter based on whether we have a subscription period.
756            has_subscription_period
757        });
758
759        let free_chip_bg = cx
760            .theme()
761            .colors()
762            .editor_background
763            .opacity(0.5)
764            .blend(cx.theme().colors().text_accent.opacity(0.05));
765
766        let pro_chip_bg = cx
767            .theme()
768            .colors()
769            .editor_background
770            .opacity(0.5)
771            .blend(cx.theme().colors().text_accent.opacity(0.2));
772
773        PopoverMenu::new("user-menu")
774            .anchor(Corner::TopRight)
775            .menu(move |window, cx| {
776                ContextMenu::build(window, cx, |menu, _, _cx| {
777                    let user_login = user_login.clone();
778
779                    let (plan_name, label_color, bg_color) = match plan {
780                        None | Some(Plan::V1(PlanV1::ZedFree) | Plan::V2(PlanV2::ZedFree)) => {
781                            ("Free", Color::Default, free_chip_bg)
782                        }
783                        Some(Plan::V1(PlanV1::ZedProTrial) | Plan::V2(PlanV2::ZedProTrial)) => {
784                            ("Pro Trial", Color::Accent, pro_chip_bg)
785                        }
786                        Some(Plan::V1(PlanV1::ZedPro) | Plan::V2(PlanV2::ZedPro)) => {
787                            ("Pro", Color::Accent, pro_chip_bg)
788                        }
789                    };
790
791                    menu.when(is_signed_in, |this| {
792                        this.custom_entry(
793                            move |_window, _cx| {
794                                let user_login = user_login.clone().unwrap_or_default();
795
796                                h_flex()
797                                    .w_full()
798                                    .justify_between()
799                                    .child(Label::new(user_login))
800                                    .child(
801                                        Chip::new(plan_name.to_string())
802                                            .bg_color(bg_color)
803                                            .label_color(label_color),
804                                    )
805                                    .into_any_element()
806                            },
807                            move |_, cx| {
808                                cx.open_url(&zed_urls::account_url(cx));
809                            },
810                        )
811                        .separator()
812                    })
813                    .action("Settings", zed_actions::OpenSettings.boxed_clone())
814                    .action("Keymap", Box::new(zed_actions::OpenKeymap))
815                    .action(
816                        "Themes…",
817                        zed_actions::theme_selector::Toggle::default().boxed_clone(),
818                    )
819                    .action(
820                        "Icon Themes…",
821                        zed_actions::icon_theme_selector::Toggle::default().boxed_clone(),
822                    )
823                    .action(
824                        "Extensions",
825                        zed_actions::Extensions::default().boxed_clone(),
826                    )
827                    .when(is_signed_in, |this| {
828                        this.separator()
829                            .action("Sign Out", client::SignOut.boxed_clone())
830                    })
831                })
832                .into()
833            })
834            .map(|this| {
835                if is_signed_in && TitleBarSettings::get_global(cx).show_user_picture {
836                    this.trigger_with_tooltip(
837                        ButtonLike::new("user-menu")
838                            .children(user_avatar.clone().map(|avatar| Avatar::new(avatar))),
839                        Tooltip::text("Toggle User Menu"),
840                    )
841                } else {
842                    this.trigger_with_tooltip(
843                        IconButton::new("user-menu", IconName::ChevronDown)
844                            .icon_size(IconSize::Small),
845                        Tooltip::text("Toggle User Menu"),
846                    )
847                }
848            })
849            .anchor(gpui::Corner::TopRight)
850    }
851}