call.rs

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