collab.rs

  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                        &current_user,
172                        peer_id,
173                        true,
174                        room.is_speaking(),
175                        room.is_muted(),
176                        None,
177                        room,
178                        project_id,
179                        &current_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                            &current_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                                        this.workspace
224                                            .update(cx, |workspace, cx| {
225                                                if is_following {
226                                                    workspace.unfollow(peer_id, window, cx);
227                                                } else {
228                                                    workspace.follow(peer_id, window, cx);
229                                                }
230                                            })
231                                            .ok();
232                                    })
233                                })
234                                .tooltip({
235                                    let login = collaborator.user.github_login.clone();
236                                    Tooltip::text(format!("Follow {login}"))
237                                }),
238                        )
239                    }))
240                },
241            )
242    }
243
244    fn render_collaborator(
245        &self,
246        user: &Arc<User>,
247        peer_id: PeerId,
248        is_present: bool,
249        is_speaking: bool,
250        is_muted: bool,
251        leader_selection_color: Option<Hsla>,
252        room: &Room,
253        project_id: Option<u64>,
254        current_user: &Arc<User>,
255        cx: &App,
256    ) -> Option<Div> {
257        if room.role_for_user(user.id) == Some(proto::ChannelRole::Guest) {
258            return None;
259        }
260
261        const FACEPILE_LIMIT: usize = 3;
262        let followers = project_id.map_or(&[] as &[_], |id| room.followers_for(peer_id, id));
263        let extra_count = followers.len().saturating_sub(FACEPILE_LIMIT);
264
265        Some(
266            div()
267                .m_0p5()
268                .p_0p5()
269                // When the collaborator is not followed, still draw this wrapper div, but leave
270                // it transparent, so that it does not shift the layout when following.
271                .when_some(leader_selection_color, |div, color| {
272                    div.rounded_sm().bg(color)
273                })
274                .child(
275                    Facepile::empty()
276                        .child(
277                            Avatar::new(user.avatar_uri.clone())
278                                .grayscale(!is_present)
279                                .border_color(if is_speaking {
280                                    cx.theme().status().info
281                                } else {
282                                    // We draw the border in a transparent color rather to avoid
283                                    // the layout shift that would come with adding/removing the border.
284                                    gpui::transparent_black()
285                                })
286                                .when(is_muted, |avatar| {
287                                    avatar.indicator(
288                                        AvatarAudioStatusIndicator::new(ui::AudioStatus::Muted)
289                                            .tooltip({
290                                                let github_login = user.github_login.clone();
291                                                Tooltip::text(format!("{} is muted", github_login))
292                                            }),
293                                    )
294                                }),
295                        )
296                        .children(followers.iter().take(FACEPILE_LIMIT).filter_map(
297                            |follower_peer_id| {
298                                let follower = room
299                                    .remote_participants()
300                                    .values()
301                                    .find_map(|p| {
302                                        (p.peer_id == *follower_peer_id).then_some(&p.user)
303                                    })
304                                    .or_else(|| {
305                                        (self.client.peer_id() == Some(*follower_peer_id))
306                                            .then_some(current_user)
307                                    })?
308                                    .clone();
309
310                                Some(div().mt(-px(4.)).child(
311                                    Avatar::new(follower.avatar_uri.clone()).size(rems(0.75)),
312                                ))
313                            },
314                        ))
315                        .children(if extra_count > 0 {
316                            Some(
317                                Label::new(format!("+{extra_count}"))
318                                    .ml_1()
319                                    .into_any_element(),
320                            )
321                        } else {
322                            None
323                        }),
324                ),
325        )
326    }
327
328    pub(crate) fn render_call_controls(
329        &self,
330        window: &mut Window,
331        cx: &mut Context<Self>,
332    ) -> Vec<AnyElement> {
333        let Some(room) = ActiveCall::global(cx).read(cx).room().cloned() else {
334            return Vec::new();
335        };
336
337        let is_connecting_to_project = self
338            .workspace
339            .update(cx, |workspace, cx| workspace.has_active_modal(window, cx))
340            .unwrap_or(false);
341
342        let room = room.read(cx);
343        let project = self.project.read(cx);
344        let is_local = project.is_local() || project.is_via_remote_server();
345        let is_shared = is_local && project.is_shared();
346        let is_muted = room.is_muted();
347        let muted_by_user = room.muted_by_user();
348        let is_deafened = room.is_deafened().unwrap_or(false);
349        let is_screen_sharing = room.is_sharing_screen();
350        let can_use_microphone = room.can_use_microphone();
351        let can_share_projects = room.can_share_projects();
352        let screen_sharing_supported = cx.is_screen_capture_supported();
353
354        let channel_store = ChannelStore::global(cx);
355        let channel = room
356            .channel_id()
357            .and_then(|channel_id| channel_store.read(cx).channel_for_id(channel_id).cloned());
358
359        let mut children = Vec::new();
360
361        children.push(
362            h_flex()
363                .gap_1()
364                .child(
365                    IconButton::new("leave-call", IconName::Exit)
366                        .style(ButtonStyle::Subtle)
367                        .tooltip(Tooltip::text("Leave Call"))
368                        .icon_size(IconSize::Small)
369                        .on_click(move |_, _window, cx| {
370                            ActiveCall::global(cx)
371                                .update(cx, |call, cx| call.hang_up(cx))
372                                .detach_and_log_err(cx);
373                        }),
374                )
375                .child(Divider::vertical().color(DividerColor::Border))
376                .into_any_element(),
377        );
378
379        if is_local && can_share_projects && !is_connecting_to_project {
380            let is_sharing_disabled = channel.is_some_and(|channel| match channel.visibility {
381                proto::ChannelVisibility::Public => project.visible_worktrees(cx).any(|worktree| {
382                    let worktree_id = worktree.read(cx).id();
383
384                    let settings_location = Some(SettingsLocation {
385                        worktree_id,
386                        path: RelPath::empty(),
387                    });
388
389                    WorktreeSettings::get(settings_location, cx).prevent_sharing_in_public_channels
390                }),
391                proto::ChannelVisibility::Members => false,
392            });
393
394            children.push(
395                Button::new(
396                    "toggle_sharing",
397                    if is_shared { "Unshare" } else { "Share" },
398                )
399                .tooltip(Tooltip::text(if is_shared {
400                    "Stop sharing project with call participants"
401                } else {
402                    "Share project with call participants"
403                }))
404                .style(ButtonStyle::Subtle)
405                .selected_style(ButtonStyle::Tinted(TintColor::Accent))
406                .toggle_state(is_shared)
407                .label_size(LabelSize::Small)
408                .when(is_sharing_disabled, |parent| {
409                    parent.disabled(true).tooltip(Tooltip::text(
410                        "This project may not be shared in a public channel.",
411                    ))
412                })
413                .on_click(cx.listener(move |this, _, window, cx| {
414                    if is_shared {
415                        this.unshare_project(window, cx);
416                    } else {
417                        this.share_project(cx);
418                    }
419                }))
420                .into_any_element(),
421            );
422        }
423
424        if can_use_microphone {
425            children.push(
426                IconButton::new(
427                    "mute-microphone",
428                    if is_muted {
429                        IconName::MicMute
430                    } else {
431                        IconName::Mic
432                    },
433                )
434                .tooltip(move |_window, cx| {
435                    if is_muted {
436                        if is_deafened {
437                            Tooltip::with_meta(
438                                "Unmute Microphone",
439                                None,
440                                "Audio will be unmuted",
441                                cx,
442                            )
443                        } else {
444                            Tooltip::simple("Unmute Microphone", cx)
445                        }
446                    } else {
447                        Tooltip::simple("Mute Microphone", cx)
448                    }
449                })
450                .style(ButtonStyle::Subtle)
451                .icon_size(IconSize::Small)
452                .toggle_state(is_muted)
453                .selected_style(ButtonStyle::Tinted(TintColor::Error))
454                .on_click(move |_, _window, cx| {
455                    toggle_mute(&Default::default(), cx);
456                })
457                .into_any_element(),
458            );
459        }
460
461        children.push(
462            IconButton::new(
463                "mute-sound",
464                if is_deafened {
465                    IconName::AudioOff
466                } else {
467                    IconName::AudioOn
468                },
469            )
470            .style(ButtonStyle::Subtle)
471            .selected_style(ButtonStyle::Tinted(TintColor::Error))
472            .icon_size(IconSize::Small)
473            .toggle_state(is_deafened)
474            .tooltip(move |_window, cx| {
475                if is_deafened {
476                    let label = "Unmute Audio";
477
478                    if !muted_by_user {
479                        Tooltip::with_meta(label, None, "Microphone will be unmuted", cx)
480                    } else {
481                        Tooltip::simple(label, cx)
482                    }
483                } else {
484                    let label = "Mute Audio";
485
486                    if !muted_by_user {
487                        Tooltip::with_meta(label, None, "Microphone will be muted", cx)
488                    } else {
489                        Tooltip::simple(label, cx)
490                    }
491                }
492            })
493            .on_click(move |_, _, cx| toggle_deafen(&Default::default(), cx))
494            .into_any_element(),
495        );
496
497        if can_use_microphone && screen_sharing_supported {
498            let trigger = IconButton::new("screen-share", IconName::Screen)
499                .style(ButtonStyle::Subtle)
500                .icon_size(IconSize::Small)
501                .toggle_state(is_screen_sharing)
502                .selected_style(ButtonStyle::Tinted(TintColor::Accent))
503                .tooltip(Tooltip::text(if is_screen_sharing {
504                    "Stop Sharing Screen"
505                } else {
506                    "Share Screen"
507                }))
508                .on_click(move |_, window, cx| {
509                    let should_share = ActiveCall::global(cx)
510                        .read(cx)
511                        .room()
512                        .is_some_and(|room| !room.read(cx).is_sharing_screen());
513
514                    window
515                        .spawn(cx, async move |cx| {
516                            let screen = if should_share {
517                                cx.update(|_, cx| pick_default_screen(cx))?.await
518                            } else {
519                                Ok(None)
520                            };
521                            cx.update(|window, cx| toggle_screen_sharing(screen, window, cx))?;
522
523                            Result::<_, anyhow::Error>::Ok(())
524                        })
525                        .detach();
526                });
527
528            children.push(
529                SplitButton::new(
530                    trigger.render(window, cx),
531                    self.render_screen_list().into_any_element(),
532                )
533                .style(SplitButtonStyle::Transparent)
534                .into_any_element(),
535            );
536        }
537
538        children.push(div().pr_2().into_any_element());
539
540        children
541    }
542
543    fn render_screen_list(&self) -> impl IntoElement {
544        PopoverMenu::new("screen-share-screen-list")
545            .with_handle(self.screen_share_popover_handle.clone())
546            .trigger(
547                ui::ButtonLike::new_rounded_right("screen-share-screen-list-trigger")
548                    .child(
549                        h_flex()
550                            .mx_neg_0p5()
551                            .h_full()
552                            .justify_center()
553                            .child(Icon::new(IconName::ChevronDown).size(IconSize::XSmall)),
554                    )
555                    .toggle_state(self.screen_share_popover_handle.is_deployed()),
556            )
557            .menu(|window, cx| {
558                let screens = cx.screen_capture_sources();
559                Some(ContextMenu::build(window, cx, |context_menu, _, cx| {
560                    cx.spawn(async move |this: WeakEntity<ContextMenu>, cx| {
561                        let screens = screens.await??;
562                        this.update(cx, |this, cx| {
563                            let active_screenshare_id = ActiveCall::global(cx)
564                                .read(cx)
565                                .room()
566                                .and_then(|room| room.read(cx).shared_screen_id());
567                            for screen in screens {
568                                let Ok(meta) = screen.metadata() else {
569                                    continue;
570                                };
571
572                                let label = meta
573                                    .label
574                                    .clone()
575                                    .unwrap_or_else(|| SharedString::from("Unknown screen"));
576                                let resolution = SharedString::from(format!(
577                                    "{} × {}",
578                                    meta.resolution.width.0, meta.resolution.height.0
579                                ));
580                                this.push_item(ContextMenuItem::CustomEntry {
581                                    entry_render: Box::new(move |_, _| {
582                                        h_flex()
583                                            .gap_2()
584                                            .child(
585                                                Icon::new(IconName::Screen)
586                                                    .size(IconSize::XSmall)
587                                                    .map(|this| {
588                                                        if active_screenshare_id == Some(meta.id) {
589                                                            this.color(Color::Accent)
590                                                        } else {
591                                                            this.color(Color::Muted)
592                                                        }
593                                                    }),
594                                            )
595                                            .child(Label::new(label.clone()))
596                                            .child(
597                                                Label::new(resolution.clone())
598                                                    .color(Color::Muted)
599                                                    .size(LabelSize::Small),
600                                            )
601                                            .into_any()
602                                    }),
603                                    selectable: true,
604                                    documentation_aside: None,
605                                    handler: Rc::new(move |_, window, cx| {
606                                        toggle_screen_sharing(Ok(Some(screen.clone())), window, cx);
607                                    }),
608                                });
609                            }
610                        })
611                    })
612                    .detach_and_log_err(cx);
613                    context_menu
614                }))
615            })
616    }
617}
618
619/// Picks the screen to share when clicking on the main screen sharing button.
620fn pick_default_screen(cx: &App) -> Task<anyhow::Result<Option<Rc<dyn ScreenCaptureSource>>>> {
621    let source = cx.screen_capture_sources();
622    cx.spawn(async move |_| {
623        let available_sources = source.await??;
624        Ok(available_sources
625            .iter()
626            .find(|it| {
627                it.as_ref()
628                    .metadata()
629                    .is_ok_and(|meta| meta.is_main.unwrap_or_default())
630            })
631            .or_else(|| available_sources.first())
632            .cloned())
633    })
634}