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