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    AppContext, AsyncAppContext, Context, EventEmitter, Global, Model, ModelContext, Subscription,
 12    Task, WeakModel,
 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(Model<ActiveCall>);
 24
 25impl Global for GlobalActiveCall {}
 26
 27pub fn init(client: Arc<Client>, user_store: Model<UserStore>, cx: &mut AppContext) {
 28    CallSettings::register(cx);
 29
 30    let active_call = cx.new_model(|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 AppContext, f: F) -> Task<Result<Option<R>>>
 43    where
 44        F: 'static + FnOnce(AsyncAppContext) -> 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<(Model<Room>, Vec<Subscription>)>,
 76    pending_room_creation: Option<Shared<Task<Result<Model<Room>, Arc<anyhow::Error>>>>>,
 77    location: Option<WeakModel<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: Model<UserStore>,
 86    _subscriptions: Vec<client::Subscription>,
 87}
 88
 89impl EventEmitter<Event> for ActiveCall {}
 90
 91impl ActiveCall {
 92    fn new(client: Arc<Client>, user_store: Model<UserStore>, cx: &mut ModelContext<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_model(), Self::handle_incoming_call),
102                client.add_message_handler(cx.weak_model(), Self::handle_call_canceled),
103            ],
104            client,
105            user_store,
106        }
107    }
108
109    pub fn channel_id(&self, cx: &AppContext) -> Option<ChannelId> {
110        self.room()?.read(cx).channel_id()
111    }
112
113    async fn handle_incoming_call(
114        this: Model<Self>,
115        envelope: TypedEnvelope<proto::IncomingCall>,
116        mut cx: AsyncAppContext,
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: Model<Self>,
142        envelope: TypedEnvelope<proto::CallCanceled>,
143        mut cx: AsyncAppContext,
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: &AppContext) -> Model<Self> {
158        cx.global::<GlobalActiveCall>().0.clone()
159    }
160
161    pub fn try_global(cx: &AppContext) -> Option<Model<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<Model<Project>>,
170        cx: &mut ModelContext<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_executor().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| this.report_call_event("invite", cx))?;
247            } else {
248                //TODO: report collaboration error
249                log::error!("invite failed: {:?}", result);
250            }
251
252            this.update(&mut cx, |this, cx| {
253                this.pending_invites.remove(&called_user_id);
254                cx.notify();
255            })?;
256            result
257        })
258    }
259
260    pub fn cancel_invite(
261        &mut self,
262        called_user_id: u64,
263        cx: &mut ModelContext<Self>,
264    ) -> Task<Result<()>> {
265        let room_id = if let Some(room) = self.room() {
266            room.read(cx).id()
267        } else {
268            return Task::ready(Err(anyhow!("no active call")));
269        };
270
271        let client = self.client.clone();
272        cx.background_executor().spawn(async move {
273            client
274                .request(proto::CancelCall {
275                    room_id,
276                    called_user_id,
277                })
278                .await?;
279            anyhow::Ok(())
280        })
281    }
282
283    pub fn incoming(&self) -> watch::Receiver<Option<IncomingCall>> {
284        self.incoming_call.1.clone()
285    }
286
287    pub fn accept_incoming(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
288        if self.room.is_some() {
289            return Task::ready(Err(anyhow!("cannot join while on another call")));
290        }
291
292        let call = if let Some(call) = self.incoming_call.0.borrow_mut().take() {
293            call
294        } else {
295            return Task::ready(Err(anyhow!("no incoming call")));
296        };
297
298        if self.pending_room_creation.is_some() {
299            return Task::ready(Ok(()));
300        }
301
302        let room_id = call.room_id;
303        let client = self.client.clone();
304        let user_store = self.user_store.clone();
305        let join = self
306            ._join_debouncer
307            .spawn(cx, move |cx| Room::join(room_id, client, user_store, cx));
308
309        cx.spawn(|this, mut cx| async move {
310            let room = join.await?;
311            this.update(&mut cx, |this, cx| this.set_room(room.clone(), cx))?
312                .await?;
313            this.update(&mut cx, |this, cx| {
314                this.report_call_event("accept incoming", cx)
315            })?;
316            Ok(())
317        })
318    }
319
320    pub fn decline_incoming(&mut self, _: &mut ModelContext<Self>) -> Result<()> {
321        let call = self
322            .incoming_call
323            .0
324            .borrow_mut()
325            .take()
326            .ok_or_else(|| anyhow!("no incoming call"))?;
327        report_call_event_for_room("decline incoming", call.room_id, None, &self.client);
328        self.client.send(proto::DeclineCall {
329            room_id: call.room_id,
330        })?;
331        Ok(())
332    }
333
334    pub fn join_channel(
335        &mut self,
336        channel_id: ChannelId,
337        cx: &mut ModelContext<Self>,
338    ) -> Task<Result<Option<Model<Room>>>> {
339        if let Some(room) = self.room().cloned() {
340            if room.read(cx).channel_id() == Some(channel_id) {
341                return Task::ready(Ok(Some(room)));
342            } else {
343                room.update(cx, |room, cx| room.clear_state(cx));
344            }
345        }
346
347        if self.pending_room_creation.is_some() {
348            return Task::ready(Ok(None));
349        }
350
351        let client = self.client.clone();
352        let user_store = self.user_store.clone();
353        let join = self._join_debouncer.spawn(cx, move |cx| async move {
354            Room::join_channel(channel_id, client, user_store, cx).await
355        });
356
357        cx.spawn(|this, mut cx| async move {
358            let room = join.await?;
359            this.update(&mut cx, |this, cx| this.set_room(room.clone(), cx))?
360                .await?;
361            this.update(&mut cx, |this, cx| {
362                this.report_call_event("join channel", cx)
363            })?;
364            Ok(room)
365        })
366    }
367
368    pub fn hang_up(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
369        cx.notify();
370        self.report_call_event("hang up", cx);
371
372        Audio::end_call(cx);
373
374        let channel_id = self.channel_id(cx);
375        if let Some((room, _)) = self.room.take() {
376            cx.emit(Event::RoomLeft { channel_id });
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            Task::ready(Ok(()))
434        } else {
435            cx.notify();
436            if let Some(room) = room {
437                if room.read(cx).status().is_offline() {
438                    self.room = None;
439                    Task::ready(Ok(()))
440                } else {
441                    let subscriptions = vec![
442                        cx.observe(&room, |this, room, cx| {
443                            if room.read(cx).status().is_offline() {
444                                this.set_room(None, cx).detach_and_log_err(cx);
445                            }
446
447                            cx.notify();
448                        }),
449                        cx.subscribe(&room, |_, _, event, cx| cx.emit(event.clone())),
450                    ];
451                    self.room = Some((room.clone(), subscriptions));
452                    let location = self
453                        .location
454                        .as_ref()
455                        .and_then(|location| location.upgrade());
456                    let channel_id = room.read(cx).channel_id();
457                    cx.emit(Event::RoomJoined { channel_id });
458                    room.update(cx, |room, cx| room.set_location(location.as_ref(), cx))
459                }
460            } else {
461                self.room = None;
462                Task::ready(Ok(()))
463            }
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                    panic!("");
532                }),
533                one_at_a_time.spawn(cx, |_| async { Ok(3) }),
534            )
535        });
536
537        assert_eq!(a.await.unwrap(), None::<u32>);
538        assert_eq!(b.await.unwrap(), Some(3));
539
540        let promise = cx.update(|cx| one_at_a_time.spawn(cx, |_| async { Ok(4) }));
541        drop(one_at_a_time);
542
543        assert_eq!(promise.await.unwrap(), None);
544    }
545}