BlueGit

ict rusty-teams

Files

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

model.rs

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