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(|cx| async move {
 51            futures::select_biased! {
 52                _ = rx.fuse() => Ok(None),
 53                result = f(cx).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(move |_, mut cx| async move {
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(&mut cx, |room, cx| room.share_project(initial_project, cx))?
194                            .await?,
195                    )
196                } else {
197                    None
198                };
199
200                room.update(&mut 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(move |this, mut cx| async move {
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(&mut 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(&mut 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(move |this, mut cx| async move {
244            let result = invite.await;
245            if result.is_ok() {
246                this.update(&mut 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(&mut 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
308            ._join_debouncer
309            .spawn(cx, move |cx| Room::join(room_id, client, user_store, cx));
310
311        cx.spawn(|this, mut cx| async move {
312            let room = join.await?;
313            this.update(&mut cx, |this, cx| this.set_room(room.clone(), cx))?
314                .await?;
315            this.update(&mut 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 |cx| async move {
356            Room::join_channel(channel_id, client, user_store, cx).await
357        });
358
359        cx.spawn(|this, mut cx| async move {
360            let room = join.await?;
361            this.update(&mut cx, |this, cx| this.set_room(room.clone(), cx))?
362                .await?;
363            this.update(&mut cx, |this, cx| {
364                this.report_call_event("Channel Joined", cx)
365            })?;
366            Ok(room)
367        })
368    }
369
370    pub fn hang_up(&mut self, cx: &mut Context<Self>) -> Task<Result<()>> {
371        cx.notify();
372        self.report_call_event("Call Ended", cx);
373
374        Audio::end_call(cx);
375
376        let channel_id = self.channel_id(cx);
377        if let Some((room, _)) = self.room.take() {
378            cx.emit(Event::RoomLeft { channel_id });
379            room.update(cx, |room, cx| room.leave(cx))
380        } else {
381            Task::ready(Ok(()))
382        }
383    }
384
385    pub fn share_project(
386        &mut self,
387        project: Entity<Project>,
388        cx: &mut Context<Self>,
389    ) -> Task<Result<u64>> {
390        if let Some((room, _)) = self.room.as_ref() {
391            self.report_call_event("Project Shared", cx);
392            room.update(cx, |room, cx| room.share_project(project, cx))
393        } else {
394            Task::ready(Err(anyhow!("no active call")))
395        }
396    }
397
398    pub fn unshare_project(
399        &mut self,
400        project: Entity<Project>,
401        cx: &mut Context<Self>,
402    ) -> Result<()> {
403        if let Some((room, _)) = self.room.as_ref() {
404            self.report_call_event("Project Unshared", cx);
405            room.update(cx, |room, cx| room.unshare_project(project, cx))
406        } else {
407            Err(anyhow!("no active call"))
408        }
409    }
410
411    pub fn location(&self) -> Option<&WeakEntity<Project>> {
412        self.location.as_ref()
413    }
414
415    pub fn set_location(
416        &mut self,
417        project: Option<&Entity<Project>>,
418        cx: &mut Context<Self>,
419    ) -> Task<Result<()>> {
420        if project.is_some() || !*ZED_ALWAYS_ACTIVE {
421            self.location = project.map(|project| project.downgrade());
422            if let Some((room, _)) = self.room.as_ref() {
423                return room.update(cx, |room, cx| room.set_location(project, cx));
424            }
425        }
426        Task::ready(Ok(()))
427    }
428
429    fn set_room(&mut self, room: Option<Entity<Room>>, cx: &mut Context<Self>) -> Task<Result<()>> {
430        if room.as_ref() == self.room.as_ref().map(|room| &room.0) {
431            Task::ready(Ok(()))
432        } else {
433            cx.notify();
434            if let Some(room) = room {
435                if room.read(cx).status().is_offline() {
436                    self.room = None;
437                    Task::ready(Ok(()))
438                } else {
439                    let subscriptions = vec![
440                        cx.observe(&room, |this, room, cx| {
441                            if room.read(cx).status().is_offline() {
442                                this.set_room(None, cx).detach_and_log_err(cx);
443                            }
444
445                            cx.notify();
446                        }),
447                        cx.subscribe(&room, |_, _, event, cx| cx.emit(event.clone())),
448                    ];
449                    self.room = Some((room.clone(), subscriptions));
450                    let location = self
451                        .location
452                        .as_ref()
453                        .and_then(|location| location.upgrade());
454                    let channel_id = room.read(cx).channel_id();
455                    cx.emit(Event::RoomJoined { channel_id });
456                    room.update(cx, |room, cx| room.set_location(location.as_ref(), cx))
457                }
458            } else {
459                self.room = None;
460                Task::ready(Ok(()))
461            }
462        }
463    }
464
465    pub fn room(&self) -> Option<&Entity<Room>> {
466        self.room.as_ref().map(|(room, _)| room)
467    }
468
469    pub fn client(&self) -> Arc<Client> {
470        self.client.clone()
471    }
472
473    pub fn pending_invites(&self) -> &HashSet<u64> {
474        &self.pending_invites
475    }
476
477    pub fn report_call_event(&self, operation: &'static str, cx: &mut App) {
478        if let Some(room) = self.room() {
479            let room = room.read(cx);
480            telemetry::event!(
481                operation,
482                room_id = room.id(),
483                channel_id = room.channel_id()
484            );
485        }
486    }
487}
488
489#[cfg(test)]
490mod test {
491    use gpui::TestAppContext;
492
493    use crate::OneAtATime;
494
495    #[gpui::test]
496    async fn test_one_at_a_time(cx: &mut TestAppContext) {
497        let mut one_at_a_time = OneAtATime { cancel: None };
498
499        assert_eq!(
500            cx.update(|cx| one_at_a_time.spawn(cx, |_| async { Ok(1) }))
501                .await
502                .unwrap(),
503            Some(1)
504        );
505
506        let (a, b) = cx.update(|cx| {
507            (
508                one_at_a_time.spawn(cx, |_| async {
509                    panic!("");
510                }),
511                one_at_a_time.spawn(cx, |_| async { Ok(3) }),
512            )
513        });
514
515        assert_eq!(a.await.unwrap(), None::<u32>);
516        assert_eq!(b.await.unwrap(), Some(3));
517
518        let promise = cx.update(|cx| one_at_a_time.spawn(cx, |_| async { Ok(4) }));
519        drop(one_at_a_time);
520
521        assert_eq!(promise.await.unwrap(), None);
522    }
523}