1mod application_menu;
2mod collab;
3mod onboarding_banner;
4pub mod platform_title_bar;
5mod platforms;
6mod title_bar_settings;
7
8#[cfg(feature = "stories")]
9mod stories;
10
11use crate::{application_menu::ApplicationMenu, platform_title_bar::PlatformTitleBar};
12
13#[cfg(not(target_os = "macos"))]
14use crate::application_menu::{
15 ActivateDirection, ActivateMenuLeft, ActivateMenuRight, OpenApplicationMenu,
16};
17
18use auto_update::AutoUpdateStatus;
19use call::ActiveCall;
20use client::{Client, UserStore};
21use gpui::{
22 Action, AnyElement, App, Context, Corner, Element, Entity, InteractiveElement, IntoElement,
23 MouseButton, ParentElement, Render, StatefulInteractiveElement, Styled, Subscription,
24 WeakEntity, Window, actions, div,
25};
26use onboarding_banner::OnboardingBanner;
27use project::Project;
28use rpc::proto;
29use settings::Settings as _;
30use std::sync::Arc;
31use theme::ActiveTheme;
32use title_bar_settings::TitleBarSettings;
33use ui::{
34 Avatar, Button, ButtonLike, ButtonStyle, ContextMenu, Icon, IconName, IconSize,
35 IconWithIndicator, Indicator, PopoverMenu, Tooltip, h_flex, prelude::*,
36};
37use util::ResultExt;
38use workspace::{Workspace, notifications::NotifyResultExt};
39use zed_actions::{OpenRecent, OpenRemote};
40
41pub use onboarding_banner::restore_banner;
42
43#[cfg(feature = "stories")]
44pub use stories::*;
45
46const MAX_PROJECT_NAME_LENGTH: usize = 40;
47const MAX_BRANCH_NAME_LENGTH: usize = 40;
48const MAX_SHORT_SHA_LENGTH: usize = 8;
49
50actions!(
51 collab,
52 [
53 /// Toggles the user menu dropdown.
54 ToggleUserMenu,
55 /// Toggles the project menu dropdown.
56 ToggleProjectMenu,
57 /// Switches to a different git branch.
58 SwitchBranch
59 ]
60);
61
62pub fn init(cx: &mut App) {
63 TitleBarSettings::register(cx);
64
65 cx.observe_new(|workspace: &mut Workspace, window, cx| {
66 let Some(window) = window else {
67 return;
68 };
69 let item = cx.new(|cx| TitleBar::new("title-bar", workspace, window, cx));
70 workspace.set_titlebar_item(item.into(), window, cx);
71
72 #[cfg(not(target_os = "macos"))]
73 workspace.register_action(|workspace, action: &OpenApplicationMenu, window, cx| {
74 if let Some(titlebar) = workspace
75 .titlebar_item()
76 .and_then(|item| item.downcast::<TitleBar>().ok())
77 {
78 titlebar.update(cx, |titlebar, cx| {
79 if let Some(ref menu) = titlebar.application_menu {
80 menu.update(cx, |menu, cx| menu.open_menu(action, window, cx));
81 }
82 });
83 }
84 });
85
86 #[cfg(not(target_os = "macos"))]
87 workspace.register_action(|workspace, _: &ActivateMenuRight, window, cx| {
88 if let Some(titlebar) = workspace
89 .titlebar_item()
90 .and_then(|item| item.downcast::<TitleBar>().ok())
91 {
92 titlebar.update(cx, |titlebar, cx| {
93 if let Some(ref menu) = titlebar.application_menu {
94 menu.update(cx, |menu, cx| {
95 menu.navigate_menus_in_direction(ActivateDirection::Right, window, cx)
96 });
97 }
98 });
99 }
100 });
101
102 #[cfg(not(target_os = "macos"))]
103 workspace.register_action(|workspace, _: &ActivateMenuLeft, window, cx| {
104 if let Some(titlebar) = workspace
105 .titlebar_item()
106 .and_then(|item| item.downcast::<TitleBar>().ok())
107 {
108 titlebar.update(cx, |titlebar, cx| {
109 if let Some(ref menu) = titlebar.application_menu {
110 menu.update(cx, |menu, cx| {
111 menu.navigate_menus_in_direction(ActivateDirection::Left, window, cx)
112 });
113 }
114 });
115 }
116 });
117 })
118 .detach();
119}
120
121pub struct TitleBar {
122 platform_titlebar: Entity<PlatformTitleBar>,
123 project: Entity<Project>,
124 user_store: Entity<UserStore>,
125 client: Arc<Client>,
126 workspace: WeakEntity<Workspace>,
127 application_menu: Option<Entity<ApplicationMenu>>,
128 _subscriptions: Vec<Subscription>,
129 banner: Entity<OnboardingBanner>,
130}
131
132impl Render for TitleBar {
133 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
134 let title_bar_settings = *TitleBarSettings::get_global(cx);
135
136 let mut children = Vec::new();
137
138 children.push(
139 h_flex()
140 .gap_1()
141 .map(|title_bar| {
142 let mut render_project_items = title_bar_settings.show_branch_name
143 || title_bar_settings.show_project_items;
144 title_bar
145 .when_some(self.application_menu.clone(), |title_bar, menu| {
146 render_project_items &= !menu.read(cx).all_menus_shown();
147 title_bar.child(menu)
148 })
149 .when(render_project_items, |title_bar| {
150 title_bar
151 .when(title_bar_settings.show_project_items, |title_bar| {
152 title_bar
153 .children(self.render_project_host(cx))
154 .child(self.render_project_name(cx))
155 })
156 .when(title_bar_settings.show_branch_name, |title_bar| {
157 title_bar.children(self.render_project_branch(cx))
158 })
159 })
160 })
161 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
162 .into_any_element(),
163 );
164
165 children.push(self.render_collaborator_list(window, cx).into_any_element());
166
167 if title_bar_settings.show_onboarding_banner {
168 children.push(self.banner.clone().into_any_element())
169 }
170
171 children.push(
172 h_flex()
173 .gap_1()
174 .pr_1()
175 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
176 .children(self.render_call_controls(window, cx))
177 .map(|el| {
178 let status = self.client.status();
179 let status = &*status.borrow();
180 if matches!(status, client::Status::Connected { .. }) {
181 el.child(self.render_user_menu_button(cx))
182 } else {
183 el.children(self.render_connection_status(status, cx))
184 .when(TitleBarSettings::get_global(cx).show_sign_in, |el| {
185 el.child(self.render_sign_in_button(cx))
186 })
187 .child(self.render_user_menu_button(cx))
188 }
189 })
190 .into_any_element(),
191 );
192
193 self.platform_titlebar.update(cx, |this, _| {
194 this.set_children(children);
195 });
196
197 self.platform_titlebar.clone().into_any_element()
198 }
199}
200
201impl TitleBar {
202 pub fn new(
203 id: impl Into<ElementId>,
204 workspace: &Workspace,
205 window: &mut Window,
206 cx: &mut Context<Self>,
207 ) -> Self {
208 let project = workspace.project().clone();
209 let user_store = workspace.app_state().user_store.clone();
210 let client = workspace.app_state().client.clone();
211 let active_call = ActiveCall::global(cx);
212
213 let platform_style = PlatformStyle::platform();
214 let application_menu = match platform_style {
215 PlatformStyle::Mac => {
216 if option_env!("ZED_USE_CROSS_PLATFORM_MENU").is_some() {
217 Some(cx.new(|cx| ApplicationMenu::new(window, cx)))
218 } else {
219 None
220 }
221 }
222 PlatformStyle::Linux | PlatformStyle::Windows => {
223 Some(cx.new(|cx| ApplicationMenu::new(window, cx)))
224 }
225 };
226
227 let mut subscriptions = Vec::new();
228 subscriptions.push(
229 cx.observe(&workspace.weak_handle().upgrade().unwrap(), |_, _, cx| {
230 cx.notify()
231 }),
232 );
233 subscriptions.push(cx.subscribe(&project, |_, _, _: &project::Event, cx| cx.notify()));
234 subscriptions.push(cx.observe(&active_call, |this, _, cx| this.active_call_changed(cx)));
235 subscriptions.push(cx.observe_window_activation(window, Self::window_activation_changed));
236 subscriptions.push(cx.observe(&user_store, |_, _, cx| cx.notify()));
237
238 let banner = cx.new(|cx| {
239 OnboardingBanner::new(
240 "Debugger Onboarding",
241 IconName::Debug,
242 "The Debugger",
243 None,
244 zed_actions::debugger::OpenOnboardingModal.boxed_clone(),
245 cx,
246 )
247 });
248
249 let platform_titlebar = cx.new(|_| PlatformTitleBar::new(id));
250
251 Self {
252 platform_titlebar,
253 application_menu,
254 workspace: workspace.weak_handle(),
255 project,
256 user_store,
257 client,
258 _subscriptions: subscriptions,
259 banner,
260 }
261 }
262
263 fn render_ssh_project_host(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
264 let options = self.project.read(cx).ssh_connection_options(cx)?;
265 let host: SharedString = options.connection_string().into();
266
267 let nickname = options
268 .nickname
269 .clone()
270 .map(|nick| nick.into())
271 .unwrap_or_else(|| host.clone());
272
273 let (indicator_color, meta) = match self.project.read(cx).ssh_connection_state(cx)? {
274 remote::ConnectionState::Connecting => (Color::Info, format!("Connecting to: {host}")),
275 remote::ConnectionState::Connected => (Color::Success, format!("Connected to: {host}")),
276 remote::ConnectionState::HeartbeatMissed => (
277 Color::Warning,
278 format!("Connection attempt to {host} missed. Retrying..."),
279 ),
280 remote::ConnectionState::Reconnecting => (
281 Color::Warning,
282 format!("Lost connection to {host}. Reconnecting..."),
283 ),
284 remote::ConnectionState::Disconnected => {
285 (Color::Error, format!("Disconnected from {host}"))
286 }
287 };
288
289 let icon_color = match self.project.read(cx).ssh_connection_state(cx)? {
290 remote::ConnectionState::Connecting => Color::Info,
291 remote::ConnectionState::Connected => Color::Default,
292 remote::ConnectionState::HeartbeatMissed => Color::Warning,
293 remote::ConnectionState::Reconnecting => Color::Warning,
294 remote::ConnectionState::Disconnected => Color::Error,
295 };
296
297 let meta = SharedString::from(meta);
298
299 Some(
300 ButtonLike::new("ssh-server-icon")
301 .child(
302 h_flex()
303 .gap_2()
304 .max_w_32()
305 .child(
306 IconWithIndicator::new(
307 Icon::new(IconName::Server)
308 .size(IconSize::XSmall)
309 .color(icon_color),
310 Some(Indicator::dot().color(indicator_color)),
311 )
312 .indicator_border_color(Some(cx.theme().colors().title_bar_background))
313 .into_any_element(),
314 )
315 .child(
316 Label::new(nickname.clone())
317 .size(LabelSize::Small)
318 .truncate(),
319 ),
320 )
321 .tooltip(move |window, cx| {
322 Tooltip::with_meta(
323 "Remote Project",
324 Some(&OpenRemote {
325 from_existing_connection: false,
326 create_new_window: false,
327 }),
328 meta.clone(),
329 window,
330 cx,
331 )
332 })
333 .on_click(|_, window, cx| {
334 window.dispatch_action(
335 OpenRemote {
336 from_existing_connection: false,
337 create_new_window: false,
338 }
339 .boxed_clone(),
340 cx,
341 );
342 })
343 .into_any_element(),
344 )
345 }
346
347 pub fn render_project_host(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
348 if self.project.read(cx).is_via_ssh() {
349 return self.render_ssh_project_host(cx);
350 }
351
352 if self.project.read(cx).is_disconnected(cx) {
353 return Some(
354 Button::new("disconnected", "Disconnected")
355 .disabled(true)
356 .color(Color::Disabled)
357 .style(ButtonStyle::Subtle)
358 .label_size(LabelSize::Small)
359 .into_any_element(),
360 );
361 }
362
363 let host = self.project.read(cx).host()?;
364 let host_user = self.user_store.read(cx).get_cached_user(host.user_id)?;
365 let participant_index = self
366 .user_store
367 .read(cx)
368 .participant_indices()
369 .get(&host_user.id)?;
370 Some(
371 Button::new("project_owner_trigger", host_user.github_login.clone())
372 .color(Color::Player(participant_index.0))
373 .style(ButtonStyle::Subtle)
374 .label_size(LabelSize::Small)
375 .tooltip(Tooltip::text(format!(
376 "{} is sharing this project. Click to follow.",
377 host_user.github_login
378 )))
379 .on_click({
380 let host_peer_id = host.peer_id;
381 cx.listener(move |this, _, window, cx| {
382 this.workspace
383 .update(cx, |workspace, cx| {
384 workspace.follow(host_peer_id, window, cx);
385 })
386 .log_err();
387 })
388 })
389 .into_any_element(),
390 )
391 }
392
393 pub fn render_project_name(&self, cx: &mut Context<Self>) -> impl IntoElement {
394 let name = {
395 let mut names = self.project.read(cx).visible_worktrees(cx).map(|worktree| {
396 let worktree = worktree.read(cx);
397 worktree.root_name()
398 });
399
400 names.next()
401 };
402 let is_project_selected = name.is_some();
403 let name = if let Some(name) = name {
404 util::truncate_and_trailoff(name, MAX_PROJECT_NAME_LENGTH)
405 } else {
406 "Open recent project".to_string()
407 };
408
409 Button::new("project_name_trigger", name)
410 .when(!is_project_selected, |b| b.color(Color::Muted))
411 .style(ButtonStyle::Subtle)
412 .label_size(LabelSize::Small)
413 .tooltip(move |window, cx| {
414 Tooltip::for_action(
415 "Recent Projects",
416 &zed_actions::OpenRecent {
417 create_new_window: false,
418 },
419 window,
420 cx,
421 )
422 })
423 .on_click(cx.listener(move |_, _, window, cx| {
424 window.dispatch_action(
425 OpenRecent {
426 create_new_window: false,
427 }
428 .boxed_clone(),
429 cx,
430 );
431 }))
432 }
433
434 pub fn render_project_branch(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> {
435 let repository = self.project.read(cx).active_repository(cx)?;
436 let workspace = self.workspace.upgrade()?;
437 let branch_name = {
438 let repo = repository.read(cx);
439 repo.branch
440 .as_ref()
441 .map(|branch| branch.name())
442 .map(|name| util::truncate_and_trailoff(&name, MAX_BRANCH_NAME_LENGTH))
443 .or_else(|| {
444 repo.head_commit.as_ref().map(|commit| {
445 commit
446 .sha
447 .chars()
448 .take(MAX_SHORT_SHA_LENGTH)
449 .collect::<String>()
450 })
451 })
452 }?;
453
454 Some(
455 Button::new("project_branch_trigger", branch_name)
456 .color(Color::Muted)
457 .style(ButtonStyle::Subtle)
458 .label_size(LabelSize::Small)
459 .tooltip(move |window, cx| {
460 Tooltip::with_meta(
461 "Recent Branches",
462 Some(&zed_actions::git::Branch),
463 "Local branches only",
464 window,
465 cx,
466 )
467 })
468 .on_click(move |_, window, cx| {
469 let _ = workspace.update(cx, |_this, cx| {
470 window.dispatch_action(zed_actions::git::Branch.boxed_clone(), cx);
471 });
472 })
473 .when(
474 TitleBarSettings::get_global(cx).show_branch_icon,
475 |branch_button| {
476 branch_button
477 .icon(IconName::GitBranch)
478 .icon_position(IconPosition::Start)
479 .icon_color(Color::Muted)
480 .icon_size(IconSize::Indicator)
481 },
482 ),
483 )
484 }
485
486 fn window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
487 if window.is_window_active() {
488 ActiveCall::global(cx)
489 .update(cx, |call, cx| call.set_location(Some(&self.project), cx))
490 .detach_and_log_err(cx);
491 } else if cx.active_window().is_none() {
492 ActiveCall::global(cx)
493 .update(cx, |call, cx| call.set_location(None, cx))
494 .detach_and_log_err(cx);
495 }
496 self.workspace
497 .update(cx, |workspace, cx| {
498 workspace.update_active_view_for_followers(window, cx);
499 })
500 .ok();
501 }
502
503 fn active_call_changed(&mut self, cx: &mut Context<Self>) {
504 cx.notify();
505 }
506
507 fn share_project(&mut self, cx: &mut Context<Self>) {
508 let active_call = ActiveCall::global(cx);
509 let project = self.project.clone();
510 active_call
511 .update(cx, |call, cx| call.share_project(project, cx))
512 .detach_and_log_err(cx);
513 }
514
515 fn unshare_project(&mut self, _: &mut Window, cx: &mut Context<Self>) {
516 let active_call = ActiveCall::global(cx);
517 let project = self.project.clone();
518 active_call
519 .update(cx, |call, cx| call.unshare_project(project, cx))
520 .log_err();
521 }
522
523 fn render_connection_status(
524 &self,
525 status: &client::Status,
526 cx: &mut Context<Self>,
527 ) -> Option<AnyElement> {
528 match status {
529 client::Status::ConnectionError
530 | client::Status::ConnectionLost
531 | client::Status::Reauthenticating { .. }
532 | client::Status::Reconnecting { .. }
533 | client::Status::ReconnectionError { .. } => Some(
534 div()
535 .id("disconnected")
536 .child(Icon::new(IconName::Disconnected).size(IconSize::Small))
537 .tooltip(Tooltip::text("Disconnected"))
538 .into_any_element(),
539 ),
540 client::Status::UpgradeRequired => {
541 let auto_updater = auto_update::AutoUpdater::get(cx);
542 let label = match auto_updater.map(|auto_update| auto_update.read(cx).status()) {
543 Some(AutoUpdateStatus::Updated { .. }) => "Please restart Zed to Collaborate",
544 Some(AutoUpdateStatus::Installing { .. })
545 | Some(AutoUpdateStatus::Downloading { .. })
546 | Some(AutoUpdateStatus::Checking) => "Updating...",
547 Some(AutoUpdateStatus::Idle) | Some(AutoUpdateStatus::Errored) | None => {
548 "Please update Zed to Collaborate"
549 }
550 };
551
552 Some(
553 Button::new("connection-status", label)
554 .label_size(LabelSize::Small)
555 .on_click(|_, window, cx| {
556 if let Some(auto_updater) = auto_update::AutoUpdater::get(cx) {
557 if auto_updater.read(cx).status().is_updated() {
558 workspace::reload(&Default::default(), cx);
559 return;
560 }
561 }
562 auto_update::check(&Default::default(), window, cx);
563 })
564 .into_any_element(),
565 )
566 }
567 _ => None,
568 }
569 }
570
571 pub fn render_sign_in_button(&mut self, _: &mut Context<Self>) -> Button {
572 let client = self.client.clone();
573 Button::new("sign_in", "Sign in")
574 .label_size(LabelSize::Small)
575 .on_click(move |_, window, cx| {
576 let client = client.clone();
577 window
578 .spawn(cx, async move |cx| {
579 client
580 .authenticate_and_connect(true, &cx)
581 .await
582 .into_response()
583 .notify_async_err(cx);
584 })
585 .detach();
586 })
587 }
588
589 pub fn render_user_menu_button(&mut self, cx: &mut Context<Self>) -> impl Element {
590 let user_store = self.user_store.read(cx);
591 if let Some(user) = user_store.current_user() {
592 let has_subscription_period = self.user_store.read(cx).subscription_period().is_some();
593 let plan = self.user_store.read(cx).current_plan().filter(|_| {
594 // Since the user might be on the legacy free plan we filter based on whether we have a subscription period.
595 has_subscription_period
596 });
597 PopoverMenu::new("user-menu")
598 .anchor(Corner::TopRight)
599 .menu(move |window, cx| {
600 ContextMenu::build(window, cx, |menu, _, _cx| {
601 menu.link(
602 format!(
603 "Current Plan: {}",
604 match plan {
605 None => "None",
606 Some(proto::Plan::Free) => "Zed Free",
607 Some(proto::Plan::ZedPro) => "Zed Pro",
608 Some(proto::Plan::ZedProTrial) => "Zed Pro (Trial)",
609 }
610 ),
611 zed_actions::OpenAccountSettings.boxed_clone(),
612 )
613 .separator()
614 .action("Settings", zed_actions::OpenSettings.boxed_clone())
615 .action("Key Bindings", Box::new(zed_actions::OpenKeymap))
616 .action(
617 "Themes…",
618 zed_actions::theme_selector::Toggle::default().boxed_clone(),
619 )
620 .action(
621 "Icon Themes…",
622 zed_actions::icon_theme_selector::Toggle::default().boxed_clone(),
623 )
624 .action(
625 "Extensions",
626 zed_actions::Extensions::default().boxed_clone(),
627 )
628 .separator()
629 .action("Sign Out", client::SignOut.boxed_clone())
630 })
631 .into()
632 })
633 .trigger_with_tooltip(
634 ButtonLike::new("user-menu")
635 .child(
636 h_flex()
637 .gap_0p5()
638 .children(
639 TitleBarSettings::get_global(cx)
640 .show_user_picture
641 .then(|| Avatar::new(user.avatar_uri.clone())),
642 )
643 .child(
644 Icon::new(IconName::ChevronDown)
645 .size(IconSize::Small)
646 .color(Color::Muted),
647 ),
648 )
649 .style(ButtonStyle::Subtle),
650 Tooltip::text("Toggle User Menu"),
651 )
652 .anchor(gpui::Corner::TopRight)
653 } else {
654 PopoverMenu::new("user-menu")
655 .anchor(Corner::TopRight)
656 .menu(|window, cx| {
657 ContextMenu::build(window, cx, |menu, _, _| {
658 menu.action("Settings", zed_actions::OpenSettings.boxed_clone())
659 .action("Key Bindings", Box::new(zed_actions::OpenKeymap))
660 .action(
661 "Themes…",
662 zed_actions::theme_selector::Toggle::default().boxed_clone(),
663 )
664 .action(
665 "Icon Themes…",
666 zed_actions::icon_theme_selector::Toggle::default().boxed_clone(),
667 )
668 .action(
669 "Extensions",
670 zed_actions::Extensions::default().boxed_clone(),
671 )
672 })
673 .into()
674 })
675 .trigger_with_tooltip(
676 IconButton::new("user-menu", IconName::ChevronDown).icon_size(IconSize::Small),
677 Tooltip::text("Toggle User Menu"),
678 )
679 }
680 }
681}