BlueGit

ict rusty-teams

Files

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

model.rs

model.rs 77.5 KiB Download Raw
1use std::cell::Cell;
2use std::collections::HashSet;
3use std::rc::Rc;
4use std::sync::Arc;
5use std::time::{Duration, Instant};
6
7use calling::{
8 AttendeeLimits, CallCommand, CallState, CallUpdate, CameraDevice, CaptionEntry, CaptionState, ContentShare,
9 DeviceChoice, DeviceLists, EndKind, EndReason, HoldState, MeetingCapability, MeetingRole,
10 MeetingTarget, Progress, Reaction, Replacement, RosterEntry, ShareKind, SharePicker, ShareSource, SpeakingDetector, StatsSample, VideoHub,
11 VideoWant,
12};
13use teams_core::RecordingPolicy;
14use tokio::sync::mpsc::UnboundedSender;
15
16use super::background::BackgroundPick;
17use super::health::{HealthBanner, HealthState};
18use super::bubbles::ChatBubble;
19use super::fullscreen::FullscreenState;
20use super::pictures::CallPictures;
21use super::stage_layout::{
22 FILMSTRIP_MAX, RECENT_SPEAKER, SPEAKER_HOLD, VisibleRotation, first_page_size, split_overflow,
23};
24use super::transcript::{Transcript, TranscriptEntry};
25use super::view_settings::{CallLayout, ViewSettings};
26use super::options_dialog::OptionsDialog;
27use super::push_to_talk::PushToTalk;
28use super::report::SharedRecorder;
29use super::share_view::ShareStage;
30
31pub const TEST_CALL_TITLE: &str = "Test call";
32pub const ECHO_NAME: &str = "Teams echo";
33pub const ECHO_MRI: &str = calling::signaling::ECHO_BOT_MRI;
34const ORGID_PREFIX: &str = "8:orgid:";
35const BOT_PREFIX: &str = "28:";
36const AVATAR_SHARE: f32 = 0.42;
37const MIN_AVATAR: f32 = 32.;
38const MAX_AVATAR: f32 = 96.;
39pub const REACTION_SHOWN: Duration = Duration::from_secs(3);
40const OWN_ECHO_WINDOW: Duration = Duration::from_secs(2);
41pub const CAPTION_SHOWN: Duration = Duration::from_secs(4);
42const CAPTION_LINES: usize = 2;
43
44pub struct ActiveCall {
45 pub id: u64,
46 pub model: CallModel,
47 pub commands: UnboundedSender<CallCommand>,
48 pub viewing: bool,
49 pub conversation_id: Option<String>,
50 pub video: Arc<VideoHub>,
51 pub pictures: CallPictures,
52 pub stage_fullscreen: bool,
53 pub fullscreen: Option<FullscreenState>,
54 pub stage_size: Rc<Cell<(f32, f32)>>,
55 pub sent_wants: Vec<VideoWant>,
56 pub share_stage: ShareStage,
57 pub bubbles: Vec<ChatBubble>,
58 pub share_menu_open: bool,
59 pub lobby_list_open: bool,
60 pub chat_open: bool,
61 pub transcript_open: bool,
62 pub people_open: bool,
63 pub people_scroll: gpui_kit::ScrollHandle,
64 pub options_dialog: Option<OptionsDialog>,
65 pub meeting_target: Option<MeetingTarget>,
66 pub pending_move: Option<PendingMove>,
67 pub consult: Option<ConsultCall>,
68 pub push_to_talk: PushToTalk,
69 pub report: Option<SharedRecorder>,
70 pub lobby_tone_at: Option<Instant>,
71}
72
73#[derive(Debug, Clone, PartialEq)]
74pub struct PendingMove {
75 pub target: MeetingTarget,
76 pub title: String,
77 pub breakout: Option<BreakoutState>,
78}
79
80pub struct ConsultCall {
81 pub target: (String, String),
82 pub held_name: String,
83 pub replacement: Option<Replacement>,
84 pub transfer: ConsultTransfer,
85}
86
87#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
88pub enum ConsultTransfer {
89 #[default]
90 Idle,
91 Pending,
92 Done,
93}
94
95impl ConsultCall {
96 pub fn new(target: (String, String), held_name: String) -> Self {
97 ConsultCall {
98 target,
99 held_name,
100 replacement: None,
101 transfer: ConsultTransfer::Idle,
102 }
103 }
104
105 pub fn ready_to_transfer(&self, model: &CallModel) -> bool {
106 model.is_live() && self.replacement.is_some() && self.transfer == ConsultTransfer::Idle
107 }
108
109 pub fn banner_text(&self) -> String {
110 match self.transfer {
111 ConsultTransfer::Idle => format!("{} is on hold", self.held_name),
112 ConsultTransfer::Pending | ConsultTransfer::Done => {
113 format!("Transferring {} to {}...", self.held_name, self.target.1)
114 }
115 }
116 }
117}
118
119impl ActiveCall {
120 pub fn new(
121 id: u64,
122 model: CallModel,
123 commands: UnboundedSender<CallCommand>,
124 conversation_id: Option<String>,
125 video: Arc<VideoHub>,
126 ) -> Self {
127 ActiveCall {
128 id,
129 model,
130 commands,
131 viewing: true,
132 conversation_id,
133 video,
134 pictures: CallPictures::default(),
135 stage_fullscreen: false,
136 fullscreen: None,
137 stage_size: Rc::default(),
138 sent_wants: Vec::new(),
139 share_stage: ShareStage::default(),
140 lobby_tone_at: None,
141 bubbles: Vec::new(),
142 share_menu_open: false,
143 lobby_list_open: false,
144 chat_open: false,
145 transcript_open: false,
146 people_open: false,
147 people_scroll: gpui_kit::ScrollHandle::new(),
148 options_dialog: None,
149 meeting_target: None,
150 pending_move: None,
151 consult: None,
152 push_to_talk: PushToTalk::default(),
153 report: None,
154 }
155 }
156
157 pub fn chat_thread(&self) -> Option<&str> {
158 chat_thread(
159 self.model.kind,
160 self.model.meeting_chat.as_deref(),
161 self.conversation_id.as_deref(),
162 )
163 }
164}
165
166pub fn chat_thread<'a>(
167 kind: CallKind,
168 meeting_chat: Option<&'a str>,
169 conversation_id: Option<&'a str>,
170) -> Option<&'a str> {
171 match kind {
172 CallKind::Meeting => meeting_chat.or(conversation_id),
173 CallKind::Test | CallKind::Direct | CallKind::Group => conversation_id,
174 }
175}
176
177#[derive(Debug, Clone, Copy, PartialEq, Eq)]
178pub enum CallKind {
179 Test,
180 Direct,
181 Group,
182 Meeting,
183}
184
185#[derive(Debug, Clone, Copy, PartialEq, Eq)]
186pub enum TileState {
187 Invited,
188 Present,
189 InLobby,
190 Left,
191}
192
193#[derive(Debug, Clone, PartialEq, Eq)]
194pub struct Tile {
195 pub mri: String,
196 pub user_id: Option<String>,
197 pub name: String,
198 pub muted: bool,
199 pub state: TileState,
200 pub invited: bool,
201 pub has_video: bool,
202 pub hand: Option<u64>,
203 pub spotlight: Option<u64>,
204 pub role: Option<MeetingRole>,
205 pub limits: AttendeeLimits,
206}
207
208impl Tile {
209 pub fn invited(mri: &str, name: &str) -> Tile {
210 Tile {
211 mri: mri.to_owned(),
212 user_id: mri.strip_prefix(ORGID_PREFIX).map(str::to_owned),
213 name: name.to_owned(),
214 muted: false,
215 state: TileState::Invited,
216 invited: true,
217 has_video: false,
218 hand: None,
219 spotlight: None,
220 role: None,
221 limits: AttendeeLimits::default(),
222 }
223 }
224}
225
226#[derive(Debug, Clone, PartialEq)]
227pub struct BreakoutState {
228 pub room_name: String,
229 pub main: Option<MeetingTarget>,
230 pub main_title: String,
231}
232
233#[derive(Debug, Clone, PartialEq, Eq)]
234pub struct Focus {
235 pub mri: String,
236 pub own: bool,
237 pub spotlight: bool,
238 pub pinned: bool,
239}
240
241#[derive(Debug, Clone, PartialEq, Eq)]
242pub struct CaptionLine {
243 pub id: String,
244 pub speaker: String,
245 pub text: String,
246 pub at: Instant,
247}
248
249#[derive(Debug, Clone, Copy, PartialEq)]
250pub struct TileSize {
251 pub width: f32,
252 pub height: f32,
253 pub avatar: f32,
254}
255
256impl TileSize {
257 pub fn sixteen_by_nine(width: f32) -> TileSize {
258 let height = width * 9. / 16.;
259 TileSize {
260 width,
261 height,
262 avatar: (height * AVATAR_SHARE).clamp(MIN_AVATAR, MAX_AVATAR),
263 }
264 }
265}
266
267#[derive(Debug, Clone, PartialEq, Eq)]
268pub struct ReactionChip {
269 pub mri: String,
270 pub reaction: Reaction,
271 pub since: Instant,
272 pub serial: u64,
273}
274
275#[derive(Debug, Clone)]
276pub struct CallModel {
277 pub title: String,
278 pub kind: CallKind,
279 pub peer_name: String,
280 pub state: CallState,
281 pub progress: Option<Progress>,
282 pub muted: bool,
283 pub listen_only: bool,
284 pub audio_off: bool,
285 pub lobby: bool,
286 pub can_end_meeting: bool,
287 pub incoming: bool,
288 pub input: DeviceChoice,
289 pub output: DeviceChoice,
290 pub devices: DeviceLists,
291 pub local_speaking: bool,
292 pub remote_speaking: bool,
293 pub speaking_mris: Vec<String>,
294 pub connected_since: Option<Instant>,
295 pub own_mri: Option<String>,
296 pub tiles: Vec<Tile>,
297 pub screen_sharer: Option<String>,
298 pub camera_on: bool,
299 pub cameras: Vec<CameraDevice>,
300 pub camera: DeviceChoice,
301 pub local_share: Option<String>,
302 pub share_picker: SharePicker,
303 pub share_kind: Option<ShareKind>,
304 pub share_sources: Vec<ShareSource>,
305 pub share_thumbnails: Vec<(ShareSource, Arc<gpui_kit::RenderImage>)>,
306 pub last_sample: Option<StatsSample>,
307 pub share_sound: bool,
308 pub own_hand: Option<u64>,
309 pub own_spotlight: Option<u64>,
310 pub organizer: bool,
311 pub own_role: Option<MeetingRole>,
312 pub capability: MeetingCapability,
313 pub pinned: Option<String>,
314 pub fitted: HashSet<String>,
315 pub captions: CaptionState,
316 pub caption_lines: Vec<CaptionLine>,
317 pub transcript: Transcript,
318 pub caption_language: Option<String>,
319 language_pending: bool,
320 pub background: BackgroundPick,
321 pub recording: bool,
322 pub recording_audio_only: bool,
323 pub transcribing: bool,
324 pub record_pending: bool,
325 pub recording_policy: RecordingPolicy,
326 pub meeting_tenant: Option<String>,
327 pub own_tenant: Option<String>,
328 pub consent_required: bool,
329 pub hold: HoldState,
330 pub health: HealthState,
331 pub whiteboard: Option<ContentShare>,
332 pub breakout: Option<BreakoutState>,
333 pub main_meeting: Option<MeetingTarget>,
334 pub reactions: Vec<ReactionChip>,
335 reaction_serial: u64,
336 pub meeting_chat: Option<String>,
337 pub view: ViewSettings,
338 pub gallery_page: usize,
339 rotation: VisibleRotation,
340 stage_speaker: Option<String>,
341 recent_speakers: Vec<String>,
342 local_detector: SpeakingDetector,
343 remote_detector: SpeakingDetector,
344}
345
346impl CallModel {
347 fn base(kind: CallKind, title: &str, peer_name: &str, tiles: Vec<Tile>) -> Self {
348 CallModel {
349 title: title.to_owned(),
350 kind,
351 peer_name: peer_name.to_owned(),
352 state: CallState::Connecting,
353 progress: None,
354 muted: false,
355 listen_only: false,
356 audio_off: false,
357 lobby: false,
358 can_end_meeting: false,
359 incoming: false,
360 input: DeviceChoice::SystemDefault,
361 output: DeviceChoice::SystemDefault,
362 devices: DeviceLists::default(),
363 local_speaking: false,
364 remote_speaking: false,
365 speaking_mris: Vec::new(),
366 connected_since: None,
367 own_mri: None,
368 tiles,
369 screen_sharer: None,
370 camera_on: false,
371 cameras: Vec::new(),
372 camera: DeviceChoice::SystemDefault,
373 local_share: None,
374 share_picker: SharePicker::List,
375 share_kind: None,
376 share_sources: Vec::new(),
377 share_thumbnails: Vec::new(),
378 last_sample: None,
379 share_sound: false,
380 own_hand: None,
381 own_spotlight: None,
382 organizer: false,
383 own_role: None,
384 capability: MeetingCapability::default(),
385 pinned: None,
386 fitted: HashSet::new(),
387 captions: CaptionState::Off,
388 caption_lines: Vec::new(),
389 transcript: Transcript::default(),
390 caption_language: None,
391 language_pending: false,
392 background: BackgroundPick::None,
393 recording: false,
394 recording_audio_only: false,
395 transcribing: false,
396 record_pending: false,
397 recording_policy: RecordingPolicy::default(),
398 meeting_tenant: None,
399 own_tenant: None,
400 consent_required: false,
401 hold: HoldState::Active,
402 health: HealthState::default(),
403 whiteboard: None,
404 breakout: None,
405 main_meeting: None,
406 reactions: Vec::new(),
407 reaction_serial: 0,
408 meeting_chat: None,
409 view: ViewSettings::default(),
410 gallery_page: 0,
411 rotation: VisibleRotation::default(),
412 stage_speaker: None,
413 recent_speakers: Vec::new(),
414 local_detector: SpeakingDetector::default(),
415 remote_detector: SpeakingDetector::default(),
416 }
417 }
418
419 pub fn test() -> Self {
420 Self::base(
421 CallKind::Test,
422 TEST_CALL_TITLE,
423 ECHO_NAME,
424 vec![Tile::invited(ECHO_MRI, ECHO_NAME)],
425 )
426 }
427
428 pub fn people(title: &str, callees: &[(String, String)]) -> Self {
429 let kind = if callees.len() == 1 {
430 CallKind::Direct
431 } else {
432 CallKind::Group
433 };
434 let peer_name = match callees {
435 [(_, name)] => name.clone(),
436 _ => title.to_owned(),
437 };
438 let tiles = callees
439 .iter()
440 .map(|(mri, name)| Tile::invited(mri, name))
441 .collect();
442 Self::base(kind, title, &peer_name, tiles)
443 }
444
445 pub fn meeting(title: &str, can_end_meeting: bool) -> Self {
446 let mut model = Self::base(CallKind::Meeting, title, title, Vec::new());
447 model.can_end_meeting = can_end_meeting;
448 model
449 }
450
451 pub fn incoming(title: &str, caller_mri: &str, caller_name: &str) -> Self {
452 let mut model = Self::base(
453 CallKind::Direct,
454 title,
455 caller_name,
456 vec![Tile {
457 state: TileState::Present,
458 ..Tile::invited(caller_mri, caller_name)
459 }],
460 );
461 model.incoming = true;
462 model
463 }
464
465 pub fn apply(&mut self, update: CallUpdate) {
466 match update {
467 CallUpdate::State(state) => {
468 if let Some(since) = state.started_at() {
469 self.connected_since = Some(since);
470 }
471 if !matches!(state, CallState::Connected { .. }) {
472 self.silence();
473 }
474 self.state = state;
475 }
476 CallUpdate::Muted(muted) => {
477 self.muted = muted;
478 if muted {
479 self.local_speaking = false;
480 self.local_detector.reset();
481 }
482 }
483 CallUpdate::Levels { local, remote } => {
484 self.local_speaking = !self.muted && self.local_detector.update(local);
485 self.remote_speaking = self.remote_detector.update(remote);
486 }
487 CallUpdate::Devices(devices) => self.devices = devices,
488 CallUpdate::Selected { input, output } => {
489 self.input = input;
490 self.output = output;
491 }
492 CallUpdate::ListenOnly(listen_only) => self.listen_only = listen_only,
493 CallUpdate::Stats { .. } => {}
494 CallUpdate::Progress(progress) => self.progress = Some(progress),
495 CallUpdate::Roster(entries) => {
496 self.apply_roster(&entries);
497 self.refresh_layout(Instant::now());
498 }
499 CallUpdate::Speakers(mris) => {
500 self.speaking_mris = mris;
501 self.refresh_layout(Instant::now());
502 }
503 CallUpdate::Lobby(lobby) => self.lobby = lobby,
504 CallUpdate::OwnIdentity { mri } => self.own_mri = Some(mri),
505 CallUpdate::ScreenShare(sharer) => self.screen_sharer = sharer,
506 CallUpdate::VideoReady | CallUpdate::VideoStopped(_) | CallUpdate::Notice(_) => {}
507 CallUpdate::Camera(on) => self.camera_on = on,
508 CallUpdate::Cameras(cameras) => self.cameras = cameras,
509 CallUpdate::LocalShare(label) => {
510 if label.is_none() {
511 self.share_sound = false;
512 }
513 self.local_share = label;
514 }
515 CallUpdate::SharePicker(picker) => self.share_picker = picker,
516 CallUpdate::ShareKind(kind) => self.share_kind = kind,
517 CallUpdate::ShareSources(sources) => {
518 self.share_thumbnails.retain(|(source, _)| sources.contains(source));
519 self.share_sources = sources;
520 }
521 CallUpdate::ShareThumbnail { source, picture } => {
522 if let Some(image) = crate::pictures::render_image((*picture).clone()) {
523 self.share_thumbnails.retain(|(known, _)| *known != source);
524 self.share_thumbnails.push((source, image));
525 }
526 }
527 CallUpdate::ShareSound(active) => self.share_sound = active,
528 CallUpdate::OwnHand(rank) => self.own_hand = rank,
529 CallUpdate::Reaction { mri, reaction } => {
530 self.note_reaction(mri, reaction, Instant::now())
531 }
532 CallUpdate::MeetingChat(thread) => self.meeting_chat = Some(thread),
533 CallUpdate::Captions(state) => {
534 if state != CaptionState::On {
535 self.caption_lines.clear();
536 }
537 self.captions = state;
538 }
539 CallUpdate::Caption(entry) => self.note_caption(entry, Instant::now()),
540 CallUpdate::Recording(on) => self.recording = on,
541 CallUpdate::RecordingAudioOnly(audio_only) => self.recording_audio_only = audio_only,
542 CallUpdate::Transcribing(on) => self.transcribing = on,
543 CallUpdate::RecordingPending(pending) => self.record_pending = pending,
544 CallUpdate::MeetingTenant(tenant) => self.meeting_tenant = Some(tenant),
545 CallUpdate::ConsentRequired(required) => self.consent_required = required,
546 CallUpdate::Hold(hold) => self.hold = hold,
547 CallUpdate::Health(health) => self.health.apply(health),
548 CallUpdate::IncomingVideo(enabled) => self.health.incoming_video = enabled,
549 CallUpdate::Whiteboard(share) => self.whiteboard = share,
550 CallUpdate::Capability(capability) => self.capability = capability,
551 CallUpdate::BreakoutRoom { main } => self.main_meeting = Some(main),
552 CallUpdate::Sample(sample) => self.last_sample = Some(sample),
553 CallUpdate::BlurTiming(_)
554 | CallUpdate::Diagnostics(_)
555 | CallUpdate::Organizer { .. }
556 | CallUpdate::MeetingOptions(_)
557 | CallUpdate::MeetingOptionsSaved(_)
558 | CallUpdate::WhiteboardUrl(_)
559 | CallUpdate::BreakoutMove(_)
560 | CallUpdate::ReplacementLink(_)
561 | CallUpdate::TransferResult { .. } => {}
562 }
563 }
564
565 pub fn note_caption(&mut self, entry: CaptionEntry, at: Instant) {
566 if self.captions == CaptionState::Off {
567 return;
568 }
569 let speaker = if entry.display_name.is_empty() {
570 "Someone".to_owned()
571 } else {
572 entry.display_name
573 };
574 let offset = self
575 .connected_since
576 .map_or(Duration::ZERO, |since| at.saturating_duration_since(since));
577 self.transcript.note(TranscriptEntry {
578 id: entry.id.clone(),
579 speaker: speaker.clone(),
580 text: entry.text.clone(),
581 offset,
582 });
583 let line = CaptionLine {
584 id: entry.id,
585 speaker,
586 text: entry.text,
587 at,
588 };
589 match self.caption_lines.last_mut() {
590 Some(last) if last.id == line.id => *last = line,
591 _ => self.caption_lines.push(line),
592 }
593 let surplus = self.caption_lines.len().saturating_sub(CAPTION_LINES);
594 self.caption_lines.drain(..surplus);
595 }
596
597 pub fn visible_captions(&self, now: Instant) -> Vec<&CaptionLine> {
598 self.caption_lines
599 .iter()
600 .filter(|line| now.saturating_duration_since(line.at) < CAPTION_SHOWN)
601 .collect()
602 }
603
604 pub fn choose_caption_language(&mut self, tag: &str) {
605 self.caption_language = Some(tag.to_owned());
606 self.language_pending = true;
607 }
608
609 pub fn take_ready_caption_language(&mut self) -> Option<String> {
610 if self.language_pending && self.captions == CaptionState::On {
611 self.language_pending = false;
612 return self.caption_language.clone();
613 }
614 None
615 }
616
617 pub fn captions_on(&self) -> bool {
618 matches!(self.captions, CaptionState::Starting | CaptionState::On)
619 }
620
621 fn silence(&mut self) {
622 self.local_speaking = false;
623 self.remote_speaking = false;
624 self.speaking_mris.clear();
625 self.local_detector.reset();
626 self.remote_detector.reset();
627 }
628
629 pub fn note_reaction(&mut self, mri: String, reaction: Reaction, at: Instant) {
630 let own_echo = Some(&mri) == self.own_mri.as_ref()
631 && self.reactions.iter().any(|chip| {
632 chip.mri == mri
633 && chip.reaction == reaction
634 && at.saturating_duration_since(chip.since) < OWN_ECHO_WINDOW
635 });
636 if own_echo {
637 return;
638 }
639 self.reactions.retain(|chip| {
640 chip.mri != mri && at.saturating_duration_since(chip.since) < REACTION_SHOWN
641 });
642 self.reaction_serial += 1;
643 self.reactions.push(ReactionChip {
644 mri,
645 reaction,
646 since: at,
647 serial: self.reaction_serial,
648 });
649 }
650
651 pub fn chip_of(&self, mri: &str, now: Instant) -> Option<&ReactionChip> {
652 self.reactions.iter().find(|chip| {
653 chip.mri == mri && now.saturating_duration_since(chip.since) < REACTION_SHOWN
654 })
655 }
656
657 pub fn own_chip(&self, now: Instant) -> Option<&ReactionChip> {
658 self.chip_of(self.own_mri.as_deref()?, now)
659 }
660
661 pub fn hand_position(&self, rank: u64) -> usize {
662 let raised = self
663 .tiles
664 .iter()
665 .filter_map(|tile| tile.hand)
666 .chain(self.own_hand);
667 1 + raised.filter(|other| *other < rank).count()
668 }
669
670 pub fn can_manage(&self) -> bool {
671 self.can_end_meeting || self.organizer
672 }
673
674 pub fn organizes_meeting(&self) -> bool {
675 self.kind == CallKind::Meeting && self.can_manage()
676 }
677
678 pub fn present_others(&self) -> usize {
679 self.tiles
680 .iter()
681 .filter(|tile| tile.state == TileState::Present)
682 .count()
683 }
684
685 pub fn can_invite(&self) -> bool {
686 let open_to_everyone = matches!(self.kind, CallKind::Direct | CallKind::Group);
687 self.is_live() && !self.lobby && (open_to_everyone || self.organizes_meeting())
688 }
689
690 pub fn tile_role(&self, mri: &str) -> Option<MeetingRole> {
691 self.tiles
692 .iter()
693 .find(|tile| tile.mri == mri)
694 .and_then(|tile| tile.role)
695 }
696
697 pub fn can_change_roles(&self, mri: &str) -> bool {
698 self.organizes_meeting() && self.tile_role(mri) != Some(MeetingRole::Organizer)
699 }
700
701 pub fn attendee_allowed(&self, mri: &str, modality: calling::Modality) -> bool {
702 let limits = self
703 .tiles
704 .iter()
705 .find(|tile| tile.mri == mri)
706 .map(|tile| tile.limits.clone())
707 .unwrap_or_default();
708 calling::modality_allowed(modality, self.capability, &limits)
709 }
710
711 pub fn can_lower_hands(&self) -> bool {
712 self.can_manage()
713 }
714
715 pub fn lobby_guests(&self) -> Vec<&Tile> {
716 self.tiles
717 .iter()
718 .filter(|tile| tile.state == TileState::InLobby)
719 .collect()
720 }
721
722 pub fn lobby_mris(&self) -> Vec<String> {
723 self.lobby_guests().into_iter().map(|tile| tile.mri.clone()).collect()
724 }
725
726 pub fn someone_entered_the_lobby(&self, before: &[String]) -> bool {
727 self.can_admit() && self.lobby_guests().iter().any(|tile| !before.contains(&tile.mri))
728 }
729
730 pub fn can_admit(&self) -> bool {
731 self.can_manage() && self.is_live() && !self.lobby
732 }
733
734 pub fn is_pinned(&self, mri: &str) -> bool {
735 self.pinned.as_deref() == Some(mri)
736 }
737
738 pub fn toggle_pin(&mut self, mri: &str) {
739 self.pinned = if self.is_pinned(mri) {
740 None
741 } else {
742 Some(mri.to_owned())
743 };
744 self.refresh_layout(Instant::now());
745 }
746
747 pub fn is_fitted(&self, mri: &str) -> bool {
748 self.fitted.contains(mri)
749 }
750
751 pub fn toggle_fit(&mut self, mri: &str) {
752 if !self.fitted.remove(mri) {
753 self.fitted.insert(mri.to_owned());
754 }
755 }
756
757 pub fn is_spotlighted(&self, mri: &str) -> bool {
758 self.own_mri.as_deref() == Some(mri) && self.own_spotlight.is_some()
759 || self
760 .tiles
761 .iter()
762 .any(|tile| tile.mri == mri && tile.spotlight.is_some())
763 }
764
765 pub fn focus(&self) -> Option<Focus> {
766 let own = |mri: &str| self.own_mri.as_deref() == Some(mri);
767 let on_stage = |mri: &str| {
768 own(mri)
769 || self
770 .visible_tiles()
771 .iter()
772 .any(|tile| tile.mri == mri && tile.state == TileState::Present)
773 };
774 if let Some(pinned) = self.pinned.as_deref().filter(|mri| on_stage(mri)) {
775 return Some(Focus {
776 mri: pinned.to_owned(),
777 own: own(pinned),
778 spotlight: self.is_spotlighted(pinned),
779 pinned: true,
780 });
781 }
782 let remote = self
783 .tiles
784 .iter()
785 .filter(|tile| tile.state == TileState::Present)
786 .filter_map(|tile| Some((tile.spotlight?, tile.mri.as_str())));
787 let (_, mri) = remote
788 .chain(self.own_spotlight.zip(self.own_mri.as_deref()))
789 .min_by_key(|(rank, _)| *rank)?;
790 Some(Focus {
791 mri: mri.to_owned(),
792 own: own(mri),
793 spotlight: true,
794 pinned: false,
795 })
796 }
797
798 pub fn raised_hands(&self) -> usize {
799 self.tiles.iter().filter(|tile| tile.hand.is_some()).count()
800 + usize::from(self.own_hand.is_some())
801 }
802
803 pub fn any_hand_raised(&self) -> bool {
804 self.own_hand.is_some() || self.tiles.iter().any(|tile| tile.hand.is_some())
805 }
806
807 pub fn own_cell_index(&self, remote_cells: usize) -> usize {
808 let Some(own) = self.own_hand else {
809 return remote_cells;
810 };
811 let ahead = self
812 .visible_tiles()
813 .iter()
814 .filter(|tile| tile.hand.is_some_and(|rank| rank < own))
815 .count();
816 ahead.min(remote_cells)
817 }
818
819 fn apply_roster(&mut self, entries: &[RosterEntry]) {
820 let own_entry = entries
821 .iter()
822 .find(|entry| Some(&entry.mri) == self.own_mri.as_ref());
823 if let Some(entry) = own_entry {
824 self.own_hand = entry.hand.as_ref().map(|hand| hand.rank);
825 }
826 self.own_spotlight =
827 own_entry.and_then(|entry| entry.spotlight.as_ref().map(|spotlight| spotlight.rank));
828 if let Some(entry) = own_entry {
829 self.organizer = entry.organizer;
830 self.own_role = entry.role;
831 }
832 for entry in entries
833 .iter()
834 .filter(|entry| Some(&entry.mri) != self.own_mri.as_ref())
835 {
836 let state = if entry.in_lobby {
837 TileState::InLobby
838 } else {
839 TileState::Present
840 };
841 match self.tiles.iter_mut().find(|tile| tile.mri == entry.mri) {
842 Some(tile) => {
843 tile.state = state;
844 tile.muted = entry.muted;
845 tile.has_video = entry.has_video;
846 tile.hand = entry.hand.as_ref().map(|hand| hand.rank);
847 tile.spotlight = entry.spotlight.as_ref().map(|spotlight| spotlight.rank);
848 tile.role = entry.role;
849 tile.limits = entry.limits.clone();
850 if tile.name.is_empty() {
851 tile.name = entry.display_name.clone();
852 }
853 }
854 None if entry.mri.starts_with(BOT_PREFIX) => {}
855 None => self.tiles.push(Tile {
856 mri: entry.mri.clone(),
857 user_id: entry.mri.strip_prefix(ORGID_PREFIX).map(str::to_owned),
858 name: entry.display_name.clone(),
859 muted: entry.muted,
860 state,
861 invited: false,
862 has_video: entry.has_video,
863 hand: entry.hand.as_ref().map(|hand| hand.rank),
864 spotlight: entry.spotlight.as_ref().map(|spotlight| spotlight.rank),
865 role: entry.role,
866 limits: entry.limits.clone(),
867 }),
868 }
869 }
870 if self.kind == CallKind::Direct && self.present_others() > 1 {
871 self.kind = CallKind::Group;
872 }
873 let own_mri = self.own_mri.clone();
874 let listed = |mri: &str| entries.iter().any(|entry| entry.mri == mri);
875 if self
876 .pinned
877 .as_deref()
878 .is_some_and(|mri| !listed(mri) && Some(mri) != own_mri.as_deref())
879 {
880 self.pinned = None;
881 }
882 self.tiles.retain_mut(|tile| {
883 if listed(&tile.mri) || Some(&tile.mri) == own_mri.as_ref() {
884 return true;
885 }
886 match (tile.invited, tile.state) {
887 (true, TileState::Invited) => true,
888 (true, _) => {
889 tile.state = TileState::Left;
890 true
891 }
892 (false, _) => false,
893 }
894 });
895 }
896
897 pub fn visible_tiles(&self) -> Vec<&Tile> {
898 let mut tiles: Vec<&Tile> = self
899 .tiles
900 .iter()
901 .filter(|tile| tile.state != TileState::InLobby)
902 .collect();
903 tiles.sort_by_key(|tile| {
904 let state = match tile.state {
905 TileState::Present => 0,
906 TileState::Invited => 1,
907 _ => 2,
908 };
909 (
910 !self.is_pinned(&tile.mri),
911 tile.hand.is_none(),
912 tile.hand.unwrap_or(0),
913 state,
914 )
915 });
916 tiles
917 }
918
919 pub fn strip_tiles(&self) -> Vec<&Tile> {
920 let mut tiles = self.visible_tiles();
921 tiles.sort_by_key(|tile| {
922 (
923 !self.is_pinned(&tile.mri),
924 tile.hand.is_none(),
925 tile.hand.unwrap_or(0),
926 !self.tile_speaking(tile),
927 )
928 });
929 tiles
930 }
931
932 pub fn has_content(&self) -> bool {
933 self.screen_sharer.is_some() || self.whiteboard.is_some()
934 }
935
936 pub fn effective_layout(&self) -> CallLayout {
937 match self.view.layout {
938 CallLayout::Content if self.has_content() => CallLayout::Content,
939 CallLayout::Content => match self.view.layout_before_content {
940 CallLayout::Content => CallLayout::Gallery,
941 before => before,
942 },
943 layout => layout,
944 }
945 }
946
947 fn is_prioritized(&self, tile: &Tile) -> bool {
948 self.is_pinned(&tile.mri) || tile.spotlight.is_some() || tile.hand.is_some()
949 }
950
951 pub fn hidden_for_no_video(&self, tile: &Tile) -> bool {
952 self.view.hide_no_video
953 && matches!(self.kind, CallKind::Group | CallKind::Meeting)
954 && tile.state == TileState::Present
955 && !tile.has_video
956 && !self.is_pinned(&tile.mri)
957 && !self.tile_speaking(tile)
958 && !self.recent_speakers.contains(&tile.mri)
959 }
960
961 pub fn hidden_without_video(&self) -> usize {
962 self.visible_tiles()
963 .into_iter()
964 .filter(|tile| self.hidden_for_no_video(tile))
965 .count()
966 }
967
968 fn layout_members(&self) -> Vec<&Tile> {
969 let mut tiles: Vec<&Tile> = self
970 .visible_tiles()
971 .into_iter()
972 .filter(|tile| !self.hidden_for_no_video(tile))
973 .collect();
974 tiles.sort_by_key(|tile| !self.is_prioritized(tile));
975 tiles
976 }
977
978 pub fn layout_tiles(&self) -> Vec<&Tile> {
979 let members = self.layout_members();
980 let mut ordered: Vec<&Tile> = self
981 .rotation
982 .order()
983 .iter()
984 .filter_map(|mri| members.iter().find(|tile| &tile.mri == mri).copied())
985 .collect();
986 ordered.extend(
987 members
988 .into_iter()
989 .filter(|tile| !self.rotation.order().contains(&tile.mri)),
990 );
991 ordered
992 }
993
994 pub fn is_recent_speaker(&self, mri: &str) -> bool {
995 self.recent_speakers.iter().any(|recent| recent == mri)
996 }
997
998 pub fn own_cells(&self) -> usize {
999 usize::from(!self.view.hide_me)
1000 }
1001
1002 fn rotation_capacity(&self, others: usize) -> usize {
1003 let cells = match self.effective_layout() {
1004 _ if self.has_content() => return others,
1005 CallLayout::Speaker => FILMSTRIP_MAX,
1006 CallLayout::Gallery | CallLayout::Content => return first_page_size(others, self.own_cells()),
1007 };
1008 split_overflow(others, self.own_cells(), cells).shown
1009 }
1010
1011 pub fn refresh_layout(&mut self, now: Instant) -> bool {
1012 let members: Vec<String> = self
1013 .layout_members()
1014 .iter()
1015 .map(|tile| tile.mri.clone())
1016 .collect();
1017 let priority: Vec<String> = self
1018 .layout_members()
1019 .iter()
1020 .filter(|tile| self.is_prioritized(tile))
1021 .map(|tile| tile.mri.clone())
1022 .collect();
1023 let capacity = self.rotation_capacity(members.len());
1024 let speaking = self.speaking_mris.clone();
1025 let reordered = self
1026 .rotation
1027 .update(now, &members, &priority, &speaking, capacity);
1028 let recent: Vec<String> = self
1029 .tiles
1030 .iter()
1031 .filter(|tile| self.rotation.spoke_within(&tile.mri, now, RECENT_SPEAKER))
1032 .map(|tile| tile.mri.clone())
1033 .collect();
1034 let held = self.stage_speaker.as_deref().is_some_and(|mri| {
1035 members.iter().any(|member| member == mri) && self.rotation.spoke_within(mri, now, SPEAKER_HOLD)
1036 });
1037 let stage_speaker = if held {
1038 self.stage_speaker.clone()
1039 } else {
1040 self.rotation
1041 .steady_speaker(now, &members)
1042 .map(str::to_owned)
1043 .or_else(|| self.stage_speaker.clone().filter(|mri| members.contains(mri)))
1044 };
1045 let changed = reordered || recent != self.recent_speakers || stage_speaker != self.stage_speaker;
1046 self.recent_speakers = recent;
1047 self.stage_speaker = stage_speaker;
1048 changed
1049 }
1050
1051 pub fn speaker_focus(&self) -> Option<Focus> {
1052 if let Some(focus) = self.focus() {
1053 return Some(focus);
1054 }
1055 let tiles = self.layout_tiles();
1056 let spoken = self
1057 .stage_speaker
1058 .as_deref()
1059 .filter(|mri| tiles.iter().any(|tile| tile.mri == *mri))
1060 .or_else(|| {
1061 self.rotation
1062 .last_speaker()
1063 .filter(|mri| tiles.iter().any(|tile| tile.mri == *mri))
1064 })
1065 .or_else(|| tiles.first().map(|tile| tile.mri.as_str()));
1066 let own_mri = self.own_mri.clone().filter(|_| self.own_cells() > 0);
1067 let (mri, own) = match (spoken, own_mri) {
1068 (Some(mri), _) => (mri.to_owned(), false),
1069 (None, Some(own_mri)) => (own_mri, true),
1070 (None, None) => return None,
1071 };
1072 Some(Focus {
1073 mri,
1074 own,
1075 spotlight: false,
1076 pinned: false,
1077 })
1078 }
1079
1080 pub fn sharing_label(&self) -> Option<String> {
1081 let sharer = self.screen_sharer.as_ref()?;
1082 let name = self
1083 .tiles
1084 .iter()
1085 .find(|tile| &tile.mri == sharer)
1086 .map(|tile| tile.name.as_str())
1087 .filter(|name| !name.is_empty())
1088 .unwrap_or("Someone");
1089 Some(format!("{name} is sharing"))
1090 }
1091
1092 pub fn whiteboard_label(&self) -> Option<String> {
1093 let share = self.whiteboard.as_ref()?;
1094 let name = share
1095 .presenter
1096 .as_deref()
1097 .and_then(|presenter| self.tiles.iter().find(|tile| tile.mri == presenter))
1098 .map(|tile| tile.name.as_str())
1099 .filter(|name| !name.is_empty())
1100 .unwrap_or("Someone");
1101 Some(format!("{name} is sharing a whiteboard"))
1102 }
1103
1104 pub fn whiteboard_url(&self) -> Option<&str> {
1105 self.whiteboard.as_ref()?.url.as_deref()
1106 }
1107
1108 pub fn health_banner(&self) -> Option<HealthBanner> {
1109 self.health.banner(self.background != BackgroundPick::None)
1110 }
1111
1112 pub fn is_one_to_one(&self) -> bool {
1113 self.kind == CallKind::Direct
1114 }
1115
1116 pub fn can_hold(&self) -> bool {
1117 self.is_one_to_one() && self.is_live() && self.hold != HoldState::Remote
1118 }
1119
1120 pub fn can_transfer(&self) -> bool {
1121 self.is_one_to_one() && self.is_live() && self.hold == HoldState::Active
1122 }
1123
1124 pub fn can_open_whiteboard(&self) -> bool {
1125 self.kind == CallKind::Meeting && self.is_live() && !self.lobby
1126 }
1127
1128 pub fn tile_speaking(&self, tile: &Tile) -> bool {
1129 if self.speaking_mris.contains(&tile.mri) {
1130 return true;
1131 }
1132 let only_remote = self.tiles.len() == 1;
1133 only_remote && tile.state != TileState::Left && self.remote_speaking
1134 }
1135
1136 pub fn tile_caption(&self, tile: &Tile) -> Option<&'static str> {
1137 match tile.state {
1138 TileState::Invited => Some(match self.progress {
1139 Some(Progress::Ringing) => "Ringing",
1140 _ => "Calling...",
1141 }),
1142 TileState::Left => Some("Left"),
1143 TileState::Present | TileState::InLobby => None,
1144 }
1145 }
1146
1147 pub fn elapsed(&self, now: Instant) -> Option<Duration> {
1148 self.connected_since
1149 .map(|since| now.saturating_duration_since(since))
1150 }
1151
1152 pub fn connecting_text(&self) -> &'static str {
1153 match (self.kind, self.progress) {
1154 (CallKind::Meeting, _) => "Joining...",
1155 (_, _) if self.incoming => "Connecting...",
1156 (_, Some(Progress::Ringing)) => "Ringing",
1157 _ => "Calling...",
1158 }
1159 }
1160
1161 pub fn is_active(&self) -> bool {
1162 matches!(
1163 self.state,
1164 CallState::Connecting | CallState::Connected { .. } | CallState::Reconnecting { .. }
1165 )
1166 }
1167
1168 pub fn is_connecting(&self) -> bool {
1169 matches!(self.state, CallState::Connecting)
1170 }
1171
1172 pub fn is_reconnecting(&self) -> bool {
1173 matches!(self.state, CallState::Reconnecting { .. })
1174 }
1175
1176 pub fn ended_reason(&self) -> Option<&EndReason> {
1177 match &self.state {
1178 CallState::Ended { reason } => Some(reason),
1179 _ => None,
1180 }
1181 }
1182
1183 pub fn timer_text(&self, now: Instant) -> String {
1184 self.elapsed(now).map(format_elapsed).unwrap_or_default()
1185 }
1186
1187 pub fn has_reaction_controls(&self) -> bool {
1188 matches!(self.kind, CallKind::Group | CallKind::Meeting)
1189 }
1190
1191 pub fn can_react(&self) -> bool {
1192 self.is_live() && !self.lobby
1193 }
1194
1195 pub fn can_use_camera(&self) -> bool {
1196 !self.cameras.is_empty()
1197 }
1198
1199 pub fn can_share(&self) -> bool {
1200 self.is_live() && (self.uses_portal_picker() || !self.share_sources.is_empty())
1201 }
1202
1203 pub fn uses_portal_picker(&self) -> bool {
1204 self.share_picker == SharePicker::Portal
1205 }
1206
1207 pub fn is_live(&self) -> bool {
1208 matches!(
1209 self.state,
1210 CallState::Connected { .. } | CallState::Reconnecting { .. }
1211 )
1212 }
1213
1214 pub fn screens(&self) -> Vec<&ShareSource> {
1215 self.share_sources
1216 .iter()
1217 .filter(|source| source.kind == ShareKind::Screen)
1218 .collect()
1219 }
1220
1221 pub fn share_thumbnail(&self, source: &ShareSource) -> Option<Arc<gpui_kit::RenderImage>> {
1222 self.share_thumbnails
1223 .iter()
1224 .find(|(known, _)| known == source)
1225 .map(|(_, image)| image.clone())
1226 }
1227
1228 pub fn windows(&self) -> Vec<&ShareSource> {
1229 self.share_sources
1230 .iter()
1231 .filter(|source| source.kind == ShareKind::Window)
1232 .collect()
1233 }
1234
1235 pub fn can_unmute(&self) -> bool {
1236 !self.listen_only && !self.audio_off
1237 }
1238}
1239
1240pub fn format_elapsed(elapsed: Duration) -> String {
1241 let seconds = elapsed.as_secs();
1242 let (hours, minutes, seconds) = (seconds / 3600, seconds / 60 % 60, seconds % 60);
1243 if hours > 0 {
1244 format!("{hours}:{minutes:02}:{seconds:02}")
1245 } else {
1246 format!("{minutes:02}:{seconds:02}")
1247 }
1248}
1249
1250pub fn ended_notice(reason: &EndReason, elapsed: Option<Duration>, peer_name: &str) -> String {
1251 let ended = || match elapsed {
1252 Some(elapsed) => format!("Call ended {}", format_elapsed(elapsed)),
1253 None => "Call ended".to_owned(),
1254 };
1255 match reason {
1256 EndReason::Cancelled => "Call cancelled".to_owned(),
1257 EndReason::Dropped => "Call dropped".to_owned(),
1258 EndReason::Failed(message) => format!("Call failed: {message}"),
1259 EndReason::LocalHangup => ended(),
1260 EndReason::Remote(EndKind::Declined) => format!("{peer_name} declined"),
1261 EndReason::Remote(EndKind::NoAnswer) => "No answer".to_owned(),
1262 EndReason::Remote(EndKind::Unavailable) => format!("{peer_name} is not available"),
1263 EndReason::Remote(_) => ended(),
1264 }
1265}
1266
1267#[cfg(test)]
1268mod tests {
1269 use super::*;
1270
1271 fn connected_model() -> CallModel {
1272 let mut model = CallModel::test();
1273 model.apply(CallUpdate::State(CallState::Connected {
1274 since: Instant::now(),
1275 }));
1276 model
1277 }
1278
1279 fn entry(mri: &str, name: &str, muted: bool, in_lobby: bool) -> RosterEntry {
1280 RosterEntry {
1281 mri: mri.into(),
1282 display_name: name.into(),
1283 muted,
1284 in_lobby,
1285 has_video: false,
1286 sharing: false,
1287 hand: None,
1288 spotlight: None,
1289 organizer: false,
1290 role: None,
1291 limits: AttendeeLimits::default(),
1292 }
1293 }
1294
1295 fn spotlit(mri: &str, name: &str, rank: u64) -> RosterEntry {
1296 RosterEntry {
1297 spotlight: Some(calling::Spotlight {
1298 state_id: format!("sp-{rank}"),
1299 rank,
1300 }),
1301 ..entry(mri, name, false, false)
1302 }
1303 }
1304
1305 fn organizer_entry(mri: &str) -> RosterEntry {
1306 RosterEntry {
1307 organizer: true,
1308 ..entry(mri, "Me", false, false)
1309 }
1310 }
1311
1312 fn raised(mri: &str, name: &str, rank: u64) -> RosterEntry {
1313 RosterEntry {
1314 hand: Some(calling::RaisedHand {
1315 state_id: format!("s-{rank}"),
1316 rank,
1317 }),
1318 ..entry(mri, name, false, false)
1319 }
1320 }
1321
1322 fn meeting_with_me() -> CallModel {
1323 let mut model = CallModel::meeting("Standup", false);
1324 model.apply(CallUpdate::OwnIdentity {
1325 mri: "8:orgid:me".into(),
1326 });
1327 model
1328 }
1329
1330 #[test]
1331 fn elapsed_text_is_minutes_and_seconds() {
1332 assert_eq!(format_elapsed(Duration::from_secs(42)), "00:42");
1333 assert_eq!(format_elapsed(Duration::from_secs(61)), "01:01");
1334 assert_eq!(format_elapsed(Duration::from_secs(3725)), "1:02:05");
1335 }
1336
1337 #[test]
1338 fn levels_drive_the_speaking_rings() {
1339 let mut model = connected_model();
1340 model.apply(CallUpdate::Levels {
1341 local: 0.0,
1342 remote: 0.4,
1343 });
1344 assert!(model.remote_speaking);
1345 assert!(!model.local_speaking);
1346 model.apply(CallUpdate::Levels {
1347 local: 0.4,
1348 remote: 0.0,
1349 });
1350 assert!(model.local_speaking);
1351 }
1352
1353 #[test]
1354 fn muting_switches_the_local_ring_off_at_once() {
1355 let mut model = connected_model();
1356 model.apply(CallUpdate::Levels {
1357 local: 0.5,
1358 remote: 0.0,
1359 });
1360 assert!(model.local_speaking);
1361 model.apply(CallUpdate::Muted(true));
1362 assert!(!model.local_speaking);
1363 model.apply(CallUpdate::Levels {
1364 local: 0.5,
1365 remote: 0.0,
1366 });
1367 assert!(!model.local_speaking);
1368 }
1369
1370 #[test]
1371 fn reconnecting_keeps_the_timer_and_clears_the_rings() {
1372 let mut model = connected_model();
1373 let since = model.connected_since.unwrap();
1374 model.apply(CallUpdate::Levels {
1375 local: 0.5,
1376 remote: 0.5,
1377 });
1378 model.apply(CallUpdate::State(CallState::Reconnecting { since }));
1379 assert!(model.is_reconnecting());
1380 assert_eq!(model.connected_since, Some(since));
1381 assert!(!model.remote_speaking && !model.local_speaking);
1382 }
1383
1384 #[test]
1385 fn notices_for_every_end_reason() {
1386 let elapsed = Some(Duration::from_secs(42));
1387 let notice = |reason: EndReason, elapsed| ended_notice(&reason, elapsed, "Bea");
1388 assert_eq!(notice(EndReason::LocalHangup, elapsed), "Call ended 00:42");
1389 assert_eq!(
1390 notice(EndReason::Remote(EndKind::Normal), elapsed),
1391 "Call ended 00:42"
1392 );
1393 assert_eq!(
1394 notice(EndReason::Remote(EndKind::Normal), None),
1395 "Call ended"
1396 );
1397 assert_eq!(notice(EndReason::Cancelled, None), "Call cancelled");
1398 assert_eq!(notice(EndReason::Dropped, elapsed), "Call dropped");
1399 assert_eq!(
1400 notice(EndReason::Failed("no route".into()), None),
1401 "Call failed: no route"
1402 );
1403 assert_eq!(
1404 notice(EndReason::Remote(EndKind::Declined), None),
1405 "Bea declined"
1406 );
1407 assert_eq!(
1408 notice(EndReason::Remote(EndKind::NoAnswer), None),
1409 "No answer"
1410 );
1411 assert_eq!(
1412 notice(EndReason::Remote(EndKind::Unavailable), None),
1413 "Bea is not available"
1414 );
1415 assert_eq!(
1416 notice(EndReason::Remote(EndKind::Cancelled), None),
1417 "Call ended"
1418 );
1419 assert_eq!(
1420 notice(EndReason::Remote(EndKind::Other), None),
1421 "Call ended"
1422 );
1423 assert_eq!(
1424 notice(EndReason::Remote(EndKind::AnsweredElsewhere), None),
1425 "Call ended"
1426 );
1427 }
1428
1429 #[test]
1430 fn the_connecting_text_follows_the_kind_of_call() {
1431 let mut direct = CallModel::people("Bea", &[("8:orgid:b".into(), "Bea".into())]);
1432 assert_eq!(direct.connecting_text(), "Calling...");
1433 direct.apply(CallUpdate::Progress(Progress::Ringing));
1434 assert_eq!(direct.connecting_text(), "Ringing");
1435 assert_eq!(
1436 CallModel::meeting("Standup", false).connecting_text(),
1437 "Joining..."
1438 );
1439 assert_eq!(
1440 CallModel::incoming("Bea", "8:orgid:b", "Bea").connecting_text(),
1441 "Connecting..."
1442 );
1443 assert_eq!(CallModel::test().connecting_text(), "Calling...");
1444 }
1445
1446 #[test]
1447 fn listen_only_blocks_unmuting() {
1448 let mut model = connected_model();
1449 assert!(model.can_unmute());
1450 model.apply(CallUpdate::ListenOnly(true));
1451 assert!(!model.can_unmute());
1452 }
1453
1454 #[test]
1455 fn a_call_without_audio_blocks_unmuting() {
1456 let mut model = connected_model();
1457 model.audio_off = true;
1458 assert!(!model.can_unmute());
1459 }
1460
1461 #[test]
1462 fn callees_start_invited_and_follow_the_progress() {
1463 let mut model = CallModel::people("Bea", &[("8:orgid:b".into(), "Bea".into())]);
1464 assert_eq!(model.kind, CallKind::Direct);
1465 assert_eq!(model.peer_name, "Bea");
1466 assert_eq!(model.tile_caption(&model.tiles[0]), Some("Calling..."));
1467 model.apply(CallUpdate::Progress(Progress::Ringing));
1468 assert_eq!(model.tile_caption(&model.tiles[0]), Some("Ringing"));
1469 model.apply(CallUpdate::Roster(vec![entry(
1470 "8:orgid:b",
1471 "Bea",
1472 false,
1473 false,
1474 )]));
1475 assert_eq!(model.tiles[0].state, TileState::Present);
1476 assert_eq!(model.tile_caption(&model.tiles[0]), None);
1477 }
1478
1479 #[test]
1480 fn several_callees_make_a_group_call_named_after_the_chat() {
1481 let model = CallModel::people(
1482 "Retro team",
1483 &[
1484 ("8:orgid:b".into(), "Bea".into()),
1485 ("8:orgid:c".into(), "Cy".into()),
1486 ],
1487 );
1488 assert_eq!(model.kind, CallKind::Group);
1489 assert_eq!(model.peer_name, "Retro team");
1490 assert_eq!(model.tiles.len(), 2);
1491 }
1492
1493 #[test]
1494 fn roster_adds_guests_updates_mute_and_drops_leavers() {
1495 let mut model = meeting_with_me();
1496 model.apply(CallUpdate::Roster(vec![
1497 entry("8:orgid:me", "Me", false, false),
1498 entry("8:orgid:a", "Ana", true, false),
1499 entry("8:orgid:b", "Bo", false, false),
1500 ]));
1501 assert_eq!(model.tiles.len(), 2);
1502 assert!(
1503 model
1504 .tiles
1505 .iter()
1506 .find(|tile| tile.name == "Ana")
1507 .unwrap()
1508 .muted
1509 );
1510 model.apply(CallUpdate::Roster(vec![
1511 entry("8:orgid:me", "Me", false, false),
1512 entry("8:orgid:b", "Bo", false, false),
1513 ]));
1514 assert_eq!(model.tiles.len(), 1);
1515 assert_eq!(model.tiles[0].name, "Bo");
1516 }
1517
1518 #[test]
1519 fn meeting_bots_get_no_tile_but_the_called_echo_bot_keeps_its_own() {
1520 let mut model = meeting_with_me();
1521 model.apply(CallUpdate::Roster(vec![
1522 entry("8:orgid:me", "Me", false, false),
1523 entry("8:orgid:a", "Ana", false, false),
1524 entry("28:bdd75849-e0a6-4cce-8fc1-d7c0d4da43e5", "", false, false),
1525 ]));
1526 let names: Vec<&str> = model.strip_tiles().iter().map(|tile| tile.name.as_str()).collect();
1527 assert_eq!(names, vec!["Ana"]);
1528 assert_eq!(model.present_others(), 1);
1529 let mut echo = CallModel::people(ECHO_NAME, &[(ECHO_MRI.into(), ECHO_NAME.into())]);
1530 echo.apply(CallUpdate::Roster(vec![entry(ECHO_MRI, "", false, false)]));
1531 assert_eq!(echo.tiles.len(), 1);
1532 assert_eq!(echo.tiles[0].state, TileState::Present);
1533 }
1534
1535 #[test]
1536 fn an_invited_callee_who_leaves_stays_as_left() {
1537 let mut model = CallModel::people("Bea", &[("8:orgid:b".into(), "Bea".into())]);
1538 model.apply(CallUpdate::Roster(vec![entry(
1539 "8:orgid:b",
1540 "Bea",
1541 false,
1542 false,
1543 )]));
1544 model.apply(CallUpdate::Roster(Vec::new()));
1545 assert_eq!(model.tiles[0].state, TileState::Left);
1546 assert_eq!(model.tile_caption(&model.tiles[0]), Some("Left"));
1547 }
1548
1549 #[test]
1550 fn lobby_guests_get_no_tile() {
1551 let mut model = meeting_with_me();
1552 model.apply(CallUpdate::Roster(vec![
1553 entry("8:orgid:a", "Ana", false, false),
1554 entry("8:orgid:g", "Guest", false, true),
1555 ]));
1556 let names: Vec<&str> = model
1557 .visible_tiles()
1558 .iter()
1559 .map(|tile| tile.name.as_str())
1560 .collect();
1561 assert_eq!(names, vec!["Ana"]);
1562 }
1563
1564 #[test]
1565 fn the_lobby_flag_follows_the_call() {
1566 let mut model = meeting_with_me();
1567 model.apply(CallUpdate::Lobby(true));
1568 assert!(model.lobby);
1569 model.apply(CallUpdate::Lobby(false));
1570 assert!(!model.lobby);
1571 }
1572
1573 #[test]
1574 fn speakers_light_their_own_tile_and_a_lone_remote_follows_the_level() {
1575 let mut model = meeting_with_me();
1576 model.apply(CallUpdate::Roster(vec![
1577 entry("8:orgid:a", "Ana", false, false),
1578 entry("8:orgid:b", "Bo", false, false),
1579 ]));
1580 model.apply(CallUpdate::State(CallState::Connected {
1581 since: Instant::now(),
1582 }));
1583 model.apply(CallUpdate::Speakers(vec!["8:orgid:b".into()]));
1584 let tiles: Vec<Tile> = model.tiles.clone();
1585 assert!(!model.tile_speaking(&tiles[0]));
1586 assert!(model.tile_speaking(&tiles[1]));
1587 let mut lone = CallModel::people("Bea", &[("8:orgid:b".into(), "Bea".into())]);
1588 lone.apply(CallUpdate::State(CallState::Connected {
1589 since: Instant::now(),
1590 }));
1591 lone.apply(CallUpdate::Levels {
1592 local: 0.0,
1593 remote: 0.5,
1594 });
1595 assert!(lone.tile_speaking(&lone.tiles[0].clone()));
1596 }
1597
1598 fn crowd(count: usize) -> CallModel {
1599 let mut model = meeting_with_me();
1600 model.apply(CallUpdate::Roster(
1601 (0..count)
1602 .map(|index| {
1603 entry(
1604 &format!("8:orgid:p{index}"),
1605 &format!("P{index}"),
1606 false,
1607 false,
1608 )
1609 })
1610 .collect(),
1611 ));
1612 model
1613 }
1614
1615 fn shown_mris(model: &CallModel) -> Vec<String> {
1616 model
1617 .layout_tiles()
1618 .iter()
1619 .map(|tile| tile.mri.clone())
1620 .collect()
1621 }
1622
1623 #[test]
1624 fn fit_to_frame_is_per_tile_and_toggles_back_to_fill() {
1625 let mut model = meeting_with_me();
1626 assert!(!model.is_fitted("8:orgid:a"));
1627 model.toggle_fit("8:orgid:a");
1628 assert!(model.is_fitted("8:orgid:a"));
1629 assert!(!model.is_fitted("8:orgid:b"));
1630 model.toggle_fit("8:orgid:a");
1631 assert!(!model.is_fitted("8:orgid:a"));
1632 }
1633
1634 #[test]
1635 fn hiding_people_without_video_keeps_speakers_and_the_pinned_person() {
1636 let mut model = meeting_with_me();
1637 model.apply(CallUpdate::Roster(vec![
1638 entry("8:orgid:a", "Ana", false, false),
1639 RosterEntry {
1640 has_video: true,
1641 ..entry("8:orgid:b", "Bo", false, false)
1642 },
1643 entry("8:orgid:c", "Cy", false, false),
1644 ]));
1645 model.view.hide_no_video = true;
1646 assert_eq!(model.hidden_without_video(), 2);
1647 assert_eq!(shown_mris(&model), vec!["8:orgid:b"]);
1648 model.apply(CallUpdate::Speakers(vec!["8:orgid:a".into()]));
1649 assert_eq!(model.hidden_without_video(), 1);
1650 assert!(shown_mris(&model).contains(&"8:orgid:a".to_owned()));
1651 model.toggle_pin("8:orgid:c");
1652 assert_eq!(model.hidden_without_video(), 0);
1653 }
1654
1655 #[test]
1656 fn people_without_video_stay_in_one_to_one_calls() {
1657 let mut model = CallModel::people("Bea", &[("8:orgid:b".into(), "Bea".into())]);
1658 model.view.hide_no_video = true;
1659 model.apply(CallUpdate::Roster(vec![entry(
1660 "8:orgid:b",
1661 "Bea",
1662 false,
1663 false,
1664 )]));
1665 assert_eq!(model.hidden_without_video(), 0);
1666 }
1667
1668 #[test]
1669 fn focus_on_content_falls_back_to_the_previous_layout_when_the_share_ends() {
1670 let mut model = meeting_with_me();
1671 model.view.choose(CallLayout::Speaker);
1672 model.view.choose(CallLayout::Content);
1673 assert_eq!(model.effective_layout(), CallLayout::Speaker);
1674 model.apply(CallUpdate::ScreenShare(Some("8:orgid:a".into())));
1675 assert_eq!(model.effective_layout(), CallLayout::Content);
1676 model.apply(CallUpdate::ScreenShare(None));
1677 assert_eq!(model.effective_layout(), CallLayout::Speaker);
1678 }
1679
1680 #[test]
1681 fn the_speaker_stage_follows_the_active_speaker_and_keeps_the_last_one() {
1682 let mut model = crowd(3);
1683 model.apply(CallUpdate::Speakers(vec!["8:orgid:p1".into()]));
1684 assert_eq!(model.speaker_focus().unwrap().mri, "8:orgid:p1");
1685 model.apply(CallUpdate::Speakers(Vec::new()));
1686 assert_eq!(model.speaker_focus().unwrap().mri, "8:orgid:p1");
1687 model.toggle_pin("8:orgid:p2");
1688 let focus = model.speaker_focus().unwrap();
1689 assert_eq!((focus.mri.as_str(), focus.pinned), ("8:orgid:p2", true));
1690 }
1691
1692 #[test]
1693 fn a_pinned_person_outside_the_grid_moves_into_it() {
1694 let mut model = crowd(12);
1695 let grid = first_page_size(12, 1);
1696 assert_eq!(grid, 8);
1697 assert!(!shown_mris(&model)[..grid].contains(&"8:orgid:p11".to_owned()));
1698 model.toggle_pin("8:orgid:p11");
1699 assert!(shown_mris(&model)[..grid].contains(&"8:orgid:p11".to_owned()));
1700 assert_eq!(model.layout_tiles().len(), 12);
1701 }
1702
1703 #[test]
1704 fn hiding_me_frees_a_grid_cell() {
1705 let mut model = crowd(12);
1706 assert_eq!(model.own_cells(), 1);
1707 model.view.hide_me = true;
1708 assert_eq!(model.own_cells(), 0);
1709 assert_eq!(first_page_size(12, model.own_cells()), 9);
1710 }
1711
1712 #[test]
1713 fn the_stage_label_names_the_sharer_and_the_strip_puts_the_speaker_first() {
1714 let mut model = meeting_with_me();
1715 model.apply(CallUpdate::Roster(vec![
1716 entry("8:orgid:a", "Ana", false, false),
1717 entry("8:orgid:b", "Bo", false, false),
1718 ]));
1719 assert_eq!(model.sharing_label(), None);
1720 model.apply(CallUpdate::ScreenShare(Some("8:orgid:b".into())));
1721 assert_eq!(model.sharing_label().as_deref(), Some("Bo is sharing"));
1722 model.apply(CallUpdate::State(CallState::Connected {
1723 since: Instant::now(),
1724 }));
1725 model.apply(CallUpdate::Speakers(vec!["8:orgid:b".into()]));
1726 let names: Vec<&str> = model
1727 .strip_tiles()
1728 .iter()
1729 .map(|tile| tile.name.as_str())
1730 .collect();
1731 assert_eq!(names, vec!["Bo", "Ana"]);
1732 model.apply(CallUpdate::ScreenShare(None));
1733 assert_eq!(model.sharing_label(), None);
1734 }
1735
1736 #[test]
1737 fn roster_entries_carry_the_camera_flag_to_the_tile() {
1738 let mut model = meeting_with_me();
1739 let mut with_camera = entry("8:orgid:a", "Ana", false, false);
1740 with_camera.has_video = true;
1741 model.apply(CallUpdate::Roster(vec![with_camera]));
1742 assert!(model.tiles[0].has_video);
1743 model.apply(CallUpdate::Roster(vec![entry(
1744 "8:orgid:a",
1745 "Ana",
1746 false,
1747 false,
1748 )]));
1749 assert!(!model.tiles[0].has_video);
1750 }
1751
1752 #[test]
1753 fn present_guests_sort_before_waiting_ones() {
1754 let mut model = CallModel::people(
1755 "Group",
1756 &[
1757 ("8:orgid:b".into(), "Bea".into()),
1758 ("8:orgid:c".into(), "Cy".into()),
1759 ],
1760 );
1761 model.apply(CallUpdate::Roster(vec![entry(
1762 "8:orgid:c",
1763 "Cy",
1764 false,
1765 false,
1766 )]));
1767 let names: Vec<&str> = model
1768 .visible_tiles()
1769 .iter()
1770 .map(|tile| tile.name.as_str())
1771 .collect();
1772 assert_eq!(names, vec!["Cy", "Bea"]);
1773 }
1774
1775 #[test]
1776 fn raised_hands_get_queue_positions_by_raise_time_and_sort_first() {
1777 let mut model = meeting_with_me();
1778 model.apply(CallUpdate::Roster(vec![
1779 entry("8:orgid:a", "Ana", false, false),
1780 raised("8:orgid:b", "Bo", 9),
1781 raised("8:orgid:c", "Cy", 4),
1782 raised("8:orgid:me", "Me", 6),
1783 ]));
1784 assert_eq!(model.own_hand, Some(6));
1785 assert!(model.any_hand_raised());
1786 let names: Vec<&str> = model
1787 .visible_tiles()
1788 .iter()
1789 .map(|tile| tile.name.as_str())
1790 .collect();
1791 assert_eq!(names, vec!["Cy", "Bo", "Ana"]);
1792 let positions: Vec<usize> = [4, 6, 9]
1793 .into_iter()
1794 .map(|rank| model.hand_position(rank))
1795 .collect();
1796 assert_eq!(positions, vec![1, 2, 3]);
1797 assert_eq!(model.own_cell_index(3), 1);
1798 let strip: Vec<&str> = model
1799 .strip_tiles()
1800 .iter()
1801 .map(|tile| tile.name.as_str())
1802 .collect();
1803 assert_eq!(strip, vec!["Cy", "Bo", "Ana"]);
1804 }
1805
1806 #[test]
1807 fn a_roster_without_the_own_entry_keeps_the_own_hand() {
1808 let mut model = meeting_with_me();
1809 model.apply(CallUpdate::OwnHand(Some(5)));
1810 model.apply(CallUpdate::Roster(vec![entry(
1811 "8:orgid:a",
1812 "Ana",
1813 false,
1814 false,
1815 )]));
1816 assert_eq!(model.own_hand, Some(5));
1817 model.apply(CallUpdate::Roster(vec![entry(
1818 "8:orgid:me",
1819 "Me",
1820 false,
1821 false,
1822 )]));
1823 assert_eq!(model.own_hand, None);
1824 }
1825
1826 #[test]
1827 fn reaction_controls_show_in_group_calls_and_meetings_only() {
1828 let mut model = CallModel::test();
1829 for (kind, expected) in [
1830 (CallKind::Test, false),
1831 (CallKind::Direct, false),
1832 (CallKind::Group, true),
1833 (CallKind::Meeting, true),
1834 ] {
1835 model.kind = kind;
1836 assert_eq!(model.has_reaction_controls(), expected);
1837 }
1838 }
1839
1840 #[test]
1841 fn the_server_echo_of_an_own_reaction_does_not_restart_the_chip() {
1842 let mut model = meeting_with_me();
1843 let start = Instant::now();
1844 model.note_reaction("8:orgid:me".into(), Reaction::Like, start);
1845 let serial = model.reactions[0].serial;
1846 model.note_reaction(
1847 "8:orgid:me".into(),
1848 Reaction::Like,
1849 start + Duration::from_millis(1500),
1850 );
1851 assert_eq!(model.reactions.len(), 1);
1852 assert_eq!(model.reactions[0].serial, serial);
1853 model.note_reaction(
1854 "8:orgid:me".into(),
1855 Reaction::Heart,
1856 start + Duration::from_millis(1600),
1857 );
1858 assert_eq!(model.reactions[0].reaction, Reaction::Heart);
1859 model.note_reaction(
1860 "8:orgid:me".into(),
1861 Reaction::Heart,
1862 start + Duration::from_secs(4),
1863 );
1864 assert_ne!(model.reactions[0].serial, serial);
1865 }
1866
1867 #[test]
1868 fn another_persons_repeated_reaction_restarts_the_chip() {
1869 let mut model = meeting_with_me();
1870 let start = Instant::now();
1871 model.note_reaction("8:orgid:a".into(), Reaction::Like, start);
1872 let serial = model.reactions[0].serial;
1873 model.note_reaction(
1874 "8:orgid:a".into(),
1875 Reaction::Like,
1876 start + Duration::from_secs(1),
1877 );
1878 assert_ne!(model.reactions[0].serial, serial);
1879 }
1880
1881 #[test]
1882 fn lowering_clears_the_hand_everywhere() {
1883 let mut model = meeting_with_me();
1884 model.apply(CallUpdate::Roster(vec![
1885 raised("8:orgid:a", "Ana", 1),
1886 raised("8:orgid:me", "Me", 2),
1887 ]));
1888 model.apply(CallUpdate::Roster(vec![
1889 entry("8:orgid:a", "Ana", false, false),
1890 entry("8:orgid:me", "Me", false, false),
1891 ]));
1892 assert!(!model.any_hand_raised());
1893 assert_eq!(model.own_cell_index(1), 1);
1894 }
1895
1896 #[test]
1897 fn only_organizers_may_lower_hands() {
1898 assert!(!CallModel::meeting("Standup", false).can_lower_hands());
1899 assert!(CallModel::meeting("Standup", true).can_lower_hands());
1900 }
1901
1902 #[test]
1903 fn a_reaction_shows_for_three_seconds_on_its_sender_and_the_latest_wins() {
1904 let mut model = meeting_with_me();
1905 let start = Instant::now();
1906 model.note_reaction("8:orgid:a".into(), Reaction::Heart, start);
1907 model.note_reaction("8:orgid:me".into(), Reaction::Like, start);
1908 let reaction_at = |model: &CallModel, mri: &str, seconds: u64| {
1909 model
1910 .chip_of(mri, start + Duration::from_secs(seconds))
1911 .map(|chip| chip.reaction.clone())
1912 };
1913 assert_eq!(reaction_at(&model, "8:orgid:a", 2), Some(Reaction::Heart));
1914 assert_eq!(
1915 model
1916 .own_chip(start + Duration::from_secs(2))
1917 .map(|chip| chip.reaction.clone()),
1918 Some(Reaction::Like)
1919 );
1920 assert_eq!(reaction_at(&model, "8:orgid:a", 3), None);
1921 model.note_reaction(
1922 "8:orgid:a".into(),
1923 Reaction::Laugh,
1924 start + Duration::from_secs(1),
1925 );
1926 assert_eq!(reaction_at(&model, "8:orgid:a", 2), Some(Reaction::Laugh));
1927 assert_eq!(model.reactions.len(), 2);
1928 }
1929
1930 #[test]
1931 fn the_chat_panel_picks_the_meeting_thread_or_the_call_chat() {
1932 assert_eq!(
1933 chat_thread(CallKind::Meeting, Some("19:meeting_x"), Some("19:list")),
1934 Some("19:meeting_x")
1935 );
1936 assert_eq!(
1937 chat_thread(CallKind::Meeting, None, Some("19:list")),
1938 Some("19:list")
1939 );
1940 assert_eq!(
1941 chat_thread(CallKind::Direct, Some("19:meeting_x"), Some("19:dm")),
1942 Some("19:dm")
1943 );
1944 assert_eq!(
1945 chat_thread(CallKind::Group, None, Some("19:group")),
1946 Some("19:group")
1947 );
1948 assert_eq!(chat_thread(CallKind::Test, None, None), None);
1949 }
1950
1951 #[test]
1952 fn computer_sound_follows_the_share() {
1953 let mut model = connected_model();
1954 model.apply(CallUpdate::LocalShare(Some("Screen".into())));
1955 model.apply(CallUpdate::ShareSound(true));
1956 assert!(model.share_sound);
1957 model.apply(CallUpdate::LocalShare(None));
1958 assert!(!model.share_sound);
1959 }
1960
1961 #[test]
1962 fn portal_share_works_without_a_source_list() {
1963 let mut model = connected_model();
1964 assert!(model.share_sources.is_empty());
1965 assert!(!model.can_share());
1966 model.apply(CallUpdate::SharePicker(SharePicker::Portal));
1967 assert!(model.uses_portal_picker());
1968 assert!(model.can_share());
1969 }
1970
1971 #[test]
1972 fn lobby_guests_are_listed_for_organizers_who_may_admit() {
1973 let mut model = meeting_with_me();
1974 model.apply(CallUpdate::State(CallState::Connected {
1975 since: Instant::now(),
1976 }));
1977 model.apply(CallUpdate::Roster(vec![
1978 entry("8:orgid:a", "Ana", false, false),
1979 entry("8:orgid:g1", "Gast Eins", false, true),
1980 entry("8:orgid:g2", "Gast Zwei", false, true),
1981 ]));
1982 let waiting: Vec<&str> = model
1983 .lobby_guests()
1984 .iter()
1985 .map(|tile| tile.name.as_str())
1986 .collect();
1987 assert_eq!(waiting, vec!["Gast Eins", "Gast Zwei"]);
1988 assert!(!model.can_admit());
1989 model.apply(CallUpdate::Roster(vec![
1990 organizer_entry("8:orgid:me"),
1991 entry("8:orgid:g1", "Gast Eins", false, true),
1992 ]));
1993 assert!(model.organizer && model.can_admit() && model.organizes_meeting());
1994 let mut owner = CallModel::meeting("Standup", true);
1995 owner.apply(CallUpdate::State(CallState::Connected {
1996 since: Instant::now(),
1997 }));
1998 assert!(owner.can_admit());
1999 owner.apply(CallUpdate::Lobby(true));
2000 assert!(!owner.can_admit());
2001 }
2002
2003 #[test]
2004 fn only_a_new_lobby_guest_counts_as_an_arrival_for_an_admitting_organizer() {
2005 let mut owner = CallModel::meeting("Standup", true);
2006 owner.apply(CallUpdate::State(CallState::Connected {
2007 since: Instant::now(),
2008 }));
2009 let empty = owner.lobby_mris();
2010 owner.apply(CallUpdate::Roster(vec![entry("8:orgid:g1", "Gast Eins", false, true)]));
2011 assert!(owner.someone_entered_the_lobby(&empty));
2012 let waiting = owner.lobby_mris();
2013 assert!(!owner.someone_entered_the_lobby(&waiting));
2014 let mut guest = meeting_with_me();
2015 guest.apply(CallUpdate::Roster(vec![entry("8:orgid:g1", "Gast Eins", false, true)]));
2016 assert!(!guest.someone_entered_the_lobby(&empty));
2017 }
2018
2019 #[test]
2020 fn a_spotlight_takes_the_stage_and_the_lowest_rank_wins() {
2021 let mut model = meeting_with_me();
2022 model.apply(CallUpdate::Roster(vec![
2023 entry("8:orgid:a", "Ana", false, false),
2024 spotlit("8:orgid:b", "Bo", 4),
2025 spotlit("8:orgid:c", "Cy", 2),
2026 ]));
2027 assert_eq!(
2028 model.focus(),
2029 Some(Focus {
2030 mri: "8:orgid:c".into(),
2031 own: false,
2032 spotlight: true,
2033 pinned: false
2034 })
2035 );
2036 assert!(model.is_spotlighted("8:orgid:b") && !model.is_spotlighted("8:orgid:a"));
2037 model.apply(CallUpdate::Roster(vec![
2038 entry("8:orgid:a", "Ana", false, false),
2039 spotlit("8:orgid:b", "Bo", 4),
2040 entry("8:orgid:c", "Cy", false, false),
2041 ]));
2042 assert_eq!(
2043 model.focus().map(|focus| focus.mri),
2044 Some("8:orgid:b".to_owned())
2045 );
2046 model.apply(CallUpdate::Roster(vec![entry(
2047 "8:orgid:a",
2048 "Ana",
2049 false,
2050 false,
2051 )]));
2052 assert_eq!(model.focus(), None);
2053 }
2054
2055 #[test]
2056 fn spotlighting_yourself_puts_your_own_tile_on_the_stage() {
2057 let mut model = meeting_with_me();
2058 model.apply(CallUpdate::Roster(vec![
2059 entry("8:orgid:a", "Ana", false, false),
2060 spotlit("8:orgid:me", "Me", 1),
2061 ]));
2062 assert_eq!(
2063 model.focus(),
2064 Some(Focus {
2065 mri: "8:orgid:me".into(),
2066 own: true,
2067 spotlight: true,
2068 pinned: false
2069 })
2070 );
2071 }
2072
2073 #[test]
2074 fn a_pin_is_local_beats_the_spotlight_and_ends_when_the_person_leaves() {
2075 let mut model = meeting_with_me();
2076 model.apply(CallUpdate::State(CallState::Connected {
2077 since: Instant::now(),
2078 }));
2079 model.apply(CallUpdate::Roster(vec![
2080 entry("8:orgid:a", "Ana", false, false),
2081 spotlit("8:orgid:b", "Bo", 1),
2082 ]));
2083 model.toggle_pin("8:orgid:a");
2084 assert_eq!(
2085 model.focus(),
2086 Some(Focus {
2087 mri: "8:orgid:a".into(),
2088 own: false,
2089 spotlight: false,
2090 pinned: true
2091 })
2092 );
2093 let names: Vec<&str> = model
2094 .strip_tiles()
2095 .iter()
2096 .map(|tile| tile.name.as_str())
2097 .collect();
2098 assert_eq!(names[0], "Ana");
2099 model.toggle_pin("8:orgid:b");
2100 assert_eq!(
2101 model
2102 .focus()
2103 .map(|focus| (focus.mri, focus.spotlight, focus.pinned)),
2104 Some(("8:orgid:b".to_owned(), true, true))
2105 );
2106 model.toggle_pin("8:orgid:b");
2107 assert_eq!(model.pinned, None);
2108 model.toggle_pin("8:orgid:a");
2109 model.apply(CallUpdate::Roster(vec![spotlit("8:orgid:b", "Bo", 1)]));
2110 assert_eq!(model.pinned, None);
2111 }
2112
2113 fn caption(id: &str, speaker: &str, text: &str, is_final: bool) -> CaptionEntry {
2114 CaptionEntry {
2115 id: id.into(),
2116 user_id: "u".into(),
2117 display_name: speaker.into(),
2118 text: text.into(),
2119 is_final,
2120 }
2121 }
2122
2123 #[test]
2124 fn captions_keep_two_lines_update_partials_and_fade_after_four_seconds() {
2125 let mut model = meeting_with_me();
2126 let start = Instant::now();
2127 model.note_caption(caption("1", "Ana", "ignored while off", false), start);
2128 assert!(model.caption_lines.is_empty());
2129 model.apply(CallUpdate::Captions(CaptionState::On));
2130 model.note_caption(caption("1", "Ana", "Hello", false), start);
2131 model.note_caption(caption("1", "Ana", "Hello there", true), start);
2132 assert_eq!(model.caption_lines.len(), 1);
2133 assert_eq!(model.caption_lines[0].text, "Hello there");
2134 model.note_caption(
2135 caption("2", "", "Next", false),
2136 start + Duration::from_secs(1),
2137 );
2138 model.note_caption(
2139 caption("3", "Bo", "Third", false),
2140 start + Duration::from_secs(2),
2141 );
2142 let texts: Vec<&str> = model
2143 .caption_lines
2144 .iter()
2145 .map(|line| line.text.as_str())
2146 .collect();
2147 assert_eq!(texts, vec!["Next", "Third"]);
2148 assert_eq!(model.caption_lines[0].speaker, "Someone");
2149 assert_eq!(
2150 model.visible_captions(start + Duration::from_secs(3)).len(),
2151 2
2152 );
2153 assert_eq!(
2154 model
2155 .visible_captions(start + Duration::from_millis(5500))
2156 .len(),
2157 1
2158 );
2159 assert!(
2160 model
2161 .visible_captions(start + Duration::from_secs(7))
2162 .is_empty()
2163 );
2164 model.apply(CallUpdate::Captions(CaptionState::Off));
2165 assert!(model.caption_lines.is_empty() && !model.captions_on());
2166 }
2167
2168 fn one_to_one() -> CallModel {
2169 let mut model = CallModel::people("Bea", &[("8:orgid:bea".into(), "Bea".into())]);
2170 model.apply(CallUpdate::State(CallState::Connected {
2171 since: Instant::now(),
2172 }));
2173 model
2174 }
2175
2176 #[test]
2177 fn hold_and_transfer_belong_to_one_to_one_calls_and_follow_the_hold_state() {
2178 let mut model = one_to_one();
2179 assert!(model.can_hold() && model.can_transfer());
2180 model.apply(CallUpdate::Hold(HoldState::Local));
2181 assert!(model.can_hold() && !model.can_transfer());
2182 model.apply(CallUpdate::Hold(HoldState::Remote));
2183 assert!(!model.can_hold() && !model.can_transfer());
2184 let meeting = meeting_with_me();
2185 assert!(!meeting.can_hold() && !meeting.can_transfer());
2186 assert!(
2187 !CallModel::people(
2188 "Group",
2189 &[
2190 ("8:orgid:a".into(), "A".into()),
2191 ("8:orgid:b".into(), "B".into())
2192 ]
2193 )
2194 .can_hold()
2195 );
2196 }
2197
2198 #[test]
2199 fn the_transcript_keeps_every_caption_with_its_offset_while_the_overlay_keeps_two() {
2200 let mut model = meeting_with_me();
2201 let start = Instant::now();
2202 model.apply(CallUpdate::State(CallState::Connected { since: start }));
2203 model.apply(CallUpdate::Captions(CaptionState::On));
2204 model.note_caption(caption("1", "Ana Example", "One", true), start + Duration::from_secs(5));
2205 model.note_caption(caption("2", "Bo Sample", "Two", true), start + Duration::from_secs(65));
2206 model.note_caption(caption("3", "Ana Example", "Three", true), start + Duration::from_secs(70));
2207 assert_eq!(model.caption_lines.len(), 2);
2208 assert_eq!(model.transcript.filtered("").len(), 3);
2209 assert_eq!(model.transcript.filtered("")[1].offset, Duration::from_secs(65));
2210 model.apply(CallUpdate::Captions(CaptionState::Off));
2211 model.note_caption(caption("4", "Bo Sample", "Ignored", true), start + Duration::from_secs(80));
2212 assert!(model.caption_lines.is_empty());
2213 assert_eq!(model.transcript.filtered("").len(), 3);
2214 }
2215
2216 #[test]
2217 fn a_chosen_spoken_language_is_handed_out_once_the_captions_are_on() {
2218 let mut model = meeting_with_me();
2219 model.choose_caption_language("de-DE");
2220 model.apply(CallUpdate::Captions(CaptionState::Starting));
2221 assert_eq!(model.take_ready_caption_language(), None);
2222 model.apply(CallUpdate::Captions(CaptionState::On));
2223 assert_eq!(model.take_ready_caption_language().as_deref(), Some("de-DE"));
2224 assert_eq!(model.take_ready_caption_language(), None);
2225 assert_eq!(model.caption_language.as_deref(), Some("de-DE"));
2226 }
2227
2228 #[test]
2229 fn audio_only_and_transcription_follow_their_own_updates() {
2230 let mut model = meeting_with_me();
2231 model.apply(CallUpdate::Transcribing(true));
2232 assert!(model.transcribing && !model.recording);
2233 model.apply(CallUpdate::Recording(true));
2234 model.apply(CallUpdate::RecordingAudioOnly(true));
2235 assert!(model.recording && model.recording_audio_only);
2236 model.apply(CallUpdate::Transcribing(false));
2237 assert!(!model.transcribing && model.recording);
2238 }
2239
2240 #[test]
2241 fn recording_and_consent_follow_the_call_updates() {
2242 let mut model = meeting_with_me();
2243 assert!(!model.can_record());
2244 model.apply(CallUpdate::State(CallState::Connected {
2245 since: Instant::now(),
2246 }));
2247 assert!(model.can_record());
2248 model.apply(CallUpdate::Recording(true));
2249 model.apply(CallUpdate::ConsentRequired(true));
2250 assert!(model.recording && model.consent_required);
2251 model.apply(CallUpdate::ConsentRequired(false));
2252 assert!(model.recording && !model.consent_required);
2253 model.apply(CallUpdate::Recording(false));
2254 assert!(!model.recording);
2255 }
2256
2257 #[test]
2258 fn a_whiteboard_share_names_the_presenter_and_offers_the_browser_only_with_a_link() {
2259 let mut model = meeting_with_me();
2260 model.apply(CallUpdate::Roster(vec![entry(
2261 "8:orgid:ana",
2262 "Ana",
2263 false,
2264 false,
2265 )]));
2266 assert_eq!(model.whiteboard_label(), None);
2267 let share = |presenter: &str, url: Option<&str>| calling::ContentShare {
2268 session_id: "s".into(),
2269 presenter: Some(presenter.into()),
2270 subject: "Whiteboard".into(),
2271 url: url.map(str::to_owned),
2272 whiteboard: true,
2273 };
2274 model.apply(CallUpdate::Whiteboard(Some(share(
2275 "8:orgid:ana",
2276 Some("https://app.whiteboard.microsoft.com/x"),
2277 ))));
2278 assert_eq!(
2279 model.whiteboard_label().as_deref(),
2280 Some("Ana is sharing a whiteboard")
2281 );
2282 assert_eq!(
2283 model.whiteboard_url(),
2284 Some("https://app.whiteboard.microsoft.com/x")
2285 );
2286 model.apply(CallUpdate::Whiteboard(Some(share(
2287 "8:orgid:stranger",
2288 None,
2289 ))));
2290 assert_eq!(
2291 model.whiteboard_label().as_deref(),
2292 Some("Someone is sharing a whiteboard")
2293 );
2294 assert_eq!(model.whiteboard_url(), None);
2295 model.apply(CallUpdate::Whiteboard(None));
2296 assert_eq!(model.whiteboard_label(), None);
2297 }
2298
2299 #[test]
2300 fn a_consultation_can_transfer_once_connected_with_a_replacement_link() {
2301 let mut model = CallModel::people("Ana", &[("8:orgid:ana".into(), "Ana".into())]);
2302 let mut consult = ConsultCall::new(("8:orgid:ana".into(), "Ana".into()), "Chris".into());
2303 assert_eq!(consult.banner_text(), "Chris is on hold");
2304 consult.replacement = Some(Replacement::of_call("https://cc/replacement"));
2305 assert!(!consult.ready_to_transfer(&model));
2306 model.apply(CallUpdate::State(CallState::Connected {
2307 since: Instant::now(),
2308 }));
2309 assert!(consult.ready_to_transfer(&model));
2310 consult.transfer = ConsultTransfer::Pending;
2311 assert!(!consult.ready_to_transfer(&model));
2312 assert_eq!(consult.banner_text(), "Transferring Chris to Ana...");
2313 }
2314}