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        if let Some((room, _)) = self.room.take() {
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: Model<Project>,
386        cx: &mut ModelContext<Self>,
387    ) -> Task<Result<u64>> {
388        if let Some((room, _)) = self.room.as_ref() {
389            self.report_call_event("share project", 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: Model<Project>,
399        cx: &mut ModelContext<Self>,
400    ) -> Result<()> {
401        if let Some((room, _)) = self.room.as_ref() {
402            self.report_call_event("unshare project", 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<&WeakModel<Project>> {
410        self.location.as_ref()
411    }
412
413    pub fn set_location(
414        &mut self,
415        project: Option<&Model<Project>>,
416        cx: &mut ModelContext<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(
428        &mut self,
429        room: Option<Model<Room>>,
430        cx: &mut ModelContext<Self>,
431    ) -> Task<Result<()>> {
432        if room.as_ref() != self.room.as_ref().map(|room| &room.0) {
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        } else {
463            Task::ready(Ok(()))
464        }
465    }
466
467    pub fn room(&self) -> Option<&Model<Room>> {
468        self.room.as_ref().map(|(room, _)| room)
469    }
470
471    pub fn client(&self) -> Arc<Client> {
472        self.client.clone()
473    }
474
475    pub fn pending_invites(&self) -> &HashSet<u64> {
476        &self.pending_invites
477    }
478
479    pub fn report_call_event(&self, operation: &'static str, cx: &mut AppContext) {
480        if let Some(room) = self.room() {
481            let room = room.read(cx);
482            report_call_event_for_room(operation, room.id(), room.channel_id(), &self.client);
483        }
484    }
485}
486
487pub fn report_call_event_for_room(
488    operation: &'static str,
489    room_id: u64,
490    channel_id: Option<ChannelId>,
491    client: &Arc<Client>,
492) {
493    let telemetry = client.telemetry();
494
495    telemetry.report_call_event(operation, Some(room_id), channel_id)
496}
497
498pub fn report_call_event_for_channel(
499    operation: &'static str,
500    channel_id: ChannelId,
501    client: &Arc<Client>,
502    cx: &AppContext,
503) {
504    let room = ActiveCall::global(cx).read(cx).room();
505
506    let telemetry = client.telemetry();
507
508    telemetry.report_call_event(operation, room.map(|r| r.read(cx).id()), Some(channel_id))
509}
510
511#[cfg(test)]
512mod test {
513    use gpui::TestAppContext;
514
515    use crate::OneAtATime;
516
517    #[gpui::test]
518    async fn test_one_at_a_time(cx: &mut TestAppContext) {
519        let mut one_at_a_time = OneAtATime { cancel: None };
520
521        assert_eq!(
522            cx.update(|cx| one_at_a_time.spawn(cx, |_| async { Ok(1) }))
523                .await
524                .unwrap(),
525            Some(1)
526        );
527
528        let (a, b) = cx.update(|cx| {
529            (
530                one_at_a_time.spawn(cx, |_| async {
531                    assert!(false);
532                    Ok(2)
533                }),
534                one_at_a_time.spawn(cx, |_| async { Ok(3) }),
535            )
536        });
537
538        assert_eq!(a.await.unwrap(), None);
539        assert_eq!(b.await.unwrap(), Some(3));
540
541        let promise = cx.update(|cx| one_at_a_time.spawn(cx, |_| async { Ok(4) }));
542        drop(one_at_a_time);
543
544        assert_eq!(promise.await.unwrap(), None);
545    }
546}