1mod application_menu;
2mod collab;
3mod platforms;
4mod window_controls;
5
6#[cfg(feature = "stories")]
7mod stories;
8
9use crate::application_menu::ApplicationMenu;
10use crate::platforms::{platform_linux, platform_mac, platform_windows};
11use auto_update::AutoUpdateStatus;
12use call::ActiveCall;
13use client::{Client, UserStore};
14use feature_flags::{FeatureFlagAppExt, ZedPro};
15use gpui::{
16 actions, div, px, Action, AnyElement, AppContext, Decorations, Element, InteractiveElement,
17 Interactivity, IntoElement, Model, MouseButton, ParentElement, Render, Stateful,
18 StatefulInteractiveElement, Styled, Subscription, View, ViewContext, VisualContext, WeakView,
19};
20use project::{Project, RepositoryEntry};
21use recent_projects::{OpenRemote, RecentProjects};
22use rpc::proto::{self, DevServerStatus};
23use smallvec::SmallVec;
24use std::sync::Arc;
25use theme::ActiveTheme;
26use ui::{
27 h_flex, prelude::*, Avatar, Button, ButtonLike, ButtonStyle, ContextMenu, Icon,
28 IconButtonShape, IconName, IconSize, Indicator, PopoverMenu, Tooltip,
29};
30use util::ResultExt;
31use vcs_menu::{BranchList, OpenRecent as ToggleVcsMenu};
32use workspace::{notifications::NotifyResultExt, Workspace};
33
34#[cfg(feature = "stories")]
35pub use stories::*;
36
37const MAX_PROJECT_NAME_LENGTH: usize = 40;
38const MAX_BRANCH_NAME_LENGTH: usize = 40;
39
40actions!(
41 collab,
42 [
43 ShareProject,
44 UnshareProject,
45 ToggleUserMenu,
46 ToggleProjectMenu,
47 SwitchBranch
48 ]
49);
50
51pub fn init(cx: &mut AppContext) {
52 cx.observe_new_views(|workspace: &mut Workspace, cx| {
53 let item = cx.new_view(|cx| TitleBar::new("title-bar", workspace, cx));
54 workspace.set_titlebar_item(item.into(), cx)
55 })
56 .detach();
57}
58
59pub struct TitleBar {
60 platform_style: PlatformStyle,
61 content: Stateful<Div>,
62 children: SmallVec<[AnyElement; 2]>,
63 project: Model<Project>,
64 user_store: Model<UserStore>,
65 client: Arc<Client>,
66 workspace: WeakView<Workspace>,
67 should_move: bool,
68 application_menu: Option<View<ApplicationMenu>>,
69 _subscriptions: Vec<Subscription>,
70}
71
72impl Render for TitleBar {
73 fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
74 let close_action = Box::new(workspace::CloseWindow);
75 let height = Self::height(cx);
76 let supported_controls = cx.window_controls();
77 let decorations = cx.window_decorations();
78 let titlebar_color = if cfg!(target_os = "linux") {
79 if cx.is_window_active() && !self.should_move {
80 cx.theme().colors().title_bar_background
81 } else {
82 cx.theme().colors().title_bar_inactive_background
83 }
84 } else {
85 cx.theme().colors().title_bar_background
86 };
87
88 h_flex()
89 .id("titlebar")
90 .w_full()
91 .h(height)
92 .map(|this| {
93 if cx.is_fullscreen() {
94 this.pl_2()
95 } else if self.platform_style == PlatformStyle::Mac {
96 this.pl(px(platform_mac::TRAFFIC_LIGHT_PADDING))
97 } else {
98 this.pl_2()
99 }
100 })
101 .map(|el| match decorations {
102 Decorations::Server => el,
103 Decorations::Client { tiling, .. } => el
104 .when(!(tiling.top || tiling.right), |el| {
105 el.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING)
106 })
107 .when(!(tiling.top || tiling.left), |el| {
108 el.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
109 })
110 // this border is to avoid a transparent gap in the rounded corners
111 .mt(px(-1.))
112 .border(px(1.))
113 .border_color(titlebar_color),
114 })
115 .bg(titlebar_color)
116 .content_stretch()
117 .child(
118 div()
119 .id("titlebar-content")
120 .flex()
121 .flex_row()
122 .justify_between()
123 .w_full()
124 // Note: On Windows the title bar behavior is handled by the platform implementation.
125 .when(self.platform_style != PlatformStyle::Windows, |this| {
126 this.on_click(|event, cx| {
127 if event.up.click_count == 2 {
128 cx.zoom_window();
129 }
130 })
131 })
132 .child(
133 h_flex()
134 .gap_1()
135 .when_some(self.application_menu.clone(), |this, menu| this.child(menu))
136 .children(self.render_project_host(cx))
137 .child(self.render_project_name(cx))
138 .children(self.render_project_branch(cx))
139 .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation()),
140 )
141 .child(self.render_collaborator_list(cx))
142 .child(
143 h_flex()
144 .gap_1()
145 .pr_1()
146 .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
147 .children(self.render_call_controls(cx))
148 .map(|el| {
149 let status = self.client.status();
150 let status = &*status.borrow();
151 if matches!(status, client::Status::Connected { .. }) {
152 el.child(self.render_user_menu_button(cx))
153 } else {
154 el.children(self.render_connection_status(status, cx))
155 .child(self.render_sign_in_button(cx))
156 .child(self.render_user_menu_button(cx))
157 }
158 }),
159 ),
160 )
161 .when(!cx.is_fullscreen(), |title_bar| match self.platform_style {
162 PlatformStyle::Mac => title_bar,
163 PlatformStyle::Linux => {
164 if matches!(decorations, Decorations::Client { .. }) {
165 title_bar
166 .child(platform_linux::LinuxWindowControls::new(close_action))
167 .when(supported_controls.window_menu, |titlebar| {
168 titlebar.on_mouse_down(gpui::MouseButton::Right, move |ev, cx| {
169 cx.show_window_menu(ev.position)
170 })
171 })
172 .on_mouse_move(cx.listener(move |this, _ev, cx| {
173 if this.should_move {
174 this.should_move = false;
175 cx.start_window_move();
176 }
177 }))
178 .on_mouse_down_out(cx.listener(move |this, _ev, _cx| {
179 this.should_move = false;
180 }))
181 .on_mouse_up(
182 gpui::MouseButton::Left,
183 cx.listener(move |this, _ev, _cx| {
184 this.should_move = false;
185 }),
186 )
187 .on_mouse_down(
188 gpui::MouseButton::Left,
189 cx.listener(move |this, _ev, _cx| {
190 this.should_move = true;
191 }),
192 )
193 } else {
194 title_bar
195 }
196 }
197 PlatformStyle::Windows => {
198 title_bar.child(platform_windows::WindowsWindowControls::new(height))
199 }
200 })
201 }
202}
203
204impl TitleBar {
205 pub fn new(
206 id: impl Into<ElementId>,
207 workspace: &Workspace,
208 cx: &mut ViewContext<Self>,
209 ) -> Self {
210 let project = workspace.project().clone();
211 let user_store = workspace.app_state().user_store.clone();
212 let client = workspace.app_state().client.clone();
213 let active_call = ActiveCall::global(cx);
214
215 let platform_style = PlatformStyle::platform();
216 let application_menu = match platform_style {
217 PlatformStyle::Mac => None,
218 PlatformStyle::Linux | PlatformStyle::Windows => {
219 Some(cx.new_view(ApplicationMenu::new))
220 }
221 };
222
223 let mut subscriptions = Vec::new();
224 subscriptions.push(
225 cx.observe(&workspace.weak_handle().upgrade().unwrap(), |_, _, cx| {
226 cx.notify()
227 }),
228 );
229 subscriptions.push(cx.observe(&project, |_, _, cx| cx.notify()));
230 subscriptions.push(cx.observe(&active_call, |this, _, cx| this.active_call_changed(cx)));
231 subscriptions.push(cx.observe_window_activation(Self::window_activation_changed));
232 subscriptions.push(cx.observe(&user_store, |_, _, cx| cx.notify()));
233
234 Self {
235 platform_style,
236 content: div().id(id.into()),
237 children: SmallVec::new(),
238 application_menu,
239 workspace: workspace.weak_handle(),
240 should_move: false,
241 project,
242 user_store,
243 client,
244 _subscriptions: subscriptions,
245 }
246 }
247
248 #[cfg(not(target_os = "windows"))]
249 pub fn height(cx: &mut WindowContext) -> Pixels {
250 (1.75 * cx.rem_size()).max(px(34.))
251 }
252
253 #[cfg(target_os = "windows")]
254 pub fn height(_cx: &mut WindowContext) -> Pixels {
255 // todo(windows) instead of hard coded size report the actual size to the Windows platform API
256 px(32.)
257 }
258
259 /// Sets the platform style.
260 pub fn platform_style(mut self, style: PlatformStyle) -> Self {
261 self.platform_style = style;
262 self
263 }
264
265 fn render_ssh_project_host(&self, cx: &mut ViewContext<Self>) -> Option<AnyElement> {
266 let host = self.project.read(cx).ssh_connection_string(cx)?;
267 let meta = SharedString::from(format!("Connected to: {host}"));
268 let indicator_color = match self.project.read(cx).ssh_connection_state(cx)? {
269 remote::ConnectionState::Connecting => Color::Info,
270 remote::ConnectionState::Connected => Color::Success,
271 remote::ConnectionState::HeartbeatMissed => Color::Warning,
272 remote::ConnectionState::Reconnecting => Color::Warning,
273 remote::ConnectionState::Disconnected => Color::Error,
274 };
275 let indicator = div()
276 .absolute()
277 .size_1p5()
278 .right_0p5()
279 .bottom_0p5()
280 .rounded_full()
281 .bg(indicator_color.color(cx));
282
283 Some(
284 div()
285 .relative()
286 .child(
287 IconButton::new("ssh-server-icon", IconName::Server)
288 .icon_size(IconSize::Small)
289 .shape(IconButtonShape::Square)
290 .tooltip(move |cx| {
291 Tooltip::with_meta(
292 "Remote Project",
293 Some(&OpenRemote),
294 meta.clone(),
295 cx,
296 )
297 })
298 .on_click(|_, cx| {
299 cx.dispatch_action(OpenRemote.boxed_clone());
300 }),
301 )
302 .child(indicator)
303 .into_any_element(),
304 )
305 }
306
307 pub fn render_project_host(&self, cx: &mut ViewContext<Self>) -> Option<AnyElement> {
308 if let Some(dev_server) =
309 self.project
310 .read(cx)
311 .dev_server_project_id()
312 .and_then(|dev_server_project_id| {
313 dev_server_projects::Store::global(cx)
314 .read(cx)
315 .dev_server_for_project(dev_server_project_id)
316 })
317 {
318 return Some(
319 ButtonLike::new("dev_server_trigger")
320 .child(Indicator::dot().color(
321 if dev_server.status == DevServerStatus::Online {
322 Color::Created
323 } else {
324 Color::Disabled
325 },
326 ))
327 .child(
328 Label::new(dev_server.name.clone())
329 .size(LabelSize::Small)
330 .line_height_style(LineHeightStyle::UiLabel),
331 )
332 .tooltip(move |cx| Tooltip::text("Project is hosted on a dev server", cx))
333 .on_click(cx.listener(|this, _, cx| {
334 if let Some(workspace) = this.workspace.upgrade() {
335 recent_projects::DevServerProjects::open(workspace, cx)
336 }
337 }))
338 .into_any_element(),
339 );
340 }
341 if self.project.read(cx).is_via_ssh() {
342 return self.render_ssh_project_host(cx);
343 }
344
345 if self.project.read(cx).is_disconnected() {
346 return Some(
347 Button::new("disconnected", "Disconnected")
348 .disabled(true)
349 .color(Color::Disabled)
350 .style(ButtonStyle::Subtle)
351 .label_size(LabelSize::Small)
352 .into_any_element(),
353 );
354 }
355
356 let host = self.project.read(cx).host()?;
357 let host_user = self.user_store.read(cx).get_cached_user(host.user_id)?;
358 let participant_index = self
359 .user_store
360 .read(cx)
361 .participant_indices()
362 .get(&host_user.id)?;
363 Some(
364 Button::new("project_owner_trigger", host_user.github_login.clone())
365 .color(Color::Player(participant_index.0))
366 .style(ButtonStyle::Subtle)
367 .label_size(LabelSize::Small)
368 .tooltip(move |cx| {
369 Tooltip::text(
370 format!(
371 "{} is sharing this project. Click to follow.",
372 host_user.github_login.clone()
373 ),
374 cx,
375 )
376 })
377 .on_click({
378 let host_peer_id = host.peer_id;
379 cx.listener(move |this, _, cx| {
380 this.workspace
381 .update(cx, |workspace, cx| {
382 workspace.follow(host_peer_id, cx);
383 })
384 .log_err();
385 })
386 })
387 .into_any_element(),
388 )
389 }
390
391 pub fn render_project_name(&self, cx: &mut ViewContext<Self>) -> impl IntoElement {
392 let name = {
393 let mut names = self.project.read(cx).visible_worktrees(cx).map(|worktree| {
394 let worktree = worktree.read(cx);
395 worktree.root_name()
396 });
397
398 names.next()
399 };
400 let is_project_selected = name.is_some();
401 let name = if let Some(name) = name {
402 util::truncate_and_trailoff(name, MAX_PROJECT_NAME_LENGTH)
403 } else {
404 "Open recent project".to_string()
405 };
406
407 let workspace = self.workspace.clone();
408 Button::new("project_name_trigger", name)
409 .when(!is_project_selected, |b| b.color(Color::Muted))
410 .style(ButtonStyle::Subtle)
411 .label_size(LabelSize::Small)
412 .tooltip(move |cx| {
413 Tooltip::for_action(
414 "Recent Projects",
415 &recent_projects::OpenRecent {
416 create_new_window: false,
417 },
418 cx,
419 )
420 })
421 .on_click(cx.listener(move |_, _, cx| {
422 if let Some(workspace) = workspace.upgrade() {
423 workspace.update(cx, |workspace, cx| {
424 RecentProjects::open(workspace, false, cx);
425 })
426 }
427 }))
428 }
429
430 pub fn render_project_branch(&self, cx: &mut ViewContext<Self>) -> Option<impl IntoElement> {
431 let entry = {
432 let mut names_and_branches =
433 self.project.read(cx).visible_worktrees(cx).map(|worktree| {
434 let worktree = worktree.read(cx);
435 worktree.root_git_entry()
436 });
437
438 names_and_branches.next().flatten()
439 };
440 let workspace = self.workspace.upgrade()?;
441 let branch_name = entry
442 .as_ref()
443 .and_then(RepositoryEntry::branch)
444 .map(|branch| util::truncate_and_trailoff(&branch, MAX_BRANCH_NAME_LENGTH))?;
445 Some(
446 Button::new("project_branch_trigger", branch_name)
447 .color(Color::Muted)
448 .style(ButtonStyle::Subtle)
449 .label_size(LabelSize::Small)
450 .tooltip(move |cx| {
451 Tooltip::with_meta(
452 "Recent Branches",
453 Some(&ToggleVcsMenu),
454 "Local branches only",
455 cx,
456 )
457 })
458 .on_click(move |_, cx| {
459 let _ = workspace.update(cx, |this, cx| {
460 BranchList::open(this, &Default::default(), cx)
461 });
462 }),
463 )
464 }
465
466 fn window_activation_changed(&mut self, cx: &mut ViewContext<Self>) {
467 if cx.is_window_active() {
468 ActiveCall::global(cx)
469 .update(cx, |call, cx| call.set_location(Some(&self.project), cx))
470 .detach_and_log_err(cx);
471 } else if cx.active_window().is_none() {
472 ActiveCall::global(cx)
473 .update(cx, |call, cx| call.set_location(None, cx))
474 .detach_and_log_err(cx);
475 }
476 self.workspace
477 .update(cx, |workspace, cx| {
478 workspace.update_active_view_for_followers(cx);
479 })
480 .ok();
481 }
482
483 fn active_call_changed(&mut self, cx: &mut ViewContext<Self>) {
484 cx.notify();
485 }
486
487 fn share_project(&mut self, _: &ShareProject, cx: &mut ViewContext<Self>) {
488 let active_call = ActiveCall::global(cx);
489 let project = self.project.clone();
490 active_call
491 .update(cx, |call, cx| call.share_project(project, cx))
492 .detach_and_log_err(cx);
493 }
494
495 fn unshare_project(&mut self, _: &UnshareProject, cx: &mut ViewContext<Self>) {
496 let active_call = ActiveCall::global(cx);
497 let project = self.project.clone();
498 active_call
499 .update(cx, |call, cx| call.unshare_project(project, cx))
500 .log_err();
501 }
502
503 fn render_connection_status(
504 &self,
505 status: &client::Status,
506 cx: &mut ViewContext<Self>,
507 ) -> Option<AnyElement> {
508 match status {
509 client::Status::ConnectionError
510 | client::Status::ConnectionLost
511 | client::Status::Reauthenticating { .. }
512 | client::Status::Reconnecting { .. }
513 | client::Status::ReconnectionError { .. } => Some(
514 div()
515 .id("disconnected")
516 .child(Icon::new(IconName::Disconnected).size(IconSize::Small))
517 .tooltip(|cx| Tooltip::text("Disconnected", cx))
518 .into_any_element(),
519 ),
520 client::Status::UpgradeRequired => {
521 let auto_updater = auto_update::AutoUpdater::get(cx);
522 let label = match auto_updater.map(|auto_update| auto_update.read(cx).status()) {
523 Some(AutoUpdateStatus::Updated { .. }) => "Please restart Zed to Collaborate",
524 Some(AutoUpdateStatus::Installing)
525 | Some(AutoUpdateStatus::Downloading)
526 | Some(AutoUpdateStatus::Checking) => "Updating...",
527 Some(AutoUpdateStatus::Idle) | Some(AutoUpdateStatus::Errored) | None => {
528 "Please update Zed to Collaborate"
529 }
530 };
531
532 Some(
533 Button::new("connection-status", label)
534 .label_size(LabelSize::Small)
535 .on_click(|_, cx| {
536 if let Some(auto_updater) = auto_update::AutoUpdater::get(cx) {
537 if auto_updater.read(cx).status().is_updated() {
538 workspace::reload(&Default::default(), cx);
539 return;
540 }
541 }
542 auto_update::check(&Default::default(), cx);
543 })
544 .into_any_element(),
545 )
546 }
547 _ => None,
548 }
549 }
550
551 pub fn render_sign_in_button(&mut self, _: &mut ViewContext<Self>) -> Button {
552 let client = self.client.clone();
553 Button::new("sign_in", "Sign in")
554 .label_size(LabelSize::Small)
555 .on_click(move |_, cx| {
556 let client = client.clone();
557 cx.spawn(move |mut cx| async move {
558 client
559 .authenticate_and_connect(true, &cx)
560 .await
561 .notify_async_err(&mut cx);
562 })
563 .detach();
564 })
565 }
566
567 pub fn render_user_menu_button(&mut self, cx: &mut ViewContext<Self>) -> impl Element {
568 let user_store = self.user_store.read(cx);
569 if let Some(user) = user_store.current_user() {
570 let plan = user_store.current_plan();
571 PopoverMenu::new("user-menu")
572 .menu(move |cx| {
573 ContextMenu::build(cx, |menu, cx| {
574 menu.when(cx.has_flag::<ZedPro>(), |menu| {
575 menu.action(
576 format!(
577 "Current Plan: {}",
578 match plan {
579 None => "",
580 Some(proto::Plan::Free) => "Free",
581 Some(proto::Plan::ZedPro) => "Pro",
582 }
583 ),
584 zed_actions::OpenAccountSettings.boxed_clone(),
585 )
586 .separator()
587 })
588 .action("Settings", zed_actions::OpenSettings.boxed_clone())
589 .action("Key Bindings", Box::new(zed_actions::OpenKeymap))
590 .action("Themes…", theme_selector::Toggle::default().boxed_clone())
591 .action("Extensions", extensions_ui::Extensions.boxed_clone())
592 .separator()
593 .action("Sign Out", client::SignOut.boxed_clone())
594 })
595 .into()
596 })
597 .trigger(
598 ButtonLike::new("user-menu")
599 .child(
600 h_flex()
601 .gap_0p5()
602 .child(Avatar::new(user.avatar_uri.clone()))
603 .child(
604 Icon::new(IconName::ChevronDown)
605 .size(IconSize::Small)
606 .color(Color::Muted),
607 ),
608 )
609 .style(ButtonStyle::Subtle)
610 .tooltip(move |cx| Tooltip::text("Toggle User Menu", cx)),
611 )
612 .anchor(gpui::AnchorCorner::TopRight)
613 } else {
614 PopoverMenu::new("user-menu")
615 .menu(|cx| {
616 ContextMenu::build(cx, |menu, _| {
617 menu.action("Settings", zed_actions::OpenSettings.boxed_clone())
618 .action("Key Bindings", Box::new(zed_actions::OpenKeymap))
619 .action("Themes…", theme_selector::Toggle::default().boxed_clone())
620 .action("Extensions", extensions_ui::Extensions.boxed_clone())
621 })
622 .into()
623 })
624 .trigger(
625 ButtonLike::new("user-menu")
626 .child(
627 h_flex().gap_0p5().child(
628 Icon::new(IconName::ChevronDown)
629 .size(IconSize::Small)
630 .color(Color::Muted),
631 ),
632 )
633 .style(ButtonStyle::Subtle)
634 .tooltip(move |cx| Tooltip::text("Toggle User Menu", cx)),
635 )
636 }
637 }
638}
639
640impl InteractiveElement for TitleBar {
641 fn interactivity(&mut self) -> &mut Interactivity {
642 self.content.interactivity()
643 }
644}
645
646impl StatefulInteractiveElement for TitleBar {}
647
648impl ParentElement for TitleBar {
649 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
650 self.children.extend(elements)
651 }
652}