BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / call / actions.rs

actions.rs

actions.rs 66.0 KiB Download Raw
1use std::time::{Duration, Instant};
2
3use calling::meeting::LiveMeeting;
4use calling::{
5 AcceptMode, CallCommand, CallHandle, CallSpec, CallUpdate, Callee, DeviceChoice, EngineEvent, MuteCommand, Reaction, RingSignal, ShareSource, VideoKey,
6};
7use gpui_kit::*;
8
9use super::background::{BACKGROUND_META_KEY, BackgroundPick, SHOWN_IMAGES, is_image_file, save_custom_backgrounds};
10use super::demo::{DemoCall, DemoScene, demo_caller, demo_guests, demo_ring, demo_video_ring, start_demo_call, start_demo_scene_call};
11use super::features::room_closed_move;
12use super::media::CallMedia;
13use super::model::{ActiveCall, CallKind, CallModel, ended_notice};
14use super::ring::{MissedCall, RingOutcome};
15use super::target::{is_organizer, plan_for_chat};
16use crate::app_state::{AppEvent, AppState, Selection, chat_title};
17use crate::notify::selection_for;
18
19const TIMER_REFRESH: Duration = Duration::from_millis(500);
20const SHARE_SOURCES_EVERY_TICKS: u32 = 10;
21pub(super) const NOT_CONNECTED_NOTICE: &str = "Not connected to Teams yet";
22const READ_ONLY_NOTICE: &str = "Calls are off in read-only mode";
23const NOT_CALLABLE_NOTICE: &str = "This chat cannot be called";
24pub(super) const MEETING_UNAVAILABLE_NOTICE: &str = "This meeting cannot be joined";
25const ANSWER_FAILED_NOTICE: &str = "Could not answer the call";
26const MEETING_KIND: &str = "meeting";
27const DEMO_LOBBY_MEETING: &str = "demo-chat-meeting-retro";
28const DEMO_CROWD: usize = 11;
29const DEMO_SMALL_MEETING: usize = 4;
30const DEMO_LIVE_MINUTES: i64 = 60;
31const ORGID_PREFIX: &str = "8:orgid:";
32pub const SHARE_SOUND_META_KEY: &str = "call_share_sound";
33const CAMERA_META_KEY: &str = "call_camera";
34const DEFAULT_CAMERA_META: &str = "default";
35
36pub fn load_share_sound(store: &store::Store) -> bool {
37 store.meta(SHARE_SOUND_META_KEY).ok().flatten().as_deref() == Some("1")
38}
39
40pub fn load_camera(store: &store::Store) -> DeviceChoice {
41 match store.meta(CAMERA_META_KEY).ok().flatten() {
42 Some(key) if !key.is_empty() && key != DEFAULT_CAMERA_META => DeviceChoice::Device(key),
43 _ => DeviceChoice::SystemDefault,
44 }
45}
46
47fn camera_meta(choice: &DeviceChoice) -> &str {
48 match choice {
49 DeviceChoice::SystemDefault => DEFAULT_CAMERA_META,
50 DeviceChoice::Device(key) => key,
51 }
52}
53
54fn now_unix() -> i64 {
55 chrono::Utc::now().timestamp()
56}
57
58impl AppState {
59 pub fn start_test_call(&mut self, cx: &mut Context<Self>) {
60 if self.call.is_some() {
61 self.show_call(true, cx);
62 return;
63 }
64 let Some(handle) = self.place_call(CallSpec::Echo, DemoCall::Test, cx) else {
65 return;
66 };
67 self.begin_call(handle, CallModel::test(), None, cx);
68 }
69
70 pub fn start_chat_call(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
71 if self.call.is_some() {
72 self.show_call(true, cx);
73 return;
74 }
75 let plan = self
76 .sidebar
77 .chats
78 .iter()
79 .find(|chat| chat.id == conversation_id)
80 .and_then(|chat| plan_for_chat(chat, self.directory.me.as_ref()));
81 let Some(plan) = plan else {
82 self.raise_notice(NOT_CALLABLE_NOTICE.to_owned(), None, cx);
83 return;
84 };
85 let spec = CallSpec::People {
86 callees: plan
87 .callees
88 .iter()
89 .map(|(mri, name)| Callee {
90 mri: mri.clone(),
91 display_name: name.clone(),
92 })
93 .collect(),
94 thread_id: conversation_id.to_owned(),
95 };
96 let Some(handle) = self.place_call(spec, DemoCall::People(plan.callees.clone()), cx) else {
97 return;
98 };
99 let user_ids = plan
100 .callees
101 .iter()
102 .filter_map(|(mri, _)| mri.strip_prefix(ORGID_PREFIX).map(str::to_owned))
103 .collect();
104 self.request_avatars(user_ids, cx);
105 let model = CallModel::people(&plan.title, &plan.callees);
106 self.begin_call(handle, model, Some(conversation_id.to_owned()), cx);
107 }
108
109 pub fn join_meeting_call(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
110 if self.call.is_some() {
111 self.show_call(true, cx);
112 return;
113 }
114 let Some(meeting) = self.running_meeting(conversation_id).cloned() else {
115 self.raise_notice(MEETING_UNAVAILABLE_NOTICE.to_owned(), None, cx);
116 return;
117 };
118 let Some(target) = meeting.target() else {
119 self.raise_notice(MEETING_UNAVAILABLE_NOTICE.to_owned(), None, cx);
120 return;
121 };
122 let guests = if conversation_id == DEMO_LOBBY_MEETING { DEMO_SMALL_MEETING } else { DEMO_CROWD };
123 let demo = DemoCall::Meeting {
124 guests: demo_guests(guests),
125 lobby: conversation_id == DEMO_LOBBY_MEETING,
126 organizer: conversation_id != DEMO_LOBBY_MEETING,
127 };
128 let Some(handle) = self.place_call(CallSpec::Meeting(target.clone()), demo, cx) else {
129 return;
130 };
131 let title = selection_for(&self.sidebar, conversation_id)
132 .map(|selection| crate::app_state::selection_title(&self.sidebar, &selection))
133 .unwrap_or_else(|| "Meeting".to_owned());
134 let model = CallModel::meeting(&title, is_organizer(&meeting, self.directory.me.as_ref()));
135 self.begin_call(handle, model, Some(conversation_id.to_owned()), cx);
136 if let Some(call) = self.call.as_mut() {
137 call.meeting_target = Some(target);
138 }
139 }
140
141 pub(super) fn place_call(&mut self, spec: CallSpec, demo: DemoCall, cx: &mut Context<Self>) -> Option<CallHandle> {
142 if self.mode.demo {
143 return Some(start_demo_call(demo));
144 }
145 if self.mode.read_only {
146 self.raise_notice(READ_ONLY_NOTICE.to_owned(), None, cx);
147 return None;
148 }
149 match self.call_launcher.clone() {
150 Some(launcher) => Some(launcher.start_call(spec)),
151 None => {
152 self.raise_notice(NOT_CONNECTED_NOTICE.to_owned(), None, cx);
153 None
154 }
155 }
156 }
157
158 pub(super) fn begin_call(
159 &mut self,
160 handle: CallHandle,
161 model: CallModel,
162 conversation_id: Option<String>,
163 cx: &mut Context<Self>,
164 ) {
165 self.call_count += 1;
166 let call_id = self.call_count;
167 let CallHandle { commands, updates, video } = handle;
168 self.call = Some(ActiveCall::new(call_id, model, commands, conversation_id, video));
169 if self.call_share_sound {
170 self.send_call_command(CallCommand::SetShareSound(true));
171 }
172 if let Some(call) = self.call.as_mut() {
173 call.model.background = self.call_background.clone();
174 call.model.camera = self.call_camera.clone();
175 }
176 if self.call_camera != DeviceChoice::SystemDefault {
177 self.send_call_command(CallCommand::SelectCamera(self.call_camera.clone()));
178 }
179 if self.call_background != BackgroundPick::None {
180 self.send_background_command(cx);
181 }
182 self.refresh_call_backgrounds(cx);
183 self.new_chat = false;
184 self.follow_call(call_id, updates, cx);
185 cx.emit(AppEvent::Call);
186 cx.notify();
187 }
188
189 fn follow_call(
190 &mut self,
191 call_id: u64,
192 mut updates: tokio::sync::mpsc::UnboundedReceiver<CallUpdate>,
193 cx: &mut Context<Self>,
194 ) {
195 cx.spawn(async move |this, cx| {
196 while let Some(update) = updates.recv().await {
197 let alive = this.update(cx, |state, cx| state.apply_call_update(call_id, update, cx));
198 if alive.is_err() {
199 return;
200 }
201 }
202 })
203 .detach();
204 cx.spawn(async move |this, cx| {
205 let mut ticks = 0u32;
206 loop {
207 cx.background_executor().timer(TIMER_REFRESH).await;
208 ticks += 1;
209 let running = this.update(cx, |state, cx| {
210 let running = state.call.as_ref().is_some_and(|call| call.id == call_id);
211 if running {
212 if ticks.is_multiple_of(SHARE_SOURCES_EVERY_TICKS) {
213 state.refresh_share_sources();
214 }
215 CallMedia::changed(&state.call_media, cx);
216 }
217 running
218 });
219 if !running.unwrap_or(false) {
220 return;
221 }
222 }
223 })
224 .detach();
225 }
226
227 pub(super) fn apply_call_update(&mut self, call_id: u64, update: CallUpdate, cx: &mut Context<Self>) {
228 let media = self.call_media.clone();
229 let Some(call) = self.call.as_mut().filter(|call| call.id == call_id) else {
230 return;
231 };
232 match update {
233 CallUpdate::VideoReady => {
234 call.pictures.apply(&call.video, cx);
235 CallMedia::changed(&media, cx);
236 return;
237 }
238 CallUpdate::Stats { .. } => return,
239 CallUpdate::Levels { local, remote } => {
240 let before = (call.model.local_speaking, call.model.remote_speaking);
241 call.model.apply(CallUpdate::Levels { local, remote });
242 if before != (call.model.local_speaking, call.model.remote_speaking) {
243 CallMedia::changed(&media, cx);
244 }
245 return;
246 }
247 CallUpdate::Notice(text) => {
248 self.raise_notice(text, None, cx);
249 return;
250 }
251 CallUpdate::WhiteboardUrl(url) => {
252 cx.open_url(&url);
253 return;
254 }
255 CallUpdate::BreakoutMove(moved) => {
256 self.begin_breakout_move(moved, cx);
257 return;
258 }
259 _ => {}
260 }
261 call.model.apply(update);
262 if call.model.screen_sharer.is_none() {
263 call.stage_fullscreen = false;
264 call.pictures.forget(&VideoKey::Screen, cx);
265 }
266 if !call.model.camera_on {
267 call.pictures.forget(&VideoKey::LocalCamera, cx);
268 }
269 let Some(reason) = call.model.ended_reason().cloned() else {
270 cx.emit(AppEvent::Call);
271 cx.notify();
272 return;
273 };
274 let elapsed = call.model.elapsed(Instant::now());
275 let notice = ended_notice(&reason, elapsed, &call.model.peer_name);
276 let next_move = call.pending_move.take().or_else(|| room_closed_move(call, &reason));
277 let consult = call.consult.take();
278 call.pictures.clear(cx);
279 self.call = None;
280 if let Some(consult) = consult {
281 let _ = consult.commands.send(CallCommand::Hangup);
282 }
283 match next_move {
284 Some(next_move) => self.join_moved_call(next_move, cx),
285 None => self.raise_notice(notice, None, cx),
286 }
287 self.refresh_call_history_after_call(cx);
288 cx.emit(AppEvent::Call);
289 cx.notify();
290 }
291
292 pub(super) fn send_call_command(&self, command: CallCommand) {
293 if let Some(call) = &self.call {
294 let _ = call.commands.send(command);
295 }
296 }
297
298 pub fn toggle_call_mute(&mut self, _cx: &mut Context<Self>) {
299 let can_toggle = self.call.as_ref().is_some_and(|call| call.model.can_unmute());
300 if can_toggle {
301 self.send_call_command(CallCommand::Mute(MuteCommand::Toggle));
302 }
303 }
304
305 pub fn toggle_call_camera(&mut self, _cx: &mut Context<Self>) {
306 let Some(call) = self.call.as_ref().filter(|call| call.model.can_use_camera()) else {
307 return;
308 };
309 let on = !call.model.camera_on;
310 self.send_call_command(CallCommand::SetCamera(on));
311 }
312
313 pub fn select_call_camera(&mut self, choice: DeviceChoice, _cx: &mut Context<Self>) {
314 let _ = self.store.set_meta(CAMERA_META_KEY, camera_meta(&choice));
315 self.call_camera = choice.clone();
316 if let Some(launcher) = &self.call_launcher {
317 launcher.set_default_camera(choice.clone());
318 }
319 if let Some(call) = self.call.as_mut() {
320 call.model.camera = choice.clone();
321 }
322 self.send_call_command(CallCommand::SelectCamera(choice));
323 }
324
325 pub fn start_call_share(&mut self, source: ShareSource, _cx: &mut Context<Self>) {
326 self.send_call_command(CallCommand::StartShare(source));
327 }
328
329 pub fn toggle_call_share(&mut self, cx: &mut Context<Self>) {
330 let Some(call) = self.call.as_ref() else {
331 return;
332 };
333 if call.model.local_share.is_some() {
334 self.stop_call_share(cx);
335 return;
336 }
337 if !call.model.can_share() {
338 return;
339 }
340 if let Some(source) = call.model.screens().first().map(|source| (*source).clone()) {
341 self.start_call_share(source, cx);
342 }
343 }
344
345 pub fn stop_call_share(&mut self, _cx: &mut Context<Self>) {
346 self.send_call_command(CallCommand::StopShare);
347 }
348
349 pub fn refresh_share_sources(&self) {
350 let idle = self.call.as_ref().is_some_and(|call| call.model.local_share.is_none());
351 if idle {
352 self.send_call_command(CallCommand::RefreshShareSources);
353 }
354 }
355
356 pub fn leave_call(&mut self, _cx: &mut Context<Self>) {
357 self.send_call_command(CallCommand::Hangup);
358 }
359
360 pub fn end_meeting_for_all(&mut self, _cx: &mut Context<Self>) {
361 let allowed = self.call.as_ref().is_some_and(|call| call.model.can_end_meeting);
362 if allowed {
363 self.send_call_command(CallCommand::EndMeeting);
364 }
365 }
366
367 pub fn select_call_input(&mut self, choice: DeviceChoice, _cx: &mut Context<Self>) {
368 self.send_call_command(CallCommand::SelectInput(choice));
369 }
370
371 pub fn select_call_output(&mut self, choice: DeviceChoice, _cx: &mut Context<Self>) {
372 self.send_call_command(CallCommand::SelectOutput(choice));
373 }
374
375 pub fn show_call(&mut self, viewing: bool, cx: &mut Context<Self>) {
376 let Some(call) = self.call.as_mut().filter(|call| call.viewing != viewing) else {
377 return;
378 };
379 call.viewing = viewing;
380 if viewing {
381 self.new_chat = false;
382 }
383 cx.emit(AppEvent::Call);
384 cx.notify();
385 }
386
387 pub fn toggle_call_chat(&mut self, cx: &mut Context<Self>) {
388 let Some(call) = self.call.as_mut().filter(|call| call.chat_thread().is_some()) else {
389 return;
390 };
391 call.chat_open = !call.chat_open;
392 cx.emit(AppEvent::Call);
393 cx.notify();
394 }
395
396 pub fn call_chat_thread(&self) -> Option<String> {
397 let call = self.call.as_ref().filter(|call| call.chat_open)?;
398 call.chat_thread().map(str::to_owned)
399 }
400
401 pub fn call_chat_unread(&self) -> u32 {
402 let Some(thread) = self.call.as_ref().filter(|call| !call.chat_open).and_then(|call| call.chat_thread()) else {
403 return 0;
404 };
405 let counted = self.directory.unread_counts.get(thread).copied();
406 counted.unwrap_or_else(|| u32::from(self.sidebar.chats.iter().any(|chat| chat.id == thread && chat.unread)))
407 }
408
409 pub fn toggle_call_hand(&mut self, cx: &mut Context<Self>) {
410 let Some(call) = self.call.as_mut().filter(|call| call.model.is_active() && call.model.has_reaction_controls()) else {
411 return;
412 };
413 let raised = call.model.own_hand.is_none();
414 call.model.own_hand = raised.then_some(u64::MAX);
415 self.send_call_command(CallCommand::SetHand(raised));
416 if raised {
417 self.raise_notice("Your hand is raised".to_owned(), None, cx);
418 }
419 cx.emit(AppEvent::Call);
420 cx.notify();
421 }
422
423 pub fn lower_call_hand(&mut self, mri: String, _cx: &mut Context<Self>) {
424 let allowed = self.call.as_ref().is_some_and(|call| call.model.can_lower_hands());
425 if allowed {
426 self.send_call_command(CallCommand::LowerHand { mri });
427 }
428 }
429
430 pub fn lower_all_call_hands(&mut self, _cx: &mut Context<Self>) {
431 let allowed = self.call.as_ref().is_some_and(|call| call.model.can_lower_hands() && call.model.any_hand_raised());
432 if allowed {
433 self.send_call_command(CallCommand::LowerAllHands);
434 }
435 }
436
437 pub fn send_call_reaction(&mut self, reaction: Reaction, cx: &mut Context<Self>) {
438 let Some(call) = self.call.as_mut().filter(|call| call.model.is_active() && call.model.has_reaction_controls()) else {
439 return;
440 };
441 if let Some(own_mri) = call.model.own_mri.clone() {
442 call.model.note_reaction(own_mri, reaction, Instant::now());
443 }
444 self.send_call_command(CallCommand::SendReaction(reaction));
445 cx.emit(AppEvent::Call);
446 cx.notify();
447 }
448
449 pub fn set_call_share_sound(&mut self, on: bool, cx: &mut Context<Self>) {
450 self.call_share_sound = on;
451 let _ = self.store.set_meta(SHARE_SOUND_META_KEY, if on { "1" } else { "0" });
452 self.send_call_command(CallCommand::SetShareSound(on));
453 cx.notify();
454 }
455
456 pub fn admit_call_guest(&mut self, mri: String, _cx: &mut Context<Self>) {
457 if self.call.as_ref().is_some_and(|call| call.model.can_admit()) {
458 self.send_call_command(CallCommand::Admit { mri });
459 }
460 }
461
462 pub fn admit_all_call_guests(&mut self, _cx: &mut Context<Self>) {
463 if self.call.as_ref().is_some_and(|call| call.model.can_admit() && !call.model.lobby_guests().is_empty()) {
464 self.send_call_command(CallCommand::AdmitAll);
465 }
466 }
467
468 pub fn deny_call_guest(&mut self, mri: String, _cx: &mut Context<Self>) {
469 if self.call.as_ref().is_some_and(|call| call.model.can_admit()) {
470 self.send_call_command(CallCommand::Deny { mri });
471 }
472 }
473
474 pub fn mute_call_participant(&mut self, mri: String, _cx: &mut Context<Self>) {
475 if self.call.as_ref().is_some_and(|call| call.model.can_manage()) {
476 self.send_call_command(CallCommand::MuteParticipant { mri });
477 }
478 }
479
480 pub fn mute_all_call(&mut self, _cx: &mut Context<Self>) {
481 if self.call.as_ref().is_some_and(|call| call.model.can_manage()) {
482 self.send_call_command(CallCommand::MuteAll);
483 }
484 }
485
486 pub fn remove_call_participant(&mut self, mri: String, _cx: &mut Context<Self>) {
487 if self.call.as_ref().is_some_and(|call| call.model.can_manage()) {
488 self.send_call_command(CallCommand::RemoveParticipant { mri });
489 }
490 }
491
492 pub fn toggle_call_spotlight(&mut self, mri: String, _cx: &mut Context<Self>) {
493 let Some(call) = self.call.as_ref().filter(|call| call.model.can_manage() && call.model.is_active()) else {
494 return;
495 };
496 let command = if call.model.is_spotlighted(&mri) { CallCommand::StopSpotlight { mri } } else { CallCommand::Spotlight { mri } };
497 self.send_call_command(command);
498 }
499
500 pub fn toggle_call_pin(&mut self, mri: &str, cx: &mut Context<Self>) {
501 if let Some(call) = self.call.as_mut() {
502 call.model.toggle_pin(mri);
503 cx.notify();
504 }
505 }
506
507 pub fn toggle_call_captions(&mut self, _cx: &mut Context<Self>) {
508 let Some(call) = self.call.as_ref().filter(|call| call.model.is_active() && call.model.kind == CallKind::Meeting) else {
509 return;
510 };
511 let on = !call.model.captions_on();
512 self.send_call_command(CallCommand::SetCaptions(on));
513 }
514
515 pub fn set_call_background(&mut self, pick: BackgroundPick, cx: &mut Context<Self>) {
516 let _ = self.store.set_meta(BACKGROUND_META_KEY, &pick.to_meta());
517 self.call_background = pick.clone();
518 if let Some(call) = self.call.as_mut() {
519 call.model.background = pick;
520 }
521 self.send_background_command(cx);
522 cx.notify();
523 }
524
525 pub(super) fn send_background_command(&mut self, cx: &mut Context<Self>) {
526 let pick = self.call_background.clone();
527 if let Some(choice) = self.call_backgrounds.choice_for(&pick) {
528 self.send_call_command(CallCommand::SetBackground(choice));
529 return;
530 }
531 let BackgroundPick::Default(id) = pick else { return };
532 let Some(image) = self.call_backgrounds.find(&id).cloned() else { return };
533 let Some(launcher) = self.call_launcher.clone() else { return };
534 let cache = self.call_backgrounds.cache.clone();
535 let receiver = crate::runtime::spawn(async move { launcher.download_background(&cache, &image).await });
536 cx.spawn(async move |this, cx| {
537 let path = receiver.await.ok().flatten();
538 this.update(cx, |state, cx| match path {
539 Some(path) if state.call_background == BackgroundPick::Default(id) => {
540 state.send_call_command(CallCommand::SetBackground(calling::BackgroundChoice::Image(path)));
541 }
542 Some(_) => {}
543 None => state.raise_notice("That background could not be downloaded".to_owned(), None, cx),
544 })
545 .ok();
546 })
547 .detach();
548 }
549
550 pub fn refresh_call_backgrounds(&mut self, cx: &mut Context<Self>) {
551 if self.mode.demo || !self.call_backgrounds.needs_refresh() {
552 return;
553 }
554 let Some(launcher) = self.call_launcher.clone() else { return };
555 self.call_backgrounds.refreshing = true;
556 let cache = self.call_backgrounds.cache.clone();
557 let wanted = SHOWN_IMAGES;
558 let receiver = crate::runtime::spawn(async move { launcher.refresh_backgrounds(&cache, wanted).await });
559 cx.spawn(async move |this, cx| {
560 let catalog = receiver.await.ok().flatten();
561 this.update(cx, |state, cx| {
562 state.call_backgrounds.refreshing = false;
563 if let Some(catalog) = catalog {
564 state.call_backgrounds.images = catalog;
565 }
566 cx.notify();
567 })
568 .ok();
569 })
570 .detach();
571 }
572
573 pub fn add_call_background(&mut self, cx: &mut Context<Self>) {
574 let receiver = cx.prompt_for_paths(PathPromptOptions { files: true, directories: false, multiple: false, prompt: None });
575 cx.spawn(async move |this, cx| {
576 let Some(path) = receiver.await.ok().and_then(Result::ok).flatten().and_then(|paths| paths.into_iter().next()) else {
577 return;
578 };
579 this.update(cx, |state, cx| {
580 if !is_image_file(&path) {
581 state.raise_notice("Pick a JPG or PNG picture".to_owned(), None, cx);
582 return;
583 }
584 state.call_backgrounds.add_custom(path.clone());
585 save_custom_backgrounds(&state.store, &state.call_backgrounds.customs);
586 state.set_call_background(BackgroundPick::Custom(path), cx);
587 })
588 .ok();
589 })
590 .detach();
591 }
592
593 pub fn toggle_stage_fullscreen(&mut self, cx: &mut Context<Self>) {
594 let Some(call) = self.call.as_mut().filter(|call| call.model.screen_sharer.is_some()) else {
595 return;
596 };
597 call.stage_fullscreen = !call.stage_fullscreen;
598 cx.emit(AppEvent::Call);
599 cx.notify();
600 }
601
602 pub fn leave_stage_fullscreen(&mut self, cx: &mut Context<Self>) {
603 let Some(call) = self.call.as_mut().filter(|call| call.stage_fullscreen) else {
604 return;
605 };
606 call.stage_fullscreen = false;
607 cx.emit(AppEvent::Call);
608 cx.notify();
609 }
610
611 pub fn stage_fullscreen(&self) -> bool {
612 self.call.as_ref().is_some_and(|call| call.stage_fullscreen && call.model.screen_sharer.is_some())
613 }
614
615 pub fn viewing_call(&self) -> bool {
616 self.call.as_ref().is_some_and(|call| call.viewing)
617 }
618}
619
620impl AppState {
621 pub fn on_engine_event(&mut self, event: EngineEvent, cx: &mut Context<Self>) {
622 match event {
623 EngineEvent::Incoming(ring) => self.push_ring(ring, false, cx),
624 EngineEvent::RingEnded { ring_id, kind, .. } => {
625 self.signal_ring(ring_id, RingSignal::Remote(kind), cx);
626 }
627 }
628 }
629
630 fn push_ring(&mut self, ring: calling::IncomingRing, demo: bool, cx: &mut Context<Self>) {
631 let caller_user_id = ring.caller.mri.strip_prefix(ORGID_PREFIX).map(str::to_owned);
632 self.rings.push(ring, demo, Instant::now());
633 if let Some(user_id) = caller_user_id {
634 self.request_avatars(vec![user_id], cx);
635 }
636 cx.emit(AppEvent::Ring);
637 cx.notify();
638 }
639
640 pub fn demo_incoming_ring(&mut self, cx: &mut Context<Self>) {
641 self.push_ring(demo_ring(), true, cx);
642 }
643
644 pub fn demo_incoming_video_ring(&mut self, cx: &mut Context<Self>) {
645 self.push_ring(demo_video_ring(), true, cx);
646 }
647
648 pub fn start_demo_scene(&mut self, scene: DemoScene, cx: &mut Context<Self>) {
649 if self.call.is_some() {
650 return;
651 }
652 let (script, model, conversation_id) = if scene.is_one_to_one() {
653 (DemoCall::People(vec![demo_caller()]), CallModel::people("Mara Lindqvist", &[demo_caller()]), "demo-chat-mara")
654 } else {
655 let script = DemoCall::Meeting { guests: demo_guests(DEMO_SMALL_MEETING), lobby: false, organizer: true };
656 (script, CallModel::meeting("Standup", true), "demo-chat-meeting-standup")
657 };
658 let handle = start_demo_scene_call(script, scene);
659 self.begin_call(handle, model, Some(conversation_id.to_owned()), cx);
660 if let Some(call) = self.call.as_mut().filter(|_| !scene.is_one_to_one()) {
661 call.meeting_target = Some(calling::MeetingTarget {
662 thread_id: conversation_id.to_owned(),
663 tenant_id: "demo-tenant".to_owned(),
664 organizer_id: "demo-me".to_owned(),
665 meeting_data: None,
666 });
667 }
668 }
669
670 fn signal_ring(&mut self, ring_id: u64, signal: RingSignal, cx: &mut Context<Self>) {
671 if let Some(outcome) = self.rings.signal(ring_id, signal, Instant::now()) {
672 self.finish_ring(ring_id, outcome, cx);
673 }
674 }
675
676 fn finish_ring(&mut self, ring_id: u64, outcome: RingOutcome, cx: &mut Context<Self>) {
677 if let RingOutcome::Missed(missed) = outcome {
678 if let Some(launcher) = &self.call_launcher {
679 launcher.drop_ring(ring_id);
680 }
681 cx.emit(AppEvent::MissedCall(missed));
682 }
683 cx.emit(AppEvent::Ring);
684 cx.notify();
685 }
686
687 pub fn tick_rings(&mut self, cx: &mut Context<Self>) {
688 if self.rings.is_empty() {
689 return;
690 }
691 for (ring_id, outcome) in self.rings.tick(Instant::now()) {
692 self.finish_ring(ring_id, outcome, cx);
693 }
694 }
695
696 pub fn accept_ringing_call(&mut self, cx: &mut Context<Self>) {
697 if let Some(ring_id) = self.rings.first_ringing_id() {
698 self.accept_ring(ring_id, AcceptMode::Audio, cx);
699 }
700 }
701
702 pub fn decline_ringing_call(&mut self, cx: &mut Context<Self>) {
703 if let Some(ring_id) = self.rings.first_ringing_id() {
704 self.decline_ring(ring_id, cx);
705 }
706 }
707
708 pub fn accept_ring(&mut self, ring_id: u64, mode: AcceptMode, cx: &mut Context<Self>) {
709 let Some(entry) = self.rings.get(ring_id).cloned() else {
710 return;
711 };
712 if self.call.is_some() {
713 self.leave_call(cx);
714 }
715 self.signal_ring(ring_id, RingSignal::Accept, cx);
716 let conversation_id = entry.ring.thread_id.clone();
717 let title = conversation_id
718 .as_deref()
719 .and_then(|id| self.sidebar.chats.iter().find(|chat| chat.id == id))
720 .filter(|_| entry.ring.is_group)
721 .map(chat_title)
722 .unwrap_or_else(|| entry.caller_name().to_owned());
723 let model = CallModel::incoming(&title, &entry.ring.caller.mri, entry.caller_name());
724 if entry.demo {
725 let handle = start_demo_call(DemoCall::Incoming(demo_caller()));
726 self.begin_call(handle, model, conversation_id, cx);
727 if mode == AcceptMode::Video {
728 self.send_call_command(CallCommand::SetCamera(true));
729 }
730 return;
731 }
732 let Some(launcher) = self.call_launcher.clone() else {
733 self.raise_notice(ANSWER_FAILED_NOTICE.to_owned(), None, cx);
734 return;
735 };
736 let receiver = crate::runtime::spawn(async move { launcher.accept_ring(ring_id, mode).await });
737 cx.spawn(async move |this, cx| {
738 let handle = receiver.await.ok().flatten();
739 this.update(cx, |state, cx| match handle {
740 Some(handle) => state.begin_call(handle, model, conversation_id, cx),
741 None => state.raise_notice(ANSWER_FAILED_NOTICE.to_owned(), None, cx),
742 })
743 .ok();
744 })
745 .detach();
746 }
747
748 pub fn decline_ring(&mut self, ring_id: u64, cx: &mut Context<Self>) {
749 let Some(entry) = self.rings.get(ring_id) else {
750 return;
751 };
752 let demo = entry.demo;
753 if !demo && let Some(launcher) = &self.call_launcher {
754 launcher.decline_ring(ring_id);
755 }
756 self.signal_ring(ring_id, RingSignal::Decline, cx);
757 }
758
759 pub fn conversation_of_missed_call(&self, missed: &MissedCall) -> Option<String> {
760 if let Some(thread_id) = missed.thread_id.as_ref().filter(|id| self.sidebar.chats.iter().any(|chat| &chat.id == *id)) {
761 return Some(thread_id.clone());
762 }
763 let user_id = missed.caller_mri.strip_prefix(ORGID_PREFIX)?;
764 self.sidebar
765 .chats
766 .iter()
767 .find(|chat| {
768 crate::data::is_one_on_one(chat)
769 && chat.members.iter().any(|member| member.user_id.as_deref() == Some(user_id))
770 })
771 .map(|chat| chat.id.clone())
772 }
773}
774
775impl AppState {
776 pub fn running_meeting(&self, conversation_id: &str) -> Option<&LiveMeeting> {
777 self.live_meetings
778 .get(conversation_id)
779 .filter(|meeting| meeting.is_running(now_unix()) && meeting.target().is_some())
780 }
781
782 pub fn demo_live_meetings(&mut self) {
783 for conversation_id in ["demo-chat-meeting-standup", DEMO_LOBBY_MEETING] {
784 self.live_meetings.insert(
785 conversation_id.to_owned(),
786 LiveMeeting {
787 thread_id: conversation_id.to_owned(),
788 conversation_url: None,
789 expiration: Some(now_unix() + DEMO_LIVE_MINUTES * 60),
790 organizer_id: Some("demo-jonas".to_owned()),
791 tenant_id: Some("demo-tenant".to_owned()),
792 meeting_code: None,
793 passcode: None,
794 },
795 );
796 }
797 }
798
799 pub fn watches_live_meeting(&self, conversation_id: &str) -> bool {
800 let meeting_chat = self
801 .sidebar
802 .chats
803 .iter()
804 .any(|chat| chat.id == conversation_id && chat.kind.eq_ignore_ascii_case(MEETING_KIND));
805 meeting_chat || matches!(selection_for(&self.sidebar, conversation_id), Some(Selection::Channel(_)))
806 }
807
808 pub fn refresh_live_meeting(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
809 if self.mode.demo || !self.watches_live_meeting(conversation_id) {
810 return;
811 }
812 let Some(launcher) = self.call_launcher.clone() else {
813 return;
814 };
815 if !self.live_refreshing.insert(conversation_id.to_owned()) {
816 return;
817 }
818 let thread_id = conversation_id.to_owned();
819 let receiver = crate::runtime::spawn(async move { launcher.live_meeting(&thread_id).await });
820 let conversation_id = conversation_id.to_owned();
821 cx.spawn(async move |this, cx| {
822 let meeting = receiver.await.ok().flatten();
823 this.update(cx, |state, cx| state.apply_live_meeting(conversation_id, meeting, cx)).ok();
824 })
825 .detach();
826 }
827
828 pub fn apply_live_meeting(&mut self, conversation_id: String, meeting: Option<LiveMeeting>, cx: &mut Context<Self>) {
829 self.live_refreshing.remove(&conversation_id);
830 let changed = match meeting {
831 Some(meeting) => self.live_meetings.insert(conversation_id.clone(), meeting.clone()) != Some(meeting),
832 None => self.live_meetings.remove(&conversation_id).is_some(),
833 };
834 if changed {
835 cx.emit(AppEvent::LiveMeeting);
836 cx.notify();
837 }
838 }
839
840 pub fn on_thread_changed(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
841 self.refresh_live_meeting(conversation_id, cx);
842 }
843}
844
845#[cfg(test)]
846mod tests {
847 use std::sync::Arc;
848 use std::time::{Duration, Instant};
849
850 use std::path::PathBuf;
851
852 use calling::{BackgroundChoice, CallCommand, CallControl, CallState, CallUpdate, DeviceChoice, EndKind, EndReason, EngineEvent, HoldState, Reaction, call_channel};
853 use gpui_kit::{AppContext as _, Entity, TestAppContext};
854 use store::{ChatRecord, MemberRecord, Store};
855
856 use super::{ActiveCall, CallModel, load_camera};
857 use crate::app_state::{AppEvent, AppState, Mode, Selection};
858 use crate::call::TransferCandidate;
859 use crate::call::background::BackgroundPick;
860 use crate::call::demo::demo_ring;
861 use crate::call::features::room_closed_move;
862 use crate::call::model::{BreakoutState, ConsultCall};
863 use crate::data::Person;
864
865 fn app_with_call(cx: &mut TestAppContext) -> Entity<AppState> {
866 cx.update(gpui_kit::init);
867 let store = Arc::new(Store::open_in_memory().unwrap());
868 let app = cx.update(|cx| cx.new(|_| AppState::new(store, Mode::default())));
869 let (handle, _control) = call_channel();
870 cx.update(|cx| {
871 app.update(cx, |state, _| {
872 state.call = Some(ActiveCall::new(7, CallModel::test(), handle.commands, None, handle.video));
873 })
874 });
875 app
876 }
877
878 fn app_with_commands(cx: &mut TestAppContext, model: CallModel, conversation_id: Option<&str>) -> (Entity<AppState>, CallControl) {
879 cx.update(gpui_kit::init);
880 let store = Arc::new(Store::open_in_memory().unwrap());
881 let app = cx.update(|cx| cx.new(|_| AppState::new(store, Mode::default())));
882 let (handle, control) = call_channel();
883 let conversation_id = conversation_id.map(str::to_owned);
884 cx.update(|cx| {
885 app.update(cx, |state, _| {
886 state.call = Some(ActiveCall::new(7, model, handle.commands, conversation_id, handle.video));
887 })
888 });
889 (app, control)
890 }
891
892 fn live_meeting(can_end: bool) -> CallModel {
893 let mut model = CallModel::meeting("Standup", can_end);
894 model.apply(CallUpdate::State(CallState::Connected { since: Instant::now() }));
895 model.apply(CallUpdate::OwnIdentity { mri: "8:orgid:me".into() });
896 model
897 }
898
899 #[gpui_kit::test]
900 fn high_rate_updates_do_not_emit_call_events(cx: &mut TestAppContext) {
901 let app = app_with_call(cx);
902 let emitted = Arc::new(std::sync::atomic::AtomicUsize::new(0));
903 let counter = emitted.clone();
904 cx.update(|cx| {
905 cx.subscribe(&app, move |_, event: &AppEvent, _| {
906 if matches!(event, AppEvent::Call) {
907 counter.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
908 }
909 })
910 .detach();
911 app.update(cx, |state, cx| {
912 state.apply_call_update(7, CallUpdate::VideoReady, cx);
913 state.apply_call_update(7, CallUpdate::Levels { local: 0.5, remote: 0.5 }, cx);
914 state.apply_call_update(7, CallUpdate::Stats { inbound_packets: 1, outbound_packets: 1 }, cx);
915 });
916 });
917 assert_eq!(emitted.load(std::sync::atomic::Ordering::SeqCst), 0);
918 assert!(cx.update(|cx| app.read(cx).call.as_ref().unwrap().model.remote_speaking));
919 cx.update(|cx| app.update(cx, |state, cx| state.apply_call_update(7, CallUpdate::Muted(true), cx)));
920 assert_eq!(emitted.load(std::sync::atomic::Ordering::SeqCst), 1);
921 }
922
923 #[gpui_kit::test]
924 fn the_computer_sound_switch_is_remembered_and_sent_to_the_call(cx: &mut TestAppContext) {
925 let (app, mut control) = app_with_commands(cx, live_meeting(false), None);
926 let store = cx.update(|cx| app.read(cx).store.clone());
927 assert!(!cx.update(|cx| app.read(cx).call_share_sound));
928 cx.update(|cx| app.update(cx, |state, cx| state.set_call_share_sound(true, cx)));
929 assert_eq!(control.try_recv_command(), Some(CallCommand::SetShareSound(true)));
930 let reopened = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));
931 assert!(cx.update(|cx| reopened.read(cx).call_share_sound));
932 cx.update(|cx| app.update(cx, |state, cx| state.set_call_share_sound(false, cx)));
933 let reopened = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));
934 assert!(!cx.update(|cx| reopened.read(cx).call_share_sound));
935 }
936
937 #[gpui_kit::test]
938 fn the_camera_pick_is_remembered_and_the_next_call_starts_with_it(cx: &mut TestAppContext) {
939 let (app, _control) = app_with_commands(cx, live_meeting(false), None);
940 let store = cx.update(|cx| app.read(cx).store.clone());
941 assert_eq!(load_camera(&store), DeviceChoice::SystemDefault);
942 cx.update(|cx| app.update(cx, |state, cx| state.select_call_camera(DeviceChoice::Device("cam-2".into()), cx)));
943 assert_eq!(load_camera(&store), DeviceChoice::Device("cam-2".into()));
944 let reopened = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));
945 assert_eq!(cx.update(|cx| reopened.read(cx).call_camera.clone()), DeviceChoice::Device("cam-2".into()));
946 cx.update(|cx| app.update(cx, |state, cx| state.select_call_camera(DeviceChoice::SystemDefault, cx)));
947 assert_eq!(load_camera(&store), DeviceChoice::SystemDefault);
948 }
949
950 #[gpui_kit::test]
951 fn hands_and_reactions_become_call_commands_and_lowering_needs_the_organizer(cx: &mut TestAppContext) {
952 let (app, mut control) = app_with_commands(cx, live_meeting(false), None);
953 cx.update(|cx| {
954 app.update(cx, |state, cx| {
955 state.toggle_call_hand(cx);
956 state.send_call_reaction(Reaction::Heart, cx);
957 state.lower_call_hand("8:orgid:a".into(), cx);
958 state.lower_all_call_hands(cx);
959 })
960 });
961 assert_eq!(control.try_recv_command(), Some(CallCommand::SetHand(true)));
962 assert_eq!(control.try_recv_command(), Some(CallCommand::SendReaction(Reaction::Heart)));
963 assert_eq!(control.try_recv_command(), None);
964 let (organizer, mut organizer_control) = app_with_commands(cx, live_meeting(true), None);
965 cx.update(|cx| {
966 organizer.update(cx, |state, cx| {
967 state.apply_call_update(7, CallUpdate::Roster(vec![calling::RosterEntry {
968 mri: "8:orgid:a".into(),
969 display_name: "Ana".into(),
970 muted: false,
971 in_lobby: false,
972 has_video: false,
973 sharing: false,
974 hand: Some(calling::RaisedHand { state_id: "s".into(), rank: 1 }),
975 spotlight: None,
976 organizer: false,
977 }]), cx);
978 state.lower_call_hand("8:orgid:a".into(), cx);
979 state.lower_all_call_hands(cx);
980 })
981 });
982 assert_eq!(organizer_control.try_recv_command(), Some(CallCommand::LowerHand { mri: "8:orgid:a".into() }));
983 assert_eq!(organizer_control.try_recv_command(), Some(CallCommand::LowerAllHands));
984 }
985
986 fn guest(mri: &str, name: &str, in_lobby: bool, spotlit: bool) -> calling::RosterEntry {
987 calling::RosterEntry {
988 mri: mri.into(),
989 display_name: name.into(),
990 muted: false,
991 in_lobby,
992 has_video: false,
993 sharing: false,
994 hand: None,
995 spotlight: spotlit.then(|| calling::Spotlight { state_id: "sp".into(), rank: 1 }),
996 organizer: false,
997 }
998 }
999
1000 #[gpui_kit::test]
1001 fn organizer_controls_become_commands_and_attendees_send_nothing(cx: &mut TestAppContext) {
1002 let (attendee, mut attendee_control) = app_with_commands(cx, live_meeting(false), None);
1003 cx.update(|cx| {
1004 attendee.update(cx, |state, cx| {
1005 state.admit_call_guest("8:orgid:g".into(), cx);
1006 state.admit_all_call_guests(cx);
1007 state.deny_call_guest("8:orgid:g".into(), cx);
1008 state.mute_call_participant("8:orgid:a".into(), cx);
1009 state.mute_all_call(cx);
1010 state.remove_call_participant("8:orgid:a".into(), cx);
1011 state.toggle_call_spotlight("8:orgid:a".into(), cx);
1012 })
1013 });
1014 assert_eq!(attendee_control.try_recv_command(), None);
1015 let (organizer, mut control) = app_with_commands(cx, live_meeting(true), None);
1016 cx.update(|cx| {
1017 organizer.update(cx, |state, cx| {
1018 state.apply_call_update(7, CallUpdate::Roster(vec![guest("8:orgid:a", "Ana", false, false), guest("8:orgid:g", "Gast", true, false)]), cx);
1019 state.admit_call_guest("8:orgid:g".into(), cx);
1020 state.admit_all_call_guests(cx);
1021 state.deny_call_guest("8:orgid:g".into(), cx);
1022 state.mute_call_participant("8:orgid:a".into(), cx);
1023 state.mute_all_call(cx);
1024 state.remove_call_participant("8:orgid:a".into(), cx);
1025 state.toggle_call_spotlight("8:orgid:a".into(), cx);
1026 })
1027 });
1028 assert_eq!(control.try_recv_command(), Some(CallCommand::Admit { mri: "8:orgid:g".into() }));
1029 assert_eq!(control.try_recv_command(), Some(CallCommand::AdmitAll));
1030 assert_eq!(control.try_recv_command(), Some(CallCommand::Deny { mri: "8:orgid:g".into() }));
1031 assert_eq!(control.try_recv_command(), Some(CallCommand::MuteParticipant { mri: "8:orgid:a".into() }));
1032 assert_eq!(control.try_recv_command(), Some(CallCommand::MuteAll));
1033 assert_eq!(control.try_recv_command(), Some(CallCommand::RemoveParticipant { mri: "8:orgid:a".into() }));
1034 assert_eq!(control.try_recv_command(), Some(CallCommand::Spotlight { mri: "8:orgid:a".into() }));
1035 }
1036
1037 #[gpui_kit::test]
1038 fn the_spotlight_button_stops_an_existing_spotlight_and_pinning_stays_local(cx: &mut TestAppContext) {
1039 let (app, mut control) = app_with_commands(cx, live_meeting(true), None);
1040 cx.update(|cx| {
1041 app.update(cx, |state, cx| {
1042 state.apply_call_update(7, CallUpdate::Roster(vec![guest("8:orgid:a", "Ana", false, true)]), cx);
1043 state.toggle_call_spotlight("8:orgid:a".into(), cx);
1044 state.toggle_call_pin("8:orgid:a", cx);
1045 assert_eq!(state.call.as_ref().unwrap().model.pinned.as_deref(), Some("8:orgid:a"));
1046 state.toggle_call_pin("8:orgid:a", cx);
1047 assert_eq!(state.call.as_ref().unwrap().model.pinned, None);
1048 })
1049 });
1050 assert_eq!(control.try_recv_command(), Some(CallCommand::StopSpotlight { mri: "8:orgid:a".into() }));
1051 assert_eq!(control.try_recv_command(), None);
1052 }
1053
1054 #[gpui_kit::test]
1055 fn captions_toggle_between_on_and_off_and_only_in_meetings(cx: &mut TestAppContext) {
1056 let (app, mut control) = app_with_commands(cx, live_meeting(false), None);
1057 cx.update(|cx| {
1058 app.update(cx, |state, cx| {
1059 state.toggle_call_captions(cx);
1060 state.apply_call_update(7, CallUpdate::Captions(calling::CaptionState::On), cx);
1061 state.toggle_call_captions(cx);
1062 })
1063 });
1064 assert_eq!(control.try_recv_command(), Some(CallCommand::SetCaptions(true)));
1065 assert_eq!(control.try_recv_command(), Some(CallCommand::SetCaptions(false)));
1066 let app = app_with_call(cx);
1067 cx.update(|cx| app.update(cx, |state, cx| state.toggle_call_captions(cx)));
1068 }
1069
1070 #[gpui_kit::test]
1071 fn the_background_choice_is_remembered_and_sent_to_the_call(cx: &mut TestAppContext) {
1072 let (app, mut control) = app_with_commands(cx, live_meeting(false), None);
1073 let store = cx.update(|cx| app.read(cx).store.clone());
1074 assert_eq!(cx.update(|cx| app.read(cx).call_background.clone()), BackgroundPick::None);
1075 cx.update(|cx| app.update(cx, |state, cx| state.set_call_background(BackgroundPick::Blur, cx)));
1076 assert_eq!(control.try_recv_command(), Some(CallCommand::SetBackground(BackgroundChoice::Blur)));
1077 assert_eq!(cx.update(|cx| app.read(cx).call.as_ref().unwrap().model.background.clone()), BackgroundPick::Blur);
1078 let reopened = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));
1079 assert_eq!(cx.update(|cx| reopened.read(cx).call_background.clone()), BackgroundPick::Blur);
1080 let picture = PathBuf::from("/pictures/wall.jpg");
1081 cx.update(|cx| app.update(cx, |state, cx| state.set_call_background(BackgroundPick::Custom(picture.clone()), cx)));
1082 assert_eq!(control.try_recv_command(), Some(CallCommand::SetBackground(BackgroundChoice::Image(picture.clone()))));
1083 let reopened = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));
1084 assert_eq!(cx.update(|cx| reopened.read(cx).call_background.clone()), BackgroundPick::Custom(picture));
1085 cx.update(|cx| app.update(cx, |state, cx| state.set_call_background(BackgroundPick::None, cx)));
1086 assert_eq!(control.try_recv_command(), Some(CallCommand::SetBackground(BackgroundChoice::None)));
1087 }
1088
1089 #[gpui_kit::test]
1090 fn a_default_image_that_is_not_downloaded_yet_sends_nothing(cx: &mut TestAppContext) {
1091 let (app, mut control) = app_with_commands(cx, live_meeting(false), None);
1092 cx.update(|cx| app.update(cx, |state, cx| state.set_call_background(BackgroundPick::Default("office_01".into()), cx)));
1093 assert_eq!(control.try_recv_command(), None);
1094 }
1095
1096 #[gpui_kit::test]
1097 fn only_the_organizer_starts_a_recording_and_the_notice_needs_a_consent_request(cx: &mut TestAppContext) {
1098 let (attendee, mut attendee_control) = app_with_commands(cx, live_meeting(false), None);
1099 cx.update(|cx| {
1100 attendee.update(cx, |state, cx| {
1101 state.set_call_recording(true, cx);
1102 state.accept_recording_notice(cx);
1103 })
1104 });
1105 assert_eq!(attendee_control.try_recv_command(), None);
1106 let (organizer, mut control) = app_with_commands(cx, live_meeting(true), None);
1107 cx.update(|cx| {
1108 organizer.update(cx, |state, cx| {
1109 state.set_call_recording(true, cx);
1110 state.apply_call_update(7, CallUpdate::Recording(true), cx);
1111 state.set_call_recording(false, cx);
1112 state.accept_recording_notice(cx);
1113 state.apply_call_update(7, CallUpdate::ConsentRequired(true), cx);
1114 state.accept_recording_notice(cx);
1115 })
1116 });
1117 assert_eq!(control.try_recv_command(), Some(CallCommand::SetRecording { on: true, title: "Standup".into() }));
1118 assert_eq!(control.try_recv_command(), Some(CallCommand::SetRecording { on: false, title: "Standup".into() }));
1119 assert_eq!(control.try_recv_command(), Some(CallCommand::ConsentToRecording));
1120 assert_eq!(control.try_recv_command(), None);
1121 }
1122
1123 fn live_one_to_one() -> CallModel {
1124 let mut model = CallModel::people("Bea", &[("8:orgid:bea".into(), "Bea".into())]);
1125 model.apply(CallUpdate::State(CallState::Connected { since: Instant::now() }));
1126 model
1127 }
1128
1129 #[gpui_kit::test]
1130 fn hold_and_resume_alternate_and_stop_while_the_other_side_holds(cx: &mut TestAppContext) {
1131 let (app, mut control) = app_with_commands(cx, live_one_to_one(), None);
1132 cx.update(|cx| {
1133 app.update(cx, |state, cx| {
1134 state.toggle_call_hold(cx);
1135 state.apply_call_update(7, CallUpdate::Hold(HoldState::Local), cx);
1136 state.toggle_call_hold(cx);
1137 state.apply_call_update(7, CallUpdate::Hold(HoldState::Remote), cx);
1138 state.toggle_call_hold(cx);
1139 })
1140 });
1141 assert_eq!(control.try_recv_command(), Some(CallCommand::Hold(true)));
1142 assert_eq!(control.try_recv_command(), Some(CallCommand::Hold(false)));
1143 assert_eq!(control.try_recv_command(), None);
1144 let (meeting, mut meeting_control) = app_with_commands(cx, live_meeting(true), None);
1145 cx.update(|cx| meeting.update(cx, |state, cx| state.toggle_call_hold(cx)));
1146 assert_eq!(meeting_control.try_recv_command(), None);
1147 }
1148
1149 fn candidate(name: &str) -> TransferCandidate {
1150 TransferCandidate { mri: format!("8:orgid:{name}"), name: name.into(), user_id: Some(name.into()), chat_id: format!("19:{name}") }
1151 }
1152
1153 #[gpui_kit::test]
1154 fn a_blind_transfer_names_the_target_and_a_consulted_one_carries_the_replacement_link(cx: &mut TestAppContext) {
1155 let (app, mut control) = app_with_commands(cx, live_one_to_one(), None);
1156 cx.update(|cx| app.update(cx, |state, cx| state.transfer_call_blind(candidate("ana"), cx)));
1157 assert_eq!(
1158 control.try_recv_command(),
1159 Some(CallCommand::Transfer { target: calling::Callee { mri: "8:orgid:ana".into(), display_name: "ana".into() }, replaces: None })
1160 );
1161 let (consulting, mut consult_control) = app_with_commands(cx, live_one_to_one(), None);
1162 let (consult_handle, _consult_updates) = call_channel();
1163 cx.update(|cx| {
1164 consulting.update(cx, |state, cx| {
1165 state.call.as_mut().unwrap().consult = Some(ConsultCall {
1166 id: 8,
1167 target: ("8:orgid:ana".into(), "Ana".into()),
1168 commands: consult_handle.commands,
1169 state: CallState::Connecting,
1170 replacement: Some("https://cc.skype.com/replacement".into()),
1171 transferring: false,
1172 });
1173 state.transfer_consulted(cx);
1174 state.call.as_mut().unwrap().consult.as_mut().unwrap().state = CallState::Connected { since: Instant::now() };
1175 state.transfer_consulted(cx);
1176 })
1177 });
1178 assert_eq!(
1179 consult_control.try_recv_command(),
1180 Some(CallCommand::Transfer {
1181 target: calling::Callee { mri: "8:orgid:ana".into(), display_name: "Ana".into() },
1182 replaces: Some("https://cc.skype.com/replacement".into()),
1183 })
1184 );
1185 assert_eq!(consult_control.try_recv_command(), None);
1186 }
1187
1188 #[gpui_kit::test]
1189 fn the_transfer_list_holds_one_to_one_chats_without_the_person_on_the_call(cx: &mut TestAppContext) {
1190 let app = app_with_chats(cx);
1191 cx.update(|cx| {
1192 app.update(cx, |state, cx| {
1193 let names: Vec<String> = state.transfer_candidates().into_iter().map(|candidate| candidate.name).collect();
1194 assert_eq!(names, vec!["Bea".to_owned()]);
1195 let (handle, _control) = call_channel();
1196 let mut on_the_call = CallModel::people("Bea", &[("8:orgid:bea-id".into(), "Bea".into())]);
1197 on_the_call.apply(CallUpdate::State(CallState::Connected { since: Instant::now() }));
1198 state.call = Some(ActiveCall::new(9, on_the_call, handle.commands, None, handle.video));
1199 assert!(state.transfer_candidates().is_empty());
1200 cx.notify();
1201 })
1202 });
1203 }
1204
1205 fn room_move(returning: bool) -> calling::BreakoutMove {
1206 calling::BreakoutMove {
1207 room_name: "Room 1".into(),
1208 target: calling::MeetingTarget { thread_id: "19:meeting_room@thread.v2".into(), tenant_id: "t".into(), organizer_id: "o".into(), meeting_data: None },
1209 returning,
1210 }
1211 }
1212
1213 fn main_target() -> calling::MeetingTarget {
1214 calling::MeetingTarget { thread_id: "19:meeting_main@thread.v2".into(), tenant_id: "t".into(), organizer_id: "o".into(), meeting_data: None }
1215 }
1216
1217 #[gpui_kit::test]
1218 fn being_moved_to_a_room_leaves_the_call_and_remembers_the_way_back(cx: &mut TestAppContext) {
1219 let (app, mut control) = app_with_commands(cx, live_meeting(false), None);
1220 cx.update(|cx| {
1221 app.update(cx, |state, cx| {
1222 state.call.as_mut().unwrap().meeting_target = Some(main_target());
1223 state.apply_call_update(7, CallUpdate::BreakoutMove(room_move(false)), cx);
1224 let pending = state.call.as_ref().unwrap().pending_move.clone().expect("a move is pending");
1225 assert_eq!(pending.target.thread_id, "19:meeting_room@thread.v2");
1226 assert_eq!(pending.title, "Room 1");
1227 let room = pending.breakout.expect("a room");
1228 assert_eq!(room.main, Some(main_target()));
1229 assert_eq!(room.main_title, "Standup");
1230 assert_eq!(state.notice.as_ref().map(|notice| notice.text.as_str()), Some("Moving you to Room 1"));
1231 state.apply_call_update(7, CallUpdate::BreakoutMove(room_move(false)), cx);
1232 })
1233 });
1234 assert_eq!(control.try_recv_command(), Some(CallCommand::Hangup));
1235 assert_eq!(control.try_recv_command(), None);
1236 }
1237
1238 #[gpui_kit::test]
1239 fn the_return_button_and_a_closed_room_both_lead_back_to_the_main_meeting(cx: &mut TestAppContext) {
1240 let mut room = live_meeting(false);
1241 room.breakout = Some(BreakoutState { room_name: "Room 1".into(), main: Some(main_target()), main_title: "Standup".into() });
1242 let (app, mut control) = app_with_commands(cx, room.clone(), None);
1243 cx.update(|cx| {
1244 app.update(cx, |state, cx| {
1245 state.return_to_main_meeting(cx);
1246 let pending = state.call.as_ref().unwrap().pending_move.clone().expect("a move is pending");
1247 assert_eq!(pending.target, main_target());
1248 assert_eq!(pending.title, "Standup");
1249 assert!(pending.breakout.is_none());
1250 })
1251 });
1252 assert_eq!(control.try_recv_command(), Some(CallCommand::Hangup));
1253 let (closed, _control) = app_with_commands(cx, room, None);
1254 cx.update(|cx| {
1255 closed.update(cx, |state, _| {
1256 let call = state.call.as_ref().unwrap();
1257 let moved = room_closed_move(call, &EndReason::Remote(EndKind::RoomClosed)).expect("goes back");
1258 assert_eq!(moved.target, main_target());
1259 assert!(room_closed_move(call, &EndReason::Remote(EndKind::Normal)).is_none());
1260 assert!(room_closed_move(call, &EndReason::LocalHangup).is_none());
1261 })
1262 });
1263 let (plain, _control) = app_with_commands(cx, live_meeting(false), None);
1264 cx.update(|cx| plain.update(cx, |state, _| assert!(room_closed_move(state.call.as_ref().unwrap(), &EndReason::Remote(EndKind::RoomClosed)).is_none())));
1265 }
1266
1267 #[gpui_kit::test]
1268 fn the_whiteboard_menu_asks_for_the_board_unless_someone_already_shares_one(cx: &mut TestAppContext) {
1269 let (app, mut control) = app_with_commands(cx, live_meeting(false), None);
1270 cx.update(|cx| {
1271 app.update(cx, |state, cx| {
1272 state.open_call_whiteboard(cx);
1273 state.apply_call_update(
1274 7,
1275 CallUpdate::Whiteboard(Some(calling::ContentShare {
1276 session_id: "s".into(),
1277 presenter: Some("8:orgid:ana".into()),
1278 subject: "Whiteboard".into(),
1279 url: Some("https://app.whiteboard.microsoft.com/x".into()),
1280 whiteboard: true,
1281 })),
1282 cx,
1283 );
1284 state.open_call_whiteboard(cx);
1285 })
1286 });
1287 assert_eq!(control.try_recv_command(), Some(CallCommand::OpenWhiteboard { title: "Standup".into() }));
1288 assert_eq!(control.try_recv_command(), None);
1289 }
1290
1291 #[gpui_kit::test]
1292 fn the_chat_panel_opens_the_meeting_thread_and_the_badge_counts_only_while_closed(cx: &mut TestAppContext) {
1293 let (app, _control) = app_with_commands(cx, live_meeting(false), Some("19:list@thread.v2"));
1294 cx.update(|cx| {
1295 app.update(cx, |state, cx| {
1296 state.directory.unread_counts.insert("19:meeting_x@thread.v2".into(), 3);
1297 assert_eq!(state.call_chat_thread(), None);
1298 assert_eq!(state.call_chat_unread(), 0);
1299 state.apply_call_update(7, CallUpdate::MeetingChat("19:meeting_x@thread.v2".into()), cx);
1300 assert_eq!(state.call_chat_unread(), 3);
1301 state.toggle_call_chat(cx);
1302 assert_eq!(state.call_chat_thread().as_deref(), Some("19:meeting_x@thread.v2"));
1303 assert_eq!(state.call_chat_unread(), 0);
1304 state.toggle_call_chat(cx);
1305 assert_eq!(state.call_chat_thread(), None);
1306 })
1307 });
1308 }
1309
1310 #[gpui_kit::test]
1311 fn a_call_without_a_chat_has_no_panel(cx: &mut TestAppContext) {
1312 let app = app_with_call(cx);
1313 cx.update(|cx| {
1314 app.update(cx, |state, cx| {
1315 state.toggle_call_chat(cx);
1316 assert!(!state.call.as_ref().unwrap().chat_open);
1317 })
1318 });
1319 }
1320
1321 fn app_with_chats(cx: &mut TestAppContext) -> Entity<AppState> {
1322 cx.update(gpui_kit::init);
1323 let store = Arc::new(Store::open_in_memory().unwrap());
1324 let app = cx.update(|cx| cx.new(|_| AppState::new(store, Mode::default())));
1325 cx.update(|cx| {
1326 app.update(cx, |state, _| {
1327 state.directory.me = Some(Person {
1328 user_id: "me-id".into(),
1329 display_name: "Me".into(),
1330 });
1331 state.sidebar.chats = vec![
1332 ChatRecord {
1333 id: "19:meeting@thread.v2".into(),
1334 kind: "meeting".into(),
1335 members: vec![MemberRecord { user_id: Some("bea-id".into()), display_name: "Bea".into() }],
1336 ..Default::default()
1337 },
1338 ChatRecord {
1339 id: "19:dm@unq.gbl.spaces".into(),
1340 kind: "oneOnOne".into(),
1341 members: vec![
1342 MemberRecord { user_id: Some("me-id".into()), display_name: "Me".into() },
1343 MemberRecord { user_id: Some("bea-id".into()), display_name: "Bea".into() },
1344 ],
1345 ..Default::default()
1346 },
1347 ];
1348 })
1349 });
1350 app
1351 }
1352
1353 #[gpui_kit::test]
1354 fn declining_by_shortcut_only_acts_while_a_ring_shows(cx: &mut TestAppContext) {
1355 let app = app_with_chats(cx);
1356 cx.update(|cx| {
1357 app.update(cx, |state, cx| {
1358 state.decline_ringing_call(cx);
1359 assert!(!state.rings.is_ringing());
1360 state.demo_incoming_ring(cx);
1361 assert!(state.rings.is_ringing());
1362 state.decline_ringing_call(cx);
1363 assert!(!state.rings.is_ringing());
1364 })
1365 });
1366 }
1367
1368 #[gpui_kit::test]
1369 fn picking_another_chat_moves_the_call_to_the_mini_window(cx: &mut TestAppContext) {
1370 let app = app_with_call(cx);
1371 cx.update(|cx| {
1372 app.update(cx, |state, cx| {
1373 assert!(state.viewing_call());
1374 state.select(Selection::Chat("c1".into()), cx);
1375 assert!(!state.viewing_call());
1376 state.show_call(true, cx);
1377 assert!(state.viewing_call());
1378 })
1379 });
1380 }
1381
1382 #[gpui_kit::test]
1383 fn an_ended_call_closes_the_view_and_raises_a_notice(cx: &mut TestAppContext) {
1384 let app = app_with_call(cx);
1385 let since = Instant::now() - Duration::from_secs(42);
1386 cx.update(|cx| {
1387 app.update(cx, |state, cx| {
1388 state.apply_call_update(7, CallUpdate::State(CallState::Connected { since }), cx);
1389 assert!(state.call.is_some());
1390 state.apply_call_update(
1391 7,
1392 CallUpdate::State(CallState::Ended {
1393 reason: EndReason::LocalHangup,
1394 }),
1395 cx,
1396 );
1397 assert!(state.call.is_none());
1398 let notice = state.notice.as_ref().expect("notice");
1399 assert_eq!(notice.text, "Call ended 00:42");
1400 })
1401 });
1402 }
1403
1404 #[gpui_kit::test]
1405 fn full_window_exists_only_while_someone_shares_and_escape_leaves_it(cx: &mut TestAppContext) {
1406 let app = app_with_call(cx);
1407 cx.update(|cx| {
1408 app.update(cx, |state, cx| {
1409 state.toggle_stage_fullscreen(cx);
1410 assert!(!state.stage_fullscreen());
1411 state.apply_call_update(7, CallUpdate::ScreenShare(Some("8:orgid:a".into())), cx);
1412 state.toggle_stage_fullscreen(cx);
1413 assert!(state.stage_fullscreen());
1414 state.leave_stage_fullscreen(cx);
1415 assert!(!state.stage_fullscreen());
1416 state.toggle_stage_fullscreen(cx);
1417 state.apply_call_update(7, CallUpdate::ScreenShare(None), cx);
1418 assert!(!state.stage_fullscreen());
1419 })
1420 });
1421 }
1422
1423 #[gpui_kit::test]
1424 fn a_declined_call_names_who_declined(cx: &mut TestAppContext) {
1425 let app = app_with_call(cx);
1426 cx.update(|cx| {
1427 app.update(cx, |state, cx| {
1428 state.call.as_mut().unwrap().model.peer_name = "Bea".into();
1429 state.apply_call_update(
1430 7,
1431 CallUpdate::State(CallState::Ended {
1432 reason: EndReason::Remote(EndKind::Declined),
1433 }),
1434 cx,
1435 );
1436 assert_eq!(state.notice.as_ref().unwrap().text, "Bea declined");
1437 })
1438 });
1439 }
1440
1441 #[gpui_kit::test]
1442 fn updates_of_an_older_call_are_ignored(cx: &mut TestAppContext) {
1443 let app = app_with_call(cx);
1444 cx.update(|cx| {
1445 app.update(cx, |state, cx| {
1446 state.apply_call_update(
1447 6,
1448 CallUpdate::State(CallState::Ended {
1449 reason: EndReason::Dropped,
1450 }),
1451 cx,
1452 );
1453 assert!(state.call.is_some());
1454 assert!(state.notice.is_none());
1455 })
1456 });
1457 }
1458
1459 #[gpui_kit::test]
1460 fn a_ring_that_times_out_becomes_a_missed_call_event(cx: &mut TestAppContext) {
1461 cx.update(gpui_kit::init);
1462 let store = Arc::new(Store::open_in_memory().unwrap());
1463 let app = cx.update(|cx| cx.new(|_| AppState::new(store, Mode::default())));
1464 cx.update(|cx| {
1465 app.update(cx, |state, cx| {
1466 state.on_engine_event(EngineEvent::Incoming(demo_ring()), cx);
1467 assert!(state.rings.is_ringing());
1468 state.tick_rings(cx);
1469 assert!(state.rings.is_ringing());
1470 state.on_engine_event(
1471 EngineEvent::RingEnded {
1472 ring_id: demo_ring().ring_id,
1473 kind: EndKind::Cancelled,
1474 answered_by: None,
1475 },
1476 cx,
1477 );
1478 assert!(!state.rings.is_ringing());
1479 })
1480 });
1481 }
1482
1483 #[gpui_kit::test]
1484 fn calls_are_refused_for_meeting_chats_and_missing_chats(cx: &mut TestAppContext) {
1485 let app = app_with_chats(cx);
1486 cx.update(|cx| {
1487 app.update(cx, |state, cx| {
1488 state.start_chat_call("19:meeting@thread.v2", cx);
1489 assert!(state.call.is_none());
1490 assert_eq!(state.notice.as_ref().unwrap().text, "This chat cannot be called");
1491 state.start_chat_call("19:unknown", cx);
1492 assert!(state.call.is_none());
1493 })
1494 });
1495 }
1496
1497 #[gpui_kit::test]
1498 fn a_missed_call_finds_the_one_on_one_chat_of_the_caller(cx: &mut TestAppContext) {
1499 let app = app_with_chats(cx);
1500 cx.update(|cx| {
1501 app.update(cx, |state, _| {
1502 let missed = super::MissedCall {
1503 caller_mri: "8:orgid:bea-id".into(),
1504 caller_name: "Bea".into(),
1505 thread_id: None,
1506 at: chrono::Utc::now(),
1507 };
1508 assert_eq!(state.conversation_of_missed_call(&missed).as_deref(), Some("19:dm@unq.gbl.spaces"));
1509 let direct = super::MissedCall { thread_id: Some("19:dm@unq.gbl.spaces".into()), ..missed.clone() };
1510 assert_eq!(state.conversation_of_missed_call(&direct).as_deref(), Some("19:dm@unq.gbl.spaces"));
1511 })
1512 });
1513 }
1514
1515 #[gpui_kit::test]
1516 fn only_meeting_chats_and_channels_watch_for_a_running_meeting(cx: &mut TestAppContext) {
1517 let app = app_with_chats(cx);
1518 cx.update(|cx| {
1519 app.update(cx, |state, _| {
1520 assert!(state.watches_live_meeting("19:meeting@thread.v2"));
1521 assert!(!state.watches_live_meeting("19:dm@unq.gbl.spaces"));
1522 assert!(!state.watches_live_meeting("19:unknown"));
1523 })
1524 });
1525 }
1526
1527 #[gpui_kit::test]
1528 fn a_live_meeting_shows_until_it_ends(cx: &mut TestAppContext) {
1529 let app = app_with_chats(cx);
1530 let meeting = calling::meeting::LiveMeeting {
1531 thread_id: "19:meeting@thread.v2".into(),
1532 conversation_url: None,
1533 expiration: Some(chrono::Utc::now().timestamp() + 600),
1534 organizer_id: Some("org".into()),
1535 tenant_id: Some("tenant".into()),
1536 meeting_code: None,
1537 passcode: None,
1538 };
1539 cx.update(|cx| {
1540 app.update(cx, |state, cx| {
1541 assert!(state.running_meeting("19:meeting@thread.v2").is_none());
1542 state.apply_live_meeting("19:meeting@thread.v2".into(), Some(meeting), cx);
1543 assert!(state.running_meeting("19:meeting@thread.v2").is_some());
1544 state.apply_live_meeting("19:meeting@thread.v2".into(), None, cx);
1545 assert!(state.running_meeting("19:meeting@thread.v2").is_none());
1546 })
1547 });
1548 }
1549}