title_bar.rs

  1mod application_menu;
  2mod collab;
  3mod onboarding_banner;
  4mod platforms;
  5mod window_controls;
  6
  7#[cfg(feature = "stories")]
  8mod stories;
  9
 10use crate::application_menu::ApplicationMenu;
 11
 12#[cfg(not(target_os = "macos"))]
 13use crate::application_menu::{
 14    ActivateDirection, ActivateMenuLeft, ActivateMenuRight, OpenApplicationMenu,
 15};
 16
 17use crate::platforms::{platform_linux, platform_mac, platform_windows};
 18use auto_update::AutoUpdateStatus;
 19use call::ActiveCall;
 20use client::{Client, UserStore};
 21use feature_flags::{FeatureFlagAppExt, ZedPro};
 22use gpui::{
 23    Action, AnyElement, App, Context, Corner, Decorations, Element, Entity, InteractiveElement,
 24    Interactivity, IntoElement, MouseButton, ParentElement, Render, Stateful,
 25    StatefulInteractiveElement, Styled, Subscription, WeakEntity, Window, actions, div, px,
 26};
 27use onboarding_banner::OnboardingBanner;
 28use project::Project;
 29use rpc::proto;
 30use settings::Settings as _;
 31use smallvec::SmallVec;
 32use std::sync::Arc;
 33use theme::ActiveTheme;
 34use ui::{
 35    Avatar, Button, ButtonLike, ButtonStyle, ContextMenu, Icon, IconName, IconSize,
 36    IconWithIndicator, Indicator, PopoverMenu, Tooltip, h_flex, prelude::*,
 37};
 38use util::ResultExt;
 39use workspace::{BottomDockLayout, Workspace, notifications::NotifyResultExt};
 40use zed_actions::{OpenBrowser, OpenRecent, OpenRemote};
 41
 42pub use onboarding_banner::restore_banner;
 43
 44#[cfg(feature = "stories")]
 45pub use stories::*;
 46
 47const MAX_PROJECT_NAME_LENGTH: usize = 40;
 48const MAX_BRANCH_NAME_LENGTH: usize = 40;
 49
 50const BOOK_ONBOARDING: &str = "https://dub.sh/zed-c-onboarding";
 51
 52actions!(collab, [ToggleUserMenu, ToggleProjectMenu, SwitchBranch]);
 53
 54pub fn init(cx: &mut App) {
 55    cx.observe_new(|workspace: &mut Workspace, window, cx| {
 56        let Some(window) = window else {
 57            return;
 58        };
 59        let item = cx.new(|cx| TitleBar::new("title-bar", workspace, window, cx));
 60        workspace.set_titlebar_item(item.into(), window, cx);
 61
 62        #[cfg(not(target_os = "macos"))]
 63        workspace.register_action(|workspace, action: &OpenApplicationMenu, window, cx| {
 64            if let Some(titlebar) = workspace
 65                .titlebar_item()
 66                .and_then(|item| item.downcast::<TitleBar>().ok())
 67            {
 68                titlebar.update(cx, |titlebar, cx| {
 69                    if let Some(ref menu) = titlebar.application_menu {
 70                        menu.update(cx, |menu, cx| menu.open_menu(action, window, cx));
 71                    }
 72                });
 73            }
 74        });
 75
 76        #[cfg(not(target_os = "macos"))]
 77        workspace.register_action(|workspace, _: &ActivateMenuRight, window, cx| {
 78            if let Some(titlebar) = workspace
 79                .titlebar_item()
 80                .and_then(|item| item.downcast::<TitleBar>().ok())
 81            {
 82                titlebar.update(cx, |titlebar, cx| {
 83                    if let Some(ref menu) = titlebar.application_menu {
 84                        menu.update(cx, |menu, cx| {
 85                            menu.navigate_menus_in_direction(ActivateDirection::Right, window, cx)
 86                        });
 87                    }
 88                });
 89            }
 90        });
 91
 92        #[cfg(not(target_os = "macos"))]
 93        workspace.register_action(|workspace, _: &ActivateMenuLeft, window, cx| {
 94            if let Some(titlebar) = workspace
 95                .titlebar_item()
 96                .and_then(|item| item.downcast::<TitleBar>().ok())
 97            {
 98                titlebar.update(cx, |titlebar, cx| {
 99                    if let Some(ref menu) = titlebar.application_menu {
100                        menu.update(cx, |menu, cx| {
101                            menu.navigate_menus_in_direction(ActivateDirection::Left, window, cx)
102                        });
103                    }
104                });
105            }
106        });
107    })
108    .detach();
109}
110
111pub struct TitleBar {
112    platform_style: PlatformStyle,
113    content: Stateful<Div>,
114    children: SmallVec<[AnyElement; 2]>,
115    project: Entity<Project>,
116    user_store: Entity<UserStore>,
117    client: Arc<Client>,
118    workspace: WeakEntity<Workspace>,
119    should_move: bool,
120    application_menu: Option<Entity<ApplicationMenu>>,
121    _subscriptions: Vec<Subscription>,
122    banner: Entity<OnboardingBanner>,
123}
124
125impl Render for TitleBar {
126    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
127        let close_action = Box::new(workspace::CloseWindow);
128        let height = Self::height(window);
129        let supported_controls = window.window_controls();
130        let decorations = window.window_decorations();
131        let titlebar_color = if cfg!(any(target_os = "linux", target_os = "freebsd")) {
132            if window.is_window_active() && !self.should_move {
133                cx.theme().colors().title_bar_background
134            } else {
135                cx.theme().colors().title_bar_inactive_background
136            }
137        } else {
138            cx.theme().colors().title_bar_background
139        };
140
141        h_flex()
142            .id("titlebar")
143            .w_full()
144            .h(height)
145            .map(|this| {
146                if window.is_fullscreen() {
147                    this.pl_2()
148                } else if self.platform_style == PlatformStyle::Mac {
149                    this.pl(px(platform_mac::TRAFFIC_LIGHT_PADDING))
150                } else {
151                    this.pl_2()
152                }
153            })
154            .map(|el| match decorations {
155                Decorations::Server => el,
156                Decorations::Client { tiling, .. } => el
157                    .when(!(tiling.top || tiling.right), |el| {
158                        el.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING)
159                    })
160                    .when(!(tiling.top || tiling.left), |el| {
161                        el.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
162                    })
163                    // this border is to avoid a transparent gap in the rounded corners
164                    .mt(px(-1.))
165                    .border(px(1.))
166                    .border_color(titlebar_color),
167            })
168            .bg(titlebar_color)
169            .content_stretch()
170            .child(
171                div()
172                    .id("titlebar-content")
173                    .flex()
174                    .flex_row()
175                    .items_center()
176                    .justify_between()
177                    .w_full()
178                    // Note: On Windows the title bar behavior is handled by the platform implementation.
179                    .when(self.platform_style != PlatformStyle::Windows, |this| {
180                        this.on_click(|event, window, _| {
181                            if event.up.click_count == 2 {
182                                window.zoom_window();
183                            }
184                        })
185                    })
186                    .child(
187                        h_flex()
188                            .gap_1()
189                            .map(|title_bar| {
190                                let mut render_project_items = true;
191                                title_bar
192                                    .when_some(self.application_menu.clone(), |title_bar, menu| {
193                                        render_project_items = !menu.read(cx).all_menus_shown();
194                                        title_bar.child(menu)
195                                    })
196                                    .when(render_project_items, |title_bar| {
197                                        title_bar
198                                            .children(self.render_project_host(cx))
199                                            .child(self.render_project_name(cx))
200                                            .children(self.render_project_branch(cx))
201                                    })
202                            })
203                            .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()),
204                    )
205                    .child(self.render_collaborator_list(window, cx))
206                    .child(self.banner.clone())
207                    .child(
208                        h_flex()
209                            .gap_1()
210                            .pr_1()
211                            .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
212                            .children(self.render_call_controls(window, cx))
213                            .child(self.render_bottom_dock_layout_menu(cx))
214                            .map(|el| {
215                                let status = self.client.status();
216                                let status = &*status.borrow();
217                                if matches!(status, client::Status::Connected { .. }) {
218                                    el.child(self.render_user_menu_button(cx))
219                                } else {
220                                    el.children(self.render_connection_status(status, cx))
221                                        .child(self.render_sign_in_button(cx))
222                                        .child(self.render_user_menu_button(cx))
223                                }
224                            }),
225                    ),
226            )
227            .when(!window.is_fullscreen(), |title_bar| {
228                match self.platform_style {
229                    PlatformStyle::Mac => title_bar,
230                    PlatformStyle::Linux => {
231                        if matches!(decorations, Decorations::Client { .. }) {
232                            title_bar
233                                .child(platform_linux::LinuxWindowControls::new(close_action))
234                                .when(supported_controls.window_menu, |titlebar| {
235                                    titlebar.on_mouse_down(
236                                        gpui::MouseButton::Right,
237                                        move |ev, window, _| window.show_window_menu(ev.position),
238                                    )
239                                })
240                                .on_mouse_move(cx.listener(move |this, _ev, window, _| {
241                                    if this.should_move {
242                                        this.should_move = false;
243                                        window.start_window_move();
244                                    }
245                                }))
246                                .on_mouse_down_out(cx.listener(move |this, _ev, _window, _cx| {
247                                    this.should_move = false;
248                                }))
249                                .on_mouse_up(
250                                    gpui::MouseButton::Left,
251                                    cx.listener(move |this, _ev, _window, _cx| {
252                                        this.should_move = false;
253                                    }),
254                                )
255                                .on_mouse_down(
256                                    gpui::MouseButton::Left,
257                                    cx.listener(move |this, _ev, _window, _cx| {
258                                        this.should_move = true;
259                                    }),
260                                )
261                        } else {
262                            title_bar
263                        }
264                    }
265                    PlatformStyle::Windows => {
266                        title_bar.child(platform_windows::WindowsWindowControls::new(height))
267                    }
268                }
269            })
270    }
271}
272
273impl TitleBar {
274    pub fn new(
275        id: impl Into<ElementId>,
276        workspace: &Workspace,
277        window: &mut Window,
278        cx: &mut Context<Self>,
279    ) -> Self {
280        let project = workspace.project().clone();
281        let user_store = workspace.app_state().user_store.clone();
282        let client = workspace.app_state().client.clone();
283        let active_call = ActiveCall::global(cx);
284
285        let platform_style = PlatformStyle::platform();
286        let application_menu = match platform_style {
287            PlatformStyle::Mac => {
288                if option_env!("ZED_USE_CROSS_PLATFORM_MENU").is_some() {
289                    Some(cx.new(|cx| ApplicationMenu::new(window, cx)))
290                } else {
291                    None
292                }
293            }
294            PlatformStyle::Linux | PlatformStyle::Windows => {
295                Some(cx.new(|cx| ApplicationMenu::new(window, cx)))
296            }
297        };
298
299        let mut subscriptions = Vec::new();
300        subscriptions.push(
301            cx.observe(&workspace.weak_handle().upgrade().unwrap(), |_, _, cx| {
302                cx.notify()
303            }),
304        );
305        subscriptions.push(cx.subscribe(&project, |_, _, _: &project::Event, cx| cx.notify()));
306        subscriptions.push(cx.observe(&active_call, |this, _, cx| this.active_call_changed(cx)));
307        subscriptions.push(cx.observe_window_activation(window, Self::window_activation_changed));
308        subscriptions.push(cx.observe(&user_store, |_, _, cx| cx.notify()));
309
310        let banner = cx.new(|cx| {
311            OnboardingBanner::new(
312                "Git Onboarding",
313                IconName::GitBranchSmall,
314                "Git Support",
315                None,
316                zed_actions::OpenGitIntegrationOnboarding.boxed_clone(),
317                cx,
318            )
319        });
320
321        Self {
322            platform_style,
323            content: div().id(id.into()),
324            children: SmallVec::new(),
325            application_menu,
326            workspace: workspace.weak_handle(),
327            should_move: false,
328            project,
329            user_store,
330            client,
331            _subscriptions: subscriptions,
332            banner,
333        }
334    }
335
336    #[cfg(not(target_os = "windows"))]
337    pub fn height(window: &mut Window) -> Pixels {
338        (1.75 * window.rem_size()).max(px(34.))
339    }
340
341    #[cfg(target_os = "windows")]
342    pub fn height(_window: &mut Window) -> Pixels {
343        // todo(windows) instead of hard coded size report the actual size to the Windows platform API
344        px(32.)
345    }
346
347    /// Sets the platform style.
348    pub fn platform_style(mut self, style: PlatformStyle) -> Self {
349        self.platform_style = style;
350        self
351    }
352
353    fn render_ssh_project_host(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
354        let options = self.project.read(cx).ssh_connection_options(cx)?;
355        let host: SharedString = options.connection_string().into();
356
357        let nickname = options
358            .nickname
359            .clone()
360            .map(|nick| nick.into())
361            .unwrap_or_else(|| host.clone());
362
363        let (indicator_color, meta) = match self.project.read(cx).ssh_connection_state(cx)? {
364            remote::ConnectionState::Connecting => (Color::Info, format!("Connecting to: {host}")),
365            remote::ConnectionState::Connected => (Color::Success, format!("Connected to: {host}")),
366            remote::ConnectionState::HeartbeatMissed => (
367                Color::Warning,
368                format!("Connection attempt to {host} missed. Retrying..."),
369            ),
370            remote::ConnectionState::Reconnecting => (
371                Color::Warning,
372                format!("Lost connection to {host}. Reconnecting..."),
373            ),
374            remote::ConnectionState::Disconnected => {
375                (Color::Error, format!("Disconnected from {host}"))
376            }
377        };
378
379        let icon_color = match self.project.read(cx).ssh_connection_state(cx)? {
380            remote::ConnectionState::Connecting => Color::Info,
381            remote::ConnectionState::Connected => Color::Default,
382            remote::ConnectionState::HeartbeatMissed => Color::Warning,
383            remote::ConnectionState::Reconnecting => Color::Warning,
384            remote::ConnectionState::Disconnected => Color::Error,
385        };
386
387        let meta = SharedString::from(meta);
388
389        Some(
390            ButtonLike::new("ssh-server-icon")
391                .child(
392                    h_flex()
393                        .gap_2()
394                        .max_w_32()
395                        .child(
396                            IconWithIndicator::new(
397                                Icon::new(IconName::Server)
398                                    .size(IconSize::XSmall)
399                                    .color(icon_color),
400                                Some(Indicator::dot().color(indicator_color)),
401                            )
402                            .indicator_border_color(Some(cx.theme().colors().title_bar_background))
403                            .into_any_element(),
404                        )
405                        .child(
406                            Label::new(nickname.clone())
407                                .size(LabelSize::Small)
408                                .truncate(),
409                        ),
410                )
411                .tooltip(move |window, cx| {
412                    Tooltip::with_meta(
413                        "Remote Project",
414                        Some(&OpenRemote),
415                        meta.clone(),
416                        window,
417                        cx,
418                    )
419                })
420                .on_click(|_, window, cx| {
421                    window.dispatch_action(OpenRemote.boxed_clone(), cx);
422                })
423                .into_any_element(),
424        )
425    }
426
427    pub fn render_project_host(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
428        if self.project.read(cx).is_via_ssh() {
429            return self.render_ssh_project_host(cx);
430        }
431
432        if self.project.read(cx).is_disconnected(cx) {
433            return Some(
434                Button::new("disconnected", "Disconnected")
435                    .disabled(true)
436                    .color(Color::Disabled)
437                    .style(ButtonStyle::Subtle)
438                    .label_size(LabelSize::Small)
439                    .into_any_element(),
440            );
441        }
442
443        let host = self.project.read(cx).host()?;
444        let host_user = self.user_store.read(cx).get_cached_user(host.user_id)?;
445        let participant_index = self
446            .user_store
447            .read(cx)
448            .participant_indices()
449            .get(&host_user.id)?;
450        Some(
451            Button::new("project_owner_trigger", host_user.github_login.clone())
452                .color(Color::Player(participant_index.0))
453                .style(ButtonStyle::Subtle)
454                .label_size(LabelSize::Small)
455                .tooltip(Tooltip::text(format!(
456                    "{} is sharing this project. Click to follow.",
457                    host_user.github_login.clone()
458                )))
459                .on_click({
460                    let host_peer_id = host.peer_id;
461                    cx.listener(move |this, _, window, cx| {
462                        this.workspace
463                            .update(cx, |workspace, cx| {
464                                workspace.follow(host_peer_id, window, cx);
465                            })
466                            .log_err();
467                    })
468                })
469                .into_any_element(),
470        )
471    }
472
473    pub fn render_project_name(&self, cx: &mut Context<Self>) -> impl IntoElement {
474        let name = {
475            let mut names = self.project.read(cx).visible_worktrees(cx).map(|worktree| {
476                let worktree = worktree.read(cx);
477                worktree.root_name()
478            });
479
480            names.next()
481        };
482        let is_project_selected = name.is_some();
483        let name = if let Some(name) = name {
484            util::truncate_and_trailoff(name, MAX_PROJECT_NAME_LENGTH)
485        } else {
486            "Open recent project".to_string()
487        };
488
489        Button::new("project_name_trigger", name)
490            .when(!is_project_selected, |b| b.color(Color::Muted))
491            .style(ButtonStyle::Subtle)
492            .label_size(LabelSize::Small)
493            .tooltip(move |window, cx| {
494                Tooltip::for_action(
495                    "Recent Projects",
496                    &zed_actions::OpenRecent {
497                        create_new_window: false,
498                    },
499                    window,
500                    cx,
501                )
502            })
503            .on_click(cx.listener(move |_, _, window, cx| {
504                window.dispatch_action(
505                    OpenRecent {
506                        create_new_window: false,
507                    }
508                    .boxed_clone(),
509                    cx,
510                );
511            }))
512    }
513
514    pub fn render_project_branch(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> {
515        let repository = self.project.read(cx).active_repository(cx)?;
516        let workspace = self.workspace.upgrade()?;
517        let branch_name = repository.read(cx).branch.as_ref()?.name.clone();
518        let branch_name = util::truncate_and_trailoff(&branch_name, MAX_BRANCH_NAME_LENGTH);
519        Some(
520            Button::new("project_branch_trigger", branch_name)
521                .color(Color::Muted)
522                .style(ButtonStyle::Subtle)
523                .label_size(LabelSize::Small)
524                .tooltip(move |window, cx| {
525                    Tooltip::with_meta(
526                        "Recent Branches",
527                        Some(&zed_actions::git::Branch),
528                        "Local branches only",
529                        window,
530                        cx,
531                    )
532                })
533                .on_click(move |_, window, cx| {
534                    let _ = workspace.update(cx, |_this, cx| {
535                        window.dispatch_action(zed_actions::git::Branch.boxed_clone(), cx);
536                    });
537                }),
538        )
539    }
540
541    fn window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
542        if window.is_window_active() {
543            ActiveCall::global(cx)
544                .update(cx, |call, cx| call.set_location(Some(&self.project), cx))
545                .detach_and_log_err(cx);
546        } else if cx.active_window().is_none() {
547            ActiveCall::global(cx)
548                .update(cx, |call, cx| call.set_location(None, cx))
549                .detach_and_log_err(cx);
550        }
551        self.workspace
552            .update(cx, |workspace, cx| {
553                workspace.update_active_view_for_followers(window, cx);
554            })
555            .ok();
556    }
557
558    fn active_call_changed(&mut self, cx: &mut Context<Self>) {
559        cx.notify();
560    }
561
562    fn share_project(&mut self, cx: &mut Context<Self>) {
563        let active_call = ActiveCall::global(cx);
564        let project = self.project.clone();
565        active_call
566            .update(cx, |call, cx| call.share_project(project, cx))
567            .detach_and_log_err(cx);
568    }
569
570    fn unshare_project(&mut self, _: &mut Window, cx: &mut Context<Self>) {
571        let active_call = ActiveCall::global(cx);
572        let project = self.project.clone();
573        active_call
574            .update(cx, |call, cx| call.unshare_project(project, cx))
575            .log_err();
576    }
577
578    fn render_connection_status(
579        &self,
580        status: &client::Status,
581        cx: &mut Context<Self>,
582    ) -> Option<AnyElement> {
583        match status {
584            client::Status::ConnectionError
585            | client::Status::ConnectionLost
586            | client::Status::Reauthenticating { .. }
587            | client::Status::Reconnecting { .. }
588            | client::Status::ReconnectionError { .. } => Some(
589                div()
590                    .id("disconnected")
591                    .child(Icon::new(IconName::Disconnected).size(IconSize::Small))
592                    .tooltip(Tooltip::text("Disconnected"))
593                    .into_any_element(),
594            ),
595            client::Status::UpgradeRequired => {
596                let auto_updater = auto_update::AutoUpdater::get(cx);
597                let label = match auto_updater.map(|auto_update| auto_update.read(cx).status()) {
598                    Some(AutoUpdateStatus::Updated { .. }) => "Please restart Zed to Collaborate",
599                    Some(AutoUpdateStatus::Installing)
600                    | Some(AutoUpdateStatus::Downloading)
601                    | Some(AutoUpdateStatus::Checking) => "Updating...",
602                    Some(AutoUpdateStatus::Idle) | Some(AutoUpdateStatus::Errored) | None => {
603                        "Please update Zed to Collaborate"
604                    }
605                };
606
607                Some(
608                    Button::new("connection-status", label)
609                        .label_size(LabelSize::Small)
610                        .on_click(|_, window, cx| {
611                            if let Some(auto_updater) = auto_update::AutoUpdater::get(cx) {
612                                if auto_updater.read(cx).status().is_updated() {
613                                    workspace::reload(&Default::default(), cx);
614                                    return;
615                                }
616                            }
617                            auto_update::check(&Default::default(), window, cx);
618                        })
619                        .into_any_element(),
620                )
621            }
622            _ => None,
623        }
624    }
625
626    pub fn render_bottom_dock_layout_menu(&self, cx: &mut Context<Self>) -> impl IntoElement {
627        let workspace = self.workspace.upgrade().unwrap();
628        let current_layout = workspace.update(cx, |workspace, _cx| workspace.bottom_dock_layout());
629
630        PopoverMenu::new("layout-menu")
631            .trigger(
632                IconButton::new("toggle_layout", IconName::Layout)
633                    .icon_size(IconSize::Small)
634                    .tooltip(Tooltip::text("Toggle Layout Menu")),
635            )
636            .anchor(gpui::Corner::TopRight)
637            .menu(move |window, cx| {
638                ContextMenu::build(window, cx, {
639                    let workspace = workspace.clone();
640                    move |menu, _, _| {
641                        menu.label("Bottom Dock")
642                            .separator()
643                            .toggleable_entry(
644                                "Contained",
645                                current_layout == BottomDockLayout::Contained,
646                                ui::IconPosition::End,
647                                None,
648                                {
649                                    let workspace = workspace.clone();
650                                    move |window, cx| {
651                                        workspace.update(cx, |workspace, cx| {
652                                            workspace.set_bottom_dock_layout(
653                                                BottomDockLayout::Contained,
654                                                window,
655                                                cx,
656                                            );
657                                        });
658                                    }
659                                },
660                            )
661                            .toggleable_entry(
662                                "Full",
663                                current_layout == BottomDockLayout::Full,
664                                ui::IconPosition::End,
665                                None,
666                                {
667                                    let workspace = workspace.clone();
668                                    move |window, cx| {
669                                        workspace.update(cx, |workspace, cx| {
670                                            workspace.set_bottom_dock_layout(
671                                                BottomDockLayout::Full,
672                                                window,
673                                                cx,
674                                            );
675                                        });
676                                    }
677                                },
678                            )
679                            .toggleable_entry(
680                                "Left Aligned",
681                                current_layout == BottomDockLayout::LeftAligned,
682                                ui::IconPosition::End,
683                                None,
684                                {
685                                    let workspace = workspace.clone();
686                                    move |window, cx| {
687                                        workspace.update(cx, |workspace, cx| {
688                                            workspace.set_bottom_dock_layout(
689                                                BottomDockLayout::LeftAligned,
690                                                window,
691                                                cx,
692                                            );
693                                        });
694                                    }
695                                },
696                            )
697                            .toggleable_entry(
698                                "Right Aligned",
699                                current_layout == BottomDockLayout::RightAligned,
700                                ui::IconPosition::End,
701                                None,
702                                {
703                                    let workspace = workspace.clone();
704                                    move |window, cx| {
705                                        workspace.update(cx, |workspace, cx| {
706                                            workspace.set_bottom_dock_layout(
707                                                BottomDockLayout::RightAligned,
708                                                window,
709                                                cx,
710                                            );
711                                        });
712                                    }
713                                },
714                            )
715                    }
716                })
717                .into()
718            })
719    }
720
721    pub fn render_sign_in_button(&mut self, _: &mut Context<Self>) -> Button {
722        let client = self.client.clone();
723        Button::new("sign_in", "Sign in")
724            .label_size(LabelSize::Small)
725            .on_click(move |_, window, cx| {
726                let client = client.clone();
727                window
728                    .spawn(cx, async move |cx| {
729                        client
730                            .authenticate_and_connect(true, &cx)
731                            .await
732                            .notify_async_err(cx);
733                    })
734                    .detach();
735            })
736    }
737
738    pub fn render_user_menu_button(&mut self, cx: &mut Context<Self>) -> impl Element {
739        let user_store = self.user_store.read(cx);
740        if let Some(user) = user_store.current_user() {
741            let plan = user_store.current_plan();
742            PopoverMenu::new("user-menu")
743                .anchor(Corner::TopRight)
744                .menu(move |window, cx| {
745                    ContextMenu::build(window, cx, |menu, _, cx| {
746                        menu.when(cx.has_flag::<ZedPro>(), |menu| {
747                            menu.action(
748                                format!(
749                                    "Current Plan: {}",
750                                    match plan {
751                                        None => "",
752                                        Some(proto::Plan::Free) => "Free",
753                                        Some(proto::Plan::ZedPro) => "Pro",
754                                    }
755                                ),
756                                zed_actions::OpenAccountSettings.boxed_clone(),
757                            )
758                            .separator()
759                        })
760                        .action("Settings", zed_actions::OpenSettings.boxed_clone())
761                        .action("Key Bindings", Box::new(zed_actions::OpenKeymap))
762                        .action(
763                            "Themes…",
764                            zed_actions::theme_selector::Toggle::default().boxed_clone(),
765                        )
766                        .action(
767                            "Icon Themes…",
768                            zed_actions::icon_theme_selector::Toggle::default().boxed_clone(),
769                        )
770                        .action(
771                            "Extensions",
772                            zed_actions::Extensions::default().boxed_clone(),
773                        )
774                        .separator()
775                        .link(
776                            "Book Onboarding",
777                            OpenBrowser {
778                                url: BOOK_ONBOARDING.to_string(),
779                            }
780                            .boxed_clone(),
781                        )
782                        .action("Sign Out", client::SignOut.boxed_clone())
783                    })
784                    .into()
785                })
786                .trigger_with_tooltip(
787                    ButtonLike::new("user-menu")
788                        .child(
789                            h_flex()
790                                .gap_0p5()
791                                .children(
792                                    workspace::WorkspaceSettings::get_global(cx)
793                                        .show_user_picture
794                                        .then(|| Avatar::new(user.avatar_uri.clone())),
795                                )
796                                .child(
797                                    Icon::new(IconName::ChevronDown)
798                                        .size(IconSize::Small)
799                                        .color(Color::Muted),
800                                ),
801                        )
802                        .style(ButtonStyle::Subtle),
803                    Tooltip::text("Toggle User Menu"),
804                )
805                .anchor(gpui::Corner::TopRight)
806        } else {
807            PopoverMenu::new("user-menu")
808                .anchor(Corner::TopRight)
809                .menu(|window, cx| {
810                    ContextMenu::build(window, cx, |menu, _, _| {
811                        menu.action("Settings", zed_actions::OpenSettings.boxed_clone())
812                            .action("Key Bindings", Box::new(zed_actions::OpenKeymap))
813                            .action(
814                                "Themes…",
815                                zed_actions::theme_selector::Toggle::default().boxed_clone(),
816                            )
817                            .action(
818                                "Icon Themes…",
819                                zed_actions::icon_theme_selector::Toggle::default().boxed_clone(),
820                            )
821                            .action(
822                                "Extensions",
823                                zed_actions::Extensions::default().boxed_clone(),
824                            )
825                            .separator()
826                            .link(
827                                "Book Onboarding",
828                                OpenBrowser {
829                                    url: BOOK_ONBOARDING.to_string(),
830                                }
831                                .boxed_clone(),
832                            )
833                    })
834                    .into()
835                })
836                .trigger_with_tooltip(
837                    IconButton::new("user-menu", IconName::ChevronDown).icon_size(IconSize::Small),
838                    Tooltip::text("Toggle User Menu"),
839                )
840        }
841    }
842}
843
844impl InteractiveElement for TitleBar {
845    fn interactivity(&mut self) -> &mut Interactivity {
846        self.content.interactivity()
847    }
848}
849
850impl StatefulInteractiveElement for TitleBar {}
851
852impl ParentElement for TitleBar {
853    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
854        self.children.extend(elements)
855    }
856}