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;
  39
  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, 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 window_project_groups: Vec<_> = self
 737            .multi_workspace
 738            .as_ref()
 739            .and_then(|mw| mw.upgrade())
 740            .map(|mw| mw.read(cx).project_group_keys().cloned().collect())
 741            .unwrap_or_default();
 742
 743        PopoverMenu::new("recent-projects-menu")
 744            .menu(move |window, cx| {
 745                Some(recent_projects::RecentProjects::popover(
 746                    workspace.clone(),
 747                    window_project_groups.clone(),
 748                    false,
 749                    focus_handle.clone(),
 750                    window,
 751                    cx,
 752                ))
 753            })
 754            .trigger_with_tooltip(
 755                Button::new("project_name_trigger", display_name)
 756                    .label_size(LabelSize::Small)
 757                    .when(self.worktree_count(cx) > 1, |this| {
 758                        this.end_icon(
 759                            Icon::new(IconName::ChevronDown)
 760                                .size(IconSize::XSmall)
 761                                .color(Color::Muted),
 762                        )
 763                    })
 764                    .selected_style(ButtonStyle::Tinted(TintColor::Accent))
 765                    .when(!is_project_selected, |s| s.color(Color::Muted)),
 766                move |_window, cx| {
 767                    Tooltip::for_action(
 768                        "Recent Projects",
 769                        &zed_actions::OpenRecent {
 770                            create_new_window: false,
 771                        },
 772                        cx,
 773                    )
 774                },
 775            )
 776            .anchor(gpui::Corner::TopLeft)
 777            .into_any_element()
 778    }
 779
 780    fn render_recent_projects_popover(
 781        &self,
 782        display_name: String,
 783        is_project_selected: bool,
 784        cx: &mut Context<Self>,
 785    ) -> impl IntoElement {
 786        let workspace = self.workspace.clone();
 787
 788        let focus_handle = workspace
 789            .upgrade()
 790            .map(|w| w.read(cx).focus_handle(cx))
 791            .unwrap_or_else(|| cx.focus_handle());
 792
 793        let window_project_groups: Vec<_> = self
 794            .multi_workspace
 795            .as_ref()
 796            .and_then(|mw| mw.upgrade())
 797            .map(|mw| mw.read(cx).project_group_keys().cloned().collect())
 798            .unwrap_or_default();
 799
 800        PopoverMenu::new("sidebar-title-recent-projects-menu")
 801            .menu(move |window, cx| {
 802                Some(recent_projects::RecentProjects::popover(
 803                    workspace.clone(),
 804                    window_project_groups.clone(),
 805                    false,
 806                    focus_handle.clone(),
 807                    window,
 808                    cx,
 809                ))
 810            })
 811            .trigger_with_tooltip(
 812                Button::new("project_name_trigger", display_name)
 813                    .label_size(LabelSize::Small)
 814                    .when(self.worktree_count(cx) > 1, |this| {
 815                        this.end_icon(
 816                            Icon::new(IconName::ChevronDown)
 817                                .size(IconSize::XSmall)
 818                                .color(Color::Muted),
 819                        )
 820                    })
 821                    .selected_style(ButtonStyle::Tinted(TintColor::Accent))
 822                    .when(!is_project_selected, |s| s.color(Color::Muted)),
 823                move |_window, cx| {
 824                    Tooltip::for_action(
 825                        "Recent Projects",
 826                        &zed_actions::OpenRecent {
 827                            create_new_window: false,
 828                        },
 829                        cx,
 830                    )
 831                },
 832            )
 833            .anchor(gpui::Corner::TopLeft)
 834    }
 835
 836    fn render_project_branch(
 837        &self,
 838        repository: Entity<project::git_store::Repository>,
 839        linked_worktree_name: Option<SharedString>,
 840        cx: &mut Context<Self>,
 841    ) -> Option<impl IntoElement> {
 842        let workspace = self.workspace.upgrade()?;
 843
 844        let (branch_name, icon_info) = {
 845            let repo = repository.read(cx);
 846
 847            let branch_name = repo
 848                .branch
 849                .as_ref()
 850                .map(|branch| branch.name())
 851                .map(|name| util::truncate_and_trailoff(name, MAX_BRANCH_NAME_LENGTH))
 852                .or_else(|| {
 853                    repo.head_commit.as_ref().map(|commit| {
 854                        commit
 855                            .sha
 856                            .chars()
 857                            .take(MAX_SHORT_SHA_LENGTH)
 858                            .collect::<String>()
 859                    })
 860                });
 861
 862            let status = repo.status_summary();
 863            let tracked = status.index + status.worktree;
 864            let icon_info = if status.conflict > 0 {
 865                (IconName::Warning, Color::VersionControlConflict)
 866            } else if tracked.modified > 0 {
 867                (IconName::SquareDot, Color::VersionControlModified)
 868            } else if tracked.added > 0 || status.untracked > 0 {
 869                (IconName::SquarePlus, Color::VersionControlAdded)
 870            } else if tracked.deleted > 0 {
 871                (IconName::SquareMinus, Color::VersionControlDeleted)
 872            } else {
 873                (IconName::GitBranch, Color::Muted)
 874            };
 875
 876            (branch_name, icon_info)
 877        };
 878
 879        let branch_name = branch_name?;
 880        let settings = TitleBarSettings::get_global(cx);
 881        let effective_repository = Some(repository);
 882
 883        Some(
 884            PopoverMenu::new("branch-menu")
 885                .menu(move |window, cx| {
 886                    Some(git_ui::git_picker::popover(
 887                        workspace.downgrade(),
 888                        effective_repository.clone(),
 889                        git_ui::git_picker::GitPickerTab::Branches,
 890                        gpui::rems(34.),
 891                        window,
 892                        cx,
 893                    ))
 894                })
 895                .trigger_with_tooltip(
 896                    ButtonLike::new("project_branch_trigger")
 897                        .selected_style(ButtonStyle::Tinted(TintColor::Accent))
 898                        .child(
 899                            h_flex()
 900                                .gap_0p5()
 901                                .when(settings.show_branch_icon, |this| {
 902                                    let (icon, icon_color) = icon_info;
 903                                    this.child(
 904                                        Icon::new(icon).size(IconSize::XSmall).color(icon_color),
 905                                    )
 906                                })
 907                                .when_some(linked_worktree_name.as_ref(), |this, worktree_name| {
 908                                    this.child(
 909                                        Label::new(worktree_name)
 910                                            .size(LabelSize::Small)
 911                                            .color(Color::Muted),
 912                                    )
 913                                    .child(
 914                                        Label::new("/").size(LabelSize::Small).color(
 915                                            Color::Custom(
 916                                                cx.theme().colors().text_muted.opacity(0.4),
 917                                            ),
 918                                        ),
 919                                    )
 920                                })
 921                                .child(
 922                                    Label::new(branch_name)
 923                                        .size(LabelSize::Small)
 924                                        .color(Color::Muted),
 925                                ),
 926                        ),
 927                    move |_window, cx| {
 928                        Tooltip::with_meta(
 929                            "Git Switcher",
 930                            Some(&zed_actions::git::Branch),
 931                            "Worktrees, Branches, and Stashes",
 932                            cx,
 933                        )
 934                    },
 935                )
 936                .anchor(gpui::Corner::TopLeft),
 937        )
 938    }
 939
 940    fn window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 941        if window.is_window_active() {
 942            ActiveCall::global(cx)
 943                .update(cx, |call, cx| call.set_location(Some(&self.project), cx))
 944                .detach_and_log_err(cx);
 945        } else if cx.active_window().is_none() {
 946            ActiveCall::global(cx)
 947                .update(cx, |call, cx| call.set_location(None, cx))
 948                .detach_and_log_err(cx);
 949        }
 950        self.workspace
 951            .update(cx, |workspace, cx| {
 952                workspace.update_active_view_for_followers(window, cx);
 953            })
 954            .ok();
 955    }
 956
 957    fn active_call_changed(&mut self, cx: &mut Context<Self>) {
 958        self.observe_diagnostics(cx);
 959        cx.notify();
 960    }
 961
 962    fn observe_diagnostics(&mut self, cx: &mut Context<Self>) {
 963        let diagnostics = ActiveCall::global(cx)
 964            .read(cx)
 965            .room()
 966            .and_then(|room| room.read(cx).diagnostics().cloned());
 967
 968        if let Some(diagnostics) = diagnostics {
 969            self._diagnostics_subscription = Some(cx.observe(&diagnostics, |_, _, cx| cx.notify()));
 970        } else {
 971            self._diagnostics_subscription = None;
 972        }
 973    }
 974
 975    fn share_project(&mut self, cx: &mut Context<Self>) {
 976        let active_call = ActiveCall::global(cx);
 977        let project = self.project.clone();
 978        active_call
 979            .update(cx, |call, cx| call.share_project(project, cx))
 980            .detach_and_log_err(cx);
 981    }
 982
 983    fn unshare_project(&mut self, _: &mut Window, cx: &mut Context<Self>) {
 984        let active_call = ActiveCall::global(cx);
 985        let project = self.project.clone();
 986        active_call
 987            .update(cx, |call, cx| call.unshare_project(project, cx))
 988            .log_err();
 989    }
 990
 991    fn render_connection_status(
 992        &self,
 993        status: &client::Status,
 994        cx: &mut Context<Self>,
 995    ) -> Option<AnyElement> {
 996        match status {
 997            client::Status::ConnectionError
 998            | client::Status::ConnectionLost
 999            | client::Status::Reauthenticating
1000            | client::Status::Reconnecting
1001            | client::Status::ReconnectionError { .. } => Some(
1002                div()
1003                    .id("disconnected")
1004                    .child(Icon::new(IconName::Disconnected).size(IconSize::Small))
1005                    .tooltip(Tooltip::text("Disconnected"))
1006                    .into_any_element(),
1007            ),
1008            client::Status::UpgradeRequired => {
1009                let auto_updater = auto_update::AutoUpdater::get(cx);
1010                let label = match auto_updater.map(|auto_update| auto_update.read(cx).status()) {
1011                    Some(AutoUpdateStatus::Updated { .. }) => "Please restart Zed to Collaborate",
1012                    Some(AutoUpdateStatus::Installing { .. })
1013                    | Some(AutoUpdateStatus::Downloading { .. })
1014                    | Some(AutoUpdateStatus::Checking) => "Updating...",
1015                    Some(AutoUpdateStatus::Idle)
1016                    | Some(AutoUpdateStatus::Errored { .. })
1017                    | None => "Please update Zed to Collaborate",
1018                };
1019
1020                Some(
1021                    Button::new("connection-status", label)
1022                        .label_size(LabelSize::Small)
1023                        .on_click(|_, window, cx| {
1024                            if let Some(auto_updater) = auto_update::AutoUpdater::get(cx)
1025                                && auto_updater.read(cx).status().is_updated()
1026                            {
1027                                workspace::reload(cx);
1028                                return;
1029                            }
1030                            auto_update::check(&Default::default(), window, cx);
1031                        })
1032                        .into_any_element(),
1033                )
1034            }
1035            _ => None,
1036        }
1037    }
1038
1039    pub fn render_sign_in_button(&mut self, _: &mut Context<Self>) -> Button {
1040        let client = self.client.clone();
1041        let workspace = self.workspace.clone();
1042        Button::new("sign_in", "Sign In")
1043            .label_size(LabelSize::Small)
1044            .on_click(move |_, window, cx| {
1045                let client = client.clone();
1046                let workspace = workspace.clone();
1047                window
1048                    .spawn(cx, async move |mut cx| {
1049                        client
1050                            .sign_in_with_optional_connect(true, cx)
1051                            .await
1052                            .notify_workspace_async_err(workspace, &mut cx);
1053                    })
1054                    .detach();
1055            })
1056    }
1057
1058    pub fn render_user_menu_button(&mut self, cx: &mut Context<Self>) -> impl Element {
1059        let show_update_button = self.update_version.read(cx).show_update_in_menu_bar();
1060
1061        let user_store = self.user_store.clone();
1062        let user_store_read = user_store.read(cx);
1063        let user = user_store_read.current_user();
1064
1065        let user_avatar = user.as_ref().map(|u| u.avatar_uri.clone());
1066        let user_login = user.as_ref().map(|u| u.github_login.clone());
1067
1068        let is_signed_in = user.is_some();
1069
1070        let has_subscription_period = user_store_read.subscription_period().is_some();
1071        let plan = user_store_read.plan().filter(|_| {
1072            // Since the user might be on the legacy free plan we filter based on whether we have a subscription period.
1073            has_subscription_period
1074        });
1075
1076        let has_organization = user_store_read.current_organization().is_some();
1077
1078        let current_organization = user_store_read.current_organization();
1079        let business_organization = current_organization
1080            .as_ref()
1081            .filter(|organization| !organization.is_personal);
1082        let organizations: Vec<_> = user_store_read
1083            .organizations()
1084            .iter()
1085            .map(|org| {
1086                let plan = user_store_read.plan_for_organization(&org.id);
1087                (org.clone(), plan)
1088            })
1089            .collect();
1090
1091        let show_user_picture = TitleBarSettings::get_global(cx).show_user_picture;
1092
1093        let trigger = if is_signed_in && show_user_picture {
1094            let avatar = user_avatar.map(|avatar| Avatar::new(avatar)).map(|avatar| {
1095                if show_update_button {
1096                    avatar.indicator(
1097                        div()
1098                            .absolute()
1099                            .bottom_0()
1100                            .right_0()
1101                            .child(Indicator::dot().color(Color::Accent)),
1102                    )
1103                } else {
1104                    avatar
1105                }
1106            });
1107
1108            ButtonLike::new("user-menu").child(
1109                h_flex()
1110                    .when_some(business_organization, |this, organization| {
1111                        this.gap_2()
1112                            .child(Label::new(&organization.name).size(LabelSize::Small))
1113                    })
1114                    .children(avatar),
1115            )
1116        } else {
1117            ButtonLike::new("user-menu")
1118                .child(Icon::new(IconName::ChevronDown).size(IconSize::Small))
1119        };
1120
1121        PopoverMenu::new("user-menu")
1122            .trigger(trigger)
1123            .menu(move |window, cx| {
1124                let user_login = user_login.clone();
1125                let current_organization = current_organization.clone();
1126                let organizations = organizations.clone();
1127                let user_store = user_store.clone();
1128
1129                ContextMenu::build(window, cx, |menu, _, _cx| {
1130                    menu.when(is_signed_in, |this| {
1131                        let user_login = user_login.clone();
1132                        this.custom_entry(
1133                            move |_window, _cx| {
1134                                let user_login = user_login.clone().unwrap_or_default();
1135
1136                                h_flex()
1137                                    .w_full()
1138                                    .justify_between()
1139                                    .child(Label::new(user_login))
1140                                    .child(PlanChip::new(plan.unwrap_or(Plan::ZedFree)))
1141                                    .into_any_element()
1142                            },
1143                            move |_, cx| {
1144                                cx.open_url(&zed_urls::account_url(cx));
1145                            },
1146                        )
1147                        .separator()
1148                    })
1149                    .when(show_update_button, |this| {
1150                        this.custom_entry(
1151                            move |_window, _cx| {
1152                                h_flex()
1153                                    .w_full()
1154                                    .gap_1()
1155                                    .justify_between()
1156                                    .child(Label::new("Restart to update Zed").color(Color::Accent))
1157                                    .child(
1158                                        Icon::new(IconName::Download)
1159                                            .size(IconSize::Small)
1160                                            .color(Color::Accent),
1161                                    )
1162                                    .into_any_element()
1163                            },
1164                            move |_, cx| {
1165                                workspace::reload(cx);
1166                            },
1167                        )
1168                        .separator()
1169                    })
1170                    .when(has_organization, |this| {
1171                        let mut this = this.header("Organization");
1172
1173                        for (organization, plan) in &organizations {
1174                            let organization = organization.clone();
1175                            let plan = *plan;
1176
1177                            let is_current =
1178                                current_organization
1179                                    .as_ref()
1180                                    .is_some_and(|current_organization| {
1181                                        current_organization.id == organization.id
1182                                    });
1183
1184                            this = this.custom_entry(
1185                                {
1186                                    let organization = organization.clone();
1187                                    move |_window, _cx| {
1188                                        h_flex()
1189                                            .w_full()
1190                                            .gap_4()
1191                                            .justify_between()
1192                                            .child(
1193                                                h_flex()
1194                                                    .gap_1()
1195                                                    .child(Label::new(&organization.name))
1196                                                    .when(is_current, |this| {
1197                                                        this.child(
1198                                                            Icon::new(IconName::Check)
1199                                                                .color(Color::Accent),
1200                                                        )
1201                                                    }),
1202                                            )
1203                                            .child(PlanChip::new(plan.unwrap_or(Plan::ZedFree)))
1204                                            .into_any_element()
1205                                    }
1206                                },
1207                                {
1208                                    let user_store = user_store.clone();
1209                                    let organization = organization.clone();
1210                                    move |_window, cx| {
1211                                        user_store.update(cx, |user_store, cx| {
1212                                            user_store
1213                                                .set_current_organization(organization.clone(), cx);
1214                                        });
1215                                    }
1216                                },
1217                            );
1218                        }
1219
1220                        this.separator()
1221                    })
1222                    .action("Settings", zed_actions::OpenSettings.boxed_clone())
1223                    .action("Keymap", Box::new(zed_actions::OpenKeymap))
1224                    .action(
1225                        "Themes…",
1226                        zed_actions::theme_selector::Toggle::default().boxed_clone(),
1227                    )
1228                    .action(
1229                        "Icon Themes…",
1230                        zed_actions::icon_theme_selector::Toggle::default().boxed_clone(),
1231                    )
1232                    .action(
1233                        "Extensions",
1234                        zed_actions::Extensions::default().boxed_clone(),
1235                    )
1236                    .when(is_signed_in, |this| {
1237                        this.separator()
1238                            .action("Sign Out", client::SignOut.boxed_clone())
1239                    })
1240                })
1241                .into()
1242            })
1243            .anchor(Corner::TopRight)
1244    }
1245}