title_bar.rs

   1mod application_menu;
   2pub mod collab;
   3mod onboarding_banner;
   4mod plan_chip;
   5mod title_bar_settings;
   6mod update_version;
   7
   8#[cfg(feature = "stories")]
   9mod stories;
  10
  11use crate::application_menu::{ApplicationMenu, show_menus};
  12use crate::plan_chip::PlanChip;
  13pub use platform_title_bar::{
  14    self, DraggedWindowTab, MergeAllWindows, MoveTabToNewWindow, PlatformTitleBar,
  15    ShowNextWindowTab, ShowPreviousWindowTab,
  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_api_types::Plan;
  27use feature_flags::{AgentV2FeatureFlag, FeatureFlagAppExt};
  28use gpui::{
  29    Action, AnyElement, App, Context, Corner, Element, Empty, Entity, Focusable,
  30    InteractiveElement, IntoElement, MouseButton, ParentElement, Render,
  31    StatefulInteractiveElement, Styled, Subscription, WeakEntity, Window, actions, div,
  32};
  33use onboarding_banner::OnboardingBanner;
  34use project::{
  35    DisableAiSettings, Project, git_store::GitStoreEvent, trusted_worktrees::TrustedWorktrees,
  36};
  37use remote::RemoteConnectionOptions;
  38use settings::Settings;
  39use settings::WorktreeId;
  40use std::sync::Arc;
  41use theme::ActiveTheme;
  42use title_bar_settings::TitleBarSettings;
  43use ui::{
  44    Avatar, ButtonLike, ContextMenu, IconWithIndicator, Indicator, PopoverMenu, PopoverMenuHandle,
  45    TintColor, Tooltip, prelude::*, utils::platform_title_bar_height,
  46};
  47use update_version::UpdateVersion;
  48use util::ResultExt;
  49use workspace::{
  50    MultiWorkspace, ToggleWorkspaceSidebar, ToggleWorktreeSecurity, Workspace,
  51    notifications::NotifyResultExt,
  52};
  53use zed_actions::OpenRemote;
  54
  55pub use onboarding_banner::restore_banner;
  56
  57#[cfg(feature = "stories")]
  58pub use stories::*;
  59
  60const MAX_PROJECT_NAME_LENGTH: usize = 40;
  61const MAX_BRANCH_NAME_LENGTH: usize = 40;
  62const MAX_SHORT_SHA_LENGTH: usize = 8;
  63
  64actions!(
  65    collab,
  66    [
  67        /// Toggles the user menu dropdown.
  68        ToggleUserMenu,
  69        /// Toggles the project menu dropdown.
  70        ToggleProjectMenu,
  71        /// Switches to a different git branch.
  72        SwitchBranch,
  73        /// A debug action to simulate an update being available to test the update banner UI.
  74        SimulateUpdateAvailable
  75    ]
  76);
  77
  78pub fn init(cx: &mut App) {
  79    platform_title_bar::PlatformTitleBar::init(cx);
  80
  81    cx.observe_new(|workspace: &mut Workspace, window, cx| {
  82        let Some(window) = window else {
  83            return;
  84        };
  85        let item = cx.new(|cx| TitleBar::new("title-bar", workspace, window, cx));
  86        workspace.set_titlebar_item(item.into(), window, cx);
  87
  88        workspace.register_action(|workspace, _: &SimulateUpdateAvailable, _window, cx| {
  89            if let Some(titlebar) = workspace
  90                .titlebar_item()
  91                .and_then(|item| item.downcast::<TitleBar>().ok())
  92            {
  93                titlebar.update(cx, |titlebar, cx| {
  94                    titlebar.toggle_update_simulation(cx);
  95                });
  96            }
  97        });
  98
  99        #[cfg(not(target_os = "macos"))]
 100        workspace.register_action(|workspace, action: &OpenApplicationMenu, window, cx| {
 101            if let Some(titlebar) = workspace
 102                .titlebar_item()
 103                .and_then(|item| item.downcast::<TitleBar>().ok())
 104            {
 105                titlebar.update(cx, |titlebar, cx| {
 106                    if let Some(ref menu) = titlebar.application_menu {
 107                        menu.update(cx, |menu, cx| menu.open_menu(action, window, cx));
 108                    }
 109                });
 110            }
 111        });
 112
 113        #[cfg(not(target_os = "macos"))]
 114        workspace.register_action(|workspace, _: &ActivateMenuRight, window, cx| {
 115            if let Some(titlebar) = workspace
 116                .titlebar_item()
 117                .and_then(|item| item.downcast::<TitleBar>().ok())
 118            {
 119                titlebar.update(cx, |titlebar, cx| {
 120                    if let Some(ref menu) = titlebar.application_menu {
 121                        menu.update(cx, |menu, cx| {
 122                            menu.navigate_menus_in_direction(ActivateDirection::Right, window, cx)
 123                        });
 124                    }
 125                });
 126            }
 127        });
 128
 129        #[cfg(not(target_os = "macos"))]
 130        workspace.register_action(|workspace, _: &ActivateMenuLeft, window, cx| {
 131            if let Some(titlebar) = workspace
 132                .titlebar_item()
 133                .and_then(|item| item.downcast::<TitleBar>().ok())
 134            {
 135                titlebar.update(cx, |titlebar, cx| {
 136                    if let Some(ref menu) = titlebar.application_menu {
 137                        menu.update(cx, |menu, cx| {
 138                            menu.navigate_menus_in_direction(ActivateDirection::Left, window, cx)
 139                        });
 140                    }
 141                });
 142            }
 143        });
 144    })
 145    .detach();
 146}
 147
 148pub struct TitleBar {
 149    platform_titlebar: Entity<PlatformTitleBar>,
 150    project: Entity<Project>,
 151    user_store: Entity<UserStore>,
 152    client: Arc<Client>,
 153    workspace: WeakEntity<Workspace>,
 154    application_menu: Option<Entity<ApplicationMenu>>,
 155    _subscriptions: Vec<Subscription>,
 156    banner: Entity<OnboardingBanner>,
 157    update_version: Entity<UpdateVersion>,
 158    screen_share_popover_handle: PopoverMenuHandle<ContextMenu>,
 159}
 160
 161impl Render for TitleBar {
 162    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 163        let title_bar_settings = *TitleBarSettings::get_global(cx);
 164
 165        let show_menus = show_menus(cx);
 166
 167        let mut children = Vec::new();
 168
 169        children.push(
 170            h_flex()
 171                .gap_0p5()
 172                .map(|title_bar| {
 173                    let mut render_project_items = title_bar_settings.show_branch_name
 174                        || title_bar_settings.show_project_items;
 175                    title_bar
 176                        .children(self.render_workspace_sidebar_toggle(window, cx))
 177                        .when_some(
 178                            self.application_menu.clone().filter(|_| !show_menus),
 179                            |title_bar, menu| {
 180                                render_project_items &=
 181                                    !menu.update(cx, |menu, cx| menu.all_menus_shown(cx));
 182                                title_bar.child(menu)
 183                            },
 184                        )
 185                        .children(self.render_restricted_mode(cx))
 186                        .when(render_project_items, |title_bar| {
 187                            title_bar
 188                                .when(title_bar_settings.show_project_items, |title_bar| {
 189                                    title_bar
 190                                        .children(self.render_project_host(cx))
 191                                        .child(self.render_project_name(cx))
 192                                })
 193                                .when(title_bar_settings.show_branch_name, |title_bar| {
 194                                    title_bar.children(self.render_project_branch(cx))
 195                                })
 196                        })
 197                })
 198                .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 199                .into_any_element(),
 200        );
 201
 202        children.push(self.render_collaborator_list(window, cx).into_any_element());
 203
 204        if title_bar_settings.show_onboarding_banner {
 205            children.push(self.banner.clone().into_any_element())
 206        }
 207
 208        let status = self.client.status();
 209        let status = &*status.borrow();
 210        let user = self.user_store.read(cx).current_user();
 211
 212        let signed_in = user.is_some();
 213
 214        children.push(
 215            h_flex()
 216                .map(|this| {
 217                    if signed_in {
 218                        this.pr_1p5()
 219                    } else {
 220                        this.pr_1()
 221                    }
 222                })
 223                .gap_1()
 224                .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 225                .children(self.render_call_controls(window, cx))
 226                .children(self.render_connection_status(status, cx))
 227                .child(self.update_version.clone())
 228                .when(
 229                    user.is_none() && TitleBarSettings::get_global(cx).show_sign_in,
 230                    |this| this.child(self.render_sign_in_button(cx)),
 231                )
 232                .child(self.render_organization_menu_button(cx))
 233                .when(TitleBarSettings::get_global(cx).show_user_menu, |this| {
 234                    this.child(self.render_user_menu_button(cx))
 235                })
 236                .into_any_element(),
 237        );
 238
 239        if show_menus {
 240            self.platform_titlebar.update(cx, |this, _| {
 241                this.set_children(
 242                    self.application_menu
 243                        .clone()
 244                        .map(|menu| menu.into_any_element()),
 245                );
 246            });
 247
 248            let height = platform_title_bar_height(window);
 249            let title_bar_color = self.platform_titlebar.update(cx, |platform_titlebar, cx| {
 250                platform_titlebar.title_bar_color(window, cx)
 251            });
 252
 253            v_flex()
 254                .w_full()
 255                .child(self.platform_titlebar.clone().into_any_element())
 256                .child(
 257                    h_flex()
 258                        .bg(title_bar_color)
 259                        .h(height)
 260                        .pl_2()
 261                        .justify_between()
 262                        .w_full()
 263                        .children(children),
 264                )
 265                .into_any_element()
 266        } else {
 267            self.platform_titlebar.update(cx, |this, _| {
 268                this.set_children(children);
 269            });
 270            self.platform_titlebar.clone().into_any_element()
 271        }
 272    }
 273}
 274
 275impl TitleBar {
 276    pub fn new(
 277        id: impl Into<ElementId>,
 278        workspace: &Workspace,
 279        window: &mut Window,
 280        cx: &mut Context<Self>,
 281    ) -> Self {
 282        let project = workspace.project().clone();
 283        let git_store = project.read(cx).git_store().clone();
 284        let user_store = workspace.app_state().user_store.clone();
 285        let client = workspace.app_state().client.clone();
 286        let active_call = ActiveCall::global(cx);
 287
 288        let platform_style = PlatformStyle::platform();
 289        let application_menu = match platform_style {
 290            PlatformStyle::Mac => {
 291                if option_env!("ZED_USE_CROSS_PLATFORM_MENU").is_some() {
 292                    Some(cx.new(|cx| ApplicationMenu::new(window, cx)))
 293                } else {
 294                    None
 295                }
 296            }
 297            PlatformStyle::Linux | PlatformStyle::Windows => {
 298                Some(cx.new(|cx| ApplicationMenu::new(window, cx)))
 299            }
 300        };
 301
 302        let mut subscriptions = Vec::new();
 303        subscriptions.push(
 304            cx.observe(&workspace.weak_handle().upgrade().unwrap(), |_, _, cx| {
 305                cx.notify()
 306            }),
 307        );
 308        subscriptions.push(
 309            cx.subscribe(&project, |this, _, event: &project::Event, cx| {
 310                if let project::Event::BufferEdited = event {
 311                    // Clear override when user types in any editor,
 312                    // so the title bar reflects the project they're actually working in
 313                    this.clear_active_worktree_override(cx);
 314                    cx.notify();
 315                }
 316            }),
 317        );
 318        subscriptions.push(cx.observe(&active_call, |this, _, cx| this.active_call_changed(cx)));
 319        subscriptions.push(cx.observe_window_activation(window, Self::window_activation_changed));
 320        subscriptions.push(
 321            cx.subscribe(&git_store, move |this, _, event, cx| match event {
 322                GitStoreEvent::ActiveRepositoryChanged(_) => {
 323                    // Clear override when focus-derived active repo changes
 324                    // (meaning the user focused a file from a different project)
 325                    this.clear_active_worktree_override(cx);
 326                    cx.notify();
 327                }
 328                GitStoreEvent::RepositoryUpdated(_, _, true) => {
 329                    cx.notify();
 330                }
 331                _ => {}
 332            }),
 333        );
 334        subscriptions.push(cx.observe(&user_store, |_a, _, cx| cx.notify()));
 335        if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 336            subscriptions.push(cx.subscribe(&trusted_worktrees, |_, _, _, cx| {
 337                cx.notify();
 338            }));
 339        }
 340
 341        let banner = cx.new(|cx| {
 342            OnboardingBanner::new(
 343                "ACP Claude Code Onboarding",
 344                IconName::AiClaude,
 345                "Claude Agent",
 346                Some("Introducing:".into()),
 347                zed_actions::agent::OpenClaudeAgentOnboardingModal.boxed_clone(),
 348                cx,
 349            )
 350            // When updating this to a non-AI feature release, remove this line.
 351            .visible_when(|cx| !project::DisableAiSettings::get_global(cx).disable_ai)
 352        });
 353
 354        let update_version = cx.new(|cx| UpdateVersion::new(cx));
 355        let platform_titlebar = cx.new(|cx| PlatformTitleBar::new(id, cx));
 356
 357        // Set up observer to sync sidebar state from MultiWorkspace to PlatformTitleBar.
 358        {
 359            let platform_titlebar = platform_titlebar.clone();
 360            let window_handle = window.window_handle();
 361            cx.spawn(async move |this: WeakEntity<TitleBar>, cx| {
 362                let Some(multi_workspace_handle) = window_handle.downcast::<MultiWorkspace>()
 363                else {
 364                    return;
 365                };
 366
 367                let _ = cx.update(|cx| {
 368                    let Ok(multi_workspace) = multi_workspace_handle.entity(cx) else {
 369                        return;
 370                    };
 371
 372                    let is_open = multi_workspace.read(cx).is_sidebar_open();
 373                    let has_notifications = multi_workspace.read(cx).sidebar_has_notifications(cx);
 374                    let is_singleton = multi_workspace.read(cx).is_singleton();
 375                    platform_titlebar.update(cx, |titlebar, cx| {
 376                        titlebar.set_workspace_sidebar_open(is_open, cx);
 377                        titlebar.set_sidebar_has_notifications(has_notifications, cx);
 378                        titlebar.set_singleton(is_singleton, cx);
 379                    });
 380
 381                    let platform_titlebar = platform_titlebar.clone();
 382                    let subscription = cx.observe(&multi_workspace, move |mw, cx| {
 383                        let is_open = mw.read(cx).is_sidebar_open();
 384                        let has_notifications = mw.read(cx).sidebar_has_notifications(cx);
 385                        let is_singleton = mw.read(cx).is_singleton();
 386                        platform_titlebar.update(cx, |titlebar, cx| {
 387                            titlebar.set_workspace_sidebar_open(is_open, cx);
 388                            titlebar.set_sidebar_has_notifications(has_notifications, cx);
 389                            titlebar.set_singleton(is_singleton, cx);
 390                        });
 391                    });
 392
 393                    if let Some(this) = this.upgrade() {
 394                        this.update(cx, |this, _| {
 395                            this._subscriptions.push(subscription);
 396                        });
 397                    }
 398                });
 399            })
 400            .detach();
 401        }
 402
 403        Self {
 404            platform_titlebar,
 405            application_menu,
 406            workspace: workspace.weak_handle(),
 407            project,
 408            user_store,
 409            client,
 410            _subscriptions: subscriptions,
 411            banner,
 412            update_version,
 413            screen_share_popover_handle: PopoverMenuHandle::default(),
 414        }
 415    }
 416
 417    fn worktree_count(&self, cx: &App) -> usize {
 418        self.project.read(cx).visible_worktrees(cx).count()
 419    }
 420
 421    fn toggle_update_simulation(&mut self, cx: &mut Context<Self>) {
 422        self.update_version
 423            .update(cx, |banner, cx| banner.update_simulation(cx));
 424        cx.notify();
 425    }
 426
 427    /// Returns the worktree to display in the title bar.
 428    /// - If there's an override set on the workspace, use that (if still valid)
 429    /// - Otherwise, derive from the active repository
 430    /// - Fall back to the first visible worktree
 431    pub fn effective_active_worktree(&self, cx: &App) -> Option<Entity<project::Worktree>> {
 432        let project = self.project.read(cx);
 433
 434        if let Some(workspace) = self.workspace.upgrade() {
 435            if let Some(override_id) = workspace.read(cx).active_worktree_override() {
 436                if let Some(worktree) = project.worktree_for_id(override_id, cx) {
 437                    return Some(worktree);
 438                }
 439            }
 440        }
 441
 442        if let Some(repo) = project.active_repository(cx) {
 443            let repo = repo.read(cx);
 444            let repo_path = &repo.work_directory_abs_path;
 445
 446            for worktree in project.visible_worktrees(cx) {
 447                let worktree_path = worktree.read(cx).abs_path();
 448                if worktree_path == *repo_path || worktree_path.starts_with(repo_path.as_ref()) {
 449                    return Some(worktree);
 450                }
 451            }
 452        }
 453
 454        project.visible_worktrees(cx).next()
 455    }
 456
 457    pub fn set_active_worktree_override(
 458        &mut self,
 459        worktree_id: WorktreeId,
 460        cx: &mut Context<Self>,
 461    ) {
 462        if let Some(workspace) = self.workspace.upgrade() {
 463            workspace.update(cx, |workspace, cx| {
 464                workspace.set_active_worktree_override(Some(worktree_id), cx);
 465            });
 466        }
 467        cx.notify();
 468    }
 469
 470    fn clear_active_worktree_override(&mut self, cx: &mut Context<Self>) {
 471        if let Some(workspace) = self.workspace.upgrade() {
 472            workspace.update(cx, |workspace, cx| {
 473                workspace.clear_active_worktree_override(cx);
 474            });
 475        }
 476        cx.notify();
 477    }
 478
 479    fn get_repository_for_worktree(
 480        &self,
 481        worktree: &Entity<project::Worktree>,
 482        cx: &App,
 483    ) -> Option<Entity<project::git_store::Repository>> {
 484        let project = self.project.read(cx);
 485        let git_store = project.git_store().read(cx);
 486        let worktree_path = worktree.read(cx).abs_path();
 487
 488        for repo in git_store.repositories().values() {
 489            let repo_path = &repo.read(cx).work_directory_abs_path;
 490            if worktree_path == *repo_path || worktree_path.starts_with(repo_path.as_ref()) {
 491                return Some(repo.clone());
 492            }
 493        }
 494
 495        None
 496    }
 497
 498    fn render_remote_project_connection(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
 499        let workspace = self.workspace.clone();
 500
 501        let options = self.project.read(cx).remote_connection_options(cx)?;
 502        let host: SharedString = options.display_name().into();
 503
 504        let (nickname, tooltip_title, icon) = match options {
 505            RemoteConnectionOptions::Ssh(options) => (
 506                options.nickname.map(|nick| nick.into()),
 507                "Remote Project",
 508                IconName::Server,
 509            ),
 510            RemoteConnectionOptions::Wsl(_) => (None, "Remote Project", IconName::Linux),
 511            RemoteConnectionOptions::Docker(_dev_container_connection) => {
 512                (None, "Dev Container", IconName::Box)
 513            }
 514            #[cfg(any(test, feature = "test-support"))]
 515            RemoteConnectionOptions::Mock(_) => (None, "Mock Remote Project", IconName::Server),
 516        };
 517
 518        let nickname = nickname.unwrap_or_else(|| host.clone());
 519
 520        let (indicator_color, meta) = match self.project.read(cx).remote_connection_state(cx)? {
 521            remote::ConnectionState::Connecting => (Color::Info, format!("Connecting to: {host}")),
 522            remote::ConnectionState::Connected => (Color::Success, format!("Connected to: {host}")),
 523            remote::ConnectionState::HeartbeatMissed => (
 524                Color::Warning,
 525                format!("Connection attempt to {host} missed. Retrying..."),
 526            ),
 527            remote::ConnectionState::Reconnecting => (
 528                Color::Warning,
 529                format!("Lost connection to {host}. Reconnecting..."),
 530            ),
 531            remote::ConnectionState::Disconnected => {
 532                (Color::Error, format!("Disconnected from {host}"))
 533            }
 534        };
 535
 536        let icon_color = match self.project.read(cx).remote_connection_state(cx)? {
 537            remote::ConnectionState::Connecting => Color::Info,
 538            remote::ConnectionState::Connected => Color::Default,
 539            remote::ConnectionState::HeartbeatMissed => Color::Warning,
 540            remote::ConnectionState::Reconnecting => Color::Warning,
 541            remote::ConnectionState::Disconnected => Color::Error,
 542        };
 543
 544        let meta = SharedString::from(meta);
 545
 546        Some(
 547            PopoverMenu::new("remote-project-menu")
 548                .menu(move |window, cx| {
 549                    let workspace_entity = workspace.upgrade()?;
 550                    let fs = workspace_entity.read(cx).project().read(cx).fs().clone();
 551                    Some(recent_projects::RemoteServerProjects::popover(
 552                        fs,
 553                        workspace.clone(),
 554                        false,
 555                        window,
 556                        cx,
 557                    ))
 558                })
 559                .trigger_with_tooltip(
 560                    ButtonLike::new("remote_project")
 561                        .selected_style(ButtonStyle::Tinted(TintColor::Accent))
 562                        .child(
 563                            h_flex()
 564                                .gap_2()
 565                                .max_w_32()
 566                                .child(
 567                                    IconWithIndicator::new(
 568                                        Icon::new(icon).size(IconSize::Small).color(icon_color),
 569                                        Some(Indicator::dot().color(indicator_color)),
 570                                    )
 571                                    .indicator_border_color(Some(
 572                                        cx.theme().colors().title_bar_background,
 573                                    ))
 574                                    .into_any_element(),
 575                                )
 576                                .child(Label::new(nickname).size(LabelSize::Small).truncate()),
 577                        ),
 578                    move |_window, cx| {
 579                        Tooltip::with_meta(
 580                            tooltip_title,
 581                            Some(&OpenRemote {
 582                                from_existing_connection: false,
 583                                create_new_window: false,
 584                            }),
 585                            meta.clone(),
 586                            cx,
 587                        )
 588                    },
 589                )
 590                .anchor(gpui::Corner::TopLeft)
 591                .into_any_element(),
 592        )
 593    }
 594
 595    pub fn render_restricted_mode(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
 596        let has_restricted_worktrees = TrustedWorktrees::try_get_global(cx)
 597            .map(|trusted_worktrees| {
 598                trusted_worktrees
 599                    .read(cx)
 600                    .has_restricted_worktrees(&self.project.read(cx).worktree_store(), cx)
 601            })
 602            .unwrap_or(false);
 603        if !has_restricted_worktrees {
 604            return None;
 605        }
 606
 607        let button = Button::new("restricted_mode_trigger", "Restricted Mode")
 608            .style(ButtonStyle::Tinted(TintColor::Warning))
 609            .label_size(LabelSize::Small)
 610            .color(Color::Warning)
 611            .icon(IconName::Warning)
 612            .icon_color(Color::Warning)
 613            .icon_size(IconSize::Small)
 614            .icon_position(IconPosition::Start)
 615            .tooltip(|_, cx| {
 616                Tooltip::with_meta(
 617                    "You're in Restricted Mode",
 618                    Some(&ToggleWorktreeSecurity),
 619                    "Mark this project as trusted and unlock all features",
 620                    cx,
 621                )
 622            })
 623            .on_click({
 624                cx.listener(move |this, _, window, cx| {
 625                    this.workspace
 626                        .update(cx, |workspace, cx| {
 627                            workspace.show_worktree_trust_security_modal(true, window, cx)
 628                        })
 629                        .log_err();
 630                })
 631            });
 632
 633        if cfg!(macos_sdk_26) {
 634            // Make up for Tahoe's traffic light buttons having less spacing around them
 635            Some(div().child(button).ml_0p5().into_any_element())
 636        } else {
 637            Some(button.into_any_element())
 638        }
 639    }
 640
 641    pub fn render_project_host(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
 642        if self.project.read(cx).is_via_remote_server() {
 643            return self.render_remote_project_connection(cx);
 644        }
 645
 646        if self.project.read(cx).is_disconnected(cx) {
 647            return Some(
 648                Button::new("disconnected", "Disconnected")
 649                    .disabled(true)
 650                    .color(Color::Disabled)
 651                    .label_size(LabelSize::Small)
 652                    .into_any_element(),
 653            );
 654        }
 655
 656        let host = self.project.read(cx).host()?;
 657        let host_user = self.user_store.read(cx).get_cached_user(host.user_id)?;
 658        let participant_index = self
 659            .user_store
 660            .read(cx)
 661            .participant_indices()
 662            .get(&host_user.id)?;
 663
 664        Some(
 665            Button::new("project_owner_trigger", host_user.github_login.clone())
 666                .color(Color::Player(participant_index.0))
 667                .label_size(LabelSize::Small)
 668                .tooltip(move |_, cx| {
 669                    let tooltip_title = format!(
 670                        "{} is sharing this project. Click to follow.",
 671                        host_user.github_login
 672                    );
 673
 674                    Tooltip::with_meta(tooltip_title, None, "Click to Follow", cx)
 675                })
 676                .on_click({
 677                    let host_peer_id = host.peer_id;
 678                    cx.listener(move |this, _, window, cx| {
 679                        this.workspace
 680                            .update(cx, |workspace, cx| {
 681                                workspace.follow(host_peer_id, window, cx);
 682                            })
 683                            .log_err();
 684                    })
 685                })
 686                .into_any_element(),
 687        )
 688    }
 689
 690    fn render_workspace_sidebar_toggle(
 691        &self,
 692        _window: &mut Window,
 693        cx: &mut Context<Self>,
 694    ) -> Option<AnyElement> {
 695        if !cx.has_flag::<AgentV2FeatureFlag>() || DisableAiSettings::get_global(cx).disable_ai {
 696            return None;
 697        }
 698
 699        if self.platform_titlebar.read(cx).is_singleton() {
 700            return None;
 701        }
 702
 703        let is_sidebar_open = self.platform_titlebar.read(cx).is_workspace_sidebar_open();
 704
 705        if is_sidebar_open {
 706            return None;
 707        }
 708
 709        let has_notifications = self.platform_titlebar.read(cx).sidebar_has_notifications();
 710
 711        Some(
 712            IconButton::new("toggle-workspace-sidebar", IconName::WorkspaceNavClosed)
 713                .icon_size(IconSize::Small)
 714                .when(has_notifications, |button| {
 715                    button
 716                        .indicator(Indicator::dot().color(Color::Accent))
 717                        .indicator_border_color(Some(cx.theme().colors().title_bar_background))
 718                })
 719                .tooltip(move |_, cx| {
 720                    Tooltip::for_action("Open Threads Sidebar", &ToggleWorkspaceSidebar, cx)
 721                })
 722                .on_click(|_, window, cx| {
 723                    window.dispatch_action(ToggleWorkspaceSidebar.boxed_clone(), cx);
 724                })
 725                .into_any_element(),
 726        )
 727    }
 728
 729    pub fn render_project_name(&self, cx: &mut Context<Self>) -> impl IntoElement {
 730        let workspace = self.workspace.clone();
 731
 732        let name = self.effective_active_worktree(cx).map(|worktree| {
 733            let worktree = worktree.read(cx);
 734            SharedString::from(worktree.root_name().as_unix_str().to_string())
 735        });
 736
 737        let is_project_selected = name.is_some();
 738
 739        let display_name = if let Some(ref name) = name {
 740            util::truncate_and_trailoff(name, MAX_PROJECT_NAME_LENGTH)
 741        } else {
 742            "Open Recent Project".to_string()
 743        };
 744
 745        let focus_handle = workspace
 746            .upgrade()
 747            .map(|w| w.read(cx).focus_handle(cx))
 748            .unwrap_or_else(|| cx.focus_handle());
 749
 750        PopoverMenu::new("recent-projects-menu")
 751            .menu(move |window, cx| {
 752                Some(recent_projects::RecentProjects::popover(
 753                    workspace.clone(),
 754                    false,
 755                    focus_handle.clone(),
 756                    window,
 757                    cx,
 758                ))
 759            })
 760            .trigger_with_tooltip(
 761                Button::new("project_name_trigger", display_name)
 762                    .label_size(LabelSize::Small)
 763                    .when(self.worktree_count(cx) > 1, |this| {
 764                        this.icon(IconName::ChevronDown)
 765                            .icon_color(Color::Muted)
 766                            .icon_size(IconSize::XSmall)
 767                    })
 768                    .selected_style(ButtonStyle::Tinted(TintColor::Accent))
 769                    .when(!is_project_selected, |s| s.color(Color::Muted)),
 770                move |_window, cx| {
 771                    Tooltip::for_action(
 772                        "Recent Projects",
 773                        &zed_actions::OpenRecent {
 774                            create_new_window: false,
 775                        },
 776                        cx,
 777                    )
 778                },
 779            )
 780            .anchor(gpui::Corner::TopLeft)
 781            .into_any_element()
 782    }
 783
 784    pub fn render_project_branch(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> {
 785        let effective_worktree = self.effective_active_worktree(cx)?;
 786        let repository = self.get_repository_for_worktree(&effective_worktree, cx)?;
 787        let workspace = self.workspace.upgrade()?;
 788
 789        let (branch_name, icon_info) = {
 790            let repo = repository.read(cx);
 791            let branch_name = repo
 792                .branch
 793                .as_ref()
 794                .map(|branch| branch.name())
 795                .map(|name| util::truncate_and_trailoff(name, MAX_BRANCH_NAME_LENGTH))
 796                .or_else(|| {
 797                    repo.head_commit.as_ref().map(|commit| {
 798                        commit
 799                            .sha
 800                            .chars()
 801                            .take(MAX_SHORT_SHA_LENGTH)
 802                            .collect::<String>()
 803                    })
 804                });
 805
 806            let status = repo.status_summary();
 807            let tracked = status.index + status.worktree;
 808            let icon_info = if status.conflict > 0 {
 809                (IconName::Warning, Color::VersionControlConflict)
 810            } else if tracked.modified > 0 {
 811                (IconName::SquareDot, Color::VersionControlModified)
 812            } else if tracked.added > 0 || status.untracked > 0 {
 813                (IconName::SquarePlus, Color::VersionControlAdded)
 814            } else if tracked.deleted > 0 {
 815                (IconName::SquareMinus, Color::VersionControlDeleted)
 816            } else {
 817                (IconName::GitBranch, Color::Muted)
 818            };
 819
 820            (branch_name, icon_info)
 821        };
 822
 823        let settings = TitleBarSettings::get_global(cx);
 824
 825        let effective_repository = Some(repository);
 826
 827        Some(
 828            PopoverMenu::new("branch-menu")
 829                .menu(move |window, cx| {
 830                    Some(git_ui::git_picker::popover(
 831                        workspace.downgrade(),
 832                        effective_repository.clone(),
 833                        git_ui::git_picker::GitPickerTab::Branches,
 834                        gpui::rems(34.),
 835                        window,
 836                        cx,
 837                    ))
 838                })
 839                .trigger_with_tooltip(
 840                    Button::new("project_branch_trigger", branch_name?)
 841                        .selected_style(ButtonStyle::Tinted(TintColor::Accent))
 842                        .label_size(LabelSize::Small)
 843                        .color(Color::Muted)
 844                        .when(settings.show_branch_icon, |branch_button| {
 845                            let (icon, icon_color) = icon_info;
 846                            branch_button
 847                                .icon(icon)
 848                                .icon_position(IconPosition::Start)
 849                                .icon_color(icon_color)
 850                                .icon_size(IconSize::Indicator)
 851                        }),
 852                    move |_window, cx| {
 853                        Tooltip::with_meta(
 854                            "Recent Branches",
 855                            Some(&zed_actions::git::Branch),
 856                            "Local branches only",
 857                            cx,
 858                        )
 859                    },
 860                )
 861                .anchor(gpui::Corner::TopLeft),
 862        )
 863    }
 864
 865    fn window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 866        if window.is_window_active() {
 867            ActiveCall::global(cx)
 868                .update(cx, |call, cx| call.set_location(Some(&self.project), cx))
 869                .detach_and_log_err(cx);
 870        } else if cx.active_window().is_none() {
 871            ActiveCall::global(cx)
 872                .update(cx, |call, cx| call.set_location(None, cx))
 873                .detach_and_log_err(cx);
 874        }
 875        self.workspace
 876            .update(cx, |workspace, cx| {
 877                workspace.update_active_view_for_followers(window, cx);
 878            })
 879            .ok();
 880    }
 881
 882    fn active_call_changed(&mut self, cx: &mut Context<Self>) {
 883        cx.notify();
 884    }
 885
 886    fn share_project(&mut self, cx: &mut Context<Self>) {
 887        let active_call = ActiveCall::global(cx);
 888        let project = self.project.clone();
 889        active_call
 890            .update(cx, |call, cx| call.share_project(project, cx))
 891            .detach_and_log_err(cx);
 892    }
 893
 894    fn unshare_project(&mut self, _: &mut Window, cx: &mut Context<Self>) {
 895        let active_call = ActiveCall::global(cx);
 896        let project = self.project.clone();
 897        active_call
 898            .update(cx, |call, cx| call.unshare_project(project, cx))
 899            .log_err();
 900    }
 901
 902    fn render_connection_status(
 903        &self,
 904        status: &client::Status,
 905        cx: &mut Context<Self>,
 906    ) -> Option<AnyElement> {
 907        match status {
 908            client::Status::ConnectionError
 909            | client::Status::ConnectionLost
 910            | client::Status::Reauthenticating
 911            | client::Status::Reconnecting
 912            | client::Status::ReconnectionError { .. } => Some(
 913                div()
 914                    .id("disconnected")
 915                    .child(Icon::new(IconName::Disconnected).size(IconSize::Small))
 916                    .tooltip(Tooltip::text("Disconnected"))
 917                    .into_any_element(),
 918            ),
 919            client::Status::UpgradeRequired => {
 920                let auto_updater = auto_update::AutoUpdater::get(cx);
 921                let label = match auto_updater.map(|auto_update| auto_update.read(cx).status()) {
 922                    Some(AutoUpdateStatus::Updated { .. }) => "Please restart Zed to Collaborate",
 923                    Some(AutoUpdateStatus::Installing { .. })
 924                    | Some(AutoUpdateStatus::Downloading { .. })
 925                    | Some(AutoUpdateStatus::Checking) => "Updating...",
 926                    Some(AutoUpdateStatus::Idle)
 927                    | Some(AutoUpdateStatus::Errored { .. })
 928                    | None => "Please update Zed to Collaborate",
 929                };
 930
 931                Some(
 932                    Button::new("connection-status", label)
 933                        .label_size(LabelSize::Small)
 934                        .on_click(|_, window, cx| {
 935                            if let Some(auto_updater) = auto_update::AutoUpdater::get(cx)
 936                                && auto_updater.read(cx).status().is_updated()
 937                            {
 938                                workspace::reload(cx);
 939                                return;
 940                            }
 941                            auto_update::check(&Default::default(), window, cx);
 942                        })
 943                        .into_any_element(),
 944                )
 945            }
 946            _ => None,
 947        }
 948    }
 949
 950    pub fn render_sign_in_button(&mut self, _: &mut Context<Self>) -> Button {
 951        let client = self.client.clone();
 952        let workspace = self.workspace.clone();
 953        Button::new("sign_in", "Sign In")
 954            .label_size(LabelSize::Small)
 955            .on_click(move |_, window, cx| {
 956                let client = client.clone();
 957                let workspace = workspace.clone();
 958                window
 959                    .spawn(cx, async move |mut cx| {
 960                        client
 961                            .sign_in_with_optional_connect(true, cx)
 962                            .await
 963                            .notify_workspace_async_err(workspace, &mut cx);
 964                    })
 965                    .detach();
 966            })
 967    }
 968
 969    pub fn render_organization_menu_button(&mut self, cx: &mut Context<Self>) -> AnyElement {
 970        let Some(organization) = self.user_store.read(cx).current_organization() else {
 971            return Empty.into_any_element();
 972        };
 973
 974        PopoverMenu::new("organization-menu")
 975            .anchor(Corner::TopRight)
 976            .menu({
 977                let user_store = self.user_store.clone();
 978                move |window, cx| {
 979                    ContextMenu::build(window, cx, |mut menu, _window, cx| {
 980                        menu = menu.header("Organizations").separator();
 981
 982                        let current_organization = user_store.read(cx).current_organization();
 983
 984                        for organization in user_store.read(cx).organizations() {
 985                            let organization = organization.clone();
 986                            let plan = user_store.read(cx).plan_for_organization(&organization.id);
 987
 988                            let is_current =
 989                                current_organization
 990                                    .as_ref()
 991                                    .is_some_and(|current_organization| {
 992                                        current_organization.id == organization.id
 993                                    });
 994
 995                            menu = menu.custom_entry(
 996                                {
 997                                    let organization = organization.clone();
 998                                    move |_window, _cx| {
 999                                        h_flex()
1000                                            .w_full()
1001                                            .gap_1()
1002                                            .child(
1003                                                div()
1004                                                    .flex_none()
1005                                                    .when(!is_current, |parent| parent.invisible())
1006                                                    .child(Icon::new(IconName::Check)),
1007                                            )
1008                                            .child(
1009                                                h_flex()
1010                                                    .w_full()
1011                                                    .gap_3()
1012                                                    .justify_between()
1013                                                    .child(Label::new(&organization.name))
1014                                                    .child(PlanChip::new(
1015                                                        plan.unwrap_or(Plan::ZedFree),
1016                                                    )),
1017                                            )
1018                                            .into_any_element()
1019                                    }
1020                                },
1021                                {
1022                                    let user_store = user_store.clone();
1023                                    let organization = organization.clone();
1024                                    move |_window, cx| {
1025                                        user_store.update(cx, |user_store, cx| {
1026                                            user_store
1027                                                .set_current_organization(organization.clone(), cx);
1028                                        });
1029                                    }
1030                                },
1031                            );
1032                        }
1033
1034                        menu
1035                    })
1036                    .into()
1037                }
1038            })
1039            .trigger_with_tooltip(
1040                Button::new("organization-menu", &organization.name)
1041                    .selected_style(ButtonStyle::Tinted(TintColor::Accent))
1042                    .label_size(LabelSize::Small),
1043                Tooltip::text("Toggle Organization Menu"),
1044            )
1045            .anchor(gpui::Corner::TopRight)
1046            .into_any_element()
1047    }
1048
1049    pub fn render_user_menu_button(&mut self, cx: &mut Context<Self>) -> impl Element {
1050        let show_update_badge = self.update_version.read(cx).show_update_in_menu_bar();
1051
1052        let user_store = self.user_store.read(cx);
1053        let user = user_store.current_user();
1054
1055        let user_avatar = user.as_ref().map(|u| u.avatar_uri.clone());
1056        let user_login = user.as_ref().map(|u| u.github_login.clone());
1057
1058        let is_signed_in = user.is_some();
1059
1060        let has_subscription_period = user_store.subscription_period().is_some();
1061        let plan = user_store.plan().filter(|_| {
1062            // Since the user might be on the legacy free plan we filter based on whether we have a subscription period.
1063            has_subscription_period
1064        });
1065
1066        PopoverMenu::new("user-menu")
1067            .anchor(Corner::TopRight)
1068            .menu(move |window, cx| {
1069                ContextMenu::build(window, cx, |menu, _, _cx| {
1070                    let user_login = user_login.clone();
1071
1072                    menu.when(is_signed_in, |this| {
1073                        this.custom_entry(
1074                            move |_window, _cx| {
1075                                let user_login = user_login.clone().unwrap_or_default();
1076
1077                                h_flex()
1078                                    .w_full()
1079                                    .justify_between()
1080                                    .child(Label::new(user_login))
1081                                    .child(PlanChip::new(plan.unwrap_or(Plan::ZedFree)))
1082                                    .into_any_element()
1083                            },
1084                            move |_, cx| {
1085                                cx.open_url(&zed_urls::account_url(cx));
1086                            },
1087                        )
1088                        .separator()
1089                    })
1090                    .when(show_update_badge, |this| {
1091                        this.custom_entry(
1092                            move |_window, _cx| {
1093                                h_flex()
1094                                    .w_full()
1095                                    .gap_1()
1096                                    .justify_between()
1097                                    .child(Label::new("Restart to update Zed").color(Color::Accent))
1098                                    .child(
1099                                        Icon::new(IconName::Download)
1100                                            .size(IconSize::Small)
1101                                            .color(Color::Accent),
1102                                    )
1103                                    .into_any_element()
1104                            },
1105                            move |_, cx| {
1106                                workspace::reload(cx);
1107                            },
1108                        )
1109                        .separator()
1110                    })
1111                    .action("Settings", zed_actions::OpenSettings.boxed_clone())
1112                    .action("Keymap", Box::new(zed_actions::OpenKeymap))
1113                    .action(
1114                        "Themes…",
1115                        zed_actions::theme_selector::Toggle::default().boxed_clone(),
1116                    )
1117                    .action(
1118                        "Icon Themes…",
1119                        zed_actions::icon_theme_selector::Toggle::default().boxed_clone(),
1120                    )
1121                    .action(
1122                        "Extensions",
1123                        zed_actions::Extensions::default().boxed_clone(),
1124                    )
1125                    .when(is_signed_in, |this| {
1126                        this.separator()
1127                            .action("Sign Out", client::SignOut.boxed_clone())
1128                    })
1129                })
1130                .into()
1131            })
1132            .map(|this| {
1133                if is_signed_in && TitleBarSettings::get_global(cx).show_user_picture {
1134                    let avatar =
1135                        user_avatar
1136                            .clone()
1137                            .map(|avatar| Avatar::new(avatar))
1138                            .map(|avatar| {
1139                                if show_update_badge {
1140                                    avatar.indicator(
1141                                        div()
1142                                            .absolute()
1143                                            .bottom_0()
1144                                            .right_0()
1145                                            .child(Indicator::dot().color(Color::Accent)),
1146                                    )
1147                                } else {
1148                                    avatar
1149                                }
1150                            });
1151                    this.trigger_with_tooltip(
1152                        ButtonLike::new("user-menu").children(avatar),
1153                        Tooltip::text("Toggle User Menu"),
1154                    )
1155                } else {
1156                    this.trigger_with_tooltip(
1157                        IconButton::new("user-menu", IconName::ChevronDown)
1158                            .icon_size(IconSize::Small),
1159                        Tooltip::text("Toggle User Menu"),
1160                    )
1161                }
1162            })
1163            .anchor(gpui::Corner::TopRight)
1164    }
1165}