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