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