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