BlueGit

ict rusty-teams

Files

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

model.rs

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