1use crate::face_pile::FacePile;
2use auto_update::AutoUpdateStatus;
3use call::{ActiveCall, ParticipantLocation, Room};
4use client::{proto::PeerId, Client, User, UserStore};
5use gpui::{
6 actions, canvas, div, point, px, Action, AnyElement, AppContext, Element, Hsla,
7 InteractiveElement, IntoElement, Model, ParentElement, Path, Render,
8 StatefulInteractiveElement, Styled, Subscription, View, ViewContext, VisualContext, WeakView,
9 WindowBounds,
10};
11use project::{Project, RepositoryEntry};
12use recent_projects::RecentProjects;
13use rpc::proto;
14use std::sync::Arc;
15use theme::ActiveTheme;
16use ui::{
17 h_flex, popover_menu, prelude::*, Avatar, AvatarAudioStatusIndicator, Button, ButtonLike,
18 ButtonStyle, ContextMenu, Icon, IconButton, IconName, TintColor, Tooltip,
19};
20use util::ResultExt;
21use vcs_menu::{build_branch_list, BranchList, OpenRecent as ToggleVcsMenu};
22use workspace::{notifications::NotifyResultExt, titlebar_height, Workspace};
23
24const MAX_PROJECT_NAME_LENGTH: usize = 40;
25const MAX_BRANCH_NAME_LENGTH: usize = 40;
26
27actions!(
28 collab,
29 [
30 ShareProject,
31 UnshareProject,
32 ToggleUserMenu,
33 ToggleProjectMenu,
34 SwitchBranch
35 ]
36);
37
38pub fn init(cx: &mut AppContext) {
39 cx.observe_new_views(|workspace: &mut Workspace, cx| {
40 let titlebar_item = cx.new_view(|cx| CollabTitlebarItem::new(workspace, cx));
41 workspace.set_titlebar_item(titlebar_item.into(), cx)
42 })
43 .detach();
44}
45
46pub struct CollabTitlebarItem {
47 project: Model<Project>,
48 user_store: Model<UserStore>,
49 client: Arc<Client>,
50 workspace: WeakView<Workspace>,
51 _subscriptions: Vec<Subscription>,
52}
53
54impl Render for CollabTitlebarItem {
55 fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
56 let room = ActiveCall::global(cx).read(cx).room().cloned();
57 let current_user = self.user_store.read(cx).current_user();
58 let client = self.client.clone();
59 let project_id = self.project.read(cx).remote_id();
60 let workspace = self.workspace.upgrade();
61
62 h_flex()
63 .id("titlebar")
64 .justify_between()
65 .w_full()
66 .h(titlebar_height(cx))
67 .map(|this| {
68 if matches!(cx.window_bounds(), WindowBounds::Fullscreen) {
69 this.pl_2()
70 } else {
71 // Use pixels here instead of a rem-based size because the macOS traffic
72 // lights are a static size, and don't scale with the rest of the UI.
73 this.pl(px(80.))
74 }
75 })
76 .bg(cx.theme().colors().title_bar_background)
77 .on_click(|event, cx| {
78 if event.up.click_count == 2 {
79 cx.zoom_window();
80 }
81 })
82 // left side
83 .child(
84 h_flex()
85 .gap_1()
86 .children(self.render_project_host(cx))
87 .child(self.render_project_name(cx))
88 .children(self.render_project_branch(cx)),
89 )
90 .child(
91 h_flex()
92 .id("collaborator-list")
93 .w_full()
94 .gap_1()
95 .overflow_x_scroll()
96 .when_some(
97 current_user.clone().zip(client.peer_id()).zip(room.clone()),
98 |this, ((current_user, peer_id), room)| {
99 let player_colors = cx.theme().players();
100 let room = room.read(cx);
101 let mut remote_participants =
102 room.remote_participants().values().collect::<Vec<_>>();
103 remote_participants.sort_by_key(|p| p.participant_index.0);
104
105 let current_user_face_pile = self.render_collaborator(
106 ¤t_user,
107 peer_id,
108 true,
109 room.is_speaking(),
110 room.is_muted(),
111 None,
112 &room,
113 project_id,
114 ¤t_user,
115 cx,
116 );
117
118 this.children(current_user_face_pile.map(|face_pile| {
119 v_flex()
120 .child(face_pile)
121 .child(render_color_ribbon(player_colors.local().cursor))
122 }))
123 .children(
124 remote_participants.iter().filter_map(|collaborator| {
125 let player_color = player_colors
126 .color_for_participant(collaborator.participant_index.0);
127 let is_following = workspace
128 .as_ref()?
129 .read(cx)
130 .is_being_followed(collaborator.peer_id);
131 let is_present = project_id.map_or(false, |project_id| {
132 collaborator.location
133 == ParticipantLocation::SharedProject { project_id }
134 });
135
136 let face_pile = self.render_collaborator(
137 &collaborator.user,
138 collaborator.peer_id,
139 is_present,
140 collaborator.speaking,
141 collaborator.muted,
142 is_following.then_some(player_color.selection),
143 &room,
144 project_id,
145 ¤t_user,
146 cx,
147 )?;
148
149 Some(
150 v_flex()
151 .id(("collaborator", collaborator.user.id))
152 .child(face_pile)
153 .child(render_color_ribbon(player_color.cursor))
154 .cursor_pointer()
155 .on_click({
156 let peer_id = collaborator.peer_id;
157 cx.listener(move |this, _, cx| {
158 this.workspace
159 .update(cx, |workspace, cx| {
160 workspace.follow(peer_id, cx);
161 })
162 .ok();
163 })
164 })
165 .tooltip({
166 let login = collaborator.user.github_login.clone();
167 move |cx| {
168 Tooltip::text(format!("Follow {login}"), cx)
169 }
170 }),
171 )
172 }),
173 )
174 },
175 ),
176 )
177 // right side
178 .child(
179 h_flex()
180 .gap_1()
181 .pr_1()
182 .when_some(room, |this, room| {
183 let room = room.read(cx);
184 let project = self.project.read(cx);
185 let is_local = project.is_local();
186 let is_shared = is_local && project.is_shared();
187 let is_muted = room.is_muted();
188 let is_deafened = room.is_deafened().unwrap_or(false);
189 let is_screen_sharing = room.is_screen_sharing();
190 let read_only = room.read_only();
191
192 this.when(is_local && !read_only, |this| {
193 this.child(
194 Button::new(
195 "toggle_sharing",
196 if is_shared { "Unshare" } else { "Share" },
197 )
198 .tooltip(move |cx| {
199 Tooltip::text(
200 if is_shared {
201 "Stop sharing project with call participants"
202 } else {
203 "Share project with call participants"
204 },
205 cx,
206 )
207 })
208 .style(ButtonStyle::Subtle)
209 .selected_style(ButtonStyle::Tinted(TintColor::Accent))
210 .selected(is_shared)
211 .label_size(LabelSize::Small)
212 .on_click(cx.listener(
213 move |this, _, cx| {
214 if is_shared {
215 this.unshare_project(&Default::default(), cx);
216 } else {
217 this.share_project(&Default::default(), cx);
218 }
219 },
220 )),
221 )
222 })
223 .child(
224 div()
225 .child(
226 IconButton::new("leave-call", ui::IconName::Exit)
227 .style(ButtonStyle::Subtle)
228 .tooltip(|cx| Tooltip::text("Leave call", cx))
229 .icon_size(IconSize::Small)
230 .on_click(move |_, cx| {
231 ActiveCall::global(cx)
232 .update(cx, |call, cx| call.hang_up(cx))
233 .detach_and_log_err(cx);
234 }),
235 )
236 .pr_2(),
237 )
238 .when(!read_only, |this| {
239 this.child(
240 IconButton::new(
241 "mute-microphone",
242 if is_muted {
243 ui::IconName::MicMute
244 } else {
245 ui::IconName::Mic
246 },
247 )
248 .tooltip(move |cx| {
249 Tooltip::text(
250 if is_muted {
251 "Unmute microphone"
252 } else {
253 "Mute microphone"
254 },
255 cx,
256 )
257 })
258 .style(ButtonStyle::Subtle)
259 .icon_size(IconSize::Small)
260 .selected(is_muted)
261 .selected_style(ButtonStyle::Tinted(TintColor::Negative))
262 .on_click(move |_, cx| crate::toggle_mute(&Default::default(), cx)),
263 )
264 })
265 .child(
266 IconButton::new(
267 "mute-sound",
268 if is_deafened {
269 ui::IconName::AudioOff
270 } else {
271 ui::IconName::AudioOn
272 },
273 )
274 .style(ButtonStyle::Subtle)
275 .selected_style(ButtonStyle::Tinted(TintColor::Negative))
276 .icon_size(IconSize::Small)
277 .selected(is_deafened)
278 .tooltip(move |cx| {
279 if !read_only {
280 Tooltip::with_meta(
281 "Deafen Audio",
282 None,
283 "Mic will be muted",
284 cx,
285 )
286 } else {
287 Tooltip::text("Deafen Audio", cx)
288 }
289 })
290 .on_click(move |_, cx| crate::toggle_deafen(&Default::default(), cx)),
291 )
292 .when(!read_only, |this| {
293 this.child(
294 IconButton::new("screen-share", ui::IconName::Screen)
295 .style(ButtonStyle::Subtle)
296 .icon_size(IconSize::Small)
297 .selected(is_screen_sharing)
298 .selected_style(ButtonStyle::Tinted(TintColor::Accent))
299 .tooltip(move |cx| {
300 Tooltip::text(
301 if is_screen_sharing {
302 "Stop Sharing Screen"
303 } else {
304 "Share Screen"
305 },
306 cx,
307 )
308 })
309 .on_click(move |_, cx| {
310 crate::toggle_screen_sharing(&Default::default(), cx)
311 }),
312 )
313 })
314 .child(div().pr_2())
315 })
316 .map(|el| {
317 let status = self.client.status();
318 let status = &*status.borrow();
319 if matches!(status, client::Status::Connected { .. }) {
320 el.child(self.render_user_menu_button(cx))
321 } else {
322 el.children(self.render_connection_status(status, cx))
323 .child(self.render_sign_in_button(cx))
324 .child(self.render_user_menu_button(cx))
325 }
326 }),
327 )
328 }
329}
330
331fn render_color_ribbon(color: Hsla) -> gpui::Canvas {
332 canvas(move |bounds, cx| {
333 let height = bounds.size.height;
334 let horizontal_offset = height;
335 let vertical_offset = px(height.0 / 2.0);
336 let mut path = Path::new(bounds.lower_left());
337 path.curve_to(
338 bounds.origin + point(horizontal_offset, vertical_offset),
339 bounds.origin + point(px(0.0), vertical_offset),
340 );
341 path.line_to(bounds.upper_right() + point(-horizontal_offset, vertical_offset));
342 path.curve_to(
343 bounds.lower_right(),
344 bounds.upper_right() + point(px(0.0), vertical_offset),
345 );
346 path.line_to(bounds.lower_left());
347 cx.paint_path(path, color);
348 })
349 .h_1()
350 .w_full()
351}
352
353impl CollabTitlebarItem {
354 pub fn new(workspace: &Workspace, cx: &mut ViewContext<Self>) -> Self {
355 let project = workspace.project().clone();
356 let user_store = workspace.app_state().user_store.clone();
357 let client = workspace.app_state().client.clone();
358 let active_call = ActiveCall::global(cx);
359 let mut subscriptions = Vec::new();
360 subscriptions.push(
361 cx.observe(&workspace.weak_handle().upgrade().unwrap(), |_, _, cx| {
362 cx.notify()
363 }),
364 );
365 subscriptions.push(cx.observe(&project, |_, _, cx| cx.notify()));
366 subscriptions.push(cx.observe(&active_call, |this, _, cx| this.active_call_changed(cx)));
367 subscriptions.push(cx.observe_window_activation(Self::window_activation_changed));
368 subscriptions.push(cx.observe(&user_store, |_, _, cx| cx.notify()));
369
370 Self {
371 workspace: workspace.weak_handle(),
372 project,
373 user_store,
374 client,
375 _subscriptions: subscriptions,
376 }
377 }
378
379 // resolve if you are in a room -> render_project_owner
380 // render_project_owner -> resolve if you are in a room -> Option<foo>
381
382 pub fn render_project_host(&self, cx: &mut ViewContext<Self>) -> Option<impl IntoElement> {
383 let host = self.project.read(cx).host()?;
384 let host_user = self.user_store.read(cx).get_cached_user(host.user_id)?;
385 let participant_index = self
386 .user_store
387 .read(cx)
388 .participant_indices()
389 .get(&host_user.id)?;
390 Some(
391 Button::new("project_owner_trigger", host_user.github_login.clone())
392 .color(Color::Player(participant_index.0))
393 .style(ButtonStyle::Subtle)
394 .label_size(LabelSize::Small)
395 .tooltip(move |cx| {
396 Tooltip::text(
397 format!(
398 "{} is sharing this project. Click to follow.",
399 host_user.github_login.clone()
400 ),
401 cx,
402 )
403 })
404 .on_click({
405 let host_peer_id = host.peer_id.clone();
406 cx.listener(move |this, _, cx| {
407 this.workspace
408 .update(cx, |workspace, cx| {
409 workspace.follow(host_peer_id, cx);
410 })
411 .log_err();
412 })
413 }),
414 )
415 }
416
417 pub fn render_project_name(&self, cx: &mut ViewContext<Self>) -> impl Element {
418 let name = {
419 let mut names = self.project.read(cx).visible_worktrees(cx).map(|worktree| {
420 let worktree = worktree.read(cx);
421 worktree.root_name()
422 });
423
424 names.next().unwrap_or("")
425 };
426
427 let name = util::truncate_and_trailoff(name, MAX_PROJECT_NAME_LENGTH);
428 let workspace = self.workspace.clone();
429 popover_menu("project_name_trigger")
430 .trigger(
431 Button::new("project_name_trigger", name)
432 .style(ButtonStyle::Subtle)
433 .label_size(LabelSize::Small)
434 .tooltip(move |cx| Tooltip::text("Recent Projects", cx)),
435 )
436 .menu(move |cx| Some(Self::render_project_popover(workspace.clone(), cx)))
437 }
438
439 pub fn render_project_branch(&self, cx: &mut ViewContext<Self>) -> Option<impl Element> {
440 let entry = {
441 let mut names_and_branches =
442 self.project.read(cx).visible_worktrees(cx).map(|worktree| {
443 let worktree = worktree.read(cx);
444 worktree.root_git_entry()
445 });
446
447 names_and_branches.next().flatten()
448 };
449 let workspace = self.workspace.upgrade()?;
450 let branch_name = entry
451 .as_ref()
452 .and_then(RepositoryEntry::branch)
453 .map(|branch| util::truncate_and_trailoff(&branch, MAX_BRANCH_NAME_LENGTH))?;
454 Some(
455 popover_menu("project_branch_trigger")
456 .trigger(
457 Button::new("project_branch_trigger", branch_name)
458 .color(Color::Muted)
459 .style(ButtonStyle::Subtle)
460 .label_size(LabelSize::Small)
461 .tooltip(move |cx| {
462 Tooltip::with_meta(
463 "Recent Branches",
464 Some(&ToggleVcsMenu),
465 "Local branches only",
466 cx,
467 )
468 }),
469 )
470 .menu(move |cx| Self::render_vcs_popover(workspace.clone(), cx)),
471 )
472 }
473
474 fn render_collaborator(
475 &self,
476 user: &Arc<User>,
477 peer_id: PeerId,
478 is_present: bool,
479 is_speaking: bool,
480 is_muted: bool,
481 leader_selection_color: Option<Hsla>,
482 room: &Room,
483 project_id: Option<u64>,
484 current_user: &Arc<User>,
485 cx: &ViewContext<Self>,
486 ) -> Option<Div> {
487 if room.role_for_user(user.id) == Some(proto::ChannelRole::Guest) {
488 return None;
489 }
490
491 const FACEPILE_LIMIT: usize = 3;
492 let followers = project_id.map_or(&[] as &[_], |id| room.followers_for(peer_id, id));
493 let extra_count = followers.len().saturating_sub(FACEPILE_LIMIT);
494
495 Some(
496 div()
497 .m_0p5()
498 .p_0p5()
499 // When the collaborator is not followed, still draw this wrapper div, but leave
500 // it transparent, so that it does not shift the layout when following.
501 .when_some(leader_selection_color, |div, color| {
502 div.rounded_md().bg(color)
503 })
504 .child(
505 FacePile::empty()
506 .child(
507 Avatar::new(user.avatar_uri.clone())
508 .grayscale(!is_present)
509 .border_color(if is_speaking {
510 cx.theme().status().info
511 } else {
512 // We draw the border in a transparent color rather to avoid
513 // the layout shift that would come with adding/removing the border.
514 gpui::transparent_black()
515 })
516 .when(is_muted, |avatar| {
517 avatar.indicator(
518 AvatarAudioStatusIndicator::new(ui::AudioStatus::Muted)
519 .tooltip({
520 let github_login = user.github_login.clone();
521 move |cx| {
522 Tooltip::text(
523 format!("{} is muted", github_login),
524 cx,
525 )
526 }
527 }),
528 )
529 }),
530 )
531 .children(followers.iter().take(FACEPILE_LIMIT).filter_map(
532 |follower_peer_id| {
533 let follower = room
534 .remote_participants()
535 .values()
536 .find_map(|p| {
537 (p.peer_id == *follower_peer_id).then_some(&p.user)
538 })
539 .or_else(|| {
540 (self.client.peer_id() == Some(*follower_peer_id))
541 .then_some(current_user)
542 })?
543 .clone();
544
545 Some(Avatar::new(follower.avatar_uri.clone()))
546 },
547 ))
548 .children(if extra_count > 0 {
549 Some(
550 div()
551 .ml_1()
552 .child(Label::new(format!("+{extra_count}")))
553 .into_any_element(),
554 )
555 } else {
556 None
557 }),
558 ),
559 )
560 }
561
562 fn window_activation_changed(&mut self, cx: &mut ViewContext<Self>) {
563 let project = if cx.is_window_active() {
564 Some(self.project.clone())
565 } else {
566 None
567 };
568 ActiveCall::global(cx)
569 .update(cx, |call, cx| call.set_location(project.as_ref(), cx))
570 .detach_and_log_err(cx);
571 }
572
573 fn active_call_changed(&mut self, cx: &mut ViewContext<Self>) {
574 cx.notify();
575 }
576
577 fn share_project(&mut self, _: &ShareProject, cx: &mut ViewContext<Self>) {
578 let active_call = ActiveCall::global(cx);
579 let project = self.project.clone();
580 active_call
581 .update(cx, |call, cx| call.share_project(project, cx))
582 .detach_and_log_err(cx);
583 }
584
585 fn unshare_project(&mut self, _: &UnshareProject, cx: &mut ViewContext<Self>) {
586 let active_call = ActiveCall::global(cx);
587 let project = self.project.clone();
588 active_call
589 .update(cx, |call, cx| call.unshare_project(project, cx))
590 .log_err();
591 }
592
593 pub fn render_vcs_popover(
594 workspace: View<Workspace>,
595 cx: &mut WindowContext<'_>,
596 ) -> Option<View<BranchList>> {
597 let view = build_branch_list(workspace, cx).log_err()?;
598 let focus_handle = view.focus_handle(cx);
599 cx.focus(&focus_handle);
600 Some(view)
601 }
602
603 pub fn render_project_popover(
604 workspace: WeakView<Workspace>,
605 cx: &mut WindowContext<'_>,
606 ) -> View<RecentProjects> {
607 let view = RecentProjects::open_popover(workspace, cx);
608
609 let focus_handle = view.focus_handle(cx);
610 cx.focus(&focus_handle);
611 view
612 }
613
614 fn render_connection_status(
615 &self,
616 status: &client::Status,
617 cx: &mut ViewContext<Self>,
618 ) -> Option<AnyElement> {
619 match status {
620 client::Status::ConnectionError
621 | client::Status::ConnectionLost
622 | client::Status::Reauthenticating { .. }
623 | client::Status::Reconnecting { .. }
624 | client::Status::ReconnectionError { .. } => Some(
625 div()
626 .id("disconnected")
627 .child(Icon::new(IconName::Disconnected).size(IconSize::Small))
628 .tooltip(|cx| Tooltip::text("Disconnected", cx))
629 .into_any_element(),
630 ),
631 client::Status::UpgradeRequired => {
632 let auto_updater = auto_update::AutoUpdater::get(cx);
633 let label = match auto_updater.map(|auto_update| auto_update.read(cx).status()) {
634 Some(AutoUpdateStatus::Updated) => "Please restart Zed to Collaborate",
635 Some(AutoUpdateStatus::Installing)
636 | Some(AutoUpdateStatus::Downloading)
637 | Some(AutoUpdateStatus::Checking) => "Updating...",
638 Some(AutoUpdateStatus::Idle) | Some(AutoUpdateStatus::Errored) | None => {
639 "Please update Zed to Collaborate"
640 }
641 };
642
643 Some(
644 Button::new("connection-status", label)
645 .label_size(LabelSize::Small)
646 .on_click(|_, cx| {
647 if let Some(auto_updater) = auto_update::AutoUpdater::get(cx) {
648 if auto_updater.read(cx).status() == AutoUpdateStatus::Updated {
649 workspace::restart(&Default::default(), cx);
650 return;
651 }
652 }
653 auto_update::check(&Default::default(), cx);
654 })
655 .into_any_element(),
656 )
657 }
658 _ => None,
659 }
660 }
661
662 pub fn render_sign_in_button(&mut self, _: &mut ViewContext<Self>) -> Button {
663 let client = self.client.clone();
664 Button::new("sign_in", "Sign in")
665 .label_size(LabelSize::Small)
666 .on_click(move |_, cx| {
667 let client = client.clone();
668 cx.spawn(move |mut cx| async move {
669 client
670 .authenticate_and_connect(true, &cx)
671 .await
672 .notify_async_err(&mut cx);
673 })
674 .detach();
675 })
676 }
677
678 pub fn render_user_menu_button(&mut self, cx: &mut ViewContext<Self>) -> impl Element {
679 if let Some(user) = self.user_store.read(cx).current_user() {
680 popover_menu("user-menu")
681 .menu(|cx| {
682 ContextMenu::build(cx, |menu, _| {
683 menu.action("Settings", zed_actions::OpenSettings.boxed_clone())
684 .action("Theme", theme_selector::Toggle.boxed_clone())
685 .separator()
686 .action("Share Feedback", feedback::GiveFeedback.boxed_clone())
687 .action("Sign Out", client::SignOut.boxed_clone())
688 })
689 .into()
690 })
691 .trigger(
692 ButtonLike::new("user-menu")
693 .child(
694 h_flex()
695 .gap_0p5()
696 .child(Avatar::new(user.avatar_uri.clone()))
697 .child(Icon::new(IconName::ChevronDown).color(Color::Muted)),
698 )
699 .style(ButtonStyle::Subtle)
700 .tooltip(move |cx| Tooltip::text("Toggle User Menu", cx)),
701 )
702 .anchor(gpui::AnchorCorner::TopRight)
703 } else {
704 popover_menu("user-menu")
705 .menu(|cx| {
706 ContextMenu::build(cx, |menu, _| {
707 menu.action("Settings", zed_actions::OpenSettings.boxed_clone())
708 .action("Theme", theme_selector::Toggle.boxed_clone())
709 .separator()
710 .action("Share Feedback", feedback::GiveFeedback.boxed_clone())
711 })
712 .into()
713 })
714 .trigger(
715 ButtonLike::new("user-menu")
716 .child(
717 h_flex()
718 .gap_0p5()
719 .child(Icon::new(IconName::ChevronDown).color(Color::Muted)),
720 )
721 .style(ButtonStyle::Subtle)
722 .tooltip(move |cx| Tooltip::text("Toggle User Menu", cx)),
723 )
724 }
725 }
726}