BlueGit

ict rusty-teams

Files

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

model.rs

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