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