mod.rs

  1pub mod participant;
  2pub mod room;
  3
  4use crate::call_settings::CallSettings;
  5use anyhow::{anyhow, Result};
  6use audio::Audio;
  7use client::{proto, ChannelId, Client, TypedEnvelope, User, UserStore, ZED_ALWAYS_ACTIVE};
  8use collections::HashSet;
  9use futures::{channel::oneshot, future::Shared, Future, FutureExt};
 10use gpui::{
 11    App, AppContext as _, AsyncApp, Context, Entity, EventEmitter, Global, Subscription, Task,
 12    WeakEntity,
 13};
 14use postage::watch;
 15use project::Project;
 16use room::Event;
 17use settings::Settings;
 18use std::sync::Arc;
 19
 20pub use participant::ParticipantLocation;
 21pub use room::Room;
 22
 23struct GlobalActiveCall(Entity<ActiveCall>);
 24
 25impl Global for GlobalActiveCall {}
 26
 27pub fn init(client: Arc<Client>, user_store: Entity<UserStore>, cx: &mut App) {
 28    CallSettings::register(cx);
 29
 30    let active_call = cx.new(|cx| ActiveCall::new(client, user_store, cx));
 31    cx.set_global(GlobalActiveCall(active_call));
 32}
 33
 34pub struct OneAtATime {
 35    cancel: Option<oneshot::Sender<()>>,
 36}
 37
 38impl OneAtATime {
 39    /// spawn a task in the given context.
 40    /// if another task is spawned before that resolves, or if the OneAtATime itself is dropped, the first task will be cancelled and return Ok(None)
 41    /// otherwise you'll see the result of the task.
 42    fn spawn<F, Fut, R>(&mut self, cx: &mut App, f: F) -> Task<Result<Option<R>>>
 43    where
 44        F: 'static + FnOnce(AsyncApp) -> Fut,
 45        Fut: Future<Output = Result<R>>,
 46        R: 'static,
 47    {
 48        let (tx, rx) = oneshot::channel();
 49        self.cancel.replace(tx);
 50        cx.spawn(async move |cx| {
 51            futures::select_biased! {
 52                _ = rx.fuse() => Ok(None),
 53                result = f(cx.clone()).fuse() => result.map(Some),
 54            }
 55        })
 56    }
 57
 58    fn running(&self) -> bool {
 59        self.cancel
 60            .as_ref()
 61            .is_some_and(|cancel| !cancel.is_canceled())
 62    }
 63}
 64
 65#[derive(Clone)]
 66pub struct IncomingCall {
 67    pub room_id: u64,
 68    pub calling_user: Arc<User>,
 69    pub participants: Vec<Arc<User>>,
 70    pub initial_project: Option<proto::ParticipantProject>,
 71}
 72
 73/// Singleton global maintaining the user's participation in a room across workspaces.
 74pub struct ActiveCall {
 75    room: Option<(Entity<Room>, Vec<Subscription>)>,
 76    pending_room_creation: Option<Shared<Task<Result<Entity<Room>, Arc<anyhow::Error>>>>>,
 77    location: Option<WeakEntity<Project>>,
 78    _join_debouncer: OneAtATime,
 79    pending_invites: HashSet<u64>,
 80    incoming_call: (
 81        watch::Sender<Option<IncomingCall>>,
 82        watch::Receiver<Option<IncomingCall>>,
 83    ),
 84    client: Arc<Client>,
 85    user_store: Entity<UserStore>,
 86    _subscriptions: Vec<client::Subscription>,
 87}
 88
 89impl EventEmitter<Event> for ActiveCall {}
 90
 91impl ActiveCall {
 92    fn new(client: Arc<Client>, user_store: Entity<UserStore>, cx: &mut Context<Self>) -> Self {
 93        Self {
 94            room: None,
 95            pending_room_creation: None,
 96            location: None,
 97            pending_invites: Default::default(),
 98            incoming_call: watch::channel(),
 99            _join_debouncer: OneAtATime { cancel: None },
100            _subscriptions: vec![
101                client.add_request_handler(cx.weak_entity(), Self::handle_incoming_call),
102                client.add_message_handler(cx.weak_entity(), Self::handle_call_canceled),
103            ],
104            client,
105            user_store,
106        }
107    }
108
109    pub fn channel_id(&self, cx: &App) -> Option<ChannelId> {
110        self.room()?.read(cx).channel_id()
111    }
112
113    async fn handle_incoming_call(
114        this: Entity<Self>,
115        envelope: TypedEnvelope<proto::IncomingCall>,
116        mut cx: AsyncApp,
117    ) -> Result<proto::Ack> {
118        let user_store = this.update(&mut cx, |this, _| this.user_store.clone())?;
119        let call = IncomingCall {
120            room_id: envelope.payload.room_id,
121            participants: user_store
122                .update(&mut cx, |user_store, cx| {
123                    user_store.get_users(envelope.payload.participant_user_ids, cx)
124                })?
125                .await?,
126            calling_user: user_store
127                .update(&mut cx, |user_store, cx| {
128                    user_store.get_user(envelope.payload.calling_user_id, cx)
129                })?
130                .await?,
131            initial_project: envelope.payload.initial_project,
132        };
133        this.update(&mut cx, |this, _| {
134            *this.incoming_call.0.borrow_mut() = Some(call);
135        })?;
136
137        Ok(proto::Ack {})
138    }
139
140    async fn handle_call_canceled(
141        this: Entity<Self>,
142        envelope: TypedEnvelope<proto::CallCanceled>,
143        mut cx: AsyncApp,
144    ) -> Result<()> {
145        this.update(&mut cx, |this, _| {
146            let mut incoming_call = this.incoming_call.0.borrow_mut();
147            if incoming_call
148                .as_ref()
149                .map_or(false, |call| call.room_id == envelope.payload.room_id)
150            {
151                incoming_call.take();
152            }
153        })?;
154        Ok(())
155    }
156
157    pub fn global(cx: &App) -> Entity<Self> {
158        cx.global::<GlobalActiveCall>().0.clone()
159    }
160
161    pub fn try_global(cx: &App) -> Option<Entity<Self>> {
162        cx.try_global::<GlobalActiveCall>()
163            .map(|call| call.0.clone())
164    }
165
166    pub fn invite(
167        &mut self,
168        called_user_id: u64,
169        initial_project: Option<Entity<Project>>,
170        cx: &mut Context<Self>,
171    ) -> Task<Result<()>> {
172        if !self.pending_invites.insert(called_user_id) {
173            return Task::ready(Err(anyhow!("user was already invited")));
174        }
175        cx.notify();
176
177        if self._join_debouncer.running() {
178            return Task::ready(Ok(()));
179        }
180
181        let room = if let Some(room) = self.room().cloned() {
182            Some(Task::ready(Ok(room)).shared())
183        } else {
184            self.pending_room_creation.clone()
185        };
186
187        let invite = if let Some(room) = room {
188            cx.spawn(async move |_, cx| {
189                let room = room.await.map_err(|err| anyhow!("{:?}", err))?;
190
191                let initial_project_id = if let Some(initial_project) = initial_project {
192                    Some(
193                        room.update(cx, |room, cx| room.share_project(initial_project, cx))?
194                            .await?,
195                    )
196                } else {
197                    None
198                };
199
200                room.update(cx, move |room, cx| {
201                    room.call(called_user_id, initial_project_id, cx)
202                })?
203                .await?;
204
205                anyhow::Ok(())
206            })
207        } else {
208            let client = self.client.clone();
209            let user_store = self.user_store.clone();
210            let room = cx
211                .spawn(async move |this, cx| {
212                    let create_room = async {
213                        let room = cx
214                            .update(|cx| {
215                                Room::create(
216                                    called_user_id,
217                                    initial_project,
218                                    client,
219                                    user_store,
220                                    cx,
221                                )
222                            })?
223                            .await?;
224
225                        this.update(cx, |this, cx| this.set_room(Some(room.clone()), cx))?
226                            .await?;
227
228                        anyhow::Ok(room)
229                    };
230
231                    let room = create_room.await;
232                    this.update(cx, |this, _| this.pending_room_creation = None)?;
233                    room.map_err(Arc::new)
234                })
235                .shared();
236            self.pending_room_creation = Some(room.clone());
237            cx.background_spawn(async move {
238                room.await.map_err(|err| anyhow!("{:?}", err))?;
239                anyhow::Ok(())
240            })
241        };
242
243        cx.spawn(async move |this, cx| {
244            let result = invite.await;
245            if result.is_ok() {
246                this.update(cx, |this, cx| {
247                    this.report_call_event("Participant Invited", cx)
248                })?;
249            } else {
250                //TODO: report collaboration error
251                log::error!("invite failed: {:?}", result);
252            }
253
254            this.update(cx, |this, cx| {
255                this.pending_invites.remove(&called_user_id);
256                cx.notify();
257            })?;
258            result
259        })
260    }
261
262    pub fn cancel_invite(
263        &mut self,
264        called_user_id: u64,
265        cx: &mut Context<Self>,
266    ) -> Task<Result<()>> {
267        let room_id = if let Some(room) = self.room() {
268            room.read(cx).id()
269        } else {
270            return Task::ready(Err(anyhow!("no active call")));
271        };
272
273        let client = self.client.clone();
274        cx.background_spawn(async move {
275            client
276                .request(proto::CancelCall {
277                    room_id,
278                    called_user_id,
279                })
280                .await?;
281            anyhow::Ok(())
282        })
283    }
284
285    pub fn incoming(&self) -> watch::Receiver<Option<IncomingCall>> {
286        self.incoming_call.1.clone()
287    }
288
289    pub fn accept_incoming(&mut self, cx: &mut Context<Self>) -> Task<Result<()>> {
290        if self.room.is_some() {
291            return Task::ready(Err(anyhow!("cannot join while on another call")));
292        }
293
294        let call = if let Some(call) = self.incoming_call.0.borrow_mut().take() {
295            call
296        } else {
297            return Task::ready(Err(anyhow!("no incoming call")));
298        };
299
300        if self.pending_room_creation.is_some() {
301            return Task::ready(Ok(()));
302        }
303
304        let room_id = call.room_id;
305        let client = self.client.clone();
306        let user_store = self.user_store.clone();
307        let join = self._join_debouncer.spawn(cx, move |mut cx| async move {
308            Room::join(room_id, client, user_store, &mut cx).await
309        });
310
311        cx.spawn(async move |this, cx| {
312            let room = join.await?;
313            this.update(cx, |this, cx| this.set_room(room.clone(), cx))?
314                .await?;
315            this.update(cx, |this, cx| {
316                this.report_call_event("Incoming Call Accepted", cx)
317            })?;
318            Ok(())
319        })
320    }
321
322    pub fn decline_incoming(&mut self, _: &mut Context<Self>) -> Result<()> {
323        let call = self
324            .incoming_call
325            .0
326            .borrow_mut()
327            .take()
328            .ok_or_else(|| anyhow!("no incoming call"))?;
329        telemetry::event!("Incoming Call Declined", room_id = call.room_id);
330        self.client.send(proto::DeclineCall {
331            room_id: call.room_id,
332        })?;
333        Ok(())
334    }
335
336    pub fn join_channel(
337        &mut self,
338        channel_id: ChannelId,
339        cx: &mut Context<Self>,
340    ) -> Task<Result<Option<Entity<Room>>>> {
341        if let Some(room) = self.room().cloned() {
342            if room.read(cx).channel_id() == Some(channel_id) {
343                return Task::ready(Ok(Some(room)));
344            } else {
345                room.update(cx, |room, cx| room.clear_state(cx));
346            }
347        }
348
349        if self.pending_room_creation.is_some() {
350            return Task::ready(Ok(None));
351        }
352
353        let client = self.client.clone();
354        let user_store = self.user_store.clone();
355        let join = self._join_debouncer.spawn(cx, move |mut cx| async move {
356            Room::join_channel(channel_id, client, user_store, &mut cx).await
357        });
358
359        cx.spawn(async move |this, cx| {
360            let room = join.await?;
361            this.update(cx, |this, cx| this.set_room(room.clone(), cx))?
362                .await?;
363            this.update(cx, |this, cx| this.report_call_event("Channel Joined", cx))?;
364            Ok(room)
365        })
366    }
367
368    pub fn hang_up(&mut self, cx: &mut Context<Self>) -> Task<Result<()>> {
369        cx.notify();
370        self.report_call_event("Call Ended", cx);
371
372        Audio::end_call(cx);
373
374        let channel_id = self.channel_id(cx);
375        if let Some((room, _)) = self.room.take() {
376            cx.emit(Event::RoomLeft { channel_id });
377            room.update(cx, |room, cx| room.leave(cx))
378        } else {
379            Task::ready(Ok(()))
380        }
381    }
382
383    pub fn share_project(
384        &mut self,
385        project: Entity<Project>,
386        cx: &mut Context<Self>,
387    ) -> Task<Result<u64>> {
388        if let Some((room, _)) = self.room.as_ref() {
389            self.report_call_event("Project Shared", cx);
390            room.update(cx, |room, cx| room.share_project(project, cx))
391        } else {
392            Task::ready(Err(anyhow!("no active call")))
393        }
394    }
395
396    pub fn unshare_project(
397        &mut self,
398        project: Entity<Project>,
399        cx: &mut Context<Self>,
400    ) -> Result<()> {
401        if let Some((room, _)) = self.room.as_ref() {
402            self.report_call_event("Project Unshared", cx);
403            room.update(cx, |room, cx| room.unshare_project(project, cx))
404        } else {
405            Err(anyhow!("no active call"))
406        }
407    }
408
409    pub fn location(&self) -> Option<&WeakEntity<Project>> {
410        self.location.as_ref()
411    }
412
413    pub fn set_location(
414        &mut self,
415        project: Option<&Entity<Project>>,
416        cx: &mut Context<Self>,
417    ) -> Task<Result<()>> {
418        if project.is_some() || !*ZED_ALWAYS_ACTIVE {
419            self.location = project.map(|project| project.downgrade());
420            if let Some((room, _)) = self.room.as_ref() {
421                return room.update(cx, |room, cx| room.set_location(project, cx));
422            }
423        }
424        Task::ready(Ok(()))
425    }
426
427    fn set_room(&mut self, room: Option<Entity<Room>>, cx: &mut Context<Self>) -> Task<Result<()>> {
428        if room.as_ref() == self.room.as_ref().map(|room| &room.0) {
429            Task::ready(Ok(()))
430        } else {
431            cx.notify();
432            if let Some(room) = room {
433                if room.read(cx).status().is_offline() {
434                    self.room = None;
435                    Task::ready(Ok(()))
436                } else {
437                    let subscriptions = vec![
438                        cx.observe(&room, |this, room, cx| {
439                            if room.read(cx).status().is_offline() {
440                                this.set_room(None, cx).detach_and_log_err(cx);
441                            }
442
443                            cx.notify();
444                        }),
445                        cx.subscribe(&room, |_, _, event, cx| cx.emit(event.clone())),
446                    ];
447                    self.room = Some((room.clone(), subscriptions));
448                    let location = self
449                        .location
450                        .as_ref()
451                        .and_then(|location| location.upgrade());
452                    let channel_id = room.read(cx).channel_id();
453                    cx.emit(Event::RoomJoined { channel_id });
454                    room.update(cx, |room, cx| room.set_location(location.as_ref(), cx))
455                }
456            } else {
457                self.room = None;
458                Task::ready(Ok(()))
459            }
460        }
461    }
462
463    pub fn room(&self) -> Option<&Entity<Room>> {
464        self.room.as_ref().map(|(room, _)| room)
465    }
466
467    pub fn client(&self) -> Arc<Client> {
468        self.client.clone()
469    }
470
471    pub fn pending_invites(&self) -> &HashSet<u64> {
472        &self.pending_invites
473    }
474
475    pub fn report_call_event(&self, operation: &'static str, cx: &mut App) {
476        if let Some(room) = self.room() {
477            let room = room.read(cx);
478            telemetry::event!(
479                operation,
480                room_id = room.id(),
481                channel_id = room.channel_id()
482            );
483        }
484    }
485}
486
487#[cfg(test)]
488mod test {
489    use gpui::TestAppContext;
490
491    use crate::OneAtATime;
492
493    #[gpui::test]
494    async fn test_one_at_a_time(cx: &mut TestAppContext) {
495        let mut one_at_a_time = OneAtATime { cancel: None };
496
497        assert_eq!(
498            cx.update(|cx| one_at_a_time.spawn(cx, |_| async { Ok(1) }))
499                .await
500                .unwrap(),
501            Some(1)
502        );
503
504        let (a, b) = cx.update(|cx| {
505            (
506                one_at_a_time.spawn(cx, |_| async {
507                    panic!("");
508                }),
509                one_at_a_time.spawn(cx, |_| async { Ok(3) }),
510            )
511        });
512
513        assert_eq!(a.await.unwrap(), None::<u32>);
514        assert_eq!(b.await.unwrap(), Some(3));
515
516        let promise = cx.update(|cx| one_at_a_time.spawn(cx, |_| async { Ok(4) }));
517        drop(one_at_a_time);
518
519        assert_eq!(promise.await.unwrap(), None);
520    }
521}