BlueGit

ict rusty-teams

Files

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

model.rs

model.rs 49.1 KiB Download Raw
1use std::sync::Arc;
2use std::time::{Duration, Instant};
3
4use calling::{
5 CallCommand, CallState, CallUpdate, CameraDevice, CaptionEntry, CaptionState, ContentShare, DeviceChoice, DeviceLists, EndKind, EndReason,
6 HoldState, MeetingTarget, Progress, Reaction, RosterEntry, ShareKind, ShareSource, SpeakingDetector, VideoHub,
7};
8use tokio::sync::mpsc::UnboundedSender;
9
10use super::background::BackgroundPick;
11use super::pictures::CallPictures;
12
13pub const TEST_CALL_TITLE: &str = "Test call";
14pub const ECHO_NAME: &str = "Teams echo";
15pub const ECHO_MRI: &str = calling::signaling::ECHO_BOT_MRI;
16pub const MAX_TILES: usize = 9;
17const ORGID_PREFIX: &str = "8:orgid:";
18const WIDE_TILES: usize = 2;
19const MEDIUM_TILES: usize = 4;
20pub const REACTION_SHOWN: Duration = Duration::from_secs(3);
21pub const CHAT_OPEN_TILES: usize = 6;
22pub const CAPTION_SHOWN: Duration = Duration::from_secs(4);
23const CAPTION_LINES: usize = 2;
24
25pub struct ActiveCall {
26 pub id: u64,
27 pub model: CallModel,
28 pub commands: UnboundedSender<CallCommand>,
29 pub viewing: bool,
30 pub conversation_id: Option<String>,
31 pub video: Arc<VideoHub>,
32 pub pictures: CallPictures,
33 pub stage_fullscreen: bool,
34 pub chat_open: bool,
35 pub meeting_target: Option<MeetingTarget>,
36 pub pending_move: Option<PendingMove>,
37 pub consult: Option<ConsultCall>,
38}
39
40#[derive(Debug, Clone, PartialEq)]
41pub struct PendingMove {
42 pub target: MeetingTarget,
43 pub title: String,
44 pub breakout: Option<BreakoutState>,
45}
46
47pub struct ConsultCall {
48 pub id: u64,
49 pub target: (String, String),
50 pub commands: UnboundedSender<CallCommand>,
51 pub state: CallState,
52 pub replacement: Option<String>,
53 pub transferring: bool,
54}
55
56impl ConsultCall {
57 pub fn connected(&self) -> bool {
58 matches!(self.state, CallState::Connected { .. })
59 }
60
61 pub fn ready_to_transfer(&self) -> bool {
62 self.connected() && self.replacement.is_some()
63 }
64
65 pub fn status_text(&self) -> String {
66 let name = &self.target.1;
67 match &self.state {
68 CallState::Connected { .. } => format!("Consulting {name}"),
69 _ => format!("Calling {name}..."),
70 }
71 }
72}
73
74impl ActiveCall {
75 pub fn new(id: u64, model: CallModel, commands: UnboundedSender<CallCommand>, conversation_id: Option<String>, video: Arc<VideoHub>) -> Self {
76 ActiveCall {
77 id,
78 model,
79 commands,
80 viewing: true,
81 conversation_id,
82 video,
83 pictures: CallPictures::default(),
84 stage_fullscreen: false,
85 chat_open: false,
86 meeting_target: None,
87 pending_move: None,
88 consult: None,
89 }
90 }
91
92 pub fn chat_thread(&self) -> Option<&str> {
93 chat_thread(self.model.kind, self.model.meeting_chat.as_deref(), self.conversation_id.as_deref())
94 }
95}
96
97pub fn chat_thread<'a>(kind: CallKind, meeting_chat: Option<&'a str>, conversation_id: Option<&'a str>) -> Option<&'a str> {
98 match kind {
99 CallKind::Meeting => meeting_chat.or(conversation_id),
100 CallKind::Test | CallKind::Direct | CallKind::Group => conversation_id,
101 }
102}
103
104#[derive(Debug, Clone, Copy, PartialEq, Eq)]
105pub enum CallKind {
106 Test,
107 Direct,
108 Group,
109 Meeting,
110}
111
112#[derive(Debug, Clone, Copy, PartialEq, Eq)]
113pub enum TileState {
114 Invited,
115 Present,
116 InLobby,
117 Left,
118}
119
120#[derive(Debug, Clone, PartialEq, Eq)]
121pub struct Tile {
122 pub mri: String,
123 pub user_id: Option<String>,
124 pub name: String,
125 pub muted: bool,
126 pub state: TileState,
127 pub invited: bool,
128 pub has_video: bool,
129 pub hand: Option<u64>,
130 pub spotlight: Option<u64>,
131}
132
133impl Tile {
134 pub fn invited(mri: &str, name: &str) -> Tile {
135 Tile {
136 mri: mri.to_owned(),
137 user_id: mri.strip_prefix(ORGID_PREFIX).map(str::to_owned),
138 name: name.to_owned(),
139 muted: false,
140 state: TileState::Invited,
141 invited: true,
142 has_video: false,
143 hand: None,
144 spotlight: None,
145 }
146 }
147}
148
149#[derive(Debug, Clone, PartialEq)]
150pub struct BreakoutState {
151 pub room_name: String,
152 pub main: Option<MeetingTarget>,
153 pub main_title: String,
154}
155
156#[derive(Debug, Clone, PartialEq, Eq)]
157pub struct Focus {
158 pub mri: String,
159 pub own: bool,
160 pub spotlight: bool,
161 pub pinned: bool,
162}
163
164#[derive(Debug, Clone, PartialEq, Eq)]
165pub struct CaptionLine {
166 pub id: String,
167 pub speaker: String,
168 pub text: String,
169 pub at: Instant,
170}
171
172#[derive(Debug, Clone, Copy, PartialEq, Eq)]
173pub struct GridLayout {
174 pub shown_others: usize,
175 pub hidden: usize,
176}
177
178pub fn grid_layout(others: usize, max_tiles: usize) -> GridLayout {
179 let total = others + 1;
180 if total <= max_tiles {
181 return GridLayout {
182 shown_others: others,
183 hidden: 0,
184 };
185 }
186 let shown_others = max_tiles - 2;
187 GridLayout {
188 shown_others,
189 hidden: others - shown_others,
190 }
191}
192
193#[derive(Debug, Clone, Copy, PartialEq)]
194pub struct TileSize {
195 pub width: f32,
196 pub height: f32,
197 pub avatar: f32,
198}
199
200pub fn tile_size(cells: usize) -> TileSize {
201 if cells <= WIDE_TILES {
202 TileSize {
203 width: 260.,
204 height: 210.,
205 avatar: 96.,
206 }
207 } else if cells <= MEDIUM_TILES {
208 TileSize {
209 width: 220.,
210 height: 180.,
211 avatar: 72.,
212 }
213 } else {
214 TileSize {
215 width: 190.,
216 height: 150.,
217 avatar: 56.,
218 }
219 }
220}
221
222#[derive(Debug, Clone, PartialEq, Eq)]
223pub struct ReactionChip {
224 pub mri: String,
225 pub reaction: Reaction,
226 pub since: Instant,
227 pub serial: u64,
228}
229
230#[derive(Debug, Clone)]
231pub struct CallModel {
232 pub title: String,
233 pub kind: CallKind,
234 pub peer_name: String,
235 pub state: CallState,
236 pub progress: Option<Progress>,
237 pub muted: bool,
238 pub listen_only: bool,
239 pub lobby: bool,
240 pub can_end_meeting: bool,
241 pub incoming: bool,
242 pub input: DeviceChoice,
243 pub output: DeviceChoice,
244 pub devices: DeviceLists,
245 pub local_speaking: bool,
246 pub remote_speaking: bool,
247 pub speaking_mris: Vec<String>,
248 pub connected_since: Option<Instant>,
249 pub own_mri: Option<String>,
250 pub tiles: Vec<Tile>,
251 pub screen_sharer: Option<String>,
252 pub camera_on: bool,
253 pub cameras: Vec<CameraDevice>,
254 pub camera: DeviceChoice,
255 pub local_share: Option<String>,
256 pub share_sources: Vec<ShareSource>,
257 pub share_sound: bool,
258 pub own_hand: Option<u64>,
259 pub own_spotlight: Option<u64>,
260 pub organizer: bool,
261 pub pinned: Option<String>,
262 pub captions: CaptionState,
263 pub caption_lines: Vec<CaptionLine>,
264 pub background: BackgroundPick,
265 pub recording: bool,
266 pub consent_required: bool,
267 pub hold: HoldState,
268 pub whiteboard: Option<ContentShare>,
269 pub breakout: Option<BreakoutState>,
270 pub main_meeting: Option<MeetingTarget>,
271 pub reactions: Vec<ReactionChip>,
272 reaction_serial: u64,
273 pub meeting_chat: Option<String>,
274 local_detector: SpeakingDetector,
275 remote_detector: SpeakingDetector,
276}
277
278impl CallModel {
279 fn base(kind: CallKind, title: &str, peer_name: &str, tiles: Vec<Tile>) -> Self {
280 CallModel {
281 title: title.to_owned(),
282 kind,
283 peer_name: peer_name.to_owned(),
284 state: CallState::Connecting,
285 progress: None,
286 muted: false,
287 listen_only: false,
288 lobby: false,
289 can_end_meeting: false,
290 incoming: false,
291 input: DeviceChoice::SystemDefault,
292 output: DeviceChoice::SystemDefault,
293 devices: DeviceLists::default(),
294 local_speaking: false,
295 remote_speaking: false,
296 speaking_mris: Vec::new(),
297 connected_since: None,
298 own_mri: None,
299 tiles,
300 screen_sharer: None,
301 camera_on: false,
302 cameras: Vec::new(),
303 camera: DeviceChoice::SystemDefault,
304 local_share: None,
305 share_sources: Vec::new(),
306 share_sound: false,
307 own_hand: None,
308 own_spotlight: None,
309 organizer: false,
310 pinned: None,
311 captions: CaptionState::Off,
312 caption_lines: Vec::new(),
313 background: BackgroundPick::None,
314 recording: false,
315 consent_required: false,
316 hold: HoldState::Active,
317 whiteboard: None,
318 breakout: None,
319 main_meeting: None,
320 reactions: Vec::new(),
321 reaction_serial: 0,
322 meeting_chat: None,
323 local_detector: SpeakingDetector::default(),
324 remote_detector: SpeakingDetector::default(),
325 }
326 }
327
328 pub fn test() -> Self {
329 Self::base(
330 CallKind::Test,
331 TEST_CALL_TITLE,
332 ECHO_NAME,
333 vec![Tile::invited(ECHO_MRI, ECHO_NAME)],
334 )
335 }
336
337 pub fn people(title: &str, callees: &[(String, String)]) -> Self {
338 let kind = if callees.len() == 1 { CallKind::Direct } else { CallKind::Group };
339 let peer_name = match callees {
340 [(_, name)] => name.clone(),
341 _ => title.to_owned(),
342 };
343 let tiles = callees.iter().map(|(mri, name)| Tile::invited(mri, name)).collect();
344 Self::base(kind, title, &peer_name, tiles)
345 }
346
347 pub fn meeting(title: &str, can_end_meeting: bool) -> Self {
348 let mut model = Self::base(CallKind::Meeting, title, title, Vec::new());
349 model.can_end_meeting = can_end_meeting;
350 model
351 }
352
353 pub fn incoming(title: &str, caller_mri: &str, caller_name: &str) -> Self {
354 let mut model = Self::base(
355 CallKind::Direct,
356 title,
357 caller_name,
358 vec![Tile {
359 state: TileState::Present,
360 ..Tile::invited(caller_mri, caller_name)
361 }],
362 );
363 model.incoming = true;
364 model
365 }
366
367 pub fn apply(&mut self, update: CallUpdate) {
368 match update {
369 CallUpdate::State(state) => {
370 if let Some(since) = state.started_at() {
371 self.connected_since = Some(since);
372 }
373 if !matches!(state, CallState::Connected { .. }) {
374 self.silence();
375 }
376 self.state = state;
377 }
378 CallUpdate::Muted(muted) => {
379 self.muted = muted;
380 if muted {
381 self.local_speaking = false;
382 self.local_detector.reset();
383 }
384 }
385 CallUpdate::Levels { local, remote } => {
386 self.local_speaking = !self.muted && self.local_detector.update(local);
387 self.remote_speaking = self.remote_detector.update(remote);
388 }
389 CallUpdate::Devices(devices) => self.devices = devices,
390 CallUpdate::Selected { input, output } => {
391 self.input = input;
392 self.output = output;
393 }
394 CallUpdate::ListenOnly(listen_only) => self.listen_only = listen_only,
395 CallUpdate::Stats { .. } => {}
396 CallUpdate::Progress(progress) => self.progress = Some(progress),
397 CallUpdate::Roster(entries) => self.apply_roster(&entries),
398 CallUpdate::Speakers(mris) => self.speaking_mris = mris,
399 CallUpdate::Lobby(lobby) => self.lobby = lobby,
400 CallUpdate::OwnIdentity { mri } => self.own_mri = Some(mri),
401 CallUpdate::ScreenShare(sharer) => self.screen_sharer = sharer,
402 CallUpdate::VideoReady | CallUpdate::Notice(_) => {}
403 CallUpdate::Camera(on) => self.camera_on = on,
404 CallUpdate::Cameras(cameras) => self.cameras = cameras,
405 CallUpdate::LocalShare(label) => {
406 if label.is_none() {
407 self.share_sound = false;
408 }
409 self.local_share = label;
410 }
411 CallUpdate::ShareSources(sources) => self.share_sources = sources,
412 CallUpdate::ShareSound(active) => self.share_sound = active,
413 CallUpdate::Reaction { mri, reaction } => self.note_reaction(mri, reaction, Instant::now()),
414 CallUpdate::MeetingChat(thread) => self.meeting_chat = Some(thread),
415 CallUpdate::Captions(state) => {
416 if state != CaptionState::On {
417 self.caption_lines.clear();
418 }
419 self.captions = state;
420 }
421 CallUpdate::Caption(entry) => self.note_caption(entry, Instant::now()),
422 CallUpdate::Recording(on) => self.recording = on,
423 CallUpdate::ConsentRequired(required) => self.consent_required = required,
424 CallUpdate::Hold(hold) => self.hold = hold,
425 CallUpdate::Whiteboard(share) => self.whiteboard = share,
426 CallUpdate::BreakoutRoom { main } => self.main_meeting = Some(main),
427 CallUpdate::BlurTiming(_)
428 | CallUpdate::Organizer { .. }
429 | CallUpdate::WhiteboardUrl(_)
430 | CallUpdate::BreakoutMove(_)
431 | CallUpdate::ReplacementLink(_) => {}
432 }
433 }
434
435 pub fn note_caption(&mut self, entry: CaptionEntry, at: Instant) {
436 if self.captions == CaptionState::Off {
437 return;
438 }
439 let speaker = if entry.display_name.is_empty() { "Someone".to_owned() } else { entry.display_name };
440 let line = CaptionLine { id: entry.id, speaker, text: entry.text, at };
441 match self.caption_lines.last_mut() {
442 Some(last) if last.id == line.id => *last = line,
443 _ => self.caption_lines.push(line),
444 }
445 let surplus = self.caption_lines.len().saturating_sub(CAPTION_LINES);
446 self.caption_lines.drain(..surplus);
447 }
448
449 pub fn visible_captions(&self, now: Instant) -> Vec<&CaptionLine> {
450 self.caption_lines.iter().filter(|line| now.saturating_duration_since(line.at) < CAPTION_SHOWN).collect()
451 }
452
453 pub fn captions_on(&self) -> bool {
454 matches!(self.captions, CaptionState::Starting | CaptionState::On)
455 }
456
457 fn silence(&mut self) {
458 self.local_speaking = false;
459 self.remote_speaking = false;
460 self.speaking_mris.clear();
461 self.local_detector.reset();
462 self.remote_detector.reset();
463 }
464
465 pub fn note_reaction(&mut self, mri: String, reaction: Reaction, at: Instant) {
466 self.reactions.retain(|chip| chip.mri != mri && at.saturating_duration_since(chip.since) < REACTION_SHOWN);
467 self.reaction_serial += 1;
468 self.reactions.push(ReactionChip { mri, reaction, since: at, serial: self.reaction_serial });
469 }
470
471 pub fn chip_of(&self, mri: &str, now: Instant) -> Option<&ReactionChip> {
472 self.reactions
473 .iter()
474 .find(|chip| chip.mri == mri && now.saturating_duration_since(chip.since) < REACTION_SHOWN)
475 }
476
477 pub fn own_chip(&self, now: Instant) -> Option<&ReactionChip> {
478 self.chip_of(self.own_mri.as_deref()?, now)
479 }
480
481 pub fn hand_position(&self, rank: u64) -> usize {
482 let raised = self.tiles.iter().filter_map(|tile| tile.hand).chain(self.own_hand);
483 1 + raised.filter(|other| *other < rank).count()
484 }
485
486 pub fn can_manage(&self) -> bool {
487 self.can_end_meeting || self.organizer
488 }
489
490 pub fn organizes_meeting(&self) -> bool {
491 self.kind == CallKind::Meeting && self.can_manage()
492 }
493
494 pub fn can_lower_hands(&self) -> bool {
495 self.can_manage()
496 }
497
498 pub fn lobby_guests(&self) -> Vec<&Tile> {
499 self.tiles.iter().filter(|tile| tile.state == TileState::InLobby).collect()
500 }
501
502 pub fn can_admit(&self) -> bool {
503 self.can_manage() && self.is_live() && !self.lobby
504 }
505
506 pub fn is_pinned(&self, mri: &str) -> bool {
507 self.pinned.as_deref() == Some(mri)
508 }
509
510 pub fn toggle_pin(&mut self, mri: &str) {
511 self.pinned = if self.is_pinned(mri) { None } else { Some(mri.to_owned()) };
512 }
513
514 pub fn is_spotlighted(&self, mri: &str) -> bool {
515 self.own_mri.as_deref() == Some(mri) && self.own_spotlight.is_some()
516 || self.tiles.iter().any(|tile| tile.mri == mri && tile.spotlight.is_some())
517 }
518
519 pub fn focus(&self) -> Option<Focus> {
520 let own = |mri: &str| self.own_mri.as_deref() == Some(mri);
521 let on_stage = |mri: &str| own(mri) || self.visible_tiles().iter().any(|tile| tile.mri == mri && tile.state == TileState::Present);
522 if let Some(pinned) = self.pinned.as_deref().filter(|mri| on_stage(mri)) {
523 return Some(Focus { mri: pinned.to_owned(), own: own(pinned), spotlight: self.is_spotlighted(pinned), pinned: true });
524 }
525 let remote = self.tiles.iter().filter(|tile| tile.state == TileState::Present).filter_map(|tile| Some((tile.spotlight?, tile.mri.as_str())));
526 let (_, mri) = remote.chain(self.own_spotlight.zip(self.own_mri.as_deref())).min_by_key(|(rank, _)| *rank)?;
527 Some(Focus { mri: mri.to_owned(), own: own(mri), spotlight: true, pinned: false })
528 }
529
530 pub fn any_hand_raised(&self) -> bool {
531 self.own_hand.is_some() || self.tiles.iter().any(|tile| tile.hand.is_some())
532 }
533
534 pub fn own_cell_index(&self, remote_cells: usize) -> usize {
535 let Some(own) = self.own_hand else { return remote_cells };
536 let ahead = self.visible_tiles().iter().filter(|tile| tile.hand.is_some_and(|rank| rank < own)).count();
537 ahead.min(remote_cells)
538 }
539
540 fn apply_roster(&mut self, entries: &[RosterEntry]) {
541 let own_entry = entries.iter().find(|entry| Some(&entry.mri) == self.own_mri.as_ref());
542 self.own_hand = own_entry.and_then(|entry| entry.hand.as_ref().map(|hand| hand.rank));
543 self.own_spotlight = own_entry.and_then(|entry| entry.spotlight.as_ref().map(|spotlight| spotlight.rank));
544 if let Some(entry) = own_entry {
545 self.organizer = entry.organizer;
546 }
547 for entry in entries.iter().filter(|entry| Some(&entry.mri) != self.own_mri.as_ref()) {
548 let state = if entry.in_lobby { TileState::InLobby } else { TileState::Present };
549 match self.tiles.iter_mut().find(|tile| tile.mri == entry.mri) {
550 Some(tile) => {
551 tile.state = state;
552 tile.muted = entry.muted;
553 tile.has_video = entry.has_video;
554 tile.hand = entry.hand.as_ref().map(|hand| hand.rank);
555 tile.spotlight = entry.spotlight.as_ref().map(|spotlight| spotlight.rank);
556 if tile.name.is_empty() {
557 tile.name = entry.display_name.clone();
558 }
559 }
560 None => self.tiles.push(Tile {
561 mri: entry.mri.clone(),
562 user_id: entry.mri.strip_prefix(ORGID_PREFIX).map(str::to_owned),
563 name: entry.display_name.clone(),
564 muted: entry.muted,
565 state,
566 invited: false,
567 has_video: entry.has_video,
568 hand: entry.hand.as_ref().map(|hand| hand.rank),
569 spotlight: entry.spotlight.as_ref().map(|spotlight| spotlight.rank),
570 }),
571 }
572 }
573 let own_mri = self.own_mri.clone();
574 let listed = |mri: &str| entries.iter().any(|entry| entry.mri == mri);
575 if self.pinned.as_deref().is_some_and(|mri| !listed(mri) && Some(mri) != own_mri.as_deref()) {
576 self.pinned = None;
577 }
578 self.tiles.retain_mut(|tile| {
579 if listed(&tile.mri) || Some(&tile.mri) == own_mri.as_ref() {
580 return true;
581 }
582 match (tile.invited, tile.state) {
583 (true, TileState::Invited) => true,
584 (true, _) => {
585 tile.state = TileState::Left;
586 true
587 }
588 (false, _) => false,
589 }
590 });
591 }
592
593 pub fn visible_tiles(&self) -> Vec<&Tile> {
594 let mut tiles: Vec<&Tile> = self.tiles.iter().filter(|tile| tile.state != TileState::InLobby).collect();
595 tiles.sort_by_key(|tile| {
596 let state = match tile.state {
597 TileState::Present => 0,
598 TileState::Invited => 1,
599 _ => 2,
600 };
601 (!self.is_pinned(&tile.mri), tile.hand.is_none(), tile.hand.unwrap_or(0), state)
602 });
603 tiles
604 }
605
606 pub fn strip_tiles(&self) -> Vec<&Tile> {
607 let mut tiles = self.visible_tiles();
608 tiles.sort_by_key(|tile| (!self.is_pinned(&tile.mri), tile.hand.is_none(), tile.hand.unwrap_or(0), !self.tile_speaking(tile)));
609 tiles
610 }
611
612 pub fn sharing_label(&self) -> Option<String> {
613 let sharer = self.screen_sharer.as_ref()?;
614 let name = self
615 .tiles
616 .iter()
617 .find(|tile| &tile.mri == sharer)
618 .map(|tile| tile.name.as_str())
619 .filter(|name| !name.is_empty())
620 .unwrap_or("Someone");
621 Some(format!("{name} is sharing"))
622 }
623
624 pub fn whiteboard_label(&self) -> Option<String> {
625 let share = self.whiteboard.as_ref()?;
626 let name = share
627 .presenter
628 .as_deref()
629 .and_then(|presenter| self.tiles.iter().find(|tile| tile.mri == presenter))
630 .map(|tile| tile.name.as_str())
631 .filter(|name| !name.is_empty())
632 .unwrap_or("Someone");
633 Some(format!("{name} is sharing a whiteboard"))
634 }
635
636 pub fn whiteboard_url(&self) -> Option<&str> {
637 self.whiteboard.as_ref()?.url.as_deref()
638 }
639
640 pub fn is_one_to_one(&self) -> bool {
641 self.kind == CallKind::Direct
642 }
643
644 pub fn can_hold(&self) -> bool {
645 self.is_one_to_one() && self.is_live() && self.hold != HoldState::Remote
646 }
647
648 pub fn can_transfer(&self) -> bool {
649 self.is_one_to_one() && self.is_live() && self.hold == HoldState::Active
650 }
651
652 pub fn can_record(&self) -> bool {
653 self.organizes_meeting() && self.is_live() && !self.lobby
654 }
655
656 pub fn can_open_whiteboard(&self) -> bool {
657 self.kind == CallKind::Meeting && self.is_live() && !self.lobby
658 }
659
660 pub fn tile_speaking(&self, tile: &Tile) -> bool {
661 if self.speaking_mris.contains(&tile.mri) {
662 return true;
663 }
664 let only_remote = self.tiles.len() == 1;
665 only_remote && tile.state != TileState::Left && self.remote_speaking
666 }
667
668 pub fn tile_caption(&self, tile: &Tile) -> Option<&'static str> {
669 match tile.state {
670 TileState::Invited => Some(match self.progress {
671 Some(Progress::Ringing) => "Ringing",
672 _ => "Calling...",
673 }),
674 TileState::Left => Some("Left"),
675 TileState::Present | TileState::InLobby => None,
676 }
677 }
678
679 pub fn elapsed(&self, now: Instant) -> Option<Duration> {
680 self.connected_since
681 .map(|since| now.saturating_duration_since(since))
682 }
683
684 pub fn connecting_text(&self) -> &'static str {
685 match (self.kind, self.progress) {
686 (CallKind::Meeting, _) => "Joining...",
687 (_, _) if self.incoming => "Connecting...",
688 (_, Some(Progress::Ringing)) => "Ringing",
689 _ => "Calling...",
690 }
691 }
692
693 pub fn is_active(&self) -> bool {
694 matches!(
695 self.state,
696 CallState::Connecting | CallState::Connected { .. } | CallState::Reconnecting { .. }
697 )
698 }
699
700 pub fn is_connecting(&self) -> bool {
701 matches!(self.state, CallState::Connecting)
702 }
703
704 pub fn is_reconnecting(&self) -> bool {
705 matches!(self.state, CallState::Reconnecting { .. })
706 }
707
708 pub fn ended_reason(&self) -> Option<&EndReason> {
709 match &self.state {
710 CallState::Ended { reason } => Some(reason),
711 _ => None,
712 }
713 }
714
715 pub fn timer_text(&self, now: Instant) -> String {
716 self.elapsed(now).map(format_elapsed).unwrap_or_default()
717 }
718
719 pub fn can_react(&self) -> bool {
720 self.is_live() && !self.lobby
721 }
722
723 pub fn can_use_camera(&self) -> bool {
724 !self.cameras.is_empty()
725 }
726
727 pub fn can_share(&self) -> bool {
728 !self.share_sources.is_empty() && self.is_live()
729 }
730
731 fn is_live(&self) -> bool {
732 matches!(self.state, CallState::Connected { .. } | CallState::Reconnecting { .. })
733 }
734
735 pub fn screens(&self) -> Vec<&ShareSource> {
736 self.share_sources.iter().filter(|source| source.kind == ShareKind::Screen).collect()
737 }
738
739 pub fn windows(&self) -> Vec<&ShareSource> {
740 self.share_sources.iter().filter(|source| source.kind == ShareKind::Window).collect()
741 }
742
743 pub fn can_unmute(&self) -> bool {
744 !self.listen_only
745 }
746}
747
748pub fn format_elapsed(elapsed: Duration) -> String {
749 let seconds = elapsed.as_secs();
750 let (hours, minutes, seconds) = (seconds / 3600, seconds / 60 % 60, seconds % 60);
751 if hours > 0 {
752 format!("{hours}:{minutes:02}:{seconds:02}")
753 } else {
754 format!("{minutes:02}:{seconds:02}")
755 }
756}
757
758pub fn ended_notice(reason: &EndReason, elapsed: Option<Duration>, peer_name: &str) -> String {
759 let ended = || match elapsed {
760 Some(elapsed) => format!("Call ended {}", format_elapsed(elapsed)),
761 None => "Call ended".to_owned(),
762 };
763 match reason {
764 EndReason::Cancelled => "Call cancelled".to_owned(),
765 EndReason::Dropped => "Call dropped".to_owned(),
766 EndReason::Failed(message) => format!("Call failed: {message}"),
767 EndReason::LocalHangup => ended(),
768 EndReason::Remote(EndKind::Declined) => format!("{peer_name} declined"),
769 EndReason::Remote(EndKind::NoAnswer) => "No answer".to_owned(),
770 EndReason::Remote(EndKind::Unavailable) => format!("{peer_name} is not available"),
771 EndReason::Remote(_) => ended(),
772 }
773}
774
775#[cfg(test)]
776mod tests {
777 use super::*;
778
779 fn connected_model() -> CallModel {
780 let mut model = CallModel::test();
781 model.apply(CallUpdate::State(CallState::Connected {
782 since: Instant::now(),
783 }));
784 model
785 }
786
787 fn entry(mri: &str, name: &str, muted: bool, in_lobby: bool) -> RosterEntry {
788 RosterEntry {
789 mri: mri.into(),
790 display_name: name.into(),
791 muted,
792 in_lobby,
793 has_video: false,
794 sharing: false,
795 hand: None,
796 spotlight: None,
797 organizer: false,
798 }
799 }
800
801 fn spotlit(mri: &str, name: &str, rank: u64) -> RosterEntry {
802 RosterEntry {
803 spotlight: Some(calling::Spotlight { state_id: format!("sp-{rank}"), rank }),
804 ..entry(mri, name, false, false)
805 }
806 }
807
808 fn organizer_entry(mri: &str) -> RosterEntry {
809 RosterEntry { organizer: true, ..entry(mri, "Me", false, false) }
810 }
811
812 fn raised(mri: &str, name: &str, rank: u64) -> RosterEntry {
813 RosterEntry {
814 hand: Some(calling::RaisedHand { state_id: format!("s-{rank}"), rank }),
815 ..entry(mri, name, false, false)
816 }
817 }
818
819 fn meeting_with_me() -> CallModel {
820 let mut model = CallModel::meeting("Standup", false);
821 model.apply(CallUpdate::OwnIdentity { mri: "8:orgid:me".into() });
822 model
823 }
824
825 #[test]
826 fn elapsed_text_is_minutes_and_seconds() {
827 assert_eq!(format_elapsed(Duration::from_secs(42)), "00:42");
828 assert_eq!(format_elapsed(Duration::from_secs(61)), "01:01");
829 assert_eq!(format_elapsed(Duration::from_secs(3725)), "1:02:05");
830 }
831
832 #[test]
833 fn levels_drive_the_speaking_rings() {
834 let mut model = connected_model();
835 model.apply(CallUpdate::Levels {
836 local: 0.0,
837 remote: 0.4,
838 });
839 assert!(model.remote_speaking);
840 assert!(!model.local_speaking);
841 model.apply(CallUpdate::Levels {
842 local: 0.4,
843 remote: 0.0,
844 });
845 assert!(model.local_speaking);
846 }
847
848 #[test]
849 fn muting_switches_the_local_ring_off_at_once() {
850 let mut model = connected_model();
851 model.apply(CallUpdate::Levels {
852 local: 0.5,
853 remote: 0.0,
854 });
855 assert!(model.local_speaking);
856 model.apply(CallUpdate::Muted(true));
857 assert!(!model.local_speaking);
858 model.apply(CallUpdate::Levels {
859 local: 0.5,
860 remote: 0.0,
861 });
862 assert!(!model.local_speaking);
863 }
864
865 #[test]
866 fn reconnecting_keeps_the_timer_and_clears_the_rings() {
867 let mut model = connected_model();
868 let since = model.connected_since.unwrap();
869 model.apply(CallUpdate::Levels {
870 local: 0.5,
871 remote: 0.5,
872 });
873 model.apply(CallUpdate::State(CallState::Reconnecting { since }));
874 assert!(model.is_reconnecting());
875 assert_eq!(model.connected_since, Some(since));
876 assert!(!model.remote_speaking && !model.local_speaking);
877 }
878
879 #[test]
880 fn notices_for_every_end_reason() {
881 let elapsed = Some(Duration::from_secs(42));
882 let notice = |reason: EndReason, elapsed| ended_notice(&reason, elapsed, "Bea");
883 assert_eq!(notice(EndReason::LocalHangup, elapsed), "Call ended 00:42");
884 assert_eq!(notice(EndReason::Remote(EndKind::Normal), elapsed), "Call ended 00:42");
885 assert_eq!(notice(EndReason::Remote(EndKind::Normal), None), "Call ended");
886 assert_eq!(notice(EndReason::Cancelled, None), "Call cancelled");
887 assert_eq!(notice(EndReason::Dropped, elapsed), "Call dropped");
888 assert_eq!(notice(EndReason::Failed("no route".into()), None), "Call failed: no route");
889 assert_eq!(notice(EndReason::Remote(EndKind::Declined), None), "Bea declined");
890 assert_eq!(notice(EndReason::Remote(EndKind::NoAnswer), None), "No answer");
891 assert_eq!(notice(EndReason::Remote(EndKind::Unavailable), None), "Bea is not available");
892 assert_eq!(notice(EndReason::Remote(EndKind::Cancelled), None), "Call ended");
893 assert_eq!(notice(EndReason::Remote(EndKind::Other), None), "Call ended");
894 assert_eq!(notice(EndReason::Remote(EndKind::AnsweredElsewhere), None), "Call ended");
895 }
896
897 #[test]
898 fn the_connecting_text_follows_the_kind_of_call() {
899 let mut direct = CallModel::people("Bea", &[("8:orgid:b".into(), "Bea".into())]);
900 assert_eq!(direct.connecting_text(), "Calling...");
901 direct.apply(CallUpdate::Progress(Progress::Ringing));
902 assert_eq!(direct.connecting_text(), "Ringing");
903 assert_eq!(CallModel::meeting("Standup", false).connecting_text(), "Joining...");
904 assert_eq!(CallModel::incoming("Bea", "8:orgid:b", "Bea").connecting_text(), "Connecting...");
905 assert_eq!(CallModel::test().connecting_text(), "Calling...");
906 }
907
908 #[test]
909 fn listen_only_blocks_unmuting() {
910 let mut model = connected_model();
911 assert!(model.can_unmute());
912 model.apply(CallUpdate::ListenOnly(true));
913 assert!(!model.can_unmute());
914 }
915
916 #[test]
917 fn callees_start_invited_and_follow_the_progress() {
918 let mut model = CallModel::people("Bea", &[("8:orgid:b".into(), "Bea".into())]);
919 assert_eq!(model.kind, CallKind::Direct);
920 assert_eq!(model.peer_name, "Bea");
921 assert_eq!(model.tile_caption(&model.tiles[0]), Some("Calling..."));
922 model.apply(CallUpdate::Progress(Progress::Ringing));
923 assert_eq!(model.tile_caption(&model.tiles[0]), Some("Ringing"));
924 model.apply(CallUpdate::Roster(vec![entry("8:orgid:b", "Bea", false, false)]));
925 assert_eq!(model.tiles[0].state, TileState::Present);
926 assert_eq!(model.tile_caption(&model.tiles[0]), None);
927 }
928
929 #[test]
930 fn several_callees_make_a_group_call_named_after_the_chat() {
931 let model = CallModel::people(
932 "Retro team",
933 &[("8:orgid:b".into(), "Bea".into()), ("8:orgid:c".into(), "Cy".into())],
934 );
935 assert_eq!(model.kind, CallKind::Group);
936 assert_eq!(model.peer_name, "Retro team");
937 assert_eq!(model.tiles.len(), 2);
938 }
939
940 #[test]
941 fn roster_adds_guests_updates_mute_and_drops_leavers() {
942 let mut model = meeting_with_me();
943 model.apply(CallUpdate::Roster(vec![
944 entry("8:orgid:me", "Me", false, false),
945 entry("8:orgid:a", "Ana", true, false),
946 entry("8:orgid:b", "Bo", false, false),
947 ]));
948 assert_eq!(model.tiles.len(), 2);
949 assert!(model.tiles.iter().find(|tile| tile.name == "Ana").unwrap().muted);
950 model.apply(CallUpdate::Roster(vec![entry("8:orgid:me", "Me", false, false), entry("8:orgid:b", "Bo", false, false)]));
951 assert_eq!(model.tiles.len(), 1);
952 assert_eq!(model.tiles[0].name, "Bo");
953 }
954
955 #[test]
956 fn an_invited_callee_who_leaves_stays_as_left() {
957 let mut model = CallModel::people("Bea", &[("8:orgid:b".into(), "Bea".into())]);
958 model.apply(CallUpdate::Roster(vec![entry("8:orgid:b", "Bea", false, false)]));
959 model.apply(CallUpdate::Roster(Vec::new()));
960 assert_eq!(model.tiles[0].state, TileState::Left);
961 assert_eq!(model.tile_caption(&model.tiles[0]), Some("Left"));
962 }
963
964 #[test]
965 fn lobby_guests_get_no_tile() {
966 let mut model = meeting_with_me();
967 model.apply(CallUpdate::Roster(vec![
968 entry("8:orgid:a", "Ana", false, false),
969 entry("8:orgid:g", "Guest", false, true),
970 ]));
971 let names: Vec<&str> = model.visible_tiles().iter().map(|tile| tile.name.as_str()).collect();
972 assert_eq!(names, vec!["Ana"]);
973 }
974
975 #[test]
976 fn the_lobby_flag_follows_the_call() {
977 let mut model = meeting_with_me();
978 model.apply(CallUpdate::Lobby(true));
979 assert!(model.lobby);
980 model.apply(CallUpdate::Lobby(false));
981 assert!(!model.lobby);
982 }
983
984 #[test]
985 fn speakers_light_their_own_tile_and_a_lone_remote_follows_the_level() {
986 let mut model = meeting_with_me();
987 model.apply(CallUpdate::Roster(vec![
988 entry("8:orgid:a", "Ana", false, false),
989 entry("8:orgid:b", "Bo", false, false),
990 ]));
991 model.apply(CallUpdate::State(CallState::Connected { since: Instant::now() }));
992 model.apply(CallUpdate::Speakers(vec!["8:orgid:b".into()]));
993 let tiles: Vec<Tile> = model.tiles.clone();
994 assert!(!model.tile_speaking(&tiles[0]));
995 assert!(model.tile_speaking(&tiles[1]));
996 let mut lone = CallModel::people("Bea", &[("8:orgid:b".into(), "Bea".into())]);
997 lone.apply(CallUpdate::State(CallState::Connected { since: Instant::now() }));
998 lone.apply(CallUpdate::Levels { local: 0.0, remote: 0.5 });
999 assert!(lone.tile_speaking(&lone.tiles[0].clone()));
1000 }
1001
1002 #[test]
1003 fn more_than_nine_cells_collapse_into_a_plus_n_tile() {
1004 assert_eq!(grid_layout(0, MAX_TILES), GridLayout { shown_others: 0, hidden: 0 });
1005 assert_eq!(grid_layout(8, MAX_TILES), GridLayout { shown_others: 8, hidden: 0 });
1006 assert_eq!(grid_layout(9, MAX_TILES), GridLayout { shown_others: 7, hidden: 2 });
1007 assert_eq!(grid_layout(30, MAX_TILES), GridLayout { shown_others: 7, hidden: 23 });
1008 }
1009
1010 #[test]
1011 fn an_open_chat_panel_leaves_room_for_fewer_tiles() {
1012 assert_eq!(grid_layout(5, CHAT_OPEN_TILES), GridLayout { shown_others: 5, hidden: 0 });
1013 assert_eq!(grid_layout(6, CHAT_OPEN_TILES), GridLayout { shown_others: 4, hidden: 2 });
1014 }
1015
1016 #[test]
1017 fn crowded_calls_get_smaller_tiles() {
1018 assert_eq!(tile_size(2).avatar, 96.);
1019 assert_eq!(tile_size(4).avatar, 72.);
1020 assert_eq!(tile_size(9).avatar, 56.);
1021 }
1022
1023 #[test]
1024 fn the_stage_label_names_the_sharer_and_the_strip_puts_the_speaker_first() {
1025 let mut model = meeting_with_me();
1026 model.apply(CallUpdate::Roster(vec![
1027 entry("8:orgid:a", "Ana", false, false),
1028 entry("8:orgid:b", "Bo", false, false),
1029 ]));
1030 assert_eq!(model.sharing_label(), None);
1031 model.apply(CallUpdate::ScreenShare(Some("8:orgid:b".into())));
1032 assert_eq!(model.sharing_label().as_deref(), Some("Bo is sharing"));
1033 model.apply(CallUpdate::State(CallState::Connected { since: Instant::now() }));
1034 model.apply(CallUpdate::Speakers(vec!["8:orgid:b".into()]));
1035 let names: Vec<&str> = model.strip_tiles().iter().map(|tile| tile.name.as_str()).collect();
1036 assert_eq!(names, vec!["Bo", "Ana"]);
1037 model.apply(CallUpdate::ScreenShare(None));
1038 assert_eq!(model.sharing_label(), None);
1039 }
1040
1041 #[test]
1042 fn roster_entries_carry_the_camera_flag_to_the_tile() {
1043 let mut model = meeting_with_me();
1044 let mut with_camera = entry("8:orgid:a", "Ana", false, false);
1045 with_camera.has_video = true;
1046 model.apply(CallUpdate::Roster(vec![with_camera]));
1047 assert!(model.tiles[0].has_video);
1048 model.apply(CallUpdate::Roster(vec![entry("8:orgid:a", "Ana", false, false)]));
1049 assert!(!model.tiles[0].has_video);
1050 }
1051
1052 #[test]
1053 fn present_guests_sort_before_waiting_ones() {
1054 let mut model = CallModel::people(
1055 "Group",
1056 &[("8:orgid:b".into(), "Bea".into()), ("8:orgid:c".into(), "Cy".into())],
1057 );
1058 model.apply(CallUpdate::Roster(vec![entry("8:orgid:c", "Cy", false, false)]));
1059 let names: Vec<&str> = model.visible_tiles().iter().map(|tile| tile.name.as_str()).collect();
1060 assert_eq!(names, vec!["Cy", "Bea"]);
1061 }
1062
1063 #[test]
1064 fn raised_hands_get_queue_positions_by_raise_time_and_sort_first() {
1065 let mut model = meeting_with_me();
1066 model.apply(CallUpdate::Roster(vec![
1067 entry("8:orgid:a", "Ana", false, false),
1068 raised("8:orgid:b", "Bo", 9),
1069 raised("8:orgid:c", "Cy", 4),
1070 raised("8:orgid:me", "Me", 6),
1071 ]));
1072 assert_eq!(model.own_hand, Some(6));
1073 assert!(model.any_hand_raised());
1074 let names: Vec<&str> = model.visible_tiles().iter().map(|tile| tile.name.as_str()).collect();
1075 assert_eq!(names, vec!["Cy", "Bo", "Ana"]);
1076 let positions: Vec<usize> = [4, 6, 9].into_iter().map(|rank| model.hand_position(rank)).collect();
1077 assert_eq!(positions, vec![1, 2, 3]);
1078 assert_eq!(model.own_cell_index(3), 1);
1079 let strip: Vec<&str> = model.strip_tiles().iter().map(|tile| tile.name.as_str()).collect();
1080 assert_eq!(strip, vec!["Cy", "Bo", "Ana"]);
1081 }
1082
1083 #[test]
1084 fn lowering_clears_the_hand_everywhere() {
1085 let mut model = meeting_with_me();
1086 model.apply(CallUpdate::Roster(vec![raised("8:orgid:a", "Ana", 1), raised("8:orgid:me", "Me", 2)]));
1087 model.apply(CallUpdate::Roster(vec![entry("8:orgid:a", "Ana", false, false), entry("8:orgid:me", "Me", false, false)]));
1088 assert!(!model.any_hand_raised());
1089 assert_eq!(model.own_cell_index(1), 1);
1090 }
1091
1092 #[test]
1093 fn only_organizers_may_lower_hands() {
1094 assert!(!CallModel::meeting("Standup", false).can_lower_hands());
1095 assert!(CallModel::meeting("Standup", true).can_lower_hands());
1096 }
1097
1098 #[test]
1099 fn a_reaction_shows_for_three_seconds_on_its_sender_and_the_latest_wins() {
1100 let mut model = meeting_with_me();
1101 let start = Instant::now();
1102 model.note_reaction("8:orgid:a".into(), Reaction::Heart, start);
1103 model.note_reaction("8:orgid:me".into(), Reaction::Like, start);
1104 let reaction_at = |model: &CallModel, mri: &str, seconds: u64| {
1105 model.chip_of(mri, start + Duration::from_secs(seconds)).map(|chip| chip.reaction)
1106 };
1107 assert_eq!(reaction_at(&model, "8:orgid:a", 2), Some(Reaction::Heart));
1108 assert_eq!(model.own_chip(start + Duration::from_secs(2)).map(|chip| chip.reaction), Some(Reaction::Like));
1109 assert_eq!(reaction_at(&model, "8:orgid:a", 3), None);
1110 model.note_reaction("8:orgid:a".into(), Reaction::Laugh, start + Duration::from_secs(1));
1111 assert_eq!(reaction_at(&model, "8:orgid:a", 2), Some(Reaction::Laugh));
1112 assert_eq!(model.reactions.len(), 2);
1113 }
1114
1115 #[test]
1116 fn the_chat_panel_picks_the_meeting_thread_or_the_call_chat() {
1117 assert_eq!(chat_thread(CallKind::Meeting, Some("19:meeting_x"), Some("19:list")), Some("19:meeting_x"));
1118 assert_eq!(chat_thread(CallKind::Meeting, None, Some("19:list")), Some("19:list"));
1119 assert_eq!(chat_thread(CallKind::Direct, Some("19:meeting_x"), Some("19:dm")), Some("19:dm"));
1120 assert_eq!(chat_thread(CallKind::Group, None, Some("19:group")), Some("19:group"));
1121 assert_eq!(chat_thread(CallKind::Test, None, None), None);
1122 }
1123
1124 #[test]
1125 fn computer_sound_follows_the_share() {
1126 let mut model = connected_model();
1127 model.apply(CallUpdate::LocalShare(Some("Screen".into())));
1128 model.apply(CallUpdate::ShareSound(true));
1129 assert!(model.share_sound);
1130 model.apply(CallUpdate::LocalShare(None));
1131 assert!(!model.share_sound);
1132 }
1133
1134 #[test]
1135 fn lobby_guests_are_listed_for_organizers_who_may_admit() {
1136 let mut model = meeting_with_me();
1137 model.apply(CallUpdate::State(CallState::Connected { since: Instant::now() }));
1138 model.apply(CallUpdate::Roster(vec![
1139 entry("8:orgid:a", "Ana", false, false),
1140 entry("8:orgid:g1", "Gast Eins", false, true),
1141 entry("8:orgid:g2", "Gast Zwei", false, true),
1142 ]));
1143 let waiting: Vec<&str> = model.lobby_guests().iter().map(|tile| tile.name.as_str()).collect();
1144 assert_eq!(waiting, vec!["Gast Eins", "Gast Zwei"]);
1145 assert!(!model.can_admit());
1146 model.apply(CallUpdate::Roster(vec![organizer_entry("8:orgid:me"), entry("8:orgid:g1", "Gast Eins", false, true)]));
1147 assert!(model.organizer && model.can_admit() && model.organizes_meeting());
1148 let mut owner = CallModel::meeting("Standup", true);
1149 owner.apply(CallUpdate::State(CallState::Connected { since: Instant::now() }));
1150 assert!(owner.can_admit());
1151 owner.apply(CallUpdate::Lobby(true));
1152 assert!(!owner.can_admit());
1153 }
1154
1155 #[test]
1156 fn a_spotlight_takes_the_stage_and_the_lowest_rank_wins() {
1157 let mut model = meeting_with_me();
1158 model.apply(CallUpdate::Roster(vec![entry("8:orgid:a", "Ana", false, false), spotlit("8:orgid:b", "Bo", 4), spotlit("8:orgid:c", "Cy", 2)]));
1159 assert_eq!(model.focus(), Some(Focus { mri: "8:orgid:c".into(), own: false, spotlight: true, pinned: false }));
1160 assert!(model.is_spotlighted("8:orgid:b") && !model.is_spotlighted("8:orgid:a"));
1161 model.apply(CallUpdate::Roster(vec![entry("8:orgid:a", "Ana", false, false), spotlit("8:orgid:b", "Bo", 4), entry("8:orgid:c", "Cy", false, false)]));
1162 assert_eq!(model.focus().map(|focus| focus.mri), Some("8:orgid:b".to_owned()));
1163 model.apply(CallUpdate::Roster(vec![entry("8:orgid:a", "Ana", false, false)]));
1164 assert_eq!(model.focus(), None);
1165 }
1166
1167 #[test]
1168 fn spotlighting_yourself_puts_your_own_tile_on_the_stage() {
1169 let mut model = meeting_with_me();
1170 model.apply(CallUpdate::Roster(vec![entry("8:orgid:a", "Ana", false, false), spotlit("8:orgid:me", "Me", 1)]));
1171 assert_eq!(model.focus(), Some(Focus { mri: "8:orgid:me".into(), own: true, spotlight: true, pinned: false }));
1172 }
1173
1174 #[test]
1175 fn a_pin_is_local_beats_the_spotlight_and_ends_when_the_person_leaves() {
1176 let mut model = meeting_with_me();
1177 model.apply(CallUpdate::State(CallState::Connected { since: Instant::now() }));
1178 model.apply(CallUpdate::Roster(vec![entry("8:orgid:a", "Ana", false, false), spotlit("8:orgid:b", "Bo", 1)]));
1179 model.toggle_pin("8:orgid:a");
1180 assert_eq!(model.focus(), Some(Focus { mri: "8:orgid:a".into(), own: false, spotlight: false, pinned: true }));
1181 let names: Vec<&str> = model.strip_tiles().iter().map(|tile| tile.name.as_str()).collect();
1182 assert_eq!(names[0], "Ana");
1183 model.toggle_pin("8:orgid:b");
1184 assert_eq!(model.focus().map(|focus| (focus.mri, focus.spotlight, focus.pinned)), Some(("8:orgid:b".to_owned(), true, true)));
1185 model.toggle_pin("8:orgid:b");
1186 assert_eq!(model.pinned, None);
1187 model.toggle_pin("8:orgid:a");
1188 model.apply(CallUpdate::Roster(vec![spotlit("8:orgid:b", "Bo", 1)]));
1189 assert_eq!(model.pinned, None);
1190 }
1191
1192 fn caption(id: &str, speaker: &str, text: &str, is_final: bool) -> CaptionEntry {
1193 CaptionEntry { id: id.into(), user_id: "u".into(), display_name: speaker.into(), text: text.into(), is_final }
1194 }
1195
1196 #[test]
1197 fn captions_keep_two_lines_update_partials_and_fade_after_four_seconds() {
1198 let mut model = meeting_with_me();
1199 let start = Instant::now();
1200 model.note_caption(caption("1", "Ana", "ignored while off", false), start);
1201 assert!(model.caption_lines.is_empty());
1202 model.apply(CallUpdate::Captions(CaptionState::On));
1203 model.note_caption(caption("1", "Ana", "Hello", false), start);
1204 model.note_caption(caption("1", "Ana", "Hello there", true), start);
1205 assert_eq!(model.caption_lines.len(), 1);
1206 assert_eq!(model.caption_lines[0].text, "Hello there");
1207 model.note_caption(caption("2", "", "Next", false), start + Duration::from_secs(1));
1208 model.note_caption(caption("3", "Bo", "Third", false), start + Duration::from_secs(2));
1209 let texts: Vec<&str> = model.caption_lines.iter().map(|line| line.text.as_str()).collect();
1210 assert_eq!(texts, vec!["Next", "Third"]);
1211 assert_eq!(model.caption_lines[0].speaker, "Someone");
1212 assert_eq!(model.visible_captions(start + Duration::from_secs(3)).len(), 2);
1213 assert_eq!(model.visible_captions(start + Duration::from_millis(5500)).len(), 1);
1214 assert!(model.visible_captions(start + Duration::from_secs(7)).is_empty());
1215 model.apply(CallUpdate::Captions(CaptionState::Off));
1216 assert!(model.caption_lines.is_empty() && !model.captions_on());
1217 }
1218
1219 fn one_to_one() -> CallModel {
1220 let mut model = CallModel::people("Bea", &[("8:orgid:bea".into(), "Bea".into())]);
1221 model.apply(CallUpdate::State(CallState::Connected { since: Instant::now() }));
1222 model
1223 }
1224
1225 #[test]
1226 fn hold_and_transfer_belong_to_one_to_one_calls_and_follow_the_hold_state() {
1227 let mut model = one_to_one();
1228 assert!(model.can_hold() && model.can_transfer());
1229 model.apply(CallUpdate::Hold(HoldState::Local));
1230 assert!(model.can_hold() && !model.can_transfer());
1231 model.apply(CallUpdate::Hold(HoldState::Remote));
1232 assert!(!model.can_hold() && !model.can_transfer());
1233 let meeting = meeting_with_me();
1234 assert!(!meeting.can_hold() && !meeting.can_transfer());
1235 assert!(!CallModel::people("Group", &[("8:orgid:a".into(), "A".into()), ("8:orgid:b".into(), "B".into())]).can_hold());
1236 }
1237
1238 #[test]
1239 fn recording_and_consent_follow_the_call_updates_and_only_organizers_may_record() {
1240 let mut model = meeting_with_me();
1241 model.apply(CallUpdate::State(CallState::Connected { since: Instant::now() }));
1242 assert!(!model.can_record());
1243 model.apply(CallUpdate::Roster(vec![organizer_entry("8:orgid:me")]));
1244 assert!(model.can_record());
1245 model.apply(CallUpdate::Recording(true));
1246 model.apply(CallUpdate::ConsentRequired(true));
1247 assert!(model.recording && model.consent_required);
1248 model.apply(CallUpdate::ConsentRequired(false));
1249 assert!(model.recording && !model.consent_required);
1250 model.apply(CallUpdate::Recording(false));
1251 assert!(!model.recording);
1252 }
1253
1254 #[test]
1255 fn a_whiteboard_share_names_the_presenter_and_offers_the_browser_only_with_a_link() {
1256 let mut model = meeting_with_me();
1257 model.apply(CallUpdate::Roster(vec![entry("8:orgid:ana", "Ana", false, false)]));
1258 assert_eq!(model.whiteboard_label(), None);
1259 let share = |presenter: &str, url: Option<&str>| calling::ContentShare {
1260 session_id: "s".into(),
1261 presenter: Some(presenter.into()),
1262 subject: "Whiteboard".into(),
1263 url: url.map(str::to_owned),
1264 whiteboard: true,
1265 };
1266 model.apply(CallUpdate::Whiteboard(Some(share("8:orgid:ana", Some("https://app.whiteboard.microsoft.com/x")))));
1267 assert_eq!(model.whiteboard_label().as_deref(), Some("Ana is sharing a whiteboard"));
1268 assert_eq!(model.whiteboard_url(), Some("https://app.whiteboard.microsoft.com/x"));
1269 model.apply(CallUpdate::Whiteboard(Some(share("8:orgid:stranger", None))));
1270 assert_eq!(model.whiteboard_label().as_deref(), Some("Someone is sharing a whiteboard"));
1271 assert_eq!(model.whiteboard_url(), None);
1272 model.apply(CallUpdate::Whiteboard(None));
1273 assert_eq!(model.whiteboard_label(), None);
1274 }
1275
1276 #[test]
1277 fn a_consultation_can_transfer_once_connected_with_a_replacement_link() {
1278 let (handle, _control) = calling::call_channel();
1279 let mut consult = ConsultCall {
1280 id: 3,
1281 target: ("8:orgid:ana".into(), "Ana".into()),
1282 commands: handle.commands,
1283 state: CallState::Connecting,
1284 replacement: None,
1285 transferring: false,
1286 };
1287 assert_eq!(consult.status_text(), "Calling Ana...");
1288 assert!(!consult.ready_to_transfer());
1289 consult.state = CallState::Connected { since: Instant::now() };
1290 assert_eq!(consult.status_text(), "Consulting Ana");
1291 assert!(!consult.ready_to_transfer());
1292 consult.replacement = Some("https://cc/replacement".into());
1293 assert!(consult.ready_to_transfer());
1294 }
1295}