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