feat(calls): ringback and ringtone picker, own reactions and hand shown at once, camera test in settings
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@@ -370,12 +370,18 @@ impl AppState {
370
370
counted.unwrap_or_else(|| u32::from(self.sidebar.chats.iter().any(|chat| chat.id == thread && chat.unread)))
371
371
}
372
372
373
pub fn toggle_call_hand(&mut self, _cx: &mut Context<Self>) {
374
let Some(call) = self.call.as_ref().filter(|call| call.model.is_active()) else {
373
pub fn toggle_call_hand(&mut self, cx: &mut Context<Self>) {
374
let Some(call) = self.call.as_mut().filter(|call| call.model.is_active() && call.model.has_reaction_controls()) else {
375
375
return;
376
376
};
377
377
let raised = call.model.own_hand.is_none();
378
call.model.own_hand = raised.then_some(u64::MAX);
378
379
self.send_call_command(CallCommand::SetHand(raised));
380
if raised {
381
self.raise_notice("Your hand is raised".to_owned(), None, cx);
382
}
383
cx.emit(AppEvent::Call);
384
cx.notify();
379
385
}
380
386
381
387
pub fn lower_call_hand(&mut self, mri: String, _cx: &mut Context<Self>) {
@@ -392,11 +398,16 @@ impl AppState {
392
398
}
393
399
}
394
400
395
pub fn send_call_reaction(&mut self, reaction: Reaction, _cx: &mut Context<Self>) {
396
let live = self.call.as_ref().is_some_and(|call| call.model.is_active());
397
if live {
398
self.send_call_command(CallCommand::SendReaction(reaction));
401
pub fn send_call_reaction(&mut self, reaction: Reaction, cx: &mut Context<Self>) {
402
let Some(call) = self.call.as_mut().filter(|call| call.model.is_active() && call.model.has_reaction_controls()) else {
403
return;
404
};
405
if let Some(own_mri) = call.model.own_mri.clone() {
406
call.model.note_reaction(own_mri, reaction, Instant::now());
399
407
}
408
self.send_call_command(CallCommand::SendReaction(reaction));
409
cx.emit(AppEvent::Call);
410
cx.notify();
400
411
}
401
412
402
413
pub fn set_call_share_sound(&mut self, on: bool, cx: &mut Context<Self>) {
@@ -370,12 +370,18 @@ impl AppState {370
counted.unwrap_or_else(|| u32::from(self.sidebar.chats.iter().any(|chat| chat.id == thread && chat.unread)))370
counted.unwrap_or_else(|| u32::from(self.sidebar.chats.iter().any(|chat| chat.id == thread && chat.unread)))371
}371
}372
372
373
pub fn toggle_call_hand(&mut self, _cx: &mut Context<Self>) {373
pub fn toggle_call_hand(&mut self, cx: &mut Context<Self>) {374
let Some(call) = self.call.as_ref().filter(|call| call.model.is_active()) else {374
let Some(call) = self.call.as_mut().filter(|call| call.model.is_active() && call.model.has_reaction_controls()) else {375
return;375
return;376
};376
};377
let raised = call.model.own_hand.is_none();377
let raised = call.model.own_hand.is_none();378
call.model.own_hand = raised.then_some(u64::MAX);378
self.send_call_command(CallCommand::SetHand(raised));379
self.send_call_command(CallCommand::SetHand(raised));380
if raised {381
self.raise_notice("Your hand is raised".to_owned(), None, cx);382
}383
cx.emit(AppEvent::Call);384
cx.notify();379
}385
}380
386
381
pub fn lower_call_hand(&mut self, mri: String, _cx: &mut Context<Self>) {387
pub fn lower_call_hand(&mut self, mri: String, _cx: &mut Context<Self>) {@@ -392,11 +398,16 @@ impl AppState {392
}398
}393
}399
}394
400
395
pub fn send_call_reaction(&mut self, reaction: Reaction, _cx: &mut Context<Self>) {401
pub fn send_call_reaction(&mut self, reaction: Reaction, cx: &mut Context<Self>) {396
let live = self.call.as_ref().is_some_and(|call| call.model.is_active());402
let Some(call) = self.call.as_mut().filter(|call| call.model.is_active() && call.model.has_reaction_controls()) else {397
if live {403
return;398
self.send_call_command(CallCommand::SendReaction(reaction));404
};405
if let Some(own_mri) = call.model.own_mri.clone() {406
call.model.note_reaction(own_mri, reaction, Instant::now());399
}407
}408
self.send_call_command(CallCommand::SendReaction(reaction));409
cx.emit(AppEvent::Call);410
cx.notify();400
}411
}401
412
402
pub fn set_call_share_sound(&mut self, on: bool, cx: &mut Context<Self>) {413
pub fn set_call_share_sound(&mut self, on: bool, cx: &mut Context<Self>) {@@ -8,6 +8,7 @@ mod join;
8
8
mod launcher;
9
9
mod model;
10
10
mod pictures;
11
mod preview;
11
12
mod ring;
12
13
mod target;
13
14
@@ -21,5 +22,6 @@ pub use model::{
21
22
ActiveCall, CAPTION_SHOWN, CHAT_OPEN_TILES, CallKind, CallModel, Focus, GridLayout, MAX_TILES, REACTION_SHOWN, Tile, TileSize, TileState,
22
23
grid_layout, tile_size,
23
24
};
25
pub use preview::{CameraPreview, preview_backgrounds};
24
26
pub use ring::{MissedCall, RingEntry, Rings};
25
27
pub use target::plan_for_chat;
@@ -8,6 +8,7 @@ mod join;8
mod launcher;8
mod launcher;9
mod model;9
mod model;10
mod pictures;10
mod pictures;11
mod preview;11
mod ring;12
mod ring;12
mod target;13
mod target;13
14
@@ -21,5 +22,6 @@ pub use model::{21
ActiveCall, CAPTION_SHOWN, CHAT_OPEN_TILES, CallKind, CallModel, Focus, GridLayout, MAX_TILES, REACTION_SHOWN, Tile, TileSize, TileState,22
ActiveCall, CAPTION_SHOWN, CHAT_OPEN_TILES, CallKind, CallModel, Focus, GridLayout, MAX_TILES, REACTION_SHOWN, Tile, TileSize, TileState,22
grid_layout, tile_size,23
grid_layout, tile_size,23
};24
};25
pub use preview::{CameraPreview, preview_backgrounds};24
pub use ring::{MissedCall, RingEntry, Rings};26
pub use ring::{MissedCall, RingEntry, Rings};25
pub use target::plan_for_chat;27
pub use target::plan_for_chat;@@ -18,6 +18,7 @@ const ORGID_PREFIX: &str = "8:orgid:";
18
18
const WIDE_TILES: usize = 2;
19
19
const MEDIUM_TILES: usize = 4;
20
20
pub const REACTION_SHOWN: Duration = Duration::from_secs(3);
21
const OWN_ECHO_WINDOW: Duration = Duration::from_secs(2);
21
22
pub const CHAT_OPEN_TILES: usize = 6;
22
23
pub const CAPTION_SHOWN: Duration = Duration::from_secs(4);
23
24
const CAPTION_LINES: usize = 2;
@@ -410,6 +411,7 @@ impl CallModel {
410
411
}
411
412
CallUpdate::ShareSources(sources) => self.share_sources = sources,
412
413
CallUpdate::ShareSound(active) => self.share_sound = active,
414
CallUpdate::OwnHand(rank) => self.own_hand = rank,
413
415
CallUpdate::Reaction { mri, reaction } => self.note_reaction(mri, reaction, Instant::now()),
414
416
CallUpdate::MeetingChat(thread) => self.meeting_chat = Some(thread),
415
417
CallUpdate::Captions(state) => {
@@ -463,6 +465,13 @@ impl CallModel {
463
465
}
464
466
465
467
pub fn note_reaction(&mut self, mri: String, reaction: Reaction, at: Instant) {
468
let own_echo = Some(&mri) == self.own_mri.as_ref()
469
&& self.reactions.iter().any(|chip| {
470
chip.mri == mri && chip.reaction == reaction && at.saturating_duration_since(chip.since) < OWN_ECHO_WINDOW
471
});
472
if own_echo {
473
return;
474
}
466
475
self.reactions.retain(|chip| chip.mri != mri && at.saturating_duration_since(chip.since) < REACTION_SHOWN);
467
476
self.reaction_serial += 1;
468
477
self.reactions.push(ReactionChip { mri, reaction, since: at, serial: self.reaction_serial });
@@ -539,7 +548,9 @@ impl CallModel {
539
548
540
549
fn apply_roster(&mut self, entries: &[RosterEntry]) {
541
550
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));
551
if let Some(entry) = own_entry {
552
self.own_hand = entry.hand.as_ref().map(|hand| hand.rank);
553
}
543
554
self.own_spotlight = own_entry.and_then(|entry| entry.spotlight.as_ref().map(|spotlight| spotlight.rank));
544
555
if let Some(entry) = own_entry {
545
556
self.organizer = entry.organizer;
@@ -716,6 +727,10 @@ impl CallModel {
716
727
self.elapsed(now).map(format_elapsed).unwrap_or_default()
717
728
}
718
729
730
pub fn has_reaction_controls(&self) -> bool {
731
self.kind == CallKind::Meeting
732
}
733
719
734
pub fn can_react(&self) -> bool {
720
735
self.is_live() && !self.lobby
721
736
}
@@ -1080,6 +1095,41 @@ mod tests {
1080
1095
assert_eq!(strip, vec!["Cy", "Bo", "Ana"]);
1081
1096
}
1082
1097
1098
#[test]
1099
fn a_roster_without_the_own_entry_keeps_the_own_hand() {
1100
let mut model = meeting_with_me();
1101
model.apply(CallUpdate::OwnHand(Some(5)));
1102
model.apply(CallUpdate::Roster(vec![entry("8:orgid:a", "Ana", false, false)]));
1103
assert_eq!(model.own_hand, Some(5));
1104
model.apply(CallUpdate::Roster(vec![entry("8:orgid:me", "Me", false, false)]));
1105
assert_eq!(model.own_hand, None);
1106
}
1107
1108
#[test]
1109
fn the_server_echo_of_an_own_reaction_does_not_restart_the_chip() {
1110
let mut model = meeting_with_me();
1111
let start = Instant::now();
1112
model.note_reaction("8:orgid:me".into(), Reaction::Like, start);
1113
let serial = model.reactions[0].serial;
1114
model.note_reaction("8:orgid:me".into(), Reaction::Like, start + Duration::from_millis(1500));
1115
assert_eq!(model.reactions.len(), 1);
1116
assert_eq!(model.reactions[0].serial, serial);
1117
model.note_reaction("8:orgid:me".into(), Reaction::Heart, start + Duration::from_millis(1600));
1118
assert_eq!(model.reactions[0].reaction, Reaction::Heart);
1119
model.note_reaction("8:orgid:me".into(), Reaction::Heart, start + Duration::from_secs(4));
1120
assert_ne!(model.reactions[0].serial, serial);
1121
}
1122
1123
#[test]
1124
fn another_persons_repeated_reaction_restarts_the_chip() {
1125
let mut model = meeting_with_me();
1126
let start = Instant::now();
1127
model.note_reaction("8:orgid:a".into(), Reaction::Like, start);
1128
let serial = model.reactions[0].serial;
1129
model.note_reaction("8:orgid:a".into(), Reaction::Like, start + Duration::from_secs(1));
1130
assert_ne!(model.reactions[0].serial, serial);
1131
}
1132
1083
1133
#[test]
1084
1134
fn lowering_clears_the_hand_everywhere() {
1085
1135
let mut model = meeting_with_me();
@@ -18,6 +18,7 @@ const ORGID_PREFIX: &str = "8:orgid:";18
const WIDE_TILES: usize = 2;18
const WIDE_TILES: usize = 2;19
const MEDIUM_TILES: usize = 4;19
const MEDIUM_TILES: usize = 4;20
pub const REACTION_SHOWN: Duration = Duration::from_secs(3);20
pub const REACTION_SHOWN: Duration = Duration::from_secs(3);21
const OWN_ECHO_WINDOW: Duration = Duration::from_secs(2);21
pub const CHAT_OPEN_TILES: usize = 6;22
pub const CHAT_OPEN_TILES: usize = 6;22
pub const CAPTION_SHOWN: Duration = Duration::from_secs(4);23
pub const CAPTION_SHOWN: Duration = Duration::from_secs(4);23
const CAPTION_LINES: usize = 2;24
const CAPTION_LINES: usize = 2;@@ -410,6 +411,7 @@ impl CallModel {410
}411
}411
CallUpdate::ShareSources(sources) => self.share_sources = sources,412
CallUpdate::ShareSources(sources) => self.share_sources = sources,412
CallUpdate::ShareSound(active) => self.share_sound = active,413
CallUpdate::ShareSound(active) => self.share_sound = active,414
CallUpdate::OwnHand(rank) => self.own_hand = rank,413
CallUpdate::Reaction { mri, reaction } => self.note_reaction(mri, reaction, Instant::now()),415
CallUpdate::Reaction { mri, reaction } => self.note_reaction(mri, reaction, Instant::now()),414
CallUpdate::MeetingChat(thread) => self.meeting_chat = Some(thread),416
CallUpdate::MeetingChat(thread) => self.meeting_chat = Some(thread),415
CallUpdate::Captions(state) => {417
CallUpdate::Captions(state) => {@@ -463,6 +465,13 @@ impl CallModel {463
}465
}464
466
465
pub fn note_reaction(&mut self, mri: String, reaction: Reaction, at: Instant) {467
pub fn note_reaction(&mut self, mri: String, reaction: Reaction, at: Instant) {468
let own_echo = Some(&mri) == self.own_mri.as_ref()469
&& self.reactions.iter().any(|chip| {470
chip.mri == mri && chip.reaction == reaction && at.saturating_duration_since(chip.since) < OWN_ECHO_WINDOW471
});472
if own_echo {473
return;474
}466
self.reactions.retain(|chip| chip.mri != mri && at.saturating_duration_since(chip.since) < REACTION_SHOWN);475
self.reactions.retain(|chip| chip.mri != mri && at.saturating_duration_since(chip.since) < REACTION_SHOWN);467
self.reaction_serial += 1;476
self.reaction_serial += 1;468
self.reactions.push(ReactionChip { mri, reaction, since: at, serial: self.reaction_serial });477
self.reactions.push(ReactionChip { mri, reaction, since: at, serial: self.reaction_serial });@@ -539,7 +548,9 @@ impl CallModel {539
548
540
fn apply_roster(&mut self, entries: &[RosterEntry]) {549
fn apply_roster(&mut self, entries: &[RosterEntry]) {541
let own_entry = entries.iter().find(|entry| Some(&entry.mri) == self.own_mri.as_ref());550
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));551
if let Some(entry) = own_entry {552
self.own_hand = entry.hand.as_ref().map(|hand| hand.rank);553
}543
self.own_spotlight = own_entry.and_then(|entry| entry.spotlight.as_ref().map(|spotlight| spotlight.rank));554
self.own_spotlight = own_entry.and_then(|entry| entry.spotlight.as_ref().map(|spotlight| spotlight.rank));544
if let Some(entry) = own_entry {555
if let Some(entry) = own_entry {545
self.organizer = entry.organizer;556
self.organizer = entry.organizer;@@ -716,6 +727,10 @@ impl CallModel {716
self.elapsed(now).map(format_elapsed).unwrap_or_default()727
self.elapsed(now).map(format_elapsed).unwrap_or_default()717
}728
}718
729
730
pub fn has_reaction_controls(&self) -> bool {731
self.kind == CallKind::Meeting732
}733
719
pub fn can_react(&self) -> bool {734
pub fn can_react(&self) -> bool {720
self.is_live() && !self.lobby735
self.is_live() && !self.lobby721
}736
}@@ -1080,6 +1095,41 @@ mod tests {1080
assert_eq!(strip, vec!["Cy", "Bo", "Ana"]);1095
assert_eq!(strip, vec!["Cy", "Bo", "Ana"]);1081
}1096
}1082
1097
1098
#[test]1099
fn a_roster_without_the_own_entry_keeps_the_own_hand() {1100
let mut model = meeting_with_me();1101
model.apply(CallUpdate::OwnHand(Some(5)));1102
model.apply(CallUpdate::Roster(vec![entry("8:orgid:a", "Ana", false, false)]));1103
assert_eq!(model.own_hand, Some(5));1104
model.apply(CallUpdate::Roster(vec![entry("8:orgid:me", "Me", false, false)]));1105
assert_eq!(model.own_hand, None);1106
}1107
1108
#[test]1109
fn the_server_echo_of_an_own_reaction_does_not_restart_the_chip() {1110
let mut model = meeting_with_me();1111
let start = Instant::now();1112
model.note_reaction("8:orgid:me".into(), Reaction::Like, start);1113
let serial = model.reactions[0].serial;1114
model.note_reaction("8:orgid:me".into(), Reaction::Like, start + Duration::from_millis(1500));1115
assert_eq!(model.reactions.len(), 1);1116
assert_eq!(model.reactions[0].serial, serial);1117
model.note_reaction("8:orgid:me".into(), Reaction::Heart, start + Duration::from_millis(1600));1118
assert_eq!(model.reactions[0].reaction, Reaction::Heart);1119
model.note_reaction("8:orgid:me".into(), Reaction::Heart, start + Duration::from_secs(4));1120
assert_ne!(model.reactions[0].serial, serial);1121
}1122
1123
#[test]1124
fn another_persons_repeated_reaction_restarts_the_chip() {1125
let mut model = meeting_with_me();1126
let start = Instant::now();1127
model.note_reaction("8:orgid:a".into(), Reaction::Like, start);1128
let serial = model.reactions[0].serial;1129
model.note_reaction("8:orgid:a".into(), Reaction::Like, start + Duration::from_secs(1));1130
assert_ne!(model.reactions[0].serial, serial);1131
}1132
1083
#[test]1133
#[test]1084
fn lowering_clears_the_hand_everywhere() {1134
fn lowering_clears_the_hand_everywhere() {1085
let mut model = meeting_with_me();1135
let mut model = meeting_with_me();@@ -0,0 +1,184 @@
1
use std::sync::atomic::{AtomicU64, Ordering};
2
use std::sync::{Arc, Mutex};
3
use std::time::{Duration, Instant};
4
5
use calling::background::BackgroundPicture;
6
use calling::blur::BlurSettings;
7
use calling::camera::start_camera;
8
use calling::capture::Capture;
9
use calling::video_frame::picture_from_i420;
10
use calling::{BackgroundChoice, CallUpdate, DeviceChoice, VideoHub, VideoKey};
11
use gpui_kit::*;
12
use tokio::sync::mpsc::{UnboundedReceiver, unbounded_channel};
13
14
use super::background::{BackgroundLibrary, BackgroundPick};
15
use super::pictures::CallPictures;
16
17
const PREVIEW_MAX_WIDTH: u32 = 640;
18
const FPS_WINDOW: Duration = Duration::from_millis(900);
19
20
pub struct CameraPreview {
21
hub: Arc<VideoHub>,
22
pictures: CallPictures,
23
blur: Arc<BlurSettings>,
24
capture: Option<Capture>,
25
frames: Arc<AtomicU64>,
26
failure: Arc<Mutex<Option<String>>>,
27
counted: (Instant, u64),
28
fps: Option<f32>,
29
}
30
31
impl CameraPreview {
32
pub fn new() -> (Self, UnboundedReceiver<CallUpdate>) {
33
let (sender, receiver) = unbounded_channel();
34
let preview = CameraPreview {
35
hub: VideoHub::new(sender),
36
pictures: CallPictures::default(),
37
blur: Arc::new(BlurSettings::default()),
38
capture: None,
39
frames: Arc::new(AtomicU64::new(0)),
40
failure: Arc::new(Mutex::new(None)),
41
counted: (Instant::now(), 0),
42
fps: None,
43
};
44
(preview, receiver)
45
}
46
47
pub fn start(&mut self, choice: &DeviceChoice) {
48
self.release_capture();
49
*self.failure.lock().expect("preview failure lock") = None;
50
self.frames.store(0, Ordering::Relaxed);
51
self.counted = (Instant::now(), 0);
52
self.fps = None;
53
let hub = self.hub.clone();
54
let frames = self.frames.clone();
55
let failure = self.failure.clone();
56
let started = start_camera(
57
choice,
58
self.blur.clone(),
59
move |buffer| {
60
frames.fetch_add(1, Ordering::Relaxed);
61
if let Some(picture) = picture_from_i420(buffer, PREVIEW_MAX_WIDTH) {
62
hub.publish(VideoKey::LocalCamera, picture);
63
}
64
},
65
move |reason| *failure.lock().expect("preview failure lock") = Some(reason),
66
);
67
match started {
68
Ok(capture) => self.capture = Some(capture),
69
Err(error) => *self.failure.lock().expect("preview failure lock") = Some(error.to_string()),
70
}
71
}
72
73
pub fn set_background(&self, choice: BackgroundChoice) {
74
match choice {
75
BackgroundChoice::None => self.apply_background(false, None),
76
BackgroundChoice::Blur => self.apply_background(true, None),
77
BackgroundChoice::Image(path) => {
78
let blur = self.blur.clone();
79
std::thread::spawn(move || {
80
if let Ok(picture) = BackgroundPicture::load(&path) {
81
blur.set_picture(Some(Arc::new(picture)));
82
blur.set_enabled(true);
83
}
84
});
85
}
86
}
87
}
88
89
fn apply_background(&self, enabled: bool, picture: Option<Arc<BackgroundPicture>>) {
90
self.blur.set_picture(picture);
91
self.blur.set_enabled(enabled);
92
}
93
94
pub fn take_frames(&mut self, cx: &mut App) {
95
self.pictures.apply(&self.hub, cx);
96
}
97
98
pub fn image(&self, now: Instant) -> Option<Arc<RenderImage>> {
99
self.pictures.live(&VideoKey::LocalCamera, now)
100
}
101
102
pub fn failure(&self) -> Option<String> {
103
self.failure.lock().expect("preview failure lock").clone()
104
}
105
106
pub fn fps(&self) -> Option<f32> {
107
self.fps
108
}
109
110
pub fn tick(&mut self, now: Instant) {
111
let total = self.frames.load(Ordering::Relaxed);
112
let (since, previous) = self.counted;
113
let elapsed = now.saturating_duration_since(since);
114
if elapsed < FPS_WINDOW {
115
return;
116
}
117
self.fps = self.capture.is_some().then(|| frames_per_second(total.saturating_sub(previous), elapsed));
118
self.counted = (now, total);
119
}
120
121
pub fn stop(&mut self, cx: &mut App) {
122
self.release_capture();
123
self.pictures.clear(cx);
124
self.fps = None;
125
}
126
127
fn release_capture(&mut self) {
128
if let Some(capture) = self.capture.take() {
129
std::thread::spawn(move || drop(capture));
130
}
131
}
132
}
133
134
pub fn frames_per_second(frames: u64, elapsed: Duration) -> f32 {
135
if elapsed.is_zero() {
136
return 0.;
137
}
138
frames as f32 / elapsed.as_secs_f32()
139
}
140
141
pub fn preview_backgrounds(library: &BackgroundLibrary) -> Vec<(BackgroundPick, String)> {
142
let defaults = library
143
.shown()
144
.iter()
145
.filter(|image| library.cached_image(&image.id).is_some())
146
.map(|image| (BackgroundPick::Default(image.id.clone()), image.name.clone()));
147
let customs = library.customs.iter().filter(|path| path.exists()).map(|path| {
148
let name = path.file_name().map_or_else(String::new, |name| name.to_string_lossy().into_owned());
149
(BackgroundPick::Custom(path.clone()), name)
150
});
151
[(BackgroundPick::None, "None".to_owned()), (BackgroundPick::Blur, "Blur".to_owned())]
152
.into_iter()
153
.chain(defaults)
154
.chain(customs)
155
.collect()
156
}
157
158
#[cfg(test)]
159
mod tests {
160
use std::time::{Duration, Instant};
161
162
use super::{BackgroundLibrary, BackgroundPick, CameraPreview, frames_per_second, preview_backgrounds};
163
164
#[test]
165
fn frames_per_second_divides_by_elapsed_time() {
166
assert_eq!(frames_per_second(30, Duration::from_secs(1)), 30.);
167
assert_eq!(frames_per_second(15, Duration::from_millis(500)), 30.);
168
assert_eq!(frames_per_second(10, Duration::ZERO), 0.);
169
}
170
171
#[test]
172
fn the_background_choices_start_with_none_and_blur() {
173
let library = BackgroundLibrary::new(std::env::temp_dir().join("teams-preview-test-no-cache"));
174
let picks: Vec<BackgroundPick> = preview_backgrounds(&library).into_iter().map(|(pick, _)| pick).collect();
175
assert_eq!(picks, vec![BackgroundPick::None, BackgroundPick::Blur]);
176
}
177
178
#[test]
179
fn a_preview_without_a_camera_reports_no_frames() {
180
let (preview, _receiver) = CameraPreview::new();
181
assert_eq!(preview.fps(), None);
182
assert!(preview.image(Instant::now()).is_none());
183
}
184
}
@@ -0,0 +1,184 @@1
use std::sync::atomic::{AtomicU64, Ordering};2
use std::sync::{Arc, Mutex};3
use std::time::{Duration, Instant};4
5
use calling::background::BackgroundPicture;6
use calling::blur::BlurSettings;7
use calling::camera::start_camera;8
use calling::capture::Capture;9
use calling::video_frame::picture_from_i420;10
use calling::{BackgroundChoice, CallUpdate, DeviceChoice, VideoHub, VideoKey};11
use gpui_kit::*;12
use tokio::sync::mpsc::{UnboundedReceiver, unbounded_channel};13
14
use super::background::{BackgroundLibrary, BackgroundPick};15
use super::pictures::CallPictures;16
17
const PREVIEW_MAX_WIDTH: u32 = 640;18
const FPS_WINDOW: Duration = Duration::from_millis(900);19
20
pub struct CameraPreview {21
hub: Arc<VideoHub>,22
pictures: CallPictures,23
blur: Arc<BlurSettings>,24
capture: Option<Capture>,25
frames: Arc<AtomicU64>,26
failure: Arc<Mutex<Option<String>>>,27
counted: (Instant, u64),28
fps: Option<f32>,29
}30
31
impl CameraPreview {32
pub fn new() -> (Self, UnboundedReceiver<CallUpdate>) {33
let (sender, receiver) = unbounded_channel();34
let preview = CameraPreview {35
hub: VideoHub::new(sender),36
pictures: CallPictures::default(),37
blur: Arc::new(BlurSettings::default()),38
capture: None,39
frames: Arc::new(AtomicU64::new(0)),40
failure: Arc::new(Mutex::new(None)),41
counted: (Instant::now(), 0),42
fps: None,43
};44
(preview, receiver)45
}46
47
pub fn start(&mut self, choice: &DeviceChoice) {48
self.release_capture();49
*self.failure.lock().expect("preview failure lock") = None;50
self.frames.store(0, Ordering::Relaxed);51
self.counted = (Instant::now(), 0);52
self.fps = None;53
let hub = self.hub.clone();54
let frames = self.frames.clone();55
let failure = self.failure.clone();56
let started = start_camera(57
choice,58
self.blur.clone(),59
move |buffer| {60
frames.fetch_add(1, Ordering::Relaxed);61
if let Some(picture) = picture_from_i420(buffer, PREVIEW_MAX_WIDTH) {62
hub.publish(VideoKey::LocalCamera, picture);63
}64
},65
move |reason| *failure.lock().expect("preview failure lock") = Some(reason),66
);67
match started {68
Ok(capture) => self.capture = Some(capture),69
Err(error) => *self.failure.lock().expect("preview failure lock") = Some(error.to_string()),70
}71
}72
73
pub fn set_background(&self, choice: BackgroundChoice) {74
match choice {75
BackgroundChoice::None => self.apply_background(false, None),76
BackgroundChoice::Blur => self.apply_background(true, None),77
BackgroundChoice::Image(path) => {78
let blur = self.blur.clone();79
std::thread::spawn(move || {80
if let Ok(picture) = BackgroundPicture::load(&path) {81
blur.set_picture(Some(Arc::new(picture)));82
blur.set_enabled(true);83
}84
});85
}86
}87
}88
89
fn apply_background(&self, enabled: bool, picture: Option<Arc<BackgroundPicture>>) {90
self.blur.set_picture(picture);91
self.blur.set_enabled(enabled);92
}93
94
pub fn take_frames(&mut self, cx: &mut App) {95
self.pictures.apply(&self.hub, cx);96
}97
98
pub fn image(&self, now: Instant) -> Option<Arc<RenderImage>> {99
self.pictures.live(&VideoKey::LocalCamera, now)100
}101
102
pub fn failure(&self) -> Option<String> {103
self.failure.lock().expect("preview failure lock").clone()104
}105
106
pub fn fps(&self) -> Option<f32> {107
self.fps108
}109
110
pub fn tick(&mut self, now: Instant) {111
let total = self.frames.load(Ordering::Relaxed);112
let (since, previous) = self.counted;113
let elapsed = now.saturating_duration_since(since);114
if elapsed < FPS_WINDOW {115
return;116
}117
self.fps = self.capture.is_some().then(|| frames_per_second(total.saturating_sub(previous), elapsed));118
self.counted = (now, total);119
}120
121
pub fn stop(&mut self, cx: &mut App) {122
self.release_capture();123
self.pictures.clear(cx);124
self.fps = None;125
}126
127
fn release_capture(&mut self) {128
if let Some(capture) = self.capture.take() {129
std::thread::spawn(move || drop(capture));130
}131
}132
}133
134
pub fn frames_per_second(frames: u64, elapsed: Duration) -> f32 {135
if elapsed.is_zero() {136
return 0.;137
}138
frames as f32 / elapsed.as_secs_f32()139
}140
141
pub fn preview_backgrounds(library: &BackgroundLibrary) -> Vec<(BackgroundPick, String)> {142
let defaults = library143
.shown()144
.iter()145
.filter(|image| library.cached_image(&image.id).is_some())146
.map(|image| (BackgroundPick::Default(image.id.clone()), image.name.clone()));147
let customs = library.customs.iter().filter(|path| path.exists()).map(|path| {148
let name = path.file_name().map_or_else(String::new, |name| name.to_string_lossy().into_owned());149
(BackgroundPick::Custom(path.clone()), name)150
});151
[(BackgroundPick::None, "None".to_owned()), (BackgroundPick::Blur, "Blur".to_owned())]152
.into_iter()153
.chain(defaults)154
.chain(customs)155
.collect()156
}157
158
#[cfg(test)]159
mod tests {160
use std::time::{Duration, Instant};161
162
use super::{BackgroundLibrary, BackgroundPick, CameraPreview, frames_per_second, preview_backgrounds};163
164
#[test]165
fn frames_per_second_divides_by_elapsed_time() {166
assert_eq!(frames_per_second(30, Duration::from_secs(1)), 30.);167
assert_eq!(frames_per_second(15, Duration::from_millis(500)), 30.);168
assert_eq!(frames_per_second(10, Duration::ZERO), 0.);169
}170
171
#[test]172
fn the_background_choices_start_with_none_and_blur() {173
let library = BackgroundLibrary::new(std::env::temp_dir().join("teams-preview-test-no-cache"));174
let picks: Vec<BackgroundPick> = preview_backgrounds(&library).into_iter().map(|(pick, _)| pick).collect();175
assert_eq!(picks, vec![BackgroundPick::None, BackgroundPick::Blur]);176
}177
178
#[test]179
fn a_preview_without_a_camera_reports_no_frames() {180
let (preview, _receiver) = CameraPreview::new();181
assert_eq!(preview.fps(), None);182
assert!(preview.image(Instant::now()).is_none());183
}184
}@@ -11,7 +11,7 @@ use super::layout::{self, Slot, ring_height};
11
11
use super::platform::{self, NativeHandle, Tray, TrayCommand, WorkArea};
12
12
use super::rules::{
13
13
ChatKind, Decision, Environment, Incoming, Preview, Settings, SoundThrottle, decide, in_call,
14
should_flash,
14
should_flash, should_ringback,
15
15
};
16
16
use super::settings;
17
17
use super::settings_view::SettingsView;
@@ -65,6 +65,7 @@ pub struct NotificationCenter {
65
65
ring_windows: HashMap<u64, OpenWindow>,
66
66
ring_opening: HashSet<u64>,
67
67
ring_tone: Option<platform::RingTone>,
68
ringback: Option<platform::RingTone>,
68
69
demo_mode: bool,
69
70
pill: Option<OpenWindow>,
70
71
pill_opening: bool,
@@ -101,6 +102,7 @@ impl NotificationCenter {
101
102
ring_windows: HashMap::new(),
102
103
ring_opening: HashSet::new(),
103
104
ring_tone: None,
105
ringback: None,
104
106
demo_mode: app.read(cx).mode.demo,
105
107
pill: None,
106
108
pill_opening: false,
@@ -219,6 +221,7 @@ impl NotificationCenter {
219
221
AppEvent::Selection => self.on_selection(cx),
220
222
AppEvent::Sidebar => self.refresh_badge(cx),
221
223
AppEvent::Ring => self.on_rings_changed(cx),
224
AppEvent::Call => self.sync_ringback(cx),
222
225
_ => {}
223
226
}
224
227
}
@@ -445,12 +448,21 @@ impl NotificationCenter {
445
448
fn sync_ring_tone(&mut self, ringing: bool) {
446
449
let audible = ringing && self.settings.sound && !self.demo_mode;
447
450
match (audible, self.ring_tone.is_some()) {
448
(true, false) => self.ring_tone = platform::start_ring(),
451
(true, false) => self.ring_tone = platform::start_ring(self.settings.ringtone),
449
452
(false, true) => self.ring_tone = None,
450
453
_ => {}
451
454
}
452
455
}
453
456
457
fn sync_ringback(&mut self, cx: &Context<Self>) {
458
let audible = should_ringback(self.app.read(cx).call.as_ref().map(|call| &call.model)) && !self.demo_mode;
459
match (audible, self.ringback.is_some()) {
460
(true, false) => self.ringback = platform::start_ringback(),
461
(false, true) => self.ringback = None,
462
_ => {}
463
}
464
}
465
454
466
fn slide_offset(&self, opened: Instant, area: WorkArea) -> i32 {
455
467
if !self.animations {
456
468
return 0;
@@ -835,7 +847,7 @@ impl NotificationCenter {
835
847
cx,
836
848
))),
837
849
titlebar: Some(TitlebarOptions {
838
title: Some("Notifications".into()),
850
title: Some("Settings".into()),
839
851
..Default::default()
840
852
}),
841
853
is_resizable: false,
@@ -11,7 +11,7 @@ use super::layout::{self, Slot, ring_height};11
use super::platform::{self, NativeHandle, Tray, TrayCommand, WorkArea};11
use super::platform::{self, NativeHandle, Tray, TrayCommand, WorkArea};12
use super::rules::{12
use super::rules::{13
ChatKind, Decision, Environment, Incoming, Preview, Settings, SoundThrottle, decide, in_call,13
ChatKind, Decision, Environment, Incoming, Preview, Settings, SoundThrottle, decide, in_call,14
should_flash,14
should_flash, should_ringback,15
};15
};16
use super::settings;16
use super::settings;17
use super::settings_view::SettingsView;17
use super::settings_view::SettingsView;@@ -65,6 +65,7 @@ pub struct NotificationCenter {65
ring_windows: HashMap<u64, OpenWindow>,65
ring_windows: HashMap<u64, OpenWindow>,66
ring_opening: HashSet<u64>,66
ring_opening: HashSet<u64>,67
ring_tone: Option<platform::RingTone>,67
ring_tone: Option<platform::RingTone>,68
ringback: Option<platform::RingTone>,68
demo_mode: bool,69
demo_mode: bool,69
pill: Option<OpenWindow>,70
pill: Option<OpenWindow>,70
pill_opening: bool,71
pill_opening: bool,@@ -101,6 +102,7 @@ impl NotificationCenter {101
ring_windows: HashMap::new(),102
ring_windows: HashMap::new(),102
ring_opening: HashSet::new(),103
ring_opening: HashSet::new(),103
ring_tone: None,104
ring_tone: None,105
ringback: None,104
demo_mode: app.read(cx).mode.demo,106
demo_mode: app.read(cx).mode.demo,105
pill: None,107
pill: None,106
pill_opening: false,108
pill_opening: false,@@ -219,6 +221,7 @@ impl NotificationCenter {219
AppEvent::Selection => self.on_selection(cx),221
AppEvent::Selection => self.on_selection(cx),220
AppEvent::Sidebar => self.refresh_badge(cx),222
AppEvent::Sidebar => self.refresh_badge(cx),221
AppEvent::Ring => self.on_rings_changed(cx),223
AppEvent::Ring => self.on_rings_changed(cx),224
AppEvent::Call => self.sync_ringback(cx),222
_ => {}225
_ => {}223
}226
}224
}227
}@@ -445,12 +448,21 @@ impl NotificationCenter {445
fn sync_ring_tone(&mut self, ringing: bool) {448
fn sync_ring_tone(&mut self, ringing: bool) {446
let audible = ringing && self.settings.sound && !self.demo_mode;449
let audible = ringing && self.settings.sound && !self.demo_mode;447
match (audible, self.ring_tone.is_some()) {450
match (audible, self.ring_tone.is_some()) {448
(true, false) => self.ring_tone = platform::start_ring(),451
(true, false) => self.ring_tone = platform::start_ring(self.settings.ringtone),449
(false, true) => self.ring_tone = None,452
(false, true) => self.ring_tone = None,450
_ => {}453
_ => {}451
}454
}452
}455
}453
456
457
fn sync_ringback(&mut self, cx: &Context<Self>) {458
let audible = should_ringback(self.app.read(cx).call.as_ref().map(|call| &call.model)) && !self.demo_mode;459
match (audible, self.ringback.is_some()) {460
(true, false) => self.ringback = platform::start_ringback(),461
(false, true) => self.ringback = None,462
_ => {}463
}464
}465
454
fn slide_offset(&self, opened: Instant, area: WorkArea) -> i32 {466
fn slide_offset(&self, opened: Instant, area: WorkArea) -> i32 {455
if !self.animations {467
if !self.animations {456
return 0;468
return 0;@@ -835,7 +847,7 @@ impl NotificationCenter {835
cx,847
cx,836
))),848
))),837
titlebar: Some(TitlebarOptions {849
titlebar: Some(TitlebarOptions {838
title: Some("Notifications".into()),850
title: Some("Settings".into()),839
..Default::default()851
..Default::default()840
}),852
}),841
is_resizable: false,853
is_resizable: false,@@ -2,6 +2,7 @@ use gpui_kit::Window;
2
2
3
3
use super::{NativeHandle, TrayCommand, WorkArea};
4
4
use crate::notify::badge::Badge;
5
use crate::notify::ring_tone::Ringtone;
5
6
6
7
pub fn native_handle(_window: &Window) -> Option<NativeHandle> {
7
8
None
@@ -35,10 +36,16 @@ pub fn play_sound() {}
35
36
36
37
pub struct RingTone;
37
38
38
pub fn start_ring() -> Option<RingTone> {
39
pub fn start_ring(_ringtone: Ringtone) -> Option<RingTone> {
39
40
None
40
41
}
41
42
43
pub fn start_ringback() -> Option<RingTone> {
44
None
45
}
46
47
pub fn play_preview(_ringtone: Ringtone) {}
48
42
49
pub struct Tray;
43
50
44
51
impl Tray {
@@ -2,6 +2,7 @@ use gpui_kit::Window;2
2
3
use super::{NativeHandle, TrayCommand, WorkArea};3
use super::{NativeHandle, TrayCommand, WorkArea};4
use crate::notify::badge::Badge;4
use crate::notify::badge::Badge;5
use crate::notify::ring_tone::Ringtone;5
6
6
pub fn native_handle(_window: &Window) -> Option<NativeHandle> {7
pub fn native_handle(_window: &Window) -> Option<NativeHandle> {7
None8
None@@ -35,10 +36,16 @@ pub fn play_sound() {}35
36
36
pub struct RingTone;37
pub struct RingTone;37
38
38
pub fn start_ring() -> Option<RingTone> {39
pub fn start_ring(_ringtone: Ringtone) -> Option<RingTone> {39
None40
None40
}41
}41
42
43
pub fn start_ringback() -> Option<RingTone> {44
None45
}46
47
pub fn play_preview(_ringtone: Ringtone) {}48
42
pub struct Tray;49
pub struct Tray;43
50
44
impl Tray {51
impl Tray {@@ -36,7 +36,7 @@ use windows::core::{BOOL, w};
36
36
37
37
use super::{NativeHandle, TrayCommand, WorkArea};
38
38
use crate::notify::badge::{BADGE_SIZE, Badge, render_badge};
39
use crate::notify::ring_tone::{SAMPLE_RATE, ring_cycle};
39
use crate::notify::ring_tone::{Ringtone, SAMPLE_RATE, ringback_cycle};
40
40
41
41
const SOUND_BYTES: &[u8] = include_bytes!("../../../assets/sounds/notification.mp3");
42
42
const TRAY_ICON_PNG: &[u8] = include_bytes!("../../../assets/icon/teams-fast-256.png");
@@ -262,7 +262,31 @@ impl Drop for RingTone {
262
262
}
263
263
}
264
264
265
pub fn start_ring() -> Option<RingTone> {
265
pub fn start_ring(ringtone: Ringtone) -> Option<RingTone> {
266
start_cycle(ringtone.cycle(SAMPLE_RATE))
267
}
268
269
pub fn start_ringback() -> Option<RingTone> {
270
start_cycle(ringback_cycle(SAMPLE_RATE))
271
}
272
273
pub fn play_preview(ringtone: Ringtone) {
274
let cycle = ringtone.cycle(SAMPLE_RATE);
275
std::thread::spawn(move || {
276
let Ok(mut sink) = rodio::DeviceSinkBuilder::open_default_sink() else {
277
return;
278
};
279
sink.log_on_drop(false);
280
let (Some(channels), Some(rate)) = (NonZero::new(1u16), NonZero::new(SAMPLE_RATE)) else {
281
return;
282
};
283
let player = rodio::Player::connect_new(sink.mixer());
284
player.append(rodio::buffer::SamplesBuffer::new(channels, rate, cycle));
285
player.sleep_until_end();
286
});
287
}
288
289
fn start_cycle(cycle: Vec<f32>) -> Option<RingTone> {
266
290
let stop = Arc::new(AtomicBool::new(false));
267
291
let flag = stop.clone();
268
292
std::thread::spawn(move || {
@@ -273,7 +297,6 @@ pub fn start_ring() -> Option<RingTone> {
273
297
let (Some(channels), Some(rate)) = (NonZero::new(1u16), NonZero::new(SAMPLE_RATE)) else {
274
298
return;
275
299
};
276
let cycle = ring_cycle(SAMPLE_RATE);
277
300
while !flag.load(Ordering::SeqCst) {
278
301
let player = rodio::Player::connect_new(sink.mixer());
279
302
player.append(rodio::buffer::SamplesBuffer::new(channels, rate, cycle.clone()));
@@ -36,7 +36,7 @@ use windows::core::{BOOL, w};36
36
37
use super::{NativeHandle, TrayCommand, WorkArea};37
use super::{NativeHandle, TrayCommand, WorkArea};38
use crate::notify::badge::{BADGE_SIZE, Badge, render_badge};38
use crate::notify::badge::{BADGE_SIZE, Badge, render_badge};39
use crate::notify::ring_tone::{SAMPLE_RATE, ring_cycle};39
use crate::notify::ring_tone::{Ringtone, SAMPLE_RATE, ringback_cycle};40
40
41
const SOUND_BYTES: &[u8] = include_bytes!("../../../assets/sounds/notification.mp3");41
const SOUND_BYTES: &[u8] = include_bytes!("../../../assets/sounds/notification.mp3");42
const TRAY_ICON_PNG: &[u8] = include_bytes!("../../../assets/icon/teams-fast-256.png");42
const TRAY_ICON_PNG: &[u8] = include_bytes!("../../../assets/icon/teams-fast-256.png");@@ -262,7 +262,31 @@ impl Drop for RingTone {262
}262
}263
}263
}264
264
265
pub fn start_ring() -> Option<RingTone> {265
pub fn start_ring(ringtone: Ringtone) -> Option<RingTone> {266
start_cycle(ringtone.cycle(SAMPLE_RATE))267
}268
269
pub fn start_ringback() -> Option<RingTone> {270
start_cycle(ringback_cycle(SAMPLE_RATE))271
}272
273
pub fn play_preview(ringtone: Ringtone) {274
let cycle = ringtone.cycle(SAMPLE_RATE);275
std::thread::spawn(move || {276
let Ok(mut sink) = rodio::DeviceSinkBuilder::open_default_sink() else {277
return;278
};279
sink.log_on_drop(false);280
let (Some(channels), Some(rate)) = (NonZero::new(1u16), NonZero::new(SAMPLE_RATE)) else {281
return;282
};283
let player = rodio::Player::connect_new(sink.mixer());284
player.append(rodio::buffer::SamplesBuffer::new(channels, rate, cycle));285
player.sleep_until_end();286
});287
}288
289
fn start_cycle(cycle: Vec<f32>) -> Option<RingTone> {266
let stop = Arc::new(AtomicBool::new(false));290
let stop = Arc::new(AtomicBool::new(false));267
let flag = stop.clone();291
let flag = stop.clone();268
std::thread::spawn(move || {292
std::thread::spawn(move || {@@ -273,7 +297,6 @@ pub fn start_ring() -> Option<RingTone> {273
let (Some(channels), Some(rate)) = (NonZero::new(1u16), NonZero::new(SAMPLE_RATE)) else {297
let (Some(channels), Some(rate)) = (NonZero::new(1u16), NonZero::new(SAMPLE_RATE)) else {274
return;298
return;275
};299
};276
let cycle = ring_cycle(SAMPLE_RATE);277
while !flag.load(Ordering::SeqCst) {300
while !flag.load(Ordering::SeqCst) {278
let player = rodio::Player::connect_new(sink.mixer());301
let player = rodio::Player::connect_new(sink.mixer());279
player.append(rodio::buffer::SamplesBuffer::new(channels, rate, cycle.clone()));302
player.append(rodio::buffer::SamplesBuffer::new(channels, rate, cycle.clone()));@@ -1,23 +1,80 @@
1
1
use std::f32::consts::PI;
2
2
3
3
pub const SAMPLE_RATE: u32 = 44_100;
4
const FADE_SECONDS: f32 = 0.015;
5
const AMPLITUDE: f32 = 0.3;
4
6
const LOW_HZ: f32 = 784.;
5
7
const HIGH_HZ: f32 = 988.;
6
8
const BEEP_SECONDS: f32 = 0.18;
7
const FADE_SECONDS: f32 = 0.015;
8
const AMPLITUDE: f32 = 0.3;
9
9
const BEEPS: [f32; 4] = [LOW_HZ, HIGH_HZ, LOW_HZ, HIGH_HZ];
10
10
const CYCLE_SECONDS: f32 = 2.4;
11
const CHIME_NOTES: [f32; 4] = [523.25, 659.25, 783.99, 1046.5];
12
const CHIME_NOTE_SECONDS: f32 = 0.22;
13
const CHIME_CYCLE_SECONDS: f32 = 2.6;
14
const PULSE_NOTES: [f32; 3] = [587.33, 587.33, 587.33];
15
const PULSE_NOTE_SECONDS: f32 = 0.26;
16
const PULSE_CYCLE_SECONDS: f32 = 2.2;
17
const RINGBACK_HZ: f32 = 425.;
18
const RINGBACK_ON_SECONDS: f32 = 1.;
19
const RINGBACK_CYCLE_SECONDS: f32 = 5.;
20
21
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
22
pub enum Ringtone {
23
#[default]
24
Default,
25
Chime,
26
Pulse,
27
}
28
29
impl Ringtone {
30
pub const ALL: [Ringtone; 3] = [Ringtone::Default, Ringtone::Chime, Ringtone::Pulse];
31
32
pub fn label(self) -> &'static str {
33
match self {
34
Ringtone::Default => "Default",
35
Ringtone::Chime => "Chime",
36
Ringtone::Pulse => "Pulse",
37
}
38
}
39
40
pub fn key(self) -> &'static str {
41
match self {
42
Ringtone::Default => "default",
43
Ringtone::Chime => "chime",
44
Ringtone::Pulse => "pulse",
45
}
46
}
47
48
pub fn from_key(key: &str) -> Option<Ringtone> {
49
Ringtone::ALL.into_iter().find(|ringtone| ringtone.key() == key)
50
}
51
52
pub fn cycle(self, sample_rate: u32) -> Vec<f32> {
53
match self {
54
Ringtone::Default => ring_cycle(sample_rate),
55
Ringtone::Chime => tone_cycle(sample_rate, &CHIME_NOTES, CHIME_NOTE_SECONDS, CHIME_CYCLE_SECONDS),
56
Ringtone::Pulse => tone_cycle(sample_rate, &PULSE_NOTES, PULSE_NOTE_SECONDS, PULSE_CYCLE_SECONDS),
57
}
58
}
59
}
11
60
12
61
pub fn ring_cycle(sample_rate: u32) -> Vec<f32> {
13
let total = (CYCLE_SECONDS * sample_rate as f32) as usize;
14
let beep = (BEEP_SECONDS * sample_rate as f32) as usize;
62
tone_cycle(sample_rate, &BEEPS, BEEP_SECONDS, CYCLE_SECONDS)
63
}
64
65
pub fn ringback_cycle(sample_rate: u32) -> Vec<f32> {
66
tone_cycle(sample_rate, &[RINGBACK_HZ], RINGBACK_ON_SECONDS, RINGBACK_CYCLE_SECONDS)
67
}
68
69
fn tone_cycle(sample_rate: u32, frequencies: &[f32], tone_seconds: f32, cycle_seconds: f32) -> Vec<f32> {
70
let total = (cycle_seconds * sample_rate as f32) as usize;
71
let tone = (tone_seconds * sample_rate as f32) as usize;
15
72
let fade = (FADE_SECONDS * sample_rate as f32) as usize;
16
73
let mut samples = vec![0.; total];
17
for (index, frequency) in BEEPS.iter().enumerate() {
18
let start = index * beep;
19
for position in 0..beep {
20
let envelope = (position.min(beep - 1 - position) as f32 / fade as f32).min(1.);
74
for (index, frequency) in frequencies.iter().enumerate() {
75
let start = index * tone;
76
for position in 0..tone {
77
let envelope = (position.min(tone - 1 - position) as f32 / fade as f32).min(1.);
21
78
let phase = 2. * PI * frequency * position as f32 / sample_rate as f32;
22
79
samples[start + position] = AMPLITUDE * envelope * phase.sin();
23
80
}
@@ -58,4 +115,35 @@ mod tests {
58
115
fn the_cycle_is_the_same_every_time() {
59
116
assert_eq!(ring_cycle(SAMPLE_RATE), ring_cycle(SAMPLE_RATE));
60
117
}
118
119
#[test]
120
fn the_ringback_is_one_second_of_425_hz_then_four_seconds_of_silence() {
121
let samples = ringback_cycle(SAMPLE_RATE);
122
let rate = SAMPLE_RATE as usize;
123
assert_eq!(samples.len(), 5 * rate);
124
assert!(samples[..rate].iter().any(|sample| sample.abs() > AMPLITUDE * 0.9));
125
assert!(samples[rate..].iter().all(|sample| *sample == 0.));
126
let crossings = samples[..rate].windows(2).filter(|pair| pair[0] < 0. && pair[1] >= 0.).count();
127
assert!((424..=426).contains(&crossings));
128
}
129
130
#[test]
131
fn every_ringtone_is_quiet_ends_in_silence_and_differs_from_the_others() {
132
for ringtone in Ringtone::ALL {
133
let samples = ringtone.cycle(SAMPLE_RATE);
134
assert!(samples.iter().all(|sample| sample.abs() <= AMPLITUDE + f32::EPSILON));
135
assert!(samples.iter().any(|sample| sample.abs() > AMPLITUDE * 0.9));
136
assert_eq!(samples.last().copied(), Some(0.));
137
}
138
assert_ne!(Ringtone::Default.cycle(SAMPLE_RATE), Ringtone::Chime.cycle(SAMPLE_RATE));
139
assert_ne!(Ringtone::Chime.cycle(SAMPLE_RATE), Ringtone::Pulse.cycle(SAMPLE_RATE));
140
}
141
142
#[test]
143
fn ringtone_keys_round_trip() {
144
for ringtone in Ringtone::ALL {
145
assert_eq!(Ringtone::from_key(ringtone.key()), Some(ringtone));
146
}
147
assert_eq!(Ringtone::from_key("nope"), None);
148
}
61
149
}
@@ -1,23 +1,80 @@1
use std::f32::consts::PI;1
use std::f32::consts::PI;2
2
3
pub const SAMPLE_RATE: u32 = 44_100;3
pub const SAMPLE_RATE: u32 = 44_100;4
const FADE_SECONDS: f32 = 0.015;5
const AMPLITUDE: f32 = 0.3;4
const LOW_HZ: f32 = 784.;6
const LOW_HZ: f32 = 784.;5
const HIGH_HZ: f32 = 988.;7
const HIGH_HZ: f32 = 988.;6
const BEEP_SECONDS: f32 = 0.18;8
const BEEP_SECONDS: f32 = 0.18;7
const FADE_SECONDS: f32 = 0.015;8
const AMPLITUDE: f32 = 0.3;9
const BEEPS: [f32; 4] = [LOW_HZ, HIGH_HZ, LOW_HZ, HIGH_HZ];9
const BEEPS: [f32; 4] = [LOW_HZ, HIGH_HZ, LOW_HZ, HIGH_HZ];10
const CYCLE_SECONDS: f32 = 2.4;10
const CYCLE_SECONDS: f32 = 2.4;11
const CHIME_NOTES: [f32; 4] = [523.25, 659.25, 783.99, 1046.5];12
const CHIME_NOTE_SECONDS: f32 = 0.22;13
const CHIME_CYCLE_SECONDS: f32 = 2.6;14
const PULSE_NOTES: [f32; 3] = [587.33, 587.33, 587.33];15
const PULSE_NOTE_SECONDS: f32 = 0.26;16
const PULSE_CYCLE_SECONDS: f32 = 2.2;17
const RINGBACK_HZ: f32 = 425.;18
const RINGBACK_ON_SECONDS: f32 = 1.;19
const RINGBACK_CYCLE_SECONDS: f32 = 5.;20
21
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]22
pub enum Ringtone {23
#[default]24
Default,25
Chime,26
Pulse,27
}28
29
impl Ringtone {30
pub const ALL: [Ringtone; 3] = [Ringtone::Default, Ringtone::Chime, Ringtone::Pulse];31
32
pub fn label(self) -> &'static str {33
match self {34
Ringtone::Default => "Default",35
Ringtone::Chime => "Chime",36
Ringtone::Pulse => "Pulse",37
}38
}39
40
pub fn key(self) -> &'static str {41
match self {42
Ringtone::Default => "default",43
Ringtone::Chime => "chime",44
Ringtone::Pulse => "pulse",45
}46
}47
48
pub fn from_key(key: &str) -> Option<Ringtone> {49
Ringtone::ALL.into_iter().find(|ringtone| ringtone.key() == key)50
}51
52
pub fn cycle(self, sample_rate: u32) -> Vec<f32> {53
match self {54
Ringtone::Default => ring_cycle(sample_rate),55
Ringtone::Chime => tone_cycle(sample_rate, &CHIME_NOTES, CHIME_NOTE_SECONDS, CHIME_CYCLE_SECONDS),56
Ringtone::Pulse => tone_cycle(sample_rate, &PULSE_NOTES, PULSE_NOTE_SECONDS, PULSE_CYCLE_SECONDS),57
}58
}59
}11
60
12
pub fn ring_cycle(sample_rate: u32) -> Vec<f32> {61
pub fn ring_cycle(sample_rate: u32) -> Vec<f32> {13
let total = (CYCLE_SECONDS * sample_rate as f32) as usize;62
tone_cycle(sample_rate, &BEEPS, BEEP_SECONDS, CYCLE_SECONDS)14
let beep = (BEEP_SECONDS * sample_rate as f32) as usize;63
}64
65
pub fn ringback_cycle(sample_rate: u32) -> Vec<f32> {66
tone_cycle(sample_rate, &[RINGBACK_HZ], RINGBACK_ON_SECONDS, RINGBACK_CYCLE_SECONDS)67
}68
69
fn tone_cycle(sample_rate: u32, frequencies: &[f32], tone_seconds: f32, cycle_seconds: f32) -> Vec<f32> {70
let total = (cycle_seconds * sample_rate as f32) as usize;71
let tone = (tone_seconds * sample_rate as f32) as usize;15
let fade = (FADE_SECONDS * sample_rate as f32) as usize;72
let fade = (FADE_SECONDS * sample_rate as f32) as usize;16
let mut samples = vec![0.; total];73
let mut samples = vec![0.; total];17
for (index, frequency) in BEEPS.iter().enumerate() {74
for (index, frequency) in frequencies.iter().enumerate() {18
let start = index * beep;75
let start = index * tone;19
for position in 0..beep {76
for position in 0..tone {20
let envelope = (position.min(beep - 1 - position) as f32 / fade as f32).min(1.);77
let envelope = (position.min(tone - 1 - position) as f32 / fade as f32).min(1.);21
let phase = 2. * PI * frequency * position as f32 / sample_rate as f32;78
let phase = 2. * PI * frequency * position as f32 / sample_rate as f32;22
samples[start + position] = AMPLITUDE * envelope * phase.sin();79
samples[start + position] = AMPLITUDE * envelope * phase.sin();23
}80
}@@ -58,4 +115,35 @@ mod tests {58
fn the_cycle_is_the_same_every_time() {115
fn the_cycle_is_the_same_every_time() {59
assert_eq!(ring_cycle(SAMPLE_RATE), ring_cycle(SAMPLE_RATE));116
assert_eq!(ring_cycle(SAMPLE_RATE), ring_cycle(SAMPLE_RATE));60
}117
}118
119
#[test]120
fn the_ringback_is_one_second_of_425_hz_then_four_seconds_of_silence() {121
let samples = ringback_cycle(SAMPLE_RATE);122
let rate = SAMPLE_RATE as usize;123
assert_eq!(samples.len(), 5 * rate);124
assert!(samples[..rate].iter().any(|sample| sample.abs() > AMPLITUDE * 0.9));125
assert!(samples[rate..].iter().all(|sample| *sample == 0.));126
let crossings = samples[..rate].windows(2).filter(|pair| pair[0] < 0. && pair[1] >= 0.).count();127
assert!((424..=426).contains(&crossings));128
}129
130
#[test]131
fn every_ringtone_is_quiet_ends_in_silence_and_differs_from_the_others() {132
for ringtone in Ringtone::ALL {133
let samples = ringtone.cycle(SAMPLE_RATE);134
assert!(samples.iter().all(|sample| sample.abs() <= AMPLITUDE + f32::EPSILON));135
assert!(samples.iter().any(|sample| sample.abs() > AMPLITUDE * 0.9));136
assert_eq!(samples.last().copied(), Some(0.));137
}138
assert_ne!(Ringtone::Default.cycle(SAMPLE_RATE), Ringtone::Chime.cycle(SAMPLE_RATE));139
assert_ne!(Ringtone::Chime.cycle(SAMPLE_RATE), Ringtone::Pulse.cycle(SAMPLE_RATE));140
}141
142
#[test]143
fn ringtone_keys_round_trip() {144
for ringtone in Ringtone::ALL {145
assert_eq!(Ringtone::from_key(ringtone.key()), Some(ringtone));146
}147
assert_eq!(Ringtone::from_key("nope"), None);148
}61
}149
}@@ -2,9 +2,11 @@ use std::collections::HashMap;
2
2
use std::time::{Duration, Instant};
3
3
4
4
use chrono::{DateTime, Utc};
5
use calling::Progress;
5
6
use store::{ChannelNotificationLevel, ChannelNotifications};
6
7
7
use crate::call::CallModel;
8
use super::ring_tone::Ringtone;
9
use crate::call::{CallKind, CallModel};
8
10
9
11
pub const SOUND_THROTTLE: Duration = Duration::from_secs(10);
10
12
@@ -73,6 +75,7 @@ pub struct Settings {
73
75
pub flash: bool,
74
76
pub close_to_tray: bool,
75
77
pub do_not_disturb: bool,
78
pub ringtone: Ringtone,
76
79
}
77
80
78
81
impl Default for Settings {
@@ -85,6 +88,7 @@ impl Default for Settings {
85
88
flash: true,
86
89
close_to_tray: true,
87
90
do_not_disturb: false,
91
ringtone: Ringtone::Default,
88
92
}
89
93
}
90
94
}
@@ -144,6 +148,15 @@ pub fn in_call(server_in_call: bool, native_call: Option<&CallModel>) -> bool {
144
148
server_in_call || native_call.is_some_and(CallModel::is_active)
145
149
}
146
150
151
pub fn should_ringback(native_call: Option<&CallModel>) -> bool {
152
native_call.is_some_and(|model| {
153
!model.incoming
154
&& model.kind != CallKind::Meeting
155
&& model.is_connecting()
156
&& matches!(model.progress, Some(Progress::Calling | Progress::Ringing))
157
})
158
}
159
147
160
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
148
161
pub struct Decision {
149
162
pub toast: bool,
@@ -321,6 +334,31 @@ mod tests {
321
334
));
322
335
}
323
336
337
#[test]
338
fn ringback_plays_only_while_an_outgoing_non_meeting_call_is_connecting() {
339
let callees = [("8:orgid:a".to_owned(), "Ana".to_owned())];
340
let outgoing = |progress: Option<Progress>, state: CallState| {
341
let mut model = CallModel::people("Ana", &callees);
342
model.progress = progress;
343
model.state = state;
344
model
345
};
346
let since = std::time::Instant::now();
347
assert!(!should_ringback(None));
348
assert!(!should_ringback(Some(&outgoing(None, CallState::Connecting))));
349
assert!(should_ringback(Some(&outgoing(Some(Progress::Calling), CallState::Connecting))));
350
assert!(should_ringback(Some(&outgoing(Some(Progress::Ringing), CallState::Connecting))));
351
assert!(!should_ringback(Some(&outgoing(Some(Progress::Ringing), CallState::Connected { since }))));
352
let ended = CallState::Ended { reason: EndReason::LocalHangup };
353
assert!(!should_ringback(Some(&outgoing(Some(Progress::Ringing), ended))));
354
let mut meeting = CallModel::meeting("Standup", false);
355
meeting.progress = Some(Progress::Calling);
356
assert!(!should_ringback(Some(&meeting)));
357
let mut incoming = CallModel::incoming("Bea", "8:orgid:b", "Bea");
358
incoming.progress = Some(Progress::Ringing);
359
assert!(!should_ringback(Some(&incoming)));
360
}
361
324
362
#[test]
325
363
fn call_keeps_toast_but_drops_sound() {
326
364
let environment = Environment {
@@ -2,9 +2,11 @@ use std::collections::HashMap;2
use std::time::{Duration, Instant};2
use std::time::{Duration, Instant};3
3
4
use chrono::{DateTime, Utc};4
use chrono::{DateTime, Utc};5
use calling::Progress;5
use store::{ChannelNotificationLevel, ChannelNotifications};6
use store::{ChannelNotificationLevel, ChannelNotifications};6
7
7
use crate::call::CallModel;8
use super::ring_tone::Ringtone;9
use crate::call::{CallKind, CallModel};8
10
9
pub const SOUND_THROTTLE: Duration = Duration::from_secs(10);11
pub const SOUND_THROTTLE: Duration = Duration::from_secs(10);10
12
@@ -73,6 +75,7 @@ pub struct Settings {73
pub flash: bool,75
pub flash: bool,74
pub close_to_tray: bool,76
pub close_to_tray: bool,75
pub do_not_disturb: bool,77
pub do_not_disturb: bool,78
pub ringtone: Ringtone,76
}79
}77
80
78
impl Default for Settings {81
impl Default for Settings {@@ -85,6 +88,7 @@ impl Default for Settings {85
flash: true,88
flash: true,86
close_to_tray: true,89
close_to_tray: true,87
do_not_disturb: false,90
do_not_disturb: false,91
ringtone: Ringtone::Default,88
}92
}89
}93
}90
}94
}@@ -144,6 +148,15 @@ pub fn in_call(server_in_call: bool, native_call: Option<&CallModel>) -> bool {144
server_in_call || native_call.is_some_and(CallModel::is_active)148
server_in_call || native_call.is_some_and(CallModel::is_active)145
}149
}146
150
151
pub fn should_ringback(native_call: Option<&CallModel>) -> bool {152
native_call.is_some_and(|model| {153
!model.incoming154
&& model.kind != CallKind::Meeting155
&& model.is_connecting()156
&& matches!(model.progress, Some(Progress::Calling | Progress::Ringing))157
})158
}159
147
#[derive(Debug, Clone, Copy, PartialEq, Eq)]160
#[derive(Debug, Clone, Copy, PartialEq, Eq)]148
pub struct Decision {161
pub struct Decision {149
pub toast: bool,162
pub toast: bool,@@ -321,6 +334,31 @@ mod tests {321
));334
));322
}335
}323
336
337
#[test]338
fn ringback_plays_only_while_an_outgoing_non_meeting_call_is_connecting() {339
let callees = [("8:orgid:a".to_owned(), "Ana".to_owned())];340
let outgoing = |progress: Option<Progress>, state: CallState| {341
let mut model = CallModel::people("Ana", &callees);342
model.progress = progress;343
model.state = state;344
model345
};346
let since = std::time::Instant::now();347
assert!(!should_ringback(None));348
assert!(!should_ringback(Some(&outgoing(None, CallState::Connecting))));349
assert!(should_ringback(Some(&outgoing(Some(Progress::Calling), CallState::Connecting))));350
assert!(should_ringback(Some(&outgoing(Some(Progress::Ringing), CallState::Connecting))));351
assert!(!should_ringback(Some(&outgoing(Some(Progress::Ringing), CallState::Connected { since }))));352
let ended = CallState::Ended { reason: EndReason::LocalHangup };353
assert!(!should_ringback(Some(&outgoing(Some(Progress::Ringing), ended))));354
let mut meeting = CallModel::meeting("Standup", false);355
meeting.progress = Some(Progress::Calling);356
assert!(!should_ringback(Some(&meeting)));357
let mut incoming = CallModel::incoming("Bea", "8:orgid:b", "Bea");358
incoming.progress = Some(Progress::Ringing);359
assert!(!should_ringback(Some(&incoming)));360
}361
324
#[test]362
#[test]325
fn call_keeps_toast_but_drops_sound() {363
fn call_keeps_toast_but_drops_sound() {326
let environment = Environment {364
let environment = Environment {@@ -1,5 +1,6 @@
1
1
use store::Store;
2
2
3
use super::ring_tone::Ringtone;
3
4
use super::rules::{Corner, Settings};
4
5
5
6
const META_KEY: &str = "notifications.settings";
@@ -26,6 +27,7 @@ fn serialize(settings: &Settings) -> String {
26
27
("taskbar_flash", settings.flash.to_string()),
27
28
("close_to_tray", settings.close_to_tray.to_string()),
28
29
("do_not_disturb", settings.do_not_disturb.to_string()),
30
("ringtone", settings.ringtone.key().to_owned()),
29
31
]
30
32
.iter()
31
33
.map(|(key, value)| format!("{key}={value}"))
@@ -48,6 +50,7 @@ fn parse(text: &str) -> Settings {
48
50
"taskbar_flash" => settings.flash = flag,
49
51
"close_to_tray" => settings.close_to_tray = flag,
50
52
"do_not_disturb" => settings.do_not_disturb = flag,
53
"ringtone" => settings.ringtone = Ringtone::from_key(value).unwrap_or_default(),
51
54
_ => {}
52
55
}
53
56
}
@@ -68,6 +71,7 @@ mod tests {
68
71
flash: false,
69
72
close_to_tray: false,
70
73
do_not_disturb: true,
74
ringtone: Ringtone::Chime,
71
75
};
72
76
assert_eq!(parse(&serialize(&settings)), settings);
73
77
}
@@ -1,5 +1,6 @@1
use store::Store;1
use store::Store;2
2
3
use super::ring_tone::Ringtone;3
use super::rules::{Corner, Settings};4
use super::rules::{Corner, Settings};4
5
5
const META_KEY: &str = "notifications.settings";6
const META_KEY: &str = "notifications.settings";@@ -26,6 +27,7 @@ fn serialize(settings: &Settings) -> String {26
("taskbar_flash", settings.flash.to_string()),27
("taskbar_flash", settings.flash.to_string()),27
("close_to_tray", settings.close_to_tray.to_string()),28
("close_to_tray", settings.close_to_tray.to_string()),28
("do_not_disturb", settings.do_not_disturb.to_string()),29
("do_not_disturb", settings.do_not_disturb.to_string()),30
("ringtone", settings.ringtone.key().to_owned()),29
]31
]30
.iter()32
.iter()31
.map(|(key, value)| format!("{key}={value}"))33
.map(|(key, value)| format!("{key}={value}"))@@ -48,6 +50,7 @@ fn parse(text: &str) -> Settings {48
"taskbar_flash" => settings.flash = flag,50
"taskbar_flash" => settings.flash = flag,49
"close_to_tray" => settings.close_to_tray = flag,51
"close_to_tray" => settings.close_to_tray = flag,50
"do_not_disturb" => settings.do_not_disturb = flag,52
"do_not_disturb" => settings.do_not_disturb = flag,53
"ringtone" => settings.ringtone = Ringtone::from_key(value).unwrap_or_default(),51
_ => {}54
_ => {}52
}55
}53
}56
}@@ -68,6 +71,7 @@ mod tests {68
flash: false,71
flash: false,69
close_to_tray: false,72
close_to_tray: false,70
do_not_disturb: true,73
do_not_disturb: true,74
ringtone: Ringtone::Chime,71
};75
};72
assert_eq!(parse(&serialize(&settings)), settings);76
assert_eq!(parse(&serialize(&settings)), settings);73
}77
}@@ -1,10 +1,47 @@
1
use gpui_kit::component::{h_flex, v_flex};
1
use std::time::{Duration, Instant};
2
3
use calling::camera::{DEFAULT_CAMERA_LABEL, list_cameras};
4
use calling::{DeviceChoice, DeviceEntry, camera_entries};
5
use gpui_kit::assets::IconName;
6
use gpui_kit::component::{
7
button::Button,
8
h_flex,
9
menu::{DropdownMenu as _, PopupMenuItem},
10
v_flex,
11
};
12
use gpui_kit::prelude::FluentBuilder as _;
2
13
use gpui_kit::*;
3
14
4
15
use super::center::NotificationCenter;
16
use super::platform;
17
use super::ring_tone::Ringtone;
5
18
use super::rules::Settings;
19
use crate::call::{BackgroundPick, CameraPreview, preview_backgrounds};
6
20
use crate::theme;
7
21
22
const FPS_TICK: Duration = Duration::from_millis(500);
23
const SELECT_WIDTH: f32 = 170.;
24
const PREVIEW_WIDTH: f32 = 380.;
25
const PREVIEW_HEIGHT: f32 = 214.;
26
const PREVIEW_RADIUS: f32 = 10.;
27
28
#[derive(Clone, Copy, PartialEq, Eq)]
29
enum Section {
30
Notifications,
31
Devices,
32
}
33
34
impl Section {
35
const ALL: [Section; 2] = [Section::Notifications, Section::Devices];
36
37
fn label(self) -> &'static str {
38
match self {
39
Section::Notifications => "Notifications",
40
Section::Devices => "Devices",
41
}
42
}
43
}
44
8
45
type Accessor = fn(&mut Settings) -> &mut bool;
9
46
10
47
struct Row {
@@ -43,18 +80,117 @@ const ROWS: [Row; 5] = [
43
80
44
81
pub struct SettingsView {
45
82
center: Entity<NotificationCenter>,
83
section: Section,
84
preview: CameraPreview,
85
cameras: Vec<DeviceEntry>,
86
cameras_requested: bool,
87
camera: DeviceChoice,
88
background: BackgroundPick,
46
89
_subscription: Subscription,
90
_release: Subscription,
47
91
}
48
92
49
93
impl SettingsView {
50
94
pub const WIDTH: f32 = 420.;
51
pub const HEIGHT: f32 = 460.;
95
pub const HEIGHT: f32 = 540.;
52
96
53
97
pub fn new(center: Entity<NotificationCenter>, cx: &mut Context<Self>) -> Self {
54
98
let subscription = cx.observe(¢er, |_, _, cx| cx.notify());
99
let release = cx.on_release(|view, cx| view.preview.stop(cx));
100
let (preview, mut updates) = CameraPreview::new();
101
let state = center.read(cx).app().read(cx);
102
let background = Some(state.call_background.clone())
103
.filter(|pick| preview_backgrounds(&state.call_backgrounds).iter().any(|(known, _)| known == pick))
104
.unwrap_or_default();
105
cx.spawn(async move |this, cx| {
106
while updates.recv().await.is_some() {
107
if this.update(cx, |view, cx| view.take_frames(cx)).is_err() {
108
return;
109
}
110
}
111
})
112
.detach();
113
cx.spawn(async move |this, cx| {
114
loop {
115
cx.background_executor().timer(FPS_TICK).await;
116
if this.update(cx, |view, cx| view.tick(cx)).is_err() {
117
break;
118
}
119
}
120
})
121
.detach();
55
122
SettingsView {
56
123
center,
124
section: Section::Notifications,
125
preview,
126
cameras: camera_entries(&[]),
127
cameras_requested: false,
128
camera: DeviceChoice::SystemDefault,
129
background,
57
130
_subscription: subscription,
131
_release: release,
132
}
133
}
134
135
fn take_frames(&mut self, cx: &mut Context<Self>) {
136
self.preview.take_frames(cx);
137
cx.notify();
138
}
139
140
fn tick(&mut self, cx: &mut Context<Self>) {
141
if self.section == Section::Devices {
142
self.preview.tick(Instant::now());
143
cx.notify();
144
}
145
}
146
147
fn select_section(&mut self, section: Section, cx: &mut Context<Self>) {
148
if self.section == section {
149
return;
150
}
151
self.section = section;
152
match section {
153
Section::Devices => {
154
self.load_cameras(cx);
155
self.apply_background(cx);
156
self.preview.start(&self.camera);
157
}
158
Section::Notifications => self.preview.stop(cx),
159
}
160
cx.notify();
161
}
162
163
fn load_cameras(&mut self, cx: &mut Context<Self>) {
164
if std::mem::replace(&mut self.cameras_requested, true) {
165
return;
166
}
167
cx.spawn(async move |this, cx| {
168
let cameras = cx.background_executor().spawn(async { list_cameras() }).await;
169
this.update(cx, |view, cx| {
170
view.cameras = camera_entries(&cameras);
171
cx.notify();
172
})
173
.ok();
174
})
175
.detach();
176
}
177
178
fn select_camera(&mut self, camera: DeviceChoice, cx: &mut Context<Self>) {
179
self.camera = camera;
180
self.preview.start(&self.camera);
181
cx.notify();
182
}
183
184
fn select_background(&mut self, pick: BackgroundPick, cx: &mut Context<Self>) {
185
self.background = pick;
186
self.apply_background(cx);
187
cx.notify();
188
}
189
190
fn apply_background(&self, cx: &App) {
191
let state = self.center.read(cx).app().read(cx);
192
if let Some(choice) = state.call_backgrounds.choice_for(&self.background) {
193
self.preview.set_background(choice);
58
194
}
59
195
}
60
196
}
@@ -100,10 +236,209 @@ fn button(label: &'static str) -> Stateful<Div> {
100
236
.child(label)
101
237
}
102
238
239
fn titled(title: &'static str, detail: &'static str) -> Div {
240
v_flex()
241
.flex_1()
242
.child(
243
div()
244
.text_size(px(14.))
245
.font_weight(FontWeight::SEMIBOLD)
246
.text_color(theme::text())
247
.child(title),
248
)
249
.child(
250
div()
251
.text_size(px(12.))
252
.text_color(theme::text_muted())
253
.child(detail),
254
)
255
}
256
257
fn control_row(title: &'static str, detail: &'static str, control: impl IntoElement) -> Div {
258
h_flex()
259
.w_full()
260
.px(px(20.))
261
.py(px(10.))
262
.gap(px(12.))
263
.items_center()
264
.child(titled(title, detail))
265
.child(control)
266
}
267
268
fn section_tab(section: Section, active: bool, view: Entity<SettingsView>) -> Stateful<Div> {
269
div()
270
.id(section.label())
271
.h(px(32.))
272
.px(px(14.))
273
.flex()
274
.items_center()
275
.rounded(px(8.))
276
.cursor_pointer()
277
.text_size(px(13.))
278
.font_weight(FontWeight::SEMIBOLD)
279
.text_color(if active { theme::on_accent() } else { theme::text() })
280
.when(active, |tab| tab.bg(theme::accent()))
281
.when(!active, |tab| tab.hover(|tab| tab.bg(theme::row_hover())))
282
.child(section.label())
283
.on_click(move |_, _, cx| view.update(cx, |view, cx| view.select_section(section, cx)))
284
}
285
286
impl SettingsView {
287
fn ringtone_row(&self, current: Ringtone) -> Div {
288
let center = self.center.clone();
289
control_row(
290
"Ringtone",
291
"Incoming calls",
292
h_flex()
293
.gap(px(8.))
294
.items_center()
295
.child(
296
Button::new("ringtone-select")
297
.outline()
298
.w(px(110.))
299
.label(current.label())
300
.icon(IconName::ChevronDown)
301
.dropdown_menu(move |menu, _, _| {
302
Ringtone::ALL.iter().fold(menu, |menu, ringtone| {
303
let (center, ringtone) = (center.clone(), *ringtone);
304
menu.item(PopupMenuItem::new(ringtone.label()).checked(ringtone == current).on_click(
305
move |_, _, cx| {
306
center.update(cx, |center, cx| {
307
center.update_settings(cx, |settings| settings.ringtone = ringtone)
308
});
309
platform::play_preview(ringtone);
310
},
311
))
312
})
313
}),
314
)
315
.child(button("Play").on_click(move |_, _, _| platform::play_preview(current))),
316
)
317
}
318
319
fn devices_section(&self, cx: &mut Context<Self>) -> Div {
320
let view = cx.entity();
321
let camera_label = self
322
.cameras
323
.iter()
324
.find(|entry| entry.choice == self.camera)
325
.map_or(DEFAULT_CAMERA_LABEL.to_owned(), |entry| entry.label.clone());
326
let cameras = self.cameras.clone();
327
let current_camera = self.camera.clone();
328
let camera_view = view.clone();
329
let backgrounds = preview_backgrounds(&self.center.read(cx).app().read(cx).call_backgrounds);
330
let background_label = backgrounds
331
.iter()
332
.find(|(pick, _)| *pick == self.background)
333
.map_or("None".to_owned(), |(_, label)| label.clone());
334
let current_background = self.background.clone();
335
let image = self.preview.image(Instant::now());
336
let status = self.preview.failure().map_or_else(
337
|| {
338
self.preview
339
.fps()
340
.map_or("Starting camera...".to_owned(), |fps| format!("{fps:.0} fps"))
341
},
342
|reason| format!("Camera could not start: {reason}"),
343
);
344
v_flex()
345
.w_full()
346
.child(control_row(
347
"Camera",
348
"Preview stays on this computer",
349
Button::new("camera-select")
350
.outline()
351
.w(px(SELECT_WIDTH))
352
.label(camera_label)
353
.icon(IconName::ChevronDown)
354
.dropdown_menu(move |menu, _, _| {
355
cameras.iter().fold(menu, |menu, entry| {
356
let (view, choice) = (camera_view.clone(), entry.choice.clone());
357
menu.item(
358
PopupMenuItem::new(entry.label.clone())
359
.checked(entry.choice == current_camera)
360
.on_click(move |_, _, cx| {
361
view.update(cx, |view, cx| view.select_camera(choice.clone(), cx))
362
}),
363
)
364
})
365
}),
366
))
367
.child(control_row(
368
"Background",
369
"Blur or a picture behind you",
370
Button::new("background-select")
371
.outline()
372
.w(px(SELECT_WIDTH))
373
.label(background_label)
374
.icon(IconName::ChevronDown)
375
.dropdown_menu(move |menu, _, _| {
376
backgrounds.iter().fold(menu, |menu, (pick, label)| {
377
let (view, pick) = (view.clone(), pick.clone());
378
menu.item(
379
PopupMenuItem::new(label.clone())
380
.checked(pick == current_background)
381
.on_click(move |_, _, cx| {
382
view.update(cx, |view, cx| view.select_background(pick.clone(), cx))
383
}),
384
)
385
})
386
}),
387
))
388
.child(
389
v_flex()
390
.w_full()
391
.px(px(20.))
392
.pt(px(8.))
393
.gap(px(8.))
394
.child(
395
div()
396
.w(px(PREVIEW_WIDTH))
397
.h(px(PREVIEW_HEIGHT))
398
.flex()
399
.items_center()
400
.justify_center()
401
.overflow_hidden()
402
.rounded(px(PREVIEW_RADIUS))
403
.bg(theme::surface())
404
.children(image.map(|image| {
405
img(ImageSource::Render(image))
406
.size_full()
407
.object_fit(ObjectFit::Cover)
408
.rounded(px(PREVIEW_RADIUS))
409
})),
410
)
411
.child(div().text_size(px(12.)).text_color(theme::text_muted()).child(status)),
412
)
413
}
414
}
415
103
416
impl Render for SettingsView {
104
417
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
418
let view = cx.entity();
419
let tabs = h_flex()
420
.w_full()
421
.px(px(20.))
422
.gap(px(8.))
423
.children(Section::ALL.map(|section| section_tab(section, section == self.section, view.clone())));
424
let body = match self.section {
425
Section::Notifications => self.notifications_section(cx).into_any_element(),
426
Section::Devices => self.devices_section(cx).into_any_element(),
427
};
428
v_flex()
429
.size_full()
430
.bg(theme::background())
431
.pt(px(12.))
432
.child(tabs)
433
.child(body)
434
}
435
}
436
437
impl SettingsView {
438
fn notifications_section(&self, cx: &App) -> Div {
105
439
let mut current = self.center.read(cx).settings().clone();
106
440
let corner = current.corner;
441
let ringtone = current.ringtone;
107
442
let rows = ROWS.iter().enumerate().map(|(index, row)| {
108
443
let on = *(row.field)(&mut current);
109
444
let center = self.center.clone();
@@ -147,42 +482,21 @@ impl Render for SettingsView {
147
482
let position_center = self.center.clone();
148
483
let test_center = self.center.clone();
149
484
v_flex()
150
.size_full()
151
.bg(theme::background())
152
.pt(px(12.))
485
.w_full()
486
.pt(px(8.))
153
487
.children(rows)
154
.child(
155
h_flex()
156
.w_full()
157
.px(px(20.))
158
.py(px(10.))
159
.gap(px(12.))
160
.items_center()
161
.child(
162
v_flex()
163
.flex_1()
164
.child(
165
div()
166
.text_size(px(14.))
167
.font_weight(FontWeight::SEMIBOLD)
168
.text_color(theme::text())
169
.child("Position"),
170
)
171
.child(
172
div()
173
.text_size(px(12.))
174
.text_color(theme::text_muted())
175
.child("Corner of the main screen"),
176
),
177
)
178
.child(button(corner.label()).on_click(move |_, _, cx| {
179
position_center.update(cx, |center, cx| {
180
center.update_settings(cx, |settings| {
181
settings.corner = settings.corner.next()
182
})
183
});
184
})),
185
)
488
.child(self.ringtone_row(ringtone))
489
.child(control_row(
490
"Position",
491
"Corner of the main screen",
492
button(corner.label()).on_click(move |_, _, cx| {
493
position_center.update(cx, |center, cx| {
494
center.update_settings(cx, |settings| {
495
settings.corner = settings.corner.next()
496
})
497
});
498
}),
499
))
186
500
.child(
187
501
h_flex()
188
502
.w_full()
@@ -1,10 +1,47 @@1
use gpui_kit::component::{h_flex, v_flex};1
use std::time::{Duration, Instant};2
3
use calling::camera::{DEFAULT_CAMERA_LABEL, list_cameras};4
use calling::{DeviceChoice, DeviceEntry, camera_entries};5
use gpui_kit::assets::IconName;6
use gpui_kit::component::{7
button::Button,8
h_flex,9
menu::{DropdownMenu as _, PopupMenuItem},10
v_flex,11
};12
use gpui_kit::prelude::FluentBuilder as _;2
use gpui_kit::*;13
use gpui_kit::*;3
14
4
use super::center::NotificationCenter;15
use super::center::NotificationCenter;16
use super::platform;17
use super::ring_tone::Ringtone;5
use super::rules::Settings;18
use super::rules::Settings;19
use crate::call::{BackgroundPick, CameraPreview, preview_backgrounds};6
use crate::theme;20
use crate::theme;7
21
22
const FPS_TICK: Duration = Duration::from_millis(500);23
const SELECT_WIDTH: f32 = 170.;24
const PREVIEW_WIDTH: f32 = 380.;25
const PREVIEW_HEIGHT: f32 = 214.;26
const PREVIEW_RADIUS: f32 = 10.;27
28
#[derive(Clone, Copy, PartialEq, Eq)]29
enum Section {30
Notifications,31
Devices,32
}33
34
impl Section {35
const ALL: [Section; 2] = [Section::Notifications, Section::Devices];36
37
fn label(self) -> &'static str {38
match self {39
Section::Notifications => "Notifications",40
Section::Devices => "Devices",41
}42
}43
}44
8
type Accessor = fn(&mut Settings) -> &mut bool;45
type Accessor = fn(&mut Settings) -> &mut bool;9
46
10
struct Row {47
struct Row {@@ -43,18 +80,117 @@ const ROWS: [Row; 5] = [43
80
44
pub struct SettingsView {81
pub struct SettingsView {45
center: Entity<NotificationCenter>,82
center: Entity<NotificationCenter>,83
section: Section,84
preview: CameraPreview,85
cameras: Vec<DeviceEntry>,86
cameras_requested: bool,87
camera: DeviceChoice,88
background: BackgroundPick,46
_subscription: Subscription,89
_subscription: Subscription,90
_release: Subscription,47
}91
}48
92
49
impl SettingsView {93
impl SettingsView {50
pub const WIDTH: f32 = 420.;94
pub const WIDTH: f32 = 420.;51
pub const HEIGHT: f32 = 460.;95
pub const HEIGHT: f32 = 540.;52
96
53
pub fn new(center: Entity<NotificationCenter>, cx: &mut Context<Self>) -> Self {97
pub fn new(center: Entity<NotificationCenter>, cx: &mut Context<Self>) -> Self {54
let subscription = cx.observe(¢er, |_, _, cx| cx.notify());98
let subscription = cx.observe(¢er, |_, _, cx| cx.notify());99
let release = cx.on_release(|view, cx| view.preview.stop(cx));100
let (preview, mut updates) = CameraPreview::new();101
let state = center.read(cx).app().read(cx);102
let background = Some(state.call_background.clone())103
.filter(|pick| preview_backgrounds(&state.call_backgrounds).iter().any(|(known, _)| known == pick))104
.unwrap_or_default();105
cx.spawn(async move |this, cx| {106
while updates.recv().await.is_some() {107
if this.update(cx, |view, cx| view.take_frames(cx)).is_err() {108
return;109
}110
}111
})112
.detach();113
cx.spawn(async move |this, cx| {114
loop {115
cx.background_executor().timer(FPS_TICK).await;116
if this.update(cx, |view, cx| view.tick(cx)).is_err() {117
break;118
}119
}120
})121
.detach();55
SettingsView {122
SettingsView {56
center,123
center,124
section: Section::Notifications,125
preview,126
cameras: camera_entries(&[]),127
cameras_requested: false,128
camera: DeviceChoice::SystemDefault,129
background,57
_subscription: subscription,130
_subscription: subscription,131
_release: release,132
}133
}134
135
fn take_frames(&mut self, cx: &mut Context<Self>) {136
self.preview.take_frames(cx);137
cx.notify();138
}139
140
fn tick(&mut self, cx: &mut Context<Self>) {141
if self.section == Section::Devices {142
self.preview.tick(Instant::now());143
cx.notify();144
}145
}146
147
fn select_section(&mut self, section: Section, cx: &mut Context<Self>) {148
if self.section == section {149
return;150
}151
self.section = section;152
match section {153
Section::Devices => {154
self.load_cameras(cx);155
self.apply_background(cx);156
self.preview.start(&self.camera);157
}158
Section::Notifications => self.preview.stop(cx),159
}160
cx.notify();161
}162
163
fn load_cameras(&mut self, cx: &mut Context<Self>) {164
if std::mem::replace(&mut self.cameras_requested, true) {165
return;166
}167
cx.spawn(async move |this, cx| {168
let cameras = cx.background_executor().spawn(async { list_cameras() }).await;169
this.update(cx, |view, cx| {170
view.cameras = camera_entries(&cameras);171
cx.notify();172
})173
.ok();174
})175
.detach();176
}177
178
fn select_camera(&mut self, camera: DeviceChoice, cx: &mut Context<Self>) {179
self.camera = camera;180
self.preview.start(&self.camera);181
cx.notify();182
}183
184
fn select_background(&mut self, pick: BackgroundPick, cx: &mut Context<Self>) {185
self.background = pick;186
self.apply_background(cx);187
cx.notify();188
}189
190
fn apply_background(&self, cx: &App) {191
let state = self.center.read(cx).app().read(cx);192
if let Some(choice) = state.call_backgrounds.choice_for(&self.background) {193
self.preview.set_background(choice);58
}194
}59
}195
}60
}196
}@@ -100,10 +236,209 @@ fn button(label: &'static str) -> Stateful<Div> {100
.child(label)236
.child(label)101
}237
}102
238
239
fn titled(title: &'static str, detail: &'static str) -> Div {240
v_flex()241
.flex_1()242
.child(243
div()244
.text_size(px(14.))245
.font_weight(FontWeight::SEMIBOLD)246
.text_color(theme::text())247
.child(title),248
)249
.child(250
div()251
.text_size(px(12.))252
.text_color(theme::text_muted())253
.child(detail),254
)255
}256
257
fn control_row(title: &'static str, detail: &'static str, control: impl IntoElement) -> Div {258
h_flex()259
.w_full()260
.px(px(20.))261
.py(px(10.))262
.gap(px(12.))263
.items_center()264
.child(titled(title, detail))265
.child(control)266
}267
268
fn section_tab(section: Section, active: bool, view: Entity<SettingsView>) -> Stateful<Div> {269
div()270
.id(section.label())271
.h(px(32.))272
.px(px(14.))273
.flex()274
.items_center()275
.rounded(px(8.))276
.cursor_pointer()277
.text_size(px(13.))278
.font_weight(FontWeight::SEMIBOLD)279
.text_color(if active { theme::on_accent() } else { theme::text() })280
.when(active, |tab| tab.bg(theme::accent()))281
.when(!active, |tab| tab.hover(|tab| tab.bg(theme::row_hover())))282
.child(section.label())283
.on_click(move |_, _, cx| view.update(cx, |view, cx| view.select_section(section, cx)))284
}285
286
impl SettingsView {287
fn ringtone_row(&self, current: Ringtone) -> Div {288
let center = self.center.clone();289
control_row(290
"Ringtone",291
"Incoming calls",292
h_flex()293
.gap(px(8.))294
.items_center()295
.child(296
Button::new("ringtone-select")297
.outline()298
.w(px(110.))299
.label(current.label())300
.icon(IconName::ChevronDown)301
.dropdown_menu(move |menu, _, _| {302
Ringtone::ALL.iter().fold(menu, |menu, ringtone| {303
let (center, ringtone) = (center.clone(), *ringtone);304
menu.item(PopupMenuItem::new(ringtone.label()).checked(ringtone == current).on_click(305
move |_, _, cx| {306
center.update(cx, |center, cx| {307
center.update_settings(cx, |settings| settings.ringtone = ringtone)308
});309
platform::play_preview(ringtone);310
},311
))312
})313
}),314
)315
.child(button("Play").on_click(move |_, _, _| platform::play_preview(current))),316
)317
}318
319
fn devices_section(&self, cx: &mut Context<Self>) -> Div {320
let view = cx.entity();321
let camera_label = self322
.cameras323
.iter()324
.find(|entry| entry.choice == self.camera)325
.map_or(DEFAULT_CAMERA_LABEL.to_owned(), |entry| entry.label.clone());326
let cameras = self.cameras.clone();327
let current_camera = self.camera.clone();328
let camera_view = view.clone();329
let backgrounds = preview_backgrounds(&self.center.read(cx).app().read(cx).call_backgrounds);330
let background_label = backgrounds331
.iter()332
.find(|(pick, _)| *pick == self.background)333
.map_or("None".to_owned(), |(_, label)| label.clone());334
let current_background = self.background.clone();335
let image = self.preview.image(Instant::now());336
let status = self.preview.failure().map_or_else(337
|| {338
self.preview339
.fps()340
.map_or("Starting camera...".to_owned(), |fps| format!("{fps:.0} fps"))341
},342
|reason| format!("Camera could not start: {reason}"),343
);344
v_flex()345
.w_full()346
.child(control_row(347
"Camera",348
"Preview stays on this computer",349
Button::new("camera-select")350
.outline()351
.w(px(SELECT_WIDTH))352
.label(camera_label)353
.icon(IconName::ChevronDown)354
.dropdown_menu(move |menu, _, _| {355
cameras.iter().fold(menu, |menu, entry| {356
let (view, choice) = (camera_view.clone(), entry.choice.clone());357
menu.item(358
PopupMenuItem::new(entry.label.clone())359
.checked(entry.choice == current_camera)360
.on_click(move |_, _, cx| {361
view.update(cx, |view, cx| view.select_camera(choice.clone(), cx))362
}),363
)364
})365
}),366
))367
.child(control_row(368
"Background",369
"Blur or a picture behind you",370
Button::new("background-select")371
.outline()372
.w(px(SELECT_WIDTH))373
.label(background_label)374
.icon(IconName::ChevronDown)375
.dropdown_menu(move |menu, _, _| {376
backgrounds.iter().fold(menu, |menu, (pick, label)| {377
let (view, pick) = (view.clone(), pick.clone());378
menu.item(379
PopupMenuItem::new(label.clone())380
.checked(pick == current_background)381
.on_click(move |_, _, cx| {382
view.update(cx, |view, cx| view.select_background(pick.clone(), cx))383
}),384
)385
})386
}),387
))388
.child(389
v_flex()390
.w_full()391
.px(px(20.))392
.pt(px(8.))393
.gap(px(8.))394
.child(395
div()396
.w(px(PREVIEW_WIDTH))397
.h(px(PREVIEW_HEIGHT))398
.flex()399
.items_center()400
.justify_center()401
.overflow_hidden()402
.rounded(px(PREVIEW_RADIUS))403
.bg(theme::surface())404
.children(image.map(|image| {405
img(ImageSource::Render(image))406
.size_full()407
.object_fit(ObjectFit::Cover)408
.rounded(px(PREVIEW_RADIUS))409
})),410
)411
.child(div().text_size(px(12.)).text_color(theme::text_muted()).child(status)),412
)413
}414
}415
103
impl Render for SettingsView {416
impl Render for SettingsView {104
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {417
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {418
let view = cx.entity();419
let tabs = h_flex()420
.w_full()421
.px(px(20.))422
.gap(px(8.))423
.children(Section::ALL.map(|section| section_tab(section, section == self.section, view.clone())));424
let body = match self.section {425
Section::Notifications => self.notifications_section(cx).into_any_element(),426
Section::Devices => self.devices_section(cx).into_any_element(),427
};428
v_flex()429
.size_full()430
.bg(theme::background())431
.pt(px(12.))432
.child(tabs)433
.child(body)434
}435
}436
437
impl SettingsView {438
fn notifications_section(&self, cx: &App) -> Div {105
let mut current = self.center.read(cx).settings().clone();439
let mut current = self.center.read(cx).settings().clone();106
let corner = current.corner;440
let corner = current.corner;441
let ringtone = current.ringtone;107
let rows = ROWS.iter().enumerate().map(|(index, row)| {442
let rows = ROWS.iter().enumerate().map(|(index, row)| {108
let on = *(row.field)(&mut current);443
let on = *(row.field)(&mut current);109
let center = self.center.clone();444
let center = self.center.clone();@@ -147,42 +482,21 @@ impl Render for SettingsView {147
let position_center = self.center.clone();482
let position_center = self.center.clone();148
let test_center = self.center.clone();483
let test_center = self.center.clone();149
v_flex()484
v_flex()150
.size_full()485
.w_full()151
.bg(theme::background())486
.pt(px(8.))152
.pt(px(12.))153
.children(rows)487
.children(rows)154
.child(488
.child(self.ringtone_row(ringtone))155
h_flex()489
.child(control_row(156
.w_full()490
"Position",157
.px(px(20.))491
"Corner of the main screen",158
.py(px(10.))492
button(corner.label()).on_click(move |_, _, cx| {159
.gap(px(12.))493
position_center.update(cx, |center, cx| {160
.items_center()494
center.update_settings(cx, |settings| {161
.child(495
settings.corner = settings.corner.next()162
v_flex()496
})163
.flex_1()497
});164
.child(498
}),165
div()499
))166
.text_size(px(14.))167
.font_weight(FontWeight::SEMIBOLD)168
.text_color(theme::text())169
.child("Position"),170
)171
.child(172
div()173
.text_size(px(12.))174
.text_color(theme::text_muted())175
.child("Corner of the main screen"),176
),177
)178
.child(button(corner.label()).on_click(move |_, _, cx| {179
position_center.update(cx, |center, cx| {180
center.update_settings(cx, |settings| {181
settings.corner = settings.corner.next()182
})183
});184
})),185
)186
.child(500
.child(187
h_flex()501
h_flex()188
.w_full()502
.w_full()@@ -72,12 +72,13 @@ pub fn reaction_glyph(reaction: Reaction) -> String {
72
72
#[derive(Default)]
73
73
struct TileExtras {
74
74
hand: Option<usize>,
75
own: bool,
75
76
reaction: Option<(Reaction, u64)>,
76
77
spotlight: bool,
77
78
pinned: bool,
78
79
}
79
80
80
fn hand_badge(position: usize) -> Div {
81
fn hand_badge(position: usize, own: bool) -> Div {
81
82
h_flex()
82
83
.h(px(24.))
83
84
.px(px(8.))
@@ -88,7 +89,7 @@ fn hand_badge(position: usize) -> Div {
88
89
.text_color(hsla(0., 0., 0.08, 1.))
89
90
.text_size(px(12.))
90
91
.font_weight(FontWeight::SEMIBOLD)
91
.child(format!("Hand {position}"))
92
.child(if own { "Hand raised".to_owned() } else { format!("Hand {position}") })
92
93
}
93
94
94
95
fn reaction_chip(reaction: Reaction, serial: u64) -> AnyElement {
@@ -124,7 +125,7 @@ fn tile_overlays(extras: &TileExtras) -> Vec<AnyElement> {
124
125
.top(px(10.))
125
126
.left(px(10.))
126
127
.gap(px(6.))
127
.children(extras.hand.map(hand_badge))
128
.children(extras.hand.map(|position| hand_badge(position, extras.own)))
128
129
.when(extras.spotlight, |row| row.child(spotlight_chip()))
129
130
.when(extras.pinned, |row| row.child(pin_chip()))
130
131
.into_any_element()
@@ -688,6 +689,7 @@ fn devices_button(app: &Entity<AppState>, model: &CallModel) -> impl IntoElement
688
689
fn person_tile(app: &Entity<AppState>, state: &AppState, model: &CallModel, remote: &Tile, size: TileSize, now: Instant) -> AnyElement {
689
690
let extras = TileExtras {
690
691
hand: remote.hand.map(|rank| model.hand_position(rank)),
692
own: false,
691
693
reaction: model.chip_of(&remote.mri, now).map(|chip| (chip.reaction, chip.serial)),
692
694
spotlight: remote.spotlight.is_some(),
693
695
pinned: model.is_pinned(&remote.mri),
@@ -719,6 +721,7 @@ fn own_tile(app: &Entity<AppState>, state: &AppState, model: &CallModel, size: T
719
721
let own_mri = model.own_mri.clone().unwrap_or_default();
720
722
let extras = TileExtras {
721
723
hand: model.own_hand.map(|rank| model.hand_position(rank)),
724
own: true,
722
725
reaction: model.own_chip(now).map(|chip| (chip.reaction, chip.serial)),
723
726
spotlight: model.own_spotlight.is_some(),
724
727
pinned: model.is_pinned(&own_mri),
@@ -837,8 +840,7 @@ pub fn render_call_view(app: &Entity<AppState>, state: &AppState, chat: Option<E
837
840
.child(mute_button(app, model, "call-mute", CONTROL_SIZE))
838
841
.child(h_flex().gap(px(2.)).items_center().child(camera_button(app, model)).children(camera_menu_button(app, model, BackgroundMenu::of(state))))
839
842
.child(share_button(app, model, state.call_share_sound))
840
.child(hand_button(app, model))
841
.child(reactions_button(app, model))
843
.when(model.has_reaction_controls(), |row| row.child(hand_button(app, model)).child(reactions_button(app, model)))
842
844
.child(devices_button(app, model))
843
845
.children(more_button(app, model))
844
846
.when(call.chat_thread().is_some(), |row| row.child(chat_button(app, call.chat_open, state.call_chat_unread())))
@@ -72,12 +72,13 @@ pub fn reaction_glyph(reaction: Reaction) -> String {72
#[derive(Default)]72
#[derive(Default)]73
struct TileExtras {73
struct TileExtras {74
hand: Option<usize>,74
hand: Option<usize>,75
own: bool,75
reaction: Option<(Reaction, u64)>,76
reaction: Option<(Reaction, u64)>,76
spotlight: bool,77
spotlight: bool,77
pinned: bool,78
pinned: bool,78
}79
}79
80
80
fn hand_badge(position: usize) -> Div {81
fn hand_badge(position: usize, own: bool) -> Div {81
h_flex()82
h_flex()82
.h(px(24.))83
.h(px(24.))83
.px(px(8.))84
.px(px(8.))@@ -88,7 +89,7 @@ fn hand_badge(position: usize) -> Div {88
.text_color(hsla(0., 0., 0.08, 1.))89
.text_color(hsla(0., 0., 0.08, 1.))89
.text_size(px(12.))90
.text_size(px(12.))90
.font_weight(FontWeight::SEMIBOLD)91
.font_weight(FontWeight::SEMIBOLD)91
.child(format!("Hand {position}"))92
.child(if own { "Hand raised".to_owned() } else { format!("Hand {position}") })92
}93
}93
94
94
fn reaction_chip(reaction: Reaction, serial: u64) -> AnyElement {95
fn reaction_chip(reaction: Reaction, serial: u64) -> AnyElement {@@ -124,7 +125,7 @@ fn tile_overlays(extras: &TileExtras) -> Vec<AnyElement> {124
.top(px(10.))125
.top(px(10.))125
.left(px(10.))126
.left(px(10.))126
.gap(px(6.))127
.gap(px(6.))127
.children(extras.hand.map(hand_badge))128
.children(extras.hand.map(|position| hand_badge(position, extras.own)))128
.when(extras.spotlight, |row| row.child(spotlight_chip()))129
.when(extras.spotlight, |row| row.child(spotlight_chip()))129
.when(extras.pinned, |row| row.child(pin_chip()))130
.when(extras.pinned, |row| row.child(pin_chip()))130
.into_any_element()131
.into_any_element()@@ -688,6 +689,7 @@ fn devices_button(app: &Entity<AppState>, model: &CallModel) -> impl IntoElement688
fn person_tile(app: &Entity<AppState>, state: &AppState, model: &CallModel, remote: &Tile, size: TileSize, now: Instant) -> AnyElement {689
fn person_tile(app: &Entity<AppState>, state: &AppState, model: &CallModel, remote: &Tile, size: TileSize, now: Instant) -> AnyElement {689
let extras = TileExtras {690
let extras = TileExtras {690
hand: remote.hand.map(|rank| model.hand_position(rank)),691
hand: remote.hand.map(|rank| model.hand_position(rank)),692
own: false,691
reaction: model.chip_of(&remote.mri, now).map(|chip| (chip.reaction, chip.serial)),693
reaction: model.chip_of(&remote.mri, now).map(|chip| (chip.reaction, chip.serial)),692
spotlight: remote.spotlight.is_some(),694
spotlight: remote.spotlight.is_some(),693
pinned: model.is_pinned(&remote.mri),695
pinned: model.is_pinned(&remote.mri),@@ -719,6 +721,7 @@ fn own_tile(app: &Entity<AppState>, state: &AppState, model: &CallModel, size: T719
let own_mri = model.own_mri.clone().unwrap_or_default();721
let own_mri = model.own_mri.clone().unwrap_or_default();720
let extras = TileExtras {722
let extras = TileExtras {721
hand: model.own_hand.map(|rank| model.hand_position(rank)),723
hand: model.own_hand.map(|rank| model.hand_position(rank)),724
own: true,722
reaction: model.own_chip(now).map(|chip| (chip.reaction, chip.serial)),725
reaction: model.own_chip(now).map(|chip| (chip.reaction, chip.serial)),723
spotlight: model.own_spotlight.is_some(),726
spotlight: model.own_spotlight.is_some(),724
pinned: model.is_pinned(&own_mri),727
pinned: model.is_pinned(&own_mri),@@ -837,8 +840,7 @@ pub fn render_call_view(app: &Entity<AppState>, state: &AppState, chat: Option<E837
.child(mute_button(app, model, "call-mute", CONTROL_SIZE))840
.child(mute_button(app, model, "call-mute", CONTROL_SIZE))838
.child(h_flex().gap(px(2.)).items_center().child(camera_button(app, model)).children(camera_menu_button(app, model, BackgroundMenu::of(state))))841
.child(h_flex().gap(px(2.)).items_center().child(camera_button(app, model)).children(camera_menu_button(app, model, BackgroundMenu::of(state))))839
.child(share_button(app, model, state.call_share_sound))842
.child(share_button(app, model, state.call_share_sound))840
.child(hand_button(app, model))843
.when(model.has_reaction_controls(), |row| row.child(hand_button(app, model)).child(reactions_button(app, model)))841
.child(reactions_button(app, model))842
.child(devices_button(app, model))844
.child(devices_button(app, model))843
.children(more_button(app, model))845
.children(more_button(app, model))844
.when(call.chat_thread().is_some(), |row| row.child(chat_button(app, call.chat_open, state.call_chat_unread())))846
.when(call.chat_thread().is_some(), |row| row.child(chat_button(app, call.chat_open, state.call_chat_unread())))@@ -1325,15 +1325,20 @@ async fn drive(
1325
1325
}
1326
1326
Some(CallCommand::RefreshShareSources) => refresh_share_sources(control.updates(), options.video),
1327
1327
Some(CallCommand::SetHand(true)) => match remote.signaling.raise_hand(&remote.conversation, &remote.participant).await {
1328
Ok(state_id) => own_hand = state_id,
1328
Ok(receipt) => {
1329
own_hand = receipt.state_id;
1330
control.send(CallUpdate::OwnHand(Some(receipt.rank)));
1331
}
1329
1332
Err(error) => {
1330
1333
timeline.record("raise hand failed", error.to_string());
1334
control.send(CallUpdate::OwnHand(None));
1331
1335
control.send(CallUpdate::Notice("Could not raise your hand".into()));
1332
1336
}
1333
1337
},
1334
1338
Some(CallCommand::SetHand(false)) => {
1335
1339
let state_ids: Vec<String> = roster.hand_of(&own_mri).map(|hand| hand.state_id.clone()).or(own_hand.take()).into_iter().collect();
1336
1340
own_hand = None;
1341
control.send(CallUpdate::OwnHand(None));
1337
1342
if !state_ids.is_empty()
1338
1343
&& let Err(error) = remote.signaling.lower_hands(&remote.conversation, &remote.participant, &state_ids).await
1339
1344
{
@@ -1325,15 +1325,20 @@ async fn drive(1325
}1325
}1326
Some(CallCommand::RefreshShareSources) => refresh_share_sources(control.updates(), options.video),1326
Some(CallCommand::RefreshShareSources) => refresh_share_sources(control.updates(), options.video),1327
Some(CallCommand::SetHand(true)) => match remote.signaling.raise_hand(&remote.conversation, &remote.participant).await {1327
Some(CallCommand::SetHand(true)) => match remote.signaling.raise_hand(&remote.conversation, &remote.participant).await {1328
Ok(state_id) => own_hand = state_id,1328
Ok(receipt) => {1329
own_hand = receipt.state_id;1330
control.send(CallUpdate::OwnHand(Some(receipt.rank)));1331
}1329
Err(error) => {1332
Err(error) => {1330
timeline.record("raise hand failed", error.to_string());1333
timeline.record("raise hand failed", error.to_string());1334
control.send(CallUpdate::OwnHand(None));1331
control.send(CallUpdate::Notice("Could not raise your hand".into()));1335
control.send(CallUpdate::Notice("Could not raise your hand".into()));1332
}1336
}1333
},1337
},1334
Some(CallCommand::SetHand(false)) => {1338
Some(CallCommand::SetHand(false)) => {1335
let state_ids: Vec<String> = roster.hand_of(&own_mri).map(|hand| hand.state_id.clone()).or(own_hand.take()).into_iter().collect();1339
let state_ids: Vec<String> = roster.hand_of(&own_mri).map(|hand| hand.state_id.clone()).or(own_hand.take()).into_iter().collect();1336
own_hand = None;1340
own_hand = None;1341
control.send(CallUpdate::OwnHand(None));1337
if !state_ids.is_empty()1342
if !state_ids.is_empty()1338
&& let Err(error) = remote.signaling.lower_hands(&remote.conversation, &remote.participant, &state_ids).await1343
&& let Err(error) = remote.signaling.lower_hands(&remote.conversation, &remote.participant, &state_ids).await1339
{1344
{@@ -81,6 +81,7 @@ pub enum CallUpdate {
81
81
LocalShare(Option<String>),
82
82
ShareSources(Vec<ShareSource>),
83
83
ShareSound(bool),
84
OwnHand(Option<u64>),
84
85
Reaction { mri: String, reaction: Reaction },
85
86
Captions(CaptionState),
86
87
Caption(CaptionEntry),
@@ -81,6 +81,7 @@ pub enum CallUpdate {81
LocalShare(Option<String>),81
LocalShare(Option<String>),82
ShareSources(Vec<ShareSource>),82
ShareSources(Vec<ShareSource>),83
ShareSound(bool),83
ShareSound(bool),84
OwnHand(Option<u64>),84
Reaction { mri: String, reaction: Reaction },85
Reaction { mri: String, reaction: Reaction },85
Captions(CaptionState),86
Captions(CaptionState),86
Caption(CaptionEntry),87
Caption(CaptionEntry),@@ -346,10 +346,10 @@ impl Signaling {
346
346
self.state_sequence.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + 1
347
347
}
348
348
349
pub async fn raise_hand(&self, conversation: &Conversation, from: &Participant) -> Result<Option<String>> {
349
pub async fn raise_hand(&self, conversation: &Conversation, from: &Participant) -> Result<HandReceipt> {
350
350
let body = raise_hand_body(from.wire(), self.next_state_sequence());
351
351
let response = self.send("POST publishState", Method::Post, conversation.link("publishState")?, Some(body)).await?;
352
Ok(response.body["publishStateResponse"]["stateId"].as_str().map(str::to_owned))
352
Ok(hand_receipt_from(&response.body))
353
353
}
354
354
355
355
pub async fn lower_hands(&self, conversation: &Conversation, from: &Participant, state_ids: &[String]) -> Result<()> {
@@ -850,6 +850,20 @@ fn conversation_from(body: &Value) -> Result<Conversation> {
850
850
Ok(Conversation { controller, links, chat_thread: chat_thread_id(body) })
851
851
}
852
852
853
#[derive(Debug, Clone, PartialEq, Eq)]
854
pub struct HandReceipt {
855
pub state_id: Option<String>,
856
pub rank: u64,
857
}
858
859
pub fn hand_receipt_from(body: &Value) -> HandReceipt {
860
let published = &body["publishStateResponse"];
861
HandReceipt {
862
state_id: published["stateId"].as_str().map(str::to_owned),
863
rank: published["typeRank"].as_u64().unwrap_or(u64::MAX),
864
}
865
}
866
853
867
pub fn raise_hand_body(from: Value, sequence_number: u32) -> Value {
854
868
json!({
855
869
"from": from,
@@ -962,6 +976,13 @@ mod tests {
962
976
assert_eq!(all["stateType"], "raiseHands");
963
977
}
964
978
979
#[test]
980
fn a_raised_hand_reads_state_id_and_rank_from_the_publish_response() {
981
let body = json!({"publishStateResponse": {"stateId": "s-9", "typeRank": 3}});
982
assert_eq!(hand_receipt_from(&body), HandReceipt { state_id: Some("s-9".to_owned()), rank: 3 });
983
assert_eq!(hand_receipt_from(&json!({})), HandReceipt { state_id: None, rank: u64::MAX });
984
}
985
965
986
#[test]
966
987
fn the_meeting_chat_thread_comes_from_the_group_chat_modality() {
967
988
let body = json!({"activeModalities": {"groupChat": {"threadId": "19:meeting_abc@thread.v2"}}});
@@ -346,10 +346,10 @@ impl Signaling {346
self.state_sequence.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + 1346
self.state_sequence.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + 1347
}347
}348
348
349
pub async fn raise_hand(&self, conversation: &Conversation, from: &Participant) -> Result<Option<String>> {349
pub async fn raise_hand(&self, conversation: &Conversation, from: &Participant) -> Result<HandReceipt> {350
let body = raise_hand_body(from.wire(), self.next_state_sequence());350
let body = raise_hand_body(from.wire(), self.next_state_sequence());351
let response = self.send("POST publishState", Method::Post, conversation.link("publishState")?, Some(body)).await?;351
let response = self.send("POST publishState", Method::Post, conversation.link("publishState")?, Some(body)).await?;352
Ok(response.body["publishStateResponse"]["stateId"].as_str().map(str::to_owned))352
Ok(hand_receipt_from(&response.body))353
}353
}354
354
355
pub async fn lower_hands(&self, conversation: &Conversation, from: &Participant, state_ids: &[String]) -> Result<()> {355
pub async fn lower_hands(&self, conversation: &Conversation, from: &Participant, state_ids: &[String]) -> Result<()> {@@ -850,6 +850,20 @@ fn conversation_from(body: &Value) -> Result<Conversation> {850
Ok(Conversation { controller, links, chat_thread: chat_thread_id(body) })850
Ok(Conversation { controller, links, chat_thread: chat_thread_id(body) })851
}851
}852
852
853
#[derive(Debug, Clone, PartialEq, Eq)]854
pub struct HandReceipt {855
pub state_id: Option<String>,856
pub rank: u64,857
}858
859
pub fn hand_receipt_from(body: &Value) -> HandReceipt {860
let published = &body["publishStateResponse"];861
HandReceipt {862
state_id: published["stateId"].as_str().map(str::to_owned),863
rank: published["typeRank"].as_u64().unwrap_or(u64::MAX),864
}865
}866
853
pub fn raise_hand_body(from: Value, sequence_number: u32) -> Value {867
pub fn raise_hand_body(from: Value, sequence_number: u32) -> Value {854
json!({868
json!({855
"from": from,869
"from": from,@@ -962,6 +976,13 @@ mod tests {962
assert_eq!(all["stateType"], "raiseHands");976
assert_eq!(all["stateType"], "raiseHands");963
}977
}964
978
979
#[test]980
fn a_raised_hand_reads_state_id_and_rank_from_the_publish_response() {981
let body = json!({"publishStateResponse": {"stateId": "s-9", "typeRank": 3}});982
assert_eq!(hand_receipt_from(&body), HandReceipt { state_id: Some("s-9".to_owned()), rank: 3 });983
assert_eq!(hand_receipt_from(&json!({})), HandReceipt { state_id: None, rank: u64::MAX });984
}985
965
#[test]986
#[test]966
fn the_meeting_chat_thread_comes_from_the_group_chat_modality() {987
fn the_meeting_chat_thread_comes_from_the_group_chat_modality() {967
let body = json!({"activeModalities": {"groupChat": {"threadId": "19:meeting_abc@thread.v2"}}});988
let body = json!({"activeModalities": {"groupChat": {"threadId": "19:meeting_abc@thread.v2"}}});