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