1use std::rc::Rc;
2use std::sync::Arc;
3
4use call::{ActiveCall, ParticipantLocation, Room};
5use channel::ChannelStore;
6use client::{User, proto::PeerId};
7use gpui::{
8 AnyElement, Hsla, IntoElement, MouseButton, Path, ScreenCaptureSource, Styled, WeakEntity,
9 canvas, point,
10};
11use gpui::{App, Task, Window, actions};
12use project::WorktreeSettings;
13use rpc::proto::{self};
14use settings::{Settings as _, SettingsLocation};
15use theme::ActiveTheme;
16use ui::{
17 Avatar, AvatarAudioStatusIndicator, ContextMenu, ContextMenuItem, Divider, DividerColor,
18 Facepile, PopoverMenu, SplitButton, SplitButtonStyle, TintColor, Tooltip, prelude::*,
19};
20use util::rel_path::RelPath;
21use workspace::notifications::DetachAndPromptErr;
22
23use crate::TitleBar;
24
25actions!(
26 collab,
27 [
28 /// Toggles screen sharing on or off.
29 ToggleScreenSharing,
30 /// Toggles microphone mute.
31 ToggleMute,
32 /// Toggles deafen mode (mute both microphone and speakers).
33 ToggleDeafen
34 ]
35);
36
37fn toggle_screen_sharing(
38 screen: anyhow::Result<Option<Rc<dyn ScreenCaptureSource>>>,
39 window: &mut Window,
40 cx: &mut App,
41) {
42 let call = ActiveCall::global(cx).read(cx);
43 let toggle_screen_sharing = match screen {
44 Ok(screen) => {
45 let Some(room) = call.room().cloned() else {
46 return;
47 };
48
49 room.update(cx, |room, cx| {
50 let clicked_on_currently_shared_screen =
51 room.shared_screen_id().is_some_and(|screen_id| {
52 Some(screen_id)
53 == screen
54 .as_deref()
55 .and_then(|s| s.metadata().ok().map(|meta| meta.id))
56 });
57 let should_unshare_current_screen = room.is_sharing_screen();
58 let unshared_current_screen = should_unshare_current_screen.then(|| {
59 telemetry::event!(
60 "Screen Share Disabled",
61 room_id = room.id(),
62 channel_id = room.channel_id(),
63 );
64 room.unshare_screen(clicked_on_currently_shared_screen || screen.is_none(), cx)
65 });
66 if let Some(screen) = screen {
67 if !should_unshare_current_screen {
68 telemetry::event!(
69 "Screen Share Enabled",
70 room_id = room.id(),
71 channel_id = room.channel_id(),
72 );
73 }
74 cx.spawn(async move |room, cx| {
75 unshared_current_screen.transpose()?;
76 if !clicked_on_currently_shared_screen {
77 room.update(cx, |room, cx| room.share_screen(screen, cx))?
78 .await
79 } else {
80 Ok(())
81 }
82 })
83 } else {
84 Task::ready(Ok(()))
85 }
86 })
87 }
88 Err(e) => Task::ready(Err(e)),
89 };
90 toggle_screen_sharing.detach_and_prompt_err("Sharing Screen Failed", window, cx, |e, _, _| Some(format!("{:?}\n\nPlease check that you have given Zed permissions to record your screen in Settings.", e)));
91}
92
93fn toggle_mute(_: &ToggleMute, cx: &mut App) {
94 let call = ActiveCall::global(cx).read(cx);
95 if let Some(room) = call.room().cloned() {
96 room.update(cx, |room, cx| {
97 let operation = if room.is_muted() {
98 "Microphone Enabled"
99 } else {
100 "Microphone Disabled"
101 };
102 telemetry::event!(
103 operation,
104 room_id = room.id(),
105 channel_id = room.channel_id(),
106 );
107
108 room.toggle_mute(cx)
109 });
110 }
111}
112
113fn toggle_deafen(_: &ToggleDeafen, cx: &mut App) {
114 if let Some(room) = ActiveCall::global(cx).read(cx).room().cloned() {
115 room.update(cx, |room, cx| room.toggle_deafen(cx));
116 }
117}
118
119fn render_color_ribbon(color: Hsla) -> impl Element {
120 canvas(
121 move |_, _, _| {},
122 move |bounds, _, window, _| {
123 let height = bounds.size.height;
124 let horizontal_offset = height;
125 let vertical_offset = height / 2.0;
126 let mut path = Path::new(bounds.bottom_left());
127 path.curve_to(
128 bounds.origin + point(horizontal_offset, vertical_offset),
129 bounds.origin + point(px(0.0), vertical_offset),
130 );
131 path.line_to(bounds.top_right() + point(-horizontal_offset, vertical_offset));
132 path.curve_to(
133 bounds.bottom_right(),
134 bounds.top_right() + point(px(0.0), vertical_offset),
135 );
136 path.line_to(bounds.bottom_left());
137 window.paint_path(path, color);
138 },
139 )
140 .h_1()
141 .w_full()
142}
143
144impl TitleBar {
145 pub(crate) fn render_collaborator_list(
146 &self,
147 _: &mut Window,
148 cx: &mut Context<Self>,
149 ) -> impl IntoElement {
150 let room = ActiveCall::global(cx).read(cx).room().cloned();
151 let current_user = self.user_store.read(cx).current_user();
152 let client = self.client.clone();
153 let project_id = self.project.read(cx).remote_id();
154 let workspace = self.workspace.upgrade();
155
156 h_flex()
157 .id("collaborator-list")
158 .w_full()
159 .gap_1()
160 .overflow_x_scroll()
161 .when_some(
162 current_user.zip(client.peer_id()).zip(room),
163 |this, ((current_user, peer_id), room)| {
164 let player_colors = cx.theme().players();
165 let room = room.read(cx);
166 let mut remote_participants =
167 room.remote_participants().values().collect::<Vec<_>>();
168 remote_participants.sort_by_key(|p| p.participant_index.0);
169
170 let current_user_face_pile = self.render_collaborator(
171 ¤t_user,
172 peer_id,
173 true,
174 room.is_speaking(),
175 room.is_muted(),
176 None,
177 room,
178 project_id,
179 ¤t_user,
180 cx,
181 );
182
183 this.children(current_user_face_pile.map(|face_pile| {
184 v_flex()
185 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
186 .child(face_pile)
187 .child(render_color_ribbon(player_colors.local().cursor))
188 }))
189 .children(remote_participants.iter().filter_map(|collaborator| {
190 let player_color =
191 player_colors.color_for_participant(collaborator.participant_index.0);
192 let is_following = workspace
193 .as_ref()?
194 .read(cx)
195 .is_being_followed(collaborator.peer_id);
196 let is_present = project_id.is_some_and(|project_id| {
197 collaborator.location
198 == ParticipantLocation::SharedProject { project_id }
199 });
200
201 let facepile = self.render_collaborator(
202 &collaborator.user,
203 collaborator.peer_id,
204 is_present,
205 collaborator.speaking,
206 collaborator.muted,
207 is_following.then_some(player_color.selection),
208 room,
209 project_id,
210 ¤t_user,
211 cx,
212 )?;
213
214 Some(
215 v_flex()
216 .id(("collaborator", collaborator.user.id))
217 .child(facepile)
218 .child(render_color_ribbon(player_color.cursor))
219 .cursor_pointer()
220 .on_click({
221 let peer_id = collaborator.peer_id;
222 cx.listener(move |this, _, window, cx| {
223 cx.stop_propagation();
224
225 this.workspace
226 .update(cx, |workspace, cx| {
227 if is_following {
228 workspace.unfollow(peer_id, window, cx);
229 } else {
230 workspace.follow(peer_id, window, cx);
231 }
232 })
233 .ok();
234 })
235 })
236 .tooltip({
237 let login = collaborator.user.github_login.clone();
238 Tooltip::text(format!("Follow {login}"))
239 }),
240 )
241 }))
242 },
243 )
244 }
245
246 fn render_collaborator(
247 &self,
248 user: &Arc<User>,
249 peer_id: PeerId,
250 is_present: bool,
251 is_speaking: bool,
252 is_muted: bool,
253 leader_selection_color: Option<Hsla>,
254 room: &Room,
255 project_id: Option<u64>,
256 current_user: &Arc<User>,
257 cx: &App,
258 ) -> Option<Div> {
259 if room.role_for_user(user.id) == Some(proto::ChannelRole::Guest) {
260 return None;
261 }
262
263 const FACEPILE_LIMIT: usize = 3;
264 let followers = project_id.map_or(&[] as &[_], |id| room.followers_for(peer_id, id));
265 let extra_count = followers.len().saturating_sub(FACEPILE_LIMIT);
266
267 Some(
268 div()
269 .m_0p5()
270 .p_0p5()
271 // When the collaborator is not followed, still draw this wrapper div, but leave
272 // it transparent, so that it does not shift the layout when following.
273 .when_some(leader_selection_color, |div, color| {
274 div.rounded_sm().bg(color)
275 })
276 .child(
277 Facepile::empty()
278 .child(
279 Avatar::new(user.avatar_uri.clone())
280 .grayscale(!is_present)
281 .border_color(if is_speaking {
282 cx.theme().status().info
283 } else {
284 // We draw the border in a transparent color rather to avoid
285 // the layout shift that would come with adding/removing the border.
286 gpui::transparent_black()
287 })
288 .when(is_muted, |avatar| {
289 avatar.indicator(
290 AvatarAudioStatusIndicator::new(ui::AudioStatus::Muted)
291 .tooltip({
292 let github_login = user.github_login.clone();
293 Tooltip::text(format!("{} is muted", github_login))
294 }),
295 )
296 }),
297 )
298 .children(followers.iter().take(FACEPILE_LIMIT).filter_map(
299 |follower_peer_id| {
300 let follower = room
301 .remote_participants()
302 .values()
303 .find_map(|p| {
304 (p.peer_id == *follower_peer_id).then_some(&p.user)
305 })
306 .or_else(|| {
307 (self.client.peer_id() == Some(*follower_peer_id))
308 .then_some(current_user)
309 })?
310 .clone();
311
312 Some(div().mt(-px(4.)).child(
313 Avatar::new(follower.avatar_uri.clone()).size(rems(0.75)),
314 ))
315 },
316 ))
317 .children(if extra_count > 0 {
318 Some(
319 Label::new(format!("+{extra_count}"))
320 .ml_1()
321 .into_any_element(),
322 )
323 } else {
324 None
325 }),
326 ),
327 )
328 }
329
330 pub(crate) fn render_call_controls(
331 &self,
332 window: &mut Window,
333 cx: &mut Context<Self>,
334 ) -> Vec<AnyElement> {
335 let Some(room) = ActiveCall::global(cx).read(cx).room().cloned() else {
336 return Vec::new();
337 };
338
339 let is_connecting_to_project = self
340 .workspace
341 .update(cx, |workspace, cx| workspace.has_active_modal(window, cx))
342 .unwrap_or(false);
343
344 let room = room.read(cx);
345 let project = self.project.read(cx);
346 let is_local = project.is_local() || project.is_via_remote_server();
347 let is_shared = is_local && project.is_shared();
348 let is_muted = room.is_muted();
349 let muted_by_user = room.muted_by_user();
350 let is_deafened = room.is_deafened().unwrap_or(false);
351 let is_screen_sharing = room.is_sharing_screen();
352 let can_use_microphone = room.can_use_microphone();
353 let can_share_projects = room.can_share_projects();
354 let screen_sharing_supported = cx.is_screen_capture_supported();
355
356 let channel_store = ChannelStore::global(cx);
357 let channel = room
358 .channel_id()
359 .and_then(|channel_id| channel_store.read(cx).channel_for_id(channel_id).cloned());
360
361 let mut children = Vec::new();
362
363 children.push(
364 h_flex()
365 .gap_1()
366 .child(
367 IconButton::new("leave-call", IconName::Exit)
368 .style(ButtonStyle::Subtle)
369 .tooltip(Tooltip::text("Leave Call"))
370 .icon_size(IconSize::Small)
371 .on_click(move |_, _window, cx| {
372 ActiveCall::global(cx)
373 .update(cx, |call, cx| call.hang_up(cx))
374 .detach_and_log_err(cx);
375 }),
376 )
377 .child(Divider::vertical().color(DividerColor::Border))
378 .into_any_element(),
379 );
380
381 if is_local && can_share_projects && !is_connecting_to_project {
382 let is_sharing_disabled = channel.is_some_and(|channel| match channel.visibility {
383 proto::ChannelVisibility::Public => project.visible_worktrees(cx).any(|worktree| {
384 let worktree_id = worktree.read(cx).id();
385
386 let settings_location = Some(SettingsLocation {
387 worktree_id,
388 path: RelPath::empty(),
389 });
390
391 WorktreeSettings::get(settings_location, cx).prevent_sharing_in_public_channels
392 }),
393 proto::ChannelVisibility::Members => false,
394 });
395
396 children.push(
397 Button::new(
398 "toggle_sharing",
399 if is_shared { "Unshare" } else { "Share" },
400 )
401 .tooltip(Tooltip::text(if is_shared {
402 "Stop sharing project with call participants"
403 } else {
404 "Share project with call participants"
405 }))
406 .style(ButtonStyle::Subtle)
407 .selected_style(ButtonStyle::Tinted(TintColor::Accent))
408 .toggle_state(is_shared)
409 .label_size(LabelSize::Small)
410 .when(is_sharing_disabled, |parent| {
411 parent.disabled(true).tooltip(Tooltip::text(
412 "This project may not be shared in a public channel.",
413 ))
414 })
415 .on_click(cx.listener(move |this, _, window, cx| {
416 if is_shared {
417 this.unshare_project(window, cx);
418 } else {
419 this.share_project(cx);
420 }
421 }))
422 .into_any_element(),
423 );
424 }
425
426 if can_use_microphone {
427 children.push(
428 IconButton::new(
429 "mute-microphone",
430 if is_muted {
431 IconName::MicMute
432 } else {
433 IconName::Mic
434 },
435 )
436 .tooltip(move |_window, cx| {
437 if is_muted {
438 if is_deafened {
439 Tooltip::with_meta(
440 "Unmute Microphone",
441 None,
442 "Audio will be unmuted",
443 cx,
444 )
445 } else {
446 Tooltip::simple("Unmute Microphone", cx)
447 }
448 } else {
449 Tooltip::simple("Mute Microphone", cx)
450 }
451 })
452 .style(ButtonStyle::Subtle)
453 .icon_size(IconSize::Small)
454 .toggle_state(is_muted)
455 .selected_style(ButtonStyle::Tinted(TintColor::Error))
456 .on_click(move |_, _window, cx| {
457 toggle_mute(&Default::default(), cx);
458 })
459 .into_any_element(),
460 );
461 }
462
463 children.push(
464 IconButton::new(
465 "mute-sound",
466 if is_deafened {
467 IconName::AudioOff
468 } else {
469 IconName::AudioOn
470 },
471 )
472 .style(ButtonStyle::Subtle)
473 .selected_style(ButtonStyle::Tinted(TintColor::Error))
474 .icon_size(IconSize::Small)
475 .toggle_state(is_deafened)
476 .tooltip(move |_window, cx| {
477 if is_deafened {
478 let label = "Unmute Audio";
479
480 if !muted_by_user {
481 Tooltip::with_meta(label, None, "Microphone will be unmuted", cx)
482 } else {
483 Tooltip::simple(label, cx)
484 }
485 } else {
486 let label = "Mute Audio";
487
488 if !muted_by_user {
489 Tooltip::with_meta(label, None, "Microphone will be muted", cx)
490 } else {
491 Tooltip::simple(label, cx)
492 }
493 }
494 })
495 .on_click(move |_, _, cx| toggle_deafen(&Default::default(), cx))
496 .into_any_element(),
497 );
498
499 if can_use_microphone && screen_sharing_supported {
500 let trigger = IconButton::new("screen-share", IconName::Screen)
501 .style(ButtonStyle::Subtle)
502 .icon_size(IconSize::Small)
503 .toggle_state(is_screen_sharing)
504 .selected_style(ButtonStyle::Tinted(TintColor::Accent))
505 .tooltip(Tooltip::text(if is_screen_sharing {
506 "Stop Sharing Screen"
507 } else {
508 "Share Screen"
509 }))
510 .on_click(move |_, window, cx| {
511 let should_share = ActiveCall::global(cx)
512 .read(cx)
513 .room()
514 .is_some_and(|room| !room.read(cx).is_sharing_screen());
515
516 window
517 .spawn(cx, async move |cx| {
518 let screen = if should_share {
519 cx.update(|_, cx| pick_default_screen(cx))?.await
520 } else {
521 Ok(None)
522 };
523 cx.update(|window, cx| toggle_screen_sharing(screen, window, cx))?;
524
525 Result::<_, anyhow::Error>::Ok(())
526 })
527 .detach();
528 });
529
530 children.push(
531 SplitButton::new(
532 trigger.render(window, cx),
533 self.render_screen_list().into_any_element(),
534 )
535 .style(SplitButtonStyle::Transparent)
536 .into_any_element(),
537 );
538 }
539
540 children.push(div().pr_2().into_any_element());
541
542 children
543 }
544
545 fn render_screen_list(&self) -> impl IntoElement {
546 PopoverMenu::new("screen-share-screen-list")
547 .with_handle(self.screen_share_popover_handle.clone())
548 .trigger(
549 ui::ButtonLike::new_rounded_right("screen-share-screen-list-trigger")
550 .child(
551 h_flex()
552 .mx_neg_0p5()
553 .h_full()
554 .justify_center()
555 .child(Icon::new(IconName::ChevronDown).size(IconSize::XSmall)),
556 )
557 .toggle_state(self.screen_share_popover_handle.is_deployed()),
558 )
559 .menu(|window, cx| {
560 let screens = cx.screen_capture_sources();
561 Some(ContextMenu::build(window, cx, |context_menu, _, cx| {
562 cx.spawn(async move |this: WeakEntity<ContextMenu>, cx| {
563 let screens = screens.await??;
564 this.update(cx, |this, cx| {
565 let active_screenshare_id = ActiveCall::global(cx)
566 .read(cx)
567 .room()
568 .and_then(|room| room.read(cx).shared_screen_id());
569 for screen in screens {
570 let Ok(meta) = screen.metadata() else {
571 continue;
572 };
573
574 let label = meta
575 .label
576 .clone()
577 .unwrap_or_else(|| SharedString::from("Unknown screen"));
578 let resolution = SharedString::from(format!(
579 "{} × {}",
580 meta.resolution.width.0, meta.resolution.height.0
581 ));
582 this.push_item(ContextMenuItem::CustomEntry {
583 entry_render: Box::new(move |_, _| {
584 h_flex()
585 .gap_2()
586 .child(
587 Icon::new(IconName::Screen)
588 .size(IconSize::XSmall)
589 .map(|this| {
590 if active_screenshare_id == Some(meta.id) {
591 this.color(Color::Accent)
592 } else {
593 this.color(Color::Muted)
594 }
595 }),
596 )
597 .child(Label::new(label.clone()))
598 .child(
599 Label::new(resolution.clone())
600 .color(Color::Muted)
601 .size(LabelSize::Small),
602 )
603 .into_any()
604 }),
605 selectable: true,
606 documentation_aside: None,
607 handler: Rc::new(move |_, window, cx| {
608 toggle_screen_sharing(Ok(Some(screen.clone())), window, cx);
609 }),
610 });
611 }
612 })
613 })
614 .detach_and_log_err(cx);
615 context_menu
616 }))
617 })
618 }
619}
620
621/// Picks the screen to share when clicking on the main screen sharing button.
622fn pick_default_screen(cx: &App) -> Task<anyhow::Result<Option<Rc<dyn ScreenCaptureSource>>>> {
623 let source = cx.screen_capture_sources();
624 cx.spawn(async move |_| {
625 let available_sources = source.await??;
626 Ok(available_sources
627 .iter()
628 .find(|it| {
629 it.as_ref()
630 .metadata()
631 .is_ok_and(|meta| meta.is_main.unwrap_or_default())
632 })
633 .or_else(|| available_sources.first())
634 .cloned())
635 })
636}