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