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(window, cx))
170                                        .child(self.render_project_name(window, cx))
171                                })
172                                .when(title_bar_settings.show_branch_name, |title_bar| {
173                                    title_bar.children(self.render_project_repo(window, 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(
354        &self,
355        window: &mut Window,
356        cx: &mut Context<Self>,
357    ) -> Option<AnyElement> {
358        let workspace = self.workspace.clone();
359        let is_picker_open = self.is_picker_open(window, cx);
360
361        let options = self.project.read(cx).remote_connection_options(cx)?;
362        let host: SharedString = options.display_name().into();
363
364        let (nickname, tooltip_title, icon) = match options {
365            RemoteConnectionOptions::Ssh(options) => (
366                options.nickname.map(|nick| nick.into()),
367                "Remote Project",
368                IconName::Server,
369            ),
370            RemoteConnectionOptions::Wsl(_) => (None, "Remote Project", IconName::Linux),
371            RemoteConnectionOptions::Docker(_dev_container_connection) => {
372                (None, "Dev Container", IconName::Box)
373            }
374        };
375
376        let nickname = nickname.unwrap_or_else(|| host.clone());
377
378        let (indicator_color, meta) = match self.project.read(cx).remote_connection_state(cx)? {
379            remote::ConnectionState::Connecting => (Color::Info, format!("Connecting to: {host}")),
380            remote::ConnectionState::Connected => (Color::Success, format!("Connected to: {host}")),
381            remote::ConnectionState::HeartbeatMissed => (
382                Color::Warning,
383                format!("Connection attempt to {host} missed. Retrying..."),
384            ),
385            remote::ConnectionState::Reconnecting => (
386                Color::Warning,
387                format!("Lost connection to {host}. Reconnecting..."),
388            ),
389            remote::ConnectionState::Disconnected => {
390                (Color::Error, format!("Disconnected from {host}"))
391            }
392        };
393
394        let icon_color = match self.project.read(cx).remote_connection_state(cx)? {
395            remote::ConnectionState::Connecting => Color::Info,
396            remote::ConnectionState::Connected => Color::Default,
397            remote::ConnectionState::HeartbeatMissed => Color::Warning,
398            remote::ConnectionState::Reconnecting => Color::Warning,
399            remote::ConnectionState::Disconnected => Color::Error,
400        };
401
402        let meta = SharedString::from(meta);
403
404        Some(
405            ButtonLike::new("remote_project")
406                .child(
407                    h_flex()
408                        .gap_2()
409                        .max_w_32()
410                        .child(
411                            IconWithIndicator::new(
412                                Icon::new(icon).size(IconSize::Small).color(icon_color),
413                                Some(Indicator::dot().color(indicator_color)),
414                            )
415                            .indicator_border_color(Some(cx.theme().colors().title_bar_background))
416                            .into_any_element(),
417                        )
418                        .child(Label::new(nickname).size(LabelSize::Small).truncate()),
419                )
420                .when(!is_picker_open, |this| {
421                    this.tooltip(move |_window, cx| {
422                        Tooltip::with_meta(
423                            tooltip_title,
424                            Some(&OpenRemote {
425                                from_existing_connection: false,
426                                create_new_window: false,
427                            }),
428                            meta.clone(),
429                            cx,
430                        )
431                    })
432                })
433                .on_click(move |event, window, cx| {
434                    let position = event.position();
435                    let _ = workspace.update(cx, |this, cx| {
436                        this.set_next_modal_placement(workspace::ModalPlacement::Anchored {
437                            position,
438                        });
439
440                        window.dispatch_action(
441                            OpenRemote {
442                                from_existing_connection: false,
443                                create_new_window: false,
444                            }
445                            .boxed_clone(),
446                            cx,
447                        );
448                    });
449                })
450                .into_any_element(),
451        )
452    }
453
454    pub fn render_restricted_mode(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
455        let has_restricted_worktrees = TrustedWorktrees::try_get_global(cx)
456            .map(|trusted_worktrees| {
457                trusted_worktrees
458                    .read(cx)
459                    .has_restricted_worktrees(&self.project.read(cx).worktree_store(), cx)
460            })
461            .unwrap_or(false);
462        if !has_restricted_worktrees {
463            return None;
464        }
465
466        let button = Button::new("restricted_mode_trigger", "Restricted Mode")
467            .style(ButtonStyle::Tinted(TintColor::Warning))
468            .label_size(LabelSize::Small)
469            .color(Color::Warning)
470            .icon(IconName::Warning)
471            .icon_color(Color::Warning)
472            .icon_size(IconSize::Small)
473            .icon_position(IconPosition::Start)
474            .tooltip(|_, cx| {
475                Tooltip::with_meta(
476                    "You're in Restricted Mode",
477                    Some(&ToggleWorktreeSecurity),
478                    "Mark this project as trusted and unlock all features",
479                    cx,
480                )
481            })
482            .on_click({
483                cx.listener(move |this, _, window, cx| {
484                    this.workspace
485                        .update(cx, |workspace, cx| {
486                            workspace.show_worktree_trust_security_modal(true, window, cx)
487                        })
488                        .log_err();
489                })
490            });
491
492        if cfg!(macos_sdk_26) {
493            // Make up for Tahoe's traffic light buttons having less spacing around them
494            Some(div().child(button).ml_0p5().into_any_element())
495        } else {
496            Some(button.into_any_element())
497        }
498    }
499
500    pub fn render_project_host(
501        &self,
502        window: &mut Window,
503        cx: &mut Context<Self>,
504    ) -> Option<AnyElement> {
505        if self.project.read(cx).is_via_remote_server() {
506            return self.render_remote_project_connection(window, cx);
507        }
508
509        if self.project.read(cx).is_disconnected(cx) {
510            return Some(
511                Button::new("disconnected", "Disconnected")
512                    .disabled(true)
513                    .color(Color::Disabled)
514                    .label_size(LabelSize::Small)
515                    .into_any_element(),
516            );
517        }
518
519        let host = self.project.read(cx).host()?;
520        let host_user = self.user_store.read(cx).get_cached_user(host.user_id)?;
521        let participant_index = self
522            .user_store
523            .read(cx)
524            .participant_indices()
525            .get(&host_user.id)?;
526
527        Some(
528            Button::new("project_owner_trigger", host_user.github_login.clone())
529                .color(Color::Player(participant_index.0))
530                .label_size(LabelSize::Small)
531                .tooltip(move |_, cx| {
532                    let tooltip_title = format!(
533                        "{} is sharing this project. Click to follow.",
534                        host_user.github_login
535                    );
536
537                    Tooltip::with_meta(tooltip_title, None, "Click to Follow", cx)
538                })
539                .on_click({
540                    let host_peer_id = host.peer_id;
541                    cx.listener(move |this, _, window, cx| {
542                        this.workspace
543                            .update(cx, |workspace, cx| {
544                                workspace.follow(host_peer_id, window, cx);
545                            })
546                            .log_err();
547                    })
548                })
549                .into_any_element(),
550        )
551    }
552
553    pub fn render_project_name(
554        &self,
555        window: &mut Window,
556        cx: &mut Context<Self>,
557    ) -> impl IntoElement {
558        let workspace = self.workspace.clone();
559        let is_picker_open = self.is_picker_open(window, cx);
560
561        let name = self.project_name(cx);
562        let is_project_selected = name.is_some();
563        let name = if let Some(name) = name {
564            util::truncate_and_trailoff(&name, MAX_PROJECT_NAME_LENGTH)
565        } else {
566            "Open Recent Project".to_string()
567        };
568
569        Button::new("project_name_trigger", name)
570            .label_size(LabelSize::Small)
571            .when(!is_project_selected, |s| s.color(Color::Muted))
572            .when(!is_picker_open, |this| {
573                this.tooltip(move |_window, cx| {
574                    Tooltip::for_action(
575                        "Recent Projects",
576                        &zed_actions::OpenRecent {
577                            create_new_window: false,
578                        },
579                        cx,
580                    )
581                })
582            })
583            .on_click(move |event, window, cx| {
584                let position = event.position();
585                let _ = workspace.update(cx, |this, _cx| {
586                    this.set_next_modal_placement(workspace::ModalPlacement::Anchored { position })
587                });
588
589                window.dispatch_action(
590                    OpenRecent {
591                        create_new_window: false,
592                    }
593                    .boxed_clone(),
594                    cx,
595                );
596            })
597    }
598
599    pub fn render_project_repo(
600        &self,
601        window: &mut Window,
602        cx: &mut Context<Self>,
603    ) -> Option<impl IntoElement> {
604        let repository = self.project.read(cx).active_repository(cx)?;
605        let repository_count = self.project.read(cx).repositories(cx).len();
606        let workspace = self.workspace.upgrade()?;
607
608        let (branch_name, icon_info) = {
609            let repo = repository.read(cx);
610            let branch_name = repo
611                .branch
612                .as_ref()
613                .map(|branch| branch.name())
614                .map(|name| util::truncate_and_trailoff(name, MAX_BRANCH_NAME_LENGTH))
615                .or_else(|| {
616                    repo.head_commit.as_ref().map(|commit| {
617                        commit
618                            .sha
619                            .chars()
620                            .take(MAX_SHORT_SHA_LENGTH)
621                            .collect::<String>()
622                    })
623                });
624
625            let branch_name = branch_name?;
626
627            let project_name = self.project_name(cx);
628            let repo_name = repo
629                .work_directory_abs_path
630                .file_name()
631                .and_then(|name| name.to_str())
632                .map(SharedString::new);
633            let show_repo_name =
634                repository_count > 1 && repo.branch.is_some() && repo_name != project_name;
635            let branch_name = if let Some(repo_name) = repo_name.filter(|_| show_repo_name) {
636                format!("{repo_name}/{branch_name}")
637            } else {
638                branch_name
639            };
640
641            let status = repo.status_summary();
642            let tracked = status.index + status.worktree;
643            let icon_info = if status.conflict > 0 {
644                (IconName::Warning, Color::VersionControlConflict)
645            } else if tracked.modified > 0 {
646                (IconName::SquareDot, Color::VersionControlModified)
647            } else if tracked.added > 0 || status.untracked > 0 {
648                (IconName::SquarePlus, Color::VersionControlAdded)
649            } else if tracked.deleted > 0 {
650                (IconName::SquareMinus, Color::VersionControlDeleted)
651            } else {
652                (IconName::GitBranch, Color::Muted)
653            };
654
655            (branch_name, icon_info)
656        };
657
658        let is_picker_open = self.is_picker_open(window, cx);
659        let settings = TitleBarSettings::get_global(cx);
660
661        Some(
662            Button::new("project_branch_trigger", branch_name)
663                .label_size(LabelSize::Small)
664                .color(Color::Muted)
665                .when(!is_picker_open, |this| {
666                    this.tooltip(move |_window, cx| {
667                        Tooltip::with_meta(
668                            "Recent Branches",
669                            Some(&zed_actions::git::Branch),
670                            "Local branches only",
671                            cx,
672                        )
673                    })
674                })
675                .when(settings.show_branch_icon, |branch_button| {
676                    let (icon, icon_color) = icon_info;
677                    branch_button
678                        .icon(icon)
679                        .icon_position(IconPosition::Start)
680                        .icon_color(icon_color)
681                        .icon_size(IconSize::Indicator)
682                })
683                .on_click(move |event, window, cx| {
684                    let position = event.position();
685                    let _ = workspace.update(cx, |this, cx| {
686                        this.set_next_modal_placement(workspace::ModalPlacement::Anchored {
687                            position,
688                        });
689                        window.focus(&this.active_pane().focus_handle(cx), cx);
690                        window.dispatch_action(zed_actions::git::Branch.boxed_clone(), cx);
691                    });
692                }),
693        )
694    }
695
696    fn window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
697        if window.is_window_active() {
698            ActiveCall::global(cx)
699                .update(cx, |call, cx| call.set_location(Some(&self.project), cx))
700                .detach_and_log_err(cx);
701        } else if cx.active_window().is_none() {
702            ActiveCall::global(cx)
703                .update(cx, |call, cx| call.set_location(None, cx))
704                .detach_and_log_err(cx);
705        }
706        self.workspace
707            .update(cx, |workspace, cx| {
708                workspace.update_active_view_for_followers(window, cx);
709            })
710            .ok();
711    }
712
713    fn active_call_changed(&mut self, cx: &mut Context<Self>) {
714        cx.notify();
715    }
716
717    fn share_project(&mut self, cx: &mut Context<Self>) {
718        let active_call = ActiveCall::global(cx);
719        let project = self.project.clone();
720        active_call
721            .update(cx, |call, cx| call.share_project(project, cx))
722            .detach_and_log_err(cx);
723    }
724
725    fn unshare_project(&mut self, _: &mut Window, cx: &mut Context<Self>) {
726        let active_call = ActiveCall::global(cx);
727        let project = self.project.clone();
728        active_call
729            .update(cx, |call, cx| call.unshare_project(project, cx))
730            .log_err();
731    }
732
733    fn render_connection_status(
734        &self,
735        status: &client::Status,
736        cx: &mut Context<Self>,
737    ) -> Option<AnyElement> {
738        match status {
739            client::Status::ConnectionError
740            | client::Status::ConnectionLost
741            | client::Status::Reauthenticating
742            | client::Status::Reconnecting
743            | client::Status::ReconnectionError { .. } => Some(
744                div()
745                    .id("disconnected")
746                    .child(Icon::new(IconName::Disconnected).size(IconSize::Small))
747                    .tooltip(Tooltip::text("Disconnected"))
748                    .into_any_element(),
749            ),
750            client::Status::UpgradeRequired => {
751                let auto_updater = auto_update::AutoUpdater::get(cx);
752                let label = match auto_updater.map(|auto_update| auto_update.read(cx).status()) {
753                    Some(AutoUpdateStatus::Updated { .. }) => "Please restart Zed to Collaborate",
754                    Some(AutoUpdateStatus::Installing { .. })
755                    | Some(AutoUpdateStatus::Downloading { .. })
756                    | Some(AutoUpdateStatus::Checking) => "Updating...",
757                    Some(AutoUpdateStatus::Idle)
758                    | Some(AutoUpdateStatus::Errored { .. })
759                    | None => "Please update Zed to Collaborate",
760                };
761
762                Some(
763                    Button::new("connection-status", label)
764                        .label_size(LabelSize::Small)
765                        .on_click(|_, window, cx| {
766                            if let Some(auto_updater) = auto_update::AutoUpdater::get(cx)
767                                && auto_updater.read(cx).status().is_updated()
768                            {
769                                workspace::reload(cx);
770                                return;
771                            }
772                            auto_update::check(&Default::default(), window, cx);
773                        })
774                        .into_any_element(),
775                )
776            }
777            _ => None,
778        }
779    }
780
781    pub fn render_sign_in_button(&mut self, _: &mut Context<Self>) -> Button {
782        let client = self.client.clone();
783        Button::new("sign_in", "Sign In")
784            .label_size(LabelSize::Small)
785            .on_click(move |_, window, cx| {
786                let client = client.clone();
787                window
788                    .spawn(cx, async move |cx| {
789                        client
790                            .sign_in_with_optional_connect(true, cx)
791                            .await
792                            .notify_async_err(cx);
793                    })
794                    .detach();
795            })
796    }
797
798    pub fn render_user_menu_button(&mut self, cx: &mut Context<Self>) -> impl Element {
799        let user_store = self.user_store.read(cx);
800        let user = user_store.current_user();
801
802        let user_avatar = user.as_ref().map(|u| u.avatar_uri.clone());
803        let user_login = user.as_ref().map(|u| u.github_login.clone());
804
805        let is_signed_in = user.is_some();
806
807        let has_subscription_period = user_store.subscription_period().is_some();
808        let plan = user_store.plan().filter(|_| {
809            // Since the user might be on the legacy free plan we filter based on whether we have a subscription period.
810            has_subscription_period
811        });
812
813        let free_chip_bg = cx
814            .theme()
815            .colors()
816            .editor_background
817            .opacity(0.5)
818            .blend(cx.theme().colors().text_accent.opacity(0.05));
819
820        let pro_chip_bg = cx
821            .theme()
822            .colors()
823            .editor_background
824            .opacity(0.5)
825            .blend(cx.theme().colors().text_accent.opacity(0.2));
826
827        PopoverMenu::new("user-menu")
828            .anchor(Corner::TopRight)
829            .menu(move |window, cx| {
830                ContextMenu::build(window, cx, |menu, _, _cx| {
831                    let user_login = user_login.clone();
832
833                    let (plan_name, label_color, bg_color) = match plan {
834                        None | Some(Plan::V1(PlanV1::ZedFree) | Plan::V2(PlanV2::ZedFree)) => {
835                            ("Free", Color::Default, free_chip_bg)
836                        }
837                        Some(Plan::V1(PlanV1::ZedProTrial) | Plan::V2(PlanV2::ZedProTrial)) => {
838                            ("Pro Trial", Color::Accent, pro_chip_bg)
839                        }
840                        Some(Plan::V1(PlanV1::ZedPro) | Plan::V2(PlanV2::ZedPro)) => {
841                            ("Pro", Color::Accent, pro_chip_bg)
842                        }
843                    };
844
845                    menu.when(is_signed_in, |this| {
846                        this.custom_entry(
847                            move |_window, _cx| {
848                                let user_login = user_login.clone().unwrap_or_default();
849
850                                h_flex()
851                                    .w_full()
852                                    .justify_between()
853                                    .child(Label::new(user_login))
854                                    .child(
855                                        Chip::new(plan_name.to_string())
856                                            .bg_color(bg_color)
857                                            .label_color(label_color),
858                                    )
859                                    .into_any_element()
860                            },
861                            move |_, cx| {
862                                cx.open_url(&zed_urls::account_url(cx));
863                            },
864                        )
865                        .separator()
866                    })
867                    .action("Settings", zed_actions::OpenSettings.boxed_clone())
868                    .action("Keymap", Box::new(zed_actions::OpenKeymap))
869                    .action(
870                        "Themes…",
871                        zed_actions::theme_selector::Toggle::default().boxed_clone(),
872                    )
873                    .action(
874                        "Icon Themes…",
875                        zed_actions::icon_theme_selector::Toggle::default().boxed_clone(),
876                    )
877                    .action(
878                        "Extensions",
879                        zed_actions::Extensions::default().boxed_clone(),
880                    )
881                    .when(is_signed_in, |this| {
882                        this.separator()
883                            .action("Sign Out", client::SignOut.boxed_clone())
884                    })
885                })
886                .into()
887            })
888            .map(|this| {
889                if is_signed_in && TitleBarSettings::get_global(cx).show_user_picture {
890                    this.trigger_with_tooltip(
891                        ButtonLike::new("user-menu")
892                            .children(user_avatar.clone().map(|avatar| Avatar::new(avatar))),
893                        Tooltip::text("Toggle User Menu"),
894                    )
895                } else {
896                    this.trigger_with_tooltip(
897                        IconButton::new("user-menu", IconName::ChevronDown)
898                            .icon_size(IconSize::Small),
899                        Tooltip::text("Toggle User Menu"),
900                    )
901                }
902            })
903            .anchor(gpui::Corner::TopRight)
904    }
905
906    fn is_picker_open(&self, window: &mut Window, cx: &mut Context<Self>) -> bool {
907        self.workspace
908            .update(cx, |workspace, cx| workspace.has_active_modal(window, cx))
909            .unwrap_or(false)
910    }
911}