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