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 can_use_microphone = room.can_use_microphone();
191 let can_share_projects = room.can_share_projects();
192
193 this.when(is_local && can_share_projects, |this| {
194 this.child(
195 Button::new(
196 "toggle_sharing",
197 if is_shared { "Unshare" } else { "Share" },
198 )
199 .tooltip(move |cx| {
200 Tooltip::text(
201 if is_shared {
202 "Stop sharing project with call participants"
203 } else {
204 "Share project with call participants"
205 },
206 cx,
207 )
208 })
209 .style(ButtonStyle::Subtle)
210 .selected_style(ButtonStyle::Tinted(TintColor::Accent))
211 .selected(is_shared)
212 .label_size(LabelSize::Small)
213 .on_click(cx.listener(
214 move |this, _, cx| {
215 if is_shared {
216 this.unshare_project(&Default::default(), cx);
217 } else {
218 this.share_project(&Default::default(), cx);
219 }
220 },
221 )),
222 )
223 })
224 .child(
225 div()
226 .child(
227 IconButton::new("leave-call", ui::IconName::Exit)
228 .style(ButtonStyle::Subtle)
229 .tooltip(|cx| Tooltip::text("Leave call", cx))
230 .icon_size(IconSize::Small)
231 .on_click(move |_, cx| {
232 ActiveCall::global(cx)
233 .update(cx, |call, cx| call.hang_up(cx))
234 .detach_and_log_err(cx);
235 }),
236 )
237 .pr_2(),
238 )
239 .when(can_use_microphone, |this| {
240 this.child(
241 IconButton::new(
242 "mute-microphone",
243 if is_muted {
244 ui::IconName::MicMute
245 } else {
246 ui::IconName::Mic
247 },
248 )
249 .tooltip(move |cx| {
250 Tooltip::text(
251 if is_muted {
252 "Unmute microphone"
253 } else {
254 "Mute microphone"
255 },
256 cx,
257 )
258 })
259 .style(ButtonStyle::Subtle)
260 .icon_size(IconSize::Small)
261 .selected(is_muted)
262 .selected_style(ButtonStyle::Tinted(TintColor::Negative))
263 .on_click(move |_, cx| crate::toggle_mute(&Default::default(), cx)),
264 )
265 })
266 .child(
267 IconButton::new(
268 "mute-sound",
269 if is_deafened {
270 ui::IconName::AudioOff
271 } else {
272 ui::IconName::AudioOn
273 },
274 )
275 .style(ButtonStyle::Subtle)
276 .selected_style(ButtonStyle::Tinted(TintColor::Negative))
277 .icon_size(IconSize::Small)
278 .selected(is_deafened)
279 .tooltip(move |cx| {
280 if can_use_microphone {
281 Tooltip::with_meta(
282 "Deafen Audio",
283 None,
284 "Mic will be muted",
285 cx,
286 )
287 } else {
288 Tooltip::text("Deafen Audio", cx)
289 }
290 })
291 .on_click(move |_, cx| crate::toggle_deafen(&Default::default(), cx)),
292 )
293 .when(can_share_projects, |this| {
294 this.child(
295 IconButton::new("screen-share", ui::IconName::Screen)
296 .style(ButtonStyle::Subtle)
297 .icon_size(IconSize::Small)
298 .selected(is_screen_sharing)
299 .selected_style(ButtonStyle::Tinted(TintColor::Accent))
300 .tooltip(move |cx| {
301 Tooltip::text(
302 if is_screen_sharing {
303 "Stop Sharing Screen"
304 } else {
305 "Share Screen"
306 },
307 cx,
308 )
309 })
310 .on_click(move |_, cx| {
311 crate::toggle_screen_sharing(&Default::default(), cx)
312 }),
313 )
314 })
315 .child(div().pr_2())
316 })
317 .map(|el| {
318 let status = self.client.status();
319 let status = &*status.borrow();
320 if matches!(status, client::Status::Connected { .. }) {
321 el.child(self.render_user_menu_button(cx))
322 } else {
323 el.children(self.render_connection_status(status, cx))
324 .child(self.render_sign_in_button(cx))
325 .child(self.render_user_menu_button(cx))
326 }
327 }),
328 )
329 }
330}
331
332fn render_color_ribbon(color: Hsla) -> gpui::Canvas {
333 canvas(move |bounds, cx| {
334 let height = bounds.size.height;
335 let horizontal_offset = height;
336 let vertical_offset = px(height.0 / 2.0);
337 let mut path = Path::new(bounds.lower_left());
338 path.curve_to(
339 bounds.origin + point(horizontal_offset, vertical_offset),
340 bounds.origin + point(px(0.0), vertical_offset),
341 );
342 path.line_to(bounds.upper_right() + point(-horizontal_offset, vertical_offset));
343 path.curve_to(
344 bounds.lower_right(),
345 bounds.upper_right() + point(px(0.0), vertical_offset),
346 );
347 path.line_to(bounds.lower_left());
348 cx.paint_path(path, color);
349 })
350 .h_1()
351 .w_full()
352}
353
354impl CollabTitlebarItem {
355 pub fn new(workspace: &Workspace, cx: &mut ViewContext<Self>) -> Self {
356 let project = workspace.project().clone();
357 let user_store = workspace.app_state().user_store.clone();
358 let client = workspace.app_state().client.clone();
359 let active_call = ActiveCall::global(cx);
360 let mut subscriptions = Vec::new();
361 subscriptions.push(
362 cx.observe(&workspace.weak_handle().upgrade().unwrap(), |_, _, cx| {
363 cx.notify()
364 }),
365 );
366 subscriptions.push(cx.observe(&project, |_, _, cx| cx.notify()));
367 subscriptions.push(cx.observe(&active_call, |this, _, cx| this.active_call_changed(cx)));
368 subscriptions.push(cx.observe_window_activation(Self::window_activation_changed));
369 subscriptions.push(cx.observe(&user_store, |_, _, cx| cx.notify()));
370
371 Self {
372 workspace: workspace.weak_handle(),
373 project,
374 user_store,
375 client,
376 _subscriptions: subscriptions,
377 }
378 }
379
380 // resolve if you are in a room -> render_project_owner
381 // render_project_owner -> resolve if you are in a room -> Option<foo>
382
383 pub fn render_project_host(&self, cx: &mut ViewContext<Self>) -> Option<impl IntoElement> {
384 let host = self.project.read(cx).host()?;
385 let host_user = self.user_store.read(cx).get_cached_user(host.user_id)?;
386 let participant_index = self
387 .user_store
388 .read(cx)
389 .participant_indices()
390 .get(&host_user.id)?;
391 Some(
392 Button::new("project_owner_trigger", host_user.github_login.clone())
393 .color(Color::Player(participant_index.0))
394 .style(ButtonStyle::Subtle)
395 .label_size(LabelSize::Small)
396 .tooltip(move |cx| {
397 Tooltip::text(
398 format!(
399 "{} is sharing this project. Click to follow.",
400 host_user.github_login.clone()
401 ),
402 cx,
403 )
404 })
405 .on_click({
406 let host_peer_id = host.peer_id;
407 cx.listener(move |this, _, cx| {
408 this.workspace
409 .update(cx, |workspace, cx| {
410 workspace.follow(host_peer_id, cx);
411 })
412 .log_err();
413 })
414 }),
415 )
416 }
417
418 pub fn render_project_name(&self, cx: &mut ViewContext<Self>) -> impl Element {
419 let name = {
420 let mut names = self.project.read(cx).visible_worktrees(cx).map(|worktree| {
421 let worktree = worktree.read(cx);
422 worktree.root_name()
423 });
424
425 names.next()
426 };
427 let is_project_selected = name.is_some();
428 let name = if let Some(name) = name {
429 util::truncate_and_trailoff(name, MAX_PROJECT_NAME_LENGTH)
430 } else {
431 "Open recent project".to_string()
432 };
433
434 let workspace = self.workspace.clone();
435 popover_menu("project_name_trigger")
436 .trigger(
437 Button::new("project_name_trigger", name)
438 .when(!is_project_selected, |b| b.color(Color::Muted))
439 .style(ButtonStyle::Subtle)
440 .label_size(LabelSize::Small)
441 .tooltip(move |cx| Tooltip::text("Recent Projects", cx)),
442 )
443 .menu(move |cx| Some(Self::render_project_popover(workspace.clone(), cx)))
444 }
445
446 pub fn render_project_branch(&self, cx: &mut ViewContext<Self>) -> Option<impl Element> {
447 let entry = {
448 let mut names_and_branches =
449 self.project.read(cx).visible_worktrees(cx).map(|worktree| {
450 let worktree = worktree.read(cx);
451 worktree.root_git_entry()
452 });
453
454 names_and_branches.next().flatten()
455 };
456 let workspace = self.workspace.upgrade()?;
457 let branch_name = entry
458 .as_ref()
459 .and_then(RepositoryEntry::branch)
460 .map(|branch| util::truncate_and_trailoff(&branch, MAX_BRANCH_NAME_LENGTH))?;
461 Some(
462 popover_menu("project_branch_trigger")
463 .trigger(
464 Button::new("project_branch_trigger", branch_name)
465 .color(Color::Muted)
466 .style(ButtonStyle::Subtle)
467 .label_size(LabelSize::Small)
468 .tooltip(move |cx| {
469 Tooltip::with_meta(
470 "Recent Branches",
471 Some(&ToggleVcsMenu),
472 "Local branches only",
473 cx,
474 )
475 }),
476 )
477 .menu(move |cx| Self::render_vcs_popover(workspace.clone(), cx)),
478 )
479 }
480
481 #[allow(clippy::too_many_arguments)]
482 fn render_collaborator(
483 &self,
484 user: &Arc<User>,
485 peer_id: PeerId,
486 is_present: bool,
487 is_speaking: bool,
488 is_muted: bool,
489 leader_selection_color: Option<Hsla>,
490 room: &Room,
491 project_id: Option<u64>,
492 current_user: &Arc<User>,
493 cx: &ViewContext<Self>,
494 ) -> Option<Div> {
495 if room.role_for_user(user.id) == Some(proto::ChannelRole::Guest) {
496 return None;
497 }
498
499 const FACEPILE_LIMIT: usize = 3;
500 let followers = project_id.map_or(&[] as &[_], |id| room.followers_for(peer_id, id));
501 let extra_count = followers.len().saturating_sub(FACEPILE_LIMIT);
502
503 Some(
504 div()
505 .m_0p5()
506 .p_0p5()
507 // When the collaborator is not followed, still draw this wrapper div, but leave
508 // it transparent, so that it does not shift the layout when following.
509 .when_some(leader_selection_color, |div, color| {
510 div.rounded_md().bg(color)
511 })
512 .child(
513 FacePile::empty()
514 .child(
515 Avatar::new(user.avatar_uri.clone())
516 .grayscale(!is_present)
517 .border_color(if is_speaking {
518 cx.theme().status().info
519 } else {
520 // We draw the border in a transparent color rather to avoid
521 // the layout shift that would come with adding/removing the border.
522 gpui::transparent_black()
523 })
524 .when(is_muted, |avatar| {
525 avatar.indicator(
526 AvatarAudioStatusIndicator::new(ui::AudioStatus::Muted)
527 .tooltip({
528 let github_login = user.github_login.clone();
529 move |cx| {
530 Tooltip::text(
531 format!("{} is muted", github_login),
532 cx,
533 )
534 }
535 }),
536 )
537 }),
538 )
539 .children(followers.iter().take(FACEPILE_LIMIT).filter_map(
540 |follower_peer_id| {
541 let follower = room
542 .remote_participants()
543 .values()
544 .find_map(|p| {
545 (p.peer_id == *follower_peer_id).then_some(&p.user)
546 })
547 .or_else(|| {
548 (self.client.peer_id() == Some(*follower_peer_id))
549 .then_some(current_user)
550 })?
551 .clone();
552
553 Some(div().mt(-px(4.)).child(
554 Avatar::new(follower.avatar_uri.clone()).size(rems(0.75)),
555 ))
556 },
557 ))
558 .children(if extra_count > 0 {
559 Some(
560 div()
561 .ml_1()
562 .child(Label::new(format!("+{extra_count}")))
563 .into_any_element(),
564 )
565 } else {
566 None
567 }),
568 ),
569 )
570 }
571
572 fn window_activation_changed(&mut self, cx: &mut ViewContext<Self>) {
573 if cx.is_window_active() {
574 ActiveCall::global(cx)
575 .update(cx, |call, cx| call.set_location(Some(&self.project), cx))
576 .detach_and_log_err(cx);
577 } else if cx.active_window().is_none() {
578 ActiveCall::global(cx)
579 .update(cx, |call, cx| call.set_location(None, cx))
580 .detach_and_log_err(cx);
581 }
582 self.workspace
583 .update(cx, |workspace, cx| {
584 workspace.update_active_view_for_followers(cx);
585 })
586 .ok();
587 }
588
589 fn active_call_changed(&mut self, cx: &mut ViewContext<Self>) {
590 cx.notify();
591 }
592
593 fn share_project(&mut self, _: &ShareProject, cx: &mut ViewContext<Self>) {
594 let active_call = ActiveCall::global(cx);
595 let project = self.project.clone();
596 active_call
597 .update(cx, |call, cx| call.share_project(project, cx))
598 .detach_and_log_err(cx);
599 }
600
601 fn unshare_project(&mut self, _: &UnshareProject, cx: &mut ViewContext<Self>) {
602 let active_call = ActiveCall::global(cx);
603 let project = self.project.clone();
604 active_call
605 .update(cx, |call, cx| call.unshare_project(project, cx))
606 .log_err();
607 }
608
609 pub fn render_vcs_popover(
610 workspace: View<Workspace>,
611 cx: &mut WindowContext<'_>,
612 ) -> Option<View<BranchList>> {
613 let view = build_branch_list(workspace, cx).log_err()?;
614 let focus_handle = view.focus_handle(cx);
615 cx.focus(&focus_handle);
616 Some(view)
617 }
618
619 pub fn render_project_popover(
620 workspace: WeakView<Workspace>,
621 cx: &mut WindowContext<'_>,
622 ) -> View<RecentProjects> {
623 let view = RecentProjects::open_popover(workspace, cx);
624
625 let focus_handle = view.focus_handle(cx);
626 cx.focus(&focus_handle);
627 view
628 }
629
630 fn render_connection_status(
631 &self,
632 status: &client::Status,
633 cx: &mut ViewContext<Self>,
634 ) -> Option<AnyElement> {
635 match status {
636 client::Status::ConnectionError
637 | client::Status::ConnectionLost
638 | client::Status::Reauthenticating { .. }
639 | client::Status::Reconnecting { .. }
640 | client::Status::ReconnectionError { .. } => Some(
641 div()
642 .id("disconnected")
643 .child(Icon::new(IconName::Disconnected).size(IconSize::Small))
644 .tooltip(|cx| Tooltip::text("Disconnected", cx))
645 .into_any_element(),
646 ),
647 client::Status::UpgradeRequired => {
648 let auto_updater = auto_update::AutoUpdater::get(cx);
649 let label = match auto_updater.map(|auto_update| auto_update.read(cx).status()) {
650 Some(AutoUpdateStatus::Updated) => "Please restart Zed to Collaborate",
651 Some(AutoUpdateStatus::Installing)
652 | Some(AutoUpdateStatus::Downloading)
653 | Some(AutoUpdateStatus::Checking) => "Updating...",
654 Some(AutoUpdateStatus::Idle) | Some(AutoUpdateStatus::Errored) | None => {
655 "Please update Zed to Collaborate"
656 }
657 };
658
659 Some(
660 Button::new("connection-status", label)
661 .label_size(LabelSize::Small)
662 .on_click(|_, cx| {
663 if let Some(auto_updater) = auto_update::AutoUpdater::get(cx) {
664 if auto_updater.read(cx).status() == AutoUpdateStatus::Updated {
665 workspace::restart(&Default::default(), cx);
666 return;
667 }
668 }
669 auto_update::check(&Default::default(), cx);
670 })
671 .into_any_element(),
672 )
673 }
674 _ => None,
675 }
676 }
677
678 pub fn render_sign_in_button(&mut self, _: &mut ViewContext<Self>) -> Button {
679 let client = self.client.clone();
680 Button::new("sign_in", "Sign in")
681 .label_size(LabelSize::Small)
682 .on_click(move |_, cx| {
683 let client = client.clone();
684 cx.spawn(move |mut cx| async move {
685 client
686 .authenticate_and_connect(true, &cx)
687 .await
688 .notify_async_err(&mut cx);
689 })
690 .detach();
691 })
692 }
693
694 pub fn render_user_menu_button(&mut self, cx: &mut ViewContext<Self>) -> impl Element {
695 if let Some(user) = self.user_store.read(cx).current_user() {
696 popover_menu("user-menu")
697 .menu(|cx| {
698 ContextMenu::build(cx, |menu, _| {
699 menu.action("Settings", zed_actions::OpenSettings.boxed_clone())
700 .action("Extensions", extensions_ui::Extensions.boxed_clone())
701 .action("Theme...", theme_selector::Toggle.boxed_clone())
702 .separator()
703 .action("Share Feedback...", feedback::GiveFeedback.boxed_clone())
704 .action("Sign Out", client::SignOut.boxed_clone())
705 })
706 .into()
707 })
708 .trigger(
709 ButtonLike::new("user-menu")
710 .child(
711 h_flex()
712 .gap_0p5()
713 .child(Avatar::new(user.avatar_uri.clone()))
714 .child(Icon::new(IconName::ChevronDown).color(Color::Muted)),
715 )
716 .style(ButtonStyle::Subtle)
717 .tooltip(move |cx| Tooltip::text("Toggle User Menu", cx)),
718 )
719 .anchor(gpui::AnchorCorner::TopRight)
720 } else {
721 popover_menu("user-menu")
722 .menu(|cx| {
723 ContextMenu::build(cx, |menu, _| {
724 menu.action("Settings", zed_actions::OpenSettings.boxed_clone())
725 .action("Theme...", theme_selector::Toggle.boxed_clone())
726 .action("Extensions", extensions_ui::Extensions.boxed_clone())
727 .separator()
728 .action("Share Feedback...", feedback::GiveFeedback.boxed_clone())
729 })
730 .into()
731 })
732 .trigger(
733 ButtonLike::new("user-menu")
734 .child(
735 h_flex()
736 .gap_0p5()
737 .child(Icon::new(IconName::ChevronDown).color(Color::Muted)),
738 )
739 .style(ButtonStyle::Subtle)
740 .tooltip(move |cx| Tooltip::text("Toggle User Menu", cx)),
741 )
742 }
743 }
744}