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