BlueGit

ict rusty-teams

Files

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

model.rs

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