BlueGit

ict rusty-teams

Files

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

model.rs

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