collab.rs

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