BlueGit

ict rusty-teams

Files

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

model.rs

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