BlueGit

ict rusty-teams

Files

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

model.rs

b608e9a1 History
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, VideoWant,
10};
11use tokio::sync::mpsc::UnboundedSender;
12
13use super::background::BackgroundPick;
14use super::health::{HealthBanner, HealthState};
15use super::bubbles::ChatBubble;
16use super::fullscreen::FullscreenState;
17use super::pictures::CallPictures;
18use super::stage_layout::{FILMSTRIP_MAX, GALLERY_MAX, RECENT_SPEAKER, SPEAKER_HOLD, VisibleRotation, split_overflow};
19use super::view_settings::{CallLayout, ViewSettings};
20use super::push_to_talk::PushToTalk;
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 sent_wants: Vec<VideoWant>,
46 pub bubbles: Vec<ChatBubble>,
47 pub share_menu_open: bool,
48 pub lobby_list_open: bool,
49 pub chat_open: bool,
50 pub meeting_target: Option<MeetingTarget>,
51 pub pending_move: Option<PendingMove>,
52 pub consult: Option<ConsultCall>,
53 pub push_to_talk: PushToTalk,
54}
55
56#[derive(Debug, Clone, PartialEq)]
57pub struct PendingMove {
58 pub target: MeetingTarget,
59 pub title: String,
60 pub breakout: Option<BreakoutState>,
61}
62
63pub struct ConsultCall {
64 pub id: u64,
65 pub target: (String, String),
66 pub commands: UnboundedSender<CallCommand>,
67 pub state: CallState,
68 pub replacement: Option<String>,
69 pub transferring: bool,
70}
71
72impl ConsultCall {
73 pub fn connected(&self) -> bool {
74 matches!(self.state, CallState::Connected { .. })
75 }
76
77 pub fn ready_to_transfer(&self) -> bool {
78 self.connected() && self.replacement.is_some()
79 }
80
81 pub fn status_text(&self) -> String {
82 let name = &self.target.1;
83 match &self.state {
84 CallState::Connected { .. } => format!("Consulting {name}"),
85 _ => format!("Calling {name}..."),
86 }
87 }
88}
89
90impl ActiveCall {
91 pub fn new(
92 id: u64,
93 model: CallModel,
94 commands: UnboundedSender<CallCommand>,
95 conversation_id: Option<String>,
96 video: Arc<VideoHub>,
97 ) -> Self {
98 ActiveCall {
99 id,
100 model,
101 commands,
102 viewing: true,
103 conversation_id,
104 video,
105 pictures: CallPictures::default(),
106 stage_fullscreen: false,
107 fullscreen: None,
108 stage_size: Rc::default(),
109 sent_wants: Vec::new(),
110 bubbles: Vec::new(),
111 share_menu_open: false,
112 lobby_list_open: false,
113 chat_open: false,
114 meeting_target: None,
115 pending_move: None,
116 consult: None,
117 push_to_talk: PushToTalk::default(),
118 }
119 }
120
121 pub fn chat_thread(&self) -> Option<&str> {
122 chat_thread(
123 self.model.kind,
124 self.model.meeting_chat.as_deref(),
125 self.conversation_id.as_deref(),
126 )
127 }
128}
129
130pub fn chat_thread<'a>(
131 kind: CallKind,
132 meeting_chat: Option<&'a str>,
133 conversation_id: Option<&'a str>,
134) -> Option<&'a str> {
135 match kind {
136 CallKind::Meeting => meeting_chat.or(conversation_id),
137 CallKind::Test | CallKind::Direct | CallKind::Group => conversation_id,
138 }
139}
140
141#[derive(Debug, Clone, Copy, PartialEq, Eq)]
142pub enum CallKind {
143 Test,
144 Direct,
145 Group,
146 Meeting,
147}
148
149#[derive(Debug, Clone, Copy, PartialEq, Eq)]
150pub enum TileState {
151 Invited,
152 Present,
153 InLobby,
154 Left,
155}
156
157#[derive(Debug, Clone, PartialEq, Eq)]
158pub struct Tile {
159 pub mri: String,
160 pub user_id: Option<String>,
161 pub name: String,
162 pub muted: bool,
163 pub state: TileState,
164 pub invited: bool,
165 pub has_video: bool,
166 pub hand: Option<u64>,
167 pub spotlight: Option<u64>,
168}
169
170impl Tile {
171 pub fn invited(mri: &str, name: &str) -> Tile {
172 Tile {
173 mri: mri.to_owned(),
174 user_id: mri.strip_prefix(ORGID_PREFIX).map(str::to_owned),
175 name: name.to_owned(),
176 muted: false,
177 state: TileState::Invited,
178 invited: true,
179 has_video: false,
180 hand: None,
181 spotlight: None,
182 }
183 }
184}
185
186#[derive(Debug, Clone, PartialEq)]
187pub struct BreakoutState {
188 pub room_name: String,
189 pub main: Option<MeetingTarget>,
190 pub main_title: String,
191}
192
193#[derive(Debug, Clone, PartialEq, Eq)]
194pub struct Focus {
195 pub mri: String,
196 pub own: bool,
197 pub spotlight: bool,
198 pub pinned: bool,
199}
200
201#[derive(Debug, Clone, PartialEq, Eq)]
202pub struct CaptionLine {
203 pub id: String,
204 pub speaker: String,
205 pub text: String,
206 pub at: Instant,
207}
208
209#[derive(Debug, Clone, Copy, PartialEq)]
210pub struct TileSize {
211 pub width: f32,
212 pub height: f32,
213 pub avatar: f32,
214}
215
216impl TileSize {
217 pub fn sixteen_by_nine(width: f32) -> TileSize {
218 let height = width * 9. / 16.;
219 TileSize {
220 width,
221 height,
222 avatar: (height * AVATAR_SHARE).clamp(MIN_AVATAR, MAX_AVATAR),
223 }
224 }
225}
226
227#[derive(Debug, Clone, PartialEq, Eq)]
228pub struct ReactionChip {
229 pub mri: String,
230 pub reaction: Reaction,
231 pub since: Instant,
232 pub serial: u64,
233}
234
235#[derive(Debug, Clone)]
236pub struct CallModel {
237 pub title: String,
238 pub kind: CallKind,
239 pub peer_name: String,
240 pub state: CallState,
241 pub progress: Option<Progress>,
242 pub muted: bool,
243 pub listen_only: bool,
244 pub lobby: bool,
245 pub can_end_meeting: bool,
246 pub incoming: bool,
247 pub input: DeviceChoice,
248 pub output: DeviceChoice,
249 pub devices: DeviceLists,
250 pub local_speaking: bool,
251 pub remote_speaking: bool,
252 pub speaking_mris: Vec<String>,
253 pub connected_since: Option<Instant>,
254 pub own_mri: Option<String>,
255 pub tiles: Vec<Tile>,
256 pub screen_sharer: Option<String>,
257 pub camera_on: bool,
258 pub cameras: Vec<CameraDevice>,
259 pub camera: DeviceChoice,
260 pub local_share: Option<String>,
261 pub share_sources: Vec<ShareSource>,
262 pub share_sound: bool,
263 pub own_hand: Option<u64>,
264 pub own_spotlight: Option<u64>,
265 pub organizer: bool,
266 pub pinned: Option<String>,
267 pub captions: CaptionState,
268 pub caption_lines: Vec<CaptionLine>,
269 pub background: BackgroundPick,
270 pub recording: bool,
271 pub consent_required: bool,
272 pub hold: HoldState,
273 pub health: HealthState,
274 pub whiteboard: Option<ContentShare>,
275 pub breakout: Option<BreakoutState>,
276 pub main_meeting: Option<MeetingTarget>,
277 pub reactions: Vec<ReactionChip>,
278 reaction_serial: u64,
279 pub meeting_chat: Option<String>,
280 pub view: ViewSettings,
281 rotation: VisibleRotation,
282 stage_speaker: Option<String>,
283 recent_speakers: Vec<String>,
284 local_detector: SpeakingDetector,
285 remote_detector: SpeakingDetector,
286}
287
288impl CallModel {
289 fn base(kind: CallKind, title: &str, peer_name: &str, tiles: Vec<Tile>) -> Self {
290 CallModel {
291 title: title.to_owned(),
292 kind,
293 peer_name: peer_name.to_owned(),
294 state: CallState::Connecting,
295 progress: None,
296 muted: false,
297 listen_only: 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
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 callees_start_invited_and_follow_the_progress() {
1263 let mut model = CallModel::people("Bea", &[("8:orgid:b".into(), "Bea".into())]);
1264 assert_eq!(model.kind, CallKind::Direct);
1265 assert_eq!(model.peer_name, "Bea");
1266 assert_eq!(model.tile_caption(&model.tiles[0]), Some("Calling..."));
1267 model.apply(CallUpdate::Progress(Progress::Ringing));
1268 assert_eq!(model.tile_caption(&model.tiles[0]), Some("Ringing"));
1269 model.apply(CallUpdate::Roster(vec![entry(
1270 "8:orgid:b",
1271 "Bea",
1272 false,
1273 false,
1274 )]));
1275 assert_eq!(model.tiles[0].state, TileState::Present);
1276 assert_eq!(model.tile_caption(&model.tiles[0]), None);
1277 }
1278
1279 #[test]
1280 fn several_callees_make_a_group_call_named_after_the_chat() {
1281 let model = CallModel::people(
1282 "Retro team",
1283 &[
1284 ("8:orgid:b".into(), "Bea".into()),
1285 ("8:orgid:c".into(), "Cy".into()),
1286 ],
1287 );
1288 assert_eq!(model.kind, CallKind::Group);
1289 assert_eq!(model.peer_name, "Retro team");
1290 assert_eq!(model.tiles.len(), 2);
1291 }
1292
1293 #[test]
1294 fn roster_adds_guests_updates_mute_and_drops_leavers() {
1295 let mut model = meeting_with_me();
1296 model.apply(CallUpdate::Roster(vec![
1297 entry("8:orgid:me", "Me", false, false),
1298 entry("8:orgid:a", "Ana", true, false),
1299 entry("8:orgid:b", "Bo", false, false),
1300 ]));
1301 assert_eq!(model.tiles.len(), 2);
1302 assert!(
1303 model
1304 .tiles
1305 .iter()
1306 .find(|tile| tile.name == "Ana")
1307 .unwrap()
1308 .muted
1309 );
1310 model.apply(CallUpdate::Roster(vec![
1311 entry("8:orgid:me", "Me", false, false),
1312 entry("8:orgid:b", "Bo", false, false),
1313 ]));
1314 assert_eq!(model.tiles.len(), 1);
1315 assert_eq!(model.tiles[0].name, "Bo");
1316 }
1317
1318 #[test]
1319 fn an_invited_callee_who_leaves_stays_as_left() {
1320 let mut model = CallModel::people("Bea", &[("8:orgid:b".into(), "Bea".into())]);
1321 model.apply(CallUpdate::Roster(vec![entry(
1322 "8:orgid:b",
1323 "Bea",
1324 false,
1325 false,
1326 )]));
1327 model.apply(CallUpdate::Roster(Vec::new()));
1328 assert_eq!(model.tiles[0].state, TileState::Left);
1329 assert_eq!(model.tile_caption(&model.tiles[0]), Some("Left"));
1330 }
1331
1332 #[test]
1333 fn lobby_guests_get_no_tile() {
1334 let mut model = meeting_with_me();
1335 model.apply(CallUpdate::Roster(vec![
1336 entry("8:orgid:a", "Ana", false, false),
1337 entry("8:orgid:g", "Guest", false, true),
1338 ]));
1339 let names: Vec<&str> = model
1340 .visible_tiles()
1341 .iter()
1342 .map(|tile| tile.name.as_str())
1343 .collect();
1344 assert_eq!(names, vec!["Ana"]);
1345 }
1346
1347 #[test]
1348 fn the_lobby_flag_follows_the_call() {
1349 let mut model = meeting_with_me();
1350 model.apply(CallUpdate::Lobby(true));
1351 assert!(model.lobby);
1352 model.apply(CallUpdate::Lobby(false));
1353 assert!(!model.lobby);
1354 }
1355
1356 #[test]
1357 fn speakers_light_their_own_tile_and_a_lone_remote_follows_the_level() {
1358 let mut model = meeting_with_me();
1359 model.apply(CallUpdate::Roster(vec![
1360 entry("8:orgid:a", "Ana", false, false),
1361 entry("8:orgid:b", "Bo", false, false),
1362 ]));
1363 model.apply(CallUpdate::State(CallState::Connected {
1364 since: Instant::now(),
1365 }));
1366 model.apply(CallUpdate::Speakers(vec!["8:orgid:b".into()]));
1367 let tiles: Vec<Tile> = model.tiles.clone();
1368 assert!(!model.tile_speaking(&tiles[0]));
1369 assert!(model.tile_speaking(&tiles[1]));
1370 let mut lone = CallModel::people("Bea", &[("8:orgid:b".into(), "Bea".into())]);
1371 lone.apply(CallUpdate::State(CallState::Connected {
1372 since: Instant::now(),
1373 }));
1374 lone.apply(CallUpdate::Levels {
1375 local: 0.0,
1376 remote: 0.5,
1377 });
1378 assert!(lone.tile_speaking(&lone.tiles[0].clone()));
1379 }
1380
1381 fn crowd(count: usize) -> CallModel {
1382 let mut model = meeting_with_me();
1383 model.apply(CallUpdate::Roster(
1384 (0..count)
1385 .map(|index| {
1386 entry(
1387 &format!("8:orgid:p{index}"),
1388 &format!("P{index}"),
1389 false,
1390 false,
1391 )
1392 })
1393 .collect(),
1394 ));
1395 model
1396 }
1397
1398 fn shown_mris(model: &CallModel) -> Vec<String> {
1399 model
1400 .layout_tiles()
1401 .iter()
1402 .map(|tile| tile.mri.clone())
1403 .collect()
1404 }
1405
1406 #[test]
1407 fn hiding_people_without_video_keeps_speakers_and_the_pinned_person() {
1408 let mut model = meeting_with_me();
1409 model.apply(CallUpdate::Roster(vec![
1410 entry("8:orgid:a", "Ana", false, false),
1411 RosterEntry {
1412 has_video: true,
1413 ..entry("8:orgid:b", "Bo", false, false)
1414 },
1415 entry("8:orgid:c", "Cy", false, false),
1416 ]));
1417 model.view.hide_no_video = true;
1418 assert_eq!(model.hidden_without_video(), 2);
1419 assert_eq!(shown_mris(&model), vec!["8:orgid:b"]);
1420 model.apply(CallUpdate::Speakers(vec!["8:orgid:a".into()]));
1421 assert_eq!(model.hidden_without_video(), 1);
1422 assert!(shown_mris(&model).contains(&"8:orgid:a".to_owned()));
1423 model.toggle_pin("8:orgid:c");
1424 assert_eq!(model.hidden_without_video(), 0);
1425 }
1426
1427 #[test]
1428 fn people_without_video_stay_in_one_to_one_calls() {
1429 let mut model = CallModel::people("Bea", &[("8:orgid:b".into(), "Bea".into())]);
1430 model.view.hide_no_video = true;
1431 model.apply(CallUpdate::Roster(vec![entry(
1432 "8:orgid:b",
1433 "Bea",
1434 false,
1435 false,
1436 )]));
1437 assert_eq!(model.hidden_without_video(), 0);
1438 }
1439
1440 #[test]
1441 fn focus_on_content_falls_back_to_the_previous_layout_when_the_share_ends() {
1442 let mut model = meeting_with_me();
1443 model.view.choose(CallLayout::Speaker);
1444 model.view.choose(CallLayout::Content);
1445 assert_eq!(model.effective_layout(), CallLayout::Speaker);
1446 model.apply(CallUpdate::ScreenShare(Some("8:orgid:a".into())));
1447 assert_eq!(model.effective_layout(), CallLayout::Content);
1448 model.apply(CallUpdate::ScreenShare(None));
1449 assert_eq!(model.effective_layout(), CallLayout::Speaker);
1450 }
1451
1452 #[test]
1453 fn the_speaker_stage_follows_the_active_speaker_and_keeps_the_last_one() {
1454 let mut model = crowd(3);
1455 model.apply(CallUpdate::Speakers(vec!["8:orgid:p1".into()]));
1456 assert_eq!(model.speaker_focus().unwrap().mri, "8:orgid:p1");
1457 model.apply(CallUpdate::Speakers(Vec::new()));
1458 assert_eq!(model.speaker_focus().unwrap().mri, "8:orgid:p1");
1459 model.toggle_pin("8:orgid:p2");
1460 let focus = model.speaker_focus().unwrap();
1461 assert_eq!((focus.mri.as_str(), focus.pinned), ("8:orgid:p2", true));
1462 }
1463
1464 #[test]
1465 fn a_pinned_person_outside_the_grid_moves_into_it() {
1466 let mut model = crowd(12);
1467 let grid = split_overflow(12, 1, GALLERY_MAX).shown;
1468 assert_eq!(grid, 7);
1469 assert!(!shown_mris(&model)[..grid].contains(&"8:orgid:p11".to_owned()));
1470 model.toggle_pin("8:orgid:p11");
1471 assert!(shown_mris(&model)[..grid].contains(&"8:orgid:p11".to_owned()));
1472 assert_eq!(model.layout_tiles().len(), 12);
1473 }
1474
1475 #[test]
1476 fn hiding_me_frees_a_grid_cell() {
1477 let mut model = crowd(12);
1478 assert_eq!(model.own_cells(), 1);
1479 model.view.hide_me = true;
1480 assert_eq!(model.own_cells(), 0);
1481 assert_eq!(split_overflow(12, model.own_cells(), GALLERY_MAX).shown, 8);
1482 }
1483
1484 #[test]
1485 fn the_stage_label_names_the_sharer_and_the_strip_puts_the_speaker_first() {
1486 let mut model = meeting_with_me();
1487 model.apply(CallUpdate::Roster(vec![
1488 entry("8:orgid:a", "Ana", false, false),
1489 entry("8:orgid:b", "Bo", false, false),
1490 ]));
1491 assert_eq!(model.sharing_label(), None);
1492 model.apply(CallUpdate::ScreenShare(Some("8:orgid:b".into())));
1493 assert_eq!(model.sharing_label().as_deref(), Some("Bo is sharing"));
1494 model.apply(CallUpdate::State(CallState::Connected {
1495 since: Instant::now(),
1496 }));
1497 model.apply(CallUpdate::Speakers(vec!["8:orgid:b".into()]));
1498 let names: Vec<&str> = model
1499 .strip_tiles()
1500 .iter()
1501 .map(|tile| tile.name.as_str())
1502 .collect();
1503 assert_eq!(names, vec!["Bo", "Ana"]);
1504 model.apply(CallUpdate::ScreenShare(None));
1505 assert_eq!(model.sharing_label(), None);
1506 }
1507
1508 #[test]
1509 fn roster_entries_carry_the_camera_flag_to_the_tile() {
1510 let mut model = meeting_with_me();
1511 let mut with_camera = entry("8:orgid:a", "Ana", false, false);
1512 with_camera.has_video = true;
1513 model.apply(CallUpdate::Roster(vec![with_camera]));
1514 assert!(model.tiles[0].has_video);
1515 model.apply(CallUpdate::Roster(vec![entry(
1516 "8:orgid:a",
1517 "Ana",
1518 false,
1519 false,
1520 )]));
1521 assert!(!model.tiles[0].has_video);
1522 }
1523
1524 #[test]
1525 fn present_guests_sort_before_waiting_ones() {
1526 let mut model = CallModel::people(
1527 "Group",
1528 &[
1529 ("8:orgid:b".into(), "Bea".into()),
1530 ("8:orgid:c".into(), "Cy".into()),
1531 ],
1532 );
1533 model.apply(CallUpdate::Roster(vec![entry(
1534 "8:orgid:c",
1535 "Cy",
1536 false,
1537 false,
1538 )]));
1539 let names: Vec<&str> = model
1540 .visible_tiles()
1541 .iter()
1542 .map(|tile| tile.name.as_str())
1543 .collect();
1544 assert_eq!(names, vec!["Cy", "Bea"]);
1545 }
1546
1547 #[test]
1548 fn raised_hands_get_queue_positions_by_raise_time_and_sort_first() {
1549 let mut model = meeting_with_me();
1550 model.apply(CallUpdate::Roster(vec![
1551 entry("8:orgid:a", "Ana", false, false),
1552 raised("8:orgid:b", "Bo", 9),
1553 raised("8:orgid:c", "Cy", 4),
1554 raised("8:orgid:me", "Me", 6),
1555 ]));
1556 assert_eq!(model.own_hand, Some(6));
1557 assert!(model.any_hand_raised());
1558 let names: Vec<&str> = model
1559 .visible_tiles()
1560 .iter()
1561 .map(|tile| tile.name.as_str())
1562 .collect();
1563 assert_eq!(names, vec!["Cy", "Bo", "Ana"]);
1564 let positions: Vec<usize> = [4, 6, 9]
1565 .into_iter()
1566 .map(|rank| model.hand_position(rank))
1567 .collect();
1568 assert_eq!(positions, vec![1, 2, 3]);
1569 assert_eq!(model.own_cell_index(3), 1);
1570 let strip: Vec<&str> = model
1571 .strip_tiles()
1572 .iter()
1573 .map(|tile| tile.name.as_str())
1574 .collect();
1575 assert_eq!(strip, vec!["Cy", "Bo", "Ana"]);
1576 }
1577
1578 #[test]
1579 fn a_roster_without_the_own_entry_keeps_the_own_hand() {
1580 let mut model = meeting_with_me();
1581 model.apply(CallUpdate::OwnHand(Some(5)));
1582 model.apply(CallUpdate::Roster(vec![entry(
1583 "8:orgid:a",
1584 "Ana",
1585 false,
1586 false,
1587 )]));
1588 assert_eq!(model.own_hand, Some(5));
1589 model.apply(CallUpdate::Roster(vec![entry(
1590 "8:orgid:me",
1591 "Me",
1592 false,
1593 false,
1594 )]));
1595 assert_eq!(model.own_hand, None);
1596 }
1597
1598 #[test]
1599 fn reaction_controls_show_in_group_calls_and_meetings_only() {
1600 let mut model = CallModel::test();
1601 for (kind, expected) in [
1602 (CallKind::Test, false),
1603 (CallKind::Direct, false),
1604 (CallKind::Group, true),
1605 (CallKind::Meeting, true),
1606 ] {
1607 model.kind = kind;
1608 assert_eq!(model.has_reaction_controls(), expected);
1609 }
1610 }
1611
1612 #[test]
1613 fn the_server_echo_of_an_own_reaction_does_not_restart_the_chip() {
1614 let mut model = meeting_with_me();
1615 let start = Instant::now();
1616 model.note_reaction("8:orgid:me".into(), Reaction::Like, start);
1617 let serial = model.reactions[0].serial;
1618 model.note_reaction(
1619 "8:orgid:me".into(),
1620 Reaction::Like,
1621 start + Duration::from_millis(1500),
1622 );
1623 assert_eq!(model.reactions.len(), 1);
1624 assert_eq!(model.reactions[0].serial, serial);
1625 model.note_reaction(
1626 "8:orgid:me".into(),
1627 Reaction::Heart,
1628 start + Duration::from_millis(1600),
1629 );
1630 assert_eq!(model.reactions[0].reaction, Reaction::Heart);
1631 model.note_reaction(
1632 "8:orgid:me".into(),
1633 Reaction::Heart,
1634 start + Duration::from_secs(4),
1635 );
1636 assert_ne!(model.reactions[0].serial, serial);
1637 }
1638
1639 #[test]
1640 fn another_persons_repeated_reaction_restarts_the_chip() {
1641 let mut model = meeting_with_me();
1642 let start = Instant::now();
1643 model.note_reaction("8:orgid:a".into(), Reaction::Like, start);
1644 let serial = model.reactions[0].serial;
1645 model.note_reaction(
1646 "8:orgid:a".into(),
1647 Reaction::Like,
1648 start + Duration::from_secs(1),
1649 );
1650 assert_ne!(model.reactions[0].serial, serial);
1651 }
1652
1653 #[test]
1654 fn lowering_clears_the_hand_everywhere() {
1655 let mut model = meeting_with_me();
1656 model.apply(CallUpdate::Roster(vec![
1657 raised("8:orgid:a", "Ana", 1),
1658 raised("8:orgid:me", "Me", 2),
1659 ]));
1660 model.apply(CallUpdate::Roster(vec![
1661 entry("8:orgid:a", "Ana", false, false),
1662 entry("8:orgid:me", "Me", false, false),
1663 ]));
1664 assert!(!model.any_hand_raised());
1665 assert_eq!(model.own_cell_index(1), 1);
1666 }
1667
1668 #[test]
1669 fn only_organizers_may_lower_hands() {
1670 assert!(!CallModel::meeting("Standup", false).can_lower_hands());
1671 assert!(CallModel::meeting("Standup", true).can_lower_hands());
1672 }
1673
1674 #[test]
1675 fn a_reaction_shows_for_three_seconds_on_its_sender_and_the_latest_wins() {
1676 let mut model = meeting_with_me();
1677 let start = Instant::now();
1678 model.note_reaction("8:orgid:a".into(), Reaction::Heart, start);
1679 model.note_reaction("8:orgid:me".into(), Reaction::Like, start);
1680 let reaction_at = |model: &CallModel, mri: &str, seconds: u64| {
1681 model
1682 .chip_of(mri, start + Duration::from_secs(seconds))
1683 .map(|chip| chip.reaction)
1684 };
1685 assert_eq!(reaction_at(&model, "8:orgid:a", 2), Some(Reaction::Heart));
1686 assert_eq!(
1687 model
1688 .own_chip(start + Duration::from_secs(2))
1689 .map(|chip| chip.reaction),
1690 Some(Reaction::Like)
1691 );
1692 assert_eq!(reaction_at(&model, "8:orgid:a", 3), None);
1693 model.note_reaction(
1694 "8:orgid:a".into(),
1695 Reaction::Laugh,
1696 start + Duration::from_secs(1),
1697 );
1698 assert_eq!(reaction_at(&model, "8:orgid:a", 2), Some(Reaction::Laugh));
1699 assert_eq!(model.reactions.len(), 2);
1700 }
1701
1702 #[test]
1703 fn the_chat_panel_picks_the_meeting_thread_or_the_call_chat() {
1704 assert_eq!(
1705 chat_thread(CallKind::Meeting, Some("19:meeting_x"), Some("19:list")),
1706 Some("19:meeting_x")
1707 );
1708 assert_eq!(
1709 chat_thread(CallKind::Meeting, None, Some("19:list")),
1710 Some("19:list")
1711 );
1712 assert_eq!(
1713 chat_thread(CallKind::Direct, Some("19:meeting_x"), Some("19:dm")),
1714 Some("19:dm")
1715 );
1716 assert_eq!(
1717 chat_thread(CallKind::Group, None, Some("19:group")),
1718 Some("19:group")
1719 );
1720 assert_eq!(chat_thread(CallKind::Test, None, None), None);
1721 }
1722
1723 #[test]
1724 fn computer_sound_follows_the_share() {
1725 let mut model = connected_model();
1726 model.apply(CallUpdate::LocalShare(Some("Screen".into())));
1727 model.apply(CallUpdate::ShareSound(true));
1728 assert!(model.share_sound);
1729 model.apply(CallUpdate::LocalShare(None));
1730 assert!(!model.share_sound);
1731 }
1732
1733 #[test]
1734 fn lobby_guests_are_listed_for_organizers_who_may_admit() {
1735 let mut model = meeting_with_me();
1736 model.apply(CallUpdate::State(CallState::Connected {
1737 since: Instant::now(),
1738 }));
1739 model.apply(CallUpdate::Roster(vec![
1740 entry("8:orgid:a", "Ana", false, false),
1741 entry("8:orgid:g1", "Gast Eins", false, true),
1742 entry("8:orgid:g2", "Gast Zwei", false, true),
1743 ]));
1744 let waiting: Vec<&str> = model
1745 .lobby_guests()
1746 .iter()
1747 .map(|tile| tile.name.as_str())
1748 .collect();
1749 assert_eq!(waiting, vec!["Gast Eins", "Gast Zwei"]);
1750 assert!(!model.can_admit());
1751 model.apply(CallUpdate::Roster(vec![
1752 organizer_entry("8:orgid:me"),
1753 entry("8:orgid:g1", "Gast Eins", false, true),
1754 ]));
1755 assert!(model.organizer && model.can_admit() && model.organizes_meeting());
1756 let mut owner = CallModel::meeting("Standup", true);
1757 owner.apply(CallUpdate::State(CallState::Connected {
1758 since: Instant::now(),
1759 }));
1760 assert!(owner.can_admit());
1761 owner.apply(CallUpdate::Lobby(true));
1762 assert!(!owner.can_admit());
1763 }
1764
1765 #[test]
1766 fn a_spotlight_takes_the_stage_and_the_lowest_rank_wins() {
1767 let mut model = meeting_with_me();
1768 model.apply(CallUpdate::Roster(vec![
1769 entry("8:orgid:a", "Ana", false, false),
1770 spotlit("8:orgid:b", "Bo", 4),
1771 spotlit("8:orgid:c", "Cy", 2),
1772 ]));
1773 assert_eq!(
1774 model.focus(),
1775 Some(Focus {
1776 mri: "8:orgid:c".into(),
1777 own: false,
1778 spotlight: true,
1779 pinned: false
1780 })
1781 );
1782 assert!(model.is_spotlighted("8:orgid:b") && !model.is_spotlighted("8:orgid:a"));
1783 model.apply(CallUpdate::Roster(vec![
1784 entry("8:orgid:a", "Ana", false, false),
1785 spotlit("8:orgid:b", "Bo", 4),
1786 entry("8:orgid:c", "Cy", false, false),
1787 ]));
1788 assert_eq!(
1789 model.focus().map(|focus| focus.mri),
1790 Some("8:orgid:b".to_owned())
1791 );
1792 model.apply(CallUpdate::Roster(vec![entry(
1793 "8:orgid:a",
1794 "Ana",
1795 false,
1796 false,
1797 )]));
1798 assert_eq!(model.focus(), None);
1799 }
1800
1801 #[test]
1802 fn spotlighting_yourself_puts_your_own_tile_on_the_stage() {
1803 let mut model = meeting_with_me();
1804 model.apply(CallUpdate::Roster(vec![
1805 entry("8:orgid:a", "Ana", false, false),
1806 spotlit("8:orgid:me", "Me", 1),
1807 ]));
1808 assert_eq!(
1809 model.focus(),
1810 Some(Focus {
1811 mri: "8:orgid:me".into(),
1812 own: true,
1813 spotlight: true,
1814 pinned: false
1815 })
1816 );
1817 }
1818
1819 #[test]
1820 fn a_pin_is_local_beats_the_spotlight_and_ends_when_the_person_leaves() {
1821 let mut model = meeting_with_me();
1822 model.apply(CallUpdate::State(CallState::Connected {
1823 since: Instant::now(),
1824 }));
1825 model.apply(CallUpdate::Roster(vec![
1826 entry("8:orgid:a", "Ana", false, false),
1827 spotlit("8:orgid:b", "Bo", 1),
1828 ]));
1829 model.toggle_pin("8:orgid:a");
1830 assert_eq!(
1831 model.focus(),
1832 Some(Focus {
1833 mri: "8:orgid:a".into(),
1834 own: false,
1835 spotlight: false,
1836 pinned: true
1837 })
1838 );
1839 let names: Vec<&str> = model
1840 .strip_tiles()
1841 .iter()
1842 .map(|tile| tile.name.as_str())
1843 .collect();
1844 assert_eq!(names[0], "Ana");
1845 model.toggle_pin("8:orgid:b");
1846 assert_eq!(
1847 model
1848 .focus()
1849 .map(|focus| (focus.mri, focus.spotlight, focus.pinned)),
1850 Some(("8:orgid:b".to_owned(), true, true))
1851 );
1852 model.toggle_pin("8:orgid:b");
1853 assert_eq!(model.pinned, None);
1854 model.toggle_pin("8:orgid:a");
1855 model.apply(CallUpdate::Roster(vec![spotlit("8:orgid:b", "Bo", 1)]));
1856 assert_eq!(model.pinned, None);
1857 }
1858
1859 fn caption(id: &str, speaker: &str, text: &str, is_final: bool) -> CaptionEntry {
1860 CaptionEntry {
1861 id: id.into(),
1862 user_id: "u".into(),
1863 display_name: speaker.into(),
1864 text: text.into(),
1865 is_final,
1866 }
1867 }
1868
1869 #[test]
1870 fn captions_keep_two_lines_update_partials_and_fade_after_four_seconds() {
1871 let mut model = meeting_with_me();
1872 let start = Instant::now();
1873 model.note_caption(caption("1", "Ana", "ignored while off", false), start);
1874 assert!(model.caption_lines.is_empty());
1875 model.apply(CallUpdate::Captions(CaptionState::On));
1876 model.note_caption(caption("1", "Ana", "Hello", false), start);
1877 model.note_caption(caption("1", "Ana", "Hello there", true), start);
1878 assert_eq!(model.caption_lines.len(), 1);
1879 assert_eq!(model.caption_lines[0].text, "Hello there");
1880 model.note_caption(
1881 caption("2", "", "Next", false),
1882 start + Duration::from_secs(1),
1883 );
1884 model.note_caption(
1885 caption("3", "Bo", "Third", false),
1886 start + Duration::from_secs(2),
1887 );
1888 let texts: Vec<&str> = model
1889 .caption_lines
1890 .iter()
1891 .map(|line| line.text.as_str())
1892 .collect();
1893 assert_eq!(texts, vec!["Next", "Third"]);
1894 assert_eq!(model.caption_lines[0].speaker, "Someone");
1895 assert_eq!(
1896 model.visible_captions(start + Duration::from_secs(3)).len(),
1897 2
1898 );
1899 assert_eq!(
1900 model
1901 .visible_captions(start + Duration::from_millis(5500))
1902 .len(),
1903 1
1904 );
1905 assert!(
1906 model
1907 .visible_captions(start + Duration::from_secs(7))
1908 .is_empty()
1909 );
1910 model.apply(CallUpdate::Captions(CaptionState::Off));
1911 assert!(model.caption_lines.is_empty() && !model.captions_on());
1912 }
1913
1914 fn one_to_one() -> CallModel {
1915 let mut model = CallModel::people("Bea", &[("8:orgid:bea".into(), "Bea".into())]);
1916 model.apply(CallUpdate::State(CallState::Connected {
1917 since: Instant::now(),
1918 }));
1919 model
1920 }
1921
1922 #[test]
1923 fn hold_and_transfer_belong_to_one_to_one_calls_and_follow_the_hold_state() {
1924 let mut model = one_to_one();
1925 assert!(model.can_hold() && model.can_transfer());
1926 model.apply(CallUpdate::Hold(HoldState::Local));
1927 assert!(model.can_hold() && !model.can_transfer());
1928 model.apply(CallUpdate::Hold(HoldState::Remote));
1929 assert!(!model.can_hold() && !model.can_transfer());
1930 let meeting = meeting_with_me();
1931 assert!(!meeting.can_hold() && !meeting.can_transfer());
1932 assert!(
1933 !CallModel::people(
1934 "Group",
1935 &[
1936 ("8:orgid:a".into(), "A".into()),
1937 ("8:orgid:b".into(), "B".into())
1938 ]
1939 )
1940 .can_hold()
1941 );
1942 }
1943
1944 #[test]
1945 fn recording_and_consent_follow_the_call_updates_and_only_organizers_may_record() {
1946 let mut model = meeting_with_me();
1947 model.apply(CallUpdate::State(CallState::Connected {
1948 since: Instant::now(),
1949 }));
1950 assert!(!model.can_record());
1951 model.apply(CallUpdate::Roster(vec![organizer_entry("8:orgid:me")]));
1952 assert!(model.can_record());
1953 model.apply(CallUpdate::Recording(true));
1954 model.apply(CallUpdate::ConsentRequired(true));
1955 assert!(model.recording && model.consent_required);
1956 model.apply(CallUpdate::ConsentRequired(false));
1957 assert!(model.recording && !model.consent_required);
1958 model.apply(CallUpdate::Recording(false));
1959 assert!(!model.recording);
1960 }
1961
1962 #[test]
1963 fn a_whiteboard_share_names_the_presenter_and_offers_the_browser_only_with_a_link() {
1964 let mut model = meeting_with_me();
1965 model.apply(CallUpdate::Roster(vec![entry(
1966 "8:orgid:ana",
1967 "Ana",
1968 false,
1969 false,
1970 )]));
1971 assert_eq!(model.whiteboard_label(), None);
1972 let share = |presenter: &str, url: Option<&str>| calling::ContentShare {
1973 session_id: "s".into(),
1974 presenter: Some(presenter.into()),
1975 subject: "Whiteboard".into(),
1976 url: url.map(str::to_owned),
1977 whiteboard: true,
1978 };
1979 model.apply(CallUpdate::Whiteboard(Some(share(
1980 "8:orgid:ana",
1981 Some("https://app.whiteboard.microsoft.com/x"),
1982 ))));
1983 assert_eq!(
1984 model.whiteboard_label().as_deref(),
1985 Some("Ana is sharing a whiteboard")
1986 );
1987 assert_eq!(
1988 model.whiteboard_url(),
1989 Some("https://app.whiteboard.microsoft.com/x")
1990 );
1991 model.apply(CallUpdate::Whiteboard(Some(share(
1992 "8:orgid:stranger",
1993 None,
1994 ))));
1995 assert_eq!(
1996 model.whiteboard_label().as_deref(),
1997 Some("Someone is sharing a whiteboard")
1998 );
1999 assert_eq!(model.whiteboard_url(), None);
2000 model.apply(CallUpdate::Whiteboard(None));
2001 assert_eq!(model.whiteboard_label(), None);
2002 }
2003
2004 #[test]
2005 fn a_consultation_can_transfer_once_connected_with_a_replacement_link() {
2006 let (handle, _control) = calling::call_channel();
2007 let mut consult = ConsultCall {
2008 id: 3,
2009 target: ("8:orgid:ana".into(), "Ana".into()),
2010 commands: handle.commands,
2011 state: CallState::Connecting,
2012 replacement: None,
2013 transferring: false,
2014 };
2015 assert_eq!(consult.status_text(), "Calling Ana...");
2016 assert!(!consult.ready_to_transfer());
2017 consult.state = CallState::Connected {
2018 since: Instant::now(),
2019 };
2020 assert_eq!(consult.status_text(), "Consulting Ana");
2021 assert!(!consult.ready_to_transfer());
2022 consult.replacement = Some("https://cc/replacement".into());
2023 assert!(consult.ready_to_transfer());
2024 }
2025}