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